text stringlengths 14 6.51M |
|---|
unit htPaint;
interface
uses
Windows, SysUtils, Types, Classes, Controls, Graphics;
procedure htPaintOutline(inCanvas: TCanvas; const inRect: TRect;
inColor: TColor = clSilver);
procedure htPaintGuides(inCanvas: TCanvas; inContainer: TCustomControl);
procedure htPaintHash(inCanvas: TCanvas; const inRect: TRect; inColor: TColor);
procedure htPaintRules(inCanvas: TCanvas; const inRect: TRect;
inDivs: Integer = 32; inSubDivs: Boolean = true);
implementation
uses
LrControlIterator, LrVclUtils, htUtils;
procedure htPaintOutline(inCanvas: TCanvas; const inRect: TRect;
inColor: TColor);
begin
with inCanvas do
begin
Pen.Width := 1;
Pen.Color := inColor;
Pen.Style := psDot;
Brush.Style := bsClear;
Rectangle(inRect);
end;
end;
procedure htPaintHash(inCanvas: TCanvas; const inRect: TRect;
inColor: TColor);
begin
with inCanvas do
begin
Brush.Style := bsBDiagonal;
Brush.Color := ColorToRgb(clSilver);
Pen.Style := psClear;
if htVisibleColor(inColor) then
SetBkColor(Handle, ColorToRgb(inColor))
else
SetBkMode(Handle, TRANSPARENT);
Rectangle(inRect);
SetBkMode(Handle, OPAQUE);
end;
end;
procedure htPaintGuides(inCanvas: TCanvas; inContainer: TCustomControl);
function Middle(inCtrl: TControl): Integer;
begin
Result := inCtrl.Top + inCtrl.Height div 2;
end;
function Center(inCtrl: TControl): Integer;
begin
Result := inCtrl.Left + inCtrl.Width div 2;
end;
begin
with inCanvas do
begin
Pen.Width := 0;
Pen.Style := psDot;
Pen.Color := clSilver;
with TLrCtrlIterator.Create(inContainer) do
try
while Next([alNone]) do
begin
MoveTo(0, Middle(Ctrl));
LineTo(inContainer.ClientWidth, Middle(Ctrl));
MoveTo(Center(Ctrl), 0);
LineTo(Center(Ctrl), inContainer.ClientHeight);
end;
finally
Free;
end;
end;
end;
procedure htPaintRules(inCanvas: TCanvas; const inRect: TRect;
inDivs: Integer; inSubDivs: Boolean);
var
d, d2, w, h, i: Integer;
begin
d := inDivs;
d2 := inDivs div 2;
w := (inRect.Right - inRect.Left + d - 1) div d;
h := (inRect.Bottom - inRect.Top + d - 1) div d;
with inCanvas do
begin
Pen.Style := psDot;
for i := 0 to w do
begin
Pen.Color := $DDDDDD;
MoveTo(i * d, inRect.Top);
LineTo(i * d, inRect.Bottom);
if inSubDivs then
begin
Pen.Color := $F0F0F0;
MoveTo(i * d + d2, inRect.Top);
LineTo(i * d + d2, inRect.Bottom);
end;
end;
for i := 0 to h do
begin
Pen.Color := $DDDDDD;
MoveTo(inRect.Left, i * d);
LineTo(inRect.Right, i * d);
if inSubDivs then
begin
Pen.Color := $F0F0F0;
MoveTo(inRect.Left, i * d + d2);
LineTo(inRect.Right, i * d + d2);
end;
end;
end;
end;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2022 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of an Embarcadero developer tools product.
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit WP.BasicDemoPlugIn.Creator;
interface
uses
System.SysUtils, Vcl.Forms, Vcl.Controls, Vcl.Graphics,
ToolsAPI.WelcomePage, WP.BasicDemoPlugin.Constants;
type
TWPDemoPlugInCreator = class(TInterfacedObject, INTAWelcomePagePlugin,
INTAWelcomePageContentPluginCreator)
private
FWPPluginView: TFrame;
FIconIndex: Integer;
{ INTAWelcomePageContentPluginCreator }
function GetView: TFrame;
function GetIconIndex: Integer;
procedure SetIconIndex(const Value: Integer);
public
constructor Create;
destructor Destroy; override;
class procedure PlugInStartup;
class procedure PlugInFinish;
{ INTAWelcomePagePlugin }
function GetPluginID: string;
function GetPluginName: string;
function GetPluginVisible: boolean;
{ INTAWelcomePageContentPluginCreator }
function CreateView: TFrame;
procedure ViewWasDestroyed;
procedure DestroyView;
function GetIcon: TGraphicArray;
end;
procedure Register;
var
WPDemoPlugInCreator : TWPDemoPlugInCreator = nil;
implementation
uses
WP.BasicDemoPlugIn.View;
procedure Register;
begin
TWPDemoPlugInCreator.PlugInStartup;
end;
{ TWPDemoPlugInCreator }
procedure TWPDemoPlugInCreator.ViewWasDestroyed;
begin
FWPPluginView := nil;
end;
function TWPDemoPlugInCreator.GetPluginID: string;
begin
Result := sPluginID;
end;
function TWPDemoPlugInCreator.GetPluginName: string;
begin
Result := sPluginName;
end;
function TWPDemoPlugInCreator.GetPluginVisible: boolean;
begin
Result := True;
end;
constructor TWPDemoPlugInCreator.Create;
begin
inherited;
FIconIndex := -1;
end;
destructor TWPDemoPlugInCreator.Destroy;
begin
DestroyView;
inherited;
end;
function TWPDemoPlugInCreator.CreateView: TFrame;
begin
if not Assigned(FWPPluginView) then
FWPPluginView := TMainFrame.Create(nil);
Result := FWPPluginView;
end;
procedure TWPDemoPlugInCreator.DestroyView;
begin
if Assigned(FWPPluginView) then
begin
FreeAndNil(FWPPluginView);
ViewWasDestroyed;
end;
end;
function TWPDemoPlugInCreator.GetIcon: TGraphicArray;
begin
Result := [];
end;
function TWPDemoPlugInCreator.GetIconIndex: Integer;
begin
Result := FIconIndex;
end;
procedure TWPDemoPlugInCreator.SetIconIndex(const Value: Integer);
begin
FIconIndex := Value;
end;
function TWPDemoPlugInCreator.GetView: TFrame;
begin
Result := FWPPluginView;
end;
class procedure TWPDemoPlugInCreator.PlugInStartup;
begin
if Assigned(WelcomePagePluginService) then
begin
WPDemoPlugInCreator := TWPDemoPlugInCreator.Create;
WelcomePagePluginService.RegisterPluginCreator(WPDemoPlugInCreator);
end;
end;
class procedure TWPDemoPlugInCreator.PlugInFinish;
begin
if Assigned(WelcomePagePluginService) then
WelcomePagePluginService.UnRegisterPlugin(sPluginID);
if Assigned(WPDemoPlugInCreator) then
WPDemoPlugInCreator := nil;
end;
initialization
finalization
TWPDemoPlugInCreator.PlugInFinish;
end.
|
unit pac;
interface
uses SysUtils, StrUtils, SyncObjs, Windows, Dialogs;
type
tpacparser_error_printer = function(const fmt: pansichar; argp: va_list): integer; cdecl;
ppacparser_error_printer = ^tpacparser_error_printer;
tpacparser_set_error_printer = procedure(func: ppacparser_error_printer); cdecl;
tpacparser_init = function: integer; cdecl;{ stdcall;
external 'pac.dll' name 'pacparser_init'; }
tpacparser_cleanup = procedure; cdecl;{ stdcall; external 'pac.dll'; }
tpacparser_version = function: pansichar; cdecl;
{ cdecl; stdcall; external 'pac.dll'; }
tpacparser_parse_pac_string = function(const pacstring: pansichar
// PAC string to parse
): integer; cdecl;{ stdcall; external 'pac.dll'; }
tpacparser_find_proxy = function(const url, // URL to find proxy for
host: pansichar // Host part of the URL
): pansichar; cdecl;{ stdcall; external 'pac.dll'; }
tPACParser = class
private
fINIT: Boolean;
fReIn: Boolean;
fCS: tCriticalSection;
fDLLHandle: Cardinal;
_init: tpacparser_init;
_cleanup: tpacparser_cleanup;
_version: tpacparser_version;
_parse_pac_string: tpacparser_parse_pac_string;
_find_proxy: tpacparser_find_proxy;
_set_error_printer: tpacparser_set_error_printer;
protected
procedure LoadLib;
function GetProc(s: pansichar): Pointer;
procedure doInit;
function pacparser_init: integer;
public
procedure LoadScript(s: ANSIString);
function GetProxy(const url, host: ANSIString): UnicodeString;
constructor Create;
destructor Destroy; override;
property Initiated: Boolean read fINIT;
property Reload: Boolean read fReIn write fReIn;
end;
implementation
{ **** tPACPARSER ******* }
function error_printer(const fmt: pansichar; argp: va_list): integer; cdecl;
var
r: array[0..1024] of ANSIChar;
//f: PWideChar;
begin
// ShowMessage('derp');
//f := PWideChar(WideString(ANSIString(fmt)));
wvsprintfA(r,fmt,argp);
raise Exception.Create(String(r));
end;
procedure tPACParser.LoadLib;
begin
fDLLHandle := LoadLibrary('pac.dll');
if fDLLHandle = 0 then
raise Exception.Create('Cannot access to pac.dll');
@_init := GetProc('pacparser_init');
@_cleanup := GetProc('pacparser_cleanup');
@_version := GetProc('pacparser_version');
@_parse_pac_string := GetProc('pacparser_parse_pac_string');
@_find_proxy := GetProc('pacparser_find_proxy');
@_set_error_printer := GetProc('pacparser_set_error_printer');
_set_error_printer(@error_printer);
end;
function tPACParser.GetProc(s: pansichar): Pointer;
begin
Result := GetProcAddress(fDLLHandle, s);
if Result = nil then
raise Exception.Create('Cannot load method "' + s + '"');
end;
procedure tPACParser.doInit;
var
w: integer;
begin
if not fINIT then
begin
LoadLib;
try
w := pacparser_init;
if w = 0 then
raise Exception.Create('PAC parser initialisation error');
fINIT := True;
except
FreeLibrary(fDLLHandle);
raise;
end;
end;
end;
function tPACParser.pacparser_init: integer;
var
w: word;
begin
w := Get8087CW;
Set8087CW($133F);
try
Result := _init;
finally
Set8087CW(w);
end;
end;
procedure tPACParser.LoadScript(s: ANSIString);
var
w: integer;
//d: va_list;
begin
doInit;
w := _parse_pac_string(PANSICHAR(s));
if w = 0 then
raise Exception.Create('PAC parser loading script error');
fReIn := false;
end;
function tPACParser.GetProxy(const url: ANSIString; const host: ANSIString)
: UnicodeString;
var
i: integer;
begin
fCS.Enter;
try
Result := UnicodeString(_find_proxy(pansichar(url), pansichar(host)));
i := pos(';', Result);
if i > 0 then
Result := Copy(Result, 1, i - 1);
i := pos('proxy ', lowercase(Result));
if i > 0 then
delete(Result, 1, i + 5);
finally
fCS.Leave;
end;
end;
constructor tPACParser.Create;
begin
inherited;
fCS := tCriticalSection.Create;
end;
destructor tPACParser.Destroy;
begin
fCS.Free;
if fINIT then
begin
_cleanup;
FreeLibrary(fDLLHandle);
end;
inherited;
end;
end.
|
{
@abstract Implements @link(TNtLanguageDialog) dialog that lets the user to choose a new language.
FMX only.
}
unit FMX.NtLanguageDlg;
{$I NtVer.inc}
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Layouts, FMX.ListBox,
FMX.StdCtrls, FMX.NtLocalization, FMX.Controls.Presentation, NtBase;
type
// Specifies options for @link(TNtLanguageDialog).
TNtLanguageDialogOption =
(
ldShowErrorIfNoResource //< Show an error if no language resource exists
);
TNtLanguageDialogOptions = set of TNtLanguageDialogOption;
{ @abstract Dialog that shows the languages of the available resource files.
Dialog shows available languages and lets you choose a new language.
@seealso(FMX.NtLanguageDlg) }
TNtLanguageDialog = class(TForm)
LanguageList: TListBox;
OkButton: TButton;
CancelButton: TButton;
Resources1: TStyleBook;
procedure FormCreate(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure LanguageListDblClick(Sender: TObject);
private
FOriginalLanguage: String;
FLanguageName: TNtLanguageName;
FOptions: TNtLanguageDialogOptions;
function GetLanguage(i: Integer): String;
function GetLanguageCount: Integer;
function GetSelectedLanguage: String;
procedure SetSelectedLanguage(const value: String);
public
class function Select(
var language: String;
originalLanguage: String = '';
languageName: TNtLanguageName = lnNative;
dialogOptions: TNtLanguageDialogOptions = [];
languageOptions: TNtResourceOptions = [];
position: TFormPosition = TFormPosition.MainFormCenter): Boolean; overload;
class function Select(
originalLanguage: String = '';
languageName: TNtLanguageName = lnNative;
dialogOptions: TNtLanguageDialogOptions = [];
languageOptions: TNtResourceOptions = [];
position: TFormPosition = TFormPosition.MainFormCenter): Boolean; overload;
class procedure Select(
done: TProc<String>;
originalLanguage: String = '';
languageName: TNtLanguageName = lnNative;
dialogOptions: TNtLanguageDialogOptions = [];
languageOptions: TNtResourceOptions = [];
position: TFormPosition = TFormPosition.MainFormCenter); overload;
class procedure Select(
done: TProc;
originalLanguage: String = '';
languageName: TNtLanguageName = lnNative;
dialogOptions: TNtLanguageDialogOptions = [];
languageOptions: TNtResourceOptions = [];
position: TFormPosition = TFormPosition.MainFormCenter); overload;
class function Choose(
var language: String;
originalLanguage: String = '';
languageName: TNtLanguageName = lnNative;
options: TNtLanguageDialogOptions = [];
position: TFormPosition = TFormPosition.MainFormCenter): Boolean; overload;
class procedure Choose(
done: TProc<String>;
originalLanguage: String = '';
languageName: TNtLanguageName = lnNative;
options: TNtLanguageDialogOptions = [];
position: TFormPosition = TFormPosition.MainFormCenter); overload;
property LanguageCount: Integer read GetLanguageCount;
property Languages[i: Integer]: String read GetLanguage;
property OriginalLanguage: String read FOriginalLanguage write FOriginalLanguage;
property SelectedLanguage: String read GetSelectedLanguage write SetSelectedLanguage;
property LanguageName: TNtLanguageName read FLanguageName write FLanguageName;
end;
implementation
{$R *.fmx}
uses
FMX.Graphics,
NtResource,
FMX.NtTranslator;
type
TLanguageCode = class(TObject)
private
FValue: String;
public
constructor Create(const value: String);
property Value: String read FValue;
end;
constructor TLanguageCode.Create(const value: String);
begin
inherited Create;
FValue := value;
end;
// TNtLanguageDialog
function TNtLanguageDialog.GetLanguageCount: Integer;
begin
Result := LanguageList.Items.Count;
end;
function TNtLanguageDialog.GetLanguage(i: Integer): String;
begin
Result := TLanguageCode(LanguageList.Items.Objects[i]).Value;
end;
function TNtLanguageDialog.GetSelectedLanguage: String;
begin
if LanguageList.ItemIndex >= 0 then
Result := Languages[LanguageList.ItemIndex]
else
Result := '';
end;
procedure TNtLanguageDialog.SetSelectedLanguage(const value: String);
var
i: Integer;
begin
for i := 0 to LanguageCount - 1 do
if Languages[i] = value then
begin
LanguageList.ItemIndex := i;
Break;
end;
end;
class function TNtLanguageDialog.Select(
var language: String;
originalLanguage: String;
languageName: TNtLanguageName;
dialogOptions: TNtLanguageDialogOptions;
languageOptions: TNtResourceOptions;
position: TFormPosition): Boolean;
begin
Result := Choose(language, originalLanguage, languageName, dialogOptions, position);
if Result then
begin
if language = originalLanguage then
language := '';
Result := TNtTranslator.SetNew(language, languageOptions, originalLanguage);
end;
end;
class procedure TNtLanguageDialog.Select(
done: TProc<String>;
originalLanguage: String;
languageName: TNtLanguageName;
dialogOptions: TNtLanguageDialogOptions;
languageOptions: TNtResourceOptions;
position: TFormPosition);
begin
Choose(
procedure(language: String)
begin
if language = originalLanguage then
language := '';
TNtTranslator.SetNew(language, languageOptions, originalLanguage);
done(language);
end,
originalLanguage,
languageName,
dialogOptions,
position);
end;
class procedure TNtLanguageDialog.Select(
done: TProc;
originalLanguage: String;
languageName: TNtLanguageName;
dialogOptions: TNtLanguageDialogOptions;
languageOptions: TNtResourceOptions;
position: TFormPosition);
begin
Choose(
procedure(language: String)
begin
if language = originalLanguage then
language := '';
TNtTranslator.SetNew(language, languageOptions, originalLanguage);
done;
end,
originalLanguage,
languageName,
dialogOptions,
position);
end;
class function TNtLanguageDialog.Select(
originalLanguage: String;
languageName: TNtLanguageName;
dialogOptions: TNtLanguageDialogOptions;
languageOptions: TNtResourceOptions;
position: TFormPosition): Boolean;
var
language: String;
begin
Result := Select(
language,
originalLanguage,
languageName,
dialogOptions,
languageOptions,
position);
end;
class function TNtLanguageDialog.Choose(
var language: String;
originalLanguage: String;
languageName: TNtLanguageName;
options: TNtLanguageDialogOptions;
position: TFormPosition): Boolean;
var
dialog: TNtLanguageDialog;
begin
if ldShowErrorIfNoResource in options then
TNtBase.CheckThatDllsExist;
if originalLanguage = '' then
originalLanguage := NtBase.OriginalLanguage;
dialog := TNtLanguageDialog.Create(nil);
dialog.OriginalLanguage := originalLanguage;
dialog.Position := position;
dialog.FLanguageName := languageName;
dialog.FOptions := options;
if dialog.ShowModal = mrOk then
begin
language := dialog.SelectedLanguage;
Result := True;
end
else
begin
language := '';
Result := False;
end;
end;
class procedure TNtLanguageDialog.Choose(
done: TProc<String>;
originalLanguage: String;
languageName: TNtLanguageName;
options: TNtLanguageDialogOptions;
position: TFormPosition);
var
dialog: TNtLanguageDialog;
begin
if ldShowErrorIfNoResource in options then
TNtBase.CheckThatDllsExist;
if originalLanguage = '' then
originalLanguage := NtBase.OriginalLanguage;
dialog := TNtLanguageDialog.Create(nil);
dialog.OriginalLanguage := originalLanguage;
dialog.Position := position;
dialog.FLanguageName := languageName;
dialog.FOptions := options;
dialog.ShowModal(procedure(modalResult: TModalResult)
begin
if modalResult = mrOk then
done(dialog.SelectedLanguage);
end);
end;
procedure TNtLanguageDialog.FormCreate(Sender: TObject);
begin
FOriginalLanguage := '';
FLanguageName := lnNative;
_T(Self);
end;
procedure TNtLanguageDialog.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := TCloseAction.caFree;
end;
procedure LoadBitmap(bitmap: TBitmap; const resName: String);
var
stream: TResourceStream;
begin
if resName = '' then
Exit;
stream := TResourceStream.Create(HInstance, resName, RT_RCDATA);
try
bitmap.LoadFromStream(stream);
finally
stream.Free;
end;
end;
procedure TNtLanguageDialog.FormActivate(Sender: TObject);
procedure Add(language: TNtLanguage);
var
item: TListBoxItem;
begin
item := TListBoxItem.Create(nil);
item.Parent := LanguageList;
//item.StyleLookup := 'CustomItem';
item.Text := language.Names[LanguageName];
item.Data := TLanguageCode.Create(language.Code);
LoadBitmap(item.ItemData.Bitmap, NtResources.LanguageImages[language.Code]);
if item.ItemData.Bitmap.Height > 0 then
item.Height := item.ItemData.Bitmap.Height;
item.Height := item.Height + 2
end;
var
i: Integer;
availableLanguages: TNtLanguages;
begin
if LanguageList.Count > 0 then
Exit;
LanguageList.BeginUpdate;
try
availableLanguages := TNtLanguages.Create;
try
if OriginalLanguage <> '' then
availableLanguages.Add(OriginalLanguage);
TNtBase.GetAvailable(availableLanguages, '');
for i := 0 to availableLanguages.Count - 1 do
Add(availableLanguages[i]);
finally
availableLanguages.Free;
end;
if LoadedResourceLocale <> '' then
begin
for i := 0 to LanguageCount - 1 do
begin
if SameText(Languages[i], LoadedResourceLocale) then
begin
LanguageList.ItemIndex := i;
Exit;
end;
end;
end
else
begin
for i := 0 to LanguageCount - 1 do
begin
if SameText(Languages[i], OriginalLanguage) then
begin
LanguageList.ItemIndex := i;
Exit;
end;
end;
end;
if (LanguageList.ItemIndex = -1) and (LanguageList.Items.Count > 0) then
LanguageList.ItemIndex := 0;
finally
LanguageList.EndUpdate;
end;
end;
procedure TNtLanguageDialog.LanguageListDblClick(Sender: TObject);
begin
ModalResult := mrOk;
end;
end.
|
////////////////////////////////////////////////////////////////////////////
// PaxCompiler
// Site: http://www.paxcompiler.com
// Author: Alexander Baranovsky (paxscript@gmail.com)
// ========================================================================
// Copyright (c) Alexander Baranovsky, 2006-2014. All rights reserved.
// Code Version: 4.2
// ========================================================================
// Unit: PaxJavaScriptLanguage.pas
// ========================================================================
////////////////////////////////////////////////////////////////////////////
{$I PaxCompiler.def}
unit PaxJavaScriptLanguage;
interface
uses
SysUtils,
Classes,
PAXCOMP_PARSER,
PAXCOMP_JS_PARSER,
PaxRegister,
PaxCompiler;
type
TPaxJavaScriptLanguage = class(TPaxCompilerLanguage)
protected
function GetParser: TBaseParser; override;
public
constructor Create(AOwner: TComponent); override;
procedure SetCallConv(CallConv: Integer); override;
function GetLanguageName: String; override;
published
end;
implementation
function TPaxJavaScriptLanguage.GetParser: TBaseParser;
begin
result := P;
end;
function TPaxJavaScriptLanguage.GetLanguageName: String;
begin
result := P.LanguageName;
end;
constructor TPaxJavaScriptLanguage.Create(AOwner: TComponent);
begin
inherited;
P := TJavaScriptParser.Create;
SetCallConv(_ccSTDCALL);
end;
procedure TPaxJavaScriptLanguage.SetCallConv(CallConv: Integer);
begin
if CallConv <> _ccSTDCALL then
raise Exception.Create('Only STDCALL convention is allowed.');
P.CallConv := CallConv;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLSpaceText<p>
3D Text component.<p>
Note: You can get valid extents (including AABB's) of this component only
after it has been rendered for the first time. It means if you ask its
extents during / after its creation, you will get zeros.
Also extents are valid only when SpaceText has one line. <p>
<b>History : </b><font size=-1><ul>
<li>05/03/10 - DanB - More state added to TGLStateCache
<li>25/12/07 - DaStr - Added MultiLine support (thanks Lexer)
Fixed Memory leak in TFontManager.Destroy
(Bugtracker ID = 1857814)
<li>19/09/07 - DaStr - Added some comments
Optimized TGLSpaceText.BarycenterAbsolutePosition
<li>12/09/07 - DaStr - Bugfixed TGLSpaceText.BarycenterAbsolutePosition
(Didn't consider rotations)
<li>08/09/07 - DaStr - Implemented AxisAlignedDimensionsUnscaled and
BarycenterAbsolutePosition for TGLSpaceText
<li>28/03/07 - DaStr - Renamed parameters in some methods
(thanks Burkhard Carstens) (Bugtracker ID = 1678658)
<li>17/03/07 - DaStr - Dropped Kylix support in favor of FPC (BugTracekrID=1681585)
<li>16/03/07 - DaStr - Added explicit pointer dereferencing
(thanks Burkhard Carstens) (Bugtracker ID = 1678644)
<li>19/10/06 - LC - Added TGLSpaceText.Assign. Bugtracker ID=1576445 (thanks Zapology)
<li>16/09/06 - NC - TGLVirtualHandle update (thx Lionel Reynaud)
<li>03/06/02 - EG - VirtualHandle notification fix (S�ren M�hlbauer)
<li>07/03/02 - EG - GetFontBase fix (S�ren M�hlbauer)
<li>30/01/02 - EG - Text Alignment (S�ren M�hlbauer),
TFontManager now GLContext compliant (RenderToBitmap ok!)
<li>28/12/01 - EG - Event persistence change (GliGli / Dephi bug)
<li>12/12/01 - EG - Creation (split from GLScene.pas)
</ul></font>
}
unit GLSpaceText;
interface
{$i GLScene.inc}
{$IFDEF UNIX}{$Message Error 'Unit not supported'}{$ENDIF}
uses
// VCL
Windows, Messages, Dialogs, Classes, Graphics,
// GLScene
GLScene, OpenGL1x, GLTexture, GLContext, GLVectorGeometry, GLStrings,
GLRenderContextInfo, GLState;
type
// TSpaceTextCharRange
//
TSpaceTextCharRange = (stcrAlphaNum, stcrNumbers, stcrAll);
// TGLTextHorzAdjust
//
// Note: haAligned, haCentrically, haFitIn have not been implemented!
//
TGLTextHorzAdjust = (haLeft, haCenter, haRight, haAligned, haCentrically, haFitIn);
// TGLTextVertAdjust
//
TGLTextVertAdjust = (vaTop, vaCenter, vaBottom, vaBaseLine);
// TGLTextAdjust
//
TGLTextAdjust = class(TPersistent)
private
{ Private Declarations }
FHorz: TGLTextHorzAdjust;
FVert: TGLTextVertAdjust;
FOnChange: TNotifyEvent;
procedure SetHorz(const Value: TGLTextHorzAdjust);
procedure SetVert(const Value: TGLTextVertAdjust);
public
{ public Declarations }
constructor Create;
procedure Assign(Source: TPersistent); override;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
published
{ Published Declarations }
property Horz: TGLTextHorzAdjust read FHorz write SetHorz default haLeft;
property Vert: TGLTextVertAdjust read FVert write SetVert default vaBaseLine;
end;
// holds an entry in the font manager list (used in TGLSpaceText)
PFontEntry = ^TFontEntry;
TFontEntry = record
Name : String;
FVirtualHandle : TGLVirtualHandle;
Styles : TFontStyles;
Extrusion : Single;
RefCount : Integer;
allowedDeviation : Single;
firstChar, lastChar : Integer;
glyphMetrics : array [0..255] of TGlyphMetricsFloat;
FClients : TList;
end;
// TGLSpaceText
//
{: Renders a text in 3D. }
TGLSpaceText = class (TGLSceneObject)
private
{ Private Declarations }
FFont : TFont;
FExtrusion : Single;
FAllowedDeviation : Single;
FCharacterRange : TSpaceTextCharRange;
FAdjust : TGLTextAdjust;
FAspectRatio : Single;
FOblique : Single;
FTextHeight : Single;
FLines: TStringList;
procedure SetCharacterRange(const val : TSpaceTextCharRange);
procedure SetAllowedDeviation(const val : Single);
procedure SetExtrusion(AValue: Single);
procedure SetFont(AFont: TFont);
function GetText: string;
procedure SetLines(const Value: TStringList);
procedure SetText(const AText: String);
procedure SetAdjust(const value : TGLTextAdjust);
procedure SetAspectRatio(const value : Single);
procedure SetOblique(const value : Single);
procedure SetTextHeight(const value : Single);
protected
{ Protected Declarations }
FTextFontEntry : PFontEntry;
FontChanged : Boolean;
procedure DestroyHandle; override;
procedure OnFontChange(sender : TObject);
procedure GetFirstAndLastChar(var firstChar, lastChar : Integer);
procedure DoOnLinesChange(Sender: TObject); virtual;
public
{ Public Declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure BuildList(var rci : TRenderContextInfo); override;
procedure DoRender(var ARci : TRenderContextInfo;
ARenderSelf, ARenderChildren : Boolean); override;
function TextWidth(const str : String = '') : Single;
function TextMaxHeight(const str : String = '') : Single;
function TextMaxUnder(const str : String = '') : Single;
{: Note: this fuction is valid only after text has been rendered
the first time. Before that it returns zeros. }
procedure TextMetrics(const str : String; var width, maxHeight, maxUnder : Single);
procedure NotifyFontChanged;
procedure NotifyChange(Sender: TObject); override;
procedure DefaultHandler(var Message); override;
function AxisAlignedDimensionsUnscaled : TVector; override;
function BarycenterAbsolutePosition: TVector; override;
published
{ Published Declarations }
{: Adjusts the 3D font extrusion.<p>
If Extrusion=0, the characters will be flat (2D), values >0 will
give them a third dimension. }
property Extrusion: Single read FExtrusion write SetExtrusion;
property Font: TFont read FFont write SetFont;
property Text: String read GetText write SetText stored False;
property Lines: TStringList read FLines write SetLines;
{: Quality related, see Win32 help for wglUseFontOutlines }
property AllowedDeviation : Single read FAllowedDeviation write SetAllowedDeviation;
{: Character range to convert.<p>
Converting less characters saves time and memory... }
property CharacterRange : TSpaceTextCharRange read FCharacterRange write SetCharacterRange default stcrAll;
property AspectRatio : Single read FAspectRatio write SetAspectRatio;
property TextHeight : Single read FTextHeight write SetTextHeight;
property Oblique : Single read FOblique write SetOblique;
property Adjust : TGLTextAdjust read FAdjust write SetAdjust;
end;
// TFontManager
//
{: Manages a list of fonts for which display lists were created. }
TFontManager = class(TList)
private
{ Private Declarations }
FCurrentBase : Integer;
protected
{ Protected Declarations }
procedure NotifyClients(Clients:TList);
procedure VirtualHandleAlloc(sender : TGLVirtualHandle; var handle : Cardinal);
procedure VirtualHandleDestroy(sender : TGLVirtualHandle; var handle : Cardinal);
public
{ Public Declarations }
constructor Create;
destructor Destroy; override;
function FindFont(AName: String; FStyles: TFontStyles; FExtrusion: Single;
FAllowedDeviation : Single;
FFirstChar, FLastChar : Integer) : PFontEntry;
function GetFontBase(AName: String; FStyles: TFontStyles; FExtrusion: Single;
allowedDeviation : Single;
firstChar, lastChar : Integer; client : TObject) : PFontEntry;
procedure Release(entry : PFontEntry; client : TObject);
end;
function FontManager : TFontManager;
procedure ReleaseFontManager;
var
vFontManagerMsgID : Cardinal;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
uses SysUtils;
const
cFontManagerMsg = 'GLScene FontManagerMessage';
var
vFontManager : TFontManager;
// FontManager
//
function FontManager : TFontManager;
begin
if not Assigned(vFontManager) then
vFontManager:=TFontManager.Create;
Result:=vFontManager;
end;
// ReleaseFontManager
//
procedure ReleaseFontManager;
begin
if Assigned(vFontManager) then begin
vFontManager.Free;
vFontManager:=nil;
end;
end;
// ------------------
// ------------------ TGLTextAdjust ------------------
// ------------------
// Create
//
constructor TGLTextAdjust.Create;
begin
inherited;
FHorz:=haLeft;
FVert:=vaBaseLine;
end;
// Assign
//
procedure TGLTextAdjust.Assign(source : TPersistent);
begin
if Source is TGLTextAdjust then begin
FHorz:=TGLTextAdjust(source).Horz;
FVert:=TGLTextAdjust(source).Vert;
if Assigned(FOnChange) then
FOnChange(Self);
end else inherited Assign(Source);
end;
// SetHorz
//
procedure TGLTextAdjust.SetHorz(const value : TGLTextHorzAdjust);
begin
if FHorz<>value then begin
FHorz:=value;
if Assigned(FOnChange) then
FOnChange(Self);
end;
end;
// SetVert
//
procedure TGLTextAdjust.SetVert(const value : TGLTextVertAdjust);
begin
if value<>FVert then begin
FVert:=value;
if Assigned(FOnChange) then
FOnChange(Self);
end;
end;
// ------------------
// ------------------ TGLSpaceText ------------------
// ------------------
// Create
//
constructor TGLSpaceText.Create(AOwner:TComponent);
begin
inherited Create(AOwner);
FFont:=TFont.Create;
FFont.Name:='Arial';
FontChanged:=True;
CharacterRange:=stcrAll;
FFont.OnChange:=OnFontChange;
FAdjust:=TGLTextAdjust.Create;
FAdjust.OnChange:=OnFontChange;
FLines := TStringList.Create;
FLines.OnChange := DoOnLinesChange;
end;
// Destroy
//
destructor TGLSpaceText.Destroy;
begin
FAdjust.OnChange:=nil;
FAdjust.Free;
FFont.OnChange:=nil;
FFont.Free;
FLines.Free;
FontManager.Release(FTextFontEntry, Self);
inherited Destroy;
end;
// TextMetrics
//
procedure TGLSpaceText.TextMetrics(const str : String; var width, maxHeight, maxUnder : Single);
var
i, firstChar, lastChar : Integer;
buf : String;
gmf : TGlyphMetricsFloat;
begin
width:=0;
maxUnder:=0;
maxHeight:=0;
if Assigned(FTextFontEntry) then begin
GetFirstAndLastChar(firstChar, lastChar);
if str='' then
buf:=GetText
else buf:=str;
for i:=1 to Length(buf) do begin
gmf:=FTextFontEntry^.GlyphMetrics[Integer(buf[i])-firstChar];
width:=width+gmf.gmfCellIncX;
if gmf.gmfptGlyphOrigin.y>maxHeight then
maxHeight:=gmf.gmfptGlyphOrigin.y;
if gmf.gmfptGlyphOrigin.y-gmf.gmfBlackBoxY<maxUnder then
maxUnder:=gmf.gmfptGlyphOrigin.y-gmf.gmfBlackBoxY;
end;
end;
end;
// TextWidth
//
function TGLSpaceText.TextWidth(const str : String = '') : Single;
var
mh, mu : Single;
begin
TextMetrics(str, Result, mh, mu);
end;
// TextMaxHeight
//
function TGLSpaceText.TextMaxHeight(const str : String = '') : Single;
var
w, mu : Single;
begin
TextMetrics(str, w, Result, mu);
end;
// TextMaxUnder
//
function TGLSpaceText.TextMaxUnder(const str : String = '') : Single;
var
w, mh : Single;
begin
TextMetrics(str, w, mh, Result);
end;
// Assign
procedure TGLSpaceText.Assign(Source: TPersistent);
begin
inherited Assign(Source);
if Source is TGLSpaceText then
begin
FAdjust.Assign(TGLSpaceText(Source).FAdjust);
FFont.Assign(TGLSpaceText(Source).FFont);
FAllowedDeviation := TGLSpaceText(Source).AllowedDeviation;
FAspectRatio := TGLSpaceText(Source).FAspectRatio;
FCharacterRange := TGLSpaceText(Source).CharacterRange;
FExtrusion := TGLSpaceText(Source).FExtrusion;
FOblique := TGLSpaceText(Source).FOblique;
FLines.Text := TGLSpaceText(Source).FLines.Text;
FTextHeight := TGLSpaceText(Source).FTextHeight;
StructureChanged;
end;
end;
// BuildList
//
procedure TGLSpaceText.BuildList(var rci : TRenderContextInfo);
var
textL, maxUnder, maxHeight : Single;
charScale : Single;
i: integer;
begin
if Length(GetText)>0 then begin
glPushMatrix;
//FAspectRatio ignore
if FAspectRatio<>0 then
glScalef(FAspectRatio, 1, 1);
if FOblique<>0 then
glRotatef(FOblique, 0, 0, 1);
rci.GLStates.PushAttrib([sttPolygon]);
case FCharacterRange of
stcrAlphaNum : glListBase(FTextFontEntry^.FVirtualHandle.Handle - 32);
stcrNumbers : glListBase(FTextFontEntry^.FVirtualHandle.Handle - Cardinal('0'));
else
glListBase(FTextFontEntry^.FVirtualHandle.Handle);
end;
for i:=0 to FLines.Count-1 do begin
glPushMatrix;
TextMetrics(FLines.Strings[i], textL, maxHeight, maxUnder);
if (FAdjust.Horz<>haLeft) or (FAdjust.Vert<>vaBaseLine) or (FTextHeight<>0) then begin
if FTextHeight<>0 then begin
charScale:=FTextHeight/MaxHeight;
glScalef(CharScale,CharScale,1);
end;
case FAdjust.Horz of
haLeft : ; // nothing
haCenter : glTranslatef(-textL*0.5, 0, 0);
haRight : glTranslatef(-textL, 0, 0);
end;
case FAdjust.Vert of
vaBaseLine : ; // nothing;
vaBottom : glTranslatef(0, abs(maxUnder), 0);
vaCenter : glTranslatef(0, abs(maxUnder)*0.5-maxHeight*0.5, 0);
vaTop : glTranslatef(0, -maxHeight, 0);
end;
end;
glTranslatef(0,-i*(maxHeight+FAspectRatio),0);
glCallLists(Length(FLines.Strings[i]), GL_UNSIGNED_BYTE, PGLChar(TGLString(FLines.Strings[i])));
glPopMatrix;
end;
rci.GLStates.PopAttrib;
glPopMatrix;
end;
end;
// DestroyHandle
//
procedure TGLSpaceText.DestroyHandle;
begin
FontChanged:=True;
inherited;
end;
// GetFirstAndLastChar
//
procedure TGLSpaceText.GetFirstAndLastChar(var firstChar, lastChar : Integer);
begin
case FCharacterRange of
stcrAlphaNum : begin
firstChar:=32;
lastChar:=127;
end;
stcrNumbers : begin
firstChar:=Integer('0');
lastChar:=Integer('9');
end;
else
// stcrAll
firstChar:=0;
lastChar:=255;
end;
end;
// DoRender
//
procedure TGLSpaceText.DoRender(var ARci : TRenderContextInfo;
ARenderSelf, ARenderChildren : Boolean);
var
firstChar, lastChar : Integer;
begin
if GetText<>'' then begin
if FontChanged or (Assigned(FTextFontEntry)
and (FTextFontEntry^.FVirtualHandle.Handle=0)) then with FFont do begin
FontManager.Release(FTextFontEntry, Self);
GetFirstAndLastChar(firstChar, lastChar);
FTextFontEntry:=FontManager.GetFontBase(Name, Style, FExtrusion,
FAllowedDeviation,
firstChar, lastChar,
Self);
FontChanged:=False;
end;
end;
inherited;
end;
// SetExtrusion
//
procedure TGLSpaceText.SetExtrusion(AValue: Single);
begin
Assert(AValue>=0, 'Extrusion must be >=0');
if FExtrusion<>AValue then begin
FExtrusion:=AValue;
OnFontChange(nil);
end;
end;
// SetAllowedDeviation
//
procedure TGLSpaceText.SetAllowedDeviation(const val : Single);
begin
if FAllowedDeviation<>val then begin
if val>0 then
FAllowedDeviation:=val
else FAllowedDeviation:=0;
OnFontChange(nil);
end;
end;
// SetCharacterRange
//
procedure TGLSpaceText.SetCharacterRange(const val : TSpaceTextCharRange);
begin
if FCharacterRange<>val then begin
FCharacterRange:=val;
OnFontChange(nil);
end;
end;
// SetFont
//
procedure TGLSpaceText.SetFont(AFont: TFont);
begin
FFont.Assign(AFont);
OnFontChange(nil);
end;
// OnFontChange
//
procedure TGLSpaceText.OnFontChange(sender : TObject);
begin
FontChanged:=True;
StructureChanged;
end;
// SetText
//
procedure TGLSpaceText.SetText(const AText: String);
begin
if GetText<>AText then
begin
FLines.Text:=AText;
// StructureChanged is Called in DoOnLinesChange.
end;
end;
procedure TGLSpaceText.DoOnLinesChange(Sender: TObject);
begin
StructureChanged;
end;
// SetAdjust
//
function TGLSpaceText.GetText: string;
begin
if FLines.Count = 1 then
Result := FLines[0]
else
Result := FLines.Text;
end;
// SetAdjust
//
procedure TGLSpaceText.SetLines(const Value: TStringList);
begin
FLines.Assign(Value);
end;
// SetAdjust
//
procedure TGLSpaceText.SetAdjust(const value : TGLTextAdjust);
begin
FAdjust.Assign(Value);
StructureChanged;
end;
// SetAspectRatio
//
procedure TGLSpaceText.SetAspectRatio(const value : Single);
begin
if FAspectRatio<>value then begin
FAspectRatio:=value;
StructureChanged;
end;
end;
// SetOblique
//
procedure TGLSpaceText.SetOblique(const value : Single);
begin
if FOblique<>Value then begin
FOblique:=value;
StructureChanged;
end;
end;
// SetTextHeight
//
procedure TGLSpaceText.SetTextHeight(const value : Single);
begin
if value<>FTextHeight then begin
FTextHeight:=value;
StructureChanged;
end;
end;
// NotifyFontChanged
//
procedure TGLSpaceText.NotifyFontChanged;
begin
FTextFontEntry:=nil;
FontChanged:=True;
end;
// NotifyChange
//
procedure TGLSpaceText.NotifyChange(sender : TObject);
begin
if Sender is TFontManager then
NotifyFontChanged
else inherited;
end;
// DefaultHandler
//
procedure TGLSpaceText.DefaultHandler(var Message);
begin
with TMessage(Message) do begin
if Msg=vFontManagerMsgID then
NotifyFontChanged
else inherited;
end;
end;
// BarycenterAbsolutePosition
//
function TGLSpaceText.BarycenterAbsolutePosition: TVector;
var
lWidth, lHeightMax, lHeightMin: Single;
AdjustVector: TVector;
begin
TextMetrics(Text, lWidth, lHeightMax, lHeightMin);
case FAdjust.FHorz of
haLeft: AdjustVector[0] := lWidth / 2;
haCenter: AdjustVector[0] := 0; // Nothing.
haRight: AdjustVector[0] := - lWidth / 2;
else
begin
AdjustVector[0] := 0;
Assert(False, glsErrorEx + glsUnknownType); // Not implemented...
end;
end;
case FAdjust.FVert of
vaTop: AdjustVector[1] := - (Abs(lHeightMin) * 0.5 + lHeightMax * 0.5);
vaCenter: AdjustVector[1] := 0; // Nothing.
vaBottom: AdjustVector[1] := (Abs(lHeightMin) * 0.5 + lHeightMax * 0.5);
vaBaseLine: AdjustVector[1] := - (Abs(lHeightMin) * 0.5 - lHeightMax * 0.5);
else
begin
AdjustVector[1] := 0;
Assert(False, glsErrorEx + glsUnknownType); // Not implemented...
end;
end;
AdjustVector[2] := - (FExtrusion / 2);
AdjustVector[3] := 1;
Result := LocalToAbsolute(AdjustVector);
end;
// AxisAlignedDimensionsUnscaled
//
function TGLSpaceText.AxisAlignedDimensionsUnscaled: TVector;
var
lWidth, lHeightMax, lHeightMin: Single;
charScale: Single;
begin
TextMetrics(Text, lWidth, lHeightMax, lHeightMin);
if FTextHeight = 0 then
charScale := 1
else
charScale := FTextHeight / lHeightMax;
Result[0] := lWidth / 2 * charScale;
Result[1] := (lHeightMax + Abs(lHeightMin)) / 2 * charScale;
Result[2] := FExtrusion / 2;
Result[3] := 0;
end;
// ------------------
// ------------------ TFontManager ------------------
// ------------------
// Create
//
constructor TFontManager.Create;
begin
inherited;
end;
// Destroy
//
destructor TFontManager.Destroy;
var
i : Integer;
begin
for i:=0 to Count-1 do begin
TFontEntry(Items[i]^).FVirtualHandle.Free;
NotifyClients(TFontEntry(Items[i]^).FClients);
TFontEntry(Items[i]^).FClients.Free;
TFontEntry(Items[i]^).Name := '';
FreeMem(Items[i], SizeOf(TFontEntry));
end;
inherited Destroy;
end;
// VirtualHandleAlloc
//
procedure TFontManager.VirtualHandleAlloc(sender : TGLVirtualHandle; var handle : Cardinal);
begin
handle:=FCurrentBase;
end;
// VirtualHandleDestroy
//
procedure TFontManager.VirtualHandleDestroy(sender : TGLVirtualHandle; var handle : Cardinal);
begin
if handle<>0 then
glDeleteLists(handle, sender.Tag);
end;
// FindFond
//
function TFontManager.FindFont(AName: String; FStyles: TFontStyles; FExtrusion: Single;
FAllowedDeviation : Single;
FFirstChar, FLastChar : Integer) : PFontEntry;
var
i : Integer;
begin
Result:=nil;
// try to find an entry with the required attributes
for I :=0 to Count-1 do with TFontEntry(Items[I]^) do
if (CompareText(Name, AName) = 0) and (Styles = FStyles)
and (Extrusion = FExtrusion) and (allowedDeviation=FAllowedDeviation)
and (firstChar=FFirstChar) and (lastChar=FLastChar) then begin
// entry found
Result:=Items[I];
Break;
end;
end;
// GetFontBase
//
function TFontManager.GetFontBase(AName: String; FStyles: TFontStyles; FExtrusion: Single;
allowedDeviation : Single;
firstChar, lastChar : Integer; client : TObject) : PFontEntry;
var
NewEntry : PFontEntry;
MemDC : HDC;
AFont : TFont;
nbLists : Integer;
begin
NewEntry:=FindFont(AName, FStyles, FExtrusion, allowedDeviation, firstChar, lastChar);
if Assigned(NewEntry) then begin
Inc(NewEntry^.RefCount);
if NewEntry^.FClients.IndexOf(Client)<0 then
NewEntry^.FClients.Add(Client);
Result:=NewEntry;
end else Result:=nil;
if (Result=nil) or (Assigned(Result) and (Result^.FVirtualHandle.Handle=0)) then begin
// no entry found, or entry was purged
nbLists:=lastChar-firstChar+1;
if not Assigned(newEntry) then begin
// no entry found, so create one
New(NewEntry);
NewEntry^.Name:=AName;
NewEntry^.FVirtualHandle:=TGLVirtualHandle.Create;
NewEntry^.FVirtualHandle.OnAllocate:=VirtualHandleAlloc;
NewEntry^.FVirtualHandle.OnDestroy:=VirtualHandleDestroy;
NewEntry^.FVirtualHandle.Tag:=nbLists;
NewEntry^.Styles:=FStyles;
NewEntry^.Extrusion:=FExtrusion;
NewEntry^.RefCount:=1;
NewEntry^.firstChar:=firstChar;
NewEntry^.lastChar:=lastChar;
NewEntry^.allowedDeviation:=allowedDeviation;
NewEntry^.FClients:=TList.Create;
NewEntry^.FClients.Add(Client);
Add(NewEntry);
end;
// create a font to be used while display list creation
AFont:=TFont.Create;
MemDC:=CreateCompatibleDC(0);
try
AFont.Name:=AName;
AFont.Style:=FStyles;
SelectObject(MemDC, AFont.Handle);
FCurrentBase:=glGenLists(nbLists);
if FCurrentBase = 0 then
raise Exception.Create('FontManager: no more display lists available');
NewEntry^.FVirtualHandle.AllocateHandle;
if not OpenGL1x.wglUseFontOutlines(MemDC, firstChar, nbLists,
FCurrentBase, allowedDeviation,
FExtrusion, WGL_FONT_POLYGONS,
@NewEntry^.GlyphMetrics) then
raise Exception.Create('FontManager: font creation failed');
finally
AFont.Free;
DeleteDC(MemDC);
end;
Result:=NewEntry;
end;
end;
// Release
//
procedure TFontManager.Release(entry : PFontEntry; client : TObject);
var
hMsg : TMessage;
begin
if Assigned(entry) then begin
Dec(entry^.RefCount);
if Assigned(Client) then begin
hMsg.Msg:=vFontManagerMsgID;
Client.DefaultHandler(hMsg);
end;
entry^.FClients.Remove(Client);
if entry^.RefCount=0 then begin
entry^.FVirtualHandle.Free;
NotifyClients(entry^.FClients);
entry^.FClients.Free;
Remove(entry);
Dispose(entry)
end;
end;
end;
// NotifyClients
//
procedure TFontManager.NotifyClients(Clients:TList);
var
i : Integer;
hMsg : TMessage;
begin
hMsg.Msg:=vFontManagerMsgID;
for i:=0 to Clients.Count-1 do
TObject(Clients[i]).DefaultHandler(hMsg);
end;
//-------------------------------------------------------------
//-------------------------------------------------------------
//-------------------------------------------------------------
initialization
//-------------------------------------------------------------
//-------------------------------------------------------------
//-------------------------------------------------------------
vFontManagerMsgID:=RegisterWindowMessage(cFontManagerMsg);
RegisterClass(TGLSpaceText);
finalization
ReleaseFontManager;
end.
|
unit FormCharsetChkMain;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Controls.Presentation, FMX.StdCtrls, KrDnceUtilTypes;
type
TForm1 = class(TForm)
Button1: TButton;
OpenDialog1: TOpenDialog;
Button2: TButton;
Label1: TLabel;
Label2: TLabel;
Button3: TButton;
Button4: TButton;
SaveDialog1: TSaveDialog;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Button5: TButton;
Button6: TButton;
Label6: TLabel;
Label7: TLabel;
Button7: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
procedure Button7Click(Sender: TObject);
private
FSize: Integer;
FCharset: array of Byte;
FChrsetIdxs: array[0..255] of Integer;
FChrsetMchs: TCharsetMatches;
FFrameCount: Integer;
FFrames: TMemoryStream;
FFramesConv: TMemoryStream;
procedure C64CharToColours(const AChar: Byte; out AColours: TC64Colours);
procedure DoFillCharset(AOffset: Integer);
procedure DoProcChrsetIdxs(const ASize: Integer);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
var
f: TMemoryStream;
begin
if OpenDialog1.Execute then
begin
f:= TMemoryStream.Create;
try
f.LoadFromFile(OpenDialog1.FileName);
if f.Size > 2048 then
begin
Label1.Text:= 'Invalid charset size';
Exit;
end;
FSize:= f.Size;
SetLength(FCharset, 2048);
FillChar(FCharset[0], 2048, 0);
Move(PByte(f.Memory)[0], FCharset[0], FSize);
Label1.Text:= IntToStr(FSize);
finally
f.Free;
end;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
try
DoProcChrsetIdxs(FSize);
Label2.Text:= IntToStr(FSize div 8);
except
on E: Exception do
Label2.Text:= E.Message;
end;
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
try
DoFillCharset(FSize);
Label3.Text:= 'Done';
except
on E: Exception do
Label3.Text:= E.Message;
end;
end;
procedure TForm1.Button4Click(Sender: TObject);
var
f: TFileStream;
begin
if SaveDialog1.Execute then
begin
f:= TFileStream.Create(SaveDialog1.FileName, fmCreate);
try
f.WriteBuffer(FCharset[0], 2048);
finally
f.Free;
end;
end;
end;
procedure TForm1.Button5Click(Sender: TObject);
begin
if OpenDialog1.Execute then
begin
if Assigned(FFrames) then
begin
FFrames.Free;
FFrames:= nil;
end;
FFrames:= TMemoryStream.Create;
FFrames.LoadFromFile(OpenDialog1.FileName);
if (FFrames.Size mod 1000) <> 0 then
begin
FFrames.Free;
FFrames:= nil;
Label6.Text:= 'Invalid frames size';
Exit;
end;
FFrameCount:= FFrames.Size div 1000;
Label6.Text:= IntToStr(FFrameCount);
end;
end;
procedure TForm1.Button6Click(Sender: TObject);
var
i: Integer;
begin
if Assigned(FFramesConv) then
begin
FFramesConv.Free;
FFramesConv:= nil;
end;
if Assigned(FFrames) then
begin
FFramesConv:= TMemoryStream.Create;
FFramesConv.SetSize(FFrames.Size);
for i:= 0 to FFrames.Size - 1 do
PByte(FFramesConv.Memory)[i]:=
FChrsetIdxs[PByte(FFrames.Memory)[i]];
Label7.Text:= IntToStr(FFramesConv.Size);
end;
end;
procedure TForm1.Button7Click(Sender: TObject);
begin
if SaveDialog1.Execute then
begin
FFramesConv.Position:= 0;
FFramesConv.SaveToFile(SaveDialog1.FileName);
end;
end;
procedure TForm1.C64CharToColours(const AChar: Byte; out AColours: TC64Colours);
var
b: Byte;
begin
b:= FCharset[AChar * 8];
AColours[0]:= TC64Colour((b and (128 or 64)) shr 6);
AColours[1]:= TC64Colour((b and (8 or 4)) shr 2);
b:= FCharset[AChar * 8 + 4];
AColours[2]:= TC64Colour((b and (128 or 64)) shr 6);
AColours[3]:= TC64Colour((b and (8 or 4)) shr 2);
end;
procedure TForm1.DoFillCharset(AOffset: Integer);
var
c: TC64Char;
i,
n: Integer;
l: TC64Colours;
begin
n:= 0;
for i:= 0 to 255 do
if not FChrsetMchs[i] then
begin
IndexToC64Colours(i, l);
ColoursToC64Char(l, c);
Move(c[0], FCharset[AOffset + n * 8], 8);
Inc(n);
if ((n * 8) + AOffset) > 2048 then
raise Exception.Create('Data range error!');
end;
end;
procedure TForm1.DoProcChrsetIdxs(const ASize: Integer);
var
i: Integer;
l: TC64Colours;
b: Byte;
begin
if (ASize mod 8) <> 0 then
raise Exception.Create('Invalid charset!');
for i:= 0 to 255 do
begin
FChrsetMchs[i]:= False;
FChrsetIdxs[i]:= -1;
end;
for i:= 0 to Pred(ASize div 8) do
begin
C64CharToColours(i, l);
b:= C64ColorsToIndex(l);
if FChrsetMchs[b] then
raise Exception.Create('Duplicate colour set!');
FChrsetMchs[b]:= True;
FChrsetIdxs[i]:= b;
end;
end;
end.
|
unit VoxelModelizer;
// Warning: DEPRECATED!
// Voxel Modelizer was an experience to create a method based
// on marching cubes to transform voxel based data into polygonal models.
// It has failed and it is deprecated. VXLSE III does not use it.
// The code is here just in case somebody get any idea from it... or not.
// It was insane and ate far too much RAM while the current method does a
// much better job using a ridiculous amount of RAM.
interface
uses VoxelMap, BasicDataTypes, VoxelModelizerItem, BasicConstants, ThreeDMap,
Palette, FaceQueue;
type
TVoxelModelizer = class
private
FItems : array of TVoxelModelizerItem;
PVoxelMap : PVoxelMap;
PSemiSurfacesMap : P3DIntGrid;
FNumVertexes : integer;
function GetNormals(_V1,_V2,_V3: TVector3f): TVector3f;
function CopyMap(const _Map: T3DIntGrid): T3DIntGrid;
public
// Constructors and Destructors
constructor Create(const _VoxelMap : TVoxelMap; const _SemiSurfaces: T3DIntGrid; var _Vertexes: TAVector3f; var _Faces: auint32; var _Normals: TAVector3f; var _Colours: TAVector4f; const _Palette: TPalette; const _ColourMap: TVoxelMap);
destructor Destroy; override;
// Misc
procedure GenerateItemsMap(var FMap : T3DIntGrid);
end;
implementation
constructor TVoxelModelizer.Create(const _VoxelMap : TVoxelMap; const _SemiSurfaces: T3DIntGrid; var _Vertexes: TAVector3f; var _Faces: auint32; var _Normals: TAVector3f; var _Colours: TAVector4f; const _Palette: TPalette; const _ColourMap: TVoxelMap);
var
FMap : T3DIntGrid;
x, y, z, i, pos, NumFaces: integer;
Size : TVector3i;
FVertexMap: T3DIntGrid;
ModelMap: T3DMap;
Vertexes: TAVector3i;
Normal : TVector3f;
Face: PFaceData;
begin
// Prepare basic variables.
PVoxelMap := @_VoxelMap;
PSemiSurfacesMap := @_SemiSurfaces;
// Store VertexMap size for ModelMap.
Size.X := ((PVoxelMap^.GetMaxX + 1)*C_VP_HIGH)+1;
Size.Y := ((PVoxelMap^.GetMaxY + 1)*C_VP_HIGH)+1;
Size.Z := ((PVoxelMap^.GetMaxZ + 1)*C_VP_HIGH)+1;
// Prepare other map types.
SetLength(FVertexMap,Size.X,Size.Y,Size.Z);
for x := Low(FVertexMap) to High(FVertexMap) do
for y := Low(FVertexMap[x]) to High(FVertexMap[x]) do
for z := Low(FVertexMap[x,y]) to High(FVertexMap[x,y]) do
FVertexMap[x,y,z] := -1;
// Write faces and vertexes for each item of the map.
GenerateItemsMap(FMap);
FNumVertexes := 0;
for x := Low(FMap) to High(FMap) do
for y := Low(FMap[x]) to High(FMap[x]) do
for z := Low(FMap[x,y]) to High(FMap[x,y]) do
begin
if FMap[x,y,z] <> -1 then
begin
FItems[FMap[x,y,z]] := TVoxelModelizerItem.Create(PVoxelMap^,PSemiSurfacesMap^,FVertexMap,x,y,z,FNumVertexes,_Palette,_ColourMap);
end;
end;
// Get rid of FMap and create Model Map.
x := High(FMap);
while x >= 0 do
begin
y := High(FMap[x]);
while y >= 0 do
begin
SetLength(FMap[x,y],0);
dec(y);
end;
SetLength(FMap[x],0);
dec(x);
end;
SetLength(FMap,0);
// Confirm the vertex list.
SetLength(_Vertexes,FNumVertexes);
SetLength(Vertexes,FNumVertexes); // internal vertex list for future operations
for x := Low(FVertexMap) to High(FVertexMap) do
for y := Low(FVertexMap[x]) to High(FVertexMap[x]) do
for z := Low(FVertexMap[x,y]) to High(FVertexMap[x,y]) do
begin
if FVertexMap[x,y,z] <> -1 then
begin
_Vertexes[FVertexMap[x,y,z]].X := (x-1) / C_VP_HIGH;
_Vertexes[FVertexMap[x,y,z]].Y := (y-1) / C_VP_HIGH;
_Vertexes[FVertexMap[x,y,z]].Z := (z-1) / C_VP_HIGH;
Vertexes[FVertexMap[x,y,z]].X := x;
Vertexes[FVertexMap[x,y,z]].Y := y;
Vertexes[FVertexMap[x,y,z]].Z := z;
end;
end;
// Wipe the VertexMap.
x := High(FVertexMap);
while x >= 0 do
begin
y := High(FVertexMap[x]);
while y >= 0 do
begin
SetLength(FVertexMap[x,y],0);
dec(y);
end;
SetLength(FVertexMap[x],0);
dec(x);
end;
SetLength(FVertexMap,0);
// Paint the faces in the 3D Map.
ModelMap := T3DMap.Create(Size.X,Size.Y,Size.Z);
for i := Low(FItems) to High(FItems) do
begin
Face := FItems[i].Faces.GetFirstElement;
while Face <> nil do
begin
ModelMap.PaintFace(Vertexes[Face^.V1],Vertexes[Face^.V2],Vertexes[Face^.V3],1);
Face := Face^.Next;
end;
end;
// Classify the voxels from the 3D Map as in, out or surface.
ModelMap.GenerateSelfSurfaceMap;
// Check every face to ensure that it is in the surface. Cut the ones inside
// the volume.
NumFaces := 0;
for i := Low(FItems) to High(FItems) do
begin
Face := FItems[i].Faces.GetFirstElement;
while Face <> nil do
begin
// if ModelMap.IsFaceValid(Vertexes[Face^.V1],Vertexes[Face^.V2],Vertexes[Face^.V3],C_INSIDE_VOLUME) then
// begin
Face^.Location := NumFaces*3;
inc(NumFaces);
// end;
Face := Face^.Next;
end;
end;
// Generate the final faces array.
SetLength(_Faces,NumFaces*3);
SetLength(_Colours,NumFaces);
SetLength(_Normals,NumFaces);
for i := Low(FItems) to High(FItems) do
begin
Face := FItems[i].Faces.GetFirstElement;
while Face <> nil do
begin
if Face^.location > -1 then
begin
pos := Face^.location div 3;
// Calculate the normals from each face.
Normal := GetNormals(_Vertexes[Face^.V1],_Vertexes[Face^.V2],_Vertexes[Face^.V3]);
// Use 'raycasting' procedure to ensure that the vertexes are ordered correctly (anti-clockwise)
if not ModelMap.IsFaceNormalsCorrect(Vertexes[Face^.V1],Vertexes[Face^.V2],Vertexes[Face^.V3],Normal) then
begin
Normal := GetNormals(_Vertexes[Face^.V3],_Vertexes[Face^.V2],_Vertexes[Face^.V1]);
_Faces[Face^.location] := Face^.v3;
_Faces[Face^.location+1] := Face^.v2;
_Faces[Face^.location+2] := Face^.v1;
end
else
begin
_Faces[Face^.location] := Face^.v1;
_Faces[Face^.location+1] := Face^.v2;
_Faces[Face^.location+2] := Face^.v3;
end;
// Set normals value
_Normals[pos].X := Normal.X;
_Normals[pos].Y := Normal.Y;
_Normals[pos].Z := Normal.Z;
// Set a colour for each face.
_Colours[pos].X := FItems[i].Colour.X;
_Colours[pos].Y := FItems[i].Colour.Y;
_Colours[pos].Z := FItems[i].Colour.Z;
_Colours[pos].W := FItems[i].Colour.W;
end;
Face := Face^.Next;
end;
end;
// Free memory
ModelMap.Free;
SetLength(Vertexes,0);
end;
destructor TVoxelModelizer.Destroy;
var
x : integer;
begin
for x := Low(FItems) to High(FItems) do
begin
FItems[x].Free;
end;
SetLength(FItems,0);
inherited Destroy;
end;
procedure TVoxelModelizer.GenerateItemsMap(var FMap : T3DIntGrid);
var
x, y, z: integer;
NumItems : integer;
begin
NumItems := 0;
// Find out the regions where we will have meshes.
SetLength(FMap,PVoxelMap^.GetMaxX+1,PVoxelMap^.GetMaxY+1,PVoxelMap^.GetMaxZ+1);
for x := Low(FMap) to High(FMap) do
for y := Low(FMap[x]) to High(FMap[x]) do
for z := Low(FMap[x,y]) to High(FMap[x,y]) do
begin
if (PVoxelMap^.Map[x,y,z] > C_OUTSIDE_VOLUME) and (PVoxelMap^.Map[x,y,z] < C_INSIDE_VOLUME) then
begin
FMap[x,y,z] := NumItems;
inc(NumItems);
end
else
begin
FMap[x,y,z] := -1;
end;
end;
SetLength(FItems,NumItems);
end;
function TVoxelModelizer.GetNormals(_V1,_V2,_V3: TVector3f): TVector3f;
begin
Result.X := ((_V3.Y - _V2.Y) * (_V1.Z - _V2.Z)) - ((_V1.Y - _V2.Y) * (_V3.Z - _V2.Z));
Result.Y := ((_V3.Z - _V2.Z) * (_V1.X - _V2.X)) - ((_V1.Z - _V2.Z) * (_V3.X - _V2.X));
Result.Z := ((_V3.X - _V2.X) * (_V1.Y - _V2.Y)) - ((_V1.X - _V2.X) * (_V3.Y - _V2.Y));
end;
function TVoxelModelizer.CopyMap(const _Map: T3DIntGrid): T3DIntGrid;
var
x, y, z: integer;
begin
SetLength(Result,High(_Map)+1,High(_Map[0])+1,High(_Map[0,0])+1);
for x := Low(_Map) to High(_Map) do
for y := Low(_Map[0]) to High(_Map[0]) do
for z := Low(_Map[0,0]) to High(_Map[0,0]) do
begin
Result[x,y,z] := _Map[x,y,z];
end;
end;
end.
|
unit UDGlobalOptions;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, UCrpe32;
type
TCrpeGlobalOptionsDlg = class(TForm)
btnOk: TButton;
btnCancel: TButton;
btnClear: TButton;
pnlGlobalOptions: TPanel;
lblMorePrintEngineErrorMessages: TLabel;
lblMatchLogOnInfo: TLabel;
lblDisableThumbnailUpdates: TLabel;
lblUse70TextCompatibility: TLabel;
cbMorePrintEngineErrorMessages: TComboBox;
cbMatchLogOnInfo: TComboBox;
cbUse70TextCompatibility: TComboBox;
cbDisableThumbnailUpdates: TComboBox;
cbVerifyWhenDatabaseDriverUpgraded: TComboBox;
lblVerifyWhenDatabaseDriverUpgraded: TLabel;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure UpdateGlobalOptions;
procedure btnClearClick(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure InitializeControls(OnOff: boolean);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
end;
var
CrpeGlobalOptionsDlg : TCrpeGlobalOptionsDlg;
bGlobalOptions : boolean;
implementation
{$R *.DFM}
uses UCrpeUtl;
{------------------------------------------------------------------------------}
{ FormCreate procedure }
{------------------------------------------------------------------------------}
procedure TCrpeGlobalOptionsDlg.FormCreate(Sender: TObject);
begin
bGlobalOptions := True;
LoadFormPos(Self);
btnOk.Tag := 1;
btnCancel.Tag := 1;
btnClear.Tag := 1;
end;
{------------------------------------------------------------------------------}
{ FormShow procedure }
{------------------------------------------------------------------------------}
procedure TCrpeGlobalOptionsDlg.FormShow(Sender: TObject);
begin
UpdateGlobalOptions;
end;
{------------------------------------------------------------------------------}
{ UpdateGlobalOptions procedure }
{------------------------------------------------------------------------------}
procedure TCrpeGlobalOptionsDlg.UpdateGlobalOptions;
var
OnOff : Boolean;
begin
{Enable/Disable controls}
OnOff := not IsStrEmpty(Cr.ReportName);
InitializeControls(OnOff);
if OnOff then
begin
cbMorePrintEngineErrorMessages.ItemIndex := Ord(Cr.GlobalOptions.MorePrintEngineErrorMessages);
cbMatchLogOnInfo.ItemIndex := Ord(Cr.GlobalOptions.MatchLogOnInfo);
cbUse70TextCompatibility.ItemIndex := Ord(Cr.GlobalOptions.Use70TextCompatibility);
cbDisableThumbnailUpdates.ItemIndex := Ord(Cr.GlobalOptions.DisableThumbnailUpdates);
cbVerifyWhenDatabaseDriverUpgraded.ItemIndex := Ord(Cr.GlobalOptions.VerifyWhenDatabaseDriverUpgraded);
end;
end;
{------------------------------------------------------------------------------}
{ InitializeControls }
{------------------------------------------------------------------------------}
procedure TCrpeGlobalOptionsDlg.InitializeControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
if TComponent(Components[i]).Tag = 0 then
begin
if Components[i] is TButton then
TButton(Components[i]).Enabled := OnOff;
if Components[i] is TCheckBox then
TCheckBox(Components[i]).Enabled := OnOff;
if Components[i] is TComboBox then
TComboBox(Components[i]).Enabled := OnOff;
end;
end;
end;
{------------------------------------------------------------------------------}
{ btnClearClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeGlobalOptionsDlg.btnClearClick(Sender: TObject);
begin
Cr.GlobalOptions.Clear;
UpdateGlobalOptions;
end;
{------------------------------------------------------------------------------}
{ btnOKClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeGlobalOptionsDlg.btnOKClick(Sender: TObject);
begin
SaveFormPos(Self);
Cr.GlobalOptions.MorePrintEngineErrorMessages := TCrBoolean(cbMorePrintEngineErrorMessages.ItemIndex);
Cr.GlobalOptions.MatchLogOnInfo := TCrBoolean(cbMatchLogOnInfo.ItemIndex);
Cr.GlobalOptions.Use70TextCompatibility := TCrBoolean(cbUse70TextCompatibility.ItemIndex);
Cr.GlobalOptions.DisableThumbnailUpdates := TCrBoolean(cbDisableThumbnailUpdates.ItemIndex);
Cr.GlobalOptions.VerifyWhenDatabaseDriverUpgraded := TCrBoolean(cbVerifyWhenDatabaseDriverUpgraded.ItemIndex);
Close;
end;
{------------------------------------------------------------------------------}
{ btnCancelClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeGlobalOptionsDlg.btnCancelClick(Sender: TObject);
begin
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose procedure }
{------------------------------------------------------------------------------}
procedure TCrpeGlobalOptionsDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
bGlobalOptions := False;
Release;
end;
end.
|
unit nfsEditAutoComplete;
interface
uses
System.SysUtils, System.Classes, Vcl.Controls, Vcl.StdCtrls, Vcl.ExtCtrls;
type
TNfsOnGetListEvent = procedure(Sender: TObject; aList: TStrings) of object;
type
TnfsEditAutoComplete = class(TEdit)
private
_ListBox: TListBox;
_Timer: TTimer;
_SearchInterrupt: Integer;
_OnGetList: TNfsOnGetListEvent;
_SearchList: TStringList;
_SearchByLetters: Integer;
_MaxItems: Integer;
_CaseSensitive: Boolean;
procedure DoTimer(Sender: TObject);
procedure CMExit(var Message: TCMExit); message CM_EXIT;
procedure ListBoxKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure ListBoxKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure ListBoxDblClick(Sender: TObject);
procedure SetSearchInterrupt(const Value: Integer);
function getSearchWindowWidth: Integer;
procedure setSearchWindowWidth(const Value: Integer);
function getSearchWindowHeight: Integer;
procedure setSearchWindowHeight(const Value: Integer);
procedure DoFilterList;
protected
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure KeyUp(var Key: Word; Shift: TShiftState); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Loaded; override;
property SearchWindowWidth: Integer read getSearchWindowWidth write setSearchWindowWidth;
property SearchWindowHeight: Integer read getSearchWindowHeight write setSearchWindowHeight;
property SearchList: TStringList read _SearchList write _SearchList;
published
property OnGetList: TNfsOnGetListEvent read _OnGetList write _OnGetList;
property SearchInterrupt: Integer read _SearchInterrupt write SetSearchInterrupt;
property SearchByLetters: Integer read _SearchByLetters write _SearchByLetters;
property MaxItems: Integer read _MaxItems write _MaxItems;
property CaseSensitive: Boolean read _CaseSensitive write _CaseSensitive;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('New frontiers', [TnfsEditAutoComplete]);
end;
{ TnfsEditAutoComplete }
constructor TnfsEditAutoComplete.Create(AOwner: TComponent);
begin
inherited;
_ListBox := TListBox.Create(Self);
_ListBox.Visible := false;
_ListBox.OnKeyUp := ListBoxKeyUp;
_ListBox.OnKeyDown := ListBoxKeyDown;
_listBox.OnDblClick := ListBoxDblClick;
_ListBox.TabStop := false;
_Timer := TTimer.Create(Self);
_Timer.Enabled := false;
_Timer.OnTimer := DoTimer;
_SearchInterrupt := _Timer.Interval;
_SearchList := TStringList.Create;
_SearchList.Duplicates := dupIgnore;
_SearchList.Sorted := true;
_SearchByLetters := 1;
_MaxItems := 0;
AutoSelect := false;
_CaseSensitive := false;
end;
destructor TnfsEditAutoComplete.Destroy;
begin
FreeAndNil(_SearchList);
inherited;
end;
procedure TnfsEditAutoComplete.CMExit(var Message: TCMExit);
begin
if not _ListBox.Focused then
_ListBox.Visible := false;
end;
procedure TnfsEditAutoComplete.DoFilterList;
var
s: string;
i1: Integer;
Laenge: Integer;
begin
s := Text;
Laenge := Length(s);
_ListBox.Clear;
for i1 := 0 to _SearchList.Count -1 do
begin
if _CaseSensitive then
begin
if s = copy(_SearchList.Strings[i1], 1, Laenge) then
_ListBox.Items.Add(_SearchList.Strings[i1]);
end
else
begin
if SameText(s, copy(_SearchList.Strings[i1], 1, Laenge)) then
_ListBox.Items.Add(_SearchList.Strings[i1]);
end;
if (_MaxItems > 0) and (_ListBox.Items.Count >= _MaxItems) then
break;
end;
if _ListBox.Count = 1 then
begin
if SameText(Trim(Text), Trim(_ListBox.Items[0])) then
_ListBox.Clear; // Auswahlbox muss nicht angezeigt werden, wenn der einzige Eintrag mit dem im Editfeld gleich ist.
end;
_ListBox.Visible := _ListBox.Items.Count > 0;
end;
procedure TnfsEditAutoComplete.DoTimer(Sender: TObject);
var
Cur: TCursor;
begin
_Timer.Enabled := false;
_ListBox.Parent := Parent;
_ListBox.Left := Left;
_ListBox.Top := Top + Height;
Cur := Parent.Cursor;
Cursor := crHourGlass;
Parent.Cursor := crHourglass;
try
if _SearchList.Count > 0 then
begin
DoFilterList;
exit;
end;
if Assigned(_OnGetList) then
begin
_Listbox.Items.Clear;
_OnGetList(Self, _ListBox.Items);
if _ListBox.Count = 1 then
begin
if SameText(Trim(Text), Trim(_ListBox.Items[0])) then
_ListBox.Clear; // Auswahlbox muss nicht angezeigt werden, wenn der einzige Eintrag mit dem im Editfeld gleich ist.
end;
_ListBox.Visible := _ListBox.Items.Count > 0;
end;
finally
Cursor := crDefault;
Parent.Cursor := Cur;
end;
end;
function TnfsEditAutoComplete.getSearchWindowHeight: Integer;
begin
Result := _ListBox.Height;
end;
function TnfsEditAutoComplete.getSearchWindowWidth: Integer;
begin
Result := _ListBox.Width;
end;
procedure TnfsEditAutoComplete.KeyDown(var Key: Word; Shift: TShiftState);
begin
inherited;
_Timer.Enabled := false;
end;
procedure TnfsEditAutoComplete.KeyUp(var Key: Word; Shift: TShiftState);
begin
inherited;
if Key = 40 then
begin
_ListBox.SetFocus;
if _ListBox.Items.Count > 0 then
_ListBox.ItemIndex := 0;
exit;
end;
if (((Key >= 35) and (Key <=39)) or (Key = 9)) then
exit;
if Length(Text) < _SearchByLetters then
begin
_ListBox.Visible := false;
exit;
end;
_Timer.Enabled := true;
end;
procedure TnfsEditAutoComplete.ListBoxDblClick(Sender: TObject);
begin
Text := _ListBox.Items[_ListBox.ItemIndex];
_ListBox.Visible := false;
SetFocus;
end;
procedure TnfsEditAutoComplete.ListBoxKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Key = 38) and (_ListBox.ItemIndex = 0) then
begin
SetFocus;
_ListBox.ItemIndex := -1;
end;
SelStart := Length(Text);
end;
procedure TnfsEditAutoComplete.ListBoxKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if _ListBox.ItemIndex < 0 then
exit;
if Key <> 13 then
exit;
Text := _ListBox.Items[_ListBox.ItemIndex];
_ListBox.Visible := false;
SetFocus;
SelStart := Length(Text);
end;
procedure TnfsEditAutoComplete.Loaded;
begin
inherited;
_ListBox.Width := Width;
end;
procedure TnfsEditAutoComplete.SetSearchInterrupt(const Value: Integer);
begin
_SearchInterrupt := Value;
_Timer.Interval := Value;
end;
procedure TnfsEditAutoComplete.setSearchWindowHeight(const Value: Integer);
begin
_ListBox.Height := Value;
end;
procedure TnfsEditAutoComplete.setSearchWindowWidth(const Value: Integer);
begin
_Listbox.Width := Value;
end;
end.
|
{*******************************************************}
{ }
{ Cards (Desktop client) }
{ }
{ Copyright (c) 2015 - 2019 Sergey Lubkov }
{ }
{*******************************************************}
unit Cards.GridHelper;
interface
uses
Vcl.Forms, System.Classes, System.SysUtils, Vcl.Dialogs, Generics.Collections,
cxGrid, cxGridExportLink, cxGridTableView;
type
TIdentities = class(TPersistent)
private
FValues: TList<Integer>;
public
property Values: TList<Integer> read FValues;
public
constructor Create(); overload;
constructor Create(const Grid: TcxGridTableView; const ColumnIndex: Integer); overload;
destructor Destroy; override;
procedure Add(const Key: Variant);
procedure Clear();
function Count(): Integer;
procedure Delete(const Index: Integer);
function GetAt(const Index: Integer): Integer;
function GetCommaText(): string;
end;
TcxGridHelper = class
public
{Сохранить грид в Excel}
class procedure SaveToExcel(const FileName: string; const Grid: TcxGrid);
end;
implementation
uses
uServiceUtils;
{ TIdentities }
constructor TIdentities.Create;
begin
inherited Create();
FValues := TList<Integer>.Create;
end;
constructor TIdentities.Create(const Grid: TcxGridTableView; const ColumnIndex: Integer);
var
i: Integer;
begin
Create();
Grid.BeginUpdate;
try
for i := 0 to Grid.Controller.SelectedRowCount - 1 do
Add(Grid.Controller.SelectedRows[i].Values[ColumnIndex]);
finally
Grid.EndUpdate;
end;
end;
destructor TIdentities.Destroy;
begin
FValues.Clear;
FValues.Free;
inherited;
end;
procedure TIdentities.Add(const Key: Variant);
begin
if not IsNullID(Key) then
FValues.Add(Key);
end;
function TIdentities.Count: Integer;
begin
Result := FValues.Count;
end;
procedure TIdentities.Clear;
begin
FValues.Clear;
end;
procedure TIdentities.Delete(const Index: Integer);
begin
FValues.Delete(Index);
end;
function TIdentities.GetAt(const Index: Integer): Integer;
begin
Result := FValues[Index];
end;
function TIdentities.GetCommaText: String;
var
i: Integer;
begin
Result := '';
for i := 0 to FValues.Count - 1 do
begin
if (i > 0) then
Result := Result + ',';
Result := Result + IntToStr(FValues[i]);
end;
end;
{ TGridHelper }
class procedure TcxGridHelper.SaveToExcel(const FileName: string; const Grid: TcxGrid);
var
Dialog: TSaveDialog;
begin
Dialog := TSaveDialog.Create(Application);
try
Dialog.DefaultExt := 'xls';
Dialog.Filter := 'Excel files|*.xls';
Dialog.FileName := FileName;
if Dialog.Execute then
begin
ExportGridToExcel(Dialog.FileName, Grid, True, True, True);
if FileExists(Dialog.FileName) then
MessageDlg('Данные таблицы успешно сохранены в файл', mtInformation, [mbOK], 0);
end;
finally
Dialog.Free;
end;
end;
end.
|
unit Action.ImportFromWebService;
interface
uses
System.JSON,
System.Variants,
System.Classes,
System.SysUtils,
ExtGUI.ListBox.Books,
Data.Main,
Model.Book;
type
TImportFromWebService = class(TComponent)
private
FBooksConfig: TBooksListBoxConfigurator;
FDataModMain: TDataModMain;
FOnAfterExecute: TProc;
FTagString: string;
procedure SetBooksConfig(const Value: TBooksListBoxConfigurator);
procedure SetDataModMain(const Value: TDataModMain);
procedure SetOnAfterExecute(const Value: TProc);
procedure SetTagString(const Value: string);
procedure ImportBooks;
procedure ImportReaderReports;
procedure AddNewBookToDataModuleFromWeb(jsBooks: TJSONArray);
public
property BooksConfig: TBooksListBoxConfigurator read FBooksConfig
write SetBooksConfig;
property DataModMain: TDataModMain read FDataModMain write SetDataModMain;
property OnAfterExecute: TProc read FOnAfterExecute write SetOnAfterExecute;
procedure Execute;
end;
function BooksToDateTime(const s: string): TDateTime;
implementation
uses
Vcl.Forms,
Vcl.DBGrids,
Data.DB,
Frame.Import,
ClientAPI.Books, ClientAPI.Readers,
Helper.TJSONObject, Helper.DataSet, Helper.TApplication, Helper.Variant,
Utils.General, Model.ReaderReport, Messaging.EventBus, Consts.Application;
function BooksToDateTime(const s: string): TDateTime;
const
months: array [1 .. 12] of string = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
var
m: string;
Y: string;
i: Integer;
mm: Integer;
yy: Integer;
begin
m := s.Substring(0, 3);
Y := s.Substring(4);
mm := 0;
for i := 1 to 12 do
if months[i].ToUpper = m.ToUpper then
mm := i;
if mm = 0 then
raise ERangeError.Create('Incorect mont name in the date: ' + s);
yy := Y.ToInteger();
Result := EncodeDate(yy, mm, 1);
end;
const
Client_API_Token = '20be805d-9cea27e2-a588efc5-1fceb84d-9fb4b67c';
{ TImportFormWebService }
procedure TImportFromWebService.Execute;
begin
ImportBooks;
ImportReaderReports;
end;
procedure TImportFromWebService.ImportBooks;
var
jsBooks: TJSONArray;
begin
jsBooks := ImportBooksFromWebService(Client_API_Token);
try
AddNewBookToDataModuleFromWeb(jsBooks);
finally
jsBooks.Free;
end;
end;
procedure TImportFromWebService.AddNewBookToDataModuleFromWeb
(jsBooks: TJSONArray);
var
jsBook: TJSONObject;
b: TBook;
b2: TBook;
i: Integer;
begin
for i := 0 to jsBooks.Count - 1 do
begin
jsBook := jsBooks.Items[i] as TJSONObject;
b := TBook.Create();
// TODO: DodaŠ try-finnaly oraz zwalanie b.Free;
// czyli b przekazywane do InsertNewBook musi byŠ sklonowane
b.LoadFromJSON (jsBook);
b.Validate;
b2 := FBooksConfig.GetBookList(blkAll).FindByISBN(b.isbn);
if not Assigned(b2) then
begin
FBooksConfig.InsertNewBook(b);
// ----------------------------------------------------------------
// Append report into the database:
// Fields: ISBN, Title, Authors, Status, ReleseDate, Pages, Price,
// Currency, Imported, Description
DataModMain.dsBooks.InsertRecord([b.isbn, b.title, b.author, b.status,
b.releseDate, b.pages, b.price, b.currency, b.imported, b.description]);
end
else
b.Free;
end;
end;
procedure TImportFromWebService.ImportReaderReports;
var
jsData: TJSONArray;
I: Integer;
ReaderReport: TReaderReport;
Book: TBook;
Ratings: array of string;
ReaderId: Variant;
AMessage: TEventMessage;
begin
jsData := ImportReaderReportsFromWebService(Client_API_Token);
try
for i := 0 to jsData.Count - 1 do
begin
// ----------------------------------------------------
// Validate ReadeReport (JSON) and insert into the Database
// Read JSON object
ReaderReport := TReaderReport.Create;
try
ReaderReport.LoadFromJSON(jsData.Items[i] as TJSONObject);
Book := FBooksConfig.GetBookList(blkAll).FindByISBN(ReaderReport.BookISBN);
if Assigned(Book) then
begin
ReaderId := DataModMain.FindReaderByEmil(ReaderReport.Email);
if ReaderId.IsNull then
begin
ReaderId := DataModMain.dsReaders.GetMaxValue('ReaderId') + 1;
// Fields: ReaderId, FirstName, LastName, Email, Company, BooksRead,
// LastReport, ReadersCreated
DataModMain.dsReaders.AppendRecord([ReaderId, ReaderReport.FirstName,
ReaderReport.LastName, ReaderReport.Email, ReaderReport.Company, 1,
ReaderReport.ReportedDate, Now()]);
end;
// Append report into the database:
// Fields: ReaderId, ISBN, Rating, Oppinion, Reported
DataModMain.dsReports.AppendRecord([ReaderId, ReaderReport.BookISBN,
ReaderReport.Rating, ReaderReport.Oppinion,
ReaderReport.ReportedDate]);
// ----------------------------------------------------------------
if Application.IsDeveloperMode then
Insert([ReaderReport.Rating.ToString], Ratings, maxInt);
end
else
raise Exception.Create('Invalid book isbn');
finally
ReaderReport.Free;
end;
end;
if Application.IsDeveloperMode then
begin
AMessage.TagString := string.Join(' ,', Ratings);
TEventBus._Post (EB_ImportReaderReports_LogInfo, AMessage);
if Assigned(FOnAfterExecute) then
FOnAfterExecute();
end;
finally
jsData.Free;
end;
end;
procedure TImportFromWebService.SetBooksConfig(const Value: TBooksListBoxConfigurator);
begin
FBooksConfig := Value;
end;
procedure TImportFromWebService.SetDataModMain(const Value: TDataModMain);
begin
FDataModMain := Value;
end;
procedure TImportFromWebService.SetOnAfterExecute(const Value: TProc);
begin
FOnAfterExecute := Value;
end;
procedure TImportFromWebService.SetTagString(const Value: String);
begin
FTagString := Value;
end;
end.
|
unit Main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls;
type
TForm1 = class(TForm)
edStringA: TEdit;
edStringB: TEdit;
pbXOR: TButton;
reReport: TRichEdit;
Label1: TLabel;
Label2: TLabel;
pbClose: TButton;
procedure FormCreate(Sender: TObject);
procedure pbXORClick(Sender: TObject);
procedure pbCloseClick(Sender: TObject);
procedure FormResize(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
SDUGeneral;
procedure TForm1.FormCreate(Sender: TObject);
begin
self.caption := Application.title;
reReport.Lines.clear();
edStringA.Text := '';
edStringB.Text := '';
end;
procedure TForm1.pbXORClick(Sender: TObject);
var
output: string;
prettyOutput: TStringList;
begin
output := SDUXOR(edStringA.Text, edStringB.Text);
prettyOutput := TStringList.Create();
try
reReport.lines.Add('String A:');
prettyOutput.clear();
SDUPrettyPrintHex(edStringA.Text, 0, length(edStringA.Text), prettyOutput);
reReport.lines.AddStrings(prettyOutput);
reReport.lines.Add('');
reReport.lines.Add('String B:');
prettyOutput.clear();
SDUPrettyPrintHex(edStringB.Text, 0, length(edStringB.Text), prettyOutput);
reReport.lines.AddStrings(prettyOutput);
reReport.lines.Add('');
reReport.lines.Add('String A XOR String B:');
prettyOutput.clear();
SDUPrettyPrintHex(output, 0, length(output), prettyOutput);
reReport.lines.AddStrings(prettyOutput);
reReport.lines.Add('');
reReport.lines.Add('-----------------------------------------');
finally
prettyOutput.Free();
end;
end;
procedure TForm1.pbCloseClick(Sender: TObject);
begin
Close();
end;
procedure TForm1.FormResize(Sender: TObject);
begin
SDUCenterControl(pbXOR, ccHorizontal);
end;
END.
|
Program Pixeles;
Const
Tope = 3;
Type
TM = array[1..100,1..100] of byte;
TV = array[1..10] of char;
TVC = array[0..Tope] of word;
Procedure LeerArchivo(Var Mat:TM; Var V:TV; Var N,M:byte);
Var
i,j:byte;
arch:text;
begin
assign(arch,'Pixeles.txt');reset(arch);
readln(arch,N,M);
For i:= 1 to N do
begin
read(arch,V[i]);
For j:= 1 to M do
read(arch,Mat[i,j]);
readln(arch);
end;
close(arch);
end;
Function Promedio(Mat:TM; N,M:byte):real; //Calcula el promedio entre 39 (cantidad total de pixeles) y 24 (cantidad de espacios de la matriz) -> 39/24 = 1.63 .
Var
i,j:byte;
Acum:word;
begin
Acum:= 0;
For i:= 1 to N do
begin
For j:= 1 to M do
Acum:= Acum + Mat[i,j];
end;
Promedio:= Acum / (N*M);
end;
Function MaximaFila(Mat:TM; V:TV; N,M:byte; Color:char):byte;
Var
i,j,MaxFila:byte;
Acum,Max:word;
begin
Max:= 0;
MaxFila:= 0;
For i:= 1 to N do
begin
Acum:= 0;
For j:= 1 to M do
Acum:= Acum + Mat[i,j];
If (V[i] = Color) then
If (Acum > Max) then
begin
Max:= Acum;
MaxFila:= i;
end;
end;
MaximaFila:= MaxFila;
end;
{Procedure MaximaFilaColor(Mat:TM; V:TV; N,M:byte; Color:char); //SIN MENU
Var
MaxFila:byte;
begin
MaxFila:= MaximaFila(Mat,V,N,M,Color);
If (MaxFila > 0) then
writeln('Color ',Color,' mayor intensidad en la fila ',MaxFila)
Else
writeln('No existe el color ingresado');
end; }
Procedure MaximaFilaColor(Mat:TM; V:TV; N,M:byte; Color:char); //CON MENU
Var
MaxFila:byte;
begin
write('Ingrese un color R / A / V / N : ');readln(Color);
MaxFila:= MaximaFila(Mat,V,N,M,Color);
If (MaxFila > 0) then
writeln('Color ',Color,' mayor intensidad en la fila ',MaxFila)
Else
writeln('No existe el color ingresado');
end;
Procedure Tonos(Mat:TM; N,M:byte; Var Cont:TVC); // Acumula y muestra la cantidad de elementos de cada Tono (0,1,2,3).
Var
i,j:byte;
begin
For i:= 1 to N do
begin
For j:= 1 to M do
Cont[Mat[i,j]]:= Cont[Mat[i,j]] + 1;
end;
For i:= 0 to Tope do
writeln('Tono ',i, ' Cantidad de pixeles: ',Cont[i]);
end;
Procedure Menu(Var Op:char);
begin
writeln;
writeln('Menu');
writeln('1 - Promedio de pixeles');
writeln('2 - Saber cual color tiene mas pixeles en una fila');
writeln('3 - Cantidad de pixeles por tono (0,1,2,3)');
writeln('4 - Salir');
writeln;
write('Ingrese una opcion: ');readln(Op);
end;
Var
Mat:TM;
V:TV;
Cont:TVC;
Color,Op:char;
N,M:byte;
Begin
LeerArchivo(Mat,V,N,M);
{writeln; //SIN MENU
Tonos(Mat,N,M,Cont);
writeln('Promedio:',Promedio(Mat,N,M):6:2);
writeln;
write('Ingrese un color R / A / V / N : ');readln(Color);
writeln;
MaximaFilaColor(Mat,V,N,M,Color);
writeln;
Tonos(Mat,N,M,Cont); }
Repeat // CON MENU
Menu(Op);
Case Op of
'1':writeln('Promedio:',Promedio(Mat,N,M):6:2);
'2':MaximaFilaColor(Mat,V,N,M,Color);
'3':Tonos(Mat,N,M,Cont);
end;
Until (Op = '4');
end.
|
{*
FtermSSH : An SSH implementation in Delphi for FTerm2 by kxn@cic.tsinghua.edu.cn
Cryptograpical code from OpenSSL Project
*}
unit sshconst;
interface
const
SSH_CIPHER_SSH2 = -3;
SSH_CIPHER_ILLEGAL = -2;
SSH_CIPHER_NOT_SET = -1;
SSH_CIPHER_NONE = 0;
SSH_CIPHER_IDEA = 1;
SSH_CIPHER_DES = 2;
SSH_CIPHER_3DES = 3;
SSH_CIPHER_BROKEN_TSS = 4;
SSH_CIPHER_BROKEN_RC4 = 5;
SSH_CIPHER_BLOWFISH = 6;
SSH_CIPHER_RESERVED = 7;
SSH_CIPHER_MAX = 31;
SSH1_MSG_DISCONNECT = 1;
SSH1_SMSG_PUBLIC_KEY = 2;
SSH1_CMSG_SESSION_KEY = 3;
SSH1_CMSG_USER = 4;
SSH1_CMSG_AUTH_RSA = 6;
SSH1_SMSG_AUTH_RSA_CHALLENGE = 7;
SSH1_CMSG_AUTH_RSA_RESPONSE = 8;
SSH1_CMSG_AUTH_PASSWORD = 9;
SSH1_CMSG_REQUEST_PTY = 10;
SSH1_CMSG_WINDOW_SIZE = 11;
SSH1_CMSG_EXEC_SHELL = 12;
SSH1_CMSG_EXEC_CMD = 13;
SSH1_SMSG_SUCCESS = 14;
SSH1_SMSG_FAILURE = 15;
SSH1_CMSG_STDIN_DATA = 16;
SSH1_SMSG_STDOUT_DATA = 17;
SSH1_SMSG_STDERR_DATA = 18;
SSH1_CMSG_EOF = 19;
SSH1_SMSG_EXIT_STATUS = 20;
SSH1_MSG_CHANNEL_OPEN_CONFIRMATION = 21;
SSH1_MSG_CHANNEL_OPEN_FAILURE = 22;
SSH1_MSG_CHANNEL_DATA = 23;
SSH1_MSG_CHANNEL_CLOSE = 24;
SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION = 25;
SSH1_SMSG_X11_OPEN = 27;
SSH1_CMSG_PORT_FORWARD_REQUEST = 28;
SSH1_MSG_PORT_OPEN = 29;
SSH1_CMSG_AGENT_REQUEST_FORWARDING = 30;
SSH1_SMSG_AGENT_OPEN = 31;
SSH1_MSG_IGNORE = 32;
SSH1_CMSG_EXIT_CONFIRMATION = 33;
SSH1_CMSG_X11_REQUEST_FORWARDING = 34;
SSH1_CMSG_AUTH_RHOSTS_RSA = 35;
SSH1_MSG_DEBUG = 36;
SSH1_CMSG_REQUEST_COMPRESSION = 37;
SSH1_CMSG_AUTH_TIS = 39;
SSH1_SMSG_AUTH_TIS_CHALLENGE = 40;
SSH1_CMSG_AUTH_TIS_RESPONSE = 41;
SSH1_CMSG_AUTH_CCARD = 70;
SSH1_SMSG_AUTH_CCARD_CHALLENGE = 71;
SSH1_CMSG_AUTH_CCARD_RESPONSE = 72;
SSH1_AUTH_TIS = 5;
SSH1_AUTH_CCARD = 16;
SSH1_PROTOFLAG_SCREEN_NUMBER = 1;
SSH1_PROTOFLAGS_SUPPORTED = 0;
SSH2_MSG_DISCONNECT = 1;
SSH2_MSG_IGNORE = 2;
SSH2_MSG_UNIMPLEMENTED = 3;
SSH2_MSG_DEBUG = 4;
SSH2_MSG_SERVICE_REQUEST = 5;
SSH2_MSG_SERVICE_ACCEPT = 6;
SSH2_MSG_KEXINIT = 20;
SSH2_MSG_NEWKEYS = 21;
SSH2_MSG_KEXDH_INIT = 30;
SSH2_MSG_KEXDH_REPLY = 31;
SSH2_MSG_KEX_DH_GEX_REQUEST_OLD = 30;
SSH2_MSG_KEX_DH_GEX_GROUP = 31;
SSH2_MSG_KEX_DH_GEX_INIT = 32;
SSH2_MSG_KEX_DH_GEX_REPLY = 33;
SSH2_MSG_KEX_DH_GEX_REQUEST = 34;
SSH2_MSG_USERAUTH_REQUEST = 50;
SSH2_MSG_USERAUTH_FAILURE = 51;
SSH2_MSG_USERAUTH_SUCCESS = 52;
SSH2_MSG_USERAUTH_BANNER = 53;
SSH2_MSG_USERAUTH_PK_OK = 60;
SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ = 60;
SSH2_MSG_USERAUTH_INFO_REQUEST = 60;
SSH2_MSG_USERAUTH_INFO_RESPONSE = 61;
SSH2_MSG_GLOBAL_REQUEST = 80;
SSH2_MSG_REQUEST_SUCCESS = 81;
SSH2_MSG_REQUEST_FAILURE = 82;
SSH2_MSG_CHANNEL_OPEN = 90;
SSH2_MSG_CHANNEL_OPEN_CONFIRMATION = 91;
SSH2_MSG_CHANNEL_OPEN_FAILURE = 92;
SSH2_MSG_CHANNEL_WINDOW_ADJUST = 93;
SSH2_MSG_CHANNEL_DATA = 94;
SSH2_MSG_CHANNEL_EXTENDED_DATA = 95;
SSH2_MSG_CHANNEL_EOF = 96;
SSH2_MSG_CHANNEL_CLOSE = 97;
SSH2_MSG_CHANNEL_REQUEST = 98;
SSH2_MSG_CHANNEL_SUCCESS = 99;
SSH2_MSG_CHANNEL_FAILURE = 100;
SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT = 1;
SSH2_DISCONNECT_PROTOCOL_ERROR = 2;
SSH2_DISCONNECT_KEY_EXCHANGE_FAILED = 3;
SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED = 4;
SSH2_DISCONNECT_RESERVED = 4;
SSH2_DISCONNECT_MAC_ERROR = 5;
SSH2_DISCONNECT_COMPRESSION_ERROR = 6;
SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE = 7;
SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED = 8;
SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE = 9;
SSH2_DISCONNECT_CONNECTION_LOST = 10;
SSH2_DISCONNECT_BY_APPLICATION = 11;
SSH2_DISCONNECT_TOO_MANY_CONNECTIONS = 12;
SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER = 13;
SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE = 14;
SSH2_DISCONNECT_ILLEGAL_USER_NAME = 15;
SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED = 1;
SSH2_OPEN_CONNECT_FAILED = 2;
SSH2_OPEN_UNKNOWN_CHANNEL_TYPE = 3;
SSH2_OPEN_RESOURCE_SHORTAGE = 4;
SSH2_EXTENDED_DATA_STDERR = 1;
implementation
end.
|
unit gr_CountCurrent_MainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLabel, cxSplitter, cxControls, cxContainer, cxEdit,
cxTextEdit, cxMemo, cxMaskEdit, cxDBEdit, Gauges, ExtCtrls,
gr_uCommonProc, gr_uCommonConsts, gr_uMessage,
iBase, gr_uThread, dxBar, dxBarExtItems, FIBQuery,
pFIBQuery, pFIBStoredProc, FIBDatabase, pFIBDatabase, cxCheckBox, ZProc,
PackageLoad;
type
TFCountCurrent = class(TForm)
cxMemo1: TcxMemo;
BarManager: TdxBarManager;
BarProgressItem: TdxBarProgressItem;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ExitBtnClick(Sender: TObject);
procedure ThreadCountEnd(Sender:TObject);
procedure FormShow(Sender: TObject);
private
pLanguageIndex:Byte;
pDBHandle:TISC_DB_HANDLE;
pThreadCount:TgrThreadStProc;
pThreadTimer:TgrThreadTimer;
public
constructor Create(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE);reintroduce;
end;
implementation
{$R *.dfm}
constructor TFCountCurrent.Create(AOwner:TComponent;ADB_Handle:TISC_DB_HANDLE);
begin
inherited Create(AOwner);
pDBHandle:=ADB_Handle;
pLanguageIndex := IndexLanguage;
//------------------------------------------------------------------------------
Caption := AllCount_Text[PLanguageIndex];
BarProgressItem.Caption:=LabelProgress_Caption[pLanguageIndex];
BarProgressItem.Hint:=LabelProgress_Caption[pLanguageIndex];
//------------------------------------------------------------------------------
cxMemo1.Text := '';
SetOptionsBarManager(BarManager);
end;
procedure TFCountCurrent.FormClose(Sender: TObject;var Action: TCloseAction);
begin
if (pThreadTimer<>nil)
then Action:=caNone
else Action:=caFree;
end;
procedure TFCountCurrent.ExitBtnClick(Sender: TObject);
begin
Close;
end;
procedure TFCountCurrent.ThreadCountEnd(Sender:TObject);
begin
pThreadCount := nil;
pThreadTimer.Terminate;
pThreadTimer.Destroy;
pThreadTimer:=nil;
if grShowMessage('Фором. відомостей','Сформувати відомості?',mtConfirmation,[mbOk,mbCancel])=mrOk then
uvFormSheet(self,pDBHandle,13,null);
Close;
end;
procedure TFCountCurrent.FormShow(Sender: TObject);
begin
grSetBeginAction(pDBHandle,13);
pThreadTimer := TgrThreadTimer.Create;
pThreadTimer.dxProgressBar := BarProgressItem;
BarProgressItem.Caption := PrepareDataContinue_Text[PLanguageIndex];
pThreadTimer.Resume;
pThreadCount := TgrThreadStProc.Create;
pThreadCount.DB_Handle := pDBHandle;
pThreadCount.StProcName := 'GR_COUNT_CURRENT';
pThreadCount.FreeOnTerminate:=True;
pThreadCount.EndThreadFunction := ThreadCountEnd;
pThreadCount.Resume;
grSetEndAction(pDBHandle,'T');
end;
end.
|
unit AddVerssion;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxLabel, StdCtrls, cxButtons, cxControls,
cxContainer, cxEdit, cxTextEdit, ExtCtrls, cxCheckBox, cnConsts_Messages, cnConsts,
ActnList, cn_Common_Messages;
type
TfrmAddVerssion = class(TForm)
Panel2: TPanel;
Panel1: TPanel;
EditNameVerssion: TcxTextEdit;
Ok_Button: TcxButton;
Cancel_Button: TcxButton;
LPriceVerssionName: TcxLabel;
chbActual: TcxCheckBox;
ActionList1: TActionList;
act_ok: TAction;
cancel: TAction;
procedure FormCreate(Sender: TObject);
constructor Create( AOwner:TComponent; LangIndex: Integer);overload;
procedure act_okExecute(Sender: TObject);
procedure cancelExecute(Sender: TObject);
procedure FormShow(Sender: TObject);
private
public
PLanguageIndex: Integer;
end;
var
frmAddVerssion: TfrmAddVerssion;
implementation
{$R *.dfm}
constructor TfrmAddVerssion.Create( AOwner:TComponent; LangIndex: Integer);
begin
inherited Create(AOwner);
PLanguageIndex:=LangIndex;
end;
procedure TfrmAddVerssion.FormCreate(Sender: TObject);
begin
Ok_Button.Caption := cn_Accept[PLanguageIndex];
Ok_Button.Hint := cn_Accept[PLanguageIndex];
Cancel_Button.Caption := cn_cancel[PLanguageIndex];
Cancel_Button.Hint := cn_cancel[PLanguageIndex];
LPriceVerssionName.Caption := cnConsts.cn_grid_ADDVerName[PLanguageIndex];
chbActual.Properties.Caption:= cnConsts.cn_grid_Actual[PLanguageIndex];
end;
procedure TfrmAddVerssion.FormShow(Sender: TObject);
begin
EditNameVerssion.SetFocus;
end;
procedure TfrmAddVerssion.act_okExecute(Sender: TObject);
begin
if EditNameVerssion.Text<>'' then ModalResult:=mrOk
else cnShowMessage(cnConsts.cn_Confirmation_Caption[PLanguageIndex], cnConsts_Messages.cn_Some_Need[PLanguageIndex], mtConfirmation, [mbOK]);
end;
procedure TfrmAddVerssion.cancelExecute(Sender: TObject);
begin
Close;
end;
end.
|
unit uSubInvAccessory;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uParentSub, siComp, siLangRT, DB, ADODB, StdCtrls, DBCtrls,
ExtCtrls, dbcgrids;
type
TSubInvAccessory = class(TParentSub)
quAccessory: TADOQuery;
quAccessoryIDInvAccessory: TIntegerField;
quAccessoryIDModel: TIntegerField;
quAccessoryModel: TStringField;
dsAccessory: TDataSource;
quAccessoryHint: TStringField;
quAccessoryLargeImage: TStringField;
quAccessorySellingPrice: TBCDField;
quAccessoryf: TIntegerField;
gridSuggestion: TDBCtrlGrid;
DBText1: TDBText;
DBText2: TDBText;
lblTitle: TLabel;
quAccessoryTotQtyOnHand: TFloatField;
procedure quAccessoryAfterOpen(DataSet: TDataSet);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
fIDModel : Integer;
sNoRecs,
sRec : String;
protected
procedure AfterSetParam; override;
public
{ Public declarations }
procedure DataSetRefresh;
procedure DataSetOpen; override;
procedure DataSetClose; override;
end;
implementation
uses uDM, uDMGlobal, uParamFunctions, DBTables;
{$R *.dfm}
{ TSubInvAccessory }
procedure TSubInvAccessory.AfterSetParam;
begin
inherited;
if FParam = '' then
Exit;
fIDModel := StrToIntDef(ParseParam(FParam, 'IDModel'),0);
DataSetRefresh;
end;
procedure TSubInvAccessory.DataSetClose;
begin
inherited;
with quAccessory do
if Active then
Close;
end;
procedure TSubInvAccessory.DataSetOpen;
begin
inherited;
with quAccessory do
if not Active then
begin
Parameters.ParamByName('IDModel').Value := fIDModel;
Open;
end;
end;
procedure TSubInvAccessory.DataSetRefresh;
begin
DataSetClose;
DataSetOpen;
end;
procedure TSubInvAccessory.quAccessoryAfterOpen(DataSet: TDataSet);
begin
inherited;
if DataSet.RecordCount = 0 then
begin
lblTitle.Caption := sNoRecs;
gridSuggestion.Visible := False;
end
else
begin
lblTitle.Caption := Format(sRec, [DataSet.RecordCount]);
gridSuggestion.Visible := True;
end;
end;
procedure TSubInvAccessory.FormCreate(Sender: TObject);
begin
inherited;
Case DMGlobal.IDLanguage of
LANG_ENGLISH :
begin
sNoRecs := 'No suggestion';
sRec := 'There are (%D) Suggestions';
end;
LANG_PORTUGUESE :
begin
sNoRecs := 'Sem sugestão de vendas';
sRec := 'Existem (%D) Sugestão de vendas';
end;
LANG_SPANISH :
begin
sNoRecs := 'No Sugerencias';
sRec := 'Existem (%D) sugerencia de ventas';
end;
end;
end;
initialization
RegisterClass(TSubInvAccessory);
end.
|
unit _uInvalidFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxEdit, DB, cxDBData, cxGridTableView, cxGridLevel,
cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView,
cxGridDBTableView, cxGrid, _uInvalidDataModule, Buttons, ExtCtrls,
ActnList, cxTextEdit, FIBDataSet, pFIBDataSet;
type
T_fmPCardInvalidPage = class(TFrame)
InvalidGrid: TcxGrid;
InvalidView: TcxGridDBTableView;
InvalidGridLevel1: TcxGridLevel;
StyleRepository: TcxStyleRepository;
InvalidViewNAME_invalid: TcxGridDBColumn;
InvalidViewDATE_BEG: TcxGridDBColumn;
InvalidViewDATE_END: TcxGridDBColumn;
Panel11: TPanel;
SB_AddInvalid: TSpeedButton;
SB_DelInvalid: TSpeedButton;
SB_ModifInvalid: TSpeedButton;
ALInvalid: TActionList;
AddInvalidA: TAction;
ModifInvalidA: TAction;
DelInvalidA: TAction;
ShowInformation: TAction;
cxStyle1: TcxStyle;
cxStyle2: TcxStyle;
cxStyle3: TcxStyle;
cxStyle4: TcxStyle;
cxStyle5: TcxStyle;
cxStyle6: TcxStyle;
cxStyle7: TcxStyle;
cxStyle8: TcxStyle;
cxStyle9: TcxStyle;
cxStyle10: TcxStyle;
cxStyle11: TcxStyle;
cxStyle12: TcxStyle;
cxStyle13: TcxStyle;
cxStyle14: TcxStyle;
cxGridTableViewStyleSheet1: TcxGridTableViewStyleSheet;
SpHistInvalid: TSpeedButton;
InvSet: TpFIBDataSet;
InvalidViewDBColumn1: TcxGridDBColumn;
procedure AddInvalidAExecute(Sender: TObject);
procedure ModifInvalidAExecute(Sender: TObject);
procedure DelInvalidAExecute(Sender: TObject);
procedure InvalidViewKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FrameEnter(Sender: TObject);
procedure FrameExit(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
private
{ Private declarations }
public
DM: T_dmInvalid;
id_pcard: integer;
constructor Create(AOwner: TComponent; DMod: T_dmInvalid; Id_PC: Integer; modify: integer); reintroduce;
end;
implementation
uses _uInvalidAdd, BaseTypes, _uInvalidHistory;
{$R *.dfm}
constructor T_fmPCardInvalidPage.Create(AOwner: TComponent; DMod: T_dmInvalid; Id_PC: Integer; modify: integer);
begin
inherited Create(AOwner);
DM := Dmod; id_pcard := Id_PC;
DM.InvalidSelect.ParamByName('Id_PCard').AsInteger := Id_PCard;
DM.InvalidSelect.Open;
InvalidView.DataController.DataSource := DM.InvalidSource;
InvalidView.ViewData.Expand(true);
if (modify = 0) then
begin
AddInvalidA.Enabled := False;
DelInvalidA.Enabled := False;
ModifInvalidA.Enabled := False;
end;
end;
procedure T_fmPCardInvalidPage.AddInvalidAExecute(Sender: TObject);
var AForm: T_AddInvalidForm;
begin
AForm := T_AddInvalidForm.Create(Self);
AForm.Add := True;
AForm.id_pcard := id_pcard;
AForm.DM := DM;
AForm.DT_DateBeg.Date := Date();
AForm.DT_DateEnd.Date := Date()+365;
AForm.ShowModal;
if AForm.ModalResult = mrOk then
begin
DM.InvalidSelect.Close;
DM.InvalidSelect.Open;
end;
AForm.Free;
InvalidView.ViewData.Expand(true);
end;
procedure T_fmPCardInvalidPage.ModifInvalidAExecute(Sender: TObject);
var AForm: T_AddInvalidForm;
begin
if DM.InvalidSelect.IsEmpty then Exit;
AForm := T_AddInvalidForm.Create(Self);
AForm.Add := False;
AForm.id_pcard := id_pcard;
AForm.DM := DM;
AForm.date_beg := DM.InvalidSelect['date_beg'];
AForm.date_end := DM.InvalidSelect['date_end'];
AForm.DT_DateBeg.Date := DM.InvalidSelect['date_beg'];
AForm.DT_DateEnd.Date := DM.InvalidSelect['date_end'];
InvSet.Close;
InvSet.SQLs.SelectSQL.Text:='select * from ASUP_GET_PCARD_ADD_PROPS('+IntTostr(Id_PCard)+') where id_rec='+VarToStr(DM.InvalidSelect['id_rec']);
InvSet.Open;
AForm.SprEdit.Text:=InvSet['prop_neme'];
AForm.id_inv := DM.InvalidSelect['id_prop'];
AForm.id_group_1:=DM.InvalidSelect['id_prop'];
AForm.SpCB_Inv.Prepare(DM.InvalidSelect['id_prop'], DM.InvalidSelect['prop_neme']);
AForm.ShowModal;
if AForm.ModalResult = mrOk then
begin
DM.InvalidSelect.Close;
DM.InvalidSelect.Open;
end;
AForm.Free;
InvalidView.ViewData.Expand(true);
end;
procedure T_fmPCardInvalidPage.DelInvalidAExecute(Sender: TObject);
begin
if DM.InvalidSelect.IsEmpty then
begin
//MessageDlg('Не можливо видалити запис бо довідник пустий', mtError, [mbYes], 0);
agMessageDlg('Увага!', 'Не можливо видалити запис бо довідник пустий', mtError, [mbYes]);
Exit;
end;
if (MessageDlg('Чи ви справді бажаєте вилучити цей запис?', mtConfirmation, [mbYes, mbNo], 0) = mrNo) then Exit;
with DM do
try
DeleteQuery.Transaction.StartTransaction;
//StartHistory(DefaultTransaction);
DeleteQuery.ParamByName('id_rec').AsInteger := InvalidSelect['id_rec'];
DeleteQuery.ExecProc;
DefaultTransaction.Commit;
except on e: Exception do
begin
//MessageDlg('Не вдалося видалити запис: ' + #13 + e.Message, mtError, [mbYes], 0);
agMessageDlg('Увага!', 'Не вдалося видалити запис: ' + #13 + e.Message, mtError, [mbYes]);
DefaultTransaction.RollBack;
end;
end;
DM.InvalidSelect.Close;
DM.InvalidSelect.Open;
InvalidView.ViewData.Expand(true);
end;
procedure T_fmPCardInvalidPage.InvalidViewKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if ((Key = VK_F12) and (ssShift in Shift)) then
ShowInfo(InvalidView.DataController.DataSource.DataSet);
end;
procedure T_fmPCardInvalidPage.FrameEnter(Sender: TObject);
begin
if not DM.ReadTransaction.InTransaction
then DM.ReadTransaction.StartTransaction;
if DM.InvalidSelect.Active
then DM.InvalidSelect.Close;
DM.InvalidSelect.Open;
end;
procedure T_fmPCardInvalidPage.FrameExit(Sender: TObject);
begin
DM.ReadTransaction.CommitRetaining;
end;
procedure T_fmPCardInvalidPage.SpeedButton1Click(Sender: TObject);
var frm:T_frmInvalidHistory;
begin
if dm.InvalidSelect.IsEmpty then
begin
showmessage('Немає записів в "Історії змін"');
exit;
end
else
begin
frm:=T_frmInvalidHistory.Create(Self);
frm.InvalidHistSet.Close;
frm.InvalidHistSet.SQLs.SelectSQL.Text:='Select * From ASUP_DT_MAN_INVALID_HST Where Id_Man=:Id_Man';
frm.InvalidHistSet.ParamByName('ID_MAN').AsInteger:=dm.InvalidSelect['ID_MAN'];
frm.InvalidHistSet.Open;
frm.ShowModal;
frm.Free;
end;
end;
end.
|
unit ibSHDriver_UIB;
interface
uses
// Native Modules
SysUtils, Classes, StrUtils, Types,
// SQLHammer Modules
SHDesignIntf, ibSHDesignIntf, ibSHDriverIntf,
// UIB Modules
JvUIBSQLParser;
type
TibBTDriver = class(TSHComponent, IibSHDRV)
private
FNativeDAC: TObject;
FErrorText: string;
function GetNativeDAC: TObject;
procedure SetNativeDAC(Value: TObject);
function GetErrorText: string;
procedure SetErrorText(Value: string);
public
property NativeDAC: TObject read GetNativeDAC write SetNativeDAC;
property ErrorText: string read GetErrorText write SetErrorText;
end;
TibBTDRVSQLParser = class(TibBTDriver, IibSHDRVSQLParser)
private
FLexer: TUIBLexer;
FGrammar: TUIBGrammar;
FSource: TStringStream;
FDDLTokenList: TStrings;
FErrorLine: Integer;
FErrorColumn: Integer;
FStatements: TStrings;
FNameCreatedList: TStrings;
FNameAlteredList: TStrings;
FNameDroppedList: TStrings;
function GetErrorLine: Integer;
function GetErrorColumn: Integer;
function GetStatementCount: Integer;
function GetNameCreatedList: TStrings;
function GetNameAlteredList: TStrings;
function GetNameDroppedList: TStrings;
procedure ExtractNameFromSQLNode(const DDLText: string; ASQLNode: TSQLNode);
procedure OnGrammarError(Sender: TObject; const Msg: string);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
class function GetClassIIDClassFnc: TGUID; override;
{IibSHDRVSQLParser}
function GetScript: TStrings;
function GetCount: Integer;
// function GetStatements: TStrings;
function GetStatements(Index: Integer): string;
function GetTerminator: string;
procedure SetTerminator(const Value: string);
function GetSQLParserNotification: IibSHDRVSQLParserNotification;
procedure SetSQLParserNotification(Value: IibSHDRVSQLParserNotification);
function Parse(const SQLText: string): Boolean; overload;
function Parse: Boolean; overload;
function StatementState(const Index: Integer): TSHDBComponentState;
function StatementObjectType(const Index: Integer): TGUID;
function StatementObjectName(const Index: Integer): string;
function StatementsCoord(Index: Integer): TRect;
function IsDataSQL(Index: Integer): Boolean;
property ErrorLine: Integer read GetErrorLine;
property ErrorColumn: Integer read GetErrorColumn;
// property Statements: TStrings read GetStatements;
property StatementCount: Integer read GetStatementCount;
property NameCreatedList: TStrings read GetNameCreatedList;
property NameAlteredList: TStrings read GetNameAlteredList;
property NameDroppedList: TStrings read GetNameDroppedList;
end;
implementation
const
DDLTokens: array[0..22] of string = (
'CREATE', 'DECLARE', 'ALTER', 'RECREATE', 'DROP',
'DOMAIN', 'TABLE', 'INDEX', 'VIEW', 'PROCEDURE', 'TRIGGER', 'GENERATOR',
'EXCEPTION', 'FUNCTION', 'FILTER', 'ROLE', 'SHADOW',
'EXTERNAL', 'UNIQUE', 'ASC', 'ASCENDING', 'DESC', 'DESCENDING');
const
WD = [' ', #13, #10, #9, '(', '''', ';'];
type
TCharSet = set of Char;
{ TibBTDriver }
function TibBTDriver.GetNativeDAC: TObject;
begin
Result := FNativeDAC;
end;
procedure TibBTDriver.SetNativeDAC(Value: TObject);
begin
FNativeDAC := Value;
end;
function TibBTDriver.GetErrorText: string;
begin
Result := FErrorText;
end;
procedure TibBTDriver.SetErrorText(Value: string);
function FormatErrorMessage(const E: string): string;
begin
Result := AnsiReplaceText(E, ':' + sLineBreak, '');
Result := AnsiReplaceText(Result, sLineBreak, '');
end;
begin
FErrorText := FormatErrorMessage(Value);
end;
{ TibBTDRVSQLParser }
constructor TibBTDRVSQLParser.Create(AOwner: TComponent);
var
I: Integer;
begin
inherited Create(AOwner);
NativeDAC := nil;
FDDLTokenList := TStringList.Create;
for I := Low(DDLTokens) to High(DDLTokens) do
FDDLTokenList.Add(DDLTokens[I]);
TStringList(FDDLTokenList).CaseSensitive := False;
TStringList(FDDLTokenList).Sorted := True;
FStatements := TStringList.Create;
FNameCreatedList := TStringList.Create;
FNameAlteredList := TStringList.Create;
FNameDroppedList := TStringList.Create;
end;
destructor TibBTDRVSQLParser.Destroy;
begin
FDDLTokenList.Free;
FStatements.Free;
FNameCreatedList.Free;
FNameAlteredList.Free;
FNameDroppedList.Free;
NativeDAC := nil;
if Assigned(FLexer) then FreeAndNil(FLexer);
if Assigned(FGrammar) then FreeAndNil(FGrammar);
if Assigned(FSource) then FreeAndNil(FSource);
inherited Destroy;
end;
class function TibBTDRVSQLParser.GetClassIIDClassFnc: TGUID;
begin
// Result := IibSHDRVSQLParser_IBX;
Result := IibSHDRVSQLParser_FIBPlus;
end;
function TibBTDRVSQLParser.GetErrorLine: Integer;
begin
Result := FErrorLine;
end;
function TibBTDRVSQLParser.GetErrorColumn: Integer;
begin
Result := FErrorColumn;
end;
function TibBTDRVSQLParser.GetStatementCount: Integer;
begin
Result := FStatements.Count;
end;
function TibBTDRVSQLParser.GetNameCreatedList: TStrings;
begin
Result := FNameCreatedList;
end;
function TibBTDRVSQLParser.GetNameAlteredList: TStrings;
begin
Result := FNameAlteredList;
end;
function TibBTDRVSQLParser.GetNameDroppedList: TStrings;
begin
Result := FNameDroppedList;
end;
// From FIBPlus unit StrUtil;
function ExtractWord(Num:integer;const Str: string;const WordDelims: TCharSet):string;
var
SLen, I: Cardinal;
wc: Integer;
begin
Result := '';
I := 1; wc:=0;
SLen := Length(Str);
while I <= SLen do
begin
while (I <= SLen) and (Str[I] in WordDelims) do Inc(I);
if I <= SLen then Inc(wc);
if wc=Num then Break;
while (I <= SLen) and not(Str[I] in WordDelims) do Inc(I);
end;
if (wc=0) and (Num=1) then Result:=Str
else
if wc<>0 then
begin
while (I <= SLen) and not (Str[I] in WordDelims) do
begin
Result:=Result+Str[I];
Inc(I);
end;
end;
end;
function ExtractLastWord(const Str: string;const WordDelims:TCharSet):string;
var
SLen, I: Cardinal;
begin
Result := '';
SLen := Length(Str);
while (Str[SLen] in WordDelims) and (SLen>0) do Dec(SLen);
for i:= SLen downTo 1 do
begin
if not(Str[I] in WordDelims) then
Result := Str[I]+Result
else
Exit
end;
end;
function WordCount(const S: string; const WordDelims: TCharSet): Integer;
var
SLen, I: Cardinal;
begin
Result := 0;
I := 1;
SLen := Length(S);
while I <= SLen do
begin
while (I <= SLen) and (S[I] in WordDelims) do Inc(I);
if I <= SLen then Inc(Result);
while (I <= SLen) and not(S[I] in WordDelims) do Inc(I);
end;
end;
procedure TibBTDRVSQLParser.ExtractNameFromSQLNode(const DDLText: string; ASQLNode: TSQLNode);
var
S, Word: string;
I: Integer;
begin
S := DDLText;
S := AnsiReplaceText(S, '/*', ' /*');
while Pos('/*', S) > 0 do Delete(S, Pos('/*', S), Pos('*/', S) - Pos('/*', S) + 2);
for I := 1 to WordCount(S, WD) do
begin
Word := ExtractWord(I, S, WD);
if Pos('"', Word) > 0 then Word := Copy(S, Pos('"', S) + 1, PosEx('"', S, Pos('"', S) + 1) - Pos('"', S) - 1);
if (Length(Word) > 0) and (FDDLTokenList.IndexOf(Word) = -1) then
begin
S := Word;
Break;
end;
end;
case ASQLNode.NodeType of
NodeAlterTable: FNameAlteredList.Add(Format('%s=%s', [GUIDToString(IibSHTable), S]));
NodeAlterTrigger: FNameAlteredList.Add(Format('%s=%s', [GUIDToString(IibSHTrigger), S]));
NodeAlterProcedure: FNameAlteredList.Add(Format('%s=%s', [GUIDToString(IibSHProcedure), S]));
NodeAlterDomain: FNameAlteredList.Add(Format('%s=%s', [GUIDToString(IibSHDomain), S]));
NodeAlterIndex: FNameAlteredList.Add(Format('%s=%s', [GUIDToString(IibSHIndex), S]));
NodeCreateException: FNameCreatedList.Add(Format('%s=%s', [GUIDToString(IibSHException), S]));
NodeCreateIndex: FNameCreatedList.Add(Format('%s=%s', [GUIDToString(IibSHIndex), S]));
NodeCreateProcedure: FNameCreatedList.Add(Format('%s=%s', [GUIDToString(IibSHProcedure), S]));
NodeCreateTable: FNameCreatedList.Add(Format('%s=%s', [GUIDToString(IibSHTable), S]));
NodeCreateTrigger: FNameCreatedList.Add(Format('%s=%s', [GUIDToString(IibSHTrigger), S]));
NodeCreateView: FNameCreatedList.Add(Format('%s=%s', [GUIDToString(IibSHView), S]));
NodeCreateGenerator: FNameCreatedList.Add(Format('%s=%s', [GUIDToString(IibSHGenerator), S]));
NodeCreateDomain: FNameCreatedList.Add(Format('%s=%s', [GUIDToString(IibSHDomain), S]));
NodeCreateShadow: FNameCreatedList.Add(Format('%s=%s', [GUIDToString(IibSHShadow), S]));
NodeCreateRole: FNameCreatedList.Add(Format('%s=%s', [GUIDToString(IibSHRole), S]));
NodeDeclareFilter: FNameCreatedList.Add(Format('%s=%s', [GUIDToString(IibSHFilter), S]));
NodeDeclareFunction: FNameCreatedList.Add(Format('%s=%s', [GUIDToString(IibSHFunction), S]));
NodeDropException: FNameDroppedList.Add(Format('%s=%s', [GUIDToString(IibSHException), S]));
NodeDropIndex: FNameDroppedList.Add(Format('%s=%s', [GUIDToString(IibSHIndex), S]));
NodeDropProcedure: FNameDroppedList.Add(Format('%s=%s', [GUIDToString(IibSHProcedure), S]));
NodeDropTable: FNameDroppedList.Add(Format('%s=%s', [GUIDToString(IibSHTable), S]));
NodeDropTrigger: FNameDroppedList.Add(Format('%s=%s', [GUIDToString(IibSHTrigger), S]));
NodeDropView: FNameDroppedList.Add(Format('%s=%s', [GUIDToString(IibSHView), S]));
NodeDropFilter: FNameDroppedList.Add(Format('%s=%s', [GUIDToString(IibSHFilter), S]));
NodeDropDomain: FNameDroppedList.Add(Format('%s=%s', [GUIDToString(IibSHDomain), S]));
NodeDropExternal: FNameDroppedList.Add(Format('%s=%s', [GUIDToString(IibSHFunction), S]));
NodeDropShadow: FNameDroppedList.Add(Format('%s=%s', [GUIDToString(IibSHShadow), S]));
NodeDropRole: FNameDroppedList.Add(Format('%s=%s', [GUIDToString(IibSHRole), S]));
NodeDropGenerator: FNameDroppedList.Add(Format('%s=%s', [GUIDToString(IibSHGenerator), S]));
NodeRecreateProcedure: FNameCreatedList.Add(Format('%s=%s', [GUIDToString(IibSHProcedure), S]));
NodeRecreateTable: FNameCreatedList.Add(Format('%s=%s', [GUIDToString(IibSHTable), S]));
NodeRecreateView: FNameCreatedList.Add(Format('%s=%s', [GUIDToString(IibSHView), S]));
end;
end;
procedure TibBTDRVSQLParser.OnGrammarError(Sender: TObject; const Msg: string);
begin
//
end;
function TibBTDRVSQLParser.GetScript: TStrings;
begin
Result := nil;
end;
function TibBTDRVSQLParser.GetCount: Integer;
begin
Result := 0;
end;
function TibBTDRVSQLParser.GetStatements(Index: Integer): string;
begin
// Result := FStatements;
end;
function TibBTDRVSQLParser.GetTerminator: string;
begin
Result := ';';//Затычка
end;
procedure TibBTDRVSQLParser.SetTerminator(const Value: string);
begin
//Затычка
end;
function TibBTDRVSQLParser.GetSQLParserNotification: IibSHDRVSQLParserNotification;
begin
//
end;
procedure TibBTDRVSQLParser.SetSQLParserNotification(
Value: IibSHDRVSQLParserNotification);
begin
//
end;
function TibBTDRVSQLParser.Parse(const SQLText: string): Boolean;
var
I: Integer;
PosFrom, PosTo: TPosition;
begin
ErrorText := EmptyStr;
FErrorLine := -1;
FErrorColumn := -1;
FStatements.Clear;
FNameCreatedList.Clear;
FNameAlteredList.Clear;
FNameDroppedList.Clear;
if Assigned(FLexer) then FreeAndNil(FLexer);
if Assigned(FGrammar) then FreeAndNil(FGrammar);
if Assigned(FSource) then FreeAndNil(FSource);
FSource := TStringStream.Create(SQLText);
FLexer := TUIBLexer.Create(FSource);
FGrammar := TUIBGrammar.Create(FLexer);
FGrammar.OnMessage := OnGrammarError;
if FGrammar.yyparse = 0 then
begin
if Assigned(FGrammar.RootNode) then
for I := 0 to Pred(FGrammar.RootNode.NodesCount) do
begin
PosFrom := FGrammar.RootNode.Nodes[I].PosFrom;
PosTo := FGrammar.RootNode.Nodes[I].PosTo;
FSource.Seek(PosFrom.Pos, soFromBeginning);
if Length(FGrammar.RootNode.Nodes[I].Value) = 0 then
begin
FStatements.Add(Trim(FSource.ReadString(PosTo.Pos - PosFrom.Pos)));
ExtractNameFromSQLNode(FStatements[Pred(FStatements.Count)], FGrammar.RootNode.Nodes[I]);
end;
end;
end else
begin
FErrorLine := FLexer.yylineno;
FErrorColumn := FLexer.yycolno;
ErrorText := Format('Parsing error: line %d, column %d', [FErrorLine, FErrorColumn]);
end;
Result := Length(ErrorText) = 0;
end;
function TibBTDRVSQLParser.Parse: Boolean;
begin
Result := False;
end;
function TibBTDRVSQLParser.StatementState(const Index: Integer): TSHDBComponentState;
begin
Result := csUnknown;
end;
function TibBTDRVSQLParser.StatementObjectType(const Index: Integer): TGUID;
begin
Result := IUnknown;
end;
function TibBTDRVSQLParser.StatementObjectName(const Index: Integer): string;
begin
Result := EmptyStr;
end;
function TibBTDRVSQLParser.StatementsCoord(Index: Integer): TRect;
begin
//
end;
function TibBTDRVSQLParser.IsDataSQL(Index: Integer): Boolean;
begin
Result := True;
end;
initialization
// BTRegisterComponents([TibBTDRVSQLParser]);
end.
|
(*
Category: SWAG Title: MENU MANAGEMENT ROUTINES
Original name: 0004.PAS
Description: Efficient Menu System
Author: BRAD ZAVITSKY
Date: 09-04-95 10:56
*)
(*
[ NOTES ]
-- Desc --
RmMenu has been created to allow easy, fast, and efficient menu's
that are very versatile and configurable to be created without
the usual amount of bulky, cryptic code and time consuming
initialization, in fact, RmMenu uses and needs NO initalization
of any variables.
-- Legal --
RmMenu was created by Brad Zavitsky and all rights are reserved.
Use at your own risk, the author(s) will not take any responsibility.
SWAG use and commercial use is fine, RmMenu is FreeWare.
Use of RmMenu is allowed free of charge provided that the CopyRight
procedure is not altered and is not removed at the initialization
part of the unit and optionally credit is given to me, the author
for the unit.
-- Switches --
DEBUG : Define this to use the compiler directives for use with
debugging. RmMenu has already been debugged so you should
not have to use this at all.
FASTW : This is on by default, remove it below to use CRT's slower
writes instead of the special FASTWRITE procedure.
-- Info --
Code size : 1121 bytes
Data size : 0 bytes
Stack size : 0 bytes
Min heap : 0 bytes
Max heap : 0 bytes
*)
{
Unit RmMenu;
Interface
}
Uses Crt;
Const
Max_Choices = 10;
Type Menu_Typ = Record
Options : array[1..max_choices] of string[20];
Key : array[1..max_choices] of char;
X : array[1..max_choices] of byte;
Y : array[1..max_choices] of byte;
Num_Opt : byte;
Hi_Col : byte;
Norm_Col : byte;
HotKey : boolean; { This option allows a choice to be higlighted by pressing it's KEY }
HotExit : boolean; { This option allows exit on HotKey }
End;
{
Procedure Menu(Menu_Dat : Menu_Typ; Var CChoice : Byte;Change : Boolean);
far;
Implementation
}
(*
Procedure Copyright; Near; Assembler;
{ This MAY NOT be removed }
asm
JMP @@1
DB 13,10,'RmMenu Unit (C)1995 by Brad Zavitsky. All rights reserved.',13,10
@@1:
end;
*)
(*
PROCEDURE FastWrite(Col, Row, Attr : Byte; Str : String); NEAR; ASSEMBLER;
{ This procedure is the only one which is not mine }
ASM
PUSH DS {Save DS}
MOV DL,CheckSnow {Save CheckSnow Setting}
MOV ES,SegB800 {ES = Colour Screen Segment}
MOV SI,SegB000 {SI = Mono Screen Segment}
MOV DS,Seg0040 {DS = ROM Bios Segment}
MOV BX,[49h] {BL = CRT Mode, BH = ScreenWidth}
MOV AL,Row {AL = Row No}
MUL BH {AX = Row * ScreenWidth}
XOR CH,CH {CH = 0}
MOV CL,Col {CX = Column No}
ADD AX,CX {(Row*ScreenWidth)+Column}
ADD AX,AX {Multiply by 2 (2 Byte per Position)}
MOV DI,AX {DI = Screen Offset}
CMP BL,7 {CRT Mode = Mono?}
JNE @@DestSet {No - Use Colour Screen Segment}
MOV ES,SI {Yes - ES = Mono Screen Segment}
XOR DX,DX {Force jump to FWrite}
@@DestSet: {ES:DI = Screen Destination Address}
LDS SI,Str {DS:SI = Source String}
CLD {Move Forward through String}
LODSB {Get Length Byte of String}
MOV CL,AL {CX = Input String Length}
JCXZ @@Done {Exit if Null String}
MOV AH,Attr {AH = Attribute}
OR DL,DL {Test Mono/CheckSnow Flag}
JZ @@FWrite {Snow Checking Disabled or Mono - Use FWrite}
{Output during Screen Retrace's}
MOV DX,003DAh {6845 Status Port}
@@WaitLoop: {Output during Retrace's}
MOV BL,[SI] {Load Next Character into BL}
INC SI {Update Source Pointer}
CLI {Interrupts off}
@@Wait1: {Wait for End of Retrace}
IN AL,DX {Get 6845 status}
TEST AL,8 {Vertical Retrace in Progress?}
JNZ @@Write {Yes - Output Next Char}
SHR AL,1 {Horizontal Retrace in Progress?}
JC @@Wait1 {Yes - Wait until End of Retrace}
@@Wait2: {Wait for Start of Next Retrace}
IN AL,DX {Get 6845 status}
SHR AL,1 {Horizontal Retrace in Progress?}
JNC @@Wait2 {No - Wait until Retrace Starts}
@@Write: {Output Char and Attribute}
MOV AL,BL {Put Char to Write into AL}
STOSW {Store Character and Attribute}
STI {Interrupts On}
LOOP @@WaitLoop {Repeat for Each Character}
JMP @@Done {Exit}
{Ignore Screen Retrace's}
@@FWrite: {Output Ignoring Retrace's}
TEST SI,1 {DS:SI an Even Offset?}
JZ @@Words {Yes - Skip (On Even Boundary)}
LODSB {Get 1st Char}
STOSW {Write 1st Char and Attrib}
DEC CX {Decrement Count}
JCXZ @@Done {Finished if only 1 Char in Str}
@@Words: {DS:SI Now on Word Boundary}
SHR CX,1 {CX = Char Pairs, Set CF if Odd Byte Left}
JZ @@ChkOdd {Skip if No Pairs to Store}
@@Loop: {Loop Outputing 2 Chars per Loop}
MOV BH,AH {BH = Attrib}
LODSW {Load 2 Chars}
XCHG AH,BH {AL = 1st Char, AH = Attrib, BH = 2nd Char}
STOSW {Store 1st Char and Attrib}
MOV AL,BH {AL = 2nd Char}
STOSW {Store 2nd Char and Attrib}
LOOP @@Loop {Repeat for Each Pair of Chars}
@@ChkOdd: {Check for Final Char}
JNC @@Done {Skip if No Odd Char to Display}
LODSB {Get Last Char}
STOSW {Store Last Char and Attribute}
@@Done: {Finished}
POP DS {Restore DS}
END;
*)
PROCEDURE FastWrite(Col, Row, Attr : Byte; Str : String);
begin
GotoXY(col, row);
{textAttr = attr;}
Write(Str);
end;
Procedure Hilight(Menu_Dat : Menu_Typ; ChoiceNum : byte);
Begin
With Menu_Dat do
{$IFDEF FASTW}
FastWrite(X[ChoiceNum],Y[ChoiceNum],Hi_Col,Options[choiceNum]);
{$ELSE}
Begin
Gotoxy(X[choiceNum],Y[ChoiceNum]);
TextAttr := Hi_Col;
Write(Options[ChoiceNum]);
End;{With Menu_Dat}
{$ENDIF}
End;
Procedure UnHilight(Menu_Dat : Menu_Typ; ChoiceNum : byte);
Begin
With Menu_Dat do
{$IFDEF FASTW}
FastWrite(X[ChoiceNum],Y[ChoiceNum],Norm_Col,Options[choiceNum]);
{$ELSE}
Begin
Gotoxy(X[choiceNum],Y[ChoiceNum]);
TextAttr := Norm_Col;
Write(Options[ChoiceNum]);
End;{With Menu_Dat}
{$ENDIF}
End;
Procedure ShowMenu(Menu_Dat : Menu_Typ);
Var B : Byte;
Begin
For B := 1 to Menu_Dat.Num_Opt do unhilight(Menu_Dat,B);
End;
Function HotKeyFound(Menu_Dat : Menu_Typ; Ch : Char) : byte;
Var B : Byte;
Begin
HotKeyFound := 0; {Not found}
CH := UpCase(Ch);
For B := 1 to menu_dat.num_opt do
Begin
if upcase(Menu_Dat.key[b]) = CH then
Begin
HotKeyFound := B;
Exit;
End;
End;
End;
Procedure Menu(Menu_Dat : Menu_Typ; Var CChoice : Byte;Change : Boolean);
{ returns choice, 0 if <Esc> or Tab ; }
{ Change means allow change field, ie.. Allows TAB/ESC to end }
Var
Ch : Char;
Done : Boolean;
oldC, B : Byte;
Begin
Done := False;
IF (CCHoice = 0) or (CChoice > Menu_Dat.num_Opt) then CChoice := 1;
OldC := CChoice;
ShowMenu(Menu_Dat);
Hilight(menu_dat, CChoice);
Repeat
Ch := Readkey;
If CH = #0 then
Begin{function key}
CH := Readkey;
If CH=#77 then CH:=#80;
IF CH=#75 then CH:=#72;
Case CH of
#72 : {Up}
If CChoice > 1 then
begin
unhilight(menu_dat, CChoice);
dec(CChoice);
End Else
Begin
unhilight(menu_dat, CChoice);
CChoice := menu_dat.num_opt;
End;
#80 : {Down}
If CChoice < Menu_Dat.num_opt then
begin
unhilight(menu_dat, CChoice);
inc(CChoice);
End Else
Begin
unhilight(menu_dat, CChoice);
CChoice := 1;
End;
#71 : {Home}
If CChoice <> 1 then
begin
unhilight(menu_dat, CChoice);
CChoice := 1;
End;
#79 : {End}
If CChoice < Menu_Dat.Num_Opt then
begin
unhilight(menu_dat, CChoice);
CChoice := Menu_Dat.Num_Opt;
End;
End;{Case}
End Else
Case CH of
#27,#9 : If Change then
Begin
CChoice := 0;
Exit;
End;
#13 :
Begin
Exit;
End;
Else if menu_dat.hotkey then
Begin
B := HotKeyFound(Menu_Dat, ch);
If (B <> 0) then
Begin
If (B <> CChoice) then
Begin
Unhilight(menu_dat, CChoice);
CChoice := B;
HiLight(Menu_dat,CChoice);
OldC := CChoice;
End;{(B <> CChoice)}
If menu_dat.hotexit then Exit;
End;{ (B <> 0) }
End; { menu_dat.hotkey }
End;{Case}
If OldC <> CChoice then HiLight(Menu_Dat, CChoice);
OldC := CChoice;
Until Done;
End;
{
Begin
Copyright;
End.
--[ Sample Program ]--
Program test;
Uses Crt, RMMENU;
}
Var
MenuC : Menu_Typ;
B : byte;
{TempS : String;}
begin
With MenuC do
Begin
options[1] := 'Continue';
options[2] := 'Quit';
options[3] := 'Abort';
key[1] := 'C';
key[2] := 'Q';
key[3] := 'A';
y[1] := 2;
y[2] := y[1];
y[3] := y[1];
x[1] := 2;
x[2] := X[1] + length(options[1])+1;
x[3] := x[2] + length(options[2])+1;
Num_Opt := 3;
Hi_Col := 30;
HotKey := True; {This allows one keypress picks}
HotExit := False; {This allows to exit on Hotkey}
Norm_Col := 31;
End;
TextAttr := 80;
ClrScr;
B := 1;
Repeat
Menu(MenuC, B, True);
Until B <> 1;
writeln;
Writeln;
If B <> 0 then Writeln('You have picked choice number ', B,'.')
else writeln('You have either pressed <ESC> or TAB to change fields');
Readln;
End.
|
unit uFrmCaptura;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants, FMX.Platform,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects,
FMX.Controls.Presentation, FMX.StdCtrls, System.Actions, FMX.ActnList,
FMX.StdActns, FMX.MediaLibrary.Actions, System.ImageList, FMX.ImgList;
type
TfrmCaptura = class(TForm)
tbCaptura: TToolBar;
imgFoto: TImage;
btnAbortar: TButton;
btnOk: TButton;
btnLibrary: TButton;
btnCamera: TButton;
ActionList1: TActionList;
btnCarregaWindows: TButton;
actCam: TTakePhotoFromCameraAction;
actLibrary: TTakePhotoFromLibraryAction;
ilCaptura: TImageList;
abrirDialog: TOpenDialog;
btnClear: TButton;
procedure actCamDidFinishTaking(Image: TBitmap);
procedure FormCreate(Sender: TObject);
procedure btnCarregaWindowsClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnClearClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure carregaFoto(img: TBitmap);
end;
var
frmCaptura: TfrmCaptura;
implementation
uses
System.IOUtils, uFrmPrincipal;
{$R *.fmx}
{ TfrmCaptura }
procedure TfrmCaptura.actCamDidFinishTaking(Image: TBitmap);
begin
carregaFoto(Image);
end;
procedure TfrmCaptura.btnCarregaWindowsClick(Sender: TObject);
var
JPG: TBitmap;
save: TBitmapCodecSaveParams;
FileName: String;
begin
if abrirDialog.Execute then
begin
Try
JPG := TBitmap.Create();
JPG.LoadFromFile(abrirDialog.FileName);
imgFoto.Bitmap := Nil; // Coloca essa linha
FileName := (ExtractFilePath(ParamStr(0)) + 'arquivoTemp.jpg');
if FileExists(FileName) then
begin
DeleteFile(FileName);
end;
save.Quality := 50;
JPG.SaveToFile(FileName, @save);
if FileExists(FileName) then
begin
imgFoto.Bitmap.LoadFromFile(FileName);
end
else
MessageDlg('Não foi possível carregar a imagem selecionada',
TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0);
// Ou pode fazer assim
// DBImage1.Picture.LoadFromFile(OpenDialog1.FileName);
Finally
FreeAndNil(JPG);
end;
end;
end;
procedure TfrmCaptura.btnClearClick(Sender: TObject);
var
bit: TBitmap;
begin
bit := TBitmap.Create;
imgFoto.Bitmap := bit;
FreeandNil(bit)
end;
procedure TfrmCaptura.Button1Click(Sender: TObject);
begin
ShowMEssage('isEmpty: ' + BoolToStr(imgFoto.Bitmap.IsEmpty, true) + ' size ' +
imgFoto.Bitmap.Size.Width.ToString + ' * ' +
imgFoto.Bitmap.Size.Height.ToString);
end;
procedure TfrmCaptura.carregaFoto(img: TBitmap);
begin
if Assigned(img) then
imgFoto.Bitmap.Assign(img);
end;
procedure TfrmCaptura.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := TCloseAction.caFree;
// frmCaptura := nil;
end;
procedure TfrmCaptura.FormCreate(Sender: TObject);
begin
{$IF DEFINED (MSWINDOWS)}
btnCarregaWindows.Visible := true;
{$ENDIF}
end;
end.
|
unit ResizePanel;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls;
type
TResizePanel = class(TPanel)
private
{ Private declarations }
IsFirst : Boolean;
PanelWidth : integer;
FSpaceInside : integer;
protected
{ Protected declarations }
constructor Create( AOwner: TComponent ); override;
procedure WMSize( var Message: TWMSize ); message WM_SIZE;
public
{ Public declarations }
published
{ Published declarations }
property SpaceInside : integer read FSpaceInside write FSpaceInside default 2;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('NewPower', [TResizePanel]);
end;
constructor TResizePanel.Create( AOwner: TComponent );
begin
inherited Create( AOwner);
FSpaceInside := 2;
IsFirst := True;
end;
procedure TResizePanel.WMSize( var Message: TWMSize );
var
i, LeftPos : integer;
begin
inherited;
Exit;
if ControlCount > 0 then
begin
LeftPos := 0;
for i := 0 to (ControlCount -1) do
begin
Controls[i].Left := LeftPos;
Controls[i].Width := Round(((Width-1)-((ControlCount-1)*FSpaceInside))/ControlCount);
Inc(LeftPos, (Controls[i].Width+FSpaceInside));
end;
end;
end;
end.
|
unit uDbPatcher;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,//SiAuto,SmartInspect,
Dialogs, StdCtrls, DB, MemDS, DBAccess, MyAccess, DBClient,JvVersionInfo,
ExtCtrls;
type
TDbPatch = class(TObject)
private
FSql: string;
FVersionNo: string;
FBuildNo: integer;
FActive: string;
public
constructor Create(const VersionNo: string; const BuildNo: integer; Active:
string; const SqlScript: string);
property VersionNo: string read FVersionNo write FVersionNo;
property BuildNo: integer read FBuildNo write FBuildNo;
property Sql: string read FSql write FSql;
property Active: string read FActive write FActive;
end;
TfrmDbPatcher = class(TForm)
MemoInfo: TMemo;
btnExecutePath: TButton;
MyConnection1: TMyConnection;
MyQuery: TMyQuery;
ClientDataSet1: TClientDataSet;
Timer1: TTimer;
procedure FormCreate(Sender: TObject);
procedure btnExecutePathClick(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
FAllowPatch , FAllowClose : boolean;
FIsNewVersion: boolean;
procedure SetIsNewVersion(const Value: boolean);
function NewVersion : boolean;
{ Private declarations }
public
{ Public declarations }
PatchList : Tstringlist;
procedure initPatchList();
procedure initialVersion();
property IsNewVersion : boolean read NewVersion ;
end;
const patch_len=9;
maxTimer=10;
var
frmDbPatcher: TfrmDbPatcher;
SQLPatchList : array of TDbPatch;
ContinueCount:integer;
implementation
uses STDLIB, CommonLIB;
{$R *.dfm}
{ TStockDbPatcherForm }
function CheckNewVersion(CurrVersion,
NewVersion: string): boolean;
var i,k:integer;
ss:string;
isNewVersion:boolean;
_V1,_V2:array[1..4] of Integer;
const _maxVClass=4;
begin
result:=false;
NewVersion:=trim(NewVersion);
k:=1;
ss:='';
for i:=1 to length(NewVersion) do begin
if (NewVersion[i]<>'.') then begin
ss:=ss+NewVersion[i];
end else begin
_V2[k]:=StrToInt(ss);
ss:='';
inc(k);
end;
if i=length(NewVersion) then
_V2[4]:=StrToInt(ss);
end;
// version 1 self
CurrVersion:=trim(CurrVersion);
k:=1;
ss:='';
for i:=1 to length(CurrVersion) do begin
if (CurrVersion[i]<>'.') then begin
ss:=ss+CurrVersion[i];
end else begin
_V1[k]:=StrToInt(ss);
ss:='';
inc(k);
end;
if i=length(CurrVersion) then
_V1[4]:=StrToInt(ss);
end;
for k:=1 to _maxVClass do begin
if _V2[k]>_V1[k] then
begin
isNewVersion:=true;
result:=isNewVersion;
Exit;
end;
end;
result:=isNewVersion;
end;
procedure TfrmDbPatcher.btnExecutePathClick(Sender: TObject);
begin
//initialVersion;
if FAllowClose then close
else begin
Timer1.Enabled:=false;
// initPatchList;
initialVersion;
end;
end;
function TfrmDbPatcher.NewVersion: boolean;
var
currentDbName : string;
TempCds,cdsGetDBName : TClientDataSet;
tfv : TJvVersionInfo;
i:integer;
rep : boolean;
begin
try
// check for allow pather;
//Si.Enabled := true;
rep := true;
tfv := TJvVersionInfo.Create(application.exename);
TempCds := TClientDataSet.Create(nil);
cdsGetDBName :=TClientDataSet.Create(nil);
ExecuteSQL(
' CREATE TABLE IF NOT EXISTS ICSTTVER ( '+
' VERVNO VARCHAR(100) NOT NULL, '+
' VERBNO INT, '+
' VERCDE VARCHAR(100) NULL,VERNAM VARCHAR(100) NULL,VERLICENSE TEXT NULL DEFAULT NULL,PRIMARY KEY (VERVNO) '+
' ) '+
' COLLATE=''tis620_thai_ci'' '+
' ENGINE=InnoDB ');
cdsGetDBName.data :=GetDataSet('select DATABASE() as DBNAME');
currentDbName := cdsGetDBName.fieldbyname('DBNAME').AsString;
TempCds.data := GetDataSet('select count(*) as n from information_schema.`TABLES` where table_name=''ICMTTVER'' and table_schema='''+currentDbName+'''');
rep :=TempCds.RecordCount<=0;
if TempCds.RecordCount>0 then
if TempCds.FieldByName('n').IsNull then rep := true;
//SiMain.LogMessage('DBPATCHER: Check Current System Version ###');
TempCds.Data := GetDataSet('select * from ICSTTVER');
if TempCds.Active then
if TempCds.RecordCount>0 then
begin
// check version
if not (TempCds.FieldByName('VERVNO').IsNull) then
if trim(TempCds.FieldByName('VERVNO').AsString)<>'' then
begin
//SiMain.LogMessage('DBPATCHER: Check Is NewVersion');
rep := CheckNewVersion(TempCds.FieldByName('VERVNO').AsString,tfv.FileVersion) ;
end
else rep :=true;
end else rep := true;
{if rep then
SiMain.LogMessage('DBPATCHER: Found NewVersion!!!')
else
SiMain.LogMessage('DBPATCHER: Not A NewVersion!!!');
}
result := rep;
finally
TempCds.free;
tfv.free;
end;
end;
procedure TfrmDbPatcher.FormClose(Sender: TObject;
var Action: TCloseAction);
var i:integer;
begin
for I := 0 to patch_len-1 do
freeandnil(SQLPatchList[i]);
end;
procedure TfrmDbPatcher.FormCreate(Sender: TObject);
begin
{
MyConnection1.Server := getzconnection.HostName;
MyConnection1.database := getzconnection.database;
MyConnection1.username := getzconnection.user;
MyConnection1.password := getzconnection.password;
}
initPatchList;
end;
procedure TfrmDbPatcher.FormShow(Sender: TObject);
begin
FAllowPatch := false;
MemoInfo.Lines.Clear;
ContinueCount:=maxTimer;
FAllowClose:=false;
// initPatchList;
Timer1.Enabled := true;
end;
procedure TfrmDbPatcher.initialVersion;
var
currentDbName : string;
TempCds,cdsGetDBName : TClientDataSet;
tv : TJvVersionInfo;
i:integer;
currVersion : string;
rep : boolean;
begin
try
// check for allow pather;
//Si.Enabled := true;
btnExecutePath.Enabled:=false;
tv := TJvVersionInfo.Create(application.exename);
TempCds := TClientDataSet.Create(nil);
cdsGetDBName :=TClientDataSet.Create(nil);
ExecuteSQL(
' CREATE TABLE IF NOT EXISTS ICSTTVER ( '+
' VERVNO VARCHAR(100) NOT NULL, '+
' VERBNO INT, '+
' VERCDE VARCHAR(100) NULL,VERNAM VARCHAR(100) NULL,VERLICENSE TEXT NULL DEFAULT NULL,PRIMARY KEY (VERVNO) '+
' ) '+
' COLLATE=''tis620_thai_ci'' '+
' ENGINE=InnoDB ');
cdsGetDBName.data :=GetDataSet('select DATABASE() as DBNAME');
currentDbName := cdsGetDBName.fieldbyname('DBNAME').AsString;
TempCds.data := GetDataSet('select count(*) as n from information_schema.`TABLES` where table_name=''ICMTTVER'' and table_schema='''+currentDbName+'''');
rep :=TempCds.RecordCount<=0;
if TempCds.RecordCount>0 then
if TempCds.FieldByName('n').IsNull then rep := true;
//SiMain.LogMessage('DBPATCHER: Check Current System Version');
TempCds.Data := GetDataSet('select * from ICSTTVER limit 1');
if TempCds.Active then
if TempCds.RecordCount>0 then
begin
// check version
if not TempCds.FieldByName('VERVNO').IsNull then
begin
if CheckNewVersion(TempCds.FieldByName('VERVNO').AsString,tv.FileVersion) then
begin
currVersion := TempCds.FieldByName('VERVNO').AsString;
// update db version
if not (TempCds.State in [dsEdit,dsInsert]) then TempCds.Edit;
TempCds.FieldByName('VERVNO').AsString:=tv.FileVersion;
TempCds.FieldByName('VERBNO').AsInteger:=0;
TempCds.Post;
end;
end;
end else
begin
// post new version
//SiMain.LogMessage('DBPATCHER: Post New System Version');
if not (TempCds.State in [dsEdit,dsInsert]) then TempCds.Append;
TempCds.FieldByName('VERVNO').AsString:=tv.FileVersion;
TempCds.FieldByName('VERBNO').AsInteger:=0;
TempCds.Post;
currVersion:='';
end;
if TempCds.ChangeCount>0 then
UpdateDataset(TempCds,'select * from ICSTTVER');
if trim(currVersion)='' then currVersion:='0.0.0.0';
// do patch here
//SiMain.LogMessage('DBPATCHER: Starting Patch...');
for I := 0 to patch_len-1 do
if SQLPatchList[i].Active='A' then
begin
if CheckNewVersion(currVersion,SQLPatchList[i].VersionNo) then
begin
try
// update build no
TempCds.Data := GetDataSet('select * from ICSTTVER');
if TempCds.Active then
begin
if TempCds.RecordCount>0 then
begin
if not (TempCds.State in [dsEdit,dsInsert]) then TempCds.Edit;
TempCds.FieldByName('VERBNO').AsInteger:=SQLPatchList[i].BuildNo;
TempCds.FieldByName('VERCDE').asstring:=_VersionCode;
TempCds.FieldByName('VERNAM').asstring:=_VersionName;
TempCds.Post;
if TempCds.ChangeCount>0 then
UpdateDataset(TempCds,'select * from ICSTTVER');
end
end;
// execute sql path
ExecuteSQL(SQLPatchList[i].Sql);
MemoInfo.Lines.Add(SQLPatchList[i].Sql);
except
on ee:Exception do
MemoInfo.Lines.Add(trim(ee.Message));
end;
end;
end;
FAllowClose := true;
btnExecutePath.Caption:='Close';
finally
btnExecutePath.Enabled:=true;
TempCds.free;
tv.free;
end;
end;
procedure TfrmDbPatcher.initPatchList;
begin
SetLength(SQLPatchList,patch_len);
SQLPatchList[0] := TDbPatch.Create('0.57.1.4',1,'A',
' ALTER TABLE `ICMTTCSH` '+
' ADD COLUMN `CSHFAX` VARCHAR(100) NULL DEFAULT NULL COMMENT ''Fax'' AFTER `CSHPHO`, '+
' ADD COLUMN `CSHMAI` VARCHAR(100) NULL DEFAULT NULL COMMENT ''Mail'' AFTER `CSHFAX` '
);
SQLPatchList[1] := TDbPatch.Create('0.57.1.5',2,'A',
' CREATE TABLE IF NOT EXISTS `ICMTTROL` ( '+
' `ROLACT` VARCHAR(1) NULL DEFAULT ''A'' COMMENT ''A=Active , I = In Active'', '+
' `ROLCOD` INT(11) NOT NULL COMMENT ''Role Code'', '+
' `ROLNAM` VARCHAR(200) NULL DEFAULT NULL COMMENT ''Role Name'', '+
' `ROLDES` TEXT NULL, '+
' `CMPCOD` VARCHAR(5) NULL DEFAULT NULL, '+
' `CMPBRN` VARCHAR(5) NULL DEFAULT NULL, '+
' `CMPDEP` VARCHAR(5) NULL DEFAULT NULL, '+
' `CMPSEC` VARCHAR(5) NULL DEFAULT NULL, '+
' `ENTUSR` VARCHAR(30) NULL DEFAULT NULL, '+
' `ENTDTE` DATETIME NULL DEFAULT NULL, '+
' `EDTUSR` VARCHAR(30) NULL DEFAULT NULL, '+
' `EDTDTE` DATETIME NULL DEFAULT NULL, '+
' PRIMARY KEY (`ROLCOD`) '+
' ) '+
' COMMENT=''User Role'' '+
' COLLATE=''tis620_thai_ci'' '+
' ENGINE=InnoDB '
);
SQLPatchList[2] := TDbPatch.Create('0.57.1.5',2,'A',
' CREATE TABLE IF NOT EXISTS `ICMTTRPM` ( '+
' `PERCOD` INT(10) NOT NULL, '+
' `PERRCO` INT(10) NOT NULL, '+
' `PERMNU` INT(10) NOT NULL, '+
' `PERENT` VARCHAR(1) NULL DEFAULT NULL, '+
' `PEREDI` VARCHAR(1) NULL DEFAULT NULL, '+
' `PERDEL` VARCHAR(1) NULL DEFAULT NULL, '+
' `PERCAN` VARCHAR(1) NULL DEFAULT NULL, '+
' `PERAPP` VARCHAR(1) NULL DEFAULT NULL, '+
' `PERO01` VARCHAR(1) NULL DEFAULT NULL, '+
' `PERO02` VARCHAR(1) NULL DEFAULT NULL, '+
' `PERO03` VARCHAR(1) NULL DEFAULT NULL, '+
' `PERO04` VARCHAR(1) NULL DEFAULT NULL, '+
' `PERO05` VARCHAR(1) NULL DEFAULT NULL, '+
' `PERO06` VARCHAR(1) NULL DEFAULT NULL, '+
' `PERO07` VARCHAR(1) NULL DEFAULT NULL, '+
' `PERO08` VARCHAR(1) NULL DEFAULT NULL, '+
' `PERO09` VARCHAR(1) NULL DEFAULT NULL, '+
' `PERO10` VARCHAR(1) NULL DEFAULT NULL, '+
' PRIMARY KEY (`PERCOD`, `PERRCO`, `PERMNU`) '+
' ) '+
' COMMENT=''Role Permission'' '+
' COLLATE=''tis620_thai_ci'' '+
' ENGINE=InnoDB '
);
SQLPatchList[3] := TDbPatch.Create('0.57.1.6',3,'A',
'ALTER TABLE `ICMTTPRD` ADD COLUMN `PRDSER` VARCHAR(100) NULL DEFAULT NULL AFTER `PRDCDE`'
);
SQLPatchList[4] := TDbPatch.Create('0.57.3.29',4,'A',
'ALTER TABLE `ICMTTPOH` CHANGE COLUMN `POHRMK` `POHRMK` TEXT NULL COMMENT ''Remark'' AFTER `POHREV`'
);
SQLPatchList[5] := TDbPatch.Create('0.57.6.1',5,'A',
'ALTER TABLE `AppReport` ADD COLUMN `RPTGROUP` VARCHAR(10) NULL DEFAULT NULL AFTER `UNID`'
);
SQLPatchList[6] := TDbPatch.Create('0.57.6.1',6,'A',
'UPDATE `AppReport` set RPTGROUP=''00'' '
);
SQLPatchList[7] := TDbPatch.Create('0.57.6.21',7,'A',
' CREATE TABLE IF NOT EXISTS `ICMTTUSR` ( '+
' `USRACT` VARCHAR(1) NULL DEFAULT ''A'' COMMENT ''A=Active , I = In Active'', '+
' `USRCOD` INT(11) NOT NULL COMMENT ''User ID (UID)'', '+
' `USRCDE` VARCHAR(30) NULL DEFAULT NULL COMMENT ''UserName'', '+
' `USRSEQ` INT(11) NULL DEFAULT NULL COMMENT ''Sequence'','+
' `USRNAM` VARCHAR(200) NULL DEFAULT NULL COMMENT ''Fullname'','+
' `USRPWD` VARCHAR(255) NULL DEFAULT NULL COMMENT ''Password'', '+
' `USRRHA` VARCHAR(255) NULL DEFAULT NULL COMMENT ''Record Hash USRCOD+USRCDE+USRPWD(decrypted)'', '+
' `CMPCOD` VARCHAR(5) NULL DEFAULT NULL, '+
' `CMPBRN` VARCHAR(5) NULL DEFAULT NULL, '+
' `CMPDEP` VARCHAR(5) NULL DEFAULT NULL, '+
' `CMPSEC` VARCHAR(5) NULL DEFAULT NULL, '+
' `ENTUSR` VARCHAR(30) NULL DEFAULT NULL, '+
' `ENTDTE` DATETIME NULL DEFAULT NULL, '+
' `EDTUSR` VARCHAR(30) NULL DEFAULT NULL, '+
' `EDTDTE` DATETIME NULL DEFAULT NULL, '+
' PRIMARY KEY (`USRCOD`) '+
' ) '+
' COLLATE=''tis620_thai_ci'' '+
' ENGINE=InnoDB '
);
SQLPatchList[8] := TDbPatch.Create('0.57.6.22',8,'A',
'ALTER TABLE `ICMTTPOH` ADD COLUMN `POHAM0` DECIMAL(18,4) NULL DEFAULT NULL AFTER `POHQTY`'
);
{
SQLPatchList[1] := TDbPatch.Create('3.6.9.13',13,'A',
' CREATE TABLE if not exists `stock_permission` ( '
+' `stock_permission_id` INT(11) NOT NULL, '
+' `stock_permission_role_id` INT(11) NOT NULL, '
+' `stock_right_id` INT(11) NOT NULL, '
+' `stock_permission_type_id` INT(11) NOT NULL, '
+' `stock_permission_entry` VARCHAR(1) NULL DEFAULT NULL, '
+' `stock_permission_edit` VARCHAR(1) NULL DEFAULT NULL, '
+' `stock_permission_delete` VARCHAR(1) NULL DEFAULT NULL, '
+' `stock_permission_cancel` VARCHAR(1) NULL DEFAULT NULL, '
+' `stock_permission_approve` VARCHAR(1) NULL DEFAULT NULL, '
+' `stock_permission_option_1` VARCHAR(1) NULL DEFAULT NULL, '
+' `stock_permission_option_2` VARCHAR(1) NULL DEFAULT NULL, '
+' `stock_permission_option_3` VARCHAR(1) NULL DEFAULT NULL, '
+' `stock_permission_option_4` VARCHAR(1) NULL DEFAULT NULL, '
+' `stock_permission_option_5` VARCHAR(1) NULL DEFAULT NULL, '
+' `stock_permission_option_6` VARCHAR(1) NULL DEFAULT NULL, '
+' `stock_permission_option_7` VARCHAR(1) NULL DEFAULT NULL, '
+' `stock_permission_option_8` VARCHAR(1) NULL DEFAULT NULL, '
+' `stock_permission_option_9` VARCHAR(1) NULL DEFAULT NULL, '
+' `stock_permission_option_10` VARCHAR(1) NULL DEFAULT NULL '
+' ) '
+' COLLATE=tis620_thai_ci '
+' ENGINE=InnoDB; ');
SQLPatchList[2] := TDbPatch.Create('3.6.9.13',13,'A','DROP TABLE IF EXISTS `stock_right`;');
SQLPatchList[3] := TDbPatch.Create('3.6.9.13',13,'A',
' CREATE TABLE IF NOT EXISTS `stock_right` ( '
+' `stock_right_id` int(11) NOT NULL, '
+' `stock_right_group` int(11) DEFAULT NULL, '
+' `stock_right_name` varchar(250) NOT NULL, '
+' `hos_guid` varchar(38) DEFAULT NULL, '
+' PRIMARY KEY (`stock_right_id`), '
+' KEY `ix_hos_guid` (`hos_guid`) '
+' ) COLLATE=tis620_thai_ci ENGINE=InnoDB; ');
SQLPatchList[4] := TDbPatch.Create('3.6.9.13',13,'A',
' INSERT INTO `stock_right` (`stock_right_id`, `stock_right_group`, `stock_right_name`, `hos_guid`) VALUES '
+' (1, 1, ''ทำแผนจัดซื้อ'', NULL), '
+' (2, 1, ''ใบขอซื้อ (PR)'', NULL), '
+' (3, 1, ''จัดซื้อ - รับสินค้า'', NULL), '
+' (4, 1, ''ตรวจสอบ - ใบสั่งซื้อ'', NULL), '
+' (5, 1, ''การจ่ายเช็ค'', NULL), '
+' (6, 2, ''สินค้าในคลัง'', NULL), '
+' (7, 2, ''โอนสินค้า'', NULL), '
+' (8, 2, ''ปรับยอดคลัง'', NULL), '
+' (9, 2, ''ตรวจนับสินค้าในคลัง'', NULL), '
+' (10, 2, ''ตัดค้างจ่ายสินค้า'', NULL), '
+' (11, 2, ''ขอเบิกระหว่างคลังใหญ่'', NULL), '
+' (12, 3, ''สินค้าในคลังย่อย'', NULL), '
+' (13, 3, ''ตัดจ่ายสินค้า'', NULL), '
+' (14, 3, ''ปรับยอดหน่วยจ่าย'', NULL), '
+' (15, 3, ''โอนสินค้าในคลังย่อย'', NULL), '
+' (16, 3, ''ขอเบิกสินค้าจากคลังย่อย'', NULL), '
+' (17, 3, ''เบิกสินค้าจากคลังใหญ่'', NULL), '
+' (18, 4, ''รันสินค้าเข้าคลัง(พิเศษ)'', NULL), '
+' (19, 4, ''รับสินค้าเข้าคลัง / ตัดจ่าคลังย่อย(พิเศษ)'', NULL), '
+' (20, 4, ''ตัดจ่ายไม่เข้าคลัง'', NULL), '
+' (21, 5, ''คลัง'', NULL), '
+' (22, 5, ''รายการคลังย่อย'', NULL), '
+' (23, 5, ''รายการหน่วยสินค้า'', NULL), '
+' (24, 5, ''ประเภทรายการคลัง'', NULL), '
+' (25, 5, ''กลุ่มรายการ'', NULL), '
+' (26, 5, ''รายการสินค้า'', NULL), '
+' (27, 5, ''บริษัทผู้ผลิต'', NULL), '
+' (28, 5, ''บริษัทตัวแทนจำหน่าย'', NULL), '
+' (29, 5, ''ประเภทเงินจัดซื้อ'', NULL), '
+' (30, 5, ''ชนิดการจัดซื้อ'', NULL), '
+' (31, 5, ''การจัดซื้อร่วม'', NULL), '
+' (32, 5, ''ชื่อโครงการ'', NULL), '
+' (33, 5, ''ชื่อกรรมการตรวจสอบ'', NULL), '
+' (34, 5, ''ตำแหน่งกรรมการ'', NULL), '
+' (35, 5, ''รายการกรรมการ'', NULL), '
+' (36, 5, ''ตั้งงบประมาณ'', NULL), '
+' (37, 5, ''กำหนดเลขที่เอกสาร'', NULL), '
+' (38, 5, ''กำหนดค่า ABC'', NULL), '
+' (39, 6, ''รายงาน'', NULL), '
+' (40, 6, ''Inventory Summary'', NULL), '
+' (41, 6, ''สรุปยอดคงคลัง'', NULL), '
+' (42, 6, ''รายงานการสั่งซื้อสินค้า'', NULL), '
+' (43, 6, ''สอบถามประวัติการซื้อ'', NULL), '
+' (44, 6, ''รายงานการเบิกสินค้า'', NULL), '
+' (45, 6, ''สอบถามสินค้าที่หมดอายุ'', NULL), '
+' (46, 6, ''รายงานสถิติการรับ/จ่ายสินค้า คลังใหญ่'', NULL), '
+' (47, 6, ''รายงานสถิติการรับ/จ่ายสินค้า คลังย่อย'', NULL), '
+' (48, 7, ''Custom Report'', NULL), '
+' (49, 7, ''Report Designer'', NULL), '
+' (50, 7, ''GPO-VMI Report'', NULL), '
+' (51, 8, ''SQL Query'', NULL), '
+' (52, 8, ''Show SQL Trace'', NULL), '
+' (53, 8, ''Stock Uitl'', NULL), '
+' (54, 9, ''MySQL Monitor'', NULL), '
+' (55, 9, ''Query Builder'', NULL), '
+' (56, 10, ''Check New Version'', NULL), '
+' (57, 10, ''Upgrade stucture'', NULL), '
+' (58, 10, ''Store Procedure Manager'', NULL), '
+' (59, 10, ''Backup'', NULL), '
+' (60, 10, ''Restore'', NULL), '
+' (61, 10, ''ตั้งค่าการใช้งานระบบ'', NULL), '
+' (62, 11, ''User Manager'', NULL), '
+' (63, 11, ''User Permission'', NULL); '
);
SQLPatchList[5] := TDbPatch.Create('3.6.9.13',13,'A','ALTER TABLE stock_request ADD COLUMN `budget_runno` INT NULL ;');
SQLPatchList[6] := TDbPatch.Create('3.6.9.13',13,'A','ALTER TABLE stock_budget ADD COLUMN `stock_budget_yrrun` INT(11) NULL DEFAULT NULL;');
SQLPatchList[7] := TDbPatch.Create('3.6.9.13',13,'A','ALTER TABLE stock_budget ADD COLUMN `stock_budget_runno` INT(11) NULL DEFAULT NULL;');
SQLPatchList[8] := TDbPatch.Create('3.6.9.13',13,'A','alter table stock_user add column `stock_user_role_id` INT(11) NOT NULL;');
SQLPatchList[9] := TDbPatch.Create('3.6.9.13',13,'A','alter table stock_request add column `request_all_complete` CHAR(1) NULL DEFAULT NULL;');
SQLPatchList[10] := TDbPatch.Create('3.6.9.13',13,'A','alter table stock_po add `significant_number` VARCHAR(50) NULL DEFAULT NULL;');
SQLPatchList[11] := TDbPatch.Create('3.6.9.13',13,'A',
'ALTER TABLE `stock_manual_head` ADD COLUMN `transaction_datetime` DATETIME NULL ;'
+'update stock_manual_head set transaction_datetime = ADDDATE(curdate(),-1);');
SQLPatchList[12] := TDbPatch.Create('3.6.9.19',19,'A','ALTER TABLE `stock_subcard` ADD COLUMN `totalqty` INT(11) NULL DEFAULT NULL;');
SQLPatchList[13] := TDbPatch.Create('3.6.9.19',19,'A','ALTER TABLE `stock_subcard` ADD COLUMN `left_price` DOUBLE(22,3) NULL DEFAULT NULL;');
SQLPatchList[14] := TDbPatch.Create('3.6.9.19',19,'A','ALTER TABLE `stock_request` ADD COLUMN `approve` VARCHAR(1) NULL DEFAULT NULL;');
SQLPatchList[15] := TDbPatch.Create('3.6.9.27',27,'A',
' CREATE TABLE IF NOT EXISTS `stock_po_creditor` ( '+
' `stock_po_creditor_id` int(11) NOT NULL, '+
' `stock_po_id` int(11) NOT NULL, '+
' `creditor_date` date DEFAULT NULL, '+
' `creditor_document_no` varchar(100) DEFAULT NULL,'+
' `creditor_amount` double(15,3) DEFAULT NULL, '+
' `payment_date` date DEFAULT NULL, '+
' `stock_po_payment_status_id` int(11) DEFAULT NULL, '+
' `payment_document_no` varchar(100) DEFAULT NULL, '+
' PRIMARY KEY (`stock_po_creditor_id`), '+
' KEY `ix_stock_po_id` (`stock_po_id`) '+
' ) ; '
);
SQLPatchList[16] := TDbPatch.Create('3.6.9.27',27,'A',
' CREATE TABLE IF NOT EXISTS `stock_po_payment_status` ( '+
' `stock_po_payment_status_id` int(11) NOT NULL, '+
' `stock_po_payment_status_name` varchar(200) NOT NULL, '+
' PRIMARY KEY (`stock_po_payment_status_id`), '+
' UNIQUE KEY `stock_po_payment_status_name` (`stock_po_payment_status_name`) '+
' ) ; '
);
}
{
SQLPatchList[15] := TDbPatch.Create('3.6.9.21',21,'I',
'CREATE TABLE if not exists `stock_config` ( `stock_config_vno` VARCHAR(100) NOT NULL '
+',`stock_config_bno` INT NULL ,PRIMARY KEY (`stock_config_vno`) )'
+' DEFAULT CHARACTER SET = tis620 COLLATE = tis620_thai_ci;');
}
end;
procedure TfrmDbPatcher.SetIsNewVersion(const Value: boolean);
begin
FIsNewVersion := Value;
end;
procedure TfrmDbPatcher.Timer1Timer(Sender: TObject);
begin
if not NewVersion then close;
if ContinueCount>0 then
Dec(ContinueCount,1);
btnExecutePath.Caption:='Execute...('+inttostr(ContinueCount)+')';
if ContinueCount<=0 then
begin
btnExecutePath.Caption:='Execute...';
btnExecutePathClick(sender);
end;
end;
{ TDbPatch }
constructor TDbPatch.Create(const VersionNo: string;
const BuildNo: integer; Active: string; const SqlScript: string);
begin
FVersionNo := VersionNo;
FBuildNo := BuildNo;
FSql := SqlScript;
FActive := Active;
end;
end.
|
{$I-,Q-,R-,S-}
{Problema 8: Charcos de Lodo [Jeffey Wang, 2007]
El Granjero Juan ha salido de su casa temprano a las 6 AM para el
ordeño diario de Bessie. Sin embargo, en la tarde anterior el vio una
fuerte lluvia, y los campos están algo enlodados. GJ comienza en el
punto (0,0) en el plano de coordenadas y se dirige hacia Bessie quien
está ubicada en el punto (X, Y) (-500 <= X <= 500; -500 <= Y <= 500).
El puede ver N charcos de lodo, ubicados en los puntos (A_i, B_i) (-
500 <= A_i <= 500; -500 <= B_i <= 500)del campo. Cada charco ocupa
solo el punto en el que está.
Habiendo comprado recientemente botas nuevas, el Granjero Juan no
quiere absolutamente ensuciarlas parándose sobre lodo, pero quiere
llegar a donde Bessie tan rápido como sea posible. A él ya se le hizo
tarde debido a que él tuvo que contar todos los charcos. Si el
Granjero Juan puede viajar únicamente paralelo a los ejes y girar en
puntos con coordenadas enteras, ¿cuál es la distancia más corta que él
debe viajar para llegar a donde Bessie y mantener limpias sus botas?
Siempre existirá un camino sin lodo que el Granjero Juan pueda tomar
para llegar a donde Bessie.
NOMBRE DEL PROBLEMA: mud
FORMATO DE ENTRADA:
* Línea 1: Tres enteros separados por espacio: X, Y, y N.
* Líneas 2..N+1: la línea i+1 contiene dos enteros separados por
espacio
ENTRADA EJEMPLO (archivo mud.in):
1 2 7
0 2
-1 3
3 1
1 1
4 2
-1 1
2 2
DETALLES DE LA ENTRADA:
Bessie está en el punto (1, 2). El Granjero Juan ve 7 charcos de lodo;
ubicados en los puntos: (0, 2); (-1, 3); (3, 1); (1, 1); (4, 2); (-1,
1). Gráficamente:
4 . . . . . . . .
3 . M . . . . . .
Y 2 . . M B M . M .
1 . M . M . M . .
0 . . * . . . . .
-1 . . . . . . . .
-2-1 0 1 2 3 4 5
X
FORMATO DE SALIDA:
* Línea 1: La distancia mínima que el Granjero Juan debe viajar para
llegar a donde está Bessie sin parase en lodo.
SALIDA EJEMPLO (archivo mud.out):
11
DETALLES DE LA SALIDA:
El mejor camino para el Granjero Juan es (0, 0); (-1, 0); (-2, 0);
(-2, 1); (-2, 2); (-2, 3); (-2, 4); (-1, 4); (0, 4); (0, 3); (1, 3);
y (1,2), llegando finalmente a donde Bessie:
4 ******* . . . .
3 * M . * . . . .
Y 2 * . M B M . M .
1 * M . M . M . .
0 ***** . . . . .
-1 . . . . . . . .
-2-1 0 1 2 3 4 5
X
}
const
mx = 501;
mov : array[1..4,1..2] of shortint
= ((1,0),(0,1),(-1,0),(0,-1));
var
fe,fs : text;
n : longint;
posi : array[1..2] of longint;
tab : array[-mx..mx,-mx..mx] of longint;
sav : array[boolean,1..mx*mx,1..2] of longint;
procedure open;
var
i,a,b : longint;
begin
assign(fe,'mud.in'); reset(fe);
assign(fs,'mud.out'); rewrite(fs);
readln(fe,posi[1],posi[2],n);
for i:=1 to n do
begin
readln(fe,a,b);
tab[a,b]:=-1;
end;
close(fe);
end;
procedure closer(x : longint);
begin
writeln(fs,x);
close(fs);
halt;
end;
procedure work;
var
cp,ch,h1,h2,i,j : longint;
s : boolean;
z : array[1..2] of longint;
begin
cp:=1; ch:=0; s:=true;
sav[s,1,1]:=0; sav[s,1,2]:=0;
while cp > 0 do
begin
for i:=1 to cp do
begin
h1:=sav[s,i,1]; h2:=sav[s,i,2];
for j:=1 to 4 do
begin
z[1]:=h1 + mov[j,1]; z[2]:=h2 + mov[j,2];
if (z[1] > -501) and (z[1] < 501) and (z[2] > -501) and (z[2] < 501)
and (tab[z[1],z[2]] = 0) then
begin
if (z[1] = posi[1]) and (z[2] = posi[2]) then
closer(tab[h1,h2] + 1);
inc(ch);
sav[not s,ch,1]:=z[1];
sav[not s,ch,2]:=z[2];
tab[z[1],z[2]]:=tab[h1,h2] + 1;
end;
end;
end;
s:=not s;
cp:=ch;
ch:=0;
end;
end;
begin
open;
work;
end. |
unit HVA;
// HVA Unit By Banshee, from Stucuk's code.
// Written using the tibsun-hva.doc by The Profound Eol
{$INCLUDE source/Global_Conditionals.inc}
interface
uses dialogs,sysutils,dglOpenGL, Voxel, Geometry, BasicMathsTypes, math3d,
BasicFunctions;
type
THVA_Main_Header = record
FilePath: array[1..16] of Char; // ASCIIZ string
N_Frames, // Number of animation frames
N_Sections : Longword; // Number of voxel sections described
end;
TSectionName = array[1..16] of Char; // ASCIIZ string - name of section
TTransformMatrix = array[1..3,1..4] of Single;
THVAData = record
SectionName : TSectionName;
end;
PHVA = ^THVA;
THVA = class
Header : THVA_Main_Header;
Data : array of THVAData;
TransformMatrices : array of TTransformMatrix;
p_Voxel : PVoxel;
private
procedure ClearMemory;
procedure MakeABlankHVA;
function LoadFromFile(const _Filename : string): boolean;
procedure ClearFrame(_Number : integer);
procedure ClearTM(_Number : integer);
Function CorrectAngle(_Angle : Single) : Single;
procedure CopyTM(Source, Dest : integer);
procedure CopyFrameTM(Source, Dest : integer);
public
// Constructors/Destructors
Constructor Create(); overload;
constructor Create(const _Filename : string; _pVoxel : PVoxel); overload;
constructor Create(const _HVA: THVA); overload;
Destructor Destroy; override;
// I/O stuff
procedure Clear;
procedure LoadFile(const _Filename : string; _pVoxel : PVoxel);
Procedure SaveFile(const _Filename : string);
procedure WestwoodToOpenGLCoordinates;
procedure OpenGLToWestwoodCoordinates;
// Frame Operations
procedure AddBlankFrame;
Procedure InsertFrame(FrameNumber : integer);
Procedure CopyFrame(FrameNumber : integer);
Procedure DeleteFrame(FrameNumber : Integer);
// Section Operations
procedure AddBlankSection;
Procedure InsertSection(_SectionNumber : integer);
Procedure CopySection(_Source,_Dest : integer); overload;
Procedure CopySection(_Source,_Dest : integer; const HVA: THVA); overload;
Procedure DeleteSection(_SectionNumber : Integer);
// Gets
Function GetMatrix(_Section,_Frames : Integer) : TMatrix; overload;
Procedure GetMatrix(var _Res : TTransformMatrix; _Section,_Frames : Integer); overload;
Function GetTMValue(_Row,_Col,_Section,_Frames : integer) : single;
Function GetPosition(_Frame,_Section : Integer) : TVector3f;
Function GetAngle_RAD(_Section,_Frames : Integer) : TVector3f;
Function GetAngle_DEG(_Section,_Frames : Integer) : TVector3f;
Function GetAngle_DEG_Correct(_Section,_Frames : Integer) : TVector3f;
// Sets
Procedure SetMatrix(const _M : TMatrix; _Frame,_Section : Integer); overload;
Procedure SetMatrix(const _M : TTransformMatrix; _Frame,_Section : Integer); overload;
Procedure SetTMValue(_Frame,_Section,_Row,_Col : Integer; _Value : single);
Procedure SetPosition(_Frame,_Section : Integer; _Position : TVector3f);
Function SetAngle(_Section,_Frames : Integer; _x,_y,_z : single) : TVector3f;
// Miscelaneous
Procedure ApplyMatrix(_VoxelScale : TVector3f; _Section : Integer; _Frame: integer);
Procedure MovePosition(_Frame,_Section : Integer; _X,_Y,_Z : single);
// Assign
procedure Assign(const _HVA: THVA);
end;
THVAVOXEL = (HVhva,HVvoxel);
implementation
///////////////////////////////////////////////////////////
//////// New HVA Engine Rock And Roll HERE ////////////////
///////////////////////////////////////////////////////////
Constructor THVA.Create();
begin
p_Voxel := nil;
MakeABlankHVA;
end;
Constructor THVA.Create (const _Filename : string; _pVoxel : PVoxel);
begin
LoadFile(_Filename,_pVoxel);
end;
constructor THVA.Create(const _HVA: THVA);
begin
Assign(_HVA);
end;
Destructor THVA.Destroy;
begin
ClearMemory;
inherited Destroy;
end;
procedure THVA.ClearMemory;
begin
SetLength(TransformMatrices,0);
end;
procedure THVA.Clear;
begin
ClearMemory;
MakeABlankHVA;
end;
// Gives the default settings for invalid HVAs
procedure THVA.MakeABlankHVA;
var
x,i : byte;
begin
Header.N_Frames := 0;
if (p_Voxel <> nil) then
begin
Header.N_Sections := p_Voxel^.Header.NumSections;
end
else
begin
Header.N_Sections := 1;
end;
Setlength(Data,Header.N_Sections);
for x := 1 to 16 do
Header.FilePath[x] := #0;
if (p_Voxel <> nil) then
begin
for i := 0 to p_Voxel^.Header.NumSections-1 do
for x := 1 to 16 do
Data[i].SectionName[x] := p_Voxel^.section[i].Header.Name[x];
end;
AddBlankFrame;
end;
Procedure THVA.SaveFile(const _Filename : string);
var
f : file;
wrote,x : integer;
begin
OpenGLToWestwoodCoordinates;
//SetCharArray('',HVAFile.Header.FilePath);
for x := 1 to 16 do
Header.FilePath[x] := #0;
AssignFile(F,_Filename); // Open file
Rewrite(F,1); // Goto first byte?
BlockWrite(F,Header,Sizeof(THVA_Main_Header),wrote); // Write Header
{$ifdef DEBUG_HVA_FILE}
Showmessage(_Filename);
showmessage(inttostr(Header.N_Sections));
showmessage(inttostr(Header.N_Frames));
showmessage(inttostr(wrote));
{$endif}
For x := 0 to High(Data) do
BlockWrite(F,Data[x].SectionName,Sizeof(TSectionName),wrote);
{$ifdef DEBUG_HVA_FILE}
showmessage(inttostr(wrote));
{$endif}
For x := 0 to High(TransformMatrices) do
BlockWrite(F,TransformMatrices[x],Sizeof(TTransformMatrix),wrote);
{$ifdef DEBUG_HVA_FILE}
showmessage(inttostr(wrote));
{$endif}
CloseFile(f);
WestwoodToOpenGLCoordinates;
end;
procedure THVA.LoadFile(const _Filename : string; _pVoxel : PVoxel);
begin
p_Voxel := _pVoxel;
ClearMemory;
if not LoadFromFile(_Filename) then MakeABlankHVA;
end;
function THVA.LoadFromFile(const _Filename: String): boolean;
var
f : file;
x: integer;
begin
Result := false;
if not FileExists(_Filename) then exit;
AssignFile(F,_Filename); // Open file
Reset(F,1); // Goto first byte?
BlockRead(F,Header,Sizeof(THVA_Main_Header)); // Read Header
SetLength(Data,Header.N_Sections);
For x := 0 to High(Data) do
BlockRead(F,Data[x].SectionName,Sizeof(TSectionName));
SetLength(TransformMatrices,Header.N_Frames*Header.N_Sections);
For x := 0 to High(TransformMatrices) do
BlockRead(F,TransformMatrices[x],Sizeof(TTransformMatrix));
CloseFile(f);
If Header.N_Frames < 1 then
exit;
WestwoodToOpenGLCoordinates;
Result := True;
end;
// This function converts the Westwood coordinates into OpenGL's
// (x,y,z) becomes (y,z,x)
procedure THVA.WestwoodToOpenGLCoordinates;
var
i : integer;
Temp: single;
begin
for i := Low(TransformMatrices) to High(TransformMatrices) do
begin
Temp := TransformMatrices[i][1][1];
TransformMatrices[i][1][1] := TransformMatrices[i][2][2];
TransformMatrices[i][2][2] := TransformMatrices[i][3][3];
TransformMatrices[i][3][3] := Temp;
Temp := TransformMatrices[i][1][2];
TransformMatrices[i][1][2] := TransformMatrices[i][2][3];
TransformMatrices[i][2][3] := TransformMatrices[i][3][1];
TransformMatrices[i][3][1] := Temp;
Temp := TransformMatrices[i][1][3];
TransformMatrices[i][1][3] := TransformMatrices[i][2][1];
TransformMatrices[i][2][1] := TransformMatrices[i][3][2];
TransformMatrices[i][3][2] := Temp;
Temp := TransformMatrices[i][1][4];
TransformMatrices[i][1][4] := TransformMatrices[i][2][4];
TransformMatrices[i][2][4] := TransformMatrices[i][3][4];
TransformMatrices[i][3][4] := Temp;
end;
end;
// This function converts the OpenGL coordinates into Westwood's
// (x,y,z) becomes (z,x,y)
procedure THVA.OpenGLToWestwoodCoordinates;
var
i : integer;
Temp: single;
begin
for i := Low(TransformMatrices) to High(TransformMatrices) do
begin
Temp := TransformMatrices[i][1][1];
TransformMatrices[i][1][1] := TransformMatrices[i][3][3];
TransformMatrices[i][3][3] := TransformMatrices[i][2][2];
TransformMatrices[i][2][2] := Temp;
Temp := TransformMatrices[i][1][2];
TransformMatrices[i][1][2] := TransformMatrices[i][3][1];
TransformMatrices[i][3][1] := TransformMatrices[i][2][3];
TransformMatrices[i][2][3] := Temp;
Temp := TransformMatrices[i][1][3];
TransformMatrices[i][1][3] := TransformMatrices[i][3][2];
TransformMatrices[i][3][2] := TransformMatrices[i][2][1];
TransformMatrices[i][2][1] := Temp;
Temp := TransformMatrices[i][1][4];
TransformMatrices[i][1][4] := TransformMatrices[i][3][4];
TransformMatrices[i][3][4] := TransformMatrices[i][2][4];
TransformMatrices[i][2][4] := Temp;
end;
end;
// Frame Operations
procedure THVA.AddBlankFrame;
begin
inc(Header.N_Frames);
SetLength(TransformMatrices,Header.N_Frames*Header.N_Sections);
ClearFrame(Header.N_Frames-1);
end;
Procedure THVA.InsertFrame(FrameNumber : integer);
var
x,i : integer;
TransformMatricesTemp : array of TTransformMatrix;
begin
// Prepare a temporary Transformation Matrix Copy.
SetLength(TransformMatricesTemp,Header.N_Frames*Header.N_Sections);
// Copy the transformation matrixes from the HVA to the temp
for x := 0 to Header.N_Frames-1 do
for i := 0 to Header.N_Sections-1 do
GetMatrix(TransformMatricesTemp[x*Header.N_Sections+i],i,x);
// Increase the ammount of frames from the HVA.
AddBlankFrame;
// Copy all info from the frames till the current frame.
if FrameNumber > 0 then
for x := 0 to FrameNumber do
for i := 0 to Header.N_Sections-1 do
SetMatrix(TransformMatricesTemp[x*Header.N_Sections+i],x,i);
// Create new frames for the selected frame.
ClearFrame(FrameNumber);
// Copy the final part.
if FrameNumber+1 < Header.N_Frames-1 then
for x := FrameNumber+2 to Header.N_Frames-1 do
for i := 0 to Header.N_Sections-1 do
SetMatrix(TransformMatricesTemp[(x-1)*Header.N_Sections+i],x,i);
end;
Procedure THVA.CopyFrame(FrameNumber : integer);
begin
InsertFrame(FrameNumber);
CopyFrameTM(FrameNumber,FrameNumber+1);
end;
Procedure THVA.DeleteFrame(FrameNumber : Integer);
var
x,i : integer;
TransformMatricesTemp : array of TTransformMatrix;
begin
// Prepare a temporary Transformation Matrix Copy.
SetLength(TransformMatricesTemp,Header.N_Frames*Header.N_Sections);
// Copy the transformation matrixes from the HVA to the temp
for x := 0 to Header.N_Frames-1 do
for i := 0 to Header.N_Sections-1 do
GetMatrix(TransformMatricesTemp[x*Header.N_Sections+i],i,x);
// Copy all info from the frames till the current frame.
if FrameNumber > 0 then
for x := 0 to FrameNumber do
for i := 0 to Header.N_Sections-1 do
SetMatrix(TransformMatricesTemp[x*Header.N_Sections+i],x,i);
// Decrease the ammount of frames from the HVA.
Dec(Header.N_Frames);
SetLength(TransformMatrices,Header.N_Frames*Header.N_Sections);
// Copy the final part.
for x := FrameNumber+1 to Header.N_Frames-1 do
for i := 0 to Header.N_Sections-1 do
SetMatrix(TransformMatricesTemp[x*Header.N_Sections+i],x-1,i);
end;
// The number received here must be the frame as the user see.
// starting from frame #1.
procedure THVA.ClearFrame(_Number : Integer);
var
x : integer;
begin
for x := 0 to Header.N_Sections-1 do
ClearTM(_Number*Header.N_Sections+x);
end;
// Section Operations
procedure THVA.AddBlankSection;
begin
InsertSection(Header.N_Sections);
end;
procedure THVA.InsertSection(_SectionNumber : integer);
var
i,f,s,oldNumSections : integer;
begin
oldNumSections := Header.N_Sections;
inc(Header.N_Sections);
SetLength(TransformMatrices,Header.N_Frames*Header.N_Sections);
i := High(TransformMatrices);
f := Header.N_Frames - 1;
while f >= 0 do
begin
s := oldNumSections - 1;
// copy frames that are after the added one.
while s >= _SectionNumber do
begin
CopyTM((f * oldNumSections) + s,i);
dec(s);
dec(i);
end;
// make a blank current one for the inserted section.
ClearTM(i);
dec(i);
dec(s);
// copy frames that are before the added one.
while s >= 0 do
begin
CopyTM((f * oldNumSections) + s,i);
dec(s);
dec(i);
end;
dec(f);
end;
// Now we add the data part:
SetLength(Data,Header.N_Sections);
i := Header.N_Sections-1;
while i > _SectionNumber do
begin
for s := 1 to 16 do
begin
Data[i].SectionName[s] := Data[i-1].SectionName[s];
end;
dec(i);
end;
end;
procedure THVA.CopySection(_Source,_Dest : integer);
var
f : integer;
begin
for f := 0 to (Header.N_frames - 1) do
begin
CopyTM((f * Header.N_Sections) + _Source,(f * Header.N_Sections) + _Dest);
end;
for f := 1 to 16 do
begin
Data[_Dest].SectionName[f] := Data[_Source].SectionName[f];
end;
end;
Procedure THVA.CopySection(_Source,_Dest : integer; const HVA: THVA);
var
f,y,z : integer;
begin
for f := 0 to (Header.N_frames - 1) do
begin
for y := 1 to 3 do
for z := 1 to 4 do
TransformMatrices[(f * Header.N_Sections) + _Dest,y,z] := HVA.TransformMatrices[(f * Header.N_Sections) + _Source,y,z];
end;
for f := 1 to 16 do
begin
Data[_Dest].SectionName[f] := HVA.Data[_Source].SectionName[f];
end;
end;
procedure THVA.DeleteSection(_SectionNumber : Integer);
var
TempTMs : array of TTransformMatrix;
i,f,s,y,z,OldNumSections : integer;
begin
// The method below might be a bit stupid, but does its job.
// Let's backup the existing TransformationMatrices.
SetLength(TempTMs,High(TransformMatrices)+1);
for i := Low(TempTMs) to High(TempTMs) do
begin
for y := 1 to 3 do
for z := 1 to 4 do
TempTMs[i,y,z] := TransformMatrices[i,y,z];
end;
// Now we mess up with the TransformMatrices.
OldNumSections := Header.N_Sections;
dec(Header.N_Sections);
SetLength(TransformMatrices,Header.N_Frames*Header.N_Sections);
f := 0;
i := 0;
while f < Header.N_Frames do
begin
s := 0;
// copy all previous sections.
while s < _SectionNumber do
begin
for y := 1 to 3 do
for z := 1 to 4 do
TransformMatrices[i,y,z] := TempTMs[(f*OldNumSections)+s,y,z];
inc(s);
inc(i);
end;
// ignore current section
inc(s);
// copy all sections after it.
while s < OldNumSections do
begin
for y := 1 to 3 do
for z := 1 to 4 do
TransformMatrices[i,y,z] := TempTMs[(f*OldNumSections)+s,y,z];
inc(s);
inc(i);
end;
inc(f);
end;
// Let's update the data content
i := _SectionNumber;
while i < Header.N_Sections do
begin
for s := 1 to 16 do
begin
Data[i].SectionName[s] := Data[i+1].SectionName[s];
end;
inc(i);
end;
SetLength(Data,Header.N_Sections);
end;
procedure THVA.ClearTM(_Number : Integer);
var
x,y : integer;
begin
for x := 1 to 3 do
for y := 1 to 4 do
TransformMatrices[_Number][x][y] := 0;
TransformMatrices[_Number][1][1] := 1;
TransformMatrices[_Number][2][2] := 1;
TransformMatrices[_Number][3][3] := 1;
end;
Function THVA.GetTMValue(_Row,_Col,_Section,_Frames : integer) : single;
begin
Result := TransformMatrices[_Frames*Header.N_Sections+_Section][_Row][_Col];
end;
Function THVA.GetMatrix(_Section,_Frames : Integer) : TMatrix;
var
x,y : integer;
begin
Result := IdentityMatrix;
for x := 1 to 3 do
for y := 1 to 4 do
Result[x-1][y-1] := GetTMValue(x,y,_Section,_Frames);
end;
Procedure THVA.GetMatrix(var _Res : TTransformMatrix; _Section,_Frames : Integer);
var
x,y : integer;
begin
for x := 1 to 3 do
for y := 1 to 4 do
_Res[x][y] := GetTMValue(x,y,_Section,_Frames);
end;
Procedure THVA.SetMatrix(const _M : TMatrix; _Frame,_Section : Integer);
var
x,y : integer;
begin
for x := 1 to 3 do
for y := 1 to 4 do
TransformMatrices[_Frame*Header.N_Sections+_Section][x][y] := _m[x-1][y-1];
end;
Procedure THVA.SetMatrix(const _M : TTransformMatrix; _Frame,_Section : Integer);
var
x,y : integer;
begin
for x := 1 to 3 do
for y := 1 to 4 do
TransformMatrices[_Frame*Header.N_Sections+_Section][x][y] := _m[x][y];
end;
Procedure THVA.ApplyMatrix(_VoxelScale : TVector3f; _Section : Integer; _Frame: integer);
var
Matrix : TGLMatrixf4;
Scale : single;
begin
if _Section = -1 then
begin
Exit;
end;
if p_Voxel <> nil then
Scale := p_Voxel^.Section[_Section].Tailer.Det
else
Scale := 1/12;
if Header.N_Sections > 0 then
begin
Matrix[0,0] := GetTMValue(1,1,_Section,_Frame);
Matrix[0,1] := GetTMValue(2,1,_Section,_Frame);
Matrix[0,2] := GetTMValue(3,1,_Section,_Frame);
Matrix[0,3] := 0;
Matrix[1,0] := GetTMValue(1,2,_Section,_Frame);
Matrix[1,1] := GetTMValue(2,2,_Section,_Frame);
Matrix[1,2] := GetTMValue(3,2,_Section,_Frame);
Matrix[1,3] := 0;
Matrix[2,0] := GetTMValue(1,3,_Section,_Frame);
Matrix[2,1] := GetTMValue(2,3,_Section,_Frame);
Matrix[2,2] := GetTMValue(3,3,_Section,_Frame);
Matrix[2,3] := 0;
Matrix[3,0] := (GetTMValue(1,4,_Section,_Frame)* Scale) * _VoxelScale.X;
Matrix[3,1] := (GetTMValue(2,4,_Section,_Frame)* Scale) * _VoxelScale.Y;
Matrix[3,2] := (GetTMValue(3,4,_Section,_Frame)* Scale) * _VoxelScale.Z;
Matrix[3,3] := 1;
end
else
begin
Matrix[0,0] := 1;
Matrix[0,1] := 0;
Matrix[0,2] := 0;
Matrix[0,3] := 0;
Matrix[1,0] := 0;
Matrix[1,1] := 1;
Matrix[1,2] := 0;
Matrix[1,3] := 0;
Matrix[2,0] := 0;
Matrix[2,1] := 0;
Matrix[2,2] := 1;
Matrix[2,3] := 0;
Matrix[3,0] := 0;
Matrix[3,1] := 0;
Matrix[3,2] := 0;
Matrix[3,3] := 1;
end;
glMultMatrixf(@Matrix[0,0]);
end;
Procedure THVA.MovePosition(_Frame,_Section : Integer; _X,_Y,_Z : single);
var
HVAD : integer;
begin
HVAD := _Frame*Header.N_Sections+_Section;
TransformMatrices[HVAD][1][4] := TransformMatrices[HVAD][1][4] + (_X);
TransformMatrices[HVAD][2][4] := TransformMatrices[HVAD][2][4] + (_Y);
TransformMatrices[HVAD][3][4] := TransformMatrices[HVAD][3][4] + (_Z);
end;
Procedure THVA.SetPosition(_Frame,_Section : Integer; _Position : TVector3f);
var
HVAD : integer;
Det : single;
begin
HVAD := _Frame*Header.N_Sections+_Section;
Det := p_Voxel^.Section[_Section].Tailer.Det;
TransformMatrices[HVAD][1][4] := _Position.X / Det;
TransformMatrices[HVAD][2][4] := _Position.Y / Det;
TransformMatrices[HVAD][3][4] := _Position.Z / Det;
end;
Function THVA.GetPosition(_Frame,_Section : Integer) : TVector3f;
var
HVAD : integer;
Det : single;
begin
HVAD := _Frame*Header.N_Sections+_Section;
Det := p_Voxel^.Section[_Section].Tailer.Det;
Result := SetVector(0,0,0);
if TransformMatrices[HVAD][1][4] > 0 then
Result.X := TransformMatrices[HVAD][1][4] * Det;
if TransformMatrices[HVAD][2][4] > 0 then
Result.Y := TransformMatrices[HVAD][2][4] * Det;
if TransformMatrices[HVAD][3][4] > 0 then
Result.Z := TransformMatrices[HVAD][3][4] * Det;
end;
Function THVA.GetAngle_RAD(_Section,_Frames : Integer) : TVector3f;
var
M : TMatrix;
T : TTransformations;
begin
M := GetMatrix(_Section,_Frames);
MatrixDecompose(M,T);
Result.X := T[ttRotateX];
Result.Y := T[ttRotateY];
Result.Z := T[ttRotateZ];
end;
Function THVA.GetAngle_DEG(_Section,_Frames : Integer) : TVector3f;
var
Angles : TVector3f;
begin
Angles := GetAngle_RAD(_Section,_Frames);
Result.X := RadToDeg(Angles.X);
Result.Y := RadToDeg(Angles.Y);
Result.Z := RadToDeg(Angles.Z);
end;
Function THVA.GetAngle_DEG_Correct(_Section,_Frames : Integer) : TVector3f;
var
Angles : TVector3f;
begin
Angles := GetAngle_RAD(_Section,_Frames);
Result.X := CorrectAngle(RadToDeg(Angles.X));
Result.Y := CorrectAngle(RadToDeg(Angles.Y));
Result.Z := CorrectAngle(RadToDeg(Angles.Z));
end;
Function THVA.CorrectAngle(_Angle : Single) : Single;
var
Ang90 : single;
begin
Ang90 := Pi/2;
If _Angle < (-Ang90) then
_Angle := Pi + _Angle
else if _Angle > Ang90 then
_Angle := Ang90 - _Angle;
Result := _Angle;
end;
Procedure THVA.SetTMValue(_Frame,_Section,_Row,_Col : Integer; _Value : single);
begin
TransformMatrices[_Frame*Header.N_Sections+_Section][_Row][_Col] := _Value;
end;
Function THVA.SetAngle(_Section,_Frames : Integer; _x,_y,_z : single) : TVector3f;
var
M : TMatrix;
begin
M := GetMatrix(_Section,_Frames);
M := Pitch(M,DegtoRad(_X));
M := Turn(M,DegtoRad(_Y));
M := Roll(M,DegtoRad(_Z));
SetMatrix(M,_Frames,_Section);
end;
procedure THVA.CopyFrameTM(Source, Dest : integer);
var
y,z,i : integer;
begin
for i := 0 to Header.N_Sections-1 do
for y := 1 to 3 do
for z := 1 to 4 do
TransformMatrices[(Dest)*Header.N_Sections+i][y][z] := TransformMatrices[(Source)*Header.N_Sections+i][y][z];
end;
procedure THVA.CopyTM(Source, Dest : integer);
var
y,z : integer;
begin
for y := 1 to 3 do
for z := 1 to 4 do
TransformMatrices[Dest,y,z] := TransformMatrices[Source,y,z];
end;
// Assign
procedure THVA.Assign(const _HVA: THVA);
var
i,j,k: integer;
begin
for i := 1 to 16 do
Header.FilePath[i] := _HVA.Header.FilePath[i];
Header.N_Frames := _HVA.Header.N_Frames;
Header.N_Sections := _HVA.Header.N_Sections;
SetLength(Data,High(_HVA.Data)+1);
for i := Low(Data) to High(Data) do
begin
for j := 1 to 16 do
Data[i].SectionName[j] := _HVA.Data[i].SectionName[j];
end;
p_Voxel := _HVA.p_Voxel;
SetLength(TransformMatrices,High(_HVA.TransformMatrices)+1);
for i := Low(TransformMatrices) to High(TransformMatrices) do
begin
for j := 1 to 3 do
for k := 1 to 4 do
TransformMatrices[i][j][k] := _HVA.TransformMatrices[i][j][k];
end;
end;
end.
|
unit TextList;
{
Bombela
20/06/2004
20/06/2004
Petite StringList limitée à 255 strings.
Chaque item à une couleur et un statut de possiblilitée d'être selectionné.
}
interface
type TListItem = record
Text: String;
Color: byte;
Selectable: boolean;
Next: pointer;
end;
type PListItem = ^TListItem;
type TStringList = object
private
FCount: byte;
FirstItem: PListItem;
public
constructor Init;
destructor Free;
function Add(Text: string; Color: byte; Selectable: boolean): boolean;
function Count: byte;
function Del(Index: byte): boolean;
function Ins(Index: byte; Text: string; Color: byte; Selectable: boolean): boolean;
procedure Clear;
function Get(Index: byte; var Text: string; var Color: byte; var Selectable: boolean): boolean;
function GetText(Index: byte; var Text: string): boolean;
function GetData(Index: byte; var Color: byte): boolean;
function GetSelectable(Index: byte; var Selectable: boolean): boolean;
function Change(Index: byte; Text: string; Color: byte; Selectable: boolean): boolean;
end;
implementation
constructor TStringList.Init;
begin
FCount := 0;
FirstItem := nil;
end;
destructor TStringList.Free;
var i: byte;
begin
Clear;
end;
function TStringList.Add(Text: string; Color: byte; Selectable: boolean): boolean;
var Item: PListItem;
begin
if FCount < 255 then
begin
If FCount = 0 then
begin
new(Item);
FirstItem := Item;
end else
begin
Item := FirstItem;
while (Item^.Next <> nil) do Item := Item^.Next;
new(PListItem(Item^.Next));
Item := Item^.Next;
end;
Item^.Next := nil;
Item^.Text := Text;
Item^.Color := Color;
Item^.Selectable := Selectable;
inc(FCount);
Add := true;
end else Add := false;
end;
function TStringList.Get(Index: byte; var Text: string; var Color: byte; var Selectable: boolean): boolean;
var i: byte; Item: PListItem;
begin
if (Index < FCount) then
begin
Item := FirstItem;
if Index > 0 then
for i := 0 to Index-1 do Item := Item^.Next;
Text := Item^.Text;
Color := Item^.Color;
Selectable := Item^.Selectable;
Get := true;
end else Get := false;
end;
function TStringList.GetText(Index: byte; var Text: string): boolean;
var Color: byte;
Selectable: boolean;
begin
GetText := Get(Index,Text,Color,Selectable);
end;
function TStringList.GetData(Index: byte; var Color: byte): boolean;
var Text: string;
Selectable: boolean;
begin
GetData := Get(Index,Text,Color,Selectable);
end;
function TStringList.GetSelectable(Index: byte; var Selectable: boolean): boolean;
var Text: string;
Color: byte;
begin
GetSelectable := Get(Index,Text,Color,Selectable);
end;
function TStringList.Count: byte;
begin
Count := FCount;
end;
function TStringList.Del(Index: byte): boolean;
var i: byte;
Item1, Item2: PListItem;
begin
if Index < FCount then
begin
if Index = 0 then
begin
Item1 := FirstItem^.Next;
Dispose(FirstItem);
FirstItem := Item1;
end else
begin
Item1 := FirstItem;
if Index > 1 then
for i := 0 to Index-2 do Item1 := Item1^.Next;
Item2 := PListItem(Item1^.Next)^.Next;
Dispose(PListItem(Item1^.Next));
Item1^.Next := Item2;
end;
dec(FCount);
Del := true;
end else Del := false;
end;
function TStringList.Ins(Index: byte; Text: string; Color: byte; Selectable: boolean): boolean;
var i: byte;
Item1, Item2: PListItem;
begin
if (Index < FCount) and (FCount < 255) then
begin
if Index = 0 then
begin
Item1 := FirstItem;
new(FirstItem);
FirstItem^.Next := Item1;
Item1 := FirstItem;
end else
begin
Item1 := FirstItem;
if Index > 1 then
if Index = 2 then Item1 := FirstItem^.Next
else for i := 0 to Index-2 do Item1 := Item1^.Next;
Item2 := Item1^.Next;
new(PListItem(Item1^.Next));
Item1 := Item1^.Next;
Item1^.Next := Item2;
end;
Item1^.Text := Text;
Item1^.Color := Color;
Item1^.Selectable := Selectable;
inc(FCount);
Ins := true;
end else Ins := false;
end;
procedure TStringList.Clear;
var Item: PListItem;
begin
Item := FirstItem;
while Item <> nil do
begin
Item := Item^.Next;
Dispose(FirstItem);
FirstItem := Item;
end;
FCount := 0;
end;
function TStringList.Change(Index: byte; Text: string; Color: byte; Selectable: boolean): boolean;
var i: byte;
Item: PListItem;
begin
if Index < FCount then
begin
Item := FirstItem;
If Index > 0 then for i := 0 to index do Item := Item^.Next;
Item^.Text := Text;
Item^.Color := Color;
Item^.Selectable := Selectable;
end;
end;
end. |
{ -------------------------------------------------------------
Leonardo Pignataro's TETRIS - versão 1.0
* Incluído para demonstrar os recursos do Pascal ZIM!
Autor : Leonardo Pignataro - Beta Tester
Contato : leopignataro@brturbo.com
Este código fonte teve de sofrer algumas adaptações para
torná-lo compatível com o Pascalzim. A versão original
pode ser encontrada no seguinte URL:
http://www.geocities.com/leopignataro86/tetris.zip
------------------------------------------------------------- }
{ -------------------------------------------------------------
Funcionamento geral do programa:
Basicamente, há um grid, que armazena em memória o estado
das 'casas' do jogo: quais estão preenchidas, e de que cor.
Este grid é representado na tela, sendo que cada casa ocupa
dois caracteres consecutivos, sendo eles caracteres #219.
Há uma peça caindo no grid (tipo T_Object, variavel obj),
controlada pelo usuário, e também uma outra fixa ao lado do
grid (mesmo tipo, variavel next) que indica a próxima peça
a cair no grid. A velocidade de queda está relacionada com
o level em que está o jogador.
Todas essas variáveis - grid, obj, next - entre outras,
são globais e os módulos (procedures e functions) do progra-
ma fazem acesso direto a elas. Geralmente, evita-se isso,
passando variáveis como parâmetros, para que se crie módulos
portáveis. Contudo, a modularização em prática nesse programa
não visa portabilidade, visto que são módulos totalmente
específicos, mas apenas simplificar o programa principal.
NOTA: o sistema de coordenadas utilizado em todo o programa é
cartesiano, e *não* segue a lógica de matrizes. Isto é, o ponto
(1,4) significa x=1 e y=4, logo está na 1a coluna, 4a linha.
- - - X --> (4,1) CORRETO
- - - - (1,4) ERRADO
- - - -
- - - -
------------------------------------------------------------- }
Program tetris;
Const
HEIGHT = 20; // Altura do grid (área interna, sem contar as bordas)
HeightPlusOne = 21; // Altura do grid + 1
WIDTH = 11; // Largura do grid (área interna, sem contar as bordas)
WidthPlusOne = 12; // Largura do grid + 1
LEFT = -1; // Identificação dos movimentos horizontais
RIGHT = 1; // (utilizado na chamada ao procedure move)
Type
T_coordinate = record // Coordenada cartesiana (x,y)
x : integer;
y : integer;
end;
T_objgrid = array[1..4, 1..4] of boolean; // Forma de peças. Constituida por uma array bidimensional
// de 4x4 do tipo boolean. Por exemplo, a forma da peça "L"
// é representada da seguinte maneira: 0 0 1 0
// 1 1 1 0
// (0 = FALSE, 1 = TRUE) 0 0 0 0
// 0 0 0 0
T_grid = record // Informações sobre um ponto do grid, se ele está
status : boolean; // preenchido ou não (status) e de que cor ele está
color : integer; // preenchido, se for o caso.
end;
T_object = record // Peças.
pos : T_coordinate; // posição
cell : T_objgrid; // formato
size : integer; // tamanho (ver comentário abaixo)
color : integer; // cor
end;
{ Quanto ao tamanho das peças, existem peças de 4x4 (size=4) e de 3x3 (size=3). No
caso das de 4x4, o eixo de rotação é bem no meio da array. Exemplo (retângulo):
| | | | |
0 1 0 0 -> 0 0 0 0 -> 0 0 1 0 -> 0 0 0 0 -> 0 1 0 0
_ 0 1 0 0 _ -> _ 1 1 1 1 _ -> _ 0 0 1 0 _ -> _ 0 0 0 0 _ -> _ 0 1 0 0 _
0 1 0 0 -> 0 0 0 0 -> 0 0 1 0 -> 1 1 1 1 -> 0 1 0 0
0 1 0 0 -> 0 0 0 0 -> 0 0 1 0 -> 0 0 0 0 -> 0 1 0 0
| | | | |
Já nas peças de 3x3, o eixo de rotação é na célula (2,2). Exemplo ("L"):
| | | | |
0 0 0 0 -> 1 0 0 0 1 1 1 0 0 1 1 0 0 0 0 0
- 0 0 1 0 - -> - 1 0 0 0 - -> - 1 0 0 0 - -> - 0 0 1 0 - -> - 0 0 1 0 -
1 1 1 0 -> 1 1 0 0 -> 0 0 0 0 -> 0 0 1 0 -> 1 1 1 0
0 0 0 0 -> 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
| | | | |
Repare que a estrutura utilizada para representar as formas de 4x4 e de 3x3 é a
mesma, uma array bidimensional de 4x4. Contudo, nas peças de 3x3, existem 7
células (as da última coluna e as da úllima linha) que são inutilizadas. }
Var
grid : array[0..WidthPlusOne, 0..HeightPlusOne] of T_grid; // Grid (incluindo bordas)
obj : T_object; // Peça caindo no grid
next : T_object; // Próxima peça (fixa)
level : integer; // Nível em que se encontra o jogador
score : integer; // Pontuação
cycle : record
freq : integer; // Intervalo entre decaimentos da peça.
status : integer; // Tempo decorrido desde último decaimento.
step : integer; // Tempo entre ciclos de execução. É a cada ciclo o programa
// checa se o usuário pressionou alguma tecla.
end; // (medidas em milisegundos)
orig : T_coordinate; // Origem - posição do canto superior esquerdo do grid na tela.
gameover : boolean; // O jogo acabou?
quit : boolean; // O usuário deseja sair do jogo?
i, j : integer; // Contadores
c : char; // Variavel auxiliar (recebe input)
{ ------------------------------------------------------------------
Procedure Xclrscr: Fornecidos 4 pontos x1, y1, x2, y2, limpa uma
área na tela equivalente ao retângulo de vértices superior
direito = (x1, y1) e inferior esquerdo = (x2, y2).
Equivale a: window( x1, y1, x2, y2 );
clrscr;
------------------------------------------------------------------ }
Procedure Xclrscr( x1, y1, x2, y2 : integer );
Var x, y : integer;
Begin
for y := y1 to y2 do
begin
gotoxy(x1, y);
for x := x1 to x2 do
write(' ');
end;
End;
{ ------------------------------------------------------------------
Function shock: Verifica se a peça está livre para mover-se
horizontalmente xmov unidades e verticalmente ymov unidades.
------------------------------------------------------------------ }
Function shock( xmov, ymov : integer ): boolean;
Var i, j : integer;
return : boolean;
Begin
gotoxy(1,1);
return := FALSE;
for i := 1 to 4 do
for j := 1 to 4 do
if (obj.cell[i,j])
and (obj.pos.x + i + xmov >= 0)
and (obj.pos.x + i + xmov <= WIDTH+1)
and (grid[obj.pos.x+i+xmov, obj.pos.y+j+ymov].status) // esta condição precisa aparecer por último!
then return := TRUE;
shock := return;
End;
{ ------------------------------------------------------------------
Procedure rotate: Roda a peça no sentido horário, se possível.
------------------------------------------------------------------ }
Procedure rotate;
Var i, j : integer;
old : T_objgrid;
Begin
for i := 1 to 4 do
for j := 1 to 4 do
old[i,j] := obj.cell[i,j];
for i := 1 to obj.size do
for j := 1 to obj.size do
obj.cell[i,j] := old[j,obj.size+1-i];
if (shock(0,0)) then
for i := 1 to 4 do
for j := 1 to 4 do
obj.cell[i,j] := old[i,j];
End;
{ ------------------------------------------------------------------
Procedure move: Move a peça para a direita ou para a esquerda,
se possível.
------------------------------------------------------------------ }
Procedure move( xmov : integer );
Begin
if (not shock(xmov, 0))
then obj.pos.x := obj.pos.x + xmov;
End;
{ ------------------------------------------------------------------
Procedure consolidate: Prende a peça ao local onde ela se
encontra. Após isso, a peça perde seu status de peça e passa a
ser apenas parte do grid. Este procedimento é chamado quando a
peça chega ao fundo do grid, ou encontra com outra abaixo dela.
------------------------------------------------------------------ }
Procedure consolidate;
Var i, j : integer;
Begin
for i := 1 to 4 do
for j := 1 to 4 do
if (obj.cell[i,j]) then
begin
grid[obj.pos.x+i, obj.pos.y+j].status := TRUE;
grid[obj.pos.x+i, obj.pos.y+j].color := obj.color;
end;
End;
{ ------------------------------------------------------------------
Procedure checklines: Checa se alguma linha do grid foi
completada. Se sim, apaga o conteudo dela, trazendo todas as
linhas acima para baixo (as linhas que estão acima da que foi
completada 'caem'). Também recalcula o score, o level e o
cycle.freq.
------------------------------------------------------------------ }
Procedure checklines;
Var i, j, down : integer;
LineCleared : boolean;
Begin
down := 0;
for j := HEIGHT downto 1 do
begin
LineCleared := TRUE;
for i := 1 to WIDTH do
if not (grid[i,j].status)
then LineCleared := FALSE;
if (LineCleared)
then
begin
down := down + 1;
score := score + 10;
end
else
for i := 1 to WIDTH do
begin
grid[i,j+down].status := grid[i,j].status;
grid[i,j+down].color := grid[i,j].color;
end;
end;
level := score div 200;
cycle.freq := trunc( 500 * exp(level*ln(0.85)) );
textcolor(YELLOW);
gotoxy( orig.x + (WIDTH+2)*2 + 18, orig.y + 15 );
write(level);
gotoxy( orig.x + (WIDTH+2)*2 + 30, orig.y + 15 );
write(score);
End;
{ ------------------------------------------------------------------
Procedure hideobj: esconde a peça da tela.
------------------------------------------------------------------ }
Procedure hideobj( obj : T_object );
Var i, j : integer;
Begin
for i := 1 to 4 do
for j := 1 to 4 do
if (obj.cell[i,j]) then
begin
gotoxy( orig.x + (obj.pos.x + i) * 2, orig.y + obj.pos.y+j );
write(' ');
end;
gotoxy( orig.x, orig.y );
End;
{ ------------------------------------------------------------------
Procedure drawobj: desenha a peça na tela.
------------------------------------------------------------------ }
Procedure drawobj( obj : T_object );
Var i, j : integer;
Begin
textcolor(obj.color);
for i := 1 to 4 do
for j := 1 to 4 do
if (obj.cell[i,j]) then
begin
gotoxy( orig.x + (obj.pos.x + i) * 2, orig.y + obj.pos.y + j );
write(#219, #219);
end;
gotoxy( orig.x, orig.y );
End;
{ ------------------------------------------------------------------
Procedure refresh: redesenha todo o grid na tela.
------------------------------------------------------------------ }
Procedure refresh;
Var i, j : integer;
Begin
for i := 0 to WIDTH+1 do
for j := 0 to HEIGHT+1 do
begin
gotoxy( orig.x + 2*i, orig.y + j );
if (grid[i,j].status)
then
begin
textcolor(grid[i,j].color);
write(#219, #219);
end
else
write(' ');
end;
gotoxy( orig.x, orig.y );
End;
{ ------------------------------------------------------------------
Procedure createtgt: pega a peça já gerada anteriormente que está
na caixa "next" (variável next) e a transforma na peça atual.
Depois, gera nova peça randomicamente, posicionando-a na caixa
"next".
------------------------------------------------------------------ }
Procedure createtgt;
Var i, j : integer;
Begin
hideobj(next);
obj := next;
obj.pos.x := WIDTH div 2 - 2;
obj.pos.y := 0;
next.pos.x := WIDTH + 4;
next.pos.y := 6;
for i := 1 to 4 do
for j := 1 to 4 do
next.cell[i,j] := FALSE;
case random(7) of
0: begin // Quadrado
next.cell[2,2] := TRUE;
next.cell[2,3] := TRUE;
next.cell[3,2] := TRUE;
next.cell[3,3] := TRUE;
next.size := 4;
next.color := WHITE;
end;
1: begin // Retangulo
next.cell[2,1] := TRUE;
next.cell[2,2] := TRUE;
next.cell[2,3] := TRUE;
next.cell[2,4] := TRUE;
next.size := 4;
next.color := LIGHTRED;
end;
2: begin // "L"
next.cell[3,2] := TRUE;
next.cell[1,3] := TRUE;
next.cell[2,3] := TRUE;
next.cell[3,3] := TRUE;
next.size := 3;
next.color := LIGHTGREEN;
end;
3: begin // "L" invertido
next.cell[1,2] := TRUE;
next.cell[1,3] := TRUE;
next.cell[2,3] := TRUE;
next.cell[3,3] := TRUE;
next.size := 3;
next.color := LIGHTBLUE;
end;
4: begin // "S"
next.cell[2,2] := TRUE;
next.cell[2,3] := TRUE;
next.cell[3,1] := TRUE;
next.cell[3,2] := TRUE;
next.size := 4;
next.color := LIGHTCYAN;
end;
5: begin // "Z"
next.cell[2,2] := TRUE;
next.cell[2,3] := TRUE;
next.cell[3,3] := TRUE;
next.cell[3,4] := TRUE;
next.size := 4;
next.color := LIGHTMAGENTA;
end;
6: begin // "T"
next.cell[1,2] := TRUE;
next.cell[2,1] := TRUE;
next.cell[2,2] := TRUE;
next.cell[2,3] := TRUE;
next.size := 3;
next.color := LIGHTGRAY;
end;
end;
drawobj(next);
End;
{ ------------------------------------------------------------------
Procedure prninfo: imprime as informações presentes ao lado
do grid (contorno da caixa "next" e comandos do jogo).
------------------------------------------------------------------ }
Procedure prninfo( xpos, ypos : integer );
Begin
// window( xpos, ypos, 80, 40 );
Xclrscr( xpos, ypos, 80, 24 );
textcolor(WHITE);
gotoxy( xpos, ypos+0 );
write(#218, #196, #196, ' Next ', #196, #196, #191);
gotoxy( xpos, ypos+1 );
write(#179, ' ', #179);
gotoxy( xpos, ypos+2 );
write(#179, ' ', #179);
gotoxy( xpos, ypos+3 );
write(#179, ' ', #179);
gotoxy( xpos, ypos+4 );
write(#179, ' ', #179);
gotoxy( xpos, ypos+5 );
write(#179, ' ', #179);
gotoxy( xpos, ypos+6 );
write(#179, ' ', #179);
gotoxy( xpos, ypos+7 );
write(#192, #196, #196, #196, #196, #196, #196, #196, #196, #196, #196, #217);
textcolor(YELLOW);
gotoxy( xpos, ypos+10 );
write(' Level: 0 Score: 0');
textcolor(WHITE);
gotoxy( xpos, ypos+13 );
write('Autor : Leonardo Pignataro');
gotoxy( xpos, ypos+14 );
write(' Pascalzim Beta Tester');
gotoxy( xpos, ypos+16 );
write('Contato : secret_doom@hotmail.com');
// window( xpos+17, ypos+1, 80, 40 );
gotoxy( xpos+17, ypos+1 );
write('Controles:');
gotoxy( xpos+17, ypos+2 );
write(' Mover : [setas]');
gotoxy( xpos+17, ypos+3 );
write(' Girar : [space]');
gotoxy( xpos+17, ypos+4 );
write(' Cair : [enter]');
gotoxy( xpos+17, ypos+5 );
write(' Pausa : "P"');
gotoxy( xpos+17, ypos+6 );
write(' Sair : [esc]');
// window(1,1,80,40);
End;
{ ------------------------------------------------------------------
Procedure prnGameover: imprime mensagem de "game over" ao lado
do grid.
------------------------------------------------------------------ }
Procedure prnGameover( xpos, ypos : integer );
Begin
// window( xpos, ypos, 80, 40 );
Xclrscr( xpos, ypos, 80, 24 );
textcolor(WHITE);
gotoxy( xpos, ypos+2 );
writeln(' * * * FIM DE JOGO * * *');
gotoxy( xpos, ypos+6 );
write('Deseja iniciar um ');
textcolor(LIGHTRED);
write('N');
textcolor(WHITE);
write('ovo jogo ou ');
textcolor(LIGHTRED);
write('S');
textcolor(WHITE);
write('air?');
// window( 1, 1, 80, 40 );
End;
{ ------------------------------------------------------------------
PROGRAMA PRINCIPAL
------------------------------------------------------------------ }
Begin
randomize;
orig.x := 2;
orig.y := 2;
clrscr;
gotoxy( orig.x + (WIDTH+2)*2 + 5, orig.y + 1 );
textcolor(WHITE);
write('> > > Pascalzim Tetris < < <');
repeat
prninfo( orig.x + (WIDTH+2)*2 + 4, orig.y + 5 );
for i := 0 to WIDTH+1 do // Preenche todo o grid (inclusive bordas)
for j := 0 to HEIGHT+1 do
begin
grid[i,j].status := TRUE;
grid[i,j].color := DARKGRAY;
end;
for i := 1 to WIDTH do // Esvazia área interna do grid (deixando apenas
for j := 1 to HEIGHT do // as bordas preenchidas)
grid[i,j].status := FALSE;
refresh;
gameover := FALSE;
quit := FALSE;
cycle.freq := 500;
cycle.step := 50;
cycle.status := 0;
score := 0;
createtgt;
createtgt;
refresh;
while not (gameover or quit) do
begin
if (keypressed) then // Se o usuário pressionou uma tecla (keypressed = TRUE),
begin // é preciso agir de acordo com o comando correspondente.
case upcase(readkey) of
#0: case (readkey) of
#75: begin // seta para esquerda
hideobj(obj);
move(left);
drawobj(obj);
end;
#77: begin // seta para direita
hideobj(obj);
move(right);
drawobj(obj);
end;
#80: cycle.status := 0; // seta para baixo
end;
#13: begin // [enter]
while (not shock(0,1)) do
obj.pos.y := obj.pos.y + 1;
cycle.status := 0;
end;
#27: quit := TRUE; // [esc]
#32: begin // espaço
hideobj(obj);
rotate;
drawobj(obj);
end;
'P': begin
textbackground(LIGHTGRAY);
for i := 1 to WIDTH do
for j := 1 to HEIGHT do
begin
gotoxy( orig.x + 2*i, orig.y + j );
write(' ');
end;
textbackground(BLACK);
textcolor(LIGHTGRAY);
gotoxy( orig.x + WIDTH - 2, orig.y + HEIGHT div 2 - 1 );
write(' ');
gotoxy( orig.x + WIDTH - 2, orig.y + HEIGHT div 2 );
write(' PAUSE ');
gotoxy( orig.x + WIDTH - 2, orig.y + HEIGHT div 2 + 1 );
write(' ');
gotoxy( orig.x, orig.y );
repeat
c := upcase(readkey);
until (c = 'P') or (c = #27);
if (c = #27) then quit := TRUE;
refresh;
drawobj(obj);
end;
end;
end;
if (cycle.status < cycle.step) then // Já está na hora de fazer um decaimento?
begin // Se sim...
hideobj(obj); // esconde peça
if (shock(0,1))
then
begin // Se a peça não pode mover-se para baixo:
consolidate; // ancora a peça
checklines; // checa por linhas completadas
refresh; // redesenha todo o grid
createtgt; // cria nova peça
if shock(0, 0) then gameover := TRUE; // caso já não haja espaço no grid para essa nova peça,
end // o jogo está acabado
else // Se a peça pode mover-se para baixo:
obj.pos.y := obj.pos.y + 1; // move a peça para baixo
drawobj(obj); // desenha peça
end;
cycle.status := (cycle.status + cycle.step) mod cycle.freq;
delay(cycle.step);
end;
if (quit) then break;
prnGameover( orig.x + (WIDTH+2)*2 + 4, orig.y + 5 );
repeat
c := upcase(readkey);
until (c = 'N') or (c = 'S');
until (c = 'S');
clrscr;
gotoxy( 25, 12 );
textcolor(WHITE);
write('Pressione [ENTER] para sair . . .');
End.
|
unit BlockDev;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, WinIOCTL; // DiskIO
type
TBlockDevice = class(TObject)
public
constructor Create; virtual;
destructor Destroy; override;
procedure ReadPhysicalSector(Sector : DWORD; count : DWORD; Buffer : Pointer); virtual; abstract;
procedure WritePhysicalSector(Sector : DWORD; count : DWORD; Buffer : Pointer); virtual; abstract;
function Open : Boolean; virtual; abstract;
function Close : Boolean; virtual; abstract;
end;
TNTDisk = class(TBlockDevice)
public
constructor Create; override;
destructor Destroy; override;
procedure ReadPhysicalSector (Sector : DWORD; count : DWORD; Buffer : Pointer); override;
procedure WritePhysicalSector(Sector : DWORD; count : DWORD; Buffer : Pointer); override;
function Open : Boolean; override;
function Close : Boolean; override;
procedure SetFileName(Name : String);
procedure SetMode(Writeable : Boolean);
procedure SetPartition(Start : _Large_Integer; Length : _Large_Integer);
private
FileName : String;
h : THandle;
Writeable : Boolean;
SectorSize : DWORD;
Start : _Large_Integer; //longlong; // start
Length : _Large_Integer; //longlong; // length
end;
{ TVirtualDisk = class(TNTDisk)
public
constructor Create; override;
destructor Destroy; override;
procedure ReadPhysicalSector(Sector : DWORD; count : DWORD; Buffer : Pointer); override;
procedure WritePhysicalSector(Sector : DWORD; count : DWORD; Buffer : Pointer); override;
end;}
implementation
uses rawwrite;
//////////////////////////////
// TBlockDevice
//////////////////////////////
constructor TBlockDevice.Create;
begin
inherited Create;
Debug('Creating BlockDevice', DebugHigh);
end;
destructor TBlockDevice.Destroy;
begin
Debug('Destroying BlockDevice', DebugHigh);
inherited Destroy;
end;
//////////////////////////////
// TNTDisk
//////////////////////////////
// This is a type of block device which uses the
// WIN32 API
constructor TNTDisk.Create;
begin
inherited Create;
Debug('Creating NTDisk', DebugHigh);
h := INVALID_HANDLE_VALUE;
Writeable := False;
SectorSize := 512;
end;
destructor TNTDisk.Destroy;
begin
Debug('Destroying NTDisk', DebugHigh);
Close;
inherited Destroy;
end;
function TNTDisk.Open : Boolean;
begin
if Writeable then
begin
h := Windows.CreateFile(PChar(FileName), GENERIC_READ or GENERIC_WRITE, FILE_SHARE_READ , nil, OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, 0);
end
else
begin
h := Windows.CreateFile(PChar(FileName), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, 0);
end;
if h <> INVALID_HANDLE_VALUE then
begin
Result := True;
end
else
begin
Result := False;
end;
end;
function TNTDisk.Close : Boolean;
begin
if h <> INVALID_HANDLE_VALUE then
begin
CloseHandle(h);
end;
h := INVALID_HANDLE_VALUE;
Result := True;
end;
procedure TNTDisk.SetFileName(Name : String);
begin
FileName := Name;
end;
procedure TNTDisk.SetMode(Writeable : Boolean);
begin
self.Writeable := Writeable;
end;
procedure TNTDisk.SetPartition(Start : _Large_Integer; Length : _Large_Integer);
begin
self.Start.QuadPart := Start.QuadPart;
self.Length.QuadPart := Length.QuadPart;
end;
procedure TNTDisk.ReadPhysicalSector(Sector : DWORD; count : DWORD; Buffer : Pointer);
var
ReadStart : _Large_Integer;
ReadLength : DWORD;
ActualLengthRead : DWORD;
Seek : DWORD;
Error : DWORD;
ErrorMsg : String;
begin
Debug('Reading sector ' + IntToStr(Sector) + ' count = ' + IntToStr(count), DebugHigh);
// check for a valid handle
if h <> INVALID_HANDLE_VALUE then
begin
// Debug('Read sector', DebugOff);
// work out the start address (of partition/file)
ReadStart.QuadPart := SectorSize;
ReadStart.QuadPart := ReadStart.QuadPart * Sector;
ReadStart.QuadPart := ReadStart.QuadPart + Start.Quadpart;
ReadLength := Count * SectorSize;
// seek to the correct pos
Seek := SetFilePointer(h, ReadStart.LowPart, @ReadStart.HighPart, FILE_BEGIN);
if Seek <> $FFFFFFFF then
begin
// seek successful, lets read
if not ReadFile2(h, Buffer, ReadLength, ActualLengthRead, nil) then
begin
Error := GetLastError;
ErrorMsg := 'Read failed error = ' + IntToStr(Error) + '(' + SysErrorMessage(Error) + ')';
Debug(ErrorMsg, DebugOff);
raise Exception.Create(ErrorMsg);
end
else if ReadLength <> ActualLengthRead then
begin
Debug('Possible error, only ' + IntToStr(ActualLengthRead) + ' bytes read', DebugLow);
end;
end
else
begin
// error
Error := GetLastError;
ErrorMsg := 'Seek failed error = ' + IntToStr(Error) + '(' + SysErrorMessage(Error) + ')';
Debug(ErrorMsg, DebugOff);
raise Exception.Create(ErrorMsg);
end;
end;
end;
procedure TNTDisk.WritePhysicalSector(Sector : DWORD; count : DWORD; Buffer : Pointer);
var
WriteStart : _Large_Integer;
WriteLength : DWORD;
ActualLengthWritten : DWORD;
Seek : DWORD;
Error : DWORD;
begin
// check for a valid handle
if h <> INVALID_HANDLE_VALUE then
begin
Debug('Write sector ' + IntToStr(Sector) + ' count = ' + IntToStr(Count), DebugOff);
// work out the start address (of partition/file)
WriteStart.QuadPart := Start.QuadPart + (Sector * SectorSize);
WriteLength := Count * SectorSize;
// seek to the correct pos
Seek := SetFilePointer(h, WriteStart.LowPart, @WriteStart.HighPart, FILE_BEGIN);
if Seek <> $FFFFFFFF then
begin
// seek successful, lets read
if not WriteFile2(h, Buffer, WriteLength, ActualLengthWritten, nil) then
begin
Error := GetLastError;
Debug('Write failed error=' + IntToStr(GetLastError), DebugOff);
raise Exception.Create('Write Failed: (' + IntToStr(GetLastError) + ')'#10 + SysErrorMessage(Error));
end
else if WriteLength <> ActualLengthWritten then
begin
Debug('Possible error, only ' + IntToStr(ActualLengthWritten) + ' bytes written', DebugLow);
end;
end
else
begin
// error
Debug('Seek failed error=' + IntToStr(GetLastError), DebugOff);
raise Exception.Create('Seek failed');
end;
end;
end;
{constructor TVirtualDisk.Create;
begin
inherited Create;
Debug('Creating VirtualDisk', DebugHigh);
end;
destructor TVirtualDisk.Destroy;
begin
Debug('Destroying VirtualDisk', DebugHigh);
inherited Destroy;
end;}
end.
|
unit Kasiski;
interface
const
PROGRESSIVE_KEY = TRUE;
STATIC_KEY = FALSE;
type
PTStatisticTable = ^TStatisticTable;
TStatisticTable = record
trigram : string[3];
distance : integer;
left : integer;
gcd : integer;
next : PTStatisticTable;
end;
var
statisticTable : PTStatisticTable;
procedure KasiskiMethod(const encipheredText : string; const key : boolean);
function getGreatCommonDivisior(statisticTable : PTStatisticTable) : integer;
implementation
uses
System.SysUtils, StringProcessing;
const
SUBSTRING_LENGTH = 3;
STATISTIC_FILE_NAME = 'statistic.kas';
CHECK_LETTER = 'E';
ALPHABET_SHIFT = 65;
ALPHABET_SIZE = 26;
type
TCipherTextTable = array of array of char;
TGCDTable = array of array of boolean;
var
progressiveKeyStepShift : byte;
progressiveKey : boolean;
function stringsAreEqual(const encipheredText : string; const i, j : integer) : boolean; overload; forward;
function stringsAreEqual(trigram1, trigram2 : string) : boolean; overload; forward;
function greatestCommonDivisor(a, b : integer) : integer; inline; forward;
function greatestCommonDisvisionExists(const savedDistance, distance : integer) : boolean; inline; forward;
function getMostFrequentLetter(const cipherColumn : array of char; const columnSize : integer) : char; forward;
function chooseGCD(var gcdTable : TGCDTable; const row, column : integer) : integer; forward;
procedure compareDistances(item : PTStatisticTable; const distance : integer); inline; forward;
procedure addItemToAnalizeTable(statisticTable : PTStatisticTable; const trigram : string;
const left, distance : integer); forward;
procedure fillGCDTable(var gcdTable : TGCDTable; statisticTable : PTStatisticTable;
const rowCount, columnCount : integer); forward;
procedure setProgressiveKeyStepShift(const keyStepShift : byte); inline; forward;
procedure sortArrays(var countArray : array of integer; var charArray : array of char; const arraySize : integer); overload; forward;
procedure swap(var num1, num2 : integer); overload; forward;
procedure swap(var char1, char2 : char); overload; forward;
procedure CleanAnalizeTable(statisticTable : PTStatisticTable); forward;
procedure frequencyAnalysis(const cipherTable : TCipherTextTable; const columnCount, rowCount : integer); forward;
function createStatisticTable : PTStatisticTable;
begin
new(statisticTable);
statisticTable^.next := nil;
Result := statisticTable;
end;
procedure addItemToAnalizeTable(statisticTable : PTStatisticTable; const trigram : string;
const left, distance : integer);
begin
while statisticTable^.next <> nil do
statisticTable := statisticTable^.next;
new(statisticTable^.next);
statisticTable^.next^.trigram := trigram;
statisticTable^.next^.distance := distance;
statisticTable^.next^.left := left;
statisticTable^.next^.next := nil;
end;
procedure saveSubstringToAnalizeTable(statisticTable : PTStatisticTable; const trigram : string;
const left, distance : integer);
var
equal : boolean;
begin
equal := false;
while (statisticTable^.next <> nil) do
begin
if stringsAreEqual(statisticTable^.next^.trigram, trigram) then
begin
equal := true;
break;
end;
statisticTable := statisticTable^.next;
end;
if not (equal and greatestCommonDisvisionExists(statisticTable^.next^.distance, distance)) then
addItemToAnalizeTable(statisticTable, trigram, left, distance);
end;
function greatestCommonDisvisionExists(const savedDistance, distance : integer) : boolean; inline;
begin
Result := (greatestCommonDivisor(savedDistance, distance) >= 2);
end;
procedure compareDistances(item : PTStatisticTable; const distance : integer); inline;
begin
if distance < item.distance then
item^.distance := distance;
end;
procedure compareSubstrings(var statisticTable : PTStatisticTable; const encipheredText : string);
var
i, j, stringLength : integer;
begin
stringLength := length(encipheredText);
statisticTable := createStatisticTable;
for i := 1 to (stringLength - 2 * SUBSTRING_LENGTH + 1) do
for j := i + 3 to stringLength do
if stringsAreEqual(encipheredText, i, j) then
saveSubstringToAnalizeTable(statisticTable, copy(encipheredText, i, SUBSTRING_LENGTH), i, j - i);
//CleanAnalizeTable(statisticTable)
end;
procedure CleanAnalizeTable(statisticTable : PTStatisticTable);
var
pnt : PTStatisticTable;
begin
while statisticTable^.next <> nil do
begin
//if not statisticTable^.next^.repeated then
begin
pnt := statisticTable^.next;
statisticTable^.next := statisticTable^.next^.next;
dispose(pnt);
end
// else
//statisticTable := statisticTable^.next;
end;
end;
function stringsAreEqual(const encipheredText : string; const i, j : integer) : boolean; overload;
var
k : integer;
flag : boolean;
begin
flag := true;
k := 0;
while (k < SUBSTRING_LENGTH - 1) and (flag) do
begin
flag := ((ordExt(encipheredText[i + k]) - ordExt(encipheredText[j + k])) xor
( ordExt(encipheredText[i + k + 1]) - ordExt(encipheredText[j + k + 1]))) = 0;
inc(k);
end;
setProgressiveKeyStepShift(ordExt(encipheredText[i]) - ordExt(encipheredText[j]));
Result := flag;
end;
function stringsAreEqual(trigram1, trigram2 : string) : boolean; overload;
var
k : integer;
flag : boolean;
begin
flag := true;
k := 0;
while (k < SUBSTRING_LENGTH - 1) and (flag) do
begin
flag := ((ordExt(trigram1[k]) - ordExt(trigram1[k])) xor
( ordExt(trigram1[k + 1]) - ordExt(trigram1[k + 1]))) = 0;
inc(k);
end;
Result := flag;
end;
procedure saveStatisticToFile(statisticTable : PTStatisticTable);
var
F : file of TStatisticTable;
tempItem : TStatisticTable;
begin
assignFile(F, STATISTIC_FILE_NAME);
Rewrite(F);
while statisticTable^.next <> nil do
begin
tempItem.trigram := statisticTable^.next^.trigram;
tempItem.distance := statisticTable^.next^.distance;
write(F, tempItem);
statisticTable := statisticTable^.next;
end;
CloseFile(F);
end;
function greatestCommonDivisor(a, b : integer) : integer;
begin
if a = b then Result := a
else if (a > b) then Result := greatestCommonDivisor(a - b, b)
else Result := greatestCommonDivisor(a, b - a);
end;
procedure setProgressiveKeyStepShift(const keyStepShift : byte); inline;
begin
if progressiveKey and ((keyStepShift < progressiveKeyStepShift) or (progressiveKeyStepShift = 0))
then progressiveKeyStepShift := keyStepShift;
end;
function getProgressiveKeyStepShift : integer; inline;
begin
Result := progressiveKeyStepShift;
end;
procedure setKeyType(const key : boolean);
begin
progressiveKey := key;
end;
procedure getResult();
var
F : file of TStatisticTable;
tempItem : TStatisticTable;
begin
assignFile(F, STATISTIC_FILE_NAME);
Reset(F);
while not Eof(F) do
begin
read(F, tempItem);
writeln(tempItem.trigram,' ', tempItem.distance : 6);
end;
CloseFile(F);
end;
procedure printTable(const cipherTable : TCipherTextTable; const gcd, rowCount : integer);
var
i, j : integer;
begin
for i := 0 to rowCount - 1 do
begin
for j := 0 to gcd - 1 do
write(cipherTable[j, i],' ');
writeln;
end;
end;
procedure fillCipherTextTable(const encipheredText : string; const gcd : integer);
var
textLength, rowCount, i, j, k : integer;
cipherTable : TCipherTextTable;
begin
textLength := length(encipheredText);
rowCount := textLength div gcd + 1;
setLength(cipherTable, gcd);
k := 1;
for i := 0 to gcd - 1 do
setLength(cipherTable[i], rowCount);
for i := 0 to gcd - 1 do
for j := 0 to rowCount - 1 do
begin
cipherTable[i, j] := encipheredText[k];
inc(k);
end;
//printTable(cipherTable, gcd, rowCount);
//frequencyAnalysis(cipherTable, gcd, rowCount);
end;
function findKey(const frequencyArray : array of char; const keyLength : integer) : string;
var
i : integer;
key : string;
begin
setLength(key, keyLength);
for i := 1 to keyLength do
key[i] := chr((ord(frequencyArray[i]) - ord(CHECK_LETTER)+ ALPHABET_SIZE) mod ALPHABET_SIZE + ALPHABET_SHIFT);
Result := key;
end;
procedure frequencyAnalysis(const cipherTable : TCipherTextTable; const columnCount, rowCount : integer);
var
i, j : integer;
frequencyArray : array of char;
key : string;
begin
setLength(frequencyArray, columnCount);
for i := 0 to columnCount - 1 do
frequencyArray[i] := getMostFrequentLetter(cipherTable[i], rowCount);
key := findKey(frequencyArray, columnCount);
//writeln(key);
Readln;
end;
function getMostFrequentLetter(const cipherColumn : array of char; const columnSize : integer) : char;
var
charArray : array of char;
countArray : array of integer;
i, j : integer;
begin
setLength(charArray, columnSize);
setLength(countArray, columnSize);
for i := 0 to columnSize - 1 do
begin
countArray[i] := 0;
for j := i + 1 to columnSize - 1 do
if cipherColumn[i] = cipherColumn[j] then
begin
charArray[i] := cipherColumn[i];
inc(countArray[i]);
end;
end;
sortArrays(countArray, charArray, columnSize);
Result := charArray[0];
end;
procedure sortArrays(var countArray : array of integer; var charArray : array of char; const arraySize : integer); overload;
var
i, j, flag : integer;
begin
flag := arraySize;
for i := 0 to arraySize - 2 do
for j := i + 1 to flag do
if countArray[i] < countArray[j] then
begin
swap(countArray[i], countArray[j]);
swap(charArray[i], charArray[j]);
flag := j;
end;
end;
procedure sortArrays(var countArray, gcdArray : array of integer; const arraySize : integer); overload;
var
i, j, flag : integer;
begin
flag := arraySize;
for i := 1 to arraySize - 1 do
for j := i + 1 to flag do
if countArray[i] < countArray[j] then
begin
swap(countArray[i], countArray[j]);
swap(gcdArray[i], gcdArray[j]);
flag := j;
end;
end;
procedure sortHighestGCD(var countArray, gcdArray : array of integer; const arraySize : integer);
var
i, j : integer;
begin
i := 1;
while (i < arraySize) and (countArray[i] = countArray[i + 1]) do
begin
j := i + 1;
while (j < arraySize) and (countArray[j] = countArray[j + 1]) do
begin
if gcdArray[i] < gcdArray[j] then
begin
swap(countArray[i], countArray[j]);
swap(gcdArray[i], gcdArray[j]);
end;
inc(j);
end;
inc(i);
end;
end;
procedure swap(var num1, num2 : integer); overload;
var
temp : integer;
begin
temp := num1;
num1 := num2;
num2 := temp;;
end;
procedure swap(var char1, char2 : char); overload;
var
temp : char;
begin
temp := char1;
char1 := char2;
char2 := temp;
end;
function statisticTableGetSize(statisticTable : PTStatisticTable) : integer;
var
counter : integer;
begin
statisticTable := statisticTable;
counter := 0;
while statisticTable^.next <> nil do
begin
inc(counter);
statisticTable := statisticTable^.next;
end;
Result := counter;
end;
{function getGreatCommonDivisior(statisticTable : PTStatisticTable) : integer;
var
gcdArray, countArray : array of integer;
i, j, statisticTableSize : integer;
begin
statisticTableSize := statisticTableGetSize(statisticTable);
setLength(gcdArray, statisticTableSize);
setLength(countArray, statisticTableSize);
i := 1;
while statisticTable^.next <> nil do
begin
gcdArray[i] := statisticTable^.next^.distance;
countArray[i] := 0;
for j := 1 to statisticTableSize do
if gcdArray[j] = statisticTable^.next^.distance then
inc(countArray[j]);
inc(i);
end;
sortArrays(countArray, gcdArray, statisticTableSize);
sortHighestGCD(gcdArray, countArray, statisticTableSize);
Result := gcdArray[1];
end; }
procedure kasiskiMethod(const encipheredText : string; const key : boolean);
var
gcd : integer;
begin
setKeyType(key);
compareSubstrings(statisticTable, encipheredText);
saveStatisticToFile(statisticTable);
gcd := getGreatCommonDivisior(statisticTable);
//fillCipherTextTable(encipheredText, gcd);
//getResult;
//Writeln(#13, #10, gcd);
end;
function getMaxDistance(statisticTable : PTStatisticTable) : integer;
var
max : integer;
begin
max := 0;
while statisticTable^.next <> nil do
begin
if statisticTable^.next^.distance > max then
max := statisticTable^.next^.distance;
statisticTable := statisticTable^.next;
end;
Result := max;
end;
function getGreatCommonDivisior(statisticTable : PTStatisticTable) : integer;
var
mid, statisticTableSize, i : integer;
gcdTable : TGCDTable;
begin
mid := round(sqrt(getMaxDistance(statisticTable)));
statisticTableSize := statisticTableGetSize(statisticTable);
setLength(gcdTable, statisticTableSize);
for i := 0 to statisticTableSize - 1 do
setLength(gcdTable[i], mid);
fillGCDTable(gcdTable, statisticTable, statisticTableSize, mid);
Result := chooseGCD(gcdTable, statisticTableSize, mid);
end;
procedure fillGCDTable(var gcdTable : TGCDTable; statisticTable : PTStatisticTable;
const rowCount, columnCount : integer);
var
i, j : integer;
begin
for i := 0 to rowCount - 1 do
begin
for j := 3 to columnCount - 1 do
if statisticTable^.next^.distance mod j = 0 then
gcdTable[i, j] := true
else
gcdTable[i, j] := false;
statisticTable := statisticTable^.next;
end;
end;
function chooseGCD(var gcdTable : TGCDTable; const row, column : integer) : integer;
var
i, j, maxGCD, gcd, sum : integer;
begin
maxGCD := 0;
for i := 0 to column - 1 do
begin
sum := 0;
for j := 0 to row - 1 do
if gcdTable[j, i] then inc(sum);
if sum > maxGCD then
begin
maxGCD := sum;
gcd := i;
end;
end;
Result := gcd;
end;
end.
|
unit Magento.Categories;
interface
uses
Magento.Interfaces, Data.DB, System.JSON, REST.Response.Adapter,SysUtils,
System.Generics.Collections, StrUtils;
type
TMagentoCategories = class (TInterfacedObject, iMagentoCategories)
private
FJSON : TJSONObject;
FID : Integer;
FName : String;
FIsActive : Boolean;
FLevel : Integer;
FInclude_in_menu : Boolean;
FCategoriaMae : Integer;
FPosition : Integer;
public
constructor Create;
destructor Destroy; override;
class function New : iMagentoCategories;
function ID(Value : Integer) : iMagentoCategories;
function Name(Value : String) : iMagentoCategories;
function Is_active(Value : Boolean) : iMagentoCategories;
function Position(Value : Integer) : iMagentoCategories;
function Level(Value : Integer) : iMagentoCategories;
function Include_in_menu(Value : Boolean) : iMagentoCategories;
function CategoriaMae(Value : Integer) : iMagentoCategories;
function ListCategories(Value : TDataSet) : iMagentoCategories;
function &End : String;
end;
implementation
{ TMagentoCategories }
uses Magento.Factory;
function TMagentoCategories.&End: String;
var
lObj,lJSON : TJSONObject;
lArray : TJSONArray;
begin
lObj := TJSONObject.Create;
FJSON := TJSONObject.Create;
lArray := TJSONArray.Create;
FJSON.AddPair('parent_id', TJSONNumber.Create(FCategoriaMae));
FJSON.AddPair('id',TJSONNumber.Create(FID));
FJSON.AddPair('include_in_menu',TJSONBool.Create(FInclude_in_menu));
FJSON.AddPair('is_active',TJSONBool.Create(FIsActive));
FJSON.AddPair('level', TJSONNumber.Create(FLevel));
FJSON.AddPair('name',FName);
FJSON.AddPair('position',TJSONNumber.Create(FPosition));
lObj.AddPair('attribute_code','url_key');
lObj.AddPair('value', LowerCase(FName));
lArray.Add(lObj);
FJSON.AddPair('custom_attributes',lArray);
Result := TJSONObject.Create.AddPair('category',FJSON).ToString;
end;
function TMagentoCategories.CategoriaMae(Value: Integer): iMagentoCategories;
begin
Result := Self;
FCategoriaMae := Value;
end;
constructor TMagentoCategories.Create;
begin
end;
destructor TMagentoCategories.Destroy;
begin
inherited;
end;
function TMagentoCategories.ID(Value: Integer): iMagentoCategories;
begin
Result := Self;
FID := Value;
end;
function TMagentoCategories.Include_in_menu(Value: Boolean): iMagentoCategories;
begin
Result := Self;
FInclude_in_menu := Value;
end;
function TMagentoCategories.Is_active(Value: Boolean): iMagentoCategories;
begin
Result := Self;
FIsActive := Value;
end;
function TMagentoCategories.Level(Value: Integer): iMagentoCategories;
begin
Result := Self;
FLevel := Value;
end;
function TMagentoCategories.ListCategories(Value: TDataSet): iMagentoCategories;
var
lJSONObj : TJSONObject;
lJSONArray : TJSONArray;
lConv : TCustomJSONDataSetAdapter;
lJSON : String;
begin
Result := Self;
lJSON := TMagentoFactory.New.MagentoHTTP.GetCatagorias;
lJSONObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(lJSON), 0) as TJSONObject;
lConv := TCustomJSONDataSetAdapter.Create(nil);
lJSONArray := lJSONObj.Get('children_data').JsonValue as TJSONArray;
lJSONArray.ToString;
try
lConv.DataSet := Value;
lConv.UpdateDataSet(lJSONArray);
finally
lConv.Free;
end;
end;
function TMagentoCategories.Name(Value: String): iMagentoCategories;
begin
Result := Self;
FName := Value;
end;
class function TMagentoCategories.New: iMagentoCategories;
begin
Result := self.Create;
end;
function TMagentoCategories.Position(Value: Integer): iMagentoCategories;
begin
Result := Self;
FPosition := Value;
end;
end.
|
namespace proholz.xsdparser;
interface
type
XsdRestrictionsVisitor = public class(AttributesVisitor)
private
// *
// * The {@link XsdRestriction} instance which owns this {@link XsdRestrictionsVisitor} instance. This way this
// * visitor instance can perform changes in the {@link XsdRestriction} object.
//
//
var owner: XsdRestriction;
public
constructor(aowner: XsdRestriction);
method visit(element: XsdEnumeration); override;
method visit(element: XsdFractionDigits); override;
method visit(element: XsdLength); override;
method visit(element: XsdMaxExclusive); override;
method visit(element: XsdMaxInclusive); override;
method visit(element: XsdMaxLength); override;
method visit(element: XsdMinExclusive); override;
method visit(element: XsdMinInclusive); override;
method visit(element: XsdMinLength); override;
method visit(element: XsdPattern); override;
method visit(element: XsdTotalDigits); override;
method visit(element: XsdWhiteSpace); override;
method visit(element: XsdSimpleType); override;
end;
implementation
constructor XsdRestrictionsVisitor(aowner: XsdRestriction);
begin
inherited constructor(aowner);
self.owner := aowner;
end;
method XsdRestrictionsVisitor.visit(element: XsdEnumeration);
begin
inherited visit(element);
owner.add(element);
end;
method XsdRestrictionsVisitor.visit(element: XsdFractionDigits);
begin
inherited visit(element);
owner.setFractionDigits(element);
end;
method XsdRestrictionsVisitor.visit(element: XsdLength);
begin
inherited visit(element);
owner.setLength(element);
end;
method XsdRestrictionsVisitor.visit(element: XsdMaxExclusive);
begin
inherited visit(element);
owner.setMaxExclusive(element);
end;
method XsdRestrictionsVisitor.visit(element: XsdMaxInclusive);
begin
inherited visit(element);
owner.setMaxInclusive(element);
end;
method XsdRestrictionsVisitor.visit(element: XsdMaxLength);
begin
inherited visit(element);
owner.setMaxLength(element);
end;
method XsdRestrictionsVisitor.visit(element: XsdMinExclusive);
begin
inherited visit(element);
owner.setMinExclusive(element);
end;
method XsdRestrictionsVisitor.visit(element: XsdMinInclusive);
begin
inherited visit(element);
owner.setMinInclusive(element);
end;
method XsdRestrictionsVisitor.visit(element: XsdMinLength);
begin
inherited visit(element);
owner.setMinLength(element);
end;
method XsdRestrictionsVisitor.visit(element: XsdPattern);
begin
inherited visit(element);
owner.setPattern(element);
end;
method XsdRestrictionsVisitor.visit(element: XsdTotalDigits);
begin
inherited visit(element);
owner.setTotalDigits(element);
end;
method XsdRestrictionsVisitor.visit(element: XsdWhiteSpace);
begin
inherited visit(element);
owner.setWhiteSpace(element);
end;
method XsdRestrictionsVisitor.visit(element: XsdSimpleType);
begin
inherited visit(element);
owner.setSimpleType(element);
end;
end. |
unit ItemFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, Spin, Menus,
InflatablesList_ShownPicturesManager,
InflatablesList_Types,
InflatablesList_Item,
InflatablesList_Manager;
type
TfrmItemFrame = class(TFrame)
pnlMain: TPanel;
shpItemTitleBcgr: TShape;
imgItemLock: TImage;
lblItemTitle: TLabel;
lblItemTitleShadow: TLabel;
shpHighlight: TShape;
tmrSecondaryPics: TTimer;
tmrHighlightTimer: TTimer;
imgManufacturerLogo: TImage;
imgPrevPicture: TImage;
imgNextPicture: TImage;
imgPictureA: TImage;
imgPictureB: TImage;
imgPictureC: TImage;
shpPictureABcgr: TShape;
shpPictureBBcgr: TShape;
shpPictureCBcgr: TShape;
lblUniqueID: TLabel;
lblTimeOfAddition: TLabel;
lblItemType: TLabel;
cmbItemType: TComboBox;
leItemTypeSpecification: TLabeledEdit;
lblPieces: TLabel;
sePieces: TSpinEdit;
leUserID: TLabeledEdit;
btnUserIDGen: TButton;
lblManufacturer: TLabel;
cmbManufacturer: TComboBox;
leManufacturerString: TLabeledEdit;
leTextID: TLabeledEdit;
lblID: TLabel;
seNumID: TSpinEdit;
gbFlagsTags: TGroupBox;
cbFlagOwned: TCheckBox;
cbFlagWanted: TCheckBox;
cbFlagOrdered: TCheckBox;
cbFlagUntested: TCheckBox;
cbFlagTesting: TCheckBox;
cbFlagTested: TCheckBox;
cbFlagBoxed: TCheckBox;
cbFlagDamaged: TCheckBox;
cbFlagRepaired: TCheckBox;
cbFlagElsewhere: TCheckBox;
cbFlagPriceChange: TCheckBox;
cbFlagAvailChange: TCheckBox;
cbFlagNotAvailable: TCheckBox;
cbFlagLost: TCheckBox;
cbFlagDiscarded: TCheckBox;
btnFlagMacros: TButton;
pmnFlagMacros: TPopupMenu;
bvlTagSep: TBevel;
lblTextTag: TLabel;
eTextTag: TEdit;
lblNumTag: TLabel;
seNumTag: TSpinEdit;
lblWantedLevel: TLabel;
seWantedLevel: TSpinEdit;
leVariant: TLabeledEdit;
leVariantTag: TLabeledEdit;
lblSurfaceFinish: TLabel;
cmbSurfaceFinish: TComboBox;
lblMaterial: TLabel;
cmbMaterial: TComboBox;
lblThickness: TLabel;
seThickness: TSpinEdit;
lblSizeX: TLabel;
seSizeX: TSpinEdit;
lblSizeY: TLabel;
seSizeY: TSpinEdit;
lblSizeZ: TLabel;
seSizeZ: TSpinEdit;
lblUnitWeight: TLabel;
seUnitWeight: TSpinEdit;
lblNotes: TLabel;
meNotes: TMemo;
lblNotesEdit: TLabel;
leReviewURL: TLabeledEdit;
btnReviewOpen: TButton;
lblUnitDefaultPrice: TLabel;
seUnitPriceDefault: TSpinEdit;
lblRating: TLabel;
seRating: TSpinEdit;
lblRatingDetails: TLabel;
btnRatingDetails: TButton;
btnPictures: TButton;
btnShops: TButton;
btnUpdateShops: TButton;
gbReadOnlyInfo: TGroupBox;
lblPictureCountTitle: TLabel;
lblPictureCount: TLabel;
lblSelectedShop: TLabel;
lblSelectedShopTitle: TLabel;
lblShopCountTitle: TLabel;
lblShopCount: TLabel;
lblAvailPiecesTitle: TLabel;
lblUnitPriceLowestTitle: TLabel;
lblUnitPriceSelectedTitle: TLabel;
lblAvailPieces: TLabel;
lblUnitPriceLowest: TLabel;
lblUnitPriceSelected: TLabel;
shpUnitPriceSelectedBcgr: TShape;
lblTotalWeightTitle: TLabel;
lblTotalWeight: TLabel;
lblTotalPriceLowest: TLabel;
lblTotalPriceLowestTitle: TLabel;
lblTotalPriceSelectedTitle: TLabel;
lblTotalPriceSelected: TLabel;
shpTotalPriceSelectedBcgr: TShape;
procedure FrameResize(Sender: TObject);
procedure lblItemTitleClick(Sender: TObject);
procedure tmrSecondaryPicsTimer(Sender: TObject);
procedure tmrHighlightTimerTimer(Sender: TObject);
procedure imgPrevPictureMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure imgPrevPictureMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure imgNextPictureMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure imgNextPictureMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure imgPictureClick(Sender: TObject);
procedure cmbItemTypeChange(Sender: TObject);
procedure leItemTypeSpecificationChange(Sender: TObject);
procedure sePiecesChange(Sender: TObject);
procedure leUserIDChange(Sender: TObject);
procedure btnUserIDGenClick(Sender: TObject);
procedure cmbManufacturerChange(Sender: TObject);
procedure leManufacturerStringChange(Sender: TObject);
procedure leTextIDChange(Sender: TObject);
procedure seNumIDChange(Sender: TObject);
procedure CommonFlagClick(Sender: TObject);
procedure btnFlagMacrosClick(Sender: TObject);
procedure CommonFlagMacroClick(Sender: TObject);
procedure eTextTagChange(Sender: TObject);
procedure seNumTagChange(Sender: TObject);
procedure seWantedLevelChange(Sender: TObject);
procedure leVariantChange(Sender: TObject);
procedure cmbSurfaceFinishChange(Sender: TObject);
procedure cmbMaterialChange(Sender: TObject);
procedure seSizeXChange(Sender: TObject);
procedure seSizeYChange(Sender: TObject);
procedure seSizeZChange(Sender: TObject);
procedure seUnitWeightChange(Sender: TObject);
procedure meNotesKeyPress(Sender: TObject; var Key: Char);
procedure lblNotesEditClick(Sender: TObject);
procedure lblNotesEditMouseEnter(Sender: TObject);
procedure lblNotesEditMouseLeave(Sender: TObject);
procedure leReviewURLChange(Sender: TObject);
procedure btnReviewOpenClick(Sender: TObject);
procedure seUnitPriceDefaultChange(Sender: TObject);
procedure seRatingChange(Sender: TObject);
procedure btnRatingDetailsClick(Sender: TObject);
procedure btnPicturesClick(Sender: TObject);
procedure btnShopsClick(Sender: TObject);
procedure btnUpdateShopsClick(Sender: TObject);
private
// other fields
fPicturesManager: TILShownPicturesManager;
fInitializing: Boolean;
fILManager: TILManager;
fCurrentItem: TILItem;
// searching
fLastFoundValue: TILItemSearchResult;
// picture arrows
fPicArrowLeft: TBitmap;
fPicArrowRight: TBitmap;
fPicArrowLeftD: TBitmap;
fPicArrowRightD: TBitmap;
protected
// item event handlers (manager)
procedure UpdateTitle(Sender: TObject; Item: TObject);
procedure UpdatePictures(Sender: TObject; Item: TObject);
procedure UpdateFlags(Sender: TObject; Item: TObject);
procedure UpdateValues(Sender: TObject; Item: TObject);
procedure UpdateOthers(Sender: TObject; Item: TObject);
// helper methods
procedure ReplaceManufacturerLogo;
procedure FillFlagsFromItem;
procedure FillValues;
procedure FillSelectedShop(const SelectedShop: String);
// searching
procedure DisableHighlight;
procedure Highlight(Control: TControl); overload;
procedure HighLight(Value: TILItemSearchResult); overload;
// initialization
procedure BuildFlagMacrosMenu;
procedure PrepareArrows;
// frame methods
procedure FrameClear;
procedure FrameSave;
procedure FrameLoad;
public
OnShowSelectedItem: TNotifyEvent;
OnFocusList: TNotifyEvent;
procedure Initialize(ILManager: TILManager);
procedure Finalize;
procedure Save;
procedure Load;
procedure SetItem(Item: TILItem; ProcessChange: Boolean);
procedure FindPrev(const Text: String);
procedure FindNext(const Text: String);
end;
implementation
uses
TextEditForm, ItemPicturesForm, ShopsForm, UpdateForm,
InflatablesList_Utils,
InflatablesList_LocalStrings,
InflatablesList_Data,
InflatablesList_ItemShop;
{$R *.dfm}
{$R '..\resources\pic_arrows.res'}
const
IL_SEARCH_HIGHLIGHT_TIMEOUT = 12; // 3 seconds highlight
IL_FLAGMACRO_CAPTIONS: array[0..4] of String = (
'Ordered item received',
'Starting item testing',
'Testing of item is finished',
'Damage has been repaired',
'Price and availability change checked');
//==============================================================================
procedure TfrmItemFrame.UpdateTitle(Sender: TObject; Item: TObject);
var
ManufStr: String;
TypeStr: String;
begin
If Assigned(fCurrentItem) and (Item = fCurrentItem) then
begin
// construct manufacturer + ID string
ManufStr := fCurrentItem.TitleStr;
// constructy item type string
TypeStr := fCurrentItem.TypeStr;
// final concatenation
If Length(TypeStr) > 0 then
ManufStr := IL_Format('%s - %s',[ManufStr,TypeStr]);
If fCurrentItem.Pieces > 1 then
ManufStr := IL_Format('%s (%dx)',[ManufStr,fCurrentItem.Pieces]);
lblItemTitle.Caption := ManufStr;
lblItemTitleShadow.Caption := lblItemTitle.Caption;
end
else
begin
lblItemTitle.Caption := '';
lblItemTitleShadow.Caption := '';
end;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.UpdatePictures(Sender: TObject; Item: TObject);
begin
DisableHighlight;
If Assigned(fCurrentItem) and (Item = fCurrentItem) and not fILManager.StaticSettings.NoPictures then
fPicturesManager.ShowPictures(fCurrentItem.Pictures)
else
fPicturesManager.ShowPictures(nil);
If Assigned(fCurrentItem) then
lblPictureCount.Caption := fCurrentItem.PictureCountStr
else
lblPictureCount.Caption := '-';
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.UpdateFlags(Sender: TObject; Item: TObject);
begin
If Assigned(fCurrentItem) and (Item = fCurrentItem) then
begin
fInitializing := True;
try
FillFlagsFromItem;
finally
fInitializing := False;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.UpdateValues(Sender: TObject; Item: TObject);
begin
If Assigned(fCurrentItem) and (Item = fCurrentItem) then
FillValues;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.UpdateOthers(Sender: TObject; Item: TObject);
begin
If Assigned(fCurrentItem) and (Item = fCurrentItem) then
begin
// item lock icon
imgItemLock.Visible := fCurrentItem.Encrypted;
lblRatingDetails.Visible := Length(fCurrentItem.RatingDetails) > 0;
end
else
begin
imgItemLock.Visible := False;
lblRatingDetails.Visible := False;
end;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.ReplaceManufacturerLogo;
begin
If Assigned(fCurrentItem) then
begin
If imgManufacturerLogo.Tag <> Ord(fCurrentItem.Manufacturer) then
imgManufacturerLogo.Picture.Assign(
fILManager.DataProvider.ItemManufacturers[fCurrentItem.Manufacturer].Logo);
imgManufacturerLogo.Tag := Ord(fCurrentItem.Manufacturer);
end
else
begin
imgManufacturerLogo.Picture.Assign(nil);
imgManufacturerLogo.Tag := -1;
end;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.FillFlagsFromItem;
begin
If fInitializing and Assigned(fCurrentItem) then
begin
cbFlagOwned.Checked := ilifOwned in fCurrentItem.Flags;
cbFlagWanted.Checked := ilifWanted in fCurrentItem.Flags;
cbFlagOrdered.Checked := ilifOrdered in fCurrentItem.Flags;
cbFlagBoxed.Checked := ilifBoxed in fCurrentItem.Flags;
cbFlagElsewhere.Checked := ilifElsewhere in fCurrentItem.Flags;
cbFlagUntested.Checked := ilifUntested in fCurrentItem.Flags;
cbFlagTesting.Checked := ilifTesting in fCurrentItem.Flags;
cbFlagTested.Checked := ilifTested in fCurrentItem.Flags;
cbFlagDamaged.Checked := ilifDamaged in fCurrentItem.Flags;
cbFlagRepaired.Checked := ilifRepaired in fCurrentItem.Flags;
cbFlagPriceChange.Checked := ilifPriceChange in fCurrentItem.Flags;
cbFlagAvailChange.Checked := ilifAvailChange in fCurrentItem.Flags;
cbFlagNotAvailable.Checked := ilifNotAvailable in fCurrentItem.Flags;
cbFlagLost.Checked := ilifLost in fCurrentItem.Flags;
cbFlagDiscarded.Checked := ilifDiscarded in fCurrentItem.Flags;
end;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.FillValues;
var
SelectedShop: TILItemShop;
begin
If Assigned(fCurrentItem) then
begin
// selected shop
If fCurrentItem.ShopsSelected(SelectedShop) then
FillSelectedShop(SelectedShop.Name)
else
FillSelectedShop('-');
// number of shops
If fCurrentItem.ShopCount > 0 then
lblShopCount.Caption := fCurrentItem.ShopsCountStr
else
lblShopCount.Caption := '-';
// available pieces
If fCurrentItem.IsAvailable(False) then
begin
If fCurrentItem.AvailableSelected < 0 then
lblAvailPieces.Caption := 'more than ' + IntToStr(Abs(fCurrentItem.AvailableSelected))
else
lblAvailPieces.Caption := IntToStr(fCurrentItem.AvailableSelected);
end
else lblAvailPieces.Caption := '-';
// total weight
If fCurrentItem.TotalWeight > 0 then
lblTotalWeight.Caption := fCurrentItem.TotalWeightStr
else
lblTotalWeight.Caption := '-';
// price lowest
If fCurrentItem.UnitPriceLowest > 0 then
begin
lblUnitPriceLowest.Caption := IL_Format('%d %s',[fCurrentItem.UnitPriceLowest,IL_CURRENCY_SYMBOL]);
lblTotalPriceLowest.Caption := IL_Format('%d %s',[fCurrentItem.TotalPriceLowest,IL_CURRENCY_SYMBOL]);
end
else
begin
lblUnitPriceLowest.Caption := '-';
lblTotalPriceLowest.Caption := '-';
end;
// price selected
If fCurrentItem.UnitPriceSelected > 0 then
begin
lblUnitPriceSelected.Caption := IL_Format('%d %s',[fCurrentItem.UnitPriceSelected,IL_CURRENCY_SYMBOL]);
lblTotalPriceSelected.Caption := IL_Format('%d %s',[fCurrentItem.TotalPriceSelected,IL_CURRENCY_SYMBOL]);
end
else
begin
lblUnitPriceSelected.Caption := '-';
lblTotalPriceSelected.Caption := '-';
end;
// price selected background
If (fCurrentItem.UnitPriceSelected <> fCurrentItem.UnitPriceLowest) and
(fCurrentItem.UnitPriceSelected > 0) and (fCurrentItem.UnitPriceLowest > 0) then
begin
shpUnitPriceSelectedBcgr.Visible := True;
shpTotalPriceSelectedBcgr.Visible := True;
end
else
begin
shpUnitPriceSelectedBcgr.Visible := False;
shpTotalPriceSelectedBcgr.Visible := False;
end;
end
else
begin
FillSelectedShop('-');
lblShopCount.Caption := '-';
lblAvailPieces.Caption := '-';
lblTotalWeight.Caption := '-';
lblUnitPriceLowest.Caption := '-';
lblTotalPriceLowest.Caption := '-';
lblUnitPriceSelected.Caption := '-';
shpUnitPriceSelectedBcgr.Visible := False;
lblTotalPriceSelected.Caption := '-';
shpTotalPriceSelectedBcgr.Visible := False;
end;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.FillSelectedShop(const SelectedShop: String);
begin
If lblSelectedShop.Canvas.TextWidth(SelectedShop) <=
(lblShopCount.BoundsRect.Right - lblSelectedShopTitle.BoundsRect.Right - 8) then
lblSelectedShop.Left := lblShopCount.BoundsRect.Right - lblSelectedShop.Canvas.TextWidth(SelectedShop)
else
lblSelectedShop.Left := lblSelectedShopTitle.BoundsRect.Right + 8;
lblSelectedShop.Caption := SelectedShop;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.DisableHighlight;
begin
shpHighlight.Visible := False;
fLastFoundValue := ilisrNone;
tmrHighlightTimer.Tag := 0;
tmrHighlightTimer.Enabled := False;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.Highlight(Control: TControl);
begin
If (Control is TComboBox) or (Control is TLabeledEdit) or
((Control is TSpinEdit) and (Control <> seNumTag)) then
begin
shpHighlight.Left := Control.Left + Control.Width - 15;
shpHighlight.Top := Control.Top - 13;
shpHighlight.Width := 16;
shpHighlight.Height := 10;
end
else If Control is TCheckBox then
begin
shpHighlight.Left := Control.Left - 5;
shpHighlight.Top := Control.Top + 2;
shpHighlight.Width := 5;
shpHighlight.Height := Control.Height - 3;
end
else If Control is TMemo then
begin
shpHighlight.Left := Control.Left + Control.Width - 35;
shpHighlight.Top := Control.Top - 13;
shpHighlight.Width := 16;
shpHighlight.Height := 10;
end
else If Control is TLabel then
begin
shpHighlight.Left := Control.Left - 6;
shpHighlight.Top := Control.Top;
shpHighlight.Width := 5;
shpHighlight.Height := Control.Height + 1;
end
else If Control is TImage then
begin
shpHighlight.Left := Control.Left;
shpHighlight.Top := Control.Top + Control.Height + 1;
shpHighlight.Width := Control.Width + 1;
shpHighlight.Height := 5;
end
// special cases
else If (Control = seNumTag) or (Control = eTextTag) then
begin
shpHighlight.Left := Control.Left - 5;
shpHighlight.Top := Control.Top;
shpHighlight.Width := 5;
shpHighlight.Height := Control.Height + 1;
end
else If Control = btnRatingDetails then
begin
shpHighlight.Left := Control.Left;
shpHighlight.Top := Control.Top - 6;
shpHighlight.Width := lblRatingDetails.Left - shpHighlight.Left;
shpHighlight.Height := 5;
end
else Exit; // control is not valid
shpHighlight.Parent := Control.Parent;
shpHighlight.Visible := True;
If Control is TLabel then
Control.BringToFront
else
shpHighlight.BringToFront;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.HighLight(Value: TILItemSearchResult);
begin
case Value of
ilisrItemPicFile: Highlight(fPicturesManager.Image(ilipkMain));
ilisrSecondaryPicFile: Highlight(fPicturesManager.Image(ilipkSecondary));
ilisrPackagePicFile: Highlight(fPicturesManager.Image(ilipkPackage));
ilisrType: Highlight(cmbItemType);
ilisrTypeSpec: Highlight(leItemTypeSpecification);
ilisrPieces: Highlight(sePieces);
ilisrUserID: Highlight(leUserID);
ilisrManufacturer: Highlight(cmbManufacturer);
ilisrManufacturerStr: Highlight(leManufacturerString);
ilisrTextID: Highlight(leTextID);
ilisrNumID: Highlight(seNumID);
ilisrFlagOwned: Highlight(cbFlagOwned);
ilisrFlagWanted: Highlight(cbFlagWanted);
ilisrFlagOrdered: Highlight(cbFlagOrdered);
ilisrFlagBoxed: Highlight(cbFlagBoxed);
ilisrFlagElsewhere: Highlight(cbFlagElsewhere);
ilisrFlagUntested: Highlight(cbFlagUntested);
ilisrFlagTesting: Highlight(cbFlagTesting);
ilisrFlagTested: Highlight(cbFlagTested);
ilisrFlagDamaged: Highlight(cbFlagDamaged);
ilisrFlagRepaired: Highlight(cbFlagRepaired);
ilisrFlagPriceChange: Highlight(cbFlagPriceChange);
ilisrFlagAvailChange: Highlight(cbFlagAvailChange);
ilisrFlagNotAvailable: Highlight(cbFlagNotAvailable);
ilisrFlagLost: Highlight(cbFlagLost);
ilisrFlagDiscarded: Highlight(cbFlagDiscarded);
ilisrTextTag: Highlight(eTextTag);
ilisrNumTag: Highlight(seNumTag);
ilisrWantedLevel: Highlight(seWantedLevel);
ilisrVariant: Highlight(leVariant);
ilisrVariantTag: Highlight(leVariantTag);
ilisrSurfaceFinish: Highlight(cmbSurfaceFinish);
ilisrMaterial: Highlight(cmbMaterial);
ilisrThickness: Highlight(seThickness);
ilisrSizeX: Highlight(seSizeX);
ilisrSizeY: Highlight(seSizeY);
ilisrSizeZ: Highlight(seSizeZ);
ilisrUnitWeight: Highlight(seUnitWeight);
ilisrNotes: Highlight(meNotes);
ilisrReviewURL: Highlight(leReviewURL);
ilisrUnitPriceDefault: Highlight(seUnitPriceDefault);
ilisrRating: Highlight(seRating);
ilisrRatingDetails: Highlight(btnRatingDetails);
ilisrSelectedShop: Highlight(lblSelectedShop);
else
DisableHighlight;
Exit; // so timer is not enabled
end;
tmrHighlightTimer.Tag := IL_SEARCH_HIGHLIGHT_TIMEOUT;
tmrHighlightTimer.Enabled := True;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.BuildFlagMacrosMenu;
var
i: Integer;
MITemp: TMenuItem;
begin
pmnFlagMacros.Items.Clear;
For i := Low(IL_FLAGMACRO_CAPTIONS) to High(IL_FLAGMACRO_CAPTIONS) do
begin
MITemp := TMenuItem.Create(Self);
MITemp.Name := IL_Format('mniFM_Macro_%d',[i]);
MITemp.Caption := IL_FLAGMACRO_CAPTIONS[i];
MITemp.OnClick := CommonFlagMacroClick;
MITemp.Tag := i;
pmnFlagMacros.Items.Add(MITemp);
end;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.PrepareArrows;
begin
fPicArrowLeft := TBitmap.Create;
TILDataProvider.LoadBitmapFromResource('pic_arr_l',fPicArrowLeft);
fPicArrowRight := TBitmap.Create;
TILDataProvider.LoadBitmapFromResource('pic_arr_r',fPicArrowRight);
fPicArrowLeftD := TBitmap.Create;
TILDataProvider.LoadBitmapFromResource('pic_arr_l_d',fPicArrowLeftD);
fPicArrowRightD := TBitmap.Create;
TILDataProvider.LoadBitmapFromResource('pic_arr_r_d',fPicArrowRightD);
imgPrevPicture.Picture.Assign(fPicArrowLeft);
imgNextPicture.Picture.Assign(fPicArrowRight);
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.FrameClear;
begin
fInitializing := True;
try
imgItemLock.Visible := False;
UpdateTitle(nil,nil);
ReplaceManufacturerLogo;
UpdatePictures(nil,nil);
// basic specs
cmbItemType.ItemIndex := 0;
cmbItemType.OnChange(nil);
leItemTypeSpecification.Text := '';
sePieces.Value := 1;
leUserID.Text := '';
cmbManufacturer.ItemIndex := 0;
cmbManufacturer.OnChange(nil);
leManufacturerString.Text := '';
leTextID.Text := '';
seNumID.Value := 0;
// flags
cbFlagOwned.Checked := False;
cbFlagWanted.Checked := False;
cbFlagOrdered.Checked := False;
cbFlagUntested.Checked := False;
cbFlagTesting.Checked := False;
cbFlagTested.Checked := False;
cbFlagBoxed.Checked := False;
cbFlagDamaged.Checked := False;
cbFlagRepaired.Checked := False;
cbFlagElsewhere.Checked := False;
cbFlagPriceChange.Checked := False;
cbFlagAvailChange.Checked := False;
cbFlagNotAvailable.Checked := False;
cbFlagLost.Checked := False;
cbFlagDiscarded.Checked := False;
eTextTag.Text := '';
seNumTag.Value := 0;
// ext. specs
seWantedLevel.Value := 0;
leVariant.Text := '';
leVariantTag.Text := '';
cmbSurfaceFinish.ItemIndex := 0;
cmbMaterial.ItemIndex := 0;
seThickness.Value := 0;
seSizeX.Value := 0;
seSizeY.Value := 0;
seSizeZ.Value := 0;
seUnitWeight.Value := 0;
// other info
meNotes.Text := '';
leReviewURL.Text := '';
seUnitPriceDefault.Value := 0;
seRating.Value := 0;
lblRatingDetails.Visible := False;
// read-only things
lblPictureCount.Caption := '0';
FillSelectedShop('-');
lblShopCount.Caption := '0';
lblAvailPieces.Caption := '0';
lblUnitPriceLowest.Caption := '-';
lblUnitPriceSelected.Caption := '-';
shpUnitPriceSelectedBcgr.Visible := False;
lblTotalWeight.Caption := '-';
lblTotalPriceLowest.Caption := '-';
lblTotalPriceSelected.Caption := '-';
shpTotalPriceSelectedBcgr.Visible := False;
finally
fInitializing := False;
end;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.FrameSave;
begin
{
pictures and shops are not needed to be saved, they are saved on the fly
(when selected/changed)
also lowest and selected prices are not saved, they are read only and set
by other processes
}
If Assigned(fCurrentItem) then
begin
fCurrentItem.BeginUpdate;
try
// basic specs
fCurrentItem.ItemType := TILItemType(cmbItemType.ItemIndex);
fCurrentItem.ItemTypeSpec := leItemTypeSpecification.Text;
fCurrentItem.Pieces := sePieces.Value;
fCurrentItem.UserID := leUserID.Text;
fCurrentItem.Manufacturer := TILItemManufacturer(cmbManufacturer.ItemIndex);
fCurrentItem.ManufacturerStr := leManufacturerString.Text;
fCurrentItem.TextID := leTextID.Text;
fCurrentItem.NumID := seNumID.Value;
// tags, flags
fCurrentItem.SetFlagValue(ilifOwned,cbFlagOwned.Checked);
fCurrentItem.SetFlagValue(ilifWanted,cbFlagWanted.Checked);
fCurrentItem.SetFlagValue(ilifOrdered,cbFlagOrdered.Checked);
fCurrentItem.SetFlagValue(ilifBoxed,cbFlagBoxed.Checked);
fCurrentItem.SetFlagValue(ilifElsewhere,cbFlagElsewhere.Checked);
fCurrentItem.SetFlagValue(ilifUntested,cbFlagUntested.Checked);
fCurrentItem.SetFlagValue(ilifTesting,cbFlagTesting.Checked);
fCurrentItem.SetFlagValue(ilifTested,cbFlagTested.Checked);
fCurrentItem.SetFlagValue(ilifDamaged,cbFlagDamaged.Checked);
fCurrentItem.SetFlagValue(ilifRepaired,cbFlagRepaired.Checked);
fCurrentItem.SetFlagValue(ilifPriceChange,cbFlagPriceChange.Checked);
fCurrentItem.SetFlagValue(ilifAvailChange,cbFlagAvailChange.Checked);
fCurrentItem.SetFlagValue(ilifNotAvailable,cbFlagNotAvailable.Checked);
fCurrentItem.SetFlagValue(ilifLost,cbFlagLost.Checked);
fCurrentItem.SetFlagValue(ilifDiscarded,cbFlagDiscarded.Checked);
fCurrentItem.TextTag := eTextTag.Text;
fCurrentItem.NumTag := seNumTag.Value;
// extended specs
fCurrentItem.WantedLevel := seWantedLevel.Value;
fCurrentItem.Variant := leVariant.Text;
fCurrentItem.VariantTag := leVariantTag.Text;
fCurrentItem.SurfaceFinish := TILItemSurfaceFinish(cmbSurfaceFinish.ItemIndex);
fCurrentItem.Material := TILItemMaterial(cmbMaterial.ItemIndex);
fCurrentItem.Thickness := seThickness.Value;
fCurrentItem.SizeX := seSizeX.Value;
fCurrentItem.SizeY := seSizeY.Value;
fCurrentItem.SizeZ := seSizeZ.Value;
fCurrentItem.UnitWeight := seUnitWeight.Value;
// others
fCurrentItem.Notes := meNotes.Text;
fCurrentItem.ReviewURL := leReviewURL.Text;
fCurrentItem.UnitPriceDefault := seUnitPriceDefault.Value;
fCurrentItem.Rating := seRating.Value;
finally
fCurrentItem.EndUpdate;
end
end;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.FrameLoad;
begin
If Assigned(fCurrentItem) then
begin
fInitializing := True;
try
imgItemLock.Visible := fCurrentItem.Encrypted;
// internals
lblUniqueID.Caption := GUIDToString(fCurrentItem.UniqueID);
lblTimeOfAddition.Caption := IL_FormatDateTime('yyyy-mm-dd hh:nn:ss',fCurrentItem.TimeOfAddition);
// header
UpdateTitle(nil,fCurrentItem);
ReplaceManufacturerLogo;
UpdatePictures(nil,fCurrentItem);
// basic specs
cmbItemType.ItemIndex := Ord(fCurrentItem.ItemType);
leItemTypeSpecification.Text := fCurrentItem.ItemTypeSpec;
sePieces.Value := fCurrentItem.Pieces;
leUserID.Text := fCurrentItem.UserID;
cmbManufacturer.ItemIndex := Ord(fCurrentItem.Manufacturer);
leManufacturerString.Text := fCurrentItem.ManufacturerStr;
leTextID.Text := fCurrentItem.TextID;
seNumID.Value := fCurrentItem.NumID;
// tags, flags
FillFlagsFromItem;
eTextTag.Text := fCurrentItem.TextTag;
seNumTag.Value := fCurrentITem.NumTag;
// extended specs
seWantedLevel.Value := fCurrentItem.WantedLevel;
leVariant.Text := fCurrentItem.Variant;
leVariantTag.Text := fCurrentItem.VariantTag;
cmbSurfaceFinish.ItemIndex := Ord(fCurrentItem.SurfaceFinish);
cmbMaterial.ItemIndex := Ord(fCurrentItem.Material);
seThickness.Value := fCurrentItem.Thickness;
seSizeX.Value := fCurrentItem.SizeX;
seSizeY.Value := fCurrentItem.SizeY;
seSizeZ.Value := fCurrentItem.SizeZ;
seUnitWeight.Value := fCurrentItem.UnitWeight;
// others
meNotes.Text := fCurrentItem.Notes;
leReviewURL.Text := fCurrentItem.ReviewURL;
seUnitPriceDefault.Value := fCurrentItem.UnitPriceDefault;
seRating.Value := fCurrentItem.Rating;
lblRatingDetails.Visible := Length(fCurrentItem.RatingDetails) > 0;
FillValues;
finally
fInitializing := False;
end;
end;
end;
//==============================================================================
procedure TfrmItemFrame.Initialize(ILManager: TILManager);
var
i: Integer;
begin
fPicturesManager := TILShownPicturesManager.Create(
ILManager,imgPictureC.BoundsRect.Right,imgPrevPicture,imgNextPicture,
imgPictureA,imgPictureB,imgPictureC,shpPictureABcgr,shpPictureBBcgr,shpPictureCBcgr);
fInitializing := False;
fCurrentItem := nil;
fLastFoundValue := ilisrNone;
fILManager := ILManager;
fILManager.OnItemTitleUpdate := UpdateTitle;
fILManager.OnItemPicturesUpdate := UpdatePictures;
fILManager.OnItemFlagsUpdate := UpdateFlags;
fILManager.OnItemValuesUpdate := UpdateValues;
fILManager.OnItemOthersUpdate := UpdateOthers;
SetItem(nil,True);
// prepare objects
imgPrevPicture.Tag := 0;
imgNextPicture.Tag := 0;
// fill drop-down lists...
// types
cmbItemType.Items.BeginUpdate;
try
cmbItemType.Items.Clear;
For i := Ord(Low(TILItemType)) to Ord(High(TILItemType)) do
cmbItemType.Items.Add(fILManager.DataProvider.GetItemTypeString(TILItemType(i)))
finally
cmbItemType.Items.EndUpdate;
end;
// manufacturers
cmbManufacturer.Items.BeginUpdate;
try
cmbManufacturer.Items.Clear;
For i := Ord(Low(TILItemManufacturer)) to Ord(High(TILItemManufacturer)) do
cmbManufacturer.Items.Add(fILManager.DataProvider.ItemManufacturers[TILItemManufacturer(i)].Str);
finally
cmbManufacturer.Items.EndUpdate;
end;
// material
cmbMaterial.Items.BeginUpdate;
try
cmbMaterial.Items.Clear;
For i := Ord(Low(TILItemMaterial)) to Ord(High(TILItemMaterial)) do
cmbMaterial.Items.Add(fILManager.DataProvider.GetItemMaterialString(TILItemMaterial(i)));
finally
cmbMaterial.Items.EndUpdate;
end;
// surface
cmbSurfaceFinish.Items.BeginUpdate;
try
cmbSurfaceFinish.Items.Clear;
For i := Ord(Low(TILItemSurfaceFinish)) to Ord(High(TILItemSurfaceFinish)) do
cmbSurfaceFinish.Items.Add(fILManager.DataProvider.GetItemSurfaceFinishString(TILItemSurfaceFinish(i)));
finally
cmbSurfaceFinish.Items.EndUpdate;
end;
// initialization
seNumTag.MinValue := IL_ITEM_NUM_TAG_MIN;
seNumTag.MaxValue := IL_ITEM_NUM_TAG_MAX;
lblUnitDefaultPrice.Caption := IL_Format(lblUnitDefaultPrice.Caption,[IL_CURRENCY_SYMBOL]);
DisableHighlight;
BuildFlagMacrosMenu;
PrepareArrows;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.Finalize;
begin
fILManager.OnItemTitleUpdate := nil;
fILManager.OnItemPicturesUpdate := nil;
fILManager.OnItemFlagsUpdate := nil;
fILManager.OnItemValuesUpdate := nil;
fILManager.OnItemOthersUpdate := nil;
FreeAndNil(fPicturesManager);
FreeAndNil(fPicArrowLeft);
FreeAndNil(fPicArrowRight);
FreeAndNil(fPicArrowLeftD);
FreeAndNil(fPicArrowRightD);
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.Save;
begin
FrameSave;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.Load;
begin
If Assigned(fCurrentItem) then
FrameLoad
else
FrameClear;
DisableHighlight;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.SetItem(Item: TILItem; ProcessChange: Boolean);
var
Reassigned: Boolean;
begin
Reassigned := fCurrentItem = Item;
If ProcessChange then
begin
If Assigned(fCurrentItem) and not Reassigned then
FrameSave;
If Assigned(Item) then
begin
fCurrentItem := Item;
If not Reassigned then
FrameLoad;
end
else
begin
fCurrentItem := nil;
FrameClear;
end;
Visible := Assigned(fCurrentItem) and fCurrentItem.DataAccessible;
Enabled := Assigned(fCurrentItem) and fCurrentItem.DataAccessible;
end
else fCurrentItem := Item;
DisableHighlight;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.FindPrev(const Text: String);
var
FoundValue: TILItemSearchResult;
begin
If Assigned(fCurrentItem) then
begin
FrameSave;
FoundValue := fCurrentItem.FindPrev(Text,fLastFoundValue);
If FoundValue <> ilisrNone then
begin
DisableHighlight;
Highlight(FoundValue);
fLastFoundValue := FoundValue;
end
else
begin
If tmrHighlightTimer.Enabled then
tmrHighlightTimer.Tag := IL_SEARCH_HIGHLIGHT_TIMEOUT;
Beep;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.FindNext(const Text: String);
var
FoundValue: TILItemSearchResult;
begin
If Assigned(fCurrentItem) then
begin
FrameSave;
FoundValue := fCurrentItem.FindNext(Text,fLastFoundValue);
If FoundValue <> ilisrNone then
begin
DisableHighlight;
Highlight(FoundValue);
fLastFoundValue := FoundValue;
end
else
begin
If tmrHighlightTimer.Enabled then
tmrHighlightTimer.Tag := IL_SEARCH_HIGHLIGHT_TIMEOUT;
Beep;
end;
end;
end;
//==============================================================================
procedure TfrmItemFrame.FrameResize(Sender: TObject);
begin
DisableHighlight;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.lblItemTitleClick(Sender: TObject);
begin
If Assigned(OnShowSelectedItem) then
OnShowSelectedItem(Self);
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.tmrSecondaryPicsTimer(Sender: TObject);
begin
If imgNextPicture.Tag <> 0 then
imgNextPicture.OnMouseDown(nil,mbLeft,[],0,0)
else If imgPrevPicture.Tag <> 0 then
imgPrevPicture.OnMouseDown(nil,mbLeft,[],0,0);
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.tmrHighlightTimerTimer(Sender: TObject);
begin
tmrHighlightTimer.Tag := tmrHighlightTimer.Tag - 1;
If tmrHighlightTimer.Tag <= 0 then
DisableHighlight;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.imgPrevPictureMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
imgPrevPicture.Picture.Assign(fPicArrowLeftD);
If Assigned(fCurrentItem) then
begin
fCurrentItem.Pictures.PrevSecondary;
fPicturesManager.UpdateSecondary;
imgPrevPicture.Tag := -1;
tmrSecondaryPics.Enabled := True;
end;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.imgPrevPictureMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
imgPrevPicture.Picture.Assign(fPicArrowLeft);
imgPrevPicture.Tag := 0;
tmrSecondaryPics.Enabled := False;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.imgNextPictureMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
imgNextPicture.Picture.Assign(fPicArrowRightD);
If Assigned(fCurrentItem) then
begin
fCurrentItem.Pictures.NextSecondary;
fPicturesManager.UpdateSecondary;
imgNextPicture.Tag := -1;
tmrSecondaryPics.Enabled := True;
end;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.imgNextPictureMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
imgNextPicture.Picture.Assign(fPicArrowRight);
imgNextPicture.Tag := 0;
tmrSecondaryPics.Enabled := False;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.imgPictureClick(Sender: TObject);
procedure OpenPicture(Index: Integer);
begin
If fCurrentItem.Pictures.CheckIndex(Index) then
fCurrentItem.Pictures.OpenPictureFile(Index);
end;
begin
If Assigned(fCurrentItem) and (Sender is TImage) then
case fPicturesManager.Kind(TImage(Sender)) of
ilipkMain: OpenPicture(fCurrentItem.Pictures.IndexOfItemPicture);
ilipkSecondary: OpenPicture(fCurrentItem.Pictures.CurrentSecondary);
ilipkPackage: OpenPicture(fCurrentItem.Pictures.IndexOfPackagePicture);
end;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.cmbItemTypeChange(Sender: TObject);
begin
If not fInitializing and Assigned(fCurrentItem) then
fCurrentItem.ItemType := TILItemType(cmbItemType.ItemIndex);
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.leItemTypeSpecificationChange(Sender: TObject);
begin
If not fInitializing and Assigned(fCurrentItem) then
fCurrentItem.ItemTypeSpec := leItemTypeSpecification.Text;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.sePiecesChange(Sender: TObject);
begin
If not fInitializing and Assigned(fCurrentItem) then
fCurrentItem.Pieces := sePieces.Value;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.leUserIDChange(Sender: TObject);
begin
If not fInitializing and Assigned(fCurrentItem) then
fCurrentItem.UserID := leUserID.Text;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.btnUserIDGenClick(Sender: TObject);
var
NewID: String;
begin
If Assigned(fCurrentItem) then
If Length(fCurrentItem.UserID) <= 0 then
begin
If fILManager.GenerateUserID(NewID) then
leUserID.Text := NewID // this will also set it in the current item
else
MessageDlg('Unable to generate unique user ID.',mtError,[mbOK],0);
end;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.cmbManufacturerChange(Sender: TObject);
begin
If not fInitializing and Assigned(fCurrentItem) then
begin
fCurrentItem.Manufacturer := TILItemManufacturer(cmbManufacturer.ItemIndex);
ReplaceManufacturerLogo;
end;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.leManufacturerStringChange(Sender: TObject);
begin
If not fInitializing and Assigned(fCurrentItem) then
fCurrentItem.ManufacturerStr := leManufacturerString.Text;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.leTextIDChange(Sender: TObject);
begin
If not fInitializing and Assigned(fCurrentItem) then
fCurrentItem.TextID := leTextID.Text;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.seNumIDChange(Sender: TObject);
begin
If not fInitializing and Assigned(fCurrentItem) then
fCurrentItem.NumID := seNumID.Value;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.CommonFlagClick(Sender: TObject);
begin
If Sender is TCheckBox then
If not fInitializing and Assigned(fCurrentItem) then
case TCheckBox(Sender).Tag of
1: fCurrentItem.SetFlagValue(ilifOwned,cbFlagOwned.Checked);
2: fCurrentItem.SetFlagValue(ilifWanted,cbFlagWanted.Checked);
3: fCurrentItem.SetFlagValue(ilifOrdered,cbFlagOrdered.Checked);
4: fCurrentItem.SetFlagValue(ilifBoxed,cbFlagBoxed.Checked);
5: fCurrentItem.SetFlagValue(ilifElsewhere,cbFlagElsewhere.Checked);
6: fCurrentItem.SetFlagValue(ilifUntested,cbFlagUntested.Checked);
7: fCurrentItem.SetFlagValue(ilifTesting,cbFlagTesting.Checked);
8: fCurrentItem.SetFlagValue(ilifTested,cbFlagTested.Checked);
9: fCurrentItem.SetFlagValue(ilifDamaged,cbFlagDamaged.Checked);
10: fCurrentItem.SetFlagValue(ilifRepaired,cbFlagRepaired.Checked);
11: fCurrentItem.SetFlagValue(ilifPriceChange,cbFlagPriceChange.Checked);
12: fCurrentItem.SetFlagValue(ilifAvailChange,cbFlagAvailChange.Checked);
13: fCurrentItem.SetFlagValue(ilifNotAvailable,cbFlagNotAvailable.Checked);
14: fCurrentItem.SetFlagValue(ilifLost,cbFlagLost.Checked);
15: fCurrentItem.SetFlagValue(ilifDiscarded,cbFlagDiscarded.Checked);
else
Exit;
end;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.btnFlagMacrosClick(Sender: TObject);
var
ScreenPoint: TPoint;
begin
ScreenPoint := btnFlagMacros.ClientToScreen(Point(btnFlagMacros.Width,btnFlagMacros.Height));
pmnFlagMacros.Popup(ScreenPoint.X,ScreenPoint.Y);
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.CommonFlagMacroClick(Sender: TObject);
begin
If (Sender is TMenuItem) and Assigned(fCurrentItem) then
case TMenuItem(Sender).Tag of
// ordered item received
0: If [ilifWanted,ilifOrdered] <= fCurrentItem.Flags then
begin
fCurrentItem.BeginUpdate;
try
fCurrentItem.SetFlagValue(ilifWanted,False);
fCurrentItem.SetFlagValue(ilifOrdered,False);
fCurrentItem.SetFlagValue(ilifOwned,True);
fCurrentItem.SetFlagValue(ilifUntested,True);
finally
fCurrentItem.EndUpdate;
end;
end;
// starting item testing
1: If ilifUntested in fCurrentItem.Flags then
begin
fCurrentItem.BeginUpdate;
try
fCurrentItem.SetFlagValue(ilifUntested,False);
fCurrentItem.SetFlagValue(ilifTesting,True);
finally
fCurrentItem.EndUpdate;
end;
end;
// testing of item is finished
2: If ilifTesting in fCurrentItem.Flags then
begin
fCurrentItem.BeginUpdate;
try
fCurrentItem.SetFlagValue(ilifTesting,False);
fCurrentItem.SetFlagValue(ilifTested,True);
finally
fCurrentItem.EndUpdate;
end;
end;
// damage has been repaired
3: If ilifDamaged in fCurrentItem.Flags then
begin
fCurrentItem.BeginUpdate;
try
fCurrentItem.SetFlagValue(ilifDamaged,False);
fCurrentItem.SetFlagValue(ilifRepaired,True);
finally
fCurrentItem.EndUpdate;
end;
end;
// price and availability change checked
4: begin
fCurrentItem.BeginUpdate;
try
fCurrentItem.SetFlagValue(ilifPriceChange,False);
fCurrentItem.SetFlagValue(ilifAvailChange,False);
finally
fCurrentItem.EndUpdate;
end;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.eTextTagChange(Sender: TObject);
begin
If not fInitializing and Assigned(fCurrentItem) then
fCurrentItem.TextTag := eTextTag.Text;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.seNumTagChange(Sender: TObject);
begin
If not fInitializing and Assigned(fCurrentItem) then
fCurrentItem.NumTag := seNumTag.Value;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.seWantedLevelChange(Sender: TObject);
begin
If not fInitializing and Assigned(fCurrentItem) then
fCurrentItem.WantedLevel := seWantedLevel.Value;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.leVariantChange(Sender: TObject);
begin
If not fInitializing and Assigned(fCurrentItem) then
fCurrentItem.Variant := leVariant.Text;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.cmbSurfaceFinishChange(Sender: TObject);
begin
If not fInitializing and Assigned(fCurrentItem) then
fCurrentItem.SurfaceFinish := TILItemSurfaceFinish(cmbSurfaceFinish.ItemIndex);
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.cmbMaterialChange(Sender: TObject);
begin
If not fInitializing and Assigned(fCurrentItem) then
fCurrentItem.Material := TILItemMaterial(cmbMaterial.ItemIndex);
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.seSizeXChange(Sender: TObject);
begin
If not fInitializing and Assigned(fCurrentItem) then
fCurrentItem.SizeX := seSizeX.Value;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.seSizeYChange(Sender: TObject);
begin
If not fInitializing and Assigned(fCurrentItem) then
fCurrentItem.SizeY := seSizeY.Value;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.seSizeZChange(Sender: TObject);
begin
If not fInitializing and Assigned(fCurrentItem) then
fCurrentItem.SizeZ := seSizeZ.Value;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.seUnitWeightChange(Sender: TObject);
begin
If not fInitializing and Assigned(fCurrentItem) then
fCurrentItem.UnitWeight := seUnitWeight.Value;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.meNotesKeyPress(Sender: TObject; var Key: Char);
begin
If Key = ^A then
begin
meNotes.SelectAll;
Key := #0;
end;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.lblNotesEditClick(Sender: TObject);
var
Temp: String;
begin
If Assigned(fCurrentItem) then
begin
Temp := meNotes.Text;
fTextEditForm.ShowTextEditor('Edit item notes',Temp,False);
meNotes.Text := Temp;
meNotes.SelStart := Length(meNotes.Text);
meNotes.SelLength := 0;
end;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.lblNotesEditMouseEnter(Sender: TObject);
begin
lblNotesEdit.Font.Style := lblNotesEdit.Font.Style + [fsBold];
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.lblNotesEditMouseLeave(Sender: TObject);
begin
lblNotesEdit.Font.Style := lblNotesEdit.Font.Style - [fsBold];
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.leReviewURLChange(Sender: TObject);
begin
If not fInitializing and Assigned(fCurrentItem) then
fCurrentItem.ReviewURL := leReviewURL.Text;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.btnReviewOpenClick(Sender: TObject);
begin
If Assigned(fCurrentItem) then
IL_ShellOpen(Self.Handle,fCurrentItem.ReviewURL);
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.seUnitPriceDefaultChange(Sender: TObject);
begin
If not fInitializing and Assigned(fCurrentItem) then
fCurrentItem.UnitPriceDefault := seUnitPriceDefault.Value;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.seRatingChange(Sender: TObject);
begin
If not fInitializing and Assigned(fCurrentItem) then
fCurrentItem.Rating := seRating.Value;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.btnRatingDetailsClick(Sender: TObject);
var
Temp: String;
begin
If Assigned(fCurrentItem) then
begin
Temp := fCurrentItem.RatingDetails;
fTextEditForm.ShowTextEditor('Edit item rating details',Temp,False);
fCurrentItem.RatingDetails := Temp;
end;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.btnPicturesClick(Sender: TObject);
begin
If Assigned(fCurrentItem) then
begin
fItemPicturesForm.ShowPictures(fCurrentItem);
If Assigned(OnFocusList) then
OnFocusList(Self);
end;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.btnShopsClick(Sender: TObject);
begin
If Assigned(fCurrentItem) then
begin
fCurrentItem.BroadcastReqCount; // should not be needed, but to be sure
fShopsForm.ShowShops(fCurrentItem);
If Assigned(OnFocusList) then
OnFocusList(Self);
end;
end;
//------------------------------------------------------------------------------
procedure TfrmItemFrame.btnUpdateShopsClick(Sender: TObject);
var
i: Integer;
Temp: TILItemShopUpdateList;
begin
If Assigned(fCurrentItem) then
begin
If fCurrentItem.ShopCount > 0 then
begin
fCurrentItem.BroadcastReqCount; // should not be needed
SetLength(Temp,fCurrentItem.ShopCount);
For i := Low(Temp) to High(Temp) do
begin
Temp[i].Item := fCurrentItem;
Temp[i].ItemTitle := IL_Format('[#%d] %s',[fCurrentItem.Index + 1,fCurrentItem.TitleStr]);
Temp[i].ItemShop := fCurrentItem.Shops[i];
Temp[i].Done := False;
end;
fUpdateForm.ShowUpdate(Temp);
// changes are loaded automatically
If Assigned(OnFocusList) then
OnFocusList(Self);
end
else MessageDlg('No shop to update.',mtInformation,[mbOK],0);
end;
end;
end.
|
unit T4502;
interface
uses
Classes, Contnrs,
PCI1751;
type
TS3 = string[3];
TS4 = string[4];
TS6 = string[6];
TOCTSet = '0'..'7';
PT4502_IO = ^TT4502_IO;
TT4502_IO = class(TPCI1751)
private
protected
procedure OutputCycle(const ADDR8, DATA8: TS6);
procedure InputCycle(const ADDR8: TS6; var DATA8: TS6);
public
constructor Create;
function RS(const ADDR: TS3): Word; overload; // Регистр состояния 16xxx0
function RS: Word; overload; // Регистр состояния 16xxx0
procedure W(const ADDR: TS3; DATA: TS4); // Выходной буфер 16xxx2
function R(const ADDR: TS3): Word; // Входной буфер 16xxx4
// property REG0(ADDR: TS3): Word read GetREG0 write SetREG0;
end;
type
TCommand = record
K: TS4;
V: TS4;
end;
PCommand = ^TCommand;
TTestResult = record
Val: Extended;
Units: string;
Good: Boolean;
end;
TTest = class(TList)
private
fN: Cardinal;
function Get(Index: Integer): PCommand;
public
constructor Create; overload;
constructor Create(const TestN: Cardinal; TestStr: String); overload;
destructor Destroy; override;
function Add(Value: PCommand): Integer;
function AddCommand(K, V: String): Integer;
function Execute: TTestResult;
procedure ExecCommand(const Command: TCommand);
property Items[Index: Integer]: PCommand read Get; default;
property N: Cardinal read fN write fN;
end;
TRunMode = (rmNormal, rmStep, rmLoop);
TPlanResult = (prGood, prDefect);
TPlan = class(TObjectList)
private
fFile: TStringList;
fCaption: string;
function GetItems(Index: Integer): TTest;
procedure SetItems(Index: Integer; const Value: TTest);
public
constructor Create;
destructor Destroy; override;
procedure LoadFromFile(const FileName: string);
function Execute(const RunMode: TRunMode): TPlanResult;
property Items[Index: Integer]: TTest read GetItems write SetItems; default;
property Caption: String read fCaption write fCaption;
end;
TT4502_Program = class(TObject)
private
fPlans: array[1..15] of TPlan;
function GetPlan(Index: Integer): TPlan;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure LoadFromFile(const FileName: string);
property Plans[Index: Integer]: TPlan read GetPlan;
end;
type
TT4502 = class(TObject)
private
// fIO: TT4502_IO;
fWP: TT4502_Program;
protected
public
// property Commands: TT4502_Commands read fCommands;
constructor Create;
destructor Destroy; override;
function PASS: Boolean; // ПРОПУСК
procedure WriteCommand(Command, Data: TS4);
function ReadCommand(Command: TS4): Word;
// property IO: TT4502_IO read fIO;
property WP: TT4502_Program read fWP;
end;
var
fIO: TT4502_IO;
implementation
uses
Windows, StrUtils, SysUtils,
CONVUNIT, PerlRegEx;
function StrOemToAnsi(const aStr : AnsiString) : AnsiString;
var
Len : Integer;
begin
Len := Length(aStr);
SetLength(Result, Len);
OemToCharBuffA(PAnsiChar(aStr), PAnsiChar(Result), Len);
end;
constructor TT4502_IO.Create;
begin
inherited Create(0);
if not fEmulation then
begin
{ К ДА = $FFFF }
Out32(fBaseAddr + 1, $FF); // PB0 = $FF
Out32(fBaseAddr + 5, $FF); // PB1 = $FF
{ Управляющие сигналы }
PC1[2] := 1; // К СБРОС
PC1[3] := 1; // К СИА
PC1[4] := 1; // К БАЙТ
PC1[5] := 1; // К ВУ
PC1[6] := 1; // К ВЫВОД
PC1[7] := 1; // К ВВОД
{ Режим работы портов }
P0_Mode := $19; // PA0 - in; PB0 - out; PC0 - in
P1_Mode := $10; // PA1 - in; PB1 - out; PC1 - out
{ Сигнал "К СБРОС" }
PC1[2] := 0;
PC1[2] := 1;
end;
end;
//------------------------------------------------------------------------------
// Цыкл "ВЫВОД"
// передача данных в тестер
//------------------------------------------------------------------------------
procedure TT4502_IO.OutputCycle(const ADDR8, DATA8: TS6);
var
ADDR_DEC: Word;
DATA_DEC: Word;
// D0, D1: Byte;
begin
ADDR_DEC := OCT2DEC(ADDR8);
DATA_DEC := OCT2DEC(DATA8);
// 1. К ДА = ADDR
Out32(fBaseAddr + 1, Lo(not ADDR_DEC)); // PB0
Out32(fBaseAddr + 5, Hi(not ADDR_DEC)); // PB1
// 2. К ВУ = 0
PC1[5] := 0;
// 3. К СИА = 0
PC1[3] := 0;
// 4. К ДА = $FFFF
// Out32(fPCI1751.BaseAddr + 1, $FF); // PB0
// Out32(fPCI1751.BaseAddr + 5, $FF); // PB1
// 5. К ВУ = 1
PC1[5] := 1;
// 6. К ДА = DATA
Out32(fBaseAddr + 1, Lo(not DATA_DEC)); // PB0
Out32(fBaseAddr + 5, Hi(not DATA_DEC)); // PB1
// 7. К ВЫВОД = 0
PC1[6] := 0;
// 8. Ждем, пока К СИП не станет равен 0
// while (PC0[2] = 1) do ;
// 9. К ВЫВОД = 1
PC1[6] := 1;
// 10. К ДА = $FFFF
Out32(fBaseAddr + 1, $FF); // PB0
Out32(fBaseAddr + 5, $FF); // PB1
// 11. Ждем, пока К СИП не станет равен 1
// while (PC0[2] = 0) do ;
// 12. К СИА = 1
PC1[3] := 1;
end;
//------------------------------------------------------------------------------
// Цыкл "ВВОД"
// передача данных из тестера
//------------------------------------------------------------------------------
procedure TT4502_IO.InputCycle(const ADDR8: TS6; var DATA8: TS6);
var
ADDR_DEC: Word;
DATA_DEC_Array: array[0..1] of Byte;
DATA_DEC: word absolute DATA_DEC_Array;
begin
ADDR_DEC := OCT2DEC(ADDR8);
// 1. К ДА = ADDR
Out32(fBaseAddr + 1, Lo(not ADDR_DEC)); // PB0
Out32(fBaseAddr + 5, Hi(not ADDR_DEC)); // PB1
// 2. К ВУ = 0
PC1[5] := 0;
// 3. К СИА = 0
PC1[3] := 0;
// 4. К ДА = $FFFF
Out32(fBaseAddr + 1, $FF); // PB0
Out32(fBaseAddr + 5, $FF); // PB1
// 5. К ВУ = 1
PC1[5] := 1;
// 6. К ВВОД = 0
PC1[7] := 0;
// 7. Ждем, пока К СИП не станет равен 0
// while (PC0[2] = 1) do ;
// 8. К ВВОД = 1
PC1[7] := 1;
// 9. Считываем данные
DATA_DEC_Array[0] := not Inp32(fBaseAddr + 0);
DATA_DEC_Array[1] := not Inp32(fBaseAddr + 4);
DATA8 := DEC2OCT(DATA_DEC);
// 10. Ждем, пока К СИП не станет равен 1
// while (PC0[2] = 0) do ;
// 11. К СИА = 1
PC1[3] := 1;
end;
function TT4502_IO.RS(const ADDR: TS3): Word;
var
D: TS6;
begin
InputCycle('16' + ADDR + '0', D);
Result := OCT2DEC(D);
end;
procedure TT4502_IO.W(const ADDR: TS3; DATA: TS4);
begin
OutputCycle('16' + ADDR + '2', DATA);
end;
function TT4502_IO.R(const ADDR: TS3): Word;
var
D: TS6;
begin
InputCycle('16' + ADDR + '4', D);
Result := OCT2DEC(D);
end;
function TT4502_IO.RS: Word;
begin
Result := RS('000');
end;
{ TT4502 }
constructor TT4502.Create;
begin
inherited Create;
// fIO := TT4502_IO.Create;
fWP := TT4502_Program.Create;
end;
destructor TT4502.Destroy;
begin
// fIO.Free;
fWP.Free;
inherited;
end;
function TT4502.PASS: Boolean;
begin
Result := ((fIO.RS shr 7) and 1) = 1;
end;
function TT4502.ReadCommand(Command: TS4): Word;
begin
Result := fIO.R(RightStr(Command, 3));
end;
procedure TT4502.WriteCommand(Command, Data: TS4);
begin
fIO.W(RightStr(Command, 3), Data);
end;
{ TT4502_Program }
procedure TT4502_Program.Clear;
var
i: Byte;
begin
for i := Low(fPlans) to High(fPlans) do
begin
fPlans[i].Clear;
end;
end;
constructor TT4502_Program.Create;
var
i: Byte;
begin
inherited Create;
for i := Low(fPlans) to High(fPlans) do
fPlans[i] := TPlan.Create;
end;
destructor TT4502_Program.Destroy;
var
i: Byte;
begin
for i := Low(fPlans) to High(fPlans) do
fPlans[i].Free;
inherited;
end;
function TT4502_Program.GetPlan(Index: Integer): TPlan;
begin
if Index in [Low(fPlans)..High(fPlans)] then
Result := fPlans[Index]
else
Result := nil;
end;
procedure TT4502_Program.LoadFromFile(const FileName: string);
begin
if FileExists(FileName) then
begin
// fFile.LoadFromFile(FileName);
// Clear;
// Parse;
end;
end;
{ TTest }
function TTest.Add(Value: PCommand): Integer;
begin
Result := inherited Add(Value);
end;
function TTest.AddCommand(K, V: String): Integer;
var
P: PCommand;
begin
New(P);
P.K := K;
P.V := V;
Result := Add(P);
end;
constructor TTest.Create;
begin
inherited Create;
fN := 0;
end;
constructor TTest.Create(const TestN: Cardinal; TestStr: String);
const
// RE_Command = '([а-яА-Яa-zA-Z0-9]+)\s([а-яА-Яa-zA-Z0-9]+)';
RE_Command = '(И[1-7][1-2]|И73|Y0[1-2]|R|Д0[1-2]|0[1-9]|[1-3][0-9]|4[0-8])\s(\d+)';
var
Regex: TPerlRegEx;
begin
{ Пустая строка }
if Trim(TestStr) = '' then
begin
Create;
Exit;
end;
inherited Create;
fN := TestN;
Regex := TPerlRegEx.Create;
try
Regex.RegEx := RE_Command;
Regex.Options := [preSingleLine];
Regex.Subject := TestStr;
if Regex.Match then
begin
repeat
if Regex.GroupCount >= 1 then
begin
AddCommand(Regex.Groups[1], Regex.Groups[2]);
end;
until not Regex.MatchAgain;
end;
finally
Regex.Free;
end;
end;
destructor TTest.Destroy;
var
i: Integer;
begin
for i := 0 to Count - 1 do
Dispose(Items[i]);
inherited;
end;
procedure TTest.ExecCommand(const Command: TCommand);
begin
if Assigned(fIO) then
begin
end;
end;
function TTest.Execute: TTestResult;
var
Command: Integer;
begin
write(#9);
for Command := 0 to Count-1 do
begin
write(Items[Command]^.K, ' ', Items[Command]^.V, '; ');
ExecCommand(Items[Command]^);
end;
Writeln;
end;
function TTest.Get(Index: Integer): PCommand;
begin
Result := PCommand(inherited Get(Index));
end;
{ TPlan }
function TPlan.GetItems(Index: Integer): TTest;
begin
Result := TTest(inherited GetItem(Index));
end;
procedure TPlan.SetItems(Index: Integer; const Value: TTest);
begin
inherited SetItem(Index, Value);
end;
constructor TPlan.Create;
begin
inherited Create;
fFile := TStringList.Create;
fCaption := '';
end;
destructor TPlan.Destroy;
var
i: Integer;
begin
fFile.Free;
inherited;
end;
procedure TPlan.LoadFromFile(const FileName: string);
const
// RE_Test = 'T(\d*)\r\n(.*?)(?:KT;|XX)';
RE_Test = 'T(\d*)\r\n(.*?)KT;'; // регулярное выражение для поиска теста
var
Regex: TPerlRegEx;
i: Integer;
begin
{ Проверка существования файла }
if not FileExists(FileName) then
Exit;
{ Загрузка тектса программы и конвертация ее из OEM->ANSI }
fFile.LoadFromFile(FileName);
fFile.Text := StrOemToAnsi(fFile.Text);
// fFile.SaveToFile(ChangeFileExt(FileName, '.NEW'));
{ Удаляем строки комментариев из текста программы }
for i := fFile.count - 1 downto 0 do
begin
if Trim(fFile[I])[1] = '#' then
fFile.Delete(I);
end;
fCaption := Trim(fFile[0]); // 1-ая строка - Название плана
Clear;
{ Разбор текста программы по тестам }
Regex := TPerlRegEx.Create;
try
Regex.RegEx := RE_Test;
Regex.Options := [preSingleLine, preMultiLine];
Regex.Subject := fFile.Text;
if Regex.Match then
begin
repeat
if Regex.GroupCount >= 1 then
begin
Add(TTest.Create(StrToInt(Regex.Groups[1]), Regex.Groups[2]));
end;
until not Regex.MatchAgain;
end;
finally
Regex.Free;
end;
end;
function TPlan.Execute(const RunMode: TRunMode): TPlanResult;
var
Test: Integer;
begin
Result := prGood;
for Test := 0 to Count - 1 do
begin
Writeln('Выполняется тест №', Test+1);
Items[Test].Execute;
end;
end;
end.
|
unit frm_ScriptIDE;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, HCCompiler,
frm_Script, SynEdit, Vcl.ExtCtrls, Vcl.StdCtrls, SynCompletionProposal;
type
TfrmScriptIDE = class(TForm)
pnl1: TPanel;
btnSave: TButton;
btnCompile: TButton;
pnlMessage: TPanel;
pnl2: TPanel;
lblMsg: TLabel;
lstMessage: TListBox;
spl2: TSplitter;
lbl1: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure btnCompileClick(Sender: TObject);
procedure lstMessageDblClick(Sender: TObject);
private
{ Private declarations }
//FCompiler: THCCompiler; // 编译器
FFrmScript: TfrmScript; // 代码书写窗体
FLastChange: Boolean; // 代码变动刻度
FOnSave, // 保存脚本
FOnCompile, // 编译
FOnCompilePreview // 预编译为代码提示服务
: TNotifyEvent;
FOnProposal: TProposalEvent;
function GetOnCodeCompletion: TCodeCompletionEvent;
procedure SetOnCodeCompletion(const Value: TCodeCompletionEvent);
procedure SetScript(const AScript: string);
function GetScript: string;
procedure DoSynEditKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure DoSynEditChange(Sender: TObject);
procedure DoProposal(const AWord: string; const AInsertList, AItemList: TStrings);
procedure SetErrorLineNo(const ALine: Integer);
public
{ Public declarations }
procedure ClearDebugInfo;
procedure SetDebugCaption(const AText: string);
procedure AddWarning(const ALineNo: Integer; const AWarning: string);
procedure AddError(const ALineNo: Integer; const AError: string);
property Script: string read GetScript write SetScript;
// property Compiler: THCCompiler read FCompiler;
property OnProposal: TProposalEvent read FOnProposal write FOnProposal;
property OnCodeCompletion: TCodeCompletionEvent read GetOnCodeCompletion write SetOnCodeCompletion;
property OnSave: TNotifyEvent read FOnSave write FOnSave;
property OnCompile: TNotifyEvent read FOnCompile write FOnCompile;
property OnCompilePreview: TNotifyEvent read FOnCompilePreview write FOnCompilePreview;
end;
implementation
type
TDebugInfo = class(TObject)
public
Line: Integer;
end;
{$R *.dfm}
procedure TfrmScriptIDE.btnSaveClick(Sender: TObject);
begin
if Assigned(FOnSave) then
FOnSave(Self)
else
Self.ModalResult := mrOk;
end;
procedure TfrmScriptIDE.ClearDebugInfo;
var
i: Integer;
begin
for i := 0 to lstMessage.Items.Count - 1 do
TDebugInfo(lstMessage.Items.Objects[i]).Free;
lstMessage.Clear;
end;
procedure TfrmScriptIDE.DoProposal(const AWord: string; const AInsertList,
AItemList: TStrings);
begin
if Assigned(FOnCompilePreview) then // 预编译为代码提示服务
begin
if FLastChange then // 上次预编译完有变动
begin
FLastChange := False;
try
FOnCompilePreview(Self);
except
end;
end;
end;
if Assigned(FOnProposal) then
FOnProposal(AWord, AInsertList, AItemList);
end;
procedure TfrmScriptIDE.DoSynEditChange(Sender: TObject);
begin
FLastChange := True;
end;
procedure TfrmScriptIDE.DoSynEditKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Shift = [ssCtrl]) and (Key = Ord('S')) then
btnSaveClick(Sender);
end;
procedure TfrmScriptIDE.AddError(const ALineNo: Integer; const AError: string);
var
vDebugInfo: TDebugInfo;
begin
vDebugInfo := TDebugInfo.Create;
vDebugInfo.Line := ALineNo;
lstMessage.AddItem(AError, vDebugInfo);
end;
procedure TfrmScriptIDE.AddWarning(const ALineNo: Integer;
const AWarning: string);
var
vDebugInfo: TDebugInfo;
begin
vDebugInfo := TDebugInfo.Create;
vDebugInfo.Line := ALineNo;
lstMessage.AddItem(AWarning, vDebugInfo);
end;
procedure TfrmScriptIDE.btnCompileClick(Sender: TObject);
begin
if Assigned(FOnCompile) then
FOnCompile(Self);
end;
procedure TfrmScriptIDE.FormCreate(Sender: TObject);
begin
FLastChange := False;
// FCompiler := THCCompiler.CreateByScriptType(nil);
FFrmScript := TfrmScript.Create(nil);
FFrmScript.SynEdit.OnKeyDown := DoSynEditKeyDown;
FFrmScript.SynEdit.OnChange := DoSynEditChange;
FFrmScript.BorderStyle := bsNone;
FFrmScript.Align := alClient;
FFrmScript.Parent := Self;
FFrmScript.OnProposal := DoProposal;
FFrmScript.Show;
end;
procedure TfrmScriptIDE.FormDestroy(Sender: TObject);
begin
ClearDebugInfo;
FreeAndNil(FFrmscript);
// FreeAndNil(FCompiler);
end;
function TfrmScriptIDE.GetOnCodeCompletion: TCodeCompletionEvent;
begin
Result := FFrmScript.OnCodeCompletion;
end;
function TfrmScriptIDE.GetScript: string;
begin
Result := FFrmScript.SynEdit.Text;
end;
procedure TfrmScriptIDE.lstMessageDblClick(Sender: TObject);
begin
if lstMessage.Items.Objects[lstMessage.ItemIndex] <> nil then
SetErrorLineNo(TDebugInfo(lstMessage.Items.Objects[lstMessage.ItemIndex]).Line + 1);
end;
procedure TfrmScriptIDE.SetDebugCaption(const AText: string);
begin
lblMsg.Caption := AText;
end;
procedure TfrmScriptIDE.SetErrorLineNo(const ALine: Integer);
begin
FFrmScript.SynEdit.SetErrorLine(ALine);
end;
procedure TfrmScriptIDE.SetOnCodeCompletion(const Value: TCodeCompletionEvent);
begin
FFrmScript.OnCodeCompletion := Value;
end;
procedure TfrmScriptIDE.SetScript(const AScript: string);
begin
FFrmScript.SynEdit.Text := AScript;
end;
end.
|
unit Grijjy.FBSDK.Types;
interface
uses
System.Messaging;
type
TFacebookLoginResult = record
public
Result: Boolean;
Error: Integer;
ErrorDesc: String;
IsCancelled: Boolean;
GrantedPermissions: TArray<String>;
Token: String;
UserId: String;
public
procedure Initialize;
end;
TFacebookLoginResultMessage = class(TMessage<TFacebookLoginResult>)
public
constructor Create(const AFacebookLoginResult: TFacebookLoginResult);
end;
TFacebookGraphResult = record
public
Result: Boolean;
Error: Integer;
ErrorDesc: String;
Json: String;
public
procedure Initialize;
end;
TFacebookGraphResultMessage = class(TMessage<TFacebookGraphResult>)
public
constructor Create(const AFacebookGraphResult: TFacebookGraphResult);
end;
type
TFacebookUser = record
public
Id: String;
Name: String;
EMail: String;
ImageUrl: String;
public
procedure Initialize;
end;
TFacebookUsers = TArray<TFacebookUser>;
implementation
{ TFacebookLoginResult }
procedure TFacebookLoginResult.Initialize;
begin
Result := False;
Error := 0;
IsCancelled := False;
GrantedPermissions := [];
Token := '';
UserId := '';
end;
{ TFacebookLoginResultMessage }
constructor TFacebookLoginResultMessage.Create(
const AFacebookLoginResult: TFacebookLoginResult);
begin
inherited Create(AFacebookLoginResult);
end;
{ TFacebookGraphResult }
procedure TFacebookGraphResult.Initialize;
begin
Result := False;
Error := 0;
ErrorDesc := '';
end;
{ TFacebookGraphResultMessage }
constructor TFacebookGraphResultMessage.Create(const AFacebookGraphResult: TFacebookGraphResult);
begin
inherited Create(AFacebookGraphResult);
end;
{ TFacebookUser }
procedure TFacebookUser.Initialize;
begin
Id := '';
Name := '';
EMail := '';
end;
end.
|
unit UUsuarioVO;
interface
uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO, UPessoasVO;
type
[TEntity]
[TTable('Usuario')]
TUsuarioVO = class(TGenericVO)
private
FidUsuario : Integer;
FLogin : String;
FSenha : String;
FidPessoa : Integer;
Fnome : String;
public
PessoaVO : TPessoasVO;
[TId('idUsuario')]
[TGeneratedValue(sAuto)]
property idUsuario : Integer read FidUsuario write FidUsuario;
[TColumn('login','Login',150,[ldGrid,ldLookup,ldComboBox], False)]
property Login: String read FLogin write FLogin;
[TColumn('senha','Senha',50,[ldLookup,ldComboBox], False)]
property senha: string read FSenha write FSenha;
[TColumn('idPessoa','Pessoa',0,[ldLookup,ldComboBox], False)]
property idPessoa: integer read FidPessoa write FidPessoa;
[TColumn('nome','Pessoa',300,[ldGrid], True, 'Pessoa', 'idPessoa', 'idPessoa')]
property Nome: string read FNome write FNome;
procedure ValidarCamposObrigatorios;
end;
implementation
procedure TUsuarioVO.ValidarCamposObrigatorios;
begin
if (Self.FidPessoa = 0) then
begin
raise Exception.Create('O campo Pessoa é obrigatório!');
end;
if (Self.Login = '') then
begin
raise Exception.Create('O campo Login é obrigatório!');
end;
if (Self.senha = '') then
begin
raise Exception.Create('O campo Senha é obrigatório!');
end;
end;
end.
|
unit UDbSaver;
interface
uses UDbStructure, Ora, SysUtils, Db {$IFDEF VER150},Variants{$ENDIF}, Classes;
type
TSqlItem = class(TCollectionItem)
public
Table: string;
Fields: string;
Key1Null: boolean;
Query: TOraQuery;
constructor Create(Collection: TCollection); override;
end;
TSqlItems = class(TCollection)
private
function GetItem(Index: integer): TSqlItem;
procedure SetItem(Index: integer; Value: TSqlItem);
function Add(
ATable, AFields: string; AKey1Null: boolean; AQuery: TOraQuery): TSqlItem;
function FindItem(ATable, AFields: string; AKey1Null: boolean): TSqlItem;
public
constructor Create;
property Items[Index: integer]: TSqlItem read GetItem write SetItem; default;
end;
TDbSaver=class
public
DBS: TDbStructure;
OS: TOraSession;
Key2Default: integer;
function SaveRecord(p_Table: string; p_Values: array of variant; p_Commit: Boolean = false): integer;
procedure SetState(p_Table: string; p_Id,p_Inst: integer; p_State: string);
procedure StartTransaction;
procedure Commit;
procedure Rollback;
function GetSQLValue(p_Sql:string; p_Field:string=''):variant;
procedure ExecSql(p_Sql: string); overload;
procedure ExecSql(p_Sql: string; p_ParValues:array of variant); overload;
constructor Create(p_ConnectString: string); overload;
constructor Create(p_OS: TOraSession); overload;
constructor Create(p_OS: TOraSession; p_DBS: TDbStructure); overload;
constructor Create(p_DBS: TDbStructure); overload;
destructor Destroy; override;
private
OSCreated, DBSCreated: Boolean;
LastTable, LastFields: string;
q: TOraQuery;
SqlList: TSqlItems;
procedure ExecSQL(p_Q:TOraQuery); overload;
procedure DefineQParams(var p_Q:TOraQuery;p_ParValues:array of variant);
function SetLocalSeparator(AVar: string): string;
end;
implementation
//==============================================================================
constructor TDbSaver.Create(p_ConnectString: string);
begin
OS := TOraSession.Create(nil);
OS.ConnectPrompt:=false;
OS.ConnectString:=p_ConnectString;
try
OS.Connect;
except
on E:Exception do
raise exception.create('TDbSaver: не удалось активизировать сессию'+#13#10+E.Message);
end;
DBS := TDbStructure.Create(OS);
OSCreated := true; DBSCreated := true;
q := TOraQuery.Create(nil);
q.Session := OS;
Self.SqlList := TSqlItems.Create;
end;
//==============================================================================
constructor TDbSaver.Create(p_OS: TOraSession);
begin
OS := p_OS;
DBS := TDbStructure.Create(OS);
OSCreated := false; DBSCreated := true;
q := TOraQuery.Create(nil);
q.Session := OS;
Self.SqlList := TSqlItems.Create;
end;
//==============================================================================
constructor TDbSaver.Create(p_OS: TOraSession; p_DBS: TDbStructure);
begin
OSCreated := false; DBSCreated := false;
q := TOraQuery.Create(nil);
OS := p_OS;
DBS := p_DBS;
q.Session:=OS;
Self.SqlList := TSqlItems.Create;
end;
//==============================================================================
constructor TDbSaver.Create(p_DBS: TDbStructure);
begin
OSCreated := true; DBSCreated := false;
OS := TOraSession.Create(nil);
OS.Username := p_DBS.OraUser;
OS.Password := p_DBS.OraPassword;
OS.Server := p_DBS.OraServer;
OS.Connect;
q := TOraQuery.Create(nil);
q.Session := OS;
DBS := p_DBS;
Self.SqlList := TSqlItems.Create;
end;
//==============================================================================
destructor TDbSaver.Destroy;
begin
q.Close;
q.Free;
if DBSCreated then DBS.Free;
if OSCreated then OS.Free;
SqlList.Free;
end;
//==============================================================================
function TDbSaver.SaveRecord(p_Table: string; p_Values: array of variant; p_Commit: Boolean = false): integer;
var
vFields,Key1,Key2: string;
Key1Exists, Key2Exists, Key1Null: Boolean;
Key1Value,Key2Value: Variant;
i: integer;
vSqlItem: TSqlItem;
//****************************************************************************
procedure PreProcessValues;
var i: integer;
begin
Key1 := DBS.Key1(p_Table);
Key2 := DBS.Key2(p_Table);
if Key1='' then
raise exception.create('не найдено первичного/уникального ключа');
vFields := '';
Key1Exists := false;
Key1Null := false;
Key2Exists := false;
for i:=0 to High(p_Values) div 2 do
begin
vFields:=vFields+VarToStr(p_Values[i*2])+',';
if p_Values[i*2]=Key1 then
begin
Key1Exists:=true;
Key1Value:=p_Values[i*2+1];
Key1Null := (VarToStr(Key1Value) = '0') or VarIsNull(Key1Value);
end;
if p_Values[i*2]=Key2 then
begin
Key2Exists:=true;
Key2Value:=p_Values[i*2+1];
end;
end;
if not Key1Exists and (DBS.ColumnOraType(p_Table,Key1)<>'NUMBER') then
raise exception.create('для таблицы с нечисловым уникальным ключем значение ключа должно быть указано явно');
if not Key2Exists and (Key2<>'') and (Key2Default=0) then
raise exception.create('значение второго ключевого поля не указано и не установлено по умолчанию');
end;
//****************************************************************************
procedure CreateSql;
var
i: integer;
s,vValues: string;
begin
q.Sql.Text:='begin'+#13#10;
if Key1Exists and (not Key1Null) then
begin
q.Sql.Add('update '+DBS.OraUser+'.'+p_Table+' set');
for i:=0 to High(p_Values) div 2 do
if (p_Values[i*2]<>Key1) and (p_Values[i*2]<>Key2) then
q.Sql.Add(Format('%s=:%s,',[p_Values[i*2],p_Values[i*2]]));
q.Sql.Text:=copy(q.Sql.Text,1,length(q.Sql.Text)-3);
q.Sql.Add('where '+Key1+'=:'+Key1);
if Key2<>'' then
q.Sql.Add('and '+Key2+'=:'+Key2);
q.Sql.Add(';');
q.Sql.Add('if sql%notfound then');
end;
vValues:='';
q.Sql.Add('insert into '+DBS.OraUser+'.'+p_Table+'(');
if (not Key1Exists) or Key1Null then
begin
q.Sql.Add(Key1 +',');
vValues := vValues + DBS.OraUser +'.'+ DBS.SeqByTable(p_Table) +'.nextval,';
end;
if not Key2Exists and (Key2<>'') then begin
q.Sql.Add(Key2+',');
vValues:=vValues+':'+Key2+',';
end;
for i := 0 to High(p_Values) div 2 do
if not ((p_Values[i*2] = Key1) and Key1Null) then
begin
s:=p_Values[i*2];
if i<>High(p_Values) div 2 then s:=s+',';
q.Sql.Add(s);
vValues:=vValues+':'+s;
end;
q.Sql.Add(') values ('+vValues+');');
if Key1Exists and (not Key1Null) then
q.Sql.Add('end if;');
q.SQL.Add('end;');
q.Prepare;
for i:=0 to q.Params.Count-1 do
begin
q.Params[i].ParamType := ptInput;
q.Params[i].DataType := DBS.ColumnParamType(p_Table,q.Params[i].Name);
end;
end;
//****************************************************************************
function GetSeqValue: integer;
var
qSeq: TOraQuery;
vSeqName: string;
begin
vSeqName := DBS.SeqByTable(p_Table);
if vSeqName = '' then
raise exception.create('значение первого поля ключа не указано, при этом сиквенс не найден');
qSeq := TOraQuery.Create(nil);
try
qSeq.Session := OS;
qSeq.Sql.Text := ' select '+DBS.OraUser+'.'+vSeqName+'.nextval from dual';
qSeq.Open;
result := qSeq.Fields[0].AsInteger;
qSeq.Close;
finally
qSeq.Free;
end;
end;
//****************************************************************************
procedure Save;
var
i: integer;
begin
if q.Active then q.Close;
if not Key2Exists and (Key2<>'') then
q.ParamByName(Key2).AsInteger:=Key2Default;
for i := 0 to High(p_Values) div 2 do
if not ((p_Values[i*2] = Key1) and Key1Null) then
begin
if (DBS.ColumnOraType(p_Table,p_Values[i*2]) = 'NUMBER') and (p_Values[i*2+1] <> null) then
q.ParamByName(p_Values[i*2]).Value := SetLocalSeparator(p_Values[i*2+1])
else
q.ParamByName(p_Values[i*2]).Value := p_Values[i*2+1];
end;
//q.SQL.SaveToFile('d:\1.sql');
q.ExecSql;
end;
//****************************************************************************
begin
try
if High(p_Values) mod 2 = 0 then
raise exception.Create('параметр p_Values должен содержать четное число значений');
if not DBS.TableExists(p_Table) then
raise exception.create('таблица не найдена');
for i:=0 to High(p_Values) div 2 do
p_Values[i*2]:=ANSIUpperCase(VarToStr(p_Values[i*2]));
PreProcessValues;
// Если последнияя таблица и поля совпадают, то не пересоздавать запрос
if (p_Table<>LastTable) or (vFields<>LastFields) then
begin
vSqlItem := SqlList.FindItem(p_Table, vFields, Key1Null);
if vSqlItem = nil then
begin
CreateSql;
SqlList.Add(p_Table, vFields, Key1Null, q);
end
else
q.Assign(vSqlItem.Query);
end;
//if p_Commit then OS.StartTransaction;
Save;
if DBS.ColumnOraType(p_Table, Key1)='NUMBER' then
begin
if (not Key1Exists) or Key1Null then
result := GetSQLValue('select '+ DBS.OraUser +'.'+ DBS.SeqByTable(p_Table) +'.currval from dual')
else
result := q.ParamByName(Key1).AsInteger;
end
else
result := -1;
if p_Commit then
OS.Commit;
except
on E:Exception do
raise exception.create(
'TDbSaver.SaveRecord('+p_Table+',...): '+#13#10+E.Message);
end;
end;
//==============================================================================
procedure TDbSaver.SetState(p_Table: string; p_Id,p_Inst: integer; p_State: string);
var
q: TOraQuery;
vKey2: string;
begin
if not DBS.ColumnExists(p_Table,'STATE') then
raise exception.create('TDbSaver.SetState: таблица '+p_Table+' не имеет поля STATE');
q:=TOraQuery.Create(nil);
q.Session:=OS;
try
q.Sql.Text:=
' update '+DBS.OraUser+'.'+p_Table+' set state='''+p_State+''' where '+DBS.Key1(p_Table)+'='+IntToStr(p_Id);
vKey2:=DBS.Key2(p_Table);
if vKey2<>'' then
q.Sql.Add(' and '+vKey2+'='+IntToStr(p_Inst));
try
q.ExecSql;
except
on E:Exception do
raise exception.create('TDbSaver.SetState: '+E.Message);
end;
q.Close;
finally
q.Free;
end;
end;
//==============================================================================
function TDbSaver.GetSQLValue(p_Sql:string; p_Field:string=''):variant;
var q: TOraQuery;
begin
q:=TOraQuery.Create(nil);
q.Session := OS;
try
q.Sql.Text:=p_Sql;
//q.Prepare;
if q.Macros.FindMacro('user')<>nil then
q.Macros.MacroByName('user').Value:=DBS.OraUser;
q.Open;
if q.IsEmpty then result:=null
else if q.RecordCount>1 then raise exception.Create('TDbSaver.GetSqlValue: получено более одной записи')
else
if p_Field='' then result:=q.Fields[0].Value
else result:=q.FieldByName(p_Field).Value;
q.Close;
finally
q.Free;
end;
end;
//==============================================================================
procedure TDbSaver.ExecSql(p_Sql: string);
var q:TOraQuery;
begin
q:=TOraQuery.Create(nil);
q.Session:=OS;
q.SQL.Text:=p_SQL;
if q.Macros.FindMacro('user')<>nil then
q.Macros.MacroByName('user').Value:=DBS.OraUser;
try
ExecSQL(q);
q.Close;
finally
q.Free;
end;
end;
//==============================================================================
procedure TDbSaver.ExecSql(p_Sql: string; p_ParValues:array of variant);
var q:TOraQuery;
begin
q:=TOraQuery.Create(nil);
q.Session:=OS;
q.SQL.Text:=p_SQL;
DefineQParams(q,p_ParValues);
if q.Macros.FindMacro('user')<>nil then
q.Macros.MacroByName('user').Value:=DBS.OraUser;
try
ExecSQL(q);
q.Close;
finally
q.Free;
end;
end;
//==============================================================================
procedure TDbSaver.ExecSql(p_Q: TOraQuery);
var InsideTransaction:Boolean;
begin
InsideTransaction:=os.InTransaction;
if not InsideTransaction then os.StartTransaction;
p_Q.ExecSql;
if not InsideTransaction then os.Commit;
end;
//==============================================================================
procedure TDbSaver.DefineQParams(var p_Q:TOraQuery;p_ParValues:array of variant);
var i:integer;
begin
if high(p_ParValues) mod 2 = 0 then
Raise Exception.Create('TDbSaver.DefineQParams: нечетное число элементов в p_ParValues');
for i:=0 to (high(p_ParValues) div 2) do
p_Q.ParamByName(p_ParValues[i*2]).Value:=p_ParValues[i*2+1];
end;
//==============================================================================
procedure TDbSaver.StartTransaction;
begin
if not os.InTransaction then
os.StartTransaction;
end;
//==============================================================================
procedure TDbSaver.Commit;
begin
if os.InTransaction then
os.Commit;
end;
//==============================================================================
procedure TDbSaver.Rollback;
begin
if os.InTransaction then
os.Rollback;
end;
//==============================================================================
constructor TSqlItem.Create(Collection: TCollection);
begin
inherited;
Query := TOraQuery.Create(nil);
end;
{TSqlItems}
constructor TSqlItems.Create;
begin
inherited Create(TSqlItem);
end;
function TSqlItems.GetItem(Index: Integer): TSqlItem;
begin
Result := TSqlItem(inherited Items[Index]);
end;
procedure TSqlItems.SetItem(Index: Integer; Value: TSqlItem);
begin
inherited SetItem(Index, TSqlItem(Value));
end;
function TSqlItems.Add(
ATable, AFields: string; AKey1Null: boolean; AQuery: TOraQuery): TSqlItem;
begin
Result := FindItem(ATable, AFields, AKey1Null);
if Result = nil then
begin
Result := TSqlItem(inherited Add);
Result.Table := ATable;
Result.Fields := AFields;
Result.Key1Null := AKey1Null;
Result.Query.Assign(AQuery);
end;
end;
function TSqlItems.FindItem(ATable, AFields: string; AKey1Null: boolean): TSqlItem;
var
i: integer;
begin
Result := nil;
for i := 0 to Count - 1 do
begin
if (Self.Items[i].Table = ATable) and (Self.Items[i].Fields = AFields)
and (Self.Items[i].Key1Null = AKey1Null) then
begin
Result := Self.Items[i];
Break;
end;
end;
end;
function TDbSaver.SetLocalSeparator(AVar: string): string;
var
s: string;
begin
s := AVar;
case DecimalSeparator of
'.': if pos(',', s) > 0 then s[pos(',', s)] := DecimalSeparator;
',': if pos('.', s) > 0 then s[pos('.', s)] := DecimalSeparator;
end;
Result := s;
end;
end.
|
unit gr_PrintAnalitControl_DM;
interface
uses
SysUtils, Classes, ibase, gr_uCommonLoader, Forms, DB, FIBDataSet, pFIBDataSet,
FIBDatabase, pFIBDatabase, frxClass, frxDBSet, frxDesgn,
gr_uCommonConsts, gr_uCommonProc, gr_uMessage, Dialogs, gr_uWaitForm,
Variants, Dates, frxExportXLS;
type
TDM = class(TDataModule)
DBDataset: TfrxDBDataset;
frxXLSExport1: TfrxXLSExport;
DB: TpFIBDatabase;
DataSet: TpFIBDataSet;
Transaction: TpFIBTransaction;
frxDesigner1: TfrxDesigner;
DataSet1: TpFIBDataSet;
DBDataset1: TfrxDBDataset;
DataSetS: TpFIBDataSet;
DBDataSetS: TfrxDBDataset;
Report: TfrxReport;
procedure DataModuleDestroy(Sender: TObject);
procedure ReportGetValue(const VarName: String; var Value: Variant);
private
PKodSetup: integer;
public
procedure ReportCreate(AParameter:TgrAccListParam;KodSetup:integer);
end;
var
DM: TDM;
implementation
{$R *.dfm}
const FullNameReport = '\grPrintAnalitControl.fr3';
procedure TDM.ReportCreate(AParameter:TgrAccListParam;KodSetup:integer);
var wf:TForm;
GroupHeader3: TfrxGroupHeader;
GroupHeader1: TfrxGroupHeader;
begin
try
PKodSetup:=KodSetup; //+IntToStr(KodSetup)+
DB.Handle:=AParameter.DB_handle;
DataSet.SQLs.SelectSQL.Text:='SELECT * FROM GR_ANALIT_CONTROL('+IntToStr(KodSetup)+') ORDER BY DEP_NAME, KURS, DEP_CHILD_NAME, FIO';
DataSet1.SQLs.SelectSQL.Text:='SELECT SHORT_NAME FROM Z_SETUP';
DataSetS.SQLs.SelectSQL.Text:='SELECT * From GR_ANALIT_CONTROL_FAC('+IntToStr(KodSetup)+')';
DataSet.Open;
DataSet1.Open;
DataSetS.Open;
Report.Clear;
Report.LoadFromFile(ExtractFilePath(Application.ExeName)+PathReports+FullNameReport,True);
GroupHeader1:=Report.FindObject('GroupHeader1') as TfrxGroupHeader;
GroupHeader3:=Report.FindObject('GroupHeader3') as TfrxGroupHeader;
if AParameter.AnalitControl=False then
begin
GroupHeader3.StartNewPage:=False;
end
else
begin
GroupHeader1.StartNewPage:=False;
GroupHeader3.StartNewPage:=True;
end;
if grDesignReport then Report.DesignReport
else Report.ShowReport;
// Report.DesignReport;
Report.Free;
except
on E:Exception do
begin
grShowMessage(ECaption[Indexlanguage],e.Message,mtError,[mbOK]);
end;
end;
end;
procedure TDM.DataModuleDestroy(Sender: TObject);
begin
if Transaction.InTransaction then Transaction.Commit;
end;
procedure TDM.ReportGetValue(const VarName: String; var Value: Variant);
begin
if UpperCase(VarName)='DATEP' then
begin
Value:=KodSetupToPeriod(PKodSetup,2);
end;
end;
end.
|
unit ProdutoOperacaoAlterar.Controller;
interface
uses Produto.Controller.interf, Produto.Model.interf,
TESTPRODUTO.Entidade.Model, System.SysUtils;
type
TProdutosOperacoesAlterarController = class(TInterfacedObject,
IProdutoOperacaoAlterarController)
private
FProdutoModel: IProdutoModel;
FRegistro: TTESTPRODUTO;
FCodigoSinapi: string;
FDescricao: string;
FUnidMedida: string;
FOrigemPreco: string;
FPrMedio: Currency;
FPrMedioSinap: Currency;
public
constructor Create;
destructor Destroy; override;
class function New: IProdutoOperacaoAlterarController;
function produtoModel(AValue: IProdutoModel): IProdutoOperacaoAlterarController;
function produtoSelecionado(AValue: TTESTPRODUTO): IProdutoOperacaoAlterarController;
function codigoSinapi(AValue: string): IProdutoOperacaoAlterarController;
function descricao(AValue: string): IProdutoOperacaoAlterarController;
function unidMedida(AValue: string): IProdutoOperacaoAlterarController;
function origemPreco(AValue: string): IProdutoOperacaoAlterarController;
function prMedio(AValue: Currency): IProdutoOperacaoAlterarController; overload;
function prMedio(AValue: string): IProdutoOperacaoAlterarController; overload;
function prMedioSinapi(AValue: Currency): IProdutoOperacaoAlterarController; overload;
function prMedioSinapi(AValue: string): IProdutoOperacaoAlterarController; overload;
procedure finalizar;
end;
implementation
{ TProdutosOperacoesAlterarController }
function TProdutosOperacoesAlterarController.codigoSinapi(AValue: string)
: IProdutoOperacaoAlterarController;
begin
Result := Self;
FCodigoSinapi := AValue;
end;
procedure TProdutosOperacoesAlterarController.finalizar;
begin
FProdutoModel.DAO.Modify(FRegistro);
FRegistro.CODIGO_SINAPI := FCodigoSinapi;
FRegistro.DESCRICAO := FDescricao;
FRegistro.UNIDMEDIDA := FUnidMedida;
FRegistro.ORIGEM_PRECO := FOrigemPreco;
FRegistro.PRMEDIO := FPrMedio;
FRegistro.PRMEDIO_SINAPI := FPrMedioSinap;
FProdutoModel.DAO.Update(FRegistro);
end;
constructor TProdutosOperacoesAlterarController.Create;
begin
end;
function TProdutosOperacoesAlterarController.descricao(AValue: string)
: IProdutoOperacaoAlterarController;
begin
Result := Self;
FDescricao := AValue;
end;
destructor TProdutosOperacoesAlterarController.Destroy;
begin
inherited;
end;
class function TProdutosOperacoesAlterarController.New
: IProdutoOperacaoAlterarController;
begin
Result := Self.Create;
end;
function TProdutosOperacoesAlterarController.origemPreco(
AValue: string): IProdutoOperacaoAlterarController;
begin
Result := Self;
FOrigemPreco := AValue;
end;
function TProdutosOperacoesAlterarController.prMedio(
AValue: string): IProdutoOperacaoAlterarController;
begin
Result := Self;
if AValue = EmptyStr then
AValue := '0';
FPrMedio := StrToCurr(AValue);
end;
function TProdutosOperacoesAlterarController.prMedio(
AValue: Currency): IProdutoOperacaoAlterarController;
begin
Result := Self;
FPrMedio := AValue;
end;
function TProdutosOperacoesAlterarController.prMedioSinapi(AValue: string)
: IProdutoOperacaoAlterarController;
begin
Result := Self;
if AValue = EmptyStr then
AValue := '0';
FPrMedioSinap := StrToCurr(AValue);
end;
function TProdutosOperacoesAlterarController.prMedioSinapi(AValue: Currency)
: IProdutoOperacaoAlterarController;
begin
Result := Self;
FPrMedioSinap := AValue;
end;
function TProdutosOperacoesAlterarController.produtoModel(AValue: IProdutoModel)
: IProdutoOperacaoAlterarController;
begin
Result := Self;
FProdutoModel := AValue;
end;
function TProdutosOperacoesAlterarController.produtoSelecionado(
AValue: TTESTPRODUTO): IProdutoOperacaoAlterarController;
begin
Result := Self;
FRegistro := AValue;
end;
function TProdutosOperacoesAlterarController.unidMedida(AValue: string)
: IProdutoOperacaoAlterarController;
begin
Result := Self;
FUnidMedida := AValue;
end;
end.
|
unit System_Fdc;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, ExtCtrls, Graphics;
type
{ TSystemFdc }
TSystemFdc = class
private // Attribute
const
// Konstanten fuer die 'fdcStatus' Bit-Adressen
BUSY = 0; // When set, command is under execution.
// When reset, no command is under execution.
DRI = 1; // This bit is a copy of the DRQ output. When set, it indicates the DR is full
// on a Read Operation or the DR is empty on a Write operation. This bit is
// reset to zero when updated. On Type 1 commands, this bit indicates the
// status of the IP signal.
LDB = 2; // When set, it indicates the computer did not respond to DRQ in one byte time.
// This bit is reset to zero when updated. On Type 1 commands, this bit
// reflects the status of the TR00 signal.
CRCERROR = 3; // If bit 4 (RNF) is set, an error is found in one or more ID fields,
// otherwise it indicates error data field. This bit is reset when updated.
RNF = 4; // Record not found. When set, it indicates that the desired track, sector or side
// were not found. This bit is reset when updated.
RTSU = 5; // When set, this bit indicates that the Motor Spin-Up sequence has completed
// on Type 1 commands. On Type 2 & 3 commands, this bit indicates record Type:
// 0 = Data Mark , 1 = Deleted Data Mark.
WP = 6; // On Read: not used. On any Write: it indicates a Write Protect. This bit is reset when updated.
MON = 7; // This bit reflects the status of the Motor On output.
// Konstanten fuer die 'extStatus' Bit-Adressen
INTQ = 0; // INTRQ-Signal des FDC, ist es gesetzt wurde das zuletzt an den
// FDC gesendete Kommando abgearbeitet.
DRQ = 1; // DRQ-Signal des FDC, ist es gesetzt enthält das Datenregister
// einen neuen zu lesenden Wert, oder es kann ein neuer Wert
// geschrieben werden.
WPS = 2; // Write-Protect Signal vom FDD-Bus, ist dieses Bit gesetzt,
// ist die im selektierten Laufwerk eingelegte Diskette schreibgeschützt.
DC = 3; // Disk-Change Signal vom FDD-Bus, ist dieses Bit gesetzt, wurde
// vom selektierten Laufwerk ein Diskettenwechsel erkannt.
// Konstanten fuer die 'extControl' Bit-Adressen
MRES = 0; // MRESET-Pin des FDC, ist das Bit gesetzt wird der FDC
// zurückgesetzt. Dieses Bit muss für den Betrieb gelöscht sein.
DDEN = 1; // DDEN-PIN des FDC, wenn dieses Bit gesetzt ist wird der
// Double-Density Modus des FDC eingeschaltet. Bei gelöschtem
// Bit arbeitet der FDC in Single-Density Modus.
D0S = 2; // Wenn dieses Bit gesetzt ist, wird Drive-0 selektiert.
D1S = 3; // Wenn dieses Bit gesetzt ist, wird Drive-1 selektiert.
SS = 4; // Side selekt der Laufwerke. Gesetzt Seite 1, gelöscht Seite 0
type
TByteArray = array of byte;
TBitReg8 = bitpacked record
case byte of
0: (Value: byte); // 8Bit Register Value
1: (bit: bitpacked array[0..7] of boolean); // Bit Data
end;
TDataMode = (SECTOR_READ, SECTOR_WRITE, ADDRESS_READ, NONE);
TFloppyDriveData = record
Sides: byte;
Tracks: byte;
Sectors: byte;
SectorBytes: integer;
Size: dword;
Changed: boolean;
MotorOn: boolean;
Loaded: boolean;
FddStatus: TPanel;
ImageData: file;
end;
ptrFloppyDriveData = ^TFloppyDriveData;
var
dataBuffer: TByteArray;
dataCount: dword;
dataMode: TDataMode;
timerFddStatus: TTimer;
fdcStatus: TBitReg8;
fdcTrack, tmpTrack: byte;
fdcSector: byte;
fdcData: byte;
fdcSide: byte;
extStatus: TBitReg8;
extControl: TBitReg8;
stepForward: boolean;
isMultiSectorCommand: boolean;
canClearIntrq: boolean;
resetFloppyDrive, floppyDrive0, floppyDrive1: TFloppyDriveData;
actualFloppyDrive: ptrFloppyDriveData;
filePos: DWord;
resetState: boolean;
protected // Attribute
public // Attribute
public // Konstruktor/Destruktor
constructor Create(var panel0: TPanel; var panel1: TPanel);
destructor Destroy; override;
private // Methoden
procedure doReset;
procedure calcFilePosition;
procedure setFddOffState(Sender: TObject);
procedure setFddReadState;
procedure setFddWriteState;
procedure clearBusyUpdateTrack;
procedure clearBusySetRecordNotFoundSetIntrq;
procedure prepareReadSectors;
procedure finishReadSectors;
procedure prepareWriteSectors;
procedure finishWriteSectors;
procedure prepareAddressRead;
procedure finishAddressRead;
protected // Methoden
public // Methoden
procedure setCommand(command: byte);
procedure setData(Data: byte);
procedure setTrack(track: byte);
procedure setSector(sector: byte);
procedure setExtControl(control: byte);
procedure setFdd0Sides(sides: integer);
procedure setFdd0Tracks(tracks: integer);
procedure setFdd0Sectors(sectors: integer);
procedure setFdd0SectorBytes(sectorbytes: integer);
procedure setFdd0Image(FileName: string);
procedure setFdd1Sides(sides: integer);
procedure setFdd1Tracks(tracks: integer);
procedure setFdd1Sectors(sectors: integer);
procedure setFdd1SectorBytes(sectorbytes: integer);
procedure setFdd1Image(FileName: string);
function getData: byte;
function getStatus: byte;
function getTrack: byte;
function getSector: byte;
function getExtStatus: byte;
end;
var
SystemFdc: TSystemFdc;
implementation
{ TSystemFdc }
uses System_Settings;
// --------------------------------------------------------------------------------
constructor TSystemFdc.Create(var panel0: TPanel; var panel1: TPanel);
var
ImageFile: string;
begin
inherited Create;
timerFddStatus := TTimer.Create(nil);
timerFddStatus.Enabled := False;
timerFddStatus.Interval := 30;
timerFddStatus.OnTimer := @setFddOffState;
resetFloppyDrive.Size := 0;
resetFloppyDrive.Changed := False;
resetFloppyDrive.MotorOn := False;
resetFloppyDrive.Loaded := False;
floppyDrive0 := resetFloppyDrive;
floppyDrive1 := resetFloppyDrive;
actualFloppyDrive := @resetFloppyDrive;
resetState := False;
floppyDrive0.FddStatus := panel0;
floppyDrive1.FddStatus := panel1;
setFdd0Sides(SystemSettings.ReadInteger('Fdd0', 'Sides', 2));
setFdd0Tracks(SystemSettings.ReadInteger('Fdd0', 'Tracks', 80));
setFdd0Sectors(SystemSettings.ReadInteger('Fdd0', 'Sectors', 9));
setFdd0SectorBytes(SystemSettings.ReadInteger('Fdd0', 'SectorBytes', 512));
ImageFile := SystemSettings.ReadString('Fdd0', 'ImageFile', '');
if ((ImageFile <> '') and (not FileExists(ImageFile))) then begin
SystemSettings.WriteString('Fdd0', 'ImageFile', '');
ImageFile := '';
end;
setFdd0Image(ImageFile);
setFdd1Sides(SystemSettings.ReadInteger('Fdd1', 'Sides', 2));
setFdd1Tracks(SystemSettings.ReadInteger('Fdd1', 'Tracks', 80));
setFdd1Sectors(SystemSettings.ReadInteger('Fdd1', 'Sectors', 9));
setFdd1SectorBytes(SystemSettings.ReadInteger('Fdd1', 'SectorBytes', 512));
ImageFile := SystemSettings.ReadString('Fdd1', 'ImageFile', '');
if ((ImageFile <> '') and (not FileExists(ImageFile))) then begin
SystemSettings.WriteString('Fdd1', 'ImageFile', '');
ImageFile := '';
end;
setFdd1Image(ImageFile);
end;
// --------------------------------------------------------------------------------
destructor TSystemFdc.Destroy;
begin
if Assigned(timerFddStatus) then begin
timerFddStatus.Enabled := False;
timerFddStatus.OnTimer := nil;
timerFddStatus.Destroy;
end;
inherited Destroy;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.doReset;
begin
fdcStatus.Value := $20;
tmpTrack := 0;
fdcTrack := tmpTrack;
fdcSector := 1;
fdcData := 0;
extStatus.Value := $00;
stepForward := True;
isMultiSectorCommand := False;
canClearIntrq := True;
dataMode := NONE;
resetState := True;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.calcFilePosition;
begin
filePos := ((((fdcTrack * actualFloppyDrive^.Sides) + fdcSide) * actualFloppyDrive^.Sectors) + (fdcSector - 1));
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.setFddOffState(Sender: TObject);
begin
timerFddStatus.Enabled := False;
with actualFloppyDrive^.FddStatus do begin
Canvas.Brush.Style := bsSolid;
Canvas.Brush.Color := clDefault;
Canvas.Pen.Style := psClear;
Canvas.Pen.Color := clDefault;
Canvas.Pen.Width := 2;
Canvas.Ellipse(20, 0, 31, 10);
end;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.setFddReadState;
begin
timerFddStatus.Enabled := False;
with actualFloppyDrive^.FddStatus do begin
Canvas.Brush.Style := bsSolid;
Canvas.Brush.Color := clLime;
Canvas.Pen.Style := psSolid;
Canvas.Pen.Color := clGreen;
Canvas.Pen.Width := 1;
Canvas.Ellipse(21, 1, 29, 9);
end;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.setFddWriteState;
begin
timerFddStatus.Enabled := False;
with actualFloppyDrive^.FddStatus do begin
Canvas.Brush.Style := bsSolid;
Canvas.Brush.Color := clRed;
Canvas.Pen.Style := psSolid;
Canvas.Pen.Color := clMaroon;
Canvas.Pen.Width := 1;
Canvas.Ellipse(21, 1, 29, 9);
end;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.clearBusyUpdateTrack;
begin
if (resetState or (not actualFloppyDrive^.Loaded)) then begin
exit;
end;
fdcTrack := tmpTrack;
fdcStatus.bit[BUSY] := False;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.clearBusySetRecordNotFoundSetIntrq;
begin
if (resetState or (not actualFloppyDrive^.Loaded)) then begin
exit;
end;
extStatus.bit[INTQ] := True;
fdcStatus.bit[RNF] := True;
fdcStatus.bit[BUSY] := False;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.prepareReadSectors;
begin
calcFilePosition;
if ((fdcSector > actualFloppyDrive^.Sectors) or ((filePos > (actualFloppyDrive^.Size - actualFloppyDrive^.SectorBytes)) or
(actualFloppyDrive^.Size = 0) or (fdcTrack >= actualFloppyDrive^.Tracks))) then begin
// Sector nicht vorhanden oder Sector und/oder Track ausserhalb der Disk
clearBusySetRecordNotFoundSetIntrq;
exit;
end
else begin
try
Reset(actualFloppyDrive^.ImageData, actualFloppyDrive^.SectorBytes);
Seek(actualFloppyDrive^.ImageData, filePos);
BlockRead(actualFloppyDrive^.ImageData, dataBuffer[0], 1);
CloseFile(actualFloppyDrive^.ImageData);
fdcStatus.bit[DRQ] := True;
extStatus.bit[DRQ] := True;
dataCount := 0;
dataMode := SECTOR_READ;
setFddReadState;
timerFddStatus.Enabled := True;
except
extStatus.bit[INTQ] := True;
fdcStatus.bit[BUSY] := False;
fdcStatus.bit[CRCERROR] := True;
end;
end;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.finishReadSectors;
begin
fdcStatus.bit[DRQ] := False;
extStatus.bit[DRQ] := False;
actualFloppyDrive^.MotorOn := False;
if ((isMultiSectorCommand) and (fdcSector < actualFloppyDrive^.Sectors)) then begin
Inc(fdcSector);
prepareReadSectors;
end
else begin
extStatus.bit[INTQ] := True;
fdcStatus.bit[BUSY] := False;
dataMode := NONE;
isMultiSectorCommand := False;
end;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.prepareWriteSectors;
begin
calcFilePosition;
if ((fdcSector > actualFloppyDrive^.Sectors) or ((filePos > (actualFloppyDrive^.Size - actualFloppyDrive^.SectorBytes)) or
(actualFloppyDrive^.Size = 0) or (fdcTrack >= actualFloppyDrive^.Tracks))) then begin
// Sector nicht vorhanden oder Sector und/oder Track ausserhalb der Disk
clearBusySetRecordNotFoundSetIntrq;
exit;
end
else begin
dataCount := 0;
fdcStatus.bit[DRQ] := True;
extStatus.bit[DRQ] := True;
dataMode := SECTOR_WRITE;
setFddWriteState;
timerFddStatus.Enabled := True;
end;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.finishWriteSectors;
begin
fdcStatus.bit[DRQ] := False;
extStatus.bit[DRQ] := False;
actualFloppyDrive^.MotorOn := False;
try
Reset(actualFloppyDrive^.ImageData, actualFloppyDrive^.SectorBytes);
Seek(actualFloppyDrive^.ImageData, filePos);
BlockWrite(actualFloppyDrive^.ImageData, dataBuffer[0], 1);
CloseFile(actualFloppyDrive^.ImageData);
if ((isMultiSectorCommand) and (fdcSector < actualFloppyDrive^.Sectors)) then begin
Inc(fdcSector);
prepareWriteSectors;
end
else begin
extStatus.bit[INTQ] := True;
fdcStatus.bit[BUSY] := False;
dataMode := NONE;
isMultiSectorCommand := False;
end;
except
extStatus.bit[INTQ] := True;
fdcStatus.bit[BUSY] := False;
fdcStatus.bit[CRCERROR] := True;
end;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.prepareAddressRead;
begin
dataCount := 0;
dataBuffer[0] := actualFloppyDrive^.Tracks;
dataBuffer[1] := actualFloppyDrive^.Sides;
dataBuffer[2] := actualFloppyDrive^.Sectors;
case (actualFloppyDrive^.SectorBytes) of
128: dataBuffer[3] := 0;
256: dataBuffer[3] := 1;
512: dataBuffer[3] := 2;
1024: dataBuffer[3] := 3;
else dataBuffer[3] := $ff;
end;
if (actualFloppyDrive^.Loaded) then begin
dataBuffer[4] := $ff;
end
else begin
dataBuffer[4] := 00;
end;
dataBuffer[5] := $ff;
fdcStatus.bit[DRQ] := True;
extStatus.bit[DRQ] := True;
dataMode := ADDRESS_READ;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.finishAddressRead;
begin
fdcStatus.bit[DRQ] := False;
extStatus.bit[DRQ] := False;
extStatus.bit[INTQ] := True;
fdcStatus.bit[BUSY] := False;
dataMode := NONE;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.setCommand(command: byte);
var
cmd: TbitReg8;
begin
cmd.Value := command;
fdcStatus.bit[BUSY] := True;
resetState := False;
case (cmd.Value and %11100000) of
%00000000: begin // Restore / Seek
fdcStatus.bit[CRCERROR] := False;
fdcStatus.bit[RNF] := False;
fdcStatus.bit[DRQ] := False;
fdcStatus.bit[RTSU] := True;
extStatus.bit[DRQ] := False;
fdcStatus.bit[LDB] := False;
if (canClearIntrq) then begin
extStatus.bit[INTQ] := False;
end;
if (not cmd.bit[4]) then begin // Restore auf Track 0
if (fdcTrack > 0) then begin // wenn aktueller Track groesser 0
stepForward := False; // Step-Direction auf backward setzen
actualFloppyDrive^.Changed := False;
end;
tmpTrack := 0;
fdcStatus.bit[LDB] := True;
end
else begin // Seek auf angeforderten Track
if (fdcTrack > fdcData) then begin // wenn aktueller Track groesser angeforderter Track
stepForward := False; // Step-Direction auf backward setzen
end
else begin
stepForward := True; // ansonsten Step-Direction forward
end;
if (fdcTrack <> fdcData) then begin
actualFloppyDrive^.Changed := False;
end;
if (fdcData > (actualFloppyDrive^.Tracks - 1)) then begin // falls der angeforderte Track nicht erreichbar ist
fdcStatus.bit[RNF] := True; // 'Seek Error / Record not Found' Flag setzen
end;
tmpTrack := fdcData;
end;
actualFloppyDrive^.MotorOn := True;
clearBusyUpdateTrack;
end; // Restore / Seek
%00100000: begin // Step
fdcStatus.bit[CRCERROR] := False;
fdcStatus.bit[RNF] := False;
fdcStatus.bit[DRQ] := False;
fdcStatus.bit[RTSU] := True;
extStatus.bit[DRQ] := False;
if (canClearIntrq) then begin
extStatus.bit[INTQ] := False;
end;
tmpTrack := fdcTrack;
if (stepForward) then begin
Inc(tmpTrack);
actualFloppyDrive^.Changed := False;
if (tmpTrack > (actualFloppyDrive^.Tracks - 1)) then begin // falls der angeforderte Track nicht erreichbar ist
fdcStatus.bit[RNF] := True; // 'Seek Error / Record not Found' Flag setzen
end;
end
else begin
if (tmpTrack > 0) then begin
Dec(tmpTrack);
actualFloppyDrive^.Changed := False;
end;
end;
if (not cmd.bit[4]) then begin // Track-Register Update
tmpTrack := fdcTrack;
end;
actualFloppyDrive^.MotorOn := True;
clearBusyUpdateTrack;
end; // Step
%01000000: begin // Step-in
fdcStatus.bit[CRCERROR] := False;
fdcStatus.bit[RNF] := False;
fdcStatus.bit[DRQ] := False;
fdcStatus.bit[RTSU] := True;
extStatus.bit[DRQ] := False;
if (canClearIntrq) then begin
extStatus.bit[INTQ] := False;
end;
tmpTrack := fdcTrack;
stepForward := True;
Inc(tmpTrack);
actualFloppyDrive^.Changed := False;
if (tmpTrack > (actualFloppyDrive^.Tracks - 1)) then begin // falls der angeforderte Track nicht erreichbar ist
fdcStatus.bit[RNF] := True; // 'Seek Error / Record not Found' Flag setzen
end;
if (not cmd.bit[4]) then begin
tmpTrack := fdcTrack;
end;
actualFloppyDrive^.MotorOn := True;
clearBusyUpdateTrack;
end; // Step-in
%01100000: begin // Step-out
fdcStatus.bit[CRCERROR] := False;
fdcStatus.bit[RNF] := False;
fdcStatus.bit[DRQ] := False;
fdcStatus.bit[RTSU] := True;
extStatus.bit[DRQ] := False;
if (canClearIntrq) then begin
extStatus.bit[INTQ] := False;
end;
tmpTrack := fdcTrack;
stepForward := False;
if (tmpTrack > 0) then begin
Dec(tmpTrack);
actualFloppyDrive^.Changed := False;
end;
if (not cmd.bit[4]) then begin
tmpTrack := fdcTrack;
end;
actualFloppyDrive^.MotorOn := True;
clearBusyUpdateTrack;
end; // Step-out
%10000000: begin // Read Sector
fdcStatus.bit[DRQ] := False;
fdcStatus.bit[LDB] := False;
fdcStatus.bit[RNF] := False;
fdcStatus.bit[RTSU] := False;
fdcStatus.bit[WP] := False;
extStatus.bit[DRQ] := False;
isMultiSectorCommand := False;
if ((not cmd.bit[0]) and (not cmd.bit[1])) then begin // Bit 0 und 1 muessen gelöscht sein
if (canClearIntrq) then begin
extStatus.bit[INTQ] := False;
end;
actualFloppyDrive^.MotorOn := True;
fdcStatus.bit[RTSU] := True;
if (cmd.bit[4]) then begin // Bit 4 gesetzt, dann Multi-Sector Read
isMultiSectorCommand := True;
end;
prepareReadSectors;
end;
end; // Read Sector
%10100000: begin // Write Sector
fdcStatus.bit[DRQ] := False;
fdcStatus.bit[LDB] := False;
fdcStatus.bit[RNF] := False;
fdcStatus.bit[RTSU] := False;
fdcStatus.bit[WP] := False;
extStatus.bit[DRQ] := False;
if (canClearIntrq) then begin
extStatus.bit[INTQ] := False;
end;
isMultiSectorCommand := False;
actualFloppyDrive^.MotorOn := True;
fdcStatus.bit[RTSU] := True;
if (cmd.bit[4]) then begin // Bit 4 gesetzt, dann Multi-Sector Write
isMultiSectorCommand := True;
end;
prepareWriteSectors;
end; // Write Sector
%11000000: begin // Read Address / Force Interrupt
if (cmd.bit[4]) then begin // Bit 4 gesetzt - Force Interrupt
if ((cmd.Value and $0f) = $00) then begin // Beendet alle Befehle ohne INTRQ
dataMode := NONE;
isMultiSectorCommand := False;
fdcStatus.bit[DRI] := False;
extStatus.bit[DRQ] := False;
fdcStatus.bit[BUSY] := False;
fdcStatus.bit[RTSU] := False;
actualFloppyDrive^.MotorOn := True;
canClearIntrq := True;
end;
if ((cmd.Value and $0f) = $08) then begin // Beendet alle Befehle mit INTRQ
dataMode := NONE;
isMultiSectorCommand := False;
fdcStatus.bit[DRI] := False;
extStatus.bit[DRQ] := False;
fdcStatus.bit[BUSY] := False;
fdcStatus.bit[RTSU] := False;
extStatus.bit[INTQ] := True;
actualFloppyDrive^.MotorOn := True;
canClearIntrq := False;
end;
end
else begin // Bit 4 gelöscht - Read Address
fdcStatus.bit[DRQ] := False;
fdcStatus.bit[LDB] := False;
fdcStatus.bit[RNF] := False;
fdcStatus.bit[RTSU] := True;
fdcStatus.bit[WP] := False;
extStatus.bit[DRQ] := False;
actualFloppyDrive^.MotorOn := True;
prepareAddressRead;
end;
end;
end;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.setData(Data: byte);
begin
case (dataMode) of
SECTOR_WRITE: begin
dataBuffer[dataCount] := Data;
Inc(dataCount);
if (dataCount >= actualFloppyDrive^.SectorBytes) then begin
finishWriteSectors;
end;
end
else begin
fdcData := Data;
end;
end;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.setTrack(track: byte);
begin
fdcTrack := track;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.setSector(sector: byte);
begin
fdcSector := sector;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.setExtControl(control: byte);
var
oldExtControl: TbitReg8;
begin
if (extControl.Value = control) then begin
exit;
end;
oldExtControl := extControl;
extControl.Value := control;
if (extControl.bit[MRES]) then begin
doReset;
end;
if ((extControl.bit[D0S]) and (not oldExtControl.bit[D0S])) then begin
if Assigned(actualFloppyDrive^.FddStatus) then begin
setFddOffState(nil);
end;
actualFloppyDrive := @floppyDrive0;
SetLength(dataBuffer, actualFloppyDrive^.SectorBytes);
end;
if ((extControl.bit[D1S]) and (not oldExtControl.bit[D1S])) then begin
if Assigned(actualFloppyDrive^.FddStatus) then begin
setFddOffState(nil);
end;
actualFloppyDrive := @floppyDrive1;
SetLength(dataBuffer, actualFloppyDrive^.SectorBytes);
end;
if ((not resetState) and (not extControl.bit[D0S]) and (not extControl.bit[D1S])) then begin
actualFloppyDrive := @resetFloppyDrive;
end;
if (extControl.bit[D0S] or extControl.bit[D1S]) then begin
if ((not resetState) and actualFloppyDrive^.Loaded) then begin
fdcStatus.bit[LDB] := True;
end;
actualFloppyDrive^.MotorOn := True;
end
else begin
fdcStatus.bit[LDB] := False;
end;
if ((extControl.bit[SS]) and (actualFloppyDrive^.Sides = 2)) then begin
fdcSide := 1;
end
else begin
fdcSide := 0;
end;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.setFdd0Sides(sides: integer);
begin
floppyDrive0.Sides := sides;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.setFdd0Tracks(tracks: integer);
begin
floppyDrive0.Tracks := tracks;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.setFdd0Sectors(sectors: integer);
begin
floppyDrive0.Sectors := sectors;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.setFdd0SectorBytes(sectorbytes: integer);
begin
floppyDrive0.SectorBytes := sectorbytes;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.setFdd0Image(FileName: string);
var
hintString: string;
begin
hintString := '';
floppyDrive0.Loaded := False;
floppyDrive0.Changed := True;
floppyDrive0.MotorOn := False;
if (FileExists(FileName)) then begin
try
AssignFile(floppyDrive0.ImageData, FileName);
Reset(floppyDrive0.ImageData, 1);
floppyDrive0.Size := FileSize(floppyDrive0.ImageData);
hintString := 'Image: ' + ExtractFileName(FileName) + LineEnding + 'Größe: ' + IntToStr(floppyDrive0.Size div 1024) +
'KB' + LineEnding + 'Seiten: ' + IntToStr(floppyDrive0.Sides) + LineEnding + 'Spuren: ' +
IntToStr(floppyDrive0.Tracks) + LineEnding + 'Sektoren: ' + IntToStr(floppyDrive0.Sectors) + LineEnding +
'Bytes/Sektor: ' + IntToStr(floppyDrive0.SectorBytes);
floppyDrive0.Loaded := True;
Close(floppyDrive0.ImageData);
except
end;
end
else begin
floppyDrive0.Size := 0;
end;
floppyDrive0.FddStatus.Hint := hintString;
floppyDrive0.FddStatus.Enabled := floppyDrive0.Loaded;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.setFdd1Sides(sides: integer);
begin
floppyDrive1.Sides := sides;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.setFdd1Tracks(tracks: integer);
begin
floppyDrive1.Tracks := tracks;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.setFdd1Sectors(sectors: integer);
begin
floppyDrive1.Sectors := sectors;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.setFdd1SectorBytes(sectorbytes: integer);
begin
floppyDrive1.SectorBytes := sectorbytes;
end;
// --------------------------------------------------------------------------------
procedure TSystemFdc.setFdd1Image(FileName: string);
var
hintString: string;
begin
hintString := '';
floppyDrive1.Loaded := False;
floppyDrive1.Changed := True;
floppyDrive1.MotorOn := False;
if (FileExists(FileName)) then begin
try
AssignFile(floppyDrive1.ImageData, FileName);
Reset(floppyDrive1.ImageData, 1);
floppyDrive1.Size := FileSize(floppyDrive1.ImageData);
hintString := 'Image: ' + ExtractFileName(FileName) + LineEnding + 'Größe: ' + IntToStr(floppyDrive1.Size div 1024) +
'KB' + LineEnding + 'Seiten: ' + IntToStr(floppyDrive1.Sides) + LineEnding + 'Spuren: ' +
IntToStr(floppyDrive1.Tracks) + LineEnding + 'Sektoren: ' + IntToStr(floppyDrive1.Sectors) + LineEnding +
'Bytes/Sektor: ' + IntToStr(floppyDrive1.SectorBytes);
floppyDrive1.Loaded := True;
Close(floppyDrive1.ImageData);
except;
end;
end
else begin
floppyDrive1.Size := 0;
end;
floppyDrive1.FddStatus.Hint := hintString;
floppyDrive1.FddStatus.Enabled := floppyDrive1.Loaded;
end;
// --------------------------------------------------------------------------------
function TSystemFdc.getData: byte;
begin
case (dataMode) of
SECTOR_READ: begin
Result := dataBuffer[dataCount];
Inc(dataCount);
if (dataCount >= actualFloppyDrive^.SectorBytes) then begin
finishReadSectors;
end;
end;
ADDRESS_READ: begin
Result := dataBuffer[dataCount];
Inc(dataCount);
if (dataCount >= 6) then begin
finishAddressRead;
end;
end
else begin
Result := fdcData;
end;
end;
end;
// --------------------------------------------------------------------------------
function TSystemFdc.getStatus: byte;
begin
// Verhalten nicht eindeutig geklaert. Auf der Original Hardware scheint das Flag verzoegert geloescht zu werden.
//if (canClearIntrq) then begin
//extStatus.bit[INTQ] := False; // beim Lesen des Status-Registers wird das Interrupt-Flag geloescht
//end;
//if (resetState and (not actualFloppyDrive^.Loaded)) then begin
if (resetState) then begin
actualFloppyDrive^.MotorOn := False;
end;
fdcStatus.bit[MON] := actualFloppyDrive^.MotorOn;
Result := fdcStatus.Value;
end;
// --------------------------------------------------------------------------------
function TSystemFdc.getTrack: byte;
begin
Result := fdcTrack;
end;
// --------------------------------------------------------------------------------
function TSystemFdc.getSector: byte;
begin
Result := fdcSector;
end;
// --------------------------------------------------------------------------------
function TSystemFdc.getExtStatus: byte;
begin
extStatus.bit[DC] := actualFloppyDrive^.Changed;
Result := extStatus.Value;
end;
end.
|
unit ibSHFilter;
interface
uses
SysUtils, Classes,
SHDesignIntf,
ibSHDesignIntf, ibSHDBObject;
type
TibBTFilter = class(TibBTDBObject, IibSHFilter)
private
FInputType: Integer;
FOutputType: Integer;
FEntryPoint: string;
FModuleName: string;
function GetInputType: Integer;
procedure SetInputType(Value: Integer);
function GetOutputType: Integer;
procedure SetOutputType(Value: Integer);
function GetEntryPoint: string;
procedure SetEntryPoint(Value: string);
function GetModuleName: string;
procedure SetModuleName(Value: string);
published
property Description;
property InputType: Integer read GetInputType {write SetInputType};
property OutputType: Integer read GetOutputType {write SetOutputType};
property EntryPoint: string read GetEntryPoint {write SetEntryPoint};
property ModuleName: string read GetModuleName {write SetModuleName};
end;
implementation
uses
ibSHConsts, ibSHSQLs;
{ TibBTFilter }
function TibBTFilter.GetInputType: Integer;
begin
Result := FInputType;
end;
procedure TibBTFilter.SetInputType(Value: Integer);
begin
FInputType := Value;
end;
function TibBTFilter.GetOutputType: Integer;
begin
Result := FOutputType;
end;
procedure TibBTFilter.SetOutputType(Value: Integer);
begin
FOutputType := Value;
end;
function TibBTFilter.GetEntryPoint: string;
begin
Result := FEntryPoint;
end;
procedure TibBTFilter.SetEntryPoint(Value: string);
begin
FEntryPoint := Value;
end;
function TibBTFilter.GetModuleName: string;
begin
Result := FModuleName;
end;
procedure TibBTFilter.SetModuleName(Value: string);
begin
FModuleName := Value;
end;
end.
|
function CorrentPrinter :String;
// Retorna a impressora padrão do windows
// Requer a unit printers declarada na clausula uses da unit
var
Device : array[0..255] of char;
Driver : array[0..255] of char;
Port : array[0..255] of char;
hDMode : THandle;
begin
Printer.GetPrinter(Device, Driver, Port, hDMode);
Result := Device+' na porta '+Port;
end;
|
program HowToCollideSpritesWithWindowEdge;
uses
SwinGame, sgTypes;
procedure KeepOnScreen(s: Sprite);
begin
if SpriteX(s) > ScreenWidth() - SpriteWidth(s) then
begin
SpriteSetDX(s, -SpriteDX(s));
SpriteSetX(s, ScreenWidth() - SpriteWidth(s));
end;
if SpriteY(s) > ScreenHeight() - SpriteHeight(s) then
begin
SpriteSetDY(s, -SpriteDY(s));
SpriteSetY(s, ScreenHeight() - SpriteHeight(s));
end;
if SpriteX(s) < 0 then
begin
SpriteSetDX(s, -SpriteDX(s));
SpriteSetX(s, 0);
end;
if SpriteY(s) < 0 then
begin
SpriteSetDY(s, -SpriteDY(s));
SpriteSetY(s, 0);
end;
end;
procedure Main();
var
asteroid: Sprite;
begin
OpenGraphicsWindow('Keeping Sprite On Screen', 800, 600);
ClearScreen(ColorWhite);
LoadBitmapNamed('asteroid', 'asteroid.png');
asteroid := CreateSprite(BitmapNamed('asteroid'));
SpriteSetX(asteroid, 100);
SpriteSetY(asteroid, 500);
SpriteSetMass(asteroid, 1);
SpriteSetVelocity(asteroid, VectorTo(4, -2.4));
repeat
ProcessEvents();
ClearScreen(ColorWhite);
DrawSprite(asteroid);
UpdateSprite(asteroid);
KeepOnScreen(asteroid);
RefreshScreen(60);
until WindowCloseRequested();
FreeSprite(asteroid);
ReleaseAllResources();
end;
begin
Main();
end. |
(*
Category: SWAG Title: ANYTHING NOT OTHERWISE CLASSIFIED
Original name: 0098.PAS
Description: Amortization Routine
Author: RICHARD ODOM
Date: 05-26-94 10:52
*)
program amort;
uses crt;
{ This program does a good job of loan amortization. The original
author is unknown. I added a procedure to exit the program without
showing all years for amortization. Richard Odom..VA Beach }
const
MonthTab = 8; {month column}
PayTab = 14; {payment column}
PrinTab = 28; {principle column}
IntTab = 41; {interest column}
BalTab = 53; {balance column}
var
balance, payment, interest{, rate}, years,
i1, i2, CurrInt, CurrPrin, ypay, yint, yprin,
GTPay, GTInt, GTPrin: real;
year, month, line: integer;
borrower: string[32];
response: char;
begin
repeat
ClrScr;
write ('Name of borrower: ');
readln (borrower);
write ('Amount of loan: ');
readln (balance);
write ('Interest rate: ');
readln (interest);
i1 := interest/1200 {monthly interest};
write ('Do you know the monthly payments? ');
readln (response);
if UpCase(response) = 'Y'
then begin
write ('Payment amount: ');
readln (payment);
end
else begin
write ('Number of years: ');
readln (years);
i2 := exp(ln(i1 + 1) * (12 * years));
payment := balance * i1 * i2 / (i2 - 1);
payment := int(payment * 100 + 0.5) / 100;
writeln ('The monthly payment is $',payment:4:2,'.')
end;
write ('Starting year for loan: ');
readln (year);
write ('Starting month for loan: ');
readln (month);
write ('Press <RETURN> to see monthly totals.');
readln (response);
ClrScr; line := 6;
writeln ('Loan for ',borrower);
writeln (' Loan of $',balance:4:2,' at ',interest:4:2,'% interest.');
writeln (' Fixed monthly payments of $',payment:4:2,'.');
writeln;
writeln (year:4,' Month Payment Principle Interest Balance');
ypay := 0; yprin := 0; yint := 0;
GTPay := 0; GTInt := 0; GTPrin := 0; {initialize totals}
while balance>0 do begin
CurrInt := int(100 * i1 * balance +0.5) / 100;
CurrPrin := payment - CurrInt;
if CurrPrin>balance then begin
CurrPrin := balance;
payment := CurrInt + CurrPrin;
end;
balance := balance - CurrPrin;
ypay := ypay + payment; yint := yint + CurrInt; yprin := yprin + CurrPrin;
GTPay := GTPay + payment; GTInt := GTInt + CurrInt; GTPrin := GTPrin + CurrPrin;
line := line + 1; GotoXY(MonthTab,line);
write (month:2); GotoXY(PayTab,line);
write (payment:10:2); GotoXY(PrinTab,line);
write (CurrPrin:10:2); GotoXY(IntTab,line);
write (CurrInt:10:2); GotoXY(BalTab,line);
writeln (balance:12:2);
month := month + 1;
if (month>12) or (balance=0.0) then begin
writeln; line := line + 2;
write (year:4,' Total'); GotoXY(PayTab,line);
write (ypay:10:2); GotoXY(PrinTab,line);
write (yprin:10:2); GotoXY(IntTab,line);
write (yint:10:2); GotoXY(BalTab,line);
writeln (balance:12:2);
year := year + 1;
month := 1;
ypay := 0; yprin := 0; yint := 0;
if balance>0 then begin
writeln;
writeln ('Press <RETURN> to see ',year:4,'.');
write('Enter Q to end program ');
readln (response);
If upcase(response)='Q' then
halt;
ClrScr; line := 2; writeln (year:4,' Month Payment Principle Interest Balance');
end;
end;
end; {while}
writeln; line := line + 2;
write ('Grand Total'); GotoXY(PayTab,line);
write (GTPay:10:2); GotoXY(PrinTab,line);
write (GTPrin:10:2); GotoXY(IntTab,line);
write (GTInt:10:2); GotoXY(BalTab,line);
writeln (balance:12:2);
writeln;
write ('Do you wish to start over? ');
readln (response);
until UpCase(response)='N';
end.
|
{Um número inteiro positivo é dito triangular se seu valor é o produto de três números naturais consecutivos. Por exemplo, o número 120 é triangular porque 120 = 4 x 5 x 6 . Faça um programa Pascal que leia do teclado um número inteiro positivo n e verifique se ele é triangular ou não. Se for, imprima 1 e se não for, imprima 0.}
program numeroTringular;
var
n:integer;
begin
read(n);
if (n mod 2 = 0) AND (n mod 3 = 0) then
writeln('1')
else
writeln('0');
end. |
inherited dPromptReplace: TdPromptReplace
ActiveControl = bYes
BorderStyle = bsDialog
Caption = 'Confirm replace'
ClientHeight = 196
ClientWidth = 442
DesignSize = (
442
196)
PixelsPerInch = 96
TextHeight = 13
object lMessage: TTntLabel
Left = 12
Top = 12
Width = 422
Height = 37
Alignment = taCenter
Anchors = [akLeft, akTop, akRight]
AutoSize = False
Caption = '...'
Layout = tlCenter
WordWrap = True
end
object bYes: TTntButton
Left = 28
Top = 168
Width = 75
Height = 23
Anchors = [akBottom]
Caption = '&Yes'
Default = True
ModalResult = 6
TabOrder = 1
end
object bCancel: TTntButton
Left = 268
Top = 168
Width = 75
Height = 23
Anchors = [akBottom]
Cancel = True
Caption = 'Cancel'
ModalResult = 2
TabOrder = 4
end
object bReplaceAll: TTntButton
Left = 108
Top = 168
Width = 75
Height = 23
Anchors = [akBottom]
Caption = 'Replace &all'
ModalResult = 10
TabOrder = 2
end
object bNo: TTntButton
Left = 188
Top = 168
Width = 75
Height = 23
Anchors = [akBottom]
Caption = '&No'
ModalResult = 7
TabOrder = 3
end
object mText: TTntMemo
Left = 12
Top = 52
Width = 422
Height = 108
Anchors = [akLeft, akTop, akRight, akBottom]
HideSelection = False
ParentColor = True
ReadOnly = True
ScrollBars = ssBoth
TabOrder = 0
WordWrap = False
end
object bHelp: TTntButton
Left = 348
Top = 168
Width = 75
Height = 23
Anchors = [akBottom]
Caption = 'Help'
TabOrder = 5
OnClick = ShowHelpNotify
end
object dklcMain: TDKLanguageController
IgnoreList.Strings = (
'*.SecondaryShortCuts')
Left = 20
Top = 60
LangData = {
0E006450726F6D70745265706C61636501010000000100000007004361707469
6F6E0107000000040062596573010100000009000000070043617074696F6E00
07006243616E63656C01010000000A000000070043617074696F6E0008006C4D
65737361676500000B00625265706C616365416C6C01010000000C0000000700
43617074696F6E000300624E6F01010000000D000000070043617074696F6E00
05006D54657874000005006248656C7001010000000E00000007004361707469
6F6E00}
end
end
|
unit Files;
{This unit defines abstract file and directory
classes as well as implementation of simple
disk file, buffered file and a text file and
a disk directory. Little addition }
interface
uses Classes,SysUtils, StdCtrls, FileCtrl, misc_utils;
Const
{Constants for text files}
txt_bufsize=8096;
txt_maxlinesize=4096;
Type
TFileInfo=class
size,
offs:longint;
Function GetString(n:Integer):String;virtual;
end;
TFileChangeControl=class
Fsize:longint;
Ftime:Integer;
Fname:String;
Procedure SetFile(name:String);
Function Changed:boolean;
end;
{TFileList=class(TStringList)
private
Procedure SetFInfo(n:Integer;fi:TFileInfo);
Function GetFInfo(n:Integer):TFileInfo;
public
Property FileInfo[N:Integer]:TFileInfo read GetFInfo write SetFInfo;
end;}
TFile=class
Function GetFullName:String;virtual;abstract;
Function GetShortName:String;virtual;abstract;
Function Fread(var buf;size:integer):integer;virtual;abstract;
Function Fwrite(const buf;size:integer):integer;virtual;abstract;
Function Fsize:Longint;virtual;abstract;
Function Fpos:Longint;virtual;abstract;
Procedure Fseek(Pos:longint);virtual;abstract;
Destructor FClose;virtual;abstract;
end;
TContainerCreator=class {Service object. Used to modify containers}
cf:TFile;
Constructor Create(name:String);
Procedure PrepareHeader(newfiles:TStringList);virtual;abstract;
Procedure AddFile(F:TFile);virtual;abstract;
Function ValidateName(name:String):String;virtual;abstract;
Destructor Destroy;override;
end;
TContainerFile=class
Permanent:Boolean;
name:String;
Files:TStringList;
Dirs:TStringList;
F:TFile;
fc:TFileChangeControl;
Constructor CreateOpen(path:String);
Procedure Free;
Destructor Destroy;Override;
Function GetColName(n:Integer):String;dynamic;
Function GetColWidth(n:Integer):Integer;dynamic;
Function ColumnCount:Integer;dynamic;
Function GetFullName:String;virtual;
Function GetShortName:String;dynamic;
Function OpenFile(Fname:TFileName;mode:Integer):TFile;virtual;
Function OpenFilebyFI(fi:TFileInfo):TFile;virtual;
Function ChDir(d:String):boolean;virtual;
Procedure RenameFile(Fname,newname:TFileName);virtual;abstract;
Function ListFiles:TStringList;virtual;
Function ListDirs:TStringList;virtual;
Function GetFileInfo(Fname:String):TFileInfo;virtual;
Function AddFiles(AddList:TStringList):boolean; virtual;
Function DeleteFiles(DelList:TStringList):boolean;virtual;abstract;
Function AddFile(Fname:String):boolean;virtual;
Function DeleteFile(Fname:String):boolean;
Function GetContainerCreator(name:String):TContainerCreator;virtual;abstract; {used for adding/deleting files}
Protected
Procedure ClearIndex;
{Below go the methods that have to be overridden}
Procedure Refresh;virtual;abstract;
{Must fill the .Files filed Format:
Strings[n] - name
Objects[n] - TFileInfo for the file }
end;
TSubFile=class(TFile)
offs,size:longint;
f:TFile;
Fname:String;
Function GetShortName:String;Override;
Function GetFullName:String;Override;
Constructor CreateRead(const fn,name:String;apos,asize:Longint);
Function Fread(var buf;size:integer):integer;override;
Function Fsize:Longint;override;
Function Fpos:Longint;override;
Procedure Fseek(Pos:longint);override;
Destructor FClose;override;
end;
TBufFile=class(TFile)
f:TFile;
pbuf:pchar;
spos:Longint;
bpos,bsize:word;
bcapacity:word;
fmode:(f_read,f_write);
Constructor CreateRead(bf:TFile);
Constructor CreateWrite(bf:TFile);
Function GetFullName:String;override;
Function GetShortName:String;override;
Function Fread(var buf;size:integer):integer;override;
Function Fwrite(const buf;size:integer):integer;override;
Function Fsize:Longint;override;
Function Fpos:Longint;override;
Procedure Fseek(Pos:longint);override;
Destructor FClose;override;
Private
Procedure InitBuffer(size:word);
Procedure ReadBuffer;
Procedure WriteBuffer;
end;
TTextFile=Class
f:TFile;
bpos,bsize:word;
buffer:array[0..txt_bufsize] of char;
curline:Integer;
Function GetFullName:String;
Constructor CreateRead(bf:TFile);
Constructor CreateWrite(bf:TFile);
Procedure Readln(var s:String);
Procedure Writeln(s:String);
Procedure WritelnFmt(const fmt:String;const args:array of const);
Function Eof:Boolean;
Destructor FClose;
Function FSize:Longint;
Function FPos:Longint;
Property CurrentLine:Integer read curLine;
Private
Procedure LoadBuffer;
Procedure SeekEoln;
end;
TLECTextFile=Class(TTextFile)
FComment:String;
Procedure Readln(var s:String);
Property Comment:String read FComment;
end;
TParsedTextFile=class(TTextFile)
private
fsp:TStringParser;
Public
Constructor CreateRead(bf:TFile);
Procedure ReadLine;
Property Parsed: TStringParser read fsp;
Destructor FClose;
end;
TDiskDirectory=class(TContainerFile)
Name:String;
Constructor CreateFromPath(Dname:TfileName);
Function GetFullName:String;override;
Function GetShortName:String;override;
Function OpenFile(Fname:TFileName;mode:Integer):TFile;override;
Procedure RenameFile(Fname,newname:TFileName);override;
Function DeleteFiles(DelList:TStringList):boolean;override;
Function ListFiles:TStringList;override;
Function AddFiles(AddList:TStringList):boolean;override;
end;
TDiskFile=class(TFile)
f:File;
Constructor CreateRead(path:TFileName);
Constructor CreateWrite(path:TFileName);
Function GetFullName:String;override;
Function GetShortName:String;override;
Function Fread(var buf;size:integer):integer;override;
Function Fwrite(const buf;size:integer):integer;override;
Function Fsize:Longint;override;
Function Fpos:Longint;override;
Procedure Fseek(Pos:longint);override;
Destructor FClose;override;
end;
implementation
Uses FileOperations;
{Procedure TFileList.SetFInfo(n:Integer;fi:TFileInfo);
begin
Objects[n]:=fi;
end;
Function TFileList.GetFInfo(n:Integer):TFIleInfo;
begin
Result:=TFileInfo(Objects[n]);
end;}
Function TFileInfo.GetString(n:Integer):String;
begin
if n=1 then Result:=IntToStr(size) else Result:='';
end;
Constructor TDiskFile.CreateRead(path:TFileName);
begin
Assign(f,path);
FileMode:=0;
Reset(f,1);
end;
Constructor TDiskFile.CreateWrite(path:TFileName);
begin
Assign(f,path);
ReWrite(f,1);
end;
Function TDiskFile.GetFullName:String;
begin
Result:=TFileRec(f).name;
end;
Function TDiskFile.GetShortName:String;
begin
Result:=ExtractFileName(GetFullName);
end;
Function TDiskFile.Fread(var buf;size:integer):integer;
begin
BlockRead(f,buf,size,Result);
end;
Function TDiskFile.Fwrite(const buf;size:integer):integer;
begin
BlockWrite(f,buf,size,Result);
end;
Function TDiskFile.Fsize:Longint;
begin
Result:=FileSize(f);
end;
Function TDiskFile.Fpos:Longint;
begin
Result:=FilePos(f);
end;
Procedure TDiskFile.Fseek(Pos:longint);
begin
Seek(f,Pos);
end;
Destructor TDiskFile.FClose;
begin
CloseFile(f);
end;
{TTextFile methods}
Destructor TTextFile.FClose;
begin
f.FClose;
end;
Function TTextFile.GetFullName:String;
begin
Result:=F.GetFullName;
end;
Constructor TTextFile.CreateRead(bf:TFile);
begin
f:=bf;
f.Fseek(0);
LoadBuffer;
end;
Function TTextFile.FSize:Longint;
begin
Result:=f.Fsize;
end;
Function TTextFile.FPos:Longint;
begin
Result:=f.Fpos+bsize-bpos;
end;
Constructor TTextFile.CreateWrite(bf:TFile);
begin
f:=bf;
end;
Procedure TTextFile.SeekEoln;
var ps:Pchar;
begin
ps:=StrScan(@buffer[bpos],#10);
if ps<>nil then {EoLn found}
begin
bpos:=ps-@buffer+1;
if bpos=bsize then LoadBuffer;
end
else {Eoln not found}
begin
Repeat
LoadBuffer;
if eof then exit;
ps:=StrScan(buffer,#10);
Until(ps<>nil);
bpos:=ps-@buffer;
SeekEoln;
end;
end;
Procedure TTextFile.Readln(var s:String);
var ps,pend:Pchar;
tmp:array[0..txt_maxlinesize-1] of char;
ssize:word;
l:word;
begin
Inc(CurLine);
s:='';
if bpos=bsize then LoadBuffer;
if eof then exit;
ps:=buffer+bpos;
pend:=StrScan(ps,#10);
if pend<>nil then
begin
ssize:=pend-ps;
if ssize>txt_maxlinesize then ssize:=txt_maxlinesize; {Limit string size to 255 chars}
s:=StrLCopy(tmp,ps,ssize);
l:=Length(s);
if l<>0 then if s[l]=#13 then SetLength(s,l-1);
inc(bpos,ssize);
SeekEoln;
end else
begin
ssize:=bsize-bpos;
if ssize>txt_maxlinesize then ssize:=txt_maxlinesize;
s:=StrLCopy(tmp,ps,ssize); {copy the tail of the buffer}
LoadBuffer;
if eof then exit;
pend:=StrScan(buffer,#10);
if pend=nil then ssize:=bsize else ssize:=pend-@buffer;
if ssize+length(s)>txt_maxlinesize then ssize:=txt_maxlinesize-length(s);
s:=ConCat(s,StrLCopy(tmp,buffer,ssize));
inc(bpos,ssize);
l:=Length(s);
if l<>0 then if s[l]=#10 then SetLength(s,l-1);
l:=Length(s);
if l<>0 then if s[l]=#13 then SetLength(s,l-1);
SeekEoln;
end;
end;
Procedure TTextFile.Writeln;
const
eol:array[0..0] of char=#10;
begin
f.FWrite(s[1],length(s));
f.FWrite(eol,sizeof(eol));
end;
Procedure TTextFile.WritelnFmt(const fmt:String;const args:array of const);
begin
Writeln(Format(fmt,args));
end;
Function TTextFile.Eof:Boolean;
begin
result:=bsize=0;
end;
Procedure TTextFile.LoadBuffer;
var bytes:longint;
begin
bytes:=f.fsize-f.fpos;
if bytes>txt_bufsize then bytes:=txt_bufsize;
f.FRead(buffer,bytes);
bpos:=0;
bsize:=bytes;
buffer[bsize]:=#0;
end;
{TLECTextFile}
Procedure TLECTextFile.Readln(var s:String);
var p:Integer;
begin
Inherited Readln(s);
p:=Pos('#',s);
if p=0 then FComment:='' else
begin
FComment:=Copy(s,p,length(s)-p);
SetLength(s,p-1);
end;
end;
{TParsedTextFile}
Constructor TParsedTextFile.CreateRead(bf:TFile);
begin
fsp:=TStringParser.Create;
Inherited CreateRead(bf);
end;
Procedure TParsedTextFile.ReadLine;
var s:String;p:Integer;
begin
Readln(s);
p:=pos('#',s); if p<>0 then SetLength(s,p-1);
fsp.ParseString(s);
end;
Destructor TParsedTextFile.FClose;
begin
fsp.free;
Inherited;
end;
{TBufFile methods}
Procedure TBufFile.InitBuffer(size:word);
begin
bcapacity:=size;
GetMem(pbuf,bcapacity);
end;
Procedure TBufFile.ReadBuffer;
var bytes:integer;
begin
Bytes:=f.fsize-spos;
if bytes>bcapacity then bytes:=bcapacity;
bsize:=bytes;
f.Fread(pbuf^,bsize);
Inc(spos,bsize);
end;
Procedure TBufFile.WriteBuffer;
begin
f.Fwrite(pbuf^,bpos);
bpos:=0;
end;
Constructor TBufFile.CreateRead(bf:TFile);
begin
InitBuffer(2048);
f:=bf;
ReadBuffer;
fmode:=f_read;
end;
Constructor TBufFile.CreateWrite(bf:TFile);
begin
fmode:=f_write;
end;
Function TBufFile.GetFullName:String;
begin
result:=f.GetFullName;
end;
Function TBufFile.GetShortName:String;
begin
Result:=f.GetShortName;
end;
Function TBufFile.Fread(var buf;size:integer):integer;
var bleft:integer;
begin
if bpos+size<bsize then
begin
move((pbuf+bpos)^,buf,size);
Inc(bpos,size);
end
else
begin
bleft:=bsize-bpos;
Move((pbuf+bpos)^,buf,bleft);
Fread((pchar(@buf)+bleft)^,size-bleft);
Inc(spos,bpos+size);
bpos:=0;bsize:=0;
end;
end;
Function TBufFile.Fwrite(const buf;size:integer):integer;
begin
if bpos+size<bcapacity then
begin
Move(buf,(pbuf+bpos)^,size);
Inc(bpos,size);
end
else
begin
WriteBuffer;
f.FWrite(buf,size);
inc(spos,size);
end;
end;
Function TBufFile.Fsize:Longint;
begin
Result:=f.Fsize;
end;
Function TBufFile.Fpos:Longint;
begin
Result:=spos+bpos;
end;
Procedure TBufFile.Fseek(Pos:longint);
begin
if fmode=f_write then WriteBuffer;
f.Fseek(pos);
spos:=pos;
if fmode=f_read then ReadBuffer;
end;
Destructor TBufFile.FClose;
begin
if fmode=f_write then WriteBuffer;
f.FClose;
FreeMem(pbuf);
end;
Constructor TDiskDirectory.CreateFromPath(Dname:TfileName);
begin
if (Dname<>'') and (Dname[length(Dname)]<>'\') and (Dname[Length(Dname)]<>':')
then Name:=Dname+'\' else Name:=Dname;
If DirectoryExists(Dname) then
else MkDir(Dname);
end;
Function TDiskDirectory.OpenFile(Fname:TFileName;mode:Integer):TFile;
begin
Result:=TDiskFile.CreateRead(name+Fname);
end;
Procedure TDiskDirectory.RenameFile(Fname,newname:TFileName);
begin
SysUtils.RenameFile(Name+Fname,Name+NewName);
end;
Function TDiskDirectory.DeleteFiles(DelList:TStringList):boolean;
var i:integer;
begin
for i:=0 to files.count-1 do
SysUtils.DeleteFile(files[i]);
Result:=true;
end;
Function TDiskDirectory.GetShortName:String;
begin
Result:=name;
end;
Function TDiskDirectory.GetFullName:String;
begin
Result:=Name;
end;
Function TDiskDirectory.ListFiles:TStringList;
var sr:TSearchRec;
Files:TStringList;
res:integer;
Fi:TFileInfo;
i:integer;
begin
if files<>nil then
begin
for i:=0 to files.count-1 do files.objects[i].free;
Files.Free;
end;
Files:=TStringList.Create;
Res:=FindFirst(Name+'*.*',faHidden+faSysFile+faArchive+faReadOnly,sr);
While res=0 do
begin
Fi:=TFileInfo.Create;
Fi.Size:=sr.size;
Files.AddObject(sr.name,fi);
res:=FindNext(sr);
end;
FindClose(sr);
Result:=Files;
end;
Function TDiskDirectory.AddFiles(AddList:TStringList):boolean;
begin
end;
Constructor TContainerCreator.Create(name:String);
begin
cf:=OpenFileWrite(name,fm_Create or fm_LetReWrite);
end;
Destructor TContainerCreator.Destroy;
begin
cf.FClose;
end;
Procedure TContainerFile.Free;
begin
if not Permanent then Destroy;
end;
Function TContainerFile.GetColWidth(n:Integer):Integer;
begin
case n of
0: Result:=13;
1: Result:=10;
else Result:=10;
end;
end;
Function TContainerFile.GetColName(n:Integer):String;
begin
case n of
0: Result:='Name';
1: Result:='Size';
else Result:='';
end;
end;
Function TContainerFile.ColumnCount:Integer;
begin
Result:=2;
end;
Function TContainerFile.OpenFile(Fname:TFileName;mode:Integer):TFile;
var i:integer;
begin
if fc.Changed then Refresh;
if mode<>0 then raise Exception.Create('Cannot write file inside container: '+Fname);
i:=Files.IndexOf(Fname);
if i=-1 then raise Exception.Create('File not found: '+Fname);
With TFileInfo(Files.Objects[i]) do
Result:=TSubFile.CreateRead(Name,Fname,offs,size);
end;
Function TContainerFile.OpenFilebyFI;
var i:integer;
begin
if fc.Changed then raise Exception.Create('File has be changed! reload.');
i:=Files.IndexOfObject(fi);
if i=-1 then raise Exception.Create('OpenFileByFI: Cannot find file' );
Result:=TSubFile.CreateRead(Name,Files[i],fi.offs,fi.size);
end;
Function TContainerFile.ListDirs:TStringList;
begin
if fc.Changed then Refresh;
Result:=Dirs;
end;
Function TContainerFile.ChDir(d:String):boolean;
begin
Result:=false;
end;
Function TContainerFile.DeleteFile(Fname:String):boolean;
var sl:TStringList;
begin
sl:=TStringList.Create;
sl.Add(name);
DeleteFiles(sl);
sl.Free;
end;
Function TContainerFile.AddFile(Fname:String):boolean;
var sl:TStringList;
begin
sl:=TStringList.Create;
sl.Add(Fname);
AddFiles(sl);
sl.Free;
end;
Constructor TContainerFile.CreateOpen;
begin
Name:=Path;
Files:=TStringList.Create;
Dirs:=TStringList.Create;
fc:=TFileChangeControl.Create;
fc.SetFile(name);
Refresh;
end;
Destructor TContainerFile.Destroy;
var i:integer;
begin
for i:=0 to Files.count-1 do Files.objects[i].Free;
for i:=0 to Dirs.count-1 do Dirs.objects[i].Free;
Files.Free;
Dirs.Free;
end;
Function TContainerFile.ListFiles:TStringList;
begin
if fc.Changed then Refresh;
Result:=files;
end;
Procedure TContainerFile.ClearIndex;
var i:integer;
begin
for i:=0 to files.count-1 do files.objects[i].free;
files.clear;
end;
Function TContainerFile.GetFileInfo(Fname:String):TFileInfo;
var i:integer;
begin
i:=Files.IndexOf(Fname);
if i=-1 then result:=nil
else Result:=TFileInfo(Files.Objects[i]);
end;
Function TContainerFile.GetFullName:String;
begin
Result:=name;
end;
Function TContainerFile.GetShortName:String;
begin
Result:=ExtractFileName(GetFullName);
end;
Function TContainerFile.AddFiles(AddList:TStringList):boolean;
var CCreator:TContainerCreator;
newName:String;
newFiles:TStringList;
cName,fName:String;
i,n:Integer;
f:TFile;
begin
NewName:=ChangeFileExt(name,'.tmp');
CCreator:=GetContainerCreator(NewName);
newFiles:=TStringList.Create;
NewFiles.Assign(Files);
for i:=0 to AddList.Count-1 do
begin
fName:=AddList[i];
n:=Files.IndexOf(ExtractName(fName));
if n=-1 then NewFiles.Add(fName)
else begin NewFiles[n]:=fName; NewFiles.Objects[n]:=nil; end;
end;
CCreator.PrepareHeader(NewFiles);
For i:=0 to NewFiles.Count-1 do
begin
if NewFiles.Objects[i]=nil then {From Container}
f:=OpenFile(NewFiles[i],0)
else {Outside file}
f:=OpenFileRead(NewFiles[i],0);
CCreator.AddFile(f);
f.Fclose;
end;
newFiles.Free;
CCreator.Free;
BackUpFile(Name);
RenameFile(NewName,Name);
Refresh;
end;
Constructor TSubFile.CreateRead(const fn,name:String;apos,asize:Longint);
begin
FName:=fn+'>'+Name;
f:=OpenFileRead(fn,0);
offs:=apos;
size:=asize;
f.Fseek(offs);
end;
Function TSubFile.GetFullName:String;
begin
Result:=Fname;
end;
Function TSubFile.GetShortName:String;
begin
Result:=ExtractName(Fname);
end;
Function TSubFile.Fread(var buf;size:integer):integer;
begin
Result:=f.FRead(buf,size);
end;
Function TSubFile.Fsize:Longint;
begin
Result:=size;
end;
Function TSubFile.Fpos:Longint;
begin
Result:=f.Fpos-offs;
end;
Procedure TSubFile.Fseek(Pos:longint);
begin
F.FSeek(offs+pos);
end;
Destructor TSubFile.FClose;
begin
f.Fclose;
end;
Procedure TFileChangeControl.SetFile(name:String);
var sr:TSearchRec;
begin
FName:=name;
FindFirst(Fname,faAnyFile,sr);
Ftime:=sr.time;
Fsize:=sr.size;
FindClose(sr);
end;
Function TFileChangeControl.Changed:boolean;
var sr:TSearchRec;
begin
FindFirst(Fname,faAnyFile,sr);
result:=(Ftime<>sr.time) or (Fsize<>sr.size);
FindClose(sr);
end;
end.
|
PROGRAM WorkWithQueryString(INPUT, OUTPUT);
USES GPC;
FUNCTION GetQueryStringParameter(Key: STRING): STRING;
VAR
QueryString: STRING;
BEGIN
QueryString := GetEnv('QUERY_STRING');
GetQueryStringParameter := COPY(QueryString, POS(Key, QueryString) + Length(Key) + 1, POS('&', QueryString) - Length(Key) + 2)
END;
BEGIN {WorkWithQueryString}
WRITELN('Content-type: text/plain');
WRITELN;
WRITELN('First Name: ', GetQueryStringParameter('first_name'));
WRITELN('Last Name: ', GetQueryStringParameter('last_name'));
WRITELN('Age: ', GetQueryStringParameter('age'))
END. {WorkWithQueryString}
|
unit Unit1;
interface
uses Windows,
SysUtils,
dialogs,
Forms,
StdCtrls,
ComCtrls,
Controls,
Classes,
ALHttpClient,
ALWinHttpClient,
ALWebSpider,
AlAVLBinaryTree,
AlHttpCommon,
ExtCtrls;
type
{-------------------}
TForm1 = class(TForm)
StatusBar1: TStatusBar;
Label1: TLabel;
editURL2Crawl: TEdit;
ButtonStart: TButton;
EditSaveDirectory: TEdit;
Label2: TLabel;
EditMaxDeepLevel: TEdit;
UpDownMaxDeepLevel: TUpDown;
Label3: TLabel;
CheckBoxDownloadImage: TCheckBox;
CheckBoxUpdateHref: TCheckBox;
CheckBoxStayInStartSite: TCheckBox;
StatusBar2: TStatusBar;
BtnChooseSaveDirectory: TButton;
MemoErrorMsg: TMemo;
MainWebSpider: TAlWebSpider;
MainHttpClient: TALWinHttpClient;
ButtonStop: TButton;
Panel1: TPanel;
Label5: TLabel;
procedure ButtonStartClick(Sender: TObject);
procedure BtnChooseSaveDirectoryClick(Sender: TObject);
procedure MainWebSpiderCrawlDownloadError(Sender: TObject; URL, ErrorMessage: String; HTTPResponseHeader: TALHTTPResponseHeader; var StopCrawling: Boolean);
procedure MainWebSpiderCrawlDownloadRedirect(Sender: TObject; Url, RedirectedTo: String; HTTPResponseHeader: TALHTTPResponseHeader; var StopCrawling: Boolean);
procedure MainWebSpiderCrawlDownloadSuccess(Sender: TObject; Url: String; HTTPResponseHeader: TALHTTPResponseHeader; HttpResponseContent: TStream; var StopCrawling: Boolean);
procedure MainWebSpiderCrawlFindLink(Sender: TObject; HtmlTagString: String; HtmlTagParams: TStrings; URL: String);
procedure MainWebSpiderCrawlGetNextLink(Sender: TObject; var Url: String);
procedure MainWebSpiderUpdateLinkToLocalPathFindLink(Sender: TObject; HtmlTagString: String; HtmlTagParams: TStrings; URL: String; var LocalPath: String);
procedure MainWebSpiderUpdateLinkToLocalPathGetNextFile(Sender: TObject; var FileName, BaseHref: String);
procedure ButtonStopClick(Sender: TObject);
private
FPageDownloadedBinTree: TAlStringKeyAVLBinaryTree;
FPageNotYetDownloadedBinTree: TAlStringKeyAVLBinaryTree;
FCurrentDeepLevel: Integer;
FCurrentLocalFileNameIndex: integer;
function GetNextLocalFileName(aContentType: String): String;
public
end;
{---------------------------------------------------------------}
TPageDownloadedBinTreeNode = Class(TALStringKeyAVLBinaryTreeNode)
Private
Protected
Public
Data: String;
end;
{---------------------------------------------------------------------}
TPageNotYetDownloadedBinTreeNode = Class(TALStringKeyAVLBinaryTreeNode)
Private
Protected
Public
DeepLevel: Integer;
end;
var Form1: TForm1;
implementation
{$R *.dfm}
uses FileCtrl,
UrlMon,
AlFcnMisc,
AlFcnString,
AlFcnMime;
Const SplitDirectoryAmount = 5000;
{*************************************************}
procedure TForm1.ButtonStartClick(Sender: TObject);
{------------------------------}
Procedure InternalEnableControl;
Begin
ButtonStop.Enabled := False;
buttonStart.Enabled := True;
editURL2Crawl.Enabled := True;
EditSaveDirectory.Enabled := True;
EditMaxDeepLevel.Enabled := True;
UpDownMaxDeepLevel.Enabled := True;
CheckBoxDownloadImage.Enabled := True;
CheckBoxUpdateHref.Enabled := True;
CheckBoxStayInStartSite.Enabled := True;
BtnChooseSaveDirectory.Enabled := True;
end;
{-------------------------------}
Procedure InternalDisableControl;
Begin
ButtonStop.Enabled := True;
buttonStart.Enabled := False;
editURL2Crawl.Enabled := False;
EditSaveDirectory.Enabled := False;
EditMaxDeepLevel.Enabled := False;
UpDownMaxDeepLevel.Enabled := False;
CheckBoxDownloadImage.Enabled := False;
CheckBoxUpdateHref.Enabled := False;
CheckBoxStayInStartSite.Enabled := False;
BtnChooseSaveDirectory.Enabled := False;
end;
Var aNode: TPageNotYetDownloadedBinTreeNode;
Begin
{check the save directory}
If trim(EditSaveDirectory.Text) = '' then
raise Exception.Create('Please select a directory to save the downloaded files!');
{Handle if we ask to start or stop}
InternalDisableControl;
Try
{clear the label control}
StatusBar1.Panels[0].Text := '';
StatusBar1.Panels[1].Text := '';
StatusBar2.Panels[0].Text := '';
MemoErrorMsg.Lines.Clear;
{init private var}
FCurrentDeepLevel := 0;
FCurrentLocalFileNameIndex := 0;
FPageDownloadedBinTree:= TAlStringKeyAVLBinaryTree.Create;
FPageNotYetDownloadedBinTree:= TAlStringKeyAVLBinaryTree.Create;
Try
{add editURL2Crawl.text to the fPageNotYetDownloadedBinTree}
aNode:= TPageNotYetDownloadedBinTreeNode.Create;
aNode.ID := trim(editURL2Crawl.text);
aNode.DeepLevel := 0;
FPageNotYetDownloadedBinTree.AddNode(aNode);
{start the crawl}
MainWebSpider.Crawl;
{exit if the user click on the stop button}
If not ButtonStop.Enabled then exit;
{update the link on downloaded page to local path}
if CheckBoxUpdateHref.Checked then MainWebSpider.UpdateLinkToLocalPath;
finally
FPageDownloadedBinTree.Free;
FPageNotYetDownloadedBinTree.Free;
end;
finally
InternalEnableControl;
StatusBar2.Panels[0].Text := '';
end;
end;
{************************************************}
procedure TForm1.ButtonStopClick(Sender: TObject);
begin
ButtonStop.Enabled := False;
end;
{************************************************************}
procedure TForm1.BtnChooseSaveDirectoryClick(Sender: TObject);
Var aDir: string;
Begin
aDir := '';
if SelectDirectory(aDir, [sdAllowCreate, sdPerformCreate, sdPrompt],0) then EditSaveDirectory.Text := ALMakeGoodEndPath(aDir);
end;
{*****************************************************************}
function TForm1.GetNextLocalFileName(aContentType: String): String;
Var aExt: String;
{-------------------------------------}
Function SplitPathMakeFilename: String;
begin
Result := EditSaveDirectory.Text + inttostr((FCurrentLocalFileNameIndex div SplitDirectoryAmount) * SplitDirectoryAmount + SplitDirectoryAmount) + '\';
If (not DirectoryExists(Result)) and (not createDir(Result)) then raise exception.Create('cannot create dir: ' + Result);
Result := Result + inttostr(FCurrentLocalFileNameIndex) + aExt;
inc(FCurrentLocalFileNameIndex);
end;
Begin
aExt := ALlowercase(ALGetDefaultFileExtFromMimeContentType(aContentType)); // '.htm'
If FCurrentLocalFileNameIndex = 0 then Begin
result := EditSaveDirectory.Text + 'Start' + aExt;
inc(FCurrentLocalFileNameIndex);
end
else result := SplitPathMakeFilename;
end;
{***************************************************************}
procedure TForm1.MainWebSpiderCrawlDownloadError(Sender: TObject;
URL, ErrorMessage: String;
HTTPResponseHeader: TALHTTPResponseHeader;
var StopCrawling: Boolean);
Var aNode: TPageDownloadedBinTreeNode;
begin
{add the url to downloaded list}
aNode:= TPageDownloadedBinTreeNode.Create;
aNode.ID := Url;
aNode.data := '!';
If not FPageDownloadedBinTree.AddNode(aNode) then aNode.Free;
{delete the url from the not yet downloaded list}
FPageNotYetDownloadedBinTree.DeleteNode(url);
{update label}
MemoErrorMsg.Lines.Add('Error: ' + ErrorMessage);
StatusBar1.Panels[0].Text := 'Url Downloaded: ' + inttostr((FPageDownloadedBinTree.nodeCount));
StatusBar1.Panels[1].Text := 'Url to Download: ' + inttostr((FPageNotYetDownloadedBinTree.nodeCount));
application.ProcessMessages;
StopCrawling := not ButtonStop.Enabled;
end;
{******************************************************************}
procedure TForm1.MainWebSpiderCrawlDownloadRedirect(Sender: TObject;
Url, RedirectedTo: String;
HTTPResponseHeader: TALHTTPResponseHeader;
var StopCrawling: Boolean);
Var aNode: TALStringKeyAVLBinaryTreeNode;
begin
{add the url to downloaded list}
aNode:= TPageDownloadedBinTreeNode.Create;
aNode.ID := Url;
TPageDownloadedBinTreeNode(aNode).data := '=>'+RedirectedTo;
If not FPageDownloadedBinTree.AddNode(aNode) then aNode.Free;
{delete the url from the not yet downloaded list}
FPageNotYetDownloadedBinTree.DeleteNode(url);
{Stay in start site}
If not CheckBoxStayInStartSite.Checked or
(ALlowercase(AlExtractHostNameFromUrl(trim(editURL2Crawl.Text))) = ALlowercase(AlExtractHostNameFromUrl(RedirectedTo))) then begin
{remove the anchor}
RedirectedTo := AlRemoveAnchorFromUrl(RedirectedTo);
{add the redirectTo url to the not yet downloaded list}
If FPageDownloadedBinTree.FindNode(RedirectedTo) = nil then begin
aNode:= TPageNotYetDownloadedBinTreeNode.Create;
aNode.ID := RedirectedTo;
TPageNotYetDownloadedBinTreeNode(aNode).DeepLevel := FCurrentDeepLevel;
If not FPageNotYetDownloadedBinTree.AddNode(aNode) then aNode.Free;
end;
end;
{update label}
StatusBar1.Panels[0].Text := 'Url Downloaded: ' + inttostr((FPageDownloadedBinTree.nodeCount));
StatusBar1.Panels[1].Text := 'Url to Download: ' + inttostr((FPageNotYetDownloadedBinTree.nodeCount));
application.ProcessMessages;
StopCrawling := not ButtonStop.Enabled;
end;
{*****************************************************************}
procedure TForm1.MainWebSpiderCrawlDownloadSuccess(Sender: TObject;
Url: String;
HTTPResponseHeader: TALHTTPResponseHeader;
HttpResponseContent: TStream;
var StopCrawling: Boolean);
Var aNode: TPageDownloadedBinTreeNode;
Str: String;
AFileName: String;
pMimeTypeFromData: LPWSTR;
begin
{put the content in str}
HttpResponseContent.Position := 0;
SetLength(Str, HttpResponseContent.size);
HttpResponseContent.ReadBuffer(Str[1],HttpResponseContent.Size);
{we add a check here to be sure that the file is an http file (text file}
{Some server send image with text/htm content type}
IF (FindMimeFromData(
nil, // bind context - can be nil
nil, // url - can be nil
pchar(str), // buffer with data to sniff - can be nil (pwzUrl must be valid)
length(str), // size of buffer
PWidechar(WideString(HTTPResponseHeader.ContentType)), // proposed mime if - can be nil
0, // will be defined
pMimeTypeFromData, // the suggested mime
0 // must be 0
) <> NOERROR) then pMimeTypeFromData := PWidechar(WideString(HTTPResponseHeader.ContentType));
{Get the FileName where to save the responseContent}
aFileName := GetNextLocalFileName(pMimeTypeFromData);
{If html then add <!-- saved from '+ URL +' -->' at the top of the file}
If sametext(pMimeTypeFromData,'text/html') then begin
Str := '<!-- saved from '+ URL+' -->' +#13#10 + Str;
AlSaveStringToFile(str,aFileName);
end
{Else Save the file without any change}
else TmemoryStream(HttpResponseContent).SaveToFile(aFileName);
{delete the Url from the PageNotYetDownloadedBinTree}
FPageNotYetDownloadedBinTree.DeleteNode(Url);
{add the url to the PageDownloadedBinTree}
aNode:= TPageDownloadedBinTreeNode.Create;
aNode.ID := Url;
aNode.data := AlCopyStr(AFileName,length(EditSaveDirectory.Text) + 1,maxint);
If not FPageDownloadedBinTree.AddNode(aNode) then aNode.Free;
{update label}
StatusBar1.Panels[0].Text := 'Url Downloaded: ' + inttostr((FPageDownloadedBinTree.nodeCount));
StatusBar1.Panels[1].Text := 'Url to Download: ' + inttostr((FPageNotYetDownloadedBinTree.nodeCount));
application.ProcessMessages;
StopCrawling := not ButtonStop.Enabled;
end;
{**********************************************************}
procedure TForm1.MainWebSpiderCrawlFindLink(Sender: TObject;
HtmlTagString: String;
HtmlTagParams: TStrings;
URL: String);
Var aNode: TPageNotYetDownloadedBinTreeNode;
begin
{If Check BoxDownload Image}
IF not CheckBoxDownloadImage.Checked and
(
sametext(HtmlTagString,'img') or
(
sametext(HtmlTagString,'input') and
sametext(Trim(HtmlTagParams.Values['type']),'image')
)
)
then Exit;
{Stay in start site}
If CheckBoxStayInStartSite.Checked and
(ALlowercase(AlExtractHostNameFromUrl(trim(editURL2Crawl.Text))) <> ALlowercase(AlExtractHostNameFromUrl(Url))) then exit;
{DeepLevel}
If (UpDownMaxDeepLevel.Position >= 0) and (FCurrentDeepLevel + 1 > UpDownMaxDeepLevel.Position) then exit;
{remove the anchor}
URL := AlRemoveAnchorFromUrl(URL);
{If the link not already downloaded then add it to the FPageNotYetDownloadedBinTree}
If FPageDownloadedBinTree.FindNode(url) = nil then begin
aNode:= TPageNotYetDownloadedBinTreeNode.Create;
aNode.ID := Url;
aNode.DeepLevel := FCurrentDeepLevel + 1;
If not FPageNotYetDownloadedBinTree.AddNode(aNode) then aNode.Free
else begin
StatusBar1.Panels[1].Text := 'Url to Download: ' + inttostr((FPageNotYetDownloadedBinTree.nodeCount));
application.ProcessMessages;
end;
end;
end;
{*************************************************************}
procedure TForm1.MainWebSpiderCrawlGetNextLink(Sender: TObject;
var Url: String);
{-----------------------------------------------------------------------------}
function InternalfindNextUrlToDownload(aNode: TPageNotYetDownloadedBinTreeNode;
alowDeepLevel: Integer): TPageNotYetDownloadedBinTreeNode;
Var aTmpNode1, aTmpNode2: TPageNotYetDownloadedBinTreeNode;
Begin
If (not assigned(Anode)) or (aNode.DeepLevel <= alowDeepLevel) then result := aNode
else begin
if aNode.ChildNodes[true] <> nil then begin
aTmpNode1 := InternalfindNextUrlToDownload(TPageNotYetDownloadedBinTreeNode(aNode.ChildNodes[true]), alowDeepLevel);
If (assigned(aTmpNode1)) and (aTmpNode1.DeepLevel <= alowDeepLevel) then begin
result := aTmpNode1;
exit;
end;
end
else aTmpNode1 := nil;
if aNode.ChildNodes[false] <> nil then begin
aTmpNode2 := InternalfindNextUrlToDownload(TPageNotYetDownloadedBinTreeNode(aNode.ChildNodes[false]), alowDeepLevel);
If (assigned(aTmpNode2)) and (aTmpNode2.DeepLevel <= alowDeepLevel) then begin
result := aTmpNode2;
exit;
end;
end
else aTmpNode2 := nil;
result := aNode;
If assigned(aTmpNode1) and (result.deepLevel > aTmpNode1.deeplevel) then result := aTmpNode1;
If assigned(aTmpNode2) and (result.deepLevel > aTmpNode2.deeplevel) then result := aTmpNode2;
end;
end;
Var aNode: TPageNotYetDownloadedBinTreeNode;
begin
{If theire is more url to download}
IF FPageNotYetDownloadedBinTree.NodeCount > 0 then begin
{Find next url with deeplevel closer to FCurrentDeepLevel}
If UpDownMaxDeepLevel.Position >= 0 then aNode := InternalfindNextUrlToDownload(
TPageNotYetDownloadedBinTreeNode(FPageNotYetDownloadedBinTree.head),
FCurrentDeepLevel
)
{Find next url without take care of FCurrentDeepLevel}
else aNode := TPageNotYetDownloadedBinTreeNode(FPageNotYetDownloadedBinTree.head);
Url := aNode.ID;
FCurrentDeepLevel := TPageNotYetDownloadedBinTreeNode(aNode).DeepLevel;
end
{If their is no more url to download then exit}
else begin
Url := '';
FCurrentDeepLevel := -1;
end;
StatusBar2.Panels[0].Text := 'Downloading Url: ' + Url;
Application.ProcessMessages;
if not ButtonStop.Enabled then url := '';
end;
{**************************************************************************}
procedure TForm1.MainWebSpiderUpdateLinkToLocalPathFindLink(Sender: TObject;
HtmlTagString: String;
HtmlTagParams: TStrings;
URL: String;
var LocalPath: String);
Var aNode: TALStringKeyAVLBinaryTreeNode;
aAnchorValue: String;
begin
LocalPath := '';
If Url <> '' then begin
{Find the local Path}
While True Do begin
Url := AlRemoveAnchorFromUrl(Url, aAnchorValue);
aNode := FPageDownloadedBinTree.FindNode(URL);
If (aNode <> nil) then begin
LocalPath := TPageDownloadedBinTreeNode(aNode).Data;
If AlPos('=>',LocalPath) = 1 then Begin
Url := AlCopyStr(LocalPath,3,MaxInt);
LocalPath := '';
end
else Break;
end
else Break;
end;
If LocalPath = '!' then localpath := ''
else If LocalPath <> '' then begin
LocalPath := AlStringReplace(
LocalPath,
'\',
'/',
[RfReplaceall]
) + aAnchorValue;
If (FCurrentLocalFileNameIndex >= 0) then LocalPath := '../' + LocalPath;
end;
end;
end;
{*****************************************************************************}
procedure TForm1.MainWebSpiderUpdateLinkToLocalPathGetNextFile(Sender: TObject;
var FileName, BaseHref: String);
{-------------------------------------}
Function SplitPathMakeFilename: String;
begin
If FCurrentLocalFileNameIndex < 0 then result := ''
else If FCurrentLocalFileNameIndex = 0 then result := EditSaveDirectory.Text + 'Start.htm'
else Result := EditSaveDirectory.Text + inttostr((FCurrentLocalFileNameIndex div SplitDirectoryAmount) * SplitDirectoryAmount + SplitDirectoryAmount) + '\' + inttostr(FCurrentLocalFileNameIndex) + '.htm';
dec(FCurrentLocalFileNameIndex);
end;
Begin
{Find FileName}
FileName := SplitPathMakeFilename;
While (FileName <> '') and not fileExists(FileName) do
Filename := SplitPathMakeFilename;
{if filename found}
If FileName <> '' then Begin
{Extract the Base Href}
BaseHref := AlGetStringFromFile(FileName);
BaseHref := Trim(
AlCopyStr(
BaseHref,
17, // '<!-- saved from ' + URL
AlPos(#13,BaseHref) - 21 // URL + ' -->' +#13#10
)
);
end
else BaseHref := '';
{update label}
StatusBar2.Panels[0].Text := 'Update Href to Local path for file: ' + FileName;
application.ProcessMessages;
if not ButtonStop.Enabled then begin
FileName := '';
BaseHref := '';
end
end;
end.
|
(*
Category: SWAG Title: DOS & ENVIRONMENT ROUTINES
Original name: 0049.PAS
Description: Check DOS Path
Author: TONY NELSON
Date: 02-15-94 07:42
*)
program chkpath;
Uses Dos;
Procedure GetNextPath ( var Path, CurrPath : String );
Var
SemiPos : Byte;
Begin
SemiPos := Pos(';',Path);
If SemiPos = 0 then
Begin
CurrPath := Path;
Path := '';
End
Else
Begin
CurrPath := Copy(Path,1,SemiPos - 1);
Path := Copy(Path,SemiPos + 1, Length(Path));
End;
End;
Function CheckPath( Path : String ) : Boolean;
Var
Result : Integer;
Begin
{$I-}
ChDir(Path);
{$I-}
Result := IOResult;
CheckPath := (Result = 0);
End;
Var
PathStr : String;
CurrPath : String;
SaveDir : String;
Count : Byte;
Begin
WriteLn('Check Path : By Tony Nelson : FreeWare 1993');
WriteLn('Checking your current path for nonexistent entries...');
WriteLn;
GetDir(0,SaveDir);
PathStr := GetEnv('Path');
While (PathStr) <> '' do
Begin
GetNextPath(PathStr, CurrPath);
If not CheckPath(CurrPath) then
Begin
WriteLn(CurrPath,' is invalid!');
Inc(Count);
End;
End;
If Count <> 0 then
WriteLn;
WriteLn('Found ',Count,' nonexistent entries.');
ChDir(SaveDir);
End.
|
unit UPClient;
interface
uses
Classes, diocp_tcp_blockClient, UPMsgPack, UPMsgCoder;
type
TOnReceiveProcess = procedure(const AProcess, ASize: Integer) of object;
TUPClient = class(TObject)
private
FTcpClient: TDiocpBlockTcpClient;
FDataStream: TMemoryStream;
FOnReceiveProcess: TOnReceiveProcess;
procedure CheckConnect;
function SendStream(pvStream: TStream): Integer;
procedure DoError(const AErrCode: Integer; const AParam: string);
protected
function GetHost: string;
procedure SetHost(const AHost: string);
function GetPort: Integer;
procedure SetPort(const APort: Integer);
function GetActive: Boolean;
function GetTimeOut: Integer;
procedure SetTimeOut(const Value: Integer);
function SendDataBuffer(buf:Pointer; len:Cardinal): Cardinal; stdcall;
function RecvDataBuffer(buf:Pointer; len:Cardinal): Cardinal; stdcall;
function SendDataStream: Integer;
function RecvDataStream: Boolean;
public
constructor Create; virtual;
constructor CreateEx(const AHost: string; const APort: Integer);
destructor Destroy; override;
function Connected: Boolean;
procedure ReConnectServer;
procedure PostMsgPack(const AMsgPack: TUPMsgPack);
procedure ReceiveMsgPack(const AMsgPack: TUPMsgPack);
property Host: string read GetHost write SetHost;
property Port: Integer read GetPort write SetPort;
property Active: Boolean read GetActive;
property TimeOut: Integer read GetTimeOut write SetTimeOut;
property OnReceiveProcess: TOnReceiveProcess read FOnReceiveProcess write FOnReceiveProcess;
end;
implementation
uses
SysUtils, utils_zipTools, utils_byteTools, DiocpError;
{ TUPClient }
procedure TUPClient.CheckConnect;
begin
if not FTcpClient.Active then
FTcpClient.Connect;
end;
function TUPClient.Connected: Boolean;
begin
Result := FTcpClient.Active;
end;
constructor TUPClient.Create;
begin
inherited Create;
FTcpClient := TDiocpBlockTcpClient.Create(nil);
FTcpClient.ReadTimeOut := 60000;
FTcpClient.OnError := DoError;
FDataStream := TMemoryStream.Create;
end;
constructor TUPClient.CreateEx(const AHost: string; const APort: Integer);
begin
Create;
FTcpClient.Host := AHost;
FTcpClient.Port := APort;
end;
destructor TUPClient.Destroy;
begin
FTcpClient.Disconnect;
FTcpClient.Free;
FDataStream.Free;
inherited Destroy;
end;
procedure TUPClient.DoError(const AErrCode: Integer; const AParam: string);
begin
end;
function TUPClient.GetActive: Boolean;
begin
Result := FTcpClient.Active;
end;
function TUPClient.GetHost: string;
begin
Result := FTcpClient.Host;
end;
function TUPClient.GetPort: Integer;
begin
Result := FTcpClient.Port;
end;
function TUPClient.GetTimeOut: Integer;
begin
Result := FTcpClient.ReadTimeOut;
end;
procedure TUPClient.PostMsgPack(const AMsgPack: TUPMsgPack);
begin
CheckConnect;
FDataStream.Clear;
AMsgPack.EncodeToStream(FDataStream);
TZipTools.ZipStream(FDataStream, FDataStream);
SendDataStream;
end;
procedure TUPClient.ReceiveMsgPack(const AMsgPack: TUPMsgPack);
begin
RecvDataStream;
TZipTools.UnZipStream(FDataStream, FDataStream);
FDataStream.Position := 0;
AMsgPack.DecodeFromStream(FDataStream);
end;
procedure TUPClient.ReConnectServer;
begin
CheckConnect;
end;
function TUPClient.RecvDataBuffer(buf: Pointer; len: Cardinal): Cardinal;
begin
FTcpClient.Recv(buf, len);
Result := len;
end;
function TUPClient.RecvDataStream: Boolean;
var
vBytes: TBytes;
vReadLen, vTempLen: Integer;
vPACK_FLAG: Word;
vDataLen: Integer;
vVerifyValue, vVerifyDataValue: Cardinal;
vPByte: PByte;
begin
RecvDataBuffer(@vPACK_FLAG, 2);
if vPACK_FLAG <> PACK_FLAG then // 错误的包数据
begin
FTcpClient.Disconnect;
raise Exception.Create(strRecvException_ErrorFlag);
end;
//datalen
RecvDataBuffer(@vDataLen, SizeOf(vDataLen));
//veri value
RecvDataBuffer(@vVerifyValue, SizeOf(vVerifyValue));
//vDataLen := TByteTools.swap32(vReadLen);
if vDataLen > MAX_OBJECT_SIZE then // 文件头过大,错误的包数据
begin
FTcpClient.Disconnect;
raise Exception.Create(strRecvException_ErrorData);
end;
SetLength(vBytes,vDataLen);
vPByte := PByte(@vBytes[0]);
vReadLen := 0;
while vReadLen < vDataLen do
begin
vTempLen := RecvDataBuffer(vPByte, vDataLen - vReadLen);
if vTempLen = -1 then
begin
RaiseLastOSError;
end;
Inc(vPByte, vTempLen);
vReadLen := vReadLen + vTempLen;
if Assigned(FOnReceiveProcess) then
FOnReceiveProcess(vReadLen, vDataLen);
end;
{$IFDEF POSIX}
vVerifyDataValue := verifyData(lvBytes[0], lvDataLen);
{$ELSE}
vVerifyDataValue := verifyData(vBytes[0], vDataLen);
{$ENDIF}
if vVerifyDataValue <> vVerifyValue then
raise Exception.Create(strRecvException_VerifyErr);
FDataStream.Clear;
FDataStream.Write(vBytes[0], vDataLen);
Result := True;
end;
function TUPClient.SendDataBuffer(buf: Pointer; len: Cardinal): Cardinal;
begin
Result := FTcpClient.SendBuffer(buf, len);
end;
function TUPClient.SendDataStream: Integer;
var
lvPACK_FLAG: WORD;
lvDataLen, lvWriteIntValue: Integer;
lvBuf: TBytes;
lvStream: TMemoryStream;
lvVerifyValue: Cardinal;
begin
lvPACK_FLAG := PACK_FLAG;
lvStream := TMemoryStream.Create;
try
FDataStream.Position := 0;
if FDataStream.Size > MAX_OBJECT_SIZE then
raise Exception.CreateFmt(strSendException_TooBig, [MAX_OBJECT_SIZE]);
lvStream.Write(lvPACK_FLAG, 2); // 包头
lvDataLen := FDataStream.Size; // stream data
SetLength(lvBuf, lvDataLen);
FDataStream.Read(lvBuf[0], lvDataLen);
// stream len
lvStream.Write(lvDataLen, SizeOf(lvDataLen));
//veri value
lvVerifyValue := verifyData(lvBuf[0], lvDataLen);
lvStream.Write(lvVerifyValue, SizeOf(lvVerifyValue));
// send pack
lvStream.write(lvBuf[0], lvDataLen);
Result := SendStream(lvStream);
finally
lvStream.Free;
end;
end;
function TUPClient.SendStream(pvStream: TStream): Integer;
var
lvBufBytes: array[0..MAX_BLOCK_SIZE - 1] of byte;
l, j, r, lvTotal: Integer;
P: PByte;
begin
Result := 0;
if pvStream = nil then Exit;
if pvStream.Size = 0 then Exit;
lvTotal :=0;
pvStream.Position := 0;
repeat
//FillMemory(@lvBufBytes[0], SizeOf(lvBufBytes), 0);
l := pvStream.Read(lvBufBytes[0], SizeOf(lvBufBytes));
if (l > 0) then
begin
P := PByte(@lvBufBytes[0]);
j := l;
while j > 0 do
begin
r := SendDataBuffer(P, j);
if r = -1 then
RaiseLastOSError;
Inc(P, r);
Dec(j, r);
end;
lvTotal := lvTotal + l;
end
else
Break;
until (l = 0);
Result := lvTotal;
end;
procedure TUPClient.SetHost(const AHost: string);
begin
FTcpClient.Host := AHost;
end;
procedure TUPClient.SetPort(const APort: Integer);
begin
FTcpClient.Port := APort;
end;
procedure TUPClient.SetTimeOut(const Value: Integer);
begin
FTcpClient.ReadTimeOut := Value;
end;
end.
|
{ ***************************************************************************
Copyright (c) 2016-2020 Kike Pérez
Unit : Quick.Logger.Provider.Twilio
Description : Log Twilio Provider
Author : Kike Pérez
Version : 1.0
Created : 01/05/2020
Modified : 02/05/2020
This file is part of QuickLogger: https://github.com/exilon/QuickLogger
***************************************************************************
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.Logger.Provider.Twilio;
{$i QuickLib.inc}
interface
uses
Classes,
SysUtils,
DateUtils,
{$IFDEF FPC}
fpjson,
fpjsonrtti,
IdURI,
Quick.Base64,
{$ELSE}
{$IFDEF DELPHIXE8_UP}
System.JSON,
System.Net.URLClient,
System.NetEncoding,
{$ELSE}
Data.DBXJSON,
IdURI,
Quick.Base64,
{$ENDIF}
{$ENDIF}
Quick.HttpClient,
Quick.Commons,
Quick.Logger;
type
TLogTwilioProvider = class (TLogProviderBase)
private
fHTTPClient : TJsonHTTPClient;
fAccountSID : string;
fAuthToken : string;
fSendFrom : string;
fSendTo : string;
fFullURL : string;
fConnectionTimeout : Integer;
fResponseTimeout : Integer;
fUserAgent : string;
protected
fHeaders : TPairList;
function LogToTwilio(cLogItem: TLogItem): string;
public
constructor Create; override;
destructor Destroy; override;
property AccountSID : string read fAccountSID write fAccountSID;
property AuthToken : string read fAuthToken write fAuthToken;
property SendFrom : string read fSendFrom write fSendFrom;
property SendTo : string read fSendTo write fSendTo;
property UserAgent : string read fUserAgent write fUserAgent;
procedure Init; override;
procedure Restart; override;
procedure WriteLog(cLogItem : TLogItem); override;
end;
var
GlobalLogTwilioProvider : TLogTwilioProvider;
implementation
const
DEF_HTTPCONNECTION_TIMEOUT = 60000;
DEF_HTTPRESPONSE_TIMEOUT = 60000;
constructor TLogTwilioProvider.Create;
begin
inherited;
LogLevel := LOG_ALL;
fHeaders := TPairList.Create;
fConnectionTimeout := DEF_HTTPCONNECTION_TIMEOUT;
fResponseTimeout := DEF_HTTPRESPONSE_TIMEOUT;
fUserAgent := DEF_USER_AGENT;
IncludedInfo := [iiAppName,iiHost,iiEnvironment];
end;
destructor TLogTwilioProvider.Destroy;
begin
if Assigned(fHTTPClient) then FreeAndNil(fHTTPClient);
if Assigned(fHeaders) then fHeaders.Free;
inherited;
end;
procedure TLogTwilioProvider.Init;
var
auth : string;
{$IFDEF DELPHIXE8_UP}
base64 : TBase64Encoding;
{$ENDIF}
begin
fFullURL := Format('https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json',[fAccountSID]);
fHTTPClient := TJsonHTTPClient.Create;
fHTTPClient.ConnectionTimeout := fConnectionTimeout;
fHTTPClient.ResponseTimeout := fResponseTimeout;
fHTTPClient.ContentType := 'application/x-www-form-urlencoded';
fHTTPClient.UserAgent := fUserAgent;
fHTTPClient.HandleRedirects := True;
fHeaders.Clear;
{$IFDEF DELPHIXE8_UP}
base64 := TBase64Encoding.Create(0);
try
auth := base64.Encode(fAccountSID + ':' + fAuthToken);
finally
base64.Free;
end;
{$ELSE}
auth := Base64Encode(fAccountSID + ':' + fAuthToken);
{$ENDIF}
fHeaders.Add('Authorization','Basic ' + auth);
inherited;
end;
function TLogTwilioProvider.LogToTwilio(cLogItem: TLogItem): string;
begin
{$IFDEF DELPHIXE8_UP}
{$IFDEF DELPHIRX10_UP}
Result := 'Body=' + TNetEncoding.URL.Encode(LogItemToText(cLogItem))
+ '&From=' + TNetEncoding.URL.Encode(fSendFrom)
+ '&To=' + TNetEncoding.URL.Encode(fSendTo);
{$ELSE}
Result := 'Body=' + TURI.URLEncode(LogItemToText(cLogItem))
+ '&From=' + TURI.URLEncode(fSendFrom)
+ '&To=' + TURI.URLEncode(fSendTo);
{$ENDIF}
{$ELSE}
Result := 'Body=' + TIdURI.URLEncode(LogItemToText(cLogItem))
+ '&From=' + TIdURI.URLEncode(fSendFrom)
+ '&To=' + TIdURI.URLEncode(fSendTo);
{$ENDIF}
end;
procedure TLogTwilioProvider.Restart;
begin
Stop;
if Assigned(fHTTPClient) then FreeAndNil(fHTTPClient);
Init;
end;
procedure TLogTwilioProvider.WriteLog(cLogItem : TLogItem);
var
resp : IHttpRequestResponse;
begin
if CustomMsgOutput then resp := fHTTPClient.Post(fFullURL,LogItemToFormat(cLogItem),fHeaders)
else resp := fHTTPClient.Post(fFullURL,LogToTwilio(cLogItem),fHeaders);
if not (resp.StatusCode in [200,201,202]) then
raise ELogger.Create(Format('[TLogTwilioProvider] : Response %d : %s trying to post event (%s)',[resp.StatusCode,resp.StatusText,resp.Response.ToString]));
end;
initialization
GlobalLogTwilioProvider := TLogTwilioProvider.Create;
finalization
if Assigned(GlobalLogTwilioProvider) and (GlobalLogTwilioProvider.RefCount = 0) then GlobalLogTwilioProvider.Free;
end.
|
{*******************************************************}
{ }
{ Tachyon Unit }
{ Vector Raster Geographic Information Synthesis }
{ VOICE .. Tracer }
{ GRIP ICE .. Tongs }
{ Digital Terrain Mapping }
{ Image Locatable Holographics }
{ SOS MAP }
{ Surreal Object Synthesis Multimedia Analysis Product }
{ Fractal3D Life MOW }
{ Copyright (c) 1995,2006 Ivan Lee Herring }
{ }
{*******************************************************}
unit fUMathA;
interface
uses
Windows, Messages, SysUtils, Dialogs, Forms,
Math, Graphics, Classes;
procedure Lorenz;
procedure Strange; {Vortex}
procedure Duffing;
procedure Rossler;
procedure Kaneko1
(KanA {01.3}, KanD {0.1}, KanStep {0.01}: Extended;
DisKan {30}, KanTeen {3000}: Integer);
procedure Kaneko2
(KanA {0.3}, KanD {1.75}, KanStep {0.02}: Extended;
DisKan {36}, KanTeen {3000}: Integer);
procedure Henon2(Target, KamStep {1.2;}: Extended; Incoming {26}:
Integer);
{Procedure Henon2;}{Limits 333 Henons Henon Range 1 Henon >>>>}
procedure Henon_Attractor;
procedure LimitCycles(Which: Integer);
{Procedure Rayleigh;Procedure VanderPol;Procedure Brusselator;}
procedure SetChemical;
procedure StrangeChemicalsa;
procedure StrangeChemicalsb;
procedure StrangeChemicalsc;
procedure StrangeChemicalsd;
procedure StrangeChemicalse;
procedure StrangeChemicalsf;
procedure StrangeChemicalsg;
implementation
uses fUGlobal,fMain, fGMath {from AVGAFRAK B_Strang};
procedure Lorenz;
const rad_per_degree = 0.0174533;
third = 0.333333333;
var
elapse, x, y, z, d0_x, d0_y, d0_z, d1_x, d1_y, d1_z, d2_x, d2_y,
d2_z,
d3_x, d3_y, d3_z, xt, yt, zt, dt, dt2, x_angle, y_angle, z_angle,
sx, sy, sz, cx, cy, cz, temp_x, temp_y, old_y: Extended;
SCol: string;
ICol, HalfX, HalfY, maxcolx, maxrowy,
dummy, i, j, row, Scolor, col, old_row, old_col: integer;
ch: char; TempColor: TColor;
Q: array[0..2305] of Extended;
Bitmap: TBitmap;
PixelLine: PByteArray;
function radians_to_degrees(degrees: Extended): Extended;
begin
while degrees >= 360 do
degrees := degrees - 360;
while degrees < 0 do
degrees := degrees + 360;
radians_to_degrees := rad_per_degree * degrees;
end;
begin
{MainForm.Show;}
FractalFilename := 'A_LORENZ000.BMP';
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
HalfX := (FYImageX div 2);
HalfY := (FYImageY div 2);
col := 0;
ICol := 0;
row := 0;
old_col := 0;
old_row := 0;
Scolor := 1;
x_angle := 45;
y_angle := 0;
z_angle := 90;
x_angle := radians_to_degrees(x_angle);
sx := sin(x_angle);
cx := cos(x_angle);
y_angle := radians_to_degrees(y_angle);
sy := sin(y_angle);
cy := cos(y_angle);
z_angle := radians_to_degrees(z_angle);
sz := sin(z_angle);
cz := cos(z_angle);
for j := 0 to 2 do begin
MainForm.DoImageStart;
with MainForm.Image2.Canvas do begin
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
{ (Left, Top, Right, Bottom: Integer);}
{FillRect(Rect(0,0,FYImageX,FYImageY));}
{TempColor:=RGB(Colors[0,1 ],
Colors[1,1 ],
Colors[2,1 ]);}
TempColor := RGB(255 - GetRValue(FBackGroundColor),
255 - GetGValue(FBackGroundColor),
255 - GetBValue(FBackGroundColor));
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(10, 10, 'Lorenz');
if j = 0 then TextOut(10, 30, 'Z Y View')
else if j = 1 then TextOut(10, 30, 'X Y View')
else TextOut(10, 30, 'Z X Y View');
x := 0;
y := 1;
z := 0;
if j = 0 then begin
old_col := Round(y * 9 + 460);
old_row := Round(480 - 6.56 * z);
Moveto(0, 478); Lineto(639, 478);
{Line(0,478,639,478);}
Moveto(320, 2); Lineto(320, 478);
{Line(320,2,320,478); }
TextOut(628, 460, 'Y');
TextOut(330, 12, 'Z');
end;
if j = 1 then
begin
old_col := Round(y * 10 + 320);
old_row := Round(240 - 7.29 * x);
Moveto(0, 240); Lineto(639, 240);
{Line(0,240,639,240);}
Moveto(320, 2); Lineto(320, 478);
{Line(320,2,320,478);}
TextOut(628, 225, 'Y');
TextOut(330, 12, 'X');
end;
if j = 2 then
begin
old_col := Round(y * 9);
old_row := Round(480 - 6.56 * z);
Moveto(0, 478); Lineto(638, 478);
{Line(0,478,638,478);}
Moveto(320, 2); Lineto(320, 478);
{Line(320,2,320,478);}
Moveto(320, 478); Lineto(648, 170);
{Line(320,478,648,170);}
TextOut(628, 460, 'Y');
TextOut(330, 12, 'Z');
TextOut(628, 162, 'X');
end;
{ SetLineStyle(0,$FFFF,1);}
Moveto(old_col, old_row);
dt := 0.01;
dt2 := dt / 2;
for i := 0 to 8000 do
begin
d0_x := 10 * (y - x) * dt2;
d0_y := (-x * z + 28 * x - y) * dt2;
d0_z := (x * y - 8 * z / 3) * dt2;
xt := x + d0_x;
yt := y + d0_y;
zt := z + d0_z;
d1_x := (10 * (yt - xt)) * dt2;
d1_y := (-xt * zt + 28 * xt - yt) * dt2;
d1_z := (xt * yt - 8 * zt / 3) * dt2;
xt := x + d1_x;
yt := y + d1_y;
zt := z + d1_z;
d2_x := (10 * (yt - xt)) * dt;
d2_y := (-xt * zt + 28 * xt - yt) * dt;
d2_z := (xt * yt - 8 * zt / 3) * dt;
xt := x + d2_x;
yt := y + d2_y;
zt := z + d2_z;
d3_x := (10 * (yt - xt)) * dt2;
d3_y := (-xt * zt + 28 * xt - yt) * dt2;
d3_z := (xt * yt - 8 * zt / 3) * dt2;
old_y := y;
x := x + (d0_x + d1_x + d1_x + d2_x + d3_x) * third;
y := y + (d0_y + d1_y + d1_y + d2_y + d3_y) * third;
z := z + (d0_z + d1_z + d1_z + d2_z + d3_z) * third;
if j = 0 then
begin
col := Round(y * 15 + HalfY); {y* 9 to 15}
row := Round(FYImageX - 11 * z); {6.56 to 11}
if col < HalfX then
if old_col >= HalfX then
inc(Scolor);
if col > HalfX then
if old_col <= HalfX then
inc(Scolor);
end;
if j = 1 then
begin
col := Round(y * 13.0 + HalfX); {10.0 to 13.0}
row := Round(HalfY - 10.29 * x); {7.29 to 10.29}
if col < HalfX then
if old_col >= HalfX then
inc(Scolor);
if col > HalfX then
if old_col <= HalfX then
inc(Scolor);
end;
if j = 2 then
begin
temp_x := x * cx + y * cy + z * cz;
temp_y := x * sx + y * sy + z * sz;
col := Round(temp_x * 12 + HalfX); {x*8 to x*12}
row := Round(FYImageY - temp_y * 7.5); {y*5 to y*7.5}
if col < HalfX then
if old_col >= HalfX then
inc(Scolor);
if col > HalfX then
if old_col <= HalfX then
inc(Scolor);
end;
{Only change color when it has been changed}
if (Scolor > ICol) then begin
ICol := Scolor;
TempColor := RGB(Colors[0, (Scolor div 255)],
Colors[1, (Scolor div 255)],
Colors[2, (Scolor div 255)]);
Pen.Color := TempColor;
Application.ProcessMessages;
end;
{ Line(old_col,old_row,col,row);}
Moveto(old_col, old_row); Lineto(col, row);
old_row := row;
old_col := col;
{If Slowdown then Application.ProcessMessages; }
end; {of 8000}
if (J < 2) then begin
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages
until (bRotateImage = True);
Mainform.DoImageDone;
end;
end;
end;
end; { of UNIT SLorenz.PAS }
procedure Strange;
var
Xmax, Xmin, Ymax, Ymin, X, Y, Z, deltaX, deltaY,
Xtemp, Ytemp, {Ztemp,} a, b, c, d, e: Extended;
{SCol:String;} Scolor: TColor;
{ Finder,} max_col, col, max_row, row, j: integer;
max_iterations, i: longint;
begin
MainForm.Show;
FractalFilename := 'A_VORTEX000.BMP';
{ const
max_col = 480; 639;
max_row = 360; 479;}
max_col := (FYImageX - 1);
max_row := (FYImageY - 1);
max_iterations := 50000;
Xmax := 2.8;
Xmin := -2.8;
Ymax := 2.0;
Ymin := -2.0;
a := 2.24;
b := 0.43;
c := -0.65;
d := -2.43;
e := 1.0;
X := 0;
Y := 0;
Z := 0;
deltaX := max_col / (Xmax - Xmin);
deltaY := max_row / (Ymax - Ymin);
for j := 0 to 1 do begin
MainForm.DoImageStart;
with MainForm.Image2.Canvas do begin
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
{ (Left, Top, Right, Bottom: Integer);}
FillRect(Rect(0, 0, FYImageX, FYImageY));
Pen.Color := clRed;
TextOut(10, 10, 'Vortex');
if j = 0 then TextOut(10, 30, 'Vertical')
else TextOut(10, 30, 'Horizontal');
Application.ProcessMessages;
for i := 0 to max_iterations do
begin
{If Slowdown then Application.ProcessMessages; }
Xtemp := sin(a * Y) - Z * cos(b * X);
Ytemp := Z * sin(c * X) - cos(d * Y);
Z := e * sin(X);
X := Xtemp;
Y := Ytemp;
if j = 0 then
begin
col := Round((X - Xmin) * deltaX);
row := Round((Y - Ymin) * deltaY);
end
else
begin
col := Round((Y - Xmin) * deltaX);
row := Round((Z - Ymin) * deltaY);
end;
if col > 0 then
if col <= max_col then
if row > 0 then
if row <= max_row then
begin
Scolor := Pixels[col, row];
if Scolor >= 0 then begin
{If (SColor= FBackGroundColor)and (clBlack <> FBackGroundColor) then
Scolor := clBlack else Scolor := clBlue;}
if (SColor = clBlack) then Scolor := clBlue else
if (SColor = clBlue) then
Scolor := clFuchsia else
if (SColor = clFuchsia) then
Scolor := clGreen else
if (SColor = clGreen) then
Scolor := clMaroon else
if (SColor = clMaroon) then
Scolor := clOlive else
if (SColor = clOlive) then
Scolor := clNavy else
if (SColor = clNavy) then
Scolor := clPurple else
if (SColor = clPurple) then
Scolor := clRed else
if (SColor = clRed) then
Scolor := clLime else
if (SColor = clLime) then
Scolor := clAqua else
if (SColor = clAqua) then
Scolor := clYellow else
Scolor := clWhite;
end;
Pixels[col, row] := Scolor;
end;
end;
if j = 0 then begin
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages
until (bRotateImage = True);
Mainform.DoImageDone;
end;
end;
end;
end; { of procedure Strange }
(*************************************************************)
(*****************************************************************)
procedure Duffing;
var
s: string[10];
A, B, C, F,
D1, D2, D3,
D, MinU, MaxU, U2, V2, X, Y, Z, U, V: Extended;
IKan, NPts, XSize, YSize, Limit, i, j, Steps: integer;
XPos, YPos: integer;
XPosT, YPosT: Longint;
Xmin, YMin, XStep, YStep, XMax, YMax: Extended;
TT, T, Q: integer;
DL1A, DL1B, DL1, Dl2, Dl3, Dl, Dr,
Step, Ua1, Ua2, Va1, Va2, YTL, YTM, YTR, TM, TL, TR, BL, BR:
Extended;
TempColor: TColor;
begin
FractalFilename := 'A_DUFFNG000.BMP';
XSize := FYImageX - 1; { physical screen size }
YSize := FYImageY - 1; { physical screen size }
with MainForm.Image2.Canvas do begin
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, FYImageX, FYImageY));
TempColor := RGB(255 - GetRValue(FBackGroundColor),
255 - GetGValue(FBackGroundColor),
255 - GetBValue(FBackGroundColor));
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(10, 10, 'Duffing' {s});
MainForm.Show;
XMax := 4.0; {3.56}
XMin := -8.0; {-3.70}
YMax := 6.0; {6.76 3.61}
YMin := -10.0; {-5.14 -3.02}
XStep := (XMax - XMin) / XSize;
YStep := (YMax - YMin) / YSize;
Step := 0.1 / 25;
X := -1.0;
Y := 1.0;
A := 1.0; {-0.50; }
B := 0.3; {0.2;}
C := 0.0; {1.0;}
F := 10.0; {1.60;}
Z := 1.0;
MinU := -1E+5;
MaxU := 1E+5;
for T := 0 to 255 do begin
TempColor := RGB(Colors[0, T],
Colors[1, T],
Colors[2, T]);
for TT := 1 to 250 do
begin
D1 := Y;
DL1A := (A * X);
DL1B := (X * X);
{If DL1A < MinU then DL1A := MinU else
If DL1A > MaxU then DL1A := MaxU;
If DL1B < MinU then DL1B := MinU else
If DL1B > MaxU then DL1B := MaxU;}
DL1 := DL1A * DL1B;
DL2 := (C * X);
DL3 := (B * Y);
DL := -(DL1 + DL2 + DL3);
{If DL < MinU then DL := MinU else
If DL > MaxU then DL := MaxU;}
DR := F * COS(Z);
D2 := DL + DR;
D3 := 1;
X := ((X + D1 * Step));
Y := ((Y + D2 * Step));
Z := ((Z + D3 * Step)); {320 240 }
XPosT := (XSize div 2) + round((x / XStep));
YPosT := (YSize div 2) - round((y / YStep));
{ If XPosT > 639 then XposT := 639;
If XPosT < 1 then XposT := 1;
If YPosT > 479 then YposT := 479;
If YPosT < 1 then YposT := 1;
XPos := XPosT;
YPos := YPosT;}
{ PutPixel( XPosT, YPosT, Round(Z) );
TempColor :=(T Div 500) +10 ;}
Pixels[XPosT, YPosT] := TempColor;
end; { of For T NEXT T}
end; { of For TT NEXT TT}
end; end; { of Duffing }
(*************************************************************)
(*************************************************************)
procedure Rossler;
var
{s : string[10];}
{MinU, MaxU, U2,U, V2,} X, Y, Z: Extended;
XSize, YSize: integer; { XPos, YPos : integer;}
XPosT, YPosT: Longint;
{ZMax,ZMin, } Xmin, YMin, XStep, YStep, XMax, YMax: Extended;
TT, {Colored,,Q} T: integer;
{Ua1, Ua2, Va1, Va2, YTL, YTM, YTR,
TM, TL,TR,BL,BR : Extended;}
Step, A, B, C, D1, D2, D3, D, N: Extended;
TempColor: TColor;
begin
FractalFilename := 'A_ROSSLR000.BMP';
XSize := FYImageX - 1; { physical screen size }
YSize := FYImageY - 1; { physical screen size }
with MainForm.Image2.Canvas do begin
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, FYImageX, FYImageY));
TempColor := RGB(255 - GetRValue(FBackGroundColor),
255 - GetGValue(FBackGroundColor),
255 - GetBValue(FBackGroundColor));
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(10, 10, 'Rossler');
MainForm.Show;
MainForm.HiddenFX.Caption := 'FX';
XMax := 10.0; {11.53}
XMin := -14.0; {-7.07}
YMax := 10.0; {7.85}
YMin := -22.0; {-9}
{ZMax := 24; }{23.95}
{ZMin := 3.0; }{2.41}
XStep := (XMax - XMin) / XSize;
YStep := (YMax - YMin) / YSize;
A := 0.2;
B := 0.2;
C := 5.7;
X := 1;
Y := 1;
Z := 1;
{T1 = Start, T2 = End time; D = Delta T (increment time amount }
{ N = number of silent computations }
D := 0.04;
N := 10.0;
{D := D + D;
Step := Step + Step;}
Step := D / N;
for T := 0 to 2000 do begin
TempColor := RGB(Colors[0, (T div 255)],
Colors[1, (T div 255)],
Colors[2, (T div 255)]);
for TT := 1 to 25 do
begin
D1 := -Y - Z;
D2 := X + (Y * A);
D3 := B + (Z * (X - C));
X := X + D1 * Step;
Y := Y + D2 * Step;
Z := Z + D3 * Step;
{ If X > 01.210 then X := 01.210;
If X < -0.750 then X := -0.750;
If Y > 01.210 then Y := 01.210;
If Y < -0.750 then Y := -0.750;}
end; { of For T NEXT T} {320 240 }
XPosT := (XSize div 2) + round((x / XStep));
YPosT := (YSize div 2) - round((y / YStep));
{ If XPosT > 639 then XposT := 639;
If XPosT < 1 then XposT := 1;
If YPosT > 479 then YposT := 479;
If YPosT < 1 then YposT := 1;
XPos := XPosT;
YPos := YPosT;}
{ PutPixel( XPosT, YPosT, Round(Z)+12 );}
{ Pixels[ XPosT, YPosT]:= (T div 500)+10 ;}
Pixels[XPosT, YPosT] := TempColor;
end; { of For TT NEXT TT}
end; end; { of Rossler }
(*************************************************************)
(*************************************************************)
(*****************************************************************)
procedure Kaneko1
(KanA {01.3}, KanD {0.1}, KanStep {0.01}: Extended;
DisKan {30}, KanTeen {3000}: Integer);
var TempColor: TColor;
s: string[10];
A, D, MinU, MaxU, {U2, V2, U, V, } X, Y: Extended;
IKan, XSize, YSize, HalfY, HalfX, Steps: integer;
T, Q: integer; XPos, YPos: integer;
XPosT, YPosT: Longint;
{Xmin, YMin,, XMax, YMax} XStep, YStep: Extended;
Ua1, Ua2, Va1, Va2, YTL, YTM, {YTR, } TM, TL {TR,,BR}: Extended;
(*************************************************************)
begin { MAIN PROGRAM BLOCK }
MainForm.Show;
FractalFilename := 'A_KANEKO000.BMP';
MainForm.HiddenFX.Caption := 'Click image to do next view';
HalfX := (FYImageX div 2);
HalfY := (FYImageY div 2);
XSize := FYImageX - 1; { physical screen size }
YSize := FYImageY - 1; { physical screen size }
XStep := { ( XMax - XMin )} 2.2 / XSize;
YStep := {( YMax - YMin )} 2.2 / YSize;
A := KanA {01.3};
D := KanD {0.1}; {1.3 .. 1.55}
for IKan := 1 to DisKan {30} do { range is ... 1.2 to 1.7 }
begin {Cleardevice;}
MainForm.DoImageStart;
with MainForm.Image2.Canvas do begin
{Brush.Color:=FBackGroundColor;
Brush.Style:=bsSolid;
FillRect(Rect(0,0,FYImageX,FYImageY));}
TempColor := RGB(255 - GetRValue(FBackGroundColor),
255 - GetGValue(FBackGroundColor),
255 - GetBValue(FBackGroundColor));
Pen.Color := TempColor;
Font.Color := TempColor;
Str(A: 8: 4, s);
TextOut(10, 10, s);
begin
{q:= 1;}
Ua1 := 0.1;
Va1 := 0.15;
{MinU := -1E+20;MaxU := 1E+20;}
MinU := -1E+7;
MaxU := 1E+7;
for T := 1 to KanTeen {3000} do
begin
TL := (1 - A * Ua1 * Ua1);
TM := (D * (Va1 - Ua1));
if TL < MinU then TL := MinU;
if TL > MaxU then TL := MaxU;
Ua2 := (TL + TM); { cycle }
YTL := (1 - A * Va1 * Va1);
YTM := (D * (Ua1 - Va1));
if YTL < MinU then YTL := MinU;
if YTL > MaxU then YTL := MaxU;
Va2 := (YTL + YTM); {cycle }
{Q := Q + 1;}
X := Ua1;
Y := Va1;
Ua1 := Ua2;
Va1 := Va2;
if X > 01.210 then X := 01.210;
if X < -0.750 then X := -0.750;
if Y > 01.210 then Y := 01.210;
if Y < -0.750 then Y := -0.750;
{320 240 }
XPosT := HalfY + round((x / XStep));
YPosT := HalfX - round((y / YStep));
{ Steps := ((Q DIV 300)+2);}
if XPosT > XSize then XposT := XSize;
if XPosT < 1 then XposT := 1;
if YPosT > YSize then YposT := YSize;
if YPosT < 1 then YposT := 1;
XPos := XPosT;
YPos := YPosT;
{ Pixels[ XPos, YPos]:= Steps;}
{TempColor:=Colors[0,(T mod 255)]; }
TempColor := RGB(Colors[0, (T mod 255)],
Colors[1, (T mod 255)],
Colors[2, (T mod 255)]);
Pixels[XPos, YPos] := TempColor;
end; { of For T NEXT T}
end; { of procedure Computit }
A := A + KanStep {0.01}; {1/(I+3); } {0.01;}
{A := A + 1/(IKan + 1); }
end;
if IKan < 30 then begin
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until
(bRotateImage = True);
Mainform.DoImageDone;
end;
end;
MainForm.HiddenFX.Caption := 'FX';
end; { of Kaneko1 }
(*************************************************************)
(*************************************************************)
(*************************************************************)
(*************************************************************)
procedure Kaneko2(KanA {0.3}, KanD {1.75}, KanStep {0.02}: Extended;
DisKan {36}, KanTeen {3000}: Integer);
var
s: string[8];
HalfX, HalfY, IK2, XSize, YSize {Limit,} { i,} {j,}: integer;
D, MinU, MaxU, {U2,} {V2,} X, Y, { U, V,} A: Extended;
{, XMax, YMax Xmin, YMin,} XStep, YStep: Extended;
TempColor: TColor;
T, {Q, } XPos, YPos: integer;
XPosT, YPosT: Longint;
TM, TL, TR, Ua1, Ua2, Va1, Va2: Extended;
(*************************************************************)
begin { MAIN PROGRAM BLOCK }
{MainForm.Show;}
FractalFilename := 'A_KANEK2000.BMP';
MainForm.HiddenFX.Caption := 'Click image to do next view';
XSize := FYImageX - 1; { physical screen size }
YSize := FYImageY - 1;
HalfX := (FYImageX div 2);
HalfY := (FYImageY div 2); { physical screen size }
XStep := { ( XMax - XMin )} 1.60 / XSize;
YStep := {( YMax - YMin )} 1.60 / YSize;
A := KanA;
D := KanD; {1.75 .. 2.16}
for IK2 := 1 to DisKan do { range is ... 1.2 to 1.7 }
begin {Cleardevice;}
MainForm.DoImageStart;
with MainForm.Image2.Canvas do begin
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, FYImageX, FYImageY));
TempColor := RGB(255 - GetRValue(FBackGroundColor),
255 - GetGValue(FBackGroundColor),
255 - GetBValue(FBackGroundColor));
Pen.Color := TempColor;
Font.Color := TempColor;
Str(D: 6: 3, s);
TextOut(10, 10, s);
begin
Ua1 := 0.1;
Va1 := 0.15;
MinU := -1E+5;
MaxU := 1E+5;
for T := 1 to KanTeen do begin
if Va1 < MinU then Va1 := MinU else
if Va1 > MaxU then Va1 := MaxU;
TL := A * Ua1 + (1 - A);
TM := Va1 * Va1;
TR := (1 - D * TM);
if TR < MinU then TR := MinU;
if TR > MaxU then TR := MaxU;
Ua2 := TL * TR;
Va2 := Ua1;
X := Ua1;
Y := Va1;
Va1 := Va2;
Ua1 := Ua2;
if X > 01.350 then X := 01.350;
if X < -0.750 then X := -0.750;
if Y > 01.350 then Y := 01.350;
if Y < -0.750 then Y := -0.750;
{320 240 }
XPosT := HalfY + round(x / XStep);
YPosT := HalfX - round(y / YStep);
{ Steps := ((T DIV 300)+2);}
if XPosT > XSize then XposT := XSize;
if XPosT < 1 then XposT := 1;
if YPosT > YSize then YposT := YSize;
if YPosT < 1 then YposT := 1;
XPos := XPosT;
YPos := YPosT;
{ Pixels[ XPos, YPos]:= Steps;}
TempColor := RGB(Colors[0, (T mod 255)],
Colors[1, (T mod 255)],
Colors[2, (T mod 255)]);
Pixels[XPos, YPos] := TempColor;
end; { of For T NEXT T}
end; { of procedure }
D := D + KanStep; {1/(I+3); } {0.01;} {A := A + 1/(IK2+1); }
end;
if IK2 < 36 then begin
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages
until (bRotateImage = True);
Mainform.DoImageDone;
end;
end;
MainForm.HiddenFX.Caption := 'FX';
end; { of Procedure Kaneko2 }
(*************************************************************)
(*************************************************************)
(*************************************************************)
procedure Henon2(Target, KamStep {1.2;}: Extended; Incoming {26}:
Integer);
type
A4000R = array[1..2002] of Extended;
A251R = array[1..251] of Extended;
var TempColor: TColor;
Henons, s: string;
{ Xa, Ya : A4000R;}
{ deleted as an array is not needed -> putpixel a dot as calculated}
Ua, Va: A251R;
MinU, MaxU, U2, V2, X, Y, U, V, A: Extended;
NPts, HalfX, HalfY: Integer;
IC, XSize, YSize, Limit, I, I2, j, Steps: integer;
XPos, YPos: integer;
XPosT, YPosT: Longint;
Xmin, YMin, XStep, YStep, XOrg, YOrg,
XMax, YMax, XIter, YIter: Extended;
Done: boolean;
T, Q: integer;
TL, TR, BL, BR,
UV_Temp, U_Temp, S_Temp, C_Temp, Orbit: Extended;
begin { MAIN PROcedure BLOCK }
{MainForm.Show;}
FractalFilename := 'A_HENON_000.BMP';
MainForm.HiddenFX.Caption := 'Click image to do next view';
Henons := 'Henon 2';
XSize := FYImageX - 1; { physical screen size }
YSize := FYImageY - 1; { physical screen size }
HalfX := (FYImageX div 2);
HalfY := (FYImageY div 2);
{ XOrg := -2.0; XMax := 0.5;
YOrg := -1.25; YMax := 1.25;}
XMin := -2.10;
XMax := 1.10;
YMin := -1.20;
YMax := 1.20;
XStep := (XMax - XMin) / XSize;
YStep := (YMax - YMin) / YSize;
A := Target; {1.2;} { range is ... 1.2 to 1.7 }
for I := 1 to Incoming {26} do begin begin
MainForm.DoImageStart;
q := 1;
Orbit := 0.1;
MaxU := 1E+5;
MinU := -1E+5;
with MainForm.Image2.Canvas do begin
{Brush.Color:=FBackGroundColor;
Brush.Style:=bsSolid;
FillRect(Rect(0,0,FYImageX,FYImageY));}
TempColor := RGB(255 - GetRValue(FBackGroundColor),
255 - GetGValue(FBackGroundColor),
255 - GetBValue(FBackGroundColor));
Pen.Color := TempColor;
Font.Color := TempColor;
{TextOut(10,10,Henons);}
Str(A: 7: 5, s);
TextOut(10, 10, 'Henon: ' + s);
{Str(Orbit:7:5,s);
TextOut(10,30,'Orbit: '+s);}
A := A + KamStep; { 0.02;} {A := A + 1/(I+1); }
{ other way of incrementing input }
{FOR Orbit = .1 TO 1.6 STEP .1}
for I2 := 1 to 24 {16} do begin
Ua[1] := Orbit / 3.0;
Va[1] := Ua[1];
Orbit := Orbit + 0.1; { TO 1.6 STEP .1}
TempColor := RGB(Colors[0, (I2 mod 255)],
Colors[1, (I2 mod 255)],
Colors[2, (I2 mod 255)]);
for T := 1 to 250 do begin
if Ua[T] < MinU then Ua[T] := MinU;
if Ua[T] > MaxU then Ua[T] := MaxU;
UV_Temp := Ua[T] * Ua[T];
U_Temp := (Va[t] - UV_Temp);
S_Temp := SIN(A);
C_Temp := COS(A);
TL := Ua[t] * C_Temp;
TR := U_Temp * S_Temp;
BL := Ua[t] * S_Temp;
BR := U_Temp * C_Temp;
Ua[T + 1] := TL - TR;
Va[T + 1] := BL + BR;
{Q := Q + 1;}
X := Ua[t];
Y := Va[t];
if X > 2.0 then X := 2.0;
if X < -2.0 then X := -2.0;
if Y > 2.0 then Y := 2.0;
if Y < -2.0 then Y := -2.0;
XPosT := HalfX + round(x / XStep);
YPosT := HalfY - round(y / YStep);
{ Steps := Round(Q/250);}
if XPosT > XSize then XposT := XSize;
if XPosT < 1 then XposT := 1;
if YPosT > YSize then YposT := YSize;
if YPosT < 1 then YposT := 1;
XPos := XPosT;
YPos := YPosT;
{If I = 16 then IC := 11
Else IC := I;
IC := I;}
Pixels[XPos, YPos] := TempColor; {IC Steps ;}
end; { of For T NEXT T}
end; end; { of FOR I NEXT Orbit}
{?? how If ((I<Incoming)and (I2 < 36) then} begin
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages
until (bRotateImage = True);
Mainform.DoImageDone;
end;
end;
end; { of procedure }
MainForm.HiddenFX.Caption := 'HiddenFX';
Application.ProcessMessages;
end; { Procedure HENON2 }
(*************************************************************)
{=======================}
{ HENON.PAS }
{=======================}
procedure Henon_Attractor;
var
{MaxColors, } MaxX, MaxY, XScale, YScale, XOff, YOff: integer;
i, Color, XPos, YPos: integer; TempColor: TColor;
{ Xmax, Ymax,} Xold, Xnew, Yold, Ynew, Xmin, Ymin: Extended;
begin
{ Henon Attractor }
{ x := y + 1 - ( 1.4 * x * x ) }
{ y := 0.3 * x }
XScale := 1; { values to adjust scale }
YScale := 1;
XOff := 0; { and screen position }
YOff := 0;
Xmin := 0; Ymin := 0; Xold := 0; Yold := 0;
{ Xmax := 0;Ymax := 0; Xnew := 0; Ynew := 0;}
with MainForm.Image2.Canvas do begin
MaxX := (FYImageX - 1);
MaxY := (FYImageY - 1);
{ Brush.Color:=FBackGroundColor;
Brush.Style:=bsSolid;
FillRect(Rect(0,0,FYImageX,FYImageY));}
TempColor := RGB(255 - GetRValue(FBackGroundColor),
255 - GetGValue(FBackGroundColor),
255 - GetBValue(FBackGroundColor));
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(10, 10, 'Henon Attractor');
TextOut(10, 30, 'XScale = ' + I2S(XScale));
TextOut(10, 50, 'YScale = ' + I2S(YScale));
TextOut(10, 70, 'XOff = ' + I2S(XOff));
TextOut(10, 90, 'YOff = ' + I2S(YOff));
{ MainForm.Show; }
MainForm.HiddenFX.Caption := 'HiddenFX Henon Attractor';
Application.ProcessMessages;
for Color := 0 to 15 do begin
MainForm.HiddenFX.Caption := 'HiddenFX Henon Attractor';
Application.ProcessMessages;
TempColor := RGB(RGBArray[0, (Color)],
RGBArray[1, (Color)],
RGBArray[2, (Color)]);
for i := 1 to 1000 do { $7FFF } begin
Xnew := Yold + 1 - (1.4 * Xold * Xold);
Ynew := 0.3 * Xold;
XPos := trunc((XNew * MaxX / 3 * XScale) + MaxX / 2 + XOff);
YPos := trunc((YNew * MaxY * YScale) + MaxY / 2 + YOff);
if (XPos > Xmin) and (XPos < MaxX) and
(YPos > Ymin) and (YPos < MaxY) then
begin Pixels[XPos, YPos] := TempColor; end;
Yold := Ynew;
Xold := Xnew;
end;
end;
end;
MainForm.HiddenFX.Caption := 'HiddenFX';
Application.ProcessMessages;
end; { of procedure Henon_Attractor; }
(*************************************************************)
(*****************************************************************)
{Rayleigh;VanderPol;Brusselator;}
procedure LimitCycles(Which: Integer);
var TempColor: TColor;
TT, T, XSize, YSize { XPos, YPos,}
{NPts,Limit, i, j, Steps}: integer;
XPosT, YPosT: Longint;
{Xmin, YMin,XMax, YMax,}
F, D1, D2, D3, X, Y, Z, {TL,TR,BL,BR,} XStep, YStep,
DL1A, DL1B, DL1, Dl2, Dl3, Dl, Dr, A, B, Step: Extended;
{Ua1, Ua2, Va1, Va2, YTL, YTM, YTR, TM,}
{C, D, MinU, MaxU, U2, V2, U, V}
begin
FractalFilename := 'A_LIMIT_000.BMP';
XSize := (FYImageX div 2); { physical screen size }
YSize := (FYImageY div 2); { physical screen size }
with MainForm.Image2.Canvas do begin
{Brush.Color:=FBackGroundColor;
Brush.Style:=bsSolid;
FillRect(Rect(0,0,FYImageX,FYImageY));}
TempColor := RGB(255 - GetRValue(FBackGroundColor),
255 - GetGValue(FBackGroundColor),
255 - GetBValue(FBackGroundColor));
Pen.Color := TempColor;
Font.Color := TempColor;
{MainForm.Show;}
{XMax := 2.67;
XMin := -5.33;
YMax := 4.0;
YMin := -6.67;}
if ((Which = 0) or (Which = 3)) then begin
TextOut(10, 50, 'Rayleigh' {s});
XStep := (12.8 { XMax - XMin}) / XSize;
YStep := (9.6 {YMax - YMin}) / YSize;
Step := 0.1 / 25;
X := 0; {-1.0;}
Y := 0; {1.0;}
F := 1.0; {1.60;}
Z := 1.0; {MinU := -1E+5;MaxU := 1E+5;}
for T := 1 to 255 do begin
MainForm.HiddenFX.Caption := 'HiddenFX Rayleigh';
Application.ProcessMessages;
TempColor := RGB(Colors[0, T],
Colors[1, T],
Colors[2, T]);
for TT := 1 to 250 do
begin
D1 := Y;
DL1A := (Y * Y * Y);
DL1B := (Y - DL1A / 3);
{If DL1A < MinU then DL1A := MinU else
If DL1A > MaxU then DL1A := MaxU;
If DL1B < MinU then DL1B := MinU else
If DL1B > MaxU then DL1B := MaxU;}
DL := DL1B - X;
{If DL < MinU then DL := MinU else
If DL > MaxU then DL := MaxU;}
DR := F * COS(Z);
D2 := DL + DR;
D3 := 1;
X := ((X + D1 * Step));
Y := ((Y + D2 * Step));
Z := ((Z + D3 * Step)); {320 240 }
XPosT := XSize + round((x / XStep));
YPosT := YSize - round((y / YStep));
{ If XPosT > 639 then XposT := 639;
If XPosT < 1 then XposT := 1;
If YPosT > 479 then YposT := 479;
If YPosT < 1 then YposT := 1;
XPos := XPosT;
YPos := YPosT;}
{ PutPixel( XPosT, YPosT, Round(Z) );}
Pixels[XPosT, YPosT] := TempColor; {( (T Div 200) + 10 );}
end; { of For T NEXT T}
end; { of For TT NEXT TT}
end; { of Rayleigh }
(*************************************************************)
(*****************************************************************)
if ((Which = 1) or (Which = 3)) then begin
TextOut(10, 30, 'Van der Pol Oscillator' {s});
{XMax := 2.67;
XMin := -5.33;
YMax := 4.0;
YMin := -6.67;}
XStep := (12.8 { XMax - XMin}) / XSize;
YStep := (9.6 { YMax - YMin}) / YSize;
Step := 0.1 / 25;
X := 0;
Y := 0;
{A := 1.0;}{-0.50; }
B := 1.0; {0.2;}
{C := 1.0; }{1.0;}
F := 0.55; {1.60;}
Z := 1.0;
{MinU := -1E+5;MaxU := 1E+5;}
for T := 1 to 255 do begin
MainForm.HiddenFX.Caption :=
'HiddenFX Van der Pol Oscillator';
Application.ProcessMessages;
TempColor := RGB(Colors[0, T],
Colors[1, T],
Colors[2, T]);
for TT := 1 to 250 do
begin
D1 := Y;
DL1A := (3 * B);
DL1B := (X * X);
{If DL1A < MinU then DL1A := MinU else
If DL1A > MaxU then DL1A := MaxU;
If DL1B < MinU then DL1B := MinU else
If DL1B > MaxU then DL1B := MaxU;}
DL1 := (DL1A * DL1B - 1);
DL2 := (DL1 * Y);
DL3 := (X + DL2);
DL := (-1.0 * DL3);
{If DL < MinU then DL := MinU else
If DL > MaxU then DL := MaxU;}
DR := F * SIN(1);
D2 := DL + DR;
D3 := 1;
X := ((X + D1 * Step));
Y := ((Y + D2 * Step));
Z := ((Z + D3 * Step)); {320 240 }
XPosT := XSize + round((x / XStep));
YPosT := YSize - round((y / YStep));
{ If XPosT > 639 then XposT := 639;
If XPosT < 1 then XposT := 1;
If YPosT > 479 then YposT := 479;
If YPosT < 1 then YposT := 1;
XPos := XPosT;
YPos := YPosT;}
{ PutPixel( XPosT, YPosT, Round(Z) );}
Pixels[XPosT, YPosT] := TempColor; {( (T Div 200) + 9 );}
end; { of For T NEXT T}
end; { of For TT NEXT TT}
end; { of VanderPol }
(*************************************************************)
(*****************************************************************)
{procedure Brusselator;}
if ((Which = 2) or (Which = 3)) then begin
TextOut(10, 10, 'Brusselator' {s});
{XMax := 2.67;
XMin := -5.33;
YMax := 4.0;
YMin := -6.67;}
XStep := (12.8 {6.4} { XMax - XMin}) / XSize;
YStep := (9.6 {4.8} { YMax - YMin}) / YSize;
Step := 0.1 / 25;
X := 0;
Y := 0;
A := 1.0; {-0.50; }
B := 3.0; {0.2;}
{MinU := -1E+5;MaxU := 1E+5;}
for T := 1 to 255 do begin
MainForm.HiddenFX.Caption := 'HiddenFX Brusselator';
Application.ProcessMessages;
TempColor := RGB(Colors[0, T],
Colors[1, T],
Colors[2, T]);
for TT := 1 to 250 do
begin
D1 := (X * X * Y);
DL1A := (A * (B + 1));
DL1B := 1 - DL1A * X;
{If DL1A < MinU then DL1A := MinU else
If DL1A > MaxU then DL1A := MaxU;
If DL1B < MinU then DL1B := MinU else
If DL1B > MaxU then DL1B := MaxU;}
D2 := DL1B + D1;
D3 := 3 * X - D1;
X := ((X + D2 * Step));
Y := ((Y + D3 * Step)); {320 240 }
XPosT := XSize + round((x / XStep));
YPosT := YSize - round((y / YStep));
{ If XPosT > 639 then XposT := 639;
If XPosT < 1 then XposT := 1;
If YPosT > 479 then YposT := 479;
If YPosT < 1 then YposT := 1;
XPos := XPosT;
YPos := YPosT;}
Pixels[XPosT, YPosT] := TempColor; { ((T Div 200) + 8 );}
end; { of For T NEXT T}
end; { of For TT NEXT TT}
end; end;
MainForm.HiddenFX.Caption := 'HiddenFX';
Application.ProcessMessages;
end; { of Brusselator }
(*************************************************************)
(*************************************************************)
(*************************************************************)
procedure SetChemical;
begin
with MainForm.Image2.Canvas do begin
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, FYImageX, FYImageY));
end; end;
(*************************************************************)
procedure StrangeChemicalsa;
{dx/dt = -k2x - k3y(x/k+x) + k1 + k6z
dy/dt = -k2y - k3x(y/k+x) + k1 + b
dz/dt = k4y - k5z}
var
s: string[10];
{A, C, F,} B, k, k1, k2, k3, k4, k5, k6,
D1, D2, D3,
D, MinU, MaxU, U2, V2, X, Y, Z, U, V: Extended;
IKan, NPts, XSize, YSize, Limit, i, j, Steps: integer;
XPos, YPos: integer;
XPosT, YPosT: Longint;
Xmin, YMin, XStep, YStep, XMax, YMax: Extended;
TT, T, Q: integer;
DL1A, DL1B, DL1, Dl2, Dl3, Dl, Dr,
Step, Ua1, Ua2, Va1, Va2, YTL, YTM, YTR, TM, TL, TR, BL, BR:
Extended;
TempColor: TColor;
begin
FractalFilename := 'A_ST_CA0.BMP';
XSize := FYImageX - 1; { physical screen size }
YSize := FYImageY - 1; { physical screen size }
with MainForm.Image2.Canvas do begin
{Brush.Color:=FBackGroundColor;
Brush.Style:=bsSolid;
FillRect(Rect(0,0,FYImageX,FYImageY)); }
TempColor := RGB(255 - GetRValue(FBackGroundColor),
255 - GetGValue(FBackGroundColor),
255 - GetBValue(FBackGroundColor));
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(10, 10, 'Chemical A' {s});
MainForm.Show;
MainForm.HiddenFX.Caption := 'A_ST_CA0.BMP';
Application.ProcessMessages;
XMax := 2.0; {3.56}
XMin := -1.0; {-3.70}
YMax := 2.0; {6.76 3.61}
YMin := -1.0; {-5.14 -3.02}
XStep := (XMax - XMin) / XSize;
YStep := (YMax - YMin) / YSize;
Step := 0.1 / 25;
X := -1.0;
Y := 1.2;
Z := 1.0;
B := 1.0;
k := 1.0;
k1 := 1.1;
k2 := 1.2;
k3 := 1.3;
k4 := 1.4;
k5 := 1.50;
k6 := 1.70;
{dx/dt = -k2x - k3y(x/k+x) + k1 + k6z
dy/dt = -k2y - k3x(y/k+x) + k1 + b
dz/dt = k4y - k5z}
MinU := -1E+5;
MaxU := 1E+5;
for T := 1 to 255 do begin
MainForm.HiddenFX.Caption := 'A_ST_CA0.BMP';
Application.ProcessMessages;
TempColor := RGB(Colors[0, T],
Colors[1, T],
Colors[2, T]);
for TT := 1 to 200 do
begin
DL1 := (-k2 * X);
DL1A := X;
DL1B := (X / k);
DL2 := (DL1A + DL1B);
DL3 := (k3 * y);
DL := (DL1 - (DL2 * DL3));
DR := (k1 + (k6 * Z));
D1 := DL + DR;
{dx/dt = -k2x - k3y(x/k+x) + k1 + k6z
dy/dt = -k2y - k3x(y/k+x) + k1 + b
dz/dt = k4y - k5z}
DL1 := (-k2 * Y);
DL1A := X;
DL1B := (Y / k);
DL2 := (DL1A + DL1B);
DL3 := (k3 * X);
DL := (DL1 - (DL2 * DL3));
DR := (k1 + (B));
D2 := DL + DR;
D3 := (k4 * Y) - (k5 * z);
X := ((X + D1 * Step));
Y := ((Y + D2 * Step));
Z := ((Z + D3 * Step)); {320 240 }
XPosT := (XSize div 2) + round((x / XStep));
YPosT := (YSize div 2) - round((y / YStep));
Pixels[XPosT, YPosT] := TempColor;
end; { of For T NEXT T}
end; { of For TT NEXT TT}
end;
MainForm.HiddenFX.Caption := 'HiddenFX';
Application.ProcessMessages;
end; { of StrangeChemicalsA }
(*************************************************************)
procedure StrangeChemicalsb;
{dx/dt = k1 + k2'x - ((k3y = k4z)x / (x+k))
dy/dt = k5x - k6y
dz/dt = k7x - k8'z / (z+k')}
var
s: string[10];
{A, C, F,} B, k, k1, k2, k3, k4, k5, k6, k7, k8,
D1, D2, D3,
D, MinU, MaxU, U2, V2, X, Y, Z, U, V: Extended;
IKan, NPts, XSize, YSize, Limit, i, j, Steps: integer;
XPos, YPos: integer;
XPosT, YPosT: Longint;
Xmin, YMin, XStep, YStep, XMax, YMax: Extended;
TT, T, Q: integer;
DL1A, DL1B, DL1, Dl2, Dl3, Dl, Dr,
Step, Ua1, Ua2, Va1, Va2, YTL, YTM, YTR, TM, TL, TR, BL, BR:
Extended;
TempColor: TColor;
begin
FractalFilename := 'A_ST_CB0.BMP';
XSize := FYImageX - 1; { physical screen size }
YSize := FYImageY - 1; { physical screen size }
with MainForm.Image2.Canvas do begin
{Brush.Color:=FBackGroundColor;
Brush.Style:=bsSolid;
FillRect(Rect(0,0,FYImageX,FYImageY));}
TempColor := RGB(255 - GetRValue(FBackGroundColor),
255 - GetGValue(FBackGroundColor),
255 - GetBValue(FBackGroundColor));
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(10, 10, 'Chemical B' {s});
MainForm.Show;
MainForm.HiddenFX.Caption := 'A_ST_CB0.BMP';
Application.ProcessMessages;
XMax := 42.0; {3.56}
XMin := 32.0; {-3.70}
YMax := 42.0; {6.76 3.61}
YMin := 32.0; {-5.14 -3.02}
XStep := (XMax - XMin) / XSize;
YStep := (YMax - YMin) / YSize;
Step := 0.1 / 25;
X := 1.1;
Y := 1.1;
Z := 0.510;
B := 1.10;
k := 1.0;
k1 := 1.1;
k2 := 1.2;
k3 := 1.3;
k4 := 1.1;
k5 := 1.15;
k6 := 1.0;
k7 := 1.0;
k8 := 1.0;
{dx/dt = k1 + k2'x - ((k3y + k4z)x / (x+k))
dy/dt = k5x - k6y
dz/dt = k7x - k8'z / (z+k')}
MinU := -1E+5;
MaxU := 1E+5;
for T := 1 to 255 do begin
MainForm.HiddenFX.Caption := 'A_ST_CB0.BMP';
Application.ProcessMessages;
TempColor := RGB(Colors[0, T],
Colors[1, T],
Colors[2, T]);
for TT := 1 to 200 do
begin
DL1 := ((k2 * X));
DL := (k1 + DL1);
DL1A := (k3 * Y);
DL1B := (k4 * Z);
DL2 := ((DL1A + DL1B) * X);
DL3 := (X + k);
DR := (DL2 / DL3);
D1 := DL - DR;
{dx/dt = k1 + k2'x - ((k3y + k4z)x / (x+k))
dy/dt = k5x - k6y
dz/dt = k7x - k8'z / (z+k')}
DL := (k5 * X);
DR := (k6 * Y);
D2 := (DL - DR);
DL1 := (k7 * X);
DL1A := (k8 * Z);
DL1B := (DL1 - DL1A); {Math correct?}
DL2 := (Z + k);
D3 := (DL1B / DL2);
X := ((X + D1 * Step));
Y := ((Y + D2 * Step));
Z := ((Z + D3 * Step)); {320 240 }
XPosT := (XSize div 2) + round((x / XStep));
YPosT := (YSize div 2) - round((y / YStep));
Pixels[XPosT, YPosT] := TempColor;
end; { of For T NEXT T}
end; { of For TT NEXT TT}
end;
MainForm.HiddenFX.Caption := 'HiddenFX';
Application.ProcessMessages;
end; { of StrangeChemicalsB }
(*************************************************************)
(*************************************************************)
procedure StrangeChemicalsc;
{dx/dt = -y - z - w
dy/dt = x
dz/dt = c(z/2 - z^2) -dw}
var
{s : string[10];}
{A, F,B, k, k1,k2,k3,k4,k5,k6,k7,k8,}
D1, D2, D3, C, w, D,
{MinU, MaxU, U2, V2,} X, Y, Z {, U, V}: Extended;
{IKan, NPts,}
HalfY, HalfX, XSize, YSize {, Limit, i, j, Steps}: integer;
{ XPos, YPos : integer; }
XPosT, YPosT: Longint;
Xmin, YMin, XStep, YStep, XMax, YMax: Extended;
TT, T {,Q}: integer;
DL1A, DL1B, DL1, Dl2, {Dl3, Dl, Dr,}
Step {Ua1, Ua2, Va1, Va2, YTL, YTM, YTR, TM, TL,TR,BL,BR}:
Extended;
TempColor: TColor;
begin
FractalFilename := 'A_ST_CC0.BMP';
XSize := FYImageX - 1; { physical screen size }
YSize := FYImageY - 1; { physical screen size }
HalfX := (FYImageX div 2);
HalfY := ((FYImageY div 4) * 3);
with MainForm.Image2.Canvas do begin
{Brush.Color:=FBackGroundColor;
Brush.Style:=bsSolid;
FillRect(Rect(0,0,FYImageX,FYImageY));}
TempColor := RGB(255 - GetRValue(FBackGroundColor),
255 - GetGValue(FBackGroundColor),
255 - GetBValue(FBackGroundColor));
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(10, 10, 'Chemical C' {s});
MainForm.Show;
MainForm.HiddenFX.Caption := 'A_ST_CC0.BMP';
Application.ProcessMessages;
XMax := 3.320; {3.56}
XMin := 2.0; {-3.70}
YMax := 6.230; {6.76 3.61}
YMin := 2.0; {-5.14 -3.02}
XStep := (XMax - XMin) / XSize;
YStep := ((YMax - YMin) * 4) / YSize;
Step := 0.1 / 25;
X := 0.12;
Y := 0.00012;
Z := 0.00211;
C := 0.00120;
w := 0.110;
D := 0.21;
{dx/dt = -y - z - w
dy/dt = x
dz/dt = c(z/2 - z^2) -dw}
{MinU := -1E+5;
MaxU := 1E+5;}
for T := 1 to 255 do begin
MainForm.HiddenFX.Caption := 'A_ST_CC0.BMP';
Application.ProcessMessages;
TempColor := RGB(Colors[0, T],
Colors[1, T],
Colors[2, T]);
for TT := 1 to 235 do
begin
D1 := ((-y) - (z - w));
{dx/dt = -y - z - w
dy/dt = x
dz/dt = c(z/2 - z^2) -dw}
D2 := (X);
DL1 := (Z / 2);
DL1A := (Z * Z);
DL1B := (c * (DL1 - DL1A));
DL2 := (d * w);
D3 := (DL1B - DL2);
X := ((X + D1 * Step));
Y := ((Y + D2 * Step));
Z := ((Z + D3 * Step)); {320 240 }
{If DL1A < MinU then DL1A := MinU else
If DL1A > MaxU then DL1A := MaxU;
If DL1B < MinU then DL1B := MinU else
If DL1B > MaxU then DL1B := MaxU;}
XPosT := HalfX + round((x / XStep));
YPosT := FYImageY {HalfY} - round((y / YStep));
Pixels[XPosT, YPosT] := TempColor;
end; { of For T NEXT T}
{in the Drawing...}
{bRotateImage:=False;
bRotatingImage:=True;
Repeat Application.ProcessMessages until (bRotateImage=True);
}
end; { of For TT NEXT TT}
end;
MainForm.HiddenFX.Caption := 'HiddenFX';
Application.ProcessMessages;
end; { of StrangeChemicalsC }
(*************************************************************)
procedure StrangeChemicalsd;
{dx/dt = V1 - b1x - V
dy/dt = V2 - b2y + V -(m(y-z))
dz/dt = ma(y-z)
V = (x - ky) / (1 + (x+y)(1 + cx^g) )}
var
{s : string[10];}
{A, F,B, k, k1,k2,k3,k4,k5,k6,k7,k8,}
C, g, V, V1, V2, b1, k, m, a, b2,
{MinU, MaxU,}
D1, D2, D3, X, Y, Z: Extended;
{IKan, NPts,} XSize, YSize {, Limit, i, j, Steps}: integer;
{ XPos, YPos : integer; }
XPosT, YPosT: Longint;
Xmin, YMin, XStep, YStep, XMax, YMax: Extended;
TT, T {,Q}: integer;
DL1A, DL1B, DL1, Dl2, Dl3, Dl, Dr,
Step {Ua1, Ua2, Va1, Va2, YTL, YTM, YTR, TM, TL,TR,BL,BR}:
Extended;
TempColor: TColor;
begin
FractalFilename := 'A_ST_CD0.BMP';
XSize := FYImageX - 1; { physical screen size }
YSize := FYImageY - 1; { physical screen size }
with MainForm.Image2.Canvas do begin
{Brush.Color:=FBackGroundColor;
Brush.Style:=bsSolid;
FillRect(Rect(0,0,FYImageX,FYImageY));}
TempColor := RGB(255 - GetRValue(FBackGroundColor),
255 - GetGValue(FBackGroundColor),
255 - GetBValue(FBackGroundColor));
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(10, 10, 'Chemical D' {s});
MainForm.Show;
MainForm.HiddenFX.Caption := 'A_ST_CD0.BMP';
Application.ProcessMessages;
XMax := 93.320; {3.56}
XMin := 25.0; {-3.70}
YMax := 96.230; {6.76 3.61}
YMin := 25.0; {-5.14 -3.02}
XStep := (XMax - XMin) / XSize;
YStep := (YMax - YMin) / YSize;
Step := 0.1 / 25;
X := 12.2;
Y := 12.0;
Z := 12.1;
V := 1.1;
V1 := 02.20;
V2 := 02.10;
b1 := 1.20;
b2 := 1.30;
m := 1.20;
a := 1.30;
k := 1.20;
g := 1.10;
C := 1.10;
{dx/dt = V1 - b1x - V
dy/dt = V2 - b2y + V -(m(y-z))
dz/dt = ma(y-z)
V = (x - ky) / (1 + (x+y)(1 + cx^g) )}
{MinU := -1E+5;
MaxU := 1E+5;}
for T := 1 to 255 do begin
MainForm.HiddenFX.Caption := 'A_ST_CD0.BMP';
Application.ProcessMessages;
TempColor := RGB(Colors[0, T],
Colors[1, T],
Colors[2, T]);
for TT := 1 to 200 do
begin
DL1 := (b1 * X);
D1 := (V1 - DL1 - V);
{dx/dt = V1 - b1x - V
dy/dt = V2 - b2y + V -(m(y-z))
dz/dt = ma(y-z)
V = (x - ky) / (1 + (x+y)(1 + cx^g) )}
DL1 := (b2 * y);
DL1A := (V2 - DL1 + V);
Dl3 := (y - z);
Dr := (m * Dl3);
D2 := (DL1A - Dr);
DL1A := (m * a);
D3 := (DL1A * Dl3);
DL1A := (k * y);
DL1 := (X - DL1A);
DL1A := power(x, g);
DL1B := (c * (DL1A));
DL2 := (1 + DL1B);
Dl := (X + Y);
Dr := (DL2 * Dl);
Dl3 := (1 + Dr);
V := (DL1 / Dl3);
{V = (x - ky) / (1 + (x+y)(1 + cx^g) )}
X := ((X + D1 * Step));
Y := ((Y + D2 * Step));
Z := ((Z + D3 * Step)); {320 240 }
{If DL1A < MinU then DL1A := MinU else
If DL1A > MaxU then DL1A := MaxU;
If DL1B < MinU then DL1B := MinU else
If DL1B > MaxU then DL1B := MaxU;}
XPosT := (XSize div 2) + round((x / XStep));
YPosT := (YSize div 2) - round((y / YStep));
Pixels[XPosT, YPosT] := TempColor;
end; { of For T NEXT T}
{in the Drawing...}
{bRotateImage:=False;
bRotatingImage:=True;
Repeat Application.ProcessMessages until (bRotateImage=True);
}
end; { of For TT NEXT TT}
end;
MainForm.HiddenFX.Caption := 'HiddenFX';
Application.ProcessMessages;
end; { of StrangeChemicals D }
(*************************************************************)
procedure StrangeChemicalse;
{dx/dt = x(a1 - k1x - z -y) + k2y^2 + a3
dy/dt = y(x - k2y - a5) + a2
dz/dt = z(a4 - x - k5z) + a3}
var
{s : string[10];}
{A, F,B, k, k1,k2,k3,k4,k5,k6,k7,k8,}
k5, k1, k2, a1, a2, a3, a4, a5,
{MinU, MaxU,}
D1, D2, D3, X, Y, Z: Extended;
{IKan, NPts,} XSize, YSize {, Limit, i, j, Steps}: integer;
{ XPos, YPos : integer; }
XPosT, YPosT: Longint;
Xmin, YMin, XStep, YStep, XMax, YMax: Extended;
TT, T {,Q}: integer;
DL1A, DL1B, DL1, Dl2, Dl3, Dl, Dr,
Step {Ua1, Ua2, Va1, Va2, YTL, YTM, YTR, TM, TL,TR,BL,BR}:
Extended;
TempColor: TColor;
begin
FractalFilename := 'A_ST_CE0.BMP';
XSize := FYImageX - 1; { physical screen size }
YSize := FYImageY - 1; { physical screen size }
with MainForm.Image2.Canvas do begin
{Brush.Color:=FBackGroundColor;
Brush.Style:=bsSolid;
FillRect(Rect(0,0,FYImageX,FYImageY));}
TempColor := RGB(255 - GetRValue(FBackGroundColor),
255 - GetGValue(FBackGroundColor),
255 - GetBValue(FBackGroundColor));
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(10, 10, 'Chemical E' {s});
MainForm.Show;
MainForm.HiddenFX.Caption := 'A_ST_CE0.BMP';
Application.ProcessMessages;
XMax := 93.320; {3.56}
XMin := 25.0; {-3.70}
YMax := 96.230; {6.76 3.61}
YMin := 25.0; {-5.14 -3.02}
XStep := (XMax - XMin) / XSize;
YStep := (YMax - YMin) / YSize;
Step := 0.1 / 25;
X := 12.2;
Y := 12.0;
Z := 12.1;
k5 := 1.1;
k1 := 02.20;
k2 := 02.10;
a1 := 1.20;
a2 := 1.30;
a3 := 1.20;
a4 := 1.30;
a5 := 1.20;
{dx/dt = x(a1 - k1x - z -y) + k2y^2 + a3
dy/dt = y(x - k2y - a5) + a2
dz/dt = z(a4 - x - k5z) + a3}
{MinU := -1E+5;
MaxU := 1E+5;}
for T := 1 to 255 do begin
MainForm.HiddenFX.Caption := 'A_ST_CE0.BMP';
Application.ProcessMessages;
TempColor := RGB(Colors[0, T],
Colors[1, T],
Colors[2, T]);
for TT := 1 to 200 do
begin
DL1 := (k1 * X);
DL1A := (a1 - DL1 - z - y);
DL1B := (x * (DL1A));
Dl := (Y * Y);
Dr := (k2 * Dl);
D1 := (Dr + Dl1B + a3);
{dx/dt = x(a1 - k1x - z -y) + k2y^2 + a3
dy/dt = y(x - k2y - a5) + a2
dz/dt = z(a4 - x - k5z) + a3}
DL1 := (k2 * y);
DL1A := (x - DL1 - a5);
Dl3 := (y * DL1A);
D2 := (DL3 + a2);
DL1 := (k5 * z);
DL1A := (a4 - x - DL1);
Dl3 := (z * DL1A);
D3 := (DL3 + a3);
X := ((X + D1 * Step));
Y := ((Y + D2 * Step));
Z := ((Z + D3 * Step)); {320 240 }
{If DL1A < MinU then DL1A := MinU else
If DL1A > MaxU then DL1A := MaxU;
If DL1B < MinU then DL1B := MinU else
If DL1B > MaxU then DL1B := MaxU;}
XPosT := (XSize div 2) + round((x / XStep));
YPosT := (YSize div 2) - round((y / YStep));
Pixels[XPosT, YPosT] := TempColor;
end; { of For T NEXT T}
{in the Drawing...}
{bRotateImage:=False;
bRotatingImage:=True;
Repeat Application.ProcessMessages until (bRotateImage=True);
}
end; { of For TT NEXT TT}
end;
MainForm.HiddenFX.Caption := 'HiddenFX';
Application.ProcessMessages;
end; { of StrangeChemicals e }
(*************************************************************)
procedure StrangeChemicalsf;
{dx/dt = V0 - b1x - V
dy/dt = 1 - y - V
V = (ay) / ( (1+ dy) (c+ x(1 + x^g)) )}
var
{s : string[10];}
{A, F,B, k, k1,k2,k3,k4,k5,k6,k7,k8,}
C, g, V, V0, b1, a, d,
{MinU, MaxU,}
D1, D2, D3, X, Y, Z: Extended;
{IKan, NPts,} XSize, YSize {, Limit, i, j, Steps}: integer;
{ XPos, YPos : integer; }
XPosT, YPosT: Longint;
Xmin, YMin, XStep, YStep, XMax, YMax: Extended;
TT, T {,Q}: integer;
DL1A, DL1B, DL1, Dl2, Dl3, Dl, Dr,
Step {Ua1, Ua2, Va1, Va2, YTL, YTM, YTR, TM, TL,TR,BL,BR}:
Extended;
TempColor: TColor;
begin
FractalFilename := 'A_ST_CF0.BMP';
XSize := FYImageX - 1; { physical screen size }
YSize := FYImageY - 1; { physical screen size }
with MainForm.Image2.Canvas do begin
{Brush.Color:=FBackGroundColor;
Brush.Style:=bsSolid;
FillRect(Rect(0,0,FYImageX,FYImageY));}
TempColor := RGB(255 - GetRValue(FBackGroundColor),
255 - GetGValue(FBackGroundColor),
255 - GetBValue(FBackGroundColor));
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(10, 10, 'Chemical F' {s});
MainForm.Show;
MainForm.HiddenFX.Caption := 'A_ST_CF0.BMP';
Application.ProcessMessages;
XMax := 93.320; {3.56}
XMin := 25.0; {-3.70}
YMax := 96.230; {6.76 3.61}
YMin := 25.0; {-5.14 -3.02}
XStep := (XMax - XMin) / XSize;
YStep := (YMax - YMin) / YSize;
Step := 0.1 / 25;
X := 12.2;
Y := 12.0;
Z := 12.1;
V := 21.1;
V0 := 02.20;
b1 := 1.20;
C := 1.20;
a := 1.30;
d := 11.20;
g := 11.10;
{dx/dt = V0 - b1x - V
dy/dt = 1 - y - V
V = (a x y) / ( (1+ dy) (c+ x(1 + x^g)) )}
{MinU := -1E+5;
MaxU := 1E+5;}
for T := 1 to 255 do begin
MainForm.HiddenFX.Caption := 'A_ST_CF0.BMP';
Application.ProcessMessages;
TempColor := RGB(Colors[0, T],
Colors[1, T],
Colors[2, T]);
for TT := 1 to 200 do
begin
DL1 := (b1 * X);
D1 := (V0 - DL1 - V);
{dx/dt = V0 - b1x - V
dy/dt = 1 - y - V
V = (a x y) / ( (1+ dy) (c+ x(1 + x^g)) )}
D2 := (1 - y - V);
DL1 := (a * x * y);
DL1A := power(x, g);
DL1B := (x * (1 + DL1A));
DL2 := (C + DL1B);
Dl := (d * Y);
Dr := (1 + Dl);
Dl3 := (Dl2 * Dr);
V := (DL1 / Dl3);
{V = (x - ky) / (1 + (x+y)(1 + cx^g) )}
X := ((X + D1 * Step));
Y := ((Y + D2 * Step));
{Z := ((Z + D3 * Step)); }{320 240 }
{If DL1A < MinU then DL1A := MinU else
If DL1A > MaxU then DL1A := MaxU;
If DL1B < MinU then DL1B := MinU else
If DL1B > MaxU then DL1B := MaxU;}
XPosT := (XSize div 2) + round((x / XStep));
YPosT := (YSize div 2) - round((y / YStep));
Pixels[XPosT, YPosT] := TempColor;
end; { of For T NEXT T}
{in the Drawing...}
{bRotateImage:=False;
bRotatingImage:=True;
Repeat Application.ProcessMessages until (bRotateImage=True);
}
end; { of For TT NEXT TT}
end;
MainForm.HiddenFX.Caption := 'HiddenFX';
Application.ProcessMessages;
end; { of StrangeChemicals }
(*************************************************************)
procedure StrangeChemicalsg;
{Rietman p111}
{dx/dt = k1A - k2Bx + k3x^2y - k4x
dy/dt = k2Bx - k3 x^2y}
var
{s : string[10];}
{A, F,B, k, k1,k2,k3,k4,k5,k6,k7,k8,}
{ C, g,V,V1,V2,b1,k,m,a,b2, }
{MinU, MaxU,} k1, k2, k3, k4, B, A,
D1, D2, D3, X, Y, Z: Extended;
{IKan, NPts,} XSize, YSize {, Limit, i, j, Steps}: integer;
{ XPos, YPos : integer; }
XPosT, YPosT: Longint;
Xmin, YMin, XStep, YStep, XMax, YMax: Extended;
TT, T {,Q}: integer;
DL1A, DL1B, DL1, Dl2, Dl3, Dl, Dr,
Step {Ua1, Ua2, Va1, Va2, YTL, YTM, YTR, TM, TL,TR,BL,BR}:
Extended;
TempColor: TColor;
begin
FractalFilename := 'A_ST_CG0.BMP';
XSize := FYImageX - 1; { physical screen size }
YSize := FYImageY - 1; { physical screen size }
with MainForm.Image2.Canvas do begin
{Brush.Color:=FBackGroundColor;
Brush.Style:=bsSolid;
FillRect(Rect(0,0,FYImageX,FYImageY));}
TempColor := RGB(255 - GetRValue(FBackGroundColor),
255 - GetGValue(FBackGroundColor),
255 - GetBValue(FBackGroundColor));
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(10, 10, 'Chemical G' {s});
MainForm.Show;
MainForm.HiddenFX.Caption := 'A_ST_CG0.BMP';
Application.ProcessMessages;
XMax := 16.320; {3.56}
XMin := 2.0; {-3.70}
YMax := 16.230; {6.76 3.61}
YMin := 2.0; {-5.14 -3.02}
XStep := (XMax - XMin) / XSize;
YStep := (YMax - YMin) / YSize;
Step := 0.1 / 25;
X := 1.2;
Y := 1.0;
Z := 1.1;
k1 := 1.1;
k2 := 01.20;
k3 := 01.10;
k4 := 1.20;
B := 1.20;
A := 1.30;
{dx/dt = k1A - k2Bx + k3x^2y - k4x
dy/dt = k2Bx - k3 x^2y}
{MinU := -1E+5;
MaxU := 1E+5;}
for T := 0 to 255 do begin
MainForm.HiddenFX.Caption := 'A_ST_CG0.BMP';
Application.ProcessMessages;
TempColor := RGB(Colors[0, T],
Colors[1, T],
Colors[2, T]);
for TT := 1 to 200 do
begin
{dx/dt = k1A - k2Bx + k3x^2y - k4x
dy/dt = k2Bx - k3 x^2y}
DL1 := (k1 * A);
DL1A := (k2 * B * X);
DL1B := (X * X);
DL2 := (k3 * DL1B * Y);
Dl3 := (k4 * X);
D1 := (DL1 - DL1A + DL2 - Dl3);
DL1A := (k2 * B * X);
DL1B := (X * X);
DL1 := (k3 * DL1B);
D2 := (DL1A - DL1);
X := ((X + D1 * Step));
Y := ((Y + D2 * Step));
{Z := ((Z + D3 * Step)); 320 240 }
{If DL1A < MinU then DL1A := MinU else
If DL1A > MaxU then DL1A := MaxU;
If DL1B < MinU then DL1B := MinU else
If DL1B > MaxU then DL1B := MaxU;}
XPosT := (XSize div 2) + round((x / XStep));
YPosT := (YSize div 2) - round((y / YStep));
Pixels[XPosT, YPosT] := TempColor;
end; { of For T NEXT T}
{in the Drawing...}
{bRotateImage:=False;
bRotatingImage:=True;
Repeat Application.ProcessMessages until (bRotateImage=True);
}
end; { of For TT NEXT TT}
end;
MainForm.HiddenFX.Caption := 'HiddenFX';
Application.ProcessMessages;
end; { of StrangeChemicals g }
(*************************************************************)
(*************************************************************)
(*************************************************************)
(*************************************************************)
end.
|
unit Unit1;
// MAKE SURE TO DEFINE "VIRTUALNAMESPACES" under Project>Options>Directories/Conditionals
//
// This is an example of a down and dirty NSE example it works ok for single objects that
// are under a real namespace. The prefered method is to create a decendant of
// TBaseVirtualNamespaceExtension and implement the necessary methods
//
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, CustomNS, VirtualNamespace, VirtualTrees, VirtualExplorerTree,
VirtualShellUtilities, ShlObj;
type
TForm2 = class(TForm)
VirtualExplorerListview1: TVirtualExplorerListview;
VirtualExplorerTreeview1: TVirtualExplorerTreeview;
procedure VirtualExplorerListview1CustomNamespace(
Sender: TCustomVirtualExplorerTree; AParentNode: PVirtualNode);
procedure VirtualExplorerListview1EnumFolder(
Sender: TCustomVirtualExplorerTree; Namespace: TNamespace;
var AllowAsChild: Boolean);
procedure VirtualExplorerListview1GetVETText(
Sender: TCustomVirtualExplorerTree; Column: TColumnIndex;
Node: PVirtualNode; Namespace: TNamespace; var Text: WideString);
private
{ Private declarations }
protected
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
{$R *.DFM}
procedure TForm2.VirtualExplorerListview1CustomNamespace(
Sender: TCustomVirtualExplorerTree; AParentNode: PVirtualNode);
{$IFDEF VIRTUALNAMESPACES}
var
NS: TNamespace;
CustomPIDL: TGerardsPIDL;
PIDL, RelativePIDL: PItemIDList;
{$ENDIF VIRTUALNAMESPACES}
begin
{$IFDEF VIRTUALNAMESPACES}
// Put it under the desktop
if VirtualExplorerListview1.ValidateNamespace(AParentNode, NS) then
begin
if NS.IsDesktop then
begin
CustomPIDL := TGerardsPIDL.Create(IID_IGerardsNamespace);
CustomPIDL.InFolderNameASCII := 'Gerards Namespace';
CustomPIDL.Data1 := True;
CustomPIDL.Data2 := 456;
RelativePIDL := CustomPIDL.ItemID;
PIDL := PIDLMgr.AppendPIDL(NS.AbsolutePIDL, RelativePIDL);
PIDLMgr.FreePIDL(RelativePIDL);
VirtualExplorerListview1.AddCustomNode(AParentNode, TNamespace.Create(PIDL, nil), False);
// Any Namespace that has a Virtual Child must be hooked
NamespaceExtensionFactory.HookPIDL(NS.AbsolutePIDL, IID_IGerardsNamespace, False);
end
end
{$ENDIF VIRTUALNAMESPACES}
end;
procedure TForm2.VirtualExplorerListview1EnumFolder(
Sender: TCustomVirtualExplorerTree; Namespace: TNamespace;
var AllowAsChild: Boolean);
//var
// GUID: TGUID;
begin
// AllowAsChild := NamespaceExtensionFactory.ExtractVirtualGUID(Namespace.AbsolutePIDL, GUID)
end;
procedure TForm2.VirtualExplorerListview1GetVETText(
Sender: TCustomVirtualExplorerTree; Column: TColumnIndex;
Node: PVirtualNode; Namespace: TNamespace; var Text: WideString);
var
Helper: TGerardsPIDL;
begin
// Because details are handled by the Parent of the objects in this case our
// custom namespace is not a child of the real namespace so it can't show the
// details. It is very difficult for VET to handle this case so we will just have
// to find it ourselves and fix the details.
if NamespaceExtensionFactory.IsVirtualPIDL(Namespace.RelativePIDL) then
begin
if Column > 0 then
begin
Helper := TGerardsPIDL.Create(IID_IGerardsNamespace);
Helper.ItemID := Namespace.RelativePIDL;
case Column of
1: if Helper.Data1 then
Text := 'Data1 = True'
else
Text := 'Data1 = False';
2: Text := 'Data2 = ' + IntToStr(Helper.Data2);
else
Text := ''
end;
Helper.Free;
end
end;
end;
end.
|
unit uPCardDataModule;
interface
uses
SysUtils, Classes, DB, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase,
Dialogs, AccMgmt;
type
TdmPCard = class(TDataModule)
DB: TpFIBDatabase;
DefaultTransaction: TpFIBTransaction;
ReadTransaction: TpFIBTransaction;
PCardModules: TpFIBDataSet;
private
{ Private declarations }
public
{ Public declarations }
end;
var
dmPCard: TdmPCard;
AdminMode: Boolean;
function CheckAccess(Path:string;Action:String;DisplayMessage:Boolean=False):Integer;
procedure ShowInfo(DataSet: TDataSet);
implementation
{$R *.dfm}
function CheckAccess(Path:string;Action:String;DisplayMessage:Boolean=False):Integer;
var
i:Integer;
begin
i:=0;
if (not AdminMode) then
begin
i:=fibCheckPermission(Path,Action);
if i<>0 then begin
if DisplayMessage then
MessageDlg(AcMgmtErrMsg(i),mtError,[mbOk],0);
end;
end;
CheckAccess:=i;
end;
procedure ShowInfo(DataSet: TDataSet);
var text: string;
i:integer;
begin
text:='';
for i:=1 to DataSet.Fields.Count do
text:=text+DataSet.Fields[i-1].FieldName+' : '+DataSet.Fields[i-1].DisplayText+#13;
ShowMessage(text);
end;
end.
|
unit UConfigSaas;
interface
uses
UConfigMySql, SysUtils;
type
TConfigSaasSensorMapping = class(TConfigMySqlAbstract)
protected
function GetDBConfigModifiedDateTime: TDateTime; override;
function ReloadDBConfig: Boolean; override;
end;
TConfigSaasTrackRetranslation = class(TConfigMySqlAbstract)
protected
function GetDBConfigModifiedDateTime: TDateTime; override;
function ReloadDBConfig: Boolean; override;
end;
implementation
{ TConfigSaasSensorMapping }
function TConfigSaasSensorMapping.GetDBConfigModifiedDateTime: TDateTime;
begin
// FMySqlQuery.SQL.Text := 'select '
Result := 0;
end;
function TConfigSaasSensorMapping.ReloadDBConfig: Boolean;
begin
Result := False;
end;
{ TConfigSaasTrackRetranslation }
function TConfigSaasTrackRetranslation.GetDBConfigModifiedDateTime: TDateTime;
begin
Result := 0;
//
// FMySqlQuery.Close;
// FMySqlQuery.SQL.Text := 'select Max(Modified) as LastChanged from TrackRetranslation';
// try
// FMySqlQuery.Open;
// FMySqlQuery.First;
// if FMySqlQuery.RecordCount >= 1 then
// Result := FMySqlQuery.FieldByName('LastChanged').AsDateTime;
// FMySqlQuery.Close;
// except
// on E: Exception do begin
// Log('Ошибка чтения конфигурации TConfigSaasTrackRetranslation "' + FMySqlQuery.SQL.Text + '": ' + E.Message);
// end;
// end;
end;
function TConfigSaasTrackRetranslation.ReloadDBConfig: Boolean;
//var
// IMEI: Int64;
// ID: Integer;
// From: TDateTime;
// Till: TDateTime;
// Name: string;
// Topic: string;
// Bootstrap: string;
begin
Result := False;
//
// FJson.Clear;
//
// FMySqlQuery.Close;
// FMySqlQuery.SQL.Text :=
// 'select ' +
// 'trn.IMEI, trn.TrackRetranslatorID, trn.Created, trn.Modified, ' +
// 'trr.ID, trr.Name, trr.Comment, trr.Target, trr.Bootstrap, trr.Topic ' +
// 'from TrackRetranslation trn ' +
// 'join TrackRetranslator trr on trr.ID = trn.TrackRetranslatorID ' +
// 'order by trn.IMEI, trr.ID';
//
// try
// FMySqlQuery.Open;
// FMySqlQuery.First;
// while not FMySqlQuery.Eof do
// begin
// //FMySqlQuery.FieldByName('LastChanged').AsDateTime
//
// IMEI := FMySqlQuery.FieldByName('IMEI').AsLargeInt;
// ID := FMySqlQuery.FieldByName('ID').AsInteger;
// Name := FMySqlQuery.FieldByName('Name').AsString;
// Topic := FMySqlQuery.FieldByName('Topic').AsString;
// Bootstrap := FMySqlQuery.FieldByName('Bootstrap').AsString;
//
//// if not FJson.Contains('imei-split-list') then
// FJson.O['imei-split-list'].A[IntToStr(IMEI)].Add(Topic);
//
// FMySqlQuery.Next;
// end;
//
// FMySqlQuery.Close;
//
// Result := True;
// except
// on E: Exception do begin
// Log('Ошибка чтения конфигурации TConfigSaasTrackRetranslation "' + FMySqlQuery.SQL.Text + '": ' + E.Message);
// end;
// end;
end;
end.
|
unit frm_History;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, JvExStdCtrls, JvMemo, JvListBox, Registry,
ComCtrls, JvExComCtrls, JvListView;
type
TfrmHistory = class(TForm)
Panel1: TPanel;
mmo: TJvMemo;
Splitter1: TSplitter;
Panel2: TPanel;
Panel3: TPanel;
btnLoad: TButton;
lv: TJvListView;
procedure FormShow(Sender: TObject);
procedure lvSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure btnLoadClick(Sender: TObject);
procedure lvDblClick(Sender: TObject);
procedure mmoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
procedure LoadHistory;
{ Private declarations }
public
end;
implementation
uses frm_Main;
{$R *.dfm}
procedure TfrmHistory.LoadHistory;
var
n: Integer;
stl: TStringList;
reg: TRegistry;
li: TListItem;
begin
reg := TRegistry.Create;
stl := TStringList.Create;
try
reg.RootKey := HKEY_CURRENT_USER;
if not reg.OpenKey(CRegPath + 'History\', False) then Exit;
reg.GetKeyNames(stl);
for n := stl.Count-1 downto 0 do
begin
reg.CloseKey;
reg.OpenKey(CRegPath + 'History\' + stl[n], True);
li := lv.Items.Add;
li.Caption := IntToStr(lv.Items.Count);
li.SubItems.Add(DateToStr(reg.ReadDateTime('Date')));
li.SubItems.Add(TimeToStr(reg.ReadDateTime('Date')));
li.SubItems.Add(stl[n]);
li.SubItems.Add(reg.ReadString('Description'));
end;
finally
stl.Free;
reg.Free;
end;
end;
procedure TfrmHistory.FormShow(Sender: TObject);
begin
LoadHistory;
end;
procedure TfrmHistory.lvSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
begin
if Item = nil then Exit;
mmo.Lines.Text := Item.SubItems[3];
end;
procedure TfrmHistory.btnLoadClick(Sender: TObject);
begin
if lv.Selected = nil then Exit;
frmMain.LoadConfig(lv.Selected.SubItems[2], True);
Close;
end;
procedure TfrmHistory.lvDblClick(Sender: TObject);
begin
btnLoad.Click;
end;
procedure TfrmHistory.mmoKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_ESCAPE then Close;
end;
end.
|
unit TestuMVC;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, System.SysUtils, Vcl.Graphics, Winapi.Windows, System.Variants,
Vcl.Menus, Vcl.Dialogs, Vcl.Controls, Vcl.Forms, Winapi.Messages,
System.Classes, uMVC, ULogin;
type
// Test methods for class TFormMenu
TestTFormMenu = class(TTestCase)
strict private
FFormMenu: TFormMenu;
public
procedure SetUp; override;
procedure TearDown; override;
procedure TestDoLogin;
published
procedure TestFormCreate;
procedure TestPessoa1Click;
procedure TestSair1Click;
procedure TestPas1Click;
procedure TestCnae1Click;
procedure TestNaturezaJurdica1Click;
procedure TestEstado1Click;
procedure TestCidade1Click;
procedure TestCondomnio1Click;
end;
implementation
procedure TestTFormMenu.SetUp;
begin
FFormMenu := TFormMenu.Create;
end;
procedure TestTFormMenu.TearDown;
begin
FFormMenu.Free;
FFormMenu := nil;
end;
procedure TestTFormMenu.TestFormCreate;
var
Sender: TObject;
begin
// TODO: Setup method call parameters
FFormMenu.FormCreate(Sender);
// TODO: Validate method results
end;
procedure TestTFormMenu.TestPessoa1Click;
var
Sender: TObject;
begin
// TODO: Setup method call parameters
FFormMenu.Pessoa1Click(Sender);
// TODO: Validate method results
end;
procedure TestTFormMenu.TestSair1Click;
var
Sender: TObject;
begin
// TODO: Setup method call parameters
FFormMenu.Sair1Click(Sender);
// TODO: Validate method results
end;
procedure TestTFormMenu.TestPas1Click;
var
Sender: TObject;
begin
// TODO: Setup method call parameters
FFormMenu.Pas1Click(Sender);
// TODO: Validate method results
end;
procedure TestTFormMenu.TestCnae1Click;
var
Sender: TObject;
begin
// TODO: Setup method call parameters
FFormMenu.Cnae1Click(Sender);
// TODO: Validate method results
end;
procedure TestTFormMenu.TestNaturezaJurdica1Click;
var
Sender: TObject;
begin
// TODO: Setup method call parameters
FFormMenu.NaturezaJurdica1Click(Sender);
// TODO: Validate method results
end;
procedure TestTFormMenu.TestEstado1Click;
var
Sender: TObject;
begin
// TODO: Setup method call parameters
FFormMenu.Estado1Click(Sender);
// TODO: Validate method results
end;
procedure TestTFormMenu.TestCidade1Click;
var
Sender: TObject;
begin
// TODO: Setup method call parameters
FFormMenu.Cidade1Click(Sender);
// TODO: Validate method results
end;
procedure TestTFormMenu.TestCondomnio1Click;
var
Sender: TObject;
begin
// TODO: Setup method call parameters
FFormMenu.Condomnio1Click(Sender);
// TODO: Validate method results
end;
procedure TestTFormMenu.TestDoLogin;
var
ReturnValue: Boolean;
begin
ReturnValue := FFormMenu.DoLogin;
// TODO: Validate method results
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTFormMenu.Suite);
end.
|
procedure TNASINI.debug(fString :string; clear:boolean=false);
begin
if(self.z_debug) then
begin
if clear then
ClearDebug();
fString:=formatDateTime('tt',time())+' | '+ 'NAS_INI ' +' > ' +fString;
WriteLn(fString);
end;
end;
function TNASINI.GetINIKeys(section: string; maxCount: int32=128): array of Int32;
Var
cnt: int32;
str: String;
begin
repeat
str:= ReadINI(section, toStr(cnt), self.path + self.name);
inc(cnt);
if(toStr(str)='') then
break
else
begin
SetLength(result, cnt);
result[cnt-1] := cnt;
end;
until cnt=maxCount;
end;
function TNASINI.ReadINIKeyValues(section: string): array of String;
Var
i: integer;
iniKeys: array of Integer;
begin
iniKeys:=self.GetINIKeys(section);
SetLength(result, length(iniKeys));
for i := low(iniKeys) to High(iniKeys) do
result[i] := ReadINI(section, toStr(i), self.path + self.name);
end;
function TNASINI.GetLastINIKey(): Int32;
begin
result:=high(self.ReadINIKeyValues(self.section))+1;
end;
function TNASINI.ParseINIValues(): array of TNASINIPair;
Var
i: integer;
strArray: Array of String;
begin
strArray:=ReadINIKeyValues(self.section);
SetLength(result, length(strArray));
for i := low(strArray) to high(strArray) do
begin
result[i].NXT_PID := StrToInt(MultiBetween(strArray[i], 'NPID:', '~')[0]);
result[i].Simba_PID := StrToInt(MultiBetween(strArray[i], 'SPID:', '~')[0]);
result[i].Simba_TID := StrToInt(MultiBetween(strArray[i], 'STID:', '~')[0]);
result[i].key := toStr(i);
end;
self.debug('ParseINIValues > '+toStr(result));
end;
procedure TNASINI.DeclareINI(iniName: String='NAS_Pairs.ini'; section: String='Paired_Clients'; path: String=IncludePath+'NAS\');
begin
self.name := iniName;
self.section := section;
self.path := path;
self.fullPath := path+iniName;
self.debug('DeclareINI > name > '+toStr(self.name)+ ' > Section > '+toStr(self.section)+ ' > FullPath > '+toStr(self.fullPath));
end;
procedure TNASINI.WritePairToINI(pair: TNASPair);
Var lKey: int32;
begin
lKey:=self.GetLastINIKey;
self.debug('WritePairToINI > '+'WriteINI('+self.section+', '+toStr(lKey)+', '+'NPID:'+toStr(pair.NXT_PID)+'~'+'SPID:'+toStr(pair.Simba_PID)+'~STID:'+toStr(pair.Simba_TID)+'~)');
WriteINI(self.section, toStr(lKey), 'NPID:'+toStr(pair.NXT_PID)+'~'+'SPID:'+toStr(pair.Simba_PID)+'~STID:'+toStr(pair.Simba_TID)+'~', self.fullPath);
end;
procedure TNASINI.CleanupINI();
Var
i: int32;
vA: Array of TNASINIPair;
rs: boolean;
begin
vA:=parseINIValues();
for i := low(vA) to high(vA) do
begin
if(NAS.isTIDActive(vA[i].Simba_TID))=false then
begin
rs:=true;
end;
if(NAS.isPIDActive(vA[i].Simba_PID))=false then
begin
rs:=true;
end;
if (NAS.isPIDActive(vA[i].NXT_PID))=false then
begin
rs:=true;
end;
if(rs) then
begin
self.debug('CleanupINI > '+toStr(rs)+' > DeleteINI > Key: '+toStr(vA[i].key));
DeleteINI(self.section, vA[i].key, self.fullPath);
exit();
end;
end;
self.debug('CleanupINI > '+toStr(rs));
end;
function TNASINI.isPairedWithINI(pair: TNASPair): boolean;
Var
i: int32;
vA: Array of TNASINIPair;
rs: boolean;
begin
vA:=ParseINIValues();
for i := low(vA) to high(vA) do
begin
result:= (pair.NXT_PID=vA[i].NXT_PID)=true and (pair.Simba_PID=vA[i].Simba_PID)=true and (pair.Simba_TID=vA[i].Simba_TID)=true;
if(result) then
break;
end;
self.debug('isPairedWithINI > '+toStr(pair)+' > '+toStr(result));
end;
|
unit UArifmetic;
interface
uses
Variants;
function Roundery(T: Extended; Ro: Extended): Extended;
function ValueInArrray(Value: Integer; A: array of Integer): Boolean;
function VarToIntDef(const V: Variant; ADefault: Integer): Integer;
function VarToFloatDef(const V: Variant; ADefault: Extended): Extended;
implementation
function Roundery(T: Extended; Ro: Extended): Extended;
(* Округление
Roundery(2.43, 0.05) = 2.45
Roundery(2.42, 0.05) = 2.40 *)
begin
Result := Ro * Round((T + 0.01 * Ro) / Ro);
end;
function ValueInArrray(Value: Integer; A: array of Integer): Boolean;
// Проверяет находится ли в массиве елемент с таким же значением
var
i: Integer;
begin
Result := False;
for i := 0 to High(A) do
begin
Result := Value = A[i];
if Result then
Break;
end;
end;
function VarToIntDef(const V: Variant; ADefault: Integer): Integer;
begin
if not VarIsNull(V) then
Result := V
else
Result := ADefault;
end;
function VarToFloatDef(const V: Variant; ADefault: Extended): Extended;
begin
if not VarIsNull(V) then
Result := V
else
Result := ADefault;
end;
end.
|
{..............................................................................}
{ Summary Create a new Via object on a PCB document. }
{ Copyright (c) 2005 by Altium Limited }
{..............................................................................}
{..............................................................................}
Procedure ViaCreation;
Var
Board : IPCB_Board;
BR : TCoordRect;
Sheet : IPCB_Sheet;
Via : IPCB_Via;
PadCache : TPadCache;
Begin
// Grab the board interface representing the current PCB document in DXP.
Board := PCBServer.GetCurrentPCBBoard;
// If the board interface doesnt exist (no PCB document) then exit.
If Board = Nil Then Exit;
// Initialize the systems in the PCB Editor.
PCBServer.PreProcess;
Sheet := Board.PCBSheet;
// Create a Via object with the PCBObjectFactory method
// and then with the new attributes.
// Note we convert values in Mils to internal coordinates
// using the MilsToCoord function. All PCB objects locations and sizes
// have internal coordinate units where 1 mil = 10000 internal units
Via := PCBServer.PCBObjectFactory(eViaObject, eNoDimension, eCreate_Default);
// obtain the bottom left coordinates of the board outline
BR := Board.BoardOutline.BoundingRectangle;
Via.x := BR.Left + MilsToCoord(500);
Via.y := BR.Bottom + MilsToCoord(500);
// Via.x := Sheet.SheetX + MilsToCoord(500);
// Via.y := Sheet.SheetY + MilsToCoord(500);
Via.Size := MilsToCoord(50);
Via.HoleSize := MilsToCoord(20);
// Assign Via to the Top layer and bottom layer.
Via.LowLayer := eTopLayer;
Via.HighLayer := eBottomLayer;
// Set up Cache info for Via
// which consists mainly solder mask, paste mask and power plane values from design rules
Padcache := Via.GetState_Cache;
Padcache.ReliefAirGap := MilsToCoord(11);
Padcache.PowerPlaneReliefExpansion := MilsToCoord(11);
Padcache.PowerPlaneClearance := MilsToCoord(11);
Padcache.ReliefConductorWidth := MilsToCoord(11);
Padcache.SolderMaskExpansion := MilsToCoord(11);
Padcache.SolderMaskExpansionValid := eCacheManual;
Padcache.PasteMaskExpansion := MilsToCoord(11);
Padcache.PasteMaskExpansionValid := eCacheManual;
// Assign the new pad cache to the via
Via.SetState_Cache := Padcache;
// Put the new Via object on the board
Board.AddPCBObject(Via);
// Update the Undo System in DXP that a new VIa object has been added to the board
PCBServer.SendMessageToRobots(Board .I_ObjectAddress, c_Broadcast, PCBM_BoardRegisteration, Via.I_ObjectAddress);
// Finalize the systems in the PCB Editor.
PCBServer.PostProcess;
// Refresh PCB screen
Client.SendMessage('PCB:Zoom', 'Action=Redraw' , 255, Client.CurrentView);
End;
{..............................................................................}
{..............................................................................}
|
unit Lookup;
{*******************************************************************************
Description : data module containing all of the tables used as lookup tables
Modifications:
--------------------------------------------------------------------------------
Date UserID Description
--------------------------------------------------------------------------------
11-17-2005 GN01 remove lck files if present
*******************************************************************************}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
BDE, DB, DBTables, Wwtable, Wwdatsrc, Filectrl;
type
TmodLookup = class(TDataModule)
tblScaleText: TwwTable;
tblQstnText: TwwTable;
tblHeadText: TwwTable;
tblScale: TTable;
srcScale: TDataSource;
tblHeading: TwwTable;
srcHeading: TwwDataSource;
tblQuestion: TTable;
srcQuestion: TDataSource;
tblUsage: TTable;
tblRecode: TTable;
tblCodeText: TTable;
dbQstnLib: TDatabase;
tblReview: TwwTable;
tblQstnTextText: TBlobField;
tblQstnTextCore: TIntegerField;
tblQstnTextLangID: TIntegerField;
tblQstnTextReview: TBooleanField;
procedure LookupCreate(Sender: TObject);
procedure CodeTextFilterRecord(DataSet: TDataSet;
var Accept: Boolean);
private
{ Private declarations }
public
{ Public declarations }
end;
var
modLookup: TmodLookup;
implementation
uses Data, DBRichEdit, Common;
{$R *.DFM}
{ INITIALIZATION }
procedure TmodLookup.LookupCreate(Sender: TObject);
var s,nd : string;
begin
Check(dbiInit(Nil));
//GN01
try
nd := aliaspath('PRIV');
SaveTempDirInRegistry(nd);
deldotstar(nd+'\p*.lck')
except
end;
{ try
nd := aliaspath('Question');
deldotstar(nd+'\p*.lck')
except
end;
ND := '\\nrc11\qualpro\QP_Lib\NET';
s := AliasPath('Question');
if directoryexists(paramstr(1)) then
ND := paramstr(1)
else if (directoryexists(copy(s,1,length(s)-7)+'net')) then
ND := copy(s,1,length(s)-7)+'net';
if dbQstnLib.connected then dbQstnlib.close;
try
session.netfiledir := nd;
tblQuestion.Open;
tblQuestion.Close;
except
on e:eDBEngineError do begin
nd := uppercase(e.message);
delete(nd,1,pos('DIRECTORY: ',nd)+10);
delete(nd,pos('FILE:',nd)-2,length(nd));
session.netfiledir := ND;
end;
end;
if copy(s,length(s),1) = '\' then delete(s,length(s),1);
if (not FileExists(s+'\Questions.DB')) or (UpperCase(paramstr(1))='/Q') then begin
s := InputBox('Find Library','Specify the directory for the Question Library',s);
if copy(s,length(s),1) = '\' then delete(s,length(s),1);
while not FileExists(s+'\Questions.DB') do begin
s := InputBox('Find Library','Specify the directory for the Question Library',s);
if copy(s,length(s),1) = '\' then delete(s,length(s),1);
end;
if uppercase(s) <> uppercase(copy(dbQstnLib.params[0],6,255)) then
with dbQstnLib do begin
Connected := False;
params.clear;
params.add('PATH='+s);
Connected := True;
end;
end;}
tblQuestion.Open;
tblHeading.Open;
tblScale.Open;
tblHeadText.Open;
tblQstnText.Open;
tblScaleText.Open;
tblCodeText.Open;
tblRecode.Open;
end;
{ CODE SUBSTITUTION FILTER }
{ !!! this is the filter responsible for determining what text gets displayed
in place of a code !!! }
procedure TmodLookup.CodeTextFilterRecord(DataSet: TDataSet; var Accept: Boolean);
begin
Accept := ((( DataSet[ 'Age' ] = copy(vAge,1,1) ) OR ( DataSet[ 'Age' ] = Null )) AND
(( DataSet[ 'Sex' ] = copy(vSex,1,1) ) OR ( DataSet[ 'Sex' ] = Null )) AND
(( DataSet[ 'Doctor' ] = copy(vDoc,1,1) ) OR ( DataSet[ 'Doctor' ] = Null )));
end;
end.
|
unit Common.Entities.Player;
interface
uses
Spring, Neon.Core.Attributes,
System.Generics.Collections;
type
TBetState=(btNone,btBet,btPass,btHold);
TTeam=(ttTeam1,ttTeam2,ttNone);
TPlayer=class
private
FName:String;
FScore: Integer;
FBetState: TBetState;
FTeam: TTeam;
public
constructor Create(const AName:String);overload;
// constructor Create;
destructor Destroy;override;
function ToString:String;override;
[NeonInclude(IncludeIf.Always)]
property Name:String read FName write FName;
property BetState:TBetState read FBetState write FBetState;
property Score: Integer read FScore write FScore;
property Team:TTeam read FTeam write FTeam;
procedure Assign(const ASource:TPlayer);virtual;
end;
TPlayers<T:TPlayer>=class(TObjectList<T>)
public
function Clone<T2:TPlayer, constructor>:TPlayers<T2>;
function Find(AName:String):T;
end;
implementation
uses
System.SysUtils
;
{ TPlayer }
procedure TPlayer.Assign(const ASource: TPlayer);
begin
FName:=ASource.Name;
FScore:=ASource.Score;
FBetState:=ASource.BetState;
FTeam:=ASource.FTeam;
end;
constructor TPlayer.Create(const AName: String);
begin
inherited Create;
FName:=AName;
FBetState:=btNone;
FScore:=0;
end;
destructor TPlayer.Destroy;
begin
inherited;
end;
function TPlayer.ToString: String;
const
FMT = 'Name: %s';
begin
Result := Format(FMT, [FName]);
end;
{ TPlayers }
function TPlayers<T>.Clone<T2>: TPlayers<T2>;
var p:T;
p2:T2;
begin
Result:=TPlayers<T2>.Create;
for p in Self do begin
p2:=T2.Create;
p2.Assign(p);
Result.Add(p2)
end;
end;
function TPlayers<T>.Find(AName: String): T;
var itm:T;
begin
Result:=nil;
AName:=AnsiUppercase(AName);
for itm in Self do begin
if AnsiUppercase(itm.Name)=AName then begin
Result:=itm;
Break;
end;
end;
end;
end.
|
namespace clockapplet;
// Sample applet project by Brian Long (http://blong.com)
// Translated from Michael McGuffin's Clock1 applet
// from http://profs.etsmtl.ca/mmcguffin/learn/java/09-clocks
interface
uses
java.util.*,
java.applet.*,
java.awt.*,
java.text.*;
type
ClockApplet = public class(Applet, Runnable)
private
var width, height: Integer;
var t: Thread := nil;
var threadSuspended: Boolean;
var hours: Integer := 0;
var minutes: Integer := 0;
var seconds: Integer := 0;
var timeString: String := '';
method drawHand(angle: Double; radius: Integer; g: Graphics);
method drawWedge(angle: Double; radius: Integer; g: Graphics);
public
method init(); override;
method paint(g: Graphics); override;
method start; override;
method stop; override;
method run;
end;
implementation
method ClockApplet.init();
begin
width := Size.width;
height := Size.height;
Background := Color.BLACK;
end;
method ClockApplet.stop;
begin
threadSuspended := true;
end;
method ClockApplet.start;
begin
if t = nil then
begin
t := new Thread(self);
t.setPriority(Thread.MIN_PRIORITY);
threadSuspended := false;
t.start()
end
else
begin
if threadSuspended then
begin
threadSuspended := false;
locking Self do
notify
end
end
end;
method ClockApplet.run;
begin
try
while true do
begin
// Here's where the thread does some work
var cal := Calendar.Instance;
hours := cal.get(Calendar.HOUR_OF_DAY);
if hours > 12 then
hours := hours - 12;
minutes := cal.get(Calendar.MINUTE);
seconds := cal.get(Calendar.SECOND);
var date := cal.Time;
// Note that some (maybe older) browsers interpret the 'default' timezone as
// something different to the local timezone, so this string might show the
// wrong time if using the commented code - the hands, however, will be right
//var formatter := new SimpleDateFormat('hh:mm:ss', Locale.getDefault());
//timeString := formatter.format(date);
timeString := date.toString();
// Now the thread checks to see if it should suspend itself
if threadSuspended then
locking Self do
while threadSuspended do
wait;
repaint();
t.sleep(1000) // interval given in milliseconds
end
except
on InterruptedException do
//Nothing
end;
end;
method ClockApplet.drawHand(angle: Double; radius: Integer; g: Graphics);
begin
angle := angle - 0.5 * Math.PI;
var x := Integer(radius * Math.cos(angle));
var y := Integer(radius * Math.sin(angle));
g.drawLine(width / 2, height / 2, width / 2 + x, height / 2 + y)
end;
method ClockApplet.drawWedge(angle: Double; radius: Integer; g: Graphics);
begin
angle := angle - 0.5 * Math.PI;
var x := Integer(radius * Math.cos(angle));
var y := Integer(radius * Math.sin(angle));
angle := angle + 2 * Math.PI / 3;
var x2 := Integer(5 * Math.cos(angle));
var y2 := Integer(5 * Math.sin(angle));
angle := angle + 2 * Math.PI / 3;
var x3 := Integer(5 * Math.cos(angle));
var y3 := Integer(5 * Math.sin(angle));
g.drawLine(width / 2 + x2, height / 2 + y2, width / 2 + x, height / 2 + y);
g.drawLine(width / 2 + x3, height / 2 + y3, width / 2 + x, height / 2 + y);
g.drawLine(width / 2 + x2, height / 2 + y2, width / 2 + x3, height / 2 + y3)
end;
method ClockApplet.paint(g: Graphics);
begin
g.setColor(Color.GRAY);
drawWedge(2 * Math.PI * hours / 12, width / 5, g);
drawWedge(2 * Math.PI * minutes / 60, width / 3, g);
drawHand(2 * Math.PI * seconds / 60, width / 2, g);
g.setColor(Color.WHITE);
g.drawString(timeString, 10, height - 10)
end;
end. |
unit uProfessorDAO;
interface
uses system.SysUtils, uDAO, uProfessor, uEndereco, system.Generics.Collections,
FireDac.comp.Client;
type
TProfessorDAO = class(TconectDAO)
private
FListaProfessor: TObjectList<TProfessor>;
procedure CriaLista(Ds: TFDQuery);
public
Constructor Create;
Destructor Destroy; override;
function CadastrarProfessor(pProfessor: TProfessor;
pEndereco: TEndereco): boolean;
function CadastrarProfessor_Curso(pProfessor: TProfessor): boolean;
function PesquisaProfessor(pProfessor: TProfessor): TObjectList<TProfessor>;
end;
implementation
{ TProfessorDAO }
function TProfessorDAO.CadastrarProfessor(pProfessor: TProfessor;
pEndereco: TEndereco): boolean;
var
SQL: string;
begin
SQL := 'select id_endereco from endereco '+
'where id_endereco not in (select id_endereco from aluno) '+
'and id_endereco not in (select id_endereco from professor)';
FQuery := RetornarDataSet(SQL);
pEndereco.id := FQuery.fieldByName('id_endereco').AsInteger;
SQL := 'INSERT INTO professor VALUES(default, ' + QuotedSTR(pProfessor.Nome) +
', ' + QuotedSTR(InttoStr(pEndereco.id)) + ', ' +
QuotedSTR(FormatDateTime('dd/mm/yyyy', pProfessor.DataNasc)) + ', ' +
QuotedSTR(pProfessor.Cpf) + ', ' + QuotedSTR(pProfessor.rg) + ', ' +
QuotedSTR(pProfessor.CNPJ) + ', ' + QuotedSTR(pProfessor.contato) + ', ' +
QuotedSTR(pProfessor.email) + ')';
result := executarComando(SQL) > 0;
end;
function TProfessorDAO.CadastrarProfessor_Curso(pProfessor: TProfessor)
: boolean;
var
I: integer;
SQL: string;
begin
for I := 0 to pProfessor.Tamanho - 1 do
if pProfessor.Cursos[I] <> '' then
begin
SQL := 'SELECT id_Professor FROM professor WHERE cpf = ' +
QuotedSTR(pProfessor.Cpf);
FQuery := RetornarDataSet(SQL);
pProfessor.id := FQuery.fieldByName('id_professor').AsInteger;
SQL := 'SELECT id_curso FROM curso WHERE nome = ' +
QuotedSTR(pProfessor.Cursos[I]);
FQuery := RetornarDataSet(SQL);
pProfessor.Curso := FQuery.fieldByName('id_curso').AsString;
SQL := 'INSERT INTO professor_curso VALUES (' +
QuotedSTR(InttoStr(pProfessor.id)) + ', ' +
QuotedSTR(pProfessor.Curso) + ')';
result := executarComando(SQL) > 0;
end;
end;
constructor TProfessorDAO.Create;
begin
inherited;
FListaProfessor := TObjectList<TProfessor>.Create;
end;
procedure TProfessorDAO.CriaLista(Ds: TFDQuery);
var
I, count: integer;
SQL: string;
begin
I := 0;
FListaProfessor.Clear;
while not Ds.eof do
begin
FListaProfessor.Add(TProfessor.Create);
FListaProfessor[I].id := Ds.fieldByName('id_professor').AsInteger;
FListaProfessor[I].Nome := Ds.fieldByName('nome').AsString;
FListaProfessor[I].IDEndereco := Ds.fieldByName('id_endereco').AsInteger;
FListaProfessor[I].DataNasc := Ds.fieldByName('data_nasc').AsDateTime;
FListaProfessor[I].Cpf := Ds.fieldByName('cpf').AsString;
FListaProfessor[I].rg := Ds.fieldByName('rg').AsString;
FListaProfessor[I].CNPJ := Ds.fieldByName('cnpj').AsString;
FListaProfessor[I].contato := Ds.fieldByName('telefone').AsString;
FListaProfessor[I].email := Ds.fieldByName('email').AsString;
SQL := 'SELECT id_curso FROM professor_curso WHERE id_professor = ' +
QuotedSTR(Ds.fieldByName('id_professor').AsString);
FQuery2 := RetornarDataSet2(SQL);
while not FQuery2.eof do
begin
FListaProfessor[I].Tamanho := FListaProfessor[I].Tamanho + 1;
SetLength(FListaProfessor[I].Cursos, FListaProfessor[I].Tamanho);
FListaProfessor[I].Cursos[FListaProfessor[I].Tamanho - 1] :=
FQuery2.fieldByName('id_curso').AsString;
FQuery2.Next;
end;
for count := 0 to FListaProfessor[I].Tamanho - 1 do
begin
SQL := 'SELECT nome FROM curso WHERE id_curso = ' +
QuotedSTR(FListaProfessor[I].Cursos[count]);
FQuery2 := RetornarDataSet2(SQL);
FListaProfessor[I].Cursos[count] := FQuery2.fieldByName('nome').AsString;
end;
Ds.Next;
I := I + 1;
end;
end;
destructor TProfessorDAO.Destroy;
begin
inherited;
if Assigned(FListaProfessor) then
FreeAndNil(FListaProfessor);
end;
function TProfessorDAO.PesquisaProfessor(pProfessor: TProfessor)
: TObjectList<TProfessor>;
var
SQL: string;
begin
Result := nil;
SQL := 'SELECT * FROM professor WHERE nome LIKE ' + QuotedStr('%' + pProfessor.Nome + '%') +
'and cnpj LIKE '+ QuotedStr('%' + pProfessor.CNPJ + '%') + ' and telefone LIKE '+ QuotedStr('%' + pProfessor.Contato + '%') +
'and id_professor in (select id_professor from professor_curso where id_curso in (select id_curso from curso where nome like '
+ QuotedStr('%' + pProfessor.Curso + '%') + ')) order by nome';
FQuery := RetornarDataSet(SQL);
if not (FQuery.IsEmpty) then
begin
CriaLista(FQuery);
Result:= FListaProfessor;
end;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, Forms,
Menus, ExtCtrls, ComCtrls, StdCtrls, ImgList, mxOneInstance, Db, Grids,
DBGrids, DBTables, Buttons, adLabelMemo, ADODB;
type
TForm1 = class(TForm)
MainMenu1: TMainMenu;
Cadastrodelistas1: TMenuItem;
ProdutosNaslistas1: TMenuItem;
StatusBar1: TStatusBar;
ImageList1: TImageList;
mxOneInstance1: TmxOneInstance;
DBGrid1: TDBGrid;
DataSource1: TDataSource;
Memo1: TMemo;
rg: TRadioGroup;
ADOConnetion: TADOConnection;
Query1: TADOQuery;
procedure ProdutosNaslistas1Click(Sender: TObject);
procedure Cadastrodelistas1Click(Sender: TObject);
procedure msgderodape(msg:String);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure DesabilitaMenu(sender:Tobject);
procedure HabilitaMenu(sender:Tobject);
procedure FormCreate(Sender: TObject);
function lerParametro(l:string):string;
procedure AppException(Sender: TObject; E: Exception);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure mxOneInstance1InstanceExists(Sender: TObject);
function ProximoValor(Sender: TObject; tabela,campo:string):String;
function ajustadataInicioDoMes(data:string):String;
function Ajustadata(data:string):String;
procedure rgClick(Sender: TObject);
procedure ADOConnetionExecuteComplete(Connection: TADOConnection;
RecordsAffected: Integer; const Error: Error;
var EventStatus: TEventStatus; const Command: _Command;
const Recordset: _Recordset);
procedure ADOConnetionWillExecute(Connection: TADOConnection;
var CommandText: WideString; var CursorType: TCursorType;
var LockType: TADOLockType; var CommandType: TCommandType;
var ExecuteOptions: TExecuteOptions; var EventStatus: TEventStatus;
const Command: _Command; const Recordset: _Recordset);
private
{ Private declarations }
public
{ Public declarations }
end;
CONST
PATH = 'c:\listas\';
ARQ_PARAMETROS = PATH + 'ListaCasamento.ini';
ARQ_ERROS = PATH + 'ErrorLog.txt';
VERSAO = '1.36';
TITULO = 'Gerenciador de Listas - '+ VERSAO;
var
Form1: TForm1;
implementation
uses Unit2, Unit3, Unit5, Unit4,unit6;
{$R *.DFM}
function Tform1.ajustadataInicioDoMes(data:string):String;
var
InicioDoMes:string;
begin
data:=DateToStr(now);
ajustadataInicioDoMes := copy(data,04,02)+ '/01/'+ copy(data,07,04);
end;
function Tform1.Ajustadata(data:string):String;
begin
ajustadata := copy(data,04,02)+'/'+copy(data,01,02)+ '/' + copy(data,07,04);
end;
function TForm1.ProximoValor(Sender: TObject; tabela,campo:string):String;
begin
with query1.sql do
begin
clear;
add('Select max ('+campo+') from '+ tabela);
end;
query1.open;
if dbgrid1.fields[0].AsString <> '' then
ProximoValor := IntToStr( StrToInt(dbgrid1.fields[0].AsString) +1 );
end;
procedure TForm1.AppException(Sender: TObject; E: Exception);
var
dest:textfile;
begin
assignFIle(dest, ARQ_ERROS );
if FileExists(ARQ_ERROS) = true then
append(dest)
else
rewrite(dest);
writeln(dest, dateToSTr(now) + ' ' + timetoStr(now)+ ' ' + E.message );
closefile(dest);
msgderodape('Erro, consulte o log!!!');
end;
procedure TForm1.ProdutosNaslistas1Click(Sender: TObject);
begin
rg.visible := false;
Application.CreateForm(TProdutosNaLista, ProdutosNaLista);
ProdutosNaLista.show;
end;
procedure TForm1.Cadastrodelistas1Click(Sender: TObject);
begin
Application.CreateForm(TCadListas, CadListas);
CadListas.show;
end;
procedure tform1.msgderodape(msg:String);
begin
statusbar1.panels[0].text:= msg;
end;
procedure Tform1.HabilitaMenu(sender:Tobject);
begin
form1.Menu:= form1.mainmenu1;
rg.visible := true;
end;
procedure Tform1.DesabilitaMenu(sender:Tobject);
begin
rg.visible := false;
form1.Menu:= nil;
end;
function TForm1.lerParametro(l:string):string;
begin
while pos('=',l) > 0 do
delete(l,01,01);
lerParametro := l;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
ADOConnetion.Connected := true;
ShortDateFormat := 'dd/mm/yyyy';
with form1 do
begin
Caption := TITULO;
top := -3;
Left:= 800 - form1.Width;
end;
Application.OnException := form1.AppException;
memo1.lines.Loadfromfile( ARQ_PARAMETROS );
statusbar1.Panels[1].text := 'Loja: ' + lerParametro(memo1.lines[0]);
memo1.lines[2] := copy(memo1.lines[2],01,pos('=',memo1.lines[2])) + VERSAO;
if form1.lerParametro(memo1.lines[3]) = 'S' then
rg.itemIndex := 1;
memo1.lines.SaveToFile( arq_parametros );
memo1.lines.SaveToFile('ListaCasamento.ini');
end;
procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
{ if (ProdutosNaLista <> nil) or( form5 <> nil) or(cadlistas <> nil) or ( Fimpressao <> nil) then
begin
application.MessageBox(pchar(' Feche as janelas que estão abertas!!! '),pchar(form1.caption),mb_ok + mb_iconwarning);
canclose := false;
end
}
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
deleteFile(BAT_DE_IMPRESSAO);
deleteFile(ARQ_DE_IMPRESSAO);
deleteFile(ARQ_DADOS);
DELETEFILE(ARQ_PROD);
end;
procedure TForm1.mxOneInstance1InstanceExists(Sender: TObject);
begin
application.messagebox(' Já existe uma instância deste programa aberta !!!! ',TITULO, MB_OK + MB_ICONERROR);
application.terminate
end;
procedure TForm1.rgClick(Sender: TObject);
begin
if rg.ItemIndex = 0 then
memo1.lines[3] := '04 Mostrar Todas as listas=N'
else
memo1.lines[3] := '04 Mostrar Todas as listas=S';
memo1.lines.SaveToFile( ARQ_PARAMETROS );
end;
procedure TForm1.ADOConnetionExecuteComplete(Connection: TADOConnection; RecordsAffected: Integer; const Error: Error; var EventStatus: TEventStatus; const Command: _Command; const Recordset: _Recordset);
begin
screen.Cursor:= crDefault;
end;
procedure TForm1.ADOConnetionWillExecute(Connection: TADOConnection; var CommandText: WideString; var CursorType: TCursorType; var LockType: TADOLockType; var CommandType: TCommandType; var ExecuteOptions: TExecuteOptions; var EventStatus: TEventStatus; const Command: _Command; const Recordset: _Recordset);
begin
screen.Cursor:= crhourglass;
end;
end.
|
// Demo application for Voro+GraphObjects
unit main;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls,
Vcl.StdCtrls,
GraphObjects,
GLMaterial,
GLCadencer,
GLWin32Viewer,
GLCrossPlatform,
GLBaseClasses,
GLScene,
Voro;
type
TForm1 = class(TForm)
GroupBox1: TGroupBox;
CheckBox1: TCheckBox;
CheckBox2: TCheckBox;
CheckBox3: TCheckBox;
PaintBox1: TPaintBox;
Button1: TButton;
Label1: TLabel;
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
GLCadencer1: TGLCadencer;
GLMaterialLibrary1: TGLMaterialLibrary;
procedure PaintBox1Paint(Sender: TObject);
procedure PaintBox1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure CheckBox1Click(Sender: TObject);
procedure PaintBox1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure PaintBox1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
private
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
var
List: TList;
Vor: TVoronoi;
mx, my, i: Integer;
down: boolean;
procedure TForm1.PaintBox1Paint(Sender: TObject);
var
z: Integer;
begin
PaintBox1.Canvas.Brush.Color := clBlack;
PaintBox1.Canvas.FillRect(Rect(0, 0, 1200, 1000));
if List = nil then
exit;
PaintBox1.Canvas.Font.Color := clWhite;
for z := 0 to List.Count - 1 do
begin
TGraphObject(List.items[z]).draw;
if (TObject(List.items[z]) is TGPoint) and CheckBox3.Checked then
PaintBox1.Canvas.TextOut(round(TGPoint(List.items[z]).GetX + 1),
round(TGPoint(List.items[z]).GetY + 1), inttostr(z));
end;
end;
procedure TForm1.PaintBox1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
mx := X;
my := Y;
Form1.Caption := inttostr(mx) + ' ' + inttostr(my);
if down then
begin
TGPoint(List.items[i]).MoveTo(X, Y);
CheckBox1Click(Form1);
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
List := TList.Create;
down := false;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
List.Clear;
PaintBox1.OnPaint(Form1);
end;
procedure TForm1.CheckBox1Click(Sender: TObject);
begin
Vor := TVoronoi.Create(PaintBox1.Canvas, List);
Vor.ClearLines;
Vor.CalcVoronoi(CheckBox1.Checked, CheckBox2.Checked);
Vor.Free;
PaintBox1.OnPaint(Form1);
end;
procedure TForm1.PaintBox1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
p: TGPoint;
z: Integer;
begin
p := TGPoint.Create(X, Y, nil, nil);
p.closeDist := 5;
for z := 0 to List.Count - 1 do
begin
if TObject(List.items[z]) is TGPoint then
if p.Match(TGPoint(List.items[z])) then
begin
if (Button = TMouseButton.mbRight) then
TGPoint(List.items[z]).Delete(true)
else
begin
down := true;
i := z;
end;
CheckBox1Click(Form1);
exit;
end;
end;
p.Free;
TGPoint.Create(X, Y, List, PaintBox1.Canvas);
CheckBox1Click(Form1);
end;
procedure TForm1.PaintBox1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
down := false;
end;
end.
|
(*
Design and define a class hierarchy, with inheritance, and test it. The first
object is a car, which can store and print its issue year and mileage, and which
can determine the average mileage per year. The second object is a car, which
can store its registration number, brand, issue year, mileage, and the lastname
of its owner, which can print the said parameters and the average mileage per
year.
*)
uses SysUtils;
type Car = class(TObject)
issueYear: Cardinal;
mileage: Cardinal;
procedure print();
function mileagePerYear(): Real;
end;
procedure Car.print();
begin
WriteLn('issue year: ', issueYear);
WriteLn('mileage: ', mileage);
end;
function Car.mileagePerYear();
begin
Result := mileage / (CurrentYear() - issueYear);
end;
type CarExt = class(Car)
regNumber: Cardinal;
brand: String;
ownerLastName: String;
procedure print();
end;
procedure CarExt.print();
begin
WriteLn('registration number: ', regNumber);
WriteLn('brand: ', brand);
WriteLn('owner last name: ', ownerLastName);
inherited print();
end;
var car1: Car;
var car2: CarExt;
begin
car1 := Car.Create();
car1.issueYear := 1992;
car1.mileage := 288000;
car1.print();
WriteLn(car1.mileagePerYear():4:2);
WriteLn('');
car2 := CarExt.Create();
car2.regNumber := 343250;
car2.brand := 'Ford';
car2.ownerLastName := 'Smith';
car2.issueYear := 1988;
car2.mileage := 320000;
car2.print();
WriteLn(car2.mileagePerYear():4:2);
end.
|
unit P4InfoVarejo_Constantes;
interface
resourcestring
mensagem_01 = 'Não existem registros com este critério.';
mensagem_02 = 'Impressão do cheque não foi possível. '+chr(10)+chr(13)+
'Código do movimento bancário está vazio.';
mensagem_03 = 'Impressão do cheque não foi possível. '+chr(10)+chr(13)+
'Nenhum registro foi encontrado com o código do movimento bancário.';
mensagem_04 = 'Impressão do cheque não foi possível. '+chr(10)+chr(13)+
'Impressão do cheque não está configurado para este banco.';
mensagem_05 = 'Não existem contatos para esta transportadora.';
mensagem_06 = 'Não existem contatos para este representante.';
mensagem_07 = 'Impressão não foi possível.'+chr(10)+chr(13)+
'Duplicata inexistente no banco de dados';
mensagem_08 = 'Não existem clientes atendidos para esta transportadora.';
mensagem_09 = 'Não existem clientes para este representante.';
mensagem_10 = 'Não existe produção com o critério especificado.';
mensagem_11 = 'Produto inexistente!';
const
P4InfoVarejo_moeda = '###,###,##0.00';
P4InfoVarejo_decimal4= '###,###,##0.0000';
P4InfoVarejo_decimal3= '###,###,##0.000';
P4InfoVarejo_decimal2= '###,###,##0.00';
P4InfoVarejo_decimal1= '###,###,##0.0';
P4InfoVarejo_integer = '###,###,##0';
P4InfoVarejo_dtbanco = 'mm/dd/yyyy';
P4InfoVarejo_hrbanco = 'hh:mm:ss';
P4InfoVarejo_dtabrev = 'dd/mm/yyyy';
P4InfoVarejo_Sintegra = '###,###,##0000';
P4InfoVarejo_KeySearch = 121;
P4InfoVarejo_keymove = 117;
P4InfoVarejo_KeyExibeInformacao = 123;
ad_control_mora_diaria = 6.00;
//Cript = '~%()*ẹ¼_ñª¬½¡Ü«»-./:;<=>?{|}ïöü~"¿#¢£¥Ñ@%>§!Ç$+ñäåç`&ëïÄæØ';
Cript = 'ABCDEFGHIJKLMNOPQRSTUVXYWZabcdefghijklmnopqrstuvxywz1234567890';
Decript = '0123456789abcdefghijklmnopqrstuvxywzABCDEFGHIJKLMNOPQRSTUVXYWZ';
implementation
end.
|
{
In the Main Form of application
}
procedure TMainUI.DoEnterAsTab(var Msg: TMsg; var Handled: Boolean);
begin
if Msg.Message = WM_KEYDOWN then
begin
if (not (Screen.ActiveControl is TCustomMemo)) and (not (Screen.ActiveControl is TButtonControl)) then
begin
if Msg.wParam = VK_RETURN then
Screen.ActiveForm.Perform(WM_NextDlgCtl, 0, 0);
end;
end;
end;
procedure TMainUI.FormCreate(Sender: TObject);
begin
// At the end of the method, add:
Application.OnMessage := DoEnterAsTab;
end;
|
unit TurboDocument;
interface
uses
LrDocument, Design;
type
TTurboDocument = class(TLrDocument)
private
FDesign: TDesignForm;
public
constructor Create; override;
destructor Destroy; override;
procedure Open(const inFilename: string); override;
procedure Save; override;
property Design: TDesignForm read FDesign;
end;
implementation
{ TTurboDocument }
constructor TTurboDocument.Create;
begin
inherited;
FDesign := TDesignForm.Create(nil);
end;
destructor TTurboDocument.Destroy;
begin
Design.Free;
inherited;
end;
procedure TTurboDocument.Save;
begin
Design.SaveToFile(Filename);
inherited;
end;
procedure TTurboDocument.Open(const inFilename: string);
begin
Filename := inFilename;
Design.LoadFromFile(Filename);
inherited;
end;
end.
|
unit HashValue_U;
// Description: Hash Value
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
sysutils;
type
{$TYPEINFO ON} // Needed to allow "published"
// Exceptions...
EHashValue = class(Exception);
EHashValueInvalidValue = EHashValue;
// This use of this is *strongly* discouraged...
THashArray = array [0..63] of byte;
THashValue = class
protected
FValue: array of byte;
function GetLength(): integer; virtual;
function GetValueAsBinary(): string; virtual;
function GetValueAsASCIIHex(): string; virtual;
procedure SetValueAsBinary(newValue: string); virtual;
procedure SetValueAsASCIIHex(newValue: string); virtual;
public
constructor Create(); virtual;
destructor Destroy(); override;
procedure Clear(); virtual;
published
property Length: integer read GetLength;
property ValueAsBinary: string read GetValueAsBinary write SetValueAsBinary;
property ValueAsASCIIHex: string read GetValueAsASCIIHex write SetValueAsASCIIHex;
function GetValueAsArray(): THashArray; virtual;
procedure SetValueAsArray(newValue: THashArray; bits: integer); virtual;
end;
implementation
uses
SDUGeneral,
Math;
constructor THashValue.Create();
begin
inherited Create();
SetLength(FValue, 0);
end;
destructor THashValue.Destroy();
begin
Clear();
inherited;
end;
procedure THashValue.Clear();
var
i: integer;
begin
for i:=low(FValue) to high(FValue) do
begin
FValue[i] := random(256);
end;
end;
function THashValue.GetLength(): integer;
begin
Result := system.Length(FValue);
end;
function THashValue.GetValueAsArray(): THashArray;
var
i: integer;
maxElem: integer;
retVal: THashArray;
begin
maxElem := min(
system.Length(FValue),
system.Length(retVal)
);
for i:=low(retVal) to high(retVal) do
begin
retVal[i] := 0;
end;
for i:=0 to (maxElem-1) do
begin
retVal[low(retVal) + i] := FValue[low(FValue) + i];
end;
Result := retVal;
end;
function THashValue.GetValueAsBinary(): string;
var
i: integer;
retVal: string;
begin
retVal := '';
for i:=low(FValue) to high(FValue) do
begin
retVal := retVal + char(FValue[i]);
end;
Result := retVal;
end;
function THashValue.GetValueAsASCIIHex(): string;
var
i: integer;
retVal: string;
begin
retVal := '';
for i:=low(FValue) to high(FValue) do
begin
retVal := retVal + inttohex(FValue[i], 2);
end;
Result := retVal;
end;
procedure THashValue.SetValueAsArray(newValue: THashArray; bits: integer);
var
i: integer;
maxElem: integer;
begin
Clear();
SetLength(FValue, (bits div 8));
// Clear, in case number of bits is greater than the array passed in
for i:=low(FValue) to high(FValue) do
begin
FValue[i] := 0;
end;
maxElem := min(
system.Length(FValue),
system.Length(newValue)
);
for i:=0 to (maxElem-1) do
begin
FValue[low(FValue) + i] := newValue[low(newValue) + i];
end;
end;
procedure THashValue.SetValueAsBinary(newValue: string);
var
i: integer;
begin
Clear();
SetLength(FValue, system.length(newValue));
for i:=1 to system.length(newValue) do
begin
FValue[low(FValue) + i - 1] := byte(newValue[i]);
end;
end;
procedure THashValue.SetValueAsASCIIHex(newValue: string);
var
i: integer;
byteAsASCIIHex: string;
byteValue: integer;
begin
Clear();
// Sanity check; must have an even number of hex characters
if ((system.length(newValue) mod 2) = 1) then
begin
raise EHashValueInvalidValue.Create('Invalid number of hex digits in hash value');
end;
SetLength(FValue, system.Length(newValue));
byteAsASCIIHex := '';
for i:=1 to system.length(newValue) do
begin
byteAsASCIIHex := byteAsASCIIHex + newValue[i];
if (system.length(byteAsASCIIHex) = 2) then
begin
if not(SDUTryHexToInt(byteAsASCIIHex, byteValue)) then
begin
raise EHashValueInvalidValue.Create('Invalid hex digits in hash value');
end;
FValue[low(FValue) + i - 1] := byteValue;
byteAsASCIIHex := '';
end;
end;
end;
END.
|
unit UBitList;
interface
type
TBitList = ^TBit;
TBit = record
bit: Boolean;
next: TBitList;
end;
procedure createList(var bitList: TBitList);
procedure insertList(bitList: TBitList; bit: Boolean);
procedure deleteList(bitList: TBitList);
procedure clearList(bitList: TBitList);
procedure clearAfterN(bitList: TBitList; num: Integer);
procedure destroyList(var bitList: TBitList);
function toString(bitList: TBitList):String;
function lengthList(bitList: TBitList):Integer;
function isEmptyList(bitList: TBitList):Boolean;
implementation
procedure createList(var bitList: TBitList);
begin
new(bitList);
bitList^.next := nil;
end;
procedure insertList(bitList: TBitList; bit: Boolean);
var
temp: TBitList;
begin
new(temp);
temp^.bit := bit;
temp^.next := bitList^.next;
bitList^.next := temp;
end;
procedure deleteList(bitList: TBitList);
var
temp: TBitList;
begin
if bitList^.next <> nil then
begin
temp := bitList^.next;
bitList^.next := temp^.next;
dispose(temp);
end;
end;
procedure clearList(bitList: TBitList);
begin
if bitList <> nil then
while bitList^.next <> nil do
deleteList(bitList);
end;
procedure clearAfterN(bitList: TBitList; num: Integer);
begin
while (bitList^.next <> nil) and (num > 0) do
begin
dec(num);
bitList := bitList^.next;
end;
clearList(bitList);
end;
procedure destroyList(var bitList: TBitList);
begin
if bitList^.next <> nil then
clearList(bitList);
dispose(bitList);
bitList := nil;
end;
function toString(bitList: TBitList):String;
var
i: Integer;
begin
result := '';
while bitList^.next <> nil do
begin
if bitList^.next^.bit then
result := '1' + result
else
result := '0' + result;
if ((length(result) + 1) mod 9 = 0) then
result := ' ' + result;
bitList := bitList^.next;
end;
end;
function lengthList(bitList: TBitList):Integer;
begin
result := 1;
while bitList^.next <> nil do
begin
inc(result);
bitList := bitList^.next;
end;
end;
function isEmptyList(bitList: TBitList):Boolean;
begin
result := bitList^.next = nil;
end;
end.
|
unit Cache.SensorValues;
interface
uses
SysUtils,
Cache.Root,
Adapter.MySQL,
Geo.Pos,
ZConnection, ZDataset,
Ils.MySql.Conf,
uTrackPoints,
Math,
DateUtils,
Ils.Utils;
type
TSensorValueKey = packed record
IMEI: Int64;
SensorID: Integer;
constructor Create(const AIMEI: Int64; const ASensorID: Integer);
end;
TSensorValue = class(TCacheDataObjectAbstract)
protected
function GetDTMark(): TDateTime; override;
private
FKey: TSensorValueKey;
FDT: TDateTime;
FValueRaw: Double;
FValue: Double;
FValueFiltered: Double;
public
property IMEI: Int64 read FKey.IMEI;
property SensorID: Integer read FKey.SensorID;
property DT: TDateTime read FDT;
property ValueRaw: Double read FValueRaw;
property Value: Double read FValue write FValue;
property ValueFiltered: Double read FValueFiltered;
procedure Assign(const ASource: TSensorValue);
function Clone: TCacheDataObjectAbstract; override;
constructor Create(const ASource: TSensorValue); overload;
constructor Create(const AIMEI: Int64; const ASensorID: Integer; const ADT: TDateTime; const AValueRaw, AValue, AValueFiltered: Double); overload;
end;
TSensorValueCacheDataAdapter = class(TCacheAdapterMySQL)
private
FQueryUpdateSensorLastValue: TZQuery;
public
procedure Flush(const ACache: TCache); override;
procedure Add(const ACache: TCache; const AObj: TCacheDataObjectAbstract); override;
procedure Change(const ACache: TCache; const AObj: TCacheDataObjectAbstract); override;
function MakeObjFromReadQuery(const AQuery: TZQuery): TCacheDataObjectAbstract; override;
constructor Create(const AReadConnection, AWriteConnection: TZConnection);
destructor Destroy; override;
end;
TSensorValueCacheHash = class(TCacheDictionary<TSensorValueKey>)
private
FSensorValueDataAdapter: TSensorValueCacheDataAdapter;
FWriteBack: Boolean;
FInterval: Double;
FMaxCount: Integer;
public
function GetSensorCache(const ASensorKey: TSensorValueKey): TCache;
constructor Create(const ASensorValueDataAdapter: TSensorValueCacheDataAdapter;
const AWriteBack: Boolean; const AInterval: Double; const AMaxCount: Integer);
end;
implementation
{ TSensorValueCacheDataAdapter }
constructor TSensorValueCacheDataAdapter.Create(
const AReadConnection, AWriteConnection: TZConnection
);
var
SQLInsert: string;
SQLUpdate: string;
SQLReadBefore: string;
SQLReadAfter: string;
SQLReadRange: string;
SQLDeleteOne: string;
SQLUpdateLastValue: string;
begin
SQLReadRange := 'SELECT *'
+ ' FROM sensorvalue'
+ ' WHERE IMEI = :imei'
+ ' AND SensorID = :SensorID'
+ ' AND DT >= :dt_from'
+ ' AND DT <= :dt_to'
;
SQLReadBefore := 'SELECT MAX(DT) as DT'
+ ' FROM sensorvalue'
+ ' WHERE IMEI = :imei'
+ ' AND SensorID = :SensorID'
+ ' AND DT < :dt'
;
SQLReadAfter := 'SELECT MIN(DT) as DT'
+ ' FROM sensorvalue'
+ ' WHERE IMEI = :imei'
+ ' AND SensorID = :SensorID'
+ ' AND DT > :dt'
;
SQLInsert :=
'insert ignore into sensorvalue set'
+ ' IMEI = :IMEI, DT = :DT, SensorID = :SensorID,'
+ ' Raw = :Raw, Value = :Value, Filtered = :Filtered'
+ ' on duplicate key update'
+ ' Raw = VALUES(Raw), Value = VALUES(Value), Filtered = VALUES(Filtered)'
;
SQLUpdate :=
'update sensorvalue set'
+ ' Raw = :Raw, Value = :Value, Filtered = :Filtered'
+ ' where'
+ ' IMEI = :IMEI'
+ ' AND SensorID = :SensorID'
+ ' and DT = :DT'
;
SQLDeleteOne :=
'*';
SQLUpdateLastValue :=
'insert ignore into sensorlastvalue set'
+ ' IMEI = :IMEI, DT = :DT, SensorID = :SensorID,'
+ ' Raw = :Raw, Value = :Value, Filtered = :Filtered'
+ ' on duplicate key update'
+ ' DT = VALUES(DT),'
+ ' Raw = VALUES(Raw), Value = VALUES(Value), Filtered = VALUES(Filtered)'
;
inherited Create(
AReadConnection, AWriteConnection,
SQLInsert, SQLUpdate, SQLReadBefore, SQLReadAfter, SQLReadRange, SQLDeleteOne);
FQueryUpdateSensorLastValue := TZQuery.Create(nil);
FQueryUpdateSensorLastValue.Connection := AWriteConnection;
FQueryUpdateSensorLastValue.SQL.Text := SQLUpdateLastValue;
end;
destructor TSensorValueCacheDataAdapter.Destroy;
begin
FQueryUpdateSensorLastValue.Free;
inherited;
end;
procedure TSensorValueCacheDataAdapter.Flush(const ACache: TCache);
begin
//
end;
procedure TSensorValueCacheDataAdapter.Add(
const ACache: TCache;
const AObj: TCacheDataObjectAbstract
);
begin
FillParamsFromKey(ACache.Key, FInsertQry);
FillParamsFromKey(ACache.Key, FQueryUpdateSensorLastValue);
with (AObj as TSensorValue), FInsertQry do
begin
Close;
ParamByName('IMEI').AsLargeInt := IMEI;
ParamByName('DT').AsDateTime := DT;
ParamByName('SensorID').AsInteger := SensorID;
ParamByName('Raw').AsFloat := ValueRaw;
ParamByName('Value').AsFloat := Value;
ParamByName('Filtered').AsFloat := ValueFiltered;
ExecSQL;
end;
with (AObj as TSensorValue), FQueryUpdateSensorLastValue do
begin
Close;
ParamByName('IMEI').AsLargeInt := IMEI;
ParamByName('DT').AsDateTime := DT;
ParamByName('SensorID').AsInteger := SensorID;
ParamByName('Raw').AsFloat := ValueRaw;
ParamByName('Value').AsFloat := Value;
ParamByName('Filtered').AsFloat := ValueFiltered;
ExecSQL;
end;
end;
procedure TSensorValueCacheDataAdapter.Change(
const ACache: TCache;
const AObj: TCacheDataObjectAbstract
);
begin
FillParamsFromKey(ACache.Key, FUpdateQry);
with (AObj as TSensorValue), FUpdateQry do
begin
Close;
ParamByName('IMEI').AsLargeInt := IMEI;
ParamByName('DT').AsDateTime := DT;
ParamByName('SensorID').AsInteger := SensorID;
ParamByName('Raw').AsFloat := ValueRaw;
ParamByName('Value').AsFloat := Value;
ParamByName('Filtered').AsFloat := ValueFiltered; //TODO: проверить на infinity
ExecSQL;
end;
end;
function TSensorValueCacheDataAdapter.MakeObjFromReadQuery(
const AQuery: TZQuery
): TCacheDataObjectAbstract;
begin
with AQuery do
begin
Result :=
TSensorValue.Create(
FieldByName('IMEI').AsLargeInt,
FieldByName('SensorID').AsInteger,
FieldByName('DT').AsDateTime,
FieldByName('Raw').AsFloat,
FieldByName('Value').AsFloat,
FieldByName('Filtered').AsFloat
);
end;
end;
{ TSensorValue }
procedure TSensorValue.Assign(const ASource: TSensorValue);
begin
FKey.IMEI := ASource.IMEI;
FKey.SensorID := ASource.SensorID;
FDT := ASource.DT;
FValueRaw := ASource.ValueRaw;
FValue := ASource.Value;
FValueFiltered := ASource.ValueFiltered;
end;
function TSensorValue.Clone: TCacheDataObjectAbstract;
begin
Result := TSensorValue.Create(Self);
end;
constructor TSensorValue.Create(const AIMEI: Int64; const ASensorID: Integer;
const ADT: TDateTime; const AValueRaw, AValue, AValueFiltered: Double);
begin
FKey.IMEI := AIMEI;
FKey.SensorID := ASensorID;
FDT := ADT;
FValueRaw := AValueRaw;
FValue := AValue;
FValueFiltered := AValueFiltered;
end;
constructor TSensorValue.Create(const ASource: TSensorValue);
begin
Assign(ASource);
end;
function TSensorValue.GetDTMark: TDateTime;
begin
Result := FDT;
end;
{ TSensorValueKey }
constructor TSensorValueKey.Create(const AIMEI: Int64; const ASensorID: Integer);
begin
IMEI := AIMEI;
SensorID := ASensorID;
end;
{ TSensorValueCacheHash }
constructor TSensorValueCacheHash.Create(
const ASensorValueDataAdapter: TSensorValueCacheDataAdapter;
const AWriteBack: Boolean; const AInterval: Double; const AMaxCount: Integer);
begin
FSensorValueDataAdapter := ASensorValueDataAdapter;
FWriteBack := AWriteBack;
FInterval := AInterval;
FMaxCount := AMaxCount;
inherited Create;
end;
function TSensorValueCacheHash.GetSensorCache(
const ASensorKey: TSensorValueKey): TCache;
begin
if not ContainsKey(ASensorKey) then
begin
Add(ASensorKey, TCache.Create(
FSensorValueDataAdapter, True, 15 * OneMinute, 1000, TConnKey.Create([
'IMEI', IntToStr(ASensorKey.IMEI),
'SensorID', IntToStr(ASensorKey.SensorID)
])
));
end;
Result := TCache(Self[ASensorKey]);
end;
end.
|
{ Wheberson Hudson Migueletti, em Brasília, 25 de março de 1999.
Internet : http://www.geocities.com/whebersite
E-mail : whebersite@zipmail.com.br
Atualização: 02/06/2001
Referências: 1) GRAPHICS INTERCHANGE FORMAT(sm) - Version 89a - Specification
2) Data Compression Reference Center
http://www.rasip.fer.hr/research/compress
3) California Technical Publishing Data Compression
http://www.dspguide.com/datacomp.htm
4) Mark Nelson's Home Page - LZW
http://www.dogma.net/markn/articles/lzw/lzw.htm
5) InfoSite - LZW
http://luke.megagis.lt/lzw.htm
6) GIF.HTM - Alexander Larkin
http://larkin.spa.umn.edu/index.htm
}
unit DelphiGIF;
interface
uses Windows, SysUtils, Classes, Graphics, DelphiImage;
type
PGIFPalette= ^TGIFPalette;
TGIFPalette= array[0..255] of TRGB;
PScreenDescriptor= ^TScreenDescriptor;
TScreenDescriptor= packed record
Signature : array[0..2] of Char; // "GIF"
Version : array[0..2] of Char; // "87a" ou "89a"
ScreenWidth : Word;
ScreenHeight : Word;
PackedFields : Byte;
BackgroundColorIndex: Byte;
PixelAspectRatio : Byte;
end;
PImageDescriptor= ^TImageDescriptor;
TImageDescriptor= packed record
ImageLeft : Word;
ImageTop : Word;
ImageWidth : Word;
ImageHeight : Word;
PackedFields: Byte; // Se NÃO existir a Paleta Local deve-se utilizar a Global
end;
PGraphicExtension= ^TGraphicExtension;
TGraphicExtension= packed record
BlockSize : Byte;
PackedFields : Byte;
DelayTime : Word;
TransparentColorIndex: Byte;
BlockTerminator : Byte;
end;
PGIFInfo= ^TGIFInfo;
TGIFInfo= record
Interlaced : Boolean;
Transparent : Boolean;
DisposalMethod : Byte;
TransparentColorIndex: Byte;
Height : Integer;
Width : Integer;
Comment : String;
Origin : TPoint;
DelayTime : Word;
PaletteLength : Word;
end;
TGIFDecoder= class
protected
GIFBitsPerPixel: Integer;
Bitmap : TBitmap;
Info : TGIFInfo;
GIFPalette : TGIFPalette;
Frames : TList;
Stream : TStream;
procedure Read (var Buffer; Count: Integer);
procedure ColorMapToPalette (var Palette: HPalette; PaletteLength: Word);
procedure DumpPalette (PaletteLength: Word);
procedure DumpScreenDescriptor;
procedure DumpImageDescriptor;
procedure DumpGraphicControlExtension;
procedure DumpCommentExtension;
procedure DumpApplicationExtension;
procedure DumpExtension;
procedure DumpBlockTerminator;
procedure DumpImage (Width, Height: Integer; Interlaced: Boolean);
procedure SkipImage (FirstImageOnly: Boolean);
procedure ClearInfo;
public
BackgroundColorIndex: Byte;
GlobalPalette : HPalette;
Count : Integer;
GlobalPaletteLength : Integer;
ScreenHeight : Integer;
ScreenWidth : Integer;
TrailingComment : String;
BackgroundColor : TRGB;
Loops : Word;
constructor Create (AStream: TStream);
destructor Destroy; override;
procedure Clear;
procedure Load (FirstImageOnly: Boolean);
procedure GetFrame (AIndex: Integer; ABitmap: TBitmap; var AInfo: TGIFInfo);
end;
TGIFEncoder= class
protected
GlobalPalette : HPalette;
BitsPerPixel : Integer;
TrailingComment: String;
Bitmap : TBitmap;
Stream : TStream;
procedure WriteLoops (Count: Word);
procedure WriteComment (const Comment: String);
procedure WritePalette (Palette: HPalette; PaletteLength: Integer);
procedure WriteImage;
public
constructor Create (AStream: TStream);
destructor Destroy; override;
procedure Encode (AScreenWidth, AScreenHeight: Integer; ALoops: Word; ABackgroundColorIndex: Byte; AGlobalPalette: HPalette; ATrailingComment: String);
procedure AddImage (ABitmap: TBitmap; ALocalPalette: HPalette; ALeft, ATop: Integer);
procedure Add (ABitmap: TBitmap; ALocalPalette: HPalette; ALeft, ATop: Integer; ADelayTime: Word; ADisposalMethod: Byte; ATransparent: Boolean; ATransparentColorIndex: Byte; const AComment: String);
end;
TGIF= class (TBitmap)
public
function IsValid (const FileName: String): Boolean;
procedure LoadFromStream (Stream: TStream); override;
end;
implementation
const
// Usado quando a imagem está entrelaçada
cYInc: array[1..4] of Byte= (8, 8, 4, 2); // As linhas de cada grupo (são 4) são incrementadas de acordo com este vetor
cYLin: array[1..4] of Byte= (0, 4, 2, 1); // Linha inicial de cada grupo
type
PLine= ^TLine;
TLine= array[0..0] of Byte;
TCelula= record
Prefixo: Word;
Sufixo : Byte;
end;
PGIFFrame1= ^TGIFFrame1;
TGIFFrame1= record
Offset: Integer;
Info : TGIFInfo;
end;
TLZWTable= class
protected
Tabela : array[0..4097] of TCelula;
Tamanho: Integer;
Maximo : Word;
public
constructor Create;
procedure Initialize (AMax: Word);
procedure Add (Prefix: Word; Suffix: Byte);
function Get (Index: Word; var Suffix: Byte): Integer;
function Find (Prefix: Word; Suffix: Byte) : Integer;
end;
TGIFLZWDecoder= class
private
Count : Integer;
Offset : Integer; // "Offset" na "Stream/Buffer" (em relação aos "bits")
StartPos : Integer;
Dictionary : TLZWTable;
ClearCode : Word;
Code : Word;
CodeSize : Word;
EOFCode : Word;
FreeCode : Word; // Indica quando é que "CodeSize" será incrementado
InitCodeSize: Word;
InitFreeCode: Word;
MaxCode : Word;
ReadMask : Word;
protected
procedure GetNextCode;
procedure Write (Value: Byte); virtual; abstract;
public
constructor Create (ACodeSize: Byte);
destructor Destroy; override;
procedure Execute (AStream: TMemoryStream; ACount: Integer);
end;
TGIFLZWDecoder_NotInterleaved= class (TGIFLZWDecoder)
protected
Height: Integer;
Width : Integer;
X, Y : Integer;
Line : PLine;
Bitmap: TBitmap;
procedure Write (Value: Byte); override;
public
constructor Create (ABitmap: TBitmap; AWidth, AHeight: Integer; ACodeSize: Byte);
end;
TGIFLZWDecoder_Interleaved= class (TGIFLZWDecoder)
protected
Group : Byte;
Height: Integer;
Width : Integer;
X, Y : Integer;
Line : PLine;
Bitmap: TBitmap;
procedure Write (Value: Byte); override;
public
constructor Create (ABitmap: TBitmap; AWidth, AHeight: Integer; ACodeSize: Byte);
end;
var
gInitTable: array[0..257] of TCelula;
procedure DestroyPalette (var Palette: HPalette);
begin
try
if Palette <> 0 then begin
DeleteObject (Palette);
Palette:= 0;
end;
except
Palette:= 0;
end;
end;
//----------------------------------------------------------------------------------------------
constructor TLZWTable.Create;
begin
inherited Create;
Move (gInitTable[0], Tabela[0], SizeOf (gInitTable));
end;
procedure TLZWTable.Initialize (AMax: Word);
begin
Maximo := AMax;
Tamanho:= Maximo + 1;
with Tabela[Maximo] do begin
Prefixo:= 0;
Sufixo := 0;
end;
end;
procedure TLZWTable.Add (Prefix: Word; Suffix: Byte);
begin
Tabela[Tamanho].Prefixo:= Prefix;
Tabela[Tamanho].Sufixo := Suffix;
Inc (Tamanho);
end;
function TLZWTable.Get (Index: Word; var Suffix: Byte): Integer;
begin
if Index < Tamanho then begin
Suffix:= Tabela[Index].Sufixo;
Result:= Tabela[Index].Prefixo;
end
else
Result:= -1;
end;
function TLZWTable.Find (Prefix: Word; Suffix: Byte): Integer;
var
P: Integer;
begin
if Prefix = 0 then
Result:= Suffix+1
else begin
Result:= -1;
for P:= Maximo to Tamanho-1 do
if (Tabela[P].Prefixo = Prefix) and (Tabela[P].Sufixo = Suffix) then begin
Result:= P;
Exit;
end;
end;
end;
//----------------------------------------------------------------------------------------------
constructor TGIFLZWDecoder.Create (ACodeSize: Byte);
begin
inherited Create;
CodeSize := ACodeSize;
ClearCode := 1 shl CodeSize;
EOFCode := ClearCode + 1;
InitFreeCode:= ClearCode + 2;
FreeCode := InitFreeCode;
CodeSize := CodeSize + 1;
InitCodeSize:= CodeSize;
MaxCode := 1 shl InitCodeSize;
ReadMask := MaxCode-1;
Offset := 0;
Code := 0;
Dictionary := TLZWTable.Create;
end;
destructor TGIFLZWDecoder.Destroy;
begin
Dictionary.Free;
inherited Destroy;
end;
procedure TGIFLZWDecoder.GetNextCode;
var
Position: Integer;
begin
Position:= Offset shr 3;
if Count < CodeSize then
Code:= EOFCode
else begin
if CodeSize >= 8 then
Code:= (PInteger (StartPos + Position)^ shr (Offset and 7)) and ReadMask
else
Code:= (PWord (StartPos + Position)^ shr (Offset and 7)) and ReadMask;
Inc (Offset, CodeSize);
Dec (Count, CodeSize);
end;
end;
procedure TGIFLZWDecoder.Execute (AStream: TMemoryStream; ACount: Integer);
var
Aux : Byte;
Character: Byte;
Prefix : Integer;
Old : Word;
// Ocorre quando é encontrado um "ClearCode"
procedure Reinicializar;
begin
CodeSize:= InitCodeSize;
FreeCode:= InitFreeCode;
MaxCode := 1 shl InitCodeSize;
ReadMask:= MaxCode-1;
end;
// Para encontrar um valor no Dicionário deve-se percorrê-lo em ordem inversa
procedure BuscarOcorrencia (CurrentPrefix: Integer);
const
cMax= $0FFF;
var
Buffer: array[0..cMax] of Byte;
I, J : Integer;
begin
for I:= cMax downto 0 do begin
CurrentPrefix:= Dictionary.Get (CurrentPrefix, Character);
Buffer[I] := Character;
if CurrentPrefix = 0 then
Break;
end;
for J:= I to cMax do
Write (Buffer[J]);
end;
begin
StartPos:= Integer (AStream.Memory) + AStream.Position;
Count := ACount shl 3; // Converte para bits
while True do begin
Old:= Code + 1;
GetNextCode;
if Code = EOFCode then
Break
else if Code = ClearCode then begin
Reinicializar;
Dictionary.Initialize (InitFreeCode);
GetNextCode;
if Code = EOFCode then
Break;
Write (Code);
end
else begin
Prefix:= Dictionary.Get (Code+1, Character);
if Prefix = 0 then
Write (Character)
else if Prefix > 0 then begin
Aux:= Character;
BuscarOcorrencia (Prefix);
Write (Aux);
end
else begin
BuscarOcorrencia (Old);
Write (Character);
end;
Dictionary.Add (Old, Character);
Inc (FreeCode);
if (FreeCode >= MaxCode) and (CodeSize < 12) then begin
Inc (CodeSize);
MaxCode := MaxCode shl 1;
ReadMask:= MaxCode-1;
end;
end;
end;
end;
//----------------------------------------------------------------------------------------------
constructor TGIFLZWDecoder_NotInterleaved.Create (ABitmap: TBitmap; AWidth, AHeight: Integer; ACodeSize: Byte);
begin
inherited Create (ACodeSize);
Bitmap:= ABitmap;
Width := AWidth;
Height:= AHeight;
Line := Bitmap.ScanLine[0];
X := 0;
Y := 0;
end;
procedure TGIFLZWDecoder_NotInterleaved.Write (Value: Byte);
begin
Line[X]:= Value;
Inc (X);
if X = Width then begin
X:= 0;
Inc (Y);
if Y < Height then
Line:= Bitmap.ScanLine[Y];
end;
end;
//----------------------------------------------------------------------------------------------
constructor TGIFLZWDecoder_Interleaved.Create (ABitmap: TBitmap; AWidth, AHeight: Integer; ACodeSize: Byte);
begin
inherited Create (ACodeSize);
Bitmap:= ABitmap;
Width := AWidth;
Height:= AHeight;
Line := Bitmap.ScanLine[0];
X := 0;
Y := 0;
Group := 1;
end;
procedure TGIFLZWDecoder_Interleaved.Write (Value: Byte);
begin
Line[X]:= Value;
Inc (X);
if X = Width then begin
X:= 0;
Y:= Y + cYInc[Group];
if Y >= Height then begin // Terminou o grupo
Inc (Group);
if Group > 4 then
Exit;
Y:= cYLin[Group];
if Y >= Height then
Exit;
end;
Line:= Bitmap.ScanLine[Y];
end;
end;
//----------------------------------------------------------------------------------------------
constructor TGIFDecoder.Create (AStream: TStream);
begin
inherited Create;
Count := 0;
Stream:= AStream;
Frames:= TList.Create;
end;
destructor TGIFDecoder.Destroy;
begin
DestroyPalette (GlobalPalette);
Frames.Free;
inherited Destroy;
end;
procedure TGIFDecoder.Read (var Buffer; Count: Integer);
var
Lidos: Integer;
begin
Lidos:= Stream.Read (Buffer, Count);
if Lidos <> Count then
raise EInvalidImage.Create (Format ('GIF read error at %.8xH (%d byte(s) expected, but %d read)', [Stream.Position-Lidos, Count, Lidos]));
end;
procedure TGIFDecoder.ColorMapToPalette (var Palette: HPalette; PaletteLength: Word);
var
Tripla: Integer;
LogPal: TMaxLogPalette;
begin
if PaletteLength > 0 then begin
DestroyPalette (Palette);
with LogPal do begin
palVersion := $0300;
palNumEntries:= PaletteLength;
for Tripla:= 0 to palNumEntries-1 do
with palPalEntry[Tripla] do begin
peRed := GIFPalette[Tripla].Red;
peGreen:= GIFPalette[Tripla].Green;
peBlue := GIFPalette[Tripla].Blue;
peFlags:= 0;
end;
end;
Palette:= CreatePalette (PLogPalette (@LogPal)^);
end;
end;
procedure TGIFDecoder.DumpPalette (PaletteLength: Word);
begin
if PaletteLength > 0 then
Read (GIFPalette, PaletteLength*SizeOf (TRGB));
end;
procedure TGIFDecoder.DumpScreenDescriptor;
var
Header: TScreenDescriptor;
begin
Read (Header, SizeOf (TScreenDescriptor));
if (Header.Signature = 'GIF') and ((Header.Version = '87a') or (Header.Version = '89a')) then begin
ScreenWidth := Header.ScreenWidth;
ScreenHeight := Header.ScreenHeight;
GIFBitsPerPixel := (Header.PackedFields and 7) + 1;
BackgroundColorIndex:= Header.BackgroundColorIndex;
if (Header.PackedFields and 128) <> 0 then
GlobalPaletteLength:= 1 shl GIFBitsPerPixel
else
GlobalPaletteLength:= 0;
end
else
raise EUnsupportedImage.Create ('Unsupported file format !');
end;
procedure TGIFDecoder.DumpImageDescriptor;
var
ImgDescriptor: TImageDescriptor;
begin
Read (ImgDescriptor, SizeOf (TImageDescriptor));
Info.Width := ImgDescriptor.ImageWidth;
Info.Height := ImgDescriptor.ImageHeight;
Info.Origin := Point (ImgDescriptor.ImageLeft, ImgDescriptor.ImageTop);
Info.Interlaced:= (ImgDescriptor.PackedFields and 64) <> 0;
if (ImgDescriptor.PackedFields and 128) <> 0 then begin
GIFBitsPerPixel := (ImgDescriptor.PackedFields and 7) + 1;
Info.PaletteLength:= 1 shl GIFBitsPerPixel;
end
else
Info.PaletteLength:= 0;
end;
procedure TGIFDecoder.DumpGraphicControlExtension;
var
GraphicExtension: TGraphicExtension;
begin
Read (GraphicExtension, SizeOf (TGraphicExtension));
Info.DelayTime := GraphicExtension.DelayTime;
Info.DisposalMethod := (GraphicExtension.PackedFields shr 2) and 7;
Info.Transparent := (GraphicExtension.PackedFields and 1) <> 0;
Info.TransparentColorIndex:= GraphicExtension.TransparentColorIndex;
end;
procedure TGIFDecoder.DumpCommentExtension;
var
Size: Byte;
begin
Read (Size, 1); // "String Length" ou "Block Terminator"
if Size > 0 then begin
SetLength (Info.Comment, Size);
Read (Info.Comment[1], Size);
DumpBlockTerminator;
end;
end;
procedure TGIFDecoder.DumpApplicationExtension;
var
Id : Byte;
Size: Byte;
App : array[0..10] of Char;
begin
Read (Size, 1); // 11
Read (App[0], 11);
Read (Size, 1); // "Data Size" ou "Block Terminator"
if Size > 0 then begin
if (App = 'NETSCAPE2.0') and (Size = 3) then begin
Read (Id, 1);
if Id = 1 then
Read (Loops, 2)
else
Stream.Seek (2, soFromCurrent);
DumpBlockTerminator;
end
else
Stream.Seek (Word (Size) + 1, soFromCurrent); // "Data" + "Block Terminator"
end;
end;
procedure TGIFDecoder.DumpExtension;
var
ExtensionLabel: Byte;
begin
Read (ExtensionLabel, 1);
case ExtensionLabel of
$F9: DumpGraphicControlExtension;
$FE: DumpCommentExtension;
$FF: DumpApplicationExtension;
else
DumpBlockTerminator;
end;
end;
procedure TGIFDecoder.DumpBlockTerminator;
var
BlockSize: Byte;
begin
while Stream.Position < Stream.Size do begin
Read (BlockSize, 1);
if BlockSize = 0 then
Exit
else
Stream.Seek (BlockSize, soFromCurrent);
end;
end;
// Desempacota/Descompacta(LZW) a imagem
procedure TGIFDecoder.DumpImage (Width, Height: Integer; Interlaced: Boolean);
var
BlockSize: Byte;
BPP : Byte;
Count : Integer;
Buffer : PByte;
Decoder : TGIFLZWDecoder;
Raster : TMemoryStream;
begin
Read (BPP, 1);
if BPP > 0 then begin
if Interlaced then
Decoder:= TGIFLZWDecoder_Interleaved.Create (Bitmap, Width, Height, BPP)
else
Decoder:= TGIFLZWDecoder_NotInterleaved.Create (Bitmap, Width, Height, BPP);
try
Raster:= TMemoryStream.Create;
try
GetMem (Buffer, 255);
try
Count:= Stream.Size-Stream.Position;
while Count > 0 do begin
Read (BlockSize, 1);
if BlockSize > 0 then begin
Stream.Read (Buffer^, BlockSize);
Raster.Write (Buffer^, BlockSize);
end
else
Break;
Dec (Count, BlockSize);
end;
finally
FreeMem (Buffer);
end;
Raster.Seek (0, soFromBeginning);
Decoder.Execute (Raster, Raster.Size);
finally
Raster.Free;
end;
finally
Decoder.Free;
end;
end;
end;
// Table-Based Image
procedure TGIFDecoder.SkipImage (FirstImageOnly: Boolean);
procedure SkipImageData;
var
BlockSize: Byte;
begin
Stream.Seek (1, soFromCurrent); // LZW Minimum Code Size
while Stream.Position < Stream.Size do begin
Read (BlockSize, 1);
if BlockSize = 0 then
Break
else
Stream.Seek (BlockSize, soFromCurrent);
end;
end;
var
Frame: PGIFFrame1;
begin
DumpImageDescriptor;
Frame := New (PGIFFrame1);
Frame.Offset:= Stream.Position;
Frame.Info := Info;
Frames.Add (Frame);
if not FirstImageOnly then begin
if Info.PaletteLength > 0 then
Stream.Seek (Info.PaletteLength*SizeOf (TRGB), soFromCurrent);
SkipImageData;
end;
ClearInfo;
end;
procedure TGIFDecoder.ClearInfo;
begin
with Info do begin
Interlaced := False;
Transparent := False;
DisposalMethod := 0;
TransparentColorIndex:= 0;
Height := 0;
Width := 0;
Comment := '';
Origin := Point (0, 0);
DelayTime := 0;
PaletteLength := 0;
end;
end;
procedure TGIFDecoder.Clear;
var
I: Integer;
begin
Count := 0;
Loops := 0;
TrailingComment:= '';
ClearInfo;
for I:= 0 to Frames.Count-1 do
Dispose (PGIFFrame1 (Frames[I]));
Frames.Clear;
end;
procedure TGIFDecoder.Load (FirstImageOnly: Boolean);
var
Separator: Char;
begin
Clear;
if Stream.Size > 0 then begin
DumpScreenDescriptor;
DumpPalette (GlobalPaletteLength);
if GlobalPaletteLength > 0 then begin
ColorMapToPalette (GlobalPalette, GlobalPaletteLength);
BackgroundColor:= GIFPalette[BackgroundColorIndex];
end;
while Stream.Position < Stream.Size do begin
Read (Separator, 1);
case Separator of
',': begin
SkipImage (FirstImageOnly);
if FirstImageOnly then
Break;
end;
'!': DumpExtension;
';': begin
if Info.Comment <> '' then
TrailingComment:= Info.Comment;
Break;
end;
else
Break;
end;
end;
Count:= Frames.Count;
end;
end;
procedure TGIFDecoder.GetFrame (AIndex: Integer; ABitmap: TBitmap; var AInfo: TGIFInfo);
var
Palette: HPalette;
begin
if (AIndex >= 0) and (AIndex < Frames.Count) and Assigned (ABitmap) then begin
AInfo := PGIFFrame1 (Frames[AIndex])^.Info;
Bitmap := ABitmap;
Bitmap.Width := AInfo.Width;
Bitmap.Height := AInfo.Height;
Bitmap.PixelFormat := pf8bit;
Bitmap.IgnorePalette:= False;
Stream.Seek (PGIFFrame1 (Frames[AIndex])^.Offset, soFromBeginning);
if AInfo.PaletteLength > 0 then begin
DumpPalette (AInfo.PaletteLength);
ColorMapToPalette (Palette, AInfo.PaletteLength);
Bitmap.Palette:= Palette;
end
else
Bitmap.Palette:= CopyPalette (GlobalPalette);
DumpImage (AInfo.Width, AInfo.Height, AInfo.Interlaced);
end;
end;
//----------------------------------------------------------------------------------------------
constructor TGIFEncoder.Create (AStream: TStream);
begin
inherited Create;
Stream := AStream;
Bitmap := nil;
GlobalPalette := 0;
BitsPerPixel := 8;
TrailingComment:= '';
end;
destructor TGIFEncoder.Destroy;
const
cTrailer: Byte= $3B;
begin
if (TrailingComment <> '') and (Trim (TrailingComment) <> '') then begin
WriteComment (TrailingComment);
Stream.Write (cTrailer, 1);
end;
try
if GlobalPalette <> 0 then
DeleteObject (GlobalPalette);
except
end;
inherited Destroy;
end;
procedure TGIFEncoder.Encode (AScreenWidth, AScreenHeight: Integer; ALoops: Word; ABackgroundColorIndex: Byte; AGlobalPalette: HPalette; ATrailingComment: String);
var
Header: TScreenDescriptor;
begin
Bitmap := nil;
TrailingComment := ATrailingComment;
Header.Signature := 'GIF';
Header.Version := '89a';
Header.ScreenWidth := AScreenWidth;
Header.ScreenHeight := AScreenHeight;
Header.PackedFields := BitsPerPixel-1;
Header.BackgroundColorIndex:= ABackgroundColorIndex;
Header.PixelAspectRatio := 0;
DestroyPalette (GlobalPalette);
if AGlobalPalette <> 0 then begin
Header.PackedFields:= Header.PackedFields or 128;
GlobalPalette:= CopyPalette (AGlobalPalette);
end;
// "Header"
Stream.Write (Header, SizeOf (TScreenDescriptor));
// "Global Color Map"
if GlobalPalette <> 0 then
WritePalette (GlobalPalette, 1 shl BitsPerPixel);
if ALoops > 0 then
WriteLoops (ALoops);
end;
procedure TGIFEncoder.WriteLoops (Count: Word);
type
TApplicationExtension= packed record
ExtensionIntroducer: Byte;
ExtensionLabel : Byte;
BlockSize : Byte;
App : array[0..10] of Char;
DataSize : Byte;
Id : Byte;
Loops : Word;
BlockTerminator : Word;
end;
var
ApplicationExtension: TApplicationExtension;
begin
with ApplicationExtension do begin
ExtensionIntroducer:= $21;
ExtensionLabel := $FF;
BlockSize := 11;
App := 'NETSCAPE2.0';
DataSize := 3;
Id := 1;
Loops := Count;
BlockTerminator := 0;
end;
Stream.Write (ApplicationExtension, SizeOf (TApplicationExtension));
end;
procedure TGIFEncoder.WriteComment (const Comment: String);
type
TCommentExtension= packed record
ExtensionIntroducer: Byte;
ExtensionLabel : Byte;
BlockSize : Byte;
end;
var
BlockTerminator : Byte;
CommentExtension: TCommentExtension;
begin
if (Comment <> '') and (Trim (Comment) <> '') then begin
with CommentExtension do begin
ExtensionIntroducer:= $21;
ExtensionLabel := $FE;
if Length (Comment) <= 255 then
BlockSize:= Length (Comment)
else
BlockSize:= 255;
end;
BlockTerminator:= 0;
Stream.Write (CommentExtension, SizeOf (TCommentExtension));
Stream.Write (Comment[1], CommentExtension.BlockSize);
Stream.Write (BlockTerminator, 1);
end;
end;
procedure TGIFEncoder.AddImage (ABitmap: TBitmap; ALocalPalette: HPalette; ALeft, ATop: Integer);
var
Separator : Char;
ImgDescriptor: TImageDescriptor;
begin
if Assigned (Stream) and Assigned (ABitmap) and (not ABitmap.Empty) then begin
Bitmap:= ABitmap;
if not (Bitmap.PixelFormat in [{pf1bit, pf4bit,} pf8bit]) then
//raise EInvalidImage.Create ('The Pixel Format must be 1bit or 4bit or 8bit !')
raise EInvalidImage.Create ('The Pixel Format must be 8bit !')
else begin
ImgDescriptor.ImageLeft := ALeft;
ImgDescriptor.ImageTop := ATop;
ImgDescriptor.ImageWidth := Bitmap.Width;
ImgDescriptor.ImageHeight := Bitmap.Height;
ImgDescriptor.PackedFields:= 0;
Separator := ',';
if ALocalPalette <> 0 then
ImgDescriptor.PackedFields:= 128;
{case Bitmap.PixelFormat of
pf1bit: BitsPerPixel:= 2;
pf4bit: BitsPerPixel:= 4;
pf8bit: BitsPerPixel:= 8;
end;}
ImgDescriptor.PackedFields:= ImgDescriptor.PackedFields + (BitsPerPixel-1);
Stream.Write (Separator, 1);
// "Image Descriptor"
Stream.Write (ImgDescriptor, SizeOf (TImageDescriptor));
// "Local Palette"
if ALocalPalette <> 0 then
WritePalette (ALocalPalette, 1 shl BitsPerPixel);
// "Image"
WriteImage;
Separator:= ';';
Stream.Write (Separator, 1);
Stream.Seek (-1, soFromCurrent);
end;
end;
end;
procedure TGIFEncoder.Add (ABitmap: TBitmap; ALocalPalette: HPalette; ALeft, ATop: Integer; ADelayTime: Word; ADisposalMethod: Byte; ATransparent: Boolean; ATransparentColorIndex: Byte; const AComment: String);
var
ExtensionIntroducer: Byte;
ExtensionLabel : Byte;
Save1, Save2 : Integer;
GraphicExtension : TGraphicExtension;
begin
if Assigned (Stream) and Assigned (ABitmap) and (not ABitmap.Empty) then begin
// "Comment Extension"
WriteComment (AComment);
// "Graphic Extension"
ExtensionIntroducer:= $21;
ExtensionLabel := $F9;
Stream.Write (ExtensionIntroducer, 1);
Stream.Write (ExtensionLabel, 1);
// Alocando área para "GraphicExtension"
Save1:= Stream.Position;
Stream.Write (GraphicExtension, SizeOf (TGraphicExtension));
// Salvando "Image"
AddImage (ABitmap, ALocalPalette, ALeft, ATop);
Save2:= Stream.Position;
// Atualizando "GraphicExtension"
GraphicExtension.BlockSize := 4;
GraphicExtension.PackedFields := ADisposalMethod shl 2;
GraphicExtension.DelayTime := ADelayTime;
GraphicExtension.TransparentColorIndex:= ATransparentColorIndex;
GraphicExtension.BlockTerminator := 0;
if ATransparent then
GraphicExtension.PackedFields:= GraphicExtension.PackedFields or 1;
Stream.Seek (Save1, soFromBeginning);
Stream.Write (GraphicExtension, SizeOf (TGraphicExtension));
// Restaurando a posição
Stream.Seek (Save2, soFromBeginning);
end;
end;
procedure TGIFEncoder.WritePalette (Palette: HPalette; PaletteLength: Integer);
var
Tripla : Integer;
Entries: array[Byte] of TPaletteEntry;
begin
FillChar (Entries, 256*SizeOf (TPaletteEntry), #0);
if GetPaletteEntries (Palette, 0, PaletteLength, Entries) = 0 then
if PaletteLength = 2 then
FillChar (Entries[1], 3, #255)
else
GetPaletteEntries (GetStockObject (DEFAULT_PALETTE), 0, PaletteLength, Entries);
for Tripla:= 0 to PaletteLength-1 do begin
Stream.Write (Entries[Tripla].peRed, 1);
Stream.Write (Entries[Tripla].peGreen, 1);
Stream.Write (Entries[Tripla].peBlue, 1);
end;
end;
procedure TGIFEncoder.WriteImage;
type
PLine= ^TLine;
TLine= array[0..0] of Byte;
TMax = array[3..12] of Word;
const
cMax2: TMax= (4, 12, 28, 60, 124, 252, 508, 1020, 2044, 4093);
cMax4: TMax= (0, 00, 16, 48, 112, 240, 496, 1008, 2032, 4081);
cMax8: TMax= (0, 00, 00, 00, 000, 000, 256, 0768, 1792, 3840); // Estes valores são assim por causa do PRIMEIRO ("Count" = 0) "ClearCode", depois do SEGUNDO "ClearCode" serão "(0, 00, 00, 00, 000, 000, 255, 0767, 1791, 3839)"
// LZW
var
Character: Byte;
Index : Integer;
Prefix : Integer;
Table : TLZWTable;
// GIF
var
ClearFlag : Boolean;
More : Boolean;
BlockSize : Byte;
Offset : Integer;
X, Y : Integer;
Block : PLine;
Line : PLine;
Max : TMax;
ClearCode : Word;
CodeSize : Word;
Count : Word;
EOFCode : Word;
FirstFree : Word;
InitCodeSize: Word;
Mask : Word;
// Inicializar a compactação do GIF
procedure Initialize;
begin
CodeSize := BitsPerPixel;
ClearCode := 1 shl CodeSize;
EOFCode := ClearCode + 1;
FirstFree := ClearCode + 2;
CodeSize := CodeSize + 1;
InitCodeSize:= CodeSize;
Line := Bitmap.ScanLine[0];
More := True;
ClearFlag := True;
X := 0;
Y := 0;
Count := 0;
BlockSize := 0;
Offset := 0;
Mask := $FFFF shr (16-CodeSize);
FillChar (Block[0], 258, #0);
case BitsPerPixel of
2: Max:= cMax2;
4: Max:= cMax4;
8: Max:= cMax8;
end;
end;
procedure Flush;
begin
if BlockSize > 0 then begin
Stream.Write (BlockSize, 1);
Stream.Write (Block[0], BlockSize);
Move (Block[BlockSize], Block[0], 3);
BlockSize:= 3;
FillChar (Block[BlockSize], 258-3, #0);
BlockSize:= 0;
end;
end;
procedure ReadChar (var Value: Byte);
begin
Value:= Line[X];
Inc (X);
if X = Bitmap.Width then begin
X:= 0;
Inc (Y);
if Y < Bitmap.Height then
Line:= Bitmap.ScanLine[Y]
else
More:= False;
end;
end;
procedure Write (Code: Word);
procedure WriteCode (NewValue: Word);
var
Longo: Integer;
Value: Word;
begin
Longo := NewValue;
BlockSize:= (Offset shr 3) mod 255;
Move (Block[BlockSize], Value, 2);
Longo:= Longo and $FFFF;
Value:= Value and Mask;
Longo:= (Longo shl (Offset and 7)) or Value; // (X mod 8) = (X and 7)
Move (Longo, Block[BlockSize], 3);
Inc (Count);
Inc (Offset, CodeSize);
Inc (BlockSize);
if (BlockSize = 255) or ((Offset shr 3) mod 255 = 0) then begin
BlockSize:= 255;
Flush;
end;
end;
begin
WriteCode (Code);
if Count >= Max[CodeSize] then begin
if CodeSize = 12 then begin
WriteCode (ClearCode);
CodeSize := InitCodeSize;
ClearFlag:= True;
Count := 1;
end
else
Inc (CodeSize);
Mask:= $FFFF shr (16-CodeSize);
end;
end;
begin
GetMem (Block, 258);
try
Table:= TLZWTable.Create;
try
// GIF
Stream.Write (BitsPerPixel, 1);
Initialize;
Write (ClearCode);
// LZW
Prefix:= 0;
while More do begin
ReadChar (Character);
if ClearFlag then begin
Table.Initialize (FirstFree);
ClearFlag:= False;
end;
Index:= Table.Find (Prefix, Character);
if Index > 0 then // Está no dicionário ?
Prefix:= Index
else begin
Write (Prefix-1);
Table.Add (Prefix, Character);
Prefix:= Character+1;
end;
end;
Write (Prefix-1);
// GIF
Write (EOFCode);
Write (0);
Flush;
Stream.Write (BlockSize, 1);
finally
Table.Free;
end;
finally
FreeMem (Block);
end;
end;
// ---------------------------------------------------------------------------------------------
function TGIF.IsValid (const FileName: String): Boolean;
var
Header: TScreenDescriptor;
Local : TStream;
begin
Result:= False;
if FileExists (FileName) then begin
Local:= TFileStream.Create (FileName, fmOpenRead);
try
Result:= (Local.Read (Header, SizeOf (TScreenDescriptor)) = SizeOf (TScreenDescriptor)) and (Header.Signature = 'GIF') and ((Header.Version = '87a') or (Header.Version = '89a'));
finally
Local.Free;
end;
end;
end;
procedure TGIF.LoadFromStream (Stream: TStream);
var
Decoder: TGIFDecoder;
Info : TGIFInfo;
begin
if Stream.Size > 0 then begin
Decoder:= TGIFDecoder.Create (Stream);
try
Decoder.Load (True);
Decoder.GetFrame (0, TBitmap (Self), Info);
finally
Decoder.Free;
end;
end;
end;
var
N: Word;
initialization
with gInitTable[0] do begin
Prefixo:= 0;
Sufixo := 0;
end;
with gInitTable[257] do begin
Prefixo:= 0;
Sufixo := 0;
end;
for N:= 0 to 255 do
with gInitTable[N+1] do begin
Prefixo:= 0;
Sufixo := N;
end;
TPicture.RegisterFileFormat ('GIF', 'GIF - Graphics Interchange Format', TGIF);
finalization
TPicture.UnRegisterGraphicClass (TGIF);
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2015 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of an Embarcadero developer tools product.
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit DataModuleUnit1;
interface
uses
System.SysUtils, System.Classes, IPPeerClient, REST.Backend.ServiceTypes,
REST.Backend.MetaTypes, System.JSON, REST.Backend.KinveyServices,
REST.Backend.Providers, REST.Backend.ServiceComponents,
REST.Backend.KinveyProvider, REST.Backend.ParseProvider, ToDoItemTypes,
Data.Bind.ObjectScope;
type
TDataModule1 = class(TDataModule)
KinveyProvider1: TKinveyProvider;
BackendStorage1: TBackendStorage;
private
FBackendList: TBackendObjectList<TToDo>;
FToDoItemsAdapter: TListBindSourceAdapter<TToDo>;
{ Private declarations }
function CreateToDoList(const AProviderID: string;
const AStorage: TBackendStorageApi): TBackendObjectList<TToDo>;
function GetToDoItemsAdapter: TBindSourceAdapter;
procedure AfterPost(Sender: TBindSourceAdapter);
procedure BeforeDelete(Sender: TBindSourceAdapter);
procedure AddBackendItem(const AItem: TToDo);
procedure UpdateBackendItem(const AItem: TToDo);
procedure DeleteBackendItem(const AItem: TToDo);
public
{ Public declarations }
procedure RefreshAdapter;
property ItemAdapter: TBindSourceAdapter read GetToDoItemsAdapter;
end;
var
DataModule1: TDataModule1;
implementation
uses System.Generics.Collections;
{$R *.dfm}
procedure TDataModule1.RefreshAdapter;
var
LList: TList<TToDo>;
LToDo: TToDo;
LOldList: TBackendObjectList<TToDo>;
begin
LOldList := FBackendList;
try
FBackendList := CreateToDoList(BackendStorage1.Provider.ProviderID, BackendStorage1.Storage);
LList := TList<TToDo>.Create;
try
for LToDo in FBackendList do
LList.Add(LToDo);
if FToDoItemsAdapter = nil then
FToDoItemsAdapter := TListBindSourceAdapter<TToDo>.Create(Self, LList, True);
FToDoItemsAdapter.SetList(LList, True);
except
LList.Free;
raise;
end;
finally
LOldList.Free;
end;
end;
function TDataModule1.CreateToDoList(const AProviderID: string; const AStorage: TBackendStorageApi): TBackendObjectList<TToDo>;
var
LQuery: TArray<string>;
LContactList: TBackendObjectList<TToDo>;
begin
// Query for the objects, sort by name
LContactList := TBackendObjectList<TToDo>.Create;
try
if SameText(AProviderID, TKinveyProvider.ProviderID) then
LQuery := TArray<string>.Create(Format('sort=%s', [TToDoNames.TitleElement]))
else if SameText(AProviderID, TParseProvider.ProviderID) then
LQuery := TArray<string>.Create(Format('order=%s', [TToDoNames.TitleElement]))
else
raise Exception.Create('Unknown provider');
AStorage.QueryObjects<TToDo>(TToDoNames.BackendClassname,
LQuery, LContactList);
except
LContactList.Free;
raise;
end;
Result := LContactList;
end;
function TDataModule1.GetToDoItemsAdapter: TBindSourceAdapter;
begin
if FToDoItemsAdapter = nil then
begin
// Create empty adapter
FToDoItemsAdapter := TListBindSourceAdapter<TToDo>.Create(Self, TList<TToDo>.Create, True);
FToDoItemsAdapter.AfterPost := AfterPost;
FToDoItemsAdapter.BeforeDelete := BeforeDelete;
end;
Result := FToDoItemsAdapter;
end;
procedure TDataModule1.AddBackendItem(const AItem: TToDo);
var
LEntity: TBackendEntityValue;
begin
BackendStorage1.Storage.CreateObject<TToDo>(
TToDoNames.BackendClassname, AItem, LEntity);
FBackendList.Add(AItem, LEntity);
end;
procedure TDataModule1.UpdateBackendItem(const AItem: TToDo);
var
LEntity: TBackendEntityValue;
LUpdate: TBackendEntityValue;
begin
LEntity := FBackendList.EntityValues[AItem];
BackendStorage1.Storage.UpdateObject<TToDo>(
LEntity, AItem, LUpdate);
end;
procedure TDataModule1.DeleteBackendItem(const AItem: TToDo);
var
LEntity: TBackendEntityValue;
begin
LEntity := FBackendList.EntityValues[AItem];
BackendStorage1.Storage.DeleteObject(
LEntity);
end;
procedure TDataModule1.BeforeDelete(Sender: TBindSourceAdapter);
var
LToDo: TToDo;
I: Integer;
begin
LToDo := FToDoItemsAdapter.List[FToDoItemsAdapter.ItemIndex];
I := FBackendList.IndexOf(LToDo);
if I >= 0 then
DeleteBackendItem(LToDo);
end;
procedure TDataModule1.AfterPost(Sender: TBindSourceAdapter);
var
LToDo: TToDo;
I: Integer;
begin
try
LToDo := FToDoItemsAdapter.List[FToDoItemsAdapter.ItemIndex];
I := FBackendList.IndexOf(LToDo);
if I >= 0 then
UpdateBackendItem(LToDo)
else
AddBackendItem(LToDo);
except
FToDoItemsAdapter.Edit; // Return to edit mode
raise;
end;
end;
end.
|
Unit WatchedDriverNames;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
Interface
Uses
Windows, IRPMonDll, Generics.Collections;
Type
TWatchableDriverName = Class
Private
FName : WideString;
FSettings : DRIVER_MONITOR_SETTINGS;
Public
Constructor Create(AName:WideString; ASettings:DRIVER_MONITOR_SETTINGS); Reintroduce; Overload;
Constructor Create(Var ARecord:DRIVER_NAME_WATCH_RECORD); Reintroduce; Overload;
Function Register:Cardinal;
Function Unregister:Cardinal;
Class Function Enumerate(AList:TList<TWatchableDriverName>):Cardinal;
Property Name : WideString Read FName;
Property Settings : DRIVER_MONITOR_SETTINGS Read FSettings;
end;
Implementation
Uses
SysUtils;
Constructor TWatchableDriverName.Create(AName:WideString; ASettings:DRIVER_MONITOR_SETTINGS);
begin
Inherited Create;
FName := AName;
FSettings := ASettings;
end;
Constructor TWatchableDriverName.Create(Var ARecord:DRIVER_NAME_WATCH_RECORD);
begin
Inherited Create;
FName := Copy(WideString(ARecord.DriverName), 1, StrLen(ARecord.DriverName));
FSettings := ARecord.MonitorSettings;
end;
Function TWatchableDriverName.Register:Cardinal;
begin
Result := IRPMonDllDriverNameWatchRegister(PWideChar(FName), FSettings);
end;
Function TWatchableDriverName.Unregister:Cardinal;
begin
Result := IRPMonDllDriverNameWatchUnregister(PWideChar(FName));
end;
Class Function TWatchableDriverName.Enumerate(AList:TList<TWatchableDriverName>):Cardinal;
Var
I : Integer;
dn : TWatchableDriverName;
tmp : PDRIVER_NAME_WATCH_RECORD;
dnCount : Cardinal;
dnArray : PDRIVER_NAME_WATCH_RECORD;
begin
Result := IRPMonDllDriverNameWatchEnum(dnArray, dnCount);
If Result = ERROR_SUCCESS Then
begin
tmp := dnArray;
For I := 0 To dnCount - 1 Do
begin
dn := TWatchableDriverName.Create(tmp^);
AList.Add(dn);
Inc(tmp);
end;
IRPMonDllDriverNameWatchEnumFree(dnArray, dnCount);
end;
end;
End.
|
unit ibSHObjectNamesManager;
interface
uses Classes, SysUtils, Forms, Graphics,
SynCompletionProposal, Menus, Controls,
SHDesignIntf, SHOptionsIntf, ibSHDesignIntf, ibSHConsts, ibSHMessages,
SynEdit,
pSHIntf, pSHCompletionProposal, pSHHighlighter, pSHSynEdit,
pSHParametersHint, pSHCommon, pSHStrUtil, pSHSqlTxtRtns,
ibSHRegExpesions;
type
TibBTObjectNamesManager = class(TBTComponent, IpSHObjectNamesManager,
IpSHCompletionProposalOptions, IpSHUserInputHistory)
private
FCodeNormalizer: IibSHCodeNormalizer;
FEditorCodeInsightOptions: ISHEditorCodeInsightOptions;
FEditorGeneralOptions: ISHEditorGeneralOptions;
FHighlighter: TpSHHighlighter;
FObjectNames: TStringList;
FCompletionProposal: TpSHCompletionProposal;
FDatabase: ISHRegistration;
FCaseCode: TpSHCaseCode;
FCaseSQLCode: TpSHCaseCode;
FCompletionEnabled: Boolean;
FCompletionExtended: Boolean;
FParametersHint: TpSHParametersHint;
FNativProposalFormKeyPress: TKeyPressEvent;
procedure CatchCodeNormilizer;
procedure CatchCodeInsightOptions;
procedure CatchEditorGeneralOptions;
protected
function IsObjectName(const MayBe: string): Boolean;
function IsCustomString(const MayBe: string): Boolean;
function InternalDoCaseCode(const Value: string): string;
procedure FormatCodeCompletion(Sender: TObject; var Value: string;
Shift: TShiftState; Index: Integer; EndToken: Char);
procedure ProposalFormKeyPress(Sender: TObject; var Key: Char);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
class function GetClassIIDClassFnc: TGUID; override;
{IpSHUserInputHistory}
function GetFindHistory: TStrings;
function GetReplaceHistory: TStrings;
function GetGotoLineNumberHistory: TStrings;
function GetPromtOnReplace: Boolean;
procedure SetPromtOnReplace(const Value: Boolean);
procedure AddToFindHistory(const AString: string);
procedure AddToReplaceHistory(const AString: string);
procedure AddToGotoLineNumberHistory(const AString: string);
{IpSHCompletionProposalOptions}
function IpSHCompletionProposalOptions.GetEnabled = GetCompletionEnabled;
procedure IpSHCompletionProposalOptions.SetEnabled = SetCompletionEnabled;
function IpSHCompletionProposalOptions.GetExtended = GetCompletionExtended;
procedure IpSHCompletionProposalOptions.SetExtended = SetCompletionExtended;
function IpSHCompletionProposalOptions.GetLinesCount = GetCompletionLinesCount;
procedure IpSHCompletionProposalOptions.SetLinesCount = SetCompletionLinesCount;
function IpSHCompletionProposalOptions.GetWidth = GetCompletionWidth;
procedure IpSHCompletionProposalOptions.SetWidth = SetCompletionWidth;
function GetCompletionEnabled: Boolean;
procedure SetCompletionEnabled(const Value: Boolean);
function GetCompletionExtended: Boolean;
procedure SetCompletionExtended(const Value: Boolean);
function GetCompletionLinesCount: Integer;
procedure SetCompletionLinesCount(const Value: Integer);
function GetCompletionWidth: Integer;
procedure SetCompletionWidth(const Value: Integer);
{IpSHObjectNamesManager}
function GetObjectNamesRetriever: IInterface;
procedure SetObjectNamesRetriever(const Value: IInterface);
function GetHighlighter: TComponent;
function GetCompletionProposal: TComponent;
function GetParametersHint: TComponent;
function GetCaseCode: TpSHCaseCode;
procedure SetCaseCode(const Value: TpSHCaseCode);
function GetCaseSQLCode: TpSHCaseCode;
procedure SetCaseSQLCode(const Value: TpSHCaseCode);
//необходимость этого обработчика вызвана неэффективностью
//предложенного в нативном компоненте метода определения
//принадлежности идентификатора к пространству имен объектов, которая
//выражается в крайне медленной работе со свойством TableNames,
//особенно при наличии нескольких экземпляров Highlighter'а, а
//также неудобством работы с этим свойством в условиях сильной
//динамичности списка объектов
procedure LinkSearchNotify(Sender: TObject; MayBe: PChar;
Position, Len: Integer; var TokenKind: TtkTokenKind);
//в данном методе должно происходить наполнение списков
//InsertList и ItemList
//ранее и в стандартной поставке код размещался в событии
//OnExecute
procedure ExecuteNotify(Kind: Integer; Sender: TObject;
var CurrentInput: string; var x, y: Integer; var CanExecute: Boolean);
procedure FindDeclaration(const AObjectName: string);
//Для обслуживания ситуаций с квотированием и регистрозависимостью
function IsIdentifiresEqual(Sender: TObject;
AIdentifire1, AIdentifire2: string): Boolean;
property ObjectNames: TStringList read FObjectNames write FObjectNames;
{End of IpSHObjectNamesManager}
property Highlighter: TpSHHighlighter read FHighlighter
write FHighlighter;
property CompletionProposal: TpSHCompletionProposal
read FCompletionProposal write FCompletionProposal;
property ParametersHint: TpSHParametersHint read FParametersHint
write FParametersHint;
end;
implementation
procedure Register;
begin
BTRegisterComponents([TibBTObjectNamesManager]);
end;
{ TibBTObjectNamesManager }
constructor TibBTObjectNamesManager.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Highlighter := TpSHHighlighter.Create(Self);
Highlighter.SQLDialect := sqlInterbase;
Highlighter.TableNameAttri.Foreground := clGreen;
Highlighter.TableNameAttri.Style := [fsUnderline];
Highlighter.ObjectNamesManager := Self as IpSHObjectNamesManager;
CompletionProposal := TpSHCompletionProposal.Create(Application.MainForm); // Owner должен быть именно Application.MainForm!
CompletionProposal.FreeNotification(Self);
CompletionProposal.Options := CompletionProposal.Options + [scoUseInsertList, scoUsePrettyText];
CompletionProposal.TriggerChars := '.';
CompletionProposal.Columns.Add.BiggestWord := ' ' + SClassHintSystemTable;
CompletionProposal.CompletionProposalOptions := Self;
CompletionProposal.OnCodeCompletion := FormatCodeCompletion;
FNativProposalFormKeyPress := CompletionProposal.OnKeyPress;
CompletionProposal.OnKeyPress := ProposalFormKeyPress;
FParametersHint := TpSHParametersHint.Create(Application.MainForm);
FParametersHint.FreeNotification(Self);
FParametersHint.ShortCut := ShortCut(Ord(' '), [ssShift, ssCtrl]);
FParametersHint.Form.ClBackground := clInfoBk;
FParametersHint.ProposalHintRetriever :=
Designer.GetDemon(IpSHProposalHintRetriever) as IpSHProposalHintRetriever;
end;
destructor TibBTObjectNamesManager.Destroy;
begin
Highlighter.Free;
if Assigned(FCompletionProposal) then
FCompletionProposal.Free;
if Assigned(FParametersHint) then
FParametersHint.Free;
// FParametersHint, FCompletionProposal может быть разрушеен (при выходе из программы) формой, на колторую положен, а именно Application.MainForm
inherited;
end;
procedure TibBTObjectNamesManager.CatchCodeNormilizer;
var
vDatabase: IibSHDatabase;
begin
if not Assigned(FCodeNormalizer) then
if Supports(FDatabase, IibSHDatabase, vDatabase) then
if Supports(Designer.GetDemon(IibSHCodeNormalizer), IibSHCodeNormalizer, FCodeNormalizer) then
ReferenceInterface(FCodeNormalizer, opInsert);
end;
procedure TibBTObjectNamesManager.CatchCodeInsightOptions;
begin
if not Assigned(FEditorCodeInsightOptions) then
if Supports(Designer.GetDemon(ISHEditorCodeInsightOptions), ISHEditorCodeInsightOptions, FEditorCodeInsightOptions) then
ReferenceInterface(FEditorCodeInsightOptions, opInsert);
end;
procedure TibBTObjectNamesManager.CatchEditorGeneralOptions;
begin
if not Assigned(FEditorGeneralOptions) then
if Supports(Designer.GetDemon(ISHEditorGeneralOptions), ISHEditorGeneralOptions, FEditorGeneralOptions) then
ReferenceInterface(FEditorGeneralOptions, opInsert);
end;
function TibBTObjectNamesManager.IsObjectName(
const MayBe: string): Boolean;
var
vMayBe: string;
begin
Result := False;
if not Assigned(FDatabase) then Exit;
vMayBe := MayBe;
CatchCodeNormilizer;
if Assigned(FCodeNormalizer) then
vMayBe := FCodeNormalizer.SourceDDLToMetadataName(MayBe)
else
vMayBe := MayBe;
Result := FDatabase.GetObjectNameList.IndexOf(vMayBe) <> -1;;
end;
function TibBTObjectNamesManager.IsCustomString(
const MayBe: string): Boolean;
var
vMayBe: string;
begin
Result := False;
if not Assigned(FDatabase) then Exit;
vMayBe := MayBe;
CatchCodeNormilizer;
if Assigned(FCodeNormalizer) then
vMayBe := FCodeNormalizer.SourceDDLToMetadataName(MayBe)
else
vMayBe := MayBe;
CatchCodeInsightOptions;
if Assigned(FEditorCodeInsightOptions) then
Result := FEditorCodeInsightOptions.CustomStrings.IndexOf(vMayBe) <> -1
else
Result := False;
end;
function TibBTObjectNamesManager.InternalDoCaseCode(const Value: string): string;
var
vDatabase: IibSHDatabase;
begin
CatchCodeNormilizer;
if Assigned(FCodeNormalizer) and Supports(FDatabase, IibSHDatabase, vDatabase) then
Result := FCodeNormalizer.MetadataNameToSourceDDLCase(vDatabase, Value)
else
Result := Value;
end;
procedure TibBTObjectNamesManager.FormatCodeCompletion(Sender: TObject;
var Value: string; Shift: TShiftState; Index: Integer; EndToken: Char);
var
vDatabase: IibSHDatabase;
function IsKeyword(const MayBe: string): Boolean;
var
vKeywordsList: IibSHKeywordsList;
begin
with TpSHCompletionProposal(Sender) do
if Assigned(TpSHSynEdit(Form.CurrentEditor).KeywordsManager) and
Supports(TpSHSynEdit(Form.CurrentEditor).KeywordsManager, IibSHKeywordsList, vKeywordsList) then
Result := (vKeywordsList.AllKeywordList.IndexOf(MayBe) <> -1)
else
Result := False;
end;
begin
if (Sender is TpSHCompletionProposal) and
(TpSHCompletionProposal(Sender).Form.AssignedList.Count = 0) then
Exit
else
begin
if IsKeyword(Value) then
Value := DoCaseCode(Value, FCaseSQLCode)
else
begin
CatchCodeNormilizer;
if Assigned(FCodeNormalizer) and Supports(FDatabase, IibSHDatabase, vDatabase) then
Value := FCodeNormalizer.MetadataNameToSourceDDLCase(vDatabase, Value);
end;
end;
end;
procedure TibBTObjectNamesManager.ProposalFormKeyPress(Sender: TObject;
var Key: Char);
var
vKey: Char;
begin
vKey := Key;
if Assigned(FNativProposalFormKeyPress) then
FNativProposalFormKeyPress(Sender, Key);
if vKey = '.' then
begin
//Для того, что переформировался список комплишена
TpSHCompletionProposal(TComponent(Sender).Owner).ActivateCompletion(
TSynEdit(TpSHCompletionProposal(TComponent(Sender).Owner).Form.CurrentEditor));
end;
end;
class function TibBTObjectNamesManager.GetClassIIDClassFnc: TGUID;
begin
Result := IpSHObjectNamesManager;
end;
function TibBTObjectNamesManager.GetFindHistory: TStrings;
begin
CatchEditorGeneralOptions;
if Assigned(FEditorGeneralOptions) then
Result := FEditorGeneralOptions.FindTextHistory
else
Result := nil;
end;
function TibBTObjectNamesManager.GetReplaceHistory: TStrings;
begin
CatchEditorGeneralOptions;
if Assigned(FEditorGeneralOptions) then
Result := FEditorGeneralOptions.ReplaceTextHistory
else
Result := nil;
end;
function TibBTObjectNamesManager.GetGotoLineNumberHistory: TStrings;
begin
CatchEditorGeneralOptions;
if Assigned(FEditorGeneralOptions) then
Result := FEditorGeneralOptions.LineNumberHistory
else
Result := nil;
end;
function TibBTObjectNamesManager.GetPromtOnReplace: Boolean;
begin
CatchEditorGeneralOptions;
if Assigned(FEditorGeneralOptions) then
Result := FEditorGeneralOptions.PromtOnReplace
else
Result := True;
end;
procedure TibBTObjectNamesManager.SetPromtOnReplace(const Value: Boolean);
begin
CatchEditorGeneralOptions;
if Assigned(FEditorGeneralOptions) then
FEditorGeneralOptions.PromtOnReplace := Value;
end;
procedure TibBTObjectNamesManager.AddToFindHistory(const AString: string);
begin
CatchEditorGeneralOptions;
if Assigned(FEditorGeneralOptions) then
if FEditorGeneralOptions.FindTextHistory.IndexOf(AString) = -1 then
FEditorGeneralOptions.FindTextHistory.Insert(0, AString);
end;
procedure TibBTObjectNamesManager.AddToReplaceHistory(
const AString: string);
begin
CatchEditorGeneralOptions;
if Assigned(FEditorGeneralOptions) then
if FEditorGeneralOptions.ReplaceTextHistory.IndexOf(AString) = -1 then
FEditorGeneralOptions.ReplaceTextHistory.Insert(0, AString);
end;
procedure TibBTObjectNamesManager.AddToGotoLineNumberHistory(
const AString: string);
begin
CatchEditorGeneralOptions;
if Assigned(FEditorGeneralOptions) then
if FEditorGeneralOptions.LineNumberHistory.IndexOf(AString) = -1 then
FEditorGeneralOptions.LineNumberHistory.Insert(0, AString);
end;
function TibBTObjectNamesManager.GetObjectNamesRetriever: IInterface;
begin
Result := FDatabase;
end;
procedure TibBTObjectNamesManager.SetObjectNamesRetriever(
const Value: IInterface);
begin
ReferenceInterface(FDatabase, opRemove);
if Supports(Value, ISHRegistration, FDatabase) then
ReferenceInterface(FDatabase, opInsert);
end;
function TibBTObjectNamesManager.GetHighlighter: TComponent;
begin
Result := FHighlighter;
end;
function TibBTObjectNamesManager.GetCompletionProposal: TComponent;
begin
Result := FCompletionProposal;
end;
function TibBTObjectNamesManager.GetParametersHint: TComponent;
begin
Result := FParametersHint;
end;
function TibBTObjectNamesManager.GetCaseCode: TpSHCaseCode;
begin
Result := FCaseCode;
end;
procedure TibBTObjectNamesManager.SetCaseCode(const Value: TpSHCaseCode);
begin
FCaseCode := Value;
end;
function TibBTObjectNamesManager.GetCaseSQLCode: TpSHCaseCode;
begin
Result := FCaseSQLCode;
end;
procedure TibBTObjectNamesManager.SetCaseSQLCode(const Value: TpSHCaseCode);
begin
FCaseSQLCode := Value;
end;
function TibBTObjectNamesManager.GetCompletionEnabled: Boolean;
begin
Result := FCompletionEnabled;
end;
procedure TibBTObjectNamesManager.SetCompletionEnabled(
const Value: Boolean);
begin
FCompletionEnabled := Value;
end;
function TibBTObjectNamesManager.GetCompletionExtended: Boolean;
begin
Result := FCompletionExtended;
end;
procedure TibBTObjectNamesManager.SetCompletionExtended(
const Value: Boolean);
begin
FCompletionExtended := Value;
end;
function TibBTObjectNamesManager.GetCompletionLinesCount: Integer;
begin
CatchCodeInsightOptions;
if Assigned(FEditorCodeInsightOptions) then
Result := FEditorCodeInsightOptions.WindowLineCount
else
Result := 8;
end;
procedure TibBTObjectNamesManager.SetCompletionLinesCount(
const Value: Integer);
begin
CatchCodeInsightOptions;
if Assigned(FEditorCodeInsightOptions) then
FEditorCodeInsightOptions.WindowLineCount := Value;
end;
function TibBTObjectNamesManager.GetCompletionWidth: Integer;
begin
CatchCodeInsightOptions;
if Assigned(FEditorCodeInsightOptions) then
Result := FEditorCodeInsightOptions.WindowWidth
else
Result := 200;
end;
procedure TibBTObjectNamesManager.SetCompletionWidth(const Value: Integer);
begin
CatchCodeInsightOptions;
if Assigned(FEditorCodeInsightOptions) then
FEditorCodeInsightOptions.WindowWidth := Value;
end;
procedure TibBTObjectNamesManager.LinkSearchNotify(Sender: TObject;
MayBe: PChar; Position, Len: Integer; var TokenKind: TtkTokenKind);
var
s: string;
begin
case TokenKind of
tkIdentifier:
begin
SetString(s, MayBe, Len);
if IsObjectName(s) then
TokenKind := tkTableName
else
if IsCustomString(s) then
TokenKind := tkCustomStrings;
end;
tkString: //Interbase only
begin
//начало серверо зависимого кода обработки имени объекта до его проверки
//для третьего диалекта IB - названия объектов могут быть в кавычках
SetString(s, MayBe, Len);
if (s[1] = '"') and (s[Len] = '"') then
if IsObjectName(s) then
TokenKind := tkTableName;
end;
end;
end;
procedure TibBTObjectNamesManager.ExecuteNotify(Kind: Integer;
Sender: TObject; var CurrentInput: string; var x, y: Integer;
var CanExecute: Boolean);
var
vObjectName: string;
vTrigger: IibSHTrigger;
vFieldListRetriever: IpSHFieldListRetriever;
FieldList: TStringList;
I: Integer;
vColor: string;
vType: string;
vDatabase: IibSHDatabase;
function GetColorStringFor(ForObjectType: TGUID): string;
begin
if IsEqualGUID(ForObjectType, IibSHField) then Result := ColorToString(clBlue) else
if IsEqualGUID(ForObjectType, IibSHProcParam) then Result := ColorToString(clBlue) else
if IsEqualGUID(ForObjectType, IibSHDomain) then Result := ColorToString(clOlive) else
if IsEqualGUID(ForObjectType, IibSHTable) then Result := ColorToString(clBlue) else
if IsEqualGUID(ForObjectType, IibSHView) then Result := ColorToString(clNavy) else
if IsEqualGUID(ForObjectType, IibSHProcedure) then Result := ColorToString(clTeal) else
if IsEqualGUID(ForObjectType, IibSHProcParam) then Result := ColorToString(clTeal) else
if IsEqualGUID(ForObjectType, IibSHTrigger) then Result := ColorToString(clPurple) else
if IsEqualGUID(ForObjectType, IibSHGenerator) then Result := ColorToString(clGreen) else
if IsEqualGUID(ForObjectType, IibSHException) then Result := ColorToString(clRed) else
if IsEqualGUID(ForObjectType, IibSHFunction) then Result := ColorToString(clMaroon) else
if IsEqualGUID(ForObjectType, IibSHFilter) then Result := ColorToString(clMaroon) else
if IsEqualGUID(ForObjectType, IibSHRole) then Result := ColorToString(clBlack) else
if IsEqualGUID(ForObjectType, IibCustomStrings) then Result := ColorToString(clGray) else
Result := ColorToString(clBlack);
end;
function IsPublishedObjectType(AObjectGUID: TGUID): Boolean;
begin
Result := not IsEqualGUID(AObjectGUID, IibSHTrigger);
end;
function GetObjectTypeDescription(AObjectGUID: TGUID): string;
var
vComponentClass: TBTComponentClass;
begin
vComponentClass := Designer.GetComponent(AObjectGUID);
if Assigned(vComponentClass) then
Result := {AnsiLowerCase(}vComponentClass.GetAssociationClassFnc{)}
else
Result := SObjectName;
end;
procedure AddObjectNames(AObjectGUID: TGUID);
var
CurrentList: TStrings;
I: Integer;
vType: string;
vColor: string;
S: string;
begin
if Assigned(FDatabase) and IsPublishedObjectType(AObjectGUID) then
begin
vType := GetObjectTypeDescription(AObjectGUID);
vColor := GetColorStringFor(AObjectGUID);
CurrentList := FDatabase.GetObjectNameList(AObjectGUID);
for I := 0 to CurrentList.Count - 1 do
with TpSHCompletionProposal(Sender) do
begin
S := InternalDoCaseCode(CurrentList[I]);
ItemList.Add(Format(sProposalTemplate, [vColor, vType, S, '']));
InsertList.Add(CurrentList[I]);
end;
end;
end;
procedure AddCustomStrings;
var
CurrentList: TStrings;
I: Integer;
vType: string;
vColor: string;
S: string;
begin
vType := SCustomString;
vColor := GetColorStringFor(IibCustomStrings);
CatchCodeInsightOptions;
if Assigned(FEditorCodeInsightOptions) then
begin
CurrentList := FEditorCodeInsightOptions.CustomStrings;
for I := 0 to CurrentList.Count - 1 do
with TpSHCompletionProposal(Sender) do
begin
S := InternalDoCaseCode(CurrentList[I]);
ItemList.Add(Format(sProposalTemplate, [vColor, vType, S, '']));
InsertList.Add(CurrentList[I]);
end;
end;
end;
procedure AddKeywords(AObjectGUID: TGUID);
var
CurrentList: TStrings;
I: Integer;
vType: string;
vColor: string;
vItem, vHint: string;
vKeywordsList: IibSHKeywordsList;
begin
with TpSHCompletionProposal(Sender) do
if Assigned(TpSHSynEdit(Form.CurrentEditor).KeywordsManager) and
Supports(TpSHSynEdit(Form.CurrentEditor).KeywordsManager, IibSHKeywordsList, vKeywordsList) then
begin
if IsEqualGUID(AObjectGUID, IibSHFunction) then
begin
vType := SBuilInFunction;
CurrentList := vKeywordsList.FunctionList;
end
else
if IsEqualGUID(AObjectGUID, IibSHDomain) then
begin
vType := SDataType;
CurrentList := vKeywordsList.DataTypeList;
end
else
begin
vType := SKeyWord;
CurrentList := vKeywordsList.KeywordList;
end;
vColor := GetColorStringFor(AObjectGUID);
for I := 0 to CurrentList.Count - 1 do
with TpSHCompletionProposal(Sender) do
begin
vItem := DoCaseCode(CurrentList.Names[I], FCaseSQLCode);
vHint := CurrentList.ValueFromIndex[I];
ItemList.Add(Format(sProposalTemplate, [vColor, vType, vItem, vHint]));
InsertList.Add(CurrentList.Names[I]);
end;
end;
end;
function FindTableNameForTrigger: string;
var
vBody: string;
vPosBegin, vPosEnd: Integer;
begin
Result := EmptyStr;
with TpSHCompletionProposal(Sender) do
begin
vBody := Form.CurrentEditor.Lines.Text;
vPosBegin := PosExtCI('FOR', vBody, CharsAfterClause, CharsAfterClause);
if vPosBegin > 0 then
begin
Inc(vPosBegin, 4);
while (I <= Length(vBody)) and (vBody[vPosBegin] in CharsAfterClause) do Inc(vPosBegin);
if vPosBegin <= Length(vBody) then
begin
vPosEnd := vPosBegin + 1;
if vBody[vPosBegin] = '"' then
begin
while (vPosEnd <= Length(vBody)) and (vBody[vPosEnd] <> '"') do Inc(vPosEnd);
Inc(vPosEnd);
end
else
while (vPosEnd <= Length(vBody)) and (not (vBody[vPosEnd] in CharsAfterClause)) do Inc(vPosEnd);
Result := Copy(vBody, vPosBegin, vPosEnd - vPosBegin);
CatchCodeNormilizer;
if Assigned(FCodeNormalizer) then
Result := FCodeNormalizer.SourceDDLToMetadataName(Result);
end;
end;
end;
end;
procedure AddVariables;
var
vInputList, vOutPutList, vLocalList: TStringList;
I: Integer;
begin
vInputList := TStringList.Create;
vOutPutList := TStringList.Create;
vLocalList := TStringList.Create;
try
with TpSHCompletionProposal(Sender) do
begin
ParseProcParams(Form.CurrentEditor.Lines, vInputList, vOutPutList, vLocalList);
vColor := GetColorStringFor(IibSHProcParam);
// vType := GetObjectTypeDescription(IibSHProcParam);
for I := 0 to vInputList.Count - 1 do
begin
ItemList.Add(Format(sProposalTemplate, [vColor, SProcParamInput, InternalDoCaseCode(Trim(vInputList.Names[I])), vInputList.ValueFromIndex[I]]));
InsertList.Add(Trim(vInputList.Names[I]));
end;
for I := 0 to vOutPutList.Count - 1 do
begin
ItemList.Add(Format(sProposalTemplate, [vColor, SProcParamOutput, InternalDoCaseCode(Trim(vOutPutList.Names[I])), vOutPutList.ValueFromIndex[I]]));
InsertList.Add(Trim(vOutPutList.Names[I]));
end;
for I := 0 to vLocalList.Count - 1 do
begin
ItemList.Add(Format(sProposalTemplate, [vColor, SProcParamLocal, InternalDoCaseCode(Trim(vLocalList.Names[I])), vLocalList.ValueFromIndex[I]]));
InsertList.Add(Trim(vLocalList.Names[I]));
end;
end;
finally
vInputList.Free;
vOutPutList.Free;
vLocalList.Free;
end;
end;
begin
if FCompletionEnabled then
begin
with TpSHCompletionProposal(Sender) do
begin
ItemList.Clear;
InsertList.Clear;
if (TpSHCompletionProposal(Sender).NeedObjectType = ntVariable) and
(not (Supports(Designer.CurrentComponent, IibSHProcedure) or
Supports(Designer.CurrentComponent, IibSHTrigger))) then
NeedObjectType := ntAll;
case NeedObjectType of
ntAll:
begin
AddKeywords(IibSHDomain);
AddKeywords(IibSHFunction);
AddKeywords(IUnknown);
AddObjectNames(IibSHDomain);
AddObjectNames(IibSHTable);
AddObjectNames(IibSHIndex);
AddObjectNames(IibSHView);
AddObjectNames(IibSHProcedure);
AddObjectNames(IibSHTrigger);
AddObjectNames(IibSHGenerator);
AddObjectNames(IibSHException);
AddObjectNames(IibSHFunction);
AddObjectNames(IibSHFilter);
AddObjectNames(IibSHRole);
AddObjectNames(IibSHSystemTable);
AddCustomStrings;
if Supports(Designer.CurrentComponent, IibSHTrigger) or
Supports(Designer.CurrentComponent, IibSHProcedure) then
AddVariables;
end;
ntKeyWords: AddKeywords(IUnknown);
ntDataTypes: AddKeywords(IibSHDomain);
ntBuildInFunctions: AddKeywords(IibSHFunction);
ntDomain:
begin
AddObjectNames(IibSHDomain);
AddKeywords(IibSHDomain);
end;
ntTable: AddObjectNames(IibSHTable);
ntView: AddObjectNames(IibSHView);
ntProcedure: AddObjectNames(IibSHProcedure);
ntTrigger: AddObjectNames(IibSHTrigger);
ntGenerator: AddObjectNames(IibSHGenerator);
ntException: AddObjectNames(IibSHException);
ntFunction:
begin
AddObjectNames(IibSHFunction);
AddKeywords(IibSHFunction);
end;
ntFilter: AddObjectNames(IibSHFilter);
ntRole: AddObjectNames(IibSHRole);
ntField:
begin
ItemList.Clear;
InsertList.Clear;
if ((AnsiUpperCase(CurrentInput) = 'NEW') or
(AnsiUpperCase(CurrentInput) = 'OLD')) and
Supports(Designer.CurrentComponent, IibSHTrigger, vTrigger) then
begin
if vTrigger.State = csCreate then
vObjectName := FindTableNameForTrigger
else
vObjectName := vTrigger.TableName;
end
else
begin
CatchCodeNormilizer;
if Assigned(FCodeNormalizer) then
vObjectName := FCodeNormalizer.SourceDDLToMetadataName(CurrentInput)
else
vObjectName := CurrentInput;
end;
FieldList := TStringList.Create;
try
if Supports(Designer.GetDemon(IpSHFieldListRetriever), IpSHFieldListRetriever, vFieldListRetriever) and
Supports(Designer.CurrentComponent, IibSHDatabase, vDatabase) then
begin
vFieldListRetriever.Database := vDatabase;
vFieldListRetriever.GetFieldList(vObjectName, FieldList);
vColor := GetColorStringFor(IibSHField);
vType := GetObjectTypeDescription(IibSHField);
for I := 0 to FieldList.Count - 1 do
begin
ItemList.Add(Format(sProposalTemplate, [vColor, vType, InternalDoCaseCode(FieldList.Names[I]), FieldList.ValueFromIndex[I]]));
InsertList.Add(FieldList.Names[I]);
end;
end;
finally
FieldList.Free;
end;
CurrentInput := TpSHSynEdit(Form.CurrentEditor).GetWordAtRowCol(TpSHSynEdit(Form.CurrentEditor).CaretXY);
end;
ntVariable:
begin
ItemList.Clear;
InsertList.Clear;
AddVariables;
CompletionStart := CompletionStart + 1;
CurrentInput := TpSHSynEdit(Form.CurrentEditor).GetWordAtRowCol(TpSHSynEdit(Form.CurrentEditor).CaretXY);
end;
end;
end;
CanExecute := True;
end
else
CanExecute := False;
end;
procedure TibBTObjectNamesManager.FindDeclaration(
const AObjectName: string);
begin
CatchCodeNormilizer;
if Assigned(FCodeNormalizer) then
Designer.JumpTo(Designer.CurrentComponent.InstanceIID, IUnknown, FCodeNormalizer.SourceDDLToMetadataName(AObjectName))
else
Designer.JumpTo(Designer.CurrentComponent.InstanceIID, IUnknown, AObjectName);
end;
function TibBTObjectNamesManager.IsIdentifiresEqual(Sender: TObject;
AIdentifire1, AIdentifire2: string): Boolean;
var
S1, S2: string;
begin
CatchCodeNormilizer;
if Assigned(FCodeNormalizer) then
begin
S1 := FCodeNormalizer.SourceDDLToMetadataName(AIdentifire1);
S2 := FCodeNormalizer.SourceDDLToMetadataName(AIdentifire2);
Result := CompareText(S1, S2) = 0;
end
else
Result := CompareText(AIdentifire1, AIdentifire2) = 0;
end;
procedure TibBTObjectNamesManager.Notification(AComponent: TComponent;
Operation: TOperation);
begin
if (Operation = opRemove) then
begin
if AComponent = FCompletionProposal then
CompletionProposal := nil;
if AComponent = FParametersHint then
FParametersHint := nil;
if AComponent.IsImplementorOf(FCodeNormalizer) then
FCodeNormalizer := nil;
if AComponent.IsImplementorOf(FEditorCodeInsightOptions) then
FEditorCodeInsightOptions := nil;
if AComponent.IsImplementorOf(FEditorGeneralOptions) then
FEditorGeneralOptions := nil;
if AComponent.IsImplementorOf(FDatabase) then
FDatabase := nil;
end;
inherited Notification(AComponent, Operation);
end;
initialization
Register;
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uChildForm;
{$I cef.inc}
interface
uses
{$IFDEF DELPHI16_UP}
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls,
System.UITypes,
{$ELSE}
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, Dialogs, ExtCtrls,
{$ENDIF}
uCEFChromium, uCEFWindowParent, uCEFInterfaces, uCEFConstants, uCEFTypes, uMainForm;
type
TChildForm = class(TForm)
CEFWindowParent1: TCEFWindowParent;
Chromium1: TChromium;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormDestroy(Sender: TObject);
procedure Chromium1AfterCreated(Sender: TObject;
const browser: ICefBrowser);
procedure Chromium1Close(Sender: TObject; const browser: ICefBrowser;
out Result: Boolean);
procedure Chromium1PreKeyEvent(Sender: TObject;
const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: PMsg;
out isKeyboardShortcut, Result: Boolean);
procedure Chromium1KeyEvent(Sender: TObject;
const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: PMsg;
out Result: Boolean);
procedure Chromium1BeforeClose(Sender: TObject;
const browser: ICefBrowser);
private
// Variables to control when can we destroy the form safely
FCanClose : boolean; // Set to True in TChromium.OnBeforeClose
FClosing : boolean; // Set to True in the CloseQuery event.
FHomepage : string;
protected
procedure BrowserCreatedMsg(var aMessage : TMessage); message CEFBROWSER_CREATED;
procedure BrowserDestroyMsg(var aMessage : TMessage); message CEFBROWSER_DESTROY;
procedure WMMove(var aMessage : TWMMove); message WM_MOVE;
procedure WMMoving(var aMessage : TMessage); message WM_MOVING;
procedure WMEnterMenuLoop(var aMessage: TMessage); message WM_ENTERMENULOOP;
procedure WMExitMenuLoop(var aMessage: TMessage); message WM_EXITMENULOOP;
procedure HandleKeyUp(const aMsg : TMsg; var aHandled : boolean);
procedure HandleKeyDown(const aMsg : TMsg; var aHandled : boolean);
public
property Closing : boolean read FClosing;
property Homepage : string read FHomepage write FHomepage;
end;
implementation
{$R *.dfm}
uses
uCEFApplication;
// Destruction steps
// =================
// 1. FormCloseQuery calls TChromium.CloseBrowser
// 2. TChromium.OnClose sends a CEFBROWSER_DESTROY message to destroy CEFWindowParent1 in the main thread.
// 3. TChromium.OnBeforeClose sets FCanClose := True and sends WM_CLOSE to the form.
procedure TChildForm.Chromium1AfterCreated(Sender: TObject; const browser: ICefBrowser);
begin
PostMessage(Handle, CEFBROWSER_CREATED, 0, 0);
end;
procedure TChildForm.Chromium1BeforeClose(Sender: TObject; const browser: ICefBrowser);
begin
FCanClose := True;
PostMessage(Handle, WM_CLOSE, 0, 0);
end;
procedure TChildForm.Chromium1Close(Sender: TObject; const browser: ICefBrowser; out Result: Boolean);
begin
PostMessage(Handle, CEFBROWSER_DESTROY, 0, 0);
Result := False;
end;
procedure TChildForm.Chromium1KeyEvent(Sender: TObject;
const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: PMsg;
out Result: Boolean);
var
TempMsg : TMsg;
begin
Result := False;
if (event <> nil) and (osEvent <> nil) then
case osEvent.Message of
WM_KEYUP :
begin
TempMsg := osEvent^;
HandleKeyUp(TempMsg, Result);
end;
WM_KEYDOWN :
begin
TempMsg := osEvent^;
HandleKeyDown(TempMsg, Result);
end;
end;
end;
procedure TChildForm.HandleKeyUp(const aMsg : TMsg; var aHandled : boolean);
var
TempMessage : TMessage;
TempKeyMsg : TWMKey;
begin
TempMessage.Msg := aMsg.message;
TempMessage.wParam := aMsg.wParam;
TempMessage.lParam := aMsg.lParam;
TempKeyMsg := TWMKey(TempMessage);
if (TempKeyMsg.CharCode = VK_ESCAPE) then
begin
aHandled := True;
PostMessage(Handle, WM_CLOSE, 0, 0);
end;
end;
procedure TChildForm.HandleKeyDown(const aMsg : TMsg; var aHandled : boolean);
var
TempMessage : TMessage;
TempKeyMsg : TWMKey;
begin
TempMessage.Msg := aMsg.message;
TempMessage.wParam := aMsg.wParam;
TempMessage.lParam := aMsg.lParam;
TempKeyMsg := TWMKey(TempMessage);
if (TempKeyMsg.CharCode = VK_ESCAPE) then aHandled := True;
end;
procedure TChildForm.Chromium1PreKeyEvent(Sender: TObject;
const browser: ICefBrowser; const event: PCefKeyEvent; osEvent: PMsg;
out isKeyboardShortcut, Result: Boolean);
begin
Result := False;
if (event <> nil) and
(event.kind in [KEYEVENT_KEYDOWN, KEYEVENT_KEYUP]) and
(event.windows_key_code = VK_ESCAPE) then
isKeyboardShortcut := True;
end;
procedure TChildForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TChildForm.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
CanClose := FCanClose;
if not(FClosing) then
begin
FClosing := True;
Chromium1.CloseBrowser(True);
end;
end;
procedure TChildForm.FormCreate(Sender: TObject);
begin
FCanClose := False;
FClosing := False;
end;
procedure TChildForm.FormDestroy(Sender: TObject);
begin
// Tell the main form that a child has been destroyed.
// The main form will check if this was the last child to close itself
PostMessage(MainForm.Handle, CEFBROWSER_CHILDDESTROYED, 0, 0);
end;
procedure TChildForm.FormShow(Sender: TObject);
begin
Chromium1.CreateBrowser(CEFWindowParent1, '');
end;
procedure TChildForm.WMMove(var aMessage : TWMMove);
begin
inherited;
if (Chromium1 <> nil) then Chromium1.NotifyMoveOrResizeStarted;
end;
procedure TChildForm.WMMoving(var aMessage : TMessage);
begin
inherited;
if (Chromium1 <> nil) then Chromium1.NotifyMoveOrResizeStarted;
end;
procedure TChildForm.WMEnterMenuLoop(var aMessage: TMessage);
begin
inherited;
if (aMessage.wParam = 0) and (GlobalCEFApp <> nil) then GlobalCEFApp.OsmodalLoop := True;
end;
procedure TChildForm.WMExitMenuLoop(var aMessage: TMessage);
begin
inherited;
if (aMessage.wParam = 0) and (GlobalCEFApp <> nil) then GlobalCEFApp.OsmodalLoop := False;
end;
procedure TChildForm.BrowserCreatedMsg(var aMessage : TMessage);
begin
CEFWindowParent1.UpdateSize;
Chromium1.LoadURL(FHomepage);
end;
procedure TChildForm.BrowserDestroyMsg(var aMessage : TMessage);
begin
CEFWindowParent1.Free;
end;
end.
|
unit HlpArrayUtils;
{$I ..\Include\HashLib.inc}
interface
uses
SysUtils,
HlpHashLibTypes;
type
TArrayUtils = class sealed(TObject)
public
class function AreEqual(const A, B: THashLibByteArray): Boolean;
overload; static;
class function ConstantTimeAreEqual(const a_ar1, a_ar2: THashLibByteArray)
: Boolean; static;
class procedure Fill(const buf: THashLibByteArray; from, &to: Int32;
filler: Byte); overload; static;
class procedure Fill(const buf: THashLibUInt32Array; from, &to: Int32;
filler: UInt32); overload; static;
class procedure Fill(const buf: THashLibUInt64Array; from, &to: Int32;
filler: UInt64); overload; static;
class procedure ZeroFill(const buf: THashLibByteArray); overload; static;
class procedure ZeroFill(const buf: THashLibUInt32Array); overload; static;
class procedure ZeroFill(const buf: THashLibUInt64Array); overload; static;
end;
implementation
{ TArrayUtils }
class function TArrayUtils.AreEqual(const A, B: THashLibByteArray): Boolean;
begin
if System.Length(A) <> System.Length(B) then
begin
Result := false;
Exit;
end;
Result := CompareMem(A, B, System.Length(A) * System.SizeOf(Byte));
end;
{$B+}
class function TArrayUtils.ConstantTimeAreEqual(const a_ar1,
a_ar2: THashLibByteArray): Boolean;
var
I: Int32;
diff: UInt32;
begin
diff := UInt32(System.Length(a_ar1)) xor UInt32(System.Length(a_ar2));
I := 0;
while (I <= System.High(a_ar1)) and (I <= System.High(a_ar2)) do
begin
diff := diff or (UInt32(a_ar1[I] xor a_ar2[I]));
System.Inc(I);
end;
Result := diff = 0;
end;
{$B-}
class procedure TArrayUtils.Fill(const buf: THashLibByteArray; from, &to: Int32;
filler: Byte);
begin
if buf <> Nil then
begin
System.FillChar(buf[from], (&to - from) * System.SizeOf(Byte), filler);
end;
end;
class procedure TArrayUtils.Fill(const buf: THashLibUInt32Array;
from, &to: Int32; filler: UInt32);
begin
if buf <> Nil then
begin
{$IFDEF FPC}
System.FillDWord(buf[from], (&to - from), filler);
{$ELSE}
while from < &to do
begin
buf[from] := filler;
System.Inc(from);
end;
{$ENDIF}
end;
end;
class procedure TArrayUtils.Fill(const buf: THashLibUInt64Array;
from, &to: Int32; filler: UInt64);
begin
if buf <> Nil then
begin
{$IFDEF FPC}
System.FillQWord(buf[from], (&to - from), filler);
{$ELSE}
while from < &to do
begin
buf[from] := filler;
System.Inc(from);
end;
{$ENDIF}
end;
end;
class procedure TArrayUtils.ZeroFill(const buf: THashLibByteArray);
begin
TArrayUtils.Fill(buf, 0, System.Length(buf), Byte(0));
end;
class procedure TArrayUtils.ZeroFill(const buf: THashLibUInt32Array);
begin
TArrayUtils.Fill(buf, 0, System.Length(buf), UInt32(0));
end;
class procedure TArrayUtils.ZeroFill(const buf: THashLibUInt64Array);
begin
TArrayUtils.Fill(buf, 0, System.Length(buf), UInt64(0));
end;
end.
|
{ Модуль работы с пинпадом сбербанка }
{
Порядок вызова функций библиотеки
При оплате (возврате) покупки по банковской карте кассовая программа должна вызвать из библиотеки Сбербанка функцию card_authorize(), заполнив поля TType и Amount и указав нулевые значения в остальных полях.
По окончании работы функции необходимо проанализировать поле RCode. Если в нем содержится значение «0» или «00», авторизация считается успешно выполненной, в противном случае – отклоненной.
Кроме этого, необходимо проверить значение поля Check. Если оно не равно NULL, его необходимо отправить на печать (в нефискальном режиме) и затем удалить вызовом функции GlobalFree().
В случае, если внешняя программа не обеспечивает гарантированной печати карточного чека из поля Check, она может использовать следующую логику:
1) Выполнить функцию card_authorize().
2) После завершения работы функции card_authorize(), если транзакция выполнена успешно, вызвать функцию SuspendTrx() и приступить к печати чека.
3) Если чек напечатан успешно, вызвать функцию CommitTrx().
4) Если во время печати чека возникла неустранимая проблема, вызвать функцию RollbackTrx() для отмены платежа.
Если в ходе печати чека произойдет зависание ККМ или сбой питания, то транзакция останется в «подвешенном» состоянии. При следующем сеансе связи с банком она автоматически отменится.
При закрытии смены кассовая программа должна вызвать из библиотеки Сбербанка функцию close_day(), заполнив поле TType = 7 и указав нулевые значения в остальных полях.
По окончании работы функции необходимо проверить значение поля Check. Если поле Check не равно NULL, его необходимо отправить на печать (в нефискальном режиме) и после этого удалить вызовом функции GlobaFree().
}
// Свернуть все регионы
// Shift + Ctrl + K + R
unit PinPad.Pilot_nt;
interface
uses Classes, Windows, SysUtils, Generics.Collections;
const
LibName: string = '.\pinpad\pilot_nt.dll';
{$REGION 'Константы'}
// Типы операций
OP_PURCHASE = 1; // Оплата покупки
OP_RETURN = 3; // Возврат либо отмена покупки
OP_FUNDS = 6; // Безнал.перевод
OP_CLOSEDAY = 7; // Закрытие дня (Сверка итогов)
OP_SHIFT = 9; // Контрольная лента (НЕ ПРОВЕРЕНО)
OP_PREAUTH = 51; // Предавторизация
OP_COMPLETION = 52; // Завершение расчета
OP_CASHIN = 53; // Взнос наличных
OP_CASHIN_COMP = 54; // Подтверждение взноса
// Типы карт
CT_USER = 0; // Выбор из меню
CT_VISA = 1; // Visa
CT_EUROCARD = 2; // Eurocard/Mastercard
CT_CIRRUS = 3; // Cirrus/Maestro
CT_AMEX = 4; // Amex
CT_DINERS = 5; // DinersCLub
CT_ELECTRON = 6; // VisaElectron
CT_PRO100 = 7; // PRO100
CT_CASHIER = 8; // Cashier card
CT_SBERCARD = 9; // Sbercard
MAX_ENCR_DATA = 32;
{$ENDREGION}
type
{$REGION 'Документация и обертка над dll'}
// Структура ответа
PAuthAnswer = ^TAuthAnswer;
TAuthAnswer = packed record
TType: integer;
// IN Тип транзакции (1 - Оплата, 3 - Возврат/отмена оплаты, 7 - Сверка итогов)
Amount: UINT; // IN Сумма операции в копейках
Rcode: array [0 .. 2] of AnsiChar;
// OUT Результат авторизации (0 или 00 - успешная авторизация, другие значения - ошибка)
AMessage: array [0 .. 15] of AnsiChar;
// OUT В случае отказа в авторизации содержит краткое сообщение о причине отказа
CType: integer;
{ OUT Тип обслуженной карты. Возможные значения:
1 – VISA
2 – MasterCard
3 – Maestro
4 – American Express
5 – Diners Club
6 – VISA Electron }
Check: PAnsiChar;
// OUT При успешной авторизации содержит образ карточного чека, который вызывающая программа должна отправить на печать, а затем освободить вызовом функции GlobalFree()
// Может иметь значение nil. В этом случае никаких действий с ним вызывающая программа выполнять не должна.
end;
// Расширенная структура
PAuthAnswer2 = ^TAuthAnswer2;
TAuthAnswer2 = packed record
AuthAnswer: TAuthAnswer;
AuthCode: array [0 .. 6] of AnsiChar;
end;
// Еще одна расширенная структура
PAuthAnswer3 = ^TAuthAnswer3;
TAuthAnswer3 = packed record
AuthAnswer: TAuthAnswer;
AuthCode: array [0 .. 6] of AnsiChar;
CardID: array [0 .. 24] of AnsiChar;
end;
// Еще более расширенная структура
PAuthAnswer4 = ^TAuthAnswer4;
TAuthAnswer4 = packed record
AuthAnswer: TAuthAnswer;
AuthCode: array [0 .. 6] of AnsiChar; // выход: код авторизации
CardID: array [0 .. 24] of AnsiChar; // выход: идентификатор карты
ErrorCode: integer; // выход: код ошибки
TransDate: array [0 .. 19] of AnsiChar; // выход: дата и время операции
TransNumber: integer; // выход: номер операции
end;
// Еще более расширенная структура
PAuthAnswer5 = ^TAuthAnswer5;
TAuthAnswer5 = packed record
AuthAnswer: TAuthAnswer;
RRN: array [0 .. 12] of AnsiChar;
AuthCode: array [0 .. 6] of AnsiChar;
end;
PAuthAnswer6 = ^TAuthAnswer6;
TAuthAnswer6 = packed record
AuthAnswer: TAuthAnswer;
AuthCode: array [0 .. 6] of AnsiChar; // added after communication with HRS
CardID: array [0 .. 24] of AnsiChar; // выход: идентификатор карты
ErrorCode: integer;
TransDate: array [0 .. 19] of AnsiChar; // выход: дата и время операции
TransNumber: integer; // выход: номер операции
RRN: Array [0 .. 12] of AnsiChar;
// вход/выход: ссылочный номер предавторизации
end;
PAuthAnswer7 = ^TAuthAnswer7;
TAuthAnswer7 = packed record
AuthAnswer: TAuthAnswer;
// вход/выход: основные параметры операции (см.выше)
AuthCode: array [0 .. 6] of AnsiChar; // Код авторизации
// OUT При успешной авторизации (по международной карте) содержит код авторизации. При операции по карте Сберкарт поле будет заполнено символами ‘*’.
CardID: array [0 .. 24] of AnsiChar; // номер карты
// OUT При успешной авторизации (по международной карте) содержит номер карты. Для международных карт все символы, кроме первых 6 и последних 4, будут заменены символами ‘*’.
SberOwnCard: integer;
// OUT Содержит 1, если обслуженная карта выдана Сбербанком, или 0 – в противном случае
end;
PAuthAnswer8 = ^TAuthAnswer8;
TAuthAnswer8 = packed record
AuthAnswer: TAuthAnswer;
// вход/выход: основные параметры операции (см.выше)
AuthCode: array [0 .. 6] of AnsiChar; // Код авторизации
// OUT При успешной авторизации (по международной карте) содержит код авторизации. При операции по карте Сберкарт поле будет заполнено символами ‘*’.
CardID: array [0 .. 24] of AnsiChar; // номер карты
// OUT При успешной авторизации (по международной карте) содержит номер карты. Для международных карт все символы, кроме первых 6 и последних 4, будут заменены символами ‘*’.
ErrorCode: integer;
TransDate: array [0 .. 19] of AnsiChar; // выход: дата и время операции
TransNumber: integer; // выход: номер операции
RRN: Array [0 .. 12] of AnsiChar;
EncryptedData: array [0 .. MAX_ENCR_DATA * 2] of AnsiChar;
// вход/выход: шифрованый номер карты и срок действия
end;
// Ответ предавторизации
PPreauthRec = ^TPreauthRec;
TPreauthRec = packed record
Amount: UINT; // вход: сумма предавторизации в копейках
RRN: array [0 .. 12] of AnsiChar; // вход: ссылочный номер предавторизации
Last4Digits: array [0 .. 4] of AnsiChar;
// вход: последние 4 цифры номера карты
ErrorCode: UINT; // выход: код завершения: 0 - успешно.
end;
PAuthAnswer9 = ^TAuthAnswer9;
TAuthAnswer9 = packed record
AuthAnswer: TAuthAnswer;
// вход/выход: основные параметры операции (см.выше)
AuthCode: array [0 .. 6] of AnsiChar; // Код авторизации
// OUT При успешной авторизации (по международной карте) содержит код авторизации. При операции по карте Сберкарт поле будет заполнено символами ‘*’.
CardID: array [0 .. 24] of AnsiChar; // номер карты
// OUT При успешной авторизации (по международной карте) содержит номер карты. Для международных карт все символы, кроме первых 6 и последних 4, будут заменены символами ‘*’.
SberOwnCard: integer;
// OUT Содержит 1, если обслуженная карта выдана Сбербанком, или 0 – в противном случае
Hash: array [0 .. 40] of AnsiChar;
// OUT хеш SHA1 от номера карты в формате ASCIIZ
end;
PAuthAnswer10 = ^TAuthAnswer10;
TAuthAnswer10 = packed record
AuthAnswer: TAuthAnswer;
AuthCode: array [0 .. 6] of AnsiChar; // Код авторизации
CardID: array [0 .. 24] of AnsiChar; // номер карты
ErrorCode: integer;
TransDate: array [0 .. 19] of AnsiChar; // выход: дата и время операции
TransNumber: integer; // выход: номер операции
SberOwnCard: integer;
Hash: array [0 .. 40] of AnsiChar;
// выход: хеш от номера карты, в формате ASCII с нулевым байтом в конце
end;
PAuthAnswer11 = ^TAuthAnswer11;
TAuthAnswer11 = packed record
AuthAnswer: TAuthAnswer;
AuthCode: array [0 .. 6] of AnsiChar; // Код авторизации
CardID: array [0 .. 24] of AnsiChar; // номер карты
ErrorCode: integer;
TransDate: array [0 .. 19] of AnsiChar; // выход: дата и время операции
TransNumber: integer; // выход: номер операции
SberOwnCard: integer;
Hash: array [0 .. 40] of AnsiChar;
// выход: хеш от номера карты, в формате ASCII с нулевым байтом в конце
Track3: array [0 .. 107] of AnsiChar; // выход: третья дорожка карты
end;
// Получение текущего отчета. При значении поля TType = 0 формируется
// краткий отчет, иначе - полный
// __declspec(dllexport) int get_statistics(struct auth_answer *auth_answer);
TGetStatistics = function(auth_ans: PAuthAnswer): integer; cdecl;
TCardAuthorize = function(track2: Pchar; auth_ans: PAuthAnswer)
: integer; cdecl;
{
Функция используется для проведения авторизации по банковской карте, а также при необходимости для возврата/отмены платежа.
Входные данные:
track2 - Может иметь значение NULL или содержать данные 2-й дорожки карты, считанные кассовой программой
TType - Тип операции: 1 – оплата, 3 –возврат/отмена оплаты.
Amount - Сумма операции в копейках.
Выходные параметры:
RCode - Результат авторизации. Значения «00» или «0» означают успешную авторизацию, любые другие – отказ в авторизации.
AMessage - В случае отказа в авторизации содержит краткое сообщение о причине отказа. Внимание: поле не имеет завершающего байта 0х00.
CType
Тип обслуженной карты. Возможные значения:
1 – VISA
2 – MasterCard
3 – Maestro
4 – American Express
5 – Diners Club
6 – VISA Electron
Сheck
При успешной авторизации содержит образ карточного чека, который вызывающая программа должна отправить на печать, а затем освободить вызовом функции GlobalFree().
Может иметь значение NULL. В этом случае никаких действий с ним вызывающая программа выполнять не должна.
AuthCode - При успешной авторизации (по международной карте) содержит код авторизации. При операции по карте Сберкарт поле будет заполнено символами ‘*’.
CardID - При успешной авторизации (по международной карте) содержит номер карты. Для международных карт все символы, кроме первых 6 и последних 4, будут заменены символами ‘*’.
SberOwnCard - Содержит 1, если обслуженная карта выдана Сбербанком, или 0 – в противном случае.
}
TCardAuthorize7 = function(track2: Pchar; auth_ans: PAuthAnswer7)
: integer; cdecl;
// Выполнение операций по картам с возвратом дополнительных данных.
// track2 - данные дорожки карты с магнитной полосой. Если NULL, то
// будет предложено считать карту
//
// auth_answer2...auth_answer7 - см. описание полей структуры
// __declspec(dllexport) int card_authorize8(char *track2, struct auth_answer8 *auth_answer);
TCardAuthorize2 = function(track2: Pchar; auth_ans: PAuthAnswer2)
: integer; cdecl;
TCardAuthorize3 = function(track2: Pchar; auth_ans: PAuthAnswer3)
: integer; cdecl;
TCardAuthorize4 = function(track2: Pchar; auth_ans: PAuthAnswer4)
: integer; cdecl;
TCardAuthorize5 = function(track2: Pchar; auth_ans: PAuthAnswer5)
: integer; cdecl;
TCardAuthorize6 = function(track2: Pchar; auth_ans: PAuthAnswer6)
: integer; cdecl;
TCardAuthorize8 = function(track2: Pchar; auth_ans: PAuthAnswer8)
: integer; cdecl;
TCardAuthorize9 = function(track2: Pchar; auth_ans: PAuthAnswer9)
: integer; cdecl;
TCardAuthorize10 = function(track2: Pchar; auth_ans: PAuthAnswer10)
: integer; cdecl;
TCardAuthorize11 = function(track2: Pchar; auth_ans: PAuthAnswer11)
: integer; cdecl;
//
// __declspec(dllexport) int card_complete_multi_auth8(char* track2,
// struct auth_answer8* auth_ans,
// struct preauth_rec* pPreAuthList,
// int NumAuths);
TCardCompleteMultiAuth8 = function(track2: Pchar; auth_ans: PAuthAnswer8;
pPreauthList: PPreauthRec; NumAuths: integer): integer; cdecl;
// Деинициализация
TDone = procedure(); cdecl;
// Получение номера версии
TGetVer = function(): UINT; cdecl;
// Получить номер терминала
TGetTerminalID = function(pTerminalID: Pchar): integer; cdecl;
// Чтение карты (возвращаются 4 последние цифры и хеш от номера карты)
TReadCard = function(Last4Digits: Pchar; Hash: Pchar): integer; cdecl;
TReadCardSB = function(Last4Digits: Pchar; Hash: Pchar): integer; cdecl;
{
Функция проверяет наличие пинпада. При успешном выполнении возвращает 0 (пинпад подключен),
при неудачном – код ошибки (пинпад не подключен или неисправен).
}
TTestPinPad = function(): integer; cdecl;
{
Функция используется для ежедневного закрытия смены по картам и формирования отчетов.
Входные параметры:
TType - Тип операции: 7 – закрытие дня по картам.
Amount - Не используется.
Выходные параметры:
Rcode - Не используется.
AMessage - Не используется.
CType - Не используется.
Check - Содержит образ отчета по картам, который вызывающая программа должна отправить на печать, а затем освободить вызовом функции GlobalFree().
Может иметь значение NULL. В этом случае никаких действий с ним вызывающая программа выполнять не должна.
}
TCloseDay = function(auth_ans: PAuthAnswer): integer; cdecl;
{
Чтение карты (возвращется полный номер и срок действия карты в формате YYMM)
Номер может иметь длину от 13 до 19 цифр.
Чтобы потом использовать эти данные для авторизации, их нужно будет
сформатировать так:
format('Track2 %s=%s', [CardNo, ValidThru])
}
TReadCardFull = function(CardNo: PAnsiString; ValidThru: PAnsiString)
: integer;
{
// Данные второй дорожки могут иметь длину до 40 символов.
// Вторая дорожка имеет формат:
//
// nnnn...nn=yymmddd...d
//
// где '=' - символ-разделитель
// nnn...n - номер карты
// yymm - срок действия карты (ГГММ)
// ddd...d - служебные данные карты
Track2 - Буфер, куда функция записывает прочитанную 2-ю дорожку.
}
TReadTrack2 = function(track2: Pchar): integer; cdecl;
// Чтение карты асинхронное
//
TEnableReader = function(hDestWindow: HWND; msg: UINT): integer; cdecl;
TDisableReader = function(): integer; cdecl;
// SuspendTrx
{
Функция переводит последнюю успешную транзакцию в «подвешенное» состояние. Если транзакция находится в этом состоянии, то при следующем сеансе связи с банком она будет отменена.
Входные параметры:
dwAmount - Сумма операции (в копейках).
pAuthCode - Код авторизации.
Функция сверяет переданные извне параметры (сумму и код авторизации) со значениями в последней успешной операции, которая была проведена через библиотеку. Если хотя бы один параметр не совпадает, функция возвращает код ошибки 4140 и не выполняет никаких действий.
}
TSuspendTrx = function(dwAmount: DWORD; pAuthCode: PAnsiString)
: integer; cdecl;
// CommitTrx
{
Функция возвращает последнюю успешную транзакцию в «нормальное» состояние. После этого транзакция будет включена в отчет и спроцессирована как успешная. Перевести ее снова в «подвешенное» состояние будет уже нельзя.
Входные параметры:
dwAmount - Сумма операции (в копейках).
pAuthCode - Код авторизации.
Функция сверяет переданные извне параметры (сумму и код авторизации) со значениями в последней успешной операции, которая была проведена через библиотеку. Если хотя бы один параметр не совпадает, функция возвращает код ошибки 4140 и не выполняет никаких действий.
}
TCommitTrx = function(dwAmount: DWORD; pAuthCode: PAnsiString)
: integer; cdecl;
// RollBackTrx
{
Функция вызывает немедленную отмену последней успешной операции (возможно, ранее переведенную в «подвешенное» состояние, хотя это и не обязательно). Если транзакция уже была возвращена в «нормальное» состояние функцией CommitTrx(), то функция RollbackTrx() завершится с кодом ошибки 4141, не выполняя никаких действий.
Входные параметры:
dwAmount - Сумма операции (в копейках).
pAuthCode - Код авторизации.
Функция сверяет переданные извне параметры (сумму и код авторизации) со значениями в последней успешной операции, которая была проведена через библиотеку. Если хотя бы один параметр не совпадает, функция возвращает код ошибки 4140 и не выполняет никаких действий.
}
TRollBackTrx = function(dwAmount: DWORD; pAuthCode: PAnsiString)
: integer; cdecl;
// Войти в техническое меню.
// При выходе поле Check может содержать образ документа для печати.
//
TServiceMenu = function(AuthAnswer: PAuthAnswer): integer; cdecl;
// Установить хендлы для вывода на экран
//
TSetGUIHandles = function(hText: HWND; hEdit: HWND): integer; cdecl;
TReadCardTrack3 = function(Last4Digits: Pchar; Hash: Pchar; pTrack3: Pchar)
: integer; cdecl;
TAbortTransaction = function(): integer; cdecl;
{$ENDREGION}
type
TPinpadException = class(Exception);
TPinPad = class(TObject)
strict private
FTerminalID: string; // номер терминала
FGUITextHandle: HWND; // Хендлы для GUI
FGUIEditHandle: HWND; //
FAuthAnswer: TAuthAnswer;
FAuthAnswer2: TAuthAnswer2;
FAuthAnswer3: TAuthAnswer3;
FAuthAnswer4: TAuthAnswer4;
FAuthAnswer5: TAuthAnswer5;
FAuthAnswer6: TAuthAnswer6;
FAuthAnswer7: TAuthAnswer7;
FAuthAnswer8: TAuthAnswer8;
FAuthAnswer9: TAuthAnswer9;
FAuthAnswer10: TAuthAnswer10;
FAuthAnswer11: TAuthAnswer11;
FCheque: String;
FAuthCode: String;
FCardID: String;
FRRN: String;
FLastError: integer;
FLastErrorMessage: string;
protected
// Получить ID терминала
function GetTerminalID: string;
function SetGUIHandles(ATextHandle: HWND; AEditHandle: HWND): integer;
// Сбросить все буферы
procedure ClearBuffers;
function GetLastErrorMessage: string;
public
// Если создаем с хендлами, то отображаем все в них, иначе будет нативный интерфейс сбера
function Initialize(ATextHandle: HWND; AEditHandle: HWND): boolean;
// Деинициализация (вызов _Done из библиотеки)
procedure Done;
destructor Destroy; reintroduce; override;
// Получить текст ошибки по коду
function GetMessageText(ErrorCode: integer): String;
// Проверяем готовность пинпада
function TestPinpad: boolean;
// Авторизация, оплата, возврат
function CardAuth(Summ: Double; Operation: integer): integer;
function CardAuth2(Summ: Double; Operation: integer): integer;
function CardAuth3(Summ: Double; Operation: integer): integer;
function CardAuth4(Summ: Double; Operation: integer): integer;
function CardAuth5(Summ: Double; Operation: integer): integer;
function CardAuth6(Summ: Double; Operation: integer): integer;
function CardAuth7(Summ: Double; Operation: integer): integer;
function CardAuth8(Summ: Double; Operation: integer): integer;
function CardAuth9(Summ: Double; Operation: integer): integer;
function CardAuth10(Summ: Double; Operation: integer): integer;
function CardAuth11(Summ: Double; Operation: integer): integer;
function ReadTrack2: string;
function ReadTrack3: string;
function SuspendTrx: integer;
function CommitTrx: integer;
function RollBackTrx: integer;
function TryReturn(Amount: Double): boolean;
function TryPurchase(Amount: Double): boolean;
// Немедленная отмена транзакции и незавершенных транзакций
function AbortTransaction: integer;
// Контрольная лента
function SberShift(IsDetailed: boolean = False): integer;
// Сверка итогов
function CloseDay: integer;
// Сервисное меню
function ServiceMenu: integer;
published
property TerminalID: string read GetTerminalID;
property AuthAnswer: TAuthAnswer read FAuthAnswer;
property AuthAnswer2: TAuthAnswer2 read FAuthAnswer2;
property AuthAnswer3: TAuthAnswer3 read FAuthAnswer3;
property AuthAnswer4: TAuthAnswer4 read FAuthAnswer4;
property AuthAnswer5: TAuthAnswer5 read FAuthAnswer5;
property AuthAnswer6: TAuthAnswer6 read FAuthAnswer6;
property AuthAnswer7: TAuthAnswer7 read FAuthAnswer7;
property AuthAnswer8: TAuthAnswer8 read FAuthAnswer8;
property AuthAnswer9: TAuthAnswer9 read FAuthAnswer9;
property AuthAnswer10: TAuthAnswer10 read FAuthAnswer10;
property AuthAnswer11: TAuthAnswer11 read FAuthAnswer11;
property Cheque: string read FCheque;
property CardID: string read FCardID;
property AuthCode: string read FAuthCode;
property RRN: string read FRRN;
property LastError: integer read FLastError;
property LastErrorMessage: string read GetLastErrorMessage;
end;
implementation
{ TPinPad }
function TPinPad.AbortTransaction: integer;
var
H: THandle;
Func: TAbortTransaction;
begin
H := LoadLibrary(Pchar(LibName));
if H <= 0 then
begin
raise TPinpadException.Create(Format('Не могу загрузить %s', [LibName]));
Exit;
end;
try
@Func := GetProcAddress(H, Pchar('_AbortTransaction'));
if not Assigned(Func) then
raise TPinpadException.Create
('Функция _AbortTransaction не найдена в pilot_nt.dll');
try
Result := Func;
FLastError := Result;
except
on E: Exception do
RaiseLastOSError;
end;
finally
Func := nil;
FreeLibrary(H);
end;
end;
function TPinPad.CardAuth(Summ: Double; Operation: integer): integer;
var
H: THandle;
Func: TCardAuthorize;
Sum: UINT;
begin
ClearBuffers;
Sum := Round(Summ * 100);
FAuthAnswer.Amount := Sum;
FAuthAnswer.TType := Operation;
FAuthAnswer.CType := 0;
H := LoadLibrary(Pchar(LibName));
try
@Func := GetProcAddress(H, Pchar('_card_authorize'));
if not Assigned(Func) then
raise TPinpadException.Create
('Функция _card_authorize не найдена в pilot_nt.dll');
try
Result := Func(nil, @FAuthAnswer);
FLastError := Result;
FCheque := PAnsiChar(FAuthAnswer.Check);
FLastErrorMessage := AnsiString(FAuthAnswer.AMessage);
except
on E: Exception do
RaiseLastOSError;
end;
finally
Func := nil;
FreeLibrary(H);
end;
end;
function TPinPad.CardAuth10(Summ: Double; Operation: integer): integer;
var
H: THandle;
Func: TCardAuthorize10;
Sum: UINT;
begin
ClearBuffers;
Sum := Round(Summ * 100);
FAuthAnswer.Amount := Sum;
FAuthAnswer.TType := Operation;
FAuthAnswer.CType := 0;
FAuthAnswer10.AuthAnswer := FAuthAnswer;
H := LoadLibrary(Pchar(LibName));
try
@Func := GetProcAddress(H, Pchar('_card_authorize10'));
if not Assigned(Func) then
raise TPinpadException.Create
('Функция _card_authorize10 не найдена в pilot_nt.dll');
try
Result := Func(nil, @FAuthAnswer10);
FLastError := Result;
FAuthAnswer := FAuthAnswer10.AuthAnswer;
FCheque := PAnsiChar(FAuthAnswer.Check);
FAuthCode := AnsiString(FAuthAnswer10.AuthCode);
FCardID := AnsiString(FAuthAnswer10.CardID);
FLastErrorMessage := AnsiString(FAuthAnswer.AMessage);
except
on E: Exception do
RaiseLastOSError;
end;
finally
Func := nil;
FreeLibrary(H);
end;
end;
function TPinPad.CardAuth11(Summ: Double; Operation: integer): integer;
var
H: THandle;
Func: TCardAuthorize11;
Sum: UINT;
begin
ClearBuffers;
Sum := Round(Summ * 100);
FAuthAnswer.Amount := Sum;
FAuthAnswer.TType := Operation;
FAuthAnswer.CType := 0;
FAuthAnswer11.AuthAnswer := FAuthAnswer;
H := LoadLibrary(Pchar(LibName));
try
@Func := GetProcAddress(H, Pchar('_card_authorize11'));
if not Assigned(Func) then
raise TPinpadException.Create
('Функция _card_authorize11 не найдена в pilot_nt.dll');
try
Result := Func(nil, @FAuthAnswer11);
FLastError := Result;
FAuthAnswer := FAuthAnswer11.AuthAnswer;
FCheque := PAnsiChar(FAuthAnswer.Check);
FAuthCode := AnsiString(FAuthAnswer11.AuthCode);
FCardID := AnsiString(FAuthAnswer11.CardID);
FLastErrorMessage := AnsiString(FAuthAnswer.AMessage);
except
on E: Exception do
RaiseLastOSError;
end;
finally
Func := nil;
FreeLibrary(H);
end;
end;
function TPinPad.CardAuth2(Summ: Double; Operation: integer): integer;
var
H: THandle;
Func: TCardAuthorize2;
Sum: UINT;
begin
ClearBuffers;
Sum := Round(Summ * 100);
FAuthAnswer.Amount := Sum;
FAuthAnswer.TType := Operation;
FAuthAnswer.CType := 0;
FAuthAnswer2.AuthAnswer := FAuthAnswer;
H := LoadLibrary(Pchar(LibName));
try
@Func := GetProcAddress(H, Pchar('_card_authorize2'));
if not Assigned(Func) then
raise TPinpadException.Create
('Функция _card_authorize2 не найдена в pilot_nt.dll');
try
Result := Func(nil, @FAuthAnswer2);
FLastError := Result;
FAuthAnswer := FAuthAnswer2.AuthAnswer;
FCheque := PAnsiChar(FAuthAnswer.Check);
FAuthCode := AnsiString(FAuthAnswer2.AuthCode);
FLastErrorMessage := AnsiString(FAuthAnswer.AMessage);
except
on E: Exception do
RaiseLastOSError;
end;
finally
Func := nil;
FreeLibrary(H);
end;
end;
function TPinPad.CardAuth3(Summ: Double; Operation: integer): integer;
var
H: THandle;
Func: TCardAuthorize3;
Sum: UINT;
begin
ClearBuffers;
Sum := Round(Summ * 100);
FAuthAnswer.Amount := Sum;
FAuthAnswer.TType := Operation;
FAuthAnswer.CType := 0;
FAuthAnswer3.AuthAnswer := FAuthAnswer;
H := LoadLibrary(Pchar(LibName));
try
@Func := GetProcAddress(H, Pchar('_card_authorize3'));
if not Assigned(Func) then
raise TPinpadException.Create
('Функция _card_authorize3 не найдена в pilot_nt.dll');
try
Result := Func(nil, @FAuthAnswer3);
FLastError := Result;
FAuthAnswer := FAuthAnswer3.AuthAnswer;
FCheque := PAnsiChar(FAuthAnswer.Check);
FAuthCode := AnsiString(FAuthAnswer3.AuthCode);
FCardID := AnsiString(FAuthAnswer3.CardID);
FLastErrorMessage := AnsiString(FAuthAnswer.AMessage);
except
on E: Exception do
RaiseLastOSError;
end;
finally
Func := nil;
FreeLibrary(H);
end;
end;
function TPinPad.CardAuth4(Summ: Double; Operation: integer): integer;
var
H: THandle;
Func: TCardAuthorize4;
Sum: UINT;
begin
ClearBuffers;
Sum := Round(Summ * 100);
FAuthAnswer.Amount := Sum;
FAuthAnswer.TType := Operation;
FAuthAnswer.CType := 0;
FAuthAnswer7.AuthAnswer := FAuthAnswer;
H := LoadLibrary(Pchar(LibName));
try
@Func := GetProcAddress(H, Pchar('_card_authorize4'));
if not Assigned(Func) then
raise TPinpadException.Create
('Функция _card_authorize4 не найдена в pilot_nt.dll');
try
Result := Func(nil, @FAuthAnswer4);
FLastError := Result;
FAuthAnswer := FAuthAnswer4.AuthAnswer;
FCheque := PAnsiChar(FAuthAnswer.Check);
FAuthCode := AnsiString(FAuthAnswer4.AuthCode);
FCardID := AnsiString(FAuthAnswer4.CardID);
FLastErrorMessage := AnsiString(FAuthAnswer.AMessage);
except
on E: Exception do
RaiseLastOSError;
end;
finally
Func := nil;
FreeLibrary(H);
end;
end;
function TPinPad.CardAuth5(Summ: Double; Operation: integer): integer;
var
H: THandle;
Func: TCardAuthorize5;
Sum: UINT;
begin
ClearBuffers;
Sum := Round(Summ * 100);
FAuthAnswer.Amount := Sum;
FAuthAnswer.TType := Operation;
FAuthAnswer.CType := 0;
FAuthAnswer5.AuthAnswer := FAuthAnswer;
H := LoadLibrary(Pchar(LibName));
try
@Func := GetProcAddress(H, Pchar('_card_authorize5'));
if not Assigned(Func) then
raise TPinpadException.Create
('Функция _card_authorize5 не найдена в pilot_nt.dll');
try
Result := Func(nil, @FAuthAnswer5);
FLastError := Result;
FAuthAnswer := FAuthAnswer5.AuthAnswer;
FCheque := PAnsiChar(FAuthAnswer.Check);
FAuthCode := AnsiString(FAuthAnswer5.AuthCode);
FLastErrorMessage := AnsiString(FAuthAnswer.AMessage);
except
on E: Exception do
RaiseLastOSError;
end;
finally
Func := nil;
FreeLibrary(H);
end;
end;
function TPinPad.CardAuth6(Summ: Double; Operation: integer): integer;
var
H: THandle;
Func: TCardAuthorize6;
Sum: UINT;
begin
ClearBuffers;
Sum := Round(Summ * 100);
FAuthAnswer.Amount := Sum;
FAuthAnswer.TType := Operation;
FAuthAnswer.CType := 0;
FAuthAnswer6.AuthAnswer := FAuthAnswer;
H := LoadLibrary(Pchar(LibName));
try
@Func := GetProcAddress(H, Pchar('_card_authorize6'));
if not Assigned(Func) then
raise TPinpadException.Create
('Функция _card_authorize6 не найдена в pilot_nt.dll');
try
Result := Func(nil, @FAuthAnswer6);
FLastError := Result;
FAuthAnswer := FAuthAnswer6.AuthAnswer;
FCheque := PAnsiChar(FAuthAnswer.Check);
FAuthCode := AnsiString(FAuthAnswer6.AuthCode);
FCardID := AnsiString(FAuthAnswer6.CardID);
FLastErrorMessage := AnsiString(FAuthAnswer.AMessage);
except
on E: Exception do
RaiseLastOSError;
end;
finally
Func := nil;
FreeLibrary(H);
end;
end;
function TPinPad.CardAuth7(Summ: Double; Operation: integer): integer;
var
H: THandle;
Func: TCardAuthorize7;
Sum: UINT;
begin
ClearBuffers;
Sum := Round(Summ * 100);
FAuthAnswer.Amount := Sum;
FAuthAnswer.TType := Operation;
FAuthAnswer.CType := 0;
FAuthAnswer7.AuthAnswer := FAuthAnswer;
H := LoadLibrary(Pchar(LibName));
try
@Func := GetProcAddress(H, Pchar('_card_authorize7'));
if not Assigned(Func) then
raise TPinpadException.Create
('Функция _card_authorize7 не найдена в pilot_nt.dll');
try
Result := Func(nil, @FAuthAnswer7);
FLastError := Result;
FAuthAnswer := FAuthAnswer7.AuthAnswer;
FCheque := PAnsiChar(FAuthAnswer.Check);
FAuthCode := AnsiString(FAuthAnswer7.AuthCode);
FCardID := AnsiString(FAuthAnswer7.CardID);
FLastErrorMessage := AnsiString(FAuthAnswer.AMessage);
except
on E: Exception do
RaiseLastOSError;
end;
finally
Func := nil;
FreeLibrary(H);
end;
end;
function TPinPad.CardAuth8(Summ: Double; Operation: integer): integer;
var
H: THandle;
Func: TCardAuthorize8;
Sum: UINT;
begin
ClearBuffers;
Sum := Round(Summ * 100);
FAuthAnswer.Amount := Sum;
FAuthAnswer.TType := Operation;
FAuthAnswer.CType := 0;
FAuthAnswer8.AuthAnswer := FAuthAnswer;
H := LoadLibrary(Pchar(LibName));
try
@Func := GetProcAddress(H, Pchar('_card_authorize8'));
if not Assigned(Func) then
raise TPinpadException.Create
('Функция _card_authorize8 не найдена в pilot_nt.dll');
try
Result := Func(nil, @FAuthAnswer8);
FLastError := Result;
FAuthAnswer := FAuthAnswer8.AuthAnswer;
FCheque := PAnsiChar(FAuthAnswer.Check);
FAuthCode := AnsiString(FAuthAnswer8.AuthCode);
FCardID := AnsiString(FAuthAnswer8.CardID);
FLastErrorMessage := AnsiString(FAuthAnswer.AMessage);
except
on E: Exception do
RaiseLastOSError;
end;
finally
Func := nil;
FreeLibrary(H);
end;
end;
function TPinPad.CardAuth9(Summ: Double; Operation: integer): integer;
var
H: THandle;
Func: TCardAuthorize9;
Sum: UINT;
begin
ClearBuffers;
Sum := Round(Summ * 100);
FAuthAnswer.Amount := Sum;
FAuthAnswer.TType := Operation;
FAuthAnswer.CType := 0;
FAuthAnswer9.AuthAnswer := FAuthAnswer;
H := LoadLibrary(Pchar(LibName));
try
@Func := GetProcAddress(H, Pchar('_card_authorize9'));
if not Assigned(Func) then
raise TPinpadException.Create
('Функция _card_authorize9 не найдена в pilot_nt.dll');
try
Result := Func(nil, @FAuthAnswer9);
FLastError := Result;
FAuthAnswer := FAuthAnswer9.AuthAnswer;
FCheque := PAnsiChar(FAuthAnswer.Check);
FAuthCode := AnsiString(FAuthAnswer9.AuthCode);
FCardID := AnsiString(FAuthAnswer9.CardID);
FLastErrorMessage := AnsiString(FAuthAnswer.AMessage);
except
on E: Exception do
RaiseLastOSError;
end;
finally
Func := nil;
FreeLibrary(H);
end;
end;
procedure TPinPad.ClearBuffers;
begin
ZeroMemory(@FAuthAnswer, SizeOf(FAuthAnswer));
ZeroMemory(@FAuthAnswer2, SizeOf(FAuthAnswer2));
ZeroMemory(@FAuthAnswer3, SizeOf(FAuthAnswer3));
ZeroMemory(@FAuthAnswer4, SizeOf(FAuthAnswer4));
ZeroMemory(@FAuthAnswer5, SizeOf(FAuthAnswer5));
ZeroMemory(@FAuthAnswer6, SizeOf(FAuthAnswer6));
ZeroMemory(@FAuthAnswer7, SizeOf(FAuthAnswer7));
ZeroMemory(@FAuthAnswer8, SizeOf(FAuthAnswer8));
ZeroMemory(@FAuthAnswer9, SizeOf(FAuthAnswer9));
ZeroMemory(@FAuthAnswer10, SizeOf(FAuthAnswer10));
ZeroMemory(@FAuthAnswer11, SizeOf(FAuthAnswer11));
FLastError := 0;
FLastErrorMessage := '';
FAuthCode := '';
FRRN := '';
FCardID := '';
FCheque := '';
end;
function TPinPad.CloseDay: integer;
var
Func: TCloseDay;
H: THandle;
begin
ClearBuffers;
FAuthAnswer.TType := OP_CLOSEDAY;
FAuthAnswer.Amount := 0;
FAuthAnswer.CType := 0;
FAuthAnswer.Check := PAnsiChar('');
H := LoadLibrary(Pchar(LibName));
if H <= 0 then
begin
raise TPinpadException.Create(Format('Не могу загрузить %s', [LibName]));
Exit;
end;
try
@Func := GetProcAddress(H, Pchar('_close_day'));
if not Assigned(Func) then
raise TPinpadException.Create
('Функция _close_day не найдена в pilot_nt.dll');
try
Result := Func(@FAuthAnswer);
FLastError := Result;
FLastErrorMessage := PAnsiChar(@AuthAnswer.AMessage);
FCheque := PAnsiChar(AuthAnswer.Check);
except
on E: Exception do
raise TPinpadException.Create(E.message);
end;
finally
Func := nil;
FreeLibrary(H);
end;
end;
function TPinPad.CommitTrx: integer;
var
H: THandle;
Func: TCommitTrx;
begin
H := LoadLibrary(Pchar(LibName));
if H <= 0 then
begin
raise TPinpadException.Create(Format('Не могу загрузить %s', [LibName]));
Exit;
end;
try
@Func := GetProcAddress(H, Pchar('_CommitTrx'));
if not Assigned(Func) then
raise TPinpadException.Create
('Функция _CommitTrx не найдена в pilot_nt.dll');
try
Result := Func(FAuthAnswer.Amount, PAnsiString(AnsiString(FAuthCode)));
FLastError := Result;
FLastErrorMessage := GetMessageText(Result);
except
on E: Exception do
RaiseLastOSError;
end;
finally
Func := nil;
FreeLibrary(H);
end;
end;
{ DONE: Деструктор }
destructor TPinPad.Destroy;
begin
ClearBuffers;
Done;
inherited Destroy;
end;
procedure TPinPad.Done;
var
H: THandle;
Func: TDone;
begin
H := LoadLibrary(Pchar(LibName));
if H <= 0 then
begin
raise TPinpadException.Create(Format('Не могу загрузить %s', [LibName]));
Exit;
end;
try
@Func := GetProcAddress(H, Pchar('_Done'));
Func;
finally
Func := nil;
FreeLibrary(H);
end;
end;
{$REGION 'GetErrorMessage'}
function TPinPad.GetMessageText(ErrorCode: integer): String;
begin
case ErrorCode of
12:
Result := 'Ошибка возникает обычно в ДОС-версиях. Возможных причин две: 1. В настройках указан неверный тип пинпада.'
+ ' Должно быть РС-2, а указано РС-3. 2. Если ошибка возникает неустойчиво, то скорее всего виноват СОМ-порт. Он или нестандартный, или неисправный. Попробовать перенести пинпад на другой порт, а лучше – на USB.';
99:
Result := 'Нарушился контакт с пинпадом, либо невозможно открыть указанный СОМ-порт (он или отсутствует в системе, или захвачен другой программой).';
361, 362, 363, 364:
Result := 'Нарушился контакт с чипом карты. Чип не читается. Попробовать вставить другую карту. Если ошибка возникает на всех картах – неисправен чиповый ридер пинпада.';
403:
Result := 'Клиент ошибся при вводе ПИНа (СБЕРКАРТ)';
405:
Result := 'ПИН клиента заблокирован (СБЕРКАРТ)';
444, 507:
Result := 'Истек срок действия карты (СБЕРКАРТ)';
518:
Result := 'На терминале установлена неверная дата';
521:
Result := 'На карте недостаточно средств (СБЕРКАРТ)';
572:
Result := 'Истек срок действия карты (СБЕРКАРТ)';
574, 579:
Result := 'Карта заблокирована (СБЕРКАРТ)';
584, 585:
Result := 'Истек период обслуживания карты (СБЕРКАРТ)';
705, 706, 707:
Result := 'Карта заблокирована (СБЕРКАРТ)';
708, 709:
Result := 'ПИН клиента заблокирован (СБЕРКАРТ)';
2000:
Result := 'Операция прервана нажатием клавиши ОТМЕНА. Другая возможная причина – не проведена предварительная сверка итогов, и на терминале еще нет сеансовых ключей.';
2002:
Result := 'Клиент слишком долго вводит ПИН. Истек таймаут.';
2004, 2005, 2006, 2007, 2405, 2406, 2407:
Result := 'Карта заблокирована (СБЕРКАРТ)';
3001:
Result := 'Недостаточно средств для загрузки на карту (СБЕРКАРТ)';
3002:
Result := 'По карте клиента числится прерванная загрузка средств (СБЕРКАРТ)';
3019, 3020, 3021:
Result := 'На сервере проводятся регламентные работы (СБЕРКАРТ)';
4100:
Result := 'Нет связи с банком при удаленной загрузке. Возможно, на терминале неверно задан параметр «Код региона и участника для удаленной загрузки».';
4101, 4102:
Result := 'Карта терминала не проинкассирована';
4103, 4104:
Result := 'Ошибка обмена с чипом карты';
4108:
Result := 'Неправильно введен или прочитан номер карты (ошибка контрольного разряда)';
4110, 4111, 4112:
Result := 'Требуется проинкассировать карту терминала (СБЕРКАРТ)';
4113, 4114:
Result := 'Превышен лимит, допустимый без связи с банком (СБЕРКАРТ)';
4115:
Result := 'Ручной ввод для таких карт запрещен';
4116:
Result := 'Введены неверные 4 последних цифры номера карты';
4117:
Result := 'Клиент отказался от ввода ПИНа';
4119:
Result := 'Нет связи с банком. Другая возможная причина – неверный ключ KLK для пинпада Verifone pp1000se или встроенного пинпада Verifone.'
+ ' Если терминал Verifone работает по Ethernet, то иногда избавиться от ошибки можно, понизив скорость порта с 115200 до 57600 бод.';
4120:
Result := 'В пинпаде нет ключа KLK.';
4121:
Result := 'Ошибка файловой структуры терминала. Невозможно записать файл BTCH.D.';
4122:
Result := 'Ошибка смены ключей: либо на хосте нет нужного KLK, либо в настройках терминала указан неверный мерчант.';
4123:
Result := 'На терминале нет сеансовых ключей';
4124:
Result := 'На терминале нет мастер-ключей';
4125:
Result := 'На карте есть чип, а прочитана была магнитная полоса';
4128:
Result := 'Неверный МАС — код при сверке итогов. Вероятно, неверный ключ KLK.';
4130:
Result := 'Память терминала заполнена. Пора делать сверку итогов (лучше несколько раз подряд, чтобы почистить старые отчеты).';
4131:
Result := 'Установлен тип пинпада РС-2, но с момента последней прогрузки параметров пинпад был заменен (изменился его серийный номер). Необходимо повторно прогрузить TLV-файл или выполнить удаленную загрузку.';
4132:
Result := 'Операция отклонена картой. Возможно, карту вытащили из чипового ридера до завершения печати чека. Повторить операцию заново. Если ошибка возникает постоянно, возможно, карта неисправна.';
4134:
Result := 'Слишком долго не выполнялась сверка итогов на терминале (прошло более 5 дней с момента последней операции).';
4135:
Result := 'Нет SAM-карты для выбранного отдела (СБЕРКАРТ)';
4136:
Result := 'Требуется более свежая версия прошивки в пинпаде.';
4137:
Result := 'Ошибка при повторном вводе нового ПИНа.';
4138:
Result := 'Номер карты получателя не может совпадать с номером карты отправителя.';
4139:
Result := 'В настройках терминала нет ни одного варианта связи, пригодного для требуемой операции.';
4140:
Result := 'Неверно указаны сумма или код авторизации в команде SUSPEND из кассовой программы.';
4141:
Result := 'Невозможно выполнить команду SUSPEND: не найден файл SHCN.D.';
4142:
Result := 'Не удалось выполнить команду ROLLBACK из кассовой прграммы.';
4143:
Result := 'На терминале слишком старый стоп-лист.';
4144, 4145, 4146, 4147:
Result := 'Неверный формат стоп-листа на терминале (для торговли в самолете без авторизации).';
4148:
Result := 'Карта в стоп-листе.';
4149:
Result := 'На карте нет фамилии держателя.';
4150:
Result := 'Превышен лимит, допустимый без связи с банком (для торговли на борту самолета без авторизации).';
4151:
Result := 'Истек срок действия карты (для торговли на борту самолета без авторизации).';
4152:
Result := 'На карте нет списка транзакций (ПРО100).';
4153:
Result := 'Список транзакций на карте имеет неизвестный формат (ПРО100).';
4154:
Result := 'Невозможно распечатать список транзакций карты, потому что его можно считать только с чипа, а прочитана магнитная полоса (ПРО100).';
4155:
Result := 'Список транзакций пуст (ПРО100).';
4160:
Result := 'Неверный ответ от карты при считывании биометрических данных';
4161:
Result := 'На терминале нет файла с биометрическим сертификатом BSCP.CR';
4162, 4163, 4164:
Result := 'Ошибка расшифровки биометрического сертификата карты. Возможно, неверный файл BSCP.CR';
4165, 4166, 4167:
Result := 'Ошибка взаимной аутентификации биосканера и карты. Возможно, неверный файл BSCP.CR';
4168, 4169:
Result := 'Ошибка расшифровки шаблонов пальцев, считанных с карты.';
4171:
Result := 'В ответе хоста на запрос enrollment’a нет биометрической криптограммы.';
4202:
Result := 'Сбой при удаленной загрузке: неверное смещение в данных.';
4203:
Result := 'Не указанный или неверный код активации при удаленной загрузке.';
4208:
Result := 'Ошибка удаленной загрузки: на сервере не активирован какой-либо шаблон для данного терминала.';
4209:
Result := 'Ошибка удаленной загрузки: на сервере проблемы с доступом к БД.';
4211:
Result := 'На терминале нет EMV-ключа с номером 62 (он нужен для удаленной загрузки).';
4300:
Result := 'Недостаточно параметров при запуске модуля sb_pilot. В командной строке указаны не все требуемые параметры.';
4301:
Result := 'Кассовая программа передала в UPOS недопустимый тип операции';
4302:
Result := 'Кассовая программа передала в UPOS недопустимый тип карты';
4303:
Result := 'Тип карты, переданный из кассовой программы, не значится в настройках UPOS. Возможно, на диске кассы имеется несколько '
+ ' каталогов с библиотекой UPOS. Банковский инженер настраивал один экземпляр, а кассовая программа обращается к другому, где никаких настроек (а значит, и типов карт) нет.';
4305:
Result := 'Ошибка инициализации библиотеки sb_kernel.dll. Кассовая программа ожидает библиотеку с более свежей версией.';
4306:
Result := '"Библиотека sb_kernel.dll не была инициализирована. Эта ошибка может разово возникать после обновления библиотеки через удаленную загрузку. Нужно просто повторить операцию."';
4308:
Result := 'В старых версиях этим кодом обозначалась любая из проблем, которые сейчас обозначаются кодами 4331-4342';
4309:
Result := 'Печатать нечего. Эта ошибка возникает в интегрированных решениях, которые выполнены не вполне корректно:'
+ ' в случае любой ошибки (нет связи, ПИН неверен, неверный ключ KLK и т.д.) кассовая программа все равно запрашивает у библиотеки '
+ ' sb_kernel.dll образ чека для печати. Поскольку по умолчанию библиотека при отказах чек не формирует, то на запрос чека она возвращает кассовой программе'
+ ' код 4309 – печатать нечего, нет документа для печати. Исходный код ошибки (тот, который обозначает причину отказа) кассовая программа при этом забывает.';
4310:
Result := 'Кассовая программа передала в UPOS недопустимый трек2.';
4313:
Result := 'В кассовой программе значится один номер карты, а через UPOS считан другой.';
4314:
Result := 'Кассовая программа передала код операции «Оплата по международной карте», а вставлена была карта СБЕРКАРТ.';
4332:
Result := 'Сверка итогов не выполнена (причина неизвестна, но печатать в итоге нечего).';
4333:
Result := 'Распечатать контрольную ленту невозможно (причина неизвестна, но печатать в итоге нечего).';
4334:
Result := 'Карта не считана. Либо цикл ожидания карты прерван нажатием клавиши ESC, либо просто истек таймаут.';
4335:
Result := 'Сумма не введена при операции ввода слипа.';
4336:
Result := 'Из кассовой программы передан неверный код валюты.';
4337:
Result := 'Из кассовой программы передан неверный тип карты.';
4338:
Result := 'Вызвана операция по карте СБЕРКАРТ, но прочитать карту СБЕРКАРТ не удалось.';
4339:
Result := 'Вызвана недопустимая операция по карте СБЕРКАРТ.';
4340:
Result := 'Ошибка повторного считывания карты СБЕРКАРТ.';
4341:
Result := 'Вызвана операция по карте СБЕРКАРТ, но вставлена карта другого типа, либо не вставлена никакая.';
4342:
Result := 'Ошибка: невозможно запустить диалоговое окно UPOS (тред почему-то не создается).';
4400 - 4499:
Result := Format('От фронтальной системы получен код ответа %d.',
[ErrorCode - 4400]);
5002:
Result := 'Карта криво выпущена и поэтому дает сбой на терминалах, поддерживающих режим Offline Enciphered PIN.';
5026:
Result := 'Ошибка проверки RSA-подписи. На терминале отсутствует (или некорректный) один из ключей из раздела «Ключи EMV».';
5063:
Result := 'На карте ПРО100 нет списка транзакций.';
5100 - 5108:
Result := 'Нарушены данные на чипе карты';
5109:
Result := 'Срок действия карты истек';
5110:
Result := 'Срок действия карты еще не начался';
5111:
Result := 'Для этой карты такая операция не разрешена';
5116, 5120:
Result := 'Клиент отказался от ввода ПИНа';
5133:
Result := 'Операция отклонена картой';
end;
end;
function TPinPad.GetLastErrorMessage: string;
begin
if FLastErrorMessage <> '' then
Result := FLastErrorMessage
else
Result := GetMessageText(FLastError);
end;
{$ENDREGION}
function TPinPad.GetTerminalID: string;
var
H: THandle;
Func: TGetTerminalID;
S: Pchar;
begin
GetMem(S, 255);
H := LoadLibrary(Pchar(LibName));
if H <= 0 then
begin
raise TPinpadException.Create(Format('Не могу загрузить %s', [LibName]));
Exit;
end;
try
@Func := GetProcAddress(H, Pchar('_GetTerminalID'));
if not Assigned(Func) then
raise TPinpadException.Create
('Функция GetTerminalID не найдена в pilot_nt.dll');
try
FLastError := Func(S);
FLastErrorMessage := GetMessageText(FLastError);
if FLastError = 0 then
Result := PAnsiChar(S)
else
Result := '';
except
on E: Exception do
RaiseLastOSError;
end;
finally
FreeMem(S, SizeOf(S^));
Func := nil;
FreeLibrary(H);
end;
end;
function TPinPad.Initialize(ATextHandle, AEditHandle: HWND): boolean;
begin
Result := False;
try
FGUITextHandle := ATextHandle;
FGUIEditHandle := AEditHandle;
FTerminalID := '';
ClearBuffers;
if TestPinpad then
try
FTerminalID := GetTerminalID; // Сразу получаем номер терминала
if (FGUITextHandle <> 0) and (FGUIEditHandle <> 0) then
FLastError := SetGUIHandles(ATextHandle, AEditHandle);
except
on E: Exception do; // Ничего не делаем
end;
finally
Result := FLastError = 0;
end;
end;
function TPinPad.TryPurchase(Amount: Double): boolean;
begin
Result := (CardAuth7(Amount, OP_PURCHASE) = 0) and (SuspendTrx = 0);
end;
function TPinPad.ReadTrack2: string;
var
H: THandle;
Func: TReadTrack2;
Res: Pchar;
begin
GetMem(Res, 255);
H := LoadLibrary(Pchar(LibName));
if H <= 0 then
begin
raise TPinpadException.Create(Format('Не могу загрузить %s', [LibName]));
Exit;
end;
try
@Func := GetProcAddress(H, Pchar('_ReadTrack2'));
try
Func(Res);
Result := PAnsiChar(Res);
except
on E: Exception do;
end;
finally
FreeMem(Res, SizeOf(Res^));
Func := nil;
FreeLibrary(H);
end;
end;
function TPinPad.ReadTrack3: string;
var
H: THandle;
Func: TReadCardTrack3;
Res: Pchar;
Last4: Pchar;
Hash: Pchar;
begin
GetMem(Res, 255);
GetMem(Last4, 4);
GetMem(Hash, 255);
H := LoadLibrary(Pchar(LibName));
if H <= 0 then
begin
raise TPinpadException.Create(Format('Не могу загрузить %s', [LibName]));
Exit;
end;
try
@Func := GetProcAddress(H, Pchar('_ReadCardTrack3'));
if not Assigned(Func) then
raise TPinpadException.Create
('Функция _ReadCardTrack3 не найдена в pilot_nt.dll');
try
FLastError := Func(Last4, Hash, Res);
Result := PAnsiChar(Res);
FCardID := PAnsiChar(Last4);
except
on E: Exception do
RaiseLastOSError;
end;
finally
FreeMem(Res, SizeOf(Res^));
FreeMem(Last4, SizeOf(Last4^));
FreeMem(Hash, SizeOf(Hash^));
Func := nil;
FreeLibrary(H);
end;
end;
function TPinPad.TryReturn(Amount: Double): boolean;
begin
Result := (CardAuth7(Amount, OP_RETURN) = 0) and (SuspendTrx = 0);
end;
function TPinPad.RollBackTrx: integer;
var
H: THandle;
Func: TRollBackTrx;
begin
H := LoadLibrary(Pchar(LibName));
if H <= 0 then
begin
raise TPinpadException.Create(Format('Не могу загрузить %s', [LibName]));
Exit;
end;
try
@Func := GetProcAddress(H, Pchar('_RollbackTrx'));
if not Assigned(Func) then
raise TPinpadException.Create
('Функция _RollbackTrx не найдена в pilot_nt.dll');
try
Result := Func(FAuthAnswer.Amount, PAnsiString(AnsiString(FAuthCode)));
FLastError := Result;
FLastErrorMessage := GetMessageText(Result);
except
on E: Exception do
RaiseLastOSError;
end;
finally
Func := nil;
FreeLibrary(H);
end;
end;
// False - Контрольная лента, True - Сводный чек
function TPinPad.SberShift(IsDetailed: boolean = False): integer;
var
H: THandle;
Func: TGetStatistics;
begin
H := LoadLibrary(Pchar(LibName));
if H <= 0 then
begin
raise TPinpadException.Create(Format('Не могу загрузить %s', [LibName]));
Exit;
end;
ClearBuffers;
case IsDetailed of
True:
FAuthAnswer.TType := 1;
False:
FAuthAnswer.TType := 0;
end;
try
@Func := GetProcAddress(H, Pchar('_get_statistics'));
if not Assigned(Func) then
raise TPinpadException.Create
('Функция _get_statistics не найдена в pilot_nt.dll');
try
Result := Func(@FAuthAnswer);
FLastErrorMessage := PAnsiChar(@FAuthAnswer.AMessage);
FCheque := PAnsiChar(FAuthAnswer.Check);
FLastError := Result;
except
on E: Exception do
RaiseLastOSError;
end;
finally
Func := nil;
FreeLibrary(H);
end;
end;
function TPinPad.ServiceMenu: integer;
var
H: THandle;
Func: TServiceMenu;
begin
ClearBuffers;
H := LoadLibrary(Pchar(LibName));
if H <= 0 then
begin
raise TPinpadException.Create(Format('Не могу загрузить %s', [LibName]));
Exit;
end;
try
@Func := GetProcAddress(H, Pchar('_ServiceMenu'));
if not Assigned(Func) then
raise TPinpadException.Create
('Функция _ServiceMenu не найдена в pilot_nt.dll');
try
Result := Func(@FAuthAnswer);
FCheque := PAnsiChar(FAuthAnswer.Check);
FLastError := Result;
except
on E: Exception do
RaiseLastOSError;
end;
finally
Func := nil;
FreeLibrary(H);
end;
end;
function TPinPad.SetGUIHandles(ATextHandle, AEditHandle: HWND): integer;
var
H: THandle;
Func: TSetGUIHandles;
begin
H := LoadLibrary(Pchar(LibName));
if H <= 0 then
begin
raise TPinpadException.Create(Format('Не могу загрузить %s', [LibName]));
Exit;
end;
try
@Func := GetProcAddress(H, Pchar('_SetGUIHandles'));
if NOT Assigned(Func) then
raise TPinpadException.Create
('Функция _SetGUIHandles не найдена в pilot_nt.dll');
try
Result := Func(ATextHandle, AEditHandle);
except
on E: Exception do
RaiseLastOSError;
end;
finally
Func := nil;
FreeLibrary(H);
end;
end;
function TPinPad.SuspendTrx: integer;
var
H: THandle;
Func: TSuspendTrx;
begin
H := LoadLibrary(Pchar(LibName));
if H <= 0 then
begin
raise TPinpadException.Create(Format('Не могу загрузить %s', [LibName]));
Exit;
end;
try
@Func := GetProcAddress(H, Pchar('_SuspendTrx'));
if not Assigned(Func) then
raise TPinpadException.Create
('Функция _SuspendTrx не найдена в pilot_nt.dll');
try
Result := Func(FAuthAnswer.Amount, PAnsiString(AnsiString(FAuthCode)));
FLastError := Result;
FLastErrorMessage := GetMessageText(Result);
except
on E: Exception do;
end;
finally
Func := nil;
FreeLibrary(H);
end;
end;
function TPinPad.TestPinpad: boolean;
var
H: THandle;
Func: TTestPinPad;
begin
Result := False;
try
H := LoadLibrary(Pchar(LibName));
if H <= 0 then
begin
raise TPinpadException.Create(Format('Не могу загрузить %s', [LibName]));
Exit;
end;
@Func := GetProcAddress(H, Pchar('_TestPinpad'));
try
FLastError := Func;
Result := FLastError = 0;
except
on E: Exception do
RaiseLastOSError;
end;
finally
Func := nil;
FreeLibrary(H);
end;
end;
end.
|
unit AppController;
interface
uses
Sysutils, Classes, Math,
System.Generics.Collections, SyncObjs, FMX.Types,
AppData, Interfaces.Controller.GUI;
type
TAddPipe = procedure(AYOffset: Double; Bottom: Boolean) of object ;
TCalculator = class(TThread)
private
FRatio: Integer;
FGameTicker: Integer;
FPipeAPos: Integer;
FPipeBPos: Integer;
FAddPipe: TAddPipe;
protected
procedure Execute; override;
public
constructor Create(ARatio: Integer);
property AddPipe: TAddPipe read FAddPipe write FAddPipe;
end;
TAppController = class(TInterfacedObject, Interfaces.Controller.GUI.IAppController)
private
FGUI: IAppGUI;
FData: TAppData;
FPipes: TPipes;
FBird: TBird;
FTimer: TTimer; // quick and dirty
FUpdater: TCalculator;
procedure RegisterGUI(const AGUI: IAppGUI);
procedure StartGame;
procedure StopGame;
procedure Replay;
procedure ResetGame;
procedure GameOver;
procedure Tapped;
procedure RemovePipes;
procedure IncScore;
procedure SetBird(AX,AY,AAngle: Double; Flap: Boolean); overload;
procedure SetBird(AYOffset,AAngle: Double; Flap: Boolean); overload;
procedure AddPipe(AYOffset: Double; Bottom: Boolean);
function HitGround: Boolean;
function HitPipe: Boolean;
function OvercomePipe: Boolean;
function CheckBoundryCollision(APipe: TPipe; OffSetY : LongInt = 2; OffSetX : LongInt = 2): Boolean;
procedure MainLoop(ASender: TObject);
public
end;
const
// some of these constants should be initialized when RegisterGUI is called
DEF_BIRD_X = 96;
DEF_BIRD_Y = 248;
DEF_BIRD_ANGLE = 0;
GROUND_POS_Y = 453;
PIPE_WIDTH = 76;
PIPE_HEIGHT = 409;
BIRD_WIDTH = 35;
BIRD_HEIGHT = 35;
SPAWN_TIME = 1.5;
var
Mutex: TCriticalSection;
BirdYPos: Double;
BirdAngle: Double;
BirdUp: Boolean;
Flap: Boolean;
GamePanelWidth: Integer;
GamePanelHeight: Integer;
implementation
{ TAppController }
procedure TAppController.RegisterGUI(const AGUI: IAppGUI);
begin
FGUI:= AGUI;
FGUI.RegisterController(Self);
FData:= TAppData.Create;
Mutex:= TCriticalSection.Create;
FPipes:= TObjectList<TPipe>.Create;
FPipes.OwnsObjects:= true;
FBird:= TBird.Create;
GamePanelWidth:= FGUI.GetGamePanelWidth;
GamePanelHeight:= FGUI.GetGamePanelHeight;
Randomize;
FTimer:= TTimer.Create(nil);
FTimer.Interval:=33;
FTimer.Enabled:= false;
FTimer.OnTimer:= MainLoop;
end;
procedure TAppController.StartGame;
begin
ResetGame;
FUpdater:= TCalculator.Create(FGUI.GetHRatio);
FUpdater.AddPipe:= AddPipe;
FTimer.Enabled:= true;
FUpdater.Start;
end;
procedure TAppController.StopGame;
begin
FUpdater.Terminate;
FUpdater.WaitFor;
FUpdater.DisposeOf;
FTimer.Enabled:= false;
end;
procedure TAppController.Replay;
begin
ResetGame;
end;
procedure TAppController.ResetGame;
begin
RemovePipes;
BirdYPos:= DEF_BIRD_Y;
BirdAngle:= DEF_BIRD_ANGLE;
BirdUp:= false;
Flap:= false;
SetBird(DEF_BIRD_X,DEF_BIRD_Y,DEF_BIRD_ANGLE,false);
FData.ResetScore;
FGUI.SetScore(FData.GetScore);
FGUI.ResetGame;
end;
procedure TAppController.GameOver;
begin
StopGame;
FGUI.GameOver(FData.GetScore, FData.GetHighscore);
end;
procedure TAppController.Tapped;
begin
Mutex.Enter;
BirdUp:= true;
Mutex.Leave;
end;
procedure TAppController.RemovePipes;
var n: Integer;
begin
for n:= 0 to FPipes.Count-1 do
FGUI.RemovePipe(TPipe(FPipes.Items[n]));
FPipes.Clear;
end;
procedure TAppController.IncScore;
begin
FData.IncScore;
FGUI.SetScore(FData.GetScore);
end;
procedure TAppController.SetBird(AX,AY,AAngle: Double; Flap: Boolean);
begin
FBird.X:= AX;
FBird.Y:= AY;
FBird.Width:= BIRD_WIDTH;
FBird.Heigth:= BIRD_HEIGHT;
FBird.Angle:= AAngle;
FBird.Flap:= Flap;
FGUI.SetBird(FBird);
end;
procedure TAppController.SetBird(AYOffset,AAngle: Double; Flap: Boolean);
begin
FBird.X:= DEF_BIRD_X;
FBird.Y:= FBird.Y+AYOffset;
FBird.Width:= BIRD_WIDTH;
FBird.Heigth:= BIRD_HEIGHT;
FBird.Angle:= AAngle;
FBird.Flap:= Flap;
FGUI.SetBird(FBird);
end;
procedure TAppController.AddPipe(AYOffset: Double; Bottom: Boolean);
begin
FPipes.Add(TPipe.Create);
{$IFDEF IOS}
TPipe(FPipes.Last).X:= FGUI.GetGamePanelWidth+PIPE_WIDTH;
{$ELSE}
TPipe(FPipes.Last).X:= GamePanelWidth+PIPE_WIDTH;
{$ENDIF}
if Bottom then
begin
{$IFDEF IOS}
TPipe(FPipes.Last).Y:= (FGUI.GetGamePanelWidth-PIPE_HEIGHT)+AYOffset;
{$ELSE}
TPipe(FPipes.Last).Y:= (GamePanelWidth-PIPE_HEIGHT)+AYOffset;
{$ENDIF}
TPipe(FPipes.Last).Angle:= 180;
end
else
begin
TPipe(FPipes.Last).Y:= AYOffset;
TPipe(FPipes.Last).Angle:= 0;
end;
TPipe(FPipes.Last).Width:= PIPE_WIDTH;
TPipe(FPipes.Last).Heigth:= PIPE_HEIGHT;
TPipe(FPipes.Last).Tag:= Integer(Bottom)+1;
TPipe(FPipes.Last).TagFloat:= 0;
TPipe(FPipes.Last).Added:= false;
TPipe(FPipes.Last).Layout:= nil;
end;
procedure TAppController.MainLoop(ASender: TObject);
var n: Integer;
aPipe: TPipe;
GameOverCheck: Boolean;
begin
GameOverCheck:= false;
if HitGround then
GameOverCheck:= true;
Mutex.Enter;
// this should be also threaded
for n:= FPipes.Count-1 downto 0 do
begin
aPipe:= TPipe(FPipes.Items[n]);
aPipe.X:= aPipe.X-5;
if not aPipe.Added then
begin
FGUI.AddPipe(aPipe);
aPipe.Added:= true;
end;
FGUI.MovePipe(aPipe);
// is pipe outside the visible area? - then delete it
if (aPipe.X<((aPipe.Width*-1)-10)) then
begin
FGUI.RemovePipe(aPipe);
FPipes.Delete(n);
end;
end;
if HitPipe then
GameOverCheck:= true
else
if OvercomePipe then
IncScore;
SetBird(BirdYPos,BirdAngle,Flap);
Mutex.Leave;
if GameOverCheck then
GameOver;
end;
function TAppController.HitGround: Boolean;
begin
Result:= ((FBird.Y+BIRD_HEIGHT)>GROUND_POS_Y);
end;
function TAppController.HitPipe: Boolean;
var n: Integer;
begin
Result:= false;
for n:= 0 to FPipes.Count-1 do
begin
if CheckBoundryCollision(TPipe(FPipes.Items[n])) then
begin
Result:= true;
break;
end;
end;
end;
function TAppController.OvercomePipe: Boolean;
var n: Integer;
aPipe: TPipe;
begin
Result:= false;
for n:= 0 to FPipes.Count-1 do
begin
aPipe:= TPipe(FPipes.Items[n]);
if (((aPipe.X+(aPipe.Width/2))<FBird.X) AND (aPipe.Tag=1) AND (aPipe.TagFloat=0)) then
begin
aPipe.TagFloat:= 1;
Result:= true;
end;
end;
end;
function TAppController.CheckBoundryCollision(APipe: TPipe; OffSetY : LongInt = 2; OffSetX : LongInt = 2): Boolean;
begin
Result:=(not((FBird.GetRect.Bottom - (OffSetY * 2) < APipe.GetRect.Top + OffSetY)
or(FBird.GetRect.Top + OffSetY > APipe.GetRect.Bottom - (OffSetY * 2))
or(FBird.GetRect.Right - (OffSetX * 2) < APipe.GetRect.Left + OffSetX)
or(FBird.GetRect.Left + OffSetX > APipe.GetRect.Right - (OffSetX * 2))));
end;
{ TUpdater }
constructor TCalculator.Create(ARatio: Integer);
begin
inherited Create(true);
FRatio:= ARatio;
BirdAngle:= DEF_BIRD_ANGLE;
BirdYPos:= DEF_BIRD_Y;
FGameTicker:= 0;
end;
procedure TCalculator.Execute;
const BIRD_UP_HEIGHT = 42;
BIRD_UP_SPEED = 5;
BIRD_DOWN_SPEED = 5;
var POffset, WOffset: Integer;
BirdUpCount: Integer;
IsBirdUp: Boolean;
begin
inherited;
BirdUpCount:= 0;
while not Terminated do
begin
// if user tapped several times in succession
if BirdUp then
begin
BirdUpCount:= 0;
IsBirdUp:= true;
BirdUp:= false;
end;
if FGameTicker = 0 then
begin
{$IFDEF MSWINDOWS}
if (Random<0.5) then
WOffset:= (300*FRatio)
else
WOffset:= (350*FRatio);
{$ENDIF}
{$IFDEF IOS}
if (Random<0.5) then
WOffset:= (200*FRatio)
else
WOffset:= (250*FRatio);
{$ENDIF}
if (Random<0.5) then
POffset:= (-125*FRatio)
else
POffset:= (-25*FRatio);
FPipeAPos:= (-WOffset)+POffset;
FPipeBPos:= WOffset+POffset;
FAddPipe(FPipeAPos,false);
FAddPipe(FPipeBPos,true);
end;
if FGameTicker>(SPAWN_TIME*30) then
FGameTicker:= 0
else
Inc(FGameTicker);
// for a smooth rising
if IsBirdUp and (BirdUpCount <= BIRD_UP_SPEED)then
begin
if BirdAngle > -15 then
BirdAngle:= BirdAngle-(90/(BIRD_UP_SPEED));
BirdYPos:= -Round(BIRD_UP_HEIGHT/BIRD_UP_SPEED);
Inc(BirdUpCount);
end
else
begin
IsBirdUp:= false;
BirdUpCount:= 0;
if BirdAngle<90 then
BirdAngle:= BirdAngle+5;
BirdYPos:= Max(BirdAngle,1)/BIRD_DOWN_SPEED;
end;
if FGameTicker mod 4 = 0 then
Flap:= true
else
Flap:= false;
Sleep(35);
end;
end;
end.
|
unit Contador;
{$mode objfpc}{$H+}
interface
uses
BrookRESTActions, BrookUtils;
type
TContadorOptions = class(TBrookOptionsAction)
end;
TContadorRetrieve = class(TBrookRetrieveAction)
end;
TContadorShow = class(TBrookShowAction)
end;
TContadorCreate = class(TBrookCreateAction)
end;
TContadorUpdate = class(TBrookUpdateAction)
end;
TContadorDestroy = class(TBrookDestroyAction)
end;
implementation
initialization
TContadorOptions.Register('contador', '/contador');
TContadorRetrieve.Register('contador', '/contador');
TContadorShow.Register('contador', '/contador/:id');
TContadorCreate.Register('contador', '/contador');
TContadorUpdate.Register('contador', '/contador/:id');
TContadorDestroy.Register('contador', '/contador/:id');
end.
|
// RemObjects CS to Pascal 0.1
namespace UT3Bots;
interface
uses
System,
System.Collections.Generic,
System.Linq,
System.Text,
UT3Bots.UTItems,
UT3Bots.Communications;
type
BotCommands = public class
private
var _utBot: UTBot;
var _utConnection: UT3Connection;
public
/// <summary>
/// Command your bot to shoot in the direction it is facing
/// </summary>
/// <param name="useSecondaryFire">True if you want to use the Alternative Fire of your current gun instead of its primary fire</param>
method StartFiring(useSecondaryFire: Boolean);
/// <summary>
/// Command your bot to shoot at a specific location
/// </summary>
/// <param name="Location">The location to fire at</param>
/// <param name="useSecondaryFire">True if you want to use the Alternative Fire of your current gun instead of its primary fire</param>
method StartFiring(Location: UTVector; useSecondaryFire: Boolean);
/// <summary>
/// Command your bot to shoot at a specific target
/// </summary>
/// <param name="Target">The target to fire at</param>
/// <param name="useSecondaryFire">True if you want to use the Alternative Fire of your current gun instead of its primary fire</param>
method StartFiring(Target: UTIdentifier; useSecondaryFire: Boolean);
/// <summary>
/// Command your bot to stop shooting
/// </summary>
method StopFiring();
/// <summary>
/// Command your bot to stop moving
/// </summary>
method StopMoving();
/// <summary>
/// Command your bot to jump
/// </summary>
method Jump();
/// <summary>
/// Command your bot to automatically turn towards and move directly to the destination
/// </summary>
/// <param name="Location">The location you want to go to (The location must be visible to you when the command is recieved or your bot will do nothing.)</param>
method RunTo(Location: UTVector);
/// <summary>
/// Command your bot to automatically turn towards and move directly to the destination
/// </summary>
/// <param name="Target">The target you want to go to (The object must be visible to you when the command is recieved or your bot will do nothing.)</param>
method RunTo(Target: UTIdentifier);
/// <summary>
/// Command your bot to move towards a destination while facing another object
/// </summary>
/// <param name="Location">The location that you want to move to</param>
/// <param name="Target">The object you want to face while moving (The object must be visible to you when the command is recieved or your bot will do nothing.)</param>
method StrafeTo(Location: UTVector; Target: UTIdentifier);
/// <summary>
/// Command your bot to move towards a destination while facing another location
/// </summary>
/// <param name="Location">The location that you want to move to</param>
/// <param name="Target">The target you want to face while moving (The target must be visible to you when the command is recieved or your bot will do nothing.)</param>
method StrafeTo(Location: UTVector; Target: UTVector);
/// <summary>
/// Command your bot to turn to face a specified location
/// </summary>
/// <param name="Location">The location you want to turn to</param>
method RotateTo(Location: UTVector);
/// <summary>
/// Command your bot to turn to face a specified object
/// </summary>
/// <param name="Target">The object you want to turn to</param>
method RotateTo(Target: UTIdentifier);
/// <summary>
/// Command your bot to turn to face a specified angle
/// </summary>
/// <param name="Target">The angle you want to turn to in degrees</param>
method RotateTo(Degrees: Integer);
//(2pi = 65535 UT units)
/// <summary>
/// Command your bot to turn a specified amount
/// </summary>
/// <param name="Degrees">The number of degrees your want to turn from where you are facing at the moment</param>
method RotateBy(Degrees: Integer);
//(2pi = 65535 UT units)
/// <summary>
/// Send a chat message to the server
/// </summary>
/// <param name="Message">The message you want to send</param>
/// <param name="SendToTeam">True if you want to only send this to your team</param>
method SendChatMessage(Message: String; SendToTeam: Boolean);
/// <summary>
/// Taunt a player with the built in voice taunts
/// </summary>
/// <param name="Target">The ID of the player you want to taunt (this must be a valid player, or nothing will happen)</param>
method SendTauntMessage(Target: UTIdentifier);
/// <summary>
/// Just killed someone? Why not taunt them with some fetching pelvic thrusts!
/// </summary>
/// <param name="Emote">The emote you want to send</param>
method PerformEmote(Emote: Emote);
/// <summary>
/// Set whether you are walking or running (default is run).
/// Walking means you move at about 1/3 normal speed, make less noise, and won't fall off ledges
/// </summary>
/// <param name="UseWalk">Send True to go into walk mode or False to go into run mode</param>
method SetMovingSpeed(UseWalk: Boolean);
/// <summary>
/// Command your bot to change to its most powerful weapon
/// </summary>
method ChangeWeapon();
/// <summary>
/// Command your bot to change to a specific weapon
/// The weapon will be changed if you have this weapon in your inventory and it has ammo left
/// </summary>
/// <param name="Weapon">The Weapon ID you want to switch to</param>
method ChangeWeapon(Weapon: UTIdentifier);
/// <summary>
/// Get a path to a specified target.
/// An ordered list of nay points will be returned to you via the OnPathReceived() event that you should attach to
/// </summary>
/// <param name="Id">A message ID made up by you and echoed in respose so you can match up response with query</param>
/// <param name="Target">The target you would like to go to</param>
method GetPath(Id: String; Target: UTIdentifier);
/// <summary>
/// Get a path to a specified location.
/// An ordered list of nay points will be returned to you via the OnPathReceived() event that you should attach to
/// </summary>
/// <param name="Id">A message ID made up by you and echoed in respose so you can match up response with query</param>
/// <param name="Location">The location you would like to go to</param>
method GetPath(Id: String; Location: UTVector);
constructor (Bot: UTBot; Connection: UT3Connection);
end;
implementation
method BotCommands.StartFiring(useSecondaryFire: Boolean);
begin
Self._utConnection.SendLine(Message.BuildMessage(CommandMessage.FIRE, 'None', useSecondaryFire.ToString()))
end;
method BotCommands.StartFiring(Location: UTVector; useSecondaryFire: Boolean);
begin
Self._utConnection.SendLine(Message.BuildMessage(CommandMessage.FIRE, Location.ToString(), useSecondaryFire.ToString()))
end;
method BotCommands.StartFiring(Target: UTIdentifier; useSecondaryFire: Boolean);
begin
Self._utConnection.SendLine(Message.BuildMessage(CommandMessage.FIRE, Target.ToString(), useSecondaryFire.ToString()))
end;
method BotCommands.StopFiring();
begin
Self._utConnection.SendLine(Message.BuildMessage(CommandMessage.STOP_FIRE))
end;
method BotCommands.StopMoving();
begin
Self._utConnection.SendLine(Message.BuildMessage(CommandMessage.STOP))
end;
method BotCommands.Jump();
begin
Self._utConnection.SendLine(Message.BuildMessage(CommandMessage.JUMP))
end;
method BotCommands.RunTo(Location: UTVector);
begin
Self._utConnection.SendLine(Message.BuildMessage(CommandMessage.RUN_TO, '0.0', '0.0', Location.ToString()))
end;
method BotCommands.RunTo(Target: UTIdentifier);
begin
Self._utConnection.SendLine(Message.BuildMessage(CommandMessage.RUN_TO, '0.0', '0.0', Target.ToString()))
end;
method BotCommands.StrafeTo(Location: UTVector; Target: UTIdentifier);
begin
Self._utConnection.SendLine(Message.BuildMessage(CommandMessage.STRAFE_TO, Location.ToString(), Target.ToString()))
end;
method BotCommands.StrafeTo(Location: UTVector; Target: UTVector);
begin
Self._utConnection.SendLine(Message.BuildMessage(CommandMessage.STRAFE_TO, Location.ToString(), Target.ToString()))
end;
method BotCommands.RotateTo(Location: UTVector);
begin
Self._utConnection.SendLine(Message.BuildMessage(CommandMessage.ROTATE_TO, Location.ToString(), 'Location'))
end;
method BotCommands.RotateTo(Target: UTIdentifier);
begin
Self._utConnection.SendLine(Message.BuildMessage(CommandMessage.ROTATE_TO, Target.ToString(), 'Target'))
end;
method BotCommands.RotateTo(Degrees: Integer);
begin
Degrees := Degrees mod 360;
var units: Integer := Integer(((Degrees / 360) * 65535));
Self._utConnection.SendLine(Message.BuildMessage(CommandMessage.ROTATE_TO, units.ToString(), 'Rotation'))
end;
method BotCommands.RotateBy(Degrees: Integer);
begin
Degrees := Degrees mod 360;
var units: Integer := Integer(((Degrees / 360) * 65535));
Self._utConnection.SendLine(Message.BuildMessage(CommandMessage.ROTATE_BY, units.ToString(), 'Horizontal'))
end;
method BotCommands.SendChatMessage(Message: String; SendToTeam: Boolean);
begin
Message := Message.Replace(#13, ' ');
Message := Message.Replace(#10, ' ');
Message := Message.Replace('|', ' ');
Self._utConnection.SendLine(Communications.Message.BuildMessage(CommandMessage.SENDCHAT, Message, iif(SendToTeam, 'Team', 'Global')))
end;
method BotCommands.SendTauntMessage(Target: UTIdentifier);
begin
if Target <> nil then
begin
Self._utConnection.SendLine(Communications.Message.BuildMessage(CommandMessage.SENDTAUNT, Target.ToString()))
end;
end;
method BotCommands.PerformEmote(Emote: Emote);
begin
Self._utConnection.SendLine(Communications.Message.BuildMessage(CommandMessage.SENDEMOTE, Emote.GetStringValue()))
end;
method BotCommands.SetMovingSpeed(UseWalk: Boolean);
begin
Self._utConnection.SendLine(Message.BuildMessage(CommandMessage.SETWALK, UseWalk.ToString()))
end;
method BotCommands.ChangeWeapon();
begin
Self._utConnection.SendLine(Communications.Message.BuildMessage(CommandMessage.CHANGE_WEAPON, 'BEST'))
end;
method BotCommands.ChangeWeapon(Weapon: UTIdentifier);
begin
Self._utConnection.SendLine(Communications.Message.BuildMessage(CommandMessage.CHANGE_WEAPON, Weapon.ToString()))
end;
method BotCommands.GetPath(Id: String; Target: UTIdentifier);
begin
if Target <> nil then
begin
Self._utConnection.SendLine(Communications.Message.BuildMessage(CommandMessage.GET_PATH, Id, Target.ToString()))
end;
end;
method BotCommands.GetPath(Id: String; Location: UTVector);
begin
Self._utConnection.SendLine(Communications.Message.BuildMessage(CommandMessage.GET_PATH, Id, Location.ToString()))
end;
constructor BotCommands(Bot: UTBot; Connection: UT3Connection);
begin
Self._utBot := Bot;
Self._utConnection := Connection
end;
end.
|
Program EDARABOL;
{Ertekelo Pr. a DARABOL feladathoz }
{ ParancsSor: Tesztkonyvtar tesztesetekszama }
{ Output: DARABOL.ERT fajlban 0/1 tesztesetenkent egy sorban }
Const
FNev='DARABOL'; { Feladatnev }
MaxTesz=15; { a tesztesetek max. szama }
TeC:Array[1..15] of Char=('1','2','3','4','5','6','7','8','9','a','b','c','d','e','f');
Var
TeK:String; { tesztkonyvtar=ParamStr(1) }
Tesz:Word; { a tesztesetek szama=ParamStr(2) }
TLim:Longint; { az idolomit=ParamStr(3) }
IdoF, { futasi ido }
Bef, { input file}
Kif, { a korrekt output }
VKif:Text; { a versenyzo outputja }
Tf :File Of Longint; { idostempli }
M1,T1:Longint; { futasi ido }
FFNev:String; { kimeneti állománynév }
Pont:Array[1..MaxTesz,1..2] Of Byte; { a pont(0/1) per teszteset }
t,i,j:Integer;
Procedure KiIr;
Var i,j:Word;
Ef:Text;
Begin
Assign(Ef,FNev+'.ERT'); Rewrite(Ef);
For j:=1 To 2 Do Begin
For i:=1 To Tesz Do
Write(Ef,Pont[i,j]:3);
WriteLn(Ef);
End;
Close(Ef);
End (*KiIr*);
Procedure Ellen(t:Byte);
Const
MaxN=1000; {a vagasok max. szama}
Var
N,EH,VT,V1,V2:Longint;
D,Dv:Array[1..MaxN] Of Longint;
Db:Word;
En, { a korrekt eredmeny }
Vn:Longint; { a versenyzo eredmenye }
OK:Boolean;
Procedure Beolvas;
Var
BeF:Text;
i:Integer;
Begin{Beolvas}
Assign(Bef,Tek+FNev+TeC[t]+'.BE'); Reset(Bef);
EH:=0;
ReadLn(BeF,N);
For i:=1 To N Do Begin
Read(BeF,D[i]);
EH:=EH+D[i];
End;
Close(BeF);
End{Beolvas};
Begin{Ellen}
{ korrekt output beolvasasa }
Readln(Kif,En);
{$I-}
Read(VKif,Vn);
{$I+}
If (IOResult<>0) Or (En<>Vn) OR Not SeekEoLn(VKif) Then Exit;
ReadLn(VKif);
Pont[t,1]:=1; {A reszfeladat OK }
{B reszfekadat:}
Beolvas;
VT:=0; Db:=1;
Dv[1]:=EH;
For i:=1 To N-1 Do Begin
{$I-}
ReadLn(VKif,V1,V2);
{$I+}
If (IOResult<>0) Then Exit;
j:=1;
While (j<=Db)And(V1<>Dv[j]) Do Inc(j);
If j>Db Then Exit;
VT:=VT+V1;
Dv[j]:=V1-V2;
Inc(Db); Dv[Db]:=V2;
End{for i};
If VT<>EN Then Exit;
For i:=1 To N Do Begin
OK:=False;
For j:=1 To N Do
If D[j]=Dv[i] Then Begin
D[j]:=0;
OK:=True;
Break
End;
If Not OK Then Exit;
End{for i};
Pont[t,2]:=1;
End (*Ellen*);
Begin {Program}
TeK:=ParamStr(1)+'\';
Val(ParamStr(2),Tesz,i);
Val(ParamStr(3),TLim,i);
For i:=1 To Tesz Do Begin
Pont[i,1]:=0; Pont[i,2]:=0;
End;
For t:=1 To Tesz Do Begin
Assign(Tf,FNev+TeC[t]+'.STP');
Reset(Tf);
Read(Tf,T1,M1);
Close(Tf);
Assign(IdoF,FNev+TeC[t]+'.IDO');
Rewrite(IdoF);
If (M1=-1) Then { idolimit tullepes }
WriteLn(IdoF,' Megszakitva, Idolimit tullepes miatt! ')
Else If (T1>TLim) Then
WriteLn(IdoF,'Futasi ido: ',T1/10.0:6:2,' mp',' Idolimit tullepes! ')
Else Begin
WriteLn(IdoF,'Futasi ido: ',T1/10.0:6:2,' mp');
FFNev:=FNev+TeC[t]+'.KI';
Assign(VKif,FFNev); { versenyzo outputja az aktualis konytarban!}
{$I-}
Reset(VKif);
{$I+}
If IOResult<>0 Then
WriteLn(FFNev+' állomány nem található!')
Else Begin
Assign(Kif,TeK+FNev+TeC[t]+'.KI');
Reset(Kif);
Ellen(t);
Close(Vkif);
Close(Kif);
End;
End;
Close(IdoF);
End{for t};
KiIr;
End. |
unit ufrmDetilPOFromTrader;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterDialog, StdCtrls, Grids, BaseGrid, AdvGrid,
ufraFooterDialog2Button, ExtCtrls, SUIForm, JvEdit, Mask, JvToolEdit, AdvObj,
JvExMask, JvExStdCtrls, JvValidateEdit;
type
TfrmDetilPOFromTrader = class(TfrmMasterDialog)
Panel1: TPanel;
Panel2: TPanel;
strgGrid: TAdvStringGrid;
lblPOTrader: TLabel;
lblPOTraderDate: TLabel;
edtTraderCode: TEdit;
edtTraderName: TEdit;
edtTraderType: TEdit;
lbl11: TLabel;
lbl3: TLabel;
lbl4: TLabel;
edtStatus: TEdit;
edtLeadTime: TEdit;
lbl5: TLabel;
lbl9: TLabel;
edtTOP: TEdit;
curredtTotalPrice: TJvValidateEdit;
lblTotalPO: TLabel;
lbl10: TLabel;
lbl8: TLabel;
dtTgl: TJvDateEdit;
edtPOASNo: TEdit;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure strgGridGetFloatFormat(Sender: TObject; ACol, ARow: Integer;
var IsFloat: Boolean; var FloatFormat: String);
private
FPOASNo: string;
FUnitID: Integer;
procedure SetPOASNo(const Value: string);
procedure ParseHeaderGrid();
procedure ParseTraderPO;
procedure ShowQtyPOAssgrosDetilByPONo;
public
{ Public declarations }
procedure SetAllComponentReadOnly;
property UnitID: Integer read FUnitID write FUnitID;
published
property POASNo: string read FPOASNo write SetPOASNo;
end;
var
frmDetilPOFromTrader: TfrmDetilPOFromTrader;
implementation
uses uRMSUnit, uPOAssgrosNew, uDOAssgros, DB, uConn;
const
_kolNo : integer = 0;
_kolBrgID : integer = 1;
_kolBrgNm : integer = 2;
_kolUom : integer = 3;
_kolQtyOrder : integer = 4;
_kolQtyStock : integer = 5;
_kolStatus : integer = 6;
_fixedRow : integer = 1;
_colCOunt : integer = 7;
_rowCount : integer = 2;
{$R *.dfm}
procedure TfrmDetilPOFromTrader.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TfrmDetilPOFromTrader.FormDestroy(Sender: TObject);
begin
inherited;
frmDetilPOFromTrader := nil;
end;
procedure TfrmDetilPOFromTrader.SetPOASNo(const Value: string);
begin
FPOASNo := Value;
end;
procedure TfrmDetilPOFromTrader.FormShow(Sender: TObject);
begin
inherited;
ParseTraderPO;
ParseHeaderGrid;
ShowQtyPOAssgrosDetilByPONo;
end;
procedure TfrmDetilPOFromTrader.ParseHeaderGrid;
begin
with strgGrid do
begin
Clear;
ColCount := _colCOunt;
RowCount := _rowcount;
Cells[_kolNo,0] := 'NO.';
Cells[_kolBrgID,0] := 'PRODUCT CODE';
Cells[_kolbrgNm,0] := 'PRODUCT NAME';
Cells[_kolUom,0] := 'UOM';
Cells[_kolQtyOrder,0] := 'QTY ORDER';
Cells[_kolQtyStock,0] := 'QTY STOCK';
Cells[_kolStatus,0] := 'STATUS';
FixedRows := _fixedRow;
AutoSize := true;
end;
end;
procedure TfrmDetilPOFromTrader.ParseTraderPO;
//var
// data: TResultDataSet;
// aParams: TArr;
begin
with cOpenQuery(getSQLPoAssGrosTrader(FPOASNo, FUnitID))do
begin
try
edtPOASNo.Text := FPOASNo;
dtTgl.Date := FieldByName('POAS_DATE').AsDateTime;
edtTraderCode.Text := FieldByName('TRD_CODE').AsString;
edtTraderName.Text := FieldByName('TRD_NAME').AsString;
if (FieldByName('TRD_IS_ASSGROS').AsInteger = 1) then
edtTraderType.Text := 'ASSGROS'
else
edtTraderType.Text := 'TRADER';
edtStatus.Text := FieldByName('POAS_STATUS').AsString;
edtLeadTime.Text := inttostr(FieldByName('POAS_LEAD_TIME').AsInteger);
edtTOP.Text := inttostr(FieldByName('POAS_TOP').AsInteger);
curredtTotalPrice.Value := FieldByName('POAS_TOTAL').AsCurrency;
finally
Free;
end;
end;
{
SetLength(aParams,1);
aParams[0].tipe := ptString;
aParams[0].data := APONo;
if not assigned(PurchasingOrder) then
PurchasingOrder := TPurchasingOrder.Create;
data := PurchasingOrder.GetTraderPOAssgros(aParams);
if (data.RecordCount > 0) then
begin
with data do
begin
edtPOASNo.Text := POASNo;
dtTgl.Date := FieldByName('POAS_DATE').AsDateTime;
edtTraderCode.Text := FieldByName('TRD_CODE').AsString;
edtTraderName.Text := FieldByName('TRD_NAME').AsString;
if (FieldByName('TRD_IS_ASSGROS').AsInteger = 1) then
edtTraderType.Text := 'ASSGROS'
else
edtTraderType.Text := 'TRADER';
edtStatus.Text := FieldByName('POAS_STATUS').AsString;
edtLeadTime.Text := inttostr(FieldByName('POAS_LEAD_TIME').AsInteger);
edtTOP.Text := inttostr(FieldByName('POAS_TOP').AsInteger);
curredtTotalPrice.Value := FieldByName('POAS_TOTAL').AsCurrency;
end;
end;
}
end;
procedure TfrmDetilPOFromTrader.ShowQtyPOAssgrosDetilByPONo;
var
//aParams: TArr;
// data: TResultDataSet;
i, n, m: integer;
begin
if strgGrid.FloatingFooter.Visible then
m := _fixedRow + 1
else
m := _fixedRow;
n := strgGrid.rowCount;
i := 0;
with cOpenQuery(getSQLPoAssGrosTraderDetail(FPOASNo, FUnitID)) do
begin
try
while not Eof do
begin
if (i >= n - m) then
strgGrid.AddRow;
strgGrid.Cells[_kolNo, i + _fixedRow] := inttostr(i + 1);
strgGrid.Cells[_kolBrgID, i + _fixedRow] := fieldByName('BRG_CODE').AsString;
strgGrid.Cells[_kolBrgNm, i + _fixedRow] := fieldByName('BRG_ALIAS').AsString;
strgGrid.Cells[_kolUom, i + _fixedRow] := fieldByName('POASD_SAT_CODE').AsString;
strgGrid.Cells[_kolQtyOrder, i + _fixedRow] := FloatToStr(fieldByName('POASD_QTY').AsFloat);
if (edtTraderType.Text = 'ASSGROS') then
begin
strgGrid.Cells[_kolQtyStock, i + _fixedRow] := inttostr(fieldByName('BRGT_ASSGROS_STOCK').AsInteger);
if (fieldByName('POASD_QTY').AsFloat < fieldByName('BRGT_ASSGROS_STOCK').AsFloat) then
strgGrid.Cells[_kolStatus, i + _fixedRow] := 'AVAILABLE'
else
strgGrid.Cells[_kolStatus, i + _fixedRow] := 'NOT AVAILABLE';
end
else
begin
strgGrid.Cells[_kolQtyStock, i + _fixedRow] := FloatToStr(fieldByName('BRGT_TRADER_STOCK').AsFloat);
if (fieldByName('POASD_QTY').AsFloat < fieldByName('BRGT_TRADER_STOCK').AsFloat) then
strgGrid.Cells[_kolStatus, i + _fixedRow] := 'AVAILABLE'
else
strgGrid.Cells[_kolStatus, i + _fixedRow] := 'NOT AVAILABLE';
end;
Inc(i);
Next;
end;
finally
Free;
strgGrid.AutoSize := true;
end;
end;
// SetLength(aParams,1);
// aParams[0].tipe := ptString;
//// aParams[0].data := APONo;
// aParams[0].data := FPOASNo;
// if not assigned(PurchasingOrder) then
// PurchasingOrder := TPurchasingOrder.Create;
// data := PurchasingOrder.GetQtyPOAssgrosDetilByNo(aParams);
//
// ParseHeaderGrid;
// if (data.RecordCount > 0) then
// begin
// with strgGrid do
// begin
// RowCount := RowCount+data.RecordCount-1;
// i:=1;
// while not data.Eof do
// begin
// Cells[0,i] := inttostr(i);
// Cells[1,i] := data.fieldByName('BRG_CODE').AsString;
// Cells[2,i] := data.fieldByName('BRG_NAME').AsString;
// Cells[3,i] := data.fieldByName('POASD_SAT_CODE').AsString;
// Cells[4,i] := FloatToStr(data.fieldByName('POASD_QTY').AsFloat);
// if (edtTraderType.Text = 'ASSGROS') then
// begin
// Cells[5,i] := inttostr(data.fieldByName('BRGT_ASSGROS_STOCK').AsInteger);
// if (data.fieldByName('POASD_QTY').AsFloat < data.fieldByName('BRGT_ASSGROS_STOCK').AsFloat) then
// Cells[6,i] := 'AVAILABLE'
// else
// Cells[6,i] := 'NOT AVAILABLE';
// end
// else
// begin
// Cells[5,i] := FloatToStr(data.fieldByName('BRGT_TRADER_STOCK').AsFloat);
// if (data.fieldByName('POASD_QTY').AsFloat < data.fieldByName('BRGT_TRADER_STOCK').AsFloat) then
// Cells[6,i] := 'AVAILABLE'
// else
// Cells[6,i] := 'NOT AVAILABLE';
// end;
//
// i:=i+1;
// data.Next;
// end;
//
// AutoSize := true;
// end;
// end;
end;
procedure TfrmDetilPOFromTrader.SetAllComponentReadOnly;
var
i: integer;
begin
for i:=0 to ComponentCount-1 do
if Components[i] is TEdit then
TEdit(Components[i]).ReadOnly := True
else if Components[i] is TJvDateEdit then
TJvDateEdit(Components[i]).ReadOnly := True
else if Components[i] is TJvValidateEdit then
TJvValidateEdit(Components[i]).ReadOnly := True;
end;
procedure TfrmDetilPOFromTrader.strgGridGetFloatFormat(Sender: TObject;
ACol, ARow: Integer; var IsFloat: Boolean; var FloatFormat: String);
begin
inherited;
FloatFormat := '%.3n';
if (ACol in [_kolQtyOrder,_kolQtyStock]) and (ARow > 0) then
IsFloat := True
else
// if (ACol in [4,6,7]) and (ARow > 0) then
// begin
// FloatFormat := '%.2n';
// IsFloat := True;
// end
// else
IsFloat := False;
end;
end.
|
unit cryptlib;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
// Note that the cryptlib Delphi module supplied with cryptlib isn't used;
// that unit staticly links to the cryptlib DLL, but we can't be sure the user
// will have this installed - therefore we have this unit to *dynamically*
// link to the cryptlib DLL.
//
// Note: This unit only includes those functions required to generate random
// data.
interface
uses
Windows, // Required for THandle
SysUtils; // Required for Exception
const
// The filename of the DLL
CRYPTLIB32_DLL = 'cryptlib\cl32.dll';
CRYPTLIB64_DLL = 'cryptlib\cl64.dll';
type
// #define TC_RET __declspec( dllXXport ) int __stdcall /* DLL XXport ret.val.*/
TC_RET = integer;
// typedef int CRYPT_CONTEXT;
TCRYPT_CONTEXT = integer;
PCRYPT_CONTEXT = ^TCRYPT_CONTEXT;
// typedef int CRYPT_USER;
TCRYPT_USER = integer;
Tcryptlib_CRYPT_ALGO_TYPE = (
// No encryption
catCRYPT_ALGO_NONE, // No encryption
// Conventional encryption
catCRYPT_ALGO_DES, // DES
catCRYPT_ALGO_3DES, // Triple DES
catCRYPT_ALGO_IDEA, // IDEA
catCRYPT_ALGO_CAST, // CAST-128
catCRYPT_ALGO_RC2, // RC2
catCRYPT_ALGO_RC4, // RC4
catCRYPT_ALGO_RC5, // RC5
catCRYPT_ALGO_AES, // AES
catCRYPT_ALGO_BLOWFISH, // Blowfish
catCRYPT_ALGO_SKIPJACK, // Skipjack
// Public-key encryption
catCRYPT_ALGO_DH, // Diffie-Hellman
catCRYPT_ALGO_RSA, // RSA
catCRYPT_ALGO_DSA, // DSA
catCRYPT_ALGO_ELGAMAL, // ElGamal
catCRYPT_ALGO_KEA, // KEA
// Hash algorithms
catCRYPT_ALGO_MD2, // MD2
catCRYPT_ALGO_MD4, // MD4
catCRYPT_ALGO_MD5, // MD5
catCRYPT_ALGO_SHA, // SHA/SHA1
catCRYPT_ALGO_RIPEMD160, // RIPE-MD 160
catCRYPT_ALGO_SHA2, // SHA2 (SHA-256/384/512)
// MAC's
catCRYPT_ALGO_HMAC_MD5, // HMAC-MD5
catCRYPT_ALGO_HMAC_SHA, // HMAC-SHA
catCRYPT_ALGO_HMAC_RIPEMD160, // HMAC-RIPEMD-160
// Vendors may want to use their own algorithms that aren't part of the
// general cryptlib suite. The following values are for vendor-defined
// algorithms, and can be used just like the named algorithm types (it's
// up to the vendor to keep track of what _VENDOR1 actually corresponds
// to)
catCRYPT_ALGO_VENDOR1,
catCRYPT_ALGO_VENDOR2,
catCRYPT_ALGO_VENDOR3
);
const
cryptlib_CRYPT_ALGO_TYPE_ID : array [Tcryptlib_CRYPT_ALGO_TYPE] of integer = (
// No encryption
0, // No encryption
// Conventional encryption
1, // DES
2, // Triple DES
3, // IDEA
4, // CAST-128
5, // RC2
6, // RC4
7, // RC5
8, // AES
9, // Blowfish
10, // Skipjack
// Public-key encryption
100, // Diffie-Hellman
101, // RSA
102, // DSA
103, // ElGamal
104, // KEA
// Hash algorithms
200, // MD2
201, // MD4
202, // MD5
203, // SHA/SHA1
204, // RIPE-MD 160
205, // SHA2 (SHA-256/384/512)
// MAC's
300, // HMAC-MD5
301, // HMAC-SHA
302, // HMAC-RIPEMD-160
// Vendors may want to use their own algorithms that aren't part of the
// general cryptlib suite. The following values are for vendor-defined
// algorithms, and can be used just like the named algorithm types (it's
// up to the vendor to keep track of what _VENDOR1 actually corresponds
// to)
10000,
10001,
10002
);
cryptlib_CRYPT_ALGO_TYPE_TITLE : array [Tcryptlib_CRYPT_ALGO_TYPE] of string = (
// No encryption
'No encryption',
// Conventional encryption
'DES',
'Triple DES',
'IDEA',
'CAST-128',
'RC2',
'RC4',
'RC5',
'AES',
'Blowfish',
'Skipjack',
// Public-key encryption
'Diffie-Hellman',
'RSA',
'DSA',
'ElGamal',
'KEA',
// Hash algorithms
'MD2',
'MD4',
'MD5',
'SHA/SHA1',
'RIPE-MD 160',
'SHA2 (SHA-256/384/512)',
// MAC's
'HMAC-MD5',
'HMAC-SHA',
'HMAC-RIPEMD-160',
// Vendors may want to use their own algorithms that aren't part of the
// general cryptlib suite. The following values are for vendor-defined
// algorithms, and can be used just like the named algorithm types (it's
// up to the vendor to keep track of what _VENDOR1 actually corresponds
// to)
'Vendor algorithm #1',
'Vendor algorithm #2',
'Vendor algorithm #3'
);
// The maximum size of a text string (e.g.key owner name)
cryptlib_CRYPT_MAX_TEXTSIZE = 64;
// Status Codes
// No error in function call
cryptlib_CRYPT_OK = 0;
// Error in parameters passed to function
cryptlib_CRYPT_ERROR_PARAM1 = -1; // Bad argument, parameter 1
cryptlib_CRYPT_ERROR_PARAM2 = -2; // Bad argument, parameter 2
cryptlib_CRYPT_ERROR_PARAM3 = -3; // Bad argument, parameter 3
cryptlib_CRYPT_ERROR_PARAM4 = -4; // Bad argument, parameter 4
cryptlib_CRYPT_ERROR_PARAM5 = -5; // Bad argument, parameter 5
cryptlib_CRYPT_ERROR_PARAM6 = -6; // Bad argument, parameter 6
cryptlib_CRYPT_ERROR_PARAM7 = -7; // Bad argument, parameter 7
// Errors due to insufficient resources
cryptlib_CRYPT_ERROR_MEMORY = -10; // Out of memory
cryptlib_CRYPT_ERROR_NOTINITED = -11; // Data has not been initialised
cryptlib_CRYPT_ERROR_INITED = -12; // Data has already been init'd
cryptlib_CRYPT_ERROR_NOSECURE = -13; // Opn.not avail.at requested sec.level
cryptlib_CRYPT_ERROR_RANDOM = -14; // No reliable random data available
cryptlib_CRYPT_ERROR_FAILED = -15; // Operation failed
// Security violations
cryptlib_CRYPT_ERROR_NOTAVAIL = -20; // This type of opn.not available
cryptlib_CRYPT_ERROR_PERMISSION = -21; // No permiss.to perform this operation
cryptlib_CRYPT_ERROR_WRONGKEY = -22; // Incorrect key used to decrypt data
cryptlib_CRYPT_ERROR_INCOMPLETE = -23; // Operation incomplete/still in progress
cryptlib_CRYPT_ERROR_COMPLETE = -24; // Operation complete/can't continue
cryptlib_CRYPT_ERROR_TIMEOUT = -25; // Operation timed out before completion
cryptlib_CRYPT_ERROR_INVALID = -26; // Invalid/inconsistent information
cryptlib_CRYPT_ERROR_SIGNALLED = -27; // Resource destroyed by extnl.event
// High-level function errors
cryptlib_CRYPT_ERROR_OVERFLOW = -30; // Resources/space exhausted
cryptlib_CRYPT_ERROR_UNDERFLOW = -31; // Not enough data available
cryptlib_CRYPT_ERROR_BADDATA = -32; // Bad/unrecognised data format
cryptlib_CRYPT_ERROR_SIGNATURE = -33; // Signature/integrity check failed
// Data access function errors
cryptlib_CRYPT_ERROR_OPEN = -40; // Cannot open object
cryptlib_CRYPT_ERROR_READ = -41; // Cannot read item from object
cryptlib_CRYPT_ERROR_WRITE = -42; // Cannot write item to object
cryptlib_CRYPT_ERROR_NOTFOUND = -43; // Requested item not found in object
cryptlib_CRYPT_ERROR_DUPLICATE = -44; // Item already present in object
// Data enveloping errors
cryptlib_CRYPT_ENVELOPE_RESOURCE = -50; // Need resource to proceed
type
Pcryptlib_CRYPT_QUERY_INFO = ^Tcryptlib_CRYPT_QUERY_INFO;
Tcryptlib_CRYPT_QUERY_INFO = record
// Algorithm information
algoName: array [0..(cryptlib_CRYPT_MAX_TEXTSIZE-1)] of Ansichar; // Algorithm name
blockSize: integer; // Block size of the algorithm
minKeySize: integer; // Minimum key size in bytes
keySize: integer; // Recommended key size in bytes
maxKeySize: integer; // Maximum key size in bytes
end;
// Initialise and shut down cryptlib
// TC_RET cryptInit( void );
Tcryptlib_cryptInit = function(): TC_RET;
// TC_RET cryptEnd( void ): TC_RET;
Tcryptlib_cryptEnd = function(): TC_RET;
// Query cryptlibs capabilities
//TC_RET cryptQueryCapability( C_IN CRYPT_ALGO_TYPE cryptAlgo,
// C_OUT CRYPT_QUERY_INFO C_PTR cryptQueryInfo );
Tcryptlib_cryptQueryCapability = function(
cryptAlgo: integer;
cryptQueryInfo: Pcryptlib_CRYPT_QUERY_INFO
): TC_RET; stdcall;
// TC_RET cryptAddRandom( C_IN void C_PTR randomData, C_IN int randomDataLength );
Tcryptlib_cryptAddRandom = function(
randomData: Pointer;
randomDataLength: integer
): TC_RET; stdcall;
// TC_RET cryptCreateContext( C_OUT CRYPT_CONTEXT C_PTR cryptContext,
// C_IN CRYPT_USER cryptUser,
// C_IN CRYPT_ALGO_TYPE cryptAlgo );
Tcryptlib_cryptCreateContext = function(
cryptContext: PCRYPT_CONTEXT;
cryptUser: TCRYPT_USER;
cryptAlgo: integer
): TC_RET; stdcall;
// TC_RET cryptDestroyContext( C_IN CRYPT_CONTEXT cryptContext );
Tcryptlib_cryptDestroyContext = function(
cryptContext: TCRYPT_CONTEXT
): TC_RET; stdcall;
// TC_RET cryptGenerateKey( C_IN CRYPT_CONTEXT cryptContext );
Tcryptlib_cryptGenerateKey = function(
cryptContext: TCRYPT_CONTEXT
): TC_RET; stdcall;
// TC_RET cryptEncrypt( C_IN CRYPT_CONTEXT cryptContext, C_INOUT void C_PTR buffer,
// C_IN int length );
Tcryptlib_cryptEncrypt = function(
cryptContext: TCRYPT_CONTEXT;
buffer: Pointer;
length: integer
): TC_RET; stdcall;
// TC_RET cryptDecrypt( C_IN CRYPT_CONTEXT cryptContext, C_INOUT void C_PTR buffer,
// C_IN int length );
Tcryptlib_cryptDecrypt = function(
cryptContext: TCRYPT_CONTEXT;
buffer: Pointer;
length: integer
): TC_RET; stdcall;
// Exceptions...
ECryptLibError = class(Exception);
ECryptLibBadDLL = class(ECryptLibError);
const
// A magic value for unused parameters
cryptlib_CRYPT_UNUSED = -101;
// The type of information polling to perform to get random seed information */
cryptlib_CRYPT_RANDOM_FASTPOLL = -300;
cryptlib_CRYPT_RANDOM_SLOWPOLL = -301;
var
// When loaded, this holds the handle to the DLL
hCryptLibDLL: THandle;
// When the DLL is loaded, these are set to the function pointers
cryptlib_cryptInit: Tcryptlib_cryptInit;
cryptlib_cryptEnd: Tcryptlib_cryptEnd;
cryptlib_cryptQueryCapability: Tcryptlib_cryptQueryCapability;
cryptlib_cryptCreateContext: Tcryptlib_cryptCreateContext;
cryptlib_cryptDestroyContext: Tcryptlib_cryptDestroyContext;
cryptlib_cryptAddRandom: Tcryptlib_cryptAddRandom;
cryptlib_cryptGenerateKey: Tcryptlib_cryptGenerateKey;
cryptlib_cryptEncrypt: Tcryptlib_cryptEncrypt;
cryptlib_cryptDecrypt: Tcryptlib_cryptDecrypt;
// Load/unload cryptlib DLL
function cryptlib_LoadDLL(): boolean;
function cryptlib_UnloadDLL(): boolean;
// Simple "helper" functions
function cryptlib_cryptStatusError(status: integer): boolean;
function cryptlib_cryptStatusOK(status: integer): boolean;
// This may *only* be called *after*:
// cryptlib_LoadDLL(...)
// cryptlib_cryptInit(...)
// cryptlib_cryptAddRandom(...)
function cryptlib_RNG(lengthBytes: integer): ansistring;
implementation
uses
//delphi
Math,// Required for min(...)
strutils,//for ifthen
//sdu
sdugeneral
;
// Internal - populate the global variable function pointers
procedure _cryptlib_GetDLLProcAddresses(); forward;
const
// Names of the various functions within the DLL
DLL_FUNCTIONNAME_cryptInit = 'cryptInit';
DLL_FUNCTIONNAME_cryptEnd = 'cryptEnd';
DLL_FUNCTIONNAME_cryptQueryCapability = 'cryptQueryCapability';
DLL_FUNCTIONNAME_cryptCreateContext = 'cryptCreateContext';
DLL_FUNCTIONNAME_cryptDestroyContext = 'cryptDestroyContext';
DLL_FUNCTIONNAME_cryptAddRandom = 'cryptAddRandom';
DLL_FUNCTIONNAME_cryptGenerateKey = 'cryptGenerateKey';
DLL_FUNCTIONNAME_cryptEncrypt = 'cryptEncrypt';
DLL_FUNCTIONNAME_cryptDecrypt = 'cryptDecrypt';
// Exception error messages
E_CRYPTLIB_NO_DLL = 'Unable to load cryptlib DLL.';
E_CRYPTLIB_BAD_DLL = 'cryptlib DLL did not have correct facilities!';
function cryptlib_cryptStatusError(status: integer): boolean;
begin
Result := (status < cryptlib_CRYPT_OK);
end;
function cryptlib_cryptStatusOK(status: integer): boolean;
begin
Result := (status = cryptlib_CRYPT_OK);
end;
function cryptlib_LoadDLL(): boolean;
var
dll : widestring;
begin
result := FALSE;
// If the lib is already loaded, just return TRUE
if (hCryptLibDLL <> 0) then begin
result := TRUE;
end else begin
//the dll version required is based on if the *app* is 32 or 64 bit - not the OS
dll := Ifthen( SDUApp64bit(), CRYPTLIB64_DLL, CRYPTLIB32_DLL);
hCryptLibDLL := LoadLibrary(PChar(dll));
if (hCryptLibDLL <> 0) then
begin
// DLL loaded, get function addresses
try
_cryptlib_GetDLLProcAddresses();
result := TRUE;
except
on ECryptLibBadDLL do
begin
// Unload DLL; there was a problem
cryptlib_UnloadDLL();
end;
end;
end;
end;
end;
function cryptlib_UnloadDLL(): boolean;
begin
if (hCryptLibDLL<>0) then
begin
FreeLibrary(hCryptLibDLL);
hCryptLibDLL := 0;
end;
Result := TRUE;
end;
procedure _cryptlib_GetDLLProcAddresses();
procedure CheckFnAvailable(fnPtr: Pointer; fnName: string);
begin
if (fnPtr = nil) then
begin
raise ECryptLibError.Create(E_CRYPTLIB_BAD_DLL+' ('+fnName+')');
end;
end;
begin
@cryptlib_cryptInit := GetProcAddress(hCryptLibDLL, DLL_FUNCTIONNAME_cryptInit);
CheckFnAvailable(@cryptlib_cryptInit, DLL_FUNCTIONNAME_cryptInit);
@cryptlib_cryptEnd := GetProcAddress(hCryptLibDLL, DLL_FUNCTIONNAME_cryptEnd);
CheckFnAvailable(@cryptlib_cryptEnd, DLL_FUNCTIONNAME_cryptEnd);
@cryptlib_cryptQueryCapability := GetProcAddress(hCryptLibDLL, DLL_FUNCTIONNAME_cryptQueryCapability);
CheckFnAvailable(@cryptlib_cryptQueryCapability, DLL_FUNCTIONNAME_cryptQueryCapability);
@cryptlib_cryptCreateContext := GetProcAddress(hCryptLibDLL, DLL_FUNCTIONNAME_cryptCreateContext);
CheckFnAvailable(@cryptlib_cryptCreateContext, DLL_FUNCTIONNAME_cryptCreateContext);
@cryptlib_cryptDestroyContext := GetProcAddress(hCryptLibDLL, DLL_FUNCTIONNAME_cryptDestroyContext);
CheckFnAvailable(@cryptlib_cryptDestroyContext, DLL_FUNCTIONNAME_cryptDestroyContext);
@cryptlib_cryptAddRandom := GetProcAddress(hCryptLibDLL, DLL_FUNCTIONNAME_cryptAddRandom);
CheckFnAvailable(@cryptlib_cryptAddRandom, DLL_FUNCTIONNAME_cryptAddRandom);
@cryptlib_cryptGenerateKey := GetProcAddress(hCryptLibDLL, DLL_FUNCTIONNAME_cryptGenerateKey);
CheckFnAvailable(@cryptlib_cryptGenerateKey, DLL_FUNCTIONNAME_cryptGenerateKey);
@cryptlib_cryptEncrypt := GetProcAddress(hCryptLibDLL, DLL_FUNCTIONNAME_cryptEncrypt);
CheckFnAvailable(@cryptlib_cryptEncrypt, DLL_FUNCTIONNAME_cryptEncrypt);
@cryptlib_cryptDecrypt := GetProcAddress(hCryptLibDLL, DLL_FUNCTIONNAME_cryptDecrypt);
CheckFnAvailable(@cryptlib_cryptDecrypt, DLL_FUNCTIONNAME_cryptDecrypt);
end;
{ TODO 1 -otdk -crefactor : convert to use bytes instead of ansichar }
// This may *only* be called *after*:
// cryptlib_LoadDLL(...)
// cryptlib_cryptInit(...)
// cryptlib_cryptAddRandom(...)
// This function carries out the procedure described in the cryptlib manual for
// generating random data.
// Specifically, after cryptInit and cryptAddRandom are called, it generates a
// random key, and encrypts an arbitary block of data with it.
// The output from this encryption is the resulting random data.
// In terms of implementation, we use AES to encrypt. We only assume that
// cryptlib is using the minimum keysize (docs refer to AES-128). We can
// therefore only rely on this minimum keysize as being the amount of entropy
// supplied by any key generated
// Because of this, we repeat the procedure, only drawing that number of bits
// each time we obtain random data.
// lengthBytes - Set this to the number of *bytes* of random data to be generated
function cryptlib_RNG(lengthBytes: integer): ansistring;
const
// The algorithm used is *relativly* arbitary
CYPHER_ALG = catCRYPT_ALGO_AES;
var
funcResult: integer;
buffer: PAnsiChar;
allOK: boolean;
cryptContext: TCRYPT_CONTEXT;
cypherKeysizeBytes: integer; // In *bytes*
info: Tcryptlib_CRYPT_QUERY_INFO;
begin
Result := '';
// Identify the minimum keysize of the encryption algorithm; this should be
// the number of random bits cryptlib generates
funcResult := cryptlib_cryptQueryCapability(
cryptlib_CRYPT_ALGO_TYPE_ID[catCRYPT_ALGO_AES],
@info
);
allOK := cryptlib_cryptStatusOK(funcResult);
cypherKeysizeBytes := 0;
if (allOK) then
begin
cypherKeysizeBytes := info.minKeySize; // In *bytes*
end;
buffer := AllocMem(cypherKeysizeBytes);
try
while (
allOK AND
(length(Result) < lengthBytes)
) do
begin
funcResult := cryptlib_cryptCreateContext(
@cryptContext,
cryptlib_CRYPT_UNUSED,
cryptlib_CRYPT_ALGO_TYPE_ID[CYPHER_ALG]
);
allOK := cryptlib_cryptStatusOK(funcResult);
if (allOK) then
begin
funcResult := cryptlib_cryptGenerateKey(cryptContext);
allOK := cryptlib_cryptStatusOK(funcResult);
if (allOK) then
begin
funcResult := cryptlib_cryptEncrypt(
cryptContext,
buffer,
cypherKeysizeBytes
);
allOK := cryptlib_cryptStatusOK(funcResult);
if (allOK) then
begin
Result := Result + Copy(buffer, 1, min(
cypherKeysizeBytes,
(lengthBytes - Length(Result))
));
end;
end;
end;
funcResult := cryptlib_cryptDestroyContext(cryptContext);
allOK := cryptlib_cryptStatusOK(funcResult);
// Clear buffer ready for next...
FillChar(buffer^, cypherKeysizeBytes, $00);
end; // while loop
finally
FreeMem(buffer);
end;
// Return an empty string on error
if not(allOK) then
begin
Result := '';
end;
end;
initialization
hCryptLibDLL := 0;
END.
|
unit DPM.Core.Packaging.IdValidator;
interface
uses
System.RegularExpressions,
DPM.Core.Constants;
// Valid Id is : Org.PackageName
// must start with a letter.
type
TPackageIdValidator = class
private
class var
FRegex : TRegEx;
public
class procedure ValidatePackageId(const Id : string);
class function IsValidPackageId(const Id : string) : boolean;
class constructor Create;
end;
implementation
uses
System.SysUtils;
{ TPackageIdValidator }
class constructor TPackageIdValidator.Create;
begin
//prefx must start with A-Z and must be at least 3 chars.
FRegex := TRegex.Create('^[A-Z](?:\w+){2,}(?:\.\w+)+$', [roIgnoreCase]);
end;
class function TPackageIdValidator.IsValidPackageId(const Id : string) : boolean;
begin
if Id = '' then
result := false
else
result := FRegex.IsMatch(Id);
end;
class procedure TPackageIdValidator.ValidatePackageId(const Id : string);
begin
if Id = '' then
raise EArgumentNilException.Create('Id is empty');
if Length(Id) > cMaxPackageIdLength then
raise EArgumentException.Create('Length of Id [' + Id + '] exceeds max Id length [' + IntToStr(cMaxPackageIdLength) + ']');
if not IsValidPackageId(Id) then
raise EArgumentException.Create('Invalid Package Id [' + Id + ']');
end;
end.
|
{$reference System.Speech.dll}
unit module;
interface
procedure SaveMP3(name,text: string; speed,voice:integer);
procedure Speak(s: string);
procedure Speed(i:integer);
procedure Voice(i: integer);
procedure SpeakAsync(s: string);
implementation
uses System.Speech.Synthesis;
var ss: SpeechSynthesizer;
procedure SaveMP3(name,text: string; speed,voice:integer);
begin
var q1:=new SpeechSynthesizer;
q1.SetOutputToWaveFile(name);
q1.Rate:=speed;
var voices := q1.GetInstalledVoices;
q1.SelectVoice(voices[voice].VoiceInfo.Name);
q1.Speak(text);
q1.SetOutputToNull;
end;
procedure Speed(i: integer);
begin
ss.Rate:=i;
end;
procedure Voice(i: integer);
begin
var voices := ss.GetInstalledVoices;
ss.SelectVoiceByHints(VoiceGender.Male, VoiceAge.Teen, 1, System.Globalization.CultureInfo.CreateSpecificCulture('ru-RU'));
ss.SelectVoice(voices[i].VoiceInfo.Name);
end;
procedure Speak(s: string);
begin
ss.Speak(s);
end;
procedure SpeakAsync(s: string);
begin
ss.SpeakAsync(s);
end;
begin
ss := new SpeechSynthesizer;
var voices := ss.GetInstalledVoices;
ss.SelectVoice(voices[0].VoiceInfo.Name)
end. |
unit pangocairolib;
{$IFDEF FPC}
{$MODE OBJFPC}{$H+}
{$PACKRECORDS C}
{$ELSE}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
// SVN: 2830
// pangocairo.h
interface
uses cairolib, pangolib;
(* Pango
* pangocairo.h:
*
* Copyright (C) 1999, 2004 Red Hat, Inc.
*
* 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.
*
* This library 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.
*)
(**
* PangoCairoFont:
*
* #PangoCairoFont is an interface exported by fonts for
* use with Cairo. The actual type of the font will depend
* on the particular font technology Cairo was compiled to use.
*
* Since: 1.18
**)
type
PPangoCairoFont = ^PangoCairoFont;
_PangoCairoFont = record
end;
PangoCairoFont = _PangoCairoFont;
//#define PANGO_TYPE_CAIRO_FONT (pango_cairo_font_get_type ())
//#define PANGO_CAIRO_FONT(object) (G_TYPE_CHECK_INSTANCE_CAST ((object), PANGO_TYPE_CAIRO_FONT, PangoCairoFont))
//#define PANGO_IS_CAIRO_FONT(object) (G_TYPE_CHECK_INSTANCE_TYPE ((object), PANGO_TYPE_CAIRO_FONT))
(**
* PangoCairoFontMap:
*
* #PangoCairoFontMap is an interface exported by font maps for
* use with Cairo. The actual type of the font map will depend
* on the particular font technology Cairo was compiled to use.
*
* Since: 1.10
**)
PPangoCairoFontMap = ^PangoCairoFontMap;
_PangoCairoFontMap = record
end;
PangoCairoFontMap = _PangoCairoFontMap;
//#define PANGO_TYPE_CAIRO_FONT_MAP (pango_cairo_font_map_get_type ())
//#define PANGO_CAIRO_FONT_MAP(object) (G_TYPE_CHECK_INSTANCE_CAST ((object), PANGO_TYPE_CAIRO_FONT_MAP, PangoCairoFontMap))
//#define PANGO_IS_CAIRO_FONT_MAP(object) (G_TYPE_CHECK_INSTANCE_TYPE ((object), PANGO_TYPE_CAIRO_FONT_MAP))
PangoCairoShapeRendererFunc = procedure(cr: PCairo; attr: PPangoAttrShape; do_path: LongBool; data: Pointer); cdecl;
(*
* PangoCairoFontMap
*)
function pango_cairo_font_map_get_type: Cardinal; cdecl;
function pango_cairo_font_map_new: PPangoFontMap; cdecl;
function pango_cairo_font_map_new_for_font_type(fonttype: cairo_font_type_t): PPangoFontMap; cdecl;
function pango_cairo_font_map_get_default: PPangoFontMap; cdecl;
procedure pango_cairo_font_map_set_default(fontmap: PPangoCairoFontMap); cdecl;
function pango_cairo_font_map_get_font_type(fontmap: PPangoCairoFontMap): TCairoFontType; cdecl;
procedure pango_cairo_font_map_set_resolution(fontmap: PPangoCairoFontMap; dpi: double); cdecl;
function pango_cairo_font_map_get_resolution(fontmap: PPangoCairoFontMap): double; cdecl;
//#ifndef PANGO_DISABLE_DEPRECATED
function pango_cairo_font_map_create_context(fontmap: PPangoCairoFontMap): PPangoContext; cdecl;
//#endif
(*
* PangoCairoFont
*)
function pango_cairo_font_get_type: Cardinal; cdecl;
function pango_cairo_font_get_scaled_font(font: PPangoCairoFont): PCairoScaledFont; cdecl;
(* Update a Pango context for the current state of a cairo context
*)
procedure pango_cairo_update_context(cr: PCairo; context: PPangoContext); cdecl;
procedure pango_cairo_context_set_font_options(context: PPangoContext; const options: PCairoFontOptions); cdecl;
function pango_cairo_context_get_font_options(context: PPangoContext): PCairoFontOptions; cdecl;
procedure pango_cairo_context_set_resolution(context: PPangoContext; dpi: double); cdecl;
function pango_cairo_context_get_resolution(context: PPangoContext): double; cdecl;
procedure pango_cairo_context_set_shape_renderer(context: PPangoContext; func: PangoCairoShapeRendererFunc; data: Pointer; dnotify: GDestroyNotify); cdecl;
function pango_cairo_context_get_shape_renderer(context: PPangoContext; data: PPointer): PangoCairoShapeRendererFunc; cdecl;
(* Convenience
*)
function pango_cairo_create_context(cr: PCairo): PPangoContext; cdecl;
function pango_cairo_create_layout(cr: PCairo): PPangoLayout; cdecl;
procedure pango_cairo_update_layout(cr: PCairo; layout: PPangoLayout); cdecl;
(*
* Rendering
*)
procedure pango_cairo_show_glyph_string(cr: PCairo; font: PPangoFont; glyphs: PPangoGlyphString); cdecl;
procedure pango_cairo_show_glyph_item(cr: PCairo; const text: PAnsiChar; glyph_item: PPangoGlyphItem); cdecl;
procedure pango_cairo_show_layout_line(cr: PCairo; line: PPangoLayoutLine); cdecl;
procedure pango_cairo_show_layout(cr: PCairo; layout: PPangoLayout); cdecl;
procedure pango_cairo_show_error_underline(cr: PCairo; x: double; y: double; width: double; height: double); cdecl;
(*
* Rendering to a path
*)
procedure pango_cairo_glyph_string_path(cr: PCairo; font: PPangoFont; glyphs: PPangoGlyphString); cdecl;
procedure pango_cairo_layout_line_path(cr: PCairo; line: PPangoLayoutLine); cdecl;
procedure pango_cairo_layout_path(cr: PCairo; layout: PPangoLayout); cdecl;
procedure pango_cairo_error_underline_path(cr: PCairo; x: double; y: double; width: double; height: double); cdecl;
implementation
const
PANGO_CAIRO_LIB = 'libpangocairo-1.0-0.dll';
function pango_cairo_font_map_get_type: Cardinal; cdecl; external PANGO_CAIRO_LIB;
function pango_cairo_font_map_new: PPangoFontMap; cdecl; external PANGO_CAIRO_LIB;
function pango_cairo_font_map_new_for_font_type(fonttype: cairo_font_type_t): PPangoFontMap; cdecl; external PANGO_CAIRO_LIB;
function pango_cairo_font_map_get_default: PPangoFontMap; cdecl; external PANGO_CAIRO_LIB;
procedure pango_cairo_font_map_set_default(fontmap: PPangoCairoFontMap); cdecl; external PANGO_CAIRO_LIB;
function pango_cairo_font_map_get_font_type(fontmap: PPangoCairoFontMap): TCairoFontType; cdecl; external PANGO_CAIRO_LIB;
procedure pango_cairo_font_map_set_resolution(fontmap: PPangoCairoFontMap; dpi: double); cdecl; external PANGO_CAIRO_LIB;
function pango_cairo_font_map_get_resolution(fontmap: PPangoCairoFontMap): double; cdecl; external PANGO_CAIRO_LIB;
function pango_cairo_font_map_create_context(fontmap: PPangoCairoFontMap): PPangoContext; cdecl; external PANGO_CAIRO_LIB;
function pango_cairo_font_get_type: Cardinal; cdecl; external PANGO_CAIRO_LIB;
function pango_cairo_font_get_scaled_font(font: PPangoCairoFont): PCairoScaledFont; cdecl; external PANGO_CAIRO_LIB;
procedure pango_cairo_update_context(cr: PCairo; context: PPangoContext); cdecl; external PANGO_CAIRO_LIB;
procedure pango_cairo_context_set_font_options(context: PPangoContext; const options: PCairoFontOptions); cdecl; external PANGO_CAIRO_LIB;
function pango_cairo_context_get_font_options(context: PPangoContext): PCairoFontOptions; cdecl; external PANGO_CAIRO_LIB;
procedure pango_cairo_context_set_resolution(context: PPangoContext; dpi: double); cdecl; external PANGO_CAIRO_LIB;
function pango_cairo_context_get_resolution(context: PPangoContext): double; cdecl; external PANGO_CAIRO_LIB;
procedure pango_cairo_context_set_shape_renderer(context: PPangoContext; func: PangoCairoShapeRendererFunc; data: Pointer; dnotify: GDestroyNotify); cdecl; external PANGO_CAIRO_LIB;
function pango_cairo_context_get_shape_renderer(context: PPangoContext; data: PPointer): PangoCairoShapeRendererFunc; cdecl; external PANGO_CAIRO_LIB;
function pango_cairo_create_context(cr: PCairo): PPangoContext; cdecl; external PANGO_CAIRO_LIB;
function pango_cairo_create_layout(cr: PCairo): PPangoLayout; cdecl; external PANGO_CAIRO_LIB;
procedure pango_cairo_update_layout(cr: PCairo; layout: PPangoLayout); cdecl; external PANGO_CAIRO_LIB;
procedure pango_cairo_show_glyph_string(cr: PCairo; font: PPangoFont; glyphs: PPangoGlyphString); cdecl; external PANGO_CAIRO_LIB;
procedure pango_cairo_show_glyph_item(cr: PCairo; const text: PAnsiChar; glyph_item: PPangoGlyphItem); cdecl; external PANGO_CAIRO_LIB;
procedure pango_cairo_show_layout_line(cr: PCairo; line: PPangoLayoutLine); cdecl; external PANGO_CAIRO_LIB;
procedure pango_cairo_show_layout(cr: PCairo; layout: PPangoLayout); cdecl; external PANGO_CAIRO_LIB;
procedure pango_cairo_show_error_underline(cr: PCairo; x: double; y: double; width: double; height: double); cdecl; external PANGO_CAIRO_LIB;
procedure pango_cairo_glyph_string_path(cr: PCairo; font: PPangoFont; glyphs: PPangoGlyphString); cdecl; external PANGO_CAIRO_LIB;
procedure pango_cairo_layout_line_path(cr: PCairo; line: PPangoLayoutLine); cdecl; external PANGO_CAIRO_LIB;
procedure pango_cairo_layout_path(cr: PCairo; layout: PPangoLayout); cdecl; external PANGO_CAIRO_LIB;
procedure pango_cairo_error_underline_path(cr: PCairo; x: double; y: double; width: double; height: double); cdecl; external PANGO_CAIRO_LIB;
end. |
unit Nullpobug.Example.Spring4d.ServiceLocator;
interface
uses
Spring.Container
;
function ServiceLocator: TContainer;
implementation
var
FContainer: TContainer;
function ServiceLocator: TContainer;
begin
if FContainer = nil then
begin
FContainer := TContainer.Create;
end;
Result := FContainer;
end;
initialization
finalization
FContainer.Free;
end.
|
unit Invoice.Controller.Interfaces;
interface
uses Vcl.ComCtrls, Vcl.ActnList, System.Classes, Data.DB, SHDocVw, Invoice.Model.Interfaces;
type
iControllerIniFileDefault = interface;
iControllerWinInfoDefault = interface;
iControllerAppInfoDefault = interface;
iControllerTabFormDefault = interface;
iControllerSecurityDefault = interface;
iModelConnectionParametros = interface;
iModelConnection = interface
['{E8538D27-DFF2-4485-A303-616176681A93}']
function Connection: TCustomConnection;
function Parametros: iModelConnectionParametros;
end;
iModelConnectionParametros = interface
['{69BA62BF-43C2-495B-8E0B-C5B6D509FFCB}']
function DriverID(Value: String): iModelConnectionParametros;
function Server(Value: String): iModelConnectionParametros;
function Porta(Value: Integer): iModelConnectionParametros;
function Database(Value: String): iModelConnectionParametros;
function UserName(Value: String): iModelConnectionParametros;
function Password(Value: String): iModelConnectionParametros;
function EndParametros: iModelConnection;
end;
iModelConnectionFactory = interface
['{20983058-4995-49E6-86B8-F638E5C05743}']
function ConnectionFiredac : iModelConnection;
end;
iEntity = interface
['{976C5307-B7E8-4C8B-B283-D24DB4ED11F0}']
function List: iEntity;
function ListWhere(aSQL: String): iEntity;
function DataSet: TDataSet;
function OrderBy(aFieldName: String): iEntity;
end;
iModelEntityFactory = interface
['{0A4C9901-4FEB-4277-A62B-444457C251DE}']
function User(Connection: iModelConnection): iEntity;
function Product(Connection: iModelConnection): iEntity;
function TypePayment(Connection: iModelConnection): iEntity;
function Customer(Connection: iModelConnection): iEntity;
end;
iModelTableFactory = interface
['{5C7FAC45-B671-4897-B18F-CCAE970B8885}']
function Table(Connection: iModelConnection): iTable;
end;
iModelQueryFactory = interface
['{8E2C37DF-507C-4539-88B4-75B093774BDA}']
function Query(Connection: iModelConnection): iQuery;
end;
iControllerIniFileFactory = interface
['{353DEFB6-3AF0-44D0-84EB-D520E664417E}']
function Default: iControllerIniFileDefault;
end;
iControllerIniFileDefault = interface
['{A69FADDB-ACE2-4D43-AC05-B4A7E0054AA8}']
function InputKey(Sector: String; Key: String; Value: String; IsCrypt: Boolean): String;
end;
iControllerWinInfoFactory = interface
['{8E4644BB-0F10-4F8D-B01A-896E3DC3F1D3}']
function Default: iControllerWinInfoDefault;
end;
iControllerWinInfoDefault = interface
['{C6FF4BD0-606C-4B7E-A4AE-C263868DAF86}']
function UserName: String;
function ComputerName: String;
end;
iControllerAppInfoFactory = interface
['{F69EB5A1-57B8-4144-94C0-94DAFA900551}']
function Default: iControllerAppInfoDefault;
end;
iControllerAppInfoDefault = interface
['{DF23FDBC-7819-4A0E-B4E2-2289313CFB28}']
function CompanyName: String;
function FileDescription: String;
function FileVersion: String;
function InternalName: String;
function LegalCopyright: String;
function LegalTradeMarks: String;
function OriginalFilename: String;
function ProductName: String;
function ProductVersion: String;
function Comments: String;
end;
iControllerChartDefault = interface
['{E68D2823-79B8-42F7-8455-B87FD5598C03}']
function SetCharTitle(aValue: String): iControllerChartDefault;
function SetCharSubTitle(aValue: String): iControllerChartDefault;
function AddTitle(aDescription, aValue: String): iControllerChartDefault;
function AddValue(aDescription, aValue: String): iControllerChartDefault;
procedure ShowChart(aWebBrowser: TWebBrowser);
end;
iControllerChartFactory = interface
['{599B5323-71FF-46A5-9473-FF934913AD48}']
function Default: iControllerChartDefault;
end;
iControllerTabFormFactory = interface
['{94895871-5E89-4FF0-8D18-F893C59FF869}']
function Default: iControllerTabFormDefault;
end;
iControllerTabFormDefault = interface
['{E75A0D8A-5BC5-44A9-AE4A-45ED9E9D3324}']
function CreateTab(aAction: TAction; aPageControl: TPageControl): TTabSheet;
procedure ShowForm(aTabSheet: TTabSheet; NameForm: String);
end;
iControllerSecurityFactory = interface
['{F4D1C694-628D-4691-BFF8-83DE765F47F5}']
function Default: iControllerSecurityDefault;
end;
iControllerSecurityDefault = interface
['{5B1DA1D8-DF07-4627-9CFE-0B4F68CDA640}']
function Login(aUsername, aPasswood: String): Integer;
function ShowLog: TStrings;
function AddLog(aLog: String): iControllerSecurityDefault;
function EnCrypt(InString: String): String;
function DeCrypt(InString: String): String;
end;
iControllerEntityFactory = interface
['{1695B22D-2EA4-4471-B1AA-D8F567588881}']
function Default: iModelEntityFactory;
end;
iControllerModelFacade = interface
['{A5B19DB6-9347-4332-BFCA-A07AE1C7D0BD}']
function AppInfoFactory: iControllerAppInfoFactory;
function IniFileFactory: iControllerIniFileFactory;
function SecurityFactory: iControllerSecurityFactory;
function TabFormFactory: iControllerTabFormFactory;
function ChartFactory: iControllerChartFactory;
function WinInfoFactory: iControllerWinInfoFactory;
function EntityFactory: iModelEntityFactory;
end;
implementation
end.
|
{ ZADANIE 2
* Vytvorte program, ktorý prevedie dvojkové číslo na desiatkové.
* Výsledok porovnajte pomocou zápisu prevodu cez formátovací znak %.
* }
program BinToDec;
uses crt, sysutils, Math;
var binarneCislo, cifra: String;
dlzkaVstupu, i, jednoCislo: integer;
vysledok: float; {vysledok po intpower(a,x) musi byt v float alebo real}
//znak: char;
spravneCislo: boolean;
begin
clrscr;
repeat {cyklus na kontrolu vstupu}
spravneCislo := true;
write('Zadaj binarne cislo: ');
readln(binarneCislo);
dlzkaVstupu := length(binarneCislo); {zistenie dlzky vstupu (vstupneho bin cisla v retazci)}
for i := 1 to dlzkaVstupu do {cyklus sa vykona prave tolkokrat kolko znakov na retazec}
begin
//cifra := (Copy(binarneCislo, (dlzkaVstupu - i + 1), 1)); {vyber 1 pismena z retazca}
cifra:= (binarneCislo[dlzkaVstupu - i + 1]); {iny zapis predchadzajuceho riadku}
if (cifra <> '1') and (cifra <> '0') then spravneCislo := false; {kontrola vstupu - resp. kontrola vybraneho pismena}
//if (ord(znak) <> 48) and (ord(znak) <> 49) then spravneCislo := false; {iny zapis predchadzajuceho riadku}
end;
if not spravneCislo then {ak sa zistil nespravny vstup, tak vypise chybu a bude nacitavat este raz}
//if spravneCislo = false then {iny zapis predchadzajuceho riadku, no lespie je pisat s NOT}
begin
clrscr;
writeln('NESPRAVNY VSTUP');
end;
until spravneCislo; {opakuje az kym nie je zadany spravny vstup}
vysledok := 0;
for i := 1 to dlzkaVstupu do {cyklus sa vykona prave tolkokrat kolko znakov na retazec}
begin
cifra := (Copy(binarneCislo, (dlzkaVstupu - i + 1), 1)); {moze byt zapisane tak isto ako v riadku 28}
jednoCislo := StrToInt(cifra); {StrToInt prevedie String do Integer-u (v kniznici Sysutils)}
vysledok := (vysledok + (jednoCislo * intpower(2, (i - 1)))); {zakazdym pripocita k vysledku prisluchajucu macninu 2-ky vynasobenu prisluchajucim cislom (jednoCislo)} {intpower(zaklad mocniny, exponent) - v kniznici Math}
end;
clrscr;
writeln('Binarne cislo: ', binarneCislo);
writeln('Decimalne cislo: ', vysledok:1:0);
readln;
end.
|
{ ******************************************************* }
{ *
{* uTVDBSeries.pas
{* Delphi Implementation of the Class TVDBSeries
{* Generated by Enterprise Architect
{* Created on: 09-févr.-2015 11:43:46
{* Original author: bvidovic OK
{*
{******************************************************* }
unit xmltvdb.TVDBSeries;
interface
uses
System.Generics.Collections, System.Classes;
type
ITVDBSeries= interface['{19AADF49-9842-4F1A-8395-4081F05BD59B}']
function equals(const o: ITVDBSeries): boolean;
function GetseriesId: String;
function GetseriesName: String;
function GetseriesYear: String;
procedure SetseriesId(const Value: String);
procedure SetseriesName(const Value: String);
procedure SetseriesYear(const Value: String);
procedure Assign(valeurs:ITVDBSeries);
function hashCode: Integer;
function toString: String;
end;
TTVDBSeries = class(TInterfacedObject,ITVDBSeries)
strict private
FseriesId: String;
FseriesName: String;
FseriesYear: String;
private
public
function equals(const o: ITVDBSeries): boolean; reintroduce;
function GetseriesId: String;
function GetseriesName: String;
function GetseriesYear: String;
procedure SetseriesId(const Value: String);
procedure SetseriesName(const Value: String);
procedure SetseriesYear(const Value: String);
function hashCode: Integer;
function toString: String; reintroduce;
procedure Assign(valeurs:ITVDBSeries);
constructor Create(const seriesId: String; const seriesName: String;const seriesYear: String); overload;
constructor Create(const seriesId: String); overload;
destructor Destroy; override;
end;
TTVDBSeriesColl = Class(TList<ITVDBSeries>)
public
constructor Create; overload;
destructor Destroy; override;
End;
implementation
uses
System.SysUtils;
{ implementation of TVDBSeries }
constructor TTVDBSeries.Create(const seriesId, seriesName, seriesYear: String);
begin
inherited Create;
Self.FseriesId := seriesId;
Self.FseriesName := seriesName;
Self.FseriesYear := seriesYear;
end;
procedure TTVDBSeries.Assign(valeurs: ITVDBSeries);
begin
Self.FseriesId := valeurs.GetseriesId;
Self.FseriesName := valeurs.GetseriesName;
Self.FseriesYear := valeurs.GetseriesYear;
end;
constructor TTVDBSeries.Create(const seriesId: String);
begin
inherited Create;
Self.FseriesId := seriesId;
end;
destructor TTVDBSeries.Destroy;
begin
inherited Destroy;
end;
function TTVDBSeries.equals(const o: ITVDBSeries): boolean;
//var
// otherSeries: TTVDBSeries;
begin
//otherSeries := o;
if (Self.FseriesId = '') then
begin
Result := (o.GetseriesId = '');
end
else
begin
Result := SameText(Self.GetseriesId, o.GetseriesId);
end;
end;
function TTVDBSeries.GetseriesId: String;
begin
REsult := FseriesId;
end;
function TTVDBSeries.GetseriesName: String;
begin
Result := FseriesName
end;
function TTVDBSeries.GetseriesYear: String;
begin
Result:= FseriesYear;
end;
function TTVDBSeries.hashCode: Integer;
var
hash: Integer;
begin
hash := 3;
hash := 97 * hash + Self.GetseriesId.GetHashCode; // Objects.hashCode(this.seriesId);
Result := hash;
end;
procedure TTVDBSeries.SetseriesId(const Value: String);
begin
FseriesId := Value;
end;
procedure TTVDBSeries.SetseriesName(const Value: String);
begin
FseriesName := Value;
end;
procedure TTVDBSeries.SetseriesYear(const Value: String);
begin
FseriesYear := Value;
end;
function TTVDBSeries.toString: String;
begin
Result := 'tvdbid: ' + GetseriesId + ', seriesName: ' + GetseriesName + ', seriesYear: ' + GetseriesYear;
end;
{ TTVDBSeriesColl }
constructor TTVDBSeriesColl.Create;
begin
inherited Create;
// Self.OwnsObjects := true;
end;
destructor TTVDBSeriesColl.Destroy;
begin
inherited;
end;
end.
|
//=============================================================================
// sgDrawingOptions.pas
//=============================================================================
//
// The drawing options provides a flexible means of providing different drawing
// features, without needing many different overloads of each function or
// procedure.
//
// Drawing Options can be composed to provide a range of different features
// including:
// - Drawing onto another Bitmap, rather than the screen
// - Scaling the drawing
// - Rotation
// - Flipping X and/or Y
// - Drawing part of a bitmap
// - Drawing to the World or Screen
//
/// DrawingOptions allows you to provide various options (such as scaling,
/// rotation, and drawing on to a bitmap) for SwinGame's drawing operations.
///
/// The one DrawingOption value can contain a number of different options.
///
/// @module DrawingOptionsConfiguration
/// @static
///
/// @doc_types DrawingOptions
unit sgDrawingOptions;
interface
uses sgTypes;
/// Returns a DrawingOptions with default values.
///
/// @lib
function OptionDefaults(): DrawingOptions;
/// Use this option to draw to a Bitmap. Pass dest the Bitmap you want to draw on.
///
/// @lib OptionDrawToBitmap
function OptionDrawTo(dest: Bitmap): DrawingOptions;
/// Use this option to draw to a Bitmap. Pass dest the Bitmap you want to draw on.
/// Pass opts the other options you want use.
///
/// @lib OptionDrawToBitmapOpts
/// @sn optionDrawToBitmap:%s withOptions:%s
function OptionDrawTo(dest: Bitmap; const opts: DrawingOptions): DrawingOptions;
/// Use this option to draw to a specified Window. Pass dest the Window you want to draw on.
///
/// @lib OptionDrawToWindow
function OptionDrawTo(dest: Window): DrawingOptions;
/// Use this option to draw to a Bitmap. Pass dest the Bitmap you want to draw on to.
/// Pass opts the other options you want use.
///
/// @lib OptionDrawToWindowOpts
/// @sn optionDrawToWindow:%s withOptions:%s
function OptionDrawTo(dest: Window; const opts: DrawingOptions): DrawingOptions;
/// Use this option to scale the drawing of bitmaps. You can scale x and y separately.
///
/// @lib
function OptionScaleBmp(scaleX, scaleY: Single): DrawingOptions;
/// Use this option to scale the drawing of bitmaps. You can scale x and y separately.
/// Pass opts the other options you want use.
///
/// @lib OptionScaleBmpOpts
function OptionScaleBmp(scaleX, scaleY: Single; const opts: DrawingOptions): DrawingOptions;
/// Use this option to rotate the drawing of a bitmap. This allows you to set the
/// anchor point and rotate around that by a number of degrees.
///
/// @lib
function OptionRotateBmp(angle, anchorX, anchorY: Single): DrawingOptions;
/// Use this option to rotate the drawing of a bitmap. This allows you to set the
/// anchor point and rotate around that by a number of degrees.
/// Pass opts the other options you want use.
///
/// @lib OptionRotateBmpOpts
function OptionRotateBmp(angle, anchorX, anchorY: Single; const opts: DrawingOptions): DrawingOptions;
/// Use this option to rotate a bitmap around its centre point.
///
/// @lib OptionRotateBmpAngleOpts
function OptionRotateBmp(angle: Single; const opts: DrawingOptions): DrawingOptions;
/// Use this option to rotate a bitmap around its centre point.
/// Pass opts the other options you want use.
///
/// @lib OptionRotateBmpAngle
function OptionRotateBmp(angle: Single): DrawingOptions;
/// Use this option to flip an image along its X axis.
///
/// @lib
function OptionFlipX(): DrawingOptions;
/// Use this option to flip an image along its X axis.
/// Pass opts the other options you want use.
///
/// @lib OptionFlipXOpts
function OptionFlipX(const opts: DrawingOptions): DrawingOptions;
/// Use this option to flip the drawing of an image along its Y axis.
///
/// @lib
function OptionFlipY(): DrawingOptions;
/// Use this option to flip the drawing of an image along its Y axis.
/// Pass opts the other options you want use.
///
/// @lib OptionFlipYOpts
function OptionFlipY(const opts: DrawingOptions): DrawingOptions;
/// Use this option to flow the drawing of an image along both X and Y axis.
///
/// @lib
function OptionFlipXY(): DrawingOptions;
/// Use this option to flow the drawing of an image along both X and Y axis.
/// Pass opts the other options you want use.
///
/// @lib OptionFlipXYOpts
function OptionFlipXY(const opts: DrawingOptions): DrawingOptions;
/// Use this option to draw only a part of a bitmap.
///
/// @lib
function OptionPartBmp(x, y, w, h: Single): DrawingOptions;
/// Use this option to draw only a part of a bitmap.
/// Pass opts the other options you want use.
///
/// @lib OptionPartBmpOpts
function OptionPartBmp(x, y, w, h: Single; const opts: DrawingOptions): DrawingOptions;
/// Use this option to draw only part of a bitmap.
///
/// @lib OptionPartBmpRect
function OptionPartBmp(const part: Rectangle): DrawingOptions;
/// Use this option to draw only part of a bitmap.
/// Pass opts the other options you want use.
///
/// @lib OptionPartBmpRectOpts
function OptionPartBmp(const part: Rectangle; const opts: DrawingOptions): DrawingOptions;
/// Use this option to draw in World coordinates -- these are affected by the movement of the camera.
///
/// @lib
function OptionToWorld(): DrawingOptions;
/// Use this option to draw in World coordinates -- these are affected by the movement of the camera.
/// Pass opts the other options you want use.
///
/// @lib OptionToWorldOpts
function OptionToWorld(const opts: DrawingOptions): DrawingOptions;
/// Use this option to draw to the screen, ignoring the positon of the camera.
///
/// @lib
function OptionToScreen(): DrawingOptions;
/// Use this option to draw to the screen, ignoring the positon of the camera.
/// Pass opts the other options you want use.
///
/// @lib OptionToScreenOpts
function OptionToScreen(const opts: DrawingOptions): DrawingOptions;
/// Use this option to change the width of line drawings.
///
/// @lib
function OptionLineWidth(width: Longint): DrawingOptions;
/// Use this option to change the width of line drawings.
///
/// @lib OptionLineWidthOpts
function OptionLineWidth(width: Longint; const opts: DrawingOptions): DrawingOptions;
implementation
uses sgShared, sgGeometry;
function OptionDefaults(): DrawingOptions;
begin
with result do
begin
dest := _CurrentWindow;
scaleX := 1;
scaleY := 1;
angle := 0;
anchorOffsetX := 0;
anchorOffsetY := 0;
flipX := false;
flipY := false;
isPart := false;
part := RectangleFrom(0,0,1,1);
camera := DrawDefault;
lineWidth := 1;
end;
end;
function OptionDrawTo(dest: Bitmap): DrawingOptions;
begin
result := OptionDrawTo(dest, OptionDefaults());
end;
function OptionDrawTo(dest: Bitmap; const opts: DrawingOptions): DrawingOptions;
begin
result := opts;
result.dest := dest;
end;
function OptionDrawTo(dest: Window): DrawingOptions;
begin
result := OptionDrawTo(dest, OptionDefaults());
end;
function OptionDrawTo(dest: Window; const opts: DrawingOptions): DrawingOptions;
begin
result := opts;
result.dest := dest;
end;
function OptionLineWidth(width: Longint): DrawingOptions;
begin
result := OptionLineWidth(width, OptionDefaults());
end;
function OptionLineWidth(width: Longint; const opts: DrawingOptions): DrawingOptions;
begin
result := opts;
result.lineWidth := width;
end;
function OptionScaleBmp(scaleX, scaleY: Single): DrawingOptions;
begin
result := OptionScaleBmp(scaleX, scaleY, OptionDefaults());
end;
function OptionScaleBmp(scaleX, scaleY: Single; const opts: DrawingOptions): DrawingOptions;
begin
result := opts;
result.scaleX := opts.scaleX * scaleX;
result.scaleY := opts.scaleY * scaleY;
end;
function OptionRotateBmp(angle, anchorX, anchorY : Single) : DrawingOptions;
begin
result := OptionRotateBmp(angle, anchorX, anchorY, OptionDefaults());
end;
function OptionRotateBmp(angle, anchorX, anchorY : Single; const opts : DrawingOptions) : DrawingOptions;
begin
result := opts;
result.angle += angle;
result.anchoroffsetX := anchorX;
result.anchoroffsetY := anchorY;
end;
function OptionRotateBmp(angle : Single) : DrawingOptions;
begin
result := OptionRotateBmp(angle, 0, 0, OptionDefaults());
end;
function OptionRotateBmp(angle : Single; const opts : DrawingOptions) : DrawingOptions;
begin
result := OptionRotateBmp(angle, 0, 0, opts);
end;
function OptionFlipX() : DrawingOptions;
begin
result := OptionFlipX(OptionDefaults());
end;
function OptionFlipX(const opts : DrawingOptions) : DrawingOptions;
begin
result := opts;
result.flipX := not result.flipX;
end;
function OptionFlipY() : DrawingOptions;
begin
result := OptionFlipY(OptionDefaults());
end;
function OptionFlipY(const opts : DrawingOptions) : DrawingOptions;
begin
result := opts;
result.flipY := not result.flipY;
end;
function OptionFlipXY() : DrawingOptions;
begin
result := OptionFlipXY(OptionDefaults());
end;
function OptionFlipXY(const opts : DrawingOptions) : DrawingOptions;
begin
result := opts;
result.flipY := not result.flipY;
result.flipX := not result.flipX;
end;
function OptionPartBmp(x, y, w, h : Single) : DrawingOptions;
begin
result := OptionPartBmp(x, y, w, h, OptionDefaults());
end;
function OptionPartBmp(x, y, w, h : Single; const opts : DrawingOptions) : DrawingOptions;
begin
result := opts;
result.isPart := true;
result.part.x := x;
result.part.y := y;
result.part.width := w;
result.part.height := h;
end;
function OptionPartBmp(const part: Rectangle): DrawingOptions;
begin
result := OptionPartBmp(part, OptionDefaults());
end;
function OptionPartBmp(const part: Rectangle; const opts : DrawingOptions) : DrawingOptions;
begin
result := opts;
result.isPart := true;
result.part := part;
end;
function OptionToWorld() : DrawingOptions;
begin
result := OptionToWorld(OptionDefaults());
end;
function OptionToWorld(const opts : DrawingOptions) : DrawingOptions;
begin
result := opts;
result.camera := DrawToWorld;
end;
function OptionToScreen() : DrawingOptions;
begin
result := OptionToScreen(OptionDefaults());
end;
function OptionToScreen(const opts : DrawingOptions) : DrawingOptions;
begin
result := opts;
result.camera := DrawToScreen;
end;
end. |
unit DebugTools;
interface
uses
Windows, Classes, SysUtils;
procedure SetDebugStr(AMsg:string);
function GetDebugStr:string;
procedure Trace(const AMsg:string);
implementation
var
DebugStr : string = ''; // TODO: 스레드 세이프하도록 변경
procedure SetDebugStr(AMsg:string);
begin
DebugStr := AMsg;
end;
function GetDebugStr:string;
begin
Result := DebugStr;
end;
procedure Trace(const AMsg:string);
begin
// DebugView에서 필터링하기 위해서 테그를 붙여 둠
OutputDebugString(PChar('[MW] ' + AMsg));
end;
end.
|
(* ================================================================
Adapted to use Scanlines.pas (pointers to Scanline[]).
Chris Willig Sep 2003
chris@5thelephant.com
All routines are unchanged from original, other than cleaning
up the formatting and adapting to use pointers of course.
================================================================ *)
unit ScanlinesFX;
interface
uses
Windows, SysUtils, Classes, Graphics, Math;
{ **************************************************************************
Procedures taken/adapted from component:
TProEffectImage Version 1.0 (FREEWARE)
Written By Babak Sateli
babak_sateli@yahoo.com
http://raveland.netfirms.com
Special thanks to Jan Verhoeven.
************************************************************************ }
Procedure Effect_Invert (SrcBmp: TBitmap);
Procedure Effect_AddColorNoise (SrcBmp: TBitmap; Amount:Integer);
Procedure Effect_AddMonoNoise (SrcBmp: TBitmap; Amount:Integer);
Procedure Effect_AntiAlias (SrcBmp: TBitmap);
Procedure Effect_Contrast (SrcBmp: TBitmap; Amount:Integer);
Procedure Effect_FishEye (SrcBmp: TBitmap; Amount:Integer);
Procedure Effect_GrayScale (SrcBmp: TBitmap);
Procedure Effect_Lightness (SrcBmp: TBitmap; Amount:Integer);
Procedure Effect_Darkness (SrcBmp: TBitmap; Amount:Integer);
Procedure Effect_Saturation (SrcBmp: TBitmap; Amount:Integer);
Procedure Effect_SplitBlur (SrcBmp: TBitmap; Amount:Integer);
Procedure Effect_GaussianBlur (SrcBmp: TBitmap; Amount:Integer);
Procedure Effect_Mosaic (SrcBmp: TBitmap; Size:Integer);
Procedure Effect_Twist (SrcBmp: TBitmap; Amount:Integer);
procedure Effect_Splitlight (SrcBmp: TBitmap; Amount:integer);
Procedure Effect_Tile (SrcBmp: TBitmap; Amount: integer);
Procedure Effect_SpotLight (SrcBmp: TBitmap; Amount: integer; Spot: TRect);
Procedure Effect_Trace (SrcBmp: TBitmap; Amount: integer);
Procedure Effect_Emboss (SrcBmp: TBitmap);
Procedure Effect_Solorize (SrcBmp: TBitmap; Amount: integer);
Procedure Effect_Posterize (SrcBmp: TBitmap; Amount: integer);
procedure Effect_SmoothResize (SrcBmp: TBitmap; NuWidth, NuHeight: integer);
procedure Effect_SmoothRotate (SrcBmp: TBitmap; cx, cy: Integer; Angle: Extended);
//**************************************************************************
procedure FishEye(var Bmp, Dst: TBitmap; Amount: Extended);
procedure Twist(var Bmp, Dst: TBitmap; Amount: integer);
procedure Emboss(var Bmp:TBitmap);
procedure AntiAlias(clip: tbitmap);
procedure SmoothRotate(var Src, Dst: TBitmap; cx, cy: Integer; Angle: Extended);
implementation
uses
Scanlines;
{$R-}
function Max(Int1, Int2: integer): integer;
begin
if Int1 > Int2 then result := Int1
else result := Int2;
end;
function Min(Int1, Int2: integer): integer;
begin
if Int1 < Int2 then result := Int1
else result := Int2;
end;
procedure PicInvert(src: tbitmap);
var
w, h, x, y : integer;
p : pbytearray;
SL : TScanlines;
begin
w := src.width;
h := src.height;
src.PixelFormat := pf24bit;
SL := TScanlines.Create(Src);
try
for y := 0 to h-1 do begin
//p:=src.scanline[y];
p := PByteArray(SL[y]);
for x:=0 to w-1 do begin
p[x*3] := not p[x*3];
p[x*3+1] := not p[x*3+1];
p[x*3+2] := not p[x*3+2];
end;
end;
finally
SL.Free;
end;
end;
function IntToByte(i:Integer):Byte;
begin
if i > 255 then
Result := 255
else
if i < 0 then
Result := 0
else
Result := i;
end;
procedure AddColorNoise(var clip: tbitmap; Amount: Integer);
var
p0 : pbytearray;
x, y, r, g, b : Integer;
SL : TScanLines;
begin
SL := TScanLines.Create(clip);
try
for y := 0 to clip.Height-1 do begin
//p0 := clip.ScanLine [y];
p0 := PByteArray(SL[y]);
for x := 0 to clip.Width-1 do
begin
r := p0[x*3]+(Random(Amount)-(Amount shr 1));
g := p0[x*3+1]+(Random(Amount)-(Amount shr 1));
b := p0[x*3+2]+(Random(Amount)-(Amount shr 1));
p0[x*3] := IntToByte(r);
p0[x*3+1] := IntToByte(g);
p0[x*3+2] := IntToByte(b);
end;
end;
finally
SL.Free;
end;
end;
procedure AddMonoNoise(var clip: tbitmap; Amount: Integer);
var
p0 : pbytearray;
x, y, a, r, g, b : Integer;
SL : TScanLines;
begin
SL := TScanlines.Create(clip);
try
for y := 0 to clip.Height-1 do begin
//p0 := clip.scanline[y];
p0 := PByteArray(SL[y]);
for x := 0 to clip.Width-1 do begin
a := Random(Amount)-(Amount shr 1);
r := p0[x*3]+a;
g := p0[x*3+1]+a;
b := p0[x*3+2]+a;
p0[x*3] := IntToByte(r);
p0[x*3+1] := IntToByte(g);
p0[x*3+2] := IntToByte(b);
end;
end;
finally
SL.Free;
end;
end;
procedure AntiAliasRect(clip: tbitmap; XOrigin, YOrigin, XFinal, YFinal: Integer);
var
Memo, x, y : Integer; (* Composantes primaires des points environnants *)
p0, p1, p2 : pbytearray;
SL : TScanlines;
begin
if XFinal<XOrigin then begin Memo := XOrigin; XOrigin := XFinal; XFinal := Memo; end; (* Inversion des valeurs *)
if YFinal<YOrigin then begin Memo := YOrigin; YOrigin := YFinal; YFinal := Memo; end; (* si diff,rence n,gative*)
XOrigin := max(1,XOrigin);
YOrigin := max(1,YOrigin);
XFinal := min(clip.width-2,XFinal);
YFinal := min(clip.height-2,YFinal);
clip.PixelFormat := pf24bit;
SL := TScanlines.Create(clip);
try
for y := YOrigin to YFinal do begin
//p0 := clip.ScanLine [y-1];
//p1 := clip.scanline [y];
//p2 := clip.ScanLine [y+1];
p0 := PByteArray(SL[y-1]);
p1 := PByteArray(SL[y]);
p2 := PByteArray(SL[y+1]);
for x := XOrigin to XFinal do begin
p1[x*3] := (p0[x*3]+p2[x*3]+p1[(x-1)*3]+p1[(x+1)*3])div 4;
p1[x*3+1] := (p0[x*3+1]+p2[x*3+1]+p1[(x-1)*3+1]+p1[(x+1)*3+1])div 4;
p1[x*3+2] := (p0[x*3+2]+p2[x*3+2]+p1[(x-1)*3+2]+p1[(x+1)*3+2])div 4;
end;
end;
finally
SL.Free;
end;
end;
procedure AntiAlias(clip: tbitmap);
begin
AntiAliasRect(clip, 0, 0, clip.width, clip.height);
end;
procedure Contrast(var clip: tbitmap; Amount: Integer);
var
p0 : pbytearray;
rg, gg, bg, r, g, b, x, y : Integer;
SL : TScanLines;
begin
SL := TScanlines.Create(clip);
try
for y := 0 to clip.Height-1 do begin
//p0 := clip.scanline[y];
p0 := PByteArray(SL[y]);
for x := 0 to clip.Width-1 do begin
r := p0[x*3];
g := p0[x*3+1];
b := p0[x*3+2];
rg := (Abs(127-r)*Amount)div 255;
gg := (Abs(127-g)*Amount)div 255;
bg := (Abs(127-b)*Amount)div 255;
if r>127 then r := r+rg else r := r-rg;
if g>127 then g := g+gg else g := g-gg;
if b>127 then b := b+bg else b := b-bg;
p0[x*3] := IntToByte(r);
p0[x*3+1] := IntToByte(g);
p0[x*3+2] := IntToByte(b);
end;
end;
finally
SL.Free;
end;
end;
procedure FishEye(var Bmp, Dst: TBitmap; Amount: Extended);
var
xmid, ymid : Single;
fx, fy : Single;
r1, r2 : Single;
ifx, ify : integer;
dx, dy : Single;
rmax : Single;
ty, tx : Integer;
weight_x, weight_y : array[0..1] of Single;
weight : Single;
new_red, new_green : Integer;
new_blue : Integer;
total_red, total_green : Single;
total_blue : Single;
ix, iy : Integer;
sli, slo : PByteArray;
SL1, SL2 : TScanlines;
begin
xmid := Bmp.Width/2;
ymid := Bmp.Height/2;
rmax := Dst.Width * Amount;
SL1 := TScanlines.Create(Bmp);
SL2 := TScanlines.Create(Dst);
try
for ty := 0 to Dst.Height - 1 do begin
for tx := 0 to Dst.Width - 1 do begin
dx := tx - xmid;
dy := ty - ymid;
r1 := Sqrt(dx * dx + dy * dy);
if r1 = 0 then begin
fx := xmid;
fy := ymid;
end else begin
r2 := rmax / 2 * (1 / (1 - r1/rmax) - 1);
fx := dx * r2 / r1 + xmid;
fy := dy * r2 / r1 + ymid;
end;
ify := Trunc(fy);
ifx := Trunc(fx);
// Calculate the weights.
if fy >= 0 then begin
weight_y[1] := fy - ify;
weight_y[0] := 1 - weight_y[1];
end else begin
weight_y[0] := -(fy - ify);
weight_y[1] := 1 - weight_y[0];
end;
if fx >= 0 then begin
weight_x[1] := fx - ifx;
weight_x[0] := 1 - weight_x[1];
end else begin
weight_x[0] := -(fx - ifx);
Weight_x[1] := 1 - weight_x[0];
end;
if ifx < 0 then
ifx := Bmp.Width-1-(-ifx mod Bmp.Width)
else
if ifx > Bmp.Width-1 then
ifx := ifx mod Bmp.Width;
if ify < 0 then
ify := Bmp.Height-1-(-ify mod Bmp.Height)
else
if ify > Bmp.Height-1 then
ify := ify mod Bmp.Height;
total_red := 0.0;
total_green := 0.0;
total_blue := 0.0;
for ix := 0 to 1 do begin
for iy := 0 to 1 do begin
if ify + iy < Bmp.Height then
//sli := Bmp.scanline[ify + iy]
sli := PByteArray(SL1[ify + iy])
else
//sli := Bmp.scanline[Bmp.Height - ify - iy];
sli := PByteArray(SL1[Bmp.Height - ify - iy]);
if ifx + ix < Bmp.Width then begin
new_red := sli[(ifx + ix)*3];
new_green := sli[(ifx + ix)*3+1];
new_blue := sli[(ifx + ix)*3+2];
end else begin
new_red := sli[(Bmp.Width - ifx - ix)*3];
new_green := sli[(Bmp.Width - ifx - ix)*3+1];
new_blue := sli[(Bmp.Width - ifx - ix)*3+2];
end;
weight := weight_x[ix] * weight_y[iy];
total_red := total_red + new_red * weight;
total_green := total_green + new_green * weight;
total_blue := total_blue + new_blue * weight;
end;
end;
//slo := Dst.scanline[ty];
slo := PByteArray(SL2[ty]);
slo[tx*3] := Round(total_red);
slo[tx*3+1] := Round(total_green);
slo[tx*3+2] := Round(total_blue);
end;
end;
finally
SL2.Free;
SL1.Free;
end;
end;
procedure GrayScale(var clip: tbitmap);
var
p0 : pbytearray;
Gray, x, y : Integer;
SL : TScanlines;
begin
SL := TScanlines.Create(clip);
try
for y:=0 to clip.Height-1 do begin
//p0 := clip.scanline[y];
p0 := PByteArray(SL[y]);
for x := 0 to clip.Width-1 do begin
Gray := Round(p0[x*3]*0.3+p0[x*3+1]*0.59+p0[x*3+2]*0.11);
p0[x*3] := Gray;
p0[x*3+1] := Gray;
p0[x*3+2] := Gray;
end;
end;
finally
SL.Free;
end;
end;
procedure Lightness(var clip: tbitmap; Amount: Integer);
var
p0 : pbytearray;
r, g, b, x, y : Integer;
SL : TScanlines;
begin
SL := TScanlines.Create(clip);
try
for y := 0 to clip.Height-1 do begin
//p0 := clip.scanline[y];
p0 := PByteArray(SL[y]);
for x := 0 to clip.Width-1 do begin
r := p0[x*3];
g := p0[x*3+1];
b := p0[x*3+2];
p0[x*3] := IntToByte(r+((255-r)*Amount)div 255);
p0[x*3+1] := IntToByte(g+((255-g)*Amount)div 255);
p0[x*3+2] := IntToByte(b+((255-b)*Amount)div 255);
end;
end;
finally
SL.Free;
end;
end;
procedure Darkness(var src: tbitmap; Amount: integer);
var
p0 : pbytearray;
r, g, b, x, y : Integer;
SL : TScanlines;
begin
src.pixelformat := pf24bit;
SL := TScanlines.Create(src);
try
for y := 0 to src.Height-1 do begin
//p0 := src.scanline[y];
p0 := PByteArray(SL[y]);
for x := 0 to src.Width-1 do begin
r := p0[x*3];
g := p0[x*3+1];
b := p0[x*3+2];
p0[x*3] := IntToByte(r-((r)*Amount)div 255);
p0[x*3+1] := IntToByte(g-((g)*Amount)div 255);
p0[x*3+2] := IntToByte(b-((b)*Amount)div 255);
end;
end;
finally
SL.Free;
end;
end;
procedure Saturation(var clip: tbitmap; Amount: Integer);
var
p0 : pbytearray;
Gray, r, g, b, x, y : Integer;
SL : TScanlines;
begin
SL := TScanlines.Create(clip);
try
for y := 0 to clip.Height-1 do begin
//p0 := clip.scanline[y];
p0 := PByteArray(SL[y]);
for x := 0 to clip.Width-1 do begin
r := p0[x*3];
g := p0[x*3+1];
b := p0[x*3+2];
Gray := (r+g+b)div 3;
p0[x*3] := IntToByte(Gray+(((r-Gray)*Amount)div 255));
p0[x*3+1] := IntToByte(Gray+(((g-Gray)*Amount)div 255));
p0[x*3+2] := IntToByte(Gray+(((b-Gray)*Amount)div 255));
end;
end;
finally
SL.Free;
end;
end;
procedure SmoothResize(var Src, Dst: TBitmap);
var
x, y, xP, yP, yP2, xP2 : Integer;
Read, Read2 : PByteArray;
t, z, z2, iz2 : Integer;
pc : PBytearray;
w1, w2, w3, w4 : Integer;
Col1r, col1g, col1b, Col2r, col2g, col2b : byte;
SL1, SL2 : TScanlines;
begin
SL1 := TScanlines.Create(Src);
SL2 := TScanlines.Create(Dst);
try
xP2 := ((src.Width-1)shl 15)div Dst.Width;
yP2 := ((src.Height-1)shl 15)div Dst.Height;
yP := 0;
for y := 0 to Dst.Height-1 do begin
xP := 0;
//Read := src.ScanLine[yP shr 15];
Read := PByteArray(SL1[yP shr 15]);
if yP shr 16<src.Height-1 then
//Read2 := src.ScanLine [yP shr 15+1]
Read2 := PByteArray(SL1[yP shr 15+1])
else
//Read2 := src.ScanLine [yP shr 15];
Read2 := PByteArray(SL1[yP shr 15]);
//pc := Dst.scanline[y];
pc := PByteArray(SL2[y]);
z2 := yP and $7FFF;
iz2 := $8000-z2;
for x := 0 to Dst.Width-1 do begin
t := xP shr 15;
Col1r := Read[t*3];
Col1g := Read[t*3+1];
Col1b := Read[t*3+2];
Col2r := Read2[t*3];
Col2g := Read2[t*3+1];
Col2b := Read2[t*3+2];
z := xP and $7FFF;
w2 := (z*iz2)shr 15;
w1 := iz2-w2;
w4 := (z*z2)shr 15;
w3 := z2-w4;
pc[x*3+2] :=
(Col1b*w1+Read[(t+1)*3+2]*w2+
Col2b*w3+Read2[(t+1)*3+2]*w4)shr 15;
pc[x*3+1] :=
(Col1g*w1+Read[(t+1)*3+1]*w2+
Col2g*w3+Read2[(t+1)*3+1]*w4)shr 15;
pc[x*3] :=
(Col1r*w1+Read2[(t+1)*3]*w2+
Col2r*w3+Read2[(t+1)*3]*w4)shr 15;
Inc(xP,xP2);
end;
Inc(yP,yP2);
end;
finally
SL2.Free;
SL1.Free;
end;
end;
function TrimInt(i, Min, Max: Integer): Integer;
begin
if i > Max then
Result := Max
else
if i < Min then
Result := Min
else
Result := i;
end;
procedure SmoothRotate(var Src, Dst: TBitmap; cx, cy: Integer; Angle: Extended);
type
TFColor = record b, g, r : Byte end;
var
Top,
Bottom,
Left,
Right,
eww, nsw,
fx, fy,
wx, wy: Extended;
cAngle,
sAngle: Double;
xDiff,
yDiff,
ifx, ify,
px, py,
ix, iy,
x, y: Integer;
nw, ne,
sw, se: TFColor;
P1, P2, P3 : Pbytearray;
SL1, SL2 : TScanlines;
begin
SL1 := TScanlines.Create(Src);
SL2 := TScanlines.Create(Dst);
try
Angle := angle;
Angle := -Angle*Pi/180;
sAngle := Sin(Angle);
cAngle := Cos(Angle);
xDiff := (Dst.Width-Src.Width)div 2;
yDiff := (Dst.Height-Src.Height)div 2;
for y := 0 to Dst.Height-1 do begin
//P3 := Dst.scanline[y];
P3 := PByteArray(SL2[y]);
py := 2*(y-cy)+1;
for x := 0 to Dst.Width-1 do begin
px := 2*(x-cx)+1;
fx := (((px*cAngle-py*sAngle)-1)/ 2+cx)-xDiff;
fy := (((px*sAngle+py*cAngle)-1)/ 2+cy)-yDiff;
ifx := Round(fx);
ify := Round(fy);
if (ifx>-1) and (ifx<Src.Width) and (ify>-1) and (ify<Src.Height) then
begin
eww := fx-ifx;
nsw := fy-ify;
iy := TrimInt(ify+1,0,Src.Height-1);
ix := TrimInt(ifx+1,0,Src.Width-1);
//P1 := Src.scanline[ify];
P1 := PByteArray(SL1[ify]);
//P2 := Src.scanline[iy];
P2 := PByteArray(SL1[iy]);
nw.r := P1[ifx*3];
nw.g := P1[ifx*3+1];
nw.b := P1[ifx*3+2];
ne.r := P1[ix*3];
ne.g := P1[ix*3+1];
ne.b := P1[ix*3+2];
sw.r := P2[ifx*3];
sw.g := P2[ifx*3+1];
sw.b := P2[ifx*3+2];
se.r := P2[ix*3];
se.g := P2[ix*3+1];
se.b := P2[ix*3+2];
Top := nw.b+eww*(ne.b-nw.b);
Bottom := sw.b+eww*(se.b-sw.b);
P3[x*3+2] := IntToByte(Round(Top+nsw*(Bottom-Top)));
Top := nw.g+eww*(ne.g-nw.g);
Bottom := sw.g+eww*(se.g-sw.g);
P3[x*3+1] := IntToByte(Round(Top+nsw*(Bottom-Top)));
Top := nw.r+eww*(ne.r-nw.r);
Bottom := sw.r+eww*(se.r-sw.r);
P3[x*3] := IntToByte(Round(Top+nsw*(Bottom-Top)));
end;
end;
end;
finally
SL2.Free;
SL1.Free;
end;
end;
procedure SplitBlur(var clip: tbitmap; Amount: integer);
var
p0, p1, p2 : pbytearray;
cx, x, y : Integer;
Buf : array[0..3,0..2]of byte;
SL : TScanlines;
begin
if Amount = 0 then Exit;
SL := TScanlines.Create(clip);
try
for y := 0 to clip.Height-1 do begin
//p0 := clip.scanline[y];
//if y-Amount<0 then p1 := clip.scanline[y]
//else {y-Amount>0} p1 := clip.ScanLine[y-Amount];
//if y+Amount<clip.Height then p2 := clip.ScanLine[y+Amount]
//else {y+Amount>=Height} p2 := clip.ScanLine[clip.Height-y];
p0 := PByteArray(SL[y]);
if y-Amount<0
then p1 := PByteArray(SL[y])
else {y-Amount>0}
p1 := PByteArray(SL[y-Amount]);
if y+Amount<clip.Height then
p2 := PByteArray(SL[y+Amount])
else {y+Amount>=Height}
p2 := PByteArray(SL[clip.Height-y]);
for x := 0 to clip.Width-1 do begin
if x-Amount<0 then
cx := x
else {x-Amount>0}
cx := x-Amount;
Buf[0,0] := p1[cx*3];
Buf[0,1] := p1[cx*3+1];
Buf[0,2] := p1[cx*3+2];
Buf[1,0] := p2[cx*3];
Buf[1,1] := p2[cx*3+1];
Buf[1,2] := p2[cx*3+2];
if x+Amount<clip.Width then
cx := x+Amount
else {x+Amount>=Width}
cx := clip.Width-x;
Buf[2,0] := p1[cx*3];
Buf[2,1] := p1[cx*3+1];
Buf[2,2] := p1[cx*3+2];
Buf[3,0] := p2[cx*3];
Buf[3,1] := p2[cx*3+1];
Buf[3,2] := p2[cx*3+2];
p0[x*3] := (Buf[0,0]+Buf[1,0]+Buf[2,0]+Buf[3,0])shr 2;
p0[x*3+1] := (Buf[0,1]+Buf[1,1]+Buf[2,1]+Buf[3,1])shr 2;
p0[x*3+2] := (Buf[0,2]+Buf[1,2]+Buf[2,2]+Buf[3,2])shr 2;
end;
end;
finally
SL.Free;
end;
end;
procedure GaussianBlur(var clip: tbitmap; Amount: integer);
var
i : Integer;
begin
for i := Amount downto 0 do
SplitBlur(clip,3);
end;
procedure Mosaic(var Bm:TBitmap;size:Integer);
var
x, y, i, j : integer;
p1, p2 : pbytearray;
r, g, b : byte;
SL : TScanlines;
begin
SL := TScanlines.Create(Bm);
try
y := 0;
repeat
//p1 := bm.scanline[y];
p1 := PByteArray(SL[y]);
repeat
j := 1;
repeat
//p2 := bm.scanline[y];
p2 := PByteArray(SL[y]);
x := 0;
repeat
r := p1[x*3];
g := p1[x*3+1];
b := p1[x*3+2];
i := 1;
repeat
p2[x*3] := r;
p2[x*3+1] := g;
p2[x*3+2] := b;
inc(x);
inc(i);
until (x>=bm.width) or (i>size);
until x>=bm.width;
inc(j);
inc(y);
until (y>=bm.height) or (j>size);
until (y>=bm.height) or (x>=bm.width);
until y>=bm.height;
finally
SL.Free;
end;
end;
procedure Twist(var Bmp, Dst: TBitmap; Amount: integer);
var
fxmid, fymid : Single;
txmid, tymid : Single;
fx,fy : Single;
tx2, ty2 : Single;
r : Single;
theta : Single;
ifx, ify : integer;
dx, dy : Single;
OFFSET : Single;
ty, tx : Integer;
weight_x, weight_y : array[0..1] of Single;
weight : Single;
new_red, new_green : Integer;
new_blue : Integer;
total_red, total_green : Single;
total_blue : Single;
ix, iy : Integer;
sli, slo : PBytearray;
SL1, SL2 : TScanlines;
function ArcTan2(xt,yt : Single): Single;
begin
if xt = 0 then
if yt > 0 then
Result := Pi/2
else
Result := -(Pi/2)
else begin
Result := ArcTan(yt/xt);
if xt < 0 then
Result := Pi + ArcTan(yt/xt);
end;
end;
begin
OFFSET := -(Pi/2);
dx := Bmp.Width - 1;
dy := Bmp.Height - 1;
r := Sqrt(dx * dx + dy * dy);
tx2 := r;
ty2 := r;
txmid := (Bmp.Width-1)/2; //Adjust these to move center of rotation
tymid := (Bmp.Height-1)/2; //Adjust these to move ......
fxmid := (Bmp.Width-1)/2;
fymid := (Bmp.Height-1)/2;
if tx2 >= Bmp.Width then tx2 := Bmp.Width-1;
if ty2 >= Bmp.Height then ty2 := Bmp.Height-1;
SL1 := TScanlines.Create(Bmp);
SL2 := TScanlines.Create(Dst);
try
for ty := 0 to Round(ty2) do begin
for tx := 0 to Round(tx2) do begin
dx := tx - txmid;
dy := ty - tymid;
r := Sqrt(dx * dx + dy * dy);
if r = 0 then begin
fx := 0;
fy := 0;
end
else begin
theta := ArcTan2(dx,dy) - r/Amount - OFFSET;
fx := r * Cos(theta);
fy := r * Sin(theta);
end;
fx := fx + fxmid;
fy := fy + fymid;
ify := Trunc(fy);
ifx := Trunc(fx);
// Calculate the weights.
if fy >= 0 then begin
weight_y[1] := fy - ify;
weight_y[0] := 1 - weight_y[1];
end else begin
weight_y[0] := -(fy - ify);
weight_y[1] := 1 - weight_y[0];
end;
if fx >= 0 then begin
weight_x[1] := fx - ifx;
weight_x[0] := 1 - weight_x[1];
end else begin
weight_x[0] := -(fx - ifx);
Weight_x[1] := 1 - weight_x[0];
end;
if ifx < 0 then
ifx := Bmp.Width-1-(-ifx mod Bmp.Width)
else
if ifx > Bmp.Width-1 then
ifx := ifx mod Bmp.Width;
if ify < 0 then
ify := Bmp.Height-1-(-ify mod Bmp.Height)
else
if ify > Bmp.Height-1 then
ify := ify mod Bmp.Height;
total_red := 0.0;
total_green := 0.0;
total_blue := 0.0;
for ix := 0 to 1 do begin
for iy := 0 to 1 do begin
if ify + iy < Bmp.Height then
//sli := Bmp.scanline[ify + iy]
sli := PByteArray(SL1[ify + iy])
else
//sli := Bmp.scanline[Bmp.Height - ify - iy];
sli := PByteArray(SL1[Bmp.Height - ify - iy]);
if ifx + ix < Bmp.Width then begin
new_red := sli[(ifx + ix)*3];
new_green := sli[(ifx + ix)*3+1];
new_blue := sli[(ifx + ix)*3+2];
end else begin
new_red := sli[(Bmp.Width - ifx - ix)*3];
new_green := sli[(Bmp.Width - ifx - ix)*3+1];
new_blue := sli[(Bmp.Width - ifx - ix)*3+2];
end;
weight := weight_x[ix] * weight_y[iy];
total_red := total_red + new_red * weight;
total_green := total_green + new_green * weight;
total_blue := total_blue + new_blue * weight;
end;
end;
//slo := Dst.scanline[ty];
slo := PByteArray(SL2[ty]);
slo[tx*3] := Round(total_red);
slo[tx*3+1] := Round(total_green);
slo[tx*3+2] := Round(total_blue);
end;
end;
finally
SL2.Free;
SL1.Free;
end;
end;
Procedure Splitlight (var clip:tbitmap;amount:integer);
var
x, y, i : integer;
p1 : pbytearray;
SL : TScanlines;
function sinpixs(a:integer):integer;
begin
result := variant(sin(a/255*pi/2)*255);
end;
begin
SL := TScanlines.Create(clip);
try
for i := 1 to amount do
for y := 0 to clip.height-1 do begin
//p1 := clip.scanline[y];
p1 := PByteArray(SL[y]);
for x := 0 to clip.width-1 do begin
p1[x*3] := sinpixs(p1[x*3]);
p1[x*3+1] := sinpixs(p1[x*3+1]);
p1[x*3+2] := sinpixs(p1[x*3+2]);
end;
end;
finally
SL.Free;
end;
end;
procedure Tile(src, dst: TBitmap; amount: integer);
var
w, h, w2, h2, i, j : integer;
bm : tbitmap;
begin
w := src.width;
h := src.height;
dst.width := w;
dst.height := h;
dst.Canvas.draw(0,0,src);
if (amount<=0) or ((w div amount)<5)or ((h div amount)<5) then
exit;
h2 := h div amount;
w2 := w div amount;
bm := tbitmap.create;
bm.width := w2;
bm.height := h2;
bm.PixelFormat := pf24bit;
smoothresize(src,bm);
for j := 0 to amount-1 do
for i := 0 to amount-1 do
dst.canvas.Draw (i*w2,j*h2,bm);
bm.free;
end;
procedure SpotLight (var src: Tbitmap; Amount: integer; Spot: TRect);
var
bm : tbitmap;
w, h : integer;
begin
Darkness(src,amount);
w := src.Width;
h := src.Height ;
bm := tbitmap.create;
bm.width := w;
bm.height := h;
bm.canvas.Brush.color := clblack;
bm.canvas.FillRect (rect(0,0,w,h));
bm.canvas.brush.Color := clwhite;
bm.canvas.Ellipse (Spot.left,spot.top,spot.right,spot.bottom);
bm.transparent := true;
bm.TransparentColor := clwhite;
src.Canvas.Draw (0,0,bm);
bm.free;
end;
procedure Trace (src:Tbitmap;intensity:integer);
var
x, y, i : integer;
P1, P2, P3, P4 : PByteArray;
tb, TraceB : byte;
hasb : boolean;
bitmap : tbitmap;
SL1, SL2 : TScanlines;
begin
bitmap := tbitmap.create;
bitmap.width := src.width;
bitmap.height := src.height;
bitmap.canvas.draw(0,0,src);
bitmap.PixelFormat := pf8bit; // pf8bit
src.PixelFormat := pf24bit;
hasb := false;
TraceB := $00;
SL1 := TScanlines.Create(src);
SL2 := TScanlines.Create(bitmap);
try
tb := 0; //make compiler smile
for i := 1 to Intensity do begin
for y := 0 to BitMap.height -2 do begin
//P1 := BitMap.ScanLine[y];
//P2 := BitMap.scanline[y+1];
P1 := PByteArray(SL2[y]);
P2 := PByteArray(SL2[y +1]);
//P3 := src.scanline[y];
//P4 := src.scanline[y+1];
P3 := PByteArray(SL1[y]);
P4 := PByteArray(SL1[y+1]);
x := 0;
repeat
if p1[x]<>p1[x+1] then begin
if not hasb then begin
tb := p1[x+1];
hasb := true;
p3[x*3] := TraceB;
p3[x*3+1] := TraceB;
p3[x*3+2] := TraceB;
end else begin
if p1[x]<>tb then begin
p3[x*3] := TraceB;
p3[x*3+1] := TraceB;
p3[x*3+2] := TraceB;
end else begin
p3[(x+1)*3] := TraceB;
p3[(x+1)*3+1] := TraceB;
p3[(x+1)*3+1] := TraceB;
end;
end;
end;
if p1[x]<>p2[x] then begin
if not hasb then begin
tb := p2[x];
hasb := true;
p3[x*3] := TraceB;
p3[x*3+1] := TraceB;
p3[x*3+2] := TraceB;
end else begin
if p1[x]<>tb then begin
p3[x*3] := TraceB;
p3[x*3+1] := TraceB;
p3[x*3+2] := TraceB;
end else begin
p4[x*3] := TraceB;
p4[x*3+1] := TraceB;
p4[x*3+2] := TraceB;
end;
end;
end;
inc(x);
until x>=(BitMap.width -2);
end;
if i>1 then
for y := BitMap.height -1 downto 1 do begin
//P1 := BitMap.ScanLine[y];
//P2 := BitMap.scanline[y-1];
P1 := PByteArray(SL2[y]);
P2 := PByteArray(SL2[y -1]);
//P3 := src.scanline[y];
//P4 := src.scanline [y-1];
P3 := PByteArray(SL1[y]);
P4 := PByteArray(SL1[y-1]);
x := Bitmap.width-1;
repeat
if p1[x]<>p1[x-1] then begin
if not hasb then begin
tb := p1[x-1];
hasb := true;
p3[x*3] := TraceB;
p3[x*3+1] := TraceB;
p3[x*3+2] := TraceB;
end else begin
if p1[x]<>tb then begin
p3[x*3] := TraceB;
p3[x*3+1] := TraceB;
p3[x*3+2] := TraceB;
end else begin
p3[(x-1)*3] := TraceB;
p3[(x-1)*3+1] := TraceB;
p3[(x-1)*3+2] := TraceB;
end;
end;
end;
if p1[x]<>p2[x] then begin
if not hasb then begin
tb := p2[x];
hasb := true;
p3[x*3] := TraceB;
p3[x*3+1] := TraceB;
p3[x*3+2] := TraceB;
end else begin
if p1[x]<>tb then begin
p3[x*3] := TraceB;
p3[x*3+1] := TraceB;
p3[x*3+2] := TraceB;
end else begin
p4[x*3] := TraceB;
p4[x*3+1] := TraceB;
p4[x*3+2] := TraceB;
end;
end;
end;
dec(x);
until x<=1;
end;
end;
finally
SL2.Free;
SL1.Free;
end;
bitmap.free;
end;
procedure Emboss(var Bmp:TBitmap);
var
x, y : Integer;
p1, p2 : Pbytearray;
SL : TScanlines;
begin
SL := TScanlines.Create(Bmp);
try
for y := 0 to Bmp.Height-2 do begin
//p1 := bmp.scanline[y];
//p2 := bmp.scanline[y+1];
p1 := PByteArray(SL[y]);
p2 := PByteArray(SL[y+1]);
for x := 0 to Bmp.Width-4 do begin
p1[x*3] := (p1[x*3]+(p2[(x+3)*3] xor $FF))shr 1;
p1[x*3+1] := (p1[x*3+1]+(p2[(x+3)*3+1] xor $FF))shr 1;
p1[x*3+2] := (p1[x*3+2]+(p2[(x+3)*3+2] xor $FF))shr 1;
end;
end;
finally
SL.Free;
end;
end;
procedure Solorize(src, dst: tbitmap; amount: integer);
var
w, h, x, y : integer;
ps, pd : pbytearray;
c : integer;
SL1, SL2 : TScanlines;
begin
w := src.width;
h := src.height;
src.PixelFormat := pf24bit;
dst.PixelFormat := pf24bit;
SL1 := TScanlines.Create(src);
SL2 := TScanlines.Create(dst);
try
for y := 0 to h-1 do begin
//ps := src.scanline[y];
//pd := dst.scanline[y];
ps := PByteArray(SL1[y]);
pd := PByteArray(SL2[y]);
for x := 0 to w-1 do begin
c := (ps[x*3]+ps[x*3+1]+ps[x*3+2]) div 3;
if c>amount then begin
pd[x*3] := 255-ps[x*3];
pd[x*3+1] := 255-ps[x*3+1];
pd[x*3+2] := 255-ps[x*3+2];
end else begin
pd[x*3] := ps[x*3];
pd[x*3+1] := ps[x*3+1];
pd[x*3+2] := ps[x*3+2];
end;
end;
end;
finally
SL2.Free;
SL1.Free;
end;
end;
procedure Posterize(src, dst: tbitmap; amount: integer);
var
w, h, x, y : integer;
ps, pd : pbytearray;
SL1, SL2 : TScanlines;
begin
w := src.width;
h := src.height;
src.PixelFormat := pf24bit;
dst.PixelFormat := pf24bit;
SL1 := TScanlines.Create(src);
SL2 := TScanlines.Create(dst);
try
for y := 0 to h-1 do begin
//ps := src.scanline[y];
//pd := dst.scanline[y];
ps := PByteArray(SL1[y]);
pd := PByteArray(SL2[y]);
for x := 0 to w-1 do begin
pd[x*3] := round(ps[x*3]/amount)*amount;
pd[x*3+1] := round(ps[x*3+1]/amount)*amount;
pd[x*3+2] := round(ps[x*3+2]/amount)*amount;
end;
end;
finally
SL2.Free;
SL1.Free;
end;
end;
// *********************************
// ******************
// ******
function GetAs24bit(Src: TBitmap): TBitmap;
begin
result := TBitmap.Create;
result.Assign(Src);
result.PixelFormat := pf24bit;
end;
procedure Effect_Invert(SrcBmp: TBitmap);
Var
BB : TBitmap;
Begin
BB := GetAs24bit(SrcBmp);
try
PicInvert ( BB );
SrcBmp .Assign (BB);
finally
BB.Free;
end;
end;
Procedure Effect_AddColorNoise (SrcBmp: TBitmap; Amount:Integer);
Var
BB : TBitmap;
Begin
BB := GetAs24bit(SrcBmp);
try
AddColorNoise (bb,Amount);
SrcBmp .Assign (BB);
finally
BB.Free;
end;
end;
Procedure Effect_AddMonoNoise (SrcBmp: TBitmap; Amount:Integer);
Var
BB : TBitmap;
Begin
BB := GetAs24bit(SrcBmp);
try
AddMonoNoise (bb,Amount);
SrcBmp .Assign (BB);
finally
BB.Free;
end;
end;
procedure Effect_AntiAlias(SrcBmp: TBitmap);
Var
BB : TBitmap;
Begin
BB := GetAs24bit(SrcBmp);
try
AntiAlias ( BB );
SrcBmp .Assign (BB);
finally
BB.Free;
end;
end;
Procedure Effect_Contrast (SrcBmp: TBitmap; Amount:Integer);
Var
BB : TBitmap;
Begin
BB := GetAs24bit(SrcBmp);
try
Contrast (bb,Amount);
SrcBmp .Assign (BB);
finally
BB.Free;
end;
end;
Procedure Effect_FishEye (SrcBmp: TBitmap; Amount:Integer);
Var
BB1, BB2 : TBitmap;
Begin
BB1 := GetAs24bit(SrcBmp);
BB2 := GetAs24bit(BB1);
try
FishEye (BB1, BB2, Amount);
SrcBmp .Assign (BB2);
finally
BB1.Free;
BB2.Free;
end;
end;
Procedure Effect_GrayScale(SrcBmp: TBitmap);
Var
BB : TBitmap;
Begin
BB := GetAs24bit(SrcBmp);
try
GrayScale (BB);
SrcBmp .Assign (BB);
finally
BB.Free;
end;
end;
Procedure Effect_Lightness (SrcBmp: TBitmap; Amount:Integer);
Var
BB : TBitmap;
Begin
BB := GetAs24bit(SrcBmp);
try
Lightness (BB,Amount);
SrcBmp .Assign (BB);
finally
BB.Free;
end;
end;
Procedure Effect_Darkness (SrcBmp: TBitmap; Amount:Integer);
Var
BB : TBitmap;
Begin
BB := GetAs24bit(SrcBmp);
try
Darkness (BB,Amount);
SrcBmp .Assign (BB);
finally
BB.Free;
end;
end;
Procedure Effect_Saturation (SrcBmp: TBitmap; Amount:Integer);
Var
BB : TBitmap;
Begin
BB := GetAs24bit(SrcBmp);
try
Saturation (BB,Amount);
SrcBmp .Assign (BB);
finally
BB.Free;
end;
end;
Procedure Effect_SplitBlur (SrcBmp: TBitmap; Amount:Integer);
Var
BB : TBitmap;
Begin
BB := GetAs24bit(SrcBmp);
try
SplitBlur (BB,Amount);
SrcBmp .Assign (BB);
finally
BB.Free;
end;
end;
Procedure Effect_GaussianBlur (SrcBmp: TBitmap; Amount:Integer);
Var
BB : TBitmap;
Begin
BB := GetAs24bit(SrcBmp);
try
GaussianBlur (BB,Amount);
SrcBmp .Assign (BB);
finally
BB.Free;
end;
end;
Procedure Effect_Mosaic (SrcBmp: TBitmap; Size:Integer);
Var
BB : TBitmap;
Begin
BB := GetAs24bit(SrcBmp);
try
Mosaic (BB,Size);
SrcBmp .Assign (BB);
finally
BB.Free;
end;
end;
Procedure Effect_Twist (SrcBmp: TBitmap; Amount:Integer);
Var
BB1, BB2 : TBitmap;
Begin
BB1 := GetAs24bit(SrcBmp);
BB2 := GetAs24bit(BB1);
try
Twist (BB1, BB2, Amount);
SrcBmp .Assign (BB2);
finally
BB1.Free;
BB2.Free;
end;
end;
Procedure Effect_Trace (SrcBmp: TBitmap; Amount: integer);
Var
BB : TBitmap;
Begin
BB := GetAs24bit(SrcBmp);
try
Trace (BB,Amount);
SrcBmp .Assign (BB);
finally
BB.Free;
end;
end;
procedure Effect_Splitlight (SrcBmp: TBitmap; Amount:integer);
Var
BB : TBitmap;
Begin
BB := GetAs24bit(SrcBmp);
try
Splitlight (BB, Amount);
SrcBmp .Assign (BB);
finally
BB.Free;
end;
end;
Procedure Effect_Tile (SrcBmp: TBitmap; Amount: integer);
Var
BB1, BB2 : TBitmap;
Begin
BB1 := GetAs24bit(SrcBmp);
BB2 := GetAs24bit(BB1);
try
Tile (BB1, BB2, Amount);
SrcBmp .Assign (BB2);
finally
BB1.Free;
BB2.Free;
end;
end;
Procedure Effect_SpotLight (SrcBmp: TBitmap; Amount: integer; Spot: TRect);
Var
BB : TBitmap;
Begin
BB := GetAs24bit(SrcBmp);
try
SpotLight (BB, Amount, Spot);
SrcBmp .Assign (BB);
finally
BB.Free;
end;
end;
Procedure Effect_Emboss(SrcBmp: TBitmap);
Var
BB : TBitmap;
Begin
BB := GetAs24bit(SrcBmp);
try
Emboss (BB);
SrcBmp .Assign (BB);
finally
BB.Free;
end;
end;
Procedure Effect_Solorize (SrcBmp: TBitmap; Amount: integer);
Var
BB1, BB2 : TBitmap;
Begin
BB1 := GetAs24bit(SrcBmp);
BB2 := GetAs24bit(BB1);
try
Solorize (BB1, BB2, Amount);
SrcBmp .Assign (BB2);
finally
BB1.Free;
BB2.Free;
end;
end;
Procedure Effect_Posterize (SrcBmp: TBitmap; Amount: integer);
Var
BB1, BB2 : TBitmap;
Begin
BB1 := GetAs24bit(SrcBmp);
BB2 := GetAs24bit(BB1);
try
Posterize (BB1, BB2, Amount);
SrcBmp .Assign (BB2);
finally
BB1.Free;
BB2.Free;
end;
end;
procedure Effect_SmoothResize(SrcBmp: TBitmap; NuWidth, NuHeight: integer);
Var
BB1, BB2 : TBitmap;
Begin
BB1 := GetAs24bit(SrcBmp);
BB2 := TBitmap.Create;
try
BB2.Width := NuWidth;
BB2.Height := NuHeight;
BB2.PixelFormat := pf24bit;
SmoothResize( BB1, BB2 );
SrcBmp .Assign (BB2);
finally
BB1.Free;
BB2.Free;
end;
end;
procedure Effect_SmoothRotate(SrcBmp: TBitmap; cx, cy: Integer; Angle: Extended);
Var
BB1, BB2 : TBitmap;
Begin
BB1 := GetAs24bit(SrcBmp);
BB2 := TBitmap.Create;
try
BB2.Width := BB1.Width;
BB2.Height := BB1.Height;
BB2.PixelFormat := pf24bit;
SmoothRotate(BB1, BB2, cx, cy, Angle);
SrcBmp .Assign (BB2);
finally
BB1.Free;
BB2.Free;
end;
end;
end.
|
program HowToCenterCameraOnASprite;
uses
SwinGame, sgTypes;
procedure Main();
var
sSprite : Sprite;
begin
OpenGraphicsWindow('Center Camera On A Sprite', 800, 600);
LoadDefaultColors();
LoadBitmapNamed('ufo', 'ufo.png');
sSprite := CreateSprite(BitmapNamed('ufo'));
SpriteSetX(sSprite, 60);
SpriteSetY(sSprite, 60);
repeat // The game loop...
ProcessEvents();
ClearScreen(ColorWhite);
if KeyDown(UPKey) then SpriteSetY(sSprite, SpriteY(sSprite)-1);
if KeyDown(DOWNKey) then SpriteSetY(sSprite, SpriteY(sSprite)+1);
if KeyDown(LEFTKey) then SpriteSetX(sSprite, SpriteX(sSprite)-1);
if KeyDown(RIGHTKey) then SpriteSetX(sSprite, SpriteX(sSprite)+1);
FillRectangle(RGBColor(205,201,201), -150, 250, 1150, 20);
FillRectangle(RGBColor(205,201,201), -150, 330, 1150, 20);
FillRectangle(RGBColor(255,255,0), -150, 290, 50, 20);
FillRectangle(RGBColor(124,252,0), -50, 290, 50, 20);
FillRectangle(RGBColor(184,134,11), 50, 290, 50, 20);
FillRectangle(RGBColor(0,255,255), 150, 290, 50, 20);
FillRectangle(RGBColor(255,165,0), 250, 290, 50, 20);
FillRectangle(RGBColor(255,192,203), 350, 290, 50, 20);
FillRectangle(RGBColor(160,32,240), 450, 290, 50, 20);
FillRectangle(RGBColor(165,42,42), 550, 290, 50, 20);
FillRectangle(RGBColor(240,230,140), 650, 290, 50, 20);
FillRectangle(RGBColor(0,0,128), 750, 290, 50, 20);
FillRectangle(RGBColor(245,255,250), 850, 290, 50, 20);
FillRectangle(RGBColor(255,228,225), 950, 290, 50, 20);
FillRectangle(RGBColor(205,201,201), 320, -275, 20, 1150);
FillRectangle(RGBColor(205,201,201), 510, -275, 20, 1150);
if KeyTyped(SPACEKey) then CenterCameraOn(sSprite, 0, 0);
DrawTextOnScreen(PointToString(CameraPos()), ColorBlack, 0, 0);
DrawSprite(sSprite);
RefreshScreen();
until WindowCloseRequested();
FreeSprite(sSprite);
ReleaseAllResources();
end;
begin
Main();
end. |
(*
Category: SWAG Title: ANYTHING NOT OTHERWISE CLASSIFIED
Original name: 0178.PAS
Description: Create a Character Pyramid
Author: CLIF PENN
Date: 05-31-96 09:17
*)
{
>I need to do two programs and I am unsure of what to do with them. If
>anyone could help me with the code or the steps necessary to write the
>programs it would be greatly appreciated. Thank you. Here's what I
>need to do:
>First program: A program that reads a char. from "A" to "Z" as input
>to produce output in the shape of a pyramid composed of the letters up
>to and including the letter that is input. Example:
> A
> ABA
> ABCBA
> ABCDCBA
Here is one way to do the pyramid of characters. }
Program Char_Pyramid;
{ <clifpenn@airmail.net 4/16/96 12:30 AM Borland Turbo v 6.0
From a single character input in ['A'..'Z'] a pyramid of chars is
formed as follows:
A A
ch1 := 'C' gives ABA ch1 := 'D' gives ABA etc.
ABCBA ABCBA
ABCDCBA }
USES CRT;
Label Finis;
CONST
Esc = Chr(27);
VAR
ch1, ch2:Char;
s, s1, s2:String;
fld:Integer;
BEGIN
Repeat
ClrScr;
Write('Input a letter, (Esc to quit): ');
fld := 40;
s1 := '';
s2 := '';
Repeat
ch1 := UpCase(ReadKey);
Until ch1 in [Esc, 'A'..'Z'];
If ch1 = Esc then Goto Finis;
Begin
Writeln(ch1);
For ch2 := 'A' to ch1 Do
Begin
s1 := s1 + ch2 ; (* forward string segment *)
s := s1 + s2 ; (* forward + reversed chars *)
Writeln(s:fld); (* centered on screen *)
Inc(fld);
s2 := ch2 + s2; (* next reversed str segment *)
End;
End;
Write('Press enter to continue');
Readln;
Finis:
Until ch1 = Esc;
END.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.