text stringlengths 14 6.51M |
|---|
unit m3Exceptions;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "m3"
// Модуль: "w:/common/components/rtl/Garant/m3/m3Exceptions.pas"
// Родные Delphi интерфейсы (.pas)
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{$Include ..\m3\m3Define.inc}
interface
uses
l3Except,
l3Base
;
type
Em3Exception = class(El3Exception)
public
class procedure Check(aCondition: Boolean; const aMessage: String); overload;
end;//Em3Exception
Em3NoIndex = class(Em3Exception)
end;//Em3NoIndex
Em3InvalidStream = class(Em3Exception)
end;//Em3InvalidStream
Em3NilStream = class(Em3InvalidStream)
end;//Em3NilStream
Em3InvalidPositionOfRoot = class(Em3Exception)
end;//Em3InvalidPositionOfRoot
Em3InvalidOldPositionOfRoot = class(Em3InvalidPositionOfRoot)
public
class procedure Check(aPosition: Int64; aRootSize: Int64); overload;
end;//Em3InvalidOldPositionOfRoot
Em3InvalidNewPositionOfRoot = class(Em3InvalidPositionOfRoot)
public
class procedure Check(aPosition: Int64; aRootSize: Int64); overload;
end;//Em3InvalidNewPositionOfRoot
Tm3Int64Predicate = function (aPosition: Int64; aName: Tl3CustomString): Boolean of object;
Em3InvalidStoreData = class(Em3Exception)
public
class procedure Check(aCondition: Boolean; const aMessage: String; aName: Tl3String; aData: Int64); overload;
class procedure Check(aCondition: Tm3Int64Predicate; const aMessage: String; aName: Tl3String; aData: Int64); overload;
end;//Em3InvalidStoreData
Em3InvalidStreamSize = class(Em3InvalidStoreData)
public
class procedure Check(aCondition: Tm3Int64Predicate; aName: Tl3String; aData: Int64); overload;
end;//Em3InvalidStreamSize
Em3InvalidStreamPos = class(Em3InvalidStoreData)
public
class procedure Check(aCondition: Tm3Int64Predicate; aName: Tl3String; aData: Int64); overload;
end;//Em3InvalidStreamPos
implementation
uses
SysUtils
;
class procedure Em3InvalidOldPositionOfRoot.Check(aPosition: Int64; aRootSize: Int64);
begin
Check(aPosition = aRootSize, Format('Неверная старая позиция рутового потока. aPosition = %d. aRootSize = %d', [aPosition, aRootSize]));
end;
class procedure Em3InvalidNewPositionOfRoot.Check(aPosition: Int64; aRootSize: Int64);
begin
Check(aPosition = aRootSize, Format('Неверная новая позиция рутового потока. aPosition = %d. aRootSize = %d', [aPosition, aRootSize]));
end;
class procedure Em3Exception.Check(aCondition: Boolean; const aMessage: String);
begin
if not aCondition then
raise Self.Create(aMessage);
end;
class procedure Em3InvalidStoreData.Check(aCondition: Boolean; const aMessage: String; aName: Tl3String; aData: Int64);
begin
Check(aCondition, Format('Документ #%S. %s: %d', [aName.AsString, aMessage, aData]));
end;
class procedure Em3InvalidStoreData.Check(aCondition: Tm3Int64Predicate; const aMessage: String; aName: Tl3String; aData: Int64);
begin
Assert(Assigned(aCondition));
Check(aCondition(aData, aName), aMessage, aName, aData);
end;
class procedure Em3InvalidStreamSize.Check(aCondition: Tm3Int64Predicate; aName: Tl3String; aData: Int64);
begin
Check(aCondition, 'Неправильный размер потока', aName, aData);
end;
class procedure Em3InvalidStreamPos.Check(aCondition: Tm3Int64Predicate; aName: Tl3String; aData: Int64);
begin
Check(aCondition, 'Неправильный указатель потока', aName, aData);
end;
end. |
//Exercicio 91: Faça um algoritmo que imite as operações básicas de uma calculadora. Deve possuir um menu principal
//(criado a partir de uma função) e possuir as quatro operações básicas: soma, subtração, multiplicação e divisão.
//Cada ação deve ser executada a partir de uma função.
{ Solução em Portugol
Algoritmo Exercício91;
VAR
FUNCIONAMENTO: CARACTER;
OPERACAO: CARACTER;
FUNCAO MENU( A: CARACTER) : CARACTER;
INICIO
EXIBA("BEM VINDO A CALCULADORA DA FATEC-BTU!");
EXIBA("QUAL OPERAÇÃO VOCÊ DESEJA FAZER?");
LEIA(A);
MENU <- A;
FIM;
FUNCAO SOMA( J: CARACTER): REAL
VAR
A,B: REAL;
INICIO
EXIBA("DIGITE O PRIMEIRO NUMERO DA SOMA: ");
LEIA(A);
EXIBA("DIGITE O SEGUNDO NUMERO DA SOMA: ");
LEIA(B);
SOMA <- A+B;
FIM;
FUNCAO SUBTRACAO( J: CARACTER): REAL
VAR
A,B: REAL;
INICIO
EXIBA("DIGITE O PRIMEIRO NUMERO DA SUBTRACAO: ");
LEIA(A);
EXIBA("DIGITE O SEGUNDO NUMERO DA SUBTRACAO: ");
LEIA(B);
SUBTRACAO <- A-B;
FIM;
FUNCAO MULTIPLICACAO( J: CARACTER): REAL
VAR
A,B: REAL;
INICIO
EXIBA("DIGITE O PRIMEIRO NUMERO DA MULTIPLICAÇÃO: ");
LEIA(A);
EXIBA("DIGITE O SEGUNDO NUMERO DA MULTIPLICAÇÃO: ");
LEIA(B);
MULTIPLICACAO <- A*B;
FIM;
FUNCAO DIVISAO( A: CARACTER): REAL
VAR
A,B: REAL;
INICIO
EXIBA("DIGITE O PRIMEIRO NUMERO DA DIVISAO: ");
LEIA(A);
EXIBA("DIGITE O SEGUNDO NUMERO DA DIVISAO: ");
LEIA(B);
ENQUANTO( B = 0) FACA
EXIBA("DIGITE UM NUMERO DIFERENTE DE 0!!");
LEIA(B);
FIMENQUANTO;
DIVISAO <- A/B;
FIM;
INICIO
FUNCIONAMENTO <- "S";
OPERACAO <- "S";
ENQUANTO (FUNCIONAMENTO = "S") FACA
CASO (MENU(OPERACAO)) DE
"+": EXIBA(SOMA(OPERACAO));
"-": EXIBA(SUBTRACAO(OPERACAO);
"*": EXIBA(MULTIPLICACAO(OPERACAO);
"/": EXIBA(DIVISAO(OPERACAO);
SENAO
EXIBA("VOCÊ NÃO DIGITOU UMA OPERAÇÃO VÁLIDA!!");
FIMCASO;
EXIBA("DESEJA CONTINUAR USANDO A CALCULADORA?");
EXIBA("DIGITE S PARA CONTINUAR E QUALQUER OUTRA TECLA PARA SAIR DA CALCULADORA");
LEIA(FUNCIONAMENTO);
FIMENQUANTO;
EXIBA("Até logo!");
FIM.
}
// Solução em Pascal
Program Exercicio;
uses crt;
VAR
FUNCIONAMENTO: char;
OPERACAO: char;
Function MENU( A: char) : char;
Begin
writeln('BEM VINDO A CALCULADORA DA FATEC-BTU!');
writeln('QUAL OPERAÇÃO VOCÊ DESEJA FAZER?');
readln(A);
MENU := A;
End;
Function SOMA( J: Char): Real;
VAR
A,B: REAL;
Begin
writeln('DIGITE O PRIMEIRO NUMERO DA SOMA: ');
readln(A);
writeln('DIGITE O SEGUNDO NUMERO DA SOMA: ');
readln(B);
SOMA := A+B;
End;
Function SUBTRACAO( J: char): real;
VAR
A,B: REAL;
Begin
writeln('DIGITE O PRIMEIRO NUMERO DA SUBTRACAO: ');
readln(A);
writeln('DIGITE O SEGUNDO NUMERO DA SUBTRACAO: ');
writeln(B);
SUBTRACAO := A-B;
End;
Function MULTIPLICACAO( J: char): real;
VAR
A,B: REAL;
Begin
writeln('DIGITE O PRIMEIRO NUMERO DA MULTIPLICAÇÃO: ');
readln(A);
writeln('DIGITE O SEGUNDO NUMERO DA MULTIPLICAÇÃO: ');
readln(B);
MULTIPLICACAO := A*B;
End;
Function DIVISAO( J: char): real;
VAR
A,B: REAL;
Begin
writeln('DIGITE O PRIMEIRO NUMERO DA DIVISAO: ');
readln(A);
writeln('DIGITE O SEGUNDO NUMERO DA DIVISAO: ');
readln(B);
while( B = 0) do
Begin
writeln('DIGITE UM NUMERO DIFERENTE DE 0!!');
readln(B);
End;
DIVISAO := A/B;
End;
Begin
FUNCIONAMENTO := 'S';
OPERACAO := 'S';
while (FUNCIONAMENTO = 'S') do
Begin
case (MENU(OPERACAO)) of
'+': writeln(SOMA(OPERACAO):0:2);
'-': writeln(SUBTRACAO(OPERACAO):0:2);
'*': writeln(MULTIPLICACAO(OPERACAO):0:2);
'/': writeln(DIVISAO(OPERACAO):0:2);
else
writeln('VOCÊ NÃO DIGITOU UMA OPERAÇÃO VÁLIDA!!');
End;
writeln('DESEJA CONTINUAR USANDO A CALCULADORA?');
writeln('DIGITE S PARA CONTINUAR E QUALQUER OUTRA TECLA PARA SAIR DA CALCULADORA');
readln(FUNCIONAMENTO);
end;
writeln('Até logo!');
repeat until keypressed;
end. |
unit kwGetFontSize;
{* Возвращает установленный размер шрифта для стиля "Нормальный". }
// Модуль: "w:\common\components\rtl\Garant\Keywords4Daily\kwGetFontSize.pas"
// Стереотип: "ScriptKeyword"
// Элемент модели: "GetFontSize" MUID: (509B9A8A0270)
// Имя типа: "TkwGetFontSize"
interface
{$If Defined(nsTest) AND NOT Defined(NoScripts) AND NOT Defined(NoVCM)}
uses
l3IntfUses
, tfwRegisterableWord
, tfwScriptingInterfaces
;
type
TkwGetFontSize = {final} class(TtfwRegisterableWord)
{* Возвращает установленный размер шрифта для стиля "Нормальный". }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
end;//TkwGetFontSize
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) AND NOT Defined(NoVCM)
implementation
{$If Defined(nsTest) AND NOT Defined(NoScripts) AND NOT Defined(NoVCM)}
uses
l3ImplUses
, evStyleInterface
, SysUtils
//#UC START# *509B9A8A0270impl_uses*
//#UC END# *509B9A8A0270impl_uses*
;
class function TkwGetFontSize.GetWordNameForRegister: AnsiString;
begin
Result := 'GetFontSize';
end;//TkwGetFontSize.GetWordNameForRegister
procedure TkwGetFontSize.DoDoIt(const aCtx: TtfwContext);
//#UC START# *4DAEEDE10285_509B9A8A0270_var*
var
l_SI : TevStyleInterface;
//#UC END# *4DAEEDE10285_509B9A8A0270_var*
begin
//#UC START# *4DAEEDE10285_509B9A8A0270_impl*
l_SI := TevStyleInterface.Make;
try
aCtx.rEngine.PushInt(l_SI.Font.Size);
finally
FreeAndNil(l_SI);
end;
//#UC END# *4DAEEDE10285_509B9A8A0270_impl*
end;//TkwGetFontSize.DoDoIt
initialization
TkwGetFontSize.RegisterInEngine;
{* Регистрация GetFontSize }
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) AND NOT Defined(NoVCM)
end.
|
unit uPermissaoSolicitacaoVO;
interface
uses
System.SysUtils;
type
TPermissaoSolicitacaoVO = class
private
FOcorrenciaGeral: Boolean;
FAnalise: Boolean;
FOcorrenciaTecnica: Boolean;
FAbertura: Boolean;
FOcorrenciaRegra: Boolean;
FStatusSolicitacao: Boolean;
FTempo: Boolean;
FConfTempoGeral: Boolean;
procedure SetAbertura(const Value: Boolean);
procedure SetAnalise(const Value: Boolean);
procedure SetOcorrenciaGeral(const Value: Boolean);
procedure SetOcorrenciaRegra(const Value: Boolean);
procedure SetOcorrenciaTecnica(const Value: Boolean);
procedure SetStatusSolicitacao(const Value: Boolean);
procedure SetTempo(const Value: Boolean);
procedure SetConfTempoGeral(const Value: Boolean);
public
property Abertura: Boolean read FAbertura write SetAbertura;
property Analise: Boolean read FAnalise write SetAnalise;
property OcorrenciaGeral: Boolean read FOcorrenciaGeral write SetOcorrenciaGeral;
property OcorrenciaTecnica: Boolean read FOcorrenciaTecnica write SetOcorrenciaTecnica;
property OcorrenciaRegra: Boolean read FOcorrenciaRegra write SetOcorrenciaRegra;
property StatusSolicitacao: Boolean read FStatusSolicitacao write SetStatusSolicitacao;
property Tempo: Boolean read FTempo write SetTempo;
property ConfTempoGeral: Boolean read FConfTempoGeral write SetConfTempoGeral;
end;
implementation
{ TPermissaoSolicitacaoVO }
procedure TPermissaoSolicitacaoVO.SetAbertura(const Value: Boolean);
begin
FAbertura := Value;
end;
procedure TPermissaoSolicitacaoVO.SetAnalise(const Value: Boolean);
begin
FAnalise := Value;
end;
procedure TPermissaoSolicitacaoVO.SetConfTempoGeral(const Value: Boolean);
begin
FConfTempoGeral := Value;
end;
procedure TPermissaoSolicitacaoVO.SetOcorrenciaGeral(const Value: Boolean);
begin
FOcorrenciaGeral := Value;
end;
procedure TPermissaoSolicitacaoVO.SetOcorrenciaRegra(const Value: Boolean);
begin
FOcorrenciaRegra := Value;
end;
procedure TPermissaoSolicitacaoVO.SetOcorrenciaTecnica(const Value: Boolean);
begin
FOcorrenciaTecnica := Value;
end;
procedure TPermissaoSolicitacaoVO.SetStatusSolicitacao(const Value: Boolean);
begin
FStatusSolicitacao := Value;
end;
procedure TPermissaoSolicitacaoVO.SetTempo(const Value: Boolean);
begin
FTempo := Value;
end;
end.
|
unit Mat.Constants;
interface
const
// Message and dialogs strings.
ANALYSIS_PROGRESS_FINISHED = 'The analysis was finished succesfully';
ANALYSIS_PROGRESS_ROOTFOLDERNOTSPECIFIED =
'Please, specify root folder with project source code';
ANALYSIS_PROJECTVERSION_NOTDETECTED = 'Not detected';
COMPONENTS_DATABASE_MISSING_ERR = 'Components database is missing';
// Routines.
CRLF = #10#13;
SHELL_OPEN_COMMAND = 'open';
STRING_YES = 'Yes';
STRING_NO = 'No';
STANDART_VENDOR_NAME = '%Embarcadero%';
// SQL.
COMPONENTS_PARSE_FIELDS_SELECT_SQL = 'SELECT * FROM ComponentsDatabase ' +
'WHERE flowertitle = ''';
COMPONENTS_PARSE_FIELDS_INSERT_SQL = 'INSERT OR IGNORE INTO Uses SELECT *' +
' FROM ComponentsDatabase WHERE flowertitle = ''';
INSERT_USES_SQL =
'INSERT or ignore INTO Uses(ftitle, flowertitle ) VALUES (:ftitle, :flowertitle);';
INSERT_PG_SQL =
'INSERT or ignore INTO ProjectGroups(ftitle, fpath, fversion) VALUES (:ftitle, :fpath, :fversion);';
INSERT_PJ_SQL =
'INSERT or ignore INTO Projects(ftitle, fpath, fpgpath, fversion)' +
' VALUES (:ftitle, :fpath, :fpgpath, :fversion);';
INSERT_UNITS_SQL = 'INSERT or ignore INTO Units(ftitle, fpath, ' +
'fppath, flinescount, fformname ) VALUES ' +
'(:ftitle, :fpath, :fppath, :flinescount, :fformname);';
SELECT_PG_COUNT = 'SELECT Count(*) from ProjectGroups';
SELECT_PJ_COUNT = 'SELECT Count(*) from Projects';
SELECT_UNITS_COUNT = 'SELECT Count(*) from Units';
SELECT_ULINESCOUNT_COUNT = 'SELECT Sum(Units.flinescount) from Units';
SELECT_PJVERSION = 'SELECT DISTINCT fversion from Projects';
SHOW_PG_SQL =
'SELECT ProjectGroups.rowno as "#", ProjectGroups.ftitle as "Project Group Name",'
+ ' ProjectGroups.fpath as "Path" , ProjectGroups.fversion as "Project version" '
+ ' FROM ProjectGroups ORDER BY ';
SHOW_PJ_SQL =
'SELECT Projects.rowno as "#", Projects.ftitle as "Project Name", ' +
' ProjectGroups.ftitle as "Project Group Name",' +
' Projects.fpath as "Path" , Count(Units.fpath) as "Units amount", ' +
' SUM(Units.fformname != "") as "Forms amount", Projects.fversion as "Project version" '
+ ' FROM Projects LEFT JOIN ProjectGroups ON (Projects.fpgpath = ProjectGroups.fpath) '
+ ' LEFT JOIN Units ON (Projects.fpath = Units.fppath) ' +
' GROUP BY Projects.fpath ORDER BY ';
SHOW_U_SQL =
'SELECT Units.rowno as "#", Projects.ftitle as "Project Name", ' +
' Units.ftitle as "Unit Name",' +
' Units.fpath as "Path" , Units.flinescount as "Lines" ' +
' FROM Units LEFT JOIN Projects ON (Projects.fpath = Units.fppath) ORDER BY ';
SHOW_C_SQL = 'SELECT Uses.rowno as "#",' +
' ftitle as "Uses", package as "Package", vendor as "Vendor", ' +
'projecthomeurl as "Project home URL", licensename as "License name", ' +
'licensetype as "License type", classes as "Classes", platformssupport as "Platforms support", '
+ ' radstudioversionssupport as "RADStudio versions support", versionscompatibility as '
+ ' "Versions compatibility", analogues as "Analogues", comment as "Comment", '
+ ' convertto as "Convert to" FROM Uses ORDER BY ';
INSERT_INTO_TABLE_SQL = ' (ftitle, flowertitle, package, vendor, ' +
'projecthomeurl, licensename, licensetype, classes, platformssupport, radstudioversionssupport, '
+ 'versionscompatibility, analogues, convertto, comment ) VALUES (:ftitle, :flowertitle, :package, :vendor, '
+ ':projecthomeurl, :licensename, :licensetype, :classes, :platformssupport, :radstudioversionssupport, '
+ ':versionscompatibility, :analogues, :convertto, :comment );';
INSERT_INTO_TABLE_SQL_P = 'INSERT or ignore INTO ';
CLEAR_PG_TABLE_SQL = 'DELETE FROM ProjectGroups;';
CLEAR_PJ_TABLE_SQL = ('DELETE FROM Projects;');
CLEAR_UNITS_TABLE_SQL = ('DELETE FROM Units;');
CLEAR_USES_TABLE_SQL = ('DELETE FROM Uses;');
CLEAR_TYPES_TABLE_SQL = ('DELETE FROM Types;');
CLEAR_CD_TABLE_SQL = ('DELETE FROM ComponentsDatabase;');
CREATE_TABLES_SQL =
'CREATE TABLE IF NOT EXISTS ProjectGroups (rowno TEXT NULL, ftitle TEXT NULL,'
+ ' fpath TEXT UNIQUE NULL PRIMARY KEY COLLATE NOCASE, fversion TEXT NULL); '
+ 'CREATE TABLE IF NOT EXISTS Projects (rowno TEXT NULL, ftitle TEXT NULL,'
+ ' fpath TEXT UNIQUE NULL PRIMARY KEY COLLATE NOCASE, fpgpath TEXT NULL, fversion TEXT NULL); '
+ ' CREATE TABLE IF NOT EXISTS Units (rowno TEXT NULL, ftitle TEXT NULL,'
+ ' fpath TEXT UNIQUE NULL PRIMARY KEY COLLATE NOCASE, fppath TEXT NULL,'
+ ' flinescount NUMERIC NULL, fpointerscount NUMERIC NULL, fformname TEXT NULL); '
+ ' CREATE TABLE IF NOT EXISTS Uses (rowno TEXT NULL, ftitle TEXT NULL,'
+ ' flowertitle TEXT UNIQUE NULL PRIMARY KEY COLLATE NOCASE, package TEXT NULL,'
+ ' vendor TEXT NULL, projecthomeurl TEXT NULL, licensename TEXT NULL,'
+ ' licensetype TEXT NULL, classes TEXT NULL, platformssupport TEXT NULL, '
+ ' radstudioversionssupport TEXT NULL, ' +
' versionscompatibility TEXT NULL, analogues TEXT NULL, comment TEXT NULL, '
+ ' convertto TEXT NULL); ' +
' CREATE TABLE IF NOT EXISTS ComponentsDatabase (rowno TEXT NULL, ftitle TEXT NULL,'
+ ' flowertitle TEXT UNIQUE NULL PRIMARY KEY COLLATE NOCASE, package TEXT NULL,'
+ ' vendor TEXT NULL, projecthomeurl TEXT NULL, licensename TEXT NULL,'
+ ' licensetype TEXT NULL, classes TEXT NULL, platformssupport TEXT NULL, '
+ ' radstudioversionssupport TEXT NULL, ' +
' versionscompatibility TEXT NULL, analogues TEXT NULL, comment TEXT NULL, '
+ ' convertto TEXT NULL); ' +
' CREATE TABLE IF NOT EXISTS Types (rowno TEXT NULL, ftitle TEXT NULL,'
+ ' flowertitle TEXT UNIQUE NULL PRIMARY KEY COLLATE NOCASE);';
DETECT_STANDART_CLASSES_COUNT_SQL =
'SELECT Count(*) FROM Uses WHERE vendor LIKE ''';
// Database settings.
SQL_DRIVER_NAME = 'SQLite';
SQL_DATABASE_FILENAME = 'ParserDatabase.db';
COMPONENTS_DATABASE_TABLE_NAME = 'ComponentsDatabase';
// Fields.
FTITLE_FIELD_NAME = 'ftitle';
FLOWER_TITLE_FIELD_NAME = 'flowertitle';
FPATH_FIELD_NAME = 'fpath';
FVERSION_FIELD_NAME = 'fversion';
FPGPATH_FIELD_NAME = 'fpgpath';
FPPATH_FIELD_NAME = 'fppath';
FLINESCOUNT_FIELD_NAME = 'flinescount';
FFORMNAME_FIELD_NAME = 'fformname';
FPACKAGE_FIELD_NAME = 'package';
FVENDOR_FIELD_NAME = 'vendor';
FPJ_HOME_URL_FIELD_NAME = 'projecthomeurl';
FLICELCSE_NAME_FIELD_NAME = 'licensename';
FLICELCSE_TYPE_FIELD_NAME = 'licensetype';
FCLASSES_FIELD_NAME = 'classes';
FPLATFORM_SUPPORT_NAME = 'platformssupport';
FRADVERSION_SUPPORT_NAME = 'radstudioversionssupport';
FVERSION_COMPATIBILITY_NAME = 'versionscompatibility';
FANALOGUES_FIELD_NAME = 'analogues';
FCONVERTTO_FIELD_NAME = 'convertto';
FCOMMENT_FIELD_NAME = 'comment';
FROW_NO_FIELD_NAME = '#';
SUPPORTED_VERSIONS_FIELD_NAME = 'RADStudio versions support';
FIELDS_LIST = 'ftitle, flowertitle, package, vendor, ' +
'projecthomeurl, licensename, licensetype, classes, platformssupport, radstudioversionssupport, '
+ 'versionscompatibility, analogues, convertto, comment ';
FIELD_BORDER_WIDTH = 3;
// Sort constants.
SORT_ASC = 0;
SORT_DESC = 1;
SORT_DESC_STR = ' Desc ';
SORT_ASC_STR = ' Asc ';
DEFAULT_SORT = ' 1 Asc ';
DELPHI_VERSIONS: TArray<String> = ['Unknown', 'Delphi 5', 'Delphi 7'];
MAX_VERSION_WARNING = 20;
// Colors.
WARNING_COLOR = $004FD0F7;
PROGRESS_COLOR = $204FD0F7;
// Ini file settings.
DATABASE_FOLDER = '\Database\';
SETTINGS_FOLDER = '\Settings\';
COLUMN_SECTION_NAME = 'column';
FOLDER_SECTION_NAME = 'Folder';
LAST_FOLDER_SECTION_NAME = 'lastfolder';
// XML file.
PG_NODE = 'PropertyGroup';
PE_NODE = 'ProjectExtensions';
BP_NODE = 'BorlandProject';
PF_NODE = 'Platforms';
PV_NODE = 'ProjectVersion';
NODE_ATTR = 'value';
WIN64_CONST = 'Win64';
TRUE_VALUE = 'True';
// Parser search strings.
ASM_SEARCH_STRING = 'asm';
USES_SEARCH_STRING = 'uses';
TYPE_SEARCH_STRING = 'type';
IMPLEMENTATION_SEARCH_STRING = 'implementation';
PROGRAMM_SEARCH_STRING = 'program';
LIBRARY_SEARCH_STRING = 'library';
BDE_USES = 'DBTables';
VERSION_CONST = 'version';
// JSON file pairs.
PACKAGE_JSON_PAIR = 'Package';
VENDOR_JSON_PAIR = 'Vendor';
PROJECTHOMEURL_JSON_PAIR = 'ProjectHomeUrl';
LICENSENAME_JSON_PAIR = 'LicenseName';
LICENSETYPE_JSON_PAIR = 'LicenseType';
CLASSES_JSON_PAIR = 'Classes';
PLATFORMSSUPPORT_JSON_PAIR = 'PlatformsSupport';
RADSTUDIOVERSIONSSUPPORT_JSON_PAIR = 'RADStudioVersionsSupport';
VERSIONSCOMPATIBILITY_JSON_PAIR = 'VersionsCompatibility';
ANALOGUES_JSON_PAIR = 'Analogues';
COMMENT_JSON_PAIR = 'Comment';
CONVERTTO_JSON_PAIR = 'ConvertTo';
// About.
CONTRIBUTORS = 'Serge Pilko, Ruvim Tsevan, Sergey Khatskevich';
// FileNames.
SETTINGS_FILE_NAME = 'Settings.ini';
JSON_FILE_NAME = 'ComponentsDatabase.json';
NEW_FILE_FORMAT_ADDICT = 'oj';
// Files extensions.
PROJECT_GROUP_EXT_AST = '*.bpg';
PROJECT_EXT_AST = '*.dpr';
PROJECT_EXT = '.dpr';
PAS_EXT = '.pas';
PAS_EXT_AST = '*.pas';
CSV_EXT = '.csv';
CSV_FILTER = 'CSV (*.csv)|*.csv';
// URLS.
URL_EMBARCADERO_CUSTOMERPORTAL = 'https://my.embarcadero.com/#login';
URL_EMBARCADERO_FIREDACMIGRATION =
'http://docwiki.embarcadero.com/RADStudio/Sydney/en/BDE_Application_Migration_(FireDAC)';
URL_EMBARCADERO_UNICODE =
'http://docwiki.embarcadero.com/RADStudio/Sydney/en/Unicode_in_RAD_Studio';
URL_LICENSE_APACHE20 = 'https://www.apache.org/licenses/LICENSE-2.0';
implementation
end.
|
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: François PIETTE
Description: This demo show how to use the TPing object to ping any host.
Creation: November 30, 1997
Version: 6.00
EMail: francois.piette@overbyte.be http://www.overbyte.be
Support: Use the mailing list twsocket@elists.org
Follow "support" link at http://www.overbyte.be for subscription.
Legal issues: Copyright (C) 1997-2006 by François PIETTE
Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56
<francois.piette@overbyte.be>
This software is provided 'as-is', without any express or
implied warranty. In no event will the author be held liable
for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it
and redistribute it freely, subject to the following
restrictions:
1. The origin of this software must not be misrepresented,
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
4. You must register this software by sending a picture postcard
to the author. Use a nice stamp and mention your name, street
address, EMail address and any comment you like to say.
Updates:
Dec 13, 1997 V1.01 Use the new OnEchoRequest and OnEchoReply events.
Dec 26, 1998 V1.02 Changed event handler for new TPing version (1.10)
Nov 10, 2002 V1.03 Added Reply.Status in display when failed
Changed argument name from Error to Status in EchoReply
event (same change has in component).
Mar 26, 2006 V6.00 Created new version 6.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
unit OverbyteIcsPingTst1;
{$I OverbyteIcsDefs.inc}
interface
uses
Windows, Messages, SysUtils, Classes, Forms, StdCtrls, Controls,
OverbyteIcsWndControl, OverbyteIcsPing;
const
PingTestVersion = 600;
CopyRight : String = ' PingTest (c) 1997-2006 Francois Piette V6.00 ';
type
TPingTstForm = class(TForm)
Ping1: TPing;
Label1: TLabel;
HostEdit: TEdit;
PingButton: TButton;
DisplayMemo: TMemo;
CancelButton: TButton;
procedure PingButtonClick(Sender: TObject);
procedure Ping1Display(Sender: TObject; Icmp: TObject; Msg: String);
procedure Ping1DnsLookupDone(Sender: TObject; Error: Word);
procedure CancelButtonClick(Sender: TObject);
procedure Ping1EchoRequest(Sender: TObject; Icmp: TObject);
procedure Ping1EchoReply(Sender: TObject; Icmp: TObject; Status: Integer);
end;
var
PingTstForm: TPingTstForm;
implementation
{$R *.DFM}
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPingTstForm.PingButtonClick(Sender: TObject);
begin
DisplayMemo.Clear;
DisplayMemo.Lines.Add('Resolving host ''' + HostEdit.Text + '''');
PingButton.Enabled := FALSE;
CancelButton.Enabled := TRUE;
Ping1.DnsLookup(HostEdit.Text);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPingTstForm.Ping1DnsLookupDone(Sender: TObject; Error: Word);
begin
CancelButton.Enabled := FALSE;
PingButton.Enabled := TRUE;
if Error <> 0 then begin
DisplayMemo.Lines.Add('Unknown Host ''' + HostEdit.Text + '''');
Exit;
end;
DisplayMemo.Lines.Add('Host ''' + HostEdit.Text + ''' is ' + Ping1.DnsResult);
Ping1.Address := Ping1.DnsResult;
Ping1.Ping;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPingTstForm.Ping1Display(Sender: TObject; Icmp: TObject; Msg: String);
begin
DisplayMemo.Lines.Add(Msg);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPingTstForm.CancelButtonClick(Sender: TObject);
begin
Ping1.CancelDnsLookup;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPingTstForm.Ping1EchoRequest(Sender: TObject; Icmp: TObject);
begin
DisplayMemo.Lines.Add('Sending ' + IntToStr(Ping1.Size) + ' bytes to ' +
Ping1.HostName + ' (' + Ping1.HostIP + ')');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TPingTstForm.Ping1EchoReply(
Sender : TObject;
Icmp : TObject;
Status : Integer);
begin
if Status <> 0 then
{ Success }
DisplayMemo.Lines.Add('Received ' + IntToStr(Ping1.Reply.DataSize) +
' bytes from ' + Ping1.HostIP +
' in ' + IntToStr(Ping1.Reply.RTT) + ' msecs')
else
{ Failure }
DisplayMemo.Lines.Add('Cannot ping host (' + Ping1.HostIP + ') : ' +
Ping1.ErrorString +
'. Status = ' + IntToStr(Ping1.Reply.Status));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
end.
|
unit csSpellCorrectTask;
interface
{$I CsDefine.inc}
uses
csProcessTask, Classes, ddProgressObj, DT_Types;
type
TcsSpellCorrectTask = class(TddProcessTask)
private
f_ReplacementFile: AnsiString;
protected
function GetDescription: AnsiString; override;
procedure LoadFrom(aStream: TStream; aIsPipe: Boolean); override;
public
constructor Create(aOwner: TObject; aUserID: TUserID); override;
procedure SaveTo(aStream: TStream; aIsPipe: Boolean); override;
property ReplacementFile: AnsiString read f_ReplacementFile write f_ReplacementFile;
end;
implementation
uses
csTaskTypes,
l3FileUtils,
SysUtils;
{
******************************** TddProcessTask ********************************
}
constructor TcsSpellCorrectTask.Create(aOwner: TObject; aUserID: TUserID);
begin
inherited;
TaskType:= cs_ttSpellCheck;
Status := cs_tsDelayed;
end;
function TcsSpellCorrectTask.GetDescription: AnsiString;
begin
Result:= 'Исправление опечаток по файлу '+ ExtractFileName(ReplacementFile);
end;
procedure TcsSpellCorrectTask.LoadFrom(aStream: TStream; aIsPipe: Boolean);
var
l_S: AnsiString;
begin
inherited;
if Status <> cs_tsDone then
begin
ReadFileFrom(aStream, TaskFolder);
ReadString(aStream, l_S);
f_ReplacementFile:= ConcatDirName(TaskFolder, l_S);
end;
end;
procedure TcsSpellCorrectTask.SaveTo(aStream: TStream; aIsPipe: Boolean);
var
l_Filename: AnsiString;
begin
inherited;
if Status <> cs_tsDone then
begin
l_FileName:= ExtractFileName(f_replacementFile);
WriteFileTo(aStream, f_replacementFile, l_FileName);
WriteString(aStream, l_FileName);
end;
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.7 10/26/2004 10:20:04 PM JPMugaas
Updated refs.
Rev 1.6 2004.02.03 5:45:14 PM czhower
Name changes
Rev 1.5 1/31/2004 1:18:40 PM JPMugaas
Illiminated Todo; item so it should work in DotNET.
Rev 1.4 1/21/2004 3:11:04 PM JPMugaas
InitComponent
Rev 1.3 10/19/2003 4:51:34 PM DSiders
Added localization comments.
Rev 1.2 2003.10.12 3:53:12 PM czhower
compile todos
Rev 1.1 3/5/2003 11:41:14 PM BGooijen
Added IdCoreGlobal to the uses, this file was needed for the call to
Sleep(...)
Rev 1.0 12/28/2002 3:04:52 PM DSiders
Initial revision.
}
unit IdIPAddrMon;
{
TIdIPAddrMon
Monitors adapters known to the IP protocol stack for changes in any
of the IP addresses. Similar to TIdIPWatch, but monitors all IP
addresses/adapters.
Does not keep a permanent IP address history list. But does trigger
a TIdIPAddrMonEvent event to signal the adapter number, old IP, and
new IP for the change in status.
OnStatusChanged is used to capture changed IP addresses, and/or
to sync with GUI display controls. If you do not assign a procedure
for the event handler, this component essentially does nothing except
eat small amounts of CPU time.
The thread instance is created and freed when the value in Active is
changed.
TIdIPAddrMonEvent
An procedure use to handle notifications from the component. Includes
parameters that represent the adapter number, previous IP or '<unknown>',
and the current IP or '<unknown>'.
TIdIPAddrMonThread
Timer thread for the IP address monitor component. Based on
TIdIPWatchThread.
Sleeps in increments of .5 seconds until the Interval has elapsed, and
fires the timer event. Sleep is called in increments to allow checking
for Terminated when a long Interval has been specified.
Original Author:
Don Siders, Integral Systems, Fri 27 Dec 2002
Donated to the Internet Direct (Indy) Project for use under the
terms of the Indy Dual License.
}
interface
{$i IdCompilerDefines.inc}
uses
Classes,
IdComponent,
IdThread;
const
IdIPAddrMonInterval = 500;
type
TIdIPAddrMonEvent =
procedure(ASender: TObject; AAdapter: Integer; AOldIP, ANewIP: string) of object;
TIdIPAddrMonThread = class(TIdThread)
protected
FOwner: TObject;
FInterval: Cardinal;
FOnTimerEvent: TNotifyEvent;
procedure Run; override;
procedure DoTimerEvent;
end;
TIdIPAddrMon = class(TIdComponent)
private
FActive: Boolean;
FBusy: Boolean;
FInterval: Cardinal;
FAdapterCount: Integer;
FThread: TIdIPAddrMonThread;
FIPAddresses: TStrings;
FPreviousIPAddresses: TStrings;
FOnStatusChanged: TIdIPAddrMonEvent;
procedure SetActive(Value: Boolean);
procedure SetInterval(Value: Cardinal);
procedure GetAdapterAddresses;
procedure DoStatusChanged;
protected
procedure InitComponent; override;
procedure Loaded; override;
public
destructor Destroy; override;
procedure CheckAdapters(Sender: TObject);
procedure ForceCheck;
property AdapterCount: Integer read FAdapterCount;
property Busy: Boolean read FBusy;
property IPAddresses: TStrings read FIPAddresses;
property Thread: TIdIPAddrMonThread read FThread;
published
property Active: Boolean read FActive write SetActive;
property Interval: Cardinal read FInterval write SetInterval default IdIPAddrMonInterval;
property OnStatusChanged: TIdIPAddrMonEvent read FOnStatusChanged write FOnStatusChanged;
end;
implementation
uses
{$IFDEF DOTNET}
{$IFDEF USE_INLINE}
System.Threading,
{$ENDIF}
{$ENDIF}
{$IFDEF USE_VCL_POSIX}
Posix.SysSelect,
Posix.SysTime,
{$ENDIF}
IdGlobal,
IdStack,
SysUtils;
procedure TIdIPAddrMon.InitComponent;
begin
inherited InitComponent;
FInterval := IdIPAddrMonInterval;
FActive := False;
FBusy := False;
FAdapterCount := 0;
FIPAddresses := TStringList.Create;
FPreviousIPAddresses := TStringList.Create;
// FThread created when component becomes Active
end;
destructor TIdIPAddrMon.Destroy;
begin
Active := False;
FBusy := False;
FIPAddresses.Free;
FPreviousIPAddresses.Free;
// FThread freed on Terminate
inherited Destroy;
end;
procedure TIdIPAddrMon.Loaded;
begin
inherited Loaded;
// Active = True must not be performed before all other props are loaded
if Active then begin
FActive := False;
Active := True;
end;
end;
procedure TIdIPAddrMon.CheckAdapters(Sender: TObject);
begin
// previous check could still be running...
if FBusy then begin
Exit;
end;
FBusy := True;
try
try
GetAdapterAddresses;
// something changed at runtime
if (not IsDesignTime) and
((FPreviousIPAddresses.Count <> FIPAddresses.Count) or
(FPreviousIPAddresses.Text <> FIPAddresses.Text)) then
begin
DoStatusChanged;
end;
except
// eat any exception
end;
finally
FBusy := False;
end;
end;
procedure TIdIPAddrMon.DoStatusChanged;
var
iOldCount: Integer;
iNewCount: Integer;
iAdapter: Integer;
sOldIP: string;
sNewIP: string;
begin
if not Assigned(FOnStatusChanged) then
begin
Exit;
end;
// figure out the change... new, removed, or altered IP for adapter(s)
iOldCount := FPreviousIPAddresses.Count;
iNewCount := FIPAddresses.Count;
// find the new adapter IP address
if iOldCount < iNewCount then
begin
sOldIP := '<unknown>'; {do not localize}
for iAdapter := 0 to iNewCount - 1 do
begin
sNewIP := FIPAddresses[iAdapter];
if FPreviousIPAddresses.IndexOf(sNewIP) = -1 then
begin
FOnStatusChanged(Self, iAdapter, sOldIP, sNewIP);
end;
end;
end
// find the missing adapter IP address
else if iOldCount > iNewCount then
begin
sNewIP := '<unknown>'; {do not localize}
for iAdapter := 0 to iOldCount - 1 do
begin
sOldIP := FPreviousIPAddresses[iAdapter];
if FIPAddresses.IndexOf(sOldIP) = -1 then
begin
FOnStatusChanged(Self, iAdapter, sOldIP, sNewIP);
end;
end;
end
// find the altered adapter IP address
else
begin
for iAdapter := 0 to AdapterCount - 1 do
begin
sOldIP := FPreviousIPAddresses[iAdapter];
sNewIP := FIPAddresses[iAdapter];
if sOldIP <> sNewIP then
begin
FOnStatusChanged(Self, iAdapter, sOldIP, sNewIP);
end;
end;
end;
end;
procedure TIdIPAddrMon.ForceCheck;
begin
CheckAdapters(nil);
end;
procedure TIdIPAddrMon.SetActive(Value: Boolean);
begin
if Value <> FActive then
begin
if Value then
begin
// get initial addresses at start-up and allow display in IDE
GetAdapterAddresses;
end;
if (not IsDesignTime) and (not IsLoading) then
begin
if Value then
begin
FThread := TIdIPAddrMonThread.Create(True);
with FThread do
begin
FOwner := Self;
FOnTimerEvent := CheckAdapters;
FInterval := Self.Interval;
Start;
end;
end else
begin
if FThread <> nil then begin
FThread.TerminateAndWaitFor;
FreeAndNil(FThread);
end;
end;
end;
FActive := Value;
end;
end;
procedure TIdIPAddrMon.SetInterval(Value: Cardinal);
begin
FInterval := Value;
if Assigned(FThread) then begin
FThread.FInterval := FInterval;
end;
end;
procedure TIdIPAddrMonThread.Run;
var
lInterval: Integer;
begin
lInterval := FInterval;
while lInterval > 0 do
begin
// force a check for terminated every .5 sec
if lInterval > 500 then
begin
IndySleep(500);
lInterval := lInterval - 500;
end else
begin
IndySleep(lInterval);
LInterval := 0;
end;
if Terminated then
begin
Exit;
end;
end;
// interval has elapsed... fire the thread timer event
Synchronize(DoTimerEvent);
end;
procedure TIdIPAddrMonThread.DoTimerEvent;
begin
if Assigned(FOnTimerEvent) then begin
FOnTimerEvent(FOwner);
end;
end;
procedure TIdIPAddrMon.GetAdapterAddresses;
begin
{
Doesn't keep a permanent history list like TIdIPWatch...
but does track previous IP addresses to detect changes.
}
FPreviousIPAddresses.Text := FIPAddresses.Text;
FIPAddresses.Clear;
GStack.AddLocalAddressesToList(FIPAddresses);
FAdapterCount := FIPAddresses.Count;
end;
end.
|
unit UntLib;
interface
uses
FMX.Objects,
FMX.Edit,
FMX.TabControl,
FMX.Multiview,
FMX.Forms,
FMX.Layouts,
FMX.Types,
FMX.StdCtrls,
FMX.VirtualKeyboard,
FMX.Platform,
FMX.Controls,
{$IFDEF ANDROID}
FMX.Platform.Android,
FMX.Helpers.Android,
// FMX.Permissions.Android,
Androidapi.JNI.GraphicsContentViewText,
Androidapi.Helpers,
Androidapi.JNI.Telephony,
Androidapi.JNI.Provider,
Androidapi.JNIBridge,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.Os,
Androidapi.JNI.Net,
Androidapi.JNI.App,
{$ENDIF}
System.StrUtils,
System.IOUtils,
System.SysUtils,
System.RegularExpressions,
System.Types,
System.Classes,
System.Rtti,
System.UITypes,
idTCPClient;
// ksTabControl;
type
TLibrary = class
private
public
class function FormataCurrency(AValue: String; ACasasDecimais: Integer; ABackspaceIsPressedEdtCurrency: Boolean = False): String;
class function LPad(S: string; Ch: Char; Len: Integer): string; // Insere a quantidade Len de Ch aa esquerda
class function RPad(S: string; Ch: Char; Len: Integer): string; // Insere a quantidade Len de Ch aa direita
end;
implementation
{ TLibrary }
class function TLibrary.FormataCurrency(AValue: String; ACasasDecimais: Integer; ABackspaceIsPressedEdtCurrency: Boolean): String;
var
VAntesSeparador, VDepoisSeparador, VMaiorQue100: String;
VLength: Integer;
i: Integer;
begin
VMaiorQue100 := '';
if (Pos(',', AValue) <= 0) then
begin
AValue := AValue + ',' + RPad('', '0', ACasasDecimais);
end;
if not(ABackspaceIsPressedEdtCurrency) then
if ((Length(AValue)) - (Pos(',', AValue)) < ACasasDecimais) then
begin
while ((Length(AValue)) - (Pos(',', AValue)) < ACasasDecimais) do
begin
AValue := AValue + '0';
end;
end;
AValue := StringReplace(AValue, ',', '', [rfReplaceAll]);
AValue := StringReplace(AValue, '.', '', [rfReplaceAll]);
{ Tira os 0 aa esquerda }
if (TryStrToInt(AValue, i)) then
AValue := IntToStr(i);
while (AValue.Length <= ACasasDecimais) do
begin
AValue := '0' + AValue;
end;
VLength := AValue.Length;
VAntesSeparador := LeftStr(AValue, VLength - ACasasDecimais);
VDepoisSeparador := RightStr(AValue, ACasasDecimais);
Result := VMaiorQue100 + VAntesSeparador + ',' + VDepoisSeparador;
end;
class function TLibrary.LPad(S: string; Ch: Char; Len: Integer): string;
var
RestLen: Integer;
begin
Result := S;
RestLen := Len - Length(S);
if RestLen < 1 then
Exit;
Result := S + StringOfChar(Ch, RestLen);
end;
class function TLibrary.RPad(S: string; Ch: Char; Len: Integer): string;
var
RestLen: Integer;
begin
Result := S;
RestLen := Len - Length(S);
if RestLen < 1 then
Exit;
Result := StringOfChar(Ch, RestLen) + S;
end;
end.
|
unit AsyncServerCnxHandler;
interface
uses
VoyagerInterfaces, VoyagerServerInterfaces, Events, Protocol, Windows, Controls,
RDOServer, RDOInterfaces, Classes, Collection;
type
TAsyncServerCnxHandler =
class( TInterfacedObject, IMetaURLHandler, IURLHandler, IAsyncClientView )
public
constructor Create;
destructor Destroy; override;
// IMetaURLHandler
private
function getName : string;
function getOptions : TURLHandlerOptions;
function getCanHandleURL( URL : TURL ) : THandlingAbility;
function Instantiate : IURLHandler;
// IURLHandler
private
function HandleURL( URL : TURL ) : TURLHandlingResult;
function HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult;
function getControl : TControl;
procedure setMasterURLHandler( URLHandler : IMasterURLHandler );
private
fMasterURLHandler : IMasterURLHandler;
// IAsyncClientView
private
function SetViewedArea( x, y, dx, dy : integer; Notification : TAsyncSetViewedAreaResponse ) : TAsyncRequestId;
function ObjectsInArea( x, y, dx, dy : integer; Notification : TAsyncObjectsInAreaResponse ) : TAsyncRequestId;
function ObjectAt( x, y : integer; Notification : TAsyncObjectAtResponse ) : TAsyncRequestId;
function ObjectStatusText( kind : TStatusKind; Id : TObjId; Notification : TAsyncObjectStatusTextResponse ) : TAsyncRequestId;
function ObjectConnections( Id : TObjId; Notification : TAsyncObjectConnectionsResponse ) : TAsyncRequestId;
function FocusObject( Id : TObjId; Notification : TAsyncFocusObjectResponse ) : TAsyncRequestId;
function UnfocusObject( Id : TObjId; Notification : TAsyncUnfocusObjectResponse ) : TAsyncRequestId;
function SwitchFocus( From : TObjId; toX, toY : integer; Notification : TAsyncSwitchFocusResponse ) : TAsyncRequestId;
function GetCompanyList( Notification : TAsyncGetCompanyListResponse ) : TAsyncRequestId;
function NewCompany( name, cluster : string; Notification : TAsyncNewCompanyResponse ) : TAsyncRequestId;
function NewFacility( FacilityId : string; CompanyId : integer; x, y : integer; Notification : TAsyncNewFacilityResponse ) : TAsyncRequestId;
function GetUserList( Notification : TAsyncGetUserListResponse ) : TAsyncRequestId;
function SayThis( Dest, Msg : string; Notification : TAsyncSayThisResponse ) : TAsyncRequestId;
function MsgCompositionChanged( State : TMsgCompositionState; Notification : TAsyncMsgCompChangedResponse ) : TAsyncRequestId;
function Chase( UserName : string; Notification : TAsyncChaseResponse ) : TAsyncRequestId;
function StopChase( Notification : TAsyncStopChaseResponse ) : TAsyncRequestId;
function Logoff( Notification : TAsyncLogoffResponse ) : TAsyncRequestId;
private
function getClientView : IClientView;
procedure DisposeObjectReport( var ObjectReport : TObjectReport );
procedure DisposeSegmentReport( var SegmentReport : TSegmentReport );
procedure DisposeCnxReport( var CnxReport : TCnxReport );
private
fClientView : IClientView;
fLastRequestId : TAsyncRequestId;
private
function GetNextRequestId : TAsyncRequestId;
end;
const
tidMetaHandlerName_AsyncServerCnx = 'AsyncServerCnx';
const
evnBase_AsyncCnxHandler = 50;
const
evnAnswerAsyncClientView = evnBase_AsyncCnxHandler + 0;
implementation
uses
ServerCnxHandler, ServerCnxEvents;
// TAsyncServerCnxHandler
constructor TAsyncServerCnxHandler.Create;
begin
inherited Create;
end;
destructor TAsyncServerCnxHandler.Destroy;
begin
inherited;
end;
function TAsyncServerCnxHandler.getName : string;
begin
result := tidMetaHandlerName_AsyncServerCnx;
end;
function TAsyncServerCnxHandler.getOptions : TURLHandlerOptions;
begin
result := [hopNonvisual];
end;
function TAsyncServerCnxHandler.getCanHandleURL( URL : TURL ) : THandlingAbility;
begin
result := 0;
end;
function TAsyncServerCnxHandler.Instantiate : IURLHandler;
begin
result := self;
end;
function TAsyncServerCnxHandler.HandleURL( URL : TURL ) : TURLHandlingResult;
begin
result := urlHandled;
end;
function TAsyncServerCnxHandler.HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult;
var
AsyncClientView : IAsyncClientView absolute info;
begin
if EventId = evnAnswerAsyncClientView
then
begin
AsyncClientView := self;
result := evnHandled;
end
else result := evnNotHandled;
end;
function TAsyncServerCnxHandler.getControl : TControl;
begin
result := nil;
end;
procedure TAsyncServerCnxHandler.setMasterURLHandler( URLHandler : IMasterURLHandler );
begin
fMasterURLHandler := URLHandler;
fMasterURLHandler.HandleEvent( evnAnswerClientView, fClientView );
end;
function TAsyncServerCnxHandler.SetViewedArea( x, y, dx, dy : integer; Notification : TAsyncSetViewedAreaResponse ) : TAsyncRequestId;
var
ErrorCode : TErrorCode;
begin
try
try
fClientView.SetViewedArea( x, y, dx, dy, ErrorCode );
except
ErrorCode := ERROR_Unknown;
end;
result := GetNextRequestId;
if assigned(Notification)
then Notification( result, ErrorCode );
except
result := ridNull;
end;
end;
function TAsyncServerCnxHandler.ObjectsInArea( x, y, dx, dy : integer; Notification : TAsyncObjectsInAreaResponse ) : TAsyncRequestId;
var
Report : TObjectReport;
ErrorCode : TErrorCode;
begin
try
try
Report := fClientView.ObjectsInArea( x, y, dx, dy, ErrorCode );
except
Report.ObjectCount := 0;
ErrorCode := ERROR_Unknown;
end;
result := GetNextRequestId;
if assigned(Notification)
then Notification( result, Report, ErrorCode );
except
result := ridNull;
end;
end;
function TAsyncServerCnxHandler.ObjectAt( x, y : integer; Notification : TAsyncObjectAtResponse ) : TAsyncRequestId;
var
ObjId : TObjId;
ErrorCode : TErrorCode;
begin
try
try
ObjId := fClientView.ObjectAt( x, y, ErrorCode );
except
ObjId := 0;
ErrorCode := ERROR_Unknown;
end;
result := GetNextRequestId;
if assigned(Notification)
then Notification( result, ObjId, ErrorCode );
except
result := ridNull;
end;
end;
function TAsyncServerCnxHandler.ObjectStatusText( kind : TStatusKind; Id : TObjId; Notification : TAsyncObjectStatusTextResponse ) : TAsyncRequestId;
var
Text : TStatusText;
ErrorCode : TErrorCode;
begin
try
try
Text := fClientView.ObjectStatusText( kind, Id, ErrorCode );
except
Text := '';
ErrorCode := ERROR_Unknown;
end;
result := GetNextRequestId;
if assigned(Notification)
then Notification( result, Text, ErrorCode );
except
result := ridNull;
end;
end;
function TAsyncServerCnxHandler.ObjectConnections( Id : TObjId; Notification : TAsyncObjectConnectionsResponse ) : TAsyncRequestId;
var
Report : TCnxReport;
ErrorCode : TErrorCode;
begin
try
try
Report := fClientView.ObjectConnections( Id, ErrorCode );
except
ErrorCode := ERROR_Unknown;
end;
Report.OutputCount := 0;
Report.Outputs := nil;
Report.InputCount := 0;
Report.Inputs := nil;
result := GetNextRequestId;
if assigned(Notification)
then Notification( result, Report, ErrorCode );
except
result := ridNull;
end;
end;
function TAsyncServerCnxHandler.FocusObject( Id : TObjId; Notification : TAsyncFocusObjectResponse ) : TAsyncRequestId;
var
ErrorCode : TErrorCode;
begin
try
try
fClientView.FocusObject( Id, ErrorCode );
except
ErrorCode := ERROR_Unknown;
end;
result := GetNextRequestId;
if assigned(Notification)
then Notification( result, ErrorCode );
except
result := ridNull;
end;
end;
function TAsyncServerCnxHandler.UnfocusObject( Id : TObjId; Notification : TAsyncUnfocusObjectResponse ) : TAsyncRequestId;
var
ErrorCode : TErrorCode;
begin
try
try
fClientView.UnfocusObject( Id, ErrorCode );
except
ErrorCode := ERROR_Unknown;
end;
result := GetNextRequestId;
if assigned(Notification)
then Notification( result, ErrorCode );
except
result := ridNull;
end;
end;
function TAsyncServerCnxHandler.SwitchFocus( From : TObjId; toX, toY : integer; Notification : TAsyncSwitchFocusResponse ) : TAsyncRequestId;
var
ObjId : TObjId;
ErrorCode : TErrorCode;
begin
try
try
ObjId := fClientView.SwitchFocus( From, toX, toY, ErrorCode );
except
ObjId := 0;
ErrorCode := ERROR_Unknown;
end;
result := GetNextRequestId;
if assigned(Notification)
then Notification( result, ObjId, ErrorCode );
except
result := ridNull;
end;
end;
function TAsyncServerCnxHandler.GetCompanyList( Notification : TAsyncGetCompanyListResponse ) : TAsyncRequestId;
var
Report : TCompanyReport;
ErrorCode : TErrorCode;
begin
try
try
Report := fClientView.GetCompanyList( ErrorCode );
except
Report := nil;
ErrorCode := ERROR_Unknown;
end;
result := GetNextRequestId;
if assigned(Notification)
then Notification( result, Report, ErrorCode );
except
result := ridNull;
end;
end;
function TAsyncServerCnxHandler.NewCompany( name, cluster : string; Notification : TAsyncNewCompanyResponse ) : TAsyncRequestId;
var
Info : TCompanyInfo;
ErrorCode : TErrorCode;
begin
try
try
Info := fClientView.NewCompany( name, cluster, ErrorCode );
except
Info := nil;
ErrorCode := ERROR_Unknown;
end;
result := GetNextRequestId;
if assigned(Notification)
then Notification( result, Info, ErrorCode );
except
result := ridNull;
end;
end;
function TAsyncServerCnxHandler.NewFacility( FacilityId : string; CompanyId : integer; x, y : integer; Notification : TAsyncNewFacilityResponse ) : TAsyncRequestId;
var
ErrorCode : TErrorCode;
begin
try
try
fClientView.NewFacility( FacilityId, CompanyId, x, y, ErrorCode );
except
ErrorCode := ERROR_Unknown;
end;
result := GetNextRequestId;
if assigned(Notification)
then Notification( result, ErrorCode );
except
result := ridNull;
end;
end;
function TAsyncServerCnxHandler.GetUserList( Notification : TAsyncGetUserListResponse ) : TAsyncRequestId;
var
List : TStringList;
ErrorCode : TErrorCode;
begin
try
try
List := fClientView.GetUserList( ErrorCode );
except
List := nil;
ErrorCode := ERROR_Unknown;
end;
result := GetNextRequestId;
if assigned(Notification)
then Notification( result, List, ErrorCode );
except
result := ridNull;
end;
end;
function TAsyncServerCnxHandler.SayThis( Dest, Msg : string; Notification : TAsyncSayThisResponse ) : TAsyncRequestId;
var
ErrorCode : TErrorCode;
begin
try
try
fClientView.SayThis( Dest, Msg, ErrorCode );
except
ErrorCode := ERROR_Unknown;
end;
result := GetNextRequestId;
if assigned(Notification)
then Notification( result, ErrorCode );
except
result := ridNull;
end;
end;
function TAsyncServerCnxHandler.MsgCompositionChanged( State : TMsgCompositionState; Notification : TAsyncMsgCompChangedResponse ) : TAsyncRequestId;
var
ErrorCode : TErrorCode;
begin
try
try
fClientView.MsgCompositionChanged( State, ErrorCode );
except
ErrorCode := ERROR_Unknown;
end;
result := GetNextRequestId;
if assigned(Notification)
then Notification( result, ErrorCode );
except
result := ridNull;
end;
end;
function TAsyncServerCnxHandler.Chase( UserName : string; Notification : TAsyncChaseResponse ) : TAsyncRequestId;
var
ErrorCode : TErrorCode;
begin
try
try
fClientView.Chase( UserName, ErrorCode );
except
ErrorCode := ERROR_Unknown;
end;
result := GetNextRequestId;
if assigned(Notification)
then Notification( result, ErrorCode );
except
result := ridNull;
end;
end;
function TAsyncServerCnxHandler.StopChase( Notification : TAsyncStopChaseResponse ) : TAsyncRequestId;
var
ErrorCode : TErrorCode;
begin
try
try
fClientView.StopChase( ErrorCode );
except
ErrorCode := ERROR_Unknown;
end;
result := GetNextRequestId;
if assigned(Notification)
then Notification( result, ErrorCode );
except
result := ridNull;
end;
end;
function TAsyncServerCnxHandler.Logoff( Notification : TAsyncLogoffResponse ) : TAsyncRequestId;
var
ErrorCode : TErrorCode;
begin
try
try
fClientView.Logoff( ErrorCode );
except
ErrorCode := ERROR_Unknown;
end;
result := GetNextRequestId;
if assigned(Notification)
then Notification( result, ErrorCode );
except
result := ridNull;
end;
end;
function TAsyncServerCnxHandler.GetNextRequestId : TAsyncRequestId;
begin
inc( fLastRequestId );
result := fLastRequestId;
end;
function TAsyncServerCnxHandler.getClientView : IClientView;
begin
result := fClientView;
end;
procedure TAsyncServerCnxHandler.DisposeObjectReport( var ObjectReport : TObjectReport );
begin
fClientView.DisposeObjectReport( ObjectReport );
end;
procedure TAsyncServerCnxHandler.DisposeSegmentReport( var SegmentReport : TSegmentReport );
begin
fClientView.DisposeSegmentReport( SegmentReport );
end;
procedure TAsyncServerCnxHandler.DisposeCnxReport( var CnxReport : TCnxReport );
begin
fClientView.DisposeCnxReport( CnxReport );
end;
end.
|
unit event;
interface
uses
Windows,
Classes,
Controls,
SysUtils,
DateUtils;
type
// TODO : pointer back to the ListItem this event is the .Data of?
// yes when new events as controllers methodology is fully realized
TRemindEvent = class(TObject)
private
FNotes : string;
FDate : TDate;
FTime : TTime;
FOccur : string;
FCompleted : boolean;
public
function GetNotes():string;
procedure SetNotes( value:string );
property Notes:string read GetNotes write SetNotes;
function GetName():string;
procedure SetName( value:string );
property Name:string read GetName write SetName;
function GetDate():TDate;
procedure SetDate( value:TDate );
property Date:TDate read GetDate write SetDate;
function GetTime():TTime;
procedure SetTime( value:TTime );
property Time:TTime read GetTime write SetTime;
function GetOccur():string;
procedure SetOccur( value:string );
property Occur:string read GetOccur write SetOccur;
function GetCompleted():boolean;
procedure SetCompleted( value:boolean );
property Completed:boolean read GetCompleted write SetCompleted;
function Triggered():boolean;
procedure RollBack();
procedure NextOccur();
procedure TakeAction();
end;
implementation
uses
main;
function TRemindEvent.GetNotes():string;
begin
result := StringReplace(FNotes,#13#10,#10,[rfReplaceAll]);
end;
procedure TRemindEvent.SetNotes( value:string );
begin
FNotes := value;
end;
function TRemindEvent.GetName():string;
var
sl : TStringList;
begin
sl := TStringList.Create();
sl.Text := Notes;
if sl.Count > 0 then begin
result := sl[0];
end else begin
result := '';
end;
sl.Free;
end;
procedure TRemindEvent.SetName( value:string );
var
sl : TStringList;
begin
sl := TStringList.Create();
sl.Text := Notes;
sl[0] := value;
sl.Free;
end;
function TRemindEvent.GetDate():TDate;
begin
result := FDate;
end;
procedure TRemindEvent.SetDate( value:TDate );
begin
FDate := value;
end;
function TRemindEvent.GetTime():TTime;
begin
result := FTime;
end;
procedure TRemindEvent.SetTime( value:TTime );
begin
FTime := value;
end;
function TRemindEvent.GetOccur():string;
begin
result := FOccur;
end;
procedure TRemindEvent.SetOccur( value:string );
begin
FOccur := value;
end;
function TRemindEvent.GetCompleted():boolean;
begin
result := FCompleted;
end;
procedure TRemindEvent.SetCompleted( value:boolean );
begin
FCompleted := value;
end;
function TRemindEvent.Triggered():boolean;
begin
result := false;
if not completed then begin
// 2005-08-14 : fixed another ancient bug where event would not trigger until time met even if date had already passed
// event date has passed {1}
if CompareDate(Now(),date)=1 then begin
result := true;
end;
// event date is today {0}
if CompareDate(Now(),date)=0 then begin
// and time has passed {1} or is now {0}
if CompareTime(Now(),time) >=0 then begin
result := true;
end;
end;
end;
end;
// TODO : how are these date's updated in the ListView?
// RollBack rolls back events so they all are triggered on their most recent possible date
// this is useful when you change your system clock for say... debugging some other app,
// then you get 30 remind popups and the events have all changed, oops!
procedure TRemindEvent.RollBack();
begin
if Occur = 'once' then begin
completed := false;
end else if Occur = 'daily' then begin
// while greater than now dec
while CompareDate(Date,Now())>0 do begin
Date := IncDay(-Date);
end;
// then if is today (always on daily) and time is more than now, dec one more
if CompareDate(Date,Now())=0 then begin
if CompareTime(Date,Now())>0 then begin
Date := IncDay(-Date);
end;
end;
// Now skip one...
Date := IncDay(Date);
end else if Occur = 'weekly' then begin
// while more than date dec
while CompareDate(Date,Now())>0 do begin
Date := IncWeek(-Date);
end;
// then if is today and time is more than now, dec one more
if CompareDate(Date,Now())=0 then begin
if CompareTime(Date,Now())>0 then begin
Date := IncWeek(-Date);
end;
end;
// Now skip one...
Date := IncWeek(Date);
end else if Occur = 'monthly' then begin
// while more than date dec
while CompareDate(Date,Now())>0 do begin
Date := IncMonth(-Date);
end;
// then if is today and time is more than now, dec one more
if CompareDate(Date,Now())=0 then begin
if CompareTime(Date,Now())>0 then begin
Date := IncMonth(-Date);
end;
end;
// Now skip one...
Date := IncMonth(Date);
end else if Occur = 'every 3 months' then begin
// while more than date dec
while CompareDate(Date,Now())>0 do begin
Date := IncMonth(-Date,3);
end;
// then if is today and time is more than now, dec one more
if CompareDate(Date,Now())=0 then begin
if CompareTime(Date,Now())>0 then begin
Date := IncMonth(-Date,3);
end;
end;
// Now skip one...
Date := IncMonth(Date,3);
end else if Occur = 'every 6 months' then begin
// while more than date dec
while CompareDate(Date,Now())>0 do begin
Date := IncMonth(-Date,6);
end;
// then if is today and time is more than now, dec one more
if CompareDate(Date,Now())=0 then begin
if CompareTime(Date,Now())>0 then begin
Date := IncMonth(-Date,6);
end;
end;
// Now skip one...
Date := IncMonth(Date,6);
end else if Occur = 'yearly' then begin
// while more than date dec
while CompareDate(Date,Now())>0 do begin
Date := IncYear(-Date);
end;
// then if is today and time is more than now, dec one more
if CompareDate(Date,Now())=0 then begin
if CompareTime(Date,Now())>0 then begin
Date := IncYear(-Date);
end;
end;
// Now skip one...
Date := IncYear(Date);
end;
// TODO : should this be here? It must be currently, but I am in between methodologies
// in the future I think all of my saves will be done in here...
MainForm.SaveEvents();
end;
// TODO : how are these date's updated in the ListView?
procedure TRemindEvent.NextOccur();
begin
if Occur = 'once' then begin
completed := true;
end else if Occur = 'daily' then begin
// while less than date inc
while CompareDate(Date,Now())<0 do begin
Date := IncDay(Date);
end;
// then if is today (always on daily) and time is less than now, inc one more
if CompareDate(Date,Now())=0 then begin
if CompareTime(Date,Now())<0 then begin
Date := IncDay(Date);
end;
end;
end else if Occur = 'weekly' then begin
// while less than date inc
while CompareDate(Date,Now())<0 do begin
Date := IncWeek(Date);
end;
// then if is today and time is less than now, inc one more
if CompareDate(Date,Now())=0 then begin
if CompareTime(Date,Now())<0 then begin
Date := IncWeek(Date);
end;
end;
end else if Occur = 'monthly' then begin
// while less than date inc
while CompareDate(Date,Now())<0 do begin
Date := IncMonth(Date);
end;
// then if is today and time is less than now, inc one more
if CompareDate(Date,Now())=0 then begin
if CompareTime(Date,Now())<0 then begin
Date := IncMonth(Date);
end;
end;
end else if Occur = 'every 3 months' then begin
// while less than date inc
while CompareDate(Date,Now())<0 do begin
Date := IncMonth(Date,3);
end;
// then if is today and time is less than now, inc one more
if CompareDate(Date,Now())=0 then begin
if CompareTime(Date,Now())<0 then begin
Date := IncMonth(Date,3);
end;
end;
end else if Occur = 'every 6 months' then begin
// while less than date inc
while CompareDate(Date,Now())<0 do begin
Date := IncMonth(Date,6);
end;
// then if is today and time is less than now, inc one more
if CompareDate(Date,Now())=0 then begin
if CompareTime(Date,Now())<0 then begin
Date := IncMonth(Date,6);
end;
end;
end else if Occur = 'yearly' then begin
// while less than date inc
while CompareDate(Date,Now())<0 do begin
Date := IncYear(Date);
end;
// then if is today and time is less than now, inc one more
if CompareDate(Date,Now())=0 then begin
if CompareTime(Date,Now())<0 then begin
Date := IncYear(Date);
end;
end;
end;
// TODO : should this be here? It must be currently, but I am in between methodologies
// in the future I think all of my saves will be done in here...
MainForm.SaveEvents();
end;
procedure TRemindEvent.TakeAction();
begin
if self = nil then exit; // takes care of snoozed events that were later deleted
// TODO : other actions instead of just this popup
MainForm.EventPopup(self);
end;
end.
|
unit d_SrchByJurOperation;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, d_SrchByAction, StdCtrls, Mask, vtCombo, vtDateEdit, Buttons,
ExtCtrls, OvcBase, vtLister,
DT_Types, afwControl, afwInputControl, afwControlPrim, afwBaseControl;
type
TSrchByJurOperationDlg = class(TSrchByActionDlg)
lstJurOperation: TvtDStringLister;
lblJurOperation: TLabel;
cbUser: TComboBox;
cbxJurOp: TCheckBox;
cbxSysOp: TCheckBox;
procedure cbxJurOpClick(Sender: TObject);
procedure cbxSysOpClick(Sender: TObject);
procedure FillOpList;
private
{ Private declarations }
public
constructor Create(aOwner : TComponent); reintroduce;
{ Public declarations }
function GetOperationSet : TLogActionSet;
end;
implementation
{$R *.dfm}
uses
l3Base,
l3String,
daDataProvider,
DT_Const,
DictsSup;
constructor TSrchByJurOperationDlg.Create(aOwner : TComponent);
begin
//lIsFull := l3System.Keyboard.Key[VK_SHIFT].Down and
// l3System.Keyboard.Key[VK_CONTROL].Down;
Inherited Create(aOwner, 'Поиск по журналам');
GlobalDataProvider.UserManager.GetFiltredUserList(cbUser.Items);
cbUser.Items.Insert(0, '[ВСЕ]');
cbUser.ItemIndex := 0;
FillOpList;
end;
function TSrchByJurOperationDlg.GetOperationSet : TLogActionSet;
var
I : Integer;
begin
Result := [];
with lstJurOperation.Items do
for I := 0 to Pred(Count) do
if lstJurOperation.Selected[I] then
Result := Result + [PLogActionType(Data[I])^];
end;
procedure TSrchByJurOperationDlg.FillOpList;
var
LASet : TLogActionSet;
lAction : TLogActionType;
begin
if cbxJurOp.Checked then
LASet := cJurLogActions
else
LASet := [];
if cbxSysOp.Checked then
LASet := LASet + cOrdLogActions;
with lstJurOperation.Items do
begin
Clear;
DataSize := SizeOf(lAction);
NeedAllocStr := True;
NeedDisposeStr := True;
for lAction := Succ(Low(TLogActionType)) to High(TLogActionType) do
if (lAction in LASet) then
AddStr(GetLogJrnlName(lAction), @lAction);
end;
end;
procedure TSrchByJurOperationDlg.cbxJurOpClick(Sender: TObject);
begin
FillOpList;
end;
procedure TSrchByJurOperationDlg.cbxSysOpClick(Sender: TObject);
begin
FillOpList;
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: StText.pas 4.04 *}
{*********************************************************}
{* SysTools: Routines for manipulating Delphi Text files *}
{*********************************************************}
{$I StDefine.inc}
unit StText;
interface
uses
Windows,
SysUtils, STConst, StBase, StSystem;
function TextSeek(var F : TextFile; Target : Integer) : Boolean;
{-Seek to the specified position in a text file opened for input}
function TextFileSize(var F : TextFile) : Integer;
{-Return the size of a text file}
function TextPos(var F : TextFile) : Integer;
{-Return the current position of the logical file pointer (that is,
the position of the physical file pointer, adjusted to account for
buffering)}
function TextFlush(var F : TextFile) : Boolean;
{-Flush the buffer(s) for a text file}
implementation
function TextSeek(var F : TextFile; Target : Integer) : Boolean;
{-Do a Seek for a text file opened for input. Returns False in case of I/O
error.}
var
Pos : Integer;
begin
with TTextRec(F) do begin
{assume failure}
Result := False;
{check for file opened for input}
if Mode <> fmInput then Exit;
Pos := FileSeek(Handle, 0, FILE_CURRENT);
if Pos = -1 then Exit;
Dec(Pos, BufEnd);
{see if the Target is within the buffer}
Pos := Target-Pos;
if (Pos >= 0) and (Pos < Integer(BufEnd)) then
{it is--just move the buffer pointer}
BufPos := Pos
else begin
if FileSeek(Handle, Target, FILE_BEGIN) = -1 then Exit;
{tell Delphi its buffer is empty}
BufEnd := 0;
BufPos := 0;
end;
end;
{if we get to here we succeeded}
Result := True;
end;
function TextFileSize(var F : TextFile) : Integer;
{-Return the size of text file F. Returns -1 in case of I/O error.}
var
Old : Integer;
Res : Integer;
begin
Result := -1;
with TTextRec(F) do begin
{check for open file}
if Mode = fmClosed then Exit;
{get/save current pos of the file pointer}
Old := FileSeek(Handle, 0, FILE_CURRENT);
if Old = -1 then Exit;
{have OS move to end-of-file}
Res := FileSeek(Handle, 0, FILE_END);
if Res = -1 then Exit;
{reset the old position of the file pointer}
if FileSeek(Handle, Old, FILE_BEGIN) = - 1 then Exit;
end;
Result := Res;
end;
function TextPos(var F : TextFile) : Integer;
{-Return the current position of the logical file pointer (that is,
the position of the physical file pointer, adjusted to account for
buffering). Returns -1 in case of I/O error.}
var
Position : Integer;
begin
Result := -1;
with TTextRec(F) do begin
{check for open file}
if Mode = fmClosed then Exit;
Position := FileSeek(Handle, 0, FILE_CURRENT);
if Position = -1 then Exit;
end;
with TTextRec(F) do
if Mode = fmOutput then {writing}
Inc(Position, BufPos)
else if BufEnd <> 0 then {reading}
Dec(Position, BufEnd-BufPos);
{return the calculated position}
Result := Position;
end;
function TextFlush(var F : TextFile) : Boolean;
{-Flush the buffer(s) for a text file. Returns False in case of I/O error.}
var
Position : Integer;
Code : Integer;
begin
Result := False;
with TTextRec(F) do begin
{check for open file}
if Mode = fmClosed then Exit;
{see if file is opened for reading or writing}
if Mode = fmInput then begin
{get current position of the logical file pointer}
Position := TextPos(F);
{exit in case of I/O error}
if Position = -1 then Exit;
if FileSeek(Handle, Position, FILE_BEGIN) = - 1 then Exit;
end
else begin
{write the current contents of the buffer, if any}
if BufPos <> 0 then begin
Code := FileWrite(Handle, BufPtr^, BufPos);
if Code = -1 {<> 0} then Exit;
end;
{flush OS's buffers}
if not FlushOsBuffers(Handle) then Exit;
end;
{tell Delphi its buffer is empty}
BufEnd := 0;
BufPos := 0;
end;
{if we get to here we succeeded}
Result := True;
end;
end.
|
// ---------------------------------------------------------------------------------------
//
// 1. In iTunes connect ensure that you have a unique App ID and when we create the application update with the bundle ID and code signing in Xcode with corresponding provisioning profile.
// 2. Create a new application and update application information. You can know more about this in apple's Add new apps documentation.
// 3. Add a new product for in-app purchase in Manage In-App Purchase of your application's page.
// 4. Ensure you setup the bank details for your application. This needs to be setup for In-App purchase to work. Also create a test user account using Manage Users option in iTunes connect page of your app.
// 5. Set this project Bundle ID with your itunesconnect app Bundle ID
// ---------------------------------------------------------------------------------------
unit uMain;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, IniFiles,
DPF.iOS.StoreKit,
DPF.iOS.Common,
DPF.iOS.BaseControl,
DPF.iOS.UIButton,
DPF.iOS.UILabel,
DPF.iOS.UIView,
DPF.iOS.UITextView,
DPF.iOS.UIActivityIndicatorView,
DPF.iOS.UITableViewItems,
DPF.iOS.UITableView,
DPF.iOS.UIToolbar,
DPF.iOS.SlideDialog;
type
TFInAppPurchase = class( TForm )
DPFUIView1: TDPFUIView;
DPFInAppPurchase1: TDPFInAppPurchase;
DPFActivityIndicatorView1: TDPFActivityIndicatorView;
DPFUITableView1: TDPFUITableView;
DPFToolbar1: TDPFToolbar;
DPFButton1: TDPFButton;
DPFSlideDialog1: TDPFSlideDialog;
DPFLabel1: TDPFLabel;
DPFButton2: TDPFButton;
procedure DPFButton1Click( Sender: TObject );
procedure DPFInAppPurchase1ProductsRequest( sender: TObject; Products: array of TProductInfo; InvalidProducts: array of string );
procedure DPFInAppPurchase1ProductsRequestFinished( sender: TObject );
procedure DPFInAppPurchase1ProductsRequestError( sender: TObject; Error: string );
procedure FormShow( Sender: TObject );
procedure DPFUITableView1GetRowHeight( Sender: TObject; Section, RowNo: Integer; var RowHeight: Single );
procedure DPFUITableView1ApplyFrameData( Sender: TObject; Section, RowNo: Integer; TableItem: TTableItem; var Frame: TFrame; var Handled: Boolean );
procedure DPFButton2Click( Sender: TObject );
private
{ Private declarations }
protected
procedure PaintRects( const UpdateRects: array of TRectF ); override;
public
{ Public declarations }
end;
var
FInAppPurchase: TFInAppPurchase;
implementation
uses uRowFrame;
{$R *.fmx}
procedure TFInAppPurchase.DPFButton1Click( Sender: TObject );
begin
DPFActivityIndicatorView1.StartAnimating;
// com.dpfaragir.dpfinapptest
DPFInAppPurchase1.FetchAvailableProducts( ['com.dpfaragir.dpfinapptest'] );
end;
procedure TFInAppPurchase.DPFButton2Click( Sender: TObject );
begin
DPFInAppPurchase1.ShowProductInAppStore( 733449578, nil );
end;
procedure TFInAppPurchase.DPFInAppPurchase1ProductsRequest( sender: TObject; Products: array of TProductInfo; InvalidProducts: array of string );
var
i : Integer;
TE: TTableItem;
begin
DPFActivityIndicatorView1.StopAnimating;
DPFUITableView1.ClearAll( );
if Length( Products ) = 0 then
begin
DPFSlideDialog1.Show( 'No product available!', 200, 80 );
exit;
end
else
DPFUITableView1.Sections.Add;
for I := 0 to Length( Products ) - 1 do
begin
TE := DPFUITableView1.Sections[0].TableItems.Add;
TE.Style := TTableViewCellStyle.tvcsSubtitle;
TE.ItemText.Text := Products[i].localizedTitle;
TE.ItemDescription.Text := Products[i].localizedDescription;
TE.TagFloat := Products[i].price;
TE.TagStr := Products[i].productIdentifier;
end;
DPFUITableView1.RefreshNeeded;
end;
procedure TFInAppPurchase.DPFInAppPurchase1ProductsRequestError( sender: TObject; Error: string );
begin
DPFActivityIndicatorView1.StopAnimating;
DPFSlideDialog1.Show( 'Request Error!' + #10#13 + Error, 200, 80 );
end;
procedure TFInAppPurchase.DPFInAppPurchase1ProductsRequestFinished( sender: TObject );
begin
DPFActivityIndicatorView1.StopAnimating;
end;
procedure TFInAppPurchase.DPFUITableView1ApplyFrameData( Sender: TObject; Section, RowNo: Integer; TableItem: TTableItem; var Frame: TFrame; var Handled: Boolean );
begin
if Frame = nil then
Frame := TFrameRow.Create( nil );
TFrameRow( Frame ).SectionNo := Section;
TFrameRow( Frame ).RowNo := RowNo;
TFrameRow( Frame ).DPFLabelTitle.Text := DPFUITableView1.Row[Section, RowNo].ItemText.Text;
TFrameRow( Frame ).DPFLabelDesc.Text := DPFUITableView1.Row[Section, RowNo].ItemDescription.Text;
TFrameRow( Frame ).DPFLabelPrice.Text := DPFUITableView1.Row[Section, RowNo].TagFloat.ToString;
end;
procedure TFInAppPurchase.DPFUITableView1GetRowHeight( Sender: TObject; Section, RowNo: Integer; var RowHeight: Single );
begin
RowHeight := 80;
end;
procedure TFInAppPurchase.FormShow( Sender: TObject );
var
n : TIniFile;
v : integer;
DPath: string;
begin
DPath := GetDocumentsFolder;
ForceDirectories( DPath );
n := TIniFile.Create( DPath + 'config.ini' );
v := n.ReadInteger( 'Rate', 'counter', 0 );
Caption := v.ToString( );
n.WriteInteger( 'Rate', 'counter', 1231 );
n.Free;
DPFActivityIndicatorView1.Visible := false;
end;
procedure TFInAppPurchase.PaintRects( const UpdateRects: array of TRectF );
begin
{ }
end;
end.
|
unit UnitUpdate;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
wininet, IdHTTP, IdFtp, IdComponent, Math,
StdCtrls, ComCtrls;
type
tidWorkType = (stFTP, stHTTP);
tWorkThread = class(TThread)
private
fHost, fDir, fURL, fURLini, fFile, fFileini, fLocalPath, fUser,
fPasswd: String;
fFileSize: integer;
aFtp: TIdFTP;
aIdHTTP: TIdHTTP;
fidWorkType: tidWorkType;
fsizes: string;
destructor Destroy;
function GetUrlSize(const URL: string): integer;
protected
procedure Execute; override;
procedure idWork(Sender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
procedure idWorkBegin(Sender: TObject; AWorkMode: TWorkMode;
AWorkCountMax: Int64);
public
constructor Create(idWorkType: tidWorkType; CreateSuspended: boolean);
reintroduce;
end;
TUpdateApp = class
private
fURL: string;
fFileName: string;
fFileSize: integer;
fUrlList: TStrings;
fEnabled: boolean;
function GetURL: String;
procedure SetURL(const Value: String);
function GetEnabled: boolean;
function GetFileName: String;
procedure SetFileName(const Value: String);
procedure SetEnabled(const Value: boolean);
constructor Create;
destructor Destroy; override;
published
function CheckUpdate: boolean;
procedure UpdateApp;
function DownloadUrl: string;
function UploadFile: boolean;
property URL: String read GetURL write SetURL;
property FileName: String read GetFileName write SetFileName;
property Enabled: boolean read GetEnabled write SetEnabled;
end;
implementation
{ WorkThread }
uses settings, MainUnit;
function tWorkThread.GetUrlSize(const URL: string): integer;
// результат в байтах
var
IdHTTP: TIdHTTP;
begin
Result := -1; // Ставим первоначальное значение -1, потом поймёте зачем
IdHTTP := TIdHTTP.Create(nil);
try
aIdHTTP.Head(URL);
// Мы получаем только заголовок нашего файла, где хранится размер файла, код запроса и т.п.
if aIdHTTP.ResponseCode = 200 then
// Если файл существует, то... (200 это успешный код: HTTP OK)
Result := aIdHTTP.Response.ContentLength;
// В результат пихаем наш размер файла в байтах.
except
IdHTTP.Free;
end;
end;
procedure tWorkThread.idWork(Sender: TObject; AWorkMode: TWorkMode;
AWorkCount: Int64);
begin
FormSettings.ProgressBar1.Position := AWorkCount;
FormSettings.LbSize.Caption := floattostr(RoundTo(AWorkCount / (1024 * 1024),
-2)) + ' MB.';
end;
procedure tWorkThread.idWorkBegin(Sender: TObject; AWorkMode: TWorkMode;
AWorkCountMax: Int64);
begin
FormSettings.ProgressBar1.Max := fFileSize;
end;
constructor tWorkThread.Create(idWorkType: tidWorkType;
CreateSuspended: boolean);
begin
fHost := 'http://avtoefi.ru/'; // 'ftp.servage.net';
fDir := '/';
fFile := ExtractFileName(Application.ExeName);
fURL := fHost + fFile;
fURLini := fHost + 'version.ini';
fUser := 'avtoefi';
fPasswd := 'RuR7nSTh7IZo';
fLocalPath := Application.ExeName + '_';
fFileini := ExtractFilePath(Application.ExeName) + 'version.ini';
fidWorkType := idWorkType;
case fidWorkType of
stFTP:
begin
aFtp := TIdFTP.Create(nil);
aFtp.OnWork := idWork;
aFtp.OnWorkBegin := idWorkBegin;
end;
stHTTP:
begin
aIdHTTP := TIdHTTP.Create(nil);
aIdHTTP.OnWork := idWork;
aIdHTTP.OnWorkBegin := idWorkBegin;
end;
end;
inherited Create(CreateSuspended);
end;
destructor tWorkThread.Destroy;
begin
case fidWorkType of
stFTP:
aFtp.Free;
stHTTP:
aIdHTTP.Free;
end;
inherited Destroy;
end;
procedure tWorkThread.Execute;
const
BufferSize = 1024;
var
stream: TMemoryStream;
FName: String;
begin
stream := TMemoryStream.Create;
{ Place thread code here }
if (aFtp = nil) and (aIdHTTP = nil) then
Exit;
case fidWorkType of
stFTP:
begin
try
aFtp.Connect;
aFtp.ChangeDir(fDir);
fFileSize := aFtp.Size(fFile);
aFtp.Get(fFile, fLocalPath);
aFtp.Disconnect;
except
// this will always be 404 for this domain (test from outside the IDE)
end;
end;
stHTTP:
begin
// URL := 'http://liga-updates.ua.tc/GDI+.zip';
try
// check ini version
FormMain.Log('Check ini from server...', 1);
try
aIdHTTP.Head(fURLini);
except
on E: Exception do
Exit;
end;
// Мы получаем только заголовок нашего файла, где хранится размер файла, код запроса и т.п.
if aIdHTTP.ResponseCode = 200 then
begin
FormMain.Log('Check ini from server OK! Download ini...', 1);
aIdHTTP.Get(fURLini, stream); // Начинаем скачивание
stream.SaveToFile(fFileini); // Сохраняем
// ---------
// aIdHTTP.URL.Host := fHost;
// aIdHTTP.URL.Path:=fURL;
// aIdHTTP.MultiThreaded := True;
FormMain.Log('Check app from server ...', 1);
try
aIdHTTP.Head(fURL);
except
on E: Exception do
Exit;
end;
// Мы получаем только заголовок нашего файла, где хранится размер файла, код запроса и т.п.
if aIdHTTP.ResponseCode = 200
then { TODO : Добавить чтение версии с ini и проверка с реальным }
begin
FormMain.Log('Check app from server OK! Download app...', 1);
// Если файл существует, то... (200 это успешный код: HTTP OK)
fFileSize := aIdHTTP.Response.ContentLength;
// В результат пихаем наш размер файла в байтах.
fsizes := floattostr(RoundTo(fFileSize / (1024 * 1024), -2));
// Переводим в МБ
FormMain.Log('Check app size... ' + inttostr(fFileSize), 1);
try
aIdHTTP.Get(fURL, stream); // Начинаем скачивание
except
on E: Exception do
Exit;
end;
stream.SaveToFile(fLocalPath); // Сохраняем
FormSettings.UpdateStart := False;
// замена старого файла программы на новый - скачанный, старый бэкап удалить
if FileExists(Application.ExeName + '_') then
begin
if FileExists(Application.ExeName + '$bak') then
DeleteFile(Application.ExeName + '$bak');
RenameFile(Application.ExeName, Application.ExeName + '$bak');
RenameFile(Application.ExeName + '_', Application.ExeName);
FormMain.Log('Update app from server OK!', 1);
end;
end;
end;
except
// FreeAndNil(aIdHTTP); //Завершаем HTTP
FreeAndNil(stream); // Завершаем Stream
end
end;
end;
end;
{
//Обновление программы
idftp1.Get('/Update/'+UN,ND+NND+UN);
Memo1.Lines.LoadFromFile(ND+NND+UN);
UVersion:=copy(Memo1.Lines[0],pos(':',Memo1.Lines[0])+1,length(Memo1.Lines[0]));
if not (UVersion=Ver) then begin
Timer1.Interval := 14400000;
UFName:=copy(Memo1.Lines[1],pos(':',Memo1.Lines[1])+1,length(Memo1.Lines[1]));
DeleteFile(ND+NND+'\'+UFName+'.exe');
showmessage(ND+NND+'\'+UFName+'.exe');
idftp1.Get('/Update/'+UFName+'.exe', ND+NND+'\'+UFName+'.exe');
WinExec(Pchar(ND+NND+'\'+UFName+'.exe'), SW_SHOWNORMAL);
idFTP1.Disconnect;
Close;
end;
}
function TUpdateApp.CheckUpdate: boolean;
begin
end;
constructor TUpdateApp.Create;
begin
inherited Create;
end;
destructor TUpdateApp.Destroy;
begin
inherited Destroy;
// procedure Free;
end;
function TUpdateApp.DownloadUrl: string;
var
Buffer: TFileStream;
HttpClient: TIdHTTP;
begin
Buffer := TFileStream.Create(fFileName, fmCreate or fmShareDenyWrite);
try
HttpClient := TIdHTTP.Create(nil);
try
HttpClient.Get(fURL, Buffer); // wait until it is done
finally
HttpClient.Free;
end;
finally
Buffer.Free;
end;
end;
function TUpdateApp.GetEnabled: boolean;
begin
Result := fEnabled;
end;
function TUpdateApp.GetFileName: String;
begin
Result := fFileName;
end;
function TUpdateApp.GetURL: String;
begin
Result := fURL;
end;
procedure TUpdateApp.SetEnabled(const Value: boolean);
begin
fEnabled := Value;
end;
procedure TUpdateApp.SetFileName(const Value: String);
begin
fFileName := Value;
end;
procedure TUpdateApp.SetURL(const Value: String);
begin
fURL := Value;
end;
procedure TUpdateApp.UpdateApp;
begin
end;
function TUpdateApp.UploadFile: boolean;
begin
end;
{
type
TNoPresizeFileStream = class(TFileStream)
procedure
procedure SetSize(const NewSize: Int64); override;
end;
procedure TNoPresizeFileStream.SetSize(const NewSize: Int64);
begin
end;
.
type
TSomeClass = class(TSomething)
...
TotalBytes: In64;
LastWorkCount: Int64;
LastTicks: LongWord;
procedure Download;
procedure HttpWorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64);
procedure HttpWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
procedure HttpWorkEnd(ASender: TObject; AWorkMode: TWorkMode);
...
end;
procedure TSomeClass.Download;
var
Buffer: TNoPresizeFileStream;
HttpClient: TIdHttp;
begin
Buffer := TNoPresizeFileStream.Create('somefile.exe', fmCreate or fmShareDenyWrite);
try
HttpClient := TIdHttp.Create(nil);
try
HttpClient.OnWorkBegin := HttpWorkBegin;
HttpClient.OnWork := HttpWork;
HttpClient.OnWorkEnd := HttpWorkEnd;
HttpClient.Get('http://somewhere.com/somefile.exe', Buffer); // wait until it is done
finally
HttpClient.Free;
end;
finally
Buffer.Free;
end;
end;
procedure TSomeClass.HttpWorkBegin(ASender: TObject; AWorkMode: TWorkMode; AWorkCountMax: Int64);
begin
if AWorkMode <> wmRead then Exit;
// initialize the status UI as needed...
//
// If TIdHTTP is running in the main thread, update your UI
// components directly as needed and then call the Form's
// Update() method to perform a repaint, or Application.ProcessMessages()
// to process other UI operations, like button presses (for
// cancelling the download, for instance).
//
// If TIdHTTP is running in a worker thread, use the TIdNotify
// or TIdSync class to update the UI components as needed, and
// let the OS dispatch repaints and other messages normally...
TotalBytes := AWorkCountMax;
LastWorkCount := 0;
LastTicks := Ticks;
end;
procedure TSomeClass.HttpWork(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
var
PercentDone: Integer;
ElapsedMS: LongWord;
BytesTransferred: Int64;
BytesPerSec: Int64;
begin
if AWorkMode <> wmRead then Exit;
ElapsedMS := GetTickDiff(LastTicks, Ticks);
if ElapsedMS = 0 then ElapsedMS := 1; // avoid EDivByZero error
if TotalBytes > 0 then
PercentDone := (Double(AWorkCount) / TotalBytes) * 100.0;
else
PercentDone := 0.0;
BytesTransferred := AWorkCount - LastWorkCount;
// using just BytesTransferred and ElapsedMS, you can calculate
// all kinds of speed stats - b/kb/mb/gm per sec/min/hr/day ...
BytesPerSec := (Double(BytesTransferred) * 1000) / ElapsedMS;
// update the status UI as needed...
LastWorkCount := AWorkCount;
LastTicks := Ticks;
end;
procedure TSomeClass.HttpWorkEnd(ASender: TObject; AWorkMode: TWorkMode);
begin
if AWorkMode <> wmRead then Exit;
// finalize the status UI as needed...
end;
}
end.
|
unit GX_CleanDirectories;
{$I GX_CondDefine.inc}
{$WARN UNIT_PLATFORM OFF}
{$WARN SYMBOL_PLATFORM OFF}
// TODO 3 -cFeature -oAnyone: Add save/restore of recursive directory checkboxes and custom-added directories?
interface
uses
Classes, Controls, Forms, StdCtrls, CheckLst, ExtCtrls, ActnList, Menus,
GX_Experts, GX_ConfigurationInfo, GX_BaseForm;
type
TCleanExpert = class;
TfmCleanDirectories = class(TfmBaseForm)
ActionList: TActionList;
actDirsCheckAll: TAction;
actDirsUncheckAll: TAction;
actExtsCheckAll: TAction;
actExtsUncheckAll: TAction;
pmuDirs: TPopupMenu;
mitDirsCheckAll: TMenuItem;
mitDirsUncheckAll: TMenuItem;
pmuExts: TPopupMenu;
mitExtsCheckAll: TMenuItem;
mitExtsUncheckAll: TMenuItem;
actDirsInvert: TAction;
actExtsInvert: TAction;
mitDirsInvertChecked: TMenuItem;
mitExtsInvertChecked: TMenuItem;
pnlButtons: TPanel;
pnlButtonsRight: TPanel;
pnlDirs: TPanel;
pnlDirectories: TPanel;
gbxDirectories: TGroupBox;
btnHelp: TButton;
btnClean: TButton;
btnCancel: TButton;
chkReportErrors: TCheckBox;
pnlBottom: TPanel;
gbxExtensions: TGroupBox;
pnlExtButtons: TPanel;
btnAddExt: TButton;
btnRemoveExt: TButton;
pnlExtensions: TPanel;
clbExtensions: TCheckListBox;
pnlMessage: TPanel;
lCleaning: TLabel;
laStatus: TLabel;
pnlDirList: TPanel;
pnlDirButtons: TPanel;
btnAdd: TButton;
btnRemove: TButton;
pnlDirMessage: TPanel;
lblDirMessage: TLabel;
clbDirs: TCheckListBox;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure btnRemoveClick(Sender: TObject);
procedure btnCleanClick(Sender: TObject);
procedure btnHelpClick(Sender: TObject);
procedure clbDirsClick(Sender: TObject);
procedure btnAddExtClick(Sender: TObject);
procedure btnRemoveExtClick(Sender: TObject);
procedure clbDirsKeyPress(Sender: TObject; var Key: Char);
procedure clbExtensionsClick(Sender: TObject);
procedure clbExtensionsKeyPress(Sender: TObject; var Key: Char);
procedure FormResize(Sender: TObject);
procedure CheckActionExecute(Sender: TObject);
private
CleanExpert: TCleanExpert;
CleanExtList: TStringList;
FTotalBytesCleaned: Integer;
FTotalFilesCleaned: Integer;
procedure FillProjectDirectoriesList;
procedure AddHorizontalScrollbar;
procedure PerformCleaning;
procedure CleanDirectory(const Directory: string; const Recursing: Boolean);
procedure DeleteFoundFile(const FileName: string);
procedure SaveSettings;
procedure LoadSettings;
procedure UpdateCleanExtList;
function ConfigurationKey: string;
procedure clbDirsOnFilesDropped(_Sender: TObject; _Files: TStrings);
procedure clbExtensionsOnFilesDropped(_Sender: TObject; _Files: TStrings);
public
constructor CreateParametrized(OwningExpert: TCleanExpert);
end;
TCleanExpert = class(TGX_Expert)
private
FReportErrors: Boolean;
FExtensionList: TStrings;
FCleanList: TStrings;
FIncludeBinaryDirs: Boolean;
protected
procedure InternalLoadSettings(Settings: TExpertSettings); override;
procedure InternalSaveSettings(Settings: TExpertSettings); override;
public
constructor Create; override;
destructor Destroy; override;
function GetActionCaption: string; override;
class function GetName: string; override;
procedure Execute(Sender: TObject); override;
function HasConfigOptions: Boolean; override;
procedure Configure; override;
property ExtensionList: TStrings read FExtensionList;
property CleanList: TStrings read FCleanList;
end;
implementation
{$R *.dfm}
uses
{$IFOPT D+} GX_DbugIntf, {$ENDIF}
Variants, SysUtils, FileCtrl, Dialogs, Math,
ToolsAPI, GX_GxUtils, GX_GenericUtils, GX_OtaUtils, GX_dzVclUtils;
resourcestring
SCouldNotDelete = 'Could not delete %s' + sLineBreak +
sLineBreak +
'Continue showing errors?';
{ TfmCleanDirectories }
procedure TfmCleanDirectories.btnAddClick(Sender: TObject);
var
Temp: string;
begin
Temp := '';
if GetDirectory(Temp) then
begin
Temp := AddSlash(Temp);
clbDirs.Items.Add(Temp);
AddHorizontalScrollbar;
end;
end;
procedure TfmCleanDirectories.btnAddExtClick(Sender: TObject);
resourcestring
SAddNewExtension = 'Add file extension';
SAddNewText = 'Enter the file extension to be cleaned:';
SStarNotAllowed = '.* is not an allowable clean extension';
var
NewExt: string;
Idx: Integer;
begin
if InputQuery(SAddNewExtension, SAddNewText, NewExt) then
begin
if NewExt[1] = '*' then
Delete(NewExt, 1, 1);
if not (NewExt[1] = '.') then
NewExt := '.' + NewExt;
NewExt := Trim(NewExt);
if NewExt = '.*' then
raise Exception.Create(SStarNotAllowed);
Idx := clbExtensions.Items.Add(NewExt);
clbExtensions.Checked[Idx] := True;
end;
end;
procedure TfmCleanDirectories.btnCleanClick(Sender: TObject);
begin
btnClean.Enabled := False;
btnCancel.Enabled := False;
try
PerformCleaning;
finally
btnClean.Enabled := True;
btnCancel.Enabled := True;
CleanExpert.SaveSettings;
SaveSettings;
ModalResult := mrOk;
end;
end;
procedure TfmCleanDirectories.btnHelpClick(Sender: TObject);
begin
GxContextHelp(Self, 14);
end;
procedure TfmCleanDirectories.btnRemoveClick(Sender: TObject);
var
i: Integer;
OldIndex: Integer;
begin
i := 0;
OldIndex := clbDirs.ItemIndex;
// MultiSelect isn't published/implemented in Delphi 5
while i <= clbDirs.Items.Count - 1 do
begin
if clbDirs.Selected[i] then
clbDirs.Items.Delete(i)
else
Inc(i);
end;
if (OldIndex > -1) and (clbDirs.Items.Count > 0) then
clbDirs.ItemIndex := Min(OldIndex, clbDirs.Items.Count - 1);
btnRemove.Enabled := (clbDirs.ItemIndex > -1) and (clbDirs.Items.Count > 0);
end;
procedure TfmCleanDirectories.btnRemoveExtClick(Sender: TObject);
var
i: Integer;
begin
i := clbExtensions.ItemIndex;
if i < 0 then
Exit;
clbExtensions.Checked[i] := False;
clbExtensions.Items.Delete(i);
btnRemoveExt.Enabled := (clbExtensions.ItemIndex > -1) and (clbExtensions.Items.Count > 0);
end;
procedure TfmCleanDirectories.clbDirsClick(Sender: TObject);
begin
btnRemove.Enabled := (clbDirs.ItemIndex > -1);
end;
procedure TfmCleanDirectories.clbDirsKeyPress(Sender: TObject; var Key: Char);
begin
btnRemove.Enabled := (clbDirs.ItemIndex > -1);
end;
procedure TfmCleanDirectories.clbExtensionsClick(Sender: TObject);
begin
btnRemoveExt.Enabled := (clbExtensions.ItemIndex > -1);
end;
procedure TfmCleanDirectories.clbExtensionsKeyPress(Sender: TObject; var Key: Char);
begin
btnRemoveExt.Enabled := (clbExtensions.ItemIndex > -1);
end;
procedure TfmCleanDirectories.CleanDirectory(const Directory: string; const Recursing: Boolean);
var
SearchRec: TSearchRec;
SearchAttr: Integer;
FindResult: Integer;
i: Integer;
begin
// We explicitly do not search for r/o files since we cannot
// delete them anyway; alternatively do search r/o files and have
// an error reported?
SearchAttr := faHidden or faSysFile or faArchive;
if Recursing then
SearchAttr := SearchAttr or faDirectory;
FindResult := FindFirst(Directory + AllFilesWildCard, SearchAttr, SearchRec);
try
laStatus.Caption := MinimizeName(Directory, laStatus.Canvas, laStatus.Width);
laStatus.Repaint;
while FindResult = 0 do
begin
// Do not localize strings in the following expression.
// Note: this test includes the "recursing" test as we
// will only find faDirectory if we are recursing.
if (SearchRec.Name <> '.') and (SearchRec.Name <> '..') then
begin
if ((SearchRec.Attr and faDirectory) <> 0) then
begin
// Recurse into sub-directories.
SearchRec.Name := AddSlash(SearchRec.Name);
CleanDirectory(Directory + SearchRec.Name, Recursing);
end
else
begin
// Delete files with matching extension(s).
for i := 0 to CleanExtList.Count - 1 do
begin
//if SameFileName(FoundFileExt, CleanExtList.Strings[i]) then
if WildcardCompare('*'+CleanExtList.Strings[i], SearchRec.Name, True) then
begin
DeleteFoundFile(Directory + SearchRec.Name);
Break;
end;
end;
end;
end;
FindResult := FindNext(SearchRec);
end;
finally
FindClose(SearchRec);
end;
end;
constructor TfmCleanDirectories.CreateParametrized(OwningExpert: TCleanExpert);
begin
CleanExpert := OwningExpert;
inherited Create(nil);
TWinControl_ActivateDropFiles(clbDirs, clbDirsOnFilesDropped);
TWinControl_ActivateDropFiles(clbExtensions, clbExtensionsOnFilesDropped);
end;
procedure TfmCleanDirectories.clbDirsOnFilesDropped(_Sender: TObject; _Files: TStrings);
var
i: Integer;
fn: string;
LastIdxAdded: Integer;
begin
for i := 0 to _Files.Count - 1 do begin
fn := _Files[i];
if SysUtils.DirectoryExists(fn) then
LastIdxAdded := clbDirs.Items.Add(AddSlash(fn))
else
LastIdxAdded := clbDirs.Items.Add(AddSlash(ExtractFileDir(fn)));
clbDirs.ItemIndex := LastIdxAdded;
end;
AddHorizontalScrollbar;
end;
procedure TfmCleanDirectories.clbExtensionsOnFilesDropped(_Sender: TObject; _Files: TStrings);
var
i: Integer;
fn: string;
LastIdxAdded: Integer;
Ext: string;
begin
LastIdxAdded := clbDirs.ItemIndex;
for i := 0 to _Files.Count - 1 do begin
fn := _Files[i];
if not SysUtils.DirectoryExists(fn) then begin
Ext := ExtractFileExt(fn);
LastIdxAdded := clbExtensions.Items.Add('*' + Ext);
end;
clbExtensions.ItemIndex := LastIdxAdded;
end;
end;
procedure TfmCleanDirectories.DeleteFoundFile(const FileName: string);
{.$DEFINE SimulateDeleting}
{$IFNDEF SimulateDeleting}
var
TempFileSize: Integer;
{$ENDIF SimulateDeleting}
begin
{$IFOPT D+}SendDebug('Deleting file: ' + FileName);{$ENDIF}
{$IFNDEF SimulateDeleting}
TempFileSize := GetFileSize(FileName);
if DeleteFile(FileName) then
begin
Inc(FTotalFilesCleaned);
FTotalBytesCleaned := FTotalBytesCleaned + TempFileSize;
end
else
begin
if chkReportErrors.Checked then
begin
chkReportErrors.Checked := (MessageDlg(Format(SCouldNotDelete,
[FileName]), mtError, [mbYes, mbNo], 0) = mrYes);
end;
end;
{$ENDIF SimulateDeleting}
end;
procedure TfmCleanDirectories.FillProjectDirectoriesList;
var
Strings: TStrings;
procedure AddPathToStrings(const Path: string);
begin
if Trim(Path) = '' then
Exit;
EnsureStringInList(Strings, Path);
end;
procedure AddProjectDir(const OptionName: string);
var
DirectoryVariant: Variant;
Directory: string;
ProjectDir: string;
begin
if GxOtaGetActiveProjectOption(OptionName, DirectoryVariant) then
if (VarType(DirectoryVariant) = varString) or
(VarType(DirectoryVariant) = varOleStr) then
begin
Directory := DirectoryVariant;
if Trim(Directory) <> '' then
begin
if IsPathAbsolute(Directory) then
begin
if not SysUtils.DirectoryExists(Directory) then
Exit;
end
else
begin
ProjectDir := ExtractFileDir(GxOtaGetCurrentProjectFileName);
if ProjectDir <> '' then
begin
Directory := AddSlash(ProjectDir) + Directory;
if not SysUtils.DirectoryExists(Directory) then
Exit;
end
else
Exit;
end;
AddPathToStrings(Directory);
end;
end;
end;
var
i: Integer;
Project: IOTAProject;
ModuleInfo: IOTAModuleInfo;
TempPathString: string;
begin
Project := GxOtaGetCurrentProject;
if not Assigned(Project) then
Exit;
Strings := clbDirs.Items;
Strings.BeginUpdate;
try
AddPathToStrings(ExtractFilePath(Project.FileName));
for i := 0 to Project.GetModuleCount - 1 do
begin
ModuleInfo := Project.GetModule(i);
Assert(Assigned(ModuleInfo));
if IsExecutable(ModuleInfo.FileName) then
Continue;
TempPathString := ExtractFilePath(ModuleInfo.FileName);
AddPathToStrings(TempPathString);
end;
if CleanExpert.FIncludeBinaryDirs then
begin
AddProjectDir('OutputDir');
AddProjectDir('UnitOutputDir');
AddProjectDir('PkgDcpDir');
end;
finally
Strings.EndUpdate;
end;
AddHorizontalScrollbar;
end;
procedure TfmCleanDirectories.FormCreate(Sender: TObject);
const // We will never localize these strings.
SDefaultCleanExts =
'.~bpg'+ sLineBreak + '.~cpp'+ sLineBreak + '.~dfm'+ sLineBreak + '.~dpk'+ sLineBreak +
'.~dsk'+ sLineBreak + '.~h' + sLineBreak + '.~hpp'+ sLineBreak + '.~pas'+ sLineBreak +
'.bak' + sLineBreak + '.cfg' + sLineBreak + '.csm' + sLineBreak + '.dcu' + sLineBreak +
'.dof' + sLineBreak + '.dsk' + sLineBreak + '.fts' + sLineBreak + '.gid' + sLineBreak +
'.il*' + sLineBreak + '.kwf' + sLineBreak + '.md' + sLineBreak + '.obj' + sLineBreak +
'.tds' + sLineBreak + '.tmp' + sLineBreak + '.$*' + sLineBreak + '.~*' + sLineBreak +
'.#??' + sLineBreak + '.ddp' + sLineBreak + '.rsm' + sLineBreak + '.map' + sLineBreak +
'.pdb' + sLineBreak + '.gex' + sLineBreak +'.~xfm' + sLineBreak + '.~nfm'+ sLineBreak +
'.~bdsproj'+ sLineBreak + '.~dproj'+ sLineBreak + '.~bdsgroup' + sLineBreak + '.~groupproj' + sLineBreak + '.identcache' + sLineBreak +
'.dcuil' + sLineBreak + '.dcpil';
var
i, j: Integer;
begin
laStatus.Caption := '';
LoadSettings;
if CleanExpert.ExtensionList.Count > 0 then
clbExtensions.Items.Assign(CleanExpert.ExtensionList)
else
clbExtensions.Items.Text := SDefaultCleanExts;
CleanExtList := TStringList.Create;
CleanExtList.Assign(CleanExpert.CleanList);
for i := CleanExtList.Count - 1 downto 0 do
begin
j := clbExtensions.Items.IndexOf(CleanExtList[i]);
if j >= 0 then
clbExtensions.Checked[j] := True
else
CleanExtList.Delete(i);
end;
FillProjectDirectoriesList;
CenterForm(Self);
EnsureFormVisible(Self);
end;
procedure TfmCleanDirectories.FormDestroy(Sender: TObject);
begin
UpdateCleanExtList;
CleanExpert.CleanList.Assign(CleanExtList);
CleanExpert.ExtensionList.Assign(clbExtensions.Items);
FreeAndNil(CleanExtList);
end;
procedure TfmCleanDirectories.PerformCleaning;
resourcestring
SCleaningComplete = 'Cleaning complete. %d files were deleted.' + sLineBreak +
'%s bytes of storage space were recovered.';
SOneCleaningComplete = 'Cleaning complete. %d file was deleted.' + sLineBreak +
'%s bytes of storage space were recovered.';
var
i: Integer;
ConfirmMessage: string;
begin
UpdateCleanExtList;
FTotalBytesCleaned := 0;
FTotalFilesCleaned := 0;
lCleaning.Visible := True;
lCleaning.Repaint;
Self.Cursor := crHourglass;
try
for i := 0 to clbDirs.Items.Count - 1 do
begin
// Ascertain that we have a trailing slash
// for each directory item.
clbDirs.Items[i] := AddSlash(clbDirs.Items[i]);
laStatus.Caption := MinimizeName(clbDirs.Items[i], laStatus.Canvas, laStatus.Width);
laStatus.Repaint;
// If a directory is checked, then the user wants
// to recurse into that directory and clean all
// items there, too.
CleanDirectory(clbDirs.Items[i], clbDirs.Checked[i]);
end;
finally
Self.Cursor := crDefault;
if FTotalFilesCleaned = 1 then
ConfirmMessage := SOneCleaningComplete
else
ConfirmMessage := SCleaningComplete;
// Prevent the status dialog from becoming hidden behind this window
Self.Hide;
MessageDlg(Format(ConfirmMessage,
[FTotalFilesCleaned,
FormatFloat('#,;;0', FTotalBytesCleaned)]),
mtInformation, [mbOK], 0);
lCleaning.Visible := False;
// This saving is also done on destruction, but duplicating it here
// preserves changes even if Delphi crashes before we are destroyed.
CleanExpert.CleanList.Assign(CleanExtList);
CleanExpert.ExtensionList.Assign(clbExtensions.Items);
end;
end;
procedure TfmCleanDirectories.AddHorizontalScrollbar;
begin
ListboxHorizontalScrollbar(clbDirs);
end;
procedure TfmCleanDirectories.FormResize(Sender: TObject);
begin
// Fixes a D5 paint bug when a horizontal scroll bar is visible
clbDirs.Repaint;
end;
procedure TfmCleanDirectories.LoadSettings;
var
Settings: TGExpertsSettings;
begin
// Do not localize any of the below strings.
Settings := TGExpertsSettings.Create;
try
Settings.LoadForm(Self, ConfigurationKey + '\Window', [fsSize]);
finally
FreeAndNil(Settings);
end;
end;
procedure TfmCleanDirectories.SaveSettings;
var
Settings: TGExpertsSettings;
begin
// Do not localize any of the below strings.
Settings := TGExpertsSettings.Create;
try
Settings.SaveForm(Self, ConfigurationKey + '\Window', [fsSize]);
finally
FreeAndNil(Settings);
end;
end;
procedure TfmCleanDirectories.CheckActionExecute(Sender: TObject);
begin
if Sender = actDirsCheckAll then
SetListBoxChecked(clbDirs, chAll)
else if Sender = actDirsUncheckAll then
SetListBoxChecked(clbDirs, chNone)
else if Sender = actDirsInvert then
SetListBoxChecked(clbDirs, chInvert)
else if Sender = actExtsCheckAll then
SetListBoxChecked(clbExtensions, chAll)
else if Sender = actExtsUncheckAll then
SetListBoxChecked(clbExtensions, chNone)
else if Sender = actExtsInvert then
SetListBoxChecked(clbExtensions, chInvert);
UpdateCleanExtList;
end;
procedure TfmCleanDirectories.UpdateCleanExtList;
var
i: Integer;
begin
Assert(Assigned(CleanExtList));
CleanExtList.Clear;
for i := 0 to clbExtensions.Items.Count - 1 do
if clbExtensions.Checked[i] then
CleanExtList.Add(clbExtensions.Items[i]);
end;
function TfmCleanDirectories.ConfigurationKey: string;
begin
Result := TCleanExpert.ConfigurationKey;
end;
{ TCleanExpert }
constructor TCleanExpert.Create;
begin
inherited Create;
FCleanList := TStringList.Create;
FExtensionList := TStringList.Create;
end;
destructor TCleanExpert.Destroy;
begin
SaveSettings;
FreeAndNil(FCleanList);
FreeAndNil(FExtensionList);
inherited Destroy;
end;
function TCleanExpert.GetActionCaption: string;
resourcestring
SMenuCaption = 'Clea&n Directories...';
begin
Result := SMenuCaption;
end;
class function TCleanExpert.GetName: string;
begin
Result := 'CleanDirectories';
end;
procedure TCleanExpert.Execute(Sender: TObject);
var
Dlg: TfmCleanDirectories;
begin
Dlg := TfmCleanDirectories.CreateParametrized(Self);
try
SetFormIcon(Dlg);
Dlg.chkReportErrors.Checked := FReportErrors;
Dlg.ShowModal;
FReportErrors := Dlg.chkReportErrors.Checked;
finally
FreeAndNil(Dlg);
end;
end;
procedure TCleanExpert.InternalLoadSettings(Settings: TExpertSettings);
begin
inherited InternalLoadSettings(Settings);
// Do not localize.
Settings.ReadStrings('Delete', CleanList, 'CleanExt');
Settings.ReadStrings('Extensions', ExtensionList, 'AvailableExt');
FReportErrors := Settings.ReadBool('ReportError', True);
FIncludeBinaryDirs := Settings.ReadBool('IncludeBinaryDirs', False)
end;
procedure TCleanExpert.InternalSaveSettings(Settings: TExpertSettings);
begin
inherited InternalSaveSettings(Settings);
// Do not localize.
Settings.WriteBool('ReportError', FReportErrors);
Settings.WriteBool('IncludeBinaryDirs', FIncludeBinaryDirs);
Settings.WriteStrings('Extensions', ExtensionList, 'AvailableExt');
Settings.WriteStrings('Delete', CleanList, 'CleanExt');
end;
function TCleanExpert.HasConfigOptions: Boolean;
begin
Result := True;
end;
procedure TCleanExpert.Configure;
resourcestring
SAddExeDcuDirsToCleanList =
'Would you like the project''s unit output and executable' + sLineBreak +
'output directories included in the default cleanable' + sLineBreak +
'directory list?';
begin
FIncludeBinaryDirs := MessageDlg(SAddExeDcuDirsToCleanList,
mtConfirmation, [mbYes, mbNo], 0) = mrYes;
end;
initialization
RegisterGX_Expert(TCleanExpert);
end.
|
unit uRESTRequest;
interface
uses
Classes, SysUtils, IdHTTP, fpjson, jsonparser;
Const
UrlBase = 'http://%s:%d/';
Type
TRSCharset = (rscUTF8, rscANSI);
TSendEvent = (seGET, sePOST, sePUT, seDELETE);
Type
TRESTClient = Class(TComponent) //Novo Componente de Acesso a Requisições REST para o RESTDataware
Protected
//Variáveis, Procedures e Funções Protegidas
HttpRequest : TIdHTTP;
Private
//Variáveis, Procedures e Funções Privadas
vRSCharset : TRSCharset;
vHost : String;
vPort : Integer;
Public
//Métodos, Propriedades, Variáveis, Procedures e Funções Publicas
Function SendEvent(EventData : String) : String;Overload;
Function SendEvent(EventData : String;
RBody : TStringList;
EventType : TSendEvent = sePOST) : String;Overload;
Constructor Create(AOwner: TComponent);
Destructor Destroy;
Published
//Métodos e Propriedades
Property Charset : TRSCharset Read vRSCharset Write vRSCharset;
Property Host : String Read vHost Write vHost;
Property Port : Integer Read vPort Write vPort;
End;
implementation
Function TRESTClient.SendEvent(EventData : String) : String;
Var
RBody : TStringList;
Begin
Try
Result := SendEvent(Format(UrlBase, [vHost, vPort]) + EventData, RBody, seGET);
Except
End;
End;
Function TRESTClient.SendEvent(EventData : String;
RBody : TStringList;
EventType : TSendEvent = sePOST) : String;
Var
StringStream : TStringStream;
vURL : String;
Begin
Try
If Pos(Uppercase(Format(UrlBase, [vHost, vPort])), Uppercase(EventData)) = 0 Then
vURL := LowerCase(Format(UrlBase, [vHost, vPort]) + EventData)
Else
vURL := LowerCase(EventData);
If vRSCharset = rscUTF8 Then
HttpRequest.Request.Charset := 'utf-8'
Else If vRSCharset = rscANSI Then
HttpRequest.Request.Charset := 'ansi';
Case EventType Of
seGET : Result := HttpRequest.Get(vURL);
sePOST,
sePUT,
seDELETE :
Begin;
If EventType = sePOST Then
Result := HttpRequest.Post(vURL, RBody)
Else If EventType = sePUT Then
Begin
StringStream := TStringStream.Create(RBody.Text);
Result := HttpRequest.Put(vURL, StringStream);
StringStream.Free;
End
Else If EventType = seDELETE Then
Result := HttpRequest.Delete(vURL);
End;
End;
Except
End;
End;
Constructor TRESTClient.Create(AOwner: TComponent);
Begin
Inherited;
HttpRequest := TIdHTTP.Create(Nil);
HttpRequest.Request.ContentType := 'application/json';
vHost := 'localhost';
vPort := 8080;
End;
Destructor TRESTClient.Destroy;
Begin
HttpRequest.Free;
Inherited;
End;
end.
|
unit RESTRequest4D.Request.Response.Intf;
interface
uses System.SysUtils, System.JSON;
type
/// <summary>
/// Interface representing the request response.
/// </summary>
IRequestResponse = interface
['{A3BB1797-E99E-4C72-8C4A-925825A50C27}']
/// <summary>
/// Get response content.
/// </summary>
/// <returns>
/// Returns the content of the request.
/// </returns>
function GetContent: string;
/// <summary>
/// Get response content length.
/// </summary>
/// <returns>
/// Returns the content length of the request.
/// </returns>
function GetContentLength: Cardinal;
/// <summary>
/// Get response content type.
/// </summary>
/// <returns>
/// Returns the content type of the request.
/// </returns>
function GetContentType: string;
/// <summary>
/// Get response content encoding.
/// </summary>
/// <returns>
/// Returns the content encoding of the request.
/// </returns>
function GetContentEncoding: string;
/// <summary>
/// Get HTTP response status code.
/// </summary>
/// <returns>
/// Status code.
/// </returns>
function GetStatusCode: Integer;
/// <summary>
/// Get response raw bytes.
/// </summary>
/// <returns>
/// Returns TBytes of the response.
/// </returns>
function GetRawBytes: TBytes;
/// <summary>
/// Get response JSON value.
/// </summary>
/// <returns>
/// Returns TJSONValue of the response.
/// </returns>
function GetJSONValue: TJSONValue;
end;
implementation
end.
|
unit MergeSort;
interface
uses
StrategyInterface;
type
TMergeSort = class(TInterfacedObject, ISorter)
procedure Sort(var A : Array of Integer);
destructor Destroy; override;
private
tmp : Array of Integer;
procedure Merge(var A : Array of Integer; l, m, r : Integer);
end;
implementation
uses
System.Math;
procedure TMergeSort.Sort(var A : Array of Integer);
var
low, mid, high, size, len : Integer;
begin
len := Length(A);
SetLength(tmp, len);
size := 1;
while size < len do begin
low := 0;
while low < len do begin
mid := low + size - 1;
high := Min(low + 2*size - 1, len-1);
Merge(A, low, mid, high);
low := low + 2*size;
end;
size := size * 2;
end;
end;
procedure TMergeSort.Merge(var A : Array of Integer; l, m, r : Integer);
var
p, q, k : Integer;
begin
p := l;
q := m+1;
k := 0;
while (p <= m) and (q <= r) do begin
if A[p] < A[q] then begin
tmp[k] := A[p];
Inc(p);
end
else begin
tmp[k] := A[q];
Inc(q);
end;
Inc(k);
end;
while p <= m do begin
tmp[k] := A[p];
Inc(k);
Inc(p);
end;
while q <= r do begin
tmp[k] := A[q];
Inc(k);
Inc(q);
end;
for p := 0 to r-l do begin
A[l+p] := tmp[p];
end;
end;
destructor TMergeSort.Destroy;
begin
WriteLn('Mergesort destr');
inherited;
end;
end.
|
//Exercicio 98:
{ Solução em Portugol
Algoritmo Exercicio 98;
Var
N: inteiro;
RESULTADO: caracter;
Procedimento Paridade(n: inteiro; Var resultado: caracter);
Inicio
se(resto(n,2) = 0)
então RESULTADO <- "VERDADEIRO"
senão RESULTADO <- "FALSO";
fimse;
Fim;
Inicio
exiba("Programa que exibe VERDADEIRO para um número par e FALSO para ímpar.");
exiba("Digite um número inteiro: ");
leia(N);
Paridade(N,RESULTADO);
exiba(RESULTADO);
Fim.
}
// Solução em Pascal
Program Exercicio;
uses crt;
Var
N: integer;
RESULTADO: string;
Procedure Paridade(n: integer; Var resultado:string);
Begin
if((n mod 2) = 0)
then RESULTADO := 'VERDADEIRO'
else RESULTADO := 'FALSO';
End;
Begin
writeln('Programa que exibe VERDADEIRO para um número par e FALSO para ímpar.');
writeln('Digite um número inteiro: ');
readln(N);
Paridade(N,RESULTADO);
writeln(RESULTADO);
repeat until keypressed;
end. |
UNIT PLAYVOCU;
{********************************************************************
* Unité pour piloter la Carte Sound Blaster avec Turbo-Pascal *
* en utilisant le Driver CT-VOICE.DRV. *
********************************************************************
* (C) 1992 MICRO APPLICATION *
* Auteur : Axel Stolz *
********************************************************************
}
INTERFACE
TYPE
VOCFileTyp = File;
CONST
VOCToolVersion = 'v1.5'; { Numéro de version de l'unité VOCTOOL }
VOCBreakEnd = 0; { Constante pour l'interruption de boucle }
VOCBreakNow = 1; { Constante pour l'interruption de boucle }
VAR
VOCStatusWord : WORD; { Variable pour Sound-Blaster-Status }
VOCErrStat : WORD; { Variable nž d'erreur driver }
VOCFileHeader : STRING; { Variable entłte du format CT }
VOCFileHeaderLength : BYTE; { Longueur de l'entłte du format CT }
VOCPaused : BOOLEAN; { Flag Voice-Pause }
VOCDriverInstalled : BOOLEAN; { Flag Driver installé }
VOCDriverVersion : WORD; { Numéro de version du Driver }
VOCPtrToDriver : Pointer; { Pointeur sur le Driver en mémoire }
OldExitProc : Pointer; { Pointeur sur l'ancienne Unit-ExitProc }
PROCEDURE PrintVOCErrMessage;
FUNCTION VOCGetBuffer(VAR VoiceBuff : Pointer; Voicefile : STRING):BOOLEAN;
FUNCTION VOCFreeBuffer(VAR VoiceBuff : Pointer):BOOLEAN;
FUNCTION VOCGetVersion:WORD;
PROCEDURE VOCSetPort(PortNumber : WORD);
PROCEDURE VOCSetIRQ(IRQNumber : WORD);
FUNCTION VOCInitDriver:BOOLEAN;
PROCEDURE VOCDeInstallDriver;
PROCEDURE VOCSetSpeaker(OnOff:BOOLEAN);
PROCEDURE VOCOutput(BufferAddress : Pointer);
PROCEDURE VOCOutputLoop (BufferAddress : Pointer);
PROCEDURE VOCStop;
PROCEDURE VOCPause;
PROCEDURE VOCContinue;
PROCEDURE VOCBreakLoop(BreakMode : WORD);
IMPLEMENTATION
USES DOS,Crt;
TYPE TypeCastType = ARRAY [0..6000] of Char;
VAR Regs : Registers;
PROCEDURE PrintVOCErrMessage;
{
* ENTRÉE : aucune
* SORTIE : aucune
* FONCTION : affiche ů l'écran, sous forme texte, l'erreur Sound Blaster
* venant de se produire, sans modifier la valeur du status.
}
BEGIN
CASE VOCErrStat OF
100 : Write(' Erreur: Driver CT-VOICE.DRV non trouvé ');
110 : Write(' Erreur: Place mémoire insuffisante pour le driver ');
120 : Write(' Erreur: Driver incorrect');
200 : Write(' Erreur: Fichier VOC non trouvé ');
210 : Write(' Erreur: Espace mémoire insuffisant pour le Fichier VOC ');
220 : Write(' Erreur: Le Fichier n''est pas au format VOC');
300 : Write(' Erreur: Erreur d''implémentation en mémoire ');
400 : Write(' Erreur: Carte Sound Blaster non trouvée ');
410 : Write(' Erreur: Adresse de port incorrecte ');
420 : Write(' Erreur: Utilisation d''une interruption erronée ');
500 : Write(' Erreur: Pas de boucle en cours ');
510 : Write(' Erreur: Aucun échantillon en cours de diffusion ');
520 : Write(' Erreur: Pas d''échantillon interrompu ');
END;
END;
FUNCTION Exists (Filename : STRING):BOOLEAN;
{ * ENTRÉE : Nom de fichier sous forme chaîne de caractŐre
* SORTIE : TRUE, au cas oŚ un fichier existe, FALSE sinon
* FONCTION : vérifie si un fichier existe et retourne une valeur
* booléenne }
VAR
F : File;
BEGIN
Assign(F,Filename);
{$I-}
Reset(F);
Close(F);
{$I+}
Exists := (IoResult = 0) AND (Filename <> '');
END;
PROCEDURE AllocateMem (VAR Pt : Pointer; Size : LongInt);
{
* ENTRÉE : Entrée pointeur sur le buffer,
* Taille du buffer sous forme d'entier long
* SORTIE : Pointeur sur le buffer
* FONCTION : Réserve un buffer ů l'adresse indiquée de la taille donnée
* Si la mémoire présente ne suffit pas, le pointeur pointera
* sur NIL
}
VAR
SizeIntern : WORD; { taille du buffer réservé au calcul interne }
BEGIN
Inc(Size,15); { augmenter la taille du buffer de 15 }
SizeIntern := (Size shr 4); { et diviser ensuite par 16 }
Regs.AH := $48; { charger la fonction $48 de MSDOS dans AH }
Regs.BX := SizeIntern; { charger la taille interne dans BX }
MsDos(Regs); { réserver la mémoire }
IF (Regs.BX <> SizeIntern) THEN Pt := NIL
ELSE Pt := Ptr(Regs.AX,0);
END;
FUNCTION CheckFreeMem (VAR VoiceBuff : Pointer; VoiceSize : LongInt):BOOLEAN;
{
* ENTRÉE : Pointeur sur le buffer, taille désirée en entier format long
* SORTIE : Pointeur sur le buffer, TRUE/FALSE, suivant AllocateMem
* FONCTION : Vérifie, qu'il y a suffisamment de mémoire pour charger un fichier VOC.
}
BEGIN
AllocateMem(VoiceBuff,VoiceSize);
CheckFreeMem := VoiceBuff <> NIL;
END;
FUNCTION VOCGetBuffer (VAR VoiceBuff : Pointer; Voicefile : STRING):BOOLEAN;
{
* ENTRÉE : Pointeur sur le buffer, nom de fichier sous forme chaîne de
caractŐre
* SORTIE : Pointeur sur le buffer avec des données VOC, TRUE/FALSE
* FONCTION : Charge un fichier en mémoire, et retourne la valeur TRUE
si le fichier a été correctement chargé
}
VAR
SampleSize : LongInt;
FPresent : BOOLEAN;
VFile : VOCFileTyp;
Segs : WORD;
Read : WORD;
BEGIN
FPresent := Exists(VoiceFile);
{ Le fichier VOC n'a pas été trouvé }
IF Not(FPresent) THEN BEGIN
VOCGetBuffer := FALSE;
VOCErrStat := 200;
EXIT
END;
Assign(VFile,Voicefile);
Reset(VFile,1);
SampleSize := Filesize(VFile);
AllocateMem(VoiceBuff,SampleSize);
{ Espace mémoire insuffisant pour le fichier VOC }
IF (VoiceBuff = NIL) THEN BEGIN
Close(VFile);
VOCGetBuffer := FALSE;
VOCErrStat := 210;
EXIT;
END;
Segs := 0;
REPEAT
Blockread(VFile,Ptr(seg(VoiceBuff^)+4096*Segs,Ofs(VoiceBuff^))^,$FFFF,Read);
Inc(Segs);
UNTIL Read = 0;
Close(VFile);
{ Le fichier n'est pas au format VOC }
IF (TypeCastType(VoiceBuff^)[0]<>'C') OR
(TypeCastType(VoiceBuff^)[1]<>'r') THEN BEGIN
VOCGetBuffer := FALSE;
VOCErrStat := 220;
EXIT;
END;
{ Le chargement a été correctement effectué }
VOCGetBuffer := TRUE;
VOCErrStat := 0;
{ Lire la longueur de l'en-tłte dans le fichier }
VOCFileHeaderLength := Ord(TypeCastType(VoiceBuff^)[20]);
END;
FUNCTION VOCFreeBuffer (VAR VoiceBuff : Pointer):BOOLEAN;
{
* ENTRÉE : Pointeur sur le buffer
* SORTIE : aucune
* FONCTION : LibŐre la mémoire occupée par les données VOC
}
BEGIN
Regs.AH := $49; { Charger la fonction MSDOS $49 dans AH }
Regs.ES := seg(VoiceBuff^); { Charger le segment de la mémoire dans ES }
MsDos(Regs); { Libérer la mémoire }
VOCFreeBuffer := TRUE;
IF (Regs.AX = 7) OR (Regs.AX = 9) THEN BEGIN
VOCFreeBuffer := FALSE;
VOCErrStat := 300 { Erreur DOS au cours de la libération de
mémoire}
END;
END;
FUNCTION VOCGetVersion:WORD;
{
* ENTRÉE : aucune
* SORTIE : Numéro de version du driver
* FONCTION : Transmet le numéro de version du driver
}
VAR
VDummy : WORD;
BEGIN
ASM
MOV BX,0
CALL VOCPtrToDriver
MOV VDummy, AX
END;
VOCGetVersion := VDummy;
END;
PROCEDURE VOCSetPort(PortNumber : WORD);
{
* ENTRÉE : Numéro d'adresse du port
* SORTIE : aucune
* FONCTION : Fixe l'adresse du port avant initialisation
}
BEGIN
ASM
MOV BX,1
MOV AX,PortNumber
CALL VOCPtrToDriver
END;
END;
PROCEDURE VOCSetIRQ(IRQNumber : WORD);
{
* ENTRÉE : Numéro d'interruption
* SORTIE : aucune
* FONCTION : Fixe le numéro d'interruption avant initialisation
}
BEGIN
ASM
MOV BX,2
MOV AX,IRQNumber
CALL VOCPtrToDriver
END;
END;
FUNCTION VOCInitDriver: BOOLEAN;
{
* ENTRÉE : aucune
* SORTIE : Numéro d'erreur suivant le résultat de l'initialisation
* FONCTION : Initialisation du driver
}
VAR
Out, VSeg, VOfs : WORD;
F : File;
Drivername,
Pdir : DirStr;
Pnam : NameStr;
Pext : ExtStr;
BEGIN
{ Le driver CT-VOICE.DRV est cherché dans le répertoire
dans lequel a été trouvé le programme qui doit utiliser le driver }
Pdir := ParamStr(0);
Fsplit(ParamStr(0),Pdir,Pnam,Pext);
Drivername := Pdir+'CT-VOICE.DRV';
VOCInitDriver := TRUE;
{ Driver non trouvé }
IF Not Exists(Drivername) THEN BEGIN
VOCInitDriver := FALSE;
VOCErrStat := 100;
EXIT;
END;
{ Chargement du driver }
Assign(F,Drivername);
Reset(F,1);
AllocateMem(VOCPtrToDriver,Filesize(F));
{ Espace mémoire insuffisant pour le driver }
IF VOCPtrToDriver = NIL THEN BEGIN
VOCInitDriver := FALSE;
VOCErrStat := 110;
EXIT;
END;
Blockread(F,VOCPtrToDriver^,Filesize(F));
Close(F);
{ Driver incorrect, ne commence pas par "CT" }
IF (TypeCastType(VOCPtrToDriver^)[3]<>'C') OR
(TypeCastType(VOCPtrToDriver^)[4]<>'T') THEN BEGIN
VOCInitDriver := FALSE;
VOCErrStat := 120;
EXIT;
END;
{ Transmettre le numéro de version, et charger dans la variable globale }
VOCDriverVersion := VOCGetVersion;
{ Lancer le Driver }
Vseg := Seg(VOCStatusWord);
VOfs := Ofs(VOCStatusWord);
ASM
MOV BX,3
CALL VOCPtrToDriver
MOV Out,AX
MOV BX,5
MOV ES,VSeg
MOV DI,VOfs
CALL VOCPtrToDriver
END;
{ Carte Sound Blaster non trouvée }
IF Out = 1 THEN BEGIN
VOCInitDriver := FALSE;
VOCErrStat := 400;
EXIT;
END;
{ Utilisation d'une adresse de port incorrecte }
IF Out = 2 THEN BEGIN
VOCInitDriver := FALSE;
VOCErrStat := 410;
EXIT;
END;
{ Utilisation d'un numéro d'interruption incorrect }
IF Out = 3 THEN BEGIN
VOCInitDriver := FALSE;
VOCErrStat := 420;
EXIT;
END;
END;
PROCEDURE VOCDeInstallDriver;
{
* ENTRÉE : aucune
* SORTIE : aucune
* FONCTION : Désactivation du driver et libération de la mémoire
}
VAR
Check : BOOLEAN;
BEGIN
IF VOCDriverInstalled THEN
ASM
MOV BX,9
CALL VOCPtrToDriver
END;
Check := VOCFreeBuffer(VOCPtrToDriver);
END;
PROCEDURE VOCSetSpeaker(OnOff:BOOLEAN);
{
* ENTRÉE : TRUE pour l'activation du haut-parleur et FALSE pour la désactivation
* SORTIE : aucune
* FONCTION : ON/OFF - Active ou désactive le haut-parleur
}
VAR
Switch : BYTE;
BEGIN
Switch := Ord(OnOff) AND $01;
ASM
MOV BX,4
MOV AL,Switch
CALL VOCPtrToDriver
END;
END;
PROCEDURE VOCOutput (BufferAddress : Pointer);
{
* ENTRÉE : Pointeur sur les données de l'échantillon numérique
* SORTIE : Aucune
* FONCTION : Diffusion d'un échantillon
}
VAR
VSeg, VOfs : WORD;
BEGIN
VOCSetSpeaker(TRUE);
VSeg := Seg(BufferAddress^);
VOfs := Ofs(BufferAddress^)+VOCFileHeaderLength;
ASM
MOV BX,6
MOV ES,VSeg
MOV DI,VOfs
CALL VOCPtrToDriver
END;
END;
PROCEDURE VOCOutputLoop (BufferAddress : Pointer);
{
* Différence avec VOCOutput :
* Le haut-parleur ne sera pas activé avant chaque diffusion d'un
* échantillon, afin d'éviter les bruits en résultant.
}
VAR
VSeg, VOfs : WORD;
BEGIN
VSeg := Seg(BufferAddress^);
VOfs := Ofs(BufferAddress^)+VOCFileHeaderLength;
ASM
MOV BX,6
MOV ES,VSeg
MOV DI,VOfs
CALL VOCPtrToDriver
END;
END;
PROCEDURE VOCStop;
{ * ENTRÉE : aucune
* SORTIE : aucune
* FONCTION : Stoppe un échantillon }
BEGIN
ASM
MOV BX,8
CALL VOCPtrToDriver
END;
END;
PROCEDURE VOCPause;
{
* ENTRÉE : aucune
* SORTIE : aucune
* FONCTION : Interrompt un échantillon
}
VAR
Switch : WORD;
BEGIN
VOCPaused := TRUE;
ASM
MOV BX,10
CALL VOCPtrToDriver
MOV Switch,AX
END;
IF (Switch = 1) THEN BEGIN
VOCPaused := FALSE;
VOCErrStat := 510;
END;
END;
PROCEDURE VOCContinue;
{
* ENTRÉE : aucune
* SORTIE : aucune
* FONCTION : Reprend un échantillon interrompu
}
VAR
Switch : WORD;
BEGIN
ASM
MOV BX,11
CALL VOCPtrToDriver
MOV Switch,AX
END;
IF (Switch = 1) THEN BEGIN
VOCPaused := FALSE;
VOCErrStat := 520;
END;
END;
PROCEDURE VOCBreakLoop(BreakMode : WORD);
{
* ENTRÉE : Mode d'interruption
* SORTIE : aucune
* FONCTION : Interrompt une boucle dans un échantillon
}
BEGIN
ASM
MOV BX,12
MOV AX,BreakMode
CALL VOCPtrToDriver
MOV BreakMode,AX
END;
IF (BreakMode = 1) THEN VOCErrStat := 500;
END;
{$F+}
PROCEDURE VoiceToolsExitProc;
{$F-}
{
* ENTRÉE : aucune
* SORTIE : aucune
* FONCTION : Dans la nouvelle ExitProc, le driver Voice sera a nouveau
installé ů la fin du programme
}
BEGIN
VOCDeInstallDriver;
ExitProc := OldExitProc;
END;
BEGIN
{
* Les instructions suivantes seront automatiquement exécutées dŐs que
* l'Unité sera reliée ů un programme et que celui-ci sera exécuté
}
{ Transpose l'ancienne ExitProc sur la nouvelle Tool-Unit }
OldExitProc := ExitProc;
ExitProc := @VoiceToolsExitProc;
{ Initialisation des valeurs de base }
VOCStatusWord := 0;
VOCErrStat := 0;
VOCPaused := FALSE;
VOCFileHeaderLength := $1A;
VOCFileHeader :=
'Creative Voice File'+#$1A+#$1A+#$00+#$0A+#$01+#$29+#$11+#$01;
{
* Contient aprŐs l'installation soit TRUE ou FALSE suivant que le driver
* a été installé correctement ou pas
}
VOCDriverInstalled := VOCInitDriver;
END.
|
{ rxFileUtils is part of RxFPC library
Copyright (C) 2005-2013 Lagunov Aleksey alexs@hotbox.ru and Lazarus team
original conception from rx library for Delphi (c)
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit rxFileUtils;
{$I rx.inc}
interface
uses
SysUtils;
function GetFileOwnerUser(const SearchDomain, FileName:String):String;
procedure GetFileOwnerData(const SearchDomain, FileName:String;out UserName, DomainName:string);
function NormalizeDirectoryName(const DirName:string):string;
function GetUserName:string;
implementation
uses
{$IFDEF WINDOWS}
Windows,
{$ELSE}
{$ENDIF}
FileUtil;
{$IF DEFINED(WINDOWS) AND NOT DEFINED(WINCE)}
function LStrError(const Ernum: Longint; const UseUTF8: Boolean = False): string;
const
MAX_ERROR = 1024;
var
Tmp: string;
TmpW: widestring;
begin
Result := ' [' + IntToStr(Ernum) + ']: ';
if USEUtf8 then begin
SetLength(TmpW, MAX_ERROR);
SetLength(TmpW, FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM or
FORMAT_MESSAGE_IGNORE_INSERTS or
FORMAT_MESSAGE_ARGUMENT_ARRAY,
nil, Ernum, 0, @TmpW[1], MAX_ERROR, nil));
Tmp := UTF8Encode(TmpW);
end else begin
SetLength(Tmp, MAX_ERROR);
SetLength(Tmp, FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM or
FORMAT_MESSAGE_IGNORE_INSERTS or
FORMAT_MESSAGE_ARGUMENT_ARRAY,
nil, Ernum, 0, @Tmp[1], MAX_ERROR, nil));
end;
if Length(Tmp) > 2 then
Delete(Tmp, Length(Tmp)-1, 2);
Result := Result + Tmp;
end;
{ TODO -oalexs : In future need rewrite this code for fix mem leak }
procedure GetFileNameOwner(const SearchDomain, FileName: String; out UserName, DomainName: string);
var
RCode, RC1:WINBOOL;
SDSize:DWORD; // Size of security descriptor
FAccountName:PChar; // Account name
lngAccountLen:DWORD; // Length of account name
FDomainName:PChar; // Domain name
lngDomainLen:DWORD; // Length of domain name
ptrUse:SID_NAME_USE; // Pointer to SID_NAME_USE
ptrOwner:PSID;
P:PByteArray;
begin
ptrOwner:=nil;
SDSize:=0;
P:=nil;
UserName:='';
DomainName:='';
RCode := GetFileSecurity(PChar(FileName), OWNER_SECURITY_INFORMATION, nil, 0, @SDSize);
GetMem(P, SDSize);
FillChar(P^, SDSize, 0);
RCode := GetFileSecurity(PChar(FileName), OWNER_SECURITY_INFORMATION, Pointer(P), SDSize, @SDSize);
if not RCode then
raise Exception.Create(LStrError(GetLastError, true));
RCode := GetSecurityDescriptorOwner(Pointer(P), ptrOwner, @RC1);
if not RCode then
raise Exception.Create(LStrError(GetLastError, true));
lngAccountLen:=0;
lngDomainLen:=0;
RCode := LookupAccountSid(PChar(SearchDomain), ptrOwner, nil, lngAccountLen, nil, lngDomainLen, ptrUse);
//' Configure the strings' buffer sizes
GetMem(FAccountName, lngAccountLen);
FillChar(FAccountName^, lngAccountLen, 0);
GetMem(FDomainName, lngDomainLen);
FillChar(FDomainName^, lngDomainLen, 0);
RCode:=LookupAccountSid(PChar(SearchDomain), ptrOwner, FAccountName, lngAccountLen, FDomainName, lngDomainLen, ptrUse);
if not RCode then
raise Exception.Create(LStrError(GetLastError, true));
UserName:=FAccountName;
DomainName:=FDomainName;
Freemem(P, SDSize);
Freemem(FAccountName, lngAccountLen);
Freemem(FDomainName, lngDomainLen);
end;
{$ELSE}
{$ENDIF}
function GetFileOwnerUser(const SearchDomain, FileName: String): String;
var
S:string;
begin
{$IF DEFINED(WINDOWS) AND NOT DEFINED(WINCE)}
GetFileNameOwner(UTF8ToSys(SearchDomain), UTF8ToSys(FileName), Result, S);
Result:=UTF8Encode(Result);
{$ELSE}
Result:='';
{$ENDIF}
end;
procedure GetFileOwnerData(const SearchDomain, FileName: String; out UserName,
DomainName: string);
begin
{$IF DEFINED(WINDOWS) AND NOT DEFINED(WINCE)}
GetFileNameOwner(UTF8ToSys(SearchDomain), UTF8ToSys(FileName), UserName, DomainName);
UserName:=UTF8Encode(UserName);
DomainName:=UTF8Encode(DomainName);
{$ELSE}
UserName:='';
DomainName:='';
{$ENDIF}
end;
{replase any dir separators '\' or '/' to system directory separator }
function NormalizeDirectoryName(const DirName: string): string;
var
i:integer;
begin
Result:=DirName;
for i:=1 to Length(Result) do
if Result[i] in ['/', '\'] then
Result[i]:=DirectorySeparator;
end;
function GetUserName: string;
{$IF DEFINED(WINDOWS) AND NOT DEFINED(WINCE)}
var
A:array [0..256] of Char;
L:DWORD;
{$ENDIF}
begin
{$IF DEFINED(WINDOWS) AND NOT DEFINED(WINCE)}
FillChar(A, SizeOf(A), 0);
L:=SizeOf(A)-1;
if Windows.GetUserNameA(@A, L) then
begin
Result:=SysToUTF8(StrPas(@A));
end
else
Result:=GetEnvironmentVariableUTF8('USERNAME');
{$ELSE}
Result:=GetEnvironmentVariable('USER');
{$ENDIF}
end;
end.
|
unit ShodanAPI;
interface
uses
Main,
System.Classes;
const
SHODAN_API_ENDPOINT = 'https://api.shodan.io/shodan/host';
type
TShoShodan = class
private
Acrawler: string;
Aptr: boolean;
Aid: string;
Amodule: string;
public
property crawler: string read Acrawler write Acrawler;
property ptr: boolean read Aptr write Aptr default false;
property id: string read Aid write Aid;
property module: string read Amodule write Amodule;
constructor Create;
end;
TShoHTTP = class
private
Arobots_hash: string;
Aredirects: TArray<string>;
Asecuritytxt: string;
Atitle: string;
Asitemap_hash: string;
Arobots: string;
Aserver: string;
Ahost: string;
Ahtml: string;
Alocation: string;
Asecuritytxt_hash: string;
Asitemap: string;
Ahtml_hash: Int64;
public
property robots_hash: string read Arobots_hash write Arobots_hash;
property redirects: TArray<string> read Aredirects write Aredirects;
property securitytxt: string read Asecuritytxt write Asecuritytxt;
property title: string read Atitle write Atitle;
property sitemap_hash: string read Asitemap_hash write Asitemap_hash;
property robots: string read Arobots write Arobots;
property server: string read Aserver write Aserver;
property host: string read Ahost write Ahost;
property html: string read Ahtml write Ahtml;
property location: string read Alocation write Alocation;
property securitytxt_hash: string read Asecuritytxt_hash write Asecuritytxt_hash;
property sitemap: string read Asitemap write Asitemap;
property html_hash: Int64 read Ahtml_hash write Ahtml_hash default 0;
constructor Create;
end;
TShoLocation = class
private
Acity: string;
Aregion_code: string;
Aarea_code: string;
Alongitude: double;
Acountry_code3: string;
Alatitude: double;
Apostal_code: string;
Adma_code: integer;
Acountry_code: string;
Acountry_name: string;
public
property city: string read Acity write Acity;
property region_code: string read Aregion_code write Aregion_code;
property area_code: string read Aarea_code write Aarea_code;
property longitude: double read Alongitude write Alongitude;
property country_code3: string read Acountry_code3 write Acountry_code3;
property latitude: double read Alatitude write Alatitude;
property postal_code: string read Apostal_code write Apostal_code;
property dma_code: integer read Adma_code write Adma_code default 0;
property country_code: string read Acountry_code write Acountry_code;
property country_name: string read Acountry_name write Acountry_name;
constructor Create;
end;
TShoMatch = class
private
Aproduct: string;
Ahash: Int64;
Aip: Int64;
Aorg: string;
Aisp: string;
Atransport: string;
Acpe: TArray<string>;
Adata: string;
Aasn: string;
Aport: word;
Ahostnames: TArray<string>;
Alocation: TShoLocation;
Atimestamp: string;
Adomains: TArray<string>;
Ahttp: TShoHTTP;
Aos: string;
A_shodan: TShoShodan;
Aip_str: string;
public
property product: string read Aproduct write Aproduct;
property hash: Int64 read Ahash write Ahash default 0;
property ip: Int64 read Aip write Aip default 0;
property org: string read Aorg write Aorg;
property isp: string read Aisp write Aisp;
property transport: string read Atransport write Atransport;
property cpe: TArray<string> read Acpe write Acpe;
property data: string read Adata write Adata;
property asn: string read Aasn write Aasn;
property port: word read Aport write Aport default 0;
property hostnames: TArray<string> read Ahostnames write Ahostnames;
property location: TShoLocation read Alocation write Alocation;
property timestamp: string read Atimestamp write Atimestamp;
property domains: TArray<string> read Adomains write Adomains;
property http: TShoHTTP read Ahttp write Ahttp;
property os: string read Aos write Aos;
property _shodan: TShoShodan read A_shodan write A_shodan;
property ip_str: string read Aip_str write Aip_str;
constructor Create;
end;
TShoResponse = class
private
Amatches: TArray<TShoMatch>;
Atotal: Int64;
Aerror: string;
public
property matches: TArray<TShoMatch> read Amatches write Amatches;
property total: Int64 read Atotal write Atotal default 0;
property error: string read Aerror write Aerror;
constructor Create;
destructor Destroy; override;
procedure ConcatMatches(Matches: TArray<TShoMatch>);
end;
procedure GetQueryResults (
var Result: TShoResponse;
ApiKey: string;
Query: string;
var ErrMsg: string;
MaxCount: Int64 = 0;
Retries: word = 5;
ProgressCallback: TProgressCallback = nil;
TaskFinishedCallBack: TThreadProcedure = nil
);
implementation
uses
// [START] DELPHI NEON
Neon.Core.Persistence
, Neon.Core.Types
, Neon.Core.Persistence.JSON
, System.TypInfo
// [END] DELPHI NEON
, System.Generics.Collections
, REST.Client
, REST.Types
, System.JSON
, System.SysUtils
, FMX.Forms;
function APIRequest(Resource: string; out ErrMsg: string; Params: TDictionary<string, string>; ApiKey: string; Page: Int64 = 1): TJSONObject;
var
JSON: TJSONObject;
RESTClient: TRESTClient;
RESTRequest: TRESTRequest;
RESTResponse: TRESTResponse;
Key, Content: string;
begin
Result := nil;
ErrMsg := '';
try
RESTClient := TRESTClient.Create(SHODAN_API_ENDPOINT);
try
RESTClient.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,';
RESTClient.AcceptCharset := 'UTF-8, *;q=0.8';
RESTClient.ContentType := 'application/json; charset=utf-8';
RESTClient.HandleRedirects := false;
RESTClient.SecureProtocols := [];
RESTRequest := TRESTRequest.Create(nil);
try
RESTRequest.Client := RESTClient;
RESTRequest.Timeout := 180000;
RESTRequest.Resource := Resource;
RESTRequest.Method := TRESTRequestMethod.rmGET;
RESTRequest.Params.Clear;
RESTRequest.Params.AddItem('key', ApiKey, TRESTRequestParameterKind.pkGETorPOST);
RESTRequest.Params.AddItem('page', IntToStr(Page), TRESTRequestParameterKind.pkGETorPOST);
RESTRequest.Params.AddItem('minify', 'true', TRESTRequestParameterKind.pkGETorPOST);
if Assigned(Params) then
begin
for Key in Params.Keys do
RESTRequest.Params.AddItem(Key, Params[Key], TRESTRequestParameterKind.pkGETorPOST);
end;
RESTResponse := TRESTResponse.Create(nil);
try
RESTRequest.Response := RESTResponse;
RESTRequest.Execute;
Content := RESTResponse.Content;
JSON := TJSONObject.Create;
if JSON.Parse(BytesOf(Content), 0) > 0 then
Result := JSON;
finally
RESTResponse.Free;
end;
finally
RESTRequest.Free;
end;
finally
RESTClient.Free;
end;
except
on E: Exception do
begin
Result := nil;
ErrMsg := E.Message;
end;
end;
end;
procedure GetQueryResults (
var Result: TShoResponse;
ApiKey: string;
Query: string;
var ErrMsg: string;
MaxCount: Int64 = 0;
Retries: word = 5;
ProgressCallback: TProgressCallback = nil;
TaskFinishedCallBack: TThreadProcedure = nil
);
var
QueryResult: TJSONObject;
Params: TDictionary<string, string>;
LConfig: INeonConfiguration;
LReader: TNeonDeserializerJSON;
MaxPages: Int64;
Response: TShoResponse;
Page, Total, CurrMatches: Int64;
Retry: word;
// CurrStatus: TProcessStatus;
begin
Result := nil;
// CurrStatus := TProcessStatus.psStart;
// if Assigned(StatusCallback) then
// StatusCallback(CurrStatus);
// CurrStatus := TProcessStatus.psInProgress;
try
try
Params := TDictionary<string, string>.Create;
try
Params.Add('query', Query);
MaxPages := 0;
if MaxCount > 0 then
begin
MaxPages := Trunc(MaxCount / 100);
if (MaxCount - (MaxPages * 100)) <> 0 then
MaxPages := MaxPages + 1;
end;
LConfig := TNeonConfiguration.Default
.SetMemberCase(TNeonCase.SnakeCase)
.SetMembers([TNeonMembers.Properties])
.SetIgnoreFieldPrefix(false)
.SetVisibility([mvPublic]);
LReader := TNeonDeserializerJSON.Create(LConfig);
try
Retry := 0;
repeat
QueryResult := APIRequest('search', ErrMsg, Params, ApiKey);
if Assigned(ProgressCallback) then
TThread.Synchronize(
TThread.CurrentThread,
procedure
begin
ProgressCallback(0, 100);
end
);
{
if Assigned(StatusCallback) then
begin
StatusCallback(CurrStatus);
if CurrStatus = TProcessStatus.psEnded then
Exit;
end;
}
if not Assigned(QueryResult) then
begin
Retry := Retry + 1;
TThread.Sleep(1000);
end;
until Assigned(QueryResult) or (Retry > Retries);
if Assigned(QueryResult) then
begin
try
Result := TShoResponse.Create;
LReader.JSONToObject(Result, QueryResult);
{
if Assigned(StatusCallback) then
begin
StatusCallback(CurrStatus);
if CurrStatus = TProcessStatus.psEnded then
Exit;
end;
}
if Assigned(Result) then
begin
if Assigned(ProgressCallback) then
begin
Total := Result.total;
TThread.Synchronize(
TThread.CurrentThread,
procedure
begin
ProgressCallback(Total, 100);
end
);
end;
Page := 2;
Retry := 0;
while (Assigned(QueryResult) or (Retry <= Retries)) and ((MaxPages = 0) or (Page <= MaxPages)) do
begin
QueryResult := APIRequest('search', ErrMsg, Params, ApiKey, Page);
{
if Assigned(StatusCallback) then
begin
StatusCallback(CurrStatus);
if CurrStatus = TProcessStatus.psEnded then
Exit;
end;
}
if Assigned(QueryResult) then
begin
Retry := 0;
Response := TShoResponse.Create;
LReader.JSONToObject(Response, QueryResult);
{
if Assigned(StatusCallback) then
begin
StatusCallback(CurrStatus);
if CurrStatus = TProcessStatus.psEnded then
Exit;
end;
}
if Assigned(Response) then
begin
try
if Response.error = '' then
begin
if Length(Response.matches) = 0 then
Exit;
Result.ConcatMatches(Response.matches);
{
if Assigned(StatusCallback) then
begin
StatusCallback(CurrStatus);
if CurrStatus = TProcessStatus.psEnded then
Exit;
end;
}
if Assigned(ProgressCallback) then
begin
CurrMatches := Length(Result.matches);
TThread.Synchronize(
TThread.CurrentThread,
procedure
begin
ProgressCallback(Total, CurrMatches);
end
);
end;
end
else
begin
Result := nil;
ErrMsg := Response.error;
Exit;
end;
finally
Response.Free;
end;
end;
end
else
begin
if ErrMsg <> '' then
begin
Retry := Retry + 1;
if Retry <= Retries then
begin
TThread.Sleep(1000);
Continue;
end
else
begin
FreeAndNil(Result);
ErrMsg := ErrMsg + ' (#' + IntToStr(Page) + ')';
end;
end;
end;
Page := Page + 1;
end;
end;
finally
if Assigned(QueryResult) then
QueryResult.Free;
end;
end;
finally
LReader.Free;
end;
finally
Params.Free;
end;
except
on E: Exception do
begin
FreeAndNil(Result);
ErrMsg := E.Message;
end;
end;
finally
if Assigned(TaskFinishedCallBack) then
TThread.Synchronize(TThread.CurrentThread, TaskFinishedCallBack);
end;
end;
{ TShoLocation }
constructor TShoLocation.Create;
begin
inherited Create;
city := '';
region_code := '';
area_code := '';
country_code3 := '';
postal_code := '';
country_code := '';
country_name := '';
longitude := 0;
latitude := 0;
end;
{ TShoHTTP }
constructor TShoHTTP.Create;
begin
inherited Create;
robots_hash := '';
redirects := nil;
securitytxt := '';
title := '';
sitemap_hash := '';
robots := '';
server := '';
host := '';
html := '';
location := '';
securitytxt_hash := '';
sitemap := '';
end;
{ TShoShodan }
constructor TShoShodan.Create;
begin
inherited Create;
crawler := '';
id := '';
module := '';
end;
{ TShoMatch }
constructor TShoMatch.Create;
begin
inherited Create;
product := '';
org := '';
isp := '';
transport := '';
cpe := nil;
data := '';
asn := '';
hostnames := nil;
location := TShoLocation.Create;
timestamp := '';
domains := nil;
http := TShoHTTP.Create;
os := '';
_shodan := TShoShodan.Create;
ip_str := '';
end;
{ TShoResponse }
procedure TShoResponse.ConcatMatches(Matches: TArray<TShoMatch>);
var
CurrLen, i: Int64;
begin
CurrLen := Length(Amatches);
SetLength(Amatches, CurrLen + Length(Matches));
for i := Low(Matches) to High(Matches) do
Amatches[CurrLen + i] := Matches[i];
end;
constructor TShoResponse.Create;
begin
inherited Create;
matches := nil;
error := '';
end;
destructor TShoResponse.Destroy;
begin
inherited;
Amatches := nil;
end;
end.
|
unit HGM.AutoTextType;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, HGM.Common;
type
TOnTextChange = procedure(Sender:TObject; Text:string) of object;
TAutoTypeText = class(TComponent)
private
FWait:Integer;
FText:string;
i:Integer;
Str:string;
DoErase:Boolean;
DoStop:Boolean;
Value: string;
CurrentW:Integer;
FList:TStringList;
FTimerNextPhrase: TTimer;
FTimerNextStep: TTimer;
FNextPhraseInterval: Cardinal;
FNextCharInteravl: Cardinal;
FOnTextChange: TOnTextChange;
FEditControl: TEdit;
FMemoControl: TMemo;
FLabelControl: TLabel;
procedure TimerNextPhraseTimer(Sender: TObject);
procedure TimerNextStepTimer(Sender: TObject);
procedure SetNextPhraseInterval(const Value: Cardinal);
procedure SetNextCharInteravl(const Value: Cardinal);
procedure AnimatePhrase;
procedure AnimateNextStep;
procedure SetOnTextChange(const Value: TOnTextChange);
procedure SetText(const Value: string);
procedure SetEditControl(const Value: TEdit);
procedure SetLabelControl(const Value: TLabel);
procedure SetMemoControl(const Value: TMemo);
procedure SetList(const Value: TStringList);
public
constructor Create(AOwner: TComponent); override;
procedure Start;
procedure Stop;
published
property NextPhraseInterval:Cardinal read FNextPhraseInterval write SetNextPhraseInterval default 2000;
property NextCharInteravl:Cardinal read FNextCharInteravl write SetNextCharInteravl default 70;
property OnTextChange:TOnTextChange read FOnTextChange write SetOnTextChange;
property Text:string read FText;
property LabelControl:TLabel read FLabelControl write SetLabelControl;
property EditControl:TEdit read FEditControl write SetEditControl;
property MemoControl:TMemo read FMemoControl write SetMemoControl;
property List:TStringList read FList write SetList;
end;
procedure Register;
implementation
uses Math;
{ TAutoTypeText }
procedure Register;
begin
RegisterComponents(PackageName, [TAutoTypeText]);
end;
constructor TAutoTypeText.Create(AOwner: TComponent);
begin
inherited;
FList:=TStringList.Create;
DoStop:=False;
FNextCharInteravl:=70;
FNextPhraseInterval:=2000;
FWait:=FNextCharInteravl;
FTimerNextPhrase:=TTimer.Create(nil);
FTimerNextPhrase.Enabled:=False;
FTimerNextPhrase.Interval:=FNextPhraseInterval;
FTimerNextPhrase.OnTimer:=TimerNextPhraseTimer;
FTimerNextStep:=TTimer.Create(nil);
FTimerNextStep.Enabled:=False;
FTimerNextStep.Interval:=70;
FTimerNextStep.OnTimer:=TimerNextStepTimer;
CurrentW:=-1;
end;
procedure TAutoTypeText.TimerNextPhraseTimer(Sender: TObject);
begin
FTimerNextPhrase.Enabled:=False;
Inc(CurrentW);
if CurrentW > FList.Count-1 then CurrentW:=0;
Value:=FList[CurrentW];
AnimatePhrase;
end;
procedure TAutoTypeText.TimerNextStepTimer(Sender: TObject);
begin
FTimerNextStep.Enabled:=False;
AnimateNextStep;
end;
procedure TAutoTypeText.SetEditControl(const Value: TEdit);
begin
FEditControl := Value;
end;
procedure TAutoTypeText.SetLabelControl(const Value: TLabel);
begin
FLabelControl := Value;
end;
procedure TAutoTypeText.SetList(const Value: TStringList);
begin
FList := Value;
end;
procedure TAutoTypeText.SetMemoControl(const Value: TMemo);
begin
FMemoControl := Value;
end;
procedure TAutoTypeText.SetNextCharInteravl(const Value: Cardinal);
begin
FNextCharInteravl := Value;
FWait:=Value;
end;
procedure TAutoTypeText.SetNextPhraseInterval(const Value: Cardinal);
begin
FNextPhraseInterval:=Value;
FTimerNextPhrase.Interval:=Value;
end;
procedure TAutoTypeText.SetOnTextChange(const Value: TOnTextChange);
begin
FOnTextChange := Value;
end;
procedure TAutoTypeText.SetText(const Value: string);
begin
FText:= Value;
if Assigned(FOnTextChange) then FOnTextChange(Self, FText);
if Assigned(FEditControl) then FEditControl.Text:=FText;
if Assigned(FLabelControl) then FLabelControl.Caption:=FText;
if Assigned(FMemoControl) then FMemoControl.Text:=FText;
end;
procedure TAutoTypeText.Start;
begin
DoStop:=False;
FTimerNextPhrase.Enabled:=True;
end;
procedure TAutoTypeText.Stop;
begin
DoStop:=true;
FTimerNextPhrase.Enabled:=False;
end;
procedure TAutoTypeText.AnimateNextStep;
var C:Char;
begin
if (i <= Value.Length) or DoErase then
begin
if DoErase then
begin
Delete(Str, Str.Length, 1);
DoErase:=False;
Dec(i);
end
else
begin
if Random(10) = 2 then
C:=Chr(RandomRange(97, 122))
else C:=Value[i];
DoErase:=C <> Value[i];
Str:=Str+C;
Inc(i);
end;
SetText(Str+'|');
FTimerNextStep.Interval:=FWait;
if (i > Value.Length) and (not DoErase) then
FTimerNextStep.Interval:=FWait * 12;
FTimerNextStep.Enabled:=True;
Exit;
end;
if Str.Length > 0 then
begin
Delete(Str, Str.Length, 1);
SetText(Str+'|');
FTimerNextStep.Interval:=FWait div 2;
FTimerNextStep.Enabled:=True;
Exit;
end;
if not DoStop then
FTimerNextPhrase.Enabled:=True;
end;
procedure TAutoTypeText.AnimatePhrase;
begin
Str:='';
DoErase:=False;
i:=1;
AnimateNextStep;
end;
end.
|
{-----------------------------------------------------------------------------
Unit Name: dataModSAFER
Author: J. L. Vasser (FMCSA)
Date: 2017-10-02
Purpose: Data Module for Data Pull.
Provides the bridge between the SAFER Oracle-based database and
the Firedbird-based Local Aspen / ISS database
History:
2018-02-05 JLV -
Removed "where MCMIS_STATUS = 'A'" clause from all child table SAFER
queries. Due to the time lag involved after creating the parent
table (CARRIERS), many records had become inactive. This then
caused the child record to not be found
2018-02-07 JLV -
Modifed query on UCR to limit the amount of (useless) data returned.
See frmMain.DoUCRLoad function
2018-02-20 JLV -
Removed unused data objects and related code.
2019-02-03 JLV -
Added a data module for using SQLite database for the local database.
This is much smaller and MUCH MUCH faster.
Then moved the Firebird database to its own data module to allow
keeping the database components the same.
-----------------------------------------------------------------------------}
unit dataModSAFER;
interface
uses
System.SysUtils, System.Classes, DALoader, UniLoader, Uni, Data.DB, MemDS,
DBAccess, InterBaseUniProvider, UniProvider, OracleUniProvider, UniScript,
CRBatchMove, DAScript, System.UITypes, Dialogs, Vcl.Forms, System.StrUtils,
VirtualTable;
type
TdmSAFER = class(TDataModule)
qryISS: TUniQuery;
qryCarrier: TUniQuery;
qryUCR: TUniQuery;
qryNAME: TUniQuery;
qryNAME2: TUniQuery;
qryHMPermit: TUniQuery;
qryINS: TUniQuery;
qryBASICS: TUniQuery;
qryNAMEUSDOTNUM: TStringField;
qryNAMENAME: TStringField;
qryNAMECITY: TStringField;
qryNAMESTATE: TStringField;
qryNAMENAME_TYPE_ID: TStringField;
dbSAFER: TUniConnection;
providerSAFER: TOracleUniProvider;
qryCensus: TUniQuery;
qryCensusCARRIER_ID_NUMBER: TWideStringField;
qryCensusUSDOTNUM: TWideStringField;
qryCensusSTATUS: TWideStringField;
qryCensusLAST_UPDATE_DATE: TDateTimeField;
qryCarrierUSDOTNUM: TWideStringField;
qryCarrierADDRESS: TWideStringField;
qryCarrierZIPCODE: TWideStringField;
qryCarrierPHONE: TWideStringField;
qryCarrierICC_NUM: TWideStringField;
qryCarrierINSPECTION_VALUE: TSmallintField;
qryCarrierINDICATOR: TWideStringField;
qryCarrierENTITY_TYPE: TWideStringField;
qryCarrierMCSIP_STATUS: TSmallintField;
qryCarrierTOTAL_VEHICLES: TFloatField;
qryCarrierTOTAL_DRIVERS: TFloatField;
qryCarrierCARRIER_OPERATION: TWideStringField;
qryCarrierCOUNTRY: TWideStringField;
qryCarrierNEW_ENTRANT_CODE: TWideStringField;
qryCarrierUNDELIVERABLE_PA: TWideStringField;
qryCarrierUNDELIVERABLE_MA: TWideStringField;
qryCarrierSTATUS: TWideStringField;
qryCarrierLAST_UPDATE_DATE: TDateTimeField;
qryCarrierHAS_POWER_UNITS: TWideStringField;
qryCarrierOOS_DATE: TWideStringField;
qryCarrierOOS_TEXT: TWideStringField;
qryCarrierOOS_REASON: TWideStringField;
qryCarrierOPER_AUTH_STATUS: TWideStringField;
qryCarrierPAD_USDOTNUM: TWideStringField;
qryNAME2USDOTNUM: TWideStringField;
qryNAME2NAME: TWideStringField;
qryNAME2CITY: TWideStringField;
qryNAME2STATE: TWideStringField;
qryNAME2NAME_TYPE_ID: TWideStringField;
qryISSUSDOTNUM: TStringField;
qryISSQUANTITY_INSPECTIONS_LAST30: TFloatField;
qryISSVEHICLE_INSPECTIONS_LAST30: TFloatField;
qryISSDRIVER_INSPECTIONS_LAST30: TFloatField;
qryISSQUANTITY_HAZMAT_PRESENT_LAST30: TFloatField;
qryISSOOS_ALL_TYPES_LAST30: TFloatField;
qryISSOOS_VEHICLE_INSPECTIONS_LAST30: TFloatField;
qryISSOOS_DRIVER_INSPECTIONS_LAST30: TFloatField;
qryISSSAFETY_RATING: TWideStringField;
qryISSRATING_DATE: TDateTimeField;
qryISSVIOLATION_BRAKES: TFloatField;
qryISSVIOLATION_WHEELS: TFloatField;
qryISSVIOLATION_STEERING: TFloatField;
qryISSVIOLATION_MEDICAL_CERTIFICATE: TFloatField;
qryISSVIOLATION_LOGS: TFloatField;
qryISSVIOLATION_HOURS: TFloatField;
qryISSVIOLATION_LICENSE: TFloatField;
qryISSVIOLATION_DRUGS: TFloatField;
qryISSVIOLATION_TRAFFIC: TFloatField;
qryISSVIOLATION_PAPERS: TFloatField;
qryISSVIOLATION_PLACARDS: TFloatField;
qryISSVIOLATION_OP_EMER_RESP: TFloatField;
qryISSVIOLATION_TANK: TFloatField;
qryISSVIOLATION_OTHER: TFloatField;
qryISSVEHICLE_OOS_RATE: TFloatField;
qryISSDRIVER_OOS_RATE: TFloatField;
qryISSVEHICLE_OOS_PERCENT: TFloatField;
qryISSDRIVER_OOS_PERCENT: TFloatField;
qryISSBRAKES_RATE: TFloatField;
qryISSWHEEL_RATE: TFloatField;
qryISSSTEER_RATE: TFloatField;
qryISSMEDICAL_RATE: TFloatField;
qryISSLOGS_RATE: TFloatField;
qryISSHOURS_RATE: TFloatField;
qryISSDQ_RATE: TFloatField;
qryISSDRUGS_RATE: TFloatField;
qryISSTRAFFIC_RATE: TFloatField;
qryISSHM_PAPER_RATE: TFloatField;
qryISSHM_PLAC_RATE: TFloatField;
qryISSHM_OPER_RATE: TFloatField;
qryISSHM_TANK_RATE: TFloatField;
qryISSHM_OTHR_RATE: TFloatField;
qryHMPermitUSDOTNUM: TWideStringField;
qryHMPermitHM_PERMIT_TYPE: TWideStringField;
qryHMPermitHM_PERMIT_STATUS: TWideStringField;
qryHMPermitHM_PERMIT_EFFECTIVE_DATE: TDateTimeField;
qryHMPermitHM_PERMIT_EXPIRATION_DATE: TDateTimeField;
qryHMPermitOPERATING_UNDER_APPEAL_FLAG: TWideStringField;
qryINSUSDOTNUM: TWideStringField;
qryINSLIABILITY_STATUS: TWideStringField;
qryINSLIABILITY_REQUIRED: TLargeintField;
qryINSCARGO_STATUS: TWideStringField;
qryINSBOND_STATUS: TWideStringField;
qryINSMEX_TERRITORY: TWideStringField;
qryBASICSUSDOTNUM: TWideStringField;
qryBASICSBASIC: TFloatField;
qryBASICSBASICPERCENTILE: TFloatField;
qryBASICSBASICSDEFIND: TWideStringField;
qryBASICSBASICSRUNDATE: TDateTimeField;
qryBASICSINVESTIGATIONDATE: TDateTimeField;
qryBASICSROAD_DISPLAY_TEXT: TWideStringField;
qryBASICSINVEST_DISPLAY_TEXT: TWideStringField;
qryBASICSOVERALL_DISPLAY_TEXT: TWideStringField;
qryUCRUSDOTNUM: TWideStringField;
qryUCRBASE_STATE: TWideStringField;
qryUCRPAYMENT_FLAG: TWideStringField;
qryUCRREGISTRATION_YEAR: TWideStringField;
qryUCRPAYMENT_DATE: TDateTimeField;
qryUCRINTRASTATE_VEHICLES: TWideStringField;
//procedure tblCarriersCalcFields(DataSet: TDataSet);
//procedure tblUCRCalcFields(DataSet: TDataSet);
//procedure tblISSCalcFields(DataSet: TDataSet);
//procedure tblUpdateStatusCalcFields(DataSet: TDataSet);
private
{ Private declarations }
public
{ Public declarations }
//function GetCountryDesc(const CountryCode: string): string;
//function RebuildIdx: Boolean;
end;
var
dmSAFER: TdmSAFER;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
uses formMain;
{$R *.dfm}
{
procedure TdmPull.tblCarriersCalcFields(DataSet: TDataSet);
begin
TblCarriersCountryCalc.AsString := GetCountryDesc(tblCarriers.FieldByName('COUNTRY').AsString);
end;
procedure TdmPull.tblISSCalcFields(DataSet: TDataSet);
begin
if (qryIss.FieldByName('VEHICLE_INSPECTIONS_LAST30').AsInteger = 0) then
tblIssVehicleOOSRate.AsInteger := qryIss.FieldByName('OOS_VEHICLE_INSPECTIONS_LAST30').AsInteger
else
tblIssVehicleOOSRate.AsFloat := qryIss.FieldByName('OOS_VEHICLE_INSPECTIONS_LAST30').AsInteger / qryIss.FieldByName('VEHICLE_INSPECTIONS_LAST30').AsInteger;
if (tblIss.FieldByName('DRIVER_INSPECTIONS').AsInteger = 0) then
tblIssDriverOOSRate.Value := tblIss.FieldByName('OOS_DRIVER').AsFloat
else
tblIssDriverOOSRate.Value := tblIss.FieldByName('OOS_DRIVER').AsFloat / tblIss.FieldByName('DRIVER_INSPECTIONS').AsFloat;
tblIssVehicleOOSPercent.Value := tblIssVehicleOOSRate.AsFloat * 100;
tblIssDriverOOSPercent.Value := tblIssDriverOOSRate.AsFLoat * 100;
if (tblCarriers.FieldByName('TOTAL_VEHICLES').AsInteger = 0) then
tblIssInspPerVehicle.Value := tblIss.FieldByName('VEHICLE_INSPECTIONS').AsFloat
else
tblIssInspPerVehicle.Value := tblIss.FieldByName('VEHICLE_INSPECTIONS').AsFloat / tblCarriers.FieldByName('TOTAL_VEHICLES').AsFloat;
if (tblCarriers.FieldByName('TOTAL_DRIVERS').AsInteger = 0) then
tblIssInspPerDriver.Value := tblIss.FieldByName('DRIVER_INSPECTIONS').AsFloat
else
tblIssInspPerDriver.Value := tblIss.FieldByName('DRIVER_INSPECTIONS').AsFloat / tblCarriers.FieldByName('TOTAL_DRIVERS').AsFloat;
if (tblIss.FieldByName('VEHICLE_INSPECTIONS').AsInteger = 0) then begin
tblISSv1BrakesRate.AsFloat := tblIss.FieldByName('VIOL_BRAKES').AsFloat;
tblIssv1WheelRate.AsFloat := tblIss.FieldByName('VIOL_WHEELS').AsFloat;
tblIssv1SteerRate.AsFloat := tblIss.FieldByName('Viol_STEERING').AsFloat;
end
else begin
tblISSv1BrakesRate.AsFloat := tblIss.FieldByName('VIOL_BRAKES').AsFloat / tblIss.FieldByName('VEHICLE_INSPECTIONS').AsInteger;
tblIssv1WheelRate.AsFloat := tblIss.FieldByName('VIOL_WHEELS').AsFloat / tblIss.FieldByName('VEHICLE_INSPECTIONS').AsInteger;
tblIssv1SteerRate.AsFloat := tblIss.FieldByName('VIOL_STEERING').AsFloat / tblIss.FieldByName('VEHICLE_INSPECTIONS').AsInteger;
end;
if (tblIss.FieldByName('DRIVER_INSPECTIONS').AsInteger = 0) then begin
tblIssv1MedicalRate.AsFloat := tblIss.FieldByName('VIOL_MEDICAL').AsFloat;
tblIssv1LogsRate.AsFloat := tblIss.FieldByName('VIOL_LOGS').AsFloat;
tblIssv1HoursRate.AsFloat := tblIss.FieldByName('VIOL_HOURS').AsFloat;
tblIssv1DQRate.AsFloat := tblIss.FieldByName('VIOL_DISQUAL').AsFloat;
tblIssv1DrugsRate.AsFloat := tblIss.FieldByName('VIOL_DRUGS').AsFloat;
tblIssv1TrafficRate.AsFloat := tblIss.FieldByName('VIOL_TRAFFIC').AsFloat;
end
else begin
tblIssv1MedicalRate.AsFloat := tblIss.FieldByName('VIOL_MEDICAL').AsFloat / tblIss.FieldByName('DRIVER_INSPECTIONS').AsInteger;
tblIssv1LogsRate.AsFloat := tblIss.FieldByName('VIOL_LOGS').AsFloat / tblIss.FieldByName('DRIVER_INSPECTIONS').AsInteger;
tblIssv1HoursRate.AsFloat := tblIss.FieldByName('VIOL_HOURS').AsFloat / tblIss.FieldByName('DRIVER_INSPECTIONS').AsInteger;
tblIssv1DQRate.AsFloat := tblIss.FieldByName('VIOL_DISQUAL').AsFloat / tblIss.FieldByName('DRIVER_INSPECTIONS').AsInteger;
tblIssv1DrugsRate.AsFloat := tblIss.FieldByName('VIOL_DRUGS').AsFloat / tblIss.FieldByName('DRIVER_INSPECTIONS').AsInteger;
tblIssv1TrafficRate.AsFloat := tblIss.FieldByName('VIOL_TRAFFIC').AsFloat / tblIss.FieldByName('DRIVER_INSPECTIONS').AsInteger;
end;
if (tblIss.FieldByName('HAZMAT_INSPECTIONS').AsInteger = 0) then begin
tblIssv1HMPaperRate.asFloat := tblIss.FieldByName('VIOL_HMPAPER').AsFloat;
tblIssv1HMPlacRate.AsFloat := tblIss.FieldByName('VIOL_HMPLAC').AsFloat;
tblIssv1HMOperRate.AsFloat := tblIss.FieldByName('VIOL_HMOPER').AsFloat;
tblIssv1HMTankRate.AsFloat := tblIss.FieldByName('VIOL_HMTANK').AsFloat;
tblIssv1HMOthrRate.AsFloat := tblIss.FieldByName('VIOL_HMOTHR').AsFloat;
end
else begin
tblIssv1HMPaperRate.AsFloat := tblIss.FieldByName('VIOL_HMPAPER').AsFloat / tblIss.FieldByName('HAZMAT_INSPECTIONS').AsInteger;
tblIssv1HMPlacRate.AsFloat := tblIss.FieldByName('VIOL_HMPLAC').AsFloat / tblIss.FieldByName('HAZMAT_INSPECTIONS').AsInteger;
tblIssv1HMOperRate.AsFloat := tblIss.FieldByName('VIOL_HMOPER').AsFloat / tblIss.FieldByName('HAZMAT_INSPECTIONS').AsInteger;
tblIssv1HMTankRate.AsFloat := tblIss.FieldByName('VIOL_HMTANK').AsFloat / tblIss.FieldByName('HAZMAT_INSPECTIONS').AsInteger;
tblIssv1HMOthrRate.AsFloat := tblIss.FieldByName('VIOL_HMOTHR').AsFloat / tblIss.FieldByName('HAZMAT_INSPECTIONS').AsInteger;
end;
end;
procedure TdmPull.tblUCRCalcFields(DataSet: TDataSet);
begin
if tblUCR.FieldByName('PAYMENT_FLAG').AsString = 'Y' then
tblUCRPAY_FLAG_TEXT.AsString := 'YES'
else if tblUCR.FieldByName('PAYMENT_FLAG').AsString = 'N' then
tblUCRPAY_FLAG_TEXT.AsString := 'NO';
if tblUCR.FieldByName('INTRASTATE_VEHICLES').AsString = 'Y' then
tblUCRINTRA_VEH_TEXT.AsString := 'YES'
else if tblUCR.FieldByName('INTRASTATE_VEHICLES').AsString = 'N' then
tblUCRINTRA_VEH_TEXT.AsString := 'NO';
end;
}
(*
{-----------------------------------------------------------------------------
Function: GetCountryDesc
Author: J. L. Vasser, FMCSA
Date: 2017-08-05
Arguments: const CountryCode: string
Return: string
Comments: Translates SAFER's strange country codes to the country name
-----------------------------------------------------------------------------}
function TdmPull.GetCountryDesc(const CountryCode: string): string;
begin
case IndexStr('CountryCode',['A','C','M','P','S']) of
0 : Result := 'UNITED STATES';
1 : Result := 'CANADA';
2 : Result := 'MEXICO';
3 : Result := 'UNITED STATES'; // Puerto Rico // Don't know why its separate
4 : Result := 'Central America';
else
Result := CountryCode;
end;
end;
procedure TdmPull.tblUpdateStatusCalcFields(DataSet: TDataSet);
begin
case tblUpdateStatus.FieldByName('UpdtStatus').asInteger of
0 : tblUpdateStatus.FieldByName('StatusDesc').AsString := 'Not Begun';
1 : tblUpdateStatus.FieldByName('StatusDesc').AsString := 'Pending';
2 : tblUpdateStatus.FieldByName('StatusDesc').AsString := 'Complete';
end;
end;
function TdmPull.RebuildIdx: Boolean;
begin
Result := False;
try
Result := True;
except on E: Exception do
ShowMessage('Reactivating and rebuilding Indexes Failed:'+#13#10+E.Message);
end;
end;
*)
end.
|
unit Audio;
interface
uses Bass;
type
TAudio = class(TObject)
private
CC: Integer;
FCount: Integer;
Channel: array[0..1023] of HSTREAM;
FVolume: ShortInt;
procedure SetVolume(Value: ShortInt);
public
constructor Create;
destructor Destroy; override;
property Volume: ShortInt read FVolume write SetVolume;
procedure Add(FileName: string; IsLoop: Boolean = False);
procedure Remove(I: Integer);
procedure Play(I: Integer = 0);
procedure Restart(I: Integer);
procedure Stop(I: Integer); overload;
procedure Stop; overload;
procedure Pause;
procedure Resume;
function Count: Integer;
end;
implementation
{ TAudio }
procedure TAudio.Add(FileName: string; IsLoop: Boolean = False);
var
I: Byte;
begin
if IsLoop then I := BASS_SAMPLE_LOOP else I := 0;
Channel[FCount] := BASS_StreamCreateFile(False, PChar(FileName), 0, 0, I);
if Channel[FCount] <> 0 then Inc(FCount);
end;
function TAudio.Count: Integer;
begin
Result := FCount
end;
constructor TAudio.Create;
begin
CC := 0;
FCount := 0;
Volume := 100;
BASS_Init(-1, 44100, BASS_DEVICE_3D, 0, nil);
end;
destructor TAudio.Destroy;
var
I: Integer;
begin
if (Count > 0) then
for I := 0 to Count - 1 do
BASS_StreamFree(Channel[I]);
inherited;
end;
procedure TAudio.Pause;
begin
BASS_Pause();
end;
procedure TAudio.Play(I: Integer);
begin
if (I >= 0) then
begin
BASS_ChannelSetAttribute(Channel[I], BASS_ATTRIB_VOL, Volume / 100);
BASS_ChannelPlay(Channel[I], False);
CC := I;
end;
end;
procedure TAudio.Remove(I: Integer);
var
A: Integer;
begin
if (I >= 0) then
begin
BASS_StreamFree(Channel[I]);
if (I < Count) then
for A := I to Count - 1 do
Channel[A] := Channel[A + 1];
Dec(FCount);
end;
end;
procedure TAudio.Restart(I: Integer);
begin
if (I >= 0) then
begin
BASS_ChannelSetAttribute(Channel[I], BASS_ATTRIB_VOL, Volume / 100);
BASS_ChannelPlay(Channel[I], True);
CC := I;
end;
end;
procedure TAudio.Resume;
begin
BASS_Start();
end;
procedure TAudio.SetVolume(Value: ShortInt);
begin
if (Value > 100) then Value := 100;
if (Value < 0) then Value := 0;
FVolume := Value;
Play(CC);
end;
procedure TAudio.Stop(I: Integer);
begin
if (I >= 0) then BASS_ChannelStop(Channel[I]);
end;
procedure TAudio.Stop;
var
I: Integer;
begin
for I := 0 to Count - 1 do Stop(I);
end;
end.
|
unit bsListTreeData;
{* - }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Business\List\bsListTreeData.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TbsListTreeData" MUID: (47F4D3AC0029)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If NOT Defined(Admin) AND NOT Defined(Monitorings)}
uses
l3IntfUses
, l3SimpleObject
, bsInterfaces
, DynamicDocListUnit
, DynamicTreeUnit
, l3TreeInterfaces
;
type
TbsListTreeData = class(Tl3SimpleObject, IbsListTreeData)
{* - }
private
f_List: IDynList;
f_Root: INodeBase;
f_Nodes: INodesClipboard;
f_Node: Il3SimpleNode;
protected
function pm_GetList: IDynList;
function pm_GetRoot: INodeBase;
function pm_GetNodes: INodesClipboard;
function pm_GetNode: Il3SimpleNode;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create(const aList: IDynList;
const aRoot: INodeBase;
const aNode: Il3SimpleNode); reintroduce;
class function Make(const aList: IDynList;
const aRoot: INodeBase;
const aNode: Il3SimpleNode): IbsListTreeData; reintroduce;
end;//TbsListTreeData
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings)
implementation
{$If NOT Defined(Admin) AND NOT Defined(Monitorings)}
uses
l3ImplUses
//#UC START# *47F4D3AC0029impl_uses*
//#UC END# *47F4D3AC0029impl_uses*
;
constructor TbsListTreeData.Create(const aList: IDynList;
const aRoot: INodeBase;
const aNode: Il3SimpleNode);
//#UC START# *48F87C29002F_47F4D3AC0029_var*
//#UC END# *48F87C29002F_47F4D3AC0029_var*
begin
//#UC START# *48F87C29002F_47F4D3AC0029_impl*
inherited Create;
f_List := aList;
f_Root := aRoot;
f_Root.CopyNodes(FM_SELECTION, f_Nodes);
f_Node := aNode;
//#UC END# *48F87C29002F_47F4D3AC0029_impl*
end;//TbsListTreeData.Create
class function TbsListTreeData.Make(const aList: IDynList;
const aRoot: INodeBase;
const aNode: Il3SimpleNode): IbsListTreeData;
var
l_Inst : TbsListTreeData;
begin
l_Inst := Create(aList, aRoot, aNode);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//TbsListTreeData.Make
function TbsListTreeData.pm_GetList: IDynList;
//#UC START# *48F876A900AF_47F4D3AC0029get_var*
//#UC END# *48F876A900AF_47F4D3AC0029get_var*
begin
//#UC START# *48F876A900AF_47F4D3AC0029get_impl*
Result := f_List;
//#UC END# *48F876A900AF_47F4D3AC0029get_impl*
end;//TbsListTreeData.pm_GetList
function TbsListTreeData.pm_GetRoot: INodeBase;
//#UC START# *48F876C701BD_47F4D3AC0029get_var*
//#UC END# *48F876C701BD_47F4D3AC0029get_var*
begin
//#UC START# *48F876C701BD_47F4D3AC0029get_impl*
Result := f_Root;
//#UC END# *48F876C701BD_47F4D3AC0029get_impl*
end;//TbsListTreeData.pm_GetRoot
function TbsListTreeData.pm_GetNodes: INodesClipboard;
//#UC START# *48F876DA0247_47F4D3AC0029get_var*
//#UC END# *48F876DA0247_47F4D3AC0029get_var*
begin
//#UC START# *48F876DA0247_47F4D3AC0029get_impl*
Result := f_Nodes;
//#UC END# *48F876DA0247_47F4D3AC0029get_impl*
end;//TbsListTreeData.pm_GetNodes
function TbsListTreeData.pm_GetNode: Il3SimpleNode;
//#UC START# *48F876F10193_47F4D3AC0029get_var*
//#UC END# *48F876F10193_47F4D3AC0029get_var*
begin
//#UC START# *48F876F10193_47F4D3AC0029get_impl*
Result := f_Node;
//#UC END# *48F876F10193_47F4D3AC0029get_impl*
end;//TbsListTreeData.pm_GetNode
procedure TbsListTreeData.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_47F4D3AC0029_var*
//#UC END# *479731C50290_47F4D3AC0029_var*
begin
//#UC START# *479731C50290_47F4D3AC0029_impl*
f_Nodes := nil;
f_Root := nil;
f_List := nil;
inherited;
//#UC END# *479731C50290_47F4D3AC0029_impl*
end;//TbsListTreeData.Cleanup
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings)
end.
|
unit fpvv_drawer;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Controls, Graphics, LCLType;
type
{ TFPVVDrawer }
TFPVVDrawer = class(TCustomControl)
private
DragDropStarted: Boolean;
DragStartPos: TPoint;
public
PosX, PosY: Integer;
Drawing: TBitmap;
RedrawCallback: TNotifyEvent;
PosChangedCallback: TNotifyEvent;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure EraseBackground(DC: HDC); override;
procedure Paint; override;
procedure HandleKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure HandleClick(Sender: TObject);
procedure HandleMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure HandleMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure Clear;
public
property OnDblClick;
property OnTripleClick;
property OnQuadClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseWheel;
property OnMouseWheelDown;
property OnMouseWheelUp;
end;
implementation
{ TFPVVDrawer }
constructor TFPVVDrawer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Drawing := TBitmap.Create;
OnKeyDown := @HandleKeyDown;
OnClick := @HandleClick;
OnMouseDown := @HandleMouseDown;
OnMouseUp := @HandleMouseUp;
end;
destructor TFPVVDrawer.Destroy;
begin
Drawing.Free;
inherited Destroy;
end;
procedure TFPVVDrawer.EraseBackground(DC: HDC);
begin
end;
procedure TFPVVDrawer.Paint;
begin
Canvas.Brush.Color := clWhite;
Canvas.Brush.Style := bsSolid;
Canvas.FillRect(Self.ClientRect);
Canvas.Draw(0, 0, Drawing); // (PosX, PosY,..
// inherited Paint;
end;
procedure TFPVVDrawer.HandleKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_UP: Inc(PosY, 5);
VK_DOWN: Dec(PosY, 5);
VK_LEFT: Inc(PosX, 5);
VK_RIGHT: Dec(PosX, 5);
else
Exit;
end;
if Assigned(PosChangedCallback) then PosChangedCallback(Self);
if Assigned(RedrawCallback) then RedrawCallback(Self);
Invalidate();
end;
procedure TFPVVDrawer.HandleClick(Sender: TObject);
begin
Self.SetFocus();
end;
procedure TFPVVDrawer.HandleMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if not DragDropStarted then
begin
DragDropStarted := True;
DragStartPos := Point(X, Y);
end;
end;
procedure TFPVVDrawer.HandleMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if DragDropStarted then
begin
DragDropStarted := False;
PosX := PosX + (X - DragStartPos.X);
PosY := PosY + (Y - DragStartPos.Y);
if Assigned(PosChangedCallback) then PosChangedCallback(Self);
if Assigned(RedrawCallback) then RedrawCallback(Self);
Invalidate();
end;
end;
procedure TFPVVDrawer.Clear;
begin
PosX := 0;
PosY := 0;
if Assigned(PosChangedCallback) then PosChangedCallback(Self);
end;
end.
|
unit ViewModels;
{$mode objfpc}{$H+}
interface
uses
MvvmClasses, DomainInterfaces;
type
TTestViewModel = class(TViewModel, ITest)
private
FStringValue : string;
function GetStringValue() : string;
procedure SetStringValue(const Value: string);
public
property StringValue : string read GetStringValue write SetStringValue;
function GetProperty(const PropertyName: string) : string; override;
end;
implementation
{ TTestViewModel }
function TTestViewModel.GetProperty(const PropertyName: string) : string;
begin
if (PropertyName = 'StringValue') then
Result := StringValue
else
Result := inherited GetProperty(PropertyName);
end;
function TTestViewModel.GetStringValue() : string;
begin
Result := FStringValue;
end;
procedure TTestViewModel.SetStringValue(const Value: string);
begin
FStringValue := Value;
PropertyChanged('StringValue');
end;
end.
|
unit clStatus;
interface
uses clConexao;
type
TStatus = class(TObject)
private
function getBaixa: String;
function getCodigo: Integer;
function getDescricao: String;
function getPercentual: Double;
procedure setBaixa(const Value: String);
procedure setCodigo(const Value: Integer);
procedure setDescricao(const Value: String);
procedure setPercentual(const Value: Double);
constructor Create;
destructor Destroy;
protected
_codigo: Integer;
_descricao: String;
_percentual: Double;
_baixa: String;
_conexao: TConexao;
public
property Codigo: Integer read getCodigo write setCodigo;
property Descricao: String read getDescricao write setDescricao;
property Percentual: Double read getPercentual write setPercentual;
property Baixa: String read getBaixa write setBaixa;
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 = 'TBSTATUSENTREGA';
implementation
uses SysUtils, Dialogs, udm, clUtil, ZDataset, ZAbstractRODataset, DB;
{ TStatus }
constructor TStatus.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 TStatus.Destroy;
begin
_conexao.Free;
end;
function TStatus.getBaixa: String;
begin
Result := _baixa;
end;
function TStatus.getCodigo: Integer;
begin
Result := _codigo;
end;
function TStatus.getDescricao: String;
begin
Result := _descricao;
end;
function TStatus.getPercentual: Double;
begin
Result := _percentual;
end;
function TStatus.Validar(): Boolean;
begin
try
Result := False;
if Self.Codigo = 0 then
begin
MessageDlg('Informe o código do Status!', mtWarning, [mbOK], 0);
Exit;
end;
if TUtil.Empty(Self.Descricao) then
begin
MessageDlg('Informe a Descrição do Status!', mtWarning, [mbOK], 0);
Exit;
end;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TStatus.Delete(filtro: String): Boolean;
begin
try
Result := False;
with dm.QryCRUD do
begin
Close;
SQL.Clear;
SQL.Add('DELETE FROM ' + TABLENAME);
if filtro = 'CODIGO' then
begin
SQL.Add('WHERE COD_STATUS = :CODIGO');
ParamByName('CODIGO').AsInteger := Self.Codigo;
end
else if filtro = 'DESCRICAO' then
begin
SQL.Add('WHERE DES_STATUS = :DESCRICAO');
ParamByName('DESCRICAO').AsString := Self.Descricao;
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 TStatus.getObject(id, filtro: String): Boolean;
begin
try
Result := False;
if TUtil.Empty(id) then
Exit;
with dm.QryGetObject do
begin
Close;
SQL.Clear;
SQL.Add('SELECT * FROM ' + TABLENAME);
if filtro = 'CODIGO' then
begin
SQL.Add('WHERE COD_STATUS = :CODIGO');
ParamByName('CODIGO').AsInteger := StrToInt(id);
end
else if filtro = 'ENTREGADOR' then
begin
SQL.Add('WHERE DES_STATUS = :DESCRICAO');
ParamByName('DESCRICAO').AsString := 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_STATUS').AsInteger;
Self.Descricao := dm.QryGetObject.FieldByName('DES_STATUS').AsString;
Self.Percentual := dm.QryGetObject.FieldByName
('VAL_PERCENTUAL_VERBA').AsFloat;
Self.Baixa := dm.QryGetObject.FieldByName('DOM_BAIXA').AsString;
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 TStatus.Insert(): Boolean;
begin
try
Result := False;
with dm.QryCRUD do
begin
Close;
SQL.Clear;
SQL.Text := 'INSERT INTO ' + TABLENAME + '(' + 'COD_STATUS, ' +
'DES_STATUS, ' + 'VAL_PERCENTUAL_VERBA, ' + 'DOM_BAIXA) ' + 'VALUES (' +
':CODIGO, ' + ':DESCRICAO, ' + ':PERCENTUAL, ' + ':BAIXA)';
ParamByName('CODIGO').AsInteger := Self.Codigo;
ParamByName('DESCRICAO').AsString := Self.Descricao;
ParamByName('PERCENTUAL').AsFloat := Self.Percentual;
ParamByName('BAIXA').AsString := Self.Baixa;
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 TStatus.Update(): Boolean;
begin
try
Result := False;
with dm.QryCRUD do
begin
Close;
SQL.Clear;
SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' + 'DES_STATUS = :DESCRICAO, '
+ 'VAL_PERCENTUAL_VERBA = :PERCENTUAL, ' + 'DOM_BAIXA = :BAIXA ' +
'WHERE ' + 'COD_STATUS = :CODIGO';
ParamByName('CODIGO').AsInteger := Self.Codigo;
ParamByName('DESCRICAO').AsString := Self.Descricao;
ParamByName('PERCENTUAL').AsFloat := Self.Percentual;
ParamByName('BAIXA').AsString := Self.Baixa;
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 TStatus.getField(campo, coluna: String): String;
begin
try
Result := '';
with dm.QryGetObject do
begin
Close;
SQL.Clear;
SQL.Text := 'SELECT ' + campo + ' FROM ' + TABLENAME;
if coluna = 'CODIGO' then
begin
SQL.Add(' WHERE COD_STATUS =:CODIGO ');
ParamByName('CODIGO').AsInteger := Self.Codigo;
end
else if coluna = 'DESCRICAO' then
begin
SQL.Add(' WHERE DES_STATUS = :DESCRICAO ');
ParamByName('DESCRICAO').AsString := Self.Descricao;
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 TStatus.setBaixa(const Value: String);
begin
_baixa := Value;
end;
procedure TStatus.setCodigo(const Value: Integer);
begin
_codigo := Value;
end;
procedure TStatus.setDescricao(const Value: String);
begin
_descricao := Value;
end;
procedure TStatus.setPercentual(const Value: Double);
begin
_percentual := Value;
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2022 Kike Pérez
Unit : Quick.IoC
Description : IoC Dependency Injector
Author : Kike Pérez
Version : 1.0
Created : 19/10/2019
Modified : 19/01/2022
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.IoC;
{$i QuickLib.inc}
interface
uses
System.SysUtils,
RTTI,
{$IFDEF DEBUG_IOC}
Quick.Debug.Utils,
{$ENDIF}
System.TypInfo,
System.Generics.Collections,
Quick.Logger.Intf,
Quick.Options;
type
TActivatorDelegate<T> = reference to function: T;
TIocRegistration = class
type
TRegisterMode = (rmTransient, rmSingleton, rmScoped);
private
fName : string;
fRegisterMode : TRegisterMode;
fIntfInfo : PTypeInfo;
fImplementation : TClass;
fActivatorDelegate : TActivatorDelegate<TValue>;
public
constructor Create(const aName : string);
property Name : string read fName;
property IntfInfo : PTypeInfo read fIntfInfo write fIntfInfo;
property &Implementation : TClass read fImplementation write fImplementation;
function IsSingleton : Boolean;
function IsTransient : Boolean;
function IsScoped : Boolean;
function AsSingleton : TIocRegistration;
function AsTransient : TIocRegistration;
function AsScoped : TIocRegistration;
property ActivatorDelegate : TActivatorDelegate<TValue> read fActivatorDelegate write fActivatorDelegate;
end;
TIocRegistrationInterface = class(TIocRegistration)
private
fInstance : IInterface;
public
property Instance : IInterface read fInstance write fInstance;
end;
TIocRegistrationInstance = class(TIocRegistration)
private
fInstance : TObject;
public
property Instance : TObject read fInstance write fInstance;
end;
TIocRegistration<T> = record
private
fRegistration : TIocRegistration;
public
constructor Create(aRegistration : TIocRegistration);
function AsSingleton : TIocRegistration<T>;
function AsTransient : TIocRegistration<T>;
function AsScoped : TIocRegistration<T>;
function DelegateTo(aDelegate : TActivatorDelegate<T>) : TIocRegistration<T>;
end;
IIocRegistrator = interface
['{F3B79B15-2874-4B66-9B7F-06E2EBFED1AE}']
function GetKey(aPInfo : PTypeInfo; const aName : string = ''): string;
function RegisterType(aTypeInfo : PTypeInfo; aImplementation : TClass; const aName : string = '') : TIocRegistration;
function RegisterInstance(aTypeInfo : PTypeInfo; const aName : string = '') : TIocRegistration;
end;
TIocRegistrator = class(TInterfacedObject,IIocRegistrator)
private
fDependencies : TDictionary<string,TIocRegistration>;
fDependencyOrder : TList<TIocRegistration>;
public
constructor Create;
destructor Destroy; override;
property Dependencies : TDictionary<string,TIocRegistration> read fDependencies write fDependencies;
property DependencyOrder : TList<TIocRegistration> read fDependencyOrder;
function IsRegistered<TInterface: IInterface; TImplementation: class>(const aName : string = '') : Boolean; overload;
function IsRegistered<T>(const aName : string = '') : Boolean; overload;
function GetKey(aPInfo : PTypeInfo; const aName : string = ''): string;
function RegisterType<TInterface: IInterface; TImplementation: class>(const aName : string = '') : TIocRegistration<TImplementation>; overload;
function RegisterType(aTypeInfo : PTypeInfo; aImplementation : TClass; const aName : string = '') : TIocRegistration; overload;
function RegisterInstance(aTypeInfo : PTypeInfo; const aName : string = '') : TIocRegistration; overload;
function RegisterInstance<T : class>(const aName : string = '') : TIocRegistration<T>; overload;
function RegisterInstance<TInterface : IInterface>(aInstance : TInterface; const aName : string = '') : TIocRegistration; overload;
function RegisterOptions<T : TOptions>(aOptions : T) : TIocRegistration<T>;
end;
IIocContainer = interface
['{6A486E3C-C5E8-4BE5-8382-7B9BCCFC1BC3}']
function RegisterType(aInterface: PTypeInfo; aImplementation : TClass; const aName : string = '') : TIocRegistration;
function RegisterInstance(aTypeInfo : PTypeInfo; const aName : string = '') : TIocRegistration;
function Resolve(aServiceType: PTypeInfo; const aName : string = ''): TValue;
procedure Build;
end;
IIocInjector = interface
['{F78E6BBC-2A95-41C9-B231-D05A586B4B49}']
end;
TIocInjector = class(TInterfacedObject,IIocInjector)
end;
IIocResolver = interface
['{B7C07604-B862-46B2-BF33-FF941BBE53CA}']
function Resolve(aServiceType: PTypeInfo; const aName : string = ''): TValue; overload;
end;
TIocResolver = class(TInterfacedObject,IIocResolver)
private
fRegistrator : TIocRegistrator;
fInjector : TIocInjector;
function CreateInstance(aClass : TClass) : TValue;
public
constructor Create(aRegistrator : TIocRegistrator; aInjector : TIocInjector);
function Resolve<T>(const aName : string = ''): T; overload;
function Resolve(aServiceType: PTypeInfo; const aName : string = ''): TValue; overload;
function ResolveAll<T>(const aName : string = '') : TList<T>;
end;
TTypedFactory<T : class, constructor> = class(TVirtualInterface)
private
fResolver : TIocResolver;
public
constructor Create(PIID: PTypeInfo; aResolver : TIocResolver);
procedure DoInvoke(Method: TRttiMethod; const Args: TArray<TValue>; out Result: TValue);
end;
IFactory<T> = interface
['{92D7AB4F-4C0A-4069-A821-B057E193DE65}']
function New : T;
end;
TSimpleFactory<T : class, constructor> = class(TInterfacedObject,IFactory<T>)
private
fResolver : TIocResolver;
public
constructor Create(aResolver : TIocResolver);
function New : T;
end;
TSimpleFactory<TInterface : IInterface; TImplementation : class, constructor> = class(TInterfacedObject,IFactory<TInterface>)
private
fResolver : TIocResolver;
public
constructor Create(aResolver : TIocResolver);
function New : TInterface;
end;
TIocContainer = class(TInterfacedObject,IIocContainer)
private
fRegistrator : TIocRegistrator;
fResolver : TIocResolver;
fInjector : TIocInjector;
fLogger : ILogger;
class var
GlobalInstance: TIocContainer;
protected
class constructor Create;
class destructor Destroy;
public
constructor Create;
destructor Destroy; override;
function IsRegistered<TInterface: IInterface; TImplementation: class>(const aName: string): Boolean; overload;
function IsRegistered<TInterface : IInterface>(const aName: string): Boolean; overload;
function RegisterType<TInterface: IInterface; TImplementation: class>(const aName : string = '') : TIocRegistration<TImplementation>; overload;
function RegisterType(aInterface: PTypeInfo; aImplementation : TClass; const aName : string = '') : TIocRegistration; overload;
function RegisterInstance<T : class>(const aName: string = ''): TIocRegistration<T>; overload;
function RegisterInstance(aTypeInfo : PTypeInfo; const aName : string = '') : TIocRegistration; overload;
function RegisterInstance<TInterface : IInterface>(aInstance : TInterface; const aName : string = '') : TIocRegistration; overload;
function RegisterOptions<T : TOptions>(aOptions : TOptions) : TIocRegistration<T>; overload;
function RegisterOptions<T : TOptions>(aOptions : TConfigureOptionsProc<T>) : TIocRegistration<T>; overload;
function Resolve<T>(const aName : string = ''): T; overload;
function Resolve(aServiceType: PTypeInfo; const aName : string = ''): TValue; overload;
function ResolveAll<T>(const aName : string = '') : TList<T>;
function AbstractFactory<T : class, constructor>(aClass : TClass) : T; overload;
function AbstractFactory<T : class, constructor> : T; overload;
function RegisterTypedFactory<TFactoryInterface : IInterface; TFactoryType : class, constructor>(const aName : string = '') : TIocRegistration<TTypedFactory<TFactoryType>>;
function RegisterSimpleFactory<TInterface : IInterface; TImplementation : class, constructor>(const aName : string = '') : TIocRegistration;
procedure Build;
end;
TIocServiceLocator = class
public
class function GetService<T> : T;
class function TryToGetService<T: IInterface>(aService : T) : Boolean;
end;
EIocRegisterError = class(Exception);
EIocResolverError = class(Exception);
EIocBuildError = class(Exception);
//singleton global instance
function GlobalContainer : TIocContainer;
function ServiceLocator : TIocServiceLocator;
implementation
function GlobalContainer: TIocContainer;
begin
Result := TIocContainer.GlobalInstance;
end;
function ServiceLocator : TIocServiceLocator;
begin
Result := TIocServiceLocator.Create;
end;
{ TIocRegistration }
constructor TIocRegistration.Create;
begin
fRegisterMode := TRegisterMode.rmTransient;
end;
function TIocRegistration.AsTransient: TIocRegistration;
begin
Result := Self;
fRegisterMode := TRegisterMode.rmTransient;
end;
function TIocRegistration.AsSingleton : TIocRegistration;
begin
Result := Self;
fRegisterMode := TRegisterMode.rmSingleton;
end;
function TIocRegistration.AsScoped: TIocRegistration;
begin
Result := Self;
fRegisterMode := TRegisterMode.rmScoped;
end;
function TIocRegistration.IsTransient: Boolean;
begin
Result := fRegisterMode = TRegisterMode.rmTransient;
end;
function TIocRegistration.IsSingleton: Boolean;
begin
Result := fRegisterMode = TRegisterMode.rmSingleton;
end;
function TIocRegistration.IsScoped: Boolean;
begin
Result := fRegisterMode = TRegisterMode.rmScoped;
end;
{ TIocContainer }
class constructor TIocContainer.Create;
begin
GlobalInstance := TIocContainer.Create;
end;
class destructor TIocContainer.Destroy;
begin
if GlobalInstance <> nil then GlobalInstance.Free;
inherited;
end;
function TIocContainer.AbstractFactory<T>(aClass: TClass): T;
begin
Result := fResolver.CreateInstance(aClass).AsType<T>;
end;
function TIocContainer.AbstractFactory<T> : T;
begin
Result := fResolver.CreateInstance(TClass(T)).AsType<T>;
end;
procedure TIocContainer.Build;
var
dependency : TIocRegistration;
begin
{$IFDEF DEBUG_IOC}
TDebugger.TimeIt(Self,'Build','Container dependencies building...');
{$ENDIF}
for dependency in fRegistrator.DependencyOrder do
begin
try
{$IFDEF DEBUG_IOC}
TDebugger.Trace(Self,'[Building container]: %s',[dependency.fIntfInfo.Name]);
{$ENDIF}
if dependency.IsSingleton then fResolver.Resolve(dependency.fIntfInfo,dependency.Name);
{$IFDEF DEBUG_IOC}
TDebugger.Trace(Self,'[Built container]: %s',[dependency.fIntfInfo.Name]);
{$ENDIF}
except
on E : Exception do raise EIocBuildError.CreateFmt('Build Error on "%s(%s)" dependency: %s!',[dependency.fImplementation.ClassName,dependency.Name,e.Message]);
end;
end;
end;
constructor TIocContainer.Create;
begin
fLogger := nil;
fRegistrator := TIocRegistrator.Create;
fInjector := TIocInjector.Create;
fResolver := TIocResolver.Create(fRegistrator,fInjector);
end;
destructor TIocContainer.Destroy;
begin
fInjector.Free;
fResolver.Free;
fRegistrator.Free;
fLogger := nil;
inherited;
end;
function TIocContainer.IsRegistered<TInterface, TImplementation>(const aName: string): Boolean;
begin
Result := fRegistrator.IsRegistered<TInterface,TImplementation>(aName);
end;
function TIocContainer.IsRegistered<TInterface>(const aName: string): Boolean;
begin
Result := fRegistrator.IsRegistered<TInterface>(aName);
end;
function TIocContainer.RegisterType<TInterface, TImplementation>(const aName: string): TIocRegistration<TImplementation>;
begin
Result := fRegistrator.RegisterType<TInterface, TImplementation>(aName);
end;
function TIocContainer.RegisterType(aInterface: PTypeInfo; aImplementation: TClass; const aName: string): TIocRegistration;
begin
Result := fRegistrator.RegisterType(aInterface,aImplementation,aName);
end;
function TIocContainer.RegisterInstance<T>(const aName: string): TIocRegistration<T>;
begin
Result := fRegistrator.RegisterInstance<T>(aName);
end;
function TIocContainer.RegisterTypedFactory<TFactoryInterface,TFactoryType>(const aName: string): TIocRegistration<TTypedFactory<TFactoryType>>;
begin
Result := fRegistrator.RegisterType<TFactoryInterface,TTypedFactory<TFactoryType>>(aName).DelegateTo(function : TTypedFactory<TFactoryType>
begin
Result := TTypedFactory<TFactoryType>.Create(TypeInfo(TFactoryInterface),fResolver);
end);
end;
function TIocContainer.RegisterInstance(aTypeInfo : PTypeInfo; const aName : string = '') : TIocRegistration;
begin
Result := fRegistrator.RegisterInstance(aTypeInfo,aName);
end;
function TIocContainer.RegisterInstance<TInterface>(aInstance: TInterface; const aName: string): TIocRegistration;
begin
Result := fRegistrator.RegisterInstance<TInterface>(aInstance,aName);
end;
function TIocContainer.RegisterOptions<T>(aOptions: TOptions): TIocRegistration<T>;
begin
Result := fRegistrator.RegisterOptions<T>(aOptions).AsSingleton;
end;
function TIocContainer.RegisterOptions<T>(aOptions: TConfigureOptionsProc<T>): TIocRegistration<T>;
var
options : T;
begin
options := T.Create;
aOptions(options);
Result := Self.RegisterOptions<T>(options);
end;
function TIocContainer.RegisterSimpleFactory<TInterface, TImplementation>(const aName: string): TIocRegistration;
begin
Result := fRegistrator.RegisterInstance<IFactory<TInterface>>(TSimpleFactory<TInterface,TImplementation>.Create(fResolver),aName).AsSingleton;
end;
function TIocContainer.Resolve(aServiceType: PTypeInfo; const aName: string): TValue;
begin
Result := fResolver.Resolve(aServiceType,aName);
end;
function TIocContainer.Resolve<T>(const aName : string = ''): T;
begin
Result := fResolver.Resolve<T>(aName);
end;
function TIocContainer.ResolveAll<T>(const aName : string = ''): TList<T>;
begin
Result := fResolver.ResolveAll<T>(aName);
end;
{ TIocRegistrator }
constructor TIocRegistrator.Create;
begin
fDependencies := TDictionary<string,TIocRegistration>.Create;
fDependencyOrder := TList<TIocRegistration>.Create;
end;
destructor TIocRegistrator.Destroy;
var
i : Integer;
regs : TArray<TIocRegistration>;
begin
for i := fDependencyOrder.Count-1 downto 0 do
begin
if fDependencyOrder[i] <> nil then
begin
//free singleton instances not interfaced
if (fDependencyOrder[i] is TIocRegistrationInstance) and
(TIocRegistrationInstance(fDependencyOrder[i]).IsSingleton) then
TIocRegistrationInstance(fDependencyOrder[i]).Instance.Free;
fDependencyOrder[i].Free;
end;
end;
fDependencies.Free;
fDependencyOrder.Free;
inherited;
end;
function TIocRegistrator.GetKey(aPInfo : PTypeInfo; const aName : string = ''): string;
begin
{$IFDEF NEXTGEN}
{$IFDEF DELPHISYDNEY_UP}
Result := string(aPInfo.Name);
{$ELSE}
Result := aPInfo .Name.ToString;
{$ENDIF}
{$ELSE}
Result := string(aPInfo.Name);
{$ENDIF}
if not aName.IsEmpty then Result := Result + '.' + aName.ToLower;
end;
function TIocRegistrator.IsRegistered<TInterface, TImplementation>(const aName: string): Boolean;
var
key : string;
reg : TIocRegistration;
begin
Result := False;
key := GetKey(TypeInfo(TInterface),aName);
if fDependencies.TryGetValue(key,reg) then
begin
if reg.&Implementation = TImplementation then Result := True;
end
end;
function TIocRegistrator.IsRegistered<T>(const aName: string): Boolean;
var
key : string;
reg : TIocRegistration;
begin
Result := False;
key := GetKey(TypeInfo(T),aName);
if fDependencies.TryGetValue(key,reg) then
begin
if reg is TIocRegistrationInterface then Result := True
else if (reg is TIocRegistrationInstance) {and (TIocRegistrationInterface(reg).Instance <> nil)} then Result := True;
end
end;
function TIocRegistrator.RegisterInstance<T>(const aName: string): TIocRegistration<T>;
var
reg : TIocRegistration;
begin
reg := RegisterInstance(TypeInfo(T),aName);
Result := TIocRegistration<T>.Create(reg);
end;
function TIocRegistrator.RegisterInstance<TInterface>(aInstance: TInterface; const aName: string): TIocRegistration;
var
key : string;
tpinfo : PTypeInfo;
begin
tpinfo := TypeInfo(TInterface);
key := GetKey(tpinfo,aName);
if fDependencies.TryGetValue(key,Result) then
begin
if Result.&Implementation = tpinfo.TypeData.ClassType then raise EIocRegisterError.Create('Implementation is already registered!');
end
else
begin
Result := TIocRegistrationInterface.Create(aName);
Result.IntfInfo := tpinfo;
TIocRegistrationInterface(Result).Instance := aInstance;
//reg.Instance := T.Create;
fDependencies.Add(key,Result);
fDependencyOrder.Add(Result);
end;
end;
function TIocRegistrator.RegisterInstance(aTypeInfo : PTypeInfo; const aName : string = '') : TIocRegistration;
var
key : string;
begin
key := GetKey(aTypeInfo,aName);
if fDependencies.TryGetValue(key,Result) then
begin
if Result.&Implementation = aTypeInfo.TypeData.ClassType then raise EIocRegisterError.Create('Implementation is already registered!');
end
else
begin
Result := TIocRegistrationInstance.Create(aName);
Result.IntfInfo := aTypeInfo;
Result.&Implementation := aTypeInfo.TypeData.ClassType;
//reg.Instance := T.Create;
fDependencies.Add(key,Result);
fDependencyOrder.Add(Result);
end;
end;
function TIocRegistrator.RegisterOptions<T>(aOptions: T): TIocRegistration<T>;
var
pInfo : PTypeInfo;
key : string;
reg : TIocRegistration;
begin
pInfo := TypeInfo(IOptions<T>);
key := GetKey(pInfo,'');
if fDependencies.TryGetValue(key,reg) then
begin
if reg.&Implementation = aOptions.ClassType then raise EIocRegisterError.Create('Implementation for this interface is already registered!');
end
else
begin
reg := TIocRegistrationInterface.Create('');
reg.IntfInfo := pInfo;
reg.&Implementation := aOptions.ClassType;
TIocRegistrationInterface(reg).Instance := TOptionValue<T>.Create(aOptions);
fDependencies.Add(key,reg);
fDependencyOrder.Add(reg);
end;
Result := TIocRegistration<T>.Create(reg);
end;
function TIocRegistrator.RegisterType<TInterface, TImplementation>(const aName: string): TIocRegistration<TImplementation>;
var
reg : TIocRegistration;
begin
reg := RegisterType(TypeInfo(TInterface),TImplementation,aName);
Result := TIocRegistration<TImplementation>.Create(reg);
end;
function TIocRegistrator.RegisterType(aTypeInfo : PTypeInfo; aImplementation : TClass; const aName : string = '') : TIocRegistration;
var
key : string;
begin
key := GetKey(aTypeInfo,aName);
if fDependencies.TryGetValue(key,Result) then
begin
if Result.&Implementation = aImplementation then raise EIocRegisterError.Create('Implementation for this interface is already registered!')
else Key := key + '#' + TGUID.NewGuid.ToString;
end;
Result := TIocRegistrationInterface.Create(aName);
Result.IntfInfo := aTypeInfo;
Result.&Implementation := aImplementation;
fDependencies.Add(key,Result);
fDependencyOrder.Add(Result);
end;
{ TIocResolver }
constructor TIocResolver.Create(aRegistrator : TIocRegistrator; aInjector : TIocInjector);
begin
fRegistrator := aRegistrator;
fInjector := aInjector;
end;
function TIocResolver.CreateInstance(aClass: TClass): TValue;
var
ctx : TRttiContext;
rtype : TRttiType;
rmethod : TRttiMethod;
rParam : TRttiParameter;
value : TValue;
values : TArray<TValue>;
begin
Result := nil;
rtype := ctx.GetType(aClass);
if rtype = nil then Exit;
for rmethod in TRttiInstanceType(rtype).GetMethods do
begin
if rmethod.IsConstructor then
begin
//if create don't have parameters
if Length(rmethod.GetParameters) = 0 then
begin
Result := rmethod.Invoke(TRttiInstanceType(rtype).MetaclassType,[]);
Break;
end
else
begin
for rParam in rmethod.GetParameters do
begin
value := Resolve(rParam.ParamType.Handle);
values := values + [value];
end;
Result := rmethod.Invoke(TRttiInstanceType(rtype).MetaclassType,values);
Break;
end;
end;
end;
end;
function TIocResolver.Resolve(aServiceType: PTypeInfo; const aName : string = ''): TValue;
var
key : string;
reg : TIocRegistration;
intf : IInterface;
begin
Result := nil;
reg := nil;
key := fRegistrator.GetKey(aServiceType,aName);
{$IFDEF DEBUG_IOC}
TDebugger.Trace(Self,'Resolving dependency: %s',[key]);
{$ENDIF}
if not fRegistrator.Dependencies.TryGetValue(key,reg) then raise EIocResolverError.CreateFmt('Type "%s" not registered for IOC!',[aServiceType.Name]);
//if is singleton return already instance if exists
if reg.IsSingleton then
begin
if reg is TIocRegistrationInterface then
begin
if TIocRegistrationInterface(reg).Instance <> nil then
begin
if TIocRegistrationInterface(reg).Instance.QueryInterface(GetTypeData(aServiceType).Guid,intf) <> 0 then raise EIocResolverError.CreateFmt('Implementation for "%s" not registered!',[aServiceType.Name]);
TValue.Make(@intf,aServiceType,Result);
{$IFDEF DEBUG_IOC}
TDebugger.Trace(Self,'Resolved dependency: %s',[reg.fIntfInfo.Name]);
{$ENDIF}
Exit;
end;
end
else
begin
if TIocRegistrationInstance(reg).Instance <> nil then
begin
Result := TIocRegistrationInstance(reg).Instance;
{$IFDEF DEBUG_IOC}
TDebugger.Trace(Self,'Resolved dependency: %s',[reg.fIntfInfo.Name]);
{$ENDIF}
Exit;
end;
end;
end;
//instance not created yet
if reg.&Implementation = nil then raise EIocResolverError.CreateFmt('Implemention for "%s" not defined!',[aServiceType.Name]);
//use activator if assigned
if reg is TIocRegistrationInterface then
begin
{$IFDEF DEBUG_IOC}
TDebugger.Trace(Self,'Building dependency: %s',[reg.fIntfInfo.Name]);
{$ENDIF}
if Assigned(reg.ActivatorDelegate) then TIocRegistrationInterface(reg).Instance := reg.ActivatorDelegate().AsInterface
else TIocRegistrationInterface(reg).Instance := CreateInstance(reg.&Implementation).AsInterface;
if (TIocRegistrationInterface(reg).Instance = nil) or (TIocRegistrationInterface(reg).Instance.QueryInterface(GetTypeData(aServiceType).Guid,intf) <> 0) then raise EIocResolverError.CreateFmt('Implementation for "%s" not registered!',[aServiceType.Name]);
TValue.Make(@intf,aServiceType,Result);
end
else
begin
{$IFDEF DEBUG_IOC}
TDebugger.Trace(Self,'Building dependency: %s',[reg.fIntfInfo.Name]);
{$ENDIF}
if Assigned(reg.ActivatorDelegate) then TIocRegistrationInstance(reg).Instance := reg.ActivatorDelegate().AsObject
else
begin
TIocRegistrationInstance(reg).Instance := CreateInstance(reg.&Implementation).AsObject;
end;
Result := TIocRegistrationInstance(reg).Instance;
end;
{$IFDEF DEBUG_IOC}
TDebugger.Trace(Self,'Built dependency: %s',[reg.fIntfInfo.Name]);
{$ENDIF}
end;
function TIocResolver.Resolve<T>(const aName : string = ''): T;
var
pInfo : PTypeInfo;
begin
Result := Default(T);
pInfo := TypeInfo(T);
Result := Resolve(pInfo,aName).AsType<T>;
end;
function TIocResolver.ResolveAll<T>(const aName : string = '') : TList<T>;
var
pInfo : PTypeInfo;
reg : TIocRegistration;
begin
Result := TList<T>.Create;
pInfo := TypeInfo(T);
for reg in fRegistrator.fDependencyOrder do
begin
if reg.IntfInfo = pInfo then Self.Resolve(pInfo,aName);
end;
end;
{ TIocRegistration<T> }
function TIocRegistration<T>.AsScoped: TIocRegistration<T>;
begin
Result := Self;
fRegistration.AsScoped;
end;
function TIocRegistration<T>.AsSingleton: TIocRegistration<T>;
begin
Result := Self;
fRegistration.AsSingleton;
end;
function TIocRegistration<T>.AsTransient: TIocRegistration<T>;
begin
Result := Self;
fRegistration.AsTransient;
end;
constructor TIocRegistration<T>.Create(aRegistration: TIocRegistration);
begin
fRegistration := aRegistration;
end;
function TIocRegistration<T>.DelegateTo(aDelegate: TActivatorDelegate<T>): TIocRegistration<T>;
begin
Result := Self;
fRegistration.ActivatorDelegate := function: TValue
begin
Result := TValue.From<T>(aDelegate);
end;
end;
{ TTypedFactory<T> }
constructor TTypedFactory<T>.Create(PIID: PTypeInfo; aResolver : TIocResolver);
begin
inherited Create(PIID, DoInvoke);
fResolver := aResolver;
end;
procedure TTypedFactory<T>.DoInvoke(Method: TRttiMethod; const Args: TArray<TValue>; out Result: TValue);
begin
if CompareText(Method.Name,'New') <> 0 then raise Exception.Create('TTypedFactory needs a method "New"');
Result := fResolver.CreateInstance(TClass(T)).AsType<T>;
end;
{ TIocServiceLocator }
class function TIocServiceLocator.GetService<T> : T;
begin
Result := GlobalContainer.Resolve<T>;
end;
class function TIocServiceLocator.TryToGetService<T>(aService : T) : Boolean;
begin
Result := GlobalContainer.IsRegistered<T>('');
if Result then aService := GlobalContainer.Resolve<T>;
end;
{ TSimpleFactory<T> }
constructor TSimpleFactory<T>.Create(aResolver: TIocResolver);
begin
fResolver := aResolver;
end;
function TSimpleFactory<T>.New: T;
begin
Result := fResolver.CreateInstance(TClass(T)).AsType<T>;
end;
{ TSimpleFactory<TInterface, TImplementation> }
constructor TSimpleFactory<TInterface, TImplementation>.Create(aResolver: TIocResolver);
begin
fResolver := aResolver;
end;
function TSimpleFactory<TInterface, TImplementation>.New: TInterface;
begin
Result := fResolver.CreateInstance(TClass(TImplementation)).AsType<TInterface>;
end;
end.
|
unit evMemoContextMenu;
{ Библиотека "Эверест" }
{ Начал: Люлин А.В. }
{ Модуль: evMemoContextMenu - }
{ Начат: 03.06.2008 12:26 }
{ $Id: evMemoContextMenu.pas,v 1.4 2010/03/02 13:34:35 lulin Exp $ }
// $Log: evMemoContextMenu.pas,v $
// Revision 1.4 2010/03/02 13:34:35 lulin
// {RequestLink:193823544}.
//
// Revision 1.3 2010/03/01 15:11:56 lulin
// {RequestLink:193823544}.
// - шаг третий.
//
// Revision 1.2 2008/07/10 13:21:00 lulin
// - bug fix: в БП не показывалось VCM'ное меню.
//
// Revision 1.1 2008/06/03 08:38:25 lulin
// - контекстное меню выделено в отдельный модуль.
//
{$Include evDefine.inc }
interface
uses
Menus
;
type
TevMemoContextMenu = class(TPopupMenu)
private
// internal fields
FmnuCopy: TMenuItem;
FmnuCut: TMenuItem;
FmnuDelete: TMenuItem;
FmnuPaste: TMenuItem;
FmnuUndo: TMenuItem;
private
// internal methods
procedure DoProcessClick(Sender: TObject);
{-}
procedure SetMenuState(Sender: TObject);
{-}
public
// public methods
constructor Create;
reintroduce;
{-}
end;//TevMemoContextMenu
function MemoContextMenu: TevMemoContextMenu;
implementation
uses
SysUtils,
Forms,
Clipbrd,
l3Base,
l3Interfaces,
l3String,
evCustomMemo,
nevInterfaces
;
var
g_MemoContextMenu: TevMemoContextMenu = nil;
procedure FreeMemoContextMenu;
begin
// FreeAndNil(g_MemoContextMenu);
end;
function MemoContextMenu: TevMemoContextMenu;
begin
if (g_MemoContextMenu = nil) then
begin
g_MemoContextMenu := TevMemoContextMenu.Create;
l3System.AddExitProc(FreeMemoContextMenu);
end;//g_MemoContextMenu = nil
Result := g_MemoContextMenu;
end;
// start class TevMemoContextMenu
constructor TevMemoContextMenu.Create;
var
TmpItem: TMenuItem;
begin
inherited Create(Application);
OnPopup := SetMenuState;
FmnuUndo := TMenuItem.Create(Self);
FmnuUndo.Caption := str_nevmcmUndo.AsStr;
FmnuUndo.OnClick := DoProcessClick;
Items.Add(FmnuUndo);
TmpItem := TMenuItem.Create(Self);
TmpItem.Caption := '-';
Items.Add(TmpItem);
FmnuCut := TMenuItem.Create(Self);
FmnuCut.Caption := str_nevmcmCut.AsStr;
FmnuCut.OnClick := DoProcessClick;
Items.Add(FmnuCut);
FmnuCopy := TMenuItem.Create(Self);
FmnuCopy.Caption := str_nevmcmCopy.AsStr;
FmnuCopy.OnClick := DoProcessClick;
Items.Add(FmnuCopy);
FmnuPaste := TMenuItem.Create(Self);
FmnuPaste.Caption := str_nevmcmPaste.AsStr;
FmnuPaste.OnClick := DoProcessClick;
Items.Add(FmnuPaste);
FmnuDelete := TMenuItem.Create(Self);
FmnuDelete.Caption := str_nevmcmDelete.AsStr;
FmnuDelete.OnClick := DoProcessClick;
Items.Add(FmnuDelete);
end;
procedure TevMemoContextMenu.DoProcessClick(Sender: TObject);
var
lMemo: TevCustomMemo;
begin
lMemo := TevCustomMemo(TevMemoContextMenu(TMenuItem(Sender).Owner).PopupComponent);
if lMemo <> nil then
begin
if Sender = FmnuCopy then
lMemo.Copy;
if Sender = FmnuCut then
lMemo.Cut;
if Sender = FmnuDelete then
lMemo.Range.Delete;
if Sender = FmnuPaste then
lMemo.Paste;
if Sender = FmnuUndo then
lMemo.Processor.Undo;
end; {if..}
end;
type
THackMemo = class(TevCustomMemo);
procedure TevMemoContextMenu.SetMenuState(Sender: TObject);
var
I: Integer;
Fmt: Tl3ClipboardFormats;
lMemo : THackMemo;
begin
lMemo := THackMemo(TevMemoContextMenu(Sender).PopupComponent);
with lMemo do
begin
FmnuUndo.Enabled := CanUndo;
FmnuCut.Enabled := HasSelection;
FmnuCopy.Enabled := HasSelection;
FmnuPaste.Enabled := False;
if Enabled and not ReadOnly then
begin
Fmt := GetAcceptableFormats;
for I := Low(Fmt) to High(Fmt) do
if Clipboard.HasFormat(Fmt[I]) then
begin
FmnuPaste.Enabled := True;
Break;
end;//Clipboard.HasFormat(Fmt[I])
end;//Enabled..
FmnuDelete.Enabled := HasSelection and Enabled and not ReadOnly;
end;//with lMemo..
end;
end.
|
unit Webhook;
interface
uses
EventType;
type
TWebhookStatusEnum = (ACTIV, INACTIVE);
TWebhook = class
private
FeventTypes: TArray<TEventTypes>;
Fsecret: String;
Fstatus: TWebhookStatusEnum;
FString: String;
public
property url : String read FString write FString ;
property secret : String read Fsecret write Fsecret;
property status : TWebhookStatusEnum read Fstatus write Fstatus;
property eventTypes : TArray<TEventTypes> read FeventTypes write FeventTypes;
destructor Destroy; override;
end;
implementation
{ TWebhook }
destructor TWebhook.Destroy;
var
eventType : TEventTypes;
begin
for eventType in FeventTypes do
eventType.Free;
inherited;
end;
end.
|
{$I OVC.INC}
{$B-} {Complete Boolean Evaluation}
{$I+} {Input/Output-Checking}
{$P+} {Open Parameters}
{$T-} {Typed @ Operator}
{$W-} {Windows Stack Frame}
{$X+} {Extended Syntax}
{$IFNDEF Win32}
{$G+} {286 Instructions}
{$N+} {Numeric Coprocessor}
{$C MOVEABLE,DEMANDLOAD,DISCARDABLE}
{$ENDIF}
{*********************************************************}
{* OVCUSER.PAS 2.17 *}
{* Copyright (c) 1995-98 TurboPower Software Co *}
{* All rights reserved. *}
{*********************************************************}
unit OvcUser;
{-User data class}
interface
uses
SysUtils,
OvcData;
type
{class for implementing user-defined mask and substitution characters}
TOvcUserData = class(TObject)
{.Z+}
protected {private}
FUserCharSets : TUserCharSets;
FForceCase : TForceCase;
FSubstChars : TSubstChars;
{property methods}
function GetForceCase(Index : TForceCaseRange) : TCaseChange;
{-get the case changing behavior of the specified user mask character}
function GetSubstChar(Index : TSubstCharRange) : AnsiChar;
{-get the meaning of the specified substitution character}
function GetUserCharSet(Index : TUserSetRange) : TCharSet;
{-get the specified user-defined character set}
procedure SetForceCase(Index : TForceCaseRange; CC : TCaseChange);
{-set the case changing behavior of the specified user mask character}
procedure SetSubstChar(Index : TSubstCharRange; SC : AnsiChar);
{-set the meaning of the specified substitution character}
procedure SetUserCharSet(Index : TUserSetRange; const US : TCharSet);
{-set the specified user-defined character set}
{.Z+}
public
constructor Create;
{-initialize using default field data}
property ForceCase[Index : TForceCaseRange] : TCaseChange
read GetForceCase
write SetForceCase;
property SubstChars[Index : TSubstCharRange] : AnsiChar
read GetSubstChar
write SetSubstChar;
property UserCharSet[Index : TUserSetRange] : TCharSet
read GetUserCharSet
write SetUserCharSet;
end;
var
{global default user data object}
OvcUserData : TOvcUserData;
implementation
{*** TOvcUserData ***}
const
DefUserCharSets : TUserCharSets = (
{User1} [#1..#255], {User2} [#1..#255], {User3} [#1..#255],
{User4} [#1..#255], {User5} [#1..#255], {User6} [#1..#255],
{User7} [#1..#255], {User8} [#1..#255] );
DefForceCase : TForceCase = (
mcNoChange, mcNoChange, mcNoChange, mcNoChange,
mcNoChange, mcNoChange, mcNoChange, mcNoChange);
DefSubstChars : TSubstChars = (
Subst1, Subst2, Subst3, Subst4, Subst5, Subst6, Subst7, Subst8);
constructor TOvcUserData.Create;
begin
inherited Create;
FUserCharSets := DefUserCharSets;
FForceCase := DefForceCase;
FSubstChars := DefSubstChars;
end;
function TOvcUserData.GetForceCase(Index : TForceCaseRange) : TCaseChange;
{-get the case changing behavior of the specified user mask character}
begin
case Index of
pmUser1..pmUser8 : Result := FForceCase[Index];
else
Result := mcNoChange;
end;
end;
function TOvcUserData.GetSubstChar(Index : TSubstCharRange) : AnsiChar;
{-get the meaning of the specified substitution character}
begin
case Index of
Subst1..Subst8 : Result := FSubstChars[Index];
else
Result := #0;
end;
end;
function TOvcUserData.GetUserCharSet(Index : TUserSetRange) : TCharSet;
{-get the specified user-defined character set}
begin
case Index of
pmUser1..pmUser8 : Result := FUserCharSets[Index];
end;
end;
procedure TOvcUserData.SetForceCase(Index : TForceCaseRange; CC : TCaseChange);
{-set the case changing behavior of the specified user mask character}
begin
case Index of
pmUser1..pmUser8 : FForceCase[Index] := CC;
end;
end;
procedure TOvcUserData.SetSubstChar(Index : TSubstCharRange; SC : AnsiChar);
{-set the meaning of the specified substitution character}
begin
case Index of
Subst1..Subst8 : FSubstChars[Index] := SC;
end;
end;
procedure TOvcUserData.SetUserCharSet(Index : TUserSetRange; const US : TCharSet);
{-set the specified user-defined character set}
begin
case Index of
pmUser1..pmUser8 : FUserCharSets[Index] := US-[#0];
end;
end;
{*** exit procedure ***}
procedure DestroyGlobalUserData; far;
begin
OvcUserData.Free
end;
initialization
{create instance of default user data class}
OvcUserData := TOvcUserData.Create;
{$IFDEF Win32}
finalization
DestroyGlobalUserData;
{$ELSE}
AddExitProc(DestroyGlobalUserData);
{$ENDIF}
end.
|
program EightQueens;
(*
* This program displays solutions to the Eight Queens puzzle. After each
* solution is displayed, the user is asked whether she wants to see nore
* solutions. The program continues until either the user says no or
* until no nore solutions are found.
*
* Requirements for compiling:
* 80% level of Project I
* 100% level of Project II
* 80% level of Project III
*)
type
QueenArray = array[1..8] of Integer;
{ Array for recording the position of the queen in each row of the board }
var
Queens : QueenArray; { Records the position of the queen in each row }
CurRow : Integer;
i, j : Integer;
answer : Char;
Continue_Flag : Boolean;
QueensOk_Flag : Boolean;
GYON_Flag : Boolean;
procedure printf; External;
procedure putchar; External;
function getchar : Char; External;
Procedure DrawBoard;
{ Draws the current state of the board to stdout. Uses the Queens array. }
begin
i := 1;
while i <= 8 do begin
j := 1;
while j <= 8 do begin
putchar(ord(' '));
if j = Queens[i] then
putchar(ord('Q'))
else
putchar(ord('.'));
j := j+1
end;
putchar(10); { Prints a newline character }
i := i+1
end
end; { DrawBoard }
function GetYesOrNo : Char;
{ Gets the first occurrence of [YyNn] from stdin and returns that character. }
begin
answer := getchar;
GYON_Flag := true;
while GYON_Flag do begin
if answer = 'Y' then
GYON_Flag := false
else if answer = 'y' then
GYON_Flag := false
else if answer = 'N' then
GYON_Flag := false
else if answer = 'n' then
GYON_Flag := false;
if GYON_Flag then
answer := getchar
end;
GetYesOrNo := answer
end;
function Stop : Boolean;
{ Returns true iff the user does not wish to see any more solutions. }
begin
printf('Search for another solution? (y/n): ');
Answer := GetYesOrNo;
Stop := (Answer = 'N');
if Answer = 'n' then
Stop := true
end;
function QueensOk : Boolean;
{ Checks whether the queen in CurRow can attack any queens in rows 1 through
CurRow-1. Returns true iff this is NOT the case. }
begin
i := 1;
QueensOk_Flag := (i < CurRow);
QueensOk := true;
while QueensOk_Flag do
if Queens[i] = Queens[CurRow] then begin
QueensOk_Flag := false;
QueensOk := false
end
else if Queens[i] = Queens[CurRow] - (CurRow - i) then begin
QueensOk_Flag := false;
QueensOk := false
end
else if Queens[i] = Queens[CurRow] + (CurRow - i) then begin
QueensOk_Flag := false;
QueensOk := false
end
else begin
i := i + 1;
QueensOk_Flag := (i < CurRow)
end
end;
function Search : Boolean;
{ Assumes that queens have been placed on the board in rows 1 through CurRow-1
so that no queen can attack another.
Looks for a way to place additional queens on rows CurRow through 8 so that no
queen can attack another.
Returns true for success and false for failure. (It places a queen
on row CurRow and uses recursive backtracking.)
If it finds queens on all eight rows, it prints the board (a solution) and
prompts the user for another solution. If the user says yes, then false is
returned (simulating failure) so that searching will continue. }
begin
if CurRow > 8 then begin
DrawBoard;
Search := Stop
end
else begin
Queens[CurRow] := 1;
Continue_Flag := true;
while Continue_Flag do begin
if QueensOk then begin
CurRow := CurRow + 1;
Continue_Flag := (Search = false);
CurRow := CurRow - 1
end;
if Continue_Flag then begin
Search := false;
Queens[CurRow] := Queens[CurRow] + 1;
Continue_Flag := (Queens[CurRow] <= 8)
end
else
Search := true
end
end
end;
begin { main }
CurRow := 1;
Continue_Flag := Search; { This is the main part of the program }
if Continue_Flag then
printf('There could be more solutions.\n')
else
printf('No more solutions.\n')
end.
|
unit uReadBin;
{$mode objfpc}{$H+}
{ Example 08 File Handling }
{ Used to Read a bin file }
{Declare some units used by this example.}
interface
uses
GlobalConst,
GlobalTypes,
Platform,
Classes,
Threads,
SysUtils,
FileSystem, {Include the file system core and interfaces}
FATFS, {Include the FAT file system driver}
MMC; {Include the MMC/SD core to access our SD card}
type
Buffer = array[0..4159] of Char;
BufPtr = ^Buffer;
{A window handle plus a couple of others.}
var
Count:Integer;
Filename:String;
SearchRec:TSearchRec;
StringList:TStringList;
FileStream:TFileStream;
//FileStreamlog:TFileStream;
//WindowHandle:TWindowHandle;
B : Buffer;
BP : BufPtr;
PP : Pointer;
i,j: integer;
Characters : String;
PCharacters : ^PString;
procedure SetFileName(const aFileName : String);
procedure SetStingList(aStringList : TStringList);
function ReadBuffer(aIndex:Integer):String;
function Readit(aIndex:Integer):String;
implementation
procedure SetFileName(const aFileName:String);
begin
FileName:=aFileName;
WriteLn(FileName);
end;
procedure SetStingList(aStringList : TStringList);
begin
StringList:=aStringList;
end;
function Readit(aIndex:Integer):String;
begin
try
FileStream:=TFileStream.Create(Filename,fmOpenReadWrite);
//FileStreamlog:=TFileStream.Create(Filenamelog,fmOpenReadWrite);
{Recreate our string list}
StringList:=TStringList.Create;
{And use LoadFromStream to read it}
StringList.LoadFromStream(FileStream);
{PP is Pointer BP is a Pointer to an Buffer = array[0..4159] of Char; }
PP:=StringList.GetText;
BP:=PP;
j:=Length(BP[0]);
Characters:=Copy(BP[0],aIndex,65);
FileStream.Free;
StringList.Free;
{If you remove the SD card and put in back in your computer, you should see the
file "Example 08 File Handling.txt" on it. If you open it in a notepad you should
see the contents exactly as they appeared on screen.}
except
{TFileStream couldn't open the file}
//ConsoleWindowWriteLn(WindowHandle,'Failed to open the file ' + Filename);
end;
Result:=Characters;
end;
function ReadBuffer(aIndex:Integer):String;
begin
j:=Length(BP[0]);
Characters:=Copy(BP[0],aIndex,65);
Result:=Characters;
end;
end.
|
{@html(<hr>)
@abstract(Base classes for objects that are checked for telemetry and game
version support.)
@author(František Milt <fmilt@seznam.cz>)
@created(2013-10-17)
@lastmod(2014-05-01)
@bold(@NoAutoLink(TelemetryVersionObjects))
©František Milt, all rights reserved.
Classes in this unit (for details, refer to declaration of individual class):
@preformatted(
TTelemetryAbstractVersionObject
|- TTelemetryVersionObject
|- TTelemetryVersionPrepareObject
)
Last change: 2014-05-01
Change List:@unorderedList(
@item(2013-10-17 - First stable version.)
@item(2014-04-06 - Type of parameters @code(GameName) and @code(GameID) in
method TTelemetryVersionPrepareObject.PrepareForGameVersion
changed to @code(TelemetryString).)
@item(2014-04-06 - Added support for eut2 1.8.)
@item(2014-05-01 - Added method
TTelemetryAbstractVersionObject.HighestSupportedGameVersion
and its variants in descendant classes.))
@html(<hr>)}
unit TelemetryVersionObjects;
interface
{$INCLUDE '.\Telemetry_defs.inc'}
uses
{$IFDEF Documentation}
TelemetryCommon,
TelemetryStrings,
{$ENDIF}
{$IFDEF UseCondensedHeader}
SCS_Telemetry_Condensed;
{$ELSE}
scssdk,
scssdk_telemetry,
scssdk_eut2,
scssdk_telemetry_eut2;
{$ENDIF}
type
{==============================================================================}
{------------------------------------------------------------------------------}
{ TTelemetryAbstractVersionObject }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TTelemetryAbstractVersionObject // Class declaration }
{==============================================================================}
{
@abstract(Common, fully abstract ancestor for all classes that needs to be
checked for version support before creation of an instance.)
This class defines set of methods used to check version support. Use it as an
ancestor for classes where you want to fully control methods implementation or
for classes that supports different set of versions than is defined for
TTelemetryVersionObject.@br
All methods must be called directly on class. They are intended to be used to
check whether the class supports required telemetry and game version before
instantiation (creation of class instance).
@member(HighestSupportedTelemetryVersion
@returns Highest supported telemetry version.)
@member(HighestSupportedGameVersion
@param GameID Game identifier.
@returns Highest supported version of passed game.)
@member(SupportsTelemetryVersion
@param TelemetryVersion Version of telemetry.
@returns @True when given telemetry version is supported, otherwise @false.)
@member(SupportsTelemetryMajorVersion
@param TelemetryVersion Version of telemetry.
@returns(@True when given telemetry major version is supported (minor part
is ignored), otherwise @false.))
@member(SupportsGameVersion
@param GameID Game identifier.
@param GameVersion Version of game.
@returns(@True when given game and its version are supported, otherwise
@false.))
@member(SupportsTelemetryAndGameVersion
@param TelemetryVersion Version of telemetry.
@param GameID Game identifier.
@param GameVersion Version of game.
@returns(@True when given telemetry, game and its version are supported,
otherwise @false.))
@member(SupportsTelemetryAndGameVersionParam
@param TelemetryVersion Version of telemetry.
@param Parameters Structure containing other version informations.
@returns(@True when given telemetry, game and its version are supported,
otherwise @false.))
}
TTelemetryAbstractVersionObject = class(TObject)
public
class Function HighestSupportedTelemetryVersion: scs_u32_t; virtual; abstract;
class Function HighestSupportedGameVersion(GameID: scs_string_t): scs_u32_t; virtual; abstract;
class Function SupportsTelemetryVersion(TelemetryVersion: scs_u32_t): Boolean; virtual; abstract;
class Function SupportsTelemetryMajorVersion(TelemetryVersion: scs_u32_t): Boolean; virtual; abstract;
class Function SupportsGameVersion(GameID: scs_string_t; GameVersion: scs_u32_t): Boolean; virtual; abstract;
class Function SupportsTelemetryAndGameVersion(TelemetryVersion: scs_u32_t; GameID: scs_string_t; GameVersion: scs_u32_t): Boolean; virtual; abstract;
class Function SupportsTelemetryAndGameVersionParam(TelemetryVersion: scs_u32_t; Parameters: scs_telemetry_init_params_t): Boolean; virtual; abstract;
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TTelemetryVersionObject }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TTelemetryVersionObject // Class declaration }
{==============================================================================}
{
@abstract(Common ancestor for all classes that needs to be checked for version
support before creation of an instance.)
This class implements all methods from TTelemetryAbstractVersionObject. Used
as an ancestor for classes that supports exactly the same versions set as this
class.@br
All methods must be called directly on class. They are intended to be used to
check whether the class supports required telemetry and game version before
instantiation (creation of class instance).
Supported versions as of 2014-04-06:
@unorderedList(
@itemSpacing(Compact)
@item(Telemetry 1.0)
@item(eut2 1.0)
@item(eut2 1.1)
@item(eut2 1.2)
@item(eut2 1.3)
@item(eut2 1.4)
@item(eut2 1.5)
@item(eut2 1.6)
@item(eut2 1.7)
@item(eut2 1.8)
)
@member(HighestSupportedTelemetryVersion See @inherited.)
@member(HighestSupportedGameVersion See @inherited.)
@member(SupportsTelemetryVersion See @inherited.)
@member(SupportsTelemetryMajorVersion See @inherited.)
@member(SupportsGameVersion See @inherited.)
@member(SupportsTelemetryAndGameVersion See @inherited.)
@member(SupportsTelemetryAndGameVersionParam See @inherited.)
}
TTelemetryVersionObject = class(TTelemetryAbstractVersionObject)
public
class Function HighestSupportedTelemetryVersion: scs_u32_t; override;
class Function HighestSupportedGameVersion(GameID: scs_string_t): scs_u32_t; override;
class Function SupportsTelemetryVersion(TelemetryVersion: scs_u32_t): Boolean; override;
class Function SupportsTelemetryMajorVersion(TelemetryVersion: scs_u32_t): Boolean; override;
class Function SupportsGameVersion(GameID: scs_string_t; GameVersion: scs_u32_t): Boolean; override;
class Function SupportsTelemetryAndGameVersion(TelemetryVersion: scs_u32_t; GameID: scs_string_t; GameVersion: scs_u32_t): Boolean; override;
class Function SupportsTelemetryAndGameVersionParam(TelemetryVersion: scs_u32_t; Parameters: scs_telemetry_init_params_t): Boolean; override;
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TTelemetryVersionPrepareObject }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TTelemetryVersionPrepareObject // Class declaration }
{==============================================================================}
{
@abstract(Common ancestor for all classes that needs to be prepared for
selected telemetry and/or game version.)
Methods beginning with @code(Prepare_) are called to prepare created object
for specific telemetry/game version.@br
Each telemetry/game version has its own method, even if no action is needed.
For each version, all lower or equal version methods are called in ascending
order (every method calls its predecessor at the beginning of its own code).
For example, for version 1.2, methods 1_0, 1_1 and 1_2 would be called.
@member(PrepareForTelemetryVersion
Performs any preparations necessary to support required telemetry version.
@param(TelemetryVersion Version of telemetry for which the object should be
prepared.)
@returns(@True when preparation for given version were done successfully,
otherwise @false.))
@member(PrepareForGameVersion
Performs preparations necessary to support required game and its version.
@param GameName Name of the game.
@param GameID Game identifier.
@param GameVersion Version of game.
@returns(@True when preparation for given game and its version were done
successfully, otherwise @false.))
@member(Prepare_Telemetry_1_0 Preparation for telemetry 1.0.)
@member(Prepare_Game_eut2_1_0 Preparation for eut2 1.0.)
@member(Prepare_Game_eut2_1_1 Preparation for eut2 1.1.@br
Calls Prepare_Game_eut2_1_0.)
@member(Prepare_Game_eut2_1_2 Preparation for eut2 1.2.@br
Calls Prepare_Game_eut2_1_1.)
@member(Prepare_Game_eut2_1_3 Preparation for eut2 1.3.@br
Calls Prepare_Game_eut2_1_2.)
@member(Prepare_Game_eut2_1_4 Preparation for eut2 1.4.@br
Calls Prepare_Game_eut2_1_3.)
@member(Prepare_Game_eut2_1_5 Preparation for eut2 1.5.@br
Calls Prepare_Game_eut2_1_4.)
@member(Prepare_Game_eut2_1_6 Preparation for eut2 1.6.@br
Calls Prepare_Game_eut2_1_5.)
@member(Prepare_Game_eut2_1_7 Preparation for eut2 1.7.@br
Calls Prepare_Game_eut2_1_6.)
@member(Prepare_Game_eut2_1_8 Preparation for eut2 1.8.@br
Calls Prepare_Game_eut2_1_7.)
}
TTelemetryVersionPrepareObject = class(TTelemetryVersionObject)
protected
Function PrepareForTelemetryVersion(TelemetryVersion: scs_u32_t): Boolean; virtual;
Function PrepareForGameVersion(const GameName, GameID: TelemetryString; GameVersion: scs_u32_t): Boolean; virtual;
procedure Prepare_Telemetry_1_0; virtual;
procedure Prepare_Game_eut2_1_0; virtual;
procedure Prepare_Game_eut2_1_1; virtual;
procedure Prepare_Game_eut2_1_2; virtual;
procedure Prepare_Game_eut2_1_3; virtual;
procedure Prepare_Game_eut2_1_4; virtual;
procedure Prepare_Game_eut2_1_5; virtual;
procedure Prepare_Game_eut2_1_6; virtual;
procedure Prepare_Game_eut2_1_7; virtual;
procedure Prepare_Game_eut2_1_8; virtual;
end;
implementation
uses
TelemetryCommon, TelemetryStrings;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TTelemetryVersionObject }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TTelemetryVersionObject // Class implementation }
{==============================================================================}
{------------------------------------------------------------------------------}
{ TTelemetryVersionObject // Constants, types, variables, etc... }
{------------------------------------------------------------------------------}
const
{$IFDEF DevelopmentHints}
{$MESSAGE HINT 'Development hint: Remember to update.'}
{$ENDIF}
// These constants can change with telemetry development, remember to update
// them if you add support for new telemetry version.
cSupportedTelemetryVersions: Array[0..0] of scs_u32_t =
(SCS_TELEMETRY_VERSION_1_00 {1.0});
cSupportedGameVersions: Array[0..8] of TGameSupportInfo =
((GameID: SCS_GAME_ID_EUT2; GameVersion: SCS_TELEMETRY_EUT2_GAME_VERSION_1_00 {ETS2 1.0}),
(GameID: SCS_GAME_ID_EUT2; GameVersion: SCS_TELEMETRY_EUT2_GAME_VERSION_1_01 {ETS2 1.1}),
(GameID: SCS_GAME_ID_EUT2; GameVersion: SCS_TELEMETRY_EUT2_GAME_VERSION_1_02 {ETS2 1.2}),
(GameID: SCS_GAME_ID_EUT2; GameVersion: SCS_TELEMETRY_EUT2_GAME_VERSION_1_03 {ETS2 1.3}),
(GameID: SCS_GAME_ID_EUT2; GameVersion: SCS_TELEMETRY_EUT2_GAME_VERSION_1_04 {ETS2 1.4}),
(GameID: SCS_GAME_ID_EUT2; GameVersion: SCS_TELEMETRY_EUT2_GAME_VERSION_1_05 {ETS2 1.5}),
(GameID: SCS_GAME_ID_EUT2; GameVersion: SCS_TELEMETRY_EUT2_GAME_VERSION_1_06 {ETS2 1.6}),
(GameID: SCS_GAME_ID_EUT2; GameVersion: SCS_TELEMETRY_EUT2_GAME_VERSION_1_07 {ETS2 1.7}),
(GameID: SCS_GAME_ID_EUT2; GameVersion: SCS_TELEMETRY_EUT2_GAME_VERSION_1_08 {ETS2 1.8}));
{------------------------------------------------------------------------------}
{ TTelemetryVersionObject // Public methods }
{------------------------------------------------------------------------------}
class Function TTelemetryVersionObject.HighestSupportedTelemetryVersion: scs_u32_t;
begin
Result := cSupportedTelemetryVersions[High(cSupportedTelemetryVersions)];
end;
//------------------------------------------------------------------------------
class Function TTelemetryVersionObject.HighestSupportedGameVersion(GameID: scs_string_t): scs_u32_t;
var
i: Integer;
begin
Result := SCS_U32_NIL;
For i := High(cSupportedGameVersions) downto Low(cSupportedGameVersions) do
{$IFDEF AssumeASCIIString}
If TelemetrySameStrNoConv(APIStringToTelemetryString(GameID),cSupportedGameVersions[i].GameID) then
{$ELSE}
If TelemetrySameStr(APIStringToTelemetryString(GameID),cSupportedGameVersions[i].GameID) then
{$ENDIF}
Result := cSupportedGameVersions[i].GameVersion;
end;
//------------------------------------------------------------------------------
class Function TTelemetryVersionObject.SupportsTelemetryVersion(TelemetryVersion: scs_u32_t): Boolean;
var
i: Integer;
begin
Result := False;
For i := Low(cSupportedTelemetryVersions) to High(cSupportedTelemetryVersions) do
If TelemetryVersion = cSupportedTelemetryVersions[i] then
begin
Result := True;
Break;
end;
end;
//------------------------------------------------------------------------------
class Function TTelemetryVersionObject.SupportsTelemetryMajorVersion(TelemetryVersion: scs_u32_t): Boolean;
var
i: Integer;
begin
Result := False;
For i := Low(cSupportedTelemetryVersions) to High(cSupportedTelemetryVersions) do
If (TelemetryVersion and $FFFF0000) = (cSupportedTelemetryVersions[i] and $FFFF0000) then
begin
Result := True;
Break;
end;
end;
//------------------------------------------------------------------------------
class Function TTelemetryVersionObject.SupportsGameVersion(GameID: scs_string_t; GameVersion: scs_u32_t): Boolean;
var
i: Integer;
begin
Result := False;
For i := Low(cSupportedGameVersions) to High(cSupportedGameVersions) do
{$IFDEF AssumeASCIIString}
If TelemetrySameStrNoConv(APIStringToTelemetryString(GameID),cSupportedGameVersions[i].GameID) and
{$ELSE}
If TelemetrySameStr(APIStringToTelemetryString(GameID),cSupportedGameVersions[i].GameID) and
{$ENDIF}
(GameVersion = cSupportedGameVersions[i].GameVersion) then
begin
Result := True;
Break;
end;
end;
//------------------------------------------------------------------------------
class Function TTelemetryVersionObject.SupportsTelemetryAndGameVersion(TelemetryVersion: scs_u32_t; GameID: scs_string_t; GameVersion: scs_u32_t): Boolean;
begin
Result := SupportsTelemetryVersion(TelemetryVersion) and SupportsGameVersion(GameID,GameVersion);
end;
//------------------------------------------------------------------------------
class Function TTelemetryVersionObject.SupportsTelemetryAndGameVersionParam(TelemetryVersion: scs_u32_t; Parameters: scs_telemetry_init_params_t): Boolean;
begin
Result := SupportsTelemetryAndGameVersion(TelemetryVersion,Parameters.common.game_id,Parameters.common.game_version);
end;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TTelemetryVersionPrepareObject }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TTelemetryVersionPrepareObject // Class implementation }
{==============================================================================}
{------------------------------------------------------------------------------}
{ TTelemetryVersionPrepareObject // Protected methods }
{------------------------------------------------------------------------------}
Function TTelemetryVersionPrepareObject.PrepareForTelemetryVersion(TelemetryVersion: scs_u32_t): Boolean;
begin
case TelemetryVersion of
SCS_TELEMETRY_VERSION_1_00: begin Prepare_Telemetry_1_0; Result := True; end; {1.0}
else
Result := False;
end;
end;
//------------------------------------------------------------------------------
Function TTelemetryVersionPrepareObject.PrepareForGameVersion(const GameName, GameID: TelemetryString; GameVersion: scs_u32_t): Boolean;
begin
Result := False;
{$IFDEF AssumeASCIIString}
If TelemetrySameStrNoConv(GameId,SCS_GAME_ID_EUT2) then {eut2, Euro Truck Simulator 2}
{$ELSE}
If TelemetrySameStr(GameId,SCS_GAME_ID_EUT2) then {eut2, Euro Truck Simulator 2}
{$ENDIF}
begin
case GameVersion of
SCS_TELEMETRY_EUT2_GAME_VERSION_1_00: begin Prepare_Game_eut2_1_0; Result := True; end; {1.0}
SCS_TELEMETRY_EUT2_GAME_VERSION_1_01: begin Prepare_Game_eut2_1_1; Result := True; end; {1.1}
SCS_TELEMETRY_EUT2_GAME_VERSION_1_02: begin Prepare_Game_eut2_1_2; Result := True; end; {1.2}
SCS_TELEMETRY_EUT2_GAME_VERSION_1_03: begin Prepare_Game_eut2_1_3; Result := True; end; {1.3}
SCS_TELEMETRY_EUT2_GAME_VERSION_1_04: begin Prepare_Game_eut2_1_4; Result := True; end; {1.4}
SCS_TELEMETRY_EUT2_GAME_VERSION_1_05: begin Prepare_Game_eut2_1_5; Result := True; end; {1.5}
SCS_TELEMETRY_EUT2_GAME_VERSION_1_06: begin Prepare_Game_eut2_1_6; Result := True; end; {1.6}
SCS_TELEMETRY_EUT2_GAME_VERSION_1_07: begin Prepare_Game_eut2_1_7; Result := True; end; {1.7}
SCS_TELEMETRY_EUT2_GAME_VERSION_1_08: begin Prepare_Game_eut2_1_8; Result := True; end; {1.8}
end;
end;
end;
//------------------------------------------------------------------------------
procedure TTelemetryVersionPrepareObject.Prepare_Telemetry_1_0;
begin
// No action.
end;
//------------------------------------------------------------------------------
procedure TTelemetryVersionPrepareObject.Prepare_Game_eut2_1_0;
begin
// No action.
end;
//------------------------------------------------------------------------------
procedure TTelemetryVersionPrepareObject.Prepare_Game_eut2_1_1;
begin
Prepare_Game_eut2_1_0;
end;
//------------------------------------------------------------------------------
procedure TTelemetryVersionPrepareObject.Prepare_Game_eut2_1_2;
begin
Prepare_Game_eut2_1_1;
end;
//------------------------------------------------------------------------------
procedure TTelemetryVersionPrepareObject.Prepare_Game_eut2_1_3;
begin
Prepare_Game_eut2_1_2;
end;
//------------------------------------------------------------------------------
procedure TTelemetryVersionPrepareObject.Prepare_Game_eut2_1_4;
begin
Prepare_Game_eut2_1_3;
end;
//------------------------------------------------------------------------------
procedure TTelemetryVersionPrepareObject.Prepare_Game_eut2_1_5;
begin
Prepare_Game_eut2_1_4;
end;
//------------------------------------------------------------------------------
procedure TTelemetryVersionPrepareObject.Prepare_Game_eut2_1_6;
begin
Prepare_Game_eut2_1_5;
end;
//------------------------------------------------------------------------------
procedure TTelemetryVersionPrepareObject.Prepare_Game_eut2_1_7;
begin
Prepare_Game_eut2_1_6;
end;
//------------------------------------------------------------------------------
procedure TTelemetryVersionPrepareObject.Prepare_Game_eut2_1_8;
begin
Prepare_Game_eut2_1_7;
end;
end.
|
{* A sample ModelMaker unit }
unit MMDemoClasses;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls,
Forms, Dialogs;
type
{* This is a demo class built entirely with ModelMaker }
TMMDemo = class (TObject)
private
FText: string;
FValue: Integer;
function GetText: string;
procedure SetText(const NewValue: string);
public
{* A simple test method with a string parameter }
procedure Test(s: string); virtual;
{* The amount represented by the object }
property Value: Integer read FValue write FValue;
published
{* Textual description of the message displayed by the object }
property Text: string read GetText write SetText;
end;
implementation
{-**********************************************************************
****************** Class: TMMDemo
************************************************************************}
{*** TMMDemo.GetText (private)
*** GetText is the read access method of the Text property. }
function TMMDemo.GetText: string;
begin
Result := FText;
end;{ TMMDemo.GetText }
{*** TMMDemo.SetText (private)
*** SetText is the write access method of the Text property. }
procedure TMMDemo.SetText(const NewValue: string);
{* Some text for the class }
begin
if FText <> NewValue then
begin
FText := NewValue;
end;
end;{ TMMDemo.SetText }
{*** TMMDemo.Test (public)
*** This is a total nonsense, as we should at least use the values
of the other properties, but I felt lazy... }
procedure TMMDemo.Test(s: string);
{* A simple test method with a string parameter }
begin
ShowMessage (s);
end;{ TMMDemo.Test }
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpIAsn1EncodableVector;
{$I ..\Include\CryptoLib.inc}
interface
uses
ClpIProxiedInterface,
ClpCryptoLibTypes;
type
IAsn1EncodableVector = interface(IInterface)
['{A78E22EB-DB67-472E-A55F-CD710BCBDBFA}']
function GetCount: Int32;
function GetSelf(Index: Int32): IAsn1Encodable;
procedure Add(const objs: array of IAsn1Encodable);
procedure AddOptional(const objs: array of IAsn1Encodable);
property Self[Index: Int32]: IAsn1Encodable read GetSelf; default;
property Count: Int32 read GetCount;
function GetEnumerable: TCryptoLibGenericArray<IAsn1Encodable>;
end;
implementation
end.
|
unit WAV.Chat.Painter;
interface
uses
WAV.Chat,
Types,
UITypes,
FMX.Graphics;
type
TElementAlign = (eaLeft, eaRight, eaCenter);
TElementPainter = class
private
FElement: TChatElement;
FBackground: TAlphaColor;
FBoundaries: TRectF;
FContentRect: TRectF;
FTimeRect: TRectF;
FAlign: TElementAlign;
FShowTime: Boolean;
function GetHeight: Single;
protected
procedure MeasureContent(const ACanvas: TCanvas; var AWidth, AHeight: Single); virtual;
procedure PaintContent(const ACanvas: TCanvas; const ATarget: TRectF); virtual;
public
constructor Create;
procedure PaintTo(const ACanvas: TCanvas; ATop: Single); virtual;
procedure UpdateSize(const ACanvas: TCanvas; AWidth: Single); virtual;
property Height: Single read GetHeight;
property Element: TChatElement read FElement write FElement;
property Background: TAlphaColor read FBackground write FBackground;
property Align: TElementAlign read FAlign write FAlign;
property ShowTime: Boolean read FShowTime write FShowTime;
end;
TTextElementPainter = class(TElementPainter)
protected
function GetText: string; virtual;
procedure MeasureContent(const ACanvas: TCanvas; var AWidth: Single; var AHeight: Single); override;
procedure PaintContent(const ACanvas: TCanvas; const ATarget: TRectF); override;
end;
TDateElementPainter = class(TTextElementPainter)
protected
function GetText: string; override;
end;
TImageElementPainter = class(TElementPainter)
protected
function GetBitmap: TBitmap;
procedure MeasureContent(const ACanvas: TCanvas; var AWidth: Single; var AHeight: Single); override;
procedure PaintContent(const ACanvas: TCanvas; const ATarget: TRectF); override;
public
procedure UpdateSize(const ACanvas: TCanvas; AWidth: Single); override;
end;
implementation
uses
FMX.Types,
Math;
const
CBubblePadding = 50;
CInnerPadding = 5;
CCornerRadius = 5;
CImagePreviewSize = 200;
CMainTextOpacity = 1;
CSecondaryTextOpacity = 0.5;
CTimeFontFactor = 0.8;
{ TElementPainter }
constructor TElementPainter.Create;
begin
inherited;
FShowTime := True;
end;
function TElementPainter.GetHeight: Single;
begin
Result := FBoundaries.Height;
end;
procedure TElementPainter.MeasureContent(const ACanvas: TCanvas; var AWidth, AHeight: Single);
begin
end;
procedure TElementPainter.PaintContent(const ACanvas: TCanvas;
const ATarget: TRectF);
begin
end;
procedure TElementPainter.PaintTo(const ACanvas: TCanvas; ATop: Single);
var
LBubble, LTarget: TRectF;
LOldFont: Single;
begin
inherited;
LBubble := FBoundaries;
LBubble.Offset(0, ATop);
ACanvas.Fill.Color := FBackground;
ACanvas.Stroke.Color := TAlphaColorRec.Grey;
ACanvas.Stroke.Kind := TBrushKind.Solid;
ACanvas.FillRect(LBubble, CCornerRadius, CCornerRadius, AllCorners, 1);
LBubble.Inflate(-1, -1);
ACanvas.DrawRect(LBubble, CCornerRadius, CCornerRadius, AllCorners, 1);
LTarget := FContentRect;
LTarget.Offset(0, ATop);
PaintContent(ACanvas, LTarget);
if FShowTime then
begin
LTarget := FTimeRect;
LTarget.Offset(0, ATop);
LOldFont := ACanvas.Font.Size;
ACanvas.Font.Size := LOldFont * CTimeFontFactor;
ACanvas.Fill.Color := TAlphaColorRec.Grey;
ACanvas.FillText(LTarget, FElement.Time, False, 1, [], TTextAlign.Trailing);
ACanvas.Font.Size := LOldFont;
end;
end;
procedure TElementPainter.UpdateSize(const ACanvas: TCanvas; AWidth: Single);
var
LWidth, LHeight, LOldFontSize: Single;
const
CMaxHeight = 9999;
begin
if FShowTime then
begin
FTimeRect := TRectF.Create(0, 0, AWidth, CMaxHeight);
LOldFontSize := ACanvas.Font.Size;
ACanvas.Font.Size := ACanvas.Font.Size * CTimeFontFactor;
ACanvas.MeasureText(FTimeRect, FElement.Time, False, [], TTextALign.Leading);
FTimeRect.Offset(0, -FTimeRect.Top);
ACanvas.Font.Size := LOldFontSize;
end;
LWidth := AWidth - CBubblePadding - CInnerPadding * 2;
if FShowTime then
LWidth := LWidth - FTimeRect.Width - CInnerPadding;
LHeight := CMaxHeight;
MeasureContent(ACanvas, LWidth, LHeight);
if LHeight = CMaxHeight then
LHeight := 0;
FBoundaries := TRectF.Create(0, 0, LWidth + CInnerPadding*2, LHeight + CInnerPadding * 2);
if FShowTime then
FBoundaries.Width := FBoundaries.Width + FTimeRect.Width + CInnerPadding;
if Align = eaRight then
FBoundaries.Offset(AWidth - FBoundaries.Width, 0)
else if Align = eaCenter then
FBoundaries.Offset((AWidth - FBoundaries.Width) / 2, 0);
FContentRect := TRectF.Create(FBoundaries.Left + CInnerPadding, CInnerPadding, 0, 0);
FContentRect.Width := LWidth;
FContentRect.Height := LHeight;
if FShowTime then
FTimeRect.Offset(FBoundaries.Left + FBoundaries.Width - FTimeRect.Width - CInnerPadding, FBoundaries.Height - FTimeRect.Height - CInnerPadding);
end;
{ TImageElementPainter }
function TImageElementPainter.GetBitmap: TBitmap;
begin
Result := TImageChatElement(FElement).Image;
end;
procedure TImageElementPainter.MeasureContent(const ACanvas: TCanvas;
var AWidth, AHeight: Single);
var
LFactor: Single;
LSize: Single;
begin
inherited;
if GetBitmap.Width > GetBitmap.Height then
LSize := GetBitmap.Width
else
LSize := GetBitmap.Height;
LFactor := CImagePreviewSize / LSize;
AWidth := Min(GetBitmap.Width * LFactor, AWidth);
AHeight := Min(GetBitmap.Height * LFactor, AHeight);
end;
procedure TImageElementPainter.PaintContent(const ACanvas: TCanvas;
const ATarget: TRectF);
begin
inherited;
ACanvas.DrawBitmap(GetBitmap, GetBitmap.BoundsF, ATarget, 1);
end;
procedure TImageElementPainter.UpdateSize(const ACanvas: TCanvas;
AWidth: Single);
begin
inherited;
if FShowTime then
begin
//resize and move Time below Image instead of right
FTimeRect.Offset(-(FTimeRect.Width + CInnerPadding), FTimeRect.Height + CInnerPadding);
FBoundaries.Width := FBoundaries.Width - FTimeRect.Width - CInnerPadding;
FBoundaries.Height := FBoundaries.Height + FTimeRect.Height + CInnerPadding;
if Align = eaRight then
begin
FBoundaries.Offset(FTimeRect.Width + CInnerPadding, 0);
FContentRect.Offset(FTimeRect.Width + CInnerPadding, 0);
FTimeRect.Offset(FTimeRect.Width + CInnerPadding, 0);
end;
end;
end;
{ TTextElementPainter }
function TTextElementPainter.GetText: string;
begin
Result := (FElement as TTextChatElement).Text;
end;
procedure TTextElementPainter.MeasureContent(const ACanvas: TCanvas; var AWidth,
AHeight: Single);
var
LRect: TRectF;
begin
inherited;
LRect := TRectF.Create(0, 0, AWidth, AHeight);
ACanvas.MeasureText(LRect, GetText, True, [], TTextAlign.Leading, TTextAlign.Leading);
AWidth := LRect.Width;
AHeight := LRect.Height;
end;
procedure TTextElementPainter.PaintContent(const ACanvas: TCanvas;
const ATarget: TRectF);
begin
inherited;
ACanvas.Fill.Color := TAlphaColorRec.Black;
ACanvas.FillText(ATarget, GetText, True, 1, [], TTextAlign.Leading);
end;
{ TDateElementPainter }
function TDateElementPainter.GetText: string;
begin
Result := FElement.Date;
end;
end.
|
unit ColorDist;
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=]
Copyright (c) 2014, Jarl K. <Slacky> Holta || http://github.com/WarPie
All rights reserved.
For more info see: Copyright.txt
[=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=}
{$mode objfpc}{$H+}
{$macro on}
{$inline on}
interface
uses
Header;
function DistanceRGB(Color1: Pointer; Color2: TColor; mul: TMultiplier): Single; inline;
function DistanceHSV(Color1: Pointer; Color2: TColor; mul: TMultiplier): Single; inline;
function DistanceHSL(Color1: Pointer; Color2: TColor; mul: TMultiplier): Single; inline;
function DistanceXYZ(Color1: Pointer; Color2: TColor; mul: TMultiplier): Single; inline;
function DistanceLAB(Color1: Pointer; Color2: TColor; mul: TMultiplier): Single; inline;
function DistanceLCH(Color1: Pointer; Color2: TColor; mul: TMultiplier): Single; inline;
function DistanceDeltaE(Color1: Pointer; Color2: TColor; mul: TMultiplier): Single; inline;
function DistanceRGB_Max(mul: TMultiplier): Single; inline;
function DistanceHSV_Max(mul: TMultiplier): Single; inline;
function DistanceHSL_Max(mul: TMultiplier): Single; inline;
function DistanceXYZ_Max(mul: TMultiplier): Single; inline;
function DistanceLAB_Max(mul: TMultiplier): Single; inline;
function DistanceLCH_Max(mul: TMultiplier): Single; inline;
function DistanceDeltaE_Max(mul: TMultiplier): Single; inline;
implementation
uses
Math, SysUtils, ColorConversion;
// ----| RGB |-----------------------------------------------------------------
function DistanceRGB(Color1: Pointer; Color2: TColor; mul: TMultiplier): Single;
var
C1,C2: ColorRGB;
begin
C1 := PColorRGB(Color1)^;
C2 := ColorToRGB(Color2);
Result := Sqrt(Sqr((C1.R-C2.R) * mul[0]) + Sqr((C1.G-C2.G) * mul[1]) + Sqr((C1.B-C2.B) * mul[2]));
end;
function DistanceRGB_Max(mul: TMultiplier): Single;
begin
Result := Sqrt(Sqr(255 * mul[0]) + Sqr(255 * mul[1]) + Sqr(255 * mul[2]));
end;
// ----| HSV |-----------------------------------------------------------------
// Hue is weighted based on max saturation of the two colors:
// The "simple" solution causes a problem where two dark slightly saturated gray colors can have
// completely different hue's, causing the distance measure to be larger than what it should be.
function DistanceHSV(Color1: Pointer; Color2: TColor; mul: TMultiplier): Single;
var
C1,C2: ColorHSV;
deltaH: Single;
begin
C1 := PColorHSV(Color1)^;
C2 := ColorToHSV(Color2);
if (C1.S < 1.0e-10) or (C2.S < 1.0e-10) then // no saturation = gray (hue has no value here)
deltaH := 0
else begin
deltaH := Abs(C1.H - C2.H);
if deltaH >= 180 then deltaH := 360 - deltaH;
deltaH *= Max(C1.S, C2.S) / 100;
end;
Result := Sqrt(Sqr(deltaH * mul[0]) + Sqr((C1.S-C2.S) * mul[1]) + Sqr((C1.V-C2.V) * mul[2]));
end;
function DistanceHSV_Max(mul: TMultiplier): Single;
begin
Result := Sqrt(Sqr(180 * mul[0]) + Sqr(100 * mul[1]) + Sqr(100 * mul[2]));
end;
// ----| HSL |-----------------------------------------------------------------
// Hue is weighted based on max saturation of the two colors:
// The "simple" solution causes a problem where two dark slightly saturated gray colors can have
// completely different hue's, causing the distance measure to be larger than what it should be.
function DistanceHSL(Color1: Pointer; Color2: TColor; mul: TMultiplier): Single;
var
C1,C2: ColorHSL;
deltaH: Single;
begin
C1 := PColorHSL(Color1)^;
C2 := ColorToHSL(Color2);
if (C1.S < 1.0e-10) or (C2.S < 1.0e-10) then // no saturation = gray (hue has no value here)
deltaH := 0
else begin
deltaH := Abs(C1.H - C2.H);
if deltaH >= 180 then deltaH := 360 - deltaH;
deltaH *= Max(C1.S, C2.S) / 100;
end;
Result := Sqrt(Sqr(deltaH * mul[0]) + Sqr((C1.S-C2.S) * mul[1]) + Sqr((C1.L-C2.L) * mul[2]));
end;
function DistanceHSL_Max(mul: TMultiplier): Single;
begin
Result := Sqrt(Sqr(180 * mul[0]) + Sqr(100 * mul[1]) + Sqr(100 * mul[2]));
end;
// ----| XYZ |-----------------------------------------------------------------
function DistanceXYZ(Color1:Pointer; Color2:TColor; mul:TMultiplier): Single;
var C1,C2: ColorXYZ;
begin
C1 := PColorXYZ(Color1)^;
C2 := ColorToXYZ(Color2);
Result := Sqrt(Sqr((C1.X-C2.X) * mul[0]) + Sqr((C1.Y-C2.Y) * mul[1]) + Sqr((C1.Z-C2.Z) * mul[2]));
end;
function DistanceXYZ_Max(mul:TMultiplier): Single;
begin
Result := Sqrt(Sqr(100 * mul[0]) + Sqr(100 * mul[1]) + Sqr(100 * mul[2]));
end;
// ----| LAB |-----------------------------------------------------------------
function DistanceLAB(Color1:Pointer; Color2:TColor; mul:TMultiplier): Single;
var C1,C2: ColorLAB;
begin
C1 := PColorLAB(Color1)^;
C2 := ColorToLAB(Color2);
Result := Sqrt(Sqr((C1.L-C2.L) * mul[0]) + Sqr((C1.A-C2.A) * mul[1]) + Sqr((C1.B-C2.B) * mul[2]));
end;
function DistanceLAB_Max(mul:TMultiplier): Single;
begin
Result := Sqrt(Sqr(100 * mul[0]) + Sqr(200 * mul[1]) + Sqr(200 * mul[2]));
end;
// ----| LCH |-----------------------------------------------------------------
// Hue is weighted based on Chroma:
// The "simple" solution causes a problem where two dark slightly saturated gray colors can have
// completely different hue's, causing the distance measure to be larger than what it should be.
function DistanceLCH(Color1:Pointer; Color2:TColor; mul:TMultiplier): Single;
var
C1,C2: ColorLCH;
deltaH: Single;
begin
C1 := PColorLCH(Color1)^;
C2 := ColorToLCH(Color2);
deltaH := Abs(C1.H - C2.H);
if deltaH >= 180 then deltaH := 360 - deltaH;
deltaH *= Max(C1.C, C2.C) / 100;
if (C1.C < 0.4) or (C2.C < 0.4) then // no chromaticity = gray (hue has no value here)
deltaH := 0
else begin
deltaH := Abs(C1.H - C2.H);
if deltaH >= 180 then deltaH := 360 - deltaH;
deltaH *= Max(C1.C, C2.C) / 142;
end;
Result := Sqrt(Sqr((C1.L-C2.L) * mul[0]) + Sqr((C1.C - C2.C) * mul[1]) + Sqr(deltaH * mul[2]));
end;
function DistanceLCH_Max(mul:TMultiplier): Single;
begin
Result := Sqrt(Sqr(100 * mul[0]) + Sqr(142 * mul[1]) + Sqr(180 * mul[2]));
end;
// ----| DeltaE |--------------------------------------------------------------
function DistanceDeltaE(Color1:Pointer; Color2:TColor; mul:TMultiplier): Single;
var
C1,C2: ColorLAB;
xc1,xc2,xdl,xdc,xde,xdh,xsc,xsh: Single;
begin
C1 := PColorLAB(Color1)^;
C2 := ColorToLAB(Color2);
xc1 := Sqrt(Sqr(C1.a) + Sqr(C1.b));
xc2 := Sqrt(Sqr(C2.a) + Sqr(C2.b));
xdl := c2.L - c1.L;
xdc := xc2 - xc1;
xde := Sqrt(Sqr(c1.L - c2.L) + Sqr(c1.a - c2.A) + Sqr(c1.b - c2.B));
if Sqrt(xDE) > Sqrt(Abs(xDL)) + Sqrt(Abs(xDC)) then
xDH := Sqrt(Sqr(xDE) - Sqr(xDL) - Sqr(xDC))
else
xDH := 0;
xSC := 1 + (0.045 * (xC1+xC2)/2);
xSH := 1 + (0.015 * (xC1+xC2)/2);
xDC /= xSC;
xDH /= xSH;
Result := Sqrt(Sqr(xDL * mul[0]) + Sqr(xDC * mul[1]) + Sqr(xDH * mul[2]));
end;
function DistanceDeltaE_Max(mul:TMultiplier): Single;
var
c1,c2: ColorLAB;
xc1,xc2,xdl,xdc,xde,xdh,xsc,xsh: Single;
begin
c1.L := 0;
c1.A := -92;
c1.B := -113;
c2.L := 100;
c2.A := 92;
c2.B := 92;
xc1 := Sqrt(Sqr(C1.a) + Sqr(C1.b));
xc2 := Sqrt(Sqr(C2.a) + Sqr(C2.b));
xdl := c2.L - c1.L;
xdc := xc2 - xc1;
xde := Sqrt(Sqr(c1.L - c2.L) + Sqr(c1.a - c2.A) + Sqr(c1.b - c2.B));
if Sqrt(xDE) > Sqrt(Abs(xDL)) + Sqrt(Abs(xDC)) then
xDH := Sqrt(Sqr(xDE) - Sqr(xDL) - Sqr(xDC))
else
xDH := 0;
xSC := 1 + (0.045 * (xC1+xC2)/2);
xSH := 1 + (0.015 * (xC1+xC2)/2);
xDC /= xSC;
xDH /= xSH;
Result := Sqrt(Sqr(xDL * mul[0]) + Sqr(xDC * mul[1]) + Sqr(xDH * mul[2]));
end;
end.
|
// ***************************************************************************
//
// Delphi MVC Framework
//
// Copyright (c) 2010-2020 Daniele Teti and the DMVCFramework Team
//
// https://github.com/danieleteti/delphimvcframework
//
// Collaborators on this file:
// João Antônio Duarte (https://github.com/joaoduarte19)
//
// ***************************************************************************
//
// 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 MVCFramework.Middleware.StaticFiles;
interface
uses
MVCFramework,
MVCFramework.Commons,
System.Generics.Collections;
type
TMVCStaticFilesDefaults = class sealed
public const
/// <summary>
/// URL segment that represents the path to static files
/// </summary>
STATIC_FILES_PATH = '/static';
/// <summary>
/// Physical path of the root folder that contains the static files
/// </summary>
DOCUMENT_ROOT = '.\www';
/// <summary>
/// Default static file
/// </summary>
INDEX_DOCUMENT = 'index.html';
/// <summary>
/// Charset of static files
/// </summary>
STATIC_FILES_CONTENT_CHARSET = TMVCConstants.DEFAULT_CONTENT_CHARSET;
end;
TMVCStaticFilesMiddleware = class(TInterfacedObject, IMVCMiddleware)
private
fMediaTypes: TDictionary<string, string>;
fStaticFilesPath: string;
fDocumentRoot: string;
fIndexDocument: string;
fStaticFilesCharset: string;
fSPAWebAppSupport: Boolean;
procedure AddMediaTypes;
function IsStaticFileRequest(const APathInfo: string; out AFileName: string): Boolean;
function SendStaticFileIfPresent(const AContext: TWebContext; const AFileName: string): Boolean;
public
constructor Create(
const AStaticFilesPath: string = TMVCStaticFilesDefaults.STATIC_FILES_PATH;
const ADocumentRoot: string = TMVCStaticFilesDefaults.DOCUMENT_ROOT;
const AIndexDocument: string = TMVCStaticFilesDefaults.INDEX_DOCUMENT;
const ASPAWebAppSupport: Boolean = True;
const AStaticFilesCharset: string = TMVCStaticFilesDefaults.STATIC_FILES_CONTENT_CHARSET);
destructor Destroy; override;
procedure OnBeforeRouting(AContext: TWebContext; var AHandled: Boolean);
procedure OnBeforeControllerAction(AContext: TWebContext; const AControllerQualifiedClassName: string;
const AActionName: string; var AHandled: Boolean);
procedure OnAfterControllerAction(AContext: TWebContext; const AActionName: string; const AHandled: Boolean);
procedure OnAfterRouting(AContext: TWebContext; const AHandled: Boolean);
end;
implementation
uses
System.SysUtils,
System.NetEncoding,
System.IOUtils, System.Classes;
{ TMVCStaticFilesMiddleware }
procedure TMVCStaticFilesMiddleware.AddMediaTypes;
begin
fMediaTypes.Add('.html', TMVCMediaType.TEXT_HTML);
fMediaTypes.Add('.htm', TMVCMediaType.TEXT_HTML);
fMediaTypes.Add('.txt', TMVCMediaType.TEXT_PLAIN);
fMediaTypes.Add('.text', TMVCMediaType.TEXT_PLAIN);
fMediaTypes.Add('.csv', TMVCMediaType.TEXT_CSV);
fMediaTypes.Add('.css', TMVCMediaType.TEXT_CSS);
fMediaTypes.Add('.js', TMVCMediaType.TEXT_JAVASCRIPT);
fMediaTypes.Add('.jpg', TMVCMediaType.IMAGE_JPEG);
fMediaTypes.Add('.jpeg', TMVCMediaType.IMAGE_JPEG);
fMediaTypes.Add('.jpe', TMVCMediaType.IMAGE_JPEG);
fMediaTypes.Add('.png', TMVCMediaType.IMAGE_PNG);
fMediaTypes.Add('.ico', TMVCMediaType.IMAGE_X_ICON);
fMediaTypes.Add('.appcache', TMVCMediaType.TEXT_CACHEMANIFEST);
fMediaTypes.Add('.svg', TMVCMediaType.IMAGE_SVG_XML);
fMediaTypes.Add('.svgz', TMVCMediaType.IMAGE_SVG_XML);
fMediaTypes.Add('.gif', TMVCMediaType.IMAGE_GIF);
end;
constructor TMVCStaticFilesMiddleware.Create(
const AStaticFilesPath: string = TMVCStaticFilesDefaults.STATIC_FILES_PATH;
const ADocumentRoot: string = TMVCStaticFilesDefaults.DOCUMENT_ROOT;
const AIndexDocument: string = TMVCStaticFilesDefaults.INDEX_DOCUMENT;
const ASPAWebAppSupport: Boolean = True;
const AStaticFilesCharset: string = TMVCStaticFilesDefaults.STATIC_FILES_CONTENT_CHARSET);
begin
inherited Create;
fStaticFilesPath := AStaticFilesPath;
fDocumentRoot := TPath.Combine(AppPath, ADocumentRoot);
fIndexDocument := AIndexDocument;
fStaticFilesCharset := AStaticFilesCharset;
fSPAWebAppSupport := ASPAWebAppSupport;
fMediaTypes := TDictionary<string, string>.Create;
AddMediaTypes;
end;
destructor TMVCStaticFilesMiddleware.Destroy;
begin
fMediaTypes.Free;
inherited Destroy;
end;
function TMVCStaticFilesMiddleware.IsStaticFileRequest(const APathInfo: string; out AFileName: string): Boolean;
begin
Result := (not fDocumentRoot.IsEmpty) and (TMVCStaticContents.IsStaticFile(fDocumentRoot, APathInfo, AFileName));
end;
procedure TMVCStaticFilesMiddleware.OnAfterControllerAction(AContext: TWebContext; const AActionName: string;
const AHandled: Boolean);
begin
// do nothing
end;
procedure TMVCStaticFilesMiddleware.OnAfterRouting(AContext: TWebContext; const AHandled: Boolean);
begin
// do nothing
end;
procedure TMVCStaticFilesMiddleware.OnBeforeControllerAction(AContext: TWebContext; const AControllerQualifiedClassName,
AActionName: string; var AHandled: Boolean);
begin
// do nothing
end;
procedure TMVCStaticFilesMiddleware.OnBeforeRouting(AContext: TWebContext; var AHandled: Boolean);
var
lPathInfo: string;
lFileName: string;
begin
lPathInfo := AContext.Request.PathInfo;
if not lPathInfo.StartsWith(fStaticFilesPath, True) then
begin
AHandled := False;
Exit;
end;
{
If user ask for
www.server.it/folder
the browser is redirected to
www.server.it/folder/
}
if SameText(lPathInfo, fStaticFilesPath) then
begin
if (not lPathInfo.EndsWith('/')) and (not fIndexDocument.IsEmpty) then
begin
AContext.Response.StatusCode := HTTP_STATUS.MovedPermanently;
AContext.Response.CustomHeaders.Values['Location'] := lPathInfo + '/';
AHandled := True;
Exit;
end;
end;
if not((fStaticFilesPath = '/') or (fStaticFilesPath = '')) then
begin
lPathInfo := lPathInfo.Remove(0, fStaticFilesPath.Length);
end;
if not fIndexDocument.IsEmpty then
begin
if (lPathInfo = '/') or (lPathInfo = '') then
begin
lFileName := TPath.GetFullPath(TPath.Combine(fDocumentRoot, fIndexDocument));
AHandled := SendStaticFileIfPresent(AContext, lFileName);
end;
end;
if (not AHandled) and (IsStaticFileRequest(lPathInfo, lFileName)) then
begin
AHandled := SendStaticFileIfPresent(AContext, lFileName);
end;
// if (not AHandled) and lPathInfo.EndsWith('favicon.ico') then
// begin
// AContext.Response.SetContentStream(TBytesStream.Create(TNetEncoding.Base64.DecodeStringToBytes(DMVC_FAVICON)),
// TMVCMediaType.IMAGE_X_ICON);
// AHandled := True;
// end;
if (not AHandled) and fSPAWebAppSupport and AContext.Request.ClientPreferHTML and (not fIndexDocument.IsEmpty) then
begin
lFileName := TPath.GetFullPath(TPath.Combine(fDocumentRoot, fIndexDocument));
AHandled := SendStaticFileIfPresent(AContext, lFileName);
end;
end;
function TMVCStaticFilesMiddleware.SendStaticFileIfPresent(const AContext: TWebContext;
const AFileName: string): Boolean;
var
lContentType: string;
begin
Result := False;
if TFile.Exists(AFileName) then
begin
if fMediaTypes.TryGetValue(LowerCase(ExtractFileExt(AFileName)), lContentType) then
begin
lContentType := BuildContentType(lContentType, fStaticFilesCharset);
end
else
begin
lContentType := BuildContentType(TMVCMediaType.APPLICATION_OCTETSTREAM, '');
end;
TMVCStaticContents.SendFile(AFileName, lContentType, AContext);
Result := True;
end;
end;
end.
|
{
pi / 4 = 4 * arctan(1 / 5) - arctan(1 / 239)
arctan(x) = x - x^3 / 3 + x^5 / 5 - x^7 / 7 + ..
}
program PiBench;
{$mode delphi}
uses
SysUtils, PiCalcs, tfNumerics;
const
MillisPerDay = 24 * 60 * 60 * 1000;
var
StartTime: TDateTime;
ElapsedMillis: Integer;
PiValue: BigCardinal;
S: string;
begin
// ReportMemoryLeaksOnShutdown:= True;
try
Writeln('Benchmark test started ...');
StartTime:= Now;
PiValue:= CalcPi;
ElapsedMillis:= Round((Now - StartTime) * MillisPerDay);
S:= PiValue.ToString;
Writeln('Pi = ', S[1] + '.' + Copy(S, 2, Length(S) - 1));
PiValue.Free;
Writeln;
Writeln('Time elapsed: ', ElapsedMillis, ' ms.');
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.
|
unit UniARC;
interface
{$IFNDEF AUTOREFCOUNT}
type
R<T : class> =record
private
GuardRef : IUnknown;
public
function O : T; inline;
class operator Implicit(a: T): R<T>; inline;
class operator Implicit(a: R<T>): T; inline;
class operator Equal(a, b: R<T>) : Boolean; inline;
class operator NotEqual(a, b: R<T>) : Boolean; inline;
class operator Equal(a : R<T>; b: Pointer) : Boolean; inline;
class operator NotEqual(a : R<T>; b: Pointer) : Boolean; inline;
class operator Equal(a : R<T>; b: T) : Boolean; inline;
class operator NotEqual(a : R<T>; b: T) : Boolean; inline;
class operator Positive(a: R<T>): T; inline;
end;
WR<T : class> =record
private
DataRef : IUnknown;
public
function O : T; inline;
class operator Implicit(a: WR<T>): R<T>; inline;
class operator Implicit(a: R<T>): WR<T>; inline;
class operator Equal(a, b: WR<T>) : Boolean; inline;
class operator NotEqual(a, b: WR<T>) : Boolean; inline;
class operator Equal(a : WR<T>; b: Pointer) : Boolean; inline;
class operator NotEqual(a : WR<T>; b: Pointer) : Boolean; inline;
class operator Equal(a : WR<T>; b: T) : Boolean; inline;
class operator NotEqual(a : WR<T>; b: T) : Boolean; inline;
class operator Equal(a : WR<T>; b: R<T>) : Boolean; inline;
class operator NotEqual(a : WR<T>; b: R<T>) : Boolean; inline;
class operator Positive(a: WR<T>): T; inline;
end;
__TGuard<T : class> = class(TInterfacedObject)
obj : T;
DataRef : IUnknown;
constructor Create(a : T);
destructor Destroy; override;
end;
__TGuardData<T : class> = class(TInterfacedObject)
Guard : __TGuard<T>;
constructor Create(G : __TGuard<T>);
end;
{$ELSE}
type
R<T : class> =record
private
obj : T;
public
function O : T; inline;
class operator Implicit(a: T): R<T>; inline;
class operator Implicit(a: R<T>): T; inline;
class operator Equal(a, b: R<T>) : Boolean; inline;
class operator NotEqual(a, b: R<T>) : Boolean; inline;
class operator Equal(a : R<T>; b: Pointer) : Boolean; inline;
class operator NotEqual(a : R<T>; b: Pointer) : Boolean; inline;
class operator Equal(a : R<T>; b: T) : Boolean; inline;
class operator NotEqual(a : R<T>; b: T) : Boolean; inline;
class operator Positive(a: R<T>): T; inline;
end;
WR<T : class> =record
private
[WEAK] obj : T;
public
function O : T; inline;
class operator Implicit(a: WR<T>): R<T>; inline;
class operator Implicit(a: R<T>): WR<T>; inline;
class operator Equal(a, b: WR<T>) : Boolean; inline;
class operator NotEqual(a, b: WR<T>) : Boolean; inline;
class operator Equal(a : WR<T>; b: Pointer) : Boolean; inline;
class operator NotEqual(a : WR<T>; b: Pointer) : Boolean; inline;
class operator Equal(a : WR<T>; b: T) : Boolean; inline;
class operator NotEqual(a : WR<T>; b: T) : Boolean; inline;
class operator Equal(a : WR<T>; b: R<T>) : Boolean; inline;
class operator NotEqual(a : WR<T>; b: R<T>) : Boolean; inline;
class operator Positive(a: WR<T>): T; inline;
end;
{$ENDIF}
implementation
{$IFNDEF AUTOREFCOUNT}
{ Guard<T> }
class operator R<T>.Implicit(a: T): R<T>;
begin
if assigned(a) then Result.GuardRef := __TGuard<T>.Create(a)
else Result.GuardRef := nil;
end;
class operator R<T>.Equal(a, b: R<T>): Boolean;
begin
Result := a.GuardRef = b.GuardRef;
end;
class operator R<T>.Equal(a: R<T>; b:Pointer): Boolean;
begin
Result := Pointer(a.O)=b;
end;
class operator R<T>.Equal(a: R<T>; b: T): Boolean;
begin
Result := a.O = b;
end;
class operator R<T>.Implicit(a: R<T>): T;
begin
Result := a.O;
end;
class operator R<T>.NotEqual(a: R<T>; b: Pointer): Boolean;
begin
Result := Pointer(a.O)<>b;
end;
class operator R<T>.NotEqual(a, b: R<T>): Boolean;
begin
Result := a.GuardRef<>b.GuardRef;
end;
class operator R<T>.NotEqual(a: R<T>; b: T): Boolean;
begin
Result := a.O<>b;
end;
function R<T>.O: T;
begin
if GuardRef=nil then Result := nil
else Result := __TGuard<T>(GuardRef).obj;
end;
class operator R<T>.Positive(a: R<T>): T;
begin
Result := a.O;
end;
{ TGuard<T> }
constructor __TGuard<T>.Create(a: T);
begin
inherited Create;
obj := a;
end;
destructor __TGuard<T>.Destroy;
begin
if assigned(DataRef) then begin
__TGuardData<T>(DataRef).Guard := nil;
end;
obj.DisposeOf;
inherited;
end;
{ TWeakGuard<T> }
constructor __TGuardData<T>.Create(G : __TGuard<T>);
begin
inherited Create;
Guard := G;
end;
{ WG<T> }
class operator WR<T>.Implicit(a: WR<T>): R<T>;
begin
if assigned(a.DataRef) then
Result.GuardRef := __TGuardData<T>(a.DataRef).Guard
else Result.GuardRef := nil;
end;
class operator WR<T>.Equal(a, b: WR<T>): Boolean;
begin
Result := a.DataRef = b.DataRef;
end;
class operator WR<T>.Equal(a: WR<T>; b:Pointer): Boolean;
begin
Result := Pointer(a.O)=b;
end;
class operator WR<T>.Equal(a: WR<T>; b: T): Boolean;
begin
Result := a.O = b;
end;
class operator WR<T>.Equal(a: WR<T>; b: R<T>): Boolean;
begin
Result := a.O = b.O;
end;
class operator WR<T>.Implicit(a: R<T>): WR<T>;
begin
if assigned(a.GuardRef) then begin
if __TGuard<T>(a.GuardRef).DataRef=nil then
__TGuard<T>(a.GuardRef).DataRef := __TGuardData<T>
.Create(__TGuard<T>(a.GuardRef));
Result.DataRef := __TGuard<T>(a.GuardRef).DataRef;
end else Result.DataRef := nil;
end;
class operator WR<T>.NotEqual(a: WR<T>; b: Pointer): Boolean;
begin
Result := Pointer(a.O)<>b;
end;
class operator WR<T>.NotEqual(a, b: WR<T>): Boolean;
begin
Result := a.DataRef<>b.DataRef;
end;
class operator WR<T>.NotEqual(a: WR<T>; b: T): Boolean;
begin
Result := a.O<>b;
end;
class operator WR<T>.NotEqual(a: WR<T>; b: R<T>): Boolean;
begin
Result := a.O<>b.O;
end;
function WR<T>.O: T;
begin
if (DataRef=nil)or(__TGuardData<T>(DataRef).Guard=nil) then Result := nil
else Result := __TGuardData<T>(DataRef).Guard.obj;
end;
class operator WR<T>.Positive(a: WR<T>): T;
begin
Result := a.O;
end;
{$ELSE}
{ Guard<T> }
class operator R<T>.Implicit(a: T): R<T>;
begin
Result.obj := a;
end;
class operator R<T>.Equal(a, b: R<T>): Boolean;
begin
Result := a.obj = b.obj;
end;
class operator R<T>.Equal(a: R<T>; b: Pointer): Boolean;
begin
Result := Pointer(a.obj)=b;
end;
class operator R<T>.Equal(a: R<T>; b: T): Boolean;
begin
Result := a.obj = b;
end;
class operator R<T>.Implicit(a: R<T>): T;
begin
Result := a.O;
end;
class operator R<T>.NotEqual(a, b: R<T>): Boolean;
begin
Result := a.obj<>b.obj;
end;
class operator R<T>.NotEqual(a: R<T>; b: Pointer): Boolean;
begin
Result := Pointer(a.obj)<>b;
end;
class operator R<T>.NotEqual(a: R<T>; b: T): Boolean;
begin
Result := a.obj <>b;
end;
function R<T>.O: T;
begin
Result := obj;
end;
class operator R<T>.Positive(a: R<T>): T;
begin
Result := a.O;
end;
{ WG<T> }
class operator WR<T>.Implicit(a: WR<T>): R<T>;
begin
Result.obj := a.obj;
end;
class operator WR<T>.Equal(a, b: WR<T>): Boolean;
begin
Result := a.obj = b.obj;
end;
class operator WR<T>.Equal(a: WR<T>; b: Pointer): Boolean;
begin
Result := Pointer(a.obj) = b;
end;
class operator WR<T>.Equal(a: WR<T>; b: T): Boolean;
begin
Result := a.obj = b;
end;
class operator WR<T>.Equal(a: WR<T>; b: R<T>): Boolean;
begin
Result := a.obj = b.obj;
end;
class operator WR<T>.Implicit(a: R<T>): WR<T>;
begin
Result.obj := a.obj;
end;
class operator WR<T>.NotEqual(a, b: WR<T>): Boolean;
begin
Result := a.obj <> b.obj;
end;
class operator WR<T>.NotEqual(a: WR<T>; b: Pointer): Boolean;
begin
Result := Pointer(a.obj)<>b;
end;
class operator WR<T>.NotEqual(a: WR<T>; b: T): Boolean;
begin
Result := a.obj <>b;
end;
class operator WR<T>.NotEqual(a: WR<T>; b: R<T>): Boolean;
begin
Result := a.obj<>b.obj;
end;
function WR<T>.O: T;
begin
Result := obj;
end;
class operator WR<T>.Positive(a: WR<T>): T;
begin
Result := a.O;
end;
{$ENDIF}
end.
|
unit nscStatusBarOperationDef;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "Nemesis"
// Модуль: "w:/common/components/gui/Garant/Nemesis/nscStatusBarOperationDef.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi For F1::Nemesis::StatusBar::TnscStatusBarOperationDef
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\Nemesis\nscDefine.inc}
interface
{$If defined(Nemesis)}
uses
l3Interfaces
{$If not defined(NoVCM)}
,
vcmExternalInterfaces
{$IfEnd} //not NoVCM
{$If not defined(NoVCM)}
,
vcmInterfaces
{$IfEnd} //not NoVCM
,
nscNewInterfaces,
nscStatusBarItemDef
;
{$IfEnd} //Nemesis
{$If defined(Nemesis)}
type
TnscStatusBarOperationDef = class(TnscStatusBarItemDef {$If defined(Nemesis) AND not defined(NoVCM)}, InscStatusBarOperationDef{$IfEnd} //Nemesis AND not NoVCM
)
private
// private fields
f_Operation : TvcmOpSelector;
protected
// realized methods
{$If defined(Nemesis) AND not defined(NoVCM)}
function Get_Operation: TvcmOpSelector;
{$IfEnd} //Nemesis AND not NoVCM
public
// public methods
constructor Create(const anOperation: TvcmOpSelector;
aShowCaption: Boolean;
const aCaption: Il3CString;
aUseToolTip: Boolean;
aRequireAutoPopup: Boolean;
anAutoPopupTimeout: Cardinal;
aToolTipKind: TnscToolTipKind); reintroduce;
class function Make(const anOperation: TvcmOpSelector;
aShowCaption: Boolean;
const aCaption: Il3CString;
aUseToolTip: Boolean;
aRequireAutoPopup: Boolean;
anAutoPopupTimeout: Cardinal;
aToolTipKind: TnscToolTipKind): InscStatusBarOperationDef; reintroduce;
{* Сигнатура фабрики TnscStatusBarOperationDef.Make }
class function MakeS(const anOperation: TvcmOPID;
aShowCaption: Boolean;
const aCaption: TvcmStringID;
aUseToolTip: Boolean;
aRequireAutoPopup: Boolean;
anAutoPopupTimeout: Cardinal;
aToolTipKind: TnscToolTipKind): InscStatusBarOperationDef;
class function MakeSDefaultCaption(const anOperation: TvcmOPID;
aUseToolTip: Boolean;
aRequireAutoPopup: Boolean;
anAutoPopupTimeout: Cardinal;
aToolTipKind: TnscToolTipKind): InscStatusBarOperationDef;
class function MakeSNoCaption(const anOperation: TvcmOPID;
aUseToolTip: Boolean;
aRequireAutoPopup: Boolean;
anAutoPopupTimeout: Cardinal;
aToolTipKind: TnscToolTipKind): InscStatusBarOperationDef;
end;//TnscStatusBarOperationDef
{$IfEnd} //Nemesis
implementation
{$If defined(Nemesis)}
uses
Classes
{$If not defined(NoVCM)}
,
vcmBase
{$IfEnd} //not NoVCM
;
{$IfEnd} //Nemesis
{$If defined(Nemesis)}
// start class TnscStatusBarOperationDef
constructor TnscStatusBarOperationDef.Create(const anOperation: TvcmOpSelector;
aShowCaption: Boolean;
const aCaption: Il3CString;
aUseToolTip: Boolean;
aRequireAutoPopup: Boolean;
anAutoPopupTimeout: Cardinal;
aToolTipKind: TnscToolTipKind);
//#UC START# *4FEC4A26030E_49871E4F01AF_var*
//#UC END# *4FEC4A26030E_49871E4F01AF_var*
begin
//#UC START# *4FEC4A26030E_49871E4F01AF_impl*
inherited Create(aShowCaption, aCaption, aUseToolTip, aRequireAutoPopup, anAutoPopupTimeout, aToolTipKind);
f_Operation := anOperation;
//#UC END# *4FEC4A26030E_49871E4F01AF_impl*
end;//TnscStatusBarOperationDef.Create
class function TnscStatusBarOperationDef.Make(const anOperation: TvcmOpSelector;
aShowCaption: Boolean;
const aCaption: Il3CString;
aUseToolTip: Boolean;
aRequireAutoPopup: Boolean;
anAutoPopupTimeout: Cardinal;
aToolTipKind: TnscToolTipKind): InscStatusBarOperationDef;
var
l_Inst : TnscStatusBarOperationDef;
begin
l_Inst := Create(anOperation, aShowCaption, aCaption, aUseToolTip, aRequireAutoPopup, anAutoPopupTimeout, aToolTipKind);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;
class function TnscStatusBarOperationDef.MakeS(const anOperation: TvcmOPID;
aShowCaption: Boolean;
const aCaption: TvcmStringID;
aUseToolTip: Boolean;
aRequireAutoPopup: Boolean;
anAutoPopupTimeout: Cardinal;
aToolTipKind: TnscToolTipKind): InscStatusBarOperationDef;
//#UC START# *4FEC5B7B00CE_49871E4F01AF_var*
var
l_Op : TvcmOpSelector;
//#UC END# *4FEC5B7B00CE_49871E4F01AF_var*
begin
//#UC START# *4FEC5B7B00CE_49871E4F01AF_impl*
l_Op.rKind := vcm_okEntity;
l_Op.rID := anOperation;
Result := Make(l_Op, aShowCaption, vcmCStr(aCaption),
aUseToolTip, aRequireAutoPopup, anAutoPopupTimeout, aToolTipKind);
//#UC END# *4FEC5B7B00CE_49871E4F01AF_impl*
end;//TnscStatusBarOperationDef.MakeS
class function TnscStatusBarOperationDef.MakeSDefaultCaption(const anOperation: TvcmOPID;
aUseToolTip: Boolean;
aRequireAutoPopup: Boolean;
anAutoPopupTimeout: Cardinal;
aToolTipKind: TnscToolTipKind): InscStatusBarOperationDef;
//#UC START# *4FF59E080381_49871E4F01AF_var*
var
l_Op : TvcmOpSelector;
//#UC END# *4FF59E080381_49871E4F01AF_var*
begin
//#UC START# *4FF59E080381_49871E4F01AF_impl*
l_Op.rKind := vcm_okEntity;
l_Op.rID := anOperation;
Result := Make(l_Op, True, nil, aUseToolTip, aRequireAutoPopup, anAutoPopupTimeout, aToolTipKind);
//#UC END# *4FF59E080381_49871E4F01AF_impl*
end;//TnscStatusBarOperationDef.MakeSDefaultCaption
class function TnscStatusBarOperationDef.MakeSNoCaption(const anOperation: TvcmOPID;
aUseToolTip: Boolean;
aRequireAutoPopup: Boolean;
anAutoPopupTimeout: Cardinal;
aToolTipKind: TnscToolTipKind): InscStatusBarOperationDef;
//#UC START# *4FFAFB0B03CC_49871E4F01AF_var*
var
l_Op : TvcmOpSelector;
//#UC END# *4FFAFB0B03CC_49871E4F01AF_var*
begin
//#UC START# *4FFAFB0B03CC_49871E4F01AF_impl*
l_Op.rKind := vcm_okEntity;
l_Op.rID := anOperation;
Result := Make(l_Op, False, nil, aUseToolTip, aRequireAutoPopup, anAutoPopupTimeout, aToolTipKind);
//#UC END# *4FFAFB0B03CC_49871E4F01AF_impl*
end;//TnscStatusBarOperationDef.MakeSNoCaption
{$If defined(Nemesis) AND not defined(NoVCM)}
function TnscStatusBarOperationDef.Get_Operation: TvcmOpSelector;
//#UC START# *4FE9F49C0299_49871E4F01AFget_var*
//#UC END# *4FE9F49C0299_49871E4F01AFget_var*
begin
//#UC START# *4FE9F49C0299_49871E4F01AFget_impl*
Result := f_Operation;
//#UC END# *4FE9F49C0299_49871E4F01AFget_impl*
end;//TnscStatusBarOperationDef.Get_Operation
{$IfEnd} //Nemesis AND not NoVCM
{$IfEnd} //Nemesis
end. |
unit MdiChilds.CompareFiles;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MdiChilds.ProgressForm, MdiChilds.Reg,
MdiChilds.CustomDialog, Vcl.StdCtrls,
Vcl.ExtCtrls, GsDocument, Generics.Collections, StrUtils, Character;
type
TCompareOptions = set of TGsBaseElementAttributes;
type
TFmCompareFiles = class(TFmProcess)
edtLeft: TLabeledEdit;
edtRight: TLabeledEdit;
btnOpenLeft: TButton;
btnOpenRight: TButton;
OpenDialog: TOpenDialog;
procedure btnOpenLeftClick(Sender: TObject);
procedure btnOpenRightClick(Sender: TObject);
private
class procedure CopyListData(From: TList<TGsRow>; Dest: TStringList);
class procedure CreateReportRow(S: TStringList; Value: string);
protected
procedure DoOk(Sender: TObject; ProgressForm: TFmProgress;
var ShowMessage: Boolean); override;
public
class function CompareText(Left, Right: string; var Difference: string): Boolean;
class procedure CompareDocs(Left, Right: TGsDocument;
AOptions: TCompareOptions);
end;
var
FmCompareFiles: TFmCompareFiles;
implementation
uses
GlobalData;
{$R *.dfm}
{ TFmCompareFiles }
procedure TFmCompareFiles.btnOpenLeftClick(Sender: TObject);
begin
if OpenDialog.Execute then
edtLeft.Text := OpenDialog.FileName;
end;
procedure TFmCompareFiles.btnOpenRightClick(Sender: TObject);
begin
if OpenDialog.Execute then
edtRight.Text := OpenDialog.FileName;
end;
class procedure TFmCompareFiles.CompareDocs(Left, Right: TGsDocument;
AOptions: TCompareOptions);
var
SLeft, SRight: TStringList;
LLeft, LRight: TList<TGsRow>;
I: Integer;
RL, RR: TGsRow;
Index: Integer;
S: TStringList;
ReportRow: string;
Dif: string;
begin
S := TStringList.Create;
try
// 1. Сравниваем левый с правым
LLeft := Left.GetAll<TGsRow>;
try
LRight := Right.GetAll<TGsRow>;
try
SLeft := TStringList.Create;
try
CopyListData(LLeft, SLeft);
SRight := TStringList.Create;
try
CopyListData(LRight, SRight);
// Собственно сравнение
for I := 0 to SLeft.Count - 1 do
begin
RL := TGsRow(SLeft.Objects[I]);
Index := SRight.IndexOf(SLeft[I]);
if Index <> -1 then
begin
RR := TGsRow(SRight.Objects[Index]);
ReportRow := '';
if not CompareText(RL.FullCaption, RR.FullCaption, Dif) then
ReportRow := RL.Number(True)+#9+'Различное наименование'+#9+RL.FullCaption + #9 + RR.FullCaption;
if not CompareText(RL.Measure, RR.Measure, Dif) then
ReportRow := ReportRow + #9 + 'различный измеритель'+#9+RL.Measure + RR.Measure;
if ReportRow <> '' then
CreateReportRow(S, ReportRow);
end
else
CreateReportRow(S, Format('Расценка не найдена в (%s)' + #9 +
'%s', [ExtractFileName(Right.FileName), SLeft[I]]));
end;
finally
SRight.Free;
end;
finally
SLeft.Free;
end;
finally
LRight.Free;
end;
finally
LLeft.Free;
end;
S.SaveToFile(TempDir + 'Протокол сравнения.txt');
finally
S.Free;
end;
end;
class function TFmCompareFiles.CompareText(Left, Right: string; var Difference: string): Boolean;
var
I: Integer;
NewLeft, NewRight: string;
begin
Left := StringReplace(ANSIUPPERCASE(Trim(Left)), ' ','',[rfReplaceAll]);
Right := StringReplace(ANSIUPPERCASE(Trim(Right)), ' ', '', [rfReplaceAll]);
Difference := '';
NewLeft := '';
NewRight := '';
for I := 1 to Length(Left) do
if TCharacter.IsLetterOrDigit(Left[I]) then
NewLeft := NewLeft + Left[I];
for I := 1 to Length(Right) do
if TCharacter.IsLetterOrDigit(Right[I]) then
NewRight := NewRight + Right[I];
Result := AnsiCompareText(NewLeft, NewRight) <> 0;
end;
class procedure TFmCompareFiles.CopyListData(From: TList<TGsRow>; Dest: TStringList);
var
I: Integer;
begin
Dest.Clear;
for I := 0 to From.Count - 1 do
Dest.AddObject(TGsRow(From[I]).Number(True), TGsRow(From[I]));
end;
class procedure TFmCompareFiles.CreateReportRow(S: TStringList; Value: string);
begin
s.Add(Value);
end;
procedure TFmCompareFiles.DoOk(Sender: TObject; ProgressForm: TFmProgress;
var ShowMessage: Boolean);
var
Left, Right: TGsDocument;
begin
ShowMessage := True;
Left := NewGsDocument;
try
Left.LoadFromFile(edtLeft.Text);
Right := NewGsDocument;
try
Right.LoadFromFile(edtRight.Text);
CompareDocs(Left, Right, [eaCaption, eaUnits]);
finally
Right.Free;
end;
finally
Left.Free;
end;
end;
begin
FormsRegistrator.RegisterForm(TFmCompareFiles,
'Сравнение 2 файлов (наим, измерители)', 'Протоколы', false,
dpkCustom, '/CMP2');
end.
|
unit TTSBRCHTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TTTSBRCHRecord = record
PLenderNum: String[4];
PBranchNum: String[8];
PModCount: Integer;
PBranchName: String[25];
PAddr1: String[30];
PAddr2: String[30];
PAddr3: String[30];
PPhone: String[30];
End;
TTTSBRCHBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TTTSBRCHRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEITTSBRCH = (TTSBRCHPrimaryKey);
TTTSBRCHTable = class( TDBISAMTableAU )
private
FDFLenderNum: TStringField;
FDFBranchNum: TStringField;
FDFModCount: TIntegerField;
FDFBranchName: TStringField;
FDFAddr1: TStringField;
FDFAddr2: TStringField;
FDFAddr3: TStringField;
FDFPhone: TStringField;
procedure SetPLenderNum(const Value: String);
function GetPLenderNum:String;
procedure SetPBranchNum(const Value: String);
function GetPBranchNum:String;
procedure SetPModCount(const Value: Integer);
function GetPModCount:Integer;
procedure SetPBranchName(const Value: String);
function GetPBranchName:String;
procedure SetPAddr1(const Value: String);
function GetPAddr1:String;
procedure SetPAddr2(const Value: String);
function GetPAddr2:String;
procedure SetPAddr3(const Value: String);
function GetPAddr3:String;
procedure SetPPhone(const Value: String);
function GetPPhone:String;
procedure SetEnumIndex(Value: TEITTSBRCH);
function GetEnumIndex: TEITTSBRCH;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TTTSBRCHRecord;
procedure StoreDataBuffer(ABuffer:TTTSBRCHRecord);
property DFLenderNum: TStringField read FDFLenderNum;
property DFBranchNum: TStringField read FDFBranchNum;
property DFModCount: TIntegerField read FDFModCount;
property DFBranchName: TStringField read FDFBranchName;
property DFAddr1: TStringField read FDFAddr1;
property DFAddr2: TStringField read FDFAddr2;
property DFAddr3: TStringField read FDFAddr3;
property DFPhone: TStringField read FDFPhone;
property PLenderNum: String read GetPLenderNum write SetPLenderNum;
property PBranchNum: String read GetPBranchNum write SetPBranchNum;
property PModCount: Integer read GetPModCount write SetPModCount;
property PBranchName: String read GetPBranchName write SetPBranchName;
property PAddr1: String read GetPAddr1 write SetPAddr1;
property PAddr2: String read GetPAddr2 write SetPAddr2;
property PAddr3: String read GetPAddr3 write SetPAddr3;
property PPhone: String read GetPPhone write SetPPhone;
published
property Active write SetActive;
property EnumIndex: TEITTSBRCH read GetEnumIndex write SetEnumIndex;
end; { TTTSBRCHTable }
procedure Register;
implementation
procedure TTTSBRCHTable.CreateFields;
begin
FDFLenderNum := CreateField( 'LenderNum' ) as TStringField;
FDFBranchNum := CreateField( 'BranchNum' ) as TStringField;
FDFModCount := CreateField( 'ModCount' ) as TIntegerField;
FDFBranchName := CreateField( 'BranchName' ) as TStringField;
FDFAddr1 := CreateField( 'Addr1' ) as TStringField;
FDFAddr2 := CreateField( 'Addr2' ) as TStringField;
FDFAddr3 := CreateField( 'Addr3' ) as TStringField;
FDFPhone := CreateField( 'Phone' ) as TStringField;
end; { TTTSBRCHTable.CreateFields }
procedure TTTSBRCHTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TTTSBRCHTable.SetActive }
procedure TTTSBRCHTable.SetPLenderNum(const Value: String);
begin
DFLenderNum.Value := Value;
end;
function TTTSBRCHTable.GetPLenderNum:String;
begin
result := DFLenderNum.Value;
end;
procedure TTTSBRCHTable.SetPBranchNum(const Value: String);
begin
DFBranchNum.Value := Value;
end;
function TTTSBRCHTable.GetPBranchNum:String;
begin
result := DFBranchNum.Value;
end;
procedure TTTSBRCHTable.SetPModCount(const Value: Integer);
begin
DFModCount.Value := Value;
end;
function TTTSBRCHTable.GetPModCount:Integer;
begin
result := DFModCount.Value;
end;
procedure TTTSBRCHTable.SetPBranchName(const Value: String);
begin
DFBranchName.Value := Value;
end;
function TTTSBRCHTable.GetPBranchName:String;
begin
result := DFBranchName.Value;
end;
procedure TTTSBRCHTable.SetPAddr1(const Value: String);
begin
DFAddr1.Value := Value;
end;
function TTTSBRCHTable.GetPAddr1:String;
begin
result := DFAddr1.Value;
end;
procedure TTTSBRCHTable.SetPAddr2(const Value: String);
begin
DFAddr2.Value := Value;
end;
function TTTSBRCHTable.GetPAddr2:String;
begin
result := DFAddr2.Value;
end;
procedure TTTSBRCHTable.SetPAddr3(const Value: String);
begin
DFAddr3.Value := Value;
end;
function TTTSBRCHTable.GetPAddr3:String;
begin
result := DFAddr3.Value;
end;
procedure TTTSBRCHTable.SetPPhone(const Value: String);
begin
DFPhone.Value := Value;
end;
function TTTSBRCHTable.GetPPhone:String;
begin
result := DFPhone.Value;
end;
procedure TTTSBRCHTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('LenderNum, String, 4, N');
Add('BranchNum, String, 8, N');
Add('ModCount, Integer, 0, N');
Add('BranchName, String, 25, N');
Add('Addr1, String, 30, N');
Add('Addr2, String, 30, N');
Add('Addr3, String, 30, N');
Add('Phone, String, 30, N');
end;
end;
procedure TTTSBRCHTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, LenderNum;BranchNum, Y, Y, N, N');
end;
end;
procedure TTTSBRCHTable.SetEnumIndex(Value: TEITTSBRCH);
begin
case Value of
TTSBRCHPrimaryKey : IndexName := '';
end;
end;
function TTTSBRCHTable.GetDataBuffer:TTTSBRCHRecord;
var buf: TTTSBRCHRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLenderNum := DFLenderNum.Value;
buf.PBranchNum := DFBranchNum.Value;
buf.PModCount := DFModCount.Value;
buf.PBranchName := DFBranchName.Value;
buf.PAddr1 := DFAddr1.Value;
buf.PAddr2 := DFAddr2.Value;
buf.PAddr3 := DFAddr3.Value;
buf.PPhone := DFPhone.Value;
result := buf;
end;
procedure TTTSBRCHTable.StoreDataBuffer(ABuffer:TTTSBRCHRecord);
begin
DFLenderNum.Value := ABuffer.PLenderNum;
DFBranchNum.Value := ABuffer.PBranchNum;
DFModCount.Value := ABuffer.PModCount;
DFBranchName.Value := ABuffer.PBranchName;
DFAddr1.Value := ABuffer.PAddr1;
DFAddr2.Value := ABuffer.PAddr2;
DFAddr3.Value := ABuffer.PAddr3;
DFPhone.Value := ABuffer.PPhone;
end;
function TTTSBRCHTable.GetEnumIndex: TEITTSBRCH;
var iname : string;
begin
result := TTSBRCHPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := TTSBRCHPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'TTS Tables', [ TTTSBRCHTable, TTTSBRCHBuffer ] );
end; { Register }
function TTTSBRCHBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..8] of string = ('LENDERNUM','BRANCHNUM','MODCOUNT','BRANCHNAME','ADDR1','ADDR2'
,'ADDR3','PHONE' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 8) and (flist[x] <> s) do inc(x);
if x <= 8 then result := x else result := 0;
end;
function TTTSBRCHBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftInteger;
4 : result := ftString;
5 : result := ftString;
6 : result := ftString;
7 : result := ftString;
8 : result := ftString;
end;
end;
function TTTSBRCHBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PLenderNum;
2 : result := @Data.PBranchNum;
3 : result := @Data.PModCount;
4 : result := @Data.PBranchName;
5 : result := @Data.PAddr1;
6 : result := @Data.PAddr2;
7 : result := @Data.PAddr3;
8 : result := @Data.PPhone;
end;
end;
end.
|
unit App;
{ Based on 016_metallic_torus.cpp example from oglplus (http://oglplus.org/) }
{$INCLUDE 'Sample.inc'}
interface
uses
System.Classes,
Neslib.Ooogles,
Neslib.FastMath,
Sample.App,
Sample.Geometry;
type
TMetallicTorusApp = class(TApplication)
private
FProgram: TGLProgram;
FVerts: TGLBuffer;
FNormals: TGLBuffer;
FIndices: TGLBuffer;
FUniProjectionMatrix: TGLUniform;
FUniCameraMatrix: TGLUniform;
FUniModelMatrix: TGLUniform;
FTorus: TTorusGeometry;
public
procedure Initialize; override;
procedure Render(const ADeltaTimeSec, ATotalTimeSec: Double); override;
procedure Shutdown; override;
procedure KeyDown(const AKey: Integer; const AShift: TShiftState); override;
procedure Resize(const AWidth, AHeight: Integer); override;
end;
implementation
uses
{$INCLUDE 'OpenGL.inc'}
System.UITypes,
Sample.Math;
{ TMetallicTorusApp }
procedure TMetallicTorusApp.Initialize;
var
VertexShader, FragmentShader: TGLShader;
VertAttr: TGLVertexAttrib;
Uniform: TGLUniform;
Color: array [0..7] of TVector4;
begin
VertexShader.New(TGLShaderType.Vertex,
'uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;'#10+
'attribute vec3 Position;'#10+
'attribute vec3 Normal;'#10+
'varying vec3 vertNormal;'#10+
'void main(void)'#10+
'{'#10+
' vertNormal = mat3(CameraMatrix) * mat3(ModelMatrix) * Normal;'#10+
' gl_Position = '#10+
' ProjectionMatrix *'#10+
' CameraMatrix *'#10+
' ModelMatrix *'#10+
' vec4(Position, 1.0);'#10+
'}');
VertexShader.Compile;
FragmentShader.New(TGLShaderType.Fragment,
'precision mediump float;'#10+
'uniform int ColorCount;'#10+
'uniform vec4 Color[8];'#10+
'varying vec3 vertNormal;'#10+
'vec3 ViewDir = vec3(0.0, 0.0, 1.0);'#10+
'vec3 TopDir = vec3(0.0, 1.0, 0.0);'#10+
'void main(void)'#10+
'{'#10+
' float k = dot(vertNormal, ViewDir);'#10+
' vec3 reflDir = 2.0 * k * vertNormal - ViewDir;'#10+
' float a = dot(reflDir, TopDir);'#10+
' vec3 reflColor = vec3(0.0);'#10+
' for(int i = 0; i != (ColorCount - 1); ++i)'#10+
' {'#10+
' if ((a<Color[i].a) && (a >= Color[i+1].a))'#10+
' {'#10+
' float m = '#10+
' (a - Color[i].a) / '#10+
' (Color[i+1].a - Color[i].a);'#10+
' reflColor = mix('#10+
' Color[i].rgb,'#10+
' Color[i+1].rgb,'#10+
' m'#10+
' );'#10+
' break;'#10+
' }'#10+
' }'#10+
' float i = max(dot(vertNormal, TopDir), 0.0);'#10+
' vec3 diffColor = vec3(i, i, i);'#10+
' gl_FragColor = vec4('#10+
' mix(reflColor, diffColor, 0.3 + i * 0.7),'#10+
' 1.0'#10+
' );'#10+
'}');
FragmentShader.Compile;
FProgram.New(VertexShader, FragmentShader);
FProgram.Link;
VertexShader.Delete;
FragmentShader.Delete;
FProgram.Use;
FTorus.Generate(72, 48, 1.0, 0.5);
{ Positions }
FVerts.New(TGLBufferType.Vertex);
FVerts.Bind;
FVerts.Data<TVector3>(FTorus.Positions);
VertAttr.Init(FProgram, 'Position');
VertAttr.SetConfig<TVector3>;
VertAttr.Enable;
{ Normals }
FNormals.New(TGLBufferType.Vertex);
FNormals.Bind;
FNormals.Data<TVector3>(FTorus.Normals);
VertAttr.Init(FProgram, 'Normal');
VertAttr.SetConfig<TVector3>;
VertAttr.Enable;
{ Indices }
FIndices.New(TGLBufferType.Index);
FIndices.Bind;
FIndices.Data<UInt16>(FTorus.Indices);
{ Don't need data anymore }
FTorus.Clear;
{ Setup the color gradient }
Uniform.Init(FProgram, 'ColorCount');
Uniform.SetValue(8);
Uniform.Init(FProgram, 'Color');
Color[0].Init(1.0, 1.0, 0.9, 1.00);
Color[1].Init(1.0, 0.9, 0.8, 0.97);
Color[2].Init(0.9, 0.7, 0.5, 0.95);
Color[3].Init(0.5, 0.5, 1.0, 0.95);
Color[4].Init(0.2, 0.2, 0.7, 0.00);
Color[5].Init(0.1, 0.1, 0.1, 0.00);
Color[6].Init(0.2, 0.2, 0.2,-0.10);
Color[7].Init(0.5, 0.5, 0.5,-1.00);
Uniform.SetValues(Color);
{ Other uniforms }
FUniProjectionMatrix.Init(FProgram, 'ProjectionMatrix');
FUniCameraMatrix.Init(FProgram, 'CameraMatrix');
FUniModelMatrix.Init(FProgram, 'ModelMatrix');
gl.ClearColor(0.1, 0.1, 0.1, 0);
gl.ClearDepth(1);
gl.Enable(TGLCapability.DepthTest);
gl.Enable(TGLCapability.CullFace);
gl.FrontFace(TGLFaceOrientation.CounterClockwise);
gl.CullFace(TGLFace.Back);
end;
procedure TMetallicTorusApp.KeyDown(const AKey: Integer; const AShift: TShiftState);
begin
{ Terminate app when Esc key is pressed }
if (AKey = vkEscape) then
Terminate;
end;
procedure TMetallicTorusApp.Render(const ADeltaTimeSec, ATotalTimeSec: Double);
var
CameraMatrix, ModelMatrix: TMatrix4;
begin
{ Clear the color and depth buffer }
gl.Clear([TGLClear.Color, TGLClear.Depth]);
{ Use the program }
FProgram.Use;
{ Set the matrix for camera orbiting the origin }
OrbitCameraMatrix(TVector3.Zero, 3.5, Radians(ATotalTimeSec * 35),
Radians(FastSin(Pi * ATotalTimeSec / 30) * 80), CameraMatrix);
FUniCameraMatrix.SetValue(CameraMatrix);
{ Update and render the torus }
ModelMatrix.InitRotationX(ATotalTimeSec * Pi * 0.5);
FUniModelMatrix.SetValue(ModelMatrix);
FTorus.DrawWithBoundIndexBuffer;
end;
procedure TMetallicTorusApp.Resize(const AWidth, AHeight: Integer);
var
ProjectionMatrix: TMatrix4;
begin
inherited;
ProjectionMatrix.InitPerspectiveFovRH(Radians(70), AWidth / AHeight, 1, 20);
FProgram.Use;
FUniProjectionMatrix.SetValue(ProjectionMatrix);
end;
procedure TMetallicTorusApp.Shutdown;
begin
{ Release resources }
FIndices.Delete;
FNormals.Delete;
FVerts.Delete;
FProgram.Delete;
end;
end.
|
unit uObservacao;
interface
uses uDM, System.SysUtils, FireDAC.Stan.Param,
Data.DB,
FireDAC.Comp.Client, uEnumerador, Vcl.Dialogs, uCadastroInterface, uObservacaoVO,
uGenericDAO, uFireDAC;
const CConsulta: string =
'SELECT Obs_Id, Obs_Codigo, Obs_Descricao, Obs_Ativo, Obs_Nome, Obs_Programa FROM Observacao ';
const CMENS_PADRAO: string = 'Já Existe uma Observação Padrão para este Programa!';
const CMENS_EMAIL_PADRAO: string = 'Já Existe uma Observação de Email Padrão para este Programa!';
type
TObservacao = class(TInterfacedObject, ICadastroInterface)
private
function RetornarNumerosDePadroes(APrograma, ATipo: Integer): Integer;
procedure ValidaPadrao(AIdObservacao, APrograma, ATipo: Integer);
procedure PersistePadrao(AObservacaoVO: TObservacaoVO);
procedure PersisteEmailPadrao(AObservacaoVO: TObservacaoVO);
public
procedure Novo(Programa, IdUsuario: Integer);
function Editar(Programa, IdUsuario: Integer): Boolean;
procedure Excluir(Programa, IdUsuario, Id: Integer);
function Filtrar(Campo, Texto, Ativo: string; Contem: Boolean = True): string;
function FiltrarPrograma(Campo, Texto, Ativo: string; StatusPrograma: Integer; Contem: Boolean = True): string;
function FiltrarCodigo(Codigo: Integer): string;
function LocalizarId(var Qry: TFDQuery; Id: integer): Boolean;
procedure LocalizarPadrao(var Qry: TFDQuery; APrograma: Integer);
procedure LocalizarEmailPadrao(var Qry: TFDQuery; APrograma: Integer);
procedure LocalizarCodigo(var Qry: TFDQuery; Codigo: integer);
procedure Salvar(Programa, IdUsuario: Integer); overload;
function Salvar(AObservacaoVO: TObservacaoVO; var AspObservacao: TFDStoredProc): Integer; overload;
function ProximoCodigo: Integer;
procedure Relatorio(Programa, IdUsuario: Integer);
function ProximoId: Integer;
end;
implementation
{ TProduto }
uses uUsuario;
function TObservacao.Editar(Programa, IdUsuario: Integer): Boolean;
var
usuario: TUsuario;
begin
usuario := TUsuario.Create;
try
Result := usuario.PermissaoEditar(Programa, IdUsuario);
finally
FreeAndNil(usuario);
end;
end;
procedure TObservacao.Excluir(Programa, IdUsuario, Id: Integer);
var
usuario: TUsuario;
obj: TFireDAC;
begin
usuario := TUsuario.Create;
try
usuario.PermissaoExcluir(Programa, IdUsuario);
finally
FreeAndNil(usuario);
end;
obj := TFireDAC.create;
try
obj.ExecutarSQL('DELETE FROM Observacao WHERE Obs_Id = ' + IntToStr(Id));
finally
FreeAndNil(obj);
end;
end;
function TObservacao.Filtrar(Campo, Texto, Ativo: string;
Contem: Boolean): string;
var
sConsulta: string;
sTexto: string;
begin
sTexto := '''' + Texto + '%''';
if Contem then
sTexto := '''%' + Texto + '%''';
sConsulta := CConsulta + ' WHERE ' + Campo + ' LIKE ' + sTexto;
if Ativo <> 'T' then
begin
if Ativo = 'A' then
sConsulta := sConsulta + ' AND Obs_Ativo = 1'
else
sConsulta := sConsulta + ' AND Obs_Ativo = 0';
end;
// sConsulta := sConsulta + ' ORDER BY ' + Campo;
Result := sConsulta;
end;
function TObservacao.FiltrarCodigo(Codigo: Integer): string;
begin
Result := CConsulta + ' WHERE Obs_Codigo = ' + Codigo.ToString();
end;
function TObservacao.FiltrarPrograma(Campo, Texto, Ativo: string;
StatusPrograma: Integer; Contem: Boolean): string;
var
sResult: string;
begin
sResult := Filtrar(Campo, Texto, Ativo, Contem);
if StatusPrograma > 0 then // Mostrar todos
sResult := sResult + ' AND Obs_Programa = ' + IntToStr(StatusPrograma);
Result := sResult;
end;
procedure TObservacao.LocalizarCodigo(var Qry: TFDQuery; Codigo: integer);
var
obj: TFireDAC;
begin
obj := TFireDAC.create;
try
obj.OpenSQL('SELECT Obs_Id, Obs_Ativo FROM Observacao WHERE Obs_Codigo = ' + IntToStr(Codigo));
if Codigo > 0 then
begin
if obj.Model.IsEmpty then
raise Exception.Create(CRegistroNaoEncontrado);
LocalizarId(Qry, obj.Model.FieldByName('Obs_Id').AsInteger);
if obj.Model.FieldByName('Obs_Ativo').AsBoolean = False then
begin
LocalizarId(Qry, 0);
raise Exception.Create(CRegistroInativo);
end;
end;
finally
FreeAndNil(obj);
end;
end;
procedure TObservacao.LocalizarEmailPadrao(var Qry: TFDQuery; APrograma: Integer);
var
obj: TFireDAC;
begin
obj := TFireDAC.create;
try
obj.Lista.Add('SELECT Obs_Id FROM Observacao');
obj.Lista.Add(' WHERE Obs_Programa = ' + APrograma.ToString());
obj.Lista.Add(' AND Obs_EmailPadrao = 1');
obj.Lista.Add(' AND Obs_Ativo = 1');
obj.OpenSQL();
LocalizarId(Qry, obj.Model.Fields[0].AsInteger);
finally
FreeAndNil(obj);
end;
end;
function TObservacao.LocalizarId(var Qry: TFDQuery; Id: integer): Boolean;
begin
Qry.Close;
Qry.Params[0].AsInteger := Id;
Qry.Open();
Result := (not Qry.IsEmpty);
end;
procedure TObservacao.LocalizarPadrao(var Qry: TFDQuery; APrograma: Integer);
var
obj: TFireDAC;
begin
obj := TFireDAC.create;
try
obj.Lista.Add('SELECT Obs_Id FROM Observacao');
obj.Lista.Add(' WHERE Obs_Programa = ' + APrograma.ToString());
obj.Lista.Add(' AND Obs_Padrao = 1');
obj.Lista.Add(' AND Obs_Ativo = 1');
obj.OpenSQL();
LocalizarId(Qry, obj.Model.Fields[0].AsInteger);
finally
FreeAndNil(obj);
end;
end;
procedure TObservacao.Novo(Programa, IdUsuario: Integer);
var
usuario: TUsuario;
begin
usuario := TUsuario.Create;
try
usuario.PermissaoIncluir(Programa, IdUsuario);
finally
FreeAndNil(usuario);
end;
end;
procedure TObservacao.PersisteEmailPadrao(AObservacaoVO: TObservacaoVO);
var
iPadroes: Integer;
begin
if AObservacaoVO.EmailPadrao then
begin
if AObservacaoVO.Id = 0 then
begin
iPadroes := RetornarNumerosDePadroes(AObservacaoVO.Programa, 2);
if iPadroes > 0 then
raise Exception.Create(CMENS_EMAIL_PADRAO);
end
else
ValidaPadrao(AObservacaoVO.Id, AObservacaoVO.Programa, 2);
end;
end;
procedure TObservacao.PersistePadrao(AObservacaoVO: TObservacaoVO);
var
iPadroes: Integer;
begin
if AObservacaoVO.Padrao then
begin
if AObservacaoVO.Id = 0 then
begin
iPadroes := RetornarNumerosDePadroes(AObservacaoVO.Programa, 1);
if iPadroes > 0 then
raise Exception.Create(CMENS_PADRAO);
end
else
ValidaPadrao(AObservacaoVO.Id, AObservacaoVO.Programa, 1);
end;
end;
function TObservacao.ProximoCodigo: Integer;
var
obj: TFireDAC;
begin
obj := TFireDAC.create;
try
obj.OpenSQL('SELECT MAX(Obs_Codigo) FROM Observacao');
Result := obj.Model.Fields[0].AsInteger + 1;
finally
FreeAndNil(obj);
end;
end;
function TObservacao.ProximoId: Integer;
var
obj: TFireDAC;
begin
obj := TFireDAC.create;
try
obj.OpenSQL('SELECT IDENT_CURRENT(''Observacao'')');
Result := obj.Model.Fields[0].AsInteger + 1;
finally
FreeAndNil(obj);
end;
end;
procedure TObservacao.Relatorio(Programa, IdUsuario: Integer);
var
usuario: TUsuario;
begin
usuario := TUsuario.Create;
try
usuario.PermissaoRelatorio(Programa, IdUsuario);
finally
FreeAndNil(usuario);
end;
end;
function TObservacao.RetornarNumerosDePadroes(APrograma, ATipo: Integer): Integer;
var
obj: TFireDAC;
begin
{
Parametro ATipo:
1 - Obs_Padrao
2 _ Obs_EmailPadrao
}
obj := TFireDAC.create;
try
obj.Lista.Add('SELECT COUNT(Obs_Codigo) FROM Observacao ');
obj.Lista.Add(' WHERE Obs_Programa = ' + IntToStr(APrograma));
if ATipo = 1 then
obj.Lista.Add(' AND Obs_Padrao = 1')
else
obj.Lista.Add(' AND Obs_EmailPadrao = 1');
obj.OpenSQL();
Result := obj.Model.Fields[0].AsInteger;
finally
FreeAndNil(obj);
end;
end;
function TObservacao.Salvar(AObservacaoVO: TObservacaoVO; var AspObservacao: TFDStoredProc): Integer;
begin
if AObservacaoVO.Nome.Trim = '' then
raise Exception.Create('Informe o Nome da Observação!');
if AObservacaoVO.Descricao.Trim = '' then
raise Exception.Create('Informe a Descrição da Observação!');
PersistePadrao(AObservacaoVO);
PersisteEmailPadrao(AObservacaoVO);
Result := TGenericDAO.Save<TObservacaoVO>(AObservacaoVO);
{TODO: Excluir procedimento do banco}
// sIU := 'U';
// if AObservacaoVO.Id = 0 then
// sIU := 'I';
// try
// AspObservacao.Close;
// AspObservacao.ParamByName('@IU').AsString := sIU;
// AspObservacao.ParamByName('@Id').AsInteger := AObservacaoVO.Id;
// AspObservacao.ParamByName('@Codigo').AsInteger := AObservacaoVO.Codigo;
// AspObservacao.ParamByName('@Descricao').AsMemo := AObservacaoVO.Descricao;
// AspObservacao.ParamByName('@Ativo').AsBoolean := AObservacaoVO.Ativo;
// AspObservacao.ParamByName('@Nome').AsString := AObservacaoVO.Nome;
// AspObservacao.ParamByName('@Padrao').AsBoolean := AObservacaoVO.Padrao;
// AspObservacao.ParamByName('@Programa').AsInteger := AObservacaoVO.Programa;
// AspObservacao.ExecProc();
//
// Result := AspObservacao.ParamByName('@RetornoId').AsInteger;
// except
// On E: Exception do
// begin
// dm.Roolback();
// raise Exception.Create(E.Message);
// end;
// end;
end;
procedure TObservacao.ValidaPadrao(AIdObservacao, APrograma, ATipo: Integer);
var
iId: Integer;
obj: TFireDAC;
begin
{
Parametro ATipo:
1 - Obs_Padrao
2 _ Obs_EmailPadrao
}
obj := TFireDAC.create;
try
obj.Lista.Add('SELECT Obs_Id FROM Observacao ');
obj.Lista.Add(' WHERE Obs_Programa = ' + IntToStr(APrograma));
if ATipo = 1 then
obj.Lista.Add(' AND Obs_Padrao = 1')
else
obj.Lista.Add(' AND Obs_EmailPadrao = 1');
obj.Lista.Add(' AND Obs_Id <> ' + IntToStr(AIdObservacao));
obj.OpenSQL();
iId := obj.Model.Fields[0].AsInteger;
finally
FreeAndNil(obj);
end;
if (iId > 0) and (ATipo = 1) then
raise Exception.Create(CMENS_PADRAO);
if (iId > 0) and (ATipo = 2) then
raise Exception.Create(CMENS_EMAIL_PADRAO);
end;
procedure TObservacao.Salvar(Programa, IdUsuario: Integer);
var
usuario: TUsuario;
begin
usuario := TUsuario.Create;
try
usuario.PermissaoEditar(Programa, IdUsuario);
finally
FreeAndNil(usuario);
end;
end;
end.
|
unit NewCheckListBox;
{ TNewCheckListBox by Martijn Laan for My Inno Setup Extensions
See http://isx.wintax.nl/ for more information
Based on TPBCheckListBox by Patrick Brisacier and TCheckListBox by Borland
Group item support, child item support, exclusive item support,
ShowLines support and 'WantTabs mode' by Alex Yackimoff.
Note: TNewCheckListBox uses Items.Objects to store the item state. Don't use
Item.Objects yourself, use ItemObject instead.
$jrsoftware: issrc/Components/NewCheckListBox.pas,v 1.57 2009/03/25 11:47:32 mlaan Exp $
}
{$IFDEF VER90}
{$DEFINE DELPHI2}
{$ENDIF}
{$IFDEF VER200}
{$DEFINE DELPHI2009}
{$ENDIF}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, UxThemeISX;
const
WM_UPDATEUISTATE = $0128;
type
TItemType = (itGroup, itCheck, itRadio);
TCheckBoxState2 = (cb2Normal, cb2Hot, cb2Pressed, cb2Disabled);
TItemState = class (TObject)
public
Enabled: Boolean;
HasInternalChildren: Boolean;
CheckWhenParentChecked: Boolean;
IsLastChild: Boolean;
ItemType: TItemType;
Level: Byte;
Obj: TObject;
State: TCheckBoxState;
SubItem: string;
ThreadCache: set of Byte;
MeasuredHeight: Integer;
end;
TCheckItemOperation = (coUncheck, coCheck, coCheckWithChildren);
TEnumChildrenProc = procedure(Index: Integer; HasChildren: Boolean; Ext: Longint) of object;
TNewCheckListBox = class (TCustomListBox)
private
FAccObjectInstance: TObject;
FCaptureIndex: Integer;
FSpaceDown: Boolean;
FCheckHeight: Integer;
FCheckWidth: Integer;
FFormFocusChanged: Boolean;
FFlat: Boolean;
FLastMouseMoveIndex: Integer;
FMinItemHeight: Integer;
FOffset: Integer;
FOnClickCheck: TNotifyEvent;
FRequireRadioSelection: Boolean;
FShowLines: Boolean;
FStateList: TList;
FWantTabs: Boolean;
FThemeData: HTHEME;
FThreadsUpToDate: Boolean;
FHotIndex: Integer;
FDisableItemStateDeletion: Integer;
FWheelAccum: Integer;
FUseRightToLeft: Boolean;
procedure UpdateThemeData(const Close, Open: Boolean);
function CanFocusItem(Item: Integer): Boolean;
function CheckPotentialRadioParents(Index, ALevel: Integer): Boolean;
procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR;
procedure CMEnter(var Message: TCMEnter); message CM_ENTER;
procedure CMExit(var Message: TCMExit); message CM_EXIT;
procedure CMFocusChanged(var Message: TCMFocusChanged); message CM_FOCUSCHANGED;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure CMWantSpecialKey(var Message: TMessage); message CM_WANTSPECIALKEY;
procedure CNDrawItem(var Message: TWMDrawItem); message CN_DRAWITEM;
procedure EndCapture(Cancel: Boolean);
function AddItem2(AType: TItemType; const ACaption, ASubItem: string;
ALevel: Byte; AChecked, AEnabled, AHasInternalChildren,
ACheckWhenParentChecked: Boolean; AObject: TObject): Integer;
function FindAccel(VK: Word): Integer;
function FindCheckedSibling(const AIndex: Integer): Integer;
function FindNextItem(StartFrom: Integer; GoForward,
SkipUncheckedRadios: Boolean): Integer;
function GetItemState(Index: Integer): TItemState;
procedure InvalidateCheck(Index: Integer);
function RemeasureItem(Index: Integer): Integer;
procedure Toggle(Index: Integer);
procedure UpdateScrollRange;
procedure LBDeleteString(var Message: TMessage); message LB_DELETESTRING;
procedure LBResetContent(var Message: TMessage); message LB_RESETCONTENT;
procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE;
procedure WMGetObject(var Message: TMessage); message $003D; //WM_GETOBJECT
procedure WMKeyDown(var Message: TWMKeyDown); message WM_KEYDOWN;
procedure WMMouseMove(var Message: TWMMouseMove); message WM_MOUSEMOVE;
procedure WMMouseWheel(var Message: TMessage); message $020A; //WM_MOUSEWHEEL
procedure WMNCHitTest(var Message: TWMNCHitTest); message WM_NCHITTEST;
procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS;
procedure WMSize(var Message: TWMSize); message WM_SIZE;
procedure WMThemeChanged(var Message: TMessage); message WM_THEMECHANGED;
procedure WMUpdateUIState(var Message: TMessage); message WM_UPDATEUISTATE;
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure CreateWnd; override;
procedure MeasureItem(Index: Integer; var Height: Integer); override;
procedure DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState);
override;
function GetCaption(Index: Integer): String;
function GetChecked(Index: Integer): Boolean;
function GetItemEnabled(Index: Integer): Boolean;
function GetLevel(Index: Integer): Byte;
function GetObject(Index: Integer): TObject;
function GetState(Index: Integer): TCheckBoxState;
function GetSubItem(Index: Integer): string;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure KeyUp(var Key: Word; Shift: TShiftState); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure UpdateHotIndex(NewHotIndex: Integer);
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
procedure SetCaption(Index: Integer; const Value: String);
procedure SetChecked(Index: Integer; const AChecked: Boolean);
procedure SetFlat(Value: Boolean);
procedure SetItemEnabled(Index: Integer; const AEnabled: Boolean);
procedure SetObject(Index: Integer; const AObject: TObject);
procedure SetOffset(AnOffset: Integer);
procedure SetShowLines(Value: Boolean);
procedure SetSubItem(Index: Integer; const ASubItem: String);
property ItemStates[Index: Integer]: TItemState read GetItemState;
public
constructor Create(AOwner: TComponent); override;
procedure CreateWindowHandle(const Params: TCreateParams); override;
destructor Destroy; override;
function AddCheckBox(const ACaption, ASubItem: string; ALevel: Byte;
AChecked, AEnabled, AHasInternalChildren, ACheckWhenParentChecked: Boolean;
AObject: TObject): Integer;
function AddGroup(const ACaption, ASubItem: string; ALevel: Byte;
AObject: TObject): Integer;
function AddRadioButton(const ACaption, ASubItem: string;
ALevel: Byte; AChecked, AEnabled: Boolean; AObject: TObject): Integer;
function CheckItem(const Index: Integer; const AOperation: TCheckItemOperation): Boolean;
procedure EnumChildrenOf(Item: Integer; Proc: TEnumChildrenProc; Ext: Longint);
function GetParentOf(Item: Integer): Integer;
procedure UpdateThreads;
property Checked[Index: Integer]: Boolean read GetChecked write SetChecked;
property ItemCaption[Index: Integer]: String read GetCaption write SetCaption;
property ItemEnabled[Index: Integer]: Boolean read GetItemEnabled write SetItemEnabled;
property ItemLevel[Index: Integer]: Byte read GetLevel;
property ItemObject[Index: Integer]: TObject read GetObject write SetObject;
property ItemSubItem[Index: Integer]: string read GetSubItem write SetSubItem;
property State[Index: Integer]: TCheckBoxState read GetState;
published
property Align;
property BorderStyle;
property Color;
property Ctl3D;
property DragCursor;
property DragMode;
property Enabled;
property Flat: Boolean read FFlat write SetFlat default False;
property Font;
property Items;
property MinItemHeight: Integer read FMinItemHeight write FMinItemHeight default 16;
property Offset: Integer read FOffset write SetOffset default 4;
property OnClick;
property OnClickCheck: TNotifyEvent read FOnClickCheck write FOnClickCheck;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property RequireRadioSelection: Boolean read FRequireRadioSelection write FRequireRadioSelection default False;
property ShowHint;
property ShowLines: Boolean read FShowLines write SetShowLines default True;
property TabOrder;
property Visible;
property WantTabs: Boolean read FWantTabs write FWantTabs default False;
end;
procedure Register;
implementation
uses
TmSchemaISX, {$IFDEF DELPHI2} Ole2 {$ELSE} ActiveX {$ENDIF}, BidiUtils{$IFDEF DELPHI2009}, Types{$ENDIF};
const
sRadioCantHaveDisabledChildren = 'Radio item cannot have disabled child items';
OBM_CHECKBOXES = 32759;
WM_CHANGEUISTATE = $0127;
WM_QUERYUISTATE = $0129;
UIS_SET = 1;
UIS_CLEAR = 2;
UIS_INITIALIZE = 3;
UISF_HIDEFOCUS = $1;
UISF_HIDEACCEL = $2;
DT_HIDEPREFIX = $00100000;
OBJID_CLIENT = $FFFFFFFC;
CHILDID_SELF = 0;
ROLE_SYSTEM_OUTLINE = $23;
ROLE_SYSTEM_STATICTEXT = $29;
ROLE_SYSTEM_CHECKBUTTON = $2c;
ROLE_SYSTEM_RADIOBUTTON = $2d;
STATE_SYSTEM_UNAVAILABLE = $1;
STATE_SYSTEM_CHECKED = $10;
STATE_SYSTEM_MIXED = $20;
EVENT_OBJECT_STATECHANGE = $800A;
IID_IUnknown: TGUID = (
D1:$00000000; D2:$0000; D3:$0000; D4:($C0,$00,$00,$00,$00,$00,$00,$46));
IID_IDispatch: TGUID = (
D1:$00020400; D2:$0000; D3:$0000; D4:($C0,$00,$00,$00,$00,$00,$00,$46));
IID_IAccessible: TGUID = (
D1:$618736e0; D2:$3c3d; D3:$11cf; D4:($81,$0c,$00,$aa,$00,$38,$9b,$71));
var
CanQueryUIState: Boolean;
type
TWinControlAccess = class (TWinControl);
{ Note: We have to use TVariantArg for Delphi 2 compat., because D2 passes
Variant parameters by reference (wrong), unlike D3+ which pass
Variant/OleVariant parameters by value }
NewOleVariant = TVariantArg;
NewWideString = Pointer;
TIUnknown = class
public
function QueryInterface(const iid: TIID; var obj): HRESULT; virtual; stdcall; abstract;
function AddRef: Longint; virtual; stdcall; abstract;
function Release: Longint; virtual; stdcall; abstract;
end;
TIDispatch = class(TIUnknown)
public
function GetTypeInfoCount(var ctinfo: Integer): HRESULT; virtual; stdcall; abstract;
function GetTypeInfo(itinfo: Integer; lcid: TLCID; var tinfo: ITypeInfo): HRESULT; virtual; stdcall; abstract;
function GetIDsOfNames(const iid: TIID; rgszNames: POleStrList;
cNames: Integer; lcid: TLCID; rgdispid: PDispIDList): HRESULT; virtual; stdcall; abstract;
function Invoke(dispIDMember: TDispID; const iid: TIID; lcid: TLCID;
flags: Word; var dispParams: TDispParams; varResult: PVariant;
excepInfo: PExcepInfo; argErr: PInteger): HRESULT; virtual; stdcall; abstract;
end;
TIAccessible = class(TIDispatch)
public
function get_accParent(var ppdispParent: IDispatch): HRESULT; virtual; stdcall; abstract;
function get_accChildCount(var pcountChildren: Integer): HRESULT; virtual; stdcall; abstract;
function get_accChild(varChild: NewOleVariant; var ppdispChild: IDispatch): HRESULT; virtual; stdcall; abstract;
function get_accName(varChild: NewOleVariant; var pszName: NewWideString): HRESULT; virtual; stdcall; abstract;
function get_accValue(varChild: NewOleVariant; var pszValue: NewWideString): HRESULT; virtual; stdcall; abstract;
function get_accDescription(varChild: NewOleVariant; var pszDescription: NewWideString): HRESULT; virtual; stdcall; abstract;
function get_accRole(varChild: NewOleVariant; var pvarRole: NewOleVariant): HRESULT; virtual; stdcall; abstract;
function get_accState(varChild: NewOleVariant; var pvarState: NewOleVariant): HRESULT; virtual; stdcall; abstract;
function get_accHelp(varChild: NewOleVariant; var pszHelp: NewWideString): HRESULT; virtual; stdcall; abstract;
function get_accHelpTopic(var pszHelpFile: NewWideString; varChild: NewOleVariant; var pidTopic: Integer): HRESULT; virtual; stdcall; abstract;
function get_accKeyboardShortcut(varChild: NewOleVariant; var pszKeyboardShortcut: NewWideString): HRESULT; virtual; stdcall; abstract;
function get_accFocus(var pvarID: NewOleVariant): HRESULT; virtual; stdcall; abstract;
function get_accSelection(var pvarChildren: NewOleVariant): HRESULT; virtual; stdcall; abstract;
function get_accDefaultAction(varChild: NewOleVariant; var pszDefaultAction: NewWideString): HRESULT; virtual; stdcall; abstract;
function accSelect(flagsSelect: Integer; varChild: NewOleVariant): HRESULT; virtual; stdcall; abstract;
function accLocation(var pxLeft: Integer; var pyTop: Integer; var pcxWidth: Integer;
var pcyHeight: Integer; varChild: NewOleVariant): HRESULT; virtual; stdcall; abstract;
function accNavigate(navDir: Integer; varStart: NewOleVariant; var pvarEnd: NewOleVariant): HRESULT; virtual; stdcall; abstract;
function accHitTest(xLeft: Integer; yTop: Integer; var pvarID: NewOleVariant): HRESULT; virtual; stdcall; abstract;
function accDoDefaultAction(varChild: NewOleVariant): HRESULT; virtual; stdcall; abstract;
function put_accName(varChild: NewOleVariant; const pszName: NewWideString): HRESULT; virtual; stdcall; abstract;
function put_accValue(varChild: NewOleVariant; const pszValue: NewWideString): HRESULT; virtual; stdcall; abstract;
end;
TAccObject = class(TIAccessible)
private
FControl: TNewCheckListBox;
FRefCount: Integer;
FStdAcc: TIAccessible;
{ TIUnknown }
function QueryInterface(const iid: TIID; var obj): HRESULT; override;
function AddRef: Longint; override;
function Release: Longint; override;
{ TIDispatch }
function GetTypeInfoCount(var ctinfo: Integer): HRESULT; override;
function GetTypeInfo(itinfo: Integer; lcid: TLCID; var tinfo: ITypeInfo): HRESULT; override;
function GetIDsOfNames(const iid: TIID; rgszNames: POleStrList;
cNames: Integer; lcid: TLCID; rgdispid: PDispIDList): HRESULT; override;
function Invoke(dispIDMember: TDispID; const iid: TIID; lcid: TLCID;
flags: Word; var dispParams: TDispParams; varResult: PVariant;
excepInfo: PExcepInfo; argErr: PInteger): HRESULT; override;
{ TIAccessible }
function get_accParent(var ppdispParent: IDispatch): HRESULT; override;
function get_accChildCount(var pcountChildren: Integer): HRESULT; override;
function get_accChild(varChild: NewOleVariant; var ppdispChild: IDispatch): HRESULT; override;
function get_accName(varChild: NewOleVariant; var pszName: NewWideString): HRESULT; override;
function get_accValue(varChild: NewOleVariant; var pszValue: NewWideString): HRESULT; override;
function get_accDescription(varChild: NewOleVariant; var pszDescription: NewWideString): HRESULT; override;
function get_accRole(varChild: NewOleVariant; var pvarRole: NewOleVariant): HRESULT; override;
function get_accState(varChild: NewOleVariant; var pvarState: NewOleVariant): HRESULT; override;
function get_accHelp(varChild: NewOleVariant; var pszHelp: NewWideString): HRESULT; override;
function get_accHelpTopic(var pszHelpFile: NewWideString; varChild: NewOleVariant; var pidTopic: Integer): HRESULT; override;
function get_accKeyboardShortcut(varChild: NewOleVariant; var pszKeyboardShortcut: NewWideString): HRESULT; override;
function get_accFocus(var pvarID: NewOleVariant): HRESULT; override;
function get_accSelection(var pvarChildren: NewOleVariant): HRESULT; override;
function get_accDefaultAction(varChild: NewOleVariant; var pszDefaultAction: NewWideString): HRESULT; override;
function accSelect(flagsSelect: Integer; varChild: NewOleVariant): HRESULT; override;
function accLocation(var pxLeft: Integer; var pyTop: Integer; var pcxWidth: Integer;
var pcyHeight: Integer; varChild: NewOleVariant): HRESULT; override;
function accNavigate(navDir: Integer; varStart: NewOleVariant; var pvarEnd: NewOleVariant): HRESULT; override;
function accHitTest(xLeft: Integer; yTop: Integer; var pvarID: NewOleVariant): HRESULT; override;
function accDoDefaultAction(varChild: NewOleVariant): HRESULT; override;
function put_accName(varChild: NewOleVariant; const pszName: NewWideString): HRESULT; override;
function put_accValue(varChild: NewOleVariant; const pszValue: NewWideString): HRESULT; override;
public
constructor Create(AControl: TNewCheckListBox);
destructor Destroy; override;
procedure ControlDestroying;
end;
function CoDisconnectObject(unk: TIUnknown; dwReserved: DWORD): HRESULT;
stdcall; external 'ole32.dll';
var
NotifyWinEventFunc: procedure(event: DWORD; hwnd: HWND; idObject: DWORD;
idChild: Longint); stdcall;
OleAccInited: BOOL;
OleAccAvailable: BOOL;
LresultFromObjectFunc: function(const riid: TGUID; wParam: WPARAM;
pUnk: TIUnknown): LRESULT; stdcall;
CreateStdAccessibleObjectFunc: function(hwnd: HWND; idObject: Longint;
const riidInterface: TGUID; var ppvObject: Pointer): HRESULT; stdcall;
function InitializeOleAcc: Boolean;
var
M: HMODULE;
begin
if not OleAccInited then begin
M := LoadLibrary('oleacc.dll');
if M <> 0 then begin
LresultFromObjectFunc := GetProcAddress(M, 'LresultFromObject');
CreateStdAccessibleObjectFunc := GetProcAddress(M, 'CreateStdAccessibleObject');
if Assigned(LresultFromObjectFunc) and
Assigned(CreateStdAccessibleObjectFunc) then
OleAccAvailable := True;
end;
OleAccInited := True;
end;
Result := OleAccAvailable;
end;
{ TNewCheckListBox }
constructor TNewCheckListBox.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
with TBitmap.Create do
begin
try
Handle := LoadBitmap(0, PChar(OBM_CHECKBOXES));
FCheckWidth := Width div 4;
FCheckHeight := Height div 3;
finally
Free;
end;
end;
FStateList := TList.Create;
FMinItemHeight := 16;
FOffset := 4;
FShowLines := True;
Style := lbOwnerDrawVariable;
FHotIndex := -1;
FCaptureIndex := -1;
end;
procedure TNewCheckListBox.CreateParams(var Params: TCreateParams);
begin
inherited;
FUseRightToLeft := SetBiDiStyles(Self, Params);
end;
procedure TNewCheckListBox.CreateWnd;
begin
{ TCustomListBox.CreateWnd causes a LB_RESETCONTENT message to be sent when
it's restoring FSaveItems. Increment FDisableItemStateDeletion so that
our LB_RESETCONTENT handler doesn't delete any item states. }
Inc(FDisableItemStateDeletion);
try
inherited;
finally
Dec(FDisableItemStateDeletion);
end;
end;
procedure TNewCheckListBox.UpdateThemeData(const Close, Open: Boolean);
begin
if Close then begin
if FThemeData <> 0 then begin
CloseThemeData(FThemeData);
FThemeData := 0;
end;
end;
if Open then begin
if UseThemes then
FThemeData := OpenThemeData(Handle, 'Button')
else
FThemeData := 0;
end;
end;
procedure TNewCheckListBox.CreateWindowHandle(const Params: TCreateParams);
begin
inherited CreateWindowHandle(Params);
UpdateThemeData(True, True);
end;
destructor TNewCheckListBox.Destroy;
var
I: Integer;
begin
if Assigned(FAccObjectInstance) then begin
{ Detach from FAccObjectInstance if someone still has a reference to it }
TAccObject(FAccObjectInstance).ControlDestroying;
FAccObjectInstance := nil;
end;
if Assigned(FStateList) then begin
for I := FStateList.Count-1 downto 0 do
TItemState(FStateList[I]).Free;
FStateList.Free;
end;
UpdateThemeData(True, False);
inherited Destroy;
end;
function TNewCheckListBox.AddCheckBox(const ACaption, ASubItem: string;
ALevel: Byte; AChecked, AEnabled, AHasInternalChildren,
ACheckWhenParentChecked: Boolean; AObject: TObject): Integer;
begin
if not AEnabled and CheckPotentialRadioParents(Items.Count, ALevel) then
raise Exception.Create(sRadioCantHaveDisabledChildren);
Result := AddItem2(itCheck, ACaption, ASubItem, ALevel, AChecked, AEnabled,
AHasInternalChildren, ACheckWhenParentChecked, AObject);
end;
function TNewCheckListBox.AddGroup(const ACaption, ASubItem: string;
ALevel: Byte; AObject: TObject): Integer;
begin
Result := AddItem2(itGroup, ACaption, ASubItem, ALevel, False, True, False,
True, AObject);
end;
function TNewCheckListBox.AddRadioButton(const ACaption, ASubItem: string;
ALevel: Byte; AChecked, AEnabled: Boolean; AObject: TObject): Integer;
begin
if not AEnabled then
AChecked := False;
Result := AddItem2(itRadio, ACaption, ASubItem, ALevel, AChecked, AEnabled,
False, True, AObject);
end;
function TNewCheckListBox.CanFocusItem(Item: Integer): Boolean;
begin
with ItemStates[Item] do
Result := Self.Enabled and Enabled and (ItemType <> itGroup);
end;
function TNewCheckListBox.CheckPotentialRadioParents(Index, ALevel: Integer): Boolean;
begin
Result := True;
Dec(Index);
Dec(ALevel);
while Index >= 0 do
begin
with ItemStates[Index] do
if Level = ALevel then
if ItemType = itRadio then
Exit
else
Break;
Dec(Index);
end;
if Index >= 0 then
begin
Index := GetParentOf(Index);
while Index >= 0 do
begin
if ItemStates[Index].ItemType = itRadio then
Exit;
Index := GetParentOf(Index);
end;
end;
Result := False;
end;
procedure TNewCheckListBox.CMDialogChar(var Message: TCMDialogChar);
var
I: Integer;
begin
if FWantTabs and CanFocus then
with Message do
begin
I := FindAccel(CharCode);
if I >= 0 then
begin
SetFocus;
if (FCaptureIndex <> I) or FSpaceDown then EndCapture(not FSpaceDown);
ItemIndex := I;
Toggle(I);
Result := 1
end;
end;
end;
procedure TNewCheckListBox.CMEnter(var Message: TCMEnter);
var
GoForward, Arrows: Boolean;
begin
if FWantTabs and FFormFocusChanged and (GetKeyState(VK_LBUTTON) >= 0) then
begin
if GetKeyState(VK_TAB) < 0 then begin
Arrows := False;
GoForward := (GetKeyState(VK_SHIFT) >= 0);
end
else if (GetKeyState(VK_UP) < 0) or (GetKeyState(VK_LEFT) < 0) then begin
Arrows := True;
GoForward := False;
end
else if (GetKeyState(VK_DOWN) < 0) or (GetKeyState(VK_RIGHT) < 0) then begin
Arrows := True;
GoForward := True;
end
else begin
{ Otherwise, just select the first item }
Arrows := False;
GoForward := True;
end;
if GoForward then
ItemIndex := FindNextItem(-1, True, not Arrows)
else
ItemIndex := FindNextItem(Items.Count, False, not Arrows)
end;
inherited;
end;
procedure TNewCheckListBox.CMExit(var Message: TCMExit);
begin
EndCapture(not FSpaceDown or (GetKeyState(VK_MENU) >= 0));
inherited;
end;
procedure TNewCheckListBox.CMFocusChanged(var Message: TCMFocusChanged);
begin
FFormFocusChanged := True;
inherited;
end;
procedure TNewCheckListBox.CMFontChanged(var Message: TMessage);
begin
inherited;
Canvas.Font := Font;
end;
procedure LineDDAProc(X, Y: Integer; Canvas: TCanvas); stdcall;
begin
if ((X xor Y) and 1) = 0 then
begin
Canvas.MoveTo(X, Y);
Canvas.LineTo(X + 1, Y)
end;
end;
procedure TNewCheckListBox.CMWantSpecialKey(var Message: TMessage);
begin
Message.Result := Ord(FWantTabs and (Message.WParam = VK_TAB));
end;
procedure TNewCheckListBox.CNDrawItem(var Message: TWMDrawItem);
var
L: Integer;
begin
with Message.DrawItemStruct^ do
begin
{ Note: itemID is -1 when there are no items }
if Integer(itemID) >= 0 then begin
L := ItemStates[itemID].Level;
if ItemStates[itemID].ItemType <> itGroup then Inc(L);
rcItem.Left := rcItem.Left + (FCheckWidth + 2 * FOffset) * L;
FlipRect(rcItem, ClientRect, FUseRightToLeft);
end;
{ Don't let TCustomListBox.CNDrawItem draw the focus }
if FWantTabs or (CanQueryUIState and
(SendMessage(Handle, WM_QUERYUISTATE, 0, 0) and UISF_HIDEFOCUS <> 0)) then
itemState := itemState and not ODS_FOCUS;
inherited;
end;
end;
function TNewCheckListBox.RemeasureItem(Index: Integer): Integer;
{ Recalculates an item's height. Does not repaint and does not update the
vertical scroll range (as the LB_SETITEMHEIGHT message does neither). }
begin
Result := ItemHeight;
MeasureItem(Index, Result);
SendMessage(Handle, LB_SETITEMHEIGHT, Index, Result);
end;
procedure TNewCheckListBox.UpdateScrollRange;
{ Updates the vertical scroll range, hiding/showing the scroll bar if needed.
This should be called after any RemeasureItem call. }
begin
{ Update the scroll bounds by sending a seemingly-ineffectual LB_SETTOPINDEX
message. This works on Windows 95 and 2000.
NOTE: This causes the selected item to be repainted for no apparent reason!
I wish I knew of a better way to do this... }
SendMessage(Handle, LB_SETTOPINDEX, SendMessage(Handle, LB_GETTOPINDEX, 0, 0), 0);
end;
procedure TNewCheckListBox.MeasureItem(Index: Integer; var Height: Integer);
var
DrawTextFormat: Integer;
Rect, SubItemRect: TRect;
ItemState: TItemState;
L, SubItemWidth: Integer;
S: String;
begin
with Canvas do begin
ItemState := ItemStates[Index];
Rect := Classes.Rect(0, 0, ClientWidth, 0);
L := ItemState.Level;
if ItemState.ItemType <> itGroup then
Inc(L);
Rect.Left := Rect.Left + (FCheckWidth + 2 * FOffset) * L;
Inc(Rect.Left);
if ItemState.SubItem <> '' then begin
DrawTextFormat := DT_CALCRECT or DT_NOCLIP or DT_NOPREFIX or DT_SINGLELINE;
if FUseRightToLeft then
DrawTextFormat := DrawTextFormat or (DT_RIGHT or DT_RTLREADING);
SetRectEmpty(SubItemRect);
DrawText(Canvas.Handle, PChar(ItemState.SubItem), Length(ItemState.SubItem),
SubItemRect, DrawTextFormat);
SubItemWidth := SubItemRect.Right + 2 * FOffset;
Dec(Rect.Right, SubItemWidth)
end else
Dec(Rect.Right, FOffset);
if not FWantTabs then
Inc(Rect.Left);
DrawTextFormat := DT_NOCLIP or DT_CALCRECT or DT_WORDBREAK or DT_WORD_ELLIPSIS;
if not FWantTabs or (ItemState.ItemType = itGroup) then
DrawTextFormat := DrawTextFormat or DT_NOPREFIX;
if FUseRightToLeft then
DrawTextFormat := DrawTextFormat or (DT_RIGHT or DT_RTLREADING);
S := Items[Index]; { Passing Items[Index] directly into DrawText doesn't work on Unicode build. }
ItemState.MeasuredHeight := DrawText(Canvas.Handle, PChar(S), Length(S), Rect, DrawTextFormat);
if ItemState.MeasuredHeight < FMinItemHeight then
Height := FMinItemHeight
else
Height := ItemState.MeasuredHeight + 4;
{ The height must be an even number for tree lines to be painted correctly }
if Odd(Height) then
Inc(Height);
end;
end;
procedure TNewCheckListBox.DrawItem(Index: Integer; Rect: TRect; State: TOwnerDrawState);
const
ButtonStates: array [TItemType] of Integer =
(
0,
DFCS_BUTTONCHECK,
DFCS_BUTTONRADIO
);
ButtonPartIds: array [TItemType] of Integer =
(
0,
BP_CHECKBOX,
BP_RADIOBUTTON
);
ButtonStateIds: array [TCheckBoxState, TCheckBoxState2] of Integer =
(
//Can be used for both checkboxes and radiobuttons because RBS_... constants
//equal CBS_... constants
(CBS_UNCHECKEDNORMAL, CBS_UNCHECKEDHOT, CBS_UNCHECKEDPRESSED, CBS_UNCHECKEDDISABLED),
(CBS_CHECKEDNORMAL, CBS_CHECKEDHOT, CBS_CHECKEDPRESSED, CBS_CHECKEDDISABLED),
(CBS_MIXEDNORMAL, CBS_MIXEDHOT, CBS_MIXEDPRESSED, CBS_MIXEDDISABLED)
);
var
SavedClientRect: TRect;
function FlipX(const X: Integer): Integer;
begin
if FUseRightToLeft then
Result := (SavedClientRect.Right - 1) - X
else
Result := X;
end;
procedure InternalDrawText(const S: string; var R: TRect; Format: Integer;
Embossed: Boolean);
begin
if Embossed then
begin
Canvas.Brush.Style := bsClear;
OffsetRect(R, 1, 1);
SetTextColor(Canvas.Handle, GetSysColor(COLOR_BTNHIGHLIGHT));
DrawText(Canvas.Handle, PChar(S), Length(S), R, Format);
OffsetRect(R, -1, -1);
SetTextColor(Canvas.Handle, GetSysColor(COLOR_BTNSHADOW));
DrawText(Canvas.Handle, PChar(S), Length(S), R, Format);
end
else
DrawText(Canvas.Handle, PChar(S), Length(S), R, Format);
end;
var
Disabled: Boolean;
uState, I, ThreadPosX, ThreadBottom, ThreadLevel, ItemMiddle,
DrawTextFormat: Integer;
CheckRect, SubItemRect, FocusRect: TRect;
NewTextColor: TColor;
OldColor: TColorRef;
ItemState: TItemState;
UIState: DWORD;
SubItemWidth: Integer;
PartId, StateId: Integer;
begin
if FShowLines and not FThreadsUpToDate then begin
UpdateThreads;
FThreadsUpToDate := True;
end;
SavedClientRect := ClientRect;
{ Undo flipping performed by TNewCheckListBox.CNDrawItem }
FlipRect(Rect, SavedClientRect, FUseRightToLeft);
ItemState := ItemStates[Index];
if CanQueryUIState then
UIState := SendMessage(Handle, WM_QUERYUISTATE, 0, 0)
else
UIState := 0; //no UISF_HIDEACCEL and no UISF_HIDEFOCUS
Disabled := not Enabled or not ItemState.Enabled;
with Canvas do begin
if not FWantTabs and (odSelected in State) and Focused then begin
Brush.Color := clHighlight;
NewTextColor := clHighlightText;
end
else begin
Brush.Color := Self.Color;
if Disabled then
NewTextColor := clGrayText
else
NewTextColor := Self.Font.Color;
end;
{ Draw threads }
if FShowLines then begin
Pen.Color := clGrayText;
ThreadLevel := ItemLevel[Index];
for I := 0 to ThreadLevel - 1 do
if I in ItemStates[Index].ThreadCache then begin
ThreadPosX := (FCheckWidth + 2 * FOffset) * I + FCheckWidth div 2 + FOffset;
ItemMiddle := (Rect.Bottom - Rect.Top) div 2 + Rect.Top;
ThreadBottom := Rect.Bottom;
if I = ThreadLevel - 1 then begin
if ItemStates[Index].IsLastChild then
ThreadBottom := ItemMiddle;
LineDDA(FlipX(ThreadPosX), ItemMiddle, FlipX(ThreadPosX + FCheckWidth div 2 + FOffset),
ItemMiddle, @LineDDAProc, Integer(Canvas));
end;
LineDDA(FlipX(ThreadPosX), Rect.Top, FlipX(ThreadPosX), ThreadBottom,
@LineDDAProc, Integer(Canvas));
end;
end;
{ Draw checkmark}
if ItemState.ItemType <> itGroup then begin
CheckRect := Bounds(Rect.Left - (FCheckWidth + FOffset),
Rect.Top + ((Rect.Bottom - Rect.Top - FCheckHeight) div 2),
FCheckWidth, FCheckHeight);
FlipRect(CheckRect, SavedClientRect, FUseRightToLeft);
if FThemeData = 0 then begin
case ItemState.State of
cbChecked: uState := ButtonStates[ItemState.ItemType] or DFCS_CHECKED;
cbUnchecked: uState := ButtonStates[ItemState.ItemType];
else
uState := DFCS_BUTTON3STATE or DFCS_CHECKED;
end;
if FFlat then
uState := uState or DFCS_FLAT;
if Disabled then
uState := uState or DFCS_INACTIVE;
if (FCaptureIndex = Index) and (FSpaceDown or (FLastMouseMoveIndex = Index)) then
uState := uState or DFCS_PUSHED;
DrawFrameControl(Handle, CheckRect, DFC_BUTTON, uState)
end else begin
PartId := ButtonPartIds[ItemState.ItemType];
if Disabled then
StateId := ButtonStateIds[ItemState.State][cb2Disabled]
else if Index = FCaptureIndex then
if FSpaceDown or (FLastMouseMoveIndex = Index) then
StateId := ButtonStateIds[ItemState.State][cb2Pressed]
else
StateId := ButtonStateIds[ItemState.State][cb2Hot]
else if (FCaptureIndex < 0) and (Index = FHotIndex) then
StateId := ButtonStateIds[ItemState.State][cb2Hot]
else
StateId := ButtonStateIds[ItemState.State][cb2Normal];
//if IsThemeBackgroundPartiallyTransparent(FThemeData, PartId, StateId) then
// DrawThemeParentBackground(Self.Handle, Handle, @CheckRect);
DrawThemeBackGround(FThemeData, Handle, PartId, StateId, CheckRect, @CheckRect);
end;
end;
{ Draw SubItem }
FlipRect(Rect, SavedClientRect, FUseRightToLeft);
FillRect(Rect);
FlipRect(Rect, SavedClientRect, FUseRightToLeft);
Inc(Rect.Left);
OldColor := SetTextColor(Handle, ColorToRGB(NewTextColor));
if ItemState.SubItem <> '' then
begin
DrawTextFormat := DT_NOCLIP or DT_NOPREFIX or DT_SINGLELINE or DT_VCENTER;
if FUseRightToLeft then
DrawTextFormat := DrawTextFormat or (DT_RIGHT or DT_RTLREADING);
SetRectEmpty(SubItemRect);
InternalDrawText(ItemState.SubItem, SubItemRect, DrawTextFormat or
DT_CALCRECT, False);
SubItemWidth := SubItemRect.Right + 2 * FOffset;
SubItemRect := Rect;
SubItemRect.Left := SubItemRect.Right - SubItemWidth + FOffset;
FlipRect(SubItemRect, SavedClientRect, FUseRightToLeft);
InternalDrawText(ItemState.SubItem, SubItemRect, DrawTextFormat,
FWantTabs and Disabled);
Dec(Rect.Right, SubItemWidth);
end
else
Dec(Rect.Right, FOffset);
{ Draw item text }
if not FWantTabs then
Inc(Rect.Left);
OffsetRect(Rect, 0, (Rect.Bottom - Rect.Top - ItemState.MeasuredHeight) div 2);
DrawTextFormat := DT_NOCLIP or DT_WORDBREAK or DT_WORD_ELLIPSIS;
if not FWantTabs or (ItemState.ItemType = itGroup) then
DrawTextFormat := DrawTextFormat or DT_NOPREFIX;
if (UIState and UISF_HIDEACCEL) <> 0 then
DrawTextFormat := DrawTextFormat or DT_HIDEPREFIX;
if FUseRightToLeft then
DrawTextFormat := DrawTextFormat or (DT_RIGHT or DT_RTLREADING);
{ When you call DrawText with the DT_CALCRECT flag and there's a word wider
than the rectangle width, it increases the rectangle width and wraps
at the new Right point. On the other hand, when you call DrawText
_without_ the DT_CALCRECT flag, it always wraps at the Right point you
specify -- it doesn't check for long words first.
Therefore, to ensure we wrap at the same place when drawing as when
measuring, pass our rectangle to DrawText with DT_CALCRECT first.
Wrapping at the same place is important because it can affect how many
lines are drawn -- and we mustn't draw too many. }
InternalDrawText(Items[Index], Rect, DrawTextFormat or DT_CALCRECT, False);
FlipRect(Rect, SavedClientRect, FUseRightToLeft);
InternalDrawText(Items[Index], Rect, DrawTextFormat, FWantTabs and Disabled);
{ Draw focus rectangle }
if FWantTabs and not Disabled and (odSelected in State) and Focused and
(UIState and UISF_HIDEFOCUS = 0) then
begin
FocusRect := Rect;
InflateRect(FocusRect, 1, 1);
DrawFocusRect(FocusRect);
end;
SetTextColor(Handle, OldColor);
end;
end;
procedure TNewCheckListBox.EndCapture(Cancel: Boolean);
var
InvalidateItem: Boolean;
Item: Integer;
begin
Item := FCaptureIndex;
if Item >= 0 then
begin
InvalidateItem := FSpaceDown or (FCaptureIndex = FLastMouseMoveIndex) or (FThemeData <> 0);
FSpaceDown := False;
FCaptureIndex := -1;
FLastMouseMoveIndex := -1;
if not Cancel then
Toggle(Item);
if InvalidateItem then
InvalidateCheck(Item);
end;
if MouseCapture then
MouseCapture := False;
end;
procedure TNewCheckListBox.EnumChildrenOf(Item: Integer; Proc: TEnumChildrenProc;
Ext: Longint);
var
L: Integer;
begin
if (Item < -1) or (Item >= Items.Count) then
Exit;
if Item = -1 then
begin
L := 0;
Item := 0;
end
else
begin
L := ItemLevel[Item] + 1;
Inc(Item);
end;
while (Item < Items.Count) and (ItemLevel[Item] >= L) do
begin
if ItemLevel[Item] = L then
Proc(Item, (Item < Items.Count - 1) and (ItemLevel[Item + 1] > L), Ext);
Inc(Item);
end;
end;
function TNewCheckListBox.AddItem2(AType: TItemType;
const ACaption, ASubItem: string; ALevel: Byte;
AChecked, AEnabled, AHasInternalChildren, ACheckWhenParentChecked: Boolean;
AObject: TObject): Integer;
var
ItemState: TItemState;
I: Integer;
begin
if Items.Count <> FStateList.Count then { sanity check }
raise Exception.Create('List item and state item count mismatch');
if Items.Count > 0 then
begin
if ItemLevel[Items.Count - 1] + 1 < ALevel then
ALevel := ItemLevel[Items.Count - 1] + 1;
end
else
ALevel := 0;
FThreadsUpToDate := False;
{ Use our own grow code to minimize heap fragmentation }
if FStateList.Count = FStateList.Capacity then begin
if FStateList.Capacity < 64 then
FStateList.Capacity := 64
else
FStateList.Capacity := FStateList.Capacity * 2;
end;
ItemState := TItemState.Create;
try
ItemState.ItemType := AType;
ItemState.Enabled := AEnabled;
ItemState.Obj := AObject;
ItemState.Level := ALevel;
ItemState.SubItem := ASubItem;
ItemState.HasInternalChildren := AHasInternalChildren;
ItemState.CheckWhenParentChecked := ACheckWhenParentChecked;
except
ItemState.Free;
raise;
end;
FStateList.Add(ItemState);
try
Result := Items.Add(ACaption);
except
FStateList.Delete(FStateList.Count-1);
ItemState.Free;
raise;
end;
{ If the first item in a radio group is being added, and it is top-level or
has a checked parent, force it to be checked. (We don't want to allow radio
groups with no selection.) }
if (AType = itRadio) and not AChecked and AEnabled then begin
I := GetParentOf(Result);
{ FRequireRadioSelection only affects top-level items; we never allow
child radio groups with no selection (because nobody should need that) }
if FRequireRadioSelection or (I <> -1) then
if (I = -1) or (GetState(I) <> cbUnchecked) then
if FindCheckedSibling(Result) = -1 then
AChecked := True;
end;
SetChecked(Result, AChecked);
end;
function TNewCheckListBox.FindAccel(VK: Word): Integer;
begin
for Result := 0 to Items.Count - 1 do
if CanFocusItem(Result) and IsAccel(VK, Items[Result]) then
Exit;
Result := -1;
end;
function TNewCheckListBox.FindNextItem(StartFrom: Integer; GoForward,
SkipUncheckedRadios: Boolean): Integer;
function ShouldSkip(Index: Integer): Boolean;
begin
with ItemStates[Index] do
Result := (ItemType = itRadio) and (State <> cbChecked)
end;
var
Delta: Integer;
begin
if StartFrom < -1 then
StartFrom := ItemIndex;
if Items.Count > 0 then
begin
Delta := Ord(GoForward) * 2 - 1;
Result := StartFrom + Delta;
while (Result >= 0) and (Result < Items.Count) and
(not CanFocusItem(Result) or SkipUncheckedRadios and ShouldSkip(Result)) do
Result := Result + Delta;
if (Result < 0) or (Result >= Items.Count) then
Result := -1;
end
else
Result := -1;
end;
function TNewCheckListBox.GetCaption(Index: Integer): String;
begin
Result := Items[Index];
end;
function TNewCheckListBox.GetChecked(Index: Integer): Boolean;
begin
Result := GetState(Index) <> cbUnchecked;
end;
function TNewCheckListBox.GetItemEnabled(Index: Integer): Boolean;
begin
Result := ItemStates[Index].Enabled;
end;
function TNewCheckListBox.GetItemState(Index: Integer): TItemState;
begin
Result := FStateList[Index];
end;
function TNewCheckListBox.GetLevel(Index: Integer): Byte;
begin
Result := ItemStates[Index].Level;
end;
function TNewCheckListBox.GetObject(Index: Integer): TObject;
begin
Result := ItemStates[Index].Obj;
end;
function TNewCheckListBox.GetParentOf(Item: Integer): Integer;
{ Gets index of Item's parent, or -1 if there is none. }
var
Level, I: Integer;
begin
Level := ItemStates[Item].Level;
if Level > 0 then
for I := Item-1 downto 0 do begin
if ItemStates[I].Level < Level then begin
Result := I;
Exit;
end;
end;
Result := -1;
end;
function TNewCheckListBox.GetState(Index: Integer): TCheckBoxState;
begin
Result := ItemStates[Index].State;
end;
function TNewCheckListBox.GetSubItem(Index: Integer): String;
begin
Result := ItemStates[Index].SubItem;
end;
procedure TNewCheckListBox.InvalidateCheck(Index: Integer);
var
IRect: TRect;
begin
IRect := ItemRect(Index);
Inc(IRect.Left, (FCheckWidth + 2 * Offset) * (ItemLevel[Index]));
IRect.Right := IRect.Left + (FCheckWidth + 2 * Offset);
FlipRect(IRect, ClientRect, FUseRightToLeft);
InvalidateRect(Handle, @IRect, FThemeData <> 0);
end;
procedure TNewCheckListBox.KeyDown(var Key: Word; Shift: TShiftState);
begin
if (Key = VK_SPACE) and not (ssAlt in Shift) and (ItemIndex >= 0) and
(FCaptureIndex < 0) and CanFocusItem(ItemIndex) then
if FWantTabs then begin
if not FSpaceDown then begin
FCaptureIndex := ItemIndex;
FSpaceDown := True;
InvalidateCheck(ItemIndex);
if (FHotIndex <> ItemIndex) and (FHotIndex <> -1) and (FThemeData <> 0) then
InvalidateCheck(FHotIndex);
end;
end
else
Toggle(ItemIndex);
inherited;
end;
procedure TNewCheckListBox.KeyUp(var Key: Word; Shift: TShiftState);
begin
if (Key = VK_SPACE) and FWantTabs and FSpaceDown and (FCaptureIndex >= 0) then begin
EndCapture(False);
if (FHotIndex <> -1) and (FThemeData <> 0) then
InvalidateCheck(FHotIndex);
end;
inherited;
end;
procedure TNewCheckListBox.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
var
Index: Integer;
begin
if Button = mbLeft then begin
Index := ItemAtPos(Point(X, Y), True);
if (Index <> -1) and CanFocusItem(Index) then
begin
if FWantTabs then begin
if not FSpaceDown then begin
if not MouseCapture then
MouseCapture := True;
FCaptureIndex := Index;
FLastMouseMoveIndex := Index;
InvalidateCheck(Index);
end;
end
else
Toggle(Index);
end;
end;
inherited;
end;
procedure TNewCheckListBox.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
var
Index: Integer;
begin
if (Button = mbLeft) and FWantTabs and not FSpaceDown and (FCaptureIndex >= 0) then
begin
Index := ItemAtPos(Point(X, Y), True);
EndCapture(Index <> FCaptureIndex);
if (FHotIndex <> -1) and (FThemeData <> 0) then
InvalidateCheck(FHotIndex);
end;
end;
procedure TNewCheckListBox.UpdateHotIndex(NewHotIndex: Integer);
var
OldHotIndex: Integer;
begin
OldHotIndex := FHotIndex;
if NewHotIndex <> OldHotIndex then
begin
FHotIndex := NewHotIndex;
if FCaptureIndex = -1 then begin
if (OldHotIndex <> -1) and (FThemeData <> 0) then
InvalidateCheck(OldHotIndex);
if (NewHotIndex <> -1) and (FThemeData <> 0) then
InvalidateCheck(NewHotIndex);
end;
end;
end;
procedure TNewCheckListBox.CMMouseLeave(var Message: TMessage);
begin
UpdateHotIndex(-1);
inherited;
end;
procedure TNewCheckListBox.SetCaption(Index: Integer; const Value: String);
begin
{ Changing an item's text actually involves deleting and re-inserting the
item. Increment FDisableItemStateDeletion so the item state isn't lost. }
Inc(FDisableItemStateDeletion);
try
Items[Index] := Value;
finally
Dec(FDisableItemStateDeletion);
end;
end;
procedure TNewCheckListBox.SetChecked(Index: Integer; const AChecked: Boolean);
begin
if AChecked then
CheckItem(Index, coCheck)
else
CheckItem(Index, coUncheck);
end;
function TNewCheckListBox.FindCheckedSibling(const AIndex: Integer): Integer;
{ Finds a checked sibling of AIndex (which is assumed to be a radio button).
Returns -1 if no checked sibling was found. }
var
ThisLevel, I: Integer;
begin
ThisLevel := ItemStates[AIndex].Level;
for I := AIndex-1 downto 0 do begin
if ItemStates[I].Level < ThisLevel then
Break;
if ItemStates[I].Level = ThisLevel then begin
if ItemStates[I].ItemType <> itRadio then
Break;
if GetState(I) <> cbUnchecked then begin
Result := I;
Exit;
end;
end;
end;
for I := AIndex+1 to Items.Count-1 do begin
if ItemStates[I].Level < ThisLevel then
Break;
if ItemStates[I].Level = ThisLevel then begin
if ItemStates[I].ItemType <> itRadio then
Break;
if GetState(I) <> cbUnchecked then begin
Result := I;
Exit;
end;
end;
end;
Result := -1;
end;
function TNewCheckListBox.CheckItem(const Index: Integer;
const AOperation: TCheckItemOperation): Boolean;
{ Tries to update the checked state of Index. Returns True if any changes were
made to the state of Index or any of its children. }
procedure SetItemState(const AIndex: Integer; const AState: TCheckBoxState);
begin
if ItemStates[AIndex].State <> AState then begin
ItemStates[AIndex].State := AState;
InvalidateCheck(AIndex);
{ Notify MSAA of the state change }
if Assigned(NotifyWinEventFunc) then
NotifyWinEventFunc(EVENT_OBJECT_STATECHANGE, Handle, OBJID_CLIENT,
1 + AIndex);
end;
end;
function CalcState(const AIndex: Integer; ACheck: Boolean): TCheckBoxState;
{ Determines new state for AIndex based on desired checked state (ACheck) and
current state of the item's immediate children. }
var
RootLevel, I: Integer;
HasChecked, HasUnchecked: Boolean;
begin
HasChecked := False;
HasUnchecked := False;
RootLevel := ItemStates[AIndex].Level;
for I := AIndex+1 to Items.Count-1 do begin
if ItemStates[I].Level <= RootLevel then
Break;
if (ItemStates[I].Level = RootLevel+1) and
(ItemStates[I].ItemType in [itCheck, itRadio]) then begin
case GetState(I) of
cbUnchecked: begin
if (ItemStates[I].ItemType <> itRadio) or
(FindCheckedSibling(I) = -1) then
HasUnchecked := True;
end;
cbChecked: begin
HasChecked := True;
end;
cbGrayed: begin
HasChecked := True;
HasUnchecked := True;
end;
end;
end;
end;
{ If the parent is a check box with children, don't allow it to be checked
if none of its children are checked, unless it "has internal children" }
if HasUnchecked and not HasChecked and
(ItemStates[AIndex].ItemType = itCheck) and
not ItemStates[AIndex].HasInternalChildren then
ACheck := False;
if ACheck or HasChecked then begin
if HasUnchecked and (ItemStates[AIndex].ItemType = itCheck) then
Result := cbGrayed
else
Result := cbChecked;
end
else
Result := cbUnchecked;
end;
function RecursiveCheck(const AIndex: Integer;
const AOperation: TCheckItemOperation): Boolean;
{ Checks or unchecks AIndex and all enabled child items of AIndex at any
level. In radio button groups, only one item per group is checked.
Returns True if any of the items' states were changed. }
var
RootLevel, I: Integer;
NewState: TCheckBoxState;
begin
Result := False;
RootLevel := ItemStates[AIndex].Level;
for I := AIndex+1 to Items.Count-1 do begin
if ItemStates[I].Level <= RootLevel then
Break;
if (ItemStates[I].Level = RootLevel+1) and ItemStates[I].Enabled and
((AOperation = coUncheck) or
((AOperation = coCheckWithChildren) and ItemStates[I].CheckWhenParentChecked) or
(ItemStates[I].ItemType = itRadio)) then
{ If checking and I is a radio button, don't recurse if a sibling
already got checked in a previous iteration of this loop. This is
needed in the following case to prevent all three radio buttons from
being checked when "Parent check" is checked. In addition, it
prevents "Child check" from being checked.
[ ] Parent check
( ) Radio 1
( ) Radio 2
( ) Radio 3
[ ] Child check
}
if (AOperation = coUncheck) or (ItemStates[I].ItemType <> itRadio) or
(FindCheckedSibling(I) = -1) then
if RecursiveCheck(I, AOperation) then
Result := True;
end;
NewState := CalcState(AIndex, AOperation <> coUncheck);
if GetState(AIndex) <> NewState then begin
SetItemState(AIndex, NewState);
Result := True;
end;
end;
procedure UncheckSiblings(const AIndex: Integer);
{ Unchecks all siblings (and their children) of AIndex, which is assumed to
be a radio button. }
var
I: Integer;
begin
while True do begin
I := FindCheckedSibling(AIndex);
if I = -1 then
Break;
RecursiveCheck(I, coUncheck);
end;
end;
procedure EnsureChildRadioItemsHaveSelection(const AIndex: Integer);
{ Ensures all radio button groups that are immediate children of AIndex have
a selected item. }
var
RootLevel, I: Integer;
begin
RootLevel := ItemStates[AIndex].Level;
for I := AIndex+1 to Items.Count-1 do begin
if ItemStates[I].Level <= RootLevel then
Break;
if (ItemStates[I].Level = RootLevel+1) and
(ItemStates[I].ItemType = itRadio) and
ItemStates[I].Enabled and
(GetState(I) <> cbChecked) and
(FindCheckedSibling(I) = -1) then
{ Note: This uses coCheck instead of coCheckWithChildren (or the value
of AOperation) in order to keep side effects to a minimum. Seems
like the most logical behavior. For example, in this case:
[ ] A
( ) B
[ ] C
[ ] D
clicking D will cause the radio button B to be checked (out of
necessity), but won't automatically check its child check box, C.
(If C were instead a radio button, it *would* be checked.) }
RecursiveCheck(I, coCheck);
end;
end;
procedure UpdateParentStates(const AIndex: Integer);
var
I: Integer;
ChildChecked: Boolean;
NewState: TCheckBoxState;
begin
I := AIndex;
while True do begin
ChildChecked := (GetState(I) <> cbUnchecked);
I := GetParentOf(I);
if I = -1 then
Break;
{ When a child item is checked, must ensure that all sibling radio button
groups have selections }
if ChildChecked then
EnsureChildRadioItemsHaveSelection(I);
NewState := CalcState(I, GetState(I) <> cbUnchecked);
{ If a parent radio button is becoming checked, uncheck any previously
selected sibling of that radio button }
if (NewState <> cbUnchecked) and (ItemStates[I].ItemType = itRadio) then
UncheckSiblings(I);
SetItemState(I, NewState);
end;
end;
begin
if ItemStates[Index].ItemType = itRadio then begin
{ Setting Checked to False on a radio button is a no-op. (A radio button
may only be unchecked by checking another radio button in the group, or
by unchecking a parent check box.) }
if AOperation = coUncheck then begin
Result := False;
Exit;
end;
{ Before checking a new item in a radio group, uncheck any siblings and
their children }
UncheckSiblings(Index);
end;
{ Check or uncheck this item and all its children }
Result := RecursiveCheck(Index, AOperation);
{ Update state of parents. For example, if a child check box is being
checked, its parent must also become checked if it isn't already. }
UpdateParentStates(Index);
end;
procedure TNewCheckListBox.SetFlat(Value: Boolean);
begin
if Value <> FFlat then
begin
FFlat := Value;
Invalidate;
end;
end;
procedure TNewCheckListBox.SetItemEnabled(Index: Integer; const AEnabled: Boolean);
begin
if ItemStates[Index].Enabled <> AEnabled then
begin
ItemStates[Index].Enabled := AEnabled;
InvalidateCheck(Index);
end;
end;
procedure TNewCheckListBox.SetObject(Index: Integer; const AObject: TObject);
begin
ItemStates[Index].Obj := AObject;
end;
procedure TNewCheckListBox.SetOffset(AnOffset: Integer);
begin
if FOffset <> AnOffset then
begin
FOffset := AnOffset;
Invalidate;
end;
end;
procedure TNewCheckListBox.SetShowLines(Value: Boolean);
begin
if FShowLines <> Value then
begin
FShowLines := Value;
Invalidate;
end;
end;
procedure TNewCheckListBox.SetSubItem(Index: Integer; const ASubItem: String);
var
OldHeight, NewHeight: Integer;
R, R2: TRect;
begin
if ItemStates[Index].SubItem <> ASubItem then
begin
ItemStates[Index].SubItem := ASubItem;
OldHeight := SendMessage(Handle, LB_GETITEMHEIGHT, Index, 0);
NewHeight := RemeasureItem(Index);
R := ItemRect(Index);
{ Scroll subsequent items down or up, if necessary }
if NewHeight <> OldHeight then begin
if Index >= TopIndex then begin
R2 := ClientRect;
R2.Top := R.Top + OldHeight;
if not IsRectEmpty(R2) then
ScrollWindowEx(Handle, 0, NewHeight - OldHeight, @R2, nil, 0, nil,
SW_INVALIDATE or SW_ERASE);
end;
UpdateScrollRange;
end;
InvalidateRect(Handle, @R, True);
end;
end;
procedure TNewCheckListBox.Toggle(Index: Integer);
begin
case ItemStates[Index].ItemType of
itCheck:
case ItemStates[Index].State of
cbUnchecked: CheckItem(Index, coCheckWithChildren);
cbChecked: CheckItem(Index, coUncheck);
cbGrayed:
{ First try checking, but if that doesn't work because of children
that are disabled and unchecked, try unchecking }
if not CheckItem(Index, coCheckWithChildren) then
CheckItem(Index, coUncheck);
end;
itRadio: CheckItem(Index, coCheckWithChildren);
end;
if Assigned(FOnClickCheck) then
FOnClickCheck(Self);
end;
procedure TNewCheckListBox.UpdateThreads;
function LastImmediateChildOf(Item: Integer): Integer;
var
L: Integer;
begin
Result := -1;
L := ItemLevel[Item] + 1;
Inc(Item);
while (Item < Items.Count) and (ItemLevel[Item] >= L) do
begin
if ItemLevel[Item] = L then
Result := Item;
Inc(Item);
end;
if Result >= 0 then
ItemStates[Result].IsLastChild := True;
end;
var
I, J, LastChild, L: Integer;
begin
for I := 0 to Items.Count - 1 do
begin
ItemStates[I].ThreadCache := [];
ItemStates[I].IsLastChild := False;
end;
for I := 0 to Items.Count - 1 do
begin
LastChild := LastImmediateChildOf(I);
L := ItemLevel[I];
for J := I + 1 to LastChild do
Include(ItemStates[J].ThreadCache, L);
end;
end;
procedure TNewCheckListBox.LBDeleteString(var Message: TMessage);
var
I: Integer;
ItemState: TItemState;
begin
inherited;
if FDisableItemStateDeletion = 0 then begin
I := Message.WParam;
if (I >= 0) and (I < FStateList.Count) then begin
ItemState := FStateList[I];
FStateList.Delete(I);
ItemState.Free;
end;
end;
end;
procedure TNewCheckListBox.LBResetContent(var Message: TMessage);
var
I: Integer;
ItemState: TItemState;
begin
inherited;
if FDisableItemStateDeletion = 0 then
for I := FStateList.Count-1 downto 0 do begin
ItemState := FStateList[I];
FStateList.Delete(I);
ItemState.Free;
end;
end;
procedure TNewCheckListBox.WMGetDlgCode(var Message: TWMGetDlgCode);
begin
inherited;
if FWantTabs then
Message.Result := Message.Result and not DLGC_WANTCHARS;
end;
procedure TNewCheckListBox.WMKeyDown(var Message: TWMKeyDown);
var
GoForward, Arrows: Boolean;
I: Integer;
Prnt, Ctrl: TWinControl;
begin
{ If space is pressed, avoid flickering -- exit now. }
if not FWantTabs or (Message.CharCode = VK_SPACE) then
begin
inherited;
Exit;
end;
Arrows := True;
case Message.CharCode of
VK_TAB:
begin
GoForward := GetKeyState(VK_SHIFT) >= 0;
Arrows := False
end;
VK_DOWN, VK_RIGHT: GoForward := True;
VK_UP, VK_LEFT: GoForward := False
else
if FSpaceDown then EndCapture(True);
inherited;
Exit;
end;
EndCapture(not FSpaceDown);
SendMessage(Handle, WM_CHANGEUISTATE, UIS_CLEAR or (UISF_HIDEFOCUS shl 16), 0);
if Arrows or TabStop then
I := FindNextItem(-2, GoForward, not Arrows)
else
I := -1;
if I < 0 then
begin
Prnt := nil;
if not Arrows then
Prnt := GetParentForm(Self);
if Prnt = nil then Prnt := Parent;
if Prnt <> nil then
begin
Ctrl := TWinControlAccess(Prnt).FindNextControl(Self, GoForward, True, Arrows);
if (Ctrl <> nil) and (Ctrl <> Self) then
begin
Ctrl.SetFocus;
Exit;
end;
end;
if GoForward then
I := FindNextItem(-1, True, not Arrows)
else
I := FindNextItem(Items.Count, False, not Arrows);
end;
ItemIndex := I;
if (I <> -1) and (ItemStates[I].ItemType = itRadio) and Arrows then
Toggle(I);
end;
procedure TNewCheckListBox.WMMouseMove(var Message: TWMMouseMove);
var
Pos: TPoint;
Index, NewHotIndex: Integer;
Rect: TRect;
Indent: Integer;
begin
Pos := SmallPointToPoint(Message.Pos);
Index := ItemAtPos(Pos, True);
if FCaptureIndex >= 0 then begin
if not FSpaceDown and (Index <> FLastMouseMoveIndex) then begin
if (FLastMouseMoveIndex = FCaptureIndex) or (Index = FCaptureIndex) then
InvalidateCheck(FCaptureIndex);
FLastMouseMoveIndex := Index;
end
end;
NewHotIndex := -1;
if (Index <> -1) and CanFocusItem(Index) then
begin
Rect := ItemRect(Index);
Indent := (FOffset * 2 + FCheckWidth);
if FWantTabs or ((Pos.X >= Rect.Left + Indent * ItemLevel[Index]) and
(Pos.X < Rect.Left + Indent * (ItemLevel[Index] + 1))) then
NewHotIndex := Index;
end;
UpdateHotIndex(NewHotIndex);
end;
procedure TNewCheckListBox.WMMouseWheel(var Message: TMessage);
const
WHEEL_DELTA = 120;
begin
{ Work around a Windows bug (reproducible on 2000/XP/2003, but not Vista):
On an ownerdraw-variable list box, scrolling up or down more than one item
at a time with animation enabled causes a strange effect: first all visible
items appear to scroll off the bottom, then the items are all repainted in
the correct position. To avoid that, we implement our own mouse wheel
handling that scrolls only one item at a time.
(Note: The same problem exists when scrolling a page at a time using the
scroll bar. But because it's not as obvious, we don't work around it.) }
if (Lo(GetVersion) = 5) and
(Message.WParam and (MK_CONTROL or MK_SHIFT) = 0) then begin
Inc(FWheelAccum, Smallint(Message.WParam shr 16));
if Abs(FWheelAccum) >= WHEEL_DELTA then begin
while FWheelAccum >= WHEEL_DELTA do begin
SendMessage(Handle, WM_VSCROLL, SB_LINEUP, 0);
Dec(FWheelAccum, WHEEL_DELTA);
end;
while FWheelAccum <= -WHEEL_DELTA do begin
SendMessage(Handle, WM_VSCROLL, SB_LINEDOWN, 0);
Inc(FWheelAccum, WHEEL_DELTA);
end;
SendMessage(Handle, WM_VSCROLL, SB_ENDSCROLL, 0);
end;
end
else
{ Like the default handling, don't scroll if Control or Shift are down,
and on Vista always use the default handling since it isn't bugged. }
inherited;
end;
procedure TNewCheckListBox.WMNCHitTest(var Message: TWMNCHitTest);
var
I: Integer;
begin
inherited;
if FWantTabs and not (csDesigning in ComponentState) then
begin
if Message.Result = HTCLIENT then
begin
I := ItemAtPos(ScreenToClient(SmallPointToPoint(Message.Pos)), True);
if (I < 0) or not CanFocusItem(I) then
begin
UpdateHotIndex(-1);
Message.Result := 12345;
Exit;
end;
end;
end;
end;
procedure TNewCheckListBox.WMSetFocus(var Message: TWMSetFocus);
begin
FWheelAccum := 0;
inherited;
end;
procedure TNewCheckListBox.WMSize(var Message: TWMSize);
var
I: Integer;
begin
inherited;
{ When the scroll bar appears/disappears, the client width changes and we
must recalculate the height of the items }
for I := Items.Count-1 downto 0 do
RemeasureItem(I);
UpdateScrollRange;
end;
procedure TNewCheckListBox.WMThemeChanged(var Message: TMessage);
begin
{ Don't Run to Cursor into this function, it will interrupt up the theme change }
UpdateThemeData(True, True);
inherited;
end;
procedure TNewCheckListBox.WMUpdateUIState(var Message: TMessage);
begin
Invalidate;
inherited;
end;
procedure TNewCheckListBox.WMGetObject(var Message: TMessage);
begin
if (Message.LParam = Integer(OBJID_CLIENT)) and InitializeOleAcc then begin
if FAccObjectInstance = nil then begin
try
FAccObjectInstance := TAccObject.Create(Self);
except
inherited;
Exit;
end;
end;
Message.Result := LresultFromObjectFunc(IID_IAccessible, Message.WParam,
TAccObject(FAccObjectInstance));
end
else
inherited;
end;
{ TAccObject }
constructor TAccObject.Create(AControl: TNewCheckListBox);
begin
inherited Create;
if CreateStdAccessibleObjectFunc(AControl.Handle, Integer(OBJID_CLIENT),
IID_IAccessible, Pointer(FStdAcc)) <> S_OK then begin
{ Note: The user will never actually see this message since the call to
TAccObject.Create in TNewCheckListBox.WMGetObject is protected by a
try..except. }
raise Exception.Create('CreateStdAccessibleObject failed');
end;
FControl := AControl;
end;
destructor TAccObject.Destroy;
begin
{ If FControl is assigned, then we are being destroyed before the control --
the usual case. Clear FControl's reference to us. }
if Assigned(FControl) then begin
FControl.FAccObjectInstance := nil;
FControl := nil;
end;
if Assigned(FStdAcc) then
FStdAcc.Release;
inherited;
end;
procedure TAccObject.ControlDestroying;
begin
{ Set FControl to nil, since it's no longer valid }
FControl := nil;
{ Take this opportunity to disconnect remote clients, i.e. don't allow them
to call us anymore. This prevents invalid memory accesses if this unit's
code is in a DLL, and the application subsequently unloads the DLL while
remote clients still hold (and are using) references to this TAccObject. }
CoDisconnectObject(Self, 0);
{ NOTE: Don't access Self in any way at this point. The CoDisconnectObject
call likely caused all references to be relinquished and Self to be
destroyed. }
end;
function TAccObject.QueryInterface(const iid: TIID; var obj): HRESULT;
begin
if IsEqualIID(iid, IID_IUnknown) or
IsEqualIID(iid, IID_IDispatch) or
IsEqualIID(iid, IID_IAccessible) then begin
Pointer(obj) := Self;
AddRef;
Result := S_OK;
end
else begin
Pointer(obj) := nil;
Result := E_NOINTERFACE;
end;
end;
function TAccObject.AddRef: Longint;
begin
Inc(FRefCount);
Result := FRefCount;
end;
function TAccObject.Release: Longint;
begin
Dec(FRefCount);
Result := FRefCount;
if Result = 0 then
Destroy;
end;
function TAccObject.GetTypeInfoCount(var ctinfo: Integer): HRESULT;
begin
Result := E_NOTIMPL;
end;
function TAccObject.GetTypeInfo(itinfo: Integer; lcid: TLCID; var tinfo: ITypeInfo): HRESULT;
begin
Result := E_NOTIMPL;
end;
function TAccObject.GetIDsOfNames(const iid: TIID; rgszNames: POleStrList;
cNames: Integer; lcid: TLCID; rgdispid: PDispIDList): HRESULT;
begin
Result := E_NOTIMPL;
end;
function TAccObject.Invoke(dispIDMember: TDispID; const iid: TIID; lcid: TLCID;
flags: Word; var dispParams: TDispParams; varResult: PVariant;
excepInfo: PExcepInfo; argErr: PInteger): HRESULT;
begin
Result := E_NOTIMPL;
end;
function TAccObject.accDoDefaultAction(varChild: NewOleVariant): HRESULT;
begin
{ A list box's default action is Double Click, which is useless for a
list of check boxes. }
Result := DISP_E_MEMBERNOTFOUND;
end;
function TAccObject.accHitTest(xLeft, yTop: Integer;
var pvarID: NewOleVariant): HRESULT;
begin
Result := FStdAcc.accHitTest(xLeft, yTop, pvarID);
end;
function TAccObject.accLocation(var pxLeft, pyTop, pcxWidth,
pcyHeight: Integer; varChild: NewOleVariant): HRESULT;
begin
Result := FStdAcc.accLocation(pxLeft, pyTop, pcxWidth, pcyHeight, varChild);
end;
function TAccObject.accNavigate(navDir: Integer; varStart: NewOleVariant;
var pvarEnd: NewOleVariant): HRESULT;
begin
Result := FStdAcc.accNavigate(navDir, varStart, pvarEnd);
end;
function TAccObject.accSelect(flagsSelect: Integer;
varChild: NewOleVariant): HRESULT;
begin
Result := FStdAcc.accSelect(flagsSelect, varChild);
end;
function TAccObject.get_accChild(varChild: NewOleVariant;
var ppdispChild: IDispatch): HRESULT;
begin
Result := FStdAcc.get_accChild(varChild, ppdispChild);
end;
function TAccObject.get_accChildCount(var pcountChildren: Integer): HRESULT;
begin
Result := FStdAcc.get_accChildCount(pcountChildren);
end;
function TAccObject.get_accDefaultAction(varChild: NewOleVariant;
var pszDefaultAction: NewWideString): HRESULT;
begin
{ A list box's default action is Double Click, which is useless for a
list of check boxes. }
pszDefaultAction := nil;
Result := S_FALSE;
end;
function TAccObject.get_accDescription(varChild: NewOleVariant;
var pszDescription: NewWideString): HRESULT;
begin
Result := FStdAcc.get_accDescription(varChild, pszDescription);
end;
function TAccObject.get_accFocus(var pvarID: NewOleVariant): HRESULT;
begin
Result := FStdAcc.get_accFocus(pvarID);
end;
function TAccObject.get_accHelp(varChild: NewOleVariant;
var pszHelp: NewWideString): HRESULT;
begin
Result := FStdAcc.get_accHelp(varChild, pszHelp);
end;
function TAccObject.get_accHelpTopic(var pszHelpFile: NewWideString;
varChild: NewOleVariant; var pidTopic: Integer): HRESULT;
begin
Result := FStdAcc.get_accHelpTopic(pszHelpFile, varChild, pidTopic);
end;
function TAccObject.get_accKeyboardShortcut(varChild: NewOleVariant;
var pszKeyboardShortcut: NewWideString): HRESULT;
begin
Result := FStdAcc.get_accKeyboardShortcut(varChild, pszKeyboardShortcut);
end;
function TAccObject.get_accName(varChild: NewOleVariant;
var pszName: NewWideString): HRESULT;
begin
Result := FStdAcc.get_accName(varChild, pszName);
end;
function TAccObject.get_accParent(var ppdispParent: IDispatch): HRESULT;
begin
Result := FStdAcc.get_accParent(ppdispParent);
end;
function TAccObject.get_accRole(varChild: NewOleVariant;
var pvarRole: NewOleVariant): HRESULT;
begin
pvarRole.vt := VT_EMPTY;
if FControl = nil then begin
Result := E_FAIL;
Exit;
end;
if varChild.vt <> VT_I4 then begin
Result := E_INVALIDARG;
Exit;
end;
if varChild.lVal = CHILDID_SELF then begin
pvarRole.lVal := ROLE_SYSTEM_OUTLINE;
pvarRole.vt := VT_I4;
Result := S_OK;
end
else begin
try
case FControl.ItemStates[varChild.lVal-1].ItemType of
itCheck: pvarRole.lVal := ROLE_SYSTEM_CHECKBUTTON;
itRadio: pvarRole.lVal := ROLE_SYSTEM_RADIOBUTTON;
else
pvarRole.lVal := ROLE_SYSTEM_STATICTEXT;
end;
pvarRole.vt := VT_I4;
Result := S_OK;
except
Result := E_INVALIDARG;
end;
end;
end;
function TAccObject.get_accSelection(var pvarChildren: NewOleVariant): HRESULT;
begin
Result := FStdAcc.get_accSelection(pvarChildren);
end;
function TAccObject.get_accState(varChild: NewOleVariant;
var pvarState: NewOleVariant): HRESULT;
var
ItemState: TItemState;
begin
Result := FStdAcc.get_accState(varChild, pvarState);
try
if (Result = S_OK) and (varChild.vt = VT_I4) and
(varChild.lVal <> CHILDID_SELF) and (pvarState.vt = VT_I4) and
Assigned(FControl) then begin
ItemState := FControl.ItemStates[varChild.lVal-1];
case ItemState.State of
cbChecked: pvarState.lVal := pvarState.lVal or STATE_SYSTEM_CHECKED;
cbGrayed: pvarState.lVal := pvarState.lVal or STATE_SYSTEM_MIXED;
end;
if not ItemState.Enabled then
pvarState.lVal := pvarState.lVal or STATE_SYSTEM_UNAVAILABLE;
end;
except
Result := E_INVALIDARG;
end;
end;
function TAccObject.get_accValue(varChild: NewOleVariant;
var pszValue: NewWideString): HRESULT;
begin
pszValue := nil;
if FControl = nil then begin
Result := E_FAIL;
Exit;
end;
if varChild.vt <> VT_I4 then begin
Result := E_INVALIDARG;
Exit;
end;
if varChild.lVal = CHILDID_SELF then
Result := S_FALSE
else begin
{ Return the level as the value, like standard tree view controls do.
Not sure if any screen readers will actually use this, seeing as we
aren't a real tree view control. }
try
pszValue := StringToOleStr(IntToStr(FControl.ItemStates[varChild.lVal-1].Level));
Result := S_OK;
except
Result := E_INVALIDARG;
end;
end;
end;
function TAccObject.put_accName(varChild: NewOleVariant;
const pszName: NewWideString): HRESULT;
begin
Result := S_FALSE;
end;
function TAccObject.put_accValue(varChild: NewOleVariant;
const pszValue: NewWideString): HRESULT;
begin
Result := S_FALSE;
end;
procedure Register;
begin
RegisterComponents('JR', [TNewCheckListBox]);
end;
procedure InitCanQueryUIState;
var
OSVersionInfo: TOSVersionInfo;
begin
CanQueryUIState := False;
if Win32Platform = VER_PLATFORM_WIN32_NT then begin
OSVersionInfo.dwOSVersionInfoSize := SizeOf(OSVersionInfo);
if GetVersionEx(OSVersionInfo) then
CanQueryUIState := OSVersionInfo.dwMajorVersion >= 5;
end;
end;
{ Note: This COM initialization code based on code from DBTables }
var
SaveInitProc: Pointer;
NeedToUninitialize: Boolean;
procedure InitCOM;
begin
if SaveInitProc <> nil then TProcedure(SaveInitProc);
NeedToUninitialize := SUCCEEDED(CoInitialize(nil));
end;
initialization
if not IsLibrary then begin
SaveInitProc := InitProc;
InitProc := @InitCOM;
end;
InitCanQueryUIState;
InitThemeLibrary;
NotifyWinEventFunc := GetProcAddress(GetModuleHandle(user32), 'NotifyWinEvent');
finalization
if NeedToUninitialize then
CoUninitialize;
end.
|
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=]
Copyright (c) 2013, Jarl K. <Slacky> Holta || http://github.com/WarPie
All rights reserved.
For more info see: Copyright.txt
[=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=}
{*
Normalizes the matrix in the range `Alpha` -> `Beta`
*}
function Normalize(const Mat:T2DByteArray; Alpha,Beta:Byte): T2DByteArray; overload;
var
Lo,Hi,oldRange,newRange:Byte;
X,Y,W,H: Int32;
begin
H := High(Mat);
if (length(mat) = 0) then
NewException('Matrix must be initalized');
W := High(Mat[0]);
SetLength(Result, H+1,W+1);
MinMax(Mat, Lo,Hi);
oldRange := Hi-Lo;
newRange := Beta-Alpha;
for Y:=0 to H do
for X:=0 to W do
Result[Y,X] := Round((Mat[Y,X] - lo) / oldRange * newRange + Alpha);
end;
function Normalize(const Mat:T2DIntArray; Alpha,Beta:Int32): T2DIntArray; overload;
var
Lo,Hi,oldRange,newRange:Int32;
X,Y,W,H: Int32;
begin
H := High(Mat);
if H = -1 then Exit();
W := High(Mat[0]);
SetLength(Result, H+1,W+1);
MinMax(Mat, Lo,Hi);
oldRange := Hi-Lo;
newRange := Beta-Alpha;
for Y:=0 to H do
for X:=0 to W do
Result[Y,X] := Round((Mat[Y,X] - lo) / oldRange * newRange + Alpha);
end;
function Normalize(const Mat:T2DExtArray; Alpha,Beta:Extended): T2DExtArray; overload;
var
Lo,Hi,oldRange,newRange:Extended;
X,Y,W,H: Int32;
begin
H := High(Mat);
if (length(mat) = 0) then
NewException('Matrix must be initalized');
W := High(Mat[0]);
SetLength(Result, H+1,W+1);
MinMax(Mat, Lo,Hi);
oldRange := Hi-Lo;
newRange := Beta-Alpha;
for Y:=0 to H do
for X:=0 to W do
Result[Y,X] := (Mat[Y,X] - lo) / oldRange * newRange + Alpha;
end;
function Normalize(const Mat:T2DDoubleArray; Alpha,Beta:Double): T2DDoubleArray; overload;
var
Lo,Hi,oldRange,newRange:Double;
X,Y,W,H: Int32;
begin
H := High(Mat);
if (length(mat) = 0) then
NewException('Matrix must be initalized');
W := High(Mat[0]);
SetLength(Result, H+1,W+1);
MinMax(Mat, Lo,Hi);
oldRange := Hi-Lo;
newRange := Beta-Alpha;
for Y:=0 to H do
for X:=0 to W do
Result[Y,X] := (Mat[Y,X] - lo) / oldRange * newRange + Alpha;
end;
function Normalize(const Mat:T2DFloatArray; Alpha,Beta:Single): T2DFloatArray; overload;
var
Lo,Hi,oldRange,newRange:Single;
X,Y,W,H: Int32;
begin
H := High(Mat);
if (length(mat) = 0) then
NewException('Matrix must be initalized');
W := High(Mat[0]);
SetLength(Result, H+1,W+1);
MinMax(Mat, Lo,Hi);
oldRange := Hi-Lo;
newRange := Beta-Alpha;
for Y:=0 to H do
for X:=0 to W do
Result[Y,X] := (Mat[Y,X] - lo) / oldRange * newRange + Alpha;
end;
|
unit Serie;
interface
uses XMLDoc, Utils, StrUtils, SysUtils, IdHTTP, IdBaseComponent,
IdComponent, IdTCPConnection, IdTCPClient, Dialogs;
type
TSerieManager = class(TObject)
private
_path: string;
_id: integer;
_title: string;
_episode: array of array of string;
public
constructor Create(path: string);
destructor Destroy; override;
function GetID: integer;
function GetTitle: string;
function GetSeasonsCount: integer;
function GetEpisodesCount(season: integer): integer;
function GetEpisodeTitle(season: integer; episode: integer): string;
procedure EditSerie(id: Integer; title: string);
function Exists(id: integer): boolean;
procedure LoadFromXML(id: integer);
procedure SaveToXML;
procedure addFromAllocine(id: integer; title : string);
end;
implementation
uses Unit1;
const
urlSaison = 'http://www.allocine.fr/series/ficheserie-XX/saisons/';
urlAutreSaison = 'http://www.allocine.fr/series/ficheserie-XX1/saison-XX2/';
constructor TSerieManager.Create(path: string);
begin
_path := path;
_id := 0;
_title := '';
SetLength(_episode, 0);
end;
destructor TSerieManager.Destroy;
begin
SetLength(_episode, 0);
inherited;
end;
function TSerieManager.GetID: integer;
begin
Result := _id;
end;
function TSerieManager.GetTitle: string;
begin
Result := _title;
end;
function TSerieManager.GetSeasonsCount: integer;
begin
Result := Length(_episode);
end;
function TSerieManager.GetEpisodesCount(season: integer): integer;
begin
if season <= Length(_episode) then
Result := Length(_episode[season - 1])
else
Result := 0;
end;
function TSerieManager.GetEpisodeTitle(season: integer; episode: integer)
: string;
begin
if ((season <= Length(_episode)) and
(episode <= Length(_episode[season - 1]))) then
Result := _episode[season - 1][episode - 1]
else
Result := '';
end;
procedure TSerieManager.EditSerie(id: Integer; title: string);
var
XMLDoc: TXMLDocument;
i: Integer;
begin
XMLDoc := TXMLDocument.Create(Form1);
XMLDoc.Active := true;
try
if _id=id then _title := title;
XMLDoc.LoadFromFile(_path);
for i := 0 to XMLDoc.DocumentElement.ChildNodes.Count - 1 do
begin
if XMLDoc.DocumentElement.ChildNodes[i].Attributes['id'] = IntToStr
(id) then
begin
XMLDoc.DocumentElement.ChildNodes[i].ChildNodes[0].Text := title;
break;
end;
end;
XMLDoc.SaveToFile(_path);
finally
XMLDoc.Active := false;
XMLDoc.Free;
end;
end;
procedure TSerieManager.addFromAllocine(id: integer; title : string);
var
urlMain: string;
page, num, titre, check, buf: string;
pos, saison, curSaison, posmax, seasonCount, index: Integer;
autrePage: array of string;
http : TIdHTTP;
begin
_id := id;
_title := title;
urlMain := AnsiReplaceText(urlSaison, 'XX', IntToStr(id));
http := TIdHTTP.Create(Form1);
http.HandleRedirects := True;
page := http.Get(urlMain);
pos := posex('class="card card-entity card-season cf card-entity-list hred"', page);
SetLength(autrePage, 50);
seasonCount := 0;
pos := posex('saison-', page, pos + 1);
while (pos <> 0) do
begin
autrePage[seasonCount] := Copy(page, pos + 7, posex('/', page, pos)
- pos - 7);
pos := posex('>', page, pos + 1);
inc(seasonCount);
pos := posex('class="card card-entity card-season cf card-entity-list hred"', page, pos+1);
if pos = 0 then
break;
pos := posex('saison-', page, pos + 1);
end;
SetLength(autrePage, seasonCount);
SetLength(_episode, seasonCount);
log('Number of seasons: ' + IntToStr(seasonCount));
for saison := seasonCount downto 1 do
begin
urlMain := AnsiReplaceText(urlAutreSaison, 'XX1', IntToStr(id));
urlMain := AnsiReplaceText(urlMain, 'XX2', autrePage[saison - 1]);
page := http.Get(urlMain);
pos := posex('titlebar-page"><div class="titlebar-title titlebar-title-lg"', page)+60;
if (posex('Saison ', page, pos)-pos) < 15 then pos := posex('Saison ', page, pos)+7
else continue;
if TryStrToInt(Copy(page, pos, posex('<', page, pos)-pos), curSaison) then
begin
log( 'Season ' + IntToStr(curSaison) + ' ...');
index := 0;
SetLength(_episode[curSaison-1], 50);
pos := posex('class="card-entity card-episode row row-col-padded-10 hred"', page);
pos := posex('"meta-title">', page, pos)+14;
pos := posex('>S', page, pos);
while pos <> 0 do
begin
num := Copy(page, pos+5, 2);
pos := pos + 10;
titre := Copy(page, pos, posex('</', page, pos) - pos);
_episode[curSaison-1][StrToInt(num) - 1] := filterName(titre);
inc(index);
pos := posex('class="card-entity card-episode row row-col-padded-10 hred"', page, pos);
if pos = 0 then break;
pos := posex('"meta-title">', page, pos);
if pos = 0 then break;
pos := posex('>S', page, pos);
end;
SetLength(_episode[curSaison-1], index);
end;
end;
http.Disconnect;
http.Free;
SaveToXML;
end;
procedure TSerieManager.LoadFromXML(id: integer);
var
iSerie, iSaison, iEpisode: integer;
XMLDoc: TXMLDocument;
begin
_id := id;
XMLDoc := TXMLDocument.Create(Form1);
XMLDoc.Active := true;
if FileExists(_path) then
begin
XMLDoc.LoadFromFile(_path);
with XMLDoc.DocumentElement.ChildNodes do
begin
for iSerie := 0 to Count - 1 do
begin
if Get(iSerie).Attributes['id'] = IntToStr(id) then
begin
_title := Get(iSerie).ChildNodes[0].Text;
with Get(iSerie).ChildNodes[1].ChildNodes do
begin
SetLength(_episode, Count);
for iSaison := 0 to Count - 1 do
begin
SetLength(_episode[iSaison], Get(iSaison)
.ChildNodes[0].ChildNodes.Count);
for iEpisode := 0 to Get(iSaison)
.ChildNodes[0].ChildNodes.Count - 1 do
begin
_episode[iSaison][iEpisode] := Get(iSaison)
.ChildNodes[0].ChildNodes[iEpisode].ChildNodes
[0].Text;
end;
end;
end;
end;
end;
end;
end;
XMLDoc.Active := false;
XMLDoc.Free;
end;
procedure TSerieManager.SaveToXML;
var
XMLDoc: TXMLDocument;
i, o: integer;
begin
if _id <> 0 then
begin
XMLDoc := TXMLDocument.Create(Form1);
XMLDoc.Active := true;
try
if FileExists(_path) then
begin
XMLDoc.LoadFromFile(_path);
end
else
begin
XMLDoc.Version := '1.0';
XMLDoc.Encoding := 'UTF-8';
XMLDoc.DocumentElement := XMLDoc.CreateElement('Series', '');
end;
with XMLDoc.DocumentElement.AddChild('Serie') do
begin
Attributes['id'] := _id;
AddChild('Name').Text := _title;
with AddChild('Seasons') do
begin
for i := 0 to Length(_episode) - 1 do
begin
with AddChild('Season') do
begin
Attributes['num'] := IntToStr(i + 1);
with AddChild('Episodes') do
begin
for o := 0 to Length(_episode[i]) - 1 do
begin
with AddChild('Episode') do
begin
Attributes['num'] := IntToStr(o + 1);
AddChild('Title').Text := _episode[i]
[o];
end;
end;
end;
end;
end;
end;
end;
XMLDoc.SaveToFile(_path);
finally
XMLDoc.Active := false;
XMLDoc.Free;
end;
end;
end;
function TSerieManager.Exists(id: integer): boolean;
var
pos : integer;
XMLDoc: TXMLDocument;
begin
Result := false;
XMLDoc := TXMLDocument.Create(Form1);
XMLDoc.Active := true;
if FileExists(_path) then
begin
XMLDoc.LoadFromFile(_path);
for pos := 0 to XMLDoc.DocumentElement.ChildNodes.Count - 1 do
begin
if XMLDoc.DocumentElement.ChildNodes[pos].Attributes['id']
= IntToStr(id) then
begin
Result := true;
break;
end;
end;
end;
XMLDoc.Active := false;
XMLDoc.Free;
end;
end.
|
unit DelphiMediaPlayer;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, MPlayer, ComCtrls, StdCtrls, ExtCtrls, Menus;
type
TForm1 = class(TForm)
Screen: TPanel;
PlayList: TListBox;
BtnAddFile: TButton;
BtnPlay: TButton;
BtnStop: TButton;
TimeLine: TProgressBar;
StatusBar: TStatusBar;
MediaPlayer: TMediaPlayer;
OpenDialogBox: TOpenDialog;
BtnPause: TButton;
BtnLoad: TButton;
MainMenu1: TMainMenu;
Menu1: TMenuItem;
Info1: TMenuItem;
Exit1: TMenuItem;
Timer1: TTimer;
BtnPrior: TButton;
BtnNext: TButton;
BtnUpPlaylist: TButton;
BtnDownPlaylist: TButton;
BtnRemovePlayList: TButton;
RandomPlay: TCheckBox;
FileInfoBox: TRichEdit;
procedure BtnAddFileClick(Sender: TObject);
procedure BtnPlayClick(Sender: TObject);
procedure BtnStopClick(Sender: TObject);
procedure Info1Click(Sender: TObject);
procedure Exit1Click(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure BtnLoadClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure BtnPauseClick(Sender: TObject);
procedure BtnNextClick(Sender: TObject);
procedure BtnPriorClick(Sender: TObject);
procedure BtnRemovePlayListClick(Sender: TObject);
procedure BtnUpPlaylistClick(Sender: TObject);
procedure BtnDownPlaylistClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses Math;
{$R *.dfm}
// Play File
function PlayFile(): integer;
begin
Form1.MediaPlayer.DisplayRect := Rect(0, 0, Form1.Screen.Width, Form1.Screen.Height);
Form1.MediaPlayer.Display := Form1.Screen;
Form1.MediaPlayer.Play;
Form1.Timer1.Enabled := true;
// Enable Pause and Stop buttons
Form1.BtnPause.Enabled := true;
Form1.BtnStop.Enabled := true;
// Disable Play button
Form1.BtnPlay.Enabled := false;
Result := 1;
end;
// Move an item up
procedure LbMoveItemUp(AListBox: TListBox);
var
CurrIndex: Integer;
begin
with AListBox do
if ItemIndex > 0 then
begin
CurrIndex := ItemIndex;
Items.Move(ItemIndex, (CurrIndex - 1));
ItemIndex := CurrIndex - 1;
end;
end;
// Move an item down
procedure LbMoveItemDown(AListBox: TListBox);
var
CurrIndex, LastIndex: Integer;
begin
with AListBox do
begin
CurrIndex := ItemIndex;
LastIndex := Items.Count;
if ItemIndex <> -1 then
begin
if CurrIndex + 1 < LastIndex then
begin
Items.Move(ItemIndex, (CurrIndex + 1));
ItemIndex := CurrIndex + 1;
end;
end;
end;
end;
// Next file
procedure nextFile();
begin
if Form1.PlayList.ItemIndex+1 < Form1.PlayList.Items.Count then
begin
// Open file
Form1.MediaPlayer.FileName := Form1.PlayList.Items.Strings[Form1.PlayList.ItemIndex+1];
Form1.MediaPlayer.Open;
Form1.StatusBar.SimpleText := Form1.MediaPlayer.FileName;
// Init progress bar status
Form1.TimeLine.Position := 0;
Form1.TimeLine.Min :=0 ;
Form1.TimeLine.Max := Form1.MediaPlayer.Length;
// Play
PlayFile();
Form1.PlayList.ItemIndex := Form1.PlayList.ItemIndex+1;
end
else
begin
// Open file
Form1.MediaPlayer.FileName := Form1.PlayList.Items.Strings[0];
Form1.MediaPlayer.Open;
Form1.StatusBar.SimpleText := Form1.MediaPlayer.FileName;
// Init progress bar status
Form1.TimeLine.Position := 0;
Form1.TimeLine.Min :=0 ;
Form1.TimeLine.Max := Form1.MediaPlayer.Length;
// Play
PlayFile();
Form1.PlayList.ItemIndex := 0;
end;
end;
// Next random file
procedure nextRandomFile();
var
randomindex : integer;
begin
randomindex := Random(Form1.PlayList.Items.Count-1);
// Open file
Form1.MediaPlayer.FileName := Form1.PlayList.Items.Strings[randomindex];
Form1.MediaPlayer.Open;
Form1.StatusBar.SimpleText := Form1.MediaPlayer.FileName;
// Init progress bar status
Form1.TimeLine.Position := 0;
Form1.TimeLine.Min :=0 ;
Form1.TimeLine.Max := Form1.MediaPlayer.Length;
// Play
PlayFile();
Form1.PlayList.ItemIndex := randomindex;
end;
// Continue playing
procedure ContinuePlaying(random: boolean);
begin
if random then
begin
nextRandomFile();
end
else
begin
nextFile();
end
end;
procedure TForm1.BtnAddFileClick(Sender: TObject);
begin
// Add news items to the play list
if OpenDialogBox.Execute then
PlayList.Items.Add(OpenDialogBox.FileName);
end;
procedure TForm1.BtnPlayClick(Sender: TObject);
begin
if PlayList.ItemIndex = -1 then
begin
ShowMessage('Please, select an item from the playlist!');
end
else
begin
// Play
PlayFile();
end
end;
procedure TForm1.BtnStopClick(Sender: TObject);
begin
// Stop and close file
MediaPlayer.Stop;
MediaPlayer.Close;
// Reset timeline
TimeLine.Position := 0;
// Enable Play button
BtnPlay.Enabled := false;
BtnPause.Enabled := false;
BtnStop.Enabled := false;
Timer1.Enabled := false;
end;
procedure TForm1.Info1Click(Sender: TObject);
begin
ShowMessage('Delphi Media Player 1.0');
end;
procedure TForm1.Exit1Click(Sender: TObject);
begin
// Close Form
Form1.Close;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
TimeLine.Position := MediaPlayer.Position;
if TimeLine.Position = MediaPlayer.Length then
begin
Timer1.Enabled := false;
ContinuePlaying(RandomPlay.Checked);
end;
end;
procedure TForm1.BtnLoadClick(Sender: TObject);
begin
if PlayList.ItemIndex = -1 then
begin
ShowMessage('Please, select an item from the playlist!');
end
else
begin
MediaPlayer.FileName := PlayList.Items.Strings[PlayList.ItemIndex];
MediaPlayer.Open;
StatusBar.SimpleText := MediaPlayer.FileName;
// Init progress bar status
TimeLine.Min :=0 ;
TimeLine.Max := MediaPlayer.Length;
// Enable play button
BtnPlay.Enabled := true;
end
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
// Save playlist
PlayList.Items.SaveToFile('C:\playlist.txt');
if TimeLine.Position > 0 then
begin
FileInfoBox.Lines.Clear;
FileInfoBox.Lines.Add(MediaPlayer.FileName);
FileInfoBox.Lines.Add(IntToStr(TimeLine.Position));
FileInfoBox.Lines.SaveToFile('C:\currentfile.txt');
end
else
begin
FileInfoBox.Lines.Clear;
FileInfoBox.Lines.SaveToFile('C:\currentfile.txt');
end
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
// Load playlist
PlayList.Items.LoadFromFile('C:\playlist.txt');
FileInfoBox.Lines.LoadFromFile('C:\currentfile.txt');
if not (FileInfoBox.Lines.Strings[0] = '') then
begin
if PlayList.Items.Count > 0 then
begin
MediaPlayer.FileName := FileInfoBox.Lines.Strings[0];
MediaPlayer.Open;
MediaPlayer.Position := StrToInt(FileInfoBox.Lines.Strings[1]);
StatusBar.SimpleText := MediaPlayer.FileName;
// Init progress bar status
TimeLine.Min :=0 ;
TimeLine.Max := MediaPlayer.Length;
TimeLine.Position := StrToInt(FileInfoBox.Lines.Strings[1]);
// Play
PlayFile();
end;
end;
end;
procedure TForm1.BtnPauseClick(Sender: TObject);
begin
MediaPlayer.Pause;
// Enable Play button
BtnPlay.Enabled := true;
end;
procedure TForm1.BtnNextClick(Sender: TObject);
begin
nextFile();
end;
procedure TForm1.BtnPriorClick(Sender: TObject);
begin
if PlayList.ItemIndex > 0 then
begin
// Open file
MediaPlayer.FileName := PlayList.Items.Strings[PlayList.ItemIndex-1];
MediaPlayer.Open;
StatusBar.SimpleText := MediaPlayer.FileName;
// Init progress bar status
TimeLine.Position := 0;
TimeLine.Min :=0 ;
TimeLine.Max := MediaPlayer.Length;
// Play
PlayFile();
PlayList.ItemIndex := PlayList.ItemIndex-1;
end
else
begin
// Open file
MediaPlayer.FileName := PlayList.Items.Strings[PlayList.Items.Count-1];
MediaPlayer.Open;
StatusBar.SimpleText := MediaPlayer.FileName;
// Init progress bar status
TimeLine.Position := 0;
TimeLine.Min :=0 ;
TimeLine.Max := MediaPlayer.Length;
// Play
PlayFile();
PlayList.ItemIndex := PlayList.Items.Count-1;
end;
end;
procedure TForm1.BtnRemovePlayListClick(Sender: TObject);
begin
PlayList.Items.Delete(PlayList.ItemIndex);
end;
procedure TForm1.BtnUpPlaylistClick(Sender: TObject);
begin
LbMoveItemUp(PlayList);
end;
procedure TForm1.BtnDownPlaylistClick(Sender: TObject);
begin
LbMoveItemDown(PlayList);
end;
end.
|
{!DOCTOPIC}{
OS module
}
{!DOCREF} {
@method: var OS = TObjOS;
@desc:
This module provides you with a miscellaneous operating system dependent functions.
[note]Note that SimbaExt is so far only build for Windows. This module will be modified to be cross-platform if linux ever where to be supported.[/note]
}
{!DOCREF} {
@method: function OS.GetEnviron(Varname:String): String;
@desc:
Call GetEnviron to retrieve the value of an environment variable
[code=pascal]
begin
WriteLn(OS.GetEnviron('PATH'));
end.
[/code]
}
function TObjOS.GetEnviron(Varname:String): String;
begin
Result := exp_GetEnviron(Varname);
end;
{!DOCREF} {
@method: function OS.SetEnviron(Varname, Value:String): Boolean;
@desc: Call SetEnviron to set the value of an environment variable
}
function TObjOS.SetEnviron(Varname, Value:String): Boolean;
begin
Result := exp_SetEnviron(Varname, Value);
end;
{!DOCREF} {
@method: function OS.ListDir(Dir:String): TStringArray;
@desc:
Lists all the files and folders in the given directory
[code=pascal]WriteLn(OS.ListDir('C:\'));[/code]
}
function TObjOS.ListDir(Dir:String): TStringArray;
begin
exp_ListDir(Dir, Result);
end;
{!DOCREF} {
@method: function OS.Remove(FileName:String): Boolean;
@desc: Remove (delete) the file path.
}
function TObjOS.Remove(FileName:String): Boolean;
begin
Result := exp_FileRemove(FileName);
end;
{!DOCREF} {
@method: function OS.RmDir(Dir:String): Boolean;
@desc: Remove (delete) the directory path.
}
function TObjOS.RmDir(Dir:String): Boolean;
begin
Result := exp_DirRemove(Dir);
end;
{!DOCREF} {
@method: function OS.Rename(Src, Dest:String): Boolean;;
@desc: Rename the file or directory src to dst
}
function TObjOS.Rename(Src, Dest:String): Boolean;
begin
Result := exp_FileRename(Src, Dest);
end;
{!DOCREF} {
@method: function OS.CopyFile(Src, Dest:String): Boolean;
@desc: Copys the file or directory src to dst
}
function TObjOS.CopyFile(Src, Dest:String): Boolean;
begin
Result := exp_FileRename(Src, Dest);
end;
{!DOCREF} {
@method: function OS.Size(Loc:String): Int64;
@desc: Returns the size of the file or directory.
}
function TObjOS.Size(Loc:String): Int64;
begin
Result := exp_FileSize2(Loc);
end;
{!DOCREF} {
@method: function OS.FileSize(F:String): Int64;
@desc: Returns the size of the file.
}
function TObjOS.FileSize(F:String): Int64;
begin
Result := -1;
if OS.Path.IsFile(F) then
Result := exp_FileSize2(F);
end;
{!DOCREF} {
@method: function OS.ReadFile(FileName: String): String;
@desc:
Reads a file directly in to a string.
[code=pascal]
var Str:String;
begin
Str := os.readfile(os.path.abspath('settings.xml'));
WriteLn(str);
end.
[/code]
}
function TObjOS.ReadFile(FileName: String): String;
begin
if OS.Path.IsFile(FileName) then
Result := exp_ReadFile(FileName);
end;
{!DOCREF} {
@method: function OS.UTime(F:String; Times:TIntArray): Boolean;
@desc:
Set the 'created', 'access' and 'modificated' times of the file specified by path. If times is 0, then the file’s access and modified times is not modified.
[code=pascal]
var tnow: Int32;
begin
tnow := Trunc(TimeUtils.Time());
OS.UTime('somefile.txt', [0,tnow,tnow]);
end.
[/code]
}
function TObjOS.UTime(F:String; Times:TIntArray): Boolean;
begin
Result := exp_UTime(F,Times);
end;
{!DOCREF} {
@method: procedure OS.Touch(F:String);
@desc: Updates the access time of the given file path.
}
procedure TObjOS.Touch(F:String);
begin
exp_TouchFile(F);
end;
// OS.Path.* \\------------------------------------------------------||
{!DOCREF} {
@method: function OS.Path.NormPath(Loc:String): String;
@desc: Normalize a pathname by collapsing redundant separators and up-level references so that A//B, A/B/, A/./B and A/foo/../B all become A/B.
}
function TObjOSPath.NormPath(Loc:String): String;
begin
Result := exp_NormPath(Loc);
end;
{!DOCREF} {
@method: function OS.Path.AbsPath(Loc:String): String;
@desc: Return a normalized absolutized version of the pathname 'loc'.
}
function TObjOSPath.AbsPath(Loc:String): String;
begin
Result := exp_AbsPath(Loc);
end;
{!DOCREF} {
@method: function OS.Path.DirName(Loc:String): String;
@desc: Return the directory name of pathname 'loc'. This is the first element of the pair returned by passing 'loc' to the function split().
}
function TObjOSPath.DirName(Loc:String): String;
begin
Result := exp_DirName(Loc);
end;
{!DOCREF} {
@method: function OS.Path.Exists(Loc:String): Boolean;
@desc: Return True if 'loc' refers to an existing path.
}
function TObjOSPath.Exists(Loc:String): Boolean;
begin
Result := exp_PathExists(Loc);
end;
{!DOCREF} {
@method: function OS.Path.IsAbs(Loc:String): Boolean;
@desc: Return True if path is an absolute pathname, meaning it should begin with a drive letter.
}
function TObjOSPath.IsAbs(Loc:String): Boolean;
begin
Result := exp_IsAbsPath(Loc);
end;
{!DOCREF} {
@method: function OS.Path.IsFile(Loc:String): Boolean;
@desc: Return True if path refers to an existing file
}
function TObjOSPath.IsFile(Loc:String): Boolean;
begin
Result := exp_IsFile(Loc);
end;
{!DOCREF} {
@method: function OS.Path.IsDir(Loc:String): Boolean;
@desc: Return True if path refers to an existing dir
}
function TObjOSPath.IsDir(Loc:String): Boolean;
begin
Result := exp_IsDir(Loc);
end;
|
//********************************************
//autorun module by SpawN
//avalible function:
//1. DoAppToRun(Название,Полный путь до приложения); - Добавить в автозагрузку
//2. IsAppInRun(Название); - Проверить добавлено ли в автозагрузку
//3. DelAppFromRun(Название); - Удалить из автозагрузки
//********************************************
unit AutoRun;
interface
uses registry,Windows;
procedure DoAppToRun(RunName, AppName: string);
function IsAppInRun(RunName: string): Boolean;
procedure DelAppFromRun(RunName: string);
implementation
procedure DoAppToRun(RunName, AppName: string);
var
Reg: TRegistry;
begin
Reg := TRegistry.Create;
with Reg do
begin
RootKey := HKEY_LOCAL_MACHINE;
OpenKey('Software\Microsoft\Windows\CurrentVersion\Run', True);
WriteString(RunName, AppName);
CloseKey;
Free;
end;
end;
// Check if the application is in the registry...
function IsAppInRun(RunName: string): Boolean;
var
Reg: TRegistry;
begin
Reg := TRegistry.Create;
with Reg do
begin
RootKey := HKEY_LOCAL_MACHINE;
OpenKey('Software\Microsoft\Windows\CurrentVersion\Run', False);
Result := ValueExists(RunName);
CloseKey;
Free;
end;
end;
// Remove the application from the registry...
procedure DelAppFromRun(RunName: string);
var
Reg: TRegistry;
begin
Reg := TRegistry.Create;
with Reg do
begin
RootKey := HKEY_LOCAL_MACHINE;
OpenKey('Software\Microsoft\Windows\CurrentVersion\Run', True);
if ValueExists(RunName) then DeleteValue(RunName);
CloseKey;
Free;
end;
end;
end.
|
{ RxDBColorBox unit
Copyright (C) 2005-2010 Lagunov Aleksey alexs@yandex.ru and Lazarus team
original conception from rx library for Delphi (c)
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit RxDBColorBox;
{$I rx.inc}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ColorBox,
DbCtrls, DB, LMessages, LCLType;
type
{ TRxCustomDBColorBox }
TRxCustomDBColorBox = class(TCustomColorBox)
FDataLink: TFieldDataLink;
procedure DataChange(Sender: TObject);
function GetDataField: string;
function GetDataSource: TDataSource;
function GetField: TField;
function GetReadOnly: Boolean;
procedure SetDataField(const AValue: string);
procedure SetDataSource(const AValue: TDataSource);
procedure SetReadOnly(const AValue: Boolean);
procedure UpdateData(Sender: TObject);
procedure FocusRequest(Sender: TObject);
procedure ActiveChange(Sender: TObject);
procedure LayoutChange(Sender: TObject);
procedure CMGetDataLink(var Message: TLMessage); message CM_GETDATALINK;
function IsReadOnly: boolean;
protected
property DataField: string read GetDataField write SetDataField;
property DataSource: TDataSource read GetDataSource write SetDataSource;
property ReadOnly: Boolean read GetReadOnly write SetReadOnly default False;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure Change; override;
procedure Loaded; override;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
procedure WMSetFocus(var Message: TLMSetFocus); message LM_SETFOCUS;
procedure WMKillFocus(var Message: TLMKillFocus); message LM_KILLFOCUS;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Field: TField read GetField;
published
{ Published declarations }
end;
TRxDBColorBox = class(TRxCustomDBColorBox)
private
{ Private declarations }
protected
{ Protected declarations }
public
{ Public declarations }
published
property DataField;
property DataSource;
property ReadOnly;
property DefaultColorColor;
property NoneColorColor;
property Selected;
property Style;
property OnGetColors;
property Align;
property Anchors;
property ArrowKeysTraverseList;
property AutoComplete;
property AutoCompleteText;
property AutoDropDown;
property AutoSelect;
property AutoSize;
property BidiMode;
property BorderSpacing;
property Color;
property Constraints;
property DragCursor;
property DragMode;
property DropDownCount;
property Enabled;
property Font;
property ItemHeight;
property ItemWidth;
property OnChange;
property OnChangeBounds;
property OnClick;
property OnCloseUp;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnDropDown;
property OnEditingDone;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnMouseWheelDown;
property OnMouseWheelUp;
property OnStartDrag;
property OnSelect;
property OnUTF8KeyPress;
property ParentBidiMode;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
end;
implementation
uses
LCLVersion;
type
TFieldDataLinkHack = class(TFieldDataLink)
end;
{ TRxCustomDBColorBox }
procedure TRxCustomDBColorBox.DataChange(Sender: TObject);
begin
if Assigned(FDataLink.Field) and (FDataLink.Field.DataType in [ftString, ftInteger, ftLargeint]) then
begin
if FDatalink.Field.DataType in [ftString] then
begin
if FDatalink.Field.AsString<>'' then
try
Selected:=StringToColor(FDatalink.Field.AsString)
except
Selected:=clNone;
end
else
Selected:=clNone;
end
else
if FDataLink.Field.DataType in [ftInteger, ftLargeint] then
begin
try
Selected:=TColor(FDatalink.Field.AsInteger);
except
Selected:=clNone;
end;
end;
end
else
begin
Selected := clNone;
end;
end;
function TRxCustomDBColorBox.GetDataField: string;
begin
Result := FDataLink.FieldName;
end;
function TRxCustomDBColorBox.GetDataSource: TDataSource;
begin
Result := FDataLink.DataSource;
end;
function TRxCustomDBColorBox.GetField: TField;
begin
Result := FDataLink.Field;
end;
function TRxCustomDBColorBox.GetReadOnly: Boolean;
begin
Result := FDataLink.ReadOnly;
end;
procedure TRxCustomDBColorBox.SetDataField(const AValue: string);
begin
FDataLink.FieldName := AValue;
end;
procedure TRxCustomDBColorBox.SetDataSource(const AValue: TDataSource);
begin
ChangeDataSource(Self,FDataLink,AValue);
end;
procedure TRxCustomDBColorBox.SetReadOnly(const AValue: Boolean);
begin
inherited;
FDataLink.ReadOnly := AValue;
end;
procedure TRxCustomDBColorBox.UpdateData(Sender: TObject);
begin
if FDataLink.Field.DataType in [ftString] then
FDataLink.Field.AsString := ColorToString(Selected)
else
if FDataLink.Field.DataType in [ftInteger, ftLargeint] then
FDataLink.Field.AsInteger := Integer(Selected);
end;
procedure TRxCustomDBColorBox.FocusRequest(Sender: TObject);
begin
SetFocus;
end;
procedure TRxCustomDBColorBox.ActiveChange(Sender: TObject);
begin
if FDatalink.Active then
DataChange(Sender)
else
begin
Selected := clNone;
FDataLink.Reset;
end;
end;
procedure TRxCustomDBColorBox.LayoutChange(Sender: TObject);
begin
DataChange(Sender);
end;
procedure TRxCustomDBColorBox.CMGetDataLink(var Message: TLMessage);
begin
Message.Result := PtrUInt(FDataLink);
end;
function TRxCustomDBColorBox.IsReadOnly: boolean;
begin
Result := true;
if FDatalink.Active and (not Self.ReadOnly) then
Result := (Field = nil) or Field.ReadOnly;
end;
procedure TRxCustomDBColorBox.KeyDown(var Key: Word; Shift: TShiftState);
begin
inherited KeyDown(Key, Shift);
if Key=VK_ESCAPE then
begin
//cancel out of editing by reset on esc
FDataLink.Reset;
SelectAll;
Key := VK_UNKNOWN;
end
else
if Key=VK_DELETE then
begin
if not IsReadOnly then
FDatalink.Edit;
end
else
if Key=VK_TAB then
begin
if FDataLink.CanModify and FDatalink.Editing then
FDataLink.UpdateRecord;
end;
end;
procedure TRxCustomDBColorBox.Change;
begin
FDatalink.Edit;
FDataLink.Modified;
inherited Change;
end;
procedure TRxCustomDBColorBox.Loaded;
begin
inherited Loaded;
if (csDesigning in ComponentState) then
DataChange(Self);
end;
procedure TRxCustomDBColorBox.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation=opRemove) then
begin
if (FDataLink<>nil) and (AComponent=DataSource) then
DataSource:=nil;
end;
end;
procedure TRxCustomDBColorBox.WMSetFocus(var Message: TLMSetFocus);
begin
inherited WMSetFocus(Message);
if not FDatalink.Editing then
FDatalink.Reset;
end;
procedure TRxCustomDBColorBox.WMKillFocus(var Message: TLMKillFocus);
begin
inherited WMKillFocus(Message);
if not FDatalink.Editing then
FDatalink.Reset
else
TFieldDataLinkHack(FDatalink).UpdateData;
end;
constructor TRxCustomDBColorBox.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDataLink := TFieldDataLink.Create;
FDataLink.Control := Self;
FDataLink.OnDataChange := @DataChange;
FDataLink.OnUpdateData := @UpdateData;
FDataLink.OnActiveChange := @ActiveChange;
{$if (lcl_major = 0) and (lcl_release <= 30)}
FDataLink.OnLayoutChange := @LayoutChange;
{$endif}
end;
destructor TRxCustomDBColorBox.Destroy;
begin
FreeAndNil(FDataLink);
inherited Destroy;
end;
end.
|
unit cmdlinefpccond;
interface
uses
SysUtils;
//todo: need to distingiush between cpu and os.
// the list however, need to come externally
type
{ TFPCConditionCheck }
TFPCConditionCheck = class(TObject)
private
fCndStr: string;
cnt : integer;
fCnd : array of record cpu, os: string end;
procedure AddSubCond(const cond: string);
procedure ParseStr(const ACndStr: string);
public
constructor Create(const ACndStr: string);
function isValid(const cpu, os: string): Boolean;
property CndStr: string read fCndStr;
end;
implementation
procedure ParseCPUOS(const cpu_os: string; var cpu, os : string);
var
i : integer;
begin
//todo: see todo above!
i:=Pos('-', cpu_os);
if i>0 then begin
cpu:=Copy(cpu_os, 1, i-1);
os:=Copy(cpu_os, i+1, length(cpu_os));
end else begin
cpu:=cpu_os;
os:='';
end;
end;
{ TFPCConditionCheck }
procedure TFPCConditionCheck.AddSubCond(const cond: string);
var
os,cpu: string;
begin
os:=''; cpu:='';
ParseCPUOS(cond, cpu, os);
if cpu<>'' then begin
if cnt=length(fCnd) then begin
if cnt=0 then SetLength(fCnd, 4)
else SetLEngth(fCnd, cnt*2);
end;
fCnd[cnt].cpu:=AnsiLowerCase(cpu);
fCnd[cnt].os:=AnsiLowerCase(os);
inc(cnt);
end;
end;
procedure TFPCConditionCheck.ParseStr(const ACndStr: string);
var
i : integer;
j : integer;
s : string;
begin
j:=1;
cnt:=0;
i:=1;
while i<=length(ACndStr) do begin
if ACndStr[i] in [','] then begin
s:=trim(Copy(ACndStr, j, i-j));
if s<>'' then AddSubCond(s);
j:=i+1;
end;
inc(i);
end;
if j<length(ACndStr) then
AddSubCond( Copy(ACndStr, j, i-j));
SetLength(fCnd, cnt);
end;
constructor TFPCConditionCheck.Create(const ACndStr: string);
begin
inherited Create;
ParseStr(ACndStr);
fCndStr:=ACndStr;
end;
function TFPCConditionCheck.isValid(const cpu, os: string): Boolean;
var
i : integer;
a, b: string;
begin
if length(fCnd)=0 then begin
Result:=true;
Exit;
end;
a:=AnsiLowerCase(cpu);
b:=AnsiLowerCase(os);
if (cpu='') and (os<>'') then begin
a:=b;
b:='';
end;
for i:=0 to length(fCnd)-1 do begin
Result:=// complete match of os and cpu
((fCnd[i].os=b) and (fCnd[i].cpu=a))
// this is the check, when only OS or only CPU is specified as a condition
// but either CPU or OS has been passed.
// i.e.
// "i386" valid for "i386-linux" or "i386-Win32"
// "darwin" valid for "arm-darwin" or "i386-darwin"
// note, that if a condition consists only of a single string, it
// will always be saved into "cpu" field of the check record.
or ( (fCnd[i].os='') and ((fCnd[i].cpu=a) or (fCnd[i].cpu=b)));
if Result then Exit;
end;
Result:=False;
end;
end.
|
unit SessionInterfaces;
interface
uses
Classes;
const
SESSION_NOERROR = 0;
SESSION_ERROR_Unknown = 1;
SESSION_ERROR_UnexpectedMember = 2;
type
IRDOSessionServer =
interface
// Connection handling
function Logon( Address : string; Port : integer; SessionId : string; out ErrorCode : integer ) : boolean;
procedure Logoff( out ErrorCode : integer );
procedure RegisterEventsHook( Hook : TObject );
// Member iteration
function GetMemberCount( out ErrorCode : integer ) : integer;
function GetMemberInfoByIdx( index : integer; out ErrorCode : integer ) : TStringList;
function GetMemberInfoByName( Name : string; out ErrorCode : integer ) : TStringList;
// Data interchange
procedure SendMessage ( Id : integer; Dest, Info : string; out ErrorCode : integer );
procedure SetMemberCookie ( Name : string; Cookie, Value : string; out ErrorCode : integer );
function GetMemberCookie ( Name : string; Cookie : string; out ErrorCode : integer ) : string;
procedure ModifyMemberCash( Name : string; Amount : currency; out ErrorCode : integer );
end;
IRDOSessionEvents =
interface
procedure RDONotifyMessage ( Id : integer; Sender, Info : widestring );
procedure RDONotifyMemberEntered( Name : widestring );
procedure RDONotifyMemberLeaved ( Name : widestring );
procedure RDONotifyCashChange ( Value : currency );
end;
const
tidRDOHook_SessionServer = 'SessionServer';
tidRDOHook_SessionEvents = 'SessionEvents';
tidMemberInfo_Name = 'Name';
tidMemberInfo_Cash = 'Cash';
implementation
end.
|
unit InfoCKACCTTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoCKACCTRecord = record
PAcctID: String[4];
PModCount: String[1];
PName: String[30];
PAccountNo: String[20];
PNextChkNo: String[6];
PRConDate: String[8];
PRConBal: Currency;
End;
TInfoCKACCTBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoCKACCTRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIInfoCKACCT = (InfoCKACCTPrimaryKey);
TInfoCKACCTTable = class( TDBISAMTableAU )
private
FDFAcctID: TStringField;
FDFModCount: TStringField;
FDFName: TStringField;
FDFAccountNo: TStringField;
FDFNextChkNo: TStringField;
FDFRConDate: TStringField;
FDFRConBal: TCurrencyField;
FDFCheckFmt: TBlobField;
procedure SetPAcctID(const Value: String);
function GetPAcctID:String;
procedure SetPModCount(const Value: String);
function GetPModCount:String;
procedure SetPName(const Value: String);
function GetPName:String;
procedure SetPAccountNo(const Value: String);
function GetPAccountNo:String;
procedure SetPNextChkNo(const Value: String);
function GetPNextChkNo:String;
procedure SetPRConDate(const Value: String);
function GetPRConDate:String;
procedure SetPRConBal(const Value: Currency);
function GetPRConBal:Currency;
procedure SetEnumIndex(Value: TEIInfoCKACCT);
function GetEnumIndex: TEIInfoCKACCT;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoCKACCTRecord;
procedure StoreDataBuffer(ABuffer:TInfoCKACCTRecord);
property DFAcctID: TStringField read FDFAcctID;
property DFModCount: TStringField read FDFModCount;
property DFName: TStringField read FDFName;
property DFAccountNo: TStringField read FDFAccountNo;
property DFNextChkNo: TStringField read FDFNextChkNo;
property DFRConDate: TStringField read FDFRConDate;
property DFRConBal: TCurrencyField read FDFRConBal;
property DFCheckFmt: TBlobField read FDFCheckFmt;
property PAcctID: String read GetPAcctID write SetPAcctID;
property PModCount: String read GetPModCount write SetPModCount;
property PName: String read GetPName write SetPName;
property PAccountNo: String read GetPAccountNo write SetPAccountNo;
property PNextChkNo: String read GetPNextChkNo write SetPNextChkNo;
property PRConDate: String read GetPRConDate write SetPRConDate;
property PRConBal: Currency read GetPRConBal write SetPRConBal;
published
property Active write SetActive;
property EnumIndex: TEIInfoCKACCT read GetEnumIndex write SetEnumIndex;
end; { TInfoCKACCTTable }
procedure Register;
implementation
procedure TInfoCKACCTTable.CreateFields;
begin
FDFAcctID := CreateField( 'AcctID' ) as TStringField;
FDFModCount := CreateField( 'ModCount' ) as TStringField;
FDFName := CreateField( 'Name' ) as TStringField;
FDFAccountNo := CreateField( 'AccountNo' ) as TStringField;
FDFNextChkNo := CreateField( 'NextChkNo' ) as TStringField;
FDFRConDate := CreateField( 'RConDate' ) as TStringField;
FDFRConBal := CreateField( 'RConBal' ) as TCurrencyField;
FDFCheckFmt := CreateField( 'CheckFmt' ) as TBlobField;
end; { TInfoCKACCTTable.CreateFields }
procedure TInfoCKACCTTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoCKACCTTable.SetActive }
procedure TInfoCKACCTTable.SetPAcctID(const Value: String);
begin
DFAcctID.Value := Value;
end;
function TInfoCKACCTTable.GetPAcctID:String;
begin
result := DFAcctID.Value;
end;
procedure TInfoCKACCTTable.SetPModCount(const Value: String);
begin
DFModCount.Value := Value;
end;
function TInfoCKACCTTable.GetPModCount:String;
begin
result := DFModCount.Value;
end;
procedure TInfoCKACCTTable.SetPName(const Value: String);
begin
DFName.Value := Value;
end;
function TInfoCKACCTTable.GetPName:String;
begin
result := DFName.Value;
end;
procedure TInfoCKACCTTable.SetPAccountNo(const Value: String);
begin
DFAccountNo.Value := Value;
end;
function TInfoCKACCTTable.GetPAccountNo:String;
begin
result := DFAccountNo.Value;
end;
procedure TInfoCKACCTTable.SetPNextChkNo(const Value: String);
begin
DFNextChkNo.Value := Value;
end;
function TInfoCKACCTTable.GetPNextChkNo:String;
begin
result := DFNextChkNo.Value;
end;
procedure TInfoCKACCTTable.SetPRConDate(const Value: String);
begin
DFRConDate.Value := Value;
end;
function TInfoCKACCTTable.GetPRConDate:String;
begin
result := DFRConDate.Value;
end;
procedure TInfoCKACCTTable.SetPRConBal(const Value: Currency);
begin
DFRConBal.Value := Value;
end;
function TInfoCKACCTTable.GetPRConBal:Currency;
begin
result := DFRConBal.Value;
end;
procedure TInfoCKACCTTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('AcctID, String, 4, N');
Add('ModCount, String, 1, N');
Add('Name, String, 30, N');
Add('AccountNo, String, 20, N');
Add('NextChkNo, String, 6, N');
Add('RConDate, String, 8, N');
Add('RConBal, Currency, 0, N');
Add('CheckFmt, Memo, 0, N');
end;
end;
procedure TInfoCKACCTTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, AcctID, Y, Y, N, N');
end;
end;
procedure TInfoCKACCTTable.SetEnumIndex(Value: TEIInfoCKACCT);
begin
case Value of
InfoCKACCTPrimaryKey : IndexName := '';
end;
end;
function TInfoCKACCTTable.GetDataBuffer:TInfoCKACCTRecord;
var buf: TInfoCKACCTRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PAcctID := DFAcctID.Value;
buf.PModCount := DFModCount.Value;
buf.PName := DFName.Value;
buf.PAccountNo := DFAccountNo.Value;
buf.PNextChkNo := DFNextChkNo.Value;
buf.PRConDate := DFRConDate.Value;
buf.PRConBal := DFRConBal.Value;
result := buf;
end;
procedure TInfoCKACCTTable.StoreDataBuffer(ABuffer:TInfoCKACCTRecord);
begin
DFAcctID.Value := ABuffer.PAcctID;
DFModCount.Value := ABuffer.PModCount;
DFName.Value := ABuffer.PName;
DFAccountNo.Value := ABuffer.PAccountNo;
DFNextChkNo.Value := ABuffer.PNextChkNo;
DFRConDate.Value := ABuffer.PRConDate;
DFRConBal.Value := ABuffer.PRConBal;
end;
function TInfoCKACCTTable.GetEnumIndex: TEIInfoCKACCT;
var iname : string;
begin
result := InfoCKACCTPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := InfoCKACCTPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoCKACCTTable, TInfoCKACCTBuffer ] );
end; { Register }
function TInfoCKACCTBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..7] of string = ('ACCTID','MODCOUNT','NAME','ACCOUNTNO','NEXTCHKNO','RCONDATE'
,'RCONBAL' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 7) and (flist[x] <> s) do inc(x);
if x <= 7 then result := x else result := 0;
end;
function TInfoCKACCTBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftString;
4 : result := ftString;
5 : result := ftString;
6 : result := ftString;
7 : result := ftCurrency;
end;
end;
function TInfoCKACCTBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PAcctID;
2 : result := @Data.PModCount;
3 : result := @Data.PName;
4 : result := @Data.PAccountNo;
5 : result := @Data.PNextChkNo;
6 : result := @Data.PRConDate;
7 : result := @Data.PRConBal;
end;
end;
end.
|
unit GX_SelectComponents;
{$I GX_CondDefine.inc}
// TODO: Prevent selecting a VCL form + components, since it isn't actually possible
interface
uses
Classes, Forms, Controls, ExtCtrls, ToolsAPI, ComCtrls, StdCtrls, Dialogs,
ActnList, ImgList, Graphics, Buttons, DesignWindows, GX_BaseForm;
type
TComponentInfo = record
rName: WideString;
rType: WideString;
end;
TSelectComponentsForm = class(TfmBaseForm)
TreeView: TTreeView;
ActionList: TActionList;
FindPanel: TPanel;
SearchEdit: TEdit;
StayOnTopCheckBox: TCheckBox;
SelectAllButton: TBitBtn;
SelectAllAction: TAction;
BottomPanel: TPanel;
ExactNameCheckBox: TCheckBox;
ExactTypeCheckBox: TCheckBox;
TreePanel: TPanel;
ResizeButton: TBitBtn;
ChangeModeAction: TAction;
FilterLabel: TLabel;
procedure TreeViewClick(aSender: TObject);
procedure TreeViewKeyUp(aSender: TObject; var aKey: Word; aShift: TShiftState);
procedure SearchEditChange(aSender: TObject);
procedure FormActivate(Sender: TObject);
procedure StayOnTopCheckBoxClick(Sender: TObject);
procedure SelectAllActionExecute(Sender: TObject);
procedure SearchEditKeyUp(Sender: TObject; var aKey: Word; Shift: TShiftState);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure SearchEditKeyPress(Sender: TObject; var aKey: Char);
procedure ExactCheckBoxClick(Sender: TObject);
procedure ChangeModeActionExecute(Sender: TObject);
procedure ActionListUpdate(Action: TBasicAction; var Handled: Boolean);
procedure ChangeModeActionHint(var HintStr: String; var CanShow: Boolean);
private
FNodesList: TList;
FCurrentNode: TTreeNode;
FFormEditor: IOTAFormEditor;
FMiniMode: Boolean;
FStayOnTop: Boolean;
FLastHeight: Integer;
procedure Init;
procedure FocusSearchEdit;
procedure ChangeMode(const aMiniMode: Boolean);
procedure ChildComponentCallback(aParam: Pointer; aComponent: IOTAComponent; var aResult: Boolean);
procedure SelectCurrentComponent;
procedure FillTreeView(const aFromComponent: IOTAComponent);
procedure SelectComponentOnForm(const aName: WideString; const aAddToSelection: Boolean = False);
procedure SetCurrentNode(const aNode: TTreeNode);
procedure FindNextNode;
procedure FindPrevNode;
procedure FilterNodes(const aFilter: TComponentInfo);
procedure SetStayOnTop(const aStayOnTop: Boolean);
protected
property CurrentNode: TTreeNode read FCurrentNode write SetCurrentNode;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
property MiniMode: Boolean read FMiniMode write ChangeMode;
property StayOnTop: Boolean read FStayOnTop write SetStayOnTop;
property LastHeight: Integer read FLastHeight;
end;
implementation
{$R *.dfm}
uses
SysUtils, Windows, Messages, TypInfo,
GX_Experts, GX_GxUtils, GX_GenericUtils, GX_OtaUtils, GX_SharedImages,
GX_ConfigurationInfo;
type
TComponentSelectExpert = class(TGX_Expert)
protected
procedure UpdateAction(aAction: TCustomAction); override;
public
class function GetName: string; override;
function GetActionCaption: string; override;
procedure Click(aSender: TObject); override;
function HasConfigOptions: Boolean; override;
end;
var
TheForm: TSelectComponentsForm;
Filter: TComponentInfo;
LastComponentName: WideString;
procedure GetInfo(const aTreeNode: TTreeNode; const aGetType: Boolean; var aInfo: TComponentInfo); overload;
var
aPos: Integer;
begin
with aInfo do
begin
rName := UpperCase(aTreeNode.Text);
aPos := Pos(' : ', rName);
if aPos > 0 then
begin
if aGetType then
rType := Copy(rName, aPos + 3, Length(rName));
rName := Copy(rName, 1, aPos - 1);
end;
end;
end;
function GetInfo(const aText: WideString): TComponentInfo; overload;
var
aPos: Integer;
begin
with Result do
begin
rName := UpperCase(aText);
aPos := Pos(':', rName);
if aPos > 0 then
begin
rType := Trim(Copy(rName, aPos + 1, Length(rName)));
rName := Trim(Copy(rName, 1, aPos - 1));
end;
end;
end;
function FilterToText(const aFilter: TComponentInfo) : WideString;
begin
with aFilter do
begin
Result := rName;
if rType <> '' then
Result := Result + ':' + rType;
end;
end;
procedure TSelectComponentsForm.SelectComponentOnForm(const aName: WideString;
const aAddToSelection: Boolean);
var
aComponent: IOTAComponent;
begin
aComponent := FFormEditor.FindComponent(aName);
TreeView.MultiSelect := aAddToSelection;
if Assigned(aComponent) then
begin
LastComponentName := aName;
aComponent.Select(aAddToSelection);
end;
end;
procedure TSelectComponentsForm.SelectCurrentComponent;
var
aInfo: TComponentInfo;
begin
if Assigned(FFormEditor) and Assigned(TreeView.Selected) then
begin
GetInfo(TreeView.Selected, False, aInfo);
SelectComponentOnForm(aInfo.rName);
end;
end;
procedure TSelectComponentsForm.SelectAllActionExecute(Sender: TObject);
var
aIndex: Integer;
aNode: TTreeNode;
aInfo: TComponentInfo;
begin
for aIndex := 0 to Pred(FNodesList.Count) do
begin
aNode := FNodesList [aIndex];
GetInfo(aNode, False, aInfo);
SelectComponentOnForm(aInfo.rName, aIndex > 0);
end;
TreeView.Select(FNodesList);
end;
procedure TSelectComponentsForm.SetCurrentNode(const aNode: TTreeNode);
begin
if FNodesList.Count > 0 then
begin
FCurrentNode := aNode;
if not Assigned(FCurrentNode) or (FNodesList.IndexOf(FCurrentNode) < 0) then
FCurrentNode := FNodesList.First;
TreeView.Select(FCurrentNode);
SelectCurrentComponent;
end
else FCurrentNode := nil;
if Assigned(FCurrentNode) then
SearchEdit.Font.Color := clBlack
else
SearchEdit.Font.Color := clRed;
end;
procedure TSelectComponentsForm.AfterConstruction;
begin
inherited;
FNodesList := TList.Create;
end;
procedure TSelectComponentsForm.BeforeDestruction;
begin
FreeAndNil(FNodesList);
inherited;
end;
procedure TSelectComponentsForm.ChangeMode(const aMiniMode: Boolean);
var
BestFitHeight: Integer;
begin
if aMiniMode = FMiniMode then
Exit;
FMiniMode := aMiniMode;
if FMiniMode then
FLastHeight := Height;
TreePanel.Visible := not FMiniMode;
if FMiniMode then begin
ChangeModeAction.ImageIndex := ImageIndexExpand;
// The above fails to change the image in D6 at least
ResizeButton.Glyph.Assign(nil);
GetSharedImageList.GetBitmap(ImageIndexExpand, ResizeButton.Glyph);
BestFitHeight := Height - ClientHeight + FindPanel.Height;
Constraints.MinHeight := BestFitHeight;
Constraints.MaxHeight := BestFitHeight;
ClientHeight := FindPanel.Height;
end
else
begin
Constraints.MinHeight := 175;
Constraints.MaxHeight := 0;
Height := FLastHeight;
ChangeModeAction.ImageIndex := ImageIndexContract;
ResizeButton.Glyph.Assign(nil);
GetSharedImageList.GetBitmap(ImageIndexContract, ResizeButton.Glyph);
end;
FocusSearchEdit;
end;
procedure TSelectComponentsForm.ChangeModeActionExecute(Sender: TObject);
begin
MiniMode := not MiniMode;
end;
procedure TSelectComponentsForm.ChildComponentCallback(aParam: Pointer;
aComponent: IOTAComponent; var aResult: Boolean);
var
aTreeNode: TTreeNode;
aName: WideString;
begin
aName := GxOtaGetComponentName(aComponent);
aTreeNode := TreeView.Items.AddChildObject(TTreeNode(aParam), aName + ' : ' + aComponent.GetComponentType, nil);
aComponent.GetChildren(aTreeNode, ChildComponentCallback);
aResult := True;
end;
procedure TSelectComponentsForm.ExactCheckBoxClick(Sender: TObject);
begin
FocusSearchEdit;
FilterNodes(Filter);
end;
procedure TSelectComponentsForm.FillTreeView(const aFromComponent: IOTAComponent);
begin
if TreeView.Items.GetFirstNode <> nil then
aFromComponent.GetChildren(TreeView.Items.GetFirstNode, ChildComponentCallback);
end;
procedure TSelectComponentsForm.FilterNodes(const aFilter: TComponentInfo);
var
aByName: Boolean;
aByType: Boolean;
aExactName: Boolean;
aExactType: Boolean;
aNameMatch: Boolean;
aTypeMatch: Boolean;
aNodeIndex: Integer;
aTreeNode: TTreeNode;
aInfo: TComponentInfo;
aFound: Boolean;
begin
FNodesList.Clear;
TreeView.Items.BeginUpdate;
try
aByName := aFilter.rName <> '';
aByType := aFilter.rType <> '';
aExactName := ExactNameCheckBox.Checked;
aExactType := ExactTypeCheckBox.Checked;
for aNodeIndex := 0 to Pred(TreeView.Items.Count) do
begin
aTreeNode := TreeView.Items [aNodeIndex];
GetInfo(aTreeNode, aByType, aInfo);
aNameMatch := aByName and
(not aExactName and (Pos(aFilter.rName, aInfo.rName) > 0) or
(aExactName and SameText(aFilter.rName, aInfo.rName)));
aTypeMatch := aByType and
(not aExactType and (Pos(aFilter.rType, aInfo.rType) > 0) or
(aExactType and SameText(aFilter.rType, aInfo.rType)));
aFound := (aByName and not aByType and aNameMatch) or
(not aByName and aByType and aTypeMatch) or
(aByName and aByType and aNameMatch and aTypeMatch);
if aFound then
FNodesList.Add(aTreeNode);
if aFound then // Images disabled for now since D6 fails to show the right images, set StateIndex as well
aTreeNode.ImageIndex := ImageIndexArrow
else
aTreeNode.ImageIndex := -1;
end;
finally
TreeView.Items.EndUpdate;
end;
CurrentNode := CurrentNode;
end;
procedure TSelectComponentsForm.SearchEditChange(aSender: TObject);
begin
Filter := GetInfo(SearchEdit.Text);
FilterNodes(Filter);
end;
procedure TSelectComponentsForm.SearchEditKeyPress(Sender: TObject; var aKey: Char);
var
aReset : Boolean;
begin
aReset := True;
case Ord(aKey) of
VK_RETURN: SelectAllAction.Execute;
VK_ESCAPE: ;
VK_SPACE: SearchEdit.Clear;
else
aReset := False;
end;
if aReset then
aKey := Chr(0);
end;
procedure TSelectComponentsForm.SearchEditKeyUp(Sender: TObject; var aKey: Word; Shift: TShiftState);
var
aReset: Boolean;
begin
aReset := True;
case aKey of
VK_UP:
FindPrevNode;
VK_DOWN:
FindNextNode;
else
aReset := False;
end;
if aReset then
aKey := 0;
end;
procedure TSelectComponentsForm.FindNextNode;
var
aNodeIndex : Integer;
begin
if FNodesList.Count <= 0 then
begin
CurrentNode := nil;
Exit;
end;
aNodeIndex := FNodesList.IndexOf(CurrentNode);
if (aNodeIndex > -1) and (aNodeIndex < Pred(FNodesList.Count)) then
begin
Inc(aNodeIndex);
CurrentNode := FNodesList[aNodeIndex];
end
else
CurrentNode := FNodesList.First;
end;
procedure TSelectComponentsForm.FindPrevNode;
var
aNodeIndex: Integer;
begin
if FNodesList.Count <= 0 then
begin
CurrentNode := nil;
Exit;
end;
aNodeIndex := FNodesList.IndexOf(CurrentNode);
if (aNodeIndex > 0) and (aNodeIndex < FNodesList.Count) then
begin
Dec(aNodeIndex);
CurrentNode := FNodesList[aNodeIndex];
end
else
CurrentNode := FNodesList.Last;
end;
procedure TSelectComponentsForm.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Key = Chr(VK_ESCAPE) then
begin
Key := #0;
Close;
end;
end;
procedure TSelectComponentsForm.FocusSearchEdit;
begin
TryFocusControl(SearchEdit);
end;
procedure TSelectComponentsForm.FormActivate(Sender: TObject);
var
aName: WideString;
aInfo: TComponentInfo;
aNodeIndex: Integer;
aTreeNode: TTreeNode;
begin
with Filter do
try
Init;
aName := LastComponentName;
FocusSearchEdit;
SearchEdit.Text := FilterToText(Filter);
SearchEdit.SelectAll;
SearchEditChange(SearchEdit);
for aNodeIndex := 0 to Pred(TreeView.Items.Count) do
begin
aTreeNode := TreeView.Items[aNodeIndex];
GetInfo(aTreeNode, False, aInfo);
if aName = aInfo.rName then
begin
CurrentNode := aTreeNode;
Exit;
end;
end;
except
end;
end;
procedure TComponentSelectExpert.UpdateAction(aAction: TCustomAction);
begin
aAction.Enabled := GxOtaCurrentlyEditingForm;
end;
procedure TComponentSelectExpert.Click(aSender: TObject);
begin
if not Assigned(TheForm) then
TheForm := TSelectComponentsForm.Create(nil);
TheForm.Show;
end;
function TComponentSelectExpert.GetActionCaption: string;
resourcestring
SMenuCaption = 'Select Components...';
begin
Result := SMenuCaption;
end;
class function TComponentSelectExpert.GetName: string;
begin
Result := 'SelectComponents';
end;
function TComponentSelectExpert.HasConfigOptions: Boolean;
begin
Result := False;
end;
function GxOtaGetCurrentModule: IOTAModule;
var
ModuleServices: IOTAModuleServices;
begin
ModuleServices := BorlandIDEServices as IOTAModuleServices;
Assert(Assigned(ModuleServices));
Result := ModuleServices.CurrentModule;
end;
procedure TSelectComponentsForm.Init;
var
aParentName: WideString;
aParentType: WideString;
aComponent: IOTAComponent;
begin
TreeView.Items.BeginUpdate;
try
FNodesList.Clear;
SearchEdit.Enabled := False;
TreeView.Items.Clear;
if not GxOtaCurrentlyEditingForm then
Abort;
FFormEditor := GxOtaGetFormEditorFromModule(GxOtaGetCurrentModule);
if not Assigned(FFormEditor) then
Abort;
aComponent := FFormEditor.GetRootComponent;
if not Assigned(aComponent) then
Abort;
aParentType := aComponent.GetComponentType;
aParentName := GxOtaGetComponentName(aComponent);
TreeView.Items.Add(nil, aParentName + ' : ' + aParentType);
FillTreeView(aComponent);
TreeView.FullExpand;
TreeView.Selected := TreeView.Items.GetFirstNode;
TreeView.Selected.MakeVisible;
SearchEdit.Enabled := True;
finally
TreeView.Items.EndUpdate;
end;
end;
procedure TSelectComponentsForm.SetStayOnTop(const aStayOnTop : Boolean);
begin
if aStayOnTop = FStayOnTop then
Exit;
FStayOnTop := aStayOnTop;
if FStayOnTop then
FormStyle := fsStayOnTop
else
FormStyle := fsNormal;
StayOnTopCheckBox.Checked := FStayOnTop;
FocusSearchEdit;
end;
procedure TSelectComponentsForm.StayOnTopCheckBoxClick(Sender: TObject);
begin
StayOnTop := StayOnTopCheckBox.Checked;
end;
procedure TSelectComponentsForm.TreeViewClick(aSender: TObject);
begin
SelectCurrentComponent;
end;
procedure TSelectComponentsForm.TreeViewKeyUp(aSender: TObject; var aKey: Word; aShift: TShiftState);
begin
SelectCurrentComponent;
end;
procedure TSelectComponentsForm.ActionListUpdate(Action: TBasicAction; var Handled: Boolean);
begin
SelectAllAction.Enabled := FNodesList.Count > 0;
if SelectAllAction.Enabled then
SelectAllAction.Caption := '&Select ' + IntToStr(FNodesList.Count)
else
SelectAllAction.Caption := 'Select';
end;
procedure TSelectComponentsForm.ChangeModeActionHint(var HintStr: String; var CanShow: Boolean);
begin
if FMiniMode then
HintStr := 'Expand'
else
HintStr := 'Contract';
end;
initialization
RegisterGX_Expert(TComponentSelectExpert);
finalization
FreeAndNil(TheForm);
end.
|
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: Arno Garrels <arno.garrels@gmx.de>
Creation: Nov 01, 2005
Description: Implementation of OpenSsl thread locking (Windows);
Version: 1.03
EMail: francois.piette@overbyte.be http://www.overbyte.be
Support: Use the mailing list ics-ssl@elists.org
Follow "SSL" link at http://www.overbyte.be for subscription.
Legal issues: Copyright (C) 2005-2011 by François PIETTE
Rue de Grady 24, 4053 Embourg, Belgium.
<francois.piette@overbyte.be>
This software is provided 'as-is', without any express or
implied warranty. In no event will the author be held liable
for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it
and redistribute it freely, subject to the following
restrictions:
1. The origin of this software must not be misrepresented,
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
4. You must register this software by sending a picture postcard
to the author. Use a nice stamp and mention your name, street
address, EMail address and any comment you like to say.
How to use: TSslStaticLock and TSslDynamicLock implement the locking callbacks
required for OpenSSL to be thread-safe. Currently (v0.98a)
only static locking is used by OpenSSL, dynamic locking is
for future OSSL versions, thus TSslDynamicLock is untested so far.
Simply drop one of the components per application on the form or
create it from within your foreground thread at runtime. Set
property Enabled to TRUE before any of the OpenSSL functions are
called, that's it. Note that setting Enabled to TRUE also loads
and initializes the OpenSSL libraries. Any multi-threaded OpenSSL
application MUST provide a single, enabled locking component,
otherwise random errors in OpenSSL will crash the application.
History:
March 03, 2006 Version 1.01, new property Enabled, OpenSSL is now loaded
when Enabled is set to TRUE.
Jun 30, 2008 A.Garrels made some changes to prepare SSL code for Unicode.
May 05, 2010 V1.02 A.Garrels changed synchronisation to use TRTLCriticalSection
instead of Mutex, removed useless contructor, should be POSIX-ready.
May 06, 2011 V1.03 Arno - Make use of new CRYPTO_THREADID_set_callback.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
unit OverbyteIcsSslThrdLock;
{$IFDEF VER80}
Bomb('This unit requires a 32 bit compiler !');
{$ENDIF}
{$B-} { Enable partial boolean evaluation }
{$T-} { Untyped pointers }
{$X+} { Enable extended syntax }
{$I OverbyteIcsDefs.inc}
{$IFDEF COMPILER14_UP}
{$IFDEF NO_EXTENDED_RTTI}
{$RTTI EXPLICIT METHODS([]) FIELDS([]) PROPERTIES([])}
{$ENDIF}
{$ENDIF}
{$IFDEF DELPHI6_UP}
{$WARN SYMBOL_PLATFORM OFF}
{$WARN SYMBOL_LIBRARY OFF}
{$WARN SYMBOL_DEPRECATED OFF}
{$ENDIF}
{#$DEFINE NO_DYNLOCK}
interface
{$IFDEF USE_SSL}
uses
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF}
{$IFDEF POSIX}
PosixGlue, PosixSysTypes,
{$ENDIF}
Classes,
SysUtils,
OverbyteIcsLIBEAY,
OverbyteIcsSSLEAY,
OverbyteIcsWSocket;
type
ESslLockException = class(Exception);
TMutexBuf = array of TRTLCriticalSection;
TSslStaticLock = class(TComponent)
protected
FSslInitialized : Boolean;
FEnabled : Boolean;
procedure InitializeSsl; virtual;
procedure FinalizeSsl; virtual;
procedure SetEnabled(const Value: Boolean); virtual;
public
destructor Destroy; override;
published
property Enabled : Boolean read FEnabled write SetEnabled;
end;
{$IFNDEF NO_DYNLOCK}
{ Suggested for use with future openssl versions, not yet tested }
TSslDynamicLock = class(TSslStaticLock)
protected
procedure SetEnabled(const Value: Boolean); override;
end;
{$ENDIF}
{$ENDIF} // USE_SSL
implementation
{$IFDEF USE_SSL}
var
MutexBuf : TMutexBuf;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TSslStaticLock.Destroy;
begin
if Enabled then
SetEnabled(FALSE);
FinalizeSsl;
inherited Destroy;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TSslStaticLock.FinalizeSsl;
begin
if not FSslInitialized then
Exit;
UnloadSsl;
FSslInitialized := False;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TSslStaticLock.InitializeSsl;
begin
if FSslInitialized then
Exit;
LoadSsl;
FSslInitialized := True;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure MutexSetup(var Mutex : TRTLCriticalSection); {$IFDEF USE_INLINE} inline; {$ENDIF}
begin
InitializeCriticalSection(Mutex);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure MutexCleanup(var Mutex : TRTLCriticalSection); {$IFDEF USE_INLINE} inline; {$ENDIF}
begin
DeleteCriticalSection(Mutex);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure MutexLock(Mutex: TRTLCriticalSection); {$IFDEF USE_INLINE} inline; {$ENDIF}
begin
EnterCriticalSection(Mutex);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure MutexUnlock(Mutex : TRTLCriticalSection); {$IFDEF USE_INLINE} inline; {$ENDIF}
begin
LeaveCriticalSection(Mutex);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure StatLockCallback(Mode : Integer; N : Integer;
const _File : PAnsiChar; Line : Integer); cdecl;
begin
if Mode and Crypto_Lock <> 0 then
MutexLock(MutexBuf[n])
else
MutexUnLock(MutexBuf[n])
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFDEF MSWINDOWS}
function IDCallback : Longword; cdecl;
begin
Result := GetCurrentThreadID;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$ELSE}
procedure ThreadIdCallback(ID : PCRYPTO_THREADID); cdecl;
begin
f_CRYPTO_THREADID_set_pointer(ID, Pointer(GetCurrentThreadID)); //? To check
end;
{$ENDIF}
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TSslStaticLock.SetEnabled(const Value: Boolean);
var
I : Integer;
begin
if Value = FEnabled then
Exit;
if not (csDesigning in ComponentState) then
begin
InitializeSsl;
if Value then
begin
SetLength(MutexBuf, f_CRYPTO_num_locks);
try
for I := Low(MutexBuf) to High(MutexBuf) do
MutexSetup(MutexBuf[I]);
except
on E : Exception do begin
for I := Low(MutexBuf) to High(MutexBuf) do
MutexCleanup(MutexBuf[I]);
SetLength(MutexBuf, 0);
raise;
end;
end;
{$IFDEF MSWINDOWS}
f_CRYPTO_set_id_callback(IDCallback);
{$ELSE}
if Assigned(f_CRYPTO_THREADID_set_callback) then // v1.0.0+
begin
Assert(Assigned(f_CRYPTO_THREADID_set_pointer));
f_CRYPTO_THREADID_set_callback(ThreadIdCallback);
end
else
{$ENDIF}
f_CRYPTO_set_locking_callback(StatLockCallback);
end
else begin
if FSslInitialized then begin
f_CRYPTO_set_locking_callback(nil);
f_CRYPTO_set_id_callback(nil);
end;
for I := Low(MutexBuf) to High(MutexBuf) do
MutexCleanup(MutexBuf[I]);
SetLength(MutexBuf, 0);
end;
end;
FEnabled := Value;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFNDEF NO_DYNLOCK}
function DynCreateCallBack(const _file : PAnsiChar;
Line: Integer): PCRYPTO_dynlock_value; cdecl;
begin
New(Result);
MutexSetup(Result^.Mutex);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure DynDestroyCallBack(L : PCRYPTO_dynlock_value; _File : PAnsiChar;
Line: Integer); cdecl;
begin
if Assigned(L) then
begin
MutexCleanUp(L^.Mutex);
Dispose(L);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure DynLockCallback(Mode : Integer; L : PCRYPTO_dynlock_value;
_File : PAnsiChar; Line: Integer); cdecl;
begin
if Assigned(L) then
begin
if Mode and CRYPTO_LOCK <> 0 then
MutexLock(L^.Mutex)
else
MutexUnlock(L^.Mutex);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TSslDynamicLock.SetEnabled(const Value: Boolean);
var
OldValue : Boolean;
begin
OldValue := FEnabled;
inherited SetEnabled(Value);
if OldValue = FEnabled then
Exit;
if not (csDesigning in ComponentState) then begin
if Value then begin
InitializeSsl;
f_CRYPTO_set_dynlock_create_callback(DynCreateCallBack);
f_CRYPTO_set_dynlock_lock_callback(DynLockCallback);
f_CRYPTO_set_dynlock_destroy_callback(DynDestroyCallBack);
end
else begin
if FSslInitialized then begin
f_CRYPTO_set_dynlock_create_callback(nil);
f_CRYPTO_set_dynlock_lock_callback(nil);
f_CRYPTO_set_dynlock_destroy_callback(nil);
end;
end;
end;
FEnabled := Value;
end;
{$ENDIF}
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$ENDIF} // USE_SSL
end.
|
unit ExtAIMsgEvents;
interface
uses
Classes, SysUtils,
ExtAICommonClasses, ExtAISharedNetworkTypes, ExtAISharedInterface;
// Packing and unpacking of Events in the message
type
TExtAIMsgEvents = class
private
// Main variables
fStream: TKExtAIMsgStream;
// Triggers
fOnSendEvent : TExtAIEventNewMsg;
fOnMissionStart : TMissionStartEvent;
fOnMissionEnd : TMissionEndEvent;
fOnTick : TTickEvent;
fOnPlayerDefeated : TPlayerDefeatedEvent;
fOnPlayerVictory : TPlayerVictoryEvent;
// Send Events
procedure InitMsg(aTypeEvent: TExtAIMsgTypeEvent);
procedure FinishMsg();
procedure SendEvent();
// Unpack Events
procedure MissionStartR();
procedure MissionEndR();
procedure TickR();
procedure PlayerDefeatedR();
procedure PlayerVictoryR();
// Others
procedure NillEvents();
public
constructor Create();
destructor Destroy(); override;
// Connection to callbacks
property OnSendEvent : TExtAIEventNewMsg write fOnSendEvent;
property OnMissionStart : TMissionStartEvent write fOnMissionStart;
property OnMissionEnd : TMissionEndEvent write fOnMissionEnd;
property OnTick : TTickEvent write fOnTick;
property OnPlayerDefeated : TPlayerDefeatedEvent write fOnPlayerDefeated;
property OnPlayerVictory : TPlayerVictoryEvent write fOnPlayerVictory;
// Pack events
procedure MissionStartW();
procedure MissionEndW();
procedure TickW(aTick: Cardinal);
procedure PlayerDefeatedW(aHandIndex: SmallInt);
procedure PlayerVictoryW(aHandIndex: SmallInt);
procedure ReceiveEvent(aData: Pointer; aEventType, aLength: Cardinal);
end;
implementation
{ TExtAIMsgEvents }
constructor TExtAIMsgEvents.Create();
begin
Inherited Create;
fStream := TKExtAIMsgStream.Create();
NillEvents();
end;
destructor TExtAIMsgEvents.Destroy();
begin
fStream.Free;
NillEvents();
Inherited;
end;
procedure TExtAIMsgEvents.NillEvents();
begin
fOnMissionStart := nil;
fOnTick := nil;
fOnPlayerDefeated := nil;
fOnPlayerVictory := nil;
end;
procedure TExtAIMsgEvents.InitMsg(aTypeEvent: TExtAIMsgTypeEvent);
begin
// Clear stream and create head with predefined 0 length
fStream.Clear;
fStream.WriteMsgType(mkEvent, Cardinal(aTypeEvent), TExtAIMsgLengthData(0));
end;
procedure TExtAIMsgEvents.FinishMsg();
var
MsgLenght: TExtAIMsgLengthData;
begin
// Replace 0 length with correct number
MsgLenght := fStream.Size - SizeOf(TExtAIMsgKind) - SizeOf(TExtAIMsgTypeEvent) - SizeOf(TExtAIMsgLengthData);
fStream.Position := SizeOf(TExtAIMsgKind) + SizeOf(TExtAIMsgTypeEvent);
fStream.Write(MsgLenght, SizeOf(MsgLenght));
// Send Event
SendEvent();
end;
procedure TExtAIMsgEvents.SendEvent();
begin
// Send message
if Assigned(fOnSendEvent) then
fOnSendEvent(fStream.Memory, fStream.Size);
end;
procedure TExtAIMsgEvents.ReceiveEvent(aData: Pointer; aEventType, aLength: Cardinal);
begin
fStream.Clear();
fStream.Write(aData^,aLength);
fStream.Position := 0;
case TExtAIMsgTypeEvent(aEventType) of
teOnMissionStart : MissionStartR();
teOnMissionEnd : MissionEndR();
teOnTick : TickR();
teOnPlayerDefeated : PlayerDefeatedR();
teOnPlayerVictory : PlayerVictoryR();
else begin end;
end;
end;
// Events
procedure TExtAIMsgEvents.MissionStartW();
begin
InitMsg(teOnMissionStart);
FinishMsg();
end;
procedure TExtAIMsgEvents.MissionStartR();
begin
if Assigned(fOnMissionStart) then
fOnMissionStart();
end;
procedure TExtAIMsgEvents.MissionEndW();
begin
InitMsg(teOnMissionEnd);
FinishMsg();
end;
procedure TExtAIMsgEvents.MissionEndR();
begin
if Assigned(fOnMissionEnd) then
fOnMissionEnd();
end;
procedure TExtAIMsgEvents.TickW(aTick: Cardinal);
begin
InitMsg(teOnTick);
fStream.Write(aTick);
FinishMsg();
end;
procedure TExtAIMsgEvents.TickR();
var
Tick: Cardinal;
begin
fStream.Read( Tick, SizeOf(Tick) );
if Assigned(fOnTick) then
fOnTick(Tick);
end;
procedure TExtAIMsgEvents.PlayerDefeatedW(aHandIndex: SmallInt);
begin
InitMsg(teOnPlayerDefeated);
fStream.Write(aHandIndex);
FinishMsg();
end;
procedure TExtAIMsgEvents.PlayerDefeatedR();
var
HandIndex: SmallInt;
begin
fStream.Read( HandIndex, SizeOf(HandIndex) );
if Assigned(fOnPlayerDefeated) then
fOnPlayerDefeated(HandIndex);
end;
procedure TExtAIMsgEvents.PlayerVictoryW(aHandIndex: SmallInt);
begin
InitMsg(teOnPlayerVictory);
fStream.Write(aHandIndex);
FinishMsg();
end;
procedure TExtAIMsgEvents.PlayerVictoryR();
var
HandIndex: SmallInt;
begin
fStream.Read( HandIndex, SizeOf(HandIndex) );
if Assigned(fOnPlayerVictory) then
fOnPlayerVictory(HandIndex);
end;
end.
|
unit UListHandlerNodes; // Fully annotated
interface
uses
Classes, UMazeHandler, UInterface, SysUtils, Dialogs;
type
TCoord = record
x: integer;
y: integer;
end;
TNode = record
HValue, FValue, GValue: integer;
Parent: TCoord;
Position: TCoord;
end;
TListHandlerNodes = class
private
List: Array of TNode;
LastIndex, ListLength, endX, endY, startX, startY: integer;
blankNode: TNode;
public
constructor Create(Maze: TMazeHandler; openList: boolean);
function RemoveNode(x, y: integer): TNode;
procedure AddNode(Node: TNode);
function GetLastIndex: integer;
function GetPositionX(index: integer): integer;
function GetPositionY(index: integer): integer;
function GetIndex(x, y: integer): integer;
function GetNode(index: integer): TNode;
procedure SetParent(posX, posY, parX, parY, GValue: integer);
function GetGValue(x, y: integer): integer;
procedure GetPositionOfLowestFValue(var posX, posY: integer);
procedure GetRoute(var Route: TRoute; endX, endY: integer);
function GetRouteLength(endX, endY: integer): integer;
end;
implementation
// Initialises the list
constructor TListHandlerNodes.Create(Maze: TMazeHandler; openList: boolean);
var
x, y, index: integer;
begin
// Records the start and end cooridnates of the maze for internal reference
startX := Maze.GetStartX;
startY := Maze.GetStartY;
endX := Maze.GetEndX;
endY := Maze.GetEndY;
// Determines the length of the list needed by determining the number of nodes
// which may need to be recorded
ListLength := Maze.GetNumberOfAir;
setLength(List, ListLength);
// Initialises the values of a blank node to be used to make the value of a
// node null
blankNode.HValue := 0;
blankNode.FValue := 0;
blankNode.GValue := 0;
blankNode.Parent.x := 0;
blankNode.Parent.y := 0;
blankNode.Position.x := 0;
blankNode.Position.y := 0;
// If the object is to manage the open list
if openList then
begin
LastIndex := ListLength - 1;
index := 0;
// Checks every cell in the maze
for x := 0 to Maze.GetLastIndex do
begin
for y := 0 to Maze.GetLastIndex do
begin
// If it is a space, record it as a node in the list
if not(Maze.GetWall(x, y)) then
begin
// Initialises the node to reflect the cell it will represent
List[index] := blankNode;
List[index].Position.x := x;
List[index].Position.y := y;
// Finds its horizontle and vertical distance from the finish
List[index].HValue := abs(endX - x) + abs(endY - y);
inc(index);
end;
end;
end;
end
// If the object is to manage another list
else
begin
// Initialise the list as empty, but with enough room for every node in the
// maze
for index := 0 to ListLength do
List[index] := blankNode;
ListLength := 0;
LastIndex := -1;
end;
end;
// Returns the value of a node and then removes it from the list
function TListHandlerNodes.RemoveNode(x, y: integer): TNode;
var
index, postIndex: integer;
begin
result.Position.x := -1;
// If it is not the last node in the list
if LastIndex > 0 then
begin
// For every index in the list
for index := 0 to LastIndex do
begin
// If the current index is the index to be removed
if (List[index].Position.x = x) and (List[index].Position.y = y) then
begin
// Return the value of the node
result := List[index];
// Moves all nodes after the node being removed to the position of the
// node
// before them
for postIndex := index to (LastIndex - 1) do
begin
List[postIndex] := List[postIndex + 1];
end;
// Nullifies the last node in the list as it is now recorded in the
// position before it
List[LastIndex] := blankNode;
// Adjusts the LastIndex and ListLength considering a node has been
// removed
dec(LastIndex);
dec(ListLength);
break;
end;
end;
end
// If there is only one node in the list
else if LastIndex = 0 then
begin
// Nullify its value
result := List[LastIndex];
List[LastIndex] := blankNode;
// Adjusts the LastIndex and ListLength considering a node has been removed
dec(ListLength);
dec(LastIndex);
end;
end;
// Adds a node to the list
procedure TListHandlerNodes.AddNode(Node: TNode);
var
index, postIndex: integer;
tempNode: TNode;
notFound: boolean;
begin
// If the list has two or more nodes in it, and is not full
if (LastIndex >= 1) and (LastIndex < length(List)) then
begin
index := 0;
notFound := true;
// While the position to be inserted is not found, and the index being
// checked does not exceed the indexes occupied
while (notFound) and (index < ListLength) do
begin
// If the current index is the position for the node to be inserted into
if ((List[index].Position.x > Node.Position.x) and
(List[index].Position.y = Node.Position.y)) or
(List[index].Position.y > Node.Position.y) then
begin
// Create space in the position to be inserted by moving the node
// currently occupying it and all those after in the list into the
// next index along from them
for postIndex := (LastIndex + 1) downto (index + 1) do
begin
List[postIndex] := List[postIndex - 1];
end;
// Inserts the node being added into the list
List[index] := Node;
// Adjusts LastIndex and ListLength considering an item has been added
inc(LastIndex);
inc(ListLength);
// Terminates the loop
notFound := false;
end;
inc(index);
end;
// If the position was not found, its position to be inserted must be on
// the end of the list, so it is inserted there
if notFound then
begin
List[ListLength] := Node;
inc(LastIndex);
inc(ListLength);
end;
end
// Else if the list only contains one node
else if LastIndex = 0 then
begin
// If it should be inserted before the node already in the list
if ((List[0].Position.x > Node.Position.x) and
(List[0].Position.y = Node.Position.y)) or
(List[0].Position.y > Node.Position.y) then
begin
// Move the node already occupying the list into the index one along from
// it
List[LastIndex + 1] := List[LastIndex];
// Insert the node being added into the list
List[LastIndex] := Node;
LastIndex := 1;
ListLength := 2;
end
// Otherwise, it should be inserted after it
else
begin
// Inserts the node on the end of the occupied list
List[LastIndex + 1] := Node;
LastIndex := 1;
ListLength := 2;
end;
end
// Else if the list is empty
else if LastIndex = -1 then
begin
// Adds the node to the 0th index in the list
List[ListLength] := Node;
LastIndex := 0;
ListLength := 1;
end;
end;
// Returns the position of the last index in the list
function TListHandlerNodes.GetLastIndex: integer;
begin
result := LastIndex;
end;
// Returns the x value of a node at a specified position
function TListHandlerNodes.GetPositionX(index: integer): integer;
begin
result := List[index].Position.x;
end;
// Returns the y value of a node at a specified position
function TListHandlerNodes.GetPositionY(index: integer): integer;
begin
result := List[index].Position.y;
end;
// Returns the position of the nodes whose x and y values correspond to the ones
// passed to the function
function TListHandlerNodes.GetIndex(x: integer; y: integer): integer;
var
index: integer;
notFound: boolean;
begin
notFound := true;
index := 0;
while notFound and (index < ListLength) do
begin
// If the nodes x and y values match those passed
if (List[index].Position.x = x) and (List[index].Position.y = y) then
begin
// Return its position and terminate the loop
result := index;
notFound := false;
end;
inc(index);
end;
// If no nodes x and y coordinates match those passed, return a null value for
// its position
if notFound then
result := -1;
end;
// Returns the node at a given position in the list
function TListHandlerNodes.GetNode(index: integer): TNode;
begin
result := List[index];
end;
// Sets the parent of a node, and updates its g and f values
procedure TListHandlerNodes.SetParent(posX, posY, parX, parY, GValue: integer);
var
index: integer;
begin
// Returns the position of the node
index := GetIndex(posX, posY);
// Sets the nodes parent to the coordinates of the one passed
List[index].Parent.x := parX;
List[index].Parent.y := parY;
// Set the nodes g value to the g value passed
List[index].GValue := GValue;
// Recalculate the nodes f value considering the change in g value
List[index].FValue := GValue + List[index].HValue;
end;
// Returns the g value of a node
function TListHandlerNodes.GetGValue(x: integer; y: integer): integer;
begin
result := List[GetIndex(x, y)].GValue;
end;
// Returns the position of the node which has the lowest f value in the list
procedure TListHandlerNodes.GetPositionOfLowestFValue(var posX: integer;
var posY: integer);
var
index, lowestFValue: integer;
begin
// Records the first node in the list as having the lowest f value
posX := List[0].Position.x;
posY := List[0].Position.y;
lowestFValue := List[0].FValue;
// Loops through all nodes after the first
for index := 1 to LastIndex do
begin
// If the node being checked has a lower f value than the current lowest
// found
if (List[index].FValue < lowestFValue) and (List[index].FValue <> 0) then
begin
// Records the node as having the lowest f value
posX := List[index].Position.x;
posY := List[index].Position.y;
lowestFValue := List[index].FValue;
end;
end;
end;
// Returns the length of the final route
function TListHandlerNodes.GetRouteLength(endX, endY: integer): integer;
var
currentX, currentY, index: integer;
begin
// Sets to start tracing at the end of the maze, first considering the end
// cell
currentX := endX;
currentY := endY;
// Sets the length to 1, counting the end square
result := 1;
// Loops until the start has been reached
while not((currentX = startX) and (currentY = startY)) do
begin
// Returns the position of the cell being considered
index := GetIndex(currentX, currentY);
// Returns the parent of the cell being considered
currentX := List[index].Parent.x;
currentY := List[index].Parent.y;
// Add 1 to the length of the route
inc(result);
end;
end;
// Returns the route in order of finish to start
procedure TListHandlerNodes.GetRoute(var Route: TRoute; endX, endY: integer);
var
indexInList, indexInRoute, stepX, stepY, routeLength: integer;
begin
// Finds the length of the route, and sets this to be the length of the array
// where the route will be stored
routeLength := GetRouteLength(endX, endY);
setLength(Route, routeLength);
// Sets to start tracing at the end of the maze, first considering the end
// cell
stepX := endX;
stepY := endY;
// Sets the start cell as being at the end of the array storing the ordered
// route
Route[routeLength - 1].x := startX;
Route[routeLength - 1].y := startY;
// For every index in the list (except the last as it has already been
// declared)
for indexInRoute := 0 to (routeLength - 2) do
begin
// Finds the position of the cell being considered
indexInList := GetIndex(stepX, stepY);
// Marks its parent as the cell to be considered in the next iteration
stepX := List[indexInList].Parent.x;
stepY := List[indexInList].Parent.y;
// Records the position of the cell currently being considered as a cell
// that forms the route from start to finish
Route[indexInRoute].x := List[indexInList].Position.x;
Route[indexInRoute].y := List[indexInList].Position.y;
end;
end;
end.
|
unit osRadioComboPanel;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, ExtCtrls, StdCtrls, graphics;
type
TCheckEvent = procedure(Sender: TObject; Value: Boolean) of Object;
TosRadioComboPanel = class(tpanel)
private
FCaption: TCaption;
procedure SetCaption(const Value: TCaption);
private
radioButton: TRadioButton;
pnlTop: TPanel;
FRadioCaption: TCaption;
FChecked: boolean;
FOpenedHeight: integer;
FClosedHeight: integer;
FonChangeCheck: TCheckEvent;
property Caption: TCaption read FCaption write SetCaption;
procedure SetRadioCaption(const Value: TCaption);
procedure SetChecked(const Value: boolean);
procedure RadioButtonClick(Sender: TObject);
procedure SetClosedHeight(const Value: integer);
procedure SetOpenedHeight(const Value: integer);
procedure PanelTopResize(Sender: TObject);
protected
procedure AdjustClientRect(var Rect: TRect); override;
public
constructor Create (AOwner: TComponent); override;
procedure CreateWnd; override;
procedure Resize; override;
published
property RadioCaption: TCaption read FRadioCaption write SetRadioCaption;
property Checked: boolean read FChecked write SetChecked stored true;
property OpenedHeight: integer read FOpenedHeight write SetOpenedHeight;
property ClosedHeight: integer read FClosedHeight write SetClosedHeight;
property onChangeCheck: TCheckEvent read FonChangeCheck write FonChangeCheck;
end;
procedure Register;
implementation
uses
Dialogs;
procedure Register;
begin
RegisterComponents('OS Controls', [TosRadioComboPanel]);
end;
{ TosRadioComboPanel }
procedure TosRadioComboPanel.AdjustClientRect(var Rect: TRect);
begin
inherited AdjustClientRect(Rect);
if pnlTop <> nil then
pnlTop.Height := ClosedHeight-2;
end;
constructor TosRadioComboPanel.create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
procedure TosRadioComboPanel.CreateWnd;
begin
inherited CreateWnd;
pnlTop := TPanel.Create(self);
pnlTop.Parent := self;
pnlTop.Align := alTop;
pnlTop.BevelInner := bvNone;
pnlTop.BevelOuter := bvNone;
pnlTop.OnResize := PanelTopResize;
radioButton := TRadioButton.Create(self);
radioButton.Parent := pnlTop;
radioButton.OnClick := RadioButtonClick;
if ClosedHeight<1 then ClosedHeight := 17;
if OpenedHeight<1 then OpenedHeight := 41;
Height := ClosedHeight;
pnlTop.Height := ClosedHeight-2;
if Checked then
begin
radioButton.Checked := Checked;
end;
Caption := '';
Align := alTop;
end;
procedure TosRadioComboPanel.SetChecked(const Value: boolean);
var
p: TComponent;
i: integer;
begin
FChecked := Value;
if radioButton=nil then
exit;
//setar o checked dos outros componentes para false
//caso este componente esteja checkado
if Value then
begin
p := Owner;
for i := 0 to p.ComponentCount-1 do
begin
if (p.components[i] is TosRadioComboPanel) then
if p.Components[i] <> self then
(p.components[i] as TosRadioComboPanel).Checked := false;
end;
end;
//setar as propriedades deste componente
if not value then
Height := ClosedHeight
else
height := OpenedHeight;
radioButton.Checked := Value;
if Assigned(FonChangeCheck) then
FonChangeCheck(Self, Value);
end;
procedure TosRadioComboPanel.SetRadioCaption(const Value: TCaption);
begin
FRadioCaption := Value;
radioButton.Caption := Value;
end;
procedure TosRadioComboPanel.RadioButtonClick(Sender: TObject);
begin
(Sender as TRadioButton).Checked := True;
Checked := true;
end;
procedure TosRadioComboPanel.SetClosedHeight(const Value: integer);
begin
FClosedHeight := Value;
end;
procedure TosRadioComboPanel.SetOpenedHeight(const Value: integer);
begin
FOpenedHeight := Value;
end;
procedure TosRadioComboPanel.PanelTopResize(Sender: TObject);
begin
if radioButton=nil then
exit;
radioButton.Top := (pnlTop.height div 2) - (radioButton.Height div 2) + 1;
radioButton.Width := Width - 5;
radioButton.Left := 5;
radioButton.Caption := RadioCaption;
end;
procedure TosRadioComboPanel.SetCaption(const Value: TCaption);
begin
FCaption := Value;
end;
procedure TosRadioComboPanel.Resize;
begin
inherited Resize;
{ if Checked then
begin
if Height=ClosedHeight then
Height := OpenedHeight;
OpenedHeight := Height;
end
else
begin
OpenedHeight := OpenedHeight + Height - ClosedHeight;
ClosedHeight := height;
end; }
end;
end.
|
UNIT ModLCGReal;
INTERFACE
FUNCTION randInt() : integer;
FUNCTION randReal() : real;
PROCEDURE initLCG(randSeed : integer);
IMPLEMENTATION
USES math;
CONST
a = 48721;
c = 1;
m = 32768; (*2 ^ 16*)
VAR
x: integer;
FUNCTION randInt : INTEGER;
BEGIN
x := (a*x+c)MOD m;
RandInt := x;
END;
FUNCTION randReal : real;
BEGIN
randReal := randInt/m;
END;
PROCEDURE initLCG(randSeed : integer);
BEGIN
x:= randSeed;
END;
BEGIN
END.
|
unit uButton;
interface
uses Graphics, uGraph, uResFont, uImage;
type
TButtonState = (bsNone, bsOver, bsDown);
TButtonType = (btShort, btNormal);
TButton = class
private
FLeft: Integer;
FTop: Integer;
FSurface: array [1..4] of TBitmap;
FCanvas: TCanvas;
FGraph: TGraph;
FResFont: TResFont;
FState: TButtonState;
FImage: TImage;
FSellected: Boolean;
procedure SetTop(const Value: Integer);
procedure SetLeft(const Value: Integer);
procedure SetCanvas(const Value: TCanvas);
procedure SetState(const Value: TButtonState);
procedure SetSellected(const Value: Boolean);
procedure Refresh;
public
property Top: Integer read FTop write SetTop;
property Left: Integer read FLeft write SetLeft;
property Sellected: Boolean read FSellected write SetSellected;
property Canvas: TCanvas read FCanvas write SetCanvas;
property State: TButtonState read FState write SetState default bsNone;
function MouseOver(X, Y: Integer): boolean; overload;
function MouseOver: boolean; overload;
procedure MouseDown(X, Y: Integer);
procedure Draw;
//** Конструктор.
constructor Create(ALeft, ATop: Integer; ACanvas: TCanvas;
S: string; T: TButtonType = btNormal);
//** Деструктор.
destructor Destroy; override;
end;
implementation
uses Types, SysUtils, uUtils, uIni, uBox;
{ TButton }
constructor TButton.Create(ALeft, ATop: Integer; ACanvas: TCanvas;
S: string; T: TButtonType = btNormal);
var
I: Byte;
Z: TSize;
R: Real;
A: TBitmap;
begin
R := 0.8;
Top := ATop;
Left := ALeft;
Canvas := ACanvas;
Sellected := False;
FImage := TImage.Create;
FResFont := TResFont.Create;
FResFont.LoadFromFile(Path + 'Data\Fonts\' + Ini.FontName);
FGraph := TGraph.Create(Path + 'Data\Images\GUI\');
for I := 1 to High(FSurface) do
begin
FSurface[I] := TBitmap.Create;
if (T = btNormal) then
begin
FGraph.LoadImage('WideButton.bmp', FSurface[I]);
if (I > 1) then
begin
FImage.Gamma(FSurface[I], R);
R := R - 0.15;
end;
with FSurface[I] do
begin
Canvas.Brush.Style := bsClear;
Canvas.Font.Size := 28;
if (I > 1) then Canvas.Font.Style := [fsBold] else Canvas.Font.Style := [];
if (I > 2) then Canvas.Font.Color := $006CB1C5 else Canvas.Font.Color := $006089A2;
Canvas.Font.Name := FResFont.FontName;
Z := Canvas.TextExtent(S);
Canvas.TextOut((Width div 2) - (Z.CX div 2),
(Height div 2) - (Z.CY div 2), S);
end;
end else begin
FGraph.LoadImage('SmallButton.bmp', FSurface[I]);
if FileExists(Path + 'Data\Images\GUI\' + S) then
begin
A := TBitmap.Create;
try
A.Transparent := True;
A.LoadFromFile(Path + 'Data\Images\GUI\' + S);
FSurface[I].Canvas.Draw(4, 4, A);
finally
A.Free;
end;
end;
if (I > 1) then
begin
FImage.Gamma(FSurface[I], R);
R := R - 0.15;
end;
end;
end;
end;
destructor TButton.Destroy;
var
I: Byte;
begin
for I := 1 to High(FSurface) do FSurface[I].Free;
FResFont.Free;
FImage.Free;
FGraph.Free();
inherited;
end;
function TButton.MouseOver(X, Y: Integer): boolean;
begin
Result := (X > Left) and (X < Left + FSurface[1].Width) and (Y > Top) and (Y < Top + FSurface[1].Height);
end;
function TButton.MouseOver: boolean;
begin
Result := MouseOver(MouseX, MouseY);
end;
procedure TButton.Refresh;
begin
case State of
bsNone: if Sellected
then Canvas.Draw(Left, Top, FSurface[3])
else Canvas.Draw(Left, Top, FSurface[1]);
bsOver: Canvas.Draw(Left, Top, FSurface[2]);
bsDown: Canvas.Draw(Left, Top, FSurface[4]);
end;
end;
procedure TButton.SetCanvas(const Value: TCanvas);
begin
FCanvas := Value;
end;
procedure TButton.SetLeft(const Value: Integer);
begin
FLeft := Value;
end;
procedure TButton.SetTop(const Value: Integer);
begin
FTop := Value;
end;
procedure TButton.SetState(const Value: TButtonState);
begin
FState := Value;
end;
procedure TButton.Draw;
begin
if (State <> bsDown) then
begin
if MouseOver and not Sellected then State := bsOver else State := bsNone;
end;
Refresh;
if (State = bsDown) and not MouseOver then State := bsNone;
end;
procedure TButton.MouseDown(X, Y: Integer);
begin
if MouseOver(X, Y) then State := bsDown else State := bsNone;
Refresh;
end;
procedure TButton.SetSellected(const Value: Boolean);
begin
FSellected := Value;
end;
end.
|
unit joinedcommand;
{$mode objfpc}{$H+}
interface
uses command;
type
{ TJoinedCommand }
TJoinedCommand = class(TCommand)
private
FNickName: string;
FHost: string;
FChannel: string;
procedure Send;
public
procedure Execute(const ANickname, AHost, AChannel: string);
end;
implementation
{ TJoinedCommand }
procedure TJoinedCommand.Send;
begin
Channels.Joined(FNickName, FHost, FChannel);
end;
procedure TJoinedCommand.Execute(const ANickname, AHost, AChannel: string);
begin
FNickName := ANickname;
FHost := AHost;
FChannel := AChannel;
Syncronize(@Send);
end;
end.
|
unit uCmdCompiler;
interface
function CompilePath(path: string): Boolean;
implementation
uses
classes, uSqlProject, uSqlGenerator, uLogger, uTextData, System.SysUtils;
type
TCompiler = class(TComponent,ILogger)
private
FGenerator: TSqlGenerator;
FProject: TSqlProject;
procedure CompileTextData(aTextData: THsTextData);
procedure Log(AValue: string);
function FolderForCompiledSQL : string;
public
constructor Create(path: string);
destructor Destroy; override;
procedure Run;
end;
procedure TCompiler.CompileTextData(aTextData: THsTextData);
var
fileName: String;
linesOfCode: TStrings;
begin
if aTextData.SqlType in [dtMacro, dtInclude] then
exit;
linesOfCode := TStringList.Create;
try
try
linesOfCode.Text := FGenerator.CompileSql(aTextData.SQL);
fileName := FolderForCompiledSQL + PathDelim + Format('%s.sql',[aTextData.SqlName]);
linesOfCode.SaveToFile(fileName);
Log(Format('Saved: %s.sql',[aTextData.SqlName]));
except
on e:exception do
begin
Log(Format('ERROR Processing %s',[aTextData.SQLName]));
Log(e.Message);
Log(StringOfChar('-',40));
Log('');
Halt(1);
end;
end;
finally
linesOfCode.Free;
end;
end;
function CompilePath(path: string): Boolean;
begin
with TCompiler.Create(path) do
try
Run;
finally
Free;
end;
end;
{ TLogger }
procedure TCompiler.Log(AValue: string);
begin
WriteLn(aValue);
end;
constructor TCompiler.Create(path: string);
var
sProjectFolder: string;
begin
sProjectFolder := path;
{$IFDEF FPC}
DoDirSeparators(sProjectFolder);
{$ENDIF}
FProject := TSqlProject.Create;
FProject.ProjectFolder := sProjectFolder;
FGenerator := TSqlGenerator.Create(FProject.Macros, FProject.Includes, self);
end;
destructor TCompiler.Destroy;
begin
FreeAndNil(FGenerator);
FreeAndNil(FProject);
inherited;
end;
function TCompiler.FolderForCompiledSQL: string;
begin
Result := FProject.ProjectFolder + PathDelim + 'Compiled';
end;
procedure TCompiler.Run;
begin
Log('Compiling SQL Routines');
FProject.IterateAll(CompileTextData);
end;
end.
|
unit PasswordEdit;
{
Inno Setup
Copyright (C) 1997-2007 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
This unit provides a true password edit for Delphi 2.
$jrsoftware: issrc/Components/PasswordEdit.pas,v 1.3 2007/12/10 18:28:53 jr Exp $
}
interface
uses
Windows, Classes, Controls, StdCtrls;
type
TPasswordEdit = class(TCustomEdit)
private
FPassword: Boolean;
procedure SetPassword(Value: Boolean);
protected
procedure CreateParams(var Params: TCreateParams); override;
public
constructor Create(AOwner: TComponent); override;
published
property AutoSelect;
property AutoSize;
property BorderStyle;
property CharCase;
property Color;
property Ctl3D;
property DragCursor;
property DragMode;
property Enabled;
property Font;
property HideSelection;
property MaxLength;
property OEMConvert;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property Password: Boolean read FPassword write SetPassword default True;
property PopupMenu;
property ReadOnly;
property ShowHint;
property TabOrder;
property TabStop;
property Text;
property Visible;
property OnChange;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
end;
procedure Register;
implementation
uses
BidiUtils;
procedure Register;
begin
RegisterComponents('JR', [TPasswordEdit]);
end;
{ TPasswordEdit }
constructor TPasswordEdit.Create(AOwner: TComponent);
begin
inherited;
FPassword := True;
end;
procedure TPasswordEdit.CreateParams(var Params: TCreateParams);
begin
inherited;
if FPassword then
Params.Style := Params.Style or ES_PASSWORD;
SetBiDiStyles(Self, Params);
end;
procedure TPasswordEdit.SetPassword(Value: Boolean);
begin
if FPassword <> Value then begin
FPassword := Value;
RecreateWnd;
end;
end;
end.
|
program PWM_TFTP_SERVO;
{$mode objfpc}{$H+}
{ Advanced example - PWM_TFTP }
{ }
{ This example shows how to create webserver and TFTP server with remote shell }
{ This version is for Raspberry Pi 2B and will also work on a 3B. }
{ After the first time that kernel7.img has been transferred to micro sd card }
{ tftp xx.xx.xx.xx < cmdstftp }
{ contents of cmdstftp }
{ binary }
{ put kernel7.img }
{ quit }
uses
{InitUnit, Include InitUnit to allow us to change the startup behaviour}
RaspberryPi, {Include RaspberryPi2 to make sure all standard functions are included}
GlobalConfig,
GlobalConst,
GlobalTypes,
Platform,
Threads,
Console,
Classes,
WebStatus,
uTFTP,
Winsock2,
{ needed to use ultibo-tftp }
{ needed for telnet }
Shell,
ShellFilesystem,
ShellUpdate,
RemoteShell,
{ needed for telnet }
Logging,
SysUtils,
PWM; {Include the PWM unit to allow access to the functions}
var
MyPLoggingDevice : ^TLoggingDevice;
PWM0Device:PPWMDevice;
PWM1Device:PPWMDevice;
Count:Integer;
handle:TWindowHandle;
Handle1:THandle;
//HTTPListener:THTTPListener;
{ needed to use ultibo-tftp }
TCP : TWinsock2TCPClient;
IPAddress : string;
function WaitForIPComplete : string;
var
TCP : TWinsock2TCPClient;
begin
TCP := TWinsock2TCPClient.Create;
Result := TCP.LocalAddress;
if (Result = '') or (Result = '0.0.0.0') or (Result = '255.255.255.255') then
begin
while (Result = '') or (Result = '0.0.0.0') or (Result = '255.255.255.255') do
begin
sleep (1500);
Result := TCP.LocalAddress;
end;
end;
TCP.Free;
end;
procedure Msg (Sender : TObject; s : string);
begin
ConsoleWindowWriteLn (Handle, s);
end;
procedure WaitForSDDrive;
begin
while not DirectoryExists ('C:\') do sleep (500);
end;
begin
{
The following 3 lines are logging to the console}
CONSOLE_REGISTER_LOGGING:=True;
LoggingConsoleDeviceAdd(ConsoleDeviceGetDefault);
LoggingDeviceSetDefault(LoggingDeviceFindByType(LOGGING_TYPE_CONSOLE));
{The following 2 lines are logging to a file
LoggingDeviceSetTarget(LoggingDeviceFindByType(LOGGING_TYPE_FILE),'c:\ultibologging.log');
LoggingDeviceSetDefault(LoggingDeviceFindByType(LOGGING_TYPE_FILE));
MyPLoggingDevice:=LoggingDeviceGetDefault;
LoggingDeviceRedirectOutput(MyPLoggingDevice);}
{Create a console window to show what is happening}
handle:=ConsoleWindowCreate(ConsoleDeviceGetDefault,CONSOLE_POSITION_TOPLEFT,True);
// wait for IP address and SD Card to be initialised.
{WaitForSDDrive;
IPAddress := WaitForIPComplete;}
{Wait a few seconds for all initialization (like filesystem and network) to be done}
Sleep(5000);
{Display a startup message on the console}
ConsoleWindowWriteLn(handle,'Starting PWM_TFTP example');
ConsoleWindowWriteLn (handle, 'Local Address ' + IPAddress);
SetOnMsg (@Msg);
{Create and start the HTTP Listener for our web status page}
//HTTPListener:=THTTPListener.Create;
//HTTPListener.Active:=True;
{Register the web status page, the "Thread List" page will allow us to see what is happening in the example}
//WebStatusRegister(HTTPListener,'','',True);
{First locate the PWM devices
The Raspberry Pi has two PWM channels which will normally end up with the names
PWM0 and PWM1 when the driver is included in an application.
You could also use PWMDeviceFindByDescription() here and use the contants defined
in the BCM2709 unit for BCM2709_PWM0_DESCRIPTION and BCM2709_PWM1_DESCRIPTION.
Those values are for Raspberry Pi 2 so you would adjust to use BCM2708 or BCM2710 for
the Raspberry Pi A/B/A+/B+/Zero or Raspberry Pi 3 respectively. The names of the
constants also change to BCM2708 or BCM2710 for the different models as well}
PWM0Device:=PWMDeviceFindByName('PWM0');
if (PWM0Device <> nil) then
begin
{This example uses the default GPIO pin values which are GPIO_PIN_18 for PWM0
and GPIO_PIN_19 for PWM1. If you need to use one of the alternate GPIO pins
then you can call PWMDeviceSetGPIO() with the required pin number.
You can also use PWMDeviceGetGPIO() to find out the currently configured pin}
PWMDeviceSetGPIO(PWM0Device, GPIO_PIN_18);
ConsoleWindowWriteLn(Handle,'PWM 0 pin set to gpio pin ' + inttostr(PWMDeviceGetGPIO(PWM0Device)));
{On the Raspberry Pi the PWM setup requires 3 values.
The first is the Mode which can be PWM_MODE_MARKSPACE, PWM_MODE_BALANCED or
PWM_MODE_SERIALIZED. These are described in detail in the BCM2835 ARM Peripherals
documentation which can be found via the resources page on the Ultibo wiki.
The second value is the Frequency which controls the frequency of the clock
used by the PWM device. On the Raspberry Pi both PWM devices share a common
clock so changing the frequency on one device also changes it on the other.
The final setup value is the Range, the exact meaning of the range value varies
depending on the mode selected but in general it represents the time period of
one full cycle of the waveform output by the device.
The range and the data define what is actually output onto the GPIO pin, as an
alternative to setting them individually you can call PWMDeviceConfigure() which
allows you to specify both a Range and a Duty cycle in nanoseconds.
Try experimenting with the range and data values to see how they affect the LEDs}
{Setup PWM device 0}
{Set the range to 2000}
PWMDeviceSetRange(PWM0Device,2000);
{And the mode to PWM_MODE_MARKSPACE}
PWMDeviceSetMode(PWM0Device,PWM_MODE_MARKSPACE);
{Finally set the frequency to 50KHz
19200000/192/2000
https://learn.adafruit.com/adafruits-raspberry-pi-lesson-8-using-a-servo-motor/software}
PWMDeviceSetFrequency(PWM0Device,100000);
ConsoleWindowWriteLn(Handle,'PWM 0 Freq ' + inttostr(PWMDeviceGetFrequency(PWM0Device)));
ConsoleWindowWriteLn(Handle,'PWM 0 Range ' + inttostr(PWMDeviceGetRange(PWM0Device)));
{Start the PWM devices
This will start the clock and enable the devices, the final step to
output something is to write some actual data which will specify how
many pulses are output within the time period defined by the range.
A data value of 0 will turn off the output whereas a data value equal
to the range will mean the pulses are continuous. We can use this to
make our LED go from fully off to fully on in gradual steps, the time
it takes to make this transition is simply controlled by the value
passed to Sleep()}
if (PWMDeviceStart(PWM0Device) = ERROR_SUCCESS) then
begin
{Start an endless loop writing data values to the PWM devices}
{start of While}
while True do
begin
{Cycle the devices through the entire range from 0 to 1023.
The PWM0 device goes upwards (from off to full brightness)
and the PWM1 device goes down (from full brightness to off)}
{Count :=100;
PWMDeviceWrite(PWM0Device,Count);
ConsoleWindowWriteLn(Handle,'PWM 0 ' + inttostr(Count));
Sleep(100);
Count :=150;
PWMDeviceWrite(PWM0Device,Count);
ConsoleWindowWriteLn(Handle,'PWM 0 ' + inttostr(Count));
Sleep(100);
Count :=200;
PWMDeviceWrite(PWM0Device,Count);
ConsoleWindowWriteLn(Handle,'PWM 0 ' + inttostr(Count));
Sleep(100);
Count :=250;
PWMDeviceWrite(PWM0Device,Count);
ConsoleWindowWriteLn(Handle,'PWM 0 ' + inttostr(Count));
Sleep(100);}
{start of for loop}
for Count:=50 to 250 do
begin
PWMDeviceWrite(PWM0Device,Count);
//ConsoleWindowWriteLn(Handle,'PWM 0 ' + inttostr(Count));
Sleep(10);
end;
{end of for loop}
ConsoleWindowWriteLn(Handle,'End of up loop');
{start of for loop}
for Count:=250 downto 50 do
begin
PWMDeviceWrite(PWM0Device,Count);
//ConsoleWindowWriteLn(Handle,'PWM 0 ' + inttostr(Count));
Sleep(10);
end;
{end of for loop}
ConsoleWindowWriteLn(Handle,'End of dn loop');
Sleep(20);
ConsoleWindowWriteLn(Handle,'End of While');
end;
{end of While}
{Stop the PWM devices
This will disable the devices and stop the clock, remember that the
clock is shared between both devices so the driver will only actually
stop the clock when PWMDeviceStop() is called for both of them}
PWMDeviceStop(PWM0Device);
end
else
begin
ConsoleWindowWriteLn(Handle,'Error: Failed to start PWM devices 0 and 1');
end;
end
else
begin
ConsoleWindowWriteLn(Handle,'Error: Failed to locate PWM devices 0 and 1');
end;
{Halt this thread}
ThreadHalt(0);
end.
|
unit RptHelper;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
type
TRptStatus = (rsNone, rsDone, rsProblem, rsScan, rsReport, rsAbort, rsNMSR, rsDelCat, rsMatch, rsCustom);
TStatusUpdateEvent = procedure(Sender: TObject; Status:TRptStatus; PctComplete:integer; StatusMsg:string) of object;
TRptHelper = class(TComponent)
private
FStatusMsg: string;
FFoundCount : integer;
FScanCount : integer;
TotalCount : integer;
ModNum : integer;
CurrentStatus : TRptStatus;
FOnStatusUpdate: TStatusUpdateEvent;
FPctComplete: integer;
procedure SetOnStatusUpdate(const Value: TStatusUpdateEvent);
{ Private declarations }
protected
{ Protected declarations }
public
{ Public declarations }
procedure ScanOne(More:string='');
procedure FoundOne;
procedure ResetCounter(n:integer);
procedure UpdateStatus(AStatus:TRptStatus;More:string = '');
property StatusMsg:string read FStatusMsg;
property PctComplete:integer read FPctComplete;
published
{ Published declarations }
property OnStatusUpdate:TStatusUpdateEvent read FOnStatusUpdate write SetOnStatusUpdate;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('FFS Common', [TRptHelper]);
end;
{ TRptHelper }
procedure TRptHelper.FoundOne;
begin
inc(FFoundCount);
end;
procedure TRptHelper.ResetCounter(n: integer);
begin
TotalCount := n;
ModNum := TotalCount div 100;
if ModNum > 100 then ModNum := 50; //100;
if ModNum = 0 then ModNum := 5;
FFoundCount := 0;
FScanCount := 0;
end;
procedure TRptHelper.ScanOne(More:string='');
begin
inc(FScanCount);
if (FScanCount mod ModNum) = 0 then UpdateStatus(CurrentStatus,More);
end;
procedure TRptHelper.SetOnStatusUpdate(const Value: TStatusUpdateEvent);
begin
FOnStatusUpdate := Value;
end;
procedure TRptHelper.UpdateStatus(AStatus: TRptStatus; More: string);
begin
if TotalCount > 0 then FPctComplete := (FScanCount * 100) div TotalCount
else FPctComplete := 0;
CurrentStatus := AStatus;
case AStatus of
rsScan : FStatusMsg := trim(more + ' Scan ' + inttostr(FScanCount) + '/' + inttostr(TotalCount) + ' Found ' + inttostr(FFoundCount));
rsReport : FStatusMsg := trim(more + ' Preparing ' + inttostr(FScanCount) + '/' + inttostr(TotalCount));
rsDone : FStatusMsg := 'Processed ' + inttostr(TotalCount) + ' Records';
rsProblem: FStatusMsg := 'Stopped Processing at ' + inttostr(FScanCount) + ' of ' + inttostr(TotalCount);
rsAbort : FStatusMsg := 'Process aborted by user';
rsMatch : FStatusMsg := trim(more + ' Matching ' + inttostr(FScanCount) + '/' + inttostr(TotalCount) + ' Found ' + inttostr(FFoundCount));
rsCustom : FStatusMsg := more;
end;
if assigned(FOnStatusUpdate) then FOnStatusUpdate(self, CurrentStatus, FPctComplete, FStatusMsg);
end;
end.
|
program RunScheduledTasks;
{$APPTYPE CONSOLE}
{$MODE DELPHI}
uses
SysUtils,
DateUtils,
Quick.Commons,
Quick.Console,
Quick.Threads;
type
{ TMyJob }
TMyJob = class
private
fId : Integer;
fName : string;
public
property Id : Integer read fId write fId;
property Name : string read fName write fName;
procedure DoJob(task : ITask);
procedure Failed(task : ITask; aException : Exception);
procedure Retry(task : ITask; aException : Exception; var vStopRetries : Boolean);
procedure Finished(task : ITask);
procedure Expired(task : ITask);
end;
var
scheduledtasks : TScheduledTasks;
myjob : TMyJob;
ScheduledDate : TDateTime;
ExpirationDate : TDateTime;
{ TMyJob }
procedure TMyJob.DoJob(task : ITask);
var
a, b, i : Integer;
begin
cout('[%s] task "%s" doing a %s job %d...',[DateTimeToStr(Now()),fName,task.Param[0].AsString,task.Param[1].AsInteger],etInfo);
Sleep(Random(1000));
a := Random(100);
b := Random(5) + 1;
i := a div b;
task.Result := i;
cout('task "%s" result %d / %d = %d',[fName,a,b,i],etSuccess);
end;
procedure TMyJob.Failed(task : ITask; aException : Exception);
begin
cout('task "%s" failed (%s)',[fName,aException.Message],etError);
end;
procedure TMyJob.Retry(task: ITask; aException: Exception; var vStopRetries: Boolean);
begin
cout('task "%s" retrying %d/%d (%s)',[fName,task.NumRetries,task.MaxRetries,aException.Message],etWarning);
end;
procedure TMyJob.Finished(task : ITask);
begin
cout('task "%s" finished (Result = %d)',[fName,task.Result.AsInteger],etDebug);
end;
procedure TMyJob.Expired(task : ITask);
begin
cout('task "%s" expired',[fName],etWarning);
end;
begin
Console.LogVerbose := LOG_DEBUG;
try
scheduledtasks := TScheduledTasks.Create;
scheduledtasks.RemoveTaskAfterExpiration := True;
myjob := TMyJob.Create;
myjob.Id := 1;
myjob.Name := 'Run now and repeat every 1 minute for 5 times';
scheduledtasks.AddTask('Task1',['blue',7],True,myjob.DoJob
).WaitAndRetry(2,100
).OnRetry(myjob.Retry
).OnException(myjob.Failed
).OnTerminated(myjob.Finished
).OnExpired(myjob.Expired
).RepeatEvery(1,TTimeMeasure.tmSeconds,5);
myjob := TMyJob.Create;
myjob.Id := 2;
myjob.Name := 'Run now and repeat every 1 second forever';
scheduledtasks.AddTask('Task2',['red',14],True,myjob.DoJob
).WaitAndRetry(2,100
).OnRetry(myjob.Retry
).OnException(myjob.Failed
).OnTerminated(myjob.Finished
).OnExpired(myjob.Expired
).StartAt(Now()
).RepeatEvery(1,TTimeMeasure.tmseconds);
ScheduledDate := IncSecond(Now(),5);
ExpirationDate := IncSecond(ScheduledDate,10);
myjob := TMyJob.Create;
myjob.Id := 3;
myjob.Name := Format('Run at %s and repeat every 1 second until %s',[DateTimeToStr(ScheduledDate),DateTimeToStr(ExpirationDate)]);
scheduledtasks.AddTask('Task3',['white',21],True,myjob.DoJob
).WaitAndRetry(2,100
).OnRetry(myjob.Retry
).OnException(myjob.Failed
).OnTerminated(myjob.Finished
).OnExpired(myjob.Expired
).StartAt(ScheduledDate
).RepeatEvery(1,TTimeMeasure.tmSeconds,ExpirationDate);
scheduledtasks.Start;
cout('Running tasks in background!',etInfo);
ConsoleWaitForEnterKey;
scheduledtasks.Free;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
|
{
Машинки. Физика, ИИ, коллизи, рендер...
}
unit uBCar;
interface
uses
uTypes, OpenGL, uModels, uTextures, uGlobal, uLog;
const
AIR_B = 0.1/64;
TRM_B = 0.5/64;
{}
T_R = -1;
T_N = 0;
T_1 = 1;
T_2 = 2;
T_3 = 3;
T_4 = 4;
type
TCarCtrl = (go_frw, go_bak, go_left, go_right, go_brk, go_hbr);
TCarCtrls = set of TCarCtrl;
TCar = class
name : string[32]; {Имя игрока}
rmp : GLfloat; {Обороты}
transm : Shortint; {передача}
mass : GLfloat; {Масса}
damage : GLfloat; {Повреждение}
{BACK WHEELS}
b_pos : TPoint3f; {Положение}
b_xang : GLfloat; {Поворот}
b_mang : GLfloat; {Движение}
b_a : GLfloat; {Ускорение}
b_vec_a: GLfloat;
b_vec_v: GLfloat;
b_vec : TVector3f;
{FRONT WHEELS}
f_pos : TPoint3f;
f_dxang: GLfloat;
f_a : GLfloat;
f_vec_a: GLfloat;
f_vec_v: GLfloat;
f_vec : TVector3f;
{OTHER POWERS}
{ f_col_ang : GLfloat;
f_col_v : GLfloat;
b_col_ang : GLfloat;
b_col_v : GLfloat; }
{CONTROLS}
ctrls : TCarCtrls;
color : array[0..2] of GLfloat;
a_korob: Boolean;
{else}
k_ang : GLfloat;
h_break : Boolean;
blowed : Boolean;
y_speed : GLfloat;
ccp : Integer;
{TEST}
is_finish : Boolean;
fin_time : Cardinal;
public
constructor Create;
destructor Destroy;
procedure Render;
procedure DoMove;
procedure Control;
procedure PushButton(button : TCarCtrl);
procedure AddTransmiss;
procedure DecTransmiss;
procedure AIControl;
procedure AutoKorobka;
end;
TCarEngine = class
cars : array of TCar;
main_car : TCar;
constructor Create;
destructor Destroy;
public
procedure DoAI;
procedure DoControl;
procedure DoMove;
procedure DoRender;
procedure AddCar(x,z:GLfloat);
procedure DoCollision;
end;
var
CarEngine : TCarEngine;
trees : array[0..200] of TPoint3f; {2,494}
implementation
uses
uTrack;
destructor TCar.Destroy;
begin
LogStr('Car Destroy', 2);
inherited Destroy;
end;
destructor TCarEngine.Destroy;
var
i:Integer;
begin
LogStr('CarEngine.Destroy', 1);
for i := 0 to length(cars)-1 do
cars[i].Destroy;
inherited Destroy;
end;
procedure TCarEngine.DoCollision;
const
TEMP_CONSTANT = 0.5;
DISTANT = 3.5;
var
i,j:Integer;
p,p1:TPoint2f;
pi,pj:TPoint3f;
begin
for i := 0 to length(cars)-2 do
begin
for j := i+1 to length(cars)-1 do
begin
if Distance3f(cars[i].b_pos, cars[j].b_pos)<DISTANT then
begin
pi.x := cars[j].b_pos.x+cwSin(AngbPoints(cars[j].b_pos.z, cars[j].b_pos.x, cars[i].b_pos.z, cars[i].b_pos.x))*DISTANT;
pi.z := cars[j].b_pos.z+cwCos(AngbPoints(cars[j].b_pos.z, cars[j].b_pos.x, cars[i].b_pos.z, cars[i].b_pos.x))*DISTANT;
pj.x := cars[i].b_pos.x+cwSin(AngbPoints(cars[i].b_pos.z, cars[i].b_pos.x, cars[j].b_pos.z, cars[j].b_pos.x))*DISTANT;
pj.z := cars[i].b_pos.z+cwCos(AngbPoints(cars[i].b_pos.z, cars[i].b_pos.x, cars[j].b_pos.z, cars[j].b_pos.x))*DISTANT;
cars[i].b_pos := pi;
cars[j].b_pos := pj;
cars[i].b_vec_a := AngbPoints(cars[j].b_pos.z, cars[j].b_pos.x, cars[i].b_pos.z, cars[i].b_pos.x);
cars[j].b_vec_a := AngbPoints(cars[i].b_pos.z, cars[i].b_pos.x, cars[j].b_pos.z, cars[j].b_pos.x);
cars[i].b_vec_v := cars[j].b_a*2;
cars[j].b_vec_v := cars[i].b_a*2;
end;
if Distance3f(cars[i].b_pos, cars[j].f_pos)<DISTANT then
begin
pi.x := cars[j].f_pos.x+cwSin(AngbPoints(cars[j].f_pos.z, cars[j].f_pos.x, cars[i].b_pos.z, cars[i].b_pos.x))*DISTANT;
pi.z := cars[j].f_pos.z+cwCos(AngbPoints(cars[j].f_pos.z, cars[j].f_pos.x, cars[i].b_pos.z, cars[i].b_pos.x))*DISTANT;
pj.x := cars[i].b_pos.x+cwSin(AngbPoints(cars[i].b_pos.z, cars[i].b_pos.x, cars[j].f_pos.z, cars[j].f_pos.x))*DISTANT;
pj.z := cars[i].b_pos.z+cwCos(AngbPoints(cars[i].b_pos.z, cars[i].b_pos.x, cars[j].f_pos.z, cars[j].f_pos.x))*DISTANT;
cars[i].b_pos := pi;
cars[j].f_pos := pj;
cars[i].b_vec_a := AngbPoints(cars[j].f_pos.z, cars[j].f_pos.x, cars[i].b_pos.z, cars[i].b_pos.x);
cars[j].f_vec_a := AngbPoints(cars[i].b_pos.z, cars[i].b_pos.x, cars[j].f_pos.z, cars[j].f_pos.x);
cars[i].b_vec_v := cars[j].b_a*2;
cars[j].f_vec_v := cars[i].b_a*2;
end;
if Distance3f(cars[i].f_pos, cars[j].b_pos)<DISTANT then
begin
pi.x := cars[j].b_pos.x+cwSin(AngbPoints(cars[j].b_pos.z, cars[j].b_pos.x, cars[i].f_pos.z, cars[i].f_pos.x))*DISTANT;
pi.z := cars[j].b_pos.z+cwCos(AngbPoints(cars[j].b_pos.z, cars[j].b_pos.x, cars[i].f_pos.z, cars[i].f_pos.x))*DISTANT;
pj.x := cars[i].f_pos.x+cwSin(AngbPoints(cars[i].f_pos.z, cars[i].f_pos.x, cars[j].b_pos.z, cars[j].b_pos.x))*DISTANT;
pj.z := cars[i].f_pos.z+cwCos(AngbPoints(cars[i].f_pos.z, cars[i].f_pos.x, cars[j].b_pos.z, cars[j].b_pos.x))*DISTANT;
cars[i].f_pos := pi;
cars[j].b_pos := pj;
cars[i].f_vec_a := AngbPoints(cars[j].b_pos.z, cars[j].b_pos.x, cars[i].f_pos.z, cars[i].f_pos.x);
cars[j].b_vec_a := AngbPoints(cars[i].f_pos.z, cars[i].f_pos.x, cars[j].b_pos.z, cars[j].b_pos.x);
cars[i].f_vec_v := cars[j].b_a*2;
cars[j].b_vec_v := cars[i].b_a*2;
end;
if Distance3f(cars[i].f_pos, cars[j].f_pos)<DISTANT then
begin
pi.x := cars[j].f_pos.x+cwSin(AngbPoints(cars[j].f_pos.z, cars[j].f_pos.x, cars[i].f_pos.z, cars[i].f_pos.x))*DISTANT;
pi.z := cars[j].f_pos.z+cwCos(AngbPoints(cars[j].f_pos.z, cars[j].f_pos.x, cars[i].f_pos.z, cars[i].f_pos.x))*DISTANT;
pj.x := cars[i].f_pos.x+cwSin(AngbPoints(cars[i].f_pos.z, cars[i].f_pos.x, cars[j].f_pos.z, cars[j].f_pos.x))*DISTANT;
pj.z := cars[i].f_pos.z+cwCos(AngbPoints(cars[i].f_pos.z, cars[i].f_pos.x, cars[j].f_pos.z, cars[j].f_pos.x))*DISTANT;
cars[i].f_pos := pi;
cars[j].f_pos := pj;
cars[i].f_vec_a := AngbPoints(cars[j].f_pos.z, cars[j].f_pos.x, cars[i].f_pos.z, cars[i].f_pos.x);
cars[j].f_vec_a := AngbPoints(cars[i].f_pos.z, cars[i].f_pos.x, cars[j].f_pos.z, cars[j].f_pos.x);
cars[i].f_vec_v := cars[j].b_a*2;
cars[j].f_vec_v := cars[i].b_a*2;
end;
end;
end;
for i := 0 to length(cars)-1 do
begin
for j := 0 to 200 do
begin
if Distance3f(cars[i].f_pos, trees[j])<5.494 then
begin
cars[i].f_pos.x := trees[j].x+cwSin(AngbPoints(trees[j].z, trees[j].x, cars[i].f_pos.z, cars[i].f_pos.x))*5.5;
cars[i].f_pos.z := trees[j].z+cwCos(AngbPoints(trees[j].z, trees[j].x, cars[i].f_pos.z, cars[i].f_pos.x))*5.5;
end;
if Distance3f(cars[i].b_pos, trees[j])<5.494 then
begin
cars[i].b_pos.x := trees[j].x+cwSin(AngbPoints(trees[j].z, trees[j].x, cars[i].b_pos.z, cars[i].b_pos.x))*5.5;
cars[i].b_pos.z := trees[j].z+cwCos(AngbPoints(trees[j].z, trees[j].x, cars[i].b_pos.z, cars[i].b_pos.x))*5.5;
end;
end;
p := Track.fin_crd[0];
p1.x := cars[i].f_pos.x;
p1.z := cars[i].f_pos.z;
if not cars[i].is_finish then
begin
while true do
begin
if abs(lineln(@p, @p1))<1 then
begin
Track.AddFinisher(cars[i]);
cars[i].is_finish := True;
cars[i].fin_time := race_time;
break;
end;
if (Track.fin_crd[1].x>Track.fin_crd[0].x) then
begin
if p.x > Track.fin_crd[1].x then
begin
if (Track.fin_crd[1].z>Track.fin_crd[0].z) then
if p.z > Track.fin_crd[1].z then
break;
if (Track.fin_crd[1].z<Track.fin_crd[0].z) then
if p.z < Track.fin_crd[1].z then
break;
end;
end;
if (Track.fin_crd[1].x<Track.fin_crd[0].x) then
begin
if p.x < Track.fin_crd[1].x then
begin
if (Track.fin_crd[1].z>Track.fin_crd[0].z) then
if p.z > Track.fin_crd[1].z then
break;
if (Track.fin_crd[1].z<Track.fin_crd[0].z) then
if p.z < Track.fin_crd[1].z then
break;
end;
end;
p.x := p.x + Track.fin_v.x*0.01;
p.z := p.z + Track.fin_v.z*0.01;
end;
end;
end;
end;
procedure TCarEngine.DoAI;
var
i:Integer;
begin
for i := 1 to length(cars)-1 do
begin
cars[i].AIControl;
end;
end;
procedure TCarEngine.AddCar(x,z:GLfloat);
begin
SetLength(cars, length(cars)+1);
cars[length(cars)-1] := TCar.Create;
cars[length(cars)-1].b_pos.x := x;
cars[length(cars)-1].b_pos.z := z;
cars[length(cars)-1].f_pos.x := x;
cars[length(cars)-1].f_pos.z := z;
cars[length(cars)-1].a_korob := True;
end;
procedure TCarEngine.DoRender;
var
i:Integer;
begin
for i := 0 to length(cars)-1 do
cars[i].Render;
end;
procedure TCarEngine.DoMove;
var
i:Integer;
begin
for i := 0 to length(cars)-1 do
cars[i].DoMove;
end;
procedure TCarEngine.DoControl;
var
i:Integer;
begin
for i := 0 to length(cars)-1 do
cars[i].Control;
end;
constructor TCarEngine.Create;
begin
LogStr(PChar(#9 + 'CarEngine.Create'));
SetLength(cars, 1);
cars[0] := TCar.Create;
cars[0].a_korob := True;
main_car := cars[0];
main_car.name := 'Player';
end;
{====================================}
procedure TCar.AutoKorobka;
begin
if transm <> T_R then
begin
if transm = T_N then transm := T_1;
if rmp>=7800 then AddTransmiss;
end;
end;
procedure TCar.AIControl;
var
d:GLfloat;
begin
if ccp<>Track.t_length-1 then
begin
if Distance3f(f_pos, Track.chpts[ccp])>ROAD_WDT then
begin
//d := AngbPoints(b_pos.z, b_pos.x, Track.chpts[ccp].z, Track.chpts[ccp].x);
{ if d-b_xang<180 then
f_dxang := f_dxang - 2 else f_dxang := f_dxang + 2;}
d := AngbPoints(f_pos.z, f_pos.x, Track.chpts[ccp].z, Track.chpts[ccp].x);
if d>315 then d := -(360-d);
if (d<180)and(d>45) then d := 45;
if d<=45 then d := d;
if (d>180)and(d<315) then d := -45;
f_dxang := d;
if((f_dxang>15)and(f_dxang>-15))or(b_a<FPSsynSpeed(100))then
ctrls := ctrls + [go_frw];
if(abs(f_dxang)>15)and(b_a<FPSsynSpeed(30)) then ctrls := [go_hbr];
end else
begin
inc(ccp, 1); {TODO : AI}
if ccp>Track.t_length-1 then ccp := Track.t_length-1;
end;
end else
begin
ctrls := [go_hbr];
end;
end;
procedure TCar.AddTransmiss;
begin
if transm<>4 then
begin
inc(transm);
rmp := rmp/2;
end;
end;
procedure TCar.DecTransmiss;
begin
if transm <> -1 then
begin
Dec(transm);
end;
end;
procedure TCar.PushButton(button : TCarCtrl);
begin
ctrls := ctrls + [button];
end;
procedure TCar.Control;
var
dr:GLfloat;
begin
if not blowed then
begin
if a_korob then AutoKorobka;
if (transm = 0)or(transm=-1) then
begin
dr := 1;
end else
begin
dr := transm;
end;
if go_left in ctrls then f_dxang := f_dxang + 2;
if go_right in ctrls then f_dxang := f_dxang - 2;
if go_frw in ctrls then rmp := rmp + 40/dr; //b_a := b_a + FPSsynSpeed(1);
if go_bak in ctrls then rmp := rmp - 40/dr; //b_a := b_a - FPSsynSpeed(1);
if go_hbr in ctrls then
begin
h_break := True;
rmp := rmp - 100;
end else h_break := False;
ctrls := [];
end;
end;
procedure TCar.DoMove;
const
DZ = 2;
var
d : Single;
begin
if damage = 0 then
begin
blowed := True;
y_speed := 1;
rmp := 0;
end;
if h_break then
begin
if b_a>0 then
b_a := b_a - TRM_B;
if b_a<0 then
b_a := b_a + TRM_B;
end;
{TEST}
if rmp < 0 then rmp := 0;
if rmp > 8000 then rmp := 8000;
if abs(f_dxang)>40 then f_dxang := 40*Signf(f_dxang);
case transm of
T_R : if b_a > -KphToFPS(40)*(rmp/8000) then b_a := b_a - FPSsynSpeed(0.5);
T_N : {Neitral};
T_1 : if b_a < KphToFPS(45)*(rmp/8000) then b_a := b_a + FPSsynSpeed(1.5);
T_2 : if b_a < KphToFPS(90)*(rmp/8000) then b_a := b_a + FPSsynSpeed(1);
T_3 : if b_a < KphToFPS(180)*(rmp/8000) then b_a := b_a + FPSsynSpeed(0.5);
T_4 : if b_a < KphToFPS(200)*(rmp/8000) then b_a := b_a + FPSsynSpeed(0.25);
end;
f_a := b_a;
{gen vectors}
b_vec.x := cwSin(b_mang)*(b_a*2);
b_vec.z := cwCos(b_mang)*(b_a*2);
b_vec.x := b_vec.x + cwSin(b_vec_a)*b_vec_v;
b_vec.z := b_vec.z + cwCos(b_vec_a)*b_vec_v;
f_vec.x := cwSin(b_xang + f_dxang)*(f_a*2);
f_vec.z := cwCos(b_xang + f_dxang)*(f_a*2);
f_vec.x := f_vec.x + cwSin(f_vec_a)*f_vec_v;
f_vec.z := f_vec.z + cwCos(f_vec_a)*f_vec_v;
{RULE}
b_pos.x := b_pos.x + b_vec.x; {v}
b_pos.z := b_pos.z + b_vec.z; {v}
f_pos.x := f_pos.x + f_vec.x; {v}
f_pos.z := f_pos.z + f_vec.z; {v}
b_xang := Angbpoints(b_pos.z, b_pos.x, f_POS.z, f_POS.x);
f_pos.x := b_pos.x + cwSin(b_xang)*3.8;
f_pos.z := b_pos.z + cwCos(b_xang)*3.8;
{after TEST}
{TODO : Zanos}
b_mang := b_xang;
if b_mang>360 then b_mang := b_mang-360;
if b_mang<0 then b_mang := 360+b_mang;
if f_dxang>0 then f_dxang := f_dxang - 1;
if f_dxang<0 then f_dxang := f_dxang + 1;
if b_a>0 then b_a := b_a - AIR_B;
if f_vec_v > 0 then f_vec_v := f_vec_v - 0.01;
if f_vec_v < 0.01 then f_vec_v := 0;
if b_vec_v > 0 then b_vec_v := b_vec_v - 0.01;
if b_vec_v < 0.01 then b_vec_v := 0;
{ if b_col_v > 0 then b_col_v := b_col_v - 0.01;
if f_col_v > 0 then f_col_v := f_col_v - 0.01;}
rmp := rmp - 5;
end;
procedure TCar.Render;
begin
k_ang := k_ang + b_a*64;
if k_ang >=360 then k_ang := 0;
glMatrixMode(GL_MODELVIEW);
glColor3f(0.0, 0.0, 0.0);
{LEFT BACK WHEEL}
glLoadIdentity;
glTranslatef(b_pos.x, b_pos.y+0.500, b_pos.z);
glRotatef(b_xang, 0.0, 0.1, 0.0);
glTranslatef(-1.3, 0.0, 0.0);
glRotatef(k_ang, 0.1, 0.0, 0.0);
glCallList(MOD_WHEEL);
{RIGHT BACK WHEEL}
glLoadIdentity;
glTranslatef(b_pos.x, b_pos.y+0.500, b_pos.z);
glRotatef(b_xang, 0.0, 0.1, 0.0);
glTranslatef(1.3, 0.0, 0.0);
glRotatef(k_ang, 0.1, 0.0, 0.0);
glCallList(MOD_WHEEL);
{LEFT FRONT WHEEL}
glLoadIdentity;
glTranslatef(f_pos.x, f_pos.y+0.500, f_pos.z);
glRotatef(b_xang, 0.0, 0.1, 0.0);
glTranslatef(-1.3, 0, 0);
glRotatef(f_dxang, 0.0, 0.1, 0.0);
glRotatef(k_ang, 0.1, 0.0, 0.0);
glCallList(MOD_WHEEL);
{RIGHT FRONT WHEEL}
glLoadIdentity;
glTranslatef(f_pos.x, f_pos.y+0.500, f_pos.z);
glRotatef(b_xang, 0.0, 0.1, 0.0);
glTranslatef(1.3, 0, 0);
glRotatef(f_dxang, 0.0, 0.1, 0.0);
glRotatef(k_ang, 0.1, 0.0, 0.0);
glCallList(MOD_WHEEL);
{KARDAN}
glColor3f(0.4, 0.4, 0.4);
glLoadIdentity;
glTranslatef(b_pos.x, b_pos.y+0.500, b_pos.z);
glRotatef(b_xang, 0.0, 0.1, 0.0);
glCallList(MOD_KARDAN);
{KUZOV}
glColor3fv(@color);
glLoadIdentity;
glTranslatef(b_pos.x, b_pos.y+0.5, b_pos.z);
glRotatef(b_xang, 0.0, 0.1, 0.0);
glCallList(MOD_KUZOV);
{------------------------ DEBUG --------------------}
{ glLoadIdentity;
glTranslatef(b_pos.x, b_pos.y+1, b_pos.z);
glRotatef(b_xang, 0.0, 0.1, 0.0);
glScalef(1.5, 1, 3);
glColor3f(1.0, 0.0, 0.0);
glCallList(MOD_QUBE);
glLoadIdentity;
glTranslatef(b_pos.x, b_pos.y+1, b_pos.z);
glRotatef(b_mang, 0.0, 0.1, 0.0);
glScalef(1.5, 1, 3);
glColor3f(1.0, 0.0, 0.0);
glCallList(MOD_QUBE); }
{------------------------ /DEBUG --------------------}
end;
constructor TCar.Create;
const
av_chrs : array[0..26] of Char =
('a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x',
'y', 'z', ' ');
var
i:Integer;
begin
damage := 1000;
mass := 1000;
{TODO : Car color}
color[0] := random(255)/255;
color[1] := random(255)/255;
color[2] := random(255)/255;
f_pos.z := b_pos.z + 3.8;
b_xang := 0;
f_dxang := 0;
rmp := 0;
transm := 0;
b_a := 0;
f_a := 0;
{ f_col_ang := 0;
f_col_v := 0;
b_col_ang := 0;
b_col_v := 0;}
ctrls := [];
is_finish := false;
for i := 0 to random(16) do
name := name + av_chrs[random(26)];
LogStr(PChar('Car - ' + String(name)), 2);
end;
end.
|
program a4;
{This program tests the shortest path algorithm from program strategy 10.16
Below you will find a test program, and some procedure headers. You must fill in the bodies
of the procedures. Do not alter the test program or type definitions in any way.
You are given a constant for INFINITY, which is defined to be the same as MAXINT.
This is a constant that returns the largest possible number of type integer.
This assumes that you will use low edge weight values.
Stick to weights less than 100 and the output will also look nicer.
NOTE - always comment every single local variable you use. }
{************* CONSTANTS ******************}
Const
MAX = 100; { This is the maximum size of graph. You can make this bigger if you want. }
INFINITY = MAXINT; { Use this anywhere you need "infinity" }
{************* TYPE DEFINITIONS *********************}
Type
{The type definitions below define an adjacency matrix
graph representation that stores edge weights.}
GraphSize = 0..MAX;
VertexNumber = 1..MAX;
AdjacencyRow = Array [VertexNumber] of integer;
GraphRep = Array [VertexNumber] of AdjacencyRow;
{ShortestPathArray is the type for the ShortestDistance
variable that returns the result of Dijkstra's algorithm}
ShortestPathArray = Array [VertexNumber] of integer;
{************** The Procedures and Functions ********************}
{procedure minimum(a,b)
pre: a and b are integers
post: returns the larger of a and b.
NOTE - Pascal does not have a built in minimum function. Use this one if you need it.}
function minimum(a,b: integer): integer;
begin
if a<b then
minimum := a
else
minimum := b
end; { fxn minimum }
{procedure NewGraph(G,S)
pre: S is the size of graph to create.
post: G should be an adjacency matrix or adjacency list that corresponds to a graph with S
vertices and no edges. If using an adjacency matrix, you must initialize the entire matrix.
HINT: Remember that the distance from a vertex to itself is always 0.}
procedure NewGraph(var G:GraphRep; S:GraphSize);
var
i, j: integer ; { indexes for the loops to initialize a graph }
begin
{ use for loops to access each element of the 2D array }
for i := 1 to S do
for j := 1 to S do
{ if i = j, i.e. the edge represents the distance from a node to itself, then the weight is 0 }
if i = j then
G[i, j] := 0
{ otherwise, set the initial weight for each edge to INFINITY }
else
G[i, j] := INFINITY
end; { proc NewGraph }
{procedure AddEdge(G,S,Origin,Terminus,Weight)
pre: G is a graph representation with S vertices. Origin, Terminus, and Weight define an edge to
be added to G.
post: G has the specified edge added. HINT - you might want to print an error message if Origin
or Terminus are bigger than S. }
procedure AddEdge(var G:GraphRep; S:GraphSize; Origin, Terminus:VertexNumber; Weight:integer);
{ This procedure adds an edge to a graph. Because of the way the main procedure is written, with E updated right
after the return from AddEdge, there are several possibilities for the E value to be incorrect. If unacceptable
parameter values (Origin, Terminus, Weight) were entered, then the implementation here prints an error
message, prompts for new values, and recursively calls AddEdge to check and add a new, correct, edge. In this
case though, the program will not exit if the user enters 0' for Origin, as this would mean that E is updated
incorrectly. I thought it best to insist on a correct edge within the AddEdge procedure. As well, there is the case
where a user enters an edge that has previously been entered - the new Weight value will overwrite the previous
value and E will be incremented but there will not have been a new edge added, and for each time this happens,
E will over-report the number of edges by one. In this case though, I thought it best to give the user the ability to
correct or change a previously entered edge and just accept that this will result in E being too large. Also, the
program will overestimate E if a user just enters an edge that is from a node to itself with a zero value - these
cases are not usually considered to be separate edges, but it seemed too much trouble to refuse this option to a
user. E is just used to report to the user and they can count the edges in the adjacency matrix display for an
accurate value of E if they want. E does not figure as a parameter for any procedures, so it doesn't really matter
if it is wrong: it won't affect the running of ShortestPath. }
procedure EdgeInput( var G:GraphRep; S:GraphSize );
{ A private procedure of AddEdge that prompts for new Origin, Terminus, and Weight values, then calls
AddEdge to verify these and add the edge if it has acceptable values. }
var
Origin, Terminus: VertexNumber; { These are the same as the main program variables }
Weight : integer ; { of the same names. }
begin
writeln( 'Please enter a correct edge to continue...');
{ Once within the AddEdge procedure - to ensure that E will be updated correctly, users do not have
the option of using 0' for Origin to exit. }
writeln( '[You cannot exit the program at this stage :( ]' ) ;
{ Prompt for and read new, hopefully acceptable, values for the edge parameters. }
write('Origin: ');
readln(Origin);
write('Terminus: ');
readln(Terminus);
write('Weight: ');
readln(Weight);
{ Call AddEdge to verify these new values and then add the edge or print a further error message and
new prompts. }
AddEdge (G, S, Origin, Terminus, Weight)
end; { proc EdgeInput }
begin
{ Check that Origin and Terminus are in the proper range. Do not have to worry about Origin = 0 here because
that value should never be passed to AddEdge from the main program. }
if not ( ( Origin in [1.. S] ) and ( Terminus in [1..S] ) ) then
begin
{ Write an appropriate error message and call EdgeInput to prompt for new values. }
writeln( 'Error: Origin and Terminus must be in the range 1 to ', S );
EdgeInput(G, S)
end { if }
{ Check that the weight value from a node to itself is not non-zero }
else if (( Origin = Terminus ) and ( Weight <> 0 )) then
begin
{ Write an appropriate error message and call EdgeInput to prompt for new values. }
writeln( 'Error: the distance from a vertex to itself is always 0. ' );
EdgeInput(G, S)
end { else if}
else
{ Otherwise, accept the values and add the appropriate edge to G. }
G[Origin, Terminus] := Weight
end; { proc AddEdge }
{procedure ShortestPath(G,S,Origin,ShortestDistance)
pre: G is a graph representation with S vertices. Origin is the start vertex.
post: ShortestDistance is an array containing the shortest distances from Origin to each vertex.
HINT - program strategy 10.16 uses set variables. This is possible in Pascal, but you can't really use
them the way you need to here. I suggest implementing the set W as an array of booleans.
Initialize them all to FALSE and then each time you want to put a new vertex in the set,
change the corresponding value to TRUE. You also might want to keep a count of the
number of vertices in W.
HINT - Watch out for the two "W" variables in 10.16. They use a big W and a small w. You can't do
that in Pascal. I suggest using "w" for the small one and "BigW" for the big one. Of course
you are free to use whatever variable names you want, but the closer you stick to the book,
the easier it will be to mark.
HINT - Comment this well! }
procedure ShortestPath( var G:GraphRep; S:GraphSize; Origin:VertexNumber; var
ShortestDistance:ShortestPathArray );
var
{ V is the set of vertices in the graph. BigW will be the set of vertices that have already been processed' by the
algorithm. }
V, BigW : set of VertexNumber ;
{ MinDistance holds the minimum value in the ShortestDistance array, for the as yet unprocessed' nodes, during
the first step of the while loop }
MinDistance : integer ;
{ w holds the index in ShortestDistance for the new node at the minimum Distance from the existing nodes. j is
an index for the for loops in the procedure. }
w, j : VertexNumber ;
begin
{ V contains all the vertices in the graph }
V := [1..S] ;
{ BigW is initialized to contain the first vertex - Origin }
BigW := [Origin] ;
{ Initialize ShortestDistance to contain the values in the Origin row of G. }
for j := 1 to S do
ShortestDistance[j] := G[Origin, j] ;
{ Start a loop to continue until all the vertices have been processed and are in BigW, i.e. stop when BigW = V }
while BigW <> V do
BEGIN
{ Initialize MinDistance }
MinDistance := INFINITY ;
{ use j to loop through the indices of ShortestDistance }
for j := 1 to S do
{ only consider those j (vertices) that have not been processed (i.e. are not yet in BigW) and that have their
value in ShortestDistance as less than or equal to the previous MinDistance. This will find the new
minimum value, and corresponding vertex, in ShortestDistance. Here, using less than or equal to'
instead of less than' is necessary to prevent an infinite loop in the case where one node in G cannot be
reached from the others - i.e. its distance from any other node in G will be INFINITY. }
if ( j in ( V - BigW ) ) and ( ShortestDistance[j] <= MinDistance ) then
BEGIN
{ When a new minimum is found, set MinDistance and record the index j with w }
MinDistance := ShortestDistance[j] ;
w := j
END ;
{ After the next vertex, w, has been found - add it to BigW }
BigW := BigW + [w] ;
{ start another loop to compare the existing ShortestDistance values to those which would be obtained by
travelling from w to the unprocessed nodes }
for j := 1 to S do
{ Only consider nodes not yet in BigW and values of G for these nodes that are not INFINITY - if the value
is INFINITY, this cannot be a new minimum, and this also prevents overflow problems with adding
amounts to MAXINT. }
if ( j in ( V - BigW ) ) and ( G[w, j] <> INFINITY ) then
{ Update ShortestDistance if the sum of the existing shortest path to the most recently added node
(ShortestDistance[w]) plus the distance' to a still unprocessed node (G[w, j]) is less than the existing
shortest path to that node (ShortestDistance[j]) }
ShortestDistance[j] := minimum( ShortestDistance[j], (ShortestDistance[w] + G[w, j]) )
END { while }
end; {}
(**************************** IDENTIFICATION **************************)
(* Change this procedure to identify yourself *)
procedure IdentifyMyself;
begin
writeln;
writeln('***** Student Name: Mark Sattolo');
writeln('***** Student Number: 428500');
writeln('***** Professor Name: Sam Scott');
writeln('***** Course Number: CSI-2114D');
writeln('***** T.A. Name: Adam Murray');
writeln('***** Tutorial Number: D-1');
writeln;
end;
var
G: GraphRep; {G and S define the graph}
S: GraphSize;
E, {Counts number of edges}
Weight: integer; { Weight, Origin and Terminus are }
Origin, Terminus, { for User input}
row, col: VertexNumber; { Row and Col are for looping through the adjacency matrix }
answer: string; { Stores users' answers to questions }
ShortestPaths: ShortestPathArray; { Stores the shortest paths }
begin
IdentifyMyself;
{INITIALIZE G}
write('What size of graph do you want (maximum size=',MAX,'): ');
readln(S); writeln;
NewGraph(G,S);
writeln('Enter the edges one by one until you are finished.');
writeln('Quit by entering a zero for the origin vertex.');
E := 0;
repeat
writeln;
write('Origin: ');
readln(Origin);
if Origin > 0 then begin
write('Terminus: ');
readln(Terminus);
write('Weight: ');
readln(Weight);
AddEdge(G,S,Origin,Terminus,Weight);
E := E+1
end
until (Origin<=0);
{DISPLAY G IF REQUESTED}
writeln;
writeln('Your graph has ',S,' vertices and ',E,' edges.');
writeln;
write('Would you like to see the adjacency matrix (y/n)' );
readln(answer); writeln;
if (answer[1] = 'y') or (answer[1] = 'Y') then
for row := 1 to S do begin
for col := 1 to S do
if G[row,col]=INFINITY then
write(' INF')
else
write(G[row,col]:4);
writeln
end;
writeln;
{RUN SHORTEST PATH IF REQUESTED }
write('Would you like to run the shortest path algorithm? (y/n)');
readln(answer); writeln;
if (answer[1] = 'y') or (answer[1] = 'Y') then begin
write('What is the start vertex? (1..',S,'): ');
readln(Origin); writeln;
ShortestPath(G,S,Origin,ShortestPaths);
writeln;
writeln('Shortest paths from start vertex ',Origin,' are: ');
for Terminus := 1 to S do
write(Terminus:5,': ',ShortestPaths[Terminus]);
writeln;
end;
{QUIT}
writeln;
writeln('Bye bye')
end. |
unit ce_common;
{$I ce_defines.inc}
interface
uses
Classes, SysUtils,
{$IFDEF WINDOWS}
Windows, JwaTlHelp32,
{$ENDIF}
{$IFDEF LINUX}
ExtCtrls,
{$ENDIF}
dialogs, forms, process, asyncprocess;
const
DdiagFilter = 'D source|*.d|D interface|*.di|All files|*.*';
exeExt = {$IFDEF WINDOWS} '.exe' {$ELSE} '' {$ENDIF};
objExt = {$IFDEF WINDOWS} '.obj' {$ELSE} '.o' {$ENDIF};
libExt = {$IFDEF WINDOWS} '.lib' {$ELSE} '.a' {$ENDIF};
dynExt = {$IFDEF WINDOWS} '.dll' {$ENDIF} {$IFDEF LINUX}'.so'{$ENDIF} {$IFDEF DARWIN}'.dylib'{$ENDIF};
var
dExtList: TStringList;
DCompiler: string = 'dmd';
type
(**
* Workaround for a TAsyncProcess Linux issue: OnTerminate event not called.
* An idle timer is started when executing and trigs the event if necessary.
*)
TCheckedAsyncProcess = class(TAsyncProcess)
{$IFDEF LINUX}
private
fTimer: TIdleTimer;
procedure checkTerminated(sender: TObject);
public
constructor Create(aOwner: TComponent); override;
procedure Execute; override;
{$ENDIF}
end;
(**
* TProcess with assign() 'overriden'.
*)
TProcessEx = class helper for TProcess
public
procedure Assign(aValue: TPersistent);
end;
(**
* CollectionItem used to store a shortcut.
*)
TCEPersistentShortcut = class(TCollectionItem)
private
fShortcut: TShortCut;
fActionName: string;
published
property shortcut: TShortCut read fShortcut write fShortcut;
property actionName: string read fActionName write fActionName;
public
procedure assign(aValue: TPersistent); override;
end;
(**
* Save a component with a readable aspect.
*)
procedure saveCompToTxtFile(const aComp: TComponent; const aFilename: string);
(**
* Load a component.
*)
procedure loadCompFromTxtFile(const aComp: TComponent; const aFilename: string;
aPropNotFoundHandler: TPropertyNotFoundEvent = nil; anErrorHandler: TReaderError = nil);
(**
* Converts a relative path to an absolute path.
*)
function expandFilenameEx(const aBasePath, aFilename: string): string;
(**
* Patches the directory separators from a string.
* This is used to ensure that a project saved on a platform can be loaded
* on another one.
*)
function patchPlateformPath(const aPath: string): string;
procedure patchPlateformPaths(const sPaths: TStrings);
(**
* Patches the file extension from a string.
* This is used to ensure that a project saved on a platform can be loaded
* on another one. Note that the ext which are handled are specific to coedit projects.
*)
function patchPlateformExt(const aFilename: string): string;
(**
* Returns aFilename without its extension.
*)
function stripFileExt(const aFilename: string): string;
(**
* Ok/Cancel modal dialog
*)
function dlgOkCancel(const aMsg: string): TModalResult;
(**
* Info message
*)
function dlgOkInfo(const aMsg: string): TModalResult;
(**
* Error message
*)
function dlgOkError(const aMsg: string): TModalResult;
(**
* Returns an unique object identifier, based on its heap address.
*)
function uniqueObjStr(const aObject: TObject): string;
(**
* Reduces a filename if its length is over the threshold defined by charThresh.
* Even if the result is not usable anymore, it avoids any "visually-overloaded" MRU menu.
*)
function shortenPath(const aPath: string; charThresh: Word = 60): string;
(**
* Returns the user data dir.
*)
function getUserDocPath: string;
(**
* Returns the documents and settings folder for Coedit.
*)
function getCoeditDocPath: string;
(**
* Fills aList with the names of the files located in aPath.
*)
procedure listFiles(aList: TStrings; const aPath: string; recursive: boolean = false);
(**
* Fills aList with the names of the folders located in aPath.
*)
procedure listFolders(aList: TStrings; const aPath: string);
(**
* Checks if aPath contains at least one sub-folder.
*)
function hasFolder(const aPath: string): boolean;
(**
* Fills aList with the system drives.
*)
procedure listDrives(aList: TStrings);
(**
* If aPath ends with an asterisk then fills aList with the names of the files located in aPath.
* Returns true if aPath was 'asterisk-ifyed'.
*)
function listAsteriskPath(const aPath: string; aList: TStrings; someExts: TStrings = nil): boolean;
(**
* Lets the shell open a file
*)
function shellOpen(const aFilename: string): boolean;
(**
* Returns true if anExeName can be spawn without its full path.
*)
function exeInSysPath(anExeName: string): boolean;
(**
* Returns the full to anExeName. Works if exeInSysPath().
*)
function exeFullName(anExeName: string): string;
(**
* Clears then fills aList with aProcess output stream.
*)
procedure processOutputToStrings(aProcess: TProcess; var aList: TStringList);
(**
* Copy available process output to a stream.
*)
procedure processOutputToStream(aProcess: TProcess; output: TMemoryStream);
(**
* Terminates and frees aProcess.
*)
procedure killProcess(var aProcess: TAsyncProcess);
procedure killProcess(var aProcess: TCheckedAsyncProcess);
(**
* Ensures that the in/out process pipes are not redirected, that it has a console, if it waits on exit.
*)
procedure ensureNoPipeIfWait(aProcess: TProcess);
(**
* Returns true if Exename is running under Windows or Linux
*)
function AppIsRunning(const ExeName: string):Boolean;
(**
* Returns the length of the line ending in aFilename;
*)
function getLineEndingLength(const aFilename: string): byte;
function getSysLineEndLen: byte;
(**
* Returns the common folder of the file names stored in aList
*)
function commonFolder(const someFiles: TStringList): string;
implementation
procedure TCEPersistentShortcut.assign(aValue: TPersistent);
var
src: TCEPersistentShortcut;
begin
if aValue is TCEPersistentShortcut then
begin
src := TCEPersistentShortcut(Avalue);
fActionName := src.fActionName;
fShortcut := src.fShortcut;
end
else inherited;
end;
{$IFDEF LINUX}
constructor TCheckedAsyncProcess.Create(aOwner: TComponent);
begin
inherited;
fTimer := TIdleTimer.Create(self);
fTimer.Enabled := false;
fTimer.Interval := 50;
fTimer.AutoEnabled := false;
end;
procedure TCheckedAsyncProcess.Execute;
begin
if OnTerminate <> nil then
fTimer.Enabled :=true;
fTimer.OnTimer := @checkTerminated;
inherited;
end;
procedure TCheckedAsyncProcess.checkTerminated(sender: TObject);
begin
if Running then exit;
if OnTerminate = nil then exit;
fTimer.Enabled:=false;
OnTerminate(Self);
end;
{$ENDIF}
procedure TProcessEx.Assign(aValue: TPersistent);
var
src: TProcess;
begin
if aValue is TProcess then
begin
src := TProcess(aValue);
PipeBufferSize := src.PipeBufferSize;
Active := src.Active;
Executable := src.Executable;
Parameters := src.Parameters;
ConsoleTitle := src.ConsoleTitle;
CurrentDirectory := src.CurrentDirectory;
Desktop := src.Desktop;
Environment := src.Environment;
Options := src.Options;
Priority := src.Priority;
StartupOptions := src.StartupOptions;
ShowWindow := src.ShowWindow;
WindowColumns := src.WindowColumns;
WindowHeight := src.WindowHeight;
WindowLeft := src.WindowLeft;
WindowRows := src.WindowRows;
WindowTop := src.WindowTop;
WindowWidth := src.WindowWidth;
FillAttribute := src.FillAttribute;
XTermProgram := src.XTermProgram;
end
else inherited;
end;
procedure saveCompToTxtFile(const aComp: TComponent; const aFilename: string);
var
str1, str2: TMemoryStream;
begin
str1 := TMemoryStream.Create;
str2 := TMemoryStream.Create;
try
str1.WriteComponent(aComp);
str1.Position := 0;
ObjectBinaryToText(str1,str2);
ForceDirectories(ExtractFilePath(aFilename));
str2.SaveToFile(aFilename);
finally
str1.Free;
str2.Free;
end;
end;
procedure loadCompFromTxtFile(const aComp: TComponent; const aFilename: string;
aPropNotFoundHandler: TPropertyNotFoundEvent = nil; anErrorHandler: TReaderError = nil);
var
str1, str2: TMemoryStream;
rdr: TReader;
begin
str1 := TMemoryStream.Create;
str2 := TMemoryStream.Create;
try
str1.LoadFromFile(aFilename);
str1.Position := 0;
ObjectTextToBinary(str1,str2);
str2.Position := 0;
try
rdr := TReader.Create(str2, 4096);
try
rdr.OnPropertyNotFound := aPropNotFoundHandler;
rdr.OnError := anErrorHandler;
rdr.ReadRootComponent(aComp);
finally
rdr.Free;
end;
except
end;
finally
str1.Free;
str2.Free;
end;
end;
function expandFilenameEx(const aBasePath, aFilename: string): string;
var
curr: string;
begin
curr := '';
getDir(0, curr);
try
if curr <> aBasePath then
chDir(aBasePath);
result := expandFileName(aFilename);
finally
chDir(curr);
end;
end;
function patchPlateformPath(const aPath: string): string;
function patchProc(const src: string; const invalid: char): string;
var
i: Integer;
dir: string;
begin
dir := ExtractFileDrive(src);
if length(dir) > 0 then
result := src[length(dir)+1..length(src)]
else
result := src;
i := pos(invalid, result);
if i <> 0 then
begin
repeat
result[i] := directorySeparator;
i := pos(invalid,result);
until
i = 0;
end;
result := dir + result;
end;
begin
result := aPath;
{$IFDEF MSWINDOWS}
result := patchProc(result, '/');
{$ENDIF}
{$IFDEF UNIX}
result := patchProc(result, '\');
{$ENDIF}
{$IFDEF DARWIN}
result := patchProc(result, '\');
{$ENDIF}
end;
procedure patchPlateformPaths(const sPaths: TStrings);
var
i: Integer;
str: string;
begin
for i:= 0 to sPaths.Count-1 do
begin
str := sPaths.Strings[i];
sPaths.Strings[i] := patchPlateformPath(str);
end;
end;
function patchPlateformExt(const aFilename: string): string;
var
ext, newext: string;
begin
ext := extractFileExt(aFilename);
newext := '';
{$IFDEF MSWINDOWS}
case ext of
'.so': newext := '.dll';
'.dylib': newext := '.dll';
'.a': newext := '.lib';
'.o': newext := '.obj';
else newext := ext;
end;
{$ENDIF}
{$IFDEF LINUX}
case ext of
'.dll': newext := '.so';
'.dylib': newext := '.so';
'.lib': newext := '.a';
'.obj': newext := '.o';
'.exe': newext := '';
else newext := ext;
end;
{$ENDIF}
{$IFDEF DARWIN}
case ext of
'.dll': newext := '.dylib';
'.so': newext := '.dylib';
'.lib': newext := '.a';
'.obj': newext := '.o';
'.exe': newext := '';
else newext := ext;
end;
{$ENDIF}
result := ChangeFileExt(aFilename, newext);
end;
function stripFileExt(const aFilename: string): string;
begin
if Pos('.', aFilename) > 1 then
exit(ChangeFileExt(aFilename, ''))
else
exit(aFilename);
end;
function dlgOkCancel(const aMsg: string): TModalResult;
const
Btns = [mbOK,mbCancel];
begin
exit( MessageDlg('Coedit', aMsg, mtConfirmation, Btns, ''));
end;
function dlgOkInfo(const aMsg: string): TModalResult;
const
Btns = [mbOK];
begin
exit( MessageDlg('Coedit', aMsg, mtInformation, Btns, ''));
end;
function dlgOkError(const aMsg: string): TModalResult;
const
Btns = [mbOK];
begin
exit( MessageDlg('Coedit', aMsg, mtError, Btns, ''));
end;
function uniqueObjStr(const aObject: Tobject): string;
begin
{$HINTS OFF}{$WARNINGS OFF}
exit( format('%.8X',[NativeUint(aObject)]));
{$HINTS ON}{$WARNINGS ON}
end;
function shortenPath(const aPath: string; charThresh: Word = 60): string;
var
i: NativeInt;
sepCnt: NativeInt;
drv: string;
pth1: string;
begin
sepCnt := 0;
if length(aPath) <= charThresh then
exit(aPath);
drv := extractFileDrive(aPath);
i := length(aPath);
while(i <> length(drv)+1) do
begin
Inc(sepCnt, Byte(aPath[i] = directorySeparator));
if sepCnt = 2 then
break;
Dec(i);
end;
pth1 := aPath[i..length(aPath)];
exit( format('%s%s...%s',[drv,directorySeparator,pth1]) );
end;
function getUserDocPath: string;
{$IFDEF WINDOWS}
var
PIDL : PItemIDList;
Folder : array[0..MAX_PATH] of Char;
const
CSIDL_APPDATA = $001A;
{$ENDIF}
begin
{$IFDEF WINDOWS}
PIDL := nil;
SHGetSpecialFolderLocation(0, CSIDL_APPDATA, PIDL);
SHGetPathFromIDList(PIDL, Folder);
result := Folder;
{$ENDIF}
{$IFDEF UNIX}
result := ExpandFileName('~/');
{$ENDIF}
{$IFDEF DARWIN}
raise Exception.Create('darwin: getUserDocPath() has to be implemented');
{$ENDIF}
result += directorySeparator;
end;
function getCoeditDocPath: string;
begin
result := getUserDocPath + 'Coedit' + directorySeparator;
end;
function isFolder(sr: TSearchRec): boolean;
begin
result := (sr.Name <> '.') and (sr.Name <> '..' ) and (sr.Name <> '' ) and
(sr.Attr and faDirectory = faDirectory);
end;
procedure listFiles(aList: TStrings; const aPath: string; recursive: boolean = false);
var
sr: TSearchrec;
procedure tryAdd;
begin
if sr.Attr and faDirectory <> faDirectory then
aList.Add(aPath+ directorySeparator + sr.Name);
end;
begin
if findFirst(aPath + directorySeparator + '*', faAnyFile, sr) = 0 then
try
repeat
tryAdd;
if recursive then if isFolder(sr) then
listFiles(aList, aPath + directorySeparator + sr.Name, recursive);
until
findNext(sr) <> 0;
finally
sysutils.FindClose(sr);
end;
end;
procedure listFolders(aList: TStrings; const aPath: string);
var
sr: TSearchrec;
begin
if findFirst(aPath + '*', faAnyFile, sr) = 0 then
try
repeat if isFolder(sr) then
aList.Add(aPath + sr.Name);
until findNext(sr) <> 0;
finally
sysutils.FindClose(sr);
end;
end;
function hasFolder(const aPath: string): boolean;
var
sr: TSearchrec;
res: boolean;
begin
res := false;
if findFirst(aPath + directorySeparator + '*', faDirectory, sr) = 0 then
try
repeat if isFolder(sr) then
begin
res := true;
break;
end;
until findNext(sr) <> 0;
finally
sysutils.FindClose(sr);
end;
result := res;
end;
function listAsteriskPath(const aPath: string; aList: TStrings; someExts: TStrings = nil): boolean;
var
pth, ext, fname: string;
files: TStringList;
begin
result := false;
if aPath = '' then
exit;
//
if aPath[length(aPath)] = '*' then
begin
pth := aPath[1..length(aPath)-1];
if pth[length(pth)] in ['/', '\'] then
pth := pth[1..length(pth)-1];
if not directoryExists(pth) then exit(false);
//
files := TStringList.Create;
try
listFiles(files, pth, true);
for fname in files do
begin
if someExts = nil then
aList.Add(fname)
else
begin
ext := extractFileExt(fname);
if someExts.IndexOf(ext) <> -1 then
aList.Add(fname);
end;
end;
finally
files.Free;
end;
exit(true);
end;
exit(false);
end;
procedure listDrives(aList: TStrings);
{$IFDEF WINDOWS}
var
drv: char;
ltr: string;
{$ENDIF}
begin
{$IFDEF WINDOWS}
for drv := 'A' to 'Z' do
begin
ltr := drv + ':\';
case GetDriveType(PChar(ltr)) of
DRIVE_REMOVABLE,
DRIVE_FIXED,
DRIVE_REMOTE: aList.Add(ltr);
end;
end;
{$ENDIF}
{$IFDEF LINUX}
aList.Add('//');
{$ENDIF}
{$IFDEF DARWIN}
// tobe checked
// aList.Add('//');
raise Exception.Create('darwin: listDrives() has to be implemented');
{$ENDIF}
end;
function shellOpen(const aFilename: string): boolean;
begin
{$IFDEF WINDOWS}
result := ShellExecute(0, 'OPEN', PChar(aFilename), nil, nil, SW_SHOW) > 32;
{$ENDIF}
{$IFDEF LINUX}
with TProcess.Create(nil) do
try
Executable := 'xdg-open';
Parameters.Add(aFilename);
Execute;
finally
result := true;
Free;
end;
{$ENDIF}
{$IFDEF DARWIN}
with TProcess.Create(nil) do
try
Executable := 'open';
Parameters.Add(aFilename);
Execute;
finally
result := true;
Free;
end;
{$ENDIF}
end;
function exeInSysPath(anExeName: string): boolean;
begin
exit(exeFullName(anExeName) <> '');
end;
function exeFullName(anExeName: string): string;
var
ext: string;
env: string;
begin
ext := extractFileExt(anExeName);
if ext <> exeExt then
anExeName += exeExt;
if FileExists(anExeName) then
exit(anExeName)
else
begin
env := sysutils.GetEnvironmentVariable('PATH');
if Application <> nil then
env += PathSeparator + ExtractFileDir(ExtractFilePath(application.ExeName));
exit(ExeSearch(anExeName, env));
end;
end;
procedure processOutputToStrings(aProcess: TProcess; var aList: TStringList);
var
str: TMemoryStream;
sum: Integer;
cnt: Integer;
buffSz: Integer;
begin
if not (poUsePipes in aProcess.Options) then
exit;
//
sum := 0;
str := TMemoryStream.Create;
try
buffSz := aProcess.PipeBufferSize;
// temp fix: messages are cut if the TAsyncProcess version is used on simple TProcess.
if aProcess is TAsyncProcess then begin
while aProcess.Output.NumBytesAvailable <> 0 do begin
str.SetSize(sum + buffSz);
cnt := aProcess.Output.Read((str.Memory + sum)^, buffSz);
sum += cnt;
end;
end else begin
repeat
str.SetSize(sum + buffSz);
cnt := aProcess.Output.Read((str.Memory + sum)^, buffSz);
sum += cnt;
until
cnt = 0;
end;
str.Size := sum;
aList.LoadFromStream(str);
finally
str.Free;
end;
end;
procedure processOutputToStream(aProcess: TProcess; output: TMemoryStream);
var
sum, cnt: Integer;
const
buffSz = 2048;
begin
if not (poUsePipes in aProcess.Options) then
exit;
//
sum := output.Size;
while aProcess.Output.NumBytesAvailable <> 0 do begin
output.SetSize(sum + buffSz);
cnt := aProcess.Output.Read((output.Memory + sum)^, buffSz);
sum += cnt;
end;
output.SetSize(sum);
output.Position := sum;
end;
procedure killProcess(var aProcess: TAsyncProcess);
begin
if aProcess = nil then
exit;
if aProcess.Running then
aProcess.Terminate(0);
aProcess.Free;
aProcess := nil;
end;
procedure killProcess(var aProcess: TCheckedAsyncProcess);
begin
if aProcess = nil then
exit;
if aProcess.Running then
aProcess.Terminate(0);
aProcess.Free;
aProcess := nil;
end;
procedure ensureNoPipeIfWait(aProcess: TProcess);
begin
if not (poWaitonExit in aProcess.Options) then
exit;
//
aProcess.Options := aProcess.Options - [poStderrToOutPut, poUsePipes];
aProcess.Options := aProcess.Options + [poNewConsole];
end;
function getLineEndingLength(const aFilename: string): byte;
var
value: char;
le: string;
begin
value := #0;
le := LineEnding;
result := length(le);
if not fileExists(aFilename) then
exit;
with TMemoryStream.Create do
try
LoadFromFile(aFilename);
while true do
begin
if Position = Size then
exit;
read(value,1);
if value = #10 then
exit(1);
if value = #13 then
exit(2);
end;
finally
Free;
end;
end;
function getSysLineEndLen: byte;
begin
{$IFDEF WINDOWS}
exit(2);
{$ELSE}
exit(1);
{$ENDIF}
end;
function countFolder(aFilename: string): integer;
var
parent: string;
begin
result := 0;
while(true) do begin
parent := ExtractFileDir(aFilename);
if parent = aFilename then exit;
aFilename := parent;
result += 1;
end;
end;
//TODO-cfeature: make it working with relative paths
function commonFolder(const someFiles: TStringList): string;
var
i,j,k: integer;
sink: TStringList;
dir: string;
cnt: integer;
begin
result := '';
if someFiles.Count = 0 then exit;
sink := TStringList.Create;
try
sink.Assign(someFiles);
for i := sink.Count-1 downto 0 do
if (not FileExists(sink.Strings[i])) and (not DirectoryExists(sink.Strings[i])) then
sink.Delete(i);
// folders count
cnt := 256;
for dir in sink do
begin
k := countFolder(dir);
if k < cnt then
cnt := k;
end;
for i := sink.Count-1 downto 0 do
begin
while (countFolder(sink.Strings[i]) <> cnt) do
sink.Strings[i] := ExtractFileDir(sink.Strings[i]);
end;
// common folder
while(true) do
begin
for i := sink.Count-1 downto 0 do
begin
dir := ExtractFileDir(sink.Strings[i]);
j := sink.IndexOf(dir);
if j = -1 then
sink.Strings[i] := dir
else if j <> i then
sink.Delete(i);
end;
if sink.Count = 1 then
break;
end;
result := sink.Strings[0];
finally
sink.free;
end;
end;
{$IFDEF WINDOWS}
function internalAppIsRunning(const ExeName: string): integer;
var
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize := SizeOf(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
Result := 0;
while integer(ContinueLoop) <> 0 do
begin
if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) =
UpperCase(ExeName)) or (UpperCase(FProcessEntry32.szExeFile) =
UpperCase(ExeName))) then
begin
Inc(Result);
// SendMessage(Exit-Message) possible?
end;
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
end;
{$ENDIF}
{$IFDEF LINUX}
function internalAppIsRunning(const ExeName: string): integer;
var
proc: TProcess;
lst: TStringList;
begin
Result := 0;
proc := tprocess.Create(nil);
proc.Executable := 'ps';
proc.Parameters.Add('-C');
proc.Parameters.Add(ExeName);
proc.Options := [poUsePipes, poWaitonexit];
try
proc.Execute;
lst := TStringList.Create;
try
lst.LoadFromStream(proc.Output);
Result := Pos(ExeName, lst.Text);
finally
lst.Free;
end;
finally
proc.Free;
end;
end;
{$ENDIF}
{$IFDEF DARWIN}
function internalAppIsRunning(const ExeName: string): integer;
var
proc: TProcess;
lst: TStringList;
begin
Result := 0;
proc := tprocess.Create(nil);
proc.Executable := 'pgrep';
proc.Parameters.Add(ExeName);
proc.Options := [poUsePipes, poWaitonexit];
try
proc.Execute;
lst := TStringList.Create;
try
lst.LoadFromStream(proc.Output);
Result := StrToIntDef(Trim(lst.Text), 0);
finally
lst.Free;
end;
finally
proc.Free;
end;
end;
{$ENDIF}
function AppIsRunning(const ExeName: string):Boolean;
begin
Result:= internalAppIsRunning(ExeName) > 0;
end;
initialization
dExtList := TStringList.Create;
dExtList.AddStrings(['.d', '.D', '.di', '.DI', '.Di', '.dI', '.dd', '.DD']);
registerClasses([TCEPersistentShortcut]);
finalization
dExtList.Free;
end.
|
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Program: EMULVT.PAS
Description: Delphi component which does Ansi terminal emulation
Not every escape sequence is implemented, but a large subset.
Author: François PIETTE
Creation: May, 1996
Version: 6.00
EMail: http://www.overbyte.be francois.piette@overbyte.be
Support: Use the mailing list twsocket@elists.org
Follow "support" link at http://www.overbyte.be for subscription.
Legal issues: Copyright (C) 1996-2006 by François PIETTE
Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56
<francois.piette@overbyte.be>
This software is provided 'as-is', without any express or
implied warranty. In no event will the author be held liable
for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it
and redistribute it freely, subject to the following
restrictions:
1. The origin of this software must not be misrepresented,
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
4. You must register this software by sending a picture postcard
to the author. Use a nice stamp and mention your name, street
address, EMail address and any comment you like to say.
Updates:
Jul 22, 1997 Some optimization
Adapted to Delphi 3
Sep 05, 1997 Version 2.01
Dec 16, 1997 V2.02 Corrected a bug int the paint routine which caused GDI
resource leak when color was used.
Feb 24, 1998 V2.03 Added AddFKey function
Jul 15, 1998 V2.04 Adapted to Delphi 4 (moved DoKeyBuffer to protected section)
Dec 04, 1998 V2.05 Added 'single char paint' and 'char zoom' features.
Dec 09, 1998 V2.10 Added graphic char drawing using graphic primitives
Added (with permission) scroll back code developed by Steve
Endicott <s_endicott@compuserve.com>
Dec 21, 1998 V2.11 Corrected some screen update problems related to scrollback.
Added fixes from Steve Endicott.
Beautified code.
Mar 14, 1999 V2.12 Added OnKeyDown event.
Corrected a missing band at right of screen when painting.
Aug 15, 1999 V2.13 Moved KeyPress procedure to public section for BCB4 compat.
Aug 20, 1999 V2.14 Added compile time options. Revised for BCB4.
Nov 12, 1999 V2.15 Corrected display attribute error in delete line.
Checked for range in SetLines/GetLine
Aug 09, 2000 V2.16 Wilfried Mestdagh" <wilfried_sonal@compuserve.com> and
Steve Endicott <s_endicott@compuserve.com> corrected a
bug related to scroll back buffer. See WM + SE 09/08/00
tags in code.
Jul 28, 2001 V2.17 Made FCharPos and FLinePos member variables instead of
global to avoid conflict when sevaral components are used
simultaneously. Suggested by Jeroen Cranendonk
<j.p.cranendonk@student.utwente.nl>
Jan 03, 2002 V2.19 Don't adjust scroll bar if not visible
Make properties with TopMargin, LeftMargin, RightMargin,
BottomMargin.
Jan 10, 2002 V2.19 Fixed SetLineHeight to fill FLinePos up to last item.
May 31, 2004 V2.20 Used ICSDEFS.INC
Jan 10, 2005 V2.21 Fixed TCustomEmulVT.SetCaret so that caret is updated
only when component has the focus. Thanks to Xie, Qi-Ming
<xieqm@axp1.csie.ncu.edu.tw> for finding an easy test case.
Jan 13, 2005 V2.22 Replaced symbol "Debug" by "DEBUG_OUTPUT"
Mar 26, 2006 V2.23 Added key #$1C (Enter key) in all 3 FKeys tables so that
using the enter key is the same as sending CRLF.
Mar 26, 2006 V6.00 New version 6 started from V5
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
unit OverbyteIcsEmulVT;
{$B-} { Enable partial boolean evaluation }
{$T-} { Untyped pointers }
{$X+} { Enable extended syntax }
{$I OverbyteIcsDefs.inc}
{$IFDEF DELPHI6_UP}
{$WARN SYMBOL_PLATFORM OFF}
{$WARN SYMBOL_LIBRARY OFF}
{$WARN SYMBOL_DEPRECATED OFF}
{$ENDIF}
{$IFNDEF VER80} { Not for Delphi 1 }
{$H+} { Use long strings }
{$J+} { Allow typed constant to be modified }
{$ENDIF}
{$IFDEF BCB3_UP}
{$ObjExportAll On}
{$ENDIF}
interface
{$DEFINE SINGLE_CHAR_PAINT}
{$DEFINE CHAR_ZOOM}
uses
Messages,
{$IFDEF USEWINDOWS}
Windows,
{$ELSE}
WinTypes, WinProcs,
{$ENDIF}
SysUtils, Classes, Graphics, Controls, Forms, StdCtrls, ClipBrd;
const
EmulVTVersion = 222;
CopyRight : String = ' TEmulVT (c) 1996-2006 F. Piette V2.22 ';
MAX_ROW = 50;
MAX_COL = 160;
NumPaletteEntries = 16;
type
TBackColors = (vtsBlack, vtsRed, vtsGreen, vtsYellow,
vtsBlue, vtsMagenta, vtsCyan, vtsWhite);
TScreenOption = (vtoBackColor, vtoCopyBackOnClear);
TScreenOptions = set of TScreenOption;
TXlatTable = array [0..255] of char;
PXlatTable = ^TXlatTable;
TFuncKeyValue = String[50];
PFuncKeyValue = ^TFuncKeyValue;
TFuncKey = record
ScanCode : Char;
Shift : TShiftState;
Ext : Boolean;
Value : TFuncKeyValue;
end;
TFuncKeysTable = array [0..63] of TFuncKey;
PFuncKeysTable = ^TFuncKeysTable;
TKeyBufferEvent = procedure (Sender : TObject; Buffer : PChar; Len : Integer) of object;
TKeyDownEvent = procedure (Sender : TObject;
var VirtKey : Integer;
var Shift : TShiftState;
var ShiftLock : Boolean;
var ScanCode : Char;
var Ext : Boolean) of object;
type
{ TLine is an object used to hold one line of text on screen }
TLine = class(TObject)
public
Txt : array [0..MAX_COL] of Char;
Att : array [0..MAX_COL] of Byte;
constructor Create;
procedure Clear(Attr : Byte);
end;
TLineArray = array [0..16382] of TLine;
PLineArray = ^TLineArray;
{ TScreen is an object to hold an entire screen of line and handle }
{ Ansi escape sequences to update this virtual screen }
TScreen = class(TObject)
public
FLines : PLineArray;
FRow : Integer;
FCol : Integer;
FRowSaved : Integer;
FColSaved : Integer;
FScrollRowTop : Integer;
FScrollRowBottom : Integer;
FAttribute : Byte;
FForceHighBit : Boolean;
FReverseVideo : Boolean;
FUnderLine : Boolean;
FRowCount : Integer;
FColCount : Integer;
FBackRowCount : Integer;
FBackEndRow : Integer;
FBackColor : TBackColors;
FOptions : TScreenOptions;
FEscBuffer : String[80];
FEscFlag : Boolean;
Focused : Boolean;
FAutoLF : Boolean;
FAutoCR : Boolean;
FAutoWrap : Boolean;
FCursorOff : Boolean;
FCKeyMode : Boolean;
FNoXlat : Boolean;
FNoXlatInitial : Boolean;
FCntLiteral : Integer;
FCarbonMode : Boolean;
FXlatInputTable : PXlatTable;
FXlatOutputTable : PXlatTable;
FCharSetG0 : Char;
FCharSetG1 : Char;
FCharSetG2 : Char;
FCharSetG3 : Char;
FAllInvalid : Boolean;
FInvRect : TRect;
FOnCursorVisible : TNotifyEvent;
constructor Create;
destructor Destroy; override;
procedure AdjustFLines(NewCount : Integer);
procedure CopyScreenToBack;
procedure SetRowCount(NewCount : Integer);
procedure SetBackRowCount(NewCount : Integer);
procedure InvRect(nRow, nCol : Integer);
procedure InvClear;
procedure SetLines(I : Integer; Value : TLine);
function GetLines(I : Integer) : TLine;
procedure WriteChar(Ch : Char);
procedure WriteStr(Str : String);
function ReadStr : String;
procedure GotoXY(X, Y : Integer);
procedure WriteLiteralChar(Ch : Char);
procedure ProcessEscape(EscCmd : Char);
procedure SetAttr(Att : Char);
procedure CursorRight;
procedure CursorLeft;
procedure CursorDown;
procedure CursorUp;
procedure CarriageReturn;
procedure ScrollUp;
procedure ScrollDown;
procedure ClearScreen;
procedure BackSpace;
procedure Eol;
procedure Eop;
procedure ProcessESC_D; { Index }
procedure ProcessESC_M; { Reverse index }
procedure ProcessESC_E; { Next line }
procedure ProcessCSI_u; { Restore Cursor }
procedure ProcessCSI_I; { Select IBM char set }
procedure ProcessCSI_J; { Clear the screen }
procedure ProcessCSI_K; { Erase to End of Line }
procedure ProcessCSI_L; { Insert Line }
procedure ProcessCSI_M; { Delete Line }
procedure ProcessCSI_m_lc; { Select Attributes }
procedure ProcessCSI_n_lc; { Cursor position report }
procedure ProcessCSI_at; { Insert character }
procedure ProcessCSI_r_lc; { Scrolling margins }
procedure ProcessCSI_s_lc; { Save cursor location }
procedure ProcessCSI_u_lc; { Restore cursor location }
procedure ProcessCSI_7; { Save cursor location }
procedure ProcessCSI_8; { Restore cursor location }
procedure ProcessCSI_H; { Set Cursor Position }
procedure ProcessCSI_h_lc; { Terminal mode set }
procedure ProcessCSI_l_lc; { Terminal mode reset }
procedure ProcessCSI_A; { Cursor Up }
procedure ProcessCSI_B; { Cursor Down }
procedure ProcessCSI_C; { Cursor Right }
procedure ProcessCSI_D; { Cursor Left }
procedure ProcessCSI_P; { Delete Character }
procedure ProcessCSI_S; { Scroll up }
procedure ProcessCSI_T; { Scroll down }
procedure process_charset_G0(EscCmd : Char);{ G0 character set }
procedure process_charset_G1(EscCmd : Char);{ G1 character set }
procedure process_charset_G2(EscCmd : Char);{ G2 character set }
procedure process_charset_G3(EscCmd : Char);{ G3 character set }
procedure UnimplementedEscape(EscCmd : Char);
procedure InvalidEscape(EscCmd : Char);
function GetEscapeParam(From : Integer; var Value : Integer) : Integer;
property OnCursorVisible : TNotifyEvent read FonCursorVisible
write FOnCursorVisible;
property Lines[I : Integer] : TLine read GetLines write SetLines;
end;
{ TCustomEmulVT is an visual component wich does the actual display }
{ of a TScreen object wich is the virtual screen }
{ No property is published. See TEmulVT class }
TCustomEmulVT = class(TCustomControl)
private
FCharPos : array [0..MAX_COL + 1] of integer;
FLinePos : array [0..MAX_ROW + 1] of integer;
FFileHandle : TextFile;
FCursorVisible : Boolean;
FCaretShown : Boolean;
FCaretCreated : Boolean;
FLineHeight : Integer;
FLineZoom : Single;
FCharWidth : Integer;
FCharZoom : Single;
FGraphicDraw : Boolean;
FInternalLeading : Integer;
FBorderStyle : TBorderStyle;
FBorderWidth : Integer;
FAutoRepaint : Boolean;
FFont : TFont;
FVScrollBar : TScrollBar;
FTopLine : Integer;
FLocalEcho : Boolean;
FOnKeyBuffer : TKeyBufferEvent;
FOnKeyDown : TKeyDownEvent;
FFKeys : Integer;
FMonoChrome : Boolean;
FLog : Boolean;
FAppOnMessage : TMessageEvent;
FFlagCirconflexe : Boolean;
FFlagTrema : Boolean;
FSelectRect : TRect;
FTopMargin : Integer;
FLeftMargin : Integer;
FRightMargin : Integer;
FBottomMargin : Integer;
FPal : HPalette;
FPaletteEntries : array[0..NumPaletteEntries - 1] of TPaletteEntry;
FMarginColor : Integer;
procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS;
procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS;
procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN;
procedure WMPaletteChanged(var Message : TMessage); message WM_PALETTECHANGED;
procedure VScrollBarScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer);
procedure SetCaret;
procedure AdjustScrollBar;
function ProcessFKeys(ScanCode: Char; Shift: TShiftState; Ext: Boolean) : Boolean;
function FindFKeys(ScanCode: Char; Shift: TShiftState;
Ext: Boolean) : PFuncKeyValue;
procedure CursorVisibleEvent(Sender : TObject);
procedure SetFont(Value : TFont);
procedure SetAutoLF(Value : Boolean);
procedure SetAutoCR(Value : Boolean);
procedure SetXlat(Value : Boolean);
procedure SetLog(Value : Boolean);
procedure SetRows(Value : Integer);
procedure SetCols(Value : Integer);
procedure SetBackRows(Value : Integer);
procedure SetTopLine(Value : Integer);
procedure SetBackColor(Value : TBackColors);
procedure SetOptions(Value : TScreenOptions);
procedure SetLineHeight(Value : Integer);
function GetAutoLF : Boolean;
function GetAutoCR : Boolean;
function GetXlat : Boolean;
function GetRows : Integer;
function GetCols : Integer;
function GetBackRows : Integer;
function GetBackColor : TBackColors;
function GetOptions : TScreenOptions;
procedure SetMarginColor(const Value: Integer);
procedure SetLeftMargin(const Value: Integer);
procedure SetBottomMargin(const Value: Integer);
procedure SetRightMargin(const Value: Integer);
procedure SetTopMargin(const Value: Integer);
protected
FScreen : TScreen;
procedure AppMessageHandler(var Msg: TMsg; var Handled: Boolean);
procedure DoKeyBuffer(Buffer : PChar; Len : Integer); virtual;
procedure PaintGraphicChar(DC : HDC;
X, Y : Integer;
rc : PRect;
ch : Char);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ShowCursor;
procedure SetCursor(Row, Col : Integer);
procedure WriteChar(Ch : Char);
procedure WriteStr(Str : String);
procedure WriteBuffer(Buffer : Pointer; Len : Integer);
function ReadStr : String;
procedure CopyHostScreen;
procedure Clear;
procedure UpdateScreen;
function SnapPixelToRow(Y : Integer) : Integer;
function SnapPixelToCol(X : Integer) : Integer;
function PixelToRow(Y : Integer) : Integer;
function PixelToCol(X : Integer) : Integer;
procedure MouseToCell(X, Y: Integer; var ACol, ARow: Longint);
procedure SetLineZoom(newValue : Single);
procedure SetCharWidth(newValue : Integer);
procedure SetCharZoom(newValue : Single);
procedure KeyPress(var Key: Char); override;
property LineZoom : Single read FLineZoom write SetLineZoom;
property CharWidth : Integer read FCharWidth write SetCharWidth;
property CharZoom : Single read FCharZoom write SetCharZoom;
property GraphicDraw : Boolean read FGraphicDraw write FGraphicDraw;
property TopLine : Integer read FTopLine write SetTopLine;
property VScrollBar : TScrollBar read FVScrollBar;
property TopMargin : Integer read FTopMargin write SetTopMargin;
property LeftMargin : Integer read FLeftMargin write SetLeftMargin;
property RightMargin : Integer read FRightMargin write SetRightMargin;
property BottomMargin : Integer read FBottomMargin write SetBottomMargin;
property MarginColor : Integer read FMarginColor write SetMarginColor;
private
procedure PaintOneLine(DC: HDC; Y, Y1 : Integer; const Line : TLine;
nColFrom : Integer; nColTo : Integer; Blank : Boolean);
procedure SetupFont;
property Text : String read ReadStr write WriteStr;
property OnMouseMove;
property OnMouseDown;
property OnMouseUp;
property OnClick;
property OnKeyPress;
property OnKeyBuffer : TKeyBufferEvent read FOnKeyBuffer write FOnKeyBuffer;
property OnKeyDown : TKeyDownEvent read FOnKeyDown write FOnKeyDown;
property Ctl3D;
property Align;
property TabStop;
property TabOrder;
property BorderStyle: TBorderStyle read FBorderStyle write FBorderStyle;
property AutoRepaint : Boolean read FAutoRepaint write FAutoRepaint;
property Font : TFont read FFont write SetFont;
property LocalEcho : Boolean read FLocalEcho write FLocalEcho;
property AutoLF : Boolean read GetAutoLF write SetAutoLF;
property AutoCR : Boolean read GetAutoCR write SetAutoCR;
property Xlat : Boolean read GetXlat write SetXlat;
property MonoChrome : Boolean read FMonoChrome write FMonoChrome;
property Log : Boolean read FLog write SetLog;
property Rows : Integer read GetRows write SetRows;
property Cols : Integer read GetCols write SetCols;
property LineHeight : Integer read FLineHeight write SetLineHeight;
property FKeys : Integer read FFKeys write FFKeys;
property SelectRect : TRect read FSelectRect write FSelectRect;
property BackRows : Integer read GetBackRows write SetBackRows;
property BackColor : TBackColors read GetBackColor write SetBackColor;
property Options : TScreenOptions read GetOptions write SetOptions;
end;
{ Same as TCustomEmulVT, but with published properties }
TEmulVT = class(TCustomEmulVT)
public
property Screen : TScreen read FScreen;
property SelectRect;
property Text;
published
property OnMouseMove;
property OnMouseDown;
property OnMouseUp;
property OnClick;
property OnKeyPress;
property OnKeyDown;
property OnKeyBuffer;
property Ctl3D;
property Align;
property BorderStyle;
property AutoRepaint;
property Font;
property LocalEcho;
property AutoLF;
property AutoCR;
property Xlat;
property MonoChrome;
property Log;
property Rows;
property Cols;
property BackRows;
property BackColor;
property Options;
property LineHeight;
property CharWidth;
property TabStop;
property TabOrder;
property FKeys;
property TopMargin;
property LeftMargin;
property RightMargin;
property BottomMargin;
property MarginColor;
end;
const
F_BLACK = $00;
F_BLUE = $01;
F_GREEN = $02;
F_CYAN = $03;
F_RED = $04;
F_MAGENTA = $05;
F_BROWN = $06;
F_WHITE = $07;
B_BLACK = $00;
B_BLUE = $01;
B_GREEN = $02;
B_CYAN = $03;
B_RED = $04;
B_MAGENTA = $05;
B_BROWN = $06;
B_WHITE = $07;
F_INTENSE = $08;
B_BLINK = $80;
{ Function keys (SCO Console) }
FKeys1 : TFuncKeysTable = (
(ScanCode: #$48; Shift: []; Ext: TRUE ; Value: #$1B + '[A'), { UP }
(ScanCode: #$50; Shift: []; Ext: TRUE ; Value: #$1B + '[B'), { DOWN }
(ScanCode: #$4D; Shift: []; Ext: TRUE ; Value: #$1B + '[C'), { RIGHT }
(ScanCode: #$4B; Shift: []; Ext: TRUE ; Value: #$1B + '[D'), { LEFT }
(ScanCode: #$49; Shift: []; Ext: TRUE ; Value: #$1B + '[I'), { PREV }
(ScanCode: #$51; Shift: []; Ext: TRUE ; Value: #$1B + '[G'), { NEXT }
(ScanCode: #$47; Shift: []; Ext: TRUE ; Value: #$1B + '[H'), { HOME }
(ScanCode: #$4F; Shift: []; Ext: TRUE ; Value: #$1B + '[F'), { END }
(ScanCode: #$52; Shift: []; Ext: TRUE ; Value: #$1B + '[L'), { INS }
(ScanCode: #$0F; Shift: []; Ext: FALSE; Value: #$1B + '[Z'), { RTAB }
(ScanCode: #$53; Shift: []; Ext: TRUE ; Value: #$7F ), { DEL }
(ScanCode: #$3B; Shift: []; Ext: FALSE; Value: #$1B + '[M'), { F1 }
(ScanCode: #$3C; Shift: []; Ext: FALSE; Value: #$1B + '[N'),
(ScanCode: #$3D; Shift: []; Ext: FALSE; Value: #$1B + '[O'),
(ScanCode: #$3E; Shift: []; Ext: FALSE; Value: #$1B + '[P'),
(ScanCode: #$3F; Shift: []; Ext: FALSE; Value: #$1B + '[Q'),
(ScanCode: #$40; Shift: []; Ext: FALSE; Value: #$1B + '[R'),
(ScanCode: #$41; Shift: []; Ext: FALSE; Value: #$1B + '[S'),
(ScanCode: #$42; Shift: []; Ext: FALSE; Value: #$1B + '[T'),
(ScanCode: #$43; Shift: []; Ext: FALSE; Value: #$1B + '[U'),
(ScanCode: #$44; Shift: []; Ext: FALSE; Value: #$1B + '[V'), { F10 }
(ScanCode: #$85; Shift: []; Ext: FALSE; Value: #$1B + '[W'), { F11 }
(ScanCode: #$86; Shift: []; Ext: FALSE; Value: #$1B + '[X'), { F12 }
(ScanCode: #$3B; Shift: [ssShift]; Ext: FALSE; Value: #$1B + '[V'),{ SF1 should be 'Y' }
(ScanCode: #$3C; Shift: [ssShift]; Ext: FALSE; Value: #$1B + '[Z'),
(ScanCode: #$3D; Shift: [ssShift]; Ext: FALSE; Value: #$1B + '[a'),
(ScanCode: #$3E; Shift: [ssShift]; Ext: FALSE; Value: #$1B + '[b'),
(ScanCode: #$3F; Shift: [ssShift]; Ext: FALSE; Value: #$1B + '[c'),
(ScanCode: #$40; Shift: [ssShift]; Ext: FALSE; Value: #$1B + '[d'),
(ScanCode: #$41; Shift: [ssShift]; Ext: FALSE; Value: #$1B + '[e'),
(ScanCode: #$42; Shift: [ssShift]; Ext: FALSE; Value: #$1B + '[f'),
(ScanCode: #$43; Shift: [ssShift]; Ext: FALSE; Value: #$1B + '[g'),
(ScanCode: #$44; Shift: [ssShift]; Ext: FALSE; Value: #$1B + '[h'),
(ScanCode: #$85; Shift: [ssShift]; Ext: FALSE; Value: #$1B + '[i'),
(ScanCode: #$86; Shift: [ssShift]; Ext: FALSE; Value: #$1B + '[j'),{ SF10 }
(ScanCode: #$3B; Shift: [ssCtrl]; Ext: FALSE; Value: #$1B + '[k'), { CF1 }
(ScanCode: #$3C; Shift: [ssCtrl]; Ext: FALSE; Value: #$1B + '[l'),
(ScanCode: #$3D; Shift: [ssCtrl]; Ext: FALSE; Value: #$1B + '[m'),
(ScanCode: #$3E; Shift: [ssCtrl]; Ext: FALSE; Value: #$1B + '[n'),
(ScanCode: #$3F; Shift: [ssCtrl]; Ext: FALSE; Value: #$1B + '[o'),
(ScanCode: #$40; Shift: [ssCtrl]; Ext: FALSE; Value: #$1B + '[p'),
(ScanCode: #$41; Shift: [ssCtrl]; Ext: FALSE; Value: #$1B + '[q'),
(ScanCode: #$42; Shift: [ssCtrl]; Ext: FALSE; Value: #$1B + '[r'),
(ScanCode: #$43; Shift: [ssCtrl]; Ext: FALSE; Value: #$1B + '[s'),
(ScanCode: #$44; Shift: [ssCtrl]; Ext: FALSE; Value: #$1B + '[t'),
(ScanCode: #$85; Shift: [ssCtrl]; Ext: FALSE; Value: #$1B + '[u'),
(ScanCode: #$86; Shift: [ssCtrl]; Ext: FALSE; Value: #$1B + '[v'), { CF12 }
(ScanCode: #$1C; Shift: []; Ext: FALSE; Value: #13#10 ), { Enter key }
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' )
);
{ Alternate function keys (ordinary VT keys) }
FKeys2 : TFuncKeysTable = (
(ScanCode: #$48; Shift: []; Ext: TRUE ; Value: #$1B + '[A'), { UP }
(ScanCode: #$50; Shift: []; Ext: TRUE ; Value: #$1B + '[B'), { DOWN }
(ScanCode: #$4D; Shift: []; Ext: TRUE ; Value: #$1B + '[C'), { RIGHT }
(ScanCode: #$4B; Shift: []; Ext: TRUE ; Value: #$1B + '[D'), { LEFT }
(ScanCode: #$49; Shift: []; Ext: TRUE ; Value: #$1B + '[5~'), { PREV }
(ScanCode: #$51; Shift: []; Ext: TRUE ; Value: #$1B + '[6~'), { NEXT }
(ScanCode: #$52; Shift: []; Ext: TRUE ; Value: #$1B + '[2~'), { INSERT }
(ScanCode: #$53; Shift: []; Ext: TRUE ; Value: #$7F ), { DELETE }
(ScanCode: #$3B; Shift: []; Ext: FALSE; Value: #$1B + 'OP'), { F1->PF1 }
(ScanCode: #$3C; Shift: []; Ext: FALSE; Value: #$1B + 'OQ'), { F2->PF2 }
(ScanCode: #$3D; Shift: []; Ext: FALSE; Value: #$1B + 'OR'), { F3->PF3 }
(ScanCode: #$3E; Shift: []; Ext: FALSE; Value: #$1B + 'OS'), { F4->PF4 }
(ScanCode: #$57; Shift: []; Ext: FALSE; Value: #$1B + '[28~'), { F11->Aide }
(ScanCode: #$58; Shift: []; Ext: FALSE; Value: #$1B + '[29~'), { F12->Exécuter }
(ScanCode: #$1C; Shift: []; Ext: FALSE; Value: #13#10 ), { Enter key }
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' )
);
{ A-Series Telnet function keys (ordinary VT100 keys + specials) }
FKeys3 : TFuncKeysTable = (
(ScanCode: #$48; Shift: []; Ext: TRUE ; Value: #$1B + '[A'), { UP }
(ScanCode: #$50; Shift: []; Ext: TRUE ; Value: #$1B + '[B'), { DOWN }
(ScanCode: #$4D; Shift: []; Ext: TRUE ; Value: #$1B + '[C'), { RIGHT }
(ScanCode: #$4B; Shift: []; Ext: TRUE ; Value: #$1B + '[D'), { LEFT }
(ScanCode: #$49; Shift: []; Ext: TRUE ; Value: #$1B + '-'), { PREV }
(ScanCode: #$51; Shift: []; Ext: TRUE ; Value: #$1B + '+'), { NEXT }
(ScanCode: #$47; Shift: []; Ext: TRUE ; Value: #$1B + 'H'), { HOME }
(ScanCode: #$47; Shift: [ssCtrl]; Ext: TRUE ; Value: #$1B + 'C'),{ HOME }
(ScanCode: #$4F; Shift: []; Ext: TRUE ; Value: #$1B + 'R'), { END }
(ScanCode: #$52; Shift: []; Ext: TRUE ; Value: #$1B + 'I'), { INSERT }
(ScanCode: #$53; Shift: []; Ext: TRUE ; Value: #$7F ), { DELETE }
(ScanCode: #$3B; Shift: []; Ext: FALSE; Value: #$1B + 'OP'), { F1->PF1 }
(ScanCode: #$3C; Shift: []; Ext: FALSE; Value: #$1B + 'OQ'), { F2->PF2 }
(ScanCode: #$3D; Shift: []; Ext: FALSE; Value: #$1B + 'OR'), { F3->PF3 }
(ScanCode: #$3E; Shift: []; Ext: FALSE; Value: #$1B + 'OS'), { F4->PF4 }
(ScanCode: #$43; Shift: []; Ext: FALSE; Value: #$1B + 'OP'), { F9 }
(ScanCode: #$44; Shift: []; Ext: FALSE; Value: ''), { F10 }
(ScanCode: #$57; Shift: []; Ext: FALSE; Value: #$1B + 'OQ'), { F11 }
(ScanCode: #$58; Shift: []; Ext: FALSE; Value: #$1B + 'OS'), { F12 }
(ScanCode: #$0F; Shift: []; Ext: FALSE; Value: #$1B + 'Z'), { RTAB }
(ScanCode: #$40; Shift: []; Ext: FALSE; Value: #$1B + 'K'), { F6 }
(ScanCode: #$53; Shift: [ssCtrl]; Ext: TRUE ; Value: #$1B + 'D'), { CDEL }
(ScanCode: #$52; Shift: [ssCtrl]; Ext: TRUE ; Value: #$1B + 'L'), { CINS }
(ScanCode: #$1C; Shift: []; Ext: FALSE; Value: #13#10 ), { Enter key }
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' ),
(ScanCode: #$00; Shift: []; Ext: FALSE; Value: '' )
);
{ Ethernet to screen }
ibm_iso8859_1_G0 : TXlatTable = (
#$00, #$01, #$02, #$03, #$04, #$05, #$06, #$07, { 00 - 07 }
#$08, #$09, #$0A, #$0B, #$0C, #$0D, #$0E, #$0F, { 08 - 0F }
#$10, #$11, #$12, #$13, #$14, #$15, #$16, #$17, { 10 - 17 }
#$18, #$19, #$1A, #$1B, #$1C, #$1D, #$1E, #$1F, { 18 - 1F }
#$20, #$21, #$22, #$23, #$24, #$25, #$26, #$27, { 20 - 27 }
#$28, #$29, #$2A, #$2B, #$2C, #$2D, #$2E, #$2F, { 28 - 2F }
#$30, #$31, #$32, #$33, #$34, #$35, #$36, #$37, { 30 - 37 }
#$38, #$39, #$3A, #$3B, #$3C, #$3D, #$3E, #$3F, { 38 - 3F }
#$40, #$41, #$42, #$43, #$44, #$45, #$46, #$47, { 40 - 47 }
#$48, #$49, #$4A, #$4B, #$4C, #$4D, #$4E, #$4F, { 48 - 4F }
#$50, #$51, #$52, #$53, #$54, #$55, #$56, #$57, { 50 - 57 }
#$58, #$59, #$5A, #$5B, #$5C, #$5D, #$5E, #$5F, { 58 - 5F }
#$60, #$61, #$62, #$63, #$64, #$65, #$66, #$67, { 60 - 67 }
#$68, #$69, #$6A, #$6B, #$6C, #$6D, #$6E, #$6F, { 68 - 6F }
#$70, #$71, #$72, #$73, #$74, #$75, #$76, #$77, { 70 - 77 }
#$78, #$79, #$7A, #$7B, #$7C, #$7D, #$7E, #$7F, { 78 - 7F }
#$20, #$20, #$20, #$20, #$20, #$20, #$20, #$20, { 80 - 87 }
#$20, #$20, #$20, #$20, #$20, #$20, #$20, #$20, { 88 - 8F }
#$20, #$20, #$20, #$20, #$20, #$20, #$20, #$20, { 90 - 97 }
#$20, #$20, #$20, #$20, #$20, #$20, #$20, #$20, { 98 - 9F }
#$B1, #$AD, #$9B, #$9C, #$0F, #$9D, #$B3, #$15, { A0 - A7 }
#$20, #$43, #$A6, #$AE, #$AA, #$C4, #$52, #$C4, { A8 - AF }
#$F8, #$F1, #$FD, #$20, #$27, #$E6, #$14, #$FA, { B0 - B7 }
#$2C, #$20, #$A7, #$AF, #$AC, #$AB, #$20, #$A8, { B8 - BF }
#$41, #$41, #$41, #$41, #$8E, #$8F, #$92, #$80, { C0 - C7 }
#$45, #$45, #$45, #$45, #$45, #$49, #$49, #$49, { C8 - CF }
#$44, #$A5, #$4F, #$4F, #$4F, #$4F, #$4F, #$78, { D0 - D7 }
#$ED, #$55, #$55, #$55, #$55, #$59, #$70, #$E1, { D8 - DF }
#$85, #$A0, #$83, #$61, #$84, #$86, #$91, #$87, { E0 - E7 }
#$8A, #$82, #$88, #$89, #$8D, #$A1, #$8C, #$49, { E8 - EF }
#$64, #$A4, #$95, #$A2, #$93, #$6F, #$94, #$F6, { F0 - F7 }
#$ED, #$97, #$A3, #$96, #$9A, #$79, #$70, #$98); { F8 - FF }
{ Ethernet to screen }
ibm_iso8859_1_G1 : TXlatTable = (
#$00, #$01, #$02, #$03, #$04, #$05, #$06, #$07, { 00 - 07 }
#$08, #$09, #$0A, #$0B, #$0C, #$0D, #$0E, #$0F, { 08 - 0F }
#$10, #$11, #$12, #$13, #$14, #$15, #$16, #$17, { 10 - 17 }
#$18, #$19, #$1A, #$1B, #$1C, #$1D, #$1E, #$1F, { 18 - 1F }
#$20, #$21, #$22, #$23, #$24, #$25, #$26, #$27, { 20 - 27 }
#$28, #$29, #$2A, #$2B, #$2C, #$2D, #$2E, #$2F, { 28 - 2F }
#$30, #$31, #$32, #$33, #$34, #$35, #$36, #$37, { 30 - 37 }
#$38, #$39, #$3A, #$3B, #$3C, #$3D, #$3E, #$3F, { 38 - 3F }
#$40, #$41, #$42, #$43, #$44, #$45, #$46, #$47, { 40 - 47 }
#$48, #$49, #$4A, #$4B, #$4C, #$4D, #$4E, #$4F, { 48 - 4F }
#$50, #$51, #$52, #$53, #$54, #$55, #$56, #$57, { 50 - 57 }
#$58, #$59, #$5A, #$5B, #$5C, #$5D, #$5E, #$5F, { 58 - 5F }
#$60, #$61, #$62, #$63, #$64, #$65, #$66, #$67, { 60 - 67 }
#$68, #$69, #$D9, #$BF, #$DA, #$C0, #$C5, #$6F, { 68 - 6F }
#$70, #$C4, #$72, #$73, #$C3, #$B4, #$C1, #$C2, { 70 - 77 }
#$B3, #$79, #$7A, #$7B, #$7C, #$7D, #$7E, #$7F, { 78 - 7F }
#$20, #$20, #$20, #$20, #$20, #$20, #$20, #$20, { 80 - 87 }
#$20, #$20, #$20, #$20, #$20, #$20, #$20, #$20, { 88 - 8F }
#$20, #$20, #$20, #$20, #$20, #$20, #$20, #$20, { 90 - 97 }
#$20, #$20, #$20, #$20, #$20, #$20, #$20, #$20, { 98 - 9F }
#$B1, #$AD, #$9B, #$9C, #$0F, #$9D, #$B3, #$15, { A0 - A7 }
#$20, #$43, #$A6, #$AE, #$AA, #$C4, #$52, #$C4, { A8 - AF }
#$F8, #$F1, #$FD, #$20, #$27, #$E6, #$14, #$FA, { B0 - B7 }
#$2C, #$20, #$A7, #$AF, #$AC, #$AB, #$20, #$A8, { B8 - BF }
#$41, #$41, #$41, #$41, #$8E, #$8F, #$92, #$80, { C0 - C7 }
#$45, #$45, #$45, #$45, #$45, #$49, #$49, #$49, { C8 - CF }
#$44, #$A5, #$4F, #$4F, #$4F, #$4F, #$4F, #$78, { D0 - D7 }
#$ED, #$55, #$55, #$55, #$55, #$59, #$70, #$E1, { D8 - DF }
#$85, #$A0, #$83, #$61, #$84, #$86, #$91, #$87, { E0 - E7 }
#$8A, #$82, #$88, #$89, #$8D, #$A1, #$8C, #$49, { E8 - EF }
#$64, #$A4, #$95, #$A2, #$93, #$6F, #$94, #$F6, { F0 - F7 }
#$ED, #$97, #$A3, #$96, #$9A, #$79, #$70, #$98); { F8 - FF }
{ Keyboard to Ethernet }
Output : TXlatTable = (
#$00, #$01, #$02, #$03, #$04, #$05, #$06, #$07, { 00 - 07 }
#$08, #$09, #$0A, #$0B, #$0C, #$0D, #$0E, #$0F, { 08 - 0F }
#$10, #$11, #$12, #$13, #$14, #$15, #$16, #$17, { 10 - 17 }
#$18, #$19, #$1A, #$1B, #$1C, #$1D, #$1E, #$1F, { 18 - 1F }
#$20, #$21, #$22, #$23, #$24, #$25, #$26, #$27, { 20 - 27 }
#$28, #$29, #$2A, #$2B, #$2C, #$2D, #$2E, #$2F, { 28 - 2F }
#$30, #$31, #$32, #$33, #$34, #$35, #$36, #$37, { 30 - 37 }
#$38, #$39, #$3A, #$3B, #$3C, #$3D, #$3E, #$3F, { 38 - 3F }
#$40, #$41, #$42, #$43, #$44, #$45, #$46, #$47, { 40 - 47 }
#$48, #$49, #$4A, #$4B, #$4C, #$4D, #$4E, #$4F, { 48 - 4F }
#$50, #$51, #$52, #$53, #$54, #$55, #$56, #$57, { 50 - 57 }
#$58, #$59, #$5A, #$5B, #$5C, #$5D, #$5E, #$5F, { 58 - 5F }
#$60, #$61, #$62, #$63, #$64, #$65, #$66, #$67, { 60 - 67 }
#$68, #$69, #$6A, #$6B, #$6C, #$6D, #$6E, #$6F, { 68 - 6F }
#$70, #$71, #$72, #$73, #$74, #$75, #$76, #$77, { 70 - 77 }
#$78, #$79, #$7A, #$7B, #$7C, #$7D, #$7E, #$7F, { 78 - 7F }
#$C7, #$FC, #$E9, #$E2, #$E4, #$E0, #$E5, #$E7, { 80 - 87 }
#$EA, #$EB, #$E8, #$EF, #$EE, #$EC, #$C4, #$C5, { 88 - 8F }
#$C9, #$E6, #$C6, #$F4, #$F6, #$F2, #$FB, #$F9, { 90 - 97 }
#$FF, #$F6, #$FC, #$A2, #$A3, #$A5, #$DE, #$20, { 98 - 9F }
#$E1, #$ED, #$F3, #$FA, #$F1, #$D1, #$AA, #$BA, { A0 - A7 }
#$BF, #$20, #$AC, #$BD, #$BC, #$A1, #$AB, #$BB, { A8 - AF }
#$A0, #$A0, #$A0, #$A6, #$A6, #$A6, #$A6, #$AD, { B0 - B7 }
#$2B, #$A6, #$A6, #$2B, #$2B, #$2B, #$2B, #$2B, { B8 - BF }
#$2B, #$AD, #$AD, #$AD, #$A6, #$AD, #$2B, #$A6, { C0 - C7 }
#$2B, #$2B, #$AD, #$AD, #$A6, #$AD, #$2B, #$AD, { C8 - CF }
#$AD, #$AD, #$AD, #$2B, #$2B, #$2B, #$2B, #$2B, { D0 - D7 }
#$2B, #$2B, #$2B, #$A0, #$A0, #$A0, #$A0, #$A0, { D8 - DF }
#$20, #$20, #$20, #$AD, #$20, #$20, #$B5, #$20, { E0 - E7 }
#$20, #$20, #$20, #$20, #$20, #$F8, #$20, #$20, { E8 - EF }
#$A0, #$B1, #$20, #$20, #$20, #$20, #$F7, #$20, { F0 - F7 }
#$B0, #$B0, #$B0, #$20, #$20, #$B2, #$A0, #$20); { F8 - FF }
procedure Register;
procedure FKeysToFile(var FKeys : TFuncKeysTable; FName : String);
procedure FileToFKeys(var FKeys : TFuncKeysTable; FName : String);
function AddFKey(var FKeys : TFuncKeysTable;
ScanCode : Char;
Shift : TShiftState;
Ext : Boolean;
Value : TFuncKeyValue) : Boolean;
implementation
{-$DEFINE DEBUG_OUTPUT} { Add or remove minus sign before dollar sign to }
{ generate code for debug message output }
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure Register;
begin
RegisterComponents('FPiette', [TEmulVT]);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function ShiftStateToString(var State : TShiftState) : String;
begin
Result := '';
if ssShift in State then
Result := Result + 'ssShift ';
if ssAlt in State then
Result := Result + 'ssAlt ';
if ssCtrl in State then
Result := Result + 'ssCtrl ';
if ssLeft in State then
Result := Result + 'ssLeft ';
if ssRight in State then
Result := Result + 'ssRight ';
if ssMiddle in State then
Result := Result + 'ssMiddle ';
if ssDouble in State then
Result := Result + 'ssDouble ';
if Result = '' then
Result := 'ssNormal';
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function StringToShiftState(var S : String) : TShiftState;
begin
Result := [];
if Pos('ssShift', S) <> 0 then
Result := Result + [ssShift];
if Pos('ssAlt', S) <> 0 then
Result := Result + [ssAlt];
if Pos('ssCtrl', S) <> 0 then
Result := Result + [ssCtrl];
if Pos('ssLeft', S) <> 0 then
Result := Result + [ssLeft];
if Pos('ssRight', S) <> 0 then
Result := Result + [ssRight];
if Pos('ssMiddle', S) <> 0 then
Result := Result + [ssMiddle];
if Pos('ssDouble', S) <> 0 then
Result := Result + [ssDouble];
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function xdigit(Ch : char) : integer;
begin
if ch in ['0'..'9'] then
Result := Ord(ch) - ord('0')
else if ch in ['A'..'Z'] then
Result := Ord(ch) - Ord('A') + 10
else if ch in ['a'..'z'] then
Result := Ord(ch) - Ord('a') + 10
else
Result := 0;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function xdigit2(S : PChar) : integer;
begin
Result := 16 * xdigit(S[0]) + xdigit(S[1]);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function FuncKeyValueToString(var S : TFuncKeyValue) : String;
var
I : Integer;
begin
Result := '';
for I := 1 to Length(S) do begin
if (Ord(S[I]) < 32) or (Ord(S[I]) >= 127) or
(S[I] = '''') or (S[I] = '\') then
Result := Result + '\x' + IntToHex(Ord(S[I]), 2)
else
Result := Result + S[I];
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function StringToFuncKeyValue(var S : String) : TFuncKeyValue;
var
I : Integer;
begin
Result := '';
I := 1;
while I <= Length(S) do begin
if (S[I] = '\') and
((I + 3) <= Length(S)) and
(S[I + 1] = 'x') then begin
Result := Result + chr(xdigit2(@S[I + 2]));
I := I + 3;
end
else
Result := Result + S[I];
Inc(I);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function AddFKey(var FKeys : TFuncKeysTable;
ScanCode : Char;
Shift : TShiftState;
Ext : Boolean;
Value : TFuncKeyValue) : Boolean;
var
I : Integer;
begin
{ Search for existing key definition to replace it }
for I := Low(FKeys) to High(FKeys) do begin
if (FKeys[I].ScanCode = ScanCode) and
(FKeys[I].Shift = Shift) and
(FKeys[I].Ext = Ext) then begin
FKeys[I].Value := Value;
Result := TRUE; { Success}
Exit;
end;
end;
{ Key not existing, add in an empty space }
for I := Low(FKeys) to High(FKeys) do begin
if FKeys[I].ScanCode = #0 then begin
FKeys[I].ScanCode := ScanCode;
FKeys[I].Shift := Shift;
FKeys[I].Ext := Ext;
FKeys[I].Value := Value;
Result := TRUE; { Success}
Exit;
end;
end;
{ Failure, no more space available }
Result := FALSE;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure FKeysToFile(var FKeys : TFuncKeysTable; FName : String);
var
I : Integer;
F : TextFile;
begin
AssignFile(F, FName);
Rewrite(F);
for I := Low(FKeys) to High(FKeys) do begin
with FKeys[I] do begin
if ScanCode <> chr(0) then
WriteLn(F, IntToHex(Ord(ScanCode), 2), ', ',
ShiftStateToString(Shift), ', ',
Ext, ', ''',
FuncKeyValueToString(Value), '''');
end;
end;
CloseFile(F);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function GetToken(var S : String; var I : Integer; Delim : Char) : String;
begin
Result := '';
while (I <= Length(S)) and (S[I] = ' ') do
Inc(I);
while (I <= Length(S)) and (S[I] <> Delim) do begin
Result := Result + S[I];
Inc(I);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure FileToFKeys(var FKeys : TFuncKeysTable; FName : String);
var
I, J : Integer;
F : TextFile;
S, T : String;
sc : Integer;
begin
AssignFile(F, FName);
{$I-}
Reset(F);
if IOResult <> 0 then begin
{ File do not exist, create default one }
FKeysToFile(FKeys, FName);
Exit;
end;
for I := Low(FKeys) to High(FKeys) do begin
with FKeys[I] do begin
ScanCode := chr(0);
Shift := [];
Ext := FALSE;
Value := '';
if not Eof(F) then begin
{ 71, ssNormal, TRUE, '\x1B[H' }
ReadLn(F, S);
J := 1;
T := GetToken(S, J, ',');
if (Length(T) > 0) and (T[1] <> ';') then begin
sc := xdigit2(@T[1]);
if sc <> 0 then begin
ScanCode := chr(sc);
Inc(J);
T := GetToken(S, J, ',');
Shift := StringToShiftState(T);
Inc(J);
T := GetToken(S, J, ',');
Ext := UpperCase(T) = 'TRUE';
Inc(J);
T := GetToken(S, J, '''');
Inc(J);
T := GetToken(S, J, '''');
Value := StringToFuncKeyValue(T);
end;
end;
end;
end;
end;
CloseFile(F);
{$I+}
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure DebugString(Msg : String);
const
Cnt : Integer = 0;
{$IFDEF DEBUG_OUTPUT}
var
Buf : String[20];
{$ENDIF}
begin
{$IFDEF DEBUG_OUTPUT}
Cnt := Cnt + 1;
Buf := IntToHex(Cnt, 4) + ' ' + #0;
OutputDebugString(@Buf[1]);
{$IFNDEF WIN32}
if Length(Msg) < High(Msg) then
Msg[Length(Msg) + 1] := #0;
{$ENDIF}
OutputDebugString(@Msg[1]);
{$ENDIF}
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{$IFNDEF WIN32}
procedure SetLength(var S: string; NewLength: Integer);
begin
S[0] := chr(NewLength);
end;
{$ENDIF}
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TLine.Create;
begin
inherited Create;
FillChar(Txt, SizeOf(Txt), ' ');
FillChar(Att, SizeOf(Att), Chr(F_WHITE));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TLine.Clear(Attr : Byte);
begin
FillChar(Txt, SizeOF(Txt), ' ');
FillChar(Att, SizeOf(Att), Attr);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TScreen.Create;
begin
inherited Create;
FRowCount := 0;
FBackRowCount := 0;
FBackEndRow := 0;
FBackColor := vtsWhite;
FOptions := [vtoBackColor];
SetRowCount(25);
FColCount := 80;
FRowSaved := -1;
FColSaved := -1;
FScrollRowTop := 0;
{FScrollRowBottom := FRowCount - 1; // WM + SE 09/08/00 }
FAttribute := F_WHITE;
InvClear;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TScreen.Destroy;
var
nRow : Integer;
begin
for nRow := 0 to FRowCount + FBackRowCount - 1 do
FLines^[nRow].Free;
FreeMem (FLines, (FRowCount + FBackRowCount) * SizeOf(TObject));
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.AdjustFLines(NewCount : Integer);
var
NewLines : PLineArray;
CurrCount : Integer;
nRow : Integer;
begin
CurrCount := FRowCount + FBackRowCount;
if (NewCount <> CurrCount) and (NewCount > 0) then begin
GetMem(NewLines, NewCount * SizeOf(TObject));
if NewCount > CurrCount then begin
if CurrCount <> 0 then
Move(FLines^, NewLines^, CurrCount * SizeOf(TObject));
for nRow := CurrCount to NewCount - 1 do
NewLines^[nRow] := TLine.Create;
if CurrCount <> 0 then
FreeMem(FLines, CurrCount * SizeOf(TObject));
end
else begin
Move (FLines^, NewLines^, NewCount * SizeOf(TObject));
for nRow := NewCount to CurrCount - 1 do
FLines^[nRow].Free;
FreeMem(FLines, CurrCount * SizeOf(TObject));
end;
FLines := NewLines;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.SetRowCount(NewCount : Integer);
begin
if NewCount <> FRowCount then begin
AdjustFLines(NewCount + FBackRowCount);
FRowCount := NewCount;
FScrollRowBottom := FRowCount - 1; { WM + SE 09/08/00 }
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.SetBackRowCount(NewCount : Integer);
begin
if NewCount <> FBackRowCount then begin
AdjustFLines(FRowCount + NewCount);
FBackRowCount := NewCount;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.CopyScreenToBack;
{ Copies the current host screen into the scrollback buffer. }
var
Temp : TLine;
Row : Integer;
Pass : Integer;
nCol : Integer;
begin
if FBackRowCount >= FRowCount then begin
Dec (FBackEndRow, FRowCount);
if (0 - FBackEndRow) >= FBackRowCount then
FBackEndRow := 1 - FBackRowCount;
{ We have to make FRowCount lines available at the head of the
scrollback buffer. These will come from the end of the scrollback
buffer. We'll make FRowCount passes through the scrollback buffer
moving the available lines up to the top and the existing lines
down a page at a time.
Net result is that we only move each line once. }
For Pass := 0 To FRowCount - 1 Do begin
Row := FBackEndRow + Pass;
Temp := Lines[Row];
Inc (Row, FRowCount);
While Row < 0 Do begin
Lines[Row - FRowCount] := Lines[Row];
Inc (Row, FRowCount);
end;
Lines[Row - FRowCount] := Temp;
end;
{ Now, copy the host screen lines to the ones we made available. }
For Row := 0 To FRowCount - 1 Do begin
Move (Lines[Row].Txt, Lines[Row - FRowCount].Txt, FColCount);
Move (Lines[Row].Att, Lines[Row - FRowCount].Att, FColCount);
if vtoBackColor in FOptions then begin
with Lines[Row - FRowCount] do begin
for nCol := 0 to FColCount - 1 do begin
Att[nCol] := Att[nCol] And $8F Or (Ord (FBackColor) shl 4);
end;
end;
end;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ScrollUp;
var
Temp : TLine;
Row : Integer;
nCol : Integer;
begin
if FBackRowCount > 0 then begin
if (0 - FBackEndRow) < (FBackRowCount - 1) then
Dec (FBackEndRow);
Temp := Lines[FBackEndRow];
For Row := FBackEndRow + 1 To -1 Do begin
Lines[Row - 1] := Lines[Row];
end;
Lines[-1] := Lines[FScrollRowTop];
if vtoBackColor in FOptions then begin
with Lines[-1] do begin
for nCol := 0 to FColCount - 1 do begin
Att[nCol] := Att[nCol] And $8F Or (Ord (FBackColor) shl 4);
end;
end;
end;
end
else
Temp := Lines[FScrollRowTop];
for Row := FScrollRowTop + 1 to FScrollRowBottom do
Lines[Row - 1] := Lines[Row];
Lines[FScrollRowBottom] := Temp;
Temp.Clear(F_WHITE {FAttribute});
FAllInvalid := TRUE;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ScrollDown;
var
Temp : TLine;
Row : Integer;
begin
Temp := Lines[FScrollRowBottom];
for Row := FScrollRowBottom DownTo FScrollRowTop + 1 do
Lines[Row] := Lines[Row - 1];
Lines[FScrollRowTop] := Temp;
Temp.Clear(F_WHITE {FAttribute});
FAllInvalid := TRUE;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.CursorDown;
begin
Inc(FRow);
if FRow > FScrollRowBottom then begin
FRow := FScrollRowBottom;
ScrollUp;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.CursorUp;
begin
Dec(FRow);
if FRow < 0 then begin
Inc(FRow);
ScrollDown;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.CursorRight;
begin
Inc(FCol);
if FCol >= FColCount then begin
FCol := 0;
CursorDown;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.CursorLeft;
begin
Dec(FCol);
if FCol < 0 then begin
FCol := FColCount - 1;
CursorUp;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.CarriageReturn;
begin
FCol := 0;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TScreen.GetEscapeParam(From : Integer; var Value : Integer) : Integer;
begin
while (From <= Length(FEscBuffer)) and (FEscBuffer[From] = ' ') do
From := From + 1;
Value := 0;
while (From <= Length(FEscBuffer)) and (FEscBuffer[From] in ['0'..'9']) do begin
Value := Value * 10 + Ord(FEscBuffer[From]) - Ord('0');
From := From + 1;
end;
Result := From;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.UnimplementedEscape(EscCmd : Char);
{var
Buf : String;}
begin
DebugString('Unimplemented Escape Sequence: ' + FEscBuffer + EscCmd + #13 + #10);
{ Buf := FEscBuffer + EscCmd + #0;
MessageBox(0, @Buf[1], 'Unimplemented Escape Sequence', MB_OK); }
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.InvalidEscape(EscCmd : Char);
{var
Buf : String;}
begin
DebugString('Invalid Escape Sequence: ' + FEscBuffer + EscCmd + #13 + #10);
{ Buf := FEscBuffer + EscCmd + #0;
MessageBox(0, @Buf[1], 'Invalid Escape Sequence', MB_OK); }
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessESC_D; { Index }
begin
UnimplementedEscape('D');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Move cursor Up, scroll down if necessary }
procedure TScreen.ProcessESC_M; { Reverse index }
begin
Dec(FRow);
if FRow < FScrollRowTop then begin
FRow := FScrollRowTop;
ScrollDown;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessESC_E; { Next line }
begin
UnimplementedEscape('E');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessCSI_u; { Restore Cursor }
begin
UnimplementedEscape('u');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ IBM character set operation (not part of the ANSI standard) }
{ <ESC>[0I => Set IBM character set }
{ <ESC>[1;nnnI => Literal mode for nnn next characters }
{ <ESC>[2;onoffI => Switch carbon mode on (1) or off (0) }
{ <ESC>[3;ch;cl;sh;slI => Receive carbon mode keyboard code }
{ <ESC>[4I => Select ANSI character set }
procedure TScreen.ProcessCSI_I;
var
From, mode, nnn : Integer;
ch, cl, sh, sl : Integer;
begin
From := GetEscapeParam(2, Mode);
case Mode of
0: begin { Select IBM character set }
FNoXlat := TRUE;
end;
1: begin { Set literal mode for next N characters }
if FEscBuffer[From] = ';' then
GetEscapeParam(From + 1, FCntLiteral)
else
FCntLiteral := 1;
end;
2: begin { Switch carbon mode on or off }
if FEscBuffer[From] = ';' then
GetEscapeParam(From + 1, nnn)
else
nnn := 0;
FCarbonMode := (nnn <> 0);
end;
3: begin { Receive carbon mode key code }
ch := 0; cl := 0; sh := 0; sl := 0;
if FEscBuffer[From] = ';' then begin
From := GetEscapeParam(From + 1, cl);
if FEscBuffer[From] = ';' then begin
From := GetEscapeParam(From + 1, ch);
if FEscBuffer[From] = ';' then begin
From := GetEscapeParam(From + 1, sl);
if FEscBuffer[From] = ';' then begin
GetEscapeParam(From + 1, sh);
end;
end;
end;
end;
DebugString('Special key ' +
IntToHex(ch, 2) + IntToHex(cl, 2) + ' ' +
IntToHex(sh, 2) + IntToHex(sl, 2));
end;
4: begin { Select ANSI character set }
FNoXlat := FALSE;
end;
else
UnimplementedEscape('I');
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.BackSpace;
begin
if FCol > 0 then
Dec(FCol);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ClearScreen;
var
Row : Integer;
begin
for Row := 0 to FRowCount - 1 do
Lines[Row].Clear(FAttribute);
FRow := 0;
FCol := 0;
FAllInvalid := TRUE;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.InvClear;
begin
with FInvRect do begin
Top := 9999;
Left := 9999;
Right := -1;
Bottom := -1;
end;
FAllInvalid := FALSE;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.InvRect(nRow, nCol : Integer);
begin
if not FAllInvalid then begin
if FInvRect.Top > nRow then
FInvRect.Top := nRow;
if FInvRect.Bottom < nRow then
FInvRect.Bottom := nRow;
if FInvRect.Left > nCol then
FInvRect.Left := nCol;
if FInvRect.Right < nCol then
FInvRect.Right := nCol;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ The FLines array is inverted with the last host line at position 0 and
the first host line as position FRowCount - 1. }
procedure Tscreen.SetLines(I : Integer; Value : TLine);
begin
if I >= FRowCount then
FLines^[0] := Value
else
FLines^[FRowCount - 1 - I] := Value;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TScreen.GetLines(I : Integer) : TLine;
begin
if I >= FRowCount then
Result := FLines^[0]
else
Result := FLines^[FRowCount - 1 - I];
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.Eol;
begin
with Lines[FRow] do begin
FillChar(Txt[FCol], FColCount - FCol, ' ');
FillChar(Att[FCol], (FColCount - FCol) * SizeOf(Att[FCol]), FAttribute);
end;
InvRect(Frow, FCol);
InvRect(Frow, FColCount);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.Eop;
var
NRow : Integer;
begin
Eol;
for NRow := FRow + 1 to FRowCount - 1 do
Lines[NRow].Clear(FAttribute);
if FRow = 0 then
FAllInvalid := TRUE
else begin
InvRect(FRow, 0);
InvRect(FRowCount, FColCount);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessCSI_J; { Clear the screen }
var
Mode : Integer;
Row : Integer;
begin
GetEscapeParam(2, Mode);
case Mode of
0: begin { Cursor to end of screen }
FAttribute := F_WHITE;
Eop;
end;
1: begin { Start of screen to cursor }
for Row := 0 to FRow do
Lines[Row].Clear(FAttribute);
InvRect(0, 0);
InvRect(FRow, FColCount);
end;
2: begin { Entire screen }
if vtoCopyBackOnClear in FOptions then CopyScreenToBack;
ClearScreen;
end;
else
InvalidEscape('J');
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessCSI_K; { Erase to End of Line }
begin
Eol;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessCSI_L; { Insert Line }
var
nLine : Integer;
nRow : Integer;
Temp : TLine;
begin
FCol := 0;
GetEscapeParam(2, nLine);
if nLine = 0 then
nLine := 1;
if (FRow + nLine) > FScrollRowBottom then begin
for nRow := FRow to FScrollRowBottom do
Lines[nRow].Clear(FAttribute);
Exit;
end;
for nRow := FScrollRowBottom downto FRow + nLine do begin
Temp := Lines[nRow];
Lines[nRow] := Lines[nRow - nLine];
Lines[nRow - nLine] := Temp;
end;
for nRow := FRow to FRow + nLine - 1 do
Lines[nRow].Clear(FAttribute);
FAllInvalid := TRUE;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessCSI_M; { Delete Line }
var
nLine : Integer;
nRow : Integer;
Temp : TLine;
begin
FAllInvalid := TRUE;
FCol := 0;
GetEscapeParam(2, nLine);
if nLine = 0 then
nLine := 1;
if (FRow + nLine) > FScrollRowBottom then begin
for nRow := FRow to FScrollRowBottom do
Lines[nRow].Clear(FAttribute);
Exit;
end;
for nRow := FRow to FRow + nLine - 1 do
Lines[nRow].Clear(F_WHITE {FAttribute}); { 12/11/99 }
for nRow := FRow to FScrollRowBottom - nLine do begin
Temp := Lines[nRow];
Lines[nRow] := Lines[nRow + nLine];
Lines[nRow + nLine] := Temp;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessCSI_m_lc; { Select Attributes }
var
From, n : Integer;
begin
if FEscBuffer[1] <> '[' then
Exit;
if Length(FEscBuffer) < 2 then begin
FAttribute := F_WHITE;
FReverseVideo := FALSE;
Exit;
end;
From := 2;
while From <= Length(FEscBuffer) do begin
if FEscBuffer[From] in [' ', '[', ';'] then
Inc(From)
else begin
From := GetEscapeParam(From, n);
case n of
0: begin { All attributes off }
FAttribute := F_WHITE;
FReverseVideo := FALSE;
FUnderLine := FALSE;
end;
1: begin { High intensity }
FAttribute := FAttribute or F_INTENSE;
end;
4: begin { Underline }
FUnderLine := TRUE;
end;
5: begin { Blinking }
FAttribute := FAttribute or B_BLINK;
end;
7: begin { Reverse video }
FReverseVideo := TRUE;
end;
8: begin { Secret }
FAttribute := 0;
end;
10: begin { Don't force high bit }
FForceHighBit := FALSE;
end;
12: begin { Force high bit on }
FForceHighBit := TRUE;
end;
22: begin { Normal intensity }
FAttribute := FAttribute and (not F_INTENSE);
end;
27: begin { Normal characters }
FAttribute := F_WHITE;
FReverseVideo := FALSE;
end;
30, 31, 32, 33, 34, 35, 36, 37:
begin { Foreground color }
FAttribute := (n mod 10) or (FAttribute and $F8);
end;
40, 41, 42, 43, 44, 45, 46, 47:
begin { Background color }
FAttribute := ((n mod 10) shl 4) or (FAttribute and $8F);
end;
else
InvalidEscape('m');
end;
end;
end;
if FReverseVideo then begin
FAttribute := ((FAttribute and 7) shl 4) or
((FAttribute shr 4) and 7) or
(FAttribute and $88);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessCSI_n_lc; { Cursor position report }
begin
UnimplementedEscape('n');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessCSI_at; { Insert character }
var
nChar : Integer;
nCnt : Integer;
nCol : Integer;
Line : TLine;
begin
GetEscapeParam(2, nChar);
if nChar = 0 then
nChar := 1;
nCnt := FColCount - FCol - nChar;
if nCnt <= 0 then begin
Eol;
Exit;
end;
Line := Lines[FRow];
for nCol := FColCount - 1 downto FCol + nChar do begin
Line.Txt[nCol] := Line.Txt[nCol - nChar];
Line.Att[nCol] := Line.Att[nCol - nChar];
InvRect(Frow, nCol);
end;
for nCol := FCol to FCol + nChar - 1 do begin
Line.Txt[nCol] := ' ';
Line.Att[nCol] := FAttribute;
InvRect(Frow, nCol);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessCSI_r_lc; { Scrolling margins }
var
From, Top, Bottom : Integer;
begin
From := GetEscapeParam(2, Top);
if Top = 0 then begin { Default = full screen }
FScrollRowTop := 0;
FScrollRowBottom := FRowCount - 1;
end
else begin
while (From <= Length(FEscBuffer)) and (FEscBuffer[From] = ' ') do
From := From + 1;
if FEscBuffer[From] = ';' then
GetEscapeParam(From + 1, Bottom)
else
Bottom := 1;
FScrollRowTop := Top - 1;
FScrollRowBottom := Bottom - 1;
if (FScrollRowBottom <= FScrollRowTop) or
(FScrollRowTop < 0) or
(FScrollRowBottom >= FRowCount) then begin
FScrollRowTop := 0;
FScrollRowBottom := FRowCount - 1;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessCSI_s_lc; { Save cursor location }
begin
ProcessCSI_7;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessCSI_u_lc; { Restore cursor location }
begin
ProcessCSI_8;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessCSI_7; { Save cursor location }
begin
FRowSaved := FRow;
FColSaved := FCol;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessCSI_8; { Restore cursor location }
begin
if FRowSaved = -1 then
GotoXY(0, 0)
else
GotoXY(FColSaved, FRowSaved);
FRowSaved := -1;
FColSaved := -1;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessCSI_H; { Set Cursor Position }
var
From, Row, Col : Integer;
begin
From := GetEscapeParam(2, Row);
while (From <= Length(FEscBuffer)) and (FEscBuffer[From] = ' ') do
From := From + 1;
if FEscBuffer[From] = ';' then
GetEscapeParam(From + 1, Col)
else
Col := 1;
GotoXY(Col - 1, Row - 1);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessCSI_h_lc; { Terminal mode set }
var
Priv : Boolean;
Mode : Integer;
begin
if FEscBuffer[1] <> '[' then begin
UnimplementedEscape('h');
Exit;
end;
Priv := (FEscBuffer[2] = '?');
if not Priv then begin
UnimplementedEscape('h');
Exit;
end;
GetEscapeParam(3, Mode);
case Mode of
1 : { ANSI cursor keys }
FCKeyMode := TRUE;
4 : { Smooth scroll OFF }
{ Ignore };
7: { Auto-wrap OFF }
FAutoWrap := TRUE;
25: { Cursor visible }
begin
FCursorOff := FALSE;
if Assigned(FOnCursorVisible) then
FOnCursorVisible(Self);
end;
else
UnimplementedEscape('h');
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessCSI_l_lc; { Terminal mode reset }
var
Priv : Boolean;
Mode : Integer;
begin
if FEscBuffer[1] <> '[' then begin
UnimplementedEscape('l');
Exit;
end;
Priv := (FEscBuffer[2] = '?');
if not Priv then begin
UnimplementedEscape('l');
Exit;
end;
GetEscapeParam(3, Mode);
case Mode of
1 : { ANSI cursor keys }
FCKeyMode := FALSE;
4 : { Smooth scroll OFF }
{ Ignore };
7: { Auto-wrap OFF }
FAutoWrap := FALSE;
25: { Cursor invisible }
begin
FCursorOff := TRUE;
if Assigned(FOnCursorVisible) then
FOnCursorVisible(Self);
end;
else
UnimplementedEscape('l');
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessCSI_A; { Cursor Up }
var
Row : Integer;
begin
GetEscapeParam(2, Row);
if Row <= 0 then
Row := 1;
FRow := FRow - Row;
if FRow < 0 then
FRow := 0;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessCSI_B; { Cursor Down }
var
Row : Integer;
begin
GetEscapeParam(2, Row);
if Row <= 0 then
Row := 1;
FRow := FRow + Row;
if FRow >= FRowCount then
FRow := FRowCount - 1;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessCSI_C; { Cursor Right }
var
Col : Integer;
begin
GetEscapeParam(2, Col);
if Col <= 0 then
Col := 1;
FCol := FCol + Col;
if FCol >= FColCount then begin
if FAutoWrap then begin
FCol := FCol - FColCount;
Inc(FRow);
if FRow >= FRowCount then
FRow := FRowCount - 1;
end
else
FCol := FColCount - 1;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessCSI_D; { Cursor Left }
var
Col : Integer;
begin
GetEscapeParam(2, Col);
if Col <= 0 then
Col := 1;
FCol := FCol - Col;
if FCol < 0 then
FCol := 0;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessCSI_P; { Delete Character }
var
Count : Integer;
nCol : Integer;
begin
GetEscapeParam(2, Count);
if Count <= 0 then
Count := 1;
with Lines[FRow] do begin
for nCol := Fcol to FColCount - Count - 1 do begin
Txt[nCol] := Txt[nCol + Count];
Att[nCol] := Att[nCol + Count];
end;
for nCol := FcolCount - Count - 1 to FColCount - 1 do begin
Txt[nCol] := ' ';
Att[nCol] := F_WHITE;
end;
end;
InvRect(Frow, FCol);
InvRect(Frow, FColCount);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessCSI_S; { Scroll up }
begin
ScrollUp;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessCSI_T; { Scroll down }
begin
UnimplementedEscape('T');
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.process_charset_G0(EscCmd : Char); { G0 character set }
begin
case EscCmd of
'0': begin
FCharSetG0 := EscCmd;
FXlatInputTable := @ibm_iso8859_1_G1;
FXlatOutputTable := @ibm_iso8859_1_G1;
FNoXlat := FNoXlatInitial;
{ FNoXlat := FALSE;}
end;
'B': begin
FCharSetG0 := EscCmd;
FXlatInputTable := @ibm_iso8859_1_G0;
FXlatOutputTable := @ibm_iso8859_1_G0;
FNoXlat := FNoXlatInitial;
end;
else
InvalidEscape(EscCmd);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.process_charset_G1(EscCmd : Char); { G1 character set }
begin
FCharSetG1 := EscCmd;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.process_charset_G2(EscCmd : Char); { G2 character set }
begin
FCharSetG2 := EscCmd;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.process_charset_G3(EscCmd : Char); { G2 character set }
begin
FCharSetG3 := EscCmd;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.ProcessEscape(EscCmd : Char);
begin
if Length(FEscBuffer) = 0 then begin
case EscCmd of
'D': ProcessESC_D; { Index }
'M': ProcessESC_M; { Reverse index }
'E': ProcessESC_E; { Next line }
'H': ; { Tabulation set }
'7': ProcessCSI_7; { Save cursor }
'8': ProcessCSI_8; { Restore Cursor }
'=': ; { VT52 } { Enter Alternate keypad }
'>': ; { VT52 } { Exit Alternate keypad }
'<': ; { VT52 } { Enter ANSI mode }
else
InvalidEscape(EscCmd);
WriteLiteralChar(EscCmd);
end;
Exit;
end;
case FEscBuffer[1] of
' ': begin
case EscCmd of
'F': ;
else
InvalidEscape(EscCmd);
end;
end;
'[': begin
case EscCmd of
'I': ProcessCSI_I; { Select IBM char set }
{ Extension F. Piette !! }
'J': ProcessCSI_J; { Clear the screen }
'K': ProcessCSI_K; { Erase to End of Line }
'L': ProcessCSI_L; { Insert Line }
'M': ProcessCSI_M; { Delete Line }
'm': ProcessCSI_m_lc; { Select Attributes }
'n': ProcessCSI_n_lc; { Cursor position report }
'@': ProcessCSI_at; { Insert character }
'r': ProcessCSI_r_lc; { Set Top and Bottom marg }
's': ProcessCSI_s_lc; { Save cursor location }
'u': ProcessCSI_u_lc; { Restore cursor location }
'H': ProcessCSI_H; { Set Cursor Position }
'f': ProcessCSI_H; { Set Cursor Position }
'g': ; { Tabulation Clear }
'h': ProcessCSI_h_lc; { Terminal mode set }
'l': ProcessCSI_l_lc; { Terminal mode reset }
'A': ProcessCSI_A; { Cursor Up }
'B': ProcessCSI_B; { Cursor Down }
'C': ProcessCSI_C; { Cursor Right }
'D': ProcessCSI_D; { Cursor Left }
'P': ProcessCSI_P; { Delete Character }
'S': ProcessCSI_S; { Scroll up }
'T': ProcessCSI_T; { Scroll down }
'>': ; { }
else
InvalidEscape(EscCmd);
end;
end;
'(': process_charset_G0(EscCmd); { G0 character set }
')': process_charset_G1(EscCmd); { G1 character set }
'*': process_charset_G2(EscCmd); { G2 character set }
'+': process_charset_G3(EscCmd); { G3 character set }
else
InvalidEscape(EscCmd);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.WriteLiteralChar(Ch : Char);
var
Line : TLine;
begin
if FCol >= FColCount then begin
if FAutoWrap then begin
FCol := 0;
Inc(FRow);
if FRow >= FRowCount then begin
Dec(FRow);
ScrollUp;
end;
end;
end;
if FForceHighBit then
Ch := Chr(ord(ch) or $80);
Line := Lines[FRow];
Line.Txt[FCol] := Ch;
Line.Att[FCol] := FAttribute;
InvRect(Frow, FCol);
if FCol < High(Line.Txt) then
Inc(FCol);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.SetAttr(Att : Char);
begin
{ Not implemented }
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Write a single character at current cursor location. }
{ Update cursor position. }
procedure TScreen.WriteChar(Ch : Char);
var
bProcess : Boolean;
begin
if FCntLiteral > 0 then begin
if (FCntLiteral and 1) <> 0 then
WriteLiteralChar(Ch)
else
SetAttr(Ch);
Dec(FCntLiteral);
Exit;
end;
if FNoXlat then
Ch := FXlatInputTable^[ord(Ch)];
if FEscFLag then begin
bProcess := FALSE;
if (Length(FEscBuffer) = 0) and
(Ch in ['D', 'M', 'E', 'H', '7', '8', '=', '>', '<']) then
bProcess := TRUE
else if (Length(FEscBuffer) = 1) and
(FEscBuffer[1] in ['(', ')', '*', '+']) then
bProcess := TRUE
else if (Ch in ['0'..'9', ';', '?', ' ']) or
((Length(FEscBuffer) = 0) and
(ch in ['[', '(', ')', '*', '+'])) then begin
FEscBuffer := FEscBuffer + Ch;
if Length(FEscBuffer) >= High(FEscBuffer) then begin
MessageBeep(MB_ICONASTERISK);
FEscBuffer := '';
FEscFlag := FALSE;
end;
end
else
bProcess := TRUE;
if bProcess then begin
ProcessEscape(Ch);
FEscBuffer := '';
FEscFlag := FALSE;
end;
Exit;
end;
case Ch of
#0: ;
#7: MessageBeep(MB_ICONASTERISK);
#8: BackSpace;
#9: begin
repeat
Inc(FCol);
until (FCol Mod 8) = 0;
end;
#10: begin
CursorDown;
if FAutoCR then
CarriageReturn;
end;
#13: begin
CarriageReturn;
if FAutoLF then
CursorDown;
end;
#14: begin
FXlatInputTable := @ibm_iso8859_1_G1;
FXlatOutputTable := @ibm_iso8859_1_G1;
end;
#15: begin
FXlatInputTable := @ibm_iso8859_1_G0;
FXlatOutputTable := @ibm_iso8859_1_G0;
end;
#27: begin
FEscBuffer := '';
FEscFlag := TRUE;
end;
else
WriteLiteralChar(Ch);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Write characters at current cursor location. Update cursor position. }
procedure TScreen.WriteStr(Str : String);
var
I : Integer;
begin
for I := 1 to Length(Str) do
WriteChar(Str[I]);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Read characters from the cursor to end of line }
function TScreen.ReadStr : String;
var
Line : TLine;
Len : Integer;
begin
Line := Lines[FRow];
Len := FColCount - FCol;
if Len <= 0 then
Result := ''
else begin
SetLength(Result, Len);
Move(Line.Txt[FCol], Result[1], Len);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TScreen.GotoXY(X, Y : Integer);
begin
if X < 0 then
FCol := 0
else if X >= FColCount then
FCol := FColCount - 1
else
FCol := X;
if Y < 0 then
FRow := 0
else if Y >= FRowCount then
FRow := FRowCount - 1
else
FRow := Y;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.SetCaret;
begin
if not FScreen.Focused then { Jan 10, 2005 }
Exit;
{$IFDEF CHAR_ZOOM}
SetCaretPos(FCharPos[FScreen.FCol] + FLeftMargin + 2,
FLinePos[FScreen.FRow - FTopLine] + FTopMargin + 3);
{$ELSE}
SetCaretPos(FScreen.FCol * FCharWidth + FLeftMargin,
(FScreen.FRow - FTopLine) * FLineHeight + FTopMargin);
{$ENDIF}
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ Adjusts the scrollbar properties to match the number of host and scrollback
lines that we can scroll through. }
procedure TCustomEmulVT.AdjustScrollBar;
var
VisibleLines : Integer;
begin
if not FVScrollBar.Visible then
Exit;
FVScrollBar.Min := FScreen.FBackEndRow;
{$IFDEF CHAR_ZOOM}
VisibleLines := Trunc((Height - FTopMargin - FBottomMargin) / (LineHeight * FLineZoom));
{$ELSE}
VisibleLines := (Height - FTopMargin - FBottomMargin) Div LineHeight;
{$ENDIF}
if VisibleLines > FScreen.FRowCount then
VisibleLines := FScreen.FRowCount;
FVScrollBar.Max := FScreen.FRowCount - VisibleLines;
FVScrollBar.Position := FTopLine;
FVScrollBar.SmallChange := 1;
FVScrollBar.LargeChange := VisibleLines;
FVScrollBar.Enabled := FVScrollBar.Max > FVScrollBar.Min;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.Clear;
begin
FScreen.ClearScreen;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.SetCursor(Row, Col : Integer);
begin
FScreen.GotoXY(Col - 1, Row - 1);
{ SetCaret; }
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.WriteChar(Ch : Char);
begin
if FCaretCreated and FCaretShown then begin
HideCaret(Handle);
FCaretShown := FALSE;
end;
if FLog then
Write(FFileHandle, Ch);
FScreen.WriteChar(ch);
if FAutoRepaint then
UpdateScreen;
{ SetCaret; }
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.WriteStr(Str : String);
var
I : Integer;
begin
if FCaretCreated and FCaretShown then begin
HideCaret(Handle);
FCaretShown := FALSE;
end;
for I := 1 to Length(Str) do begin
if FLog then
Write(FFileHandle, Str[I]);
FScreen.WriteChar(Str[I]);
end;
if FAutoRepaint then
UpdateScreen;
{ SetCaret; }
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.WriteBuffer(Buffer : Pointer; Len : Integer);
var
I : Integer;
begin
if FCaretCreated and FCaretShown then begin
HideCaret(Handle);
FCaretShown := FALSE;
end;
for I := 0 to Len - 1 do begin
if FLog then
Write(FFileHandle, PChar(Buffer)[I]);
FScreen.WriteChar(PChar(Buffer)[I]);
end;
if FAutoRepaint then
UpdateScreen;
{ SetCaret; }
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomEmulVT.ReadStr : String;
begin
Result := FScreen.ReadStr;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.CopyHostScreen;
begin
FScreen.CopyScreenToBack;
AdjustScrollBar;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
constructor TCustomEmulVT.Create(AOwner: TComponent);
type
TMyLogPalette = record
palVersion: Word;
palNumEntries: Word;
palPalEntry: array[0..NumPaletteEntries - 1] of TPaletteEntry;
end;
TPLogPalette = ^TLogPalette;
var
plgpl : ^TMyLogPalette;
I : Integer;
begin
inherited Create(AOwner);
ControlStyle := ControlStyle + [csOpaque];
New(plgpl);
plgpl^.palNumEntries := High(plgpl^.palPalEntry) + 1;
plgpl^.palVersion := $300;
FTopMargin := 4;
FLeftMargin := 6;
FRightMargin := 6;
FBottomMargin := 4;
FPaletteEntries[0].peRed := 0; { Black }
FPaletteEntries[0].peGreen := 0;
FPaletteEntries[0].peBlue := 0;
FPaletteEntries[1].peRed := 168; { Red }
FPaletteEntries[1].peGreen := 0;
FPaletteEntries[1].peBlue := 0;
FPaletteEntries[2].peRed := 0; { Green }
FPaletteEntries[2].peGreen := 168;
FPaletteEntries[2].peBlue := 0;
FPaletteEntries[3].peRed := 168; { Yellow }
FPaletteEntries[3].peGreen := 168;
FPaletteEntries[3].peBlue := 0;
FPaletteEntries[4].peRed := 0; { Dark Blue }
FPaletteEntries[4].peGreen := 0;
FPaletteEntries[4].peBlue := 168;
FPaletteEntries[5].peRed := 168; { Magenta }
FPaletteEntries[5].peGreen := 0;
FPaletteEntries[5].peBlue := 168;
FPaletteEntries[6].peRed := 0; { Cyan }
FPaletteEntries[6].peGreen := 112;
FPaletteEntries[6].peBlue := 216;
FPaletteEntries[7].peRed := 200; { White }
FPaletteEntries[7].peGreen := 200;
FPaletteEntries[7].peBlue := 200;
FPaletteEntries[8].peRed := 84; { Grey }
FPaletteEntries[8].peGreen := 84;
FPaletteEntries[8].peBlue := 84;
FPaletteEntries[9].peRed := 255; { Red Highlight }
FPaletteEntries[9].peGreen := 84;
FPaletteEntries[9].peBlue := 212;
FPaletteEntries[10].peRed := 84; { Green Highlight }
FPaletteEntries[10].peGreen := 255;
FPaletteEntries[10].peBlue := 84;
FPaletteEntries[11].peRed := 255; { Yellow Highlight }
FPaletteEntries[11].peGreen := 255;
FPaletteEntries[11].peBlue := 84;
FPaletteEntries[12].peRed := 84; { Blue Highlight }
FPaletteEntries[12].peGreen := 84;
FPaletteEntries[12].peBlue := 255;
FPaletteEntries[13].peRed := 255; { Magenta Highlight }
FPaletteEntries[13].peGreen := 84;
FPaletteEntries[13].peBlue := 255;
FPaletteEntries[14].peRed := 84; { Cyan highlight }
FPaletteEntries[14].peGreen := 255;
FPaletteEntries[14].peBlue := 255;
FPaletteEntries[15].peRed := 255; { White Highlight }
FPaletteEntries[15].peGreen := 255;
FPaletteEntries[15].peBlue := 255;
for I := 0 to High(plgpl^.palPalEntry) do begin
plgpl^.PalPalEntry[I].peRed := FPaletteEntries[I].peRed;
plgpl^.PalPalEntry[I].peGreen := FPaletteEntries[I].peGreen;
plgpl^.PalPalEntry[I].peBlue := FPaletteEntries[I].peBlue;
plgpl^.PalPalEntry[I].peFlags := PC_NOCOLLAPSE;
end;
FPal := CreatePalette(TPLogPalette(plgpl)^);
Dispose(plgpl);
FScreen := TScreen.Create;
FVScrollBar := TScrollBar.Create(Self);
FFont := TFont.Create;
FFont.Name := 'Terminal';
FFont.Size := 12;
FFont.Style := [];
FCharZoom := 1.0;
FLineZoom := 1.0;
SetupFont;
FScreen.FXlatInputTable := @ibm_iso8859_1_G0;
FScreen.FXlatOutputTable := @ibm_iso8859_1_G0;
FScreen.OnCursorVisible := CursorVisibleEvent;
FCursorVisible := TRUE;
Width := 250;
Height := 100;
FBorderStyle := bsSingle;
FBorderWidth := 1;
FAutoRepaint := TRUE;
FFkeys := 1;
FGraphicDraw := FALSE;
with FVScrollBar do begin
Parent := Self;
Kind := sbVertical;
Width := 16;
Visible := TRUE;
Align := alRight;
OnScroll := VScrollBarScroll;
end;
AdjustScrollBar;
with FScreen do begin
GotoXY(0, 0);
WriteStr('EmulVT');
GotoXY(0, 1);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.SetRows(Value : Integer);
begin
with FScreen do begin
if FRowCount <> Value then begin
SetRowCount(Value);
AdjustScrollBar;
ClearScreen;
Repaint;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomEmulVT.GetRows : Integer;
begin
Result := FScreen.FRowCount;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.SetCols(Value : Integer);
begin
with FScreen do begin
if FColCount <> Value then begin
FColCount := Value;
ClearScreen;
Repaint;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomEmulVT.GetCols : Integer;
begin
Result := FScreen.FColCount;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.CursorVisibleEvent(Sender : TObject);
begin
if FScreen.FCursorOff then begin
if FCaretShown then begin
HideCaret(Handle);
FCaretShown := FALSE;
end;
end
else begin
if FScreen.Focused and not FCaretShown then begin
ShowCaret(Handle);
FCaretShown := TRUE;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.SetAutoLF(Value : Boolean);
begin
FScreen.FAutoLF := Value;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.SetAutoCR(Value : Boolean);
begin
FScreen.FAutoCR := Value;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.SetLog(Value : Boolean);
begin
if FLog = Value then
Exit;
FLog := Value;
if FLog then begin
{$I-}
AssignFile(FFileHandle, 'EMULVT.LOG');
Append(FFileHandle);
if IOResult <> 0 then
Rewrite(FFileHandle);
Write(FFileHandle, '<Open>');
{$I+}
end
else begin
Write(FFileHandle, '<Close>');
CloseFile(FFileHandle);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.SetXlat(Value : Boolean);
begin
FScreen.FNoXlat := not Value;
FScreen.FNoXlatInitial := not Value;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomEmulVT.GetXlat : Boolean;
begin
Result := not FScreen.FNoXlatInitial;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomEmulVT.GetAutoLF : Boolean;
begin
Result := FScreen.FAutoLF;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomEmulVT.GetAutoCR : Boolean;
begin
Result := FScreen.FAutoCR;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
destructor TCustomEmulVT.Destroy;
begin
if FLog then
Log := FALSE;
FFont.Free;
FVScrollBar.Free;
FScreen.Free;
DeleteObject(FPal);
inherited Destroy;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.SetBackRows(Value : Integer);
begin
with FScreen do begin
if FBackRowCount <> Value then begin
SetBackRowCount(Value);
AdjustScrollBar;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.SetTopLine(Value : Integer);
begin
if Value < FVScrollBar.Min then
Value := FVScrollBar.Min;
if Value > FVScrollBar.Max then
Value := FVScrollBar.Max;
FTopLine := Value;
FVScrollBar.Position := FTopLine;
Repaint;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomEmulVT.GetBackRows : Integer;
begin
Result := FScreen.FBackRowCount;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.SetBackColor(Value : TBackColors);
begin
FScreen.FBackColor := Value;
Invalidate;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomEmulVT.GetBackColor : TBackColors;
begin
Result := FScreen.FBackColor;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.SetMarginColor(const Value: Integer);
begin
FMarginColor := Value;
Invalidate;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.SetLeftMargin(const Value: Integer);
begin
FLeftMargin := Value;
Invalidate;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.SetBottomMargin(const Value: Integer);
begin
FBottomMargin := Value;
Invalidate;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.SetRightMargin(const Value: Integer);
begin
FRightMargin := Value;
Invalidate;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.SetTopMargin(const Value: Integer);
begin
FTopMargin := Value;
Invalidate;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.SetOptions(Value : TScreenOptions);
begin
FScreen.FOptions := Value;
Invalidate;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomEmulVT.GetOptions : TScreenOptions;
begin
Result := FScreen.FOptions;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.SetupFont;
var
DC : HDC;
Metrics : TTextMetric;
hObject : THandle;
begin
DC := GetDC(0);
hObject := SelectObject(DC, FFont.Handle);
GetTextMetrics(DC, Metrics);
SelectObject(DC, hOBject);
ReleaseDC(0, DC);
SetCharWidth(Metrics.tmMaxCharWidth);
SetLineHeight(Metrics.tmHeight);
FInternalLeading := Metrics.tmInternalLeading;
Invalidate;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.SetCharWidth(newValue : Integer);
var
nCol : Integer;
begin
FCharWidth := newValue;
for nCol := Low(FCharPos) to High(FCharPos) do
FCharPos[nCol] := Trunc(FCharWidth * nCol * FCharZoom);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.SetCharZoom(newValue : Single);
begin
FCharZoom := newValue;
SetCharWidth(FCharWidth);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.SetLineHeight(Value : Integer);
var
nRow : Integer;
begin
FLineHeight := Value;
for nRow := 0 to High(FLinePos) do { Jan 10, 2002 }
FLinePos[nRow] := Trunc(FLineHeight * nRow * FLineZoom);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.SetLineZoom(newValue : Single);
begin
FLineZoom := newValue;
SetLineHeight(FLineHeight);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.SetFont(Value : TFont);
begin
FFont.Assign(Value);
{$IFNDEF SINGLE_CHAR_PAINT}
FFont.Pitch := fpFixed;
{$ENDIF}
SetupFont;
SetCaret;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.WMLButtonDown(var Message: TWMLButtonDown);
begin
inherited;
SetFocus;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.VScrollBarScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer);
begin
FTopLine := ScrollPos;
Repaint;
SetFocus;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.DoKeyBuffer(Buffer : PChar; Len : Integer);
var
J : Integer;
ch : Char;
begin
if Assigned(FOnKeyBuffer) then
FOnKeyBuffer(Self, Buffer, Len)
else begin
for J := 0 to Len - 1 do begin
ch := Buffer[J];
KeyPress(ch);
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomEmulVT.FindFKeys(ScanCode: Char; Shift: TShiftState;
Ext: Boolean) : PFuncKeyValue;
var
I : Integer;
pFKeys : PFuncKeysTable;
begin
Result := nil;
case FKeys of
0 : pFKeys := @FKeys1;
1 : pFKeys := @FKeys2;
2 : pFKeys := @FKeys3;
else
pFKeys := @FKeys2;
end;
for I := Low(pFKeys^) to High(pFKeys^) do begin
if (pFKeys^[I].ScanCode <> #0) and (pFKeys^[I].ScanCode = ScanCode) and
(pFKeys^[I].Shift = Shift) and
(pFKeys^[I].Ext = Ext) then begin
Result := @pFKeys^[I].Value;
Break;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomEmulVT.ProcessFKeys(ScanCode: Char; Shift: TShiftState;
Ext: Boolean) : Boolean;
var
I : Integer;
pFKeys : PFuncKeysTable;
begin
Result := FALSE;
case FKeys of
0 : pFKeys := @FKeys1;
1 : pFKeys := @FKeys2;
2 : pFKeys := @FKeys3;
else
pFKeys := @FKeys2;
end;
for I := Low(pFKeys^) to High(pFKeys^) do begin
if (pFKeys^[I].ScanCode <> #0) and (pFKeys^[I].ScanCode = ScanCode) and
(pFKeys^[I].Shift = Shift) and
(pFKeys^[I].Ext = Ext) then begin
Result := TRUE;
DoKeyBuffer(@pFKeys^[I].Value[1], Length(pFKeys^[I].Value));
Break;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.AppMessageHandler(var Msg: TMsg; var Handled: Boolean);
const
v1 : String = 'aeiou';
v2 : String = 'âêîôû';
v3 : String = 'äëïöü';
SpyFlag : Boolean = FALSE;
var
Shift : TShiftState;
ShiftLock : Boolean;
VirtKey : Integer;
Key : Char;
I : Integer;
ScanCode : Char;
Ext : Boolean;
SpyBuffer : String;
FnBuffer : String;
pFV : PFuncKeyValue;
begin
if (Msg.hWnd = Handle) and (Msg.Message = WM_KEYDOWN) then begin
VirtKey := Msg.wParam;
Key := chr(Msg.wParam and $FF);
{ DebugString('AppMessageHandler KEYDOWN ' + IntToHex(Msg.wParam, 4) + #13 + #10); }
Shift := KeyDataToShiftState(Msg.lParam);
ShiftLock := ((GetKeyState(VK_CAPITAL) and 1) > 0);
ScanCode := Chr(LOBYTE(HIWORD(Msg.lParam)));
Ext := ((Msg.lParam and $1000000) <> 0);
if Assigned(FOnKeyDown) then begin
FOnKeyDown(Self, VirtKey, Shift, ShiftLock, ScanCode, Ext);
if VirtKey = 0 then begin
Handled := TRUE;
Exit;
end;
end;
if (Msg.wParam <> VK_SHIFT) and
(Msg.wParam <> VK_CONTROL) and
(Msg.wParam <> VK_MENU) then begin
if (ScanCode = '7') and
(Shift = [ssAlt, ssCtrl]) and (Ext = FALSE) then begin
{ This is CTRL-ALT-* (on num pad) }
SpyFlag := TRUE;
Handled := TRUE;
Exit;
end;
if SpyFlag then begin
SpyFlag := FALSE;
pFV := FindFKeys(ScanCode, Shift, Ext);
SpyBuffer := IntToHex(Ord(ScanCode), 2) + ', ' +
ShiftStateToString(Shift) + ', ';
if Ext then
SpyBuffer := SpyBuffer + 'TRUE'
else
SpyBuffer := SpyBuffer + 'FALSE';
if pFV <> nil then
SpyBuffer := SpyBuffer + ', ''' +
FuncKeyValueToString(pFV^) + '''';
SpyBuffer := SpyBuffer + #0;
ClipBoard.SetTextBuf(@SpyBuffer[1]);
FnBuffer := 'Key definition from tnchrk' +
IntToStr(FKeys) + '.cfg' + #0;
Application.MessageBox(@SpyBuffer[1], @FnBuffer[1], MB_OK);
Handled := TRUE;
Exit;
end;
if ProcessFKeys(ScanCode, Shift, Ext) then begin
Handled := TRUE;
Exit;
end;
end;
case Msg.wParam of
VK_SHIFT, VK_CONTROL, VK_MENU: ;
VK_NEXT, VK_PRIOR, VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT, VK_HOME, VK_END:
begin
if ProcessFKeys(ScanCode, Shift, TRUE) then begin
Handled := TRUE;
Exit;
end;
end;
VK_TAB, VK_RETURN, VK_ESCAPE, VK_BACK:
begin
Handled := TRUE;
end;
$DD:
begin
if not (ssAlt in Shift) then begin
Key := #0;
Handled := TRUE;
if (ssShift in Shift) then
FFlagTrema := TRUE
else
FFlagCirconflexe := TRUE;
end;
end;
ord('A')..ord('Z') :
begin
if (ssCtrl in Shift) then
Key := chr(Word(Key) and $1F)
else if not ShiftLock and not (ssShift in Shift) then
Key := chr(Word(Key) or $20);
if (FFlagCirconflexe) then begin
for I := Length(v1) downto 1 do begin
if Key = v1[I] then begin
Key := v2[I];
Break;
end;
end;
FFlagCirconflexe := FALSE;
end;
if (FFlagTrema) then begin
for I := Length(v1) downto 1 do begin
if Key = v1[I] then begin
Key := v3[I];
Break;
end;
end;
FFlagTrema := FALSE;
end;
Handled := TRUE;
end;
end;
{ DebugString('Char = ' + IntToHex(Integer(Key), 2) + #13 + #10); }
if Handled and (Key <> #0) then
KeyPress(Key);
end;
if not Handled and Assigned(FAppOnMessage) then
FAppOnMessage(Msg, Handled);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.KeyPress(var Key: Char);
begin
if not FScreen.FNoXlat then
Key := FScreen.FXlatOutputTable^[ord(Key)];
inherited KeyPress(Key);
if FLocalEcho then begin
WriteChar(Key);
if not FAutoRepaint then
UpdateScreen;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.WMSetFocus(var Message: TWMSetFocus);
begin
{ inherited; }
FScreen.Focused := TRUE;
{ SetupFont; }
if not FCursorVisible then
Exit;
CreateCaret(Handle, 0, 2, FLineHeight);
FCaretCreated := TRUE;
SetCaret;
if not FScreen.FCursorOff then begin
ShowCaret(Handle);
FCaretShown := TRUE;
end;
FAppOnMessage := Application.OnMessage;
Application.OnMessage := AppMessageHandler;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.WMKillFocus(var Message: TWMKillFocus);
begin
{ inherited; }
FScreen.Focused := FALSE;
if not FCursorVisible then
Exit;
if FCaretShown then begin
HideCaret(Handle);
FCaretShown := FALSE;
end;
if FCaretCreated then begin
DestroyCaret;
FCaretCreated := FALSE;
end;
Application.OnMessage := FAppOnMessage;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.MouseToCell(X, Y: Integer; var ACol, ARow: Longint);
begin
{$IFDEF CHAR_ZOOM}
aRow := FScreen.FRowCount - 1;
while (Y - FTopMargin) <= FLinePos[aRow] do
Dec(aRow);
{$ELSE}
aRow := (Y - FTopMargin) div FLineHeight;
{$ENDIF}
if aRow < 0 then
aRow := 0
else if aRow >= FScreen.FRowCount then
aRow := FScreen.FRowCount - 1;
{$IFDEF CHAR_ZOOM}
aCol := FScreen.FColCount - 1;
while (X - FLeftMargin) <= FCharPos[aCol] do
Dec(aCol);
{$ELSE}
aCol := (X - FLeftMargin) div FCharWidth;
{$ENDIF}
if aCol < 0 then
aCol := 0
else if aCol >= FScreen.FColCount then
aCol := FScreen.FColCount - 1;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.ShowCursor;
begin
SetCaret;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.WMPaletteChanged(var Message : TMessage);
{var
HandleDC : HDC;}
begin
{ if Message.wParam <> Handle then begin
HandleDC := GetDC(Handle);
SelectPalette(HandleDC, FPal, FALSE);
if RealizePalette(HandleDC) <> 0 then begin
InvalidateRect(Handle, nil, TRUE);
MessageBeep(0);
end;
ReleaseDC(Handle, HandleDC);
end;
}
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.UpdateScreen;
var
rc : TRect;
begin
if FScreen.FAllInvalid then
InvalidateRect(Handle, nil, FALSE)
else begin
{$Q-}
with FScreen.FInvRect do begin
{$IFDEF CHAR_ZOOM}
if Left = 9999 then begin
rc.Top := 0;
rc.Bottom := 0;
rc.Left := 0;
rc.Right := 0;
end
else begin
rc.Top := FTopMargin + FLinePos[Top - FTopLine] + FInternalLeading;
rc.Bottom := FTopMargin + FLinePos[Bottom + 1 - FTopLine] + FInternalLeading;
rc.Left := FLeftMargin + FCharPos[Left];
rc.Right := FLeftMargin + FCharPos[Right + 1];
end;
{$ELSE}
rc.Top := FTopMargin + FLineHeight * (Top - FTopLine) + FInternalLeading;
rc.Bottom := FTopMargin + FLineHeight * (Bottom + 1 - FTopLine) + FInternalLeading;
rc.Left := FLeftMargin + FCharWidth * Left;
rc.Right := FLeftMargin + FCharWidth * (Right + 1);
{$ENDIF}
end;
InvalidateRect(Handle, @rc, FALSE);
{$Q+}
end;
{ Invalidate the region where the caret is. I should'nt do that, but }
{ if I do'nt, the caret remains where it is ! Bug ? }
{$IFDEF CHAR_ZOOM}
rc.Top := FLinePos[FScreen.FRow - FTopLine] + FTopMargin;
rc.Bottom := FLinePos[FScreen.FRow - FTopLine + 1] + FTopMargin;
rc.Left := FLeftMargin + FCharPos[FScreen.FCol];
rc.Right := FLeftMargin + FCharPos[FScreen.FCol + 1];
{$ELSE}
rc.Top := FTopMargin + FLineHeight * (FScreen.FRow - FTopLine);
rc.Bottom := rc.Top + FLineHeight;
rc.Left := FLeftMargin + FCharWidth * FScreen.FCol;
rc.Right := rc.Left + FCharWidth;
{$ENDIF}
InvalidateRect(Handle, @rc, FALSE);
FScreen.InvClear;
if FCaretCreated then begin
ShowCaret(Handle);
FCaretShown := TRUE;
end;
SetCaret;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomEmulVT.SnapPixelToRow(Y : Integer) : Integer;
var
nRow : Integer;
begin
nRow := PixelToRow(Y);
{$IFDEF CHAR_ZOOM}
Result := FTopMargin + FLinePos[nRow];
{$ELSE}
Result := FTopMargin + nRow * FLineHeight;
{$ENDIF}
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomEmulVT.SnapPixelToCol(X : Integer) : Integer;
var
nCol : Integer;
begin
nCol := PixelToCol(X);
{$IFDEF CHAR_ZOOM}
Result := FLeftMargin + FCharPos[nCol];
{$ELSE}
Result := FLeftMargin + nCol * FCharWidth;
{$ENDIF}
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomEmulVT.PixelToRow(Y : Integer) : Integer;
var
nRow : Integer;
begin
{$IFDEF CHAR_ZOOM}
nRow := FScreen.FRowCount - 1;
while (nRow > 0) and ((Y - FTopMargin) < FLinePos[nRow]) do
Dec(nRow);
{$ELSE}
nRow := (Y - FTopMargin) div FLineHeight;
{$ENDIF}
if nRow < 0 then
nRow := 0;
Result := nRow;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function TCustomEmulVT.PixelToCol(X : Integer) : Integer;
var
nCol : Integer;
begin
{$IFDEF CHAR_ZOOM}
nCol := FScreen.FColCount - 1;
while (X - FLeftMargin) < FCharPos[nCol] do
Dec(nCol);
{$ELSE}
nCol := (X - FLeftMargin) div FCharWidth;
{$ENDIF}
if nCol < 0 then
nCol := 0;
Result := nCol;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ This procedure will paint graphic char from the OEM charset (lines, }
{ corners, T and other like) using GDI functions. This will result in }
{ autosized characters, necessary for example to draw a frame when zoom }
{ affect character and line spacing. }
procedure TCustomEmulVT.PaintGraphicChar(
DC : HDC;
X, Y : Integer;
rc : PRect;
ch : Char);
const
OneSpace : Char = ' ';
var
X1, X2, X3 : Integer;
Y1, Y2, Y3 : Integer;
Co : TColor;
begin
ExtTextOut(DC,
X, Y,
ETO_OPAQUE or ETO_CLIPPED, rc,
@OneSpace, 1, nil);
X1 := X;
X3 := rc^.Right;
X2 := (X1 + X3) div 2;
Y1 := rc^.Top;
Y3 := rc^.Bottom;
Y2 := (Y1 + Y3) div 2;
case Ch of
#$C4: begin { Horizontal single line }
Canvas.MoveTo(X1, Y2);
Canvas.LineTo(X3, Y2);
end;
#$B3: begin { Vertical single line }
Canvas.MoveTo(X2, Y1);
Canvas.LineTo(X2, Y3);
end;
#$DA: begin { Upper Left Single Corner }
Canvas.MoveTo(X3, Y2);
Canvas.LineTo(X2, Y2);
Canvas.LineTo(X2, Y3);
end;
#$C0: begin { Bottom Left Single Corner }
Canvas.MoveTo(X2, Y1);
Canvas.LineTo(X2, Y2);
Canvas.LineTo(X3, Y2);
end;
#$C1: begin { Reverse T }
Canvas.MoveTo(X2, Y1);
Canvas.LineTo(X2, Y2);
Canvas.MoveTo(X1, Y2);
Canvas.LineTo(X3, Y2);
end;
#$C2: begin { T }
Canvas.MoveTo(X2, Y3);
Canvas.LineTo(X2, Y2);
Canvas.MoveTo(X1, Y2);
Canvas.LineTo(X3, Y2);
end;
#$C3: begin { Left T }
Canvas.MoveTo(X2, Y1);
Canvas.LineTo(X2, Y3);
Canvas.MoveTo(X2, Y2);
Canvas.LineTo(X3, Y2);
end;
#$B4: begin { Right T }
Canvas.MoveTo(X2, Y1);
Canvas.LineTo(X2, Y3);
Canvas.MoveTo(X2, Y2);
Canvas.LineTo(X1 - 1, Y2);
end;
#$BF: begin { Top Right Single Corner }
Canvas.MoveTo(X1, Y2);
Canvas.LineTo(X2, Y2);
Canvas.LineTo(X2, Y3);
end;
#$D9: begin { Bottom Right Single Corner }
Canvas.MoveTo(X1, Y2);
Canvas.LineTo(X2, Y2);
Canvas.LineTo(X2, Y1 - 1);
end;
#$D6: begin { Upper Left Single/Double Corner }
Canvas.MoveTo(X3, Y2);
Canvas.LineTo(X2 - 1, Y2);
Canvas.LineTo(X2 - 1, Y3);
Canvas.MoveTo(X2 + 1, Y2);
Canvas.LineTo(X2 + 1, Y3);
end;
#$D3: begin { Bottom Left Single/Double Corner }
Canvas.MoveTo(X2 - 1, Y1);
Canvas.LineTo(X2 - 1, Y2);
Canvas.LineTo(X3, Y2);
Canvas.MoveTo(X2 + 1, Y1);
Canvas.LineTo(X2 + 1, Y2);
end;
#$B7: begin { Top Right Single/Double Corner }
Canvas.MoveTo(X1, Y2);
Canvas.LineTo(X2 + 1, Y2);
Canvas.LineTo(X2 + 1, Y3);
Canvas.MoveTo(X2 - 1, Y2);
Canvas.LineTo(X2 - 1, Y3);
end;
#$BD: begin { Bottom Right Single/Double Corner }
Canvas.MoveTo(X2 + 1, Y1);
Canvas.LineTo(X2 + 1, Y2);
Canvas.LineTo(X1 - 1, Y2);
Canvas.MoveTo(X2 - 1, Y1);
Canvas.LineTo(X2 - 1, Y2);
end;
#$D5: begin { Upper Left Double/Single Corner }
Canvas.MoveTo(X3, Y2 - 1);
Canvas.LineTo(X2, Y2 - 1);
Canvas.LineTo(X2, Y3);
Canvas.MoveTo(X3, Y2 + 1);
Canvas.LineTo(X2, Y2 + 1);
end;
#$D4: begin { Bottom Left Double/Single Corner }
Canvas.MoveTo(X2, Y1);
Canvas.LineTo(X2, Y2 + 1);
Canvas.LineTo(X3, Y2 + 1);
Canvas.MoveTo(X2, Y2 - 1);
Canvas.LineTo(X3, Y2 - 1);
end;
#$B8: begin { Top Right Double/Single Corner }
Canvas.MoveTo(X1, Y2 - 1);
Canvas.LineTo(X2, Y2 - 1);
Canvas.LineTo(X2, Y3);
Canvas.MoveTo(X1, Y2 + 1);
Canvas.LineTo(X2, Y2 + 1);
end;
#$BE: begin { Bottom Right Double/Single Corner }
Canvas.MoveTo(X2, Y1);
Canvas.LineTo(X2, Y2 + 1);
Canvas.LineTo(X1 - 1, Y2 + 1);
Canvas.MoveTo(X1, Y2 - 1);
Canvas.LineTo(X2, Y2 - 1);
end;
#$CD: begin { Horizontal Double line }
Canvas.MoveTo(X1, Y2 + 1);
Canvas.LineTo(X3, Y2 + 1);
Canvas.MoveTo(X1, Y2 - 1);
Canvas.LineTo(X3, Y2 - 1);
end;
#$BA: begin { Vertical Double line }
Canvas.MoveTo(X2 + 1, Y1);
Canvas.LineTo(X2 + 1, Y3);
Canvas.MoveTo(X2 - 1, Y1);
Canvas.LineTo(X2 - 1, Y3);
end;
#$D1: begin { T Top Horizontal Double line }
Canvas.MoveTo(X1, Y2 + 1);
Canvas.LineTo(X3, Y2 + 1);
Canvas.MoveTo(X1, Y2 - 1);
Canvas.LineTo(X3, Y2 - 1);
Canvas.MoveTo(X2, Y2 + 1);
Canvas.LineTo(X2, Y3);
end;
#$CF: begin { T Bottom Horizontal Double line }
Canvas.MoveTo(X1, Y2 + 1);
Canvas.LineTo(X3, Y2 + 1);
Canvas.MoveTo(X1, Y2 - 1);
Canvas.LineTo(X3, Y2 - 1);
Canvas.MoveTo(X2, Y2 - 1);
Canvas.LineTo(X2, Y1);
end;
#$C6: begin { T Left Horizontal Double line }
Canvas.MoveTo(X2, Y2 + 1);
Canvas.LineTo(X3, Y2 + 1);
Canvas.MoveTo(X2, Y2 - 1);
Canvas.LineTo(X3, Y2 - 1);
Canvas.MoveTo(X2, Y1);
Canvas.LineTo(X2, Y3);
end;
#$B5: begin { T Right Horizontal Double line }
Canvas.MoveTo(X1, Y2 + 1);
Canvas.LineTo(X2, Y2 + 1);
Canvas.MoveTo(X1, Y2 - 1);
Canvas.LineTo(X2, Y2 - 1);
Canvas.MoveTo(X2, Y1);
Canvas.LineTo(X2, Y3);
end;
#$C9: begin { Upper Left Double Corner }
Canvas.MoveTo(X3, Y2 - 1);
Canvas.LineTo(X2 - 1, Y2 - 1);
Canvas.LineTo(X2 - 1, Y3);
Canvas.MoveTo(X3, Y2 + 1);
Canvas.LineTo(X2 + 1, Y2 + 1);
Canvas.LineTo(X2 + 1, Y3);
end;
#$C8: begin { Bottom Left Double Corner }
Canvas.MoveTo(X2 - 1, Y1);
Canvas.LineTo(X2 - 1, Y2 + 1);
Canvas.LineTo(X3, Y2 + 1);
Canvas.MoveTo(X2 + 1, Y1);
Canvas.LineTo(X2 + 1, Y2 - 1);
Canvas.LineTo(X3, Y2 - 1);
end;
#$BB: begin { Top Right Double Corner }
Canvas.MoveTo(X1, Y2 - 1);
Canvas.LineTo(X2 + 1, Y2 - 1);
Canvas.LineTo(X2 + 1, Y3);
Canvas.MoveTo(X1, Y2 + 1);
Canvas.LineTo(X2 - 1, Y2 + 1);
Canvas.LineTo(X2 - 1, Y3);
end;
#$BC: begin { Bottom Right Double Corner }
Canvas.MoveTo(X2 - 1, Y1);
Canvas.LineTo(X2 - 1, Y2 - 1);
Canvas.LineTo(X1 - 1, Y2 - 1);
Canvas.MoveTo(X2 + 1, Y1);
Canvas.LineTo(X2 + 1, Y2 + 1);
Canvas.LineTo(X1 - 1, Y2 + 1);
end;
#$CC: begin { Double left T }
Canvas.MoveTo(X2 - 1, Y1);
Canvas.LineTo(X2 - 1, Y3);
Canvas.MoveTo(X2 + 1, Y1);
Canvas.LineTo(X2 + 1, Y2 - 1);
Canvas.LineTo(X3, Y2 - 1);
Canvas.MoveTo(X3, Y2 + 1);
Canvas.LineTo(X2 + 1, Y2 + 1);
Canvas.LineTo(X2 + 1, Y3);
end;
#$B9: begin { Double Right T }
Canvas.MoveTo(X2 + 1, Y1);
Canvas.LineTo(X2 + 1, Y3);
Canvas.MoveTo(X2 - 1, Y1);
Canvas.LineTo(X2 - 1, Y2 - 1);
Canvas.LineTo(X1 - 1, Y2 - 1);
Canvas.MoveTo(X1, Y2 + 1);
Canvas.LineTo(X2 - 1, Y2 + 1);
Canvas.LineTo(X2 - 1, Y3);
end;
#$C7: begin { Double T Single Left }
Canvas.MoveTo(X2 + 1, Y1);
Canvas.LineTo(X2 + 1, Y3);
Canvas.MoveTo(X2 - 1, Y1);
Canvas.LineTo(X2 - 1, Y3);
Canvas.MoveTo(X2 + 1, Y2);
Canvas.LineTo(X3, Y2);
end;
#$B6: begin { Double T Single Right }
Canvas.MoveTo(X2 + 1, Y1);
Canvas.LineTo(X2 + 1, Y3);
Canvas.MoveTo(X2 - 1, Y1);
Canvas.LineTo(X2 - 1, Y3);
Canvas.MoveTo(X2 - 1, Y2);
Canvas.LineTo(X1 - 1, Y2);
end;
#$D2: begin { Single T Double Top }
Canvas.MoveTo(X1, Y2);
Canvas.LineTo(X3, Y2);
Canvas.MoveTo(X2 - 1, Y2);
Canvas.LineTo(X2 - 1, Y3);
Canvas.MoveTo(X2 + 1, Y2);
Canvas.LineTo(X2 + 1, Y3);
end;
#$D0: begin { Single T Double Bottom }
Canvas.MoveTo(X1, Y2);
Canvas.LineTo(X3, Y2);
Canvas.MoveTo(X2 - 1, Y2);
Canvas.LineTo(X2 - 1, Y1);
Canvas.MoveTo(X2 + 1, Y2);
Canvas.LineTo(X2 + 1, Y1);
end;
#$DB: begin { Full Block }
Canvas.Rectangle(X1, Y1, X3, Y3);
end;
#$DC: begin { Half Bottom Block }
Canvas.Rectangle(X1, Y2, X3, Y3);
end;
#$DD: begin { Half Left Block }
Canvas.Rectangle(X1, Y1, X2, Y3);
end;
#$DE: begin { Half Right Block }
Canvas.Rectangle(X2, Y1, X3, Y3);
end;
#$DF: begin { Half Top Block }
Canvas.Rectangle(X1, Y1, X2, Y2);
end;
#$C5: begin { Single Cross }
Canvas.MoveTo(X1, Y2);
Canvas.LineTo(X3, Y2);
Canvas.MoveTo(X2, Y1);
Canvas.LineTo(X2, Y3);
end;
#$CE: begin { Double Cross }
Canvas.MoveTo(X1, Y2 - 1);
Canvas.LineTo(X2 - 1, Y2 - 1);
Canvas.LineTo(X2 - 1, Y1);
Canvas.MoveTo(X1, Y2 + 1);
Canvas.LineTo(X2 - 1, Y2 + 1);
Canvas.LineTo(X2 - 1, Y3);
Canvas.MoveTo(X2 + 1, Y1);
Canvas.LineTo(X2 + 1, Y2 - 1);
Canvas.LineTo(X3, Y2 - 1);
Canvas.MoveTo(X2 + 1, Y3);
Canvas.LineTo(X2 + 1, Y2 + 1);
Canvas.LineTo(X3, Y2 + 1);
end;
#$D8: begin { Cross Double Horizontal Single vertical }
Canvas.MoveTo(X1, Y2 + 1);
Canvas.LineTo(X3, Y2 + 1);
Canvas.MoveTo(X1, Y2 - 1);
Canvas.LineTo(X3, Y2 - 1);
Canvas.MoveTo(X2, Y1);
Canvas.LineTo(X2, Y3);
end;
#$D7: begin { Cross Single Horizontal Double Vertical }
Canvas.MoveTo(X2 + 1, Y1);
Canvas.LineTo(X2 + 1, Y3);
Canvas.MoveTo(X2 - 1, Y1);
Canvas.LineTo(X2 - 1, Y3);
Canvas.MoveTo(X1, Y2);
Canvas.LineTo(X3, Y2);
end;
#$CA: begin { Double T bottom }
Canvas.MoveTo(X1, Y2 - 1);
Canvas.LineTo(X2 - 1, Y2 - 1);
Canvas.LineTo(X2 - 1, Y1);
Canvas.MoveTo(X2 + 1, Y1);
Canvas.LineTo(X2 + 1, Y2 - 1);
Canvas.LineTo(X3, Y2 - 1);
Canvas.MoveTo(X1, Y2 + 1);
Canvas.LineTo(X3, Y2 + 1);
end;
#$CB: begin { Double T }
Canvas.MoveTo(X1, Y2 + 1);
Canvas.LineTo(X2 - 1, Y2 + 1);
Canvas.LineTo(X2 - 1, Y3);
Canvas.MoveTo(X2 + 1, Y3);
Canvas.LineTo(X2 + 1, Y2 + 1);
Canvas.LineTo(X3, Y2 + 1);
Canvas.MoveTo(X1, Y2 - 1);
Canvas.LineTo(X3, Y2 - 1);
end;
#$B0: begin
Co := Canvas.Pen.Color;
for Y := Y1 to Y3 do begin
X := X1 + (Y mod 3);
while X < X3 do begin
Canvas.Pixels[X, Y] := Co;
X := X + 3;
end;
end;
end;
#$B1: begin
Co := Canvas.Pen.Color;
for Y := Y1 to Y3 do begin
X := X1 + (Y and 1);
while X < X3 do begin
Canvas.Pixels[X, Y] := Co;
X := X + 2;
end;
end;
end;
#$B2: begin
Co := Canvas.Pen.Color;
for Y := Y1 to Y3 do begin
X := X1 + (Y mod 3);
while X < X3 do begin
Canvas.Pixels[X, Y] := Co;
Inc(X);
if X < X3 then
Canvas.Pixels[X, Y] := Co;
Inc(X);
Inc(X);
end;
end;
end;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.PaintOneLine(
DC : HDC;
Y, Y1 : Integer;
const Line : TLine;
nColFrom : Integer;
nColTo : Integer;
Blank : Boolean);
var
rc : TRect;
nCnt : Integer;
nAtt : Byte;
X : Integer;
nChr : Integer;
Ch : Char;
const
BlankLine : array [0..MAX_COL] of char = '';
begin
nAtt := Line.Att[nColFrom];
{ if nAtt = $0B then
X := 0; }
{
SetBkColor(DC, PALETTEINDEX(nAtt div $0F));
SetTextColor(DC, PALETTEINDEX(nAtt and $0F));
}
if not FMonoChrome then begin
with FPaletteEntries[(nAtt shr 4) and $0F] do
SetBkColor(DC, PALETTERGB(peRed, peGreen, peBlue));
with FPaletteEntries[nAtt and $0F] do begin
SetTextColor(DC, PALETTERGB(peRed, peGreen, peBlue));
Canvas.Pen.Color := PALETTERGB(peRed, peGreen, peBlue);
Canvas.Brush.Color := PALETTERGB(peRed, peGreen, peBlue);
end;
end
else begin
if (nAtt div $0F) <> 0 then
SetBkColor(DC, RGB(127, 127, 127))
else
SetBkColor(DC, RGB(255, 255, 255));
if (nAtt and $0F) <> 0 then
SetTextColor(DC, RGB(0, 0, 0))
else
SetTextColor(DC, RGB(255, 255, 255));
end;
nCnt := nColTo - nColFrom;
nChr := 0;
{$IFDEF SINGLE_CHAR_PAINT}
while nChr < nCnt do begin
{$IFDEF CHAR_ZOOM}
X := FLeftMargin + FCharPos[nColFrom + nChr];
rc.Top := Y + FInternalLeading;
rc.Bottom := Y1 + FInternalLeading;
rc.Left := X;
rc.Right := FLeftMargin + FCharPos[nColFrom + nChr + 1];
{$ELSE}
X := FLeftMargin + (nColFrom + nChr) * FCharWidth;
rc.Top := Y + FInternalLeading;
rc.Bottom := Y1 + FInternalLeading;
rc.Left := X;
rc.Right := rc.Left + FCharWidth;
{$ENDIF}
if (nColFrom + nChr) = 0 then
rc.Left := rc.Left - FLeftMargin;
if (nColFrom + nChr) >= FScreen.FColCount then
rc.Right := rc.Right + FRightMargin;
if Blank then
Ch := ' '
else
Ch := Line.Txt[nColFrom + nChr];
if FGraphicDraw and
(FScreen.FXlatOutputTable = @ibm_iso8859_1_G0) and
(Ch >= #$B0) and (Ch <= #$DF) and
(Ch in [#$B3, #$C4, #$DA, #$C0, #$C1, #$C2, #$C3, #$B4, #$BF, #$D9,
#$DB, #$DC, #$DD, #$DE, #$DF,
#$BA, #$CD, #$C9, #$C8, #$BB, #$BC,
#$CC, #$B9, #$C7, #$B6, #$D2, #$D0,
#$D5, #$D4, #$B8, #$BE,
#$C6, #$D1, #$B5, #$CF,
#$D6, #$B7, #$D3, #$BD,
#$C5, #$CE, #$D8, #$D7, #$CA, #$CB,
#$B0, #$B1, #$B2]) then
PaintGraphicChar(DC, X, Y, @rc, Ch)
else
ExtTextOut(DC, X, Y, ETO_OPAQUE or ETO_CLIPPED, @rc, @Ch, 1, nil);
Inc(nChr);
end;
{$ELSE}
{$IFDEF CHAR_ZOOM}
X := LeftMargin + FCharPos[nColFrom];
rc.Top := Y + FInternalLeading;
rc.Bottom := Y1 + FInternalLeading;
rc.Left := X;
rc.Right := LeftMargin + FCharPos[nColFrom + nCnt];
{$ELSE}
X := LeftMargin + nColFrom * FCharWidth;
rc.Top := Y + FInternalLeading;
rc.Bottom := Y1 + FInternalLeading;
rc.Left := X;
rc.Right := rc.Left + nCnt * FCharWidth;
{$ENDIF}
if nColFrom = 0 then
rc.Left := rc.Left - LeftMargin;
if nColTo >= FScreen.FColCount then
rc.Right := rc.Right + RightMargin;
if Blank then
ExtTextOut(DC,
X, Y,
ETO_OPAQUE or ETO_CLIPPED, @rc,
@BlankLine[0], nCnt, nil)
else
ExtTextOut(DC,
X, Y,
ETO_OPAQUE or ETO_CLIPPED, @rc,
@Line.Txt[nColFrom], nCnt, nil);
{$ENDIF}
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function WRectangle(DC: HDC; X1, Y1, X2, Y2 : Integer) : LongBool;
begin
{$IFDEF USEWINDOWS}
Result := Windows.Rectangle(DC, X1, Y1, X2, Y2);
{$ELSE}
Result := Winprocs.Rectangle(DC, X1, Y1, X2, Y2);
{$ENDIF}
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TCustomEmulVT.WMPaint(var Message: TWMPaint);
var
DC : HDC;
PS : TPaintStruct;
Y, Y1 : Integer;
rc : TRect;
OldPen : THandle;
OldBrush : THandle;
OldFont : THandle;
rcPaint : TRect;
DrawRct : TRect;
nRow : Integer;
nCol : Integer;
nColFrom : Integer;
Line : TLine;
BackBrush : HBrush;
BackIndex : Integer;
begin
{ This may be a bit of overkill but we have to keep the scrollbar tracking
with the number of lines visible on the screen. The calling program can
change the Height of the screen and we don't have a good way to know that.
This routine will get called whenever the screen gets updated so it is a
good time to update the scrollbar. }
AdjustScrollBar;
if not GetUpdateRect(WindowHandle, rc, FALSE) then
Exit;
BackBrush := 0;
OldBrush := 0;
DC := Message.DC;
if DC = 0 then
DC := BeginPaint(WindowHandle, PS);
try
if not FMonoChrome then begin
SelectPalette(DC, FPal, FALSE);
RealizePalette(DC);
if FMarginColor = -1 then
BackIndex := FScreen.FAttribute div $0F
else
BackIndex := FMarginColor mod NumPaletteEntries;
with FPaletteEntries[BackIndex] do
BackBrush := CreateSolidBrush(PALETTERGB(peRed, peGreen, peBlue));
OldBrush := SelectObject(DC, BackBrush);
end;
{$IFDEF USEWINDOWS}
Windows.GetClientRect(WindowHandle, DrawRct);
{$ELSE}
WinProcs.GetClientRect(WindowHandle, DrawRct);
{$ENDIF}
rcPaint := PS.rcPaint;
rc.Left := 2;
rc.Right := DrawRct.Right - 2;
nRow := PixelToRow(rcPaint.top);
nRow := nRow - 1;
if nRow < 0 then
nRow := 0;
{$IFDEF CHAR_ZOOM}
Y := FTopMargin + FLinePos[nRow];
Y1 := FTopMargin + FLinePos[nRow + 1];
{$ELSE}
Y := FTopMargin + nRow * FLineHeight;
Y1 := Y + FLineHeight;
{$ENDIF}
if rcPaint.Top <= FTopMargin then begin
OldPen := SelectObject(DC, GetStockObject(NULL_PEN));
WRectangle(DC, rcPaint.left, rcPaint.Top,
rcPaint.Right + 1,
FTopMargin + FInternalLeading + 1);
SelectObject(DC, OldPen);
end;
if (nRow = 0) and (FInternalLeading > 0) then begin
OldPen := SelectObject(DC, GetStockObject(NULL_PEN));
WRectangle(DC, rcPaint.left, rcPaint.Top,
rcPaint.Right + 1,
Y + FInternalLeading + 1);
SelectObject(DC, OldPen);
end;
OldFont := SelectObject(DC, FFont.Handle);
nRow := nRow + FTopLine;
while nRow < FScreen.FRowCount do begin
rc.Top := Y;
rc.Bottom := Y + FLineHeight;
if rc.Bottom > (DrawRct.Bottom - FBottomMargin) then begin
OldPen := SelectObject(DC, GetStockObject(NULL_PEN));
WRectangle(DC, rc.Left - 2, rc.Top, rc.Right + 1,
DrawRct.Bottom - 1);
SelectObject(DC, OldPen);
Break;
end;
Line := FScreen.Lines[nRow];
nCol := 0;
nColFrom := 0;
while nCol < FScreen.FColCount do begin
while (nCol < FScreen.FColCount) and
(Line.Att[nCol] = Line.Att[nColFrom]) do
Inc(nCol);
PaintOneLine(DC, Y, Y1, Line, nColFrom, nCol, FALSE);
nColFrom := nCol;
end;
nRow := nRow + 1;
{$IFDEF CHAR_ZOOM}
Y := FTopMargin + FLinePos[nRow - FTopLine];
Y1 := FTopMargin + FLinePos[nRow + 1 - FTopLine];
{$ELSE}
Y := Y + FLineHeight;
Y1 := Y + FLineHeight;
{$ENDIF}
if Y > rcPaint.Bottom then
Break;
end;
{ Fill region between last text line and bottom of the window }
OldPen := SelectObject(DC, GetStockObject(NULL_PEN));
if (FScreen.FRowCount - FTopLine) <= MAX_ROW then begin { WM + SE 09/08/00 }
WRectangle(DC, rc.Left - 2,
FTopMargin + FLinePos[FScreen.FRowCount - FTopLine]{ + 1},
rc.Right + 3, DrawRct.Bottom + 1);
end;
SelectObject(DC, OldPen);
{$IFDEF CHAR_ZOOM}
if (FLeftMargin + FCharPos[FScreen.FColCount]) < rc.Right then begin
OldPen := SelectObject(DC, GetStockObject(NULL_PEN));
WRectangle(DC, FLeftMargin + FCharPos[FScreen.FColCount],
FTopMargin, { 09/03/99 }
rcPaint.Right + 1, DrawRct.Bottom + 1);
SelectObject(DC, OldPen);
end;
{$ELSE}
if (FLeftMargin + FScreen.FColCount * FCharWidth) < rc.Right then begin
OldPen := SelectObject(DC, GetStockObject(NULL_PEN));
WRectangle(DC, FLeftMargin + FScreen.FColCount * FCharWidth,
FTopMargin, rc.Right + 1, DrawRct.Bottom - 1);
SelectObject(DC, OldPen);
end;
{$ENDIF}
if FSelectRect.Top <> -1 then begin
SelectObject(DC, GetStockObject(NULL_BRUSH));
SelectObject(DC, GetStockObject(BLACK_PEN));
WRectangle(DC, FSelectRect.Left,
FSelectRect.Top,
FSelectRect.Right + 1,
FSelectRect.Bottom - 1);
SelectObject(DC, GetStockObject(WHITE_PEN));
WRectangle(DC, FSelectRect.Left - 1,
FSelectRect.Top - 1,
FSelectRect.Right + 2,
FSelectRect.Bottom);
end;
SelectObject(DC, OldFont);
if OldBrush <> 0 then
SelectObject(DC, OldBrush);
if BackBrush <> 0 then
DeleteObject(BackBrush);
finally
if Message.DC = 0 then
EndPaint(WindowHandle, PS);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
end.
|
program TM1638_demo;
{$mode objfpc}{$H+}
{ Raspberry Pi Application }
{ Add your program code below, add additional units to the "uses" section if }
{ required and create new units by selecting File, New Unit from the menu. }
{ }
{ To compile your program select Run, Compile (or Run, Build) from the menu. }
uses
RaspberryPi,
GlobalConfig,
GlobalConst,
GlobalTypes,
Platform,
Threads,
SysUtils,
Classes,
Ultibo,
Console,
TM1638;
var
TM1630Ac: TTM1630;
Handle: TWindowHandle;
function Counting(): Byte;
var
position: Byte;
const {0} {1} {2} {3} {4} {5} {6} {7} {8} {9}
digits: array[0..9] of Byte = ($3f, $06, $5b, $4f, $66, $6d, $7d, $07, $7f, $6f);
digit: Byte = 0;
begin
TM1630Ac.SendCommand($40);
TM1630Ac.Start();
TM1630Ac.ShiftOut(soLsbFirst, $C0);
for position := 0 to 7 do
begin
TM1630Ac.ShiftOut(soLsbFirst, digits[digit]);
TM1630Ac.ShiftOut(soLsbFirst, $00);
end;
TM1630Ac.Stop();
digit := (digit + 1) mod 10;
if digit = 0 then
Result := 1
else
Result := 0;
end;
function Scroll(): Byte;
var
scrollLength, i, c: Byte;
const
scrollText: array [0..31] of Byte =
(* *)(* *)(* *)(* *)(* *)(* *)(* *)(* *)
($00, $00, $00, $00, $00, $00, $00, $00,
(*H*)(*E*)(*L*)(*L*)(*O*)(*.*)(*.*)(*.*)
$76, $79, $38, $38, $3f, $80, $80, $80,
(* *)(* *)(* *)(* *)(* *)(* *)(* *)(* *)
$00, $00, $00, $00, $00, $00, $00, $00,
(*H*)(*E*)(*L*)(*L*)(*O*)(*.*)(*.*)(*.*)
$76, $79, $38, $38, $3f, $80, $80, $80);
index: Byte = 0;
begin
scrollLength := Length(scrollText);
TM1630Ac.SendCommand($40);
TM1630Ac.Start();
TM1630Ac.ShiftOut(soLsbFirst, $C0);
for i := 0 to 7 do
begin
c := scrollText[(index + i) mod scrollLength];
TM1630Ac.ShiftOut(soLsbFirst, c);
if c <> 0 then
TM1630Ac.ShiftOut(soLsbFirst, 1)
else
TM1630Ac.ShiftOut(soLsbFirst, 0);
end;
TM1630Ac.Stop();
index := (index + 1) mod (scrollLength shl 1);
if index = 0 then
Result := 1
else
Result := 0;
end;
procedure Buttons();
var
textStartPos, position, buttons, mask: Byte;
const
promptText: array [0..31] of Byte =
(*P*) (*r*) (*E*) (*S*) (*S*) (* *) (* *) (* *)
($73, $50, $79, $6d, $6d, $00, $00, $00,
(* *) (* *) (* *) (* *) (* *) (* *) (* *) (* *)
$00, $00, $00, $00, $00, $00, $00, $00,
(*b*) (*u*) (*t*) (*t*) (*o*) (*n*) (*S*) (* *)
$7c, $1c, $78, $78, $5c, $54, $6d, $00,
(* *) (* *) (* *) (* *) (* *) (* *) (* *) (* *)
$00, $00, $00, $00, $00, $00, $00, $00);
block: Byte = 0;
begin
textStartPos := (block div 4) shl 3;
for position := 0 to 7 do
begin
TM1630Ac.SendCommand($44);
TM1630Ac.Start();
TM1630Ac.ShiftOut(soLsbFirst, $C0 + (position << 1));
TM1630Ac.ShiftOut(soLsbFirst, promptText[textStartPos + position]);
TM1630Ac.Stop();
end;
block := (block + 1) mod 16;
buttons := TM1630Ac.ReadButtons();
for position := 0 to 7 do
begin
mask := $1 shl position;
if buttons and mask = 0 then
TM1630Ac.SetLed(0, position)
else
TM1630Ac.SetLed(1, position);
end;
end;
procedure Setup();
begin
{Let's create a console window again but this time on the left side of the screen}
Handle := ConsoleWindowCreate(ConsoleDeviceGetDefault, CONSOLE_POSITION_FULL, True);
{To prove that worked let's output some text on the console window}
ConsoleWindowWriteLn(Handle, 'TM1638 demo');
try
TM1630Ac := TTM1630.Create;
except
on E: Exception do
begin
TM1630Ac := nil;
ConsoleWindowWriteLn(Handle, 'Setup() error: ' + E.Message);
end;
end;
end;
const
COUNTING_MODE = 0;
SCROLL_MODE = 1;
BUTTON_MODE = 2;
procedure Loop();
const
mode: Byte = COUNTING_MODE;
begin
try
case mode of
COUNTING_MODE: Inc(mode, Counting());
SCROLL_MODE: Inc(mode, Scroll());
BUTTON_MODE: Buttons();
end;
Sleep(200);
except
on E: Exception do
begin
TM1630Ac.Free;
TM1630Ac := nil;
ConsoleWindowWriteLn(Handle, 'Loop() error: ' + E.Message);
end;
end;
end;
begin
Setup();
while Assigned(TM1630Ac) do
Loop();
ConsoleWindowWriteLn(Handle, '');
ConsoleWindowWriteLn(Handle, 'Bye');
{Halt the main thread if we ever get to here}
ThreadHalt(0);
end.
|
unit thread_heat;
interface
uses
SysUtils, Classes, Windows, ActiveX, Forms, SyncObjs;
type
// Здесь необходимо описать класс TThreadMain:
TThreadHeat = class(TThread)
private
{ Private declarations }
protected
procedure Execute; override;
end;
var
ThreadHeat: TThreadHeat;
// {$DEFINE DEBUG}
procedure WrapperHeat;
// обертка для синхронизации и выполнения с другим потоком
implementation
uses
main, settings, logging, chart, sql;
procedure TThreadHeat.Execute;
begin
CoInitialize(nil);
while True do
begin
Synchronize(WrapperHeat);
sleep(1000);
// при уменьшении надо увеличивать счетчик в charts для правильного затирания графиков
end;
CoUninitialize;
end;
procedure WrapperHeat;
begin
try
Application.ProcessMessages; // следующая операция не тормозит интерфейс
// SqlReadCurrentHeat;
except
on E: Exception do
SaveLog('error' + #9#9 + E.ClassName + ', с сообщением: ' + E.Message);
end;
end;
// При загрузке программы класс будет создаваться
initialization
// создаем поток
ThreadHeat := TThreadHeat.Create(True);
ThreadHeat.Priority := tpNormal;
ThreadHeat.FreeOnTerminate := True;
// При закрытии программы уничтожаться
finalization
ThreadHeat.Terminate;
end.
|
unit Global;
interface
uses
Windows, Messages, Dialogs, controls;
resourceString
rsArticuloNoValido = 'Articulo %s no es valido';
rsCantidadCero = 'Cantidad no puede ser 0';
rsTasaIVA = 'No se pueden incluir en la misma factura articulos con distintas tasas de IVA';
rsPrecioNulo = 'Por favor, indique precio de venta';
rsErrorGrabacion = 'Error al grabar Factura';
rsDescuentoErroneo = 'Porcentaje de Descuento es erroneo';
rsConfirmaEliminar = 'Confirma eliminacion ?';
type
usuNivel = ( Admin, AdminEsp, Gerente, GerenteEsp, Usuario, UsuarioEsp );
function VerificaCUIT( sValor: string ): boolean;
function confirmaEliminar: boolean;
var
FUsuario: integer;
implementation
function VerificaCUIT( sValor: string ): boolean;
const
Tabla: array[ 1..11 ] of integer = ( 5,4,3,2,7,6,5,4,3,2,1 );
var
Acumulado, x: integer;
begin
Result := false;
// RUTINA DE VERIFICACION DE NUMERO DE CUIT */
// Maxima cantidad de digitos en el nro.de cuit */
// Tabla de pesos para el calculo del cuit */
// static char tbl_peso[]={5,4,3,2,7,6,5,4,3,2,1};
if Length( sValor ) < 11 then
exit;
Acumulado := 0;
for x:=1 to 11 do
Acumulado := Acumulado + (( Ord( sValor[ x ])-48 ) * Tabla[ x ] );
if ( Acumulado mod 11 ) = 0 then
Result := true;
end;
function confirmaEliminar: boolean;
begin
Result := MessageDlg( rsConfirmaEliminar, mtWarning, [ mbYes, mbNo ], 0 ) = mrYes;
end;
end.
|
{ Date Created: 5/25/00 5:01:02 PM }
unit InfoPAYECODETable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoPAYECODERecord = record
PCode: String[4];
PDescription: String[30];
PAddress: String[30];
PCityState: String[25];
PZipCode: String[10];
PContact: String[30];
PPhone: String[30];
PTaxID: String[12];
PExpCode: String[5];
End;
TInfoPAYECODEBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoPAYECODERecord
end;
TEIInfoPAYECODE = (InfoPAYECODEPrimaryKey);
TInfoPAYECODETable = class( TDBISAMTableAU )
private
FDFCode: TStringField;
FDFDescription: TStringField;
FDFAddress: TStringField;
FDFCityState: TStringField;
FDFZipCode: TStringField;
FDFContact: TStringField;
FDFPhone: TStringField;
FDFTaxID: TStringField;
FDFExpCode: TStringField;
procedure SetPCode(const Value: String);
function GetPCode:String;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetPAddress(const Value: String);
function GetPAddress:String;
procedure SetPCityState(const Value: String);
function GetPCityState:String;
procedure SetPZipCode(const Value: String);
function GetPZipCode:String;
procedure SetPContact(const Value: String);
function GetPContact:String;
procedure SetPPhone(const Value: String);
function GetPPhone:String;
procedure SetPTaxID(const Value: String);
function GetPTaxID:String;
procedure SetPExpCode(const Value: String);
function GetPExpCode:String;
function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
procedure SetEnumIndex(Value: TEIInfoPAYECODE);
function GetEnumIndex: TEIInfoPAYECODE;
protected
function CreateField( const FieldName : string ): TField;
procedure CreateFields; virtual;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoPAYECODERecord;
procedure StoreDataBuffer(ABuffer:TInfoPAYECODERecord);
property DFCode: TStringField read FDFCode;
property DFDescription: TStringField read FDFDescription;
property DFAddress: TStringField read FDFAddress;
property DFCityState: TStringField read FDFCityState;
property DFZipCode: TStringField read FDFZipCode;
property DFContact: TStringField read FDFContact;
property DFPhone: TStringField read FDFPhone;
property DFTaxID: TStringField read FDFTaxID;
property DFExpCode: TStringField read FDFExpCode;
property PCode: String read GetPCode write SetPCode;
property PDescription: String read GetPDescription write SetPDescription;
property PAddress: String read GetPAddress write SetPAddress;
property PCityState: String read GetPCityState write SetPCityState;
property PZipCode: String read GetPZipCode write SetPZipCode;
property PContact: String read GetPContact write SetPContact;
property PPhone: String read GetPPhone write SetPPhone;
property PTaxID: String read GetPTaxID write SetPTaxID;
property PExpCode: String read GetPExpCode write SetPExpCode;
procedure Validate; virtual;
published
property Active write SetActive;
property EnumIndex: TEIInfoPAYECODE read GetEnumIndex write SetEnumIndex;
end; { TInfoPAYECODETable }
procedure Register;
implementation
function TInfoPAYECODETable.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 { TInfoPAYECODETable.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; { TInfoPAYECODETable.GenerateNewFieldName }
function TInfoPAYECODETable.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; { TInfoPAYECODETable.CreateField }
procedure TInfoPAYECODETable.CreateFields;
begin
FDFCode := CreateField( 'Code' ) as TStringField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFAddress := CreateField( 'Address' ) as TStringField;
FDFCityState := CreateField( 'CityState' ) as TStringField;
FDFZipCode := CreateField( 'ZipCode' ) as TStringField;
FDFContact := CreateField( 'Contact' ) as TStringField;
FDFPhone := CreateField( 'Phone' ) as TStringField;
FDFTaxID := CreateField( 'TaxID' ) as TStringField;
FDFExpCode := CreateField( 'ExpCode' ) as TStringField;
end; { TInfoPAYECODETable.CreateFields }
procedure TInfoPAYECODETable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoPAYECODETable.SetActive }
procedure TInfoPAYECODETable.Validate;
begin
{ Enter Validation Code Here }
end; { TInfoPAYECODETable.Validate }
procedure TInfoPAYECODETable.SetPCode(const Value: String);
begin
DFCode.Value := Value;
end;
function TInfoPAYECODETable.GetPCode:String;
begin
result := DFCode.Value;
end;
procedure TInfoPAYECODETable.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TInfoPAYECODETable.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TInfoPAYECODETable.SetPAddress(const Value: String);
begin
DFAddress.Value := Value;
end;
function TInfoPAYECODETable.GetPAddress:String;
begin
result := DFAddress.Value;
end;
procedure TInfoPAYECODETable.SetPCityState(const Value: String);
begin
DFCityState.Value := Value;
end;
function TInfoPAYECODETable.GetPCityState:String;
begin
result := DFCityState.Value;
end;
procedure TInfoPAYECODETable.SetPZipCode(const Value: String);
begin
DFZipCode.Value := Value;
end;
function TInfoPAYECODETable.GetPZipCode:String;
begin
result := DFZipCode.Value;
end;
procedure TInfoPAYECODETable.SetPContact(const Value: String);
begin
DFContact.Value := Value;
end;
function TInfoPAYECODETable.GetPContact:String;
begin
result := DFContact.Value;
end;
procedure TInfoPAYECODETable.SetPPhone(const Value: String);
begin
DFPhone.Value := Value;
end;
function TInfoPAYECODETable.GetPPhone:String;
begin
result := DFPhone.Value;
end;
procedure TInfoPAYECODETable.SetPTaxID(const Value: String);
begin
DFTaxID.Value := Value;
end;
function TInfoPAYECODETable.GetPTaxID:String;
begin
result := DFTaxID.Value;
end;
procedure TInfoPAYECODETable.SetPExpCode(const Value: String);
begin
DFExpCode.Value := Value;
end;
function TInfoPAYECODETable.GetPExpCode:String;
begin
result := DFExpCode.Value;
end;
procedure TInfoPAYECODETable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('Code, String, 4, N');
Add('Description, String, 30, N');
Add('Address, String, 30, N');
Add('CityState, String, 25, N');
Add('ZipCode, String, 10, N');
Add('Contact, String, 30, N');
Add('Phone, String, 30, N');
Add('TaxID, String, 12, N');
Add('ExpCode, String, 5, N');
end;
end;
procedure TInfoPAYECODETable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, Code, Y, Y, N, N');
end;
end;
procedure TInfoPAYECODETable.SetEnumIndex(Value: TEIInfoPAYECODE);
begin
case Value of
InfoPAYECODEPrimaryKey : IndexName := '';
end;
end;
function TInfoPAYECODETable.GetDataBuffer:TInfoPAYECODERecord;
var buf: TInfoPAYECODERecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PCode := DFCode.Value;
buf.PDescription := DFDescription.Value;
buf.PAddress := DFAddress.Value;
buf.PCityState := DFCityState.Value;
buf.PZipCode := DFZipCode.Value;
buf.PContact := DFContact.Value;
buf.PPhone := DFPhone.Value;
buf.PTaxID := DFTaxID.Value;
buf.PExpCode := DFExpCode.Value;
result := buf;
end;
procedure TInfoPAYECODETable.StoreDataBuffer(ABuffer:TInfoPAYECODERecord);
begin
DFCode.Value := ABuffer.PCode;
DFDescription.Value := ABuffer.PDescription;
DFAddress.Value := ABuffer.PAddress;
DFCityState.Value := ABuffer.PCityState;
DFZipCode.Value := ABuffer.PZipCode;
DFContact.Value := ABuffer.PContact;
DFPhone.Value := ABuffer.PPhone;
DFTaxID.Value := ABuffer.PTaxID;
DFExpCode.Value := ABuffer.PExpCode;
end;
function TInfoPAYECODETable.GetEnumIndex: TEIInfoPAYECODE;
var iname : string;
begin
iname := uppercase(indexname);
if iname = '' then result := InfoPAYECODEPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoPAYECODETable, TInfoPAYECODEBuffer ] );
end; { Register }
function TInfoPAYECODEBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PCode;
2 : result := @Data.PDescription;
3 : result := @Data.PAddress;
4 : result := @Data.PCityState;
5 : result := @Data.PZipCode;
6 : result := @Data.PContact;
7 : result := @Data.PPhone;
8 : result := @Data.PTaxID;
9 : result := @Data.PExpCode;
end;
end;
end. { InfoPAYECODETable }
|
{
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.Resources;
{ Application wide type definitions, constants and resource strings. }
interface
uses
Winapi.Windows, Winapi.Messages,
System.Classes,
Vcl.Graphics,
DDuce.Logger.Interfaces;
type
TVKSet = set of Byte;
var
VK_EDIT_KEYS : TVKSet = [
VK_DELETE,
VK_BACK,
VK_LEFT,
VK_RIGHT,
VK_HOME,
VK_END,
VK_SHIFT,
VK_CONTROL,
VK_SPACE,
Ord('0')..Ord('9'),
Ord('A')..Ord('Z'),
VK_OEM_1..VK_OEM_102,
VK_NUMPAD0..VK_DIVIDE
];
VK_CTRL_EDIT_KEYS : TVKSet = [
VK_INSERT,
VK_DELETE,
VK_LEFT,
VK_RIGHT,
VK_HOME,
VK_END,
Ord('C'),
Ord('X'),
Ord('V'),
Ord('Z')
];
VK_SHIFT_EDIT_KEYS : TVKSet = [
VK_INSERT,
VK_DELETE,
VK_LEFT,
VK_RIGHT,
VK_HOME,
VK_END
];
resourcestring
// message types
SName = 'Name';
SType = 'Type';
SValue = 'Value';
STimestamp = 'Timestamp';
SProcessName = 'ProcessName';
SColor = 'Color';
SBitmap = 'Bitmap';
SComponent = 'Component';
SObject = 'Object';
SPersistent = 'Persistent';
SInterface = 'Interface';
SStrings = 'Strings';
SCheckpoint = 'Checkpoint';
SDataSet = 'DataSet';
SScreenShot = 'ScreenShot';
SText = 'Text';
SAction = 'Action';
SInfo = 'Info';
SWarning = 'Warning';
SError = 'Error';
SException = 'Exception';
SCounter = 'Counter';
SEnter = 'Enter';
SLeave = 'Leave';
STextMessages = 'Text messages';
SNotificationMessages = 'Notification messages';
SValueMessages = 'Value messages';
STraceMessages = 'Trace messages';
STrackMethod = 'Track method';
// settings dialog
SViewSettings = 'View settings';
SDisplaySettings = 'Display settings';
SWatches = 'Watches';
SCallStack = 'Callstack';
SChannelSettings = 'Channel settings';
SGeneralSettings = 'General settings';
SAdvanced = 'Advanced';
SWinIPC = 'WinIPC';
SWinODS = 'OutputDebugString API';
SComPort = 'Serial port';
SZeroMQ = 'ZeroMQ';
const
ALL_MESSAGES = [
lmtInfo,
lmtError,
lmtWarning,
lmtValue,
lmtAlphaColor,
lmtColor,
lmtEnterMethod,
lmtLeaveMethod,
lmtConditional,
lmtCheckpoint,
lmtStrings,
lmtCallStack,
lmtComponent,
lmtObject,
lmtInterface,
lmtPersistent,
lmtException,
lmtBitmap,
lmtHeapInfo,
lmtMemory,
lmtCustomData,
lmtWatch,
lmtCounter,
lmtText,
lmtScreenShot,
lmtDataSet,
lmtAction
];
// channel receiver names
const
RECEIVERNAME_WINIPC = 'WinIPC';
RECEIVERNAME_WINODS = 'WinODS';
RECEIVERNAME_ZEROMQ = 'ZeroMQ';
RECEIVERNAME_MQTT = 'MQTT';
RECEIVERNAME_COMPORT = 'ComPort';
RECEIVERNAME_FILESYSTEM = 'FileSystem';
resourcestring
SReceiverCaptionWinIPC = 'Windows IPC receiver';
SReceiverCaptionWinODS = 'Windows API OutputDebugString receiver';
SReceiverCaptionZeroMQ = 'ZeroMQ subscription receiver';
SReceiverCaptionMQTT = 'MQTT subscription receiver';
SReceiverCaptionComPort = 'ComPort receiver';
SReceiverCaptionFileSystem = 'File system receiver';
// message viewer
const
COLUMN_LEVEL = 0;
COLUMN_MAIN = 1;
COLUMN_VALUENAME = 2;
COLUMN_VALUE = 3;
COLUMN_VALUETYPE = 4;
COLUMN_TIMESTAMP = 5;
{ max. amount of characters allowed to be displayed in the value column of the
logtree. }
MAX_TEXTLENGTH_VALUECOLUMN = 255;
{ TCP port used for debugging another LogViewer instance using ZMQ. }
LOGVIEWER_ZMQ_PORT : Integer = 42134;
implementation
end.
|
unit uDataYxDserver;
interface
uses Classes,FireDAC.Comp.Client,System.SysUtils,SQLFirDACPoolUnit;
type
TYxDSvr = class
private
//数据库链接对象
DATABASE : TFDConnection;
FQry:TFDQuery;
//执行sql语句
function ExeSql(AQuery: TFDQuery; CSQL: string; ExecFlag: Boolean): Boolean;
public
FRet:String;
FError:String; //错误信息
function HelloWorld:Boolean;
constructor Create(AOwner: TComponent);
destructor Destroy; override;
end;
implementation
{ TYxDSvr }
function TYxDSvr.ExeSql(AQuery: TFDQuery; CSQL: string; ExecFlag: Boolean): Boolean;
begin
Result := False;
if not Assigned(DATABASE) then
raise Exception.Create('无数据库连接!请检查!');
if CSQL = '' then
raise Exception.Create('没有SQL语句!请检查!');
AQuery.Connection := DATABASE;
with AQuery do
begin
Close;
Sql.Clear;
Sql.Add(CSQL);
try
if ExecFlag then
ExecSQL
else
Open;
except
on E: Exception do
begin
Close;
FError := '错误信息:' + E.Message + #13#10 +
' SQL:' + CSQL;
Exit;
end;
end;
end;
Result := True;
end;
constructor TYxDSvr.Create(AOwner: TComponent);
begin
DATABASE := DACPool.GetCon(DAConfig);
{ DATABASE:= TFDConnection.Create(nil);
with DATABASE do
begin
ConnectionDefName := 'MSSQL_Pooled';
try
Connected := True;
except
raise Exception.Create('数据库连接失败!请检查数据库配置或者网络链接!');
end;
end; }
FQry:=TFDQuery.Create(nil);
end;
destructor TYxDSvr.Destroy;
begin
DACPool.PutCon(DATABASE);
{if Assigned(DATABASE) then
FreeAndNil(DATABASE); }
if Assigned(FQry) then
FreeAndNil(FQry);
inherited;
end;
function TYxDSvr.HelloWorld: Boolean;
var
CSQL:String;
begin
Result := False;
try
CSQL := 'SELECT GETDATE() Time';
if not ExeSql(FQry,CSQL,False) then Exit;
FRet := 'HelloWorld:'+FQry.FieldByName('Time').AsString;
finally
end;
Result := True;
end;
end.
|
unit UOpcaoimagem;
interface
uses
Windows, System.UITypes, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Buttons, jpeg, AcquireImage;
type
TfrmOpcaoImagem = class(TForm)
edtDescrImagem: TEdit;
Label1: TLabel;
btnOk: TBitBtn;
btnCancelar: TBitBtn;
rgpOpcaoImagem: TRadioGroup;
aiScanearImagem: TAcquireImage;
AcquireImage1: TAcquireImage;
procedure edtDescrImagemExit(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure edtDescrImagemKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
iRet: Integer;
function EscanearImagem: TJpegImage;
end;
var
frmOpcaoImagem : TfrmOpcaoImagem;
implementation
{$R *.dfm}
procedure TfrmOpcaoImagem.edtDescrImagemExit(Sender: TObject);
begin
if btnCancelar.Focused or rgpOpcaoImagem.Focused then
exit;
if Length(edtDescrImagem.Text) = 0 then
begin
MessageDlg('Obrigatório informar uma descrição para a Imagem!', mtWarning, [mbOk], 0);
edtDescrImagem.SetFocus;
end;
end;
procedure TfrmOpcaoImagem.btnOkClick(Sender: TObject);
begin
edtDescrImagemExit(edtDescrImagem);
end;
procedure TfrmOpcaoImagem.btnCancelarClick(Sender: TObject);
begin
Close;
Exit;
end;
procedure TfrmOpcaoImagem.FormShow(Sender: TObject);
begin
edtDescrImagem.SetFocus;
end;
function TfrmOpcaoImagem.EscanearImagem: TJpegImage;
var
imgJpg : TJpegImage;
ws : Widestring;
sArqScaneado : string;
sArqComprimido : string;
iRet : integer;
begin
result := nil;
with aiScanearImagem do
begin
if loadTwainModule then
begin
try
iRet := OpenSourceManager;
ws := GetSource(false);
iRet := selectSource(ws);
if iRet = 3 then
exit;
iRet := openSource;
acquirejpg(imgJpg, 75);
finally
closeTwainSession;
unloadTwainModule;
end;
end
else
MessageDlg('Erro ao carregar a biblioteca TWAIN_32.DLL. Tente novamente!', mtError, [mbOk], 0);
end;
imgJpg.CompressionQuality := 50;
imgJpg.Compress;
result := imgJpg;
end;
procedure TfrmOpcaoImagem.edtDescrImagemKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then
SelectNext(Sender as TWinControl, True, True);
end;
end.
|
unit uCopiar;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LazFileUtils, Forms, Controls, Graphics, Dialogs, StdCtrls,
ComCtrls, ExtCtrls, DefaultTranslator, FileUtil;
type
{ TfrmCopiar }
TfrmCopiar = class(TForm)
Label1: TLabel;
Label2: TLabel;
pbrAvance: TProgressBar;
sttPos: TStaticText;
sttOrigen: TStaticText;
sttDestino: TStaticText;
procedure FormActivate(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ private declarations }
iPos: Integer;
public
{ public declarations }
Origenes,
Destinos: TStringList;
bPreservar: Boolean;
end;
var
frmCopiar: TfrmCopiar;
implementation
{$R *.lfm}
{ TfrmCopiar }
procedure TfrmCopiar.FormCreate(Sender: TObject);
begin
iPos := 0;
bPreservar := True;
end;
procedure TfrmCopiar.FormActivate(Sender: TObject);
var
i: Integer;
begin
pbrAvance.Max := Origenes.Count;
for i := 0 to Origenes.Count - 1 do
begin
pbrAvance.Position := i + 1;
sttOrigen.Caption := Origenes.Strings[i];
sttDestino.Caption := Destinos.Strings[i];
sttPos.Caption := IntToStr(i + 1) + '/' + IntToStr(Origenes.Count);
if FileExists(Destinos.Strings[i]) then //evitar copiar ya copiados
Continue;
if CopyFile(Origenes.Strings[i], Destinos.Strings[i]) then
begin
if not bPreservar then //borrar el archivo de origen
DeleteFile(Origenes.Strings[i]);
end
else
if MessageDlg('Error', 'No se pudo copiar el archivo: ' + Origenes.Strings[i]
, mtError, [mbIgnore, mbAbort], 0) = mrAbort then
Abort; //--->
Application.ProcessMessages;
end;
Close;
end;
end.
|
unit uConfig;
interface
uses
System.SysUtils, System.IniFiles, Vcl.Forms, Vcl.Dialogs;
type tpBanco = (banFB, banMSS);
type
TConfig = class
private
FArquivo: string;
FPorta: Integer;
FDataBase: string;
FServidor: string;
FHostName: string;
FUser_Name: string;
FPassword: string;
FEstiloTelas: string;
FTipoBanco: tpBanco;
procedure SetEstiloTelas(const Value: string);
public
procedure Carregar();
procedure Salvar;
property Porta: Integer read FPorta write FPorta;
property DataBase: string read FDataBase write FDataBase;
property Servidor: string read FServidor write FServidor;
property HostName: string read FHostName write FHostName;
property User_Name: string read FUser_Name write FUser_Name;
property Password: string read FPassword write FPassword;
property EstiloTelas: string read FEstiloTelas write SetEstiloTelas;
constructor create(ABanco: tpBanco); overload;
constructor CreateFB(); overload;
end;
implementation
{ TConfig }
procedure TConfig.Carregar();
var
ArqIni: TIniFile;
begin
ArqIni := TIniFile.Create(FArquivo);
try
FPorta := ArqIni.ReadInteger('Servidor', 'Porta', 0);
FDataBase := ArqIni.ReadString('Servidor', 'DataBase', '');
FServidor := ArqIni.ReadString('Servidor', 'Servidor', '');
FUser_Name := ArqIni.ReadString('Servidor', 'User_Name', '');
FHostName := ArqIni.ReadString('Cliente', 'HostName', '');
FEstiloTelas := ArqIni.ReadString('Cliente', 'Stilo', '');
if FTipoBanco = banFB then
FPassword := 'masterkey'
else
FPassword := '12';
finally
FreeAndNil(ArqIni);
end;
end;
constructor TConfig.create(ABanco: tpBanco);
var
sCaminho: string;
begin
inherited create;
sCaminho := ExtractFilePath(application.ExeName);
if ABanco = banFB then
sCaminho := sCaminho + 'DomperFB.ini'
else
sCaminho := sCaminho + 'Domper.ini';
FArquivo := sCaminho;
FTipoBanco := ABanco;
end;
constructor TConfig.CreateFB;
var
sCaminho: string;
begin
inherited create;
sCaminho := ExtractFilePath(application.ExeName);
sCaminho := sCaminho + 'DomperFB.ini';
FArquivo := sCaminho;
FTipoBanco := banFB;
end;
procedure TConfig.Salvar;
var
ArqIni: TIniFile;
begin
ArqIni := TIniFile.Create(FArquivo);
try
ArqIni.WriteInteger('Servidor', 'Porta', FPorta);
ArqIni.WriteString('Servidor', 'Servidor', FServidor);
ArqIni.WriteString('Servidor', 'DataBase', FDataBase);
ArqIni.WriteString('Servidor', 'User_Name', FUser_Name);
ArqIni.WriteString('Cliente', 'HostName', FHostName);
ArqIni.WriteString('Cliente', 'Stilo', FEstiloTelas);
finally
FreeAndNil(ArqIni);
end;
end;
procedure TConfig.SetEstiloTelas(const Value: string);
begin
FEstiloTelas := Value;
end;
end.
|
{
DBAExplorer - Oracle Admin Management Tool
Copyright (C) 2008 Alpaslan KILICKAYA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
unit frmAddLanguage;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, cxLookAndFeelPainters, StdCtrls, cxButtons, ExtCtrls,
cxTextEdit, cxMaskEdit, cxButtonEdit, cxControls, cxContainer, cxEdit,
cxLabel;
type
TAddLanguageFrm = class(TForm)
Panel2: TPanel;
btnCancel: TcxButton;
btnOK: TcxButton;
Panel1: TPanel;
imgToolBar: TImage;
lblObjectName: TcxLabel;
Shape1: TShape;
lblAction: TLabel;
Label1: TLabel;
bedtLanguageFile: TcxButtonEdit;
edtLanguageName: TcxTextEdit;
OpenDialog: TOpenDialog;
procedure btnCancelClick(Sender: TObject);
procedure bedtLanguageFilePropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure btnOKClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function Init(): string;
end;
var
AddLanguageFrm: TAddLanguageFrm;
implementation
uses GenelDM, VisualOptions;
{$R *.dfm}
function TAddLanguageFrm.Init(): string;
begin
AddLanguageFrm := TAddLanguageFrm.Create(Application);
Self := AddLanguageFrm;
DMGenel.ChangeLanguage(self);
ChangeVisualGUI(self);
result := '';
ShowModal;
result := edtLanguageName.Text+'='+bedtLanguageFile.Text;
Free;
end;
procedure TAddLanguageFrm.btnCancelClick(Sender: TObject);
begin
close;
end;
procedure TAddLanguageFrm.bedtLanguageFilePropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
begin
if OpenDialog.Execute then
bedtLanguageFile.Text := OpenDialog.FileName;
end;
procedure TAddLanguageFrm.btnOKClick(Sender: TObject);
begin
if edtLanguageName.Text = '' then
begin
MessageDlg('Language Name must be specified', mtWarning, [mbOk], 0);
exit;
end;
close;
end;
end.
|
{$mode objfpc}
{$ifdef darwin}
{$linklib libpython3.7m.a}
{$endif}
{$ifdef linux}
{$linklib c}
{$linklib m}
{$linklib pthread}
{$linklib util}
{$linklib dl}
{$linklib libpython3.7m.a}
{$endif}
{$assertions on}
// python building instructions (darwin and linux):
// https://www.python.org/downloads/release/python-374/
// ./configure --disable-shared
// make
program Main;
uses
Python3Core, PythonBridge, SysUtils;
function PyVERSION(Self, Args : PPyObject): PPyObject; cdecl;
begin
result:= PyString_FromString('0.0.1b');
end;
type
TForm = class
procedure GotPythonData(data: UnicodeString);
end;
procedure TForm.GotPythonData(data: UnicodeString);
begin
writeln(data);
end;
var
methods: array[0..0] of TPythonBridgeMethod = ( (name: 'version'; callback: @PyVERSION; help: 'doc string for my function')
);
var
test_file: ansistring = 'import gl'+LF+
'import sys'+LF+
'print(gl.version())'+LF+
'print(sys.path)'+LF+
#0;
var
test_help: ansistring = 'import gl'+LF+
'print(gl.__doc__)'+LF+
'for key in dir( gl ):'+LF+
' if not key.startswith(''_''):'+LF+
' x = getattr( gl, key ).__doc__'+LF+
' print(key+'' (built-in function): '')'+LF+
' print(x)'+LF+
#0;
var
home, root: ansistring;
form: TForm;
begin
form := TForm.Create;
root := ExtractFileDir(ParamStr(0));
{$ifdef unix}
home := root+'/unix/python37';
{$ifdef PYTHON_DYNAMIC}
LoadLibrary(home+'/darwin/libpython3.7.dylib');
{$endif}
{$endif}
{$ifdef windows}
home := root+'\windows\python37';
{$ifdef PYTHON_DYNAMIC}
LoadLibrary(root+'\windows\python37.dll');
{$endif}
{$endif}
Assert(DirectoryExists(home), 'Python home can''t be found at '+home);
PythonInitialize(home, @form.GotPythonData);
PythonAddModule('gl', @methods, length(methods));
PyRun_SimpleString(PAnsiChar(test_file));
end. |
{ Subroutine SST_CONFIG_OUT (FNAM)
*
* Set up the output source configuration and init the back end routines.
* The configuration information is read from the file FNAM.
*
* The file named in FNAM contains a set of commands, one per line.
* "/*" starts an end of line comment. Valid commands are:
*
* BITS_ADR n
*
* N is the number of bits in one machine address.
*
* SIZE_INT n name
*
* Declares that an integer is available directly in the target language
* that is N machine addresses in size. There may be several SIZE_INT commands
* to indicate more than one available integer size. If so, all SIZE_INT
* commands must be in order from smallest to largest integer sizes. NAME
* is the name of this data type in the target language.
*
* SIZE_INT_MACHINE n
*
* Declares the size of the preferred "machine" integer. This must be one
* of the integer sizes previously declared with a SIZE_INT command.
*
* SIZE_INT_ADR n
*
* Declares the size of the integer needed to hold a machine address.
* This must be one of the integer sizes previously declared with a
* SIZE_INT command.
*
* UNIV_POINTER name
*
* Declare the name of the universal pointer data type in the target
* language.
*
* SIZE_FLOAT n name
*
* Just like SIZE_INT, but declares the size of one available floating point
* format. NAME is the name of this data type in the target language.
*
* SIZE_FLOAT_MACHINE n
*
* Declares the size of the preferred "machine" floating point number.
* This must be one of the floating point sizes previously declared with a
* SIZE_FLOAT command.
*
* SIZE_FLOAT_SINGLE n
* SIZE_FLOAT_DOUBLE n
*
* Declare the size of what is typically referred to as the "single" and
* "double" precision floating numbers on the target machine. The sizes
* used must have been previously declared with a SIZE_FLOAT command.
*
* SIZE_ENUMERATED_NATIVE n
*
* Declare the size in machine addresses of the target compiler's enumerated
* data type. This will default to the smallest SIZE_INT declared.
*
* SIZE_ENUMERATED_FORCE n
*
* Declare what size variables of enumerated types should be, regardless of
* whether this is the native size. N must be either the same as the value
* for SIZE_ENUMEREATED_NATIVE, or must be one of the sizes previously
* declared with a SIZE_INT command.
*
* SIZE_SET n
*
* Declare an available size for SET data types. There may be any number
* of these commands, but they must be in order from smallest to largest
* N. N is a size in machine address increments. If no SIZE_SET commands
* are given, and the target compiler has a native SET data type, then
* the set sizes will be set to match the native SET data type. If no
* SIZE_SET commands are given and the target compiler has no native SET
* data type, then there will be one SIZE_SET for every integer size
* declared with a SIZE_INT command.
*
* SIZE_SET_MULTIPLE n
*
* Declare the size in machine address units that large sets should be a
* multiple of. If the target compiler has a native SET data type, then
* the default will be such that the native SET data type can be used.
* Otherwise, this will default to the size declared in SIZE_INT_MACHINE.
*
* Set data types will be the smallest size specified with a SIZE_SET
* command that is still big enough to have one bit for every element.
* If the set requires more bits than available in the largest SIZE_SET,
* then the size will be a multiple of SIZE_SET_MULTIPLE.
*
* SIZE_BOOLEAN n name
*
* Declare the size in machine addresses of the standard BOOLEAN or LOGICAL
* data type of the target compiler. Variables of this data type can only
* take on values of TRUE or FALSE. NAME is the name of this data type in
* the target language.
*
* BITS_CHAR n name
*
* Declare the number of bits of storage allocated for one CHARACTER.
* NAME is the name of the basic character data type in the target language.
*
* OS name
*
* Declare the operating system name. Valid names are
* DOMAIN, HPUX, AIX, IRIX, and SOLARIS.
*
* LANGUAGE name
*
* Declare the target language name. Valid names are C and PASCAL.
*
* SUFFIX_FILE_NAME suffix
*
* Declare the mandatory output file name suffix. The output file name
* will always end with this suffix. If the output file name is specified
* without this suffix, then it will be added. Nothing will be done to it
* if it already ends with this suffix. The empty string (two quotes
* in a row) specifies no particular suffix is required. This is also
* the default.
*
* MAX_SYMBOL_LEN n
*
* Declare the maximum allowable length of a symbol in the output source
* code. N is the maximum number of characters.
*
* CONFIG string
*
* Pass additional configuration information to the back end. The string
* may be interpreted uniquely for each back end. Back end selection is
* a function of the MANUFACTURER, OS, and LANGUAGE parameters.
* This string must be enclosed in quotes if it contains any spaces.
*
* CASE <character case>
*
* Set the character case handling to be used for symbol names. Valid
* choices are:
*
* UPPER - All symbol names will be written in upper case, regardless
* of their case in the input source.
*
* LOWER - All symbol names will be written in lower case, regardless
* of their case in the input source. This is the default.
*
* RESERVED name
*
* Declare the name of a reserved symbol. No output symbol will have this
* name, whether it originally came from the input source code or was
* created implicitly by the translator. Symbols will be renamed, if
* necessary, to avoid these names. There may be any number of these
* commands.
*
* SUFFIX_DATA_TYPE suffix
*
* Declare the suffix that all data type names will end with. The default
* is no suffix (null string).
*
* SUFFIX_CONSTANT suffix
*
* Declare the suffix that all constant names will end with. The default
* is no suffix (null string).
*
* PASS_VAL_SIZE_MAX n
*
* Indicate the maximum size call argument that may be passed by value.
*
* ALIGN_MIN_REC n
*
* Set minimum alignment for all record data types. Default is 1, meaning
* arbitrary address alignment.
*
* ALIGN_MIN_PACKED_REC n
*
* Set minimum aligment of packed records. This defaults to the
* ALIGN_MIN_REC value.
}
module sst_CONFIG_OUT;
define sst_config_out;
%include 'sst2.ins.pas';
const
align_not_set_k = 65535; {alignment value to indicate align not set}
n_cmds = 27; {number of possible commands}
cmd_len_max = 22; {size of largest command name}
max_msg_parms = 2; {max arguments we can pass to a message}
cmd_len_alloc = cmd_len_max + 1; {chars to allocate for each command}
cmds_len = cmd_len_alloc * n_cmds; {total number of chars in commands list}
type
cmd_t = {one command name}
array[1..cmd_len_alloc] of char;
cmds_t = record {array of all the command names}
max: string_index_t; {simulate a var string}
len: string_index_t;
str: array[1..n_cmds] of cmd_t;
end;
var
cmds: cmds_t := [ {all the command names}
max := cmds_len, len := cmds_len, str := [
'BITS_ADR ', {1}
'SIZE_INT ', {2}
'SIZE_INT_MACHINE ', {3}
'SIZE_INT_ADR ', {4}
'SIZE_FLOAT ', {5}
'SIZE_FLOAT_MACHINE ', {6}
'SIZE_FLOAT_SINGLE ', {7}
'SIZE_FLOAT_DOUBLE ', {8}
'SIZE_ENUMERATED_NATIVE', {9}
'SIZE_BOOLEAN ', {10}
'BITS_CHAR ', {11}
'OS ', {12}
'LANGUAGE ', {13}
'SUFFIX_FILE_NAME ', {14}
'MAX_SYMBOL_LEN ', {15}
'CONFIG ', {16}
'CASE ', {17}
'RESERVED ', {18}
'SUFFIX_DATA_TYPE ', {19}
'SUFFIX_CONSTANT ', {20}
'UNIV_POINTER ', {21}
'SIZE_ENUMERATED_FORCE ', {22}
'SIZE_SET ', {23}
'SIZE_SET_MULTIPLE ', {24}
'PASS_VAL_SIZE_MAX ', {25}
'ALIGN_MIN_REC ', {26}
'ALIGN_MIN_PACKED_REC ', {27}
]
];
comment: string_var4_t := {end of line comment delimiter}
[str := '/*', len := 2, max := 4];
procedure sst_config_out ( {configure and init back end}
in fnam: univ string_var_arg_t); {configuration file name}
var
conn: file_conn_t; {connection handle to config file}
buf: string_var8192_t; {one line input buffer}
p: string_index_t; {input line parse index}
cmd: string_var32_t; {command name parsed from config file}
pick: sys_int_machine_t; {number of command picked from list}
parm: string_var32_t; {parameter to command from config file}
i: sys_int_machine_t; {loop counter and scratch integer}
al: sys_int_machine_t; {scratch alignment value}
sz: sys_int_adr_t; {amount of memory needed to allocate}
szi: sys_int_machine_t; {mem size in SYS_INT_MACHINE_T format}
ent_p: string_chain_ent_p_t; {pointer to current string chain entry}
sym_p: sst_symbol_p_t; {scratch pointer to symbol descriptor}
dt_p: sst_dtype_p_t; {scratch pointer to data type descriptor}
char_none_h: syo_char_t; {source stream char handle, set to invalid}
uptr_given: boolean; {TRUE if UNIV_POINTER command given}
os_given: boolean; {TRUE if OS command given}
msg_parm: {parameter references for messages}
array[1..max_msg_parms] of sys_parm_msg_t;
stat: sys_err_t; {status return code}
label
next_line, loop_fp, done_fp, set_size_found, set_size_found2,
no_err, parm_err, parm_range_err, read_err, eof, enum_done;
{
*********************************************
*
* Local subroutine UNSPEC_ERR (CMD_NAME)
*
* Complain that a value was unspecified. CMD_NAME is the name of the
* command that is used to specify the value.
}
procedure unspec_err (
in cmd_name: string);
options (noreturn);
begin
sys_msg_parm_str (msg_parm[1], cmd_name);
sys_message_bomb ('sst', 'config_cmd_missing', msg_parm, 1);
end;
{
*********************************************
*
* Start of main routine.
}
begin
buf.max := sizeof(buf.str); {init local var strings}
cmd.max := sizeof(cmd.str);
parm.max := sizeof(parm.str);
char_none_h.crange_p := nil; {init invalid source character handle}
char_none_h.ofs := 0;
file_open_read_text (fnam, '', conn, stat); {open config file for reading text}
if sys_error(stat) then begin {error opening config file ?}
sys_msg_parm_vstr (msg_parm[1], fnam);
sys_error_print (stat, 'sst', 'config_open', msg_parm, 1);
sys_bomb;
end;
{
* Init the configuration data before reading config file.
}
sst_config.bits_adr := 0;
sst_config.n_size_int := 0;
sst_config.int_machine_p := nil;
sst_config.int_adr_p := nil;
sst_config.name_univ_ptr.max := sizeof(sst_config.name_univ_ptr.str);
sst_config.name_univ_ptr.len := 0;
sst_config.n_size_float := 0;
sst_config.float_machine_p := nil;
sst_config.float_single_p := nil;
sst_config.float_double_p := nil;
sst_config.n_size_set := 0;
sst_config.size_set_multiple.size := 0;
sst_config.align_min_rec := 1;
sst_config.align_min_rec_pack := align_not_set_k;
sst_config.pass_val_size_max := 0;
sst_config.size_enum_native := 0;
sst_config.size_enum := 0;
sst_config.size_bool := 0;
sst_config.name_bool.max := sizeof(sst_config.name_bool.str);
sst_config.name_bool.len := 0;
sst_config.bits_char := 0;
sst_config.size_char := 0;
sst_config.name_char.max := sizeof(sst_config.name_char.str);
sst_config.name_char.len := 0;
sst_config.manuf := sst_manuf_none_k;
sst_config.lang := sst_lang_none_k;
sst_config.suffix_fnam.max := sizeof(sst_config.suffix_fnam.str);
sst_config.suffix_fnam.len := 0;
sst_config.suffix_dtype.max := sizeof(sst_config.suffix_dtype.str);
sst_config.suffix_dtype.len := 0;
sst_config.suffix_const.max := sizeof(sst_config.suffix_const.str);
sst_config.suffix_const.len := 0;
sst_config.sym_len_max := 0;
sst_config.config.max := sizeof(sst_config.config.str);
sst_config.config.len := 0;
sst_config.charcase := syo_charcase_down_k;
sst_config.reserve_p := nil;
uptr_given := false; {init to UNIV_POINTER command not given yet}
os_given := false; {init to no OS command given yet}
next_line: {back here each new line from config file}
file_read_text (conn, buf, stat); {read next line from config file}
if file_eof(stat) then goto eof; {hit end of file ?}
string_find (comment, buf, p); {look for comment start}
if p > 0 then begin {found start of comment ?}
buf.len := p - 1; {truncate input line at comment start}
end;
p := 1; {init input line parse index}
string_token (buf, p, cmd, stat); {extract command name from this line}
if string_eos(stat) then goto next_line; {no command at all on this line ?}
if sys_error(stat) then goto read_err;
string_upcase (cmd); {make upper case for name matching}
string_tkpick (cmd, cmds, pick); {pick command name from list}
case pick of
{
* BITS_ADR n
}
1: begin
string_token_int (buf, p, sst_config.bits_adr, stat);
if sys_error(stat) then goto parm_err;
if sst_config.bits_adr < 1 then goto parm_range_err;
end;
{
* SIZE_INT n name
}
2: begin
sst_config.n_size_int := sst_config.n_size_int + 1; {one more integer size}
if sst_config.n_size_int > sst_size_list_max then begin
sys_message ('sst', 'config_too_many_int');
goto read_err;
end;
with sst_config.size_int[sst_config.n_size_int]: csize {CSIZE is SIZE_INT entry}
do begin
string_token_int (buf, p, csize.size, stat); {get size of this integer}
if sys_error(stat) then goto parm_err; {error reading parameter ?}
if csize.size <= 0 then goto parm_range_err; {value out of range ?}
if sst_config.n_size_int > 1 then begin {there was a previous size ?}
if csize.size <= {not bigger than previous integer size ?}
sst_config.size_int[sst_config.n_size_int-1].size
then begin
sys_message ('sst', 'config_int_le_previous');
goto read_err;
end;
end;
csize.name.max := sizeof(csize.name.str); {init data type name var string}
string_token (buf, p, csize.name, stat); {get data type name}
sst_dtype_new (csize.dtype_p); {create new data type}
csize.dtype_p^.dtype := sst_dtype_int_k; {initialize data type descriptor}
csize.dtype_p^.bits_min := csize.size * sst_config.bits_adr;
csize.dtype_p^.align_nat := csize.size;
csize.dtype_p^.align := csize.size;
csize.dtype_p^.size_used := csize.size;
csize.dtype_p^.size_align := csize.size;
end; {done with CSIZE abbreviation}
end;
{
* SIZE_INT_MACHINE n
}
3: begin
string_token_int (buf, p, szi, stat); {get size of this data type}
if sys_error(stat) then goto parm_err;
for i := 1 to sst_config.n_size_int do begin {loop thru the integer sizes}
if sst_config.size_int[i].size = szi then begin
sst_config.int_machine_p := sst_config.size_int[i].dtype_p;
goto no_err;
end;
end; {back and try next integer size}
sys_message ('sst', 'config_size_bad');
goto read_err;
end;
{
* SIZE_INT_ADR n
}
4: begin
string_token_int (buf, p, szi, stat); {get size of this data type}
if sys_error(stat) then goto parm_err;
for i := 1 to sst_config.n_size_int do begin {loop thru the integer sizes}
if sst_config.size_int[i].size = szi then begin
sst_config.int_adr_p := sst_config.size_int[i].dtype_p;
goto no_err;
end;
end; {back and try next integer size}
sys_message ('sst', 'config_size_bad');
goto read_err;
end;
{
* SIZE_FLOAT n name [ALIGN n]
}
5: begin
sst_config.n_size_float := sst_config.n_size_float + 1; {one more float size}
if sst_config.n_size_float > sst_size_list_max then begin
sys_message ('sst', 'config_too_many_float');
goto read_err;
end;
with sst_config.size_float[sst_config.n_size_float]: csize {CSIZE is SIZE_FLOAT entry}
do begin
string_token_int (buf, p, csize.size, stat); {get size of this float}
if sys_error(stat) then goto parm_err; {error reading parameter ?}
if csize.size <= 0 then goto parm_range_err; {value out of range ?}
if sst_config.n_size_float > 1 then begin {there was a previous size ?}
if csize.size <= {not bigger than previous float size ?}
sst_config.size_float[sst_config.n_size_float-1].size
then begin
sys_message ('sst', 'config_float_le_previous');
goto read_err;
end;
end;
csize.name.max := sizeof(csize.name.str); {init data type name var string}
string_token (buf, p, csize.name, stat); {get data type name}
al := csize.size; {init aligment to its own size}
loop_fp: {back here for each new optional keyword}
string_token (buf, p, parm, stat); {get next keyword}
if string_eos(stat) then goto done_fp; {exhausted optional keywords ?}
string_upcase (parm); {make upper case for keyword matching}
string_tkpick80 (parm,
'ALIGN',
pick); {number of keyword picked from list}
case pick of
1: begin {ALIGN n}
string_token_int (buf, p, al, stat); {get alignment of this data type}
if sys_error(stat) then goto parm_err;
end;
otherwise
goto parm_err;
end;
goto loop_fp; {back for next subcommand}
done_fp: {done with all the subcommands}
sst_dtype_new (csize.dtype_p); {create new data type}
csize.dtype_p^.dtype := sst_dtype_float_k; {initialize data type descriptor}
csize.dtype_p^.bits_min := csize.size * sst_config.bits_adr;
csize.dtype_p^.align_nat := al;
csize.dtype_p^.align := al;
csize.dtype_p^.size_used := csize.size;
csize.dtype_p^.size_align :=
((csize.size + al - 1) div al) * al;
end; {done with CSIZE abbreviation}
end;
{
* SIZE_FLOAT_MACHINE n
}
6: begin
string_token_int (buf, p, szi, stat); {get size of this data type}
if sys_error(stat) then goto parm_err;
for i := 1 to sst_config.n_size_float do begin {loop thru the float sizes}
if sst_config.size_float[i].size = szi then begin
sst_config.float_machine_p := sst_config.size_float[i].dtype_p;
goto no_err;
end;
end; {back and try next float size}
sys_message ('sst', 'config_size_bad');
goto read_err;
end;
{
* SIZE_FLOAT_SINGLE n
}
7: begin
string_token_int (buf, p, szi, stat); {get size of this data type}
if sys_error(stat) then goto parm_err;
for i := 1 to sst_config.n_size_float do begin {loop thru the float sizes}
if sst_config.size_float[i].size = szi then begin
sst_config.float_single_p := sst_config.size_float[i].dtype_p;
goto no_err;
end;
end; {back and try next float size}
sys_message ('sst', 'config_size_bad');
goto read_err;
end;
{
* SIZE_FLOAT_DOUBLE n
}
8: begin
string_token_int (buf, p, szi, stat); {get size of this data type}
if sys_error(stat) then goto parm_err;
for i := 1 to sst_config.n_size_float do begin {loop thru the float sizes}
if sst_config.size_float[i].size = szi then begin
sst_config.float_double_p := sst_config.size_float[i].dtype_p;
goto no_err;
end;
end; {back and try next float size}
sys_message ('sst', 'config_size_bad');
goto read_err;
end;
{
* SIZE_ENUMERATED_NATIVE n
}
9: begin
string_token_int (buf, p, szi, stat);
sst_config.size_enum_native := szi;
if sys_error(stat) then goto parm_err;
if sst_config.size_enum_native < 1 then goto parm_range_err;
end;
{
* SIZE_BOOLEAN n name
}
10: begin
string_token_int (buf, p, szi, stat);
sst_config.size_bool := szi;
if sys_error(stat) then goto parm_err;
if sst_config.size_bool < 1 then goto parm_range_err;
string_token (buf, p, sst_config.name_bool, stat);
end;
{
* BITS_CHAR n name
}
11: begin
string_token_int (buf, p, sst_config.bits_char, stat);
if sys_error(stat) then goto parm_err;
if sst_config.bits_char < 1 then goto parm_range_err;
string_token (buf, p, sst_config.name_char, stat);
end;
{
* OS name
}
12: begin
string_token (buf, p, parm, stat);
if sys_error(stat) then goto parm_err;
string_upcase (parm);
string_tkpick80 (parm,
'DOMAIN HPUX AIX IRIX SOLARIS WIN32',
pick);
case pick of
1: begin
sst_config.os := sys_os_domain_k;
sst_config.manuf := sst_manuf_apollo_k;
end;
2: begin
sst_config.os := sys_os_hpux_k;
sst_config.manuf := sst_manuf_hp_k;
end;
3: begin
sst_config.os := sys_os_aix_k;
sst_config.manuf := sst_manuf_ibm_k;
end;
4: begin
sst_config.os := sys_os_irix_k;
sst_config.manuf := sst_manuf_sgi_k;
end;
5: begin
sst_config.os := sys_os_solaris_k;
sst_config.manuf := sst_manuf_sun_k;
end;
6: begin
sst_config.os := sys_os_win32_k;
sst_config.manuf := sst_manuf_none_k;
end;
otherwise
goto parm_range_err;
end; {end of operating system name cases}
os_given := true; {indicate OS command was given}
end;
{
* LANGUAGE name
}
13: begin
string_token (buf, p, parm, stat);
if sys_error(stat) then goto parm_err;
string_upcase (parm);
string_tkpick80 (parm,
'PASCAL C',
pick);
case pick of
1: sst_config.lang := sst_lang_pas_k;
2: sst_config.lang := sst_lang_c_k;
otherwise
goto parm_range_err;
end; {end of language name cases}
end;
{
* SUFFIX_FILE_NAME suffix
}
14: begin
string_token (buf, p, sst_config.suffix_fnam, stat);
end;
{
* MAX_SYMBOL_LEN n
}
15: begin
string_token_int (buf, p, sst_config.sym_len_max, stat);
if sys_error(stat) then goto parm_err;
if sst_config.sym_len_max < 1 then goto parm_range_err;
end;
{
* CONFIG string
}
16: begin
string_token (buf, p, sst_config.config, stat);
end;
{
* CASE <character case>
}
17: begin
string_token (buf, p, parm, stat);
if sys_error(stat) then goto parm_err;
string_upcase (parm); {make upper case for keyword list compare}
string_tkpick80 (parm,
'UPPER LOWER',
pick);
case pick of
1: sst_config.charcase := syo_charcase_up_k;
2: sst_config.charcase := syo_charcase_down_k;
otherwise
goto parm_range_err;
end;
end;
{
* RESERVED name
}
18: begin
string_token (buf, p, parm, stat);
if sys_error(stat) then goto parm_err;
sz := {amount of memory needed for this chain entry}
sizeof(ent_p^) - sizeof(ent_p^.s.str) + parm.len;
util_mem_grab (sz, sst_scope_root_p^.mem_p^, false, ent_p); {grab mem for this name}
ent_p^.next_p := sst_config.reserve_p; {link new entry to start of chain}
ent_p^.prev_p := nil;
if ent_p^.next_p <> nil then begin {there is a following entry ?}
ent_p^.next_p^.prev_p := ent_p; {point old first ent to new chain start}
end;
sst_config.reserve_p := ent_p; {update pointer to new start of chain}
ent_p^.s.max := parm.len; {init new var string}
string_copy (parm, ent_p^.s); {copy string into new entry}
end;
{
* SUFFIX_DATA_TYPE suffix
}
19: begin
string_token (buf, p, sst_config.suffix_dtype, stat);
end;
{
* SUFFIX_CONSTANT suffix
}
20: begin
string_token (buf, p, sst_config.suffix_const, stat);
end;
{
* UNIV_POINTER name
}
21: begin
string_token (buf, p, sst_config.name_univ_ptr, stat);
uptr_given := true;
end;
{
* SIZE_ENUMERATED_FORCE n
}
22: begin
string_token_int (buf, p, szi, stat);
sst_config.size_enum := szi;
if sys_error(stat) then goto parm_err;
if sst_config.size_enum < 1 then goto parm_range_err;
end;
{
* SIZE_SET n
}
23: begin
sst_config.n_size_set := sst_config.n_size_set + 1; {one more explicit SET size}
if sst_config.n_size_set > sst_size_list_max then begin
sys_message ('sst', 'config_too_many_set');
goto read_err;
end;
with sst_config.size_set[sst_config.n_size_set]: ss do begin {SS is set size entry}
string_token_int (buf, p, ss.size, stat);
if sys_error(stat) then goto parm_err;
if {value not bigger than last SIZE_SET ?}
(sst_config.n_size_set > 1) and then {there was previous SIZE_SET command ?}
(ss.size <= sst_config.size_set[sst_config.n_size_set-1].size)
then begin
sys_message ('sst', 'config_set_le_previous');
goto read_err;
end;
for i := 1 to sst_config.n_size_int do begin {loop thru the integer sizes}
if sst_config.size_int[i].size = ss.size {found integer of the right size ?}
then goto set_size_found;
end; {back and try next integer size}
sys_message ('sst', 'config_nosuch_int_size');
goto read_err;
set_size_found: {I is index to integer size data}
ss.dtype_p := sst_config.size_int[i].dtype_p; {copy pointer to data type}
end; {done with SS abbreviation}
end;
{
* SIZE_SET_MULTIPLE n
}
24: begin
string_token_int (buf, p, sst_config.size_set_multiple.size, stat);
if sys_error(stat) then goto parm_err;
for i := 1 to sst_config.n_size_int do begin {loop thru the integer sizes}
if sst_config.size_int[i].size = sst_config.size_set_multiple.size
then goto set_size_found2;
end; {back and try next integer size}
sys_message ('sst', 'config_nosuch_int_size');
goto read_err;
set_size_found2:
sst_config.size_set_multiple.dtype_p := sst_config.size_int[i].dtype_p;
end;
{
* PASS_VAL_SIZE_MAX n
}
25: begin
string_token_int (buf, p, szi, stat);
sst_config.pass_val_size_max := szi;
end;
{
* ALIGN_MIN_REC n
}
26: begin
string_token_int (buf, p, szi, stat);
sst_config.align_min_rec := szi;
end;
{
* ALIGN_MIN_PACKED_REC n
}
27: begin
string_token_int (buf, p, szi, stat);
sst_config.align_min_rec_pack := szi;
end;
{
* Illegal command name.
}
otherwise
sys_msg_parm_vstr (msg_parm[1], cmd);
sys_message_parms ('sst', 'config_cmd_bad', msg_parm, 1);
goto read_err;
end; {end of command name cases}
{
* Done processing current command. Now make sure there were no errors and
* also make sure there are no unsed tokens remaining on the line.
}
if sys_error(stat) then goto parm_err; {check for parameter error}
no_err: {jump here if no error processing command}
string_token (buf, p, parm, stat); {try to get one more token from this line}
if not string_eos(stat) then begin {there really was another token ?}
sys_msg_parm_vstr (msg_parm[1], cmd);
sys_msg_parm_vstr (msg_parm[2], parm);
sys_message_parms ('sst', 'config_token_extraneous', msg_parm, 2);
goto read_err;
end;
goto next_line; {back and process next input line}
parm_err: {jump here on error with command parameter}
sys_msg_parm_vstr (msg_parm[1], cmd);
sys_error_print (stat, 'sst', 'config_parm_err', msg_parm, 1);
goto read_err;
parm_range_err: {jump here if parameter is out of range}
sys_msg_parm_vstr (msg_parm[1], cmd);
sys_message_parms ('sst', 'config_parm_range', msg_parm, 1);
goto read_err;
read_err: {print file name and line number, then bomb}
sys_msg_parm_int (msg_parm[1], conn.lnum);
sys_msg_parm_vstr (msg_parm[2], conn.tnam);
sys_message_bomb ('sst', 'config_fnam_lnum', msg_parm, 2);
{
* We just encountered end of config file.
}
eof:
file_close (conn); {close config file}
{
* Make sure all the mandatory information was supplied.
}
if sst_config.bits_adr = 0 then unspec_err ('BITS_ADR');
if sst_config.n_size_int = 0 then unspec_err ('SIZE_INT');
if sst_config.int_machine_p = nil then unspec_err ('SIZE_INT_MACHINE');
if sst_config.int_adr_p = nil then unspec_err ('SIZE_INT_ADR');
if not uptr_given then unspec_err ('UNIV_POINTER');
if sst_config.n_size_float = 0 then unspec_err ('SIZE_FLOAT');
if sst_config.float_machine_p = nil then unspec_err ('SIZE_FLOAT_MACHINE');
if sst_config.float_single_p = nil then unspec_err ('SIZE_FLOAT_SINGLE');
if sst_config.float_double_p = nil then unspec_err ('SIZE_FLOAT_DOUBLE');
if sst_config.size_bool = 0 then unspec_err ('SIZE_BOOLEAN');
if sst_config.bits_char = 0 then unspec_err ('BITS_CHAR');
if not os_given then unspec_err ('OS');
if sst_config.lang = sst_lang_none_k then unspec_err ('LANGUAGE');
if sst_config.sym_len_max = 0 then unspec_err ('MAX_SYMBOL_LEN');
sst_config.size_char :=
(sst_config.bits_char + sst_config.bits_adr - 1) div sst_config.bits_adr;
if sst_config.align_min_rec_pack = align_not_set_k then begin {align not speced ?}
sst_config.align_min_rec_pack := {use default for this field}
sst_config.align_min_rec;
end;
{
* Set up the pointers to the mandatory base data types the translator
* requires internally. The floating point and integer data types can just
* reference the appropriate ones from the lists already created. The others
* must be created from scratch.
*
* The data types and symbol descriptors will be created, but the symbols
* will not be entered into any symbol table. This will be done by the
* front/back ends if appropriate.
}
for i := 1 to sst_config.n_size_int do begin {once for each integer data type}
with sst_config.size_int[i]: szent do begin {SZENT is this size array entry}
sst_mem_alloc_scope (sizeof(sym_p^), sym_p); {allocate new symbol descriptor}
sym_p^.name_in_p := nil; {set up symbol descriptor}
sym_p^.name_out_p := univ_ptr(addr(szent.name));
sym_p^.next_p := nil;
sym_p^.char_h := char_none_h;
sym_p^.scope_p := sst_scope_p;
sym_p^.symtype := sst_symtype_dtype_k;
sym_p^.flags := [sst_symflag_def_k, sst_symflag_intrinsic_out_k];
sym_p^.dtype_dtype_p := szent.dtype_p;
szent.dtype_p^.symbol_p := sym_p; {point data type to symbol descriptor}
end; {done with SZENT abbreviation}
end; {back for next integer data type}
for i := 1 to sst_config.n_size_float do begin {once for each float data type}
with sst_config.size_float[i]: szent do begin {SZENT is this size array entry}
sst_mem_alloc_scope (sizeof(sym_p^), sym_p); {allocate new symbol descriptor}
sym_p^.name_in_p := nil; {set up symbol descriptor}
sym_p^.name_out_p := univ_ptr(addr(szent.name));
sym_p^.next_p := nil;
sym_p^.char_h := char_none_h;
sym_p^.scope_p := sst_scope_p;
sym_p^.symtype := sst_symtype_dtype_k;
sym_p^.flags := [sst_symflag_def_k, sst_symflag_intrinsic_out_k];
sym_p^.dtype_dtype_p := szent.dtype_p;
szent.dtype_p^.symbol_p := sym_p; {point data type to symbol descriptor}
end; {done with SZENT abbreviation}
end; {back for next float data type}
sst_mem_alloc_scope (sizeof(dt_p^), dt_p); {allocate new data type descriptor}
dt_p^ := sst_config.float_machine_p^; {make separate copy for SYS_FP_MACHINE_T}
sst_config.float_machine_p := dt_p;
sst_dtype_int_max_p := {largest directly available integer}
sst_config.size_int[sst_config.n_size_int].dtype_p;
sst_dtype_float_max_p := {largest directly available floating point}
sst_config.size_float[sst_config.n_size_float].dtype_p;
sst_dtype_new (sst_dtype_uptr_p); {create universal pointer dtype descriptor}
sst_dtype_uptr_p^.dtype := sst_dtype_pnt_k;
sst_dtype_uptr_p^.bits_min := sst_config.int_adr_p^.bits_min;
sst_dtype_uptr_p^.align_nat := sst_config.int_adr_p^.align_nat;
sst_dtype_uptr_p^.align := sst_config.int_adr_p^.align;
sst_dtype_uptr_p^.size_used := sst_config.int_adr_p^.size_used;
sst_dtype_uptr_p^.size_align := sst_config.int_adr_p^.size_align;
sst_dtype_uptr_p^.pnt_dtype_p := nil;
sst_mem_alloc_scope (sizeof(sym_p^), sym_p); {allocate new symbol descriptor}
sym_p^.name_in_p := nil; {set up symbol descriptor}
sym_p^.name_out_p := univ_ptr(addr(sst_config.name_univ_ptr));
sym_p^.next_p := nil;
sym_p^.char_h := char_none_h;
sym_p^.scope_p := sst_scope_p;
sym_p^.symtype := sst_symtype_dtype_k;
sym_p^.flags := [sst_symflag_def_k, sst_symflag_intrinsic_out_k];
sym_p^.dtype_dtype_p := sst_dtype_uptr_p; {point symbol to data type descriptor}
sst_dtype_uptr_p^.symbol_p := sym_p; {point data type to symbol descriptor}
sst_dtype_new (sst_dtype_bool_p); {create boolean data type descriptor}
sst_dtype_bool_p^.dtype := sst_dtype_bool_k;
sst_dtype_bool_p^.bits_min := 1;
sst_dtype_bool_p^.align_nat := sst_config.size_bool;
sst_dtype_bool_p^.align := sst_config.size_bool;
sst_dtype_bool_p^.size_used := sst_config.size_bool;
sst_dtype_bool_p^.size_align := sst_config.size_bool;
sst_mem_alloc_scope (sizeof(sym_p^), sym_p); {allocate new symbol descriptor}
sym_p^.name_in_p := nil; {set up symbol descriptor}
sym_p^.name_out_p := univ_ptr(addr(sst_config.name_bool));
sym_p^.next_p := nil;
sym_p^.char_h := char_none_h;
sym_p^.scope_p := sst_scope_p;
sym_p^.symtype := sst_symtype_dtype_k;
sym_p^.flags := [sst_symflag_def_k, sst_symflag_intrinsic_out_k];
sym_p^.dtype_dtype_p := sst_dtype_bool_p; {point symbol to data type descriptor}
sst_dtype_bool_p^.symbol_p := sym_p; {point data type to symbol descriptor}
sst_dtype_new (sst_dtype_char_p); {create character data type descriptor}
sst_dtype_char_p^.dtype := sst_dtype_char_k;
sst_dtype_char_p^.bits_min := sst_config.size_char * sst_config.bits_adr;
sst_dtype_char_p^.align_nat := sst_config.size_char;
sst_dtype_char_p^.align := sst_config.size_char;
sst_dtype_char_p^.size_used := sst_config.size_char;
sst_dtype_char_p^.size_align := sst_config.size_char;
sst_mem_alloc_scope (sizeof(sym_p^), sym_p); {allocate new symbol descriptor}
sym_p^.name_in_p := nil; {set up symbol descriptor}
sym_p^.name_out_p := univ_ptr(addr(sst_config.name_char));
sym_p^.next_p := nil;
sym_p^.char_h := char_none_h;
sym_p^.scope_p := sst_scope_p;
sym_p^.symtype := sst_symtype_dtype_k;
sym_p^.flags := [sst_symflag_def_k, sst_symflag_intrinsic_out_k];
sym_p^.dtype_dtype_p := sst_dtype_char_p; {point symbol to data type descriptor}
sst_dtype_char_p^.symbol_p := sym_p; {point data type to symbol descriptor}
{
* Figure out how enumerated types will be handled. The fields
* SIZE_ENUM and SIZE_ENUM_NATIVE have been set if commands were supplied.
* Otherwise they are set to zero to indicate no commands were supplied.
}
if sst_config.size_enum = 0 {no SIZE_ENUMERATED_FORCE command given ?}
then sst_config.size_enum := sst_config.size_enum_native; {use native size}
if sst_config.size_enum = 0 {no SIZE_ENUMERATED_NATIVE command either ?}
then sst_config.size_enum := {pick the size from the smallest integer}
sst_config.size_int[1].size;
sst_dtype_enum_p := nil; {init to using native enum type directly}
if sst_config.size_enum <> sst_config.size_enum_native then begin {use integer ?}
for i := 1 to sst_config.n_size_int do begin {once for each size integer}
if sst_config.size_int[i].size = sst_config.size_enum then begin {found it ?}
sst_dtype_enum_p := sst_config.size_int[i].dtype_p;
goto enum_done;
end;
end; {back and check next size integer for match}
sys_msg_parm_int (msg_parm[1], sst_config.size_enum);
sys_message_bomb ('sst', 'config_enum_size_bad', msg_parm, 1);
end; {done handling not use native enum data type}
enum_done: {done handling enumerated type issues}
if sst_config.pass_val_size_max = 0 then begin {no PASS_VAL_SIZE_MAX command ?}
sst_config.pass_val_size_max := {default to size of maximum size integer}
sst_config.size_int[sst_config.n_size_int].size;
end;
end;
|
{$include lem_directives.inc}
unit GameControl;
{-------------------------------------------------------------------------------
The gamecontrol class is in fact just a global var which is passed through as
a parameter to all screens.
-------------------------------------------------------------------------------}
interface
uses
Classes,
GR32, GR32_Image,
UTools,
LemCore, LemTypes, LemLevel, LemDosStyle, LemGraphicSet, LemDosGraphicSet,
{$ifdef flexi}LemDosStructures,{$endif}
LemLevelSystem, LemRendering;
type
TGameResultsRec = record
gSuccess : Boolean; // level played successfully?
gCheated : Boolean; // level cheated?
gCount : Integer; // number
gToRescue : Integer;
gRescued : Integer;
gTarget : Integer;
gDone : Integer;
gTimeIsUp : Boolean;
end;
type
TGameScreenType = (
gstUnknown,
gstMenu,
gstPreview,
gstPlay,
gstPostview,
gstLevelCode,
gstSounds,
gstExit,
gstNavigation
);
type
// how do we load the level
TWhichLevel = (
wlFirst,
wlFirstSection,
wlLevelCode,
wlNext,
wlSame,
wlCongratulations
);
type
TGameSoundOption = (
gsoSound,
gsoMusic
);
TGameSoundOptions = set of TGameSoundOption;
type
TMiscOption = (
moGradientBridges, // 0
moFastForward, // 1
moSaveState, // 2
moHyperJumps, // 3
moCheatCodes, // 4
moShowParticles, // 5
moLookForLVLFiles, // 6
// moUseSystemCursor, // 7
moLemmixTrapBug,
moStateControlEnabled,
moPauseAssignEnabled,
mo11, mo12, mo13, mo14, mo15,
mo16, mo17, mo18, mo19, mo20, mo21, mo22, mo23,
mo24, mo25, mo26, mo27, mo28, mo29, mo30, mo31
);
TMiscOptions = set of TMiscOption;
const
DEF_MISCOPTIONS = [
moGradientBridges,
moFastForward,
moSaveState,
moHyperJumps,
// moCheatCodes,
moShowParticles,
moStateControlEnabled,
moPauseAssignEnabled
{$ifdef cust}, moLemmixTrapBug{$endif}
// moLookForLVLFiles
// moUseSystemCursor
];
type (*
TOptionsRec = packed record
oSignature : array[0..2] of Char; // LOF LemmingsOptions File
oVersion : Byte; // version of this record
oRecordSize : Integer;
oOptions : TMiscOptions; // 32 bits
oSoundOptions: TGameSoundOptions; // 8 bits
end; *)
TDosGameParams = class(TPersistent)
private
fDirectory : string;
fLevelPackName: String;
fDumpMode : Boolean;
function GetLevelPackName: String;
procedure SetLevelPackName(Value: String);
function GetCheatCodesEnabled: Boolean;
procedure SetCheatCodesEnabled(Value: Boolean);
function GetMusicEnabled: Boolean;
function GetSoundEnabled: Boolean;
procedure SetMusicEnabled(Value: Boolean);
procedure SetSoundEnabled(Value: Boolean);
function GetShowParticles: Boolean;
procedure SetShowParticles(const Value: Boolean);
function GetLookForLVLFiles: Boolean;
procedure SetLookForLVLFiles(Value: Boolean);
function GetUseSystemCursor: Boolean;
procedure SetUseSystemCursor(const Value: Boolean);
function GetLemmixTrapBug: Boolean;
procedure SetLemmixTrapBug(Value: Boolean);
function GetStateControlEnabled: Boolean;
procedure SetStateControlEnabled(Value: Boolean);
function GetPauseAssignEnabled: Boolean;
procedure SetPauseAssignEnabled(Value: Boolean);
public
// this is initialized by appcontroller
MainDatFile : string;
Info : TDosGamePlayInfoRec;
WhichLevel : TWhichLevel;
SoundOptions : TGameSoundOptions;
Level : TLevel;
Style : TBaseDosLemmingStyle;
GraphicSet : TBaseDosGraphicSet;
Renderer : TRenderer;
// this is initialized by the window in which the game will be played
TargetBitmap : TBitmap32;
// this is initialized by the game
GameResult: TGameResultsRec;
// this is set by the individual screens when closing (if they know)
NextScreen: TGameScreenType;
// resource vars
LemDataInResource : Boolean;
LemDataOnDisk : Boolean;
LemSoundsInResource : Boolean;
LemSoundsOnDisk : Boolean;
LemMusicInResource : Boolean;
LemMusicOnDisk : Boolean;
// cheat
// Cheatmode: Boolean; // levelcode screen
MiscOptions : TMiscOptions;
fZoomFactor : Integer;
fLevelPack : String;
fExternalPrefix : String;
// set if replay loaded in postviewscreen
//StartupWithReplay : Boolean;
{$ifdef testmode}
fTestMode : Boolean;
fTestGroundFile : String;
fTestVgagrFile : String;
fTestVgaspecFile : String;
fTestLevelFile : String;
fQuickTestMode : integer;
{$endif}
{$ifdef cust}{$ifndef flexi}
fMechanics : Integer;
{$endif}{$endif}
{$ifdef flexi}
SysDat : TSysDatRec;
{$endif}
constructor Create;
procedure LoadFromIniFile(const aFileName: string);
procedure SaveToIniFile(const aFileName: string);
{$ifdef flexi}property LevelPack: String read fLevelPack write fLevelPack;{$endif}
{$ifndef cust}property LevelPack: String read fLevelPack write fLevelPack;{$endif}
property Directory: string read fDirectory write fDirectory;
property DumpMode: boolean read fDumpMode write fDumpMode;
published
{ easy readable published props for streaming to inifile }
property CheatCodesEnabled: Boolean read GetCheatCodesEnabled write SetCheatCodesEnabled;
property MusicEnabled: Boolean read GetMusicEnabled write SetMusicEnabled;
property SoundEnabled: Boolean read GetSoundEnabled write SetSoundEnabled;
property ShowParticles: Boolean read GetShowParticles write SetShowParticles;
property LookForLVLFiles: Boolean read GetLookForLVLFiles write SetLookForLVLFiles;
{$ifdef cust}{$ifndef flexi}property Mechanics: Integer read fMechanics write fMechanics;
property LevelPack: String read fLevelPack write fLevelPack;
property ExternalPrefix: String read fExternalPrefix write fExternalPrefix;{$endif}{$endif}
property LemmixTrapBug: boolean read GetLemmixTrapBug write SetLemmixTrapBug;
{$ifdef testmode}property QuickTestMode: Integer read fQuickTestMode write fQuickTestMode;{$endif}
property StateControlEnabled: Boolean read GetStateControlEnabled write SetStateControlEnabled;
property PauseAssignEnabled: Boolean read GetPauseAssignEnabled write SetPauseAssignEnabled;
{ zoom }
property ZoomFactor: Integer read fZoomFactor write fZoomFactor;
end;
implementation
{ TDosGameParams }
constructor TDosGameParams.Create;
begin
inherited Create;
MiscOptions := DEF_MISCOPTIONS;
LevelPack := 'LEVELPAK.DAT';
fDumpMode := false;
{$ifdef develop}
Include(MiscOptions, moCheatCodes);
{$endif}
{$ifdef resourcelemdata}
LemDataInResource := True;
{$endif}
{$ifdef resourcelemsounds}
LemSoundsInResource := True;
{$endif}
{$ifdef resourcelemmusic}
LemMusicInResource := True;
{$endif}
{.$ifdef resourcebassmod}
{.$endif}
end;
function TDosGameParams.GetCheatCodesEnabled: Boolean;
begin
Result := moCheatCodes in MiscOptions;
end;
function TDosGameParams.GetLevelPackName: String;
begin
Result := fLevelPackName;
end;
procedure TDosGameParams.SetLevelPackName(Value: String);
begin
fLevelPackName := Value;
end;
function TDosGameParams.GetMusicEnabled: Boolean;
begin
Result := gsoMusic in SoundOptions;
end;
function TDosGameParams.GetShowParticles: Boolean;
begin
Result := moShowParticles in MiscOptions;
end;
function TDosGameParams.GetSoundEnabled: Boolean;
begin
Result := gsoSound in SoundOptions;
end;
function TDosGameParams.GetLookForLVLFiles: Boolean;
begin
Result := moLookForLVLFiles in MiscOptions;
end;
function TDosGameParams.GetLemmixTrapBug: Boolean;
begin
Result := moLemmixTrapBug in MiscOptions;
end;
function TDosGameParams.GetStateControlEnabled: Boolean;
begin
Result := moStateControlEnabled in MiscOptions;
end;
function TDosGameParams.GetPauseAssignEnabled: Boolean;
begin
Result := moPauseAssignEnabled in MiscOptions;
end;
procedure TDosGameParams.LoadFromIniFile(const aFileName: string);
begin
IniToObject(aFileName, 'GameSettings', Self, False);
end;
procedure TDosGameParams.SaveToIniFile(const aFileName: string);
begin
ObjectToIni(aFileName, 'GameSettings', Self, False);
end;
procedure TDosGameParams.SetCheatCodesEnabled(Value: Boolean);
begin
case Value of
False: Exclude(MiscOptions, moCheatCodes);
True: Include(MiscOptions, moCheatCodes);
end;
end;
procedure TDosGameParams.SetMusicEnabled(Value: Boolean);
begin
case Value of
False: Exclude(SoundOptions, gsoMusic);
True: Include(SoundOptions, gsoMusic);
end;
end;
procedure TDosGameParams.SetShowParticles(const Value: Boolean);
begin
case Value of
False: Exclude(MiscOptions, moShowParticles);
True: Include(MiscOptions, moShowParticles);
end;
end;
procedure TDosGameParams.SetSoundEnabled(Value: Boolean);
begin
case Value of
False: Exclude(SoundOptions, gsoSound);
True: Include(SoundOptions, gsoSound);
end;
end;
procedure TDosGameParams.SetLookForLVLFiles(Value: Boolean);
begin
case Value of
False: Exclude(MiscOptions, moLookForLVLFiles);
True: Include(MiscOptions, moLookForLVLFiles);
end;
end;
procedure TDosGameParams.SetLemmixTrapBug(Value: Boolean);
begin
case Value of
False: Exclude(MiscOptions, moLemmixTrapBug);
True: Include(MiscOptions, moLemmixTrapBug);
end;
end;
procedure TDosGameParams.SetStateControlEnabled(Value: Boolean);
begin
case Value of
False: Exclude(MiscOptions, moStateControlEnabled);
True: Include(MiscOptions, moStateControlEnabled);
end;
end;
procedure TDosGameParams.SetPauseAssignEnabled(Value: Boolean);
begin
case Value of
False: Exclude(MiscOptions, moPauseAssignEnabled);
True: Include(MiscOptions, moPauseAssignEnabled);
end;
end;
function TDosGameParams.GetUseSystemCursor: Boolean;
begin
// Result := moUseSystemCursor in MiscOptions;
end;
procedure TDosGameParams.SetUseSystemCursor(const Value: Boolean);
begin
{case Value of
False: Exclude(MiscOptions, moUseSystemCursor);
True: Include(MiscOptions, moUseSystemCursor);
end;}
end;
end.
|
unit ASUProc;
// Процедуры обработки пакетов из сети АСУ
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls;
const
ASU1_PACKET_IKONKI_LENGTH = 1000; // длина пакета для передачи 200 табличек
var
IkonkiOut : array[0..1006] of char; // буфер массива табличек для передачи в канал АСУ
IkonkiIn : array[0..999] of char; // буфер для массива табличек, полученых из канала АСУ
Dat : array[1..1000] of byte;
CountState : Integer;
function ExtractPacketASU(Buf : pchar; pLen : PInteger) : Boolean; // распаковка пакетов АСУ
procedure IkonkiApply(cru,extype : byte); // применить массив табличек, полученный из канала АСУ
procedure IkonkiPack; // упаковка массива информационных табличек
implementation
uses
TypeAll,
//VarStruct,
crccalc,
PipeProc;
//------------------------------------------------------------------------------
// распаковка пакетов АСУ
function ExtractPacketASU(Buf : pchar; pLen : PInteger) : Boolean;
var i,j,k : integer; ptype,sru,etype, bh,bl : byte; ln : word; crc : crc16_t;
begin
result := false;
if not Assigned(pLen) then exit;
ln := word(pLen^);
if ln = 0 then exit;
repeat
i := 0;
while i < ln do
begin
if Buf[i] = #$AA then
begin
if i > 0 then
begin // урезать голову строки
j := 0; k := i;
while k < Ln do
begin
Buf[j] := Buf[k]; inc(k); inc(j);
end;
Ln := j;
end;
break;
end else
inc(i);
end;
if i > ln then
begin // нет заголовка в полученом фрагменте
pLen^ := 0; exit;
end;
if ln < 10 then begin pLen^ := ln; exit; end;
i := 1; ptype := byte(Buf[i]); // тип пакета
inc(i); etype := byte(Buf[i]); // вид обработки
inc(i); sru := byte(Buf[i]); // код района
case ptype of
105 : begin // массив информационных табличек
if ln < 1007 then exit; // неполный пакет
if Buf[1006] = #$55 then
begin
crc := CalculateCRC16(@Buf[1],1003);
bl := byte(Buf[1004]); bh := byte(Buf[1005]);
if crc = (bl + bh *$100) then
begin // получен пакет с массивом табличек
for k := 0 to 999 do IkonkiIn[k] := Buf[k+4];
IkonkiApply(sru,etype);
// продолжить поиск в буфере
j := 1; k := 1007; while k < Ln do begin Buf[j] := Buf[k];inc(k);inc(j); end; Ln := j-1;
end else
begin // контрольная сумма ошибочная - найти заголовок дальше по тексту
j := 1; k := 2; while k < Ln do begin Buf[j] := Buf[k];inc(k);inc(j); end; Ln := j-1;
end;
end;
end;
else
// неизвестный тип пакета - найти заголовок дальше по тексту
j := 1; k := 2; while k <= Ln do begin Buf[j] := Buf[k];inc(k);inc(j); end; Ln := j-1;
end;
until false;
end;
//------------------------------------------------------------------------------
// применить массив табличек, полученный из канала АСУ
procedure IkonkiApply(cru,extype : byte);
var i,j : integer; bh,bl : byte;
begin
if (extype < $10) and (extype < IkonPri) and (config.ru = cru) then
begin // применить массив из канала ДСП-ДСП
j := 0;
for i := 1 to 200 do
begin
case cru of
1 : begin
Ikonki[i,1] := byte(IkonkiIn[j]); inc(j); bl := byte(IkonkiIn[j]); inc(j); bh := byte(IkonkiIn[j]); inc(j); Ikonki[i,2] := bl + bh * $100; bl := byte(IkonkiIn[j]); inc(j); bh := byte(IkonkiIn[j]); inc(j); Ikonki[i,3] := bl + bh * $100;
end;
2 : begin
Ikonki2[i,1] := byte(IkonkiIn[j]); inc(j); bl := byte(IkonkiIn[j]); inc(j); bh := byte(IkonkiIn[j]); inc(j); Ikonki2[i,2] := bl + bh * $100; bl := byte(IkonkiIn[j]); inc(j); bh := byte(IkonkiIn[j]); inc(j); Ikonki2[i,3] := bl + bh * $100;
end;
else
break;
end;
end;
end;
end;
//------------------------------------------------------------------------------
// упаковка массива информационных табличек в формат канала АСУ
procedure IkonkiPack;
var i,j : integer; bh,bl : Byte; w : Word; crc : crc16_t;
begin
j := 0;
IkonkiOut[j] := #$AA; inc(j);
IkonkiOut[j] := #105; inc(j);
IkonkiOut[j] := char(IkonPri); inc(j);
IkonkiOut[j] := char(config.ru); inc(j);
// сформировать массив табличек
case config.ru of
1 : begin
for i := 1 to High(Ikonki) do
begin
IkonkiOut[j] := char(Ikonki[i,1]); inc(j);
w := Ikonki[i,2]; bh := w shr 8; bl := w - bh * $100; IkonkiOut[j] := char(bl); inc(j); IkonkiOut[j] := char(bh); inc(j);
w := Ikonki[i,3]; bh := w shr 8; bl := w - bh * $100; IkonkiOut[j] := char(bl); inc(j); IkonkiOut[j] := char(bh); inc(j);
end;
end;
2 : begin
for i := 1 to High(Ikonki2) do
begin
IkonkiOut[j] := char(Ikonki2[i,1]); inc(j);
w := Ikonki2[i,2]; bh := w shr 8; bl := w - bh * $100; IkonkiOut[j] := char(bl); inc(j); IkonkiOut[j] := char(bh); inc(j);
w := Ikonki2[i,3]; bh := w shr 8; bl := w - bh * $100; IkonkiOut[j] := char(bl); inc(j); IkonkiOut[j] := char(bh); inc(j);
end;
end;
end;
crc := CalculateCRC16(@IkonkiOut[1],1003); // подсчитать контрольную сумму
bh := crc shr 8; bl := crc - bh * $100; IkonkiOut[j] := char(bl); inc(j); IkonkiOut[j] := char(bh); inc(j);
IkonkiOut[j] := #$55;
end;
end.
|
unit Utils;
interface
uses
Classes, SysUtils, Windows, Forms;
type
TStrings = array of string;
TCharSet = set of Char;
TApplicationVersion = record
Major, Minor, Release, Build: Word;
end;
const
Space: string = ' ';
LineBreak: string = #10#13;
Number: string = '#';
DecCharSet: TCharSet = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
HexCharSet: TCharSet = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F'];
UserNameCharSet: TCharSet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '_', '-', '.'];
function ApplicationVersion: TApplicationVersion;
function ApplicationFileName: string;
function SettingsFileName: string;
function AddStr(const Str: string; const AdditionalStr: string;
const DelimiterStr: string): string;
procedure WriteStrToFile(const Str: string; const FileName: string);
function CharCount(const Ch: Char; const Str: string): Integer;
function CharPos(const Ch: Char; const Str: string): Integer;
function StrConsistsOfChars(const Str: string; const CharSet:
TCharSet): Boolean;
function DisAssembleStr(const Str: string; const Delimiter: Char): TStrings;
function EncodeStr(const Str: string; const EmptyStrCode: string;
const CharsPerEncodedChar: Integer): string;
function DecodeStr(const Str: string; const EmptyStrCode: string;
const CharsPerEncodedChar: Integer): string;
function IntBetween(const Value: Integer; const MinValue: Integer;
const MaxValue: Integer; const Strict: Boolean = True): Boolean;
implementation
function ApplicationVersion: TApplicationVersion;
const
VersionShrBits: Integer = 16;
HexFullBits: Integer = $FFFF;
var
Info: Pointer;
FileInfo: PVSFixedFileInfo;
InfoSize, FileSize: Cardinal;
begin
InfoSize := GetFileVersionInfoSize(PChar(Application.ExeName), FileSize);
GetMem(Info, InfoSize);
try
GetFileVersionInfo(PChar(Application.ExeName), 0, InfoSize, Info);
VerQueryValue(Info, '\', Pointer(FileInfo), FileSize);
Result.Major := FileInfo.dwFileVersionMS shr VersionShrBits;
Result.Minor := FileInfo.dwFileVersionMS and HexFullBits;
Result.Release := FileInfo.dwFileVersionLS shr VersionShrBits;
Result.Build := FileInfo.dwFileVersionLS and HexFullBits;
finally
FreeMem(Info);
end;
end;
function ApplicationFileName: string;
begin
Result := ParamStr(0);
end;
function SettingsFileName: string;
const
SettingsFileExt: string = '.ini';
begin
Result := ChangeFileExt(ParamStr(0), SettingsFileExt);
end;
function AddStr(const Str: string; const AdditionalStr: string;
const DelimiterStr: string): string;
begin
if Str = EmptyStr then
begin
Result := AdditionalStr;
end
else
begin
Result := Str + DelimiterStr + AdditionalStr;
end;
end;
procedure WriteStrToFile(const Str: string; const FileName: string);
var
S: string;
F: TFileStream;
PStr: PChar;
StrLength: Integer;
begin
S := Str + LineBreak;
StrLength := Length(S);
PStr := StrAlloc(StrLength + 1);
StrPCopy(PStr, S);
try
if FileExists(FileName) then
begin
F := TFileStream.Create(FileName, fmOpenWrite);
end
else
begin
F := TFileStream.Create(FileName, fmCreate);
end;
try
F.Position := F.Size;
F.Write(PStr^, StrLength);
finally
F.Free;
end;
finally
StrDispose(PStr);
end;
end;
function CharCount(const Ch: Char; const Str: string): Integer;
var
CharCounter: Integer;
begin
Result := 0;
for CharCounter := 1 to Length(Str) do
begin
if Str[CharCounter] = Ch then
begin
Inc(Result);
end;
end;
end;
function CharPos(const Ch: Char; const Str: string): Integer;
var
CharCounter: Integer;
begin
Result := 0;
for CharCounter := 1 to Length(Str) do
begin
if Str[CharCounter] = Ch then
begin
Result := CharCounter;
Break;
end;
end;
end;
function StrConsistsOfChars(const Str: string; const CharSet: TCharSet): Boolean;
var
CharCounter: Integer;
begin
Result := True;
if (Str <> EmptyStr) and (CharSet <> []) then
begin
for CharCounter := 1 to Length(Str) do
begin
if not (Str[CharCounter] in CharSet) then
begin
Result := False;
Break;
end;
end;
end
else
begin
Result := False;
end;
end;
function DisAssembleStr(const Str: string; const Delimiter: Char): TStrings;
var
CharCounter, StrLength, ChPos, SubstrCount: Integer;
Substr: string;
begin
SetLength(Result, 0);
StrLength := Length(Str);
SubstrCount := 0;
ChPos := 1;
for CharCounter := 1 to StrLength do
begin
if (Str[CharCounter] = Delimiter) or (CharCounter = StrLength) then
begin
Inc(SubstrCount);
SetLength(Result, SubstrCount);
if StrLength <> CharCounter then
begin
Substr := Copy(Str, ChPos, CharCounter - ChPos);
end
else
begin
Substr := Copy(Str, ChPos, CharCounter - ChPos + 1);
end;
Result[SubstrCount - 1] := Substr;
ChPos := CharCounter + 1;
end;
end;
end;
function EncodeStr(const Str: string; const EmptyStrCode: string;
const CharsPerEncodedChar: Integer): string;
var
CharCounter: Integer;
begin
if Str = EmptyStr then
begin
Result := EmptyStrCode;
end
else
begin
Result := EmptyStr;
for CharCounter := 1 to Length(Str) do
begin
Result := Result + IntToHex(Ord(Str[CharCounter]), CharsPerEncodedChar);
end;
end;
end;
function DecodeStr(const Str: string; const EmptyStrCode: string;
const CharsPerEncodedChar: Integer): string;
var
CharCounter: Integer;
EncodedCharStr: string;
begin
Result := EmptyStr;
if Str <> EmptyStrCode then
begin
EncodedCharStr := EmptyStr;
for CharCounter := 1 to Length(Str) do
begin
EncodedCharStr := EncodedCharStr + Str[CharCounter];
if Length(EncodedCharStr) = CharsPerEncodedChar then
begin
Result := Result + Chr(StrToInt('$' + EncodedCharStr));
EncodedCharStr := EmptyStr;
end;
end;
end;
end;
function IntBetween(const Value: Integer; const MinValue: Integer;
const MaxValue: Integer; const Strict: Boolean = True): Boolean;
begin
if Strict then
begin
Result := (Value >= MinValue) and (Value <= MaxValue);
end
else
begin
Result := (Value > MinValue) and (Value < MaxValue);
end;
end;
end.
|
unit SpawnClient;
{
Inno Setup
Copyright (C) 1997-2007 Jordan Russell
Portions by Martijn Laan
For conditions of distribution and use, see LICENSE.TXT.
Spawn client
NOTE: These functions are NOT thread-safe. Do not call them from multiple
threads simultaneously.
$jrsoftware: issrc/Projects/SpawnClient.pas,v 1.5 2007/09/05 02:07:35 jr Exp $
}
interface
uses
Windows, SysUtils, Messages, InstFunc;
procedure InitializeSpawnClient(const AServerWnd: HWND);
function InstExecEx(const RunAsOriginalUser: Boolean;
const DisableFsRedir: Boolean; const Filename, Params, WorkingDir: String;
const Wait: TExecWait; const ShowCmd: Integer;
const ProcessMessagesProc: TProcedure; var ResultCode: Integer): Boolean;
function InstShellExecEx(const RunAsOriginalUser: Boolean;
const Verb, Filename, Params, WorkingDir: String;
const Wait: TExecWait; const ShowCmd: Integer;
const ProcessMessagesProc: TProcedure; var ResultCode: Integer): Boolean;
implementation
uses
Classes, CmnFunc2, SpawnCommon;
var
SpawnServerPresent: Boolean;
SpawnServerWnd: HWND;
procedure WriteLongintToStream(const M: TMemoryStream; const Value: Longint);
begin
M.WriteBuffer(Value, SizeOf(Value));
end;
procedure WriteStringToStream(const M: TMemoryStream; const Value: String);
var
Len: Integer;
begin
Len := Length(Value);
if Len > $FFFF then
InternalError('WriteStringToStream: Length limit exceeded');
WriteLongintToStream(M, Len);
M.WriteBuffer(Value[1], Len * SizeOf(Value[1]));
end;
procedure AllowSpawnServerToSetForegroundWindow;
{ This is called to allow processes started by the spawn server process to
come to the foreground, above the current process's windows. The effect
normally lasts until new input is generated (a keystroke or click, not
simply mouse movement).
Note: If the spawn server process has no visible windows, it seems this
isn't needed (on 2000 & Vista); the process can set the foreground window
as it pleases. If it does have a visible window, though, it definitely is
needed (e.g. in the /DebugSpawnServer case). Let's not rely on any
undocumented behavior and call AllowSetForegroundWindow unconditionally. }
var
PID: DWORD;
AllowSetForegroundWindowFunc: function(dwProcessId: DWORD): BOOL; stdcall;
begin
if GetWindowThreadProcessId(SpawnServerWnd, @PID) <> 0 then begin
AllowSetForegroundWindowFunc := GetProcAddress(GetModuleHandle(user32),
'AllowSetForegroundWindow');
if Assigned(AllowSetForegroundWindowFunc) then
AllowSetForegroundWindowFunc(PID);
end;
end;
function QuerySpawnServer(const SequenceNumber: Word;
const Operation: Integer): Word;
var
MsgResult: LRESULT;
begin
MsgResult := SendMessage(SpawnServerWnd, WM_SpawnServer_Query, Operation,
SequenceNumber);
if MsgResult and not $FFFF <> SPAWN_MSGRESULT_SUCCESS_BITS then
InternalErrorFmt('QuerySpawnServer: Unexpected response: $%x', [MsgResult]);
Result := Word(MsgResult);
end;
function CallSpawnServer(const CopyDataMsg: DWORD; var M: TMemoryStream;
const ProcessMessagesProc: TProcedure; var ResultCode: Integer): Boolean;
var
CopyDataStruct: TCopyDataStruct;
MsgResult: LRESULT;
SequenceNumber: Word;
Status: Word;
LastQueryTime, NowTime: DWORD;
begin
CopyDataStruct.dwData := CopyDataMsg;
CopyDataStruct.cbData := M.Size;
CopyDataStruct.lpData := M.Memory;
AllowSpawnServerToSetForegroundWindow;
MsgResult := SendMessage(SpawnServerWnd, WM_COPYDATA, 0, LPARAM(@CopyDataStruct));
FreeAndNil(M); { it isn't needed anymore, might as well free now }
if MsgResult = SPAWN_MSGRESULT_OUT_OF_MEMORY then
OutOfMemoryError;
if MsgResult and not $FFFF <> SPAWN_MSGRESULT_SUCCESS_BITS then
InternalErrorFmt('CallSpawnServer: Unexpected response: $%x', [MsgResult]);
SequenceNumber := Word(MsgResult);
Status := 0; { avoid compiler warning }
LastQueryTime := GetTickCount;
repeat
ProcessMessagesProc;
{ Now that the queue is empty (we mustn't break without first processing
messages found by a previous MsgWaitForMultipleObjects call), see if
the status changed, but only if at least 10 ms has elapsed since the
last query }
NowTime := GetTickCount;
if Cardinal(NowTime - LastQueryTime) >= Cardinal(10) then begin
LastQueryTime := NowTime;
Status := QuerySpawnServer(SequenceNumber, SPAWN_QUERY_STATUS);
case Status of
SPAWN_STATUS_RUNNING: ;
SPAWN_STATUS_RETURNED_TRUE, SPAWN_STATUS_RETURNED_FALSE: Break;
else
InternalErrorFmt('CallSpawnServer: Unexpected status: %d', [Status]);
end;
end;
{ Delay for 10 ms, or until a message arrives }
MsgWaitForMultipleObjects(0, THandle(nil^), False, 10, QS_ALLINPUT);
until False;
ResultCode := QuerySpawnServer(SequenceNumber, SPAWN_QUERY_RESULTCODE_LO) or
(QuerySpawnServer(SequenceNumber, SPAWN_QUERY_RESULTCODE_HI) shl 16);
Result := (Status = SPAWN_STATUS_RETURNED_TRUE);
end;
function InstExecEx(const RunAsOriginalUser: Boolean;
const DisableFsRedir: Boolean; const Filename, Params, WorkingDir: String;
const Wait: TExecWait; const ShowCmd: Integer;
const ProcessMessagesProc: TProcedure; var ResultCode: Integer): Boolean;
var
M: TMemoryStream;
begin
if not RunAsOriginalUser or not SpawnServerPresent then begin
Result := InstExec(DisableFsRedir, Filename, Params, WorkingDir,
Wait, ShowCmd, ProcessMessagesProc, ResultCode);
Exit;
end;
M := TMemoryStream.Create;
try
WriteLongintToStream(M, Ord(DisableFsRedir));
WriteStringToStream(M, Filename);
WriteStringToStream(M, Params);
WriteStringToStream(M, WorkingDir);
WriteLongintToStream(M, Ord(Wait));
WriteLongintToStream(M, ShowCmd);
WriteStringToStream(M, GetCurrentDir);
Result := CallSpawnServer(CD_SpawnServer_Exec, M, ProcessMessagesProc,
ResultCode);
finally
M.Free;
end;
end;
function InstShellExecEx(const RunAsOriginalUser: Boolean;
const Verb, Filename, Params, WorkingDir: String;
const Wait: TExecWait; const ShowCmd: Integer;
const ProcessMessagesProc: TProcedure; var ResultCode: Integer): Boolean;
var
M: TMemoryStream;
begin
if not RunAsOriginalUser or not SpawnServerPresent then begin
Result := InstShellExec(Verb, Filename, Params, WorkingDir,
Wait, ShowCmd, ProcessMessagesProc, ResultCode);
Exit;
end;
M := TMemoryStream.Create;
try
WriteStringToStream(M, Verb);
WriteStringToStream(M, Filename);
WriteStringToStream(M, Params);
WriteStringToStream(M, WorkingDir);
WriteLongintToStream(M, Ord(Wait));
WriteLongintToStream(M, ShowCmd);
WriteStringToStream(M, GetCurrentDir);
Result := CallSpawnServer(CD_SpawnServer_ShellExec, M, ProcessMessagesProc,
ResultCode);
finally
M.Free;
end;
end;
procedure InitializeSpawnClient(const AServerWnd: HWND);
begin
SpawnServerWnd := AServerWnd;
SpawnServerPresent := True;
end;
end.
|
unit vtStringLister;
{ Библиотека "" }
{ Начал: Люлин А.В. }
{ Модуль: vtStringLister - }
{ Начат: 30.05.2005 16:36 }
{ $Id: vtStringLister.pas,v 1.6 2007/03/20 13:38:56 lulin Exp $ }
// $Log: vtStringLister.pas,v $
// Revision 1.6 2007/03/20 13:38:56 lulin
// - избавляемся от лишних преобразований строк.
//
// Revision 1.5 2007/02/16 17:17:26 lulin
// - избавляемся от стандартного строкового типа.
//
// Revision 1.4 2007/02/13 11:44:32 mmorozov
// - new: заголовок дерева (TvtHeader) использует таблицу стилей (CQ: OIT5-24283);
//
// Revision 1.3 2006/12/26 13:14:17 lulin
// - cleanup.
//
// Revision 1.2 2006/12/22 15:10:21 lulin
// - bug fix: не собиралась библиотека.
//
// Revision 1.1 2005/05/30 13:02:22 lulin
// - new unit: vtStringLister.
//
{$Include vtDefine.inc }
interface
uses
Classes,
l3Interfaces,
l3Types,
vtLister
;
type
TvtStringLister = class(TvtCustomLister)
{*! Видимый элемент для отображения списка строк из TStrings. }
private
FAlienSource : Boolean;
FItems : TStrings;
procedure ListChange(Sender: TObject);
protected
function DoOnGetItem(Index : LongInt) : Il3CString;
override;
procedure SetItems(Value: TStrings);
function GetSorted : Boolean;
Procedure SetSorted(Value : Boolean);
{procedure CharToItem(Sender : TObject; Var SrchStr : String; var Index : LongInt);}
procedure Cleanup;
override;
{-}
public
Constructor Create(AOwner: TComponent); override;
procedure SetItemsList(Value : TStrings; NeedDestroy : Boolean);
property SelectArray;
published
property Items : TStrings Read FItems Write SetItems;
{* - элементы для отображения. }
property Sorted : Boolean Read GetSorted Write SetSorted;
{* - признак сортировки. }
property AlienSource : Boolean Read FAlienSource Write FAlienSource;
{* - признак того что этот элемент не владеет Items и не должен освобождать их. }
property Images;
property AutoRowHeight;
property BorderStyle;
property Columns;
property Header;
property IntegralHeight;
property MultiSelect;
property ProtectColor;
property RowHeight;
property ScrollStyle;
property SelectColor;
property SelectNonFocusColor;
property ShowHeader;
property UseTabStops;
property PickedList;
property TriplePicked;
property MultiStrokeItem;
property ReadOnly;
property ViewOptions;
// property OnClickHeader;
property OnGetItemImageIndex;
property OnGetItemColor;
property OnGetItemFont;
property OnGetItemCursor;
property OnGetItemStatus;
property OnIsSelected;
property OnSelect;
property OnSelectChange;
property OnSelectChanged;
property OnTopIndexChanged;
property OnCurrentChanged;
property OnCountChanged;
property OnUserCommand;
property OnIsCommandProcessed;
{inherited properties}
property Align;
property Color;
property Controller;
property Ctl3D;
property DragCursor;
property DragMode;
property Enabled;
property Font;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property Anchors;
property Constraints;
{inherited events}
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnActionElement;
end;//TvtStringLister
implementation
uses
SysUtils,
l3Base,
l3String,
OvcConst,
OvcData
;
// start class TvtStringLister
constructor TvtStringLister.Create(AOwner: TComponent);
begin
inherited;
fItems := TStringList.Create;
TStringList(FItems).OnChange:=ListChange;
OnCharToItem := CharToItem;
end;
procedure TvtStringLister.Cleanup;
begin
if FItems <> nil then
begin
if (FItems Is TStringList) then
TStringList(FItems).OnChange := nil;
if not FAlienSource then FItems.Free;
end;
Inherited;
end;
procedure TvtStringLister.SetItems(Value: TStrings);
begin
if fItems <> Value then
fItems.Assign(Value);
Total := fItems.Count;
end;
procedure TvtStringLister.SetItemsList(Value : TStrings; NeedDestroy : Boolean);
begin
if (FItems <> Value) then
begin
if FAlienSource
then
begin
if (FItems <> nil) AND (FItems Is TStringList) then
TStringList(FItems).OnChange := nil;
end
else FItems.Free;
end;
FItems:=Value;
if (FItems <> nil)
then
begin
if (FItems Is TStringList) then TStringList(FItems).OnChange:=ListChange;
Total:=FItems.Count;
end
else
Total:=0;
AlienSource:=not NeedDestroy;
end;
function TvtStringLister.GetSorted : Boolean;
begin
if (FItems Is TStringList) then Result:=TStringList(FItems).Sorted else Result := false;
end;
procedure TvtStringLister.SetSorted(Value : Boolean);
begin
if (FItems Is TStringList) then TStringList(FItems).Sorted:=Value;
end;
procedure TvtStringLister.ListChange(Sender: TObject);
begin
Changing;
try
Total := FItems.Count;
finally
Changed;
end;
end;
function TvtStringLister.DoOnGetItem(Index : LongInt) : Il3CString;
begin
if (csDesigning in ComponentState) and (FItems.Count <= 0) then
Result := l3Fmt(GetOrphStr(SCSampleListItem), [Index])
else
Result := l3CStr(FItems.Strings[Index]);
end;
end.
|
unit Gifs;
interface
uses
Classes, Windows, SysUtils, GDI, Dibs;
const
idGifSignature = 'GIF';
idGifVersion87a = '87a';
idGifVersion89a = '89a';
const
// Logical screen descriptor bit masks
lbmGlobalColorTable = $80; // set if global color table follows L.S.D.
lbmColorResolution = $70; // Color resolution - 3 bits
lbmSort = $08; // set if global color table is sorted - 1 bit
lbmColorTableSize = $07; // size of global color table - 3 bits
// Actual size = 2^value+1 - value is 3 bits
type
PLogicalScreenDescriptor = ^TLogicalScreenDescriptor;
TLogicalScreenDescriptor = // 7 6 5 4 3 2 1 0
packed record // +---------------+ Raster width in pixels ( LSB first )
Width : word; // + Screen Width + 0
Height : word; // +---------------+ Raster height in pixels ( LSB first )
BitMask : byte; // + Screen Height + 2
BackColor : byte; // +-+-----+-+-----+ M = 1, Global color map follows Descriptor
Ratio : byte; // |M| cr |0|pixel| 4 cr + 1 = # bits of color resolution
end; // +-+-----+-+-----+ pixel + 1 = # bits/pixel in image
// | background | 5
// +---------------+ background=Color index of screen background
// | Pixel Ratio | 6 (color is defined from the Global color
// +---------------+ map or default map if none specified)
//
// Aspect Ratio = (Pixel Aspect Ratio + 15) / 64
//
// The Pixel Aspect Ratio is defined to be the quotient of the pixel's
// width over its height. The value range in this field allows
// specification of the widest pixel of 4:1 to the tallest pixel of
// 1:4 in increments of 1/64th.
//
// Values : 0 - No aspect ratio information is given.
// 1..255 - Value used in the computation.
const
sigGIF = 'GIF';
sigVersion89 = '89a';
sigVersion87 = '87a';
type
PGifFileHeader = ^TGifFileHeader;
TGifFileHeader =
packed record
strSignature : array[0..2] of char;
strVersion : array[0..2] of char;
Header : TLogicalScreenDescriptor;
end;
type
PGifColorTable = ^TGifColorTable;
TGifColorTable = array[0..255] of TDosRgb; // 0..2^(BitCount)
const // Gif block IDs
gifSignature = ord( 'G' );
gifExtensionId = ord( '!' );
gifImageId = ord( ',' );
gifTerminatorId = ord( ';' );
gifPlainTextId = $01;
gifGraphicControlId = $f9;
gifCommentId = $fe;
gifApplicationId = $ff;
const // Image descriptor bit masks
ibmLocalColorTable = $80; // set if a local color table follows
ibmInterlaced = $40; // set if image is interlaced
ibmSort = $20; // set if color table is sorted
ibmReserved = $0C; // reserved - must be set to $00
ibmColorTableSize = $07; // size of color table as in LSD
type
PGifImageDescriptor = ^TGifImageDescriptor;
TGifImageDescriptor =
packed record
Signature : byte; // Block signature, ',' for images
Left : word; // Column in pixels in respect to left edge of logical screen
Top : word; // row in pixels in respect to top of logical screen
Width : word; // width of image in pixels
Height : word; // height of image in pixels
BitMask : byte; // See image descriptor bitmasks
end;
const // Graphic control extension bit masks
gbmReserved = $e0; // For future use
gbmDisposalMethod = $1c; //
gbmUserInput = $02;
gbmTransparent = $01;
const // Disposal methods
dmIgnore = 0;
dmDontDispose = 1;
dmRestoreBackground = 2;
dmRestorePrevios = 3;
type
PGraphicControlExtension = ^TGraphicControlExtension;
TGraphicControlExtension =
packed record
Signature : byte; // Block signature, '!' for extensions
ExtensionId : byte; // Id for extensions, $F9 for graphic control extensions
BlockSize : byte; // Size is 4 for graphic control extensions (Count starts after BlockSize but w/out Terminator field)
BitMask : byte;
DelayTime : word;
TransparentIndx : byte;
Terminator : byte; // A zero
end;
type
PCommentExtensionHeader = ^TCommentExtensionHeader;
TCommentExtensionHeader =
packed record
Signature : byte; // Block signature, '!' for extensions
ExtensionId : byte; // Id for extensions, $fe for comment extensions
end;
PCommentExtension = ^TCommentExtension;
TCommentExtension =
record
Text : string;
Header : TCommentExtensionHeader;
end;
type
PPlainTextExtensionHeader = ^TPlainTextExtensionHeader;
TPlainTextExtensionHeader =
packed record
Signature : byte; // Block signature, '!' for extensions
ExtensionId : byte; // Id for extensions, $01 for plain text extensions
BlockSize : byte;
GridLeft : word;
GridTop : word;
GridWidth : word;
GridHeight : word;
CellWidth : byte;
CellHeight : byte;
ForegroundIndx : byte;
BackgroundIndx : byte;
end;
PPlainTextExtension = ^TPlainTextExtension;
TPlainTextExtension =
record
Text : string;
Header : TPlainTextExtensionHeader;
end;
type
PAppExtensionHeader = ^TAppExtensionHeader;
TAppExtensionHeader =
packed record
Signature : byte; // Block signature, '!' for extensions
ExtensionId : byte; // Id for extensions, $ff for application extensions
BlockSize : byte;
AppId : array[0..7] of char;
AppAuthentication : array[0..2] of byte;
end;
PAppExtension = ^TAppExtension;
TAppExtension =
record
DataSize : integer;
Data : pointer;
Header : TAppExtensionHeader;
end;
// GIF Error Handling ===========================================================
type
EGifError =
class( Exception )
private
fErrorCode : integer;
public
constructor Create( const ErrorMessage : string; ErrorCode : integer );
public
property ErrorCode : integer read fErrorCode;
end;
const
errNoError = 0;
errIllegalGIFStream = 1;
errIOError = 2;
errOutOfMemory = 3;
errLZWStackOverFlow = 4;
errLZWCircularTableEntry = 5;
errMissingEOD = 6;
errIllegalPixelValue = 7;
errNotAGIFStream = 8;
errIllegalGIFVersion = 9;
errUnknownError = 10;
// Gif Decoding
procedure UnpackGIFPixels( aStream : TStream; GifWidth, GifHeight : integer; DestPixels : pointer; DestWidth : integer; Interlaced : boolean );
// Helper functions
const
bidGifTerminator = 0;
bidGifHeader = 1;
bidGifImageDescriptor = 2;
bidGraphControlExt = 3;
bidCommentExt = 4;
bidPlainTextExt = 5;
bidAppExt = 6;
bidUnknown = $ff;
type
TBlockIds = set of byte;
procedure GifSkipSubBlocks( Stream : TStream );
function GifSkipBlocksExcept( Stream : TStream; BlockIds : TBlockIds ) : integer;
function GifReadBlockId( Stream : TStream ) : integer;
procedure GifReadBlockInfo( Stream : TStream; BlockId : integer; var Data );
function GifReadSubBlocks( Stream : TStream; var Data : pointer ) : integer;
function GifDibHeaderFromGlobal( GlobalHeader : TLogicalScreenDescriptor ) : PDib;
function GifDibHeaderFromLocal( LocalHeader : TGifImageDescriptor ) : PDib;
implementation
function GifDibHeaderFromGlobal( GlobalHeader : TLogicalScreenDescriptor ) : PDib;
var
BitCount, DibBitCount : integer;
begin
with GlobalHeader do
begin
BitCount := ( BitMask and lbmColorTableSize ) + 1;
case BitCount of
2..4 :
DibBitCount := 4;
5..8 :
DibBitCount := 8;
else
DibBitCount := 1;
end;
Result := DibNewHeader( Width, Height, DibBitCount );
end;
Result.biClrUsed := 1 shl BitCount;
end;
function GifDibHeaderFromLocal( LocalHeader : TGifImageDescriptor ) : PDib;
var
BitCount, DibBitCount : integer;
begin
with LocalHeader do
begin
BitCount := ( BitMask and ibmColorTableSize ) + 1;
case BitCount of
2..4 :
DibBitCount := 4;
5..8 :
DibBitCount := 8;
else
DibBitCount := 1;
end;
Result := DibNewHeader( Width, Height, DibBitCount );
end;
Result.biClrUsed := 1 shl BitCount;
end;
function GifReadSubBlocks( Stream : TStream; var Data : pointer ) : integer;
var
BlockSize : byte;
begin
Result := 0;
Data := nil;
repeat
Stream.ReadBuffer( BlockSize, sizeof( BlockSize ) );
if BlockSize > 0
then
begin
inc( Result, BlockSize );
reallocmem( Data, Result );
Stream.ReadBuffer( pchar(Data)[Result - BlockSize], BlockSize );
end;
until BlockSize = 0;
end;
procedure GifSkipSubBlocks( Stream : TStream );
var
BlockSize : byte;
begin
with Stream do
repeat
ReadBuffer( BlockSize, sizeof( BlockSize ) );
Seek( BlockSize, soFromCurrent );
until BlockSize = 0;
end;
function GifSkipBlocksExcept( Stream : TStream; BlockIds : TBlockIds ) : integer;
var
Found : boolean;
begin
repeat
Result := GifReadBlockId( Stream );
Found := Result in BlockIds;
if not Found
then // Skip
begin
if Result = bidGifImageDescriptor
then
begin
//
end
else
begin
Stream.Seek( 2, soFromCurrent );
GifSkipSubBlocks( Stream );
end;
end;
until Found;
end;
function GifReadBlockId( Stream : TStream ) : integer;
var
StartPos : integer;
Signature : byte;
SigRest : word;
ExtId : byte;
begin
StartPos := Stream.Position;
try
Stream.ReadBuffer( Signature, sizeof( Signature ) );
case Signature of
gifSignature :
begin // OK, first letter was 'G', let's find out if rest is 'IF'
Stream.ReadBuffer( SigRest, sizeof( SigRest ) );
if SigRest <> $4649
then Result := bidGifHeader
else Result := bidUnknown;
end;
gifExtensionId :
begin
Stream.ReadBuffer( ExtId, sizeof( ExtId ) );
case ExtId of
gifPlainTextId :
Result := bidPlainTextExt;
gifGraphicControlId :
Result := bidGraphControlExt;
gifCommentId :
Result := bidCommentExt;
gifApplicationId :
Result := bidAppExt;
else Result := bidUnknown;
end;
end;
gifImageId :
Result := bidGifImageDescriptor;
gifTerminatorId :
Result := bidGifTerminator;
else Result := bidUnknown;
end;
finally
Stream.Position := StartPos;
end;
end;
procedure GifReadBlockInfo( Stream : TStream; BlockId : integer; var Data );
var
GifHeaderData : TGifFileHeader absolute Data;
GifImageData : TGifImageDescriptor absolute Data;
ControlData : TGraphicControlExtension absolute Data;
CommentData : TCommentExtension absolute Data;
PlainTextData : TPlainTextExtension absolute Data;
AppExtData : TAppExtension absolute Data;
TmpData : pchar;
TmpCount : integer;
begin
if BlockId <> bidGifHeader
then GifSkipBlocksExcept( Stream, [BlockId] );
case BlockId of
bidGifHeader :
Stream.ReadBuffer( GifHeaderData, sizeof( GifHeaderData ) );
bidGifImageDescriptor :
Stream.ReadBuffer( GifImageData, sizeof( GifImageData ) );
bidGraphControlExt :
Stream.ReadBuffer( ControlData, sizeof( ControlData ) );
bidCommentExt :
begin
Stream.ReadBuffer( CommentData.Header, sizeof( CommentData.Header ) );
TmpCount := GifReadSubBlocks( Stream, pointer( TmpData ) );
SetString( CommentData.Text, TmpData, TmpCount );
end;
bidPlainTextExt :
begin
Stream.ReadBuffer( PlainTextData.Header, sizeof( PlainTextData.Header ) );
TmpCount := GifReadSubBlocks( Stream, pointer( TmpData ) );
SetString( PlainTextData.Text, TmpData, TmpCount );
end;
bidAppExt :
begin
Stream.ReadBuffer( AppExtData.Header, sizeof( AppExtData.Header ) );
AppExtData.DataSize := GifReadSubBlocks( Stream, AppExtData.Data );
end;
end;
end;
// EGifError
constructor EGifError.Create( const ErrorMessage : string; ErrorCode : integer );
begin
inherited Create( ErrorMessage );
fErrorCode := ErrorCode
end;
// The meat stuff
const
MaxLzwBits = 12;
const
PassIncTable : array[0..3] of byte = ( 8, 8, 4, 2 );
PassInitialPosTable : array[0..3] of byte = ( 0, 4, 2, 1 );
const
MaskTable : array[0..pred( 16 )] of word =
(
$0000, $0001, $0003, $0007, $000f, $001f, $003f, $007f,
$00ff, $01ff, $03ff, $07ff, $0fff, $1fff, $3fff, $7fff
);
var
ZeroDataBlock : boolean = false;
procedure UnpackGIFPixels( aStream : TStream; GifWidth, GifHeight : integer; DestPixels : pointer; DestWidth : integer; Interlaced : boolean );
const
PassIncrements : array[1..4] of byte = ( 8, 8, 4, 2 );
PassStartRows : array[1..4] of byte = ( 0, 4, 2, 1 );
var
XPos : integer;
YPos : integer;
ImageBufPtr : pchar;
CurPixVal : smallint;
Pass : byte;
PassInc : byte;
function ReadDataBlock( out Buffer ) : integer;
var
Count : byte;
begin
Count := 0;
if aStream.Read( Count, sizeof( Count ) ) <> sizeof( Count )
then raise EGifError.Create( 'Corrupt GIF stream', errIllegalGIFStream )
else
begin
Result := Count;
ZeroDataBlock := ( Count = 0 );
if ( Count <> 0 ) and ( aStream.Read( Buffer, Count ) <> Count )
then raise EGifError.Create( 'Corrupt GIF stream', errIllegalGIFStream );
end;
end;
var
CC : smallint;
// Pulled out of NextCode
var
CurBit : smallint;
LastBit : smallint;
LastByte : smallint;
ReturnCC : boolean;
GetDone : boolean;
Buffer : array[0..279] of byte;
function NextCode( CodSize : integer ) : integer;
var
i : integer;
j : integer;
Done : integer;
Count : integer;
RetCode : longint;
var
ExitFlag : boolean;
begin
if ReturnCC
then
begin
ReturnCC := false;
Result := CC;
end
else
begin
Result := -1;
ExitFlag := false;
Done := CurBit + CodSize;
if Done >= LastBit
then
begin
if GetDone
then
begin
ExitFlag := true;
if CurBit >= LastBit
then raise EGifError.Create( 'Corrupt GIF stream', errUnknownError );
end
else
begin
Buffer[0] := Buffer[LastByte - 2];
Buffer[1] := Buffer[LastByte - 1];
Count := ReadDataBlock( Buffer[2] );
if Count = 0
then GetDone := true;
if Count < 0
then
begin
Result := -1;
ExitFlag := true;
end
else
begin
LastByte := 2 + Count;
CurBit := ( CurBit - LastBit ) + 16;
LastBit := ( 2 + Count ) * 8;
Done := CurBit + CodSize;
end;
end;
end;
if not ExitFlag
then
begin
j := Done div 8;
i := CurBit div 8;
if i = j
then RetCode := longint( Buffer[i] )
else
if i + 1 = j
then RetCode := longint( Buffer[i] ) or ( longint( Buffer[i + 1] ) shl 8 )
else RetCode := longint( Buffer[i] ) or ( longint( Buffer[i + 1] ) shl 8 ) or ( longint( Buffer[i + 2] ) shl 16 );
RetCode := ( RetCode shr ( CurBit mod 8 ) ) and MaskTable[CodSize];
inc( CurBit, CodSize );
Result := integer( RetCode );
end;
end;
end;
// Out of NextLZW
var
Stack : array [0..1 shl MaxLZWBits * 2 - 1] of smallint;
SP : integer;
var
CodeSize : smallint;
SetCodeSize : smallint;
MaxCode : smallint;
MaxCodeSize : smallint;
EOI : smallint;
procedure InitLZW( InputCodeSize : integer );
begin
SetCodeSize := InputCodeSize;
CodeSize := SetCodeSize + 1;
CC := 1 shl SetCodeSize;
EOI := CC + 1;
MaxCodeSize := 2 * CC;
MaxCode := CC + 2;
LastBit := 0;
CurBit := 0;
LastByte := 2;
GetDone := false;
ReturnCC := true;
SP := 0
end;
var
Table : array [0..1, 0..1 shl MaxLZWBits - 1] of smallint;
FirstCode : smallint;
OldCode : smallint;
function ReadLZW : smallint;
var
i : integer;
Count : integer;
Code : smallint;
InCode : smallint;
Buffer : array [0..259] of byte;
ExitFlag : boolean;
begin
if SP > 0
then
begin
dec( SP );
Result := Stack[SP];
end
else
begin
ExitFlag := false;
Code := NextCode( CodeSize );
while ( Code >= 0 ) and not ExitFlag do
begin
if Code = CC
then
begin
// corrupt GIFs can make this happen
if CC >= 1 shl MaxLZWBits
then raise EGifError.Create( 'Corrupt GIF file', errIllegalGIFStream )
else
begin
for i := 0 to CC - 1 do
begin
Table[0][i] := 0;
Table[1][i] := i;
end;
for i := CC to 1 shl MaxLZWBits - 1 do
begin
Table[1][i] := 0;
Table[0][i] := 0;
end;
CodeSize := SetCodeSize + 1;
MaxCodeSize := 2 * CC;
MaxCode := CC + 2;
SP := 0;
repeat
OldCode := NextCode( CodeSize );
FirstCode := OldCode;
until FirstCode <> CC;
Result := FirstCode;
ExitFlag := true;
end;
end
else
if Code = EOI
then
begin
if not ZeroDataBlock
then
begin
repeat
Count := ReadDataBlock( Buffer );
until Count <= 0;
if Count <> 0
then raise EGifError.Create( 'Missing EOD in data stream', errMissingEOD );
end;
Result := -2;
ExitFlag := true;
end
else
begin
InCode := Code;
if Code >= MaxCode
then
begin
Stack[SP] := FirstCode;
inc( SP );
Code := OldCode;
end;
while Code >= CC do
begin
Stack[SP] := Table[1][Code];
inc( SP );
if Code = Table[0][Code]
then raise EGifError.Create( 'Circular table entry BIG ERROR', errLZWCircularTableEntry )
else
if SP >= sizeof( Stack )
then raise EGifError.Create( 'Circular table Stack OVERFLOW!', errLZWStackOverflow )
else Code := Table[0][Code];
end;
if not ExitFlag
then
begin
FirstCode := Table[1][Code];
Stack[SP] := FirstCode;
inc( SP );
Code := MaxCode;
if Code < 1 shl MaxLZWBits
then
begin
Table[0][Code] := OldCode;
Table[1][Code] := FirstCode;
inc( MaxCode );
if ( MaxCode >= MaxCodeSize ) and ( MaxCodeSize < 1 shl MaxLZWBits )
then
begin
MaxCodeSize := MaxCodeSize * 2;
inc( CodeSize );
end;
end;
OldCode := InCode;
if SP > 0
then
begin
dec( SP );
Result := Stack[SP];
ExitFlag := true;
end
else Code := NextCode( CodeSize );
end;
end;
end;
if not ExitFlag
then Result := Code;
end;
end;
var
InputCodeSize : byte;
begin
YPos := 0;
Pass := 1;
PassInc := PassIncrements[1];
aStream.Read( InputCodeSize, sizeof( InputCodeSize ) );
// Initialize the compression routines
InitLZW( InputCodeSize );
while YPos < GifHeight do
begin
ImageBufPtr := pchar(DestPixels) + YPos * DestWidth;
for XPos := 0 to GifWidth - 1 do
begin
CurPixVal := ReadLZW;
if CurPixVal >= 0
then ImageBufPtr[XPos] := char( CurPixVal )
else raise EGifError.Create( 'Illegal pixel value', errIllegalPixelValue );
end;
if Interlaced
then
begin
inc( YPos, PassInc );
if YPos >= GifHeight
then
begin
inc( Pass );
if Pass <= 4
then
begin
YPos := PassStartRows[Pass];
PassInc := PassIncrements[Pass];
end;
end;
end
else inc( YPos );
end;
//while ReadLZW >= 0 do
// ;
end;
end.
|
unit K590758825;
{* [Requestlink:590758825] }
// Модуль: "w:\common\components\rtl\Garant\Daily\K590758825.pas"
// Стереотип: "TestCase"
// Элемент модели: "K590758825" MUID: (55100F3F014E)
// Имя типа: "TK590758825"
{$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas}
interface
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, RTFtoEVDWriterTest
;
type
TK590758825 = class(TRTFtoEVDWriterTest)
{* [Requestlink:590758825] }
protected
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TK590758825
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
implementation
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, TestFrameWork
//#UC START# *55100F3F014Eimpl_uses*
//#UC END# *55100F3F014Eimpl_uses*
;
function TK590758825.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := '7.11';
end;//TK590758825.GetFolder
function TK590758825.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '55100F3F014E';
end;//TK590758825.GetModelElementGUID
initialization
TestFramework.RegisterTest(TK590758825.Suite);
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, StdCtrls;
type
TForm1 = class(TForm)
MainMenu1: TMainMenu;
Menu11: TMenuItem;
Item11: TMenuItem;
Item21: TMenuItem;
Item31: TMenuItem;
Menu21: TMenuItem;
Item12: TMenuItem;
Item22: TMenuItem;
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
f_BackgroundBrush: TBrush;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure SetMainMenuBackground(aMainMenu: TMainMenu; aBackgroundBrush: TBrush; aMainForm: TCustomForm = nil);
var
l_MenuInfo: TMenuInfo;
begin
l_MenuInfo.cbSize := SizeOf(TMenuInfo);
l_MenuInfo.fMask := MIM_BACKGROUND or MIM_APPLYTOSUBMENUS;
l_MenuInfo.hbrBack := aBackgroundBrush.Handle;
SetMenuInfo(aMainMenu.Handle, l_MenuInfo);
{ если окно уже открыто, то меню надо перерисовать }
if aMainForm <> nil then
DrawMenuBar(aMainForm.Handle);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
f_BackgroundBrush.Color := clRed;
SetMainMenuBackground(MainMenu1, f_BackgroundBrush, Self);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
f_BackgroundBrush := TBrush.Create;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FreeAndNil(f_BackgroundBrush);
end;
end.
|
unit deProfile;
{* Интерфейс обмена данными для формы "efUserProfile" }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Admin\deProfile.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TdeProfile" MUID: (4AA5275401A5)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If Defined(Admin)}
uses
l3IntfUses
, l3ProtoObject
, AdminInterfaces
, SecurityUnit
;
type
TdeProfile = class(Tl3ProtoObject, IdeProfile)
{* Интерфейс обмена данными для формы "efUserProfile" }
private
f_Profile: IUserProfile;
f_IsNew: Boolean;
protected
function pm_GetUserProfile: IUserProfile;
function pm_GetIsNewProfile: Boolean;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create(const aProfile: IUserProfile;
aNew: Boolean); reintroduce;
class function Make(const aProfile: IUserProfile;
aNew: Boolean = False): IdeProfile; reintroduce;
end;//TdeProfile
{$IfEnd} // Defined(Admin)
implementation
{$If Defined(Admin)}
uses
l3ImplUses
//#UC START# *4AA5275401A5impl_uses*
//#UC END# *4AA5275401A5impl_uses*
;
constructor TdeProfile.Create(const aProfile: IUserProfile;
aNew: Boolean);
//#UC START# *4AA5279D0119_4AA5275401A5_var*
//#UC END# *4AA5279D0119_4AA5275401A5_var*
begin
//#UC START# *4AA5279D0119_4AA5275401A5_impl*
inherited Create;
f_Profile := aProfile;
f_IsNew := aNew;
//#UC END# *4AA5279D0119_4AA5275401A5_impl*
end;//TdeProfile.Create
class function TdeProfile.Make(const aProfile: IUserProfile;
aNew: Boolean = False): IdeProfile;
var
l_Inst : TdeProfile;
begin
l_Inst := Create(aProfile, aNew);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//TdeProfile.Make
function TdeProfile.pm_GetUserProfile: IUserProfile;
//#UC START# *4AA526EC03C7_4AA5275401A5get_var*
//#UC END# *4AA526EC03C7_4AA5275401A5get_var*
begin
//#UC START# *4AA526EC03C7_4AA5275401A5get_impl*
Result := f_Profile;
//#UC END# *4AA526EC03C7_4AA5275401A5get_impl*
end;//TdeProfile.pm_GetUserProfile
function TdeProfile.pm_GetIsNewProfile: Boolean;
//#UC START# *4AA527110040_4AA5275401A5get_var*
//#UC END# *4AA527110040_4AA5275401A5get_var*
begin
//#UC START# *4AA527110040_4AA5275401A5get_impl*
Result := f_IsNew;
//#UC END# *4AA527110040_4AA5275401A5get_impl*
end;//TdeProfile.pm_GetIsNewProfile
procedure TdeProfile.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_4AA5275401A5_var*
//#UC END# *479731C50290_4AA5275401A5_var*
begin
//#UC START# *479731C50290_4AA5275401A5_impl*
f_Profile := nil;
f_IsNew := False;
inherited;
//#UC END# *479731C50290_4AA5275401A5_impl*
end;//TdeProfile.Cleanup
{$IfEnd} // Defined(Admin)
end.
|
unit nscTabTable;
{* Таблица перехода фокуса. }
// Библиотека : Компоненты проекта Немезис
// Автор : Морозов М.А.
// Модуль : nscTabTable - Таблица перехода фокуса.
// Начат : 27.03.2007
// Версия : $Id: nscTabTable.pas,v 1.8 2011/05/19 13:50:15 lulin Exp $
(*-------------------------------------------------------------------------------
$Log: nscTabTable.pas,v $
Revision 1.8 2011/05/19 13:50:15 lulin
{RequestLink:266409354}.
Revision 1.7 2011/05/19 12:19:01 lulin
{RequestLink:266409354}.
Revision 1.6 2008/02/05 09:57:33 lulin
- выделяем базовые объекты в отдельные файлы и переносим их на модель.
Revision 1.5 2008/02/01 15:14:27 lulin
- избавляемся от излишней универсальности списков.
Revision 1.4 2007/11/02 12:23:22 mmorozov
- new: при перемещении между столбцами таблицы перехода фокуса учитываем не порядковый номер ячейки в столбце из которого переходим, а координаты ячейки (в рамках работы над CQ: OIT5-27189) + сопутствующий рефакторинг;
Revision 1.3 2007/03/28 13:12:09 mmorozov
- new: очистка таблицы перехода фокуса;
Revision 1.2 2007/03/28 11:39:38 mmorozov
- подключаем таблицу перехода фокуса к панели задач;
Revision 1.1 2007/03/28 11:02:54 mmorozov
- "таблица перехода фокуса" перенесена в библиотеку визуальных компонентов проекта Немезис;
-------------------------------------------------------------------------------*)
interface
uses
l3Base,
l3ObjectRefList,
l3ProtoObject,
l3ProtoObjectRefList,
nscInterfaces
;
type
TnscTabTableColumn = class;
TnscTabTable = class;
TnscTabTableList = Tl3ProtoObjectRefList;
Tnsc_ttBase = class(Tl3ProtoObject)
{* Базовый класс таблицы перехода фокуса. }
end;//Tnsc_ttBase
TnscProcessKey = class(Tnsc_ttBase)
{* - для обработки нажатия на клавиши в TeeTreeView, TvtLister. }
private
// private fields
f_Cell : InscTabTableCell;
f_Column : TnscTabTableColumn;
f_Index : Integer;
private
// private methods
function IsLocalJump(const aKey : TnscTabTableKey) : Boolean;
{* - если True, значит фокус находился не на первом/последнем элементе
дерева, списка, не передаем выше. }
procedure OnProcessKey(const aKey : TnscTabTableKey);
{* - событие нажатия на клавишу. }
private
// property methods
function pm_GetCanFocus : Boolean;
{-}
protected
// protected methods
procedure Cleanup;
override;
{-}
protected
// protected properties
property Index : Integer
read f_Index
write f_Index;
{* - порядковый номер в столбце, устанавливается при добавлении элемента
в список. }
public
// public methods
constructor Create(const aItem : InscTabTableCell;
const aColumn : TnscTabTableColumn);
reintroduce;
virtual;
{-}
procedure SetFocus(const aFromNext: Boolean = True);
{-}
public
// public properties
property CanFocus : Boolean
read pm_GetCanFocus;
{* - может ли компонент получать фокус. }
property Cell: InscTabTableCell
read f_Cell;
{-}
end;//TnscProcessKey
TnscTabTableColumn = class(TnscTabTableList, InscTabTableColumn)
{* - колеция элементов одного столбца меню. }
private
f_Table : TnscTabTable;
f_Index : Integer;
private
// private methods
procedure ProcessKey(const aKey : TnscTabTableKey;
const aItem : TnscProcessKey);
{* - на элементе столбца aItem нажали клавишу, транслируем событие к
TmmColums. }
function CheckSetFocus(const aItem : Integer;
const aUp : Boolean = True;
const aLeftRight : Boolean = False;
const aTop : Integer = -1) : Boolean;
{* - устанавливает фокус элементу aItem, если фокус не может быть
установлен, например элемент не виден, то ищем первый который может
в зависимости от aUp. }
protected
// protected property
property Index : Integer
read f_Index
write f_Index;
{-}
public
// public methods
constructor Create(const aTable: TnscTabTable);
reintroduce;
virtual;
{-}
procedure AddItem(const aItem: InscTabTableCell);
{* - добавляет элемент в список. }
procedure SetFocus(const aFromNext : Boolean = True);
{-}
end;//TnscTabTableColumn
TnscTabTable = class(TnscTabTableList, InscTabTable)
{* - столбцы в основном меню. }
private
// InscTabTable
function pm_GetColumnCount: Integer;
{-}
function pm_GetColumn(const aIndex: Integer): InscTabTableColumn;
{-}
function AddColumn: InscTabTableColumn;
{* - добавляет новый столбец. }
procedure InscTabTable_Clear;
procedure InscTabTable.Clear = InscTabTable_Clear;
{-}
private
// private methods
procedure ProcessKey(const aKey : TnscTabTableKey;
const aColumn : Integer;
const aItem : TnscProcessKey);
{* - была нажата клавиша влево, вправо, нужно переместить фокус на
соответствующий элемент соседнего стобца. }
private
// property methods
function pm_GetLastColumn : TnscTabTableColumn;
{-}
public
// public methods
class function Make: InscTabTable;
reintroduce;
{-}
public
// public properties
property LastColumn : TnscTabTableColumn
read pm_GetLastColumn;
{* - последний столбец в списке. }
end;//TnscTabTable
implementation
uses
Math,
SysUtils
;
{ TnscProcessKey }
procedure TnscProcessKey.OnProcessKey(const aKey : TnscTabTableKey);
{* - событие нажатия на клавишу. }
begin
if not IsLocalJump(aKey) then
f_Column.ProcessKey(aKey, Self);
end;//OnProcessKey
function TnscProcessKey.IsLocalJump(const aKey : TnscTabTableKey) : Boolean;
{* - если True, значит фокус находился не на первом/последнем элементе
дерева, списка, не передаем выше. }
begin
Result := False;
case aKey of
// На предыдущий элемент
ns_kUp:
if f_Cell.Current > 0 then
begin
Result := True;
f_Cell.Current := Pred(f_Cell.Current);
end;//ns_kUp
// На следующий элемент
ns_kDown:
if f_Cell.Current < Pred(f_Cell.Count) then
begin
Result := True;
f_Cell.Current := Succ(f_Cell.Current);
end;//ns_kDown
end//case aKey of
end;//IsLocalJump
function TnscProcessKey.pm_GetCanFocus : Boolean;
{-}
begin
Result := f_Cell.Control.CanFocus;
end;//pm_GetCanFocus
procedure TnscProcessKey.Cleanup;
// override;
begin
f_Cell := nil;
inherited;
end;//Cleanup
constructor TnscProcessKey.Create(const aItem : InscTabTableCell;
const aColumn : TnscTabTableColumn);
// reintroduce;
// virtual;
begin
inherited Create;
f_Column := aColumn;
f_Cell := aItem;
f_Cell.OnProcessKey := OnProcessKey;
end;//Create
procedure TnscProcessKey.SetFocus(const aFromNext: Boolean = True);
{-}
begin
f_Cell.SetFocus(aFromNext);
end;//SetFocus
{ TnscTabTableColumn }
constructor TnscTabTableColumn.Create(const aTable: TnscTabTable);
// reintroduce;
// virtual;
{-}
begin
inherited Create;
f_Table := aTable;
end;//Create
procedure TnscTabTableColumn.AddItem(const aItem: InscTabTableCell);
{* - добавляет элемент в список. }
var
l_Temp: TnscProcessKey;
begin
l_Temp := TnscProcessKey.Create(aItem, Self);
try
l_Temp.Index := Add(l_Temp);
finally
FreeAndNil(l_Temp);
end;{try..finally}
end;//AddItem
procedure TnscTabTableColumn.ProcessKey(const aKey : TnscTabTableKey;
const aItem : TnscProcessKey);
{* - на элементе столбца aItem нажали клавишу. }
var
l_Process : Boolean;
begin
l_Process := True;
case aKey of
ns_kUp:
if aItem.Index > 0 then
l_Process := not CheckSetFocus(Pred(aItem.Index), True);
ns_kDown:
if aItem.Index < Pred(Count) then
l_Process := not CheckSetFocus(Succ(aItem.Index), False);
end;//case aKey of
if l_Process then
f_Table.ProcessKey(aKey, f_Index, aItem);
end;//ProcessKey
function TnscTabTableColumn.CheckSetFocus(const aItem : Integer;
const aUp : Boolean = True;
const aLeftRight : Boolean = False;
const aTop : Integer = -1) : Boolean;
{* - устанавливает фокус элементу aItem, если фокус не может быть установлен,
например элемент не виден, то ищем первый который может в зависимости от
aUp. }
var
l_Item : Integer;
l_Top : Integer;
function lp_Item: TnscProcessKey;
begin
Result := TnscProcessKey(Items[l_Item]);
end;//lp_Item
function lp_NeedSetFocus: Boolean;
begin
with lp_Item, Cell.Bounds do
Result := CanFocus and ((l_Top = -1) or (Top >= l_Top) or (Bottom >= l_Top));
end;//lp_NeedSetFocus
function lp_Move(const aLow : Integer;
const aHigh : Integer;
const aUp : Boolean = True) : Boolean;
function lp_Finish: Boolean;
begin
Result := False;
if aUp then
begin
if (l_Item < aLow) then
Result := True;
end//if aUp then
else
if (l_Item > aHigh) then
Result := True;
end;//lp_IsExit
procedure lp_NextCell;
begin
if aUp then
Dec(l_Item)
else
Inc(l_Item);
end;//lp_NextCell
procedure lp_InitCell;
begin
if aUp then
l_Item := aHigh
else
l_Item := aLow;
end;//lp_InitCell
begin
Result := False;
lp_InitCell;
while True do
begin
if lp_NeedSetFocus then
begin
lp_Item.SetFocus(aUp);
Result := True;
Break;
end;//if TnscProcessKey(Items[l_Item]).CanFocus then
lp_NextCell;
if lp_Finish then
Break;
end;//while (l_Item >= aLow) do
end;//lp_Up
begin
l_Top := aTop;
if aUp then
begin
// Продемся до верху
Result := lp_Move(0, aItem);
if not Result and aLeftRight then
begin
l_Top := -1;
// Нет ни одного видимого идем сверху до aItem + 1
Result := lp_Move(0, Pred(Count), False);
end;//if not Result and aLeftRight then
end//if aUp then
else
begin
// Пройдемся до низу
Result := lp_Move(aItem, Pred(Count), False);
if not Result and aLeftRight then
begin
l_Top := -1;
// Пройдемся с первого до aItem - 1
Result := lp_Move(0, Pred(Count));
end;//if not Result and aLeftRight then
end;//if aUp then
end;//CheckSetFocus
procedure TnscTabTableColumn.SetFocus(const aFromNext : Boolean);
begin
if Count > 0 then
CheckSetFocus(IfThen(aFromNext, Pred(Count), 0), aFromNext);
end;
{ TnscTabTable }
class function TnscTabTable.Make: InscTabTable;
{-}
var
l_Class: TnscTabTable;
begin
l_Class := inherited Make;
try
Result := l_Class;
finally
FreeAndNil(l_Class);
end;{try..finally}
end;//Make
function TnscTabTable.pm_GetColumn(const aIndex: Integer): InscTabTableColumn;
{-}
begin
Supports(Items[aIndex], InscTabTableColumn, Result);
end;//pm_GetColumn
function TnscTabTable.pm_GetColumnCount: Integer;
{-}
begin
Result := Count;
end;//pm_GetColumnCount
procedure TnscTabTable.InscTabTable_Clear;
begin
Clear;
end;//InscTabTable_Clear
function TnscTabTable.AddColumn: InscTabTableColumn;
var
l_Class: TnscTabTableColumn;
begin
l_Class := TnscTabTableColumn.Create(Self);
try
l_Class.Index := Add(l_Class);
Result := l_Class;
finally
FreeAndNil(l_Class);
end;{try..finally}
end;//AddItem
procedure TnscTabTable.ProcessKey(const aKey : TnscTabTableKey;
const aColumn : Integer;
const aItem : TnscProcessKey);
{* - была нажата клавиша влево, вправо, нужно переместить фокус на
соответствующий элемент соседнего стобца. }
function lp_ItemIndex(const aColumn : TnscTabTableColumn) : Integer;
begin
if aItem.Index > Pred(aColumn.Count) then
Result := Pred(aColumn.Count)
else
Result := aItem.Index;
end;//lp_ItemIndex
procedure lp_SetColumn(const aColumn : Integer;
const aTop : Integer = -1);
function lp_Index: Integer;
begin
if aTop = -1 then
Result := lp_ItemIndex(TnscTabTableColumn(Items[aColumn]))
else
Result := 0;
end;//lp_Index
begin
TnscTabTableColumn(Items[aColumn]).CheckSetFocus(lp_Index, False, True, aTop);
end;//lp_SetColumn
var
l_Index : Integer;
begin
case aKey of
ns_kUp:
begin
if aColumn > 0 then
l_Index := Pred(aColumn)
else
l_Index := Pred(Count);
TnscTabTableColumn(Items[l_Index]).SetFocus;
end;
ns_kDown:
begin
if aColumn < Pred(Count) then
l_Index := Succ(aColumn)
else
l_Index := 0;
TnscTabTableColumn(Items[l_Index]).SetFocus(False);
end;
ns_kLeft:
begin
if aColumn > 0 then
l_Index := Pred(aColumn)
else
l_Index := Pred(Count);
lp_SetColumn(l_Index, aItem.Cell.Bounds.Top);
end;//ns_kLeft
ns_kRight:
begin
if aColumn < Pred(Count) then
l_Index := Succ(aColumn)
else
l_Index := 0;
lp_SetColumn(l_Index, aItem.Cell.Bounds.Top);
end;//ns_kRight
end;//case aKey of
end;//ProcessKey
function TnscTabTable.pm_GetLastColumn: TnscTabTableColumn;
begin
Result := nil;
if Count > 0 then
Result := TnscTabTableColumn(Items[Pred(Count)]);
end;//pm_GetLastColumn
end.
|
{
This file is part of the Free Pascal run time library.
A file in Amiga system run time library.
Copyright (c) 1998-2003 by Nils Sjoholm
member of the Amiga RTL development team.
See the file COPYING.FPC, included in this distribution,
for details about the copyright.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
**********************************************************************}
{
History:
Added the define use_amiga_smartlink.
13 Jan 2003.
nils.sjoholm@mailbox.swipnet.se Nils Sjoholm
}
{$I useamigasmartlink.inc}
{$ifdef use_amiga_smartlink}
{$smartlink on}
{$endif use_amiga_smartlink}
unit MsgBox;
interface
FUNCTION MessageBox(tit,txt,gad:string) : LONGint;
function MessageBox(tit,txt,gad:pchar):longint;
implementation
uses pastoc;
type
pEasyStruct = ^tEasyStruct;
tEasyStruct = record
es_StructSize : longint; { should be sizeof (struct EasyStruct )}
es_Flags : longint; { should be 0 for now }
es_Title : pchar; { title of requester window }
es_TextFormat : pchar; { 'printf' style formatting string }
es_GadgetFormat : pchar; { 'printf' style formatting string }
END;
FUNCTION EasyRequestArgs(window : pointer; easyStruct : pEasyStruct; idcmpPtr : longint; args : POINTER) : LONGINT;
BEGIN
ASM
MOVE.L A6,-(A7)
MOVEA.L window,A0
MOVEA.L easyStruct,A1
MOVEA.L idcmpPtr,A2
MOVEA.L args,A3
MOVEA.L _IntuitionBase,A6
JSR -588(A6)
MOVEA.L (A7)+,A6
MOVE.L D0,@RESULT
END;
END;
FUNCTION MessageBox(tit,txt,gad:string) : LONGint;
begin
MessageBox := MessageBox(pas2c(tit),pas2c(txt),pas2c(gad));
end;
FUNCTION MessageBox(tit,txt,gad:pchar) : LONGint;
VAR
MyStruct : tEasyStruct;
BEGIN
MyStruct.es_StructSize:=SizeOf(tEasyStruct);
MyStruct.es_Flags:=0;
MyStruct.es_Title:=(tit);
MyStruct.es_TextFormat:=(txt);
MyStruct.es_GadgetFormat:=(gad);
MessageBox := EasyRequestArgs(nil,@MyStruct,0,NIL);
END;
end.
|
unit uCommands;
interface
uses Data.DB,
xn.grid.link.sample,
xn.grid.common;
type
TxnCommands = class
const
LINK_NIL = 'Link not assigned!';
DATASET_NIL = 'Dataset not assigned!';
private
fLink: IxnGridLinkCustom<string>;
fDataSet: TDataSet;
fId: Integer;
procedure Clear;
procedure Asserts;
procedure DatasetValues(aValue: string);
public
constructor Create;
function NewId(): string;
procedure Init(aLink: IxnGridLinkCustom<string>; aDataSet: TDataSet);
procedure First;
procedure Prior;
procedure Next;
procedure Last;
procedure Append(aValue: string);
procedure Insert(aValue: string);
procedure Edit(aValue: string);
procedure Delete;
function RandNumber: Integer;
function RandCommand: String;
procedure Execute(aCommand: String);
end;
var
xnCommands: TxnCommands;
implementation
uses System.SysUtils, System.Math;
function TxnCommands.NewId(): string;
begin
Inc(fId);
Result := IntToStr(fId);
end;
procedure TxnCommands.Asserts;
begin
Assert(fDataSet <> nil, DATASET_NIL);
Assert(fLink <> nil, LINK_NIL);
end;
procedure TxnCommands.Init(aLink: IxnGridLinkCustom<string>; aDataSet: TDataSet);
begin
fLink := aLink;
fDataSet := aDataSet;
end;
procedure TxnCommands.DatasetValues(aValue: string);
begin
Asserts;
fDataSet.Fields[0].AsString := aValue;
fDataSet.Fields[1].AsString := aValue;
fDataSet.Fields[2].AsString := aValue;
end;
procedure TxnCommands.Append(aValue: string);
begin
if fLink.RecNoGet > 10 then
Exit;
Asserts;
fLink.Append(aValue);
fDataSet.Append;
DatasetValues(aValue);
fDataSet.Post;
end;
procedure TxnCommands.Insert(aValue: string);
begin
if fLink.RecNoGet > 10 then
Exit;
Asserts;
if fLink.RecNoGet < 0 then
fLink.Insert(0, aValue)
else
fLink.Insert(fLink.RecNoGet, aValue);
fDataSet.Insert;
DatasetValues(aValue);
fDataSet.Post;
end;
procedure TxnCommands.Edit(aValue: string);
begin
if fLink.RowCountGet = 0 then
Exit;
Asserts;
fLink.Edit(fLink.RecNoGet, aValue);
fDataSet.Edit;
DatasetValues(aValue);
fDataSet.Post;
end;
procedure TxnCommands.Delete;
begin
if fLink.RowCountGet = 0 then
Exit;
Asserts;
fLink.Delete(fLink.RecNoGet);
fDataSet.Delete;
end;
procedure TxnCommands.Clear;
begin
Asserts;
fLink.Clear;
while not fDataSet.IsEmpty do
fDataSet.Delete;
end;
procedure TxnCommands.First;
begin
Asserts;
fLink.First;
fDataSet.First;
end;
procedure TxnCommands.Last;
begin
Asserts;
fLink.Last;
fDataSet.Last;
end;
procedure TxnCommands.Prior;
begin
Asserts;
fLink.Prior;
fDataSet.Prior;
end;
procedure TxnCommands.Next;
begin
Asserts;
fLink.Next;
fDataSet.Next;
end;
function TxnCommands.RandNumber: Integer;
begin
Result := RandomRange(1, 10);
end;
function TxnCommands.RandCommand: String;
begin
case RandNumber() of
1:
Exit('append');
2:
Exit('insert');
3:
Exit('delete');
4:
Exit('edit');
5:
Exit('first');
6:
Exit('last');
7:
Exit('prior');
8:
Exit('next');
9:
Exit('clear');
else
raise Exception.Create('Invalid number');
end;
end;
procedure TxnCommands.Execute(aCommand: String);
begin
if SameText(aCommand, 'clear') then
Clear
else if SameText(aCommand, 'delete') then
Delete
else if SameText(aCommand, 'edit') then
Edit(NewId())
else if SameText(aCommand, 'append') then
Append(NewId())
else if SameText(aCommand, 'insert') then
Insert(NewId())
else if SameText(aCommand, 'first') then
First
else if SameText(aCommand, 'last') then
Last
else if SameText(aCommand, 'prior') then
Prior
else if SameText(aCommand, 'next') then
Next
else
raise Exception.CreateFmt('Invalid command "%s"', [aCommand]);
end;
constructor TxnCommands.Create;
begin
fLink := nil;
fDataSet := nil;
fId := 0;
end;
initialization
xnCommands := TxnCommands.Create;
finalization
xnCommands.Free;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.