text stringlengths 14 6.51M |
|---|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
FA:word;
FB:integer;
FC:string;
procedure SetA(const Value: word);
function GetB: integer;
function GetC:string;
procedure SetC(Value: string);
public
property B:integer read GetB write FB;
property A:word read FA write SetA;
property C:string read FC write SetC;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
begin
A:=100;
Memo1.lines.add(Inttostr(A));
B:=300;
Memo1.Lines.Add(inttostr(B+B));
C:='Help me!';
Memo1.Lines.Add(C+C);
end;
function TForm1.GetB: integer;
begin
Result := FB+5;
end;
function TForm1.GetC: string;
begin
FC:=FC+'Pomogi!';
result:=FC;
end;
procedure TForm1.SetA(const Value: word);
begin
FA := Value+5000;
end;
procedure TForm1.SetC(Value: string);
begin
FC := Value+ '^_^';
end;
end.
|
unit uMainForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Stan.Param,
FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.VCLUI.Wait,
FireDAC.Phys.ODBCBase, FireDAC.Phys.MSSQL, FireDAC.Phys.Oracle,
FireDAC.Comp.UI, FireDAC.Phys.IBBase, FireDAC.Phys.IB, Data.DB,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.ComCtrls, Vcl.Buttons,
Vcl.ExtCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, FireDAC.Moni.Base,
FireDAC.Moni.RemoteClient, FireDAC.Phys.IBDef, FireDAC.Phys.OracleDef,
FireDAC.Phys.MSSQLDef, FireDAC.Phys.PGDef, FireDAC.Phys.PG;
type
TForm1 = class(TForm)
ADConnection1: TFDConnection;
ADQuery1: TFDQuery;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
ADPhysIBDriverLink1: TFDPhysIBDriverLink;
ADGUIxWaitCursor1: TFDGUIxWaitCursor;
Panel1: TPanel;
ADPhysOracleDriverLink1: TFDPhysOracleDriverLink;
ADPhysMSSQLDriverLink1: TFDPhysMSSQLDriverLink;
ADQuery1CUSTNO: TFloatField;
ADQuery1COMPANY: TStringField;
ADQuery1ADDR1: TStringField;
ADQuery1ADDR2: TStringField;
ADQuery1CITY: TStringField;
ADQuery1STATE: TStringField;
ADQuery1ZIP: TStringField;
ADQuery1COUNTRY: TStringField;
ADQuery1PHONE: TStringField;
ADQuery1FAX: TStringField;
ADQuery1TAXRATE: TFloatField;
ADQuery1CONTACT: TStringField;
ADQuery1LASTINVOICEDATE: TSQLTimeStampField;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
SpeedButton3: TSpeedButton;
StatusBar1: TStatusBar;
Button1: TButton;
FDMoniRemoteClientLink1: TFDMoniRemoteClientLink;
SpeedButton4: TSpeedButton;
FDPhysPgDriverLink1: TFDPhysPgDriverLink;
procedure SpeedButton1Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure ADQuery1UpdateError(ASender: TDataSet; AException: EFDException;
ARow: TFDDatSRow; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction);
private
{ Private declarations }
public
{ Public declarations }
procedure SetupIB;
procedure SetupMSSQl;
procedure SetupORA;
procedure SetupPG;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.ADQuery1UpdateError(ASender: TDataSet;
AException: EFDException; ARow: TFDDatSRow; ARequest: TFDUpdateRequest;
var AAction: TFDErrorAction);
begin
ShowMessage(AException.Message);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ADConnection1.ApplyUpdates([ADQuery1]);
end;
procedure TForm1.SetupIB;
begin
ADConnection1.DriverName := 'IB';
ADConnection1.Params.Add('Server=RIZZATOX64');
ADConnection1.Params.Add('Database=C:\DB_INTERBASE\MASTSQL.GDB');
ADConnection1.Params.Add('User_Name=sysdba');
ADConnection1.Params.Add('Password=masterkey');
ADConnection1.Params.Add('CharacterSet=win1252');
ADConnection1.Params.Add('ExtendedMeTFData=True');
ADConnection1.Params.Add('MonitorBy=Remote');
end;
procedure TForm1.SetupMSSQl;
begin
ADConnection1.DriverName := 'MSSQL';
ADConnection1.Params.Add('Server=RIZZATO2K3');
ADConnection1.Params.Add('Database=MASTSQL');
ADConnection1.Params.Add('User_name=sa');
ADConnection1.Params.Add('Password=embT');
ADConnection1.Params.Add('MonitorBy=Remote');
end;
procedure TForm1.SetupORA;
begin
ADConnection1.DriverName := 'Ora';
ADConnection1.Params.Add('Database=ORA_RIZZATO2K3');
ADConnection1.Params.Add('User_Name=MASTSQL');
ADConnection1.Params.Add('Password=embT');
ADConnection1.Params.Add('MonitorBy=Remote');
end;
procedure TForm1.SetupPG;
begin
ADConnection1.DriverName := 'PG';
ADConnection1.Params.Add('Server=RIZZATO2K3');
ADConnection1.Params.Add('Port=5432');
ADConnection1.Params.Add('Database=dvdrental');
ADConnection1.Params.Add('User_Name=postgres');
ADConnection1.Params.Add('Password=postgres');
ADConnection1.Params.Add('CharacterSet=utf8');
ADConnection1.Params.Add('MetaDefSchema=Public');
ADConnection1.Params.Add('ExtendedMetadata=True');
end;
procedure TForm1.SpeedButton1Click(Sender: TObject);
begin
if ADQuery1.Active then
ADQuery1.Close;
if ADConnection1.Connected then
ADConnection1.Connected := False;
ADConnection1.Params.Clear;
case TComponent(Sender).Tag of
1: SetupIB;
2: SetupMSSQL;
3: SetupORA;
4: SetupPG;
end;
try
ADConnection1.Connected := True;
ADQuery1.Open;
StatusBar1.SimpleText := ' FireDAC is connected using ' + ADConnection1.DriverName + ' driver.';
except
on E: EFDDBEngineException do
case E.Kind of
ekUserPwdInvalid: ShowMessage('Usuรกrio ou senha invรกlidos!');
ekUserPwdExpired: ShowMessage('Password expirado!');
ekServerGone: ShowMessage('Servidor encontra-se inacessรญvel!');
else
ShowMessage(E.Message);
end;
end;
end;
end.
|
unit strtools;
interface
uses SysUtils;
const
cname_bool: array[boolean]of string = ('รรฅรฒ', 'รร ');
function datetime2sql(const Source: TDateTime): string;
function datetime2str(const Source: TDateTime; Fmt: string): string;
function str2bool(Source: string; def: boolean): boolean;
function str2digits(const Source: string): string;
function str2int(const Source: string): int64;
function str2uint(const Source: string): uint64;
function expand4int(Source: string; Value: PInteger; Count: integer): integer;
function str2float(const Source: string): double;
function str2barcode(const Source: string; Count: word): string;
function str2ean13(const src: string): uint64;
function getname(const src: string): string;
implementation
function datetime2sql(const Source: TDateTime): string;
begin
if Source < 4000 then
begin
Result := 'NULL';
end
else begin
DateTimeToString(Result, 'YYYY-MM-DD HH:MM:SS', Source, FormatSettings);
Result := Format('CONVERT(datetime, ''%s'', 20)', [Result]);
end;
end;
function datetime2str(const Source: TDateTime; Fmt: string): string;
begin
if Source < 4000 then
begin
Result := '';
end
else begin
DateTimeToString(Result, Fmt, Source, FormatSettings);
end;
end;
function str2digits(const Source: string): string;
var
j: integer;
begin
Result := '';
j := 1;
while j <= Length(Source) do
begin
case Source[j] of
'-':
if Result = '' then
Result := '-'
else
j := Length(Source);
'0' .. '9':
Result := Result + Source[j];
#9, #32, #160:
;
else
if Result <> '' then
j := Length(Source);
end;
Inc(j);
end;
if (Result = '') or (Result = '-') then
Result := '0';
end;
function str2int(const Source: string): int64;
var
s: string;
begin
if Source = '' then
begin
Result := 0;
end
else begin
s := str2digits(Source);
if Length(s) < 19 then
Result := StrToInt64(s)
else
Result := StrToInt64(copy(s, 1, 18));
end;
end;
function str2uint(const Source: string): uint64;
begin
Result := abs(str2int(Source));
end;
function expand4int(Source: string; Value: PInteger; Count: integer): integer;
var
j: integer;
begin
Result := 0;
while (Source <> '') and (Result < Count) do
begin
j := pos(':', Source);
if j > 0 then
begin
PInteger(PByte(Value) + SizeOf(integer) * Result)^ := str2int(copy(Source, 1, j - 1));
Source := copy(Source, j + 1);
end
else begin
PInteger(PByte(Value) + SizeOf(integer) * Result)^ := str2int(Source);
Source := '';
end;
Inc(Result);
end;
end;
function str2bool(Source: string; def: boolean): boolean;
begin
Result := def;
Source := Trim(Source);
if Source <> '' then
begin
if pos(Source[1], 'tTeE1+yYรครรฏร') > 0 then
Result := true
else
if pos(Source[1], 'fFdD0-nNรญรรซร') > 0 then
Result := false;
end;
end;
function str2float(const Source: string): double;
var
j: integer;
s: string;
begin
s := '';
for j := 1 to Length(Source) do
case Source[j] of
'0' .. '9':
s := s + Source[j];
'.', ',':
if s = '' then
s := '0.'
else
s := s + FormatSettings.DecimalSeparator;
'-':
if s = '' then
s := '-';
end;
if (s = '') or (s = '-') then
Result := 0
else
begin
if s[Length(s)] = '.' then
s := s + '0';
Result := StrToFloat(s);
end;
end;
function str2barcode(const Source: string; Count: word): string;
begin
Result := str2digits(Source);
if Length(Result) > Count then
Result := copy(Result, 1, Count)
else
begin
while Length(Result) < Count do
Result := '0' + Result;
end;
end;
function str2ean13(const src: string): uint64;
const
nn: array [1 .. 12] of byte = (1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3);
var
s, ss: integer;
buff: string;
begin
buff := str2digits(src);
if Length(buff) < 2 then
begin
Result := 0;
Exit;
end;
if Length(buff) > 13 then
buff := copy(buff, Length(buff) - 12)
else
while Length(buff) < 13 do
buff := '0' + buff;
ss := 0;
for s := 1 to 12 do
Inc(ss, StrToInt(buff[s]) * nn[s]);
s := round(int(ss / 10));
if ss > (10 * s) then
Inc(s);
buff[13] := IntToStr((10 * s) - ss)[1];
Result := StrToUInt64(copy(buff, 1, 13));
end;
function getname(const src: string): string;
var
j: integer;
begin
if src = '' then
Result := ''
else
begin
j := pos('=', src);
if j > 0 then
Result := Trim(copy(src, 1, j - 1))
else
Result := Trim(src);
end;
end;
end.
|
unit EntryFormatting;
{
Formats EDICT entries in several common text formats used in these utilities.
}
interface
uses UniStrUtils, Edict;
{
XSLT formatting.
Usage:
xslt := TEntryFormatter.Create('filename.xslt');
Result := xslt.Transform(entry);
Result := xslt.Transform(EdictEntryToXml(entry1) + EdictEntryToXml(entry2));
}
var
OutputXml: boolean;
procedure SetXsltSchema(const AFilename: string);
procedure FreeXsltSchema;
function FormatEntry(AEntry: PEdictEntry): WideString;
procedure FormatEntryAdd(var AText: string; AEntry: PEdictEntry);
function FormatEntryFinalize(const AText: string): string;
implementation
uses SysUtils, StrUtils, ActiveX, XmlDoc, XmlIntf, EdictReader;
function EdictSensesToText(entry: PEdictEntry): string; forward;
function EdictEntryToXml(entry: PEdictEntry): string; forward;
function EdictSensesToText(entry: PEdictEntry): string;
begin
Result := UniReplaceStr(entry.AllSenses, '/', ', ');
end;
function EdictEntryToXml(entry: PEdictEntry): string;
var i, j: integer;
parts: UniStrUtils.TStringArray;
kanji: PKanjiEntry;
kana: PKanaEntry;
sense: PSenseEntry;
begin
//Note: Everything must be escaped. "&" often appears in fields.
Result := '<entry>'
+'<ref>'+HtmlEscape(entry.ref)+'</ref>';
for i := 0 to Length(entry.kanji)-1 do begin
kanji := @entry.kanji[i];
Result := Result+'<expr>'+HtmlEscape(kanji.kanji);
for j := 1 to Length(kanji.markers) do
Result := Result + '<mark>' + HtmlEscape(GetMarkerText(kanji.markers[j]))+'</mark>';
Result := Result + '</expr>';
end;
for i := 0 to Length(entry.kana)-1 do begin
kana := @entry.kana[i];
Result := Result+'<read>'+HtmlEscape(kana.kana);
for j := 1 to Length(kana.markers) do
Result := Result + '<mark>' + HtmlEscape(GetMarkerText(kana.markers[j]))+'</mark>';
Result := Result+'</read>';
end;
for i := 0 to Length(entry.senses)-1 do begin
sense := @entry.senses[i];
Result := Result+'<sense>';
parts := StrSplit(PChar(sense.text), '/');
for j := 0 to Length(parts)-1 do
Result := Result+'<gloss>'+HtmlEscape(Trim(parts[j]))+'</gloss>';
for j := 1 to Length(sense.pos) do
Result := Result+'<pos>'+HtmlEscape(GetMarkerText(sense.pos[j]))+'</pos>';
for j := 1 to Length(sense.markers) do
Result := Result+'<mark>'+HtmlEscape(GetMarkerText(sense.markers[j]))+'</mark>';
Result := Result+'</sense>';
end;
if entry.pop then
Result := Result + '<pop />';
Result := Result + '</entry>';
end;
{ Entry formatting }
var
iInp, iXsl: IXMLDocument;
procedure SetXsltSchema(const AFilename: string);
begin
FreeXsltSchema;
if AFilename<>'' then begin
CoInitialize(nil);
iInp := TXMLDocument.Create(nil);
iXsl := LoadXMLDocument(AFilename);
OutputXml := true;
end;
end;
procedure FreeXsltSchema;
begin
iInp := nil;
//Release
if iXsl<>nil then begin
iXsl := nil;
CoUninitialize;
end;
end;
function FormatEntryXml(const entryXml: UnicodeString): WideString;
begin
if iXsl<>nil then begin
iInp.LoadFromXML(entryXml);
iInp.Node.TransformNode(iXsl.Node, Result);
end else
Result := entryXml;
end;
//Formats EDICT entry according to current settings
function FormatEntry(AEntry: PEdictEntry): WideString;
begin
if not OutputXml then
Result := EdictSensesToText(AEntry)
else
Result := FormatEntryXml(EdictEntryToXml(AEntry));
end;
//Add() several entries to format them together as a single operation -
//this is supported by XSLT schema.
procedure FormatEntryAdd(var AText: string; AEntry: PEdictEntry);
var entry_text: string;
begin
if not OutputXml then begin
entry_text := EdictSensesToText(AEntry);
if AText<>'' then
AText := AText + '; ' + entry_text
else
AText := entry_text;
end else begin
entry_text := EdictEntryToXml(AEntry);
AText := AText + entry_text;
//will call xslt at the end
end;
end;
//Finalize formatting for entries you have added together with FormatEntryAdd().
function FormatEntryFinalize(const AText: string): string;
begin
if not OutputXml then
Result := AText
else
Result := FormatEntryXml(AText);
end;
end.
|
{************************************************}
{* *}
{* AIMP Programming Interface *}
{* Menu Wrappers *}
{* *}
{* Artem Izmaylov *}
{* (C) 2006-2017 *}
{* www.aimp.ru *}
{* Mail: support@aimp.ru *}
{* *}
{************************************************}
unit apiWrappersMenus;
{$I apiConfig.inc}
interface
uses
Classes,
Generics.Collections,
// API
apiActions,
apiMenu,
apiMusicLibrary,
apiObjects,
apiPlaylists,
apiWrappers;
const
RT_PNG = 'PNG';
type
//----------------------------------------------------------------------------------------------------------------------
// Basic
//----------------------------------------------------------------------------------------------------------------------
TAIMPUICustomMenuItem = class;
TAIMPUIMenuItemStates = (isEnabled, isVisible);
TAIMPUIMenuItemState = set of TAIMPUIMenuItemStates;
{ IAIMPUIMenuItemController }
IAIMPUIMenuItemController = interface(IAIMPActionEvent)
['{3F4AA204-E1BC-4EC9-AC70-3F74F5225604}']
procedure Bind(Handle: IAIMPMenuItem; MenuItem: TAIMPUICustomMenuItem);
function IsAvailable: Boolean;
end;
{ TAIMPUICustomMenuItem }
TAIMPUICustomMenuItem = class abstract(TInterfacedObject, IAIMPActionEvent)
strict private
FController: IAIMPUIMenuItemController;
FID: UnicodeString;
protected
function GetGlyphResName: string; virtual;
function GetState: TAIMPUIMenuItemState; virtual;
// IAIMPActionEvent
procedure OnExecute(Sender: IUnknown); virtual; stdcall; abstract;
//
procedure UpdateGlyph(AMenuItem: IAIMPMenuItem);
procedure UpdateState; overload;
procedure UpdateState(AMenuItem: IAIMPMenuItem); overload; virtual;
//
property Controller: IAIMPUIMenuItemController read FController;
public
constructor Create(AController: IAIMPUIMenuItemController);
procedure Register(const ID: UnicodeString; const ParentID: Variant);
end;
{ TAIMPUILineMenuItem }
TAIMPUILineMenuItem = class(TAIMPUICustomMenuItem)
protected
procedure OnExecute(Sender: IInterface); override; stdcall;
procedure UpdateState(AMenuItem: IAIMPMenuItem); override;
end;
{ TAIMPUICustomMenuItemController }
TAIMPUICustomMenuItemController = class abstract(TInterfacedObject,
IAIMPActionEvent,
IAIMPUIMenuItemController)
strict private
FIsAvailable: Boolean;
FMenuItems: TList;
// IAIMPUIMenuItemController
procedure Bind(Handle: IAIMPMenuItem; MenuItem: TAIMPUICustomMenuItem);
function IsAvailable: Boolean;
// IAIMPActionEvent
procedure OnExecute(Data: IInterface); stdcall;
protected
function CheckData: Boolean; virtual; abstract;
public
constructor Create;
destructor Destroy; override;
procedure Refresh;
end;
//----------------------------------------------------------------------------------------------------------------------
// Files Providers
//----------------------------------------------------------------------------------------------------------------------
TAIMPFileListClass = class of TAIMPFileList;
TAIMPFileList = class(TStringList)
strict private
FFocusIndex: Integer;
function GetFocused: string;
public
procedure Add(const FileURI: IAIMPString); reintroduce; overload;
procedure AfterConstruction; override;
procedure Clear; override;
procedure MarkFocused(const FileURI: string); overload; virtual;
procedure MarkFocused(const FileURI: IAIMPString); overload;
//
property Focused: string read GetFocused;
property FocusIndex: Integer read FFocusIndex write FFocusIndex;
end;
IAIMPUIFileBasedMenuItemController = interface
['{B9FB51EF-0637-45A8-AF38-21C03C818AE7}']
function GetFiles: TAIMPFileList;
end;
{ TAIMPUICustomFileBasedMenuItemController }
TAIMPUICustomFileBasedMenuItemController = class abstract(TAIMPUICustomMenuItemController,
IAIMPUIFileBasedMenuItemController)
strict private
FFiles: TAIMPFileList;
// IAIMPUIFileBasedMenuItemController
function GetFiles: TAIMPFileList;
protected
function CheckData: Boolean; override;
function CheckIsOurStorage: Boolean; virtual;
procedure QueryFiles(AFiles: TAIMPFileList); virtual; abstract;
public
constructor Create; overload;
constructor Create(AFileListClass: TAIMPFileListClass); overload;
destructor Destroy; override;
end;
{ TAIMPUIMusicLibraryBasedMenuItemController }
TAIMPUIMusicLibraryBasedMenuItemController = class(TAIMPUICustomFileBasedMenuItemController)
protected
procedure QueryFiles(AFiles: TAIMPFileList); override;
end;
{ TAIMPUIPlaylistBasedMenuItemController }
TAIMPUIPlaylistBasedMenuItemController = class(TAIMPUICustomFileBasedMenuItemController)
strict private
function GetFocusedFileName(Playlist: IAIMPPlaylist; out FileURI: IAIMPString): Boolean;
protected
procedure QueryFiles(AFiles: TAIMPFileList); override;
end;
procedure AddSimpleMenuItem(AParent: IAIMPMenuItem; const ATitle: string; AEvent: IUnknown); overload;
procedure AddSimpleMenuItem(AParent: Integer; const ATitle: string; AEvent: IUnknown); overload;
implementation
uses
Windows, SysUtils, Variants, Math;
const
sErrorAlreadyRegistered = 'The instance is already registered as handler for %s menu';
sErrorDuplicateID = 'The %s ID is already registered';
sErrorNoID = 'Cannot register menu item without ID';
procedure AddSimpleMenuItem(AParent: IAIMPMenuItem; const ATitle: string; AEvent: IUnknown); overload;
var
ASubItem: IAIMPMenuItem;
begin
CoreCreateObject(IAIMPMenuItem, ASubItem);
PropListSetStr(ASubItem, AIMP_MENUITEM_PROPID_NAME, ATitle);
PropListSetObj(ASubItem, AIMP_MENUITEM_PROPID_PARENT, AParent);
PropListSetObj(ASubItem, AIMP_MENUITEM_PROPID_EVENT, AEvent);
CoreIntf.RegisterExtension(IAIMPServiceMenuManager, ASubItem);
end;
procedure AddSimpleMenuItem(AParent: Integer; const ATitle: string; AEvent: IUnknown); overload;
var
AMenuItem: IAIMPMenuItem;
AService: IAIMPServiceMenuManager;
begin
if CoreGetService(IAIMPServiceMenuManager, AService) then
begin
if Succeeded(AService.GetBuiltIn(AParent, AMenuItem)) then
AddSimpleMenuItem(AMenuItem, ATitle, AEvent);
end;
end;
//----------------------------------------------------------------------------------------------------------------------
// Basic
//----------------------------------------------------------------------------------------------------------------------
{ TAIMPUICustomMenuItem }
constructor TAIMPUICustomMenuItem.Create(AController: IAIMPUIMenuItemController);
begin
FController := AController;
end;
procedure TAIMPUICustomMenuItem.Register(const ID: UnicodeString; const ParentID: Variant);
var
AHandle: IAIMPMenuItem;
AParentHandle: IAIMPMenuItem;
AService: IAIMPServiceMenuManager;
begin
if CoreGetService(IAIMPServiceMenuManager, AService) then
begin
if FID <> '' then
raise EInvalidInsert.CreateFmt(sErrorAlreadyRegistered, [FID]);
if ID = '' then
raise EInvalidOp.Create(sErrorNoID);
if Succeeded(AService.GetByID(MakeString(ID), AHandle)) then
raise EInvalidInsert.CreateFmt(sErrorDuplicateID, [ID]);
FID := ID;
if VarIsStr(ParentID) then
CheckResult(AService.GetByID(MakeString(ParentID), AParentHandle))
else
CheckResult(AService.GetBuiltIn(ParentID, AParentHandle));
CoreCreateObject(IAIMPMenuItem, AHandle);
if Controller <> nil then
Controller.Bind(AHandle, Self);
PropListSetStr(AHandle, AIMP_MENUITEM_PROPID_ID, ID);
PropListSetObj(AHandle, AIMP_MENUITEM_PROPID_EVENT, Self);
PropListSetObj(AHandle, AIMP_MENUITEM_PROPID_PARENT, AParentHandle);
CoreIntf.RegisterExtension(IAIMPServiceMenuManager, AHandle);
end;
end;
function TAIMPUICustomMenuItem.GetGlyphResName: string;
begin
Result := '';
end;
function TAIMPUICustomMenuItem.GetState: TAIMPUIMenuItemState;
begin
if Controller.IsAvailable then
Result := [isEnabled, isVisible]
else
Result := [];
end;
procedure TAIMPUICustomMenuItem.UpdateGlyph(AMenuItem: IAIMPMenuItem);
function GetActualResName(ATargetDPI: Integer): string;
const
SupportedDPI: array[0..3] of Integer = (120, 144, 168, 192);
var
AIndex: Integer;
begin
for AIndex := Low(SupportedDPI) to High(SupportedDPI) do
if ATargetDPI >= SupportedDPI[AIndex] then
begin
Result := GetGlyphResName + IntToStr(SupportedDPI[AIndex]);
if FindResource(HInstance, PWideChar(Result), RT_PNG) <> 0 then
Exit;
end;
Result := GetGlyphResName;
end;
var
AGlyph: IAIMPImage2;
AGlyphName: string;
ASourceDPI: IAIMPDPIAware;
ATargetDPI: IAIMPDPIAware;
begin
AGlyphName := GetGlyphResName;
if AGlyphName <> '' then
try
CoreCreateObject(IAIMPImage2, AGlyph);
if Supports(AMenuItem, IAIMPDPIAware, ASourceDPI) and Supports(AGlyph, IAIMPDPIAware, ATargetDPI) then
begin
ATargetDPI.SetDPI(ASourceDPI.GetDPI);
if ATargetDPI.GetDPI > 96 then
AGlyphName := GetActualResName(ATargetDPI.GetDPI);
end;
CheckResult(AGlyph.LoadFromResource(HInstance, PWideChar(AGlyphName), RT_PNG));
PropListSetObj(AMenuItem, AIMP_MENUITEM_PROPID_GLYPH, AGlyph);
except
// do nothing
end;
end;
procedure TAIMPUICustomMenuItem.UpdateState;
var
AMenuItem: IAIMPMenuItem;
AService: IAIMPServiceMenuManager;
begin
if FID <> '' then
begin
if CoreGetService(IAIMPServiceMenuManager, AService) and Succeeded(AService.GetByID(MakeString(FID), AMenuItem)) then
begin
UpdateGlyph(AMenuItem);
UpdateState(AMenuItem);
end;
end;
end;
procedure TAIMPUICustomMenuItem.UpdateState(AMenuItem: IAIMPMenuItem);
var
AState: TAIMPUIMenuItemState;
begin
AState := GetState;
PropListSetInt32(AMenuItem, AIMP_MENUITEM_PROPID_ENABLED, Ord(isEnabled in AState));
PropListSetInt32(AMenuItem, AIMP_MENUITEM_PROPID_VISIBLE, Ord(isVisible in AState));
end;
{ TAIMPUILineMenuItem }
procedure TAIMPUILineMenuItem.OnExecute(Sender: IInterface);
begin
// do nothing
end;
procedure TAIMPUILineMenuItem.UpdateState(AMenuItem: IAIMPMenuItem);
begin
inherited;
PropListSetStr(AMenuItem, AIMP_MENUITEM_PROPID_NAME, '-');
end;
{ TAIMPUICustomMenuItemController }
constructor TAIMPUICustomMenuItemController.Create;
begin
inherited Create;
FMenuItems := TList.Create;
end;
destructor TAIMPUICustomMenuItemController.Destroy;
begin
FreeAndNil(FMenuItems);
inherited Destroy;
end;
procedure TAIMPUICustomMenuItemController.Bind(Handle: IAIMPMenuItem; MenuItem: TAIMPUICustomMenuItem);
begin
FMenuItems.Add(MenuItem);
if FMenuItems.Count = 1 then
PropListSetObj(Handle, AIMP_MENUITEM_PROPID_EVENT_ONSHOW, Self);
end;
function TAIMPUICustomMenuItemController.IsAvailable: Boolean;
begin
Result := FIsAvailable;
end;
procedure TAIMPUICustomMenuItemController.OnExecute(Data: IInterface);
begin
Refresh;
end;
procedure TAIMPUICustomMenuItemController.Refresh;
var
AIndex: Integer;
begin
FIsAvailable := CheckData;
for AIndex := 0 to FMenuItems.Count - 1 do
TAIMPUICustomMenuItem(FMenuItems.List[AIndex]).UpdateState;
end;
{ TAIMPFileList }
procedure TAIMPFileList.Add(const FileURI: IAIMPString);
begin
Add(IAIMPStringToString(FileURI));
end;
procedure TAIMPFileList.AfterConstruction;
begin
inherited;
CaseSensitive := False;
FocusIndex := -1;
end;
procedure TAIMPFileList.Clear;
begin
inherited;
FocusIndex := -1;
end;
procedure TAIMPFileList.MarkFocused(const FileURI: IAIMPString);
begin
MarkFocused(IAIMPStringToString(FileURI));
end;
procedure TAIMPFileList.MarkFocused(const FileURI: string);
begin
FocusIndex := IndexOf(FileURI);
end;
function TAIMPFileList.GetFocused: string;
begin
Result := Strings[FocusIndex];
end;
{ TAIMPUICustomFileBasedMenuItemController }
constructor TAIMPUICustomFileBasedMenuItemController.Create;
begin
Create(TAIMPFileList);
end;
constructor TAIMPUICustomFileBasedMenuItemController.Create(AFileListClass: TAIMPFileListClass);
begin
inherited Create;
FFiles := AFileListClass.Create;
end;
destructor TAIMPUICustomFileBasedMenuItemController.Destroy;
begin
FreeAndNil(FFiles);
inherited Destroy;
end;
function TAIMPUICustomFileBasedMenuItemController.CheckData: Boolean;
begin
FFiles.Clear;
Result := CheckIsOurStorage;
if Result then
QueryFiles(FFiles);
end;
function TAIMPUICustomFileBasedMenuItemController.CheckIsOurStorage: Boolean;
begin
Result := True;
end;
function TAIMPUICustomFileBasedMenuItemController.GetFiles: TAIMPFileList;
begin
Result := FFiles;
end;
{ TAIMPUIMusicLibraryBasedMenuItemController }
procedure TAIMPUIMusicLibraryBasedMenuItemController.QueryFiles(AFiles: TAIMPFileList);
var
AFileURI: IAIMPString;
AIndex: Integer;
AList: IAIMPMLFileList;
AService: IAIMPServiceMusicLibraryUI;
begin
if CoreGetService(IAIMPServiceMusicLibraryUI, AService) then
begin
if Succeeded(AService.GetFiles(AIMPML_GETFILES_FLAGS_SELECTED, AList)) then
begin
AFiles.Capacity := AList.GetCount;
for AIndex := 0 to AList.GetCount - 1 do
begin
if Succeeded(AList.GetFileName(AIndex, AFileURI)) then
AFiles.Add(AFileURI);
end;
if Succeeded(AService.GetFiles(AIMPML_GETFILES_FLAGS_FOCUSED, AList)) then
begin
if (AList.GetCount > 0) and Succeeded(AList.GetFileName(0, AFileURI)) then
AFiles.MarkFocused(AFileURI);
end;
end;
end;
end;
{ TAIMPUIPlaylistBasedMenuItemController }
procedure TAIMPUIPlaylistBasedMenuItemController.QueryFiles(AFiles: TAIMPFileList);
var
AFileURI: IAIMPString;
AList: IAIMPObjectList;
APlaylist: IAIMPPlaylist;
AService: IAIMPServicePlaylistManager;
AIndex: Integer;
begin
if CoreGetService(IAIMPServicePlaylistManager, AService) and Succeeded(AService.GetActivePlaylist(APlaylist)) then
begin
if Succeeded(APlaylist.GetFiles(AIMP_PLAYLIST_GETFILES_FLAGS_SELECTED_ONLY, AList)) then
begin
AFiles.Capacity := AList.GetCount;
for AIndex := 0 to AList.GetCount - 1 do
begin
if Succeeded(AList.GetObject(AIndex, IAIMPString, AFileURI)) then
AFiles.Add(AFileURI);
end;
//TODO - FIXME - This is not ready for duplicates
if GetFocusedFileName(APlaylist, AFileURI) then
AFiles.MarkFocused(AFileURI);
end;
end;
end;
function TAIMPUIPlaylistBasedMenuItemController.GetFocusedFileName(Playlist: IAIMPPlaylist; out FileURI: IAIMPString): Boolean;
var
AGroup: IAIMPPlaylistGroup;
AItem: IAIMPPlaylistItem;
AProperties: IAIMPPropertyList;
begin
Result := False;
if Supports(Playlist, IAIMPPropertyList, AProperties) then
begin
if
Succeeded(AProperties.GetValueAsObject(AIMP_PLAYLIST_PROPID_FOCUSED_OBJECT, IAIMPPlaylistItem, AItem)) or
Succeeded(AProperties.GetValueAsObject(AIMP_PLAYLIST_PROPID_FOCUSED_OBJECT, IAIMPPlaylistGroup, AGroup)) and
Succeeded(AGroup.GetItem(0, IAIMPPlaylistItem, AItem))
then
if PropListGetInt32(AItem, AIMP_PLAYLISTITEM_PROPID_SELECTED) <> 0 then
Result := Succeeded(AItem.GetValueAsObject(AIMP_PLAYLISTITEM_PROPID_FILENAME, IAIMPString, FileURI));
end;
end;
end.
|
unit uSubStationAlphaFile;
{ SubStationAlpha file (ssa ver 4 and 4+ (ass)) decoder, encoder and more.
written with GUI interaction in mind.
Copyright (C) 2018 Mohammadreza Bahrami m.audio91@gmail.com
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1335, USA.
}
{$mode objfpc}{$H+}{$MODESWITCH ADVANCEDRECORDS}
interface
uses
Classes, SysUtils, FPImage, strutils, Graphics, uGenericSubtitleFile,
uTimeSlice, uMinimalList, CommonStrUtils, CommonNumeralUtils;
type
{ TCustomAlphaInfoManager }
TCustomAlphaInfoManager = specialize TMinimalList<String>;
{ TAlphaInfoManager }
TAlphaInfoManager = class(TCustomAlphaInfoManager)
public
function IndexOf(const AItem: String): Integer;
function New: Integer; override;
function Add(AItem: String): Integer; override;
procedure RemoveComments;
function ToText(IsAdvanced: Boolean = True): String;
end;
{ TAlphaStyle }
TAlphaStyle = record
private
FName: String;
FScaleX,
FScaleY: Integer; //0..100
FAngle: Double; //0..360
FBorderStyle, //1 or 3
FOutline, //0..4
FShadow, //0..4
//SSA alignment is sub: 1,2,3, top(4+sub): 5,6,7, mid(8+sub): 9,10,11. ASS is (1..3 sub, 4..6 mid, 7..9 top).
FAlignment: Integer;
procedure SetName(AValue: String);
procedure SetScaleX(AValue: Integer);
procedure SetScaleY(AValue: Integer);
procedure SetAngle(AValue: Double);
procedure SetBorderStyle(AValue: Integer);
procedure SetOutline(AValue: Integer);
procedure SetShadow(AValue: Integer);
procedure SetAlignment(AValue: Integer);
public
Fontname: String;
PrimaryColour,
SecondaryColour,
OutlineColour,
BackColour: TFPColor;
Bold,
Italic,
Underline,
StrikeOut: Boolean;
Fontsize,
Spacing,
MarginL,
MarginR,
MarginV,
AlphaLevel,
Encoding: LongWord;
property Name: String read FName write SetName;
property ScaleX: Integer read FScaleX write SetScaleX;
property ScaleY: Integer read FScaleY write SetScaleY;
property Angle: Double read FAngle write SetAngle;
property BorderStyle: Integer read FBorderStyle write SetBorderStyle;
property Outline: Integer read FOutline write SetOutline;
property Shadow: Integer read FShadow write SetShadow;
property Alignment: Integer read FAlignment write SetAlignment;
function ParseFromString(const AStyle: String; IsAdvanced: Boolean = True)
: Boolean;
function ToString(IsAdvanced: Boolean = True): String;
end;
{ TCustomAlphaStyleManager }
TCustomAlphaStyleManager = specialize TMinimalList<TAlphaStyle>;
{ TAlphaStyleManager }
TAlphaStyleManager = class(TCustomAlphaStyleManager)
private
function GetUniqueName(const AName: String): String;
public
function New: Integer; override;
function Add(AItem: TAlphaStyle): Integer; override;
function ToText(IsAdvanced: Boolean = True): String;
end;
{ TAlphaEventType }
TAlphaEventType = (aeDialogue,aeComment,aePicture,aeSound,aeMovie,aeCommand);
{ TAlphaEvent }
TAlphaEvent = record
private
FStyle,
FName,
FEffect: String;
procedure SetStyle(const AValue: String);
procedure SetName(const AValue: String);
procedure SetEffect(const AValue: String);
public
TimeSlice: TTimeSlice;
LayerOrMarked,
MarginL,
MarginR,
MarginV: Integer;
Text: String;
EventType: TAlphaEventType;
property Style: String read FStyle write SetStyle;
property Name: String read FName write SetName;
property Effect: String read FEffect write SetEffect;
function ParseFromString(const AEvent: String): Boolean;
function ToString(IsAdvanced: Boolean = True): String;
end;
{ TCustomSubStationAlphaFile }
TCustomSubStationAlphaFile = specialize TGenericSubtitleFile<TAlphaEvent>;
{ TSubStationAlphaFile: not a completed class. still can be extended with
other functionalities like [Fonts] and [Graphics] handling.
more ssa info can be found on:
https://www.paralog.net/files/SubTitler/SSA4%20Spec.doc
https://wiki.multimedia.cx/index.php/SubStation_Alpha
https://www.matroska.org/technical/specs/subtitles/ssa.html }
TSubStationAlphaFile = class(TCustomSubStationAlphaFile)
private
FAlphaIsAdvanced: Boolean;
procedure ConvertToAdvancedAlpha; // ToDo: Extend these methods to convert alpha overrides as well (such as {\b0} etc)
procedure ConvertToOldAlpha; // not safe currently. look at the above comment.
procedure SetAdvanced(AValue: Boolean);
public
Infos: TAlphaInfoManager;
Styles: TAlphaStyleManager;
property AlphaIsAdvanced: Boolean read FAlphaIsAdvanced write SetAdvanced;
procedure LoadFromString(const AContents: String); override;
procedure SaveToString(out AContents: String); override;
constructor Create; override;
destructor Destroy; override;
end;
function DefaultAlphaStyle: TAlphaStyle;
function DefaultAlphaEvent: TAlphaEvent;
//to translate alignment from two ComboBoxes, one for H pos (0=left, 1=center
//, 2=right) and one for V pos(0=top, 1=center, 2=bottom) use the three following
//fuctions but beaware these are assuming advanced alpha (v4.00+) style values
//by default: 1..9. you can change the third parameter to False to have ssa
//(v4.00) align.
function HVAlignToAlphaAlign(AHorizontalValue, AVerticalValue: Integer;
IsAdvanced: Boolean = True): Integer;
function GetHorizontalAlign(AAlphaAlign: Integer): Integer;
function GetVerticalAlign(AAlphaAlign: Integer): Integer;
//additional alignment conversion functions
function AlphaOldAlignToAdvancedAlign(A: Integer): Integer;
function AlphaAdvancedAlignToOldAlign(A: Integer): Integer;
//color translation functions from GUI and back
//AColor can be from a TColorButton etc and AALphaPercent can be from
//a TSpinEdit with it's Min=0=>transparent and it's Max=100=>visible
function FPColor(AColor: TColor; AALphaPercent: Integer): TFPColor; overload;
function AlphaPercentFromFPColor(AColor: TFPColor): Integer;
function AlphaColorToFPColor(const C: String): TFPColor;
function FPColorToAlphaColor(const C: TFPColor; IsAdvanced: Boolean): String;
implementation
const
AlphaSep = ',';
AlphaSepReplacement = ';';
AlphaInfoHeader = '[Script Info]';
AlphaVersionMarker = 'ScriptType: ';
AlphaVersionValue = 'v4.00+';
OldAlphaVersionValue = 'v4.00';
AlphaStylesHeader = '[V4+ Styles]';
OldAlphaStylesHeader = '[V4 Styles]';
AlphaStylesHint = 'Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour,'
+'OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, '
+'Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding';
OldAlphaStylesHint = 'Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, '
+'TertiaryColour, BackColour, Bold, Italic, BorderStyle, Outline, Shadow, Alignment, '
+'MarginL, MarginR, MarginV, AlphaLevel, Encoding';
AlphaStyleFormatMarker = 'Format: ';
AlphaStyleMarker = 'Style: ';
AlphaEventsHeader = '[Events]';
AlphaEventsHint = 'Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text';
OldAlphaEventsHint = 'Format: Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text';
OldAlphaMarkers: array[0..1] of String = ('Marked=','AlphaLevel');
AlphaDialogueMarker = 'Dialogue: ';
AlphaCommentMarker = 'Comment: ';
AlphaPictureMarker = 'Picture: ';
AlphaSoundMarker = 'Sound: ';
AlphaMovieMarker = 'Movie: ';
AlphaCommandMarker = 'Command: ';
AlphaEventMarkers: array[0..5] of String = (AlphaDialogueMarker,AlphaCommentMarker,
AlphaPictureMarker,AlphaSoundMarker,AlphaMovieMarker,AlphaCommandMarker);
AlphaDialogueDefaultText = 'hi there, I am a Sub Station Alpha dialog!';
function AlphaColorToFPColor(const C: String): TFPColor;
begin
if (C.StartsWith('&H')) then
begin
if (C.Length = 10) then
Result := FPColor(
Hex2Dec(C.Substring(8,2)),
Hex2Dec(C.Substring(6,2)),
Hex2Dec(C.Substring(4,2)),
Hex2Dec(C.Substring(2,2)))
else if (C.Length = 8) then
Result := FPColor(
Hex2Dec(C.Substring(6,2)),
Hex2Dec(C.Substring(4,2)),
Hex2Dec(C.Substring(2,2)),
0)
end
else
Result := FPColor(
(C.ToInteger and $FF),
((C.ToInteger shr 8) and $FF),
((C.ToInteger shr 16) and $FF),
0);
end;
function FPColorToAlphaColor(const C: TFPColor; IsAdvanced: Boolean)
: String;
begin
if IsAdvanced then
Result := '&H'
+Dec2Numb(C.alpha, 2, 16)
+Dec2Numb(C.blue, 2, 16)
+Dec2Numb(C.green, 2, 16)
+Dec2Numb(C.red, 2, 16)
else
Result := Numb2Dec(
Dec2Numb(C.blue, 2, 16)
+Dec2Numb(C.green, 2, 16)
+Dec2Numb(C.red, 2, 16) ,16).ToString;
end;
function AlphaOldAlignToAdvancedAlign(A: Integer): Integer;
begin
Result := 2;
case A of
1..3: Result := A;
5: Result := 4;
6: Result := 5;
7: Result := 6;
9: Result := 7;
10: Result := 8;
11: Result := 9;
end;
end;
function AlphaAdvancedAlignToOldAlign(A: Integer): Integer;
begin
Result := 2;
case A of
1..3: Result := A;
4: Result := 5;
5: Result := 6;
6: Result := 7;
7: Result := 9;
8: Result := 10;
9: Result := 11;
end;
end;
function FPColor(AColor: TColor; AALphaPercent: Integer): TFPColor;
begin
Result.blue := Blue(Cardinal(AColor));
Result.green := Green(Cardinal(AColor));
Result.red := Red(Cardinal(AColor));
ForceInRange(AALphaPercent,0,100);
AALphaPercent := ConvertInRange(AALphaPercent,0,100,0,255);
AALphaPercent := 255-AALphaPercent;
Result.alpha := AALphaPercent;
end;
function AlphaPercentFromFPColor(AColor: TFPColor): Integer;
begin
Result := AColor.alpha;
Result := ConvertInRange(Result,0,255,0,100);
Result := 100-Result;
end;
function DefaultAlphaStyle: TAlphaStyle;
begin
with Result do
begin
Name := 'Default';
Fontname := 'Arial';
Fontsize := 20;
PrimaryColour := AlphaColorToFPColor('&H00FFFFFF');
SecondaryColour := AlphaColorToFPColor('&H000000FF');
OutlineColour := AlphaColorToFPColor('&H00000000');
BackColour := AlphaColorToFPColor('&H00000000');
Bold := False;
Italic := False;
Underline := False;
StrikeOut := False;
ScaleX := 100;
ScaleY := 100;
Spacing := 0;
Angle := 0;
BorderStyle := 1;
Outline := 2;
Shadow := 2;
Alignment := 2;
MarginL := 10;
MarginR := 10;
MarginV := 10;
AlphaLevel := 0;
Encoding := 1;
end;
end;
function DefaultAlphaEvent: TAlphaEvent;
begin
with Result do
begin
TimeSlice.Reset;
TimeSlice.Value.StartPos.ValueAsDouble := 120;
LayerOrMarked := 0;
MarginL := 0;
MarginR := 0;
MarginV := 0;
Text := AlphaDialogueDefaultText;
EventType := aeDialogue;
Style := DefaultAlphaStyle.Name;
Name := EmptyStr;
Effect := EmptyStr;
end;
end;
function HVAlignToAlphaAlign(AHorizontalValue, AVerticalValue: Integer;
IsAdvanced: Boolean): Integer;
var
v: Byte;
begin
ForceInRange(AHorizontalValue, 0, 2);
ForceInRange(AVerticalValue, 0, 2);
v := 1;
if IsAdvanced then
begin
case AVerticalValue of
0: v := 7;
1: v := 4;
end;
end
else
begin
case AVerticalValue of
0: v := 5;
1: v := 9;
end;
end;
Result := AHorizontalValue+v;
end;
function GetHorizontalAlign(AAlphaAlign: Integer): Integer;
begin
if AAlphaAlign in [1,4,7] then
Result := 0
else if AAlphaAlign in [3,6,9] then
Result := 2
else
Result := 1;
end;
function GetVerticalAlign(AAlphaAlign: Integer): Integer;
begin
if AAlphaAlign in [7,8,9] then
Result := 0
else if AAlphaAlign in [4,5,6] then
Result := 1
else
Result := 2;
end;
{ TAlphaInfoManager }
function TAlphaInfoManager.IndexOf(const AItem: String): Integer;
var
i: Integer;
begin
Result := -1;
for i := 0 to Count-1 do
if Items[i].Contains(AItem) then
Exit(i);
end;
function TAlphaInfoManager.New: Integer;
begin
Result := inherited New;
Items[Result] := '; ';
end;
function TAlphaInfoManager.Add(AItem: String): Integer;
var
i: Integer;
begin
i := IndexOf(AItem.Split(':')[0]);
if i >= 0 then
begin
Items[i] := AItem;
Result := i;
end
else
begin
Result := inherited Add(AItem);
if not IsEmptyStr(AItem) then
Items[Result] := AItem;
end;
end;
procedure TAlphaInfoManager.RemoveComments;
var
i: Integer;
begin
for i := Count-1 downto 0 do
if Items[i].StartsWith(';') or Items[i].StartsWith('!:')then
Remove(i);
end;
function TAlphaInfoManager.ToText(IsAdvanced: Boolean): String;
var
sa: TStringArray;
s: String;
i: Integer;
begin
Result := EmptyStr;
if IsAdvanced then
s := AlphaVersionValue
else
s := OldAlphaVersionValue;
i := IndexOf(AlphaVersionMarker);
if i >= 0 then
Items[i] := AlphaVersionMarker +s
else
Add(AlphaVersionMarker +s);
SetLength(sa, Count);
for i := 0 to Count-1 do
sa[i] := Items[i];
RemoveDupsInArray(sa);
Result := Result.Join(LineEnding,sa) +LineEnding;
end;
{ TAlphaStyle }
procedure TAlphaStyle.SetName(AValue: String);
begin
FName := AValue.Replace(AlphaSep, AlphaSepReplacement);
end;
procedure TAlphaStyle.SetScaleX(AValue: Integer);
begin
FScaleX := AValue;
ForceInRange(FScaleX, 0, 100);
end;
procedure TAlphaStyle.SetScaleY(AValue: Integer);
begin
FScaleY := AValue;
ForceInRange(FScaleY, 0, 100);
end;
procedure TAlphaStyle.SetAngle(AValue: Double);
begin
FAngle := AValue;
ForceInRange(FAngle, 0, 360);
end;
procedure TAlphaStyle.SetBorderStyle(AValue: Integer);
begin
FBorderStyle := AValue;
if not FBorderStyle in [1,3] then
FBorderStyle := 1;
end;
procedure TAlphaStyle.SetOutline(AValue: Integer);
begin
FOutline := AValue;
ForceInRange(FOutline, 0, 4);
end;
procedure TAlphaStyle.SetShadow(AValue: Integer);
begin
FShadow := AValue;
ForceInRange(FShadow, 0, 4);
end;
procedure TAlphaStyle.SetAlignment(AValue: Integer);
begin
FAlignment := AValue;
ForceInRange(FAlignment, 0, 11);
end;
function TAlphaStyle.ParseFromString(const AStyle: String; IsAdvanced: Boolean)
: Boolean;
var
sa,sa2: TStringArray;
s: String;
i: Integer;
begin
Result := True;
if not AStyle.StartsWith(AlphaStyleMarker) then
Exit(False);
if IsAdvanced then
sa := AlphaStylesHint.Substring(AlphaStyleFormatMarker.Length).Split(',')
else
sa := OldAlphaStylesHint.Substring(AlphaStyleFormatMarker.Length).Split(',');
sa2 := AStyle.Substring(AlphaStyleMarker.Length).Split(',');
if High(sa) <> High(sa2) then Exit(False);
Self := DefaultAlphaStyle;
for i := 0 to High(sa) do
begin
s := sa2[i];
case sa[i].Trim.ToLower of
'name': Name := s;
'fontname': Fontname := s;
'fontsize': Fontsize := s.ToInteger;
'primarycolour': PrimaryColour := AlphaColorToFPColor(s);
'secondarycolour': SecondaryColour := AlphaColorToFPColor(s);
'tertiarycolour': OutlineColour := AlphaColorToFPColor(s);
'outlinecolour': OutlineColour := AlphaColorToFPColor(s);
'backcolour': BackColour := AlphaColorToFPColor(s);
'bold': Bold := s.ToBoolean;
'italic': Italic := s.ToBoolean;
'underline': Underline := s.ToBoolean;
'strikeout': StrikeOut := s.ToBoolean;
'scalex': ScaleX := s.ToInteger;
'scaley': ScaleY := s.ToInteger;
'spacing': Spacing := s.ToInteger;
'angle': Angle := s.ToDouble;
'borderstyle': BorderStyle := s.ToInteger;
'outline': Outline := s.ToInteger;
'shadow': Shadow := s.ToInteger;
'alignment': Alignment := s.ToInteger;
'marginl': MarginL := s.ToInteger;
'marginr': MarginR := s.ToInteger;
'marginv': MarginV := s.ToInteger;
'alphalevel': AlphaLevel := s.ToInteger;
'encoding': Encoding := s.ToInteger;
end;
end;
end;
function TAlphaStyle.ToString(IsAdvanced: Boolean): String;
var
sa: TStringArray;
i: Integer;
begin
Result := EmptyStr;
if IsAdvanced then
sa := AlphaStylesHint.Substring(AlphaStyleFormatMarker.Length).Split(',')
else
sa := OldAlphaStylesHint.Substring(AlphaStyleFormatMarker.Length).Split(',');
for i := 0 to High(sa) do
begin
case sa[i].Trim.ToLower of
'name': sa[i] := Name;
'fontname': sa[i] := Fontname;
'fontsize': sa[i] := Fontsize.ToString;
'primarycolour': sa[i] := FPColorToAlphaColor(PrimaryColour, IsAdvanced);
'secondarycolour': sa[i] := FPColorToAlphaColor(SecondaryColour, IsAdvanced);
'tertiarycolour': sa[i] := FPColorToAlphaColor(OutlineColour, IsAdvanced);
'outlinecolour': sa[i] := FPColorToAlphaColor(OutlineColour, IsAdvanced);
'backcolour': sa[i] := FPColorToAlphaColor(BackColour, IsAdvanced);
'bold': sa[i] := Bold.ToString;
'italic': sa[i] := Italic.ToString;
'underline': sa[i] := Underline.ToString;
'strikeout': sa[i] := StrikeOut.ToString;
'scalex': sa[i] := ScaleX.ToString;
'scaley': sa[i] := ScaleY.ToString;
'spacing': sa[i] := Spacing.ToString;
'angle': sa[i] := Angle.ToString;
'borderstyle': sa[i] := BorderStyle.ToString;
'outline': sa[i] := Outline.ToString;
'shadow': sa[i] := Shadow.ToString;
'alignment': sa[i] := Alignment.ToString;
'marginl': sa[i] := MarginL.ToString;
'marginr': sa[i] := MarginR.ToString;
'marginv': sa[i] := MarginV.ToString;
'alphalevel': sa[i] := AlphaLevel.ToString;
'encoding': sa[i] := Encoding.ToString;
end;
end;
Result := AlphaStyleMarker +Result.Join(AlphaSep, sa);
end;
{ TAlphaStyleManager }
function TAlphaStyleManager.GetUniqueName(const AName: String): String;
var
i: Integer;
begin
Result := AName;
if Count <= 1 then Exit;
i := 0;
while i < Count do
begin
if Result.Equals(Items[i].Name) then
begin
Result := Result +' - Copy';
i := 0;
Continue;
end
else
Inc(i);
end;
end;
function TAlphaStyleManager.New: Integer;
begin
Result := inherited New;
Items[Result] := DefaultAlphaStyle;
PItems[Result]^.Name := GetUniqueName(PItems[Result]^.Name);
end;
function TAlphaStyleManager.Add(AItem: TAlphaStyle): Integer;
begin
AItem.Name := GetUniqueName(AItem.Name);
Result := inherited Add(AItem);
end;
function TAlphaStyleManager.ToText(IsAdvanced: Boolean): String;
var
i: Integer;
begin
Result := EmptyStr;
for i := 0 to Count-1 do
Result := Result +Items[i].ToString(IsAdvanced) +LineEnding;
end;
{ TAlphaEvent }
procedure TAlphaEvent.SetStyle(const AValue: String);
begin
FStyle := AValue.Replace(AlphaSep, AlphaSepReplacement);
end;
procedure TAlphaEvent.SetName(const AValue: String);
begin
FName := AValue.Replace(AlphaSep, AlphaSepReplacement);
end;
procedure TAlphaEvent.SetEffect(const AValue: String);
begin
FEffect := AValue.Replace(AlphaSep, AlphaSepReplacement);
end;
function TAlphaEvent.ParseFromString(const AEvent: String): Boolean;
var
sa: TStringArray;
i: Integer;
begin
Result := True;
case AEvent.Substring(0, AEvent.IndexOf(' ')+1) of
AlphaDialogueMarker: EventType := aeDialogue;
AlphaCommentMarker: EventType := aeComment;
AlphaPictureMarker: EventType := aePicture;
AlphaSoundMarker: EventType := aeSound;
AlphaMovieMarker: EventType := aeMovie;
AlphaCommandMarker: EventType := aeCommand;
end;
sa := AEvent.Substring(AEvent.IndexOf(' ')+1).Split(AlphaSep);
if Length(sa) < 10 then Exit(False);
for i := 0 to 8 do
sa[i] := DelSpace(sa[i]);
if sa[0].StartsWith(OldAlphaMarkers[0]) then
LayerOrMarked := sa[0].Substring(OldAlphaMarkers[0].Length).ToInteger
else
LayerOrMarked := sa[0].ToInteger;
TimeSlice.Initialize(2, ':', '.', AlphaSep);
TimeSlice.ValueAsString := sa[1] +AlphaSep +sa[2];
Style := sa[3];
Name := sa[4];
MarginL := sa[5].ToInteger;
MarginR := sa[6].ToInteger;
MarginV := sa[7].ToInteger;
Effect := sa[8];
i := NthIndexOf(AlphaSep, AEvent, 9);
if i > 0 then
Text := AEvent.Substring(i+1);
end;
function TAlphaEvent.ToString(IsAdvanced: Boolean): String;
begin
Result := LayerOrMarked.ToString;
if not IsAdvanced then
Result := OldAlphaMarkers[0] +Result;
Result :=
Result +AlphaSep +TimeSlice.ValueAsString
+AlphaSep +Style
+AlphaSep +Name
+AlphaSep +StrForceLength(MarginL.ToString, 4, '0')
+AlphaSep +StrForceLength(MarginR.ToString, 4, '0')
+AlphaSep +StrForceLength(MarginV.ToString, 4, '0')
+AlphaSep +Effect
+AlphaSep +Text;
case EventType of
aeDialogue: Result := AlphaDialogueMarker +Result;
aeComment: Result := AlphaCommentMarker +Result;
aePicture: Result := AlphaPictureMarker +Result;
aeSound: Result := AlphaSoundMarker +Result;
aeMovie: Result := AlphaMovieMarker +Result;
aeCommand: Result := AlphaCommandMarker +Result;
end;
end;
{ TSubStationAlphaFile }
procedure TSubStationAlphaFile.ConvertToAdvancedAlpha;
var
i: Integer;
begin
if FAlphaIsAdvanced = True then Exit;
FAlphaIsAdvanced := True;
for i := 0 to Styles.Count-1 do
begin
Styles.PItems[i]^.OutlineColour := Styles[i].BackColour;
Styles.PItems[i]^.Alignment :=
AlphaOldAlignToAdvancedAlign(Styles.PItems[i]^.Alignment);
end;
end;
procedure TSubStationAlphaFile.ConvertToOldAlpha;
var
i: Integer;
begin
if FAlphaIsAdvanced = False then Exit;
FAlphaIsAdvanced := False;
for i := 0 to Styles.Count-1 do
Styles.PItems[i]^.Alignment :=
AlphaAdvancedAlignToOldAlign(Styles.PItems[i]^.Alignment);
end;
procedure TSubStationAlphaFile.SetAdvanced(AValue: Boolean);
begin
if AValue and not FAlphaIsAdvanced then
ConvertToAdvancedAlpha
else if not AValue and FAlphaIsAdvanced then
ConvertToOldAlpha;
end;
procedure TSubStationAlphaFile.LoadFromString(const AContents: String);
var
sa: TStringArray;
sl: TStringList;
ae: TAlphaEvent;
i,j,k: Integer;
Stl: TAlphaStyle;
begin
Events.Clear;
if IsEmptyStr(AContents) then Exit;
sl := TStringList.Create;
try
sl.Text := AContents.Trim;
sa := StringListToArray(sl);
finally
sl.Free;
end;
i := FindInArray(sa, AlphaInfoHeader);
if i < 0 then Exit;
i := FindAnyInArray(sa, [AlphaStylesHeader,OldAlphaStylesHeader], i+1);
if i < 0 then Exit;
i := FindInArray(sa, AlphaEventsHeader, i+1);
if i < 0 then Exit;
if (FindInArray(sa, OldAlphaMarkers[0]) >= 0)
and (FindInArray(sa, OldAlphaMarkers[1]) >= 0) then
FAlphaIsAdvanced := False
else
FAlphaIsAdvanced := True;
Infos.Clear;
i := FindInArray(sa, AlphaInfoHeader);
j := FindAnyInArray(sa, [AlphaStylesHeader,OldAlphaStylesHeader])-2;
for k := i+1 to j do
Infos.Add(sa[k]);
Styles.Clear;
i := FindAnyInArray(sa, [AlphaStylesHeader,OldAlphaStylesHeader]);
j := FindInArray(sa, AlphaEventsHeader)-2;
for k := i+2 to j do
if Stl.ParseFromString(sa[k], FAlphaIsAdvanced) then
Styles.Add(Stl);
Events.Clear;
Events.Capacity := Length(sa);
for i := 0 to High(sa) do
if (sa[i].IndexOfAny(AlphaEventMarkers) >= 0)
and ae.ParseFromString(sa[i]) then
Events.Add(ae);
end;
procedure TSubStationAlphaFile.SaveToString(out AContents: String);
var
sl: TStringList;
i: Integer;
begin
sl := TStringList.Create;
sl.Capacity := Infos.Count+Styles.Count+Events.Count+10;
try
sl.Add(AlphaInfoHeader);
sl.Add(Infos.ToText(FAlphaIsAdvanced));
if FAlphaIsAdvanced then
begin
sl.Add(AlphaStylesHeader);
sl.Add(AlphaStylesHint);
end
else
begin
sl.Add(OldAlphaStylesHeader);
sl.Add(OldAlphaStylesHint);
end;
sl.Add(Styles.ToText(FAlphaIsAdvanced));
sl.Add(AlphaEventsHeader);
if FAlphaIsAdvanced then
sl.Add(AlphaEventsHint)
else
sl.Add(OldAlphaEventsHint);
for i := 0 to Events.Count-1 do
sl.Add(Events[i].ToString(FAlphaIsAdvanced));
finally
AContents := sl.Text;
sl.Free;
end;
end;
constructor TSubStationAlphaFile.Create;
begin
inherited Create;
TimeSlice.Initialize(2, ':', '.', AlphaSep);
FAlphaIsAdvanced := True;
Infos := TAlphaInfoManager.Create;
Styles := TAlphaStyleManager.Create;
Styles.New;
end;
destructor TSubStationAlphaFile.Destroy;
begin
if Assigned(Infos) then Infos.Free;
if Assigned(Styles) then Styles.Free;
inherited Destroy;
end;
end.
|
unit uEnumContinente;
interface
type
tContinentes = (tcVazio = -1, tcAmerica, tcEuropa, tcAsia, tcAfrica, tcOceania, tcAntartida);
implementation
end.
|
unit VolumeRGBData;
interface
uses Windows, Graphics, Abstract3DVolumeData, RGBSingleDataSet, AbstractDataSet,
dglOpenGL, Math;
type
T3DVolumeRGBData = class (TAbstract3DVolumeData)
private
// Gets
function GetData(_x, _y, _z, _c: integer):single;
function GetDataUnsafe(_x, _y, _z, _c: integer):single;
// Sets
procedure SetData(_x, _y, _z, _c: integer; _value: single);
procedure SetDataUnsafe(_x, _y, _z, _c: integer; _value: single);
protected
// Constructors and Destructors
procedure Initialize; override;
// Gets
function GetBitmapPixelColor(_Position: longword):longword; override;
function GetRPixelColor(_Position: longword):byte; override;
function GetGPixelColor(_Position: longword):byte; override;
function GetBPixelColor(_Position: longword):byte; override;
function GetAPixelColor(_Position: longword):byte; override;
function GetRedPixelColor(_x,_y,_z: integer):single; override;
function GetGreenPixelColor(_x,_y,_z: integer):single; override;
function GetBluePixelColor(_x,_y,_z: integer):single; override;
function GetAlphaPixelColor(_x,_y,_z: integer):single; override;
// Sets
procedure SetBitmapPixelColor(_Position, _Color: longword); override;
procedure SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte); override;
procedure SetRedPixelColor(_x,_y,_z: integer; _value:single); override;
procedure SetGreenPixelColor(_x,_y,_z: integer; _value:single); override;
procedure SetBluePixelColor(_x,_y,_z: integer; _value:single); override;
procedure SetAlphaPixelColor(_x,_y,_z: integer; _value:single); override;
// Copies
procedure CopyData(const _Data: TAbstractDataSet; _DataXSize, _DataYSize, _DataZSize: integer); override;
public
// Gets
function GetOpenGLFormat:TGLInt; override;
// Misc
procedure ScaleBy(_Value: single); override;
procedure Invert; override;
procedure Fill(_Value: single);
// properties
property Data[_x,_y,_z,_c:integer]:single read GetData write SetData; default;
property DataUnsafe[_x,_y,_z,_c:integer]:single read GetDataUnsafe write SetDataUnsafe;
end;
implementation
// Constructors and Destructors
procedure T3DVolumeRGBData.Initialize;
begin
FData := TRGBSingleDataSet.Create;
end;
// Gets
function T3DVolumeRGBData.GetData(_x, _y, _z, _c: integer):single;
begin
if IsPixelValid(_x,_y,_z) and (_c >= 0) and (_c <= 2) then
begin
case (_c) of
0: Result := (FData as TRGBSingleDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x];
1: Result := (FData as TRGBSingleDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x];
else
begin
Result := (FData as TRGBSingleDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
end;
end
else
begin
Result := -99999;
end;
end;
function T3DVolumeRGBData.GetDataUnsafe(_x, _y, _z, _c: integer):single;
begin
case (_c) of
0: Result := (FData as TRGBSingleDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x];
1: Result := (FData as TRGBSingleDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x];
else
begin
Result := (FData as TRGBSingleDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
end;
end;
function T3DVolumeRGBData.GetBitmapPixelColor(_Position: longword):longword;
begin
Result := RGB(Round((FData as TRGBSingleDataSet).Blue[_Position]) and $FF,Round((FData as TRGBSingleDataSet).Green[_Position]) and $FF,Round((FData as TRGBSingleDataSet).Red[_Position]) and $FF);
end;
function T3DVolumeRGBData.GetRPixelColor(_Position: longword):byte;
begin
Result := Round((FData as TRGBSingleDataSet).Red[_Position]) and $FF;
end;
function T3DVolumeRGBData.GetGPixelColor(_Position: longword):byte;
begin
Result := Round((FData as TRGBSingleDataSet).Green[_Position]) and $FF;
end;
function T3DVolumeRGBData.GetBPixelColor(_Position: longword):byte;
begin
Result := Round((FData as TRGBSingleDataSet).Blue[_Position]) and $FF;
end;
function T3DVolumeRGBData.GetAPixelColor(_Position: longword):byte;
begin
Result := 0;
end;
function T3DVolumeRGBData.GetRedPixelColor(_x,_y,_z: integer):single;
begin
Result := (FData as TRGBSingleDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
function T3DVolumeRGBData.GetGreenPixelColor(_x,_y,_z: integer):single;
begin
Result := (FData as TRGBSingleDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
function T3DVolumeRGBData.GetBluePixelColor(_x,_y,_z: integer):single;
begin
Result := (FData as TRGBSingleDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x];
end;
function T3DVolumeRGBData.GetAlphaPixelColor(_x,_y,_z: integer):single;
begin
Result := 0;
end;
function T3DVolumeRGBData.GetOpenGLFormat:TGLInt;
begin
Result := GL_RGB;
end;
// Sets
procedure T3DVolumeRGBData.SetBitmapPixelColor(_Position, _Color: longword);
begin
(FData as TRGBSingleDataSet).Red[_Position] := GetRValue(_Color);
(FData as TRGBSingleDataSet).Green[_Position] := GetGValue(_Color);
(FData as TRGBSingleDataSet).Blue[_Position] := GetBValue(_Color);
end;
procedure T3DVolumeRGBData.SetRGBAPixelColor(_Position: integer; _r, _g, _b, _a: byte);
begin
(FData as TRGBSingleDataSet).Red[_Position] := _r;
(FData as TRGBSingleDataSet).Green[_Position] := _g;
(FData as TRGBSingleDataSet).Blue[_Position] := _b;
end;
procedure T3DVolumeRGBData.SetRedPixelColor(_x,_y,_z: integer; _value:single);
begin
(FData as TRGBSingleDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
end;
procedure T3DVolumeRGBData.SetGreenPixelColor(_x,_y,_z: integer; _value:single);
begin
(FData as TRGBSingleDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
end;
procedure T3DVolumeRGBData.SetBluePixelColor(_x,_y,_z: integer; _value:single);
begin
(FData as TRGBSingleDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
end;
procedure T3DVolumeRGBData.SetAlphaPixelColor(_x,_y,_z: integer; _value:single);
begin
// do nothing
end;
procedure T3DVolumeRGBData.SetData(_x, _y, _z, _c: integer; _value: single);
begin
if IsPixelValid(_x,_y,_z) and (_c >= 0) and (_c <= 2) then
begin
case (_c) of
0: (FData as TRGBSingleDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
1: (FData as TRGBSingleDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
2: (FData as TRGBSingleDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
end;
end;
end;
procedure T3DVolumeRGBData.SetDataUnsafe(_x, _y, _z, _c: integer; _value: single);
begin
case (_c) of
0: (FData as TRGBSingleDataSet).Red[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
1: (FData as TRGBSingleDataSet).Green[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
2: (FData as TRGBSingleDataSet).Blue[(_z * FYxXSize) + (_y * FXSize) + _x] := _value;
end;
end;
// Copies
procedure T3DVolumeRGBData.CopyData(const _Data: TAbstractDataSet; _DataXSize, _DataYSize, _DataZSize: integer);
var
x,y,z,ZPos,ZDataPos,Pos,maxPos,DataPos,maxX, maxY, maxZ: integer;
begin
maxX := min(FXSize,_DataXSize)-1;
maxY := min(FYSize,_DataYSize)-1;
maxZ := min(FZSize,_DataZSize)-1;
for z := 0 to maxZ do
begin
ZPos := z * FYxXSize;
ZDataPos := z * _DataYSize * _DataXSize;
for y := 0 to maxY do
begin
Pos := ZPos + (y * FXSize);
DataPos := ZDataPos + (y * _DataXSize);
maxPos := Pos + maxX;
for x := Pos to maxPos do
begin
(FData as TRGBSingleDataSet).Data[x] := (_Data as TRGBSingleDataSet).Data[DataPos];
inc(DataPos);
end;
end;
end;
end;
// Misc
procedure T3DVolumeRGBData.ScaleBy(_Value: single);
var
x,maxx: integer;
begin
maxx := (FYxXSize * FZSize) - 1;
for x := 0 to maxx do
begin
(FData as TRGBSingleDataSet).Red[x] := Round((FData as TRGBSingleDataSet).Red[x] * _Value);
(FData as TRGBSingleDataSet).Green[x] := Round((FData as TRGBSingleDataSet).Green[x] * _Value);
(FData as TRGBSingleDataSet).Blue[x] := Round((FData as TRGBSingleDataSet).Blue[x] * _Value);
end;
end;
procedure T3DVolumeRGBData.Invert;
var
x,maxx: integer;
begin
maxx := (FYxXSize * FZSize) - 1;
for x := 0 to maxx do
begin
(FData as TRGBSingleDataSet).Red[x] := 1 - (FData as TRGBSingleDataSet).Red[x];
(FData as TRGBSingleDataSet).Green[x] := 1 - (FData as TRGBSingleDataSet).Green[x];
(FData as TRGBSingleDataSet).Blue[x] := 1 - (FData as TRGBSingleDataSet).Blue[x];
end;
end;
procedure T3DVolumeRGBData.Fill(_value: single);
var
x,maxx: integer;
begin
maxx := (FYxXSize * FZSize) - 1;
for x := 0 to maxx do
begin
(FData as TRGBSingleDataSet).Red[x] := _value;
(FData as TRGBSingleDataSet).Green[x] := _value;
(FData as TRGBSingleDataSet).Blue[x] := _value;
end;
end;
end.
|
{*******************************************************************************
* uDepartmentsAdd *
* *
* ะะพะฑะฐะฒะปะตะฝะธะต ะฟะพะดัะฐะทะดะตะปะตะฝะธั *
* Copyright ยฉ 2002-2005, ะะปะตะณ ะ. ะะพะปะบะพะฒ, ะะพะฝะตัะบะธะน ะะฐัะธะพะฝะฐะปัะฝัะน ะฃะฝะธะฒะตััะธัะตั *
*******************************************************************************}
unit uDepartmentsAdd;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uDateControl, uSpravControl, uFControl, uLabeledFControl,
uCharControl, ExtCtrls, StdCtrls, Buttons, uLogicCheck, uSimpleCheck,
uFormControl, ActnList, uDepartmentsData;
type
TfmDepartmentAdd = class(TForm)
OkButton: TBitBtn;
CancelButton: TBitBtn;
MainPanel: TPanel;
NameFull: TqFCharControl;
NameShort: TqFCharControl;
DepType: TqFSpravControl;
DateBeg: TqFDateControl;
DateEnd: TqFDateControl;
qFSimpleCheck1: TqFSimpleCheck;
ActionList1: TActionList;
Accept: TAction;
CancelAction: TAction;
FormControl: TqFFormControl;
Department_Code: TqFCharControl;
Name_Full_Rus: TqFCharControl;
Name_Full_Eng: TqFCharControl;
procedure CancelActionExecute(Sender: TObject);
procedure AcceptExecute(Sender: TObject);
procedure DepTypeOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: string);
procedure FormActivate(Sender: TObject);
procedure FormControlNewRecordAfterPrepare(Sender: TObject);
private
{ Private declarations }
public
DM: TdmDepartments;
end;
var
fmDepartmentAdd: TfmDepartmentAdd;
implementation
uses uDepartmentsConsts;
{$R *.dfm}
procedure TfmDepartmentAdd.CancelActionExecute(Sender: TObject);
begin
Exit;
end;
procedure TfmDepartmentAdd.AcceptExecute(Sender: TObject);
begin
FormControl.Ok;
end;
procedure TfmDepartmentAdd.DepTypeOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: string);
begin
DM.GetDepType(Value, DisplayText);
end;
procedure TfmDepartmentAdd.FormActivate(Sender: TObject);
begin
NameFull.ShowFocus;
end;
procedure TfmDepartmentAdd.FormControlNewRecordAfterPrepare(
Sender: TObject);
begin
DM.DepTypesSelect.Close;
DM.DepTypesSelect.Open;
DM.DepTypesSelect.Locate('Id_Dep_Type', DefaultDepType, []);
DepType.Value := DM.DepTypesSelect['Id_Dep_Type'];
DepType.DisplayText := DM.DepTypesSelect['Name_Dep_Type'];
end;
initialization
RegisterClass(TfmDepartmentAdd);
end.
|
unit BCEditor.TextDrawer;
interface
uses
Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, System.Math, System.Types, System.UITypes,
BCEditor.Utils;
const
CFontStyleCount = Ord(High(TFontStyle)) + 1;
CFontStyleCombineCount = 1 shl CFontStyleCount;
type
TBCEditorStockFontPatterns = 0 .. CFontStyleCombineCount - 1;
TBCEditorFontData = record
Style: TFontStyles;
Handle: HFont;
CharAdvance: Integer;
CharHeight: Integer;
end;
PBCEditorFontData = ^TBCEditorFontData;
TBCEditorFontsData = array [TBCEditorStockFontPatterns] of TBCEditorFontData;
TBCEditorSharedFontsInfo = record
RefCount: Integer;
LockCount: Integer;
BaseFont: TFont;
BaseLogFont: TLogFont;
IsTrueType: Boolean;
FontsData: TBCEditorFontsData;
end;
PBCEditorSharedFontsInfo = ^TBCEditorSharedFontsInfo;
{ TBCEditorFontsInfoManager }
TBCEditorFontsInfoManager = class(TObject)
strict private
FFontsInfo: TList;
function FindFontsInfo(const ALogFont: TLogFont): PBCEditorSharedFontsInfo;
function CreateFontsInfo(ABaseFont: TFont; const ALogFont: TLogFont): PBCEditorSharedFontsInfo;
procedure DestroyFontHandles(ASharedFontsInfo: PBCEditorSharedFontsInfo);
procedure RetrieveLogFontForComparison(ABaseFont: TFont; var ALogFont: TLogFont);
public
constructor Create;
destructor Destroy; override;
procedure LockFontsInfo(ASharedFontsInfo: PBCEditorSharedFontsInfo);
procedure UnLockFontsInfo(ASharedFontsInfo: PBCEditorSharedFontsInfo);
function GetFontsInfo(ABaseFont: TFont): PBCEditorSharedFontsInfo;
procedure ReleaseFontsInfo(ASharedFontsInfo: PBCEditorSharedFontsInfo);
end;
TBCEditorFontStock = class(TObject)
strict private
FCurrentFont: HFont;
FCurrentStyle: TFontStyles;
FHandle: HDC;
FHandleRefCount: Integer;
FPSharedFontsInfo: PBCEditorSharedFontsInfo;
FUsingFontHandles: Boolean;
FPCurrentFontData: PBCEditorFontData;
FBaseLogFont: TLogFont;
function GetBaseFont: TFont;
function GetIsTrueType: Boolean;
protected
function CalculateFontAdvance(AHandle: HDC; ACharHeight: PInteger): Integer; virtual;
function GetCharAdvance: Integer; virtual;
function GetCharHeight: Integer; virtual;
function GetFontData(AIndex: Integer): PBCEditorFontData; virtual;
function InternalGetHandle: HDC; virtual;
function InternalCreateFont(AStyle: TFontStyles): HFont; virtual;
procedure InternalReleaseDC(AValue: HDC); virtual;
procedure ReleaseFontsInfo;
procedure SetBaseFont(AValue: TFont); virtual;
procedure SetStyle(AValue: TFontStyles); virtual;
procedure UseFontHandles;
property FontData[AIndex: Integer]: PBCEditorFontData read GetFontData;
property FontsInfo: PBCEditorSharedFontsInfo read FPSharedFontsInfo;
public
constructor Create(AInitialFont: TFont); virtual;
destructor Destroy; override;
procedure ReleaseFontHandles; virtual;
property BaseFont: TFont read GetBaseFont;
property Style: TFontStyles read FCurrentStyle write SetStyle;
property FontHandle: HFont read FCurrentFont;
property CharAdvance: Integer read GetCharAdvance;
property CharHeight: Integer read GetCharHeight;
property IsTrueType: Boolean read GetIsTrueType;
end;
{ TBCEditorTextDrawer }
ETextDrawerException = class(Exception);
TBCEditorTextDrawer = class(TObject)
strict private
FBackgroundColor: TColor;
FBaseCharHeight: Integer;
FBaseCharWidth: Integer;
FCalcExtentBaseStyle: TFontStyles;
FCharABCWidthCache: array [0 .. 127] of TABC;
FCharExtra: Integer;
FCharWidthCache: array [0 .. 127] of Integer;
FColor: TColor;
FCurrentFont: HFont;
FDrawingCount: Integer;
FExtTextOutDistance: PIntegerArray;
FExtTextOutLength: Integer;
FFontStock: TBCEditorFontStock;
FHandle: HDC;
FSaveHandle: Integer;
FStockBitmap: TBitmap;
protected
function GetCachedABCWidth(AChar: Cardinal; var AABC: TABC): Boolean;
procedure AfterStyleSet; virtual;
procedure DoSetCharExtra(AValue: Integer); virtual;
procedure FlushCharABCWidthCache;
property BaseCharHeight: Integer read FBaseCharHeight;
property BaseCharWidth: Integer read FBaseCharWidth;
property DrawingCount: Integer read FDrawingCount;
property FontStock: TBCEditorFontStock read FFontStock;
property StockHandle: HDC read FHandle;
public
constructor Create(ACalcExtentBaseStyle: TFontStyles; ABaseFont: TFont); virtual;
destructor Destroy; override;
function GetCharCount(AChar: PChar): Integer;
function GetCharHeight: Integer; virtual;
function GetCharWidth: Integer; virtual;
function TextExtent(const Text: string): TSize;
function TextCharWidth(const AChar: PChar): Integer;
procedure BeginDrawing(AHandle: HDC); virtual;
procedure EndDrawing; virtual;
procedure ExtTextOut(X, Y: Integer; AOptions: Longint; var ARect: TRect; AText: PChar; ALength: Integer); virtual;
procedure SetBackgroundColor(AValue: TColor); virtual;
procedure SetBaseFont(AValue: TFont); virtual;
procedure SetBaseStyle(const AValue: TFontStyles); virtual;
procedure SetCharExtra(AValue: Integer); virtual;
procedure SetForegroundColor(AValue: TColor); virtual;
procedure SetStyle(AValue: TFontStyles); virtual;
procedure TextOut(X, Y: Integer; AText: PChar; ALength: Integer); virtual;
property BackgroundColor: TColor read FBackgroundColor write SetBackgroundColor;
property BaseFont: TFont write SetBaseFont;
property BaseStyle: TFontStyles write SetBaseStyle;
property CharExtra: Integer read FCharExtra write SetCharExtra;
property CharHeight: Integer read GetCharHeight;
property CharWidth: Integer read GetCharWidth;
property ForegroundColor: TColor write SetForegroundColor;
property Style: TFontStyles write SetStyle;
end;
function GetFontsInfoManager: TBCEditorFontsInfoManager;
implementation
var
GFontsInfoManager: TBCEditorFontsInfoManager;
{ utility routines }
function GetFontsInfoManager: TBCEditorFontsInfoManager;
begin
if not Assigned(GFontsInfoManager) then
GFontsInfoManager := TBCEditorFontsInfoManager.Create;
Result := GFontsInfoManager;
end;
{ TFontsInfoManager }
procedure TBCEditorFontsInfoManager.LockFontsInfo(ASharedFontsInfo: PBCEditorSharedFontsInfo);
begin
Inc(ASharedFontsInfo^.LockCount);
end;
constructor TBCEditorFontsInfoManager.Create;
begin
inherited;
FFontsInfo := TList.Create;
end;
function TBCEditorFontsInfoManager.CreateFontsInfo(ABaseFont: TFont; const ALogFont: TLogFont): PBCEditorSharedFontsInfo;
begin
New(Result);
FillChar(Result^, SizeOf(TBCEditorSharedFontsInfo), 0);
with Result^ do
try
BaseFont := TFont.Create;
BaseFont.Assign(ABaseFont);
BaseLogFont := ALogFont;
IsTrueType := (0 <> (TRUETYPE_FONTTYPE and ALogFont.lfPitchAndFamily));
except
Result^.BaseFont.Free;
Dispose(Result);
raise;
end;
end;
procedure TBCEditorFontsInfoManager.UnLockFontsInfo(ASharedFontsInfo: PBCEditorSharedFontsInfo);
begin
with ASharedFontsInfo^ do
begin
Dec(LockCount);
if 0 = LockCount then
DestroyFontHandles(ASharedFontsInfo);
end;
end;
destructor TBCEditorFontsInfoManager.Destroy;
begin
GFontsInfoManager := nil;
if Assigned(FFontsInfo) then
begin
while FFontsInfo.Count > 0 do
begin
Assert(1 = PBCEditorSharedFontsInfo(FFontsInfo[FFontsInfo.Count - 1])^.RefCount);
ReleaseFontsInfo(PBCEditorSharedFontsInfo(FFontsInfo[FFontsInfo.Count - 1]));
end;
FFontsInfo.Free;
end;
inherited;
end;
procedure TBCEditorFontsInfoManager.DestroyFontHandles(ASharedFontsInfo: PBCEditorSharedFontsInfo);
var
i: Integer;
LFontData: TBCEditorFontData;
begin
with ASharedFontsInfo^ do
for i := Low(TBCEditorStockFontPatterns) to High(TBCEditorStockFontPatterns) do
begin
LFontData := FontsData[i];
if LFontData.Handle <> 0 then
begin
DeleteObject(LFontData.Handle);
LFontData.Handle := 0;
end;
end;
end;
function TBCEditorFontsInfoManager.FindFontsInfo(const ALogFont: TLogFont): PBCEditorSharedFontsInfo;
var
i: Integer;
begin
for i := 0 to FFontsInfo.Count - 1 do
begin
Result := PBCEditorSharedFontsInfo(FFontsInfo[i]);
if CompareMem(@(Result^.BaseLogFont), @ALogFont, SizeOf(TLogFont)) then
Exit;
end;
Result := nil;
end;
function TBCEditorFontsInfoManager.GetFontsInfo(ABaseFont: TFont): PBCEditorSharedFontsInfo;
var
LLogFont: TLogFont;
begin
Assert(Assigned(ABaseFont));
RetrieveLogFontForComparison(ABaseFont, LLogFont);
Result := FindFontsInfo(LLogFont);
if not Assigned(Result) then
begin
Result := CreateFontsInfo(ABaseFont, LLogFont);
FFontsInfo.Add(Result);
end;
if Assigned(Result) then
Inc(Result^.RefCount);
end;
procedure TBCEditorFontsInfoManager.ReleaseFontsInfo(ASharedFontsInfo: PBCEditorSharedFontsInfo);
begin
Assert(Assigned(ASharedFontsInfo));
with ASharedFontsInfo^ do
begin
Assert(LockCount < RefCount);
if RefCount > 1 then
Dec(RefCount)
else
begin
FFontsInfo.Remove(ASharedFontsInfo);
BaseFont.Free;
Dispose(ASharedFontsInfo);
end;
end;
end;
procedure TBCEditorFontsInfoManager.RetrieveLogFontForComparison(ABaseFont: TFont; var ALogFont: TLogFont);
var
LPEnd: PChar;
begin
GetObject(ABaseFont.Handle, SizeOf(TLogFont), @ALogFont);
with ALogFont do
begin
lfItalic := 0;
lfUnderline := 0;
lfStrikeOut := 0;
LPEnd := StrEnd(lfFaceName);
FillChar(LPEnd[1], @lfFaceName[high(lfFaceName)] - LPEnd, 0);
end;
end;
{ TFontStock }
function TBCEditorFontStock.CalculateFontAdvance(AHandle: HDC; ACharHeight: PInteger): Integer;
var
LTextMetric: TTextMetric;
LCharInfo: TABC;
LHasABC: Boolean;
begin
GetTextMetrics(AHandle, LTextMetric);
LHasABC := GetCharABCWidths(AHandle, Ord('M'), Ord('M'), LCharInfo);
if not LHasABC then
begin
with LCharInfo do
begin
abcA := 0;
abcB := LTextMetric.tmAveCharWidth;
abcC := 0;
end;
LTextMetric.tmOverhang := 0;
end;
with LCharInfo do
Result := abcA + Integer(abcB) + abcC + LTextMetric.tmOverhang;
if Assigned(ACharHeight) then
ACharHeight^ := Abs(LTextMetric.tmHeight)
end;
constructor TBCEditorFontStock.Create(AInitialFont: TFont);
begin
inherited Create;
SetBaseFont(AInitialFont);
end;
destructor TBCEditorFontStock.Destroy;
begin
ReleaseFontsInfo;
Assert(FHandleRefCount = 0);
inherited;
end;
function TBCEditorFontStock.GetBaseFont: TFont;
begin
Result := FPSharedFontsInfo^.BaseFont;
end;
function TBCEditorFontStock.GetCharAdvance: Integer;
begin
Result := FPCurrentFontData^.CharAdvance;
end;
function TBCEditorFontStock.GetCharHeight: Integer;
begin
Result := FPCurrentFontData^.CharHeight;
end;
function TBCEditorFontStock.GetFontData(AIndex: Integer): PBCEditorFontData;
begin
Result := @FPSharedFontsInfo^.FontsData[AIndex];
end;
function TBCEditorFontStock.GetIsTrueType: Boolean;
begin
Result := FPSharedFontsInfo^.IsTrueType
end;
function TBCEditorFontStock.InternalCreateFont(AStyle: TFontStyles): HFont;
const
CBolds: array [Boolean] of Integer = (400, 700);
begin
with FBaseLogFont do
begin
lfWeight := CBolds[fsBold in Style];
lfItalic := Ord(BOOL(fsItalic in Style));
lfUnderline := Ord(BOOL(fsUnderline in Style));
lfStrikeOut := Ord(BOOL(fsStrikeOut in Style));
end;
Result := CreateFontIndirect(FBaseLogFont);
end;
function TBCEditorFontStock.InternalGetHandle: HDC;
begin
if FHandleRefCount = 0 then
begin
Assert(FHandle = 0);
FHandle := GetDC(0);
end;
Inc(FHandleRefCount);
Result := FHandle;
end;
procedure TBCEditorFontStock.InternalReleaseDC(AValue: HDC);
begin
Dec(FHandleRefCount);
if FHandleRefCount <= 0 then
begin
Assert((FHandle <> 0) and (FHandle = AValue));
ReleaseDC(0, FHandle);
FHandle := 0;
Assert(FHandleRefCount = 0);
end;
end;
procedure TBCEditorFontStock.ReleaseFontHandles;
begin
if FUsingFontHandles then
with GetFontsInfoManager do
begin
UnLockFontsInfo(FPSharedFontsInfo);
FUsingFontHandles := False;
end;
end;
procedure TBCEditorFontStock.ReleaseFontsInfo;
begin
if Assigned(FPSharedFontsInfo) then
with GetFontsInfoManager do
begin
if FUsingFontHandles then
begin
UnLockFontsInfo(FPSharedFontsInfo);
FUsingFontHandles := False;
end;
ReleaseFontsInfo(FPSharedFontsInfo);
FPSharedFontsInfo := nil;
end;
end;
procedure TBCEditorFontStock.SetBaseFont(AValue: TFont);
var
LSharedFontsInfo: PBCEditorSharedFontsInfo;
begin
if Assigned(AValue) then
begin
LSharedFontsInfo := GetFontsInfoManager.GetFontsInfo(AValue);
if LSharedFontsInfo = FPSharedFontsInfo then
GetFontsInfoManager.ReleaseFontsInfo(LSharedFontsInfo)
else
begin
ReleaseFontsInfo;
FPSharedFontsInfo := LSharedFontsInfo;
FBaseLogFont := FPSharedFontsInfo^.BaseLogFont;
SetStyle(AValue.Style);
end;
end
else
raise Exception.Create('SetBaseFont: ''Value'' must be specified.');
end;
procedure TBCEditorFontStock.SetStyle(AValue: TFontStyles);
var
LIndex: Integer;
LHandle: HDC;
LOldFont: HFont;
LFontDataPointer: PBCEditorFontData;
begin
Assert(SizeOf(TFontStyles) = 1);
LIndex := Byte(AValue);
Assert(LIndex <= High(TBCEditorStockFontPatterns));
UseFontHandles;
LFontDataPointer := FontData[LIndex];
if FPCurrentFontData = LFontDataPointer then
Exit;
FPCurrentFontData := LFontDataPointer;
with LFontDataPointer^ do
if Handle <> 0 then
begin
FCurrentFont := Handle;
FCurrentStyle := Style;
Exit;
end;
FCurrentFont := InternalCreateFont(AValue);
LHandle := InternalGetHandle;
LOldFont := SelectObject(LHandle, FCurrentFont);
with FPCurrentFontData^ do
begin
Handle := FCurrentFont;
CharAdvance := CalculateFontAdvance(LHandle, @CharHeight);
end;
SelectObject(LHandle, LOldFont);
InternalReleaseDC(LHandle);
end;
procedure TBCEditorFontStock.UseFontHandles;
begin
if not FUsingFontHandles then
with GetFontsInfoManager do
begin
LockFontsInfo(FPSharedFontsInfo);
FUsingFontHandles := True;
end;
end;
{ TBCEditorTextDrawer }
constructor TBCEditorTextDrawer.Create(ACalcExtentBaseStyle: TFontStyles; ABaseFont: TFont);
begin
inherited Create;
FFontStock := TBCEditorFontStock.Create(ABaseFont);
FStockBitmap := TBitmap.Create;
FCalcExtentBaseStyle := ACalcExtentBaseStyle;
SetBaseFont(ABaseFont);
FColor := clWindowText;
FBackgroundColor := clWindow;
FExtTextOutLength := 0;
end;
destructor TBCEditorTextDrawer.Destroy;
begin
FStockBitmap.Free;
FFontStock.Free;
if Assigned(FExtTextOutDistance) then
begin
FreeMem(FExtTextOutDistance);
FExtTextOutDistance := nil;
end;
inherited;
end;
procedure TBCEditorTextDrawer.BeginDrawing(AHandle: HDC);
begin
if FHandle = AHandle then
Assert(FHandle <> 0)
else
begin
Assert((FHandle = 0) and (AHandle <> 0) and (FDrawingCount = 0));
FHandle := AHandle;
FSaveHandle := SaveDC(AHandle);
SelectObject(AHandle, FCurrentFont);
Winapi.Windows.SetTextColor(AHandle, ColorToRGB(FColor));
Winapi.Windows.SetBkColor(AHandle, ColorToRGB(FBackgroundColor));
DoSetCharExtra(FCharExtra);
end;
Inc(FDrawingCount);
end;
procedure TBCEditorTextDrawer.EndDrawing;
begin
Assert(FDrawingCount >= 1);
Dec(FDrawingCount);
if FDrawingCount <= 0 then
begin
if FHandle <> 0 then
RestoreDC(FHandle, FSaveHandle);
FSaveHandle := 0;
FHandle := 0;
FDrawingCount := 0;
end;
end;
function TBCEditorTextDrawer.GetCharWidth: Integer;
begin
Result := FBaseCharWidth + FCharExtra;
end;
function TBCEditorTextDrawer.GetCharHeight: Integer;
begin
Result := FBaseCharHeight;
end;
procedure TBCEditorTextDrawer.SetBaseFont(AValue: TFont);
begin
if Assigned(AValue) then
begin
FlushCharABCWidthCache;
FStockBitmap.Canvas.Font.Assign(AValue);
FStockBitmap.Canvas.Font.Style := [];
with FFontStock do
begin
SetBaseFont(AValue);
Style := FCalcExtentBaseStyle;
FBaseCharWidth := CharAdvance;
FBaseCharHeight := CharHeight;
end;
SetStyle(AValue.Style);
end
else
raise ETextDrawerException.Create('SetBaseFont: ''Value'' must be specified.');
end;
procedure TBCEditorTextDrawer.SetBaseStyle(const AValue: TFontStyles);
begin
if FCalcExtentBaseStyle <> AValue then
begin
FlushCharABCWidthCache;
FCalcExtentBaseStyle := AValue;
with FFontStock do
begin
Style := AValue;
FBaseCharWidth := CharAdvance;
FBaseCharHeight := CharHeight;
end;
end;
end;
procedure TBCEditorTextDrawer.SetStyle(AValue: TFontStyles);
begin
with FFontStock do
begin
SetStyle(AValue);
Self.FCurrentFont := FontHandle;
end;
AfterStyleSet;
end;
procedure TBCEditorTextDrawer.FlushCharABCWidthCache;
begin
FillChar(FCharABCWidthCache, SizeOf(TABC) * Length(FCharABCWidthCache), 0);
FillChar(FCharWidthCache, SizeOf(Integer) * Length(FCharWidthCache), 0);
end;
procedure TBCEditorTextDrawer.AfterStyleSet;
begin
if FHandle <> 0 then
SelectObject(FHandle, FCurrentFont);
end;
function TBCEditorTextDrawer.GetCachedABCWidth(AChar: Cardinal; var AABC: TABC): Boolean;
begin
if AChar > High(FCharABCWidthCache) then
begin
Result := GetCharABCWidthsW(FHandle, AChar, AChar, AABC);
Exit;
end;
AABC := FCharABCWidthCache[AChar];
if (AABC.abcA or Integer(AABC.abcB) or AABC.abcC) = 0 then
begin
Result := GetCharABCWidthsW(FHandle, AChar, AChar, AABC);
if Result then
FCharABCWidthCache[AChar] := AABC;
end
else
Result := True;
end;
procedure TBCEditorTextDrawer.SetForegroundColor(AValue: TColor);
begin
if FColor <> AValue then
begin
FColor := AValue;
if FHandle <> 0 then
SetTextColor(FHandle, ColorToRGB(AValue));
end;
end;
procedure TBCEditorTextDrawer.SetBackgroundColor(AValue: TColor);
begin
if FBackgroundColor <> AValue then
begin
FBackgroundColor := AValue;
if FHandle <> 0 then
Winapi.Windows.SetBkColor(FHandle, ColorToRGB(AValue));
end;
end;
procedure TBCEditorTextDrawer.SetCharExtra(AValue: Integer);
begin
if FCharExtra <> AValue then
begin
FCharExtra := AValue;
DoSetCharExtra(FCharExtra);
end;
end;
procedure TBCEditorTextDrawer.DoSetCharExtra(AValue: Integer);
begin
if FHandle <> 0 then
SetTextCharacterExtra(FHandle, AValue);
end;
procedure TBCEditorTextDrawer.TextOut(X, Y: Integer; AText: PChar; ALength: Integer);
var
LTempRect: TRect;
begin
LTempRect := Rect(X, Y, X, Y);
Winapi.Windows.ExtTextOut(FHandle, X, Y, 0, @LTempRect, AText, ALength, nil);
end;
function TBCEditorTextDrawer.GetCharCount(AChar: PChar): Integer;
begin
Result := CeilOfIntDiv(TextCharWidth(AChar), CharWidth);
end;
procedure TBCEditorTextDrawer.ExtTextOut(X, Y: Integer; AOptions: Longint; var ARect: TRect; AText: PChar;
ALength: Integer);
var
i, LCharWidth: Integer;
LLastChar: Cardinal;
LRealCharWidth, LNormalCharWidth: Integer;
LCharInfo: TABC;
LTextMetricA: TTextMetricA;
begin
LCharWidth := GetCharWidth;
if ALength > FExtTextOutLength then
begin
FExtTextOutLength := ALength;
ReallocMem(FExtTextOutDistance, ALength * SizeOf(Integer));
end;
for i := 0 to ALength - 1 do
if Ord(AText[i]) < 128 then
FExtTextOutDistance[i] := LCharWidth
else
FExtTextOutDistance[i] := GetCharCount(@AText[i]) * LCharWidth;
{ avoid clipping the last pixels of text in italic }
if ALength > 0 then
begin
LLastChar := Ord(AText[ALength - 1]);
if LLastChar <> 32 then
begin
LNormalCharWidth := FExtTextOutDistance[ALength - 1];
LRealCharWidth := LNormalCharWidth;
if GetCachedABCWidth(LLastChar, LCharInfo) then
begin
LRealCharWidth := LCharInfo.abcA + Integer(LCharInfo.abcB);
if LCharInfo.abcC >= 0 then
Inc(LRealCharWidth, LCharInfo.abcC);
end
else
if LLastChar < Ord(High(AnsiChar)) then
begin
GetTextMetricsA(FHandle, LTextMetricA);
LRealCharWidth := LTextMetricA.tmAveCharWidth + LTextMetricA.tmOverhang;
end;
if LRealCharWidth > LNormalCharWidth then
Inc(ARect.Right, LRealCharWidth - LNormalCharWidth);
FExtTextOutDistance[ALength - 1] := Max(LRealCharWidth, LNormalCharWidth);
end;
end;
Winapi.Windows.ExtTextOut(FHandle, X, Y, AOptions, @ARect, AText, ALength, Pointer(FExtTextOutDistance));
end;
function TBCEditorTextDrawer.TextExtent(const Text: string): TSize;
begin
Result := BCEditor.Utils.TextExtent(FStockBitmap.Canvas, Text);
end;
function TBCEditorTextDrawer.TextCharWidth(const AChar: PChar): Integer;
var
LCharCode: Cardinal;
begin
LCharCode := Ord(AChar^);
if LCharCode <= High(FCharWidthCache) then
begin
Result := FCharWidthCache[LCharCode];
if Result = 0 then
begin
Result := BCEditor.Utils.TextExtent(FStockBitmap.Canvas, AChar^).cX;
FCharWidthCache[LCharCode] := Result;
end;
Exit;
end;
Result := BCEditor.Utils.TextExtent(FStockBitmap.Canvas, AChar^).cX;
end;
initialization
finalization
if Assigned(GFontsInfoManager) then
GFontsInfoManager.Free;
end.
|
unit St_sp_Type_Category_Form;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxEdit, DB, cxDBData, cxCheckBox, FIBQuery, pFIBQuery,
pFIBStoredProc, ActnList, FIBDataSet, pFIBDataSet, cxContainer, cxLabel,
ExtCtrls, cxGridLevel, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid,
ImgList, ComCtrls, ToolWin, cxGridCustomPopupMenu, cxGridPopupMenu, Menus,
StdCtrls ;
type
TTypeCategoryForm = class(TForm)
cxGrid1: TcxGrid;
cxGrid1DBTableView1: TcxGridDBTableView;
cxGrid1DBTableView1DBColumn1: TcxGridDBColumn;
cxGrid1DBTableView1ID_TYPE_CATEGORY: TcxGridDBColumn;
cxGrid1DBTableView1NAME_TYPE_CATEGORY: TcxGridDBColumn;
cxGrid1DBTableView1NAME_SHORT: TcxGridDBColumn;
cxGrid1DBTableView1MONTH_OPL: TcxGridDBColumn;
cxGrid1Level1: TcxGridLevel;
Panel1: TPanel;
cxLabel1: TcxLabel;
MonthOplCheck: TcxCheckBox;
cxStyleRepository1: TcxStyleRepository;
cxStyle1: TcxStyle;
cxStyle2: TcxStyle;
DataSet: TpFIBDataSet;
DataSource: TDataSource;
ActionList1: TActionList;
AddAction: TAction;
EditAction: TAction;
DeleteAction: TAction;
RefreshAction: TAction;
ExitAction: TAction;
WriteProc: TpFIBStoredProc;
ReadDataSet: TpFIBDataSet;
ToolBar1: TToolBar;
AddButton: TToolButton;
EditButton: TToolButton;
DeleteButton: TToolButton;
RefreshButton: TToolButton;
ExitButton: TToolButton;
ImageListOfCategory: TImageList;
SelectButton: TToolButton;
cxStyle3: TcxStyle;
cxStyle4: TcxStyle;
PopupMenu1: TPopupMenu;
N1: TMenuItem;
N2: TMenuItem;
DeleteAction1: TMenuItem;
RefreshAction1: TMenuItem;
ShortNameLabel: TEdit;
SearchButton_Naim: TToolButton;
N3: TMenuItem;
procedure SelectButtonClick(Sender: TObject);
procedure cxGrid1DBTableView1DblClick(Sender: TObject);
procedure DataSetAfterScroll(DataSet: TDataSet);
procedure ExitButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure DataSetAfterOpen(DataSet: TDataSet);
procedure FormCreate(Sender: TObject);
procedure AddButtonClick(Sender: TObject);
procedure EditButtonClick(Sender: TObject);
procedure DeleteButtonClick(Sender: TObject);
procedure RefreshButtonClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure SearchButton_NaimClick(Sender: TObject);
private
{ Private declarations }
public
KeyField : string;
// AllowMultiSelect : boolean;
MultiResult:Variant;
constructor Create(Aowner:TComponent;FormST:TFormStyle);overload;
function GetMultiValue():variant;
procedure SelectAll;
end;
var
TypeCategoryForm: TTypeCategoryForm;
implementation
uses DataModule1_Unit, St_sp_Category_Type_Add, Unit_of_Utilits, main,
Search_LgotUnit, Search_Unit;
{$R *.dfm}
constructor TTypeCategoryForm.Create(Aowner:TComponent;FormST:TFormStyle);
begin
Inherited Create(Aowner);
FormStyle:=FormST;
SelectButton.Enabled:=true;
cxGrid1DBTableView1.OptionsSelection.MultiSelect:=true;
end;
function TTypeCategoryForm.GetMultiValue():variant;
begin
ShowModal;
GetMultiValue:=MultiResult;
end;
procedure TTypeCategoryForm.SelectAll;
begin
DataSet.Close;
DataSet.Open;
end;
procedure TTypeCategoryForm.SelectButtonClick(Sender: TObject);
var i : integer;
RecMultiSelected : integer;
begin
if cxGrid1DBTableView1.OptionsSelection.MultiSelect=true then
begin
RecMultiSelected:=cxGrid1DBTableView1.DataController.GetSelectedCount;
MultiResult:=VarArrayCreate([0,RecMultiSelected-1],varVariant);
for i:=0 to cxGrid1DBTableView1.DataController.GetSelectedCount-1 do
begin
MultiResult[i]:=cxGrid1DBTableView1.Controller.SelectedRecords[i].Values[1];
end;
end;
ModalResult:=mrOk;
end;
procedure TTypeCategoryForm.cxGrid1DBTableView1DblClick(Sender: TObject);
begin
ModalResult:=mrOk;
end;
procedure TTypeCategoryForm.DataSetAfterScroll(DataSet: TDataSet);
begin
if DataSet.RecordCount = 0 then exit;
if DataSet['NAME_SHORT']<> null then ShortNameLabel.Text := DataSet['NAME_SHORT'];
if DataSet['MONTH_OPL']<> null then MonthOplCheck.Checked := DataSet['MONTH_OPL'] = 1;
end;
procedure TTypeCategoryForm.ExitButtonClick(Sender: TObject);
begin
close;
end;
procedure TTypeCategoryForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action:=caFree;
if MainForm.N5.Enabled = false then MainForm.N5.Enabled := true;
MainForm.CloseAllWindows;
end;
procedure TTypeCategoryForm.DataSetAfterOpen(DataSet: TDataSet);
begin
if DataSet.RecordCount = 0 then begin
EditButton.Enabled := false;
DeleteButton.Enabled := false;
// SelectButton.Enabled := false;
end else begin
EditButton.Enabled := true;
DeleteButton.Enabled := true;
// SelectButton.Enabled := true;
end;
end;
procedure TTypeCategoryForm.FormCreate(Sender: TObject);
begin
KeyField := 'ID_TYPE_CATEGORY';
end;
procedure TTypeCategoryForm.AddButtonClick(Sender: TObject);
var
ActionStr : string;
new_id : integer;
begin
ActionStr := 'ะะพะฑะฐะฒะธัั';
TypeCategoryFormAdd := TTypeCategoryFormAdd.Create(Self);
TypeCategoryFormAdd.Caption := ActionStr + ' ' + TypeCategoryFormAdd.Caption;
TypeCategoryFormAdd.OKButton.Caption := ActionStr;
if TypeCategoryFormAdd.ShowModal = mrOK then begin
WriteProc.StoredProcName := 'ST_INI_TYPE_CATEGORY_INSERT';
WriteProc.Transaction.StartTransaction;
WriteProc.Prepare;
WriteProc.ParamByName('NAME_TYPE_CATEGORY').AsString := TypeCategoryFormAdd.NameEdit.Text;
WriteProc.ParamByName('NAME_SHORT').AsString := TypeCategoryFormAdd.ShortEdit.Text;
WriteProc.ParamByName('MONTH_OPL').AsInteger := BoolConvert(TypeCategoryFormAdd.MonthOplCheck.Checked);
WriteProc.ExecProc;
new_id := WriteProc[KeyField].AsInteger;
WriteProc.Transaction.Commit;
WriteProc.Close;
SelectAll;
DataSet.Locate(KeyField, new_id, []);
end;
TypeCategoryFormAdd.Free;
end;
procedure TTypeCategoryForm.EditButtonClick(Sender: TObject);
var
ActionStr, ActionKeyStr : string;
id : integer;
begin
id := DataSet[KeyField];
ActionStr := 'ะะทะผะตะฝะธัั';
ActionKeyStr:='ะัะธะฝััั';
TypeCategoryFormAdd := TTypeCategoryFormAdd.Create(Self);
TypeCategoryFormAdd.Caption := ActionStr + ' ' + TypeCategoryFormAdd.Caption;
TypeCategoryFormAdd.OKButton.Caption := ActionKeyStr;
if DataSet['NAME_SHORT']<> null then TypeCategoryFormAdd.ShortEdit.Text := DataSet['NAME_SHORT'];
if DataSet['NAME_TYPE_CATEGORY']<> null then TypeCategoryFormAdd.NameEdit.Text := DataSet['NAME_TYPE_CATEGORY'];
if DataSet['MONTH_OPL']<> null then TypeCategoryFormAdd.MonthOplCheck.Checked := DataSet['MONTH_OPL'] = 1;
if TypeCategoryFormAdd.ShowModal = mrOK then begin
WriteProc.StoredProcName := 'ST_INI_TYPE_CATEGORY_UPDATE';
WriteProc.Transaction.StartTransaction;
WriteProc.Prepare;
WriteProc.ParamByName(KeyField).AsInteger := id;
WriteProc.ParamByName('NAME_TYPE_CATEGORY').AsString := TypeCategoryFormAdd.NameEdit.Text;
WriteProc.ParamByName('NAME_SHORT').AsString := TypeCategoryFormAdd.ShortEdit.Text;
WriteProc.ParamByName('MONTH_OPL').AsInteger := BoolConvert(TypeCategoryFormAdd.MonthOplCheck.Checked);
WriteProc.ExecProc;
WriteProc.Transaction.Commit;
WriteProc.Close;
SelectAll;
DataSet.Locate(KeyField, id, []);
end;
TypeCategoryFormAdd.Free;
end;
procedure TTypeCategoryForm.DeleteButtonClick(Sender: TObject);
var
selected : integer;
begin
//if MessageBox(Handle,PChar('ะั ะดะตะนััะฒะธัะตะปัะฝะพ ั
ะพัะธัะต ัะดะฐะปะธัั ัะธะฟ ะบะฐัะตะณะพัะธะธ "' + DataSet.FieldByName('NAME_TYPE_CATEGORY').AsString + '"?'),'ะะพะดัะฒะตัะดะธัะต ...',MB_YESNO or MB_ICONQUESTION)= mrNo then exit;
if MessageBox(Handle,PChar('ะั ะดะตะนััะฒะธัะตะปัะฝะพ ั
ะพัะธัะต ัะดะฐะปะธัั ะทะฐะฟะธัั ?'),'ะะพะดัะฒะตัะถะดะตะฝะธะต ัะดะฐะปะตะฝะธั ...',MB_YESNO or MB_ICONQUESTION)= mrNo then exit;
WriteProc.StoredProcName := 'ST_INI_TYPE_CATEGORY_DELETE';
WriteProc.Transaction.StartTransaction;
WriteProc.Prepare;
WriteProc.ParamByName(KeyField).AsInteger := DataSet[KeyField];
WriteProc.ExecProc;
WriteProc.Transaction.Commit;
WriteProc.Close;
selected := cxGrid1DBTableView1.DataController.FocusedRowIndex-1;
SelectAll;
cxGrid1DBTableView1.DataController.FocusedRowIndex := selected;
end;
procedure TTypeCategoryForm.RefreshButtonClick(Sender: TObject);
var
selected : integer;
begin
selected := -1;
if DataSet.RecordCount <> 0 then selected := DataSet[KeyField];
SelectAll;
DataSet.Locate(KeyField, selected, []);
end;
procedure TTypeCategoryForm.FormShow(Sender: TObject);
begin
//cxGrid1DBTableView1.Items[0].DataBinding.ValueTypeClass := TcxIntegerValueType;
// if AllowMultiSelect then cxGrid1DBTableView1.Columns[0].Visible := true;
if not DataSet.Active then SelectAll;
end;
procedure TTypeCategoryForm.SearchButton_NaimClick(Sender: TObject);
begin
if PopupMenu1.Items[4].Checked= true then
begin
Search_LgotForm := TSearch_LgotForm.Create(Self);
while Search_LgotForm.FindFlag = false do begin
if Search_LgotForm.FindClosed = true then begin
Search_LgotForm.Free;
exit;
end;
if Search_LgotForm.ShowModal = mrOk then begin
if Search_LgotForm.FindFlag = true then begin
cxGrid1DBTableView1NAME_TYPE_CATEGORY.SortOrder:=soAscending;
DataSet.Locate('NAME_TYPE_CATEGORY', Search_LgotForm.Naim_Edit.Text, [loCaseInsensitive, loPartialKey]);
Search_LgotForm.Free;
exit;
end
else begin
cxGrid1DBTableView1NAME_TYPE_CATEGORY.SortOrder:=soAscending;
DataSet.Locate('NAME_TYPE_CATEGORY', Search_LgotForm.Naim_Edit.Text, [loCaseInsensitive, loPartialKey]);
Search_LgotForm.showModal;
end;
end;
end;
if Search_LgotForm.FindFlag = true then begin
cxGrid1DBTableView1NAME_TYPE_CATEGORY.SortOrder:=soAscending;
DataSet.Locate('NAME_TYPE_CATEGORY', Search_LgotForm.Naim_Edit.Text, [loCaseInsensitive, loPartialKey]);
Search_LgotForm.Free;
end;
end
else begin
Search_Form:= TSearch_Form.create(self);
if Search_Form.ShowModal = mrOk then begin
cxGrid1DBTableView1NAME_TYPE_CATEGORY.SortOrder:=soAscending;
DataSet.Locate('NAME_TYPE_CATEGORY', Search_Form.Naim_Edit.Text, [loCaseInsensitive, loPartialKey]);
end;
end;
end;
end.
|
unit fUninstall;
interface
uses
ShellAPI, registry, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TShortcutFolder = (sfCustom, sfStartMenu, sfPrograms, sfDesktop);
TfrmUninstall = class(TForm)
Label1: TLabel;
Label2: TLabel;
btnUninstall: TButton;
btnCancel: TButton;
procedure btnCancelClick(Sender: TObject);
procedure btnUninstallClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
sInstallDir: string;
procedure DeleteRegistryKeys;
procedure DeleteShortcuts;
function GetShortcutFolder(ShortcutFolder: TShortcutFolder): string;
procedure LoadInstallationDirFromRegistry;
procedure UnregisterUninstaller;
end;
var
frmUninstall: TfrmUninstall;
implementation
{$R *.dfm}
{= <fh>
*******************************************************************************
FUNCTION: SH_DeleteFiles()
-------------------------------------------------------------------------------
DESCRIPTION :
Deletes file(s) specified by pointer "sFiles" mask,
using SHFileOperation() shell API function.
-------------------------------------------------------------------------------
INPUT:
sFiles: Mask for specified files.
bConfirm: Should Windows ask for confirmation before deleting?
bSilent: Should windows suppress the progress dialog?
bAllowUndo: Should files be sent to the recycle bin instead of being deleted?
-------------------------------------------------------------------------------
RETURN VALUE:
0 if no errors occurred,
otherwise error code returned by SHFileOperation().
-------------------------------------------------------------------------------
REMARKS:
sFiles MUST be a fully qualified pathname,
especially if we set bAllowUndo := true.
Otherwise results may be unpredictable.
*******************************************************************************
}
function SH_DeleteFiles(sFiles: string;
bConfirm : boolean = false;
bSilent: boolean = true;
bAllowUndo: Boolean = false): integer;
var
SHInfo : TSHFileOpStruct;
begin
{ The list of names of files to be deleted must be double null-terminated. }
sFiles := sFiles + #0#0;
FillChar(SHInfo, SizeOf(TSHFileOpStruct), 0);
with SHInfo do begin
wnd := Application.Handle;
wFunc := FO_DELETE;
pFrom := PChar(sFiles);
pTo := nil;
fFlags := 0;
if not bConfirm then fFlags := fFlags or FOF_NOCONFIRMATION;
if bSilent then fFlags := fFlags or FOF_SILENT;
if bAllowUndo then fFlags := fFlags or FOF_ALLOWUNDO;
end;
Result := SHFileOperation(SHInfo);
end; { SH_DeleteFiles }
procedure TfrmUninstall.LoadInstallationDirFromRegistry;
var
reg: TRegistry;
begin
reg := TRegistry.Create;
try
reg.RootKey := HKEY_CURRENT_USER;
reg.OpenKey('Software\MyCompany\MyApp', true);
sInstallDir := reg.ReadString('Installation directory');
finally
reg.Free
end;
end;
procedure TfrmUninstall.btnUninstallClick(Sender: TObject);
begin
{ Find out where the application has been installed }
LoadInstallationDirFromRegistry;
{ Remove the last backslash from the installation folder name }
Delete(sInstallDir, length(sInstallDir), 1);
{ Delete the created shortcuts }
DeleteShortcuts;
{ Delete the Windows registry keys we created at installation }
DeleteRegistryKeys;
{ "Unregister" the uninstaller app from the "Add/Remove programs" control panel section }
UnregisterUninstaller;
{ Delete the installation folder }
if DirectoryExists(sInstallDir) then
SH_DeleteFiles(sInstallDir);
MessageDlg('MyApp has been successfully removed from your computer.', mtInformation, [mbOK], 0);
Close;
end;
procedure TfrmUninstall.DeleteRegistryKeys;
var
reg: TRegistry;
begin
reg := TRegistry.Create;
try
reg.RootKey := HKEY_CURRENT_USER;
reg.DeleteKey('Software\MyCompany\MyApp');
{
Note that this will leave the HKEY_CURRENT_USER\Software\MyCompany registry key
on the user's computer.
This is desired if e.g. we have installed more than one of our company's applications
on the user's computer, and we want to delete the registry key only for the current,
leaving the other ones intact.
If this is not the case, then the above command should be instead:
reg.DeleteKey('Software\MyCompany');
}
finally
reg.Free
end;
end;
procedure TfrmUninstall.UnregisterUninstaller;
var
reg: TRegistry;
begin
reg := TRegistry.Create;
try
reg.RootKey := HKEY_CURRENT_USER;
reg.DeleteKey('Software\Microsoft\Windows\CurrentVersion\Uninstall\MyApp');
finally
reg.Free
end;
end;
procedure TfrmUninstall.btnCancelClick(Sender: TObject);
begin
Close;
end;
procedure TfrmUninstall.DeleteShortcuts;
var
sFileMask: string;
begin
{
delete shortcuts in "programs" - delete the entire folder.
This deletes the Application shortcut, the help file shortcut as well as the uninstaller shortcut
}
sFileMask := GetShortcutFolder(sfPrograms) + 'MyApp';
if DirectoryExists(sFileMask) then
SH_DeleteFiles(sFileMask);
{ shortcut on desktop }
sFileMask := GetShortcutFolder(sfDesktop) + 'MyApp.lnk';
DeleteFile(sFileMask);
{ shortcut in start menu }
sFileMask := GetShortcutFolder(sfStartMenu) + 'MyApp.lnk';
DeleteFile(sFileMask);
end;
function TfrmUninstall.GetShortcutFolder(ShortcutFolder: TShortcutFolder): string;
var
reg: TRegistry;
begin
reg := TRegistry.Create;
try
reg.RootKey := HKEY_CURRENT_USER;
reg.OpenKey('Software\MicroSoft\Windows\CurrentVersion\Explorer\Shell Folders', false);
case ShortcutFolder of
sfCustom: result := '';{ Do nothing }
sfStartMenu: result := reg.ReadString('Start Menu') + '\';
sfPrograms: result := reg.ReadString('Programs') + '\';
sfDesktop: result := reg.ReadString('Desktop') + '\';
end;
finally
reg.Free
end;
end;
end.
|
unit MyHTTP;
interface
uses IdHTTP, IdInterceptThrottler, Classes, SysUtils, SyncObjs, Strutils,
Variants, Common, IdURI, MyIdURI, idHTTPHeaderInfo, HTTPApp, pac;
type
tIdProxyRec = record
Auth: Boolean;
User, Password, Host: String;
Port: integer;
end;
TMyCookieList = class(TStringList)
private
FCS: TCriticalSection;
protected
property CS: TCriticalSection read FCS write FCS;
public
constructor Create;
destructor Destroy; override;
function GetCookieValue(CookieName, CookieDomain: string): string;
function GetCookieByValue(CookieName, CookieDomain: string): string;
procedure DeleteCookie(CookieDomain: string);
procedure ChangeCookie(CookieDomain, CookieString: String);
function GetCookiesByDomain(domain: string): string;
procedure SaveToFile(const FileName: string); override;
// property Lines[index:integer]: String read Get;
end;
TOnSetCookies = procedure(AURL: String; ARequest: TIdHTTPRequest) of object;
TOnProcessCookies = procedure(ARequest: TIdHTTPRequest;
AResponse: TIdHTTPResponse) of object;
// TIDHTTPHelper = class helper for TIdHTTP
// protected
// FOnSetCookies: TOnSetCookies;
// FOnProcessCookies: TOnProcessCookies;
// public
// property OnSetCookies: TOnSetCookies read FOnSetCookies write FOnSetCookies;
// property OnProcessCookies: TOnProcessCookies read FOnProcessCookies write FOnProcessCookies;
// end;
TMyIdHTTP = class(TIdCustomHTTP)
private
FCookieList: TMyCookieList;
fPACParser: tPACParser;
fPAC: Boolean;
procedure SetCookieList(Value: TMyCookieList);
protected
procedure DoSetCookies(AURL: String; ARequest: TIdHTTPRequest);
procedure DoProcessCookies(ARequest: TIdHTTPRequest;
AResponse: TIdHTTPResponse);
procedure doPAC(AURL: String);
public
{ procedure Get(AURL: string; AResponseContent: TStream;
AIgnoreReplies: array of SmallInt); }
function Get(AURL: string; AResponse: TStream = nil): string; overload;
function Get(AURL: string; AIgnoreReplies: array of SmallInt)
: string; overload;
function Post(AURL: string; ASource: TStrings): string; overload;
procedure Post(AURL: string; ASource: TStrings;
AResponse: TStream); overload;
procedure ReadCookies(url: string; AResponse: TIdHTTPResponse);
procedure WriteCookies(url: string; ARequest: TIdHTTPRequest);
property CookieList: TMyCookieList read FCookieList write SetCookieList;
property PACParser: tPACParser read fPACParser write fPACParser;
property UsePAC: Boolean read fPAC write fPAC;
procedure Head(AURL: string; AIgnoreReplies: array of SmallInt); overload;
end;
function CreateHTTP { (AOwner: TComponent) } : TMyIdHTTP;
function RemoveURLDomain(url: string): string;
function GetUrlVarValue(url, Variable: String): String;
function AddURLVar(url, Variable: String; Value: Variant): String;
function GetURLDomain(url: string): string;
procedure GetPostStrings(s: string; outs: TStrings);
function CheckProto(url, referer: string): string;
function GetProxyParams(const pp: tIdProxyConnectionInfo): tIdProxyRec;
procedure SetProxyParams(const pp: tIdProxyConnectionInfo;
const p: tIdProxyRec);
var
idThrottler: tidInterceptThrottler;
implementation
function CheckProto(url, referer: string): string;
var
uri1, uri2: tiduri;
begin
uri1 := tiduri.Create(url);
try
uri2 := tiduri.Create(referer);
try
if uri1.Protocol = '' then
if uri2.Protocol = '' then
uri1.Protocol := 'http'
else
uri1.Protocol := uri2.Protocol;
if (uri1.Host = '') then
begin
uri1.Host := uri2.Host;
if uri1.Path = '' then
uri1.Path := uri2.Path;
end;
result := uri1.GetFullURI;
finally
uri2.Free;
end;
finally
uri1.Free;
end;
end;
procedure GetPostStrings(s: string; outs: TStrings);
var
tmp: string;
begin
s := trim(CopyFromTo(s, '?', ''));
while s <> '' do
begin
tmp := GetNextS(s, '&');
outs.Add(tmp);
end;
end;
function CreateHTTP { (AOwner: TComponent) } : TMyIdHTTP;
begin
result := TMyIdHTTP.Create { (AOwner) };
result.Intercept := idThrottler;
result.HandleRedirects := true;
result.AllowCookies := False;
result.Request.UserAgent :=
'Mozilla/5.0 (Windows NT 6.1; rv:23.0) Gecko/20100101 Firefox/23.0';
result.ConnectTimeout := 10000;
result.ReadTimeout := 10000;
// result.ProxyParams
// Result.Request.AcceptLanguage := 'en-us,en;q=0.8';
// Result.Request.AcceptEncoding := 'gzip, deflate';
// Result.Request.Accept := 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
end;
{ var
cs: TCriticalSection; }
function GetUrlVarValue(url, Variable: String): String;
var
s: string;
begin
url := CopyFromTo(url, '?', '');
while url <> '' do
begin
s := GetNextS(url, '&');
result := GetNextS(s, '=');
if SameText(result, Variable) then
begin
result := s;
Exit;
end;
end;
result := '';
end;
function AddURLVar(url, Variable: String; Value: Variant): String;
begin
if pos('?', url) > 0 then
result := url + '&' + Variable + '=' + VarToStr(Value)
else
result := url + '?' + Variable + '=' + VarToStr(Value);
end;
function GetCookieName(Cookie: string): string;
var
i: integer;
begin
result := '';
i := pos('=', Cookie);
if i = 0 then
Exit;
result := Copy(Cookie, 1, i - 1);
end;
function GetCookieDomain(Cookie: string): string;
var
i, j: integer;
begin
result := '';
Cookie := lowercase(Cookie);
i := pos('domain=', Cookie);
if i = 0 then
Exit;
j := PosEx('www.', Cookie, i + 1);
if j > 0 then
i := i + 4;
j := CharPos(Cookie, ';', [], [], i);
if j = 0 then
j := Length(Cookie) + 1;
result := Copy(Cookie, i + 7, j - i - 7);
// Remove dot
{ if (Result<>'') and (Result[1]='.') then
Result:=Copy(Result,2,Length(Result)-1); }
end;
function RemoveURLDomain(url: string): string;
var
n: integer;
begin
result := url;
n := pos('://', result);
if n > 0 then
begin
Delete(result, 1, n + 2);
n := pos('/', result);
Delete(result, 1, n);
end;
end;
function GetURLDomain(url: string): string;
begin
result := DeleteTo(url, '://');
result := CopyFromTo(result, 'www.', '/');
end;
function GetCookieValue(Cookie: String): string;
begin
result := '';
if pos('=', Cookie) = 0 then
Exit;
result := CopyFromTo(Cookie, '=', ';');
end;
function SameDomain(s1, s2: string): Boolean;
begin
if s1 = s2 then
result := true
else if (s1[1] = '.') and (pos(trim(s1, '.'), s2) > 0) then
result := true
else if (s2[1] = '.') and (pos(trim(s2, '.'), s1) > 0) then
result := true
else
result := False;
end;
function GetProxyParams(const pp: tIdProxyConnectionInfo): tIdProxyRec;
begin
result.Auth := pp.BasicAuthentication;
result.User := pp.ProxyUsername;
result.Password := pp.ProxyPassword;
result.Host := pp.ProxyServer;
result.Port := pp.ProxyPort;
end;
procedure SetProxyParams(const pp: tIdProxyConnectionInfo;
const p: tIdProxyRec);
begin
pp.BasicAuthentication := p.Auth;
pp.ProxyServer := p.Host;
pp.ProxyPort := p.Port;
pp.ProxyUsername := p.User;
pp.ProxyPassword := p.Password;
end;
constructor TMyCookieList.Create;
begin
inherited;
FCS := TCriticalSection.Create;
end;
destructor TMyCookieList.Destroy;
begin
FCS.Free;
inherited;
end;
procedure TMyCookieList.ChangeCookie(CookieDomain, CookieString: String);
function DelleteIfExist(Cookie: string): Boolean;
var
i: integer;
begin
result := False;
for i := 0 to Count - 1 do
if (SameDomain(GetCookieDomain(Strings[i]), GetCookieDomain(Cookie))) and
(GetCookieName(Strings[i]) = GetCookieName(Cookie)) then
begin
Delete(i);
Exit;
end;
end;
begin
FCS.Enter;
try
if GetCookieDomain(CookieString) = '' then
CookieString := CookieString + '; domain=' + CookieDomain;
DelleteIfExist(CookieString);
Add(CookieString);
finally
FCS.Leave;
end;
end;
procedure TMyCookieList.SaveToFile(const FileName: string);
begin
FCS.Enter;
inherited SaveToFile(FileName);
FCS.Leave;
end;
function TMyCookieList.GetCookiesByDomain(domain: string): string;
var
i, j: integer;
s: string;
begin
result := '';
// if (length(domain) > 0) and ((pos('www.',lowercase(domain)) = 1)){ or (url[1] = '.'))} then
// domain:= DeleteTo(domain,'.');
FCS.Enter;
try
for i := 0 to Count - 1 do
begin
s := GetCookieDomain(Strings[i]);
if SameDomain(s, domain) then
begin
j := pos(';', Strings[i]);
result := result + Copy(Strings[i], 1, j) + ' ';
end;
end;
finally
FCS.Leave;
end;
end;
procedure TMyCookieList.DeleteCookie(CookieDomain: string);
var
i: integer;
begin
// Result := '';
FCS.Enter;
try
for i := 0 to Self.Count - 1 do
if SameDomain(GetCookieDomain(Self[i]), CookieDomain)
{ and (GetCookieName(Self[i])=CookieName) } then
begin
// Result := MyHTTP.GetCookieValue(Self[i]);
// Exit;
Self.Delete(i);
end;
finally
FCS.Leave;
end;
end;
function TMyCookieList.GetCookieValue(CookieName, CookieDomain: string): string;
var
i: integer;
begin
// CookieDomain := CopyTo(CookieDomain,'/');
result := '';
FCS.Enter;
try
for i := 0 to Self.Count - 1 do
if SameDomain(GetCookieDomain(Self[i]), CookieDomain) and
(GetCookieName(Self[i]) = CookieName) then
begin
result := MyHTTP.GetCookieValue(Self[i]);
Exit;
end;
finally
FCS.Leave;
end;
end;
function TMyCookieList.GetCookieByValue(CookieName, CookieDomain
: string): string;
var
i: integer;
begin
result := '';
FCS.Enter;
try
for i := 0 to Self.Count - 1 do
if SameDomain(GetCookieDomain(Self[i]), CookieDomain) and
(GetCookieName(Self[i]) = CookieName) then
begin
result := Self[i];
Exit
end;
finally
FCS.Leave;
end;
end;
procedure TMyIdHTTP.Head(AURL: string; AIgnoreReplies: array of SmallInt);
begin
// if fPAC and Assigned(fPACParser) then
doPAC(AURL);
DoRequest(Id_HTTPMethodHead, AURL, nil, nil, AIgnoreReplies);
// if fPAC and Assigned(fPACParser) then
// SetProxyParams(ProxyParams,p);
end;
function TMyIdHTTP.Get(AURL: string; AResponse: TStream): string;
begin
doPAC(AURL);
if AResponse = nil then
result := inherited Get(AURL)
else
begin
result := '';
inherited Get(AURL, AResponse);
end;
end;
function TMyIdHTTP.Get(AURL: string; AIgnoreReplies: array of SmallInt): string;
begin
doPAC(AURL);
result := inherited Get(AURL, AIgnoreReplies);
end;
function TMyIdHTTP.Post(AURL: string; ASource: TStrings): String;
begin
doPAC(AURL);
result := inherited Post(AURL, ASource);
end;
procedure TMyIdHTTP.Post(AURL: string; ASource: TStrings; AResponse: TStream);
begin
doPAC(AURL);
inherited Post(AURL, ASource, AResponse);
end;
procedure TMyIdHTTP.ReadCookies(url: string; AResponse: TIdHTTPResponse);
var
i: integer;
Cookie: string;
begin
for i := 0 to AResponse.RawHeaders.Count - 1 do
if pos('Set-Cookie: ', AResponse.RawHeaders[i]) > 0 then
begin
Cookie := SysUtils.StringReplace(AResponse.RawHeaders[i],
'Set-Cookie: ', '', []);
FCookieList.ChangeCookie(GetURLDomain(url), Cookie);
end;
end;
procedure TMyIdHTTP.WriteCookies(url: string; ARequest: TIdHTTPRequest);
var
Cookies: string;
begin
url := GetURLDomain(url);
Cookies := CookieList.GetCookiesByDomain(url);
if Cookies <> '' then
begin
Cookies := 'Cookie: ' + Copy(Cookies, 1, Length(Cookies) - 2);
// ARequest.RawHeaders.Clear;
ARequest.RawHeaders.Add(Cookies);
end;
end;
procedure TMyIdHTTP.DoSetCookies(AURL: String; ARequest: TIdHTTPRequest);
begin
// cs.Acquire;
// try
WriteCookies(AURL, ARequest);
// finally
// cs.Release;
// end;
end;
procedure TMyIdHTTP.doPAC(AURL: String);
var
Host: string;
Port, i: integer;
begin
if not(fPAC and Assigned(fPACParser)) then
Exit;
Host := fPACParser.GetProxy(ANSIString(AURL), ANSIString(GetURLDomain(AURL)));
if SameText(Host, 'direct') then
Host := '';
i := pos(':', Host);
if i > 0 then
begin
Port := StrToInt(CopyFromTo(Host, ':', ''));
Host := Copy(Host, 1, i - 1);
end
else
Port := 80;
with ProxyParams do
begin
BasicAuthentication := False;
ProxyServer := Host;
ProxyPort := Port;
ProxyUsername := '';
ProxyPassword := '';
end;
end;
procedure TMyIdHTTP.DoProcessCookies(ARequest: TIdHTTPRequest;
AResponse: TIdHTTPResponse);
begin
ReadCookies(ARequest.Host, AResponse);
end;
procedure TMyIdHTTP.SetCookieList(Value: TMyCookieList);
begin
if Value = nil then
begin
OnSetCookies := nil;
OnProcessCookies := nil;
end
else
begin
OnSetCookies := DoSetCookies;
OnProcessCookies := DoProcessCookies;
end;
FCookieList := Value;
end;
initialization
idThrottler := tidInterceptThrottler.Create(nil);
// cs := TCriticalSection.Create;
finalization
idThrottler.Free;
// cs.Free;
end.
|
unit uTransactionLogQuery;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uListFormBaseFrm, Buttons, jpeg, ExtCtrls, cxStyles,
cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB,
cxDBData, Menus, cxLookAndFeelPainters, StdCtrls, cxButtons, cxTextEdit,
cxContainer, cxMaskEdit, cxDropDownEdit, cxCalendar, cxGridLevel,
cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxGrid, DBClient, cxCheckBox,DateUtils,
cxTimeEdit, cxLabel,cxGridExportLink;
type
TTransactionLogQuery = class(TListFormBaseFrm)
Panel8: TPanel;
Image2: TImage;
btn_Edit: TSpeedButton;
Panel1: TPanel;
cdsLogList: TClientDataSet;
dsLogList: TDataSource;
cxGrid1: TcxGrid;
cxFiledList: TcxGridDBTableView;
cxGridLevel1: TcxGridLevel;
QDbegin: TcxDateEdit;
Label5: TLabel;
QDEnd: TcxDateEdit;
Label3: TLabel;
txt_QDBill: TcxTextEdit;
Label1: TLabel;
btn_QDQuery: TcxButton;
cdsLogListFID: TWideStringField;
cdsLogListFTRANSACTIONID: TWideStringField;
cdsLogListFTRANSACTIONNAME: TWideStringField;
cdsLogListFBEGINDATETIME: TDateTimeField;
cdsLogListFENDDATETIME: TDateTimeField;
cdsLogListFLOGTEXT: TWideStringField;
cdsLogListFISSUCCEED: TIntegerField;
cdsLogListFISDISPOSE: TIntegerField;
cdsLogListFDUTYUSERID: TWideStringField;
cdsLogListFDISPOSETIME: TDateTimeField;
cdsLogListFEXEXTYPE: TIntegerField;
cdsLogListFEXEXUSERID: TWideStringField;
cdsLogListDutyUserName: TWideStringField;
cdsLogListExecUserName: TWideStringField;
cxFiledListFID: TcxGridDBColumn;
cxFiledListFTRANSACTIONID: TcxGridDBColumn;
cxFiledListFTRANSACTIONNAME: TcxGridDBColumn;
cxFiledListFBEGINDATETIME: TcxGridDBColumn;
cxFiledListFENDDATETIME: TcxGridDBColumn;
cxFiledListFLOGTEXT: TcxGridDBColumn;
cxFiledListFISSUCCEED: TcxGridDBColumn;
cxFiledListFISDISPOSE: TcxGridDBColumn;
cxFiledListFDUTYUSERID: TcxGridDBColumn;
cxFiledListFDISPOSETIME: TcxGridDBColumn;
cxFiledListFEXEXTYPE: TcxGridDBColumn;
cxFiledListFExexUserID: TcxGridDBColumn;
cxFiledListDutyUserName: TcxGridDBColumn;
cxFiledListExecUserName: TcxGridDBColumn;
cdsLogListFSumTime: TFloatField;
cxFiledListSumTime: TcxGridDBColumn;
spt_ExportExcel: TSpeedButton;
SaveDg: TSaveDialog;
cxStyle_1: TcxStyleRepository;
cxStyle1: TcxStyle;
procedure cdsLogListFEXEXTYPEGetText(Sender: TField; var Text: String;
DisplayText: Boolean);
procedure FormShow(Sender: TObject);
procedure btn_QDQueryClick(Sender: TObject);
procedure btn_EditClick(Sender: TObject);
procedure cdsLogListCalcFields(DataSet: TDataSet);
procedure spt_ExportExcelClick(Sender: TObject);
procedure cxFiledListCustomDrawCell(Sender: TcxCustomGridTableView;
ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo;
var ADone: Boolean);
private
{ Private declarations }
public
{ Public declarations }
procedure Query;
end;
var
TransactionLogQuery: TTransactionLogQuery;
implementation
uses FrmCliDM,Pub_Fun,uMaterDataSelectHelper,StringUtilClass,uDrpHelperClase;
{$R *.dfm}
procedure TTransactionLogQuery.cdsLogListFEXEXTYPEGetText(Sender: TField;
var Text: String; DisplayText: Boolean);
begin
inherited;
if Sender.AsString ='0' then Text := '็ณป็ปๆง่ก' else
if Sender.AsString ='1' then Text := 'ๆๅจๆง่ก' ;
end;
procedure TTransactionLogQuery.Query;
var _SQL,ErrMsg:string;
begin
if trim(QDbegin.Text) = '' then
begin
ShowMsg(Handle, 'ๆง่กๅผๅงๆฅๆไธ่ฝไธบ็ฉบ! ',[]);
QDbegin.SetFocus;
exit;
end;
if trim(QDEnd.Text) = '' then
begin
ShowMsg(Handle, 'ๆง่ก็ปๆๆฅๆไธ่ฝไธบ็ฉบ! ',[]);
QDEnd.SetFocus;
exit;
end;
if DateUtils.MonthsBetween(QDbegin.Date,QDEnd.Date) > 12 then
begin
ShowMsg(Handle, 'ๆฅ่ฏขๆถ้ดๆฎตไธ่ฝ่ถ
่ฟ12ไธชๆ! ',[]);
QDEnd.SetFocus;
exit;
end;
_SQL := ' select logs.*,Duty.Fname_L2 as DutyUserName ,Exex.Fname_L2 as ExecUserName '
+' from T_BD_TransactionLog logs left join T_Pm_User Duty on logs.fdutyuserid = Duty.fid '
+' left join T_Pm_User Exex on Exex.fid = logs.fexexuserid where 1=1';
_SQL := _SQL+' and to_char(logs.FBeginDateTime ,''YYYY-MM-DD'')>='+Quotedstr(FormatDateTime('YYYY-MM-DD',QDbegin.Date))
+' and to_char(logs.FBeginDateTime ,''YYYY-MM-DD'')<='+Quotedstr(FormatDateTime('YYYY-MM-DD',QDEnd.Date));
if Trim(txt_QDBill.Text) <> '' then
_SQL := _SQL+' and logs.FTransactionName like ''%'+Trim(txt_QDBill.Text)+'%''';
_SQL := _SQL+' Order by logs.FBeginDateTime asc';
if Not CliDM.Get_OpenSQL(cdsLogList,_SQL,ErrMsg) then
begin
ShowMsg(Handle, 'ๆฅ่ฏขๅบ้:'+ErrMsg,[]);
Exit;
end;
end;
procedure TTransactionLogQuery.FormShow(Sender: TObject);
var FilePath : string;
begin
FilePath := ExtractFilePath(paramstr(0))+'\Img\Tool_bk.jpg';
if not LoadImage(FilePath,Image2) then Gio.AddShow('ๅพ็่ทฏๅพไธๅญๅจ๏ผ'+FilePath);
inherited;
QDbegin.Date := IncDay(Date,-30);
QDEnd.Date := Date;
Query;
end;
procedure TTransactionLogQuery.btn_QDQueryClick(Sender: TObject);
begin
inherited;
Query;
end;
procedure TTransactionLogQuery.btn_EditClick(Sender: TObject);
var _sql,ErrMsg,FID:string;
begin
inherited;
if cdsLogList.IsEmpty then Exit;
if cdsLogList.FieldByName('FIsDispose').AsInteger = 1 then
begin
ShowMsg(Handle, 'ๅฝๅ่ฎฐๅฝๆ ้กปๅค็! ',[]);
Exit;
end;
if cdsLogList.FieldByName('FDUTYUSERID').AsString <> '' then
if cdsLogList.FieldByName('FDUTYUSERID').AsString <> UserInfo.LoginUser_FID then
begin
ShowMsg(Handle, 'ๆจไธๆฏๅฝๅไบๅก็่ดฃไปปไบบ๏ผๆ ๆๅค็ไบๅกๆฅๅฟ! ',[]);
Exit;
end;
FID := cdsLogList.FieldByName('FID').AsString;
_sql := ' update T_BD_TransactionLog set FIsDispose = 1 and FDisposeTIME=sysdate where FID='+Quotedstr(FID);
if not CliDM.Get_ExecSQL(_sql,ErrMsg) then
begin
ShowMsg(Handle, 'ๅค็ๅคฑ่ดฅ:'+ErrMsg,[]);
Exit;
end;
cdsLogList.Edit;
cdsLogList.FieldByName('FIsDispose').AsInteger := 1 ;
cdsLogList.Post;
end;
procedure TTransactionLogQuery.cdsLogListCalcFields(DataSet: TDataSet);
var btime,eTime:TDateTime;
begin
inherited;
btime := DataSet.FieldByName('FBEGINDATETIME').AsDateTime;
eTime := DataSet.FieldByName('FENDDATETIME').AsDateTime;
DataSet.FieldByName('FSumTime').AsFloat := DateUtils.SecondsBetween(btime,eTime);
end;
procedure TTransactionLogQuery.spt_ExportExcelClick(Sender: TObject);
begin
inherited;
if cxFiledList.DataController.DataSource.DataSet.IsEmpty then Exit;
SaveDg.FileName := Self.Caption;
if SaveDg.Execute then
ExportGridToExcel(SaveDg.FileName, cxGrid1, True, true, True);
end;
procedure TTransactionLogQuery.cxFiledListCustomDrawCell(
Sender: TcxCustomGridTableView; ACanvas: TcxCanvas;
AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
var FISSUCCEED,FISDISPOSE:string;
ARec: TRect;
begin
inherited;
FISSUCCEED := Trim(AViewInfo.GridRecord.DisplayTexts[cxFiledListFISSUCCEED.Index]);
FISDISPOSE := Trim(AViewInfo.GridRecord.DisplayTexts[cxFiledListFISDISPOSE.Index]);
if Trim(FISSUCCEED) = '' then FISSUCCEED := '0';
if Trim(FISDISPOSE) = '' then FISDISPOSE := '0';
{ๅ็้ข่ฒไบคๆฟ
if AViewInfo.Item.Index mod 2 = 0 then
ACanvas.Canvas.brush.color := clInfoBk
else
ACanvas.Canvas.brush.color := clInactiveCaptionText;
}
if (UpperCase(FISSUCCEED) = 'FALSE' ) and (UpperCase(FISDISPOSE) = 'FALSE' )then
begin
ACanvas.Canvas.brush.color := clRed; //ๆด่กๅ่ฒ๏ผACanvas.Canvas.brush.color:=clred;
end;
ACanvas.Canvas.FillRect(ARec);
end;
end.
|
unit umfmLockboxTests;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uTPLb_Hash, uTPLb_BaseNonVisualComponent, uTPLb_CryptographicLibrary,
StdCtrls, uTPLb_Codec;
type
TmfmLockboxTests = class(TForm)
Hash1: THash;
Button1: TButton;
CryptographicLibrary1: TCryptographicLibrary;
Button2: TButton;
Memo1: TMemo;
Edit1: TEdit;
Codec1: TCodec;
CryptographicLibrary2: TCryptographicLibrary;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
mfmLockboxTests: TmfmLockboxTests;
implementation
uses uTPLb_StreamUtils, uTPLb_AES, uTPLb_BlockCipher, uTPLb_StreamCipher;
{$R *.dfm}
procedure TmfmLockboxTests.Button1Click( Sender: TObject);
const sBoolStrs: array[ boolean ] of string = ('Failed','Passed');
var
Ok: boolean;
begin
// This test passes ...
//Codec1.StreamCipherId := 'native.StreamToBlock';
//Codec1.BlockCipherId := 'native.AES-128';
//Codec1.ChainModeId := 'native.ECB';
//Codec1.Password := 'a';
//Memo1.Lines.Add( Format( '%s self test %s', [ Codec1.Cipher, sBoolStrs[ Codec1.SelfTest]]));
Codec1.StreamCipherId := 'native.StreamToBlock';
Codec1.BlockCipherId := 'native.AES-192';
Codec1.ChainModeId := 'native.CBC';
Codec1.Password := 'ab';
Ok := Codec1.SelfTest;
Memo1.Lines.Add( Format( '%s self test %s', [ Codec1.Cipher, sBoolStrs[ Ok]]));
//Codec1.StreamCipherId := 'native.StreamToBlock';
//Codec1.BlockCipherId := 'native.AES-256';
//Codec1.ChainModeId := 'native.CTR';
//Codec1.Password := 'abc';
//Memo1.Lines.Add( Format( '%s self test %s', [ Codec1.Cipher, sBoolStrs[ Codec1.SelfTest]]));
end;
end.
|
{
Lua4Lazarus
StringsObject
License: New BSD
Copyright(c)2010- Malcome@Japan All rights reserved.
}
unit l4l_strings;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, lua54, l4l_object;
type
{ TLuaStringsObject }
TLuaStringsObject = class(TLuaObject)
private
FStrings: TStringList;
function GetCommaText: string;
function GetCount: integer;
function GetText: string;
procedure SetCommaText(const AValue: string);
procedure SetText(const AValue: string);
protected
function Iterator(index: integer): integer; override;
public
property Strings: TStringList read FStrings;
constructor Create(L : Plua_State); override;
destructor Destroy; override;
published
function l4l_Add: integer;
function l4l_Insert: integer;
function l4l_Delete: integer;
function l4l_Clear: integer;
function l4l_IndexOf: integer;
function l4l_Sort: integer;
function l4l_SaveToFile: integer;
function l4l_LoadFromFile: integer;
function l4l_Strings: integer;
property l4l_Count: integer read GetCount;
property l4l_Text: string read GetText write SetText;
property l4l_CommaText: string read GetCommaText write SetCommaText;
end;
function CreateStringsObject(L : Plua_State) : Integer; cdecl;
implementation
{ TLuaStringsObject }
function TLuaStringsObject.GetText: string;
begin
Result := FStrings.Text;
end;
function TLuaStringsObject.GetCommaText: string;
begin
Result := FStrings.CommaText;
end;
function TLuaStringsObject.GetCount: integer;
begin
Result := FStrings.Count;
end;
procedure TLuaStringsObject.SetCommaText(const AValue: string);
begin
FStrings.CommaText:=AValue;
end;
procedure TLuaStringsObject.SetText(const AValue: string);
begin
FStrings.Text:=AValue;
end;
function TLuaStringsObject.Iterator(index: integer): integer;
begin
try
lua_pushstring(LS, PChar(FStrings[index]));
except
lua_pushnil(LS);
end;
Result:=1;
end;
constructor TLuaStringsObject.Create(L: Plua_State);
begin
inherited Create(L);
FStrings:= TStringList.Create;
end;
destructor TLuaStringsObject.Destroy;
begin
FStrings.Free;
inherited Destroy;
end;
function TLuaStringsObject.l4l_Add: integer;
begin
lua_pushinteger(LS, FStrings.Add(lua_tostring(LS, 1)));
Result:=1;
end;
function TLuaStringsObject.l4l_Insert: integer;
begin
FStrings.Insert(lua_tointeger(LS, 1), lua_tostring(LS, 2));
Result:=0;
end;
function TLuaStringsObject.l4l_Delete: integer;
begin
FStrings.Delete(lua_tointeger(LS, 1));
Result:=0;
end;
function TLuaStringsObject.l4l_Clear: integer;
begin
FStrings.Clear;
Result:=0;
end;
function TLuaStringsObject.l4l_IndexOf: integer;
begin
lua_pushinteger(LS, FStrings.IndexOf(lua_tostring(LS, 1)));
Result:=1;
end;
function TLuaStringsObject.l4l_Sort: integer;
begin
FStrings.Sort;
Result:=0;
end;
function TLuaStringsObject.l4l_SaveToFile: integer;
begin
FStrings.SaveToFile(lua_tostring(LS, 1));
Result:=0;
end;
function TLuaStringsObject.l4l_LoadFromFile: integer;
begin
FStrings.LoadFromFile(lua_tostring(LS, 1));
Result:=0;
end;
function TLuaStringsObject.l4l_Strings: integer;
begin
lua_pushstring(LS, PChar(FStrings[lua_tointeger(LS, 1)]));
Result:=1;
end;
function CreateStringsObject(L : Plua_State) : Integer; cdecl;
begin
l4l_PushLuaObject(TLuaStringsObject.Create(L));
Result := 1;
end;
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 uCEFFindHandler;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
uCEFBaseRefCounted, uCEFTypes, uCEFInterfaces;
type
TCefFindHandlerOwn = class(TCefBaseRefCountedOwn, ICefFindHandler)
protected
procedure OnFindResult(const browser: ICefBrowser; identifier, count: Integer; const selectionRect: PCefRect; activeMatchOrdinal: Integer; finalUpdate: Boolean); virtual; abstract;
public
constructor Create; virtual;
end;
TCustomFindHandler = class(TCefFindHandlerOwn)
protected
FEvent: IChromiumEvents;
procedure OnFindResult(const browser: ICefBrowser; identifier, count: Integer; const selectionRect: PCefRect; activeMatchOrdinal: Integer; finalUpdate: Boolean); override;
public
constructor Create(const events: IChromiumEvents); reintroduce; virtual;
destructor Destroy; override;
end;
implementation
uses
uCEFMiscFunctions, uCEFLibFunctions, uCEFBrowser;
procedure cef_find_handler_on_find_result(self: PCefFindHandler; browser: PCefBrowser; identifier, count: Integer; const selection_rect: PCefRect; active_match_ordinal, final_update: Integer); stdcall;
begin
with TCefFindHandlerOwn(CefGetObject(self)) do
OnFindResult(TCefBrowserRef.UnWrap(browser), identifier, count, selection_rect, active_match_ordinal, final_update <> 0);
end;
constructor TCefFindHandlerOwn.Create;
begin
CreateData(SizeOf(TCefFindHandler));
with PCefFindHandler(FData)^ do on_find_result := cef_find_handler_on_find_result;
end;
// TCustomFindHandler
constructor TCustomFindHandler.Create(const events: IChromiumEvents);
begin
inherited Create;
FEvent := events;
end;
destructor TCustomFindHandler.Destroy;
begin
FEvent := nil;
inherited Destroy;
end;
procedure TCustomFindHandler.OnFindResult(const browser: ICefBrowser; identifier, count: Integer; const selectionRect: PCefRect; activeMatchOrdinal: Integer; finalUpdate: Boolean);
begin
if (FEvent <> nil) then
FEvent.doOnFindResult(browser, identifier, count, selectionRect, activeMatchOrdinal, finalUpdate);
end;
end.
|
unit DebugUtils;
interface
uses
System.Types, System.Classes;
//function PtInCircle(const Point, Center: TPointF; Radius: Single): Boolean; overload;
//function PtInCircle(const Point, Center: TPoint; Radius: Integer): Boolean; overload;
procedure Debug(ALog: string); overload;
procedure Debug(ALog: string; args: array of const); overload;
procedure AddDebug(ALog: string); overload;
procedure AddDebug(ALog: string; args: array of const); overload;
procedure PrintLog;
procedure ConditionalDebug(ALog: string; args: array of const); overload;
var
DebugStart: Boolean = False;
List: TStringList;
implementation
uses
System.SysUtils
{$IFDEF MACOS}
{$ENDIF}
{$IFDEF MSWINDOWS}
, WinAPI.Windows
{$ENDIF}
;
procedure Debug(ALog: string);
begin
{$IFNDEF DEBUG}
Exit;
{$ENDIF}
{$IFDEF MACOS}
{$ENDIF}
{$IFDEF MSWINDOWS}
OutputDebugString(PChar(ALog));
{$ENDIF}
end;
procedure Debug(ALog: string; args: array of const);
begin
Debug(Format(ALog, args));
end;
procedure AddDebug(ALog: string);
begin
if not Assigned(List) then
List := TStringList.Create;
List.Add(ALog);
end;
procedure AddDebug(ALog: string; args: array of const);
begin
AddDebug(Format(ALog, args));
end;
procedure PrintLog;
var
Log: string;
begin
if not Assigned(List) then
Exit;
for Log in List do
Debug(Log);
end;
procedure ConditionalDebug(ALog: string; args: array of const);
begin
if DebugStart then
Debug(Format(ALog, args));
end;
//function PtInCircle(const Point, Center: TPointF; Radius: Single): Boolean;
//begin
// if Radius > 0 then
// begin
// Result := Sqr(Point.X - Center.X) + Sqr(Point.Y - Center.Y) <= Sqr(Radius);
//// Result := Sqr((Point.X - Center.X) / Radius) +
//// Sqr((Point.Y - Center.Y) / Radius) <= 1;
// end
// else
// begin
// Result := False;
// end;
//end;
initialization
finalization
if Assigned(List) then
List.Free;
end.
|
unit PassGen;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Controls.Presentation, FMX.Edit, FMX.NumberBox, FMX.EditBox, FMX.SpinBox,
FMX.Platform;
type
TCharacterSet = set of (pmUpper, pmLower, pmNumbers, pmSpecial);
type
TFrmPassGen = class(TForm)
EdtResul: TEdit;
GrbCharacter: TGroupBox;
ChbLower: TCheckBox;
ChbUpper: TCheckBox;
ChbNumbe: TCheckBox;
ChbSpeci: TCheckBox;
GrbLength: TGroupBox;
SpbLengt: TSpinBox;
Panel: TPanel;
BtnGener: TButton;
BtnCancel: TButton;
BtnAccept: TButton;
Label1: TLabel;
procedure BtnGenerClick(Sender: TObject);
procedure ChbPModeClick(Sender: TObject);
procedure ChbSpeciClick(Sender: TObject);
procedure BtnAcceptClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private-Deklarationen }
function GenPassword(iLength: integer; Mode: TCharacterSet):string;
public
{ Public-Deklarationen }
end;
var
FrmPassGen: TFrmPassGen;
implementation
{$R *.fmx}
procedure TFrmPassGen.ChbPModeClick(Sender: TObject);
begin
BtnGener.Enabled := ChbLower.IsChecked or ChbUpper.IsChecked or
ChbNumbe.IsChecked or ChbSpeci.IsChecked;
end;
procedure TFrmPassGen.ChbSpeciClick(Sender: TObject);
begin
ChbSpeci.OnClick := nil;
ChbSpeci.OnChange := nil;
end;
procedure TFrmPassGen.FormShow(Sender: TObject);
begin
BtnGener.OnClick(Self);
end;
function TFrmPassGen.GenPassword(iLength: integer; Mode: TCharacterSet):string;
const
cLower = 'abcdefghijklmnopqrstuvwxyz';
cUpper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
cNumbers = '0123456789';
cSpecial = 'ยฐ!"ยง$&/()=-+*?ร}{][@.,;:_~';
var
i : Integer;
S : string;
iM: BYTE;
begin
if Mode = [] then Exit;
i := 0;
Randomize;
while (i < iLength) do
begin
iM := Random(4);
case iM of
0: if (pmLower in Mode) then
begin
S := S + cLower[1 + Random(Length(cLower)-1)];
Inc(i);
end;
1: if (pmUpper in Mode) then
begin
S := S + cUpper[1 + Random(Length(cUpper)-1)];
Inc(i);
end;
2: if (pmNumbers in Mode) then
begin
S := S + cNumbers[1 + Random(Length(cNumbers)-1)];
Inc(i);
end;
3: if (pmSpecial in Mode) then
begin
S := S + cSpecial[1 + Random(Length(cSpecial)-1)];
Inc(i);
end;
end;
end;
Result := S;
end;
procedure TFrmPassGen.BtnAcceptClick(Sender: TObject);
begin
Close;
end;
procedure TFrmPassGen.BtnGenerClick(Sender: TObject);
var
Mode: TCharacterSet;
begin
Mode := [];
if ChbLower.IsChecked then
Mode := Mode + [pmLower];
if ChbUpper.IsChecked then
Mode := Mode + [pmUpper];
if ChbNumbe.IsChecked then
Mode := Mode + [pmNumbers];
if ChbSpeci.IsChecked then
Mode := Mode + [pmSpecial];
EdtResul.Text := GenPassword(StrToInt(SpbLengt.Text), Mode);
end;
end.
|
unit CoachMain;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs, ExtCtrls,
Menus, IniPropStorage, IniFiles, Roles, StdCtrls, lNetComponents,
LogCompat, DecConsts, lNet, WLan, Main, DOM, XMLRead;
type
TRobotStateForm = record
CBRobotActive, CBForceRobotActive: TCheckBox;
EditRobotState: TEdit;
end;
TObsStates = record
Obs: array[0..MaxRobots-1] of TObstacle;
end;
{ TFCoachMain }
TFCoachMain = class(TForm)
BRefBoxConnect: TButton;
BRefBoxDisconnect: TButton;
ButtonStop: TButton;
ButtonStart: TButton;
CBForceRobotActive2: TCheckBox;
CBForceRobotActive3: TCheckBox;
CBForceRobotActive4: TCheckBox;
CBForceRobotActive5: TCheckBox;
CBForceRobotActive6: TCheckBox;
CBRobotActive1: TCheckBox;
CBRobotActive2: TCheckBox;
CBRobotActive3: TCheckBox;
CBRobotActive4: TCheckBox;
CBRobotActive5: TCheckBox;
CBRobotActive6: TCheckBox;
CBForceRobotActive1: TCheckBox;
CBRobotForceActive2: TCheckBox;
CBRobotForceActive3: TCheckBox;
CBRobotForceActive4: TCheckBox;
CBRobotForceActive5: TCheckBox;
CBRobotForceActive6: TCheckBox;
CBKeeperActive: TCheckBox;
CheckBoxOtherTactic: TCheckBox;
EditVbatRobot5: TEdit;
EditVbatRobot3: TEdit;
EditVbatRobot2: TEdit;
EditVbatRobot4: TEdit;
EditVbatRobot1: TEdit;
EditRobotState1: TEdit;
EditRobotActive2: TEdit;
EditRobotActive3: TEdit;
EditRobotActive4: TEdit;
EditRobotActive5: TEdit;
EditRobotActive6: TEdit;
EditRobotAvailableCount: TEdit;
EditPlayState: TEdit;
EditRefBoxIP: TEdit;
EditMessIP: TEdit;
EditRefState: TEdit;
EditRobotState2: TEdit;
EditRobotState3: TEdit;
EditRobotState4: TEdit;
EditRobotState5: TEdit;
EditRobotState6: TEdit;
GBRefBox: TGroupBox;
GBRobotInfo1: TGroupBox;
GBRobotInfo2: TGroupBox;
GBRobotInfo3: TGroupBox;
GBRobotInfo4: TGroupBox;
GBRobotInfo5: TGroupBox;
GBRobotInfo6: TGroupBox;
ImageMap: TPaintBox;
FormStorage: TIniPropStorage;
Label1: TLabel;
Label2: TLabel;
UDPRefBox: TLUDPComponent;
MemoRefBoxBad: TMemo;
MemoRefBox: TMemo;
RGDecision: TRadioGroup;
RGRobotSel: TRadioGroup;
TCPRefBox: TLTCPComponent;
MainMenu: TMainMenu;
MenuAbout: TMenuItem;
MenuExit: TMenuItem;
MenuFile: TMenuItem;
MenuWindows: TMenuItem;
N1: TMenuItem;
TimerDoTactic: TTimer;
procedure BRefBoxConnectClick(Sender: TObject);
procedure BRefBoxDisconnectClick(Sender: TObject);
procedure ButtonStartClick(Sender: TObject);
procedure ButtonStopClick(Sender: TObject);
procedure CBForceRobotActive1Change(Sender: TObject);
procedure CBForceRobotActive2Change(Sender: TObject);
procedure CBKeeperActiveChange(Sender: TObject);
procedure CBRobotActive1Change(Sender: TObject);
procedure CBRobotActive2Change(Sender: TObject);
procedure EditRefBoxIPChange(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure ImageMapMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure ImageMapMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure MenuAboutClick(Sender: TObject);
procedure MenuExitClick(Sender: TObject);
procedure MenuWinDefaultClick(Sender: TObject);
procedure RGDecisionClick(Sender: TObject);
procedure SdpoUDPCoachReceive(aSocket: TLSocket);
procedure ShowAll;
procedure MainLoop;
procedure TCPRefBoxAccept(aSocket: TLSocket);
procedure TCPRefBoxReceive(aSocket: TLSocket);
procedure TimerDoTacticTimer(Sender: TObject);
procedure ParseRefBoxData(data: String);
procedure ParseRefBoxUDPData(data: String);
procedure ParseRefBoxUDPData(data, attr: String);
procedure ParseXmlData(xmldata: string);
procedure ShowRobotTimes(var RS: TRobotstate; var RSF: TRobotStateForm; robnum:integer);
procedure MergeBallState;
procedure UDPRefBoxReceive(aSocket: TLSocket);
private
{ private declarations }
public
{ public declarations }
NetTime: DWORD;
deb_txt: string;
AuxForms: array[0..MaxAuxForms-1] of TForm;
NumAuxForms: integer;
DataDir: string;
down_x,down_y: integer;
procedure ProcessPlayerPacket(packet_str: string);
procedure SendCoachInfo;
procedure InsertAuxForms(Fm: TForm; cap: string);
procedure AuxFormClosed(cap: string);
procedure SaveAuxForms;
procedure CloseAuxForms;
procedure RestoreAuxForms;
procedure SetRobotStateForm;
end;
var
FCoachMain: TFCoachMain;
BallStates,LastBallStates: array[0..MaxRobots-1] of TBallState;
BallsFiltered: array[0..MaxRobots-1] of double;
ObsStates: array[0..MaxRobots-1] of TObsStates;
RobotStateForm: array[0..MaxRobots-1] of TRobotStateForm;
implementation
uses Field, Robots, Utils, Tactic, Param;
{ TFCoachMain }
procedure TFCoachMain.MenuExitClick(Sender: TObject);
begin
Close;
end;
procedure TFCoachMain.MenuAboutClick(Sender: TObject);
begin
Showmessage('5dpo2000 Coach'+#$0d+'(c)2008 5dpo');
end;
procedure TFCoachMain.FormCreate(Sender: TObject);
var SessionPropsList: TStringList;
SessionPropsFileName: string;
begin
NumAuxForms:=0;
if paramcount>=1 then begin
DataDir:=paramstr(1);
if not directoryExists(extractfilepath(application.ExeName)+DataDir) then DataDir:=DataPath+'data';
end else begin
DataDir:=DataPath+'data'
end;
// FormStorage.IniFileName:=extractfilepath(application.ExeName)+'\'+dataDir+'\Config.ini';
if not DirectoryExists(ExtractFilePath(Application.ExeName)+DataDir) then
mkdir(ExtractFilePath(Application.ExeName)+DataDir);
SessionPropsFileName := ExtractFilePath(Application.ExeName)+DataDir+'/SessionPropsMain.txt';
if FileExists(SessionPropsFileName) then begin
SessionPropsList := TStringList.Create;
try
SessionPropsList.LoadFromFile(SessionPropsFileName);
SessionPropsList.Delimiter:=';';
SessionProperties := SessionPropsList.DelimitedText;
finally
SessionPropsList.Free;
end;
end;
FormStorage.IniFileName:=ExtractFilePath(Application.ExeName)+DataDir+'/Config.ini';
FormStorage.Restore;
SetRobotStateForm;
end;
procedure TFCoachMain.SetRobotStateForm;
begin
with RobotStateForm[0] do begin
CBForceRobotActive:=CBForceRobotActive1;
CBRobotActive:=CBRobotActive1;
EditRobotState:=EditRobotState1;
end;
with RobotStateForm[1] do begin
CBForceRobotActive:=CBForceRobotActive2;
CBRobotActive:=CBRobotActive2;
EditRobotState:=EditRobotState2;
end;
with RobotStateForm[2] do begin
CBForceRobotActive:=CBForceRobotActive3;
CBRobotActive:=CBRobotActive3;
EditRobotState:=EditRobotState3;
end;
with RobotStateForm[3] do begin
CBForceRobotActive:=CBForceRobotActive4;
CBRobotActive:=CBRobotActive4;
EditRobotState:=EditRobotState4;
end;
with RobotStateForm[4] do begin
CBForceRobotActive:=CBForceRobotActive5;
CBRobotActive:=CBRobotActive5;
EditRobotState:=EditRobotState5;
end;
with RobotStateForm[5] do begin
CBForceRobotActive:=CBForceRobotActive6;
CBRobotActive:=CBRobotActive6;
EditRobotState:=EditRobotState6;
end;
end;
procedure TFCoachMain.FormShow(Sender: TObject);
begin
RestoreAuxForms;
UpdateFieldDims;
Dfieldmag:=Dfieldmag/20*35; //Big canvas ratio
TimerDoTactic.Enabled := true;
end;
procedure TFCoachMain.ImageMapMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
down_x:=x;
down_y:=y;
end;
procedure TFCoachMain.ImageMapMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var Xw,Yw,V: double;
//Mess: THighMessage;
new_teta: double;
begin
// new_teta:=atan2(-Y+down_y,X-down_x);
new_teta:=atan2(-Y+down_y,X-down_x);
MapToWorld(down_x,down_y,xw,yw);
V:=sqrt(sqr(-Y+down_y)+sqr(X-down_x));
{ if CBSimulator.Checked then begin
with BallState do begin
x:=xw;
y:=yw;
Vx:=V*cos(new_teta)*0.1;
Vy:=V*sin(new_teta)*0.1;
end;
end;
end else begin
if RGRobotSel.ItemIndex<>6 then begin
with RobotState[RGRobotSel.ItemIndex] do begin
x:=xw;
y:=yw;
teta:=new_teta;
end; }
if ssShift in Shift then begin
with BallState do begin
x:=xw;
y:=yw;
//Vx:=V*cos(new_teta)*0.1;
//Vy:=V*sin(new_teta)*0.1;
end;
end else begin
with RobotState[RGRobotSel.ItemIndex] do begin
x:=xw;
y:=yw;
teta:=new_teta;
end;
end;
end;
procedure TFCoachMain.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
SaveAuxForms;
CloseAuxForms;
TCPRefBox.Disconnect;
FMain.Close;
end;
procedure TFCoachMain.BRefBoxConnectClick(Sender: TObject);
begin
TCPRefBox.Connect(EditRefBoxIP.Text, 28097);
UDPRefBox.Listen(30000);
end;
procedure TFCoachMain.BRefBoxDisconnectClick(Sender: TObject);
begin
TCPRefBox.Disconnect;
UDPRefBox.Disconnect;
end;
procedure TFCoachMain.ButtonStartClick(Sender: TObject);
begin
RefereeState:=rsStartPos;
end;
procedure TFCoachMain.ButtonStopClick(Sender: TObject);
begin
RefereeState:=rsStopPos;
end;
procedure TFCoachMain.CBForceRobotActive1Change(Sender: TObject);
begin
end;
procedure TFCoachMain.CBForceRobotActive2Change(Sender: TObject);
begin
end;
procedure TFCoachMain.CBKeeperActiveChange(Sender: TObject);
begin
if CBKeeperActive.Checked then begin
KeeperWay:=roleKeeper;
end else begin
KeeperWay:=roleKeeperPassive;
end;
//RobotStatus[0].default_role:=KeeperWay;
end;
procedure TFCoachMain.CBRobotActive1Change(Sender: TObject);
begin
end;
procedure TFCoachMain.CBRobotActive2Change(Sender: TObject);
begin
end;
procedure TFCoachMain.EditRefBoxIPChange(Sender: TObject);
begin
end;
procedure TFCoachMain.InsertAuxForms(Fm: TForm; cap: string);
var NewItem: TMenuItem;
begin
NewItem := TMenuItem.Create(Self); //first create the separator
NewItem.Caption := cap;
NewItem.tag := NumAuxForms;
NewItem.OnClick := @MenuWinDefaultClick;
MenuWindows.Add(NewItem); //add the new item to the Windows menu
if NumAuxForms<MaxAuxForms-1 then begin
AuxForms[NumAuxForms]:=Fm;
inc(NumAuxForms);
end;
end;
procedure TFCoachMain.AuxFormClosed(cap: string);
var i: integer;
begin
for i := 0 to NumAuxForms - 1 do begin
if MenuWindows.Items[i].Caption = cap then begin
MenuWindows.Items[i].Checked := false;
exit;
end;
end;
end;
procedure TFCoachMain.MenuWinDefaultClick(Sender: TObject);
var MenuItem: TMenuItem;
begin
MenuItem:=Sender as TMenuItem;
// if not AuxForms[MenuItem.Tag].visible then begin
MenuItem.Checked:=true;
AuxForms[MenuItem.Tag].Show;
AuxForms[MenuItem.Tag].BringToFront;
// end;
end;
procedure TFCoachMain.RGDecisionClick(Sender: TObject);
begin
end;
procedure TFCoachMain.SdpoUDPCoachReceive(aSocket: TLSocket);
var PlayerInfo: TPlayerInfo;
packet_str: string;
i, RobotNumber: integer;
begin
try
aSocket.GetMessage(packet_str);
// only accpet valid length packets
if length(packet_str) <> sizeof(PlayerInfo) then exit;
copymemory(@PlayerInfo, @(packet_str[1]), sizeof(PlayerInfo));
if PlayerInfo.Magic <> PACKET_PLAYER_MAGIC then exit;
EditMessIP.Text:= aSocket.PeerAddress;
{ RobotNumber := PlayerInfo.RobotState.;
// send my robot state
with RobotState[MyNumber] do begin
PlayerInfo.RobotState.x := x;
PlayerInfo.RobotState.y := y;
PlayerInfo.RobotState.teta := teta;
PlayerInfo.RobotState.conf := count; //TODO: calculate confidence level
end;
// send the ball state
PlayerInfo.BallState.x := BallState.x;
PlayerInfo.BallState.y := BallState.y;
PlayerInfo.BallState.conf := BallState.quality;
// send the obstacles
// TODO: actually send the obstacles
zeromemory(@(PlayerInfo.ObsState), sizeof(PlayerInfo.ObsState));
packet_str := StringOfChar(#0, sizeof(PlayerInfo));
copymemory(@(packet_str[1]), @PlayerInfo, sizeof(PlayerInfo));
SdpoUDPSuper.SendMessage(packet_str, FParam.EditSuperIP.Text + ':7373');}
except
end;
end;
procedure TFCoachMain.SaveAuxForms;
var i: integer;
Ini: TIniFile;
begin
Ini := TIniFile.Create(FormStorage.IniFileName);
try
for i:=0 to MenuWindows.Count-1 do begin
Ini.WriteInteger('WINDOWS',MenuWindows.items[i].Caption+'_Visible',ord(MenuWindows.items[i].Checked));
end;
finally
Ini.Free;
end;
end;
procedure TFCoachMain.CloseAuxForms;
var
i: integer;
begin
for i:=0 to MenuWindows.Count-1 do begin
AuxForms[MenuWindows.items[i].tag].Close;
end;
end;
procedure TFCoachMain.RestoreAuxForms;
var i: integer;
Ini: TIniFile;
begin
Ini := TIniFile.Create(FormStorage.IniFileName);
try
for i:=0 to MenuWindows.Count-1 do begin
if Ini.readInteger('WINDOWS',MenuWindows.items[i].Caption+'_Visible',0)<>0 then begin
MenuWindows.items[i].Checked:=true;
AuxForms[MenuWindows.items[i].tag].Show;
end;
end;
finally
Ini.Free;
end;
end;
procedure TFCoachMain.ShowRobotTimes(var RS: TRobotstate; var RSF: TRobotStateForm; robnum:integer);
begin
RSF.EditRobotState.Text:=format('%.2f',[(getTickcount-RS.timestamp)/1000]);//format('%2f',[GetTickCount-RS.timestamp]);
if (getTickcount-RS.timestamp)/1000 > 10 then begin
RobotStatus[robnum].Active:=false;
end;
if RobotStatus[robnum].Active then begin
RSF.EditRobotState.Color:=clGreen;
end else begin
RSF.EditRobotState.Color:=clRed;
end;
end;
procedure TFCoachMain.ShowAll;
var i,tx,ty: integer;
cl: Tcolor;
begin
//if CBShow.Checked then begin
FMain.DrawFieldMap(ImageMap.canvas);
for i:=0 to MaxRobots-1 do begin
//if i=myNumber then cl:=clwhite else cl:=CTeamColorColor24[TeamColor];
DrawRobot(RobotState[i],cl,ImageMap.canvas);
DrawRobotInfo(RobotState[i],RobotInfo[i],ImageMap.canvas);
ShowRobotTimes(RobotState[i],RobotStateForm[i],i);
end;
FMain.DrawBall(ImageMap.canvas,BallState,clred);
{with ImageShow.Canvas do begin
brush.Style:=bsSolid;
brush.Color:=clBlack;
pen.color:=clBlack;
Rectangle(0,0,width,height);
end;
if CBShowCenters.Checked then ShowCenters;
if CBShowEdges.Checked then ShowEdges;
if CBShowRadar.Checked then ShowRadar;
if CBShowRegions.Checked then ShowRegions;
ShowLine(GWLine);
ShowLine(WGLine);
Gtext.Clear;
FillShowValues(Gtext,RobotState[myNumber], BallState, View);
if CBShowLog.Checked then FLog.LogToStrings(GText,FLog.TreeView,LogBufferIn);
tx:=draw_x;
ty:=draw_y;
ImageShow.canvas.Font.Color:=clgray;
ImageShow.canvas.brush.Style:=bsClear;
StringsDraw(ImageShow.canvas,Gtext,tx,ty);}
//end;
end;
procedure TFCoachMain.MainLoop;
var i,j: integer;
begin
NetTime:=getTickcount();
deb_txt:='';
{ResetView;
ParseLanMess;
UpdateEdges;
UpdateRadar;
UpdateOdos;
UpdateCenters([iYellowGoal,iBlueGoal]);
// TODO localization
//Localize;
UpdateCenters([iBallColor,iPurpleTeam,iCyanTeam]);
UpdateObstacles;
PropagateObstacles;
for i:=0 to MaxRobots-1 do begin
if i=mynumber then
PropagateXYTeta(RobotState[i])
else
PropagateXYTetaOthers(RobotState[i]);
end;
LastBallState:=BallState;
LastObsBallState:=ObsBallState;
PropagateXYBall(BallState);
ExtractBallFromCenters(ObsBallState);
if ObsBallState.quality>=0 then begin
MergeBallState(LastObsBallState,ObsBallState);
MergeBallState(BallState,ObsBallState);
end;
MainControl;
deb_txt:=deb_txt+format('%3d',[getTickcount()-NetTime]);
sleep(1);
//MainHighMessage;
SendPlayerInfo;
deb_txt:=deb_txt+format(',%3d',[getTickcount()-NetTime]);
if RGController.ItemIndex=0 then // freeze
FLog.LogFrame(GetTickCount,0,0)
else
FLog.LogFrame(GetTickCount,0,1);
deb_txt:=deb_txt+format(',%3d',[getTickcount()-NetTime]);
}
ShowAll;
deb_txt:=deb_txt+format(',%3d',[getTickcount()-NetTime]);
//LastView:=View;
//EditTimes.text:=deb_txt;
//inc(cycleCount);
end;
procedure TFCoachMain.TCPRefBoxAccept(aSocket: TLSocket);
begin
end;
procedure TFCoachMain.TCPRefBoxReceive(aSocket: TLSocket);
var data: string;
begin
TCPRefBox.GetMessage(data);
//MemoRefBox.Append(data);
ParseRefBoxData(data);
end;
procedure TFCoachMain.ParseRefBoxData(data: String);
var i: integer;
command,s: string;
c: char;
begin
//LastData := data;
//StartCount:=GetTickCount();
command := '';
//while MemoRefBox.Lines.Count > 100 do MemoRefBox.Lines.Delete(0);
while MemoRefBoxBad.Lines.Count > 4 do MemoRefBoxBad.Lines.Delete(0);
for i:=1 to length(data) do begin
if data[i]=#0 then continue;
command:=command+data[i];
end;
if (length(command) <> 1) and (command<>'1s') and (command<>'2s')
and (command<>'Hh') and (command<>'He') and (command<>'N') then
begin
MemoRefBoxBad.Lines.Add(command);
exit;
end;
//if ( (command <> 'K' ) ) then exit;
//MemoRefBoxBad.Lines.Add(command);
//MemoRefBox.Lines.Add(command);
//FCoachMain.MemoRefBox.Clear;
//FCoachMain.MemoRefBox.Append(command[1]);
c := command[1];
s := copy(command,1,1);
FCoachMain.MemoRefBox.Append(c);
FCoachMain.MemoRefBox.Append(s);
if command = '1s' then c := 's';
if command = '2s' then c := 's';
if c='*' then ; // nothing
TacticProcessRefereeComand(c);
end;
procedure TFCoachMain.ParseRefBoxUDPData(data: String);
var i: integer;
command: string;
c: char;
begin
c:=' ';
if data='GameStart' then c:='s'
else if data='GameStop' then c:='S'
else if data='Cancel' then c:='H' //?
else if data='DroppedBall' then c:='@' //?
else if data='StageChange' then ; //????
TacticProcessRefereeComand(c);
end;
procedure TFCoachMain.ParseRefBoxUDPData(data, attr: String);
var i: integer;
command: string;
c: char;
begin
c:=' ';
//assumes that we are cyan, need to review this
if data='KickOff' then begin
if attr='Cyan' then
c:='k'
else
c:='K';
end else if data='FreeKick' then begin
if attr='Cyan' then
c:='f'
else
c:='F';
end else if data='GoalKick' then begin
end else if data='ThrowIn' then begin
end else if data='Corner' then begin
end else if data='Penalty' then begin
if attr='Cyan' then
c:='p'
else
c:='P';
end else if data='Substitution' then begin
end else if data='CardAwarded' then begin
end else if data='GoalAwarded' then begin
end;
TacticProcessRefereeComand(c);
end;
procedure TFCoachMain.ParseXmlData(xmldata: string);
var
Child: TDOMNode;
doc: TXMLDocument;
s: TStringStream;
i: integer;
begin
s:=TStringStream.Create(xmldata);
try
s.Position:=0;
ReadXMLFile(doc,s);
Child:=doc.DocumentElement.FirstChild;
while Assigned(Child) do begin
EditMessIP.Text:=Child.Attributes.Item[2].NodeValue+': '+Child.Attributes.Item[1].NodeValue;
with Child.ChildNodes do
try
for i := 0 to (Count-1) do begin
if ((Item[i].NodeName = 'GameStart') or (Item[i].NodeName = 'GameStop') or (Item[i].NodeName = 'Cancel') or (Item[i].NodeName = 'DroppedBall') or (Item[i].NodeName = 'StageChange')) then
ParseRefBoxUDPData(Item[i].NodeName)
else
ParseRefBoxUDPData(Item[i].NodeName, Item[i].Attributes.Item[0].NodeValue);
end;
finally
free;
end;
Child:=Child.NextSibling;
end;
finally
s.Free;
end;
end;
procedure TFCoachMain.MergeBallState;
var ball_filt, BestBall: double;
i,BestBallIdx,quality: integer;
begin
ball_filt := 0.7;
BestBall:=0;
BestBallIdx:=-1;
quality:=0;
for i:=0 to MaxRobots-1 do begin
// filtro
BallsFiltered[i] := ball_filt*BallsFiltered[i] + (1-ball_filt)*BallStates[i].quality;
if RobotStatus[i].active and (BallsFiltered[i]>BestBall) then begin
BestBall:=BallsFiltered[i];
BestBallIdx:=i;
end;
end;
// the best robot seeing the ball is used to update the new ball position
if BestBallIdx>=0 then begin
BallState:=BallStates[BestBallIdx];
BallState.timestamp:=GetTickCount;
end;
end;
procedure TFCoachMain.UDPRefBoxReceive(aSocket: TLSocket);
var
xmldata: string;
begin
UDPRefBox.GetMessage(xmldata);
ParseXmlData(xmldata);
end;
procedure TFCoachMain.TimerDoTacticTimer(Sender: TObject);
begin
MergeBallState;
DoTactic;
SendCoachInfo;
ShowAll;
end;
{procedure TFCoachMain.SdpoUDPSuperReceive(aSocket: TLSocket);
var CoachInfo: TCoachInfo;
packet_str: string;
i: integer;
begin
try
aSocket.GetMessage(packet_str);
// only accpet valid length packets
if length(packet_str) <> sizeof(CoachInfo) then exit;
copymemory(@CoachInfo, @(packet_str[1]), sizeof(CoachInfo));
if CoachInfo.Magic <> PACKET_COACH_MAGIC then exit;
for i := 0 to MaxRobots - 1 do begin
// update robot role
if RobotInfo[i].role <> CoachInfo.RobotState[i].role then begin
with RobotInfo[i] do begin
roleTime := GetTickCount;
last_role := role;
role := CoachInfo.RobotState[i].role;
ZeroMemory(@TaskPars[i], sizeof(TaskPars[0]));
end;
end;
// don't update my own state
if i = MyNumber then continue;
// update all others
with CoachInfo.RobotState[i] do begin
RobotState[i].count := Ord(active);
RobotState[i].x := x;
RobotState[i].y := y;
RobotState[i].teta := teta;
RobotStatus[i].active := active;
end;
end;
// if I'm not seeing the ball, I have to trust the coach
if BallState.quality < 0 then begin
BallState.x := CoachInfo.BallState.x;
BallState.y := CoachInfo.BallState.y;
BallState.quality := 0;
end;
except
end;
end;}
{procedure TFCoachMain.SendPlayerInfo;
var PlayerInfo: TPlayerInfo;
packet_str: string;
i: integer;
begin
try
PlayerInfo.Magic := PACKET_PLAYER_MAGIC;
// send my robot state
with RobotState[MyNumber] do begin
PlayerInfo.RobotState.x := x;
PlayerInfo.RobotState.y := y;
PlayerInfo.RobotState.teta := teta;
PlayerInfo.RobotState.conf := count; //TODO: calculate confidence level
end;
// send the ball state
PlayerInfo.BallState.x := BallState.x;
PlayerInfo.BallState.y := BallState.y;
PlayerInfo.BallState.conf := BallState.quality;
// send the obstacles
// TODO: actually send the obstacles
zeromemory(@(PlayerInfo.ObsState), sizeof(PlayerInfo.ObsState));
packet_str := StringOfChar(#0, sizeof(PlayerInfo));
copymemory(@(packet_str[1]), @PlayerInfo, sizeof(PlayerInfo));
SdpoUDPSuper.SendMessage(packet_str, FParam.EditSuperIP.Text + ':7373');
except
end;
end;}
procedure TFCoachMain.ProcessPlayerPacket(packet_str: string);
var PlayerInfo: TPlayerInfo;
i: integer;
begin
if length(packet_str) <> sizeof(PlayerInfo) then exit;
copymemory(@PlayerInfo, @(packet_str[1]), sizeof(PlayerInfo));
if PlayerInfo.Magic <> PACKET_PLAYER_MAGIC then exit;
// update ONE robot state
with RobotState[PlayerInfo.num] do begin
case PlayerInfo.num of
0:EditVbatRobot1.Text:=format('%2f',[Vbatery]);
1:EditVbatRobot2.Text:=format('%2f',[Vbatery]);
2:EditVbatRobot3.Text:=format('%2f',[Vbatery]);
3:EditVbatRobot4.Text:=format('%2f',[Vbatery]);
4:EditVbatRobot5.Text:=format('%2f',[Vbatery]);
end;
x:=PlayerInfo.RobotState.x;
y:=PlayerInfo.RobotState.y;
Vbatery:=PlayerInfo.Batery;
teta:=PlayerInfo.RobotState.teta;
count:=Round(PlayerInfo.RobotState.conf);
timestamp:=GetTickCount;
end;
with RobotStatus[PlayerInfo.num] do begin
if RobotStateForm[PlayerInfo.num].CBForceRobotActive.Checked then begin
Active:=RobotStateForm[PlayerInfo.num].CBRobotActive.Checked
end else
if (RobotStateForm[PlayerInfo.num].CBRobotActive.Checked) and (PlayerInfo.RobotState.Active) then begin
active:=true;
end else begin
active:=false;
end;
end;
// update this robot's ball state for future merging
with BallStates[PlayerInfo.num] do begin
x:=PlayerInfo.BallState.x;
y:=PlayerInfo.BallState.y;
vx:=PlayerInfo.BallState.vx;
vy:=PlayerInfo.BallState.vy;
x_n:=PlayerInfo.BallState.x_n;
y_n:=PlayerInfo.BallState.y_n;
vx_n:=PlayerInfo.BallState.vx_n;
vy_n:=PlayerInfo.BallState.vy_n;
x_next:=PlayerInfo.BallState.x_next;
y_next:=PlayerInfo.BallState.y_next;
quality:=PlayerInfo.BallState.quality;
end;
for i:=0 to MaxRobots-1 do begin
with ObsStates[PlayerInfo.num] do begin
Obs[i].xw:=PlayerInfo.ObsState[i].x;
Obs[i].yw:=PlayerInfo.ObsState[i].y;
Obs[i].quality:=PlayerInfo.ObsState[i].conf;
end;
end;
end;
procedure TFCoachMain.SendCoachInfo;
var CoachInfo: TCoachInfo;
packet_str: string;
i: integer;
begin
try
CoachInfo.Magic := PACKET_COACH_MAGIC;
for i := 0 to MaxRobots-1 do begin
with RobotState[i] do begin
CoachInfo.RobotState[i].x := x;
CoachInfo.RobotState[i].y := y;
CoachInfo.RobotState[i].teta := teta;
CoachInfo.RobotState[i].active := RobotStatus[i].active;
end;
CoachInfo.RobotState[i].role := RobotInfo[i].role;
end;
with BallState do begin
CoachInfo.BallState.x:=x;
CoachInfo.BallState.y:=y;
CoachInfo.BallState.vx:=vx;
CoachInfo.BallState.vy:=vy;
CoachInfo.BallState.x_next:=x_next;
CoachInfo.BallState.y_next:=y_next;
CoachInfo.BallState.coachQuality:=quality;
end;
CoachInfo.Play:=Play;
packet_str := StringOfChar(#0, sizeof(CoachInfo));
copymemory(@(packet_str[1]), @CoachInfo, sizeof(CoachInfo));
for i := 0 to MaxRobots-1 do begin
// robots ip+port must be 'IPBase'.'101-106':'7271-7276'
if RGDecision.ItemIndex=0 then //Local Host
FMain.SdpoUDPSuper.SendMessage(packet_str, '127.0.0.1:'+inttostr(7271 + i))
else //Net
FMain.SdpoUDPSuper.SendMessage(packet_str, FParam.EditIPBase.Text +'.'+IntToStr(101 + i)+ ':'+inttostr(7272 + i));
end;
except
end;
{ try
PlayerInfo.Magic := PACKET_PLAYER_MAGIC;
// send my robot state
with RobotState[MyNumber] do begin
PlayerInfo.RobotState.x := x;
PlayerInfo.RobotState.y := y;
PlayerInfo.RobotState.teta := teta;
PlayerInfo.RobotState.conf := count; //TODO: calculate confidence level
end;
// send the ball state
PlayerInfo.BallState.x := BallState.x;
PlayerInfo.BallState.y := BallState.y;
PlayerInfo.BallState.conf := BallState.quality;
// send the obstacles
// TODO: actually send the obstacles
num := myNumber;
zeromemory(@(PlayerInfo.ObsState), sizeof(PlayerInfo.ObsState));
packet_str := StringOfChar(#0, sizeof(PlayerInfo));
copymemory(@(packet_str[1]), @PlayerInfo, sizeof(PlayerInfo));
SdpoUDPSuper.SendMessage(packet_str, FParam.EditSuperIP.Text + ':7373');
except
end; }
end;
initialization
{$I CoachMain.lrs}
RobotState[0].Vbatery:=0;
RobotState[1].Vbatery:=0;
RobotState[2].Vbatery:=0;
RobotState[3].Vbatery:=0;
RobotState[4].Vbatery:=0;
end.
|
unit LibPQ;
{
LibPQ: libpq.dll wrapper
https://github.com/stijnsanders/DataLank
based on PostgreSQL 10.7
include/libpq-fe.h
}
interface
//debugging: prevent step-into from debugging TQueryResult calls:
{$D-}
{$L-}
type
Oid = cardinal; //Postgres Object ID
POid = ^Oid;
const
InvalidOid {:Oid} = 0;
OID_MAX = cardinal(-1);//UINT_MAX;
PG_DIAG_SEVERITY = 'S';
PG_DIAG_SQLSTATE = 'C';
PG_DIAG_MESSAGE_PRIMARY = 'M';
PG_DIAG_MESSAGE_DETAIL = 'D';
PG_DIAG_MESSAGE_HINT = 'H';
PG_DIAG_STATEMENT_POSITION = 'P';
PG_DIAG_INTERNAL_POSITION = 'p';
PG_DIAG_INTERNAL_QUERY = 'q';
PG_DIAG_CONTEXT = 'W';
PG_DIAG_SCHEMA_NAME = 's';
PG_DIAG_TABLE_NAME = 't';
PG_DIAG_COLUMN_NAME = 'c';
PG_DIAG_DATATYPE_NAME = 'd';
PG_DIAG_CONSTRAINT_NAME = 'n';
PG_DIAG_SOURCE_FILE = 'F';
PG_DIAG_SOURCE_LINE = 'L';
PG_DIAG_SOURCE_FUNCTION = 'R';
PG_COPYRES_ATTRS = $1;
PG_COPYRES_TUPLES = $2; // Implies PG_COPYRES_ATTRS
PG_COPYRES_EVENTS = $4;
PG_COPYRES_NOTICEHOOKS = $8;
type
ConnStatusType = (
CONNECTION_OK,
CONNECTION_BAD,
CONNECTION_STARTED,
CONNECTION_MADE,
CONNECTION_AWAITING_RESPONSE,
CONNECTION_AUTH_OK,
CONNECTION_SETENV,
CONNECTION_SSL_STARTUP,
CONNECTION_NEEDED
);
PostgresPollingStatusType = (
PGRES_POLLING_FAILED,
PGRES_POLLING_READING,
PGRES_POLLING_WRITING,
PGRES_POLLING_OK,
PGRES_POLLING_ACTIVE
);
ExecStatusType = (
PGRES_EMPTY_QUERY,
PGRES_COMMAND_OK,
PGRES_TUPLES_OK,
PGRES_COPY_OUT,
PGRES_COPY_IN,
PGRES_BAD_RESPONSE,
PGRES_NONFATAL_ERROR,
PGRES_FATAL_ERROR,
PGRES_COPY_BOTH,
PGRES_SINGLE_TUPLE
);
PGTransactionStatusType = (
PQTRANS_IDLE,
PQTRANS_ACTIVE,
PQTRANS_INTRANS,
PQTRANS_INERROR,
PQTRANS_UNKNOWN
);
PGVerbosity = (
PQERRORS_TERSE,
PQERRORS_DEFAULT,
PQERRORS_VERBOSE
);
PGPing = (
PQPING_OK,
PQPING_REJECT,
PQPING_NO_RESPONSE,
PQPING_NO_ATTEMPT
);
type
PGConn = record
Handle:pointer;//opaque
end;
PGResult = record
Handle:pointer;//opaque
end;
PGCancel = record
Handle:pointer;//opaque
end;
PpgNotify = ^pgNotify;
PGnotify = record
relname: PAnsiChar;
pe_pid: integer;
extra: PAnsiChar;
next: PpgNotify;
end;
PQnoticeReceiver = procedure(arg:pointer;res:PGResult); cdecl;
PQnoticeProcessor = procedure(arg:pointer;msg:PAnsiChar); cdecl;
pgbool = byte;
_PQprintOpt = packed record
header, align, standard, html3, pager: pgbool;
fieldSep, tableOpt, caption: PAnsiChar;
fieldName: PPAnsiChar; //PAnsiChar? delimited by #0#0?
end;
PQprintOpt = ^_PQprintOpt;
_PQconninfoOption = record
keyword, envvar, compiled, val, label_, dispchar: PAnsiChar;
dispsize: integer;
end;
PQconninfoOption = ^_PQconninfoOption;
_PQArgBlock = record
len, isint: integer;
case integer of
0: (ptr: PInteger);
1: (integer_: integer);
end;
PQArgBlock = ^_PQArgBlock;
_PGresAttDesc = record
name: PAnsiChar;
tableid: Oid;
columnid: integer;
format: integer;
typid: Oid;
typlen: integer;
atttypmod: integer;
end;
PGresAttDesc = ^_PGresAttDesc;
function PQconnectStart(conninfo: PAnsiChar): PGconn; cdecl;
function PQconnectStartParams(keywords, values: PPAnsiChar; expand_dbname: integer): PGconn; cdecl;
function PQconnectPoll(conn: PGconn): PostgresPollingStatusType; cdecl;
function PQconnectdb(conninfo: PAnsiChar): PGconn; cdecl;
function PQconnectdbParams(keywords, values: PPAnsiChar; expand_dbname: integer): PGconn; cdecl;
function PQsetdbLogin(pghost, pgport, pgoptions, pgtty, dbName, login, pwd: PAnsiChar): PGconn; cdecl;
//#define
// PQsetdb(M_PGHOST,M_PGPORT,M_PGOPT,M_PGTTY,M_DBNAME)
// PQsetdbLogin(M_PGHOST, M_PGPORT, M_PGOPT, M_PGTTY, M_DBNAME, NULL, NULL)
procedure PQfinish(conn: PGconn); cdecl;
function PQconndefaults: PQconninfoOption; cdecl;
function PQconninfoParse(conninfo: PAnsiChar; var errmsg: PAnsiChar): PQconninfoOption; cdecl;
function PQconninfo(conn: PGconn): PQconninfoOption; cdecl;
procedure PQconninfoFree(connOptions: PQconninfoOption); cdecl;
function PQresetStart(conn: PGconn): integer; cdecl;
function PQresetPoll(conn: PGconn): PostgresPollingStatusType; cdecl;
procedure PQreset(conn: PGconn); cdecl;
function PQgetCancel(conn: PGconn): PGcancel; cdecl;
procedure PQfreeCancel(cancel: PGcancel); cdecl;
function PQcancel(cancel: PGcancel; errbuf: PAnsiChar; errbufsize: integer): integer; cdecl;
function PQrequestCancel(conn: PGconn): integer; cdecl;//deprecated
function PQdb(conn: PGconn): PAnsichar; cdecl;
function PQuser(conn: PGconn): PAnsichar; cdecl;
function PQpass(conn: PGconn): PAnsichar; cdecl;
function PQhost(conn: PGconn): PAnsichar; cdecl;
function PQport(conn: PGconn): PAnsichar; cdecl;
function PQtty(conn: PGconn): PAnsichar; cdecl;
function PQoptions(conn: PGconn): PAnsichar; cdecl;
function PQstatus(conn: PGconn): ConnStatusType; cdecl;
function PQtransactionStatus(conn: PGconn): PGTransactionStatusType; cdecl;
function PQparameterStatus(conn: PGconn; paramName: PAnsiChar): PAnsiChar; cdecl;
function PQprotocolVersion(conn: PGconn): integer; cdecl;
function PQserverVersion(conn: PGconn): integer; cdecl;
function PQerrorMessage(conn: PGconn): PAnsiChar; cdecl;
function PQsocket(conn: PGconn): integer; cdecl;
function PQbackendPID(conn: PGconn): integer; cdecl;
function PQconnectionNeedsPassword(conn: PGconn): integer; cdecl;
function PQconnectionUsedPassword(conn: PGconn): integer; cdecl;
function PQclientEncoding(conn: PGconn): integer; cdecl;
function PQsetClientEncoding(conn: PGconn; encoding: PAnsiChar): integer; cdecl;
function PQsslInUse(conn: PGconn): integer; cdecl;
function PQsslStruct(conn: PGconn; struct_name: PAnsiChar): pointer; cdecl;
function PQsslAttribute(conn: PGconn; attribute_name: PAnsiChar): PAnsiChar; cdecl;
function PQsslAttributeNames(conn: PGconn): PPAnsiChar; cdecl;
function PQgetssl(conn: PGconn): pointer; cdecl;
procedure PQinitSSL(do_init: integer);
procedure PQinitOpenSSL(do_ssl, do_crypto: integer);
function PQsetErrorVerbosity(conn: PGconn; verbosity: PGVerbosity): PGVerbosity; cdecl;
procedure PQtrace(conn: PGconn; debug_port: pointer {*FILE}); cdecl;
procedure PQuntrace(conn: PGconn); cdecl;
function PQsetNoticeReceiver(conn: PGconn; proc: PQnoticeReceiver; arg: pointer): PQnoticeReceiver; cdecl;
function PQsetNoticeProcessor(conn: PGconn; proc: PQnoticeProcessor; arg: pointer): PQnoticeProcessor; cdecl;
type pgthreadlock_t = type pointer; //typedef void (*pgthreadlock_t) (int acquire);
function PQregisterThreadLock(newhandler: pgthreadlock_t): pgthreadlock_t; cdecl;
//---
function PQexec(conn: PGconn; query: PAnsiChar): PGresult; cdecl;
function PQexecParams(conn: PGconn; command: PAnsiChar; nParams: integer;
paramTypes: POid; paramValues: PPAnsiChar; paramLengths: PInteger;
paramFormats: PInteger; resultFormat: integer): PGresult; cdecl;
function PQprepare(conn: PGconn; stmtName: PAnsiChar;
query: PAnsiChar; nParams: integer; paramTypes: POid): PGresult; cdecl;
function PQexecPrepared(conn: PGconn; stmtName: PAnsiChar; nParams: integer;
paramValues: PPAnsiChar; paramLengths: PInteger;
paramFormats: PInteger; resultFormat: integer): PGresult; cdecl;
function PQsendQuery(conn: PGconn; query: PAnsiChar): integer; cdecl;
function PQsendQueryParams(conn: PGconn; command: PAnsiChar; nParams: integer;
paramTypes: POid; paramValues: PPAnsiChar; paramLengths: PInteger;
paramFormats: PInteger; resultFormat: integer): integer; cdecl;
function PQsendPrepare(conn: PGconn; stmtName: PAnsiChar;
query: PAnsiChar; nParams: integer;
paramTypes: POid): integer; cdecl;
function PQsendQueryPrepared(conn: PGconn; stmtName: PAnsiChar; nParams: integer;
paramValues: PPAnsiChar; paramLengths: PInteger;
paramFormats: PInteger; resultFormat: integer): integer; cdecl;
function PQsetSingleRowMode(conn: PGconn): integer; cdecl;
function PQgetResult(conn: PGconn): PGresult; cdecl;
function PQisBusy(conn: PGconn): integer; cdecl;
function PQconsumeInput(conn: PGconn): integer; cdecl;
function PQnotifies(conn: PGconn): PGnotify; cdecl;
function PQputCopyData(conn: PGconn; buffer: PAnsiChar; nbytes: integer): integer; cdecl;
function PQputCopyEnd(conn: PGconn; errormsg: PAnsiChar): integer; cdecl;
function PQgetCopyData(conn: PGconn; buffer: PPAnsiChar; async: integer): integer; cdecl;
function PQsetnonblocking(conn: PGconn; arg: integer): integer; cdecl;
function PQisnonblocking(conn: PGconn): integer; cdecl;
function PQisthreadsafe: integer; cdecl;
function PQping(conninfo: PAnsiChar): PGPing; cdecl;
function PQpingParams(keywords: PPAnsiChar; values: PPAnsiChar; expand_dbname: integer): PGPing; cdecl;
function PQflush(conn: PGconn): integer; cdecl;
function PQfn(conn: PGconn; fnid: integer; result_buf: PInteger; result_len: PInteger; result_is_int: integer;
args: PQArgBlock; nargs: integer): PGresult; cdecl;
function PQresultStatus(res: PGResult): ExecStatusType; cdecl;
function PQresStatus(status: ExecStatusType): PAnsiChar; cdecl;
function PQresultErrorMessage(res: PGResult): PAnsiChar; cdecl;
function PQresultErrorField(res: PGResult; fieldcode: integer): PAnsiChar; cdecl;
function PQntuples(res: PGResult): integer; cdecl;
function PQnfields(res: PGResult): integer; cdecl;
function PQbinaryTuples(res: PGResult): integer; cdecl;
function PQfname(res: PGResult; field_num: integer): PAnsiChar; cdecl;
function PQfnumber(res: PGResult; field_name: PAnsiChar): integer; cdecl;
function PQftable(res: PGResult; field_num: integer): Oid; cdecl;
function PQftablecol(res: PGResult; field_num: integer): integer; cdecl;
function PQfformat(res: PGResult; field_num: integer): integer; cdecl;
function PQftype(res: PGResult; field_num: integer): Oid; cdecl;
function PQfsize(res: PGResult; field_num: integer): integer; cdecl;
function PQfmod(res: PGResult; field_num: integer): integer; cdecl;
function PQcmdStatus(res: PGresult): PAnsiChar; cdecl;
function PQoidValue(res: PGResult): Oid; cdecl;
function PQcmdTuples(res: PGresult): PAnsiChar; cdecl;
function PQgetvalue(res: PGResult; tup_num: integer; field_num: integer): PAnsiChar; cdecl;
function PQgetlength(res: PGResult; tup_num: integer; field_num: integer): integer; cdecl;
function PQgetisnull(res: PGResult; tup_num: integer; field_num: integer): integer; cdecl;
function PQnparams(res: PGResult): integer; cdecl;
function PQparamtype(res: PGResult; param_num: integer): Oid; cdecl;
function PQdescribePrepared(conn: PGconn; stmt: PAnsiChar): PGresult; cdecl;
function PQdescribePortal(conn: PGconn; portal: PAnsiChar): PGresult; cdecl;
function PQsendDescribePrepared(conn: PGconn; stmt: PAnsiChar): integer; cdecl;
function PQsendDescribePortal(conn: PGconn; portal: PAnsiChar): integer; cdecl;
procedure PQclear(res: PGResult); cdecl;
procedure PQfreemem(ptr: pointer); cdecl;
type
size_t= cardinal;
function PQmakeEmptyPGresult(conn: PGconn; status: ExecStatusType): PGresult; cdecl;
function PQcopyResult(src: PGresult; flags: integer): PGresult; cdecl;
function PQsetResultAttrs(res: PGresult; numAttributes: integer; attDescs: PGresAttDesc): integer; cdecl;
function PQresultAlloc(res: PGresult; nBytes: size_t): pointer; cdecl;
function PQsetvalue(res: PGresult; tup_num: integer; field_num: integer; value: PAnsiChar; len: integer): integer; cdecl;
function PQescapeStringConn(conn: PGconn; to_: PAnsiChar; from: PAnsiChar; length: size_t; error: PInteger): size_t; cdecl;
function PQescapeLiteral(conn: PGconn; str: PAnsiChar; len: size_t): PAnsiChar; cdecl;
function PQescapeIdentifier(conn: PGconn; str: PAnsiChar; len: size_t): PAnsiChar; cdecl;
function PQescapeByteaConn(conn: PGconn; from: PByte; from_length: size_t; var to_length: size_t): PByte; cdecl;
function PQunescapeBytea(strtext: PByte; var retbuflen: size_t): PByte; cdecl;
procedure PQprint(fout: pointer{*FILE}; res: PGResult; ps: PQprintOpt); cdecl;
{
extern int lo_open(conn: PGconn, Oid lobjId, int mode): integer; cdecl;
extern int lo_close(conn: PGconn, int fd): integer; cdecl;
extern int lo_read(conn: PGconn, int fd, char *buf, size_t len): integer; cdecl;
extern int lo_write(conn: PGconn, int fd, const char *buf, size_t len): integer; cdecl;
extern int lo_lseek(conn: PGconn, int fd, int offset, int whence): integer; cdecl;
extern pg_int64 lo_lseek64(conn: PGconn, int fd, pg_int64 offset, int whence): integer; cdecl;
extern Oid lo_creat(conn: PGconn, int mode);
extern Oid lo_create(conn: PGconn, Oid lobjId);
extern int lo_tell(conn: PGconn, int fd): integer; cdecl;
extern pg_int64 lo_tell64(conn: PGconn, int fd);
extern int lo_truncate(conn: PGconn, int fd, size_t len): integer; cdecl;
extern int lo_truncate64(conn: PGconn, int fd, pg_int64 len): integer; cdecl;
extern int lo_unlink(conn: PGconn, Oid lobjId): integer; cdecl;
extern Oid lo_import(conn: PGconn, const char *filename);
extern Oid lo_import_with_oid(conn: PGconn, const char *filename, Oid lobjId);
extern int lo_export(conn: PGconn, Oid lobjId, const char *filename): integer; cdecl;
}
function PQlibVersion: integer; cdecl;
function PQmblen(s:PAnsiChar; encoding: integer): integer; cdecl;
function PQdsplen(s:PAnsiChar; encoding: integer): integer; cdecl;
function PQenv2encoding: integer; cdecl;
function PQencryptPassword(passwd: PAnsiChar; user: PAnsiChar): PAnsiChar; cdecl;
function pg_char_to_encoding(name: PAnsiChar): integer; cdecl;
function pg_encoding_to_char(encoding: integer): PAnsiChar; cdecl;
function pg_valid_server_encoding_id(encoding: integer): integer; cdecl;
implementation
function PQconnectStart; external 'libpq.dll';
function PQconnectStartParams; external 'libpq.dll';
function PQconnectPoll; external 'libpq.dll';
function PQconnectdb; external 'libpq.dll';
function PQconnectdbParams; external 'libpq.dll';
function PQsetdbLogin; external 'libpq.dll';
procedure PQfinish; external 'libpq.dll';
function PQconndefaults; external 'libpq.dll';
function PQconninfoParse; external 'libpq.dll';
function PQconninfo; external 'libpq.dll';
procedure PQconninfoFree; external 'libpq.dll';
function PQresetStart; external 'libpq.dll';
function PQresetPoll; external 'libpq.dll';
procedure PQreset; external 'libpq.dll';
function PQgetCancel; external 'libpq.dll';
procedure PQfreeCancel; external 'libpq.dll';
function PQcancel; external 'libpq.dll';
function PQrequestCancel; external 'libpq.dll';
function PQdb; external 'libpq.dll';
function PQuser; external 'libpq.dll';
function PQpass; external 'libpq.dll';
function PQhost; external 'libpq.dll';
function PQport; external 'libpq.dll';
function PQtty; external 'libpq.dll';
function PQoptions; external 'libpq.dll';
function PQstatus; external 'libpq.dll';
function PQtransactionStatus; external 'libpq.dll';
function PQparameterStatus; external 'libpq.dll';
function PQprotocolVersion; external 'libpq.dll';
function PQserverVersion; external 'libpq.dll';
function PQerrorMessage; external 'libpq.dll';
function PQsocket; external 'libpq.dll';
function PQbackendPID; external 'libpq.dll';
function PQconnectionNeedsPassword; external 'libpq.dll';
function PQconnectionUsedPassword; external 'libpq.dll';
function PQclientEncoding; external 'libpq.dll';
function PQsetClientEncoding; external 'libpq.dll';
function PQsslInUse; external 'libpq.dll';
function PQsslStruct; external 'libpq.dll';
function PQsslAttribute; external 'libpq.dll';
function PQsslAttributeNames; external 'libpq.dll';
function PQgetssl; external 'libpq.dll';
procedure PQinitSSL; external 'libpq.dll';
procedure PQinitOpenSSL; external 'libpq.dll';
function PQsetErrorVerbosity; external 'libpq.dll';
procedure PQtrace; external 'libpq.dll';
procedure PQuntrace; external 'libpq.dll';
function PQsetNoticeReceiver; external 'libpq.dll';
function PQsetNoticeProcessor; external 'libpq.dll';
function PQregisterThreadLock; external 'libpq.dll';
function PQexec; external 'libpq.dll';
function PQexecParams; external 'libpq.dll';
function PQprepare; external 'libpq.dll';
function PQexecPrepared; external 'libpq.dll';
function PQsendQuery; external 'libpq.dll';
function PQsendQueryParams; external 'libpq.dll';
function PQsendPrepare; external 'libpq.dll';
function PQsendQueryPrepared; external 'libpq.dll';
function PQsetSingleRowMode; external 'libpq.dll';
function PQgetResult; external 'libpq.dll';
function PQisBusy; external 'libpq.dll';
function PQconsumeInput; external 'libpq.dll';
function PQnotifies; external 'libpq.dll';
function PQputCopyData; external 'libpq.dll';
function PQputCopyEnd; external 'libpq.dll';
function PQgetCopyData; external 'libpq.dll';
function PQsetnonblocking; external 'libpq.dll';
function PQisnonblocking; external 'libpq.dll';
function PQisthreadsafe; external 'libpq.dll';
function PQping; external 'libpq.dll';
function PQpingParams; external 'libpq.dll';
function PQflush; external 'libpq.dll';
function PQfn; external 'libpq.dll';
function PQresultStatus; external 'libpq.dll';
function PQresStatus; external 'libpq.dll';
function PQresultErrorMessage; external 'libpq.dll';
function PQresultErrorField; external 'libpq.dll';
function PQntuples; external 'libpq.dll';
function PQnfields; external 'libpq.dll';
function PQbinaryTuples; external 'libpq.dll';
function PQfname; external 'libpq.dll';
function PQfnumber; external 'libpq.dll';
function PQftable; external 'libpq.dll';
function PQftablecol; external 'libpq.dll';
function PQfformat; external 'libpq.dll';
function PQftype; external 'libpq.dll';
function PQfsize; external 'libpq.dll';
function PQfmod; external 'libpq.dll';
function PQcmdStatus; external 'libpq.dll';
function PQoidValue; external 'libpq.dll';
function PQcmdTuples; external 'libpq.dll';
function PQgetvalue; external 'libpq.dll';
function PQgetlength; external 'libpq.dll';
function PQgetisnull; external 'libpq.dll';
function PQnparams; external 'libpq.dll';
function PQparamtype; external 'libpq.dll';
function PQdescribePrepared; external 'libpq.dll';
function PQdescribePortal; external 'libpq.dll';
function PQsendDescribePrepared; external 'libpq.dll';
function PQsendDescribePortal; external 'libpq.dll';
procedure PQclear; external 'libpq.dll';
procedure PQfreemem; external 'libpq.dll';
function PQmakeEmptyPGresult; external 'libpq.dll';
function PQcopyResult; external 'libpq.dll';
function PQsetResultAttrs; external 'libpq.dll';
function PQresultAlloc; external 'libpq.dll';
function PQsetvalue; external 'libpq.dll';
function PQescapeStringConn; external 'libpq.dll';
function PQescapeLiteral; external 'libpq.dll';
function PQescapeIdentifier; external 'libpq.dll';
function PQescapeByteaConn; external 'libpq.dll';
function PQunescapeBytea; external 'libpq.dll';
procedure PQprint; external 'libpq.dll';
function PQlibVersion; external 'libpq.dll';
function PQmblen; external 'libpq.dll';
function PQdsplen; external 'libpq.dll';
function PQenv2encoding; external 'libpq.dll';
function PQencryptPassword; external 'libpq.dll';
function pg_char_to_encoding; external 'libpq.dll';
function pg_encoding_to_char; external 'libpq.dll';
function pg_valid_server_encoding_id; external 'libpq.dll';
end.
|
unit uFrmBuildGrid;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls, CheckLst;
type
TFrmBuildGrid = class(TForm)
pnlBotton: TPanel;
imgBotton: TImage;
btnClose: TBitBtn;
btnApply: TBitBtn;
clbSize: TCheckListBox;
clbColor: TCheckListBox;
btnAddSize: TSpeedButton;
btnAddColor: TSpeedButton;
edtColor: TEdit;
edtSize: TEdit;
Label2: TLabel;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnCloseClick(Sender: TObject);
procedure btnApplyClick(Sender: TObject);
procedure btnAddSizeClick(Sender: TObject);
procedure btnAddColorClick(Sender: TObject);
private
FModel, FFilter : String;
procedure RefreshSize;
procedure RefreshColor;
procedure ReCreateGrid;
function Validate : Boolean;
public
function Start(Model : String) : Boolean;
end;
implementation
uses uDMExport, DB, uMsgBox;
{$R *.dfm}
{ TFrmBuildGrid }
function TFrmBuildGrid.Start(Model : String): Boolean;
begin
FModel := Model;
RefreshColor;
RefreshSize;
FFilter := DMExport.cdsGrid.Filter;
DMExport.cdsGrid.Filtered := False;
DMExport.cdsGrid.Filter := 'Model = ' + QuotedStr(FModel);
DMExport.cdsGrid.Filtered := True;
ShowModal;
DMExport.cdsGrid.Filtered := False;
DMExport.cdsGrid.Filter := FFilter;
DMExport.cdsGrid.Filtered := True;
Result := (ModalResult = mrOk);
end;
procedure TFrmBuildGrid.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TFrmBuildGrid.btnCloseClick(Sender: TObject);
begin
Close;
end;
procedure TFrmBuildGrid.btnApplyClick(Sender: TObject);
begin
ModalResult := mrNone;
if Validate then
if MsgBox('Recriar Grade?_Os valores atuais serรฃo perdidos.', vbYesNo + vbQuestion) = vbYes then
begin
ReCreateGrid;
ModalResult := mrOk;
end;
end;
procedure TFrmBuildGrid.RefreshColor;
begin
with DMExport.cdsColor do
begin
First;
clbColor.Clear;
while not EOF do
begin
if DMExport.cdsGrid.Locate('MColor', DMExport.cdsColor.FieldByName('MColor').AsString, []) then
begin
clbColor.AddItem(DMExport.cdsColor.FieldByName('MColor').AsString, nil);
clbColor.Checked[clbColor.Items.IndexOf(DMExport.cdsColor.FieldByName('MColor').AsString)] := True;
end
else
clbColor.AddItem(DMExport.cdsColor.FieldByName('MColor').AsString, nil);
Next;
end;
First;
end;
end;
procedure TFrmBuildGrid.RefreshSize;
begin
with DMExport.cdsSize do
begin
First;
clbSize.Clear;
while not EOF do
begin
if DMExport.cdsGrid.Locate('MSize', DMExport.cdsSize.FieldByName('MSize').AsString, []) then
begin
clbSize.AddItem(DMExport.cdsSize.FieldByName('MSize').AsString, nil);
clbSize.Checked[clbSize.Items.IndexOf(DMExport.cdsSize.FieldByName('MSize').AsString)] := True;
end
else
clbSize.AddItem(DMExport.cdsSize.FieldByName('MSize').AsString, nil);
Next;
end;
First;
end;
end;
procedure TFrmBuildGrid.btnAddSizeClick(Sender: TObject);
begin
if Trim(edtSize.Text) <> '' then
begin
if not DMExport.cdsSize.Locate('MSize', edtSize.Text, []) then
begin
DMExport.cdsSize.Append;
DMExport.cdsSize.FieldByName('MSize').Value := edtSize.Text;
DMExport.cdsSize.Post;
RefreshSize;
end;
edtSize.Clear;
edtSize.SetFocus;
end;
end;
procedure TFrmBuildGrid.btnAddColorClick(Sender: TObject);
begin
if Trim(edtColor.Text) <> '' then
begin
if not DMExport.cdsColor.Locate('MColor', edtColor.Text, []) then
begin
DMExport.cdsColor.Append;
DMExport.cdsColor.FieldByName('MColor').Value := edtColor.Text;
DMExport.cdsColor.Post;
RefreshColor;
end;
edtColor.Clear;
edtColor.SetFocus;
end;
end;
procedure TFrmBuildGrid.ReCreateGrid;
var
i, j : Integer;
Qty : Double;
Sale : Currency;
begin
DMExport.RemoveGridModel(FModel);
Qty := 1;
Sale := 1;
with DMExport.cdsModel do
if Locate('Model', FModel, []) then
begin
Qty := FieldByName('Qty').AsFloat;
Sale := FieldByName('SalePrice').AsCurrency;
end;
for i := 0 to clbSize.Count-1 do
if clbSize.Checked[i] then
for j := 0 to clbColor.Count-1 do
if clbColor.Checked[j] then
begin
with DMExport.cdsGrid do
begin
Append;
FieldByName('Model').Value := FModel;
FieldByName('MSize').Value := clbSize.Items.Strings[i];
FieldByName('MColor').Value := clbColor.Items.Strings[j];
FieldByName('Qty').Value := Qty;
FieldByName('SalePrice').Value := Sale;
Post;
end;
end;
end;
function TFrmBuildGrid.Validate: Boolean;
var
i : Integer;
begin
Result := False;
for i := 0 to clbSize.Count-1 do
if clbSize.Checked[i] then
begin
Result := True;
Break;
end;
if not Result then
begin
MsgBox('Selecione um item de Horizontal', vbOkOnly + vbInformation);
Exit;
end;
Result := False;
for i := 0 to clbColor.Count-1 do
if clbColor.Checked[i] then
begin
Result := True;
Break;
end;
if not Result then
begin
MsgBox('Selecione um item de Vertical', vbOkOnly + vbInformation);
Exit;
end;
end;
end.
|
unit PlayThread;
interface
uses
Classes, SysUtils, Forms, Jpeg, DateUtils, TopImage, TopFlash, FormCont,
TransEff, TransitionCell;
type
TPlayThread = class(TThread)
private
TopCell: TTransitionCell;
BottomCell: TTransitionCell;
procedure ProcessMessageSleep(ms: Integer);
procedure ShowImage(cell: TTransitionCell; fileName: String);
procedure TransImageToImage(cell: TTransitionCell; fileName: String);
procedure TransImageToFlash(cell: TTransitionCell; fileName: String);
procedure TransFlashToFlash(cell: TTransitionCell; fileName: String);
procedure TransFlashToImage(cell: TTransitionCell; fileName: String);
protected
procedure Execute; override;
public
constructor Create(CreateSuspended: Boolean; cellTop: TTransitionCell; cellBottom: TTransitionCell);
destructor Destroy; override;
end;
implementation
{ TPlayThread }
constructor TPlayThread.Create(CreateSuspended: Boolean;
cellTop: TTransitionCell; cellBottom: TTransitionCell);
begin
self.TopCell := cellTop;
self.BottomCell := cellBottom;
inherited Create(CreateSuspended);
end;
destructor TPlayThread.Destroy;
begin
inherited;
end;
procedure TPlayThread.Execute;
begin
ShowImage(TopCell, '1.jpg');
ShowImage(BottomCell, '2.jpg');
ProcessMessageSleep(TopCell.SleepTime);
while true do begin
TransImageToImage(TopCell, '2.jpg');
TransImageToImage(BottomCell, '3.jpg');
ProcessMessageSleep(TopCell.SleepTime);
TransImageToFlash(TopCell, '3.swf');
ProcessMessageSleep(TopCell.SleepTime);
TransImageToImage(BottomCell, '4.jpg');
TransFlashToFlash(TopCell, '4.swf');
ProcessMessageSleep(TopCell.SleepTime);
TransFlashToImage(TopCell, '4.jpg');
TransImageToFlash(BottomCell, '5.swf');
ProcessMessageSleep(TopCell.SleepTime);
TransFlashToImage(BottomCell, '3.jpg');
end;
end;
procedure TPlayThread.ProcessMessageSleep(ms: Integer);
var
startTime: TDateTime;
begin
startTime := GetTime;
while true do begin
if MilliSecondsBetween(GetTime, startTime) >= ms then Exit;
Application.ProcessMessages;
end;
end;
procedure TPlayThread.ShowImage(cell: TTransitionCell; fileName: String);
begin
with cell do begin
FormImage.LoadImage(fileName);
FormContainer.ShowFormEx(FormImage, False);
end;
end;
procedure TPlayThread.TransFlashToFlash(cell: TTransitionCell; fileName: String);
begin
with cell do begin
FormFlash.Stop;
Transition.Prepare(FormContainer, FormContainer.ClientRect);
FormFlash.LoadMovie(fileName);
Transition.Execute;
Transition.UnPrepare;
FormFlash.Play;
end;
end;
procedure TPlayThread.TransFlashToImage(cell: TTransitionCell; fileName: String);
begin
with cell do begin
FormFlash.Stop;
FormImage.LoadImage(fileName);
FormContainer.ShowFormEx(FormImage, False, Transition);
end;
end;
procedure TPlayThread.TransImageToFlash(cell: TTransitionCell; fileName: String);
begin
with cell do begin
FormFlash.LoadMovie(fileName);
FormContainer.ShowFormEx(FormFlash, False, Transition);
FormFlash.Play;
end;
end;
procedure TPlayThread.TransImageToImage(cell: TTransitionCell; fileName: String);
begin
with cell do begin
Transition.Prepare(FormContainer, FormContainer.ClientRect);
FormImage.LoadImage(fileName);
Transition.Execute;
Transition.UnPrepare;
end;
end;
end.
|
unit ibSHTXTLoaderEditors;
interface
uses
SysUtils, Classes, DesignIntf, TypInfo,
SHDesignIntf, ibSHDesignIntf, ibSHCommonEditors;
type
// -> Property Editors
TibSHTXTLoaderPropEditor = class(TibBTPropertyEditor)
private
FTXTLoader: IibSHTXTLoader;
FValues: string;
procedure Prepare;
public
constructor Create(APropertyEditor: TObject); override;
destructor Destroy; override;
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure GetValues(AValues: TStrings); override;
procedure SetValue(const Value: string); override;
procedure Edit; override;
property TXTLoader: IibSHTXTLoader read FTXTLoader;
end;
IibSHTXTLoaderDelimiterPropEditor = interface
['{030422C2-B39F-4A43-B9EF-AD15560D447D}']
end;
TibSHTXTLoaderDelimiterPropEditor = class(TibSHTXTLoaderPropEditor, IibSHTXTLoaderDelimiterPropEditor);
implementation
uses
ibSHConsts, ibSHValues;
{ TibSHTXTLoaderPropEditor }
constructor TibSHTXTLoaderPropEditor.Create(APropertyEditor: TObject);
begin
inherited Create(APropertyEditor);
Supports(Component, IibSHTXTLoader, FTXTLoader);
Assert(TXTLoader <> nil, 'TXTLoader = nil');
Prepare;
end;
destructor TibSHTXTLoaderPropEditor.Destroy;
begin
FTXTLoader := nil;
inherited Destroy;
end;
procedure TibSHTXTLoaderPropEditor.Prepare;
begin
if Supports(Self, IibSHTXTLoaderDelimiterPropEditor) then
FValues := FormatProps(Delimiters);
end;
function TibSHTXTLoaderPropEditor.GetAttributes: TPropertyAttributes;
begin
Result := inherited GetAttributes;
Result := [paValueList];
end;
function TibSHTXTLoaderPropEditor.GetValue: string;
begin
Result := inherited GetValue;
end;
procedure TibSHTXTLoaderPropEditor.GetValues(AValues: TStrings);
begin
inherited GetValues(AValues);
AValues.Text := FValues;
end;
procedure TibSHTXTLoaderPropEditor.SetValue(const Value: string);
begin
inherited SetValue(Value);
// if Designer.CheckPropValue(Value, FValues) then
// inherited SetStrValue(Value);
end;
procedure TibSHTXTLoaderPropEditor.Edit;
begin
inherited Edit;
end;
end.
|
๏ปฟunit School;
interface
/// ะะตัะตะฒะพะด ะดะตัััะธัะฝะพะณะพ ัะธัะปะฐ ะฒ ะดะฒะพะธัะฝัั ัะธััะตะผั ััะธัะปะตะฝะธั
function Bin(x: int64): string;
/// ะะตัะตะฒะพะด ะดะตัััะธัะฝะพะณะพ ัะธัะปะฐ ะฒ ะดะฒะพะธัะฝัั ัะธััะตะผั ััะธัะปะตะฝะธั
function Bin(x: BigInteger): string;
/// ะะตัะตะฒะพะด ะดะตัััะธัะฝะพะณะพ ัะธัะปะฐ ะฒ ะฒะพััะผะตัะธัะฝัั ัะธััะตะผั ััะธัะปะตะฝะธั
function Oct(x: int64): string;
/// ะะตัะตะฒะพะด ะดะตัััะธัะฝะพะณะพ ัะธัะปะฐ ะฒ ะฒะพััะผะตัะธัะฝัั ัะธััะตะผั ััะธัะปะตะฝะธั
function Oct(x: BigInteger): string;
/// ะะตัะตะฒะพะด ะดะตัััะธัะฝะพะณะพ ัะธัะปะฐ ะฒ ัะตััะฝะฐะดัะฐัะธัะธัะฝัั ัะธััะตะผั ััะธัะปะตะฝะธั
function Hex(x: int64): string;
/// ะะตัะตะฒะพะด ะดะตัััะธัะฝะพะณะพ ัะธัะปะฐ ะฒ ัะตััะฝะฐะดัะฐัะธัะธัะฝัั ัะธััะตะผั ััะธัะปะตะฝะธั
function Hex(x: BigInteger): string;
/// ะะตัะตะฒะพะด ะธะท ัะธััะตะผั ะฟะพ ะพัะฝะพะฒะฐะฝะธั base [2..36] ะฒ ะดะตัััะธัะฝัั
function Dec(s: string; base: integer): int64;
/// ะะตัะตะฒะพะด ะธะท ัะธััะตะผั ะฟะพ ะพัะฝะพะฒะฐะฝะธั base [2..36] ะฒ ะดะตัััะธัะฝัั
function DecBig(s: string; base: integer): BigInteger;
/// ะะพะทะฒัะฐัะฐะตั ะบะพััะตะถ ะธะท ะผะธะฝะธะผัะผะฐ ะธ ะผะฐะบัะธะผัะผะฐ ะฟะพัะปะตะดะพะฒะฐัะตะปัะฝะพััะธ s
function MinMax(s: sequence of int64): (int64, int64);
/// ะะพะทะฒัะฐัะฐะตั ะบะพััะตะถ ะธะท ะผะธะฝะธะผัะผะฐ ะธ ะผะฐะบัะธะผัะผะฐ ะฟะพัะปะตะดะพะฒะฐัะตะปัะฝะพััะธ s
function MinMax(s: sequence of integer): (integer, integer);
/// ะะฒะพะทะฒัะฐัะฐะตั ะะะ ะธ ะะะ ะฟะฐัั ัะธัะตะป
function ะะะะะะ(a, b: int64): (int64, int64);
/// ะ ะฐะทะปะพะถะตะฝะธะต ัะธัะปะฐ ะฝะฐ ะฟัะพัััะต ะผะฝะพะถะธัะตะปะธ
function Factorize(n: int64): array of int64;
/// ะ ัะฐะทะปะพะถะตะฝะธะต ัะธัะปะฐ ะฝะฐ ะฟัะพัััะต ะผะฝะพะถะธัะตะปะธ
function Factorize(n: integer): array of integer;
/// ะัะพัััะต ัะธัะปะฐ ะฝะฐ ะธะฝัะตัะฒะฐะปะต [2;n]
function Primes(n: integer): array of integer;
/// ะะตัะฒัะต n ะฟัะพัััั
ัะธัะตะป
function FirstPrimes(n: integer): array of integer;
/// ะะพะทะฒัะฐัะฐะตั ะผะฐััะธะฒ, ัะพะดะตัะถะฐัะธะน ัะธััั ัะธัะปะฐ
function Digits(n: int64): array of integer;
implementation
type
School_BadCharInString = class(Exception)
end;
School_InvalidBase = class(Exception)
end;
{$region Bin}
function Bin(x: int64): string;
begin
x := Abs(x);
var r := '';
while x >= 2 do
(r, x) := (x mod 2 + r, x Shr 1);
Result := x + r
end;
function Bin(x: BigInteger): string;
begin
x := Abs(x);
var r := '';
while x >= 2 do
(r, x) := (byte(x mod 2) + r, x div 2);
Result := byte(x) + r
end;
{$region}
{$region Oct}
function Oct(x: int64): string;
begin
x := Abs(x);
var r := '';
while x >= 8 do
(r, x) := (x mod 8 + r, x Shr 3);
Result := x + r
end;
function Oct(x: BigInteger): string;
begin
x := Abs(x);
var r := '';
while x >= 8 do
(r, x) := (byte(x mod 8) + r, x div 8);
Result := byte(x) + r
end;
{$region}
{$region Hex}
function Hex(x: int64): string;
begin
x := Abs(x);
var s := '0123456789ABCDEF';
var r := '';
while x >= 16 do
(r, x) := (s[x mod 16 + 1] + r, x Shr 4);
Result := s[x + 1] + r
end;
function Hex(x: BigInteger): string;
begin
x := Abs(x);
var s := '0123456789ABCDEF';
var r := '';
while x >= 16 do
(r, x) := (s[byte(x mod 16) + 1] + r, x div 16);
Result := s[byte(x) + 1] + r
end;
{$region}
{$region Dec}
function Dec(s: string; base: integer): int64;
begin
if not (base in 2..36) then
raise new School_InvalidBase
($'ToDecimal: ะะตะดะพะฟัััะธะผะพะต ะพัะฝะพะฒะฐะฝะธะต {base}');
var sb := '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
s := s.ToUpper;
var r := s.Except(sb[:base + 1]).JoinToString;
if r.Length > 0 then
raise new School_BadCharInString
($'ToDecimal: ะะตะดะพะฟัััะธะผัะน ัะธะผะฒะพะป "{r}" ะฒ ัััะพะบะต {s}');
var (pa, p) := (BigInteger.One, BigInteger.Zero);
foreach var c in s.Reverse do
begin
var i := Pos(c, sb) - 1;
p += pa * i;
pa *= base
end;
Result := int64(p)
end;
function DecBig(s: string; base: integer): BigInteger;
begin
if not (base in 2..36) then
raise new School_InvalidBase
($'ToDecimal: ะะตะดะพะฟัััะธะผะพะต ะพัะฝะพะฒะฐะฝะธะต {base}');
var sb := '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
s := s.ToUpper;
var r := s.Except(sb[:base + 1]).JoinToString;
if r.Length > 0 then
raise new School_BadCharInString
($'ToDecimal: ะะตะดะพะฟัััะธะผัะน ัะธะผะฒะพะป "{r}" ะฒ ัััะพะบะต {s}');
var pa := BigInteger.One;
Result := BigInteger.Zero;
foreach var c in s.Reverse do
begin
var i := Pos(c, sb) - 1;
Result += pa * i;
pa *= base
end
end;
{$region}
{$region MinMax}
/// ะะพะทะฒัะฐัะฐะตั ะบะพััะตะถ ะธะท ะผะธะฝะธะผัะผะฐ ะธ ะผะฐะบัะธะผัะผะฐ ะฟะพัะปะตะดะพะฒะฐัะตะปัะฝะพััะธ s
function MinMax(s: sequence of int64): (int64, int64);
begin
var (min, max) := (int64.MaxValue, int64.MinValue);
foreach var m in s do
if m < min then
min := m
else if m > max then
max := m;
Result := (min, max)
end;
/// ะะพะทะฒัะฐัะฐะตั ะบะพััะตะถ ะธะท ะผะธะฝะธะผัะผะฐ ะธ ะผะฐะบัะธะผัะผะฐ ะฟะพัะปะตะดะพะฒะฐัะตะปัะฝะพััะธ s
function MinMax(s: sequence of integer): (integer, integer);
begin
var (min, max) := (integer.MaxValue, integer.MinValue);
foreach var m in s do
if m < min then
min := m
else if m > max then
max := m;
Result := (min, max)
end;
/// ะะพะทะฒัะฐัะฐะตั ะบะพััะตะถ ะธะท ะผะธะฝะธะผัะผะฐ ะธ ะผะฐะบัะธะผัะผะฐ ะฟะพัะปะตะดะพะฒะฐัะตะปัะฝะพััะธ
function MinMax(Self: sequence of int64): (int64, int64); extensionmethod :=
MinMax(Self);
/// ะะพะทะฒัะฐัะฐะตั ะบะพััะตะถ ะธะท ะผะธะฝะธะผัะผะฐ ะธ ะผะฐะบัะธะผัะผะฐ ะฟะพัะปะตะดะพะฒะฐัะตะปัะฝะพััะธ
function MinMax(Self: sequence of integer): (integer, integer);
extensionmethod := MinMax(Self);
{$region}
{$region ะะะะะะ}
/// ะะพะทะฒัะฐัะฐะตั ะะะ ะธ ะะะ ะฟะฐัั ัะธัะตะป
function ะะะะะะ(a, b: int64): (int64, int64);
begin
(a, b) := (Abs(a), Abs(b));
var (a1, b1) := (a, b);
while b <> 0 do
(a, b) := (b, a mod b);
Result := (a, a1 div a * b1)
end;
{$region}
{$region Factorize}
/// ะ ะฐะทะปะพะถะตะฝะธะต ัะธัะปะฐ ะฝะฐ ะฟัะพัััะต ะผะฝะพะถะธัะตะปะธ
function Factorize(n: int64): array of int64;
begin
n := Abs(n);
var i: int64 := 2;
var L := new List<int64>;
while i * i <= n do
if n mod i = 0 then
begin
L.Add(i);
n := n div i;
if n < i then
break
end
else
i += i = 2 ? 1 : 2;
if n > 1 then
L.Add(n);
Result := L.ToArray
end;
/// ะ ะฐะทะปะพะถะตะฝะธะต ัะธัะปะฐ ะฝะฐ ะฟัะพัััะต ะผะฝะพะถะธัะตะปะธ
function Factorize(n: integer): array of integer;
begin
n := Abs(n);
var i := 2;
var L := new List<integer>;
while i * i <= n do
if n mod i = 0 then
begin
L.Add(i);
n := n div i;
if n < i then
break
end
else
i += i = 2 ? 1 : 2;
if n > 1 then
L.Add(n);
Result := L.ToArray
end;
/// ัะฐะทะปะพะถะตะฝะธะต ัะธัะปะฐ ะฝะฐ ะฟัะพัััะต ะผะฝะพะถะธัะตะปะธ
function Factorize(Self: int64): array of int64; extensionmethod :=
Factorize(Self);
/// ะ ะฐะทะปะพะถะตะฝะธะต ัะธัะปะฐ ะฝะฐ ะฟัะพัััะต ะผะฝะพะถะธัะตะปะธ
function Factorize(Self: integer): array of integer; extensionmethod :=
Factorize(Self);
{$region}
{$region Primes}
/// ะัะพัััะต ัะธัะปะฐ ะฝะฐ ะธะฝัะตัะฒะฐะปะต [2;n]
function Primes(n: integer): array of integer;
// ะะพะดะธัะธัะธัะพะฒะฐะฝะฝะพะต ัะตัะตัะพ ะญัะฐัะพััะตะฝะฐ ะฝะฐ [2;n]
begin
var Mas := ArrFill(n, True);
var i := 2;
while i * i <= n do
begin
if Mas[i-1] then
begin
var k := i*i;
while k <= n do
begin
Mas[k-1] := False;
k += i
end
end;
Inc(i)
end;
n := Mas.Count(t -> t);
Result := new integer[n-1];
i := 0;
for var j := 1 to Mas.High do
if Mas[j] then
begin
Result[i] := j+1;
Inc(i)
end
end;
/// ะะตัะฒัะต n ะฟัะพัััั
ัะธัะตะป
function FirstPrimes(n: integer): array of integer;
// ะะพะดะธัะธัะธัะพะฒะฐะฝะฝะพะต ัะตัะตัะพ ะญัะฐัะพััะตะฝะฐ
begin
var n1 := Trunc(Exp((Ln(n)+1.088)/0.8832));
var Mas := ArrFill(n1, True);
var i := 2;
while i * i <= n1 do
begin
if Mas[i-1] then
begin
var k := i*i;
while k <= n1 do
begin
Mas[k-1] := False;
k += i
end
end;
Inc(i)
end;
//n := Mas.Count(t -> t);
Result := new integer[n];
i := 0;
for var j := 1 to Mas.High do
if Mas[j] then
begin
Result[i] := j+1;
Inc(i);
if i = n then
break
end
end;
{$region}
{$region Digits}
/// ะะพะทะฒัะฐัะฐะตั ะผะฐััะธะฒ, ัะพะดะตัะถะฐัะธะน ัะธััั ัะธัะปะฐ
function Digits(n: int64): array of integer;
begin
var St := new Stack<integer>;
n := Abs(n);
if n = 0 then
Result := Arr(0)
else
begin
while n > 0 do
begin
St.Push(n mod 10);
n := n div 10
end;
Result := St.ToArray
end
end;
/// ะะพะทะฒัะฐัะฐะตั ะผะฐััะธะฒ, ัะพะดะตัะถะฐัะธะน ัะธััั ัะธัะปะฐ
function Digits(Self: integer): array of integer;
extensionmethod := Digits(Self);
/// ะฒะพะทะฒัะฐัะฐะตั ะผะฐััะธะฒ, ัะพะดะตัะถะฐัะธะน ัะธััั ัะธัะปะฐ
function Digits(Self: int64): array of integer;
extensionmethod := Digits(Self);
{$region}
end. |
unit UnitPackingTable;
interface
uses
Classes,
Windows,
Sysutils,
ComObj,
ActiveX,
UnitDBDeclare,
uDBConnection,
uDBThread,
uDBForm;
type
TPackingTableThreadOptions = record
OwnerForm: TDBForm;
FileName: string;
OnEnd: TNotifyEvent;
WriteLineProc: TWriteLineProcedure;
end;
PackingTable = class(TDBThread)
private
{ Private declarations }
FText: string;
FOptions: TPackingTableThreadOptions;
protected
function GetThreadID : string; override;
procedure Execute; override;
public
procedure AddTextLine;
procedure DoExit;
constructor Create(Options: TPackingTableThreadOptions);
end;
implementation
procedure PackingTable.AddTextLine;
begin
FOptions.WriteLineProc(Self, FText, LINE_INFO_OK);
end;
procedure PackingTable.Execute;
begin
inherited;
FreeOnTerminate := True;
try
FText := L('Packing collection files...');
SynchronizeEx(AddTextLine);
PackTable(FOptions.FileName, nil);
FText := L('Packing completed...');
SynchronizeEx(AddTextLine);
finally
SynchronizeEx(DoExit);
end;
end;
function PackingTable.GetThreadID: string;
begin
Result := 'CMD';
end;
procedure PackingTable.DoExit;
begin
FOptions.OnEnd(Self);
end;
constructor PackingTable.Create(Options: TPackingTableThreadOptions);
begin
inherited Create(Options.OwnerForm, False);
FOptions := Options;
end;
end.
|
unit Server.Register;
interface
uses
Spring.Container
;
function GetContainer: TContainer;
implementation
uses
Spring.Container.Common
, Spring.Logging.Configuration
, Server.Logger
, Server.Repository
, Server.Controller
, Server.Configuration
, Server.WiRL;
var
Container: TContainer;
{======================================================================================================================}
function GetContainer: TContainer;
{======================================================================================================================}
begin
Result := Container;
end;
{======================================================================================================================}
procedure RegisterWithContainer(AContainer: TContainer);
{======================================================================================================================}
begin
AContainer.RegisterType<TRepository>.AsPooled(1, 1);
AContainer.RegisterType<TApiV1Controller>;
AContainer.RegisterType<TConfiguration>.AsSingleton(TRefCounting.False);
AContainer.RegisterType<TServerREST>.AsSingleton(TRefCounting.False);
AContainer.Build;
end;
{======================================================================================================================}
procedure InitializeLogger(AContainer: TContainer);
{======================================================================================================================}
var
configuration: TConfiguration;
begin
configuration := GetContainer.Resolve<TConfiguration>;
TLoggingConfiguration.LoadFromString(
Container,
GetLoggingConfiguration(configuration.LogFilename, configuration.LogLevel)
);
Container.Build;
end;
initialization
Container := TContainer.Create;
RegisterWithContainer(Container);
InitializeLogger(Container);
finalization
Container.Free;
end.
|
unit feli_errors;
{$mode objfpc}
interface
type
FeliErrors = class(TObject)
public
const
invalidEmail = 'Invalid Email';
invalidUsernameLength = 'Invalid username length';
invalidPasswordLength = 'Invalid password length';
emptyFirstName = 'Invalid first name length';
emptyLastName = 'Invalid last name length';
emptyDisplayName = 'Invalid display name length';
accessLevelNotAllowed = 'Access level not allowed';
end;
implementation
end. |
unit BitwiseOrOpTest;
{$mode objfpc}{$H+}
interface
uses
fpcunit,
testregistry,
uIntXLibTypes,
uIntX,
uConstants;
type
{ TTestBitwiseOrOp }
TTestBitwiseOrOp = class(TTestCase)
published
procedure ShouldBitwiseOrTwoIntX();
procedure ShouldBitwiseOrPositiveAndNegativeIntX();
procedure ShouldBitwiseOrTwoNegativeIntX();
procedure ShouldBitwiseOrIntXAndZero();
procedure ShouldBitwiseOrTwoBigIntX();
end;
implementation
procedure TTestBitwiseOrOp.ShouldBitwiseOrTwoIntX();
var
int1, int2, Result: TIntX;
begin
int1 := TIntX.Create(3);
int2 := TIntX.Create(5);
Result := int1 or int2;
AssertTrue(Result.Equals(7));
end;
procedure TTestBitwiseOrOp.ShouldBitwiseOrPositiveAndNegativeIntX();
var
int1, int2, Result: TIntX;
begin
int1 := TIntX.Create(-3);
int2 := TIntX.Create(5);
Result := int1 or int2;
AssertTrue(Result.Equals(-7));
end;
procedure TTestBitwiseOrOp.ShouldBitwiseOrTwoNegativeIntX();
var
int1, int2, Result: TIntX;
begin
int1 := TIntX.Create(-3);
int2 := TIntX.Create(-5);
Result := int1 or int2;
AssertTrue(Result.Equals(-7));
end;
procedure TTestBitwiseOrOp.ShouldBitwiseOrIntXAndZero();
var
int1, int2, Result: TIntX;
begin
int1 := TIntX.Create(3);
int2 := TIntX.Create(0);
Result := int1 or int2;
AssertTrue(Result.Equals(int1));
end;
procedure TTestBitwiseOrOp.ShouldBitwiseOrTwoBigIntX();
var
temp1, temp2, temp3: TIntXLibUInt32Array;
int1, int2, int3, Result: TIntX;
begin
SetLength(temp1, 3);
temp1[0] := 3;
temp1[1] := 5;
temp1[2] := TConstants.MaxUInt32Value;
SetLength(temp2, 2);
temp2[0] := 1;
temp2[1] := 8;
SetLength(temp3, 3);
temp3[0] := 3;
temp3[1] := 13;
temp3[2] := TConstants.MaxUInt32Value;
int1 := TIntX.Create(temp1, False);
int2 := TIntX.Create(temp2, False);
int3 := TIntX.Create(temp3, False);
Result := int1 or int2;
AssertTrue(Result.Equals(int3));
end;
initialization
RegisterTest(TTestBitwiseOrOp);
end.
|
unit Class_TrUtils;
interface
uses
Windows,Classes,SysUtils,ElTree;
type
TTrUtils=class(TObject)
public
class function GetLastCode(ASelfLevel:Integer;ASelfCode,ACodeRule:string;AWithDash:Integer):string;
public
class procedure TreeListType(ACodeRule:string;AWithDash:Integer;AListType:TStringList;ATreeView:TElTree;ANeedCheckBox:Boolean=True);overload;
class function FindPrevType(ATreeView:TElTree;ASelfLevel:Integer;ASelfCode,ACodeRule:string;AWithDash:Integer):TElTreeItem;overload;
class procedure TreeListType(ACodeRule:string;AListCord,AListType:TStringList;ATreeView:TElTree;ANeedCheckBox:Boolean=True);overload;
class function FindPrevType(ATreeView:TElTree;ACordIdex:Integer):TElTreeItem;overload;
end;
implementation
uses
Class_CORD_IN_GKZF,Class_TYPE_IN_GKZF;
{ TTrUtils }
class function TTrUtils.FindPrevType(ATreeView: TElTree;
ACordIdex: Integer): TElTreeItem;
var
I:Integer;
CordA:TCord;
ItemA:TElTreeItem;
begin
Result:=nil;
for I:=0 to ATreeView.Items.RootCount-1 do
begin
ItemA:=ATreeView.Items.RootItem[I];
if TObject(ItemA.Data) Is TCORD then
begin
CordA:=TCord(ItemA.Data);
if CordA=nil then Continue;
if CordA.CORDIDEX=ACordIdex then
begin
Result:=ItemA;
Exit;
end;
end;
end;
end;
class function TTrUtils.FindPrevType(ATreeView: TElTree;
ASelfLevel: Integer; ASelfCode, ACodeRule: string;AWithDash:Integer): TElTreeItem;
var
I:Integer;
TypeA:TType;
ItemA:TElTreeItem;
begin
Result:=nil;
for I:=0 to ATreeView.Items.Count-1 do
begin
ItemA:=ATreeView.Items.Item[I];
TypeA:=TType(ItemA.Data);
if TypeA.TypeLevl >= ASelfLevel then Continue;
if TypeA.TypeLink = GetLastCode(ASelfLevel,ASelfCode,ACodeRule,AWithDash) then
begin
Result:=ItemA;
Exit;
end;
end;
end;
class function TTrUtils.GetLastCode(ASelfLevel: Integer; ASelfCode,
ACodeRule: string;AWithDash:Integer): string;
var
ALength:Integer;
begin
Result:='';
ALength:=StrToInt(ACodeRule[ASelfLevel]);
if AWithDash =1 then
begin
Result :=Copy(ASelfCode,1,Length(ASelfCode)-ALength-1);
end else
begin
Result :=Copy(ASelfCode,1,Length(ASelfCode)-ALength);
end;
end;
class procedure TTrUtils.TreeListType(ACodeRule: string; AListCord,
AListType: TStringList; ATreeView: TElTree; ANeedCheckBox: Boolean);
var
I:Integer;
CordA:TCORD;
TypeA:TType;
ItemA:TElTreeItem;
begin
ATreeView.Items.Clear;
if (AListCord=nil) or (AListCord.Count=0) then Exit;
if (AListType=nil) or (AListType.Count=0) then Exit;
with ATreeView do
begin
if ANeedCheckBox then
begin
ShowCheckboxes:=True;
end;
Items.BeginUpdate;
for I:=0 to AListCord.Count-1 do
begin
CordA:=nil;
CordA:=TCORD(AListCord.Objects[I]);
if CordA=nil then Continue;
Items.AddObject(nil,CordA.CORDNAME,CordA);
end;
for I:=0 to AListType.Count-1 do
begin
TypeA:=nil;
TypeA:=TType(AListType.Objects[I]);
ItemA:=nil;
if TypeA.TYPELEVL=1 then
begin
ItemA:=FindPrevType(ATreeView,TypeA.CORDIDEX);
end else
begin
ItemA:=FindPrevType(ATreeView,TypeA.TYPELEVL,TypeA.TYPELINK,ACodeRule,1);
if ItemA=nil then
begin
ItemA:=FindPrevType(ATreeView,TypeA.CORDIDEX);
end;
end;
if ANeedCheckBox then
begin
Items.AddChildObject(ItemA,Format('%S %S',[TypeA.TYPECODE,TypeA.TYPENAME]),TypeA).ShowCheckBox:=True;
end else
begin
Items.AddChildObject(ItemA,Format('%S %S',[TypeA.TYPECODE,TypeA.TYPENAME]),TypeA);
end;
end;
FullExpand;
Items.EndUpdate;
end;
end;
class procedure TTrUtils.TreeListType(ACodeRule: string;AWithDash:Integer;
AListType: TStringList; ATreeView: TElTree; ANeedCheckBox: Boolean);
var
I,M :Integer;
TypeA:TType;
ItemA:TElTreeItem;
ItemB:TElTreeItem;
begin
ATreeView.Items.Clear;
with ATreeView do
begin
if ANeedCheckBox then
begin
ShowCheckboxes:=True;
end;
Items.BeginUpdate;
for I:=1 to Length(ACodeRule) do
begin
for M:=0 to AListType.Count-1 do
begin
TypeA:=nil;
TypeA:=TType(AListType.Objects[M]);
if TypeA.TYPELEVL=I then
begin
ItemA:=FindPrevType(ATreeView,TypeA.TYPELEVL,TypeA.TYPELINK,ACodeRule,AWithDash);
ItemB:=Items.AddChildObject(ItemA,Format('%s %s',[TypeA.TYPECODE,TypeA.TYPENAME]),TypeA);
ItemB.ColumnText.Add(TypeA.TYPEMEMO);
if ANeedCheckBox then
begin
ItemB.ShowCheckBox:=True;
end;
end;
end;
end;
//FullExpand;
FullCollapse;
Items.EndUpdate;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2011-2013 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FMX.Consts;
interface
const
DefaultFontSize = 11;
DefaultFontFamily = 'Tahoma';
// Keys for TPlatformServices.GlobalFlags
GlobalDisableStylusGestures: string = 'GlobalDisableStylusGestures'; // do not localize
GlobalDisableiOSGPUCanvas: string = 'GlobalDisableiOSGPUCanvas'; // do not localize
resourcestring
{ Error Strings }
SInvalidPrinterOp = 'Operation not supported on selected printer';
SInvalidPrinter = 'Printer selected is not valid';
SPrinterIndexError = 'Printer index out of range';
SDeviceOnPort = '%s on %s';
SNoDefaultPrinter = 'There is no default printer currently selected';
SNotPrinting = 'Printer is not currently printing';
SPrinting = 'Printing in progress';
SInvalidPrinterSettings = 'Invalid printing job settings';
SInvalidPageFormat = 'Invalid page format settings';
SCantStartPrintJob = 'Cannot start the printing job';
SCantEndPrintJob = 'Cannot end the printing job';
SCantPrintNewPage = 'Cannot add the page for printing';
SCantSetNumCopies = 'Cannot change the number of document copies';
StrCannotFocus = 'Cannot focus this control';
SInvalidStyleForPlatform = 'The style you have chosen is not available for your currently selected target platform. You can select a custom style or remove the stylebook to allow FireMonkey to automatically load the native style at run time';
SInvalidPrinterClass = 'Invalid printer class: %s';
SPromptArrayTooShort = 'Length of value array must be >= length of prompt array';
SPromptArrayEmpty = 'Prompt array must not be empty';
SInvalidColorString = 'Invalid Color string';
SInvalidFmxHandle = 'Invalid FMX Handle: %s%.*x';
SMediaFileNotSupported = 'Unsupported media file %s%';
SUnsupportedPlatformService = 'Unsupported platform service: %s';
SUnsupportedVersion = 'Unsupported data version: %s';
SNotInstance = 'Instance of "%s" do not created';
SFlasherNotRegistered = 'Class of flashing control, is not registered';
SUnsupportedInterface = 'Class %0:s does not support interface %1:s';
SNullException = 'Handled null exception';
StrErrorShortCut = 'An unknown combination of keys %s';
StrEUseHeirs = 'You can use only the inheritors of class "%s"';
SInvalidGestureID = 'Invalid gesture ID (%d)';
SInvalidStreamFormat = 'Invalid stream format';
SDuplicateGestureName = 'Duplicate gesture name: %s';
SDuplicateRecordedGestureName = 'A recorded gesture named %s already exists';
SControlNotFound = 'Control not found';
SRegisteredGestureNotFound = 'The following registered gestures were not found:'#13#10#13#10'%s';
SErrorLoadingFile = 'Error loading previously saved settings file: %s'#13'Would you like to delete it?';
STooManyRegisteredGestures = 'Too many registered gestures';
SDuplicateRegisteredGestureName = 'A registered gesture named %s already exists';
SUnableToSaveSettings = 'Unable to save settings';
SInvalidGestureName = 'Invalid gesture name (%s)';
SOutOfRange = 'Value must be between %d and %d';
SAddIStylusAsyncPluginError = 'Unable to add IStylusAsyncPlugin: %s';
SAddIStylusSyncPluginError = 'Unable to add IStylusSyncPlugin: %s';
SRemoveIStylusAsyncPluginError = 'Unable to remove IStylusAsyncPlugin: %s';
SRemoveIStylusSyncPluginError = 'Unable to remove IStylusSyncPlugin: %s';
SStylusHandleError = 'Unable to get or set window handle: %s';
SStylusEnableError = 'Unable to enable or disable IRealTimeStylus: %s';
SEnableRecognizerError = 'Unable to enable or disable IGestureRecognizer: %s';
SInitialGesturePointError = 'Unable to retrieve initial gesture point';
SSetStylusGestureError = 'Unable to set stylus gestures: %s';
StrESingleMainMenu = 'The main menu can be only a single instance';
SMainMenuSupportsOnlyTMenuItems = 'A main menu only supports TMenuItem children';
SNoImplementation = 'No %s implementation found';
SBitmapSizeNotEqual = 'Bitmap size must be equal in copy operation';
{ grids }
StrInvalidThePosition = 'Invalid positions or sizes';
SDuplicateCustomOptions = 'A registered grid options class named %s already exists';
SDefColumnText = '<Column # %d>';
{ Dialog Strings }
SMsgDlgWarning = 'Warning';
SMsgDlgError = 'Error';
SMsgDlgInformation = 'Information';
SMsgDlgConfirm = 'Confirmaรงรฃo';
SMsgDlgYes = 'Yes';
SMsgDlgNo = 'No';
SMsgDlgOK = 'OK';
SMsgDlgCancel = 'Cancel';
SMsgDlgHelp = 'Help';
SMsgDlgHelpNone = 'No help available';
SMsgDlgHelpHelp = 'Help';
SMsgDlgAbort = 'Abort';
SMsgDlgRetry = 'Retry';
SMsgDlgIgnore = 'Ignore';
SMsgDlgAll = 'All';
SMsgDlgNoToAll = 'No to All';
SMsgDlgYesToAll = 'Yes to &All';
SMsgDlgClose = 'Close';
SUsername = '&Username';
SPassword = '&Password';
SDomain = '&Domain';
SLogin = 'Login';
{ Menus }
SMenuAppQuit = 'Quit %s';
SMenuCloseWindow = 'Close Window';
SMenuAppHide = 'Hide %s';
SMenuAppHideOthers = 'Hide Others';
SAppDesign = '<Application.Title>';
SAppDefault = 'application';
SGotoTab = 'Go to %s';
SGotoNilTab = 'Go to <Tab>';
SmkcBkSp = 'BkSp';
SmkcTab = 'Tab';
SmkcEsc = 'Esc';
SmkcEnter = 'Enter';
SmkcSpace = 'Space';
SmkcPgUp = 'PgUp';
SmkcPgDn = 'PgDn';
SmkcEnd = 'End';
SmkcHome = 'Home';
SmkcLeft = 'Left';
SmkcUp = 'Up';
SmkcRight = 'Right';
SmkcDown = 'Down';
SmkcIns = 'Ins';
SmkcDel = 'Del';
SmkcShift = 'Shift+';
SmkcCtrl = 'Ctrl+';
SmkcAlt = 'Alt+';
SmkcCmd = 'Cmd+';
SEditUndo = 'Undo';
SEditCopy = 'Copy';
SEditCut = 'Cut';
SEditPaste = 'Paste';
SEditDelete = 'Delete';
SEditSelectAll = 'Select All';
SAseLexerTokenError = 'ERROR at line %d. %s expected but token %s found.';
SAseLexerCharError = 'ERROR at line %d. ''%s'' expected but char ''%s'' found.';
SAseLexerFileCorruption = 'File is corrupt.';
SAseParserWrongMaterialsNumError = 'Wrong materials number';
SAseParserWrongVertexNumError = 'Wrong vertex number';
SAseParserWrongNormalNumError = 'Wrong normal number';
SAseParserWrongTexCoordNumError = 'Wrong texture coord number';
SAseParserWrongVertexIdxError = 'Wrong vertex index';
SAseParserWrongFacesNumError = 'Wrong faces number';
SAseParserWrongFacesIdxError = 'Wrong faces index';
SAseParserWrongTriangleMeshNumError = 'Wrong triangle mesh number';
SAseParserWrongTriangleMeshIdxError = 'Wrong triangle mesh index';
SAseParserWrongTexCoordIdxError = 'Wrong texture coord index';
SAseParserUnexpectedKyWordError = 'Unexpected key word';
SIndexDataNotFoundError = 'Index data not found. File is corrupt.';
SEffectIdNotFoundError = 'Effect id %s not found. File is corrupt.';
SMeshIdNotFoundError = 'Mesh id %s not found. File is corrupt.';
SControllerIdNotFoundError = 'Controller id %s not found. File is corrupt.';
SCannotCreateCircularDependence = 'Cannot create a circular dependency beetwen components';
SPropertyOutOfRange = '%s property out of range';
SPrinterDPIChangeError = 'Active printer DPI can''t be changed while printing';
SPrinterSettingsReadError = 'Error occured while reading printer settings: %s';
SPrinterSettingsWriteError = 'Error occured while writing printer settings: %s';
SVAllFiles = 'All Files';
SVBitmaps = 'Bitmaps';
SVIcons = 'Icons';
SVTIFFImages = 'TIFF Images';
SVJPGImages = 'JPEG Images';
SVPNGImages = 'PNG Images';
SVGIFImages = 'GIF Images';
SVJP2Images = 'Jpeg 2000 Images';
SVTGAImages = 'TGA Images';
SWMPImages = 'WMP Images';
SVAviFiles = 'AVI Files';
SVWMVFiles = 'WMV Files';
SVMP4Files = 'Mpeg4 Files';
SVMOVFiles = 'QuickTime Files';
SVM4VFiles = 'M4V Files';
SVWMAFiles = 'Windows Media Audio Files';
SVMP3Files = 'Mpeg Layer 3 Files';
SVWAVFiles = 'WAV Files';
SVCAFFiles = 'Apple Core Audio Format Files';
{ Media }
SNoFlashError = 'Flash doesn''t exist on this device';
SNoTorchError = 'Flash doesn''t exist on this device';
{ Pickers }
SPickerCancel = 'Cancel';
SPickerDone = 'Done';
{ Media Library }
STakePhotoFromCamera = 'Take Photo';
STakePhotoFromLibarary = 'Photo Library';
SOpenStandartServices = 'Open to';
{ Canvas helpers / 2D and 3D engine / GPU }
SInvalidCallingConditions = 'Invalid calling conditions for ''%s''.';
SInvalidRenderingConditions = 'Invalid rendering conditions for ''%s''.';
STextureSizeTooSmall = 'Cannot create texture for ''%s'' because the size is too small.';
SCannotAcquireBitmapAccess = 'Cannot acquire bitmap access for ''%s''.';
SCannotFindSuitablePixelFormat = 'Cannot find a suitable pixel format for ''%s''.';
SCannotCreateDirect3D = 'Cannot create Direct3D object for ''%s''.';
SCannotCreateD3DDevice = 'Cannot create Direct3D device for ''%s''.';
SCannotAcquireDXGIFactory = 'Cannot acquire DXGI factory from Direct3D device for ''%s''.';
SCannotAssociateWindowHandle = 'Cannot associate the window handle for ''%s''.';
SCannotRetrieveDisplayMode = 'Cannot retrieve display mode for ''%s''.';
SCannotRetrieveBufferDesc = 'Cannot retrieve buffer description for ''%s''.';
SCannotCreateSamplerState = 'Cannot create sampler state for ''%s''.';
SCannotRetrieveSurface = 'Cannot retreive surface for ''%s''.';
SCannotCreateTexture = 'Cannot create texture for ''%s''.';
SCannotUploadTexture = 'Cannot upload pixel data to texture for ''%s''.';
SCannotActivateTexture = 'Cannot activate the texture for ''%s''.';
SCannotAcquireTextureAccess = 'Cannot acquire texture access for ''%s''.';
SCannotCopyTextureResource = 'Cannot copy texture resource ''%s''.';
SCannotCreateRenderTargetView = 'Cannot create render target view for ''%s''.';
SCannotActivateFrameBuffers = 'Cannot activate frame buffers for ''%s''.';
SCannotCreateRenderBuffers = 'Cannot create render buffers for ''%s''.';
SCannotRetrieveRenderBuffers = 'Cannot retrieve device render buffers for ''%s''.';
SCannotActivateRenderBuffers = 'Cannot activate render buffers for ''%s''.';
SCannotBeginRenderingScene = 'Cannot begin rendering scene for ''%s''.';
SCannotSyncDeviceBuffers = 'Cannot synchronize device buffers for ''%s''.';
SCannotUploadDeviceBuffers = 'Cannot upload device buffers for ''%s''.';
SCannotCreateDepthStencil = 'Cannot create a depth/stencil buffer for ''%s''.';
SCannotRetrieveDepthStencil = 'Cannot retrieve device depth/stencil buffer for ''%s''.';
SCannotActivateDepthStencil = 'Cannot activate depth/stencil buffer for ''%s''.';
SCannotCreateSwapChain = 'Cannot create a swap chain for ''%s''.';
SCannotResizeSwapChain = 'Cannot resize swap chain for ''%s''.';
SCannotActivateSwapChain = 'Cannot activate swap chain for ''%s''.';
SCannotCreateVertexShader = 'Cannot create vertex shader for ''%s''.';
SCannotCreatePixelShader = 'Cannot create pixel shader for ''%s''.';
SCannotCreateVertexLayout = 'Cannot create vertex layout for ''%s''.';
SCannotCreateVertexDeclaration = 'Cannot create vertex declaration for ''%s''.';
SCannotCreateVertexBuffer = 'Cannot create vertex buffer for ''%s''.';
SCannotCreateIndexBuffer = 'Cannot create index buffer for ''%s''.';
SCannotCreateShader = 'Cannot create shader for ''%s''.';
SCannotFindShaderVariable = 'Cannot find shader variable ''%s'' for ''%s''.';
SCannotActivateShaderProgram = 'Cannot activate shader program for ''%s''.';
SCannotCreateOpenGLContext = 'Cannot create OpenGL context for ''%s''.';
SCannotUpdateOpenGLContext = 'Cannot update OpenGL context for ''%s''.';
SCannotDrawMeshObject = 'Cannot draw mesh object for ''%s''.';
SErrorInContextMethod = 'Error in context method ''%s''.';
SFeatureNotSupported = 'This feature is not supported in ''%s''.';
SErrorCompressingStream = 'Error compressing stream.';
SErrorDecompressingStream = 'Error decompressing stream.';
SErrorUnpackingShaderCode = 'Error unpacking shader code.';
implementation
end.
|
unit cilk;
interface
uses windows,SysUtils,Classes;
type
ICilk = interface;
Targs = record
ICilk : ICilk;
function spawn<T>(a:T; const p : TProc<T>) : ICilk;overload;
function spawn<T1,T2>(a1:T1; a2:T2; const p : TProc<T1,T2>) : ICilk; overload;
end;
ICilk = interface
['{97CE2295-4885-4966-8CB3-6DF72AF28F74}']
function spawn(const p : TProc) : ICilk;
function args : Targs;
function sync : ICilk;
end;
function newCilk : ICilk;
implementation
type
TCilk = class(TInterfacedObject, ICilk)
FCount : integer;
FErrorCount : integer;
FCountIsZero: THandle;
function spawn(const p : TProc) : ICilk;
function args : Targs;
function sync : ICilk;
procedure _sync; inline;
constructor Create;
destructor Destroy; override;
private
end;
PProc = ^TProc;
PTask = ^TTask;
TTask = record
Count : PInteger;
ErrorCount : PInteger;
CountIsZero : PHandle;
Proc : TProc;
end;
function __ThreadStartRoutine(lpThreadParameter: Pointer): Integer stdcall;
var
task : PTask;
begin
task := lpThreadParameter;
try
task.Proc();
except
InterlockedIncrement( task.ErrorCount^ );
end;
if InterlockedDecrement(task.Count^) = 0 then
SetEvent(task.CountIsZero^);
Dispose(task);
result := 0;
end;
{ TCilk }
constructor TCilk.Create;
begin
FCountIsZero := CreateEvent(nil,false,false,nil);
end;
destructor TCilk.Destroy;
begin
_sync;
CloseHandle(FCountIsZero);
inherited;
end;
function TCilk.spawn(const p: TProc) : ICilk;
var
task : PTask;
begin
result := self;
new(task);
InterlockedIncrement(FCount);
task.Count := @FCount;
task.ErrorCount := @FErrorCount;
task.CountIsZero := @FCountIsZero;
task.Proc := p;
if not QueueUserWorkItem(__ThreadStartRoutine,task,WT_EXECUTELONGFUNCTION) then
begin
dispose(task);
InterlockedDecrement(FCount);
InterlockedIncrement(FErrorCount);
end;
end;
function Targs.spawn<T>(a:T; const p:TProc<T>) : ICilk;
begin
result := ICilk;
result.spawn(
procedure
begin
p(a);
end);
end;
function Targs.spawn<T1,T2>(a1:T1;a2:T2; const p:TProc<T1,T2>) : ICilk;
begin
result := ICilk;
result.spawn(
procedure
begin
p(a1,a2);
end);
end;
function TCilk.args : Targs;
begin
result.ICilk := self;
end;
function TCilk.sync : ICilk;
begin
result := self;
_sync;
end;
procedure TCilk._sync;
begin
if InterlockedCompareExchange(FCount,0,0) <> 0 then
begin
WaitForSingleObject(FCountIsZero,INFINITE);
end;
end;
function newCilk : ICilk;
begin
Result := TCilk.Create;
end;
Initialization
IsMultiThread := true;
finalization
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
PythonEngine, StdCtrls, ComCtrls, ExtCtrls, PythonGUIInputOutput,
AtomPythonEngine;
type
TForm1 = class(TForm)
Memo1: TMemo;
PythonModule1: TPythonModule;
Panel1: TPanel;
Button1: TButton;
Splitter1: TSplitter;
Button2: TButton;
Button3: TButton;
OpenDialog1: TOpenDialog;
SaveDialog1: TSaveDialog;
PythonGUIInputOutput1: TPythonGUIInputOutput;
AtomPythonEngine1: TAtomPythonEngine;
Memo2: TMemo;
procedure Button1Click(Sender: TObject);
procedure PythonModule1Initialization(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Dรฉclarations privรฉes }
public
{ Dรฉclarations publiques }
end;
function spam_foo( self, args : PPyObject ) : PPyObject; cdecl;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
AtomPythonEngine1.ExecStrings( Memo1.Lines );
end;
// Here's an example of functions defined for the module spam
function spam_foo( self, args : PPyObject ) : PPyObject; cdecl;
var
varArgs, first, second, varNewObject: Variant;
begin
//Use the modified PyObjectAsVariant to get an PytonAtom if the argument
//can't convert to standard Variant type. (string, integer, array etc.)
//This way you don't have to think about conversion or reference counting,
//it is handled automaticly by PythonAtom and AtomPythonEngine
varArgs := GetPythonEngine.PyObjectAsVariant(args);
first := varArgs[0];
second := varArgs[1];
ShowMessage( 'first argument: ' + first );
ShowMessage( 'Name of second argument: ' + second.name );
varNewObject:=second.getObject(first);
ShowMessage( 'Name of new object: ' + varNewObject.name );
//Use VariantAsPyObject to return the object to python
Result := GetPythonEngine.VariantAsPyObject(varNewObject);
end;
procedure TForm1.PythonModule1Initialization(Sender: TObject);
begin
// In a module initialization, we just need to add our
// new methods
with Sender as TPythonModule do
begin
AddMethod( 'foo', spam_foo, 'foo' );
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
with OpenDialog1 do
begin
if Execute then
Memo1.Lines.LoadFromFile( FileName );
end;
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
with SaveDialog1 do
begin
if Execute then
Memo1.Lines.SaveToFile( FileName );
end;
end;
end.
|
(*
Category: SWAG Title: FILE HANDLING ROUTINES
Original name: 0039.PAS
Description: Checking File Open
Author: GUY MCLOUGHLIN
Date: 11-21-93 09:30
*)
{
From: GUY MCLOUGHLIN
Subj: Checking file open
I'm looking for a way of detecting if a file is currently open,
so my ExitProc can close it when open and not fail when trying
to close a file that is not open.
(* Public-domain demo to check a file variable's *)
(* current file mode. Guy McLoughlin - Oct '93. *)
}
program Test_FileMode_Demo;
uses
dos;
(**** Display current filemode for a file variable. *)
(* *)
procedure DisplayFileMode({input } const fi_IN);
begin
case textrec(fi_IN).mode of
FMclosed : writeln('* File closed');
FMinput : writeln('* File open in read-only mode');
FMoutput : writeln('* File open in write-only mode');
FMinout : writeln('* File open in read/write mode')
else
writeln('* File not assigned')
end
end; (* DisplayFileMode. *)
(**** Check for IO file errors. *)
(* *)
procedure CheckForIOerror;
var
in_Error : integer;
begin
in_Error := ioresult;
if (ioresult <> 0) then
begin
writeln('Error creating file');
halt(1)
end
end; (* CheckForIOerror. *)
var
fi_Temp1 : text;
fi_Temp2 : file;
BEGIN
(* Demo filemodes for a TEXT file variable. *)
writeln('TEXT file variable test');
DisplayFileMode(fi_Temp1);
assign(fi_Temp1, 'TEST.DAT');
DisplayFileMode(fi_Temp1);
{$I-} rewrite(fi_Temp1); {$I+}
CheckForIOerror;
DisplayFileMode(fi_Temp1);
{$I-} close(fi_Temp1); {$I+}
CheckForIOerror;
DisplayFileMode(fi_Temp1);
(* Demo filemodes for an UNTYPED file variable. *)
writeln;
writeln('UNTYPED file variable test');
DisplayFileMode(fi_Temp2);
assign(fi_Temp2, 'TEST.DAT');
DisplayFileMode(fi_Temp2);
{$I-} rewrite(fi_Temp2); {$I+}
CheckForIOerror;
DisplayFileMode(fi_Temp2);
{$I-} close(fi_Temp2); {$I+}
CheckForIOerror;
DisplayFileMode(fi_Temp2)
END.
(*
*** NOTE: If you are not using version 7 of Turbo Pascal, change
the input parameter of the DisplayFileMode routine from
a CONSTANT parameter to a VAR parameter.
ie: TP7+ : DisplayFileMode({input } const fi_IN);
TP4+ : DisplayFileMode({input } var fi_IN);
- Guy
*)
*
|
unit UDCrossTabGroups;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, UCrpe32;
type
TCrpeCrossTabGroupsDlg = class(TForm)
pnlCrossTabGroups: TPanel;
editFieldName: TEdit;
lblFieldName: TLabel;
lblGOCondition: TLabel;
cbCondition: TComboBox;
lblGODirection: TLabel;
cbDirection: TComboBox;
cbSuppressSubtotal: TCheckBox;
cbSuppressLabel: TCheckBox;
lblBackgroundColor: TLabel;
cbBackgroundColor: TComboBox;
btnOk: TButton;
lblNumber: TLabel;
lbNumbers: TListBox;
lblCount: TLabel;
editCount: TEdit;
ColorDialog1: TColorDialog;
procedure FormCreate(Sender: TObject);
procedure editFieldNameChange(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure UpdateCrossTabGroups;
procedure InitializeControls(OnOff: boolean);
procedure lbNumbersClick(Sender: TObject);
procedure cbConditionChange(Sender: TObject);
procedure cbDirectionChange(Sender: TObject);
procedure cbBackgroundColorChange(Sender: TObject);
procedure cbSuppressSubtotalClick(Sender: TObject);
procedure cbSuppressLabelClick(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure cbBackgroundColorDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
private
{ Private declarations }
public
{ Public declarations }
Crg : TCrpeCrossTabGroups;
CIndex : integer;
CustomBGColor : TColor;
end;
var
CrpeCrossTabGroupsDlg: TCrpeCrossTabGroupsDlg;
bCrossTabGroups : boolean;
implementation
{$R *.DFM}
uses UCrpeUtl;
{------------------------------------------------------------------------------}
{ FormCreate }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabGroupsDlg.FormCreate(Sender: TObject);
begin
LoadFormPos(Self);
btnOk.Tag := 1;
CIndex := -1;
bCrossTabGroups := True;
CustomBGColor := clNone;
{ColorColumnGrandTotals}
with cbBackgroundColor.Items do
begin
AddObject('clBlack', Pointer(clBlack));
AddObject('clMaroon', Pointer(clMaroon));
AddObject('clGreen', Pointer(clGreen));
AddObject('clOlive', Pointer(clOlive));
AddObject('clNavy', Pointer(clNavy));
AddObject('clPurple', Pointer(clPurple));
AddObject('clTeal', Pointer(clTeal));
AddObject('clGray', Pointer(clGray));
AddObject('clSilver', Pointer(clSilver));
AddObject('clRed', Pointer(clRed));
AddObject('clLime', Pointer(clLime));
AddObject('clYellow', Pointer(clYellow));
AddObject('clBlue', Pointer(clBlue));
AddObject('clFuchsia', Pointer(clFuchsia));
AddObject('clAqua', Pointer(clAqua));
AddObject('clWhite', Pointer(clWhite));
AddObject('clNone', Pointer(clNone));
AddObject('Custom', Pointer(CustomBGColor));
end;
end;
{------------------------------------------------------------------------------}
{ FormShow }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabGroupsDlg.FormShow(Sender: TObject);
begin
UpdateCrossTabGroups;
end;
{------------------------------------------------------------------------------}
{ UpdateCrossTabGroups }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabGroupsDlg.UpdateCrossTabGroups;
var
i : integer;
OnOff : boolean;
begin
CIndex := -1;
{Enable/Disable controls}
if IsStrEmpty(Crg.Cr.ReportName) then
OnOff := False
else
begin
OnOff := (Crg.Count > 0);
{Get CrossTabGroup Index}
if OnOff then
begin
if Crg.ItemIndex > -1 then
CIndex := Crg.ItemIndex
else
CIndex := 0;
end;
end;
InitializeControls(OnOff);
{Update list box}
if OnOff = True then
begin
{Fill Numbers ListBox}
for i := 0 to Crg.Count - 1 do
lbNumbers.Items.Add(IntToStr(i));
editCount.Text := IntToStr(Crg.Count);
lbNumbers.ItemIndex := CIndex;
lbNumbersClick(self);
end;
end;
{------------------------------------------------------------------------------}
{ InitializeControls }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabGroupsDlg.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
begin
TComboBox(Components[i]).Color := ColorState(OnOff);
TComboBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TListBox then
begin
TListBox(Components[i]).Clear;
TListBox(Components[i]).Color := ColorState(OnOff);
TListBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TEdit then
begin
TEdit(Components[i]).Text := '';
if TEdit(Components[i]).ReadOnly = False then
TEdit(Components[i]).Color := ColorState(OnOff);
TEdit(Components[i]).Enabled := OnOff;
end;
end;
end;
end;
{------------------------------------------------------------------------------}
{ editFieldNameChange }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabGroupsDlg.editFieldNameChange(Sender: TObject);
begin
Crg[CIndex].FieldName := editFieldName.Text;
end;
{------------------------------------------------------------------------------}
{ lbNumbersClick }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabGroupsDlg.lbNumbersClick(Sender: TObject);
begin
CIndex := lbNumbers.ItemIndex;
editFieldName.Text := Crg[CIndex].FieldName;
cbCondition.ItemIndex := Ord(Crg.Item.Condition);
cbDirection.ItemIndex := Ord(Crg.Item.Direction);
{BackgroundColor}
case Crg.Item.BackgroundColor of
clBlack : cbBackgroundColor.ItemIndex := 0;
clMaroon : cbBackgroundColor.ItemIndex := 1;
clGreen : cbBackgroundColor.ItemIndex := 2;
clOlive : cbBackgroundColor.ItemIndex := 3;
clNavy : cbBackgroundColor.ItemIndex := 4;
clPurple : cbBackgroundColor.ItemIndex := 5;
clTeal : cbBackgroundColor.ItemIndex := 6;
clGray : cbBackgroundColor.ItemIndex := 7;
clSilver : cbBackgroundColor.ItemIndex := 8;
clRed : cbBackgroundColor.ItemIndex := 9;
clLime : cbBackgroundColor.ItemIndex := 10;
clYellow : cbBackgroundColor.ItemIndex := 11;
clBlue : cbBackgroundColor.ItemIndex := 12;
clFuchsia : cbBackgroundColor.ItemIndex := 13;
clAqua : cbBackgroundColor.ItemIndex := 14;
clWhite : cbBackgroundColor.ItemIndex := 15;
clNone : cbBackgroundColor.ItemIndex := 16;
else {Custom}
begin
cbBackgroundColor.ItemIndex := 17;
CustomBGColor := Crg.Item.BackgroundColor;
cbBackgroundColor.Items.Objects[17] := Pointer(CustomBGColor);
end;
end;
cbSuppressSubtotal.Checked := Crg.Item.SuppressSubtotal;
cbSuppressLabel.Checked := Crg.Item.SuppressLabel;
end;
{------------------------------------------------------------------------------}
{ cbConditionChange }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabGroupsDlg.cbConditionChange(Sender: TObject);
begin
Crg.Item.Condition := TCrGroupCondition(cbCondition.ItemIndex);
end;
{------------------------------------------------------------------------------}
{ cbDirectionChange }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabGroupsDlg.cbDirectionChange(Sender: TObject);
begin
Crg[CIndex].Direction := TCrGroupDirection(cbDirection.ItemIndex);
end;
{------------------------------------------------------------------------------}
{ cbBackgroundColorChange }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabGroupsDlg.cbBackgroundColorChange(Sender: TObject);
var
xColor : TColor;
i : integer;
begin
i := cbBackgroundColor.ItemIndex;
xColor := TColor(cbBackgroundColor.Items.Objects[i]);
if cbBackgroundColor.Items[i] = 'Custom' then
begin
ColorDialog1.Color := xColor;
if ColorDialog1.Execute then
begin
xColor := ColorDialog1.Color;
CustomBGColor := xColor;
cbBackgroundColor.Items.Objects[i] := Pointer(CustomBGColor);
cbBackgroundColor.Invalidate;
end;
end;
Crg[CIndex].BackgroundColor := xColor;
end;
{------------------------------------------------------------------------------}
{ cbBackgroundColorDrawItem }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabGroupsDlg.cbBackgroundColorDrawItem(
Control: TWinControl; Index: Integer; Rect: TRect;
State: TOwnerDrawState);
var
ColorR : TRect;
TextR : TRect;
OldColor : TColor;
begin
ColorR.Left := Rect.Left + 1;
ColorR.Top := Rect.Top + 1;
ColorR.Right := Rect.Left + 18{ColorWidth} - 1;
ColorR.Bottom := Rect.Top + cbBackgroundColor.ItemHeight - 1;
TextR.Left := Rect.Left + 18{ColorWidth} + 4;
TextR.Top := Rect.Top + 1;
TextR.Right := Rect.Right;
TextR.Bottom := Rect.Bottom - 1;
with cbBackgroundColor.Canvas do
begin
FillRect(Rect); { clear the rectangle }
OldColor := Brush.Color;
Brush.Color := TColor(cbBackgroundColor.Items.Objects[Index]);
Rectangle(ColorR.Left, ColorR.Top, ColorR.Right, ColorR.Bottom);
Brush.Color := OldColor;
DrawText(Handle, PChar(cbBackgroundColor.Items[Index]), -1, TextR, DT_VCENTER or DT_SINGLELINE);
end;
end;
{------------------------------------------------------------------------------}
{ cbSuppressSubtotalClick }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabGroupsDlg.cbSuppressSubtotalClick(Sender: TObject);
begin
Crg.Item.SuppressSubtotal := cbSuppressSubtotal.Checked;
end;
{------------------------------------------------------------------------------}
{ cbSuppressLabelClick }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabGroupsDlg.cbSuppressLabelClick(Sender: TObject);
begin
Crg.Item.SuppressLabel := cbSuppressLabel.Checked;
end;
{------------------------------------------------------------------------------}
{ btnClearClick }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabGroupsDlg.btnClearClick(Sender: TObject);
begin
Crg.Clear;
UpdateCrossTabGroups;
end;
{------------------------------------------------------------------------------}
{ btnOkClick }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabGroupsDlg.btnOkClick(Sender: TObject);
begin
SaveFormPos(Self);
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose }
{------------------------------------------------------------------------------}
procedure TCrpeCrossTabGroupsDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
bCrossTabGroups := False;
Release;
end;
end.
|
// "Surface3D" produces several perspective plots of a surface described
// mathematically as z = f(x,y) = x * y * (x^2 - y^2) / (x^2 + y^2).
// Hidden lines are not removed.
// Copyright (C) 1982, 1987, 1995, 1998 Earl F. Glynn, Overland Park, KS
// All Rights Reserved. E-Mail Address: EarlGlynn@att.net
unit ScreenSurface3D;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, ExtCtrls;
type
TSurface = class(TForm)
ButtonDraw: TButton;
ClearClear: TButton;
Image: TImage;
ButtonPrint: TButton;
ButtonWriteBMP: TButton;
procedure FormCreate(Sender: TObject);
procedure ClearClearClick(Sender: TObject);
procedure ButtonDrawClick(Sender: TObject);
procedure ButtonPrintClick(Sender: TObject);
procedure ButtonWriteBMPClick(Sender: TObject);
private
PROCEDURE DrawSurface (Canvas: TCanvas; RepaintNeeded: BOOLEAN);
public
end;
var
Surface: TSurface;
implementation
{$R *.DFM}
USES
Printers,
GraphicsMathLibrary,
GraphicsPrimitivesLibrary;
//*** TSurface.FormCreate *****************************************
procedure TSurface.FormCreate(Sender: TObject);
VAR
BitMap: TBitMap;
begin
BitMap := TBitMap.Create;
TRY
BitMap.Width := Image.Width;
BitMap.Height := Image.Height;
Image.Picture.Graphic := BitMap;
FINALLY
Bitmap.Free
END
end;
//*** TSurface.ClearButtonClick ***********************************
procedure TSurface.ClearClearClick(Sender: TObject);
begin
Image.Picture := NIL
end;
//*** DrawSurface *************************************************
PROCEDURE TSurface.DrawSurface (Canvas: TCanvas; RepaintNeeded: BOOLEAN);
CONST
N = 40; {lines 0..N}
xfirst = -2.0;
xlast = 2.0;
yfirst = -2.0;
ylast = 2.0;
VAR
area : TPantoGraph;
azimuth : DOUBLE;
a : TMatrix;
denom : DOUBLE;
distance : DOUBLE;
elevation: DOUBLE;
loop : INTEGER;
x,y : DOUBLE;
xinc,yinc: DOUBLE;
xsq,ysq : DOUBLE;
z : ARRAY[0..N,0..N] OF DOUBLE;
PROCEDURE CreateSurfacePoints;
VAR
i,j : 0..N;
BEGIN
xinc := (xlast-xfirst)/N;
yinc := (ylast-yfirst)/N;
FOR j := N DOWNTO 0 DO
BEGIN
y := yfirst + yinc*j;
ysq := SQR(y);
FOR i := 0 TO N DO
BEGIN
x := xfirst + xinc*i;
xsq := SQR(x);
denom := xsq+ysq;
IF defuzz(denom) = 0.0
THEN z[i,j] := 0.0
ELSE z[i,j] := x * y * (xsq-ysq) / denom;
END;
Application.ProcessMessages
END
END {CreateSurfacePoints};
PROCEDURE DrawSurfaceLines;
VAR
i,j: 0..N;
u : TVector;
BEGIN
FOR i := 0 TO N DO BEGIN
x := xfirst + xinc*i;
FOR j := 0 TO N DO BEGIN
y := yfirst + yinc*j;
u := Vector3D (x,y,z[i,j]);
IF j = 0
THEN area.MoveTo (u)
ELSE area.LineTo (u)
END;
IF RepaintNeeded
THEN Image.Repaint
END;
FOR j := 0 TO N DO
BEGIN
y := yfirst + yinc*j;
FOR i := 0 TO N DO
BEGIN
x := xfirst + xinc*i;
u := Vector3D(x,y,z[i,j]);
IF i = 0
THEN area.MoveTo (u)
ELSE area.LineTo (u)
END;
IF RepaintNeeded
THEN Image.Repaint
END;
END {DrawSurfaceLines};
BEGIN
CreateSurfacePoints;
area := TPantoGraph.Create(Canvas);
area.WorldCoordinatesRange(0.0,1.0, 0.0,1.0);
FOR loop := 0 TO 3 DO
BEGIN
CASE loop OF
0: BEGIN
Canvas.Pen.Color := clRed;
area.ViewPort (0.50,1.00, 0.50,1.00); // upper right corner
azimuth := ToRadians(45.0);
elevation := ToRadians(30.0);
distance := 15.0
END;
1: BEGIN
Canvas.Pen.Color := clGreen;
area.ViewPort (0.00,0.50, 0.50,1.00); // upper left corner
azimuth := TORadians(45.0);
elevation := ToRadians(30.0);
distance := 5.0
END;
2: BEGIN
Canvas.Pen.Color := clBlue;
area.ViewPort (0.00,0.50, 0.00,0.50); // lower left corner
azimuth := ToRadians(45.0);
elevation := ToRadians(0.0);
distance := 15.0
END;
3: BEGIN
Canvas.Pen.Color := clPurple;
area.ViewPort (0.50,1.00, 0.00,0.50); // lower right corner
azimuth := ToRadians(45.0);
elevation := ToRadians(90.0);
distance := 15.0
END;
ELSE
azimuth := 0.0;
elevation := 0.0;
distance := 0.0
END;
a := ViewTransformMatrix (coordSpherical, azimuth,elevation,distance,
4.0,4.0,10.0);
area.SetTransform(a);
DrawSurfaceLines
END;
area.Free
END;
//*** TSurface.DrawButtonClick ************************************
procedure TSurface.ButtonDrawClick(Sender: TObject);
begin
Screen.Cursor := crHourGlass;
TRY
DrawSurface (Surface.Image.Canvas, TRUE)
FINALLY
Screen.Cursor := crDefault
END
end;
//*** TSurface.PrintButtonClock ***********************************
procedure TSurface.ButtonPrintClick(Sender: TObject);
begin
Screen.Cursor := crHourGlass;
TRY
Printer.Orientation := poLandscape;
Printer.BeginDoc;
DrawSurface (Printer.Canvas, FALSE);
Printer.EndDoc;
ShowMessage('Surface printed.');
FINALLY
Screen.Cursor := crDefault
END
end;
//*******************************************************************
procedure TSurface.ButtonWriteBMPClick(Sender: TObject);
VAR
Bitmap: TBitmap;
begin
Screen.Cursor := crHourGlass;
TRY
Bitmap := TBitmap.Create;
Bitmap.Width := 1024;
Bitmap.Height := 1024;
Bitmap.PixelFormat := pf8bit;
DrawSurface (Bitmap.Canvas, FALSE);
Bitmap.SaveToFile('Surface.BMP');
ShowMessage('Surface.BMP written to disk (1024-by-1024 pixels)')
FINALLY
Screen.Cursor := crDefault
END
end;
end.
|
unit colorTable;
{$ifdef fpc}{$mode delphi}{$endif}
interface
uses
Classes, SysUtils, dialogs, userdir, prefs, IniFiles, define_types;
const //maximum number of control points for color schemes...
maxNodes = 100;
kPaintHideDefaultBehavior = -1;
kPaintHideDarkHideBright = 0;
kPaintHideDarkShowBright = 1;
kPaintShowDarkHideBright = 2;
kPaintShowDarkShowBright = 3;
type
TLUT = array [0..255] of TRGBA;
TLUTnodes = record
isFreeSurfer: boolean; //make items brighter or darker than range transparent
rgba: array [0..maxNodes] of TRGBA;
intensity: array [0..maxNodes] of integer;
end;
function UpdateTransferFunction(lLUTnodes :TLUTnodes; isInvert: boolean): TLUT; overload;
function UpdateTransferFunction (lo, hi: TRGBA; isInvert: boolean): TLUT; overload;
//function UpdateTransferFunction (var lIndex: integer; fnm: string; isInvert: boolean): TLUT; overload;
function UpdateTransferFunction (fnm: string; isInvert: boolean): TLUT; overload;
function UpdateTransferFunction (var lIndex: integer; isInvert: boolean): TLUT; overload;//change color table
function CLUTDir: string;
function blendRGBA(c1, c2: TRGBA ): TRGBA;
function blendRGBAover(ca, cb: TRGBA ): TRGBA;
function maxRGBA(c1, c2: TRGBA ): TRGBA;
//function inten2rgb(intensity, mn, mx: single; lut: TLUT): TRGBA;
function inten2rgb(intensity, mn, mx: single; lut: TLUT; mode: integer): TRGBA; overload;
//function inten2rgb(intensity, mn, mx: single; lut: TLUT): TRGBA; overload;
function inten2rgb1(intensity, mn, mx: single; lut: TLUT): TRGBA; //use 1st not 0th LUT color (0 is transparent)
function desaturateRGBA ( rgba: TRGBA; frac: single; alpha: byte): TRGBA;
function isFreeSurferLUT(lIndex: integer): boolean;
implementation
uses mainunit;
function isFreeSurferLUT(lIndex: integer): boolean;
begin
result := (lIndex >= 15) and (lIndex <= 18);
end;
function blendRGBAover(ca, cb: TRGBA ): TRGBA;
//https://en.wikipedia.org/wiki/Alpha_compositing#Analytical_derivation_of_the_over_operator
var
aa, ab, ao: single;
begin
if cb.A = 0 then exit(ca);
if ca.A = 0 then exit(cb);
aa := ca.A / 255;
ab := cb.A / 255;
ao := 1.0 - (1.0-aa)*(1.0-ab);
result.R := round(((aa*ca.r)+(1-aa)*ab*cb.r)/ao) ;
result.G := round(((aa*ca.g)+(1-aa)*ab*cb.g)/ao) ;
result.B := round(((aa*ca.b)+(1-aa)*ab*cb.b)/ao) ;
result.A := round(ao * 255.0);
end;
function blendRGBA(c1, c2: TRGBA ): TRGBA;
var
frac1, frac2: single;
begin
result := c1;
if c2.A = 0 then exit;
result := c2;
if c1.A = 0 then exit;
frac1 := c1.A / (c1.A+c2.A);
frac2 := 1 - frac1;
result.R := round(c1.R*frac1 + c2.R*frac2) ;
result.G := round(c1.G*frac1 + c2.G*frac2);
result.B := round(c1.B*frac1 + c2.B*frac2);
if frac1 >= 0.5 then //result.a = max(c1.a, c2.a)
result.A := c1.A
else
result.A := c2.A;
end;
function maxRGBA(c1, c2: TRGBA ): TRGBA;
begin
result := c1;
if c2.A = 0 then exit;
if (c2.R > result.R) then
result.R := c2.R;
if (c2.G > result.G) then
result.G := c2.G;
if (c2.B > result.B) then
result.B := c2.B;
if (c2.A > result.A) then
result.A := c2.A;
end;
function inten2rgb(intensity, mn, mx: single; lut: TLUT; mode: integer): TRGBA; overload;
var
i: byte;
//isInvert : boolean;
begin
if (mn < 0) and (mx < 0) and (mode = kPaintHideDefaultBehavior) then begin
if intensity >= mx then
exit( lut[0])
else if intensity <= mn then
exit( lut[255])
else
exit( lut[round(255* (1.0- (intensity-mn)/(mx-mn)))]);
end;
if intensity > mx then begin
i := 255;
if (mode = kPaintHideDarkHideBright) or (mode = kPaintShowDarkHideBright) then //hide bright
i := 0;
end else if intensity < mn then begin
i := 0;
if (mode = kPaintShowDarkHideBright) or (mode = kPaintShowDarkShowBright) then //hide dark
i := 1;
end else begin
i := round(255*(intensity-mn)/(mx-mn));
if (i = 0) and ((mode = kPaintHideDefaultBehavior) or (mode = kPaintShowDarkHideBright) or (mode = kPaintShowDarkShowBright)) then //hide dark
i := 1;
end;
result := lut[i];
end;
function inten2rgb(intensity, mn, mx: single; lut: TLUT): TRGBA; overload;
begin
//result := inten2rgb(intensity, mn, mx, lut, kPaintHideDefaultBehavior);
result := inten2rgb(intensity, mn, mx, lut,kPaintHideDarkHideBright);
end;
(*function inten2rgb(intensity, mn, mx: single; lut: TLUT): TRGBA;
begin
if (mn < 0) and (mx < 0) then begin
if intensity >= mx then begin
result := lut[0];
end else if intensity <= mn then
result := lut[255]
else
result := lut[round(255* (1.0- (intensity-mn)/(mx-mn)))];
end else begin
if (intensity <= mn) and (intensity <> 0) and (LUT[0].A <> 0) then
result := lut[1]
else if intensity < mn then
result := lut[0]
else if intensity = mn then begin
result := lut[0];
result.A := lut[1].A;
end else if intensity >= mx then
result := lut[255]
else
result := lut[round(255*(intensity-mn)/(mx-mn))];
end;
end; *)
function inten2rgb1(intensity, mn, mx: single; lut: TLUT): TRGBA; //use 1st not 0th LUT color (0 is transparent)
var i :integer;
begin
if (mn < 0) and (mx < 0) then begin
if intensity >= mx then
i := 0
else if intensity <= mn then
i := 255
else
i := round(255* (1.0- (intensity-mn)/(mx-mn)));
end else begin
if intensity <= mn then
i := 0
else if intensity >= mx then
i := 255
else
i := round(255*(intensity-mn)/(mx-mn));
end;
if (i < 1) then i := 1;
result := lut[i];
end;
function desaturateRGBA ( rgba: TRGBA; frac: single; alpha: byte): TRGBA;
var
y: single;
begin
//convert RGB->YUV http://en.wikipedia.org/wiki/YUV
y := 0.299 * rgba.r + 0.587 * rgba.g + 0.114 * rgba.b;
result.r := round(y * (1-frac) + rgba.r * frac);
result.g := round(y * (1-frac) + rgba.g * frac);
result.b := round(y * (1-frac) + rgba.b * frac);
result.a := alpha;
end;
procedure printf(s: string);
begin
{$ifdef Unix}
writeln(s);
{$endif}
end;
function CLUTDir: string;
begin
//result := extractfilepath(paramstr(0))+'lut';
result := ResourceDir+pathdelim+'lut';
if DirectoryExists(result) then exit;
result := AppDir+'lut';
{$IFDEF UNIX}
if DirectoryExists(result) then exit;
result := '/usr/share/surfice/lut';
if DirectoryExists(result) then exit;
result := AppDir+'lut';
{$ENDIF}
printf('Unable to find "lut" resource folder');
end;
procedure setNode (r,g,b,a,i, node: integer; var lLUTnodes : TLUTnodes);
begin
lLUTnodes.rgba[node].R := r;
lLUTnodes.rgba[node].G := g;
lLUTnodes.rgba[node].B := b;
lLUTnodes.rgba[node].A := a;
lLUTnodes.intensity[node] := i;
end;
function loadCustomLUT(lFilename: string): TLUTnodes; overload;
var
lIniFile: TIniFile;
numnodes, i: integer;
inten: byte;
rgba: TRGBA;
begin
setNode(0,0,0,0,0, 0, result);
setNode(255,255,255,255,255, 1, result);
result.isFreeSurfer:= false;
lIniFile := TIniFile.Create(lFilename);
IniInt(true,lIniFile, 'numnodes', numnodes);
if (numnodes < 1) or (numnodes > maxNodes) then begin
if (numnodes > maxNodes) then
showmessage(format('Too many nodes (%d, maximum %d)', [numnodes, maxNodes]));
lIniFile.Free;
//lIndex := 0;
exit;
end;
for i := 0 to (numnodes-1) do begin
IniByte(true,lIniFile, 'nodeintensity'+inttostr(i),inten);
IniRGBA(true,lIniFile, 'nodergba'+inttostr(i),rgba);
setNode(rgba.r, rgba.g, rgba.b, rgba.a, inten, i, result);
end;
lIniFile.Free;
end;
function loadCustomLUT(var lIndex: integer): TLUTnodes; overload;
var
lFilename: string;
(*lIniFile: TIniFile;
numnodes, i: integer;
inten: byte;
rgba: TRGBA; *)
begin
setNode(0,0,0,0,0, 0, result);
setNode(255,255,255,255,255, 1, result);
result.isFreeSurfer:= false;
if lIndex >= GLForm1.LayerColorDrop.Items.Count then
lIndex := GLForm1.LayerColorDrop.Items.Count -1;
if lIndex < 0 then
lIndex := 0;
lFilename := CLUTdir+pathdelim+GLForm1.LayerColorDrop.Items[lIndex]+'.clut';
if not fileexists(lFilename) then begin
lIndex := 0;
exit;
end;
result := loadCustomLUT(lFilename);
(* lIniFile := TIniFile.Create(lFilename);
IniInt(true,lIniFile, 'numnodes', numnodes);
if (numnodes < 1) or (numnodes > maxNodes) then begin
if (numnodes > maxNodes) then
showmessage(format('Too many nodes (%d, maximum %d)', [numnodes, maxNodes]));
lIniFile.Free;
lIndex := 0;
exit;
end;
for i := 0 to (numnodes-1) do begin
IniByte(true,lIniFile, 'nodeintensity'+inttostr(i),inten);
IniRGBA(true,lIniFile, 'nodergba'+inttostr(i),rgba);
setNode(rgba.r, rgba.g, rgba.b, rgba.a, inten, i, result);
end;
lIniFile.Free; *)
end;
function defaultLabelLut: TLUT;
function makeRGB (r,b,g: byte): TRGBA;
//linear interpolation
begin
result.R := r;
result.G := g;
result.B := b;
end;//lerpRGBA()
var
lut: TLUT;
i: integer;
begin
//lut[0] := makeRGB(fBackColor.r,fBackColor.g, fBackColor.b);
lut[0].A := 0;
lut[1] := makeRGB(71,46,154);
lut[2] := makeRGB(33,78,43);
lut[3] := makeRGB(192,199,10);
lut[4] := makeRGB(32,79,207);
lut[5] := makeRGB(195,89,204);
lut[6] := makeRGB(208,41,164);
lut[7] := makeRGB(173,208,231);
lut[8] := makeRGB(233,135,136);
lut[9] := makeRGB(202,20,58);
lut[10] := makeRGB(25,154,239);
lut[11] := makeRGB(210,35,30);
lut[12] := makeRGB(145,21,147);
lut[13] := makeRGB(89,43,230);
lut[14] := makeRGB(87,230,101);
lut[15] := makeRGB(245,113,111);
lut[16] := makeRGB(246,191,150);
lut[17] := makeRGB(38,147,35);
lut[18] := makeRGB(3,208,128);
lut[19] := makeRGB(25,37,57);
lut[20] := makeRGB(57,28,252);
lut[21] := makeRGB(167,27,79);
lut[22] := makeRGB(245,86,173);
lut[23] := makeRGB(86,203,120);
lut[24] := makeRGB(227,25,25);
lut[25] := makeRGB(208,209,126);
lut[26] := makeRGB(81,148,81);
lut[27] := makeRGB(64,187,85);
lut[28] := makeRGB(90,139,8);
lut[29] := makeRGB(199,111,7);
lut[30] := makeRGB(140,48,122);
lut[31] := makeRGB(48,102,237);
lut[32] := makeRGB(212,76,190);
lut[33] := makeRGB(180,110,152);
lut[34] := makeRGB(70,106,246);
lut[35] := makeRGB(120,130,182);
lut[36] := makeRGB(9,37,130);
lut[37] := makeRGB(192,160,219);
lut[38] := makeRGB(245,34,67);
lut[39] := makeRGB(177,222,76);
lut[40] := makeRGB(65,90,167);
lut[41] := makeRGB(157,165,178);
lut[42] := makeRGB(9,245,235);
lut[43] := makeRGB(193,222,250);
lut[44] := makeRGB(100,102,28);
lut[45] := makeRGB(181,47,61);
lut[46] := makeRGB(125,19,186);
lut[47] := makeRGB(145,130,250);
lut[48] := makeRGB(62,4,199);
lut[49] := makeRGB(8,232,67);
lut[50] := makeRGB(108,137,58);
lut[51] := makeRGB(36,211,50);
lut[52] := makeRGB(140,240,86);
lut[53] := makeRGB(237,11,182);
lut[54] := makeRGB(242,140,108);
lut[55] := makeRGB(248,21,77);
lut[56] := makeRGB(161,42,89);
lut[57] := makeRGB(189,22,112);
lut[58] := makeRGB(41,241,59);
lut[59] := makeRGB(114,61,125);
lut[60] := makeRGB(65,99,226);
lut[61] := makeRGB(121,115,50);
lut[62] := makeRGB(97,199,205);
lut[63] := makeRGB(50,166,227);
lut[64] := makeRGB(238,114,125);
lut[65] := makeRGB(149,190,128);
lut[66] := makeRGB(44,204,104);
lut[67] := makeRGB(214,60,27);
lut[68] := makeRGB(124,233,59);
lut[69] := makeRGB(167,66,66);
lut[70] := makeRGB(40,115,53);
lut[71] := makeRGB(167,230,133);
lut[72] := makeRGB(127,125,159);
lut[73] := makeRGB(178,103,203);
lut[74] := makeRGB(231,203,97);
lut[75] := makeRGB(30,125,125);
lut[76] := makeRGB(173,13,139);
lut[77] := makeRGB(244,176,159);
lut[78] := makeRGB(193,94,158);
lut[79] := makeRGB(203,131,7);
lut[80] := makeRGB(204,39,215);
lut[81] := makeRGB(238,198,47);
lut[82] := makeRGB(139,167,140);
lut[83] := makeRGB(135,124,226);
lut[84] := makeRGB(71,67,223);
lut[85] := makeRGB(234,175,231);
lut[86] := makeRGB(234,254,44);
lut[87] := makeRGB(217,1,110);
lut[88] := makeRGB(66,15,184);
lut[89] := makeRGB(14,198,61);
lut[90] := makeRGB(129,62,233);
lut[91] := makeRGB(19,237,47);
lut[92] := makeRGB(97,159,67);
lut[93] := makeRGB(165,31,148);
lut[94] := makeRGB(112,218,22);
lut[95] := makeRGB(244,58,120);
lut[96] := makeRGB(35,244,173);
lut[97] := makeRGB(73,47,156);
lut[98] := makeRGB(192,61,117);
lut[99] := makeRGB(12,67,181);
lut[100] := makeRGB(149,94,94);
for i := 1 to 100 do
lut[i+100] := lut[i]; //fill 101..200
for i := 1 to 55 do
lut[i+200] := lut[i]; //fill 201..255
result := lut;
end;
function makeLUT(var lIndex: integer): TLUTnodes;
begin
//generate default grayscale color table
//result.numnodes := 2; //number of nodes implicit: final node has intensity=255
setNode(0,0,0,0,0, 0, result);
setNode(255,255,255,255,255, 1, result);
result.isFreeSurfer:= false;
case lIndex of //generate alternative color table if specified
0: exit; //default grayscale
1: begin //Red-Yellow
setNode(192,0,0,0,0, 0, result);
setNode(255,255,0,255,255, 1, result);
end;
2: begin //Blue-Green
setNode(0,0,192,0,0, 0, result);
setNode(0,255,128,255,255, 1, result);
end;
3: begin //Red
setNode(255,0,0,255,255, 1, result);
end;
4: begin //Green
setNode(0,255,0,255,255, 1, result);
end;
5: begin //Blue
setNode(0,0,255,255,255, 1, result);
end;
6: begin //Violet R+B
setNode(255,0,255,255,255, 1, result);
end;
7: begin //Yellow R+G
setNode(255,255,0,255,255, 1, result);
end;
8: begin //Cyan B+G
setNode(0,255,255,255,255, 1, result);
end;
9: begin //HotLut
//result.numnodes:=4;
setNode(3,0,0,0,0, 0, result);
setNode(255,0,0,48,95, 1, result);
setNode(255,255,0,96,191, 2, result);
setNode(255,255,255,128,255, 3, result);
end;
10: begin //bone
//result.numnodes:=3;
setNode(0,0,0,0,0, 0, result);
setNode(103,126,165,76,153, 1, result);
setNode(255,255,255,128,255, 2, result);
end;
11: begin //WinterLut
//result.numnodes:=3;
setNode(0,0,255,0,0, 0, result);
setNode(0,128,196,64,128, 1, result);
setNode(0,255,128,128,255, 2, result);
end;
12: begin //GE-Color
//result.numnodes:=5;
setNode(0,0,0,0,0, 0, result);
setNode(0,128,125,32,63, 1, result);
setNode(128,0,255,64,128, 2, result);
setNode(255,128,0,96,192, 3, result);
setNode(255,255,255,128,255, 4, result);
end;
13: begin //ACTC
//result.numnodes:=5;
setNode(0,0,0,0,0, 0, result);
setNode(0,0,136,32,64, 1, result);
setNode(24,177,0,64,128, 2, result);
setNode(248,254,0,78,156, 3, result);
setNode(255,0,0,128,255, 4, result);
end;
14: begin //X-rain
//result.numnodes:=7;
setNode(0,0,0,0,0, 0, result);
setNode(64,0,128,8,32, 1, result);
setNode(0,0,255,16,64, 2, result);
setNode(0,255,0,24,96, 3, result);
setNode(255,255,0,32,160, 4, result);
setNode(255,192,0,52,192, 5, result);
setNode(255,3,0,80,255, 6, result);
end;
15: begin //FreeSurferCurve - valleys dark
result.isFreeSurfer:= true;
setNode( 0, 0, 0, 0, 0, 0, result);
setNode( 0, 0, 0, 0,136, 1, result);
setNode( 0, 0, 0,140,155, 2, result);
setNode( 0, 0, 0,200,255, 3, result);
end;
16: begin //FreeSurferCurve - curves (valleys and ridges) dark
result.isFreeSurfer:= true;
setNode(0,0,0,255,0, 0, result);
setNode(0,0,0,0,100, 1, result);
setNode(0,0,0,0,156, 2, result);
setNode(0,0,0,255,255, 3, result);
end;
17: begin //FreeSurferCurve - flat surfaces darkened
result.isFreeSurfer:= true;
setNode(0,0,0,0,0, 0, result);
setNode(0,0,0,0,100, 1, result);
setNode(0,0,0,255,128, 2, result);
setNode(0,0,0,0,156, 3, result);
setNode(0,0,0,0,255, 4, result);
end;
18: begin //FreeSurferCurve - ridges dark
result.isFreeSurfer:= true;
setNode(0,0,0,255,0, 0, result);
setNode(0,0,0,0,100,1, result);
setNode(0,0,0,0,255, 2, result);
end;
19: begin //Random Label
result.isFreeSurfer:= false;
setNode(7,7,7,255,255, 0, result);
setNode(0,0,0,0,100,1, result);
end;
else begin
result := loadCustomLUT(lIndex); //index unknown!!!
end;
end; //case: alternative LUTs
end; //makeLUT()
function lerpRGBA (p1,p2: TRGBA; frac: single): TRGBA;
//linear interpolation
begin
result.R := round(p1.R + frac * (p2.R - p1.R));
result.G := round(p1.G + frac * (p2.G - p1.G));
result.B := round(p1.B + frac * (p2.B - p1.B));
result.A := round(p1.A + frac * (p2.A - p1.A));
end;//lerpRGBA()
function UpdateTransferFunction (fnm: string; isInvert: boolean): TLUT; overload;//change color table
var
lLUTNodes :TLUTnodes;
begin
lLUTNodes := loadCustomLUT(fnm);
result := UpdateTransferFunction(lLUTNodes, isInvert);
end;
function UpdateTransferFunction (var lIndex: integer; isInvert: boolean): TLUT; overload;//change color table
var
lLUTNodes :TLUTnodes;
begin
lLUTNodes := makeLUT(lIndex);
result := UpdateTransferFunction(lLUTNodes, isInvert);
end;
function UpdateTransferFunction (lo, hi: TRGBA; isInvert: boolean): TLUT; overload;
var
lLUTNodes :TLUTnodes;
i: integer = 0;
begin
lLUTNodes := makeLUT(i);
setNode(lo.r,lo.g,lo.b,0,0, 0, lLUTNodes);
setNode(hi.r,hi.g,hi.b,255,255, 1, lLUTNodes);
//lLUTNodes.isFreeSurfer:= false;
result := UpdateTransferFunction(lLUTnodes, isInvert);
end;
function UpdateTransferFunction(lLUTnodes :TLUTnodes; isInvert: boolean): TLUT; overload;
label
123;
var
lInc,lNodeLo: integer;
frac, f: single;
rev: TLUT;
begin
(*if fnm <> '' then
lLUTNodes := loadCustomLUT(fnm)
else
lLUTNodes := makeLUT(lIndex);*)
if (lLUTNodes.rgba[0].R = 7) and (lLUTNodes.rgba[0].G = 7) and (lLUTNodes.rgba[0].B = 7) and (lLUTNodes.rgba[0].A = 255) and (lLUTNodes.intensity[0] = 255) then begin
result := defaultLabelLut;
goto 123;
end;
lNodeLo := 0;
result[0] := lerpRGBA(lLUTNodes.rgba[0],lLUTNodes.rgba[0],1);
for lInc := 1 to 255 do begin
f := lInc;
if (f < 0) then f := 0;
if (f > 255) then f := 255;
//if ((lNodeLo+1) < lLUTNodes.numnodes) and ( f > lLUTNodes.intensity[lNodeLo + 1] ) then
if ( f > lLUTNodes.intensity[lNodeLo + 1] ) then
lNodeLo := lNodeLo + 1;
frac := (f-lLUTNodes.Intensity[lNodeLo])/(lLUTNodes.Intensity[lNodeLo+1]-lLUTNodes.Intensity[lNodeLo]);
if (frac < 0) then frac := 0;
if frac > 1 then frac := 1;
result[lInc] := lerpRGBA(lLUTNodes.rgba[lNodeLo],lLUTNodes.rgba[lNodeLo+1],frac);
end;
123:
if isInvert then begin
rev := result;
for lInc := 0 to 255 do
result[lInc] := rev[255-lInc];
result[0].A := rev[0].A;
result[255].A := rev[255].A;
end;
if lLUTNodes.isFreeSurfer then begin
exit; //not for freesurfer
end;
//result[0].A := 0; //see LUT[0].A <> 0
for lInc := 1 to 255 do
result[lInc].A := 255;
end;
(*function UpdateTransferFunction (var lIndex: integer; fnm: string; isInvert: boolean): TLUT; overload;
label
123;
var
lLUTnodes :TLUTnodes;
lInc,lNodeLo: integer;
frac, f: single;
rev: TLUT;
begin
if fnm <> '' then
lLUTNodes := loadCustomLUT(fnm)
else
lLUTNodes := makeLUT(lIndex);
if (lLUTNodes.rgba[0].R = 7) and (lLUTNodes.rgba[0].G = 7) and (lLUTNodes.rgba[0].B = 7) and (lLUTNodes.rgba[0].A = 255) and (lLUTNodes.intensity[0] = 255) then begin
result := defaultLabelLut;
goto 123;
end;
lNodeLo := 0;
result[0] := lerpRGBA(lLUTNodes.rgba[0],lLUTNodes.rgba[0],1);
for lInc := 1 to 255 do begin
f := lInc;
if (f < 0) then f := 0;
if (f > 255) then f := 255;
//if ((lNodeLo+1) < lLUTNodes.numnodes) and ( f > lLUTNodes.intensity[lNodeLo + 1] ) then
if ( f > lLUTNodes.intensity[lNodeLo + 1] ) then
lNodeLo := lNodeLo + 1;
frac := (f-lLUTNodes.Intensity[lNodeLo])/(lLUTNodes.Intensity[lNodeLo+1]-lLUTNodes.Intensity[lNodeLo]);
if (frac < 0) then frac := 0;
if frac > 1 then frac := 1;
result[lInc] := lerpRGBA(lLUTNodes.rgba[lNodeLo],lLUTNodes.rgba[lNodeLo+1],frac);
end;
123:
if isInvert then begin
rev := result;
for lInc := 0 to 255 do
result[lInc] := rev[255-lInc];
result[0].A := rev[0].A;
result[255].A := rev[255].A;
end;
if lLUTNodes.isFreeSurfer then begin
exit; //not for freesurfer
end;
//result[0].A := 0; //see LUT[0].A <> 0
for lInc := 1 to 255 do
result[lInc].A := 255;
end;//LoadLUT() *)
end.
|
unit ibSHDependencies;
interface
uses
SysUtils, Classes, StrUtils, Contnrs,
SHDesignIntf, ibSHDesignIntf, ibSHDriverIntf, ibSHComponent;
type
TibBTDependenceDescr = class
private
FObjectType: Integer;
FObjectName: string;
FFieldName: string;
public
property ObjectType: Integer read FObjectType write FObjectType;
property ObjectName: string read FObjectName write FObjectName;
property FieldName: string read FFieldName write FFieldName;
end;
TibBTDependencies = class(TibBTComponent, IibSHDependencies)
private
FDependenceList: TObjectList;
FResultList: TStrings;
procedure Execute(AType: TibSHDependenceType; const BTCLDatabase: IibSHDatabase;
const AClassIID: TGUID; const ACaption: string; AOwnerCaption: string = '');
function GetObjectNames(const AClassIID: TGUID; AOwnerCaption: string = ''): TStrings;
function IsEmpty: Boolean;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
implementation
uses
ibSHConsts, ibSHSQLs, ibSHValues, ibSHStrUtil;
{ TibBTDependencies }
constructor TibBTDependencies.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDependenceList := TObjectList.Create;
FResultList := TStringList.Create;
end;
destructor TibBTDependencies.Destroy;
begin
FDependenceList.Free;
FResultList.Free;
inherited Destroy;
end;
procedure TibBTDependencies.Execute(AType: TibSHDependenceType; const BTCLDatabase: IibSHDatabase;
const AClassIID: TGUID; const ACaption: string; AOwnerCaption: string = '');
var
SQL: string;
DependenceDescr: TibBTDependenceDescr;
BegSub, EndSub: TCharSet;
GeneratorID: string;
begin
BegSub := ['+', ')', '(', '*', '/', '|', ',', '=', '>', '<', '-', '!', '^', '~', ',', ';', ' ', #13, #10, #9, '"'];
EndSub := ['+', ')', '(', '*', '/', '|', ',', '=', '>', '<', '-', '!', '^', '~', ',', ';', ' ', #13, #10, #9, '"'];
if AnsiSameText(BTCLDatabase.BTCLServer.Version, SInterBase70) or
AnsiSameText(BTCLDatabase.BTCLServer.Version, SInterBase71) or
AnsiSameText(BTCLDatabase.BTCLServer.Version, SInterBase75) or
AnsiSameText(BTCLDatabase.BTCLServer.Version, SInterBase2007)
then
GeneratorID := '11'
else
GeneratorID := '14';
if IsEqualGUID(AClassIID, IibSHDomain) or IsEqualGUID(AClassIID, IibSHSystemDomain) then
case AType of
dtUsedBy: SQL := FormatSQL(SQL_GET_DOMAIN_USED_BY);
dtUses:;
end
else
if IsEqualGUID(AClassIID, IibSHTable) or IsEqualGUID(AClassIID, IibSHSystemTable) or IsEqualGUID(AClassIID, IibSHSystemTableTmp) then
case AType of
dtUsedBy: SQL := FormatSQL(SQL_GET_TABLE_USED_BY);
dtUses: SQL := FormatSQL(SQL_GET_TABLE_USES);
end
else
if IsEqualGUID(AClassIID, IibSHField) then
{ TODO : ะ ะฐะทะพะฑัะฐัััั ั ะทะฐะฒะธัะธะผะพัััะผะธ ะฟะพะปะตะน }
case AType of
dtUsedBy: SQL := Format(FormatSQL(SQL_GET_FIELD_USED_BY), [AOwnerCaption, ACaption, AOwnerCaption, ACaption, AOwnerCaption, ACaption, AOwnerCaption, ACaption]);
dtUses:
SQL:= Format(FormatSQL(SQL_GET_FIELD_USES),
[AOwnerCaption, ACaption, AOwnerCaption, ACaption,
AOwnerCaption, ACaption, AOwnerCaption, ACaption]);
end
else
if IsEqualGUID(AClassIID, IibSHConstraint) then
case AType of
dtUsedBy:;
dtUses:;
end
else
if IsEqualGUID(AClassIID, IibSHIndex) then
case AType of
dtUsedBy:;
dtUses:;
end
else
if IsEqualGUID(AClassIID, IibSHView) then
case AType of
dtUsedBy: SQL := FormatSQL(SQL_GET_VIEW_USED_BY);
dtUses: SQL := FormatSQL(SQL_GET_VIEW_USES);
end
else
if IsEqualGUID(AClassIID, IibSHProcedure) then
case AType of
dtUsedBy: SQL := FormatSQL(SQL_GET_PROCEDURE_USED_BY);
dtUses: SQL := FormatSQL(SQL_GET_PROCEDURE_USES);
end
else
if IsEqualGUID(AClassIID, IibSHTrigger) then
case AType of
dtUsedBy:;
dtUses: SQL := FormatSQL(SQL_GET_TRIGGER_USES);
end
else
if IsEqualGUID(AClassIID, IibSHGenerator) then
case AType of
dtUsedBy: SQL := Format(FormatSQL(SQL_GET_GENERATOR_USED_BY), [GeneratorID]);
dtUses:;
end
else
if IsEqualGUID(AClassIID, IibSHException) then
case AType of
dtUsedBy: SQL := FormatSQL(SQL_GET_EXCEPTION_USED_BY);
dtUses:;
end
else
if IsEqualGUID(AClassIID, IibSHFunction) then
case AType of
dtUsedBy: SQL := FormatSQL(SQL_GET_FUNCTION_USED_BY);
dtUses:;
end
else
if IsEqualGUID(AClassIID, IibSHFilter) then
case AType of
dtUsedBy: SQL := FormatSQL(SQL_GET_FILTER_USED_BY);
dtUses:;
end;
FDependenceList.Clear;
if Length(SQL) = 0 then Exit;
if BTCLDatabase.DRVQuery.ExecSQL(SQL, [ACaption], False, not IsEqualGUID(AClassIID, IibSHField)) then
begin
while not BTCLDatabase.DRVQuery.Eof do
begin
DependenceDescr := TibBTDependenceDescr.Create;
DependenceDescr.ObjectType := BTCLDatabase.DRVQuery.GetFieldIntValue(0);
DependenceDescr.ObjectName := BTCLDatabase.DRVQuery.GetFieldStrValue(1);
DependenceDescr.FieldName := BTCLDatabase.DRVQuery.GetFieldStrValue(2);
FDependenceList.Add(DependenceDescr);
BTCLDatabase.DRVQuery.Next;
end;
end;
if IsEqualGUID(AClassIID, IibSHFunction) or IsEqualGUID(AClassIID, IibSHFilter) or
(IsEqualGUID(AClassIID, IibSHGenerator) and (GeneratorID = '11')) then
begin
SQL := FormatSQL(SQL_GET_FUNCTION_USED_BY2);
if BTCLDatabase.DRVQuery.ExecSQL(SQL, [ACaption], False,True) then
begin
while not BTCLDatabase.DRVQuery.Eof do
begin
if PosExtCI(ACaption, BTCLDatabase.DRVQuery.GetFieldStrValue(3), BegSub, EndSub) > 0 then
begin
DependenceDescr := TibBTDependenceDescr.Create;
DependenceDescr.ObjectType := BTCLDatabase.DRVQuery.GetFieldIntValue(0);
DependenceDescr.ObjectName := BTCLDatabase.DRVQuery.GetFieldStrValue(1);
DependenceDescr.FieldName := BTCLDatabase.DRVQuery.GetFieldStrValue(2);
FDependenceList.Add(DependenceDescr);
end;
BTCLDatabase.DRVQuery.Next;
end;
end;
if not BTCLDatabase.DRVDatabase.IsFirebirdConnect then
begin
SQL := FormatSQL(SQL_GET_FUNCTION_USED_BY3);
if BTCLDatabase.DRVQuery.ExecSQL(SQL, [ACaption], False,True) then
begin
while not BTCLDatabase.DRVQuery.Eof do
begin
if PosExtCI(ACaption, BTCLDatabase.DRVQuery.GetFieldStrValue(3), BegSub, EndSub) > 0 then
begin
DependenceDescr := TibBTDependenceDescr.Create;
DependenceDescr.ObjectType := BTCLDatabase.DRVQuery.GetFieldIntValue(0);
DependenceDescr.ObjectName := BTCLDatabase.DRVQuery.GetFieldStrValue(1);
DependenceDescr.FieldName := BTCLDatabase.DRVQuery.GetFieldStrValue(2);
FDependenceList.Add(DependenceDescr);
end;
BTCLDatabase.DRVQuery.Next;
end;
end;
end
end;
BTCLDatabase.DRVQuery.Transaction.Commit;
end;
function TibBTDependencies.IsEmpty: Boolean;
begin
Result := FDependenceList.Count = 0;
end;
function TibBTDependencies.GetObjectNames(const AClassIID: TGUID; AOwnerCaption: string = ''): TStrings;
var
I, J: Integer;
DependenceDescr: TibBTDependenceDescr;
begin
FResultList.Clear;
J := -1;
if IsEqualGUID(AClassIID, IibSHTable) then J := 0;
if IsEqualGUID(AClassIID, IibSHField) then J := 9;
if IsEqualGUID(AClassIID, IibSHDomain) then J := 9;
if IsEqualGUID(AClassIID, IibSHConstraint) then J := 4;
if IsEqualGUID(AClassIID, IibSHIndex) then J := 10;
if IsEqualGUID(AClassIID, IibSHView) then J := 1;
if IsEqualGUID(AClassIID, IibSHProcedure) then J := 5;
if IsEqualGUID(AClassIID, IibSHTrigger) then J := 2;
if IsEqualGUID(AClassIID, IibSHGenerator) then J := 14;
if IsEqualGUID(AClassIID, IibSHException) then J := 7;
if IsEqualGUID(AClassIID, IibSHFunction) then J := 15;
if IsEqualGUID(AClassIID, IibSHFilter) then J := 16;
for I := 0 to Pred(FDependenceList.Count) do
begin
DependenceDescr := TibBTDependenceDescr(FDependenceList[I]);
if DependenceDescr.ObjectType = J then
begin
if Length(AOwnerCaption) > 0 then
begin
if AnsiSameText(DependenceDescr.ObjectName, AOwnerCaption) and
(Length(Trim(DependenceDescr.FieldName)) > 0) then
if FResultList.IndexOf(DependenceDescr.FieldName) = -1 then
FResultList.Add(DependenceDescr.FieldName);
end else
begin
if FResultList.IndexOf(DependenceDescr.ObjectName) = -1 then
FResultList.Add(DependenceDescr.ObjectName);
end;
end;
end;
if FResultList.Count > 0 then TStringList(FResultList).Sort;
Result := FResultList;
end;
end.
|
unit InflatablesList_ItemShop_Update;
{$INCLUDE '.\InflatablesList_defs.inc'}
interface
uses
InflatablesList_ItemShop_Base;
const
// how many times to repeat update when it fails in certain ways
IL_LISTFILE_UPDATE_TRYCOUNT = 5;
type
TILItemShop_Update = class(TILItemShop_Base)
public
Function Update: Boolean; virtual;
end;
implementation
uses
InflatablesList_Types,
InflatablesList_Utils,
InflatablesList_ShopUpdater;
const
IL_RESULT_STRS: array[0..11] of String = (
'Success (%d bytes downloaded) - Avail: %d Price: %d',
'No item link',
'Insufficient search data',
'Download failed (code: %d)',
'Parsing failed (%s)',
'Search of available count failed',
'Search failed',
'Unable to obtain available count',
'Unable to obtain values',
'Failed - general error (%s)',
'Failed - unknown state (%d)',
'Success (untracked) - Avail: %d Price: %d');
//------------------------------------------------------------------------------
Function TILItemShop_Update.Update: Boolean;
var
Updater: TILShopUpdater;
UpdaterResult: TILShopUpdaterResult;
TryCounter: Integer;
begin
If not fUntracked then
begin
TryCounter := IL_LISTFILE_UPDATE_TRYCOUNT;
Result := False;
Updater := TILShopUpdater.Create(Self);
try
repeat
UpdaterResult := Updater.Run(fAltDownMethod);
case UpdaterResult of
ilurSuccess: begin
SetValues(IL_Format(IL_RESULT_STRS[0],
[Updater.DownloadSize,Updater.Available,Updater.Price]),
ilisurSuccess,Updater.Available,Updater.Price);
Result := True;
end;
ilurDownSuccess: Result := True; // do not change last result
ilurNoLink: SetValues(IL_RESULT_STRS[1],ilisurDataFail,0,0);
ilurNoData: SetValues(IL_RESULT_STRS[2],ilisurDataFail,0,0);
// when download fails, keep old price (assumes the item vent unavailable)
ilurFailDown: SetValues(IL_Format(IL_RESULT_STRS[3],[Updater.DownloadResultCode]),ilisurDownload,0,fPrice);
// when parsing fails, keep old values (assumes bad download or internal exception)
ilurFailParse: SetValues(IL_Format(IL_RESULT_STRS[4],[Updater.ErrorString]),ilisurParsing,fAvailable,fPrice);
// following assumes the item is unavailable
ilurFailAvailSearch: SetValues(IL_RESULT_STRS[5],ilisurSoftFail,0,Updater.Price);
// following assumes the item is unavailable, keep old price
ilurFailSearch: SetValues(IL_RESULT_STRS[6],ilisurHardFail,0,fPrice);
// following assumes the item is unavailable
ilurFailAvailValGet: SetValues(IL_RESULT_STRS[7],ilisurSoftFail,0,Updater.Price);
// following assumes the item is unavailable, keep old price
ilurFailValGet: SetValues(IL_RESULT_STRS[8],ilisurHardFail,0,fPrice);
// general fail, invalidate
ilurFail: SetValues(IL_Format(IL_RESULT_STRS[9],[Updater.ErrorString]),ilisurFatal,0,0);
else
SetValues(IL_Format(IL_RESULT_STRS[10],[Ord(UpdaterResult)]),ilisurFatal,0,0);
end;
Dec(TryCounter);
until (TryCounter <= 0) or not(UpdaterResult in [ilurFailDown,ilurFailParse]);
finally
Updater.Free;
end;
end
else
begin
SetValues(IL_Format(IL_RESULT_STRS[11],[fAvailable,fPrice]),ilisurMildSucc,fAvailable,fPrice);
Result := True;
end;
end;
end.
|
unit FrmSelectReport;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, ComCtrls, StdCtrls, Buttons, StrUtils;
type
TFMSelectReport = class(TForm)
pnlWork: TPanel;
pnlButton: TPanel;
lvFileList: TListView;
btnOk: TBitBtn;
btnCancel: TBitBtn;
p_path: TPanel;
procedure lvFileListDblClick(Sender: TObject);
private
{ Private declarations }
//ๆ็ดข็ฎๅฝไธ็ๆไปถ
function Get_PathFiles(Path, Filter: string; ContainSubDir: Boolean; var FileList: TStrings): Boolean;
//ๅๅพ็ญๆไปถ่ทฏๅพ
function Get_Spath(FileName, BasePath: string): string;
public
{ Public declarations }
end;
//้ๆฉๆฅ่กจๆจก็
function Select_Report(Path: string): string;
var
FMSelectReport: TFMSelectReport;
implementation
{$R *.dfm}
function Select_Report(Path: string): string;
var
FileList: TStrings;
i: Integer;
ListItem: TListItem;
begin
Result := '';
with TFMSelectReport.Create(nil) do
try
p_path.Caption:='่ทฏๅพ: '+Path;
if RightStr(Path, 1) <> '\' then Path := Path + '\';
FileList := TStringList.Create;
FileList.Clear;
Get_PathFiles(Path, '*.rls;*.rmf', False, FileList);
for i := 0 to FileList.Count - 1 do
begin
ListItem := lvFileList.Items.Add;
ListItem.Caption := IntToStr(i + 1);
ListItem.SubItems.Add(Get_Spath(FileList[i], Path));
end;
if lvFileList.Items.Count > 0 then
lvFileList.ItemIndex := 0;
if ShowModal = mrok then
begin
i := lvFileList.ItemIndex;
if i < 0 then Exit;
Result := Path + lvFileList.Items[i].SubItems[0];
end;
finally
FileList.Free;
Free;
end;
end;
{ TFMSelectReport }
function TFMSelectReport.Get_PathFiles(Path, Filter: string;
ContainSubDir: Boolean; var FileList: TStrings): Boolean;
var
SrRec: TSearchRec;
TemList: TStrings;
i: Integer;
begin
TemList := TStringList.Create;
TemList.Clear;
try
TemList.Delimiter := ';';
TemList.DelimitedText := Filter;
for i := 0 to TemList.Count - 1 do
begin
if RightStr(Path, 1)<>'\' then Path := Path + '\';
try
if SysUtils.FindFirst(Path + TemList[i],faAnyFile and (not faDirectory),SrRec) = 0 then
begin
FileList.Add(Path + SrRec.Name);
while (SysUtils.FindNext(SrRec)=0) do
FileList.Add(Path + SrRec.Name);
end;
finally
SysUtils.FindClose(SrRec);
end;
try
if (ContainSubDir)and(SysUtils.FindFirst(Path + '*', faDirectory, SrRec) = 0) then
begin
if (SrRec.Name<>'.')and(SrRec.Name<>'..') then
Get_PathFiles(Path + SrRec.Name, TemList[i], ContainSubDir, FileList);
while (SysUtils.FindNext(SrRec)=0) do
if (SrRec.Name<>'.')and(SrRec.Name<>'..') then
Get_PathFiles(Path + SrRec.Name, TemList[i], ContainSubDir, FileList);
end;
finally
SysUtils.FindClose(SrRec);
end;
end;
finally
TemList.Free;
end;
Result := True;
end;
function TFMSelectReport.Get_Spath(FileName, BasePath: string): string;
begin
Result := '';
if RightStr(BasePath, 1) <> '\' then BasePath := BasePath + '\';
Result := FileName;
Delete(Result, 1, Length(BasePath));
end;
procedure TFMSelectReport.lvFileListDblClick(Sender: TObject);
begin
Self.ModalResult := mrOk;
end;
end.
|
{-------------------------------------------------------------------------------
Copyright 2012-2018 Ethea S.r.l.
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.
-------------------------------------------------------------------------------}
/// <summary>
/// Regex support. Wraps TPerlRegEx in Delphi versions prior do Delphi XE.
/// </summary>
unit EF.RegEx;
{$I EF.Defines.inc}
interface
/// <summary>
/// Matches a string to a pattern. If the specified pattern includes a regex
/// introducer, the rest is interpreted as a regular expression, otherwise
/// the whole string is interpreted as a (optionally negated) pattern and
/// passed to StrMatchesEx. The regex introducer is either the string
/// 'REGEX:' (the function returns True if the string matches the expression)
/// or '~REGEX:' (the function returns True if the string DOESN'T match the
/// expression) at the beginning of the pattern.
/// </summary>
function StrMatchesPatternOrRegex(const AString, APatternOrRegex: string): Boolean;
/// <summary>
/// Simple regex pattern matching.
/// </summary>
function RegExMatches(const AString, APattern: string): Boolean;
implementation
uses
SysUtils, SyncObjs,
RegularExpressionsCore,
EF.StrUtils;
// Creating an instance of this component is costly, so we cache it.
var
_RegExEngine: TPerlRegEx;
_CriticalSection: TCriticalSection;
function GetRegExEngine: TPerlRegEx;
begin
if Assigned(_RegExEngine) then
Result := _RegExEngine
else
begin
_CriticalSection.Enter;
try
_RegExEngine := TPerlRegEx.Create;
Result := _RegExEngine;
finally
_CriticalSection.Enter;
end;
end;
end;
function RegExMatches(const AString, APattern: string): Boolean;
var
LEngine: TPerlRegEx;
begin
LEngine := GetRegExEngine;
{$IF CompilerVersion > 26}
LEngine.RegEx := APattern;
LEngine.Subject := AString;
{$ELSE}
LEngine.RegEx := UTF8Encode(APattern);
LEngine.Subject := UTF8Encode(AString);
{$IFEND}
Result := LEngine.Match;
end;
function RegExDoesntMatch(const AString, APattern: string): Boolean;
begin
Result := not RegExMatches(AString, APattern);
end;
function StrMatchesPatternOrRegex(const AString, APatternOrRegex: string): Boolean;
const
REGEX_INTRODUCER = 'REGEX:';
REGEX_NEGATED_INTRODUCER = '~REGEX:';
var
LPattern: string;
LMatchFunction: function(const AString, APattern: string): Boolean;
begin
LPattern := APatternOrRegex;
// Regexes are costly to process, so we only support them if explicitly
// declared.
if Pos(REGEX_INTRODUCER, LPattern) = 1 then
begin
LMatchFunction := RegExMatches;
Delete(LPattern, 1, Length(REGEX_INTRODUCER));
end
else if Pos(REGEX_NEGATED_INTRODUCER, LPattern) = 1 then
begin
LMatchFunction := RegExDoesntMatch;
Delete(LPattern, 1, Length(REGEX_NEGATED_INTRODUCER));
end
else
LMatchFunction := StrMatchesEx;
Result := LMatchFunction(AString, LPattern);
end;
initialization
_CriticalSection := TCriticalSection.Create;
finalization
FreeAndNil(_RegExEngine);
FreeAndNil(_CriticalSection);
end.
|
//
// Generated by JavaToPas v1.4 20140515 - 182714
////////////////////////////////////////////////////////////////////////////////
unit android.widget.ShareActionProvider;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.GraphicsContentViewText,
android.widget.ShareActionProvider_OnShareTargetSelectedListener,
android.view.SubMenu,
android.content.Intent;
type
JShareActionProvider = interface;
JShareActionProviderClass = interface(JObjectClass)
['{B6234388-64B8-4078-93C5-AA678307A45F}']
function _GetDEFAULT_SHARE_HISTORY_FILE_NAME : JString; cdecl; // A: $19
function hasSubMenu : boolean; cdecl; // ()Z A: $1
function init(context : JContext) : JShareActionProvider; cdecl; // (Landroid/content/Context;)V A: $1
function onCreateActionView : JView; cdecl; // ()Landroid/view/View; A: $1
procedure onPrepareSubMenu(subMenu : JSubMenu) ; cdecl; // (Landroid/view/SubMenu;)V A: $1
procedure setOnShareTargetSelectedListener(listener : JShareActionProvider_OnShareTargetSelectedListener) ; cdecl;// (Landroid/widget/ShareActionProvider$OnShareTargetSelectedListener;)V A: $1
procedure setShareHistoryFileName(shareHistoryFile : JString) ; cdecl; // (Ljava/lang/String;)V A: $1
procedure setShareIntent(shareIntent : JIntent) ; cdecl; // (Landroid/content/Intent;)V A: $1
property DEFAULT_SHARE_HISTORY_FILE_NAME : JString read _GetDEFAULT_SHARE_HISTORY_FILE_NAME;// Ljava/lang/String; A: $19
end;
[JavaSignature('android/widget/ShareActionProvider$OnShareTargetSelectedListener')]
JShareActionProvider = interface(JObject)
['{06BB6268-8057-4159-B262-BB58FF9FB490}']
function hasSubMenu : boolean; cdecl; // ()Z A: $1
function onCreateActionView : JView; cdecl; // ()Landroid/view/View; A: $1
procedure onPrepareSubMenu(subMenu : JSubMenu) ; cdecl; // (Landroid/view/SubMenu;)V A: $1
procedure setOnShareTargetSelectedListener(listener : JShareActionProvider_OnShareTargetSelectedListener) ; cdecl;// (Landroid/widget/ShareActionProvider$OnShareTargetSelectedListener;)V A: $1
procedure setShareHistoryFileName(shareHistoryFile : JString) ; cdecl; // (Ljava/lang/String;)V A: $1
procedure setShareIntent(shareIntent : JIntent) ; cdecl; // (Landroid/content/Intent;)V A: $1
end;
TJShareActionProvider = class(TJavaGenericImport<JShareActionProviderClass, JShareActionProvider>)
end;
const
TJShareActionProviderDEFAULT_SHARE_HISTORY_FILE_NAME = 'share_history.xml';
implementation
end.
|
{* ***** BEGIN LICENSE BLOCK *****
Copyright 2010 Sean B. Durkin
This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free
software being offered under a dual licensing scheme: LGPL3 or MPL1.1.
The contents of this file are subject to the Mozilla Public License (MPL)
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
Alternatively, you may redistribute it and/or modify it under the terms of
the GNU Lesser General Public License (LGPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
You should have received a copy of the Lesser GNU General Public License
along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>.
TurboPower LockBox 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. In relation to LGPL,
see the GNU Lesser General Public License for more details. In relation to MPL,
see the MPL License for the specific language governing rights and limitations
under the License.
The Initial Developer of the Original Code for TurboPower LockBox version 2
and earlier was TurboPower Software.
* ***** END LICENSE BLOCK ***** *}
unit uTPLb_3DES;
interface
uses
SysUtils, Classes, uTPLb_BlockCipher, uTPLb_StreamCipher;
type
T3DES = class( TInterfacedObject,
IBlockCipher, ICryptoGraphicAlgorithm)
private
function DisplayName: string; virtual;
function ProgId: string; virtual;
function Features: TAlgorithmicFeatureSet;
function DefinitionURL: string;
function WikipediaReference: string;
function GenerateKey( Seed: TStream): TSymetricKey; virtual;
function LoadKeyFromStream( Store: TStream): TSymetricKey; virtual;
function BlockSize: integer; virtual; // in units of bits. Must be a multiple of 8.
function KeySize: integer; virtual;
function SeedByteSize: integer; virtual; // Size that the input of the GenerateKey must be.
function MakeBlockCodec( Key: TSymetricKey): IBlockCodec; virtual;
function SelfTest_Key: TBytes; virtual;
function SelfTest_Plaintext: TBytes; virtual;
function SelfTest_Ciphertext: TBytes; virtual;
public
constructor Create; virtual;
end;
T3DES_KO1 = class( T3DES)
private
function DisplayName: string; override;
function ProgId: string; override;
function GenerateKey( Seed: TStream): TSymetricKey; override;
function LoadKeyFromStream( Store: TStream): TSymetricKey; override;
function KeySize: integer; override;
function SeedByteSize: integer; override;
function MakeBlockCodec( Key: TSymetricKey): IBlockCodec; override;
function SelfTest_Key: TBytes; override;
function SelfTest_Plaintext: TBytes; override;
function SelfTest_Ciphertext: TBytes; override;
end;
implementation
uses uTPLb_Constants, uTPLb_DES, uTPLb_I18n, uTPLb_StrUtils;
{ TDES }
type
T3DESKey = class( TSymetricKey)
protected
FNativeKey1, FNativeKey2: uint64;
FExpandedKey1, FExpandedKey2: TExpandedKey;
public
constructor Create( NativeKey1, NativeKey2: uint64);
constructor CreateFromStream( Store: TStream); virtual;
procedure SaveToStream( Stream: TStream); override;
procedure Burn; override;
end;
T3DESKey_KO1 = class( T3DESKey)
private
FNativeKey3: uint64;
FExpandedKey3: TExpandedKey;
public
constructor Create( NativeKey1, NativeKey2, NativeKey3: uint64);
constructor CreateFromStream( Store: TStream); override;
procedure SaveToStream( Stream: TStream); override;
procedure Burn; override;
end;
T3DESCodec = class( TInterfacedObject, IBlockCodec)
protected
FLockBoxKey: T3DESKey;
constructor Create( LockBoxKey1: T3DESKey);
procedure Encrypt_Block( Plaintext{in}, Ciphertext{out}: TMemoryStream); virtual;
procedure Decrypt_Block( Plaintext{out}, Ciphertext{in}: TMemoryStream); virtual;
procedure Reset; virtual;
procedure Burn; virtual;
end;
T3DESCodec_KO1 = class( T3DESCodec)
private
FLockBoxKey_KO1: T3DESKey_KO1;
constructor Create( LockBoxKey1: T3DESKey_KO1);
procedure Encrypt_Block( Plaintext{in}, Ciphertext{out}: TMemoryStream); override;
procedure Decrypt_Block( Plaintext{out}, Ciphertext{in}: TMemoryStream); override;
end;
function T3DES.BlockSize: integer;
begin
result := 64
end;
constructor T3DES.Create;
begin
end;
function T3DES.DefinitionURL: string;
begin
result := 'http://csrc.nist.gov/publications/drafts/800-67-rev1/SP-800-67-rev1-2_July-2011.pdf'
end;
function T3DES.DisplayName: string;
begin
result := '3DES (Keying option 2)'
end;
function T3DES.Features: TAlgorithmicFeatureSet;
begin
result := [afOpenSourceSoftware]
end;
function T3DES.GenerateKey( Seed: TStream): TSymetricKey;
var
SeedKey1, SeedKey2: uint64;
begin
Seed.ReadBuffer( SeedKey1, 8);
Seed.ReadBuffer( SeedKey2, 8);
result := T3DESKey.Create( SeedKey1, SeedKey2)
end;
function T3DES.KeySize: integer;
begin
result := 80
// Quote from wikipedia:
// Keying option 2 reduces the key size to 112 bits. However, this option
// is susceptible to certain chosen-plaintext or known-plaintext attacks
// and thus it is designated by NIST to have only 80 bits of security.
end;
function T3DES.LoadKeyFromStream( Store: TStream): TSymetricKey;
begin
result := T3DESKey.CreateFromStream( Store)
end;
function T3DES.MakeBlockCodec( Key: TSymetricKey): IBlockCodec;
begin
result := T3DESCodec.Create( Key as T3DESKey)
end;
function T3DES.ProgId: string;
begin
result := TripleDES_ProgId
end;
function T3DES.SeedByteSize: integer;
begin
result := 16
end;
//From the first line of the KAT table at: http://crypto.stackexchange.com/questions/926/does-anyone-have-a-kat-for-3des-ko-2/927#927
//<------------- key -------------> <-- plaintext -> <- ciphertext ->
//E62CABB93D1F3BDC 524FDF91A279C297 DD16B3D004069AB3 8ADDBD2290E565CE
function T3DES.SelfTest_Ciphertext: TBytes;
begin
result := AnsiBytesOf('8ADDBD2290E565CE');
end;
function T3DES.SelfTest_Key: TBytes;
begin
result := AnsiBytesOf('E62CABB93D1F3BDC 524FDF91A279C297')
end;
function T3DES.SelfTest_Plaintext: TBytes;
begin
result := AnsiBytesOf('DD16B3D004069AB3')
end;
function T3DES.WikipediaReference: string;
begin
result := 'Triple_DES'
end;
{ T3DESKey }
constructor T3DESKey.Create( NativeKey1, NativeKey2: uint64);
begin
FNativeKey1 := NativeKey1;
FNativeKey2 := NativeKey2;
SetParityBitsOnKey( FNativeKey1);
SetParityBitsOnKey( FNativeKey2);
ExpandKey( FNativeKey1, FExpandedKey1);
ExpandKey( FNativeKey2, FExpandedKey2)
end;
constructor T3DESKey.CreateFromStream( Store: TStream);
begin
Store.ReadBuffer( FNativeKey1, 8);
Store.ReadBuffer( FNativeKey2, 8);
if (not hasCorrectParity( FNativeKey1)) or
(not hasCorrectParity( FNativeKey2)) then
raise Exception.Create( ES_InvalidKey);
ExpandKey( FNativeKey1, FExpandedKey1);
ExpandKey( FNativeKey2, FExpandedKey2)
end;
procedure T3DESKey.SaveToStream( Stream: TStream);
begin
Stream.Write( FNativeKey1, 8);
Stream.Write( FNativeKey2, 8)
end;
procedure T3DESKey.Burn;
begin
FNativeKey1 := 0;
FillChar( FExpandedKey1, SizeOf( FExpandedKey1), 0);
FNativeKey2 := 0;
FillChar( FExpandedKey2, SizeOf( FExpandedKey2), 0)
end;
{ T3DESCodec }
constructor T3DESCodec.Create( LockBoxKey1: T3DESKey);
begin
FLockBoxKey := LockBoxKey1
end;
procedure T3DESCodec.Encrypt_Block( Plaintext, Ciphertext: TMemoryStream);
var
PlaintextBlock, CiphertextBlock: uint64;
begin
Move( Plaintext.Memory^, PlaintextBlock, 8);
DES_EncryptBlock( PlaintextBlock, CiphertextBlock, FLockBoxKey.FExpandedKey1);
DES_DecryptBlock( CiphertextBlock, PlaintextBlock, FLockBoxKey.FExpandedKey2);
DES_EncryptBlock( PlaintextBlock, CiphertextBlock, FLockBoxKey.FExpandedKey1);
Move( CiphertextBlock, Ciphertext.Memory^, 8)
end;
procedure T3DESCodec.Decrypt_Block( Plaintext, Ciphertext: TMemoryStream);
var
PlaintextBlock, CiphertextBlock: uint64;
begin
Move( Ciphertext.Memory^, CiphertextBlock, 8);
DES_DecryptBlock( CiphertextBlock, PlaintextBlock, FLockBoxKey.FExpandedKey1);
DES_EncryptBlock( PlaintextBlock, CiphertextBlock, FLockBoxKey.FExpandedKey2);
DES_DecryptBlock( CiphertextBlock, PlaintextBlock, FLockBoxKey.FExpandedKey1);
Move( PlaintextBlock, Plaintext.Memory^, 8)
end;
procedure T3DESCodec.Reset;
begin
end;
procedure T3DESCodec.Burn;
begin
end;
{ T3DES_KO1 }
function T3DES_KO1.DisplayName: string;
begin
result := '3DES (Keying option 1)'
end;
function T3DES_KO1.GenerateKey( Seed: TStream): TSymetricKey;
var
SeedKey1, SeedKey2, SeedKey3: uint64;
begin
Seed.ReadBuffer( SeedKey1, 8);
Seed.ReadBuffer( SeedKey2, 8);
Seed.ReadBuffer( SeedKey3, 8);
result := T3DESKey_KO1.Create( SeedKey1, SeedKey2, SeedKey3)
end;
function T3DES_KO1.KeySize: integer;
begin
result := 112
end;
function T3DES_KO1.LoadKeyFromStream( Store: TStream): TSymetricKey;
begin
result := T3DESKey_KO1.CreateFromStream( Store)
end;
function T3DES_KO1.MakeBlockCodec( Key: TSymetricKey): IBlockCodec;
begin
result := T3DESCodec_KO1.Create( Key as T3DESKey_KO1)
end;
function T3DES_KO1.ProgId: string;
begin
result := TripleDES_KO1_ProgId
end;
function T3DES_KO1.SeedByteSize: integer;
begin
result := 24
end;
// This test vector from section B1 of
// http://csrc.nist.gov/publications/drafts/800-67-rev1/SP-800-67-rev1-2_July-2011.pdf
function T3DES_KO1.SelfTest_Key: TBytes;
begin
result := AnsiBytesOf('0123456789ABCDEF 23456789ABCDEF01 456789ABCDEF0123');
end;
function T3DES_KO1.SelfTest_Plaintext: TBytes;
begin
result := AnsiBytesOf('5468652071756663');
end;
function T3DES_KO1.SelfTest_Ciphertext: TBytes;
begin
result := AnsiBytesOf('A826FD8CE53B855F');
end;
{ T3DESKey_KO1 }
procedure T3DESKey_KO1.Burn;
begin
inherited;
FNativeKey3 := 0;
FillChar( FExpandedKey3, SizeOf( FExpandedKey3), 0);
end;
constructor T3DESKey_KO1.Create( NativeKey1, NativeKey2, NativeKey3: uint64);
begin
inherited Create( NativeKey1, NativeKey2);
FNativeKey3 := NativeKey3;
SetParityBitsOnKey( FNativeKey3);
ExpandKey( FNativeKey3, FExpandedKey3)
end;
constructor T3DESKey_KO1.CreateFromStream( Store: TStream);
begin
inherited CreateFromStream( Store);
Store.ReadBuffer( FNativeKey3, 8);
if not hasCorrectParity( FNativeKey3) then
raise Exception.Create( ES_InvalidKey);
ExpandKey( FNativeKey3, FExpandedKey3)
end;
procedure T3DESKey_KO1.SaveToStream( Stream: TStream);
begin
inherited SaveToStream( Stream);
Stream.Write( FNativeKey3, 8)
end;
{ T3DESCodec_KO1 }
constructor T3DESCodec_KO1.Create( LockBoxKey1: T3DESKey_KO1);
begin
inherited Create( LockBoxKey1);
FLockBoxKey_KO1 := LockBoxKey1
end;
procedure T3DESCodec_KO1.Encrypt_Block( Plaintext, Ciphertext: TMemoryStream);
var
PlaintextBlock, CiphertextBlock: uint64;
begin
Move( Plaintext.Memory^, PlaintextBlock, 8);
DES_EncryptBlock( PlaintextBlock, CiphertextBlock, FLockBoxKey_KO1.FExpandedKey1);
DES_DecryptBlock( CiphertextBlock, PlaintextBlock, FLockBoxKey_KO1.FExpandedKey2);
DES_EncryptBlock( PlaintextBlock, CiphertextBlock, FLockBoxKey_KO1.FExpandedKey3);
Move( CiphertextBlock, Ciphertext.Memory^, 8)
end;
procedure T3DESCodec_KO1.Decrypt_Block( Plaintext, Ciphertext: TMemoryStream);
var
PlaintextBlock, CiphertextBlock: uint64;
begin
Move( Ciphertext.Memory^, CiphertextBlock, 8);
DES_DecryptBlock( CiphertextBlock, PlaintextBlock, FLockBoxKey_KO1.FExpandedKey3);
DES_EncryptBlock( PlaintextBlock, CiphertextBlock, FLockBoxKey_KO1.FExpandedKey2);
DES_DecryptBlock( CiphertextBlock, PlaintextBlock, FLockBoxKey_KO1.FExpandedKey1);
Move( PlaintextBlock, Plaintext.Memory^, 8)
end;
end.
|
{
Delphi Thread Unit by Aphex
http://iamaphex.cjb.net
unremote@knology.net
}
unit ThreadUnit;
interface
uses
Windows;
type
TThread = class
private
FHandle: THandle;
FThreadID: Cardinal;
FCreateSuspended: Boolean;
FTerminated: Boolean;
FSuspended: Boolean;
FFreeOnTerminate: Boolean;
FFinished: Boolean;
FReturnValue: Integer;
procedure SetSuspended(Value: Boolean);
protected
procedure Execute; virtual; abstract;
property Terminated: Boolean read FTerminated;
public
constructor Create(CreateSuspended: Boolean);
destructor Destroy; override;
procedure Resume;
procedure Suspend;
procedure Terminate;
property Handle: THandle read FHandle;
property Suspended: Boolean read FSuspended write SetSuspended;
property ThreadID: Cardinal read FThreadID;
end;
implementation
var
ThreadCount: integer;
SyncEvent: THandle;
ThreadLock: TRTLCriticalSection;
procedure InitThreadSynchronization;
begin
InitializeCriticalSection(ThreadLock);
SyncEvent := CreateEvent(nil, True, False, '');
end;
procedure DoneThreadSynchronization;
begin
DeleteCriticalSection(ThreadLock);
CloseHandle(SyncEvent);
end;
procedure SignalSyncEvent;
begin
SetEvent(SyncEvent);
end;
procedure AddThread;
begin
InterlockedIncrement(ThreadCount);
end;
procedure RemoveThread;
begin
InterlockedDecrement(ThreadCount);
end;
function ThreadProc(Thread: TThread): Integer;
var
FreeThread: Boolean;
begin
{$IFDEF LINUX}
if Thread.FSuspended then sem_wait(Thread.FCreateSuspendedSem);
{$ENDIF}
try
if not Thread.Terminated then
try
Thread.Execute;
except
end;
finally
FreeThread := Thread.FFreeOnTerminate;
Result := Thread.FReturnValue;
Thread.FFinished := True;
SignalSyncEvent;
if FreeThread then Thread.Free;
{$IFDEF MSWINDOWS}
EndThread(Result);
{$ENDIF}
{$IFDEF LINUX}
// Directly call pthread_exit since EndThread will detach the thread causing
// the pthread_join in TThread.WaitFor to fail. Also, make sure the EndThreadProc
// is called just like EndThread would do. EndThreadProc should not return
// and call pthread_exit itself.
if Assigned(EndThreadProc) then
EndThreadProc(Result);
pthread_exit(Pointer(Result));
{$ENDIF}
end;
end;
constructor TThread.Create(CreateSuspended: Boolean);
begin
inherited Create;
AddThread;
FSuspended := CreateSuspended;
FCreateSuspended := CreateSuspended;
FHandle := BeginThread(nil, 0, @ThreadProc, Pointer(Self), CREATE_SUSPENDED, FThreadID);
end;
destructor TThread.Destroy;
begin
if (FThreadID <> 0) and not FFinished then
begin
Terminate;
if FCreateSuspended then Resume;
end;
if FHandle <> 0 then CloseHandle(FHandle);
inherited Destroy;
RemoveThread;
end;
procedure TThread.SetSuspended(Value: Boolean);
begin
if Value <> FSuspended then
if Value then
Suspend
else
Resume;
end;
procedure TThread.Suspend;
var
OldSuspend: Boolean;
begin
OldSuspend := FSuspended;
try
FSuspended := True;
SuspendThread(FHandle);
except
FSuspended := OldSuspend;
raise;
end;
end;
procedure TThread.Resume;
var
SuspendCount: Integer;
begin
SuspendCount := ResumeThread(FHandle);
if SuspendCount = 1 then FSuspended := False;
end;
procedure TThread.Terminate;
begin
FTerminated := True;
end;
initialization
InitThreadSynchronization;
finalization
DoneThreadSynchronization;
end.
|
unit Forms.Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Actions, Vcl.ActnList, Vcl.StdCtrls, Vcl.ExtCtrls
, Server.WiRL
;
type
TFrmMain = class(TForm)
TopPanel: TPanel;
StartButton: TButton;
StopButton: TButton;
MainActionList: TActionList;
StartServerAction: TAction;
StopServerAction: TAction;
laPortNumber: TLabel;
edPortNumber: TEdit;
procedure FormShow(Sender: TObject);
procedure StartServerActionExecute(Sender: TObject);
procedure StopServerActionExecute(Sender: TObject);
procedure StartServerActionUpdate(Sender: TObject);
procedure StopServerActionUpdate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmMain: TFrmMain;
implementation
uses
Server.Configuration,
Server.Register,
Common.Entities.Card,
Common.Entities.GameType;
{$R *.dfm}
{======================================================================================================================}
procedure TFrmMain.FormShow(Sender: TObject);
{======================================================================================================================}
begin
edPortNumber.Text := GetContainer.Resolve<TConfiguration>.ServerPort.ToString;
end;
{======================================================================================================================}
procedure TFrmMain.StartServerActionExecute(Sender: TObject);
{======================================================================================================================}
var
serverREST: TServerREST;
begin
serverREST := GetContainer.Resolve<TServerREST>;
serverREST.Active := True;
Common.Entities.Card.Initialize;
Common.Entities.GameType.Initialize;
Caption := 'Server started';
end;
{======================================================================================================================}
procedure TFrmMain.StartServerActionUpdate(Sender: TObject);
{======================================================================================================================}
begin
// StartServerAction.Enabled := not Assigned(WorkerThread);
end;
{======================================================================================================================}
procedure TFrmMain.StopServerActionExecute(Sender: TObject);
{======================================================================================================================}
var
serverREST: TServerREST;
begin
serverREST := GetContainer.Resolve<TServerREST>;
serverREST.Active := False;
Common.Entities.Card.TearDown;
Common.Entities.GameType.TearDown;
Caption := 'Server stopped';
end;
{======================================================================================================================}
procedure TFrmMain.StopServerActionUpdate(Sender: TObject);
{======================================================================================================================}
begin
// StopServerAction.Enabled := Assigned(WorkerThread);
end;
initialization
ReportMemoryLeaksOnShutdown := True;
end.
|
unit Physics;
{$mode objfpc}{$H+}
interface
uses SysUtils;
// The approximate amount of points we want to calculate
const num_points_target = 400;
// The parameters required by the model
type Parameters = record
mass: double; // Mass in kg
impulse_force: double; // Initial force in N
impulse_time: double; // Time interval in s during which initial force was applied
initial_elevation: double; // Elevation of starting position in m
launch_angle: double; // Initial angle in rad
gravity: double; // Gravitational acceleration in m/s^2
surface_area: double; // Frontal surface area of object in m^2
drag_coefficient: double; // Drag coefficient (dimensionless constant)
air_density: double; // Air density in kg/m^3;
initial_velocity: double; // Initial velocity in m/s
drag_constant: double; // Calculated drag constant
time_interval: double; // Time interval between calculations
xmax: double; // Max x coordinate observed during calculations
ymax: double; // Max y coordinate observed during calculations
end;
type Point = record
// Position with air resistance
x: double;
y: double;
// Position without air resistance
nax: double;
nay: double;
end;
// An array containing the calculated trajectory
type Path = array of Point;
procedure InitPhysics(var p: Parameters);
procedure CalcTrajectory(var p: Parameters; var t: Path);
implementation
procedure InitPhysics(var p: Parameters);
var estimated_flight_time: double;
begin
p.initial_velocity := p.impulse_force * p.impulse_time / p.mass;
p.drag_constant := p.surface_area * p.drag_coefficient * p.air_density / 2;
estimated_flight_time := ( (p.initial_velocity * sin(p.launch_angle))
+ sqrt( sqr(p.initial_velocity * sin(p.launch_angle))
+ (2 * p.gravity * p.initial_elevation)
)
) / p.gravity;
p.time_interval := estimated_flight_time / num_points_target;
p.xmax := 0;
p.ymax := p.initial_elevation;
end;
procedure CalcTrajectory(var p: Parameters; var t: Path);
var x,y: double;
v, vx, vy: double;
ax, ay: double;
cur_point: integer;
drag_factor: double;
nax,nay: double;
navx, navy: double;
begin
// Initial position
x := 0;
y := p.initial_elevation;
nax := x;
nay := y;
// Initial velocity
v := p.initial_velocity;
vx := v * cos(p.launch_angle);
vy := v * sin(p.launch_angle);
navx := vx;
navy := vy;
drag_factor := p.drag_constant / p.mass;
// Initialize array of points
cur_point := 0;
SetLength(t, 100);
t[cur_point].x := x;
t[cur_point].y := y;
t[cur_point].nax := nax;
t[cur_point].nay := nay;
// Stop when both objects are on the ground
while ((y > 0) or (nay > 0)) do
begin
// Expand array if required
if cur_point >= High(t) then SetLength(t, Length(t) + 100);
// Determine acceleration
v := sqrt(sqr(vx) + sqr(vy));
ax := - v * vx * drag_factor;
ay := - p.gravity - v * vy * drag_factor;
// Determine new velocity
vx := vx + ax * p.time_interval;
vy := vy + ay * p.time_interval;
navy := navy - p.gravity * p.time_interval;
// Determine new position
x := x + vx * p.time_interval + 0.5 * ax * sqr(p.time_interval);
y := y + vy * p.time_interval + 0.5 * ay * sqr(p.time_interval);
if (y <= 0) then
begin
y := 0;
vx := 0;
vy := 0;
end;
nax := nax + navx * p.time_interval;
nay := nay + navy * p.time_interval - 0.5 * p.gravity * sqr(p.time_interval);
if (nay < 0) then
begin
nay := 0;
navx := 0;
navy := 0;
end;
// Store new position
inc(cur_point);
t[cur_point].x := x;
t[cur_point].y := y;
t[cur_point].nax := nax;
t[cur_point].nay := nay;
// Store max x and y seen so far
if (p.xmax < x) then p.xmax := x;
if (p.ymax < y) then p.ymax := y;
if (p.xmax < nax) then p.xmax := nax;
if (p.ymax < nay) then p.ymax := nay;
end;
// Trim array of points
SetLength(t, cur_point + 1);
end;
end.
|
unit Pospolite.View.Drawing.DrawerD2D1;
{
+-------------------------+
| Package: Pospolite View |
| Author: Matek0611 |
| Email: matiowo@wp.pl |
| Version: 1.0p |
+-------------------------+
Comments:
Some parts of the code are based on Codebot Pascal Library by Anthony Walter
https://github.com/sysrpl/Cross.Codebot/tree/master/source
}
{$mode objfpc}{$H+}
{$warnings off}
interface
uses
Windows, Classes, SysUtils, Graphics, Pospolite.View.Basics, Pospolite.View.Drawing.Basics,
Pospolite.View.Drawing.Drawer, Pospolite.View.Drawing.DrawerD2D1.Definitions,
math;
type
{ TPLD2D1Drawer }
TPLD2D1Drawer = class(TPLAbstractDrawer)
public
constructor Create(ACanvas: TCanvas); override;
destructor Destroy; override;
procedure DrawObjectBackground(const AObject: TPLHTMLObject); override;
procedure DrawObjectBorder(const AObject: TPLHTMLObject); override;
procedure DrawObjectOutline(const AObject: TPLHTMLObject); override;
procedure DrawObjectOutlineText(const AObject: TPLHTMLObject); override;
procedure DrawObjectText(const AObject: TPLHTMLObject); override;
procedure DrawObjectDebug(const AObject: TPLHTMLObject); override;
procedure DrawObjectShadow(const AObject: TPLHTMLObject); override;
procedure DrawObjectTextShadow(const AObject: TPLHTMLObject); override;
procedure DrawObjectPseudoBefore(const AObject: TPLHTMLObject); override;
procedure DrawObjectPseudoAfter(const AObject: TPLHTMLObject); override;
procedure DrawFrame(const ABorders: TPLDrawingBorders; const ARect: TPLRectF); override;
end;
var
PLD2D1Locale: WideString = 'en-us';
function NewDrawingMatrixD2D: IPLDrawingMatrix;
function NewDrawingPenD2D(ABrush: IPLDrawingBrush; AWidth: TPLFloat = 1): IPLDrawingPen;
overload;
function NewDrawingPenD2D(AColor: TPLColor; AWidth: TPLFloat = 1): IPLDrawingPen;
overload;
function NewDrawingSolidBrushD2D(AColor: TPLColor): IPLDrawingBrushSolid;
function NewDrawingBitmapBrushD2D(ABitmap: IPLDrawingBitmap): IPLDrawingBrushBitmap;
function NewDrawingLinearGradientBrushD2D(
const A, B: TPLPointF): IPLDrawingBrushGradientLinear;
function NewDrawingRadialGradientBrushD2D(
const ARect: TPLRectF): IPLDrawingBrushGradientRadial;
function NewDrawingFontD2D(AFontData: TPLDrawingFontData): IPLDrawingFont;
function NewDrawingSurfaceD2D(ACanvas: TCanvas): IPLDrawingSurface;
function NewDrawingBitmapD2D(AWidth, AHeight: TPLInt): IPLDrawingBitmap;
implementation
uses Forms;
operator := (c: TPLColor) r: TD3DColorValue;
begin
r.r := c.Red / 255;
r.g := c.Green / 255;
r.b := c.Blue / 255;
r.a := c.Alpha / 255;
end;
operator := (c: TD3DColorValue) r: TPLColor;
begin
r.Red := round(c.r * 255);
r.Green := round(c.g * 255);
r.Blue := round(c.b * 255);
r.Alpha := round(c.a * 255);
end;
operator := (p: TPLPointF) r: TD2D1Point2F;
begin
r.x := p.X;
r.y := p.Y;
end;
operator := (p: TD2D1Point2F) r: TPLPointF; inline;
begin
r := TPLPointF.Create(p.x, p.y);
end;
operator := (p: TPLRectF) r: TD2D1RectF;
begin
r.left := p.Left;
r.top := p.Top;
r.right := p.Right;
r.bottom := p.Bottom;
end;
operator := (p: TD2D1RectF) r: TPLRectF; inline;
begin
r := TPLRectF.Create(p.left, p.top, p.right - p.left, p.bottom - p.top);
end;
operator := (p: TPLRectI) r: TD2D1RectU;
begin
r.left := p.Left;
r.top := p.Top;
r.right := p.Right;
r.bottom := p.Bottom;
end;
type
{ TPLDrawingMatrixD2D }
TPLDrawingMatrixD2D = class(TInterfacedObject, IPLDrawingMatrix)
private
FMatrix: TD2DMatrix3X2F;
FChanged: TPLBool;
FIsIdentity: TPLBool;
public
constructor Create(const AMatrix: TD2DMatrix3X2F);
function Clone: IPLDrawingMatrix;
procedure Multiply(AMatrix: IPLDrawingMatrix);
procedure Scale(AX, AY: TPLFloat);
procedure Translate(AX, AY: TPLFloat);
function Transform(AP: TPLPointF): TPLPointF;
procedure Identify;
procedure Rotate(ARad: TPLFloat);
property Matrix: TD2DMatrix3x2F read FMatrix;
property Changed: TPLBool read FChanged;
property Identity: TPLBool read FIsIdentity;
end;
{ TPLDrawingPenD2D }
TPLDrawingPenD2D = class(TInterfacedObject, IPLDrawingPen)
private
FTarget: ID2D1RenderTarget;
FID: TPLInt;
FFill: ID2D1Brush;
FStyle: ID2D1StrokeStyle;
FBrush: IPLDrawingBrush;
FColor: TPLColor;
FWidth: TPLFloat;
FLineStyle: TPLDrawingPenStyle;
FLineStyleOffset: TPLFloat;
FLineCap: TPLDrawingPenEndCap;
FLineJoin: TPLDrawingPenJoinStyle;
FMiterLimit: TPLFloat;
function GetBrush: IPLDrawingBrush;
function GetColor: TPLColor;
function GetEndCap: TPLDrawingPenEndCap;
function GetJoinStyle: TPLDrawingPenJoinStyle;
function GetMiterLimit: TPLFloat;
function GetStyle: TPLDrawingPenStyle;
function GetStyleOffset: TPLFloat;
function GetWidth: TPLFloat;
procedure SetBrush(AValue: IPLDrawingBrush);
procedure SetColor(AValue: TPLColor);
procedure SetEndCap(AValue: TPLDrawingPenEndCap);
procedure SetJoinStyle(AValue: TPLDrawingPenJoinStyle);
procedure SetMiterLimit(AValue: TPLFloat);
procedure SetStyle(AValue: TPLDrawingPenStyle);
procedure SetStyleOffset(AValue: TPLFloat);
procedure SetWidth(AValue: TPLFloat);
protected
function Acquire(ATarget: ID2D1RenderTarget; AID: TPLInt): TPLBool;
function CurrentBrush: ID2D1Brush;
function HandleAvailable: TPLBool;
public
constructor Create(AB: IPLDrawingBrush; AW: TPLFloat); overload;
constructor Create(const AC: TPLColor; AW: TPLFloat); overload;
property Color: TPLColor read GetColor write SetColor;
property Width: TPLFloat read GetWidth write SetWidth;
property Brush: IPLDrawingBrush read GetBrush write SetBrush;
property Style: TPLDrawingPenStyle read GetStyle write SetStyle;
property EndCap: TPLDrawingPenEndCap read GetEndCap write SetEndCap;
property JoinStyle: TPLDrawingPenJoinStyle read GetJoinStyle write SetJoinStyle;
property StyleOffset: TPLFloat read GetStyleOffset write SetStyleOffset;
property MiterLimit: TPLFloat read GetMiterLimit write SetMiterLimit;
end;
{ TPLDrawingBrushD2D }
TPLDrawingBrushD2D = class(TInterfacedObject, IPLDrawingBrush)
private
FTarget: ID2D1RenderTarget;
FID: TPLInt;
FBrush: ID2D1Brush;
FMatrix: IPLDrawingMatrix;
FAlpha: Byte;
function GetAlpha: Byte;
function GetMatrix: IPLDrawingMatrix;
procedure SetAlpha(AValue: Byte);
procedure SetMatrix(AValue: IPLDrawingMatrix);
protected
function Acquire(ATarget: ID2D1RenderTarget; AID: TPLInt): TPLBool;
function HandleAvailable: TPLBool; virtual;
public
constructor Create;
property Alpha: Byte read GetAlpha write SetAlpha;
property Matrix: IPLDrawingMatrix read GetMatrix write SetMatrix;
end;
{ TPLDrawingBrushSolidD2D }
TPLDrawingBrushSolidD2D = class(TPLDrawingBrushD2D, IPLDrawingBrushSolid)
private
FColor: TPLColor;
function GetColor: TPLColor;
procedure SetColor(AValue: TPLColor);
protected
function HandleAvailable: TPLBool; override;
public
constructor Create(AC: TPLColor);
property Color: TPLColor read GetColor write SetColor;
end;
{ TPLDrawingGradientStopsD2D }
TPLDrawingGradientStopsD2D = specialize TPLList<TD2D1GradientStop>;
{ TPLDrawingBrushGradientD2D }
TPLDrawingBrushGradientD2D = class(TPLDrawingBrushD2D, IPLDrawingBrushGradient)
private
FCreated: TPLBool;
FMidPoint: TPLPointF;
FWrap: TPLDrawingBrushGradientWrap;
FStops: TPLDrawingGradientStopsD2D;
function GetWrap: TPLDrawingBrushGradientWrap;
procedure SetWrap(AValue: TPLDrawingBrushGradientWrap);
protected
function HandleAvailable: TPLBool; override;
public
constructor Create(AMiddle: TPLPointF);
destructor Destroy; override;
procedure AddStop(AColor: TPLColor; AOffset: TPLFloat);
property Wrap: TPLDrawingBrushGradientWrap read GetWrap write SetWrap;
end;
{ TPLDrawingBrushGradientLinearD2D }
TPLDrawingBrushGradientLinearD2D = class(TPLDrawingBrushGradientD2D, IPLDrawingBrushGradientLinear)
private
FA: TPLPointF;
FB: TPLPointF;
protected
function HandleAvailable: TPLBool; override;
public
constructor Create(const A, B: TPLPointF);
end;
{ TPLDrawingBrushGradientRadialD2D }
TPLDrawingBrushGradientRadialD2D = class(TPLDrawingBrushGradientD2D, IPLDrawingBrushGradientRadial)
private
FRect: TPLRectF;
protected
function HandleAvailable: TPLBool; override;
public
constructor Create(const R: TPLRectF);
end;
{ TPLDrawingBrushBitmapD2D }
TPLDrawingBrushBitmapD2D = class(TPLDrawingBrushD2D, IPLDrawingBrushBitmap)
private
FBitmap: IPLDrawingBitmap;
protected
function HandleAvailable: TPLBool; override;
public
constructor Create(B: IPLDrawingBitmap);
end;
{ TPLDrawingFontD2D }
TPLDrawingFontD2D = class(TInterfacedObject, IPLDrawingFont)
private
FFormat: IDWriteTextFormat;
FData: TPLDrawingFontData;
function GetColor: TPLColor;
function GetDecoration: TPLDrawingFontDecorations;
function GetName: TPLString;
function GetQuality: TFontQuality;
function GetSize: TPLFloat;
function GetStretch: TPLDrawingFontStretch;
function GetStyle: TPLDrawingFontStyle;
function GetVariantTags: TPLDrawingFontVariantTags;
function GetWeight: TPLDrawingFontWeight;
procedure SetColor(AValue: TPLColor);
procedure SetDecoration(AValue: TPLDrawingFontDecorations);
procedure SetName(AValue: TPLString);
procedure SetQuality(AValue: TFontQuality);
procedure SetSize(AValue: TPLFloat);
procedure SetStretch(AValue: TPLDrawingFontStretch);
procedure SetStyle(AValue: TPLDrawingFontStyle);
procedure SetVariantTags(AValue: TPLDrawingFontVariantTags);
procedure SetWeight(AValue: TPLDrawingFontWeight);
function Format: IDWriteTextFormat;
public
constructor Create(AFontData: TPLDrawingFontData);
property Name: TPLString read GetName write SetName;
property Color: TPLColor read GetColor write SetColor;
property Quality: TFontQuality read GetQuality write SetQuality;
property Size: TPLFloat read GetSize write SetSize;
property Weight: TPLDrawingFontWeight read GetWeight write SetWeight;
property Style: TPLDrawingFontStyle read GetStyle write SetStyle;
property Stretch: TPLDrawingFontStretch read GetStretch write SetStretch;
property Decoration: TPLDrawingFontDecorations read GetDecoration write SetDecoration;
property VariantTags: TPLDrawingFontVariantTags read GetVariantTags write SetVariantTags;
end;
{ TPLDrawingPathDataD2D }
TPLDrawingPathDataD2D = class(TInterfacedObject, IPLDrawingPathData)
private
FPath: ID2D1Geometry;
public
constructor Create(APath: ID2D1Geometry);
end;
TPLDrawingSurfaceD2D = class;
TPLD2D1GeometryList = specialize TPLList<ID2D1Geometry>;
{ TPLDrawingSurfacePathD2D }
TPLDrawingSurfacePathD2D = class(TInterfacedObject, IPLDrawingPath)
private
FSurface: TPLDrawingSurfaceD2D;
FClipStack: TPLD2D1GeometryList;
FClipHeight: Integer;
FData: TPLD2D1GeometryList;
FFigure: ID2D1PathGeometry;
FFigureSink: ID2D1GeometrySink;
FFigureOrigin: TD2DPoint2f;
FFigureOpened: Boolean;
function ClipStack: TPLD2D1GeometryList;
protected
function HandleAvailable: TPLBool;
procedure Open; overload;
procedure Open(X, Y: TPLFloat); overload;
procedure SaveClipStack;
procedure RestoreClipStack;
public
constructor Create(AC: TPLDrawingSurfaceD2D);
destructor Destroy; override;
function Clone: IPLDrawingPathData;
procedure Add; overload;
procedure Add(G: ID2D1Geometry); overload;
procedure Clip;
procedure JoinData(APath: IPLDrawingPathData);
procedure Remove;
procedure Unclip;
end;
{ TPLDrawingSurfaceStateD2D }
TPLDrawingSurfaceStateD2D = class
public
ClipStack: TPLD2D1GeometryList;
Data: TPLD2D1GeometryList;
Matrix: IPLDrawingMatrix;
constructor Create(C: TPLDrawingSurfaceD2D);
destructor Destroy; override;
procedure Restore(C: TPLDrawingSurfaceD2D);
end;
{ TPLDrawingSurfaceStateD2DList }
TPLDrawingSurfaceStateD2DList = specialize TPLObjectList<TPLDrawingSurfaceStateD2D>;
{ TPLDrawingSurfaceD2D }
TPLDrawingSurfaceD2D = class(TInterfacedObject, IPLDrawingSurface)
private
FTarget: ID2D1RenderTarget;
FID: TPLInt;
FPath: IPLDrawingPath;
FMatrix: IPLDrawingMatrix;
FStateStack: TPLDrawingSurfaceStateD2DList;
FDrawing: TPLBool;
function GetHandle: Pointer;
function GetMatrix: IPLDrawingMatrix;
function GetPath: IPLDrawingPath;
procedure SetMatrix(AValue: IPLDrawingMatrix);
function Path: TPLDrawingSurfacePathD2D;
function Matrix: TPLDrawingMatrixD2D;
procedure Draw;
protected
procedure AcquireTarget(Target: ID2D1RenderTarget);
function AcquireBrush(Brush: IPLDrawingBrush; out B: ID2D1Brush): TPLBool;
function AcquirePen(Pen: IPLDrawingPen; out B: ID2D1Brush; out S: ID2D1StrokeStyle): TPLBool;
function HandleAvailable: TPLBool; virtual;
procedure HandleRelease; virtual;
public
constructor Create(T: ID2D1RenderTarget);
destructor Destroy; override;
procedure ShareRelease; virtual;
procedure Save;
procedure Restore;
procedure Flush; virtual;
procedure Clear(const AColor: TPLColor);
procedure MoveTo(const AX, AY: TPLFloat);
procedure LineTo(const AX, AY: TPLFloat);
procedure ArcTo(const ARect: TPLRectF; const ABeginAngle, AEndAngle: TPLFloat);
procedure CurveTo(const AX, AY: TPLFloat; const AC1, AC2: TPLPointF);
procedure Ellipse(const ARect: TPLRectF);
procedure Rectangle(const ARect: TPLRectF);
procedure RoundRectangle(const ARect: TPLRectF; const ARadius: TPLFloat);
procedure FillOrStroke(ABrush: IPLDrawingBrush; APen: IPLDrawingPen; APreserve: TPLBool);
procedure Stroke(APen: IPLDrawingPen; const APreserve: TPLBool = false);
procedure Fill(ABrush: IPLDrawingBrush; const APreserve: TPLBool = false);
function TextSize(AFont: IPLDrawingFont; const AText: string;
const ALineSpacing: single = NaN; const AWordWrap: boolean = true;
const AWritingMode: TPLWritingMode = wmHorizontalTB;
const AReading: TPLReadingDirection = rdLTR): TPLPointF;
function TextHeight(AFont: IPLDrawingFont; const AText: string; const AWidth: TPLFloat;
const ALineSpacing: single = NaN; const AWordWrap: boolean = true;
const AWritingMode: TPLWritingMode = wmHorizontalTB;
const AReading: TPLReadingDirection = rdLTR): TPLFloat;
procedure TextOut(AFont: IPLDrawingFont; const AText: string; const ARect: TPLRectF;
const ADirection: TPLTextDirections; const ALineSpacing: single = NaN;
const AWordWrap: boolean = true; const AWritingMode: TPLWritingMode = wmHorizontalTB;
const AReading: TPLReadingDirection = rdLTR; const AImmediate: TPLBool = true);
property Handle: Pointer read GetHandle;
//property Matrix: IPLDrawingMatrix read GetMatrix write SetMatrix;
//property Path: IPLDrawingPath read GetPath;
end;
{ IPLSharedBitmapTargetD2D }
IPLSharedBitmapTargetD2D = interface
['{0959D148-21A8-4A20-9EAB-2503BB6C3A9F}']
function ShareCreate(Target: ID2D1RenderTarget): ID2D1Bitmap;
procedure ShareRelease;
end;
TPLDrawingBitmapD2D = class;
{ TPLDrawingBitmapSurfaceD2D }
TPLDrawingBitmapSurfaceD2D = class(TPLDrawingSurfaceD2D, IPLSharedBitmapTargetD2D)
private
FBitmap: TPLDrawingBitmapD2D;
FSurfaceBitmap: ID2D1Bitmap;
FSharedTarget: ID2D1RenderTarget;
FSharedBitmap: ID2D1Bitmap;
protected
function HandleAvailable: TPLBool; override;
procedure HandleRelease; override;
public
constructor Create(B: TPLDrawingBitmapD2D);
function ShareCreate(Target: ID2D1RenderTarget): ID2D1Bitmap;
procedure ShareRelease; override;
end;
{ TPLDrawingBitmapD2D }
TPLDrawingBitmapD2D = class(TPLDrawingInterfacedBitmap)
protected
procedure HandleRelease; override;
function GetSurface: IPLDrawingSurface; override;
function GetPixels: PPLPixel; override;
public
destructor Destroy; override;
procedure Clear; override;
end;
//TPLDrawingText
{ Matrix math }
const
MatrixIdentity: TD2DMatrix3X2F = (
m11: 1; m12: 0; m21: 0; m22: 1; m31: 0; m32: 0);
function MatrixMultiply(const A, B: TD2DMatrix3X2F): TD2DMatrix3X2F;
begin
with Result do
begin
m11 := A.m11 * B.m11 + A.m12 * B.m21;
m12 := A.m11 * B.m12 + A.m12 * B.m22;
m21 := A.m21 * B.m11 + A.m22 * B.m21;
m22 := A.m21 * B.m12 + A.m22 * B.m22;
m31 := A.m31 * B.m11 + A.m32 * B.m21 + B.m31;
m32 := A.m31 * B.m12 + A.m32 * B.m22 + B.m32;
end;
end;
procedure MatrixTranslate(var M: TD2DMatrix3X2F; X, Y: TPLFloat);
var
T: TD2DMatrix3X2F;
begin
with T do
begin
m11 := 1;
m12 := 0;
m21 := 0;
m22 := 1;
m31 := X;
m32 := Y;
end;
M := MatrixMultiply(M, T);
end;
procedure MatrixRotate(var M: TD2DMatrix3X2F; A: single);
var
C: TD2D1Point2F;
R: TD2DMatrix3X2F;
begin
C.x := 0;
C.y := 0;
D2D1MakeRotateMatrix(A / Pi * 180, C, @R);
M := MatrixMultiply(M, R);
end;
procedure MatrixScale(var M: TD2DMatrix3X2F; X, Y: TPLFloat);
var
S: TD2DMatrix3X2F;
begin
with S do
begin
m11 := X;
m12 := 0;
m21 := 0;
m22 := Y;
m31 := 0;
m32 := 0;
end;
M := MatrixMultiply(M, S);
end;
{ Direct2D helper routines }
var
RenderFactoryInstance: ID2D1Factory;
WriteFactoryInstance: IDWriteFactory;
function RenderFactory: ID2D1Factory;
begin
if RenderFactoryInstance = nil then
D2D1CreateFactory(D2D1_FACTORY_TYPE_MULTI_THREADED, IID_ID2D1Factory, nil,
RenderFactoryInstance);
Result := RenderFactoryInstance;
end;
function WriteFactory: IDWriteFactory;
begin
if WriteFactoryInstance = nil then
DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, IDWriteFactory,
WriteFactoryInstance);
Result := WriteFactoryInstance;
end;
{ RenderFactory object creation routines }
function DefaultPixelFormat: TD2D1PixelFormat;
begin
Result.format := DXGI_FORMAT_B8G8R8A8_UNORM;
Result.alphaMode := D2D1_ALPHA_MODE_PREMULTIPLIED;
end;
function DefaultRenderTargetProperties: TD2D1RenderTargetProperties;
begin
Result._type := D2D1_RENDER_TARGET_TYPE_DEFAULT;
Result.pixelFormat := DefaultPixelFormat;
Result.dpiX := 0;
Result.dpiY := 0;
Result.usage := D2D1_RENDER_TARGET_USAGE_GDI_COMPATIBLE;
Result.minLevel := D2D1_FEATURE_LEVEL_DEFAULT;
end;
function CreateDCTarget: ID2D1DCRenderTarget;
var
Prop: TD2D1RenderTargetProperties;
begin
Prop := DefaultRenderTargetProperties;
RenderFactory.CreateDCRenderTarget(Prop, Result);
end;
function CreateWndTarget(Wnd: HWND; out Rect: TRect): ID2D1HwndRenderTarget;
var
Prop: TD2D1HwndRenderTargetProperties;
begin
Rect := TRect.Empty;
Result := nil;
if not IsWindow(Wnd) then exit;
GetClientRect(Wnd, Rect);
Rect.Right := Rect.Right;
Rect.Bottom := Rect.Bottom;
Prop.hwnd := Wnd;
Prop.pixelSize.Width := Rect.Right - Rect.Left;
Prop.pixelSize.Height := Rect.Bottom - Rect.Top;
Prop.presentOptions := D2D1_PRESENT_OPTIONS_NONE;
RenderFactory.CreateHwndRenderTarget(DefaultRenderTargetProperties, Prop, Result);
end;
function CreateBitmap(Target: ID2D1RenderTarget; Width, Height: integer;
Bits: Pointer = nil): ID2D1Bitmap;
var
Size: TD2DSizeU;
Stride: cardinal;
Prop: TD2D1BitmapProperties;
begin
Result := nil;
if (Width < 1) or (Height < 1) then exit;
Size.Width := Width;
Size.Height := Height;
Stride := Width * SizeOf(TPLColor);
Prop.pixelFormat := DefaultPixelFormat;
Prop.dpiX := 0;
Prop.dpiY := 0;
Target.CreateBitmap(Size, Bits, Stride, Prop, Result);
end;
function CreateSharedBitmap(Target: ID2D1RenderTarget; Bitmap: ID2D1Bitmap): ID2D1Bitmap;
var
Prop: TD2D1BitmapProperties;
begin
Prop.pixelFormat := DefaultPixelFormat;
Prop.dpiX := 0;
Prop.dpiY := 0;
Target.CreateSharedBitmap(ID2D1Bitmap, Pointer(Bitmap), @Prop, Result);
end;
function CreatePenStyle(Pen: IPLDrawingPen): ID2D1StrokeStyle;
const
Caps: array[TPLDrawingPenEndCap] of D2D1_CAP_STYLE =
(D2D1_CAP_STYLE_FLAT, D2D1_CAP_STYLE_SQUARE, D2D1_CAP_STYLE_ROUND,
D2D1_CAP_STYLE_TRIANGLE);
Joins: array[TPLDrawingPenJoinStyle] of D2D1_LINE_JOIN =
(D2D1_LINE_JOIN_MITER, D2D1_LINE_JOIN_BEVEL, D2D1_LINE_JOIN_ROUND);
Dashes: array[TPLDrawingPenStyle] of D2D1_DASH_STYLE =
(D2D1_DASH_STYLE_SOLID, D2D1_DASH_STYLE_DASH,
D2D1_DASH_STYLE_DOT, D2D1_DASH_STYLE_DASH_DOT, D2D1_DASH_STYLE_DASH_DOT_DOT,
D2D1_DASH_STYLE_CUSTOM);
var
Prop: TD2D1StrokeStyleProperties;
begin
Prop.startCap := Caps[Pen.EndCap];
Prop.endCap := Prop.startCap;
if (Pen.Style = dpsDot) and (Pen.EndCap = dpecFlat) then
Prop.dashCap := D2D1_CAP_STYLE_SQUARE
else
Prop.dashCap := Prop.startCap;
Prop.lineJoin := Joins[Pen.JoinStyle];
Prop.miterLimit := Pen.MiterLimit;
Prop.dashStyle := Dashes[Pen.Style];
Prop.dashOffset := Pen.StyleOffset;
RenderFactory.CreateStrokeStyle(Prop, nil, 0, Result);
end;
function CreateSolidBrush(Target: ID2D1RenderTarget; const C: TPLColor;
Opacity: byte): ID2D1SolidColorBrush;
var
Prop: TD2D1BrushProperties;
begin
Prop.opacity := Opacity / $FF;
Prop.transform := MatrixIdentity;
Target.CreateSolidColorBrush(C, @Prop, Result);
end;
function CreateLinearGradientBrush(Target: ID2D1RenderTarget;
const A, B: TPLPointF; Opacity: byte; const Stops: TPLDrawingGradientStopsD2D;
Wrap: TPLDrawingBrushGradientWrap): ID2D1LinearGradientBrush;
const
Wraps: array[TPLDrawingBrushGradientWrap] of TD2D1ExtendMode =
(D2D1_EXTEND_MODE_CLAMP, D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_MIRROR);
EmptyStops: TD2D1GradientStop = ();
var
LineProp: TD2D1LinearGradientBrushProperties;
BrushProp: TD2D1BrushProperties;
Collection: ID2D1GradientStopCollection;
Gamma: TD2D1Gamma;
S: Pointer;
I: integer;
begin
LineProp.startPoint := A;
LineProp.endPoint := B;
BrushProp.opacity := Opacity / $FF;
BrushProp.transform := MatrixIdentity;
if Stops.Empty then
begin
S := @EmptyStops;
I := 1;
end
else
begin
S := Stops.Data;
I := Stops.Count;
end;
Gamma := D2D1_GAMMA_2_2;
Target.CreateGradientStopCollection(S, I, Gamma, Wraps[Wrap], Collection);
Target.CreateLinearGradientBrush(LineProp, @BrushProp, Collection, Result);
end;
function CreateRadialGradientBrush(Target: ID2D1RenderTarget;
const Rect: TPLRectF; Opacity: byte; const Stops: TPLDrawingGradientStopsD2D;
Wrap: TPLDrawingBrushGradientWrap): ID2D1RadialGradientBrush;
const
Wraps: array[TPLDrawingBrushGradientWrap] of TD2D1ExtendMode =
(D2D1_EXTEND_MODE_CLAMP, D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_MIRROR);
EmptyStops: TD2D1GradientStop = ();
Offset: TD2D1Point2F = ();
var
RadProp: TD2D1RadialGradientBrushProperties;
BrushProp: TD2D1BrushProperties;
Collection: ID2D1GradientStopCollection;
Gamma: TD2D1Gamma;
S: Pointer;
I: integer;
begin
RadProp.center := Rect.Middle;
RadProp.gradientOriginOffset := Offset;
RadProp.radiusX := Rect.Width / 2;
RadProp.radiusY := Rect.Height / 2;
BrushProp.opacity := Opacity / $FF;
BrushProp.transform := MatrixIdentity;
if Stops.Empty then
begin
S := @EmptyStops;
I := 1;
end
else
begin
S := Stops.Data;
I := Stops.Count;
end;
Gamma := D2D1_GAMMA_2_2;
Target.CreateGradientStopCollection(S, I, Gamma, Wraps[Wrap], Collection);
Target.CreateRadialGradientBrush(RadProp, @BrushProp, Collection, Result);
end;
function CreateBitmapBrush(Target: ID2D1RenderTarget; Bitmap: IPLDrawingBitmap;
Opacity: byte): ID2D1BitmapBrush;
var
BitTarget: ID2D1Bitmap;
BitProp: TD2D1BitmapBrushProperties;
BrushProp: TD2D1BrushProperties;
begin
if Bitmap.Empty then
Exit(nil);
BitTarget := CreateBitmap(Target, Bitmap.Width, Bitmap.Height, Bitmap.Pixels);
BitProp.extendModeX := D2D1_EXTEND_MODE_WRAP;
BitProp.extendModeY := D2D1_EXTEND_MODE_WRAP;
BitProp.interpolationMode := D2D1_BITMAP_INTERPOLATION_MODE_LINEAR;
BrushProp.opacity := Opacity / $FF;
BrushProp.transform := MatrixIdentity;
Target.CreateBitmapBrush(BitTarget, @BitProp, @BrushProp, Result);
end;
function CreateFigure: ID2D1PathGeometry;
begin
RenderFactory.CreatePathGeometry(Result);
end;
function CreateEllispe(const Rect: TPLRectF): ID2D1EllipseGeometry;
var
E: TD2D1Ellipse;
begin
E.point := Rect.Middle;
E.radiusX := Rect.Width / 2;
E.radiusY := Rect.Height / 2;
RenderFactory.CreateEllipseGeometry(E, Result);
end;
function CreateRectangle(const Rect: TPLRectF): ID2D1RectangleGeometry;
begin
RenderFactory.CreateRectangleGeometry(Rect, Result);
end;
function CreateRoundRectangle(const Rect: TPLRectF;
Radius: TPLFloat): ID2D1RoundedRectangleGeometry;
var
R: TD2D1RoundedRect;
begin
R.rect := Rect;
if Rect.Width < Radius * 2 then
Radius := Rect.Width / 2;
if Rect.Height < Radius * 2 then
Radius := Rect.Height / 2;
R.radiusX := Radius;
R.radiusY := Radius;
RenderFactory.CreateRoundedRectangleGeometry(R, Result);
end;
function CreateTransformed(G: ID2D1Geometry; Matrix: IPLDrawingMatrix): ID2D1Geometry;
var
M: TPLDrawingMatrixD2D;
T: ID2D1TransformedGeometry;
begin
if Matrix is TPLDrawingMatrixD2D then
begin
M := Matrix as TPLDrawingMatrixD2D;
if TPLDrawingMatrixD2D(M).Identity then
Result := G
else
begin
RenderFactory.CreateTransformedGeometry(G, TPLDrawingMatrixD2D(M).Matrix, T);
Result := T;
end;
end
else
Result := G;
end;
function CreateGroup(G: PID2D1Geometry; Count: integer): ID2D1GeometryGroup;
begin
if Count < 1 then
Count := 0;
RenderFactory.CreateGeometryGroup(D2D1_FILL_MODE_WINDING, G, Count, Result);
end;
function CreateLayerParameters(G: ID2D1Geometry): TD2D1LayerParameters;
const
InfiniteRect: TD2D1RectF =
(left: -$400000; top: -$400000;
right: $800000; bottom: $800000);
begin
with Result do
begin
contentBounds := InfiniteRect;
geometricMask := G;
maskAntialiasMode := D2D1_ANTIALIAS_MODE_PER_PRIMITIVE;
maskTransform := MatrixIdentity;
opacity := 1;
opacityBrush := nil;
layerOptions := D2D1_LAYER_OPTIONS_NONE;
end;
end;
{ WriteFactory object creation routines }
function CreateTextFormat(Font: IPLDrawingFont): IDWriteTextFormat;
const
Factor = 96 / 72;//72 / 96;
Weight: array[TPLDrawingFontWeight] of DWRITE_FONT_WEIGHT =
(DWRITE_FONT_WEIGHT_THIN, DWRITE_FONT_WEIGHT_EXTRA_LIGHT, DWRITE_FONT_WEIGHT_LIGHT,
DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_WEIGHT_MEDIUM, DWRITE_FONT_WEIGHT_SEMI_BOLD,
DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_WEIGHT_EXTRA_BOLD, DWRITE_FONT_WEIGHT_BLACK
);
Style: array[TPLDrawingFontStyle] of DWRITE_FONT_STYLE =
(DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STYLE_ITALIC, DWRITE_FONT_STYLE_OBLIQUE);
Stretch: array[TPLDrawingFontStretch] of DWRITE_FONT_STRETCH =
(DWRITE_FONT_STRETCH_ULTRA_CONDENSED, DWRITE_FONT_STRETCH_EXTRA_CONDENSED,
DWRITE_FONT_STRETCH_CONDENSED, DWRITE_FONT_STRETCH_SEMI_CONDENSED,
DWRITE_FONT_STRETCH_NORMAL, DWRITE_FONT_STRETCH_SEMI_EXPANDED,
DWRITE_FONT_STRETCH_EXPANDED, DWRITE_FONT_STRETCH_EXTRA_EXPANDED,
DWRITE_FONT_STRETCH_ULTRA_EXPANDED
);
var
Size: TPLFloat;
Name: WideString;
begin
Size := Font.Size * Factor * (Screen.PixelsPerInch / 96);
Name := Font.Name;
if WriteFactory.CreateTextFormat(PWideChar(Name), nil, Weight[Font.Weight],
Style[Font.Style], Stretch[Font.Stretch], Size, PWideChar(PLD2D1Locale),
Result) <> S_OK then
Result := nil;
end;
function CreateTextLayout(Format: IDWriteTextFormat; const Text: string;
Width, Height: TPLFloat): IDWriteTextLayout;
var
S: WideString;
begin
if Format = nil then
Result := nil;
S := Text;
if WriteFactory.CreateTextLayout(PWideChar(S), Length(S), Format,
Width, Height, Result) <> S_OK then
Result := nil;
end;
function CreateGdiTextLayout(Format: IDWriteTextFormat; const Text: string;
Width, Height: TPLFloat): IDWriteTextLayout;
var
S: WideString;
begin
if Format = nil then
Result := nil;
S := Text;
if WriteFactory.CreateGdiCompatibleTextLayout(PWideChar(S), Length(S),
Format, Width, Height, 1, nil, True, Result) <> S_OK then
Result := nil;
end;
function CreateFontTypography(const AFont: IPLDrawingFont): IDWriteTypography;
var
typg: IDWriteTypography absolute Result;
function ApplyTag(const ATag: TPLDrawingFontVariantTag; const ACode: DWORD;
const AParameter: Cardinal = 1): TPLBool;
var
f: TDWriteFontFeature;
begin
Result := ATag in AFont.VariantTags;
if Result then begin
f.parameter := AParameter;
f.nameTag := ACode;
Result := typg.AddFontFeature(f) = S_OK;
end;
end;
begin
Result := nil;
if AFont.VariantTags = [] then exit;
if WriteFactory.CreateTypography(Result) <> S_OK then Result := nil;
if not Assigned(Result) then exit;
if not ApplyTag(dfvtCapsSmall, DWRITE_FONT_FEATURE_TAG_SMALL_CAPITALS) then
if not ApplyTag(dfvtCapsAllSmall, DWRITE_FONT_FEATURE_TAG_SMALL_CAPITALS_FROM_CAPITALS) then
if not ApplyTag(dfvtCapsPetite, DWRITE_FONT_FEATURE_TAG_PETITE_CAPITALS) then
if not ApplyTag(dfvtCapsAllPetite, DWRITE_FONT_FEATURE_TAG_PETITE_CAPITALS_FROM_CAPITALS) then
if not ApplyTag(dfvtUnicase, DWRITE_FONT_FEATURE_TAG_UNICASE) then
ApplyTag(dfvtCapsTitling, DWRITE_FONT_FEATURE_TAG_TITLING);
ApplyTag(dfvtKerningNone, DWRITE_FONT_FEATURE_TAG_KERNING, 0);
ApplyTag(dfvtEastAsianRuby, DWRITE_FONT_FEATURE_TAG_RUBY_NOTATION_FORMS);
if not ApplyTag(dfvtEastAsianFullWidth, DWRITE_FONT_FEATURE_TAG_FULL_WIDTH) then
ApplyTag(dfvtEastAsianProportionalWidth, DWRITE_FONT_FEATURE_TAG_PROPORTIONAL_WIDTHS);
if not ApplyTag(dfvtEastAsianJIS78, DWRITE_FONT_FEATURE_TAG_JIS78_FORMS) then
if not ApplyTag(dfvtEastAsianJIS83, DWRITE_FONT_FEATURE_TAG_JIS83_FORMS) then
if not ApplyTag(dfvtEastAsianJIS90, DWRITE_FONT_FEATURE_TAG_JIS90_FORMS) then
if not ApplyTag(dfvtEastAsianJIS04, DWRITE_FONT_FEATURE_TAG_JIS04_FORMS) then
if not ApplyTag(dfvtEastAsianSimplified, DWRITE_FONT_FEATURE_TAG_SIMPLIFIED_FORMS) then
ApplyTag(dfvtEastAsianTraditional, DWRITE_FONT_FEATURE_TAG_TRADITIONAL_FORMS);
if not ApplyTag(dfvtLigaturesCommon, DWRITE_FONT_FEATURE_TAG_STANDARD_LIGATURES) then
ApplyTag(dfvtLigaturesNoCommon, DWRITE_FONT_FEATURE_TAG_STANDARD_LIGATURES, 0);
if not ApplyTag(dfvtLigaturesDiscretionary, DWRITE_FONT_FEATURE_TAG_DISCRETIONARY_LIGATURES) then
ApplyTag(dfvtLigaturesNoDiscretionary, DWRITE_FONT_FEATURE_TAG_DISCRETIONARY_LIGATURES, 0);
if not ApplyTag(dfvtLigaturesHistorical, DWRITE_FONT_FEATURE_TAG_HISTORICAL_LIGATURES) then
ApplyTag(dfvtLigaturesNoHistorical, DWRITE_FONT_FEATURE_TAG_HISTORICAL_LIGATURES, 0);
if not ApplyTag(dfvtLigaturesContextual, DWRITE_FONT_FEATURE_TAG_CONTEXTUAL_LIGATURES) then
ApplyTag(dfvtLigaturesNoContextual, DWRITE_FONT_FEATURE_TAG_CONTEXTUAL_LIGATURES, 0);
if not ApplyTag(dfvtNumericLiningNums, DWRITE_FONT_FEATURE_TAG_LINING_FIGURES) then
ApplyTag(dfvtNumericOldstyleNums, DWRITE_FONT_FEATURE_TAG_OLD_STYLE_FIGURES);
if not ApplyTag(dfvtNumericProportionalNums, DWRITE_FONT_FEATURE_TAG_PROPORTIONAL_FIGURES) then
ApplyTag(dfvtNumericTabularNums, DWRITE_FONT_FEATURE_TAG_TABULAR_FIGURES);
if not ApplyTag(dfvtNumericDiagonalFractions, DWRITE_FONT_FEATURE_TAG_FRACTIONS) then
ApplyTag(dfvtNumericStackedFractions, DWRITE_FONT_FEATURE_TAG_ALTERNATIVE_FRACTIONS);
ApplyTag(dfvtNumericOrdinal, DWRITE_FONT_FEATURE_TAG_ORDINALS);
ApplyTag(dfvtNumericSlashedZero, DWRITE_FONT_FEATURE_TAG_SLASHED_ZERO);
end;
{ TPLDrawingMatrixD2D }
constructor TPLDrawingMatrixD2D.Create(const AMatrix: TD2DMatrix3X2F);
begin
FMatrix := AMatrix;
FChanged := True;
FIsIdentity := CompareMem(@FMatrix, @MatrixIdentity, SizeOf(FMatrix));
end;
function TPLDrawingMatrixD2D.Clone: IPLDrawingMatrix;
begin
Result := TPLDrawingMatrixD2D.Create(FMatrix);
end;
procedure TPLDrawingMatrixD2D.Multiply(AMatrix: IPLDrawingMatrix);
begin
if AMatrix is TPLDrawingMatrixD2D then
FMatrix := MatrixMultiply(FMatrix, (AMatrix as TPLDrawingMatrixD2D).FMatrix);
FChanged := True;
FIsIdentity := False;
end;
procedure TPLDrawingMatrixD2D.Scale(AX, AY: TPLFloat);
begin
MatrixScale(FMatrix, AX, AY);
FChanged := True;
FIsIdentity := False;
end;
procedure TPLDrawingMatrixD2D.Translate(AX, AY: TPLFloat);
begin
MatrixTranslate(FMatrix, AX, AY);
FChanged := True;
FIsIdentity := False;
end;
function TPLDrawingMatrixD2D.Transform(AP: TPLPointF): TPLPointF;
begin
Result.X := FMatrix.m11 * AP.X + FMatrix.m12 * AP.Y + FMatrix.m31;
Result.Y := FMatrix.m21 * AP.X + FMatrix.m22 * AP.Y + FMatrix.m32;
end;
procedure TPLDrawingMatrixD2D.Identify;
begin
FMatrix := MatrixIdentity;
FChanged := True;
FIsIdentity := True;
end;
procedure TPLDrawingMatrixD2D.Rotate(ARad: TPLFloat);
begin
MatrixRotate(FMatrix, ARad);
FChanged := True;
FIsIdentity := False;
end;
{ TPLDrawingPenD2D }
function TPLDrawingPenD2D.GetBrush: IPLDrawingBrush;
begin
Result := FBrush;
end;
function TPLDrawingPenD2D.GetColor: TPLColor;
begin
Result := FColor;
end;
function TPLDrawingPenD2D.GetEndCap: TPLDrawingPenEndCap;
begin
Result := FLineCap;
end;
function TPLDrawingPenD2D.GetJoinStyle: TPLDrawingPenJoinStyle;
begin
Result := FLineJoin;
end;
function TPLDrawingPenD2D.GetMiterLimit: TPLFloat;
begin
Result := FMiterLimit;
end;
function TPLDrawingPenD2D.GetStyle: TPLDrawingPenStyle;
begin
Result := FLineStyle;
end;
function TPLDrawingPenD2D.GetStyleOffset: TPLFloat;
begin
Result := FLineStyleOffset;
end;
function TPLDrawingPenD2D.GetWidth: TPLFloat;
begin
Result := FWidth;
end;
procedure TPLDrawingPenD2D.SetBrush(AValue: IPLDrawingBrush);
begin
FBrush := AValue;
end;
procedure TPLDrawingPenD2D.SetColor(AValue: TPLColor);
begin
FColor := AValue;
end;
procedure TPLDrawingPenD2D.SetEndCap(AValue: TPLDrawingPenEndCap);
begin
if AValue = FLineCap then exit;
FLineCap := AValue;
FStyle := nil;
end;
procedure TPLDrawingPenD2D.SetJoinStyle(AValue: TPLDrawingPenJoinStyle);
begin
if AValue = FLineJoin then exit;
FLineJoin := AValue;
FStyle := nil;
end;
procedure TPLDrawingPenD2D.SetMiterLimit(AValue: TPLFloat);
begin
if AValue = FMiterLimit then exit;
FMiterLimit := AValue;
FStyle := nil;
end;
procedure TPLDrawingPenD2D.SetStyle(AValue: TPLDrawingPenStyle);
begin
if AValue = FLineStyle then exit;
FLineStyle := AValue;
FStyle := nil;
end;
procedure TPLDrawingPenD2D.SetStyleOffset(AValue: TPLFloat);
begin
if AValue = FLineStyleOffset then exit;
FLineStyleOffset := AValue;
FStyle := nil;
end;
procedure TPLDrawingPenD2D.SetWidth(AValue: TPLFloat);
begin
FWidth := AValue;
end;
function TPLDrawingPenD2D.Acquire(ATarget: ID2D1RenderTarget; AID: TPLInt
): TPLBool;
begin
if ATarget = nil then
exit(False);
Result := True;
if FBrush is TPLDrawingBrushD2D then
Result := (FBrush as TPLDrawingBrushD2D).Acquire(ATarget, AID);
if not Result then
exit;
if AID <> FID then
FFill := nil;
FTarget := ATarget;
FID := AID;
Result := HandleAvailable;
end;
function TPLDrawingPenD2D.CurrentBrush: ID2D1Brush;
begin
if FFill <> nil then
Result := FFill
else if FBrush is TPLDrawingBrushD2D then
Result := (FBrush as TPLDrawingBrushD2D).FBrush
else
Result := nil;
end;
function TPLDrawingPenD2D.HandleAvailable: TPLBool;
begin
if FStyle = nil then
FStyle := CreatePenStyle(Self);
Result := False;
if FBrush is TPLDrawingBrushD2D then
Result := (FBrush as TPLDrawingBrushD2D).HandleAvailable;
if Result then
FFill := nil
else if FFill = nil then
FFill := CreateSolidBrush(FTarget, Color, $FF);
Result := CurrentBrush <> nil;
end;
constructor TPLDrawingPenD2D.Create(AB: IPLDrawingBrush; AW: TPLFloat);
begin
inherited Create;
FBrush := AB;
FWidth := AW;
FColor := '#000';
FMiterLimit := 10;
end;
constructor TPLDrawingPenD2D.Create(const AC: TPLColor; AW: TPLFloat);
begin
inherited Create;
FColor := AC;
FWidth := AW;
FMiterLimit := 10;
end;
{ TPLDrawingBrushD2D }
function TPLDrawingBrushD2D.GetAlpha: Byte;
begin
Result := FAlpha;
end;
function TPLDrawingBrushD2D.GetMatrix: IPLDrawingMatrix;
begin
if FMatrix = nil then
FMatrix := NewDrawingMatrixD2D;
Result := FMatrix;
end;
procedure TPLDrawingBrushD2D.SetAlpha(AValue: Byte);
begin
FAlpha := AValue;
if FBrush <> nil then
FBrush.SetOpacity(FAlpha / 255);
end;
procedure TPLDrawingBrushD2D.SetMatrix(AValue: IPLDrawingMatrix);
begin
if AValue is TPLDrawingMatrixD2D then
begin
(Matrix as TPLDrawingMatrixD2D).FMatrix := (AValue as TPLDrawingMatrixD2D).FMatrix;
(Matrix as TPLDrawingMatrixD2D).FChanged := True;
end else
Matrix.Identify;
end;
function TPLDrawingBrushD2D.Acquire(ATarget: ID2D1RenderTarget; AID: TPLInt
): TPLBool;
begin
if ATarget = nil then
exit(False);
if AID <> FID then
begin
FBrush := nil;
if FMatrix is TPLDrawingMatrixD2D then
(FMatrix as TPLDrawingMatrixD2D).FChanged := True;
end;
FTarget := ATarget;
FID := AID;
Result := HandleAvailable;
end;
function TPLDrawingBrushD2D.HandleAvailable: TPLBool;
var
M: IPLDrawingMatrix;
begin
Result := FBrush <> nil;
if not Result then exit;
M := nil;
if (FMatrix is TPLDrawingMatrixD2D) and (FMatrix as TPLDrawingMatrixD2D).FChanged then
begin
M := FMatrix;
(FMatrix as TPLDrawingMatrixD2D).FChanged := False;
end;
if M <> nil then
FBrush.SetTransform((M as TPLDrawingMatrixD2D).FMatrix);
end;
constructor TPLDrawingBrushD2D.Create;
begin
inherited Create;
FAlpha := 255;
end;
{ TPLDrawingBrushSolidD2D }
procedure TPLDrawingBrushSolidD2D.SetColor(AValue: TPLColor);
begin
FColor := AValue;
FBrush := nil;
end;
function TPLDrawingBrushSolidD2D.HandleAvailable: TPLBool;
begin
if FTarget = nil then
exit(False);
if FBrush = nil then
FBrush := CreateSolidBrush(FTarget, Color, Alpha);
Result := inherited HandleAvailable;
end;
function TPLDrawingBrushSolidD2D.GetColor: TPLColor;
begin
Result := FColor;
end;
constructor TPLDrawingBrushSolidD2D.Create(AC: TPLColor);
begin
inherited Create;
FColor := AC;
end;
{ TPLDrawingBrushGradientD2D }
function TPLDrawingBrushGradientD2D.GetWrap: TPLDrawingBrushGradientWrap;
begin
Result := FWrap;
end;
procedure TPLDrawingBrushGradientD2D.SetWrap(AValue: TPLDrawingBrushGradientWrap
);
begin
if AValue = FWrap then exit;
FWrap := AValue;
FBrush := nil;
end;
function TPLDrawingBrushGradientD2D.HandleAvailable: TPLBool;
var
M: IPLDrawingMatrix;
begin
Result := FBrush <> nil;
if not Result then exit;
M := nil;
if (FMatrix is TPLDrawingMatrixD2D) and (FMatrix as TPLDrawingMatrixD2D).FChanged then
begin
(FMatrix as TPLDrawingMatrixD2D).FChanged := False;
M := FMatrix.Clone;
FCreated := True;
end
else if FCreated then
M := NewDrawingMatrixD2D;
if FCreated then
begin
M.Translate(FMidPoint.X, FMidPoint.Y);
FBrush.SetTransform((M as TPLDrawingMatrixD2D).FMatrix);
FCreated := False;
end;
end;
constructor TPLDrawingBrushGradientD2D.Create(AMiddle: TPLPointF);
begin
inherited Create;
FCreated := True;
FMidPoint := AMiddle;
FWrap := dbgwWrap;
FStops := TPLDrawingGradientStopsD2D.Create;
end;
destructor TPLDrawingBrushGradientD2D.Destroy;
begin
FStops.Free;
inherited Destroy;
end;
procedure TPLDrawingBrushGradientD2D.AddStop(AColor: TPLColor; AOffset: TPLFloat
);
var
S: TD2D1GradientStop;
begin
FBrush := nil;
S.color := AColor;
S.position := AOffset;
FStops.Add(S);
end;
{ TPLDrawingBrushGradientLinearD2D }
function TPLDrawingBrushGradientLinearD2D.HandleAvailable: TPLBool;
begin
if FTarget = nil then
exit(False);
FCreated := FBrush = nil;
if FCreated then
FBrush := CreateLinearGradientBrush(FTarget, FA, FB, FAlpha, FStops, FWrap);
Result := inherited HandleAvailable;
end;
constructor TPLDrawingBrushGradientLinearD2D.Create(const A, B: TPLPointF);
var
M: TPLPointF;
begin
M := TPLPointF.Create((A.X + B.X) / 2, (A.Y + B.Y) / 2);
inherited Create(M);
FA := A - M;
FB := B - M;
end;
{ TPLDrawingBrushGradientRadialD2D }
function TPLDrawingBrushGradientRadialD2D.HandleAvailable: TPLBool;
begin
if FTarget = nil then
exit(False);
FCreated := FBrush = nil;
if FCreated then
FBrush := CreateRadialGradientBrush(FTarget, FRect, FAlpha, FStops, FWrap);
Result := inherited HandleAvailable;
end;
constructor TPLDrawingBrushGradientRadialD2D.Create(const R: TPLRectF);
begin
inherited Create(R.Middle);
FRect := R;
FRect := FRect ** TPLPointF.Create(0, 0);
end;
{ TPLDrawingBrushBitmapD2D }
function TPLDrawingBrushBitmapD2D.HandleAvailable: TPLBool;
begin
if FTarget = nil then
exit(False);
if FBrush = nil then
FBrush := CreateBitmapBrush(FTarget, FBitmap, FAlpha);
Result := inherited HandleAvailable;
end;
constructor TPLDrawingBrushBitmapD2D.Create(B: IPLDrawingBitmap);
begin
inherited Create;
FBitmap := B.Clone;
end;
{ TPLDrawingFontD2D }
function TPLDrawingFontD2D.GetColor: TPLColor;
begin
Result := FData.Color;
end;
function TPLDrawingFontD2D.GetDecoration: TPLDrawingFontDecorations;
begin
Result := FData.Decoration;
end;
function TPLDrawingFontD2D.GetName: TPLString;
begin
Result := FData.Name;
end;
function TPLDrawingFontD2D.GetQuality: TFontQuality;
begin
Result := FData.Quality;
end;
function TPLDrawingFontD2D.GetSize: TPLFloat;
begin
Result := FData.Size;
end;
function TPLDrawingFontD2D.GetStretch: TPLDrawingFontStretch;
begin
Result := FData.Stretch;
end;
function TPLDrawingFontD2D.GetStyle: TPLDrawingFontStyle;
begin
Result := FData.Style;
end;
function TPLDrawingFontD2D.GetVariantTags: TPLDrawingFontVariantTags;
begin
Result := FData.VariantTags;
end;
function TPLDrawingFontD2D.GetWeight: TPLDrawingFontWeight;
begin
Result := FData.Weight;
end;
procedure TPLDrawingFontD2D.SetColor(AValue: TPLColor);
begin
FData.Color := AValue;
end;
procedure TPLDrawingFontD2D.SetDecoration(AValue: TPLDrawingFontDecorations);
begin
FData.Decoration := AValue;
end;
procedure TPLDrawingFontD2D.SetName(AValue: TPLString);
begin
FData.Name := AValue;
end;
procedure TPLDrawingFontD2D.SetQuality(AValue: TFontQuality);
begin
FData.Quality := AValue;
end;
procedure TPLDrawingFontD2D.SetSize(AValue: TPLFloat);
begin
if AValue < 1 then AValue := 1;
if AValue = FData.Size then exit;
FData.Size := AValue;
FFormat := nil;
end;
procedure TPLDrawingFontD2D.SetStretch(AValue: TPLDrawingFontStretch);
begin
FData.Stretch := AValue;
end;
procedure TPLDrawingFontD2D.SetStyle(AValue: TPLDrawingFontStyle);
begin
FData.Style := AValue;
end;
procedure TPLDrawingFontD2D.SetVariantTags(AValue: TPLDrawingFontVariantTags);
begin
FData.VariantTags := AValue;
end;
procedure TPLDrawingFontD2D.SetWeight(AValue: TPLDrawingFontWeight);
begin
FData.Weight := AValue;
end;
function TPLDrawingFontD2D.Format: IDWriteTextFormat;
begin
if FFormat = nil then
FFormat := CreateTextFormat(Self);
Result := FFormat;
end;
constructor TPLDrawingFontD2D.Create(AFontData: TPLDrawingFontData);
begin
inherited Create;
FData := AFontData;
end;
{ TPLDrawingPathDataD2D }
constructor TPLDrawingPathDataD2D.Create(APath: ID2D1Geometry);
begin
inherited Create;
FPath := APath;
end;
{ TPLDrawingSurfacePathD2D }
function TPLDrawingSurfacePathD2D.ClipStack: TPLD2D1GeometryList;
begin
if not Assigned(FClipStack) then FClipStack := TPLD2D1GeometryList.Create;
Result := FClipStack;
end;
function TPLDrawingSurfacePathD2D.HandleAvailable: TPLBool;
begin
Result := (FSurface <> nil) and (FSurface.FTarget <> nil);
end;
procedure TPLDrawingSurfacePathD2D.Open;
begin
if not HandleAvailable then exit;
if not FFigureOpened then
Open(FFigureOrigin.x, FFigureOrigin.y);
end;
procedure TPLDrawingSurfacePathD2D.Open(X, Y: TPLFloat);
begin
if not HandleAvailable then exit;
if FFigure = nil then begin
FFigure := CreateFigure;
FFigure.Open(FFigureSink);
end else if FFigureOpened then
FFigureSink.EndFigure(D2D1_FIGURE_END_OPEN);
FFigureOrigin.x := X;
FFigureOrigin.y := Y;
FFigureSink.BeginFigure(FFigureOrigin, D2D1_FIGURE_BEGIN_FILLED);
FFigureOpened := True;
end;
procedure TPLDrawingSurfacePathD2D.SaveClipStack;
begin
if not HandleAvailable then exit;
FSurface.Draw;
while FClipHeight > 0 do
begin
FSurface.FTarget.PopLayer;
Dec(FClipHeight);
end;
end;
procedure TPLDrawingSurfacePathD2D.RestoreClipStack;
var
Params: TD2D1LayerParameters;
G: ID2D1Geometry;
L: ID2D1Layer;
i: SizeInt;
begin
if not HandleAvailable then exit;
FSurface.Draw;
if (FClipHeight > 0) or (FClipStack = nil) then exit;
for i := 0 to FClipStack.Count-1 do
begin
G := FClipStack[i];
FSurface.FTarget.CreateLayer(nil, L);
Params := CreateLayerParameters(G);
FSurface.FTarget.PushLayer(Params, L);
Inc(FClipHeight);
end;
end;
constructor TPLDrawingSurfacePathD2D.Create(AC: TPLDrawingSurfaceD2D);
begin
inherited Create;
FSurface := AC;
FData := TPLD2D1GeometryList.Create;
end;
destructor TPLDrawingSurfacePathD2D.Destroy;
begin
FData.Free;
inherited Destroy;
end;
function TPLDrawingSurfacePathD2D.Clone: IPLDrawingPathData;
var
G: ID2D1Geometry;
I: SizeInt;
begin
Add;
I := FData.Count;
if I = 0 then
G := nil
else if I = 1 then
G := FData.First
else
G := CreateGroup(FData.Data, I);
Result := TPLDrawingPathDataD2D.Create(G);
end;
procedure TPLDrawingSurfacePathD2D.Add;
begin
if not HandleAvailable then exit;
if FFigure <> nil then begin
if FFigureOpened then
FFigureSink.EndFigure(D2D1_FIGURE_END_OPEN);
FFigureSink.Close;
FData.Add(CreateTransformed(FFigure, FSurface.Matrix));
FFigure := nil;
FFigureSink := nil;
FFigureOpened := False;
end;
end;
procedure TPLDrawingSurfacePathD2D.Add(G: ID2D1Geometry);
begin
if not HandleAvailable then exit;
Add;
FData.Add(CreateTransformed(G, FSurface.Matrix));
end;
procedure TPLDrawingSurfacePathD2D.Clip;
var
Params: TD2D1LayerParameters;
P: IPLDrawingPathData;
G: ID2D1Geometry;
L: ID2D1Layer;
begin
if not HandleAvailable then exit;
FSurface.Draw;
Add;
P := Clone;
G := (P as TPLDrawingPathDataD2D).FPath;
if G = nil then exit;
FSurface.FTarget.CreateLayer(nil, L);
Params := CreateLayerParameters(G);
FSurface.FTarget.PushLayer(Params, L);
ClipStack.Add(G);
Inc(FClipHeight);
Remove;
end;
procedure TPLDrawingSurfacePathD2D.JoinData(APath: IPLDrawingPathData);
var
G: ID2D1Geometry;
begin
G := (APath as TPLDrawingPathDataD2D).FPath;
if G <> nil then Add(G);
end;
procedure TPLDrawingSurfacePathD2D.Remove;
begin
if not HandleAvailable then exit;
Add;
if Assigned(FData) then FData.Free;
FData := TPLD2D1GeometryList.Create;
end;
procedure TPLDrawingSurfacePathD2D.Unclip;
begin
if not HandleAvailable then exit;
SaveClipStack;
if Assigned(FClipStack) then FClipStack.Free;
FClipStack := nil;
FClipHeight := 0;
end;
{ TPLDrawingSurfaceStateD2D }
constructor TPLDrawingSurfaceStateD2D.Create(C: TPLDrawingSurfaceD2D);
var
Path: TPLDrawingSurfacePathD2D;
i: SizeInt;
begin
inherited Create;
Path := C.Path;
if Path.FClipStack <> nil then begin
ClipStack := TPLD2D1GeometryList.Create;
for i := 0 to Path.FClipStack.Count-1 do
ClipStack.Add(Path.FClipStack[i]);
end else ClipStack := nil;
Data := TPLD2D1GeometryList.Create;
for i := 0 to Path.FData.Count-1 do
Data.Add(Path.FData[i]);
Matrix := C.Matrix.Clone;
end;
destructor TPLDrawingSurfaceStateD2D.Destroy;
begin
if Assigned(ClipStack) then ClipStack.Free;
if Assigned(Data) then Data.Free;
inherited Destroy;
end;
procedure TPLDrawingSurfaceStateD2D.Restore(C: TPLDrawingSurfaceD2D);
var
Path: TPLDrawingSurfacePathD2D;
begin
Path := C.Path;
Path.SaveClipStack;
Path.FClipStack := ClipStack;
Path.FClipHeight := 0;
Path.RestoreClipStack;
Path.Add;
Path.FData := Path.FData;
C.SetMatrix(Matrix);
end;
{ TPLDrawingSurfaceD2D }
function TPLDrawingSurfaceD2D.GetHandle: Pointer;
begin
if not HandleAvailable then exit(nil);
Result := FTarget;
end;
function TPLDrawingSurfaceD2D.GetMatrix: IPLDrawingMatrix;
begin
Result := FMatrix;
end;
function TPLDrawingSurfaceD2D.GetPath: IPLDrawingPath;
begin
Result := FPath;
end;
procedure TPLDrawingSurfaceD2D.SetMatrix(AValue: IPLDrawingMatrix);
begin
FMatrix := AValue;
end;
function TPLDrawingSurfaceD2D.Path: TPLDrawingSurfacePathD2D;
begin
Result := FPath as TPLDrawingSurfacePathD2D;
end;
function TPLDrawingSurfaceD2D.Matrix: TPLDrawingMatrixD2D;
begin
Result := FMatrix as TPLDrawingMatrixD2D;
end;
procedure TPLDrawingSurfaceD2D.Draw;
begin
if not FDrawing then begin
FTarget.BeginDraw;
FDrawing := True;
Path.RestoreClipStack;
end;
end;
procedure TPLDrawingSurfaceD2D.AcquireTarget(Target: ID2D1RenderTarget);
const
NextSurfaceID: Integer = 0;
begin
FTarget := Target;
FID := InterLockedIncrement(NextSurfaceID);
end;
function TPLDrawingSurfaceD2D.AcquireBrush(Brush: IPLDrawingBrush; out
B: ID2D1Brush): TPLBool;
var
D: TPLDrawingBrushD2D;
begin
B := nil;
if not HandleAvailable then exit(False);
D := Brush as TPLDrawingBrushD2D;
Result := D.Acquire(FTarget, FID);
if Result then B := D.FBrush;
end;
function TPLDrawingSurfaceD2D.AcquirePen(Pen: IPLDrawingPen; out B: ID2D1Brush;
out S: ID2D1StrokeStyle): TPLBool;
var
D: TPLDrawingPenD2D;
begin
B := nil;
S := nil;
if not HandleAvailable then exit(False);
D := Pen as TPLDrawingPenD2D;
Result := D.Acquire(FTarget, FID);
if Result then begin
B := D.CurrentBrush;
S := D.FStyle;
end;
end;
function TPLDrawingSurfaceD2D.HandleAvailable: TPLBool;
begin
Result := FTarget <> nil;
end;
procedure TPLDrawingSurfaceD2D.HandleRelease;
begin
Flush;
FTarget := nil;
Path.FClipStack := nil;
Path.FClipHeight := 0;
if Assigned(FStateStack) then FStateStack.Free;
FStateStack := nil;
end;
constructor TPLDrawingSurfaceD2D.Create(T: ID2D1RenderTarget);
begin
inherited Create;
FStateStack := TPLDrawingSurfaceStateD2DList.Create;
AcquireTarget(T);
FPath := TPLDrawingSurfacePathD2D.Create(Self);
FMatrix := NewDrawingMatrixD2D;
end;
destructor TPLDrawingSurfaceD2D.Destroy;
begin
HandleRelease;
Path.FSurface := nil;
FStateStack.Free;
inherited Destroy;
end;
procedure TPLDrawingSurfaceD2D.ShareRelease;
begin
//
end;
procedure TPLDrawingSurfaceD2D.Save;
begin
if not HandleAvailable then exit;
if FStateStack = nil then
FStateStack := TPLDrawingSurfaceStateD2DList.Create(True);
FStateStack.Add(TPLDrawingSurfaceStateD2D.Create(Self));
end;
procedure TPLDrawingSurfaceD2D.Restore;
var
S: TPLDrawingSurfaceStateD2D;
begin
if not HandleAvailable then
exit;
if FStateStack = nil then
exit;
S := FStateStack.Last;
S.Restore(Self);
FStateStack.Remove(S);
if FStateStack.Count < 1 then
FreeAndNil(FStateStack);
end;
procedure TPLDrawingSurfaceD2D.Flush;
begin
if not HandleAvailable then exit;
if FDrawing then begin
Path.SaveClipStack;
FTarget.EndDraw;
FTarget.Flush(nil, nil);
end;
FDrawing := False;
end;
procedure TPLDrawingSurfaceD2D.Clear(const AColor: TPLColor);
begin
ShareRelease;
if not HandleAvailable then exit;
Draw;
FTarget.Clear(AColor);
end;
procedure TPLDrawingSurfaceD2D.MoveTo(const AX, AY: TPLFloat);
begin
if not HandleAvailable then exit;
Path.Open(AX, AY);
end;
procedure TPLDrawingSurfaceD2D.LineTo(const AX, AY: TPLFloat);
var
L: TD2D1Point2F;
begin
ShareRelease;
if not HandleAvailable then exit;
L.x := AX;
L.y := AY;
Path.Open;
Path.FFigureSink.AddLine(L);
end;
procedure TPLDrawingSurfaceD2D.ArcTo(const ARect: TPLRectF; const ABeginAngle,
AEndAngle: TPLFloat);
const
Sweep: array[Boolean] of TD2D1SweepDirection =
(D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE, D2D1_SWEEP_DIRECTION_CLOCKWISE);
Size: array[Boolean] of TD2D1ArcSize =
(D2D1_ARC_SIZE_SMALL, D2D1_ARC_SIZE_LARGE);
var
P: TPLDrawingSurfacePathD2D;
A: TD2D1ArcSegment;
L: TD2D1Point2F;
W, H: TPLFloat;
begin
ShareRelease;
if not HandleAvailable then
Exit;
P := Path;
L.x := Sin(ABeginAngle);
L.y := -Cos(ABeginAngle);
W := ARect.Width / 2;
H := ARect.Height / 2;
with ARect.Middle do begin
L.x := X + L.x * W;
L.y := Y + L.y * H;
end;
if P.FFigureOpened then
P.FFigureSink.AddLine(L)
else
P.Open(L.x, L.y);
L.x := Sin(AEndAngle);
L.y := -Cos(AEndAngle);
with ARect.Middle do begin
L.x := X + L.x * W;
L.y := Y + L.y * H;
end;
A.point := L;
A.size.width := W;
A.size.height := H;
A.rotationAngle := 0;
A.sweepDirection := Sweep[AEndAngle > ABeginAngle];
A.arcSize := Size[Abs(ABeginAngle - AEndAngle) > Pi];
P.FFigureSink.AddArc(A);
end;
procedure TPLDrawingSurfaceD2D.CurveTo(const AX, AY: TPLFloat; const AC1,
AC2: TPLPointF);
var
B: TD2D1BezierSegment;
begin
ShareRelease;
if not HandleAvailable then exit;
B.point1 := AC1;
B.point2 := AC2;
B.point3.x := AX;
B.point3.y := AY;
Path.Open;
Path.FFigureSink.AddBezier(B);
end;
procedure TPLDrawingSurfaceD2D.Ellipse(const ARect: TPLRectF);
begin
ShareRelease;
if not HandleAvailable then exit;
Path.Add(CreateEllispe(ARect));
end;
procedure TPLDrawingSurfaceD2D.Rectangle(const ARect: TPLRectF);
begin
ShareRelease;
if not HandleAvailable then exit;
Path.Add(CreateRectangle(ARect));
end;
procedure TPLDrawingSurfaceD2D.RoundRectangle(const ARect: TPLRectF;
const ARadius: TPLFloat);
begin
ShareRelease;
if not HandleAvailable then exit;
Path.Add(CreateRoundRectangle(ARect, ARadius));
end;
procedure ApplyMatrix(ABrush: ID2D1Brush; AMatrix: IPLDrawingMatrix; out AState: TD2D1Matrix3x2F);
var
M: TD2D1Matrix3x2F;
begin
AState := MatrixIdentity;
if ABrush = nil then exit;
M := (AMatrix as TPLDrawingMatrixD2D).FMatrix;
ABrush.GetTransform(AState);
M := MatrixMultiply(AState, M);
ABrush.SetTransform(M);
end;
procedure RestoreMatrix(ABrush: ID2D1Brush; AState: TD2D1Matrix3x2F);
begin
if ABrush = nil then exit;
ABrush.SetTransform(AState);
end;
function PenWidth(AMatrix: IPLDrawingMatrix; Width: TPLFloat): TPLFloat;
const
A: TPLPointF = (FX: 1; FY: 0);
B: TPLPointF = (FX: 0; FY: 0);
begin
Result := AMatrix.Transform(A) >< AMatrix.Transform(B);
Result := abs(Result * Width);
end;
procedure TPLDrawingSurfaceD2D.FillOrStroke(ABrush: IPLDrawingBrush;
APen: IPLDrawingPen; APreserve: TPLBool);
var
Acquired: TPLBool;
State: TD2D1Matrix3x2F;
P: TPLDrawingSurfacePathD2D;
B: ID2D1Brush;
S: ID2D1StrokeStyle;
G: ID2D1Geometry;
I: Integer;
begin
ShareRelease;
B := nil;
S := nil;
if ABrush <> nil then begin
Acquired := AcquireBrush(ABrush, B);
if Acquired then ApplyMatrix(B, GetMatrix, State);
end else begin
Acquired := AcquirePen(APen, B, S);
if Acquired then ApplyMatrix(B, GetMatrix, State);
end;
if not Acquired then exit;
Draw;
P := Path;
P.Add;
I := P.FData.Count;
if I = 0 then exit;
if I = 1 then
G := P.FData.First
else
G := CreateGroup(P.FData.Data, I);
if ABrush <> nil then
FTarget.FillGeometry(G, B)
else
FTarget.DrawGeometry(G, B, PenWidth(GetMatrix, APen.Width), S);
if not APreserve then P.Remove;
if B <> nil then RestoreMatrix(B, State);
end;
procedure TPLDrawingSurfaceD2D.Stroke(APen: IPLDrawingPen;
const APreserve: TPLBool);
begin
FillOrStroke(nil, APen, APreserve);
end;
procedure TPLDrawingSurfaceD2D.Fill(ABrush: IPLDrawingBrush;
const APreserve: TPLBool);
begin
FillOrStroke(ABrush, nil, APreserve);
end;
const
MaxTextSize = High(integer);
function TPLDrawingSurfaceD2D.TextSize(AFont: IPLDrawingFont;
const AText: string; const ALineSpacing: single; const AWordWrap: boolean;
const AWritingMode: TPLWritingMode; const AReading: TPLReadingDirection
): TPLPointF;
var
Layout: IDWriteTextLayout;
M: TDWriteTextMetrics;
plinesp, pbasel: single;
lsmethod: DWRITE_LINE_SPACING_METHOD;
begin
if AText = '' then exit(TPLPointF.Empty);
Layout := CreateTextLayout((AFont as TPLDrawingFontD2D).Format, AText, MaxTextSize, MaxTextSize);
Layout.SetWordWrapping(ifthen(AWordWrap, 0, 1));
Layout.SetFlowDirection(Ord(AWritingMode));
Layout.SetReadingDirection(Ord(AReading));
if not IsNan(ALineSpacing) then begin
Layout.GetLineSpacing(lsmethod, plinesp, pbasel);
Layout.SetLineSpacing(lsmethod, ALineSpacing, pbasel);
end;
if (Layout = nil) or (Layout.GetMetrics(M) <> S_OK) then exit(TPLPointF.Empty);
Result.X := M.widthIncludingTrailingWhitespace;
Result.Y := M.height;
end;
function TPLDrawingSurfaceD2D.TextHeight(AFont: IPLDrawingFont;
const AText: string; const AWidth: TPLFloat; const ALineSpacing: single;
const AWordWrap: boolean; const AWritingMode: TPLWritingMode;
const AReading: TPLReadingDirection): TPLFloat;
var
Layout: IDWriteTextLayout;
M: TDWriteTextMetrics;
plinesp, pbasel: single;
lsmethod: DWRITE_LINE_SPACING_METHOD;
begin
if AWidth < 1 then exit(0);
Layout := CreateTextLayout((AFont as TPLDrawingFontD2D).Format, AText, AWidth, MaxTextSize);
Layout.SetWordWrapping(ifthen(AWordWrap, 0, 1));
Layout.SetFlowDirection(Ord(AWritingMode));
Layout.SetReadingDirection(Ord(AReading));
if not IsNan(ALineSpacing) then begin
Layout.GetLineSpacing(lsmethod, plinesp, pbasel);
Layout.SetLineSpacing(lsmethod, ALineSpacing, pbasel);
end;
if (Layout = nil) or (Layout.GetMetrics(M) <> S_OK) then exit(0);
Result := M.height;
end;
type
{ TPLCustomTextRenderer }
TPLCustomTextRenderer = class(TInterfacedObject, IDWritePixelSnapping, IDWriteTextRenderer)
private
FSurface: TPLDrawingSurfaceD2D;
FMatrix: TDWriteMatrix;
function TranslatedMatrix(X, Y: Float): TD2D1Matrix3x2F;
public
constructor Create(Surface: TPLDrawingSurfaceD2D);
{ IDWritePixelSnapping }
function IsPixelSnappingDisabled(clientDrawingContext: Pointer;
var isDisabled: BOOL): HResult; stdcall;
function GetCurrentTransform(clientDrawingContext: Pointer;
var transform: TDWriteMatrix): HResult; stdcall;
function GetPixelsPerDip(clientDrawingContext: Pointer;
var pixelsPerDip: Single): HResult; stdcall;
{ IDWriteTextRenderer }
function DrawGlyphRun(clientDrawingContext: Pointer; baselineOriginX: Single;
baselineOriginY: Single; measuringMode: TDWriteMeasuringMode;
var glyphRun: TDwriteGlyphRun;
var glyphRunDescription: TDwriteGlyphRunDescription;
clientDrawingEffect: IUnknown): HResult; stdcall;
function DrawUnderline(clientDrawingContext: Pointer; baselineOriginX: Single;
baselineOriginY: Single; var underline: TDwriteUnderline;
clientDrawingEffect: IUnknown): HResult; stdcall;
function DrawStrikethrough(clientDrawingContext: Pointer;
baselineOriginX: Single; baselineOriginY: Single;
var strikethrough: TDwriteStrikethrough;
clientDrawingEffect: IUnknown): HResult; stdcall;
function DrawInlineObject(clientDrawingContext: Pointer; originX: Single;
originY: Single; inlineObject: IDWriteInlineObject; isSideways: BOOL;
isRightToLeft: BOOL; clientDrawingEffect: IUnknown): HResult; stdcall;
end;
{ TPLCustomTextRenderer }
function TPLCustomTextRenderer.TranslatedMatrix(X, Y: Float): TD2D1Matrix3x2F;
var
M: TD2D1Matrix3x2F;
begin
M := MatrixIdentity;
MatrixTranslate(M, X, Y);
Result := MatrixMultiply(M, TD2D1Matrix3x2F(FMatrix));
end;
constructor TPLCustomTextRenderer.Create(Surface: TPLDrawingSurfaceD2D);
begin
inherited Create;
FSurface := Surface;
FMatrix := TDWriteMatrix(FSurface.Matrix.FMatrix);
end;
function TPLCustomTextRenderer.IsPixelSnappingDisabled(
clientDrawingContext: Pointer; var isDisabled: BOOL): HResult; stdcall;
begin
isDisabled := false;
Result := S_OK;
end;
function TPLCustomTextRenderer.GetCurrentTransform(
clientDrawingContext: Pointer; var transform: TDWriteMatrix): HResult;
stdcall;
begin
transform := FMatrix;
Result := S_OK;
end;
function TPLCustomTextRenderer.GetPixelsPerDip(clientDrawingContext: Pointer;
var pixelsPerDip: Single): HResult; stdcall;
begin
pixelsPerDip := 1;
Result := S_OK;
end;
function TPLCustomTextRenderer.DrawGlyphRun(clientDrawingContext: Pointer;
baselineOriginX: Single; baselineOriginY: Single;
measuringMode: TDWriteMeasuringMode; var glyphRun: TDwriteGlyphRun;
var glyphRunDescription: TDwriteGlyphRunDescription;
clientDrawingEffect: IUnknown): HResult; stdcall;
var
F: ID2D1PathGeometry;
S: ID2D1GeometrySink;
M: TD2D1Matrix3x2F;
T: ID2D1TransformedGeometry;
begin
F := CreateFigure;
F.Open(S);
glyphRun.fontFace.GetGlyphRunOutline(
glyphRun.fontEmSize,
glyphRun.glyphIndices,
glyphRun.glyphAdvances,
glyphRun.glyphOffsets,
glyphRun.glyphCount,
glyphRun.isSideways,
glyphRun.bidiLevel <> 0,
S);
S.Close;
M := TranslatedMatrix(baselineOriginX, baselineOriginY);
RenderFactory.CreateTransformedGeometry(F, M, T);
FSurface.Path.FData.Add(T);
Result := S_OK;
end;
function TPLCustomTextRenderer.DrawUnderline(clientDrawingContext: Pointer;
baselineOriginX: Single; baselineOriginY: Single;
var underline: TDwriteUnderline; clientDrawingEffect: IUnknown): HResult;
stdcall;
var
R: TPLRectF;
G: ID2D1RectangleGeometry;
M: TD2D1Matrix3x2F;
T: ID2D1TransformedGeometry;
begin
R := TPLRectF.Create(0, 0, underline.width, underline.thickness);
R.Inflate(0, underline.offset);
G := CreateRectangle(R);
M := TranslatedMatrix(baselineOriginX, baselineOriginY);
RenderFactory.CreateTransformedGeometry(G, M, T);
FSurface.Path.FData.Add(T);
Result := S_OK;
end;
function TPLCustomTextRenderer.DrawStrikethrough(clientDrawingContext: Pointer;
baselineOriginX: Single; baselineOriginY: Single;
var strikethrough: TDwriteStrikethrough; clientDrawingEffect: IUnknown
): HResult; stdcall;
var
R: TPLRectF;
G: ID2D1RectangleGeometry;
M: TD2D1Matrix3x2F;
T: ID2D1TransformedGeometry;
begin
R := TPLRectF.Create(0, 0, strikethrough.width, strikethrough.thickness);
R.Inflate(0, strikethrough.offset);
G := CreateRectangle(R);
M := TranslatedMatrix(baselineOriginX, baselineOriginY);
RenderFactory.CreateTransformedGeometry(G, M, T);
FSurface.Path.FData.Add(T);
Result := S_OK;
end;
function TPLCustomTextRenderer.DrawInlineObject(clientDrawingContext: Pointer;
originX: Single; originY: Single; inlineObject: IDWriteInlineObject;
isSideways: BOOL; isRightToLeft: BOOL; clientDrawingEffect: IUnknown
): HResult; stdcall;
var
R: IDWriteTextRenderer;
begin
R := self;
inlineObject.Draw(clientDrawingContext, R, originX, originY, isSideways,
isRightToLeft, clientDrawingEffect);
Result := S_OK;
end;
procedure TPLDrawingSurfaceD2D.TextOut(AFont: IPLDrawingFont;
const AText: string; const ARect: TPLRectF;
const ADirection: TPLTextDirections; const ALineSpacing: single;
const AWordWrap: boolean; const AWritingMode: TPLWritingMode;
const AReading: TPLReadingDirection; const AImmediate: TPLBool);
const
TrimChar: TDWriteTrimming = (granularity: DWRITE_TRIMMING_GRANULARITY_CHARACTER);
RenderingModes: array[TFontQuality] of DWORD = (DWRITE_RENDERING_MODE_DEFAULT,
DWRITE_RENDERING_MODE_ALIASED, DWRITE_RENDERING_MODE_CLEARTYPE_GDI_CLASSIC, DWRITE_RENDERING_MODE_ALIASED,
DWRITE_RENDERING_MODE_CLEARTYPE_GDI_CLASSIC, DWRITE_RENDERING_MODE_CLEARTYPE_GDI_CLASSIC,
DWRITE_RENDERING_MODE_CLEARTYPE_NATURAL);
AntialiasModes: array[TFontQuality] of DWORD = (D2D1_TEXT_ANTIALIAS_MODE_DEFAULT,
D2D1_TEXT_ANTIALIAS_MODE_ALIASED, D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE,
D2D1_TEXT_ANTIALIAS_MODE_ALIASED, D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE,
D2D1_TEXT_ANTIALIAS_MODE_CLEARTYPE, D2D1_TEXT_ANTIALIAS_MODE_CLEARTYPE);
FontWeight: array[TPLDrawingFontWeight] of DWRITE_FONT_WEIGHT =
(DWRITE_FONT_WEIGHT_THIN, DWRITE_FONT_WEIGHT_EXTRA_LIGHT, DWRITE_FONT_WEIGHT_LIGHT,
DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_WEIGHT_MEDIUM, DWRITE_FONT_WEIGHT_SEMI_BOLD,
DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_WEIGHT_EXTRA_BOLD, DWRITE_FONT_WEIGHT_BLACK
);
FontStyle: array[TPLDrawingFontStyle] of DWRITE_FONT_STYLE =
(DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STYLE_ITALIC, DWRITE_FONT_STYLE_OBLIQUE);
FontStretch: array[TPLDrawingFontStretch] of DWRITE_FONT_STRETCH =
(DWRITE_FONT_STRETCH_ULTRA_CONDENSED, DWRITE_FONT_STRETCH_EXTRA_CONDENSED,
DWRITE_FONT_STRETCH_CONDENSED, DWRITE_FONT_STRETCH_SEMI_CONDENSED,
DWRITE_FONT_STRETCH_NORMAL, DWRITE_FONT_STRETCH_SEMI_EXPANDED,
DWRITE_FONT_STRETCH_EXPANDED, DWRITE_FONT_STRETCH_EXTRA_EXPANDED,
DWRITE_FONT_STRETCH_ULTRA_EXPANDED
);
var
FontObj: TPLDrawingFontD2D;
Layout: IDWriteTextLayout;
Range: TDWriteTextRange;
AEllipse: IDWriteInlineObject;
Params1: IDWriteRenderingParams;
Params2: IDWriteRenderingParams;
Brush: ID2D1Brush;
Renderer: IDWriteTextRenderer;
M: TD2D1Matrix3x2F;
txta, prga: DWORD;
typg: IDWriteTypography;
plinesp, pbasel: single;
lsmethod: DWRITE_LINE_SPACING_METHOD;
begin
ShareRelease;
if not HandleAvailable then exit;
if AImmediate then Path.Remove;
if ARect.IsEmpty or (AText = '') then exit;
Draw;
Path.Add;
FontObj := AFont as TPLDrawingFontD2D;
Layout := CreateGdiTextLayout(FontObj.Format, AText, ARect.Width, ARect.Height);
case ADirection.TextPosition of
tdLeft, tdWrap, tdFlow: txta := DWRITE_TEXT_ALIGNMENT_LEADING;
tdRight: txta := DWRITE_TEXT_ALIGNMENT_TRAILING;
tdFill: txta := DWRITE_TEXT_ALIGNMENT_JUSTIFIED;
else txta := DWRITE_TEXT_ALIGNMENT_CENTER;
end;
case ADirection.ParagraphPosition of
tdCenter, tdFill: prga := DWRITE_PARAGRAPH_ALIGNMENT_CENTER;
tdDown: prga := DWRITE_PARAGRAPH_ALIGNMENT_FAR;
else prga := DWRITE_PARAGRAPH_ALIGNMENT_NEAR;
end;
Layout.SetTextAlignment(txta);
Layout.SetParagraphAlignment(prga);
Range.StartPosition := 0;
Range.Length := Length(AText);
Layout.SetFontWeight(FontWeight[FontObj.Weight], Range);
Layout.SetFontStretch(FontStretch[FontObj.Stretch], Range);
Layout.SetFontStyle(FontStyle[FontObj.Style], Range);
if dfdUnderline in FontObj.Decoration then
Layout.SetUnderline(true, Range);
if dfdLineThrough in FontObj.Decoration then
Layout.SetStrikethrough(true, Range);
if dfdOverline in FontObj.Decoration then { TODO : add overline text effect }
;//Layout.Set;
Layout.SetWordWrapping(ifthen(AWordWrap, 0, 1));
Layout.SetFlowDirection(Ord(AWritingMode));
Layout.SetReadingDirection(Ord(AReading));
if not IsNan(ALineSpacing) then begin
Layout.GetLineSpacing(lsmethod, plinesp, pbasel);
Layout.SetLineSpacing(lsmethod, ALineSpacing, pbasel);
end;
typg := CreateFontTypography(FontObj);
if Assigned(typg) then Layout.SetTypography(typg, Range);
WriteFactory.CreateEllipsisTrimmingSign(Layout, AEllipse);
Layout.SetTrimming(TrimChar, AEllipse);
WriteFactory.CreateRenderingParams(Params1);
WriteFactory.CreateCustomRenderingParams(Params1.GetGamma, Params1.GetEnhancedContrast,
1, Params1.GetPixelGeometry, RenderingModes[AFont.Quality], Params2);
FTarget.SetTextRenderingParams(Params2);
FTarget.SetTextAntialiasMode(AntialiasModes[AFont.Quality]);
if AImmediate then begin
Brush := CreateSolidBrush(FTarget, AFont.Color, 255);
FTarget.GetTransform(M);
FTarget.SetTransform(Matrix.FMatrix);
FTarget.DrawTextLayout(ARect.TopLeft, Layout, Brush, D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT or D2D1_DRAW_TEXT_OPTIONS_CLIP);
FTarget.SetTransform(M);
end else begin
Renderer := TPLCustomTextRenderer.Create(self);
Layout.Draw(nil, Renderer, ARect.Left, ARect.Top);
end;
end;
{ TPLDrawingBitmapSurfaceD2D }
function TPLDrawingBitmapSurfaceD2D.HandleAvailable: TPLBool;
begin
Result := inherited HandleAvailable;
end;
procedure TPLDrawingBitmapSurfaceD2D.HandleRelease;
begin
inherited HandleRelease;
end;
constructor TPLDrawingBitmapSurfaceD2D.Create(B: TPLDrawingBitmapD2D);
begin
end;
function TPLDrawingBitmapSurfaceD2D.ShareCreate(Target: ID2D1RenderTarget): ID2D1Bitmap;
begin
end;
procedure TPLDrawingBitmapSurfaceD2D.ShareRelease;
begin
inherited ShareRelease;
end;
{ TPLDrawingBitmapD2D }
procedure TPLDrawingBitmapD2D.HandleRelease;
begin
inherited HandleRelease;
end;
function TPLDrawingBitmapD2D.GetSurface: IPLDrawingSurface;
begin
Result:=inherited GetSurface;
end;
function TPLDrawingBitmapD2D.GetPixels: PPLPixel;
begin
Result:=inherited GetPixels;
end;
destructor TPLDrawingBitmapD2D.Destroy;
begin
inherited Destroy;
end;
procedure TPLDrawingBitmapD2D.Clear;
begin
inherited Clear;
end;
{ TPLD2D1Drawer }
constructor TPLD2D1Drawer.Create(ACanvas: TCanvas);
begin
inherited Create(ACanvas);
FSurface := NewDrawingSurfaceD2D(ACanvas);
end;
destructor TPLD2D1Drawer.Destroy;
begin
inherited Destroy;
end;
procedure TPLD2D1Drawer.DrawObjectBackground(const AObject: TPLHTMLObject);
begin
inherited DrawObjectBackground(AObject);
end;
procedure TPLD2D1Drawer.DrawObjectBorder(const AObject: TPLHTMLObject);
begin
inherited DrawObjectBorder(AObject);
end;
procedure TPLD2D1Drawer.DrawObjectOutline(const AObject: TPLHTMLObject);
begin
inherited DrawObjectOutline(AObject);
end;
procedure TPLD2D1Drawer.DrawObjectOutlineText(const AObject: TPLHTMLObject);
begin
inherited DrawObjectOutlineText(AObject);
end;
procedure TPLD2D1Drawer.DrawObjectText(const AObject: TPLHTMLObject);
begin
inherited DrawObjectText(AObject);
end;
procedure TPLD2D1Drawer.DrawObjectDebug(const AObject: TPLHTMLObject);
begin
//FSurface.;
end;
procedure TPLD2D1Drawer.DrawObjectShadow(const AObject: TPLHTMLObject);
begin
inherited DrawObjectShadow(AObject);
end;
procedure TPLD2D1Drawer.DrawObjectTextShadow(const AObject: TPLHTMLObject);
begin
inherited DrawObjectTextShadow(AObject);
end;
procedure TPLD2D1Drawer.DrawObjectPseudoBefore(const AObject: TPLHTMLObject);
begin
inherited DrawObjectPseudoBefore(AObject);
end;
procedure TPLD2D1Drawer.DrawObjectPseudoAfter(const AObject: TPLHTMLObject);
begin
inherited DrawObjectPseudoAfter(AObject);
end;
procedure TPLD2D1Drawer.DrawFrame(const ABorders: TPLDrawingBorders;
const ARect: TPLRectF);
begin
//inherited DrawFrame(ABorders);
end;
// public functions
function NewDrawingMatrixD2D: IPLDrawingMatrix;
begin
Result := TPLDrawingMatrixD2D.Create(MatrixIdentity);
end;
function NewDrawingPenD2D(ABrush: IPLDrawingBrush; AWidth: TPLFloat): IPLDrawingPen;
begin
Result := TPLDrawingPenD2D.Create(ABrush, AWidth);
end;
function NewDrawingPenD2D(AColor: TPLColor; AWidth: TPLFloat): IPLDrawingPen;
begin
Result := TPLDrawingPenD2D.Create(AColor, AWidth);
end;
function NewDrawingSolidBrushD2D(AColor: TPLColor): IPLDrawingBrushSolid;
begin
Result := TPLDrawingBrushSolidD2D.Create(AColor);
end;
function NewDrawingBitmapBrushD2D(ABitmap: IPLDrawingBitmap): IPLDrawingBrushBitmap;
begin
Result := TPLDrawingBrushBitmapD2D.Create(ABitmap);
end;
function NewDrawingLinearGradientBrushD2D(
const A, B: TPLPointF): IPLDrawingBrushGradientLinear;
begin
Result := TPLDrawingBrushGradientLinearD2D.Create(A, B);
end;
function NewDrawingRadialGradientBrushD2D(
const ARect: TPLRectF): IPLDrawingBrushGradientRadial;
begin
Result := TPLDrawingBrushGradientRadialD2D.Create(ARect);
end;
function NewDrawingFontD2D(AFontData: TPLDrawingFontData): IPLDrawingFont;
begin
Result := TPLDrawingFontD2D.Create(AFontData);
end;
var
ScreenDC: HDC;
function NewDrawingSurfaceD2D(ACanvas: TCanvas): IPLDrawingSurface;
var
T: ID2D1DCRenderTarget;
R: TRect;
begin
T := CreateDCTarget;
if ACanvas = nil then
begin
if ScreenDC = 0 then ScreenDC := GetDC(0);
GetWindowRect(GetDesktopWindow, R);
T.BindDC(ScreenDC, TPLRectI.Create(0, 0, R.Right - R.Left, R.Bottom - R.Top));
end else
T.BindDC(ACanvas.Handle, TPLRectI.Create(0, 0, ACanvas.Width, ACanvas.Height));
Result := TPLDrawingSurfaceD2D.Create(T);
end;
function NewDrawingBitmapD2D(AWidth, AHeight: TPLInt): IPLDrawingBitmap;
begin
Result := TPLDrawingBitmapD2D.Create;
Result.SetSize(AWidth, AHeight);
end;
initialization
Direct2DInit;
end.
|
unit processor;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, Process, LCLType;
type
{ TForm2 }
TForm2 = class(TForm)
memOutput: TMemo;
procedure run();
procedure makeProxy();
procedure readOutput(S: TStringList; M: TMemoryStream);
private
{ private declarations }
public
{ public declarations }
end;
var
Form2: TForm2;
FFmpegProcess: TProcess;
FFmpegPath, OutputPath: String;
Shakiness, Bitrate: Integer;
Deinterlace, Stabilize: Boolean;
InputFiles: TStrings;
implementation
{$R *.lfm}
{ TForm2 }
procedure TForm2.run();
var
S: TStringList;
M: TMemoryStream;
i, Result: Integer;
AlwaysSkipDeinterlace, AlwaysContinueDeinterlace, AlwaysSkipAnalyze, AlwaysContinueAnalyze, Continue: Boolean;
begin
AlwaysSkipDeinterlace := false;
AlwaysContinueDeinterlace := false;
AlwaysSkipAnalyze := false;
AlwaysContinueAnalyze := false;
//deinterlace
for i := 0 to InputFiles.Count-1 do begin
if Deinterlace = true then begin
memOutput.Lines.Add('Deinterlacing ' + InputFiles.Strings[i]);
// Abort if Overwrite Dialogs are answered to not overwrite
Continue := true;
if (Stabilize = true) and AlwaysSkipDeinterlace and FileExists('tmp_'+ExtractFileName(InputFiles.Strings[i])) then Continue:=false;
if AlwaysContinueDeinterlace then Continue:=true;
if ((Stabilize = true) and FileExists('tmp_'+ExtractFileName(InputFiles.Strings[i]))) and not (AlwaysSkipDeinterlace or AlwaysContinueDeinterlace) then begin
Result := MessageDlg('You''ve been here before', 'Found deinterlaced version. Do you want to use it? Otherwise it will be overwritten.', mtConfirmation, [mbYes, mbNo, mbYesToAll, mbNoToAll], 0);
if (Result = mrYes) or (Result = mrYesToAll) then Continue:=false else Continue:=true;
if Result = mrYestoAll then AlwaysSkipDeinterlace:=true;
if Result = mrNotoAll then AlwaysContinueDeinterlace:=true;
end;
if Continue then begin
S := TStringList.Create;
M := TMemoryStream.Create;
Sleep(1000);
//init ffmpeg
FFmpegProcess := TProcess.Create(nil);
FFmpegProcess.Executable := FFmpegPath;
FFmpegProcess.Parameters.Add('-y');
FFmpegProcess.Parameters.Add('-i');
FFmpegProcess.Parameters.Add(InputFiles.Strings[i]);
FFmpegProcess.Parameters.Add('-q:v');
FFmpegProcess.Parameters.Add('0');
if Stabilize = false then begin
FFmpegProcess.Parameters.Add('-b:v');
FFmpegProcess.Parameters.Add(IntToStr(Bitrate)+'k');
end;
FFmpegProcess.Parameters.Add('-vf');
FFmpegProcess.Parameters.Add('yadif=1');
FFmpegProcess.Parameters.Add('-acodec');
FFmpegProcess.Parameters.Add('copy');
if Stabilize = true then
FFmpegProcess.Parameters.Add('tmp_'+ExtractFileName(InputFiles.Strings[i]))
else
FFmpegProcess.Parameters.Add(OutputPath+'\'+ExtractFileName(InputFiles.Strings[i]));
FFmpegProcess.Options := [poUsePipes,poStderrToOutPut];
FFmpegProcess.ShowWindow := swoHIDE;
FFmpegProcess.Execute;
//show log
while FFmpegProcess.Running do
begin
readOutput(S,M);
end;
//read last output part
readOutput(S,M);
S.Free;
FFmpegProcess.Free;
M.Free;
end else memOutput.Lines.Add('Skipped.');
end;
//stabilize(analyze)
if Stabilize = true then begin
memOutput.Lines.Add('Analysing ' + InputFiles.Strings[i]);
// Abort if Overwrite Dialogs are answered to not overwrite
Continue := true;
if (Stabilize = true) and AlwaysSkipAnalyze and FileExists(ExtractFileName(InputFiles.Strings[i])+'_transform_vectors.trf') then Continue:=false;
if AlwaysContinueAnalyze then Continue:=true;
if ((Stabilize = true) and FileExists(ExtractFileName(InputFiles.Strings[i])+'_transform_vectors.trf')) and not (AlwaysSkipAnalyze or AlwaysContinueAnalyze) then begin
Result := MessageDlg('You''ve been here before', 'Found analysing data. Do you want to use it? Otherwise it will be overwritten.', mtConfirmation, [mbYes, mbNo, mbYesToAll, mbNoToAll], 0);
if (Result = mrYes) or (Result = mrYesToAll) then Continue:=false else Continue:=true;
if Result = mrYestoAll then AlwaysSkipAnalyze:=true;
if Result = mrNotoAll then AlwaysContinueAnalyze:=true;
end;
if Continue then begin
S := TStringList.Create;
M := TMemoryStream.Create;
Sleep(1000);
//init ffmpeg
FFmpegProcess := TProcess.Create(nil);
FFmpegProcess.Executable := FFmpegPath;
FFmpegProcess.Parameters.Add('-y');
FFmpegProcess.Parameters.Add('-i');
if Deinterlace = true then
FFmpegProcess.Parameters.Add('tmp_'+ExtractFileName(InputFiles.Strings[i]))
else
FFmpegProcess.Parameters.Add(InputFiles.Strings[i]);
FFmpegProcess.Parameters.Add('-vf');
FFmpegProcess.Parameters.Add('vidstabdetect=stepsize=6:shakiness='+IntToStr(Shakiness)+':accuracy=9:result='+ExtractFileName(InputFiles.Strings[i])+'_transform_vectors.trf');
FFmpegProcess.Parameters.Add('-f');
FFmpegProcess.Parameters.Add('null');
FFmpegProcess.Parameters.Add('-');
FFmpegProcess.Options := [poUsePipes,poStderrToOutPut];
FFmpegProcess.ShowWindow := swoHIDE;
FFmpegProcess.Execute;
//show log
while FFmpegProcess.Running do
begin
readOutput(S,M);
end;
//read last output part
readOutput(S,M);
S.Free;
FFmpegProcess.Free;
M.Free;
end else memOutput.Lines.Add('Skipped.');
//stabilize(render)
memOutput.Lines.Add('Stabilising ' + InputFiles.Strings[i]);
Continue := true;
if Continue then begin
S := TStringList.Create;
M := TMemoryStream.Create;
Sleep(1000);
//init ffmpeg
FFmpegProcess := TProcess.Create(nil);
FFmpegProcess.Executable := FFmpegPath;
FFmpegProcess.Parameters.Add('-y');
FFmpegProcess.Parameters.Add('-i');
if Deinterlace = true then
FFmpegProcess.Parameters.Add('tmp_'+ExtractFileName(InputFiles.Strings[i]))
else
FFmpegProcess.Parameters.Add(InputFiles.Strings[i]);
FFmpegProcess.Parameters.Add('-q:v');
FFmpegProcess.Parameters.Add('0');
FFmpegProcess.Parameters.Add('-b:v');
FFmpegProcess.Parameters.Add(IntToStr(Bitrate)+'k');
FFmpegProcess.Parameters.Add('-vf');
FFmpegProcess.Parameters.Add('vidstabtransform=input='+ExtractFileName(InputFiles.Strings[i])+'_transform_vectors.trf:zoom=1:smoothing=30,unsharp=5:5:0.8:3:3:0.4');
FFmpegProcess.Parameters.Add('-acodec');
FFmpegProcess.Parameters.Add('copy');
FFmpegProcess.Parameters.Add(OutputPath+'\'+ExtractFileName(InputFiles.Strings[i]));
FFmpegProcess.Options := [poUsePipes,poStderrToOutPut];
FFmpegProcess.ShowWindow := swoHIDE;
FFmpegProcess.Execute;
//show log
while FFmpegProcess.Running do
begin
readOutput(S,M);
end;
//read last output part
readOutput(S,M);
S.Free;
FFmpegProcess.Free;
M.Free;
end else memOutput.Lines.Add('Skipped.');
//stabilize(cleanup)
memOutput.Lines.Add('Cleanup');
if Stabilize = true then DeleteFile(ExtractFileName(InputFiles.Strings[i])+'_transform_vectors.trf');
if Deinterlace and Stabilize then DeleteFile('tmp_'+ExtractFileName(InputFiles.Strings[i]));
memOutput.Lines.Add(IntToStr(i+1)+'/'+IntToStr(InputFiles.Count)+' Done!');
end;
end;
end;
procedure TForm2.makeProxy();
var
S: TStringList;
M: TMemoryStream;
i: Integer;
Continue: Boolean;
begin
//deinterlace
for i := 0 to InputFiles.Count-1 do begin
memOutput.Lines.Add('Proxying ' + InputFiles.Strings[i]);
// Abort if Overwrite Dialogs are answered to not overwrite
Continue := true;
if Continue then begin
S := TStringList.Create;
M := TMemoryStream.Create;
Sleep(1000);
//init ffmpeg
FFmpegProcess := TProcess.Create(nil);
FFmpegProcess.Executable := FFmpegPath;
FFmpegProcess.Parameters.Add('-y');
FFmpegProcess.Parameters.Add('-i');
FFmpegProcess.Parameters.Add(InputFiles.Strings[i]);
FFmpegProcess.Parameters.Add('-q:v');
FFmpegProcess.Parameters.Add('15');
FFmpegProcess.Parameters.Add('-vf');
FFmpegProcess.Parameters.Add('scale=iw/4:ih/4');
FFmpegProcess.Parameters.Add('-acodec');
FFmpegProcess.Parameters.Add('copy');
FFmpegProcess.Parameters.Add(OutputPath+'\'+ExtractFileName(InputFiles.Strings[i]));
FFmpegProcess.Options := [poUsePipes,poStderrToOutPut];
FFmpegProcess.ShowWindow := swoHIDE;
FFmpegProcess.Execute;
//show log
while FFmpegProcess.Running do
begin
readOutput(S,M);
end;
//read last output part
readOutput(S,M);
S.Free;
FFmpegProcess.Free;
M.Free;
end else memOutput.Lines.Add('Skipped.');
memOutput.Lines.Add(IntToStr(i+1)+'/'+IntToStr(InputFiles.Count)+' Done!');
end;
end;
procedure TForm2.readOutput(S: TStringList; M: TMemoryStream);
var
n: LongInt = 0;
BytesRead: LongInt = 0;
READ_BYTES: LongInt = 0;
begin
READ_BYTES := FFmpegProcess.Output.NumBytesAvailable;
if READ_BYTES > 0
then begin
//reserve memory
M.SetSize(BytesRead + READ_BYTES);
//read output
n := FFmpegProcess.Output.Read((M.Memory + BytesRead)^, READ_BYTES);
if n > 0
then
Inc(BytesRead, n);
end else begin
Sleep(100);
end;
//print to log
M.SetSize(BytesRead);
S.LoadFromStream(M);
M.Clear;
BytesRead := 0;
memOutput.Lines.AddText(S.Text);
memOutput.Update;
memOutput.SelStart:=Length(memOutput.Text);
Application.ProcessMessages;
end;
end.
|
unit Demo.GeoChart.Coloring;
interface
uses
System.Classes, System.Variants, Demo.BaseFrame, cfs.GCharts;
type
TDemo_GeoChart_Coloring = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_GeoChart_Coloring.GenerateChart;
var
Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_GEO_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Country'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Latitude')
]);
Chart.Data.AddRow(['Algeria', 36]);
Chart.Data.AddRow(['Angola', -8]);
Chart.Data.AddRow(['Benin', 6]);
Chart.Data.AddRow(['Botswana', -24]);
Chart.Data.AddRow(['Burkina Faso', 12]);
Chart.Data.AddRow(['Burundi', -3]);
Chart.Data.AddRow(['Cameroon', 3]);
Chart.Data.AddRow(['Canary Islands', 28]);
Chart.Data.AddRow(['Cape Verde', 15]);
Chart.Data.AddRow(['Central African Republic', 4]);
Chart.Data.AddRow(['Ceuta', 35]);
Chart.Data.AddRow(['Chad', 12]);
Chart.Data.AddRow(['Comoros', -12]);
Chart.Data.AddRow(['Cote d''Ivoire', 6]);
Chart.Data.AddRow(['Democratic Republic of the Congo', -3]);
Chart.Data.AddRow(['Djibouti', 12]);
Chart.Data.AddRow(['Egypt', 26]);
Chart.Data.AddRow(['Equatorial Guinea', 3]);
Chart.Data.AddRow(['Eritrea', 15]);
Chart.Data.AddRow(['Ethiopia', 9]);
Chart.Data.AddRow(['Gabon', 0]);
Chart.Data.AddRow(['Gambia', 13]);
Chart.Data.AddRow(['Ghana', 5]);
Chart.Data.AddRow(['Guinea', 10]);
Chart.Data.AddRow(['Guinea-Bissau', 12]);
Chart.Data.AddRow(['Kenya', -1]);
Chart.Data.AddRow(['Lesotho', -29]);
Chart.Data.AddRow(['Liberia', 6]);
Chart.Data.AddRow(['Libya', 32]);
Chart.Data.AddRow(['Madagascar', null]);
Chart.Data.AddRow(['Madeira', 33]);
Chart.Data.AddRow(['Malawi', -14]);
Chart.Data.AddRow(['Mali', 12]);
Chart.Data.AddRow(['Mauritania', 18]);
Chart.Data.AddRow(['Mauritius', -20]);
Chart.Data.AddRow(['Mayotte', -13]);
Chart.Data.AddRow(['Melilla', 35]);
Chart.Data.AddRow(['Morocco', 32]);
Chart.Data.AddRow(['Mozambique', -25]);
Chart.Data.AddRow(['Namibia', -22]);
Chart.Data.AddRow(['Niger', 14]);
Chart.Data.AddRow(['Nigeria', 8]);
Chart.Data.AddRow(['Republic of the Congo', -1]);
Chart.Data.AddRow(['Rรฉunion', -21]);
Chart.Data.AddRow(['Rwanda', -2]);
Chart.Data.AddRow(['Saint Helena', -16]);
Chart.Data.AddRow(['Sรฃo Tomรฉ and Principe', 0]);
Chart.Data.AddRow(['Senegal', 15]);
Chart.Data.AddRow(['Seychelles', -5]);
Chart.Data.AddRow(['Sierra Leone', 8]);
Chart.Data.AddRow(['Somalia', 2]);
Chart.Data.AddRow(['Sudan', 15]);
Chart.Data.AddRow(['South Africa', -30]);
Chart.Data.AddRow(['South Sudan', 5]);
Chart.Data.AddRow(['Swaziland', -26]);
Chart.Data.AddRow(['Tanzania', -6]);
Chart.Data.AddRow(['Togo', 6]);
Chart.Data.AddRow(['Tunisia', 34]);
Chart.Data.AddRow(['Uganda', 1]);
Chart.Data.AddRow(['Western Sahara', 25]);
Chart.Data.AddRow(['Zambia', -15]);
Chart.Data.AddRow(['Zimbabwe', -18]);
// Options
Chart.Options.Region('002'); // Africa
Chart.Options.ColorAxis('colors', '[''#00853f'', ''black'', ''#e31b23'']');
Chart.Options.BackgroundColor('#81d4fa');
Chart.Options.DefaultColor('#f5f5f5');
Chart.Options.DatalessRegionColor('#f8bbd0');
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody('<div id="Chart1" style="width:100%;height:100%;"></div>');
GChartsFrame.DocumentGenerate('Chart1', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_GeoChart_Coloring);
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 ToDoItemTypes;
interface
type
TToDo = class(TObject)
private
FTitle: string;
FContent: string;
public
property Title: string read FTitle write FTitle;
property Content: string read FContent write FContent;
end;
TToDoNames = record
public
const
TitleProperty = 'Title';
ContentProperty = 'Content';
BackendClassname = 'ToDos';
TitleElement = 'title';
ContentElement = 'content';
end;
implementation
end.
|
{: Octree raycast/mesh sample.<p>
Demonstrating how to find the intersection point between eye-screen ray
and a high poly mesh with an Octree property.
To see the performance difference:
-move mouse around on the scene with octree disabled (default)
-check the "octree enabled" box. Note the frame-rate difference.
.<p>
}
unit Unit1;
{$MODE Delphi}
interface
uses
SysUtils, Classes, Controls, Forms,
GLScene, GLVectorFileObjects, GLObjects, GLLCLViewer,
GLCadencer, ExtCtrls, StdCtrls, GLGeomObjects, GLCrossPlatform, GLCoordinates,
GLBaseClasses;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLLightSource1: TGLLightSource;
DummyCube1: TGLDummyCube;
FreeForm1: TGLFreeForm;
Sphere1: TGLSphere;
ArrowLine1: TGLArrowLine;
GLSceneViewer2: TGLSceneViewer;
GLCamera2: TGLCamera;
GLCadencer1: TGLCadencer;
Timer1: TTimer;
Panel1: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label5: TLabel;
LABuild: TLabel;
CheckBox1: TCheckBox;
CBOctree: TCheckBox;
Label4: TLabel;
procedure FormCreate(Sender: TObject);
procedure GLSceneViewer2MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: integer);
procedure GLSceneViewer2MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: integer);
procedure GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: double);
procedure Timer1Timer(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
mousex, mousey: integer;
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
uses GLVectorGeometry, GLVectorLists, GLFile3DS, GLUtils;
procedure TForm1.FormCreate(Sender: TObject);
var
t: int64;
path: UTF8String;
p: integer;
begin
SetGLSceneMediaDir();
// Load high poly mesh (10,000 triangles).
FreeForm1.LoadFromFile('HighPolyObject.3ds');
t := StartPrecisionTimer;
FreeForm1.BuildOctree;
LABuild.Caption := Format('Build time: %.3f ms', [StopPrecisionTimer(t) * 1000]);
with FreeForm1.Octree do
begin
Label1.Caption := 'Octree Nodes: ' + IntToStr(NodeCount);
Label2.Caption := 'Tri Count Octree: ' + IntToStr(TriCountOctree);
Label3.Caption := 'Tri Count Mesh: ' + IntToStr(TriCountMesh);
end;
mousex := -1;
mousey := -1;
end;
procedure TForm1.GLSceneViewer2MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: integer);
var
rayStart, rayVector, iPoint, iNormal: TVector;
t: int64;
begin
SetVector(rayStart, GLCamera2.AbsolutePosition);
SetVector(rayVector, GLSceneViewer2.Buffer.ScreenToVector(
AffineVectorMake(x, GLSceneViewer2.Height - y, 0)));
NormalizeVector(rayVector);
t := StartPrecisionTimer;
if CBOctree.Checked then
begin
// Octree method (fast)
if FreeForm1.OctreeRayCastIntersect(raystart, rayvector, @iPoint, @iNormal) then
begin
Sphere1.Visible := True;
Sphere1.Position.AsVector := iPoint;
Sphere1.Direction.AsVector := VectorNormalize(iNormal);
end
else
Sphere1.Visible := False;
Label4.Hint := '# Nodes hit with raycast: ' + IntToStr(
High(FreeForm1.Octree.ResultArray) + 1);
end
else
begin
// Brute-Force method (slow)
if FreeForm1.RayCastIntersect(rayStart, rayVector, @iPoint, @iNormal) then
begin
Sphere1.Visible := True;
Sphere1.Position.AsVector := iPoint;
Sphere1.Direction.AsVector := VectorNormalize(iNormal);
end
else
Sphere1.Visible := False;
end;
Label5.Hint := Format('Intersect Time: %.3f ms', [StopPrecisionTimer(t) * 1000]);
end;
procedure TForm1.GLSceneViewer2MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: integer);
begin
mousex := x;
mousey := y;
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double);
begin
if CheckBox1.Checked then
GLSceneViewer2MouseDown(Sender, TMouseButton(mbLeft), [ssShift], mousex, mousey);
FreeForm1.RollAngle := 5 * newTime; // 45ยฐ per second
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
// Show FPS Rating
Caption := Format('%.2f FPS', [GLSceneViewer2.FramesPerSecond]);
GLSceneViewer2.ResetPerformanceMonitor;
// Not doing so causes ugly flickering and a significant decrease in FPS...
with Label4 do
Caption := Hint;
with Label5 do
Caption := Hint;
end;
end.
|
unit AppSettings;
{$mode objfpc}{$H+}
//========================================================================================
//
// Unit : AppSettings.pas
//
// Description : Add " SQLiteLibraryName := cstrSQLiteLibraryName; "
//
// Called By : AppInit : Initialize
// Main : TfrmMain.mnuSettingsDIrectoriesClick
// TfrmMain.mnuSettingsDatabasesClick
// SuppliersTable : frmSuppliersTable.CreateSuppliersTable
//
// Calls : HUConstants
//
// Ver. : 1.0.0
//
// Date : 21 Dec 2019
//
//========================================================================================
interface
uses
Buttons, Classes, ComCtrls, Controls, Dialogs, FileUtil, Forms, Graphics, INIFiles,
StdCtrls, SysUtils, Types,
//App Units
SuppliersTable,
// HULib units
HUConstants, HUMessageBoxes;
type
{ TfrmSettings }
TfrmSettings = class(TForm)
bbtCancel: TBitBtn;
bbtOk: TBitBtn;
edtBackupsDirectory: TEdit;
edtAppDataDirectory: TEdit;
edtLogbooksDirectory: TEdit;
edtSettingsDirectory: TEdit;
edtApplicationDirectory: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
pcSettings: TPageControl;
pgDirectories: TTabSheet;
procedure bbtCancelClick(Sender: TObject);
procedure bbtOkClick(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure pgDirectoriesContextPopup(Sender: TObject; MousePos: TPoint;
var Handled: Boolean);
private
fApplicationDirectory : string;
fAppName : string;
fSystemUserDirectory : string;
fUserDirectory : string;
fSettingsDirectory : string;
fLogbooksDirectory : string;
fBackupsDirectory : string;
fAppDataDirectory : string;
fSQLiteLibraryName : string;
fOwnerFirstName : string;
fOwnerLastName : string;
fOwnerCallsign : string;
fOwnerEmailAddress : string;
fOwnerID : string;
function GetApplicationDirectory : string;
procedure SetApplicationDirectory(Dir : string);
function GetAppName : string;
procedure SetAppName(AppName : string);
function GetSystemUserDirectory : string;
procedure SetSystemUserDirectory(Dir : string);
function GetUserDirectory : string;
procedure SetUserDirectory(Dir : string);
function GetSettingsDirectory : string;
procedure SetSettingsDirectory(Dir : string);
function GetLogbooksDirectory : string;
procedure SetLogbooksDirectory(Dir : string);
function GetBackupsDirectory : string;
procedure SetBackupsDirectory(Dir : string);
function GetAppDataDirectory : string;
procedure SetAppDataDirectory(Dir : string);
function GetSQLiteLibraryName : string;
procedure SetSQLiteLibraryName(LibName : string);
function GetOwnerFirstName : string;
procedure SetOwnerFirstName (FirstName : string);
function GetOwnerLastName : string;
procedure SetOwnerLastName (LastName : string);
function GetOwnerCallsign : string;
procedure SetOwnerCallsign (Callsign : string);
function GetOwnerEmailAddress : string;
procedure SetOwnerEmailAddress (EmailAddress : string);
function GetOwnerID : string;
procedure SetOwnerID (OwnerID : string);
public
property pApplicationDirectory : string read GetApplicationDirectory write SetApplicationDirectory;
property pAppName : string read GetAppName write SetAppName;
property pSystemUserDirectory : string read GetSystemUserDirectory write SetSystemUserDirectory;
property pUserDirectory : string read GetUserDirectory write SetUserDirectory;
property pSettingsDirectory : string read GetSettingsDirectory write SetSettingsDirectory;
property pLogbooksDirectory : string read GetLogbooksDirectory write SetLogbooksDirectory;
property pBackupsDirectory : string read GetBackupsDirectory write SetBackupsDirectory;
property pAppDataDirectory : string read GetAppDataDirectory write SetAppDataDirectory;
property pSQLiteLibraryName : string read GetSQLiteLibraryName write SetSQLiteLibraryName;
property pOwnerFirstName : string read GetOwnerFirstName write SetOwnerFirstName;
property pOwnerLastName : string read GetOwnerLastName write SetOwnerLastName;
property pOwnerCallsign : string read GetOwnerCallsign write SetOwnerCallsign;
property pOwnerEmailAddress : string read GetOwnerEmailAddress write SetOwnerEmailAddress;
property pOwnerID : string read GetOwnerID write SetOwnerID;
function UserDataDirectoriesExist : Boolean;
procedure ReadSettingsINIFile;
procedure WriteSettingsINIFile;
function CreateUserDataDirectories : Boolean;
end;// TfrmSettings
//========================================================================================
// PUBLIC CONSTANTS
//========================================================================================
const
//==========
// SQLite
//==========
cstrSQLiteBaseLibraryName = 'sqlite3';
//==========
// MESSAGES
//==========
// Error MEssages
{ erNoDataDirectoriesFound = ' MAJOR ERROR' +
K_CR +
K_CR +
'No Data Directories found.' +
K_CR +
K_CR +
'Is this an Initial installation ?'; }
erCreateUserDataDirFailed = 'Failure Creating User Data Directory';
erCreateUserSettingsDirFailed = 'Failure Creating User Settings Directory';
erCreateUserDirsFailed = 'Failure Creating User Directories';
// Information Messages
imCreateUserDirs = 'Creating User Directories';
{ imNoINIFile = ' The .INI file Does Not Exist.'
+ K_CR
+ ' Is this an Initial installation ?'; }
//==========
// DATA ELEMENTS
//==========
cstrApplicationDBName = 'ApplicationDB';
//========================================================================================
// PUBLIC VARIABLES
//========================================================================================
var
frmSettings: TfrmSettings;
implementation
{$R *.lfm}
uses
Main;
//========================================================================================
// PRIVATE CONSTANTS
//========================================================================================
const
cstrAppName = 'RVMasterLog';
cstrSettingsDirectoryName = 'Settings';
cstrLogbooksDirectoryName = 'Logbooks';
cstrBackupsDirectoryName = 'Backups';
cstrAppDataDirectoryName = 'App Data';
cstrUserDirectoryPath = 'AppData\Roaming\RVMasterLog';
//========================================================================================
// PRIVATE VARIABLES
//========================================================================================
//========================================================================================
// PRIVATE ROUTINES
//========================================================================================
function TfrmSettings.UserDataDirectoriesExist : Boolean;
begin
Result := True;
if not DirectoryExists(pUserDirectory) then
begin
{ if HUErrorMsgYN('erNoDataDirectoriesFound', erNoDataDirectoriesFound) = mrYes then
HUInformationMsgOK('imCreateUserDirs', imCreateUserDirs); }
if not CreateUserDataDirectories then
Result := False;
end;// if UserDataDirectoriesExist(pUserDirectory)
end;// function TfrmAppSetupApplicationDirectoryp.UserFIlesExist
//========================================================================================
function TfrmSettings.CreateUserDataDirectories : Boolean;
var
VStr : string;
begin
// CREATE USER DATA DIRECTORY
pUserDirectory := frmSettings.pSystemUserDirectory + cstrUserDirectoryPath;
if not CreateDir(pUserDirectory) then
begin
// HUErrorMsgYN('erNoDataDirectoriesFound', erNoDataDirectoriesFound);
Result := False;
Main.TerminateApp;
end;// if not CreateDir(pUserDirectory)
// CREATE SETTINGS DIRECTORY
pSettingsDirectory := pUserDirectory + '\' + cstrSettingsDirectoryName;
if not CreateDir(pSettingsDirectory)then
begin
showmessage('SETTINGS DIRECTORY FAILED');
// HUErrorMsgYN('erNoDataDirectoriesFound', erNoDataDirectoriesFound);
Result := False;
Main.TerminateApp;
end;// if not CreateDir(pSettingsDirectory)
// CREATE BACKUPS DIRECTORY
pBackupsDirectory := pUserDirectory + '\' + cstrBackupsDirectoryName;
if not CreateDir(pBackupsDirectory)then
begin
showmessage('BACKUP DIRECTORY FAILED');
Result := False;
Main.TerminateApp;
end;// if not CreateDir(pBackupsDirectory)
// CREATE LOGBOOKS DIRECTORY
pLogbooksDirectory := pUserDirectory + '\' + cstrLogbooksDirectoryName;
if not CreateDir(pLogbooksDirectory)then
begin
showmessage('LOGBOOKS DIRECTORY FAILED');
Result := False;
Main.TerminateApp;
end;// if not CreateDir(pLogbooksDirectory)
// CREATE APPLICATION Database and Tables
pAppDataDirectory := pUserDirectory + '\' + cstrAppDataDirectoryName;
if not CreateDir(pAppDataDirectory)then
begin
showmessage('APPDATADIRECTORY FAILED');
Result := False;
Main.TerminateApp;
end;// if not CreateDir(pAppDataDirectory)
// frmSuppliersTable.CreateSuppliersTable;
Result := True;
end;// function CreateUserDataDirectories
//========================================================================================
// PUBLIC ROUTINES
//========================================================================================
//========================================================================================
// PROPERTY ROUTINES
//========================================================================================
function TfrmSettings.GetApplicationDirectory: string;
begin
Result := fApplicationDirectory;
end;// function TfrmSettings.GetApplicationDirectory
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetApplicationDirectory(Dir: string);
begin
fApplicationDirectory := Dir;
end;// procedure TfrmSettings.SetApplicationDirectory
//========================================================================================
function TfrmSettings.GetAppName: string;
begin
Result := fAppName;
end;// function TfrmSettings.GetAppName
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetAppName(AppName: string);
begin
fAppName := AppName;
end;// procedure TfrmSettings.SetAppName
//========================================================================================
function TfrmSettings.GetUserDirectory: string;
begin
Result := fUserDirectory;
end;// function TfrmSettings.GetUserDirectory
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetUserDirectory(Dir: string);
begin
fUserDirectory := Dir;
end;// procedure TfrmSettings.SetUserDirectory
//========================================================================================
function TfrmSettings.GetSystemUserDirectory: string;
begin
Result := fSystemUserDirectory;
end;// function TfrmSettings.GetSystemUserDirectory
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetSystemUserDirectory(Dir: string);
begin
fSystemUserDirectory := Dir;
end;// procedure TfrmSettings.SetSystemUserDirectory
//========================================================================================
function TfrmSettings.GetSettingsDirectory: string;
begin
Result := fSettingsDirectory;
end;// procedure TfrmSettings.GetAppSettingsDirectory
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetSettingsDirectory(Dir: string);
begin
fSettingsDirectory := Dir;
end;// procedure TfrmSettings.SetAppSettingsDirectory
//========================================================================================
function TfrmSettings.GetLogbooksDirectory: string;
begin
Result := fLogbooksDirectory;
end;// procedure TfrmSettings.GetLogbooksDirectory
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetLogbooksDirectory(Dir: string);
begin
fLogbooksDirectory := Dir;
end;// procedure TfrmSettings.SetLogbooksDirectory
//========================================================================================
function TfrmSettings.GetBackupsDirectory: string;
begin
Result := fBackupsDirectory;
end;// procedure TfrmSettings.GetBackupsDirectory
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetBackupsDirectory(Dir: string);
begin
fBackupsDirectory := Dir;
end;// procedure TfrmSettings.SetBackupsDirectory
//========================================================================================
function TfrmSettings.GetAppDataDirectory: string;
begin
Result := fAppDataDirectory;
end;// procedure TfrmSettings.GetAppDataDirectory
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetAppDataDirectory(Dir: string);
begin
fAppDataDirectory := Dir;
end;// procedure TfrmSettings.SetAppDataDirectory
//========================================================================================
function TfrmSettings.GetSQLiteLibraryName: string;
begin
Result := fSQLiteLibraryName;
end;// procedure TfrmSettings.GetSQLiteLibraryName
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetSQLiteLibraryName(LibName: string);
begin
fSQLiteLibraryName := LibName;
end;// procedure TfrmSettings.SetSQLiteLibraryName
//========================================================================================
function TfrmSettings.GetOwnerFirstName: string;
begin
Result := fOwnerFirstName;
end;// procedure TfrmSettings.GetOwnerFirstName
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetOwnerFirstName(FirstName: string);
begin
fOwnerFirstName := FirstName;
end;// procedure TfrmSettings.SetOwnerFirstName
//========================================================================================
function TfrmSettings.GetOwnerLastName: string;
begin
Result := fOwnerLastName;
end;// procedure TfrmSettings.GetOwnerLastName
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetOwnerLastName(LastName: string);
begin
fOwnerLastName := LastName;
end;// procedure TfrmSettings.SetOwnerLastName
//========================================================================================
function TfrmSettings.GetOwnerCallsign: string;
begin
Result := fOwnerCallsign;
end;// procedure TfrmSettings.GetOwnerCallsign
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetOwnerCallsign(Callsign: string);
begin
fOwnerCallsign := Callsign;
end;// procedure TfrmSettings.SetOwnerCallsign
//========================================================================================
function TfrmSettings.GetOwnerEmailAddress: string;
begin
Result := fOwnerEmailAddress;
end;// procedure TfrmSettings.GetOwnerEmailAddress
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetOwnerEmailAddress(EmailAddress: string);
begin
fOwnerEmailAddress := EMailAddress;
end;// procedure TfrmSettings.SetOwnerEmailAddress
//========================================================================================
function TfrmSettings.GetOwnerID: string;
begin
Result := fOwnerID;
end;// procedure TfrmSettings.GetUserID
//----------------------------------------------------------------------------------------
procedure TfrmSettings.SetOwnerID(OwnerID: string);
begin
fOwnerID := OwnerID;
end;// procedure TfrmSettings.SetOwnerID
//========================================================================================
// MENU ROUTINES
//========================================================================================
//========================================================================================
// COMMAND BUTTON ROUTINES
//========================================================================================
procedure TfrmSettings.bbtCancelClick(Sender: TObject);
begin
end;// procedure TfrmSettings.bbtCancelClick
//----------------------------------------------------------------------------------------
procedure TfrmSettings.bbtOkClick(Sender: TObject);
begin
end;// procedure TfrmSettings.bbtOkClick
//========================================================================================
// CONTROL ROUTINES
//========================================================================================
//========================================================================================
// FILE ROUTINES
//========================================================================================
const
cstrApplicationINIFileName = 'RVMasterLog.ini';
cstrUserDirectories = 'USER DIRECTORIES';
cstrKeyuserDirectory = 'User Directory';
cstrKeySettingsDirectory = 'Settings Directory';
cstrKeyLogbooksDirectory = 'Logbooks Directory';
cstrKeyBackupsDirectory = 'Backups Directory';
cstrKeyAppDataDirectory = 'App Data Directory';
cstrRegistrationData = 'REGISTRATION DATA';
cstrKeyOwnerFirstName = 'Owner First Name';
cstrKeyOwnerLastName = 'Owner Last Name';
cstrKeyOwnerCallsign = 'Owner Callsign';
cstrKeyOwnerEmailAddress = 'Owner Email Address';
cstrKeyOwnerID = 'Owner ID';
var
ApplicationINIFile : TINIFile;
ApplicationINIFileName : string;
//==============================
// SettingsINIFile
//==============================
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
procedure TfrmSettings.ReadSettingsINIFile;
var
vstrTStr : string;
begin
showmessage('ReadSettingsINIFile');
ApplicationINIFileName := pApplicationDirectory + '\' + cstrApplicationINIFileName;
ApplicationINIFile := TINIFile.Create(ApplicationINIFileName);
// DIRECTORY SECTION
// USER Directory
vstrTStr := ApplicationINIFile.ReadString(cstrUserDirectories,
cstrKeyUserDirectory,
pSystemUserDirectory);
pSystemUserDirectory := vstrTStr;
// SETTINGS DIRECTORY
vstrTStr := ApplicationINIFile.ReadString(cstrUserDirectories,
cstrKeySettingsDirectory,
pSettingsDirectory);
pSettingsDirectory := vstrTStr;
// LOGBOOKS DIRECTORY
vstrTStr := ApplicationINIFile.ReadString(cstrUserDirectories,
cstrKeyLogbooksDirectory,
pLogbooksDirectory);
pLogbooksDirectory := vstrTStr;
// BACKUPS DIRECTORY
vstrTStr := ApplicationINIFile.ReadString(cstrUserDirectories,
cstrKeyBackupsDirectory,
pBackupsDirectory);
pBackupsDirectory := vstrTStr;
// APPLICATION DATA DIRECTORY
vstrTStr := ApplicationINIFile.ReadString(cstrUserDirectories,
cstrKeyAppDataDirectory,
pAppDataDirectory);
pAppDataDirectory := vstrTStr;
// REGISTRATION DATA
// Owner First Name
vstrTStr := ApplicationINIFile.ReadString(cstrRegistrationData,
cstrKeyOwnerFirstName,
pOwnerFirstName);
// Owner Last Name
vstrTStr := ApplicationINIFile.ReadString(cstrRegistrationData,
cstrKeyOwnerLastName,
pOwnerLastName);
// Owner Callsign
vstrTStr := ApplicationINIFile.ReadString(cstrRegistrationData,
cstrKeyOwnerCallsign,
pOwnerCallsign);
// Owner Email Address
vstrTStr := ApplicationINIFile.ReadString(cstrRegistrationData,
cstrKeyOwnerEmailAddress,
pOwnerEmailAddress);
// OwnerID
vstrTStr := ApplicationINIFile.ReadString(cstrRegistrationData,
cstrKeyOwnerID,
pOwnerID);
ApplicationINIFile.Free;
end;// procedure TfrmSettings.ReadSettingsINIFile
//----------------------------------------------------------------------------------------
procedure TfrmSettings.WriteSettingsINIFile;
begin
ApplicationINIFileName := pApplicationDirectory + '\' + cstrApplicationINIFileName;
ApplicationINIFile := TINIFile.Create(ApplicationINIFileName);
// DIRECTORY SECTION
// USER Directory
ApplicationINIFile.WriteString(cstrUserDirectories,
cstrKeyUserDirectory,
pUserDirectory);
ApplicationINIFile.WriteString(cstrUserDirectories,
cstrKeySettingsDirectory,
pSettingsDirectory);
ApplicationINIFile.WriteString(cstrUserDirectories,
cstrKeyLogbooksDirectory,
pLogbooksDirectory);
ApplicationINIFile.WriteString(cstrUserDirectories,
cstrKeyBackupsDirectory,
pBackupsDirectory);
ApplicationINIFile.WriteString(cstrUserDirectories,
cstrKeyAppDataDirectory,
pAppDataDirectory);
// REGISTRATION DATA
// Owner First Name
ApplicationINIFile.WriteString(cstrRegistrationData,
cstrKeyOwnerFirstName,
pOwnerFirstName);
// Owner Last Name
ApplicationINIFile.WriteString(cstrRegistrationData,
cstrKeyOwnerLastName,
pOwnerLastName);
// Owner Callsign
ApplicationINIFile.WriteString(cstrRegistrationData,
cstrKeyOwnerCallsign,
pOwnerCallsign);
// Owner Email Address
ApplicationINIFile.WriteString(cstrRegistrationData,
cstrKeyOwnerEmailAddress,
pOwnerEmailAddress);
// OwnerID
ApplicationINIFile.WriteString(cstrRegistrationData,
cstrKeyOwnerID,
pOwnerID);
ApplicationINIFile.Free;
end;// procedure TfrmSettings.WriteSettingsINIFile
//========================================================================================
// FORM ROUTINES
//========================================================================================
procedure TfrmSettings.FormCreate(Sender: TObject);
begin
pSQLiteLibraryName := cstrSQLiteBaseLibraryName;
pAppName := cstrAppName;
pApplicationDirectory := GetCurrentDir;
pSystemUserDirectory := GetUserDir;
pUserDirectory := frmSettings.pSystemUserDirectory + cstrUserDirectoryPath;
pSettingsDirectory := pUserDirectory + '\' + cstrSettingsDirectoryName;
end;// procedure TfrmAppSetup.FormCreate
//----------------------------------------------------------------------------------------
procedure TfrmSettings.FormShow(Sender: TObject);
begin
// Load current properties
edtApplicationDirectory.Text:= pApplicationDirectory;
edtSettingsDirectory.Text:=pSettingsDirectory;
edtLogbooksDirectory.Text:=pLogbooksDirectory;
edtBackupsDirectory.Text := pBackupsDirectory;
edtAppDataDirectory.Text := pAppDataDirectory;
end; // procedure TfrmAppSetup.FormShow
procedure TfrmSettings.pgDirectoriesContextPopup(Sender: TObject;
MousePos: TPoint; var Handled: Boolean);
begin
end;
//----------------------------------------------------------------------------------------
procedure TfrmSettings.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
end;// procedure TfrmAppSetup.FormClose
//========================================================================================
end.// unit AppSettings
|
unit EmployeeEdit;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls,
MaskEdit, EditBtn, Spin, ExtDlgs,
// ะะพะดะบะปััะฐะตะผ ะผะพะดัะปะธ ะฟัะพะตะบัะฐ
Data;
type
{ TForm2 }
TForm2 = class(TForm)
BtnOk: TButton;
BtnCancel: TButton;
EDivision: TComboBox;
EPost: TComboBox;
ComDate: TDateEdit;
EEmployee: TEdit;
ESalary: TEdit;
EPrize: TEdit;
EExperience: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Panel1: TPanel;
procedure ComDateChange(Sender: TObject);
procedure FormShow(Sender: TObject);
private
// ะะตัะพะด-ััะฝะบัะธั ะดะปั ะฟะพะปััะตะฝะธั ะดะฐะฝะฝัั
ะธะท ะบะพะผะฟะพะฝะตะฝั ะฒะฒะพะดะฐ
function GetEmployee: TEmployeeRec;
// ะะตัะพะด-ะฟัะพัะตะดััะฐ ะดะปั ะทะฐะฟะธัะธ ะดะฐะฝะฝัั
ะฒ ะบะพะผะฟะพะฝะตะฝัั ะฒะฒะพะดะฐ
procedure SetEmployee(const AEmployee: TEmployeeRec);
// ะะตัะพะด-ััะฝะบัะธั ะดะปั ะฟัะพะฒะตัะบะธ ะทะฐะฟะพะปะฝะตะฝะธั ะพะฑัะทะฐัะตะปัะฝัั
ะฟะพะปะตะน
function DataIsAll:boolean;
public
// ะกะฒะพะนััะฒะพ-ััััะบัััะฐ ะดะปั ะฟัะตะดััะฐะฒะปะตะฝะธั ะทะฐะฟะธัะธ ะพ ัะพัััะดะฝะธะบะฐั
property EmployeeRec: TEmployeeRec read GetEmployee write SetEmployee;
end;
// ะคัะฝะบัะธั ะดะปั ะพะฑัะฐัะตะฝะธั ะบ ัะพัะผะต ะธะท ะณะปะฐะฒะฝะพะน ัะพัะผั
function ShowEmployeeEdit(const InitialEmployee: TEmployeeRec; var OutEmployee: TEmployeeRec):byte;
var
Form2: TForm2;
implementation
{$R *.lfm}
// ะคัะฝะบัะธั ะดะปั ะพะฑัะฐัะตะฝะธั ะบ ัะพัะผะต ะธะท ะณะปะฐะฒะฝะพะน ัะพัะผั
function ShowEmployeeEdit(const InitialEmployee: TEmployeeRec; var OutEmployee: TEmployeeRec):byte;
begin
// ะกะพะทะดะฐะฝะธะต ัะบะทะตะผะฟะปััะฐ ัะพัะผั
Form2:= TForm2.Create(Application);
with Form2 do
try
// ะฃััะฐะฝะพะฒะบะฐ ะฝะฐัะฐะปัะฝะพะณะพ ะทะฝะฐัะตะฝะธั
EmployeeRec:= InitialEmployee;
// ะัะฒะพะด ัะพัะผั ะฝะฐ ัะบัะฐะฝ ะฒ ะผะพะดะฐะปัะฝะพะผ ัะตะถะธะผะต
ShowModal;
// ะัะพะฒะตัะบะฐ ัะฟะพัะพะฑะฐ ะทะฐะบัััะธั ัะพัะผั
if ModalResult = mrOk then
// ะัะปะธ ัะพัะผะฐ ะทะฐะบัััะฐ ะฝะฐะถะฐัะธะตะผ BtnOk, ั.ะต ะธะทะผะตะฝะตะฝะธั ะฟะพะดัะฒะตัะถะดะตะฝั
begin
OutEmployee:= EmployeeRec; // ะะพะทะฒัะฐัะฐะตะผ ะธะทะผะตะฝะตะฝะฝะพะต ะทะฝะฐัะตะฝะธะต
result:= mrOK; // ะธ ะฟัะธะทะฝะฐะบ ะฟะพะดัะฒะตัะถะดะตะฝะธั (OK)
end
else
// ะัะปะธ ัะพัะผะฐ ะทะฐะบัััะฐ ะปัะฑัะผ ะดััะณะธะผ ัะฟะพัะพะฑะพะผ, ั.ะต ะธะทะผะตะฝะตะฝะธั ะพัะผะตะฝะตะฝั
begin
OutEmployee:= InitialEmployee; // ะะพะทะฒัะฐัะฐะตั ะฟะตัะฒะพะฝะฐัะฐะปัะฝะพะต ะทะฝะฐัะตะฝะธะต
result:= mrCancel; // ะธ ะฟัะธะทะฝะฐะบ ะพัะผะตะฝั (Cansel)
end;
finally
Free; // ะฃะฝะธััะพะถะตะฝะธะต ัะบะทะตะผะฟะปััะฐ ัะพัะผั ะธ ะพัะฒะพะฑะพะถะดะตะฝะธะต ัะตััััะพะฒ
end;
end;
// ะะตัะพะด-ััะฝะบัะธั ะดะปั ะฟัะพะฒะตัะบะธ ะทะฐะฟะพะปะฝะตะฝะธั ะพะฑัะทะฐัะตะปัะฝัั
ะฟะพะปะตะน
function TForm2.DataIsAll:boolean;
begin
if (EEmployee.Text <> '') // ะกะพัััะดะฝะธะบ
then result:= true
else result:= false;
end;
// ะะฑัะฐะฑะพััะธะบ ะธะทะผะตะฝะตะฝะธั ะดะฐะฝะฝัั
ะฒ ะบะพะผะฟะพะฝะตะฝัะฐั
ะฒะฒะพะดะฐ
procedure TForm2.ComDateChange(Sender: TObject);
begin
// ะฃััะฐะฝะพะฒะบะฐ ะดะพัััะฟะฝะพััะธ ะบะฝะพะฟะบะธ ะฟะพะดัะฒะตัะถะดะตะฝะธั
BtnOk.Enabled:=DataIsAll;
end;
// ะะฑัะฐะฑะพััะบะธ ัะพะฑััะธั ะฟะพะบะฐะทะฐ ัะพัะผั
procedure TForm2.FormShow(Sender: TObject);
begin
// ะคะพัะผะธัะพะฒะฐะฝะธะต ะทะฐะณะฐะปะพะฒะบะฐ ัะพัะผั ะธ ะบะฝะพะฟะบะธ BtnOk
if EmployeeRec.Owner = '' then
// ะคะพัะผะฐ ะฒ ัะตะถะธะผะต ะดะพะฑะฐะฒะปะตะฝะธั
begin
// ะขะตะบัั ะทะฐะณะพะปะพะฒะบะฐ ัะพัะผั
Caption:= 'ะะพะฑะฐะฒะธัั ัะพัััะดะฝะธะบะฐ';
// ะะบะพะฝะบะฐ ัะพัะผั
Icon.LoadFromFile(ExtractFilePath(Application.ExeName)+'\addphone.ico');
// ะะฝะพะฟะบะฐ OK
BtnOk.Caption:='ะะพะฑะฐะฒะธัั';
BtnOk.Hint:='ะะพะฑะฐะฒะธัั ัะพัััะดะฝะธะบะฐ ะฒ ัะฟะธัะพะบ';
end
else
// ะคะพัะผะฐ ะฒ ัะตะถะธะผะต ัะตะดะฐะบัะธัะพะฒะฐะฝะธั
begin
// ะขะตะบั ะทะฐะณะพะปะพะฒะบะฐ ัะพัะผั
Caption:= 'ะ ะตะดะฐะบัะธัะพะฒะฐะฝะธะต ะฟะพะปัะทะพะฒะฐัะตะปั';
// ะะบะพะฝะบะฐ ัะพัะผั
Icon.LoadFromFile(ExtractFilePath(Application.ExeName)+'\editphone.ico');
// ะะฝะพะฟะบะฐ OK
BtnOK.Caption:='ะะทะผะตะฝะธัั';
BtnOK.Hint:='ะะทะผะตะฝะธัั ะดะฐะฝะฝัะต ัะพัััะดะฝะธะบะฐ';
end;
// ะะฝะพะฟะบะฐ ะฟะพะดัะฒะตัะถะดะตะฝะธั ะฝะตะดะพัััะฟะฝะฐ, ะฑัะดะตั ะดะพัััะฟะฝะฐ ะฟะพัะปะต ัะตะดะฐะบัะธัะพะฒะฐะฝะธั
// ะธ ะทะฐะฟะพะปะฝะตะฝะธั ะฒัะตั
ะพะฑัะทะฐัะตะปัะฝัั
ะฟะพะปะตะน
BtnOK.Enabled:= False;
end;
// ะะตัะพะด-ััะฝะบัะธะธ ะดะปั ะฟะพะปััะตะฝะธั ะดะฐะฝะฝัั
ะธะท ะบะพะผะฟะพะฝะตะฝั ะฒะฒะพะดะฐ
function TForm2.GetEmployee: TEmployeeRec;
var
EmRec: TEmployeeRec;
begin
with EmRec do
begin
Owner:= EEmployee.Text;
Division:= EDivision.Text;
Post:= EPost.Text;
BirthDay:= ComDate.Date;
Experience:= StrToInt(EExperience.Text);
Salary:= StrToFloat(ESalary.Text);
Prize:= StrToFloat(EPrize.Text);
end;
result:= EmRec;
end;
// ะะตัะพะด-ะฟัะพัะตะดััะฐ ะดะปั ะทะฐะฟะธัะธ ะดะฐะฝะฝัั
ะฒ ะบะพะผะฟะพะฝะตะฝัั ะฒะฒะพะดะฐ
procedure TForm2.SetEmployee(const AEmployee: TEmployeeRec);
begin
with AEmployee do
begin
EEmployee.Text:= Owner;
EDivision.Text:= Division;
EPost.Text:= Post;
ComDate.Date:= BirthDay;
EExperience.Text:= IntToStr(Experience);
ESalary.Text:=FloatToStr(Salary);
EPrize.Text:=FloatToStr(Prize);
end;
end;
end.
|
unit OpenDocumentsView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls,
JvTabBar,
LrOpenDocumentsController;
const
TM_CLOSE = WM_APP + $02;
type
TOpenDocumentsForm = class(TForm)
DocumentTabs: TJvTabBar;
DocumentPanel: TPanel;
procedure FormCreate(Sender: TObject);
procedure DocumentTabsTabClosing(Sender: TObject; Item: TJvTabBarItem;
var AllowClose: Boolean);
procedure DocumentTabsTabSelected(Sender: TObject;
Item: TJvTabBarItem);
procedure DocumentTabsTabClosed(Sender: TObject; Item: TJvTabBarItem);
private
{ Private declarations }
procedure BeginTabsUpdate;
procedure EndTabsUpdate;
procedure OpenDocumentsChange(inSender: TObject);
procedure TMClose(var Message: TMessage); message TM_Close;
procedure UpdateDocumentTabs;
public
{ Public declarations }
end;
var
OpenDocumentsForm: TOpenDocumentsForm;
implementation
{$R *.dfm}
procedure TOpenDocumentsForm.FormCreate(Sender: TObject);
begin
LrOpenDocuments.OnChange := OpenDocumentsChange;
end;
procedure TOpenDocumentsForm.OpenDocumentsChange(inSender: TObject);
begin
UpdateDocumentTabs;
end;
procedure TOpenDocumentsForm.BeginTabsUpdate;
begin
DocumentTabs.OnTabSelected := nil;
DocumentTabs.Tabs.BeginUpdate;
end;
procedure TOpenDocumentsForm.EndTabsUpdate;
begin
DocumentTabs.Tabs.EndUpdate;
DocumentTabs.OnTabSelected := DocumentTabsTabSelected;
end;
procedure TOpenDocumentsForm.UpdateDocumentTabs;
var
i: Integer;
tab: TJvTabBarItem;
begin
BeginTabsUpdate;
with LrOpenDocuments do
try
//DocumentPanel.Visible := Count > 0;
DocumentTabs.Tabs.Clear;
for i := 0 to Pred(Count) do
with Documents[i] do
begin
tab := DocumentTabs.AddTab(DisplayName);
tab.Modified := Modified;
if (SelectedIndex = i) then
DocumentTabs.SelectedTab := tab;
end;
finally
EndTabsUpdate;
end;
end;
procedure TOpenDocumentsForm.DocumentTabsTabSelected(Sender: TObject;
Item: TJvTabBarItem);
begin
LrOpenDocuments.SelectedIndex := Item.Index;
end;
procedure TOpenDocumentsForm.DocumentTabsTabClosing(Sender: TObject;
Item: TJvTabBarItem; var AllowClose: Boolean);
begin
AllowClose := true;
end;
procedure TOpenDocumentsForm.DocumentTabsTabClosed(Sender: TObject;
Item: TJvTabBarItem);
begin
if LrOpenDocuments.BeginCloseCurrent then
PostMessage(Handle, TM_CLOSE, 0, 0);
end;
procedure TOpenDocumentsForm.TMClose(var Message: TMessage);
begin
LrOpenDocuments.EndCloseCurrent;
end;
end.
|
//
// Generated by JavaToPas v1.5 20180804 - 083225
////////////////////////////////////////////////////////////////////////////////
unit android.graphics.ImageDecoder_DecodeException;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
android.graphics.ImageDecoder_Source;
type
JImageDecoder_DecodeException = interface;
JImageDecoder_DecodeExceptionClass = interface(JObjectClass)
['{76570E62-9BD4-469B-BC2E-CAA7A6EBD399}']
function _GetSOURCE_EXCEPTION : Integer; cdecl; // A: $19
function _GetSOURCE_INCOMPLETE : Integer; cdecl; // A: $19
function _GetSOURCE_MALFORMED_DATA : Integer; cdecl; // A: $19
function getError : Integer; cdecl; // ()I A: $1
function getSource : JImageDecoder_Source; cdecl; // ()Landroid/graphics/ImageDecoder$Source; A: $1
property SOURCE_EXCEPTION : Integer read _GetSOURCE_EXCEPTION; // I A: $19
property SOURCE_INCOMPLETE : Integer read _GetSOURCE_INCOMPLETE; // I A: $19
property SOURCE_MALFORMED_DATA : Integer read _GetSOURCE_MALFORMED_DATA; // I A: $19
end;
[JavaSignature('android/graphics/ImageDecoder_DecodeException')]
JImageDecoder_DecodeException = interface(JObject)
['{71BD8D0D-2F4A-46EB-A642-9C300BF4ACB9}']
function getError : Integer; cdecl; // ()I A: $1
function getSource : JImageDecoder_Source; cdecl; // ()Landroid/graphics/ImageDecoder$Source; A: $1
end;
TJImageDecoder_DecodeException = class(TJavaGenericImport<JImageDecoder_DecodeExceptionClass, JImageDecoder_DecodeException>)
end;
const
TJImageDecoder_DecodeExceptionSOURCE_EXCEPTION = 1;
TJImageDecoder_DecodeExceptionSOURCE_INCOMPLETE = 2;
TJImageDecoder_DecodeExceptionSOURCE_MALFORMED_DATA = 3;
implementation
end.
|
{*******************************************************************************
Title: T2TiPDV
Description: Biblioteca de funรงรตes.
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
alberteije@gmail.com
@author T2Ti.COM
@version 2.0
*******************************************************************************}
unit Biblioteca;
{$mode objfpc}{$H+}
interface
uses
SysUtils, Classes, Math;
function TextoParaData(pData: string): TDate;
function DataParaTexto(pData: TDate): string;
Function ArredondaTruncaValor(Operacao: String; Value: Extended; Casas: integer): Extended;
implementation
function TextoParaData(pData: string): TDate;
var
Dia, Mes, Ano: Integer;
begin
if (pData <> '') AND (pData <> '0000-00-00') then
begin
Dia := StrToInt(Copy(pData,9,2));
Mes := StrToInt(Copy(pData,6,2));
Ano := StrToInt(Copy(pData,1,4));
Result := EncodeDate(Ano,Mes,Dia);
end
else
begin
Result := 0;
end;
end;
function DataParaTexto(pData: TDate): string;
begin
if pData > 0 then
Result := FormatDateTime('YYYY-MM-DD',pData)
else
Result := '0000-00-00';
end;
Function ArredondaTruncaValor(Operacao: String; Value: Extended; Casas: integer): Extended;
Var
sValor: String;
nPos: integer;
begin
if Operacao = 'A' then
Result := SimpleRoundTo(Value, Casas * -1)
else
begin
// Transforma o valor em string
sValor := FloatToStr(Value);
// Verifica se possui ponto decimal
nPos := Pos(FormatSettings.DecimalSeparator, sValor);
If (nPos > 0) Then
begin
sValor := Copy(sValor, 1, nPos + Casas);
End;
Result := StrToFloat(sValor);
end;
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Ivory shader simulate Ivory material.
At this time only one light source is supported
}
unit VXS.GLSLIvoryShader;
interface
{$I VXScene.inc}
uses
System.Classes,
VXS.Scene, VXS.CrossPlatform, VXS.BaseClasses, VXS.State, Winapi.OpenGL, Winapi.OpenGLext, VXS.OpenGL1x,
VXS.Context, VXS.RenderContextInfo, VXS.VectorGeometry, VXS.Coordinates,
VXS.TextureFormat, VXS.Color, VXS.Texture, VXS.Material,
GLSL.Shader, VXS.CustomShader;
//TVXCustomGLSLIvoryShader
//
{ Custom class for GLSLIvoryShader.
A shader that simulate Ivory Material }
type
TVXCustomGLSLIvoryShader = class(TVXCustomGLSLShader)
private
protected
procedure DoApply(var rci : TVXRenderContextInfo; Sender : TObject); override;
function DoUnApply(var rci: TVXRenderContextInfo): Boolean; override;
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
end;
type
TVXSLIvoryShader = class(TVXCustomGLSLIvoryShader)
end;
implementation
{ TVXCustomGLSLIvoryShader }
constructor TVXCustomGLSLIvoryShader.Create(AOwner: TComponent);
begin
inherited;
with VertexProgram.Code do
begin
Clear;
Add('varying vec3 normal; ');
Add('varying vec3 lightVec; ');
Add('varying vec3 viewVec; ');
Add(' ');
Add('void main() ');
Add('{ ');
Add(' gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; ');
Add(' vec4 lightPos = gl_LightSource[0].position;');
Add(' vec4 vert = gl_ModelViewMatrix * gl_Vertex; ');
Add(' normal = gl_NormalMatrix * gl_Normal; ');
Add(' lightVec = vec3(lightPos - vert); ');
Add(' viewVec = -vec3(vert); ');
Add('} ');
end;
with FragmentProgram.Code do
begin
Clear;
Add('varying vec3 normal; ');
Add('varying vec3 lightVec; ');
Add('varying vec3 viewVec; ');
Add(' ');
Add('void main() ');
Add('{ ');
Add('vec3 norm = normalize(normal); ');
Add('vec3 L = normalize(lightVec); ');
Add('vec3 V = normalize(viewVec); ');
Add('vec3 halfAngle = normalize(L + V); ');
Add('float NdotL = dot(L, norm); ');
Add('float NdotH = clamp(dot(halfAngle, norm), 0.0, 1.0); ');
Add('// "Half-Lambert" technique for more pleasing diffuse term ');
Add('float diffuse = 0.5 * NdotL + 0.5; ');
Add('float specular = pow(NdotH, 64.0); ');
Add('float result = diffuse + specular; ');
Add('gl_FragColor = vec4(result); ');
Add('} ');
end;
// Initial stuff.
end;
destructor TVXCustomGLSLIvoryShader.Destroy;
begin
inherited;
end;
procedure TVXCustomGLSLIvoryShader.DoApply(var rci: TVXRenderContextInfo;
Sender: TObject);
begin
GetGLSLProg.UseProgramObject;
end;
function TVXCustomGLSLIvoryShader.DoUnApply(
var rci: TVXRenderContextInfo): Boolean;
begin
Result := False;
GetGLSLProg.EndUseProgramObject;
end;
end.
|
// Class 3D Points Detector for Voxel Section Editor III
// Made by Banshee at 01/09/2009
unit ThreeDPointsDetector;
// This class was created to detect repetitive 3D vertices. Use GetIDFromPosition.
// If the Id is the same that you provided, the vertex that you are checking is
// legitimate. Otherwise, it is repetitive with a previous ID that you provided.
interface
uses BasicMathsTypes;
type
P3DPositionDet = ^T3DPositionDet;
T3DPositionDet = record
x, y, z: real;
id: integer;
Next: P3DPositionDet;
end;
C3DPointsDetector = class
private
F3DMap : array of array of array of P3DPositionDet;
public
// Constructors and Destructors
constructor Create(_Size: TVector3i);
destructor Destroy; override;
procedure Initialize;
procedure Clear;
procedure Reset;
// Gets
function GetIDFromPosition(_x, _y, _z: real; _id : integer): integer;
// Adds
function AddPosition(_x, _y, _z: real; _id: integer):P3DPositionDet;
// Deletes
procedure DeleteGroup(var _Element: P3DPositionDet);
end;
implementation
// Constructors and Destructors
constructor C3DPointsDetector.Create(_Size: TVector3i);
begin
SetLength(F3DMap,_Size.X,_Size.Y,_Size.Z);
Initialize;
end;
destructor C3DPointsDetector.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure C3DPointsDetector.Initialize;
var
x,y,z: integer;
begin
for x := Low(F3DMap) to High(F3DMap) do
for y := Low(F3DMap[x]) to High(F3DMap[x]) do
for z := Low(F3DMap[x,y]) to High(F3DMap[x,y]) do
begin
F3DMap[x,y,z] := nil;
end;
end;
procedure C3DPointsDetector.Clear;
var
x,y,z: integer;
begin
for x := Low(F3DMap) to High(F3DMap) do
for y := Low(F3DMap[x]) to High(F3DMap[x]) do
for z := Low(F3DMap[x,y]) to High(F3DMap[x,y]) do
begin
DeleteGroup(F3DMap[x,y,z]);
end;
end;
procedure C3DPointsDetector.Reset;
begin
Clear;
Initialize;
end;
// Gets
function C3DPointsDetector.GetIDFromPosition(_x, _y, _z: real; _id : integer): integer;
var
ix,iy,iz: integer;
Previous,Element : P3DPositionDet;
begin
ix := Trunc(_x);
iy := Trunc(_y);
iz := Trunc(_z);
if F3DMap[ix,iy,iz] <> nil then
begin
Element := F3DMap[ix,iy,iz];
Previous := nil;
while Element <> nil do
begin
if (Element^.x = _x) and (Element^.y = _y) and (Element^.z = _z) then
begin
Result := Element^.id;
exit;
end;
Previous := Element;
Element := Element^.Next;
end;
Element := AddPosition(_x, _y, _z, _id);
Previous^.Next := Element;
Result := _id;
end
else
begin
F3DMap[ix,iy,iz] := AddPosition(_x, _y, _z, _id);
Result := _id;
end;
end;
// Adds
function C3DPointsDetector.AddPosition( _x, _y, _z: real; _id: integer): P3DPositionDet;
begin
new(Result);
Result^.Next := nil;
Result^.id := _id;
Result^.x := _x;
Result^.y := _y;
Result^.z := _z;
end;
// Deletes
procedure C3DPointsDetector.DeleteGroup(var _Element: P3DPositionDet);
begin
if _Element <> nil then
begin
DeleteGroup(_Element^.Next);
Dispose(_Element);
end;
end;
end.
|
unit wordaddons;
interface
{=== ะกัะธะปะธ ะปะธะฝะธะน ัะฐะฑะปะธัั ===}
const wdLineStyleDashDot=5; // A dash followed by a dot.
const wdLineStyleDashDotDot=6; // A dash followed by two dots.
const wdLineStyleDashDotStroked= 20; // A dash followed by a dot stroke, thus rendering a border similar to a barber pole.
const wdLineStyleDashLargeGap= 4; // A dash followed by a large gap.
const wdLineStyleDashSmallGap= 3; // A dash followed by a small gap.
const wdLineStyleDot= 2; // Dots.
const wdLineStyleDouble= 7; // Double solid lines.
const wdLineStyleDoubleWavy= 19; // Double wavy solid lines.
const wdLineStyleEmboss3D= 21; // The border appears to have a 3-D embossed look.
const wdLineStyleEngrave3D= 22; // The border appears to have a 3-D engraved look.
const wdLineStyleInset= 24; // The border appears to be inset.
const wdLineStyleNone= 0; // No border.
const wdLineStyleOutset= 23; // The border appears to be outset.
const wdLineStyleSingle= 1; // A single solid line.
const wdLineStyleSingleWavy= 18; // A single wavy solid line.
const wdLineStyleThickThinLargeGap= 16; // An internal single thick solid line surrounded by a single thin solid line with a large gap between them.
const wdLineStyleThickThinMedGap= 13; // An internal single thick solid line surrounded by a single thin solid line with a medium gap between them.
const wdLineStyleThickThinSmallGap= 10; // An internal single thick solid line surrounded by a single thin solid line with a small gap between them.
const wdLineStyleThinThickLargeGap= 15; // An internal single thin solid line surrounded by a single thick solid line with a large gap between them.
const wdLineStyleThinThickMedGap= 12; // An internal single thin solid line surrounded by a single thick solid line with a medium gap between them.
const wdLineStyleThinThickSmallGap= 9; // An internal single thin solid line surrounded by a single thick solid line with a small gap between them.
const wdLineStyleThinThickThinLargeGap= 17; // An internal single thin solid line surrounded by a single thick solid line surrounded by a single thin solid line with a large gap between all lines.
const wdLineStyleThinThickThinMedGap= 14; // An internal single thin solid line surrounded by a single thick solid line surrounded by a single thin solid line with a medium gap between all lines.
const wdLineStyleThinThickThinSmallGap= 11; // An internal single thin solid line surrounded by a single thick solid line surrounded by a single thin solid line with a small gap between all lines.
const wdLineStyleTriple= 8; // Three solid thin lines.
{=== ะขะพะปัะธะฝะฐ ะปะธะฝะธะน ===}
const wdLineWidth025pt=2; // 0.25 point.
const wdLineWidth050pt=4; // 0.50 point.
const wdLineWidth075pt=6; // 0.75 point.
const wdLineWidth100pt=8; // 1.00 point. default.
const wdLineWidth150pt=12; // 1.50 points.
const wdLineWidth225pt=18; // 2.25 points.
const wdLineWidth300pt=24; // 3.00 points.
const wdLineWidth450pt=36; // 4.50 points.
const wdLineWidth600pt=48; // 6.00 points.
{=== ะัััะพะตะฝะฝัะต ััะธะปะธ ===}
const wdStyleBlockQuotation= -85; // Block Text.
const wdStyleBodyText= -67; // Body Text.
const wdStyleBodyText2= -81; // Body Text 2.
const wdStyleBodyText3= -82; // Body Text 3.
const wdStyleBodyTextFirstIndent= -78; // Body Text First Indent.
const wdStyleBodyTextFirstIndent2= -79; // Body Text First Indent 2.
const wdStyleBodyTextIndent= -68; // Body Text Indent.
const wdStyleBodyTextIndent2= -83; // Body Text Indent 2.
const wdStyleBodyTextIndent3= -84; // Body Text Indent 3.
const wdStyleBookTitle= -265; // Book Title.
const wdStyleCaption= -35; // Caption.
const wdStyleClosing= -64; // Closing.
const wdStyleCommentReference= -40; //Comment Reference.
const wdStyleCommentText= -31; // Comment Text.
const wdStyleDate= -77; // Date.
const wdStyleDefaultParagraphFont= -66; // Default Paragraph Font.
const wdStyleEmphasis= -89; // Emphasis.
const wdStyleEndnoteReference= -43; // Endnote Reference.
const wdStyleEndnoteText= -44; // Endnote Text.
const wdStyleEnvelopeAddress= -37; // Envelope Address.
const wdStyleEnvelopeReturn= -38; // Envelope Return.
const wdStyleFooter= -33; // Footer.
const wdStyleFootnoteReference= -39; // Footnote Reference.
const wdStyleFootnoteText= -30; // Footnote Text.
const wdStyleHeader= -32; // Header.
const wdStyleHeading1= -2; // Heading 1.
const wdStyleHeading2= -3; // Heading 2.
const wdStyleHeading3= -4; // Heading 3.
const wdStyleHeading4= -5; // Heading 4.
const wdStyleHeading5= -6; // Heading 5.
const wdStyleHeading6= -7; // Heading 6.
const wdStyleHeading7= -8; // Heading 7.
const wdStyleHeading8= -9; // Heading 8.
const wdStyleHeading9= -10; //Heading 9.
const wdStyleHtmlAcronym= -96; // HTML Acronym.
const wdStyleHtmlAddress= -97; // HTML Address.
const wdStyleHtmlCite= -98; // HTML Cite.
const wdStyleHtmlCode= -99; // HTML Code.
const wdStyleHtmlDfn= -100; // HTML Definition.
const wdStyleHtmlKbd= -101; // HTML Keyboard.
const wdStyleHtmlNormal= -95; // Normal (Web).
const wdStyleHtmlPre= -102; // HTML Preformatted.
const wdStyleHtmlSamp= -103; // HTML Sample.
const wdStyleHtmlTt= -104; // HTML Typewriter.
const wdStyleHtmlVar= -105; // HTML Variable.
const wdStyleHyperlink= -86; // Hyperlink.
const wdStyleHyperlinkFollowed= -87; // Followed Hyperlink.
const wdStyleIndex1= -11; // Index 1.
const wdStyleIndex2= -12; // Index 2.
const wdStyleIndex3= -13; // Index 3.
const wdStyleIndex4= -14; // Index 4.
const wdStyleIndex5= -15; // Index 5.
const wdStyleIndex6= -16; // Index 6.
const wdStyleIndex7= -17; // Index 7.
const wdStyleIndex8= -18; // Index 8.
const wdStyleIndex9= -19; // Index 9.
const wdStyleIndexHeading= -34; // Index Heading
const wdStyleIntenseEmphasis= -262; // Intense Emphasis.
const wdStyleIntenseQuote= -182; // Intense Quote.
const wdStyleIntenseReference= -264; // Intense Reference.
const wdStyleLineNumber= -41; // Line Number.
const wdStyleList= -48; // List.
const wdStyleList2= -51; // List 2.
const wdStyleList3= -52; // List 3.
const wdStyleList4= -53; // List 4.
const wdStyleList5= -54; // List 5.
const wdStyleListBullet= -49; // List Bullet.
const wdStyleListBullet2= -55; // List Bullet 2.
const wdStyleListBullet3= -56; // List Bullet 3.
const wdStyleListBullet4= -57; // List Bullet 4.
const wdStyleListBullet5= -58; // List Bullet 5.
const wdStyleListContinue= -69; // List Continue.
const wdStyleListContinue2= -70; // List Continue 2.
const wdStyleListContinue3= -71; // List Continue 3.
const wdStyleListContinue4= -72; // List Continue 4.
const wdStyleListContinue5= -73; // List Continue 5.
const wdStyleListNumber= -50; // List Number.
const wdStyleListNumber2= -59; // List Number 2.
const wdStyleListNumber3= -60; // List Number 3.
const wdStyleListNumber4= -61; // List Number 4.
const wdStyleListNumber5= -62; // List Number 5.
const wdStyleListParagraph= -180; // List Paragraph.
const wdStyleMacroText= -46; // Macro Text.
const wdStyleMessageHeader= -74; // Message Header.
const wdStyleNavPane= -90; // Document Map.
const wdStyleNormal= -1; // Normal.
const wdStyleNormalIndent= -29; // Normal Indent.
const wdStyleNormalObject= -158; // Normal (applied to an object).
const wdStyleNormalTable= -106; // Normal (applied within a table).
const wdStyleNoteHeading= -80; // Note Heading.
const wdStylePageNumber= -42; // Page Number.
const wdStylePlainText= -91; // Plain Text.
const wdStyleQuote= -181; // Quote.
const wdStyleSalutation= -76; // Salutation.
const wdStyleSignature= -65; // Signature.
const wdStyleStrong= -88; // Strong.
const wdStyleSubtitle= -75; // Subtitle.
const wdStyleSubtleEmphasis= -261; // Subtle Emphasis.
const wdStyleSubtleReference= -263; // Subtle Reference.
const wdStyleTableColorfulGrid= -172; // Colorful Grid.
const wdStyleTableColorfulList= -171; // Colorful List.
const wdStyleTableColorfulShading= -170; // Colorful Shading.
const wdStyleTableDarkList= -169; // Dark List.
const wdStyleTableLightGrid= -161; // Light Grid.
const wdStyleTableLightGridAccent1= -175; // Light Grid Accent 1.
const wdStyleTableLightList= -160; // Light List.
const wdStyleTableLightListAccent1= -174; // Light List Accent 1.
const wdStyleTableLightShading= -159; // Light Shading.
const wdStyleTableLightShadingAccent1= -173; // Light Shading Accent 1.
const wdStyleTableMediumGrid1= -166; // Medium Grid 1.
const wdStyleTableMediumGrid2= -167; // Medium Grid 2.
const wdStyleTableMediumGrid3= -168; // Medium Grid 3.
const wdStyleTableMediumList1= -164; // Medium List 1.
const wdStyleTableMediumList1Accent1= -178; // Medium List 1 Accent 1.
const wdStyleTableMediumList2= -165; // Medium List 2.
const wdStyleTableMediumShading1= -162; // Medium Shading 1.
const wdStyleTableMediumShading1Accent1= -176; // Medium Shading 1 Accent 1.
const wdStyleTableMediumShading2= -163; // Medium Shading 2.
const wdStyleTableMediumShading2Accent1= -177; // Medium Shading 2 Accent 1.
const wdStyleTableOfAuthorities= -45; // Table of Authorities.
const wdStyleTableOfFigures= -36; // Table of Figures.
const wdStyleTitle= -63; // Title.
const wdStyleTOAHeading= -47; // TOA Heading.
const wdStyleTOC1= -20; // TOC 1.
const wdStyleTOC2= -21; // TOC 2.
const wdStyleTOC3= -22; // TOC 3.
const wdStyleTOC4= -23; // TOC 4.
const wdStyleTOC5= -24; // TOC 5.
const wdStyleTOC6= -25; // TOC 6.
const wdStyleTOC7= -26; // TOC 7.
const wdStyleTOC8= -27; // TOC 8.
const wdStyleTOC9= -28; // TOC 9.
{=== ะจะธัะธะฝะฐ ัะธะผะฒะพะปะพะฒ ===}
const wdWidthFullWidth=7; // Characters are displayed in full character width.
const wdWidthHalfWidth=6; // Characters are displayed in half the character width.
{=== ะััะฐะฒะฝะธะฒะฐะฝะธะต ===}
const wdAlignRowCenter=1; // Centered.
const wdAlignRowLeft=0; // Left-aligned. Default.
const wdAlignRowRight=2; // Right-aligned.
{=== ะะฐะผะตะฝะฐ ===}
const wdReplaceAll=2; // Replace all occurrences.
const wdReplaceNone=0; // Replace no occurrences.
const wdReplaceOne=1; // Replace the first occurrence encountered.
implementation
end.
|
unit htReg;
interface
procedure Register;
implementation
uses
Classes,
htColumns, htRows, htLayout, htAutoTable, htPanel,
htLabel, htImage,
htDb;
{$R TurboHtml5Palette.res}
procedure Register;
begin
RegisterComponents('TurboHtml5', [
ThtColumns, ThtRows, ThtLayout, ThtAutoTable,
ThtPanel, ThtLabel, ThtImage
]);
RegisterComponents('TurboHtml5 DB', [
ThtDb, ThtDbTable
]);
end;
end.
|
unit ufrmJurnal;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ufrmMasterBrowse, cxGraphics,
cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxBarBuiltInMenu, cxStyles,
cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB,
cxDBData, cxContainer, Vcl.ComCtrls, dxCore, cxDateUtils, Vcl.Menus,
System.Actions, Vcl.ActnList, ufraFooter4Button, Vcl.StdCtrls, cxButtons,
cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxLabel, cxGridLevel,
cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, cxPC, Vcl.ExtCtrls, Datasnap.DBClient,
ufrmDialogJurnal, uDXUtils, uAppUtils, uDButils;
type
TfrmJurnal = class(TfrmMasterBrowse)
cxGridViewColumn1: TcxGridDBColumn;
cxGridViewColumn2: TcxGridDBColumn;
cxGridViewColumn3: TcxGridDBColumn;
cxGridViewColumn4: TcxGridDBColumn;
cxGridViewColumn5: TcxGridDBColumn;
cxGridViewColumn6: TcxGridDBColumn;
procedure actAddExecute(Sender: TObject);
procedure actEditExecute(Sender: TObject);
private
FCDS: TClientDataSet;
property CDS: TClientDataSet read FCDS write FCDS;
{ Private declarations }
protected
public
procedure RefreshData; override;
{ Public declarations }
end;
var
frmJurnal: TfrmJurnal;
implementation
{$R *.dfm}
uses uDMClient;
procedure TfrmJurnal.actAddExecute(Sender: TObject);
begin
inherited;
ShowDialogForm(TfrmDialogJurnal)
end;
procedure TfrmJurnal.actEditExecute(Sender: TObject);
begin
inherited;
ShowDialogForm(TfrmDialogJurnal, cxGridView.DS.FieldByName('JURNAL_ID').AsString);
end;
procedure TfrmJurnal.RefreshData;
begin
inherited;
try
TAppUtils.cShowWaitWindow('Mohon Ditunggu');
if Assigned(FCDS) then FreeAndNil(FCDS);
CDS := TDBUtils.DSToCDS(
DMClient.DSProviderClient.Jurnal_GetDSOverview(dtAwalFilter.Date,dtAkhirFilter.Date),
Self
);
cxGridView.LoadFromCDS(FCDS, False, False);
// cxGridView.ApplyBestFit();
finally
TAppUtils.cCloseWaitWindow;
end;
end;
end.
|
unit uFrameGrid;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFrameBaseGrid, cxStyles, cxCustomData, cxGraphics, cxFilter,
cxData, cxDataStorage, cxEdit, DB, cxDBData, ADODB, cxGridLevel,
cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView,
cxGridTableView, cxGridBandedTableView, cxGridDBBandedTableView, cxGrid,
cxGridCardView, cxGridDBCardView, ActnList, Menus, StdCtrls, uMetaData,
cxCurrencyEdit, dxBar, dxPSGlbl,
dxPSUtl, dxPrnPg, dxBkgnd, dxWrap, dxPrnDev, dxPgsDlg, dxPSCore,
dxPrnDlg, dxPSEngn, dxPSDBBasedXplorer, dxPSCompsProvider,
dxPSFillPatterns, dxPSEdgePatterns, dxPScxCommon, dxPScxGrid6Lnk,
cxPropertiesStore, DBTables, ExtCtrls, dxStatusBar, cxInplaceContainer,
cxVGrid, cxDBVGrid, uParams, uCashDataSource, cxtCustomDataSource,
cxtCustomDataSourceM, cxTableViewCds, uCommonUtils;
type
TFrameGrid = class(TFrameBaseGrid)
spUpdate: TADOStoredProc;
spDelete: TADOStoredProc;
pmGrid: TPopupMenu;
miAddRecord: TMenuItem;
miProperties: TMenuItem;
ActionList: TActionList;
actProperties: TAction;
actAddRecord: TAction;
bbShowProps: TdxBarButton;
actShowProps: TAction;
GridVert: TcxDBVerticalGrid;
actLinkObject: TAction;
bbLinkObject: TdxBarButton;
bbLinkObjectDel: TdxBarButton;
actLinkObjectDel: TAction;
pnlLinkObjectHeader: TPanel;
Image_TopHeader: TImage;
lFrameHeader: TLabel;
lFrameDescription: TLabel;
Label1: TLabel;
Label2: TLabel;
dxBarButton1: TdxBarButton;
actAddObjectsToDoc: TAction;
bbAddObjectsToDoc: TdxBarButton;
actShowParentProps: TAction;
bbShowParentProps: TdxBarButton;
actCopyFrom: TAction;
bbCopyFrom: TdxBarButton;
procedure QueryAfterInsert(DataSet: TDataSet);
procedure actPropertiesExecute(Sender: TObject);
procedure actAddRecordExecute(Sender: TObject);
procedure actInsertUpdate(Sender: TObject);
procedure actShowPropsExecute(Sender: TObject);
procedure bbSavePropertyClick(Sender: TObject);
procedure actLinkObjectExecute(Sender: TObject);
procedure actLinkObjectDelExecute(Sender: TObject);
procedure ViewCustomDrawCell(Sender: TcxCustomGridTableView;
ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo;
var ADone: Boolean);
procedure actInsertExecute(Sender: TObject);
procedure actEditExecute(Sender: TObject);
procedure actDeleteExecute(Sender: TObject);
procedure QueryBeforeInsert(DataSet: TDataSet);
procedure ViewChDataControllerAfterPost(
ADataController: TcxCustomDataController);
procedure TimerRecCountTimer(Sender: TObject);
procedure ViewChDataControllerAfterInsert(
ADataController: TcxCustomDataController);
procedure ViewChDataControllerAfterCancel(
ADataController: TcxCustomDataController);
procedure actEditUpdate(Sender: TObject);
procedure ViewChFocusedRecordChanged(Sender: TcxCustomGridTableView;
APrevFocusedRecord, AFocusedRecord: TcxCustomGridRecord;
ANewItemRecordFocusingChanged: Boolean);
procedure ViewChCustomDrawCell(Sender: TcxCustomGridTableView;
ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo;
var ADone: Boolean);
procedure actAddObjectsToDocExecute(Sender: TObject);
procedure actShowParentPropsExecute(Sender: TObject);
procedure actShowParentPropsUpdate(Sender: TObject);
procedure actCopyFromExecute(Sender: TObject);
private
CurRecChecked: boolean;
FOwnerBook: TObject;
FScrollHandled: boolean;
FCardViewPrimaryKey: variant;
FExtendedParams: TParamCollection;
FPrepared: boolean;
FSrollHandled: boolean;
FEmptyOpen: boolean;
FPropertyIDAfterInsert: integer;
FCopyFrom: TCopyFromObjectRecord;
function GetIsCardView: boolean;{Ch}
procedure SetIsCardView(const Value: boolean);{Ch}
procedure SetPrepared(const Value: boolean);{Ch}
protected
PrepareData_WithObjectFields: boolean;
RestoryGrid_DefObjectID: integer;
RestoryGrid_IsDefaultView: boolean;
MarkLinkedObjects: boolean;
InsertFlag: boolean;
MetaData: TMetaDataCollection;
property CopyFrom: TCopyFromObjectRecord read FCopyFrom write FCopyFrom;
procedure HideColumns; virtual;{Ch}
procedure HideRows; virtual;{Ch}
procedure PrepareGridView; virtual;{Ch}
procedure PrepareGridCardView; virtual;{Ch}
procedure OnAddressButtonClick(Sender: TObject; AButtonIndex: Integer); virtual;{B}
procedure OnCardAddressButtonClick(Sender: TObject; AButtonIndex: Integer); virtual;{B}
procedure OnDocumentButtonClick(Sender: TObject; AButtonIndex: Integer); virtual;{B}
procedure OnCardDocumentButtonClick(Sender: TObject; AButtonIndex: Integer); virtual;{B}
procedure OnBookButtonClick(Sender: TObject; AButtonIndex: Integer); virtual;{B}
procedure OnCardBookButtonClick(Sender: TObject; AButtonIndex: Integer); virtual;{B}
procedure PrepareCardData; virtual;{Ch}
function InternalObjectName(AForDelete: boolean = false): string; override;{Ch}
procedure InternalInsertRec; override;{Ch}
procedure InternalEditRec; override;{Ch}
procedure InternalDeleteRec; override; {Ch}
procedure InternalRefreshCurrentRec(UpdateFieldsData: boolean = true); override;{Ch}
procedure InternalRefreshAllRec; override;{Ch}
procedure SetShowExtendedProps(const Value: boolean); override;{Ch}
function GetShowExtendedProps: boolean; override;{Ch}
procedure DoLinkObject; virtual;{Ch}
procedure DoLinkObjectDelete; virtual;{Ch}
procedure DoShowParentProps; virtual; {Ch}
procedure OnHyperCell_ConractNum_Start(Sender: TObject); virtual;
procedure OnHyperCell_ConractTo_Start(Sender: TObject); virtual;
procedure OnHyperCell_ConractFrom_Start(Sender: TObject); virtual;
function ObjectIDForReportMenu: integer; override;
//ะะพะฑะฐะฒะปะตะฝะธะต ะพะฑัะตะบัะฐ ะฒ ัะตะตััั ะดะพะบัะผะตะฝัะพะฒ
//ัะพะพัะฒะตัััะฒะตะฝะฝะพ ะบะฝะพะฟะบะฐ ะดะพะฑะฐะฒะปะตะฝะธั ะฒะธะดะฝะฐ ัะพะปัะบะพ ะดะปั "ะ ะตะตัััะฐ ะดะพะบัะผะตะฝัะพะฒ", sys_ะะฑัะตะบั.ะบะพะด_ะะฑัะตะบั = 450
procedure AddObjectsToDoc; virtual;
public
property CardViewPrimaryKey: variant read FCardViewPrimaryKey write FCardViewPrimaryKey;
property OwnerBook: TObject read FOwnerBook write FOwnerBook;
property ScrollHandled: boolean read FSrollHandled write FScrollHandled;
property IsCardView: boolean read GetIsCardView write SetIsCardView;
property ExtendedParams: TParamCollection read FExtendedParams write FExtendedParams;
property Prepared: boolean read FPrepared write SetPrepared;
property EmptyOpen: boolean read FEmptyOpen write FEmptyOpen;
property PropertyIDAfterInsert: integer read FPropertyIDAfterInsert;
procedure ShowGroupSummary(AVisible: boolean); override;{Ch}
procedure ShowGroupSummaryByMeta(AVisible: boolean);{Ch}
procedure SetExtPropertyVisible(AVisible: boolean); override;{Ch}
function IsExtPropertyExists: boolean; override;{Ch}
function InsertRecord(AGridVert: TcxDBVerticalGrid = nil; PropsForm: TForm = nil; CallFromSimpleGrid: boolean = false; AItemsCreated: boolean = true; AFromObjectByProps: boolean = false): integer; virtual;{}
procedure UpdateRecord(AGridVert: TcxDBVerticalGrid = nil; PropsForm: TForm = nil; AItemsCreated: boolean = true); virtual;{Ch -}
function KeyFieldName: string; virtual;{Ch}
procedure RestoryGrid(DefObjectID: integer = -1; IsDefaultView: boolean = false); override;{Ch}
procedure StoreGrid(DefObjectID: integer = -1; IsDefaultView: boolean = false); override;{Ch}
procedure PrepareData(WithObjectFields: boolean = true; SoftPrepare: boolean = false); virtual;{Ch}
constructor Create(AOwner: TComponent); override;{Ch}
end;
var
FrameGrid: TFrameGrid;
implementation
uses
GlobalVars, uMain, uUserBook, uException, uDlgAddress,
uDlgDocument, cxButtonEdit, uAttributes, cxCalendar, cxTimeEdit, cxBlobEdit,
jpeg, cxDropDownEdit, uAccess, uBASE_ObjectPropsForm, cxGridDBTableView,
uFrameUnitProps, uDlgSelectObjectTypeToLink, uObjectActionsRightHelp, cxHyperLinkEdit,
uDlgContractCard, uDlgContract3Card, uDlgContract2Card,
uDlgOrganizationCard, uDlgSelectObjectsForDocs, uDlgObjectsForDocs;
const
adAffectCurrent = $00000001;
adResyncAllValues = $00000002;
{$R *.dfm}
constructor TFrameGrid.Create(AOwner: TComponent);
begin
inherited;
FExtendedParams:=TParamCollection.Create(TParamItem);
FEmptyOpen:=false;
MarkLinkedObjects:=false;
Query.Connection:=Connection;
spUpdate.Connection:=Connection;
spDelete.Connection:=Connection;
ScrollHandled:=false;
InsertFlag:=false;
end;
function TFrameGrid.InsertRecord(AGridVert: TcxDBVerticalGrid = nil; PropsForm: TForm = nil; CallFromSimpleGrid: boolean = false; AItemsCreated: boolean = true; AFromObjectByProps: boolean = false): integer;
var
i: integer;
col: TcxGridBandedColumnCds;
row: TcxDBEditorRow;
book: TUserBookItem;
ResyncCommand: string;
new_instance: integer;
qry: TAdoQuery;
sql, sql_insfields, sql_insvals: string;
spAddrUpd: TAdoStoredProc;
r: integer;
Flag_IsChildObject: boolean;
FK_UE: integer;
begin
result:=-1;
book:=OwnerBook as TUserBookItem;
if not book.CanAddRecord then
raise Exception.Create('ะะตะปัะทั ะดะพะฑะฐะฒะปััั ะทะฐะฟะธัะธ ะฒ ะพะฑัะตะบั. ะะพะฑะฐะฒะปะตะฝะธะต ะฒะพะทะผะพะถะฝะพ ัะพะปัะบะพ ะฒ ะฝะฐัะปะตะดัะตะผัั
ะพะฑัะตะบัะฐั
');
Connection.BeginTrans;
try
spUpdate.ProcedureName:='sp_ะฐ_'+book.ObjectName+'_ะธะทะผะตะฝะธัั';
spUpdate.Parameters.Refresh;
if AItemsCreated then begin
for i:=1 to spUpdate.Parameters.Count-1 do begin
if spUpdate.Parameters[i].DataType=ftVarBytes then
spUpdate.Parameters[i].DataType:=ftBlob;
if not Assigned(AGridVert) then begin
if (spUpdate.Parameters[i].Name='@IsInsert') or (spUpdate.Parameters[i].Name='@prcDate') or (spUpdate.Parameters[i].Name='@GUID') or (spUpdate.Parameters[i].Name='@RealObjectID') then
continue;
col:=ColumnByParamName(ViewCh, spUpdate.Parameters[i].Name);
if not Assigned(col) then
raise EFieldNotFoundException.Create('ะะต ะฝะฐะนะดะตะฝ ะฟะฐัะฐะผะตัั '+spUpdate.Parameters[i].Name);
if ViewCh.Controller.FocusedRow.IsNewItemRow then begin
r:=ViewCh.DataController.FocusedRecordIndex;
// ViewCh.ViewData.EditingRecord.DisplayTexts
spUpdate.Parameters[i].Value:=ViewCh.Controller.FocusedRow.Values[col.Index]
end
else
spUpdate.Parameters[i].Value:=CurRecItemValue(col.DataBinding.FieldName);
end
else begin
if (spUpdate.Parameters[i].Name='@IsInsert') or (spUpdate.Parameters[i].Name='@prcDate') or (spUpdate.Parameters[i].Name='@GUID') or (spUpdate.Parameters[i].Name='@RealObjectID') then
continue;
row:=RowByParamName(AGridVert, spUpdate.Parameters[i].Name);
if not Assigned(row) then
raise EFieldNotFoundException.Create('ะะต ะฝะฐะนะดะตะฝ ะฟะฐัะฐะผะตัั '+spUpdate.Parameters[i].Name);
spUpdate.Parameters[i].Value:=AGridVert.DataController.DataSet[row.Properties.DataBinding.FieldName];
end;
end;
end;
Flag_IsChildObject:=false;
FK_UE:=0;
qry:=CreateQuery('');
try
sql_insfields:='ForAdoInsertCol,';
sql_insvals:='0,';
if AFromObjectByProps then begin
sql_insfields:=sql_insfields+'ะฒะบ_ะะฐััะพััะธะนะะฑัะตะบัะะปะฐะดะตะปะตั,';
sql_insvals:=sql_insvals+IntToStr(book.ObjectID)+',';
end
else begin
if (dsCh.Fields[3].FieldName='ะฒะบ_ะะฐััะพััะธะนะะฑัะตะบัะะปะฐะดะตะปะตั') then begin
sql_insfields:=sql_insfields+'ะฒะบ_ะะฐััะพััะธะนะะฑัะตะบัะะปะฐะดะตะปะตั,';
sql_insvals:=sql_insvals+IntToStr(book.ObjectID)+',';
end;
if dsCh.Fields[2].FieldName=book.ObjectAlias+'.ะฒะบ_ะ ะพะดะธัะตะปั' then begin
sql_insfields:=sql_insfields+'ะฒะบ_ะ ะพะดะธัะตะปั,';
sql_insvals:=sql_insvals+IntToStr(book.ParentItem.PrimaryKeyValue)+',';
end;
if (dsCh.FieldCount>4) and (dsCh.Fields[4].FieldName='ะฒะบ_ะะฑัะตะบัะ ะพะดะธัะตะปั') then begin
Flag_IsChildObject:=true;
if Assigned(book.ParentItem) then begin
sql_insfields:=sql_insfields+'ะฒะบ_ะะฑัะตะบัะ ะพะดะธัะตะปั,ะฒะบ_ะะฐะฟะธััะะฑัะตะบัะ ะพะดะธัะตะปั,';
sql_insvals:=sql_insvals+IntToStr(book.ParentItem.ObjectID)+','+IntToStr(book.ParentItem.PrimaryKeyValue)+',';
end;
end;
end;
delete(sql_insfields, length(sql_insfields), 1);
delete(sql_insvals, length(sql_insvals), 1);
if Flag_IsChildObject or AFromObjectByProps then
sql:=format('insert into [%s](%s) values(%s) select [%0:s].[ะบะพะด_%0:s], [ะฒะบ_ะกะฒะพะนััะฒะฐ] from [%0:s] where [%0:s].[ะบะพะด_%0:s] = scope_identity()', [book.BaseTableName, sql_insfields, sql_insvals])
else
sql:=format('insert into [%s](%s) values(%s) select scope_identity()', [book.BaseTableName, sql_insfields, sql_insvals]);
qry.SQL.Text:=sql;
qry.Open;
result:=qry.Fields[0].Value;
if Flag_IsChildObject or AFromObjectByProps then
FK_UE:=qry.Fields[1].Value;
FPropertyIDAfterInsert:=FK_UE;
finally
qry.Free;
end;
if Assigned(spUpdate.Parameters.FindParam('@'+book.ObjectAlias+'_ะฒะบ_ะ ะพะดะธัะตะปั')) then
spUpdate.Parameters.ParamByName('@'+book.ObjectAlias+'_ะฒะบ_ะ ะพะดะธัะตะปั').Value:=book.ParentItem.PrimaryKeyValue;
spUpdate.Parameters[1].Value:=result;
spUpdate.Parameters[2].Value:=GetGUID;
spUpdate.Parameters[3].Value:=true;
spUpdate.Parameters[4].Value:=now;
spUpdate.Parameters[5].Value:=book.ObjectID;
spUpdate.ExecProc;
//ะตัะปะธ ะทะฐะฟะธัั - ะพะฑัะตะบั, ัะพ ัััะฐะฝะพะฒะธะผ ะฐะดัะตั ะฟะพ ัะผะพะปัะฐะฝะธั - ะฒะพะทัะผะตะผ ะธะท ัะพะดะธัะตะปั ะฟัะธ ะตะณะพ ะฝะฐะปะธัะธะธ
//ะฟะพัะปะต ะฟะตัะตะดะตะปะบะธ ะพั ะะฝะดัะตั: ะพัะบะปััะธะปะธ ะฒะพะทะผะพะถะฝะพััั ะดะพะฑะฐะฒะปััั ะทะฐะฟะธัั ะธะท ะณัะธะดะฐ (ะฝะฐ 18-04-2009), ะฟะพััะพะผ ััะพั ะบััะพะบ ะฝะต ะฐะบััะฐะปะตะฝ, ะฝะพ ะดะพะปะถะตะฝ ัะฐะฑะพัะฐัั :)
// if (book.IsObject) and (not Assigned(PropsForm)) and (not (VarIsNullMy(Query['ะฒะบ_ะะฑัะตะบัะ ะพะดะธัะตะปั']) or VarIsNullMy(Query['ะฒะบ_ะะฐะฟะธััะะฑัะตะบัะ ะพะดะธัะตะปั']))) then begin
if book.IsObject and (not Assigned(PropsForm)) and Flag_IsChildObject then begin
sql:=format('select * from ะฐัั_ะะดัะตั where ะฒะบ_ะะฑัะตะบั = 163 and ะฒะบ_ะะฐะฟะธััะะฑัะตะบั = %d', [FK_UE]);
qry:=CreateQuery(sql);
try
qry.Open;
spAddrUpd:=TAdoStoredProc.Create(nil);
try
spAddrUpd.Connection:=Connection;
spAddrUpd.ProcedureName:='sp_sys_ะฐัั_ะะดัะตั_ะธะทะผะตะฝะธัั';
spAddrUpd.Parameters.Refresh;
spAddrUpd.Parameters.FindParam('@ะบะพะด_ะะดัะตั').Value:=null;
spAddrUpd.Parameters.FindParam('@ะบะพะด_ะฃะปะธัะฐ').Value:=qry['ะฒะบ_ะฃะปะธัะฐ'];
spAddrUpd.Parameters.FindParam('@ะะฝะดะตะบั').Value:=qry['ะะฝะดะตะบั'];
spAddrUpd.Parameters.FindParam('@ะ_ะดะพะผะฐ').Value:=qry['โ ะดะพะผะฐ'];
spAddrUpd.Parameters.FindParam('@ะะพัะฟัั').Value:=qry['ะะพัะฟัั'];
spAddrUpd.Parameters.FindParam('@ะะธัะตั').Value:=qry['ะะธัะตั'];
spAddrUpd.Parameters.FindParam('@ะ_ะบะฒะฐััะธัั').Value:=qry['โ ะบะฒะฐััะธัั'];
spAddrUpd.Parameters.FindParam('@ะบะพะด_ะะฑัะตะบั').Value:=book.ObjectID;
spAddrUpd.Parameters.FindParam('@ะบะพะด_ะะฐะฟะธััะะฑัะตะบั').Value:=result;
spAddrUpd.ExecProc;
sql:=format('update [ะฃัะตัะฝะฐั ะตะดะธะฝะธัะฐ] set ะะดัะตั = %d where [ะบะพะด_ะฃัะตัะฝะฐั ะตะดะธะฝะธัะฐ] = %d', [integer(spAddrUpd.Parameters.FindParam('@ะบะพะด_ะะดัะตั').Value), FK_UE]);
ExecSQL(sql);
// InternalRefreshCurrentRec(false);
finally
spAddrUpd.Free;
end;
finally
qry.Free;
end;
end;
if Assigned(PropsForm) and (PropsForm is TBASE_ObjectPropsForm) then begin
(PropsForm as TBASE_ObjectPropsForm).UnitPropsFrame.sys_ObjectID:=book.ObjectID;
(PropsForm as TBASE_ObjectPropsForm).UnitPropsFrame.Save([stProps, stAmort, stAmortInfo, stDocs], FK_UE, book.ObjectID, result);
end;
// InternalRefreshCurrentRec();
Connection.CommitTrans;
except
Connection.RollbackTrans;
raise;
end
end;
procedure TFrameGrid.UpdateRecord(AGridVert: TcxDBVerticalGrid = nil; PropsForm: TForm = nil; AItemsCreated: boolean = true);
var
i: integer;
col: TcxGridBandedColumnCds;
row: TcxDBEditorRow;
book: TUserBookItem;
ResyncCommand: string;
frm: TForm;
begin
book:=OwnerBook as TUserBookItem;
Connection.BeginTrans;
try
if Assigned(PropsForm) and (PropsForm is TBASE_ObjectPropsForm) then begin
(PropsForm as TBASE_ObjectPropsForm).UnitPropsFrame.Save;
end;
if AItemsCreated then begin
spUpdate.ProcedureName:='sp_ะฐ_'+book.ObjectName+'_ะธะทะผะตะฝะธัั';
spUpdate.Parameters.Refresh;
for i:=1 to spUpdate.Parameters.Count-1 do begin
if spUpdate.Parameters[i].DataType=ftVarBytes then
spUpdate.Parameters[i].DataType:=ftBlob;
if not Assigned(AGridVert) then begin
if (spUpdate.Parameters[i].Name='@IsInsert') or (spUpdate.Parameters[i].Name='@prcDate') or (spUpdate.Parameters[i].Name='@GUID') or (spUpdate.Parameters[i].Name='@RealObjectID') then
continue;
col:=ColumnByParamName(ViewCh, spUpdate.Parameters[i].Name);
if not Assigned(col) then
raise EFieldNotFoundException.Create('ะะต ะฝะฐะนะดะตะฝ ะฟะฐัะฐะผะตัั '+spUpdate.Parameters[i].Name);
spUpdate.Parameters[i].Value:=CurRecItemValue(col.DataBinding.FieldName);
end
else begin
if (spUpdate.Parameters[i].Name='@IsInsert') or (spUpdate.Parameters[i].Name='@prcDate') or (spUpdate.Parameters[i].Name='@GUID') or (spUpdate.Parameters[i].Name='@RealObjectID') then
continue;
row:=RowByParamName(AGridVert, spUpdate.Parameters[i].Name);
if not Assigned(row) then
raise EFieldNotFoundException.Create('ะะต ะฝะฐะนะดะตะฝ ะฟะฐัะฐะผะตัั '+spUpdate.Parameters[i].Name);
spUpdate.Parameters[i].Value:=AGridVert.DataController.DataSet[row.Properties.DataBinding.FieldName];
end;
end;
spUpdate.Parameters[2].Value:=GetGUID;
spUpdate.Parameters[3].Value:=false;
spUpdate.Parameters[4].Value:=now;
spUpdate.Parameters[5].Value:=CurRecItemValue('ะฒะบ_ะะฐััะพััะธะนะะฑัะตะบัะะปะฐะดะตะปะตั');
spUpdate.ExecProc;
end;
InternalRefreshCurrentRec;
Connection.CommitTrans;
except
Connection.RollbackTrans;
raise;
end
end;
function TFrameGrid.KeyFieldName: string;
var
book: TUserBookItem;
begin
book:=OwnerBook as TUserBookItem;
result:=book.ObjectAlias+'.ะบะพะด_'+book.ObjectName;
end;
procedure TFrameGrid.HideColumns;
var
i, p: integer;
meta: TMetaDataItem;
begin
for i:=0 to ViewCh.ColumnCount-1 do begin
meta:=pointer(ViewCh.Columns[i].Tag);
ViewCh.Columns[i].VisibleForCustomization:=meta.Visible;
ViewCh.Columns[i].Visible:=meta.Visible;
p:=pos('.', ViewCh.Columns[i].Caption);
if p<>0 then
ViewCh.Columns[i].Caption:=copy(ViewCh.Columns[i].Caption, p+1, length(ViewCh.Columns[i].Caption)-p);
end;
end;
procedure TFrameGrid.OnAddressButtonClick(Sender: TObject; AButtonIndex: Integer);
var
frm: TdlgAddress;
col: TcxGridBandedColumnCds;
GroupID: integer;
r: integer;
begin
frm:=TdlgAddress.Create(nil);
try
col:=pointer(TcxButtonEdit(Sender).Properties.Buttons[0].Tag);
// row:=view.Controller.FocusedRow;
r:=ViewCh.DataController.FocusedRecordIndex;
{ if row.IsNewItemRow then begin
if qry.State<>dsInsert then
qry.Insert
end
else}
if not ViewCh.Controller.FocusedRow.IsNewItemRow then
begin
GroupID:=TMetaDataItem(pointer(col.Tag)).GroupID;
col:=ColumnByGroupID(ViewCh, GroupID, '.ะบะพะด_ะฃะปะธัะฐ');
frm.StreetID:=CurRecItemValue(col.DataBinding.FieldName);
col:=ColumnByGroupID(ViewCh, GroupID, '.ะะฝะดะตะบั');
frm.Index:=CurRecItemValue(col.DataBinding.FieldName);
col:=ColumnByGroupID(ViewCh, GroupID, '.โ ะดะพะผะฐ');
frm.House:=CurRecItemValue(col.DataBinding.FieldName);
col:=ColumnByGroupID(ViewCh, GroupID, '.ะะพัะฟัั');
frm.Corpus:=CurRecItemValue(col.DataBinding.FieldName);
col:=ColumnByGroupID(ViewCh, GroupID, '.ะะธัะตั');
frm.Liter:=CurRecItemValue(col.DataBinding.FieldName);
col:=ColumnByGroupID(ViewCh, GroupID, '.โ ะบะฒะฐััะธัั');
frm.Flat:=CurRecItemValue(col.DataBinding.FieldName);
end;
if frm.ShowModal<>mrOK then exit;
GroupID:=TMetaDataItem(pointer(col.Tag)).GroupID;
col:=ColumnByGroupID(ViewCh, GroupID, '.ะ ะฐะนะพะฝ');
ViewCh.DataController.Values[r, col.Index]:=frm.Region;
// qry.FieldByName(col.DataBinding.FieldName).Value:=frm.Region;
col:=ColumnByGroupID(ViewCh, GroupID, '.ะะฐัะตะปะตะฝะฝัะน ะฟัะฝะบั');
ViewCh.DataController.Values[r, col.Index]:=frm.Settlement;
// qry.FieldByName(col.DataBinding.FieldName).Value:=frm.Settlement;
col:=ColumnByGroupID(ViewCh, GroupID, '.ะบะพะด_ะขะธะฟ ัะปะธัั');
ViewCh.DataController.Values[r, col.Index]:=frm.StreetTypeID;
// qry.FieldByName(col.DataBinding.FieldName).Value:=frm.StreetTypeID;
col:=ColumnByGroupID(ViewCh, GroupID, '.ะขะธะฟ');
ViewCh.DataController.Values[r, col.Index]:=frm.StreetType;
// qry.FieldByName(col.DataBinding.FieldName).Value:=frm.StreetType;
col:=ColumnByGroupID(ViewCh, GroupID, '.ะบะพะด_ะฃะปะธัะฐ');
ViewCh.DataController.Values[r, col.Index]:=frm.StreetID;
// qry.FieldByName(col.DataBinding.FieldName).Value:=frm.StreetID;
col:=ColumnByGroupID(ViewCh, GroupID, '.ะฃะปะธัะฐ');
ViewCh.DataController.Values[r, col.Index]:=frm.Street;
// qry.FieldByName(col.DataBinding.FieldName).Value:=frm.Street;
col:=ColumnByGroupID(ViewCh, GroupID, '.ะะฝะดะตะบั');
ViewCh.DataController.Values[r, col.Index]:=frm.Index;
// qry.FieldByName(col.DataBinding.FieldName).Value:=frm.Index;
col:=ColumnByGroupID(ViewCh, GroupID, '.โ ะดะพะผะฐ');
ViewCh.DataController.Values[r, col.Index]:=frm.House;
// qry.FieldByName(col.DataBinding.FieldName).Value:=frm.House;
col:=ColumnByGroupID(ViewCh, GroupID, '.ะะพัะฟัั');
ViewCh.DataController.Values[r, col.Index]:=frm.Corpus;
// qry.FieldByName(col.DataBinding.FieldName).Value:=frm.Corpus;
col:=ColumnByGroupID(ViewCh, GroupID, '.ะะธัะตั');
ViewCh.DataController.Values[r, col.Index]:=frm.Liter;
// qry.FieldByName(col.DataBinding.FieldName).Value:=frm.Liter;
col:=ColumnByGroupID(ViewCh, GroupID, '.โ ะบะฒะฐััะธัั');
ViewCh.DataController.Values[r, col.Index]:=frm.Flat;
// qry.FieldByName(col.DataBinding.FieldName).Value:=frm.Flat;
finally
frm.Free;
end;
end;
procedure TFrameGrid.OnDocumentButtonClick(Sender: TObject; AButtonIndex: Integer);
var
frm: TdlgDocument;
col: TcxGridBandedColumnCds;
row: TcxCustomGridRow;
GroupID: integer;
qry: TAdoQuery;
begin
frm:=TdlgDocument.Create(nil);
try
// grd:=TcxButtonEdit(Sender).Parent.Parent as TcxGrid;
col:=pointer(TcxButtonEdit(Sender).Properties.Buttons[0].Tag);
row:=view.Controller.FocusedRow;
qry:=Query;//view.DataController.DataSource.DataSet as TAdoQuery;
if row.IsNewItemRow then begin
if qry.State<>dsInsert then
qry.Insert
end
else
begin
GroupID:=TMetaDataItem(pointer(col.Tag)).GroupID;
col:=ColumnByGroupID(ViewCh, GroupID, '.ะะพะผะตั');
frm.Num:=qry.FieldByName(col.DataBinding.FieldName).Value;
col:=ColumnByGroupID(ViewCh, GroupID, '.ะะฐัะฐ');
frm.Date:=qry.FieldByName(col.DataBinding.FieldName).Value;
col:=ColumnByGroupID(ViewCh, GroupID, '.ะะฐะธะผะตะฝะพะฒะฐะฝะธะต');
frm.DocName:=qry.FieldByName(col.DataBinding.FieldName).Value;
col:=ColumnByGroupID(ViewCh, GroupID, '.ะบะพะด_ะขะธะฟ ะดะพะบัะผะตะฝัะฐ');
frm.DocTypeID:=qry.FieldByName(col.DataBinding.FieldName).Value;
col:=ColumnByGroupID(ViewCh, GroupID, '.ะกััะปะบะฐ ะฝะฐ ัะฐะนะป');
frm.Link:=qry.FieldByName(col.DataBinding.FieldName).Value;
col:=ColumnByGroupID(ViewCh, GroupID, '.ะัะธะผะตัะฐะฝะธะต');
frm.Comment:=qry.FieldByName(col.DataBinding.FieldName).Value;
qry.Edit;
end;
if frm.ShowModal<>mrOK then exit;
GroupID:=TMetaDataItem(pointer(col.Tag)).GroupID;
col:=ColumnByGroupID(ViewCh, GroupID, '.ะะพะผะตั');
qry.FieldByName(col.DataBinding.FieldName).Value:=frm.Num;
col:=ColumnByGroupID(ViewCh, GroupID, '.ะะฐัะฐ');
qry.FieldByName(col.DataBinding.FieldName).Value:=frm.Date;
col:=ColumnByGroupID(ViewCh, GroupID, '.ะะฐะธะผะตะฝะพะฒะฐะฝะธะต');
qry.FieldByName(col.DataBinding.FieldName).Value:=frm.DocName;
col:=ColumnByGroupID(ViewCh, GroupID, '.ะบะพะด_ะขะธะฟ ะดะพะบัะผะตะฝัะฐ');
qry.FieldByName(col.DataBinding.FieldName).Value:=frm.DocTypeID;
col:=ColumnByGroupID(ViewCh, GroupID, '.ะขะธะฟ ะดะพะบัะผะตะฝัะฐ');
qry.FieldByName(col.DataBinding.FieldName).Value:=frm.DocTypeName;
col:=ColumnByGroupID(ViewCh, GroupID, '.ะกััะปะบะฐ ะฝะฐ ัะฐะนะป');
qry.FieldByName(col.DataBinding.FieldName).Value:=frm.Link;
col:=ColumnByGroupID(ViewCh, GroupID, '.ะัะธะผะตัะฐะฝะธะต');
qry.FieldByName(col.DataBinding.FieldName).Value:=frm.Comment;
finally
frm.Free;
end;
end;
procedure TFrameGrid.OnBookButtonClick(Sender: TObject; AButtonIndex: Integer);
var
GroupID: integer;
meta: TMetaDataItem;
ASF: TAccessSelectorForm;
pk: variant;
v: variant;
atr_id: integer;
atr_name: string;
obj_id: integer;
obj_name: string;
col: TcxGridBandedColumnCds;
r: integer;
begin
ASF:=TAccessSelectorForm.Create;
try
pk:=null;
r:=ViewCh.DataController.FocusedRecordIndex;
col:=pointer(TcxButtonEdit(Sender).Properties.Buttons[0].Tag);
meta:=pointer(col.Tag);
ASF.ObjectID:=meta.Param1;
if not ViewCh.Controller.FocusedRow.IsNewItemRow then
begin
GroupID:=TMetaDataItem(pointer(col.Tag)).GroupID;
col:=ColumnByGroupIDAndFK(ViewCh, GroupID);
pk:=CurRecItemValue(col.DataBinding.FieldName);
end;
if ASF.ShowModal(nil, pk)<>mrOK then exit;
GroupID:=TMetaDataItem(pointer(col.Tag)).GroupID;
col:=ColumnByGroupIDAndFK(ViewCh, GroupID);
dsCh.Values[r, dsCh.FindFieldIndex(col.DataBinding.FieldName)]:=ASF.PrimaryKeyValue;
// Query.FieldByName(col.DataBinding.FieldName).Value:=ASF.PrimaryKeyValue;
col:=pointer(TcxButtonEdit(Sender).Properties.Buttons[0].Tag);
meta:=pointer(col.Tag);
obj_id:=meta.Param1;
atr_id:=meta.Param2;
obj_name:=ExecSQLExpr('select ะัะตะฒะดะพะฝะธะผ from sys_ะะฑัะตะบั where ะบะพะด_ะะฑัะตะบั = '+IntToStr(obj_id));
atr_name:=ExecSQLExpr('select ะัะตะฒะดะพะฝะธะผ from sys_ะััะธะฑัั where ะบะพะด_ะััะธะฑัั = '+IntToStr(atr_id));
dsCh.Values[r, dsCh.FindFieldIndex(col.DataBinding.FieldName)]:=ASF.CurRecordValues[obj_name+'.'+atr_name].Value;
// Query.FieldByName(col.DataBinding.FieldName).Value:=ASF.CurRecordValues[obj_name+'.'+atr_name].Value;
// Query.FieldByName(col.DataBinding.FieldName).Value:=ASF.CurRecordValues[meta.ForeignTableLookupFieldName].Value;
finally
ASF.Free;
end;
end;
procedure TFrameGrid.PrepareData(WithObjectFields: boolean = true; SoftPrepare: boolean = false);
function SetJoinSql(sql: string): string;
var
i: integer;
begin
if pos('ะฒ_ััะตัะฝะฐั ะตะดะธะฝะธัะฐ_ะดะปั_ะพะฑัะตะดะธะฝะตะฝะธั', sql)<>0 then begin
result:=sql;
exit;
end;
result:='';
i:=pos('where', sql);
result:=copy(sql, 1, i-1);
result:=result+'inner join [ะฒ_ััะตัะฝะฐั ะตะดะธะฝะธัะฐ_ะดะปั_ะพะฑัะตะดะธะฝะตะฝะธั] on ะฒะบ_ะกะฒะพะนััะฒะฐ = [ะฃัะตัะฝะฐั ะตะดะธะฝะธัะฐ.ะบะพะด_ะฃัะตัะฝะฐั ะตะดะธะฝะธัะฐ]';
result:=result+copy(sql, i-1, length(sql)-i+1);
end;
var
i: integer;
book: TUserBookItem;
Tables: TTables;
sql, sql_top: string;
Band1, Band2: TcxGridBand;
begin
book:=OwnerBook as TUserBookItem;
//ะะพะฑะฐะฒะปะตะฝะธะต ะพะฑัะตะบัะฐ ะฒ ัะตะตััั ะดะพะบัะผะตะฝัะพะฒ
//ัะพะพัะฒะตัััะฒะตะฝะฝะพ ะบะฝะพะฟะบะฐ ะดะพะฑะฐะฒะปะตะฝะธั ะฒะธะดะฝะฐ ัะพะปัะบะพ ะดะปั "ะ ะตะตัััะฐ ะดะพะบัะผะตะฝัะพะฒ", sys_ะะฑัะตะบั.ะบะพะด_ะะฑัะตะบั = 450
bbAddObjectsToDoc.Visible:=ivNever;
if book.ObjectID=450 then
bbAddObjectsToDoc.Visible:=ivAlways;
if SoftPrepare then begin
self.PrepareData_WithObjectFields:=WithObjectFields;
self.FPrepared:=false;
exit;
end;
if not Prepared then
FPrepared:=true;
actShowProps.Visible:=book.IsObject;
actLinkObject.Visible:=book.IsObject;
actLinkObjectDel.Visible:=book.IsObject;
actShowParentProps.Visible:=book.IsObject;
actCopyFrom.Visible:=book.IsObject;
if not actShowProps.Visible then
WithObjectFields:=false;
if IsCardView then begin
PrepareCardData;
exit;
end;
dsCh.Close;
dsCh.ClearFields;
ViewCh.ClearItems;
ViewCh.Bands.Clear;
ViewCh.Bands.Add;
ViewCh.Bands.Add.Caption:='ะัะฝะพะฒะฝัะต ะฐััะธะฑััั';
Query.AfterScroll:=nil;
if EmptyOpen then sql_top:='top 0';
if book.IsChild then begin
if not WithObjectFields then
Query.SQL.Text:=format('select top 0 * from [ะฒ_%s]', [book.ObjectName])
else
Query.SQL.Text:=SetJoinSql(Query.SQL.Text);
end
else begin
if ((book is TUserBookSubListItem) and (book as TUserBookSubListItem).MainUserBook.AccessManager.WillBeChild) then
sql_top:='top 0'
else
if not EmptyOpen then
sql_top:='';
if not WithObjectFields then
Query.SQL.Text:=format('select %s * from [ะฒ_%s]', [sql_top, book.ObjectName])
else
Query.SQL.Text:=format('select %s * from [ะฒ_%s] inner join [ะฒ_ััะตัะฝะฐั ะตะดะธะฝะธัะฐ_ะดะปั_ะพะฑัะตะดะธะฝะตะฝะธั] on ะฒะบ_ะกะฒะพะนััะฒะฐ = [ะฃัะตัะฝะฐั ะตะดะธะฝะธัะฐ.ะบะพะด_ะฃัะตัะฝะฐั ะตะดะธะฝะธัะฐ]', [sql_top, book.ObjectName]);
end;
//ะพัะผะตัะธะผ ัะฒะตัะพะผ ะทะฐะฟะธัะธ ะบะพัะพััะต ะฟัะธะฒัะทะฐะฝั ะบ ัะพะดะธัะตะปััะบะพะผั ะพะฑัะตะบัั - ะฒ ะพััะธัะพะฒะบะต ะณัะธะดะฐ
self.MarkLinkedObjects:=ExtendedParams.Exists('ะัะผะตัะฐััะัะธะฒัะทะฐะฝะฝัะตะะฑัะตะบัั');
self.pnlLinkObjectHeader.Visible:=self.MarkLinkedObjects;
if ExtendedParams.Exists('where') then
Query.SQL.Add('where '+ExtendedParams['where'].Value);
dsCh.Open;
dsCh.KeyFields:=dsCh.Fields[0].FieldName;
Query.Close;
ViewCh.BeginUpdate;
try
MetaData:=TMetaDataCollection.Create(TMetaDataItem);
MetaData.CreateItems(book.ObjectName, WithObjectFields);
PrepareGridView;
SetColWidth(View);
Tables:=TTables.Create;
try
if not WithObjectFields then begin
Tables.CreateTables(book.ObjectID, true);
CreateViewBands(ViewCh, Tables.Tables[0], ViewCh.Bands[1]);
end
else begin
Tables.CreateTables(book.ObjectID, true);
CreateViewBands(ViewCh, Tables.Tables[0], ViewCh.Bands[1]);
Band2:=ViewCh.Bands.Add;
Band2.Caption:='ะกะฒะพะนััะฒะฐ ััะตัะฝะพะน ะตะดะธะฝะธัั';
Tables.Free;
Tables:=TTables.Create;
Tables.CreateTables(163, true);
CreateViewBands(ViewCh, Tables.Tables[0], Band2);
end;
finally
Tables.Free;
end;
AssignColumnsToBands(ViewCh, ViewCh.Bands[1]);
HideColumns;
MarkFieldChange_AssignEventToColumnCh;
if (OwnerBook is TUserBookSubListItem) then
(OwnerBook as TUserBookSubListItem).RefreshChilds;
self.RestoryGrid(book.ObjectID);
finally
ViewCh.EndUpdate;
end;
end;
procedure TFrameGrid.PrepareGridView;
var
i: integer;
col: TcxGridBandedColumnCds;
qry: TAdoQuery;
begin
for i:=0 to MetaData.Count-1 do begin
col:=ColumnByName(ViewCh, MetaData[i].ColName);
if not Assigned(col) then continue;
col.Tag:=integer(MetaData[i]);
if MetaData[i].AttrType=atAddress then begin
col.PropertiesClass:=TcxButtonEditProperties;
(col.Properties as TcxButtonEditProperties).HideSelection:=false;
(col.Properties as TcxButtonEditProperties).OnButtonClick:=OnAddressButtonClick;
(col.Properties as TcxButtonEditProperties).Buttons[0].Tag:=integer(col);
end;
if MetaData[i].AttrType=atDocument then begin
col.PropertiesClass:=TcxButtonEditProperties;
(col.Properties as TcxButtonEditProperties).HideSelection:=false;
(col.Properties as TcxButtonEditProperties).OnButtonClick:=OnDocumentButtonClick;
(col.Properties as TcxButtonEditProperties).Buttons[0].Tag:=integer(col);
end;
if MetaData[i].AttrType=atInt then begin
col.PropertiesClass:=TcxCurrencyEditProperties;
(col.Properties as TcxCurrencyEditProperties).DecimalPlaces:=0;
(col.Properties as TcxCurrencyEditProperties).DisplayFormat:='0';
end;
if MetaData[i].AttrType=atFloat then begin
col.PropertiesClass:=TcxCurrencyEditProperties;
(col.Properties as TcxCurrencyEditProperties).DecimalPlaces:=MetaData[i].Param2;
(col.Properties as TcxCurrencyEditProperties).DisplayFormat:=',0.'+Zeros(MetaData[i].Param2);
end;
if MetaData[i].AttrType=atDateTime then begin
col.PropertiesClass:=TcxDateEditProperties;
(col.Properties as TcxDateEditProperties).Kind:=ckDateTime;
end;
if MetaData[i].AttrType=atDate then begin
col.PropertiesClass:=TcxDateEditProperties;
end;
if MetaData[i].AttrType=atTime then begin
col.PropertiesClass:=TcxTimeEditProperties;
end;
if MetaData[i].AttrType=atImage then begin
col.PropertiesClass:=TcxBlobEditProperties;
(col.Properties as TcxBlobEditProperties).PictureGraphicClass:=TJPEGImage;
(col.Properties as TcxBlobEditProperties).BlobEditKind:=bekPict;
end;
if MetaData[i].AttrType=atList then begin
col.PropertiesClass:=TcxComboBoxProperties;
qry:=CreateQuery('sp_ะกะฟะธัะพะบ_ะฟะพะปััะธัั @ะบะพะด_ะััะธะฑัั = '+IntToStr(MetaData[i].Param1));
try
qry.Open;
while not qry.Eof do begin
(col.Properties as TcxComboBoxProperties).Items.Add(qry['ะะฝะฐัะตะฝะธะต']);
qry.Next;
end;
finally
qry.Free;
end;
end;
if MetaData[i].AttrType=atBook then begin
col.PropertiesClass:=TcxButtonEditProperties;
(col.Properties as TcxButtonEditProperties).HideSelection:=false;
(col.Properties as TcxButtonEditProperties).OnButtonClick:=OnBookButtonClick;
(col.Properties as TcxButtonEditProperties).Buttons[0].Tag:=integer(col);
end;
if AnsiLowerCase(col.DataBinding.FieldName)='ะดะพะณะพะฒะพั.ะฝะพะผะตั ' then begin
col.PropertiesClass:=TcxHyperLinkEditProperties;
(col.Properties as TcxHyperLinkEditProperties).AutoSelect:=true;
(col.Properties as TcxHyperLinkEditProperties).ReadOnly:=true;
(col.Properties as TcxHyperLinkEditProperties).SingleClick:=true;
(col.Properties as TcxHyperLinkEditProperties).UsePrefix:=upNever;
(col.Properties as TcxHyperLinkEditProperties).OnStartClick:=OnHyperCell_ConractNum_Start;
end;
if AnsiLowerCase(col.DataBinding.FieldName)='ะดะพะณะพะฒะพั.ะบัะพ ะฟะตัะตะดะฐะป ' then begin
col.PropertiesClass:=TcxHyperLinkEditProperties;
(col.Properties as TcxHyperLinkEditProperties).AutoSelect:=true;
(col.Properties as TcxHyperLinkEditProperties).ReadOnly:=true;
(col.Properties as TcxHyperLinkEditProperties).SingleClick:=true;
(col.Properties as TcxHyperLinkEditProperties).UsePrefix:=upNever;
(col.Properties as TcxHyperLinkEditProperties).OnStartClick:=OnHyperCell_ConractFrom_Start;
end;
if AnsiLowerCase(col.DataBinding.FieldName)='ะดะพะณะพะฒะพั.ะบะพะผั ะฟะตัะตะดะฐะปะธ' then begin
col.PropertiesClass:=TcxHyperLinkEditProperties;
(col.Properties as TcxHyperLinkEditProperties).AutoSelect:=true;
(col.Properties as TcxHyperLinkEditProperties).ReadOnly:=true;
(col.Properties as TcxHyperLinkEditProperties).SingleClick:=true;
(col.Properties as TcxHyperLinkEditProperties).UsePrefix:=upNever;
(col.Properties as TcxHyperLinkEditProperties).OnStartClick:=OnHyperCell_ConractTo_Start;
end;
end;
end;
procedure TFrameGrid.QueryAfterInsert(DataSet: TDataSet);
var
book: TUserBookItem;
begin
book:=OwnerBook as TUserBookItem;
if Assigned(book.ParentItem) then
if VarIsNullMy(book.ParentItem.PrimaryKeyValue) then begin
Query.Cancel;
raise ENoParentRowException.Create('ะ ะฝะฐัะฐะปะต ะฝะตะพะฑั
ะพะดะธะผะพ ะดะพะฑะฐะฒะธัั ัะพะดะธัะตะปััะบัั ะทะฐะฟะธัั')
end
else begin
if Query.Fields[2].DisplayName = book.ObjectAlias+'.ะฒะบ_ะ ะพะดะธัะตะปั' then
Query.Fields[2].Value:=book.ParentItem.PrimaryKeyValue
else begin
Query.Fields[4].Value:=book.ParentItem.ObjectID;
Query.Fields[5].Value:=book.ParentItem.PrimaryKeyValue;
end;
end;
InsertFlag:=true;
end;
function TFrameGrid.GetIsCardView: boolean;
begin
result:=GridVert.Visible;
end;
procedure TFrameGrid.SetIsCardView(const Value: boolean);
begin
if Value then begin
GridVert.Visible:=true;
GridVert.Align:=alClient;
Grid.Visible:=false;
end
else begin
GridVert.Visible:=false;
Grid.Visible:=true;
end;
pnlRecCount.Visible:=not Value;
end;
procedure TFrameGrid.PrepareCardData;
var
book: TUserBookItem;
Tables: TTables;
begin
book:=OwnerBook as TUserBookItem;
if book.IsChild then
Query.SQL.Text:=format('select top 1 * from [ะฒ_%s]', [book.ObjectName])
else
if VarIsNull(CardViewPrimaryKey) then
Query.SQL.Text:=format('select * from [ะฒ_%s] where [%s.ะบะพะด_%s] = 0', [book.ObjectName, book.ObjectAlias, book.ObjectName])
else
Query.SQL.Text:=format('select * from [ะฒ_%s] where [%s.ะบะพะด_%s] = %d', [book.ObjectName, book.ObjectAlias, book.ObjectName, integer(CardViewPrimaryKey)]);
Query.CursorLocation:=clUseClient;
Query.CursorType:=ctStatic;
Query.LockType:=ltBatchOptimistic;
Query.Open;
GridVert.BeginUpdate;
try
GridVert.DataController.DataSource:=DataSource;
GridVert.DataController.CreateAllItems;
MetaData:=TMetaDataCollection.Create(TMetaDataItem);
MetaData.CreateItems(book.ObjectName);
PrepareGridCardView;
Tables:=TTables.Create;
try
Tables.CreateTables(book.ObjectID);
CreateRowCategories(GridVert, Tables.Tables[0], nil);
AssignRowsToCategories(GridVert);
finally
Tables.Free;
end;
HideRows;
if Assigned(GridVert.RowByCaption('ForADOInsertCol')) then
GridVert.RowByCaption('ForADOInsertCol').Visible:=false;
finally
GridVert.EndUpdate;
end
end;
procedure TFrameGrid.HideRows;
var
i, p: integer;
meta: TMetaDataItem;
row: TcxDBEditorRow;
begin
for i:=0 to GridVert.Rows.Count-1 do begin
if (not (GridVert.Rows[i] is TcxDBEditorRow)) then continue;
row:=GridVert.Rows[i] as TcxDBEditorRow;
meta:=pointer(row.Tag);
row.Visible:=meta.Visible;
p:=pos('.', row.Properties.Caption);
while p<>0 do begin
if p<>0 then
row.Properties.Caption:=copy(row.Properties.Caption, p+1, length(row.Properties.Caption)-p);
p:=pos('.', row.Properties.Caption);
end
end;
end;
procedure TFrameGrid.PrepareGridCardView;
var
i: integer;
row: TcxDBEditorRow;
qry: TAdoQuery;
begin
for i:=0 to MetaData.Count-1 do begin
row:=RowByName(GridVert, MetaData[i].ColName);
if not Assigned(row) then continue;
row.Tag:=integer(MetaData[i]);
if MetaData[i].AttrType=atAddress then begin
row.Properties.EditPropertiesClass:=TcxButtonEditProperties;
(row.Properties.EditProperties as TcxButtonEditProperties).HideSelection:=false;
(row.Properties.EditProperties as TcxButtonEditProperties).OnButtonClick:=OnCardAddressButtonClick;
(row.Properties.EditProperties as TcxButtonEditProperties).Buttons[0].Tag:=integer(row);
end;
if MetaData[i].AttrType=atDocument then begin
row.Properties.EditPropertiesClass:=TcxButtonEditProperties;
(row.Properties.EditProperties as TcxButtonEditProperties).HideSelection:=false;
(row.Properties.EditProperties as TcxButtonEditProperties).OnButtonClick:=OnCardDocumentButtonClick;
(row.Properties.EditProperties as TcxButtonEditProperties).Buttons[0].Tag:=integer(row);
end;
if MetaData[i].AttrType=atInt then begin
row.Properties.EditPropertiesClass:=TcxCurrencyEditProperties;
(row.Properties.EditProperties as TcxCurrencyEditProperties).DecimalPlaces:=0;
(row.Properties.EditProperties as TcxCurrencyEditProperties).DisplayFormat:='0';
end;
if MetaData[i].AttrType=atFloat then begin
row.Properties.EditPropertiesClass:=TcxCurrencyEditProperties;
(row.Properties.EditProperties as TcxCurrencyEditProperties).DecimalPlaces:=MetaData[i].Param2;
(row.Properties.EditProperties as TcxCurrencyEditProperties).DisplayFormat:=',0.'+Zeros(MetaData[i].Param2);
end;
if MetaData[i].AttrType=atDateTime then begin
row.Properties.EditPropertiesClass:=TcxDateEditProperties;
(row.Properties.EditProperties as TcxDateEditProperties).Kind:=ckDateTime;
end;
if MetaData[i].AttrType=atDate then begin
row.Properties.EditPropertiesClass:=TcxDateEditProperties;
end;
if MetaData[i].AttrType=atTime then begin
row.Properties.EditPropertiesClass:=TcxTimeEditProperties;
end;
if MetaData[i].AttrType=atImage then begin
row.Properties.EditPropertiesClass:=TcxBlobEditProperties;
(row.Properties.EditProperties as TcxBlobEditProperties).PictureGraphicClass:=TJPEGImage;
(row.Properties.EditProperties as TcxBlobEditProperties).BlobEditKind:=bekPict;
end;
if MetaData[i].AttrType=atList then begin
row.Properties.EditPropertiesClass:=TcxComboBoxProperties;
qry:=CreateQuery('sp_ะกะฟะธัะพะบ_ะฟะพะปััะธัั @ะบะพะด_ะััะธะฑัั = '+IntToStr(MetaData[i].Param1));
try
qry.Open;
while not qry.Eof do begin
(row.Properties.EditProperties as TcxComboBoxProperties).Items.Add(qry['ะะฝะฐัะตะฝะธะต']);
qry.Next;
end;
finally
qry.Free;
end;
end;
if MetaData[i].AttrType=atBook then begin
row.Properties.EditPropertiesClass:=TcxButtonEditProperties;
(row.Properties.EditProperties as TcxButtonEditProperties).HideSelection:=false;
(row.Properties.EditProperties as TcxButtonEditProperties).OnButtonClick:=OnCardBookButtonClick;
(row.Properties.EditProperties as TcxButtonEditProperties).Buttons[0].Tag:=integer(row);
(row.Properties.EditProperties as TcxButtonEditProperties).ReadOnly:=true;
end;
if Assigned(row.Properties.EditProperties) then
(row.Properties.EditProperties as TcxCustomEditProperties).Alignment.Horz:=taLeftJustify;
end;
end;
procedure TFrameGrid.actPropertiesExecute(Sender: TObject);
var
book: TUserBookItem;
a: TAccessBook;
begin
a:=TAccessBook.Create;
try
a.ObjectID:=(self.OwnerBook as TUserBookItem).ObjectID;
if (self.OwnerBook is TUserBookSubListItem) then
a.PropsFormClass:=(self.OwnerBook as TUserBookSubListItem).MainUserBook.PropsFormClass;
if a.ShowModal(Query[KeyFieldName], true, false)<>mrOK then exit;
UpdateRecord((a.UserBook as TUserBook).Items[0].FrameGrid.GridVert, (a.UserBook as TUserBook).OwnerForm);
finally
a.Free;
end;
end;
procedure TFrameGrid.OnCardAddressButtonClick(Sender: TObject; AButtonIndex: Integer);
var
frm: TdlgAddress;
row: TcxDBEditorRow;
GroupID: integer;
qry: TAdoQuery;
begin
frm:=TdlgAddress.Create(nil);
try
row:=pointer(TcxButtonEdit(Sender).Properties.Buttons[0].Tag);
qry:=Query;
GroupID:=TMetaDataItem(pointer(row.Tag)).GroupID;
// row:=RowByGroupID(GridVert, GroupID, '.ะบะพะด_ะ ะฐะนะพะฝ');
// frm.RegionID:=qry.FieldByName(row.Properties.DataBinding.FieldName).Value;
// row:=RowByGroupID(GridVert, GroupID, '.ะบะพะด_ะะฐัะตะปะตะฝะฝัะน ะฟัะฝะบั');
// frm.SettlementID:=qry.FieldByName(row.Properties.DataBinding.FieldName).Value;
row:=RowByGroupID(GridVert, GroupID, '.ะบะพะด_ะฃะปะธัะฐ');
frm.StreetID:=qry.FieldByName(row.Properties.DataBinding.FieldName).Value;
row:=RowByGroupID(GridVert, GroupID, '.โ ะดะพะผะฐ');
frm.House:=qry.FieldByName(row.Properties.DataBinding.FieldName).Value;
row:=RowByGroupID(GridVert, GroupID, '.ะะพัะฟัั');
frm.Corpus:=qry.FieldByName(row.Properties.DataBinding.FieldName).Value;
row:=RowByGroupID(GridVert, GroupID, '.ะะธัะตั');
frm.Liter:=qry.FieldByName(row.Properties.DataBinding.FieldName).Value;
row:=RowByGroupID(GridVert, GroupID, '.โ ะบะฒะฐััะธัั');
frm.Flat:=qry.FieldByName(row.Properties.DataBinding.FieldName).Value;
qry.Edit;
if frm.ShowModal<>mrOK then exit;
GroupID:=TMetaDataItem(pointer(row.Tag)).GroupID;
// row:=RowByGroupID(GridVert, GroupID, '.ะบะพะด_ะ ะฐะนะพะฝ');
// qry.FieldByName(row.Properties.DataBinding.FieldName).Value:=frm.RegionID;
row:=RowByGroupID(GridVert, GroupID, '.ะ ะฐะนะพะฝ');
qry.FieldByName(row.Properties.DataBinding.FieldName).Value:=frm.Region;
// row:=RowByGroupID(GridVert, GroupID, '.ะบะพะด_ะะฐัะตะปะตะฝะฝัะน ะฟัะฝะบั');
// qry.FieldByName(row.Properties.DataBinding.FieldName).Value:=frm.SettlementID;
row:=RowByGroupID(GridVert, GroupID, '.ะะฐัะตะปะตะฝะฝัะน ะฟัะฝะบั');
qry.FieldByName(row.Properties.DataBinding.FieldName).Value:=frm.Settlement;
row:=RowByGroupID(GridVert, GroupID, '.ะบะพะด_ะขะธะฟ ัะปะธัั');
qry.FieldByName(row.Properties.DataBinding.FieldName).Value:=frm.StreetTypeID;
row:=RowByGroupID(GridVert, GroupID, '.ะขะธะฟ');
qry.FieldByName(row.Properties.DataBinding.FieldName).Value:=frm.StreetType;
row:=RowByGroupID(GridVert, GroupID, '.ะบะพะด_ะฃะปะธัะฐ');
qry.FieldByName(row.Properties.DataBinding.FieldName).Value:=frm.StreetID;
row:=RowByGroupID(GridVert, GroupID, '.ะฃะปะธัะฐ');
qry.FieldByName(row.Properties.DataBinding.FieldName).Value:=frm.Street;
row:=RowByGroupID(GridVert, GroupID, '.โ ะดะพะผะฐ');
qry.FieldByName(row.Properties.DataBinding.FieldName).Value:=frm.House;
row:=RowByGroupID(GridVert, GroupID, '.ะะพัะฟัั');
qry.FieldByName(row.Properties.DataBinding.FieldName).Value:=frm.Corpus;
row:=RowByGroupID(GridVert, GroupID, '.ะะธัะตั');
qry.FieldByName(row.Properties.DataBinding.FieldName).Value:=frm.Liter;
row:=RowByGroupID(GridVert, GroupID, '.โ ะบะฒะฐััะธัั');
qry.FieldByName(row.Properties.DataBinding.FieldName).Value:=frm.Flat;
finally
frm.Free;
end;
end;
procedure TFrameGrid.OnCardDocumentButtonClick(Sender: TObject; AButtonIndex: Integer);
var
frm: TdlgDocument;
row: TcxDBEditorRow;
GroupID: integer;
qry: TAdoQuery;
begin
frm:=TdlgDocument.Create(nil);
try
row:=pointer(TcxButtonEdit(Sender).Properties.Buttons[0].Tag);
qry:=Query;
GroupID:=TMetaDataItem(pointer(row.Tag)).GroupID;
row:=RowByGroupID(GridVert, GroupID, '.ะะพะผะตั');
frm.Num:=qry.FieldByName(row.Properties.DataBinding.FieldName).Value;
row:=RowByGroupID(GridVert, GroupID, '.ะะฐัะฐ');
frm.Date:=qry.FieldByName(row.Properties.DataBinding.FieldName).Value;
row:=RowByGroupID(GridVert, GroupID, '.ะะฐะธะผะตะฝะพะฒะฐะฝะธะต');
frm.DocName:=qry.FieldByName(row.Properties.DataBinding.FieldName).Value;
row:=RowByGroupID(GridVert, GroupID, '.ะบะพะด_ะขะธะฟ ะดะพะบัะผะตะฝัะฐ');
frm.DocTypeID:=qry.FieldByName(row.Properties.DataBinding.FieldName).Value;
row:=RowByGroupID(GridVert, GroupID, '.ะกััะปะบะฐ ะฝะฐ ัะฐะนะป');
frm.Link:=qry.FieldByName(row.Properties.DataBinding.FieldName).Value;
row:=RowByGroupID(GridVert, GroupID, '.ะัะธะผะตัะฐะฝะธะต');
frm.Comment:=qry.FieldByName(row.Properties.DataBinding.FieldName).Value;
qry.Edit;
if frm.ShowModal<>mrOK then exit;
GroupID:=TMetaDataItem(pointer(row.Tag)).GroupID;
row:=RowByGroupID(GridVert, GroupID, '.ะะพะผะตั');
qry.FieldByName(row.Properties.DataBinding.FieldName).Value:=frm.Num;
row:=RowByGroupID(GridVert, GroupID, '.ะะฐัะฐ');
qry.FieldByName(row.Properties.DataBinding.FieldName).Value:=frm.Date;
row:=RowByGroupID(GridVert, GroupID, '.ะะฐะธะผะตะฝะพะฒะฐะฝะธะต');
qry.FieldByName(row.Properties.DataBinding.FieldName).Value:=frm.DocName;
row:=RowByGroupID(GridVert, GroupID, '.ะบะพะด_ะขะธะฟ ะดะพะบัะผะตะฝัะฐ');
qry.FieldByName(row.Properties.DataBinding.FieldName).Value:=frm.DocTypeID;
row:=RowByGroupID(GridVert, GroupID, '.ะขะธะฟ ะดะพะบัะผะตะฝัะฐ');
qry.FieldByName(row.Properties.DataBinding.FieldName).Value:=frm.DocTypeName;
row:=RowByGroupID(GridVert, GroupID, '.ะกััะปะบะฐ ะฝะฐ ัะฐะนะป');
qry.FieldByName(row.Properties.DataBinding.FieldName).Value:=frm.Link;
row:=RowByGroupID(GridVert, GroupID, '.ะัะธะผะตัะฐะฝะธะต');
qry.FieldByName(row.Properties.DataBinding.FieldName).Value:=frm.Comment;
finally
frm.Free;
end;
end;
procedure TFrameGrid.OnCardBookButtonClick(Sender: TObject; AButtonIndex: Integer);
var
row: TcxDBEditorRow;
GroupID: integer;
meta: TMetaDataItem;
ASF: TAccessSelectorForm;
pk: variant;
v: variant;
begin
ASF:=TAccessSelectorForm.Create;
try
pk:=null;
row:=pointer(TcxButtonEdit(Sender).Properties.Buttons[0].Tag);
meta:=pointer(row.Tag);
ASF.ObjectID:=meta.Param1;
GroupID:=TMetaDataItem(pointer(row.Tag)).GroupID;
row:=RowByGroupIDAndFK(GridVert, GroupID);
pk:=Query[row.Properties.DataBinding.FieldName];
Query.Edit;
if ASF.ShowModal(nil, pk)<>mrOK then exit;
GroupID:=TMetaDataItem(pointer(row.Tag)).GroupID;
row:=RowByGroupIDAndFK(GridVert, GroupID);
Query.FieldByName(row.Properties.DataBinding.FieldName).Value:=ASF.PrimaryKeyValue;
row:=pointer(TcxButtonEdit(Sender).Properties.Buttons[0].Tag);
Query.FieldByName(row.Properties.DataBinding.FieldName).Value:=ASF.CurRecordValues[meta.ForeignTableLookupFieldName].Value;
finally
ASF.Free;
end;
end;
procedure TFrameGrid.actAddRecordExecute(Sender: TObject);
var
book: TUserBookItem;
a: TAccessBook;
begin
a:=TAccessBook.Create;
try
a.ObjectID:=(self.OwnerBook as TUserBookItem).ObjectID;
if a.ShowModal(null, true, true)<>mrOK then exit;
InsertRecord((a.UserBook as TUserBook).Items[0].FrameGrid.GridVert);
finally
a.Free;
end;
end;
procedure TFrameGrid.InternalInsertRec;
var
a: TAccessBook;
book: TUserBookItem;
PGridVert: pointer;
r, new_id: integer;
begin
book:=OwnerBook as TUserBookItem;
if not book.CanAddRecord then
raise Exception.Create('ะะตะปัะทั ะดะพะฑะฐะฒะปััั ะทะฐะฟะธัะธ ะฒ ะพะฑัะตะบั. ะะพะฑะฐะฒะปะตะฝะธะต ะฒะพะทะผะพะถะฝะพ ัะพะปัะบะพ ะฒ ะฝะฐัะปะตะดัะตะผัั
ะพะฑัะตะบัะฐั
');
a:=TAccessBook.Create;
try
a.ObjectID:=(self.OwnerBook as TUserBookItem).ObjectID;
a.RealBook:=OwnerBook;
a.CopyFrom.EnableCopy:=CopyFrom.EnableCopy;
a.CopyFrom.ObjectID:=CopyFrom.ObjectID;
a.CopyFrom.RecordID:=CopyFrom.RecordID;
a.CopyFrom.UEID:=CopyFrom.UEID;
if a.ShowModal(null, true, true)<>mrOK then exit;
PGridVert:=nil;
if (a.UserBook as TUserBook).ItemsCreated then
PGridVert:=(a.UserBook as TUserBook).Items[0].FrameGrid.GridVert;
new_id:=InsertRecord(PGridVert, (a.UserBook as TUserBook).OwnerForm, false, (a.UserBook as TUserBook).ItemsCreated);
r:=ViewCh.DataController.FocusedRecordIndex;
if r<0 then r:=0;
r:=dsCh.InsertRecord(r);
ViewCh.DataController.FocusedRecordIndex:=r;
//ะัะปะธ ะฝะต ะฝัะถะฝั ะธะทะผะตะฝะธั, ะปัััะต ะพัะธััะธัั ะบัั ะธะทะผะตะฝะตะฝะธะน
dsCh.StoreModified.ClearUpdates;
dsCh.CashEdit(r, 0, new_id, true, true);
InternalRefreshCurrentRec();
finally
a.Free;
end;
end;
procedure TFrameGrid.InternalEditRec;
var
a: TAccessBook;
UEid: integer;
book: TUserBookItem;
PGridVert: pointer;
f: TcdField;
r, c: integer;
begin
book:=OwnerBook as TUserBookItem;
a:=TAccessBook.Create;
try
if book.IsObject then begin
if book.FrameGrid.dsCh.Fields[3].FieldName='ะฒะบ_ะะฐััะพััะธะนะะฑัะตะบัะะปะฐะดะตะปะตั' then
a.ObjectID:=book.FrameGrid.CurRecItemValue('ะฒะบ_ะะฐััะพััะธะนะะฑัะตะบัะะปะฐะดะตะปะตั')
else
raise Exception.Create('ะัะธะฑะบะฐ ะฒ procedure TFrameGrid.InternalEditRec. ะะฑัะฐัะธัะตะปั ะบ ัะฐะทัะฐะฑะพััะธะบั');
end
else
a.ObjectID:=book.ObjectID;
if (self.OwnerBook is TUserBookSubListItem) then
if Assigned((self.OwnerBook as TUserBookSubListItem).MainUserBook) then
a.PropsFormClass:=(self.OwnerBook as TUserBookSubListItem).MainUserBook.PropsFormClass;
UEid:=-1;
r:=ViewCh.DataController.FocusedRecordIndex;
if r<0 then exit;
f:=dsCh.FindField('ะฒะบ_ะกะฒะพะนััะฒะฐ');
if Assigned(f) then
UEid:=dsCh.Values[r, f.Index];
if a.ShowModal(dsCh.Values[r, 0], true, false, false, UEid)<>mrOK then exit;
PGridVert:=nil;
if (a.UserBook as TUserBook).ItemsCreated then
PGridVert:=(a.UserBook as TUserBook).Items[0].FrameGrid.GridVert;
UpdateRecord(PGridVert, (a.UserBook as TUserBook).OwnerForm, (a.UserBook as TUserBook).ItemsCreated);
InternalRefreshCurrentRec;
finally
a.Free;
end;
end;
procedure TFrameGrid.InternalDeleteRec;
var
sr: TViewSelectedRecords;
sp: TADOStoredProc;
i: integer;
st: string;
begin
sr:=TViewSelectedRecords.Create(ViewCh);
try
st:='ะฃะดะฐะปะธัั ะบะพะปะธัะตััะฒะพ ะทะฐะฟะธัะตะน: '+IntToStr(sr.Count)+'?';
if MessageBox(Application.Handle, pchar(st), 'ะฃะดะฐะปะตะฝะธะต', MB_YESNO or MB_ICONQUESTION or MB_APPLMODAL) <> IDYES then exit;
ViewCh.BeginUpdate;
try
sp:=TADOStoredProc.Create(nil);
sp.Connection:=frmMain.ADOConnection;
if InternalDeleteStoredProcName='' then
sp.ProcedureName:=format('sp_ะฐ_%s_ัะดะฐะปะธัั', [InternalObjectName(true)])
else
sp.ProcedureName:=InternalDeleteStoredProcName;
sp.Parameters.Refresh;
sp.Parameters[1].Value:=sr.AsString;
frmMain.ADOConnection.BeginTrans;
try
sp.ExecProc;
frmMain.ADOConnection.CommitTrans;
for i:=sr.Count-1 downto 0 do
dsCh.DeleteRecord(sr.Items[i].RecordIndex);
except
frmMain.ADOConnection.RollbackTrans;
raise;
end;
finally
ViewCh.EndUpdate;
end;
finally
sr.Free;
end;
end;
procedure TFrameGrid.InternalRefreshAllRec;
begin
InternalRefreshAllRecCh();
end;
procedure TFrameGrid.InternalRefreshCurrentRec(UpdateFieldsData: boolean = true);
var
book: TUserBookItem;
ResyncCommand: string;
begin
if IsCardView then exit;
book:=OwnerBook as TUserBookItem;
if (not book.IsObject) or (not self.ShowExtendedProps) then
ResyncCommand:=format('select * from [ะฒ_%s] where [%s.ะบะพะด_%s] = %d', [book.ObjectName, book.ObjectAlias, book.ObjectName, integer(CurRecPKValue)])
else
ResyncCommand:=format('select * from [ะฒ_%s] inner join [ะฒ_ััะตัะฝะฐั ะตะดะธะฝะธัะฐ_ะดะปั_ะพะฑัะตะดะธะฝะตะฝะธั] on ะฒะบ_ะกะฒะพะนััะฒะฐ = [ะฃัะตัะฝะฐั ะตะดะธะฝะธัะฐ.ะบะพะด_ะฃัะตัะฝะฐั ะตะดะธะฝะธัะฐ] where [%s.ะบะพะด_%s] = %d', [book.ObjectName, book.ObjectAlias, book.ObjectName, integer(CurRecPKValue)]);
InternalRefreshCurrentCash(ResyncCommand, ViewCh);
end;
procedure TFrameGrid.actInsertUpdate(Sender: TObject);
var
pi: TUserBookItem;
begin
inherited;
pi:=(OwnerBook as TUserBookItem).ParentItem;
if Assigned(pi) then
(Sender as TAction).Enabled:=not VarIsNullMy(pi.PrimaryKeyValue)
else
(Sender as TAction).Enabled:=true;
end;
procedure TFrameGrid.SetShowExtendedProps(const Value: boolean);
begin
inherited;
self.PrepareData(Value, false);
end;
procedure TFrameGrid.actShowPropsExecute(Sender: TObject);
begin
inherited;
ShowExtendedProps:=bbShowProps.Down;
end;
procedure TFrameGrid.ShowGroupSummaryByMeta(AVisible: boolean);
var
i: integer;
col: TcxGridBandedColumnCds;
sm: TcxGridDBTableSummaryItem;
si: TcxGridTableSummaryItem;
begin
ViewCh.DataController.Summary.DefaultGroupSummaryItems.Clear;
if AVisible then
for i:=0 to MetaData.Count-1 do begin
col:=ColumnByName(ViewCh, MetaData[i].ColName);
if not Assigned(col) then continue;
if MetaData[i].AttrType in [atFloat, atInt] then begin
si:=ViewCh.DataController.Summary.DefaultGroupSummaryItems.Add as TcxGridTableSummaryItem;
si.Column:=col;
si.Kind:=skSum;
si.Format:=',0.####';
end;
end;
end;
function TFrameGrid.GetShowExtendedProps: boolean;
begin
result:=self.bbShowProps.Down;
end;
procedure TFrameGrid.ShowGroupSummary(AVisible: boolean);
begin
ShowGroupSummaryByMeta(AVisible);
end;
procedure TFrameGrid.SetExtPropertyVisible(AVisible: boolean);
begin
if bbShowProps.Down = AVisible then exit;
bbShowProps.Down:= AVisible;
actShowPropsExecute(nil);
end;
function TFrameGrid.IsExtPropertyExists: boolean;
begin
result:= bbShowProps.Down;
end;
function TFrameGrid.InternalObjectName(AForDelete: boolean = false): string;
var
MainObjectID: integer;
begin
if not AForDelete then
result:=(OwnerBook as TUserBookItem).ObjectName
else begin
if (OwnerBook as TUserBookItem).IsObject then begin
MainObjectID:=ExecSQLExpr(format('select dbo.f_ะะพะดะะปะฐะฒะฝะพะณะพะ ะพะดะธัะตะปั(%d)', [(OwnerBook as TUserBookItem).ObjectID]));
result:=ExecSQLExpr(format('select dbo.f_ะะผัะะฑัะตะบัะฐ(%d)', [MainObjectID]));
end
else
result:=(OwnerBook as TUserBookItem).ObjectName
end;
end;
procedure TFrameGrid.bbSavePropertyClick(Sender: TObject);
begin
self.StoreGrid((OwnerBook as TUserBookItem).ObjectID);
end;
procedure TFrameGrid.actLinkObjectExecute(Sender: TObject);
begin
inherited;
DoLinkObject;
end;
procedure TFrameGrid.DoLinkObject;
var
dlg: TdlgSelectObjectTypeToLink;
a: TAccessBook;
sr, st: string;
r: integer;
begin
r:=ViewCh.DataController.FocusedRecordIndex;
if r<0 then exit;
dlg:=TdlgSelectObjectTypeToLink.Create(nil);
try
dlg.ObjectID:=(OwnerBook as TUserBookItem).ObjectID;
if dlg.ShowModal<>mrOK then exit;
a:=TAccessBook.Create;
try
a.ObjectID:=dlg.SelectedObjectID;
a.ExtendedParams['ะัะผะตัะฐััะัะธะฒัะทะฐะฝะฝัะตะะฑัะตะบัั'].Value:='ะดะฐ';
a.ExtendedParams['where'].Value:=format('(ะฒะบ_ะะฑัะตะบัะ ะพะดะธัะตะปั is null) or not (ะฒะบ_ะะฑัะตะบัะ ะพะดะธัะตะปั=%d and ะฒะบ_ะะฐะฟะธััะะฑัะตะบัะ ะพะดะธัะตะปั=%d)', [(OwnerBook as TUserBookItem).ObjectID, integer(dsCh.Values[r, 0])]);
if a.ShowModal(null, false, false)<>mrOK then exit;
sr:=a.SelectedRecords.AsString;
if sr='' then exit;
st:=format('sp_ะะฑัะตะบั_ะัะธะฒัะทะฐัั @ะบะพะด_ะะฑัะตะบั = %d, @ะะพะดัะะฐะฟะธัะตะน = ''%s'', @ะบะพะด_ะะฑัะตะบัะัะธะฒัะทะฐััะ = %d, @ะะพะดะะฐะฟะธัะธะัะธะฒัะทะฐััะ = %d', [integer(dlg.SelectedObjectID), sr, (OwnerBook as TUserBookItem).ObjectID, integer(dsCh.Values[r, 0])]);
try
ScreenCursor.IncCursor;
ExecSQL(st);
finally
ScreenCursor.DecCursor;
end;
finally
a.Free;
end;
finally
dlg.Free;
end;
end;
procedure TFrameGrid.DoLinkObjectDelete;
var
sr: TViewSelectedRecords;
st: string;
begin
sr:=TViewSelectedRecords.Create(ViewCh);
try
st:='ะัะผะตะฝะธัั ะฟัะธะฒัะทะบั ะพะฑัะตะบัะฐ ะบ ะฒะปะฐะดะตะปััั, ะบะพะปะธัะตััะฒะพ: '+IntToStr(sr.Count)+'?';
if MessageBox(Application.Handle, pchar(st), 'ะฃะดะฐะปะตะฝะธะต', MB_YESNO or MB_ICONQUESTION or MB_APPLMODAL) <> IDYES then exit;
st:=format('sp_ะะฑัะตะบั_ะัะฒัะทะฐัั @ะบะพะด_ะะฑัะตะบั = %d, @ะะพะดัะะฐะฟะธัะตะน = ''%s''', [(OwnerBook as TUserBookItem).ObjectID, sr.AsString]);
try
ScreenCursor.IncCursor;
ExecSQL(st);
InternalRefreshAllRec;
finally
ScreenCursor.DecCursor;
end;
finally
sr.Free;
end;
end;
procedure TFrameGrid.actLinkObjectDelExecute(Sender: TObject);
begin
inherited;
DoLinkObjectDelete;
end;
procedure TFrameGrid.ViewCustomDrawCell(Sender: TcxCustomGridTableView;
ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo;
var ADone: Boolean);
begin
inherited;
if self.MarkLinkedObjects then
if not VarIsNullMy(Sender.DataController.Values[AViewInfo.GridRecord.Index, 4]) then
ACanvas.Font.Color:=clGray;
end;
procedure TFrameGrid.actInsertExecute(Sender: TObject);
begin
if not ObjActionsRightHelper.Right((OwnerBook as TUserBookItem).ObjectID, raInsert) then
raise EAccessException.Create('ะะต ะดะพััะฐัะพัะฝะพ ะฟัะฐะฒ ะฝะฐ ะดะพะฑะฐะฒะปะตะฝะธะต ะทะฐะฟะธัะธ');
inherited;
end;
procedure TFrameGrid.actEditExecute(Sender: TObject);
begin
if not ObjActionsRightHelper.Right((OwnerBook as TUserBookItem).ObjectID, raUpdate) then
raise EAccessException.Create('ะะต ะดะพััะฐัะพัะฝะพ ะฟัะฐะฒ ะฝะฐ ะธะทะผะตะฝะตะฝะธะต ะทะฐะฟะธัะธ');
inherited;
end;
procedure TFrameGrid.actDeleteExecute(Sender: TObject);
begin
if not ObjActionsRightHelper.Right((OwnerBook as TUserBookItem).ObjectID, raDelete) then
raise EAccessException.Create('ะะต ะดะพััะฐัะพัะฝะพ ะฟัะฐะฒ ะฝะฐ ัะดะฐะปะตะฝะธะต ะทะฐะฟะธัะธ');
inherited;
end;
procedure TFrameGrid.QueryBeforeInsert(DataSet: TDataSet);
begin
{ if not ObjActionsRightHelper.Right((OwnerBook as TUserBookItem).ObjectID, 2) then
raise EAccessException.Create('ะะตะดะพััะฐัะพัะฝะพ ะฟัะฐะฒ ะฝะฐ ะดะพะฑะฐะฒะปะตะฝะธะต ะทะฐะฟะธัะธ');}
inherited;
end;
procedure TFrameGrid.SetPrepared(const Value: boolean);
begin
if not value then
exit;
self.PrepareData(self.PrepareData_WithObjectFields, false);
FPrepared := true;
end;
procedure TFrameGrid.RestoryGrid(DefObjectID: integer; IsDefaultView: boolean);
var
book: TUserBookItem;
begin
inherited RestoryGrid((OwnerBook as TUserBookItem).ObjectID, IsDefaultView);
end;
procedure TFrameGrid.StoreGrid(DefObjectID: integer; IsDefaultView: boolean);
begin
inherited StoreGrid((OwnerBook as TUserBookItem).ObjectID, IsDefaultView);
end;
procedure TFrameGrid.ViewChDataControllerAfterPost(
ADataController: TcxCustomDataController);
begin
if InsertFlag then
InsertRecord
else
UpdateRecord;
InsertFlag:=false;
end;
procedure TFrameGrid.TimerRecCountTimer(Sender: TObject);
begin
pnlRecCount.Caption:=format('ะะฐะฟะธัะตะน: %d ะธะท %d', [ViewCh.DataController.FilteredRecordCount, ViewCh.DataController.RecordCount]);
end;
procedure TFrameGrid.ViewChDataControllerAfterInsert(
ADataController: TcxCustomDataController);
begin
inherited;
InsertFlag:=true;
end;
procedure TFrameGrid.ViewChDataControllerAfterCancel(
ADataController: TcxCustomDataController);
begin
inherited;
InsertFlag:=false;
end;
procedure TFrameGrid.actEditUpdate(Sender: TObject);
begin
(Sender as TAction).Enabled:=ViewCh.DataController.FilteredRecordCount>0;
end;
procedure TFrameGrid.ViewChFocusedRecordChanged(
Sender: TcxCustomGridTableView; APrevFocusedRecord,
AFocusedRecord: TcxCustomGridRecord;
ANewItemRecordFocusingChanged: Boolean);
var
book: TUserBookSubListItem;
begin
ScrollHandled:=false;
book:=nil;
if (OwnerBook is TUserBookSubListItem) then
book:=OwnerBook as TUserBookSubListItem;
if not Assigned(book) then exit;
book.RefreshChilds;
end;
procedure TFrameGrid.ViewChCustomDrawCell(Sender: TcxCustomGridTableView;
ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo;
var ADone: Boolean);
var
fld: TcdField;
status: variant;
begin
fld:=dsCh.FindField('ะฃัะตัะฝะฐั ะตะดะธะฝะธัะฐ.ะกัะฐััั ะทะฐะฟะธัะธ');
if Assigned(fld) then begin
status:=dsCh.Values[AViewInfo.GridRecord.RecordIndex, fld.Index];
if status=1 then
ACanvas.Font.Color:=clRed;
end;
if self.MarkLinkedObjects then
if not VarIsNullMy(Sender.DataController.Values[AViewInfo.GridRecord.RecordIndex, 4]) then
ACanvas.Font.Color:=clGray;
end;
procedure TFrameGrid.OnHyperCell_ConractNum_Start(Sender: TObject);
var
dlg: TdlgContractCard;
dlg2: TdlgContract2Card;
dlg3: TdlgContract3Card;
r, c: integer;
v: variant;
DepID: variant;
begin
r:=ViewCh.DataController.FocusedRecordIndex;
if r<0 then exit;
c:=dsCh.FieldByName('ะฃัะตัะฝะฐั ะตะดะธะฝะธัะฐ.ะะตะดะพะผััะฒะพ').Index;
DepID:=dsCh.Values[r, c];
if VarIsNullMy(DepID) then
raise Exception.Create('ะะตะฒะพะทะผะพะถะฝะพ ะพัะบัััั ะบะฐััะพัะบั ะดะพะณะพะฒะพัะฐ, ั.ะบ. ะฝะต ัะบะฐะทะฐะฝะพ ะฒะตะดะพะผััะฒะพ');
c:=dsCh.FieldByName('ะะพะณะพะฒะพั.ะบะพะด_ะะพะณะพะฒะพั').Index;
v:=dsCh.Values[r, c];
if VarIsNullMy(v) then exit;
if DepID=1 then begin
dlg:=TdlgContractCard.Create(nil);
try
dlg.ReadOnly:=true;
dlg.PrimaryKey:=v;
dlg.ShowModal;
finally
dlg.Free;
end;
end;
if DepID=2 then begin
dlg2:=TdlgContract2Card.Create(nil);
try
dlg2.ReadOnly:=true;
dlg2.PrimaryKey:=v;
dlg2.ShowModal;
finally
dlg2.Free;
end;
end;
if DepID=3 then begin
dlg3:=TdlgContract3Card.Create(nil);
try
dlg3.ReadOnly:=true;
dlg3.PrimaryKey:=v;
dlg3.ShowModal;
finally
dlg3.Free;
end;
end;
end;
procedure TFrameGrid.OnHyperCell_ConractFrom_Start(Sender: TObject);
var
dlg: TdlgOrganizationCard;
r, c: integer;
v: variant;
begin
r:=ViewCh.DataController.FocusedRecordIndex;
if r<0 then exit;
c:=dsCh.FieldByName('ะะพะณะพะฒะพั.ะฒะบ_ะัะพ ะฟะตัะตะดะฐะป ').Index;
v:=dsCh.Values[r, c];
if VarIsNullMy(v) then exit;
dlg:=TdlgOrganizationCard.Create(nil);
try
dlg.ReadOnly:=true;
dlg.PrimaryKey:=v;
dlg.ShowModal;
finally
dlg.Free;
end;
end;
procedure TFrameGrid.OnHyperCell_ConractTo_Start(Sender: TObject);
var
dlg: TdlgOrganizationCard;
r, c: integer;
v: variant;
begin
r:=ViewCh.DataController.FocusedRecordIndex;
if r<0 then exit;
c:=dsCh.FieldByName('ะะพะณะพะฒะพั.ะฒะบ_ะะพะผั ะฟะตัะตะดะฐะปะธ').Index;
v:=dsCh.Values[r, c];
if VarIsNullMy(v) then exit;
dlg:=TdlgOrganizationCard.Create(nil);
try
dlg.ReadOnly:=true;
dlg.PrimaryKey:=v;
dlg.ShowModal;
finally
dlg.Free;
end;
end;
function TFrameGrid.ObjectIDForReportMenu: integer;
begin
result:=(OwnerBook as TUserBookItem).ObjectID;
end;
procedure TFrameGrid.actAddObjectsToDocExecute(Sender: TObject);
begin
inherited;
AddObjectsToDoc;
end;
procedure TFrameGrid.AddObjectsToDoc;
var
dlg: TdlgObjectsForDocs;
begin
dlg:=TdlgObjectsForDocs.Create(nil);
dlg.PrimaryKey:=CurRecPKValue;
dlg.ShowModal;
dlg.Free;
end;
procedure TFrameGrid.actShowParentPropsExecute(Sender: TObject);
begin
DoShowParentProps;
end;
function ColIndex(View: TcxGridBandedTableViewCds; ColName: string): integer;
var
i: integer;
begin
result:=-1;
ColName:=AnsiUpperCase(ColName);
for i:=0 to View.ColumnCount-1 do
if AnsiUpperCase(View.Columns[i].DataBinding.FieldName) = ColName then begin
result:=i;
exit;
end;
end;
procedure TFrameGrid.DoShowParentProps;
var
a: TAccessBook;
r, c: integer;
id: integer;
sql: string;
UE: integer;
begin
a:=TAccessBook.Create;
try
r:=ViewCh.DataController.FocusedRecordIndex;
c:=ColIndex(ViewCh, 'ะฒะบ_ะะฑัะตะบัะ ะพะดะธัะตะปั');
id:=ViewCh.DataController.Values[r, c];
a.ObjectID:=id;
a.PropsFormClass:=TBASE_ObjectPropsForm;
c:=ColIndex(ViewCh, 'ะฒะบ_ะะฐะฟะธััะะฑัะตะบัะ ะพะดะธัะตะปั');
id:=ViewCh.DataController.Values[r, c];
// c:=dsCh.FindFieldIndex('ะฃัะตัะฝะฐั ะตะดะธะฝะธัะฐ.ะบะพะด_ะฃัะตัะฝะฐั ะตะดะธะฝะธัะฐ');
UE:=ExecSQLExpr(format('select [ะบะพะด_ะฃัะตัะฝะฐั ะตะดะธะฝะธัะฐ] from [ะฃัะตัะฝะฐั ะตะดะธะฝะธัะฐ] where sys_ะะฑัะตะบั = %d and ะญะบะทะตะผะฟะปััะะฑัะตะบัะฐ = %d', [a.ObjectID, id]));
if a.ShowModal(id, true, false, false, UE)<>mrOK then exit;
if (a.UserBook as TUserBook).Items.Count>0 then
(a.UserBook as TUserBook).Items[0].FrameGrid.UpdateRecord((a.UserBook as TUserBook).Items[0].FrameGrid.GridVert, (a.UserBook as TUserBook).OwnerForm)
else
((a.UserBook as TUserBook).OwnerForm as TBASE_ObjectPropsForm).UnitPropsFrame.Save();
finally
a.Free;
end;
end;
procedure TFrameGrid.actShowParentPropsUpdate(Sender: TObject);
var
r, c: integer;
v: variant;
begin
if (Sender as TAction).Visible then begin
r:=ViewCh.DataController.FocusedRecordIndex;
c:=ColIndex(ViewCh, 'ะฒะบ_ะะฑัะตะบัะ ะพะดะธัะตะปั');
v:=null;
if c<>-1 then
v:=ViewCh.DataController.Values[r, c];
(Sender as TAction).Enabled:=not VarIsNullMy(v);
end
else
(Sender as TAction).Enabled:=false;
end;
procedure TFrameGrid.actCopyFromExecute(Sender: TObject);
var
UEid: integer;
book: TUserBookItem;
f: TcdField;
r, c: integer;
begin
FCopyFrom.EnableCopy:=true;
book:=OwnerBook as TUserBookItem;
if book.IsObject then begin
if book.FrameGrid.dsCh.Fields[3].FieldName='ะฒะบ_ะะฐััะพััะธะนะะฑัะตะบัะะปะฐะดะตะปะตั' then
FCopyFrom.ObjectID:=book.FrameGrid.CurRecItemValue('ะฒะบ_ะะฐััะพััะธะนะะฑัะตะบัะะปะฐะดะตะปะตั')
else
raise Exception.Create('ะัะธะฑะบะฐ ะฒ procedure TFrameGrid.InternalEditRec. ะะฑัะฐัะธัะตะปั ะบ ัะฐะทัะฐะฑะพััะธะบั');
end;
r:=ViewCh.DataController.FocusedRecordIndex;
FCopyFrom.RecordID:=dsCh.Values[r, 0];
if r<0 then exit;
f:=dsCh.FindField('ะฒะบ_ะกะฒะพะนััะฒะฐ');
if Assigned(f) then
FCopyFrom.UEID:=dsCh.Values[r, f.Index];
actInsert.Execute;
end;
end.
|
unit brProlanisU;
interface
uses Dialogs, Classes, brCommonsU, System.SysUtils, System.StrUtils;
type
brProlanis = class(bridgeCommon)
private
kd_obat_sk : Integer;
procedure masukkanDelPeserta(id : string);
procedure masukkanDelKegiatan(id : string);
procedure masukkanGetProlanisKelompok(jenis_kelompok : string);
procedure masukkanGetProlanisKegiatan(bulan: TDate);
procedure masukkanGetProlanisPeserta(kegiatan, edu_id: string);
procedure masukkanPostKegiatan(id : string);
procedure masukkanPostPeserta(id : string);
public
function ambilJsonPostObat(idxstr : string) : string;
function ambilJsonPostKegiatan(id : string) : string;
function ambilJsonPostPesertaTunggal(id : string) : string;
function getProlanisKelompok (jenis_kelompok : string) : Boolean;
function getProlanisKegiatan (bulan : TDate) : Boolean;
function getProlanisPeserta (kegiatan, edu_id : string) : Boolean;
function postPeserta (idxstr : string) : Boolean;
function postPesertaTunggal (id : string) : Boolean;
function postKegiatan (id : string) : Boolean;
function delPeserta (id : string) : Boolean;
function delKegiatan (id : string) : Boolean;
constructor Create;
destructor destroy;
// property Uri : string;
end;
implementation
uses SynCommons, synautil;
{ brObat }
function brProlanis.ambilJsonPostObat(idxstr : string): string;
var sql0, sql1 : string;
tes : string;
i : Integer;
V0 , V1, V2, list : Variant;
begin
Result := '{"i": 0 }';
parameter_bridging('OBAT', 'POST');
sql0 := 'select * from jkn.obat_view where idxstr = %s and kd_obat_sk = 0 and bpjs_kunjungan is not null;';
sql1 := Format(sql0,[QuotedStr(idxstr)]);
fdQuery.Close;
fdQuery.SQL.Clear;
fdQuery.SQL.Add(sql1);
fdQuery.Open();
if fdQuery.IsEmpty then
begin
fdQuery.Close;
Exit;
end;
fdQuery.First;
list := _Arr([]);
V1 := _Json(FormatJson);
// myJson := _ObjFast([list]);
// tambahi id untuk merubah database jika respon sukses
V1.Add('id', '');
while not fdQuery.Eof do
begin
V1.id := fdQuery.FieldByName('id').AsString;
V1.noKunjungan := fdQuery.FieldByName('bpjs_kunjungan').AsString;
V1.racikan := fdQuery.FieldByName('racikan').AsBoolean;
{/*
if not fdQuery.FieldByName('kd_racikan').IsNull then
V1.kdRacikan := fdQuery.FieldByName('kd_racikan').AsString;
*/}
V1.obatDPHO := fdQuery.FieldByName('obat_dpho').AsBoolean;
V1.kdObat := fdQuery.FieldByName('kd_obat').AsString;
V1.signa1 := fdQuery.FieldByName('signa1').AsInteger;
V1.signa2 := fdQuery.FieldByName('signa2').AsInteger;
V1.jmlObat := fdQuery.FieldByName('jml_obat').AsInteger;
V1.jmlPermintaan := fdQuery.FieldByName('jml_permintaan').AsInteger;
if not fdQuery.FieldByName('nm_obat_non_dpho').IsNull then
V1.nmObatNonDPHO := fdQuery.FieldByName('nm_obat_non_dpho').AsString;
list.Add(V1);
fdQuery.Next;
end;
V0 := _Obj(['list', list]);
Result := VariantSaveJSON(V0);
//FileFromString(Result, 'tes_obat.json');
fdQuery.Close;
end;
function brProlanis.ambilJsonPostPesertaTunggal(id: string): string;
var sql0, sql1 : string;
tglStr : string;
i, panjang_edu : Integer;
V1 : Variant;
begin
Result := '';
parameter_bridging('PROLANIS PESERTA', 'POST');
// DateTimeToString(tglSqlStr, 'YYYY-MM-DD', tgl);
sql0 := 'select * from kelompok.peserta_view where id = %s and status = ''belum terkirim'';';
sql1 := Format(sql0,[QuotedStr(id)]);
// ShowMessage(idxstr);
fdQuery.Close;
fdQuery.SQL.Clear;
fdQuery.SQL.Add(sql1);
fdQuery.Open();
panjang_edu := Length(fdQuery.FieldByName('edu_id').AsString);
V1 := _Json(FormatJson);
// ShowMessage(FormatJson);
if (not fdQuery.IsEmpty) and (panjang_edu > 0) then
begin
// ShowMessage('not empty');
jejakIdxstr := fdQuery.FieldByName('id').AsString;
V1.eduId := fdQuery.FieldByName('edu_id').AsString;
V1.noKartu := fdQuery.FieldByName('no_kartu').AsString;
fdQuery.Close;
Result := VariantSaveJSON(V1);
// FileFromString(Result, 'pendaftaran.json');
end else ShowMessage('data kosong');
//ShowMessage(Result);
end;
function brProlanis.ambilJsonPostKegiatan(id: string): string;
var sql0, sql1 : string;
tglStr : string;
i : Integer;
V1 : Variant;
begin
Result := '';
parameter_bridging('PROLANIS KEGIATAN', 'POST');
// DateTimeToString(tglSqlStr, 'YYYY-MM-DD', tgl);
sql0 := 'select * from kelompok.kegiatan_view where id = %s and edu_id is null;';
sql1 := Format(sql0,[QuotedStr(id)]);
// ShowMessage(idxstr);
fdQuery.Close;
fdQuery.SQL.Clear;
fdQuery.SQL.Add(sql1);
fdQuery.Open();
V1 := _Json(FormatJson);
// ShowMessage(FormatJson);
if not fdQuery.IsEmpty then
begin
// ShowMessage('not empty');
jejakIdxstr := fdQuery.FieldByName('id').AsString;
// V1.eduId := fdQuery.FieldByName('edu_id').AsString;
V1.clubId := fdQuery.FieldByName('club_id').AsInteger;
DateTimeToString(tglStr, 'dd-MM-yyyy', fdQuery.FieldByName('tgl_pelayanan').AsDateTime);
V1.tglPelayanan := tglStr;
V1.kdKegiatan := fdQuery.FieldByName('kd_kegiatan').AsString;
V1.kdKelompok := fdQuery.FieldByName('kd_program').AsString;
V1.materi := fdQuery.FieldByName('materi').AsString;
V1.pembicara := fdQuery.FieldByName('pembicara').AsString;
V1.lokasi := fdQuery.FieldByName('lokasi').AsString;
V1.keterangan := fdQuery.FieldByName('keterangan').AsString;
V1.biaya := fdQuery.FieldByName('biaya').AsInteger;
fdQuery.Close;
Result := VariantSaveJSON(V1);
// FileFromString(Result, 'pendaftaran.json');
end else ShowMessage('data kosong - semua data sudah dikirimkan?');
//ShowMessage(Result);
end;
constructor brProlanis.Create;
begin
inherited Create;
end;
function brProlanis.delKegiatan(id: string): Boolean;
var sql0, sql1 : string;
tglStr : string;
edu_id, no_kartu : string;
jml : Integer;
ts : TMemoryStream;
begin
Result := False;
parameter_bridging('PROLANIS KEGIATAN', 'DELETE');
// mencari parameter pendaftaran
sql0 := 'select edu_id from kelompok.kegiatan_view where id = %s and edu_id is not null;';
sql1 := Format(sql0, [quotedStr(id)]);
fdQuery.Close;
fdQuery.SQL.Clear;
fdQuery.SQL.Add(sql1);
fdQuery.Open;
//jml := fdQuery.FieldByName('jml').AsInteger;
edu_id := fdQuery.FieldByName('edu_id').AsString;
if not fdQuery.IsEmpty then
begin
Uri := StringReplace( Uri, '{eduId}', edu_id, []);
//Uri := StringReplace( Uri, '{noKartu}', no_kartu, []);
//Uri := StringReplace(Uri, '{noUrut}', noUrut, []);
Result := httpDelete(Uri);
jejakIdxstr := id;
if Result then masukkanDelKegiatan(id);
end else adl_berhasil := True;
fdQuery.Close;
FDConn.Close;
end;
function brProlanis.delPeserta(id : string): Boolean;
var sql0, sql1 : string;
tglStr : string;
edu_id, no_kartu : string;
ts : TMemoryStream;
begin
Result := False;
parameter_bridging('PROLANIS PESERTA', 'DELETE');
// mencari parameter pendaftaran
sql0 := 'select edu_id, no_kartu from kelompok.peserta_view where id = %s and lower(status) = ''ok'';';
sql1 := Format(sql0, [quotedStr(id)]);
fdQuery.Close;
fdQuery.SQL.Clear;
fdQuery.SQL.Add(sql1);
fdQuery.Open;
if not fdQuery.IsEmpty then
begin
edu_id := fdQuery.FieldByName('edu_id').AsString;
no_kartu := fdQuery.FieldByName('no_kartu').AsString;
Uri := StringReplace( Uri, '{eduId}', edu_id, []);
Uri := StringReplace( Uri, '{noKartu}', no_kartu, []);
//Uri := StringReplace(Uri, '{noUrut}', noUrut, []);
Result := httpDelete(Uri);
jejakIdxstr := id;
if Result then masukkanDelPeserta(id);
end else adl_berhasil := True;
fdQuery.Close;
FDConn.Close;
end;
destructor brProlanis.destroy;
begin
inherited;
end;
function brProlanis.getProlanisKelompok(jenis_kelompok : string): Boolean;
var sql0, sql1 : string;
begin
Result := False;
parameter_bridging('PROLANIS KELOMPOK', 'GET');
//ShowMessage(uri);
Uri := StringReplace( Uri, '{kdJnsKelompok}', jenis_kelompok, []);
//Uri := StringReplace( Uri, '{start}', mulaiDari, []);
//Uri := StringReplace(Uri, '{limit}', jumlahData, []);
//ShowMessage(uri);
Result:= httpGet(uri);
if Result then masukkanGetProlanisKelompok(jenis_kelompok);
FDConn.Close;
end;
function brProlanis.getProlanisPeserta(kegiatan, edu_id: string): Boolean;
var sql0, sql1, tglStr : string;
begin
Result := False;
//DateTimeToString(tglStr, 'dd-MM-yyyy', bulan);
parameter_bridging('PROLANIS PESERTA', 'GET');
//ShowMessage(uri);
Uri := StringReplace( Uri, '{eduId}', edu_id, []);
//Uri := StringReplace( Uri, '{start}', mulaiDari, []);
//Uri := StringReplace(Uri, '{limit}', jumlahData, []);
//ShowMessage(uri);
Result:= httpGet(uri);
if Result then masukkanGetProlanisPeserta(kegiatan, edu_id);
FDConn.Close;
end;
function brProlanis.getProlanisKegiatan(bulan: TDate): Boolean;
var sql0, sql1, tglStr : string;
begin
Result := False;
DateTimeToString(tglStr, 'dd-MM-yyyy', bulan);
parameter_bridging('PROLANIS KEGIATAN', 'GET');
//ShowMessage(uri);
Uri := StringReplace( Uri, '{bulan}', tglStr, []);
//Uri := StringReplace( Uri, '{start}', mulaiDari, []);
//Uri := StringReplace(Uri, '{limit}', jumlahData, []);
//ShowMessage(uri);
Result:= httpGet(uri);
if Result then masukkanGetProlanisKegiatan(bulan);
FDConn.Close;
end;
procedure brProlanis.masukkanDelKegiatan(id: string);
var dataResp, dataList : Variant;
i : Integer;
tSl : TStringList;
sqlDel0, sqlDel1, sql0, sql1 : string;
kdDiag, nmDiag : string;
tglStr : string;
nonSpesialis : Boolean;
kdObatSk : integer;
kdRacikan : string;
begin
// ShowMessage('awal masukkan get');
if logRest('DEL', 'PROLANIS KEGIATAN', tsResponse.Text) then
begin
tsL := TStringList.Create;
try
dataResp := _jsonFast(tsResponse.Text);
// ShowMessage(tsResponse.Text);
sqlDel0 := 'update kelompok.kegiatan set edu_id = null where id = %s;';
sqlDel1 := Format(sqlDel0, [quotedStr(id)]);
tSl.Add(sqlDel1);
finally
jalankanScript(tSl);
FreeAndNil(tSl);
end;
end;
end;
procedure brProlanis.masukkanDelPeserta(id : string);
var dataResp, dataList : Variant;
i : Integer;
tSl : TStringList;
sqlDel0, sqlDel1, sql0, sql1 : string;
kdDiag, nmDiag : string;
tglStr : string;
nonSpesialis : Boolean;
kdObatSk : integer;
kdRacikan : string;
begin
// ShowMessage('awal masukkan get');
if logRest('DEL', 'PROLANIS PESERTA', tsResponse.Text) then
begin
tsL := TStringList.Create;
try
dataResp := _jsonFast(tsResponse.Text);
// ShowMessage(tsResponse.Text);
sqlDel0 := 'update kelompok.kegiatan_peserta set status = ''belum terkirim'' where id = %s;';
sqlDel1 := Format(sqlDel0, [quotedStr(id)]);
tSl.Add(sqlDel1);
finally
jalankanScript(tSl);
FreeAndNil(tSl);
end;
end;
end;
procedure brProlanis.masukkanGetProlanisKelompok(jenis_kelompok : string);
var dataResp, dataList : Variant;
i : Integer;
tSl : TStringList;
sqlDel0, sqlDel1, sql0, sql1 : string;
club_id, kd_program, tgl_mulai, tgl_akhir, alamat, nama, ketua_no_hp, ketua_nama : string;
//sedia : integer;
begin
// ShowMessage('awal masukkan get');
if logRest('GET', 'PROLANIS KELOMPOK', tsResponse.Text) then
begin
sqlDel0 := 'delete from kelompok.club where club_id = %s;';
sql0 := 'insert into kelompok.club(puskesmas, club_id, kd_program, tgl_mulai, tgl_akhir, alamat, nama, ketua_no_hp, ketua_nama) ' +
'values(0, %s, %s, %s, %s, %s, %s, %s, %s);';
tsL := TStringList.Create;
try
dataResp := _jsonFast(tsResponse.Text);
// ShowMessage(tsResponse.Text);
// ShowMessage(IntToStr(dataResp.response.list._Count));
for I := 0 to dataResp.response.list._count - 1 do
begin
club_id := dataResp.response.list.Value(i).clubId;
kd_program := dataResp.response.list.Value(i).jnsKelompok.kdProgram;
// ShowMessage('BooltoStr (nonSpesialis, True)');
tgl_mulai := dataResp.response.list.Value(i).tglMulai;
if VarIsEmptyOrNull(dataResp.response.list.Value(i).tglAkhir) then
tgl_akhir := 'null' else QuotedStr(dataResp.response.list.Value(i).tglAkhir);
alamat := dataResp.response.list.Value(i).alamat;
nama := dataResp.response.list.Value(i).nama;
ketua_no_hp := dataResp.response.list.Value(i).ketua_noHP;
ketua_nama := dataResp.response.list.Value(i).ketua_nama;
sqlDel1 := Format(sqlDel0,[QuotedStr(club_id)]);
tSl.Add(sqlDel1);
sql1 := Format(sql0, [
club_id,
QuotedStr(kd_program),
QuotedStr(tgl_mulai),
tgl_akhir,
QuotedStr(alamat),
QuotedStr(nama),
QuotedStr(ketua_no_hp),
QuotedStr(ketua_nama)
]);
tSl.Add(sql1);
// showMessage(sqlDel1);
// showMessage(sql1);
end;
finally
jalankanScript(tSl);
FreeAndNil(tSl);
end;
end;
end;
procedure brProlanis.masukkanGetProlanisPeserta(kegiatan, edu_id: string);
var dataResp, dataList : Variant;
i : Integer;
tSl : TStringList;
sqlDel0, sqlDel1, sql0, sql1 : string;
no_kartu : string;
begin
// ShowMessage('awal masukkan get');
if logRest('GET', 'PROLANIS PESERTA', tsResponse.Text) then
begin
sqlDel0 := 'delete from kelompok.kegiatan_peserta where kegiatan = %s and edu_id = %s and no_kartu = %s;';
sql0 := 'insert into kelompok.kegiatan_peserta(status, kegiatan, edu_id, no_kartu) ' +
'values(''OK'', %s, %s, %s);';
tsL := TStringList.Create;
try
dataResp := _jsonFast(tsResponse.Text);
// ShowMessage(tsResponse.Text);
// ShowMessage(IntToStr(dataResp.response.list._Count));
for I := 0 to dataResp.response.list._count - 1 do
begin
edu_id := dataResp.response.list.Value(i).eduId;
no_kartu := dataResp.response.list.Value(i).peserta.noKartu;
sqlDel1 := Format(sqlDel0,[QuotedStr(kegiatan), QuotedStr(edu_id), QuotedStr(no_kartu)]);
tSl.Add(sqlDel1);
sql1 := Format(sql0, [
QuotedStr(kegiatan),
QuotedStr(edu_id),
QuotedStr(no_kartu)
]);
tSl.Add(sql1);
// showMessage(sqlDel1);
// showMessage(sql1);
end;
finally
jalankanScript(tSl);
FreeAndNil(tSl);
end;
end;
end;
procedure brProlanis.masukkanGetProlanisKegiatan(bulan: TDate);
var dataResp, dataList : Variant;
i : Integer;
tSl : TStringList;
sqlDel0, sqlDel1, sql0, sql1 : string;
edu_id, tgl_pelayanan, kegiatan, kelompok, materi, pembicara, lokasi, keterangan : string;
club_prol, biaya : integer;
begin
// ShowMessage('awal masukkan get');
if logRest('GET', 'PROLANIS KEGIATAN', tsResponse.Text) then
begin
sqlDel0 := 'delete from kelompok.kegiatan where edu_id = %s;';
sql0 := 'insert into kelompok.kegiatan(puskesmas, edu_id, club_prol, tgl_pelayanan, kegiatan, kelompok, materi, pembicara, lokasi, keterangan, biaya) ' +
'values(0, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s );';
tsL := TStringList.Create;
try
dataResp := _jsonFast(tsResponse.Text);
// ShowMessage(tsResponse.Text);
// ShowMessage(IntToStr(dataResp.response.list._Count));
for I := 0 to dataResp.response.list._count - 1 do
begin
edu_id := dataResp.response.list.Value(i).eduId;
club_prol := dataResp.response.list.Value(i).clubProl.clubId;
// ShowMessage('BooltoStr (nonSpesialis, True)');
tgl_pelayanan := dataResp.response.list.Value(i).tglPelayanan;
kegiatan := dataResp.response.list.Value(i).kegiatan.nama;
kelompok := dataResp.response.list.Value(i).kelompok.nama;
materi := dataResp.response.list.Value(i).materi;
pembicara := dataResp.response.list.Value(i).pembicara;
lokasi := dataResp.response.list.Value(i).lokasi;
keterangan := dataResp.response.list.Value(i).keterangan;
biaya := dataResp.response.list.Value(i).biaya;
sqlDel1 := Format(sqlDel0,[QuotedStr(edu_id)]);
tSl.Add(sqlDel1);
sql1 := Format(sql0, [
QuotedStr(edu_id),
IntToStr(club_prol),
QuotedStr(tgl_pelayanan),
QuotedStr(kegiatan),
QuotedStr(kelompok),
QuotedStr(materi),
QuotedStr(pembicara),
QuotedStr(lokasi),
QuotedStr(keterangan),
IntToStr(biaya)
]);
tSl.Add(sql1);
// showMessage(sqlDel1);
// showMessage(sql1);
end;
finally
jalankanScript(tSl);
FreeAndNil(tSl);
end;
end;
end;
procedure brProlanis.masukkanPostKegiatan(id : string);
var dataResp, dataList : Variant;
i : Integer;
tSl : TStringList;
sqlDel0, sqlDel1, sql0, sql1 : string;
kdDiag, nmDiag : string;
tglStr : string;
nonSpesialis : Boolean;
edu_id : string;
kdRacikan : string;
begin
// ShowMessage('awal masukkan get');
if logRest('POST', 'PROLANIS KEGIATAN', tsResponse.Text) then
begin
tsL := TStringList.Create;
try
dataResp := _jsonFast(tsResponse.Text);
// ShowMessage(tsResponse.Text);
edu_id := dataResp.response.message;
sqlDel0 := 'update kelompok.kegiatan set edu_id = %s where id = %s;';
sqlDel1 := Format(sqlDel0, [QuotedStr(edu_id), QuotedStr(id)]);
tSl.Add(sqlDel1);
finally
jalankanScript(tSl);
FreeAndNil(tSl);
end;
end;
end;
procedure brProlanis.masukkanPostPeserta(id: string);
var dataResp, dataList : Variant;
i : Integer;
tSl : TStringList;
sqlDel0, sqlDel1, sql0, sql1 : string;
kdDiag, nmDiag : string;
tglStr : string;
nonSpesialis : Boolean;
kdObatSk : integer;
kdRacikan : string;
begin
// ShowMessage('awal masukkan get');
if logRest('POST', 'PROLANIS PESERTA', tsResponse.Text) then
begin
tsL := TStringList.Create;
try
dataResp := _jsonFast(tsResponse.Text);
// ShowMessage(tsResponse.Text);
sqlDel0 := 'update kelompok.kegiatan_peserta set status = ''ok'' where id = %s;';
sqlDel1 := Format(sqlDel0, [quotedStr(id)]);
tSl.Add(sqlDel1);
finally
jalankanScript(tSl);
FreeAndNil(tSl);
end;
end;
end;
function brProlanis.postKegiatan(id: string): Boolean;
var
mStream : TMemoryStream;
js : string;
begin
mStream := TMemoryStream.Create;
Result := False;
//ShowMessage('awal pendaftaran');
js := ambilJsonPostKegiatan(id);
//ShowMessage('akhir ambil json pendaftaran');
if Length(js) > 20 then
begin
WriteStrToStream(mStream, js);
FormatJson := js;
//Uri := ReplaceStr(Uri, '{puskesmas}', puskesmas);
//ShowMessage('awal post pendaftaran');
Result:= httpPost(Uri, mStream);
jejakIdxstr := id;
//ShowMessage('setelah post pendaftaran');
end;
mStream.Free;
if Result then masukkanPostKegiatan(id);
FDConn.Close;
end;
function brProlanis.postPeserta(idxstr : string): Boolean;
var sql0, sql1 : string;
tglStr : string;
no_urut : Integer;
ts : TMemoryStream;
V1, V2 : Variant;
I: Integer;
dataStr : string;
js : string;
id : string;
begin
Result := False;
//parameter_bridging('OBAT', 'POST');
js := ambilJsonPostObat(idxstr);
if Length(js) > 20 then
begin
V1 := _Json(js);
ts := TMemoryStream.Create;
if V1.list._count > 0 then
begin
try
for I := 0 to V1.list._count - 1 do
begin
VarClear(V2);
V2:= V1.List.Value(i);
_Unique(V2);
id := V2.id;
//ShowMessage(id);
V2.delete('id');
dataStr := VariantSaveJSON(V2);
FormatJson := dataStr;
ts.Clear;
WriteStrToStream(ts, FormatJson);
//ts.Write(dataStr[1], Length(dataStr));
Result := httpPost(Uri, ts);
jejakIdxstr := idxstr;
if Result then masukkanPostKegiatan(id);
//FileFromString(dataStr, 'tes_obat'+ IntToStr(i)+'.json');
end;
finally
ts.Free;
end;
end;
end;
FDConn.Close;
end;
function brProlanis.postPesertaTunggal(id: string): Boolean;
var
mStream : TMemoryStream;
js : string;
begin
mStream := TMemoryStream.Create;
Result := False;
//ShowMessage('awal pendaftaran');
js := ambilJsonPostPesertaTunggal(id);
//ShowMessage('akhir ambil json pendaftaran');
if Length(js) > 20 then
begin
WriteStrToStream(mStream, js);
FormatJson := js;
//Uri := ReplaceStr(Uri, '{puskesmas}', puskesmas);
//ShowMessage('awal post pendaftaran');
Result:= httpPost(Uri, mStream);
jejakIdxstr := id;
//ShowMessage('setelah post pendaftaran');
end;
mStream.Free;
if Result then masukkanPostPeserta(id);
FDConn.Close;
end;
end.
|
(**
This module contains a form for requesting the subdirectory for files.
@Author David Hoyle
@Version 1.0
@Date 16 Feb 2018
**)
Unit JVTGRelativePathForm;
Interface
Uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.Buttons,
JVTGTypes;
Type
(** A class to represent a form for prompting the user to provide a relative path for a module. **)
TfrmExtractRelPath = Class(TForm)
lblExistingGitRepoPath: TLabel;
edtExistingGitRepoPath: TEdit;
edtModulePath: TEdit;
lblModulePath: TLabel;
edtModuleName: TEdit;
lblModuleName: TLabel;
lblRelPath: TLabel;
btnAbort: TBitBtn;
btnCancel: TBitBtn;
btnOK: TBitBtn;
edtRelPath: TComboBox;
Strict Private
Strict Protected
Class Procedure AddTrailingSlash(Var strPath : String);
Class Function CheckPathExists(Const boolResult : Boolean; Const strNewGitRepoPath : String;
Var strRelPath : String) : Boolean;
Public
Class Function Execute(Const slPaths : TStringList; Const RepoData : TJVTGRepoData;
Var strRelPath : String) : Boolean;
End;
Implementation
{$R *.dfm}
(**
This method ensures that the given path has a trailing backslash.
@precon None.
@postcon The give path is ensured to have a trailing backslash.
@param strPath as a String as a reference
**)
Class Procedure TfrmExtractRelPath.AddTrailingSlash(Var strPath: String);
Begin
If (Length(strPath) > 0) And (strPath[Length(strPath)] <> '\') Then
strPath := strPath + '\';
End;
(**
This method checks whether the given path need creating and if so prompts the user for the relative
path and then creates the path else raises an exception.
@precon None.
@postcon Either the path is created or an exception is raised.
@param boolResult as a Boolean as a constant
@param strNewGitRepoPath as a String as a constant
@param strRelPath as a String as a reference
@return a Boolean
**)
Class Function TfrmExtractRelPath.CheckPathExists(Const boolResult : Boolean;
Const strNewGitRepoPath : String; Var strRelPath : String) : Boolean;
ResourceString
strCreateDirectory = 'Create Directory';
strCouldNotCreateFolder = 'Could not create the folder "%s"!';
Begin
Result := boolResult;
If Not DirectoryExists(strNewGitRepoPath + strRelPath) Then begin
// If InputQuery(Application.Title, strCreateDirectory, strRelPath) Then Begin
AddTrailingSlash(strRelPath);
If Not ForceDirectories(strNewGitRepoPath + strRelPath) Then
Raise Exception.Create(Format(strCouldNotCreateFolder,
[strNewGitRepoPath + strRelPath]));
// End Else begin
// Result := False;
// end;
end;
End;
(**
This method is the main method for invoking the dialogue.
@precon slPaths must be a valid instance.
@postcon Checks to see if the relative path is known. If not the dialogue is shown to the user.
@param slPaths as a TStringList as a constant
@param RepoData as a TJVTGRepoData as a constant
@param strRelPath as a String as a reference
@return a Boolean
**)
Class Function TfrmExtractRelPath.Execute(Const slPaths : TStringList; Const RepoData : TJVTGRepoData;
Var strRelPath : String) : Boolean;
Var
F : TfrmExtractRelPath;
iResult : TModalResult;
iIndex: Integer;
iLen: Integer;
i: Integer;
Begin
Result := False;
iIndex := slPaths.IndexOfName(RepoData.FModuleName);
If iIndex = -1 Then
Begin
iLen := Length(RepoData.FOLDGitRepoPath);
If CompareText(Copy(RepoData.FModulePath, 1, iLen), RepoData.FOLDGitRepoPath) = 0 Then
Begin
strRelPath := RepoData.FModulePath;
Delete(strRelPath, 1, iLen);
Result := True;
// Ignore Units outside of OldPath
// End Else
// Begin
// F := TfrmExtractRelPath.Create(Application.MainForm);
// Try
// F.edtExistingGitRepoPath.Text := RepoData.FOLDGitRepoPath;
// F.edtModulePath.Text := RepoData.FModulePath;
// F.edtModuleName.Text := RepoData.FModuleName;
// F.edtRelPath.Text := strRelPath;
// For i := 0 To slPaths.Count - 1 Do
// If F.edtRelPath.Items.IndexOf(slPaths.ValueFromIndex[i]) = -1 Then
// F.edtRelPath.Items.Add(slPaths.ValueFromIndex[i]);
// iResult := F.ShowModal;
// Case iResult Of
// mrOk:
// Begin
// strRelPath := F.edtRelPath.Text;
// F.AddTrailingSlash(strRelPath);
// slPaths.Values[RepoData.FModuleName] := strRelPath;
// Result := True;
// End;
// mrAbort: Abort;
// End;
// Finally
// F.Free;
// End;
End;
End Else
Begin
strRelPath := slPaths.ValueFromIndex[iIndex];
Result := True;
End;
Result := CheckPathExists(Result, RepoData.FNEWGitRepoPath, strRelPath);
End;
End.
|
{
@abstract(Provides Old Format 1.8 highlighters import)
@authors(Vitalik [just_vitalik@yahoo.com])
@created(2005)
@lastmod(2006-06-30)
}
{$IFNDEF QSynUniFormatNativeXml18}
unit SynUniFormatNativeXml18;
{$ENDIF}
{$I SynUniHighlighter.inc}
interface
uses
{$IFDEF SYN_CLX}
QClasses,
QGraphics,
QSynUniFormat,
QSynUniClasses,
QSynUniRules,
QSynUniHighlighter
{$ELSE}
Classes,
Graphics,
{$IFDEF SYN_COMPILER_6_UP}
Variants,
{$ENDIF}
SynUniFormat,
SynUniFormatNativeXml,
SynUniClasses,
SynUniRules,
SynUniHighlighter,
{$ENDIF}
SysUtils,
{XMLIntf; } // DW
SimpleXML;
type
TSynUniFormatNativeXml18 = class(TSynUniFormatNativeXml)
class function ImportInfo(AInfo: TSynInfo; ANode: IXMLNode): Boolean; override;
class function ExportInfo(AInfo: TSynInfo; ANode: IXMLNode): Boolean; override;
class function ImportEditorProperties(AEditorProperties: TEditorProperties; ANode: IXMLNode): Boolean; override;
class function ExportEditorProperties(AEditorProperties: TEditorProperties; ANode: IXMLNode): Boolean; override;
class function ImportAttributes(Attributes: TSynAttributes; ANode: IXMLNode): Boolean; overload; override;
class function ExportAttributes(Attributes: TSynAttributes; ANode: IXMLNode): Boolean; overload; override;
class function ImportAttributes(Attributes: TSynAttributes; AString: string): Boolean; overload;
class function ExportAttributes(Attributes: TSynAttributes; var AString: string): Boolean; overload;
class function ImportSchemes(ASchemes: TSynUniSchemes; ANode: IXMLNode): Boolean; override;
class function ExportSchemes(ASchemes: TSynUniSchemes; ANode: IXMLNode): Boolean; override;
class function ImportToken(AToken: TSynMultiToken; ANode: IXMLNode; Kind: string = ''): Boolean;
class function ExportToken(AToken: TSynMultiToken; ANode: IXMLNode; Kind: string = ''): Boolean;
class function ImportKeyList(AKeyList: TSynKeyList; ANode: IXMLNode): Boolean; override;
class function ExportKeyList(AKeyList: TSynKeyList; ANode: IXMLNode): Boolean; override;
class function ImportSet(ASet: TSynSet; ANode: IXMLNode): Boolean; override;
class function ExportSet(ASet: TSynSet; ANode: IXMLNode): Boolean; override;
class function ImportRange(ARange: TSynRange; ANode: IXMLNode): Boolean; override;
class function ExportRange(ARange: TSynRange; ANode: IXMLNode): Boolean; override;
class function ImportHighlighter(SynUniSyn: TSynUniSyn; ANode: IXMLNode): Boolean; override;
class function ExportHighlighter(SynUniSyn: TSynUniSyn; ANode: IXMLNode): Boolean; override;
class function ImportFromStream(AObject: TObject; AStream: TStream): Boolean; override;
class function ExportToStream(AObject: TObject; AStream: TStream): Boolean; override;
class function ImportFromFile(AObject: TObject; AFileName: string): Boolean; override;
class function ExportToFile(AObject: TObject; AFileName: string): Boolean; override;
end;
implementation
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml18.ImportInfo(AInfo: TSynInfo; ANode: IXMLNode): Boolean;
var
i: Integer;
begin
with ANode, AInfo do
begin
with EnsureChild('General'), General do
begin
Name := GetVarAttr('Name','');
Extensions := GetVarAttr('Extensions','');
end;
with EnsureChild('Author'), Author do
begin
Name := GetVarAttr('Name','');
Email := GetVarAttr('Email','');
Web := GetVarAttr('Web','');
Copyright := GetVarAttr('Copyright','');
Company := GetVarAttr('Company','');
Remark := GetVarAttr('Remark','');
end;
with EnsureChild('Version'), General do
begin
Version := StrToInt(GetVarAttr('Version',''));
Revision := StrToInt(GetVarAttr('Revision',''));
GetVarAttr('Date','');
end;
with EnsureChild('Sample'), General do
for i := 0 to ChildNodes.Count-1 do
Sample := Sample + ChildNodes[i].Text + #13#10;
with EnsureChild('History'), General do
for i := 0 to ChildNodes.Count-1 do
History := History + ChildNodes[i].Text + #13#10;
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml18.ExportInfo(AInfo: TSynInfo; ANode: IXMLNode): Boolean;
var
i: Integer;
Buffer: TStringList;
Node: IXMLNode;
begin
with AInfo, ANode do
begin
with General, AppendElement('General') do
begin
SetVarAttr('Name', Name);
SetVarAttr('Extensions', Extensions);
end;
with Author, AppendElement('Author') do
begin
SetVarAttr('Name', Name);
SetVarAttr('Email', Email);
SetVarAttr('Web', Web);
SetVarAttr('Copyright', Copyright);
SetVarAttr('Company', Company);
SetVarAttr('Remark', Remark);
end;
with General, AppendElement('Version') do
begin
SetVarAttr('Version', Version);
SetVarAttr('Revision', Revision);
end;
Buffer := TStringList.Create();
with General, AppendElement('History') do
begin
Text := ' ';
Buffer.Text := History;
for i := 0 to Buffer.Count-1 do
begin
Node := AppendElement('H');
Node.Text := Buffer[i];
end;
end;
with General, AppendElement('Sample') do
begin
Text := ' ';
Buffer.Text := Sample;
for i := 0 to Buffer.Count-1 do
begin
Node := AppendElement('S');
Node.Text := Buffer[i];
end;
end;
FreeAndNil(Buffer);
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml18.ImportEditorProperties(AEditorProperties:
TEditorProperties; ANode: IXMLNode): Boolean;
begin
// ัะพัะผะฐั ะฝะต ะฟะพะดะดะตัะถะธะฒะฐะตั
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml18.ExportEditorProperties(AEditorProperties:
TEditorProperties; ANode: IXMLNode): Boolean;
begin
// ัะพัะผะฐั ะฝะต ะฟะพะดะดะตัะถะธะฒะฐะตั
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml18.ImportAttributes(Attributes: TSynAttributes;
AString: string): Boolean;
begin
with Attributes do
begin
ParentForeground := False; // ะัะถะฝะพ ะปะธ?..
ParentBackground := False;
Foreground := StrToIntDef(Copy(AString, 1, pos(',',AString)-1), 0);
Background := StrToIntDef(Copy(AString, pos(',',AString)+1, pos(';',AString)-pos(',',AString)-1), $FFFFFF);
ParentForeground := LowerCase(Copy(AString, pos(';',AString)+1, pos(':',AString)-pos(';',AString)-1)) = 'true';
ParentBackground := LowerCase(Copy(AString, pos(':',AString)+1, pos('.',AString)-pos(':',AString)-1)) = 'true';
Style := StrToFontStyle(Copy(AString, pos('.',AString)+1, Length(AString)-pos('.',AString)));
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml18.ExportAttributes(Attributes: TSynAttributes; var AString: string): Boolean;
begin
with Attributes do
begin
AString := IntToStr(Foreground)+','+IntToStr(Background)+';'+
BoolToStr(ParentForeground,True)+':'+
BoolToStr(ParentBackground,True)+'.'+
FontStyleToStr(Style);
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml18.ImportAttributes(Attributes: TSynAttributes;
ANode: IXMLNode): Boolean;
begin
Result := ImportAttributes(Attributes, ANode.GetVarAttr('Attributes',''));
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml18.ExportAttributes(Attributes: TSynAttributes;
ANode: IXMLNode): Boolean;
var
AString: string;
begin
Result := ExportAttributes(Attributes, AString);
ANode.SetVarAttr('Attributes', AString);
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml18.ImportSchemes(ASchemes: TSynUniSchemes; ANode: IXMLNode): Boolean;
begin
//TODO: Add implementation here
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml18.ExportSchemes(ASchemes: TSynUniSchemes; ANode: IXMLNode): Boolean;
begin
// ัะพัะผะฐั ะฝะต ะฟะพะดะดะตัะถะธะฒะฐะตั
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml18.ImportKeyList(AKeyList: TSynKeyList; ANode: IXMLNode): Boolean;
var
i: Integer;
begin
with AKeyList, ANode do
begin
Name := VarToStr(GetVarAttr('Name',''));
Enabled := VarToBool(GetVarAttr('Enabled',''), True);
ImportAttributes(AKeyList.Attributes, VarToStr(GetVarAttr('Attributes','')));
Style := VarToStr(GetVarAttr('Style',''));
for i := 0 to ChildNodes.Count-1 do
//if ChildNodes[i].NodeName = 'W' then
KeyList.Add(VarToStr(ChildNodes[i].GetVarAttr('value','')));
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml18.ExportKeyList(AKeyList: TSynKeyList; ANode: IXMLNode): Boolean;
var
i: Integer;
Buffer: TStringList;
Node: IXMLNode;
begin
with AKeyList, ANode do
begin
SetVarAttr('Name',Name);
if not Enabled then
SetVarAttr('Enabled', BoolToStr(Enabled, True));
ExportAttributes(AKeyList.Attributes, ANode);
SetVarAttr('Style',Style);
Buffer := TStringList.Create();
Buffer.Text := KeyList.Text;
for i := 0 to Buffer.Count-1 do
begin
Node := AppendElement('word');
Node.SetVarAttr('value', Buffer[i]);
end;
FreeAndNil(Buffer);
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml18.ImportSet(ASet: TSynSet; ANode: IXMLNode): Boolean;
begin
with ASet, ANode do
begin
Name := VarToStr(GetVarAttr('Name',''));
Enabled := VarToBool(GetVarAttr('Enabled',''), True);
ImportAttributes(ASet.Attributes, VarToStr(GetVarAttr('Attributes','')));
Style := VarToStr(GetVarAttr('Style',''));
CharSet := VarToSet(GetVarAttr('Symbols',''));
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml18.ExportSet(ASet: TSynSet; ANode: IXMLNode): Boolean;
begin
with ASet, ANode do
begin
SetVarAttr('Name', Name);
if not Enabled then
SetVarAttr('Enabled', BoolToStr(Enabled, True));
ExportAttributes(ASet.Attributes, ANode);
SetVarAttr('Style', Style);
SetVarAttr('Symbols', SetToStr(CharSet));
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml18.ImportToken(AToken: TSynMultiToken; ANode: IXMLNode; Kind: string = ''): Boolean;
begin
with AToken, ANode do
begin
FinishOnEol := VarToBool(GetVarAttr(Kind+'FinishOnEol', ''));
StartLine := StrToStartLine(VarToStr(GetVarAttr(Kind+'StartLine', '')));
StartType := StrToStartType(VarToStr(GetVarAttr(Kind+'PartOfTerm', '')));
BreakType := StrToBreakType(VarToStr(GetVarAttr(Kind+'PartOfTerm', '')));
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml18.ExportToken(AToken: TSynMultiToken; ANode: IXMLNode; Kind: string = ''): Boolean;
begin
with AToken, ANode do
begin
if FinishOnEol then
SetVarAttr(Kind+'FinishOnEol', BoolToStr(FinishOnEol, True));
if StartLine <> slNotFirst then
SetVarAttr(Kind+'StartLine', StartLineToStr(StartLine));
if (StartType = stTerm) and (BreakType = btTerm) then
SetVarAttr(Kind+'PartOfTerm', 'False')
else if (StartType = stAny) and (BreakType = btTerm) then
SetVarAttr(Kind+'PartOfTerm', 'Left')
else if (StartType = stTerm) and (BreakType = btAny) then
SetVarAttr(Kind+'PartOfTerm', 'Right');
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml18.ImportRange(ARange: TSynRange; ANode: IXMLNode): Boolean;
var
i: Integer;
NewRange: TSynRange;
NewKeyList: TSynKeyList;
NewSet: TSynSet;
begin
with ARange, ANode do
begin
Name := VarToStr(GetVarAttr('Name', ''));
Enabled := VarToBool(GetVarAttr('Enabled', ''), True);
CaseSensitive := VarToBool(GetVarAttr('CaseSensitive', ''));
Style := VarToStr(GetVarAttr('Style', ''));
ImportAttributes(ARange.Attributes, VarToStr(GetVarAttr('Attributes', '')));
Delimiters := VarToSet(GetVarAttr('Delimiters', ''));
with EnsureChild('Rule') do
begin
CloseOnTerm := VarToBool(GetVarAttr('CloseOnTerm', ''));
CloseOnEol := VarToBool(GetVarAttr('CloseOnEol', ''));
AllowPreviousClose := VarToBool(GetVarAttr('AllowPredClose', ''));
OpenToken.Clear();
CloseToken.Clear();
AddCoupleTokens(VarToStr(GetVarAttr('OpenSymbol', '')), VarToStr(GetVarAttr('CloseSymbol', '')));
end;
ImportToken(OpenToken, EnsureChild('Rule'), 'OpenSymbol');
ImportToken(CloseToken, EnsureChild('Rule'), 'CloseSymbol');
for i := 0 to ChildNodes.Count-1 do
if ChildNodes[i].NodeName = 'Keywords' then
begin
NewKeyList := TSynKeyList.Create();
ImportKeyList(NewKeyList, ChildNodes[i]);
AddKeyList(NewKeyList);
end
else if ChildNodes[i].NodeName = 'Set' then
begin
NewSet := TSynSet.Create();
ImportSet(NewSet, ChildNodes[i]);
AddSet(NewSet);
end
else if ChildNodes[i].NodeName = 'Range' then
begin
NewRange := TSynRange.Create;
ImportRange(NewRange, ChildNodes[i]);
AddRange(NewRange);
end
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml18.ExportRange(ARange: TSynRange; ANode: IXMLNode): Boolean;
var
i: Integer;
NodeRule: IXMLNode;
begin
with ARange, ANode do
begin
SetVarAttr('Name', Name);
if not Enabled then
SetVarAttr('Enabled', BoolToStr(Enabled, True));
if CaseSensitive then
SetVarAttr('CaseSensitive', BoolToStr(CaseSensitive, True));
ExportAttributes(Attributes, ANode);
SetVarAttr('Style', Style);
SetVarAttr('Delimiters', SetToStr(Delimiters));
NodeRule := AppendElement('Rule');
with NodeRule do
begin
if OpenToken.Symbols[0] <> '' then
SetVarAttr('OpenSymbol', OpenToken.Symbols[0]);
ExportToken(OpenToken, NodeRule, 'OpenSymbol');
if CloseToken.Symbols[0] <> '' then
SetVarAttr('CloseSymbol', CloseToken.Symbols[0]);
ExportToken(CloseToken, NodeRule, 'CloseSymbol');
if CloseOnTerm then
SetVarAttr('CloseOnTerm', BoolToStr(CloseOnTerm, True));
if CloseOnEol then
SetVarAttr('CloseOnEol', BoolToStr(CloseOnEol, True));
if AllowPreviousClose then
SetVarAttr('AllowPredClose', BoolToStr(AllowPreviousClose, True));
end;
for i := 0 to KeyListCount -1 do
ExportKeyList(KeyLists[i], AppendElement('Keywords'));
for i := 0 to SetCount -1 do
ExportSet(Sets[i], AppendElement('Set'));
for i := 0 to RangeCount -1 do
ExportRange(Ranges[i], AppendElement('Range'));
end;
Result := True;
end;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml18.ImportHighlighter(SynUniSyn: TSynUniSyn; ANode: IXMLNode): Boolean;
var
Schemes: TStringList;
SchemeIndex: Integer;
begin
with ANode, SynUniSyn do
begin
Clear();
ImportInfo(Info, EnsureChild('Info'));
ImportSchemes(Schemes, EnsureChild('Scheme'));
ImportRange(MainRules, EnsureChild('Range'));
FormatVersion := '1.8';
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml18.ExportHighlighter(SynUniSyn: TSynUniSyn; ANode: IXMLNode): Boolean;
begin
//:(ANode.NodeName := 'UniHighlighter';
ANode.SetVarAttr('Version', '1.8.3');
with SynUniSyn, ANode do
begin
ExportInfo(Info, AppendElement('Info'));
ExportSchemes(Schemes, AppendElement('Scheme'));
ExportRange(MainRules, AppendElement('Range'));
// '<CopyRight>Rule file for UniHighlighter Delphi component (Copyright(C) Fantasist(walking_in_the_sky@yahoo.com), Vit(nevzorov@yahoo.com), Vitalik(vetal-x@mail.ru), 2002-2006)</CopyRight>'
end;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml18.ImportFromStream(AObject: TObject; AStream: TStream): Boolean;
var
Buffer: TStringlist;
Stream: TMemoryStream;
begin
VerifyStream(AStream);
Buffer := TStringList.Create();
Buffer.LoadFromStream(AStream);
Buffer.Insert(0, '<?xml version="1.0" encoding="windows-1251"?>');
Stream := TMemoryStream.Create();
Buffer.SaveToStream(Stream);
FreeAndNil(Buffer);
Result := inherited ImportFromStream(AObject, Stream);
FreeAndNil(Stream);
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml18.ExportToStream(AObject: TObject; AStream: TStream): Boolean;
var
Buffer: TStringlist;
Stream: TMemoryStream;
begin
Stream := TMemoryStream.Create();
Result := inherited ExportToStream(AObject, Stream);
Buffer := TStringList.Create();
Stream.Position := 0;
Buffer.LoadFromStream(Stream);
Buffer.Delete(0);
Buffer.SaveToStream(AStream);
FreeAndNil(Stream);
FreeAndNil(Buffer);
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml18.ImportFromFile(AObject: TObject; AFileName: string): Boolean;
begin
Result := inherited ImportFromFile(AObject, AFileName);
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXml18.ExportToFile(AObject: TObject; AFileName: string): Boolean;
begin
Result := inherited ExportToFile(AObject, AFileName);
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: Base classes for GLScene.<p>
<b>History : </b><font size=-1><ul>
<li>05/10/08 - DanB - Creation, from GLMisc.pas + other places
</ul></font>
}
unit GLBaseClasses;
interface
uses Classes, GLPersistentClasses, GLCrossPlatform;
type
// TProgressTimes
//
TProgressTimes = record
deltaTime, newTime : Double
end;
// TGLProgressEvent
//
{: Progression event for time-base animations/simulations.<p>
deltaTime is the time delta since last progress and newTime is the new
time after the progress event is completed. }
TGLProgressEvent = procedure (Sender : TObject; const deltaTime, newTime : Double) of object;
IGLNotifyAble = interface(IInterface)
['{00079A6C-D46E-4126-86EE-F9E2951B4593}']
procedure NotifyChange(Sender : TObject);
end;
IGLProgessAble = interface(IInterface)
['{95E44548-B0FE-4607-98D0-CA51169AF8B5}']
procedure DoProgress(const progressTime : TProgressTimes);
end;
// TGLUpdateAbleObject
//
{: An abstract class describing the "update" interface.<p> }
TGLUpdateAbleObject = class (TGLInterfacedPersistent, IGLNotifyAble)
private
{ Private Declarations }
FOwner : TPersistent;
FUpdating : Integer;
FOnNotifyChange : TNotifyEvent;
public
{ Public Declarations }
constructor Create(AOwner: TPersistent); virtual;
procedure NotifyChange(Sender : TObject); virtual;
function GetOwner : TPersistent; override;
property Updating : Integer read FUpdating;
procedure BeginUpdate;
procedure EndUpdate;
property Owner : TPersistent read FOwner;
property OnNotifyChange : TNotifyEvent read FOnNotifyChange write FOnNotifyChange;
end;
// TGLCadenceAbleComponent
//
{: A base class describing the "cadenceing" interface.<p> }
TGLCadenceAbleComponent = class (TGLComponent, IGLProgessAble)
public
{ Public Declarations }
procedure DoProgress(const progressTime : TProgressTimes); virtual;
end;
// TGLUpdateAbleComponent
//
{: A base class describing the "update" interface.<p> }
TGLUpdateAbleComponent = class (TGLCadenceAbleComponent, IGLNotifyAble)
public
{ Public Declarations }
procedure NotifyChange(Sender : TObject); virtual;
end;
// TNotifyCollection
//
TNotifyCollection = class (TOwnedCollection)
private
{ Private Declarations }
FOnNotifyChange : TNotifyEvent;
protected
{ Protected Declarations }
procedure Update(item : TCollectionItem); override;
public
{ Public Declarations }
constructor Create(AOwner : TPersistent; AItemClass : TCollectionItemClass);
property OnNotifyChange : TNotifyEvent read FOnNotifyChange write FOnNotifyChange;
end;
implementation
//---------------------- TGLUpdateAbleObject -----------------------------------------
// Create
//
constructor TGLUpdateAbleObject.Create(AOwner: TPersistent);
begin
inherited Create;
FOwner:=AOwner;
end;
// NotifyChange
//
procedure TGLUpdateAbleObject.NotifyChange(Sender : TObject);
begin
if (FUpdating=0) and Assigned(Owner) then begin
if Owner is TGLUpdateAbleObject then
TGLUpdateAbleObject(Owner).NotifyChange(Self)
else if Owner is TGLUpdateAbleComponent then
TGLUpdateAbleComponent(Owner).NotifyChange(Self);
if Assigned(FOnNotifyChange) then
FOnNotifyChange(Self);
end;
end;
// GetOwner
//
function TGLUpdateAbleObject.GetOwner : TPersistent;
begin
Result:=Owner;
end;
// BeginUpdate
//
procedure TGLUpdateAbleObject.BeginUpdate;
begin
Inc(FUpdating);
end;
// EndUpdate
//
procedure TGLUpdateAbleObject.EndUpdate;
begin
Dec(FUpdating);
if FUpdating<=0 then begin
Assert(FUpdating=0);
NotifyChange(Self);
end;
end;
// ------------------
// ------------------ TGLCadenceAbleComponent ------------------
// ------------------
// DoProgress
//
procedure TGLCadenceAbleComponent.DoProgress(const progressTime : TProgressTimes);
begin
// nothing
end;
// ------------------
// ------------------ TGLUpdateAbleObject ------------------
// ------------------
// NotifyChange
//
procedure TGLUpdateAbleComponent.NotifyChange(Sender : TObject);
begin
if Assigned(Owner) then
if (Owner is TGLUpdateAbleComponent) then
(Owner as TGLUpdateAbleComponent).NotifyChange(Self);
end;
// ------------------
// ------------------ TNotifyCollection ------------------
// ------------------
// Create
//
constructor TNotifyCollection.Create(AOwner: TPersistent; AItemClass: TCollectionItemClass);
begin
inherited Create(AOwner,AItemClass);
if Assigned(AOwner) and (AOwner is TGLUpdateAbleComponent) then
OnNotifyChange:=TGLUpdateAbleComponent(AOwner).NotifyChange;
end;
// Update
//
procedure TNotifyCollection.Update(Item: TCollectionItem);
begin
inherited;
if Assigned(FOnNotifyChange) then
FOnNotifyChange(Self);
end;
end.
|
unit ReportsDataM;
interface
uses
SysUtils, Classes, frxClass, frxExportBaseDialog, frxExportPDF, frxDBSet,
Data.DB, MemDS, DBAccess, Uni, frxGradient, siComp, frxRich,
TypInfo;
type
TReportsDM = class(TDataModule)
RepLng: TUniQuery;
RepLngrptObj: TWideStringField;
RepLngobjEN: TWideStringField;
RepLngobjAR: TWideStringField;
RepParams: TUniQuery;
RepParamsrptObj: TWideStringField;
RepParamsrptParam: TWideStringField;
frxReport1: TfrxReport;
frxPDFExport1: TfrxPDFExport;
frxGradientObject1: TfrxGradientObject;
frxDBDataset1: TfrxDBDataset;
frxRichObject1: TfrxRichObject;
RepDS: TUniQuery;
procedure frxReport1BeforePrint(Sender: TfrxReportComponent);
private
{ Private declarations }
// procedure CloseDS;
// procedure OpenDS(RepName, Id: string; ReportQDS: TUniDataSource);
RepType,RepType2,RepFdate,RepTdate:String;
public
{ Public declarations }
procedure LoadRepoParams(RepTypePar,RepType2Par,RepFdatePar,RepTdatePar:String);
function GenReportPDF(const RepName : string ): String;
end;
implementation
{$R *.dfm}
uses MainModule, ServerModule, rRegister;
//---------------------------------------
//---------------------------------------
//-----------------------------------------====================================
//---------------------------------------
procedure TReportsDM.LoadRepoParams(RepTypePar,RepType2Par,RepFdatePar,RepTdatePar:String);
begin
RepType := RepTypePar;
RepType2:= RepType2Par;
RepFdate:= RepFdatePar;
RepTdate:= RepTdatePar;
end;
//---------------------------------------
////---------------------------------------
procedure TReportsDM.frxReport1BeforePrint(Sender: TfrxReportComponent);
begin
// if Sender.Name = 'RpTypTxt' then
// (sender as TfrxMemoView).Memo.Text := RepType;
// if Sender.Name = 'RpParTxt' then
// (sender as TfrxMemoView).Memo.Text := RepType2;
//
// if Sender.Name = 'MemFdate' then
// (sender as TfrxMemoView).Memo.Text :=DateToStr( FromD.DateTime );
//
// if Sender.Name = 'MemTdate' then
// (sender as TfrxMemoView).Memo.Text := DateToStr( TooD.DateTime );
// if sender is TfrxMemoView then begin /////WOrking;
//
// mMemo := sender as TfrxMemoView;
// EnCap:= mMemo.Text;
//
//
////
// TempQry.SQL.Clear;
// TempQry.SQL.Text := 'Select * from ReportLng where objEn = ''+Income+'' ';// '''+mMemo.Text+''' ';
// TempQry.Open;
// ArCap := TempQry.FieldByName('objAR').AsString;
//
//// PaymentsVQ.FilterSQL := 'PaymentDate Between ''' + YearCB.Text + '-' + MnthCB.Text + '-01'' '
//// +' And ''' + YearCB.Text + '-' + MnthCB.Text + '-30'' '
////
//
//
//// (sender as TfrxMemoView).Memo.Text := StringReplace( (sender as TfrxMemoView).Memo.Text, 'Income', 'ุงูุงูุฑุงุฏ', [rfReplaceAll]);
//
// mMemo.Text :=
// StringReplace( mMemo.Text , mMemo.Text, ArCap, [rfReplaceAll]);
//
//
// end;
// if UniMainModule.RTL then
// ReportLang;
// fProp := GetPropInfo(Sender.ClassInfo, 'Memo.Text');
// if Assigned(fProp) then begin
// // fProp1:=GetPropInfo(Sender., 'Memo.Text');
// EnCap := GetPropValue(Sender.ClassInfo, 'Memo.Text');
// UniMainModule.testTXT:= EnCap;
// end;
// if sender.ClassName = 'TfrxMemoView' then begin
// if (Sender is TfrxMemoView) then begin
//
//
//
// EnCap := (sender as TfrxMemoView).Memo.Text;
// // (sender as TfrxMemoView).Memo.Text := TranslateToArabic(EnCap)
//
// // if RepLng.Locate('rptObj', EnCap, [loCaseInsensitive]) then begin
// RepLng.Locate('rptObj', EnCap, [loCaseInsensitive]);
//
// UniMainModule.testTXT:= RepLng.FieldByName('objAR').AsString;
//// end else begin
//// UniMainModule.testTXT:= EnCap;
////
//// end;
//
//// EnCap :=TranslateToArabic(EnCap);
//// UniMainModule.testTXT:= RepLngobjAR.AsString;
// end;
//UniMainModule.testTXT:= (sender as TfrxMemoView).Memo.Text;
// TfrxMemoView(frxReport1.FindObject(Sender)).Text:= 'MyFirstString';
// frxReport1.Components[2].
// UniMainModule.testTXT:= TfrxMemoView(frxReport1.FindObject(Sender)).Text;
// end;
//-----------------------
// if (Sender is TfrxMemoView) then begin
//
// EnCap := GetPropValue(Sender, 'Text');
//
// for I := 0 to RepLng.RecordCount do begin
//
// if RepLng['rptObj'] = EnCap then begin
// (Sender as TfrxMemoView).Memo.Text := RepLng['objAR'];
//
// end ;
//
// RepLng.Next;
// end;
////
////
// end ;
// for I := 0 to RepLng.RecordCount do begin
// t := TfrxMemoView(frxReport1.FindObject( RepLng['rptObj'])) ;
// if t <> nil then begin
// t.Memo.Text := RepLng['objAR'];
// end;
//
//
// RepLng.Next;
// end;
//
// end;
//
//
// RepParams.First;
// for I := 0 to RepParams.RecordCount do begin
// t := TfrxMemoView(frxReport1.FindObject( RepParams['rptObj'])) ;
// if t <> nil then begin
// t.Memo.Text := RepParams['rptParam'];
// end;
// RepParams.Next;
// end;
//
// if (Sender is TfrxMemoView) then begin
//for I := 0 to frxReport1.ComponentCount do
//
// if ((Sender as TfrxMemoView).Name ) = RepParams['rptObj'] then begin
// (Sender as TfrxMemoView).Memo.Text := RepParams['rptParam'];
// end ;
// RepParams.Next;
// end ;
//
// t := TfrxMemoView(frxReport1.FindObject('Memo15'));
// if t <> nil then
//t.Memo.Text := 'FastReport';
// or this:
//if t <> nil then
//t.Prop['Memo'] := 'FastReport';
//end;
end;
function TReportsDM.GenReportPDF(const RepName :String ): string;
begin
//frxDBDataset1.DataSource := ReportQDS;
RepDS.Open;
try
frxReport1.PrintOptions.ShowDialog := False;
frxReport1.ShowProgress := false;
frxReport1.EngineOptions.SilentMode := True;
frxReport1.EngineOptions.EnableThreadSafe := True;
frxReport1.EngineOptions.DestroyForms := False;
frxReport1.EngineOptions.UseGlobalDataSetList := False;
frxReport1.LoadFromFile(UniMainModule.ReportsPath + RepName + '.fr3');
frxPDFExport1.Background := True;
frxPDFExport1.ShowProgress := False;
frxPDFExport1.ShowDialog := False;
frxPDFExport1.FileName := UniServerModule.NewCacheFileUrl(False, 'pdf', '', '', Result, True);
frxPDFExport1.DefaultPath := '';
frxReport1.PreviewOptions.AllowEdit := False;
frxReport1.PrepareReport;
// frxReport1.ShowPreparedReport; Arabic Language is fine
//frxReport1.Print;
frxReport1.Export(frxPDFExport1);
finally
// CloseDS;
end;
end;
end.
|
unit uPlotClass;
{
*****************************************************************************
* This file is part of Multiple Acronym Math and Audio Plot - MAAPlot *
* *
* See the file COPYING. *
* for details about the copyright. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* *
* MAAplot for Lazarus/fpc *
* (C) 2014 Stefan Junghans *
*****************************************************************************
}
{$DEFINE GUIsupport} // you won't be happy without the context menu....
// This is MAAplot, a Math and Audio Plot Program
// version 141020
// also known as Multiple Acronym Advanced Plot or anything else starting with M A A....
{
What it is : Pascal classes for plotting data, especially 2D measurement data
- Fast modes for 2D waterfall and 3D waterfall and spectrum display.
- for use with Lazarus / fpc
Author Stefan Junghans (C) 2010-2014
Credits Stephan Schamberger (first concept and support)
//
Description: Plots data series into axis grid.
How to use:
1. Establish Plot
2. Establish a PlotRect (or more)
3. Establish Axis (or more) and connect it to OwnerPlotRect
4. Create a Series and give it axes (2 or 3)
TPLot: Container for PlotRects, Axes and Series.
PlotRects: Logical Rects within the Plot area (making plot-in-plot plossible if needed)
Could be regarded as a container for axes and series belonging together.
Used for drawing calculations.
Axis: Logical Axis with arbitrary origin and vector (draws itself)
Axes have also labels drawn next to it.
Cloneaxes could be drawn at other coordinates for indication.
Axes are given a PlotRect as owner.
Series: Currently 2D and 3D Series are implemented which need 2 or 3 axes
Series could have units of measure (Text) drawn next to the used axis.
Fast plotting series for 2D and 3D waterfalls and 2D spectra.
Autoscaling is done on request (AutoScaleSeries(x))
- TPLotSeries: XY Data, plotted to the plot image - no data is kept
- TXYPlotSeries: XY Data, plotted to the plot image - data is kept for redraw
- TXYZPlotSeries: XYZ data, otherwise as XYSeries
- TSpectrumPlotSeries: like XYSeries but plots inderectly via a TLazIntfImage (fast)
- TXYWFPlotSeries: like XYZSeries but plots inderectly via a TLazIntfImage (fast)
Y axis is colored (and not shown otherwise), Z axis is usually time
Series rolls down one line with every new dataline added (waterfall)
- TXYWFPlotSeries: like TXYWFSeries but Y axis is respected.
Shifting is upwards AND to the right giving a 2.5D effect.
Series get axes (2 or 3).
Legends: Part of a PlotRect showing the series names
ColorScales: Part of a PlotRect showing a colorscale (if values are coloured)
MarkerContainer:
Container for Markers within a series.
Marker: Element of a markercontainer, marks something like maxpeak
Constraints:
- Axes must be scaled from low to high value
- ColorScales and Legends shall be horizonal or vertical
//
License: no public license, except otherwise stated with the bundle you received
inquiries to >> MAAplot@junghans-electronics.de <<
}
{ bad bugs:
- ?? whats that ?? (Linux)
- GamesOS: issue with FPU exceptionmask: FPU exceptions (like logn(-x) or x/0) lead to exceptions
on linux we check for exceptions OR we evaluate the result for NaN or inf
on windows this does not work.
If you find some ramaining EDIV0 error or the like, please catch it manually (like if n <> 0 then result := x/n) }
{ minor bugs:
- some properties not needed, unused or deprecated - delete these }
{ compatibility
- Lazarus 0.9.26 .. 1.2.4 (latest testing with Lazarus 1.2.4)
- Linux 3.x.y (i.e. Ubuntu 12.04. and 14.04) with Qt4 (also GTK2, needs some tweaks in uPlotHIDHandler and Markerdrawer)
- Windows XP, 7
}
{ Future improvements:
- Separate data from series drawer so the drawer can be changed without pushing the data again
(currently a series holds all the data to be able to redraw itself).
- Seaparete screen coordinates from internal coordinates to enable arbitrary transforms
- Interpolation also for 3D and more interpolation modes added to simple "linear".
- Value interpolation instead of PixelInterpolation as implemented
- Unified Datatype for plotting (i.e. MAAResult)
- Improved unit structure and more modularizations
- Better exception handling, especially for win32
}
{ Future additions:
- More series like Smith Charts, polar charts
}
{ This component consists of the following units:
- uPlotClass: base classes (TPLot holds a PLotImage = TImage where the display is presented) *
- uPLotDataTypes: basic datatypes
- uPlotRect: plotrect, the container for axes *
- uPlotAxis: axes (to be used by the series as X, Y, Z axis...) *
- uPlotSeries: data series (stores the data for autonomous redrawing)
- uPlotStyles: points, lines etc.; actual drawing is done here
- uPlotTemplates: to ease your life creating plotrects, series and axes, otherwise not needed
- uSeriesMarkers: data storage and data evaluation for markers (like peakmarkers)
- uMarkerDrawer: class for drawing the markers
- uPlotUtils: math helpers
- uPLotInterpolator: connect points with lines (i.e. interpolate between points on a pixel base)
- uPLotOverrides: LazIntfImage changes and additions
- uPlot_ResultWriter: Export data (exports the values, please use ResultReader to read again, stand alone reader available)
- uPlotForms: Helper forms (used with context menu)
- uPlotHIDhandler: Mouse (and keyboard) input handler for Zoom, Pan and AdHoc markers
Along with your copy you should have received
- a license
- a brief user documentation
Please submit feature requests, bug requests and comments to MAAplot@junghans-electronics.de
}
{$mode objfpc}{$H+}
interface
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
SysUtils, Classes, Types, Controls, ExtCtrls, Graphics, math, Menus,
Dialogs, Forms, LCLType, IntfGraphics, FPimage, ExtDlgs, dateutils; // GraphType, dateutils; // GraphType not needed
type
EPlot = class(Exception);
TPlot = class;
TColorPoint = packed record
Pt: TPoint;
Color: TColor;
end;
THIDMouseState = (mcNone, mcMLeft, mcShiftMLeft, mcCtrlMLeft, mcWheel, mcShiftWheel);
THIDMouseStates = set of THIDMouseState;
THIDAction = (haNone, haZoom, haPan, haAdHocMarker);
{ TPlotStyleBase }
{ TODO : test documentation
}
TPlotStyleBase = class
protected
{$HINTS OFF}
procedure DrawPoint(Pt: TPoint; Canvas: TCanvas); virtual; overload;
procedure DrawPoint(Pt: TPoint; Canvas: TCanvas; AColor: TColor); virtual; overload;
procedure DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage); virtual; overload;
procedure DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage; AColor: TColor); virtual; overload;
procedure DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage; AFPColor: TFPColor; AAlphaBlend: Boolean = true; AAlphaMergeOnly: Boolean = false); virtual;overload;
procedure DrawSamplePoint(Pt: TPoint; Canvas: TCanvas; BeginNew: Boolean); virtual;overload;
{$HINTS ON}
public
constructor Create; virtual;
destructor Destroy; override;
end;
TAxisOrientation = (aoHorizontal, aoVertical, aoVariable);
TAutoScaleMode = (asFirstManualThenFit, asFit, asFit125, asFitNext, asFitNextMargined);
TValueRange = packed record
min : Extended;
max : Extended;
end;
TSeriesType = (stBASE, stPLAIN, stXY, stXYZ, stSPECTRUM, stWF2D, stWF3D);
TZoomRecord = record
dbZooming: Boolean;
PlotRectIndex: Integer;
dwOldRect: TRect;
dwNewRect: TRect;
end;
{ TBasePlotRect }
{ This is used as a container for axes, legends, colorscales etc. mainly for position calculations}
TBasePlotRect = class
private
FAutoFrameRect: Boolean;
FAutoRect: Boolean; // deprecated
FOwnerPlot: TPlot;
FVisible: Boolean;
FZooming: Boolean;
function GetBottomLeft: TPoint;
function GetDataRect: TRect;
function GetHeigth: integer;
function GetPlotRectIndex: integer;
function GetSeriesContainedIdx: TFPList;
function GetTopLeft: TPoint;
function GetWidth: integer;
function GetZooming: Boolean;
procedure SetAutoFrameRect(const AValue: Boolean);
procedure SetAutoRect(const AValue: Boolean);
procedure SetClientRect(const AValue: TRect);
procedure SetDataRect(AValue: TRect);
procedure SetFrameRect(const AValue: TRect);
procedure SetOwnerPlot(const APlot: TPlot);
procedure SetVisible(const AValue: Boolean);
procedure SetZooming(AValue: Boolean);
protected
FFrameRect: TRect; // bounds of PlotRect
FClientRect: TRect; // axes length calculation (without text etc.)
FDataRect: TRect; // Data plot area = max. extent of axes
function GetClientRect: TRect; virtual;
function GetFrameRect: TRect; virtual;
procedure Redraw; virtual;
public
constructor Create(OwnerPlot: TPlot); virtual;
destructor Destroy; override;
function PlotImage: TImage;
// ClientRect is inner part of plotrect used for ALL calculations
property ClientRect: TRect read GetClientRect write SetClientRect;
// FrameRect is toal size of plotrect including title, axes-marks, axis label, colorscale and serieslabel (from 12.10.12)
property FrameRect: TRect read GetFrameRect write SetFrameRect;
// DataRect is the Data plot area
property DataRect: TRect read GetDataRect write SetDataRect;
property AutoClientRect: Boolean read FAutoRect write SetAutoRect;
property AutoFrameRect: Boolean read FAutoFrameRect write SetAutoFrameRect;
property Width: integer read GetWidth;
property Heigth: integer read GetHeigth;
property TopLeft: TPoint read GetTopLeft;
property BottomLeft: TPoint read GetBottomLeft;
property OwnerPlot: TPlot read FOwnerPlot write SetOwnerPlot;
property Visible: Boolean read FVisible write SetVisible;
property SeriesContainedIdx: TFPList read GetSeriesContainedIdx;
property PlotRectIndex: integer read GetPlotRectIndex;
property Zooming: Boolean read GetZooming write SetZooming;
end;
(*
TPlotAxis Class
This class will handle the axis operations.
*)
{ TPlotAxisBase }
TPlotAxisBase = class
private
FOwnerPlot: TPlot;
FAutoRect: Boolean; // deprecated
FOwnerPlotRect: TBasePlotRect;
FVisible: Boolean;
FStyle: TPlotStyleBase;
FOrientation: TAxisOrientation;
FViewRange: TValueRange;
procedure SetOwnerPlot(APlot: TPlot);
procedure SetOwnerPlotRect(const AValue: TBasePlotRect);
procedure SetStyle(AStyle: TPlotStyleBase);
procedure SetOrientation(Value: TAxisOrientation);
procedure SetVisible(Value: Boolean);
protected
FNetAxisRect: TRect; // used to check for additional space required for labels and other text
function GetViewRange: TValueRange; virtual;
procedure SetViewRange(AValue: TValueRange); virtual;
function GetPixelsPerValue: Extended; virtual;
function Redraw(ADrawVisible:Boolean): TRect; virtual;
function PlotImage: TImage;
public
constructor Create(OwnerPlot: TPlot); virtual;
destructor Destroy; override;
function CheckSize(out ANetAxisRect: TRect): TRect; virtual; // delivers used rect now while ADataRect excludes text
property OwnerPlot: TPlot read FOwnerPlot write SetOwnerPlot;
property OwnerPlotRect: TBasePlotRect read FOwnerPlotRect write SetOwnerPlotRect;
property Style: TPlotStyleBase read FStyle write SetStyle;
property Orientation: TAxisOrientation read FOrientation write SetOrientation;
property ViewRange : TValueRange read GetViewRange write SetViewRange;
property PixelsPerValue : Extended read GetPixelsPerValue;
property Visible: Boolean read FVisible write SetVisible;
end;
(*
TplotSeries Class
This class will keep all data (not TPLotSeries) and calculate the current point position and draw
it using the style and the assigned axis.
*)
{ TPlotSeriesBase }
TPlotSeriesBase = class
private
FAutoScaleMode: TAutoScaleMode;
FSeriestype: TSeriestype;
FOwnerPlot: TPlot;
FVisible: Boolean;
FStyle: TPlotStyleBase;
FAxis: Integer;
procedure SetAutoScaleMode(AValue: TAutoScaleMode);
procedure SetOwnerPlot(APlot: TPlot);
procedure SetStyle(AStyle: TPlotStyleBase);
procedure SetVisible(Value: Boolean);
protected
FIsFastSeries: Boolean;
FSeriesIndex: Integer;
procedure Redraw; virtual;
function PlotImage: TImage;virtual;
function GetAxesUsed: TList; virtual;
function GetValueRange(AAxisIndex: Integer): TValueRange; virtual;
function GetAutoScaleRange(AAxisIndex: Integer): TValueRange; virtual;
function GetUnitString(AAxisIndex: Integer): ShortString; virtual;
procedure DrawPoint(Pt: TPoint; Canvas: TCanvas); overload;
procedure DrawPoint(Pt: TPoint; Canvas: TCanvas; AColor: TColor); overload;
procedure DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage); overload;
procedure DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage; AColor: TColor); overload;
//procedure DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage; AFPColor: TFPColor); overload;
procedure DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage; AFPColor: TFPColor; AAlphaBlend: Boolean = false; AAlphaMergeOnly: Boolean = false); overload;
procedure DrawSamplePoint(Pt: TPoint; Canvas: TCanvas; BeginNew: Boolean);
public
constructor Create(OwnerPlot: TPlot); virtual;
destructor Destroy; override;
procedure DoPlotToImage; virtual;abstract;
procedure UpdateMarkers(AContainerIndex: Integer);virtual; abstract;
procedure Clear;virtual;abstract;
property AxesUsed: TList read GetAxesUsed; // TODO: better give the index, not the axis
property ValueRange[AAxisIndex: Integer]: TValueRange read GetValueRange;
property AutoScaleRange[AAxisIndex: Integer]: TValueRange read GetAutoScaleRange;
property OwnerPlot: TPlot read FOwnerPlot write SetOwnerPlot;
property OwnerAxis: Integer read FAxis write FAxis;
property Style: TPlotStyleBase read FStyle write SetStyle;
property Visible: Boolean read FVisible write SetVisible;
property UnitString[AAxisIndex: Integer]: ShortString read GetUnitString; // TODO: move to uPlotSeries ?
property SeriesIndex: Integer read FSeriesIndex;// write FSeriesIndex; // TODO: dynamically deliver !!!!!
property IsFastSeries: Boolean read FIsFastSeries;
property SeriesType: TSeriestype read FSeriestype;
property AutoScaleMode: TAutoScaleMode read FAutoScaleMode write SetAutoScaleMode;
end;
{ THelperFormsBase }
{used mainly for the context PopUp menu}
THelperFormsBase = class(TForm)
private
FOwnerPlot: TPlot;
procedure SetOwnerPlot(const APlot: TPlot);
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property OwnerPlot: TPlot read FOwnerPlot write SetOwnerPlot;
end;
{ TPlotMenuHelpers }
{ MenuHelpers are called from the PopupMenu
( The PopUpMenu itself is handeled by TPlot )
MenuHelper Mehods might do some action or evaluation AND/OR
they call some HelperForms (see above)
}
TPlotMenuHelpers = class
private
FFileDialog: TFileDialog;
FColorDialog: TColorDialog;
FHelperFormsExport: THelperFormsBase;
FHelperFormsSeries: THelperFormsBase;
FHelperFormsPlotRect: THelperFormsBase;
FHelperFormsAxes: THelperFormsBase;
FOwnerPlot: TPlot;
procedure SetOwnerPlot(const AValue: TPlot);
protected
public
constructor Create(AOwnerPlot: TPlot); virtual;
destructor Destroy; override;
property OwnerPlot: TPlot read FOwnerPlot;
procedure EvalMenuPlotOpts(Sender: TObject); // 22.03.13
procedure EvalMenuSeriesOpts(Sender:TObject); // markers 22.08.14
procedure EvalMenuPlotRectOpts(Sender:TObject);
procedure EvalMenuAxesOpts(Sender:TObject);
procedure DoMenuPRAutoScale(Sender: TObject);
procedure DoMenuSeriesScale(ASeriesIndex: Integer);
procedure DoMenuSeriesColorChoose(ASeriesIndex: Integer);
procedure DoMenuSeriesStyleChoose(ASeriesIndex: Integer);
procedure DoMenuSeriesMarkersChoose(ASeriesIndex: Integer);
procedure DoMenuPlotRectStyleChoose(APlotRectIndex: Integer);
procedure DoExportImportData(AImport: Boolean; ASeriesIndex: Integer);
end;
{ TPlotHIDHandlerBase }
{Catch mouse/keyboard input for Zoom, Pan or AdHoc marker}
TPlotHIDHandlerBase = class
private
function GetOnMouseDownProc: TMouseEvent;
function GetOnMouseMoveProc: TMouseMoveEvent;
function GetOnMouseUpProc: TMouseEvent;
function GetOnMouseWheelProc: TMouseWheelEvent;
function GetOwnerPlot: TPlot;
function GetZoomInfo: TZoomRecord;
protected
FZoomInfo: TZoomRecord;
FOwnerPlot: TPLot;
FOnMouseWheelProc: TMouseWheelEvent;
FOnMouseUpProc: TMouseEvent;
FOnMouseDownProc: TMouseEvent;
FOnMouseMoveProc: TMouseMoveEvent;
public
constructor Create(AOwnerPlot: TPLot);virtual;
destructor Destroy; override;
procedure GetHIDActionStatesAvail(AHIDAction: THIDAction; out AHIDMouseStates: THIDMouseStates);virtual;abstract;
function SetHIDAction(AHIDAction: THIDAction; AHIDMouseState: THIDMouseState): Integer; virtual;abstract;
procedure GetHIDActionState(AHIDAction: THIDAction; out AHIDMouseState: THIDMouseState); virtual;abstract;
property OwnerPlot: TPlot read GetOwnerPlot;
property OnMouseDown: TMouseEvent read GetOnMouseDownProc; // GetOnMouseDownProc;
property OnMouseUp: TMouseEvent read GetOnMouseUpProc;
property OnMouseMove: TMouseMoveEvent read GetOnMouseMoveProc;
property OnMouseWheel: TMouseWheelEvent read GetOnMouseWheelProc;
property ZoomInfo: TZoomRecord read GetZoomInfo;
end;
(*
TPlot class
This is the main container class.
*)
TPlot = class(TWinControl)
private
FExportDialog: TSavePictureDialog;
FImage: TImage;
FAxis: TList;
FSeries: TList;
FPlotRects: TList;
FMenuHelpers: TPlotMenuHelpers;
FHIDHandler: TPlotHIDHandlerBase;
procedure _Clear;
function _GetImage: TImage;
// axis properties
function GetAxisCount: Integer;
function GetAxis(Index: Integer): TPlotAxisBase;
// series properties
function GetSeriesCount: Integer;
function GetSeries(Index: Integer): TPlotSeriesBase;
// PlotRects properties
function GeTBasePlotRectCount: Integer;
function GeTBasePlotRect(Index: Integer): TBasePlotRect;
private
//FDebugTime1, FDebugTime2: TTime;
FExportPrinterFriedlyColors: Boolean;
FExportSize: TSize;
FMPlotRectDown: Integer;
//FMLeftButtonDown: Boolean; // currently unused - could be used for smart drawing of zoomrects
FSmartSizing: Boolean; // if set from outside, series are NOT redrawn for smart Repaint routine...
// do this when you have huge waterfalls - set SmartSize when resizing host, reset when finished (i.e. left mouse released)
// TODO: is not fully implemented, do not use (just an idea)
FBackGroundColor: TColor;
FOnResize: TNotifyEvent;
FStyle: TPlotStyleBase;
FTimedRefresh: Boolean;
procedure DoOnResize(Sender: TObject); reintroduce;
function GetZoominfo: TZoomRecord;
procedure SetBackGroundColor(const AValue: TColor);
procedure SetPopupMenu(const AValue: TPopupMenu);
procedure SetStyle(const AStyle: TPlotStyleBase);
procedure DoExportToFilePlot(Sender: TObject);
protected
function RegisterPlotObject(Obj: TObject) : Integer; virtual;
procedure UnregisterPlotObject(Obj: TObject); virtual;
procedure OnPaintImage(Sender: TObject); experimental;
property MousePlotRectDown: Integer read FMPlotRectDown;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function ScrCoordToPlotRect(X, Y: Integer; out PlotRectIndex: Integer): Integer;
// new HID handling 10.09.14
procedure DrawZoomRect(AZoomInfo: TZoomRecord);
procedure Zoom(AZoomInfo: TZoomRecord);
procedure Zoom(AZoomInfo: TZoomRecord; ACenterPoint: TPoint; AFactorX: Extended; AFactorY: Extended);
procedure Pan(AZoomInfo: TZoomRecord);
// PopupMenu functions
procedure AddPMContextItems(AMenu: TObject);
procedure CheckPMContextItems(AMenu: TObject);
procedure RemovePMContextItems(AMenu: TObject);
procedure Repaint; override;
procedure AutoScaleSeries(ASeriesIndex: Integer; AGrowOnly: Boolean = FALSE);
procedure AutoScalePlotRect(APlotRectIndex: Integer);
procedure LockImage(ADoLock: Boolean);
procedure ExportToFile(AFileName: TFilename);
procedure ClearAll; // attention: removes everything (series, axes, plotrects..)
procedure ForceRefreshFastPlotRects;
property PlotImage: TImage read _GetImage;
property OnResize: TNotifyEvent read FOnResize write FOnResize;
property BackgroundColor: TColor read FBackGroundColor write SetBackGroundColor;
property Style: TPlotStyleBase read FStyle write SetStyle;
property AxisCount: Integer read GetAxisCount;
property Axis[Index: Integer]: TPlotAxisBase read GetAxis;
property SeriesCount: Integer read GetSeriesCount;
property Series[Index: Integer]: TPlotSeriesBase read GetSeries;
property PlotRectCount: Integer read GeTBasePlotRectCount;
property PlotRect[Index: Integer]: TBasePlotRect read GeTBasePlotRect;
property ExportSize: TSize read FExportSize write FExportSize;
property ExportPrinterFriedlyColors: Boolean read FExportPrinterFriedlyColors write FExportPrinterFriedlyColors;
property TimedRefresh: Boolean read FTimedRefresh write FTimedRefresh; // use this for refresh rates > 20..40/sec
property SmartSizing: Boolean read FSmartSizing write FSmartSizing; // currently unused
property HIDHandler: TPlotHIDHandlerBase read FHIDHandler; // class for handling mouse/key actions for zoom, pan etc
end;
const
c_GLOBALMIN = 1e-30; // used to avoid SIGFPE, maximum value the component will handle
c_GLOBALMAX = 1e30; // and for var init , minimum value the component will handle
c_INVALIDCOORDINATE = -16777216;
c_MAININTERVAL_MAXDIGITS = 10; // maximum fractional digits for formatting numbers
implementation
uses uPlotStyles, uPlotRect, uPlotUtils, uPlotSeries, uPlotForms, uPlotAxis, uPlotHIDHandler;
resourcestring
S_InvalidPlotStyle = 'This is a invalid PlotStyle.'#13#10+
'Please use one of uPlotStyles unit.';
S_InvalidSeries = 'This is a invalid PlotSeries.'#13#10+
'Please use one of uPlotSeries unit.';
S_UnknownPlotObject = 'Unable to register unknown plot object.';
//S_MaxSmallerMin = 'Maximun cannot be smaller than minimum.';
//S_MinHigherMax = 'Minimum cannot be higher than maximum.';
{ TPlotHIDHandlerBase }
function TPlotHIDHandlerBase.GetOnMouseDownProc: TMouseEvent;
begin
Result := FOnMouseDownProc;
end;
function TPlotHIDHandlerBase.GetOnMouseMoveProc: TMouseMoveEvent;
begin
Result := FOnMouseMoveProc;
end;
function TPlotHIDHandlerBase.GetOnMouseUpProc: TMouseEvent;
begin
Result := FOnMouseUpProc;
end;
function TPlotHIDHandlerBase.GetOnMouseWheelProc: TMouseWheelEvent;
begin
Result := FOnMouseWheelProc;
end;
function TPlotHIDHandlerBase.GetOwnerPlot: TPlot;
begin
Result := FOwnerPlot;
end;
function TPlotHIDHandlerBase.GetZoomInfo: TZoomRecord;
begin
Result := FZoominfo;
end;
constructor TPlotHIDHandlerBase.Create(AOwnerPlot: TPLot);
begin
FOwnerPlot := AOwnerPlot;
FOnMouseDownProc := nil;
FOnMouseUpProc := nil;
FOnMouseMoveProc := nil;
FOnMouseWheelProc := nil;
end;
destructor TPlotHIDHandlerBase.Destroy;
begin
inherited Destroy;
FOnMouseDownProc := nil;
FOnMouseUpProc := nil;
FOnMouseMoveProc := nil;
FOnMouseWheelProc := nil;
end;
{ TPlotStyleBase }
// **************************************************************************
{$HINTS OFF}
procedure TPlotStyleBase.DrawPoint(Pt: TPoint; Canvas: TCanvas);
begin
raise EPlot.CreateRes(@S_InvalidPlotStyle);
end;
procedure TPlotStyleBase.DrawPoint(Pt: TPoint; Canvas: TCanvas; AColor: TColor);
begin
raise EPlot.CreateRes(@S_InvalidPlotStyle);
end;
procedure TPlotStyleBase.DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage);
begin
raise EPlot.CreateRes(@S_InvalidPlotStyle);
end;
procedure TPlotStyleBase.DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage;
AColor: TColor);
begin
raise EPlot.CreateRes(@S_InvalidPlotStyle);
end;
procedure TPlotStyleBase.DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage;
AFPColor: TFPColor; AAlphaBlend: Boolean; AAlphaMergeOnly: Boolean = false);
begin
raise EPlot.CreateRes(@S_InvalidPlotStyle);
end;
procedure TPlotStyleBase.DrawSamplePoint(Pt: TPoint; Canvas: TCanvas; BeginNew: Boolean);
begin
raise EPlot.CreateRes(@S_InvalidPlotStyle);
end;
constructor TPlotStyleBase.Create;
begin
inherited Create;
end;
destructor TPlotStyleBase.Destroy;
begin
inherited Destroy;
end;
{$HINTS ON}
{ TPlotAxisBase }
// **************************************************************************
constructor TPlotAxisBase.Create(OwnerPlot: TPlot);
begin
FOwnerPlot := OwnerPlot;
inherited Create;
FAutoRect := TRUE;
FViewRange.min := 0;
FViewRange.max := 100;
FVisible := TRUE;
// create default style object
FStyle := uPlotStyles.TAxisStyle.Create;
FOrientation := aoHorizontal;
// register axis in the plot container object
OwnerPlot.RegisterPlotObject(Self);
IF OwnerPlot.PlotRect[0] <> nil THEN FOwnerPlotRect := OwnerPlot.PlotRect[0]
ELSE FOwnerPlotRect := TBasePlotRect.Create(OwnerPlot);
FNetAxisRect := Rect(0,0,0,0);
end;
destructor TPlotAxisBase.Destroy;
begin
Visible := FALSE;
OwnerPlot.UnRegisterPlotObject(Self);
OwnerPlot := nil; Style := nil;
inherited;
end;
function TPlotAxisBase.CheckSize(out ANetAxisRect: TRect): TRect;
begin
ANetAxisRect := Rect(0,0,0,0);
Result := Self.Redraw(FALSE);
ANetAxisRect := FNetAxisRect;
end;
function TPlotAxisBase.PlotImage: TImage;
begin Result := OwnerPlot.PlotImage; end;
function TPlotAxisBase.Redraw(ADrawVisible: Boolean): TRect;
var vDrawRect: TRect;
ptA, ptB: TPoint;
begin
IF (not Visible) or (not ADrawVisible) THEN exit;
{IF FAutoRect THEN
vDrawRect := OwnerPlot.PlotImage.ClientRect
ELSE vDrawRect := FClientRect; }
vDrawRect := OwnerPlotRect.ClientRect;
case Orientation of
aoHorizontal : begin
ptA.X := vDrawRect.Left;
ptA.Y := vDrawRect.Bottom;
ptB.X := vDrawRect.Right;
ptB.Y := ptA.Y;
uPlotStyles.TAxisStyle(Style).DrawLine(ptA, ptB, PlotImage.Canvas);
end;
aoVertical : begin
ptA.X := vDrawRect.Left;
ptA.Y := vDrawRect.Bottom;
ptB.X := ptA.X;
ptB.Y := vDrawRect.Top;
uPlotStyles.TAxisStyle(Style).DrawLine(ptA, ptB, PlotImage.Canvas);
end;
end;
Result := vDrawRect;
end;
procedure TPlotAxisBase.SetOrientation(Value: TAxisOrientation);
begin
IF Value = FOrientation THEN exit;
FOrientation := Value;
OwnerPlot.Repaint;
end;
procedure TPlotAxisBase.SetViewRange(AValue: TValueRange);
begin
FViewRange.min := AValue.min;
FViewRange.max := AValue.max;
IF FViewRange.min >= FViewRange.max THEN BEGIN
FViewRange.max := FViewRange.min + 1;// c_GLOBALMIN; // c_GlobalMin does not work (too small here ?)
END;
end;
procedure TPlotAxisBase.SetOwnerPlot(APlot: TPlot);
begin
IF APlot = FOwnerPlot THEN exit;
IF FOwnerPlot <> nil THEN
FOwnerPlot.UnregisterPlotObject(Self);
FOwnerPlot := APlot;
IF FOwnerPlot <> nil THEN
begin
FOwnerPlot.RegisterPlotObject(Self);
OwnerPlot.Repaint;
end;
end;
function TPlotAxisBase.GetViewRange: TValueRange;
begin
Result := FViewRange;
end;
function TPlotAxisBase.GetPixelsPerValue: Extended;
begin
Result := 1;
end;
procedure TPlotAxisBase.SetOwnerPlotRect(const AValue: TBasePlotRect);
begin
if FOwnerPlotRect=AValue then exit;
FOwnerPlotRect:=AValue;
end;
procedure TPlotAxisBase.SetStyle(AStyle: TPlotStyleBase);
begin
IF AStyle = FStyle THEN exit;
IF FStyle <> nil THEN FreeAndNil(FStyle);
FStyle := AStyle;
IF (FStyle <> nil) AND (OwnerPlot <> nil) THEN OwnerPlot.Repaint;
end;
procedure TPlotAxisBase.SetVisible(Value: Boolean);
begin
IF Value = FVisible THEN exit;
FVisible := Value;
IF FVisible THEN OwnerPlot.Repaint;
end;
{ TPlotSeriesBase }
// **************************************************************************
constructor TPlotSeriesBase.Create(OwnerPlot: TPlot);
begin
FSeriestype := stBase;
FIsFastSeries := FALSE;
FOwnerPlot := OwnerPlot;
inherited Create;
FStyle := uPlotStyles.TSeriesStyle.Create;
uPlotStyles.TSeriesStyle(FStyle).OwnerSeries := Self;
FVisible := TRUE;
// register series in the plot container object
FSeriesIndex := OwnerPlot.RegisterPlotObject(Self);
FAutoScaleMode := asFitNextMargined; // asFit, asFit125, asFirstManualThenFit, asFitNext;
end;
destructor TPlotSeriesBase.Destroy;
begin
Visible := FALSE;
//OwnerPlot.UnRegisterPlotObject(Self); is done with next line Ownerplot:=nil;
OwnerPlot := nil; Style := nil;
inherited;
end;
procedure TPlotSeriesBase.DrawPoint(Pt: TPoint; Canvas: TCanvas);
begin Style.DrawPoint(Pt, Canvas); end;
procedure TPlotSeriesBase.DrawPoint(Pt: TPoint; Canvas: TCanvas; AColor: TColor);
begin
Style.DrawPoint(Pt, Canvas, AColor);
end;
procedure TPlotSeriesBase.DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage);
begin
Style.DrawPoint(Pt, ADataImage);
end;
procedure TPlotSeriesBase.DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage;
AColor: TColor);
begin
Style.DrawPoint(Pt, ADataImage, AColor);
end;
procedure TPlotSeriesBase.DrawPoint(Pt: TPoint; ADataImage: TLazIntfImage;
AFPColor: TFPColor; AAlphaBlend: Boolean = false; AAlphaMergeOnly: Boolean = false);
begin
Style.DrawPoint(Pt, ADataImage, AFPColor, AAlphaBlend, AAlphaMergeOnly);
end;
procedure TPlotSeriesBase.DrawSamplePoint(Pt: TPoint; Canvas: TCanvas;
BeginNew: Boolean);
begin
Style.DrawSamplePoint(Pt, Canvas, BeginNew);
end;
function TPlotSeriesBase.PlotImage: TImage;
begin Result := OwnerPlot.PlotImage; end;
procedure TPlotSeriesBase.Redraw;
begin
raise EPlot.CreateRes(@S_InvalidSeries);
end;
procedure TPlotSeriesBase.SetOwnerPlot(APlot: TPlot);
begin
IF APlot = FOwnerPlot THEN exit;
IF FOwnerPlot <> nil THEN
FOwnerPlot.UnregisterPlotObject(Self);
FOwnerPlot := APlot;
IF FOwnerPlot <> nil THEN
begin
FOwnerPlot.RegisterPlotObject(Self);
OwnerPlot.Repaint;
end;
end;
procedure TPlotSeriesBase.SetAutoScaleMode(AValue: TAutoScaleMode);
begin
if FAutoScaleMode=AValue then Exit;
FAutoScaleMode:=AValue;
end;
function TPlotSeriesBase.GetAutoScaleRange(AAxisIndex: Integer): TValueRange;
begin
Result.min := -1;
Result.max := 1; // this is default, TPlotSeriesBase and TPlotSeries do not store values
end;
function TPlotSeriesBase.GetUnitString(AAxisIndex: Integer): ShortString;
begin
Result:='not available in base class';
end;
function TPlotSeriesBase.GetValueRange(AAxisIndex: Integer): TValueRange;
var
vResult: TValueRange;
begin
vResult.min := 0; //c_GLOBALMAX;
vResult.max := 0; //c_GLOBALMIN;
Result := vResult;
end;
function TPlotSeriesBase.GetAxesUsed: TList;
var
vItem : PInteger;
begin
try
Result := TList.Create;
new(vItem);
try
vItem^ := OwnerAxis;
Result.Add(vItem);
except
Dispose(vItem); raise;
end;
except
FreeAndNil(Result);
raise;
end;
end;
procedure TPlotSeriesBase.SetStyle(AStyle: TPlotStyleBase);
begin
IF AStyle = FStyle THEN exit;
IF FStyle <> nil THEN FreeAndNil(FStyle);
FStyle := AStyle;
// set OwnerSeries of style if possible
IF AStyle is uPlotStyles.TSeriesStyle
THEN uPlotStyles.TSeriesStyle(FStyle).OwnerSeries := Self;
// repaint if possible
IF (FStyle <> nil) AND (OwnerPlot <> nil) THEN OwnerPlot.Repaint;
end;
procedure TPlotSeriesBase.SetVisible(Value: Boolean);
begin
IF Value = FVisible THEN exit;
FVisible := Value;
IF FVisible THEN OwnerPlot.Repaint;
end;
{ TPlot }
// **************************************************************************
// **************************************************************************
constructor TPlot.Create(AOwner: TComponent);
begin
inherited;
FSmartSizing:=false;
FTimedRefresh:=FALSE;
FImage := TImage.Create(Self);
FImage.Parent := Self;
FImage.Align := alClient;
FImage.Visible := TRUE;
inherited OnResize := @Self.DoOnResize;
FAxis := TList.Create;
FSeries := TList.Create;
FPlotRects := TList.Create;
// we do NOT create default axes, plotrects or series, just the lists
FBackgroundColor := clLtGray;
FHIDHandler := TPlotHIDHandler.Create(Self);
FImage.OnMouseDown := FHIDHandler.OnMouseDown;
FImage.OnMouseUp := FHIDHandler.OnMouseUp;
FImage.OnMouseWheel := FHIDHandler.OnMouseWheel;
FImage.OnMouseMove := nil; //set by HIDHandler if needed
FIMage.OnPaint:=@OnPaintImage; // use this when you do not want to draw to TIMage.Picture.Bitmap.Canvas
// I noticed no speed improvement when drawing during onpaint, so we still paint to the persistent bitmap
FExportSize.cx := 1024;
FExportSize.cy := 768;
FExportPrinterFriedlyColors := TRUE;
{$IFDEF GUIsupport}
FMenuHelpers := TPlotMenuHelpers.Create(Self);
PopupMenu := TPopupMenu.Create(Self);
PopupMenu.AutoPopup := TRUE;
AddPMContextItems(PopupMenu);
PopupMenu.OnPopup := @CheckPMContextItems;
{$ENDIF}
end;
destructor TPlot.Destroy;
begin
_Clear;
FHIDHandler.Free;
{$IFDEF GUIsupport}
FMenuHelpers.Free;
RemovePMContextItems(PopupMenu);;
{$ENDIF}
FSeries.Free; FAxis.Free; FPlotRects.Free;
//
FImage.Free;
inherited;
end;
procedure TPlot.DrawZoomRect(AZoomInfo: TZoomRecord);
begin
TPlotRect(PlotRect[AZoominfo.PlotRectIndex]).UpdateZoomRect;
end;
procedure TPlot.Zoom(AZoomInfo: TZoomRecord);
var
vRect: TRect;
begin
vRect.Left:= Min(AZoomInfo.dwNewRect.Left, AZoomInfo.dwNewRect.Right);
vRect.Right:= Max(AZoomInfo.dwNewRect.Left, AZoomInfo.dwNewRect.Right);
vRect.Top:= Min(AZoomInfo.dwNewRect.Bottom, AZoomInfo.dwNewRect.Top);
vRect.Bottom:= Max(AZoomInfo.dwNewRect.Bottom, AZoomInfo.dwNewRect.Top);
// zoom PR
TPlotRect(PlotRect[AZoomInfo.PlotRectIndex]).Zoom(vRect);
end;
procedure TPlot.Zoom(AZoomInfo: TZoomRecord; ACenterPoint: TPoint; AFactorX: Extended; AFactorY: Extended);
begin
TPlotRect(PlotRect[AZoomInfo.PlotRectIndex]).Zoom(ACenterPoint.X, ACenterPoint.Y, AFactorX, AFactorY);
end;
procedure TPlot.Pan(AZoomInfo: TZoomRecord);
begin
if (AZoomInfo.PlotRectIndex < PlotRectCount) and (AZoomInfo.PlotRectIndex >= 0) then
TPlotRect(PlotRect[AZoomInfo.PlotRectIndex]).Pan(-AZoomInfo.dwNewRect.Right + AZoomInfo.dwOldRect.Right, AZoomInfo.dwNewRect.Bottom - AZoomInfo.dwOldRect.Bottom);
end;
procedure TPlot.AddPMContextItems(AMenu: TObject);
// used to populate the PM with the top level items
var
vItem: TMenuItem;
begin
IF not (AMenu is TPopupMenu) then exit;
// auto scale rect
vItem := TMenuItem.Create(AMenu as TPopupMenu);
vItem.Caption := 'AutoScale PlotRect';
vItem.OnClick := @FMenuHelpers.DoMenuPRAutoScale;
TPopupMenu(AMenu).Items.Add(vItem);
// Plot settings file export
vItem := TMenuItem.Create(AMenu as TPopupMenu);
vItem.Caption := 'Plot ...';
TPopupMenu(AMenu).Items.Add(vItem);
vItem := TMenuItem.Create(AMenu as TPopupMenu);
vItem.Caption := 'Settings';
vItem.OnClick := @FMenuHelpers.EvalMenuPlotOpts;
TPopupMenu(AMenu).Items[1].Add(vItem);
vItem := TMenuItem.Create(AMenu as TPopupMenu);
vItem.Caption := 'Export to file';
vItem.OnClick := @FMenuHelpers.EvalMenuPlotOpts;
TPopupMenu(AMenu).Items[1].Add(vItem);
vItem := TMenuItem.Create(AMenu as TPopupMenu);
vItem.Caption := '-';
TPopupMenu(AMenu).Items[1].Add(vItem);
vItem := TMenuItem.Create(AMenu as TPopupMenu);
vItem.Caption := 'Clear all data';
vItem.OnClick := @FMenuHelpers.EvalMenuPlotOpts;
TPopupMenu(AMenu).Items[1].Add(vItem);
// series menu
vItem := TMenuItem.Create(AMenu as TPopupMenu);
vItem.Caption := 'Series';
TPopupMenu(AMenu).Items.Add(vItem);
// plotrect menu
vItem := TMenuItem.Create(AMenu as TPopupMenu);
vItem.Caption := 'PlotRect';
TPopupMenu(AMenu).Items.Add(vItem);
// axes menu
vItem := TMenuItem.Create(AMenu as TPopupMenu);
vItem.Caption := 'Axes';
TPopupMenu(AMenu).Items.Add(vItem);
end;
procedure TPlot.CheckPMContextItems(AMenu: TObject);
//TODO: find out number of submenu instead of fixed numer "2" or "3"
var
vName: String;
vLoop: Integer;
vSubItem, vSubSubItem, vSub3Item: TMenuItem;
vItem: TMenuItem;
vItemNumber: Integer;
vMCoord, vOrigin: TPoint;
begin
IF not (AMenu is TPopupMenu) then exit;
vMCoord := Mouse.CursorPos;
vOrigin := FImage.ClientOrigin;
ScrCoordToPlotRect(vMCoord.X - vOrigin.X,
vMCoord.Y-vOrigin.Y, FMPlotRectDown);
//
// adjust visibility of items not needed outside plotrects
vItem := TPopupMenu(AMenu).Items.Find('AutoScale PlotRect');
IF vItem <> nil THEN
vItem.Visible := (FMPlotRectDown >= 0);
vItem := TPopupMenu(AMenu).Items.Find('Series');
IF vItem <> nil THEN
vItem.Visible := (FMPlotRectDown >= 0);
IF FMPlotRectDown < 0 THEN exit;
// SERIES ------------------------------------------
// remove subitems SERIES
vItem := TPopupMenu(AMenu).Items.Find('Series');
vItemNumber := TPopupMenu(AMenu).Items.IndexOf(vItem);
IF TPopupMenu(AMenu).ComponentCount > 0 THEN
while (TPopupMenu(AMenu).Items[vItemNumber].Count > 0) do
TPopupMenu(AMenu).Items[vItemNumber].Remove(TMenuItem(TPopupMenu(AMenu).Items[vItemNumber].Items[0] ));
// add subitems manual scale
with PlotRect[FMPlotRectDown].SeriesContainedIdx do try
// attach ManualScale to series
for vLoop := 0 to Count-1 do begin
// attach one series as subitem
BEGIN
vName := TPlotSeries(Series[Pinteger(Items[vLoop])^]).Caption;
vSubItem := TMenuItem.Create(vItem);
vSubItem.Caption := IntToStr(Pinteger(Items[vLoop])^) + ' - ' + vName;
//TPopupMenu(AMenu).Items[vItemNumber].Add(vSubItem); // for ADD
TPopupMenu(AMenu).Items[vItemNumber].Insert(0,vSubItem);
// attach subsubitems "ManualScale" ------------------------------------
vSubSubItem := TMenuItem.Create(vSubItem);
vSubSubItem.Caption := 'Manual scale';
vSubSubItem.OnClick := @FMenuHelpers.EvalMenuSeriesOpts;
//TPopupMenu(AMenu).Items[vItemNumber].Items[vLoop].Add(vSubSubItem); // for ADD
TPopupMenu(AMenu).Items[vItemNumber].Items[0].Add(vSubSubItem); // for Insert
// attach subsubitems "ColorChoose" ------------------------------------
vSubSubItem := TMenuItem.Create(vSubItem);
vSubSubItem.Caption := 'Color';
vSubSubItem.OnClick := @FMenuHelpers.EvalMenuSeriesOpts;
//TPopupMenu(AMenu).Items[vItemNumber].Items[vLoop].Add(vSubSubItem); // for ADD
TPopupMenu(AMenu).Items[vItemNumber].Items[0].Add(vSubSubItem); // for Insert
// attach subsubitems "StyleChoose" ------------------------------------
vSubSubItem := TMenuItem.Create(vSubItem);
vSubSubItem.Caption := 'Style';
vSubSubItem.OnClick := @FMenuHelpers.EvalMenuSeriesOpts;
//TPopupMenu(AMenu).Items[vItemNumber].Items[vLoop].Add(vSubSubItem); // for ADD
TPopupMenu(AMenu).Items[vItemNumber].Items[0].Add(vSubSubItem); // for Insert
// attach subsubitems "Markers" ------------------------------------ // 22.08.14
vSubSubItem := TMenuItem.Create(vSubItem);
vSubSubItem.Caption := 'Markers';
vSubSubItem.OnClick := @FMenuHelpers.EvalMenuSeriesOpts;
//TPopupMenu(AMenu).Items[vItemNumber].Items[vLoop].Add(vSubSubItem); // for ADD
TPopupMenu(AMenu).Items[vItemNumber].Items[0].Add(vSubSubItem); // for Insert
// attach subsubitems "Data" ------------------------------------------
vSubSubItem := TMenuItem.Create(vSubItem);
vSubSubItem.Caption := 'Data';
//vSubSubItem.OnClick := @FMenuHelpers.EvalMenuSeriesOpts;
//TPopupMenu(AMenu).Items[vItemNumber].Items[vLoop].Add(vSubSubItem); // for ADD
TPopupMenu(AMenu).Items[vItemNumber].Items[0].Add(vSubSubItem); // for Insert
// attach sub3item "Data"
vSub3Item := TMenuItem.Create(vSubItem);
vSub3Item.Caption := 'Clear';
vSub3Item.OnClick := @FMenuHelpers.EvalMenuSeriesOpts;
//TPopupMenu(AMenu).Items[vItemNumber].Items[vLoop].Add(vSubSubItem); // for ADD
TPopupMenu(AMenu).Items[vItemNumber].Items[0].Items[TPopupMenu(AMenu).Items[vItemNumber].Items[0].Count-1].Add(vSub3Item); // for Insert
// attach sub3item "Data"
vSub3Item := TMenuItem.Create(vSubItem);
vSub3Item.Caption := 'Export';
vSub3Item.OnClick := @FMenuHelpers.EvalMenuSeriesOpts;
//TPopupMenu(AMenu).Items[vItemNumber].Items[vLoop].Add(vSubSubItem); // for ADD
TPopupMenu(AMenu).Items[vItemNumber].Items[0].Items[TPopupMenu(AMenu).Items[vItemNumber].Items[0].Count-1].Add(vSub3Item); // for Insert
// attach sub3item "Data"
vSub3Item := TMenuItem.Create(vSubItem);
vSub3Item.Caption := 'Import';
vSub3Item.OnClick := @FMenuHelpers.EvalMenuSeriesOpts;
//TPopupMenu(AMenu).Items[vItemNumber].Items[vLoop].Add(vSubSubItem); // for ADD
TPopupMenu(AMenu).Items[vItemNumber].Items[0].Items[TPopupMenu(AMenu).Items[vItemNumber].Items[0].Count-1].Add(vSub3Item); // for Insert
// test case: more than one series in plotrect with non-ongoing numbers
END;
//
end;
finally
while Count > 0 do begin
Dispose(Pinteger(Items[0]));
Delete(0);
end;
Free;
end;
// PLOTRECT ------------------------------------------
// remove subitems plotrect
vItem := TPopupMenu(AMenu).Items.Find('PlotRect');
vItemNumber := TPopupMenu(AMenu).Items.IndexOf(vItem);
IF TPopupMenu(AMenu).ComponentCount > 0 THEN
while (TPopupMenu(AMenu).Items[vItemNumber].Count > 0) do
TPopupMenu(AMenu).Items[vItemNumber].Remove(TMenuItem(TPopupMenu(AMenu).Items[vItemNumber].Items[0] ));
// add subitems
vName := TPlotRect(PlotRect[FMPlotRectDown]).Title;
vSubItem := TMenuItem.Create(vItem);
vSubItem.Caption := IntToStr(FMPlotRectDown) + ' - ' + vName;
TPopupMenu(AMenu).Items[vItemNumber].Add(vSubItem);
// attach subsubitems "StyleChoose"
vSubSubItem := TMenuItem.Create(vSubItem);
vSubSubItem.Caption := 'Properties';
vSubSubItem.OnClick := @FMenuHelpers.EvalMenuPlotRectOpts;
TPopupMenu(AMenu).Items[vItemNumber].Items[0].Add(vSubSubItem); // TODO: number by code
// AXES ------------------------------------------
// remove subitems axes
vItem := TPopupMenu(AMenu).Items.Find('Axes');
vItemNumber := TPopupMenu(AMenu).Items.IndexOf(vItem);
IF TPopupMenu(AMenu).ComponentCount > 0 THEN
while (TPopupMenu(AMenu).Items[vItemNumber].Count > 0) do
TPopupMenu(AMenu).Items[vItemNumber].Remove(TMenuItem(TPopupMenu(AMenu).Items[vItemNumber].Items[0] ));
for vLoop := 0 to AxisCount - 1 do begin
IF Axis[vLoop].OwnerPlotRect.PlotRectIndex = FMPlotRectDown THEN BEGIN
vSubItem := TMenuItem.Create(vItem);
vSubItem.Caption := (IntToStr(vLoop) + ' - ' + TPlotAxis(Axis[vLoop]).AxisLabel );
vSubItem.OnClick := @FMenuHelpers.EvalMenuAxesOpts;
TPopupMenu(AMenu).Items[vItemNumber].Add(vSubItem);
END;
end;
end;
procedure TPlot.RemovePMContextItems(AMenu: TObject);
begin
// remove everything
while (TPopupMenu(AMenu).Items.Count > 0) do begin
while (TPopupMenu(AMenu).Items[0].Count > 0) do begin
TPopupMenu(AMenu).Items[0].Remove(TMenuItem(TPopupMenu(AMenu).Items[0].Items[0] ));
end;
TPopupMenu(AMenu).Items.Remove(TMenuItem(TPopupMenu(AMenu).Items[0] ));
end;
end;
procedure TPlot.DoOnResize(Sender: TObject);
begin
Repaint;
end;
function TPlot.GetZoominfo: TZoomRecord;
begin
Result := FHIDHandler.ZoomInfo;
end;
procedure TPlot.SetBackGroundColor(const AValue: TColor);
begin
if FBackGroundColor=AValue then exit;
FBackGroundColor:=AValue;
end;
procedure TPlot.SetPopupMenu(const AValue: TPopupMenu);
begin
IF AValue <> nil THEN
FImage.PopupMenu := AValue;
end;
procedure TPlot.SetStyle(const AStyle: TPlotStyleBase);
begin
IF AStyle = FStyle THEN exit;
IF FStyle <> nil THEN FreeAndNil(FStyle);
FStyle := AStyle;
IF (FStyle <> nil) THEN Repaint;
end;
function TPlot.ScrCoordToPlotRect(X, Y: Integer; out PlotRectIndex: Integer
): Integer;
var
vPlotX, vPlotY: Integer;
vLoop: Integer;
vIndex: Integer;
begin
Result := -1; PlotRectIndex := -1; vIndex := -1;
IF PlotRectCount < 1 THEN exit;
// transform screen to Plot (FImage)
vPlotX := X - PlotImage.ClientRect.Left;
vPlotY := Y - PlotImage.ClientRect.Top;
// check if it is in a PlotRect (from high to low order
// so we have highest plotrects respected first for zooming, i.e. they are topmost
for vLoop := PlotRectCount-1 downto 0 do begin
IF IsInsideRect(vPlotX, vPlotY, PlotRect[vLoop].ClientRect) THEN BEGIN
vIndex := vLoop;
Result := 0;
break;
end;
end;
PlotRectIndex := vIndex;
end;
procedure TPlot.DoExportToFilePlot(Sender: TObject);
var
vFreeDialog: Boolean;
vFileName: TFilename;
vExtension: String;
begin
vFreeDialog := FExportDialog = nil;
if FExportDialog = nil then FExportDialog := TSavePictureDialog.Create(Self);
try
FExportDialog.Filter := 'Bitmap|*.bmp|PNG|*.png';
if FExportDialog.Execute then begin
vFileName := FExportDialog.FileName;
vExtension := '.' + FExportDialog.GetFilterExt;
end;
finally
if vFreeDialog then FreeAndNil(FExportDialog);
end;
IF UpperCase(vExtension) <> UpperCase(ExtractFileExt(vFileName)) THEN
vFileName := vFileName + '.' + vExtension;
ExportToFile(vFileName);
end;
function TPlot.GeTBasePlotRect(Index: Integer): TBasePlotRect;
begin
IF (Index > PlotRectCount-1) then exit;
Result := TBasePlotRect(FPlotRects.Items[Index]);
end;
function TPlot.GeTBasePlotRectCount: Integer;
begin Result := FPlotRects.Count; end;
function TPlot.GetAxis(Index: Integer): TPlotAxisBase;
begin
IF (Index > AxisCount-1) then exit;
Result := TPlotAxisBase(FAxis.Items[Index]);
end;
function TPlot.GetAxisCount: Integer;
begin Result := FAxis.Count; end;
function TPlot.GetSeries(Index: Integer): TPlotSeriesBase;
begin
IF (Index > SeriesCount-1) then exit;
Result := TPlotSeriesBase(FSeries.Items[Index]);
end;
function TPlot.GetSeriesCount: Integer;
begin Result := FSeries.Count; end;
function TPlot.RegisterPlotObject(Obj: TObject): Integer;
begin
Result := -1;
IF Obj is TPlotAxisBase THEN
begin
Result := FAxis.Add(Obj);
exit;
end;
IF Obj is TPlotSeriesBase THEN
begin
Result := FSeries.Add(Obj);
exit;
end;
IF Obj is TBasePlotRect THEN
begin
Result := FPlotRects.Add(Obj);
exit;
end;
raise EPlot.CreateRes(@S_UnknownPlotObject);
end;
procedure TPlot.Repaint;
var vLoop: Integer;
begin
inherited;
IF not Visible THEN exit;
DoubleBuffered := TRUE; //false; //TRUE;
//Mouse
// smart repainting:
FImage.Color := clWhite;
FImage.Picture.Clear;
//FImage.Picture.Bitmap.PixelFormat:=pf32bit;
//FImage.Transparent:=false;
//FImage.Picture.Bitmap.Transparent:=true;
FImage.Canvas.Brush.Color := BackgroundColor;
FImage.Canvas.FillRect(FImage.ClientRect);
FOR vLoop:= 0 TO PlotRectCount-1 do
PlotRect[vLoop].Redraw;
FOR vLoop:= 0 TO AxisCount-1 do
Axis[vLoop].Redraw(TRUE);
// postpone updates when mouse button is down
//IF not FSmartSizing then begin
FOR vLoop:= 0 TO PlotRectCount-1 do
TPlotRect(PlotRect[vLoop]).StoreBackGround;
// legend needs to be drawn in plotrect as soon as alpha channel works ?
//FOR vLoop:= 0 TO PlotRectCount-1 do
// uPlotRect.TPlotRect(PlotRect[vLoop]).LegendRect.Redraw(True, False);
FOR vLoop:= 0 TO SeriesCount-1 do
Series[vLoop].Redraw;
//end;
end;
procedure TPlot.AutoScaleSeries(ASeriesIndex: Integer; AGrowOnly: Boolean = FALSE);
var
vViewRange: TValueRange;
vAxis: Integer;
begin
vAxis := TXYPlotSeries(Self.Series[ASeriesIndex]).XAxis;
vViewRange := (Self.Series[ASeriesIndex]).AutoScaleRange[vAxis];
if AGrowOnly then begin
vViewRange.min := math.min(vViewRange.min, Self.Axis[vAxis].ViewRange.min);
vViewRange.max := math.max(vViewRange.max, Self.Axis[vAxis].ViewRange.max);
end;
Self.Axis[vAxis].ViewRange := vViewRange;
vAxis := TXYPlotSeries(Self.Series[ASeriesIndex]).YAxis;
vViewRange := (Self.Series[ASeriesIndex]).AutoScaleRange[vAxis];
if AGrowOnly then begin
vViewRange.min := math.min(vViewRange.min, Self.Axis[vAxis].ViewRange.min);
vViewRange.max := math.max(vViewRange.max, Self.Axis[vAxis].ViewRange.max);
end;
Self.Axis[vAxis].ViewRange := vViewRange;
IF Self.Series[ASeriesIndex] is TXYZPlotSeries THEN begin
vAxis := TXYZPlotSeries(Self.Series[ASeriesIndex]).ZAxis;
vViewRange := Self.Series[ASeriesIndex].AutoScaleRange[vAxis];
if AGrowOnly then begin
vViewRange.min := math.min(vViewRange.min, Self.Axis[vAxis].ViewRange.min);
vViewRange.max := math.max(vViewRange.max, Self.Axis[vAxis].ViewRange.max);
end;
Self.Axis[vAxis].ViewRange := vViewRange;
end;
Repaint;
end;
procedure TPlot.AutoScalePlotRect(APlotRectIndex: Integer);
var
vItem: Pinteger;
vSeriesList : TFPList;
vLoop: Integer;
begin
IF APlotRectIndex < 0 THEN exit;
vSeriesList := PlotRect[APlotRectIndex].SeriesContainedIdx;
try
for vLoop := 0 to vSeriesList.Count-1 do begin
vItem := Pinteger(vSeriesList.Items[vLoop]);
AutoScaleSeries(vItem^, (vLoop <> 0));
end;
Repaint;
finally
while vSeriesList.Count > 0 do begin
Dispose(Pinteger(vSeriesList.Items[0]));
vSeriesList.Delete(0);
end;
vSeriesList.Free;
end;
end;
procedure TPlot.LockImage(ADoLock: Boolean);
begin
IF ADoLock THEN BEGIN
Self.PlotImage.Picture.Bitmap.BeginUpdate(TRUE); // why Canvas only ? difference ?
exit;
END;
Self.PlotImage.Picture.Bitmap.EndUpdate(TRUE);
end;
procedure TPlot.ExportToFile(AFileName: TFilename);
var
vAlign: TAlign;
vSize: TSize;
vPNG: TPortableNetworkGraphic;
vColor_BackGround: TColor;
vColor_PlotRectTitles: array of TColor;
vColor_PlotRects: array of TColor;
vColor_Axes: array of TColor;
vColor_AxesTicks: array of TColor;
vColor_AxesSubticks: array of TColor;
vColor_Series: array of TColor;
vLoop: Integer;
const
c_DefaultName = 'PVsim_plot_defaultname.png';
begin
// --- change colorscheme -------------------------------------
// --- TODO: implement colorschemes
IF ExportPrinterFriedlyColors THEN
BEGIN
vColor_BackGround := Self.BackgroundColor;
Self.BackgroundColor := clWhite;
setlength(vColor_PlotRects, Self.PlotRectCount);
setlength(vColor_PlotRectTitles, Self.PlotRectCount);
for vLoop := 0 to PlotRectCount-1 do begin
vColor_PlotRects[vLoop] := TPlotRect(PlotRect[vLoop]).Style.Color;
vColor_PlotRectTitles[vLoop] := TPlotRect(PlotRect[vLoop]).Style.Font.Color;
TPlotRect(PlotRect[vLoop]).Style.Color := clWhite;
TPlotRect(PlotRect[vLoop]).Style.Font.Color := clBlack;
end;
setlength(vColor_Axes, Self.AxisCount);
setlength(vColor_AxesTicks, Self.AxisCount);
setlength(vColor_AxesSubticks, Self.AxisCount);
for vLoop := 0 to AxisCount-1 do begin
vColor_Axes[vLoop] := TAxisStyle(TPlotAxis(Axis[vLoop]).Style).Color;
vColor_AxesTicks[vLoop] := TAxisStyle(TPlotAxis(Axis[vLoop]).TickStyle).Color;
vColor_AxesSubticks[vLoop] := TAxisStyle(TPlotAxis(Axis[vLoop]).SubTickStyle).Color;
TAxisStyle(TPlotAxis(Axis[vLoop]).Style).Color := clBlack;
TAxisStyle(TPlotAxis(Axis[vLoop]).TickStyle).Color := clBlack;
TAxisStyle(TPlotAxis(Axis[vLoop]).SubTickStyle).Color := clBlack;
end;
setlength(vColor_Series, Self.SeriesCount);
for vLoop := 0 to SeriesCount-1 do begin
vColor_Series[vLoop] := TSeriesStyle(TPlotSeries(Series[vLoop]).Style).Color;
IF TSeriesStyle(TPlotSeries(Series[vLoop]).Style).Color = clWhite THEN
TSeriesStyle(TPlotSeries(Series[vLoop]).Style).Color := clBlue;
end;
END;
// ------------------------------------
// Rescale
vAlign := Self.Align;
vSize.cx := Self. Width;
vSize.cy := Self.Height;
Self.Align := alNone;
Self.Width := FExportSize.cx;
Self.Height := FExportSize.cy;
Repaint;
// Export
IF AFileName = '' THEN AFileName := c_DefaultName;
// convert to png if wanted
IF UpperCase(ExtractFileExt(AFileName)) = '.PNG' THEN BEGIN
vPNG := TPortableNetworkGraphic.Create;
vPNG.Assign(FImage.Picture.Bitmap);
vPNG.SaveToFile(AFileName);
vPNG.Free;
END ELSE
FImage.Picture.Bitmap.SaveToFile(AFileName);
// --- revert colorscheme -------------------------------------
IF ExportPrinterFriedlyColors THEN
BEGIN
Self.BackgroundColor := vColor_BackGround;
for vLoop := 0 to PlotRectCount-1 do begin
TPlotRect(PlotRect[vLoop]).Style.Color := vColor_PlotRects[vLoop];
TPlotRect(PlotRect[vLoop]).Style.Font.Color := vColor_PlotRectTitles[vLoop];
end;
setlength(vColor_PlotRects, 0);
setlength(vColor_PlotRectTitles, 0);
for vLoop := 0 to AxisCount-1 do begin
TAxisStyle(TPlotAxis(Axis[vLoop]).Style).Color := vColor_Axes[vLoop];
TAxisStyle(TPlotAxis(Axis[vLoop]).TickStyle).Color := vColor_AxesTicks[vLoop];
TAxisStyle(TPlotAxis(Axis[vLoop]).SubTickStyle).Color := vColor_AxesSubticks[vLoop];
end;
setlength(vColor_Axes, 0);
setlength(vColor_AxesTicks, 0);
setlength(vColor_AxesSubticks, 0);
for vLoop := 0 to SeriesCount-1 do begin
TSeriesStyle(TPlotSeries(Series[vLoop]).Style).Color := vColor_Series[vLoop];
end;
setlength(vColor_Series, 0);
END;
Self.Align := vAlign;
Self. Width := vSize.cx;
Self.Height := vSize.cy;
Repaint;
end;
procedure TPlot.ClearAll;
begin
_Clear;
Visible := TRUE;
end;
procedure TPlot.ForceRefreshFastPlotRects;
// TODO: number of series is obsolete as ALL series in one fast plot are updated together (for multitrace)
var
vLoop: Integer;
begin
IF SeriesCount < 1 THEN exit;
FOR vLoop:= 0 TO PlotRectCount-1 do begin
TPlotRect(PlotRect[vLoop]).UpdateSeriesData(TPlotSeries(Series[0]), FALSE, TRUE); // TODO: series not evaluated ! do not clear waterfalls
end;
end;
procedure TPlot.UnregisterPlotObject(Obj: TObject);
var
vDeletedIndex, vLoop: Integer;
begin
IF Obj is TPlotAxisBase THEN
begin
FAxis.Remove(Obj);
exit;
end;
IF Obj is TPlotSeriesBase THEN
begin
vDeletedIndex := FSeries.IndexOf(Obj);
FSeries.Remove(Obj);
// adjust indices
IF (FSeries.Count = 0) THEN exit;
for vLoop := vDeletedIndex to FSeries.Count - 1 do begin
TPlotSeriesBase(FSeries.Items[vLoop]).FSeriesIndex := vLoop;
end;
exit;
end;
IF Obj is TBasePlotRect THEN
begin
FPlotRects.Remove(Obj);
exit;
end;
raise EPlot.CreateRes(@S_UnknownPlotObject);
end;
procedure TPlot.OnPaintImage(Sender: TObject);
begin
// This is dperecated;
// was used to draw in the OnPaint event of the PlotIMage
// however there is no speed improve, so we still plot to the Bitmap
// for now used to check update rate....
//FDebugTime2:=Now;
//writeln('OnPaint time: ', MilliSecondsBetween(FDebugTime2, FDebugTime1));
//FDebugTime1:=FDebugTime2;
end;
procedure TPlot._Clear;
begin
Visible := FALSE;
while SeriesCount > 0 do
Series[SeriesCount-1].Free;
while AxisCount > 0 do
Axis[AxisCount-1].Free;
while PlotRectCount > 0 do
PlotRect[PlotRectCount-1].Free;
end;
function TPlot._GetImage: TImage;
begin Result := FImage; end;
{ TBasePlotRect }
// **************************************************************************
function TBasePlotRect.GetClientRect: TRect;
begin
IF AutoClientRect THEN
Result := PlotImage.ClientRect
ELSE Result := FClientRect;
end;
procedure TBasePlotRect.Redraw;
begin
// do nothing since real work is implemented in next class only
end;
function TBasePlotRect.GetPlotRectIndex: integer;
begin
Result := OwnerPlot.FPlotRects.IndexOf(Self);
end;
function TBasePlotRect.GetSeriesContainedIdx: TFPList;
var
vLoop1: Integer;
vItem: PInteger;
begin
Result := TFPList.Create;
FOR vLoop1 := OwnerPlot.SeriesCount-1 downto 0 do
begin
if TPlotAxis(OwnerPlot.Axis[TPLotSeries(OwnerPlot.Series[vLoop1]).XAxis]).OwnerPlotRect = Self then begin
New(vItem);
try
vItem^ := vLoop1;
Result.Add(vItem);
except
Dispose(vItem);
end;
end;
end;
end;
function TBasePlotRect.GetBottomLeft: TPoint;
begin
Result.X := FrameRect.Left;
Result.Y := FrameRect.Bottom;
end;
function TBasePlotRect.GetDataRect: TRect;
begin
Result := FDataRect;
end;
function TBasePlotRect.GetFrameRect: TRect;
begin
Result := FFrameRect;
end;
function TBasePlotRect.GetTopLeft: TPoint;
begin
Result := FrameRect.TopLeft;
end;
function TBasePlotRect.GetWidth: integer;
begin
Result := FrameRect.Right - FrameRect.Left;
end;
function TBasePlotRect.GetZooming: Boolean;
begin
Result := FZooming;
end;
function TBasePlotRect.GetHeigth: integer;
begin
Result := FrameRect.Bottom - FrameRect.Top;
end;
procedure TBasePlotRect.SetAutoFrameRect(const AValue: Boolean);
begin
if FAutoFrameRect=AValue then exit;
FAutoFrameRect:=AValue;
OwnerPlot.Repaint;
end;
procedure TBasePlotRect.SetAutoRect(const AValue: Boolean);
begin
IF AValue = FAutoRect THEN exit;
FAutoRect := AValue;
OwnerPlot.Repaint;
end;
procedure TBasePlotRect.SetClientRect(const AValue: TRect);
begin
FClientRect := AValue;
//PlotImage.Repaint; // TODO: needed repaint ?
end;
procedure TBasePlotRect.SetDataRect(AValue: TRect);
begin
FDataRect := AValue;
end;
procedure TBasePlotRect.SetFrameRect(const AValue: TRect);
begin
FFrameRect := AValue;
PlotImage.Repaint;
end;
procedure TBasePlotRect.SetOwnerPlot(const APlot: TPlot);
begin
IF APlot = FOwnerPlot THEN exit;
IF FOwnerPlot <> nil THEN
FOwnerPlot.UnregisterPlotObject(Self);
FOwnerPlot := APlot;
IF FOwnerPlot <> nil THEN
begin
FOwnerPlot.RegisterPlotObject(Self);
OwnerPlot.Repaint;
end;
end;
procedure TBasePlotRect.SetVisible(const AValue: Boolean);
begin
if FVisible=AValue then exit;
FVisible:=AValue;
end;
procedure TBasePlotRect.SetZooming(AValue: Boolean);
begin
IF FZooming = AValue THEN exit;
FZooming := AValue;
end;
function TBasePlotRect.PlotImage: TImage;
begin Result := OwnerPlot.PlotImage; end;
constructor TBasePlotRect.Create(OwnerPlot: TPlot);
begin
inherited Create;
FOwnerPlot := OwnerPlot;
OwnerPlot.RegisterPlotObject(Self);
FAutoRect := TRUE;
FAutoFrameRect := TRUE;
FVisible := TRUE;
FZooming:=false;
FFrameRect := Rect(0,0,4,4);
FClientRect := FFrameRect;
FDataRect := FClientRect;
end;
destructor TBasePlotRect.Destroy;
begin
OwnerPlot.UnRegisterPlotObject(Self);
OwnerPlot := nil;
inherited Destroy;
end;
{ TPlotMenuHelpers }
// **************************************************************************
procedure TPlotMenuHelpers.SetOwnerPlot(const AValue: TPlot);
begin
if FOwnerPlot = AValue then exit;
FOwnerPlot := AValue;
end;
constructor TPlotMenuHelpers.Create(AOwnerPlot: TPlot);
begin
inherited Create;
FOwnerPlot := AOwnerPlot;
FHelperFormsSeries := THelperFormsSeries.Create(FOwnerPlot.Owner);
FHelperFormsSeries.OwnerPlot := FOwnerPlot;
FHelperFormsPlotRect := THelperFormsPlotRect.Create(FOwnerPlot.Owner);
FHelperFormsPlotRect.OwnerPlot := FOwnerPlot;
FHelperFormsAxes := THelperFormsAxes.Create(FOwnerPlot.Owner);
FHelperFormsAxes.OwnerPlot := FOwnerPlot;
FHelperFormsExport := THelperFormsPlot.Create(FOwnerPlot.Owner);
FHelperFormsExport.OwnerPlot := FOwnerPlot;
FColorDialog := TColorDialog.Create(AOwnerPlot);
end;
destructor TPlotMenuHelpers.Destroy;
begin
IF FColorDialog <> nil THEN FColorDialog.Free;
IF FFileDialog <> nil THEN FFileDialog.Free;
FHelperFormsSeries.Free;
FHelperFormsPlotRect.Free;
FHelperFormsAxes.Free;
FHelperFormsExport.Free;
inherited Destroy;
end;
procedure TPlotMenuHelpers.EvalMenuPlotOpts(Sender: TObject);
var
vLoop: Integer;
begin
IF TMenuItem(Sender).Caption = 'Export to file' THEN
OwnerPlot.DoExportToFilePlot(Sender) ELSE
IF TMenuItem(Sender).Caption = 'Settings' THEN
THelperFormsPlot(FHelperFormsExport).PlotOptionsShow;
IF TMenuItem(Sender).Caption = 'Clear all data' THEN begin
for vLoop := 0 to OwnerPlot.SeriesCount-1 do begin
OwnerPlot.Series[vLoop].Clear;
OwnerPlot.Repaint;
end;
end;
end;
procedure TPlotMenuHelpers.EvalMenuSeriesOpts(Sender: TObject);
var
vSeriesString: AnsiString;
vIndexString: AnsiString;
vSeriesIndex: Integer;
begin
// Data subitem clicked ?
IF TMenuItem(Sender).Parent.Caption = 'Data' THEN
BEGIN
vSeriesString := AnsiString(TMenuItem(Sender).Parent.Parent.Caption);
vIndexString := vSeriesString[1];
IF (Length(vSeriesString)>1) THEN
IF (vSeriesString[2]<>' ') THEN vIndexString := vIndexString + vSeriesString[2];
vSeriesIndex := StrToInt(vIndexString);
// Clear Clicked ?
IF TMenuItem(Sender).Caption = 'Clear' THEN
OwnerPlot.Series[vSeriesIndex].Clear
ELSE IF TMenuItem(Sender).Caption = 'Export' THEN
begin
DoExportImportData(FALSE, vSeriesIndex);
end
ELSE IF TMenuItem(Sender).Caption = 'Import' THEN
begin
DoExportImportData(TRUE, vSeriesIndex);
end;
END
ELSE BEGIN
// else find out series index clicked
vSeriesString := AnsiString(TMenuItem(Sender).Parent.Caption);
vIndexString := vSeriesString[1];
IF (Length(vSeriesString)>1) THEN
IF (vSeriesString[2]<>' ') THEN vIndexString := vIndexString + vSeriesString[2];
vSeriesIndex := StrToInt(vIndexString);
// find out wether 'Manual scale' or 'Color' was chosen
IF TMenuItem(Sender).Caption = 'Manual scale' THEN
DoMenuSeriesScale(vSeriesIndex) ELSE
IF TMenuItem(Sender).Caption = 'Color' THEN
DoMenuSeriesColorChoose(vSeriesIndex);
IF TMenuItem(Sender).Caption = 'Style' THEN
DoMenuSeriesStyleChoose(vSeriesIndex);
IF TMenuItem(Sender).Caption = 'Markers' THEN
DoMenuSeriesMarkersChoose(vSeriesIndex);
END;
end;
procedure TPlotMenuHelpers.EvalMenuPlotRectOpts(Sender: TObject);
begin
// for PlotRects the number is stored in MousePlotRectDown, so we need no parser here
IF TMenuItem(Sender).Caption = 'Properties' THEN
DoMenuPlotRectStyleChoose(OwnerPlot.MousePlotRectDown);
end;
procedure TPlotMenuHelpers.EvalMenuAxesOpts(Sender: TObject);
var
vAxisString: AnsiString;
vIndexString: AnsiString;
vAxisIndex: Integer;
begin
// again that Parser, please please modularize it
// find out axis index clicked
vAxisString := AnsiString(TMenuItem(Sender).Caption);
vIndexString := vAxisString[1];
IF (Length(vAxisString)>1) THEN
IF (vAxisString[2]<>' ') THEN vIndexString := vIndexString + vAxisString[2];
vAxisIndex := StrToInt(vIndexString);
THelperFormsAxes(FHelperFormsAxes).AxesStyleChoose(vAxisIndex) ;
end;
procedure TPlotMenuHelpers.DoMenuPRAutoScale(Sender: TObject);
begin
OwnerPlot.AutoScalePlotRect(OwnerPlot.MousePlotRectDown);
end;
procedure TPlotMenuHelpers.DoMenuSeriesScale(ASeriesIndex: Integer);
begin
THelperFormsSeries(FHelperFormsSeries).SeriesManualScale(ASeriesIndex);
end;
procedure TPlotMenuHelpers.DoMenuSeriesColorChoose(ASeriesIndex: Integer);
var
vNewColor: TColor;
vFreeDialog: Boolean;
begin
vFreeDialog := FColorDialog = nil;
if FColorDialog = nil then FColorDialog := TColorDialog.Create(OwnerPlot.Parent);
try
vNewColor := TPlotStyle(OwnerPlot.Series[ASeriesIndex].Style).Color;
FColorDialog.Color := vNewColor;
if FColorDialog.Execute then
vNewColor := FColorDialog.Color;
finally
if vFreeDialog then FreeAndNil(FColorDialog);
end;
TPlotStyle(OwnerPlot.Series[ASeriesIndex].Style).Color := vNewColor;
OwnerPlot.Repaint;
end;
procedure TPlotMenuHelpers.DoMenuSeriesStyleChoose(ASeriesIndex: Integer);
begin
THelperFormsSeries(FHelperFormsSeries).SeriesStyleChoose(ASeriesIndex);
end;
procedure TPlotMenuHelpers.DoMenuSeriesMarkersChoose(ASeriesIndex: Integer);
begin
THelperFormsSeries(FHelperFormsSeries).SeriesMarkersChoose(ASeriesIndex);
end;
procedure TPlotMenuHelpers.DoMenuPlotRectStyleChoose(APlotRectIndex: Integer);
begin
THelperFormsPlotRect(FHelperFormsPlotRect).PlotRectStyleChoose(APlotRectIndex);
end;
procedure TPlotMenuHelpers.DoExportImportData(AImport: Boolean;
ASeriesIndex: Integer);
var
vFileName: TFilename;
vFreeDialog: Boolean;
begin
vFreeDialog := FFileDialog = nil;
if FFileDialog = nil then begin
IF AImport THEN FFileDialog := TOpenDialog.Create(OwnerPlot.Parent)
ELSE FFileDialog := TSaveDialog.Create(OwnerPlot.Parent);
end;
try
FFileDialog.Filter := 'MAAResult | *.mdt';
if FFileDialog.Execute then
vFileName := FFileDialog.FileName;
finally
if vFreeDialog then FreeAndNil(FFileDialog);
end;
IF vFileName = '' then exit;
//
IF AImport THEN begin
TXYPlotSeries(OwnerPlot.Series[ASeriesIndex]).ImportSeriesData(vFileName);
OwnerPlot.Repaint;
end
ELSE
TXYPlotSeries(OwnerPlot.Series[ASeriesIndex]).ExportSeriesData(vFileName);
end;
{ THelperFormsBase }
// **************************************************************************
procedure THelperFormsBase.SetOwnerPlot(const APlot: TPlot);
begin
FOwnerPlot := APlot;
end;
constructor THelperFormsBase.Create(AOwner: TComponent);
begin
inherited CreateNew(AOwner); // resourceless forms need CreateNew !
end;
destructor THelperFormsBase.Destroy;
begin
inherited Destroy;
end;
end.
|
function GetToggleState(Key: integer): boolean;
//
// Testa se uma certa tecla estรก pressionada ou nรฃo
//
begin
Result := Odd(GetKeyState(Key));
end;
end; |
unit uShellUtils;
interface
{$WARN SYMBOL_PLATFORM OFF}
uses
Windows,
Classes,
Forms,
UnitINI,
uConstants,
Registry,
SysUtils,
uLogger,
uMemory,
uTranslate,
uDBBaseTypes,
uAssociations,
Controls,
ShellApi,
ShlObj,
Dmitry.Utils.System,
Dmitry.Utils.Files,
uRuntime,
Messages;
const
BCM_FIRST = $1600; //Button control messages
BCM_SETSHIELD = BCM_FIRST + $000C;
type
TRegistryInstallCallBack = procedure(Current, Total: Integer; var Terminate : Boolean) of object;
function RegInstallApplication(FileName: string; CallBack : TRegistryInstallCallBack): Boolean;
function IsNewVersion: Boolean;
function DeleteRegistryEntries: Boolean;
function GetSystemPath(PathType: Integer): string;
function InstalledDirectory: string;
function InstalledFileName: string;
function GetProgramFilesPath: string;
function GetStartMenuPath: string;
function GetDesktopPath: string;
function GetMyDocumentsPath: string;
function GetMyPicturesPath: string;
function GetAppDataPath: string;
function GetTempDirectory: string;
function GetTempFileName: TFileName;
function GetTempFileNameEx(Directory, Extension: string): TFileName;
procedure RefreshSystemIconCache;
implementation
function InstalledDirectory: string;
begin
Result := ExtractFileDir(InstalledFileName);
end;
function InstalledFileName: string;
var
FReg: TBDRegistry;
begin
Result := '';
FReg := TBDRegistry.Create(REGISTRY_ALL_USERS, True);
try
FReg.OpenKey(RegRoot, False);
Result := FReg.ReadString('DataBase');
if PortableWork then
if Result <> '' then
Result[1] := Application.Exename[1];
except
end;
FReg.Free;
end;
function IsNewVersion: Boolean;
var
FReg: TBDRegistry;
Func: TIntegerFunction;
H: Thandle;
ProcH: Pointer;
FileName: string;
begin
Result := False;
Freg := TBDRegistry.Create(REGISTRY_ALL_USERS, True);
try
FReg.OpenKey(RegRoot, True);
FileName := FReg.ReadString('DataBase');
if FileExistsSafe(FileName) then
begin
H := LoadLibrary(PWideChar(FileName));
if H <> 0 then
begin
ProcH := GetProcAddress(H, 'FileVersion');
if ProcH <> nil then
begin
@Func := ProcH;
if Func > ReleaseNumber then
Result := True;
end;
FreeLibrary(H);
end;
end;
except
on e: Exception do
EventLog(e.Message);
end;
F(FReg);
end;
function DeleteRegistryEntries: Boolean;
var
Freg: TRegistry;
begin
Result := False;
FReg := TRegistry.Create;
try
FReg.RootKey := Windows.HKEY_LOCAL_MACHINE;
FReg.DeleteKey('\.photodb');
FReg.DeleteKey('\PhotoDB.PhotodbFile\');
FReg.DeleteKey('\.ids');
FReg.DeleteKey('\PhotoDB.IdsFile\');
FReg.DeleteKey('\.dbl');
FReg.DeleteKey('\PhotoDB.DblFile\');
FReg.DeleteKey('\.ith');
FReg.DeleteKey('\PhotoDB.IthFile\');
FReg.DeleteKey('\Directory\Shell\PhDBBrowse\');
FReg.DeleteKey('\Drive\Shell\PhDBBrowse\');
except
on E: Exception do
begin
EventLog(':DeleteRegistryEntries() throw exception: ' + E.message);
FReg.Free;
end;
end;
FReg.Free;
FReg := TRegistry.Create;
try
FReg.RootKey := HKEY_INSTALL;
FReg.DeleteKey(RegRoot);
except
on E: Exception do
begin
EventLog(':DeleteRegistryEntries()/HKEY_INSTALL throw exception: ' + E.message);
FReg.Free;
end;
end;
FReg.Free;
FReg := TRegistry.Create;
try
FReg.RootKey := HKEY_USER_WORK;
FReg.DeleteKey(RegRoot);
except
on E: Exception do
begin
EventLog(':DeleteRegistryEntries()/HKEY_USER_WORK throw exception: ' + E.message);
FReg.Free;
end;
end;
FReg.Free;
FReg := Tregistry.Create;
try
FReg.RootKey := Windows.HKEY_LOCAL_MACHINE;
FReg.DeleteKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Photo DataBase');
Result := True;
except
on E: Exception do
EventLog(':DeleteRegistryEntries() throw exception: ' + E.message);
end;
FReg.Free;
FReg := TRegistry.Create;
try
FReg.RootKey := Windows.HKEY_LOCAL_MACHINE;
FReg.DeleteKey('\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers\EventHandlers\WPD\Source');
FReg.DeleteKey(
'\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers\Handlers\PhotoDBGetPhotosHandler');
FReg.DeleteKey('\SOFTWARE\Classes\PhotoDB.AutoPlayHandler');
FReg.OpenKey(
'\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers\EventHandlers\ShowPicturesOnArrival', True);
FReg.DeleteValue('PhotoDBgetPhotosHandler');
Result := True;
except
on E: Exception do
EventLog(':DeleteRegistryEntries() throw exception: ' + E.message);
end;
FReg.Free;
FReg := TRegistry.Create;
try
FReg.RootKey := Windows.HKEY_LOCAL_MACHINE;
FReg.DeleteKey(
'\SOFTWARE\Microsoft\Windows\CurrentVersion\explorer\AutoplayHandlers\EventHandlers\WPD\Compat\WiaDeviceConnected');
FReg.DeleteKey('\SOFTWARE\Microsoft\Windows\CurrentVersion\explorer\AutoplayHandlers\Handlers\WIA_{6288D3A0-3E70-481A-8037-378532BED8C6}');
Result := True;
except
on E: Exception do
EventLog(':DeleteRegistryEntries() throw exception: ' + E.message);
end;
FReg.Free;
end;
function RegInstallApplication(FileName: string; CallBack : TRegistryInstallCallBack): Boolean;
const
ActionCount = 14;
WPD_CONTENT_TYPE_IMAGE = '{EF2107D5-A52A-4243-A26B-62D4176D7603}';
var
FReg: TBDRegistry;
Terminate : Boolean;
begin
Terminate := False;
Result := True;
CallBack(1, ActionCount, Terminate);
FReg := TBDRegistry.Create(REGISTRY_ALL_USERS);
try
FReg.OpenKey(RegRoot, True);
FReg.WriteDateTime('InstallDate', FReg.ReadDateTime('InstallDate', Now));
FReg.WriteString('ReleaseNumber', IntToStr(ReleaseNumber));
FReg.WriteString('DataBase', Filename);
FReg.WriteString('Language', TTranslateManager.Instance.Language);
FReg.WriteString('Folder', ExtractFileDir(Filename));
except
on E: Exception do
begin
Result := False;
EventLog(':RegInstallApplication() throw exception: ' + E.message);
F(FReg);
Exit;
end;
end;
F(FReg);
CallBack(2, ActionCount, Terminate);
FReg := TBDRegistry.Create(REGISTRY_ALL_USERS);
try
FReg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Photo DataBase', True);
FReg.WriteString('UninstallString', IncludeTrailingBackslash(ExtractFileDir(FileName)) + 'UnInstall.exe');
FReg.WriteString('DisplayIcon', FileName);
FReg.WriteString('DisplayName', 'Photo DataBase');
FReg.WriteString('DisplayVersion', ReleaseToString(GetExeVersion(FileName)));
FReg.WriteString('HelpLink', ResolveLanguageString(HomePageURL));
FReg.WriteString('Publisher', CopyRightString);
FReg.WriteString('URLInfoAbout', 'mailto:' + ProgramMail);
FReg.WriteInteger('EstimatedSize', ProgramInstallSize);
FReg.WriteBool('NoModify', True);
FReg.WriteBool('NoRepair', True);
except
on E: Exception do
begin
Result := False;
EventLog(':RegInstallApplication() throw exception: ' + E.message);
F(FReg);
Exit;
end;
end;
F(FReg);
CallBack(3, ActionCount, Terminate);
FReg := TBDRegistry.Create(REGISTRY_CLASSES);
try
FReg.OpenKey('\.photodb', True);
FReg.WriteString('', 'PhotoDB.PhotodbFile');
FReg.CloseKey;
FReg.OpenKey('\PhotoDB.PhotodbFile', True);
FReg.OpenKey('\PhotoDB.PhotodbFile\DefaultIcon', True);
FReg.WriteString('', FileName + ',0');
FReg.CloseKey;
except
on E: Exception do
begin
EventLog(':RegInstallApplication() throw exception: ' + E.message);
Result := False;
Exit;
end;
end;
F(FReg);
CallBack(4, ActionCount, Terminate);
FReg := TBDRegistry.Create(REGISTRY_CLASSES);
try
FReg.OpenKey('\.ids', True);
FReg.WriteString('', 'PhotoDB.IdsFile');
FReg.CloseKey;
FReg.OpenKey('\PhotoDB.IdsFile', True);
FReg.OpenKey('\PhotoDB.IdsFile\DefaultIcon', True);
FReg.WriteString('', FileName + ',0');
FReg.OpenKey('\PhotoDB.IdsFile\Shell\Open\Command', True);
FReg.WriteString('', Format('"%s" "%%1"', [FileName]));
FReg.CloseKey;
except
on E: Exception do
begin
EventLog(':RegInstallApplication() throw exception: ' + E.message);
Result := False;
Exit;
end;
end;
F(FReg);
CallBack(5, ActionCount, Terminate);
FReg := TBDRegistry.Create(REGISTRY_CLASSES);
try
FReg.OpenKey('\.dbl', True);
FReg.WriteString('', 'PhotoDB.dblFile');
FReg.CloseKey;
FReg.OpenKey('\PhotoDB.dblFile', True);
FReg.CloseKey;
FReg.OpenKey('\PhotoDB.dblFile\DefaultIcon', True);
FReg.WriteString('', FileName + ',0');
FReg.OpenKey('\PhotoDB.dblFile\Shell\Open\Command', True);
FReg.WriteString('', Format('"%s" "%%1"', [FileName]));
FReg.CloseKey;
except
on E: Exception do
begin
EventLog(':RegInstallApplication() throw exception: ' + E.message);
Result := False;
Exit;
end;
end;
F(FReg);
CallBack(6, ActionCount, Terminate);
FReg := TBDRegistry.Create(REGISTRY_CLASSES);
try
FReg.OpenKey('\.ith', True);
FReg.Writestring('', 'PhotoDB.IthFile');
FReg.CloseKey;
FReg.OpenKey('\PhotoDB.IthFile', True);
FReg.CloseKey;
FReg.OpenKey('\PhotoDB.IthFile\DefaultIcon', True);
FReg.Writestring('', FileName + ',0');
FReg.OpenKey('\PhotoDB.IthFile\Shell\Open\Command', True);
FReg.WriteString('', Format('"%s" "%%1"', [FileName]));
FReg.CloseKey;
except
on E: Exception do
begin
EventLog(':RegInstallApplication() throw exception: ' + E.message);
Result := False;
Exit;
end;
end;
F(FReg);
// Adding Handler for removable drives
CallBack(7, ActionCount, Terminate);
FReg := TBDRegistry.Create(REGISTRY_ALL_USERS);
try
FReg.OpenKey('\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers\EventHandlers\WPD\Source\' + WPD_CONTENT_TYPE_IMAGE, True);
FReg.WriteString('PhotoDBGetPhotosHandler', '');
FReg.CloseKey;
FReg.OpenKey('\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers\Handlers\PhotoDBGetPhotosHandler', True);
FReg.WriteString('Action', TA('Get photos', 'System'));
FReg.WriteString('DefaultIcon', FileName + ',0');
FReg.WriteString('ProgID', 'PhotoDBBridge.PhotoDBAutoplayHandler');
FReg.WriteString('InitCmdLine', '/import');
FReg.WriteString('Provider', 'Photo DataBase ' + IIF(ProgramVersionString = '', ProductVersion, ProgramVersionString));
FReg.CloseKey;
except
on E: Exception do
begin
EventLog(':RegInstallApplication() throw exception: ' + E.message);
Result := False;
Exit;
end;
end;
F(FReg);
CallBack(8, ActionCount, Terminate);
FReg := TBDRegistry.Create(REGISTRY_ALL_USERS);
try
FReg.OpenKey('\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers\EventHandlers\ShowPicturesOnArrival', True);
FReg.WriteString('PhotoDBGetPhotosHandler', '');
FReg.CloseKey;
FReg.OpenKey('\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\AutoplayHandlers\EventHandlers\MixedContentOnArrival', True);
FReg.WriteString('PhotoDBGetPhotosHandler', '');
FReg.CloseKey;
except
on E: Exception do
begin
EventLog(':RegInstallApplication() throw exception: ' + E.message);
Result := False;
Exit;
end;
end;
F(FReg);
CallBack(11, ActionCount, Terminate);
FReg := TBDRegistry.Create(REGISTRY_ALL_USERS);
try
FReg.OpenKey('\SOFTWARE\Classes', True);
FReg.CloseKey;
FReg.OpenKey('\SOFTWARE\Classes\PhotoDB.AutoPlayHandler', True);
FReg.CloseKey;
FReg.OpenKey('\SOFTWARE\Classes\PhotoDB.AutoPlayHandler\Shell', True);
FReg.CloseKey;
FReg.OpenKey('\SOFTWARE\Classes\PhotoDB.AutoPlayHandler\Shell\Open', True);
FReg.CloseKey;
FReg.OpenKey('\SOFTWARE\Classes\PhotoDB.AutoPlayHandler\Shell\Open\Command', True);
FReg.WriteString('', Format('"%s" "/GETPHOTOS" "%%1"', [FileName]));
FReg.CloseKey;
except
on E: Exception do
begin
EventLog(':RegInstallApplication() throw exception: ' + E.message);
Result := False;
Exit;
end;
end;
F(FReg);
CallBack(12, ActionCount, Terminate);
FReg := TBDRegistry.Create(REGISTRY_CLASSES);
try
FReg.OpenKey('\Directory\Shell\PhDBBrowse', True);
FReg.Writestring('', TA('Browse with PhotoDB', 'System'));
FReg.CloseKey;
FReg.OpenKey('\Directory\Shell\PhDBBrowse\Command', True);
FReg.Writestring('', Format('"%s" "/EXPLORER" "%%1"', [Filename]));
except
on E: Exception do
begin
EventLog(':ExtInstallApplication() throw exception: ' + E.message);
Result := False;
Exit;
end;
end;
F(FReg);
CallBack(13, ActionCount, Terminate);
FReg := TBDRegistry.Create(REGISTRY_CLASSES);
try
FReg.OpenKey('\Drive\Shell\PhDBBrowse', True);
FReg.Writestring('', TA('Browse with PhotoDB', 'System'));
FReg.CloseKey;
FReg.OpenKey('\Drive\Shell\PhDBBrowse\Command', True);
FReg.Writestring('', Format('"%s" "/EXPLORER" "%%1"', [Filename]));
except
on E: Exception do
begin
EventLog(':ExtInstallApplication() throw exception: ' + E.message);
Result := False;
Exit;
end;
end;
F(FReg);
CallBack(14, ActionCount, Terminate);
FReg := TBDRegistry.Create(REGISTRY_CLASSES);
try
FReg.OpenKey('\Drive\Shell\PhDBGetPhotos', True);
FReg.Writestring('', TA('Get photos', 'System'));
FReg.CloseKey;
FReg.OpenKey('\Drive\Shell\PhDBGetPhotos\Command', True);
FReg.Writestring('', Format('"%s" "/GETPHOTOS" "%%1"', [Filename]));
except
on E: Exception do
begin
EventLog(':ExtInstallApplication() throw exception: ' + E.message);
Result := False;
Exit;
end;
end;
F(FReg);
end;
function GetSystemPath(PathType: Integer): string;
var
P: array[0..MAX_PATH] of char;
SystemDir: string;
begin
if SHGetFolderPath(0, PathType, 0,0, @P[0]) = S_OK then
SystemDir:= P
else
SystemDir:= '';
Result:= SystemDir;
end;
function GetStartMenuPath: string;
begin
Result := GetSystemPath(CSIDL_COMMON_PROGRAMS);
end;
function GetProgramFilesPath: string;
begin
Result := GetSystemPath(CSIDL_PROGRAM_FILES);
end;
function GetDesktopPath: string;
begin
Result := GetSystemPath(CSIDL_COMMON_DESKTOPDIRECTORY);
end;
function GetAppDataPath: string;
begin
Result := GetSystemPath(CSIDL_APPDATA);
end;
function GetMyPicturesPath: string;
begin
Result := GetSystemPath(CSIDL_MYPICTURES);
end;
function GetMyDocumentsPath: string;
begin
Result := GetSystemPath(CSIDL_MYDOCUMENTS);
end;
function GetTempDirectory: string;
var
TempFolder: array[0..MAX_PATH] of Char;
begin
GetTempPath(MAX_PATH, @tempFolder);
Result := StrPas(TempFolder);
end;
function GetTempFileName: TFileName;
var
TempFileName: array [0..MAX_PATH-1] of char;
begin
if Windows.GetTempFileName(PChar(GetTempDirectory), '~', 0, TempFileName) = 0 then
raise Exception.Create(SysErrorMessage(GetLastError));
Result := TempFileName;
end;
function GetTempFileNameEx(Directory, Extension: string): TFileName;
var
TempFileName: array [0..MAX_PATH-1] of char;
begin
if Windows.GetTempFileName(PChar(Directory), '~', 0, TempFileName) = 0 then
raise Exception.Create(SysErrorMessage(GetLastError));
Result := TempFileName + Extension;
end;
procedure RefreshSystemIconCache;
begin
SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_FLUSH or SHCNF_PATH, nil, nil);
SHChangeNotify(SHCNE_UPDATEIMAGE, SHCNF_FLUSH or SHCNF_PATH, nil, nil);
end;
end.
|
unit MagentoHTTP;
interface
uses
REST.Response.Adapter, Data.DB, Datasnap.DBClient, REST.Types, REST.Client,
Data.Bind.Components, Data.Bind.ObjectScope, System.JSON, Magento.Interfaces,
System.Classes;
type
TMagentoHTTP = class (TInterfacedObject, iMagentoHTTP)
private
FRestClient: TRESTClient;
FRestRequest: TRESTRequest;
FRestResponse: TRESTResponse;
FField : String;
FValue : String;
FCondition_Type : String;
FURI : String;
FStatus : Integer;
public
constructor Create;
destructor Destroy; override;
class function New : iMagentoHTTP;
function GetAtributo : String;
function GetAtributoID(Value : String) : String;
function PostAttribute(Value : String) : iMagentoHTTP;
function Field(Value : String) : iMagentoHTTP;
function Value(aValue : String) : iMagentoHTTP;
function Condition_type(Value : String) : iMagentoHTTP;
function GetCatagorias : String;
function PostCategorias(Value : String) : iMagentoHTTP;
function GetPedidos : String;
function PostProduto(value : TJSONObject) : iMagentoHTTP; overload;
function PostProduto(value : TStringList) : iMagentoHTTP; overload;
function Status : Integer;
end;
implementation
{ TMagentoHTTP }
uses ServerMagento.Model.Env, System.SysUtils;
function TMagentoHTTP.Condition_type(Value: String): iMagentoHTTP;
begin
Result := Self;
FCondition_Type := Value;
end;
constructor TMagentoHTTP.Create;
begin
end;
destructor TMagentoHTTP.Destroy;
begin
inherited;
end;
function TMagentoHTTP.Field(Value: String): iMagentoHTTP;
begin
Result := Self;
FField := Value;
end;
function TMagentoHTTP.GetAtributo: String;
begin
FURI := '';
FURI := API +
'/eav/attribute-sets/list?searchCriteria[filterGroups][0]'+
'[filters][0][field]=attribute_set_name&searchCriteria[filterGroups]'+
'[0][filters][0][value]=&searchCriteria[filterGroups][0][filters][0][conditionType]=neq';
try
FRestClient := TRESTClient.Create(FURI);
FRestClient.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,';
FRestClient.AcceptCharset := 'UTF-8, *;q=0.8';
FRestClient.AcceptEncoding := '';
FRestClient.AutoCreateParams := true;
FRestClient.AllowCookies := True;
FRestClient.BaseURL := FURI;
FRestClient.ContentType := '';
FRestClient.FallbackCharsetEncoding := 'utf-8';
FRestClient.HandleRedirects := True;
FRestResponse := TRESTResponse.Create(FRestClient);
FRestResponse.ContentType := 'application/json';
FRestRequest := TRESTRequest.Create(FRestClient);
FRestRequest.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,';
FRestRequest.AcceptCharset := 'UTF-8, *;q=0.8';
FRestRequest.AcceptEncoding := '';
FRestRequest.AutoCreateParams := true;
FRestRequest.Client := FRestClient;
FRestRequest.Method := rmGET;
FRestRequest.SynchronizedEvents := False;
FRestRequest.Response := FRestResponse;
FRestRequest.Params.Add;
FRestRequest.Params[0].ContentType := ctNone;
FRestRequest.Params[0].Kind := pkHTTPHEADER;
FRestRequest.Params[0].Name := 'Authorization';
FRestRequest.Params[0].Value := 'Bearer ' + ACCES_TOKEN;
FRestRequest.Params[0].Options := [poDoNotEncode];
FRestRequest.Execute;
Result := FRestResponse.Content;
FStatus := FRestResponse.StatusCode;
except
end;
end;
function TMagentoHTTP.GetAtributoID(Value: String): String;
begin
FURI := '';
FURI := API + '/products/attribute-sets/'+Value+'/attributes';
try
FRestClient := TRESTClient.Create(FURI);
FRestClient.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,';
FRestClient.AcceptCharset := 'UTF-8, *;q=0.8';
FRestClient.AcceptEncoding := '';
FRestClient.AutoCreateParams := true;
FRestClient.AllowCookies := True;
FRestClient.BaseURL := FURI;
FRestClient.ContentType := '';
FRestClient.FallbackCharsetEncoding := 'utf-8';
FRestClient.HandleRedirects := True;
FRestResponse := TRESTResponse.Create(FRestClient);
FRestResponse.ContentType := 'application/json';
FRestRequest := TRESTRequest.Create(FRestClient);
FRestRequest.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,';
FRestRequest.AcceptCharset := 'UTF-8, *;q=0.8';
FRestRequest.AcceptEncoding := '';
FRestRequest.AutoCreateParams := true;
FRestRequest.Client := FRestClient;
FRestRequest.Method := rmGET;
FRestRequest.SynchronizedEvents := False;
FRestRequest.Response := FRestResponse;
FRestRequest.Params.Add;
FRestRequest.Params[0].ContentType := ctNone;
FRestRequest.Params[0].Kind := pkHTTPHEADER;
FRestRequest.Params[0].Name := 'Authorization';
FRestRequest.Params[0].Value := 'Bearer ' + ACCES_TOKEN;
FRestRequest.Params[0].Options := [poDoNotEncode];
FRestRequest.Execute;
Result := FRestResponse.Content;
FStatus := FRestResponse.StatusCode;
except
end;
end;
function TMagentoHTTP.GetCatagorias: String;
begin
FURI := '';
FURI := API + '/categories?'+
'searchCriteria[filter_groups][0][filters][0][field]=id&'+
'searchCriteria[filter_groups][0][filters][0][value]=1&'+
'searchCriteria[filter_groups][0][filters][0][condition_type]=gte';
try
FRestClient := TRESTClient.Create(FURI);
FRestClient.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,';
FRestClient.AcceptCharset := 'UTF-8, *;q=0.8';
FRestClient.AcceptEncoding := '';
FRestClient.AutoCreateParams := true;
FRestClient.AllowCookies := True;
FRestClient.BaseURL := FURI;
FRestClient.ContentType := '';
FRestClient.FallbackCharsetEncoding := 'utf-8';
FRestClient.HandleRedirects := True;
FRestResponse := TRESTResponse.Create(FRestClient);
FRestResponse.ContentType := 'application/json';
FRestRequest := TRESTRequest.Create(FRestClient);
FRestRequest.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,';
FRestRequest.AcceptCharset := 'UTF-8, *;q=0.8';
FRestRequest.AcceptEncoding := '';
FRestRequest.AutoCreateParams := true;
FRestRequest.Client := FRestClient;
FRestRequest.Method := rmGET;
FRestRequest.SynchronizedEvents := False;
FRestRequest.Response := FRestResponse;
FRestRequest.Params.Add;
FRestRequest.Params[0].ContentType := ctNone;
FRestRequest.Params[0].Kind := pkHTTPHEADER;
FRestRequest.Params[0].Name := 'Authorization';
FRestRequest.Params[0].Value := 'Bearer ' + ACCES_TOKEN;
FRestRequest.Params[0].Options := [poDoNotEncode];
FRestRequest.Execute;
Result := FRestResponse.Content;
FStatus := FRestResponse.StatusCode;
except
end;
end;
function TMagentoHTTP.GetPedidos: String;
begin
FURI := '';
FURI := API + '/orders?searchCriteria[filterGroups][0][filters][0][field]=entity_id'+
'&searchCriteria[filterGroups][0][filters][0][value]='+
'&searchCriteria[filterGroups][0][filters][0][conditionType]=neq';
try
FRestClient := TRESTClient.Create(FURI);
FRestClient.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,';
FRestClient.AcceptCharset := 'UTF-8, *;q=0.8';
FRestClient.AcceptEncoding := '';
FRestClient.AutoCreateParams := true;
FRestClient.AllowCookies := True;
FRestClient.BaseURL := FURI;
FRestClient.ContentType := '';
FRestClient.FallbackCharsetEncoding := 'utf-8';
FRestClient.HandleRedirects := True;
FRestResponse := TRESTResponse.Create(FRestClient);
FRestResponse.ContentType := 'application/json';
FRestRequest := TRESTRequest.Create(FRestClient);
FRestRequest.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,';
FRestRequest.AcceptCharset := 'UTF-8, *;q=0.8';
FRestRequest.AcceptEncoding := '';
FRestRequest.AutoCreateParams := true;
FRestRequest.Client := FRestClient;
FRestRequest.Method := rmGET;
FRestRequest.SynchronizedEvents := False;
FRestRequest.Response := FRestResponse;
FRestRequest.Params.Add;
FRestRequest.Params[0].ContentType := ctNone;
FRestRequest.Params[0].Kind := pkHTTPHEADER;
FRestRequest.Params[0].Name := 'Authorization';
FRestRequest.Params[0].Value := 'Bearer ' + ACCES_TOKEN;
FRestRequest.Params[0].Options := [poDoNotEncode];
FRestRequest.Execute;
Result := FRestResponse.Content;
FStatus := FRestResponse.StatusCode;
except
end;
end;
class function TMagentoHTTP.New: iMagentoHTTP;
begin
Result := self.Create;
end;
function TMagentoHTTP.PostAttribute(Value: String): iMagentoHTTP;
begin
Result := Self;
FURI := '';
FURI := API + '/products/attribute-sets';
try
FRestClient := TRESTClient.Create(FURI);
FRestClient.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,';
FRestClient.AcceptCharset := 'UTF-8, *;q=0.8';
FRestClient.AcceptEncoding := '';
FRestClient.AutoCreateParams := true;
FRestClient.AllowCookies := True;
FRestClient.BaseURL := FURI;
FRestClient.ContentType := '';
FRestClient.FallbackCharsetEncoding := 'utf-8';
FRestClient.HandleRedirects := True;
FRestResponse := TRESTResponse.Create(FRestClient);
FRestResponse.ContentType := 'application/json';
FRestRequest := TRESTRequest.Create(FRestClient);
FRestRequest.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,';
FRestRequest.AcceptCharset := 'UTF-8, *;q=0.8';
FRestRequest.AcceptEncoding := '';
FRestRequest.AutoCreateParams := true;
FRestRequest.Client := FRestClient;
FRestRequest.Method := rmPOST;
FRestRequest.SynchronizedEvents := False;
FRestRequest.Response := FRestResponse;
FRestRequest.Params.Add;
FRestRequest.Params[0].ContentType := ctNone;
FRestRequest.Params[0].Kind := pkHTTPHEADER;
FRestRequest.Params[0].Name := 'Authorization';
FRestRequest.Params[0].Value := 'Bearer ' + ACCES_TOKEN;
FRestRequest.Params[0].Options := [poDoNotEncode];
FRestRequest.Params.Add;
FRestRequest.Params[1].ContentType := ctAPPLICATION_JSON;
FRestRequest.Params[1].Kind := pkREQUESTBODY;
FRestRequest.Params[1].Name := 'body';
FRestRequest.Params[1].Value := value;
FRestRequest.Params[1].Options := [poDoNotEncode];
FRestRequest.Execute;
FStatus := FRestResponse.StatusCode;
except
end;
end;
function TMagentoHTTP.PostCategorias(Value: String): iMagentoHTTP;
begin
Result := Self;
FURI := '';
FURI := API + '/categories';
try
FRestClient := TRESTClient.Create(FURI);
FRestClient.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,';
FRestClient.AcceptCharset := 'UTF-8, *;q=0.8';
FRestClient.AcceptEncoding := '';
FRestClient.AutoCreateParams := true;
FRestClient.AllowCookies := True;
FRestClient.BaseURL := FURI;
FRestClient.ContentType := '';
FRestClient.FallbackCharsetEncoding := 'utf-8';
FRestClient.HandleRedirects := True;
FRestResponse := TRESTResponse.Create(FRestClient);
FRestResponse.ContentType := 'application/json';
FRestRequest := TRESTRequest.Create(FRestClient);
FRestRequest.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,';
FRestRequest.AcceptCharset := 'UTF-8, *;q=0.8';
FRestRequest.AcceptEncoding := '';
FRestRequest.AutoCreateParams := true;
FRestRequest.Client := FRestClient;
FRestRequest.Method := rmPOST;
FRestRequest.SynchronizedEvents := False;
FRestRequest.Response := FRestResponse;
FRestRequest.Params.Add;
FRestRequest.Params[0].ContentType := ctNone;
FRestRequest.Params[0].Kind := pkHTTPHEADER;
FRestRequest.Params[0].Name := 'Authorization';
FRestRequest.Params[0].Value := 'Bearer ' + ACCES_TOKEN;
FRestRequest.Params[0].Options := [poDoNotEncode];
FRestRequest.Params.Add;
FRestRequest.Params[1].ContentType := ctAPPLICATION_JSON;
FRestRequest.Params[1].Kind := pkREQUESTBODY;
FRestRequest.Params[1].Name := 'body';
FRestRequest.Params[1].Value := value;
FRestRequest.Params[1].Options := [poDoNotEncode];
FRestRequest.Execute;
FStatus := FRestResponse.StatusCode;
except
end;
end;
function TMagentoHTTP.PostProduto(value: TStringList): iMagentoHTTP;
var
i:integer;
aux:TStringList;
begin
Result := Self;
FURI := '';
FURI := API + '/products';
aux:=TStringList.Create;
for I := 0 to Pred(value.Count) do
begin
try
FRestClient := TRESTClient.Create(FURI);
FRestClient.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,';
FRestClient.AcceptCharset := 'UTF-8, *;q=0.8';
FRestClient.AcceptEncoding := '';
FRestClient.AutoCreateParams := true;
FRestClient.AllowCookies := True;
FRestClient.BaseURL := FURI;
FRestClient.ContentType := '';
FRestClient.FallbackCharsetEncoding := 'utf-8';
FRestClient.HandleRedirects := True;
FRestResponse := TRESTResponse.Create(FRestClient);
FRestResponse.ContentType := 'application/json';
FRestRequest := TRESTRequest.Create(FRestClient);
FRestRequest.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,';
FRestRequest.AcceptCharset := 'UTF-8, *;q=0.8';
FRestRequest.AcceptEncoding := '';
FRestRequest.AutoCreateParams := true;
FRestRequest.Client := FRestClient;
FRestRequest.Method := rmPOST;
FRestRequest.SynchronizedEvents := False;
FRestRequest.Response := FRestResponse;
FRestRequest.Params.Add;
FRestRequest.Params[0].ContentType := ctNone;
FRestRequest.Params[0].Kind := pkHTTPHEADER;
FRestRequest.Params[0].Name := 'Authorization';
FRestRequest.Params[0].Value := 'Bearer ' + ACCES_TOKEN;
FRestRequest.Params[0].Options := [poDoNotEncode];
FRestRequest.Params.Add;
FRestRequest.Params[1].ContentType := ctAPPLICATION_JSON;
FRestRequest.Params[1].Kind := pkREQUESTBODY;
FRestRequest.Params[1].Name := 'body';
FRestRequest.Params[1].Value := value.Strings[I];
FRestRequest.Params[1].Options := [poDoNotEncode];
FRestRequest.Execute;
FStatus := FRestResponse.StatusCode;
except
end;
end;
end;
function TMagentoHTTP.PostProduto(value: TJSONObject): iMagentoHTTP;
begin
Result := Self;
FURI := '';
FURI := API + '/products';
try
FRestClient := TRESTClient.Create(FURI);
FRestClient.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,';
FRestClient.AcceptCharset := 'UTF-8, *;q=0.8';
FRestClient.AcceptEncoding := '';
FRestClient.AutoCreateParams := true;
FRestClient.AllowCookies := True;
FRestClient.BaseURL := FURI;
FRestClient.ContentType := '';
FRestClient.FallbackCharsetEncoding := 'utf-8';
FRestClient.HandleRedirects := True;
FRestResponse := TRESTResponse.Create(FRestClient);
FRestResponse.ContentType := 'application/json';
FRestRequest := TRESTRequest.Create(FRestClient);
FRestRequest.Accept := 'application/json, text/plain; q=0.9, text/html;q=0.8,';
FRestRequest.AcceptCharset := 'UTF-8, *;q=0.8';
FRestRequest.AcceptEncoding := '';
FRestRequest.AutoCreateParams := true;
FRestRequest.Client := FRestClient;
FRestRequest.Method := rmPOST;
FRestRequest.SynchronizedEvents := False;
FRestRequest.Response := FRestResponse;
FRestRequest.Params.Add;
FRestRequest.Params[0].ContentType := ctNone;
FRestRequest.Params[0].Kind := pkHTTPHEADER;
FRestRequest.Params[0].Name := 'Authorization';
FRestRequest.Params[0].Value := 'Bearer ' + ACCES_TOKEN;
FRestRequest.Params[0].Options := [poDoNotEncode];
FRestRequest.Params.Add;
FRestRequest.Params[1].ContentType := ctAPPLICATION_JSON;
FRestRequest.Params[1].Kind := pkREQUESTBODY;
FRestRequest.Params[1].Name := 'body';
FRestRequest.Params[1].Value := value.ToString;
FRestRequest.Params[1].Options := [poDoNotEncode];
FRestRequest.Execute;
FStatus := FRestResponse.StatusCode;
except
end;
end;
function TMagentoHTTP.Status: Integer;
begin
Result := FStatus;
end;
function TMagentoHTTP.Value(aValue: String): iMagentoHTTP;
begin
Result := Self;
FValue := aValue;
end;
end.
|
๏ปฟ{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.5 12/2/2004 9:26:44 PM JPMugaas
Bug fix.
Rev 1.4 11/11/2004 10:25:24 PM JPMugaas
Added OpenProxy and CloseProxy so you can do RecvFrom and SendTo functions
from the UDP client with SOCKS. You must call OpenProxy before using
RecvFrom or SendTo. When you are finished, you must use CloseProxy to close
any connection to the Proxy. Connect and disconnect also call OpenProxy and
CloseProxy.
Rev 1.3 11/11/2004 3:42:52 AM JPMugaas
Moved strings into RS. Socks will now raise an exception if you attempt to
use SOCKS4 and SOCKS4A with UDP. Those protocol versions do not support UDP
at all.
Rev 1.2 2004.05.20 11:39:12 AM czhower
IdStreamVCL
Rev 1.1 6/4/2004 5:13:26 PM SGrobety
EIdMaxCaptureLineExceeded message string
Rev 1.0 2004.02.03 4:19:50 PM czhower
Rename
Rev 1.15 10/24/2003 4:21:56 PM DSiders
Addes resource string for stream read exception.
Rev 1.14 2003.10.16 11:25:22 AM czhower
Added missing ;
Rev 1.13 10/15/2003 11:11:06 PM DSiders
Added resource srting for exception raised in TIdTCPServer.SetScheduler.
Rev 1.12 10/15/2003 11:03:00 PM DSiders
Added resource string for circular links from transparent proxy.
Corrected spelling errors.
Rev 1.11 10/15/2003 10:41:34 PM DSiders
Added resource strings for TIdStream and TIdStreamProxy exceptions.
Rev 1.10 10/15/2003 8:48:56 PM DSiders
Added resource strings for exceptions raised when setting thread component
properties.
Rev 1.9 10/15/2003 8:35:28 PM DSiders
Added resource string for exception raised in TIdSchedulerOfThread.NewYarn.
Rev 1.8 10/15/2003 8:04:26 PM DSiders
Added resource strings for exceptions raised in TIdLogFile, TIdReply, and
TIdIOHandler.
Rev 1.7 10/15/2003 1:03:42 PM DSiders
Created resource strings for TIdBuffer.Find exceptions.
Rev 1.6 2003.10.14 1:26:44 PM czhower
Uupdates + Intercept support
Rev 1.5 10/1/2003 10:49:02 PM GGrieve
Rework buffer for Octane Compability
Rev 1.4 7/1/2003 8:32:32 PM BGooijen
Added RSFibersNotSupported
Rev 1.3 7/1/2003 02:31:34 PM JPMugaas
Message for invalid IP address.
Rev 1.2 5/14/2003 6:40:22 PM BGooijen
RS for transparent proxy
Rev 1.1 1/17/2003 05:06:04 PM JPMugaas
Exceptions for scheduler string.
Rev 1.0 11/13/2002 08:42:02 AM JPMugaas
}
unit IdResourceStringsCore;
interface
{$i IdCompilerDefines.inc}
resourcestring
RSNoBindingsSpecified = 'Aucune liaison n'#39'a รฉtรฉ spรฉcifiรฉe.';
RSCannotAllocateSocket = 'Impossible d'#39'allouer le socket.';
RSSocksUDPNotSupported = 'UDP n'#39'est pas supportรฉ dans cette version SOCKS.';
RSSocksRequestFailed = 'Rejet ou รฉchec de la requรชte.';
RSSocksRequestServerFailed = 'Requรชte rejetรฉe car le serveur SOCKS ne peut pas รฉtablir de connexion.';
RSSocksRequestIdentFailed = 'Requรชte rejetรฉe car le programme client et l'#39'identd indiquent des ID utilisateur diffรฉrents.';
RSSocksUnknownError = 'Erreur socks inconnue.';
RSSocksServerRespondError = 'Le serveur Socks n'#39'a pas rรฉpondu.';
RSSocksAuthMethodError = 'Mรฉthode d'#39'authentification socks incorrecte.';
RSSocksAuthError = 'Erreur d'#39'authentification sur le serveur socks.';
RSSocksServerGeneralError = 'Panne du serveur SOCKS gรฉnรฉrale.';
RSSocksServerPermissionError = 'Connexion non autorisรฉe par l'#39'ensemble de rรจgles.';
RSSocksServerNetUnreachableError = 'Rรฉseau inaccessible.';
RSSocksServerHostUnreachableError = 'Hรดte inaccessible.';
RSSocksServerConnectionRefusedError = 'Connexion refusรฉe.';
RSSocksServerTTLExpiredError = 'Expiration du TTL.';
RSSocksServerCommandError = 'Commande non supportรฉe.';
RSSocksServerAddressError = 'Type d'#39'adresse non supportรฉ.';
RSInvalidIPAddress = 'Adresse IP non valide';
RSInterceptCircularLink = '%s : Les liens circulaires ne sont pas autorisรฉs';
RSNotEnoughDataInBuffer = 'Pas assez de donnรฉes dans le tampon. (%d/%d)';
RSTooMuchDataInBuffer = 'Trop de donnรฉes dans le tampon.';
RSCapacityTooSmall = 'La capacitรฉ ne peut pas รชtre plus petite que la taille.';
RSBufferIsEmpty = 'Pas d'#39'octets dans le tampon.';
RSBufferRangeError = 'Index hors limites.';
RSFileNotFound = 'Fichier "%s" introuvable';
RSNotConnected = 'Non connectรฉ';
RSObjectTypeNotSupported = 'Type d'#39'objet non supportรฉ.';
RSIdNoDataToRead = 'Pas de donnรฉes pour la lecture.';
RSReadTimeout = 'Dรฉlai de lecture.';
RSReadLnWaitMaxAttemptsExceeded = 'Le nombre maximal de tentatives de lecture de lignes a รฉtรฉ dรฉpassรฉ.';
RSAcceptTimeout = 'Dรฉlai d'#39'acceptation dรฉpassรฉ.';
RSReadLnMaxLineLengthExceeded = 'Longueur de ligne maximale dรฉpassรฉe.';
RSRequiresLargeStream = 'Dรฉfinissez LargeStream sur True pour envoyer des flux supรฉrieurs ร 2 Go';
RSDataTooLarge = 'Les donnรฉes sont trop grandes pour le flux';
RSConnectTimeout = 'Dรฉlai de connexion.';
RSICMPNotEnoughtBytes = 'Pas suffisamment d'#39'octets reรงus';
RSICMPNonEchoResponse = 'Rรฉponse de type non-รฉcho reรงue';
RSThreadTerminateAndWaitFor = 'Impossible d'#39'appeler TerminateAndWaitFor sur les threads FreeAndTerminate';
RSAlreadyConnected = 'Dรฉjร connectรฉ.';
RSTerminateThreadTimeout = 'Dรฉlai du thread de terminaison dรฉpassรฉ';
RSNoExecuteSpecified = 'Aucun gestionnaire d'#39'exรฉcution n'#39'a รฉtรฉ trouvรฉ.';
RSNoCommandHandlerFound = 'Aucun gestionnaire de commande n'#39'a รฉtรฉ trouvรฉ.';
RSCannotPerformTaskWhileServerIsActive = 'Impossible d'#39'effectuer la tรขche tant que le serveur est actif.';
RSThreadClassNotSpecified = 'Classe Thread non spรฉcifiรฉe.';
RSMaximumNumberOfCaptureLineExceeded = 'Le nombre de lignes maximal autorisรฉ a รฉtรฉ dรฉpassรฉ'; // S.G. 6/4/2004: IdIOHandler.DoCapture
RSNoCreateListeningThread = 'Impossible de crรฉer un thread d'#39'รฉcoute.';
RSInterceptIsDifferent = 'Une autre interception est dรฉjร affectรฉe au IOHandler';
//scheduler
RSchedMaxThreadEx = 'Le nombre maximal de threads pour ce planificateur a รฉtรฉ dรฉpassรฉ.';
//transparent proxy
RSTransparentProxyCannotBind = 'Impossible de lier le proxy transparent.';
RSTransparentProxyCanNotSupportUDP = 'UDP non supportรฉ par ce proxy.';
//Fibers
RSFibersNotSupported = 'Les fibres ne sont pas supportรฉes sur ce systรจme';
// TIdICMPCast
RSIPMCastInvalidMulticastAddress = 'L'#39'adresse IP fournie n'#39'est pas une adresse de multidiffusion valide [224.0.0.0 ร 239.255.255.255].';
RSIPMCastNotSupportedOnWin32 = 'Cette fonction n'#39'est pas supportรฉe sur Win32.';
RSIPMCastReceiveError0 = 'Erreur de rรฉception (diffusion IP) = 0.';
// Log strings
RSLogConnected = 'Connectรฉ.';
RSLogDisconnected = 'Dรฉconnectรฉ.';
RSLogEOL = '<EOL>'; // End of Line
RSLogCR = '<CR>'; // Carriage Return
RSLogLF = '<LF>'; // Line feed
RSLogRecv = 'Reรงu '; // Receive
RSLogSent = 'Envoyรฉ '; // Send
RSLogStat = 'Stat '; // Status
RSLogFileAlreadyOpen = 'Impossible de dรฉfinir le nom de fichier quand le fichier journal est ouvert.';
RSBufferMissingTerminator = 'Le terminateur du tampon doit รชtre spรฉcifiรฉ.';
RSBufferInvalidStartPos = 'La position de dรฉbut du tampon est incorrecte.';
RSIOHandlerCannotChange = 'Impossible de changer un IOHandler connectรฉ.';
RSIOHandlerTypeNotInstalled = 'Aucun IOHandler de type %s n'#39'est installรฉ.';
RSReplyInvalidCode = 'Le code de rรฉponse n'#39'est pas valide : %s';
RSReplyCodeAlreadyExists = 'Le code de rรฉponse existe dรฉjร : %s';
RSThreadSchedulerThreadRequired = 'Le thread doit รชtre spรฉcifiรฉ pour le planificateur.';
RSNoOnExecute = 'Vous devez avoir un รฉvรฉnement OnExecute.';
RSThreadComponentLoopAlreadyRunning = 'Impossible de dรฉfinir la propriรฉtรฉ Loop quand le thread est dรฉjร en cours d'#39'exรฉcution.';
RSThreadComponentThreadNameAlreadyRunning = 'Impossible de dรฉfinir le nom du thread quand le thread est dรฉjร en cours d'#39'exรฉcution.';
RSStreamProxyNoStack = 'Une pile n'#39'a pas รฉtรฉ crรฉรฉe pour la conversion du type de donnรฉes.';
RSTransparentProxyCyclic = 'Erreur cyclique de proxy transparent.';
RSTCPServerSchedulerAlreadyActive = 'Impossible de changer le planificateur tant que le serveur est actif.';
RSUDPMustUseProxyOpen = 'Vous devez utiliser proxyOpen';
//ICMP stuff
RSICMPTimeout = 'Dรฉlai dรฉpassรฉ';
//Destination Address -3
RSICMPNetUnreachable = 'net inaccessible;';
RSICMPHostUnreachable = 'hรดte inaccessible;';
RSICMPProtUnreachable = 'protocole inaccessible;';
RSICMPPortUnreachable = 'Port inaccessible';
RSICMPFragmentNeeded = 'Fragmentation nรฉcessaire et Ne pas fragmenter a รฉtรฉ dรฉfini';
RSICMPSourceRouteFailed = 'Echec de l'#39'itinรฉraire source';
RSICMPDestNetUnknown = 'Rรฉseau de destination inconnu';
RSICMPDestHostUnknown = 'Hรดte de destination inconnu';
RSICMPSourceIsolated = 'Hรดte source isolรฉ';
RSICMPDestNetProhibitted = 'La communication avec le rรฉseau de destination est administrativement interdite';
RSICMPDestHostProhibitted = 'La communication avec l'#39'hรดte de destination est administrativement interdite';
RSICMPTOSNetUnreach = 'Rรฉseau de destination inaccessible pour le type de service';
RSICMPTOSHostUnreach = 'Hรดte de destination inaccessible pour le type de service';
RSICMPAdminProhibitted = 'Communication administrativement interdite';
RSICMPHostPrecViolation = 'Violation de la prรฉcรฉdence de l'#39'hรดte';
RSICMPPrecedenceCutoffInEffect = 'Coupure de prรฉcรฉdence en vigueur';
//for IPv6
RSICMPNoRouteToDest = 'pas d'#39'itinรฉraire vers la destination';
RSICMPAAdminDestProhibitted = 'communication avec destination administrativement interdite';
RSICMPSourceFilterFailed = 'รฉchec de la stratรฉgie d'#39'entrรฉe/sortie (ingress/egress) de l'#39'adresse source';
RSICMPRejectRoutToDest = 'rejeter l'#39'itinรฉraire vers la destination';
// Destination Address - 11
RSICMPTTLExceeded = 'durรฉe de vie dรฉpassรฉe dans le transit';
RSICMPHopLimitExceeded = 'limite de saut dรฉpassรฉe dans le transit';
RSICMPFragAsmExceeded = 'temps de rรฉassemblage du fragment dรฉpassรฉ.';
//Parameter Problem - 12
RSICMPParamError = 'Problรจme de paramรจtre (offset %d)';
//IPv6
RSICMPParamHeader = 'champ en-tรชte erronรฉ (offset %d)';
RSICMPParamNextHeader = 'type en-tรชte suivant non reconnu (offset %d)';
RSICMPUnrecognizedOpt = 'option IPv6 non reconnue (offset %d)';
//Source Quench Message -4
RSICMPSourceQuenchMsg = 'Message Extinction de source';
//Redirect Message
RSICMPRedirNet = 'Rediriger les datagrammes pour le rรฉseau.';
RSICMPRedirHost = 'Rediriger les datagrammes pour l'#39'hรดte.';
RSICMPRedirTOSNet = 'Rediriger les datagrammes pour le type de service et le rรฉseau.';
RSICMPRedirTOSHost = 'Rediriger les datagrammes pour le type de service et l'#39'hรดte.';
//echo
RSICMPEcho = 'Echo';
//timestamp
RSICMPTimeStamp = 'Horodatage';
//information request
RSICMPInfoRequest = 'Requรชte d'#39'information';
//mask request
RSICMPMaskRequest = 'Requรชte de masque d'#39'adresse';
// Traceroute
RSICMPTracePacketForwarded = 'Le paquet sortant a รฉtรฉ transfรฉrรฉ avec succรจs';
RSICMPTraceNoRoute = 'Pas d'#39'itinรฉraire pour le paquet sortant ; paquet ignorรฉ';
//conversion errors
RSICMPConvUnknownUnspecError = 'Erreur inconnue/non spรฉcifiรฉe';
RSICMPConvDontConvOptPresent = 'Prรฉsence d'#39'une option Ne pas convertir';
RSICMPConvUnknownMandOptPresent = 'Prรฉsence d'#39'une option obligatoire inconnue';
RSICMPConvKnownUnsupportedOptionPresent = 'Prรฉsence d'#39'une option non supportรฉe connue';
RSICMPConvUnsupportedTransportProtocol = 'Protocole de transport non supportรฉ';
RSICMPConvOverallLengthExceeded = 'Longueur globale dรฉpassรฉe';
RSICMPConvIPHeaderLengthExceeded = 'Longueur de l'#39'en-tรชte IP dรฉpassรฉe';
RSICMPConvTransportProtocol_255 = 'Protocole de transport > 255';
RSICMPConvPortConversionOutOfRange = 'Conversion de port hors limites';
RSICMPConvTransportHeaderLengthExceeded = 'Longueur de l'#39'en-tรชte de transport dรฉpassรฉe';
RSICMPConv32BitRolloverMissingAndACKSet = 'Rollover 32 bits manquant et ACK dรฉfini';
RSICMPConvUnknownMandatoryTransportOptionPresent = 'Prรฉsence d'#39'une option de transport obligatoire inconnue';
//mobile host redirect
RSICMPMobileHostRedirect = 'Redirection d'#39'hรดte mobile';
//IPv6 - Where are you
RSICMPIPv6WhereAreYou = 'IPv6 Where-Are-You';
//IPv6 - I am here
RSICMPIPv6IAmHere = 'IPv6 I-Am-Here';
// Mobile Regestration request
RSICMPMobReg = 'Requรชte d'#39'enregistrement mobile';
//Skip
RSICMPSKIP = 'SKIP';
//Security
RSICMPSecBadSPI = 'SPI incorrect';
RSICMPSecAuthenticationFailed = 'Echec d'#39'authentification';
RSICMPSecDecompressionFailed = 'Echec de la dรฉcompression';
RSICMPSecDecryptionFailed = 'Echec du dรฉcryptage';
RSICMPSecNeedAuthentication = 'Authentification nรฉcessaire';
RSICMPSecNeedAuthorization = 'Autorisation nรฉcessaire';
//IPv6 Packet Too Big
RSICMPPacketTooBig = 'Paquet trop gros (MTU = %d)';
{ TIdCustomIcmpClient }
// TIdSimpleServer
RSCannotUseNonSocketIOHandler = 'Impossible d'#39'utiliser un IOHandler non-socket';
implementation
end.
|
{**********************************************************************
Package pl_Shapes.pkg
This unit is part of CodeTyphon Studio (http://www.pilotlogic.com/)
***********************************************************************}
unit TplFillShapeUnit;
interface
uses
Messages, LMessages, Types, LCLType, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
const
DefSize = 10;
DefSpacing = 20;
DefShadowOfs = 2;
type
TplFillShapeType = (msRectangle, msRoundRect, msDiamond, msEllipse,
msTriangle, msLine, msText);
TRepeatMode = (rpNone, rpVert, rpHoriz, rpBoth);
TShapeStr = string
[255];
TplFillShape = class(TGraphicControl)
private
FAngle: integer;
FAutoSize: boolean;
FDX, FDY: integer;
FFilled: boolean;
FRepeatMode: TRepeatMode;
FShapeType: TplFillShapeType;
FShapeH: integer;
FShapeW: integer;
FXSpacing: integer;
FYSpacing: integer;
FXMargin: integer;
FYMargin: integer;
FBorder: boolean;
FBorderColor: TColor;
FBorderWidth: integer;
FShadow: boolean;
FShadowColor: TColor;
FShadowX: integer;
FShadowY: integer;
procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure CMColorChanged(var Message: TMessage); message CM_COLORCHANGED;
protected
procedure SetAngle(Value: integer);
procedure SetAutoSize(Value: boolean); override;
procedure SetFilled(Value: boolean);
procedure SetRepeatMode(Value: TRepeatMode);
procedure SetShapeType(Value: TplFillShapeType);
procedure SetShapeH(Value: integer);
procedure SetShapeW(Value: integer);
procedure SetXSpacing(Value: integer);
procedure SetYSpacing(Value: integer);
procedure SetXMargin(Value: integer);
procedure SetYMargin(Value: integer);
procedure SetBorder(Value: boolean);
procedure SetBorderColor(Value: TColor);
procedure SetBorderWidth(Value: integer);
procedure SetShadow(Value: boolean);
procedure SetShadowColor(Value: TColor);
procedure SetShadowX(Value: integer);
procedure SetShadowY(Value: integer);
procedure PrepareText;
procedure UnprepareText;
procedure AdjustShapeSize;
procedure AdjustControlSize;
procedure DrawRectangle(X, Y: integer);
procedure DrawRoundRect(X, Y: integer);
procedure DrawDiamond(X, Y: integer);
procedure DrawEllipse(X, Y: integer);
procedure DrawTriangle(X, Y: integer);
procedure DrawLine(X, Y: integer);
procedure DrawText(X, Y: integer);
procedure Paint; override;
property AutoSize: boolean read FAutoSize write SetAutoSize;
public
constructor Create(AOwner: TComponent); override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: integer); override;
published
property Angle: integer read FAngle write SetAngle;
property Filled: boolean read FFilled write SetFilled default True;
property RepeatMode: TRepeatMode read FRepeatMode write SetRepeatMode default rpBoth;
property ShapeType: TplFillShapeType read FShapeType write SetShapeType;
property ShapeH: integer read FShapeH write SetShapeH default DefSize;
property ShapeW: integer read FShapeW write SetShapeW default DefSize;
property XSpacing: integer read FXSpacing write SetXSpacing default DefSpacing;
property YSpacing: integer read FYSpacing write SetYSpacing default DefSpacing;
property XMargin: integer read FXMargin write SetXMargin;
property YMargin: integer read FYMargin write SetYMargin;
property Border: boolean read FBorder write SetBorder;
property BorderColor: TColor read FBorderColor write SetBorderColor default clBlack;
property BorderWidth: integer read FBorderWidth write SetBorderWidth default 1;
property Shadow: boolean read FShadow write SetShadow;
property ShadowColor: TColor read FShadowColor write SetShadowColor default clGray;
property ShadowX: integer read FShadowX write SetShadowX default DefShadowOfs;
property ShadowY: integer read FShadowY write SetShadowY default DefShadowOfs;
property Align;
property Color;
property Font;
property ParentColor;
property ParentFont;
property Text;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
end;
implementation
constructor TplFillShape.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Width := 64;
Height := 64;
Color := clNavy;
FFilled := True;
FShapeH := DefSize;
FShapeW := DefSize;
FRepeatMode := rpBoth;
FXSpacing := DefSpacing;
FYSpacing := DefSpacing;
FBorderColor := clBlack;
FBorderWidth := 1;
FShadowColor := clGray;
FShadowX := DefShadowOfs;
FShadowY := DefShadowOfs;
end;
procedure TplFillShape.Paint;
var
i, j, XN, YN, X, Y: integer;
begin
inherited Paint;
if FShapeType = msText then
PrepareText;
XN := 1;
YN := 1;
if (RepeatMode in [rpHoriz, rpBoth]) and (XSpacing > 0) then
XN := Width div XSpacing + 1;
if (RepeatMode in [rpVert, rpBoth]) and (YSpacing > 0) then
YN := Height div YSpacing + 1;
for i := 1 to YN do
for j := 1 to XN do
begin
X := (j - 1) * XSpacing + XMargin;
Y := (i - 1) * YSpacing + YMargin;
case FShapeType of
msRectangle: DrawRectangle(X, Y);
msRoundRect: DrawRoundRect(X, Y);
msDiamond: DrawDiamond(X, Y);
msEllipse: DrawEllipse(X, Y);
msTriangle: DrawTriangle(X, Y);
msLine: DrawLine(X, Y);
msText: DrawText(X, Y);
end;
end;
if FShapeType = msText then
UnprepareText;
end;
procedure TplFillShape.SetBounds(ALeft, ATop, AWidth, AHeight: integer);
begin
inherited SetBounds(ALeft, ATop, AWidth, AHeight);
AdjustShapeSize;
end;
procedure TplFillShape.CMTextChanged(var Message: TMessage);
begin
Invalidate;
end;
procedure TplFillShape.CMFontChanged(var Message: TMessage);
begin
inherited;
Color := Font.Color;
end;
procedure TplFillShape.CMColorChanged(var Message: TMessage);
begin
inherited;
Font.Color := Color;
end;
procedure TplFillShape.AdjustShapeSize;
begin
if FAutoSize then
begin
FShapeW := Width - FXMargin * 2;
FShapeH := Height - FYMargin * 2;
if Shadow then
begin
Dec(FShapeW, ShadowX);
Dec(FShapeH, ShadowY);
end;
end;
end;
procedure TplFillShape.AdjustControlSize;
var
H, W: integer;
begin
if FAutoSize then
begin
W := FShapeW + FXMargin * 2;
H := FShapeH + FYMargin * 2;
if FShadow then
begin
Inc(W, ShadowX);
Inc(H, ShadowY);
end;
Width := W;
Height := H;
end;
end;
procedure TplFillShape.SetAngle(Value: integer);
begin
if Value <> FAngle then
begin
FAngle := Value;
{-- Normalization: -179ยฐ .. +180ยฐ ---------------}
FAngle := FAngle mod 360;
if FAngle = -180 then
FAngle := 180;
if FAngle > 180 then
FAngle := -(360 - FAngle);
if FAngle < -180 then
FAngle := (360 + FAngle);
{-- Only 45ยฐ steps allowed for triangles --------}
if ShapeType in [msTriangle, msLine] then
FAngle := Round(FAngle / 45) * 45;
{-- Refresh -------------------------------------}
Invalidate;
end;
end;
procedure TplFillShape.SetAutoSize(Value: boolean);
begin
if Value <> FAutoSize then
begin
FAutoSize := Value;
if FAutoSize then
begin
FShapeW := Width - FXMargin * 2;
FShapeH := Height - FYMargin * 2;
end;
Invalidate;
end;
end;
procedure TplFillShape.SetFilled(Value: boolean);
begin
if Value <> FFilled then
begin
FFilled := Value;
Invalidate;
end;
end;
procedure TplFillShape.SetRepeatMode(Value: TRepeatMode);
begin
if Value <> FRepeatMode then
begin
FRepeatMode := Value;
AutoSize := FRepeatMode = rpNone;
Invalidate;
end;
end;
procedure TplFillShape.SetShapeType(Value: TplFillShapeType);
begin
if Value <> FShapeType then
begin
FShapeType := Value;
Invalidate;
end;
end;
procedure TplFillShape.SetShapeH(Value: integer);
begin
if Value <> FShapeH then
begin
FShapeH := Value;
AdjustControlSize;
Invalidate;
end;
end;
procedure TplFillShape.SetShapeW(Value: integer);
begin
if Value <> FShapeW then
begin
FShapeW := Value;
AdjustControlSize;
Invalidate;
end;
end;
procedure TplFillShape.SetXSpacing(Value: integer);
begin
if Value <> FXSpacing then
begin
FXSpacing := Value;
Invalidate;
end;
end;
procedure TplFillShape.SetYSpacing(Value: integer);
begin
if Value <> FYSpacing then
begin
FYSpacing := Value;
Invalidate;
end;
end;
procedure TplFillShape.SetXMargin(Value: integer);
begin
if Value <> FXMargin then
begin
FXMargin := Value;
AdjustControlSize;
Invalidate;
end;
end;
procedure TplFillShape.SetYMargin(Value: integer);
begin
if Value <> FYMargin then
begin
FYMargin := Value;
AdjustControlSize;
Invalidate;
end;
end;
procedure TplFillShape.SetBorder(Value: boolean);
begin
if Value <> FBorder then
begin
FBorder := Value;
Invalidate;
end;
end;
procedure TplFillShape.SetBorderColor(Value: TColor);
begin
if Value <> FBorderColor then
begin
FBorderColor := Value;
Invalidate;
end;
end;
procedure TplFillShape.SetBorderWidth(Value: integer);
begin
if Value <> FBorderWidth then
begin
FBorderWidth := Value;
Invalidate;
end;
end;
procedure TplFillShape.SetShadow(Value: boolean);
begin
if Value <> FShadow then
begin
FShadow := Value;
AdjustControlSize;
Invalidate;
end;
end;
procedure TplFillShape.SetShadowColor(Value: TColor);
begin
if Value <> FShadowColor then
begin
FShadowColor := Value;
Invalidate;
end;
end;
procedure TplFillShape.SetShadowX(Value: integer);
begin
if Value <> FShadowX then
begin
FShadowX := Value;
AdjustControlSize;
Invalidate;
end;
end;
procedure TplFillShape.SetShadowY(Value: integer);
begin
if Value <> FShadowY then
begin
FShadowY := Value;
AdjustControlSize;
Invalidate;
end;
end;
{--------------------------------------------------------------}
{ Draw methods }
{--------------------------------------------------------------}
procedure TplFillShape.PrepareText;
var
Rad: extended;
TL, TH: integer;
Sz: TSize;
FontName: string[255];
begin
Canvas.Font.Assign(Font);
Canvas.Brush.Style := bsClear;
{-- Calculates text offset from shape center -------------}
// GetTextExtentPoint32(Canvas.Handle,@Text[1],Length(Text),Sz);
Sz := canvas.TextExtent(Text);
TL := Abs(Sz.CX);
TH := Abs(Sz.CY);
Rad := FAngle * Pi / 180;
FDX := Round(TL / 2 * cos(Rad) + TH / 2 * sin(Rad));
FDY := Round(TL / 2 * sin(Rad) - TH / 2 * cos(Rad));
end;
procedure TplFillShape.UnprepareText;
begin
end;
procedure TplFillShape.DrawRectangle(X, Y: integer);
var
SX, SY, i: integer;
Pt, ShPt: array[1..5] of TPoint;
begin
Pt[1].X := X;
Pt[1].Y := Y;
Pt[2].X := X + ShapeW;
Pt[2].Y := Y;
Pt[3].X := X + ShapeW;
Pt[3].Y := Y + ShapeH;
Pt[4].X := X;
Pt[4].Y := Y + ShapeH;
Pt[5] := Pt[1];
if Shadow then
begin
for i := 1 to 5 do
begin
ShPt[i] := Pt[i];
Inc(ShPt[i].X, ShadowX);
Inc(ShPt[i].Y, ShadowY);
end;
SX := X + ShadowX;
SY := Y + ShadowY;
Canvas.Pen.Color := ShadowColor;
Canvas.Pen.Width := BorderWidth;
Canvas.Brush.Color := ShadowColor;
if Filled then
Canvas.Rectangle(SX, SY, SX + ShapeW, SY + ShapeH)
else
Canvas.PolyLine(ShPt);
end;
if Border then
Canvas.Pen.Color := BorderColor
else
Canvas.Pen.Color := Color;
Canvas.Pen.Width := BorderWidth;
Canvas.Brush.Color := Color;
if Filled then
Canvas.Rectangle(X, Y, X + ShapeW, Y + ShapeH)
else
Canvas.PolyLine(Pt);
end;
procedure TplFillShape.DrawRoundRect(X, Y: integer);
var
SX, SY: integer;
begin
if Shadow then
begin
SX := X + ShadowX;
SY := Y + ShadowY;
Canvas.Pen.Color := ShadowColor;
Canvas.Pen.Width := 1;
Canvas.Brush.Color := ShadowColor;
Canvas.RoundRect(SX, SY, SX + ShapeW, SY + ShapeH, ShapeW div 2, ShapeH div 2);
end;
if Border then
Canvas.Pen.Color := BorderColor
else
Canvas.Pen.Color := Color;
Canvas.Pen.Width := BorderWidth;
Canvas.Brush.Color := Color;
Canvas.RoundRect(X, Y, X + ShapeW, Y + ShapeH, ShapeW div 2, ShapeH div 2);
end;
procedure TplFillShape.DrawDiamond(X, Y: integer);
var
i: integer;
Pt, ShPt: array[1..5] of TPoint;
begin
Pt[1].X := X + ShapeW div 2;
Pt[1].Y := Y;
Pt[2].X := X + (ShapeW div 2) * 2;
Pt[2].Y := Y + ShapeH div 2;
Pt[3].X := Pt[1].X;
Pt[3].Y := Y + (ShapeH div 2) * 2;
Pt[4].X := X;
Pt[4].Y := Pt[2].Y;
Pt[5] := Pt[1];
if Shadow then
begin
for i := 1 to 5 do
begin
ShPt[i] := Pt[i];
Inc(ShPt[i].X, ShadowX);
Inc(ShPt[i].Y, ShadowY);
end;
Canvas.Pen.Color := ShadowColor;
Canvas.Pen.Width := BorderWidth;
Canvas.Brush.Color := ShadowColor;
if Filled then
Canvas.Polygon(ShPt)
else
Canvas.PolyLine(ShPt);
end;
if Border then
Canvas.Pen.Color := BorderColor
else
Canvas.Pen.Color := Color;
Canvas.Pen.Width := BorderWidth;
Canvas.Brush.Color := Color;
if Filled then
Canvas.Polygon(Pt)
else
Canvas.PolyLine(Pt);
end;
procedure TplFillShape.DrawEllipse(X, Y: integer);
var
SX, SY: integer;
begin
if Shadow then
begin
SX := X + ShadowX;
SY := Y + ShadowY;
Canvas.Pen.Color := ShadowColor;
Canvas.Pen.Width := BorderWidth;
Canvas.Brush.Color := ShadowColor;
if Filled then
Canvas.Ellipse(SX, SY, SX + ShapeW, SY + ShapeH)
else
Canvas.Arc(SX, SY, SX + ShapeW, SY + ShapeH, SX, SY, SX, SY);
end;
if Border then
Canvas.Pen.Color := BorderColor
else
Canvas.Pen.Color := Color;
Canvas.Pen.Width := BorderWidth;
Canvas.Brush.Color := Color;
if Filled then
Canvas.Ellipse(X, Y, X + ShapeW, Y + ShapeH)
else
Canvas.Arc(X, Y, X + ShapeW, Y + ShapeH, X, Y, X, Y);
end;
procedure TplFillShape.DrawTriangle(X, Y: integer);
var
i, SW, SH: integer;
Pt, ShPt: array[1..4] of TPoint;
begin
SW := (ShapeW div 2) * 2;
SH := (ShapeH div 2) * 2;
case Angle of
-135:
begin
Pt[1].X := X;
Pt[1].Y := Y;
Pt[2].X := X;
Pt[2].Y := Y + SH;
Pt[3].X := X + SW;
Pt[3].Y := Y + SH;
end;
-90:
begin
Pt[1].X := X;
Pt[1].Y := Y;
Pt[2].X := X + SW;
Pt[2].Y := Y;
Pt[3].X := X + SW div 2;
Pt[3].Y := Y + SH;
end;
-45:
begin
Pt[1].X := X + SW;
Pt[1].Y := Y;
Pt[2].X := X + SW;
Pt[2].Y := Y + SH;
Pt[3].X := X;
Pt[3].Y := Y + SH;
end;
0:
begin
Pt[1].X := X;
Pt[1].Y := Y;
Pt[2].X := X + SW;
Pt[2].Y := Y + SH div 2;
Pt[3].X := X;
Pt[3].Y := Y + SH;
end;
45:
begin
Pt[1].X := X;
Pt[1].Y := Y;
Pt[2].X := X + SW;
Pt[2].Y := Y;
Pt[3].X := X + SW;
Pt[3].Y := Y + SH;
end;
90:
begin
Pt[1].X := X + SW div 2;
Pt[1].Y := Y;
Pt[2].X := X + SW;
Pt[2].Y := Y + SH;
Pt[3].X := X;
Pt[3].Y := Y + SH;
end;
135:
begin
Pt[1].X := X;
Pt[1].Y := Y;
Pt[2].X := X + SW;
Pt[2].Y := Y;
Pt[3].X := X;
Pt[3].Y := Y + SH;
end;
180:
begin
Pt[1].X := X;
Pt[1].Y := Y + SH div 2;
Pt[2].X := X + SW;
Pt[2].Y := Y;
Pt[3].X := X + SW;
Pt[3].Y := Y + SH;
end;
end;
Pt[4] := Pt[1];
if Shadow then
begin
for i := 1 to 4 do
begin
ShPt[i] := Pt[i];
Inc(ShPt[i].X, ShadowX);
Inc(ShPt[i].Y, ShadowY);
end;
Canvas.Pen.Color := ShadowColor;
Canvas.Pen.Width := BorderWidth;
Canvas.Brush.Color := ShadowColor;
if Filled then
Canvas.Polygon(ShPt)
else
Canvas.PolyLine(ShPt);
end;
if Border then
Canvas.Pen.Color := BorderColor
else
Canvas.Pen.Color := Color;
Canvas.Pen.Width := BorderWidth;
Canvas.Brush.Color := Color;
if Filled then
Canvas.Polygon(Pt)
else
Canvas.PolyLine(Pt);
end;
procedure TplFillShape.DrawLine(X, Y: integer);
var
A, X1, Y1, X2, Y2, CX, CY: integer;
begin
if Angle < 0 then
A := 180 - Angle
else
A := Angle;
A := A mod 180;
CX := ShapeW div 2;
CY := ShapeH div 2;
case A of
0:
begin
X1 := X;
Y1 := Y + CY;
X2 := X + ShapeW;
Y2 := Y + CY;
end;
45:
begin
X1 := X;
Y1 := Y + ShapeH;
X2 := X + ShapeW;
Y2 := Y;
end;
90:
begin
X1 := X + CX;
Y1 := Y;
X2 := X + CX;
Y2 := Y + ShapeH;
end;
135:
begin
X1 := X;
Y1 := Y;
X2 := X + ShapeW;
Y2 := Y + ShapeH;
end;
else
begin
X1 := X + CX;
Y1 := Y + CY;
X2 := CX + ShapeW;
Y2 := Y + CY;
end;
end;
Canvas.Pen.Width := BorderWidth;
if Shadow then
begin
Canvas.Pen.Color := ShadowColor;
Inc(X1, ShadowX);
Inc(Y1, ShadowY);
Inc(X2, ShadowX);
Inc(Y2, ShadowY);
Canvas.MoveTo(X1, Y1);
Canvas.LineTo(X2, Y2);
Dec(X1, ShadowX);
Dec(Y1, ShadowY);
Dec(X2, ShadowX);
Dec(Y2, ShadowY);
end;
Canvas.Pen.Color := Color;
Canvas.MoveTo(X1, Y1);
Canvas.LineTo(X2, Y2);
end;
procedure TplFillShape.DrawText(X, Y: integer);
var
TX, TY, SX, SY: integer;
begin
TX := X + ShapeW div 2 - FDX;
TY := Y + ShapeH div 2 + FDY;
if Shadow then
begin
canvas.Font.Color := ColorToRGB(ShadowColor);
SX := TX + ShadowX;
SY := TY + ShadowY;
Canvas.TextOut(SX, SY, Text);
end;
canvas.Font.Color := ColorToRGB(Color);
Canvas.TextOut(TX, TY, Text);
Canvas.TextOut(TX, TY, Text);
end;
end.
|
unit Tests;
interface
uses SimpleDS, SqliteConnection;
type
// Record to model user data
TUser = record
id : string[36];
firstName : string[40];
lastName : string[150];
birtDate : TDateTime;
active : Boolean;
phoneNumber : string[12];
end;
// Class responsible to test the database connection
TDatabaseConnectionTester = class
dbConnection : TSqliteConnection;
usersToTest : Array of TUser;
private
// Connects to database
function ConnectToDatabase : Boolean;
// Disconnects from database
procedure DisconnectDatabase;
// Fills the list of users to use during the tests
procedure FillUsersList;
// Creates the users table in database
function CreateUsersTable : Boolean;
// Inserts all users to database
function InsertUsers : Boolean;
// Selects all users from database
function SelectAllUsers : TSimpleDataSet;
// Check if users received from database are equals to inserted ones
function CheckInsertedUsers : Boolean;
public
constructor Create;
destructor Destroy; override;
function ExecuteTest : Boolean;
end;
implementation
uses SysUtils, GuidHelper, DatabaseConnection;
const DatabaseFileName = 'testdb.sqlite';
{ TDatabaseConnectionTester }
function TDatabaseConnectionTester.CheckInsertedUsers: Boolean;
var
usersDataSet : TSimpleDataSet;
begin
usersDataSet := SelectAllUsers;
Result := False;
if not Assigned(usersDataSet) then
Exit;
Result := usersDataSet.RecordCount = Length(self.usersToTest);
FreeAndNil(usersDataSet);
end;
function TDatabaseConnectionTester.ConnectToDatabase: Boolean;
begin
Result := self.dbConnection.Connect;
end;
constructor TDatabaseConnectionTester.Create;
begin
self.dbConnection := TSqliteConnection.Create(nil, ':memory:');
SetLength(self.usersToTest, 2);
self.FillUsersList;
end;
function TDatabaseConnectionTester.CreateUsersTable: Boolean;
const
CreateUsersTableComand = 'CREATE TABLE users ' +
'( ' +
'id text not null primary key, ' +
'firstname text not null, ' +
'lastname text not null, ' +
'birthdate date not null, ' +
'active int default 1 not null, ' +
'phonenumber text not null ' +
')';
begin
Result := self.dbConnection.Execute(CreateUsersTableComand);
end;
destructor TDatabaseConnectionTester.Destroy;
begin
self.DisconnectDatabase;
FreeAndNil(self.dbConnection);
FreeAndNil(self.usersToTest);
inherited;
end;
procedure TDatabaseConnectionTester.DisconnectDatabase;
begin
if Assigned(self.dbConnection) and self.dbConnection.Connected then
self.dbConnection.Disconnect;
end;
function TDatabaseConnectionTester.ExecuteTest : Boolean;
begin
Result := False;
if not self.ConnectToDatabase then
Exit;
if not self.CreateUsersTable then
begin
self.DisconnectDatabase;
Exit;
end;
if not self.InsertUsers then
begin
self.DisconnectDatabase;
Exit;
end;
if not self.CheckInsertedUsers then
begin
self.DisconnectDatabase;
Exit;
end;
self.DisconnectDatabase;
Result := True;
end;
function TDatabaseConnectionTester.InsertUsers: Boolean;
var
i : Integer;
insertParameters : TSqlParams;
const
InsertStatement = 'insert into users (id, firstname, lastname, birthdate, active, phonenumber) '+
'values (:id, :firstname, :lastname, :birthdate, :active, :phonenumber)';
begin
insertParameters := TSqlParams.Create;
Result := False;
for i := 0 to Length(self.usersToTest) - 1 do
begin
insertParameters.Clear;
with self.usersToTest[i] do
begin
insertParameters.AddString('id', id);
insertParameters.AddString('firstname', firstName);
insertParameters.AddString('lastname', lastName);
insertParameters.AddDateTime('birthdate', birtDate);
insertParameters.AddBoolean('active', active);
insertParameters.AddString('phonenumber', phoneNumber);
end;
if not self.dbConnection.Execute(InsertStatement, insertParameters) then
begin
// TODO Write Log
Exit;
end;
end;
Result := True;
end;
procedure TDatabaseConnectionTester.FillUsersList;
var
i : Integer;
begin
for i := 0 to Length(self.usersToTest) - 1 do
begin
with self.usersToTest[i] do
begin
id := NewGuid;
firstName := format('User %d first name', [i + 1]);
lastName := format('User %d last name', [i + 1]);
birtDate := EncodeDate(1987, 10, 1 + Random(31));
active := (i mod 2) = 0;
phoneNumber := '123456789874';
end;
end;
end;
function TDatabaseConnectionTester.SelectAllUsers: TSimpleDataSet;
const
SelectStatement = 'SELECT * FROM users';
begin
Result := self.dbConnection.ExecuteSelect(SelectStatement);
end;
end.
|
{***************************
ๅ
ฌๅ
ฑๅฝๆฐ
ๆๅก็ซฏๅๅฎขๆท็ซฏ้ฝ่ฝ่ฐ็จ็ๅ
ฌๅ
ฑ็ๅฝๆฐ
mx 2014-11-28
****************************}
unit uPubFun;
interface
uses
Windows, Classes, Db, DBClient, SysUtils, Variants;
function StrToOleData(const AText: string): OleVariant; //STRING ็ๅ
ๅฎนๆตๅๅฐ OLEVARIANT ไธญ
function OleDataToStr(const AData: OleVariant): string; //็ฑ OLEVARIANT ไธญๅ ่ฝฝ STRING ็ๅ
ๅฎน
function StringEmpty(const AStr: string): Boolean; //ๅญ็ฌฆไธฒๆฏๅฆไธบ็ฉบ
function StringFormat(const AFormat: string; const AArgs: array of const): string; //ๆ ผๅผๅญ็ฌฆไธฒ
function IsNumberic(AStr: string): Boolean; //ๅญ็ฌฆไธฒๆฏๅฆๆฏๆฐๅญ
function StringToInt(const AStr: string; ADefault: Integer = 0): Integer; //ๅญ็ฌฆไธฒ่ฝฌๆขไธบๆดๆฐ
function IntToString(const AStr: Integer): string; //ๆดๆฐๆขไธบๅญ็ฌฆไธฒ่ฝฌ
function IfThen(condition: Boolean; const ATrue, AFalse: string): string;
function IfThenExt(condition: Boolean; const ATrue, AFalse: Extended): Extended;
function IfThenInt(condition: Boolean; const ATrue, AFalse: Integer): Integer;
function IfThenBool(condition: Boolean; const ATrue, AFalse: Boolean): Boolean;
implementation
function StrToOleData(const AText: string): OleVariant;
var
nSize: Integer;
pData: Pointer;
begin
nSize := Length(AText);
if nSize = 0 then
Result := null
else
begin
Result := VarArrayCreate([0, nSize - 1], varByte);
pData := VarArrayLock(Result);
try
Move(Pchar(AText)^, pData^, nSize);
finally
VarArrayUnlock(Result);
end;
end;
end;
function OleDataToStr(const AData: OleVariant): string;
var
nSize: Integer;
pData: Pointer;
begin
if AData = Null then
Result := ''
else
begin
nSize := VarArrayHighBound(AData, 1) - VarArrayLowBound(AData, 1) + 1;
SetLength(Result, nSize);
pData := VarArrayLock(AData);
try
Move(pData^, Pchar(Result)^, nSize);
finally
VarArrayUnlock(AData);
end;
end;
end;
function StringEmpty(const AStr: string): Boolean;
begin
Result := False;
if Trim(AStr) = EmptyStr then
begin
Result := True;
end;
end;
function StringFormat(const AFormat: string; const AArgs: array of const): string;
begin
Result := Format(AFormat, AArgs)
end;
function IsNumberic(AStr: string): Boolean;
var
i: integer;
begin
Result := False;
if StringEmpty(AStr) then Exit;
AStr := trim(AStr);
for i := 1 to length(AStr) do
begin
if not (AStr[i] in ['0'..'9']) then
begin
Result := false;
exit;
end;
end;
Result := True;
end;
function StringToInt(const AStr: string; ADefault: Integer = 0): Integer;
begin
Result := StrToIntDef(AStr, ADefault);
end;
function IntToString(const AStr: Integer): string;
begin
Result := IntToStr(AStr);
end;
function IfThen(condition: Boolean; const ATrue, AFalse: string): string;
begin
if condition then
Result := ATrue
else
Result := AFalse;
end;
function IfThenExt(condition: Boolean; const ATrue, AFalse: Extended): Extended;
begin
if condition then
Result := ATrue
else
Result := AFalse;
end;
function IfThenInt(condition: Boolean; const ATrue, AFalse: Integer): Integer;
begin
if condition then
Result := ATrue
else
Result := AFalse;
end;
function IfThenBool(condition: Boolean; const ATrue, AFalse: Boolean): Boolean;
begin
if condition then
Result := ATrue
else
Result := AFalse;
end;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Objects, FMX.Edit,
FMX.Menus, FMX.StdCtrls, FMX.Controls.Presentation;
type
TForm1 = class(TForm)
DistanceLabel: TLabel;
DistanceEdit: TEdit;
SpeedLabel: TLabel;
SpeedEdit: TEdit;
CalculateButton: TButton;
CarImage: TImage;
TimeLabel: TLabel;
HoursLabel: TLabel;
MinutesLabel: TLabel;
FlagImage: TImage;
MainMenu1: TMainMenu;
File1: TMenuItem;
Calculate1: TMenuItem;
N1: TMenuItem;
Exit1: TMenuItem;
Help1: TMenuItem;
About1: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure EditChange(Sender: TObject);
procedure CalculateButtonClick(Sender: TObject);
procedure Exit1Click(Sender: TObject);
procedure About1Click(Sender: TObject);
private
function GetDistance: Double;
function GetSpeed: Double;
public
property Distance: Double read GetDistance;
property Speed: Double read GetSpeed;
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
function TForm1.GetDistance: Double;
begin
Result := StrToFloatDef(DistanceEdit.Text, 0);
end;
function TForm1.GetSpeed: Double;
begin
Result := StrToFloatDef(SpeedEdit.Text, 0);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
EditChange(Self);
end;
procedure TForm1.EditChange(Sender: TObject);
begin
CalculateButton.Enabled := (Distance > 0) and (Speed > 0);
Calculate1.Enabled := CalculateButton.Enabled;
end;
procedure TForm1.CalculateButtonClick(Sender: TObject);
var
time: Double;
hours, minutes: Integer;
begin
if Speed = 0 then
Exit;
time := Distance/Speed;
hours := Trunc(time);
minutes := Round(60*(time - hours));
HoursLabel.Text := IntToStr(hours) + ' hours';
MinutesLabel.Text := IntToStr(minutes) + ' minutes';
end;
procedure TForm1.Exit1Click(Sender: TObject);
begin
Close;
end;
procedure TForm1.About1Click(Sender: TObject);
begin
ShowMessage('Driving time calculator');
end;
end.
|
unit Objekt.DHLUpdateShipmentOrderRequestAPI;
interface
uses
SysUtils, Classes, geschaeftskundenversand_api_2,
Objekt.DHLVersion, Objekt.DHLShipmentorder;
type
TDHLUpdateShipmentOrderRequestAPI = class
private
fRequest: UpdateShipmentOrderRequest;
fDHLVersion: TDHLVersion;
fDHLShipmentorder: TDHLShipmentorder;
fShipmentNumber: string;
procedure setShipmentNumber(const Value: string);
public
constructor Create;
destructor Destroy; override;
property Request: UpdateShipmentOrderRequest read fRequest write fRequest;
property Version: TDHLVersion read fDHLVersion write fDHLVersion;
property ShipmentOrder: TDHLShipmentorder read fDHLShipmentorder write fDHLShipmentOrder;
property ShipmentNumber: string read fShipmentNumber write setShipmentNumber;
end;
implementation
{ TDHLUpdateShipmentOrderRequestAPI }
constructor TDHLUpdateShipmentOrderRequestAPI.Create;
begin
fRequest := UpdateShipmentOrderRequest.Create;
fDHLVersion := TDHLVersion.Create;
Request.Version := fDHLVersion.VersionAPI;
fDHLShipmentorder := TDHLShipmentorder.Create;
Request.ShipmentOrder := fDHLShipmentorder.ShipmentorderAPI;
end;
destructor TDHLUpdateShipmentOrderRequestAPI.Destroy;
begin
FreeAndNil(fDHLVersion);
FreeAndNil(fDHLShipmentorder);
FreeAndNil(fRequest);
inherited;
end;
procedure TDHLUpdateShipmentOrderRequestAPI.setShipmentNumber(
const Value: string);
begin
fShipmentNumber := Value;
fRequest.shipmentNumber := Value;
end;
end.
|
unit MixiPage;
interface
uses
Classes, SysUtils, Crypt, superxmlparser, superobject;
type
TMixiContent = class
public
constructor Create(json: ISuperObject);
function HasUpdates(json: ISuperObject): Boolean; virtual;
function GetUpdateMessage(json: ISuperObject): String; virtual;
procedure Update(json: ISuperObject); virtual;
end;
TMixiPage = class(TMixiContent)
private
FId: Cardinal;
FName: String;
FDetails: String;
FFollowerCount: Cardinal;
public
function HasUpdates(json: ISuperObject): Boolean; override;
function GetUpdateMessage(json: ISuperObject): String; override;
procedure Update(json: ISuperObject); override;
property Id: Cardinal read FId;
property Name: String read FName;
property Details: String read FDetails;
property FollowerCount: Cardinal read FFollowerCount;
end;
TMixiPageFeed = class(TMixiContent)
private
FContentUri: String;
FTitle: String;
FBody: String;
FPCUrl: String;
FMobileUrl: String;
FSmartphoneUrl: String;
FFavoriteCount: Cardinal;
FCommentCount: Cardinal;
public
function HasUpdates(json: ISuperObject): Boolean; override;
function GetUpdateMessage(json: ISuperObject): String; override;
procedure Update(json: ISuperObject); override;
property ContentUri: String read FContentUri;
property Title: String read FTitle;
property Body: String read FBody;
property PCUrl: String read FPCUrl;
property MobileUrl: String read FMobileUrl;
property SmartphoneUrl: String read FSmartphoneUrl;
property FavoriteCoiunt: Cardinal read FFavoriteCount;
property CommentCount: Cardinal read FCommentCount;
end;
implementation
{
TMixiContent
}
// ็ถๆฟๅ
ใงoverrideใใชใ้ใใฏfalse
constructor TMixiContent.Create(json: ISuperObject);
begin
Self.Update(json);
end;
function TMixiContent.HasUpdates(json: ISuperObject): Boolean;
begin
Result := False;
end;
function TMixiContent.GetUpdateMessage(json: ISuperObject): String;
begin
Result := '';
end;
procedure TMixiContent.Update(json: ISuperObject);
begin
end;
{
TMixiPage
}
function TMixiPage.HasUpdates(json: ISuperObject): Boolean;
begin
Result := json['entry.followerCount'].AsInteger > FFollowerCount;
end;
function TMixiPage.GetUpdateMessage(json: ISuperObject): String;
begin
Result := Format(
'ใใฉใญใฏใผใ%dไบบ ๅขใใพใใ',
[json['entry.followerCount'].AsInteger - FFollowerCount]
);
end;
procedure TMixiPage.Update(json: ISuperObject);
begin
Fid := json['entry.id'].AsInteger;
FName := json['entry.displayName'].AsString;
FDetails := json['entry.details'].AsString;
FFollowerCount := json['entry.followerCount'].AsInteger;
end;
{
TMixiPageFeed
}
function TMixiPageFeed.HasUpdates(json: ISuperObject): Boolean;
begin
Result := False;
if ( json['favoriteCount'].AsInteger > FFavoriteCount ) then
Result := True;
if ( json['commentCount'].AsInteger > FCommentCount ) then
Result := True;
end;
function TMixiPageFeed.GetUpdateMessage(json: ISuperObject): String;
var favoriteDiff, commentDiff: Integer;
begin
favoriteDiff := json['favoriteCount'].AsInteger - FFavoriteCount;
commentDiff := json['commentCount'].AsInteger - FCommentCount;
Result := '';
if ( (favoriteDiff = 0) and (commentDiff = 0) ) then Exit;
if ( favoriteDiff > 0 ) then
Result := Result + Format('ใคใคใ%dไปถ ', [favoriteDiff]);
if ( commentDiff > 0 ) then
Result := Result + Format('ใณใกใณใ%dไปถ ', [commentDiff]);
Result := Result + 'ใใคใใพใใ';
end;
procedure TMixiPageFeed.Update(json: ISuperObject);
begin
FContentUri := json['contentUri'].AsString;
FTitle := json['title'].AsString;
FBody := json['body'].AsString;
FPCUrl := json['urls.pcUrl'].AsString;
FMobileUrl := json['urls.mobileUrl'].AsString;
FSmartphoneUrl := json['urls.smartphoneUrl'].AsString;
FFavoriteCount := json['favoriteCount'].AsInteger;
FCommentCount := json['commentCount'].AsInteger;
end;
end.
|
๏ปฟnamespace Environment2;
//Sample Mono console application
//by Brian Long, 2009
//App is compiled against Mono assemblies and reports various bits of environment information
//Does Win32/Unix differentiation using PlatformID check
//Does Linux/OS X differentiation using a Unix P/Invoke call
interface
uses
System.Runtime.InteropServices;
type
ConsoleApp = class
private
class method InternalRunningLinuxInsteadOfOSX: Boolean;
[DllImport('libc')]
class method uname(buf: IntPtr): Integer; external;
public
class method RunningOnUnix: Boolean;
class method RunningOnLinux: Boolean;
class method RunningOnOSX: Boolean;
class method RunningOnWindows: Boolean;
class method Main;
end;
implementation
class method ConsoleApp.Main;
begin
Console.Write('Hello World from your ');
if RunningOnLinux then
Console.Write('Linux');
if RunningOnOSX then
Console.Write('Mac OS X');
if RunningOnWindows then
Console.Write('Windows');
Console.WriteLine(' system :o)');
Console.ReadLine
end;
class method ConsoleApp.RunningOnUnix: Boolean;
begin
//.NET 1.x didn't have a Unix value in System.PlatformID enum, so Mono
//just used value 128.
//.NET 2 added Unix to PlatformID, but with value 4
//.NET 3.5 added MacOSX with a value of 6
exit Integer(Environment.OSVersion.Platform) in [4, 6, 128];
end;
class method ConsoleApp.RunningOnLinux: Boolean;
begin
exit RunningOnUnix and InternalRunningLinuxInsteadOfOSX
end;
class method ConsoleApp.RunningOnOSX: Boolean;
begin
exit RunningOnUnix and not InternalRunningLinuxInsteadOfOSX
end;
class method ConsoleApp.RunningOnWindows: Boolean;
begin
Result := not RunningOnUnix
end;
class method ConsoleApp.InternalRunningLinuxInsteadOfOSX: Boolean;
begin
//based on Mono cross-platform checking code in:
// mcs\class\Managed.Windows.Forms\System.Windows.Forms\XplatUI.cs
if not RunningOnUnix then
raise new Exception('This is not a Unix platform!');
var Buf: IntPtr := Marshal.AllocHGlobal(8192);
try
if uname(buf) <> 0 then
//assume Linux of some sort
exit True
else
//Darwin is the Unix variant that OS X is based on
exit Marshal.PtrToStringAnsi(Buf) <> 'Darwin'
finally
Marshal.FreeHGlobal(Buf);
end;
end;
end.
|
unit Form_ListProd;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, RzPanel, ExtCtrls, Grids, AdvObj, BaseGrid, AdvGrid, RzButton,
FormEx_View,Class_Prod,Uni,UniConnct, RzRadChk;
type
TFormListProd = class(TFormExView)
Grid_PROD: TAdvStringGrid;
RzStatusBar1: TRzStatusBar;
RzToolbar1: TRzToolbar;
Btnx_AddX: TRzBitBtn;
Btnx_Delt: TRzBitBtn;
Btnx_Edit: TRzBitBtn;
Btnx_Init: TRzBitBtn;
Btnx_Quit: TRzBitBtn;
Line_1: TRzSpacer;
ChkBox_ALL: TRzCheckBox;
Btnx_ORDR: TRzBitBtn;
procedure Btnx_QuitClick(Sender: TObject);
procedure Btnx_AddXClick(Sender: TObject);
procedure Btnx_DeltClick(Sender: TObject);
procedure Btnx_EditClick(Sender: TObject);
procedure Btnx_InitClick(Sender: TObject);
procedure Grid_PRODGetAlignment(Sender: TObject; ARow, ACol: Integer;
var HAlign: TAlignment; var VAlign: TVAlignment);
procedure Grid_PRODCanEditCell(Sender: TObject; ARow, ACol: Integer;
var CanEdit: Boolean);
procedure Grid_PRODDblClickCell(Sender: TObject; ARow, ACol: Integer);
procedure ChkBox_ALLClick(Sender: TObject);
procedure Btnx_ORDRClick(Sender: TObject);
private
FListProd:TStringList;
FModified:Boolean;
protected
procedure SetInitialize;override;
procedure SetCommParams;override;
procedure SetGridParams;override;
procedure SetComboItems;override;
procedure TryFreeAndNil;override;
public
procedure InitProd;
procedure AddxProd;
procedure DeltProd;
procedure EditProd;
procedure FillProd(AList:TStringList);overload;
procedure FillProd(AIdex:Integer;AProd:TProd);overload;
end;
var
FormListProd: TFormListProd;
function ViewListProd(var Modified:Boolean):Integer;
implementation
uses
Class_AppUtil,Class_KzUtils,Dialog_EditProd;
{$R *.dfm}
function ViewListProd(var Modified:Boolean):Integer;
begin
try
FormListProd:=TFormListProd.Create(nil);
Result:=FormListProd.ShowModal;
Modified:=FormListProd.FModified;
finally
FreeAndNil(FormListProd);
end;
end;
procedure TFormListProd.AddxProd;
var
ProdA:TProd;
begin
try
ProdA:=TProd.Create;
if ViewEditProd(ProdA,depemAddX)<>Mrok then
begin
FreeAndNil(ProdA);
Exit;
end;
FModified:=True;
FListProd.AddObject(ProdA.GetStrsIndex,ProdA);
with Grid_PROD do
begin
if Cells[3,RowCount-1]<>'' then
begin
AddRow;
end;
FillProd(RowCount-1,ProdA);
end;
finally
end;
end;
procedure TFormListProd.DeltProd;
var
I:Integer;
IdexA:Integer;
ListA:TStringList;
ProdA:TProd;
UniConnct:TUniConnection;
begin
with Grid_PROD do
begin
ListA:=TAppUtil.GetStrsCellChked(Grid_PROD,1);
if (ListA=nil) or (ListA.Count=0) then
begin
FreeAndNil(ListA);
Exit;
end;
if TKzUtils.WarnBox('ๆฏๅฆ็กฎๅฎๅ ้ค?')<>Mrok then Exit;
if TKzUtils.WarnBox('ๅฆๆ็ณป็ปๅทฒ็ปๅญๅจๅฏนๅบๆฐๆฎ,ๅไธๅ
่ฎธๅ ้ค.') <>Mrok then Exit;
BeginUpdate;
try
UniConnct:=UniConnctEx.GetConnection(CONST_MARK_DATA);
try
UniConnct.StartTransaction;
//-<
for I:=ListA.Count-1 downto 0 do
begin
IdexA:=StrToIntDef(ListA.Strings[I],-1);
if IdexA=-1 then Continue;
ProdA:=TProd(Objects[0,IdexA]);
if ProdA=nil then Continue;
if not ProdA.CheckExist('TBL_BILL_FL',['PROD_IDEX',ProdA.ProdIdex],UniConnct) then
begin
ProdA.DeleteDB(UniConnct);
if RowCount=2 then
begin
ClearRows(1,1);
end else
begin
RemoveRows(IdexA,1);
end;
end;
end;
//->
UniConnct.Commit;
FModified:=True;
except
on E:Exception do
begin
UniConnct.Rollback;
raise Exception.Create(E.Message);
end;
end;
finally
FreeAndNil(UniConnct);
if ListA<>nil then FreeAndNil(ListA);
end;
EndUpdate;
end;
end;
procedure TFormListProd.EditProd;
var
ProdA:TProd;
begin
//
with Grid_Prod do
begin
ProdA:=TProd(Objects[0,RealRow]);
if ProdA=nil then Exit;
if ViewEditProd(ProdA,depemEdit)=Mrok then
begin
FillProd(RealRow,ProdA);
FModified:=True;
end;
end;
end;
procedure TFormListProd.FillProd(AList: TStringList);
var
I:Integer;
ProdA:TProd;
begin
with Grid_PROD do
begin
TAppUtil.ClearGrid(Grid_PROD,1);
if (AList=nil) or (AList.Count=0) then Exit;
TAppUtil.ClearGrid(Grid_PROD,AList.Count);
BeginUpdate;
for I:=0 to AList.Count -1 do
begin
ProdA:=TProd(AList.Objects[I]);
if ProdA=nil then Continue;
FillProd(I+1,ProdA);
end;
EndUpdate;
end;
end;
procedure TFormListProd.FillProd(AIdex: Integer; AProd: TProd);
begin
//DelimitedText:='ๅบๅท,ๅพ้,็ผๅท,ๅ็งฐ,ๅ็ฑป,ไปทๆ ผ,ๅคๆณจ';
with Grid_PROD do
begin
Ints [0,AIdex]:=AIdex;
Objects[0,AIdex]:=AProd;
AddCheckBox(1,AIdex,False,False);
Cells [2,AIdex]:=AProd.ProdCode;
Cells [3,AIdex]:=AProd.ProdName;
Cells [4,AIdex]:=AProd.ProdType;
Cells [5,AIdex]:=TKzUtils.FloatToText(AProd.ProdMony);
Alignments[5,AIdex]:=taRightJustify;
Cells [6,AIdex]:=AProd.ProdMemo;
end;
end;
procedure TFormListProd.InitProd;
var
SQLA:string;
UniConnct:TUniConnection;
begin
SQLA:='SELECT * FROM TBL_PROD ORDER BY PROD_ORDR';
try
UniConnct:=UniConnctEx.GetConnection(CONST_MARK_DATA);
//-<
if FListProd=nil then
begin
FListProd:=TStringList.Create;
end;
TKzUtils.JustCleanList(FListProd);
TProd.ListDB(SQLA,UniConnct,FListProd);
//->
finally
FreeAndNil(UniConnct);
end;
FillProd(FListProd);
end;
procedure TFormListProd.Btnx_QuitClick(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TFormListProd.SetComboItems;
begin
inherited;
end;
procedure TFormListProd.SetCommParams;
var
I:Integer;
begin
inherited;
Caption:='ไบงๅไฟกๆฏ';
for I:=0 to ComponentCount-1 do
begin
if Components[I] is TRzBitBtn then
begin
TRzBitBtn(Components[I]).ThemeAware:=False;
end;
end;
end;
procedure TFormListProd.SetGridParams;
begin
inherited;
with Grid_PROD do
begin
RowCount:=2;
ColCount:=20;
DefaultColWidth:=80;
ColWidths[0]:=40;
ColWidths[1]:=40;
ShowHint:=True;
HintShowCells:=True;
HintShowSizing:=True;
Options:=Options+[goColSizing];
Options:=Options+[goRowMoving];
Font.Size:=10;
Font.Name:='ๅฎไฝ';
FixedFont.Size:=10;
FixedFont.Name:='ๅฎไฝ';
with ColumnHeaders do
begin
Clear;
Delimiter:=',';
DelimitedText:='ๅบๅท,ๅพ้,็ผๅท,ๅ็งฐ,ๅ็ฑป,ไปทๆ ผ,ๅคๆณจ';
end;
ColCount:=ColumnHeaders.Count;
ColumnSize.Stretch:=True;
end;
end;
procedure TFormListProd.SetInitialize;
begin
FListProd:=nil;
FModified:=False;
inherited;
InitProd;
end;
procedure TFormListProd.TryFreeAndNil;
begin
inherited;
if FListProd<>nil then TKzUtils.TryFreeAndNil(FListProd);
end;
procedure TFormListProd.Btnx_AddXClick(Sender: TObject);
begin
AddxProd;
end;
procedure TFormListProd.Btnx_DeltClick(Sender: TObject);
begin
DeltProd;
end;
procedure TFormListProd.Btnx_EditClick(Sender: TObject);
begin
EditProd;
end;
procedure TFormListProd.Btnx_InitClick(Sender: TObject);
begin
InitProd;
end;
procedure TFormListProd.Grid_PRODGetAlignment(Sender: TObject; ARow,
ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment);
begin
if (ARow=0) or (ACol in [0,1]) then
begin
HAlign:=taCenter;
end;
end;
procedure TFormListProd.Grid_PRODCanEditCell(Sender: TObject; ARow,
ACol: Integer; var CanEdit: Boolean);
begin
CanEdit:=ACol= 1;
end;
procedure TFormListProd.Grid_PRODDblClickCell(Sender: TObject; ARow,
ACol: Integer);
begin
EditProd;
end;
procedure TFormListProd.ChkBox_ALLClick(Sender: TObject);
begin
TAppUtil.CellCheck(Grid_PROD,TRzCheckBox(Sender).Checked);
end;
procedure TFormListProd.Btnx_ORDRClick(Sender: TObject);
var
I:Integer;
SQLA:string;
StatA:Boolean;
ProdA:TProd;
UniConnct:TUniConnection;
begin
StatA:=False;
if TKzUtils.WarnBox('ๆฏๅฆ็กฎ่ฎคไฟๅญๆๅบ?') <> Mrok then Exit;
try
UniConnct:=UniConnctEx.GetConnection(CONST_MARK_DATA);
try
UniConnct.StartTransaction;
//-<
with Grid_PROD do
begin
for I:=1 to RowCount-1 do
begin
ProdA:=TProd(Objects[0,I]);
if ProdA=nil then Continue;
ProdA.ProdOrdr:=I;
ProdA.UpdateDB(UniConnct);
end;
end;
//->
UniConnct.Commit;
StatA:=True;
except
on E:Exception do
begin
UniConnct.Rollback;
raise Exception.Create(E.Message);
end;
end;
finally
FreeAndNil(UniConnct);
end;
if StatA then
begin
TAppUtil.CellIndex(Grid_PROD,0);
end;
end;
end.
|
unit uAutoFhtMultiplier;
{$I ..\Include\IntXLib.inc}
interface
uses
Math,
SysUtils,
uMultiplierBase,
uDigitOpHelper,
uIMultiplier,
uFhtHelper,
uConstants,
uStrings,
uIntX,
uIntXLibTypes;
type
/// <summary>
/// Multiplies using FHT.
/// </summary>
TAutoFhtMultiplier = class sealed(TMultiplierBase)
private
/// <summary>
/// IIMultiplier Instance.
/// </summary>
F_classicMultiplier: IIMultiplier;
public
/// <summary>
/// Creates new <see cref="TAutoFhtMultiplier" /> instance.
/// </summary>
/// <param name="classicMultiplier">Multiplier to use if FHT is unapplicatible.</param>
constructor Create(classicMultiplier: IIMultiplier);
/// <summary>
/// Destructor.
/// </summary>
destructor Destroy(); override;
/// <summary>
/// Multiplies two big integers using pointers.
/// </summary>
/// <param name="digitsPtr1">First big integer digits.</param>
/// <param name="length1">First big integer length.</param>
/// <param name="digitsPtr2">Second big integer digits.</param>
/// <param name="length2">Second big integer length.</param>
/// <param name="digitsResPtr">Resulting big integer digits.</param>
/// <returns>Resulting big integer real length.</returns>
function Multiply(digitsPtr1: PCardinal; length1: UInt32;
digitsPtr2: PCardinal; length2: UInt32; digitsResPtr: PCardinal)
: UInt32; override;
end;
implementation
constructor TAutoFhtMultiplier.Create(classicMultiplier: IIMultiplier);
begin
inherited Create;
F_classicMultiplier := classicMultiplier;
end;
destructor TAutoFhtMultiplier.Destroy();
begin
F_classicMultiplier := Nil;
inherited Destroy;
end;
function TAutoFhtMultiplier.Multiply(digitsPtr1: PCardinal; length1: UInt32;
digitsPtr2: PCardinal; length2: UInt32; digitsResPtr: PCardinal): UInt32;
var
newLength, lowerDigitCount: UInt32;
data1, data2: TIntXLibDoubleArray;
slice1: PDouble;
validationResult: TIntXLibUInt32Array;
validationResultPtr: PCardinal;
begin
// Check length - maybe use classic multiplier instead
if ((length1 < TConstants.AutoFhtLengthLowerBound) or
(length2 < TConstants.AutoFhtLengthLowerBound) or
(length1 > TConstants.AutoFhtLengthUpperBound) or
(length2 > TConstants.AutoFhtLengthUpperBound)) then
begin
result := F_classicMultiplier.Multiply(digitsPtr1, length1, digitsPtr2,
length2, digitsResPtr);
Exit;
end;
newLength := length1 + length2;
// Do FHT for first big integer
data1 := TFhtHelper.ConvertDigitsToDouble(digitsPtr1, length1, newLength);
TFhtHelper.Fht(data1, UInt32(Length(data1)));
// Compare digits
if ((digitsPtr1 = digitsPtr2) or (TDigitOpHelper.Cmp(digitsPtr1, length1,
digitsPtr2, length2) = 0)) then
begin
// Use the same FHT for equal big integers
data2 := data1;
end
else
begin
// Do FHT over second digits
data2 := TFhtHelper.ConvertDigitsToDouble(digitsPtr2, length2, newLength);
TFhtHelper.Fht(data2, UInt32(Length(data2)));
end;
// Perform multiplication and reverse FHT
TFhtHelper.MultiplyFhtResults(data1, data2, UInt32(Length(data1)));
TFhtHelper.ReverseFht(data1, UInt32(Length(data1)));
// Convert to digits
slice1 := @data1[0];
TFhtHelper.ConvertDoubleToDigits(slice1, UInt32(Length(data1)), newLength,
digitsResPtr);
// Maybe check for validity using classic multiplication
if (TIntX.GlobalSettings.ApplyFhtValidityCheck) then
begin
lowerDigitCount :=
Min(length2, Min(length1, TConstants.FhtValidityCheckDigitCount));
// Validate result by multiplying lowerDigitCount digits using classic algorithm and comparing
SetLength(validationResult, lowerDigitCount * 2);
validationResultPtr := @validationResult[0];
F_classicMultiplier.Multiply(digitsPtr1, lowerDigitCount, digitsPtr2,
lowerDigitCount, validationResultPtr);
if (TDigitOpHelper.Cmp(validationResultPtr, lowerDigitCount, digitsResPtr,
lowerDigitCount) <> 0) then
begin
raise EFhtMultiplicationException.Create
(Format(uStrings.FhtMultiplicationError, [length1, length2],
TIntX._FS));
end;
end;
if digitsResPtr[newLength - 1] = 0 then
begin
Dec(newLength);
result := newLength;
end
else
result := newLength;
end;
end.
|
(* MP_SS 03.05.17 *)
(* Syntax Analysator (scanner) fรผr mini pascal*)
UNIT MP_SS;
INTERFACE
VAR
success: BOOLEAN;
PROCEDURE S;
IMPLEMENTATION
USES
MP_Lex;
FUNCTION SyIsNot(expectedSy: SymbolCode): BOOLEAN;
BEGIN
success := success AND (sy = expectedSy);
SyIsNot := NOT success;
END;
PROCEDURE MP; FORWARD;
PROCEDURE VarDecal; FORWARD;
PROCEDURE StatSeq; FORWARD;
PROCEDURE Stat; FORWARD;
PROCEDURE Expr; FORWARD;
PROCEDURE Term; FORWARD;
PROCEDURE Fact; FORWARD;
PROCEDURE S;
BEGIN
success := TRUE;
MP; IF NOT success OR SyIsNot(eofSy) THEN
WriteLn('Error in line ', syLnr, ' at position ', syCnr)
ELSE
WriteLn('Sucessfully parsed');
END;
PROCEDURE MP;
BEGIN
IF SyIsNot(programSy) THEN EXIT;
NewSy;
IF SyIsNot(identSy) THEN EXIT;
NewSy;
IF SyIsNot(semicolonSy) THEN EXIT;
NewSy;
IF sy = varSy THEN BEGIN
VarDecal; IF NOT success THEN EXIT;
END;
IF SyIsNot(beginSy) THEN EXIT;
NewSy;
StatSeq; IF NOT success THEN EXIT;
IF SyIsNot(endSy) THEN EXIT;
NewSy;
IF SyIsNot(periodSy) THEN EXIT;
NewSy; (* to get eofSy *)
END;
PROCEDURE VarDecal;
BEGIN
IF SyIsNot(varSy) THEN EXIT;
NewSy;
IF SyIsNot(identSy) THEN EXIT;
NewSy;
WHILE sy = commaSy DO BEGIN
NewSy;
IF SyIsNot(identSy) THEN EXIT;
NewSy;
END;
IF SyIsNot(colonSy) THEN EXIT;
NewSy;
IF SyIsNot(integerSy) THEN EXIT;
NewSy;
IF SyIsNot(semicolonSy) THEN EXIT;
NewSy;
END;
PROCEDURE StatSeq;
BEGIN
Stat; IF NOT success THEN EXIT;
WHILE sy = semicolonSy DO BEGIN
NewSy;
Stat; IF NOT success THEN EXIT;
END;
END;
PROCEDURE Stat;
BEGIN
CASE sy OF
identSy: BEGIN
NewSy;
IF SyIsNot(assignSy) THEN EXIT;
NewSy;
Expr; IF NOT success THEN EXIT;
END;
readSy: BEGIN
NewSy;
IF SyIsNot(leftParSy) THEN EXIT;
NewSy;
IF SyIsNot(identSy) THEN EXIT;
NewSy;
IF SyIsNot(rightParSy) THEN EXIT;
NewSy;
END;
writeSy: BEGIN
NewSy;
IF SyIsNot(leftParSy) THEN EXIT;
NewSy;
Expr; IF NOT success THEN EXIT;
IF SyIsNot(rightParSy) THEN EXIT;
NewSy;
END;
ELSE
(* no statement *)
END;
END;
PROCEDURE Expr;
BEGIN
Term; IF NOT success THEN EXIT;
WHILE (sy = plusSy) OR (sy = minusSy) DO BEGIN
CASE sy OF
plusSy: BEGIN
NewSy;
Term; IF NOT success THEN EXIT;
END;
minusSy: BEGIN
NewSy;
Term; IF NOT success THEN EXIT;
END;
END;
END;
END;
PROCEDURE Term;
BEGIN
Fact; IF NOT success THEN EXIT;
WHILE (sy = timesSy) OR (sy = divSy) DO BEGIN
CASE sy OF
timesSy: BEGIN
NewSy;
Fact; IF NOT success THEN EXIT;
END;
divSy: BEGIN
NewSy;
Fact; IF NOT success THEN EXIT;
END;
END;
END;
END;
PROCEDURE Fact;
BEGIN
CASE sy OF
identSy: BEGIN
NewSy;
END;
numberSy: BEGIN
NewSy;
END;
leftParSy: BEGIN
NewSy;
Expr; IF NOT success THEN EXIT;
IF sy <> rightParSy THEN BEGIN success:= FALSE; EXIT; END;
NewSy;
END;
ELSE
success := FALSE;
END;
END;
END. |
unit uNewMerchandizeGroup;
interface
uses
SysUtils, Classes, uTSBaseClass, uNewMerchandize, uNewUnit, uCompany, udmMain;
type
TNewMerchandizeGroup = class(TSBaseClass)
private
FCompany: TCompany;
FDefaultMarkUp: Double;
FID: Integer;
FKode: string;
FKodeRekening: string;
FMerchandizeUnit: TUnit;
FNama: string;
FNewMerchadize: TNewMerchadize;
FNewUnit: TUnit;
function FLoadFromDB( aSQL : String ): Boolean;
public
constructor Create(aOwner : TComponent); override;
destructor Destroy; override;
procedure ClearProperties;
function ExecuteCustomSQLTask: Boolean;
function ExecuteCustomSQLTaskPrior: Boolean;
function CustomTableName: string;
function GenerateInterbaseMetaData: Tstrings;
function ExecuteGenerateSQL: Boolean;
function GetFieldNameFor_Company: string; dynamic;
function GetFieldNameFor_DefaultMarkUp: string; dynamic;
function GetFieldNameFor_ID: string; dynamic;
function GetFieldNameFor_Kode: string; dynamic;
function GetFieldNameFor_KodeRekening: string; dynamic;
function GetFieldNameFor_MerchandizeUnit: string; dynamic;
function GetFieldNameFor_Nama: string; dynamic;
function GetFieldNameFor_NewMerchadize: string; dynamic;
function GetFieldNameFor_NewUnit: string; dynamic;
function GetGeneratorName: string;
function GetHeaderFlag: Integer;
function LoadByID(aID: Integer): Boolean;
function LoadByKode(aKode: string; aUnitID, aMerId, aMerUnitID: Integer):
Boolean;
function RemoveFromDB: Boolean;
procedure UpdateData(aCompany_ID : Integer; aDefaultMarkUp : Double; aID :
Integer; aKode : string; aKodeRekening : string;
aMerchandizeUnit_ID : Integer; aNama : string; aNewMerchadize_ID :
Integer; aNewUnit_ID : Integer);
property Company: TCompany read FCompany write FCompany;
property DefaultMarkUp: Double read FDefaultMarkUp write FDefaultMarkUp;
property ID: Integer read FID write FID;
property Kode: string read FKode write FKode;
property KodeRekening: string read FKodeRekening write FKodeRekening;
property MerchandizeUnit: TUnit read FMerchandizeUnit write
FMerchandizeUnit;
property Nama: string read FNama write FNama;
property NewMerchadize: TNewMerchadize read FNewMerchadize write
FNewMerchadize;
property NewUnit: TUnit read FNewUnit write FNewUnit;
end;
implementation
{
***************************** TNewMerchandizeGroup *****************************
}
constructor TNewMerchandizeGroup.Create(aOwner : TComponent);
begin
inherited create(aOwner);
FCompany := TCompany.Create(Self);
FMerchandizeUnit := TUnit.Create(Self);
FNewMerchadize := TNewMerchadize.Create(Self);
FNewUnit := TUnit.Create(Self);
end;
destructor TNewMerchandizeGroup.Destroy;
begin
FCompany.free;
FMerchandizeUnit.free;
FNewMerchadize.free;
FNewUnit.free;
inherited Destroy;
end;
procedure TNewMerchandizeGroup.ClearProperties;
begin
Company.ClearProperties;
DefaultMarkUp := 0;
ID := 0;
Kode := '';
KodeRekening := '';
MerchandizeUnit.ClearProperties;
Nama := '';
NewMerchadize.ClearProperties;
NewUnit.ClearProperties;
end;
function TNewMerchandizeGroup.ExecuteCustomSQLTask: Boolean;
begin
Result := True;
end;
function TNewMerchandizeGroup.ExecuteCustomSQLTaskPrior: Boolean;
begin
Result := True;
end;
function TNewMerchandizeGroup.CustomTableName: string;
begin
result := 'REF$MERCHANDISE_GRUP';
end;
function TNewMerchandizeGroup.FLoadFromDB( aSQL : String ): Boolean;
begin
Result := false;
State := csNone;
ClearProperties;
with cOpenQuery(aSQL) do
Begin
if not EOF then
begin
FCompany.LoadByID(FieldByName(GetFieldNameFor_Company).asInteger);
FNewUnit.LoadByID(FieldByName(GetFieldNameFor_NewUnit).AsString);
FDefaultMarkUp := FieldByName(GetFieldNameFor_DefaultMarkUp).asFloat;
FID := FieldByName(GetFieldNameFor_ID).asInteger;
FKode := FieldByName(GetFieldNameFor_Kode).asString;
FKodeRekening := FieldByName(GetFieldNameFor_KodeRekening).asString;
FMerchandizeUnit.LoadByID(FieldByName(GetFieldNameFor_MerchandizeUnit).AsString);
FNama := FieldByName(GetFieldNameFor_Nama).asString;
FNewMerchadize.LoadByID(FieldByName(GetFieldNameFor_NewMerchadize).AsString);
Self.State := csLoaded;
Result := True;
end;
Free;
End;
end;
function TNewMerchandizeGroup.GenerateInterbaseMetaData: Tstrings;
begin
result := TstringList.create;
result.Append( '' );
result.Append( 'Create Table TNewMerchandizeGroup ( ' );
result.Append( 'TRMSBaseClass_ID Integer not null, ' );
result.Append( 'Company_ID Integer Not Null, ' );
result.Append( 'DefaultMarkUp double precision Not Null , ' );
result.Append( 'ID Integer Not Null Unique, ' );
result.Append( 'Kode Varchar(30) Not Null Unique, ' );
result.Append( 'KodeRekening Varchar(30) Not Null , ' );
result.Append( 'MerchandizeUnit_ID Integer Not Null, ' );
result.Append( 'Nama Varchar(30) Not Null , ' );
result.Append( 'NewMerchadize_ID Integer Not Null, ' );
result.Append( 'NewUnit_ID Integer Not Null, ' );
result.Append( 'Stamp TimeStamp ' );
result.Append( ' ); ' );
end;
function TNewMerchandizeGroup.ExecuteGenerateSQL: Boolean;
var
S: string;
begin
Result := True;
if State = csNone then
Begin
raise Exception.create('Tidak bisa generate dalam Mode csNone')
end;
if not ExecuteCustomSQLTaskPrior then
begin
cRollbackTrans;
Exit;
end else begin
If FID <= 0 then
begin
FID := cGetNextID(GetFieldNameFor_ID, CustomTableName);
S := 'Insert into ' + CustomTableName + ' ( ' + GetFieldNameFor_Company + ', ' + GetFieldNameFor_DefaultMarkUp + ', ' + GetFieldNameFor_ID + ', ' + GetFieldNameFor_Kode + ', ' + GetFieldNameFor_KodeRekening + ', ' + GetFieldNameFor_MerchandizeUnit + ', ' + GetFieldNameFor_Nama + ', ' + GetFieldNameFor_NewMerchadize + ', ' + GetFieldNameFor_NewUnit + ') values ('
+ InttoStr( FCompany.ID) + ', '
+ FormatFloat('0.00', FDefaultMarkUp) + ', '
+ IntToStr( FID) + ', '
+ QuotedStr(FKode ) + ','
+ QuotedStr(FKodeRekening ) + ','
+ QuotedStr( FMerchandizeUnit.ID) + ', '
+ QuotedStr(FNama ) + ','
+ QuotedStr( FNewMerchadize.ID) + ', '
+ QuotedStr( FNewUnit.ID) + ');'
end else
begin
S := 'Update ' + CustomTableName + ' set ' + GetFieldNameFor_Company + ' = ' + IntToStr( FCompany.ID)
+ ' , ' + GetFieldNameFor_DefaultMarkUp + ' = ' + FormatFloat('0.00', FDefaultMarkUp)
+ ' , ' + GetFieldNameFor_Kode + ' = ' + QuotedStr( FKode )
+ ' , ' + GetFieldNameFor_KodeRekening + ' = ' + QuotedStr( FKodeRekening )
+ ' , ' + GetFieldNameFor_MerchandizeUnit + ' = ' + QuotedStr( FMerchandizeUnit.ID)
+ ' , ' + GetFieldNameFor_Nama + ' = ' + QuotedStr( FNama )
+ ' , ' + GetFieldNameFor_NewMerchadize + ' = ' + QuotedStr( FNewMerchadize.ID)
+ ' where ' + GetFieldNameFor_NewUnit + ' = ' + QuotedStr( FNewUnit.ID)
+ ' and ' + GetFieldNameFor_ID + ' = ' + IntToStr(FID) + ';';
end;
if cExecSQL(S, dbtPOS, False) then
begin
cRollbackTrans;
Exit;
end else
Result := ExecuteCustomSQLTask;
end;
end;
function TNewMerchandizeGroup.GetFieldNameFor_Company: string;
begin
Result := 'MERCHANGRUP_COMP_ID';// <<-- Rubah string ini untuk mapping
end;
function TNewMerchandizeGroup.GetFieldNameFor_DefaultMarkUp: string;
begin
Result := 'MERCHANGRUP_DEF_MARK_UP';// <<-- Rubah string ini untuk mapping
end;
function TNewMerchandizeGroup.GetFieldNameFor_ID: string;
begin
Result := 'MERCHANGRUP_ID';// <<-- Rubah string ini untuk mapping
end;
function TNewMerchandizeGroup.GetFieldNameFor_Kode: string;
begin
Result := 'MERCHANGRUP_CODE';// <<-- Rubah string ini untuk mapping
end;
function TNewMerchandizeGroup.GetFieldNameFor_KodeRekening: string;
begin
Result := 'MERCHANGRUP_REK_CODE';// <<-- Rubah string ini untuk mapping
end;
function TNewMerchandizeGroup.GetFieldNameFor_MerchandizeUnit: string;
begin
Result := 'MERCHANGRUP_MERCHAN_UNT_ID';// <<-- Rubah string ini untuk mapping
end;
function TNewMerchandizeGroup.GetFieldNameFor_Nama: string;
begin
Result := 'MERCHANGRUP_NAME';// <<-- Rubah string ini untuk mapping
end;
function TNewMerchandizeGroup.GetFieldNameFor_NewMerchadize: string;
begin
Result := 'MERCHANGRUP_MERCHAN_ID';// <<-- Rubah string ini untuk mapping
end;
function TNewMerchandizeGroup.GetFieldNameFor_NewUnit: string;
begin
Result := 'MERCHANGRUP_UNT_ID';// <<-- Rubah string ini untuk mapping
end;
function TNewMerchandizeGroup.GetGeneratorName: string;
begin
Result := 'gen_ref$merchandise_grup_id';
end;
function TNewMerchandizeGroup.GetHeaderFlag: Integer;
begin
result := 1498;
end;
function TNewMerchandizeGroup.LoadByID(aID: Integer): Boolean;
begin
result := FloadFromDB('Select * from ' + CustomTableName
+ ' Where ' + GetFieldNameFor_ID + ' = ' + IntToStr(aID)
);
end;
function TNewMerchandizeGroup.LoadByKode(aKode: string; aUnitID, aMerId,
aMerUnitID: Integer): Boolean;
begin
result := FloadFromDB('Select * from ' + CustomTableName
+ ' Where ' + GetFieldNameFor_Kode + ' = ' + QuotedStr(aKode)
+ ' and ' + GetFieldNameFor_NewUnit + ' = ' + IntToStr(aUnitID)
+ ' and ' + GetFieldNameFor_NewMerchadize + ' = ' + IntToStr(aMerId)
+ ' and ' + GetFieldNameFor_MerchandizeUnit + ' = ' + IntToStr(aMerUnitID)
);
end;
function TNewMerchandizeGroup.RemoveFromDB: Boolean;
var
sSQL: String;
begin
Result := False;
sSQL := 'delete from ' + CustomTableName
+ ' where ' + GetFieldNameFor_ID + ' = ' + IntToStr(ID)
+ ' and ' + GetFieldNameFor_NewUnit + ' = ' + QuotedStr(NewUnit.ID) ;
if not cExecSQL(sSQL, dbtPOS, False) then
begin
cRollbackTrans;
Exit;
end else
Result := True;
end;
procedure TNewMerchandizeGroup.UpdateData(aCompany_ID : Integer; aDefaultMarkUp
: Double; aID : Integer; aKode : string; aKodeRekening : string;
aMerchandizeUnit_ID : Integer; aNama : string; aNewMerchadize_ID :
Integer; aNewUnit_ID : Integer);
begin
FCompany.LoadByID(aCompany_ID);
FDefaultMarkUp := aDefaultMarkUp;
FID := aID;
FKode := trim(aKode);
FKodeRekening := trim(aKodeRekening);
FMerchandizeUnit.LoadByID(IntToStr(aMerchandizeUnit_ID));
FNama := trim(aNama);
FNewMerchadize.LoadByID(IntToStr(aNewMerchadize_ID));
FNewUnit.LoadByID(IntToStr(aNewUnit_ID));
State := csCreated;
end;
end.
|
unit VH_Global;
interface
Uses Windows,Graphics,Palette,OpenGL15,VH_Types,Math3d,Voxel,TimerUnit,HVA;//,OpenGLWrapper;
Const
ENGINE_TITLE = 'Voxel HVA Engine';
ENGINE_VER = '1.52';
ENGINE_BY = 'Stucuk and Banshee';
RemapColourMap : array [0..8] of TVector3b =
(
( //DarkRed
R : 244;
G : 3;
B : 3;
),
( //DarkBlue
R : 9;
G : 32;
B : 140;
),
( //DarkGreen
R : 13;
G : 136;
B : 16;
),
( //White
R : 200;
G : 200;
B : 200;
),
( //Orange
R : 146;
G : 92;
B : 3;
),
( //Purple
R : 137;
G : 12;
B : 134;
),
( //Magenta
R : 104;
G : 43;
B : 73;
),
( //Gold
R : 149;
G : 119;
B : 0;
),
( //DarkSky
R : 13;
G : 102;
B : 136;
)
);
// View list is made from the list below. Easyer to make sure all views are the same in each app.
VH_Default_View = 10; // Game TS/RA2
VH_Views_No = 11;
VH_Views : array [0..VH_Views_No-1] of TVH_Views =
(
(
Name : 'Front';
XRot : -90;
YRot : -90;
Section : 0;
),
(
Name : 'Back';
XRot : -90;
YRot : 90;
Section : 0;
),
(
Name : 'Left';
XRot : -90;
YRot : -180;
Section : 1;
),
(
Name : 'Right';
XRot : -90;
YRot : 0;
Section : 1;
),
(
Name : 'Bottom';
XRot : 180;
YRot : 180;
Section : 2;
),
(
Name : 'Top';
XRot : 0;
YRot : 180;
Section : 2;
),
(
Name : 'Cameo1';
XRot : 287;
YRot : 225;
Section : 3;
),
(
Name : 'Cameo2';
XRot : 287;
YRot : 315;
Section : 3;
),
(
Name : 'Cameo3';
XRot : 287;
YRot : 255;
Section : 3;
),
(
Name : 'Cameo4';
XRot : 287;
YRot : 285;
Section : 3;
),
(
Name : 'Game TS/RA2';
XRot : 305;
YRot : 46;
Depth : -121.333297729492;
Section : 4;
NotUnitRot : True;
)
);
light0_position:TGLArrayf4=( 5.0, 0.0, 10.0, 0.0);
ambient: TGLArrayf4=( 0.5, 0.5, 0.5, 1);
Light0_Light: TGLArrayf4=( 1, 1, 1, 1);
Light0_Spec: TGLArrayf4=( 1, 0.5, 0, 0);
C_ONE_LEPTON = 43/256;
C_ONE_LEPTON_GE = 45/256;
//Games
C_GAME_TS = 0;
C_GAME_RA2 = C_GAME_TS + 1;
C_GAME_MAX = C_GAME_RA2;
C_DEFAULT_BULLET_SIZE = 5;
var
h_DC : HDC;
h_rc : HGLRC;
h_Wnd : HWND;
gTimer : TTimerSystem;
VoxelFile,VoxelTurret,VoxelBarrel : TVoxel;
CurrentVoxel,CurrentSectionVoxel : PVoxel;
VXLPalette: TPalette;
DefaultPalette,VHLocation,VXLFilename : String;
VoxelBoxes,VoxelBoxesT,VoxelBoxesB : TVoxelBoxs;
VoxelBox_No,VoxelBox_NoT,VoxelBox_NoB,
base, VoxelsUsed,CurrentVoxelSection,CurrentSection,
Xcoord,Xcoord2,Ycoord,Ycoord2,Zcoord,MouseButton,
SCREEN_WIDTH,SCREEN_HEIGHT,GroundTex_No,
Default_View,Axis : Integer;
BGColor,FontColor,RemapColour,UnitShift,
TurretOffset,CameraCenter : TVector3f;
// Bullet
PrimaryFireFLH, BulletPosition, BulletSpeed : TVector3f;
ShowBullet : boolean;
VoxelOpen,VoxelOpenT,VoxelOpenB,
HVAOpen,HVAOpenT,HVAOpenB,
ColoursOnly,TileGround,Ground_Tex_Draw,
XRotB,YRotB,oglloaded,DebugMode,
ShowVoxelCount,VVSLoading,DrawSky,
DrawCenter,VXLChanged : Boolean;
DrawSectionCenter: Boolean = False;
DrawPrimaryFireFLH: Boolean = False;
DrawVHWorld : Boolean = True;
Highlight : Boolean = False;
DrawAllOfVoxel : Boolean = True;
DrawTurret : Boolean = True;
DrawBarrel : Boolean = True;
CullFace : Boolean = True;
GroundTex : TGTI;
GroundTex_Textures : array of TGT;
SkyTexList : array of TSKYTex;
SkyTexList_No : integer;
SkyList,SkyTex : integer;
SkyPos,SkySize : TVector3f;
CamMov : Single = 0.33333333333;
SpectrumMode : ESpectrumMode;
xRot,yRot,xRot2,yRot2,Depth,FOV,DEPTH_OF_VIEW,
Size,DefaultDepth,UnitRot,LowestZ,GroundHeightOffset,
TexShiftX,TexShiftY,GSize : Single;
HVAFile,HVABarrel,HVATurret : THVA;
HVAFrame : integer = 0;
HVAFrameB : integer = 0;
HVAFrameT : integer = 0;
HVACurrentFrame : integer = 0;
HVAScale : single = 1/12;
CurrentHVA : PHVA;
VXLTurretRotation : TVector3f;
ScreenShot : TScreenShot;
VHControlType : TControlType;
LightAmb,LightDif : TVector4f;
LightGround : Boolean = False;
RebuildLists : Boolean = False;
UnitCount : Single = 1;
UnitSpace : Single = 15;
FTexture : Cardinal = 0;
FUpdateWorld : Boolean = False;
LeptonSize : single = C_ONE_LEPTON;
BulletSize : single = C_DEFAULT_BULLET_SIZE;
//var
//OGLW : TOpenGLWrapper;
Function TColorToTVector3f(Color : TColor) : TVector3f;
Function TVector3fToTColor(Vector3f : TVector3f) : TColor;
Function TColorToTVector4f(Color : TColor) : TVector4f;
Function TVector4fToTColor(Vector : TVector4f) : TColor;
Function TVector3bToTVector3f(Vector3b : TVector3b) : TVector3f;
function CleanAngle(Angle : single) : single;
implementation
Function TColorToTVector3f(Color : TColor) : TVector3f;
begin
Result.X := GetRValue(Color) / 255;
Result.Y := GetGValue(Color) / 255;
Result.Z := GetBValue(Color) / 255;
end;
Function TVector3fToTColor(Vector3f : TVector3f) : TColor;
begin
Result := RGB(trunc(Vector3f.X*255),trunc(Vector3f.Y*255),trunc(Vector3f.Z*255));
end;
Function TColorToTVector4f(Color : TColor) : TVector4f;
begin
Result.X := GetRValue(Color) / 255;
Result.Y := GetGValue(Color) / 255;
Result.Z := GetBValue(Color) / 255;
Result.W := 1;
end;
Function TVector4fToTColor(Vector : TVector4f) : TColor;
begin
Result := RGB(trunc(Vector.X*255),trunc(Vector.Y*255),trunc(Vector.Z*255));
end;
Function TVector3bToTVector3f(Vector3b : TVector3b) : TVector3f;
begin
Result.X := Vector3b.R/255;
Result.Y := Vector3b.G/255;
Result.Z := Vector3b.B/255;
end;
function CleanAngle(Angle : single) : single;
begin
Result := Angle;
If result < 0 then
Result := 360 + Result;
If result > 360 then
Result := Result - 360;
end;
begin
BGColor := TColorToTVector3f(RGB(40,111,162));
FontColor := TColorToTVector3f(RGB(255,255,255));
RemapColour := TVector3bToTVector3f(RemapColourMap[0]);
xRot :=-90;
yRot :=-90;
Depth :=-60;
FOV := 45;
DEPTH_OF_VIEW := 4000;
Size := 0.1;
CameraCenter := SetVector(0, 0, 0);
TurretOffset := SetVector(0, 0, 0);
SpectrumMode := ModeColours;
Default_View := VH_Default_View;
ScreenShot._Type := 0;
ScreenShot.CompressionRate := 1;
ScreenShot.Width := -1;
ScreenShot.Height := -1;
ScreenShot.Frames := 90;
ScreenShot.FrameAdder := 4;
VHControlType := CTview;
LightAmb := SetVector4f(134/255, 134/255, 134/255, 1.0);
LightDif := SetVector4f(172/255, 172/255, 172/255, 1.0);
end.
|
// This demo is part of the GLSCene project
// Advanced GLBlur demo
// by Marcus Oblak
unit Unit1;
interface
uses
SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, GLLCLViewer, GLScene, GLObjects, GLHUDObjects,
GLGeomObjects, GLCadencer, ExtCtrls, GLBlur, GLTexture, ComCtrls,
StdCtrls, GLCrossPlatform, GLMaterial, GLCoordinates, GLBaseClasses;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
GLCadencer1: TGLCadencer;
GLCamera1: TGLCamera;
GLCube1: TGLCube;
GLLightSource1: TGLLightSource;
GLDummyCube1: TGLDummyCube;
GLAnnulus1: TGLAnnulus;
GLBlur1: TGLBlur;
Timer1: TTimer;
GLMaterialLibrary1: TGLMaterialLibrary;
Panel1: TPanel;
edtAdvancedBlurAmp: TEdit;
Label1: TLabel;
Label2: TLabel;
edtAdvancedBlurPasses: TEdit;
trkAdvancedBlurHiClamp: TTrackBar;
Label3: TLabel;
Label4: TLabel;
trkAdvancedBlurLoClamp: TTrackBar;
Label5: TLabel;
Bevel1: TBevel;
GLSphere1: TGLSphere;
TorusImpostor: TGLTorus;
Memo1: TMemo;
GLTorus2: TGLTorus;
procedure Timer1Timer(Sender: TObject);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: integer);
procedure FormCreate(Sender: TObject);
procedure GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: double);
procedure edtAdvancedBlurAmpChange(Sender: TObject);
procedure trkAdvancedBlurHiClampChange(Sender: TObject);
procedure trkAdvancedBlurLoClampChange(Sender: TObject);
procedure edtAdvancedBlurPassesChange(Sender: TObject);
procedure GLBlur1BeforeTargetRender(Sender: TObject);
procedure GLBlur1AfterTargetRender(Sender: TObject);
private
{ Private declarations }
mx, my: integer;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
uses
GLUtils;
procedure TForm1.FormCreate(Sender: TObject);
begin
SetGLSceneMediaDir();
// Blur GLDummyCube1and it's children
GLBlur1.TargetObject := GLDummyCube1;
// point to GLDummyCube1
GLCamera1.TargetObject := GLDummyCube1;
// load materials
with GLMaterialLibrary1 do
begin
Materials[0].Material.Texture.Image.LoadFromFile('beigemarble.jpg');
Materials[1].Material.Texture.Image.LoadFromFile('moon.bmp');
end;
end;
procedure TForm1.GLBlur1BeforeTargetRender(Sender: TObject);
begin
TorusImpostor.Visible := True; // GLBlur1 must render the Torusimpostor
end;
procedure TForm1.GLBlur1AfterTargetRender(Sender: TObject);
begin
TorusImpostor.Visible := False; // GLSCeneViewer1 must NOT render the Torusimpostor
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime, newTime: double);
begin
GLSceneViewer1.Invalidate;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: integer);
begin
if (ssRight in Shift) and (y > 10) then
GLCamera1.AdjustDistanceToTarget(my / y);
if ssLeft in Shift then
GLCamera1.MoveAroundTarget(my - y, mx - x);
mx := x;
my := y;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
Caption := GLSceneViewer1.FramesPerSecondText(0);
GLSceneViewer1.ResetPerformanceMonitor;
end;
procedure TForm1.trkAdvancedBlurHiClampChange(Sender: TObject);
begin
GLBlur1.AdvancedBlurHiClamp := trkAdvancedBlurHiClamp.Position;
end;
procedure TForm1.trkAdvancedBlurLoClampChange(Sender: TObject);
begin
GLBlur1.AdvancedBlurLowClamp := trkAdvancedBlurLoClamp.Position;
end;
procedure TForm1.edtAdvancedBlurAmpChange(Sender: TObject);
begin
GLBlur1.AdvancedBlurAmp := StrToFloat(edtAdvancedBlurAmp.Text);
end;
procedure TForm1.edtAdvancedBlurPassesChange(Sender: TObject);
begin
GLBlur1.AdvancedBlurPasses := StrToInt(edtAdvancedBlurPasses.Text);
end;
end.
|
unit Sorter;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
TSorterSortAction=(off,asc,desc);
TSorterDelDuplicates=(skip,DelAllDups);
TSorterOptions = record
SortAction: TSorterSortAction {enum: off/ asc/ desc};
DelDuplicates: TSorterDelDuplicates {enum: skip, DelAllDups};
end;
function Sorter(L: TStringList; Opts: TSorterOptions): boolean;
implementation
function Sorter(L: TStringList; Opts: TSorterOptions): boolean;
begin
Result:=true;
end;
end.
|
unit UConfigJson;
interface
uses
UConfigBase, Ils.Kafka, JsonDataObjects, System.SysUtils, SyncObjs, Windows;
type
TConfigJson = class(TConfigBase)
private
FConfigFileName: string;
protected
FCriticalSection: TCriticalSection;
FJson: TJsonObject;
function Reload: Boolean; override;
function GetModifiedDateTime: TDateTime; override;
function GetModifiedCount: Integer; override;
function ReadJSONValue(const AValuePath: string): TJsonDataValueHelper;
procedure Log(AMessage: string); virtual;
function GetJson: TJsonObject;
public
constructor Create(
const AConfigFileName: string;
const AConfigChangeCB: TConfigEvent;
const ALogCB: TLogFunc = nil;
const ACheckInterval: Integer = 1000); reintroduce; virtual;
destructor Destroy; override;
property Json: TJsonObject read GetJson;
function ReadInteger(const AValuePath: string; const ADef: Integer = 0): Integer;
function ReadLong(const AValuePath: string; const ADef: Int64 = 0): Int64;
function ReadFloat(const AValuePath: string; const ADef: Double = 0): Double;
function ReadDateTime(const AValuePath: string; const ADef: TDateTime = 0): TDateTime;
function ReadString(const AValuePath: string; const ADef: string = ''): string;
function IsArray(const AValuePath: string): Boolean;
function ArrayCount(const AValuePath: string): Integer;
end;
implementation
function GetFileModifiedDateTime(AFileName: string): TDateTime;
var
fad: TWin32FileAttributeData;
ModifiedTime: TFileTime;
SystemTime: TSystemTime;
begin
if not FileExists(AFileName) then
Exit(0);
if not GetFileAttributesEx(PChar(AFileName), GetFileExInfoStandard, @fad) then
RaiseLastOSError;
//fad.ftCreationTime, fad.ftLastAccessTime
FileTimeToLocalFileTime(fad.ftLastWriteTime, ModifiedTime);
FileTimeToSystemTime(ModifiedTime, SystemTime);
Result := SystemTimeToDateTime(SystemTime);
end;
{ TConfigJson }
function TConfigJson.ArrayCount(const AValuePath: string): Integer;
var
JSONValue: TJsonDataValueHelper;
begin
JSONValue := ReadJSONValue(AValuePath);
if not JSONValue.IsNull and (JSONValue.Typ = jdtArray) then
Result := JSONValue.Count
else
Result := -1;
end;
constructor TConfigJson.Create(const AConfigFileName: string; const AConfigChangeCB: TConfigEvent; const ALogCB: TLogFunc; const ACheckInterval: Integer);
begin
FCriticalSection := TCriticalSection.Create;
FJson := TJsonObject.Create;
FConfigFileName := AConfigFileName;
inherited Create(AConfigChangeCB, ALogCB, ACheckInterval);
Load;
end;
destructor TConfigJson.Destroy;
begin
FreeAndNil(FJson);
FreeAndNil(FCriticalSection);
inherited;
end;
function TConfigJson.GetJson: TJsonObject;
begin
FCriticalSection.Enter;
FCriticalSection.Leave;
Result := FJson;
end;
function TConfigJson.GetModifiedDateTime: TDateTime;
begin
Result := GetFileModifiedDateTime(FConfigFileName);
end;
function TConfigJson.GetModifiedCount: Integer;
begin
Result := 0;
end;
function TConfigJson.IsArray(const AValuePath: string): Boolean;
var
JSONValue: TJsonDataValueHelper;
begin
JSONValue := ReadJSONValue(AValuePath);
Result := not JSONValue.IsNull and (JSONValue.Typ = jdtArray);
end;
procedure TConfigJson.Log(AMessage: string);
begin
if Assigned(FLogCB) then
FLogCB(AMessage);
end;
function TConfigJson.ReadDateTime(const AValuePath: string; const ADef: TDateTime = 0): TDateTime;
var
JSONValue: TJsonDataValueHelper;
begin
Result := ADef;
JSONValue := ReadJSONValue(AValuePath);
if not JSONValue.IsNull and (JSONValue.Typ = jdtDateTime) then
Result := JSONValue.DateTimeValue
else
Log('ะัะธะฑะบะฐ ััะตะฝะธั ะดะฐัั/ะฒัะตะผะตะฝะธ');
end;
function TConfigJson.ReadFloat(const AValuePath: string; const ADef: Double = 0): Double;
var
JSONValue: TJsonDataValueHelper;
begin
Result := ADef;
JSONValue := ReadJSONValue(AValuePath);
if not JSONValue.IsNull and ((JSONValue.Typ = jdtFloat) or (JSONValue.Typ = jdtInt) or (JSONValue.Typ = jdtLong)) then
Result := JSONValue.FloatValue
else
Log('ะัะธะฑะบะฐ ััะตะฝะธั ัะธัะปะฐ ั ะฟะปะฐะฒะฐััะตะน ะทะฐะฟััะพะน');
end;
function TConfigJson.ReadInteger(const AValuePath: string; const ADef: Integer = 0): Integer;
var
JSONValue: TJsonDataValueHelper;
begin
Result := ADef;
JSONValue := ReadJSONValue(AValuePath);
if not JSONValue.IsNull and (JSONValue.Typ = jdtInt) then
Result := JSONValue.IntValue
else
Log('ะัะธะฑะบะฐ ััะตะฝะธั ัะตะปะพะณะพ ัะธัะปะฐ');
end;
function TConfigJson.ReadJSONValue(const AValuePath: string): TJsonDataValueHelper;
begin
try
Result := FJson.Path[AValuePath];
except
on e: Exception do
Log(e.Message);
end;
end;
function TConfigJson.ReadLong(const AValuePath: string; const ADef: Int64 = 0): Int64;
var
JSONValue: TJsonDataValueHelper;
begin
Result := ADef;
JSONValue := ReadJSONValue(AValuePath);
if not JSONValue.IsNull and ((JSONValue.Typ = jdtInt) or (JSONValue.Typ = jdtLong)) then
Result := JSONValue.LongValue
else
Log('ะัะธะฑะบะฐ ััะตะฝะธั ะดะปะธะฝะฝะพะณะพ ัะตะปะพะณะพ');
end;
function TConfigJson.ReadString(const AValuePath: string; const ADef: string = ''): string;
var
JSONValue: TJsonDataValueHelper;
begin
Result := ADef;
JSONValue := ReadJSONValue(AValuePath);
if not JSONValue.IsNull and (JSONValue.Typ <> jdtArray) then
Result := JSONValue.Value
else
Log('ะัะธะฑะบะฐ ััะตะฝะธั ัััะพะบะพะฒะพะณะพ ะฟะฐัะฐะผะตััะฐ');
end;
function TConfigJson.Reload: Boolean;
begin
Result := True;
FCriticalSection.Enter;
try
try
FJson.LoadFromFile(FConfigFileName);
Log('Config loaded.');
except
Result := False;
end;
finally
FCriticalSection.Leave;
end;
end;
end.
|
unit UpProlongBonusesMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, cxTextEdit,
cxMaskEdit, cxDropDownEdit, cxCalendar, cxLabel, uFControl,
uLabeledFControl, uSpravControl, cxControls, cxContainer, cxEdit,
cxCheckBox, uCommonSp, Ibase, GlobalSPR, pFibStoredProc,
pFibDatabase;
type
TfrmProlongBonuses = class(TForm)
CheckDepartmentValue: TcxCheckBox;
DepartmentValue: TqFSpravControl;
CheckDepartmentWithChild: TcxCheckBox;
CheckRaiseValue: TcxCheckBox;
ExistRateValue: TqFSpravControl;
lblNewDateBeg: TcxLabel;
NewDateBeg: TcxDateEdit;
lblNewDateEnd: TcxLabel;
NewDateEnd: TcxDateEdit;
btnOk: TcxButton;
btnCancel: TcxButton;
lblDateFilter: TcxLabel;
DateFilter: TcxDateEdit;
procedure btnOkClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure DepartmentValueOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
procedure ExistRateValueOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
procedure CheckDepartmentValuePropertiesChange(Sender: TObject);
procedure CheckRaiseValuePropertiesChange(Sender: TObject);
private
{ Private declarations }
db_handle: Tisc_db_handle;
id_order: Int64;
public
{ Public declarations }
constructor Create(AOwner: TComponent; DbHandle: TISC_DB_HANDLE; idorder: Int64); reintroduce;
end;
var
frmProlongBonuses: TfrmProlongBonuses;
implementation
uses DateUtils;
{$R *.dfm}
procedure TfrmProlongBonuses.btnOkClick(Sender: TObject);
var
Sproc: TpFibStoredProc;
begin
if DepartmentValue.Value = NULL then
begin
ShowMessage('ะะต ะฒะฒะตะดะตะฝะพ ะฟัะดัะพะทะดัะป!');
Exit;
end;
if ExistRateValue.Value = NULL then
begin
ShowMessage('ะะต ะฒะฒะตะดะตะฝะพ ะฝะฐะดะฑะฐะฒะบั ะดะปั ะทะฐะผัะฝะธ ะฑัะดะถะตั!');
Exit;
end;
ShowMessage('ะะพะฟะตัะตะดะถะตะฝะฝั! ะะฐะฝะฐ ะพะฟะตัะฐััั ะฟัะฐััั ะปะธัะต ะดะปั ะฝะฐะดะฑะฐะฒะพะบ ะท ัะธะฟะพะผ "ะฑะตะท ะฟัะธะฒ''''ัะทะบะธ ะดะพ ะฟะพัะฐะดะพะฒะพะณะพ ะพะบะปะฐะดั". ' +
'ะ ะฟะธัะฐะฝะฝัะผะธ ะทะฒะตััะฐัะธัั ะดะพ ัะพะทัะพะฑะฝะธะบัะฒ ัะธ ะฐะดะผัะฝััััะฐัะพััะฒ.');
Sproc := TpFibStoredProc.Create(self);
Sproc.Database := TpFibDatabase.Create(self);
Sproc.Database.SQLDialect := 3;
Sproc.Database.Handle := db_handle;
Sproc.Transaction := TpFIBTransaction.Create(self);
Sproc.Transaction.DefaultDatabase := Sproc.Database;
Sproc.Database.DefaultTransaction := Sproc.Transaction;
Sproc.Database.DefaultUpdateTransaction := Sproc.Transaction;
Sproc.Transaction.StartTransaction;
try
Sproc.StoredProcName := 'UP_PROLONG_BONUSES';
Sproc.Prepare;
Sproc.ParamByName('ID_DEPARTMENT').Value := DepartmentValue.Value;
if CheckDepartmentWithChild.Checked then
Sproc.ParamByName('WITH_CHILD').Value := 1
else
Sproc.ParamByName('WITH_CHILD').Value := 0;
Sproc.ParamByName('ID_RAISE').Value := ExistRateValue.Value;
Sproc.ParamByName('FILTER_DATE').Value := DateFilter.EditValue;
Sproc.ParamByName('NEW_DATE_BEG').Value := NewDateBeg.EditValue;
Sproc.ParamByName('NEW_DATE_END').Value := NewDateEnd.EditValue;
Sproc.ParamByName('ID_ORDER').AsInt64 := Id_Order;
Sproc.ExecProc;
Sproc.Transaction.Commit;
except on E: Exception do
begin
ShowMessage('ะฃะฒะฐะณะฐ! ะัะด ัะฐั ัะพัะผัะฒะฐะฝะฝั ะฟัะฝะบััะฒ ะฒะธะฝะธะบะปะฐ ะฟะพะผะธะปะบะฐ: ' + E.Message);
Sproc.Transaction.Rollback;
end;
end;
Sproc.Free;
ShowMessage('ะัะฝะบัะธ ะฝะฐะบะฐะทั ััะฟััะฝะพ ััะพัะผะพะฒะฐะฝะพ!');
ModalResult := mrYes;
end;
procedure TfrmProlongBonuses.btnCancelClick(Sender: TObject);
begin
ModalResult := mrNo;
end;
procedure TfrmProlongBonuses.DepartmentValueOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: String);
var
sp: TSprav;
begin
sp := GetSprav('SpDepartment');
if sp <> nil then
begin
with sp.Input do
begin
Append;
FieldValues['DBHandle'] := Integer(db_Handle);
FieldValues['Select'] := 1;
FieldValues['ShowStyle'] := 0;
Post;
end;
sp.Show;
if (sp.Output <> nil) and not sp.Output.IsEmpty then
begin
Value := sp.Output['ID_DEPARTMENT'];
DisplayText := sp.Output['NAME_FULL'];
end;
end;
end;
procedure TfrmProlongBonuses.ExistRateValueOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: String);
var
sp: TSprav;
begin
sp := GetSprav('Asup/SpRaise');
if sp <> nil then
begin
with sp.Input do
begin
Append;
FieldValues['DBHandle'] := Integer(Db_Handle);
FieldValues['Select'] := 1;
FieldValues['Actual_Date'] := date;
FieldValues['ShowStyle'] := 0;
Post;
end;
sp.Show;
if (sp.Output <> nil) and not sp.Output.IsEmpty then
begin
Value := sp.Output['ID_RAISE'];
DisplayText := sp.Output['NAME'];
end;
end;
end;
constructor TfrmProlongBonuses.Create(AOwner: TComponent;
DbHandle: TISC_DB_HANDLE; idorder: Int64);
begin
inherited Create(AOwner);
db_handle := DbHandle;
id_order := idorder;
NewDateBeg.EditValue := EncodeDate(YearOf(Date), Monthof(Date), 1);
NewDateEnd.EditValue := IncMonth(NewDateBeg.EditValue) - 1;
end;
procedure TfrmProlongBonuses.CheckDepartmentValuePropertiesChange(
Sender: TObject);
var
Res: Variant;
s: string;
begin
if CheckDepartmentValue.Checked then
begin
DepartmentValueOpenSprav(DepartmentValue, Res, s);
DepartmentValue.Value := Res;
DepartmentValue.DisplayText := s;
end;
end;
procedure TfrmProlongBonuses.CheckRaiseValuePropertiesChange(
Sender: TObject);
var
Res: Variant;
s: string;
begin
if CheckRaiseValue.Checked then
begin
ExistRateValueOpenSprav(ExistRateValue, Res, s);
ExistRateValue.Value := Res;
ExistRateValue.DisplayText := s;
end;
end;
end.
|
unit StrategyControl;
interface
uses
CarControl, WorldControl, GameControl, MoveControl;
type
TStrategy = class
public
procedure Move(const AMe: TCar; const AWorld: TWorld; const AGame: TGame; const AMove: TMove); virtual; abstract;
end;
implementation
end.
|
{Program example;
var x,y:integer;
function gcd(a,b:integer):integer;
begin
if b=0 then gcd:=a
else gcd:=gcd(b,a mod b);
end;
begin
read(x,y);
write(gcd(x,y));
end.}
Program example;
const c1=0.0;
var x,y,tmp:integer;
function gcd(a,b:integer):integer;
begin
if b=0 then gcd:=a
else gcd:=gcd(b,a mod b);
end;
begin
read(x,y);
tmp:=gcd(x,y);
write(tmp);
end. |
{$B-}
unit tests;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
procedure tests();
implementation
uses
RegExpr;
procedure tests();
var
r : TRegExpr;
procedure Check (ASubExprMatchCount, APos, ALen : integer);
begin
if (r.SubExprMatchCount <> ASubExprMatchCount)
or (r.MatchPos [0] <> APos) or (r.MatchLen [0] <> ALen) then begin
writeln ('Error. '#$d#$a'Expression "', r.Expression, '"'#$d#$a,
'Modifiers "', r.ModifierStr, '"'#$d#$a,
'Input text "', r.InputString, '"'#$d#$a,
'Actual/expected results: '#$d#$a,
' Sub-expressions matched: ', r.SubExprMatchCount, ' / ', ASubExprMatchCount, #$d#$a,
' Expression match starting position: ', r.MatchPos [0], ' / ', APos, #$d#$a,
' Expression match length: ', r.MatchLen [0], ' / ', ALen);
writeln ('P-Code:'#$d#$a, r.Dump);
readln ();
halt (1);
end;
end;
procedure CheckReplace (AExpr, AText, ASubs, AExpected : string);
var
ActualResult: string;
begin
ActualResult := ReplaceRegExpr(AExpr, AText, ASubs, True);
if (ActualResult <> AExpected) then begin
writeln ('Error. '#$d#$a'Expression "', AExpr, '"'#$d#$a,
'Input text "', AText, '"'#$d#$a,
'Pattern "', ASubs, '"'#$d#$a,
'Actual/expected results: ', ActualResult, ' / ', AExpected);
readln ();
halt (1);
end;
end;
begin
writeln ('*** Testing library RegExpr (www.RegExpStudio.com) ***');
{ basic tests }
r := TRegExpr.Create;
r.Expression := '[A-Z]';
r.Exec ('234578923457823659GHJK38');
Check (0, 19, 1);
r.Expression := '[A-Z]*?';
r.Exec ('234578923457823659ARTZU38');
Check (0, 1, 0);
r.Expression := '[A-Z]+';
r.Exec ('234578923457823659ARTZU38');
Check (0, 19, 5);
r.Expression := '[A-Z][A-Z]*';
r.Exec ('234578923457823659ARTZU38');
Check (0, 19, 5);
r.Expression := '[A-Z][A-Z]?';
r.Exec ('234578923457823659ARTZU38');
Check (0, 19, 2);
r.Expression := '[^\d]+';
r.Exec ('234578923457823659ARTZU38');
Check (0, 19, 5);
{ test chaining }
r.Expression := '[A-Z][A-Z]?[A-Z]';
r.Exec ('234578923457823659ARTZU38');
Check (0, 19, 3);
r.Expression := '[A-Z][A-Z]*[0-9]';
r.Exec ('234578923457823659ARTZU38');
Check (0, 19, 6);
r.Expression := '[A-Z]+[0-9]';
r.Exec ('234578923457823659ARTZU38');
Check (0, 19, 6);
{ case insensitive: }
r.ModifierI := True;
r.Expression := '[A-Z]';
r.Exec ('234578923457823659a38');
Check (0, 19, 1);
{ case insensitive: }
r.Expression := '[a-z]';
r.Exec ('234578923457823659A38');
Check (0, 19, 1);
r.ModifierI := False;
{ with parenthsis }
r.Expression := '(foo)1234';
r.Exec ('1234 foo1234XXXX');
Check (1, 8, 7);
r.Expression := '(((foo)))1234';
r.Exec ('1234 foo1234XXXX');
Check (3, 8, 7);
r.Expression := '(foo)(1234)';
r.Exec ('1234 foo1234XXXX');
Check (2, 8, 7);
{ test real backtracking }
r.Expression := 'nofoo|foo';
r.Exec ('1234 foo1234XXXX');
Check (0, 8, 3);
r.Expression := '(nofoo|foo)1234';
r.Exec ('1234 nofoo1234XXXX');
Check (1, 8, 9);
r.Expression := '(nofoo|foo|anotherfoo)1234';
r.Exec ('1234 nofoo1234XXXX');
Check (1, 8, 9);
r.Expression := 'nofoo1234|foo1234';
r.Exec ('1234 foo1234XXXX');
Check (0, 8, 7);
r.Expression := '(\w*)';
r.Exec ('name.ext');
Check (1, 1, 4);
CheckReplace('(\w*)', 'name.ext', '$1.new', 'name.new.new.ext.new.new');
writeln ('*** The test have been successfully finished ***');
end;
end.
|
{
Tryb blokowy ECB (Delphi)
implementacja trybu blokowego ECB
(szyfrowanie danych algorytmem pseudoDES)
autor: Rafal Toborek (toborek.info)
}
function ecb(sTekst: string; sKlucz: string; byDlugoscBloku: byte): string;
var
iX, iY: integer;
sA, sB: string;
begin
iX:= 0;
sA:= '';
sB:= '';
repeat
inc(iX, byDlugoscBloku);
for iY:= iX-byDlugoscBloku+1 to iX do
if iY <= Length(sTekst) then
sA:= sA+sTekst[iY];
// tutaj nastepuje szyfrowanie bloku przy uzyciu dowolnego
// algorytmu kryptograficznego (np. pseudoDES)
sB:= sB + pseudoDES(sA, sKlucz);
sA:= '';
until (iX >= Length(sTekst));
result:= sB;
end;
|
(*
Category: SWAG Title: DATE & TIME ROUTINES
Original name: 0055.PAS
Description: Find Difference b/w 2 Time Strings
Author: SCOTT STONE
Date: 05-26-95 23:30
*)
{From: Scott Stone <Scott.Stone@m.cc.utah.edu> }
Procedure CompTimes(t1,t2 : string);
Var
h1,h2,m1,m2,s1,s2 : string;
x0,x1,x2,x3,x4,x5,sec0,sec1 : integer;
err : integer;
timediff : integer;
Begin
h1:=t1[1]+t1[2];
h2:=t2[1]+t2[2];
m1:=t1[4]+t1[5];
m2:=t2[4]+t2[5];
s1:=t1[7]+t1[8];
s2:=t2[7]+t2[8];
val(h1,x0,err);
val(h2,x1,err);
val(m1,x2,err);
val(m2,x3,err);
val(s1,x4,err);
val(s2,x5,err);
sec0:=((3600*x0)+(60*x2)+(x4));
sec1:=((3600*x1)+(60*x3)+(x5));
timediff:=abs(sec1-sec0);
writeln('Time Difference is ',timediff,' seconds.');
End;
begin
CompTimes('11:23:31','16:32:21');
end.
|
{***************************************************************************}
{ }
{ DUnitX }
{ }
{ Copyright (C) 2013 Vincent Parrett }
{ }
{ vincent@finalbuilder.com }
{ http://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DUnitX.TestRunner;
interface
uses
DUnitX.TestFramework,
Generics.Collections,
DUnitX.InternalInterfaces,
DUnitX.Generics,
DUnitX.WeakReference,
Rtti;
{$I DUnitX.inc}
type
/// Note - we rely on the fact that there will only ever be 1 testrunner
/// per thread, if this changes then handling of WriteLn will need to change
TDUnitXTestRunner = class(TWeakReferencedObject, ITestRunner)
private class var
FRttiContext : TRttiContext;
public class var
FActiveRunners : TDictionary<Cardinal,ITestRunner>;
private
FLoggers : TList<ITestLogger>;
FUseCommandLine : boolean;
FUseRTTI : boolean;
FExitBehavior : TRunnerExitBehavior;
FFixtureClasses : TDictionary<string,TClass>;
FFixtureList : ITestFixtureList;
protected
//Logger calls - sequence ordered
procedure Loggers_TestingStarts(const threadId, testCount, testActiveCount : Cardinal);
procedure Loggers_StartTestFixture(const threadId : Cardinal; const fixture : ITestFixtureInfo);
procedure Loggers_SetupFixture(const threadId : Cardinal; const fixture : ITestFixtureInfo);
procedure Loggers_EndSetupFixture(const threadId : Cardinal; const fixture : ITestFixtureInfo);
procedure Loggers_BeginTest(const threadId : Cardinal; const Test: ITestInfo);
procedure Loggers_SetupTest(const threadId : Cardinal; const Test: ITestInfo);
procedure Loggers_EndSetupTest(const threadId : Cardinal; const Test: ITestInfo);
procedure Loggers_ExecuteTest(const threadId : Cardinal; const Test: ITestInfo);
procedure Loggers_AddSuccess(const threadId : Cardinal; const Test: ITestResult);
procedure Loggers_AddError(const threadId : Cardinal; const Error: ITestError);
procedure Loggers_AddFailure(const threadId : Cardinal; const Failure: ITestError);
procedure Loggers_AddWarning(const threadId : Cardinal; const AWarning: ITestResult);
procedure Loggers_EndTest(const threadId : Cardinal; const Test: ITestResult);
procedure Loggers_TeardownTest(const threadId : Cardinal; const Test: ITestInfo);
procedure Loggers_TeardownFixture(const threadId : Cardinal; const fixture : ITestFixtureInfo);
procedure Loggers_EndTestFixture(const threadId : Cardinal; const results : IFixtureResult);
procedure Loggers_TestingEnds(const TestResult: ITestResults);
//ITestRunner
procedure AddLogger(const value: ITestLogger);
function Execute: ITestResults;
procedure ExecuteFixtures(const context: ITestExecuteContext; const threadId: Cardinal; const fixtures: ITestFixtureList);
function GetExitBehavior: TRunnerExitBehavior;
function GetUseCommandLineOptions: Boolean;
function GetUseRTTI: Boolean;
procedure SetExitBehavior(const value: TRunnerExitBehavior);
procedure SetUseCommandLineOptions(const value: Boolean);
procedure SetUseRTTI(const value: Boolean);
procedure Log(const logType : TLogLevel; const msg : string);overload;
procedure Log(const msg : string);overload;
//for backwards compatibilty with DUnit tests.
procedure Status(const msg : string);overload;
//redirects WriteLn to our loggers.
procedure WriteLn(const msg : string);overload;
procedure WriteLn;overload;
//internals
procedure RTTIDiscoverFixtureClasses;
function BuildFixtures : IInterface;
procedure AddStatus(const threadId; const msg : string);
class constructor Create;
class destructor Destroy;
public
constructor Create(const useCommandLineOptions : boolean; const AListener : ITestLogger);
destructor Destroy;override;
class function GetActiveRunner : ITestRunner;
end;
implementation
uses
DUnitX.TestFixture,
DUnitX.TestResults,
DUnitX.TestResult,
TypInfo,
SysUtils,
StrUtils,
Types,
classes;
{ TDUnitXTestRunner }
procedure TDUnitXTestRunner.Log(const msg: string);
begin
Self.Log(TLogLevel.ltInformation,msg);
end;
procedure TDUnitXTestRunner.Loggers_AddError(const threadId : Cardinal; const Error: ITestError);
var
logger : ITestLogger;
begin
for logger in FLoggers do
begin
logger.OnTestError(threadId,Error);
end;
end;
procedure TDUnitXTestRunner.Loggers_AddFailure(const threadId : Cardinal; const Failure: ITestError);
var
logger : ITestLogger;
begin
for logger in FLoggers do
begin
logger.OnTestFailure(threadId, Failure);
end;
end;
procedure TDUnitXTestRunner.AddLogger(const value: ITestLogger);
begin
if not FLoggers.Contains(value) then
FLoggers.Add(value);
end;
procedure TDUnitXTestRunner.Loggers_AddSuccess(const threadId : Cardinal; const Test: ITestResult);
var
logger : ITestLogger;
begin
for logger in FLoggers do
begin
logger.OnTestSuccess(threadId,Test);
end;
end;
procedure TDUnitXTestRunner.Loggers_AddWarning(const threadId : Cardinal; const AWarning: ITestResult);
var
logger : ITestLogger;
begin
for logger in FLoggers do
begin
logger.OnTestWarning(threadId,AWarning);
end;
end;
procedure TDUnitXTestRunner.AddStatus(const threadId; const msg: string);
begin
end;
function TDUnitXTestRunner.BuildFixtures : IInterface;
var
fixture : ITestFixture;
parentFixture : ITestFixture;
pair : TPair<string,TClass>;
uName : string;
namespaces : TStringDynArray;
namespace : string;
parentNamespace : string;
fixtureNamespace : string;
tmpFixtures : TDictionary<string,ITestFixture>;
begin
if FFixtureList <> nil then
begin
result := FFixtureList;
exit;
end;
FFixtureList := TTestFixtureList.Create;
if FUseRTTI then
RTTIDiscoverFixtureClasses;
for pair in TDUnitX.RegisteredFixtures do
begin
if not FFixtureClasses.ContainsValue(pair.Value) then
FFixtureClasses.AddOrSetValue(pair.Key, pair.Value);
end;
//Build up a fixture heriachy based on unit names.
tmpFixtures := TDictionary<string,ITestFixture>.Create;
try
for pair in FFixtureClasses do
begin
uName := pair.Value.UnitName;
namespaces := SplitString(uName,'.');
//if the unit name has no namespaces the just add the tests.
fixtureNamespace := '';
parentNameSpace := '';
parentFixture := nil;
fixture := nil;
for namespace in namespaces do
begin
if fixtureNamespace <> '' then
fixtureNamespace := fixtureNamespace + '.' + namespace
else
fixtureNamespace := namespace;
//first time through the loop it will be empty.
if parentNamespace = '' then
parentNamespace := fixtureNamespace
else
begin
if not tmpFixtures.TryGetValue(parentNamespace,parentFixture) then
begin
parentFixture := TDUnitXTestFixture.Create(parentNamespace, TObject);
FFixtureList.Add(parentFixture);
tmpFixtures.Add(parentNamespace,parentFixture);
end;
if not tmpFixtures.TryGetValue(fixtureNamespace,fixture) then
begin
fixture := TDUnitXTestFixture.Create(fixtureNamespace, TObject);
parentFixture.Children.Add(fixture);
tmpFixtures.Add(fixtureNamespace,fixture);
end;
parentFixture := fixture;
parentNamespace := fixtureNamespace;
end;
end;
fixtureNamespace := fixtureNamespace + '.' + pair.Key;
fixture := TDUnitXTestFixture.Create(fixtureNamespace, pair.Value);
parentFixture.Children.Add(fixture);
end;
finally
tmpFixtures.Free;
end;
result := FFixtureList;
end;
class constructor TDUnitXTestRunner.Create;
begin
FRttiContext := TRttiContext.Create;
FActiveRunners := TDictionary<Cardinal,ITestRunner>.Create;
end;
constructor TDUnitXTestRunner.Create(const useCommandLineOptions: boolean; const AListener: ITestLogger);
begin
FLoggers := TList<ITestLogger>.Create;
if AListener <> nil then
FLoggers.Add(AListener);
FFixtureClasses := TDictionary<string,TClass>.Create;
FUseCommandLine := useCommandLineOptions;
FUseRTTI := False;
MonitorEnter(TDUnitXTestRunner.FActiveRunners);
try
TDUnitXTestRunner.FActiveRunners.Add(TThread.CurrentThread.ThreadID, Self);
finally
MonitorExit(TDUnitXTestRunner.FActiveRunners);
end;
end;
destructor TDUnitXTestRunner.Destroy;
var
tId : Cardinal;
begin
MonitorEnter(TDUnitXTestRunner.FActiveRunners);
try
tId := TThread.CurrentThread.ThreadID;
if TDUnitXTestRunner.FActiveRunners.ContainsKey(tId) then
TDUnitXTestRunner.FActiveRunners.Remove(tId);
finally
MonitorExit(TDUnitXTestRunner.FActiveRunners);
end;
FLoggers.Free;
FFixtureClasses.Free;
inherited;
end;
class destructor TDUnitXTestRunner.Destroy;
begin
FActiveRunners.Free;
end;
procedure TDUnitXTestRunner.RTTIDiscoverFixtureClasses;
var
types : TArray<TRttiType>;
rType : TRttiType;
attributes : TArray<TCustomAttribute>;
attribute : TCustomAttribute;
sName : string;
begin
types := FRttiContext.GetTypes;
for rType in types do
begin
//try and keep the iteration down as much as possible
if (rType.TypeKind = TTypeKind.tkClass) and (not rType.InheritsFrom(TPersistent)) then
begin
attributes := rType.GetAttributes;
if Length(attributes) > 0 then
for attribute in attributes do
begin
if attribute.ClassType = TestFixtureAttribute then
begin
sName := TestFixtureAttribute(attribute).Name;
if sName = '' then
sName := TRttiInstanceType(rType).MetaclassType.ClassName;
if not FFixtureClasses.ContainsValue(TRttiInstanceType(rType).MetaclassType) then
FFixtureClasses.Add(sName,TRttiInstanceType(rType).MetaclassType);
end;
end;
end;
end;
end;
procedure TDUnitXTestRunner.Loggers_EndSetupFixture(const threadId: Cardinal; const fixture: ITestFixtureInfo);
var
logger : ITestLogger;
begin
for logger in FLoggers do
logger.OnEndSetupFixture(threadId,fixture);
end;
procedure TDUnitXTestRunner.Loggers_EndSetupTest(const threadId: Cardinal; const Test: ITestInfo);
var
logger : ITestLogger;
begin
for logger in FLoggers do
begin
try
logger.OnEndSetupTest(threadid,Test);
except
//Hmmmm what to do with errors here. This kinda smells.
on e : Exception do
begin
try
logger.OnLog(TLogLevel.ltError,'Error in OnEndSetupEvent : ' + e.Message);
except
on e : Exception do
System.Write('unable to log error in OnEndSetupTest event : ' + e.Message);
end;
end;
end;
end;
end;
procedure TDUnitXTestRunner.Loggers_EndTest(const threadId : Cardinal; const Test: ITestResult);
var
logger : ITestLogger;
begin
for logger in FLoggers do
logger.OnEndTest(threadId,Test);
end;
procedure TDUnitXTestRunner.Loggers_EndTestFixture(const threadId : Cardinal; const results: IFixtureResult);
var
logger : ITestLogger;
begin
for logger in FLoggers do
begin
logger.OnEndTestFixture(threadId,results);
end;
end;
procedure TDUnitXTestRunner.Loggers_ExecuteTest(const threadId: Cardinal; const Test: ITestInfo);
var
logger : ITestLogger;
begin
for logger in FLoggers do
logger.OnExecuteTest(threadId, Test);
end;
//TODO - this needs to be thread aware so we can run tests in threads.
function TDUnitXTestRunner.Execute: ITestResults;
var
fixtures : ITestFixtureList;
fixture : ITestFixture;
test : ITest;
context : ITestExecuteContext;
threadId : Cardinal;
testCount : Cardinal;
testActiveCount : Cardinal;
begin
result := nil;
fixtures := BuildFixtures as ITestFixtureList;
if fixtures.Count = 0 then
raise ENoTestsRegistered.Create('No Test Fixtures found');
testCount := 0;
//TODO: Count the active tests that we have.
testActiveCount := 0;
//TODO: Move to the fixtures class
for fixture in fixtures do
for test in fixture.Tests do
Inc(testCount);
//TODO: Need a simple way of converting one list to another list of a supported interface. Generics should help here.
result := TDUnitXTestResults.Create(fixtures.AsFixtureInfoList);
context := result as ITestExecuteContext;
//TODO: Record Test metrics.. runtime etc.
threadId := TThread.CurrentThread.ThreadID;
Self.Loggers_TestingStarts(threadId, testCount, testActiveCount);
try
ExecuteFixtures(context, threadId, fixtures);
finally
//TODO: Actully pass the results for all fixtures and tests here.
Self.Loggers_TestingEnds(result);
end;
end;
class function TDUnitXTestRunner.GetActiveRunner: ITestRunner;
begin
result := nil;
FActiveRunners.TryGetValue(TThread.CurrentThread.ThreadId,result)
end;
procedure TDUnitXTestRunner.ExecuteFixtures(const context: ITestExecuteContext; const threadId: Cardinal; const fixtures: ITestFixtureList);
var
testResult: ITestResult;
tests: System.IEnumerable<ITest>;
testError: ITestError;
testExecute: ITestExecute;
test: ITest;
fixture: ITestFixture;
begin
for fixture in fixtures do
begin
if not fixture.Enabled then
System.continue;
Self.Loggers_StartTestFixture(threadId, fixture as ITestFixtureInfo);
try
if Assigned(fixture.SetupFixtureMethod) then
begin
try
Self.Loggers_SetupFixture(threadid, fixture as ITestFixtureInfo);
fixture.SetupFixtureMethod;
Self.Loggers_EndSetupFixture(threadid, fixture as ITestFixtureInfo);
except
on e: Exception do
begin
Log(TLogLevel.ltError, 'Error in Fixture SetupError : ' + fixture.Name + ' : ' + e.Message);
Log(TLogLevel.ltError, 'Skipping Fixture.');
System.Continue;
end;
end;
end;
try
tests := fixture.Tests;
for test in tests do
begin
if not test.Enabled then
System.Continue;
testResult := nil;
testError := nil;
Self.Loggers_BeginTest(threadId, test as ITestInfo);
//Setup method is called before each test method.
if Assigned(fixture.SetupMethod) then
begin
try
Self.Loggers_SetupTest(threadId, test as ITestInfo);
fixture.SetupMethod;
Self.Loggers_EndSetupTest(threadId, test as ITestInfo);
except
on e: Exception do
begin
testResult := TDUnitXTestResult.Create(test as ITestInfo, TTestResultType.Error, e.Message);
Log(TLogLevel.ltError, 'Error running test Setup method : ' + e.Message);
Log(TLogLevel.ltError, 'Skipping test.');
System.Continue;
end;
end;
end;
try
try
if Supports(test, ITestExecute, testExecute) then
begin
Self.Loggers_ExecuteTest(threadId, test as ITestInfo);
testExecute.Execute(context);
testResult := TDUnitXTestResult.Create(test as ITestInfo, TTestResultType.Pass);
context.RecordResult(testResult);
Self.Loggers_AddSuccess(threadId, testResult);
end;
except
on e: ETestPass do
begin
testResult := TDUnitXTestResult.Create(test as ITestInfo, TTestResultType.Pass);
context.RecordResult(testResult);
Self.Loggers_AddSuccess(threadId, testResult);
end;
on e: ETestFailure do
begin
//TODO: Does test failure require its own results interface and class?
Log(TLogLevel.ltError, 'Test failed : ' + test.Name + ' : ' + e.Message);
testError := TDUnitXTestError.Create(test as ITestInfo, TTestResultType.Failure, e, ExceptAddr);
context.RecordResult(testError);
Self.Loggers_AddFailure(threadId, testError);
end;
on e: ETestWarning do
begin
//TODO: Does test warning require its own results interface and class?
Log(TLogLevel.ltWarning, 'Test warning : ' + test.Name + ' : ' + e.Message);
testResult := TDUnitXTestResult.Create(test as ITestInfo, TTestResultType.Warning, e.Message);
context.RecordResult(testResult);
Self.Loggers_AddWarning(threadId, testResult);
end;
on e: Exception do
begin
Log(TLogLevel.ltError, 'Test Error : ' + test.Name + ' : ' + e.Message);
testError := TDUnitXTestError.Create(test as ITestInfo, TTestResultType.Error, e, ExceptAddr);
context.RecordResult(testError);
Self.Loggers_AddError(threadId, testError);
end;
end;
if Assigned(fixture.TearDownMethod) then
begin
try
Self.Loggers_TeardownTest(threadId, test as ITestInfo);
fixture.TearDownMethod;
except
//TODO: Report test tear down exceptions to the user
end;
end;
finally
//TODO: Actully pass the results for the test here.
Self.Loggers_EndTest(threadId, nil);
end;
end;
except
//WTF?
end;
if fixture.HasChildFixtures then
ExecuteFixtures(context,threadId,fixture.Children);
if Assigned(fixture.TearDownFixtureMethod) then
begin
try
Self.Loggers_TeardownFixture(threadId, fixture as ITestFixtureInfo);
fixture.TearDownFixtureMethod;
except
on e: Exception do
begin
end;
end;
//TODO: Report fixture tear down exceptions to the user
end;
finally
//TODO: Actully pass the results for the fixture here
Self.Loggers_EndTestFixture(threadId, nil);
end;
end;
end;
function TDUnitXTestRunner.GetExitBehavior: TRunnerExitBehavior;
begin
result := FExitBehavior;
end;
function TDUnitXTestRunner.GetUseCommandLineOptions: Boolean;
begin
result := FUseCommandLine;
end;
function TDUnitXTestRunner.GetUseRTTI: Boolean;
begin
result := FUseRTTI;
end;
procedure TDUnitXTestRunner.SetExitBehavior(const value: TRunnerExitBehavior);
begin
FExitBehavior := value;
end;
procedure TDUnitXTestRunner.SetUseCommandLineOptions(const value: Boolean);
begin
FUseCommandLine := value;
end;
procedure TDUnitXTestRunner.SetUseRTTI(const value: Boolean);
begin
FUseRTTI := value;
end;
procedure TDUnitXTestRunner.Status(const msg: string);
begin
Self.Log(TLogLevel.ltInformation,msg);
end;
procedure TDUnitXTestRunner.WriteLn;
begin
Self.Log(TLogLevel.ltInformation,'');
end;
procedure TDUnitXTestRunner.WriteLn(const msg: string);
begin
Self.Log(TLogLevel.ltInformation,msg);
end;
procedure TDUnitXTestRunner.Loggers_SetupFixture(const threadId: Cardinal; const fixture: ITestFixtureInfo);
var
logger : ITestLogger;
begin
for logger in FLoggers do
logger.OnSetupFixture(threadId,fixture);
end;
procedure TDUnitXTestRunner.Loggers_SetupTest(const threadId: Cardinal; const Test: ITestInfo);
var
logger : ITestLogger;
begin
for logger in FLoggers do
logger.OnSetupTest(threadId,Test);
end;
procedure TDUnitXTestRunner.Loggers_BeginTest(const threadId : Cardinal; const Test: ITestInfo);
var
logger : ITestLogger;
begin
for logger in FLoggers do
logger.OnBeginTest(threadId, Test);
end;
procedure TDUnitXTestRunner.Loggers_StartTestFixture(const threadId : Cardinal; const fixture: ITestFixtureInfo);
var
logger : ITestLogger;
begin
for logger in FLoggers do
logger.OnStartTestFixture(threadId, fixture);
end;
procedure TDUnitXTestRunner.Loggers_TeardownFixture(const threadId: Cardinal; const fixture: ITestFixtureInfo);
var
logger : ITestLogger;
begin
for logger in FLoggers do
logger.OnTearDownFixture(threadId, fixture);
end;
procedure TDUnitXTestRunner.Loggers_TeardownTest(const threadId: Cardinal; const Test: ITestInfo);
var
logger : ITestLogger;
begin
for logger in FLoggers do
logger.OnTeardownTest(threadId, Test);
end;
procedure TDUnitXTestRunner.Loggers_TestingEnds(const TestResult: ITestResults);
var
logger : ITestLogger;
begin
for logger in FLoggers do
logger.OnTestingEnds(TestResult);
end;
procedure TDUnitXTestRunner.Loggers_TestingStarts(const threadId, testCount, testActiveCount : Cardinal);
var
logger : ITestLogger;
begin
for logger in FLoggers do
logger.OnTestingStarts(threadId, testCount, testActiveCount);
end;
procedure TDUnitXTestRunner.Log(const logType: TLogLevel; const msg: string);
var
logger : ITestLogger;
begin
if logType >= TDUnitX.CommandLine.LogLevel then
begin
for logger in FLoggers do
logger.OnLog(logType,msg);
end;
end;
end.
|
unit ExclusiveOrOpTest;
{$mode objfpc}{$H+}
interface
uses
fpcunit,
testregistry,
uIntXLibTypes,
uIntX,
uConstants;
type
{ TTestExclusiveOrOp }
TTestExclusiveOrOp = class(TTestCase)
published
procedure ShouldExclusiveOrTwoIntX();
procedure ShouldExclusiveOrPositiveAndNegativeIntX();
procedure ShouldExclusiveOrTwoNegativeIntX();
procedure ShouldExclusiveOrIntXAndZero();
procedure ShouldExclusiveOrTwoBigIntX();
procedure ShouldExclusiveOrTwoBigIntXOfDifferentLength();
end;
implementation
procedure TTestExclusiveOrOp.ShouldExclusiveOrTwoIntX();
var
int1, int2, Result: TIntX;
begin
int1 := TIntX.Create(3);
int2 := TIntX.Create(5);
Result := int1 xor int2;
AssertTrue(Result.Equals(6));
end;
procedure TTestExclusiveOrOp.ShouldExclusiveOrPositiveAndNegativeIntX();
var
int1, int2, Result: TIntX;
begin
int1 := TIntX.Create(-3);
int2 := TIntX.Create(5);
Result := int1 xor int2;
AssertTrue(Result.Equals(-6));
end;
procedure TTestExclusiveOrOp.ShouldExclusiveOrTwoNegativeIntX();
var
int1, int2, Result: TIntX;
begin
int1 := TIntX.Create(-3);
int2 := TIntX.Create(-5);
Result := int1 xor int2;
AssertTrue(Result.Equals(6));
end;
procedure TTestExclusiveOrOp.ShouldExclusiveOrIntXAndZero();
var
int1, int2, Result: TIntX;
begin
int1 := TIntX.Create(3);
int2 := TIntX.Create(0);
Result := int1 xor int2;
AssertTrue(Result.Equals(int1));
end;
procedure TTestExclusiveOrOp.ShouldExclusiveOrTwoBigIntX();
var
temp1, temp2, temp3: TIntXLibUInt32Array;
int1, int2, Result: TIntX;
begin
SetLength(temp1, 3);
temp1[0] := 3;
temp1[1] := 5;
temp1[2] := TConstants.MaxUInt32Value;
SetLength(temp2, 3);
temp2[0] := 1;
temp2[1] := 8;
temp2[2] := TConstants.MaxUInt32Value;
SetLength(temp3, 2);
temp3[0] := 2;
temp3[1] := 13;
int1 := TIntX.Create(temp1, False);
int2 := TIntX.Create(temp2, False);
Result := int1 xor int2;
AssertTrue(Result.Equals(TIntX.Create(temp3, False)));
end;
procedure TTestExclusiveOrOp.ShouldExclusiveOrTwoBigIntXOfDifferentLength();
var
temp1, temp2, temp3: TIntXLibUInt32Array;
int1, int2, Result: TIntX;
begin
SetLength(temp1, 4);
temp1[0] := 3;
temp1[1] := 5;
temp1[2] := TConstants.MaxUInt32Value;
temp1[3] := TConstants.MaxUInt32Value;
SetLength(temp2, 3);
temp2[0] := 1;
temp2[1] := 8;
temp2[2] := TConstants.MaxUInt32Value;
SetLength(temp3, 4);
temp3[0] := 2;
temp3[1] := 13;
temp3[2] := 0;
temp3[3] := TConstants.MaxUInt32Value;
int1 := TIntX.Create(temp1, False);
int2 := TIntX.Create(temp2, False);
Result := int1 xor int2;
AssertTrue(Result.Equals(TIntX.Create(temp3, False)));
end;
initialization
RegisterTest(TTestExclusiveOrOp);
end.
|
program ext26(input, output);
{}
{Initialized Variable Testing - Record constants}
{}
type
intrecord = record
x, y : integer;
u, v : integer;
end;
realrecord = record
s, t : real;
x : real;
end;
ostype = (VM370, MVS, CPM80, MSDOS);
complicated = record
os : ostype;
num_users : integer;
cost : real;
cartesian : array [1..2] of record
squid : intrecord;
octopus : realrecord;
end;
end;
const
pgmname = 'ext26';
{}
transform : intrecord = (x:0; y:0; u:1; v:2);
realrec : realrecord = (s:Pi; t:1.2e4; x:0.0);
biggie : complicated = (os:MVS; num_users:2; cost:1e20; cartesian:((squid:(x:1;
y:1; u:2; v:2); octopus:(s:-1.0; t:16.0; x:2.0)), (squid:(x:10; y:10; u:20; v:
20); octopus:(s:-22.0; t:Pi; x:Pi))));
var
error : Boolean;
{+Class Declarations}{+Hide}{+Revealed PASS/FAIL output routines}
const
tstnum : integer = 1; {global test number}
procedure pass ;
{write out the PASS message for test number tstnum}
{+ <<Declarations>>}
begin
writeln(pgmname, tstnum:4, ' PASS');
tstnum := tstnum + 1;
end;
procedure fail ;
{write out the FAIL message for test number tstnum}
{+ <<Declarations>>}
begin
writeln(pgmname, tstnum:4, ' ** FAIL **');
tstnum := tstnum + 1;
end;
{+Hide end}
begin
{Test 1 - test record initialization of simple integer record}
if (transform.x = 0) and (transform.y = 0) then begin
error := false;
end
else begin
error := true;
end;
if not ((transform.u = 1) and (transform.v = 2)) then begin
error := true;
end;
if not error then begin
pass ;
end
else begin
fail ;
end;
{Test 2 - test record initialization of simple reals}
if (realrec.s = Pi) and (realrec.t = 12000) and (realrec.x = 0) then begin
pass ;
end
else begin
fail ;
end;
{Test 3 - test fairly complicated initialized record}
if (biggie.os = MVS) and (biggie.num_users = 2) and (biggie.cost = 1e20) then begin
error := false;
end
else begin
error := true;
end;
if biggie.cartesian[1].squid.x <> 1 then begin
error := true;
end;
if biggie.cartesian[1].squid.y <> 1 then begin
error := true;
end;
if biggie.cartesian[1].squid.u <> 2 then begin
error := true;
end;
if biggie.cartesian[1].squid.v <> 2 then begin
error := true;
end;
if biggie.cartesian[1].octopus.s <> -1.0 then begin
error := true;
end;
if biggie.cartesian[1].octopus.t <> 16.0 then begin
error := true;
end;
if biggie.cartesian[1].octopus.x <> 2.0 then begin
error := true;
end;
if biggie.cartesian[2].squid.x <> 10 then begin
error := true;
end;
if biggie.cartesian[2].squid.y <> 10 then begin
error := true;
end;
if biggie.cartesian[2].squid.u <> 20 then begin
error := true;
end;
if biggie.cartesian[2].squid.v <> 20 then begin
error := true;
end;
if biggie.cartesian[2].octopus.s <> -22.0 then begin
error := true;
end;
if biggie.cartesian[2].octopus.t <> Pi then begin
error := true;
end;
if biggie.cartesian[2].octopus.x <> Pi then begin
error := true;
end;
if not error then begin
pass ;
end
else begin
fail ;
end;
end.
|
unit UnitStringPromtForm;
interface
uses
System.SysUtils,
System.Classes,
Winapi.Windows,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Dmitry.Controls.WatermarkedEdit,
uDBForm,
uFormInterfaces;
type
TFormStringPromt = class(TDBForm, IStringPromtForm)
EdString: TWatermarkedEdit;
LbInfo: TLabel;
BtnOK: TButton;
BtnCancel: TButton;
procedure FormCreate(Sender: TObject);
procedure BtnCancelClick(Sender: TObject);
procedure BtnOKClick(Sender: TObject);
procedure EdStringKeyPress(Sender: TObject; var Key: Char);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
FOldString: string;
FIsOk: Boolean;
{ Private declarations }
protected
function GetFormID: string; override;
procedure CustomFormAfterDisplay; override;
procedure InterfaceDestroyed; override;
public
{ Public declarations }
function Query(Caption, Text: String; var UserString: string): Boolean;
end;
implementation
{$R *.dfm}
function TFormStringPromt.Query(Caption, Text: String;
var UserString: string): Boolean;
begin
Self.Caption := Caption;
LbInfo.Caption := Text;
FOldString := UserString;
EdString.Text := UserString;
ShowModal;
UserString := EdString.Text;
Result := FIsOk;
end;
procedure TFormStringPromt.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caHide;
end;
procedure TFormStringPromt.FormCreate(Sender: TObject);
begin
FIsOk := False;
BtnCancel.Caption := L('Cancel');
BtnOK.Caption := L('Ok');
EdString.WatermarkText := L('Enter your text here');
BtnOK.Top := EdString.Top + EdString.Height + 3;
BtnCancel.Top := EdString.Top + EdString.Height + 3;
ClientHeight := BtnOK.Top + BtnOK.Height + 3;
end;
function TFormStringPromt.GetFormID: string;
begin
Result := 'TextPromt';
end;
procedure TFormStringPromt.InterfaceDestroyed;
begin
inherited;
Release;
end;
procedure TFormStringPromt.BtnCancelClick(Sender: TObject);
begin
FIsOk := False;
Close;
end;
procedure TFormStringPromt.BtnOKClick(Sender: TObject);
begin
FIsOk := True;
Close;
end;
procedure TFormStringPromt.CustomFormAfterDisplay;
begin
inherited;
if EdString <> nil then
EdString.Refresh;
end;
procedure TFormStringPromt.EdStringKeyPress(Sender: TObject; var Key: Char);
begin
if Key = Char(VK_RETURN) then
begin
Key := #0;
BtnOKClick(Sender);
end;
end;
initialization
FormInterfaces.RegisterFormInterface(IStringPromtForm, TFormStringPromt);
end.
|
unit UFrmCadastroFilial;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFrmCRUD, Menus, Buttons, StdCtrls, ExtCtrls
, UFilial
, URegraCRUDFilial
, UUtilitarios
, URegraCRUDPais
, URegraCRUDCidade
, URegraCRUDEstado
, URegraCRUDEmpresaMatriz
;
type
TFrmCadastroFilial = class(TFrmCRUD)
gbInformacoes: TGroupBox;
edNome: TLabeledEdit;
edInscricaoEstadual: TLabeledEdit;
Endereลกo: TGroupBox;
lblCidade: TLabel;
edLogradouro: TLabeledEdit;
edNumero: TLabeledEdit;
edBairro: TLabeledEdit;
edCidade: TEdit;
btnLocalizarCidade: TButton;
stNomeCidade: TStaticText;
edCnpj: TLabeledEdit;
edTelefone: TLabeledEdit;
edEmpresaMatriz: TEdit;
lblEmpresa: TLabel;
btnLocalizarEmpresa: TButton;
stNomeEmpresa: TStaticText;
procedure btnLocalizarCidadeClick(Sender: TObject);
procedure edCidadeExit(Sender: TObject);
procedure btnLocalizarEmpresaClick(Sender: TObject);
procedure edEmpresaMatrizExit(Sender: TObject);
protected
FFILIAL: TFILIAL;
FRegraCRUDFilial : TregraCRUDFILIAL;
FRegraCRUDEmpresa : TregraCRUDEEmpresaMatriz;
FRegraCRUDCidade : TRegraCRUDCidade;
FRegraCRUDPais : TRegraCRUDPais;
FRegraCRUDEstado : TRegraCRUDEstado;
procedure Inicializa; override;
procedure Finaliza; override;
procedure PreencheEntidade; override;
procedure PreencheFormulario; override;
procedure PosicionaCursorPrimeiroCampo; override;
procedure HabilitaCampos(const ceTipoOperacaoUsuario: TTipoOperacaoUsuario); override;
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmCadastroFilial: TFrmCadastroFilial;
implementation
uses
UOpcaoPesquisa
, UEntidade
, UFrmPesquisa
, UCidade
, UEmpresaMatriz
, UDialogo
;
{$R *.dfm}
procedure TFrmCadastroFilial.btnLocalizarCidadeClick(Sender: TObject);
begin
inherited;
edCidade.Text := TfrmPesquisa.MostrarPesquisa(TOpcaoPesquisa
.Create
.DefineVisao(VW_CIDADE)
.DefineNomeCampoRetorno(VW_CIDADE_ID)
.DefineNomePesquisa(STR_CIDADE)
.AdicionaFiltro(VW_CIDADE_NOME));
if Trim(edCidade.Text) <> EmptyStr then
edCidade.OnExit(btnLocalizarCidade);
end;
procedure TFrmCadastroFilial.btnLocalizarEmpresaClick(Sender: TObject);
begin
inherited;
edEmpresaMatriz.Text := TfrmPesquisa.MostrarPesquisa(TOpcaoPesquisa
.Create
.DefineVisao(VW_EMPRESA)
.DefineNomeCampoRetorno(VW_EMPRESA_ID)
.DefineNomePesquisa(STR_EMPRESAMATRIZ)
.AdicionaFiltro(VW_EMPRESA_NOME));
if Trim(edEmpresaMatriz.Text) <> EmptyStr then
edEmpresaMatriz.OnExit(btnLocalizarEmpresa);
end;
procedure TFrmCadastroFilial.edCidadeExit(Sender: TObject);
begin
inherited;
stNomeCidade.Caption := EmptyStr;
if Trim(edCidade.Text) <> EmptyStr then
try
FRegraCRUDCidade.ValidaExistencia(StrToIntDef(edCidade.Text, 0));
FFILIAL.CIDADE := TCIDADE(
FRegraCRUDCidade.Retorna(StrToIntDef(edCidade.Text, 0)));
stNomeCidade.Caption := FFILIAL.CIDADE.NOME;
except
on E: Exception do
begin
TDialogo.Excecao(E);
edCidade.SetFocus;
end;
end;
end;
procedure TFrmCadastroFilial.edEmpresaMatrizExit(Sender: TObject);
begin
inherited;
stNomeEmpresa.Caption := EmptyStr;
if Trim(edEmpresaMatriz.Text) <> EmptyStr then
try
FRegraCRUDEmpresa.ValidaExistencia(StrToIntDef(edEmpresaMatriz.Text, 0));
FFILIAL.EMPRESA := TEmpresa(
FRegraCRUDEmpresa.Retorna(StrToIntDef(edEmpresaMatriz.Text, 0)));
stNomeEmpresa.Caption := FFILIAL.EMPRESA.NOME;
except
on E: Exception do
begin
TDialogo.Excecao(E);
edEmpresaMatriz.SetFocus;
end;
end;
end;
procedure TFrmCadastroFilial.Finaliza;
begin
inherited;
FreeAndNil(FRegraCRUDCidade);
FreeAndNil(FRegraCRUDPais);
FreeAndNil(FRegraCRUDEstado);
FreeAndNil(FRegraCRUDEmpresa);
end;
procedure TFrmCadastroFilial.HabilitaCampos(
const ceTipoOperacaoUsuario: TTipoOperacaoUsuario);
begin
inherited;
gbInformacoes.Enabled := FTipoOperacaoUsuario In [touInsercao, touAtualizacao];
end;
procedure TFrmCadastroFilial.Inicializa;
begin
inherited;
DefineEntidade(@FFILIAL, TFILIAL);
DefineRegraCRUD(@FRegraCRUDFilial, TregraCRUDFILIAL);
AdicionaOpcaoPesquisa(TOpcaoPesquisa
.Create
.AdicionaFiltro(FLD_FILIAL_NOME)
.DefineNomeCampoRetorno(FLD_ENTIDADE_ID)
.DefineNomePesquisa(STR_FILIAL)
.DefineVisao(TBL_FILIAL));
FRegraCRUDCidade := TRegraCRUDCidade.Create;
FRegraCRUDEstado := TRegraCRUDEstado.Create;
FRegraCRUDPais := TRegraCRUDPais.Create;
FRegraCRUDEmpresa:= TregraCRUDEEmpresaMatriz.Create;
end;
procedure TFrmCadastroFilial.PosicionaCursorPrimeiroCampo;
begin
inherited;
end;
procedure TFrmCadastroFilial.PreencheEntidade;
begin
inherited;
FFILIAL.NOME := edNome.Text;
FFILIAL.IE := StrToIntDef(edInscricaoEstadual.Text, 0);
FFILIAL.CNPJ := edCnpj.Text;
FFILIAL.TELEFONE := edTelefone.Text;
FFILIAL.LOGRADOURO := edLogradouro.Text;
FFILIAL.NUMERO := StrToIntDef(edNumero.Text, 0);
FFILIAL.BAIRRO := edBairro.Text;
end;
procedure TFrmCadastroFilial.PreencheFormulario;
begin
inherited;
edNome.Text := FFILIAL.NOME;
edInscricaoEstadual.Text := IntToStr(FFILIAL.IE);
edCnpj.Text := FFILIAL.CNPJ;
edTelefone.Text := FFILIAL.TELEFONE;
edLogradouro.Text := FFILIAL.LOGRADOURO;
edNumero.Text := IntToStr(FFILIAL.NUMERO);
edBairro.Text := FFILIAL.BAIRRO;
edCidade.Text := IntToStr(FFILIAL.CIDADE.ID);
edEmpresaMatriz.Text := IntToStr(FFILIAL.EMPRESA.ID);
stNomeCidade.Caption := FFILIAL.CIDADE.NOME;
stNomeEmpresa.Caption := FFILIAL.EMPRESA.NOME;
end;
end.
|
unit Wwgttbl;
interface
uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons,
StdCtrls, db, dbtables, dialogs, sysutils, ExtCtrls;
type
TGetTableForm = class(TForm)
OKBtn: TBitBtn;
CancelBtn: TBitBtn;
Bevel1: TBevel;
DBListBox: TListBox;
TableListBox: TListBox;
Label1: TLabel;
Label2: TLabel;
UseTableExtension: TCheckBox;
procedure DBListBoxClick(Sender: TObject);
procedure OKBtnClick(Sender: TObject);
procedure TableListBoxDblClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
end;
function wwGetTableDlg(
var databaseName: string;
var tablename: string;
var useExtension: char): Boolean;
implementation
{$R *.DFM}
uses wwcommon;
function wwGetTableDlg(
var databaseName: string;
var tablename: string;
var useExtension: char): Boolean;
begin
with TGetTableForm.create(Application) do
try
Session.getDatabaseNames(DBListBox.Items);
DBListBox.itemIndex:= DBListBox.items.indexof(databaseName);
if DBListBox.itemIndex>=0 then begin
TableListBox.clear;
Session.getTableNames(DBListBox.Items[DBListBox.itemIndex],
'', True {Extensions}, False, TableListBox.items);
TableListBox.itemIndex:= TableListBox.items.indexof(tableName);
end;
useTableExtension.checked:= useExtension<>'N';
Result := ShowModal = IDOK;
if Result then begin
databaseName:= DBListBox.items[DBListBox.itemIndex];
tableName:= TableListBox.items[TableListBox.itemIndex];
if useTableExtension.checked then useExtension:='Y'
else useExtension:='N';
end;
finally
Free;
end
end;
procedure TGetTableForm.DBListBoxClick(Sender: TObject);
var lastIndex: integer;
begin
lastIndex:= DBListBox.itemIndex;
TableListBox.clear;
Session.getTableNames(DBListBox.Items[DBListBox.itemIndex], '', True {Extensions}, False,
TableListBox.items);
{ A Delphi bug FT5 makes the following line necessary to }
{ properly retain highlight on selected object! }
DBListBox.itemIndex:= lastIndex;
end;
procedure TGetTableForm.OKBtnClick(Sender: TObject);
var table1: TTable;
begin
if (DBListBox.itemIndex<0) or (TableListBox.itemIndex<0) then begin
MessageDlg('Please select a table.', mtInformation, [mbok], 0);
ModalResult:= mrNone;
exit;
end;
table1:= TTable.create(self);
table1.databasename:= DBListBox.items[DBListBox.itemIndex];
table1.tableName:= TableListBox.items[TableListBox.itemIndex];
Table1.IndexDefs.update; { refreshes Index list }
if Table1.IndexDefs.count>0 then begin
table1.free;
ModalResult:= IDOK;
end
else begin
table1.free;
MessageDlg('Please select a table with a primary or secondary index.',
mtInformation, [mbok], 0);
ModalResult:= mrNone;
end
end;
procedure TGetTableForm.TableListBoxDblClick(Sender: TObject);
begin
{ mrResult:= mrOK;}
end;
procedure TGetTableForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (key=vk_f1) then wwHelp(Handle, 'Select Linked Table Dialog Box')
end;
end.
|
unit TestThItemGroupingHistory;
interface
uses
TestFramework, BaseTestUnit, FMX.Types, FMX.Forms,
System.UITypes, System.Types, System.SysUtils, FMX.Controls, System.UIConsts;
type
// #275 Grouping์ด Undo / Redo ์์๋ ์ ์ฉ๋์ด์ผ ํ๋ค.
TestTThItemGrouppingHistory = class(TBaseCommandHistoryTestUnit)
published
// #277 P1์ C1์ ์ฌ๋ฆฌ๊ณ Undo / Redo ํ C1์ ๋ถ๋ชจ์ ์์น ํ์ธ
procedure TestMoveChild;
// #276 C1์ P1์ผ๋ก ๋ฎ๊ณ Undo / Redo ํ C1์ ๋ถ๋ชจ์ ์์น ํ์ธ
procedure TestMoveParent;
// #279 P1์ C1์ ์ถ๊ฐํ๊ณ Undo / Redo ํ C1์ ๋ถ๋ชจ๋ฅผ ํ์ธ
procedure TestAdd;
// #280 P1์์ C1์ ์ญ์ ํ๊ณ Undo / Redo ํ C1์ ๋ถ๋ชจ๋ฅผ ํ์ธ
procedure TestDeleteChild;
// #281 C1์ ํฌ๊ธฐ๋ฅผ P1์ ๋ฒ์ด๋๊ณ Undo/Redo ํ C1์ ๋ถ๋ชจ๋ฅผ ํ์ธ
procedure TestResizeChild;
// #282 P1์ ํฌ๊ธฐ๋ฅผ ์ค์ด๊ณ Undo/Redo ํ C1์ ๋ถ๋ชจ๋ฅผ ํ์ธ
procedure TestResizeParent;
// #249 Undo / Redo ์ ItemIndex๊ฐ ์๋๋๋ก ๋์์์ผ ํ๋ค.
procedure TestRecoveryIndexMove;
// #285: P1์ C1์ ๊ทธ๋ฆฌ๊ณ C1์ ๋ฐ์ผ๋ก ๋บ ํ Undo / Redo
procedure TestMoveReleaseUndo;
// #288 Undo / Redo ๋ฐ๋ณต ์ Contain ์ค๋ฅ
// ์ฌ๋ฌ ๋ถ๋ชจ๋ก ์ด๋ ํ Undo ์ ์ด์ ์ผ๋ก ์๋ณต๋์ผ ํ๋ค.
procedure TestParentCmdHistory;
procedure BugUndoRedoIncorrectParent;
// #291 P1, C1์์ P1์ผ๋ก C1์ ๋ฎ๊ณ Undo*2 ์ดํ Redo*2 ์ P1์ C1์ ํฌํจํด์ผ ํ๋ค.
procedure TestMoveContainChildUndo2Redo2;
// #290: P1>P2>P3>P4์์ C1์ ๊ทธ๋ฆฌ๊ณ ํฌ๊ธฐ๋ฅผ ๋ณ๊ฒฝํด์ P3>P2>P1์ผ๋ก ๋ถ๋ชจ ๋ณ๊ฒฝ ํ Undo์ ๋ถ...
procedure TestResizeParentAndParent;
// #293 ํฌ๊ธฐ๋ณ๊ฒฝ>๋ถ๋ชจ์ด๋ ํ Undo 2ํ ์ ํฌ๊ธฐ๋ณ๊ฒฝ๊ณผ ์ด๋์ด ๋จ
procedure TestResizeAndMoveUndo2;
// #287 P1์ C1์ ์ฌ๋ฆฌ๊ณ P2๋ก C1์ ๋ฎ๊ณ , Delete ํ Undo*2 ์ C1๋ ์ฌ๋ผ์ง
procedure TestDeleteParentUndoHideChild;
// #286 P1์์ P2๋ก ์ด๋ํ C1์ Undo
procedure TestMoveBetweenParentUndo;
end;
implementation
uses
FMX.TestLib, ThItem, ThShapeItem, ThItemFactory, ThConsts, System.Math, DebugUtils;
{ TestTThItemGrouppingMulti }
procedure TestTThItemGrouppingHistory.TestMoveChild;
var
P1, C1: TThItem;
C1P_O, C1p_N: TPointF;
begin
P1 := DrawRectangle(10, 10, 150, 150, 'P1');
C1 := DrawRectangle(160, 160, 210, 210, 'C1');
C1P_O := C1.Position.Point;
TestLib.RunMousePath(MousePath.New
.Add(180, 180)
.Add(100, 30)
.Add(30, 30).Path);
Check(C1.Parent = P1, 'Contain');
C1P_N := C1.Position.Point;
FThothController.Undo;
Check(C1.Parent <> P1, Format('Undo: %s', [C1.Parent.Name]));
CheckEquals(C1.Position.Point.X, C1P_O.X, 'C1P_O');
FThothController.Redo;
Check(C1.Parent = P1, Format('Redo: %s', [C1.Parent.Name]));
Check(C1.Position.Point = C1P_N, 'C1P_N');
end;
procedure TestTThItemGrouppingHistory.TestMoveParent;
var
P1, C1, C2: TThItem;
begin
// C2๊ฐ ์ฌ๋ผ๊ฐ P1์ผ๋ก C1์ ๋ฎ๋๋ก ์ด๋ํ๋ค.
// Undo ์ P1์ด C2๋ฅผ ํฌํจํ์ฌ ์ ์๋ฆฌ์ ๊ฐ๊ณ
// C1์ด ๊ทธ๋๋ก ์์นํ๋์ง ํ์ธํ๋ค.
P1 := DrawRectangle(10, 10, 150, 150, 'P1');
C2 := DrawRectangle(20, 50, 50, 50, 'C2');
TThRectangle(C2).BgColor := claBlue;
C1 := DrawRectangle(130, 130, 180, 180, 'C1');
TThRectangle(C1).BgColor := claRed;
// P1์ผ๋ก C1 ๋ฎ๊ธฐ
TestLib.RunMouseClick(20, 20);
TestLib.RunMousePath(MousePath.New
.Add(50, 50)
.Add(100, 100)
.Add(140, 140).Path);
Check(C1.Parent = P1, 'Contain');
FThothController.Undo;
// C1์ ์์น, ๋ถ๋ชจ ํ์ธ
FCanvas.ClearSelection;
TestLib.RunMouseClick(150, 150);
CheckEquals(C1.Index, 1, 'C1.Index');
Check(FCanvas.SelectedItem = C1, 'Not selected C1');
Check(C1.Parent <> P1, Format('C1.Parent is %s(Not Parent <> P1)', [C1.Parent.Name]));
Check(C2.Parent = P1, 'C2.Parent is P1');
FThothController.Redo;
Check(C1.Parent = P1, Format('Redo: %s', [C1.Parent.Name]));
end;
procedure TestTThItemGrouppingHistory.TestAdd;
var
P1, C1: TThItem;
begin
P1 := DrawRectangle(10, 10, 150, 150, 'P1');
C1 := DrawRectangle(30, 30, 130, 130, 'C1');
Check(C1.Parent = P1, 'Contain');
FThothController.Undo;
Check(not Assigned(C1.Parent), Format('Undo: %s', ['C1.Parent is not null']));
FThothController.Redo;
Check(C1.Parent = P1, Format('Redo: %s', [C1.Parent.Name]));
end;
procedure TestTThItemGrouppingHistory.TestDeleteChild;
var
P1, C1: TThItem;
begin
P1 := DrawRectangle(10, 10, 150, 150, 'P1');
C1 := DrawRectangle(30, 30, 130, 130, 'C1');
Check(C1.Parent = P1, 'Contain');
TestLib.RunMouseClick(100, 100);
FCanvas.DeleteSelection;
Check(not Assigned(C1.Parent), Format('Delete: %s', ['C1.Parent is not null']));
FThothController.Undo;
Check(Assigned(C1.Parent), Format('Undo: %s', ['C1.Parent is null']));
Check(C1.Parent = P1, Format('Undo: %s', [C1.Parent.Name]));
FThothController.Redo;
CheckEquals(P1.ItemCount, 0, Format('ItemCount: %d', [P1.ItemCount]));
end;
procedure TestTThItemGrouppingHistory.TestResizeChild;
var
P1, C1: TThItem;
begin
P1 := DrawRectangle(110, 110, 250, 250, 'P1');
C1 := DrawRectangle(130, 130, 290, 290, 'C1');
Check(C1.Parent <> P1, 'Not contain');
CheckEquals(C1.Position.X, -20, Format('C1.Position.X : %f', [C1.Position.X]));
TestLib.RunMouseClick(200, 200);
TestLib.RunMousePath(MousePath.New
.Add(290, 290)
.Add(200, 200)
.Add(230, 230).Path);
Check(C1.Parent = P1, 'Contain');
FThothController.Undo;
Application.ProcessMessages;
Check(C1.Parent <> P1, 'Undo> Not contain');
CheckEquals(C1.Position.X, -20, Format('Undo> C1.Position.X : %f', [C1.Position.X]));
FThothController.Redo;
Application.ProcessMessages;
Check(C1.Parent = P1, 'Contain');
end;
procedure TestTThItemGrouppingHistory.TestResizeParent;
var
P1, C1: TThItem;
begin
P1 := DrawRectangle(110, 110, 250, 250, 'P1');
C1 := DrawRectangle(130, 130, 240, 240, 'C1');
Check(C1.Parent = P1, 'Contain');
CheckEquals(C1.Position.X, 20, Format('C1.Position.X : %f', [C1.Position.X]));
TestLib.RunMouseClick(120, 120);
TestLib.RunMousePath(MousePath.New
.Add(250, 250)
.Add(200, 200)
.Add(230, 230).Path);
Check(C1.Parent <> P1, 'Not contain');
FThothController.Undo;
Check(C1.Parent = P1, 'Undo> Contain');
CheckEquals(C1.Position.X, 20, Format('Undo> C1.Position.X : %f', [C1.Position.X]));
FThothController.Redo;
Check(C1.Parent <> P1, 'Redo> Not contain');
end;
procedure TestTThItemGrouppingHistory.TestRecoveryIndexMove;
var
P1, P2, C1: TThItem;
C1P: TPointF;
begin
// C1์์ P2๋ฅผ ๊ฒน์น๊ฒ ๊ทธ๋ฆฌ๊ณ
// C1์ P1์ ์ฌ๋ฆฐ ํ Undo ์ C1์ด ๊ทธ๋๋ก P2์๋์ ์์ด์ผ ํ๋ค.
P1 := DrawRectangle(10, 10, 130, 130, 'P1');
C1 := DrawRectangle(150, 150, 200, 200, 'C1');
P2 := DrawRectangle(170, 170, 250, 250, 'P2');
C1P := C1.Position.Point;
TestLib.RunMouseClick(180, 180);
Check(FCanvas.SelectedItem = P2);
TestLib.RunMouseClick(155, 155);
TestLib.RunMousePath(MousePath.New
.Add(160, 160)
.Add(100, 100)
.Add(30, 30).Path);
Check(C1.Parent = P1, Format('C1.Parent = %s', [C1.Name]));
FThothController.Undo;
TestLib.RunMouseClick(180, 180);
Check(FCanvas.SelectedItem = P2, Format('Selection Item = %s(Not P2)', [FCanvas.SelectedItem.Name]));
Check(C1.Position.Point = C1P, Format('C1.Position.Point: %f.%f', [C1.Position.Point.X, C1.Position.Point.Y]));
end;
procedure TestTThItemGrouppingHistory.TestMoveReleaseUndo;
var
P1, C1: TThItem;
begin
P1 := DrawRectangle(10, 10, 140, 140, 'P1');
C1 := DrawRectangle(50, 50, 120, 120, 'C1');
Check(C1.Parent = P1, Format('[0] C1.Parent = %s', [C1.Name]));
CheckEquals(C1.Position.X, 40);
// TestLib.RunMouseClick(65, 65);
TestLib.RunMousePath(MousePath.New
.Add(65, 65)
.Add(100, 100)
.Add(165, 165).Path);
Check(C1.Parent <> P1, Format('[1] C1.Parent <> %s', [C1.Name]));
CheckEquals(C1.AbsolutePoint.X, 0);
FThothController.Undo;
Check(C1.Parent = P1, Format('[2] C1.Parent = %s', [C1.Name]));
CheckEquals(C1.Position.X, 40);
end;
procedure TestTThItemGrouppingHistory.TestParentCmdHistory;
var
P1, P2, P3, C1: TThItem;
begin
// P1์ C1 ๊ทธ๋ฆผ
P1 := DrawRectangle(10, 210, 60, 260, 'P1');
P2 := DrawRectangle(70, 210, 120, 260, 'P2');
P3 := DrawRectangle(130, 210, 180, 260, 'P3');
C1 := DrawRectangle(10, 10, 40, 40, 'C1');
// Contain P1
TestLib.RunMousePath(MousePath.New
.Add(20, 20).Add(100, 100).Add(20, 220).Path);
Check(C1.Parent = P1, '[0] P1');
// Contain P2
TestLib.RunMousePath(MousePath.New
.Add(20, 220).Add(100, 100).Add(80, 220).Path);
Check(C1.Parent = P2, '[0] P2');
// Contain P3
TestLib.RunMousePath(MousePath.New
.Add(80, 220).Add(100, 100).Add(140, 220).Path);
Check(C1.Parent = P3, '[0] P3');
// Contain P3
TestLib.RunMousePath(MousePath.New
.Add(140, 220).Add(100, 100).Add(140, 20).Path);
Check(C1.Parent = FCanvas.Controls[0], '[0] Cotents');
Debug('Undo start');
// ๋ถ๋ชจ ๋๋๋ฆฌ๊ธฐ
FThothController.Undo;
Check(C1.Parent = P3, '[1] P3');
FThothController.Undo;
Check(C1.Parent = P2, '[1] P2');
FThothController.Undo;
Check(C1.Parent = P1, '[1] P1');
FThothController.Undo;
Check(C1.Parent = FCanvas.Controls[0], '[1] Cotents');
end;
procedure TestTThItemGrouppingHistory.BugUndoRedoIncorrectParent;
var
P1, C1: TThItem;
begin
// P1์ C1 ๊ทธ๋ฆผ
P1 := DrawRectangle(10, 10, 140, 140, 'P1');
C1 := DrawRectangle(50, 50, 120, 120, 'C1');
Check(C1.Parent = P1);
// P1์ด๋
// TestLib.RunMousePath(MousePath.New
// .Add(20, 20)
// .Add(100, 100)
// .Add(40, 40).Path);
// C1์ด๋(๋ฒ์ด๋๊ธฐ)
TestLib.RunMousePath(MousePath.New
.Add(100, 100)
.Add(100, 100)
.Add(180, 180).Path);
Check(C1.Parent <> P1);
FThothController.Undo; // C1 Move
Application.ProcessMessages;
// FThothController.Undo; // P1 Move
FThothController.Undo; // Draw C1
Application.ProcessMessages;
FThothController.Redo; // Draw C1
Application.ProcessMessages;
// FThothController.Redo; // P1 Move
FThothController.Redo; // C1 Move
Application.ProcessMessages;
Check(C1.Parent <> P1, C1.Parent.Name);
end;
procedure TestTThItemGrouppingHistory.TestMoveContainChildUndo2Redo2;
var
P1, C1: TThItem;
begin
// P1์ C1 ๊ทธ๋ฆผ
P1 := DrawRectangle(10, 10, 100, 100, 'P1');
C1 := DrawRectangle(150, 150, 180, 180, 'C1');
TestLib.RunMousePath(MousePath.New
.Add(80, 80)
.Add(100, 100)
.Add(170, 170).Path);
Check(C1.Parent = P1, '[0] C1.Parent = P1');
CheckEquals(C1.Position.X, 50, 4, Format('[0] %f', [C1.Position.X]));
FThothController.Undo; // C1 Move
Application.ProcessMessages;
// FThothController.Undo; // P1 Move
FThothController.Undo; // Draw C1
Application.ProcessMessages;
FThothController.Redo; // Draw C1
Application.ProcessMessages;
// FThothController.Redo; // P1 Move
FThothController.Redo; // C1 Move
Application.ProcessMessages;
Check(C1.Parent = P1, '[1] C1.Parent = P1');
CheckEquals(C1.Position.X, 50, 4, Format('[1] %f', [C1.Position.X]));
end;
procedure TestTThItemGrouppingHistory.TestResizeParentAndParent;
var
P1, P2, P3, P4, C1: TThItem;
begin
// P1์ C1 ๊ทธ๋ฆผ
P1 := DrawRectangle(10, 10, 250, 250, 'P1');
P2 := DrawRectangle(20, 20, 220, 220, 'P2');
P3 := DrawRectangle(30, 30, 190, 190, 'P3');
P4 := DrawRectangle(40, 40, 160, 160, 'P4');
C1 := DrawRectangle(100, 100, 130, 130, 'C1');
Check(C1.Parent = P4, '[0] P4');
CheckEquals(C1.Position.X, 60);
TestLib.RunMousePath(MousePath.New
.Add(130, 130).Add(100, 100)
.Add(170, 170).Path);
Check(C1.Parent = P3, '[0] P3');
CheckEquals(C1.Position.X, 70);
TestLib.RunMousePath(MousePath.New
.Add(170, 170).Add(100, 100)
.Add(200, 200).Path);
Check(C1.Parent = P2, '[0] P2');
CheckEquals(C1.Position.X, 80);
TestLib.RunMousePath(MousePath.New
.Add(200, 200).Add(100, 100)
.Add(230, 230).Path);
Check(C1.Parent = P1, '[0] P1');
CheckEquals(C1.Position.X, 90);
TestLib.RunMousePath(MousePath.New
.Add(230, 230).Add(100, 100)
.Add(260, 260).Path);
Check(C1.Parent <> P1, '[0] P1');
CheckEquals(C1.Position.X, -50);
// Undo Action
FThothController.Undo;
Application.ProcessMessages;
Check(C1.Parent = P1, '[1] P1');
CheckEquals(C1.Position.X, 90);
FThothController.Undo;
Application.ProcessMessages;
Check(C1.Parent = P2, '[1] P2');
CheckEquals(C1.Position.X, 80);
FThothController.Undo;
Application.ProcessMessages;
Check(C1.Parent = P3, '[1] P3');
CheckEquals(C1.Position.X, 70);
FThothController.Undo;
Application.ProcessMessages;
Check(C1.Parent = P4, '[1] P4');
CheckEquals(C1.Position.X, 60);
// RedoAction
FThothController.Redo;
Application.ProcessMessages;
Check(C1.Parent = P3, '[2] P3');
CheckEquals(C1.Position.X, 70);
FThothController.Redo;
Application.ProcessMessages;
Check(C1.Parent = P2, '[2] P2');
CheckEquals(C1.Position.X, 80);
FThothController.Redo;
Application.ProcessMessages;
Check(C1.Parent = P1, '[2] P1');
CheckEquals(C1.Position.X, 90);
FThothController.Redo;
Application.ProcessMessages;
Check(C1.Parent <> P1, '[2] P1');
CheckEquals(C1.Position.X, -50);
end;
procedure TestTThItemGrouppingHistory.TestResizeAndMoveUndo2;
var
P1, P2, C1: TThItem;
begin
P1 := DrawRectangle(10, 10, 140, 290, 'P1');
P2 := DrawRectangle(160, 10, 290, 290, 'P2');
C1 := DrawRectangle(170, 20, 280, 150, 'C1');
Check(C1.Parent = P2, '[0] C1.Parent = P2');
TestLib.RunMousePath(MousePath.New
.Add(280, 150).Add(100, 100)
.Add(220, 80).Path);
Check(C1.Parent = P2, '[1] C1.Parent = P2');
TestLib.RunMousePath(MousePath.New
.Add(180, 30).Add(100, 100)
.Add(30, 30).Path);
Check(C1.Parent = P1, '[1] C1.Parent = P1');
FThothController.Undo;
Application.ProcessMessages;
Check(C1.Parent = P2, '[2] C1.Parent = P2');
FThothController.Undo;
Application.ProcessMessages;
Check(C1.Parent = P2, '[3] C1.Parent = P2');
CheckEquals(C1.Position.X, 10);
end;
procedure TestTThItemGrouppingHistory.TestDeleteParentUndoHideChild;
var
P1, P2, C1: TThItem;
begin
P1 := DrawRectangle(10, 10, 150, 150, 'P1');
C1 := DrawRectangle(80, 80, 120, 120, 'C1');
P2 := DrawRectangle(30, 30, 140, 140, 'P2');
Check(C1.Parent = P2, '[0] C1.Parent = P2');
FCanvas.DeleteSelection;
FThothController.Undo;
Application.ProcessMessages;
Check(C1.Parent = P2, '[1] C1.Parent = P2');
FThothController.Undo;
Application.ProcessMessages;
Check(C1.Parent = P1, '[2] C1.Parent = P1');
end;
procedure TestTThItemGrouppingHistory.TestMoveBetweenParentUndo;
var
P1, P2, C1: TThItem;
begin
P1 := DrawRectangle(10, 10, 140, 290, 'P1');
P2 := DrawRectangle(160, 10, 290, 290, 'P2');
C1 := DrawRectangle(170, 20, 200, 50, 'C1');
Check(C1.Parent = P2, '[0] C1.Parent = P2');
TestLib.RunMousePath(MousePath.New
.Add(185, 35).Add(100, 100)
.Add(35, 35).Path);
Check(C1.Parent = P1, '[1] C1.Parent = P1');
FThothController.Undo;
Check(C1.Parent = P2, '[2] C1.Parent = P2');
FThothController.Redo;
Check(C1.Parent = P1, '[3] C1.Parent = P1');
end;
initialization
RegisterTest(TestTThItemGrouppingHistory.Suite);
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.