text stringlengths 14 6.51M |
|---|
unit uRDMCatalog;
{$WARN SYMBOL_PLATFORM OFF}
interface
uses
Windows, Messages, SysUtils, Classes, ComServ, ComObj, VCLCom, DataBkr,
DBClient, MRAppServer_TLB, StdVcl, ADODB, DB, Provider, uDMCalcPrice;
type
TRDMCatalog = class(TRemoteDataModule, IRDMCatalog)
dspSearchProduct: TDataSetProvider;
qrySearchProduct: TADOQuery;
dspLUVendor: TDataSetProvider;
qryLUVendor: TADOQuery;
dspLUDepartment: TDataSetProvider;
qryLUDepartment: TADOQuery;
dspLUCategory: TDataSetProvider;
qryLUCategory: TADOQuery;
dspLUSubCategory: TDataSetProvider;
qryLUSubCategory: TADOQuery;
qryListVendor: TADOQuery;
dspListVendor: TDataSetProvider;
procedure dspSearchProductBeforeGetRecords(Sender: TObject;
var OwnerData: OleVariant);
procedure dspSearchProductAfterGetRecords(Sender: TObject;
var OwnerData: OleVariant);
procedure dspListVendorBeforeUpdateRecord(Sender: TObject;
SourceDS: TDataSet; DeltaDS: TCustomClientDataSet;
UpdateKind: TUpdateKind; var Applied: Boolean);
private
FIRDMApplicationHub: IRDMApplicationHub;
FSQLConnection: TADOConnection;
FOldSQL: String;
procedure SetConnection;
protected
class procedure UpdateRegistry(Register: Boolean; const ClassID, ProgID: string); override;
function Get_RDMApplicationHub: IRDMApplicationHub; safecall;
procedure Set_RDMApplicationHub(const Value: IRDMApplicationHub); safecall;
function GetNewCostPriceList(const AFilter: WideString): OleVariant; safecall;
function UpdatePrices(ModelList: OleVariant; var MsgLog: WideString;
const ACatalogConfig: WideString): WordBool; safecall;
function GetNewInventoryList(const AFilter: WideString): OleVariant; safecall;
function UpdateInventory(ModelList: OleVariant; var MsgLog: WideString): WordBool; safecall;
public
{ Public declarations }
end;
var
RDMCatalog: TRDMCatalog;
RDMCatalogFactory: TComponentFactory;
implementation
uses uSqlFunctions, uMRSQLParam, uDMImportInventoryCatalog;
{$R *.DFM}
class procedure TRDMCatalog.UpdateRegistry(Register: Boolean; const ClassID, ProgID: string);
begin
if Register then
begin
inherited UpdateRegistry(Register, ClassID, ProgID);
EnableSocketTransport(ClassID);
EnableWebTransport(ClassID);
end else
begin
DisableSocketTransport(ClassID);
DisableWebTransport(ClassID);
inherited UpdateRegistry(Register, ClassID, ProgID);
end;
end;
function TRDMCatalog.Get_RDMApplicationHub: IRDMApplicationHub;
begin
Result := FIRDMApplicationHub;
end;
procedure TRDMCatalog.Set_RDMApplicationHub(const Value: IRDMApplicationHub);
begin
FIRDMApplicationHub := Value;
FSQLConnection := TADOConnection(FIRDMApplicationHub.SQLConnection);
SetConnection;
end;
function TRDMCatalog.GetNewCostPriceList(const AFilter: WideString): OleVariant;
begin
with TDMImportInventoryCatalog.Create(Self) do
try
SetConnection(FSQLConnection);
ConfigureCalcPrice(FSQLConnection);
Result := GetModelPricesList(AFilter);
finally
Free;
end;
end;
function TRDMCatalog.GetNewInventoryList(const AFilter: WideString): OleVariant;
begin
with TDMImportInventoryCatalog.Create(Self) do
try
SetConnection(FSQLConnection);
Result := GetInventoryList(AFilter);
finally
Free;
end;
end;
function TRDMCatalog.UpdateInventory(ModelList: OleVariant; var MsgLog: WideString): WordBool;
begin
with TDMImportInventoryCatalog.Create(Self) do
try
SetConnection(FSQLConnection);
Result := UpdateMRInventoryWithCatalog(ModelList);
MsgLog := Log.Text;
finally
Free;
end;
end;
function TRDMCatalog.UpdatePrices(ModelList: OleVariant;
var MsgLog: WideString; const ACatalogConfig: WideString): WordBool;
begin
with TDMImportInventoryCatalog.Create(Self) do
try
SetConnection(FSQLConnection);
Result := UpdateMRPricesWithCatalog(ModelList);
MsgLog := Log.Text;
finally
Free;
end;
end;
procedure TRDMCatalog.dspSearchProductBeforeGetRecords(Sender: TObject;
var OwnerData: OleVariant);
var
Param: TMRSQLParam;
begin
try
Param := TMRSQLParam.Create;
Param.ParamString := OwnerData;
if FOldSQL = '' then
FOldSQL := qrySearchProduct.SQL.Text;
if OwnerData <> '' then
begin
qrySearchProduct.SQL.Text := FOldSQL + ' WHERE ' + Param.GetWhereSQL;
end;
finally
FreeAndNil(Param);
end;
OwnerData := '';
end;
procedure TRDMCatalog.dspSearchProductAfterGetRecords(Sender: TObject;
var OwnerData: OleVariant);
begin
qrySearchProduct.SQL.Text := FOldSQL;
end;
procedure TRDMCatalog.SetConnection;
var
i: Integer;
begin
for i := 0 to Pred(ComponentCount) do
if Components[i] is TADOQuery then
TADOQuery(Components[i]).Connection := FSQLConnection
else if Components[i] is TADODataSet then
TADODataSet(Components[i]).Connection := FSQLConnection;
end;
procedure TRDMCatalog.dspListVendorBeforeUpdateRecord(Sender: TObject;
SourceDS: TDataSet; DeltaDS: TCustomClientDataSet;
UpdateKind: TUpdateKind; var Applied: Boolean);
var
sSQL : String;
IDVendorMR : String;
begin
IDVendorMR := DeltaDS.FieldByName('IDVendorMR').AsString;
if IDVendorMR = '' then
IDVendorMR := 'NULL';
sSQL := Format('UPDATE MRCatalogDB..Vendors Set IDVendorMR = %S WHERE IDVendor = %S',
[IDVendorMR, DeltaDS.FieldByName('IDVendor').OldValue]);
FSQLConnection.Execute(sSQL);
Applied := True;
end;
initialization
RDMCatalogFactory := TComponentFactory.Create(ComServer, TRDMCatalog,
Class_RDMCatalog, ciInternal, tmApartment);
end.
|
namespace SnapTileSample;
interface
uses
System,
System.Collections.Generic,
System.Linq,
System.Text,
Windows.UI.Xaml.Media,
System,
Windows.UI.Xaml.Data,
Windows.UI.Xaml.Media,
Windows.UI.Xaml.Media.Imaging;
type
Item = public class(System.ComponentModel.INotifyPropertyChanged)
public
event PropertyChanged: System.ComponentModel.PropertyChangedEventHandler;
protected
method OnPropertyChanged(propertyName: System.String); virtual;
private
var _Title: System.String := System.String.Empty;
public
property Title: System.String read self._Title write set_Title;
method set_Title(value: System.String);
private
var _Subtitle: System.String := System.String.Empty;
public
property Subtitle: System.String read self._Subtitle write set_Subtitle;
method set_Subtitle(value: System.String);
private
var _Image: ImageSource := nil;
public
property Image: ImageSource read self._Image write set_Image;
method set_Image(value: ImageSource);
method SetImage(baseUri: Uri; path: String);
private
var _Link: System.String := System.String.Empty;
public
property Link: System.String read self._Link write set_Link;
method set_Link(value: System.String);
private
var _Category: System.String := System.String.Empty;
public
property Category: System.String read self._Category write set_Category;
method set_Category(value: System.String);
private
var _Description: System.String := System.String.Empty;
public
property Description: System.String read self._Description write set_Description;
method set_Description(value: System.String);
private
var _Content: System.String := System.String.Empty;
public
property Content: System.String read self._Content write set_Content;
method set_Content(value: System.String);
end;
GroupInfoList<T> = public class(List<System.Object>)
public
property Key: System.Object;
method GetEnumerator: IEnumerator<System.Object>; reintroduce;
end;
DataSource = public class
public
constructor ;
private
var _Collection: ItemCollection := new ItemCollection();
public
property Collection: ItemCollection read _Collection;
assembly
method GetGroupsByCategory: List<GroupInfoList<System.Object>>;
method GetGroupsByLetter: List<GroupInfoList<System.Object>>;
end;
// Workaround: data binding works best with an enumeration of objects that does not implement IList
ItemCollection = public class(IEnumerable<Item>)
private
var itemCollection: System.Collections.ObjectModel.ObservableCollection<Item> := new System.Collections.ObjectModel.ObservableCollection<Item>();
public
method GetEnumerator: IEnumerator<Item>;
private
method GetEnumeratorOld: System.Collections.IEnumerator; implements System.Collections.IEnumerable.GetEnumerator;
public
method &Add(item: Item);
end;
implementation
method Item.OnPropertyChanged(propertyName: System.String);
begin
if self.PropertyChanged <> nil then begin
self.PropertyChanged(self, new System.ComponentModel.PropertyChangedEventArgs(propertyName))
end
end;
method Item.set_Title(value: System.String); begin
if self._Title <> value then begin
self._Title := value;
self.OnPropertyChanged('Title')
end
end;
method Item.set_Subtitle(value: System.String); begin
if self._Subtitle <> value then begin
self._Subtitle := value;
self.OnPropertyChanged('Subtitle')
end
end;
method Item.set_Image(value: ImageSource); begin
if self._Image <> value then begin
self._Image := value;
self.OnPropertyChanged('Image')
end
end;
method Item.SetImage(baseUri: Uri; path: String);
begin
Image := new BitmapImage(new Uri(baseUri, path))
end;
method Item.set_Link(value: System.String); begin
if self._Link <> value then begin
self._Link := value;
self.OnPropertyChanged('Link')
end
end;
method Item.set_Category(value: System.String); begin
if self._Category <> value then begin
self._Category := value;
self.OnPropertyChanged('Category')
end
end;
method Item.set_Description(value: System.String); begin
if self._Description <> value then begin
self._Description := value;
self.OnPropertyChanged('Description')
end
end;
method Item.set_Content(value: System.String); begin
if self._Content <> value then begin
self._Content := value;
self.OnPropertyChanged('Content')
end
end;
method GroupInfoList<T>.GetEnumerator: IEnumerator<System.Object>;
begin
exit System.Collections.Generic.IEnumerator<System.Object>(inherited GetEnumerator())
end;
constructor DataSource;
begin
var item: Item;
var LONG_LOREM_IPSUM: String := String.Format('{0}'#10#10'{0}'#10#10'{0}'#10#10'{0}', 'Curabitur class aliquam vestibulum nam curae maecenas sed integer cras phasellus suspendisse quisque donec dis praesent accumsan bibendum pellentesque condimentum adipiscing etiam consequat vivamus dictumst aliquam duis convallis scelerisque est parturient ullamcorper aliquet fusce suspendisse nunc hac eleifend amet blandit facilisi condimentum commodo scelerisque faucibus aenean ullamcorper ante mauris dignissim consectetuer nullam lorem vestibulum habitant conubia elementum pellentesque morbi facilisis arcu sollicitudin diam cubilia aptent vestibulum auctor eget dapibus pellentesque inceptos leo egestas interdum nulla consectetuer suspendisse adipiscing pellentesque proin lobortis sollicitudin augue elit mus congue fermentum parturient fringilla euismod feugiat');
var _baseUri: Uri := new Uri('ms-appx:///');
item := new Item(
Title := 'Data Abstract',
Subtitle := 'Data Abstract for Java',
Link := 'http://www.remobjects.com/da/java',
Category := 'Java',
Description := 'Premier multi-tier data access.',
Content := LONG_LOREM_IPSUM);
item.SetImage(_baseUri, 'SampleData/Images/da.png');
Collection.Add(item);
item := new Item(
Title := 'Data Abstract',
Subtitle := 'Data Abstract for .NET',
Link := 'http://www.remobjects.com/da/net',
Category := '.NET',
Description := 'Premier multi-tier data access.',
Content := LONG_LOREM_IPSUM);
item.SetImage(_baseUri, 'SampleData/Images/da.png');
Collection.Add(item);
item := new Item(
Title := 'Data Abstract',
Subtitle := 'Data Abstract for Delphi',
Link := 'http://www.remobjects.com/da/delphi',
Category := 'Delphi',
Description := 'Premier multi-tier data access.',
Content := LONG_LOREM_IPSUM);
item.SetImage(_baseUri, 'SampleData/Images/da.png');
Collection.Add(item);
item := new Item(
Title := 'Data Abstract',
Subtitle := 'Data Abstract for Xcode',
Link := 'http://www.remobjects.com/da/xcode',
Category := 'Xcode',
Description := 'Premier multi-tier data access.',
Content := LONG_LOREM_IPSUM);
item.SetImage(_baseUri, 'SampleData/Images/da.png');
Collection.Add(item);
item := new Item(
Title := 'RemObjects SDK',
Subtitle := 'Data Abstract for Xcode',
Link := 'http://www.remobjects.com/ro/xcode',
Category := 'Xcode',
Description := 'Award-winning cross-platform remoting.',
Content := LONG_LOREM_IPSUM);
item.SetImage(_baseUri, 'SampleData/Images/ro.png');
Collection.Add(item);
item := new Item(
Title := 'RemObjects SDK',
Subtitle := 'Data Abstract for Delphi',
Link := 'http://www.remobjects.com/ro/delphi',
Category := 'Delphi',
Description := 'Award-winning cross-platform remoting.',
Content := LONG_LOREM_IPSUM);
item.SetImage(_baseUri, 'SampleData/Images/ro.png');
Collection.Add(item);
item := new Item(
Title := 'RemObjects SDK',
Subtitle := 'Data Abstract for Java',
Link := 'http://www.remobjects.com/ro/java',
Category := 'Java',
Description := 'Award-winning cross-platform remoting.',
Content := LONG_LOREM_IPSUM);
item.SetImage(_baseUri, 'SampleData/Images/ro.png');
Collection.Add(item);
item := new Item(
Title := 'RemObjects SDK',
Subtitle := 'Data Abstract for .NET',
Link := 'http://www.remobjects.com/ro/net',
Category := '.NET',
Description := 'Award-winning cross-platform remoting.',
Content := LONG_LOREM_IPSUM);
item.SetImage(_baseUri, 'SampleData/Images/ro.png');
Collection.Add(item);
item := new Item(
Title := 'Oxygene',
Subtitle := 'Oxygene for .NET',
Link := 'http://www.remobjects.com/oxygene/net',
Category := '.NET',
Description := 'Next Generation Object Pascal for .NET.',
Content := LONG_LOREM_IPSUM);
item.SetImage(_baseUri, 'SampleData/Images/oxygene.png');
Collection.Add(item);
item := new Item(
Title := 'Oxygene',
Subtitle := 'Oxygene for Java',
Link := 'http://www.remobjects.com/oxygene/java',
Category := 'Java',
Description := "This is Not your daddy's Pascal!",
Content := LONG_LOREM_IPSUM);
item.SetImage(_baseUri, 'SampleData/Images/oxygene.png');
Collection.Add(item);
item := new Item(
Title := 'Hydra',
Subtitle := 'Hydra for Delphi and .NET',
Link := 'http://www.remobjects.com/hydra',
Category := 'Delphi',
Description := "Why choose? Mix Delphi & .NET!",
Content := LONG_LOREM_IPSUM);
item.SetImage(_baseUri, 'SampleData/Images/hydra.png');
Collection.Add(item);
item := new Item(
Title := 'Oxfuscator',
Subtitle := 'Oxfuscator for .NET',
Link := 'http://www.remobjects.com/oxfuscator',
Category := '.NET',
Description := "Assembly Obfuscation for .NET",
Content := LONG_LOREM_IPSUM);
item.SetImage(_baseUri, 'SampleData/Images/oxfuscator.png');
Collection.Add(item);
item := new Item(
Title := 'Pascal Script',
Subtitle := 'RemObjects Pascal Script',
Link := 'http://www.remobjects.com/ps',
Category := 'Delphi',
Description := "A Pascal-based scripting language for Delphi.",
Content := LONG_LOREM_IPSUM);
item.SetImage(_baseUri, 'SampleData/Images/pascalscript.png');
Collection.Add(item);
item := new Item(
Title := 'RemObjects Script',
Subtitle := '(ECMAScript) JavaScript',
Link := 'http://www.remobjects.com/script',
Category := '.NET',
Description := "100% native script engine for .NET.",
Content := LONG_LOREM_IPSUM);
item.SetImage(_baseUri, 'SampleData/Images/script.png');
Collection.Add(item);
end;
method DataSource.GetGroupsByCategory: List<GroupInfoList<System.Object>>;
begin
var groups: List<GroupInfoList<System.Object>> := new List<GroupInfoList<System.Object>>();
var query := from item in Collection
order by item.Category asc
group item by item.Category into g
select new class (GroupName := g.Key, Items := g);
for each g in query do begin
var info: GroupInfoList<System.Object> := new GroupInfoList<System.Object>();
info.Key := g.GroupName;
for each item in g.Items do begin
info.Add(item)
end;
groups.Add(info)
end;
exit groups
end;
method DataSource.GetGroupsByLetter: List<GroupInfoList<System.Object>>;
begin
var groups: List<GroupInfoList<System.Object>> := new List<GroupInfoList<System.Object>>();
var query := from item in Collection
order by item.Title asc
group item by item.Title[0] into g
select new class (GroupName := g.Key,
Items := g
);
for each g in query do begin
var info: GroupInfoList<System.Object> := new GroupInfoList<System.Object>();
info.Key := g.GroupName;
for each item in g.Items do begin
info.Add(item)
end;
groups.Add(info)
end;
exit groups
end;
method ItemCollection.GetEnumerator: IEnumerator<Item>;
begin
exit itemCollection.GetEnumerator()
end;
method ItemCollection.GetEnumeratorOld: System.Collections.IEnumerator;
begin
exit itemCollection.GetEnumerator()
end;
method ItemCollection.&Add(item: Item);
begin
itemCollection.Add(item)
end;
end.
|
program HowToCreateProgressBar;
uses
SwinGame, sgTypes;
procedure Main();
var
partRect: Rectangle;
fullBar: Bitmap;
width: LongInt;
size: rectangle;
begin
OpenGraphicsWindow('Progress Bar', 400, 400);
LoadBitmapNamed('empty', 'progress_empty.png');
fullBar := LoadBitmapNamed('full', 'progress_full.png');
width := 0;
partRect := RectangleFrom(0, 0, width, 39);
repeat
ProcessEvents();
ClearScreen(ColorWhite);
DrawText('Press Space to progress :)', ColorBlack, 10, 10);
DrawBitmap ('empty', 46, 180);
if KeyTyped(SpaceKey) then
begin
width := width + 31;
partRect := RectangleFrom(0, 0, width, 39);
end;
DrawBitmapPart (fullBar, partRect, 46, 180);
RefreshScreen();
until WindowCloseRequested();
ReleaseAllResources();
end;
begin
Main();
end. |
unit DSA.Hash.HashTable;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
Generics.Collections,
Rtti,
DSA.Interfaces.DataStructure,
DSA.Tree.AVLTreeMap,
DSA.Tree.BSTMap,
DSA.Tree.RBTree,
DSA.Utils;
type
{ THashTable }
generic THashTable<K, V, TKeyCmp> = class
private
type
TTreeMap_K_V = specialize TAVLTreeMap<K, V, TKeyCmp>;
TArray_treeMap = array of TTreeMap_K_V;
TPtrV = specialize TPtr_V<V>;
const
UPPER_TOL = 10; // 容量上界
LOWER_TOL = 2; // 容量下界
INIT_CAPCITY = 7; // 初始容量
var
__hashTable: TArray_treeMap;
__capcity: integer;
__size: integer;
function __hash(key: K): integer;
procedure __resize(newCapcity: integer);
public
constructor Create(newCapcity: integer = INIT_CAPCITY);
destructor Destroy; override;
function GetSize(): integer;
procedure Add(key: K; Value: V);
function Remove(key: K): V;
procedure Set_(key: K; Value: V);
function Contains(key: K): boolean;
function Get(key: K): TPtrV;
end;
procedure Main;
implementation
type
TBSTMap_str_int = specialize TBSTMap<string, integer, TComparer_str>;
TAVLTree_str_int = specialize TAVLTreeMap<string, integer, TComparer_str>;
TRBTree_str_int = specialize TRBTree<string, integer, TComparer_str>;
THashTable_str_int = specialize THashTable<string, integer, TComparer_str>;
TDictionary_str_int = specialize TDictionary<string, integer>;
procedure Main;
var
startTime, endTime: cardinal;
words: TArrayList_str;
i: integer;
bst: TBSTMap_str_int;
alt: TAVLTree_str_int;
rbt: TRBTree_str_int;
ht: THashTable_str_int;
dtn: TDictionary_str_int;
vTime: string;
begin
words := TArrayList_str.Create;
Writeln(A_FILE_NAME + ':');
if TDsaUtils.ReadFile(FILE_PATH + A_FILE_NAME, words) then
begin
Writeln('Total words: ', words.GetSize);
end;
// BSTMap
startTime := TThread.GetTickCount64;
bst := TBSTMap_str_int.Create;
for i := 0 to words.GetSize - 1 do
begin
if bst.Contains(words[i]) then
bst.Set_(words[i], bst.Get(words[i]).PValue^ + 1)
else
bst.Add(words[i], 1);
end;
for i := 0 to words.GetSize - 1 do
bst.Contains(words[i]);
endTime := TThread.GetTickCount64;
vTime := FloatToStr((endTime - startTime) / 1000);
Writeln('BST: ', vTime, ' s');
// AVLTree
startTime := TThread.GetTickCount64;
alt := TAVLTree_str_int.Create;
for i := 0 to words.GetSize - 1 do
begin
if alt.Contains(words[i]) then
alt.Set_(words[i], alt.Get(words[i]).PValue^ + 1)
else
alt.Add(words[i], 1);
end;
for i := 0 to words.GetSize - 1 do
alt.Contains(words[i]);
endTime := TThread.GetTickCount64;
vTime := FloatToStr((endTime - startTime) / 1000);
Writeln('AVLTree: ', vTime, ' s');
// RBTree
startTime := TThread.GetTickCount64;
rbt := TRBTree_str_int.Create;
for i := 0 to words.GetSize - 1 do
begin
if rbt.Contains(words[i]) then
rbt.Set_(words[i], rbt.Get(words[i]).PValue^ + 1)
else
rbt.Add(words[i], 1);
end;
for i := 0 to words.GetSize - 1 do
rbt.Contains(words[i]);
endTime := TThread.GetTickCount64;
vTime := FloatToStr((endTime - startTime) / 1000);
Writeln('RBTree: ', vTime, ' s');
// HashTable
startTime := TThread.GetTickCount64;
ht := THashTable_str_int.Create;
for i := 0 to words.GetSize - 1 do
begin
if ht.Contains(words[i]) then
ht.Set_(words[i], ht.Get(words[i]).PValue^ + 1)
else
ht.Add(words[i], 1);
end;
for i := 0 to words.GetSize - 1 do
ht.Contains(words[i]);
endTime := TThread.GetTickCount64;
vTime := FloatToStr((endTime - startTime) / 1000);
Writeln('HashTable: ', vTime, ' s');
// Dictionary
startTime := TThread.GetTickCount64;
dtn := TDictionary_str_int.Create;
for i := 0 to words.GetSize - 1 do
begin
if dtn.containsKey(words[i]) then
//dtn.KeyData[words[i]] := 1d
else
dtn.Add(words[i], 1);
end;
for i := 0 to words.GetSize - 1 do
dtn.containsKey(words[i]);
endTime := TThread.GetTickCount64;
vTime := FloatToStr((endTime - startTime) / 1000);
Writeln('Dictionary: ', vTime, ' s');
end;
{ THashTable }
procedure THashTable.Add(key: K; Value: V);
var
map: TTreeMap_K_V;
hc: integer;
begin
hc := __hash(key);
map := __hashTable[hc];
if map.Contains(key) then
begin
map.Set_(key, Value);
end
else
begin
map.Add(key, Value);
Inc(__size);
if __size >= UPPER_TOL * __capcity then
__resize(2 * __capcity);
end;
end;
function THashTable.Contains(key: K): boolean;
begin
Result := __hashTable[__hash(key)].Contains(key);
end;
constructor THashTable.Create(newCapcity: integer);
var
i: integer;
begin
__capcity := newCapcity;
__size := 0;
SetLength(__hashTable, newCapcity);
for i := 0 to newCapcity - 1 do
__hashTable[i] := TTreeMap_K_V.Create;
end;
destructor THashTable.Destroy;
var
i: integer;
begin
for i := 0 to __capcity - 1 do
__hashTable[i].Free;
inherited;
end;
function THashTable.Get(key: K): TPtrV;
begin
Result := __hashTable[__hash(key)].Get(key);
end;
function THashTable.GetSize(): integer;
begin
Result := __size;
end;
function THashTable.Remove(key: K): V;
var
index: integer;
ret: V;
begin
index := __hash(key);
ret := default(V);
if __hashTable[index].Contains(key) then
begin
__hashTable[index].Remove(key);
Dec(__size);
if (__size < LOWER_TOL * __capcity) and ((__capcity div 2) >=
INIT_CAPCITY) then
__resize(__capcity div 2);
end;
Result := ret;
end;
procedure THashTable.Set_(key: K; Value: V);
var
map: TTreeMap_K_V;
begin
map := __hashTable[__hash(key)];
if not map.Contains(key) then
raise Exception.Create('key doesn''t exist.');
map.Set_(key, Value);
end;
function THashTable.__hash(key: K): integer;
var
Value: TValue;
begin
TValue.Make(@key, TypeInfo(K), Value);
Result := (Value.ToString.GetHashCode and $7FFFFFFF) mod __capcity;
end;
procedure THashTable.__resize(newCapcity: integer);
var
newHashTable: TArray_treeMap;
i, oldCapcity: integer;
map: TTreeMap_K_V;
key: K;
begin
SetLength(newHashTable, newCapcity);
for i := 0 to newCapcity - 1 do
newHashTable[i] := TTreeMap_K_V.Create;
oldCapcity := __capcity;
Self.__capcity := newCapcity;
for i := 0 to oldCapcity - 1 do
begin
map := __hashTable[i];
for key in map.KeySets.ToArray do
begin
newHashTable[__hash(key)].Add(key, map.Get(key).PValue^);
end;
end;
__hashTable := newHashTable;
end;
end.
|
unit IdResourceStringsOpenSSL;
interface
resourcestring
{IdOpenSSL}
RSOSSFailedToLoad = 'Fehler beim Laden von %s.';
RSOSSLModeNotSet = 'Der Modus wurde nicht gesetzt.';
RSOSSLCouldNotLoadSSLLibrary = 'SSL.-Bibliothek konnte nicht geladen werden.';
RSOSSLStatusString = 'SSL-Status: "%s"';
RSOSSLConnectionDropped = 'Die SSL-Verbindung ging verloren.';
RSOSSLCertificateLookup = 'Fehler bei der Anforderung eines SSL-Zertifikats.';
RSOSSLInternal = 'SSL-Bibliotheksinterner Fehler.';
//callback where strings
RSOSSLAlert = '%s Meldung';
RSOSSLReadAlert = '%s Lesemeldung';
RSOSSLWriteAlert = '%s Schreibmeldung';
RSOSSLAcceptLoop = 'Annahme-Schleife';
RSOSSLAcceptError = 'Fehler bei der Annahme';
RSOSSLAcceptFailed = 'Annahme fehlgeschlagen';
RSOSSLAcceptExit = 'Annahme-Ende';
RSOSSLConnectLoop = 'Verbindungsschleife';
RSOSSLConnectError = 'Fehler bei der Verbindung';
RSOSSLConnectFailed = 'Verbindung fehlgeschlagen';
RSOSSLConnectExit = 'Verbindungsende';
RSOSSLHandshakeStart = 'Handshake-Start';
RSOSSLHandshakeDone = 'Handshake ausgeführt';
implementation
end.
|
unit UserScript;
// globally scoped variables
var
formlistCount: Integer;
kFormlist: IInterface;
lsForms, lsItems: TStringList;
function Initialize: Integer;
begin
// create string lists
lsForms := TStringList.Create;
lsItems := TStringList.Create;
// initialize selected FLST record count
formlistCount := 0;
end;
function Process(e: IInterface): Integer;
begin
// process loops through selected records
// - when FLST found, make record globally referenceable
// - when all other records found, add Form ID string to string list
// - if more than one FLST record was found, throw exception
if Signature(e) = 'FLST' then begin
kFormlist := e;
Inc(formlistCount);
AssertEqual(formlistCount, 1, '[FATAL] Cannot have more than one FLST record selected');
end else
lsForms.Add(IntToHex(FormID(e), 8));
end;
function Finalize: Integer;
var
i: Integer;
kParent, kChild, kRecord: IInterface;
begin
AssertNotEqual(formlistCount, 0, '[FATAL] Cannot populate formlist because no FLST record was selected');
AssertNotEqual(lsForms.Count, 0, '[FATAL] Cannot populate formlist because no records were selected');
try
// return 'FormIDs' element, or create the 'FormIDs' element if needed
kParent := ElementByPath(kFormlist, 'FormIDs');
if not Assigned(kParent) then
kParent := Add(kFormlist, 'FormIDs', false);
// loop through FLST and initialize temporary list of FormID strings
// we'll use this list to prevent duplicates from being added
for i := 0 to Pred(ElementCount(kParent)) do begin
kChild := ElementByIndex(kParent, i);
// do not add null items
if pos('NULL', GetEditValue(kChild)) > 0 then
continue;
lsItems.Add(IntToHex(FormID(LinksTo(kChild)), 8));
end;
// loop through selected records
for i := 0 to Pred(lsForms.Count) do begin
// do not add duplicates
if lsItems.IndexOf(lsForms[i]) > -1 then
continue;
// assign item element and set value to FormID string
kChild := ElementAssign(kParent, HighInteger, nil, True);
SetEditValue(kChild, lsForms[i]);
// retrieve the added record so we can print the log message
kRecord := RecordByFormID(GetFile(kParent), StrToInt('$' + lsForms[i]), false);
AddMessage('[INFO] Added item to formlist: [' + Signature(kRecord) + ':' + lsForms[i] + '] ' + EditorID(kRecord));
end;
// reinitialize changed FormIDs element
kParent := ElementByPath(kFormlist, 'FormIDs');
// loop through formlist and remove NULL items
for i := 0 to Pred(ElementCount(kParent)) do begin
kChild := ElementByIndex(kParent, i);
if pos('NULL', GetEditValue(kChild)) > 0 then
Remove(kChild);
end;
except
on e : Exception do
raise Exception.Create('[FATAL] Could not populate formlist because: ' + e.Message);
end;
end;
// unit test procedures
procedure AssertEqual(a: Variant; b: Variant; s: String = 'FAIL');
begin
if a <> b then
raise Exception.Create(s);
end;
procedure AssertNotEqual(a: Variant; b: Variant; s: String = 'FAIL');
begin
if a = b then
raise Exception.Create(s);
end;
end.
|
unit HS4D.Send;
interface
uses
RESTRequest4D,
HS4D.Interfaces,
System.Classes,
Vcl.ExtCtrls;
type
THS4DSend = class(TInterfacedObject, iHS4DSend)
private
FParent : iHS4D;
FFileName : String;
FContentType : String;
FFileStream : TBytesStream;
FEndPoint : string;
FContent : string;
FPath : string;
public
constructor Create(Parent : iHS4D);
destructor Destroy; override;
class function New (aParent : iHS4D): iHS4DSend;
function Send : iHS4DSend;
function FileName( aValue : String ) : iHS4DSend;
function ContentType( aValue : String ) : iHS4DSend;
function EndPoint(aValue : string) : iHS4DSend;
function Path(aValue : string) : iHS4DSend;
function FileStream( aValue : TBytesStream ) : iHS4DSend; overload;
function FileStream( aValue : TImage ) : iHS4DSend; overload;
function ToString : string;
end;
implementation
{ THS4DSend }
function THS4DSend.ContentType(aValue: String): iHS4DSend;
begin
Result:= Self;
FContentType:= aValue;
end;
constructor THS4DSend.Create(Parent : iHS4D);
begin
FParent:= Parent;
end;
destructor THS4DSend.Destroy;
begin
inherited;
end;
function THS4DSend.EndPoint(aValue: string): iHS4DSend;
begin
result:= self;
FEndPoint:= aValue;
end;
function THS4DSend.FileName(aValue: String): iHS4DSend;
begin
Result:= Self;
FFileName:= aValue;
end;
function THS4DSend.FileStream(aValue: TBytesStream): iHS4DSend;
begin
Result := Self;
FFileStream := aValue;
end;
function THS4DSend.FileStream(aValue: TImage): iHS4DSend;
begin
Result := Self;
if not Assigned(FFileStream) then
FFileStream := TBytesStream.Create();
{$IFDEF HAS_FMX}
aValue.Bitmap.SaveToStream(FFileStream);
{$ELSE}
aValue.Picture.SaveToStream(FFileStream);
{$ENDIF}
end;
class function THS4DSend.New(aParent : iHS4D): iHS4DSend;
begin
Result:= Self.Create(aParent);
end;
function THS4DSend.Path(aValue: string): iHS4DSend;
begin
Result:= Self;
FPath:= aValue;
end;
function THS4DSend.Send : iHS4DSend;
var
LResponse: IResponse;
lHost : string;
begin
Result:= Self;
lHost:= copy(FParent.Credential.BaseURL,(pos('//',FParent.Credential.BaseURL)+2), length(FParent.Credential.BaseURL));
lHost:= copy(lHost,0,(pos(':',lHost)-1));
LResponse :=
TRequest.New.BaseURL(FParent.Credential.BaseURL+FEndPoint)
.ContentType(FContentType)
.AddHeader('FileName', FFileName)
.AddHeader('Path', FPath)
.AddHeader('Host', lHost)
.Accept('*/*')
.AddBody(FFileStream)
.Post;
if LResponse.StatusCode = 201 then
FContent:= FParent.Credential.BaseURL + LResponse.Content;
end;
function THS4DSend.ToString: string;
begin
Result:= FContent;
end;
end.
|
unit uMain;
interface
uses
System.JSON,System.Generics.Collections, FMX.Ani,
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, FMX.StdCtrls, FMX.Objects,
FMX.TabControl, FMX.Layouts, FMX.Effects;
type
TForm2 = class(TForm)
Memo1: TMemo;
Rectangle1: TRectangle;
Label1: TLabel;
Label2: TLabel;
TabControl1: TTabControl;
GridPanelLayout1: TGridPanelLayout;
Rectangle2: TRectangle;
Rectangle3: TRectangle;
Rectangle4: TRectangle;
ShadowEffect1: TShadowEffect;
Text1: TText;
Text2: TText;
procedure RespostaClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Label2Click(Sender: TObject);
procedure Text2Click(Sender: TObject);
procedure Text1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Animacao :TFloatAnimation;
Fundo :TRectangle;
ListaText : TObjectList<TText>;
procedure Quiz(AJSON :String);
procedure AnimacaoFinish(Sender: TObject);
procedure ContinuarClick(Sender: TObject);
procedure Proximo;
end;
var
Form2: TForm2;
implementation
{$R *.fmx}
procedure TForm2.AnimacaoFinish(Sender: TObject);
begin
if TFloatAnimation(Sender).Tag = 0 then begin
TFloatAnimation(Sender).Tag := 2;
TFloatAnimation(Sender).StopValue := Self.Height + 100;
end else if TFloatAnimation(Sender).Tag = 1 then begin
TFloatAnimation(Sender).Tag := 3;
TFloatAnimation(Sender).Duration := 1.5;
TFloatAnimation(Sender).Delay := 1;
TFloatAnimation(Sender).StopValue := Self.Height + 150;
TFloatAnimation(Sender).Start;
end else Fundo.DisposeOf;
end;
procedure TForm2.ContinuarClick(Sender: TObject);
begin
Animacao.Start;
end;
procedure TForm2.FormClose(Sender: TObject; var Action: TCloseAction);
begin
ListaText.DisposeOf;
end;
procedure TForm2.FormCreate(Sender: TObject);
begin
Rectangle2.Visible := false;
Rectangle3.Visible := false;
Label1.Visible := false;
Label2.Visible := false;
Quiz(Memo1.Text);
end;
procedure TForm2.Label2Click(Sender: TObject);
begin
TabControl1.Previous;
end;
procedure TForm2.Proximo;
var
I,J,A : Integer;
Respondeu : Boolean;
Texto :TText;
FundoBotao,
Resultado : TRectangle;
begin
Respondeu := false;
for I := 0 to ListaText.Count -1 do begin
if ListaText.Items[I].StyleName = IntToStr(TTabItem(TabControl1.ActiveTab).Index) then begin
if (ListaText.Items[I].TextSettings.Font.Style <> []) then begin
Respondeu := True;
end;
end;
end;
if not Respondeu then begin
Fundo := TRectangle.Create(Self);
Fundo.Align := TAlignLayout.Contents;
Fundo.Fill.Color := TAlphaColorRec.Null;
Fundo.Stroke.Color := TAlphaColorRec.Null;
Fundo.Opacity := 0.7;
Self.AddObject(Fundo);
Resultado := TRectangle.Create(Self);
// Resultado.Align := TAlignLayout.Bottom;
Resultado.Height := 120;
Resultado.Position.Y := Self.Height + Resultado.Height;
Resultado.Width := Self.Width;
Resultado.Position.X := 0;
Resultado.Fill.Color := TAlphaColorRec.Black;
Resultado.Stroke.Color := TAlphaColorRec.Black;
Self.AddObject(Resultado);
Texto := TText.Create(Resultado);
Texto.Text := 'Escolha uma resposta';
Texto.Align := TAlignLayout.client;
Texto.TextSettings.Font.Size := 16;
Texto.TextSettings.FontColor := TAlphaColorRec.Darkgrey;
Texto.TextSettings.HorzAlign := TTextAlign.Center;
Resultado.AddObject(Texto);
Animacao := TFloatAnimation.Create(Resultado);
Resultado.AddObject(Animacao);
Animacao.Tag := 1;
Animacao.Duration := 0.5;
Animacao.StopValue := (Self.Height - 160) ;
Animacao.StartFromCurrent := True;
Animacao.PropertyName := 'Position.Y';
Animacao.OnFinish := AnimacaoFinish;
Animacao.Interpolation := TInterpolationType.Linear;
Animacao.Start;
abort;
end;
if TTabItem(TabControl1.ActiveTab).Index = TabControl1.TabCount-1 then begin
Rectangle2.Visible := True;
A := 0;
for J := 0 to TabControl1.TabCount-1 do begin
for I := 0 to ListaText.Count -1 do begin
if ListaText.Items[I].StyleName = IntToStr(J) then begin
if (ListaText.Items[I].Tag = 1) and (ListaText.Items[I].TextSettings.Font.Style <> []) then begin
ListaText.Items[I].TextSettings.FontColor := TAlphaColorRec.Cornflowerblue;
A := A + 1;
end else if (ListaText.Items[I].Tag = 1) and (ListaText.Items[I].TextSettings.Font.Style = []) then
ListaText.Items[I].TextSettings.FontColor := TAlphaColorRec.Cornflowerblue
else if (ListaText.Items[I].Tag = 0) and (ListaText.Items[I].TextSettings.Font.Style <> []) then
ListaText.Items[I].TextSettings.FontColor := TAlphaColorRec.Darkred
end;
end;
end;
Fundo := TRectangle.Create(Self);
Fundo.Align := TAlignLayout.Contents;
Fundo.Fill.Color := TAlphaColorRec.white;
Fundo.Stroke.Color := TAlphaColorRec.white;
Fundo.Opacity := 0.7;
Self.AddObject(Fundo);
Resultado := TRectangle.Create(Self);
Resultado.YRadius := 5;
Resultado.XRadius := 5;
Resultado.Position.Y := Self.Height + 10;
Resultado.Width := Self.Width - 70;
Resultado.Position.X := 35;
Resultado.Height := Resultado.Width/2;
Resultado.Fill.Color := TAlphaColorRec.Black;
Resultado.Stroke.Color := TAlphaColorRec.Black;
Self.AddObject(Resultado);
Texto := TText.Create(Resultado);
Texto.Text := 'VocÍ acertou '+Inttostr(A)+' de ' +Inttostr(TabControl1.TabCount);
Texto.Align := TAlignLayout.Client;
Texto.Margins.Left := 10;
Texto.Margins.Right := 10;
Texto.Margins.Top := 5;
Texto.Margins.Bottom := 5;
Texto.Position.Y := 500;
Texto.TextSettings.Font.Size := 20;
Texto.TextSettings.FontColor := TAlphaColorRec.Darkgrey;
Texto.TextSettings.HorzAlign := TTextAlign.Center;
Texto.TextSettings.VertAlign := TTextAlign.Center;
Resultado.AddObject(Texto);
FundoBotao := TRectangle.Create(Resultado);
FundoBotao.Align := TAlignLayout.Bottom;
FundoBotao.Margins.Bottom := 5;
FundoBotao.Height := 40;
FundoBotao.YRadius := 5;
FundoBotao.XRadius := 5;
FundoBotao.Margins.Left := FundoBotao.Margins.Bottom;
FundoBotao.Margins.Right := FundoBotao.Margins.Bottom;
FundoBotao.Fill.Color := TAlphaColorRec.Cornflowerblue;
FundoBotao.Stroke.Color := TAlphaColorRec.Cornflowerblue;
Resultado.AddObject(FundoBotao);
Texto := TText.Create(FundoBotao);
Texto.Text := 'VER RESPOSTAS';
Texto.Align := TAlignLayout.Client;
Texto.OnClick := ContinuarClick;
Texto.TextSettings.FontColor := TAlphaColorRec.White;
FundoBotao.AddObject(Texto);
Animacao := TFloatAnimation.Create(Resultado);
Resultado.AddObject(Animacao);
Animacao.Duration := 0.3;
Animacao.StopValue := (Self.Height - Resultado.Height)/2 ;
Animacao.StartFromCurrent := True;
Animacao.PropertyName := 'Position.Y';
Animacao.OnFinish := AnimacaoFinish;
Animacao.Interpolation := TInterpolationType.Linear;
Animacao.Start;
end;
TabControl1.Next;
end;
procedure TForm2.Quiz(AJSON: String);
var
JSON,JSON2,JSON3,JSON4,JSON5 : TJSONObject;
I, J, K, L : Integer;
TabPerguntas :TTabItem;
Questao : TText;
FundoVert :TRectangle;
Check : TRadioButton;
Vert :TVertScrollBox;
Respostas :TText;
begin
ListaText := TObjectList<TText>.Create;
Rectangle2.Visible := False;
Rectangle3.Visible := True;
Label1.Visible := True;
Label2.Visible := True;
JSON := TJSONObject.ParseJSONValue(AJSON) as TJSONObject;
for I := 0 to JSON.Count -1 do begin
Label1.Text := (JSON.Pairs[i].JsonString.Value);
JSON2 := TJSONObject.ParseJSONValue(JSON.Pairs[i].JsonValue.ToString) as TJSONObject;
for J := 0 to JSON2.Count -1 do begin
Label2.Text := (JSON2.Pairs[J].JsonString.Value);
JSON3 := TJSONObject.ParseJSONValue(JSON2.Pairs[i].JsonValue.ToString) as TJSONObject;
for K := 0 to JSON3.Count -1 do begin
TabPerguntas := TTabItem.Create(TabControl1);
TabPerguntas.Text := JSON3.Pairs[K].JsonString.Value;
TabPerguntas.Name := 'tab_'+JSON3.Pairs[K].JsonString.Value+ IntToStr(K);
TabControl1.AddObject(TabPerguntas);
FundoVert := TRectangle.Create(Self);
FundoVert.Align := TAlignLayout.Client;
FundoVert.Fill.Color := Rectangle1.Fill.Color;
FundoVert.Stroke.Color := Rectangle1.Fill.Color;
TabPerguntas.AddObject(FundoVert);
Vert := TVertScrollBox.Create(FundoVert);
Vert.Align := TAlignLayout.Client;
FundoVert.AddObject(Vert);
JSON4 := TJSONObject.ParseJSONValue(JSON3.Pairs[k].JsonValue.ToString) as TJSONObject;
Questao := TText.Create(Vert);
Questao.Text := InttoStr(K+1)+') '+ JSON4.GetValue('questao').Value;
Questao.Align := TAlignLayout.Top;
Questao.Margins.Top := 20;
Questao.Margins.Left := 25;
Questao.Margins.Right := 25;
Questao.Margins.Bottom := 10;
Questao.TextSettings.Font.Size := 24;
Questao.TextSettings.HorzAlign := TTextAlign.Leading;
Questao.AutoSize := true;
Vert.AddObject(Questao);
JSON5 := TJSONObject.ParseJSONValue(JSON4.GetValue('opcoes').ToString) as TJSONObject;
for L := 0 to JSON5.Count - 1 do begin
Respostas := TText.Create(Vert);
Respostas.StyleName := IntToStr(K);
Respostas.Text := ' '+JSON5.Pairs[L].JsonString.Value +') '+JSON5.Pairs[L].JsonValue.Value;
Respostas.Align := TAlignLayout.Top;
Respostas.AutoSize := True;
Respostas.Margins.Left := 35;
Respostas.Margins.Right := 35;
Respostas.Margins.Top := 10;
Respostas.Margins.Bottom := 5;
Respostas.Position.Y := 500;
Respostas.TextSettings.Font.Size := 16;
Respostas.OnClick := RespostaClick;
Respostas.TextSettings.FontColor := TAlphaColorRec.Darkgrey;
Respostas.TextSettings.HorzAlign := TTextAlign.Leading;
ListaText.Add(Respostas);
Vert.AddObject(Respostas);
if JSON4.GetValue('correta') <> nil then begin
if JSON5.Pairs[L].JsonString.Value <> JSON4.GetValue('correta').Value then
Respostas.Tag := 0
else
Respostas.Tag := 1;
end;
end;
end;
end;
end;
JSON.Free;
JSON2.Free;
JSON3.Free;
JSON4.Free;
JSON5.Free;
end;
procedure TForm2.RespostaClick(Sender: TObject);
var
I : Integer;
begin
for I := 0 to ListaText.Count -1 do begin
if ListaText.Items[I].StyleName = TText(Sender).StyleName then begin
ListaText.Items[I].TextSettings.FontColor := TAlphaColorRec.Darkgrey;
ListaText.Items[I].TextSettings.Font.Style := [];
end;
end;
TText(Sender).TextSettings.FontColor := TAlphaColorRec.Black;
TText(Sender).TextSettings.Font.Style := [TFontStyle.fsBold];
end;
procedure TForm2.Text1Click(Sender: TObject);
begin
TabControl1.Previous;
end;
procedure TForm2.Text2Click(Sender: TObject);
begin
Proximo;
end;
end.
|
unit InstituitionsModel;
interface
uses connection, Ragna, System.JSON, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf,
FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.ConsoleUI.Wait, Data.DB,
FireDAC.Comp.Client, FireDAC.Phys.PG, FireDAC.Phys.PGDef, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt,
FireDAC.Comp.DataSet, Horse, System.SysUtils, Dataset.serialize,
System.Classes, System.NetEncoding, Soap.EncdDecd;
function findByPK(id: integer): TFDQuery;
function save(instituitionJson: string ): TFDQuery;
function update(id: integer; instituitionJson: string ): TFDQuery;
function delete(id: integer ): boolean;
function findAll(page: integer; limit: integer; findName:string; findValue: string; var tot_page: integer): TFDQuery; overload;
function findAll(): TFDQuery; overload;
implementation
function findByPK(id: integer): TFDQuery;
begin
DMConnection := TDMConnection.Create(DMConnection);
const Instituition = DMConnection.Instituicoes;
instituition.where('id').equals(id).openup;
result := instituition;
end;
function save(instituitionJson: string ): TFDQuery;
begin
DMConnection := TDMConnection.Create(DMConnection);
const Instituition = DMConnection.Instituicoes;
var jsonObj := TJSONObject
.ParseJSONValue(TEncoding.UTF8.GetBytes(instituitionJson), 0) as TJSONObject;
Instituition.New(jsonObj).OpenUp;
Result := Instituition;
end;
function update(id: integer; instituitionJson: string ): TFDQuery;
begin
DMConnection := TDMConnection.Create(DMConnection);
const Instituition = DMConnection.Instituicoes;
var jsonObj := TJSONObject
.ParseJSONValue(TEncoding.UTF8.GetBytes(instituitionJson), 0) as TJSONObject;
Instituition
.where('id')
.Equals(id)
.OpenUp;
Instituition
.MergeFromJSONObject(jsonObj);
Result := Instituition;
end;
function delete(id: integer ): boolean;
begin
DMConnection := TDMConnection.Create(DMConnection);
const Instituition = DMConnection.Instituicoes;
try
Instituition
.Remove(Instituition.FieldByName('id'), id)
.OpenUp;
result:= true;
except
on E:Exception do
result:= false;
end;
end;
function findAll(page: integer; limit: integer; findName:string; findValue: string; var tot_page: integer): TFDQuery; overload;
begin
DMConnection := TDMConnection.Create(DMConnection);
const Instituition = DMConnection.Instituicoes;
Instituition.Close;
Instituition.SQL.Clear;
Instituition.SQL.Add('select ');
Instituition.SQL.Add('i.*');
Instituition.SQL.Add('from ');
Instituition.SQL.Add('instituicoes i');
var filtered := false;
var tot := false;
if ((findName <> '') and (findValue <> '')) then
begin
Instituition.SQL.Add(' where ');
Instituition.SQL.Add( findName +' like ' + QuotedStr('%' + findValue + '%'));
Instituition.Open;
filtered := true;
tot := Trunc((Instituition.RowsAffected/limit)) < (Instituition.RowsAffected/limit);
if tot then
tot_page := Trunc(Instituition.RowsAffected/limit) + 1
else
tot_page := Trunc(Instituition.RowsAffected/limit);
Instituition.close;
end;
if not filtered then
begin
tot := Trunc((Instituition.OpenUp.RowsAffected/limit)) < (Instituition.OpenUp.RowsAffected/limit);
if tot then
tot_page := Trunc(Instituition.OpenUp.RowsAffected/limit) + 1
else
tot_page := Trunc(Instituition.OpenUp.RowsAffected/limit);
end;
var initial := page - 1;
initial := initial * limit;
Instituition.SQL.Add('ORDER BY ');
Instituition.SQL.Add('i.id OFFSET :offset ROWS FETCH NEXT :limit ROWS ONLY;');
Instituition.ParamByName('offset').AsInteger := initial;
Instituition.ParamByName('limit').AsInteger := limit;
Instituition.Open;
Result := Instituition;
end;
function findAll(): TFDQuery; overload;
begin
DMConnection := TDMConnection.Create(DMConnection);
const Instituition = DMConnection.Instituicoes;
Instituition.OpenUp;
Result := Instituition;
end;
end.
|
program DXVA_VideoProc;
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
// Copyright (c) Microsoft Corporation. All rights reserved.
(*++
Copyright (c) 2006 Microsoft Corporation
Module Name:
dxva2vp.cpp
Abstract:
This sample code demonstrates DXVA2 Video Processor API.
Environment:
Windows XP or later.
Command line options:
-hh : Force to use hardware D3D9 device and hardware DXVA2 device.
-hs : Force to use hardware D3D9 device and software DXVA2 device.
-ss : Force to use software D3D9 device and software DXVA2 device.
Keyboard assignment:
ESC or Alt + F4 : Exit.
Alt + Enter : Mode change between Window mode and Fullscreen mode.
F1 - F8 : Sub stream's color is changed and enters in the following modes.
HOME : Reset to the default/initial values in each modes.
END : Enable/Disable the frame drop debug spew.
F1 : [WHITE] Increment and decrement alpha values.
UP : increment main and sub stream's planar alpha
DOWN : decrement main and sub stream's planar alpha
RIGHT: increment sub stream's pixel alpha
LEFT : decrement sub stream's pixel alpha
F2 : [RED] Increment and decrement main stream's source area.
UP : decrement in the vertical direction (zoom in)
DOWN : increment in the vertical direction (zoom out)
RIGHT: increment in the horizontal direction (zoom in)
LEFT : decrement in the horizontal direction (zoom out)
F3 : [YELLOW] Move main stream's source area.
UP : move up
DOWN : move down
RIGHT: move right
LEFT : move left
F4 : [GREEN] Increment and decrement main stream's destination area.
UP : increment in the vertical direction
DOWN : decrement in the vertical direction
RIGHT: increment in the horizontal direction
LEFT : decrement in the horizontal direction
F5 : [CYAN] Move main stream's destination area.
UP : move up
DOWN : move down
RIGHT: move right
LEFT : move left
F6 : [BLUE] Change background color or extended color information.
UP : change to the next extended color in EX_COLOR_INFO
DOWN : change to the previous extended color in EX_COLOR_INFO
RIGHT: change to the next background color in BACKGROUND_COLORS
LEFT : change to the previous background color in BACKGROUND_COLORS
EX_COLOR_INFO : SDTV ITU-R BT.601 YCbCr to driver's optimal RGB range,
SDTV ITU-R BT.601 YCbCr to studio RGB [16...235],
SDTV ITU-R BT.601 YCbCr to computer RGB [0...255],
HDTV ITU-R BT.709 YCbCr to driver's optimal RGB range,
HDTV ITU-R BT.709 YCbCr to studio RGB [16...235],
HDTV ITU-R BT.709 YCbCr to computer RGB [0...255]
BACKGROUND_COLORS : WHITE, RED, YELLOW, GREEN, CYAN, BLUE, MAGENTA, BLACK
F7 : [MAGENTA] Increment and decrement the brightness or contrast.
UP : increment brightness
DOWN : decrement brightness
RIGHT: increment contrast
LEFT : decrement contrast
F8 : [BLACK] Increment and decrement the hue or saturation.
UP : increment hue
DOWN : decrement hue
RIGHT: increment saturation
LEFT : decrement saturation
F9 : [ORANGE] Increment and decrement target area.
UP : decrement in the vertical direction
DOWN : increment in the vertical direction
RIGHT: increment in the horizontal direction
LEFT : decrement in the horizontal direction
--*)
{$mode delphi}{$H+}
uses {$IFDEF UNIX} {$IFDEF UseCThreads}
cthreads, {$ENDIF} {$ENDIF}
Interfaces, // this includes the LCL widgetset
{ you can add units after this }
Windows,
SysUtils,
ActiveX,
CMC.DXVA2API,
CMC.MFAPI,
CMC.DWMAPI,
MMSystem,
Math,
Direct3D9;
const
CLASS_NAME = 'DXVA2 VP Sample Class';
WINDOW_NAME = 'DXVA2 VP Sample Application';
VIDEO_MAIN_WIDTH = 640;
VIDEO_MAIN_HEIGHT = 480;
VIDEO_SUB_WIDTH = 128;
VIDEO_SUB_HEIGHT = 128;
VIDEO_SUB_VX = 5;
VIDEO_SUB_VY = 3;
VIDEO_FPS = 60;
VIDEO_MSPF = UINT((1000 + VIDEO_FPS div 2) div VIDEO_FPS);
VIDEO_100NSPF = VIDEO_MSPF * 10000;
DEFAULT_PLANAR_ALPHA_VALUE = $FF;
DEFAULT_PIXEL_ALPHA_VALUE = $80;
VIDEO_REQUIED_OP = DXVA2_VideoProcess_YUV2RGB or DXVA2_VideoProcess_StretchX or DXVA2_VideoProcess_StretchY or
DXVA2_VideoProcess_SubRects or DXVA2_VideoProcess_SubStreams;
VIDEO_RENDER_TARGET_FORMAT = D3DFMT_X8R8G8B8;
VIDEO_MAIN_FORMAT = D3DFMT_YUY2;
BACK_BUFFER_COUNT = 1;
SUB_STREAM_COUNT = 1;
DWM_BUFFER_COUNT = 4;
EX_COLOR_INFO: array [0..5, 0..1] of UINT = (
// SDTV ITU-R BT.601 YCbCr to driver's optimal RGB range
(Ord(DXVA2_VideoTransferMatrix_BT601), Ord(DXVA2_NominalRange_Unknown)),
// SDTV ITU-R BT.601 YCbCr to studio RGB [16...235]
(Ord(DXVA2_VideoTransferMatrix_BT601), Ord(DXVA2_NominalRange_16_235)),
// SDTV ITU-R BT.601 YCbCr to computer RGB [0...255]
(Ord(DXVA2_VideoTransferMatrix_BT601), Ord(DXVA2_NominalRange_0_255)),
// HDTV ITU-R BT.709 YCbCr to driver's optimal RGB range
(Ord(DXVA2_VideoTransferMatrix_BT709), Ord(DXVA2_NominalRange_Unknown)),
// HDTV ITU-R BT.709 YCbCr to studio RGB [16...235]
(Ord(DXVA2_VideoTransferMatrix_BT709), Ord(DXVA2_NominalRange_16_235)),
// HDTV ITU-R BT.709 YCbCr to computer RGB [0...255]
(Ord(DXVA2_VideoTransferMatrix_BT709), Ord(DXVA2_NominalRange_0_255)));
VIDEO_MAIN_RECT: TRECT = (Left: 0; Top: 0; Right: VIDEO_MAIN_WIDTH; Bottom: VIDEO_MAIN_HEIGHT);
VIDEO_SUB_RECT: TRECT = (Left: 0; Top: 0; Right: VIDEO_SUB_WIDTH; Bottom: VIDEO_SUB_HEIGHT);
type
// Type definitions.
PFNDWMISCOMPOSITIONENABLED = function(out pfEnabled: boolean): HResult; stdcall;
PFNDWMGETCOMPOSITIONTIMINGINFO = function(hwnd: HWND; out pTimingInfo: TDWM_TIMING_INFO): HResult; stdcall;
PFNDWMSETPRESENTPARAMETERS = function(hwnd: HWND; var pPresentParams: TDWM_PRESENT_PARAMETERS): HResult; stdcall;
var
// Global variables.
g_bD3D9HW: boolean = True;
g_bD3D9SW: boolean = True;
g_bDXVA2HW: boolean = True;
g_bDXVA2SW: boolean = True;
g_bWindowed: boolean = True;
g_bTimerSet: boolean = False;
g_bInModeChange: boolean = False;
g_bUpdateSubStream: boolean = False;
g_bDspFrameDrop: boolean = False;
g_bDwmQueuing: boolean = False;
g_Hwnd: HWND = 0;
g_hTimer: THANDLE = 0;
g_hRgb9rastDLL: HMODULE = 0;
g_hDwmApiDLL: HMODULE = 0;
g_StartSysTime: DWORD = 0;
g_PreviousTime: DWORD = 0;
g_pD3D9: IDirect3D9 = nil;
g_pD3DD9: IDirect3DDevice9 = nil;
g_pD3DRT: IDirect3DSurface9 = nil;
g_pDXVAVPS: IDirectXVideoProcessorService = nil;
g_pDXVAVPD: IDirectXVideoProcessor = nil;
g_pMainStream: IDirect3DSurface9 = nil;
g_pSubStream: IDirect3DSurface9 = nil;
g_TargetWidthPercent: UINT = 100;
g_TargetHeightPercent: UINT = 100;
g_pfnD3D9GetSWInfo: pointer = nil;
g_pfnDwmIsCompositionEnabled: pointer = nil;
g_pfnDwmGetCompositionTimingInfo: pointer = nil;
g_pfnDwmSetPresentParameters: pointer = nil;
{ initialize zero memory }
g_D3DPP: D3DPRESENT_PARAMETERS;
g_GuidVP: TGUID;
g_VideoDesc: TDXVA2_VideoDesc;
g_VPCaps: TDXVA2_VideoProcessorCaps;
VIDEO_SUB_FORMAT: TD3DFormat; // ToDo
g_ProcAmpRanges: array [0..3] of TDXVA2_ValueRange; // ={0}
g_NFilterRanges: array [0..5] of TDXVA2_ValueRange;// = {0};
g_DFilterRanges: array [0..5] of TDXVA2_ValueRange; // = {0};
g_ProcAmpValues: array [0..3] of TDXVA2_Fixed32; // = {0};
g_NFilterValues: array [0..5] of TDXVA2_Fixed32; // = {0};
g_DFilterValues: array [0..5] of TDXVA2_Fixed32;// = {0};
g_BackgroundColor: integer = 0;
g_ExColorInfo: integer = 0;
g_ProcAmpSteps: array [0..3] of integer; // = {0};
g_VK_Fx: UINT = VK_F1;
// 100%
RGB_WHITE: TD3DCOLOR;// = D3DCOLOR_XRGB($EB, $EB, $EB);
RGB_RED: TD3DCOLOR;// = = D3DCOLOR_XRGB($EB, $10, $10);
RGB_YELLOW: TD3DCOLOR;// = D3DCOLOR_XRGB($EB, $EB, $10);
RGB_GREEN: TD3DCOLOR;// = D3DCOLOR_XRGB($10, $EB, $10);
RGB_CYAN: TD3DCOLOR;// = D3DCOLOR_XRGB($10, $EB, $EB);
RGB_BLUE: TD3DCOLOR;// = D3DCOLOR_XRGB($10, $10, $EB);
RGB_MAGENTA: TD3DCOLOR;// = D3DCOLOR_XRGB($EB, $10, $EB);
RGB_BLACK: TD3DCOLOR;// = D3DCOLOR_XRGB($10, $10, $10);
RGB_ORANGE: TD3DCOLOR;// = D3DCOLOR_XRGB($EB, $7E, $10);
// 75%
RGB_WHITE_75pc: TD3DCOLOR;// = D3DCOLOR_XRGB($B4, $B4, $B4);
RGB_YELLOW_75pc: TD3DCOLOR;// = D3DCOLOR_XRGB($B4, $B4, $10);
RGB_CYAN_75pc: TD3DCOLOR;// = D3DCOLOR_XRGB($10, $B4, $B4);
RGB_GREEN_75pc: TD3DCOLOR;// = D3DCOLOR_XRGB($10, $B4, $10);
RGB_MAGENTA_75pc: TD3DCOLOR;// = D3DCOLOR_XRGB($B4, $10, $B4);
RGB_RED_75pc: TD3DCOLOR;// = D3DCOLOR_XRGB($B4, $10, $10);
RGB_BLUE_75pc: TD3DCOLOR;// = D3DCOLOR_XRGB($10, $10, $B4);
// -4% / +4%
RGB_BLACK_n4pc: TD3DCOLOR;// = D3DCOLOR_XRGB($07, $07, $07);
RGB_BLACK_p4pc: TD3DCOLOR;// = D3DCOLOR_XRGB($18, $18, $18);
// -Inphase / +Quadrature
RGB_I: TD3DCOLOR;// = D3DCOLOR_XRGB($00, $1D, $42);
RGB_Q: TD3DCOLOR;// = D3DCOLOR_XRGB($2C, $00, $5C);
g_PlanarAlphaValue: word = DEFAULT_PLANAR_ALPHA_VALUE;
g_PixelAlphaValue: byte = DEFAULT_PIXEL_ALPHA_VALUE;
g_RectWindow: TRECT;// = {0};
BACKGROUND_COLORS: array [0..7] of D3DCOLOR;
g_SrcRect: TRECT = (Left: 0; Top: 0; Right: VIDEO_MAIN_WIDTH; Bottom: VIDEO_MAIN_HEIGHT);
g_DstRect: TRECT = (Left: 0; Top: 0; Right: VIDEO_MAIN_WIDTH; Bottom: VIDEO_MAIN_HEIGHT);
{$R *.res}
function CompareDXVA2ValueRange(x, y: TDXVA2_ValueRange): boolean; inline;
begin
Result := CompareMem(@x, @y, sizeof(TDXVA2_ValueRange));
end;
function RegisterSoftwareRasterizer(): boolean;
var
hr: HRESULT;
begin
if (g_hRgb9rastDLL = 0) then
begin
Result := False;
Exit;
end;
hr := g_pD3D9.RegisterSoftwareDevice(g_pfnD3D9GetSWInfo);
if (FAILED(hr)) then
begin
//DBGMSG((TEXT("RegisterSoftwareDevice failed with error $%x.\n"), hr));
Result := False;
Exit;
end;
Result := True;
end;
function InitializeD3D9(): boolean;
var
hr: HResult;
begin
g_pD3D9 := Direct3DCreate9(D3D_SDK_VERSION);
if (g_pD3D9 = nil) then
begin
// DBGMSG((TEXT("Direct3DCreate9 failed.\n")));
Result := False;
Exit;
end;
// Register the inbox software rasterizer if software D3D9 could be used.
// CreateDevice(D3DDEVTYPE_SW) will fail if software device is not registered.
if (g_bD3D9SW) then
begin
RegisterSoftwareRasterizer();
end;
if (g_bWindowed) then
begin
g_D3DPP.BackBufferWidth := 0;
g_D3DPP.BackBufferHeight := 0;
end
else
begin
g_D3DPP.BackBufferWidth := GetSystemMetrics(SM_CXSCREEN);
g_D3DPP.BackBufferHeight := GetSystemMetrics(SM_CYSCREEN);
end;
g_D3DPP.BackBufferFormat := VIDEO_RENDER_TARGET_FORMAT;
g_D3DPP.BackBufferCount := BACK_BUFFER_COUNT;
g_D3DPP.SwapEffect := D3DSWAPEFFECT_DISCARD;
g_D3DPP.hDeviceWindow := g_Hwnd;
g_D3DPP.Windowed := g_bWindowed;
g_D3DPP.Flags := D3DPRESENTFLAG_VIDEO;
g_D3DPP.FullScreen_RefreshRateInHz := D3DPRESENT_RATE_DEFAULT;
g_D3DPP.PresentationInterval := D3DPRESENT_INTERVAL_ONE;
// Mark the back buffer lockable if software DXVA2 could be used.
// This is because software DXVA2 device requires a lockable render target
// for the optimal performance.
if (g_bDXVA2SW) then
begin
g_D3DPP.Flags := g_D3DPP.Flags or D3DPRESENTFLAG_LOCKABLE_BACKBUFFER;
end;
// First try to create a hardware D3D9 device.
if (g_bD3D9HW) then
begin
hr := g_pD3D9.CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, g_Hwnd, D3DCREATE_FPU_PRESERVE or
D3DCREATE_MULTITHREADED or D3DCREATE_SOFTWARE_VERTEXPROCESSING, @g_D3DPP, g_pD3DD9);
if (FAILED(hr)) then
begin
// DBGMSG((TEXT("CreateDevice(HAL) failed with error $%x.\n"), hr));
end;
end;
// Next try to create a software D3D9 device.
if (g_pD3DD9 = nil) and (g_bD3D9SW) then
begin
hr := g_pD3D9.CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_SW, g_Hwnd, D3DCREATE_FPU_PRESERVE or
D3DCREATE_MULTITHREADED or D3DCREATE_SOFTWARE_VERTEXPROCESSING, @g_D3DPP, g_pD3DD9);
if (FAILED(hr)) then
begin
// DBGMSG((TEXT("CreateDevice(SW) failed with error $%x.\n"), hr));
end;
end;
if (g_pD3DD9 = nil) then
begin
Result := False;
Exit;
end;
Result := True;
end;
procedure DestroyD3D9();
begin
if (g_pD3DD9 <> nil) then
g_pD3DD9 := nil;
if (g_pD3D9 <> nil) then
g_pD3D9 := nil;
end;
function ComputeLongSteps(range: TDXVA2_ValueRange): integer;
var
f_step: single;
f_max: single;
f_min: single;
steps: integer;
begin
f_step := DXVA2FixedToFloat(range.StepSize);
if (f_step = 0.0) then
begin
Result := 0;
Exit;
end;
f_max := DXVA2FixedToFloat(range.MaxValue);
f_min := DXVA2FixedToFloat(range.MinValue);
steps := trunc((f_max - f_min) / f_step / 32);
Result := max(steps, 1);
end;
function CreateDXVA2VPDevice(const guid: TGUID): boolean;
var
hr: HResult;
i, Count: UINT;
formats: PD3DFORMAT;
range: TDXVA2_ValueRange;
begin
// Query the supported render target format.
formats := nil;
hr := g_pDXVAVPS.GetVideoProcessorRenderTargets(guid, g_VideoDesc, Count, formats);
if (FAILED(hr)) then
begin
// DBGMSG((TEXT("GetVideoProcessorRenderTargets failed with error $%x.\n"), hr));
Result := False;
Exit;
end;
for i := 0 to Count - 1 do
begin
if (formats[i] = VIDEO_RENDER_TARGET_FORMAT) then
begin
break;
end;
end;
CoTaskMemFree(formats);
if (i >= Count) then
begin
// DBGMSG((TEXT("GetVideoProcessorRenderTargets doesn't support that format.\n")));
Result := False;
Exit;
end;
// Query the supported substream format.
formats := nil;
hr := g_pDXVAVPS.GetVideoProcessorSubStreamFormats(guid, g_VideoDesc, VIDEO_RENDER_TARGET_FORMAT, Count, formats);
if (FAILED(hr)) then
begin
// DBGMSG((TEXT("GetVideoProcessorSubStreamFormats failed with error $%x.\n"), hr));
Result := False;
Exit;
end;
for i := 0 to Count - 1 do
begin
if (formats[i] = VIDEO_SUB_FORMAT) then
begin
break;
end;
end;
CoTaskMemFree(formats);
if (i >= Count) then
begin
// DBGMSG((TEXT("GetVideoProcessorSubStreamFormats doesn't support that format.\n")));
Result := False;
Exit;
end;
// Query video processor capabilities.
hr := g_pDXVAVPS.GetVideoProcessorCaps(guid, g_VideoDesc, VIDEO_RENDER_TARGET_FORMAT, g_VPCaps);
if (FAILED(hr)) then
begin
// DBGMSG((TEXT("GetVideoProcessorCaps failed with error $%x.\n"), hr));
Result := False;
Exit;
end;
// Check to see if the device is software device.
if (g_VPCaps.DeviceCaps and DXVA2_VPDev_SoftwareDevice = DXVA2_VPDev_SoftwareDevice) then
begin
if (not g_bDXVA2SW) then
begin
// DBGMSG((TEXT("The DXVA2 device isn't a hardware device.\n")));
Result := False;
Exit;
end;
end
else
begin
if (not g_bDXVA2HW) then
begin
// DBGMSG((TEXT("The DXVA2 device isn't a software device.\n")));
Result := False;
Exit;
end;
end;
// This is a progressive device and we cannot provide any reference sample.
if (g_VPCaps.NumForwardRefSamples > 0) or (g_VPCaps.NumBackwardRefSamples > 0) then
begin
// DBGMSG((TEXT("NumForwardRefSamples or NumBackwardRefSamples is greater than 0.\n")));
Result := False;
Exit;
end;
// Check to see if the device supports all the VP operations we want.
if ((g_VPCaps.VideoProcessorOperations and VIDEO_REQUIED_OP) <> VIDEO_REQUIED_OP) then
begin
// DBGMSG((TEXT("The DXVA2 device doesn't support the VP operations.\n")));
Result := False;
Exit;
end;
// Create a main stream surface.
hr := g_pDXVAVPS.CreateSurface(VIDEO_MAIN_WIDTH, VIDEO_MAIN_HEIGHT, 0, VIDEO_MAIN_FORMAT, g_VPCaps.InputPool,
0, DXVA2_VideoSoftwareRenderTarget, g_pMainStream, nil);
if (FAILED(hr)) then
begin
// DBGMSG((TEXT("CreateSurface(MainStream) failed with error $%x.\n"), hr));
Result := False;
Exit;
end;
// Create a sub stream surface.
hr := g_pDXVAVPS.CreateSurface(VIDEO_SUB_WIDTH, VIDEO_SUB_HEIGHT, 0, VIDEO_SUB_FORMAT, g_VPCaps.InputPool,
0, DXVA2_VideoSoftwareRenderTarget, g_pSubStream, nil);
if (FAILED(hr)) then
begin
// DBGMSG((TEXT("CreateSurface(SubStream, InputPool) failed with error $%x.\n"), hr));
end;
// Fallback to default pool type if the suggested pool type failed.
// This could happen when software DXVA2 device is used with hardware D3D9 device.
// This is due to the fact that D3D9 doesn't understand AYUV format and D3D9 needs
// an information from the driver in order to allocate it from the system memory.
// Since software DXVA2 device suggests system memory pool type for the optimal
// performance but the driver may not support it other than default pool type,
// D3D9 will fail to create it.
// Note that creating a default pool type surface will significantly reduce the
// performance when it is used with software DXVA2 device.
if (g_pSubStream = nil) and (Ord(g_VPCaps.InputPool) <> Ord(D3DPOOL_DEFAULT)) then
begin
hr := g_pDXVAVPS.CreateSurface(VIDEO_SUB_WIDTH, VIDEO_SUB_HEIGHT, 0, VIDEO_SUB_FORMAT, Ord(D3DPOOL_DEFAULT),
0, DXVA2_VideoSoftwareRenderTarget, g_pSubStream, nil);
if (FAILED(hr)) then
begin
// DBGMSG((TEXT("CreateSurface(SubStream, DEFAULT) failed with error $%x.\n"), hr));
end;
end;
if (g_pSubStream = nil) then
begin
Result := False;
Exit;
end;
// Query ProcAmp ranges.
for i := 0 to Length(g_ProcAmpRanges) - 1 do
begin
if ((g_VPCaps.ProcAmpControlCaps and (1 shl i)) <> 0) then
begin
hr := g_pDXVAVPS.GetProcAmpRange(guid, g_VideoDesc, VIDEO_RENDER_TARGET_FORMAT, 1 shl i, range);
if (FAILED(hr)) then
begin
// DBGMSG((TEXT("GetProcAmpRange failed with error $%x.\n"), hr));
Result := False;
Exit;
end;
// Reset to default value if the range is changed.
if not CompareDXVA2ValueRange(range, g_ProcAmpRanges[i]) then
begin
g_ProcAmpRanges[i] := range;
g_ProcAmpValues[i] := range.DefaultValue;
g_ProcAmpSteps[i] := ComputeLongSteps(range);
end;
end;
end;
// Query Noise Filter ranges.
if ((g_VPCaps.VideoProcessorOperations and DXVA2_VideoProcess_NoiseFilter) <> 0) then
begin
for i := 0 to length(g_NFilterRanges) - 1 do
begin
hr := g_pDXVAVPS.GetFilterPropertyRange(guid, g_VideoDesc, VIDEO_RENDER_TARGET_FORMAT,
DXVA2_NoiseFilterLumaLevel + i, range);
if (FAILED(hr)) then
begin
// DBGMSG((TEXT("GetFilterPropertyRange(Noise) failed with error $%x.\n"), hr));
Result := False;
Exit;
end;
// Reset to default value if the range is changed.
if not CompareDXVA2ValueRange(range, g_NFilterRanges[i]) then
begin
g_NFilterRanges[i] := range;
g_NFilterValues[i] := range.DefaultValue;
end;
end;
end;
// Query Detail Filter ranges.
if ((g_VPCaps.VideoProcessorOperations and DXVA2_VideoProcess_DetailFilter) <> 0) then
begin
for i := 0 to length(g_DFilterRanges) - 1 do
begin
hr := g_pDXVAVPS.GetFilterPropertyRange(guid, g_VideoDesc, VIDEO_RENDER_TARGET_FORMAT,
DXVA2_DetailFilterLumaLevel + i, range);
if (FAILED(hr)) then
begin
// DBGMSG((TEXT("GetFilterPropertyRange(Detail) failed with error $%x.\n"), hr));
Result := False;
Exit;
end;
// Reset to default value if the range is changed.
if not CompareDXVA2ValueRange(range, g_DFilterRanges[i]) then
begin
g_DFilterRanges[i] := range;
g_DFilterValues[i] := range.DefaultValue;
end;
end;
end;
// Finally create a video processor device.
hr := g_pDXVAVPS.CreateVideoProcessor(guid, g_VideoDesc, VIDEO_RENDER_TARGET_FORMAT, SUB_STREAM_COUNT, g_pDXVAVPD);
if (FAILED(hr)) then
begin
// DBGMSG((TEXT("CreateVideoProcessor failed with error $%x.\n"), hr));
Result := False;
Exit;
end;
g_GuidVP := guid;
Result := True;
end;
function RGBtoYUV(const rgb: TD3DCOLOR): DWORD;
var
A, R, G, B: integer;
Y, U, V: integer;
begin
A := HIBYTE(HIWORD(rgb));
R := LOBYTE(HIWORD(rgb)) - 16;
G := HIBYTE(LOWORD(rgb)) - 16;
B := LOBYTE(LOWORD(rgb)) - 16;
// studio RGB [16...235] to SDTV ITU-R BT.601 YCbCr
Y := (77 * R + 150 * G + 29 * B + 128) div 256 + 16;
U := (-44 * R - 87 * G + 131 * B + 128) div 256 + 128;
V := (131 * R - 110 * G - 21 * B + 128) div 256 + 128;
Result := D3DCOLOR_AYUV(A, Y, U, V);
end;
function RGBtoYUY2(const rgb: TD3DCOLOR): DWORD;
var
yuv: TD3DCOLOR;
y, u, v: byte;
begin
yuv := RGBtoYUV(rgb);
Y := LOBYTE(HIWORD(yuv));
U := HIBYTE(LOWORD(yuv));
V := LOBYTE(LOWORD(yuv));
Result := MAKELONG(MAKEWORD(Y, U), MAKEWORD(Y, V));
end;
procedure FillRectangle(lr: TD3DLOCKED_RECT; const sx: UINT; const sy: UINT; const ex: UINT; const ey: UINT; const color: DWORD);
var
y: uint;
P: PDWORD;
x: uint;
begin
p := lr.pBits;
p := p + (lr.Pitch div 4) * sy; // cause the Pitch is in Byte and we have a pointer to a DWORD ;)
for y := sy to ey - 1 do
begin
for x := sx to ex - 1 do
begin
P[x] := Color;
end;
p := p + (lr.Pitch div 4); // cause the Pitch is in Byte and we have a pointer to a DWORD ;)
end;
end;
function UpdateSubStream(): boolean;
var
hr: HResult;
color: TD3DCOLOR;
lr: TD3DLOCKED_RECT;
R, G, B: byte;
begin
if (not g_bUpdateSubStream) then
begin
Result := True;
Exit;
end;
case (g_VK_Fx) of
VK_F1:
begin
color := RGB_WHITE;
end;
VK_F2:
begin
color := RGB_RED;
end;
VK_F3:
begin
color := RGB_YELLOW;
end;
VK_F4:
begin
color := RGB_GREEN;
end;
VK_F5:
begin
color := RGB_CYAN;
end;
VK_F6:
begin
color := RGB_BLUE;
end;
VK_F7:
begin
color := RGB_MAGENTA;
end;
VK_F8:
begin
color := RGB_BLACK;
end;
VK_F9:
begin
color := RGB_ORANGE;
end;
else
begin
Result := False;
Exit;
end;
end;
hr := g_pSubStream.LockRect(lr, nil, D3DLOCK_NOSYSLOCK);
if (FAILED(hr)) then
begin
// DBGMSG((TEXT("LockRect failed with error $%x.\n"), hr));
Result := False;
Exit;
end;
R := LOBYTE(HIWORD(color));
G := HIBYTE(LOWORD(color));
B := LOBYTE(LOWORD(color));
FillRectangle(lr, 0, 0, VIDEO_SUB_WIDTH, VIDEO_SUB_HEIGHT,
RGBtoYUV(D3DCOLOR_ARGB(g_PixelAlphaValue, R, G, B)));
hr := g_pSubStream.UnlockRect();
if (FAILED(hr)) then
begin
// DBGMSG((TEXT("UnlockRect failed with error $%x.\n"), hr));
Result := False;
Exit;
end;
g_bUpdateSubStream := False;
Result := True;
end;
function InitializeVideo(): boolean;
var
hr: HRESULT;
lr: TD3DLOCKED_RECT;
dx, y1, y2, y3: UINT;
begin
// Draw the main stream (SMPTE color bars).
hr := g_pMainStream.LockRect(lr, nil, D3DLOCK_NOSYSLOCK);
if (FAILED(hr)) then
begin
// DBGMSG((TEXT("LockRect failed with error $%x.\n"), hr));
Result := False;
Exit;
end;
// YUY2 is two pixels per DWORD.
dx := VIDEO_MAIN_WIDTH div 2;
// First row stripes.
y1 := VIDEO_MAIN_HEIGHT * 2 div 3;
FillRectangle(lr, dx * 0 div 7, 0, dx * 1 div 7, y1, RGBtoYUY2(RGB_WHITE_75pc));
FillRectangle(lr, dx * 1 div 7, 0, dx * 2 div 7, y1, RGBtoYUY2(RGB_YELLOW_75pc));
FillRectangle(lr, dx * 2 div 7, 0, dx * 3 div 7, y1, RGBtoYUY2(RGB_CYAN_75pc));
FillRectangle(lr, dx * 3 div 7, 0, dx * 4 div 7, y1, RGBtoYUY2(RGB_GREEN_75pc));
FillRectangle(lr, dx * 4 div 7, 0, dx * 5 div 7, y1, RGBtoYUY2(RGB_MAGENTA_75pc));
FillRectangle(lr, dx * 5 div 7, 0, dx * 6 div 7, y1, RGBtoYUY2(RGB_RED_75pc));
FillRectangle(lr, dx * 6 div 7, 0, dx * 7 div 7, y1, RGBtoYUY2(RGB_BLUE_75pc));
// Second row stripes.
y2 := VIDEO_MAIN_HEIGHT * 3 div 4;
FillRectangle(lr, dx * 0 div 7, y1, dx * 1 div 7, y2, RGBtoYUY2(RGB_BLUE_75pc));
FillRectangle(lr, dx * 1 div 7, y1, dx * 2 div 7, y2, RGBtoYUY2(RGB_BLACK));
FillRectangle(lr, dx * 2 div 7, y1, dx * 3 div 7, y2, RGBtoYUY2(RGB_MAGENTA_75pc));
FillRectangle(lr, dx * 3 div 7, y1, dx * 4 div 7, y2, RGBtoYUY2(RGB_BLACK));
FillRectangle(lr, dx * 4 div 7, y1, dx * 5 div 7, y2, RGBtoYUY2(RGB_CYAN_75pc));
FillRectangle(lr, dx * 5 div 7, y1, dx * 6 div 7, y2, RGBtoYUY2(RGB_BLACK));
FillRectangle(lr, dx * 6 div 7, y1, dx * 7 div 7, y2, RGBtoYUY2(RGB_WHITE_75pc));
// Third row stripes.
y3 := VIDEO_MAIN_HEIGHT;
FillRectangle(lr, dx * 0 div 28, y2, dx * 5 div 28, y3, RGBtoYUY2(RGB_I));
FillRectangle(lr, dx * 5 div 28, y2, dx * 10 div 28, y3, RGBtoYUY2(RGB_WHITE));
FillRectangle(lr, dx * 10 div 28, y2, dx * 15 div 28, y3, RGBtoYUY2(RGB_Q));
FillRectangle(lr, dx * 15 div 28, y2, dx * 20 div 28, y3, RGBtoYUY2(RGB_BLACK));
FillRectangle(lr, dx * 20 div 28, y2, dx * 16 div 21, y3, RGBtoYUY2(RGB_BLACK_n4pc));
FillRectangle(lr, dx * 16 div 21, y2, dx * 17 div 21, y3, RGBtoYUY2(RGB_BLACK));
FillRectangle(lr, dx * 17 div 21, y2, dx * 6 div 7, y3, RGBtoYUY2(RGB_BLACK_p4pc));
FillRectangle(lr, dx * 6 div 7, y2, dx * 7 div 7, y3, RGBtoYUY2(RGB_BLACK));
hr := g_pMainStream.UnlockRect();
if (FAILED(hr)) then
begin
// DBGMSG((TEXT("UnlockRect failed with error $%x.\n"), hr));
Result := False;
Exit;
end;
// Draw the sub stream in the next video process.
g_bUpdateSubStream := True;
Result := True;
end;
function InitializeDXVA2(): boolean;
var
hr: HRESULT;
Count: UINT;
guids: PGUID = nil;
I: integer;
begin
// Retrieve a back buffer as the video render target.
hr := g_pD3DD9.GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, g_pD3DRT);
if (FAILED(hr)) then
begin
// DBGMSG((TEXT("GetBackBuffer failed with error $%x.\n"), hr));
Result := False;
Exit;
end;
// Create DXVA2 Video Processor Service.
hr := DXVA2CreateVideoService(g_pD3DD9, IID_IDirectXVideoProcessorService, g_pDXVAVPS);
if (FAILED(hr)) then
begin
// DBGMSG((TEXT("DXVA2CreateVideoService failed with error $%x.\n"), hr));
Result := False;
Exit;
end;
// Initialize the video descriptor.
g_VideoDesc.SampleWidth := VIDEO_MAIN_WIDTH;
g_VideoDesc.SampleHeight := VIDEO_MAIN_HEIGHT;
g_VideoDesc.SampleFormat.VideoChromaSubsampling := Ord(DXVA2_VideoChromaSubsampling_MPEG2);
g_VideoDesc.SampleFormat.NominalRange := Ord(DXVA2_NominalRange_16_235);
g_VideoDesc.SampleFormat.VideoTransferMatrix := EX_COLOR_INFO[g_ExColorInfo][0];
g_VideoDesc.SampleFormat.VideoLighting := Ord(DXVA2_VideoLighting_dim);
g_VideoDesc.SampleFormat.VideoPrimaries := Ord(DXVA2_VideoPrimaries_BT709);
g_VideoDesc.SampleFormat.VideoTransferFunction := Ord(DXVA2_VideoTransFunc_709);
g_VideoDesc.SampleFormat.SampleFormat := Ord(DXVA2_SampleProgressiveFrame);
g_VideoDesc.Format := VIDEO_MAIN_FORMAT;
g_VideoDesc.InputSampleFreq.Numerator := VIDEO_FPS;
g_VideoDesc.InputSampleFreq.Denominator := 1;
g_VideoDesc.OutputFrameFreq.Numerator := VIDEO_FPS;
g_VideoDesc.OutputFrameFreq.Denominator := 1;
// Query the video processor GUID.
hr := g_pDXVAVPS.GetVideoProcessorDeviceGuids(g_VideoDesc, Count, guids);
if (FAILED(hr)) then
begin
//DBGMSG((TEXT("GetVideoProcessorDeviceGuids failed with error $%x.\n"), hr));
Result := False;
Exit;
end;
// Create a DXVA2 device.
for i := 0 to Count - 1 do
begin
if (CreateDXVA2VPDevice(guids[i])) then
begin
break;
end;
end;
CoTaskMemFree(guids);
if (g_pDXVAVPD = nil) then
begin
// DBGMSG((TEXT("Failed to create a DXVA2 device.\n")));
Result := False;
Exit;
end;
if (not InitializeVideo()) then
begin
Result := False;
Exit;
end;
Result := True;
end;
procedure DestroyDXVA2();
begin
if (g_pSubStream <> nil) then
g_pSubStream := nil;
if (g_pMainStream <> nil) then
g_pMainStream := nil;
if (g_pDXVAVPD <> nil) then
g_pDXVAVPD := nil;
if (g_pDXVAVPS <> nil) then
g_pDXVAVPS := nil;
if (g_pD3DRT <> nil) then
g_pD3DRT := nil;
end;
function EnableDwmQueuing(): boolean;
var
hr: HRESULT;
bDWM: boolean;
dwmti: TDWM_TIMING_INFO;
dwmpp: TDWM_PRESENT_PARAMETERS;
begin
// DWM is not available.
if (g_hDwmApiDLL = 0) then
begin
Result := True;
Exit;
end;
// Check to see if DWM is currently enabled.
bDWM := False;
hr := PFNDWMISCOMPOSITIONENABLED(g_pfnDwmIsCompositionEnabled)(bDWM);
if (FAILED(hr)) then
begin
// DBGMSG((TEXT("DwmIsCompositionEnabled failed with error $%x.\n"), hr));
Result := False;
Exit;
end;
// DWM queuing is disabled when DWM is disabled.
if (not bDWM) then
begin
g_bDwmQueuing := False;
Result := True;
Exit;
end;
// DWM queuing is enabled already.
if (g_bDwmQueuing) then
begin
Result := True;
Exit;
end;
// Retrieve DWM refresh count of the last vsync.
ZeroMemory(@dwmti, SizeOf(dwmti));
dwmti.cbSize := sizeof(dwmti);
hr := PFNDWMGETCOMPOSITIONTIMINGINFO(g_pfnDwmGetCompositionTimingInfo)(0, dwmti);
if (FAILED(hr)) then
begin
// DBGMSG((TEXT("DwmGetCompositionTimingInfo failed with error $%x.\n"), hr));
Result := False;
Exit;
end;
// Enable DWM queuing from the next refresh.
ZeroMemory(@dwmpp, SizeOf(dwmpp));
dwmpp.cbSize := sizeof(dwmpp);
dwmpp.fQueue := True;
dwmpp.cRefreshStart := dwmti.cRefresh + 1;
dwmpp.cBuffer := DWM_BUFFER_COUNT;
dwmpp.fUseSourceRate := False;
dwmpp.cRefreshesPerFrame := 1;
dwmpp.eSampling := DWM_SOURCE_FRAME_SAMPLING_POINT;
hr := PFNDWMSETPRESENTPARAMETERS(g_pfnDwmSetPresentParameters)(g_Hwnd, dwmpp);
if (FAILED(hr)) then
begin
// DBGMSG((TEXT("DwmSetPresentParameters failed with error $%x.\n"), hr));
Result := False;
Exit;
end;
// DWM queuing is enabled.
g_bDwmQueuing := True;
Result := True;
end;
function ChangeFullscreenMode(bFullscreen: boolean): boolean;
begin
// Mark the mode change in progress to prevent the device is being reset in OnSize.
// This is because these API calls below will generate WM_SIZE messages.
g_bInModeChange := True;
if (bFullscreen) then
begin
// Save the window position.
if (not GetWindowRect(g_Hwnd, g_RectWindow)) then
begin
// DBGMSG((TEXT("GetWindowRect failed with error %d.\n"), GetLastError()));
Result := False;
Exit;
end;
if (SetWindowLongPtr(g_Hwnd, GWL_STYLE, WS_POPUP or WS_VISIBLE) = 0) then
begin
// DBGMSG((TEXT("SetWindowLongPtr failed with error %d.\n"), GetLastError()));
Result := False;
Exit;
end;
if (not SetWindowPos(g_Hwnd, HWND_NOTOPMOST, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN),
SWP_FRAMECHANGED)) then
begin
// DBGMSG((TEXT("SetWindowPos failed with error %d.\n"), GetLastError()));
Result := False;
Exit;
end;
end
else
begin
if (SetWindowLongPtr(g_Hwnd, GWL_STYLE, WS_OVERLAPPEDWINDOW or WS_VISIBLE) = 0) then
begin
// DBGMSG((TEXT("SetWindowLongPtr failed with error %d.\n"), GetLastError()));
Result := False;
Exit;
end;
// Restore the window position.
if (not SetWindowPos(g_Hwnd, HWND_NOTOPMOST, g_RectWindow.left, g_RectWindow.top, g_RectWindow.right -
g_RectWindow.left, g_RectWindow.bottom - g_RectWindow.top, SWP_FRAMECHANGED)) then
begin
// DBGMSG((TEXT("SetWindowPos failed with error %d.\n"), GetLastError()));
Result := False;
Exit;
end;
end;
g_bInModeChange := False;
Result := True;
end;
function ResetDevice(bChangeWindowMode: boolean = False): boolean;
var
hr: HRESULT;
d3dpp: D3DPRESENT_PARAMETERS;
begin
if (bChangeWindowMode) then
begin
g_bWindowed := not g_bWindowed;
if (not ChangeFullscreenMode(not g_bWindowed)) then
begin
Result := False;
Exit;
end;
end;
if (g_pD3DD9 <> nil) then
begin
// Destroy DXVA2 device because it may be holding any D3D9 resources.
DestroyDXVA2();
if (g_bWindowed) then
begin
g_D3DPP.BackBufferWidth := 0;
g_D3DPP.BackBufferHeight := 0;
end
else
begin
g_D3DPP.BackBufferWidth := GetSystemMetrics(SM_CXSCREEN);
g_D3DPP.BackBufferHeight := GetSystemMetrics(SM_CYSCREEN);
end;
g_D3DPP.Windowed := g_bWindowed;
// Reset will change the parameters, so use a copy instead.
d3dpp := g_D3DPP;
hr := g_pD3DD9.Reset(d3dpp);
if (FAILED(hr)) then
begin
// DBGMSG((TEXT("Reset failed with error $%x.\n"), hr));
end;
if (SUCCEEDED(hr) and InitializeDXVA2()) then
begin
Result := True;
Exit;
end;
// If either Reset didn't work or failed to initialize DXVA2 device,
// try to recover by recreating the devices from the scratch.
DestroyDXVA2();
DestroyD3D9();
end;
if (InitializeD3D9() and InitializeDXVA2()) then
begin
Result := True;
Exit;
end;
// Fallback to Window mode, if failed to initialize Fullscreen mode.
if (g_bWindowed) then
begin
Result := False;
Exit;
end;
DestroyDXVA2();
DestroyD3D9();
if (not ChangeFullscreenMode(False)) then
begin
Result := False;
Exit;
end;
g_bWindowed := True;
if (InitializeD3D9() and InitializeDXVA2()) then
begin
Result := True;
Exit;
end;
Result := False;
end;
function GetFrameNumber(): DWORD;
var
currentTime: DWORD;
currentSysTime: DWORD;
frame: dword;
delta: dword;
begin
currentSysTime := timeGetTime();
if (g_StartSysTime > currentSysTime) then
begin
currentTime := currentSysTime + ($FFFFFFFF - g_StartSysTime);
end
else
begin
currentTime := currentSysTime - g_StartSysTime;
end;
frame := currentTime div VIDEO_MSPF;
delta := (currentTime - g_PreviousTime) div VIDEO_MSPF;
if (delta > 1) then
begin
if (g_bDspFrameDrop) then
begin
//DBGMSG((TEXT("Frame dropped %u frame(s).\n"), delta - 1));
end;
end;
if (delta > 0) then
begin
g_PreviousTime := currentTime;
end;
Result := frame;
end;
function GetBackgroundColor(): TDXVA2_AYUVSample16;
var
yuv: D3DCOLOR;
y, u, v: byte;
color: TDXVA2_AYUVSample16;
begin
yuv := RGBtoYUV(BACKGROUND_COLORS[g_BackgroundColor]);
Y := LOBYTE(HIWORD(yuv));
U := HIBYTE(LOWORD(yuv));
V := LOBYTE(LOWORD(yuv));
color.Cr := V * $100;
color.Cb := U * $100;
color.Y := Y * $100;
color.Alpha := $FFFF;
Result := color;
end;
function ScaleRectangle(const input: TRECT; const src: TRECT; const dst: TRECT): TRECT;
var
rect: TRECT;
src_dx, src_dy, dst_dx, dst_dy: UINT;
begin
src_dx := src.right - src.left;
src_dy := src.bottom - src.top;
dst_dx := dst.right - dst.left;
dst_dy := dst.bottom - dst.top;
// Scale input rectangle within src rectangle to dst rectangle.
rect.left := input.left * dst_dx div src_dx;
rect.right := input.right * dst_dx div src_dx;
rect.top := input.top * dst_dy div src_dy;
rect.bottom := input.bottom * dst_dy div src_dy;
Result := rect;
end;
function ProcessVideo(): boolean;
var
hr: HRESULT;
rect: TRECT;
blt: TDXVA2_VideoProcessBltParams;
samples: array [0..1] of TDXVA2_VideoSample;
frame: DWORD;
start_100ns: LONGLONG;
end_100ns: LONGLONG;
client: TRECT;
target: TRECT;
ssdest: TRECT;
x, y, wx, wy: integer;
lHandle: THandle;
begin
if (g_pD3DD9 = nil) then
begin
Result := False;
Exit;
end;
GetClientRect(g_Hwnd, rect);
if (IsRectEmpty(rect)) then
begin
Result := True;
Exit;
end;
// Check the current status of D3D9 device.
hr := g_pD3DD9.TestCooperativeLevel();
case (hr) of
D3D_OK:
begin
end;
D3DERR_DEVICELOST:
begin
// DBGMSG((TEXT("TestCooperativeLevel returned D3DERR_DEVICELOST.\n")));
Result := True;
end;
D3DERR_DEVICENOTRESET:
begin
// DBGMSG((TEXT("TestCooperativeLevel returned D3DERR_DEVICENOTRESET.\n")));
if (not ResetDevice()) then
begin
Result := False;
Exit;
end;
end;
else
begin
// DBGMSG((TEXT("TestCooperativeLevel failed with error $%x.\n"), hr));
Result := False;
Exit;
end;
end;
ZeroMemory(@blt, SizeOf(TDXVA2_VideoProcessBltParams));
ZeroMemory(@samples, SizeOf(samples));
frame := GetFrameNumber();
start_100ns := frame * LONGLONG(VIDEO_100NSPF);
end_100ns := start_100ns + LONGLONG(VIDEO_100NSPF);
GetClientRect(g_Hwnd, client);
target.left := client.left + (client.right - client.left) div 2 * (100 - g_TargetWidthPercent) div 100;
target.right := client.right - (client.right - client.left) div 2 * (100 - g_TargetWidthPercent) div 100;
target.top := client.top + (client.bottom - client.top) div 2 * (100 - g_TargetHeightPercent) div 100;
target.bottom := client.bottom - (client.bottom - client.top) div 2 * (100 - g_TargetHeightPercent) div 100;
// Calculate sub stream destination based on the current frame number.
x := frame * VIDEO_SUB_VX;
wx := VIDEO_MAIN_WIDTH - VIDEO_SUB_WIDTH;
if ((x div wx) and $1 <> 0) then
begin
x := wx - (x mod wx);
end
else
begin
x := x mod wx;
end;
y := frame * VIDEO_SUB_VY;
wy := VIDEO_MAIN_HEIGHT - VIDEO_SUB_HEIGHT;
if ((y div wy) and $1 <> 0) then
begin
y := wy - (y mod wy);
end
else
begin
y := y mod wy;
end;
SetRect(ssdest, x, y, x + VIDEO_SUB_WIDTH, y + VIDEO_SUB_HEIGHT);
// Initialize VPBlt parameters.
blt.TargetFrame := start_100ns;
blt.TargetRect := target;
// DXVA2_VideoProcess_Constriction
blt.ConstrictionSize.cx := target.right - target.left;
blt.ConstrictionSize.cy := target.bottom - target.top;
blt.BackgroundColor := GetBackgroundColor();
// DXVA2_VideoProcess_YUV2RGBExtended
blt.DestFormat.VideoChromaSubsampling := Ord(DXVA2_VideoChromaSubsampling_Unknown);
blt.DestFormat.NominalRange := EX_COLOR_INFO[g_ExColorInfo][1];
blt.DestFormat.VideoTransferMatrix := Ord(DXVA2_VideoTransferMatrix_Unknown);
blt.DestFormat.VideoLighting := Ord(DXVA2_VideoLighting_dim);
blt.DestFormat.VideoPrimaries := Ord(DXVA2_VideoPrimaries_BT709);
blt.DestFormat.VideoTransferFunction := Ord(DXVA2_VideoTransFunc_709);
blt.DestFormat.SampleFormat := Ord(DXVA2_SampleProgressiveFrame);
// DXVA2_ProcAmp_Brightness
blt.ProcAmpValues.Brightness := g_ProcAmpValues[0];
// DXVA2_ProcAmp_Contrast
blt.ProcAmpValues.Contrast := g_ProcAmpValues[1];
// DXVA2_ProcAmp_Hue
blt.ProcAmpValues.Hue := g_ProcAmpValues[2];
// DXVA2_ProcAmp_Saturation
blt.ProcAmpValues.Saturation := g_ProcAmpValues[3];
// DXVA2_VideoProcess_AlphaBlend
blt.Alpha := DXVA2_Fixed32OpaqueAlpha();
// DXVA2_VideoProcess_NoiseFilter
blt.NoiseFilterLuma.Level := g_NFilterValues[0];
blt.NoiseFilterLuma.Threshold := g_NFilterValues[1];
blt.NoiseFilterLuma.Radius := g_NFilterValues[2];
blt.NoiseFilterChroma.Level := g_NFilterValues[3];
blt.NoiseFilterChroma.Threshold := g_NFilterValues[4];
blt.NoiseFilterChroma.Radius := g_NFilterValues[5];
// DXVA2_VideoProcess_DetailFilter
blt.DetailFilterLuma.Level := g_DFilterValues[0];
blt.DetailFilterLuma.Threshold := g_DFilterValues[1];
blt.DetailFilterLuma.Radius := g_DFilterValues[2];
blt.DetailFilterChroma.Level := g_DFilterValues[3];
blt.DetailFilterChroma.Threshold := g_DFilterValues[4];
blt.DetailFilterChroma.Radius := g_DFilterValues[5];
// Initialize main stream video sample.
samples[0].Start := start_100ns;
samples[0].Ende := end_100ns;
// DXVA2_VideoProcess_YUV2RGBExtended
samples[0].SampleFormat.VideoChromaSubsampling := Ord(DXVA2_VideoChromaSubsampling_MPEG2);
samples[0].SampleFormat.NominalRange := Ord(DXVA2_NominalRange_16_235);
samples[0].SampleFormat.VideoTransferMatrix := EX_COLOR_INFO[g_ExColorInfo][0];
samples[0].SampleFormat.VideoLighting := Ord(DXVA2_VideoLighting_dim);
samples[0].SampleFormat.VideoPrimaries := Ord(DXVA2_VideoPrimaries_BT709);
samples[0].SampleFormat.VideoTransferFunction := Ord(DXVA2_VideoTransFunc_709);
samples[0].SampleFormat.SampleFormat := Ord(DXVA2_SampleProgressiveFrame);
samples[0].SrcSurface := g_pMainStream;
// DXVA2_VideoProcess_SubRects
samples[0].SrcRect := g_SrcRect;
// DXVA2_VideoProcess_StretchX, Y
samples[0].DstRect := ScaleRectangle(g_DstRect, VIDEO_MAIN_RECT, client);
// DXVA2_VideoProcess_PlanarAlpha
samples[0].PlanarAlpha := DXVA2FloatToFixed(g_PlanarAlphaValue / $FF);
// Initialize sub stream video sample.
samples[1] := samples[0];
// DXVA2_VideoProcess_SubStreamsExtended
samples[1].SampleFormat := samples[0].SampleFormat;
// DXVA2_VideoProcess_SubStreams
samples[1].SampleFormat.SampleFormat := Ord(DXVA2_SampleSubStream);
samples[1].SrcSurface := g_pSubStream;
samples[1].SrcRect := VIDEO_SUB_RECT;
samples[1].DstRect := ScaleRectangle(ssdest, VIDEO_MAIN_RECT, client);
if (not UpdateSubStream()) then
begin
Result := False;
Exit;
end;
if (g_TargetWidthPercent < 100) or (g_TargetHeightPercent < 100) then
begin
hr := g_pD3DD9.ColorFill(g_pD3DRT, nil, D3DCOLOR_XRGB(0, 0, 0));
if (FAILED(hr)) then
begin
// DBGMSG((TEXT("ColorFill failed with error $%x.\n"), hr));
end;
end;
hr := g_pDXVAVPD.VideoProcessBlt(g_pD3DRT, blt, samples, SUB_STREAM_COUNT + 1, lHandle);
if (FAILED(hr)) then
begin
//DBGMSG((TEXT("VideoProcessBlt failed with error $%x.\n"), hr));
end;
// Re-enable DWM queuing if it is not enabled.
EnableDwmQueuing();
hr := g_pD3DD9.Present(nil, nil, 0, nil);
if (FAILED(hr)) then
begin
// DBGMSG((TEXT("Present failed with error $%x.\n"), hr));
end;
Result := True;
end;
procedure OnDestroy(hwnd: HWND);
begin
PostQuitMessage(0);
end;
procedure ResetParameter();
begin
case (g_VK_Fx) of
VK_F1:
begin
g_PlanarAlphaValue := DEFAULT_PLANAR_ALPHA_VALUE;
g_PixelAlphaValue := DEFAULT_PIXEL_ALPHA_VALUE;
g_bUpdateSubStream := True;
end;
VK_F2, VK_F3:
begin
g_SrcRect := VIDEO_MAIN_RECT;
end;
VK_F4, VK_F5:
begin
g_DstRect := VIDEO_MAIN_RECT;
end;
VK_F6:
begin
g_BackgroundColor := 0;
g_ExColorInfo := 0;
end;
VK_F7:
begin
g_ProcAmpValues[0] := g_ProcAmpRanges[0].DefaultValue;
g_ProcAmpValues[1] := g_ProcAmpRanges[1].DefaultValue;
end;
VK_F8:
begin
g_ProcAmpValues[2] := g_ProcAmpRanges[2].DefaultValue;
g_ProcAmpValues[3] := g_ProcAmpRanges[3].DefaultValue;
end;
VK_F9:
begin
g_TargetWidthPercent := 100;
g_TargetHeightPercent := 100;
end;
end;
end;
function ValidateValueRange(const Value: TDXVA2_Fixed32; const steps: integer; const range: TDXVA2_ValueRange): TDXVA2_Fixed32;
var
f_value, f_max, f_min: single;
begin
f_value := DXVA2FixedToFloat(Value);
f_max := DXVA2FixedToFloat(range.MaxValue);
f_min := DXVA2FixedToFloat(range.MinValue);
f_value := f_value + DXVA2FixedToFloat(range.StepSize) * steps;
f_value := min(max(f_value, f_min), f_max);
Result := DXVA2FloatToFixed(f_value);
end;
procedure IncrementParameter(vk: UINT);
var
rect, intersect: TRECT;
begin
case (g_VK_Fx) of
VK_F1:
begin
if (vk = VK_UP) then
begin
g_PlanarAlphaValue := min(g_PlanarAlphaValue + 8, $FF);
end
else
begin
g_PixelAlphaValue := min(g_PixelAlphaValue + 8, $FF);
g_bUpdateSubStream := True;
end;
end;
VK_F2:
begin
rect := g_SrcRect;
if vk = VK_UP then
InflateRect(rect, 0, -8)
else
InflateRect(rect, -8, 0);
IntersectRect(intersect, rect, VIDEO_MAIN_RECT);
if (not IsRectEmpty(intersect)) then
begin
g_SrcRect := intersect;
end;
end;
VK_F3:
begin
rect := g_SrcRect;
if (vk = VK_UP) then
OffsetRect(rect, 0, -8)
else
OffsetRect(rect, 8, 0);
IntersectRect(intersect, rect, VIDEO_MAIN_RECT);
if (EqualRect(rect, intersect)) then
begin
g_SrcRect := rect;
end;
end;
VK_F4:
begin
rect := g_DstRect;
if (vk = VK_UP) then
InflateRect(rect, 0, 8)
else
InflateRect(rect, 8, 0);
IntersectRect(intersect, rect, VIDEO_MAIN_RECT);
if (not IsRectEmpty(intersect)) then
begin
g_DstRect := intersect;
end;
end;
VK_F5:
begin
rect := g_DstRect;
if (vk = VK_UP) then
OffsetRect(rect, 0, -8)
else
OffsetRect(rect, 8, 0);
IntersectRect(intersect, rect, VIDEO_MAIN_RECT);
if (EqualRect(rect, intersect)) then
begin
g_DstRect := rect;
end;
end;
VK_F6:
begin
if (vk = VK_UP) then
begin
Inc(g_ExColorInfo);
if (g_ExColorInfo >= length(EX_COLOR_INFO)) then
begin
g_ExColorInfo := 0;
end;
end
else
begin
Inc(g_BackgroundColor);
if (g_BackgroundColor >= length(BACKGROUND_COLORS)) then
begin
g_BackgroundColor := 0;
end;
end;
end;
VK_F7:
begin
if (vk = VK_UP) then
g_ProcAmpValues[0] := ValidateValueRange(g_ProcAmpValues[0], g_ProcAmpSteps[0], g_ProcAmpRanges[0])
else
g_ProcAmpValues[1] := ValidateValueRange(g_ProcAmpValues[1], g_ProcAmpSteps[1], g_ProcAmpRanges[1]);
end;
VK_F8:
begin
if (vk = VK_UP) then
g_ProcAmpValues[2] := ValidateValueRange(g_ProcAmpValues[2], g_ProcAmpSteps[2], g_ProcAmpRanges[2])
else
g_ProcAmpValues[3] := ValidateValueRange(g_ProcAmpValues[3], g_ProcAmpSteps[3], g_ProcAmpRanges[3]);
end;
VK_F9:
begin
if (vk = VK_UP) then
g_TargetHeightPercent := min(g_TargetHeightPercent + 4, 100)
else
g_TargetWidthPercent := min(g_TargetWidthPercent + 4, 100);
end;
end;
end;
procedure DecrementParameter(vk: UINT);
var
rect, intersect: TRECT;
begin
case (g_VK_Fx) of
VK_F1:
begin
if (vk = VK_DOWN) then
begin
g_PlanarAlphaValue := max(g_PlanarAlphaValue - 8, 0);
end
else
begin
g_PixelAlphaValue := max(g_PixelAlphaValue - 8, 0);
g_bUpdateSubStream := True;
end;
end;
VK_F2:
begin
rect := g_SrcRect;
if (vk = VK_DOWN) then
InflateRect(rect, 0, 8)
else
InflateRect(rect, 8, 0);
IntersectRect(intersect, rect, VIDEO_MAIN_RECT);
if (not IsRectEmpty(intersect)) then
begin
g_SrcRect := intersect;
end;
end;
VK_F3:
begin
rect := g_SrcRect;
if vk = VK_DOWN then
OffsetRect(rect, 0, 8)
else
OffsetRect(rect, -8, 0);
IntersectRect(intersect, rect, VIDEO_MAIN_RECT);
if (EqualRect(rect, intersect)) then
begin
g_SrcRect := rect;
end;
end;
VK_F4:
begin
rect := g_DstRect;
if (vk = VK_DOWN) then
InflateRect(rect, 0, -8)
else
InflateRect(rect, -8, 0);
IntersectRect(intersect, rect, VIDEO_MAIN_RECT);
if (not IsRectEmpty(intersect)) then
begin
g_DstRect := intersect;
end;
end;
VK_F5:
begin
rect := g_DstRect;
if (vk = VK_DOWN) then
OffsetRect(rect, 0, 8)
else
OffsetRect(rect, -8, 0);
IntersectRect(intersect, rect, VIDEO_MAIN_RECT);
if (EqualRect(rect, intersect)) then
begin
g_DstRect := rect;
end;
end;
VK_F6:
begin
if (vk = VK_DOWN) then
begin
Dec(g_ExColorInfo);
if (g_ExColorInfo < 0) then
begin
g_ExColorInfo := length(EX_COLOR_INFO) - 1;
end;
end
else
begin
Dec(g_BackgroundColor);
if (g_BackgroundColor < 0) then
begin
g_BackgroundColor := length(BACKGROUND_COLORS) - 1;
end;
end;
end;
VK_F7:
begin
if (vk = VK_DOWN) then
begin
g_ProcAmpValues[0] := ValidateValueRange(g_ProcAmpValues[0], g_ProcAmpSteps[0] * -1, g_ProcAmpRanges[0]);
end
else
begin
g_ProcAmpValues[1] := ValidateValueRange(g_ProcAmpValues[1], g_ProcAmpSteps[1] * -1, g_ProcAmpRanges[1]);
end;
end;
VK_F8:
begin
if (vk = VK_DOWN) then
begin
g_ProcAmpValues[2] := ValidateValueRange(g_ProcAmpValues[2], g_ProcAmpSteps[2] * -1, g_ProcAmpRanges[2]);
end
else
begin
g_ProcAmpValues[3] := ValidateValueRange(g_ProcAmpValues[3], g_ProcAmpSteps[3] * -1, g_ProcAmpRanges[3]);
end;
end;
VK_F9:
begin
if (vk = VK_DOWN) then
begin
g_TargetHeightPercent := max(g_TargetHeightPercent - 4, 4);
end
else
begin
g_TargetWidthPercent := max(g_TargetWidthPercent - 4, 4);
end;
end;
end;
end;
procedure OnKey(hwnd: HWND; vk: UINT; fDown: boolean; cRepeat: integer; flags: UINT);
begin
if (not fDown) then
begin
Exit;
end;
if (vk = VK_ESCAPE) then
begin
DestroyWindow(hwnd);
Exit;
end;
if (g_pD3DD9 = nil) then
begin
Exit;
end;
case (vk) of
VK_F1, VK_F2, VK_F3, VK_F4, VK_F5, VK_F6, VK_F7, VK_F8, VK_F9:
begin
g_VK_Fx := vk;
g_bUpdateSubStream := True;
end;
VK_HOME:
ResetParameter();
VK_END:
g_bDspFrameDrop := not g_bDspFrameDrop;
VK_UP, VK_RIGHT:
IncrementParameter(vk);
VK_DOWN, VK_LEFT:
DecrementParameter(vk);
end;
end;
procedure OnPaint(hwnd: HWND);
begin
ValidateRect(hwnd, nil);
ProcessVideo();
end;
procedure OnSize(hwnd: HWND; state: UINT; cx: integer; cy: integer);
var
rect: TRECT;
begin
if (g_pD3DD9 = nil) then
begin
Exit;
end;
GetClientRect(hwnd, rect);
if (IsRectEmpty(rect)) then
begin
Exit;
end;
// Do not reset the device while the mode change is in progress.
if (g_bInModeChange) then
begin
Exit;
end;
if (not ResetDevice()) then
begin
DestroyWindow(hwnd);
Exit;
end;
InvalidateRect(hwnd, nil, False);
end;
function WindowProc(hwnd: HWND; uMsg: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
begin
case (uMsg) of
WM_DESTROY:
begin
OnDestroy(hwnd);
Result := 0;
end;
WM_KEYDOWN:
begin
OnKey(hwnd, wparam, True, LOWORD(lParam), hiword(lparam));
Result := 0;
end;
WM_PAINT:
begin
OnPaint(hwnd);
Result := 0;
end;
WM_SIZE:
begin
OnSize(hwnd, WParam, loword(lparam), hiword(lParam));
Result := 0;
end;
else
Result := DefWindowProc(hwnd, uMsg, wParam, lParam);
end;
end;
function InitializeWindow(): boolean;
var
wc: WNDCLASS;
begin
zeroMemory(@wc, SizeOf(wc));
wc.lpfnWndProc := @WindowProc;
wc.hInstance := GetModuleHandle(0);
wc.hCursor := LoadCursor(0, IDC_ARROW);
wc.lpszClassName := PAnsiChar(CLASS_NAME);
if (RegisterClass(wc) = 0) then
begin
// DBGMSG((TEXT("RegisterClass failed with error %d.\n"), GetLastError()));
Result := False;
Exit;
end;
// Start in Window mode regardless of the initial mode.
g_Hwnd := CreateWindow(PAnsiChar(CLASS_NAME), PAnsiChar(WINDOW_NAME), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, GetModuleHandle(0), 0);
if (g_Hwnd = 0) then
begin
// DBGMSG((TEXT("CreateWindow failed with error %d.\n"), GetLastError()));
Result := False;
Exit;
end;
ShowWindow(g_Hwnd, SW_SHOWDEFAULT);
UpdateWindow(g_Hwnd);
// Change the window from Window mode to Fullscreen mode.
if (not g_bWindowed) then
begin
if (not ChangeFullscreenMode(True)) then
begin
// If failed, revert to Window mode.
if (not ChangeFullscreenMode(False)) then
begin
Result := False;
Exit;
end;
g_bWindowed := True;
end;
end;
Result := True;
end;
function InitializeTimer(): boolean;
var
li: TLargeInteger;
begin
g_hTimer := CreateWaitableTimer(0, False, 0);
if (g_hTimer = 0) then
begin
// DBGMSG((TEXT("CreateWaitableTimer failed with error %d.\n"), GetLastError()));
Result := False;
Exit;
end;
li := 0;
if (not SetWaitableTimer(g_hTimer, li, VIDEO_MSPF, 0, 0, False)) then
begin
// DBGMSG((TEXT("SetWaitableTimer failed with error %d.\n"), GetLastError()));
Result := False;
Exit;
end;
g_bTimerSet := (timeBeginPeriod(1) = TIMERR_NOERROR);
g_StartSysTime := timeGetTime();
Result := True;
end;
procedure DestroyTimer();
begin
if (g_bTimerSet) then
begin
timeEndPeriod(1);
g_bTimerSet := False;
end;
if (g_hTimer <> 0) then
begin
CloseHandle(g_hTimer);
g_hTimer := 0;
end;
end;
function PreTranslateMessage(const msg: TMSG): boolean;
var
rect: TRECT;
begin
// Only interested in Alt + Enter.
if (msg.message <> WM_SYSKEYDOWN) or (msg.wParam <> VK_RETURN) then
begin
Result := False;
Exit;
end;
if (g_pD3DD9 = nil) then
begin
Result := True;
Exit;
end;
GetClientRect(msg.hwnd, &rect);
if (IsRectEmpty(rect)) then
begin
Result := True;
Exit;
end;
if (ResetDevice(True)) then
begin
Result := True;
Exit;
end;
DestroyWindow(msg.hwnd);
Result := True;
end;
function MessageLoop(): integer;
var
msg: TMSG;
begin
while (msg.message <> WM_QUIT) do
begin
if (PeekMessage(msg, 0, 0, 0, PM_REMOVE)) then
begin
if (PreTranslateMessage(msg)) then
begin
continue;
end;
TranslateMessage(&msg);
DispatchMessage(&msg);
continue;
end;
// Wait until the timer expires or any message is posted.
if (MsgWaitForMultipleObjects(1, g_hTimer, False, INFINITE, QS_ALLINPUT) = WAIT_OBJECT_0) then
begin
if (not ProcessVideo()) then
begin
DestroyWindow(g_Hwnd);
end;
end;
end;
Result := integer(msg.wParam);
end;
function InitializeModule(): boolean;
begin
// Load these DLLs dynamically because these may not be available prior to Vista.
g_hRgb9rastDLL := LoadLibrary('rgb9rast.dll');
if (g_hRgb9rastDLL <> 0) then
begin
// DBGMSG((TEXT("LoadLibrary(rgb9rast.dll) failed with error %d.\n"), GetLastError()));
// goto SKIP_RGB9RAST;
g_pfnD3D9GetSWInfo := GetProcAddress(g_hRgb9rastDLL, 'D3D9GetSWInfo');
if (g_pfnD3D9GetSWInfo = nil) then
begin
// DBGMSG((TEXT("GetProcAddress(D3D9GetSWInfo) failed with error %d.\n"), GetLastError()));
Result := False;
Exit;
end;
end;
// SKIP_RGB9RAST:
g_hDwmApiDLL := LoadLibrary('dwmapi.dll');
if (g_hDwmApiDLL <> 0) then
begin
// DBGMSG((TEXT("LoadLibrary(dwmapi.dll) failed with error %d.\n"), GetLastError()));
// goto SKIP_DWMAPI;
g_pfnDwmIsCompositionEnabled := GetProcAddress(g_hDwmApiDLL, 'DwmIsCompositionEnabled');
if (g_pfnDwmIsCompositionEnabled = nil) then
begin
// DBGMSG((TEXT("GetProcAddress(DwmIsCompositionEnabled) failed with error %d.\n"), GetLastError()));
Result := False;
Exit;
end;
g_pfnDwmGetCompositionTimingInfo := GetProcAddress(g_hDwmApiDLL, 'DwmGetCompositionTimingInfo');
if (g_pfnDwmGetCompositionTimingInfo = nil) then
begin
// DBGMSG((TEXT("GetProcAddress(DwmGetCompositionTimingInfo) failed with error %d.\n"), GetLastError()));
Result := False;
Exit;
end;
g_pfnDwmSetPresentParameters := GetProcAddress(g_hDwmApiDLL, 'DwmSetPresentParameters');
if (g_pfnDwmSetPresentParameters = nil) then
begin
// DBGMSG((TEXT("GetProcAddress(DwmSetPresentParameters) failed with error %d.\n"), GetLastError()));
Result := False;
Exit;
end;
end;
// SKIP_DWMAPI:
Result := True;
end;
function InitializeParameter(psz: PWideChar): boolean;
begin
Result := True;
end;
begin
RGB_WHITE := D3DCOLOR_XRGB($EB, $EB, $EB);
RGB_RED := D3DCOLOR_XRGB($EB, $10, $10);
RGB_YELLOW := D3DCOLOR_XRGB($EB, $EB, $10);
RGB_GREEN := D3DCOLOR_XRGB($10, $EB, $10);
RGB_CYAN := D3DCOLOR_XRGB($10, $EB, $EB);
RGB_BLUE := D3DCOLOR_XRGB($10, $10, $EB);
RGB_MAGENTA := D3DCOLOR_XRGB($EB, $10, $EB);
RGB_BLACK := D3DCOLOR_XRGB($10, $10, $10);
RGB_ORANGE := D3DCOLOR_XRGB($EB, $7E, $10);
// 75%
RGB_WHITE_75pc := D3DCOLOR_XRGB($B4, $B4, $B4);
RGB_YELLOW_75pc := D3DCOLOR_XRGB($B4, $B4, $10);
RGB_CYAN_75pc := D3DCOLOR_XRGB($10, $B4, $B4);
RGB_GREEN_75pc := D3DCOLOR_XRGB($10, $B4, $10);
RGB_MAGENTA_75pc := D3DCOLOR_XRGB($B4, $10, $B4);
RGB_RED_75pc := D3DCOLOR_XRGB($B4, $10, $10);
RGB_BLUE_75pc := D3DCOLOR_XRGB($10, $10, $B4);
// -4% / +4%
RGB_BLACK_n4pc := D3DCOLOR_XRGB($07, $07, $07);
RGB_BLACK_p4pc := D3DCOLOR_XRGB($18, $18, $18);
// -Inphase / +Quadrature
RGB_I := D3DCOLOR_XRGB($00, $1D, $42);
RGB_Q := D3DCOLOR_XRGB($2C, $00, $5C);
VIDEO_SUB_FORMAT := D3DFORMAT('VUYA'); // AYUV
VIDEO_SUB_FORMAT := byte('A') or (byte('Y') shl 8) or (byte('U') shl 16) or (byte('V') shl 24);
// VIDEO_SUB_FORMAT := Byte('V') or (Byte('U') shl 8) or (Byte('Y') shl 16) or (Byte('A') shl 24);
BACKGROUND_COLORS[0] := RGB_WHITE;
BACKGROUND_COLORS[1] := RGB_RED;
BACKGROUND_COLORS[2] := RGB_YELLOW;
BACKGROUND_COLORS[3] := RGB_GREEN;
BACKGROUND_COLORS[4] := RGB_CYAN;
BACKGROUND_COLORS[5] := RGB_BLUE;
BACKGROUND_COLORS[6] := RGB_MAGENTA;
BACKGROUND_COLORS[7] := RGB_BLACK;
if (InitializeModule() and InitializeParameter('') and InitializeWindow() and InitializeD3D9() and
InitializeDXVA2() and InitializeTimer()) then
begin
MessageLoop();
end;
DestroyTimer();
DestroyDXVA2();
DestroyD3D9();
end.
|
{Необходимо записать данные обо всех подписчиках некоторого почтового отделения в файл. Формат сведений: индекс издания, газета(журнал),
фамилия, адрес подписчика, количество экземпляровкаждого из изданий. Все сведения заносятся в список. Разработать хеш-таблицу для
обработки сведений о подписчиках, ключом для формирования таблицы взять почтовый индекс издания. Всех подписчиков одного издания
упорядочить по фамилиям методом вставки. Обеспечить поиск подписчика, дополнение списков подписчиков. Все виды работ выполнять через меню.}
program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils;
type PList = ^subscriber;
subscriber = record
index : integer;
magazine : string[255];
surname : string[255];
address : string[255];
copy : integer;
next : PList;
end;
ff_rec = file of subscriber;
var hashTable : array [1..100] of Plist;
x, p : PList;
i, hashQuantity, menu, number : integer;
theSameIndex : boolean;
forWriting, forReading : ff_rec;
temp : subscriber;
procedure cin();
begin
writeln('Enter index of publication.');
readln(temp.index);
writeln('Enter name of the magazine/newspaper.');
readln(temp.magazine);
writeln('Enter subscriber surname.');
readln(temp.surname);
writeln('Enter subscriber address.');
readln(temp.address);
writeln('Enter number of copies.');
readln(temp.copy);
temp.next := nil;
end;
begin
assign(forWriting, 'info.dat');
assign(forReading, 'info.dat');
//clearing a file before starting work
rewrite(forWriting);
close(forWriting);
hashQuantity := 0;
//initializing a hash table
for i := 1 to 10 do
hashTable[i] := nil;
repeat
writeln('Enter 1 to add data in file.');
writeln('Enter 2 to display data from the file to the console');
writeln('Enter 3 to create a hashtable');
writeln('Enter 0 end work with this program.');
readln(menu);
if (menu = 1) then
begin
reset(forWriting);
while not Eof(forWriting) do
begin
read(forWriting, temp);
end;
//rewrite(forWriting);
writeln('Enter how many subscribers do you want to add.');
readln(number);
for i := 1 to number do
begin
cin();
write(forWriting, temp);
end;
close(forWriting);
end;
if (menu = 2) then
begin
reset(forReading);
while not Eof(forReading) do
begin
read(forReading, temp);
writeln(temp.index, ' ', temp.magazine, ' ', temp.surname, ' ', temp.address, ' ', temp.copy);
end;
writeln;
close(forReading)
end;
if(menu = 3) then
begin
hashQuantity := 0;
//initializing a hash table
for i := 1 to 10 do
hashTable[i] := nil;
reset(forReading);
while not Eof(forReading) do
begin
theSameIndex := false; //While not found the list for this index
new(x);
read(forReading, temp);
x^ := temp;
//If the hashtable is empty, just add the first key
if (hashQuantity = 0) then
begin
hashTable[1] := x;
hashQuantity := hashQuantity + 1;
end
else begin
//Checking the existence of a pointer to a list with this index
for i := 1 to hashQuantity do
if(x^.index = hashTable[i]^.index) then
begin
theSameIndex := true; //Found!
//insert
if(x^.surname < hashTable[i]^.surname) then
begin
x^.next := hashTable[i];
hashTable[i] := x;
end
else begin
p := hashTable[i];
while (p<>Nil) do
begin
if(p^.surname < x^.surname) then
begin
if (p^.next = nil) then
begin
p^.next := x;
p := nil;
end
else if(x^.surname < p^.next^.surname) then
begin
x^.next := p^.next;
p^.next := x;
p := nil;
end;
end
else p := p^.next;
end;
end;
end;
if (theSameIndex = false) then
begin
hashQuantity := hashQuantity + 1;
hashTable[hashQuantity] := x;
end;
end;
end;
for i := 1 to hashQuantity do
begin
p := hashTable[i];
writeln(hashTable[i]^.index, ':');
while p<>nil do
begin
writeln(p^.surname, ' ', p^.address, ' ', p^.magazine, ' ', p^.copy);
p := p^.next;
end;
writeln;
end;
close(forReading);
end;
until (menu = 0);
readln;
end.
|
unit Demo.PieChart_3D;
interface
uses
System.Classes, Demo.BaseFrame, cfs.GCharts;
type
TDemo_PieChart_3D = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_PieChart_3D.GenerateChart;
var
Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_PIE_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Tasks'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Hours per Day')
]);
Chart.Data.AddRow(['Work', 11]);
Chart.Data.AddRow(['Eat', 2]);
Chart.Data.AddRow(['Commute', 2]);
Chart.Data.AddRow(['Watch TV', 2]);
Chart.Data.AddRow(['Sleep', 7]);
// Options
Chart.Options.Title('My Daily Activities');
Chart.Options.Is3D(True);
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody('<div id="Chart1" style="width:100%;height:100%;"></div>');
GChartsFrame.DocumentGenerate('Chart1', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_PieChart_3D);
end.
|
unit OrcamentoItens.Model;
interface
uses OrcamentoItens.Model.Interf, TESTORCAMENTOITENS.Entidade.Model,
ormbr.container.objectset.interfaces, ormbr.Factory.interfaces;
type
TOrcamentoItensModel = class(TInterfacedObject, IOrcamentoItensModel)
private
FConexao: IDBConnection;
FEntidade: TTESTORCAMENTOITENS;
FDao: IContainerObjectSet<TTESTORCAMENTOITENS>;
public
constructor Create;
destructor Destroy; override;
class function New: IOrcamentoItensModel;
function Entidade(AValue: TTESTORCAMENTOITENS): IOrcamentoItensModel; overload;
function Entidade: TTESTORCAMENTOITENS; overload;
function DAO: IContainerObjectSet<TTESTORCAMENTOITENS>;
end;
implementation
{ TOrcamentoItensModel }
uses FacadeController, ormbr.container.objectset;
constructor TOrcamentoItensModel.Create;
begin
FConexao := TFacadeController.New.ConexaoController.conexaoAtual;
FDao := TContainerObjectSet<TTESTORCAMENTOITENS>.Create(FConexao, 1);
end;
function TOrcamentoItensModel.DAO: IContainerObjectSet<TTESTORCAMENTOITENS>;
begin
Result := FDao;
end;
destructor TOrcamentoItensModel.Destroy;
begin
inherited;
end;
function TOrcamentoItensModel.Entidade(AValue: TTESTORCAMENTOITENS): IOrcamentoItensModel;
begin
Result := Self;
FEntidade := AValue;
end;
function TOrcamentoItensModel.Entidade: TTESTORCAMENTOITENS;
begin
Result := FEntidade;
end;
class function TOrcamentoItensModel.New: IOrcamentoItensModel;
begin
Result := Self.Create;
end;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2015 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of an Embarcadero developer tools product.
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
unit MusicPlayer.Android;
interface
{$IFDEF ANDROID}
uses
FMX.Graphics,
MusicPlayer.Utils,
System.IoUtils, System.SysUtils, System.Classes,
FMX.Types, FMX.Platform.Android,
Androidapi.JNI.Os, Androidapi.JNI.Net,
Androidapi.JNIBridge, Androidapi.JNI.JavaTypes, Androidapi.JNI.GraphicsContentViewText,
Androidapi.JNI.Media, Androidapi.JNI.Provider, Androidapi.Helpers, Androidapi.JNI.App;
type
TMusicPlayer = class
private
type
TProcessThread = class (TThread)
private
[weak] FMusicPlayer: TMusicPlayer;
FOnProcessPlay: TOnProcessPlayEvent;
procedure DoProcessPlay;
public
constructor Create(CreateSuspended: Boolean; AMusicPlayer: TMusicPlayer; processHandler: TOnProcessPlayEvent);
destructor Destroy; override;
procedure Execute; override;
end;
protected
class var FInstance: TMusicPlayer;
private
FCurrentIndex: Integer;
FPlaylist: TArray<TMPSong>;
FAlbums: TArray<TMPAlbum>;
FMusicPlayer: JMediaPlayer;
FPlayBackState: TMPPlaybackState;
FRepeatMode: TMPRepeatMode;
FShuffleMode: Boolean;
FDefaultAlbumImage: TBitmap;
FOnSongChange: TOnSongChangeEvent;
FOnProcessPlay: TOnProcessPlayEvent;
constructor Create(AType: TMPControllerType = TMPControllerType.App);
procedure DoOnSongChange(newIndex: Integer);
procedure DoOnProcessPlay(newPos: Single);
procedure SetVolume(const Value: Single);
procedure SetTime(const Value: Single);
procedure SetRepeatMode(const Value: TMPRepeatMode);
procedure SetShuffleMode(const Value: Boolean);
function GetVolume: Single;
function GetTime: Single;
function GetRepeatMode: TMPRepeatMode;
function GetDuration: Single;
function GetPlaybackState: TMPPlaybackState;
function GetShuffleMode: Boolean;
public
destructor Destroy; override;
class procedure SetPlayerType(AType: TMPControllerType);
class function DefaultPlayer: TMusicPlayer;
property CurrentIndex: Integer read FCurrentIndex;
property Volume: Single read GetVolume write SetVolume;
property Time: Single read GetTime write SetTime;
property Duration: Single read GetDuration;
property PlaybackState: TMPPlaybackState read GetPlaybackState;
property ShuffleMode: Boolean read GetShuffleMode write SetShuffleMode;
property RepeatMode: TMPRepeatMode read GetRepeatMode write SetRepeatMode;
property Playlist: TArray<TMPSong> read FPlaylist;
property Albums: TArray<TMPAlbum> read FAlbums;
property DefaultAlbumImage: TBitmap read FDefaultAlbumImage write FDefaultAlbumImage;
property OnSongChange: TOnSongChangeEvent read FOnSongChange write FOnSongChange;
property OnProcessPlay: TOnProcessPlayEvent read FOnProcessPlay write FOnProcessPlay;
function GetAlbums: TArray<string>;
function GetSongs: TArray<string>;
function GetSongsInAlbum(AName: string): TArray<string>;
function IsPlaying: Boolean;
function CanSkipBack: Boolean;
function CanSkipForward: Boolean;
procedure PlaySong(path: string);
procedure PlayByIndex(Index: Integer);
procedure Play;
procedure Stop;
procedure Pause;
procedure Next;
procedure Previous;
end;
var
NoArtBitmap: TBitmap;
{$ENDIF}
implementation
{$IFDEF ANDROID}
{ TMusicPlayer }
function TMusicPlayer.CanSkipBack: Boolean;
begin
Result := (Length(FPlaylist) > 0) and (FCurrentIndex > 0) and
(FPlayBackState in [TMPPlaybackState.Playing, TMPPlaybackState.Paused]);
end;
function TMusicPlayer.CanSkipForward: Boolean;
begin
Result := False;
if (Length(FPlaylist) = 0) or not (FPlayBackState in [TMPPlaybackState.Playing, TMPPlaybackState.Paused]) then
Exit(Result);
case RepeatMode of
TMPRepeatMode.One:
Result := FCurrentIndex in [Low(FPlaylist) .. High(FPlaylist)] ;
TMPRepeatMode.Default,
TMPRepeatMode.None:
Result := FCurrentIndex in [Low(FPlaylist) .. High(FPlaylist)-1] ;
TMPRepeatMode.All:
Result := True;
end;
end;
constructor TMusicPlayer.Create(AType: TMPControllerType);
begin
MainActivity.setVolumeControlStream(TJAudioManager.JavaClass.STREAM_MUSIC);
FMusicPlayer := TJMediaPlayer.Create;
FPlayBackState := TMPPlaybackState.Stopped;
FRepeatMode := TMPRepeatMode.All;
FShuffleMode := False;
FDefaultAlbumImage := TBitmap.CreateFromFile(TPath.Combine(TPath.GetDocumentsPath,'MusicNote.png'));
TProcessThread.Create(True,self,DoOnProcessPlay).Start;
end;
class function TMusicPlayer.DefaultPlayer: TMusicPlayer;
begin
if not Assigned(FInstance) then
FInstance := TMusicPlayer.Create;
Result := FInstance;
end;
destructor TMusicPlayer.Destroy;
begin
FMusicPlayer.release;
end;
procedure TMusicPlayer.DoOnSongChange(newIndex: Integer);
begin
if Assigned(FOnSongChange) then
TThread.Queue(TThread.CurrentThread, procedure
begin
FOnSongChange(newIndex);
end);
end;
procedure TMusicPlayer.DoOnProcessPlay(newPos: Single);
begin
if Assigned(FOnProcessPlay) then
TThread.Queue(TThread.CurrentThread, procedure
begin
FOnProcessPlay(newPos);
end);
end;
function TMusicPlayer.GetAlbums: TArray<string>;
var
projection: TJavaObjectArray<JString>;
cursor: JCursor;
artPath: String;
tmpPath: String;
begin
projection := TJavaObjectArray<JString>.Create(4);
projection.Items[0] := TJAudio_AlbumColumns.JavaClass.ALBUM;
projection.Items[1] := TJAudio_AlbumColumns.JavaClass.ARTIST;
projection.Items[2] := StringToJString('_id');
projection.Items[3] := TJAudio_AlbumColumns.JavaClass.ALBUM_ART;
cursor := MainActivity.getContentResolver.query(
TJAudio_Albums.JavaClass.EXTERNAL_CONTENT_URI,
projection,
nil,
nil,
nil);
SetLength(Result, cursor.getCount);
SetLength(FAlbums, cursor.getCount + 1);
FAlbums[cursor.getCount] := TMPAlbum.AllMusicAlbum;
while (cursor.moveToNext) do
begin
FAlbums[cursor.getPosition].Name := JStringToString(cursor.getString(0));
FAlbums[cursor.getPosition].Artist := JStringToString(cursor.getString(1));
FAlbums[cursor.getPosition].Album_ID := cursor.getInt(2);
artPath := JStringToString(cursor.getString(3));
if TFile.Exists(artPath) then
begin
try
//Workaround for loading problems: copy to a file with correct extension.
tmpPath := System.IOUtils.TPath.Combine(System.IOUtils.TPath.GetDocumentsPath, 'tmp.jpg');
TFile.Copy(artPath, tmpPath);
FAlbums[cursor.getPosition].Artwork := TBitmap.CreateFromFile(tmpPath);
TFile.Delete(tmpPath);
except
end;
end
else
FAlbums[cursor.getPosition].Artwork := FDefaultAlbumImage;
Result[cursor.getPosition] := FAlbums[cursor.getPosition].Name;
end;
cursor.close;
end;
function TMusicPlayer.GetDuration: Single;
begin
Result := FMusicPlayer.getDuration;
end;
function TMusicPlayer.GetPlaybackState: TMPPlaybackState;
begin
Result := FPlayBackState;
end;
function TMusicPlayer.GetRepeatMode: TMPRepeatMode;
begin
Result := FRepeatMode;
end;
function TMusicPlayer.GetShuffleMode: Boolean;
begin
Result := FShuffleMode;
end;
function TMusicPlayer.GetSongs: TArray<string>;
var
projection: TJavaObjectArray<JString>;
cursor: JCursor;
selection: JString;
begin
selection := StringToJString(JStringToString(TJAudio_AudioColumns.JavaClass.IS_MUSIC) + ' != 0');
projection := TJavaObjectArray<JString>.Create(5);
projection.Items[0] := TJAudio_AudioColumns.JavaClass.ARTIST;
projection.Items[1] := StringToJString('title');
projection.Items[2] := StringToJString('_data');
projection.Items[3] := TJAudio_AudioColumns.JavaClass.ALBUM;
projection.Items[4] := TJAudio_AudioColumns.JavaClass.DURATION;
cursor := MainActivity.getContentResolver.query(
TJAudio_Media.JavaClass.EXTERNAL_CONTENT_URI,
projection,
selection,
nil,
nil);
SetLength(Result,cursor.getCount);
SetLength(FPlaylist, cursor.getCount);
while (cursor.moveToNext) do
begin
FPlaylist[cursor.getPosition] := TMPSong.FromCursor(cursor);
Result[cursor.getPosition] := Format('[%s]-[%s]', [FPlaylist[cursor.getPosition].Artist, FPlaylist[cursor.getPosition].Title]);
end;
cursor.close;
end;
function TMusicPlayer.GetSongsInAlbum(AName: string): TArray<string>;
var
projection: TJavaObjectArray<JString>;
cursor: JCursor;
selection: JString;
begin
if AName = TMPAlbum.AllMusicAlbum.Name then
begin
Result := GetSongs;
Exit;
end;
selection := StringToJString(JStringToString(TJAudio_AudioColumns.JavaClass.IS_MUSIC) + ' != 0 and ' +
JStringToString(TJAudio_AudioColumns.JavaClass.ALBUM) + ' = "' + AName + '"');
projection := TJavaObjectArray<JString>.Create(5);
projection.Items[0] := TJAudio_AudioColumns.JavaClass.ARTIST;
projection.Items[1] := StringToJString('title');
projection.Items[2] := StringToJString('_data');
projection.Items[3] := TJAudio_AudioColumns.JavaClass.ALBUM;
projection.Items[4] := TJAudio_AudioColumns.JavaClass.DURATION;
cursor := MainActivity.getContentResolver.query(
TJAudio_Media.JavaClass.EXTERNAL_CONTENT_URI,
projection,
selection,
nil,
nil);
SetLength(Result,cursor.getCount);
SetLength(FPlaylist, cursor.getCount);
while (cursor.moveToNext) do
begin
FPlaylist[cursor.getPosition] := TMPSong.FromCursor(cursor);
Result[cursor.getPosition] := Format('[%s]-[%s]', [FPlaylist[cursor.getPosition].Artist, FPlaylist[cursor.getPosition].Title]);
end;
cursor.close;
end;
function TMusicPlayer.GetTime: Single;
begin
Result := FMusicPlayer.getCurrentPosition;
end;
function TMusicPlayer.GetVolume: Single;
var
AudioManager: JAudioManager;
begin
AudioManager := TJAudioManager.Wrap(MainActivity.getSystemService(TJContext.JavaClass.AUDIO_SERVICE));
Result := AudioManager.getStreamVolume(TJAudioManager.JavaClass.STREAM_MUSIC);
Result := Result / AudioManager.getStreamMaxVolume(TJAudioManager.JavaClass.STREAM_MUSIC);
end;
procedure TMusicPlayer.Next;
begin
case RepeatMode of
TMPRepeatMode.One:
begin
Time := 0;
Play;
end;
TMPRepeatMode.Default,
TMPRepeatMode.None:
if CurrentIndex = Length(FPlaylist) - 1 then
FMusicPlayer.Stop
else
begin
if ShuffleMode then
PlayByIndex(Random(Length(FPlaylist)))
else
PlayByIndex(FCurrentIndex + 1);
end;
TMPRepeatMode.All:
if FCurrentIndex = Length(FPlaylist) - 1 then
PlayByIndex(0)
else
begin
if FShuffleMode then
PlayByIndex(Random(Length(FPlaylist)))
else
PlayByIndex(FCurrentIndex + 1);
end;
end;
DoOnSongChange(FCurrentIndex);
end;
procedure TMusicPlayer.Pause;
begin
FMusicPlayer.pause;
FPlayBackState := TMPPlaybackState.Paused;
end;
procedure TMusicPlayer.Play;
begin
if FPlayBackState = TMPPlaybackState.Stopped then
FMusicPlayer.prepare;
FMusicPlayer.start;
FPlayBackState := TMPPlaybackState.Playing;
end;
procedure TMusicPlayer.PlayByIndex(Index: Integer);
begin
FCurrentIndex := Index;
PlaySong(FPlaylist[FCurrentIndex].Path);
end;
function TMusicPlayer.IsPlaying: Boolean;
begin
Result := FMusicPlayer.isPlaying;
end;
procedure TMusicPlayer.PlaySong(path: string);
begin
Stop;
FMusicPlayer.reset;
FMusicPlayer.setDataSource(StringToJString(path));
Play;
end;
procedure TMusicPlayer.Previous;
begin
if (FCurrentIndex > 0) and (FCurrentIndex < Length(FPlaylist)) then
begin
PlayByIndex(FCurrentIndex -1);
DoOnSongChange(FCurrentIndex);
end;
end;
class procedure TMusicPlayer.SetPlayerType(AType: TMPControllerType);
begin
// Do nothing
end;
procedure TMusicPlayer.SetRepeatMode(const Value: TMPRepeatMode);
begin
FRepeatMode := Value;
end;
procedure TMusicPlayer.SetShuffleMode(const Value: Boolean);
begin
FShuffleMode := Value;
end;
procedure TMusicPlayer.SetTime(const Value: Single);
begin
FMusicPlayer.seekTo(Trunc(Value));
end;
procedure TMusicPlayer.SetVolume(const Value: Single);
var
AudioManager: JAudioManager;
begin
AudioManager := TJAudioManager.Wrap(MainActivity.getSystemService(TJContext.JavaClass.AUDIO_SERVICE));
AudioManager.setStreamVolume(TJAudioManager.JavaClass.STREAM_MUSIC,
Round(AudioManager.getStreamMaxVolume(TJAudioManager.JavaClass.STREAM_MUSIC) * Value), 0);
end;
procedure TMusicPlayer.Stop;
begin
if FPlayBackState in [TMPPlaybackState.Playing, TMPPlaybackState.Paused] then
FMusicPlayer.seekTo(0);
FPlayBackState := TMPPlaybackState.Stopped;
FMusicPlayer.stop;
while FMusicPlayer.isPlaying do
sleep(10);
DoOnProcessPlay(0);
end;
{ TMusicPlayer.TProcessThread }
constructor TMusicPlayer.TProcessThread.Create(CreateSuspended: Boolean;
AMusicPlayer: TMusicPlayer; processHandler: TOnProcessPlayEvent);
begin
inherited Create(CreateSuspended);
FOnProcessPlay := processHandler;
FMusicPlayer := AMusicPlayer;
end;
destructor TMusicPlayer.TProcessThread.Destroy;
begin
FMusicPlayer := nil;
inherited;
end;
procedure TMusicPlayer.TProcessThread.Execute;
begin
inherited;
while Assigned(FMusicPlayer) do
begin
case FMusicPlayer.PlaybackState of
Playing: DoProcessPlay;
Stopped,
Paused,
Interrupted,
SeekingForward,
SeekingBackward: sleep(200);
end;
end;
end;
procedure TMusicPlayer.TProcessThread.DoProcessPlay;
var
currentPos: Single;
begin
currentPos := FMusicPlayer.Time;
if Assigned(FOnProcessPlay) then
FOnProcessPlay((currentPos/FMusicPlayer.Duration) * 100);
if FMusicPlayer.IsPlaying then
Sleep(200)
else
FMusicPlayer.Next;
end;
{$ENDIF}
end.
|
unit uRabbitVCS;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Menus, Graphics, uPixMapManager;
const
RabbitVCSAddress = 'org.google.code.rabbitvcs.RabbitVCS.Checker';
RabbitVCSObject = '/org/google/code/rabbitvcs/StatusChecker';
RabbitVCSInterface = 'org.google.code.rabbitvcs.StatusChecker';
{$IF DEFINED(RabbitVCS)}
type
TVcsStatus = (vscNormal, vscModified, vscAdded, vscDeleted, vscIgnored,
vscReadOnly, vscLocked, vscUnknown, vscMissing, vscReplaced,
vscComplicated, vscCalculating, vscError, vscUnversioned);
const
VcsStatusText: array[TVcsStatus] of String =
(
'normal',
'modified',
'added',
'deleted',
'ignored',
'locked',
'locked',
'unknown',
'missing',
'replaced',
'complicated',
'calculating',
'error',
'unversioned'
);
VcsStatusEmblems: array[TVcsStatus] of String =
(
'emblem-rabbitvcs-normal',
'emblem-rabbitvcs-modified',
'emblem-rabbitvcs-added',
'emblem-rabbitvcs-deleted',
'emblem-rabbitvcs-ignored',
'emblem-rabbitvcs-locked',
'emblem-rabbitvcs-locked',
'emblem-rabbitvcs-unknown',
'emblem-rabbitvcs-complicated',
'emblem-rabbitvcs-modified',
'emblem-rabbitvcs-complicated',
'emblem-rabbitvcs-calculating',
'emblem-rabbitvcs-error',
'emblem-rabbitvcs-unversioned'
);
{en
Requests a status check from the underlying status checker.
}
function CheckStatus(Path: String; Recurse: Boolean32 = False;
Invalidate: Boolean32 = True; Summary: Boolean32 = False): string;
{$ENDIF}
procedure FillRabbitMenu(Menu: TPopupMenu; Paths: TStringList);
var
RabbitVCS: Boolean = False;
implementation
uses
BaseUnix, Unix, DBus,
DCUnix, DCClassesUtf8, uGlobs, uGlobsPaths, uMyUnix, uPython
{$IF DEFINED(RabbitVCS)}
, fpjson, jsonparser, jsonscanner
{$ENDIF}
{$IF DEFINED(LCLQT) or DEFINED(LCLQT5)}
, uGObject2
{$ENDIF}
;
const
MODULE_NAME = 'rabbit-vcs';
var
error: DBusError;
RabbitGtk3: Boolean;
conn: PDBusConnection = nil;
PythonModule: PPyObject = nil;
ShellContextMenu: PPyObject = nil;
PythonVersion: array[Byte] of AnsiChar;
procedure Initialize(Self: TObject); forward;
procedure Print(const sMessage: String);
begin
WriteLn('RabbitVCS: ', sMessage);
end;
function CheckError(const sMessage: String; pError: PDBusError): Boolean;
begin
if (dbus_error_is_set(pError) <> 0) then
begin
Print(sMessage + ': ' + pError^.name + ' ' + pError^.message);
dbus_error_free(pError);
Result := True;
end
else
Result := False;
end;
function CheckRabbit: Boolean;
var
service_exists: dbus_bool_t;
begin
dbus_error_init(@error);
// Check if RabbitVCS service is running
service_exists := dbus_bus_name_has_owner(conn, RabbitVCSAddress, @error);
if CheckError('Cannot query RabbitVCS on DBUS', @error) then
Result:= False
else
Result:= (service_exists <> 0);
end;
function CheckService: Boolean;
var
pyValue: PPyObject;
begin
Result:= CheckRabbit;
if Result then
Print('Service found running')
else begin
// Try to start RabbitVCS service
pyValue:= PythonRunFunction(PythonModule, 'StartService');
Py_XDECREF(pyValue);
Result:= CheckRabbit;
if Result then Print('Service successfully started');
end;
end;
{$IF DEFINED(RabbitVCS)}
function CheckStatus(Path: String; Recurse: Boolean32;
Invalidate: Boolean32; Summary: Boolean32): string;
var
Return: Boolean;
StringPtr: PAnsiChar;
JAnswer : TJSONObject;
VcsStatus: TVcsStatus;
message: PDBusMessage;
argsIter: DBusMessageIter;
pending: PDBusPendingCall;
arrayIter: DBusMessageIter;
begin
if not RabbitVCS then Exit;
// Create a new method call and check for errors
message := dbus_message_new_method_call(RabbitVCSAddress, // target for the method call
RabbitVCSObject, // object to call on
RabbitVCSInterface, // interface to call on
'CheckStatus'); // method name
if (message = nil) then
begin
Print('Cannot create message "CheckStatus"');
Exit;
end;
try
// Append arguments
StringPtr:= PAnsiChar(Path);
dbus_message_iter_init_append(message, @argsIter);
if not RabbitGtk3 then
Return:= (dbus_message_iter_append_basic(@argsIter, DBUS_TYPE_STRING, @StringPtr) <> 0)
else begin
Return:= (dbus_message_iter_open_container(@argsIter, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE_AS_STRING, @arrayIter) <> 0);
Return:= Return and (dbus_message_iter_append_fixed_array(@arrayIter, DBUS_TYPE_BYTE, @StringPtr, Length(Path)) <> 0);
Return:= Return and (dbus_message_iter_close_container(@argsIter, @arrayIter) <> 0);
end;
Return:= Return and (dbus_message_iter_append_basic(@argsIter, DBUS_TYPE_BOOLEAN, @Recurse) <> 0);
Return:= Return and (dbus_message_iter_append_basic(@argsIter, DBUS_TYPE_BOOLEAN, @Invalidate) <> 0);
Return:= Return and (dbus_message_iter_append_basic(@argsIter, DBUS_TYPE_BOOLEAN, @Summary) <> 0);
if not Return then
begin
Print('Cannot append arguments');
Exit;
end;
// Send message and get a handle for a reply
if (dbus_connection_send_with_reply(conn, message, @pending, -1) = 0) then
begin
Print('Error sending message');
Exit;
end;
if (pending = nil) then
begin
Print('Pending call is null');
Exit;
end;
dbus_connection_flush(conn);
finally
dbus_message_unref(message);
end;
// Block until we recieve a reply
dbus_pending_call_block(pending);
// Get the reply message
message := dbus_pending_call_steal_reply(pending);
// Free the pending message handle
dbus_pending_call_unref(pending);
if (message = nil) then
begin
Print('Reply is null');
Exit;
end;
try
// Read the parameters
if (dbus_message_iter_init(message, @argsIter) <> 0) then
begin
if (dbus_message_iter_get_arg_type(@argsIter) = DBUS_TYPE_STRING) then
begin
dbus_message_iter_get_basic(@argsIter, @StringPtr);
with TJSONParser.Create(StrPas(StringPtr), [joUTF8]) do
try
try
JAnswer:= Parse as TJSONObject;
try
Result:= JAnswer.Strings['content'];
if Result = 'unknown' then Exit(EmptyStr);
finally
JAnswer.Free;
end;
except
Exit(EmptyStr);
end;
finally
Free;
end;
for VcsStatus:= Low(TVcsStatus) to High(VcsStatus) do
begin
if (VcsStatusText[VcsStatus] = Result) then
begin
Result:= VcsStatusEmblems[VcsStatus];
Break;
end;
end;
end;
end;
finally
dbus_message_unref(message);
end;
end;
{$ENDIF}
procedure MenuClickHandler(Self, Sender: TObject);
var
pyMethod, pyArgs: PPyObject;
MenuItem: TMenuItem absolute Sender;
begin
if Assigned(ShellContextMenu) then
begin
pyMethod:= PyString_FromString('Execute');
pyArgs:= PyString_FromString(PAnsiChar(MenuItem.Hint));
PyObject_CallMethodObjArgs(ShellContextMenu, pyMethod, pyArgs, nil);
Py_XDECREF(pyArgs);
Py_XDECREF(pyMethod);
end;
end;
procedure FillRabbitMenu(Menu: TPopupMenu; Paths: TStringList);
var
Handler: TMethod;
pyMethod, pyValue: PPyObject;
procedure SetBitmap(Item: TMenuItem; const IconName: String);
var
bmpTemp: TBitmap;
begin
bmpTemp:= PixMapManager.LoadBitmapEnhanced(IconName, 16, True, clMenu);
if Assigned(bmpTemp) then
begin
Item.Bitmap.Assign(bmpTemp);
FreeAndNil(bmpTemp);
end;
end;
procedure BuildMenu(pyMenu: PPyObject; BaseItem: TMenuItem);
var
Index: Integer;
IconName: String;
MenuItem: TMenuItem;
pyItem, pyObject: PPyObject;
begin
for Index:= 0 to PyList_Size(pyMenu) - 1 do
begin
pyItem:= PyList_GetItem(pyMenu, Index);
MenuItem:= TMenuItem.Create(BaseItem);
pyObject:= PyObject_GetAttrString(pyItem, 'label');
MenuItem.Caption:= PyStringToString(pyObject);
if MenuItem.Caption <> '-' then
begin
pyObject:= PyObject_GetAttrString(pyItem, 'identifier');
MenuItem.Hint:= PyStringToString(pyObject);
if Length(MenuItem.Hint) > 0 then begin
MenuItem.OnClick:= TNotifyEvent(Handler);
end;
pyObject:= PyObject_GetAttrString(pyItem, 'icon');
IconName:= PyStringToString(pyObject);
if Length(IconName) > 0 then SetBitmap(MenuItem, IconName);
end;
pyObject:= PyObject_GetAttrString(pyItem, 'menu');
if Assigned(pyObject) and (PyList_Size(pyObject) > 0) then
begin
BuildMenu(pyObject, MenuItem);
Py_DECREF(pyObject);
end;
BaseItem.Add(MenuItem);
end;
end;
begin
if not RabbitVCS then Exit;
Py_XDECREF(ShellContextMenu);
ShellContextMenu:= PythonRunFunction(PythonModule, 'GetContextMenu', Paths);
if Assigned(ShellContextMenu) then
begin
Handler.Data:= Menu;
Handler.Code:= @MenuClickHandler;
pyMethod:= PyString_FromString('GetMenu');
pyValue:= PyObject_CallMethodObjArgs(ShellContextMenu, pyMethod, nil);
if Assigned(pyValue) then
begin
BuildMenu(pyValue, Menu.Items);
Py_DECREF(pyValue);
end;
Py_XDECREF(pyMethod);
end;
end;
function FindPython(const Path: String): String;
const
Debian = '/usr/share/python3/debian_defaults';
begin
Result:= ExtractFileName(Path);
Result:= StringReplace(Result, 'python', '', []);
if Length(Result) > 0 then
begin
if Result[1] = '2' then Exit;
if fpAccess(Debian, F_OK) = 0 then
try
with TIniFileEx.Create(Debian, fmOpenRead) do
try
Result:= ReadString('DEFAULT', 'default-version', Result);
Result:= StringReplace(Trim(Result), 'python', '', []);
finally
Free;
end;
except
// Ignore
end;
end;
end;
function CheckPackage({%H-}Parameter : Pointer): PtrInt;
const
Path = '/usr/lib';
var
DirPtr: pDir;
Handler: TMethod;
Directory: String;
DirEntPtr: pDirent;
PackageFormat: String;
begin
if fpAccess('/etc/debian_version', F_OK) = 0 then
PackageFormat:= 'dist-packages/rabbitvcs'
else begin
PackageFormat:= 'site-packages/rabbitvcs';
end;
DirPtr:= fpOpenDir(Path);
if Assigned(DirPtr) then
try
DirEntPtr:= fpReadDir(DirPtr^);
while DirEntPtr <> nil do
begin
if (DirEntPtr^.d_name <> '..') and (DirEntPtr^.d_name <> '.') then
begin
if FNMatch('python*', DirEntPtr^.d_name, 0) = 0 then
begin
Directory:= Path + PathDelim + DirEntPtr^.d_name;
if (fpAccess(Directory + PathDelim + PackageFormat, F_OK) = 0) then
begin
PythonVersion:= FindPython(Directory);
if Length(PythonVersion) > 0 then
begin
Handler.Data:= nil;
Handler.Code:= @Initialize;
while (gConfig = nil) do Sleep(10);
TThread.Synchronize(nil, TThreadMethod(Handler));
end;
Exit(0);
end;
end;
end;
DirEntPtr:= fpReadDir(DirPtr^);
end;
finally
fpCloseDir(DirPtr^);
end;
Result:= 1;
end;
function CheckVersion: Boolean;
var
ATemp: AnsiString;
pyModule: PPyObject;
pyVersion: PPyObject;
AVersion: TStringArray;
Major, Minor, Micro: Integer;
{$IF DEFINED(LCLQT) or DEFINED(LCLQT5)}
GtkWidget: TGType;
GtkClass, Gtk3: Pointer;
{$ENDIF}
begin
Result:= False;
pyModule:= PythonLoadModule('rabbitvcs');
if Assigned(pyModule) then
begin
pyVersion:= PythonRunFunction(pyModule, 'package_version');
if Assigned(pyVersion) then
begin
ATemp:= PyStringToString(pyVersion);
AVersion:= ATemp.Split(['.']);
Print('Version ' + ATemp);
if (Length(AVersion) > 1) then
begin
Major:= StrToIntDef(AVersion[0], 0);
Minor:= StrToIntDef(AVersion[1], 0);
if (Length(AVersion) > 2) then
Micro:= StrToIntDef(AVersion[2], 0)
else begin
Micro:= 0;
end;
// RabbitVCS migrated to GTK3 from version 0.17.1
RabbitGtk3:= (Major > 0) or (Minor > 17) or ((Minor = 17) and (Micro > 0));
{$IF DEFINED(LCLQT) or DEFINED(LCLQT5)}
// Check GTK platform theme plugin
GtkWidget:= g_type_from_name('GtkWidget');
Result:= (GtkWidget = 0);
if not Result then
begin
GtkClass:= g_type_class_ref(GtkWidget);
// Property 'expand' since GTK 3.0
Gtk3:= g_object_class_find_property(GtkClass, 'expand');
// RabbitVCS GTK version should be same as Qt platform theme plugin GTK version
Result:= (RabbitGtk3 = Assigned(Gtk3));
end;
{$ELSEIF DEFINED(LCLGTK2)}
Result:= not RabbitGTK3;
{$ELSEIF DEFINED(LCLGTK3)}
Result:= RabbitGTK3;
{$ELSE}
Result:= True
{$ENDIF}
end;
end;
end;
end;
procedure Initialize(Self: TObject);
begin
dbus_error_init(@error);
conn := dbus_bus_get(DBUS_BUS_SESSION, @error);
if CheckError('Cannot acquire connection to DBUS session bus', @error) then
Exit;
if PythonInitialize(PythonVersion) then
begin
if not CheckVersion then Exit;
Print('Python version ' + PythonVersion);
PythonAddModulePath(gpExePath + 'scripts');
PythonModule:= PythonLoadModule(MODULE_NAME);
RabbitVCS:= Assigned(PythonModule) and CheckService;
end;
end;
procedure Finalize;
begin
PythonFinalize;
if Assigned(conn) then dbus_connection_unref(conn);
end;
initialization
BeginThread(@CheckPackage);
finalization
Finalize;
end.
|
unit Pdma160;
interface
uses winTypes,winProcs,
Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls,
util1,dtf0,Dgraphic,stmDef,
DirectD0,PDMA1632,
debug0;
{
La carte PDMA16 permet l'acquisition de 16 entrées logiques en mode DMA.
Le buffer DMA est alloué par le programme PDMA-win qui doit être appelé dans
Autoexec.bat.
La taille du buffer est fixée à 8192 octets et la cadence d'acquisition est
fixée à 1 milliseconde. Il faut donc 4 secondes pour qu'il y ait un débordement
du buffer, ce qui est largement suffisant.
Pour piloter la carte, il suffit d'appeler LancerAcq et TerminerAcq.
La fonction getCountAcq renvoie le nombre de spikes détectés depuis le dernier
appel et range les spikes (transitions montantes sur une entrée) dans le
buffer evt.
evt est un tableau pouvant contenir jusqu'à 100000 spikes
}
procedure lancerAcq;
procedure terminerAcq;
function getCountAcq:longint;
{setTopSync permet d'ouvrir ou fermer la porte de sortie des tops synchro }
procedure setTopSync(Von:boolean);
{rangerSpike range un spike dans le tampon Evt }
procedure rangerSpike(code:word;t:longint);
{getNbSpike donne le nb de spikes entre 2 dates. Est utilisé par Replay}
function getNbSpike(t1,t2:float):longint;
{procédures pour debug}
procedure testCompteur;
procedure inspectTab;
implementation
const
dma3:boolean=false; { La carte peut utiliser DMA1 ou DMA3}
NbPt=4096;
tailleDmaBuf=nbPt*2;
DmaCount=tailleDmaBuf-1;
maxMask=$0FFF; {= 4096-1 }
var
oldCount:longint;
nbtmp:longint;
etatAB:word;
function inPort(n:word):byte;assembler;pascal;
asm
mov dx,n
in al,dx
end;
function inPortW(n:word):word;assembler;pascal;
asm
mov dx,n
in ax,dx
end;
procedure outPort(n:word;b:byte);assembler;pascal;
asm
mov dx,n
mov al,b
out dx,al
end;
var
current302:byte;
procedure initAcq;
var
b:byte;
begin
b:=inport(8); {lire etat DMA}
outport(BaseAddress+2,0); {DMA reg}
outPort(BaseAddress+3,0); {INT reg}
outPort(BaseAddress+7,$03A); {programmation Timer0 en mode 5}
outPort(BaseAddress+6,0); {empêche son fonctionnement}
outPort(BaseAddress+6,0);
current302:=0;
end;
procedure progTimers;
begin
outPort(BaseAddress+7,$03A); {programmation Timer0 en mode 5}
outPort(BaseAddress+6,0); {empêche son fonctionnement}
outPort(BaseAddress+6,0);
outPort(BaseAddress+7,$0B4); {programmation Timer2}
outPort(BaseAddress+6,lo(tailleDmaBuf));
outPort(BaseAddress+6,hi(tailleDmaBuf));
outPort(BaseAddress+7,$074); {programmation Timer1}
outPort(BaseAddress+5,2); {divise par 2}
outPort(BaseAddress+5,0); {donc sortie= 1 ms}
outPort(BaseAddress+7,$034); {programmation Timer0}
outPort(BaseAddress+4,lo(5000));
outPort(BaseAddress+4,hi(5000)); {sortie= 0.5 milliseconde}
end;
procedure LancerAcq;
var
b:byte;
begin
nbEvt:=0;
nbtmp:=0;
oldCount:=-1;
etatAB:=inportW(baseAddress);
outPort($0A,5+2*ord(dma3)); {masquer}
b:=inport(08); {lire etat DMA}
outPort($83-ord(dma3),segBuf);{Page canal 1}
outPort($0C,0); {Flip Flop à zéro}
outPort(2+4*ord(dma3),lo(offsbuf));
outPort(2+4*ord(dma3),hi(offsbuf));
outPort($0C,0); {Flip Flop à zéro}
outPort(3+4*ord(dma3),lo(DmaCount)); {Count DMA}
outPort(3+4*ord(dma3),hi(DmaCount));
outPort($0B,5+$40+$10); {Mode DMA auto-init canal 1}
current302:=$80+8+4;
outPort(BaseAddress+2,current302); {DMA enable+ source=timer +word}
progTimers;
outPort($0A,1+2*ord(dma3)); {démasquer DMA}
end;
procedure setTopSync(Von:boolean);
begin
if Von
then outPort(BaseAddress+2,current302+$10)
else outPort(BaseAddress+2,current302);
topSynchro:=Von; {topSynchro est utilisé uniquement par la simulation}
end;
function lire2:word;assembler;pascal;
asm
mov dx,BaseAddress
add dx,7
mov al,80h
out dx,al
dec dx
in al,dx
xchg ah,al
in al,dx
xchg ah,al
end;
procedure testCompteur;
var
i:integer;
begin
progTimers;
for i:=1 to 10000 do
{ affDebug(Istr(lire2));}
end;
procedure TerminerAcq;
begin
outPort($0A,5+2*ord(dma3)); {masquer canal DMA }
initAcq;
end;
procedure rangerSpike(code:word;t:longint);
begin
{affdebug('ranger '+Istr(nbevt));}
if nbEvt>=maxNbEvt then exit;
with evt^[nbEvt] do
begin
x:=code;
date:=t;
end;
inc(nbEvt);
end;
function getNbSpike(t1,t2:float):longint;
const
old:longint=0;
var
n,nb:longint;
begin
nb:=0;
getNbSpike:=0;
if old>=nbEvt then old:=0;
with evt^[old]do
if date<=t1 then n:=old
else n:=0;
while (n<nbEvt) and (evt^[n].date<t1)
do inc(n);
if n=nbEvt then exit;
while n<nbEvt do
with evt^[n] do
begin
if (date<t2) and (x and TrackMask<>0) then inc(nb)
else
begin
getNbSpike:=nb;
old:=n-1;
if old<0 then old:=0;
exit;
end;
inc(n);
end;
getNbSpike:=nb;
end;
function getCountAcq:longint;
var
n,nb:longint;
x,y:word;
begin
n:=nbtmp*nbpt+nbpt-lire2 div 2;
if n<oldCount then
begin
inc(n,nbpt);
inc(nbtmp);
end;
{affdebug('n='+Istr(n));}
nb:=0;
while oldCount<n do
begin
inc(oldCount);
x:=tab^[oldCount and maxMask];
x:=x and ChannelMask;
y:=not etatAB and x;
if y<>0 then
begin
rangerSpike(y,oldCount);
if y and TrackMask<>0 then inc(nb);
end;
etatAB:=x;
end;
getCountAcq:=nb;
end;
{
procedure allocateDmaBuffer;
var
p:array[1..2000] of longint;
i,n:integer;
ad:longint;
begin
fillchar(p,sizeof(p),0);
DmaBuf:=0;
n:=0;
repeat
inc(n);
if DmaBuf<>0 then globalDosFree(word(dmaBuf));
p[n]:=globalDosAlloc(32);
DmaBuf:=globalDosAlloc(tailleDmaBuf);
ad:=longint(hiword(dmabuf))*16;
until (DmaBuf=0) or (ad div (64*1024) -(ad+tailleDmabuf) div (64*1024)=0)
or (n>=2000);
for i:=1 to n do
if p[i]<>0 then globalDosFree(word(p[i]));
if (DmaBuf=0) or (n>=2000) then
begin
messageCentral('Unable to allocate DMA buffer');
halt;
end;
offsBuf:=ad and $FFFF;
segBuf:=ad shr 16;
tab:=ptr(word(dmaBuf),0);
fillchar(tab^,tailleDmaBuf,0);
end;
procedure freeDmaBuffer;
begin
globalDosFree(word(DmaBuf));
end;
}
procedure inspectTab;
var
st:string;
i:integer;
begin
i:=0;
repeat
inc(i)
until (i>=nbpt) or (tab^[i]<>0);
messageCentral('i='+Istr(i));
st:='';
for i:=0 to 100 do
begin
st:=st+Istr(tab^[i])+' ';
if i mod 10=0 then st:=st+#13;
end;
messageCentral(st);
messageCentral(Istr(oldCount));
end;
initialization
end.
|
{ ***************************************************************************
Copyright (c) 2016-2020 Kike Pérez
Unit : Quick.Logger.Provider.Files
Description : Log Console Provider
Author : Kike Pérez
Version : 1.30
Created : 12/10/2017
Modified : 24/04/2020
This file is part of QuickLogger: https://github.com/exilon/QuickLogger
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Logger.Provider.Files;
{$i QuickLib.inc}
interface
uses
Classes,
SysUtils,
DateUtils,
{$IFDEF FPC}
Quick.Files,
zipper,
{$ELSE}
System.IOUtils,
System.Zip,
{$ENDIF}
Quick.Commons,
Quick.Logger;
type
TLogFileProvider = class (TLogProviderBase,IRotable)
private
fLogWriter : TStreamWriter;
fFileName : string;
fMaxRotateFiles : Integer;
fMaxFileSizeInMB : Integer;
fLimitLogSize : Int64;
fDailyRotate : Boolean;
fCompressRotatedFiles : Boolean;
fRotatedFilesPath : string;
fFileCreationDate : TDateTime;
fShowEventTypes : Boolean;
fShowHeaderInfo : Boolean;
fIsRotating : Boolean;
fUnderlineHeaderEventType: Boolean;
fAutoFlush : Boolean;
fAutoFileName : Boolean;
FDailyRotateFileDateFormat: string;
function CalcRotateLogFileName(cNumBackup: Integer; cFileDate: string; cZipped: Boolean; cFormatNumBackup: Boolean =
true): string;
function CheckNeedRotate : Boolean;
function GetFileDate(cFileName: string): string;
function GetLogFileBackup(cNumBackup: Integer; zipped: Boolean): string;
procedure SetFileName(const Value: string);
procedure SetRotatedFilesPath(const Value: string);
protected
procedure CompressLogFile(const cFileName : string); virtual;
procedure WriteHeaderInfo; virtual;
procedure WriteToStream(const cMsg : string); virtual;
public
constructor Create; override;
destructor Destroy; override;
property FileName : string read fFileName write SetFileName;
{$IFDEF MSWINDOWS}
property AutoFileNameByProcess : Boolean read fAutoFileName write fAutoFileName;
{$ENDIF}
property MaxRotateFiles : Integer read fMaxRotateFiles write fMaxRotateFiles;
property MaxFileSizeInMB : Integer read fMaxFileSizeInMB write fMaxFileSizeInMB;
property DailyRotate : Boolean read fDailyRotate write fDailyRotate;
property DailyRotateFileDateFormat: string read FDailyRotateFileDateFormat write FDailyRotateFileDateFormat;
property RotatedFilesPath : string read fRotatedFilesPath write SetRotatedFilesPath;
property CompressRotatedFiles : Boolean read fCompressRotatedFiles write fCompressRotatedFiles;
property ShowEventType : Boolean read fShowEventTypes write fShowEventTypes;
property ShowHeaderInfo : Boolean read fShowHeaderInfo write fShowHeaderInfo;
property UnderlineHeaderEventType : Boolean read fUnderlineHeaderEventType write fUnderlineHeaderEventType;
property AutoFlush : Boolean read fAutoFlush write fAutoFlush;
procedure Init; override;
procedure Restart; override;
procedure RotateLog; virtual;
procedure WriteLog(cLogItem : TLogItem); override;
end;
{$IFDEF MSWINDOWS}
function GetCurrentProcessId : Cardinal; stdcall; external 'kernel32.dll';
{$ENDIF}
var
GlobalLogFileProvider : TLogFileProvider;
implementation
constructor TLogFileProvider.Create;
begin
inherited;
fFileName := '';
fIsRotating := False;
fMaxRotateFiles := 5;
fMaxFileSizeInMB := 20;
fDailyRotate := False;
fCompressRotatedFiles := False;
fShowEventTypes := True;
fShowHeaderInfo := True;
fUnderlineHeaderEventType := False;
fRotatedFilesPath := '';
fAutoFlush := False;
fAutoFileName := False;
LogLevel := LOG_ALL;
IncludedInfo := [iiAppName,iiHost,iiUserName,iiOSVersion];
end;
destructor TLogFileProvider.Destroy;
begin
if Assigned(fLogWriter) then fLogWriter.Free;
fLogWriter := nil;
inherited;
end;
procedure CreateNewLogFile(const aFilename : string);
var
fs : TFileStream;
begin
//resolve windows filesystem tunneling creation date?
fs := TFile.Create(aFilename);
try
//do nothing...created to set new creationdate
finally
fs.Free;
end;
TFile.SetCreationTime(aFilename,Now());
end;
function TLogFileProvider.CalcRotateLogFileName(cNumBackup: Integer; cFileDate: string; cZipped: Boolean;
cFormatNumBackup: Boolean = true): string;
var
zipExt: string;
LogName: string;
LogExt: string;
Num: string;
begin
if cZipped then
zipExt := '.zip'
else
zipExt := '';
LogName := TPath.GetFileNameWithoutExtension (fFileName);
LogExt := TPath.GetExtension (fFileName);
if cNumBackup > 0 then
if cFormatNumBackup then
Num := '.' + cNumBackup.ToString.PadLeft (MaxRotateFiles.ToString.Length, '0')
else
Num := '.' + cNumBackup.ToString
else
Num := '';
if cFileDate = '' then
Result := Format ('%s%s%s%s', [LogName, Num, LogExt, zipExt])
else
Result := Format ('%s%s.%s%s%s', [LogName, Num, cFileDate, LogExt, zipExt]);
if fRotatedFilesPath = '' then
Result := TPath.GetDirectoryName (fFileName) + PathDelim + Result
else
Result := IncludeTrailingPathDelimiter (fRotatedFilesPath) + Result;
end;
procedure TLogFileProvider.Init;
var
FileMode : Word;
fs : TFileStream;
exepath : string;
begin
if Assigned(fLogWriter) then fLogWriter.Free;
fLogWriter := nil;
//get exepath only if not running as dll
if IsLibrary then exepath := SystemInfo.AppPath
else exepath := ParamStr(0);
if fFileName = '' then
begin
{$IFNDEF ANDROID}
fFileName := TPath.GetDirectoryName(exepath) + PathDelim + TPath.GetFileNameWithoutExtension(exepath) + '.log';
{$ELSE}
fFileName := TPath.GetDocumentsPath + PathDelim + 'logger.log';
{$ENDIF}
end;
if fFileName.StartsWith('.'+PathDelim) then fFileName := StringReplace(fFileName,'.'+PathDelim,TPath.GetDirectoryName(exepath) + PathDelim,[])
else if ExtractFilePath(fFileName) = '' then fFileName := TPath.GetDirectoryName(exepath) + PathDelim + fFileName;
{$IFDEF MSWINDOWS}
if fAutoFileName then fFileName := Format('%s\%s_%d.log',[TPath.GetDirectoryName(fFileName),TPath.GetFileNameWithoutExtension(fFileName),GetCurrentProcessId]);
{$ENDIF}
if fMaxFileSizeInMB > 0 then fLimitLogSize := fMaxFileSizeInMB * 1024 * 1024
else fLimitLogSize := 0;
if TFile.Exists(fFileName) then
begin
fFileCreationDate := TFile.GetCreationTime(fFileName);
FileMode := fmOpenWrite or fmShareDenyWrite;
end
else
begin
FileMode := fmCreate or fmShareDenyWrite;
fFileCreationDate := Now();
//resolve windows filesystem tunneling creation date
CreateNewLogFile(fFileName);
end;
//create stream file
fs := TFileStream.Create(fFileName, FileMode);
try
fs.Seek(0,TSeekOrigin.soEnd);
fLogWriter := TStreamWriter.Create(fs,TEncoding.Default,32);
fLogWriter.AutoFlush := fAutoFlush;
fLogWriter.OwnStream;
//check if need to rotate
if CheckNeedRotate then
begin
try
RotateLog;
except
on E : Exception do NotifyError(Format('Can''t rotate log file: %s',[e.message]));
end;
Exit;
end;
//writes header info
if fShowHeaderInfo then WriteHeaderInfo;
except
fs.Free;
raise;
end;
//creates the threadlog
inherited;
end;
procedure TLogFileProvider.WriteHeaderInfo;
begin
WriteToStream(FillStr('-',70));
if iiAppName in IncludedInfo then
begin
WriteToStream(Format('Application : %s %s',[SystemInfo.AppName,SystemInfo.AppVersion]));
end;
if iiProcessId in IncludedInfo then WriteToStream(Format('PID : %d',[SystemInfo.ProcessId]));
WriteToStream(Format('Path : %s',[SystemInfo.AppPath]));
WriteToStream(Format('CPU cores : %d',[SystemInfo.CPUCores]));
if iiOSVersion in IncludedInfo then WriteToStream(Format('OS version : %s',[SystemInfo.OSVersion]));
//{$IFDEF MSWINDOWS}
if iiHost in IncludedInfo then WriteToStream(Format('Host : %s',[SystemInfo.HostName]));
if iiUserName in IncludedInfo then WriteToStream(Format('Username : %s',[Trim(SystemInfo.UserName)]));
//{$ENDIF}
WriteToStream(Format('Started : %s',[DateTimeToStr(Now(),FormatSettings)]));
{$IFDEF MSWINDOWS}
if IsService then WriteToStream('AppType : Service')
else if System.IsConsole then WriteToStream('AppType : Console');
if IsDebug then WriteToStream('Debug mode : On');
{$ENDIF}
WriteToStream(FillStr('-',70));
end;
procedure TLogFileProvider.WriteToStream(const cMsg : string);
begin
try
//check if need to rotate
if CheckNeedRotate then
begin
try
RotateLog;
except
on E : Exception do NotifyError(Format('Can''t rotate log file: %s',[e.message]));
end;
end;
//writes to stream file
fLogWriter.WriteLine(cMsg);
//needs to flush if autoflush??
if not fAutoFlush then fLogWriter.Flush;
except
raise ELogger.Create('Error writting to file log!');
end;
end;
procedure TLogFileProvider.WriteLog(cLogItem : TLogItem);
begin
if CustomMsgOutput then
begin
WriteToStream(LogItemToFormat(cLogItem));
Exit;
end;
if cLogItem.EventType = etHeader then
begin
WriteToStream(cLogItem.Msg);
if fUnderlineHeaderEventType then WriteToStream(FillStr('-',cLogItem.Msg.Length));
end
else
begin
//if fShowEventTypes then WriteToStream(Format('%s [%s] %s',[DateTimeToStr(cLogItem.EventDate,FormatSettings),EventTypeName[cLogItem.EventType],LogItemToLine(cLogItem.Msg)]))
// else WriteToStream(Format('%s %s',[DateTimeToStr(cLogItem.EventDate,FormatSettings),cLogItem.Msg]));
WriteToStream(LogItemToLine(cLogItem,True,fShowEventTypes));
end;
end;
function TLogFileProvider.GetFileDate(cFileName: string): string;
var
fileDate: TDateTime;
begin
Result := '';
if FDailyRotateFileDateFormat = '' then
Exit;
try
fileDate := TFile.GetCreationTime (cFileName);
Result := FormatDateTime (FDailyRotateFileDateFormat, fileDate);
except
Result := '';
end;
end;
function TLogFileProvider.GetLogFileBackup(cNumBackup: Integer; zipped: Boolean): string;
var
SearchRec: TSearchRec;
i: Integer;
begin
// Doing this twice to be backward compatible independent if the numbackup is formatted or not
for i := 0 to 1 do
begin
if DailyRotate then
Result := CalcRotateLogFileName (cNumBackup, '*', zipped, i = 0)
else
Result := CalcRotateLogFileName (cNumBackup, '', zipped, i = 0);
if findfirst (Result, faAnyFile, SearchRec) = 0 then
Result := TPath.GetDirectoryName (Result) + PathDelim + SearchRec.Name
else
Result := '';
FindClose (SearchRec);
if Result <> '' then
Exit;
end;
end;
procedure TLogFileProvider.Restart;
begin
Stop;
//if Assigned(fLogWriter) then fLogWriter.Free;
Init;
end;
procedure TLogFileProvider.RotateLog;
var
RotateFile: string;
i: Integer;
begin
if fIsRotating then
Exit;
fIsRotating := true;
try
// frees stream file
if Assigned (fLogWriter) then
begin
fLogWriter.Free;
fLogWriter := nil;
end;
try
if fRotatedFilesPath <> '' then
ForceDirectories (fRotatedFilesPath);
// delete older log backup and zip
RotateFile := GetLogFileBackup (fMaxRotateFiles, true);
if RotateFile <> '' then
TFile.Delete (RotateFile);
RotateFile := GetLogFileBackup (fMaxRotateFiles, False);
if RotateFile <> '' then
TFile.Delete (RotateFile);
// rotates older log backups or zips
for i := fMaxRotateFiles - 1 downto 1 do
begin
RotateFile := GetLogFileBackup (i, true);
if RotateFile <> '' then
TFile.Move (RotateFile, CalcRotateLogFileName(i + 1, GetFileDate(RotateFile), true));
RotateFile := GetLogFileBackup (i, False);
if RotateFile <> '' then
TFile.Move (RotateFile, CalcRotateLogFileName(i + 1, GetFileDate(RotateFile), False));
end;
// rename current log
RotateFile := CalcRotateLogFileName (1, GetFileDate(fFileName), False);
TFile.Move (fFileName, RotateFile);
finally
// initialize stream file again
Init;
end;
finally
fIsRotating := False;
end;
// compress log file
if fCompressRotatedFiles then
begin
{$IFDEF FPC}
CompressLogFile (RotateFile);
{$ELSE}
TThread.CreateAnonymousThread (
procedure
begin
CompressLogFile(RotateFile);
end).Start;
{$ENDIF}
end;
end;
procedure TLogFileProvider.SetFileName(const Value: string);
begin
if Value <> fFileName then
begin
fFileName := Value;
if IsEnabled then Restart;
end;
end;
procedure TLogFileProvider.SetRotatedFilesPath(const Value: string);
var
exepath : string;
begin
if IsLibrary then exepath := SystemInfo.AppPath
else exepath := ParamStr(0);
if Value.StartsWith('.' + PathDelim) then fRotatedFilesPath := StringReplace(Value,'.' + PathDelim,TPath.GetDirectoryName(exepath) + PathDelim,[])
else fRotatedFilesPath := Value;
end;
function TLogFileProvider.CheckNeedRotate: Boolean;
begin
if ((fLimitLogSize > 0) and (fLogWriter.BaseStream.Size > fLimitLogSize))
or ((fDailyRotate) and (not IsSameDay(fFileCreationDate,Now()))) then
Result := True
else Result := False;
end;
procedure TLogFileProvider.CompressLogFile(const cFileName : string);
{$IFDEF FPC}
var
zip : TZipper;
begin
try
zip := TZipper.Create;
try
zip.FileName := GetLogFileBackup(1,True);
zip.Entries.AddFileEntry(cFilename,ExtractFileName(cFilename));
zip.ZipAllFiles;
finally
zip.Free;
end;
TFile.Delete(cFileName);
except
raise ELogger.Create('Error trying to backup log file!');
end;
end;
{$ELSE}
var
zip : TZipFile;
begin
try
zip := TZipFile.Create;
try
zip.Open(GetLogFileBackup(1,True),zmWrite);
zip.Add(cFileName,'',TZipCompression.zcDeflate);
zip.Close;
finally
zip.Free;
end;
TFile.Delete(cFileName);
except
raise ELogger.Create('Error trying to backup log file!');
end;
end;
{$ENDIF}
initialization
GlobalLogFileProvider := TLogFileProvider.Create;
finalization
if Assigned(GlobalLogFileProvider) and (GlobalLogFileProvider.RefCount = 0) then GlobalLogFileProvider.Free;
end.
|
unit DModDanceAnimMain;
interface
uses
System.SysUtils, System.Classes, System.ImageList, FMX.ImgList, FMX.Types,
FMX.Dialogs, System.IniFiles, XSIDTypes, XSIDFiles;
type
TDanceAnimConfig = class(TObject)
private
FSonglenFile: string;
FDefaultLen: TTime;
procedure SetDefaultLen(const AValue: TTime);
public
constructor Create;
destructor Destroy; override;
procedure SaveToIniFile(const AFileName: string);
procedure LoadFromIniFile(const AFileName: string);
property SonglenFile: string read FSonglenFile write FSonglenFile;
property DefaultLen: TTime read FDefaultLen write SetDefaultLen;
end;
TDanceAnimMainDMod = class(TDataModule)
ImgLstStandard: TImageList;
ImgLstCategories: TImageList;
OpenDlgLibrary: TOpenDialog;
OpenDlgSongLen: TOpenDialog;
OpenDlgSIDTune: TOpenDialog;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
FConfig: TDanceAnimConfig;
FPlayConfig: TXSIDConfig;
public
procedure InitConfigForXSIDFile(AFileConfig: TXSIDFileConfig);
property Configuration: TDanceAnimConfig read FConfig;
property PlayConfig: TXSIDConfig read FPlayConfig;
end;
var
DanceAnimMainDMod: TDanceAnimMainDMod;
implementation
{%CLASSGROUP 'FMX.Controls.TControl'}
{$R *.dfm}
uses
System.IOUtils, FMX.Forms, C64Types, SIDConvTypes, XSIDPlatform,
FMX.Platform.Win;
{ TDanceAnimConfig }
constructor TDanceAnimConfig.Create;
begin
inherited Create;
FDefaultLen:= EncodeTime(0, 3, 0, 0);
end;
destructor TDanceAnimConfig.Destroy;
begin
inherited;
end;
procedure TDanceAnimConfig.LoadFromIniFile(const AFileName: string);
var
ini: TIniFile;
begin
ini:= TIniFile.Create(AFileName);
try
FSonglenFile:= ini.ReadString('Dependencies', 'SonglenFile', '');
FDefaultLen:= ini.ReadTime('Defaults', 'DefaultLen',
EncodeTime(0, 3, 0, 0));
finally
ini.Free;
end;
end;
procedure TDanceAnimConfig.SaveToIniFile(const AFileName: string);
var
ini: TIniFile;
begin
ini:= TIniFile.Create(AFileName);
try
ini.WriteString('Dependencies', 'SonglenFile', FSonglenFile);
ini.WriteTime('Defaults', 'DefaultLen', FDefaultLen);
finally
ini.Free;
end;
end;
procedure TDanceAnimConfig.SetDefaultLen(const AValue: TTime);
var
h,
m,
s,
ms: Word;
begin
DecodeTime(AValue, h, m, s, ms);
FDefaultLen:= EncodeTime(0, m, s, 0);
end;
procedure TDanceAnimMainDMod.DataModuleCreate(Sender: TObject);
var
f: string;
begin
f:= TPath.ChangeExtension(ParamStr(0), '.ini');
FConfig:= TDanceAnimConfig.Create;
FConfig.LoadFromIniFile(f);
InitialiseConfig(f);
FPlayConfig:= TXSIDConfig.Create;
if FConfig.SonglenFile <> '' then
LoadSongLengths(FConfig.SonglenFile);
end;
procedure TDanceAnimMainDMod.DataModuleDestroy(Sender: TObject);
var
f: string;
ini: TIniFile;
begin
FPlayConfig.Free;
f:= TPath.ChangeExtension(ParamStr(0), '.ini');
FConfig.SaveToIniFile(f);
FinaliseConfig(f);
end;
procedure TDanceAnimMainDMod.InitConfigForXSIDFile(
AFileConfig: TXSIDFileConfig);
var
p: TStringList;
begin
FPlayConfig.Assign(GlobalConfig);
p:= TStringList.Create;
try
p.Add('Handle=' + IntToStr(WindowHandleToPlatform(
Application.MainForm.Handle).wnd));
FPlayConfig.SetRenderParams(p);
finally
p.Free;
end;
if not FPlayConfig.SystemOverride
and (AFileConfig.System > cstUnknown) then
FPlayConfig.System:= AFileConfig.System;
if not FPlayConfig.UpdateRateOverride then
FPlayConfig.UpdateRate:= AFileConfig.UpdateRate;
if not FPlayConfig.ModelOverride
and (AFileConfig.Model > csmAny) then
FPlayConfig.Model:= AFileConfig.Model;
FPlayConfig.FilterEnable:= AFileConfig.FilterEnable;
FPlayConfig.Filter6581:= AFileConfig.Filter6581;
FPlayConfig.Filter8580:= AFileConfig.Filter8580;
FPlayConfig.DigiBoostEnable:= AFileConfig.DigiBoostEnable;
end;
end.
|
//
// Generated by JavaToPas v1.5 20140918 - 132127
////////////////////////////////////////////////////////////////////////////////
unit java.util.concurrent.RejectedExecutionHandler;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
java.util.concurrent.TimeUnit,
java.util.concurrent.BlockingQueue,
java.util.concurrent.ThreadFactory;
type
JThreadPoolExecutor = interface; // merged
JRejectedExecutionHandler = interface;
JRejectedExecutionHandlerClass = interface(JObjectClass)
['{641AAAD8-D325-4B64-A0A4-71B11A8F7CDC}']
procedure rejectedExecution(JRunnableparam0 : JRunnable; JThreadPoolExecutorparam1 : JThreadPoolExecutor) ; cdecl;// (Ljava/lang/Runnable;Ljava/util/concurrent/ThreadPoolExecutor;)V A: $401
end;
[JavaSignature('java/util/concurrent/RejectedExecutionHandler')]
JRejectedExecutionHandler = interface(JObject)
['{67A45BCA-A294-404E-B322-895AB60CD8DC}']
procedure rejectedExecution(JRunnableparam0 : JRunnable; JThreadPoolExecutorparam1 : JThreadPoolExecutor) ; cdecl;// (Ljava/lang/Runnable;Ljava/util/concurrent/ThreadPoolExecutor;)V A: $401
end;
TJRejectedExecutionHandler = class(TJavaGenericImport<JRejectedExecutionHandlerClass, JRejectedExecutionHandler>)
end;
// Merged from: .\android-19\java.util.concurrent.ThreadPoolExecutor.pas
JThreadPoolExecutorClass = interface(JObjectClass)
['{E147A695-9FD8-4DE4-B9BA-5EB746A9ABAB}']
function allowsCoreThreadTimeOut : boolean; cdecl; // ()Z A: $1
function awaitTermination(timeout : Int64; &unit : JTimeUnit) : boolean; cdecl;// (JLjava/util/concurrent/TimeUnit;)Z A: $1
function getActiveCount : Integer; cdecl; // ()I A: $1
function getCompletedTaskCount : Int64; cdecl; // ()J A: $1
function getCorePoolSize : Integer; cdecl; // ()I A: $1
function getKeepAliveTime(&unit : JTimeUnit) : Int64; cdecl; // (Ljava/util/concurrent/TimeUnit;)J A: $1
function getLargestPoolSize : Integer; cdecl; // ()I A: $1
function getMaximumPoolSize : Integer; cdecl; // ()I A: $1
function getPoolSize : Integer; cdecl; // ()I A: $1
function getQueue : JBlockingQueue; cdecl; // ()Ljava/util/concurrent/BlockingQueue; A: $1
function getRejectedExecutionHandler : JRejectedExecutionHandler; cdecl; // ()Ljava/util/concurrent/RejectedExecutionHandler; A: $1
function getTaskCount : Int64; cdecl; // ()J A: $1
function getThreadFactory : JThreadFactory; cdecl; // ()Ljava/util/concurrent/ThreadFactory; A: $1
function init(corePoolSize : Integer; maximumPoolSize : Integer; keepAliveTime : Int64; &unit : JTimeUnit; workQueue : JBlockingQueue) : JThreadPoolExecutor; cdecl; overload;// (IIJLjava/util/concurrent/TimeUnit;Ljava/util/concurrent/BlockingQueue;)V A: $1
function init(corePoolSize : Integer; maximumPoolSize : Integer; keepAliveTime : Int64; &unit : JTimeUnit; workQueue : JBlockingQueue; handler : JRejectedExecutionHandler) : JThreadPoolExecutor; cdecl; overload;// (IIJLjava/util/concurrent/TimeUnit;Ljava/util/concurrent/BlockingQueue;Ljava/util/concurrent/RejectedExecutionHandler;)V A: $1
function init(corePoolSize : Integer; maximumPoolSize : Integer; keepAliveTime : Int64; &unit : JTimeUnit; workQueue : JBlockingQueue; threadFactory : JThreadFactory) : JThreadPoolExecutor; cdecl; overload;// (IIJLjava/util/concurrent/TimeUnit;Ljava/util/concurrent/BlockingQueue;Ljava/util/concurrent/ThreadFactory;)V A: $1
function init(corePoolSize : Integer; maximumPoolSize : Integer; keepAliveTime : Int64; &unit : JTimeUnit; workQueue : JBlockingQueue; threadFactory : JThreadFactory; handler : JRejectedExecutionHandler) : JThreadPoolExecutor; cdecl; overload;// (IIJLjava/util/concurrent/TimeUnit;Ljava/util/concurrent/BlockingQueue;Ljava/util/concurrent/ThreadFactory;Ljava/util/concurrent/RejectedExecutionHandler;)V A: $1
function isShutdown : boolean; cdecl; // ()Z A: $1
function isTerminated : boolean; cdecl; // ()Z A: $1
function isTerminating : boolean; cdecl; // ()Z A: $1
function prestartAllCoreThreads : Integer; cdecl; // ()I A: $1
function prestartCoreThread : boolean; cdecl; // ()Z A: $1
function remove(task : JRunnable) : boolean; cdecl; // (Ljava/lang/Runnable;)Z A: $1
function shutdownNow : JList; cdecl; // ()Ljava/util/List; A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
procedure allowCoreThreadTimeOut(value : boolean) ; cdecl; // (Z)V A: $1
procedure execute(command : JRunnable) ; cdecl; // (Ljava/lang/Runnable;)V A: $1
procedure purge ; cdecl; // ()V A: $1
procedure setCorePoolSize(corePoolSize : Integer) ; cdecl; // (I)V A: $1
procedure setKeepAliveTime(time : Int64; &unit : JTimeUnit) ; cdecl; // (JLjava/util/concurrent/TimeUnit;)V A: $1
procedure setMaximumPoolSize(maximumPoolSize : Integer) ; cdecl; // (I)V A: $1
procedure setRejectedExecutionHandler(handler : JRejectedExecutionHandler) ; cdecl;// (Ljava/util/concurrent/RejectedExecutionHandler;)V A: $1
procedure setThreadFactory(threadFactory : JThreadFactory) ; cdecl; // (Ljava/util/concurrent/ThreadFactory;)V A: $1
procedure shutdown ; cdecl; // ()V A: $1
end;
[JavaSignature('java/util/concurrent/ThreadPoolExecutor$DiscardOldestPolicy')]
JThreadPoolExecutor = interface(JObject)
['{0A67A0AA-F620-4959-88E0-F786D6C69600}']
function allowsCoreThreadTimeOut : boolean; cdecl; // ()Z A: $1
function awaitTermination(timeout : Int64; &unit : JTimeUnit) : boolean; cdecl;// (JLjava/util/concurrent/TimeUnit;)Z A: $1
function getActiveCount : Integer; cdecl; // ()I A: $1
function getCompletedTaskCount : Int64; cdecl; // ()J A: $1
function getCorePoolSize : Integer; cdecl; // ()I A: $1
function getKeepAliveTime(&unit : JTimeUnit) : Int64; cdecl; // (Ljava/util/concurrent/TimeUnit;)J A: $1
function getLargestPoolSize : Integer; cdecl; // ()I A: $1
function getMaximumPoolSize : Integer; cdecl; // ()I A: $1
function getPoolSize : Integer; cdecl; // ()I A: $1
function getQueue : JBlockingQueue; cdecl; // ()Ljava/util/concurrent/BlockingQueue; A: $1
function getRejectedExecutionHandler : JRejectedExecutionHandler; cdecl; // ()Ljava/util/concurrent/RejectedExecutionHandler; A: $1
function getTaskCount : Int64; cdecl; // ()J A: $1
function getThreadFactory : JThreadFactory; cdecl; // ()Ljava/util/concurrent/ThreadFactory; A: $1
function isShutdown : boolean; cdecl; // ()Z A: $1
function isTerminated : boolean; cdecl; // ()Z A: $1
function isTerminating : boolean; cdecl; // ()Z A: $1
function prestartAllCoreThreads : Integer; cdecl; // ()I A: $1
function prestartCoreThread : boolean; cdecl; // ()Z A: $1
function remove(task : JRunnable) : boolean; cdecl; // (Ljava/lang/Runnable;)Z A: $1
function shutdownNow : JList; cdecl; // ()Ljava/util/List; A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
procedure allowCoreThreadTimeOut(value : boolean) ; cdecl; // (Z)V A: $1
procedure execute(command : JRunnable) ; cdecl; // (Ljava/lang/Runnable;)V A: $1
procedure purge ; cdecl; // ()V A: $1
procedure setCorePoolSize(corePoolSize : Integer) ; cdecl; // (I)V A: $1
procedure setKeepAliveTime(time : Int64; &unit : JTimeUnit) ; cdecl; // (JLjava/util/concurrent/TimeUnit;)V A: $1
procedure setMaximumPoolSize(maximumPoolSize : Integer) ; cdecl; // (I)V A: $1
procedure setRejectedExecutionHandler(handler : JRejectedExecutionHandler) ; cdecl;// (Ljava/util/concurrent/RejectedExecutionHandler;)V A: $1
procedure setThreadFactory(threadFactory : JThreadFactory) ; cdecl; // (Ljava/util/concurrent/ThreadFactory;)V A: $1
procedure shutdown ; cdecl; // ()V A: $1
end;
TJThreadPoolExecutor = class(TJavaGenericImport<JThreadPoolExecutorClass, JThreadPoolExecutor>)
end;
implementation
end.
|
Function IsWhitespace(chr : Char) : Boolean;
Begin
// #9 = \t (tab)
// #13 = \r (carriage return)
IsWhitespace := (chr = ' ') Or (chr = sLineBreak) Or (chr = ''#9'')
Or (chr = ''#13'');
End;
Function IsNumberLike(chr : Char) : Boolean;
Begin
IsNumberLike := (chr = '0') Or (chr = '1') Or (chr = '2') Or (chr = '3') Or (
chr = '4') Or (chr = '5') Or (chr = '6') Or (chr = '7') Or (
chr = '8') Or (chr = '9') Or (chr = '.');
End;
Type
Parser = Object
Index : Integer;
Buffer : String;
Constructor Init;
Private
Procedure Expect(chr : Char);
Procedure SkipWhitespace();
Procedure MoveNext();
Function Peek() : Char;
Function ReadNode() : Node;
Function ReadString() : StringNode;
Function ReadNumber() : NumberNode;
Function ReadArray() : ArrayNode;
Function ReadObject() : ObjectNode;
Public
Function Parse(s: String) : Node;
End;
Constructor Parser.Init();
Begin
Index := 1;
Buffer := '';
End;
Procedure Parser.Expect(chr : Char);
Var found : Char;
Begin
found := Self.Peek();
If found <> chr Then
Begin
WriteLn('Expected ' + chr + ', found ' + found);
halt(1);
End;
End;
Procedure Parser.SkipWhitespace();
Begin
While IsWhitespace(Self.Peek()) Do
Begin
Self.MoveNext();
End;
End;
Function Parser.Peek() : Char;
Begin
Peek := Buffer[Self.Index];
End;
Procedure Parser.MoveNext();
Begin
Self.Index := Self.Index + 1;
End;
Function Parser.ReadNode() : Node;
Var chr : Char;
Begin
Self.SkipWhitespace();
chr := Self.Peek();
If IsNumberLike(chr) Then
Begin
ReadNode := Self.ReadNumber();
End;
Case chr Of
'"' : ReadNode := Self.ReadString();
'[' : ReadNode := Self.ReadArray();
'{' : ReadNode := Self.ReadObject();
't' :
Begin
ReadNode := BooleanNode.Init(true);
Self.Index := Self.Index + 4;
End;
'f':
Begin
ReadNode := BooleanNode.Init(false);
Self.Index := Self.Index + 5;
End;
'n':
Begin
ReadNode := NullNode.Init();
Self.Index := Self.Index + 4;
End;
End;
End;
Function Parser.ReadString() : StringNode;
Var chr : Char;
Var str : String;
Begin
str := '';
Self.Expect('"');
Self.MoveNext();
While Self.Peek() <> '"' Do
Begin
chr := Self.Peek();
If chr = '\' Then
Begin
// move past the escape character.
Self.MoveNext();
str := str + Self.Peek();
Self.MoveNext();
End
Else
Begin
str := str + chr;
Self.Index := Self.Index + 1
End
End;
Self.MoveNext();
ReadString := StringNode.Init(str);
End;
Function Parser.ReadNumber() : NumberNode;
Var str : String;
Var ch : Char;
Begin
str := '';
While IsNumberLike(Self.Peek()) Do
Begin
str := str + Self.Peek();
Self.MoveNext();
End;
ReadNumber := NumberNode.Init(StrToFloat(str));
End;
Function Parser.ReadArray() : ArrayNode;
Var nodes : NodeList;
Var i : Integer;
Begin
Self.Expect('[');
Self.MoveNext();
i := 0;
While Self.Peek() <> ']' Do
Begin
nodes[i] := Self.ReadNode();
i := i + 1;
Self.SkipWhitespace();
If Self.Peek() = ',' Then
Begin
Self.MoveNext();
End;
End;
Self.MoveNext();
ReadArray := ArrayNode.Init(nodes);
End;
Function Parser.ReadObject() : ObjectNode;
Var i : Integer;
Var key : StringNode;
Var value : Node;
Var entries : ObjectEntryList;
Begin
Self.Expect('{');
Self.MoveNext();
i := 0;
While Self.Peek() <> '}' Do
Begin
Self.SkipWhitespace();
key := Self.ReadString();
Self.SkipWhitespace();
Self.Expect(':');
Self.MoveNext();
value := Self.ReadNode();
entries[i] := ObjectEntry.Init(key.Value, value);
i := i + 1;
Self.SkipWhitespace();
If Self.Peek() = ',' Then
Begin
Self.MoveNext();
End;
End;
Self.MoveNext();
ReadObject := ObjectNode.Init(entries);
End;
Function Parser.Parse(s: String) : Node;
Begin
// the string type is 1-indexed.
Self.Index := 1;
Self.Buffer := s;
Parse := self.ReadNode();
End;
|
unit Objekt.DHLUpdateShipmentorderResponse;
interface
uses
System.SysUtils, System.Classes, Objekt.DHLVersionResponse, Objekt.DHLStatusinformation,
Objekt.DHLLabelData;
type
TDHLUpdateShipmentorderResponse = class
private
fVersion: TDHLVersionResponse;
fStatus: TDHLStatusinformation;
fLabelData: TDHLLabelData;
public
constructor Create;
destructor Destroy; override;
property Version: TDHLVersionResponse read fVersion write fVersion;
property Status: TDHLStatusinformation read fStatus write fStatus;
property LabelData: TDHLLabelData read fLabelData write fLabelData;
end;
implementation
{ TDHLUpdateShipmentorderResponse }
constructor TDHLUpdateShipmentorderResponse.Create;
begin
fVersion := TDHLVersionResponse.Create;
fStatus := TDHLStatusinformation.Create;
fLabelData := TDHLLabelData.Create;
end;
destructor TDHLUpdateShipmentorderResponse.Destroy;
begin
FreeAndNil(fVersion);
FreeAndNil(fStatus);
FreeAndNil(fLabelData);
inherited;
end;
end.
|
{ Ingresar en un arreglo N números enteros, generar dos arreglos VPos y VNeg que contendrán
los números positivos y negativos respectivamente. Mostrar el más numeroso, ambos si la cantidad
de elementos coinciden}
Program eje3;
Type
TV = array[1..100] of integer;
Procedure LeeVector(Var Vec:TV; Var N:byte);
Var
Num:integer;
begin
N:= 0;
write('Ingrese un numero (0 cuando desee finalizar) : ');readln(Num);
while (Num <> 0) do
begin
N:= N + 1;
Vec[N]:= Num;
write('Ingrese un numero : ');readln(Num);
end;
end;
Procedure GeneraArrays(Vec:TV; N:byte; Var M,K:byte; Var VPos,VNeg:TV);
Var
i:byte;
begin
M:= 0;
K:= 0;
For i:= 1 to N do
begin
If (Vec[i] > 0) then
begin
M:= M + 1;
VPos[M]:= Vec[i];
end
Else
begin
K:= K + 1;
VNeg[K]:= Vec[i];
end;
end;
end;
Procedure Muestra(VPos:TV; VNeg:TV; M:byte; K:byte);
Var
i:byte;
begin
writeln;
If (M = K) then
begin
writeln('Ambos vectores poseen la misma cantidad de numeros');
For i:= 1 to M do
writeln(VPos[i]);
writeln;
For i:= 1 to K do
writeln(VNeg[i]);
end
Else
If (M > K) then
begin
writeln('El vector mas numeroso es el positivo con los numeros: ');
For i:= 1 to M do
writeln(VPos[i]);
end
else
begin
writeln('El vector mas numeroso es el negativo con los numeros: ');
For i:= 1 to K do
writeln(VNeg[i]);
end;
end;
Var
Vec,VPos,VNeg:TV;
N,M,K:byte;
Begin
LeeVector(Vec,N);
GeneraArrays(Vec,N,M,K,VPos,VNeg);
Muestra(VPos,VNeg,M,K);
end.
|
unit MyJSONObjectHelper;
interface
uses
System.JSON;
type
TMyJSONObjectFunctions = class
public
class function AsLowerCasePath( const aJSONObject: TJSONObject ): TJSONObject; overload;
class function AsLowerCasePath( const aJSONArray: TJSONArray ): TJSONArray; overload;
class function AsUpperCasePath( const aJSONObject: TJSONObject ): TJSONObject; overload;
class function AsUpperCasePath( const aJSONArray: TJSONArray ): TJSONArray; overload;
end;
implementation
uses
System.SysUtils
, System.Generics.Collections
;
{ TMyJSONObjectFunctions }
class function TMyJSONObjectFunctions.AsLowerCasePath(
const aJSONArray: TJSONArray): TJSONArray;
var
i: Integer;
begin
Result:=TJSONArray.Create;
for i := 0 to aJSONArray.Count-1 do
Result.AddElement( AsLowerCasePath( TJSONObject( aJSONArray.Items[i] ) ) );
end;
class function TMyJSONObjectFunctions.AsUpperCasePath(
const aJSONArray: TJSONArray): TJSONArray;
var
i: Integer;
begin
Result:=TJSONArray.Create;
for i := 0 to aJSONArray.Count-1 do
Result.AddElement( AsLowerCasePath( TJSONObject( aJSONArray.Items[i] ) ) );
end;
class function TMyJSONObjectFunctions.AsUpperCasePath(
const aJSONObject: TJSONObject): TJSONObject;
var
i: Integer;
begin
Result:=TJSONObject.Create;
for i := 0 to aJSONObject.Count-1 do
Result.AddPair( UpperCase( aJSONObject.Pairs[i].JsonString.Value ), aJSONObject.Pairs[i].JsonValue.Value );
end;
class function TMyJSONObjectFunctions.AsLowerCasePath(
const aJSONObject: TJSONObject): TJSONObject;
var
i: Integer;
begin
Result:=TJSONObject.Create;
for i := 0 to aJSONObject.Count-1 do
Result.AddPair( LowerCase( aJSONObject.Pairs[i].JsonString.Value ), aJSONObject.Pairs[i].JsonValue.Value );
end;
end.
|
unit UntMain;
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.Ani, FMX.ListView, FMX.Objects, FMX.Controls.Presentation, FMX.StdCtrls,
FMX.Layouts, FMX.Effects, FMX.MultiView, FMX.ListBox, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.StorageBin, Data.DB,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, frameList, FMX.Edit, FMX.SearchBox;
type
TfrmMain = class(TForm)
layout_principal: TLayout;
Rectangle1: TRectangle;
Layout1: TLayout;
Label1: TLabel;
img_menu: TImage;
ShadowEffect2: TShadowEffect;
mtvMenu: TMultiView;
rect_menu: TRectangle;
AnimationMenu: TFloatAnimation;
Layout5: TLayout;
Layout2: TLayout;
Layout3: TLayout;
Path1: TPath;
Layout4: TLayout;
Label3: TLabel;
SpeedButton2: TSpeedButton;
lytExit: TLayout;
lytIcoExit: TLayout;
pthIcoExit: TPath;
lytTextExit: TLayout;
lblExit: TLabel;
speLogoff: TSpeedButton;
Rectangle4: TRectangle;
Label2: TLabel;
SpeedButton1: TSpeedButton;
Circle3: TCircle;
Circle4: TCircle;
ShadowEffect1: TShadowEffect;
ListBoxExample: TListBox;
StyleBook1: TStyleBook;
SearchBox1: TSearchBox;
lytCont: TLayout;
FDMemTable: TFDMemTable;
FDMemTableID_VEHICULO: TIntegerField;
FDMemTableCHAPA: TStringField;
FDMemTableMARCA: TStringField;
FDMemTableANHO: TIntegerField;
FDMemTableFECHA: TDateTimeField;
procedure FormResize(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
{$R *.fmx}
procedure Close_Menu();
begin
with frmMain do
begin
mtvMenu.Mode := TMultiViewMode.Drawer;
end;
end;
procedure Open_Menu();
begin
with frmMain do
begin
mtvMenu.Mode := TMultiViewMode.Panel;
end;
end;
procedure Menu();
var
larg_screen: Integer;
begin
{$IFDEF ANDROID}
larg_screen := Screen.width;
{$ENDIF}
{$IFDEF MSWINDOWS}
larg_screen := frmMain.width;
{$ENDIF}
with frmMain do
begin
begin
if (larg_screen < 600) then
begin
// Si la pantalla es menor a 600 se cerrara el menu(cambia de modo a Drawer)
Close_Menu;
end;
if (larg_screen >= 600) then
begin
// Si la pantalla es mayor a 599 se abrira el menu (cambia de modo a Panel)
Open_Menu;
end;
end;
end;
end;
procedure TfrmMain.FormResize(Sender: TObject);
begin
Menu();
end;
procedure TfrmMain.FormShow(Sender: TObject);
var
item: TListBoxItem;
vFrame: TframeListExample;
begin
ListBoxExample.Clear;
ListBoxExample.BeginUpdate;
FDMemTable.First;
while not FDMemTable.Eof do
begin
item := TListBoxItem.Create(self);
vFrame := TframeListExample.Create(self);
vFrame.Name:= 'Frame'+FDMemTable.FieldByName('ID_VEHICULO').AsString;;
vFrame.Align := TAlignLayout.Client;
vFrame.Parent := item;
// ---------------------------------------
//for the search by (CHAPA) and (MARCA)
item.Text := FDMemTable.FieldByName('CHAPA').AsString+' '+ FDMemTable.FieldByName('MARCA').AsString;
//Text visible:= false in style designer
// ---------------------------------------
item.Height := 167;
item.Margins.Left:= 3;
item.Margins.Right:= 3;
item.Margins.Top:= 3;
item.Margins.Bottom:= 3;
vFrame.lblTituloPrincipal.Text := FDMemTable.FieldByName('CHAPA').AsString;
vFrame.lblSubTitu1.Text := FDMemTable.FieldByName('FECHA').AsString;
vFrame.lblSubTitu2.Text := FDMemTable.FieldByName('MARCA').AsString;
vFrame.lblSubTitu3.Text := FDMemTable.FieldByName('ANHO').AsString;
item.Parent := ListBoxExample;
FDMemTable.Next;
end;
ListBoxExample.EndUpdate;
end;
end.
|
unit LazyShakerForm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
System.Sensors,
{$IFDEF VER270}
System.Sensors.Components,
{$ELSE}
FMX.Sensors,
{$ENDIF}
FMX.Layouts, FMX.Memo, FMX.Media,
FMX.StdCtrls, System.Actions, FMX.ActnList, FMX.StdActns, FMX.Objects;
type
TLazyShakeSensor = class
strict private
type
TSensorData = double;
var
FMotionSensor: TMotionSensor;
FTimer: TTimer;
FOnShake: TNotifyEvent;
// acceleration apart from gravity
FAccel: TLazyShakeSensor.TSensorData;
// current acceleration including gravity
FAccelCurrent: TLazyShakeSensor.TSensorData;
// last acceleration including gravity
FAccelLast: TLazyShakeSensor.TSensorData;
procedure DoOnSensorDataChanged(Sender: TObject);
procedure DoTriggerShakeEvent;
public
procedure InitSensors;
procedure DeInitSensors;
constructor Create;
destructor Destroy; override;
property OnShake: TNotifyEvent read FOnShake write FOnShake;
end;
TfrmLazyShaker = class(TForm)
MediaPlayer1: TMediaPlayer;
ActionList1: TActionList;
FileExit1: TFileExit;
Button1: TButton;
Image1: TImage;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
strict private
FShakeSensor: TLazyShakeSensor;
procedure PlaySound(const aFile: string);
procedure PlayDefaultSound;
procedure DoOnShake(Sender: TObject);
end;
var
frmLazyShaker: TfrmLazyShaker;
implementation
uses
IoUtils;
{$R *.fmx}
procedure TfrmLazyShaker.DoOnShake(Sender: TObject);
begin
PlayDefaultSound;
end;
procedure TfrmLazyShaker.FormCreate(Sender: TObject);
begin
FShakeSensor:= TLazyShakeSensor.Create;
FShakeSensor.OnShake := DoOnShake;
FShakeSensor.InitSensors;
end;
procedure TfrmLazyShaker.FormDestroy(Sender: TObject);
begin
try
FShakeSensor.DeInitSensors;
except
// act bad - eat exception
end;
FreeAndNil(FShakeSensor);
end;
procedure TfrmLazyShaker.PlayDefaultSound;
var
s: string;
begin
s := TPath.GetDocumentsPath;
s := TPath.Combine(s, 'ElevatorBell.mp3');
PlaySound(s);
end;
procedure TfrmLazyShaker.PlaySound(const aFile: string);
begin
if FileExists(aFile) then
begin
MediaPlayer1.Stop;
MediaPlayer1.Clear;
MediaPlayer1.Volume := 100;
MediaPlayer1.FileName := aFile;
MediaPlayer1.CurrentTime := 0;
MediaPlayer1.Play;
end;
end;
{ TLazyShakeSensor }
constructor TLazyShakeSensor.Create;
begin
FAccel:=0;
FAccelCurrent:=0.9;
FAccelLast:=0.9;
end;
procedure TLazyShakeSensor.DeInitSensors;
begin
FTimer.Enabled := False;
FreeAndNil(FTimer);
FreeAndNil(FMotionSensor);
end;
destructor TLazyShakeSensor.Destroy;
begin
inherited;
end;
procedure TLazyShakeSensor.DoOnSensorDataChanged(Sender: TObject);
var
tmpSensor: TCustomMotionSensor;
x,y,z: TSensorData;
begin
if FMotionSensor.Sensor<>nil then
begin
tmpSensor := FMotionSensor.Sensor;
x := tmpSensor.AccelerationX;
y := tmpSensor.AccelerationY;
z := tmpSensor.AccelerationZ;
FAccelLast := FAccelCurrent;
FAccelCurrent := Sqrt(x*x+y*y+z*z);
FAccel := FAccel*0.9+(FAccelCurrent-FAccelLast);
if FAccel >1.3 then
DoTriggerShakeEvent;
end;
end;
procedure TLazyShakeSensor.DoTriggerShakeEvent;
begin
if Assigned(FOnShake) then
FOnShake(Self);
end;
procedure TLazyShakeSensor.InitSensors;
begin
FMotionSensor := TMotionSensor.Create(nil);
FMotionSensor.Active := True;
FTimer := TTimer.Create(nil);
FTimer.OnTimer := DoOnSensorDataChanged;
FTimer.Interval := 50;
FTimer.Enabled := True;
end;
end.
|
unit uWMISUserRight;
{$WARN SYMBOL_PLATFORM OFF}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComServ, ComObj, VCLCom, StdVcl, bdemts, DataBkr, DBClient,
MtsRdm, Mtx, WMISUserRightPJT_TLB, DB, ADODB,Provider,XMLIntf, XMLDoc,StrUtils;
type
TWMISUserRight = class(TMtsDataModule, IWMISUserRight)
adoqryPublic: TADOQuery;
adoConnection: TADOConnection;
procedure MtsDataModuleCreate(Sender: TObject);
private
{ Private declarations }
function GetLibraryFullPath(sLibraryName: string): string;
function GetConnectionString(sLibraryName: string;sSystemId: string): string;
protected
class procedure UpdateRegistry(Register: Boolean; const ClassID, ProgID: string); override;
procedure GetDefaultDepartment(const sUserID: WideString;
var sDefaultDepartment, sErrMsg: WideString); safecall;
procedure GetMenuInfo(const sUserID: WideString; iSysID: Integer;
var vData: OleVariant; var sErrMs: WideString); safecall;
procedure GetSystemInfo(const SysName: WideString; var SysId: Integer;
var SysFullName, UpdatePath, Mail: WideString); safecall;
procedure GetUserDepartmentList(const sUserID: WideString;
var sDepartmentList, sErrMsg: WideString); safecall;
procedure GetUserDepartments(const sUserID: WideString; iSysID: Integer;
var vData: OleVariant; var sErrMsg: WideString); safecall;
procedure GetUserLevel(vSystem_ID: Integer;
const vComputer_Name: WideString; var vLevelList: WideString);
safecall;
procedure IsTerminal(const vComputer_Name: WideString;
var vTerminal: WordBool); safecall;
procedure Login(vSystem_ID: Integer; const vComputer_Name: WideString;
var vUser_ID, vUser_Name, vMenuList, vMsg: WideString); safecall;
procedure Logoff(vSystem_ID: Integer; const vUser_ID,
vComputer_Name: WideString); safecall;
procedure GetUserLevelByUserid(vSysID: Integer; const vUserID: WideString;
var vLevelList: WideString); safecall;
public
{ Public declarations }
end;
var
WMISUserRight: TWMISUserRight;
implementation
{$R *.DFM}
class procedure TWMISUserRight.UpdateRegistry(Register: Boolean; const ClassID, ProgID: string);
begin
if Register then
begin
inherited UpdateRegistry(Register, ClassID, ProgID);
EnableSocketTransport(ClassID);
EnableWebTransport(ClassID);
end
else
begin
DisableSocketTransport(ClassID);
DisableWebTransport(ClassID);
inherited UpdateRegistry(Register, ClassID, ProgID);
end;
end;
procedure TWMISUserRight.IsTerminal(const vComputer_Name: WideString;
var vTerminal: WordBool);
begin
vTerminal := False;
try
adoConnection.Open;
adoqryPublic.SQL.Text := 'SELECT ServerName '#13#10 +
'FROM systempanel.dbo.TermServerName '#13#10 +
'WHERE ServerName = ''' + vComputer_Name + ''' ';
adoqryPublic.Open;
if adoqryPublic.RecordCount > 0 then
vTerminal := True;
finally
SetComplete;
adoqryPublic.Close;
adoConnection.Close;
end;
end;
procedure TWMISUserRight.Login(vSystem_ID: Integer;
const vComputer_Name: WideString; var vUser_ID, vUser_Name, vMenuList,
vMsg: WideString);
begin
vMsg := '错误!';
try
try
adoConnection.Open;
with adoqryPublic do
begin
SQL.Text := 'EXEC systempanel.dbo.up_GetUsername ''' +
vComputer_Name + ''', ' + IntToStr(vSystem_ID)+','+Quotedstr(vUser_ID);
Open;
if RecordCount = 0 then
begin
vMsg := '对不起,你不能使用该系统!';
Exit;
end;
vUser_ID := FieldByName('userid').AsString;
vUser_Name := FieldByName('username').AsString;
Close;
SQL.Text := 'EXEC systempanel.dbo.up_GetRight ''' +
vComputer_Name + ''', ' + IntToStr(vSystem_ID)+','+Quotedstr(vUser_ID);
Open;
if RecordCount = 0 then
begin
vMsg := '对不起,你没有权限使用本系统!';
Exit;
end;
while not Eof do
begin
vMenuList := vMenuList + FieldByName('MenuId').AsString + #13#10;
Next;
end;
vMsg := 'OK';
end;
except
on E: Exception do
begin
vMsg := E.Message;
end;
end;
finally
SetComplete;
adoqryPublic.Close;
adoConnection.Close;
end;
end;
procedure TWMISUserRight.Logoff(vSystem_ID: Integer; const vUser_ID,
vComputer_Name: WideString);
begin
try
adoConnection.Open;
adoqryPublic.SQL.Text := 'EXEC systempanel.dbo.write_exit_time ''' +
vComputer_Name + ''', ''' + vUser_ID + ''', ' + IntToStr(vSystem_ID);
adoqryPublic.ExecSQL;
finally
SetComplete;
adoConnection.Close;
end;
end;
procedure TWMISUserRight.GetUserLevel(vSystem_ID: Integer;
const vComputer_Name: WideString; var vLevelList: WideString);
begin
vLevelList := '';
try
adoConnection.Open;
with adoqryPublic do
begin
SQL.Text := 'EXEC systempanel.dbo.up_GetUserLevel ''' +
vComputer_Name + ''', ' + IntToStr(vSystem_ID);
Open;
while not Eof do
begin
vLevelList := vLevelList + FieldByName('userLevel').AsString + #13#10;
Next;
end;
end;
finally
SetComplete;
adoqryPublic.Close;
adoConnection.Close;
end;
end;
procedure TWMISUserRight.GetSystemInfo(const SysName: WideString;
var SysId: Integer; var SysFullName, UpdatePath, Mail: WideString);
var sqlText:widestring;
begin
sqlText:='select sysid,sysfullname_CHN,exefilepath,mailbox from systempanel.dbo.system_detail'+
' where sysname='''+sysName+'''';
try
adoConnection.Open;
with adoqryPublic do
begin
SQL.Text :=sqlText;
Open ;
if not( Eof and Bof ) then
begin
sysid:=FieldBYName('SysId').AsInteger ;
sysfullname:=FieldBYName('sysfullname_CHN').AsString ;
updatepath:=FieldByName('ExeFilePath').AsString ;
mail:=FieldByName('MailBox').AsString ;
end
else
sysid:=-1;
end;
finally
SetComplete;
adoConnection.Close;
end;
end;
procedure TWMISUserRight.GetUserDepartmentList(const sUserID: WideString;
var sDepartmentList, sErrMsg: WideString);
var sqlText:widestring;
begin
sqlText:='exec SystemPanel..usp_GetUserDepartmentList '+ QuotedStr(sUserID);
try
adoConnection.Open;
with adoqryPublic do
begin
Close;
SQL.Text :=sqlText;
Open ;
if not IsEmpty then
sDepartmentList:=FieldBYName('DeptList').AsString
else
sDepartmentList:='';
end;
finally
SetComplete;
adoConnection.Close;
end;
end;
procedure TWMISUserRight.GetDefaultDepartment(const sUserID: WideString;
var sDefaultDepartment, sErrMsg: WideString);
var sqlText:widestring;
begin
sqlText:='select Default_Department from user_info where UserID= '+ QuotedStr(sUserID);
try
adoConnection.Open;
with adoqryPublic do
begin
Close;
SQL.Text :=sqlText;
Open ;
if not IsEmpty then
sDefaultDepartment:=FieldBYName('Default_Department').AsString
else
sDefaultDepartment:='';
end;
finally
SetComplete;
adoConnection.Close;
end;
end;
procedure TWMISUserRight.GetMenuInfo(const sUserID: WideString;
iSysID: Integer; var vData: OleVariant; var sErrMs: WideString);
var
sqlText:widestring;
Adsp:TDataSetProvider;
begin
sqlText:=' exec usp_WmisGetSysMenuInfo '+ QuotedStr(sUserID)+','+IntToStr(iSysID);
Adsp:=TDataSetProvider.Create(self);
Adsp.DataSet:=adoqryPublic;
try
adoConnection.Open;
with adoqryPublic do
begin
Close;
SQL.Text :=sqlText;
Open;
vData:=Adsp.Data;
end;
finally
SetComplete;
Adsp.Free;
adoConnection.Close;
end;
end;
procedure TWMISUserRight.GetUserDepartments(const sUserID: WideString;
iSysID: Integer; var vData: OleVariant; var sErrMsg: WideString);
var
sqlText:widestring;
Adsp:TDataSetProvider;
begin
sqlText:=' exec usp_WmisGetUserDepartments '+ QuotedStr(sUserID)+','+IntToStr(iSysID);
Adsp:=TDataSetProvider.Create(self);
Adsp.DataSet:=adoqryPublic;
try
adoConnection.Open;
with adoqryPublic do
begin
Close;
SQL.Text :=sqlText;
Open;
vData:=Adsp.Data;
end;
finally
SetComplete;
Adsp.Free;
adoConnection.Close;
end;
end;
function TWMISUserRight.GetConnectionString(sLibraryName,
sSystemId: string): string;
var connXMLFile,ConfigerFilePath,LibraryFullPath,ServerName,DatabaseName,UserID,Password,TimeOut: string;
xmlDoc: TXMLDocument;
ANode: IXMLNode;
iStringLength:integer;
begin
LibraryFullPath:=GetLibraryFullPath(sLibraryName);
if Rightstr(LibraryFullPath,1)=':' then
ConfigerFilePath:=LibraryFullPath+'\Configer\'
else
begin
iStringLength:=Length(LibraryFullPath);
while (iStringLength>=1) do
begin
if Midstr(LibraryFullPath,iStringLength,1)='\' then
break
else
iStringLength:=iStringLength-1;
end;
ConfigerFilePath:=Copy(LibraryFullPath,1,iStringLength-1)+'\Configer\';
end;
connXMLFile:=ConfigerFilePath+sSystemId+'.XML';
xmlDoc := TXMLDocument.Create(Application);
xmlDoc.FileName :=connXMLFile;
xmlDoc.Active :=true;
try
ANode:=xmlDoc.ChildNodes.FindNode('WMIS');
ANode:=ANode.ChildNodes.FindNode('Connection');
ServerName:=ANode.Attributes['ServerName'];
DatabaseName:=ANode.Attributes['DatabaseName'];
UserId:=ANode.Attributes['UserId'];
Password:=Anode.Attributes['Password'];
TimeOut:=inttostr(ANode.Attributes['TimeOut']);
finally
xmlDoc.Active := False;
xmlDoc.Free;
end;
Result :=
'Provider=SQLOLEDB.1;Password=' + Password +
';Persist Security Info=True;User ID=' + UserID +
';Initial Catalog=' + DatabaseName +
';Data Source=' + ServerName +
';TimeOut='+TimeOut+
';Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;' +
'Use Encryption for Data=False;Tag with column collation when possible=False';
end;
function TWMISUserRight.GetLibraryFullPath(sLibraryName: string): string;
var
hModule: THandle;
buff: array[0..255] of Char;
sFullName:string;
begin
hModule := GetModuleHandle(pChar(sLibraryName));
GetModuleFileName(hModule, buff, sizeof(buff));
sFullName:=buff;
result:=Copy(sFullName,1,Length(sFullName)-Length(sLibraryName)-1);
end;
procedure TWMISUserRight.MtsDataModuleCreate(Sender: TObject);
begin
adoConnection.ConnectionString :=self.GetConnectionString('WMISUserRightPJT.dll','WMISUSERRIGHT');
end;
procedure TWMISUserRight.GetUserLevelByUserid(vSysID: Integer;
const vUserID: WideString; var vLevelList: WideString);
begin
vLevelList := '';
try
adoConnection.Open;
with adoqryPublic do
begin
SQL.Text := 'EXEC systempanel.dbo.up_GetUserLevel '+quotedstr('')+','
+ IntToStr(vSysID)+','+quotedstr(vUserID);
Open;
while not Eof do
begin
vLevelList := vLevelList + FieldByName('userLevel').AsString + #13#10;
Next;
end;
end;
finally
SetComplete;
adoqryPublic.Close;
adoConnection.Close;
end;
end;
initialization
TComponentFactory.Create(ComServer, TWMISUserRight,
Class_WMISUserRight, ciMultiInstance, tmNeutral);
end.
|
{*******************************************************************************
* uActionControl *
* *
* Библиотека компонентов для работы с формой редактирования (qFControls) *
* Работа с действиями (добавление, изменение и т.д. (TqFActionControl) *
* Copyright © 2005-2006, Олег Г. Волков, Донецкий Национальный Университет *
*******************************************************************************}
unit uActionControl;
interface
uses
SysUtils, Classes, Controls, pFIBDatabase, pFIBDataset, pFIBQuery,
FIB, ActnList, uFormControl, Forms, DB;
type
TqFFormShowEvent = procedure (Sender: TObject; Form: TForm) of object;
TqFGetKeysEvent = procedure (Sender: TObject; var ValueString: Variant) of object;
TqFAfterRefreshEvent = procedure (Sender: TObject; Value: Variant) of object;
TqFCanPrepare = procedure(Sender: TObject; Mode: TFormMode; var CanPrepare: Boolean) of object;
TqFActionControl = class(TComponent)
private
FDatabase: TpFIBDatabase;
FWriteTransaction: TpFIBTransaction;
FDeleteQuery: TpFIBQuery;
FSelectDataset: TDataSet;
FKeyFields: String;
FNameField: String;
FKeyValues: Variant;
FRefreshAction: TAction;
FDeleteAction: TAction;
FAddAction: TAction;
FModifyAction: TAction;
FInfoAction: TAction;
FCloneAction: TAction;
FAddFormClass: String;
FBeforePrepare: TqFFormShowEvent;
FAfterPrepare: TqFFormShowEvent;
FOnShowForm: TqFFormShowEvent;
FAfterRefresh: TqFAfterRefreshEvent;
FOnRefresh: TNotifyEvent;
FAfterDelete: TNotifyEvent;
FOnGetKeys: TqFGetKeysEvent;
FCanEdit: TqFCanPrepare;
FCanDelete: TqFCanPrepare;
FBeforeDelete: TqFDatabaseEvent;
FYesFocusOnDelete: Boolean;
procedure FreeDBObjects;
procedure SetDeleteSQL(SQL: TStrings);
function GetDeleteSQL: TStrings;
procedure SetDatabase(DB: TpFIBDatabase);
procedure SetRefreshAction(Action: TAction);
procedure SetDeleteAction(Action: TAction);
procedure SetAddAction(Action: TAction);
procedure SetModifyAction(Action: TAction);
procedure SetInfoAction(Action: TAction);
procedure SetCloneAction(Action: TAction);
procedure GetKeyValues;
public
LastMode: TFormMode;
AddKeys: Variant;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Refresh;
procedure StdRefresh;
procedure Delete(Sender: TObject);
procedure DeleteQuery(Sender: TObject);
procedure ShowEditForm(Mode: TFormMode);
procedure ActionRefresh(Sender: TObject);
procedure ActionAdd(Sender: TObject);
procedure ActionModify(Sender: TObject);
procedure ActionInfo(Sender: TObject);
procedure ActionClone(Sender: TObject);
published
property DeleteSQL: TStrings read GetDeleteSQL write SetDeleteSQL;
property SelectDataSet: TDataSet read FSelectDataset write FSelectDataSet;
property KeyFields: String read FKeyFields write FKeyFields;
property NameField: String read FNameField write FNameField;
property RefreshAction: TAction read FRefreshAction write SetRefreshAction;
property DeleteAction: TAction read FDeleteAction write SetDeleteAction;
property Database: TpFIBDatabase read FDatabase write SetDatabase;
property AddFormClass: String read FAddFormClass write FAddFormClass;
property AddAction: TAction read FAddAction write SetAddAction;
property ModifyAction: TAction read FModifyAction write SetModifyAction;
property InfoAction: TAction read FInfoAction write SetInfoAction;
property CloneAction: TAction read FCloneAction write SetCloneAction;
property OnShowForm: TqFFormShowEvent read FOnShowForm write FOnShowForm;
property AfterPrepare: TqFFormShowEvent read FAfterPrepare write FAfterPrepare;
property BeforePrepare: TqFFormShowEvent read FBeforePrepare write FBeforePrepare;
property AfterRefresh: TqFAfterRefreshEvent read FAfterRefresh write FAfterRefresh;
property OnRefresh: TNotifyEvent read FOnRefresh write FOnRefresh;
property OnGetKeys: TqFGetKeysEvent read FOnGetKeys write FOnGetKeys;
property AfterDelete: TNotifyEvent read FAfterDelete write FAfterDelete;
property CanEdit: TqFCanPrepare read FCanEdit write FCanEdit;
property CanDelete: TqFCanPrepare read FCanDelete write FCanDelete;
property BeforeDelete: TqFDatabaseEvent read FBeforeDelete write FBeforeDelete;
property YesFocusOnDelete: Boolean read FYesFocusOnDelete write FYesFocusOnDelete default True;
end;
procedure Register;
{$R *.res}
implementation
uses qFTools, qFStrings, Variants;
procedure TqFActionControl.ActionInfo(Sender: TObject);
begin
ShowEditForm(fmInfo);
end;
procedure TqFActionControl.ActionClone(Sender: TObject);
begin
ShowEditForm(fmClone);
end;
procedure TqFActionControl.ActionModify(Sender: TObject);
begin
ShowEditForm(fmModify);
end;
procedure TqFActionControl.ActionAdd(Sender: TObject);
begin
ShowEditForm(fmAdd);
end;
// показать форму для редактирования
procedure TqFActionControl.ShowEditForm(Mode: TFormMode);
var
form: TForm;
fclass: TPersistentClass;
FormControl: TqFFormControl;
i: Integer;
res: Boolean;
canEdit: Boolean;
begin
if ( Mode <> fmInfo ) and Assigned(FCanEdit) then
begin
FCanEdit(Self, Mode, canEdit);
if not canEdit then Exit;
end;
Self.LastMode := Mode;
// если в списке ничего нет, то и показывать нечего
// если нет привязанного датасета, не бузить!
if ( Mode <> fmAdd ) and
( (FSelectDataset <> nil ) and FSelectDataset.IsEmpty ) then
begin
qFErrorDialog(qFEmpty);
Exit;
end;
// создать форму по имени класса
form := nil;
try
fclass := GetClass(FAddFormClass);
if fclass <> nil then
Application.CreateForm(TFormClass(fclass),form);
except
end;
// проверить, создалась она или нет
if form = nil then
begin
qFErrorDialog(qFCantCreateForm);
Exit;
end;
// получить ключ, по которому отбирать данные
if Mode <> fmAdd then GetKeyValues;
// если получить ключ не удалось, а он нужен - сказать и закрыться
if ( Mode <> fmAdd ) and VarIsNull(FKeyValues) then
begin
qFErrorDialog(qFEmpty);
form.Free;
Exit;
end;
// найти управляющий элемент формы
FormControl := nil;
for i:=0 to form.ComponentCount-1 do
if form.Components[i] is TqFFormControl then
begin
FormControl := form.Components[i] as TqFFormControl;
break;
end;
if Assigned(FBeforePrepare) then FBeforePrepare(Self, form);
// подготовить форму
if FormControl <> nil then
begin
res := FormControl.Prepare(FDatabase, Mode, FKeyValues, AddKeys);
if not res then
begin
form.Free;
Exit;
end;
end;
// запустить дополнительные обработчики, если есть
if Assigned(FAfterPrepare) then FAfterPrepare(Self, form);
if Assigned(FOnShowForm) then FOnShowForm(Self, form);
// показать
if form.ShowModal = mrOk then
begin
// получить, какую запись добавили
if ( ( Mode = fmAdd ) or ( Mode = fmClone) ) and ( FormControl <> nil )
then FKeyValues := FormControl.LastId;
// обновить список
if Mode <> fmInfo then
if Assigned(FOnRefresh) then
FOnRefresh(Self)
else StdRefresh;
end;
form.Free;
end;
procedure TqFActionControl.GetKeyValues;
begin
FKeyValues := Null;
if Assigned(FOnGetKeys) then FOnGetKeys(Self, FKeyValues)
else
if (FSelectDataSet <> nil ) and not FSelectDataSet.IsEmpty then
FKeyValues := FSelectDataSet[FKeyFields];
end;
procedure TqFActionControl.DeleteQuery(Sender: TObject);
var
canDelete: Boolean;
confirmString: String;
begin
if Assigned(FCanDelete) then
begin
FCanDelete(Self, fmDelete , canDelete);
if not canDelete then Exit;
end;
if FDatabase = nil then
begin
qFErrorDialog(qFNoDatabase);
Exit;
end;
if ( FNameField <> '' ) and ( FSelectDataset <> nil ) then
confirmString := qFConfirmDeleteMsg + #13#10'(' + FSelectDataset[FNameField] + ')'
else confirmString := qFConfirmDeleteMsg;
if qFConfirmEx(confirmString, FYesFocusOnDelete) then
Delete(Sender);
end;
procedure TqFActionControl.SetInfoAction(Action: TAction);
begin
FInfoAction := Action;
FInfoAction.OnExecute := ActionInfo;
end;
procedure TqFActionControl.SetModifyAction(Action: TAction);
begin
FModifyAction := Action;
FModifyAction.OnExecute := ActionModify;
end;
procedure TqFActionControl.SetAddAction(Action: TAction);
begin
FAddAction := Action;
FAddAction.OnExecute := ActionAdd;
end;
procedure TqFActionControl.SetCloneAction(Action: TAction);
begin
FCloneAction := Action;
FCloneAction.OnExecute := ActionClone;
end;
procedure TqFActionControl.SetDeleteAction(Action: TAction);
begin
FDeleteAction := Action;
FDeleteAction.OnExecute := DeleteQuery;
end;
procedure TqFActionControl.SetRefreshAction(Action: TAction);
begin
FRefreshAction := Action;
FRefreshAction.OnExecute := ActionRefresh;
end;
procedure TqFActionControl.Delete(Sender: TObject);
var
origSQL, newSQL: String;
begin
GetKeyValues;
if VarIsNull(FKeyValues) then
begin
qFErrorDialog(qFGetErrorMsg);
Exit;
end;
try
FDeleteQuery.Transaction.StartTransaction;
if Assigned(FBeforeDelete) then
FBeforeDelete(Self, nil, fmDelete, FDeleteQuery.Transaction);
// заменить значения ключа в запросе на удаление
origSQL := FDeleteQuery.SQL.Text;
newSQL := StringReplace(origSQL, ':where',
qFVariantToString(FKeyValues), [rfReplaceAll]);
// заменить дополнительные параметры
if qFNotEmpty(AddKeys) then
newSQL := StringReplace(newSQL, ':add', qFVariantToString(AddKeys),
[rfReplaceAll]);
// заменить идентификатор пользоваля
newSQL := StringReplace(newSQL, ':Acc_Id_User',
IntToStr(Acc_Id_User), [rfReplaceAll]);
FDeleteQuery.SQL.Text := newSQL;
// выхватить предыдущую запись
if ( FSelectDataSet <> nil ) and not FSelectDataSet.Bof then
FSelectDataSet.Prior;
if Assigned(FAfterDelete) then FAfterDelete(Self);
GetKeyValues;
FDeleteQuery.ExecQuery;
FDeleteQuery.SQL.Text := origSQL;
FDeleteQuery.Transaction.Commit;
Refresh;
except on e: Exception do
begin
FDeleteQuery.Transaction.Rollback;
FDeleteQuery.SQL.Text := origSQL;
// проверить, не блокировка ли это
if ( e is EFIBInterbaseError ) and
( (e as EFIBInterbaseError).IBErrorCode = 335544345 ) then
qFErrorDialog(qFLockErrorMsg)
else qFErrorDialog(qFErrorMsg + ': ' + e.Message + '!');
end;
end
end;
procedure TqFActionControl.ActionRefresh(Sender: TObject);
begin
Refresh;
end;
procedure TqFActionControl.Refresh;
begin
if Assigned(FOnRefresh) then
FOnRefresh(Self)
else
begin
GetKeyValues;
StdRefresh;
end;
end;
procedure TqFActionControl.StdRefresh;
begin
// if FDatabase = nil then Exit;
if FSelectDataset <> nil then
begin
FSelectDataset.Close;
FSelectDataset.Open;
FSelectDataset.Locate(FKeyFields, FKeyValues, []);
end;
if Assigned(FAfterRefresh) then FAfterRefresh(Self, FKeyValues);
end;
procedure TqFActionControl.SetDeleteSQL(SQL: TStrings);
begin
FDeleteQuery.SQL := SQL;
end;
function TqFActionControl.GetDeleteSQL: TStrings;
begin
Result := FDeleteQuery.SQL;
end;
procedure TqFActionControl.SetDatabase(DB: TpFIBDatabase);
begin
FDatabase := DB;
FWriteTransaction.DefaultDatabase := DB;
with FWriteTransaction.TRParams do
begin
Add('read_committed');
Add('rec_version');
Add('nowait');
end;
FDeleteQuery.Transaction := FWriteTransaction;
FDeleteQuery.Database := FWriteTransaction.DefaultDatabase;
end;
procedure TqFActionControl.FreeDBObjects;
begin
FDeleteQuery.Free;
FWriteTransaction.Free;
end;
destructor TqFActionControl.Destroy;
begin
FreeDBObjects;
inherited Destroy;
end;
constructor TqFActionControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FWriteTransaction := TpFIBTransaction.Create(nil);
FDeleteQuery := TpFIBQuery.Create(nil);
FYesFocusOnDelete := True;
end;
procedure Register;
begin
RegisterComponents('qFControls', [TqFActionControl]);
end;
end.
|
unit TextToolUnit;
interface
uses
System.SysUtils,
System.UITypes,
System.Classes,
System.Math,
Winapi.Windows,
Vcl.Graphics,
Vcl.StdCtrls,
Vcl.Controls,
Vcl.Forms,
Vcl.ExtCtrls,
Vcl.Buttons,
Vcl.Dialogs,
Vcl.Samples.Spin,
Effects,
CustomSelectTool,
Dmitry.Graphics.Types,
uDBGraphicTypes,
uMemory,
uSettings;
type
TextToolClass = Class(TCustomSelectToolClass)
private
{ Private declarations }
TextMemoLabel: TStaticText;
TextMemo: TMemo;
FontNameLabel: TStaticText;
FontNameEdit: TComboBox;
FontSizeLabel: TStaticText;
FontSizeEdit: TComboBox;
FontColorEdit: TShape;
FontColorEditDialog: TColorDialog;
FontColorLabel: TStaticText;
RotateTextChooser: TRadioGroup;
LeftOrientationButton: TSpeedButton;
CenterOrientationButton: TSpeedButton;
RightOrientationButton: TSpeedButton;
OrientationLabel: TStaticText;
EnableOutline: TCheckBox;
OutLineSizeLabel: TStaticText;
OutLineSizeEdit: TSpinEdit;
OutLineColorLabel: TStaticText;
OutLineColorEdit: TShape;
Loading: Boolean;
protected
function LangID: string; override;
public
{ Public declarations }
class function ID: string; override;
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure DoEffect(Bitmap : TBitmap; aRect : TRect; FullImage : Boolean); override;
procedure DoBorder(Bitmap : TBitmap; aRect : TRect); override;
procedure OnTextChanged(Sender : TObject);
procedure ColorClick(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure OutLineColorClick(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure DoSaveSettings(Sender : TObject); override;
procedure EnableOutlineClick(Sender : TObject);
Procedure SetProperties(Properties : String); override;
Procedure ExecuteProperties(Properties : String; OnDone : TNotifyEvent); override;
end;
implementation
{ TextToolClass }
{$R TextToolRes.res}
procedure TextToolClass.ColorClick(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
FontColorEditDialog.Color := FontColorEdit.Brush.Color;
if FontColorEditDialog.Execute then
begin
FontColorEdit.Brush.Color := FontColorEditDialog.Color;
OnTextChanged(Sender);
end;
end;
constructor TextToolClass.Create(AOwner: TComponent);
const
MaxSizes = 21;
Sizes: array [1 .. MaxSizes] of Integer = (8, 10, 12, 14, 16, 18, 20, 24, 28, 32, 45, 50, 60, 70, 80, 100, 120, 150,
200, 400, 600);
var
I: Integer;
Bit: TBitmap;
begin
inherited;
AnyRect := True;
Loading := True;
CloseLink.Hide;
MakeItLink.Hide;
SaveSettingsLink.Hide;
TextMemoLabel := TStaticText.Create(AOwner);
TextMemoLabel.Top := EditWidth.Top + EditWidth.Height + 5;
TextMemoLabel.Left := 8;
TextMemoLabel.Caption := L('Text') + ':';
TextMemoLabel.Parent := AOwner as TWinControl;
TextMemo := TMemo.Create(AOwner);
TextMemo.Top := TextMemoLabel.Top + TextMemoLabel.Height + 2;
TextMemo.Left := 8;
TextMemo.Width := 160;
TextMemo.Height := 40;
TextMemo.ScrollBars := SsVertical;
TextMemo.OnChange := OnTextChanged;
TextMemo.Parent := AOwner as TWinControl;
if AppSettings.ReadString('Editor', 'TextToolText') <> '' then
TextMemo.Text := AppSettings.ReadString('Editor', 'TextToolText')
else
TextMemo.Text := L('My text');
FontNameLabel := TStaticText.Create(AOwner);
FontNameLabel.Top := TextMemo.Top + TextMemo.Height + 5;
FontNameLabel.Left := 8;
FontNameLabel.Caption := L('Font name') + ':';
FontNameLabel.Parent := AOwner as TWinControl;
FontNameEdit := TComboBox.Create(AOwner);
FontNameEdit.Top := FontNameLabel.Top + FontNameLabel.Height + 2;
FontNameEdit.Left := 8;
FontNameEdit.OnChange := OnTextChanged;
FontNameEdit.Parent := AOwner as TWinControl;
FontNameEdit.Items := Screen.Fonts;
if AppSettings.ReadString('Editor', 'TextToolFontName') <> '' then
FontNameEdit.Text := AppSettings.ReadString('Editor', 'TextToolFontName')
else
FontNameEdit.Text := 'Times New Roman';
FontSizeLabel := TStaticText.Create(AOwner);
FontSizeLabel.Top := FontNameEdit.Top + FontNameEdit.Height + 3;
FontSizeLabel.Left := 8;
FontSizeLabel.Caption := L('Font size');
FontSizeLabel.Parent := AOwner as TWinControl;
FontSizeEdit := TComboBox.Create(AOwner);
FontSizeEdit.Top := FontSizeLabel.Top + FontSizeLabel.Height + 2;
FontSizeEdit.Left := 8;
FontSizeEdit.OnChange := OnTextChanged;
FontSizeEdit.Parent := AOwner as TWinControl;
FontSizeEdit.Items.Clear;
FontSizeEdit.Width := 45;
for I := 1 to MaxSizes do
FontSizeEdit.Items.Add(IntToStr(Sizes[I]));
if AppSettings.ReadInteger('Editor', 'TextToolFontSize', 0) <> 0 then
FontSizeEdit.Text := IntToStr(AppSettings.ReadInteger('Editor', 'TextToolFontSize', 0))
else
FontSizeEdit.Text := '12';
FontColorEdit := TShape.Create(Self);
FontColorEdit.Parent := Self as TWinControl;
FontColorEdit.Top := FontSizeLabel.Top + FontSizeLabel.Height + 2;
FontColorEdit.Left := FontSizeEdit.Left + FontSizeEdit.Width + 10;
FontColorEdit.Width := 16;
FontColorEdit.Height := 16;
FontColorEdit.OnMouseDown := ColorClick;
FontColorEdit.Pen.Color := 0;
if AppSettings.ReadInteger('Editor', 'TextToolFontColor', -1) <> -1 then
FontColorEdit.Brush.Color := AppSettings.ReadInteger('Editor', 'TextToolFontColor', 0)
else
FontColorEdit.Brush.Color := 0;
FontColorEditDialog := TColorDialog.Create(AOwner);
FontColorLabel := TStaticText.Create(AOwner);
FontColorLabel.Top := FontSizeLabel.Top + FontSizeLabel.Height + 3;
FontColorLabel.Left := FontColorEdit.Left + FontColorEdit.Width + 5;
FontColorLabel.Caption := L('Font color');
FontColorLabel.Parent := AOwner as TWinControl;
RotateTextChooser := TRadioGroup.Create(AOwner);
RotateTextChooser.Caption := L('Text rotation');
RotateTextChooser.Left := 8;
RotateTextChooser.Width := 160;
RotateTextChooser.Height := 80;
RotateTextChooser.Top := FontColorLabel.Top + FontColorLabel.Height + 5;
RotateTextChooser.Parent := AOwner as TWinControl;
RotateTextChooser.OnClick := OnTextChanged;
RotateTextChooser.Items.Clear;
RotateTextChooser.Items.Add(L('Normal'));
RotateTextChooser.Items.Add(L('90°'));
RotateTextChooser.Items.Add(L('180°'));
RotateTextChooser.Items.Add(L('270°'));
RotateTextChooser.ItemIndex := AppSettings.ReadInteger('Editor', 'TextToolFontRotation', 0);
OrientationLabel := TStaticText.Create(AOwner);
OrientationLabel.Top := RotateTextChooser.Top + RotateTextChooser.Height + 3;
OrientationLabel.Left := 8;
OrientationLabel.Caption := L('Text orientation');
OrientationLabel.Parent := AOwner as TWinControl;
LeftOrientationButton := TSpeedButton.Create(AOwner);
LeftOrientationButton.Width := 20;
LeftOrientationButton.Height := 20;
LeftOrientationButton.Left := 8;
LeftOrientationButton.GroupIndex := 1;
LeftOrientationButton.Top := OrientationLabel.Top + OrientationLabel.Height + 2;
LeftOrientationButton.OnClick := OnTextChanged;
LeftOrientationButton.Parent := Self;
Bit := TBitmap.Create;
try
Bit.Handle := LoadBitmap(HInstance, 'LEFTTEXT');
LeftOrientationButton.Glyph := Bit;
finally
F(Bit);
end;
CenterOrientationButton := TSpeedButton.Create(AOwner);
CenterOrientationButton.Width := 20;
CenterOrientationButton.Height := 20;
CenterOrientationButton.Left := LeftOrientationButton.Left + LeftOrientationButton.Width + 2;
CenterOrientationButton.GroupIndex := 1;
CenterOrientationButton.Top := OrientationLabel.Top + OrientationLabel.Height + 2;
CenterOrientationButton.OnClick := OnTextChanged;
CenterOrientationButton.Parent := Self;
Bit := TBitmap.Create;
try
Bit.Handle := LoadBitmap(HInstance, 'CENTERTEXT');
CenterOrientationButton.Glyph := Bit;
finally
F(Bit);
end;
RightOrientationButton := TSpeedButton.Create(AOwner);
RightOrientationButton.Width := 20;
RightOrientationButton.Height := 20;
RightOrientationButton.Left := CenterOrientationButton.Left + CenterOrientationButton.Width + 2;
RightOrientationButton.GroupIndex := 1;
RightOrientationButton.Top := OrientationLabel.Top + OrientationLabel.Height + 2;
RightOrientationButton.OnClick := OnTextChanged;
RightOrientationButton.Parent := Self;
Bit := TBitmap.Create;
try
Bit.Handle := LoadBitmap(HInstance, 'RIGHTTEXT');
RightOrientationButton.Glyph := Bit;
finally
F(Bit);
end;
case AppSettings.ReadInteger('Editor', 'TextToolFontOrientation', 1) of
1:
LeftOrientationButton.Down := True;
2:
CenterOrientationButton.Down := True;
3:
RightOrientationButton.Down := True;
else
LeftOrientationButton.Down := True;
end;
EnableOutline := TCheckBox.Create(AOwner);
EnableOutline.Top := RightOrientationButton.Top + RightOrientationButton.Height + 3;
EnableOutline.Left := 8;
EnableOutline.Width := 160;
EnableOutline.Caption := L('Use outline color');
EnableOutline.OnClick := EnableOutlineClick;
EnableOutline.Checked := AppSettings.ReadBool('Editor', 'TextToolEnableOutLine', False);
EnableOutline.Parent := Self;
OutLineSizeLabel := TStaticText.Create(AOwner);
OutLineSizeLabel.Top := EnableOutline.Top + EnableOutline.Height + 3;
OutLineSizeLabel.Left := 8;
OutLineSizeLabel.Caption := L('Size') + ':';
OutLineSizeLabel.Parent := Self;
OutLineSizeEdit := TSpinEdit.Create(AOwner);
OutLineSizeEdit.Top := OutLineSizeLabel.Top + OutLineSizeLabel.Height + 3;
OutLineSizeEdit.Left := 8;
OutLineSizeEdit.Width := 50;
OutLineSizeEdit.MinValue := 1;
OutLineSizeEdit.MaxValue := 100;
OutLineSizeEdit.Value := AppSettings.ReadInteger('Editor', 'TextToolOutLineSize', 5);
OutLineSizeEdit.OnChange := OnTextChanged;
OutLineSizeEdit.Parent := Self;
OutLineSizeEdit.Enabled := EnableOutline.Checked;
OutLineColorLabel := TStaticText.Create(AOwner);
OutLineColorLabel.Left := OutLineSizeEdit.Left + OutLineSizeEdit.Width + 15;
OutLineColorLabel.Top := EnableOutline.Top + EnableOutline.Height + 3;
OutLineColorLabel.Caption := L('Color') + ':';
OutLineColorLabel.Parent := Self;
OutLineColorEdit := TShape.Create(AOwner);
OutLineColorEdit.Top := OutLineSizeLabel.Top + OutLineSizeLabel.Height + 5;
OutLineColorEdit.Left := OutLineSizeEdit.Left + OutLineSizeEdit.Width + 15;
OutLineColorEdit.Width := 15;
OutLineColorEdit.Height := 15;
OutLineColorEdit.Brush.Color := AppSettings.ReadInteger('Editor', 'TextToolOutLineColor', OutLineColorEdit.Brush.Color);
OutLineColorEdit.OnMouseDown := OutLineColorClick;
OutLineColorEdit.Parent := Self;
SaveSettingsLink.Top := OutLineSizeEdit.Top + OutLineSizeEdit.Height + 10;
MakeItLink.Top := SaveSettingsLink.Top + SaveSettingsLink.Height + 5;
CloseLink.Top := MakeItLink.Top + MakeItLink.Height + 5;
CloseLink.Show;
MakeItLink.Show;
SaveSettingsLink.Show;
Loading := False;
end;
destructor TextToolClass.Destroy;
begin
F(TextMemo);
F(TextMemoLabel);
F(FontNameLabel);
F(FontNameEdit);
F(FontSizeLabel);
F(FontSizeEdit);
F(FontColorEdit);
F(FontColorEditDialog);
F(FontColorLabel);
F(RotateTextChooser);
F(OrientationLabel);
F(LeftOrientationButton);
F(CenterOrientationButton);
F(RightOrientationButton);
F(EnableOutline);
F(OutLineSizeLabel);
F(OutLineSizeEdit);
F(OutLineColorLabel);
F(OutLineColorEdit);
inherited;
end;
procedure TextToolClass.DoBorder(Bitmap: TBitmap; aRect: TRect);
var
Xdp: TArPARGB;
Rct: TRect;
I, J: Integer;
procedure Border(I, J: Integer; var RGB: TRGB);
begin
if Odd((I + J) div 3) then
begin
RGB.R := RGB.R div 5;
RGB.G := RGB.G div 5;
RGB.B := RGB.B div 5;
end else
begin
RGB.R := RGB.R xor $FF;
RGB.G := RGB.G xor $FF;
RGB.B := RGB.B xor $FF;
end;
end;
begin
Rct.Top := Min(ARect.Top, ARect.Bottom);
Rct.Bottom := Max(ARect.Top, ARect.Bottom);
Rct.Left := Min(ARect.Left, ARect.Right);
Rct.Right := Max(ARect.Left, ARect.Right);
ARect := Rct;
SetLength(Xdp, Bitmap.Height);
for I := 0 to Bitmap.Height - 1 do
Xdp[I] := Bitmap.ScanLine[I];
I := Min(Bitmap.Height - 1, Max(0, ARect.Top));
if I = ARect.Top then
for J := 0 to Bitmap.Width - 1 do
begin
if (J > ARect.Left) and (J < ARect.Right) then
Border(I, J, Xdp[I, J]);
end;
I := Min(Bitmap.Height - 1, Max(0, ARect.Bottom));
if I = ARect.Bottom then
for J := 0 to Bitmap.Width - 1 do
begin
if (J > ARect.Left) and (J < ARect.Right) then
Border(I, J, Xdp[I, J]);
end;
for I := Max(0, ARect.Top) to Min(ARect.Bottom - 1, Bitmap.Height - 1) do
begin
J := Max(0, Min(Bitmap.Width - 1, ARect.Left));
if J = ARect.Left then
Border(I, J, Xdp[I, J]);
end;
for I := Max(0, ARect.Top) to Min(ARect.Bottom - 1, Bitmap.Height - 1) do
begin
J := Min(Bitmap.Width - 1, Max(0, ARect.Right));
if J = ARect.Right then
Border(I, J, Xdp[I, J]);
end;
end;
procedure TextToolClass.DoEffect(Bitmap: TBitmap; aRect: TRect; FullImage : Boolean);
var
FontSize: Extended;
Text: string;
Rct: TRect;
IntSize, OutLineSize: Integer;
Options: Cardinal;
begin
Rct.Top := Min(ARect.Top, ARect.Bottom);
Rct.Bottom := Max(ARect.Top, ARect.Bottom);
Rct.Left := Min(ARect.Left, ARect.Right);
Rct.Right := Max(ARect.Left, ARect.Right);
ARect := Rct;
Text := TextMemo.Text;
Bitmap.Canvas.Brush.Style := BsClear;
Bitmap.Canvas.Font.name := FontNameEdit.Text;
Bitmap.Canvas.Font.Color := FontColorEdit.Brush.Color;
IntSize := StrToIntDef(FontSizeEdit.Text, 12);
if not FullImage then
FontSize := (IntSize * GetZoom)
else
FontSize := IntSize;
Bitmap.Canvas.Font.Size := Round(FontSize);
Options := DT_WORDBREAK;
if LeftOrientationButton.Down then
Options := Options + DT_LEFT;
if CenterOrientationButton.Down then
Options := Options + DT_CENTER;
if RightOrientationButton.Down then
Options := Options + DT_RIGHT;
if not EnableOutline.Checked then
begin
case RotateTextChooser.ItemIndex of
0:
DrawText(Bitmap.Canvas.Handle, PChar(Text), Length(Text), ARect, Options);
1:
StrRotated(Arect.Right, Arect.Top, Rect(0, 0, Arect.Bottom - Arect.Top, Arect.Right - Arect.Left),
Bitmap.Canvas.Handle, Bitmap.Canvas.Font.Handle, Text, 90, Options);
2:
StrRotated(Arect.Right, Arect.Bottom, Rect(0, 0, Arect.Right - Arect.Left, Arect.Bottom - Arect.Top),
Bitmap.Canvas.Handle, Bitmap.Canvas.Font.Handle, Text, 180, Options);
3:
StrRotated(Arect.Left, Arect.Bottom, Rect(0, 0, Arect.Bottom - Arect.Top, Arect.Right - Arect.Left),
Bitmap.Canvas.Handle, Bitmap.Canvas.Font.Handle, Text, 270, Options);
end;
end else
begin
if not FullImage then
OutLineSize := Min(100, Max(1, Round(OutLineSizeEdit.Value * GetZoom)))
else
OutLineSize := OutLineSizeEdit.Value;
case RotateTextChooser.ItemIndex of
0:
CoolDrawTextEx(Bitmap, PChar(Text), Bitmap.Canvas.Font.Handle, OutLineSize, OutLineColorEdit.Brush.Color,
ARect, 0, Options);
1:
CoolDrawTextEx(Bitmap, PChar(Text), Bitmap.Canvas.Font.Handle, OutLineSize, OutLineColorEdit.Brush.Color,
ARect, 1, Options);
2:
CoolDrawTextEx(Bitmap, PChar(Text), Bitmap.Canvas.Font.Handle, OutLineSize, OutLineColorEdit.Brush.Color,
ARect, 2, Options);
3:
CoolDrawTextEx(Bitmap, PChar(Text), Bitmap.Canvas.Font.Handle, OutLineSize, OutLineColorEdit.Brush.Color,
ARect, 3, Options);
end;
end;
end;
procedure TextToolClass.DoSaveSettings(Sender: TObject);
begin
AppSettings.WriteString('Editor', 'TextToolText', TextMemo.Text);
AppSettings.WriteString('Editor', 'TextToolFontName', FontNameEdit.Text);
AppSettings.WriteInteger('Editor', 'TextToolFontSize', StrToIntDef(FontSizeEdit.Text, 12));
AppSettings.WriteInteger('Editor', 'TextToolFontColor', FontColorEdit.Brush.Color);
AppSettings.WriteInteger('Editor', 'TextToolFontRotation', RotateTextChooser.ItemIndex);
if LeftOrientationButton.Down then
AppSettings.WriteInteger('Editor', 'TextToolFontOrientation', 1);
if CenterOrientationButton.Down then
AppSettings.WriteInteger('Editor', 'TextToolFontOrientation', 2);
if RightOrientationButton.Down then
AppSettings.WriteInteger('Editor', 'TextToolFontOrientation', 3);
AppSettings.WriteBool('Editor', 'TextToolEnableOutLine', EnableOutline.Checked);
AppSettings.WriteInteger('Editor', 'TextToolOutLineColor', OutLineColorEdit.Brush.Color);
AppSettings.WriteInteger('Editor', 'TextToolOutLineSize', OutLineSizeEdit.Value);
end;
procedure TextToolClass.EnableOutlineClick(Sender: TObject);
begin
if Loading then
Exit;
OutLineSizeEdit.Enabled := EnableOutline.Checked;
OnTextChanged(Sender);
end;
procedure TextToolClass.ExecuteProperties(Properties: string; OnDone: TNotifyEvent);
begin
end;
class function TextToolClass.ID: string;
begin
Result := '{E52516CC-8235-4A1D-A135-6D84A2E298E9}';
end;
function TextToolClass.LangID: string;
begin
Result := 'TextTool';
end;
procedure TextToolClass.OnTextChanged(Sender: TObject);
begin
if Assigned(FProcRecteateImage) then
FProcRecteateImage(Self);
end;
procedure TextToolClass.OutLineColorClick(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if not EnableOutline.Checked then
Exit;
FontColorEditDialog.Color := OutLineColorEdit.Brush.Color;
if FontColorEditDialog.Execute then
begin
OutLineColorEdit.Brush.Color := FontColorEditDialog.Color;
OnTextChanged(Sender);
end;
end;
procedure TextToolClass.SetProperties(Properties: string);
begin
end;
end.
|
unit CFSafeEdit;
interface
uses
Windows, Classes, Controls, CFControl, Graphics, Messages;
type
TScrollAlign = (csaLeft, csaRight);
TCFSafeEdit = class(TCFCustomControl)
private
FTopPadding, // 上偏移多少开始显示文本
FLeftPadding, // 左偏移多少开始显示文本
FRightPadding, // 右偏移多少停止显示文本
FMaxLength // 最大长度
: Byte;
FDrawLeftOffs, FTextWidth: Integer; // 绘制时左偏移,文本内容宽度
FSafeChar: Char;
FSafeText: string;
FSelStart: Integer; // 选择发生在第几个后面 >0 有效
FReadOnly: Boolean;
FShowKeyBoard: Boolean;
FBtnMouseState: TMouseState;
FOnChange: TNotifyEvent;
FOnKeyDown: TKeyEvent;
/// <summary>
/// 根据位置在第几个字符后面(>0有效)
/// </summary>
/// <param name="AX">位置</param>
/// <returns>在第几个字符后面</returns>
function GetOffsetBeforAt(const AX: Integer): Integer;
procedure ScrollTo(const AOffset: Integer; const AAlign: TScrollAlign);
procedure MoveCaretAfter(const AOffset: Integer);
procedure RightKeyPress;
procedure LeftKeyPress;
//
procedure SetReadOnly(Value: Boolean);
procedure SetShowKeyBord(Value: Boolean);
procedure AdjustBounds;
/// <summary> 绘制到画布 </summary>
procedure DrawControl(ACanvas: TCanvas); override;
//
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;
//
// 通过Tab移出焦点
procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
procedure CMMouseEnter(var Msg: TMessage ); message CM_MOUSEENTER;
procedure CMMouseLeave(var Msg: TMessage ); message CM_MOUSELEAVE;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS;
procedure KeyPress(var Key: Char); override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
public
constructor Create(AOwner: TComponent); override;
procedure SetFocus; override;
procedure Clear;
function TextLength: Integer;
//
property RightPadding: Byte read FRightPadding write FRightPadding;
property LeftPadding: Byte read FLeftPadding write FLeftPadding;
property SafeText: string read FSafeText;
published
property ReadOnly: Boolean read FReadOnly write SetReadOnly default False;
//
property MaxLength: Byte read FMaxLength write FMaxLength;
property ShowKeyBoard: Boolean read FShowKeyBoard write SetShowKeyBord;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property OnKeyDown: TKeyEvent read FOnKeyDown write FOnKeyDown;
property Font;
end;
implementation
{$R CFSafeEdit.RES}
uses
SysUtils;
{ TCSafeEdit }
procedure TCFSafeEdit.ScrollTo(const AOffset: Integer; const AAlign: TScrollAlign);
var
vS: string;
vW, vDecW: Integer;
begin
vS := Copy(Text, 1, AOffset);
//vW := Canvas.TextWidth(vS);
vW := Canvas.TextWidth(vS);
if AAlign = csaRight then // 向左滚动到AOffset恰好显示
begin
vDecW := FDrawLeftOffs + FLeftPadding + vW - (Width - FRightPadding);
if vDecW > 0 then // 超过宽度
begin
FDrawLeftOffs := FDrawLeftOffs - vDecW;
UpdateDirectUI;
end
else
if vDecW < 0 then // 没有超过宽度
begin
if FDrawLeftOffs < 0 then // 左侧有没显示出来的
begin
FDrawLeftOffs := FDrawLeftOffs - vDecW;
if FDrawLeftOffs > 0 then
FDrawLeftOffs := 0;
UpdateDirectUI;
end;
end;
end
else
begin
vDecW := FDrawLeftOffs + vW;
if vDecW < 0 then
begin
FDrawLeftOffs := FDrawLeftOffs - vDecW;
UpdateDirectUI;
end;
end;
end;
procedure TCFSafeEdit.Clear;
begin
FSafeText := '';
Text := '';
if Self.Focused then
begin
FSelStart := 0;
MoveCaretAfter(FSelStart);
end;
UpdateDirectUI;
end;
procedure TCFSafeEdit.CMFontChanged(var Message: TMessage);
begin
inherited;
AdjustBounds;
end;
procedure TCFSafeEdit.CMMouseEnter(var Msg: TMessage);
begin
inherited;
UpdateDirectUI;
end;
procedure TCFSafeEdit.CMMouseLeave(var Msg: TMessage);
begin
inherited;
FBtnMouseState := FBtnMouseState - [cmsMouseIn];
UpdateDirectUI;
end;
procedure TCFSafeEdit.CMTextChanged(var Message: TMessage);
begin
inherited;
UpdateDirectUI;
end;
constructor TCFSafeEdit.Create(AOwner: TComponent);
begin
inherited;
FTopPadding := 2;
FLeftPadding := 2;
FRightPadding := 2;
FDrawLeftOffs := 0;
FSelStart := -1;
FMaxLength := 8;
FSafeChar := Char($25CF);
Text := ''; // 处理win32自带属性默认值
FSafeText := '';
FShowKeyBoard := True;
FBtnMouseState := [];
Width := 120;
Height := 20;
Self.Cursor := crIBeam;
end;
procedure TCFSafeEdit.DrawControl(ACanvas: TCanvas);
var //绘制半透明需要的变量
vRect: TRect;
vS: string;
vLeft, vRight: Integer;
//vRgn: HRGN;
vBmp: TBitmap;
//vIcon: HICON;
begin
inherited DrawControl(ACanvas);
// 外观矩形
vRect := Rect(0, 0, Width, Height);
ACanvas.Brush.Style := bsSolid;
if not FReadOnly then
ACanvas.Brush.Color := GBackColor
else
ACanvas.Brush.Color := clInfoBk;
if Self.Focused or (cmsMouseIn in MouseState) then
ACanvas.Pen.Color := GBorderHotColor
else
ACanvas.Pen.Color := GBorderColor;
if BorderVisible then
ACanvas.Pen.Style := psSolid
else
ACanvas.Pen.Style := psClear;
//ACanvas.RoundRect(vRect, GRoundSize, GRoundSize);
ACanvas.Rectangle(vRect);
// 设置可绘制区域
InflateRect(vRect, 0, -FTopPadding);
vRect.Left := vRect.Left + FLeftPadding;
vRect.Right := vRect.Right - FRightPadding;
//vRgn := CreateRectRgnIndirect(vRect);
if FShowKeyBoard then
begin
vBmp := TBitmap.Create;
try
vBmp.Transparent := True;
if cmsMouseIn in FBtnMouseState then
vBmp.LoadFromResourceName(HInstance, 'KEYBOARDHOT')
else
vBmp.LoadFromResourceName(HInstance, 'KEYBOARD');
ACanvas.Draw(vRect.Right, (Height - GIconWidth) div 2, vBmp);
finally
FreeAndNil(vBmp);
end;
end;
//SelectClipRgn(ACanvas.Handle, vRgn); //ExtSelectClipRgn(ACanvas.Handle, vRgn)
IntersectClipRect(ACanvas.Handle, vRect.Left, vRect.Top, vRect.Right, vRect.Bottom);
try
// 绘制文本
if Text <> '' then // 有内容
begin
// 绘制文本
vRect := Bounds(0, 0, FTextWidth, Height);
OffsetRect(vRect, FDrawLeftOffs + FLeftPadding, 0);
vS := Text;
ACanvas.TextRect(vRect, vS, [tfLeft, tfVerticalCenter, tfSingleLine]);
// 绘制字符长度提示
{vS := IntToStr(TextLength);
ACanvas.Font.Size := 8;
vRect.Left := vRect.Right + 2;
vRect.Right := vRect.Left + ACanvas.TextWidth(vS);
vRect.Top := vRect.Top + 4;
ACanvas.Font.Color := clMedGray;
ACanvas.TextRect(vRect, vS, [tfLeft, tfVerticalCenter, tfSingleLine]);}
end;
finally
SelectClipRgn(ACanvas.Handle, 0); // 清除剪切区域
//DeleteObject(vRgn)
end;
end;
procedure TCFSafeEdit.AdjustBounds;
var
vRect: TRect;
begin
//if not (csReading in ComponentState) then
begin
vRect := ClientRect;
Canvas.Font := Font;
vRect.Bottom := vRect.Top + Canvas.TextHeight('荆') + GetSystemMetrics(SM_CYBORDER) * 4;
FTextWidth := Canvas.TextWidth(Text);
SetBounds(Left, Top, vRect.Right, vRect.Bottom);
end;
end;
function TCFSafeEdit.GetOffsetBeforAt(const AX: Integer): Integer;
var
i, vW, vRight: Integer;
begin
Result := -1;
//if (AX < FDrawLeftOffs) or (AX > FTextWidth) then Exit;
if AX < FDrawLeftOffs then
begin
Result := 0;
Exit;
end;
if AX > FTextWidth then
begin
Result := TextLength;
Exit;
end;
//if AX < Canvas.TextWidth(Text) then // 在文本中
if AX < Canvas.TextWidth(Text) then
begin
vRight := 0;
for i := 1 to Length(Text) do
begin
//vW := Canvas.TextWidth(Text[i]);
vW := Canvas.TextWidth(Text[i]);
if vRight + vW > AX then
begin
if vRight + vW div 2 > AX then
Result := i - 1
else
begin
Result := i;
vRight := vRight + vW;
end;
Break;
end
else
vRight := vRight + vW;
end;
end
else // 不在文本中
Result := TextLength;
end;
procedure TCFSafeEdit.KeyDown(var Key: Word; Shift: TShiftState);
{$REGION 'DoBackKey'}
procedure DoBackKey;
var
vS: string;
begin
if (Text <> '') and (FSelStart > 0) then
begin
vS := Text;
Delete(vS, FSelStart, 1);
Delete(FSafeText, FSelStart, 1);
Text := vS;
//FTextWidth := Canvas.TextWidth(Text);
FTextWidth := Canvas.TextWidth(Text);
Dec(FSelStart);
if FSelStart = TextLength then // 在最后面向前删除
begin
if FDrawLeftOffs < 0 then // 前面有没显示出来的
ScrollTo(FSelStart, csaRight);
end;
UpdateDirectUI;
MoveCaretAfter(FSelStart);
end;
end;
{$ENDREGION}
{$REGION 'DoDeleteKey'}
procedure DoDeleteKey;
var
vS: string;
begin
if (Text <> '') and (FSelStart < TextLength) then
begin
vS := Text;
Delete(vS, FSelStart + 1, 1);
Delete(FSafeText, FSelStart + 1, 1);
Text := vS;
//FTextWidth := Canvas.TextWidth(Text);
FTextWidth := Canvas.TextWidth(Text);
if FSelStart = TextLength then // 在最后面向前删除
begin
if FDrawLeftOffs < 0 then // 前面有没显示出来的
begin
ScrollTo(FSelStart, csaRight);
MoveCaretAfter(FSelStart);;
end;
end;
UpdateDirectUI;
end;
end;
{$ENDREGION}
{$REGION 'DoHomeKey'}
procedure DoHomeKey;
begin
FSelStart := 0;
FDrawLeftOffs := 0;
UpdateDirectUI;
MoveCaretAfter(FSelStart);;
end;
{$ENDREGION}
{$REGION 'DoEndKey'}
procedure DoEndKey;
begin
FSelStart := TextLength;
ScrollTo(FSelStart, csaRight);
MoveCaretAfter(FSelStart);;
end;
{$ENDREGION}
begin
inherited;
if FReadOnly then Exit;
case Key of
VK_BACK: DoBackKey;
VK_DELETE: DoDeleteKey;
VK_LEFT: LeftKeyPress;
VK_RIGHT: RightKeyPress;
VK_HOME: DoHomeKey;
VK_END: DoEndKey;
VK_RETURN:
begin
if Assigned(FOnKeyDown) then
FOnKeyDown(Self, Key, Shift);
end;
end;
end;
procedure TCFSafeEdit.KeyPress(var Key: Char);
var
vS: string;
begin
inherited;
if FReadOnly then Exit;
//if Ord(Key) in [VK_BACK, VK_RETURN] then Exit;
if ((Key < #32) or (Key = #127)) and (Ord(Key) <> VK_TAB) then Exit;;
vS := Text;
if Length(vS) >= FMaxLength then Exit;
Insert(FSafeChar, vS, FSelStart + 1);
Insert(Key, FSafeText, FSelStart + 1);
Text := vS;
//FTextWidth := Canvas.TextWidth(Text);
FTextWidth := Canvas.TextWidth(Text);
RightKeyPress;
end;
procedure TCFSafeEdit.LeftKeyPress;
begin
if FSelStart > 0 then
begin
Dec(FSelStart);
ScrollTo(FSelStart, csaLeft);
MoveCaretAfter(FSelStart);;
end;
end;
procedure TCFSafeEdit.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
var
vS: string;
vOffs: Integer;
vSelStart: Integer absolute vOffs;
vReUpdate: Boolean;
vRect: TRect;
begin
inherited;
if FReadOnly then Exit;
// 判断是否点击在按钮区
vRect := Rect(Width - RightPadding, GBorderWidth, Width - GBorderWidth, Height - GBorderWidth);
if PtInRect(vRect, Point(X, Y)) then
begin
FBtnMouseState := FBtnMouseState + [cmsMouseDown];
UpdateDirectUI(vRect);
end;
if (X < FLeftPadding) or (X > Width - FRightPadding) then Exit;
vReUpdate := False;
vSelStart := GetOffsetBeforAt(X - FDrawLeftOffs - FLeftPadding);
if FSelStart <> vSelStart then
begin
FSelStart := vSelStart;
vReUpdate := True;
end;
// 当显示最右侧的字符有半个露出时,滚动到全显示
vS := Copy(Text, 1, FSelStart);
vOffs := Width - FLeftPadding - FRightPadding - //(Canvas.TextWidth(vS) + FDrawLeftOffs);
(Canvas.TextWidth(vS) + FDrawLeftOffs);
if vOffs < 0 then
begin
FDrawLeftOffs := FDrawLeftOffs + vOffs;
vReUpdate := True;
end;
if vReUpdate then
UpdateDirectUI;
MoveCaretAfter(FSelStart);
end;
procedure TCFSafeEdit.MouseMove(Shift: TShiftState; X, Y: Integer);
var
vS: string;
vSelEnd, vW: Integer;
vReUpdate: Boolean;
vRect: TRect;
begin
inherited;
if FReadOnly then Exit;
if ssLeft in Shift then
begin
vReUpdate := False;
if X > Width - FRightPadding then // 鼠标在控件右侧
begin
vW := FTextWidth - (Width - FLeftPadding - FRightPadding);
if FDrawLeftOffs + vW > 0 then // 右侧内容未显示完全
begin
Dec(FDrawLeftOffs, 5);
if FDrawLeftOffs < -vW then
FDrawLeftOffs := -vW;
vReUpdate := True;
end;
vSelEnd := GetOffsetBeforAt(Width - FDrawLeftOffs + FLeftPadding - FRightPadding);
vS := Copy(Text, 1, vSelEnd);
//if Canvas.TextWidth(vS)
if Canvas.TextWidth(vS) + FDrawLeftOffs > Width - FLeftPadding - FRightPadding then
Dec(vSelEnd);
end
else
if X < FLeftPadding then
begin
if FDrawLeftOffs < 0 then // 左侧内容未显示完全
begin
Inc(FDrawLeftOffs, 5);
if FDrawLeftOffs > 0 then
FDrawLeftOffs := 0;
vReUpdate := True;
end;
vSelEnd := GetOffsetBeforAt({FLeftPadding - 当字符一半小于FLeftPadding时计算不准确}-FDrawLeftOffs);
vS := Copy(Text, 1, vSelEnd);
//if Canvas.TextWidth(vS) + FDrawLeftOffs < 0 then
if Canvas.TextWidth(vS) + FDrawLeftOffs < 0 then
Inc(vSelEnd);
end
else
begin
vSelEnd := GetOffsetBeforAt(X - FDrawLeftOffs - FLeftPadding);
vS := Copy(Text, 1, vSelEnd);
//if Canvas.TextWidth(vS)
if Canvas.TextWidth(vS) + FDrawLeftOffs + FLeftPadding > Width - FRightPadding then
Dec(vSelEnd);
end;
if vSelEnd < 0 then Exit; // 鼠标不在内容中
if vReUpdate then
UpdateDirectUI;
FSelStart := vSelEnd;
MoveCaretAfter(FSelStart);
end
else
begin
vRect := Rect(Width - RightPadding, GBorderWidth, Width - GBorderWidth, Height - GBorderWidth);
if PtInRect(vRect, Point(X, Y)) then
begin
if not (cmsMouseIn in FBtnMouseState) then
begin
FBtnMouseState := FBtnMouseState + [cmsMouseIn];
UpdateDirectUI(vRect);
end;
end
else
begin
if cmsMouseIn in FBtnMouseState then
begin
FBtnMouseState := FBtnMouseState - [cmsMouseIn];
UpdateDirectUI(vRect);
end;
end;
end;
end;
procedure TCFSafeEdit.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
var
vRect: TRect;
begin
if cmsMouseDown in FBtnMouseState then
begin
FBtnMouseState := FBtnMouseState - [cmsMouseDown];
vRect := Rect(Width - RightPadding, GBorderWidth, Width - GBorderWidth, Height - GBorderWidth);
UpdateDirectUI(vRect);
end
else
inherited;
end;
procedure TCFSafeEdit.MoveCaretAfter(const AOffset: Integer);
var
vS: string;
vCaretLeft, vCaretHeight: Integer;
begin
if AOffset < 0 then Exit;
vCaretHeight := Height - 2 * FTopPadding;
vCaretLeft := FLeftPadding;
if AOffset > 0 then
begin
vS := Copy(Text, 1, AOffset);
vCaretLeft := vCaretLeft + Canvas.TextWidth(vS)
+ FDrawLeftOffs;
end;
DestroyCaret;
CreateCaret(Handle, 0, 1, vCaretHeight);
SetCaretPos(vCaretLeft, FTopPadding);
ShowCaret(Handle);
end;
procedure TCFSafeEdit.RightKeyPress;
begin
if FSelStart < TextLength then
begin
Inc(FSelStart);
ScrollTo(FSelStart, csaRight);
MoveCaretAfter(FSelStart);
end;
end;
procedure TCFSafeEdit.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
inherited SetBounds(ALeft, ATop, AWidth, AHeight);
if FShowKeyBoard then
FRightPadding := GIconWidth + GPadding * 2
else
FRightPadding := GPadding;
end;
procedure TCFSafeEdit.SetFocus;
begin
inherited SetFocus;
FSelStart := TextLength;
MoveCaretAfter(FSelStart);
end;
procedure TCFSafeEdit.SetReadOnly(Value: Boolean);
begin
if FReadOnly <> Value then
begin
FReadOnly := Value;
DestroyCaret;
UpdateDirectUI;
end;
end;
procedure TCFSafeEdit.SetShowKeyBord(Value: Boolean);
begin
if FShowKeyBoard <> Value then
begin
FShowKeyBoard := Value;
if Value then
FRightPadding := GIconWidth + GPadding * 2
else
FRightPadding := GPadding;
end;
end;
function TCFSafeEdit.TextLength: Integer;
begin
Result := Length(Text);
end;
procedure TCFSafeEdit.WMKillFocus(var Message: TWMKillFocus);
begin
inherited;
DestroyCaret;
end;
end.
|
PROGRAM Kleines;
USES
OWindows,OTypes,ODialogs;
{$I KLEINES.I}
TYPE
TMyApplication = OBJECT(TApplication)
PROCEDURE InitInstance; VIRTUAL;
PROCEDURE InitMainWindow; VIRTUAL;
END;
PMyDialog = ^TMyDialog;
TMyDialog = OBJECT(TDialog)
FUNCTION Ok : BOOLEAN; VIRTUAL;
FUNCTION Cancel : BOOLEAN; VIRTUAL;
END;
VAR
MyApplication : TMyApplication;
Buffer : RECORD
Kette : STRING[19];
O1,O2 : INTEGER;
END;
PROCEDURE TMyApplication.InitInstance;
BEGIN
LoadResource('KLEINES.RSC','');
INHERITED InitInstance;
END;
PROCEDURE TMyApplication.InitMainWindow;
VAR
p : PMyDialog;
BEGIN
IF MainWindow = NIL THEN
BEGIN
p := NEW(PMyDialog,Init(NIL,'KLEINES šbungsprogramm',main_dial));
IF MainWindow <> NIL THEN
BEGIN
NEW(PButton,Init(p,md_ok,id_ok,TRUE,'Zeigt Eingaben in einer Alertbox an und beendet das Programm.'));
NEW(PButton,Init(p,md_cancel,id_cancel,TRUE,'Beendet Programm, ohne Daten Anzuzeigen.'));
NEW(PEdit,Init(p,md_edit,20,'Hier kann Text eingegeben werden.'));
NEW(PGroupBox,Init(p,md_option_box,'Optionen','In dieser Box befinden sich zwei RadioButtons'));
NEW(PRadioButton,Init(p,md_option1,TRUE,'Die erste Option'));
NEW(PRadioButton,Init(p,md_option2,TRUE,'Die zweite Option'));
p^.TransferBuffer := @Buffer;
END;
END;
IF MainWindow <> NIL THEN
MainWindow^.MakeWindow;
END;
FUNCTION TMyDialog.Ok : BOOLEAN;
VAR
Valid : BOOLEAN;
Ausgabe : STRING;
BEGIN
Valid := INHERITED Ok;
IF Valid = TRUE THEN
BEGIN
Ausgabe := 'In die Editzeile wurde "'+Buffer.Kette+'" eingegeben. Es wurde der Radiobutton "';
IF Buffer.O1 = bf_checked THEN
Ausgabe := Ausgabe+'1'
ELSE
Ausgabe := Ausgabe+'2';
Ausgabe := Ausgabe+'. Option" ausgew„hlt.';
Application^.Alert(NIL,1,0,Ausgabe,'&Ok');
Application^.Quit;
Ok := TRUE;
END
ELSE
Ok := FALSE;
END;
FUNCTION TMyDialog.Cancel : BOOLEAN;
BEGIN
IF Application^.Alert(NIL,2,2,'Wirklich Beenden?','&Abbruch|&Ok') = 2 THEN
BEGIN
Application^.Quit;
Cancel := TRUE;
END
ELSE
Cancel := FALSE;
END;
BEGIN
MyApplication.Init('Kleines');
MyApplication.Run;
MyApplication.Done;
END. |
unit euroconv;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
ExtCtrls;
type
{ TFConv }
TFConv = class(TForm)
BtnConv: TButton;
BtnRAZ: TButton;
BtnQuit: TButton;
EdEuro: TEdit;
EdDollar: TEdit;
LbEuro: TLabel;
LbDollar: TLabel;
RadioOption: TRadioGroup;
procedure BtnConvClick(Sender: TObject);
procedure BtnQuitClick(Sender: TObject);
procedure BtnRAZClick(Sender: TObject);
procedure EdDollarClick(Sender: TObject);
procedure EdEuroClick(Sender: TObject);
private
public
end;
const taux = 1.1229;
var
FConv: TFConv;
implementation
{$R *.lfm}
{ TFConv }
procedure TFConv.BtnConvClick(Sender: TObject);
begin
if (RadioOption.ItemIndex = 0) then
begin
EdDollar.Text := floattostr(strtofloat(EdEuro.Text)*taux);
end
else
if (RadioOption.ItemIndex = 1) then
begin
EdEuro.Text := floattostr(strtofloat(EdDollar.Text)/taux);
end;
end;
procedure TFConv.BtnQuitClick(Sender: TObject);
begin
if MessageDlg('Question', 'Voulez-vous quitter ?', mtConfirmation,
[mbYes, mbNo, mbIgnore],0) = mrYes
then Close;
end;
procedure TFConv.BtnRAZClick(Sender: TObject);
begin
EdDollar.Text := '0,0';
EdEuro.Text := '0,0';
EdEuro.SelectAll;
end;
procedure TFConv.EdDollarClick(Sender: TObject);
begin
RadioOption.ItemIndex := 1;
end;
procedure TFConv.EdEuroClick(Sender: TObject);
begin
RadioOption.ItemIndex := 0;
end;
end.
|
// MMArchPath unit and MMArchSimple class
// Part of mmarch
// Command line tool to handle Heroes 3 and Might and Magic 6, 7, 8
// resource archive files (e.g. lod files). Based on GrayFace's MMArchive.
// By Tom CHEN <tomchen.org@gmail.com> (tomchen.org)
// MIT License
// https://github.com/might-and-magic/mmarch
unit MMArchPath;
interface
uses
Windows, SysUtils, StrUtils, Classes, RSQ, ShellApi;
procedure Split(Delimiter: Char; Str: string; TStr: TStrings);
function trimCharLeft(str: string; charToTrim: char): string;
function trimCharsRight(str: string; charToTrim, char2ToTrim: char): string;
function wildcardFileNameToExt(fileName: string): string;
function wildcardArchiveNameToArchiveList(archiveName: string): TStringList;
function getAllFilesInFolder(path: string; ext: string = '*'; isDir: boolean = false): TStringList;
procedure addAllFilesToFileList(var fileList: TStringList; path: string; recursive: integer; isDir: boolean; usePathFilenamePair: boolean; extList: TStringList); overload;
procedure addAllFilesToFileList(var fileList: TStringList; path: string; recursive: integer; isDir: boolean; usePathFilenamePair: boolean); overload;
procedure addKeepToAllEmptyFoldersRecur(folder: string);
function beautifyPath(oldStr: String): string;
function withTrailingSlash(path: string): string;
procedure createDirRecur(dir: string);
procedure copyFile0(oldFile, newFile: string);
function createEmptyFile(filePath: string): boolean;
procedure StrToFile(filePath, SourceString: string);
function isSubfolder(folder, potentialSubfolder: string): boolean;
function moveDir(folderFrom, folderTo: string): Boolean;
procedure delDir(folder: string);
const
nameValSeparator: char = ':';
archResSeparator: char = ':';
EmptyFolderKeep: string = '.mmarchkeep';
supportedExts: array[0..7] of string = ('.lod', '.pac', '.snd', '.vid', '.lwd', '.mm7', '.dod', '.mm6');
{$IFDEF MSWINDOWS}
slash: char = '\';
{$ELSE}
slash: char = '/';
{$ENDIF}
resourcestring
DirNotFound = 'Directory %s is not found';
implementation
procedure Split(Delimiter: Char; Str: string; TStr: TStrings);
begin
TStr.Clear;
TStr.Delimiter := Delimiter;
TStr.StrictDelimiter := True;
TStr.DelimitedText := Str;
end;
function trimCharLeft(str: string; charToTrim: char): string;
var
n: integer;
begin
n := 1;
while (n <= Length(str)) and (str[n] = charToTrim) do
Inc(n);
SetString(Result, PChar(@str[n]), Length(str) - n + 1);
end;
function trimCharsRight(str: string; charToTrim, char2ToTrim: char): string;
var
n: integer;
begin
n := Length(str);
while (n >= 1) and ((str[n] = charToTrim) or (str[n] = char2ToTrim)) do
Dec(n);
SetString(Result, PChar(@str[1]), n);
end;
// private
function stringsToStringList(const Strings: array of string): TStringList;
var
i: Integer;
begin
Result := TStringList.Create;
for i := low(Strings) to high(Strings) do
Result.Add(Strings[i]);
end;
function wildcardFileNameToExt(fileName: string): string;
begin
if (fileName = '*') or (fileName = '*.*') then // all files
Result := '*'
else
begin
if fileName = '*.' then // all files without extension
Result := ''
else // all files with specified extension
Result := trimCharLeft(fileName, '*');
end;
end;
// private
function fileNameToExtList(fileName: string): TStringList; // Ext in Result has dot
var
ext, extTemp: string;
ResultTemp: TStringList;
begin
ext := ExtractFileExt(fileName);
if (fileName = '*') or (fileName = '*.*') then
Result := stringsToStringList(supportedExts)
else
begin
Result := TStringList.Create;
if Pos('|', fileName) > 0 then
begin
ResultTemp := TStringList.Create;
Split('|', trimCharLeft(ext, '.'), ResultTemp);
for extTemp in ResultTemp do
if MatchStr('.' + AnsiLowerCase(extTemp), supportedExts) then
Result.Add('.' + AnsiLowerCase(extTemp));
ResultTemp.Free;
end
else
Result.Add(ext);
end;
end;
function wildcardArchiveNameToArchiveList(archiveName: string): TStringList;
var
path, fileName, pathRightAst, pathTemp: string;
extList: TStringList;
begin
path := trimCharsRight(ExtractFilePath(archiveName), '\', '/');
fileName := ExtractFileName(archiveName);
extList := fileNameToExtList(fileName);
Result := TStringList.Create;
Result.Clear;
Result.NameValueSeparator := nameValSeparator;
pathRightAst := copy(path, length(path)-1, 2);
if pathRightAst = '**' then
begin
pathTemp := copy(path, 1, length(path)-2); // part of path where pathRightAst is substracted
addAllFilesToFileList(Result, pathTemp, 1, false, true, extList);
end
else
begin
pathRightAst := copy(path, length(path), 1);
if pathRightAst = '*' then
begin
pathTemp := copy(path, 1, length(path)-1);
addAllFilesToFileList(Result, pathTemp, 2, false, true, extList);
end
else
addAllFilesToFileList(Result, path, 3, false, true, extList);
end;
extList.Free;
end;
function getAllFilesInFolder(path: string; ext: string = '*'; isDir: boolean = false): TStringList;
// `ext` :
// '*': all files or all directory
// '': without extension, works no matter isDir or not
// (other string with dot): extension filter, works no matter isDir or not
var
searchResult: TSearchRec;
fileMask: string;
attr: integer;
currentDir: array[0 .. MAX_PATH] of char;
begin
Result := TStringList.Create;
if ext = '*' then // all files or all directory
fileMask := '*'
else
begin
if (ext = '') then // without extension, works no matter isDir or not
fileMask := '*.'
// '*.' will match `.gitignore` (no stem) and `LICENSE` (no ext)
// because they are seen as `.gitignore.` and `LICENSE.`
// so we'll have to check against its real extension it later
else
begin
fileMask := '*' + ext;
end;
end;
if isDir then
attr := faDirectory
else
attr := faAnyFile;
if path = '' then // DirectoryExists('') = false, so we need this
path := '.';
GetCurrentDirectory(MAX_PATH, currentDir);
if not DirectoryExists(path) then
raise Exception.CreateFmt(DirNotFound, [path]);
SetCurrentDirectory(PChar(path));
if findfirst(fileMask, attr, searchResult) = 0 then
begin
repeat
if (
(
(not isDir) and
FileExists(searchResult.Name)
) or (
isDir and
( (searchResult.attr and faDirectory) = faDirectory ) and
(searchResult.Name <> '.') and
(searchResult.Name <> '..')
)
)
and
(
(fileMask <> '*.') or
( (fileMask = '*.') and (ExtractFileExt(searchResult.Name) = '') )
)
and
(searchResult.Name <> EmptyFolderKeep) // special: ignore all .mmarchkeep file
then
Result.Add(searchResult.Name);
until FindNext(searchResult) <> 0;
SysUtils.FindClose(searchResult);
end;
SetCurrentDirectory(currentDir);
end;
// private
procedure addAllFilesToFileListNonRecur(var fileList: TStringList; path: string; isDir: boolean; usePathFilenamePair: boolean; extList: TStringList); overload;
var
ext, fileName: string;
begin
for ext in extList do
for fileName in getAllFilesInFolder(path, ext, isDir) do
if usePathFilenamePair then
fileList.Add(fileName + nameValSeparator + beautifyPath(path))
else
fileList.Add(withTrailingSlash(beautifyPath(path)) + fileName);
end;
// private
procedure addAllFilesToFileListNonRecur(var fileList: TStringList; path: string; isDir: boolean; usePathFilenamePair: boolean); overload;
var
extList: TStringList;
begin
extList := TStringList.Create;
extList.Add('*');
addAllFilesToFileListNonRecur(fileList, path, isDir, usePathFilenamePair, extList);
extList.Free;
end;
procedure addAllFilesToFileList(var fileList: TStringList; path: string; recursive: integer; isDir: boolean; usePathFilenamePair: boolean; extList: TStringList); overload;
// `recursive`:
// `1`: recursive
// `2`: in level 1 folders only
// `3`: current folder only
// `isDir`: directory or file
// `extList`: file/dir extension list, ext has dot
var
dirListTemp: TStringList;
dir: string;
begin
if (recursive = 1) or (recursive = 3) then
addAllFilesToFileListNonRecur(fileList, path, isDir, usePathFilenamePair, extList);
if recursive <> 3 then
begin
dirListTemp := getAllFilesInFolder(path, '*', true);
for dir in dirListTemp do
if recursive = 1 then
addAllFilesToFileList(fileList, withTrailingSlash(path) + dir, 1, isDir, usePathFilenamePair, extList)
else
if recursive = 2 then
addAllFilesToFileListNonRecur(fileList, withTrailingSlash(path) + dir, isDir, usePathFilenamePair, extList);
dirListTemp.Free;
end;
end;
procedure addAllFilesToFileList(var fileList: TStringList; path: string; recursive: integer; isDir: boolean; usePathFilenamePair: boolean); overload;
var
extList: TStringList;
begin
extList := TStringList.Create;
extList.Add('*');
addAllFilesToFileList(fileList, path, recursive, isDir, usePathFilenamePair, extList);
extList.Free;
end;
procedure addKeepToAllEmptyFoldersRecur(folder: string);
var
allFolders: TStringList;
elTemp: string;
begin
folder := trimCharsRight(beautifyPath(folder), '\', '/');
allFolders := TStringList.Create;
allFolders.Add(folder);
addAllFilesToFileList(allFolders, folder, 1, true, false);
for elTemp in allFolders do
if (getAllFilesInFolder(elTemp, '*', true).Count = 0)
and (getAllFilesInFolder(elTemp, '*', false).Count = 0) then // folder is empty (but maybe contain .mmarchkeep)
createEmptyFile(withTrailingSlash(elTemp) + EmptyFolderKeep);
allFolders.Free;
end;
function beautifyPath(oldStr: String): string;
var
i, start: integer;
currentChar: char;
begin
if length(oldStr) > 0 then
begin
if oldStr[1] = '.' then
begin
Result := '.';
start := 2;
end
else
begin
Result := '';
start := 1;
end;
for i := start to length(oldStr) do
begin
currentChar := oldStr[i];
if (currentChar = '\') or (currentChar = '/') then
begin
if (Result = '') or not (Result[length(Result)] = slash) then
Result := Result + slash;
end
else
begin
Result := Result + currentChar;
end;
end;
if System.Copy(Result, 0, 2) = ('.' + slash) then
System.Delete(Result, 1, 2);
end
else
Result := '';
end;
function withTrailingSlash(path: string): string;
begin
if path <> '' then
Result := IncludeTrailingPathDelimiter(path)
else
Result := path;
end;
procedure createDirRecur(dir: string);
var
currentDir, absDir: string;
begin
currentDir := GetCurrentDir;
absDir := withTrailingSlash(currentDir) + beautifyPath(dir);
if not DirectoryExists(absDir) then
ForceDirectories(absDir);
end;
procedure copyFile0(oldFile, newFile: string);
var
currentDir: string;
begin
currentDir := GetCurrentDir;
createDirRecur(ExtractFilePath(newFile));
CopyFile(
PAnsiChar(withTrailingSlash(currentDir) + beautifyPath(oldFile)),
PAnsiChar(withTrailingSlash(currentDir) + beautifyPath(newFile)),
false
);
end;
function createEmptyFile(filePath: string): boolean;
var
currentDir: string;
f: textfile;
begin
currentDir := GetCurrentDir;
createDirRecur(ExtractFilePath(filePath));
AssignFile(f, withTrailingSlash(currentDir) + beautifyPath(filePath));
{$I-}
Rewrite(f);
{$I+}
Result := IOResult = 0;
CloseFile(f);
end;
procedure StrToFile(filePath, SourceString: string);
var
currentDir: string;
Stream: TFileStream;
begin
currentDir := GetCurrentDir;
createDirRecur(ExtractFilePath(filePath));
Stream := TFileStream.Create(withTrailingSlash(currentDir) + beautifyPath(filePath), fmCreate);
try
Stream.WriteBuffer(Pointer(SourceString)^, Length(SourceString));
finally
Stream.Free;
end;
end;
function isSubfolder(folder, potentialSubfolder: string): boolean;
var
parentFolder, lastParentFolder: string;
begin
parentFolder := trimCharsRight(beautifyPath(potentialSubfolder), '\', '/');
folder := trimCharsRight(beautifyPath(folder), '\', '/');
repeat
lastParentFolder := parentFolder;
parentFolder := trimCharsRight(ExtractFilePath(parentFolder), '\', '/');
Result := (parentFolder = folder);
until (parentFolder = lastParentFolder) or (parentFolder = '') or Result;
end;
function moveDir(folderFrom, folderTo: string): Boolean;
// folderFrom, folderTo cannot be current folder or ancestor folder
var
fos: TSHFileOpStruct;
begin
folderFrom := trimCharsRight(beautifyPath(folderFrom), '\', '/');
folderTo := trimCharsRight(beautifyPath(folderTo), '\', '/');
if isSubfolder(folderFrom, folderTo) then
begin
Result := moveDir(folderFrom, folderFrom + '.mmarchtmp');
Result := Result and moveDir(folderFrom + '.mmarchtmp', folderTo);
end
else
if folderFrom <> folderTo then
begin
createDirRecur(ExtractFilePath(folderTo));
ZeroMemory(@fos, SizeOf(fos));
with fos do
begin
wFunc := FO_MOVE;
fFlags := FOF_FILESONLY;
pFrom := PChar(folderFrom + #0);
pTo := PChar(folderTo);
end;
Result := (0 = ShFileOperation(fos));
end
else
begin
Result := false;
end;
end;
procedure delDir(folder: string);
var
FileOp: TSHFileOpStruct;
begin
FillChar(FileOp, SizeOf(FileOp), 0);
FileOp.wFunc := FO_DELETE;
FileOp.pFrom := PChar(folder + #0); // double zero-terminated
FileOp.fFlags := FOF_SILENT or FOF_NOERRORUI or FOF_NOCONFIRMATION;
SHFileOperation(FileOp);
end;
end.
|
unit UDTables;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, UCrpe32;
type
TCrpeTablesDlg = class(TForm)
btnOk: TButton;
btnClear: TButton;
pnlTables: TPanel;
lblNumber: TLabel;
lblName: TLabel;
lblPath: TLabel;
lblPassword: TLabel;
lblTableType: TLabel;
lblDLLName: TLabel;
lblServerType: TLabel;
lblSubName: TLabel;
lblConnectBuffer: TLabel;
lbNumbers: TListBox;
editName: TEdit;
btnName: TButton;
editPath: TEdit;
btnPath: TButton;
cbPropagate: TCheckBox;
editPassword: TEdit;
editTableType: TEdit;
editDLLName: TEdit;
editServerType: TEdit;
btnCheckDifferences: TButton;
editSubName: TEdit;
editConnectBuffer: TEdit;
btnTest: TButton;
OpenDialog1: TOpenDialog;
btnVerify: TButton;
cbVerifyFix: TCheckBox;
lblFieldMapping: TLabel;
cbFieldMapping: TComboBox;
lblAliasName: TLabel;
editAliasName: TEdit;
btnFields: TButton;
lblCount: TLabel;
editCount: TEdit;
btnConvertDriver: TButton;
procedure btnNameClick(Sender: TObject);
procedure btnPathClick(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure UpdateTables;
procedure lbNumbersClick(Sender: TObject);
procedure editNameChange(Sender: TObject);
procedure editPasswordChange(Sender: TObject);
procedure cbPropagateClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure editSubNameChange(Sender: TObject);
procedure editConnectBufferChange(Sender: TObject);
procedure btnCheckDifferencesClick(Sender: TObject);
procedure btnTestClick(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure cbFieldMappingChange(Sender: TObject);
procedure cbVerifyFixClick(Sender: TObject);
procedure btnVerifyClick(Sender: TObject);
procedure editAliasNameChange(Sender: TObject);
procedure InitializeControls(OnOff: boolean);
procedure btnConvertDriverClick(Sender: TObject);
procedure btnFieldsClick(Sender: TObject);
procedure editServerTypeChange(Sender: TObject);
procedure editPathExit(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
TableIndex : smallint;
procedure OpenFieldsDlg;
end;
var
CrpeTablesDlg: TCrpeTablesDlg;
bTables : boolean;
implementation
{$R *.DFM}
uses UCrpeUtl, UDPathEdit, UDTableFields;
{------------------------------------------------------------------------------}
{ FormCreate procedure }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.FormCreate(Sender: TObject);
begin
bTables := True;
LoadFormPos(Self);
btnOk.Tag := 1;
TableIndex := -1;
{FieldMapping}
cbFieldMapping.Clear;
cbFieldMapping.Items.Add('fmAuto');
cbFieldMapping.Items.Add('fmPrompt');
cbFieldMapping.Items.Add('fmEvent');
end;
{------------------------------------------------------------------------------}
{ FormShow procedure }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.FormShow(Sender: TObject);
begin
UpdateTables;
end;
{------------------------------------------------------------------------------}
{ UpdateTables procedure }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.UpdateTables;
var
OnOff : boolean;
Ver7 : Boolean;
i : integer;
begin
TableIndex := -1;
{Enable/Disable controls}
if IsStrEmpty(Cr.ReportName) then
OnOff := False
else
begin
OnOff := (Cr.Tables.Count > 0);
{Get Tables Index}
if OnOff then
begin
if Cr.Tables.ItemIndex > -1 then
TableIndex := Cr.Tables.ItemIndex
else
TableIndex := 0;
end;
end;
InitializeControls(OnOff);
{Update list box}
if OnOff = True then
begin
{Check for CRW 7+ features}
Ver7 := (Cr.Version.Crpe.Major > 6);
cbFieldMapping.Enabled := Ver7;
btnVerify.Enabled := Ver7;
cbVerifyFix.Enabled := Ver7;
cbFieldMapping.ItemIndex := Ord(Cr.Tables.FieldMapping);
lbNumbers.Clear;
for i := 0 to (Cr.Tables.Count - 1) do
lbNumbers.Items.Add(IntToStr(i));
editCount.Text := IntToStr(Cr.Tables.Count);
lbNumbers.ItemIndex := TableIndex;
lbNumbersClick(Self);
end;
end;
{------------------------------------------------------------------------------}
{ InitializeControls }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.InitializeControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
if TComponent(Components[i]).Tag = 0 then
begin
if Components[i] is TButton then
TButton(Components[i]).Enabled := OnOff;
if Components[i] is TCheckBox then
TCheckBox(Components[i]).Enabled := OnOff;
if Components[i] is TComboBox then
begin
TComboBox(Components[i]).Color := ColorState(OnOff);
TComboBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TListBox then
begin
TListBox(Components[i]).Clear;
TListBox(Components[i]).Color := ColorState(OnOff);
TListBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TEdit then
begin
if not OnOff then
TEdit(Components[i]).Text := '';
if TEdit(Components[i]).ReadOnly = False then
TEdit(Components[i]).Color := ColorState(OnOff);
TEdit(Components[i]).Enabled := OnOff;
end;
end;
end;
end;
{------------------------------------------------------------------------------}
{ lbNumbersClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.lbNumbersClick(Sender: TObject);
var
OnOff : Boolean;
begin
{Disable events}
cbPropagate.OnClick := nil;
{Update components}
TableIndex := lbNumbers.ItemIndex;
editName.Text := Cr.Tables[TableIndex].Name;
editSubName.Text := Cr.Tables.Item.SubName;
editConnectBuffer.Text := Cr.Tables.Item.ConnectBuffer;
editPath.Text := Cr.Tables.Item.Path;
editAliasName.Text := Cr.Tables.Item.AliasName;
cbPropagate.Checked := Cr.Tables.Propagate;
{Check for SQL}
case Ord(Cr.Tables.Item.TableType) of
0: editTableType.Text := 'ttUnknown';
1: editTableType.Text := 'ttStandard';
2: editTableType.Text := 'ttSQL';
end;
btnName.Enabled := (Cr.Tables.Item.TableType <> ttSQL);
btnPath.Enabled := (Cr.Tables.Item.TableType <> ttSQL);
editPath.Enabled := (Cr.Tables.Item.TableType <> ttSQL);
editPath.Color := ColorState(editPath.Enabled);
{Check Propagate}
if Cr.Subreports.ItemIndex = 0 then
OnOff := True
else
OnOff := (Cr.Subreports.ItemIndex > 0) and not (cbPropagate.Checked);
editPath.Enabled := OnOff;
editPath.Color := ColorState(OnOff);
{Get Read-Only values}
editDLLName.Text := Cr.Tables.Item.DLLName;
editServerType.Text := Cr.Tables.Item.ServerType;
{Enable events}
cbPropagate.OnClick := cbPropagateClick;
end;
{------------------------------------------------------------------------------}
{ editNameChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.editNameChange(Sender: TObject);
begin
Cr.Tables.Item.Name := editName.Text;
end;
{------------------------------------------------------------------------------}
{ editSubNameChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.editSubNameChange(Sender: TObject);
begin
Cr.Tables.Item.SubName := editSubName.Text;
end;
{------------------------------------------------------------------------------}
{ editConnectBufferChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.editConnectBufferChange(Sender: TObject);
begin
Cr.Tables.Item.ConnectBuffer := editConnectBuffer.Text;
end;
{------------------------------------------------------------------------------}
{ editPathExit procedure }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.editPathExit(Sender: TObject);
begin
Cr.Tables.Item.Path := editPath.Text;
end;
{------------------------------------------------------------------------------}
{ editTablePasswordChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.editPasswordChange(Sender: TObject);
begin
Cr.Tables.Item.Password := editPassword.Text;
end;
{------------------------------------------------------------------------------}
{ editAliasNameChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.editAliasNameChange(Sender: TObject);
begin
Cr.Tables.Item.AliasName := editAliasName.Text;
end;
{------------------------------------------------------------------------------}
{ editServerTypeChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.editServerTypeChange(Sender: TObject);
begin
Cr.Tables.Item.ServerType := editServerType.Text;
end;
{------------------------------------------------------------------------------}
{ cbPropagateClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.cbPropagateClick(Sender: TObject);
begin
Cr.Tables.Propagate := cbPropagate.Checked;
UpdateTables;
end;
{------------------------------------------------------------------------------}
{ btnSetNameClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.btnNameClick(Sender: TObject);
begin
{Set the dialog default filename, filter and title}
OpenDialog1.FileName := '*' + ExtractFileExt(editName.Text);
OpenDialog1.Filter := 'Database Files (*' + UpperCase(OpenDialog1.FileName)
+ ')|*' + OpenDialog1.FileName + '|' + 'All files (*.*)|*.*';
OpenDialog1.Title := 'Choose New Table...';
OpenDialog1.InitialDir := editPath.Text;
if OpenDialog1.Execute then
begin
Refresh;
editName.Text := ExtractFileName(OpenDialog1.FileName);
editPath.Text := ExtractFilePath(OpenDialog1.FileName);
end;
end;
{------------------------------------------------------------------------------}
{ btnPathClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.btnPathClick(Sender: TObject);
begin
CrpePathDlg := TCrpePathDlg.Create(Application);
CrpePathDlg.Caption := 'Select Table Path...';
CrpePathDlg.rPath := editPath.Text;
CrpePathDlg.ShowModal;
if CrpePathDlg.ModalResult = mrOk then
editPath.Text := CrpePathDlg.rPath;
end;
{------------------------------------------------------------------------------}
{ btnCheckDifferencesClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.btnCheckDifferencesClick(Sender: TObject);
var
slNums,
slStrings : TStringList;
i : integer;
begin
slNums := TStringList.Create;
slStrings := TStringList.Create;
if not Cr.Tables.Item.CheckDifferences(slNums, slStrings) then
MessageDlg('Check Failed.', mtError, [mbOk], 0)
else
begin
for i := 0 to slNums.Count - 1 do
MessageDlg(slNums[i] + ': ' + slStrings[i], mtInformation, [mbOk], 0);
end;
slNums.Free;
slStrings.Free;
end;
{------------------------------------------------------------------------------}
{ btnTestClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.btnTestClick(Sender: TObject);
begin
if Cr.Tables.Item.Test then
MessageDlg('Table is Good!' , mtInformation, [mbOk], 0)
else
begin
MessageDlg('Table has a Problem.' + chr(10) +
'Error Number: ' + IntToStr(Cr.LastErrorNumber) + chr(10) +
Cr.LastErrorString, mtError, [mbOk], 0);
end;
end;
{------------------------------------------------------------------------------}
{ cbFieldMappingChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.cbFieldMappingChange(Sender: TObject);
begin
Cr.Tables.FieldMapping := TCrFieldMappingType(cbFieldMapping.ItemIndex);
end;
{------------------------------------------------------------------------------}
{ cbVerifyFixClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.cbVerifyFixClick(Sender: TObject);
begin
Cr.Tables.VerifyFix := cbVerifyFix.Checked;
end;
{------------------------------------------------------------------------------}
{ btnVerifyClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.btnVerifyClick(Sender: TObject);
begin
if Cr.Tables.Verify then
MessageDlg('The Database is up to date.', mtInformation, [mbOk], 0)
else
MessageDlg('An Error occured during Verify.', mtError, [mbOk], 0);
end;
{------------------------------------------------------------------------------}
{ btnConvertDriverClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.btnConvertDriverClick(Sender: TObject);
var
s1 : string;
begin
if InputQuery('Tables.ConvertDriver', 'Specify New Database DLL Name: ', s1) then
begin
Cr.Tables.ConvertDriver(s1);
UpdateTables;
end;
end;
{------------------------------------------------------------------------------}
{ btnFieldsClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.btnFieldsClick(Sender: TObject);
begin
if not bTableFields then
begin
CrpeTableFieldsDlg := TCrpeTableFieldsDlg.Create(Application);
CrpeTableFieldsDlg.Cr := Cr;
end;
CrpeTableFieldsDlg.Show;
end;
{------------------------------------------------------------------------------}
{ OpenFieldsDlg }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.OpenFieldsDlg;
begin
btnFieldsClick(Self);
end;
{------------------------------------------------------------------------------}
{ btnClearClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.btnClearClick(Sender: TObject);
begin
Cr.Tables.Clear;
UpdateTables;
end;
{------------------------------------------------------------------------------}
{ btnOkClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.btnOkClick(Sender: TObject);
begin
if (not IsStrEmpty(Cr.ReportName)) and (TableIndex > -1) then
editPathExit(editPath);
SaveFormPos(Self);
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose procedure }
{------------------------------------------------------------------------------}
procedure TCrpeTablesDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if bTableFields then
CrpeTableFieldsDlg.Release;
bTables := False;
Release;
end;
end.
|
unit MetaF1;
{$mode objfpc}{$H+}
interface
uses
Windows, Classes, SysUtils, Graphics;
type
TmetaFile = class;
TMetafileCanvas = class(TCanvas)
private
FMetafile: TMetafile;
public
constructor Create(AMetafile: TMetafile; ReferenceDevice: HDC);
constructor CreateWithComment(AMetafile: TMetafile; ReferenceDevice: HDC;
const CreatedBy, Description: AnsiString);
destructor Destroy; override;
end;
TSharedImage = class
private
FRefCount: Integer;
protected
procedure Reference;
procedure Release;
procedure FreeHandle; virtual; abstract;
property RefCount: Integer read FRefCount;
end;
TMetafileImage = class(TSharedImage)
private
FHandle: HENHMETAFILE;
FWidth: Integer; // FWidth and FHeight are in 0.01 mm logical pixels
FHeight: Integer; // These are converted to device pixels in TMetafile
FPalette: HPALETTE;
FInch: Word; // Used only when writing WMF files.
FTempWidth: Integer; // FTempWidth and FTempHeight are in device pixels
FTempHeight: Integer; // Used only when width/height are set when FHandle = 0
protected
procedure FreeHandle; override;
public
destructor Destroy; override;
end;
TMetafile = class(TGraphic)
private
FImage: TMetafileImage;
FEnhanced: Boolean;
function GetAuthor: AnsiString;
function GetDesc: AnsiString;
function GetHandle: HENHMETAFILE;
function GetInch: Word;
function GetMMHeight: Integer;
function GetMMWidth: Integer;
procedure NewImage;
procedure SetHandle(Value: HENHMETAFILE);
procedure SetInch(Value: Word);
procedure SetMMHeight(Value: Integer);
procedure SetMMWidth(Value: Integer);
procedure UniqueImage;
protected
function GetEmpty: Boolean; override;
function GetHeight: Integer; override;
function GetPalette: HPALETTE; override;
function GetWidth: Integer; override;
procedure Draw(ACanvas: TCanvas; const Rect: TRect); override;
procedure ReadData(Stream: TStream); override;
procedure SetHeight(Value: Integer); override;
procedure SetTransparent(Value: Boolean); override;
procedure SetWidth(Value: Integer); override;
function TestEMF(Stream: TStream): Boolean;
procedure WriteData(Stream: TStream); override;
procedure WriteEMFStream(Stream: TStream);
procedure WriteWMFStream(Stream: TStream);
public
constructor Create; override;
destructor Destroy; override;
procedure Clear;
function HandleAllocated: Boolean;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToFile(const Filename: AnsiString); override;
procedure SaveToStream(Stream: TStream); override;
// procedure LoadFromClipboardFormat(AFormat: Word; AData: THandle;
// APalette: HPALETTE); override;
// procedure SaveToClipboardFormat(var AFormat: Word; var AData: THandle;
// var APalette: HPALETTE); override;
procedure Assign(Source: TPersistent); override;
function ReleaseHandle: HENHMETAFILE;
property CreatedBy: AnsiString read GetAuthor;
property Description: AnsiString read GetDesc;
property Enhanced: Boolean read FEnhanced write FEnhanced default True;
property Handle: HENHMETAFILE read GetHandle write SetHandle;
property MMWidth: Integer read GetMMWidth write SetMMWidth;
property MMHeight: Integer read GetMMHeight write SetMMHeight;
property Inch: Word read GetInch write SetInch;
end;
implementation
const
csAllValid = [csHandleValid..csBrushValid];
var
ScreenLogPixels: Integer;
StockPen: HPEN;
StockBrush: HBRUSH;
StockFont: HFONT;
StockIcon: HICON;
BitmapImageLock: TRTLCriticalSection;
CounterLock: TRTLCriticalSection;
{ Exception routines }
procedure InvalidOperation(Str: PResStringRec);
begin
raise EInvalidGraphicOperation.CreateRes(Str);
end;
procedure InvalidGraphic(Str: PResStringRec);
begin
raise EInvalidGraphic.CreateRes(Str);
end;
procedure InvalidBitmap;
begin
end;
procedure InvalidIcon;
begin
end;
procedure InvalidMetafile;
begin
//InvalidGraphic(@SInvalidMetafile);
end;
procedure OutOfResources;
begin
raise EOutOfResources.Create('Out of resources');
end;
procedure GDIError;
var
ErrorCode: Integer;
Buf: array [Byte] of Char;
begin
ErrorCode := GetLastError;
if (ErrorCode <> 0) and (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nil,
ErrorCode, LOCALE_USER_DEFAULT, Buf, sizeof(Buf), nil) <> 0) then
raise EOutOfResources.Create(Buf)
else
OutOfResources;
end;
function GDICheck(Value: Integer): Integer;
begin
if Value = 0 then GDIError;
Result := Value;
end;
{ TSharedImage }
procedure TSharedImage.Reference;
begin
Inc(FRefCount);
end;
procedure TSharedImage.Release;
begin
if Pointer(Self) <> nil then
begin
Dec(FRefCount);
if FRefCount = 0 then
begin
FreeHandle;
Free;
end;
end;
end;
{ TMetafileImage }
destructor TMetafileImage.Destroy;
begin
if FHandle <> 0 then DeleteEnhMetafile(FHandle);
// InternalDeletePalette(FPalette);
inherited Destroy;
end;
procedure TMetafileImage.FreeHandle;
begin
end;
{ TMetafileCanvas }
constructor TMetafileCanvas.Create(AMetafile: TMetafile; ReferenceDevice: HDC);
begin
CreateWithComment(AMetafile, ReferenceDevice, AMetafile.CreatedBy,
AMetafile.Description);
end;
constructor TMetafileCanvas.CreateWithComment(AMetafile : TMetafile;
ReferenceDevice: HDC; const CreatedBy, Description: AnsiString);
var
RefDC: HDC;
R: TRect;
Temp: HDC;
P: Pansichar;
begin
inherited Create;
FMetafile := AMetafile;
RefDC := ReferenceDevice;
if ReferenceDevice = 0 then RefDC := GetDC(0);
try
if FMetafile.MMWidth = 0 then
if FMetafile.Width = 0 then
FMetafile.MMWidth := GetDeviceCaps(RefDC, HORZSIZE)*100
else
FMetafile.MMWidth := MulDiv(FMetafile.Width,
GetDeviceCaps(RefDC, HORZSIZE)*100, GetDeviceCaps(RefDC, HORZRES));
if FMetafile.MMHeight = 0 then
if FMetafile.Height = 0 then
FMetafile.MMHeight := GetDeviceCaps(RefDC, VERTSIZE)*100
else
FMetafile.MMHeight := MulDiv(FMetafile.Height,
GetDeviceCaps(RefDC, VERTSIZE)*100, GetDeviceCaps(RefDC, VERTRES));
R := Rect(0,0,FMetafile.MMWidth,FMetafile.MMHeight);
if (Length(CreatedBy) > 0) or (Length(Description) > 0) then
P := Pansichar(CreatedBy+#0+Description+#0#0)
else
P := nil;
Temp := CreateEnhMetafileA(RefDC, nil, @R, P);
// if Temp = 0 then GDIError;
Handle := Temp;
finally
if ReferenceDevice = 0 then ReleaseDC(0, RefDC);
end;
end;
destructor TMetafileCanvas.Destroy;
var
Temp: HDC;
begin
Temp := Handle;
Handle := 0;
FMetafile.Handle := CloseEnhMetafile(Temp);
inherited Destroy;
end;
{ TMetafile }
constructor TMetafile.Create;
begin
inherited Create;
FEnhanced := True;
// FTransparent := True;
Assign(nil);
end;
destructor TMetafile.Destroy;
begin
FImage.Release;
inherited Destroy;
end;
procedure TMetafile.Assign(Source: TPersistent);
var
Pal: HPalette;
begin
if (Source = nil) or (Source is TMetafile) then
begin
Pal := 0;
if FImage <> nil then
begin
Pal := FImage.FPalette;
FImage.Release;
end;
if Assigned(Source) then
begin
FImage := TMetafile(Source).FImage;
FEnhanced := TMetafile(Source).Enhanced;
end
else
begin
FImage := TMetafileImage.Create;
FEnhanced := True;
end;
FImage.Reference;
PaletteModified := (Pal <> Palette) and (Palette <> 0);
Changed(Self);
end
else
inherited Assign(Source);
end;
procedure TMetafile.Clear;
begin
NewImage;
end;
procedure TMetafile.Draw(ACanvas: TCanvas; const Rect: TRect);
var
MetaPal, OldPal: HPALETTE;
R: TRect;
begin
if FImage = nil then Exit;
MetaPal := Palette;
OldPal := 0;
if MetaPal <> 0 then
begin
OldPal := SelectPalette(ACanvas.Handle, MetaPal, True);
RealizePalette(ACanvas.Handle);
end;
R := Rect;
Dec(R.Right); // Metafile rect includes right and bottom coords
Dec(R.Bottom);
PlayEnhMetaFile(ACanvas.Handle, FImage.FHandle, R);
if MetaPal <> 0 then
SelectPalette(ACanvas.Handle, OldPal, True);
end;
function TMetafile.GetAuthor: AnsiString;
var
Temp: Integer;
begin
Result := '';
if (FImage = nil) or (FImage.FHandle = 0) then Exit;
Temp := GetEnhMetafileDescription(FImage.FHandle, 0, nil);
if Temp <= 0 then Exit;
SetLength(Result, Temp);
GetEnhMetafileDescriptionA(FImage.FHandle, Temp, Pansichar(Result));
SetLength(Result, StrLen(Pansichar(Result)));
end;
function TMetafile.GetDesc: AnsiString;
var
Temp: Integer;
begin
Result := '';
if (FImage = nil) or (FImage.FHandle = 0) then Exit;
Temp := GetEnhMetafileDescription(FImage.FHandle, 0, nil);
if Temp <= 0 then Exit;
SetLength(Result, Temp);
GetEnhMetafileDescriptionA(FImage.FHandle, Temp, Pansichar(Result));
Delete(Result, 1, StrLen(Pansichar(Result))+1);
SetLength(Result, StrLen(Pansichar(Result)));
end;
function TMetafile.GetEmpty: boolean;
begin
Result := FImage = nil;
end;
function TMetafile.GetHandle: HENHMETAFILE;
begin
if Assigned(FImage) then
Result := FImage.FHandle
else
Result := 0;
end;
function TMetaFile.HandleAllocated: Boolean;
begin
Result := Assigned(FImage) and (FImage.FHandle <> 0);
end;
const
HundredthMMPerInch = 2540;
function TMetafile.GetHeight: Integer;
var
EMFHeader: TEnhMetaHeader;
begin
if FImage = nil then NewImage;
with FImage do
if FInch = 0 then
if FHandle = 0 then
Result := FTempHeight
else
begin { convert 0.01mm units to referenceDC device pixels }
GetEnhMetaFileHeader(FHandle, Sizeof(EMFHeader), @EMFHeader);
Result := MulDiv(FHeight, { metafile height in 0.01mm }
EMFHeader.szlDevice.cy, { device height in pixels }
EMFHeader.szlMillimeters.cy*100); { device height in mm }
end
else { for WMF files, convert to font dpi based device pixels }
Result := MulDiv(FHeight, ScreenLogPixels, HundredthMMPerInch);
end;
function TMetafile.GetInch: Word;
begin
Result := 0;
if FImage <> nil then Result := FImage.FInch;
end;
function TMetafile.GetMMHeight: Integer;
begin
if FImage = nil then NewImage;
Result := FImage.FHeight;
end;
function TMetafile.GetMMWidth: Integer;
begin
if FImage = nil then NewImage;
Result := FImage.FWidth;
end;
function TMetafile.GetPalette: HPALETTE;
begin
Result := 0;
end;
function TMetafile.GetWidth: Integer;
var
EMFHeader: TEnhMetaHeader;
begin
if FImage = nil then NewImage;
with FImage do
if FInch = 0 then
if FHandle = 0 then
Result := FTempWidth
else
begin { convert 0.01mm units to referenceDC device pixels }
GetEnhMetaFileHeader(FHandle, Sizeof(EMFHeader), @EMFHeader);
Result := MulDiv(FWidth, { metafile width in 0.01mm }
EMFHeader.szlDevice.cx, { device width in pixels }
EMFHeader.szlMillimeters.cx*100); { device width in 0.01mm }
end
else { for WMF files, convert to font dpi based device pixels }
Result := MulDiv(FWidth, ScreenLogPixels, HundredthMMPerInch);
end;
procedure TMetafile.LoadFromStream(Stream: TStream);
begin
end;
procedure TMetafile.NewImage;
begin
FImage.Release;
FImage := TMetafileImage.Create;
FImage.Reference;
end;
procedure TMetafile.ReadData(Stream: TStream);
begin
end;
procedure TMetafile.SaveToFile(const Filename: AnsiString);
var
SaveEnh: Boolean;
begin
SaveEnh := Enhanced;
try
if AnsiLowerCaseFileName(ExtractFileExt(Filename)) = '.wmf' then
Enhanced := False; { For 16 bit compatibility }
inherited SaveToFile(Filename);
finally
Enhanced := SaveEnh;
end;
end;
procedure TMetafile.SaveToStream(Stream: TStream);
begin
if FImage <> nil then
if Enhanced then
WriteEMFStream(Stream)
else
WriteWMFStream(Stream);
end;
procedure TMetafile.SetHandle(Value: HENHMETAFILE);
var
EnhHeader: TEnhMetaHeader;
begin
if (Value <> 0) and
(GetEnhMetafileHeader(Value, sizeof(EnhHeader), @EnhHeader) = 0) then
InvalidMetafile;
UniqueImage;
if FImage.FHandle <> 0 then DeleteEnhMetafile(FImage.FHandle);
// InternalDeletePalette(FImage.FPalette);
FImage.FPalette := 0;
FImage.FHandle := Value;
FImage.FTempWidth := 0;
FImage.FTempHeight := 0;
if Value <> 0 then
with EnhHeader.rclFrame do
begin
FImage.FWidth := Right - Left;
FImage.FHeight := Bottom - Top;
end;
PaletteModified := Palette <> 0;
Changed(Self);
end;
procedure TMetafile.SetHeight(Value: Integer);
var
EMFHeader: TEnhMetaHeader;
begin
if FImage = nil then NewImage;
with FImage do
if FInch = 0 then
if FHandle = 0 then
FTempHeight := Value
else
begin { convert device pixels to 0.01mm units }
GetEnhMetaFileHeader(FHandle, Sizeof(EMFHeader), @EMFHeader);
MMHeight := MulDiv(Value, { metafile height in pixels }
EMFHeader.szlMillimeters.cy*100, { device height in 0.01mm }
EMFHeader.szlDevice.cy); { device height in pixels }
end
else
MMHeight := MulDiv(Value, HundredthMMPerInch, ScreenLogPixels);
end;
procedure TMetafile.SetInch(Value: Word);
begin
if FImage = nil then NewImage;
if FImage.FInch <> Value then
begin
UniqueImage;
FImage.FInch := Value;
Changed(Self);
end;
end;
procedure TMetafile.SetMMHeight(Value: Integer);
begin
if FImage = nil then NewImage;
FImage.FTempHeight := 0;
if FImage.FHeight <> Value then
begin
UniqueImage;
FImage.FHeight := Value;
Changed(Self);
end;
end;
procedure TMetafile.SetMMWidth(Value: Integer);
begin
if FImage = nil then NewImage;
FImage.FTempWidth := 0;
if FImage.FWidth <> Value then
begin
UniqueImage;
FImage.FWidth := Value;
Changed(Self);
end;
end;
procedure TMetafile.SetTransparent(Value: Boolean);
begin
// Ignore assignments to this property.
// Metafiles must always be considered transparent.
end;
procedure TMetafile.SetWidth(Value: Integer);
var
EMFHeader: TEnhMetaHeader;
begin
if FImage = nil then NewImage;
with FImage do
if FInch = 0 then
if FHandle = 0 then
FTempWidth := Value
else
begin { convert device pixels to 0.01mm units }
GetEnhMetaFileHeader(FHandle, Sizeof(EMFHeader), @EMFHeader);
MMWidth := MulDiv(Value, { metafile width in pixels }
EMFHeader.szlMillimeters.cx*100, { device width in mm }
EMFHeader.szlDevice.cx); { device width in pixels }
end
else
MMWidth := MulDiv(Value, HundredthMMPerInch, ScreenLogPixels);
end;
function TMetafile.TestEMF(Stream: TStream): Boolean;
var
Size: Longint;
Header: TEnhMetaHeader;
begin
Size := Stream.Size - Stream.Position;
if Size > Sizeof(Header) then
begin
Stream.Read(Header, Sizeof(Header));
Stream.Seek(-Sizeof(Header), soFromCurrent);
end;
Result := (Size > Sizeof(Header)) and
(Header.iType = EMR_HEADER) and (Header.dSignature = ENHMETA_SIGNATURE);
end;
procedure TMetafile.UniqueImage;
var
NewImage1: TMetafileImage;
begin
if FImage = nil then
Self.NewImage
else
if FImage.FRefCount > 1 then
begin
NewImage1:= TMetafileImage.Create;
if FImage.FHandle <> 0 then
NewImage1.FHandle := CopyEnhMetafile(FImage.FHandle, nil);
NewImage1.FHeight := FImage.FHeight;
NewImage1.FWidth := FImage.FWidth;
NewImage1.FInch := FImage.FInch;
NewImage1.FTempWidth := FImage.FTempWidth;
NewImage1.FTempHeight := FImage.FTempHeight;
FImage.Release;
FImage := NewImage1;
FImage.Reference;
end;
end;
procedure TMetafile.WriteData(Stream: TStream);
var
SavePos: Longint;
begin
if FImage <> nil then
begin
SavePos := 0;
Stream.Write(SavePos, Sizeof(SavePos));
SavePos := Stream.Position - Sizeof(SavePos);
if Enhanced then
WriteEMFStream(Stream)
else
WriteWMFStream(Stream);
Stream.Seek(SavePos, soFromBeginning);
SavePos := Stream.Size - SavePos;
Stream.Write(SavePos, Sizeof(SavePos));
Stream.Seek(0, soFromEnd);
end;
end;
procedure TMetafile.WriteEMFStream(Stream: TStream);
var
Buf: Pointer;
Length: Longint;
begin
if FImage = nil then Exit;
Length := GetEnhMetaFileBits(FImage.FHandle, 0, nil);
if Length = 0 then Exit;
GetMem(Buf, Length);
try
GetEnhMetaFileBits(FImage.FHandle, Length, Buf);
Stream.WriteBuffer(Buf^, Length);
finally
FreeMem(Buf, Length);
end;
end;
procedure TMetafile.WriteWMFStream(Stream: TStream);
begin
end;
(*
procedure TMetafile.LoadFromClipboardFormat(AFormat: Word; AData: THandle;
APalette: HPALETTE);
var
EnhHeader: TEnhMetaHeader;
begin
AData := GetClipboardData(CF_ENHMETAFILE); // OS will convert WMF to EMF
if AData = 0 then InvalidGraphic(@SUnknownClipboardFormat);
NewImage;
with FImage do
begin
FHandle := CopyEnhMetafile(AData, nil);
GetEnhMetaFileHeader(FHandle, sizeof(EnhHeader), @EnhHeader);
with EnhHeader.rclFrame do
begin
FWidth := Right - Left;
FHeight := Bottom - Top;
end;
FInch := 0;
end;
Enhanced := True;
PaletteModified := Palette <> 0;
Changed(Self);
end;
procedure TMetafile.SaveToClipboardFormat(var AFormat: Word; var AData: THandle;
var APalette: HPALETTE);
begin
if FImage = nil then Exit;
AFormat := CF_ENHMETAFILE;
APalette := 0;
AData := CopyEnhMetaFile(FImage.FHandle, nil);
end;
*)
function TMetafile.ReleaseHandle: HENHMETAFILE;
begin
UniqueImage;
Result := FImage.FHandle;
FImage.FHandle := 0;
end;
end.
|
unit UTreeNode;
interface
uses
ComCtrls;
Type
TIndex = 'a'..'z';
PtrTrieTree = ^TNode;
TNode = class
private
Ptrs: array [TIndex] of TNode;
eow: boolean;
public
Constructor Create;
procedure PushString (s: string; i:byte);
procedure PrintString (s:string);
procedure resString (s:string;var i:integer;chr:char);
function IsEow: boolean;
procedure SetEow(ok: boolean);
function IsEmpty:boolean;
procedure print(treeView: TTreeView; parent:TTreeNode);
destructor Destroy;
end;
implementation
constructor TNode.Create;
var ch:char;
begin
inherited;
self.eow:=false;
for ch:=low(TIndex) to High(TIndex) do
Ptrs[ch]:=nil;
end;
Function TNode.IsEmpty: boolean;
var ch:char;
begin
result:=true;
ch:=Low(TIndex);
repeat
result:=Ptrs[ch]=nil;
inc(ch);
until (not result) or (ch = High(TIndex))
end;
function TNode.IsEow;
begin
result:=eow;
end;
procedure TNode.SetEow(ok: boolean);
begin
eow:=ok;
end;
procedure TNode.PushString (s: string; i:byte);
begin
if ptrs[s[i]] = nil then
ptrs[s[i]] := TNode.Create;
if length(s)<=i then
ptrs[s[i]].SetEow(true)
else
Ptrs[S[i]].PushString(s,i+1);
end;
procedure TNode.print(treeView: TTreeView; parent:TTreeNode);
var
i:Char;
newParent: TTreeNode;
begin
for i:= Low(TIndex) to high(TIndex) do
if ptrs[i]<>nil then
begin
newParent := treeView.Items.AddChild(parent, i);
ptrs[i].print(treeView, newParent);
end;
end;
procedure TNode.PrintString (s:string);
var ch: TIndex;
begin
if eow then
writeln(s);
for ch:=Low(TIndex) to High(TIndex) do
if Ptrs[ch]<>nil then
Ptrs[ch].PrintString(s+ch)
end;
procedure TNode.resString (s:string;var i:integer;chr:char);
var
k:integer;
ch: TIndex;
ok:boolean;
begin
if eow then
begin
k:=1;
ok:=false;
while (not ok) and (k<=length(s)) do
begin
if s[k] = chr then
ok:=true;
inc(k);
end;
if ok then
inc(i);
end;
for ch:=Low(TIndex) to High(TIndex) do
if Ptrs[ch]<>nil then
Ptrs[ch].resString(s+ch,i,chr)
end;
Destructor TNode.Destroy;
var ch: TIndex;
begin
for ch:=low(TIndex) to High(TIndex) do
if Ptrs[ch] <> nil then
Ptrs[ch].Destroy;
inherited;
end;
end.
|
unit uSteps;
interface
uses
Classes,
uMemory,
Controls,
uInstallFrame;
type
TInstallStep = class(TObject)
end;
TInstallSteps = class(TObject)
private
FStepTypes: TList;
FX, FY: Integer;
FOwner: TWinControl;
FSteps: TList;
FOnChange: TNotifyEvent;
FCurrentStep: Integer;
function GetStepByIndex(Index: Integer): TInstallFrame;
function GetCount: Integer;
function GetCanInstall: Boolean;
function GetCanNext: Boolean;
function GetCanPrevious: Boolean;
function GetCurrentStep: Integer;
procedure UpdateCurrentStep;
procedure Changed;
procedure OnStepChanged(Sender : TObject);
protected
procedure AddStep(Step : TInstallFrameClass);
public
constructor Create; virtual;
destructor Destroy; override;
procedure Start(Owner: TWinControl; X, Y: Integer);
procedure NextStep;
procedure PreviousStep;
procedure PrepaireInstall;
property Steps[Index: Integer]: TInstallFrame read GetStepByIndex; default;
property Count: Integer read GetCount;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property CanInstall: Boolean read GetCanInstall;
property CurrentStep: Integer read GetCurrentStep;
property CanNext: Boolean read GetCanNext;
property CanPrevious: Boolean read GetCanPrevious;
end;
implementation
{ TInstallSteps }
procedure TInstallSteps.AddStep(Step: TInstallFrameClass);
begin
FStepTypes.Add(Step);
end;
procedure TInstallSteps.Changed;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
constructor TInstallSteps.Create;
begin
FOnChange := nil;
FStepTypes := TList.Create;
FSteps := TList.Create;
FCurrentStep := 0;
end;
destructor TInstallSteps.Destroy;
begin
F(FStepTypes);
FreeList(FSteps);
inherited;
end;
function TInstallSteps.GetCanInstall: Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to Count - 1 do
if not Steps[I].ValidateFrame then
Exit;
Result := True;
end;
function TInstallSteps.GetCanNext: Boolean;
begin
Result := (CurrentStep < Count - 1) and Steps[CurrentStep].ValidateFrame;
end;
function TInstallSteps.GetCanPrevious: Boolean;
begin
Result := CurrentStep > 0;
end;
function TInstallSteps.GetCount: Integer;
begin
Result := FSteps.Count;
end;
function TInstallSteps.GetCurrentStep: Integer;
begin
Result := FCurrentStep;
end;
function TInstallSteps.GetStepByIndex(Index: Integer): TInstallFrame;
begin
Result := FSteps[Index];
end;
procedure TInstallSteps.NextStep;
begin
if CanNext then
begin
Inc(FCurrentStep);
UpdateCurrentStep;
Changed;
end;
end;
procedure TInstallSteps.OnStepChanged(Sender: TObject);
begin
if Assigned(FOnChange) then
FOnChange(Sender);
end;
procedure TInstallSteps.PrepaireInstall;
var
I : Integer;
begin
for I := 0 to Count - 1 do
Steps[I].InitInstall;
end;
procedure TInstallSteps.PreviousStep;
begin
if CanPrevious then
begin
Dec(FCurrentStep);
UpdateCurrentStep;
Changed;
end;
end;
procedure TInstallSteps.Start(Owner: TWinControl; X, Y: Integer);
var
I: Integer;
Frame: TInstallFrame;
begin
FOwner := Owner;
FX := X;
FY := Y;
for I := 0 to FStepTypes.Count - 1 do
begin
Frame := TInstallFrameClass(FStepTypes[I]).Create(Owner);
Frame.Parent := Owner;
Frame.Left := X;
Frame.Top := Y;
Frame.Visible := False;
Frame.Init;
Frame.OnChange := OnStepChanged;
FSteps.Add(Frame);
end;
Changed;
UpdateCurrentStep;
end;
procedure TInstallSteps.UpdateCurrentStep;
var
I: Integer;
begin
for I := 0 to Count - 1 do
begin
if (I <> FCurrentStep) and Steps[I].Visible then
Steps[I].Hide;
Steps[CurrentStep].Show;
end;
end;
end.
|
unit URepositorioPais;
interface
uses
UPais
, UEntidade
, URepositorioDB
, SqlExpr
;
type
TRepositorioPais = class (TRepositorioDB<TPAIS>)
public
constructor Create;
procedure AtribuiDBParaEntidade(const coPais: TPAIS); override;
procedure AtribuiEntidadeParaDB(const coPais: TPAIS;
const coSQLQuery: TSQLQuery); override;
end;
implementation
uses
UDM
;
{ TRepositorioPais }
procedure TRepositorioPais.AtribuiDBParaEntidade(const coPais: TPAIS);
begin
inherited;
with FSQLSelect do
begin
coPais.NOME := FieldByName(FLD_PAIS_NOME).AsString;
end;
end;
procedure TRepositorioPais.AtribuiEntidadeParaDB(const coPais: TPAIS;
const coSQLQuery: TSQLQuery);
begin
inherited;
with coSQLQuery do
begin
ParamByName(FLD_PAIS_NOME).AsString := coPais.NOME;
end;
end;
constructor TRepositorioPais.Create;
begin
inherited Create(TPAIS, TBL_PAIS, FLD_ENTIDADE_ID, STR_PAIS);
end;
end.
|
(*
2019-2020 "Tsusai": Printer Installer: Uses windows scripts to deploy multiple printers.
*)
unit Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.CheckLst, Vcl.ComCtrls,
Vcl.ExtCtrls;
type
TMainApp = class(TForm)
PrinterCheckBox: TCheckListBox;
DefaultBox: TListBox;
InstallBtn: TButton;
PrintersLbl: TLabel;
DefaultLbl: TLabel;
PresetsLbl: TLabel;
PresetsBox: TListBox;
DuplexRadio: TRadioGroup;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure InstallBtnClick(Sender: TObject);
procedure PrinterCheckBoxClickCheck(Sender: TObject);
procedure PresetsBoxClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
MainApp: TMainApp;
implementation
{$R *.dfm}
uses
ShellAPI,
System.IOUtils,
IniFiles;
procedure RunAndWait(
hWnd: HWND;
filename: string;
Parameters: string;
AsAdmin : boolean=false
);
{
See Step 3: Redesign for UAC Compatibility (UAC)
http://msdn.microsoft.com/en-us/library/bb756922.aspx
}
var
sei: TShellExecuteInfo;
ExitCode: DWORD;
begin
ZeroMemory(@sei, SizeOf(sei));
sei.cbSize := SizeOf(TShellExecuteInfo);
sei.Wnd := hwnd;
sei.fMask := SEE_MASK_FLAG_DDEWAIT or SEE_MASK_FLAG_NO_UI or SEE_MASK_NOCLOSEPROCESS;
if AsAdmin then sei.lpVerb := PChar('runas'); //Triggers UAC Elevation
sei.lpFile := PChar(Filename); // PAnsiChar;
if parameters <> '' then
sei.lpParameters := PChar(parameters); // PAnsiChar;
sei.nShow := SW_SHOWNORMAL; //Integer;
if ShellExecuteEx(@sei) then
begin
repeat
Application.ProcessMessages;
GetExitCodeProcess(sei.hProcess, ExitCode) ;
until (ExitCode <> STILL_ACTIVE) or Application.Terminated;
end;
end;
var
PrinterDir : string;// = '\\server\path\path\path\Printers';
DriverTMP : string;// = 'C:\PDRIVERS';
PausePhase : boolean;
TestMode : boolean;
type
TPrinter = class(TObject)
Name : string;
IP : string;
DrvN : string;
DrvD : string;
InfF :string;
end;
TPreset = class(TObject)
Printers : array of byte;
end;
//Application Startup
procedure TMainApp.FormCreate(Sender: TObject);
var
Ini : TMemIniFile;
Sections : TStringlist;
PresetPrinters : TStringList;
sidx, pidx, iidx : integer;
APrinter : TPrinter;
APreset : TPreset;
begin
//Set to the center of the screen on startup
Left:=(Screen.Width-Width) div 2;
Top:=(Screen.Height-Height) div 2;
(*Load Settings
[Settings]
RootFolder=\\server\path\path\path\Printers
TempFolder=C:\PDRIVERS
Pause=True
TestMode=False
*)
Ini := TMemIniFile.Create('Settings.ini');
PrinterDir := Ini.ReadString('Settings','RootFolder',ExtractFilePath(ParamStr(0)));
DriverTMP := Ini.ReadString('Settings','TempFolder','C:\PDRIVERS');
PausePhase := Ini.ReadBool('Settings','Pause',true);
TestMode := Ini.ReadBool('Settings','TestMode',false);
Ini.Free;
(*Load Printers
[Boss Workroom] (Name of the Printer in the GUI)
Name=Workroom (Color) (Installed Name of the Printer)
IP=192.168.1.16 (IP Address of Printer)
DriverName=Kyocera Classic Universaldriver PCL6 (Driver Name in INI File)
DriverDir=Kx630909_UPD_en\64bit\XP and newer (Path to Driver)
INF=OEMSETUP.INF (Optional, already assumes OEMSETUP.INF)
*)
Ini := TMemIniFile.Create('Printers.ini');
Sections := TStringlist.Create;
Ini.ReadSections(Sections);
if Sections.Count > 0 then
begin
//Loop through INI Sections
for sidx := 0 to Sections.Count-1 do
begin
//Grab Printer Info, Store in TObject to store into CheckListBox
//Box "owns" object, freed on Application Destruction
APrinter := TPrinter.Create;
APrinter.Name :=Ini.ReadString(Sections[sidx],'Name','');
APrinter.IP :=Ini.ReadString(Sections[sidx],'IP','');
APrinter.DrvN :=Ini.ReadString(Sections[sidx],'DriverName','');
APrinter.DrvD :=Ini.ReadString(Sections[sidx],'DriverDir','');
APrinter.InfF :=Ini.ReadString(Sections[sidx],'INF','oemsetup.inf');
PrinterCheckBox.Items.AddObject(Sections[sidx],APrinter);
end;
end;
//Free Data
Ini.Free;
Sections.Free;
(*Load Presets!
[Group Name ] (Name of the Group/Preset)
Printers="Printer A","Printer B" (Use the names of [Printers] from Printers.ini)
*)
Ini := TMemIniFile.Create('Presets.ini');
Sections := TStringlist.Create;
Ini.ReadSections(Sections);
PresetPrinters := TStringList.Create;
if Sections.Count > 0 then
begin
for sidx := 0 to Sections.Count-1 do
begin
PresetPrinters.Clear;
//Loading the Printerlist into a TStringList
PresetPrinters.CommaText := Ini.ReadString(Sections[sidx],'Printers','');
if PresetPrinters.CommaText = '' then continue;
APreset := TPreset.Create;
for pidx := 0 to PresetPrinters.Count-1 do
begin;
//Matching Preset Printer list to Actual Printers
iidx := PrinterCheckBox.Items.IndexOf(PresetPrinters[pidx]);
if iidx = -1 then continue else
begin
//Got one, expand array and store the printer index number
SetLength(APreset.Printers,Length(APreset.Printers)+1);
APreset.Printers[High(APreset.Printers)] := iidx;
end;
end;
PresetsBox.AddItem(Sections[sidx],APreset);
end;
end;
//Free Data
Ini.Free;
PresetPrinters.Free;
Sections.Free;
end;
//Application Shutdown
procedure TMainApp.FormDestroy(Sender: TObject);
var
ini : TMemIniFile;
idx : integer;
begin
Ini := TMemIniFile.Create('Settings.ini');
Ini.WriteString('Settings','RootFolder',PrinterDir);
Ini.WriteString('Settings','TempFolder',DriverTMP);
Ini.WriteBool('Settings','Pause',PausePhase);
Ini.WriteBool('Settings','TestMode',TestMode);
Ini.UpdateFile;
Ini.Free;
for idx := PrinterCheckBox.Items.Count-1 downto 0 do PrinterCheckBox.Items.Objects[idx].Free;
for idx := PresetsBox.Items.Count-1 downto 0 do PresetsBox.Items.Objects[idx].Free;
end;
//Preset Logic.
procedure TMainApp.PresetsBoxClick(Sender: TObject);
var
idx : integer;
APreset : TPreset;
begin
if PresetsBox.ItemIndex = -1 then exit;
//Grab our Preset Object with all our indexes
APreset := TPreset(PresetsBox.Items.Objects[PresetsBox.ItemIndex]);
//Clear Checks
for idx := PrinterCheckBox.Count-1 downto 0 do PrinterCheckBox.Checked[idx] := false;
//Run through Printer Index array and Check Printer
for idx := Low(APreset.Printers) to High(APreset.Printers) do
PrinterCheckBox.Checked[APreset.Printers[idx]] := true;
//Refresh Defaults Box as if we manually did a checkbox click
PrinterCheckBox.OnClickCheck(Sender);
end;
//Load current selection of Printers into Default Printers column
procedure TMainApp.PrinterCheckBoxClickCheck(Sender: TObject);
var
i : integer;
begin
Defaultbox.Clear;
for i := 0 to PrinterCheckBox.Count-1 do
begin
if PrinterCheckBox.Checked[i] then
begin
Defaultbox.Items.Add(TPrinter(PrinterCheckBox.Items.Objects[i]).Name);
end;
end;
if Defaultbox.Count>0 then Defaultbox.ItemIndex:=0;
end;
//Main Execution
procedure TMainApp.InstallBtnClick(Sender: TObject);
var
pidx : integer;
CMD : string;
APrinter : TPrinter;
Phase1, Phase2, Phase3 : TStringList;
TestDump : TStringList;
AFolder : string;
begin
InstallBtn.Enabled := false;
Phase1 := TStringList.Create;
Phase2 := TStringList.Create;
Phase3 := TStringList.Create;
TestDump := TStringList.Create;
try
TestDump.Clear;
Phase1.Clear;
Phase2.Clear;
Phase3.Clear;
//Phase 1, Copy files, remove old printer userlevel
//Phase 2, remove printer admin level, install driver admin level
//Phase 3, userlevel cleanup and tweaks
for pidx := 0 to PrinterCheckBox.Count-1 do
begin
AFolder := DriverTMP+'\'+IntToStr(pidx)+'\';
if TDirectory.Exists(AFolder) then TDirectory.Delete(AFolder, true);
if PrinterCheckBox.Checked[pidx] then
begin
APrinter := PrinterCheckBox.Items.Objects[pidx] as TPrinter;
TDirectory.CreateDirectory(AFolder);
//Copy Files User Level
Phase1.Add(
Format('xcopy "%s\%s" %s /I /y /D /E',[PrinterDir,APrinter.DrvD,AFolder])
);
//Remove Printer User Level
Phase1.Add(
Format('cscript %%WINDIR%%\System32\Printing_Admin_Scripts\en-US\Prnmngr.vbs -d -p "%s"',[APrinter.Name])
);
//Add Printer Port
Phase1.Add(
Format('cscript %%WINDIR%%\System32\Printing_Admin_Scripts\en-US\Prnport.vbs -a -r IP_%s -h %s -o raw -n 9100 -me -i 1 -y public',[APrinter.IP,APrinter.IP])
);
//Remove Printer Admin Level
Phase2.Add(
Format('cscript %%WINDIR%%\System32\Printing_Admin_Scripts\en-US\Prnmngr.vbs -d -p "%s"',[APrinter.Name])
);
//Add Printer Driver Admin Level
Phase2.Add(
Format('cscript %%WINDIR%%\System32\Printing_Admin_Scripts\en-US\Prndrvr.vbs -a -m "%s" -v 3 -e "Windows x64" -i %s\%s -h %s',[APrinter.DrvN,AFolder,APrinter.InfF,AFolder])
);
//Add Printer User Level
Phase3.Add(
Format('cscript %%WINDIR%%\System32\Printing_Admin_Scripts\en-US\Prnmngr.vbs -a -p "%s" -m "%s" -r IP_%s',[APrinter.Name,APrinter.DrvN,APrinter.IP])
);
end;
end;
if Phase1.Count > 0 then
begin
//Prepare CMD string to run Phase 1
CMD := '/c ';
for pidx := 0 to Phase1.Count-1 do
begin
CMD := CMD + Phase1.Strings[pidx];
if pidx <> (Phase1.Count-1) then CMD := CMD + ' & ';
end;
if PausePhase then CMD := CMD+ ' & pause';
if Not TestMode then RunAndWait(Self.Handle,'cmd',CMD) else TestDump.Add('Phase 1: ' + CMD);
//End of Phase1
//Phase 2
//Clear all Print Jobs, add to top of list
Phase2.Insert(0,'cscript %WINDIR%\System32\Printing_Admin_Scripts\en-US\prnqctl.vbs -x');
CMD := '/c ';
for pidx := 0 to Phase2.Count-1 do
begin
CMD := CMD + Phase2.Strings[pidx];
if pidx <> (Phase2.Count-1) then CMD := CMD + ' & ';
end;
if PausePhase then CMD := CMD+ ' & pause';
if Not TestMode then RunAndWait(Self.Handle,'cmd',CMD,true) else TestDump.Add('Phase 2: ' + CMD);
//End of Phase 2
//Phase 3
CMD := '/c ';
for pidx := 0 to Phase3.Count-1 do
begin
CMD := CMD + Phase3.Strings[pidx];
if pidx <> (Phase3.Count-1) then CMD := CMD + ' & ';
end;
//Disable Duplex?
if FileExists(GetCurrentDir+'\Tools\setprinter.exe') then
begin
case DuplexRadio.ItemIndex of
0: CMD := CMD + ' & ' + GetCurrentDir+'\Tools\setprinter.exe "" 8 "pDevMode=dmDuplex=1"'; //8 = All Users
1: CMD := CMD + ' & ' + GetCurrentDir+'\Tools\setprinter.exe "" 2 "pDevMode=dmDuplex=1"'; //2 = Current User
end;
end;
//Set Default Printer
if Defaultbox.ItemIndex <> -1 then
begin
CMD := CMD + ' & ' +
Format(
'cscript %%WINDIR%%\System32\Printing_Admin_Scripts\en-US\Prnmngr.vbs -p "%s" -t',
[Defaultbox.Items.Strings[Defaultbox.ItemIndex]]
);
end;
if PausePhase then CMD := CMD+ ' & pause';
if Not TestMode then RunAndWait(Self.Handle,'cmd',CMD) else TestDump.Add('Phase 3: ' + CMD);
//End of Phase 3
if TestMode then TestDump.SaveToFile('Test Mode Dump.txt');
if Assigned(TestDump) then TestDump.Free;
end;
finally
if TDirectory.Exists(DriverTMP) then TDirectory.Delete(DriverTMP, true);
ShowMessage('Done');
Phase1.Free;
Phase2.Free;
Phase3.Free;
InstallBtn.Enabled := true;
end;
end;
end.
|
(* CodeInt: HDO, 2004-02-06
-------
Interpreter for MiniPascal byte code.
===================================================================*)
UNIT CodeInt;
(*$I Chooser.inc*)
INTERFACE
USES
CodeDef;
PROCEDURE InterpretCode(ca: CodeArray);
IMPLEMENTATION
CONST
maxStackSize = 10;
maxStorageSize = 20;
VAR
ca: CodeArray; (*array of opCodes and operands*)
pc: INTEGER; (*program counter*)
stack: ARRAY [1 .. maxStackSize] OF INTEGER;
sp: INTEGER; (*stack pointer = top of stack*)
storage: ARRAY [0 .. maxStorageSize] OF INTEGER;
PROCEDURE ExecError(msg: STRING);
BEGIN
WriteLn('*** Execution error: ', msg);
HALT;
END; (*ExecError*)
PROCEDURE InitStack;
BEGIN
sp := 0;
END; (*InitStack*)
PROCEDURE Push(v: INTEGER);
BEGIN
IF sp = maxStackSize THEN
ExecError('stack overflow');
sp := sp + 1;
stack[sp] := v;
END; (*Push*)
PROCEDURE Pop(VAR v: INTEGER);
BEGIN
IF sp = 0 THEN
ExecError('stack underflow');
v := stack[sp];
sp := sp - 1;
END; (*Pop*)
PROCEDURE InitStorage;
VAR
i: INTEGER;
BEGIN
FOR i := 1 TO maxStorageSize DO BEGIN
storage[i] := 0;
END; (*FOR*)
END; (*InitStorage*)
PROCEDURE CheckAdr(adr: INTEGER);
BEGIN
IF (adr < 0) OR (adr > maxStorageSize) THEN
ExecError('address out of storage range');
END; (*CheckAdr*)
PROCEDURE FetchOpc(VAR opc: OpCode);
BEGIN
opc := OpCode(ca[pc]);
pc := pc + 1;
END; (*FetchOpc*)
PROCEDURE FetchOpd(VAR opd: INTEGER);
BEGIN
opd := Ord(ca[pc])*256 + Ord(ca[pc + 1]);
pc := pc + 2;
END; (*FetchOpc*)
PROCEDURE InterpretCode(ca: CodeArray);
(*-----------------------------------------------------------------*)
VAR
opc: OpCode;
opd: INTEGER;
val, val1, val2: INTEGER;
BEGIN
CodeInt.ca := ca;
WriteLn('code interpretation started ...');
InitStack;
InitStorage;
pc := 1;
FetchOpc(opc);
WHILE (opc <> EndOpc) DO BEGIN
CASE opc OF
LoadConstOpc: BEGIN
FetchOpd(opd);
Push(opd);
END;
LoadValOpc: BEGIN
FetchOpd(opd);
CheckAdr(opd);
Push(storage[opd]);
END;
LoadAddrOpc: BEGIN
FetchOpd(opd);
Push(opd);
END;
StoreOpc: BEGIN
Pop(val);
Pop(opd);
CheckAdr(opd);
storage[opd] := val;
END;
AddOpc: BEGIN
Pop(val2);
Pop(val1);
Push(val1 + val2);
END;
SubOpc: BEGIN
Pop(val2);
Pop(val1);
Push(val1 - val2);
END;
MulOpc: BEGIN
Pop(val2);
Pop(val1);
Push(val1 * val2);
END;
DivOpc: BEGIN
Pop(val2);
Pop(val1);
IF val2 = 0 THEN
ExecError('zero division');
Push(val1 DIV val2);
END;
ReadOpc: BEGIN
FetchOpd(opd);
CheckAdr(opd);
Write('var@', opd:0, ' > '); ReadLn(val);
storage[opd] := val;
END;
WriteOpc: BEGIN
Pop(val);
WriteLn(val);
END;
(*$IFDEF Midi*)
JmpOpc: BEGIN
FetchOpd(opd);
pc := opd;
END;
JmpZOpc: BEGIN
FetchOpd(opd);
Pop(val);
IF val = 0 THEN
pc := opd;
END;
(*$ENDIF*)
ELSE
ExecError('invalid operation code');
END; (*CASE*)
FetchOpc(opc);
END; (*WHILE*)
WriteLn('... code interpretation ended');
END; (*InterpretCode*)
END. (*CodeInt*) |
unit uFrmBaseKtypeInput;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFrmBaseInput, Menus, cxLookAndFeelPainters, ActnList, cxLabel,
cxControls, cxContainer, cxEdit, cxCheckBox, StdCtrls, cxButtons,
ExtCtrls, Mask, cxTextEdit, cxMaskEdit, cxButtonEdit, cxGraphics,
cxDropDownEdit, uParamObject, ComCtrls, cxStyles, cxCustomData, cxFilter,
cxData, cxDataStorage, DB, cxDBData, cxGridLevel, cxClasses,
cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, uDBComConfig, cxMemo;
type
TfrmBaseKtypeInput = class(TfrmBaseInput)
edtFullname: TcxButtonEdit;
lbl1: TLabel;
lbl2: TLabel;
edtUsercode: TcxButtonEdit;
Label1: TLabel;
edtName: TcxButtonEdit;
edtPYM: TcxButtonEdit;
lbl3: TLabel;
chkStop: TcxCheckBox;
lbl4: TLabel;
lbl5: TLabel;
lbl6: TLabel;
edtAddress: TcxButtonEdit;
edtPerson: TcxButtonEdit;
edtTel: TcxButtonEdit;
grpComment: TGroupBox;
mmComment: TcxMemo;
protected
{ Private declarations }
procedure SetFrmData(ASender: TObject; AList: TParamObject); override;
procedure GetFrmData(ASender: TObject; AList: TParamObject); override;
procedure ClearFrmData; override;
public
{ Public declarations }
procedure BeforeFormShow; override;
class function GetMdlDisName: string; override; //得到模块显示名称
end;
var
frmBaseKtypeInput: TfrmBaseKtypeInput;
implementation
{$R *.dfm}
uses uSysSvc, uBaseFormPlugin, uBaseInfoDef, uModelBaseTypeIntf, uModelControlIntf, uOtherIntf, uDefCom;
{ TfrmBasePtypeInput }
procedure TfrmBaseKtypeInput.BeforeFormShow;
begin
SetTitle('仓库信息');
FModelBaseType := IModelBaseTypePtype((SysService as IModelControl).GetModelIntf(IModelBaseTypeKtype));
FModelBaseType.SetParamList(ParamList);
FModelBaseType.SetBasicType(btKtype);
DBComItem.AddItem(edtFullname, 'Fullname', 'KFullname');
DBComItem.AddItem(edtUsercode, 'Usercode', 'KUsercode');
DBComItem.AddItem(edtName, 'Name', 'Name');
DBComItem.AddItem(edtPYM, 'Namepy', 'Knamepy');
DBComItem.AddItem(edtAddress, 'Address', 'Address');
DBComItem.AddItem(edtPerson, 'Person', 'Person');
DBComItem.AddItem(edtTel, 'Tel', 'Tel');
DBComItem.AddItem(chkStop, 'IsStop', 'IsStop');
DBComItem.AddItem(mmComment, 'Comment', 'KComment');
inherited;
end;
procedure TfrmBaseKtypeInput.ClearFrmData;
begin
inherited;
end;
procedure TfrmBaseKtypeInput.GetFrmData(ASender: TObject;
AList: TParamObject);
begin
inherited;
AList.Add('@Parid', ParamList.AsString('ParId'));
DBComItem.SetDataToParam(AList);
if FModelBaseType.DataChangeType in [dctModif] then
begin
AList.Add('@typeId', ParamList.AsString('CurTypeid'));
end;
end;
class function TfrmBaseKtypeInput.GetMdlDisName: string;
begin
Result := '仓库信息';
end;
procedure TfrmBaseKtypeInput.SetFrmData(ASender: TObject;
AList: TParamObject);
begin
inherited;
DBComItem.GetDataFormParam(AList);
end;
end.
|
unit ibSHIndex;
interface
uses
SysUtils, Classes, Controls, Forms, Dialogs,
SHDesignIntf,
ibSHDesignIntf, ibSHDBObject;
type
TibBTIndex = class(TibBTDBObject, IibSHIndex)
private
FIndexTypeID: Integer;
FSortingID: Integer;
FStatusID: Integer;
FIndexType: string;
FSorting: string;
FTableName: string;
FExpression: TStrings;
FStatistics: string;
FStatus: string;
FIsConstraintIndex:boolean;
function GetIndexTypeID: Integer;
procedure SetIndexTypeID(Value: Integer);
function GetSortingID: Integer;
procedure SetSortingID(Value: Integer);
function GetStatusID: Integer;
procedure SetStatusID(Value: Integer);
function GetIndexType: string;
procedure SetIndexType(Value: string);
function GetSorting: string;
procedure SetSorting(Value: string);
function GetTableName: string;
procedure SetTableName(Value: string);
function GetExpression: TStrings;
procedure SetExpression(Value: TStrings);
function GetStatus: string;
procedure SetStatus(Value: string);
function GetStatistics: string;
procedure SetStatistics(Value: string);
procedure SetIsConstraintIndex(const Value:boolean);
function GetIsConstraintIndex:boolean;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure RecountStatistics;
property IndexTypeID: Integer read GetIndexTypeID write SetIndexTypeID;
property SortingID: Integer read GetSortingID write SetSortingID;
property StatusID: Integer read GetStatusID write SetStatusID;
published
property Description;
property IndexType: string read GetIndexType {write SetIndexType};
property Sorting: string read GetSorting {write SetSorting};
property TableName: string read GetTableName {write SetTableName};
property Fields;
// property Expression: TStrings read GetExpression write SetExpression;
property Status: string read GetStatus {write SetStatus};
property Statistics: string read GetStatistics{ write SetStatistics};
end;
implementation
uses
ibSHConsts, ibSHSQLs, ibSHValues;
{ TibBTIndex }
constructor TibBTIndex.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FExpression := TStringList.Create;
end;
destructor TibBTIndex.Destroy;
begin
FExpression.Free;
inherited Destroy;
end;
procedure TibBTIndex.RecountStatistics;
var
S, OldStatistics: string;
vCodeNormalizer: IibSHCodeNormalizer;
begin
S := Self.Caption;
if Supports(Designer.GetDemon(IibSHCodeNormalizer), IibSHCodeNormalizer, vCodeNormalizer) then
S := vCodeNormalizer.MetadataNameToSourceDDL(BTCLDatabase, S);
try
BTCLDatabase.DRVQuery.Transaction.Params.Text := TRWriteParams;
OldStatistics := Statistics;
BTCLDatabase.DRVQuery.ExecSQL(Format(FormatSQL(SQL_SET_STATISTICS), [S]), [], True);
finally
BTCLDatabase.DRVQuery.Transaction.Params.Text := TRReadParams;
Refresh;
end;
Designer.ShowMsg(Format('OLD_STATISTICS:' + SLineBreak +
'%s' + SLineBreak + SLineBreak +
'NEW_STATISTICS:' + SLineBreak +
'%s', [OldStatistics, Statistics]), mtInformation);
end;
function TibBTIndex.GetIndexTypeID: Integer;
begin
Result := FIndexTypeID;
end;
procedure TibBTIndex.SetIndexTypeID(Value: Integer);
begin
FIndexTypeID := Value;
end;
function TibBTIndex.GetSortingID: Integer;
begin
Result := FSortingID;
end;
procedure TibBTIndex.SetSortingID(Value: Integer);
begin
FSortingID := Value;
end;
function TibBTIndex.GetStatusID: Integer;
begin
Result := FStatusID;
end;
procedure TibBTIndex.SetStatusID(Value: Integer);
begin
FStatusID := Value;
end;
function TibBTIndex.GetIndexType: string;
begin
Result := FIndexType;
end;
procedure TibBTIndex.SetIndexType(Value: string);
begin
FIndexType := Value;
end;
function TibBTIndex.GetSorting: string;
begin
Result := FSorting;
end;
procedure TibBTIndex.SetSorting(Value: string);
begin
FSorting := Value;
end;
function TibBTIndex.GetTableName: string;
begin
Result := FTableName;
end;
procedure TibBTIndex.SetTableName(Value: string);
begin
FTableName := Value;
end;
function TibBTIndex.GetExpression: TStrings;
begin
Result := FExpression;
end;
procedure TibBTIndex.SetExpression(Value: TStrings);
begin
FExpression.Assign(Value);
end;
function TibBTIndex.GetStatus: string;
begin
Result := FStatus;
end;
procedure TibBTIndex.SetStatus(Value: string);
begin
FStatus := Value;
end;
function TibBTIndex.GetStatistics: string;
begin
Result := FStatistics;
end;
procedure TibBTIndex.SetStatistics(Value: string);
begin
FStatistics := Value;
end;
function TibBTIndex.GetIsConstraintIndex: boolean;
begin
Result:=FIsConstraintIndex
end;
procedure TibBTIndex.SetIsConstraintIndex(const Value: boolean);
begin
FIsConstraintIndex:=Value;
end;
end.
|
unit UDRunningTotals;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, UCrpe32;
type
TCrpeRunningTotalsDlg = class(TForm)
pnlRunningTotals: TPanel;
lblNumber: TLabel;
lbNumbers: TListBox;
editCount: TEdit;
lblCount: TLabel;
gbFormat: TGroupBox;
editFieldName: TEdit;
lblFieldName: TLabel;
lblFieldType: TLabel;
editFieldType: TEdit;
lblFieldLength: TLabel;
editFieldLength: TEdit;
btnBorder: TButton;
btnFont: TButton;
btnFormat: TButton;
editTop: TEdit;
lblTop: TLabel;
lblLeft: TLabel;
editLeft: TEdit;
lblSection: TLabel;
editWidth: TEdit;
lblWidth: TLabel;
lblHeight: TLabel;
editHeight: TEdit;
cbSection: TComboBox;
btnOk: TButton;
btnClear: TButton;
FontDialog1: TFontDialog;
editName: TEdit;
cbSummaryType: TComboBox;
editSummaryTypeN: TEdit;
cbSummaryTypeField: TComboBox;
cbSummaryField: TComboBox;
lblName: TLabel;
lineSummary: TBevel;
lblSummary: TLabel;
lblSummaryField: TLabel;
lblSummaryType: TLabel;
lblSummaryTypeN: TLabel;
lblEvaluate: TLabel;
lineEvaluate: TBevel;
pnlEvaluate: TPanel;
rbEvalNoCondition: TRadioButton;
rbEvalOnChangeField: TRadioButton;
rbEvalOnChangeGroup: TRadioButton;
rbEvalOnFormula: TRadioButton;
cbEvalField: TComboBox;
cbEvalGroup: TComboBox;
sbFormulaRed: TSpeedButton;
sbFormulaBlue: TSpeedButton;
sbEvalFormula: TSpeedButton;
lblReset: TLabel;
lineReset: TBevel;
pnlReset: TPanel;
sbResetFormula: TSpeedButton;
rbResetNoCondition: TRadioButton;
rbResetOnChangeField: TRadioButton;
rbResetOnChangeGroup: TRadioButton;
rbResetOnFormula: TRadioButton;
cbResetField: TComboBox;
cbResetGroup: TComboBox;
rgUnits: TRadioGroup;
btnHiliteConditions: TButton;
procedure btnClearClick(Sender: TObject);
procedure lbNumbersClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnFontClick(Sender: TObject);
procedure EditSizeEnter(Sender: TObject);
procedure EditSizeExit(Sender: TObject);
procedure cbSectionChange(Sender: TObject);
procedure btnBorderClick(Sender: TObject);
procedure rgUnitsClick(Sender: TObject);
procedure btnFormatClick(Sender: TObject);
procedure cbSummaryTypeChange(Sender: TObject);
procedure cbSummaryFieldChange(Sender: TObject);
procedure btnHiliteConditionsClick(Sender: TObject);
procedure rbEvalOnChangeFieldClick(Sender: TObject);
procedure rbEvalOnChangeGroupClick(Sender: TObject);
procedure rbEvalOnFormulaClick(Sender: TObject);
procedure rbResetNoConditionClick(Sender: TObject);
procedure rbEvalNoConditionClick(Sender: TObject);
procedure rbResetOnChangeFieldClick(Sender: TObject);
procedure rbResetOnChangeGroupClick(Sender: TObject);
procedure rbResetOnFormulaClick(Sender: TObject);
procedure editNameChange(Sender: TObject);
procedure cbSummaryTypeFieldChange(Sender: TObject);
procedure editSummaryTypeNChange(Sender: TObject);
procedure cbEvalFieldChange(Sender: TObject);
procedure cbEvalGroupChange(Sender: TObject);
procedure cbResetFieldChange(Sender: TObject);
procedure cbResetGroupChange(Sender: TObject);
procedure UpdateRunningTotals;
procedure InitializeControls(OnOff: boolean);
procedure InitializeFormatControls(OnOff: boolean);
procedure sbEvalFormulaClick(Sender: TObject);
procedure sbResetFormulaClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
RTIndex : integer;
PrevSize : string;
end;
var
CrpeRunningTotalsDlg: TCrpeRunningTotalsDlg;
bRunningTotals : boolean;
implementation
{$R *.DFM}
uses TypInfo, UCrpeUtl, UDBorder, UDFormat, UDHiliteConditions,
UDFormulaEdit, UDFont, UCrpeClasses;
{------------------------------------------------------------------------------}
{ FormCreate }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.FormCreate(Sender: TObject);
begin
bRunningTotals := True;
LoadFormPos(Self);
RTIndex := -1;
btnOk.Tag := 1;
end;
{------------------------------------------------------------------------------}
{ FormShow }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.FormShow(Sender: TObject);
begin
UpdateRunningTotals;
end;
{------------------------------------------------------------------------------}
{ UpdateRunningTotals }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.UpdateRunningTotals;
var
i : smallint;
OnOff : boolean;
begin
RTIndex := -1;
{Enable/Disable controls}
if IsStrEmpty(Cr.ReportName) then
OnOff := False
else
begin
OnOff := (Cr.RunningTotals.Count > 0);
{Get RunningTotal Index}
if OnOff then
begin
if Cr.RunningTotals.ItemIndex > -1 then
RTIndex := Cr.RunningTotals.ItemIndex
else
RTIndex := 0;
end;
end;
InitializeControls(OnOff);
{Update list box}
if OnOff = True then
begin
{Fill SummarizedField ComboBox}
cbSummaryField.Clear;
cbSummaryField.Items.AddStrings(Cr.Tables.FieldNames);
{Fill SummaryTypeField ComboBox}
cbSummaryTypeField.Clear;
cbSummaryTypeField.Items.AddStrings(Cr.Tables.FieldNames);
{Fill EvalField ComboBox}
cbEvalField.Clear;
cbEvalField.Items.AddStrings(Cr.Tables.FieldNames);
{Fill EvalGroup ComboBox}
cbEvalGroup.Clear;
cbEvalGroup.Items.AddStrings(Cr.Groups.Names);
{Fill ResetField ComboBox}
cbResetField.Clear;
cbResetField.Items.AddStrings(Cr.Tables.FieldNames);
{Fill ResetGroup ComboBox}
cbResetGroup.Clear;
cbResetGroup.Items.AddStrings(Cr.Groups.Names);
{Fill Section ComboBox}
cbSection.Clear;
cbSection.Items.AddStrings(Cr.SectionFormat.Names);
{Fill Numbers ListBox}
for i := 0 to Cr.RunningTotals.Count - 1 do
lbNumbers.Items.Add(IntToStr(i));
editCount.Text := IntToStr(Cr.RunningTotals.Count);
lbNumbers.ItemIndex := RTIndex;
lbNumbersClick(self);
end;
end;
{------------------------------------------------------------------------------}
{ InitializeControls }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.InitializeControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
if TComponent(Components[i]).Tag = 0 then
begin
if Components[i] is TButton then
TButton(Components[i]).Enabled := OnOff;
if Components[i] is TSpeedButton then
TSpeedButton(Components[i]).Enabled := OnOff;
if Components[i] is TCheckBox then
TCheckBox(Components[i]).Enabled := OnOff;
if Components[i] is TRadioGroup then
TRadioGroup(Components[i]).Enabled := OnOff;
if Components[i] is TRadioButton then
TRadioButton(Components[i]).Enabled := OnOff;
if Components[i] is TComboBox then
begin
TComboBox(Components[i]).Color := ColorState(OnOff);
TComboBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TListBox then
begin
TListBox(Components[i]).Clear;
TListBox(Components[i]).Color := ColorState(OnOff);
TListBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TEdit then
begin
TEdit(Components[i]).Text := '';
if TEdit(Components[i]).ReadOnly = False then
TEdit(Components[i]).Color := ColorState(OnOff);
TEdit(Components[i]).Enabled := OnOff;
end;
end;
end;
end;
{------------------------------------------------------------------------------}
{ InitializeFormatControls }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.InitializeFormatControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
{Check Tag}
if TComponent(Components[i]).Tag <> 0 then
Continue;
{Make sure these components are owned by the Format groupbox}
if Components[i] is TButton then
begin
if TButton(Components[i]).Parent <> gbFormat then Continue;
TButton(Components[i]).Enabled := OnOff;
end;
if Components[i] is TRadioGroup then
begin
if TRadioGroup(Components[i]).Parent <> gbFormat then Continue;
TRadioGroup(Components[i]).Enabled := OnOff;
end;
if Components[i] is TComboBox then
begin
if TComboBox(Components[i]).Parent <> gbFormat then Continue;
TComboBox(Components[i]).Color := ColorState(OnOff);
TComboBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TEdit then
begin
if TEdit(Components[i]).Parent <> gbFormat then Continue;
TEdit(Components[i]).Text := '';
if TEdit(Components[i]).ReadOnly = False then
TEdit(Components[i]).Color := ColorState(OnOff);
TEdit(Components[i]).Enabled := OnOff;
end;
end;
end;
{------------------------------------------------------------------------------}
{ lbNumbersClick }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.lbNumbersClick(Sender: TObject);
var
i : integer;
FieldInfo : TCrFieldInfo;
OnOff : Boolean;
begin
RTIndex := lbNumbers.ItemIndex;
{Name}
editName.OnChange := nil;
editName.Text := Cr.RunningTotals[RTIndex].Name;
editName.OnChange := editNameChange;
{SummaryField}
cbSummaryField.OnChange := nil;
cbSummaryField.ItemIndex := cbSummaryField.Items.IndexOf(Cr.RunningTotals.Item.SummaryField);
cbSummaryField.OnChange := cbSummaryFieldChange;
{Fill SummaryType ComboBox - Integer gets all options}
cbSummaryType.OnChange := nil;
cbSummaryType.Clear;
FieldInfo := Cr.FieldNameToFieldInfo(Cr.RunningTotals.Item.SummaryField);
Cr.Tables.GetFieldInfo(FieldInfo);
if FieldInfo.FieldType in [fvInt8s..fvCurrency] then
begin
cbSummaryType.Items.Add('stSum');
cbSummaryType.Items.Add('stAverage');
cbSummaryType.Items.Add('stSampleVariance');
cbSummaryType.Items.Add('stSampleStdDev');
cbSummaryType.Items.Add('stMaximum');
cbSummaryType.Items.Add('stMinimum');
cbSummaryType.Items.Add('stCount');
cbSummaryType.Items.Add('stPopVariance');
cbSummaryType.Items.Add('stPopStdDev');
cbSummaryType.Items.Add('stDistinctCount');
cbSummaryType.Items.Add('stCorrelation');
cbSummaryType.Items.Add('stCoVariance');
cbSummaryType.Items.Add('stWeightedAvg');
cbSummaryType.Items.Add('stMedian');
cbSummaryType.Items.Add('stPercentile');
cbSummaryType.Items.Add('stNthLargest');
cbSummaryType.Items.Add('stNthSmallest');
cbSummaryType.Items.Add('stMode');
cbSummaryType.Items.Add('stNthMostFrequent');
cbSummaryType.Items.Add('stPercentage');
cbSummaryType.ItemIndex := Ord(Cr.RunningTotals.Item.SummaryType);
end
{Fill SummaryType ComboBox - String/Date/Time,etc. only get some options}
else
begin
cbSummaryType.Items.Add('stMaximum');
cbSummaryType.Items.Add('stMinimum');
cbSummaryType.Items.Add('stCount');
cbSummaryType.Items.Add('stDistinctCount');
cbSummaryType.Items.Add('stNthLargest');
cbSummaryType.Items.Add('stNthSmallest');
cbSummaryType.Items.Add('stMode');
cbSummaryType.Items.Add('stNthMostFrequent');
cbSummaryType.Items.Add('stPercentage');
case Cr.RunningTotals.Item.SummaryType of
stMaximum : cbSummaryType.ItemIndex := 0;
stMinimum : cbSummaryType.ItemIndex := 1;
stCount : cbSummaryType.ItemIndex := 2;
stDistinctCount : cbSummaryType.ItemIndex := 3;
stNthLargest : cbSummaryType.ItemIndex := 4;
stNthSmallest : cbSummaryType.ItemIndex := 5;
stMode : cbSummaryType.ItemIndex := 6;
stNthMostFrequent : cbSummaryType.ItemIndex := 7;
stPercentage : cbSummaryType.ItemIndex := 8;
else
cbSummaryType.ItemIndex := 0;
end;
end;
cbSummaryType.OnChange := cbSummaryTypeChange;
{SummaryTypeN/Field}
editSummaryTypeN.OnChange := nil;
cbSummaryTypeField.OnChange := nil;
editSummaryTypeN.Text := IntToStr(Cr.RunningTotals.Item.SummaryTypeN);
case Cr.RunningTotals.Item.SummaryType of
stSum,
stAverage,
stSampleVariance,
stSampleStdDev,
stMaximum,
stMinimum,
stCount,
stPopVariance,
stPopStdDev,
stDistinctCount,
stMedian,
stMode :
begin
lblSummaryTypeN.Visible := False;
editSummaryTypeN.Visible := False;
cbSummaryTypeField.Visible := False;
end;
{Use SummaryTypeField}
stCorrelation,
stCoVariance,
stWeightedAvg :
begin
lblSummaryTypeN.Visible := True;
editSummaryTypeN.Visible := False;
cbSummaryTypeField.Visible := True;
cbSummaryTypeField.ItemIndex := cbSummaryTypeField.Items.IndexOf(Cr.RunningTotals.Item.SummaryTypeField);
end;
{Use SummaryTypeN}
stPercentile,
stNthLargest,
stNthSmallest,
stNthMostFrequent :
begin
lblSummaryTypeN.Visible := True;
cbSummaryTypeField.Visible := False;
editSummaryTypeN.Visible := True;
end;
{Use SummaryTypeField with GrandTotal field}
stPercentage :
begin
lblSummaryTypeN.Visible := True;
editSummaryTypeN.Visible := False;
cbSummaryTypeField.Visible := True;
i := cbSummaryTypeField.Items.IndexOf(Cr.RunningTotals.Item.SummaryTypeField);
if i > -1 then
cbSummaryTypeField.ItemIndex := i
else
cbSummaryTypeField.Text := Cr.RunningTotals.Item.SummaryTypeField;
end;
end;
editSummaryTypeN.OnChange := editSummaryTypeNChange;
cbSummaryTypeField.OnChange := cbSummaryTypeFieldChange;
{Evaluate}
case Cr.RunningTotals.Item.EvalCondition of
rtcNoCondition : rbEvalNoConditionClick(Self);
rtcOnChangeField : rbEvalOnChangeFieldClick(Self);
rtcOnChangeGroup :
begin
if Cr.Groups.Count > 0 then
rbEvalOnChangeGroupClick(Self)
else
rbEvalNoConditionClick(Self);
end;
rtcOnFormula : rbEvalOnFormulaClick(Self);
end;
{Reset}
case Cr.RunningTotals.Item.ResetCondition of
rtcNoCondition : rbResetNoConditionClick(Self);
rtcOnChangeField : rbResetOnChangeFieldClick(Self);
rtcOnChangeGroup :
begin
if Cr.Groups.Count > 0 then
rbResetOnChangeGroupClick(Self)
else
rbResetNoConditionClick(Self);
end;
rtcOnFormula : rbResetOnFormulaClick(Self);
end;
{Activate Format options}
OnOff := Cr.RunningTotals.Handle > 0;
InitializeFormatControls(OnOff);
if OnOff then
begin
{Field Info}
editFieldName.Text := Cr.RunningTotals.Item.FieldName;
editFieldType.Text := GetEnumName(TypeInfo(TCrFieldValueType),
Ord(Cr.RunningTotals.Item.FieldType));
editFieldLength.Text := IntToStr(Cr.RunningTotals.Item.FieldLength);
{Size and Position}
cbSection.ItemIndex := Cr.SectionFormat.IndexOf(Cr.RunningTotals.Item.Section);
rgUnitsClick(Self);
end;
{Set HiliteConditions button}
btnHiliteConditions.Enabled := (Cr.RunningTotals.Item.FieldType in [fvInt8s..fvCurrency])
and OnOff;
end;
{------------------------------------------------------------------------------}
{ cbSummaryFieldChange }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.cbSummaryFieldChange(Sender: TObject);
begin
Cr.RunningTotals.Item.SummaryField := cbSummaryField.Text;
UpdateRunningTotals; {needed to refresh SummaryType combo-box}
end;
{------------------------------------------------------------------------------}
{ cbSummaryTypeChange }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.cbSummaryTypeChange(Sender: TObject);
var
i : integer;
x : integer;
begin
x := GetEnumValue(TypeInfo(TCrSummaryType), cbSummaryType.Text);
Cr.RunningTotals.Item.SummaryType := TCrSummaryType(x);
case Cr.RunningTotals.Item.SummaryType of
stSum,
stAverage,
stSampleVariance,
stSampleStdDev,
stMaximum,
stMinimum,
stCount,
stPopVariance,
stPopStdDev,
stDistinctCount,
stMedian,
stMode :
begin
lblSummaryTypeN.Visible := False;
editSummaryTypeN.Visible := False;
cbSummaryTypeField.Visible := False;
end;
{Use SummaryTypeField}
stCorrelation,
stCoVariance,
stWeightedAvg :
begin
lblSummaryTypeN.Visible := True;
editSummaryTypeN.Visible := False;
cbSummaryTypeField.Visible := True;
cbSummaryTypeField.ItemIndex := cbSummaryTypeField.Items.IndexOf(Cr.RunningTotals.Item.SummaryTypeField);
end;
{Use SummaryTypeN}
stPercentile,
stNthLargest,
stNthSmallest,
stNthMostFrequent :
begin
lblSummaryTypeN.Visible := True;
cbSummaryTypeField.Visible := False;
editSummaryTypeN.Visible := True;
editSummaryTypeN.Text := IntToStr(Cr.RunningTotals.Item.SummaryTypeN);
end;
{Use SummaryTypeField with GrandTotal field}
stPercentage :
begin
lblSummaryTypeN.Visible := True;
editSummaryTypeN.Visible := False;
cbSummaryTypeField.Visible := True;
i := cbSummaryTypeField.Items.IndexOf(Cr.RunningTotals.Item.SummaryTypeField);
if i > -1 then
cbSummaryTypeField.ItemIndex := i
else
cbSummaryTypeField.Text := Cr.RunningTotals.Item.SummaryTypeField;
end;
end;
end;
{------------------------------------------------------------------------------}
{ rbEvalNoConditionClick }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.rbEvalNoConditionClick(Sender: TObject);
begin
Cr.RunningTotals.Item.EvalCondition := rtcNoCondition;
rbEvalNoCondition.Checked := True;
sbEvalFormula.Enabled := False;
end;
{------------------------------------------------------------------------------}
{ rbEvalOnChangeFieldClick }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.rbEvalOnChangeFieldClick(Sender: TObject);
begin
rbEvalOnChangeField.Checked := True;
sbEvalFormula.Enabled := False;
cbEvalGroup.ItemIndex := -1;
Cr.RunningTotals.Item.EvalCondition := rtcOnChangeField;
cbEvalField.ItemIndex := cbEvalField.Items.IndexOf(Cr.RunningTotals.Item.EvalField);
if cbEvalField.ItemIndex = -1 then
cbEvalField.ItemIndex := 0;
end;
{------------------------------------------------------------------------------}
{ rbEvalOnChangeGroupClick }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.rbEvalOnChangeGroupClick(Sender: TObject);
begin
if Cr.Groups.Count > 0 then
begin
rbEvalOnChangeGroup.Checked := True;
sbEvalFormula.Enabled := False;
cbEvalField.ItemIndex := -1;
Cr.RunningTotals.Item.EvalCondition := rtcOnChangeGroup;
cbEvalGroup.ItemIndex := Cr.RunningTotals.Item.EvalGroupN;
end
else
begin
rbEvalNoConditionClick(Self);
end;
end;
{------------------------------------------------------------------------------}
{ rbEvalOnFormulaClick }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.rbEvalOnFormulaClick(Sender: TObject);
begin
Cr.RunningTotals.Item.EvalCondition := rtcOnFormula;
rbEvalOnFormula.Checked := True;
sbEvalFormula.Enabled := True;
if not IsStringListEmpty(Cr.RunningTotals.Item.EvalFormula) then
begin
if sbEvalFormula.Glyph <> sbFormulaRed.Glyph then
sbEvalFormula.Glyph := sbFormulaRed.Glyph;
end
else
begin
if sbEvalFormula.Glyph <> sbFormulaBlue.Glyph then
sbEvalFormula.Glyph := sbFormulaBlue.Glyph
end;
end;
{------------------------------------------------------------------------------}
{ rbResetNoConditionClick }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.rbResetNoConditionClick(Sender: TObject);
begin
Cr.RunningTotals.Item.ResetCondition := rtcNoCondition;
rbResetNoCondition.Checked := True;
sbResetFormula.Enabled := False;
end;
{------------------------------------------------------------------------------}
{ rbResetOnChangeFieldClick }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.rbResetOnChangeFieldClick(Sender: TObject);
begin
rbResetOnChangeField.Checked := True;
sbResetFormula.Enabled := False;
cbResetGroup.ItemIndex := -1;
Cr.RunningTotals.Item.ResetCondition := rtcOnChangeField;
cbResetField.ItemIndex := cbResetField.Items.IndexOf(Cr.RunningTotals.Item.ResetField);
if cbResetField.ItemIndex = -1 then
cbResetField.ItemIndex := 0;
end;
{------------------------------------------------------------------------------}
{ rbResetOnChangeGroupClick }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.rbResetOnChangeGroupClick(Sender: TObject);
begin
if Cr.Groups.Count > 0 then
begin
Cr.RunningTotals.Item.ResetCondition := rtcOnChangeGroup;
rbResetOnChangeGroup.Checked := True;
sbResetFormula.Enabled := False;
cbResetGroup.ItemIndex := Cr.RunningTotals.Item.ResetGroupN;
end
else
begin
rbResetNoConditionClick(Self);
end;
end;
{------------------------------------------------------------------------------}
{ rbResetOnFormulaClick }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.rbResetOnFormulaClick(Sender: TObject);
begin
Cr.RunningTotals.Item.ResetCondition := rtcOnFormula;
rbResetOnFormula.Checked := True;
sbResetFormula.Enabled := True;
if not IsStringListEmpty(Cr.RunningTotals.Item.ResetFormula) then
begin
if sbResetFormula.Glyph <> sbFormulaRed.Glyph then
sbResetFormula.Glyph := sbFormulaRed.Glyph;
end
else
begin
if sbResetFormula.Glyph <> sbFormulaBlue.Glyph then
sbResetFormula.Glyph := sbFormulaBlue.Glyph
end;
end;
{------------------------------------------------------------------------------}
{ editNameChange }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.editNameChange(Sender: TObject);
begin
Cr.RunningTotals.Item.Name := editName.Text;
end;
{------------------------------------------------------------------------------}
{ cbSummaryTypeFieldChange }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.cbSummaryTypeFieldChange(Sender: TObject);
begin
Cr.RunningTotals.Item.SummaryTypeField := cbSummaryTypeField.Text;
end;
{------------------------------------------------------------------------------}
{ editSummaryTypeNChange }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.editSummaryTypeNChange(Sender: TObject);
begin
if IsNumeric(editSummaryTypeN.Text) then
Cr.RunningTotals.Item.SummaryTypeN := StrToInt(editSummaryTypeN.Text);
end;
{------------------------------------------------------------------------------}
{ cbEvalFieldChange }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.cbEvalFieldChange(Sender: TObject);
begin
Cr.RunningTotals.Item.EvalField := cbEvalField.Text;
end;
{------------------------------------------------------------------------------}
{ cbEvalGroupChange }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.cbEvalGroupChange(Sender: TObject);
begin
Cr.RunningTotals.Item.EvalGroupN := cbEvalGroup.ItemIndex;
end;
{------------------------------------------------------------------------------}
{ sbEvalFormulaClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.sbEvalFormulaClick(Sender: TObject);
var
xList : TStrings;
begin
xList := Cr.RunningTotals.Item.EvalFormula;
{Create the Formula editing form}
CrpeFormulaEditDlg := TCrpeFormulaEditDlg.Create(Application);
CrpeFormulaEditDlg.SenderList := xList;
CrpeFormulaEditDlg.Caption := TSpeedButton(Sender).Hint;
CrpeFormulaEditDlg.ShowModal;
{Update the main form}
lbNumbersClick(Self);
end;
{------------------------------------------------------------------------------}
{ cbResetFieldChange }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.cbResetFieldChange(Sender: TObject);
begin
Cr.RunningTotals.Item.ResetField := cbResetField.Text;
end;
{------------------------------------------------------------------------------}
{ cbResetGroupChange }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.cbResetGroupChange(Sender: TObject);
begin
Cr.RunningTotals.Item.ResetGroupN := cbResetGroup.ItemIndex;
end;
{------------------------------------------------------------------------------}
{ sbResetFormulaClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.sbResetFormulaClick(Sender: TObject);
var
xList : TStrings;
begin
xList := Cr.RunningTotals.Item.ResetFormula;
{Create the Formula editing form}
CrpeFormulaEditDlg := TCrpeFormulaEditDlg.Create(Application);
CrpeFormulaEditDlg.SenderList := xList;
CrpeFormulaEditDlg.Caption := TSpeedButton(Sender).Hint;
CrpeFormulaEditDlg.ShowModal;
{Update the main form}
lbNumbersClick(Self);
end;
{------------------------------------------------------------------------------}
{ rgUnitsClick }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.rgUnitsClick(Sender: TObject);
begin
if rgUnits.ItemIndex = 0 then {inches}
begin
editTop.Text := TwipsToInchesStr(Cr.RunningTotals.Item.Top);
editLeft.Text := TwipsToInchesStr(Cr.RunningTotals.Item.Left);
editWidth.Text := TwipsToInchesStr(Cr.RunningTotals.Item.Width);
editHeight.Text := TwipsToInchesStr(Cr.RunningTotals.Item.Height);
end
else {twips}
begin
editTop.Text := IntToStr(Cr.RunningTotals.Item.Top);
editLeft.Text := IntToStr(Cr.RunningTotals.Item.Left);
editWidth.Text := IntToStr(Cr.RunningTotals.Item.Width);
editHeight.Text := IntToStr(Cr.RunningTotals.Item.Height);
end;
end;
{------------------------------------------------------------------------------}
{ EditSizeEnter }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.EditSizeEnter(Sender: TObject);
begin
if Sender is TEdit then
PrevSize := TEdit(Sender).Text;
end;
{------------------------------------------------------------------------------}
{ EditSizeExit }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.EditSizeExit(Sender: TObject);
begin
if rgUnits.ItemIndex = 0 then {inches}
begin
if not IsFloating(TEdit(Sender).Text) then
TEdit(Sender).Text := PrevSize
else
begin
if TEdit(Sender).Name = 'editTop' then
Cr.RunningTotals.Item.Top := InchesStrToTwips(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editLeft' then
Cr.RunningTotals.Item.Left := InchesStrToTwips(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editWidth' then
Cr.RunningTotals.Item.Width := InchesStrToTwips(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editHeight' then
Cr.RunningTotals.Item.Height := InchesStrToTwips(TEdit(Sender).Text);
UpdateRunningTotals; {this will truncate any decimals beyond 3 places}
end;
end
else {twips}
begin
if not IsNumeric(TEdit(Sender).Text) then
TEdit(Sender).Text := PrevSize
else
begin
if TEdit(Sender).Name = 'editTop' then
Cr.RunningTotals.Item.Top := StrToInt(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editLeft' then
Cr.RunningTotals.Item.Left := StrToInt(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editWidth' then
Cr.RunningTotals.Item.Width := StrToInt(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editHeight' then
Cr.RunningTotals.Item.Height := StrToInt(TEdit(Sender).Text);
end;
end;
end;
{------------------------------------------------------------------------------}
{ cbSectionChange }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.cbSectionChange(Sender: TObject);
begin
Cr.RunningTotals.Item.Section := cbSection.Items[cbSection.ItemIndex];
end;
{------------------------------------------------------------------------------}
{ btnBorderClick }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.btnBorderClick(Sender: TObject);
begin
CrpeBorderDlg := TCrpeBorderDlg.Create(Application);
CrpeBorderDlg.Border := Cr.RunningTotals.Item.Border;
CrpeBorderDlg.ShowModal;
end;
{------------------------------------------------------------------------------}
{ btnFontClick }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.btnFontClick(Sender: TObject);
begin
if Cr.Version.Crpe.Major > 7 then
begin
CrpeFontDlg := TCrpeFontDlg.Create(Application);
CrpeFontDlg.Crf := Cr.RunningTotals.Item.Font;
CrpeFontDlg.ShowModal;
end
else
begin
FontDialog1.Font.Assign(Cr.RunningTotals.Item.Font);
if FontDialog1.Execute then
Cr.RunningTotals.Item.Font.Assign(FontDialog1.Font);
end;
end;
{------------------------------------------------------------------------------}
{ btnFormatClick }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.btnFormatClick(Sender: TObject);
begin
CrpeFormatDlg := TCrpeFormatDlg.Create(Application);
CrpeFormatDlg.Format := Cr.RunningTotals.Item.Format;
CrpeFormatDlg.ShowModal;
end;
{------------------------------------------------------------------------------}
{ btnHiliteConditionsClick }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.btnHiliteConditionsClick(Sender: TObject);
begin
CrpeHiliteConditionsDlg := TCrpeHiliteConditionsDlg.Create(Application);
CrpeHiliteConditionsDlg.Crh := Cr.RunningTotals.Item.HiliteConditions;
CrpeHiliteConditionsDlg.ShowModal;
end;
{------------------------------------------------------------------------------}
{ btnClearClick }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.btnClearClick(Sender: TObject);
begin
Cr.RunningTotals.Clear;
UpdateRunningTotals;
end;
{------------------------------------------------------------------------------}
{ btnOkClick }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.btnOkClick(Sender: TObject);
begin
rgUnits.ItemIndex := 1; {change to twips to avoid the UpdateRunningTotals call}
if (not IsStrEmpty(Cr.ReportName)) and (RTIndex > -1) then
begin
editSizeExit(editTop);
editSizeExit(editLeft);
editSizeExit(editWidth);
editSizeExit(editHeight);
end;
SaveFormPos(Self);
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose }
{------------------------------------------------------------------------------}
procedure TCrpeRunningTotalsDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
bRunningTotals := False;
Release;
end;
end.
|
uses Crt;
const
N = 4; // количество проектов
M = 5; // бюджет (в млн.)
type
Table = record // Таблица:{ сумма, план:[] }
Sum: real;
Plan: array[1..N] of real;
end;
//доходность
const Profitability: array[0..M, 1..N] of real = (
(0.00, 0.00, 0.00, 0.00),
(0.28, 0.25, 0.15, 0.20),
(0.23, 0.21, 0.13, 0.18),
(0.22, 0.18, 0.13, 0.14),
(0.20, 0.16, 0.13, 0.12),
(0.18, 0.15, 0.12, 0.11)
);
var
Income: array[0..M, 1..N] of real; // доход
Optimal: array[0..M, 1..N] of Table; // оптимальные планы
Best: array [0..M] of real; // суммы оптимальных
maxI: integer; // индекс максимального
answerIncome :string; // строка ответа c доходом
begin
writeln();
writeln('Моделирования оптимального плана инвестиций методом Беллмана.');
writeln();
for var i := 0 to M do begin
for var k := 1 to N do begin
Income[i,k] := Profitability[i,k] * i;
end;
end;
for var i := 0 to M do begin
for var k := 1 to N do begin
Optimal[i,k].Sum := 0;
for var j := 1 to N do
Optimal[i,k].Plan[j] := 0;
end;
end;
for var i:=0 to M do begin
Optimal[i,1].Sum := Income[i,1];
Optimal[i,1].Plan[1] := i;
end;
for var i := 0 to M do begin
for var k := 2 to N do begin
for var j := 0 to i do begin
Best[j] := Optimal[j,k-1].Sum + Income[i-j,k];
end;
maxI:=0;
for var j := 0 to i do begin
if (Best[j] > Best[maxI]) then
maxI:=j;
end;
Optimal[i,k].Sum := Best[maxI];
Optimal[i,k].Plan := Optimal[maxI,k-1].Plan;
Optimal[i,k].Plan[k] := i - maxI;
end;
end;
writeln('Оптимальный план инвестиций:');
writeln('------------------------------');
for var i:=1 to N do begin
writeln('В проект №' + IntToStr(i) + ' инвестировать ' + IntToStr(round(Optimal[M,N].Plan[i])) + 'млн.');
end;
writeln('------------------------------');
str(Optimal[M,N].Sum:5:2, answerIncome);
writeln('Планируется получить доход: ' + answerIncome + ' млн.');
end. |
unit gsf_Date;
{-----------------------------------------------------------------------------
Date Processor
gsf_Date Copyright (c) 1996 Griffin Solutions, Inc.
Date
4 Apr 1996
Programmer:
Richard F. Griffin tel: (912) 953-2680
Griffin Solutions, Inc. e-mail: grifsolu@hom.net
102 Molded Stone Pl
Warner Robins, GA 31088
Modified (m) 1997-2000 by Valery Votintsev 2:5021/22
-------------------------------------------------------------
This unit handles date conversion.
Acknowledgements:
An astronomers' Julian day number is a calendar system which is useful
over a very large span of time. (January 1, 1988 A.D. is 2,447,162 in
this system.) The mathematics of these procedures originally restricted
the valid range to March 1, 0000 through February 28, 4000. The update
by Carley Phillips changes the valid end date to December 31, 65535.
The basic algorithms are based on those contained in the COLLECTED
ALGORITHMS from Communications of the ACM, algorithm number 199,
originally submitted by Robert G. Tantzen in the August, 1963 issue
(Volume 6, Number 8). Note that these algorithms do not take into
account that years divisible by 4000 are NOT leap years. Therefore the
calculations are only valid until 02-28-4000. These procedures were
modified by Carley Phillips (76630,3312) to provide a mathematically
valid range of 03-01-0000 through 12-31-65535.
The main part of Tantzen's original algorithm depends on treating
January and February as the last months of the preceding year. Then,
one can look at a series of four years (for example, 3-1-84 through
2-29-88) in which the last day will be either the 1460th or the 1461st
day depending on whether the 4-year series ended in a leap day.
By assigning a longint julian date, computing differences between
dates, adding days to an existing date, and other mathematical actions
become much easier.
Changes:
18 Apr 96 - Added GSbytNextCentury variable in gsf_Glbl to allow
the programmer to determine a limit year that will
use the next century instead of the current century
when the actual century is unknown (e.g. 04/18/96).
Any year equal to or greater than GSbytNextCentury
will use the current centruy. Any value lower will
use the next century. Default is 0 (unused)
The variable was added because many routines for date
entry do not allow including the century as part of
the entry field. Thus, as the year 2000 approaches,
there must be some method to resolve unknown century
issues. While this method is limited, it does offer
a solution for the majority of potential problems.
For example;
if GSbytNextCentury = 5, then
04/18/04 would be treated as 18 April, 2004
04/18/05 would be treated as 18 April, 1905
This is used in GS_Date_CurCentury to return the
'correct' century when the century is unknown.
010898 - Added routine to automtatically set the correct date
format in Delphi. This is based on the Windows date
format.
------------------------------------------------------------------------------}
{$I gsf_FLAG.PAS}
interface
Uses
gsf_DOS,
vString,
gsf_Glbl;
{private}
type
GS_Date_StrTyp = String[10];
GS_Date_ValTyp = longint;
GS_Date_CenTyp = String[2];
const
GS_Date_Empty:GS_Date_StrTyp = ' . . ';{constant for invalid Julian day}
GS_Date_JulInv = -1; {constant for invalid Julian day}
GS_Date_JulMty = 0; {constant for blank julian entry}
MonthNames:String[48] ='JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC ';
const
GSblnUseCentury : Boolean = false;
GSbytNextCentury : Byte = 0;
GSsetDateType : GSsetDateTypes = American;
Var
Today: GS_Date_ValTyp;
function GS_Date_CurCentury(yr: integer) : GS_Date_CenTyp;
function GS_Date_Curr : GS_Date_ValTyp;
function GS_Date_DBLoad(sdate: GS_Date_StrTyp): GS_Date_ValTyp;
function GS_Date_DBStor(nv : GS_Date_ValTyp) : GS_Date_StrTyp;
function GS_Date_View(nv: GS_Date_ValTyp): GS_Date_StrTyp;
function GS_Date_Juln(sdate : GS_Date_StrTyp) : GS_Date_ValTyp;
function GS_Date_MDY2Jul(month, day, year : word) : GS_Date_ValTyp;
procedure GS_Date_Jul2MDY(jul : GS_Date_ValTyp; var month, day, year : word);
function DateStrOk (cDate:Gs_Date_StrTyp) : boolean;
Function CNMONTH(Line:Gs_Date_StrTyp):Gs_Date_StrTyp;
Function ParseDateStr(S:String):Gs_Date_StrTyp;
implementation
const
JulianConstant = 1721119; {constant for Julian day for 02-28-0000}
JulianMin = 1721120; {constant for Julian day for 03-01-0000}
JulianMax = 25657575; {constant for Julian day for 12-31-65535}
type
Str4 = String[4];
{*──────────────────────────────────────────*}
Function CNMONTH(Line:Gs_Date_StrTyp):Gs_Date_StrTyp;
{--- Convert Month Name to Month Number }
Var
n,e:integer;
S:Gs_Date_StrTyp;
begin
n:=(Pos(UPPER(Line),MonthNames) div 4) + 1;
Str(n:2,S);
If S[1]=' ' then S[1]:='0';
CNMONTH:=S;
end;
{*──────────────────────────────────────────*}
Function ParseDateStr(S:String):Gs_Date_StrTyp;
{--- Parse Date String & Form DB Date Field }
Var
n:integer;
cDay,cMonth,cYear:String[4];
begin
S := AllTrim(S);
n := AT(', ',S); {Strip the Day of Week}
If n = 4 then S:=Substr(S,n+2,255);
cDay := Substr(S,1,2);
cMonth:= CnMonth(Substr(S,4,3));
cYear := Substr(S,8,4);
n := AT(' ',cYear); {Check Year for 2 or 4 digits}
If n > 0 then cYear:=Substr(cYear,1,n-1);
If Length(cYear)=2 then begin
If cYear[1]>'5' then
cYear:= '19'+cYear
else
cYear:= '20'+cYear;
end;
ParseDateStr:=cYear+cMonth+cDay;
end;
{*──────────────────────────────────────────*}
function DateType_MDY(mm, dd, yy: Str4): GS_Date_StrTyp;
var
ss : String[10];
begin
case GSsetDateType of
American,
MDY : ss := ' / / ';
USA : ss := ' - - ';
end;
if not GSblnUseCentury then Delete(ss,9,2);
if mm <> '' then
begin
move(mm[1],ss[1],2);
move(dd[1],ss[4],2);
if GSblnUseCentury then
move(yy[1],ss[7],4)
else
move(yy[3],ss[7],2);
end;
DateType_MDY := ss;
end;
function DateType_DMY(mm, dd, yy: Str4): GS_Date_StrTyp;
var
ss : String[10];
begin
case GSsetDateType of
British,
French,
DMY : ss := ' / / ';
German : ss := ' . . ';
Italian : ss := ' - - ';
end;
if not GSblnUseCentury then Delete(ss,9,2);
if mm <> '' then
begin
move(dd[1],ss[1],2);
move(mm[1],ss[4],2);
if GSblnUseCentury then
move(yy[1],ss[7],4)
else
move(yy[3],ss[7],2);
end;
DateType_DMY := ss;
end;
function DateType_YMD(mm, dd, yy: Str4): GS_Date_StrTyp;
var
ss : String[10];
begin
case GSsetDateType of
Japan,
YMD : ss := ' / / ';
ANSI : ss := ' . . ';
end;
if not GSblnUseCentury then system.Delete(ss,1,2);
if mm <> '' then
begin
if GSblnUseCentury then
begin
move(yy[1],ss[1],4);
move(mm[1],ss[6],2);
move(dd[1],ss[9],2);
end
else
begin
move(yy[3],ss[1],2);
move(mm[1],ss[4],2);
move(dd[1],ss[7],2);
end;
end;
DateType_YMD := ss;
end;
function LeapYearTrue (year : word) : boolean;
begin
LeapYearTrue := false;
if (year mod 4 = 0) then
if (year mod 100 <> 0) or (year mod 400 = 0) then
if (year mod 4000 <> 0) then
LeapYearTrue := true;
end;
function DateOk (month, day, year : word) : boolean;
var
daz : integer;
begin
if (day <> 0) and
((month > 0) and (month < 13)) and
((year <> 0) or (month > 2)) then
begin
case month of
2 : begin
daz := 28;
if (LeapYearTrue(year)) then inc(daz);
end;
4,
6,
9,
11 : daz := 30;
else daz := 31;
end;
DateOk := day <= daz;
end
else DateOk := false;
end;
function DateStrOk (cDate:Gs_Date_StrTyp) : boolean;
var
rsl:integer;
month, day, year : word;
s:string[4];
begin
If cDate = GS_Date_Empty then DateStrOk := True
else begin
s:=System.copy(cDate,1,2);
val(s,day,rsl);
s:=System.copy(cDate,4,2);
val(s,month,rsl);
{ If GSblnUseCentury then
s:=System.copy(cDate,7,4)
else}
s:=System.copy(cDate,7,2);
val(s,year,rsl);
s:= GS_Date_CurCentury(year) + s;
val(s,year,rsl);
DateStrOk := DateOk(month, day, year);
end;
end;
function GS_Date_MDY2Jul(month, day, year : word) : GS_Date_ValTyp;
var
wmm,
wyy,
jul : longint;
begin
wyy := year;
if (month > 2) then wmm := month - 3
else
begin
wmm := month + 9;
dec(wyy);
end;
jul := (wyy div 4000) * 1460969;
wyy := (wyy mod 4000);
jul := jul +
(((wyy div 100) * 146097) div 4) +
(((wyy mod 100) * 1461) div 4) +
(((153 * wmm) + 2) div 5) +
day +
JulianConstant;
if (jul < JulianMin) or (JulianMax < jul) then
jul := GS_Date_JulInv;
GS_Date_MDY2Jul := jul;
end;
procedure GS_Date_Jul2MDY(jul : GS_Date_ValTyp; var month, day, year : word);
var
tmp1 : longint;
tmp2 : longint;
begin
if (JulianMin <= jul) and (jul <= JulianMax) then
begin
tmp1 := jul - JulianConstant; {will be at least 1}
year := ((tmp1-1) div 1460969) * 4000;
tmp1 := ((tmp1-1) mod 1460969) + 1;
tmp1 := (4 * tmp1) - 1;
tmp2 := (4 * ((tmp1 mod 146097) div 4)) + 3;
year := (100 * (tmp1 div 146097)) + (tmp2 div 1461) + year;
tmp1 := (5 * (((tmp2 mod 1461) + 4) div 4)) - 3;
month := tmp1 div 153;
day := ((tmp1 mod 153) + 5) div 5;
if (month < 10) then
month := month + 3
else
begin
month := month - 9;
year := year + 1;
end {else}
end {if}
else
begin
month := 0;
day := 0;
year := 0;
end; {else}
end;
function GS_Date_CurCentury(yr: integer) : GS_Date_CenTyp;
Var
month, day, year : word;
cw : word;
tc: GS_Date_CenTyp;
begin
gsGetDate(year,month,day,cw);
day := year mod 100;
year := year div 100;
if (yr < GSbytNextCentury) and
(day >= GSbytNextCentury) then inc(year); {Use next century if under limit}
Str(year:2, tc);
GS_Date_CurCentury := tc;
end;
function GS_Date_Curr : GS_Date_ValTyp;
Var
month, day, year : word;
cw : word;
begin
gsGetDate(year,month,day,cw);
GS_Date_Curr := GS_Date_MDY2Jul(month, day, year);
end;
function GS_Date_DBStor(nv : GS_Date_ValTyp) : GS_Date_StrTyp;
var
mm,
dd,
yy : word;
ss : String[8];
sg : String[4];
i : integer;
begin
ss := ' ';
if nv > 0 then
begin
GS_Date_Jul2MDY(nv,mm,dd,yy);
str(mm:2,sg);
move(sg[1],ss[5],2);
str(dd:2,sg);
move(sg[1],ss[7],2);
str(yy:4,sg);
move(sg[1],ss[1],4);
for i := 1 to 8 do if ss[i] = ' ' then ss[i] := '0';
end;
GS_Date_DBStor := ss;
end;
function GS_Date_View(nv: GS_Date_ValTyp): GS_Date_StrTyp;
var
mm,
dd,
yy : word;
ss : String[10];
sg1,
sg2,
sg3 : String[4];
i : integer;
begin
if nv > GS_Date_JulInv then begin
GS_Date_Jul2MDY(nv,mm,dd,yy);
if mm = 0 then sg1 := ''
else begin
str(mm:2,sg1);
str(dd:2,sg2);
str(yy:4,sg3);
end;
end
else sg1 := '';
case GSsetDateType of
American,
USA,
MDY : ss := DateType_MDY(sg1,sg2,sg3);
British,
French,
German,
Italian,
DMY : ss := DateType_DMY(sg1,sg2,sg3);
ANSI,
Japan,
YMD : ss := DateType_YMD(sg1,sg2,sg3);
end;
if sg1 <> '' then
for i := 1 to length(ss) do
if ss[i] = ' ' then ss[i] := '0';
GS_Date_View := ss;
end;
function GS_Date_Juln(sdate: GS_Date_StrTyp): GS_Date_ValTyp;
var
t : GS_Date_StrTyp;
yy,
mm,
dd : Str4;
mmn,
ddn,
yyn : word;
i : integer;
e : integer;
rsl : integer;
okDate : boolean;
co : longint;
function StripDate(var sleft: GS_Date_StrTyp): Str4;
var
ss1 : integer;
begin
ss1 := 1;
while (ss1 <= length(sleft)) and (sleft[ss1] in ['0'..'9']) do inc(ss1);
StripDate := system.copy(sleft,1,pred(ss1));
system.delete(sleft,1,ss1);
end;
begin
ddn := 0;
yyn := 0;
mm:= '';
dd := '';
yy := '';
t := sdate;
rsl := 0;
e := 0;
for i := length(t) downto 1 do
begin
if t[i] < '0' then rsl := i;
if not (t[i] in [' ','/','-','.']) then e := i;
end;
if e = 0 then
begin
GS_Date_Juln := GS_Date_JulMty;
exit;
end;
if rsl = 0 then
begin
mm := system.copy(t,5,2);
dd := system.copy(t,7,2);
yy := system.copy(t,1,4);
end
else
begin
case GSsetDateType of
American,
USA,
MDY : begin
mm := StripDate(t);
dd := StripDate(t);
yy := StripDate(t);
end;
British,
French,
German,
Italian,
DMY : begin
dd := StripDate(t);
mm := StripDate(t);
yy := StripDate(t);
end;
ANSI,
Japan,
YMD : begin
yy := StripDate(t);
mm := StripDate(t);
dd := StripDate(t);
end;
end;
if length(yy) < 3 then {Get Century}
begin
val(yy,yyn,rsl);
if rsl = 0 then
yy := GS_Date_CurCentury(yyn)+yy;
end;
end;
okDate := false;
val(mm,mmn,rsl);
if rsl = 0 then
begin
val(dd,ddn,rsl);
if rsl = 0 then
begin
val(yy,yyn,rsl);
if rsl = 0 then
begin
if DateOk(mmn,ddn,yyn) then okDate := true;
end;
end;
end;
if not okDate then
co := GS_Date_JulInv
else
begin
co := GS_Date_MDY2Jul(mmn, ddn, yyn);
end;
GS_Date_Juln := co;
end;
function GS_Date_DBLoad(sdate: GS_Date_StrTyp): GS_Date_ValTyp;
var
yy,
mm,
dd : Str4;
mmn,
ddn,
yyn : word;
rsl : integer;
okDate : boolean;
co : longint;
begin
ddn := 0;
yyn := 0;
mm := system.copy(sdate,5,2);
dd := system.copy(sdate,7,2);
yy := system.copy(sdate,1,4);
okDate := false;
val(mm,mmn,rsl);
if rsl = 0 then
begin
val(dd,ddn,rsl);
if rsl = 0 then
begin
val(yy,yyn,rsl);
if rsl = 0 then
begin
if DateOk(mmn,ddn,yyn) then okDate := true;
end;
end;
end;
if not okDate then
co := GS_Date_JulInv
else
begin
co := GS_Date_MDY2Jul(mmn, ddn, yyn);
end;
GS_Date_DBLoad := co;
end;
begin
Today:=Gs_Date_Curr; {Get Current Date}
end.
|
unit CFColorCombobox;
interface
uses
Windows, Classes, Graphics, Controls, Messages, CFControl, CFPopupForm, CFPopupFormBase,
CFColorPad;
type
TPadForm = class(TfrmPopupFormBase)
private
FColorPad: TCFRichColorPad;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property ColorPad: TCFRichColorPad read FColorPad;
end;
TCFColorPopup = class(TCFPopupForm)
private
FPadForm: TPadForm;
FOnChanged: TNotifyEvent;
procedure DoColorChange(Sender: TObject);
function GetColor: TColor;
procedure SetColor(const Value: TColor);
procedure DoPopupClose(Sender: TObject);
protected
function StopPeekMessage(const AMsg: TMsg): Boolean; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Color: TColor read GetColor write SetColor;
published
property OnChanged: TNotifyEvent read FOnChanged write FOnChanged;
end;
TCFColorCombobox = class(TCFCustomControl)
private
FColorPopup: TCFColorPopup;
//FOnCloseUp: TCloseUpEvent;
function GetButtonRect: TRect;
procedure PopupItem;
procedure DoColorChange(Sender: TObject);
protected
procedure DrawControl(ACanvas: TCanvas); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
implementation
{$R CFCombobox.res}
{ TCFColorCombobox }
constructor TCFColorCombobox.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FColorPopup := TCFColorPopup.Create(Self);
FColorPopup.OnChanged := DoColorChange;
Width := 120;
Height := 20;
end;
destructor TCFColorCombobox.Destroy;
begin
FColorPopup.Free;
inherited;
end;
procedure TCFColorCombobox.DoColorChange(Sender: TObject);
begin
Self.UpdateDirectUI;
end;
procedure TCFColorCombobox.DrawControl(ACanvas: TCanvas);
procedure DrawDownArrow;
var
vBmp: TBitmap;
begin
{if cmsMouseDown in MouseState then
begin
ACanvas.Brush.Color := $00E5C27F;
ACanvas.FillRect(FButtonRect);
ACanvas.Pen.Color := GBorderHotColor;
ACanvas.MoveTo(FButtonRect.Left - 1, FButtonRect.Top);
ACanvas.LineTo(FButtonRect.Left - 1, FButtonRect.Bottom);
end
else
if cmsMouseIn in MouseState then
begin
ACanvas.Brush.Color := GHotColor;
ACanvas.FillRect(FButtonRect);
ACanvas.Pen.Color := GBorderColor;
ACanvas.MoveTo(FButtonRect.Left - 1, FButtonRect.Top);
ACanvas.LineTo(FButtonRect.Left - 1, FButtonRect.Bottom);
end;}
vBmp := TBitmap.Create;
try
vBmp.Transparent := True;
vBmp.LoadFromResourceName(HInstance, 'DROPDOWN');
ACanvas.Draw(Width - GSpace - GIconWidth, GSpace, vBmp);
finally
vBmp.Free;
end;
end;
var
vRect: TRect;
begin
inherited DrawControl(ACanvas);
vRect := Rect(0, 0, Width, Height);
if Self.Focused or (cmsMouseIn in MouseState) then
ACanvas.Pen.Color := GBorderHotColor
else
ACanvas.Pen.Color := GBorderColor;
if BorderVisible then
ACanvas.Pen.Style := psSolid
else
ACanvas.Pen.Style := psClear;
if BorderVisible then // 显示边框时圆角区域
ACanvas.Rectangle(vRect)
else
ACanvas.FillRect(vRect);
InflateRect(vRect, -GSpace, -GSpace);
if FColorPopup.Color <> clNone then
begin
ACanvas.Brush.Color := FColorPopup.Color;
ACanvas.FillRect(vRect);
end
else
begin
end;
DrawDownArrow;
end;
function TCFColorCombobox.GetButtonRect: TRect;
begin
Result := Bounds(Width - GSpace - GIconWidth, GSpace, GIconWidth, GIconWidth);
end;
procedure TCFColorCombobox.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
var
vRect: TRect;
begin
vRect := GetButtonRect;
if (not (csDesigning in ComponentState)) and PtInRect(vRect, Point(X, Y)) then
PopupItem
else
inherited;
end;
procedure TCFColorCombobox.PopupItem;
begin
FColorPopup.Popup(Self);
end;
{ TCFColorPopup }
constructor TCFColorPopup.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FPadForm := TPadForm.Create(nil);
FPadForm.ColorPad.OnChange := DoColorChange;
Self.PopupControl := FPadForm;
Self.OnPopupClose := DoPopupClose;
end;
destructor TCFColorPopup.Destroy;
begin
FPadForm.Free;
inherited Destroy;
end;
procedure TCFColorPopup.DoColorChange(Sender: TObject);
begin
Self.ClosePopup(False);
end;
procedure TCFColorPopup.DoPopupClose(Sender: TObject);
begin
if Assigned(FOnChanged) then
FOnChanged(Self);
end;
function TCFColorPopup.GetColor: TColor;
begin
Result := FPadForm.ColorPad.Select;
end;
procedure TCFColorPopup.SetColor(const Value: TColor);
begin
FPadForm.ColorPad.Select := Value;
end;
function TCFColorPopup.StopPeekMessage(const AMsg: TMsg): Boolean;
//var
// vPt: TPoint;
// vRect: TRect;
begin
Result := inherited StopPeekMessage(AMsg);
{case AMsg.message of
WM_NCLBUTTONDOWN, WM_NCLBUTTONDBLCLK, WM_LBUTTONDOWN, WM_LBUTTONDBLCLK,
WM_NCRBUTTONDOWN, WM_NCRBUTTONDBLCLK, WM_RBUTTONDOWN, WM_RBUTTONDBLCLK,
WM_NCMBUTTONDOWN, WM_NCMBUTTONDBLCLK, WM_MBUTTONDOWN, WM_MBUTTONDBLCLK:
begin
if not IsPopupWindow(AMsg.hwnd) then // 不在弹出窗体上
Result := True;
end;
end;}
end;
{ TPadForm }
constructor TPadForm.Create(AOwner: TComponent);
begin
inherited;
FColorPad := TCFRichColorPad.Create(Self);
Self.Width := FColorPad.Width;
Self.Height := FColorPad.Height;
FColorPad.Parent := Self;
end;
destructor TPadForm.Destroy;
begin
FColorPad.Free;
inherited Destroy;
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 uCEFRenderProcessHandler;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
{$IFDEF DELPHI16_UP}
System.Classes,
{$ELSE}
Classes,
{$ENDIF}
uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes, uCEFListValue, uCEFBrowser, uCEFFrame, uCEFRequest,
uCEFv8Context, uCEFv8Exception, uCEFv8StackTrace, uCEFDomNode, uCEFProcessMessage, uCEFApplication;
type
TCefRenderProcessHandlerOwn = class(TCefBaseRefCountedOwn, ICefRenderProcessHandler)
protected
procedure OnRenderThreadCreated(const extraInfo: ICefListValue); virtual; abstract;
procedure OnWebKitInitialized; virtual; abstract;
procedure OnBrowserCreated(const browser: ICefBrowser); virtual; abstract;
procedure OnBrowserDestroyed(const browser: ICefBrowser); virtual; abstract;
function GetLoadHandler: ICefLoadHandler; virtual;
function OnBeforeNavigation(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; navigationType: TCefNavigationType; isRedirect: Boolean): Boolean; virtual;
procedure OnContextCreated(const browser: ICefBrowser; const frame: ICefFrame; const context: ICefv8Context); virtual; abstract;
procedure OnContextReleased(const browser: ICefBrowser; const frame: ICefFrame; const context: ICefv8Context); virtual; abstract;
procedure OnUncaughtException(const browser: ICefBrowser; const frame: ICefFrame; const context: ICefv8Context; const exception: ICefV8Exception; const stackTrace: ICefV8StackTrace); virtual; abstract;
procedure OnFocusedNodeChanged(const browser: ICefBrowser; const frame: ICefFrame; const node: ICefDomNode); virtual; abstract;
function OnProcessMessageReceived(const browser: ICefBrowser; sourceProcess: TCefProcessId; const aMessage: ICefProcessMessage): Boolean; virtual;
public
constructor Create; virtual;
end;
TCefCustomRenderProcessHandler = class(TCefRenderProcessHandlerOwn)
protected
FCefApp : TCefApplication;
procedure OnRenderThreadCreated(const extraInfo: ICefListValue); override;
procedure OnWebKitInitialized; override;
procedure OnBrowserCreated(const browser: ICefBrowser); override;
procedure OnBrowserDestroyed(const browser: ICefBrowser); override;
function OnBeforeNavigation(const browser: ICefBrowser; const frame: ICefFrame; const request: ICefRequest; navigationType: TCefNavigationType; isRedirect: Boolean): Boolean; override;
procedure OnContextCreated(const browser: ICefBrowser; const frame: ICefFrame; const context: ICefv8Context); override;
procedure OnContextReleased(const browser: ICefBrowser; const frame: ICefFrame; const context: ICefv8Context); override;
procedure OnUncaughtException(const browser: ICefBrowser; const frame: ICefFrame; const context: ICefv8Context; const exception: ICefV8Exception; const stackTrace: ICefV8StackTrace); override;
procedure OnFocusedNodeChanged(const browser: ICefBrowser; const frame: ICefFrame; const node: ICefDomNode); override;
function OnProcessMessageReceived(const browser: ICefBrowser; sourceProcess: TCefProcessId; const aMessage : ICefProcessMessage): Boolean; override;
public
constructor Create(const aCefApp : TCefApplication); reintroduce;
destructor Destroy; override;
end;
implementation
uses
uCEFMiscFunctions, uCEFLibFunctions, uCEFConstants;
procedure cef_render_process_handler_on_render_thread_created(self : PCefRenderProcessHandler;
extra_info : PCefListValue); stdcall;
var
TempObject : TObject;
begin
TempObject := CefGetObject(self);
if (TempObject <> nil) and (TempObject is TCefRenderProcessHandlerOwn) then
TCefRenderProcessHandlerOwn(TempObject).OnRenderThreadCreated(TCefListValueRef.UnWrap(extra_info));
end;
procedure cef_render_process_handler_on_web_kit_initialized(self: PCefRenderProcessHandler); stdcall;
var
TempObject : TObject;
begin
TempObject := CefGetObject(self);
if (TempObject <> nil) and (TempObject is TCefRenderProcessHandlerOwn) then
TCefRenderProcessHandlerOwn(TempObject).OnWebKitInitialized;
end;
procedure cef_render_process_handler_on_browser_created(self : PCefRenderProcessHandler;
browser : PCefBrowser); stdcall;
var
TempObject : TObject;
begin
TempObject := CefGetObject(self);
if (TempObject <> nil) and (TempObject is TCefRenderProcessHandlerOwn) then
TCefRenderProcessHandlerOwn(TempObject).OnBrowserCreated(TCefBrowserRef.UnWrap(browser));
end;
procedure cef_render_process_handler_on_browser_destroyed(self : PCefRenderProcessHandler;
browser : PCefBrowser); stdcall;
var
TempObject : TObject;
begin
TempObject := CefGetObject(self);
if (TempObject <> nil) and (TempObject is TCefRenderProcessHandlerOwn) then
TCefRenderProcessHandlerOwn(TempObject).OnBrowserDestroyed(TCefBrowserRef.UnWrap(browser));
end;
function cef_render_process_handler_get_load_handler(self: PCefRenderProcessHandler): PCefLoadHandler; stdcall;
var
TempObject : TObject;
begin
TempObject := CefGetObject(self);
if (TempObject <> nil) and (TempObject is TCefRenderProcessHandlerOwn) then
Result := CefGetData(TCefRenderProcessHandlerOwn(TempObject).GetLoadHandler)
else
Result := nil;
end;
function cef_render_process_handler_on_before_navigation(self : PCefRenderProcessHandler;
browser : PCefBrowser;
frame : PCefFrame;
request : PCefRequest;
navigation_type : TCefNavigationType;
is_redirect : Integer): Integer; stdcall;
var
TempObject : TObject;
begin
TempObject := CefGetObject(self);
if (TempObject <> nil) and (TempObject is TCefRenderProcessHandlerOwn) then
Result := Ord(TCefRenderProcessHandlerOwn(TempObject).OnBeforeNavigation(TCefBrowserRef.UnWrap(browser),
TCefFrameRef.UnWrap(frame),
TCefRequestRef.UnWrap(request),
navigation_type,
is_redirect <> 0))
else
Result := 0;
end;
procedure cef_render_process_handler_on_context_created(self : PCefRenderProcessHandler;
browser : PCefBrowser;
frame : PCefFrame;
context : PCefv8Context); stdcall;
var
TempObject : TObject;
begin
TempObject := CefGetObject(self);
if (TempObject <> nil) and (TempObject is TCefRenderProcessHandlerOwn) then
TCefRenderProcessHandlerOwn(TempObject).OnContextCreated(TCefBrowserRef.UnWrap(browser),
TCefFrameRef.UnWrap(frame),
TCefv8ContextRef.UnWrap(context));
end;
procedure cef_render_process_handler_on_context_released(self : PCefRenderProcessHandler;
browser : PCefBrowser;
frame : PCefFrame;
context : PCefv8Context); stdcall;
var
TempObject : TObject;
begin
TempObject := CefGetObject(self);
if (TempObject <> nil) and (TempObject is TCefRenderProcessHandlerOwn) then
TCefRenderProcessHandlerOwn(TempObject).OnContextReleased(TCefBrowserRef.UnWrap(browser),
TCefFrameRef.UnWrap(frame),
TCefv8ContextRef.UnWrap(context));
end;
procedure cef_render_process_handler_on_uncaught_exception(self : PCefRenderProcessHandler;
browser : PCefBrowser;
frame : PCefFrame;
context : PCefv8Context;
exception : PCefV8Exception;
stackTrace : PCefV8StackTrace); stdcall;
var
TempObject : TObject;
begin
TempObject := CefGetObject(self);
if (TempObject <> nil) and (TempObject is TCefRenderProcessHandlerOwn) then
TCefRenderProcessHandlerOwn(TempObject).OnUncaughtException(TCefBrowserRef.UnWrap(browser),
TCefFrameRef.UnWrap(frame),
TCefv8ContextRef.UnWrap(context),
TCefV8ExceptionRef.UnWrap(exception),
TCefV8StackTraceRef.UnWrap(stackTrace));
end;
procedure cef_render_process_handler_on_focused_node_changed(self : PCefRenderProcessHandler;
browser : PCefBrowser;
frame : PCefFrame;
node : PCefDomNode); stdcall;
var
TempObject : TObject;
begin
TempObject := CefGetObject(self);
if (TempObject <> nil) and (TempObject is TCefRenderProcessHandlerOwn) then
TCefRenderProcessHandlerOwn(TempObject).OnFocusedNodeChanged(TCefBrowserRef.UnWrap(browser),
TCefFrameRef.UnWrap(frame),
TCefDomNodeRef.UnWrap(node));
end;
function cef_render_process_handler_on_process_message_received(self : PCefRenderProcessHandler;
browser : PCefBrowser;
source_process : TCefProcessId;
message_ : PCefProcessMessage): Integer; stdcall;
var
TempObject : TObject;
begin
TempObject := CefGetObject(self);
if (TempObject <> nil) and (TempObject is TCefRenderProcessHandlerOwn) then
Result := Ord(TCefRenderProcessHandlerOwn(TempObject).OnProcessMessageReceived(TCefBrowserRef.UnWrap(browser),
source_process,
TCefProcessMessageRef.UnWrap(message_)))
else
Result := 0;
end;
// TCefRenderProcessHandlerOwn
constructor TCefRenderProcessHandlerOwn.Create;
begin
inherited CreateData(SizeOf(TCefRenderProcessHandler));
with PCefRenderProcessHandler(FData)^ do
begin
on_render_thread_created := cef_render_process_handler_on_render_thread_created;
on_web_kit_initialized := cef_render_process_handler_on_web_kit_initialized;
on_browser_created := cef_render_process_handler_on_browser_created;
on_browser_destroyed := cef_render_process_handler_on_browser_destroyed;
get_load_handler := cef_render_process_handler_get_load_handler;
on_before_navigation := cef_render_process_handler_on_before_navigation;
on_context_created := cef_render_process_handler_on_context_created;
on_context_released := cef_render_process_handler_on_context_released;
on_uncaught_exception := cef_render_process_handler_on_uncaught_exception;
on_focused_node_changed := cef_render_process_handler_on_focused_node_changed;
on_process_message_received := cef_render_process_handler_on_process_message_received;
end;
end;
function TCefRenderProcessHandlerOwn.GetLoadHandler: ICefLoadHandler;
begin
Result := nil;
end;
function TCefRenderProcessHandlerOwn.OnBeforeNavigation(const browser : ICefBrowser;
const frame : ICefFrame;
const request : ICefRequest;
navigationType : TCefNavigationType;
isRedirect : Boolean): Boolean;
begin
Result := False;
end;
function TCefRenderProcessHandlerOwn.OnProcessMessageReceived(const browser : ICefBrowser;
sourceProcess : TCefProcessId;
const aMessage : ICefProcessMessage): Boolean;
begin
Result := False;
end;
// TCefCustomRenderProcessHandler
constructor TCefCustomRenderProcessHandler.Create(const aCefApp : TCefApplication);
begin
inherited Create;
FCefApp := aCefApp;
end;
destructor TCefCustomRenderProcessHandler.Destroy;
begin
FCefApp := nil;
inherited Destroy;
end;
procedure TCefCustomRenderProcessHandler.OnRenderThreadCreated(const extraInfo: ICefListValue);
begin
if (FCefApp <> nil) then FCefApp.Internal_OnRenderThreadCreated(extraInfo);
end;
procedure TCefCustomRenderProcessHandler.OnWebKitInitialized;
begin
if (FCefApp <> nil) then FCefApp.Internal_OnWebKitInitialized;
end;
procedure TCefCustomRenderProcessHandler.OnBrowserCreated(const browser: ICefBrowser);
begin
if (FCefApp <> nil) then FCefApp.Internal_OnBrowserCreated(browser);
end;
procedure TCefCustomRenderProcessHandler.OnBrowserDestroyed(const browser: ICefBrowser);
begin
if (FCefApp <> nil) then FCefApp.Internal_OnBrowserDestroyed(browser);
end;
function TCefCustomRenderProcessHandler.OnBeforeNavigation(const browser : ICefBrowser;
const frame : ICefFrame;
const request : ICefRequest;
navigationType : TCefNavigationType;
isRedirect : Boolean): Boolean;
begin
Result := inherited OnBeforeNavigation(browser, frame, request, navigationType, isRedirect);
if (FCefApp <> nil) then FCefApp.Internal_OnBeforeNavigation(browser, frame, request, navigationType, isRedirect, Result);
end;
procedure TCefCustomRenderProcessHandler.OnContextCreated(const browser : ICefBrowser;
const frame : ICefFrame;
const context : ICefv8Context);
begin
if (FCefApp <> nil) then FCefApp.Internal_OnContextCreated(browser, frame, context);
end;
procedure TCefCustomRenderProcessHandler.OnContextReleased(const browser : ICefBrowser;
const frame : ICefFrame;
const context : ICefv8Context);
begin
if (FCefApp <> nil) then FCefApp.Internal_OnContextReleased(browser, frame, context);
end;
procedure TCefCustomRenderProcessHandler.OnUncaughtException(const browser : ICefBrowser;
const frame : ICefFrame;
const context : ICefv8Context;
const exception : ICefV8Exception;
const stackTrace : ICefV8StackTrace);
begin
if (FCefApp <> nil) then FCefApp.Internal_OnUncaughtException(browser, frame, context, exception, stackTrace);
end;
procedure TCefCustomRenderProcessHandler.OnFocusedNodeChanged(const browser : ICefBrowser;
const frame : ICefFrame;
const node : ICefDomNode);
begin
if (FCefApp <> nil) then FCefApp.Internal_OnFocusedNodeChanged(browser, frame, node);
end;
function TCefCustomRenderProcessHandler.OnProcessMessageReceived(const browser : ICefBrowser;
sourceProcess : TCefProcessId;
const aMessage : ICefProcessMessage): Boolean;
begin
Result := inherited OnProcessMessageReceived(browser, sourceProcess, aMessage);
if (FCefApp <> nil) then FCefApp.Internal_OnProcessMessageReceived(browser, sourceProcess, aMessage, Result);
end;
end.
|
//******************************************************************************
// Проект ""
// Справочник типов документов
//
// последние изменения
//******************************************************************************
unit uDocumentType_main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uCommon_Funcs, uConsts,uDocumentType_DM, uDocumentType_AE,
uCommon_Messages, uConsts_Messages, uCommon_Types, cxTimeEdit, AccMGMT,
cxGraphics, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage,
cxEdit, DB, cxDBData, cxTextEdit, Placemnt, Menus, cxGridTableView,
ImgList, dxBar, dxBarExtItems, cxGridLevel, cxGridCustomTableView,
cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid,
dxStatusBar, ActnList;
type
TfrmDocumentType_main = class(TForm)
StatusBar: TdxStatusBar;
Grid: TcxGrid;
GridDBView: TcxGridDBTableView;
name_document_type: TcxGridDBColumn;
GridLevel: TcxGridLevel;
BarManager: TdxBarManager;
AddButton: TdxBarLargeButton;
EditButton: TdxBarLargeButton;
DeleteButton: TdxBarLargeButton;
RefreshButton: TdxBarLargeButton;
ExitButton: TdxBarLargeButton;
SelectButton: TdxBarLargeButton;
PopupImageList: TImageList;
LargeImages: TImageList;
DisabledLargeImages: TImageList;
Styles: TcxStyleRepository;
BackGround: TcxStyle;
FocusedRecord: TcxStyle;
Header: TcxStyle;
DesabledRecord: TcxStyle;
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;
cxStyle15: TcxStyle;
cxStyle16: TcxStyle;
Default_StyleSheet: TcxGridTableViewStyleSheet;
DevExpress_Style: TcxGridTableViewStyleSheet;
PopupMenu1: TPopupMenu;
AddPop: TMenuItem;
EditPop: TMenuItem;
DeletePop: TMenuItem;
RefreshPop: TMenuItem;
ExitPop: TMenuItem;
bsFormStorage: TFormStorage;
DocTypeActionList: TActionList;
ActIns: TAction;
ActEdit: TAction;
ActClose: TAction;
ActDel: TAction;
ActRefresh: TAction;
ActSelect: TAction;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure GridDBViewDblClick(Sender: TObject);
procedure ActInsExecute(Sender: TObject);
procedure ActEditExecute(Sender: TObject);
procedure ActDelExecute(Sender: TObject);
procedure ActRefreshExecute(Sender: TObject);
procedure ActSelectExecute(Sender: TObject);
procedure ActCloseExecute(Sender: TObject);
procedure AddPopClick(Sender: TObject);
procedure EditPopClick(Sender: TObject);
procedure DeletePopClick(Sender: TObject);
procedure RefreshPopClick(Sender: TObject);
procedure ExitPopClick(Sender: TObject);
private
PLanguageIndex: byte;
DM : TDocumentType_DM;
procedure FormIniLanguage;
procedure DocTypeDSetCloseOpen;
public
res:Variant;
Is_admin:Boolean;
constructor Create(AParameter:TbsSimpleParams);reintroduce;
end;
{frmDocumentType_main: TfrmDocumentType_main; }
implementation
uses FIBQuery, pFIBStoredProc, pFIBQuery;
{$R *.dfm}
constructor TfrmDocumentType_main.Create(AParameter:TbsSimpleParams);
begin
Screen.Cursor:=crHourGlass;
inherited Create(AParameter.Owner);
self.Is_admin := AParameter.is_admin;
DM:=TDocumentType_DM.Create(Self);
DM.DB.Handle := AParameter.Db_Handle;
DM.DB.Connected := True;
DM.ReadTransaction.StartTransaction;
GridDBView.DataController.DataSource := DM.DataSource;
DM.DataSet.Close;
DM.DataSet.SQLs.SelectSQL.Text := 'select * from BS_DOCUMENT_TYPE_SEL';
DM.DataSet.Open;
if AParameter.ID_Locate <> null
then DM.DataSet.Locate('id_document_type', AParameter.ID_Locate, [] );
FormIniLanguage();
Screen.Cursor:=crDefault;
bsFormStorage.RestoreFormPlacement;
end;
procedure TfrmDocumentType_main.DocTypeDSetCloseOpen;
begin
DM.DataSet.Close;
DM.DataSet.SQLs.SelectSQL.Text := 'select * from BS_DOCUMENT_TYPE_SEL';
DM.DataSet.Open;
end;
procedure TfrmDocumentType_main.FormIniLanguage;
begin
PLanguageIndex:= uCommon_Funcs.bsLanguageIndex();
//кэпшн формы
Caption:= uConsts.bs_sp_document_type[PLanguageIndex];
//названия кнопок
ActIns.Caption := uConsts.bs_InsertBtn_Caption[PLanguageIndex];
ActEdit.Caption := uConsts.bs_EditBtn_Caption[PLanguageIndex];
ActDel.Caption := uConsts.bs_DeleteBtn_Caption[PLanguageIndex];
ActRefresh.Caption := uConsts.bs_RefreshBtn_Caption[PLanguageIndex];
ActSelect.Caption := uConsts.bs_SelectBtn_Caption[PLanguageIndex];
ActClose.Caption := uConsts.bs_ExitBtn_Caption[PLanguageIndex];
// попап
AddPop.Caption := uConsts.bs_InsertBtn_Caption[PLanguageIndex];
EditPop.Caption := uConsts.bs_EditBtn_Caption[PLanguageIndex];
DeletePop.Caption := uConsts.bs_DeleteBtn_Caption[PLanguageIndex];
RefreshPop.Caption := uConsts.bs_RefreshBtn_Caption[PLanguageIndex];
ExitPop.Caption := uConsts.bs_ExitBtn_Caption[PLanguageIndex];
//грид
name_document_type.Caption := uConsts.bs_name_document_type[PLanguageIndex];
//статусбар
StatusBar.Panels[0].Text:= uConsts.bs_InsertBtn_ShortCut[PLanguageIndex] + uConsts.bs_InsertBtn_Caption[PLanguageIndex];
StatusBar.Panels[1].Text:= uConsts.bs_EditBtn_ShortCut[PLanguageIndex] + uConsts.bs_EditBtn_Caption[PLanguageIndex];
StatusBar.Panels[2].Text:= uConsts.bs_DeleteBtn_ShortCut[PLanguageIndex] + uConsts.bs_DeleteBtn_Caption[PLanguageIndex];
StatusBar.Panels[3].Text:= uConsts.bs_RefreshBtn_ShortCut[PLanguageIndex] + uConsts.bs_RefreshBtn_Caption[PLanguageIndex];
StatusBar.Panels[4].Text:= uConsts.bs_EnterBtn_ShortCut[PLanguageIndex] + uConsts.bs_SelectBtn_Caption[PLanguageIndex];
StatusBar.Panels[5].Text:= uConsts.bs_ExitBtn_ShortCut[PLanguageIndex] + uConsts.bs_ExitBtn_Caption[PLanguageIndex];
end;
procedure TfrmDocumentType_main.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
bsFormStorage.SaveFormPlacement;
if FormStyle = fsMDIChild then action:=caFree
else
DM.Free;
end;
procedure TfrmDocumentType_main.FormShow(Sender: TObject);
begin
if FormStyle = fsMDIChild then SelectButton.Visible:=ivNever;
end;
procedure TfrmDocumentType_main.GridDBViewDblClick(Sender: TObject);
begin
if FormStyle = fsNormal then ActSelectExecute(Sender)
else ActEditExecute(Sender);
end;
procedure TfrmDocumentType_main.ActInsExecute(Sender: TObject);
var
ViewForm : TfrmDocumentType_AE;
Id, i:Integer;
begin
if not Is_Admin then
if fibCheckPermission('/ROOT/BillingSystem/bs_sprav/bs_sp_DocType','Add') <> 0 then
begin
messagebox(handle,
pchar(uConsts_Messages.bs_NotHaveRights[PLanguageIndex]
+#13+ uConsts_Messages.bs_GoToAdmin[PLanguageIndex]),
pchar(uConsts_Messages.bs_ActionDenied[PLanguageIndex]), MB_ICONWARNING or mb_Ok);
exit;
end;
ViewForm := TfrmDocumentType_AE.Create(Self, PLanguageIndex, Null, DM);
ViewForm.Caption := uConsts.bs_InsertBtn_Caption[PLanguageIndex];
if ViewForm.ShowModal = mrOk then
begin
with DM.StProc do
begin
DM.WriteTransaction.StartTransaction;
StoredProcName := 'BS_DOCUMENT_TYPE_INS_UPD';
Prepare;
ParamByName('id_document_type').Value:=Null;
ParamByName('name_document_type').AsString:= ViewForm.NameEdit.Text;
ExecProc;
try
Id:=FieldByName('RET_VALUE').AsInteger;
for i:=0 to ViewForm.DocPropsList.Count-1 do
begin
if ViewForm.DocPropsList.Items.Items[i].Checked then
begin
StoredProcName := 'BS_DOC_TYPE_JN_DOC_PROPS_INS';
Prepare;
ParamByName('ID_TYPE_DOC').AsInteger:=Id;
ParamByName('Id_Prop').AsInteger:=i+1;
ExecProc;
end;
end;
DM.WriteTransaction.Commit;
except
on E:Exception do
begin
LogException;
bsShowMessage('Error',e.Message,mtError,[mbOK]);
DM.WriteTransaction.Rollback;
raise;
end;
end;
end;
DocTypeDSetCloseOpen;
DM.DataSet.Locate('Id_Document_Type', Id, []);
end;
end;
procedure TfrmDocumentType_main.ActEditExecute(Sender: TObject);
var
ViewForm : TfrmDocumentType_AE;
Id, i:Integer;
begin
if not Is_Admin then
if fibCheckPermission('/ROOT/BillingSystem/bs_sprav/bs_sp_DocType','Edit') <> 0 then
begin
messagebox(handle,
pchar(uConsts_Messages.bs_NotHaveRights[PLanguageIndex]
+#13+ uConsts_Messages.bs_GoToAdmin[PLanguageIndex]),
pchar(uConsts_Messages.bs_ActionDenied[PLanguageIndex]), MB_ICONWARNING or mb_Ok);
exit;
end;
If GridDBView.DataController.RecordCount = 0 then Exit;
Id:=DM.DataSet['id_document_type'];
ViewForm:= TfrmDocumentType_AE.Create(Self, PLanguageIndex, Id, DM);
ViewForm.Caption := uConsts.bs_EditBtn_Caption[PLanguageIndex];
if VarIsNull(DM.DataSet['name_document_type']) then ViewForm.NameEdit.Text:=''
else ViewForm.NameEdit.Text := DM.DataSet['name_document_type'];
if ViewForm.ShowModal = mrOk then
begin
with DM.StProc do
Begin
DM.WriteTransaction.StartTransaction;
StoredProcName := 'BS_DOCUMENT_TYPE_INS_UPD';
Prepare;
ParamByName('id_document_type').AsInteger:= Id;
ParamByName('name_document_type').AsString:= ViewForm.NameEdit.Text;
ExecProc;
try
Id:=FieldByName('RET_VALUE').AsInteger;
StoredProcName := 'BS_DOC_TYPE_JN_DOC_PROPS_DEL';
Prepare;
ParamByName('ID_TYPE_DOC').AsInteger:=Id;
ParamByName('ID_DOC_PROP').Value:=Null;
ExecProc;
for i:=0 to ViewForm.DocPropsList.Count-1 do
begin
if ViewForm.DocPropsList.Items.Items[i].Checked then
begin
StoredProcName := 'BS_DOC_TYPE_JN_DOC_PROPS_INS';
Prepare;
ParamByName('ID_TYPE_DOC').AsInteger:=Id;
ParamByName('Id_Prop').AsInteger:=i+1;
ExecProc;
end;
end;
DM.WriteTransaction.Commit;
except
on E:Exception do
begin
LogException;
bsShowMessage('Error',e.Message,mtError,[mbOK]);
DM.WriteTransaction.Rollback;
end;
end;
end;
DocTypeDSetCloseOpen;
DM.DataSet.Locate('Id_Document_Type', Id, []);
end;
end;
procedure TfrmDocumentType_main.ActDelExecute(Sender: TObject);
var
i: byte;
str:string;
begin
if VarIsNull(DM.DataSet['name_document_type']) then str:=''
else str:=DM.DataSet['name_document_type'];
if not Is_Admin then
if fibCheckPermission('/ROOT/BillingSystem/bs_sprav/bs_sp_DocType','Del') <> 0 then
begin
messagebox(handle,
pchar(uConsts_Messages.bs_NotHaveRights[PLanguageIndex]
+#13+ uConsts_Messages.bs_GoToAdmin[PLanguageIndex]),
pchar(uConsts_Messages.bs_ActionDenied[PLanguageIndex]), MB_ICONWARNING or mb_Ok);
exit;
end;
If GridDBView.DataController.RecordCount = 0 then Exit;
i:= uCommon_Messages.bsShowMessage(uConsts.bs_Confirmation_Caption[PLanguageIndex], uConsts_Messages.bs_document_type_del[PLanguageIndex]+' '+str+'?', mtConfirmation, [mbYes, mbNo]);
if ((i = 7) or (i= 2)) then exit;
with DM.StProc do
begin
Transaction.StartTransaction;
StoredProcName := 'BS_DOCUMENT_TYPE_DEL';
Prepare;
ParamByName('id_document_type').AsInt64 := DM.DataSet['id_document_type'];
ExecProc;
Transaction.Commit;
try
except
on E:Exception do
begin
LogException;
bsShowMessage('Error',e.Message,mtError,[mbOK]);
Transaction.Rollback;
end;
end;
end;
DocTypeDSetCloseOpen;
end;
procedure TfrmDocumentType_main.ActRefreshExecute(Sender: TObject);
begin
DocTypeDSetCloseOpen;
end;
procedure TfrmDocumentType_main.ActSelectExecute(Sender: TObject);
var
id_sp: int64;
begin
if GridDBView.datacontroller.recordcount = 0 then exit;
Res:=VarArrayCreate([0,3],varVariant);
id_sp:= DM.DataSet['id_document_type'];
Res[0]:= id_sp;
Res[1]:=DM.DataSet['name_document_type'];
ModalResult:=mrOk;
end;
procedure TfrmDocumentType_main.ActCloseExecute(Sender: TObject);
begin
Close
end;
procedure TfrmDocumentType_main.AddPopClick(Sender: TObject);
begin
ActInsExecute(Sender);
end;
procedure TfrmDocumentType_main.EditPopClick(Sender: TObject);
begin
ActEditExecute(Sender);
end;
procedure TfrmDocumentType_main.DeletePopClick(Sender: TObject);
begin
ActDelExecute(Sender);
end;
procedure TfrmDocumentType_main.RefreshPopClick(Sender: TObject);
begin
ActRefreshExecute(Sender);
end;
procedure TfrmDocumentType_main.ExitPopClick(Sender: TObject);
begin
ActCloseExecute(Sender);
end;
end.
|
unit uDaoMatricula;
interface
uses uClassMatricula, ADODB,uClassConexao,Classes, DBClient,SysUtils;
type TDaoMatricula = class
private
FQuery : TadoQuery;
FConexao : TConexao;
public
constructor Create(Conexao : TConexao);
procedure Incluir( Matricula : TMatricula );
procedure Excluir( Matricula : TMatricula );
Function BuscarPorAluno(AlunoId : Integer) : TClientDataSet;
function UltimoAnoMatricula(AlunoId : Integer) : Integer;
end;
implementation
{ TDaoMatricula }
function TDaoMatricula.BuscarPorAluno(AlunoId: Integer): TClientDataSet;
var Parametros : TStringList;
begin
Parametros := TStringList.Create;
try
Result := FConexao.BuscarDadosAdo('Select * from Matriculas where AlunoId='+IntToStr(AlunoId),Parametros);
finally
FreeAndNil(Parametros);
end;
end;
constructor TDaoMatricula.Create(Conexao: TConexao);
begin
FConexao := Conexao;
end;
procedure TDaoMatricula.Excluir(Matricula: TMatricula);
var qryInclusao : TadoQuery;
begin
qryInclusao := TadoQuery.Create(nil);
qryInclusao.Connection := fConexao.adoConection;
qryInclusao.SQL.Text := 'Delete from Matriculas where Alunoid=:parId and Ano=:parAno';
qryInclusao.Parameters.ParamValues['parId'] := Matricula.AlunoId;
qryInclusao.Parameters.ParamValues['parAno'] := Matricula.ano;
qryInclusao.ExecSQL;
end;
procedure TDaoMatricula.Incluir(Matricula: TMatricula);
var qryInclusao : TadoQuery;
begin
qryInclusao := TadoQuery.Create(nil);
qryInclusao.Connection := fConexao.adoConection;
qryInclusao.SQL.Text := 'Insert Into Matriculas ( Id,AlunoId,Ano ) Values ' +
' ( :parId,:parAlunoId,:parAno )';
qryInclusao.Parameters.ParamValues['parId'] := Matricula.Id;
qryInclusao.Parameters.ParamValues['parAlunoId']:= Matricula.AlunoId;
qryInclusao.Parameters.ParamValues['parAno'] := Matricula.Ano;
qryInclusao.ExecSQL;
end;
function TDaoMatricula.UltimoAnoMatricula(AlunoId: Integer): Integer;
var Parametros : TStringList;
begin
Parametros := TStringList.Create;
try
Result := FConexao.BuscarDadosAdo('Select Max(Ano) as Ano from Matriculas where AlunoId='+IntToStr(AlunoId),Parametros).FieldByName('Ano').AsInteger;
finally
FreeAndNil(Parametros);
end;
end;
end.
|
uses UConst, UGeneticAlgorithm;
function read_txt(filename: string): array of array of real;
begin
foreach var (i, line) in ReadLines(filename).Numerate(0) do
begin
SetLength(result, i + 1);
result[i] := line.ToReals
end;
end;
function mix_flows(ratio: array of real;
fractions: array of array of real): array of real;
begin
result := ArrFill(fractions.Length, 0.0);
foreach var i in fractions.Indices do
foreach var j in ratio.Indices do
result[i] += ratio[j] * fractions[i][j]
end;
function get_octane_number(c: array of real;
octane_numbers: array of real;
bi: array of real): real;
begin
result := 0.0;
foreach var i in c.Indices do
result += octane_numbers[i] * c[i];
foreach var i in c.Indices do
for var j := i + 1 to c.High do
result += bi[i] * bi[j] * c[i] * c[j]
end;
function normalize(x: array of real): array of real;
begin
result := ArrFill(x.Length, 0.0);
var s := x.Sum;
foreach var i in x.Indices do
result[i] := x[i] / s
end;
function obj_func(ratio: array of real;
act_values: array of real): real;
begin
var data := read_txt('data.txt');
var flow := mix_flows(normalize(ratio), data);
var ron := get_octane_number(flow, UConst.RON, UConst.Bi);
result := (ron - act_values[0]) ** 2 + (flow[56] - act_values[1]) ** 2
end;
begin
var bounds := ||0.0001, 0.9|, |0.0001, 0.9|, |0.0001, 0.9|,
|0.0001, 0.9|, |0.0001, 0.9|, |0.0001, 0.9||;
var results := genetic_algorithm(bounds, obj_func, |92.2, 0.01|);
var data := read_txt('data.txt');
var flow := ArrFill(data.Length, 0.0);
foreach var r in results do
begin
flow := mix_flows(normalize(r[:^1]), data);
println($'ОЧИ = {get_octane_number(flow, UConst.RON, Uconst.Bi):f}, содержание бензола = {flow[56] * 100:f}, % об.')
end;
end. |
unit ConverterClassDataClass;
interface
uses
Classes;
type
TTemperatureFormula = record
Name : String;
A : Extended;
B : Extended;
C : Extended;
end;
TTemperature = class
private
FValue : Extended;
FScale : TTemperatureFormula;
protected
procedure Assign(const ATemperature: TTemperature);
procedure SetScale(const AScale: TTemperatureFormula);
function GetTemperature(const AIndex: TTemperatureFormula): Extended;
procedure SetTemperature(const AIndex: TTemperatureFormula; AValue : Extended);
property Scale : TTemperatureFormula read FScale write SetScale;
public
constructor Create;
property Temperature : TTemperature write Assign;
function ScaleToString(const AIndex: TTemperatureFormula): String;
property Value[const Index : TTemperatureFormula]: Extended read GetTemperature write SetTemperature; default;
property ScaleName[const Index : TTemperatureFormula]: String read ScaleToString;
end;
const
tfCelsius : TTemperatureFormula = ( Name: 'Celsius'; A: 0; B:1; C:0);
tfFahrenheit : TTemperatureFormula = ( Name: 'Fahrenheit'; A: 0; B:1.8; C:32);
tfKelvin : TTemperatureFormula = ( Name: 'Kelvin'; A: 273.15; B:1; C:0);
function FormulasEqual(A, B : TTemperatureFormula): Boolean;
implementation
uses ConvUtils, SysUtils;
function FormulasEqual(A, B : TTemperatureFormula): Boolean;
begin
Result := (A.A = B.A) and (A.B = B.B) and (A.C = B.C);
end;
// Base = (Temp - C) / B - A
// Temp = (Base + A) * B + C
constructor TTemperature.Create;
begin
FValue := 0;
FScale := tfCelsius;
end;
function TTemperature.GetTemperature(const AIndex: TTemperatureFormula): Extended;
begin
if FormulasEqual(AIndex, FScale) then
Result := FValue
else
begin
Scale := AIndex;
Result := FValue;
end;
end;
procedure TTemperature.SetTemperature(const AIndex: TTemperatureFormula; AValue: Extended);
begin
FValue := AValue;
FScale := AIndex;
end;
procedure TTemperature.SetScale(const AScale: TTemperatureFormula);
var
lBase, lNew : Extended;
begin
lBase := (FValue - FScale.C) / FScale.B - FScale.A;
lNew := (lBase + AScale.A) * AScale.B + AScale.C;
FValue := lNew;
FScale := AScale;
end;
procedure TTemperature.Assign(const ATemperature: TTemperature);
begin
FValue := ATemperature.FValue;
FScale := ATemperature.FScale;
end;
function TTemperature.ScaleToString(const AIndex: TTemperatureFormula): String;
begin
Result := AIndex.Name;
Delete(Result, 1, 1);
end;
end. |
unit uModUnit;
interface
uses
uModApp, uModCompany, System.SysUtils, uModAuthApp, uModTipePerusahaan,
uModPropinsi;
type
TModUnitType = class;
TModUnit = class(TModApp)
private
FAUTAPP: TModAutApp;
FCOMPANY: TModCompany;
FUNT_NPWP: string;
FUNT_NPWP_ADR: string;
FUNT_NPWP_NAME: string;
FUNT_NPWP_REG_DATE: TDatetime;
FREF_TIPE_PERUSAHAAN: TModTipePerusahaan;
FUNT_IS_HO: Integer;
FUNT_IS_WH: Integer;
FUNT_IS_STORE: Integer;
FUNT_ZIP: string;
FUNT_CODE: string;
FUNT_CONTACT_PERSON: string;
FUNT_DESCRIPTION: string;
FUNT_EMAIL: string;
FUNT_ADR: string;
FUNT_FAX: string;
FUNT_ISGRALLOWED: Integer;
FUNT_IS_ACTIVE: Integer;
FUNT_IS_ALLOWPO: Integer;
FKABUPATEN: TModKabupaten;
FUNT_NAME: string;
FUNT_PARENT: TModUnit;
FUNT_PHONE: string;
FUNT_RGN_CODE: string;
procedure SetUNT_NPWP_ADR(const Value: string);
public
destructor Destroy; override;
class function GetTableName: String; override;
published
[AttributeOfForeign('AUT$APP_ID')]
property AUTAPP: TModAutApp read FAUTAPP write FAUTAPP;
property COMPANY: TModCompany read FCOMPANY write FCOMPANY;
property UNT_NPWP: string read FUNT_NPWP write FUNT_NPWP;
property UNT_NPWP_ADR: string read FUNT_NPWP_ADR write SetUNT_NPWP_ADR;
property UNT_NPWP_NAME: string read FUNT_NPWP_NAME write FUNT_NPWP_NAME;
property UNT_NPWP_REG_DATE: TDatetime read FUNT_NPWP_REG_DATE write
FUNT_NPWP_REG_DATE;
[AttributeOfForeign('REF$TIPE_PERUSAHAAN_ID')]
property REF_TIPE_PERUSAHAAN: TModTipePerusahaan read FREF_TIPE_PERUSAHAAN
write FREF_TIPE_PERUSAHAAN;
property UNT_IS_HO: Integer read FUNT_IS_HO write FUNT_IS_HO;
property UNT_IS_WH: Integer read FUNT_IS_WH write FUNT_IS_WH;
property UNT_IS_STORE: Integer read FUNT_IS_STORE write FUNT_IS_STORE;
property UNT_ZIP: string read FUNT_ZIP write FUNT_ZIP;
[AttributeOfCode]
property UNT_CODE: string read FUNT_CODE write FUNT_CODE;
property UNT_CONTACT_PERSON: string read FUNT_CONTACT_PERSON write
FUNT_CONTACT_PERSON;
property UNT_DESCRIPTION: string read FUNT_DESCRIPTION write FUNT_DESCRIPTION;
property UNT_EMAIL: string read FUNT_EMAIL write FUNT_EMAIL;
property UNT_ADR: string read FUNT_ADR write FUNT_ADR;
property UNT_FAX: string read FUNT_FAX write FUNT_FAX;
property UNT_ISGRALLOWED: Integer read FUNT_ISGRALLOWED write FUNT_ISGRALLOWED;
property UNT_IS_ACTIVE: Integer read FUNT_IS_ACTIVE write FUNT_IS_ACTIVE;
property UNT_IS_ALLOWPO: Integer read FUNT_IS_ALLOWPO write FUNT_IS_ALLOWPO;
property KABUPATEN: TModKabupaten read FKABUPATEN write FKABUPATEN;
property UNT_NAME: string read FUNT_NAME write FUNT_NAME;
property UNT_PARENT: TModUnit read FUNT_PARENT write FUNT_PARENT;
property UNT_PHONE: string read FUNT_PHONE write FUNT_PHONE;
property UNT_RGN_CODE: string read FUNT_RGN_CODE write FUNT_RGN_CODE;
end;
TModUnitType = class(TModApp)
private
FType_Desc: string;
FType_Name: string;
public
class function GetTableName: String; override;
published
property Type_Desc: string read FType_Desc write FType_Desc;
property Type_Name: string read FType_Name write FType_Name;
end;
implementation
destructor TModUnit.Destroy;
begin
inherited;
FreeAndNil(FCOMPANY);
FreeAndNil(FREF_TIPE_PERUSAHAAN);
FreeAndNil(FAUTAPP);
FreeAndNil(FKABUPATEN);
end;
class function TModUnit.GetTableName: String;
begin
Result := 'AUT$UNIT';
end;
procedure TModUnit.SetUNT_NPWP_ADR(const Value: string);
begin
FUNT_NPWP_ADR := Value;
end;
class function TModUnitType.GetTableName: String;
begin
Result := 'UNIT_TYPE';
end;
initialization
TModUnit.RegisterRTTI;
end.
|
PROGRAM RLE;
USES
(* sysutils for StrToInt, IntToStr and FileExists *)
Crt, sysutils;
(* check if char is a number
returns true if number *)
FUNCTION IsNumber(c: CHAR): BOOLEAN;
BEGIN
IF ((Ord(c) >= 48) AND (Ord(c) <= 57)) THEN
IsNumber := TRUE
ELSE
IsNumber := FALSE;
END;
(* Get line of TEXT file
returns false if EOF, true if not *)
FUNCTION GetLine(VAR txt: TEXT; VAR curLine: STRING): BOOLEAN;
BEGIN
IF NOT Eof(txt) THEN BEGIN
ReadLn(txt, curLine);
GetLine := TRUE;
END
ELSE
GetLine := FALSE; (* EOF of txt *)
END;
(* compresses a string *)
PROCEDURE CompressString(VAR curLine: STRING);
VAR
s : STRING;
curChar : CHAR;
count, i, i2 : INTEGER;
BEGIN
curChar := curLine[1];
curLine := curLine + ' ';
s := '';
count := 0;
FOR i := 1 TO Length(curLine) DO BEGIN
IF curLine[i] = curChar THEN count := count + 1
ELSE
IF count < 3 THEN BEGIN
FOR i2 := 1 TO count DO s := s + curChar;
count := 1;
curChar := curLine[i];
END
ELSE BEGIN
s := s + curChar + IntToStr(count) ;
count := 1;
curChar := curLine[i];
END;
END;
IF Length(curLine) > 1 THEN curLine := s;
END;
(* decompress a string *)
PROCEDURE DecompressString(VAR curLine: STRING);
VAR
s, temp : STRING;
i, i2, count : INTEGER;
curChar : CHAR;
BEGIN
s := '';
temp := '';
curChar := curLine[1];
i := 1;
WHILE i <= Length(curLine) DO BEGIN
IF NOT IsNumber(curLine[i]) THEN BEGIN
s := s + curLine[i];
curChar := curLine[i];
END
ELSE BEGIN
i2 := i;
WHILE IsNumber(curLine[i]) AND (i2 <= Length(curLine)) DO BEGIN
temp := temp + curLine[i];
i := i + 1;
END;
i:= i - 1;
IF temp <> '' THEN count := StrToInt(temp);
temp := '';
FOR i2 := 1 TO count - 1 DO s := s + curChar;
END;
i := i + 1;
END;
IF Length(curLine) > 1 THEN curLine := s;
END;
(* compress txt file *)
PROCEDURE Compress(VAR txt1, txt2 : TEXT);
VAR
curLine: STRING;
BEGIN
WHILE GetLine(txt1, curLine) DO BEGIN
CompressString(curline);
WriteLn(txt2, curLine);
END;
WriteLn('Compressed');
END;
(* decompress txt file *)
PROCEDURE Decompress(VAR txt1, txt2 : TEXT);
VAR
curLine: STRING;
BEGIN
WHILE GetLine(txt1, curLine) DO BEGIN
DecompressString(curline);
WriteLn(txt2, curLine);
END;
WriteLn('Decompressed!');
END;
(* check for command line args
calls Decompress or Compress *)
PROCEDURE ParamCheck();
VAR
option, inFileName, outFileName : STRING;
txt1, txt2 : TEXT; (* text files *)
BEGIN
IF (ParamCount < 3) OR ((ParamStr(1) <> '-c') AND (ParamStr(1) <> '-d')) OR
(NOT FileExists(ParamStr(2))) OR (NOT FileExists(ParamStr(3))) THEN
BEGIN
WriteLn('Wrong input, try again: ');
Write('-c | -d > ');
ReadLn(option);
Write('inFile > ');
ReadLn(inFileName);
Write('outFile > ');
ReadLn(outFileName);
END
ELSE BEGIN
option := ParamStr(1);
inFileName := ParamStr(2);
outFileName := ParamStr(3);
END;
(*$I-*)
(* File initialization *)
Assign(txt1, inFileName);
Reset(txt1); (* read file *)
Assign(txt2, outFileName);
Rewrite(txt2); (* Rewrite new file or write*)
IF IOResult <> 0 THEN
BEGIN
WriteLn('Error opening file!');
Exit;
END;
IF option = '-c' THEN Compress(txt1, txt2) ELSE IF option = '-d' THEN Decompress(txt1, txt2);
(* Close Files *)
Close(txt1);
Close(txt2);
END;
BEGIN
ParamCheck();
END. |
unit frmJournalOpening;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Mask, Vcl.ComCtrls, dbfunc, uKernel;
type
TfJournalOpening = class(TForm)
lvLGNameLastLesson: TListView;
lvPedagogueList: TListView;
bCheckAllPedagogue: TButton;
bCheckAllGroup: TButton;
Panel1: TPanel;
bOpenJournal: TButton;
Label1: TLabel;
DateTimePicker1: TDateTimePicker;
bClose: TButton;
Panel2: TPanel;
cmbAcademicYear: TComboBox;
Label2: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure bOpenJournalClick(Sender: TObject);
procedure lvPedagogueListSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure DateTimePicker1Change(Sender: TObject);
procedure bCheckAllPedagogueClick(Sender: TObject);
procedure bCheckAllGroupClick(Sender: TObject);
procedure cmbAcademicYearChange(Sender: TObject);
private
PedagogueList: TResultTable;
GropeNameLastLesson: TResultTable;
AcademicYear: TResultTable;
FIDPedagogue: integer;
FIDAcademicYear: integer;
// FStrPedagogue: string;
// FStrAcademicYear: string;
id_learning_group: integer;
ending_period: string;
procedure SetIDPedagogue(const Value: integer);
procedure SetIDAcademicYear(const Value: integer);
// procedure SetStrPedagogue(const Value: string);
// procedure SetStrAcademicYear(const Value: string);
procedure ShowPedagogueList;
procedure ShowLGNameLastLesson(const IDPedagogue, IDAcademicYear: integer);
procedure Checking(const ListView: TListView;
const Check_, Pedagogue_: Boolean; Caption_: string; Button_: TButton);
public
property IDPedagogue: integer read FIDPedagogue write SetIDPedagogue;
property IDAcademicYear: integer read FIDAcademicYear
write SetIDAcademicYear;
// property StrPedagogue: string read FStrPedagogue write SetStrPedagogue;
// property StrAcademicYear: string read FStrAcademicYear write SetStrAcademicYear;
end;
var
fJournalOpening: TfJournalOpening;
implementation
{$R *.dfm}
{ TfJournalOpening }
procedure TfJournalOpening.bCheckAllGroupClick(Sender: TObject);
var
i: integer;
begin
if lvLGNameLastLesson.Items.Count > 0 then
begin
if bCheckAllGroup.Caption = 'Выбрать все группы / учащихся' then
begin
for i := 0 to lvLGNameLastLesson.Items.Count - 1 do
lvLGNameLastLesson.Items[i].Checked := true;
bCheckAllGroup.Caption := 'Убрать метки у всех групп/ учащихся';
end
else if bCheckAllGroup.Caption = 'Убрать метки у всех групп/ учащихся' then
begin
for i := 0 to lvLGNameLastLesson.Items.Count - 1 do
lvLGNameLastLesson.Items[i].Checked := false;
bCheckAllGroup.Caption := 'Выбрать все группы / учащихся';
end;
end
else
ShowMessage('Выберите педагога!');
end;
// TODO: разобраться, чтобы когда не нужно не срабатывало событие lvPedagogueListSelectItem
// при клике на lvPedagogueList будто срабатывает не SelectItem, а в lvLGNameLastLesson отображаются записы выбранного ранее педагога
// если несколько раз чекоть всех, то будто предыдущие выборы канут в лету, что происходит...
procedure TfJournalOpening.bCheckAllPedagogueClick(Sender: TObject);
var
i: integer;
begin
if bCheckAllPedagogue.Caption = 'Выбрать всех педагогов' then
begin
lvPedagogueList.Checkboxes := true;
lvPedagogueList.RowSelect := false;
for i := 0 to lvPedagogueList.Items.Count - 1 do
lvPedagogueList.Items[i].Checked := true;
bCheckAllPedagogue.Caption := 'Убрать метки у всех педагогов';
Panel2.Caption :=
'Журнал будет открыт для ВСЕХ групп/учащихся ВСЕХ педагогов!';
lvLGNameLastLesson.Enabled := false;
lvLGNameLastLesson.Clear;
bCheckAllGroup.Enabled := false;
end
else if bCheckAllPedagogue.Caption = 'Убрать метки у всех педагогов' then
begin
lvPedagogueList.Checkboxes := false;
lvPedagogueList.RowSelect := true;
bCheckAllPedagogue.Caption := 'Выбрать всех педагогов';
Panel2.Caption := '';
bCheckAllGroup.Caption := 'Выбрать все группы / учащихся';
bCheckAllGroup.Enabled := true;
lvLGNameLastLesson.Clear;
end;
end;
procedure TfJournalOpening.bOpenJournalClick(Sender: TObject);
var
i, ii, s, ss: integer;
begin
ending_period := DateToStr(DateTimePicker1.Date);
// если нет чекнутых записей, может быть выбран только один педагог, его ID получили в lvPedagogueListSelectItem
if lvPedagogueList.Checkboxes = false then
begin
ss := 0; // detail LV2
for ii := 0 to lvLGNameLastLesson.Items.Count - 1 do
if lvLGNameLastLesson.Items[ii].Checked then
ss := ss + 1; // пролистываем LV2, проверяем - есть ли чекнутые записи
if ss = 0 then // если нет, выходим из процедуры
begin
ShowMessage('Выберите группу / учащегося для открытия журнал!');
Exit;
end;
// пролистываем LV2 еще раз, работаем с чекнутыми записями
for ii := 0 to lvLGNameLastLesson.Items.Count - 1 do
// begin
if lvLGNameLastLesson.Items[ii].Checked then
begin
id_learning_group := GropeNameLastLesson[ii].ValueByName('ID_OUT');
if Kernel.SaveJournalForPeriod([id_learning_group, ending_period]) then
// ShowMessage('Сохранение выполнено!');
else
ShowMessage('Ошибка при сохранении!');
// end;
end;
end
else // lvPedagogueList.Checkboxes = true и если есть чекнутые записи в lvPedagogueListSelectItem, то листаем его
begin
s := 0; // master LV
for i := 0 to lvPedagogueList.Items.Count - 1 do
if lvPedagogueList.Items[i].Checked then
s := s + 1; // пролистываем lvPedagogueList, проверяем - есть ли чекнутые записи
if s = 0 then
begin
ShowMessage('Выберите педагога/педагогов для открытия журнала!');
Exit;
end;
if s > 0 then // пролистываем LV еще раз, работаем с чекнутыми записями
for i := 0 to lvPedagogueList.Items.Count - 1 do
// begin
if lvPedagogueList.Items[i].Checked then
begin
IDPedagogue := PedagogueList[i].ValueByName('ID_OUT');
for ii := 0 to lvLGNameLastLesson.Items.Count - 1 do
begin
id_learning_group := GropeNameLastLesson[ii].ValueByName('ID_OUT');
if Kernel.SaveJournalForPeriod([id_learning_group, ending_period])
then
// ShowMessage('Сохранение выполнено!');
else
ShowMessage('Ошибка при сохранении!');
end;
end;
// end;
end;
ShowLGNameLastLesson(IDPedagogue, IDAcademicYear);
end;
procedure TfJournalOpening.Checking(const ListView: TListView;
const Check_, Pedagogue_: Boolean; Caption_: string; Button_: TButton);
var
i: integer;
begin
// if Check_ = true then
// begin
// for i := 0 to ListView.Items.Count - 1 do
// ListView.Items[i].Checked := true;
// if Pedagogue_ = true then
// begin
// lvLGNameLastLesson.Enabled := false;
// Panel2.Caption :=
// 'Журнал будет открыт для ВСЕХ групп/учащихся ВСЕХ педагогов!';
// end
// else
// // lvLGNameLastLesson.Enabled := true;
// end
// else
// begin
// for i := 0 to ListView.Items.Count - 1 do
// ListView.Items[i].Checked := false;
// lvLGNameLastLesson.Enabled := true;
// end;
// Button_.Caption := Caption_;
end;
procedure TfJournalOpening.cmbAcademicYearChange(Sender: TObject);
begin
IDAcademicYear := AcademicYear[cmbAcademicYear.ItemIndex].ValueByName('ID');
ShowLGNameLastLesson(IDPedagogue, IDAcademicYear);
end;
procedure TfJournalOpening.DateTimePicker1Change(Sender: TObject);
begin
ending_period := DateToStr(DateTimePicker1.Date);
end;
procedure TfJournalOpening.FormCreate(Sender: TObject);
begin
PedagogueList := nil;
GropeNameLastLesson := nil;
AcademicYear := nil;
end;
procedure TfJournalOpening.FormDestroy(Sender: TObject);
begin
if Assigned(PedagogueList) then
FreeAndNil(PedagogueList);
if Assigned(GropeNameLastLesson) then
FreeAndNil(GropeNameLastLesson);
if Assigned(AcademicYear) then
FreeAndNil(AcademicYear);
end;
procedure TfJournalOpening.FormShow(Sender: TObject);
begin
ShowPedagogueList;
ShowLGNameLastLesson(IDPedagogue, IDAcademicYear);
ending_period := DateToStr(DateTimePicker1.Date);
if not Assigned(AcademicYear) then
AcademicYear := Kernel.GetAcademicYear;
Kernel.FillingComboBox(cmbAcademicYear, AcademicYear, 'NAME', false);
Kernel.ChooseComboBoxItemIndex(cmbAcademicYear, AcademicYear, true, 'ID',
IDAcademicYear);
DateTimePicker1.Date := Now;
end;
procedure TfJournalOpening.lvPedagogueListSelectItem(Sender: TObject;
Item: TListItem; Selected: Boolean);
begin
if PedagogueList.Count > 0 then // а надо ли проверку, если нет записей события не произойдет жэ
with PedagogueList[Item.Index] do
begin
IDPedagogue := ValueByName('ID_OUT');
ShowLGNameLastLesson(IDPedagogue, IDAcademicYear);
Panel2.Caption := 'Список групп / учащихся педагога: ' +
ValueByName('SURNAMENP');
end;
lvLGNameLastLesson.Enabled := true;
end;
procedure TfJournalOpening.SetIDAcademicYear(const Value: integer);
begin
if FIDAcademicYear <> Value then
FIDAcademicYear := Value;
end;
procedure TfJournalOpening.SetIDPedagogue(const Value: integer);
begin
if FIDPedagogue <> Value then
FIDPedagogue := Value;
end;
procedure TfJournalOpening.ShowLGNameLastLesson(const IDPedagogue,
IDAcademicYear: integer);
begin
if Assigned(GropeNameLastLesson) then
FreeAndNil(GropeNameLastLesson);
GropeNameLastLesson := Kernel.GetLGNameLastLesson(IDPedagogue,
IDAcademicYear);
Kernel.GetLVGropeNameLastLesson(lvLGNameLastLesson, GropeNameLastLesson);
if lvLGNameLastLesson.Items.Count > 0 then
lvLGNameLastLesson.ItemIndex := 0;
end;
procedure TfJournalOpening.ShowPedagogueList;
begin
if not Assigned(PedagogueList) then
PedagogueList := Kernel.GetPsnpForAutorization;
Kernel.GetLVPedagogueList(lvPedagogueList, PedagogueList);
if lvPedagogueList.Items.Count > 0 then
lvPedagogueList.ItemIndex := 0;
// по IDPedagogue сделать педагога чекнутым
end;
end.
|
unit GLDRepository;
interface
uses
Classes, GL, GLDTypes, GLDConst, GLDClasses,
GLDObjects, GLDCamera, GLDMaterial;
type
TGLDRepository = class(TGLDSysComponent)
private
FCameras: TGLDUserCameraList;
FMaterials: TGLDMaterialList;
FObjects: TGLDObjectList;
procedure SetCameras(Value: TGLDUserCameraList);
procedure SetMaterials(Value: TGLDMaterialList);
procedure SetObjects(Value: TGLDObjectList);
protected
procedure SetOnChange(Value: TNotifyEvent); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
procedure Clear;
procedure LoadFromStream(Stream: TStream);
procedure SaveToStream(Stream: TStream);
function Import3dsFile(const FileName: string): GLboolean;
procedure Render;
procedure RenderEdges;
procedure RenderWireframe;
procedure RenderBoundingBox;
procedure RenderForSelection;
procedure Select(Index: GLuint);
procedure AddSelection(Index: GLuint);
procedure DeleteSelections;
procedure DeleteSelectedObjects;
procedure CopyObjectsTo(ObjList: TGLDObjectList; CamList: TGLDUserCameraList);
procedure PasteObjectsFrom(ObjList: TGLDObjectList; CamList: TGLDUserCameraList);
function CenterOfSelectedObjects: TGLDVector3f;
function AverageOfRotations: TGLDRotation3D;
procedure MoveSelectedObjects(const Vector: TGLDVector3f);
procedure RotateSelectedObjects(const Rotation: TGLDRotation3D);
published
property Cameras: TGLDUserCameraList read FCameras write SetCameras;
property Materials: TGLDMaterialList read FMaterials write SetMaterials;
property Objects: TGLDObjectList read FObjects write SetObjects;
end;
procedure Register;
implementation
uses
SysUtils, GLDX, GLDMesh, dialogs,
{$INCLUDE GLD3dsUnits.inc};
constructor TGLDRepository.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCameras := TGLDUserCameraList.Create(Self);
FMaterials := TGLDMaterialList.Create(Self);
FObjects := TGLDObjectList.Create(Self);
end;
destructor TGLDRepository.Destroy;
begin
FObjects.Free;
FMaterials.Free;
FCameras.Free;
inherited Destroy;
end;
procedure TGLDRepository.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLDRepository) then Exit;
FCameras.Assign(TGLDRepository(Source).FCameras);
FMaterials.Assign(TGLDRepository(Source).FMaterials);
FObjects.Assign(TGLDRepository(Source).FObjects);
end;
procedure TGLDRepository.Clear;
begin
FCameras.Clear;
FMaterials.Clear;
FObjects.Clear;
end;
procedure TGLDRepository.LoadFromStream(Stream: TStream);
begin
FCameras.LoadFromStream(Stream);
FMaterials.LoadFromStream(Stream);
FObjects.LoadFromStream(Stream);
end;
procedure TGLDRepository.SaveToStream(Stream: TStream);
begin
FCameras.SaveToStream(Stream);
FMaterials.SaveToStream(Stream);
FObjects.SaveToStream(Stream);
end;
function TGLDRepository.Import3dsFile(const FileName: string): GLboolean;
var
F: TGLD3dsFile;
i: GLuint;
begin
Result := False;
if not FileExists(FileName) then Exit;
F := TGLD3dsFile.Create(nil);
if F.ReadFromFile(FileName) then
begin
if F.Meshes.Count > 0 then
for i := 1 to F.Meshes.Count do
begin
if FObjects.CreateNew(TGLDTriMesh) > 0 then
F.Meshes.Items[i].ConvertToTriMesh(FObjects.Last);
end;
Change;
Result := True;
end;
F.Free;
end;
procedure TGLDRepository.Render;
begin
FObjects.Render;
FCameras.RenderWireframe;
end;
procedure TGLDRepository.RenderEdges;
begin
FObjects.RenderEdges;
FCameras.RenderWireframe;
end;
procedure TGLDRepository.RenderWireframe;
begin
FObjects.RenderWireframe;
FCameras.RenderWireframe;
end;
procedure TGLDRepository.RenderBoundingBox;
begin
FObjects.RenderBoundingBox;
FCameras.RenderWireframe;
end;
procedure TGLDRepository.RenderForSelection;
begin
FObjects.RenderForSelection;
FCameras.RenderForSelection(FObjects.Count);
end;
procedure TGLDRepository.Select(Index: GLuint);
begin
if (Index > 0) and (Index <= FObjects.Count) then
begin
FCameras.DeleteSelections;
FObjects.Select(Index)
end else
if (Index > FObjects.Count) and
(Index <= FObjects.Count + FCameras.Count * 2) then
begin
FCameras.Select(FObjects.Count, Index);
FObjects.DeleteSelections;
end;
end;
procedure TGLDRepository.AddSelection(Index: GLuint);
begin
if (Index > 0) and (Index <= FObjects.Count) then
FObjects.AddSelection(Index) else
if (Index > FObjects.Count) and
(Index <= FObjects.Count + FCameras.Count * 2) then
FCameras.AddSelection(FObjects.Count, Index);
end;
procedure TGLDRepository.DeleteSelections;
begin
FObjects.DeleteSelections;
FCameras.DeleteSelections;
end;
procedure TGLDRepository.DeleteSelectedObjects;
begin
FObjects.DeleteSelectedObjects;
FCameras.DeleteSelectedCameras;
end;
procedure TGLDRepository.CopyObjectsTo(ObjList: TGLDObjectList; CamList: TGLDUserCameraList);
begin
FObjects.CopySelectedObjectsTo(ObjList);
FCameras.CopySelectedCamerasTo(CamList);
end;
procedure TGLDRepository.PasteObjectsFrom(ObjList: TGLDObjectList; CamList: TGLDUserCameraList);
begin
FObjects.PasteObjectsFrom(ObjList);
FCameras.PasteCamerasFrom(CamList);
end;
function TGLDRepository.CenterOfSelectedObjects: TGLDVector3f;
var
Cnt: GLubyte;
begin
Result := GLDXVectorAdd(FObjects.CenterOfSelectedObjects,
FCameras.CenterOfSelectedObjects);
Cnt := 0;
if FObjects.SelectionCount > 0 then Inc(Cnt);
if FCameras.SelectionCount > 0 then Inc(Cnt);
if Cnt > 0 then
begin
if Result.X <> 0 then Result.X := Result.X / Cnt;
if Result.Y <> 0 then Result.Y := Result.Y / Cnt;
if Result.Z <> 0 then Result.Z := Result.Z / Cnt;
end;
end;
function TGLDRepository.AverageOfRotations: TGLDRotation3D;
var
Cnt: GLubyte;
begin
Result := GLDXRotation3DAdd(FObjects.AverageOfRotations,
FCameras.AverageOfRotations);
Cnt := 0;
if FObjects.SelectionCount > 0 then Inc(Cnt);
if FCameras.SelectionCount > 0 then Inc(Cnt);
if Cnt > 0 then
begin
if Result.XAngle <> 0 then Result.XAngle := Result.XAngle / Cnt;
if Result.YAngle <> 0 then Result.YAngle := Result.YAngle / Cnt;
if Result.ZAngle <> 0 then Result.ZAngle := Result.ZAngle / Cnt;
end;
end;
procedure TGLDRepository.MoveSelectedObjects(const Vector: TGLDVector3f);
begin
FObjects.MoveSelectedObjects(Vector);
FCameras.MoveSelectedObjects(Vector);
end;
procedure TGLDRepository.RotateSelectedObjects(const Rotation: TGLDRotation3D);
begin
FObjects.RotateSelectedObjects(Rotation);
FCameras.RotateSelectedObjects(Rotation);
end;
procedure TGLDRepository.SetOnChange(Value: TNotifyEvent);
begin
FOnChange := Value;
FCameras.OnChange := Value;
FMaterials.OnChange := Value;
FObjects.OnChange := Value;
end;
procedure TGLDRepository.SetCameras(Value: TGLDUserCameraList);
begin
if Value = nil then Exit;
FCameras.Assign(Value);
end;
procedure TGLDRepository.SetMaterials(Value: TGLDMaterialList);
begin
if Value = nil then Exit;
FMaterials.Assign(Value);
end;
procedure TGLDRepository.SetObjects(Value: TGLDObjectList);
begin
if Value = nil then Exit;
FObjects.Assign(Value);
end;
procedure Register;
begin
RegisterComponents('GLDraw', [TGLDRepository]);
end;
end.
|
unit uTestClass;
interface
type TOnLogEvent = procedure(Sender: TObject; AText: string) of object;
type TTestClass = class(TObject)
private
FOnLog: TOnLogEvent;
public
Caption: string;
constructor Create;
destructor Destroy; override;
procedure Start; virtual;
procedure Log(AText: string);
property OnLog: TOnLogEvent read FOnLog write FOnLog;
end;
implementation
{ TTestClass }
//==============================================================================
constructor TTestClass.Create;
begin
end;
//==============================================================================
destructor TTestClass.Destroy;
begin
inherited;
end;
//==============================================================================
procedure TTestClass.Log(AText: string);
begin
if Assigned(FOnLog) then
FOnLog(Self, AText);
end;
//==============================================================================
procedure TTestClass.Start;
begin
Log('Start test - ' + Caption);
end;
//==============================================================================
end.
|
unit Call_Frm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons,
Vcl.ExtCtrls, Vcl.ComCtrls, SIPVoipSDK_TLB, Vcl.ImgList;
type
TFrameCall = class(TFrame)
pnlMenu: TPanel;
Menu: TGridPanel;
GridMain: TGridPanel;
ButtonVoice: TSpeedButton;
ButtonCall: TSpeedButton;
ButtonVideo: TSpeedButton;
lbl1: TLabel;
TrackBarVolume: TTrackBar;
lbl2: TLabel;
ImageList: TImageList;
Panel1: TPanel;
ButtonClose: TSpeedButton;
GridMessageSend: TGridPanel;
mmoMessage: TMemo;
ButtonSend: TSpeedButton;
pnl1: TPanel;
lstMessage: TListBox;
procedure ButtonCallClick(Sender: TObject);
private
procedure CMRelease(var Message: TMessage); message CM_RELEASE;
public
gIsCallEstablish: Boolean;
pUserName: string;
pUserId: string;
procedure Release;
procedure AbtoPhone_OnEstablishedCall(ASender: TObject;
const Msg: WideString; LineId: Integer);
procedure AbtoPhone_OnTextMessageReceived(ASender: TObject;
const address: WideString; const Message: WideString);
procedure Load(Phone: TCAbtoPhone);
constructor Create(AOwner: TComponent); override;
property gUserName: string read pUserName write pUserName;
property gUserId: string read pUserName write pUserId;
published
property ClientHeight;
property ClientWidth;
end;
var
AbtoPhone: TCAbtoPhone;
implementation
{$R *.dfm}
uses Main_Wnd;
procedure TFrameCall.AbtoPhone_OnTextMessageReceived(ASender: TObject;
const address, Message: WideString);
begin
//
end;
procedure TFrameCall.ButtonCallClick(Sender: TObject);
var
tmpBitmap: TBitmap;
begin
tmpBitmap := TBitmap.Create();
if gIsCallEstablish then
begin
AbtoPhone.HangUpLastCall;
ImageList.GetBitmap(4, tmpBitmap);
ButtonCall.Glyph := tmpBitmap;
gIsCallEstablish := False;
end
else
begin
AbtoPhone.StartCall(gUserName + '@iptel.org');
ImageList.GetBitmap(3, tmpBitmap);
ButtonCall.Glyph := tmpBitmap;
end
end;
procedure TFrameCall.CMRelease(var Message: TMessage);
begin
Free;
end;
procedure TFrameCall.Release;
begin
PostMessage(Handle, CM_RELEASE, 0, 0);
end;
constructor TFrameCall.Create(AOwner: TComponent);
begin
inherited;
ButtonClose.Caption := '';
end;
procedure TFrameCall.Load(Phone: TCAbtoPhone);
begin
AbtoPhone := Phone;
gIsCallEstablish := False;
AbtoPhone.OnEstablishedCall := AbtoPhone_OnEstablishedCall;
end;
procedure TFrameCall.AbtoPhone_OnEstablishedCall(ASender: TObject;
const Msg: WideString; LineId: Integer);
begin
gIsCallEstablish := True;
end;
end.
|
//------------------------------------------------------------------------------
//AddFriendEvent UNIT
//------------------------------------------------------------------------------
// What it does-
// An event used when add friend.
//
// Changes -
// [2007/12/08] - Aeomin - Created
//
//------------------------------------------------------------------------------
unit AddFriendEvent;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
{RTL/VCL}
//none
{Project}
Being,
Event
{3rd Party}
//none
;
type
//------------------------------------------------------------------------------
//TFriendRequestEvent
//------------------------------------------------------------------------------
TFriendRequestEvent = class(TRootEvent)
private
ABeing : TBeing;
public
PendingFriend : LongWord;
constructor Create(SetExpiryTime : LongWord; Being : TBeing);
end;
//------------------------------------------------------------------------------
implementation
constructor TFriendRequestEvent.Create(SetExpiryTime : LongWord; Being : TBeing);
begin
inherited Create(SetExpiryTime);
Self.ABeing := Being;
end;
end. |
unit MeshSmoothMasters;
// This is the third type of mesh smooth made for this program made for my Master
// Dissertation. It works with manifold meshes where all vertexes must be real
// vertexes (and not part of edges or faces). If these conditions are met, the
// results are interesting using a single interaction, regardless of how irregular
// is the mesh. However, the execution time is slower than other methods.
interface
uses MeshProcessingBase, Mesh, BasicMathsTypes, BasicDataTypes, NeighborDetector,
LOD;
{$INCLUDE source/Global_Conditionals.inc}
type
TMeshSmoothMasters = class (TMeshProcessingBase)
protected
procedure MeshSmoothOperation(var _Vertices,_VertexNormals,_FaceNormals: TAVector3f; const _Faces:auint32; _NumVertices,_VerticesPerFace: integer; const _VertexNeighborDetector,_FaceNeighborDetector: TNeighborDetector; const _VertexEquivalences: auint32);
procedure DoMeshProcessing(var _Mesh: TMesh); override;
public
DistanceFunction: TDistanceFunc;
constructor Create(var _LOD: TLOD); override;
end;
implementation
uses MeshPluginBase, MeshBRepGeometry, NeighborhoodDataPlugin, GLConstants, Math,
VertexTransformationUtils, math3d, SysUtils, GlobalVars, DistanceFormulas,
MeshNormalVectorCalculator;
constructor TMeshSmoothMasters.Create(var _LOD: TLOD);
begin
inherited Create(_LOD);
DistanceFunction := GetLinearDistance;
end;
procedure TMeshSmoothMasters.DoMeshProcessing(var _Mesh: TMesh);
var
VertexNeighborDetector,FaceNeighborDetector : TNeighborDetector;
NeighborhoodPlugin : PMeshPluginBase;
NumVertices: integer;
VertexEquivalences: auint32;
MyFaces: auint32;
MyFaceNormals: TAVector3f;
MyVerticesPerFace: integer;
Calculator: TMeshNormalVectorCalculator;
begin
_Mesh.Geometry.GoToFirstElement;
NeighborhoodPlugin := _Mesh.GetPlugin(C_MPL_NEIGHBOOR);
if NeighborhoodPlugin <> nil then
begin
VertexNeighborDetector := TNeighborhoodDataPlugin(NeighborhoodPlugin^).VertexNeighbors;
FaceNeighborDetector := TNeighborhoodDataPlugin(NeighborhoodPlugin^).FaceNeighbors;
NumVertices := TNeighborhoodDataPlugin(NeighborhoodPlugin^).InitialVertexCount;
VertexEquivalences := TNeighborhoodDataPlugin(NeighborhoodPlugin^).VertexEquivalences;
end
else
begin
VertexNeighborDetector := TNeighborDetector.Create;
VertexNeighborDetector.BuildUpData(_Mesh.Geometry,High(_Mesh.Vertices)+1);
_Mesh.Geometry.GoToFirstElement;
FaceNeighborDetector := TNeighborDetector.Create(C_NEIGHBTYPE_VERTEX_FACE);
FaceNeighborDetector.BuildUpData(_Mesh.Geometry,High(_Mesh.Vertices)+1);
NumVertices := High(_Mesh.Vertices)+1;
VertexEquivalences := nil;
end;
MyFaces := (_Mesh.Geometry.Current^ as TMeshBRepGeometry).Faces;
MyFaceNormals := (_Mesh.Geometry.Current^ as TMeshBRepGeometry).Normals;
MyVerticesPerFace := (_Mesh.Geometry.Current^ as TMeshBRepGeometry).VerticesPerFace;
if High(_Mesh.Normals) <= 0 then
begin
Calculator := TMeshNormalVectorCalculator.Create;
Calculator.FindMeshVertexNormals(_Mesh);
Calculator.Free;
end;
MeshSmoothOperation(_Mesh.Vertices,_Mesh.Normals,MyFaceNormals,MyFaces,NumVertices,MyVerticesPerFace,VertexNeighborDetector,FaceNeighborDetector,VertexEquivalences);
// Free memory
if NeighborhoodPlugin = nil then
begin
VertexNeighborDetector.Free;
FaceNeighborDetector.Free;
end;
_Mesh.ForceRefresh;
end;
procedure TMeshSmoothMasters.MeshSmoothOperation(var _Vertices,_VertexNormals,_FaceNormals: TAVector3f; const _Faces:auint32; _NumVertices,_VerticesPerFace: integer; const _VertexNeighborDetector,_FaceNeighborDetector: TNeighborDetector; const _VertexEquivalences: auint32);
const
C_2Pi = Pi * 2;
var
HitCounter,Weight: single;
OriginalVertexes : TAVector3f;
v,v1,i,mini,maxi : integer;
nv : array[0..1] of integer;
IsConcave,Found: boolean;
CossineAngle: single;
Direction,LaplacianDirection: TVector3f;
CurrentScale,MaxScale,Frequency: single;
Util : TVertexTransformationUtils;
begin
Util := TVertexTransformationUtils.Create;
SetLength(OriginalVertexes,High(_Vertices)+1);
BackupVector3f(_Vertices,OriginalVertexes);
// Sum up vertices with its neighbours, using the desired distance formula.
for v := Low(_Vertices) to (_NumVertices-1) do
begin
HitCounter := 0;
MaxScale := 999999;
IsConcave := false;
v1 := _VertexNeighborDetector.GetNeighborFromID(v);
while v1 <> -1 do
begin
// Check if the vertex is concave or conves to determine the direction
// of the final vertex translation.
Direction := SubtractVector(OriginalVertexes[v1],OriginalVertexes[v]);
Normalize(Direction);
CossineAngle := DotProduct(_VertexNormals[v],Direction);
IsConcave := IsConcave or (CossineAngle < 0);
// Check the maximum possible scale of the final vertex translation
Direction := SubtractVector(OriginalVertexes[v],OriginalVertexes[v1]);
Normalize(Direction);
CurrentScale := Abs(DotProduct(Direction,_VertexNormals[v]));
// if (CurrentScale <> 0) and (CurrentScale < MaxScale) then
if (CurrentScale < MaxScale) then
begin
MaxScale := CurrentScale;
end;
{$ifdef SMOOTH_TEST}
{
if CurrentScale = 0 then
begin
GlobalVars.SmoothFile.Add('v1 = ' + IntToStr(v1) + ' = (' + FloatToStr(OriginalVertexes[v1].X) + ', ' + FloatToStr(OriginalVertexes[v1].Y) + ', ' + FloatToStr(OriginalVertexes[v1].Z) + ') forces MaxScale 0 with v = ' + IntToStr(v));
end;
}
{$endif}
v1 := _VertexNeighborDetector.GetNextNeighbor;
end;
if MaxScale = 999999 then
MaxScale := 0;
if IsConcave then
begin
LaplacianDirection := ScaleVector(_VertexNormals[v],-1);
{$ifdef SMOOTH_TEST}
GlobalVars.SmoothFile.Add('vertex ' + IntToStr(v) + ' is concave.');
{$endif}
end
else
begin
LaplacianDirection := SetVector(_VertexNormals[v]);
{$ifdef SMOOTH_TEST}
GlobalVars.SmoothFile.Add('vertex ' + IntToStr(v) + ' is convex.');
{$endif}
end;
{$ifdef SMOOTH_TEST}
GlobalVars.SmoothFile.Add('v = ' + IntToStr(v) + ' = (' + FloatToStr(OriginalVertexes[v].X) + ', ' + FloatToStr(OriginalVertexes[v].Y) + ', ' + FloatToStr(OriginalVertexes[v].Z) + ') , MaxScale: ' + FloatToStr(MaxScale));
{$endif}
// Finally, we do an average for all vertices.
Frequency := 0;
v1 := _FaceNeighborDetector.GetNeighborFromID(v); // face neighbour of the vertex v
if MaxScale > 0 then
begin
while v1 <> -1 do
begin
// Obtain both edges of the face that has v
mini := v1 * _VerticesPerFace;
maxi := mini + _VerticesPerFace - 1;
Found := false;
// Find v in the face.
i := 0;
while (i < _VerticesPerFace) and (not Found) do
begin
if _Faces[mini + i] = v then
begin
Found := true;
end
else
begin
inc(i);
end;
end;
// Now we obtain both edges (actually vertexes that have edges with v)
if i = 0 then
begin
nv[0] := _Faces[maxi];
nv[1] := _Faces[mini + 1];
end
else if i = (_VerticesPerFace-1) then
begin
nv[0] := _Faces[maxi - 1];
nv[1] := _Faces[mini];
end
else
begin
nv[0] := _Faces[mini + i - 1];
nv[1] := _Faces[mini + i + 1];
end;
// Obtain the percentage of angle from the triangle at tangent space level
Weight := Util.GetArcCosineFromAngleOnTangentSpace(OriginalVertexes[v],OriginalVertexes[nv[0]],OriginalVertexes[nv[1]],_VertexNormals[v]) / C_2Pi;
HitCounter := HitCounter + Weight;
// Obtain dot product of face normal and vertex normal
Frequency := Frequency + ((1 - abs(DotProduct(_VertexNormals[v],_FaceNormals[v1]))) * Weight);
v1 := _FaceNeighborDetector.GetNextNeighbor;
end;
{$ifdef SMOOTH_TEST}
GlobalVars.SmoothFile.Add('v = ' + IntToStr(v) + ', Weight Value: ' + FloatToStr(Weight) + ', MaxScale: ' + FloatToStr(MaxScale) + ', Frequency: ' +FloatToStr(Frequency) + ') with ' + FloatToStr(HitCounter*100) + ' % of the neighbourhood. Expected frequency: (' + FloatToStr(Frequency / HitCounter) + ')');
{$endif}
end;
if HitCounter > 0 then
begin
CurrentScale := MaxScale * DistanceFunction(Frequency / HitCounter);
_Vertices[v].X := OriginalVertexes[v].X + CurrentScale * LaplacianDirection.X;
_Vertices[v].Y := OriginalVertexes[v].Y + CurrentScale * LaplacianDirection.Y;
_Vertices[v].Z := OriginalVertexes[v].Z + CurrentScale * LaplacianDirection.Z;
{$ifdef SMOOTH_TEST}
GlobalVars.SmoothFile.Add('New position for vertex ' + IntToStr(v) + ' = (' + FloatToStr(_Vertices[v].X) + ', ' + FloatToStr(_Vertices[v].Y) + ', ' + FloatToStr(_Vertices[v].Z) + ') , Intensity: ' + FloatToStr(CurrentScale));
{$endif}
end
else
begin
_Vertices[v].X := OriginalVertexes[v].X;
_Vertices[v].Y := OriginalVertexes[v].Y;
_Vertices[v].Z := OriginalVertexes[v].Z;
{$ifdef SMOOTH_TEST}
GlobalVars.SmoothFile.Add('Vertex ' + IntToStr(v) + ' = (' + FloatToStr(_Vertices[v].X) + ', ' + FloatToStr(_Vertices[v].Y) + ', ' + FloatToStr(_Vertices[v].Z) + ') was not moved.');
{$endif}
end;
end;
v := _NumVertices;
while v <= High(_Vertices) do
begin
v1 := GetEquivalentVertex(v,_NumVertices,_VertexEquivalences);
_Vertices[v].X := _Vertices[v1].X;
_Vertices[v].Y := _Vertices[v1].Y;
_Vertices[v].Z := _Vertices[v1].Z;
inc(v);
end;
// Free memory
SetLength(OriginalVertexes,0);
Util.Free;
end;
end.
|
{*
FtermSSH : An SSH implementation in Delphi for FTerm2 by kxn@cic.tsinghua.edu.cn
Cryptograpical code from OpenSSL Project
*}
unit sshsession;
interface
uses sshkex, sshmac, sshcipher, sshutil, wsocket, sshauth, sshchannel;
type
TSSHSession = class;
TAuthUserPrompt = procedure(Sender: TSSHSession; var user: string;
var canceled: boolean) of object;
TAuthPassPrompt = procedure(Sender: TSSHSession; var pass: string;
var canceled: boolean) of object;
TSSHSession = class
private
FAuthUser: TAuthUserPrompt;
FAuthPass: TAuthPassPrompt;
public
Closed: boolean;
InBuffer: TSSHBuffer;
OutBuffer: TSSHBuffer;
Auth: TSSHAuth;
Sock: TWSocket;
MainChan: TSSHChannel;
constructor Create(Owner: TObject); virtual;
destructor Destroy; override;
procedure Write(Data: Pointer; Len: integer); virtual;
procedure WriteDefer(Data: Pointer; Len: integer); virtual;
procedure OnPacket(Packet: TSSHPacketReceiver); virtual;
procedure Disconnect(reasonstr: string); virtual;
procedure OnDisConnectHandler(reason: integer); virtual;
//procedure OnUserPrompt(var user:string;var canceled:boolean);
//procedure OnPassPrompt(var pass:string;var canceled:boolean);
procedure ChangeWindowSize(col, row: integer); virtual;
published
property OnUserPrompt: TAuthUserPrompt read FAuthUser write FAuthUser;
property OnPassPrompt: TAuthPassPrompt read FAuthPass write FAuthPass;
end;
TSSH1ServiceState = (BEGIN_SERVICE, REQPTY_SENT, REQCMD_SENT, SERVICE_OK);
TSSH1Session = class(TSSHSession)
private
SrvState: TSSH1ServiceState;
function InitServices(Buffer: TSSH1PacketReceiver): boolean;
public
InPacket: TSSH1PacketReceiver;
OutPacket: TSSH1PacketSender;
CSCipher, SCCipher: TSSHCipher;
KeyEx: TSSH1Kex;
Auth: TSSH1PASSWDAuth;
constructor Create(Owner: TObject); override;
destructor Destroy; override;
procedure OnPacket(Packet: TSSHPacketReceiver); override;
procedure Disconnect(reasonstr: string); override;
procedure ChangeWindowSize(col, row: integer); override;
end;
TSSH2ServiceState = (BEGIN_SERVICE2, REQPTY_SENT2, REQCMD_SENT2, SERVICE_OK2);
TSSH2Session = class(TSSHSession)
private
state: TSSH2ServiceState;
function InitServices(Buffer: TSSH2PacketReceiver): boolean;
public
KeyEx: TSSH2Kex;
schmac, cshmac: TSSH2MAC;
sccipher, cscipher: TSSHCipher;
inseq, outseq: integer;
InPacket: TSSH2PacketReceiver;
OutPacket: TSSH2PacketSender;
SessionID: array [1..20] of byte;
Channels: array of TSSH2Channel;
constructor Create(Owner: TObject); override;
destructor Destroy; override;
procedure OnPacket(Packet: TSSHPacketReceiver); override;
procedure Disconnect(reasonstr: string); override;
procedure AddChannel(Chn: TSSH2Channel);
procedure CloseChannel(chnid: integer);
function FindChannel(id: integer): TSSH2Channel;
procedure ChangeWindowSize(col, row: integer); override;
end;
implementation
uses Dialogs, sshconst, sshwsock;
{ TSSH2Session }
procedure TSSH2Session.AddChannel(Chn: TSSH2Channel);
var
i: integer;
begin
for i := 0 to high(Channels) do
if Chn = Channels[i] then raise ESSHError.Create('duplicate channel?');
SetLength(Channels, high(Channels) + 2);
Channels[high(Channels)] := Chn;
end;
procedure TSSH2Session.ChangeWindowSize(col, row: integer);
begin
if not Assigned(MainChan) then exit;
OutPacket.StartPacket(SSH2_MSG_CHANNEL_REQUEST);
OutPacket.AddInteger(TSSH2Channel(MainChan).RemoteChannelID);
OutPacket.AddString('window-change');
OutPacket.AddByte(0);
OutPacket.AddInteger(col);
OutPacket.AddInteger(row);
OutPacket.AddInteger(0);
OutPacket.AddInteger(0);
OutPacket.Write;
end;
procedure TSSH2Session.CloseChannel(chnid: integer);
var
i: integer;
j: integer;
begin
for i := 0 to high(Channels) do
with Channels[i] as TSSH2Channel do
if chnid = LocalChannelID then
begin
Free;
for j := i to high(Channels) - 1 do
Channels[j] := Channels[j + 1];
SetLength(Channels, high(Channels));
if Length(Channels) = 0 then
begin
DisConnect('session close');
exit;
end;
end;
end;
constructor TSSH2Session.Create(Owner: TObject);
begin
inherited Create(Owner);
InPacket := TSSH2PacketReceiver.Create(self);
OutPacket := TSSH2PacketSender.Create(self);
KeyEx := TSSH2DHGSHA1Kex.Create(self);
Auth := TSSH2PASSWDAuth.Create(Self);
state := BEGIN_SERVICE2;
end;
destructor TSSH2Session.Destroy;
var
i: integer;
begin
for i := 0 to high(Channels) do
if Assigned(Channels[i]) then Channels[i].Free;
if Assigned(KeyEx) then KeyEx.Free;
if Assigned(Auth) then Auth.Free;
if Assigned(CSCipher) then CScipher.Free;
if Assigned(ScCipher) then Sccipher.Free;
if Assigned(SCHmac) then schmac.Free;
if Assigned(cshmac) then cshmac.Free;
if Assigned(InPacket) then InPacket.Free;
if Assigned(OutPacket) then OutPacket.Free;
inherited;
end;
procedure TSSH2Session.Disconnect(reasonstr: string);
begin
OutPacket.StartPacket(SSH2_MSG_DISCONNECT);
OutPacket.AddInteger(SSH2_DISCONNECT_BY_APPLICATION);
OutPacket.AddString(reasonstr);
OutPacket.Write;
Closed := True;
end;
function TSSH2Session.FindChannel(id: integer): TSSH2Channel;
var
i: integer;
begin
for i := 0 to high(channels) do
with Channels[i] as TSSH2Channel do
if LocalChannelId = id then
begin
Result := channels[i];
exit;
end;
Result := nil;
end;
function TSSH2Session.InitServices(Buffer: TSSH2PacketReceiver): boolean;
var
remoteid: integer;
Chn: TSSH2Channel;
ConsumedLen: integer;
i: integer;
wantreply: byte;
cmdstr: string;
begin
Result := False;
case state of
BEGIN_SERVICE2:
begin
OutPacket.StartPacket(SSH2_MSG_CHANNEL_REQUEST);
OutPacket.AddInteger(TSSH2Channel(MainChan).RemoteChannelID);
OutPacket.AddString('pty-req');
OutPacket.AddByte(1);
OutPacket.AddString(TSSHWSocket(Sock).stermtype);
OutPacket.AddInteger(TSSHWSocket(Sock).cols);
OutPacket.AddInteger(TSSHWSocket(Sock).rows);
OutPacket.AddInteger(0);
OutPacket.AddInteger(0);
OutPacket.AddInteger(1);
OutPacket.AddByte(0); // It is a zero string, length 1
OutPacket.Write;
state := REQPTY_SENT2;
Result := True;
end;
REQPTY_SENT2:
begin
if Buffer.PacketType <> SSH2_MSG_CHANNEL_SUCCESS then
raise ESSHError.Create('Server refuses allocate pty!');
OutPacket.StartPacket(SSH2_MSG_CHANNEL_REQUEST);
OutPacket.AddInteger(TSSH2Channel(MainChan).RemoteChannelID);
OutPacket.AddString('shell');
OutPacket.AddByte(1);
OutPacket.Write;
state := REQCMD_SENT2;
Result := True;
end;
REQCMD_SENT2:
begin
if Buffer.PacketType <> SSH2_MSG_CHANNEL_SUCCESS then
raise ESSHError.Create('Server refuses shell request');
state := SERVICE_OK2;
Result := True;
end;
SERVICE_OK2:
begin
Consumedlen := 0;
chn := nil;
case Buffer.PacketType of
SSH2_MSG_CHANNEL_DATA:
begin
buffer.GetInteger(remoteid);
chn := FindChannel(remoteid);
if chn <> nil then
begin
Buffer.GetInteger(i);
if Assigned(chn.OnDataAvalible) then
chn.OnDataAvalible(buffer.Buffer.Data, i);
Consumedlen := i;
end;
end;
SSH2_MSG_CHANNEL_EXTENDED_DATA:
begin
buffer.GetInteger(remoteid);
chn := FindChannel(remoteid);
if chn <> nil then
begin
Buffer.GetInteger(i);
if i = SSH2_EXTENDED_DATA_STDERR then
begin
Buffer.GetInteger(i);
if Assigned(chn.OnExtDataAvalible) then
chn.OnExtDataAvalible(buffer.Buffer.Data, i);
Consumedlen := i;
end
else
Buffer.GetInteger(Consumedlen);
end;
end;
SSH2_MSG_CHANNEL_EOF:
begin
buffer.GetInteger(remoteid);
chn := FindChannel(remoteid);
if (chn <> nil) and (chn <> MainChan) then
begin
OutPacket.StartPacket(SSH2_MSG_CHANNEL_CLOSE);
OutPacket.AddInteger(chn.RemoteChannelID);
OutPacket.Write;
end;
end;
SSH2_MSG_CHANNEL_CLOSE:
begin
buffer.GetInteger(remoteid);
chn := FindChannel(remoteid);
if (chn <> nil) then
begin
if chn = MainChan then MainChan := nil;
CloseChannel(chn.LocalChannelID);
end;
end;
SSH2_MSG_CHANNEL_OPEN_CONFIRMATION,
SSH2_MSG_CHANNEL_OPEN_FAILURE:
begin
// do nothing!
end;
SSH2_MSG_CHANNEL_REQUEST:
begin
buffer.GetInteger(remoteid);
chn := FindChannel(remoteid);
if chn = nil then
begin
DisConnect('faint');
end;
buffer.GetString(cmdstr);
buffer.GetByte(wantreply);
// BUG rejected all request
if wantreply = 1 then
begin
OutPacket.StartPacket(SSH2_MSG_CHANNEL_FAILURE);
OutPacket.AddInteger(chn.RemoteChannelID);
OutPacket.Write;
end;
end;
SSH2_MSG_GLOBAL_REQUEST:
begin
buffer.GetString(cmdstr);
buffer.GetByte(wantreply);
// BUG rejected all request
if wantreply = 1 then
begin
OutPacket.StartPacket(SSH2_MSG_REQUEST_FAILURE);
OutPacket.AddInteger(chn.RemoteChannelID);
OutPacket.Write;
end;
end;
SSH2_MSG_CHANNEL_OPEN:
begin
buffer.GetString(cmdstr);
buffer.GetInteger(remoteid);
OutPacket.StartPacket(SSH2_MSG_CHANNEL_OPEN_FAILURE);
OutPacket.AddInteger(remoteid);
OutPacket.AddInteger(SSH2_OPEN_CONNECT_FAILED);
OutPacket.AddString('not supported');
OutPacket.AddString('en');
OutPacket.Write;
end;
end;
// if the frontend consumed some data , we adjust the remote window
if (Consumedlen <> 0) and (chn <> nil) then
begin
OutPacket.StartPacket(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
OutPacket.AddInteger(chn.RemoteChannelID);
OutPacket.AddInteger(ConsumedLen);
OutPacket.Write; // we do not care the local window in fact
end;
// BUG : only send main channel's data
if Assigned(MainChan) then MainChan.Flush;
end;
end;
end;
procedure TSSH2Session.OnPacket(Packet: TSSHPacketReceiver);
begin
with keyex as TSSH2DHGSHA1Kex do
begin
if not OnPacket(TSSH2PacketReceiver(Packet)) then
if not auth.OnPacket(Packet) then
InitServices(TSSH2PacketReceiver(Packet));;
end;
end;
procedure TSSHSession.Write(Data: Pointer; Len: integer);
begin
if OutBuffer.Length > 0 then
begin
TSSHWSocket(Sock).MySend(OutBuffer.Data, OutBuffer.Length);
OutBuffer.Reset;
end;
TSSHWSocket(sock).MySend(Data, Len);
end;
procedure TSSHSession.WriteDefer(Data: Pointer; Len: integer);
begin
OutBuffer.Add(Data, Len);
end;
{ TSSH1Session }
procedure TSSH1Session.ChangeWindowSize(col, row: integer);
begin
OutPacket.StartPacket(SSH1_CMSG_WINDOW_SIZE);
OutPacket.AddInteger(row);
OutPacket.AddInteger(col);
OutPacket.AddInteger(0);
OutPacket.AddInteger(0);
OutPacket.Write;
end;
constructor TSSH1Session.Create(Owner: TObject);
begin
inherited Create(Owner);
InPacket := TSSH1PacketReceiver.Create(Self);
OutPacket := TSSH1PacketSender.Create(Self);
KeyEx := TSSH1Kex.Create(Self);
Auth := TSSH1PASSWDAuth.Create(Self);
SrvState := BEGIN_SERVICE;
end;
destructor TSSH1Session.Destroy;
begin
if Assigned(SCCipher) then SCCipher.Free;
if Assigned(CSCipher) then CSCipher.Free;
if Assigned(InPacket) then InPacket.Free;
if Assigned(OutPacket) then OutPacket.Free;
if Assigned(MainChan) then MainChan.Free;
if Assigned(Auth) then Auth.Free;
if Assigned(KeyEx) then KeyEx.Free;
inherited;
end;
procedure TSSH1Session.Disconnect(reasonstr: string);
begin
OutPacket.StartPacket(SSH1_MSG_DISCONNECT);
OutPacket.AddString(reasonstr);
OutPacket.Write;
Closed := True;
end;
function TSSH1Session.InitServices(Buffer: TSSH1PacketReceiver): boolean;
var
i: integer;
Error: word;
begin
Result := False;
case SrvState of
BEGIN_SERVICE:
begin
OutPacket.StartPacket(SSH1_CMSG_REQUEST_PTY);
// pty request is of no use in BBS , but we do this
OutPacket.AddString(TSSHWSocket(Sock).stermtype); // term type
OutPacket.AddInteger(TSSHWSocket(Sock).rows); // row
OutPacket.AddInteger(TSSHWSocket(Sock).cols); //col
OutPacket.AddInteger(0); // ???
OutPacket.AddInteger(0); // ???
OutPacket.AddByte(0);
OutPacket.Write;
Srvstate := REQPTY_SENT;
Result := True;
end;
REQPTY_SENT:
begin
// in theory the client can continue without a pty
// but since SecureCRT bombs out error here,we won't continue
if Buffer.PacketType <> SSH1_SMSG_SUCCESS then
raise ESSHError.Create('server refused pty allocation');
OutPacket.StartPacket(SSH1_CMSG_EXEC_SHELL);
OutPacket.Write;
Srvstate := SERVICE_OK;
MainChan := TSSH1Channel.Create(Self);
MainChan.OnDataAvalible := TSSHWSocket(Sock).AddData;
// trigger the session
Error := 0;
TSSHWSocket(Sock).DoTriggerSessionConnected(Error);
Result := True;
end;
REQCMD_SENT:
begin
// faint
if Buffer.PacketType <> SSH1_SMSG_SUCCESS then
raise ESSHError.Create('server did not say success to shell request');
MainChan := TSSH1Channel.Create(Self);
Srvstate := SERVICE_OK;
Result := True;
end;
SERVICE_OK:
begin
// this is the final step
case Buffer.PacketType of
SSH1_SMSG_STDOUT_DATA,
SSH1_SMSG_STDERR_DATA:
begin
Buffer.GetInteger(i);
MainChan.OnDataAvalible(Buffer.Buffer.Data, i);
end;
SSH1_SMSG_X11_OPEN,
SSH1_SMSG_AGENT_OPEN,
SSH1_MSG_PORT_OPEN:
begin
Buffer.GetInteger(i);
OutPacket.StartPacket(SSH1_MSG_CHANNEL_OPEN_FAILURE);
OutPacket.AddInteger(i);
OutPacket.Write;
end;
SSH1_SMSG_EXIT_STATUS:
begin
OutPacket.StartPacket(SSH1_CMSG_EXIT_CONFIRMATION);
OutPacket.Write;
DisConnect('end');
Closed := True;
end;
SSH1_SMSG_SUCCESS,
SSH1_SMSG_FAILURE:
begin
end; // do nothing
else
begin
// we should not see these messages
raise ESSHError.Create('unimplemented message');
end;
end;
Result := True;
end;
end;
end;
procedure TSSH1Session.OnPacket(Packet: TSSHPacketReceiver);
begin
if not KeyEx.OnPacket(TSSH1PacketReceiver(Packet)) then
if not Auth.OnPacket(Packet) then
InitServices(TSSH1PacketReceiver(Packet));
end;
{ TSSHSession }
constructor TSSHSession.Create(Owner: TObject);
begin
InBuffer := TSSHBuffer.Create(1000);
OutBuffer := TSSHBuffer.Create(1000);
Closed := False;
end;
destructor TSSHSession.Destroy;
begin
if Assigned(InBuffer) then InBuffer.Free;
if Assigned(OutBuffer) then OutBuffer.Free;
inherited;
end;
procedure TSSHSession.Disconnect(reasonstr: string);
begin
end;
procedure TSSHSession.OnDisConnectHandler(reason: integer);
begin
Closed := True;
end;
procedure TSSHSession.OnPacket(Packet: TSSHPacketReceiver);
begin
// pure virtual;
end;
{procedure TSSHSession.OnPassPrompt(var pass:string;var canceled:boolean);
begin
pass:= sshpass;
end;
procedure TSSHSession.OnUserPrompt(var user:string;var canceled:boolean);
begin
user := sshuser;
end;
}
procedure TSSHSession.ChangeWindowSize(col, row: integer);
begin
// pure virtual;
end;
end.
|
unit MouseRNGDialog_U;
// Description: MouseRNG Dialog
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
type
// This exception if an attempt is made to set "RequiredBits" to a value
// which *isn't* a multiple of 8
ERequiredNot8Multiple = Exception;
EInternalError = Exception;
TMouseRNGDialog = class(TObject)
private
{ Private declarations }
protected
FRequiredBits: integer;
FData: array of byte;
procedure SetRequiredBits(bits: integer);
public
function Execute(): boolean;
// published
constructor Create();
destructor Destroy(); override;
// This value must be set to a multiple of 8
// An exception will be raised if an attempt is made to set this to a
// value which *isn't* a multiple of 8
property RequiredBits: integer read FRequiredBits write SetRequiredBits default 512;
// Copy up to "count" bits into the buffer, return the number of bits copied
// Note: "buffer" is indexed from 0
// count - Set to the number of *bits* to copy into "data"
// data - Zero indexed array into which the random data should be copied
// Returns: The number of bits copied into "data"
function RandomData(countBits: integer; var data: array of byte): integer;
// Securely cleardown any random data collected
procedure Wipe();
end;
//procedure Register;
implementation
uses
MouseRNGCaptureDlg_U,
Math; // Required for "min(...)"
//procedure Register;
//begin
// RegisterComponents('SDeanSecurity', [TMouseRNGDialog]);
//end;
constructor TMouseRNGDialog.Create();
begin
inherited;
end;
destructor TMouseRNGDialog.Destroy();
begin
Wipe();
inherited;
end;
function TMouseRNGDialog.Execute(): boolean;
var
captureDlg: TMouseRNGCaptureDlg;
bitsGot: integer;
begin
Result := FALSE;
// Cleardown any previous data...
Wipe();
captureDlg:= TMouseRNGCaptureDlg.create(nil);
try
captureDlg.RequiredBits := FRequiredBits;
if captureDlg.Showmodal()=mrOK then
begin
SetLength(FData, (FRequiredBits div 8));
bitsGot := captureDlg.RandomData(FRequiredBits, FData);
if (bitsGot <> FRequiredBits) then begin
// Cleardown and raise error...
Wipe();
raise EInternalError.Create('Could not retieve all random data');
end else begin
Result := TRUE;
end;
end;
finally
captureDlg.Wipe();
captureDlg.Free();
end;
end;
procedure TMouseRNGDialog.Wipe();
var
i: integer;
begin
randomize;
for i:=low(FData) to high(FData) do
begin
FData[i] := random(255);
FData[i] := 0;
end;
SetLength(FData, 0);
end;
function TMouseRNGDialog.RandomData(countBits: integer; var data: array of byte): integer;
var
copyCountBytes: integer;
i: integer;
begin
copyCountBytes := min((countBits div 8), Length(FData));
for i:=0 to (copyCountBytes-1) do
begin
data[i] := FData[i];
end;
Result := (copyCountBytes * 8);
end;
procedure TMouseRNGDialog.SetRequiredBits(bits: integer);
begin
if ((bits mod 8) <> 0) then
raise ERequiredNot8Multiple.Create('Required bits must be a multiple of 8');
FRequiredBits := bits
end;
END.
|
unit StaticConfig;
interface
const
INITIAL_HP: array[0..9] of integer = (0, 10, 20, 30, 40, 50, 60, 70, 80, 100);
INITIAL_HP_SPEED = 100;
MIN_HP_SPEED = 5.0;
CH: array [0..10] of char = (' ','.',',',':','&','%','#','$','@','O','G');
FIELD_WIDTH = 0.2;
FIELD_HEIGHT = 0.39;
{ How much should the wind acceleration change per second }
WIND_FLUCT = 0.3;
{ More or less, every how many seconds should the wind change from
increasing to decreasing or vice versa }
WIND_CHANGE_TIME = 2;
SIGHT_LEN = 2;
MAX_W = 5000;
MAX_H = 5000;
implementation
begin
end.
|
unit uPerson;
interface
type
{ TPerson }
TPerson = class
private
fFirstName: string;
fSurname: string;
published
property FirstName: string read fFirstName write fFirstName;
property Surname: string read fSurname write fSurname;
end;
implementation
{ TPerson }
end.
|
unit fGrid;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
StdCtrls, Grids,
iStart, rtti_broker_iBroker, rtti_idebinder_Lib, rtti_idebinder_iBindings;
type
{ TGridForm }
TGridForm = class(TForm{, IStartContextConnectable})
btnAdd: TButton;
btnDelete: TButton;
btnEdit: TButton;
grdGrid: TDrawGrid;
pnRunEdit: TPanel;
procedure btnAddClick(Sender: TObject);
procedure btnEditClick(Sender: TObject);
private
//fContext: IStartContext;
fEditForm: TFormClass;
fObjectClass: string;
fDirty: Boolean;
fBinder: IRBTallyBinder;
fFactory: IRBFactory;
fStore: IRBStore;
protected
//procedure Connect(const AContext: IStartContext);
procedure Actualize;
public
constructor Create(TheOwner: TComponent; const AObjectClass: string;
AEditForm: TFormClass);
property Factory: IRBFactory read fFactory write fFactory;
property Store: IRBStore read fStore write fStore;
end;
implementation
{$R *.lfm}
{ TGridForm }
procedure TGridForm.btnAddClick(Sender: TObject);
var
mData: IRBData;
begin
mData := Factory.CreateObject(fObjectClass) as IRBData;
if TIDE.Edit(fEditFOrm, mData, Store as IRBDataQuery) then
begin
Store.Save(mData);
Store.Flush;
fDirty := True;
Actualize;
end;
end;
procedure TGridForm.btnEditClick(Sender: TObject);
var
mData, mNewData: IRBData;
begin
mData := fBinder.CurrentData;
if mData = nil then
Exit;
mNewData := Factory.CreateObject(mData.ClassName) as IRBData;
mNewData.Assign(mData);
if TIDE.Edit(fEditFOrm, mNewData, Store as IRBDataQuery) then
begin
mData.Assign(mNewData);
Store.Save(mData);
Store.Flush;
fDirty := True;
Actualize;
end;
end;
//procedure TGridForm.Connect(const AContext: IStartContext);
//var
// mClass: TClass;
//begin
// fContext := AContext;
// mClass := fContext.SerialFactory.FindClass(fObjectClass);
// //lbList.Items.Add(fListField);
// fBinder := TLib.NewListBinder(grdGrid, fContext.BinderContext, mClass);
//end;
procedure TGridForm.Actualize;
begin
fBinder.Reload;
end;
constructor TGridForm.Create(TheOwner: TComponent; const AObjectClass: string;
AEditForm: TFormClass);
begin
inherited Create(TheOwner);
fObjectClass := AObjectClass;
fEditForm := AEditForm;
end;
end.
|
unit MO14MainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Ibase, FIBDatabase, pFIBDatabase, cxStyles, cxCustomData,
cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData,
cxTextEdit, ComCtrls, ToolWin, ImgList, cxGridLevel,
cxGridCustomTableView, cxGridTableView, cxGridBandedTableView,
cxGridDBBandedTableView, cxClasses, cxControls, cxGridCustomView, cxGrid,
pFibDataSet, cxLookAndFeelPainters, cxContainer, cxRadioGroup, StdCtrls,
cxButtons, ExtCtrls, cxMaskEdit, cxButtonEdit, FIBDataSet, frxClass,
frxDBSet, frxExportHTML, frxExportPDF, frxExportRTF,
frxExportXML, frxExportXLS, cxDropDownEdit, AppStruClasses, cxCheckBox;
type
TTMo14MainForm = class(TForm)
WorkDatabase: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
WriteTransaction: TpFIBTransaction;
Panel1: TPanel;
Panel2: TPanel;
cxButton1: TcxButton;
cxButton2: TcxButton;
frxDBDataset1: TfrxDBDataset;
ResultsDataSet: TpFIBDataSet;
frxXLSExport1: TfrxXLSExport;
frxXMLExport1: TfrxXMLExport;
frxRTFExport1: TfrxRTFExport;
frxPDFExport1: TfrxPDFExport;
frxHTMLExport1: TfrxHTMLExport;
Panel4: TPanel;
cbMonthBeg: TcxComboBox;
cbYearBeg: TcxComboBox;
Label3: TLabel;
cxButtonEdit1: TcxButtonEdit;
Label1: TLabel;
Label2: TLabel;
cxButtonEdit2: TcxButtonEdit;
Label4: TLabel;
cxButtonEdit3: TcxButtonEdit;
cxCheckBox1: TcxCheckBox;
frxReport1: TfrxReport;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cxButton1Click(Sender: TObject);
procedure cxButton2Click(Sender: TObject);
procedure cxButtonEdit1PropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure cxCheckBox1PropertiesChange(Sender: TObject);
private
{ Private declarations }
ActualDate:TDateTime;
public
{ Public declarations }
id_sch:Int64;
id_pkv:int64;
id_type_finance:int64;
constructor Create(AOwner:TComponent;DbHandle:TISC_DB_HANDLE;id_User:Int64);reintroduce;
end;
implementation
uses GlobalSpr, BaseTypes, Resources_unitb, DateUtils;
{$R *.dfm}
{ TTMoMainForm }
constructor TTMo14MainForm.Create(AOwner: TComponent;
DbHandle: TISC_DB_HANDLE; id_User: Int64);
var I:Integer;
begin
inherited Create(AOwner);
WorkDatabase.Handle:=DbHandle;
ReadTransaction.StartTransaction;
self.ActualDate:=Date;
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_01));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_02));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_03));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_04));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_05));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_06));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_07));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_08));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_09));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_10));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_11));
cbMonthBeg.Properties.Items.Add(TRIM(BU_Month_12));
for i:=2000 to YearOf(ActualDate) do
begin
cbYearBeg.Properties.Items.Add(TRIM(IntToStr(i)));
end;
cbMonthBeg.ItemIndex:=MonthOf(ActualDate)-1;
for i:=0 to cbYearBeg.Properties.Items.Count-1 do
begin
if pos(cbYearBeg.Properties.Items[i],IntToStr(YearOf(ActualDate)))>0
then begin
cbYearBeg.ItemIndex:=i;
break;
end;
end;
end;
procedure TTMo14MainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action:=caFree;
end;
procedure TTMo14MainForm.cxButton1Click(Sender: TObject);
begin
ActualDate:=StrToDate('01.'+IntToStr(cbMonthBeg.ItemIndex+1)+'.'+cbYearBeg.Properties.Items[cbYearBeg.ItemIndex]);
if ResultsDataSet.Active then ResultsDataSet.Close;
if not cxCheckBox1.Checked
then begin
ResultsDataSet.SelectSQL.Text:='SELECT * from MBOOK_MO14_GET_DATA('+''''+DateToStr(ActualDate)+''''+',0,'+IntToStr(id_sch)+','+IntToStr(id_pkv)+','+IntToStr(id_type_finance)+')';
end
else begin
ResultsDataSet.SelectSQL.Text:='SELECT * from MBOOK_MO14_GET_DATA('+''''+DateToStr(ActualDate)+''''+',1,'+IntToStr(id_sch)+','+IntToStr(id_pkv)+','+IntToStr(id_type_finance)+')';
end;
ResultsDataSet.Open;
frxReport1.LoadFromFile(ExtractFilePath(Application.ExeName)+'\Reports\Mbook\ReportMO14.fr3',true);
frxReport1.Variables['DATA'] :=ActualDate;
frxReport1.Variables['SCH_DATA'] :=''''+cxButtonEdit1.Text+'''';
frxReport1.Variables['PKV_DATA'] :=''''+cxButtonEdit2.Text+'''';
frxReport1.Variables['TYPEF_DATA']:=''''+cxButtonEdit3.Text+'''';
frxReport1.PrepareReport(true);
frxReport1.ShowPreparedReport;
end;
procedure TTMo14MainForm.cxButton2Click(Sender: TObject);
begin
Close;
end;
procedure TTMo14MainForm.cxButtonEdit1PropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var PC: TFMASAppModule;
FS:Integer;
Root:Integer;
tmp:Integer;
begin
with TFMASAppModuleCreator.Create do
begin
PC :=CreateFMASModule(ExtractFilePath(Application.ExeName)+'Kernell\','SchPackage');
if (PC<>nil)
then begin
FS :=1;
Root:=-7;
tmp :=0;
PC.InParams.items['Book_date']:=PDateTime(@ActualDate);
PC.InParams.items['FS'] :=PInteger(@FS);
PC.InParams.Items['DBhandle'] :=PInteger(@WorkDatabase.Handle);
PC.InParams.items['AOwner'] :=@self;
PC.InParams.items['Root'] :=PInteger(@Root);
PC.InParams.items['ID_FU'] :=PInteger(@tmp);
PC.InParams.items['id_sch'] :=PInteger(@id_sch);
(PC as IFMASModule).Run;
if (PC.OutParams.Items['Result'])<>nil
then begin
id_sch :=VarAsType((PVariant(PC.OutParams.Items['Result'])^)[0][0], varInt64);
cxButtonEdit1.Text :=VarToStr((PVariant(PC.OutParams.Items['Result'])^)[0][3])+' "'+
VarToStr((PVariant(PC.OutParams.Items['Result'])^)[0][1]);
end;
end
else agMessageDlg('Увага!','Помилка при работі з бібліотекою SchPackage.bpl',mtError,[mbOk]);
end;
end;
procedure TTMo14MainForm.cxCheckBox1PropertiesChange(Sender: TObject);
begin
label2.Enabled:=cxCheckBox1.Checked;
label4.Enabled:=cxCheckBox1.Checked;
cxButtonEdit2.Enabled:=cxCheckBox1.Checked;
cxButtonEdit3.Enabled:=cxCheckBox1.Checked;
end;
end.
|
{*****************************************************************************
The DEC team (see file NOTICE.txt) licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. A copy of this licence is found in the root directory of
this project in the file LICENCE.txt or alternatively at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*****************************************************************************}
/// <summary>
/// Simple demonstration of using the IDECProgress interface for displaying
/// progress of an operation
/// </summary>
unit MainForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, DECUtil;
type
TFormMain = class(TForm, IDECProgress)
Button1: TButton;
Edit1: TEdit;
ProgressBar1: TProgressBar;
procedure Button1Click(Sender: TObject);
public
procedure OnProgress(const Min, Max, Pos: Int64); stdcall;
end;
var
FormMain: TFormMain;
implementation
uses
System.UITypes, DECCiphers, DECCipherBase;
{$R *.dfm}
resourcestring
rFileNameEmptyFailure = 'No input file specified!';
procedure TFormMain.Button1Click(Sender: TObject);
var
Cipher : TCipher_AES;
TargetFile : string;
begin
if Edit1.Text = '' then
begin
MessageDlg(rFileNameEmptyFailure, mtError, [mbOK], -1);
exit;
end;
Cipher := TCipher_AES.Create;
try
try
// Init encryption
Cipher.Init('Passwort', #1#2#3#4#5#6#7#99, 0);
Cipher.Mode := cmCBCx;
// replace file extension of input file
TargetFile := Edit1.Text;
Delete(TargetFile, pos('.', TargetFile), length(TargetFile));
TargetFile := TargetFile + '.enc';
Cipher.EncodeFile(Edit1.Text, TargetFile, self);
except
on E: Exception do
MessageDlg(E.Message, mtError, [mbOK], -1);
end;
finally
Cipher.Free;
end;
end;
procedure TFormMain.OnProgress(const Min, Max, Pos: Int64);
begin
ProgressBar1.Min := Min;
ProgressBar1.Max := Max;
ProgressBar1.Position := Pos;
end;
end.
|
unit C64Thread;
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$H+}
interface
uses
Classes, SyncObjs, C64Types;
type
{ TC64SystemThread }
TC64SystemThread = class(TThread)
protected
// FLock: TCriticalSection;
FRunSignal: TSimpleEvent;
FPausedSignal: TSimpleEvent;
FWasPaused: Boolean;
FCycPSec: Cardinal;
FIntrval: Double;
FCycPUpd: TC64Float;
FCycResidual: TC64Float;
FRefreshCnt: Integer;
FRefreshUpd: Integer;
FCycRefresh: Cardinal;
FThsDiff,
FLstIntrv,
FThsIntrv,
FThsComp,
FLstCompI: Double;
FCmpOffs,
FCmpTick: cycle_count;
FLstTick,
FThsTick: cycle_count;
FDelayCount: Cardinal;
FName: string;
FFreeRun: Boolean;
procedure DoConstruction; virtual; abstract;
procedure DoDestruction; virtual; abstract;
procedure DoClock(const ATicks: Cardinal); virtual; abstract;
procedure DoPause; virtual; abstract;
procedure DoPlay; virtual; abstract;
procedure UpdateFrontEnd(const ATicks: Cardinal; const ACount: Integer); virtual;
procedure Execute; override;
public
constructor Create(const ASystemType: TC64SystemType;
const AUpdateRate: TC64UpdateRate);
destructor Destroy; override;
property RunSignal: TSimpleEvent read FRunSignal;
property PausedSignal: TSimpleEvent read FPausedSignal;
// procedure Lock;
// procedure Unlock;
procedure SetDelayCount(const ACycles: Cardinal);
end;
implementation
uses
SysUtils;
const
ARR_VAL_CNT_UPDRATE: array[TC64UpdateRate] of Integer =
(16, 8, 4, 2, 1);
{ TC64SystemThread }
procedure TC64SystemThread.UpdateFrontEnd(const ATicks: Cardinal;
const ACount: Integer);
begin
end;
procedure TC64SystemThread.Execute;
var
doCyclesF: TC64Float;
doCyclesI: cycle_count;
// delyCount: Integer;
// actCyclesF: TC64Float;
// actCycles: cycle_count;
delyFact: Integer;
begin
// FLock:= TCriticalSection.Create;
FRunSignal:= TSimpleEvent.Create;
FRunSignal.SetEvent;
FPausedSignal:= TSimpleEvent.Create;
FPausedSignal.ResetEvent;
// doTicks:= 0;
FThsTick:= 0;
FLstTick:= 0;
FCmpOffs:= 0;
FCmpTick:= 0;
FCycResidual:= 0;
FRefreshCnt:= 0;
// It seems that we have to call this here. See the constructor.
DoConstruction;
FLstIntrv:= C64TimerGetTime;
FLstCompI:= FLstIntrv;
while not Terminated do
begin
FThsIntrv:= C64TimerGetTime;
FThsDiff:= FThsIntrv - FLstIntrv;
if FThsDiff < 0 then
begin
// UpdateFrontEnd;
Continue;
end;
doCyclesF:= FCycPUpd + FCycResidual;
doCyclesI:= Trunc(doCyclesF);
FCycResidual:= doCyclesF - doCyclesI;
if FRunSignal.WaitFor(0) = wrSignaled then
begin
if FWasPaused then
begin
FWasPaused:= False;
DoPlay;
end;
delyFact:= FDelayCount;
// actCyclesF:= doCyclesI;
//
// if actCyclesF < 1 then
// begin
// Inc(delyCount);
// actCycles:= 0;
// end
// else
// begin
// actCycles:= Trunc(actCyclesF) + delyCount;
// delyCount:= 0;
// end;
//
// if actCycles > 0 then
DoClock(doCyclesI);
if delyFact > 1 then
Sleep(Trunc(doCyclesI * delyFact * FIntrval * 1000));
Inc(FRefreshCnt, FRefreshUpd);
if FRefreshCnt > 15 then
begin
FThsIntrv:= C64TimerGetTime;
FThsDiff:= FThsIntrv - FLstIntrv;
// FThsTick:= Round(FThsDiff / FIntrval);
// Dec(FThsTick, FCycRefresh);
//dengland I am having trouble getting this to work. I think this calculation
// of free time is correct but it may be colliding with wait for buffer
// sleeping in the audio?? I think I may have to run the audio buffer
// handling in a different thread to the SID? I wonder if it would pay
// off then. Perhaps I could collect metrics about delays spent and
// factor those in???
//
// -- Update: Halving the expected value seems to work well? Nah...
FThsTick:= Trunc((FCycRefresh * FIntrval - FThsDiff) * 500);
FRefreshCnt:= 0;
// UpdateFrontEnd;
if FThsTick <= 0 then
begin
FLstIntrv:= FThsIntrv;
Continue;
end
else
begin
// if not FFreeRun then
//dengland Can't do this at the moment
// Sleep(FThsTick);
//dengland High accuracy alternative
// C64Wait(Abs(FThsTick) * FIntrval);
FLstIntrv:= C64TimerGetTime;
end;
end;
end
else if not (FPausedSignal.WaitFor(0) = wrSignaled) then
begin
FWasPaused:= True;
FPausedSignal.SetEvent;
DoPause;
end
else
begin
FRunSignal.WaitFor(100);
FLstIntrv:= C64TimerGetTime;
FRefreshCnt:= 0;
end;
end;
DoDestruction;
FPausedSignal.Free;
FRunSignal.Free;
// FLock.Free;
end;
procedure TC64SystemThread.SetDelayCount(const ACycles: Cardinal);
begin
FDelayCount:= ACycles;
end;
constructor TC64SystemThread.Create(const ASystemType: TC64SystemType;
const AUpdateRate: TC64UpdateRate);
begin
// We can't call DoConstruction here because the memory doesn't seem to get
// allocated in a way in which we can use it if we do... Annoying.
FRefreshUpd:= ARR_VAL_CNT_UPDRATE[AUpdateRate];
FCycRefresh:= Trunc(ARR_VAL_SYSCYCPRFS[ASystemType]);
FCycPUpd:= FCycRefresh / (1 shl Ord(AUpdateRate));
FCycPSec:= ARR_VAL_SYSCYCPSEC[ASystemType];
FIntrval:= (1 / FCycPSec);
FDelayCount:= 1;
inherited Create(False);
end;
destructor TC64SystemThread.Destroy;
begin
// Don't call DoDestruction here because we aren't calling DoConstruction in
// the constructor.
inherited Destroy;
end;
//procedure TC64SystemThread.Lock;
// begin
// FLock.Acquire;
// end;
//procedure TC64SystemThread.Unlock;
// begin
// FLock.Release;
// end;
end.
|
//////////////////////////////////////////////////////////////////////////
// This file is a part of NotLimited.Framework.Wpf NuGet package.
// You are strongly discouraged from fiddling with it.
// If you do, all hell will break loose and living will envy the dead.
//////////////////////////////////////////////////////////////////////////
using System;
using System.Windows;
using System.Windows.Media;
namespace NotLimited.Framework.Wpf
{
public class TextRenderer
{
private Typeface _typeface;
private GlyphTypeface _glyphFace;
private double _fontSize;
private double _fontHeight;
public TextRenderer()
: this(new Typeface(new FontFamily("Arial"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal))
{
}
public TextRenderer(Typeface typeface)
{
_typeface = typeface;
_fontSize = 12;
CreateGlyphFace();
}
public Typeface Typeface
{
get { return _typeface; }
set { _typeface = value; CreateGlyphFace(); }
}
public double FontSize
{
get { return _fontSize; }
set { _fontSize = value; RecalculateFontHeight(); }
}
public double FontHeight { get { return _fontHeight; } }
private void CreateGlyphFace()
{
if (!_typeface.TryGetGlyphTypeface(out _glyphFace))
throw new InvalidOperationException("Can't get the plygh typeface!");
RecalculateFontHeight();
}
private void RecalculateFontHeight()
{
_fontHeight = _glyphFace.Height * FontSize;
}
public Size MeasureText(string text)
{
double width = 0;
ushort idx;
for (int i = 0; i < text.Length; i++)
{
idx = _glyphFace.CharacterToGlyphMap[text[i]];
width += _glyphFace.AdvanceWidths[idx] * _fontSize;
}
return new Size(width, _fontHeight);
}
public void DrawText(DrawingContext dc, string text, Point origin)
{
var indexes = new ushort[text.Length];
var widths = new double[text.Length];
for (int i = 0; i < text.Length; i++)
{
indexes[i] = _glyphFace.CharacterToGlyphMap[text[i]];
widths[i] = _glyphFace.AdvanceWidths[indexes[i]] * _fontSize;
}
var run = new GlyphRun(_glyphFace, 0, false, _fontSize, indexes, origin, widths, null, null, null, null, null, null);
dc.DrawGlyphRun(Brushes.Black, run);
}
}
} |
// 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 uEditorPlugins;
interface
{$I ConTEXT.inc}
uses
Windows,
Messages,
SysUtils,
Classes,
Graphics,
Dialogs,
ConTEXTSynEdit,
SynEdit,
uCommon,
SynEditMiscProcs,
JclGraphUtils,
SynEditHighlighter,
SynEditTypes,
SynEditTextBuffer,
JclStrings,
SynEditMiscClasses,
uCommonClass;
type
TEmphasizeWordStyle = (ewNone, ewLine, ewDoubleLine, ewWave);
TEmphasizeWordPlugin = class(TSynEditPlugin)
private
fWord: string;
fWordLen: integer;
fColor: TColor;
fStyle: TEmphasizeWordStyle;
fCaseSensitive: boolean;
procedure SetWord(const Value: string);
protected
procedure AfterPaint(ACanvas: TCanvas; const AClip: TRect; FirstLine, LastLine: integer); override;
procedure LinesInserted(FirstLine, Count: integer); override;
procedure LinesDeleted(FirstLine, Count: integer); override;
public
constructor Create(AOwner: TCustomSynEdit);
property Word: string read fWord write SetWord;
property Style: TEmphasizeWordStyle read fStyle write fStyle;
property Color: TColor read fColor write fColor;
property CaseSensitive: boolean read fCaseSensitive write fCaseSensitive;
end;
implementation
////////////////////////////////////////////////////////////////////////////////////////////
// TEmphasizeWordPlugin
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
constructor TEmphasizeWordPlugin.Create(AOwner: TCustomSynEdit);
begin
inherited;
fColor := clRed;
fStyle := ewWave;
// fStyle:=ewLine;
// fStyle:=ewDoubleLine;
end;
//------------------------------------------------------------------------------------------
procedure TEmphasizeWordPlugin.AfterPaint(ACanvas: TCanvas; const AClip: TRect;
FirstLine, LastLine: integer);
var
i: integer;
n: integer;
search_index: integer;
s: string;
canvas_properties_set: boolean;
drawP: TPoint;
drawW: integer;
oldPenStyle: TPenStyle;
found_pos: integer;
begin
if (fStyle <> ewNone) then
begin
oldPenStyle := ACanvas.Pen.Style;
drawW := Editor.CharWidth * fWordLen;
canvas_properties_set := FALSE;
for i := FirstLine to LastLine do
begin
n := Editor.RowToLine(i);
s := Editor.Lines[n - 1];
if (Length(s) > 0) then
begin
search_index := 1;
repeat
if fCaseSensitive then
found_pos := StrNPos(s, fWord, search_index)
else
found_pos := StrNIPos(s, fWord, search_index);
if (found_pos > 0) then
begin
drawP := Editor.RowColumnToPixels(Editor.BufferToDisplayPos(BufferCoord(found_pos, n)));
inc(drawP.Y, Editor.LineHeight - 1);
with ACanvas do
begin
if not canvas_properties_set then
begin
Pen.Color := fColor;
oldPenStyle := Pen.Style;
Brush.Style := bsClear;
if (fStyle = ewWave) then
Pen.Style := psDot
else
Pen.Style := psSolid;
canvas_properties_set := TRUE;
end;
case fStyle of
ewLine:
begin
MoveTo(drawP.X, drawP.Y);
LineTo(drawP.X + drawW, drawP.Y);
end;
ewDoubleLine:
begin
MoveTo(drawP.X, drawP.Y);
LineTo(drawP.X + drawW, drawP.Y);
MoveTo(drawP.X, drawP.Y - 2);
LineTo(drawP.X + drawW, drawP.Y - 2);
end;
ewWave:
begin
MoveTo(drawP.X + 3, drawP.Y);
LineTo(drawP.X + drawW, drawP.Y);
MoveTo(drawP.X, drawP.Y - 1);
LineTo(drawP.X + drawW, drawP.Y - 1);
end;
end;
end;
inc(search_index);
end;
until (found_pos = 0);
end;
end;
if canvas_properties_set then
ACanvas.Pen.Style := oldPenStyle;
end;
end;
//------------------------------------------------------------------------------------------
procedure TEmphasizeWordPlugin.LinesDeleted(FirstLine, Count: integer);
begin
//
end;
//------------------------------------------------------------------------------------------
procedure TEmphasizeWordPlugin.LinesInserted(FirstLine, Count: integer);
begin
//
end;
//------------------------------------------------------------------------------------------
procedure TEmphasizeWordPlugin.SetWord(const Value: string);
begin
if (fWord <> Value) then
begin
fWord := Value;
fWordLen := Length(fWord);
end;
end;
//------------------------------------------------------------------------------------------
end.
|
unit UDMapCondField;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, UCrpe32;
type
TCrpeMapConditionFieldsDlg = class(TForm)
pnlMapConditionFields: TPanel;
lblNumber: TLabel;
lblCount: TLabel;
lbNumbers: TListBox;
editCount: TEdit;
btnOk: TButton;
lblFieldName: TLabel;
editFieldName: TEdit;
Edit1: TEdit;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure UpdateConditions;
procedure InitializeControls(OnOff: boolean);
procedure btnOkClick(Sender: TObject);
procedure lbNumbersClick(Sender: TObject);
procedure editFieldNameExit(Sender: TObject);
private
{ Private declarations }
public
Crs : TCrpeMapConditionFields;
CondIndex : integer;
end;
var
CrpeMapConditionFieldsDlg: TCrpeMapConditionFieldsDlg;
bMapConditions : boolean;
implementation
{$R *.DFM}
uses UCrpeUtl;
{------------------------------------------------------------------------------}
{ FormCreate }
{------------------------------------------------------------------------------}
procedure TCrpeMapConditionFieldsDlg.FormCreate(Sender: TObject);
begin
bMapConditions := True;
LoadFormPos(Self);
CondIndex := -1;
btnOk.Tag := 1;
end;
{------------------------------------------------------------------------------}
{ FormShow }
{------------------------------------------------------------------------------}
procedure TCrpeMapConditionFieldsDlg.FormShow(Sender: TObject);
begin
UpdateConditions;
end;
{------------------------------------------------------------------------------}
{ UpdateConditions }
{------------------------------------------------------------------------------}
procedure TCrpeMapConditionFieldsDlg.UpdateConditions;
var
i : smallint;
OnOff : boolean;
begin
CondIndex := -1;
{Enable/Disable controls}
if IsStrEmpty(Crs.Cr.ReportName) then
OnOff := False
else
begin
OnOff := (Crs.Count > 0);
{Get Index}
if OnOff then
begin
if Crs.ItemIndex > -1 then
CondIndex := Crs.ItemIndex
else
CondIndex := 0;
end;
end;
InitializeControls(OnOff);
{Update list box}
if OnOff = True then
begin
{Fill Numbers ListBox}
for i := 0 to Crs.Count - 1 do
lbNumbers.Items.Add(IntToStr(i));
editCount.Text := IntToStr(Crs.Count);
if CondIndex < 0 then CondIndex := 0;
lbNumbers.ItemIndex := CondIndex;
lbNumbersClick(self);
end;
end;
{------------------------------------------------------------------------------}
{ Initialize }
{------------------------------------------------------------------------------}
procedure TCrpeMapConditionFieldsDlg.InitializeControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
if TComponent(Components[i]).Tag = 0 then
begin
if Components[i] is TButton then
TButton(Components[i]).Enabled := OnOff;
if Components[i] is TListBox then
begin
TListBox(Components[i]).Color := ColorState(OnOff);
TListBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TEdit then
begin
if TEdit(Components[i]).ReadOnly = False then
TEdit(Components[i]).Color := ColorState(OnOff);
TEdit(Components[i]).Enabled := OnOff;
end;
end;
end;
end;
{------------------------------------------------------------------------------}
{ lbNumbersClick }
{------------------------------------------------------------------------------}
procedure TCrpeMapConditionFieldsDlg.lbNumbersClick(Sender: TObject);
begin
CondIndex := lbNumbers.ItemIndex;
editFieldName.Text := Crs[CondIndex].FieldName;
end;
{------------------------------------------------------------------------------}
{ editFieldNameExit }
{------------------------------------------------------------------------------}
procedure TCrpeMapConditionFieldsDlg.editFieldNameExit(Sender: TObject);
begin
if (Crs.Cr = nil) then Exit;
if Crs.ItemIndex < 0 then Exit;
if Crs.Item.FieldName <> editFieldName.Text then
Crs.Item.FieldName := editFieldName.Text;
end;
{------------------------------------------------------------------------------}
{ btnOkClick }
{------------------------------------------------------------------------------}
procedure TCrpeMapConditionFieldsDlg.btnOkClick(Sender: TObject);
begin
editFieldNameExit(Self);
SaveFormPos(Self);
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose }
{------------------------------------------------------------------------------}
procedure TCrpeMapConditionFieldsDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
bMapConditions := False;
Release;
end;
end.
|
unit messagesWindow;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls;
type
{ TmsgForm }
TmsgForm = class(TForm)
msgMemo: TMemo;
procedure FormCreate(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
procedure addText(t:AnsiString);
procedure clear();
end;
var
msgForm: TmsgForm;
implementation
{$R *.lfm}
procedure TmsgForm.FormCreate(Sender: TObject);
begin
msgForm.clear;
end;
procedure TmsgForm.addText(t:AnsiString);
begin
msgForm.msgMemo.Append('['+DateTimeToStr(Now)+'] '+t);
end;
procedure TmsgForm.clear();
begin
msgForm.msgMemo.Clear;
end;
end.
|
unit Objekt.SepaBSHeaderList;
interface
uses
SysUtils, Classes, Objekt.SepaBSHeader, contnrs;
type
TSepaBSHeaderList = class
private
fList: TObjectList;
fMsgId: string;
fNm: string;
fCreDtTM: string;
fCtrlSum: real;
fNbOfTxs: Integer;
function GetCount: Integer;
function getSepaBSHeader(Index: Integer): TSepaBSHeader;
function getMsgId: string;
function getNbOfTxs: Integer;
function getCtrlSum: real;
public
constructor Create;
destructor Destroy; override;
property Count: Integer read GetCount;
property Item[Index: Integer]: TSepaBSHeader read getSepaBSHeader;
function Add: TSepaBSHeader;
property MsgId: string read getMsgId write fMsgId;
property CreDtTm: string read fCreDtTM write fCreDtTM;
property CtrlSum: real read getCtrlSum;
property NbOfTxs: Integer read getNbOfTxs;
property Nm: string read fNm write fNm;
procedure Init;
function getBSHeader(aIBAN: string; aZahldatum: TDateTime): TSepaBSHeader;
end;
implementation
{ TSepaBSHeaderList }
constructor TSepaBSHeaderList.Create;
begin
fList := TObjectList.Create;
Init;
end;
destructor TSepaBSHeaderList.Destroy;
begin
FreeAndNil(fList);
inherited;
end;
function TSepaBSHeaderList.GetCount: Integer;
begin
Result := fList.Count;
end;
function TSepaBSHeaderList.getCtrlSum: real;
var
i1: Integer;
begin
Result := 0;
for i1 := 0 to fList.Count -1 do
begin
Result := Result + TSepaBSHeader(fList.Items[i1]).CtrlSum;
end;
end;
function TSepaBSHeaderList.getMsgId: string;
begin
if fMsgId = '' then
fMsgId := FormatDateTime('yyyy-mm-dd hh:mm:nn:zzz', now);
Result := fMsgId;
end;
function TSepaBSHeaderList.getNbOfTxs: Integer;
begin
fNbOfTxs := fList.Count;
Result := fNbOfTxs;
end;
function TSepaBSHeaderList.getSepaBSHeader(Index: Integer): TSepaBSHeader;
begin
Result := nil;
if Index > fList.Count -1 then
exit;
Result := TSepaBSHeader(fList[Index]);
end;
procedure TSepaBSHeaderList.Init;
begin
fMsgId := '';
fNm := '';
fCreDtTM := '';
fCtrlSum := 0;
end;
function TSepaBSHeaderList.Add: TSepaBSHeader;
begin
Result := TSepaBSHeader.Create;
fList.Add(Result);
end;
function TSepaBSHeaderList.getBSHeader(aIBAN: string; aZahldatum: TDateTime): TSepaBSHeader;
var
i1: Integer;
begin
for i1 := 0 to fList.Count -1 do
begin
if (TSepaBSHeader(fList.Items[i1]).IBAN = aIBAN) and (TSepaBSHeader(fList.Items[i1]).Zahldatum = aZahldatum) then
begin
Result := TSepaBSHeader(fList.Items[i1]);
exit;
end;
end;
Result := Add;
end;
end.
|
{
Memory Stream based on already mapped PE image in current process.
Basically it's TMemoryStream with Memory pointing to ImageBase and Size equal
to SizeOfImage.
}
unit PE.MemoryStream;
interface
uses
Classes,
SysUtils;
type
TPECustomMemoryStream = class(TStream)
protected
FMemory: Pointer;
FSize, FPosition: NativeInt;
public
constructor CreateFromPointer(Ptr: Pointer; Size: integer);
procedure SetPointer(Ptr: Pointer; const Size: NativeInt);
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: integer): integer; override;
procedure SaveToStream(Stream: TStream); virtual;
procedure SaveToFile(const FileName: string);
property Memory: Pointer read FMemory;
end;
TPEMemoryStream = class(TPECustomMemoryStream)
private
FModuleToUnload: HMODULE; // needed if module loading is forced.
FModuleFileName: string;
FModuleSize: uint32;
private
procedure CreateFromModulePtr(ModulePtr: Pointer);
public
// Create stream from module in current process.
// If module is not found exception raised.
// To force loading module set ForceLoadingModule to True.
constructor Create(const ModuleName: string; ForceLoadingModule: boolean = False); overload;
// Create from module by known base address.
constructor Create(ModuleBase: NativeUInt); overload;
destructor Destroy; override;
// Simply read SizeOfImage from memory.
class function GetModuleImageSize(ModulePtr: PByte): uint32; static;
end;
implementation
uses
Windows,
PE.Types.DosHeader,
PE.Types.NTHeaders;
{ TPECustomMemoryStream }
procedure TPECustomMemoryStream.SetPointer(Ptr: Pointer; const Size: NativeInt);
begin
FMemory := Ptr;
FSize := Size;
FPosition := 0;
end;
constructor TPECustomMemoryStream.CreateFromPointer(Ptr: Pointer; Size: integer);
begin
inherited Create;
SetPointer(Ptr, Size);
end;
procedure TPECustomMemoryStream.SaveToFile(const FileName: string);
var
Stream: TStream;
begin
Stream := TFileStream.Create(FileName, fmCreate);
try
SaveToStream(Stream);
finally
Stream.Free;
end;
end;
procedure TPECustomMemoryStream.SaveToStream(Stream: TStream);
begin
if FSize <> 0 then
Stream.WriteBuffer(FMemory^, FSize);
end;
function TPECustomMemoryStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
begin
case Origin of
soBeginning:
FPosition := Offset;
soCurrent:
Inc(FPosition, Offset);
soEnd:
FPosition := FSize + Offset;
end;
Result := FPosition;
end;
function TPECustomMemoryStream.Read(var Buffer; Count: integer): Longint;
begin
if Count = 0 then
Exit(0);
Result := FSize - FPosition;
if Result > 0 then
begin
if Result > Count then
Result := Count;
Move(PByte(FMemory)[FPosition], Buffer, Result);
Inc(FPosition, Result);
end;
end;
function TPECustomMemoryStream.Write(const Buffer; Count: integer): integer;
begin
if Count = 0 then
Exit(0);
Result := FSize - FPosition;
if Result > 0 then
begin
if Result > Count then
Result := Count;
Move(Buffer, PByte(FMemory)[FPosition], Result);
Inc(FPosition, Result);
end;
end;
{ TPEMemoryStream }
procedure TPEMemoryStream.CreateFromModulePtr(ModulePtr: Pointer);
begin
if ModulePtr = nil then
raise Exception.CreateFmt('Module "%s" not found in address space',
[FModuleFileName]);
FModuleSize := TPEMemoryStream.GetModuleImageSize(ModulePtr);
SetPointer(ModulePtr, FModuleSize);
end;
constructor TPEMemoryStream.Create(const ModuleName: string;
ForceLoadingModule: boolean);
var
FModulePtr: Pointer;
begin
inherited Create;
FModuleFileName := ModuleName;
FModulePtr := Pointer(GetModuleHandle(PChar(ModuleName)));
FModuleToUnload := 0;
if (FModulePtr = nil) and (ForceLoadingModule) then
begin
FModuleToUnload := LoadLibrary(PChar(ModuleName));
FModulePtr := Pointer(FModuleToUnload);
end;
CreateFromModulePtr(FModulePtr);
end;
constructor TPEMemoryStream.Create(ModuleBase: NativeUInt);
begin
inherited Create;
FModuleFileName := GetModuleName(ModuleBase);
FModuleToUnload := 0; // we didn't load it and won't free it
CreateFromModulePtr(Pointer(ModuleBase));
end;
destructor TPEMemoryStream.Destroy;
begin
if FModuleToUnload <> 0 then
FreeLibrary(FModuleToUnload);
inherited;
end;
class function TPEMemoryStream.GetModuleImageSize(ModulePtr: PByte): uint32;
var
dos: PImageDOSHeader;
nt: PImageNTHeaders;
begin
dos := PImageDOSHeader(ModulePtr);
if not dos.e_magic.IsMZ then
raise Exception.Create('Not PE image');
nt := PImageNTHeaders(ModulePtr + dos^.e_lfanew);
if not nt.Signature.IsPE00 then
raise Exception.Create('Not PE image');
Result := nt^.OptionalHeader.pe32.SizeOfImage;
end;
end.
|
{-----------------------------------------------------------------------------
Unit Name: cRefactoring
Author: Kiriakos Vlahos
Date: 03-Jul-2005
Purpose: Refactoring support
History:
-----------------------------------------------------------------------------}
unit cRefactoring;
interface
uses
SysUtils, Classes, Windows, Variants, cPythonSourceScanner, Contnrs;
type
{
Wrapper class for Bicycle RepainMan
}
TBRMRefactor = class
private
fBRMContext : Variant;
fBRMCache : Variant;
fInitialized : boolean;
fRefactoringIsAvailable : boolean;
procedure LoadOpenFilesToBRMCache;
procedure SetupBRM;
function GeTBRMRefactoringIsAvailable: boolean;
public
constructor Create;
destructor Destroy; override;
{ an ide friendly method which renames a class/fn/method
pointed to by the coords and filename }
function RenameByCoordinates(Filename : string; Line, Col: integer;
NewName : string) : boolean;
{ extracts the region into the named method/function based on context }
function Extract(Filename : string; BeginLine, BeginCol, EndLine,
EndCol : integer; Name : string) : boolean;
{ Inlines the variable pointed to by line:col.
(N.B. line:col can also point to a reference to the
variable as well as the definition) }
function InlineLocalVariable(Filename : string; Line, Col: integer) : boolean;
{ Extracts the region into a variable }
function ExtractLocalVariable(Filename : string; BeginLine, BeginCol, EndLine,
EndCol : integer; VvariableName: string) : boolean;
{ undoes the last refactoring. WARNING: this is dangerous if
the user has modified files since the last refactoring.
Raises UndoStackEmptyException }
function Undo : boolean;
{ given the coords of a function, class, method or variable
returns a generator which finds references to it. }
function FindReferencesByCoordinates(Filename : string; Line, Col: integer;
ShowMessages : boolean = True; Silent : boolean = False) : Variant;
{ given the coordates to a reference, tries to find the
definition of that reference - Returns an iterator over mathces}
function FindDefinitionByCoordinates(Filename : string; Line, Col: integer;
ShowMessages : boolean = True; Silent : boolean = False) : Variant;
{ moves the class pointed to by (filename_path, line) to a new module }
function MoveClassToNewModule(Filename : string; Line, Col: integer;
NewFilename : string) : boolean;
procedure ProcessBRMMatches(Matches: Variant; ShowMessages,
Silent: Boolean; var FirstMatch : Variant);
property Initialized : boolean read fInitialized;
property RefactoringIsAvailable : boolean read GeTBRMRefactoringIsAvailable;
end;
{
Our own limited refactoring implementation
}
ERefactoringException = class(Exception);
TModuleProxy = class(TParsedModule)
private
fPyModule : Variant;
fIsExpanded : boolean;
protected
function GetAllExportsVar: string; override;
function GetDocString: string; override;
function GetCodeHint : string; override;
public
constructor CreateFromModule(AModule : Variant);
procedure Expand;
procedure GetNameSpace(SList : TStringList); override;
property PyModule : Variant read fPyModule;
property IsExpanded : boolean read fIsExpanded;
end;
TClassProxy = class(TParsedClass)
private
fPyClass : Variant;
fIsExpanded : boolean;
protected
function GetDocString: string; override;
public
constructor CreateFromClass(AName : string; AClass : Variant);
function GetConstructor : TParsedFunction; override;
procedure Expand;
procedure GetNameSpace(SList : TStringList); override;
property PyClass : Variant read fPyClass;
property IsExpanded : boolean read fIsExpanded;
end;
TFunctionProxy = class(TParsedFunction)
private
fPyFunction : Variant;
fIsExpanded : boolean;
protected
function GetDocString: string; override;
public
constructor CreateFromFunction(AName : string; AFunction : Variant);
procedure Expand;
function ArgumentsString : string; override;
procedure GetNameSpace(SList : TStringList); override;
property PyFunction : Variant read fPyFunction;
property IsExpanded : boolean read fIsExpanded;
end;
TVariableProxy = class(TCodeElement)
private
fPyObject : Variant;
fIsExpanded : boolean;
protected
function GetDocString: string; override;
function GetCodeHint : string; override;
public
constructor CreateFromPyObject(const AName : string; AnObject : Variant);
procedure Expand;
procedure GetNameSpace(SList : TStringList); override;
property PyObject : Variant read fPyObject;
property IsExpanded : boolean read fIsExpanded;
end;
TPyScripterRefactor = class
private
fPythonScanner : TPythonScanner;
fProxyModules : TStringList;
fParsedModules : TStringList;
fImportResolverCache : TStringList;
fGetTypeCache : TStringList;
fSpecialPackages : TStringList;
// Begin For find references
fFindRefCE : TBaseCodeElement;
fFindRefFileList : TStringList;
fFindRefDirectoryList : TStringList;
fFindRefResults : TStringList;
procedure FindRefFileHandler(const FileName: string);
procedure FindRefFileHandlerEx(const Directory: string; const FileInfo: TSearchRec);
// End For find references
public
constructor Create;
destructor Destroy; override;
procedure ClearParsedModules;
procedure ClearProxyModules;
procedure InitializeQuery;
function GetSource(const FName : string; var Source : string): Boolean;
function GetParsedModule(const ModuleName : string; PythonPath : Variant) : TParsedModule;
{ given the coordates to a reference, tries to find the
definition of that reference - Returns TCodeElement, TVariable or nil}
function FindDefinitionByCoordinates(const Filename : string; Line, Col: integer;
var ErrMsg : string; Initialize : Boolean = True) : TBaseCodeElement;
{ given the coords of a function, class, method or variable
returns a list of references to it. }
procedure FindReferencesByCoordinates(Filename : string; Line, Col: integer;
var ErrMsg : string; List : TStringList);
function FindUnDottedDefinition(const Ident : string; ParsedModule : TParsedModule;
Scope : TCodeElement; var ErrMsg : string) : TBaseCodeElement;
function FindDottedIdentInScope(const DottedIdent : string; Scope : TCodeElement;
var ErrMsg: string) : TBaseCodeElement;
function FindDottedDefinition(const DottedIdent : string; ParsedModule : TParsedModule;
Scope : TCodeElement; var ErrMsg : string) : TBaseCodeElement;
function ResolveModuleImport(ModuleImport : TModuleImport): TParsedModule;
function ResolveImportedName(const Ident: string; ModuleImport: TModuleImport;
var ErrMsg: string): TBaseCodeElement;
function GetType(Variable : TVariable; var ErrMsg : string) : TCodeElement;
procedure FindReferences(CE : TBaseCodeElement; var ErrMsg : string;
List : TStringList);
procedure FindReferencesInModule(CE : TBaseCodeElement; Module : TParsedModule;
CodeBlock: TCodeBlock; var ErrMsg : string; List : TStringList);
procedure FindReferencesGlobally(CE : TBaseCodeElement; var ErrMsg : string;
List : TStringList);
end;
var
PyScripterRefactor : TPyScripterRefactor;
Const
FilePosInfoFormat = '%s (%d:%d)';
FilePosInfoRegExpr = '(.+) \((\d+):(\d+)\)$';
implementation
uses
frmPyIDEMain, frmPythonII, PythonEngine, VarPyth, dmCommands,
uEditAppIntfs, frmMessages, JvDockControlForm, Dialogs, JclStrings,
uCommonFunctions, SynEditTypes, JclFileUtils, Math, StringResources;
{ Refactor }
constructor TBRMRefactor.Create;
begin
inherited;
fInitialized := False;
fRefactoringIsAvailable := False
end;
destructor TBRMRefactor.Destroy;
begin
VarClear(fBRMContext);
VarClear(fBRMCache);
inherited;
end;
function TBRMRefactor.Extract(Filename: string; BeginLine, BeginCol, EndLine,
EndCol: integer; Name: string): boolean;
begin
Result := False;
end;
function TBRMRefactor.ExtractLocalVariable(Filename: string; BeginLine,
BeginCol, EndLine, EndCol: integer; VvariableName: string): boolean;
begin
Result := False;
end;
function TBRMRefactor.FindDefinitionByCoordinates(Filename: string; Line,
Col: integer; ShowMessages : boolean = True; Silent : boolean = False): Variant;
Var
SupressOutput : IInterface;
begin
VarClear(Result);
if not fRefactoringIsAvailable then Exit;
LoadOpenFilesToBRMCache;
try
if Silent then
SupressOutput := PythonIIForm.OutputSupressor;
// we use the brmctx to avoid resetting the file Cache
Result := fBRMContext.brmctx.findDefinitionByCoordinates(Filename, Line, Col);
except
// CheckError already called by VarPyth
on E: Exception do begin
if ShowMessages then begin
MessagesWindow.ShowPythonTraceback;
MessagesWindow.AddMessage(E.Message);
ShowDockForm(MessagesWindow);
end;
if not Silent then
raise;
end;
end;
end;
function TBRMRefactor.FindReferencesByCoordinates(Filename: string; Line,
Col: integer; ShowMessages : boolean = True; Silent : boolean = False): Variant;
Var
SupressOutput : IInterface;
begin
VarClear(Result);
if not fRefactoringIsAvailable then Exit;
LoadOpenFilesToBRMCache;
try
if Silent then
SupressOutput := PythonIIForm.OutputSupressor;
// wih use th brmctx to avoid resetting the file Cache
Result := fBRMContext.brmctx.findReferencesByCoordinates(Filename, Line, Col);
except
// CheckError already called by VarPyth
on E: Exception do begin
MessageBeep(MB_ICONASTERISK);
if ShowMessages then begin
MessagesWindow.ShowPythonTraceback;
MessagesWindow.AddMessage(E.Message);
ShowDockForm(MessagesWindow);
end;
if not Silent then
raise;
end;
end;
end;
function TBRMRefactor.GeTBRMRefactoringIsAvailable: boolean;
begin
if not fInitialized then
SetupBRM;
Result := fRefactoringIsAvailable;
end;
function TBRMRefactor.InlineLocalVariable(Filename: string; Line,
Col: integer): boolean;
begin
Result := False;
end;
procedure TBRMRefactor.LoadOpenFilesToBRMCache;
Var
i : integer;
FName,
Source : string;
begin
// inject unsaved code into LineCache
fBRMCache.instance.reset();
for i := 0 to GI_EditorFactory.Count - 1 do
with GI_EditorFactory.Editor[i] do
if HasPythonFile then begin
FName := GetFileNameOrTitle;
Source := CommandsDataModule.CleanEOLs(SynEdit.Text+#10);
PythonIIForm.II.loadFileToBRMCache(FName, Source);
end;
end;
function TBRMRefactor.MoveClassToNewModule(Filename: string; Line,
Col: integer; NewFilename: string): boolean;
begin
Result := False;
end;
procedure TBRMRefactor.ProcessBRMMatches(Matches: Variant; ShowMessages,
Silent: Boolean; var FirstMatch : Variant);
var
Match : Variant;
SupressOutput : IInterface;
begin
if Silent then
SupressOutput := PythonIIForm.OutputSupressor;
VarClear(FirstMatch);
if not VarIsPython(Matches) or VarIsNone(Matches) then Exit;
while True do
try
Match := Matches.next();
if ShowMessages then
MessagesWindow.AddMessage(Format(' Certainty %s%%', [match.confidence]),
Match.filename, Match.lineno, Match.colno + 1); //ColNo zero based!!
if VarIsEmpty(FirstMatch) then
FirstMatch := Match;
except
on EPyStopIteration do break;
on E: Exception do begin
MessageBeep(MB_ICONASTERISK);
if ShowMessages then begin
MessagesWindow.ShowPythonTraceback;
MessagesWindow.AddMessage(E.Message);
ShowDockForm(MessagesWindow);
end;
if Silent then
Exit
else
raise;
end;
end;
end;
function TBRMRefactor.RenameByCoordinates(Filename: string; Line, Col: integer;
NewName: string): boolean;
begin
Result := False;
end;
procedure TBRMRefactor.SetupBRM;
begin
PythonIIForm.II.setupRefactoring();
fBRMContext := PythonIIForm.II.BRMContext;
if VarIsNone(fBRMContext) then begin
fRefactoringIsAvailable := False;
MessageDlg('Refactoring services are not available. Please install Bicycle Repair Man from http://sourceforge.net/projects/bicyclerepair/ .',
mtError, [mbOK], 0);
end else begin
fRefactoringIsAvailable := True;
fBRMCache := PythonIIForm.II.BRMCache;
end;
fInitialized := True;
end;
function TBRMRefactor.Undo: boolean;
begin
Result := False;
end;
{ TPyScripterRefactor }
constructor TPyScripterRefactor.Create;
begin
inherited;
fPythonScanner := TPythonScanner.Create;
fParsedModules := TStringList.Create;
fParsedModules.CaseSensitive := True;
fParsedModules.Sorted := True;
fParsedModules.Duplicates := dupError;
fProxyModules := TStringList.Create;
fProxyModules.CaseSensitive := True;
fProxyModules.Sorted := True;
fProxyModules.Duplicates := dupError;
fImportResolverCache := TStringList.Create;
fImportResolverCache.CaseSensitive := True;
fGetTypeCache := TStringList.Create;
fGetTypeCache.CaseSensitive := True;
fSpecialPackages := TStringList.Create;
fSpecialPackages.CaseSensitive := true;
end;
function TPyScripterRefactor.FindDefinitionByCoordinates(const Filename: string; Line,
Col: integer; var ErrMsg : string; Initialize : Boolean = True): TBaseCodeElement;
var
DottedIdent, LineS : string;
ParsedModule : TParsedModule;
Scope : TCodeElement;
PythonPathAdder : IInterface;
begin
Result := nil;
if Initialize then begin
InitializeQuery;
// Add the file path to the Python path - Will be automatically removed
PythonPathAdder := AddPathToPythonPath(ExtractFilePath(FileName));
end;
// GetParsedModule
ParsedModule := GetParsedModule(FileNameToModuleName(FileName), None);
if not Assigned(ParsedModule) then begin
ErrMsg := Format('Could not load and parse module: "%s"', [FileName]);
Exit;
end;
// Extract the identifier
LineS := GetNthLine(ParsedModule.Source, Line);
DottedIdent := GetWordAtPos(LineS, Col, IdentChars+['.'], True, False);
DottedIdent := DottedIdent + GetWordAtPos(LineS, Col + 1, IdentChars, False, True);
if DottedIdent = '' then begin
ErrMsg := 'No Identifier at the given line and column';
Exit;
end;
// Find scope for line
Scope := ParsedModule.GetScopeForLine(Line);
if not assigned(Scope) then
ErrMsg := 'Could not find scope for the given line'
else
// Find identifier in the module and scope
Result := FindDottedDefinition(DottedIdent, ParsedModule, Scope, ErrMsg);
end;
destructor TPyScripterRefactor.Destroy;
begin
fPythonScanner.Free;
ClearParsedModules;
fParsedModules.Free;
ClearProxyModules;
fProxyModules.Free;
fImportResolverCache.Free;
fGetTypeCache.Free;
fSpecialPackages.Free;
inherited;
end;
function TPyScripterRefactor.GetParsedModule(const ModuleName: string;
PythonPath : Variant): TParsedModule;
var
Index, SpecialPackagesIndex : integer;
FName : Variant;
ModuleSource, DottedModuleName : string;
ParsedModule : TParsedModule;
Editor : IEditor;
FoundSource : boolean;
begin
DottedModuleName := ModuleName;
fSpecialPackages.CommaText := CommandsDataModule.PyIDEOptions.SpecialPackages;
SpecialPackagesIndex := fSpecialPackages.IndexOf(ModuleName);
if SpecialPackagesIndex >= 0 then
try
Import(ModuleName);
except
SpecialPackagesIndex := -1;
end;
FoundSource := False;
if SpecialPackagesIndex < 0 then begin
// Check whether it is an unsaved file
Editor := GI_EditorFactory.GetEditorByNameOrTitle(ModuleName);
if Assigned(Editor) and (Editor.FileName = '') and Editor.HasPythonFile then
begin
ModuleSource := Editor.SynEdit.Text;
FName := ModuleName;
FoundSource := True;
end else begin
// Find the source file
FName := PythonIIForm.II.findModuleOrPackage(ModuleName, PythonPath);
if not VarIsNone(FName) and (ExtractFileExt(FName) = '.py') and
GetSource(FName, ModuleSource)
then begin
FoundSource := True;
end;
end;
end;
if FoundSource then begin
DottedModuleName := FileNameToModuleName(FName);
Index := fParsedModules.IndexOf(DottedModuleName);
if Index < 0 then begin
ParsedModule := TParsedModule.Create;
ParsedModule.Name := DottedModuleName;
ParsedModule.FileName := FName;
fPythonScanner.ScanModule(ModuleSource, ParsedModule);
fParsedModules.AddObject(DottedModuleName, ParsedModule);
Result := ParsedModule;
end else
Result := fParsedModules.Objects[Index] as TParsedModule;
end else if SysModule.modules.has_key(DottedModuleName) then begin
// If the source file does not exist look at sys.modules to see whether it
// is available in the interpreter. If yes then create a proxy module
Index := fProxyModules.IndexOf(DottedModuleName);
if Index < 0 then begin
Index := fProxyModules.AddObject(DottedModuleName,
TModuleProxy.CreateFromModule(SysModule.modules.GetItem(DottedModuleName)));
Result := fProxyModules.Objects[Index] as TParsedModule;
end else
Result := fProxyModules.Objects[Index] as TParsedModule;
end else
Result := nil; // no source and not in sys.modules
end;
function TPyScripterRefactor.GetSource(const FName: string;
var Source: string): Boolean;
var
Editor : IEditor;
begin
Result := False;
Editor := GI_EditorFactory.GetEditorByNameOrTitle(FName);
if Assigned(Editor) then begin
Source := Editor.SynEdit.Text;
Result := True;
end;
if not Result then begin
if not FileExists(FName) then
Exit;
try
Source := FileToString(FName);
Result := True;
except
// We cannot open the file for some reason
Result := False;
end;
end;
end;
procedure TPyScripterRefactor.ClearParsedModules;
var
i : integer;
begin
for i := 0 to fParsedModules.Count - 1 do
fParsedModules.Objects[i].Free;
fParsedModules.Clear;
end;
procedure TPyScripterRefactor.ClearProxyModules;
var
i : integer;
begin
for i := 0 to fProxyModules.Count - 1 do
fProxyModules.Objects[i].Free;
fProxyModules.Clear;
end;
function TPyScripterRefactor.FindDottedDefinition(const DottedIdent: string;
ParsedModule : TParsedModule; Scope: TCodeElement; var ErrMsg: string): TBaseCodeElement;
{
Look for a dotted identifier in a given CodeElement (scope) of a ParsedModule
The function first finds the first part of the dotted definition and then
calls the recursive function FindDottedIdentInScope
}
Var
Prefix, Suffix : string;
Def : TBaseCodeElement;
begin
Result := nil;
Suffix := DottedIdent;
Prefix := StrToken(Suffix, '.');
Def := FindUnDottedDefinition(Prefix, ParsedModule, Scope, ErrMsg);
if Assigned(Def) then begin
if Suffix <> '' then begin
if Def.ClassType = TVariable then
Def := GetType(TVariable(Def), ErrMsg);
if Assigned(Def) then
Result := FindDottedIdentInScope(Suffix, Def as TCodeElement, ErrMsg);
end else
Result := Def;
end else
ErrMsg := Format('Could not find identifier "%s" in scope "%s"',
[DottedIdent, Scope.Name]);
end;
function TPyScripterRefactor.FindUnDottedDefinition(const Ident: string;
ParsedModule : TParsedModule; Scope: TCodeElement; var ErrMsg: string): TBaseCodeElement;
{
Look for an undotted (root) identifier in a given CodeElement (scope)
of a ParsedModule
First it checks the Scope and Parent scopes
Then it checks the builtin module
Finally it looks for implicitely imported modules and from * imports
}
Var
NameSpace : TStringList;
BuiltinModule : TParsedModule;
Index: integer;
CodeElement : TCodeElement;
begin
Result := nil;
if Ident = 'self' then begin
Result := Scope;
while not (Result is TParsedClass) and Assigned(TCodeElement(Result).Parent) do
Result := TCodeElement(Result).Parent;
if not (Result is TParsedClass) then begin
Result := nil;
ErrMsg := '"self" used outside a class scope';
end;
Exit;
end;
NameSpace := TStringList.Create;
NameSpace.CaseSensitive := True;
try
// First check the Scope and Parent scopes
CodeElement := Scope;
while Assigned(CodeElement) do begin
NameSpace.Clear;
CodeElement.GetNameSpace(NameSpace);
Index := NameSpace.IndexOf(Ident);
if Index >= 0 then begin
Result := NameSpace.Objects[Index] as TBaseCodeElement;
break;
end;
CodeElement := CodeElement.Parent as TCodeElement;
end;
// then check the builtin module
NameSpace.Clear;
if not Assigned(Result) then begin
BuiltInModule := GetParsedModule('__builtin__', None);
if not Assigned(BuiltInModule) then
raise ERefactoringException.Create(
'Internal Error in FindUnDottedDefinition: Could not get the Builtin module');
BuiltInModule.GetNameSpace(NameSpace);
Index := NameSpace.IndexOf(Ident);
if Index >= 0 then
Result := NameSpace.Objects[Index] as TBaseCodeelement;
NameSpace.Clear;
end;
finally
NameSpace.Free;
end;
if Assigned(Result) and (Result is TVariable)
and (TVariable(Result).Parent is TModuleImport)
then
// Resolve further
Result := ResolveImportedName(TVariable(Result).RealName,
TModuleImport(TVariable(Result).Parent), ErrMsg);
if Assigned(Result) and (Result is TModuleImport) then
Result := ResolveModuleImport(TModuleImport(Result));
if not Assigned(Result) then
ErrMsg := Format('Could not find identifier "%s" in module "%s"',
[Ident, ParsedModule.Name]);
end;
function TPyScripterRefactor.ResolveModuleImport(ModuleImport: TModuleImport) : TParsedModule;
var
ParentModule : TParsedModule;
RealName : string;
begin
RealName := ModuleImport.RealName;
Result := GetParsedModule(RealName, None);
if not Assigned(Result) then begin
// try a relative import
ParentModule := ModuleImport.GetModule;
if ParentModule.IsPackage then
Result := GetParsedModule(ParentModule.Name + '.' + RealName, None);
{ Should we check whether ParentModule belongs to a package?}
end;
end;
function TPyScripterRefactor.ResolveImportedName(const Ident: string;
ModuleImport: TModuleImport; var ErrMsg: string): TBaseCodeElement;
// May be called recursively
// fImportResolverCache is used to prevent infinite recursion
Var
S : string;
ImportedModule : TParsedModule;
NameSpace : TStringList;
Index : integer;
begin
Result := nil;
S := ModuleImport.Name + '.' + Ident;
if fImportResolverCache.IndexOf(S) >= 0 then
ErrMsg := 'Cyclic imports encountered!'
else begin
ImportedModule := ResolveModuleImport(ModuleImport);
if not Assigned(ImportedModule) then
ErrMsg := Format('Could not analyse module: "%s"', [ModuleImport.Name])
else begin
fImportResolverCache.Add(S);
NameSpace := TStringList.Create;
NameSpace.CaseSensitive := True;
try
ImportedModule.GetNameSpace(NameSpace);
Index := NameSpace.IndexOf(Ident);
if Index >= 0 then begin
Result := NameSpace.Objects[Index] as TBaseCodeElement;
if Assigned(Result) and (Result is TVariable)
and (TVariable(Result).Parent is TModuleImport)
then
// Resolve further
Result := ResolveImportedName(TVariable(Result).RealName,
TModuleImport(TVariable(Result).Parent), ErrMsg);
if Assigned(Result) and (Result is TModuleImport) then
Result := ResolveModuleImport(TModuleImport(Result));
end;
{ Check whether Ident is a sub-packages }
if not Assigned(Result) and ImportedModule.IsPackage then
Result := GetParsedModule(ImportedModule.Name + '.' + Ident, None);
if not Assigned(Result) then
ErrMsg := Format('Could not find identifier "%s" in module "%s"',
[Ident, ModuleImport.Name]);
finally
NameSpace.Free;
fImportResolverCache.Delete(fImportResolverCache.IndexOf(S));
end;
end;
end;
end;
function TPyScripterRefactor.GetType(Variable: TVariable;
var ErrMsg: string): TCodeElement;
// Returns the type of a TVariable as a TCodeElement
// One limitation is that it does not differentiate between Classes and their
// instances, which should be OK for our needs (FindDefinition and CodeCompletion)
Var
BaseCE, TypeCE : TBaseCodeElement;
AVar : TVariable;
Module : TParsedModule;
BuiltInModule : TParsedModule;
S : string;
begin
Result := nil;
// Resolve imported variables
if Variable.Parent is TModuleImport then begin
// ResolveImportedName returns either a CodeElement or Variable whose
// parent is not a ModuleImport
BaseCE := ResolveImportedName(Variable.RealName,
TModuleImport(Variable.Parent), ErrMsg);
if not Assigned(BaseCE) then
Exit
else if BaseCE is TCodeElement then begin
Result := TCodeElement(BaseCE);
Exit;
end else begin
// cannot be anything but TVariable !
Assert(BaseCE is TVariable, 'Internal Error in GetType');
AVar := TVariable(BaseCE);
end;
end else
AVar := Variable;
Module := AVar.GetModule;
S := Module.Name + '.' + AVar.Parent.Name + '.' + AVar.Name;
if fGetTypeCache.IndexOf(S) >= 0 then
ErrMsg := 'Cyclic imports encountered!'
else begin
fGetTypeCache.Add(S);
try
// check standard types
if vaBuiltIn in AVar.Attributes then begin
BuiltInModule := GetParsedModule('__builtin__', None);
(BuiltInModule as TModuleProxy).Expand;
Result := BuiltInModule.GetChildByName(AVar.ObjType)
end else if (AVar.ObjType <> '') and Assigned(AVar.Parent) and
(AVar.Parent is TCodeElement) then
begin
TypeCE := FindDottedDefinition(AVar.ObjType, Module,
TCodeElement(AVar.Parent), ErrMsg);
// Note: currently we are not able to detect the return type of functions
if (TypeCE is TParsedClass) or (TypeCE is TParsedModule) or
((TypeCE is TVariableProxy) and not (vaCall in AVar.Attributes)) or
((TypeCE is TParsedFunction) and not (vaCall in AVar.Attributes))
then
Result := TCodeElement(TypeCE)
else if TypeCE is TVariable then
Result := GetType(TVariable(TypeCE), ErrMsg);
end;
if not Assigned(Result) then
ErrMsg := Format('Type of "%s" is unknown', [AVar.Name]);
finally
fGetTypeCache.Delete(fGetTypeCache.IndexOf(S));
end;
end;
end;
function TPyScripterRefactor.FindDottedIdentInScope(const DottedIdent: string;
Scope: TCodeElement; var ErrMsg: string): TBaseCodeElement;
// Recursive routine
// Do not call directly - It is called from FindDottedDefinition
// and assumes that the first part (Suffix) of the DottedIdent is not
// a root code element
Var
Prefix, Suffix : string;
NameSpace : TStringList;
Def : TBaseCodeElement;
Index : integer;
begin
Result := nil;
Suffix := DottedIdent;
Prefix := StrToken(Suffix, '.');
Def := nil;
NameSpace := TStringList.Create;
NameSpace.CaseSensitive := True;
try
Scope.GetNameSpace(NameSpace);
Index := NameSpace.IndexOf(Prefix);
if Index >= 0 then begin
Def := NameSpace.Objects[Index] as TBaseCodeElement;
if Assigned(Def) and (Def is TVariable) and (Def.Parent is TModuleImport) then
Def := ResolveImportedName(TVariable(Def).RealName, TModuleImport(Def.Parent), ErrMsg);
if Assigned(Def) and (Def is TModuleImport) then
Def := ResolveModuleImport(TModuleImport(Def));
end else if (Scope is TParsedModule) and TParsedModule(Scope).IsPackage then
// check for submodules of packages
Def := GetParsedModule(TParsedModule(Scope).Name + '.' + Prefix, None);
finally
NameSpace.Free;
end;
if Assigned(Def) then begin
if Suffix <> '' then begin
if Def.ClassType = TVariable then
Def := GetType(TVariable(Def), ErrMsg);
if Assigned(Def) then
Result := FindDottedIdentInScope(Suffix, Def as TCodeElement, ErrMsg);
end else
Result := Def;
end else
ErrMsg := Format('Could not find identifier "%s" in scope "%s"',
[DottedIdent, Scope.Name]);
end;
procedure TPyScripterRefactor.InitializeQuery;
begin
ClearParsedModules; // in case source has changed
fImportResolverCache.Clear; // fresh start
fGetTypeCache.Clear; // fresh start
end;
procedure TPyScripterRefactor.FindReferencesByCoordinates(Filename: string;
Line, Col: integer; var ErrMsg: string; List: TStringList);
Var
DottedIdent, LineS : string;
ParsedModule : TParsedModule;
Scope : TCodeElement;
PythonPathAdder : IInterface;
Def : TBaseCodeElement;
begin
InitializeQuery;
// Add the file path to the Python path - Will be automatically removed
PythonPathAdder := AddPathToPythonPath(ExtractFilePath(FileName));
// GetParsedModule
ParsedModule := GetParsedModule(FileNameToModuleName(FileName), None);
if not Assigned(ParsedModule) then begin
ErrMsg := Format('Could not load and parse module: "%s"', [FileName]);
Exit;
end;
// Extract the identifier
LineS := GetNthLine(ParsedModule.Source, Line);
DottedIdent := GetWordAtPos(LineS, Col, IdentChars+['.'], True, False);
DottedIdent := DottedIdent + GetWordAtPos(LineS, Col + 1, IdentChars, False, True);
if DottedIdent = '' then begin
ErrMsg := 'No Identifier at the given line and column';
Exit;
end;
// Find scope for line
Scope := ParsedModule.GetScopeForLine(Line);
Def := nil;
if not assigned(Scope) then
ErrMsg := 'Could not find scope for the given line'
else
// Find identifier in the module and scope
Def := FindDottedDefinition(DottedIdent, ParsedModule, Scope, ErrMsg);
if Assigned(Def) and (Def is TVariable)
and (TVariable(Def).Parent is TModuleImport)
then
// Resolve further
Def := ResolveImportedName(TVariable(Def).RealName,
TModuleImport(TVariable(Def).Parent), ErrMsg);
if Assigned(Def) and (Def is TModuleImport) then
Def := ResolveModuleImport(TModuleImport(Def));
if Assigned(Def) then
FindReferences(Def, ErrMsg, List);
end;
procedure TPyScripterRefactor.FindReferences(CE: TBaseCodeElement;
var ErrMsg: string; List: TStringList);
Var
Module : TParsedModule;
SearchScope : TCodeElement;
begin
Assert(Assigned(CE));
Assert(Assigned(List));
Module := CE.GetModule;
Assert(Assigned(Module));
if (CE is TParsedModule) or (CE.Parent is TParsedModule) then
SearchScope := nil // global scope
else if CE.Parent is TParsedFunction then
// Local variable or argument or classes/ functions nested in functions
SearchScope := TParsedFunction(CE.Parent)
else if (CE.Parent is TParsedClass) and (CE.Parent.Parent is TParsedModule) then
// methods and properties
SearchScope := nil // global scope
else if CE is TParsedClass then
// Nested functions and classes
SearchScope := CE.Parent as TCodeElement
else
// e.g. methods of nested classes
SearchScope := CE.Parent.Parent as TCodeElement;
if Assigned(SearchScope) then
FindReferencesInModule(CE, Module, SearchScope.CodeBlock, ErrMsg, List)
else
FindReferencesGlobally(CE, ErrMsg, List);
end;
procedure TPyScripterRefactor.FindRefFileHandlerEx(const Directory: string;
const FileInfo: TSearchRec);
Var
ParsedModule : TParsedModule;
FileName, ErrMsg, ModuleSource, CEName : string;
begin
FileName := Directory + FileInfo.Name;
// the following if for seaching for sub-modules and sub-packages
CEName := Copy(fFindRefCE.Name, CharLastPos(fFindRefCE.Name, '.') + 1, MaxInt);
{ TODO 2 : Currently we are reading the source code twice for modules that get searched.
Once to scan them and then when they get parsed. This can be optimised out. }
if GetSource(FileName, ModuleSource) and
(Pos(CEName, ModuleSource) > 0) then
begin
ParsedModule := GetParsedModule(FileNameToModuleName(FileName), None);
if Assigned(ParsedModule) then
FindReferencesInModule(fFindRefCE, ParsedModule, ParsedModule.CodeBlock,
ErrMsg, fFindRefResults);
end;
end;
procedure TPyScripterRefactor.FindRefFileHandler(const FileName: string);
begin
fFindRefDirectoryList.Add(FileName);
end;
procedure TPyScripterRefactor.FindReferencesGlobally(CE: TBaseCodeElement;
var ErrMsg: string; List: TStringList);
Var
Module : TParsedModule;
FileName, Dir, PackageRootDir : string;
i : integer;
begin
Module := CE.GetModule;
Assert(Assigned(Module));
fFindRefFileList := TStringList.Create;
fFindRefDirectoryList := TStringList.Create;
fFindRefResults := List;
fFindRefCE := CE;
try
FileName := Module.FileName;
Dir := ExtractFileDir(FileName);
if IsDirPythonPackage(Dir) then begin
PackageRootDir := GetPackageRootDir(Dir);
EnumDirectories(PathAddSeparator(PackageRootDir), FindRefFileHandler);
end else
fFindRefDirectoryList.Add(PathAddSeparator(Dir));
for i := 0 to fFindRefDirectoryList.Count - 1 do
EnumFiles(fFindRefDirectoryList[i]+ '*.py', FindRefFileHandlerEx);
finally
FreeAndNil(fFindRefFileList);
FreeAndNil(fFindRefDirectoryList);
end;
end;
procedure TPyScripterRefactor.FindReferencesInModule(CE: TBaseCodeElement;
Module: TParsedModule; CodeBlock: TCodeBlock; var ErrMsg: string;
List: TStringList);
Var
SL : TStringList;
Line, CEName, CEModuleName : string;
i, j : integer;
LinePos: Integer;
Found : Boolean;
EndPos : integer;
Def : TBaseCodeElement;
Start: Integer;
TestChar: Char;
ModuleIsImported : boolean;
begin
// the following if for seaching for sub-modules and sub-packages
CEName := Copy(CE.Name, CharLastPos(CE.Name, '.') + 1, MaxInt);
ModuleIsImported := False;
if not SameFileName(CE.GetModule.FileName, Module.FileName) then begin
// Check (approximately!) whether CE.GetModule gets imported in Module
CEModuleName := CE.GetModule.Name;
if CharPos(CE.GetModule.Name, '.') > 0 then
CEModuleName := Copy(CEModuleName, CharLastPos(CEModuleName, '.') + 1, MaxInt);
for i := 0 to Module.ImportedModules.Count - 1 do begin
if Pos(CEModuleName, TModuleImport(Module.ImportedModules[i]).Name) >0 then begin
ModuleIsImported := True;
break;
end;
// the following is for dealing with the syntax
// from package import submodule
// if CE.Module is a submodule and subpackage
if CharPos(CE.GetModule.Name, '.') > 0 then begin
if Assigned(TModuleImport(Module.ImportedModules[i]).ImportedNames) then
for j := 0 to TModuleImport(Module.ImportedModules[i]).ImportedNames.Count - 1 do
if Pos(CEModuleName, TVariable(
TModuleImport(Module.ImportedModules[i]).ImportedNames[j]).Name) >0 then
begin
ModuleIsImported := True;
break;
end;
end;
end;
end else
ModuleIsImported := True;
if not ModuleIsImported then Exit; // no need to process further
SL := TStringList.Create;
SL.Text := Module.MaskedSource;
try
for i := CodeBlock.StartLine-1 to Min(SL.Count, CodeBlock.EndLine) - 1 do begin
Line := SL[i];
EndPos := 0;
Repeat
LinePos := StrSearch(CEName, Line, EndPos + 1);
Found := LinePos > 0;
if Found then begin
// check if it is a whole word
EndPos := LinePos + Length(CEName) - 1;
Start := LinePos - 1; // Point to previous character
if (Start > 0) then
begin
TestChar := Line[Start];
if IsCharAlphaNumeric(TestChar) or (TestChar = '_') then
Continue;
end;
if EndPos < Length(Line) then begin
TestChar := Line[EndPos+1]; // Next Character
if IsCharAlphaNumeric(TestChar) or (TestChar = '_') then
Continue;
end;
// Got Match - now process it -------------------
Def := FindDefinitionByCoordinates(Module.FileName, i+1, LinePos, ErrMsg, False);
if Assigned(Def) and (Def is TVariable)
and (TVariable(Def).Parent is TModuleImport)
then
// Resolve further
Def := ResolveImportedName(TVariable(Def).RealName,
TModuleImport(TVariable(Def).Parent), ErrMsg);
if Assigned(Def) and (Def is TModuleImport) then
Def := ResolveModuleImport(TModuleImport(Def));
if Def = CE then
List.Add(Format(FilePosInfoFormat, [Module.FileName, i+1, LinePos]));
// End of processing -------------------
end;
Until not Found;
end;
finally
SL.Free;
end;
end;
{ TModuleProxy }
procedure TModuleProxy.Expand;
Var
InspectModule, ItemsDict, ItemKeys, ItemValue : Variant;
i : integer;
S : string;
VariableProxy : TVariableProxy;
begin
InspectModule := Import('inspect');
ItemsDict := fPyModule.__dict__;
ItemKeys := ItemsDict.keys();
ItemKeys.sort();
for i := 0 to len(ItemKeys) - 1 do begin
S := ItemKeys.GetItem(i);
ItemValue := ItemsDict.GetItem(S);
if InspectModule.isroutine(ItemValue) then
AddChild(TFunctionProxy.CreateFromFunction(S, ItemValue))
else if InspectModule.isclass(ItemValue) then
AddChild(TClassProxy.CreateFromClass(S, ItemValue))
// the following would risk infinite recursion and fails in e.g. os.path
// path is a variable pointing to the module ntpath
// else if InspectModule.ismodule(ItemValue) then
// AddChild(TModuleProxy.CreateFromModule(ItemValue))
else begin
VariableProxy := TVariableProxy.CreateFromPyObject(S, ItemValue);
VariableProxy.Parent := self;
Globals.Add(VariableProxy);
end;
end;
fIsExpanded := True;
end;
constructor TModuleProxy.CreateFromModule(AModule: Variant);
begin
inherited Create;
if not VarIsPythonModule(AModule) then
Raise Exception.Create('TModuleProxy creation error');
Name := AModule.__name__;
fPyModule := AModule;
fIsExpanded := false;
fIsProxy := True;
if BuiltInModule.hasattr(fPyModule, '__file__') then
FileName := fPyModule.__file__;
end;
procedure TModuleProxy.GetNameSpace(SList: TStringList);
begin
if not fIsExpanded then Expand;
inherited;
end;
function TModuleProxy.GetAllExportsVar: string;
begin
Result := '';
// No need since we are exporting what is needed
// if BuiltInModule.hasattr(fPyModule, '__all__') then begin
// try
// PythonIIForm.ShowOutput := False;
// Result := BuiltInModule.str(fPyModule.__all__);
// Result := Copy(Result, 2, Length(Result) - 2);
// except
// Result := '';
// end;
// PythonIIForm.ShowOutput := True;
// end;
end;
function TModuleProxy.GetDocString: string;
Var
PyDocString : Variant;
begin
PyDocString := Import('inspect').getdoc(fPyModule);
if not VarIsNone(PyDocString) then
Result := PyDocString
else
Result := '';
end;
function TModuleProxy.GetCodeHint: string;
begin
if IsPackage then
Result := Format(SPackageProxyCodeHint, [Name])
else
Result := Format(SModuleProxyCodeHint, [Name]);
end;
{ TClassProxy }
procedure TClassProxy.Expand;
Var
InspectModule, ItemsDict, ItemKeys, ItemValue : Variant;
i : integer;
S : string;
VariableProxy : TVariableProxy;
begin
InspectModule := Import('inspect');
ItemsDict := BuiltInModule.dict(InspectModule.getmembers(fPyClass));
ItemKeys := ItemsDict.keys();
ItemKeys.sort();
for i := 0 to len(ItemKeys) - 1 do begin
S := ItemKeys.GetItem(i);
ItemValue := ItemsDict.GetItem(S);
if InspectModule.isroutine(ItemValue) then
AddChild(TFunctionProxy.CreateFromFunction(S, ItemValue))
else if InspectModule.isclass(ItemValue) then
AddChild(TClassProxy.CreateFromClass(S, ItemValue))
else begin
VariableProxy := TVariableProxy.CreateFromPyObject(S, ItemValue);
VariableProxy.Parent := self;
Attributes.Add(VariableProxy);
end;
end;
// setup base classes
for i := 0 to len(fPyClass.__bases__) - 1 do
SuperClasses.Add(fPyClass.__bases__[i].__name__);
fIsExpanded := True;
end;
constructor TClassProxy.CreateFromClass(AName : string; AClass: Variant);
begin
inherited Create;
if not VarIsPythonClass(AClass) then
Raise Exception.Create('TClassProxy creation error');
Name := AName;
fPyClass := AClass;
fIsExpanded := false;
fIsProxy := True;
end;
procedure TClassProxy.GetNameSpace(SList: TStringList);
Var
i : integer;
begin
if not fIsExpanded then Expand;
// There is no need to examine base classes so we do not call inherited
// Add from Children
for i := 0 to ChildCount - 1 do
SList.AddObject(TCodeElement(Children[i]).Name, Children[i]);
for i := 0 to Attributes.Count - 1 do
SList.AddObject(TVariable(Attributes[i]).Name, Attributes[i])
end;
function TClassProxy.GetDocString: string;
Var
PyDocString : Variant;
begin
PyDocString := Import('inspect').getdoc(fPyClass);
if not VarIsNone(PyDocString) then
Result := PyDocString
else
Result := '';
end;
function TClassProxy.GetConstructor: TParsedFunction;
begin
if not fIsExpanded then Expand;
Result := inherited GetConstructor;
end;
{ TFunctionProxy }
function TFunctionProxy.ArgumentsString: string;
begin
Result := PythonIIForm.II.get_arg_text(fPyFunction);
end;
constructor TFunctionProxy.CreateFromFunction(AName : string; AFunction: Variant);
var
InspectModule : Variant;
begin
inherited Create;
InspectModule := Import('inspect');
if InspectModule.isroutine(AFunction) then begin
// Name := AFunction.__name__;
Name := AName;
fPyFunction := AFunction;
fIsExpanded := false;
fIsProxy := True;
end else
Raise Exception.Create('TFunctionProxy creation error');
end;
procedure TFunctionProxy.Expand;
Var
InspectModule, ItemsDict, ItemKeys, ItemValue : Variant;
i : integer;
S : string;
NoOfArgs : integer;
Variable : TVariable;
VariableProxy : TVariableProxy;
begin
// insert members of Function type
InspectModule := Import('inspect');
ItemsDict := BuiltInModule.dict(InspectModule.getmembers(fPyFunction));
ItemKeys := ItemsDict.keys();
ItemKeys.sort();
for i := 0 to len(ItemKeys) - 1 do begin
S := ItemKeys.GetItem(i);
ItemValue := ItemsDict.GetItem(S);
if InspectModule.isroutine(ItemValue) then
AddChild(TFunctionProxy.CreateFromFunction(S, ItemValue))
else if InspectModule.isclass(ItemValue) then
AddChild(TClassProxy.CreateFromClass(S, ItemValue))
else begin
VariableProxy := TVariableProxy.CreateFromPyObject(S, ItemValue);
VariableProxy.Parent := self;
Locals.Add(VariableProxy);
end;
end;
fIsExpanded := True;
// Arguments and Locals
if BuiltinModule.hasattr(fPyFunction, 'func_code') then begin
NoOfArgs := fPyFunction.func_code.co_argcount;
for i := 0 to len(fPyFunction.func_code.co_varnames) - 1 do begin
Variable := TVariable.Create;
Variable.Name := fPyFunction.func_code.co_varnames[i];
Variable.Parent := Self;
if i < NoOfArgs then begin
Variable.Attributes := [vaArgument];
Arguments.Add(Variable);
end else
Locals.Add(Variable);
end;
end;
end;
function TFunctionProxy.GetDocString: string;
Var
PyDocString : Variant;
begin
PyDocString := Import('inspect').getdoc(fPyFunction);
if not VarIsNone(PyDocString) then
Result := PyDocString
else
Result := '';
end;
procedure TFunctionProxy.GetNameSpace(SList: TStringList);
begin
if not fIsExpanded then Expand;
inherited;
end;
{ TVariableProxy }
constructor TVariableProxy.CreateFromPyObject(const AName: string; AnObject: Variant);
begin
inherited Create;
Name := AName;
fPyObject := AnObject;
fIsExpanded := false;
fIsProxy := True;
end;
procedure TVariableProxy.GetNameSpace(SList: TStringList);
begin
if not fIsExpanded then Expand;
inherited;
end;
procedure TVariableProxy.Expand;
Var
InspectModule, ItemsDict, ItemKeys, ItemValue : Variant;
i : integer;
S : string;
begin
InspectModule := Import('inspect');
ItemsDict := BuiltinModule.dict(InspectModule.getmembers(fPyObject));
ItemKeys := ItemsDict.keys();
ItemKeys.sort();
for i := 0 to len(ItemKeys) - 1 do begin
S := ItemKeys.GetItem(i);
ItemValue := ItemsDict.GetItem(S);
if InspectModule.isroutine(ItemValue) then
AddChild(TFunctionProxy.CreateFromFunction(S, ItemValue))
else if InspectModule.isclass(ItemValue) then
AddChild(TClassProxy.CreateFromClass(S, ItemValue))
else if InspectModule.ismodule(ItemValue) then
AddChild(TModuleProxy.CreateFromModule(ItemValue))
else begin
AddChild(TVariableProxy.CreateFromPyObject(S, ItemValue))
end;
end;
fIsExpanded := True;
end;
function TVariableProxy.GetDocString: string;
Var
PyDocString : Variant;
begin
PyDocString := Import('inspect').getdoc(fPyObject);
if not VarIsNone(PyDocString) then
Result := PyDocString
else
Result := '';
end;
function TVariableProxy.GetCodeHint: string;
Var
Fmt, ObjType : string;
begin
if Parent is TParsedFunction then
Fmt := SLocalVariableCodeHint
else if Parent is TParsedClass then
Fmt := SInstanceVariableCodeHint
else if Parent is TParsedModule then
Fmt := SGlobalVariableCodeHint
else
Fmt := '';
if Fmt <> '' then begin
Result := Format(Fmt,
[Name, Parent.Name, '']);
ObjType := BuiltInModule.type(PyObject).__name__;
Result := Result + Format(SVariableTypeCodeHint, [ObjType]);
end else
Result := '';
end;
initialization
PyScripterRefactor := TPyScripterRefactor.Create;
finalization
PyScripterRefactor.Free;
end.
|
unit uSQLObj;
interface
type
TSQL = Class
private
public
end;
TSQLConnection = Class(TSQL)
private
fPW : String;
fUserName : String;
fDBAlias : String;
fServer : String;
fWinLogin : Boolean;
fStatus : String;
fTime : String;
public
function toString : String;
property PW : String read fPW write fPW;
property UserName : String read fUserName write fUserName;
property DBAlias : String read fDBAlias write fDBAlias;
property Server : String read fServer write fServer;
property WinLogin : Boolean read fWinLogin write fWinLogin;
property Status : String read fStatus write fStatus;
property Time : String read fTime write fTime;
end;
implementation
function TSQLConnection.toString : String;
var
sAut : string;
begin
if not fWinLogin then
begin
sAut := 'Authentication:SQL' + #13#10 +
'User :' + fUserName;
end
else
sAut := 'Authentication:Windows';
Result := 'Connection string' + #13#10 +
'Server :' + fServer + #13#10 +
'Database :' + fDBAlias + #13#10 +
sAut + #13#10 +
'Status :' + fStatus + #13#10 +
'Since :' + fTime;
end;
end.
|
unit uNewBarangHargaJual;
interface
uses
SysUtils, Classes, uTSBaseClass, uNewUnit, uNewBarang, uNewUOM;
type
TBarangHargaJual = class(TSBaseClass)
private
FAlokasiDanaSupplierID: Integer;
FDATE_CREATE: TDateTime;
FDATE_MODIFY: TDateTime;
FDiscNominal: Double;
FDiscPersen: Double;
FID: string;
FIsLimitQty: Integer;
FIsMailer: Integer;
FIsQtySubsidy: Integer;
FKonversiValue: Double;
FLimitQty: Integer;
FLimitQtyPrice: Double;
FMarkUp: Double;
FMaxQtyDisc: Double;
FNewBarang: TNewBarang;
FNewUnit: TUnit;
FNewUOM: TNewUOM;
// FOPC_UNIT: TUnit;
// FOPC_UNITID: Integer;
// FOPM_UNIT: TUnit;
// FOPM_UNITID: Integer;
FQtySubsidy: Integer;
FQtySubsidyPrice: Double;
FRemark: string;
FSellPrice: Double;
FSellPriceCoret: Double;
FSellPriceDisc: Double;
FTipeHargaID: string;
FUnitID: string;
function ExecuteGenerateSQLPerLine: Boolean;
function FLoadFromDB( aSQL : String ): Boolean;
public
constructor Create(aOwner : TComponent); override;
destructor Destroy; override;
procedure ClearProperties;
function CountBarangHargaJual(AKode: String; ATipeHargaID: Integer; AUnitID:
string): Integer;
function CustomTableName: string;
function ExecuteCustomSQLTask: Boolean;
function ExecuteCustomSQLTaskPrior: Boolean;
function ExecuteGenerateSQL: Boolean;
function ExecuteGenerateSQLByUnit: Boolean;
function GenerateInterbaseMetaData: Tstrings;
function GetFieldNameFor_AlokasiDanaSupplierID: string; dynamic;
function GetFieldNameFor_DATE_CREATE: string;
function GetFieldNameFor_DATE_MODIFY: string;
function GetFieldNameFor_DiscNominal: string; dynamic;
function GetFieldNameFor_DiscPersen: string; dynamic;
function GetFieldNameFor_ID: string; dynamic;
function GetFieldNameFor_IsLimitQty: string; dynamic;
function GetFieldNameFor_IsMailer: string;
function GetFieldNameFor_IsQtySubsidy: string; dynamic;
function GetFieldNameFor_KonversiValue: string; dynamic;
function GetFieldNameFor_LimitQty: string; dynamic;
function GetFieldNameFor_LimitQtyPrice: string; dynamic;
function GetFieldNameFor_MarkUp: string; dynamic;
function GetFieldNameFor_MaxQtyDisc: string;
function GetFieldNameFor_NewBarang: string; dynamic;
function GetFieldNameFor_NewUnit: string; dynamic;
function GetFieldNameFor_NewUOM: string; dynamic;
// function GetFieldNameFor_OPC_UNIT: string;
// function GetFieldNameFor_OPM_UNIT: string;
function GetFieldNameFor_QtySubsidy: string; dynamic;
function GetFieldNameFor_QtySubsidyPrice: string; dynamic;
function GetFieldNameFor_Remark: string; dynamic;
function GetFieldNameFor_SellPrice: string; dynamic;
function GetFieldNameFor_SellPriceCoret: string; dynamic;
function GetFieldNameFor_SellPriceDisc: string; dynamic;
function GetFieldNameFor_TipeHargaID: string; dynamic;
// function GetFieldNameFor_TipeHargaUnit: string; dynamic;
function GetGeneratorName: string;
function GetHeaderFlag: Integer;
function GetStorePrice(aKode : String; aUnitID : Integer; aTipeHrgID : Integer;
aTipeHrgUnitID : Integer): Double;
function GetTipeHargaName: string;
function IsSettingHargaJualSudahAda(aUnitID: integer; aKodeBrg : String;
aSatuanCOde : String; aTiPehargID : Integer; aExcluedID : Integer): Boolean;
function LoadBarangBarcodeUom(ABarcode, ATipeHargaCode: String): Boolean;
function LoadBarangHargaJualTermurah(AKode, ATipeHargaCode: String): Boolean;
function LoadBarangHargaJualTermurahUOM(AKode, ATipeHargaCode, aUoM: String):
Boolean;
function LoadByBarangKode(aBarangCode : String): Boolean; overload;
function LoadByBarangKode(aBarangCode : String; aBarangUnitID : Integer;
aSatCode : String; aSatUnitID : Integer): Boolean; overload;
function LoadByBarangKodeTipeHarga(aBarangCode : String; aSatCode : String;
aTipeHrg : Integer): Boolean;
function LoadByID(aID: string): Boolean; overload;
function RemoveFromDB: Boolean;
function SetHargaAverage(aKode : String; aUnitID : Integer; aUOMCode : String;
Var aConValue : Double; Var aHargaAvg : Double): Double;
procedure UpdateData(aAlokasiDanaSupplierID: Integer; aDiscNominal,
aDiscPersen: Double; aID: string; aIsLimitQty, aIsQtySubsidy: Integer;
aKonversiValue: Double; aLimitQty: Integer; aLimitQtyPrice, aMarkUp:
Double; aNewBarangKode, aNewUnit_ID, aUOM: string; aQtySubsidy: Integer;
aQtySubsidyPrice: Double; aRemark: string; aSellPrice, aSellPriceCoret,
aSellPriceDisc: Double; aTipeHargaID: string; aIsMailer: Integer;
aMaxQtyDisc: Double);
property AlokasiDanaSupplierID: Integer read FAlokasiDanaSupplierID write
FAlokasiDanaSupplierID;
property DATE_CREATE: TDateTime read FDATE_CREATE write FDATE_CREATE;
property DATE_MODIFY: TDateTime read FDATE_MODIFY write FDATE_MODIFY;
property DiscNominal: Double read FDiscNominal write FDiscNominal;
property DiscPersen: Double read FDiscPersen write FDiscPersen;
property ID: string read FID write FID;
property IsLimitQty: Integer read FIsLimitQty write FIsLimitQty;
property IsMailer: Integer read FIsMailer write FIsMailer;
property IsQtySubsidy: Integer read FIsQtySubsidy write FIsQtySubsidy;
property KonversiValue: Double read FKonversiValue write FKonversiValue;
property LimitQty: Integer read FLimitQty write FLimitQty;
property LimitQtyPrice: Double read FLimitQtyPrice write FLimitQtyPrice;
property MarkUp: Double read FMarkUp write FMarkUp;
property MaxQtyDisc: Double read FMaxQtyDisc write FMaxQtyDisc;
property NewBarang: TNewBarang read FNewBarang write FNewBarang;
property NewUnit: TUnit read FNewUnit write FNewUnit;
property NewUOM: TNewUOM read FNewUOM write FNewUOM;
// property OPC_UNIT: TUnit read GetOPC_UNIT write FOPC_UNIT;
// property OPM_UNIT: TUnit read GetOPM_UNIT write FOPM_UNIT;
property QtySubsidy: Integer read FQtySubsidy write FQtySubsidy;
property QtySubsidyPrice: Double read FQtySubsidyPrice write
FQtySubsidyPrice;
property Remark: string read FRemark write FRemark;
property SellPrice: Double read FSellPrice write FSellPrice;
property SellPriceCoret: Double read FSellPriceCoret write FSellPriceCoret;
property SellPriceDisc: Double read FSellPriceDisc write FSellPriceDisc;
property TipeHargaID: string read FTipeHargaID write FTipeHargaID;
property UnitID: string read FUnitID write FUnitID;
end;
function IsUOMSudahAdaKonversi(aBrgCode, aUOM: String): Boolean;
implementation
uses FireDAC.Comp.Client, FireDAC.Stan.Error, udmMain, uAppUtils, StrUtils;
function IsUOMSudahAdaKonversi(aBrgCode, aUOM: String): Boolean;
var
sSQL: string;
begin
Result := False;
sSQL := 'select count(KONVSAT_ID)'
+ ' from REF$KONVERSI_SATUAN'
+ ' where KONVSAT_BRG_CODE = ' + QuotedStr(aBrgCode)
// + ' and KONVSAT_UNT_ID = KONVSAT_BRG_UNT_ID'
// + ' and KONVSAT_SCF_UNT_ID = KONVSAT_UNT_ID'
// + ' and KONVSAT_UNT_ID = ' + IntToStr(aUnitID)
+ ' and KONVSAT_SAT_CODE_FROM = ' + QuotedStr(aUOM);
with cOpenQuery(sSQL) do
begin
try
if not Fields[0].IsNull then
if Fields[0].asInteger > 0 then
Result := True;
finally
Free;
end;
end;
end;
{
******************************* TBarangHargaJual *******************************
}
constructor TBarangHargaJual.Create(aOwner : TComponent);
begin
inherited create(aOwner);
FNewBarang := TNewBarang.Create(Self);
FNewUnit := TUnit.Create(Self);
FNewUOM := TNewUOM.Create(Self);
end;
destructor TBarangHargaJual.Destroy;
begin
FNewBarang.free;
FNewUnit.free;
FNewUOM.free;
inherited Destroy;
end;
procedure TBarangHargaJual.ClearProperties;
begin
FAlokasiDanaSupplierID := 0;
FDiscNominal := 0;
FDiscPersen := 0;
FID := '';
FIsLimitQty := 0;
FIsQtySubsidy := 0;
FKonversiValue := 0;
FLimitQty := 0;
FLimitQtyPrice := 0;
FMarkUp := 0;
FUnitID := '';
FQtySubsidy := 0;
FQtySubsidyPrice := 0;
FRemark := '';
FSellPrice := 0;
FSellPriceCoret := 0;
FSellPriceDisc := 0;
FTipeHargaID := '';
FIsMailer := 0;
FMaxQtyDisc := 0;
FNewBarang.ClearProperties;
FNewUnit.ClearProperties;
FNewUOM.ClearProperties;
end;
function TBarangHargaJual.CountBarangHargaJual(AKode: String; ATipeHargaID:
Integer; AUnitID: string): Integer;
var
sSQL: string;
begin
//Result := 0;
sSQL := 'select count(*) '
+ 'from ' + CustomTableName
+ ' where bhj_tphrg_id = ' + IntToStr(ATipeHargaID)
+ ' and bhj_tphrg_unt_id = ' + QuotedStr(AUnitID)
+ ' and bhj_brg_code = ' + QuotedStr(AKode);
with cOpenQuery(sSQL) do
begin
Try
Result := Fields[0].AsInteger;
Finally
Free;
end;
end;
end;
function TBarangHargaJual.CustomTableName: string;
begin
Result := 'BARANG_HARGA_JUAL';
end;
function TBarangHargaJual.ExecuteCustomSQLTask: Boolean;
begin
result := True;
end;
function TBarangHargaJual.ExecuteCustomSQLTaskPrior: Boolean;
begin
result :=True;
end;
function TBarangHargaJual.ExecuteGenerateSQL: Boolean;
var
S: string;
begin
result := False;
try
if State = csNone then
Begin
raise Exception.create('Tidak bisa generate dalam Mode csNone')
end;
if not ExecuteCustomSQLTaskPrior then
begin
cRollbackTrans;
Exit
end
else
begin
DATE_MODIFY := cGetServerDateTime;
// FOPM_UNITID := FNewUnit.ID;
// if FID <= 0 then
if FID = '' then
begin
//Generate Insert SQL
DATE_CREATE := DATE_MODIFY;
// FOPC_UNITID := FOPM_UNITID;
// FID := cGetNextID(GetFieldNameFor_ID, CustomTableName);
FID := cGetNextIDGUIDToString;
S := 'Insert into ' + CustomTableName + ' ( '
+ GetFieldNameFor_DATE_CREATE + ', '
+ GetFieldNameFor_DATE_MODIFY + ', '
// + GetFieldNameFor_OPC_UNIT + ', '
// + GetFieldNameFor_OPM_UNIT + ', '
+ GetFieldNameFor_AlokasiDanaSupplierID + ', '
+ GetFieldNameFor_DiscNominal + ', ' + GetFieldNameFor_DiscPersen + ', '
+ GetFieldNameFor_ID + ', ' + GetFieldNameFor_IsLimitQty + ', '
+ GetFieldNameFor_IsQtySubsidy + ', ' + GetFieldNameFor_KonversiValue + ', '
+ GetFieldNameFor_LimitQty + ', ' + GetFieldNameFor_LimitQtyPrice + ', '
+ GetFieldNameFor_MarkUp + ', ' + GetFieldNameFor_NewBarang + ', '
+ GetFieldNameFor_NewUnit + ', ' + GetFieldNameFor_NewUOM + ', '
+ GetFieldNameFor_QtySubsidy + ', ' + GetFieldNameFor_QtySubsidyPrice + ', '
+ GetFieldNameFor_Remark + ', ' + GetFieldNameFor_SellPrice + ', '
+ GetFieldNameFor_SellPriceCoret + ', ' + GetFieldNameFor_SellPriceDisc + ','
// + GetFieldNameFor_TipeHargaID + ', ' + GetFieldNameFor_TipeHargaUnit + ','
+ GetFieldNameFor_IsMailer + ', '
+ GetFieldNameFor_MaxQtyDisc
+ ') values ('
+ TAppUtils.QuotDT(FDATE_CREATE) + ', '
+ TAppUtils.QuotDT(FDATE_MODIFY) + ', '
// + InttoStr(FOPC_UNITID) + ', '
// + InttoStr(FOPM_UNITID) + ', '
+ IfThen(FAlokasiDanaSupplierID = 0, 'null, ', IntToStr(FAlokasiDanaSupplierID) + ', ')
+ FormatFloat('0.00', FDiscNominal) + ', '
+ FormatFloat('0.00', FDiscPersen) + ', '
+ QuotedStr( FID) + ', '
+ IntToStr( FIsLimitQty) + ', '
+ IntToStr( FIsQtySubsidy) + ', '
+ FormatFloat('0.00000000', FKonversiValue) + ', '
+ IntToStr( FLimitQty) + ', '
+ FormatFloat('0.00', FLimitQtyPrice) + ', '
+ FormatFloat('0.00', FMarkUp) + ', '
+ QuotedStr( FNewBarang.Kode) + ', '
+ QuotedStr( FUnitID) + ', '
+ QuotedStr( FNewUOM.UOM) + ', '
+ IntToStr( FQtySubsidy) + ', '
+ FormatFloat('0.00', FQtySubsidyPrice) + ', '
+ QuotedStr(FRemark ) + ','
+ FormatFloat('0.00', FSellPrice) + ', '
+ FormatFloat('0.00', FSellPriceCoret) + ', '
+ FormatFloat('0.00', FSellPriceDisc) + ', '
+ QuotedStr( FTipeHargaID) + ', '
+ QuotedStr( FUnitID) + ', '
+ InttoStr( FIsMailer) + ', '
+ FormatFloat('0.00', FMaxQtyDisc)
+ ');'
end
else
begin
S := 'Update ' + CustomTableName + ' set '
+ GetFieldNameFor_DATE_MODIFY + ' = ' + TAppUtils.QuotDT(FDATE_MODIFY)
// + ', ' + GetFieldNameFor_OPM_UNIT + ' = ' + IntToStr(FOPM_UNITID)
+ ', ' + GetFieldNameFor_AlokasiDanaSupplierID + ' = ' + IfThen(FAlokasiDanaSupplierID = 0, 'null', IntToStr(FAlokasiDanaSupplierID) + '')
+ ', ' + GetFieldNameFor_DiscNominal + ' = ' + FormatFloat('0.00', FDiscNominal)
+ ', ' + GetFieldNameFor_DiscPersen + ' = ' + FormatFloat('0.00', FDiscPersen)
+ ', ' + GetFieldNameFor_IsLimitQty + ' = ' + IntToStr( FIsLimitQty)
+ ', ' + GetFieldNameFor_IsQtySubsidy + ' = ' + IntToStr( FIsQtySubsidy)
+ ', ' + GetFieldNameFor_KonversiValue + ' = ' + FormatFloat('0.00000000', FKonversiValue)
+ ', ' + GetFieldNameFor_LimitQty + ' = ' + IntToStr( FLimitQty)
+ ', ' + GetFieldNameFor_LimitQtyPrice + ' = ' + FormatFloat('0.00', FLimitQtyPrice)
+ ', ' + GetFieldNameFor_MarkUp + ' = ' + FormatFloat('0.00', FMarkUp)
+ ', ' + GetFieldNameFor_NewBarang + ' = ' + QuotedStr( FNewBarang.Kode)
+ ', ' + GetFieldNameFor_NewUnit + ' = ' + QuotedStr( FUnitID)
+ ', ' + GetFieldNameFor_NewUOM + ' = ' + QuotedStr( FNewUOM.UOM)
+ ', ' + GetFieldNameFor_QtySubsidy + ' = ' + IntToStr( FQtySubsidy)
+ ', ' + GetFieldNameFor_QtySubsidyPrice + ' = ' + FormatFloat('0.00', FQtySubsidyPrice)
+ ' , ' + GetFieldNameFor_Remark + ' = ' + QuotedStr( FRemark )
+ ', ' + GetFieldNameFor_SellPrice + ' = ' + FormatFloat('0.00', FSellPrice)
+ ', ' + GetFieldNameFor_SellPriceCoret + ' = ' + FormatFloat('0.00', FSellPriceCoret)
+ ', ' + GetFieldNameFor_SellPriceDisc + ' = ' + FormatFloat('0.00', FSellPriceDisc)
+ ', ' + GetFieldNameFor_TipeHargaID + ' = ' + QuotedStr( FTipeHargaID)
// + ', ' + GetFieldNameFor_TipeHargaUnit + ' = ' + IntToStr(FUnitID)
+ ', ' + GetFieldNameFor_IsMailer + ' = ' + IntToStr( IsMailer)
+ ', ' + GetFieldNameFor_MaxQtyDisc + ' = ' + FormatFloat('0.00', FMaxQtyDisc)
+ ' Where '+ GetFieldNameFor_NewUnit +' = ' + QuotedStr(FUnitID)
+ ' and '+ GetFieldNameFor_ID +' = ' + QuotedStr(FID) + ';';
end;
end;
if not cExecSQL(S, dbtPOS, False) then
begin
cRollbackTrans;
Exit;
end else
Result := ExecuteCustomSQLTask;
finally
// DecimalSeparator := lDecimalSeparator;
end;
end;
function TBarangHargaJual.ExecuteGenerateSQLByUnit: Boolean;
begin
Result := ExecuteGenerateSQLPerLine;
end;
function TBarangHargaJual.ExecuteGenerateSQLPerLine: Boolean;
begin
try
Result := ExecuteGenerateSQL;
if not IsUOMSudahAdaKonversi(fnewBarang.Kode, FNewUOM.UOM) then
begin
Result := False;
end;
except
Result := False;
end;
end;
function TBarangHargaJual.FLoadFromDB( aSQL : String ): Boolean;
begin
result := false;
State := csNone;
ClearProperties;
with cOpenQuery(aSQL) do
Begin
if not EOF then
begin
FAlokasiDanaSupplierID := FieldByName(GetFieldNameFor_AlokasiDanaSupplierID).asInteger;
FDiscNominal := FieldByName(GetFieldNameFor_DiscNominal).asFloat;
FDiscPersen := FieldByName(GetFieldNameFor_DiscPersen).asFloat;
FID := FieldByName(GetFieldNameFor_ID).AsString;
FIsLimitQty := FieldByName(GetFieldNameFor_IsLimitQty).asInteger;
FIsQtySubsidy := FieldByName(GetFieldNameFor_IsQtySubsidy).asInteger;
FKonversiValue := FieldByName(GetFieldNameFor_KonversiValue).asFloat;
FLimitQty := FieldByName(GetFieldNameFor_LimitQty).asInteger;
FLimitQtyPrice := FieldByName(GetFieldNameFor_LimitQtyPrice).asFloat;
FMarkUp := FieldByName(GetFieldNameFor_MarkUp).asFloat;
FIsMailer := FieldByName(GetFieldNameFor_IsMailer).AsInteger;
FMaxQtyDisc := FieldByName(GetFieldNameFor_MaxQtyDisc).asFloat;
FNewUnit.LoadByID(FieldByName(GetFieldNameFor_NewUnit).AsString);
FNewBarang.LoadByKode(FieldByName(GetFieldNameFor_NewBarang).AsString);
FNewUOM.LoadByID(FieldByName(GetFieldNameFor_NewUOM).AsString);
FQtySubsidy := FieldByName(GetFieldNameFor_QtySubsidy).asInteger;
FQtySubsidyPrice := FieldByName(GetFieldNameFor_QtySubsidyPrice).asFloat;
FRemark := FieldByName(GetFieldNameFor_Remark).asString;
FSellPrice := FieldByName(GetFieldNameFor_SellPrice).asFloat;
FSellPriceCoret := FieldByName(GetFieldNameFor_SellPriceCoret).asFloat;
FSellPriceDisc := FieldByName(GetFieldNameFor_SellPriceDisc).asFloat;
FTipeHargaID := FieldByName(GetFieldNameFor_TipeHargaID).AsString;
Self.State := csLoaded;
Result := True;
end;
Free;
End;
end;
function TBarangHargaJual.GenerateInterbaseMetaData: Tstrings;
begin
result := TstringList.create;
result.Append( '' );
result.Append( 'Create Table TBarangHargaJual ( ' );
result.Append( 'TRMSBaseClass_ID Integer not null, ' );
result.Append( 'AlokasiDanaSupplierID Integer Not Null , ' );
result.Append( 'AlokasiDanaSupplierUnit_ID Integer Not Null, ' );
result.Append( 'BarangUnit_ID Integer Not Null, ' );
result.Append( 'DiscNominal double precision Not Null , ' );
result.Append( 'DiscPersen double precision Not Null , ' );
result.Append( 'ID Integer Not Null Unique, ' );
result.Append( 'IsLimitQty Integer Not Null , ' );
result.Append( 'IsQtySubsidy Integer Not Null , ' );
result.Append( 'KonversiValue double precision Not Null , ' );
result.Append( 'LimitQty Integer Not Null , ' );
result.Append( 'LimitQtyPrice double precision Not Null , ' );
result.Append( 'MarkUp double precision Not Null , ' );
result.Append( 'NewBarang_ID Integer Not Null, ' );
result.Append( 'NewUnit_ID Integer Not Null, ' );
result.Append( 'NewUOM_ID Integer Not Null, ' );
result.Append( 'QtySubsidy Integer Not Null , ' );
result.Append( 'QtySubsidyPrice double precision Not Null , ' );
result.Append( 'Remark Varchar(30) Not Null , ' );
result.Append( 'SellPrice double precision Not Null , ' );
result.Append( 'SellPriceCoret double precision Not Null , ' );
result.Append( 'SellPriceDisc double precision Not Null , ' );
result.Append( 'TipeHargaID Integer Not Null , ' );
result.Append( 'TipeHargaUnit_ID Integer Not Null, ' );
result.Append( 'UOMUnit_ID Integer Not Null, ' );
result.Append( 'Stamp TimeStamp ' );
result.Append( ' ); ' );
end;
function TBarangHargaJual.GetFieldNameFor_AlokasiDanaSupplierID: string;
begin
Result := 'BHJ_ADSO_ID';// <<-- Rubah string ini untuk mapping
end;
function TBarangHargaJual.GetFieldNameFor_DATE_CREATE: string;
begin
Result := 'DATE_CREATE';
end;
function TBarangHargaJual.GetFieldNameFor_DATE_MODIFY: string;
begin
Result := 'DATE_MODIFY';
end;
function TBarangHargaJual.GetFieldNameFor_DiscNominal: string;
begin
Result := 'BHJ_DISC_NOMINAL';// <<-- Rubah string ini untuk mapping
end;
function TBarangHargaJual.GetFieldNameFor_DiscPersen: string;
begin
Result := 'BHJ_DISC_PERSEN';// <<-- Rubah string ini untuk mapping
end;
function TBarangHargaJual.GetFieldNameFor_ID: string;
begin
// Result := 'BHJ_ID';// <<-- Rubah string ini untuk mapping
Result := 'BARANG_HARGA_JUAL_ID'
end;
function TBarangHargaJual.GetFieldNameFor_IsLimitQty: string;
begin
Result := 'BHJ_IS_LIMIT_QTY';// <<-- Rubah string ini untuk mapping
end;
function TBarangHargaJual.GetFieldNameFor_IsMailer: string;
begin
Result := 'BHJ_IS_MAILER';
end;
function TBarangHargaJual.GetFieldNameFor_IsQtySubsidy: string;
begin
Result := 'BHJ_IS_QTY_SUBSIDY';// <<-- Rubah string ini untuk mapping
end;
function TBarangHargaJual.GetFieldNameFor_KonversiValue: string;
begin
Result := 'BHJ_CONV_VALUE';// <<-- Rubah string ini untuk mapping
end;
function TBarangHargaJual.GetFieldNameFor_LimitQty: string;
begin
Result := 'BHJ_LIMIT_QTY';// <<-- Rubah string ini untuk mapping
end;
function TBarangHargaJual.GetFieldNameFor_LimitQtyPrice: string;
begin
Result := 'BHJ_LIMIT_QTY_PRICE';// <<-- Rubah string ini untuk mapping
end;
function TBarangHargaJual.GetFieldNameFor_MarkUp: string;
begin
Result := 'BHJ_MARK_UP';// <<-- Rubah string ini untuk mapping
end;
function TBarangHargaJual.GetFieldNameFor_MaxQtyDisc: string;
begin
Result := 'BHJ_Max_Qty_Disc';
end;
function TBarangHargaJual.GetFieldNameFor_NewBarang: string;
begin
Result := 'BHJ_BRG_CODE';// <<-- Rubah string ini untuk mapping
end;
function TBarangHargaJual.GetFieldNameFor_NewUnit: string;
begin
Result := 'BHJ_UNT_ID';// <<-- Rubah string ini untuk mapping
end;
function TBarangHargaJual.GetFieldNameFor_NewUOM: string;
begin
// Result := 'BHJ_SAT_CODE';// <<-- Rubah string ini untuk mapping
Result := 'REF$SATUAN_ID';
end;
//function TBarangHargaJual.GetFieldNameFor_OPC_UNIT: string;
//begin
// Result := 'OPC_UNIT';
//end;
//function TBarangHargaJual.GetFieldNameFor_OPM_UNIT: string;
//begin
// Result := 'OPM_UNIT';
//end;
function TBarangHargaJual.GetFieldNameFor_QtySubsidy: string;
begin
Result := 'BHJ_QTY_SUBSIDY';// <<-- Rubah string ini untuk mapping
end;
function TBarangHargaJual.GetFieldNameFor_QtySubsidyPrice: string;
begin
Result := 'BHJ_QTY_SUBSIDY_PRICE';// <<-- Rubah string ini untuk mapping
end;
function TBarangHargaJual.GetFieldNameFor_Remark: string;
begin
Result := 'BHJ_REMARK';// <<-- Rubah string ini untuk mapping
end;
function TBarangHargaJual.GetFieldNameFor_SellPrice: string;
begin
Result := 'BHJ_SELL_PRICE';// <<-- Rubah string ini untuk mapping
end;
function TBarangHargaJual.GetFieldNameFor_SellPriceCoret: string;
begin
Result := 'BHJ_SELL_PRICE_CORET';// <<-- Rubah string ini untuk mapping
end;
function TBarangHargaJual.GetFieldNameFor_SellPriceDisc: string;
begin
Result := 'BHJ_SELL_PRICE_DISC';// <<-- Rubah string ini untuk mapping
end;
function TBarangHargaJual.GetFieldNameFor_TipeHargaID: string;
begin
// Result := 'BHJ_TPHRG_ID';// <<-- Rubah string ini untuk mapping
Result := 'REF$TIPE_HARGA_ID';
end;
//function TBarangHargaJual.GetFieldNameFor_TipeHargaUnit: string;
//begin
// Result := 'BHJ_TPHRG_UNT_ID';// <<-- Rubah string ini untuk mapping
//end;
function TBarangHargaJual.GetGeneratorName: string;
begin
Result := 'gen_barang_harga_jual_id' ;
end;
function TBarangHargaJual.GetHeaderFlag: Integer;
begin
result := 1678;
end;
//function TBarangHargaJual.GetOPC_UNIT: TUnit;
//begin
// try
// if FOPC_UNIT = nil then
// begin
// FOPC_UNIT := TUnit.Create(nil);
// FOPC_UNIT.LoadByID(FOPC_UNITID);
// end;
//
// finally
// Result := FOPC_UNIT;
// end;
//end;
//function TBarangHargaJual.GetOPM_UNIT: TUnit;
//begin
// try
// if FOPM_UNIT = nil then
// begin
// FOPM_UNIT := TUnit.Create(nil);
// FOPM_UNIT.LoadByID(FOPM_UNITID);
// end;
//
// finally
// Result := FOPM_UNIT;
// end;
//end;
function TBarangHargaJual.GetStorePrice(aKode : String; aUnitID : Integer;
aTipeHrgID : Integer; aTipeHrgUnitID : Integer): Double;
var
s: string;
begin
Result := 0;
s := 'SELECT BHJ_SELL_PRICE_DISC FROM BARANG_HARGA_JUAL BHJ'
+ ' WHERE BHJ_BRG_CODE = ' + QuotedStr(aKode)
+ ' AND BHJ_TPHRG_ID = ' + IntToStr(aTipeHrgID)
+ ' AND BHJ_UNT_ID = ' + IntToStr(aUnitID)
+ ' AND BHJ_TPHRG_UNT_ID = ' + IntToStr(aTipeHrgUnitID);
with cOpenQuery(s) do
begin
try
if not eof then
begin
Result := Fields[0].AsFloat;
end;
finally
Free;
end;
end;
end;
function TBarangHargaJual.GetTipeHargaName: string;
var
sSQL: string;
begin
Result := '';
sSQL := 'select tphrg_name'
+ ' from ref$tipe_harga'
+ ' where ref$tipe_harga_id = ' + QuotedStr(TipeHargaID);
with cOpenQuery(sSQL) do
begin
try
while not Eof do
begin
Result := FieldByName('tphrg_name').AsString;
Next;
end;
finally
Free;
end;
end;
end;
function TBarangHargaJual.IsSettingHargaJualSudahAda(aUnitID: integer; aKodeBrg
: String; aSatuanCOde : String; aTiPehargID : Integer; aExcluedID :
Integer): Boolean;
var
sSQL: string;
begin
Result := False;
sSQL := 'select count(1) from ' + CustomTableName
// + ' where bhj_unt_id = ' + IntToStr(aUnitID)
+ ' WHERE bhj_brg_code = ' + QuotedStr(aKodeBrg)
+ ' and bhj_sat_code = ' + QuotedStr(aSatuanCOde)
+ ' and bhj_tphrg_id = ' + IntToStr(aTiPehargID)
+ ' and ' + GetFieldNameFor_ID + ' <> ' + IntToStr(aExcluedID);
with cOpenQuery(sSQL) do
begin
try
if Fields[0].AsInteger > 0 then
Result := True;
finally
Free;
end;
end;
end;
function TBarangHargaJual.LoadBarangBarcodeUom(ABarcode, ATipeHargaCode:
String): Boolean;
var
sSQL: string;
begin
Result := False;
sSQL := 'select bhj.* '
+ ' FROM REF$KONVERSI_SATUAN ks INNER JOIN '
+ CustomTableName + ' bhj ON (ks.KONVSAT_BRG_CODE = bhj.BHJ_BRG_CODE) '
+ ' AND (ks.KONVSAT_SAT_CODE_FROM = bhj.BHJ_SAT_CODE) '
+ ' INNER JOIN REF$TIPE_HARGA TH ON TH.' + GetFieldNameFor_TipeHargaID
+ ' = bhj.' + GetFieldNameFor_TipeHargaID
+ ' WHERE TH.TPHRG_CODE = ' + QuotedStr(ATipeHargaCode)
+ ' and ks.KONVSAT_BARCODE = ' + QuotedStr(ABarcode)
+ ' order by bhj.bhj_sell_price asc';
if FLoadFromDB(sSQL) then
Result := True;
end;
function TBarangHargaJual.LoadBarangHargaJualTermurah(AKode, ATipeHargaCode:
String): Boolean;
var
sSQL: string;
begin
Result := False;
sSQL := 'select A.* '
+ 'from ' + CustomTableName + ' A '
+ ' inner join REF$TIPE_HARGA B on A.' + GetFieldNameFor_TipeHargaID + ' = B.' + GetFieldNameFor_TipeHargaID
+ ' inner join BARANG C on C.BARANG_ID = A.BARANG_ID '
+ ' where B.TPHRG_CODE = ' + QuotedStr(ATipeHargaCode)
// + ' and bhj_tphrg_unt_id = ' + IntToStr(AUnitID)
+ ' and C.brg_code = ' + QuotedStr(AKode)
+ ' order by A.bhj_sell_price asc';
if FLoadFromDB(sSQL) then
Result := True;
end;
function TBarangHargaJual.LoadBarangHargaJualTermurahUOM(AKode, ATipeHargaCode,
aUoM: String): Boolean;
var
sSQL: string;
begin
Result := False;
sSQL := 'select B.* '
+ ' from ' + CustomTableName + ' B '
+ ' inner join REF$TIPE_HARGA T on T.REF$TIPE_HARGA_ID = B.REF$TIPE_HARGA_ID '
+ ' inner join BARANG A on A.BARANG_ID = B.BARANG_ID '
+ ' inner join REF$SATUAN S on S.REF$SATUAN_ID = B.REF$SATUAN_ID '
// + ' and T.TPHRG_UNT_ID = B.BHJ_TPHRG_UNT_ID '
+ ' where T.TPHRG_CODE = ' + QuotedStr(ATipeHargaCode)
// + ' and B.bhj_tphrg_unt_id = ' + QuotedStr(AUnitID)
+ ' and A.brg_code = ' + QuotedStr(AKode)
+ IfThen(aUoM='', '', ' and S.SAT_CODE = ' + QuotedStr(aUoM))
+ ' order by B.bhj_sell_price asc';
if FLoadFromDB(sSQL) then
Result := True;
end;
function TBarangHargaJual.LoadByBarangKode(aBarangCode : String): Boolean;
var
s: string;
begin
s := 'SELECT * FROM ' + CustomTableName
+ ' WHERE BHJ_BRG_CODE =' + QuotedStr(aBarangCode);
Result := FLoadFromDB(s);
end;
function TBarangHargaJual.LoadByBarangKode(aBarangCode : String; aBarangUnitID
: Integer; aSatCode : String; aSatUnitID : Integer): Boolean;
var
s: string;
begin
s := 'SELECT * FROM ' + CustomTableName
+ ' WHERE BHJ_SAT_CODE = ' + QuotedStr(aSatCode)
+ ' AND BHJ_BRG_CODE =' + QuotedStr(aBarangCode);
Result := FLoadFromDB(s);
end;
function TBarangHargaJual.LoadByBarangKodeTipeHarga(aBarangCode : String;
aSatCode : String; aTipeHrg : Integer): Boolean;
var
s: string;
begin
Result := False;
s := 'SELECT * FROM ' + CustomTableName
+ ' WHERE BHJ_SAT_CODE = ' + QuotedStr(aSatCode)
+ ' AND BHJ_BRG_CODE =' + QuotedStr(aBarangCode)
+ ' AND BHJ_TPHRG_ID = ' + IntToStr(aTipeHrg);
if FLoadFromDB(s) then
Result := True;
end;
function TBarangHargaJual.LoadByID(aID: string): Boolean;
begin
result := FloadFromDB('Select * from ' + CustomTableName + ' Where '
+ GetFieldNameFor_ID +' = ' + QuotedStr(aID) );
end;
function TBarangHargaJual.RemoveFromDB: Boolean;
var
sSQL: string;
begin
Result := False;
sSQL := 'delete from ' + CustomTableName
+ ' where ' + GetFieldNameFor_ID + ' = ' + QuotedStr(ID)
+ ' and ' + GetFieldNameFor_NewUnit + ' = ' + QuotedStr(NewUnit.ID) ;
if cExecSQL(sSQL, dbtPOS, False) then
Result := True; //SimpanBlob(sSQL,GetHeaderFlag);
end;
function TBarangHargaJual.SetHargaAverage(aKode : String; aUnitID : Integer;
aUOMCode : String; Var aConValue : Double; Var aHargaAvg : Double): Double;
var
s: string;
begin
Result := 0;
aConValue := 0;
aHargaAvg := 0;
s := 'SELECT b.KONVSAT_SCALE, (a.BRG_HARGA_AVERAGE * b.KONVSAT_SCALE) as HargaAverage'
+ ' FROM BARANG a, REF$KONVERSI_SATUAN b WHERE a.BRG_CODE = b.KONVSAT_BRG_CODE'
+ ' AND a.BRG_SAT_CODE_STOCK = b.KONVSAT_SAT_CODE_TO'
+ ' AND b.KONVSAT_SAT_CODE_FROM = ' + QuotedStr(aUOMCode)
+ ' AND a.BRG_CODE = ' + QuotedStr(aKode);
with cOpenQuery(s) do
begin
try
if not eof then
begin
aConValue := Fields[0].AsFloat;
aHargaAvg := Fields[1].AsFloat;
end;
finally
Free;
end;
end;
end;
procedure TBarangHargaJual.UpdateData(aAlokasiDanaSupplierID: Integer;
aDiscNominal, aDiscPersen: Double; aID: string; aIsLimitQty, aIsQtySubsidy:
Integer; aKonversiValue: Double; aLimitQty: Integer; aLimitQtyPrice,
aMarkUp: Double; aNewBarangKode, aNewUnit_ID, aUOM: string; aQtySubsidy:
Integer; aQtySubsidyPrice: Double; aRemark: string; aSellPrice,
aSellPriceCoret, aSellPriceDisc: Double; aTipeHargaID: string; aIsMailer:
Integer; aMaxQtyDisc: Double);
begin
FAlokasiDanaSupplierID := aAlokasiDanaSupplierID;
FDiscNominal := aDiscNominal;
FDiscPersen := aDiscPersen;
FID := aID;
FIsLimitQty := aIsLimitQty;
FIsQtySubsidy := aIsQtySubsidy;
FKonversiValue := aKonversiValue;
FLimitQty := aLimitQty;
FLimitQtyPrice := aLimitQtyPrice;
FMarkUp := aMarkUp;
FUnitID := aNewUnit_ID;
FNewUnit.LoadByID(aNewUnit_ID);
FNewBarang.LoadByKode(aNewBarangKode);
FNewUOM.LoadByUOM(aUOM);
FQtySubsidy := aQtySubsidy;
FQtySubsidyPrice := aQtySubsidyPrice;
FRemark := trim(aRemark);
FSellPrice := aSellPrice;
FSellPriceCoret := aSellPriceCoret;
FSellPriceDisc := aSellPriceDisc;
FTipeHargaID := aTipeHargaID;
FIsMailer := aIsMailer;
FMaxQtyDisc := aMaxQtyDisc;
state := csCreated;
end;
end.
|
{-------------------------------------------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-------------------------------------------------------------------------------}
{===============================================================================
Memory vector classes
©František Milt 2018-10-22
Version 1.1.2
Dependencies:
AuxTypes - github.com/ncs-sniper/Lib.AuxTypes
AuxClasses - github.com/ncs-sniper/Lib.AuxClasses
StrRect - github.com/ncs-sniper/Lib.StrRect
ListSorters - github.com/ncs-sniper/Lib.ListSorters
===============================================================================}
(*******************************************************************************
Not implemented as generic class mainly because of backward compatibility. To
create a derived/specialized class from base class, replace @ClassName@ with a
class identifier and @Type@ with identifier of used type in the following
template. Also remember to implement proper comparison function for a chosen
type.
Optional methods are not required to be implemented, but they might be usefull
in some instances (eg. when item contains reference-counted types, pointers
or object references).
== Declaration ===============================================================
--------------------------------------------------------------------------------
@ClassName@ = class(TMemVector)
protected
Function GetItem(Index: Integer): @Type@; virtual;
procedure SetItem(Index: Integer; Value: @Type@); virtual;
//procedure ItemInit(ItemPtr: Pointer); override;
//procedure ItemFinal(ItemPtr: Pointer); override;
//procedure ItemCopy(SrcItem,DstItem: Pointer); override;
Function ItemCompare(Item1,Item2: Pointer): Integer; override;
//Function ItemEquals(Item1,Item2: Pointer): Boolean; override;
public
constructor Create; overload;
constructor Create(Memory: Pointer; Count: Integer); overload;
Function First: @Type@; reintroduce;
Function Last: @Type@; reintroduce;
Function IndexOf(Item: @Type@): Integer; reintroduce;
Function Add(Item: @Type@): Integer; reintroduce;
procedure Insert(Index: Integer; Item: @Type@); reintroduce;
Function Remove(Item: @Type@): Integer; reintroduce;
Function Extract(Item: @Type@): @Type@; reintroduce;
property Items[Index: Integer]: @Type@ read GetItem write SetItem; default;
end;
== Implementation ============================================================
--------------------------------------------------------------------------------
Function @ClassName@.GetItem(Index: Integer): @Type@;
begin
Result := @Type@(GetItemPtr(Index)^);
end;
//------------------------------------------------------------------------------
procedure @ClassName@.SetItem(Index: Integer; Value: @Type@);
begin
SetItemPtr(Index,@Value);
end;
//------------------------------------------------------------------------------
// Method called for each item that is implicitly (eg. when changing the Count
// property to a higher number) added to the vector.
// Item is filled with zeroes in default implementation.
//procedure @ClassName@.ItemInit(ItemPtr: Pointer); override;
//begin
//{$MESSAGE WARN 'Implement item initialization to suit actual type.'}
//end;
//------------------------------------------------------------------------------
// Method called for each item that is implicitly (e.g. when changing the Count
// property to a lower number) removed from the vector.
// No default behavior.
//procedure @ClassName@.ItemFinal(ItemPtr: Pointer); override;
//begin
//{$MESSAGE WARN 'Implement item finalization to suit actual type.'}
//end;
//------------------------------------------------------------------------------
// Called when an item is copied to the vector from an external source and
// ManagedCopy is set to true. Called only by methods that has parameter
// ManagedCopy.
// Item is copied without any further processing in default implementation.
//procedure @ClassName@.ItemCopy(SrcItem,DstItem: Pointer); override;
//begin
//{$MESSAGE WARN 'Implement item copy to suit actual type.'}
//end;
//------------------------------------------------------------------------------
// This method is called when there is a need to compare two items, for example
// when sorting the vector.
// Must return negative number when Item1 is higher/larger than Item2, zero when
// they are equal and positive number when Item1 is lower/smaller than Item2.
// No default implementation.
// This method must be implemented in derived classes!
Function @ClassName@.ItemCompare(Item1,Item2: Pointer): Integer;
begin
{$MESSAGE WARN 'Implement comparison to suit actual type.'}
end;
//------------------------------------------------------------------------------
// Called when two items are compared for equality (e.g. when searching for a
// particular item).
// In default implementation, it calls ItemCompare and when it returns zero,
// items are considered to be equal.
//Function @ClassName@.ItemEquals(Item1,Item2: Pointer): Boolean; override;
//begin
//{$MESSAGE WARN 'Implement equality comparison to suit actual type.'}
//end;
//==============================================================================
constructor @ClassName@.Create;
begin
inherited Create(SizeOf(@Type@));
end;
// --- --- --- --- --- --- --- --- --- --- --- --- ---
constructor @ClassName@.Create(Memory: Pointer; Count: Integer);
begin
inherited Create(Memory,Count,SizeOf(@Type@));
end;
//------------------------------------------------------------------------------
Function @ClassName@.First: @Type@;
begin
Result := @Type@(inherited First^);
end;
//------------------------------------------------------------------------------
Function @ClassName@.Last: @Type@;
begin
Result := @Type@(inherited Last^);
end;
//------------------------------------------------------------------------------
Function @ClassName@.IndexOf(Item: @Type@): Integer;
begin
Result := inherited IndexOf(@Item);
end;
//------------------------------------------------------------------------------
Function @ClassName@.Add(Item: @Type@): Integer;
begin
Result := inherited Add(@Item);
end;
//------------------------------------------------------------------------------
procedure @ClassName@.Insert(Index: Integer; Item: @Type@);
begin
inherited Insert(Index,@Item);
end;
//------------------------------------------------------------------------------
Function @ClassName@.Remove(Item: @Type@): Integer;
begin
Result := inherited Remove(@Item);
end;
//------------------------------------------------------------------------------
Function @ClassName@.Extract(Item: @Type@): @Type@;
begin
Result := @Type@(inherited Extract(@Item)^);
end;
*******************************************************************************)
unit MemVector;
{$IFDEF FPC}
{$MODE Delphi}
{$DEFINE FPC_DisableWarns}
{$MACRO ON}
{$ENDIF}
interface
uses
Classes, AuxTypes, AuxClasses;
type
{===============================================================================
--------------------------------------------------------------------------------
TMemVector
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TMemVector - class declaration
===============================================================================}
TMemVector = class(TCustomListObject)
private
fItemSize: Integer;
fOwnsMemory: Boolean;
fMemory: Pointer;
fCapacity: Integer;
fCount: Integer;
fChangeCounter: Integer;
fChanged: Boolean;
fOnChange: TNotifyEvent;
protected
fTempItem: Pointer;
Function GetCapacity: Integer; override;
procedure SetCapacity(Value: Integer); override;
Function GetCount: Integer; override;
procedure SetCount(Value: Integer); override;
Function GetItemPtr(Index: Integer): Pointer; virtual;
procedure SetItemPtr(Index: Integer; Value: Pointer); virtual;
Function GetSize: TMemSize; virtual;
Function GetAllocatedSize: TMemSize; virtual;
Function CheckIndexAndRaise(Index: Integer; CallingMethod: String = 'CheckIndexAndRaise'): Boolean; virtual;
procedure RaiseError(const ErrorMessage: String; Values: array of const); overload; virtual;
procedure RaiseError(const ErrorMessage: String); overload; virtual;
Function GetNextItemPtr(ItemPtr: Pointer): Pointer; virtual;
procedure ItemInit(Item: Pointer); virtual;
procedure ItemFinal(Item: Pointer); virtual;
procedure ItemCopy(SrcItem,DstItem: Pointer); virtual;
Function ItemCompare(Item1,Item2: Pointer): Integer; virtual;
Function ItemEquals(Item1,Item2: Pointer): Boolean; virtual;
Function CompareItems(Index1,Index2: Integer): Integer; virtual;
procedure FinalizeAllItems; virtual;
procedure DoOnChange; virtual;
public
constructor Create(ItemSize: Integer); overload;
constructor Create(Memory: Pointer; Count: Integer; ItemSize: Integer); overload;
destructor Destroy; override;
procedure BeginChanging; virtual;
Function EndChanging: Integer; virtual;
Function LowIndex: Integer; override;
Function HighIndex: Integer; override;
Function First: Pointer; virtual;
Function Last: Pointer; virtual;
Function IndexOf(Item: Pointer): Integer; virtual;
Function Add(Item: Pointer): Integer; virtual;
procedure Insert(Index: Integer; Item: Pointer); virtual;
Function Remove(Item: Pointer): Integer; virtual;
Function Extract(Item: Pointer): Pointer; virtual;
procedure Delete(Index: Integer); virtual;
procedure Move(SrcIndex,DstIndex: Integer); virtual;
procedure Exchange(Index1,Index2: Integer); virtual;
procedure Reverse; virtual;
procedure Clear; virtual;
procedure Sort(Reversed: Boolean = False); virtual;
Function IsEqual(Vector: TMemVector): Boolean; virtual;
Function EqualsBinary(Vector: TMemVector): Boolean; virtual;
procedure Assign(Data: Pointer; Count: Integer; ManagedCopy: Boolean = False); overload; virtual;
procedure Assign(Vector: TMemVector; ManagedCopy: Boolean = False); overload; virtual;
procedure Append(Data: Pointer; Count: Integer; ManagedCopy: Boolean = False); overload; virtual;
procedure Append(Vector: TMemVector; ManagedCopy: Boolean = False); overload; virtual;
procedure SaveToStream(Stream: TStream); virtual;
procedure LoadFromStream(Stream: TStream); virtual;
procedure SaveToFile(const FileName: String); virtual;
procedure LoadFromFile(const FileName: String); virtual;
property Memory: Pointer read fMemory;
property Pointers[Index: Integer]: Pointer read GetItemPtr;
property ItemSize: Integer read fItemSize;
property OwnsMemory: Boolean read fOwnsMemory write fOwnsMemory;
property Size: TMemSize read GetSize;
property AllocatedSize: TMemSize read GetAllocatedSize;
property OnChange: TNotifyEvent read fOnChange write fOnChange;
end;
{===============================================================================
--------------------------------------------------------------------------------
TIntegerVector
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TIntegerVector - class declaration
===============================================================================}
TIntegerVector = class(TMemVector)
protected
Function GetItem(Index: Integer): Integer; virtual;
procedure SetItem(Index: Integer; Value: Integer); virtual;
Function ItemCompare(Item1,Item2: Pointer): Integer; override;
public
constructor Create; overload;
constructor Create(Memory: Pointer; Count: Integer); overload;
Function First: Integer; reintroduce;
Function Last: Integer; reintroduce;
Function IndexOf(Item: Integer): Integer; reintroduce;
Function Add(Item: Integer): Integer; reintroduce;
procedure Insert(Index: Integer; Item: Integer); reintroduce;
Function Remove(Item: Integer): Integer; reintroduce;
Function Extract(Item: Integer): Integer; reintroduce;
property Items[Index: Integer]: Integer read GetItem write SetItem; default;
end;
implementation
uses
SysUtils, StrRect, ListSorters;
{$IFDEF FPC_DisableWarns}
{$DEFINE FPCDWM}
{$DEFINE W4055:={$WARN 4055 OFF}} // Conversion between ordinals and pointers is not portable
{$DEFINE W5024:={$WARN 5024 OFF}} // Parameter "$1" not used
{$ENDIF}
{===============================================================================
--------------------------------------------------------------------------------
TMemVector
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TMemVector - class declaration
===============================================================================}
{-------------------------------------------------------------------------------
TMemVector - protected methods
-------------------------------------------------------------------------------}
Function TmemVector.GetCapacity: Integer;
begin
Result := fCapacity;
end;
//------------------------------------------------------------------------------
procedure TMemVector.SetCapacity(Value: Integer);
var
i: Integer;
begin
If fOwnsMemory then
begin
If (Value <> fCapacity) and (Value >= 0) then
begin
If Value < fCount then
For i := Value to HighIndex do
ItemFinal(GetItemPtr(i));
ReallocMem(fMemory,TMemSize(Value) * TMemSize(fItemSize));
fCapacity := Value;
If Value < fCount then
begin
fCount := Value;
DoOnChange;
end;
end;
end
else RaiseError('SetCapacity: Operation not allowed for not owned memory.');
end;
//------------------------------------------------------------------------------
Function TmemVector.GetCount: Integer;
begin
Result := fCount;
end;
//------------------------------------------------------------------------------
procedure TMemVector.SetCount(Value: Integer);
var
OldCount: Integer;
i: Integer;
begin
If fOwnsMemory then
begin
If (Value <> fCount) and (Value >= 0) then
begin
BeginChanging;
try
If Value > fCapacity then
SetCapacity(Value);
If Value > fCount then
begin
OldCount := fCount;
fCount := Value;
For i := OldCount to HighIndex do
ItemInit(GetItemPtr(i));
end
else
begin
For i := HighIndex downto Value do
ItemFinal(GetItemPtr(i));
fCount := Value;
end;
DoOnChange;
finally
EndChanging;
end;
end;
end
else RaiseError('SetCount: Operation not allowed for not owned memory.');
end;
//------------------------------------------------------------------------------
{$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF}
Function TMemVector.GetItemPtr(Index: Integer): Pointer;
begin
Result := nil;
If CheckIndex(Index) then
Result := Pointer(PtrUInt(fMemory) + PtrUInt(Index * fItemSize))
else
RaiseError('GetItemPtr: Index (%d) out of bounds.',[Index]);
end;
{$IFDEF FPCDWM}{$POP}{$ENDIF}
//------------------------------------------------------------------------------
procedure TMemVector.SetItemPtr(Index: Integer; Value: Pointer);
begin
If CheckIndex(Index) then
begin
System.Move(GetItemPtr(Index)^,fTempItem^,fItemSize);
System.Move(Value^,GetItemPtr(Index)^,fItemSize);
If not ItemEquals(fTempItem,Value) then DoOnChange;
end
else RaiseError('SetItemPtr: Index (%d) out of bounds.',[Index]);
end;
//------------------------------------------------------------------------------
Function TMemVector.GetSize: TMemSize;
begin
Result := TMemSize(fCount) * TMemSize(fItemSize);
end;
//------------------------------------------------------------------------------
Function TMemVector.GetAllocatedSize: TMemSize;
begin
Result := TMemSize(fCapacity) * TMemSize(fItemSize);
end;
//------------------------------------------------------------------------------
Function TMemVector.CheckIndexAndRaise(Index: Integer; CallingMethod: String = 'CheckIndexAndRaise'): Boolean;
begin
Result := CheckIndex(Index);
If not Result then
RaiseError('%s: Index (%d) out of bounds.',[CallingMethod,Index]);
end;
//------------------------------------------------------------------------------
procedure TMemVector.RaiseError(const ErrorMessage: String; Values: array of const);
begin
raise Exception.CreateFmt(Format('%s.%s',[Self.ClassName,ErrorMessage]),Values);
end;
//------------------------------------------------------------------------------
procedure TMemVector.RaiseError(const ErrorMessage: String);
begin
RaiseError(ErrorMessage,[]);
end;
//------------------------------------------------------------------------------
Function TMemVector.GetNextItemPtr(ItemPtr: Pointer): Pointer;
begin
{$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF}
Result := Pointer(PtrUInt(ItemPtr) + PtrUInt(fItemSize));
{$IFDEF FPCDWM}{$POP}{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure TMemVector.ItemInit(Item: Pointer);
begin
FillChar(Item^,fItemSize,0);
end;
//------------------------------------------------------------------------------
{$IFDEF FPCDWM}{$PUSH}W5024{$ENDIF}
procedure TMemVector.ItemFinal(Item: Pointer);
begin
// nothing to do here
end;
{$IFDEF FPCDWM}{$POP}{$ENDIF}
//------------------------------------------------------------------------------
procedure TMemVector.ItemCopy(SrcItem,DstItem: Pointer);
begin
System.Move(SrcItem^,DstItem^,fItemSize);
end;
//------------------------------------------------------------------------------
Function TMemVector.ItemCompare(Item1,Item2: Pointer): Integer;
begin
{$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF}
Result := Integer(PtrUInt(Item2) - PtrUInt(Item1));
{$IFDEF FPCDWM}{$POP}{$ENDIF}
end;
//------------------------------------------------------------------------------
Function TMemVector.ItemEquals(Item1,Item2: Pointer): Boolean;
begin
Result := ItemCompare(Item1,Item2) = 0;
end;
//------------------------------------------------------------------------------
Function TMemVector.CompareItems(Index1,Index2: Integer): Integer;
begin
Result := ItemCompare(GetItemPtr(Index1),GetItemPtr(Index2));
end;
//------------------------------------------------------------------------------
procedure TMemVector.FinalizeAllItems;
var
i: Integer;
begin
For i := LowIndex to HighIndex do
ItemFinal(GetItemPtr(i));
end;
//------------------------------------------------------------------------------
procedure TMemVector.DoOnChange;
begin
fChanged := True;
If (fChangeCounter <= 0) and Assigned(fOnChange) then
fOnChange(Self);
end;
{-------------------------------------------------------------------------------
TMemVector - public methods
-------------------------------------------------------------------------------}
constructor TMemVector.Create(ItemSize: Integer);
begin
inherited Create;
If ItemSize <= 0 then
RaiseError('Create: Size of the item must be larger than zero.');
fItemSize := ItemSize;
fOwnsMemory := True;
fMemory := nil;
fCapacity := 0;
fCount := 0;
fChangeCounter := 0;
fChanged := False;
fOnChange := nil;
GetMem(fTempItem,ItemSize);
end;
// --- --- --- --- --- --- --- --- --- --- --- --- ---
constructor TMemVector.Create(Memory: Pointer; Count: Integer; ItemSize: Integer);
begin
Create(ItemSize);
fOwnsMemory := False;
fMemory := Memory;
fCapacity := Count;
fCount := Count;
end;
//------------------------------------------------------------------------------
destructor TMemVector.Destroy;
begin
FreeMem(fTempItem,fItemSize);
If fOwnsMemory then
begin
FinalizeAllItems;
FreeMem(fMemory,TMemSize(fCapacity) * TMemSize(fItemSize));
end;
inherited;
end;
//------------------------------------------------------------------------------
procedure TMemVector.BeginChanging;
begin
If fChangeCounter <= 0 then
fChanged := False;
Inc(fChangeCounter);
end;
//------------------------------------------------------------------------------
Function TMemVector.EndChanging: Integer;
begin
Dec(fChangeCounter);
If fChangeCounter <= 0 then
begin
fChangeCounter := 0;
If fChanged and Assigned(fOnChange) then
fOnChange(Self);
fChanged := False;
end;
Result := fChangeCounter;
end;
//------------------------------------------------------------------------------
Function TMemVector.LowIndex: Integer;
begin
Result := 0;
end;
//------------------------------------------------------------------------------
Function TMemVector.HighIndex: Integer;
begin
Result := fCount - 1;
end;
//------------------------------------------------------------------------------
Function TMemVector.First: Pointer;
begin
Result := GetItemPtr(LowIndex);
end;
//------------------------------------------------------------------------------
Function TMemVector.Last: Pointer;
begin
Result := GetItemPtr(HighIndex);
end;
//------------------------------------------------------------------------------
Function TMemVector.IndexOf(Item: Pointer): Integer;
var
i: Integer;
begin
Result := -1;
For i := LowIndex to HighIndex do
If ItemEquals(Item,GetItemPtr(i)) then
begin
Result := i;
Exit;
end;
end;
//------------------------------------------------------------------------------
Function TMemVector.Add(Item: Pointer): Integer;
begin
Result := -1;
If fOwnsMemory then
begin
Grow;
Result := fCount;
Inc(fCount);
System.Move(Item^,GetItemPtr(Result)^,fItemSize);
DoOnChange;
end
else RaiseError('Add: Operation not allowed for not owned memory.');
end;
//------------------------------------------------------------------------------
procedure TMemVector.Insert(Index: Integer; Item: Pointer);
var
InsertPtr: Pointer;
begin
If fOwnsMemory then
begin
If CheckIndex(Index) then
begin
Grow;
InsertPtr := GetItemPtr(Index);
System.Move(InsertPtr^,GetNextItemPtr(InsertPtr)^,fItemSize * (fCount - Index));
System.Move(Item^,InsertPtr^,fItemSize);
Inc(fCount);
DoOnChange;
end
else
begin
If Index >= fCount then
Add(Item)
else
RaiseError('Insert: Index (%d) out of bounds.',[Index]);
end;
end
else RaiseError('Insert: Operation not allowed for not owned memory.');
end;
//------------------------------------------------------------------------------
Function TMemVector.Remove(Item: Pointer): Integer;
begin
Result := -1;
If fOwnsMemory then
begin
Result := IndexOf(Item);
If Result >= 0 then
Delete(Result);
end
else RaiseError('Remove: Operation not allowed for not owned memory.');
end;
//------------------------------------------------------------------------------
Function TMemVector.Extract(Item: Pointer): Pointer;
var
Index: Integer;
begin
Result := nil;
If fOwnsMemory then
begin
Index := IndexOf(Item);
If Index >= 0 then
begin
System.Move(GetItemPtr(Index)^,fTempItem^,fItemSize);
Delete(Index);
Result := fTempItem;
end
else RaiseError('Extract: Requested item not found.');
end
else RaiseError('Extract: Operation not allowed for not owned memory.');
end;
//------------------------------------------------------------------------------
procedure TMemVector.Delete(Index: Integer);
var
DeletePtr: Pointer;
begin
If fOwnsMemory then
begin
If CheckIndex(Index) then
begin
DeletePtr := GetItemPtr(Index);
ItemFinal(DeletePtr);
If Index < Pred(fCount) then
System.Move(GetNextItemPtr(DeletePtr)^,DeletePtr^,fItemSize * Pred(fCount - Index));
Dec(fCount);
Shrink;
DoOnChange;
end
else RaiseError('Delete: Index (%d) out of bounds.',[Index]);
end
else RaiseError('Delete: Operation not allowed for not owned memory.');
end;
//------------------------------------------------------------------------------
procedure TMemVector.Move(SrcIndex,DstIndex: Integer);
var
SrcPtr: Pointer;
DstPtr: Pointer;
begin
If CheckIndexAndRaise(SrcIndex,'Move') and CheckIndexAndRaise(DstIndex,'Move') then
If SrcIndex <> DstIndex then
begin
SrcPtr := GetItemPtr(SrcIndex);
DstPtr := GetItemPtr(DstIndex);
System.Move(SrcPtr^,fTempItem^,fItemSize);
If SrcIndex < DstIndex then
System.Move(GetNextItemPtr(SrcPtr)^,SrcPtr^,fItemSize * (DstIndex - SrcIndex))
else
System.Move(DstPtr^,GetNextItemPtr(DstPtr)^,fItemSize * (SrcIndex - DstIndex));
System.Move(fTempItem^,DstPtr^,fItemSize);
DoOnChange;
end;
end;
//------------------------------------------------------------------------------
procedure TMemVector.Exchange(Index1,Index2: Integer);
var
Idx1Ptr: Pointer;
Idx2Ptr: Pointer;
begin
If CheckIndexAndRaise(Index1,'Exchange') and CheckIndexAndRaise(Index2,'Exchange') then
If Index1 <> Index2 then
begin
Idx1Ptr := GetItemPtr(Index1);
Idx2Ptr := GetItemPtr(Index2);
System.Move(Idx1Ptr^,fTempItem^,fItemSize);
System.Move(Idx2Ptr^,Idx1Ptr^,fItemSize);
System.Move(fTempItem^,Idx2Ptr^,fItemSize);
DoOnChange;
end;
end;
//------------------------------------------------------------------------------
procedure TMemVector.Reverse;
var
i: Integer;
begin
If fCount > 1 then
begin
BeginChanging;
try
For i := LowIndex to Pred(fCount shr 1) do
Exchange(i,Pred(fCount - i));
DoOnChange;
finally
EndChanging;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TMemVector.Clear;
var
OldCount: Integer;
begin
OldCount := fCount;
If fOwnsMemory then
begin
FinalizeAllItems;
fCount := 0;
Shrink;
end
else
begin
fCapacity := 0;
fCount := 0;
fMemory := nil;
end;
If OldCount > 0 then
DoOnChange;
end;
//------------------------------------------------------------------------------
procedure TMemVector.Sort(Reversed: Boolean = False);
var
Sorter: TListQuickSorter;
begin
If fCount > 1 then
begin
BeginChanging;
try
Sorter := TListQuickSorter.Create(CompareItems,Exchange);
try
Sorter.Reversed := Reversed;
Sorter.Sort(LowIndex,HighIndex);
finally
Sorter.Free;
end;
DoOnChange;
finally
EndChanging;
end;
end;
end;
//------------------------------------------------------------------------------
Function TMemVector.IsEqual(Vector: TMemVector): Boolean;
var
i: Integer;
begin
Result := False;
If Vector is Self.ClassType then
begin
If Vector.Count = fCount then
begin
For i := LowIndex to HighIndex do
If not ItemEquals(GetItemPtr(i),Vector.Pointers[i]) then Exit;
Result := True;
end;
end
else RaiseError('IsEqual: Object is of incompatible class (%s).',[Vector.ClassName]);
end;
//------------------------------------------------------------------------------
Function TMemVector.EqualsBinary(Vector: TMemVector): Boolean;
var
i: PtrUInt;
begin
Result := False;
If Size = Vector.Size then
begin
If Size > 0 then
For i := 0 to Pred(Size) do
{$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF}
If PByte(PtrUInt(fMemory) + i)^ <> PByte(PtrUInt(Vector.Memory) + i)^ then Exit;
{$IFDEF FPCDWM}{$POP}{$ENDIF}
Result := True;
end;
end;
//------------------------------------------------------------------------------
procedure TMemVector.Assign(Data: Pointer; Count: Integer; ManagedCopy: Boolean = False);
var
i: Integer;
begin
If fOwnsMemory then
begin
BeginChanging;
try
FinalizeAllItems;
fCount := 0;
SetCapacity(Count);
fCount := Count;
If ManagedCopy then
For i := 0 to Pred(Count) do
{$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF}
ItemCopy(Pointer(PtrUInt(Data) + PtrUInt(i * fItemSize)),GetItemPtr(i))
{$IFDEF FPCDWM}{$POP}{$ENDIF}
else
If Count > 0 then
System.Move(Data^,fMemory^,Count * fItemSize);
DoOnChange;
finally
EndChanging;
end;
end
else RaiseError('Assign: Operation not allowed for not owned memory.');
end;
//------------------------------------------------------------------------------
procedure TMemVector.Assign(Vector: TMemVector; ManagedCopy: Boolean = False);
begin
If fOwnsMemory then
begin
If Vector is Self.ClassType then
Assign(Vector.Memory,Vector.Count,ManagedCopy)
else
RaiseError('Assign: Object is of incompatible class (%s).',[Vector.ClassName]);
end
else RaiseError('Assign: Operation not allowed for not owned memory.');
end;
//------------------------------------------------------------------------------
procedure TMemVector.Append(Data: Pointer; Count: Integer; ManagedCopy: Boolean = False);
var
i: Integer;
begin
If fOwnsMemory then
begin
BeginChanging;
try
If (fCount + Count) > fCapacity then
SetCapacity(fCount + Count);
fCount := fCount + Count;
If ManagedCopy then
For i := 0 to Pred(Count) do
{$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF}
ItemCopy(Pointer(PtrUInt(Data) + PtrUInt(i * fItemSize)),GetItemPtr((fCount - Count) + i))
{$IFDEF FPCDWM}{$POP}{$ENDIF}
else
If Count > 0 then
System.Move(Data^,GetItemPtr(fCount - Count)^,Count * fItemSize);
DoOnChange;
finally
EndChanging;
end;
end
else RaiseError('Append: Operation not allowed for not owned memory.');
end;
//------------------------------------------------------------------------------
procedure TMemVector.Append(Vector: TMemVector; ManagedCopy: Boolean = False);
begin
If fOwnsMemory then
begin
If Vector is Self.ClassType then
Append(Vector.Memory,Vector.Count,ManagedCopy)
else
RaiseError('Append: Object is of incompatible class (%s).',[Vector.ClassName]);
end
else RaiseError('Append: Operation not allowed for not owned memory.');
end;
//------------------------------------------------------------------------------
procedure TMemVector.SaveToStream(Stream: TStream);
begin
Stream.WriteBuffer(fMemory^,fCount * fItemSize);
end;
//------------------------------------------------------------------------------
procedure TMemVector.LoadFromStream(Stream: TStream);
begin
If fOwnsMemory then
begin
BeginChanging;
try
FinalizeAllItems;
fCount := 0;
SetCapacity(Integer((Stream.Size - Stream.Position) div fItemSize));
fCount := fCapacity;
Stream.ReadBuffer(fMemory^,fCount * fItemSize);
DoOnChange;
finally
EndChanging;
end;
end
else RaiseError('LoadFromStream: Operation not allowed for not owned memory.');
end;
//------------------------------------------------------------------------------
procedure TMemVector.SaveToFile(const FileName: String);
var
FileStream: TFileStream;
begin
FileStream := TFileStream.Create(StrToRTL(FileName),fmCreate or fmShareExclusive);
try
SaveToStream(FileStream);
finally
FileStream.Free;
end;
end;
//------------------------------------------------------------------------------
procedure TMemVector.LoadFromFile(const FileName: String);
var
FileStream: TFileStream;
begin
FileStream := TFileStream.Create(StrToRTL(FileName),fmOpenRead or fmShareDenyWrite);
try
LoadFromStream(FileStream);
finally
FileStream.Free;
end;
end;
{===============================================================================
--------------------------------------------------------------------------------
TIntegerVector
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TIntegerVector - class declaration
===============================================================================}
{-------------------------------------------------------------------------------
TIntegerVector - private methods
-------------------------------------------------------------------------------}
Function TIntegerVector.GetItem(Index: Integer): Integer;
begin
Result := Integer(GetItemPtr(Index)^);
end;
//------------------------------------------------------------------------------
procedure TIntegerVector.SetItem(Index: Integer; Value: Integer);
begin
SetItemPtr(Index,@Value);
end;
//------------------------------------------------------------------------------
Function TIntegerVector.ItemCompare(Item1,Item2: Pointer): Integer;
begin
Result := Integer(Item2^) - Integer(Item1^);
end;
{-------------------------------------------------------------------------------
TIntegerVector - public methods
-------------------------------------------------------------------------------}
constructor TIntegerVector.Create;
begin
inherited Create(SizeOf(Integer));
end;
// --- --- --- --- --- --- --- --- --- --- --- --- ---
constructor TIntegerVector.Create(Memory: Pointer; Count: Integer);
begin
inherited Create(Memory,Count,SizeOf(Integer));
end;
//------------------------------------------------------------------------------
Function TIntegerVector.First: Integer;
begin
Result := Integer(inherited First^);
end;
//------------------------------------------------------------------------------
Function TIntegerVector.Last: Integer;
begin
Result := Integer(inherited Last^);
end;
//------------------------------------------------------------------------------
Function TIntegerVector.IndexOf(Item: Integer): Integer;
begin
Result := inherited IndexOf(@Item);
end;
//------------------------------------------------------------------------------
Function TIntegerVector.Add(Item: Integer): Integer;
begin
Result := inherited Add(@Item);
end;
//------------------------------------------------------------------------------
procedure TIntegerVector.Insert(Index: Integer; Item: Integer);
begin
inherited Insert(Index,@Item);
end;
//------------------------------------------------------------------------------
Function TIntegerVector.Remove(Item: Integer): Integer;
begin
Result := inherited Remove(@Item);
end;
//------------------------------------------------------------------------------
Function TIntegerVector.Extract(Item: Integer): Integer;
begin
Result := Integer(inherited Extract(@Item)^);
end;
end.
|
unit NormalizeTest;
interface
uses
DUnitX.TestFramework,
uIntX;
type
[TestFixture]
TNormalizeTest = class(TObject)
public
[Test]
procedure Zero();
[Test]
procedure Simple();
end;
implementation
[Test]
procedure TNormalizeTest.Zero();
var
int1: TIntX;
begin
int1 := TIntX.Create(7) - 7;
int1.Normalize();
Assert.IsTrue(int1 = 0);
end;
[Test]
procedure TNormalizeTest.Simple();
var
int1: TIntX;
begin
int1 := TIntX.Create(8);
int1 := int1 * int1;
int1.Normalize();
Assert.IsTrue(int1 = 64);
end;
initialization
TDUnitX.RegisterTestFixture(TNormalizeTest);
end.
|
unit fre_base_client;
{
(§LIC)
(c) Autor,Copyright
Dipl.Ing.- Helmut Hartl, Dipl.Ing.- Franz Schober, Dipl.Ing.- Christian Koch
FirmOS Business Solutions GmbH
www.openfirmos.org
New Style BSD Licence (OSI)
Copyright (c) 2001-2013, FirmOS Business Solutions GmbH
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 the <FirmOS Business Solutions GmbH> 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 HOLDER 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.
(§LIC_END)
}
{$mode objfpc}{$H+}
{$codepage utf8}
{$modeswitch nestedprocvars}
//TODO: Expire pending commands
interface
uses
Classes, SysUtils,FRE_APS_INTERFACE,FOS_FCOM_TYPES,FRE_SYS_BASE_CS,FRE_DB_INTERFACE,FOS_TOOL_INTERFACES,
FRE_SYSTEM,baseunix,fre_diff_transport,fre_db_core;
var G_CONNREFUSED_TO : integer = 5;
G_RETRY_TO : integer = 5;
type
{ TFRE_BASE_CLIENT }
TFRE_BASE_CLIENT=class(TFRE_DB_Base,IFRE_FLEX_CLIENT)
private
type
TBC_ClientState = (csUnknown,csWaitConnect,csConnected,csTimeoutWait,csSETUPSESSION);
TSUB_FEED_CSTATE = (sfc_NOT_CONNECTED,sfc_TRYING,sfc_OK,sfc_ErrorWait);
TSUB_CMD_STATE = (cs_READ_LEN,cs_READ_DATA);
TDispatch_Continuation = record
CID : Qword;
Contmethod : TFRE_DB_CONT_HANDLER;
ExpiredAt : TFRE_DB_DateTime64;
end;
TSUB_FEED_STATE=class
FId : ShortString;
FConnectState : TSUB_FEED_CSTATE;
FCMDState : TSUB_CMD_STATE;
FLen : Cardinal;
FData : Pointer;
FSpecfile : Shortstring;
FIp : Shortstring;
FPort : Shortstring;
FErrorTimeout : Integer;
end;
var
FApps : IFRE_DB_Object;
FTimeout : integer;
fMySessionID : String;
FClientState : TBC_ClientState;
FContinuationArray : Array [0..cFRE_DB_MAX_PENDING_CLIENT_REQUESTS] of TDispatch_Continuation;
FContinuationLock : IFOS_LOCK;
FBaseconnection : TFRE_CLIENT_BASE_CONNECTION;
fsendcmd_id : QWord;
FRifClassList : TFPList;
FChannel : IFRE_APSC_CHANNEL;
FChannelTimer : IFRE_APSC_TIMER;
FClientStateLock : IFOS_LOCK;
FSubFeedLock : IFOS_LOCK;
FSubfeedlist : TList;
FCompleteList : TStringList;
procedure ChannelEvent (const channel : IFRE_APSC_CHANNEL ; const event : TAPSC_ChannelState ; const errorstring: string; const errorcode: NativeInt);
procedure CCB_SessionSetup (const DATA: IFRE_DB_Object; const status: TFRE_DB_COMMAND_STATUS; const error_txt: string);
procedure ChannelDisco (const channel : IFRE_APSC_CHANNEL);
procedure ChannelRead (const channel : IFRE_APSC_CHANNEL);
procedure _SendServerCommand (const base_connection: TFRE_CLIENT_BASE_CONNECTION; const InvokeClass, InvokeMethod: String; const uidpath: Array of TFRE_DB_GUID; const DATA: IFRE_DB_Object; const ContinuationCB: TFRE_DB_CONT_HANDLER=nil; const timeout: integer=5000);
procedure MyStateCheckTimer (const TIM : IFRE_APSC_TIMER ; const flag1,flag2 : boolean); // Timout & CMD Arrived & Answer Arrived
procedure MySubFeederStateTimer (const TIM : IFRE_APSC_TIMER ; const flag1,flag2 : boolean);
procedure ChannelTimerCB (const TIM : IFRE_APSC_TIMER ; const flag1,flag2 : boolean);
procedure MyCommandAnswerArrived (const sender:TObject;const cmd:IFRE_DB_COMMAND);
procedure MyRequestArrived (const sender:TObject;const cmd:IFRE_DB_COMMAND);
procedure MyHandleSignals (const signal : NativeUint);
procedure SubFeederNewSocket (const channel : IFRE_APSC_CHANNEL ; const channel_event : TAPSC_ChannelState ; const errorstring: string; const errorcode: NativeInt);
procedure SubfeederReadClientChannel (const channel : IFRE_APSC_CHANNEL);
procedure SubfeederDiscoClientChannel (const channel : IFRE_APSC_CHANNEL);
procedure HandleContinuationTimeouts ;
protected
procedure Terminate; virtual;
procedure ReInit; virtual;
procedure User1; virtual;
procedure User2; virtual;
procedure Interrupt; virtual;
procedure MyJobInspectCallback (const job : TFRE_DB_JOB ; const has_failed : boolean); virtual ; { this is stateful, eg. gets called multiple times per job }
public
constructor Create ;
destructor Destroy ; override ;
procedure Setup ; virtual;
procedure MyRegisterClasses ; virtual;
procedure RegisterSupportedRifClass(const rif_class : TFRE_DB_BaseClass);
function Get_AppClassAndUid (const appkey : string ; out app_classname : TFRE_DB_String ; out uid: TFRE_DB_Guid) : boolean;
function SendServerCommand (const InvokeClass,InvokeMethod : String;const uidpath:Array of TFRE_DB_GUID;const DATA: IFRE_DB_Object;const ContinuationCB : TFRE_DB_CONT_HANDLER=nil;const timeout:integer=5000) : boolean;
function AnswerSyncCommand (const command_id : QWord ; const data : IFRE_DB_Object) : boolean;
function AnswerSyncError (const command_id : QWord ; const error : TFRE_DB_String) : boolean;
procedure MySessionEstablished (const chanman : IFRE_APSC_CHANNEL_MANAGER); virtual;
procedure MySessionDisconnected (const chanman : IFRE_APSC_CHANNEL_MANAGER); virtual;
procedure MySessionSetupFailed (const reason : string); virtual;
procedure MyInitialize ; virtual;
procedure MyFinalize ; virtual;
procedure MyConnectionTimer ; virtual; { runs in sync with the connected MWS channel }
procedure QueryUserPass (out user,pass:string);virtual;
procedure RegisterRemoteMethods (var remote_method_array : TFRE_DB_RemoteReqSpecArray); virtual;
procedure WorkRemoteMethods (const rclassname,rmethodname : TFRE_DB_NameType ; const command_id : Qword ; const input : IFRE_DB_Object ; const cmd_type : TFRE_DB_COMMANDTYPE); virtual;
function GetCurrentChanManLocked : IFRE_APSC_CHANNEL_MANAGER;
procedure UnlockCurrentChanMan ;
procedure AddSubFeederEventViaUX (const special_id : Shortstring);
procedure AddSubFeederEventViaTCP (const ip,port,special_id : Shortstring);
procedure SubfeederEvent (const id:string; const dbo:IFRE_DB_Object);virtual;
end;
implementation
{ TFRE_BASE_CLIENT }
procedure TFRE_BASE_CLIENT.ChannelEvent(const channel: IFRE_APSC_CHANNEL; const event: TAPSC_ChannelState; const errorstring: string; const errorcode: NativeInt);
var data : IFRE_DB_Object;
configmachine : IFRE_DB_Object;
fuser : string;
fpass : string;
cstate : TAPSC_ChannelState;
begin
FClientStateLock.Acquire; // self
try
//writeln('GOT A NEW CHANNEL ON CM_',channel.cs_GetChannelManager.GetID,' ',channel.ch_GetVerboseDesc,' ',event,' ',channel.ch_GetHandleKey);
if assigned(FChannel) then
GFRE_BT.CriticalAbort('I SHOULD NOT HAVE A CHANNEL HERE (B)!');
case event of
ch_ErrorOccured:
begin
channel.cs_Finalize;
end;
ch_NEW_CS_CONNECTED:
begin
GFRE_DBI.LogInfo(dblc_FLEXCOM,'CONNECT OK MACHINE [%s/%s] on [%s]',[cFRE_MACHINE_NAME,cFRE_MACHINE_UID.AsHexString,channel.CH_GetVerboseDesc]);
FClientState := csSETUPSESSION;
FBaseconnection := TFRE_CLIENT_BASE_CONNECTION.Create(Channel);
FBaseconnection.OnNewCommandAnswerHere := @MyCommandAnswerArrived;
FBaseconnection.OnNewServerRequest := @MyRequestArrived;
data := GFRE_DBI.NewObject;
configmachine := GFRE_DBI.NewObject;
data.Field('SESSION_ID').AsString:=fMySessionID;
data.Field('MACHINECFG').AsObject:=configmachine;
configmachine.Field('MACHINENAME').AsString := cFRE_MACHINE_NAME;
configmachine.Field('MACHINEMAC').AsString := cFRE_MACHINE_MAC;
configmachine.Field('MACHINEUID').AsGUID := cFRE_MACHINE_UID;
if assigned(cFRE_MACHINE_CONFIG) then
configmachine.Field('MACHINECFG').AsObject := (TObject(cFRE_MACHINE_CONFIG) as TFRE_DB_Object).CloneToNewObject;
if cFRE_CONFIG_MODE then
begin
configmachine.Field('STANDALONE').AsBoolean := true;
end
else
begin
configmachine.Field('STANDALONE').AsBoolean := true; { FIXXME - PXE BOOT}
end;
QueryUserPass(fuser,fpass);
if fuser<>'' then begin
data.Field('USER').AsString:=fuser;
data.Field('PASS').AsString:=fpass;
end;
FChannel := channel;
_SendServerCommand(FBaseconnection,'FIRMOS','INIT',[],data,@CCB_SessionSetup,5000); // Pending Q
channel.CH_Enable_Reading;
end;
ch_NEW_CHANNEL_FAILED:
begin
GFRE_DBI.LogInfo(dblc_FLEXCOM,'CONNECT FAILED MACHINE [%s/%s] ERR [%s] on [%s]',[cFRE_MACHINE_NAME,cFRE_MACHINE_UID.AsHexString,errorstring,channel.CH_GetVerboseDesc]);
FTimeout := G_CONNREFUSED_TO;
FClientState := csTimeoutwait;
channel.cs_Finalize;
end
else
GFRE_BT.CriticalAbort('unexpected channel event' +inttostr(ord(event)));
end;
finally
FClientStateLock.Release;
end;
end;
procedure TFRE_BASE_CLIENT.CCB_SessionSetup(const DATA: IFRE_DB_Object; const status: TFRE_DB_COMMAND_STATUS; const error_txt: string);
var arr : TFRE_DB_RemoteReqSpecArray;
i : NativeInt;
regdata : IFRE_DB_Object;
fmuid : IFRE_DB_Field;
begin
FClientStateLock.Acquire;
try
case status of
cdcs_OK: begin
if FClientState = csSETUPSESSION then begin
if (data.FieldExists('LOGIN_OK') and (data.Field('LOGIN_OK').AsBoolean=true)) then
begin
GFRE_DBI.LogInfo(dblc_FLEXCOM,'SESSION SETUP OK : SESSION [%s] MACHINE [%s/%s]',[fMySessionID,cFRE_MACHINE_NAME,cFRE_MACHINE_UID.AsHexString]);
FClientState := csConnected;
FApps := data.Field('APPS').AsObject.CloneToNewObject();
//writeln('GOT APPS : ',FApps.DumpToString());
RegisterRemoteMethods(arr);
if Length(arr)>0 then
begin
regdata := GFRE_DBI.NewObject;
regdata.Field('mc').AsUInt16 := Length(arr);
for i := 0 to length(arr)-1 do
begin
regdata.Field('cl'+IntToStr(i)).AsString := arr[i].classname;
regdata.Field('mn'+IntToStr(i)).AsString := arr[i].methodname;
regdata.Field('ir'+IntToStr(i)).AsString := arr[i].invokationright;
end;
SendServerCommand('FIRMOS','REG_REM_METH',[],regdata);
end;
MySessionEstablished(FChannel.cs_GetChannelManager);
end
else
begin
GFRE_DBI.LogInfo(dblc_FLEXCOM,'SESSION SETUP FAILED : SESSION [%s]',[fMySessionID]);
if assigned(FApps) then
try
FApps.Finalize;
except
writeln('*** APP FINALIZE EXCEPTION');
end;
FApps:=nil;
FTimeout := G_RETRY_TO;
FClientState := csTimeoutWait;
fMySessionID := 'NEW';
FChannel.cs_Finalize;
FChannel:=nil;
try
writeln('SETUP FAIL',data.DumpToString());
MySessionSetupFailed(data.Field('LOGIN_TXT').AsString);
except
end;
end;
end else begin
//Connection failed due to an intermediate failure
writeln('CCB_SetupSession FAILED ????');
FClientState := csTimeoutWait;
fMySessionID := 'NEW';
FChannel.cs_Finalize;
FChannel:=nil;
exit;
end;
end;
cdcs_TIMEOUT: ;
cdcs_ERROR: begin
writeln('Session Setup Error - Server Returned Error: ',error_txt);
writeln(' ' ,FTimeout,' ',FClientState);
FTimeout := G_RETRY_TO;
FClientState := csTimeoutWait;
fMySessionID := 'NEW';
FClientState := csTimeoutWait;
FChannel:=nil;
end;
end;
finally
FClientStateLock.Release;
end;
end;
procedure TFRE_BASE_CLIENT.ChannelDisco(const channel: IFRE_APSC_CHANNEL);
begin
FClientStateLock.Acquire;
try
//writeln('CHANNEL ',channel.GetVerboseDesc,' DISCONNECT CM_' ,channel.GetChannelManager.GetID);
if FClientState=csConnected then
MySessionDisconnected(FChannel.cs_GetChannelManager);
try
if assigned(FBaseconnection) then
begin
FBaseconnection.Finalize;
FBaseconnection := nil;
end;
if FClientState=csConnected then
FClientState := csUnknown
else
FClientState := csTimeoutWait
finally
FChannel := nil;
end;
finally
FClientStateLock.Release;
end;
end;
procedure TFRE_BASE_CLIENT.ChannelRead(const channel: IFRE_APSC_CHANNEL);
begin
FBaseconnection.Handler(channel);
end;
procedure TFRE_BASE_CLIENT._SendServerCommand(const base_connection: TFRE_CLIENT_BASE_CONNECTION; const InvokeClass, InvokeMethod: String; const uidpath: array of TFRE_DB_GUID; const DATA: IFRE_DB_Object; const ContinuationCB: TFRE_DB_CONT_HANDLER; const timeout: integer);
var i : integer;
send_ok : boolean;
uip : TFRE_DB_GUIDArray;
begin
FContinuationLock.Acquire;
try
if assigned(ContinuationCB) then begin
send_ok := false;
for i := 0 to high(FContinuationArray) do begin
if FContinuationArray[i].CID=0 then begin
FContinuationArray[i].CID := fsendcmd_id;
FContinuationArray[i].Contmethod := ContinuationCB;
FContinuationArray[i].ExpiredAt := GFRE_BT.Get_DBTimeNow+timeout;
send_ok := true;
break;
end;
end;
end else begin
send_ok := true;
end;
finally
FContinuationLock.Release;
end;
if send_ok then begin
SetLength(uip,Length(uidpath));
for i:=0 to high(uidpath) do
uip[i] := uidpath[i];
base_connection.InvokeServerCommand(InvokeClass,InvokeMethod,uip,data,fsendcmd_id,ContinuationCB=nil);
inc(fsendcmd_id);
end else begin
raise EFRE_DB_Exception.Create(edb_ERROR,'BASE/CLIENT TOO MUCH PENDING C-S Commands !');
end;
end;
procedure TFRE_BASE_CLIENT.MyStateCheckTimer(const TIM: IFRE_APSC_TIMER; const flag1, flag2: boolean);
procedure _HandleClientStatechanges;
begin
FClientStateLock.Acquire;
try
if (flag1=false) and (flag2=false) then
begin
case FClientState of
csUnknown: begin
FClientState:=csWaitConnect;
if Assigned(FChannel) then
GFRE_BT.CriticalAbort('SHOULD NOT HAVE A CHANNEL HERE!');
if cFRE_MWS_IP<>'' then
begin
GFRE_SC.AddClient_TCP(cFRE_MWS_IP,'44001','FEED',true,nil,@ChannelEvent,@ChannelRead,@ChannelDisco)
end
else
if cFRE_MWS_UX<>'' then
GFRE_SC.AddClient_UX(cFRE_MWS_UX,'FEED',true,nil,@ChannelEvent,@ChannelRead,@ChannelDisco)
else
GFRE_SC.AddClient_TCP('0.0.0.0','44001','FEED',true,nil,@ChannelEvent,@ChannelRead,@ChannelDisco)
end;
csWaitConnect: begin
end;
csConnected: begin
end;
csTimeoutWait:begin
dec(FTimeout);
if FTimeout<=0 then begin
FClientState:=csUnknown;
end;
end;
end;
end;
finally
FClientStateLock.Release;
end;
end;
begin
_HandleClientStatechanges;
end;
procedure TFRE_BASE_CLIENT.MySubFeederStateTimer(const TIM: IFRE_APSC_TIMER; const flag1, flag2: boolean);
var i : NativeInt;
subs : TSUB_FEED_STATE;
begin
FSubFeedLock.Acquire;
try
for i := 0 to FSubfeedlist.Count-1 do
begin
subs := TSUB_FEED_STATE(FSubfeedlist[i]);
case subs.FConnectState of
sfc_NOT_CONNECTED:
begin // Start a client
subs.FConnectState:=sfc_TRYING;
if (subs.FSpecfile<>'') then
begin
if FileExists(subs.FSpecfile) then
GFRE_SC.AddClient_UX(subs.FSpecfile,inttostr(i),true,nil,@SubFeederNewSocket,@SubfeederReadClientChannel,@SubfeederDiscoClientChannel)
end
else
GFRE_SC.AddClient_TCP(subs.FIp,subs.FPort,inttostr(i),true,nil,@SubFeederNewSocket,@SubfeederReadClientChannel,@SubfeederDiscoClientChannel);
end;
sfc_TRYING: ; // do nothing
sfc_OK: ; // do nothing
sfc_ErrorWait:
begin
dec(subs.FErrorTimeout);
if subs.FErrorTimeout<=0 then
subs.FConnectState:=sfc_NOT_CONNECTED;
end;
end;
end;
finally
FSubFeedLock.Release;
end;
end;
procedure TFRE_BASE_CLIENT.ChannelTimerCB(const TIM: IFRE_APSC_TIMER; const flag1, flag2: boolean);
begin
MyConnectionTimer;
HandleContinuationTimeouts;
end;
procedure TFRE_BASE_CLIENT.MyCommandAnswerArrived(const sender: TObject; const cmd: IFRE_DB_COMMAND);
var i : integer;
answer_matched : boolean;
contmethod : TFRE_DB_CONT_HANDLER;
status : TFRE_DB_COMMAND_STATUS;
data : IFRE_DB_Object;
begin
try
answer_matched:=false;
FContinuationLock.Acquire;
try
for i:=0 to high(FContinuationArray) do begin
if cmd.CommandID = FContinuationArray[i].CID then begin
try
if now <= FContinuationArray[i].ExpiredAt then
begin
answer_matched := true;
contmethod := FContinuationArray[i].Contmethod;
data := cmd.CheckoutData;
case cmd.CommandType of
fct_SyncRequest: GFRE_BT.CriticalAbort('LOGIC: ANSWER CANNOT BE A SYNC REQUEST');
fct_SyncReply: status := cdcs_OK;
fct_Error: status := cdcs_ERROR;
end;
try
contmethod(data,status,cmd.ErrorText);
finally
data.Finalize;
end;
end;
finally
FContinuationArray[i].ExpiredAt:=0;
FContinuationArray[i].CID:=0; // mark slot free
FContinuationArray[i].Contmethod := nil;
end;
break;
end;
end;
finally
FContinuationLock.Release;
end;
if not answer_matched then
GFRE_LOG.Log('GOT ANSWER FOR UNKNOWN COMMAND/TIMEOUT CID=%d',[CMD.CommandID],catError);
finally
cmd.Finalize;
end;
end;
procedure TFRE_BASE_CLIENT.MyRequestArrived(const sender: TObject; const cmd: IFRE_DB_COMMAND);
begin
try
WorkRemoteMethods(cmd.InvokeClass,cmd.InvokeMethod,cmd.CommandID,cmd.CheckoutData,cmd.CommandType);
finally
CMD.Finalize;
end;
end;
procedure TFRE_BASE_CLIENT.MyHandleSignals(const signal: NativeUint);
begin
case signal of
SIGHUP : ReInit;
SIGTERM : Terminate;
SIGINT : Interrupt;
SIGUSR1 : User1;
SIGUSR2 : USer2;
end;
end;
procedure TFRE_BASE_CLIENT.MyRegisterClasses;
begin
RegisterSupportedRifClass(TFRE_DB_TIMERTEST_JOB);
end;
procedure TFRE_BASE_CLIENT.RegisterSupportedRifClass(const rif_class: TFRE_DB_BaseClass);
begin
FRifClassList.Add(rif_class);
end;
procedure TFRE_BASE_CLIENT.SubFeederNewSocket(const channel: IFRE_APSC_CHANNEL; const channel_event: TAPSC_ChannelState; const errorstring: string; const errorcode: NativeInt);
var subs : TSUB_FEED_STATE;
id : NativeInt;
begin
if channel_event=ch_NEW_CS_CONNECTED then
begin
FSubFeedLock.Acquire;
try
id := StrToInt(channel.CH_GetID);
subs := TSUB_FEED_STATE(FSubfeedlist[id]);
subs.FConnectState := sfc_OK;
subs.FCMDState := cs_READ_LEN;
channel.CH_Enable_Reading;
finally
FSubFeedLock.Release;
end;
end
else
begin
id := StrToInt(channel.CH_GetID);
subs := TSUB_FEED_STATE(FSubfeedlist[id]);
subs.FConnectState := sfc_ErrorWait;
subs.FErrorTimeout := G_CONNREFUSED_TO;
channel.cs_Finalize;
end;
end;
procedure TFRE_BASE_CLIENT.SubfeederReadClientChannel(const channel: IFRE_APSC_CHANNEL);
var subs : TSUB_FEED_STATE;
id : NativeInt;
len : cardinal;
fcont : boolean;
dbo : IFRE_DB_Object;
begin
FSubFeedLock.Acquire;
try
id := StrToInt(channel.CH_GetID);
subs := TSUB_FEED_STATE(FSubfeedlist[id]);
repeat
fcont := false;
case subs.FCMDState of
cs_READ_LEN:
begin
if channel.CH_GetDataCount>=4 then
begin
channel.CH_ReadBuffer(@subs.FLen,4);
fcont := true;
getmem(subs.FData,subs.FLen);
subs.FCMDState:=cs_READ_DATA;
end;
end;
cs_READ_DATA:
begin
if channel.CH_GetDataCount>=subs.FLen then
begin
channel.CH_ReadBuffer(subs.FData,subs.FLen);
fcont := true;
try
try
dbo := GFRE_DBI.CreateFromMemory(subs.FData);
try
SubfeederEvent(subs.FId,dbo);
except on e:exception do
begin
writeln('Failure in Subfeeder event processing '+e.Message);
end;
end;
finally
Freemem(subs.FData);
subs.FData:=nil;
if assigned(dbo) then
dbo.Finalize;
end;
except on e:exception do
begin
writeln('SUB CHANNEL READ FAILED ',e.Message);
channel.cs_Finalize;
subs.FConnectState := sfc_NOT_CONNECTED;
end;
end;
subs.FCMDState := cs_READ_LEN;
end;
end;
end;
until fcont=false;
finally
FSubFeedLock.Release;
end;
end;
procedure TFRE_BASE_CLIENT.SubfeederDiscoClientChannel(const channel: IFRE_APSC_CHANNEL);
var subs : TSUB_FEED_STATE;
id : NativeInt;
begin
FSubFeedLock.Acquire;
try
id := StrToInt(channel.CH_GetID);
subs := TSUB_FEED_STATE(FSubfeedlist[id]);
writeln('SUBFEEER DISCO :: ',id,' ',subs.FConnectState);
if subs.FCMDState=cs_READ_DATA then
begin
if assigned(subs.FData) then
begin
writeln('****************** SUBSUBFEEDER : Disconnected while reading data!');
Freemem(subs.FData);
end;
subs.FData := nil;
end;
subs.FConnectState := sfc_NOT_CONNECTED;
finally
FSubFeedLock.Release;
end;
end;
procedure TFRE_BASE_CLIENT.HandleContinuationTimeouts;
var i : NativeInt;
now : TFRE_DB_DateTime64;
contmethod : TFRE_DB_CONT_HANDLER;
begin
now := GFRE_BT.Get_DBTimeNow;
FContinuationLock.Acquire;
try
for i := 0 to high(FContinuationArray) do
if (FContinuationArray[i].CID<>0)
and (now > FContinuationArray[i].ExpiredAt) then
begin
contmethod := FContinuationArray[i].Contmethod;
FContinuationArray[i].CID:=0; // mark slot free
FContinuationArray[i].Contmethod:=nil;
FContinuationArray[i].ExpiredAt:=0;
try
contmethod(nil,cdcs_TIMEOUT,'TIMEOUT');
except
on e:Exception do
begin
GFRE_DB.LogError(dblc_FLEXCOM,'CONTINUATION TIMEOUT METHOD FAILED [%s]',[e.Message]);
end;
end;
end;
finally
FContinuationLock.Release;
end;
end;
procedure TFRE_BASE_CLIENT.MyJobInspectCallback(const job: TFRE_DB_JOB; const has_failed: boolean);
begin
end;
procedure TFRE_BASE_CLIENT.Terminate;
begin
writeln('SIGNAL TERMINATE');
GFRE_SC.RequestTerminate;
end;
procedure TFRE_BASE_CLIENT.ReInit;
begin
writeln('SIGNAL HANGUP');
end;
procedure TFRE_BASE_CLIENT.User1;
begin
writeln('SIGNAL USER1');
end;
procedure TFRE_BASE_CLIENT.User2;
begin
writeln('SIGNAL USER2');
end;
procedure TFRE_BASE_CLIENT.Interrupt;
begin
if G_NO_INTERRUPT_FLAG THEN
exit;
writeln('INTERRUPT');
GFRE_SC.RequestTerminate;
end;
constructor TFRE_BASE_CLIENT.Create;
begin
inherited;
FClientState := csUnknown;
fsendcmd_id := 1;
fMySessionID := 'NEW';
FChannel := nil;
GFRE_TF.Get_Lock(FClientStateLock);
GFRE_TF.Get_Lock(FSubFeedLock);
GFRE_TF.Get_Lock(FContinuationLock);
FSubfeedlist := TList.Create;
FRifClassList := TFPList.Create;
FCompleteList := TStringList.Create;
end;
destructor TFRE_BASE_CLIENT.Destroy;
var i: NativeInt;
begin
MyFinalize;
if assigned(FBaseconnection) then begin
FBaseconnection.Finalize;
end;
if assigned(FApps) then begin
FApps.Finalize;
end;
FClientStateLock.Finalize;
FSubFeedLock.Finalize;
for i:=0 to FSubfeedlist.Count-1 do
begin
TSUB_FEED_STATE(FSubfeedlist[i]).free;
end;
FSubfeedlist.Free;
FRifClassList.Free;
FCompleteList.Free;
inherited Destroy;
end;
procedure TFRE_BASE_CLIENT.Setup;
begin
GFRE_SC.SetSignalCB(@MyHandleSignals);
MyInitialize;
if cFRE_MACHINE_NAME='' then
GFRE_BT.CriticalAbort('no MACHINE NAME set / NAME entry missing in subsection [MACHINE] in .ini File / or startparameter --machine=<> missing ');
if cFRE_MACHINE_MAC='' then
GFRE_BT.CriticalAbort('no MACHINE MAC set / MAC entry missing in subsection [MACHINE] in .ini File / or startparameter --mac=<> missing ');
if not FREDB_CheckMacAddress(cFRE_MACHINE_MAC) then
GFRE_BT.CriticalAbort('mac address format invalid use a contiguos hexstring or a colon seperated string invalid [%s]',[cFRE_MACHINE_MAC]);
if cFRE_MACHINE_UID=CFRE_DB_NullGUID then
GFRE_BT.CriticalAbort('no MACHINE UID set !');
{ Start (!) timers after initialize }
GFRE_SC.AddDefaultGroupTimer('F_STATE',1000,@MyStateCheckTimer,true);
GFRE_SC.AddDefaultGroupTimer('F_SUB_STATE',1000,@MySubFeederStateTimer,true);
end;
function TFRE_BASE_CLIENT.Get_AppClassAndUid(const appkey: string; out app_classname: TFRE_DB_String; out uid: TFRE_DB_Guid): boolean;
begin
if FApps.FieldExists(appkey) then begin
app_classname := FApps.Field(appkey).AsObject.Field('CLASS').AsString;
uid := FApps.Field(appkey).AsObject.Field('UID').AsGUID;
result := true;
end else begin
result := false;
end;
end;
procedure TFRE_BASE_CLIENT.MyInitialize;
begin
end;
procedure TFRE_BASE_CLIENT.MyFinalize;
begin
end;
procedure TFRE_BASE_CLIENT.MyConnectionTimer;
begin
end;
procedure TFRE_BASE_CLIENT.QueryUserPass(out user, pass: string);
begin
user := '';
pass := '';
end;
procedure TFRE_BASE_CLIENT.RegisterRemoteMethods(var remote_method_array: TFRE_DB_RemoteReqSpecArray);
var rem_methods : TFRE_DB_StringArray;
i,j : nativeInt;
rc : TFRE_DB_BaseClass;
lastix : NativeInt;
begin
rem_methods := Get_DBI_RemoteMethods;
SetLength(remote_method_array,Length(rem_methods));
for i:=0 to high(rem_methods) do
begin
remote_method_array[i].classname := uppercase(ClassName);
remote_method_array[i].methodname := UpperCase(rem_methods[i]);
remote_method_array[i].invokationright := '$REMIC_'+remote_method_array[i].classname+'.'+remote_method_array[i].methodname;
end;
for i:= 0 to FRifClassList.Count-1 do
begin
rem_methods := TFRE_DB_BaseClass(FRifClassList[i]).Get_DBI_RifMethods;
lastix := Length(remote_method_array);
SetLength(remote_method_array,Length(remote_method_array)+Length(rem_methods));
for j := 0 to high(rem_methods) do
begin
remote_method_array[lastix+j].classname := uppercase(TFRE_DB_BaseClass(FRifClassList[i]).Classname);
remote_method_array[lastix+j].methodname := UpperCase(rem_methods[j]);
remote_method_array[lastix+j].invokationright := '$RIFIC_'+remote_method_array[lastix+j].classname+'.'+remote_method_array[lastix+j].methodname;
end;
end;
end;
procedure TFRE_BASE_CLIENT.WorkRemoteMethods(const rclassname, rmethodname: TFRE_DB_NameType; const command_id: Qword; const input: IFRE_DB_Object; const cmd_type: TFRE_DB_COMMANDTYPE);
var replydata : IFRE_DB_Object;
objecthc : TFRE_DB_ObjectEx;
begin
try
if pos('RIF_',rmethodname)=1 then
begin
try
objecthc := (input.Implementor_HC as TFRE_DB_ObjectEx);
case cmd_type of
fct_SyncRequest:
begin
replydata := objecthc.Invoke_DBRIF_Method(rmethodname,self,command_id,input,cmd_type);
AnswerSyncCommand(command_id,replydata);
end;
fct_AsyncRequest:
begin
try
replydata := nil;
replydata := objecthc.Invoke_DBRIF_Method(rmethodname,self,command_id,input,cmd_type);
if assigned(replydata) then
begin
GFRE_DBI.LogWarning(dblc_FLEXCOM,'WorkRemoteMethod RIF Method Async Called but delivered a result (!) Failed [%s.%s]: SESSION [%s] MACHINE [%s/%s]',[rclassname,rmethodname,fMySessionID,cFRE_MACHINE_NAME,cFRE_MACHINE_UID.AsHexString]);
writeln('REPLYDATA: ',replydata.DumpToString());
replydata.Finalize;
end;
except
GFRE_DBI.LogWarning(dblc_FLEXCOM,'WorkRemoteMethod RIF Method Async Called but failed finalizing the (unexpected) result (!) Failed [%s.%s]: SESSION [%s] MACHINE [%s/%s]',[rclassname,rmethodname,fMySessionID,cFRE_MACHINE_NAME,cFRE_MACHINE_UID.AsHexString]);
end;
end
else
GFRE_DBI.LogEmergency(dblc_FLEXCOM,'WorkRemoteMethod RIF unexpected packet type [%s.%s]: SESSION [%s] MACHINE [%s/%s]',[rclassname,rmethodname,fMySessionID,cFRE_MACHINE_NAME,cFRE_MACHINE_UID.AsHexString]);
end;
except
on e:exception do
begin
case cmd_type of
fct_SyncRequest:
begin
AnswerSyncError(command_id,e.Message);
end;
fct_AsyncRequest:
begin
GFRE_DBI.LogError(dblc_FLEXCOM,'WorkRemoteMethod RIF Method Failed [%s.%s]: (%s) SESSION [%s] MACHINE [%s/%s]',[rclassname,rmethodname,e.Message,fMySessionID,cFRE_MACHINE_NAME,cFRE_MACHINE_UID.AsHexString]);
end
else
GFRE_DBI.LogEmergency(dblc_FLEXCOM,'WorkRemoteMethod RIF unexpected packet type [%s.%s]: SESSION [%s] MACHINE [%s/%s]',[rclassname,rmethodname,fMySessionID,cFRE_MACHINE_NAME,cFRE_MACHINE_UID.AsHexString]);
end;
end;
end;
end
else
if uppercase(rclassname)=uppercase(ClassName) then
Invoke_DBREM_Method(rmethodname,command_id,input,cmd_type)
else
raise EFRE_DB_Exception.Create(edb_ERROR,'Classname mismatch Mine:[%s] <> Requested:[%s] Method: [%s] CommandType [%s]',[ClassName,rclassname,rmethodname, CFRE_DB_COMMANDTYPE[cmd_type]]);
except on e:exception
do
begin
AnswerSyncError(command_id,e.Message);
input.Finalize;
end;
end;
end;
function TFRE_BASE_CLIENT.GetCurrentChanManLocked: IFRE_APSC_CHANNEL_MANAGER;
begin
FClientStateLock.Acquire;
result := FChannel.cs_GetChannelManager;
end;
procedure TFRE_BASE_CLIENT.UnlockCurrentChanMan;
begin
FClientStateLock.Release;
end;
procedure TFRE_BASE_CLIENT.AddSubFeederEventViaUX(const special_id: Shortstring);
var sub_state : TSUB_FEED_STATE;
begin
FSubFeedLock.Acquire;
try
sub_state := TSUB_FEED_STATE.Create;
sub_state.FConnectState := sfc_NOT_CONNECTED;
sub_state.FId := special_id;
sub_state.FSpecfile := cFRE_UX_SOCKS_DIR+special_id;
FSubfeedlist.Add(sub_state);
finally
FSubFeedLock.Release;
end;
end;
procedure TFRE_BASE_CLIENT.AddSubFeederEventViaTCP(const ip, port, special_id: Shortstring);
var sub_state : TSUB_FEED_STATE;
begin
FSubFeedLock.Acquire;
try
sub_state := TSUB_FEED_STATE.Create;
sub_state.FConnectState := sfc_NOT_CONNECTED;
sub_state.FId := special_id;
sub_state.FSpecfile := '';
sub_state.FPort := port;
sub_state.FIp := ip;
FSubfeedlist.Add(sub_state);
finally
FSubFeedLock.Release;
end;
end;
procedure TFRE_BASE_CLIENT.SubfeederEvent(const id: string; const dbo: IFRE_DB_Object);
begin
end;
function TFRE_BASE_CLIENT.SendServerCommand(const InvokeClass, InvokeMethod: String; const uidpath: array of TFRE_DB_GUID; const DATA: IFRE_DB_Object; const ContinuationCB: TFRE_DB_CONT_HANDLER; const timeout: integer): boolean;
begin
if Assigned(FBaseconnection) then begin
_SendServerCommand(FBaseconnection,InvokeClass,InvokeMethod,uidpath,DATA,ContinuationCB,timeout);
result := true;
end else begin
result := false;
end;
end;
function TFRE_BASE_CLIENT.AnswerSyncCommand(const command_id: QWord; const data: IFRE_DB_Object):boolean;
begin
if assigned(FBaseconnection) then
begin
FBaseconnection.SendSyncAnswer(command_id,data);
result := true;
end
else
result := false;
end;
function TFRE_BASE_CLIENT.AnswerSyncError(const command_id: QWord; const error: TFRE_DB_String): boolean;
begin
if assigned(FBaseconnection) then
begin
FBaseconnection.SendSyncErrorAnswer(command_id,error);
result := true;
end
else
result := false;
end;
procedure TFRE_BASE_CLIENT.MySessionEstablished(const chanman: IFRE_APSC_CHANNEL_MANAGER);
begin
FChannelTimer := chanman.AddChannelManagerTimer('CT',1000,@ChannelTimerCB,true);
end;
procedure TFRE_BASE_CLIENT.MySessionDisconnected(const chanman: IFRE_APSC_CHANNEL_MANAGER);
begin
if assigned(FChannelTimer) then
begin
FChannelTimer.cs_Finalize;
FChannelTimer := nil;
end;
end;
procedure TFRE_BASE_CLIENT.MySessionSetupFailed(const reason: string);
begin
writeln('SETUP FAILED REASON : ',reason);
end;
end.
|
{
Purpose: To generate "loose mods" for object modification records
Games: Fallout 4
Author: fireundubh <fireundubh@gmail.com>
INSTRUCTIONS:
1. Ensure that sEditorPrefix is desired.
2. Select one or many OMOD records, and apply the script.
3. Select the file where the new MISC records should be saved.
NOTE: This script will automatically assign the "loose mods" to the OMOD records.
However, if the respective OMOD records cannot be edited, overrides will be
automatically created in the target file, and assignment will take place there.
}
unit UserScript;
uses dubhFunctions;
var
kTargetFile: IwbFile;
kTemplate: IInterface;
sEditorPrefix: String;
lsMasters: TStringList;
// ----------------------------------------------------------------------------
function Initialize: integer;
begin
// CHANGE, AS NEEDED
sEditorPrefix := 'miscmod_'; // miscmod_mod_ or miscmod_PA_, for example
// DO NOT CHANGE ANYTHING ELSE
kTargetFile := FileSelect('Select the target file:');
kTemplate := RecordByHexFormID('0015503D'); // miscmod_mod_HuntingRifle_Scope_SightsIron [MISC:0015503D]
lsMasters := TStringList.Create;
lsMasters.Duplicates := dupIgnore;
end;
// ----------------------------------------------------------------------------
function Process(e: IInterface): integer;
var
kGroup, kTargetRecord, kOverride: IInterface;
i: Integer;
begin
if Signature(e) <> 'OMOD' then
exit;
AddMastersToList(GetFile(e), lsMasters);
if lsMasters.Count > 0 then
AddMastersToFile(kTargetFile, lsMasters, True);
kGroup := AddGroupBySignature(kTargetFile, 'MISC');
if not Assigned(kGroup) then
exit;
kTargetRecord := TryToCreateRecord(e, kGroup);
if IsEditable(e) then begin
SetElementEditValues(e, 'LNAM', SmallNameEx(kTargetRecord));
Log('Generated loose mod: ' + SmallNameEx(kTargetRecord) + ' | Assigned to: ' + SmallNameEx(e));
end else begin
kOverride := wbCopyElementToFile(e, kTargetFile, False, True);
SetElementEditValues(kOverride, 'LNAM', SmallNameEx(kTargetRecord));
Log('Generated loose mod: ' + SmallNameEx(kTargetRecord) + ' | Assigned to new override: ' + SmallNameEx(kOverride));
end;
end;
// ----------------------------------------------------------------------------
function TryToCreateRecord(e, akGroup: IInterface): IInterface;
var
r, kSource, kTarget: IInterface;
begin
r := AddNewRecordToGroup(akGroup, 'MISC');
if not Assigned(r) then
exit;
// ------------------------------------------------------------------
// VMAD
// ------------------------------------------------------------------
kSource := ElementBySignature(e, 'VMAD');
if Assigned(kSource) then
wbCopyElementToRecord(kSource, r, False, True);
// ------------------------------------------------------------------
// Editor ID
// ------------------------------------------------------------------
kSource := ElementBySignature(e, 'EDID');
if Assigned(kSource) then begin
kTarget := AddElementByString(r, 'EDID');
if Assigned(kTarget) then
SetEditValue(kTarget, sEditorPrefix + GetEditValue(kSource));
end;
// ------------------------------------------------------------------
// Object Bounds
// ------------------------------------------------------------------
kSource := ElementBySignature(kTemplate, 'OBND');
if Assigned(kSource) then
wbCopyElementToRecord(kSource, r, False, True);
// ------------------------------------------------------------------
// Transform
// ------------------------------------------------------------------
kSource := ElementBySignature(kTemplate, 'PTRN');
if Assigned(kSource) then
wbCopyElementToRecord(kSource, r, False, True);
// ------------------------------------------------------------------
// Name *required
// ------------------------------------------------------------------
kSource := ElementBySignature(e, 'FULL');
kTarget := AddElementByString(r, 'FULL');
if Assigned(kSource) then
SetEditValue(kTarget, GetEditValue(kSource));
// ----------------------------------------------------------------
// Model\MODL
// ----------------------------------------------------------------
kSource := ElementByName(kTemplate, 'Model');
if Assigned(kSource) then
wbCopyElementToRecord(kSource, r, False, True);
// ----------------------------------------------------------------
// KSIZ
// ----------------------------------------------------------------
kSource := ElementBySignature(kTemplate, 'KSIZ');
if Assigned(kSource) then
wbCopyElementToRecord(kSource, r, False, True);
// ----------------------------------------------------------------
// KWDA
// ----------------------------------------------------------------
kSource := ElementBySignature(kTemplate, 'KWDA');
if Assigned(kSource) then
wbCopyElementToRecord(kSource, r, False, True);
// ----------------------------------------------------------------
// DATA
// ----------------------------------------------------------------
kSource := ElementBySignature(kTemplate, 'DATA');
if Assigned(kSource) then
wbCopyElementToRecord(kSource, r, False, True);
Result := r;
end;
end.
|
unit ErrorConstants;
interface
const
//----------------------------------------------------------------------
// For add items
//----------------------------------------------------------------------
ADDITEM_FAIL = 1;
ADDITEM_OVERWEIGHT = 2;
ADDITEM_TOOMUCH = 4;
ADDITEM_TOOMUCHSTACKING = 5;
implementation
end. |
unit GuiaAlvo.Model.Contrato;
interface
uses GuiaAlvo.Model.Comercio;
type
// TTipoContrato = (tcBasico, tcPlus, tcFotosI, tcFotosII, tcAnuncioI, tcAnuncioII, tcFull);
TContrato = class
private
FFVISIVELPESQUISAS: BOOLEAN;
FFANUNCIOSECAO: BOOLEAN;
FFQTDEFOTOS: INTEGER;
FFGRAFICOESTATISTICA: BOOLEAN;
FFANUNCIODESTAQUE: BOOLEAN;
FFVISIVELSECOES: BOOLEAN;
FFIDPLANO: INTEGER;
FFQTDEANUNCIOPUSH: INTEGER;
FFQTDEPUSHANUNCIO: INTEGER;
FFPUSHALTERACAO: BOOLEAN;
FFREDESSOCIAIS: BOOLEAN;
FFANUNCIOPRINCIPAL: BOOLEAN;
FFLINKAPP: BOOLEAN;
FFPUSHINCLUSAO: BOOLEAN;
FFPUSHINFORMATIVO: INTEGER;
FFNOMEPLANO: STRING;
FFDELIVERYS: BOOLEAN;
FFCRIACAOARTE: BOOLEAN;
FFRESPOSTAAVALIACAO: BOOLEAN;
procedure SetFANUNCIODESTAQUE(const Value: BOOLEAN);
procedure SetFANUNCIOPRINCIPAL(const Value: BOOLEAN);
procedure SetFANUNCIOSECAO(const Value: BOOLEAN);
procedure SetFCRIACAOARTE(const Value: BOOLEAN);
procedure SetFDELIVERYS(const Value: BOOLEAN);
procedure SetFGRAFICOESTATISTICA(const Value: BOOLEAN);
procedure SetFIDPLANO(const Value: INTEGER);
procedure SetFLINKAPP(const Value: BOOLEAN);
procedure SetFNOMEPLANO(const Value: STRING);
procedure SetFPUSHALTERACAO(const Value: BOOLEAN);
procedure SetFPUSHINCLUSAO(const Value: BOOLEAN);
procedure SetFPUSHINFORMATIVO(const Value: INTEGER);
procedure SetFQTDEANUNCIOPUSH(const Value: INTEGER);
procedure SetFQTDEFOTOS(const Value: INTEGER);
procedure SetFQTDEPUSHANUNCIO(const Value: INTEGER);
procedure SetFREDESSOCIAIS(const Value: BOOLEAN);
procedure SetFRESPOSTAAVALIACAO(const Value: BOOLEAN);
procedure SetFVISIVELPESQUISAS(const Value: BOOLEAN);
procedure SetFVISIVELSECOES(const Value: BOOLEAN);
public
property FPUSHALTERACAO: BOOLEAN read FFPUSHALTERACAO write SetFPUSHALTERACAO;
property FREDESSOCIAIS: BOOLEAN read FFREDESSOCIAIS write SetFREDESSOCIAIS;
property FANUNCIOPRINCIPAL: BOOLEAN read FFANUNCIOPRINCIPAL write SetFANUNCIOPRINCIPAL;
property FPUSHINCLUSAO: BOOLEAN read FFPUSHINCLUSAO write SetFPUSHINCLUSAO;
property FLINKAPP: BOOLEAN read FFLINKAPP write SetFLINKAPP;
property FPUSHINFORMATIVO: INTEGER read FFPUSHINFORMATIVO write SetFPUSHINFORMATIVO;
property FNOMEPLANO: STRING read FFNOMEPLANO write SetFNOMEPLANO;
property FDELIVERYS: BOOLEAN read FFDELIVERYS write SetFDELIVERYS;
property FCRIACAOARTE: BOOLEAN read FFCRIACAOARTE write SetFCRIACAOARTE;
property FRESPOSTAAVALIACAO: BOOLEAN read FFRESPOSTAAVALIACAO write SetFRESPOSTAAVALIACAO;
property FANUNCIOSECAO: BOOLEAN read FFANUNCIOSECAO write SetFANUNCIOSECAO;
property FVISIVELPESQUISAS: BOOLEAN read FFVISIVELPESQUISAS write SetFVISIVELPESQUISAS;
property FQTDEFOTOS: INTEGER read FFQTDEFOTOS write SetFQTDEFOTOS;
property FGRAFICOESTATISTICA: BOOLEAN read FFGRAFICOESTATISTICA write SetFGRAFICOESTATISTICA;
property FANUNCIODESTAQUE: BOOLEAN read FFANUNCIODESTAQUE write SetFANUNCIODESTAQUE;
property FVISIVELSECOES: BOOLEAN read FFVISIVELSECOES write SetFVISIVELSECOES;
property FQTDEPUSHANUNCIO: INTEGER read FFQTDEPUSHANUNCIO write SetFQTDEPUSHANUNCIO;
property FQTDEANUNCIOPUSH: INTEGER read FFQTDEANUNCIOPUSH write SetFQTDEANUNCIOPUSH;
property FIDPLANO: INTEGER read FFIDPLANO write SetFIDPLANO;
end;
implementation
{ TContrato }
procedure TContrato.SetFANUNCIODESTAQUE(const Value: BOOLEAN);
begin
FFANUNCIODESTAQUE := Value;
end;
procedure TContrato.SetFANUNCIOPRINCIPAL(const Value: BOOLEAN);
begin
FFANUNCIOPRINCIPAL := Value;
end;
procedure TContrato.SetFANUNCIOSECAO(const Value: BOOLEAN);
begin
FFANUNCIOSECAO := Value;
end;
procedure TContrato.SetFCRIACAOARTE(const Value: BOOLEAN);
begin
FFCRIACAOARTE := Value;
end;
procedure TContrato.SetFDELIVERYS(const Value: BOOLEAN);
begin
FFDELIVERYS := Value;
end;
procedure TContrato.SetFGRAFICOESTATISTICA(const Value: BOOLEAN);
begin
FFGRAFICOESTATISTICA := Value;
end;
procedure TContrato.SetFIDPLANO(const Value: INTEGER);
begin
FFIDPLANO := Value;
end;
procedure TContrato.SetFLINKAPP(const Value: BOOLEAN);
begin
FFLINKAPP := Value;
end;
procedure TContrato.SetFNOMEPLANO(const Value: STRING);
begin
FFNOMEPLANO := Value;
end;
procedure TContrato.SetFPUSHALTERACAO(const Value: BOOLEAN);
begin
FFPUSHALTERACAO := Value;
end;
procedure TContrato.SetFPUSHINCLUSAO(const Value: BOOLEAN);
begin
FFPUSHINCLUSAO := Value;
end;
procedure TContrato.SetFPUSHINFORMATIVO(const Value: INTEGER);
begin
FFPUSHINFORMATIVO := Value;
end;
procedure TContrato.SetFQTDEANUNCIOPUSH(const Value: INTEGER);
begin
FFQTDEANUNCIOPUSH := Value;
end;
procedure TContrato.SetFQTDEFOTOS(const Value: INTEGER);
begin
FFQTDEFOTOS := Value;
end;
procedure TContrato.SetFQTDEPUSHANUNCIO(const Value: INTEGER);
begin
FFQTDEPUSHANUNCIO := Value;
end;
procedure TContrato.SetFREDESSOCIAIS(const Value: BOOLEAN);
begin
FFREDESSOCIAIS := Value;
end;
procedure TContrato.SetFRESPOSTAAVALIACAO(const Value: BOOLEAN);
begin
FFRESPOSTAAVALIACAO := Value;
end;
procedure TContrato.SetFVISIVELPESQUISAS(const Value: BOOLEAN);
begin
FFVISIVELPESQUISAS := Value;
end;
procedure TContrato.SetFVISIVELSECOES(const Value: BOOLEAN);
begin
FFVISIVELSECOES := Value;
end;
end.
|
unit MovimentoService;
interface
uses
BasicService, Datasnap.DBClient, System.Generics.Collections, TurnoVO,
System.SysUtils, OperadorVO, MovimentoVO, SuprimentoVO, SangriaVO,
MovimentoFechamentoVO, TipoImpressaoVO, ImprimirVO, ViewImprimirVO,
ViewVendaVO, System.Math, Nfc01VO, Nfc02VO, TerminalVO, PessoaVO, Vcl.Forms,
Vcl.ExtCtrls, Vcl.Controls, PanelHelper;
type
TMovimentoService = class(TBasicService)
class procedure getTurno(DataSet: TClientDataSet);
class function getOperador(Login,Senha: string; Nivel: Integer): Boolean; overload;
class function getOperador(Login,Senha: string): TOperadorVO; overload;
class function MovimentoInserir(Movimento: TMovimentoVO): Boolean;
class function getMovimentoByIdCaixa(idOfCaixa: Integer): TMovimentoVO;
class function SangriaInserir(Sangria: TSangriaVO): Boolean;
class function SuprimentoInserir(Suprimento: TSuprimentoVO): Boolean;
class function MovimentoFechar(Lst: TList<TMovimentoFechamentoVO>; idOfMovimento: Integer): Boolean;
class procedure getTipoImpressao(Dataset: TClientDataSet);
class procedure getImprimir(idOfMovimento, idOfTipoImpressao: Integer; Dataset: TClientDataSet);
class procedure getImprimirPedido(idOfMovimento, idOfTipoImpressao: Integer; Dataset: TClientDataSet);
class function Reimprimir(idOfImprimir: Integer): Boolean;
class function Mensagem(MS: string; Tipo: Integer = 0): Boolean;
class procedure getVendasDoMovimento(idOfMovimento: Integer; Dataset: TClientDataSet);
class function NFExiste(idOfVenda: Integer): Boolean;
class function getResultNF(idOfVenda: Integer): string;
class function getTerminal(Identificador: string): TTerminalVO;
class function PessoaInserir(Nome,Doc: string): Integer;
class procedure GetVendedorAll(Scrol: TScrollBox);
class function GetVendedor(Login,Senha: string): Integer;
end;
implementation
{ TMovimentoService }
uses MovimentoRepository, Biblioteca, ufrmMensagem, VendedorVO;
class function TMovimentoService.Mensagem(MS: string; Tipo: Integer = 0): Boolean;
begin
try
frmMensagem:= TfrmMensagem.Create(nil);
frmMensagem.tipo:= Tipo;
frmMensagem.Label2.Caption:= MS;
frmMensagem.ShowModal;
Result:= frmMensagem.Tag = 1;
finally
FreeAndNil(frmMensagem);
end;
end;
class function TMovimentoService.MovimentoFechar(
Lst: TList<TMovimentoFechamentoVO>; idOfMovimento: Integer): Boolean;
begin
try
Result:= True;
BeginTransaction;
TMovimentoRepository.MovimentoFechamentoInserir(Lst);
TMovimentoRepository.MovimentoFechar(idOfMovimento);
Commit;
except
Rollback;
Result:= False;
end;
end;
class procedure TMovimentoService.getImprimir(idOfMovimento,
idOfTipoImpressao: Integer; Dataset: TClientDataSet);
var
Lst: TList<TImprimirVO>;
I: Integer;
begin
if not (Dataset.Active) then
Dataset.CreateDataSet;
Dataset.EmptyDataSet;
Lst:= TMovimentoRepository.getImprimir(idOfMovimento,idOfTipoImpressao);
if Assigned(Lst) then
begin
for I := 0 to Pred(Lst.Count) do
begin
Dataset.Append;
Dataset.FieldByName('ID').AsInteger:= Lst.Items[i].Id;
Dataset.FieldByName('LANCAMENTO').AsDateTime:= Lst.Items[i].Lancamento;
Dataset.FieldByName('IDOFTABLE').AsInteger:= Lst.Items[i].Idoftable;
Dataset.Post;
Lst.Items[i].Free;
end;
Dataset.First;
FreeAndNil(Lst);
end;
end;
class procedure TMovimentoService.getImprimirPedido(idOfMovimento,
idOfTipoImpressao: Integer; Dataset: TClientDataSet);
var
Lst: TList<TViewImprimirVO>;
I: Integer;
begin
if not (Dataset.Active) then
Dataset.CreateDataSet;
Dataset.EmptyDataSet;
Lst:= TMovimentoRepository.getImprimirPedido(idOfMovimento,idOfTipoImpressao);
if Assigned(Lst) then
begin
for I := 0 to Pred(Lst.Count) do
begin
Dataset.Append;
Dataset.FieldByName('ID').AsInteger:= Lst.Items[i].Id;
Dataset.FieldByName('LANCAMENTO').AsDateTime:= Lst.Items[i].Lancamento;
Dataset.FieldByName('IDOFTABLE').AsInteger:= Lst.Items[i].Idoftable;
Dataset.Post;
Lst.Items[i].Free;
end;
Dataset.First;
FreeAndNil(Lst);
end;
end;
class function TMovimentoService.getMovimentoByIdCaixa(
idOfCaixa: Integer): TMovimentoVO;
begin
Result:= TMovimentoRepository.getMovimentoByIdCaixa(idOfCaixa);
end;
class function TMovimentoService.getOperador(Login, Senha: string): TOperadorVO;
var
Identificacao: string;
begin
Identificacao:= MD5String(Login + Senha);
Result:= TMovimentoRepository.getOperador(Identificacao);
end;
class function TMovimentoService.getResultNF(idOfVenda: Integer): string;
var
R: TNfc02VO;
begin
Result:= EmptyStr;
R:= TMovimentoRepository.getResultNF(idOfVenda);
if Assigned(R) then
Result:= R.Result;
FreeAndNil(R);
end;
class function TMovimentoService.getOperador(Login,Senha: string;
Nivel: Integer): Boolean;
var
Identificacao: string;
Operador: TOperadorVO;
begin
Result:= False;
Identificacao:= MD5String(Login + Senha);
Operador:= TMovimentoRepository.getOperador(Identificacao);
case Nivel of
1:Result:= Assigned(Operador);
3:Result:= (Assigned(Operador) and (Operador.NivelAutorizacao = Nivel));
end;
FreeAndNil(Operador);
end;
class function TMovimentoService.getTerminal(
Identificador: string): TTerminalVO;
begin
Result:= TMovimentoRepository.getTerminal(Identificador);
end;
class procedure TMovimentoService.getTipoImpressao(Dataset: TClientDataSet);
var
Lst: TList<TTipoImpressaoVO>;
I: Integer;
begin
if not (Dataset.Active) then
Dataset.CreateDataSet;
Dataset.EmptyDataSet;
Lst:= TMovimentoRepository.getTipoImpressao;
if Assigned(Lst) then
begin
for I := 0 to Pred(Lst.Count) do
begin
Dataset.Append;
Dataset.FieldByName('ID').AsInteger:= Lst.Items[i].Id;
Dataset.FieldByName('NOME').AsString:= Lst.Items[i].Nome;
Dataset.Post;
Lst.Items[i].Free;
end;
Dataset.First;
FreeAndNil(Lst);
end;
end;
class procedure TMovimentoService.getTurno(DataSet: TClientDataSet);
var
Lst: TList<TTurnoVO>;
I: Integer;
begin
Lst:= TMovimentoRepository.getTuno;
if not (DataSet.Active) then
DataSet.CreateDataSet;
DataSet.EmptyDataSet;
if Assigned(Lst) then
begin
for I := 0 to Pred(Lst.Count) do
begin
DataSet.Append;
DataSet.FieldByName('ID').AsInteger:= Lst.Items[i].Id;
DataSet.FieldByName('NOME').AsString:= Lst.Items[i].Nome;
DataSet.FieldByName('INICIO').AsString:= Lst.Items[i].Inicio;
DataSet.FieldByName('FIM').AsString:= Lst.Items[i].Fim;
DataSet.Post;
Lst.Items[i].Free;
end;
FreeAndNil(Lst);
end;
end;
class function TMovimentoService.MovimentoInserir(
Movimento: TMovimentoVO): Boolean;
var
Suprimento: TSuprimentoVO;
begin
Result:= True;
BeginTransaction;
try
TMovimentoRepository.MovimentoInserir(Movimento);
if Movimento.Suprimento > 0 then
begin
Suprimento:= TSuprimentoVO.Create;
Suprimento.IdMovimento:= Movimento.Id;
Suprimento.Valor:= Movimento.Suprimento;
TMovimentoRepository.MovimentoInserirSuprimento(Suprimento);
Suprimento.Free;
end;
Commit;
except
Rollback;
Result:= False;
end;
end;
class function TMovimentoService.NFExiste(idOfVenda: Integer): Boolean;
var
Nf: TNfc01VO;
begin
Nf:= TMovimentoRepository.getNF(idOfVenda);
Result:= Assigned(Nf);
FreeAndNil(Nf);
end;
class function TMovimentoService.PessoaInserir(Nome,Doc: string): Integer;
var
Pessoa: TPessoaVO;
begin
Pessoa:= TPessoaVO.Create;
Pessoa.Nome:= Nome;
Pessoa.Doc:= Doc;
Pessoa.ContaCorrente:= 'N';
try
BeginTransaction;
Result:= TMovimentoRepository.PessoaInserir(Pessoa);
FreeAndNil(Pessoa);
Commit;
except
Rollback;
Result:= 0;
end;
end;
class function TMovimentoService.Reimprimir(idOfImprimir: Integer): Boolean;
begin
try
Result:= True;
BeginTransaction;
TMovimentoRepository.Reimprimir(idOfImprimir);
Commit;
except
Rollback;
Result:= False;
end;
end;
class function TMovimentoService.SangriaInserir(Sangria: TSangriaVO): Boolean;
begin
try
Result:= True;
BeginTransaction;
TMovimentoRepository.SangriaInserir(Sangria);
Commit;
except
Rollback;
Result:= False;
end;
end;
class function TMovimentoService.SuprimentoInserir(
Suprimento: TSuprimentoVO): Boolean;
begin
try
Result:= True;
BeginTransaction;
TMovimentoRepository.MovimentoInserirSuprimento(Suprimento);
Commit;
except
Rollback;
Result:= False;
end;
end;
class procedure TMovimentoService.getVendasDoMovimento(idOfMovimento: Integer;
Dataset: TClientDataSet);
var
Lst: TList<TViewVendaVO>;
I: Integer;
begin
if not (Dataset.Active) then
Dataset.CreateDataSet;
Dataset.EmptyDataSet;
Lst:= TMovimentoRepository.getVendasDoMovimento(idOfMovimento);
if Assigned(Lst) then
begin
for I := 0 to Pred(Lst.Count) do
begin
Dataset.Append;
Dataset.FieldByName('ID').AsInteger:= Lst.Items[i].Id;
Dataset.FieldByName('PEDIDO').AsInteger:= Lst.Items[i].Pedido;
Dataset.FieldByName('ID_MOVIMENTO').AsInteger:= Lst.Items[i].IdMovimento;
Dataset.FieldByName('ID_PESSOA').AsInteger:= Lst.Items[i].IdPessoa;
Dataset.FieldByName('LANCAMENTO').AsDateTime:= Lst.Items[i].Lancamento;
Dataset.FieldByName('SUBTOTAL').AsFloat:= Lst.Items[i].Subtotal;
Dataset.FieldByName('DESCONTO').AsFloat:= Lst.Items[i].Desconto;
Dataset.FieldByName('TOTAL').AsFloat:= Lst.Items[i].Total;
Dataset.FieldByName('RECEBIDO').AsFloat:= Lst.Items[i].Recebido;
Dataset.FieldByName('TROCO').AsFloat:= Lst.Items[i].Troco;
Dataset.FieldByName('CLIENTE_NOME').AsString:= Lst.Items[i].ClienteNome;
Dataset.FieldByName('CLIENTE_DOC').AsString:= Lst.Items[i].ClienteDoc;
Dataset.FieldByName('FISCAL').AsInteger:= IfThen(Lst.Items[i].Fiscal = 'S',1,0);
Dataset.FieldByName('ID_CONTA_RECEBER').AsInteger:= Lst.Items[i].IdContaReceber;
Dataset.Post;
Lst.Items[i].Free;
end;
Dataset.First;
FreeAndNil(Lst);
end;
end;
class function TMovimentoService.GetVendedor(Login, Senha: string): Integer;
var
Identificacao: string;
Vendedor: TVendedorVO;
begin
try
Result:= 0;
Identificacao:= MD5String(Login + Senha);
Vendedor:= TMovimentoRepository.getVendedor(Identificacao);
if Assigned(Vendedor) then
begin
Result:= Vendedor.Id;
FreeAndNil(Vendedor);
end;
except
Result:= 0;
end;
end;
class procedure TMovimentoService.GetVendedorAll(Scrol: TScrollBox);
var
Lst: TList<TVendedorVO>;
Panel: TPanel;
i: Integer;
begin
Lst:= TMovimentoRepository.GetVendedorAll();
if Assigned(Lst) then
begin
for i := 0 to Pred(Lst.Count) do
begin
Panel:= TPanel.Create(Scrol);
Panel.Parent:= Scrol;
Panel.Align:= alTop;
Panel.Height:= 96;
Panel.BevelInner:= bvSpace;
Panel.BevelOuter:= bvSpace;
Panel.BevelKind:= bkNone;
Panel.DragMode:= dmManual;
Panel.Name:= 'P' + IntToStr(Lst.Items[i].Id);
Panel.Caption:= EmptyStr;
Panel.OnClick:= Scrol.OnClick;
Panel.OnDblClick:= Scrol.OnDblClick;
Panel.Vendedor(Lst.Items[i]);
end;
FreeAndNil(Lst);
end;
end;
end.
|
unit CDAPrincipal;
interface
uses
SysUtils, Classes, DB, DBTables;
type
TDAPrincipal = class(TDataModule)
DBPrincipal: TDatabase;
QKilosAprovechados: TQuery;
QKilosSalida: TQuery;
QKilosTerceros: TQuery;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
{ Private declarations }
procedure SQLKilosAprovecha( const ACentro, AProducto, ACosecheros: string );
// function EsAgrupacionTomate( const AProducto: String):boolean;
public
{ Public declarations }
procedure KilosAprovecha( const AEmpresa, ACentro, AProducto, ACosecheros: String;
const AFechaini, AFechaFin: TDateTime;
var VPrimera, VSegunda, VTercera, VDestrio, VMerma: Real );
procedure KilosSalida( const AEmpresa, ACentro, AProducto: String;
const AFechaini, AFechaFin: TDateTime;
var VPrimera, VSegunda, VTercera, VDestrio, VBotado: Real );
procedure KilosTerceros( const AEmpresa, ACentro, AProducto: String;
const AFechaini, AFechaFin: TDateTime;
var VPrimera, VSegunda, VTercera, VDestrio, VBotado: Real );
function EsAgrupacionTomate( const AProducto: String):boolean;
end;
var
DAPrincipal: TDAPrincipal;
implementation
{$R *.dfm}
procedure TDAPrincipal.DataModuleCreate(Sender: TObject);
begin
with QKilosSalida do
begin
SQL.Clear;
SQL.Add(' select categoria_sl, sum(kilos_sl) kilos ');
SQL.Add(' from frf_salidas_l, frf_salidas_c ');
SQL.Add(' where empresa_sl = :empresa ');
SQL.Add(' and centro_salida_sl = :centro ');
SQL.Add(' and fecha_sl between :fechaini and :fechafin ');
SQL.Add(' and producto_sl = :producto ');
SQL.Add(' and empresa_sc = empresa_sl ');
SQL.Add(' and centro_salida_sc = centro_salida_sl ');
SQL.Add(' and n_albaran_sc = n_albaran_sl ');
SQL.Add(' and fecha_sc = fecha_sl ');
SQL.Add(' and n_factura_sc is not null ');
SQL.Add(' and es_transito_sc <> 2 '); //Tipo Salida: Devolucion
SQL.Add(' group by 1 ');
Prepare;
end;
with QKilosTerceros do
begin
SQL.Clear;
SQL.Add(' select categoria_st, sum(kilos_st) kilos ');
SQL.Add(' from frf_salidas_terceros, frf_salidas_c ');
SQL.Add(' where empresa_st = :empresa ');
SQL.Add(' and centro_salida_st = :centro ');
SQL.Add(' and fecha_st between :fechaini and :fechafin ');
SQL.Add(' and producto_st = :producto ');
SQL.Add(' and emp_procedencia_st <> empresa_st');
SQL.Add(' and empresa_sc = empresa_st ');
SQL.Add(' and centro_salida_sc = centro_salida_st ');
SQL.Add(' and n_albaran_sc = n_albaran_st ');
SQL.Add(' and fecha_sc = fecha_st ');
SQL.Add(' and n_factura_sc is not null ');
SQL.Add(' and es_transito_sc <> 2 '); //Tipo Salida: Devolucion
SQL.Add(' group by 1 ');
Prepare;
end;
end;
procedure TDAPrincipal.DataModuleDestroy(Sender: TObject);
procedure Desprepara( var VQuery: TQuery );
begin
VQuery.Cancel;
VQuery.Close;
if VQuery.Prepared then
VQuery.UnPrepare;
end;
begin
Desprepara( QKilosSalida );
Desprepara( QKilosTerceros );
end;
function TDAPrincipal.EsAgrupacionTomate(const AProducto: String): boolean;
var QAux: TQuery;
begin
QAux := TQuery.Create(Self);
with QAUx do
try
DataBaseName := 'DBPrincipal';
SQL.Clear;
SQL.Add(' select * from frf_agrupacion ');
SQL.Add(' where producto_a = :producto ');
SQL.Add(' and codigo_a = 1 '); // Agrupacion Tomate
ParamByName('producto').AsString := AProducto;
Open;
result := not IsEmpty;
finally
free;
end;
end;
procedure TDAPrincipal.SQLKilosAprovecha( const ACentro, AProducto, ACosecheros: string );
begin
if ((EsAgrupacionTomate(AProducto)) and (ACentro = '1')) or
((AProducto = 'CAL') and (ACentro = '1')) then
begin
with QKilosAprovechados do
begin
SQL.Clear;
SQL.Add(' select ');
SQL.Add(' round( sum( ( porcen_primera_e * total_kgs_e2l ) / 100 ), 2 ) primera, ');
SQL.Add(' round( sum( ( porcen_segunda_e * total_kgs_e2l ) / 100 ), 2 ) segunda, ');
SQL.Add(' round( sum( ( porcen_tercera_e * total_kgs_e2l ) / 100 ), 2 ) tercera, ');
SQL.Add(' round( sum( ( porcen_destrio_e * total_kgs_e2l ) / 100 ), 2 ) destrio, ');
SQL.Add(' round( sum( ( aporcen_merma_e * total_kgs_e2l ) / 100 ), 2 ) merma ');
SQL.Add(' from frf_entradas2_l, frf_escandallo ');
SQL.Add(' where empresa_e2l = :empresa ');
SQL.Add(' and centro_e2l in (:centro,6) '); // :centro '); Se buscan compras en centro 1 - los llanos y 6 - Tenerife. Luego se asignaran ventas del centro 1
SQL.Add(' and fecha_e2l between :fechaini and :fechafin ');
SQL.Add(' and producto_e2l = :producto ');
if Trim(ACosecheros) <> '' then
SQL.Add(' and cosechero_e2l in ( ' + ACosecheros + ' ) ');
SQL.Add(' and empresa_e = empresa_e2l ');
SQL.Add(' and centro_e = centro_e2l ');
SQL.Add(' and numero_entrada_e = numero_entrada_e2l ');
SQL.Add(' and fecha_e = fecha_e2l ');
SQL.Add(' and producto_e = :producto ');
SQL.Add(' and cosechero_e = cosechero_e2l ');
Prepare;
end;
end
else if ACentro = '3' then
begin
with QKilosAprovechados do
begin
SQL.Clear;
SQL.Add(' select ');
SQL.Add(' 0 primera, ');
SQL.Add(' 0 segunda, ');
SQL.Add(' round(sum(total_kgs_e2l)) tercera, ');
SQL.Add(' 0 destrio, ');
SQL.Add(' 0 merma ');
SQL.Add(' from frf_entradas2_l ');
SQL.Add(' where empresa_e2l = :empresa ');
SQL.Add(' and centro_e2l = :centro ');
SQL.Add(' and fecha_e2l between :fechaini and :fechafin ');
SQL.Add(' and producto_e2l = :producto ');
if Trim(ACosecheros) <> '' then
SQL.Add(' and cosechero_e2l in ( ' + ACosecheros + ' ) ');
Prepare;
end;
end
else
begin
with QKilosAprovechados do
begin
SQL.Clear;
SQL.Add(' select ');
SQL.Add(' round(sum(total_kgs_e2l)) primera, ');
SQL.Add(' 0 segunda, ');
SQL.Add(' 0 tercera, ');
SQL.Add(' 0 destrio, ');
SQL.Add(' 0 merma ');
SQL.Add(' from frf_entradas2_l ');
SQL.Add(' where empresa_e2l = :empresa ');
SQL.Add(' and centro_e2l = :centro ');
SQL.Add(' and fecha_e2l between :fechaini and :fechafin ');
SQL.Add(' and producto_e2l = :producto ');
if Trim(ACosecheros) <> '' then
SQL.Add(' and cosechero_e2l in ( ' + ACosecheros + ' ) ');
Prepare;
end;
end;
end;
procedure TDAPrincipal.KilosAprovecha( const AEmpresa, ACentro, AProducto, ACosecheros: String;
const AFechaini, AFechaFin: TDateTime;
var VPrimera, VSegunda, VTercera, VDestrio, VMerma: Real );
begin
SQLKilosAprovecha( ACentro, AProducto, ACosecheros );
with QKilosAprovechados do
begin
ParamByName('empresa').AsString:= AEmpresa;
ParamByName('centro').AsString:= ACentro;
ParamByName('producto').AsString:= AProducto;
ParamByName('fechaini').AsDateTime:= AFechaini;
ParamByName('fechafin').AsDateTime:= AFechaFin;
Open;
VPrimera:= FieldByName('primera').AsFloat;
VSegunda:= FieldByName('segunda').AsFloat;
VTercera:= FieldByName('tercera').AsFloat;
VDestrio:= FieldByName('destrio').AsFloat;
VMerma:= FieldByName('merma').AsFloat;
Close;
end;
end;
procedure TDAPrincipal.KilosSalida( const AEmpresa, ACentro, AProducto: String;
const AFechaini, AFechaFin: TDateTime;
var VPrimera, VSegunda, VTercera, VDestrio, VBotado: Real );
begin
VPrimera:= 0;
VSegunda:= 0;
VTercera:= 0;
VDestrio:= 0;
VBotado:= 0;
with QKilosSalida do
begin
ParamByName('empresa').AsString:= AEmpresa;
ParamByName('centro').AsString:= ACentro;
ParamByName('producto').AsString:= AProducto;
ParamByName('fechaini').AsDateTime:= AFechaini;
ParamByName('fechafin').AsDateTime:= AFechaFin;
Open;
while not Eof do
begin
if FieldByName('categoria_sl').AsString = '1' then
begin
VPrimera:= VPrimera + FieldByName('kilos').AsFloat;
end
else
if FieldByName('categoria_sl').AsString = '2' then
begin
VSegunda:= VSegunda + FieldByName('kilos').AsFloat;
end
else
if FieldByName('categoria_sl').AsString = '3' then
begin
VTercera:= VTercera + FieldByName('kilos').AsFloat;
end
else
if FieldByName('categoria_sl').AsString = 'B' then
begin
VBotado:= VBotado + FieldByName('kilos').AsFloat;
end
else
begin
VDestrio:= VDestrio + FieldByName('kilos').AsFloat;
end;
Next;
end;
Close;
end;
end;
procedure TDAPrincipal.KilosTerceros( const AEmpresa, ACentro, AProducto: String;
const AFechaini, AFechaFin: TDateTime;
var VPrimera, VSegunda, VTercera, VDestrio, VBotado: Real );
begin
VPrimera:= 0;
VSegunda:= 0;
VTercera:= 0;
VDestrio:= 0;
VBotado:= 0;
with QKilosTerceros do
begin
ParamByName('empresa').AsString:= AEmpresa;
ParamByName('centro').AsString:= ACentro;
ParamByName('producto').AsString:= AProducto;
ParamByName('fechaini').AsDateTime:= AFechaini;
ParamByName('fechafin').AsDateTime:= AFechaFin;
Open;
while not Eof do
begin
if FieldByName('categoria_st').AsString = '1' then
begin
VPrimera:= VPrimera + FieldByName('kilos').AsFloat;
end
else
if FieldByName('categoria_st').AsString = '2' then
begin
VSegunda:= VSegunda + FieldByName('kilos').AsFloat;
end
else
if FieldByName('categoria_st').AsString = '3' then
begin
VTercera:= VTercera + FieldByName('kilos').AsFloat;
end
else
if FieldByName('categoria_st').AsString = 'B' then
begin
VBotado:= VBotado + FieldByName('kilos').AsFloat;
end
else
begin
VDestrio:= VDestrio + FieldByName('kilos').AsFloat;
end;
Next;
end;
Close;
end;
end;
end.
|
unit uFormPrincipal;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, jpeg, uLogin, uMenu, uManutencao, DB,
DBClient, uSaque, uRelatorioSaque;
type
TFrmPrincipal = class(TForm)
ImgLogo: TImage;
PnlCentro: TPanel;
CdsAgencias: TClientDataSet;
CdsContas: TClientDataSet;
CdsNotas: TClientDataSet;
DsAgencias: TDataSource;
DsContas: TDataSource;
DsNotas: TDataSource;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormKeyPress(Sender: TObject; var Key: Char);
private
FTela: integer; { Número da tela atual }
FTelaAnterior: integer; { Tela anterior }
FFrameAtual: TFrame; { Frame atual }
procedure SelecionarTela; { Ajusta formulário principal de acordo com a tela selecionada }
public
FrmMenu: TFrmMenu; { Frame de menu principal }
FrmLogin: TFrmLogin; { Frame de Login de Agencia, CC e Senha }
FrmManutencao: TFrmManutencao; { Frame de Manutençao }
FrmSaque: TFrmSaque; { Frame de Saque }
FrmRelatorioSaque: TFrmRelatorioSaque; { Frame de Relatorio de Saque }
procedure AlterarTela(NovaTela: integer); { Seleção de uma nova tela }
procedure TelaAnterior; { Seleciona a tela anterior }
procedure DiminuiNotas(coValorNota : String; coMenosNota: Integer);
end;
var
FrmPrincipal: TFrmPrincipal;
implementation
//const
//CNT_FORMATA_MEMO := 'Notas de ' %d: ' + IntToStr(%d);;
{$R *.dfm}
procedure TFrmPrincipal.AlterarTela(NovaTela: integer);
begin
{ Seleciona a nova tela }
FTelaAnterior := FTela;
FTela := NovaTela;
SelecionarTela;
end;
procedure TFrmPrincipal.FormCreate(Sender: TObject);
begin
{ Inicializa variáveis }
FTela := 1;
FFrameAtual := nil;
{ Cria os frames }
FrmLogin := TFrmLogin.Create(Self);
FrmMenu := TFrmMenu.Create(Self);
FrmManutencao := TFrmManutencao.Create(Self);
FrmSaque := TFrmSaque.Create(Self);
FrmRelatorioSaque := TFrmRelatorioSaque.Create(Self);
FrmManutencao.DbAgencias.DataSource := DsAgencias;
FrmManutencao.DbContas.DataSource := DsContas;
FrmManutencao.DbNotas.DataSource := DsNotas;
FrmManutencao.NavAgencias.DataSource := DsAgencias;
FrmManutencao.NavContas.DataSource := DsContas;
FrmManutencao.NavNotas.DataSource := DsNotas;
{ Seleciona a tela atual }
SelecionarTela;
{ Cria os datasets }
CdsAgencias.FileName := GetCurrentDir + '\Agencias.cds';
CdsAgencias.CreateDataset;
CdsContas.FileName := GetCurrentDir + '\Contas.cds';
CdsContas.CreateDataset;
CdsNotas.FileName := GetCurrentDir + '\Notas.cds';
CdsNotas.CreateDataset;
{ Verifica a existencia dos arquivos de dados e faz a leitura }
if FileExists(GetCurrentDir + '\Agencias.dat') then
CdsAgencias.LoadFromFile(GetCurrentDir + '\Agencias.dat');
if FileExists(GetCurrentDir + '\Contas.dat') then
CdsContas.LoadFromFile(GetCurrentDir + '\Contas.dat');
if FileExists(GetCurrentDir + '\Notas.dat') then
cdsNotas.LoadFromFile(GetCurrentDir + '\Notas.dat');
{ Desliga o log de alterações para não aumentar o tamenho dos arquivos }
CdsAgencias.LogChanges := False;
CdsContas.LogChanges := False;
cdsNotas.LogChanges := False;
end;
procedure TFrmPrincipal.SelecionarTela;
begin
{ Sempre que inicializa, deve pegar o frame anterior (se ele existir um anterior) }
{ e coloca como inivisivel para não ter problemas de sobreposição. }
if FFrameAtual <> nil then
begin
FFrameAtual.Visible := False;
FFrameAtual.Parent := nil;
end;
{ Verifica a tela selecionada }
Case FTela of
1: begin { 1 = Menu inicial }
FFrameAtual := FrmMenu;
end;
2: begin { 2 = Login }
FFrameAtual := FrmLogin;
FrmLogin.Inicializar;
end;
3: begin { 3 = Manutencao }
FFrameAtual := FrmManutencao;
end;
4: begin { 4 = Saques }
FFrameAtual := FrmSaque;
end;
5: begin { 5 = Relatorio Saques }
FFrameAtual := FrmRelatorioSaque;
end;
else
end;
{ Ajusta o Frame atual na tela e faz o show dele }
if FFrameAtual <> nil then
begin
FFrameAtual.Parent := PnlCentro;
FFrameAtual.Show;
end;
end;
procedure TFrmPrincipal.TelaAnterior;
begin
{ Verifica se a tela anterior é válida }
if FTelaAnterior = 0 then
exit;
{ Seleciona a nova tela }
AlterarTela(FTelaAnterior);
SelecionarTela;
end;
procedure TFrmPrincipal.DiminuiNotas(coValorNota :String; coMenosNota: Integer);
begin
CdsNotas.IndexName := 'CEDULAASC';
if CdsNotas.Locate('CEDULA', coValorNota, [loCaseInsensitive]) then
begin
CdsNotas.Edit;
CdsNotas.FieldByName('QUANTIDADE').AsInteger := CdsNotas.FieldByName('QUANTIDADE').AsInteger - coMenosNota;
//CdsNotas.FieldByName('CEDULA').AsString :=
CdsNotas.UpdateRecord;
end;
end;
procedure TFrmPrincipal.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
{ Verifica a existencia dos arquivos de dados e faz a leitura }
CdsAgencias.SaveToFile(GetCurrentDir + '\Agencias.dat');
CdsContas.SaveToFile(GetCurrentDir + '\Contas.dat');
cdsNotas.SaveToFile(GetCurrentDir + '\Notas.dat');
end;
procedure TFrmPrincipal.FormKeyPress(Sender: TObject; var Key: Char);
begin
if FTela <> 4 then
Exit;
if StrToIntDef(Key, -1) > -1 then
FrmSaque.Tecla(StrToInt(Key));
// if Key = Char(VK_BACK) ;
end;
end.
|
{******************************************************************************}
{* fs_imvxrtti.pas *}
{* This module is part of Internal Project but is released under *}
{* the MIT License: http://www.opensource.org/licenses/mit-license.php *}
{* Copyright (c) 2006 by Jaimy Azle *}
{* All rights reserved. *}
{******************************************************************************}
{* Desc: *}
{******************************************************************************}
unit fs_imvxrtti;
interface
uses
SysUtils, Classes, fs_iinterpreter, fs_itools, fs_idbrtti,
DB, MvxCon;
implementation
type
TFunctions = class(TfsRTTIModule)
private
function CallMethod(Instance: TObject; ClassType: TClass;
const MethodName: String; Caller: TfsMethodHelper): Variant;
function GetProp(Instance: TObject; ClassType: TClass;
const PropName: String): Variant;
procedure SetProp(Instance: TObject; ClassType: TClass;
const PropName: String; Value: Variant);
public
constructor Create(AScript: TfsScript); override;
end;
{ TFunctions }
function TFunctions.CallMethod(Instance: TObject; ClassType: TClass;
const MethodName: String; Caller: TfsMethodHelper): Variant;
begin
Result := 0;
if ClassType = TMvxParams then
begin
if MethodName = 'ADD' then
Result := Integer(TMvxParams(Instance).Add)
else if MethodName = 'PARAMBYNAME' then
Result := Integer(TMvxParams(Instance).ParamByName(Caller.Params[0]))
else if MethodName = 'FINDPARAM' then
Result := Integer(TMvxParams(Instance).FindParam(Caller.Params[0]))
else if MethodName = 'ITEMS.GET' then
Result := Integer(TMvxParams(Instance).Items[Caller.Params[0]]);
end
end;
constructor TFunctions.Create(AScript: TfsScript);
begin
inherited Create(AScript);
with AScript do
begin
AddType('TDataType', fvtInt);
AddClass(TMvxConnection, 'TComponent');
with AddClass(TMvxParam, 'TCollectionItem') do
begin
AddProperty('Name', 'String', GetProp, SetProp);
AddProperty('Size', 'Integer', GetProp, SetProp);
AddProperty('DataType', 'TFieldType', GetProp, SetProp);
AddProperty('Mandatory', 'Boolean', GetProp, SetProp);
AddProperty('Value','Variant', GetProp, SetProp);
AddProperty('AsString','String', GetProp, SetProp);
AddProperty('AsInteger','Integer', GetProp, SetProp);
AddProperty('AsBCD','Currency', GetProp, SetProp);
end;
with AddClass(TMvxParams, 'TCollection') do
begin
AddMethod('function Add: TMvxParam', CallMethod);
AddMethod('function ParamByName(const Value: string): TParam', CallMethod);
AddMethod('function FindParam(const Value: string): TParam', CallMethod);
AddDefaultProperty('Items', 'Integer', 'TMvxParam', CallMethod, True);
end;
with AddClass(TMvxCustomDataset, 'TDataSet') do
begin
AddProperty('MIProgram', 'String', GetProp, SetProp);
AddProperty('MICommand', 'String', GetProp, SetProp);
end;
AddClass(TMvxDataset, 'TMvxCustomDataset');
end;
end;
function TFunctions.GetProp(Instance: TObject; ClassType: TClass;
const PropName: String): Variant;
begin
Result := 0;
if ClassType = TMvxParam then
begin
if PropName = 'NAME' then
Result := TMvxParam(Instance).Name
else
if PropName = 'SIZE' then
Result := TMvxParam(Instance).Size
else
if PropName = 'DATATYPE' then
Result := TMvxParam(Instance).DataType
else
if PropName = 'MANDATORY' then
Result := TMvxParam(Instance).Mandatory
else
if PropName = 'VALUE' then
Result := TMvxParam(Instance).Value
else
if PropName = 'ASSTRING' then
Result := TMvxParam(Instance).AsString
else
if PropName = 'ASINTEGER' then
Result := TMvxParam(Instance).AsInteger
else
if PropName = 'ASBCD' then
Result := TMvxParam(Instance).AsBCD
end else
if ClassType = TMvxCustomDataset then
begin
if PropName = 'MIPROGRAM' then
Result := TMvxDataset(Instance).MIProgram
else
if PropName = 'MICOMMAND' then
Result := TMvxDataset(Instance).MICommand;
end
end;
procedure TFunctions.SetProp(Instance: TObject; ClassType: TClass;
const PropName: String; Value: Variant);
begin
if ClassType = TMvxParam then
begin
if PropName = 'NAME' then
TMvxParam(Instance).Name := Value
else
if PropName = 'SIZE' then
TMvxParam(Instance).Size := Value
else
if PropName = 'DATATYPE' then
TMvxParam(Instance).DataType := Value
else
if PropName = 'MANDATORY' then
TMvxParam(Instance).Mandatory := Value
else
if PropName = 'VALUE' then
TMvxParam(Instance).Value := Value
else
if PropName = 'ASSTRING' then
TMvxParam(Instance).AsString := Value
else
if PropName = 'ASINTEGER' then
TMvxParam(Instance).AsInteger := Value
else
if PropName = 'ASBCD' then
TMvxParam(Instance).AsBCD := Value;
end else
if ClassType = TMvxCustomDataset then
begin
if PropName = 'MIPROGRAM' then
TMvxDataset(Instance).MIProgram := Value
else
if PropName = 'MICOMMAND' then
TMvxDataset(Instance).MICommand := Value;
end
end;
initialization
fsRTTIModules.Add(TFunctions);
finalization
fsRTTIModules.Remove(TFunctions);
end.
|
// ##################################
// ###### IT PAT 2018 #######
// ###### GrowCery #######
// ###### Tiaan van der Riel #######
// ##################################
unit frmPointOfSale_u;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Spin, StdCtrls, ExtCtrls, ComCtrls, Grids, DBGrids, pngimage,
DBCtrls, clsDisplayUserInfo_u, Printers;
const
MAX = 250;
type
TfrmPointOfSale = class(TForm)
imgLogo: TImage;
dbgStock: TDBGrid;
redTransactionSummary: TRichEdit;
pnlTransactionTotal: TPanel;
btn1: TButton;
btn2: TButton;
btn3: TButton;
btn4: TButton;
btn5: TButton;
btn6: TButton;
btn7: TButton;
btn8: TButton;
btn9: TButton;
btn0: TButton;
edtBarcode: TEdit;
lblSearchBarcode: TLabel;
btnNewSale: TButton;
btnVoidSale: TButton;
btnAddItem: TButton;
btnCheckout: TButton;
lblStockSearch: TLabel;
lblTransactionSummary: TLabel;
lblTellarInfo: TLabel;
lblTransactionTotalHeading: TLabel;
lblTransactionTotalAmount: TLabel;
imgCompanyName: TImage;
btnEndShift: TButton;
DBNavigator1: TDBNavigator;
btnBackspace: TButton;
procedure FormActivate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnVoidSaleClick(Sender: TObject);
procedure btnNewSaleClick(Sender: TObject);
procedure btnCheckoutClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnAddItemClick(Sender: TObject);
procedure btn1Click(Sender: TObject);
procedure btn2Click(Sender: TObject);
procedure btn3Click(Sender: TObject);
procedure btn4Click(Sender: TObject);
procedure btn5Click(Sender: TObject);
procedure btn6Click(Sender: TObject);
procedure btn7Click(Sender: TObject);
procedure btn8Click(Sender: TObject);
procedure btn9Click(Sender: TObject);
procedure btn0Click(Sender: TObject);
procedure edtBarcodeChange(Sender: TObject);
procedure btnBackspaceClick(Sender: TObject);
procedure btnEndShiftClick(Sender: TObject);
private
{ Private declarations }
objDisplayUserInfo: TDisplayUserInfo;
// Arrays
arrItemNames: array [1 .. MAX] of string;
arrUnitPrices: array [1 .. MAX] of real;
arrBarcodes: array [1 .. MAX] of string;
// Arrays that contain no duplicates
arrItemsNoDuplicates: array [1 .. MAX] Of string;
arrPricesNoDuplicates: array [1 .. MAX] of real;
arrBarcodesNoDuplicates: array [1 .. MAX] of string;
arrQTYNoDuplicates: array [1 .. MAX] of integer;
// Procedures
procedure DisableButtons;
// 1-2. Done as items are added
procedure UpdateTransactionSummary; // 1.)
procedure UpdateSaleTotal; // 2.)
// Part of checkout procedure
procedure RemoveDuplicates; // 3.)
procedure DetremineQuantities; // 4.)
procedure GenerateTransactionID; // 5.)
procedure CreateTillSlip; // 6.)
procedure PrintTillSlip; // 7.)
procedure SaveTransactionToDatabase; // 8.)
procedure ClearArrays;
procedure VoidCurrentSale;
public
{ Public declarations }
sLoggedOnUser: string;
sLoggedOnUserName: string;
sTodaysDate: string;
iNoOfElements: integer;
rTransactionTotal: real;
iNoElemntsWithoutDup: integer;
sNewTransactionID: string;
rTotalDue: real;
end;
var
frmPointOfSale: TfrmPointOfSale;
implementation
uses
frmTellerHomeScreen_u, dmDatabase_u;
{$R *.dfm}
/// =============================== New Sale Button ===========================
procedure TfrmPointOfSale.btnNewSaleClick(Sender: TObject);
{ The purpose of this piece of code is to enable all of the neccesary buttons
as soon as a sale is started, having the buttons disabled pefore a sale is
statred prevents the user from adding items to a sale that does not exist }
begin
Beep;
ShowMessage('NEW TRANSACTION STARTED.');
btnNewSale.Enabled := False;
btnVoidSale.Enabled := True;
btnAddItem.Enabled := True;
btnCheckout.Enabled := True;
btn0.Enabled := True;
btn1.Enabled := True;
btn2.Enabled := True;
btn3.Enabled := True;
btn4.Enabled := True;
btn5.Enabled := True;
btn6.Enabled := True;
btn7.Enabled := True;
btn8.Enabled := True;
btn9.Enabled := True;
redTransactionSummary.Lines.Add('Item Name:' + #9 + 'Unit Price:');
redTransactionSummary.Lines.Add(
'===========================================================');
end;
/// ===================== Button Add The Selected Item ========================
procedure TfrmPointOfSale.btnAddItemClick(Sender: TObject);
var
sSelectedItemName: string;
sSelectedItemPrice: string;
sSelectedItemBarcode: string;
begin
// Input
with dmDatabase do
Begin
sSelectedItemName := tblItems['ItemName'];
sSelectedItemPrice := tblItems['UnitPrice'];
sSelectedItemBarcode := tblItems['Barcode'];
End;
Inc(iNoOfElements);
if iNoOfElements <= MAX then
Begin
arrItemNames[iNoOfElements] := sSelectedItemName;
arrUnitPrices[iNoOfElements] := StrToFloat(sSelectedItemPrice);
arrBarcodes[iNoOfElements] := sSelectedItemBarcode;
/// /
UpdateTransactionSummary; // 1.)
UpdateSaleTotal; // 2.)
/// /
Windows.Beep(1000, 50);
End
else
// MAX number exceeded
begin
ShowMessage(
'You have exceded the maximum amount of items purchasable, please request the assistance of a manager.');
end;
end;
/// 1.) ================== Update The Transaction Summary =====================
procedure TfrmPointOfSale.UpdateTransactionSummary;
var
K: integer;
begin
redTransactionSummary.Lines.Clear;
redTransactionSummary.Lines.Add('Item Name:' + #9 + 'Unit Price:');
redTransactionSummary.Lines.Add(
'===========================================================');
for K := 1 to iNoOfElements do
Begin
redTransactionSummary.Lines.Add(arrItemNames[K] + #9 + FloatToStrF
(arrUnitPrices[K], ffCurrency, 8, 2));
End;
end;
/// 2.) ====================== Update Sale Total ==============================
procedure TfrmPointOfSale.UpdateSaleTotal;
var
K: integer;
begin
rTransactionTotal := 0;
for K := 1 to iNoOfElements do
Begin
rTransactionTotal := rTransactionTotal + arrUnitPrices[K];
lblTransactionTotalAmount.Caption := FloatToStrF
(rTransactionTotal, ffCurrency, 8, 2);
End;
if iNoOfElements = 0 then
Begin
lblTransactionTotalAmount.Caption := FloatToStrF
(0.00, ffCurrency, 8, 2);
End;
end;
/// ======================== Checkout Button ==================================
procedure TfrmPointOfSale.btnCheckoutClick(Sender: TObject);
begin
ShowMessage('Total Amount Due: ' + FloatToStr(rTransactionTotal));
ShowMessage('Printing till-slip');
RemoveDuplicates; // 3.)
DetremineQuantities; // 4.)
GenerateTransactionID; // 5.)
CreateTillSlip; // 6.)
PrintTillSlip; // 7.)
SaveTransactionToDatabase; // 8.)
end;
/// 3.) ==================== Procedure To Remove Duplicates ===================
procedure TfrmPointOfSale.RemoveDuplicates;
{ Each individual item`s name and unit price (as well as barcode when saved) is
only shown once on the till slip, and saved once in the database, together with the
'quantity' bought of each - the duplicates consequently need to be removed }
var
K: integer;
iCheck: integer;
bDup: boolean;
begin
iNoElemntsWithoutDup := 0;
for K := 1 to iNoOfElements - 1 do
Begin
iCheck := K + 1;
bDup := False;
while (iCheck <= iNoOfElements) AND (NOT bDup) do
begin
if arrItemNames[K] = arrItemNames[iCheck] then
bDup := True
else
Inc(iCheck);
end; // while
if NOT(bDup) then
begin
Inc(iNoElemntsWithoutDup);
arrItemsNoDuplicates[iNoElemntsWithoutDup] := arrItemNames[K];
arrPricesNoDuplicates[iNoElemntsWithoutDup] := arrUnitPrices[K];
arrBarcodesNoDuplicates[iNoElemntsWithoutDup] := arrBarcodes[K];
end;
End; // for
// The last item cannot be compared to anythin and has to be added
Inc(iNoElemntsWithoutDup);
arrItemsNoDuplicates[iNoElemntsWithoutDup] := arrItemNames[iNoOfElements];
arrPricesNoDuplicates[iNoElemntsWithoutDup] := arrUnitPrices[iNoOfElements];
arrBarcodesNoDuplicates[iNoElemntsWithoutDup] := arrBarcodes[iNoOfElements];
{ ///////////// Testing purposes //////////////////
redTransactionSummary.Lines.Add(
'===========================================================');
for K := 1 to iNoElemntsWithoutDup do
Begin
redTransactionSummary.Lines.Add(arrItemsNoDuplicates[K] + #9 + FloatToStrF
(arrPricesNoDuplicates[K], ffCurrency, 8, 2));
End;
}
end;
/// 4.) ======= Procedure To Determine The Quantity Of Each Item ==============
procedure TfrmPointOfSale.DetremineQuantities;
{ This procedur checks each item in the array without duplicates, and sees how many
times each unique record appears in the array with duplicates, in order to determine
the 'quantity' of that item purchased
- This needs to be done since each unique item bought is only showed once on the
till slip and saved once in the database, together with the 'Quantity' of each bought }
var
K: integer; // Counter - Outer Loop
sTemp: string;
L: integer; // Counter - Inner Loop
begin
for K := 1 to iNoElemntsWithoutDup do
Begin
sTemp := arrItemsNoDuplicates[K];
for L := 1 to iNoOfElements do
Begin
if sTemp = arrItemNames[L] then
arrQTYNoDuplicates[K] := arrQTYNoDuplicates[K] + 1;
End; // For - inner loop
End; // For outer loop
{ ///////////// Testing purposes //////////////////
redTransactionSummary.Lines.Add(
'===========================================================');
for K := 1 to iNoElemntsWithoutDup do
Begin
redTransactionSummary.Lines.Add(arrItemsNoDuplicates[K] + #9 + IntToStr
(arrQTYNoDuplicates[K]));
End;
redTransactionSummary.Lines.Add(
'===========================================================');
}
end;
/// 5.) ====================== Genrate Transaction ID =========================
procedure TfrmPointOfSale.GenerateTransactionID;
var
iTemp: integer;
iHighest: integer;
iNoOfZeros: integer;
K: integer;
begin
// Get all of the appropriate TransactionIDs
with dmDatabase do
Begin
dsrTransactions.DataSet := qryTransactions;
qryTransactions.SQL.Clear;
qryTransactions.SQL.Add('SELECT AccountID, DateOfTransaction, TransID ');
qryTransactions.SQL.Add('FROM Transactions ');
qryTransactions.SQL.Add(' WHERE (AccountID = ' + QuotedStr(sLoggedOnUser)
+ ')');
qryTransactions.SQL.Add(' AND (DateOfTransaction = ' + QuotedStr
(sTodaysDate) + ')');
qryTransactions.SQL.Add(' GROUP BY TransID, AccountID, DateOfTransaction ');
qryTransactions.Open;
// Determine the highest item index for the day
iHighest := 0;
iTemp := 0;
while NOT qryTransactions.Eof do
begin
iTemp := StrToInt(Copy(qryTransactions['TransID'], 9, 4));
if iTemp > iHighest then
Begin
iHighest := iTemp;
End;
qryTransactions.Next;
end;
qryTransactions.First;
End;
// Fomat all the data into the TransactionID
sNewTransactionID := Copy(sTodaysDate, 1, 4) + Copy(sTodaysDate, 6, 2) + Copy
(sTodaysDate, 9, 2);
iNoOfZeros := 4 - Length(IntToStr(iHighest));
for K := 1 to iNoOfZeros do
Begin
sNewTransactionID := sNewTransactionID + '0';
End;
sNewTransactionID := sNewTransactionID + IntToStr(iHighest + 1);
// Inc Highest
sNewTransactionID := sNewTransactionID + Copy(sLoggedOnUser, 1, 2);
// ShowMessage(sNewTransactionID);
end;
/// 6.) =========================== Create Till Slip ==========================
procedure TfrmPointOfSale.CreateTillSlip;
var
TillSlip: TextFile;
K: integer;
rTotalVatEXCL: real;
rTotalVAT: real;
begin
AssignFile(TillSlip, sNewTransactionID + '.txt');
Rewrite(TillSlip);
Writeln(TillSlip, '');
Writeln(TillSlip,
' GrowCery ');
Writeln(TillSlip,
' Protea Heights ');
Writeln(TillSlip,
' 021 982 4774 ');
Writeln(TillSlip, '');
Writeln(TillSlip, 'Cashier ID: ' + sLoggedOnUser);
Writeln(TillSlip, 'Cashier Name: ' + sLoggedOnUserName);
Writeln(TillSlip,
'=================================================================');
Writeln(TillSlip, '');
Writeln(TillSlip,
'ITEM: QTY: PRICE: ');
// Adds all of the items
for K := 1 to iNoElemntsWithoutDup do
Begin
Writeln(TillSlip, arrItemsNoDuplicates[K], ' ':51 - Length
(arrItemsNoDuplicates[K]), IntToStr(arrQTYNoDuplicates[K]),
' ':6 - Length(IntToStr(arrQTYNoDuplicates[K])), FloatToStr
(arrPricesNoDuplicates[K]));
End;
Writeln(TillSlip, '');
Writeln(TillSlip, 'TOTAL DUE:', ' ':57 - Length('TOTAL DUE:'), FloatToStr
(rTransactionTotal));
/// VAT
Writeln(TillSlip,
'============================TAX INVOICE==========================');
Writeln(TillSlip,
'VAT RATE: 15.00% ');
rTotalVatEXCL := rTransactionTotal / (1 + 0.15);
rTotalVAT := rTransactionTotal - rTotalVatEXCL;
///
Writeln(TillSlip, 'TOTAL VAT INCL:', ' ':57 - Length('TOTAL VAT INCL:'),
FloatToStr(rTransactionTotal));
Writeln(TillSlip, 'TOTAL VAT EXCL:', ' ':57 - Length('TOTAL VAT EXCL:'),
FloatToStrF(rTotalVatEXCL, ffNumber, 8, 2));
Writeln(TillSlip, 'TOTAL VAT:', ' ':57 - Length('TOTAL VAT:'), FloatToStrF
(rTotalVAT, ffNumber, 8, 2)); ;
Writeln(TillSlip, '');
Writeln(TillSlip, 'Vat No. 49101756960 ');
Writeln(TillSlip,
'=================================================================');
Writeln(TillSlip,
'Date: Time: ');
Writeln(TillSlip, sTodaysDate, ' ':54 - 10, TimeToStr(Time));
Writeln(TillSlip,
'=================================================================');
Writeln(TillSlip, ' Thank you');
Writeln(TillSlip, ' for shopping with us.');
CloseFile(TillSlip);
end;
/// 7.) ======================== Print Till Slip ==============================
procedure TfrmPointOfSale.PrintTillSlip;
var
printDialog: TPrintDialog;
myPrinter: TPrinter;
//
sLine: string;
tTillSlip: TextFile;
//
y: integer; { This variable determines the location of the line on the y-axis
of the till slip }
begin
// Create a printer selection dialog
printDialog := TPrintDialog.Create(frmPointOfSale);
if printDialog.Execute then
begin
myPrinter := printer;
with myPrinter do
begin
// Start the page
BeginDoc;
Canvas.Font.Name := 'Consolas';
Canvas.Font.Size := 9;
Canvas.Font.Color := clBlack;
// Find the till slip
AssignFile(tTillSlip, sNewTransactionID + '.txt');
Try
Reset(tTillSlip);
Except
ShowMessage(
'The till slip could not be found. Please request a manager for assistance');
Exit;
End;
// Write out the till slip
y := 300;
while NOT Eof(tTillSlip) do
begin
Readln(tTillSlip, sLine);
y := y + 100;
Canvas.TextOut(200, y, sLine);
end;
// Finish printing
EndDoc;
CloseFile(tTillSlip);
end;
end;
end;
/// 8.) ================= Save Transaction To Database ========================
procedure TfrmPointOfSale.SaveTransactionToDatabase;
{ The functio of this procedure is to save all of the items purchased in the
transaction into the database }
var
K: integer;
begin
with dmDatabase do
Begin
tblTransactions.Open;
tblTransactions.Last;
tblTransactions.Insert;
tblTransactions['TransID'] := sNewTransactionID;
tblTransactions['AccountID'] := sLoggedOnUser;
tblTransactions['ProcessedBy'] := sLoggedOnUserName;
tblTransactions['DateOfTransaction'] := sTodaysDate;
tblTransactions.Post;
///
tblItemTransactions.Open;
for K := 1 to iNoElemntsWithoutDup do
Begin
tblItemTransactions.Last;
tblItemTransactions.Insert;
tblItemTransactions['TransID'] := sNewTransactionID;
tblItemTransactions['Barcode'] := arrBarcodesNoDuplicates[K];
tblItemTransactions['ItemName'] := arrItemsNoDuplicates[K];
tblItemTransactions['Quantity'] := arrQTYNoDuplicates[K];
tblItemTransactions['UnitPrice'] := arrPricesNoDuplicates[K];
tblItemTransactions.Post;
end;
End;
ShowMessage('Items Added To Database.');
end;
/// ========================= Form Gets Activated =============================
procedure TfrmPointOfSale.FormActivate(Sender: TObject);
var
sTellarInfo: string;
begin
sLoggedOnUser := frmTellerHomeScreen.sLoggedOnUser;
sLoggedOnUserName := frmTellerHomeScreen.sLoggedOnUserName;
sTodaysDate := frmTellerHomeScreen.sTodaysDate;
// Get the full name of the logged on user
// Object to display user information
objDisplayUserInfo := TDisplayUserInfo.Create(sLoggedOnUser);
lblTellarInfo.Caption := objDisplayUserInfo.ToString;
objDisplayUserInfo.Free;
lblTellarInfo.Caption := lblTellarInfo.Caption + #13 + 'Today`s date: ' +
sTodaysDate;
lblTellarInfo.Font.Color := rgb(161, 255, 94);
//
DisableButtons;
//
with redTransactionSummary do
begin
Paragraph.TabCount := 3;
Paragraph.Tab[0] := 292;
Paragraph.Tab[1] := 330;
Font.Size := 9;
end;
imgLogo.Height := 83;
end;
/// =============== Procedure That Disables All Of The Buttons ================
procedure TfrmPointOfSale.DisableButtons;
begin
btnNewSale.Enabled := True;
btnVoidSale.Enabled := False;
btnAddItem.Enabled := False;
btnCheckout.Enabled := False;
btn0.Enabled := False;
btn1.Enabled := False;
btn2.Enabled := False;
btn3.Enabled := False;
btn4.Enabled := False;
btn5.Enabled := False;
btn6.Enabled := False;
btn7.Enabled := False;
btn8.Enabled := False;
btn9.Enabled := False;
redTransactionSummary.Lines.Clear;
end;
/// ============================== Form Gets Closed ===========================
procedure TfrmPointOfSale.FormClose(Sender: TObject; var Action: TCloseAction);
begin
ShowMessage('Ending your shift.');
// The user closes the form while a sale is still in progress
if rTransactionTotal > 0 then
Begin
MessageDlg('You are leaving while a sale is still in progress.' + #13 +
'THE CURRENT SALE WILL BE VOIDED', mtWarning, [mbOK], 0);
VoidCurrentSale;
end;
frmTellerHomeScreen.Show;
end;
/// ============================= Void Sale Button ============================
procedure TfrmPointOfSale.btnVoidSaleClick(Sender: TObject);
begin
begin
if MessageDlg(' Are you sure you want to void the current sale ?',
mtWarning, [mbYes, mbCancel], 0) = mrYes then
begin
VoidCurrentSale;
end
else
Exit
end;
end;
/// ==================== Void Current Sale Procedure ==========================
procedure TfrmPointOfSale.VoidCurrentSale;
begin
ShowMessage('VOIDING SALE.');
DisableButtons;
/// CLEAR THE ARRAYS
ClearArrays;
redTransactionSummary.Lines.Clear;
/// Set Total back to 0 and display it
rTransactionTotal := 0;
UpdateSaleTotal;
ShowMessage('Sale Successfully voided');
end;
/// ==================== Procedure To Clear The Arrays ========================
procedure TfrmPointOfSale.ClearArrays;
var
i: integer;
begin
for i := 1 to iNoOfElements do
Begin
arrItemNames[i] := '';
arrUnitPrices[i] := 0;
arrBarcodes[i] := '';
End;
iNoOfElements := 0;
end;
/// =========================== Form Gets Shown ===============================
procedure TfrmPointOfSale.FormShow(Sender: TObject);
begin
with dmDatabase do
begin
tblItems.Open;
tblItems.First;
end;
iNoOfElements := 0;
end;
/// =================== Search For A Spesific Barcode =========================
procedure TfrmPointOfSale.edtBarcodeChange(Sender: TObject);
{ This porcedure is used to search, and filter the table of items, to
display the smilar barcodes, as the user types a barcode into the edit field }
begin
if (edtBarcode.Text <> '') then
Begin
dmDatabase.tblItems.Filter := 'Barcode LIKE ''' + (edtBarcode.Text)
+ '%'' ';
dmDatabase.tblItems.Filtered := True;
End
else
begin
dmDatabase.tblItems.Filtered := False;
end;
end;
/// ============================= Buttons 0 - 9 ===============================
procedure TfrmPointOfSale.btn0Click(Sender: TObject);
begin
edtBarcode.Text := edtBarcode.Text + '0';
end;
procedure TfrmPointOfSale.btn1Click(Sender: TObject);
begin
edtBarcode.Text := edtBarcode.Text + '1';
end;
procedure TfrmPointOfSale.btn2Click(Sender: TObject);
begin
edtBarcode.Text := edtBarcode.Text + '2';
end;
procedure TfrmPointOfSale.btn3Click(Sender: TObject);
begin
edtBarcode.Text := edtBarcode.Text + '3';
end;
procedure TfrmPointOfSale.btn4Click(Sender: TObject);
begin
edtBarcode.Text := edtBarcode.Text + '4';
end;
procedure TfrmPointOfSale.btn5Click(Sender: TObject);
begin
edtBarcode.Text := edtBarcode.Text + '5';
end;
procedure TfrmPointOfSale.btn6Click(Sender: TObject);
begin
edtBarcode.Text := edtBarcode.Text + '6';
end;
procedure TfrmPointOfSale.btn7Click(Sender: TObject);
begin
edtBarcode.Text := edtBarcode.Text + '7';
end;
procedure TfrmPointOfSale.btn8Click(Sender: TObject);
begin
edtBarcode.Text := edtBarcode.Text + '8';
end;
procedure TfrmPointOfSale.btn9Click(Sender: TObject);
begin
edtBarcode.Text := edtBarcode.Text + '9';
end;
/// ========================== Backspace Button ===============================
procedure TfrmPointOfSale.btnBackspaceClick(Sender: TObject);
begin
edtBarcode.Text := Copy(edtBarcode.Text, 1, Length(edtBarcode.Text) - 1);
end;
/// ========================== Exit POS Button ================================
procedure TfrmPointOfSale.btnEndShiftClick(Sender: TObject);
begin
if MessageDlg(' Are you sure you want exit your POS ?', mtConfirmation,
[mbYes, mbCancel], 0) = mrYes then
begin
frmPointOfSale.Close;
end
else
Exit
end;
end.
|
unit Demo.AnnotationChart.Sample;
interface
uses
System.Classes, System.SysUtils, System.Variants, Demo.BaseFrame, cfs.GCharts;
type
TDemo_AnnotationChart_Sample = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_AnnotationChart_Sample.GenerateChart;
var
Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_ANNOTATION_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtDate, 'Date'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Kepler-22b mission'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Kepler title'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Kepler text'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, 'Gliese 163 mission'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Gliese title'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Gliese text')
]);
Chart.Data.AddRow([EncodeDate(2314, 3, 15), 12400, null, null, 10645, null, null]);
Chart.Data.AddRow([EncodeDate(2314, 3, 16), 24045, 'Lalibertines', 'First encounter', 12374, null, null]);
Chart.Data.AddRow([EncodeDate(2314, 3, 17), 35022, 'Lalibertines', 'They are very tall', 15766, 'Gallantors', 'First Encounter']);
Chart.Data.AddRow([EncodeDate(2314, 3, 18), 12284, 'Lalibertines', 'Attack on our crew!', 34334, 'Gallantors', 'Statement of shared principles']);
Chart.Data.AddRow([EncodeDate(2314, 3, 19), 8476, 'Lalibertines', 'Heavy casualties', 66467, 'Gallantors', 'Mysteries revealed']);
Chart.Data.AddRow([EncodeDate(2314, 3, 20), 0, 'Lalibertines', 'All crew lost', 79463, 'Gallantors', 'Omniscience achieved']);
// Options
Chart.Options.DisplayAnnotations(True);
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody(
'<div style="width:80%; height:10%"></div>' +
'<div id="Chart1" style="width:80%; height:80%;margin: auto"></div>' +
'<div style="width:80%; height:10%"></div>'
);
GChartsFrame.DocumentGenerate('Chart1', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_AnnotationChart_Sample);
end.
|
unit QuestionsInterview;
interface
uses
System.SysUtils;
type
TSampleInterview = class
public
class function IsOdd( const ANumber: Integer ): Boolean;
class function IsPowerTwo(const ANumber: Integer): Boolean; static;
end;
implementation
{ TSampleInterview }
class function TSampleInterview.IsOdd(const ANumber: Integer):
Boolean;
begin
Result := (ANumber mod 2) = 0;
end;
class function TSampleInterview.IsPowerTwo(
const ANumber: Integer): Boolean;
begin
Result:= ANumber = 2;
end;
end.
|
//*******************************************************//
// //
// DelphiFlash.com //
// Copyright (c) 2004-2007 FeatherySoft, Inc. //
// info@delphiflash.com //
// //
//*******************************************************//
// Description: Standart ActionScript classes name
// Last update: 7 jun 2007
Unit StdClassName;
interface
uses Windows, SysUtils;
function IsStandartClassName(Name: string): boolean;
implementation
const
StdNamesCount = 75;
AStdNames : array [0..StdNamesCount - 1] of PChar = (
// root
'toplevel',
//FP7
'Accessibility',
'Array',
'AsBroadcaster',
'Boolean',
'Button',
'Camera',
'Color',
'ContextMenu',
'ContextMenuItem',
'CustomActions',
'Date',
'Enumeration',
'Error',
'File',
'FontName',
'Function',
'FunctionArguments',
'Key',
'LoadVars',
'LocalConnection',
'Math',
'Microphone',
'Mouse',
'MovieClip',
'MovieClipLoader',
'NetConnection',
'NetStream',
'Number',
'Object',
'ObjectID',
'PrintJob',
'Selection',
'SharedObject',
'Sound',
'Stage',
'String',
'System',
'System.capabilities',
'System.security',
'TextField',
'TextField.StyleSheet',
'TextFormat',
'TextSnapshot',
'URI',
'Video',
'XML',
'XMLNode',
'XMLSocket',
'XMLUI',
//fp8
'flash.display.BitmapData',
'flash.external.ExternalInterface',
'flash.filters.BevelFilter',
'flash.filters.BitmapFilter',
'flash.filters.BlurFilter',
'flash.filters.ColorMatrixFilter',
'flash.filters.ConvolutionFilter',
'flash.filters.DisplacementMapFilter',
'flash.filters.DropShadowFilter',
'flash.filters.GlowFilter',
'flash.filters.GradientBevelFilter',
'flash.filters.GradientGlowFilter',
'flash.geom.ColorTransform',
'flash.geom.Matrix',
'flash.geom.Point',
'flash.geom.Rectangle',
'flash.geom.Transform',
'flash.net.FileReference',
'flash.net.FileReferenceList',
'flash.text.TextRenderer',
'System.IME',
// not classes
'mx.core.ComponentVersion',
'mx.video.ComponentVersion',
'mx.video.MediaComponentVersion',
'mx.transitions.Version'
//fp9
{ no unique classes }
);
function IsStandartClassName(Name: string): boolean;
var
il: integer;
begin
Result := false;
for il := 0 to StdNamesCount - 1 do
if lowercase(Name) = lowercase(AStdNames[il]) then
begin
Result := true;
Break;
end;
end;
end. |
unit UDSectionFormat;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, UCrpe32;
type
TCrpeSectionFormatDlg = class(TForm)
pnlSectionFormat: TPanel;
lblSection: TLabel;
cbPrintAtBottomOfPage: TCheckBox;
cbNewPageBefore: TCheckBox;
cbNewPageAfter: TCheckBox;
cbResetPageNAfter: TCheckBox;
cbKeepTogether: TCheckBox;
cbSuppressBlankSection: TCheckBox;
cbUnderlaySection: TCheckBox;
cbSuppress: TCheckBox;
cbFreeFormPlacement: TCheckBox;
lbSections: TListBox;
btnOk: TButton;
sbSuppress: TSpeedButton;
sbPrintAtBottomOfPage: TSpeedButton;
sbNewPageBefore: TSpeedButton;
sbNewPageAfter: TSpeedButton;
sbResetPageNAfter: TSpeedButton;
sbKeepTogether: TSpeedButton;
sbSuppressBlankSection: TSpeedButton;
sbUnderlaySection: TSpeedButton;
sbFormulaRed: TSpeedButton;
sbFormulaBlue: TSpeedButton;
lblCount: TLabel;
editCount: TEdit;
gbBackgroundColor: TGroupBox;
lblRed: TLabel;
lblGreen: TLabel;
lblBlue: TLabel;
editRed: TEdit;
editGreen: TEdit;
editBlue: TEdit;
cbBackgroundColor: TCheckBox;
sbBackgroundColor: TSpeedButton;
colorboxBackgroundColor: TColorBox;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure lbSectionsClick(Sender: TObject);
procedure cbCommonClick(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure UpdateSectionFormat;
procedure sbFormulaButtonClick(Sender: TObject);
procedure InitializeControls(OnOff: boolean);
procedure colorboxBackgroundColorChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
SFIndex : smallint;
end;
var
CrpeSectionFormatDlg: TCrpeSectionFormatDlg;
bSectionFormat : boolean;
implementation
{$R *.DFM}
uses UCrpeUtl, UDFormulaEdit;
{------------------------------------------------------------------------------}
{ FormCreate }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFormatDlg.FormCreate(Sender: TObject);
begin
bSectionFormat := True;
LoadFormPos(Self);
btnOk.Tag := 1;
SFIndex := -1;
end;
{------------------------------------------------------------------------------}
{ FormShow }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFormatDlg.FormShow(Sender: TObject);
begin
UpdateSectionFormat;
end;
{------------------------------------------------------------------------------}
{ UpdateSectionFormat }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFormatDlg.UpdateSectionFormat;
var
OnOff : boolean;
begin
{Enable/Disable controls}
if IsStrEmpty(Cr.ReportName) then
begin
OnOff := False;
SFIndex := -1;
end
else
begin
OnOff := (Cr.SectionFormat.Count > 0);
{Get SectionFormat Index}
if OnOff then
begin
if Cr.SectionFormat.ItemIndex > -1 then
SFIndex := Cr.SectionFormat.ItemIndex
else
SFIndex := 0;
end;
end;
InitializeControls(OnOff);
if OnOff then
begin
lbSections.Clear;
lbSections.Items.AddStrings(Cr.SectionFormat.Names);
editCount.Text := IntToStr(Cr.SectionFormat.Count);
lbSections.ItemIndex := SFIndex;
lbSectionsClick(self);
end;
end;
{------------------------------------------------------------------------------}
{ InitializeControls }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFormatDlg.InitializeControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
if TComponent(Components[i]).Tag = 0 then
begin
if Components[i] is TButton then
TButton(Components[i]).Enabled := OnOff;
if Components[i] is TSpeedButton then
TSpeedButton(Components[i]).Enabled := OnOff;
if Components[i] is TCheckBox then
TCheckBox(Components[i]).Enabled := OnOff;
if Components[i] is TListBox then
begin
TListBox(Components[i]).Clear;
TListBox(Components[i]).Color := ColorState(OnOff);
TListBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TEdit then
begin
TEdit(Components[i]).Text := '';
if TEdit(Components[i]).ReadOnly = False then
TEdit(Components[i]).Color := ColorState(OnOff);
TEdit(Components[i]).Enabled := OnOff;
end;
end;
end;
end;
{------------------------------------------------------------------------------}
{ lbSectionsClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFormatDlg.lbSectionsClick(Sender: TObject);
var
i : integer;
sTmp : string;
s1 : string;
s2 : string;
begin
SFIndex := lbSections.ItemIndex;
{Disable events}
for i := 0 to ComponentCount - 1 do
begin
if Components[i] is TCheckBox then
TCheckBox(Components[i]).OnClick := nil;
end;
{Set the CheckBoxes from the VCL settings}
cbFreeFormPlacement.Checked := Cr.SectionFormat[SFIndex].FreeFormPlacement;
cbSuppress.Checked := Cr.SectionFormat.Item.Suppress;
cbPrintAtBottomOfPage.Checked := Cr.SectionFormat.Item.PrintAtBottomOfPage;
cbNewPageBefore.Checked := Cr.SectionFormat.Item.NewPageBefore;
cbNewPageAfter.Checked := Cr.SectionFormat.Item.NewPageAfter;
cbResetPageNAfter.Checked := Cr.SectionFormat.Item.ResetPageNAfter;
cbKeepTogether.Checked := Cr.SectionFormat.Item.KeepTogether;
cbSuppressBlankSection.Checked := Cr.SectionFormat.Item.SuppressBlankSection;
cbUnderlaySection.Checked := Cr.SectionFormat.Item.UnderlaySection;
{Disable inapplicable items for the section}
{Subreport RHb/RFb have same limitations as PH on main report}
if (Cr.Subreports.ItemIndex > 0) then
begin
if (CompareText(UpperCase(Cr.SectionFormat.Item.Section),'RHB') = 0) or
(CompareText(UpperCase(Cr.SectionFormat.Item.Section),'RFB') = 0) then
sTmp := 'PH'
end
else
sTmp := Cr.SectionFormat.Item.SectionType;
{if the Section is Page Header or Page Footer, or RHb on Subreport...}
if (sTmp = 'PH') or (sTmp = 'PF') then
begin
{Disable: PrintAtBottomOfPage, NewPageAfter,
NewPageBefore, KeepTogether}
cbPrintAtBottomOfPage.Enabled := False;
cbNewPageAfter.Enabled := False;
cbNewPageBefore.Enabled := False;
cbKeepTogether.Enabled := False;
end
else
begin
{enable the 4 options as required}
{PrintAtBottomOfPage}
if cbPrintAtBottomOfPage.Enabled = False then
cbPrintAtBottomOfPage.Enabled := True;
{NewPageAfter}
if cbNewPageAfter.Enabled = False then
cbNewPageAfter.Enabled := True;
{NewPageBefore}
if cbNewPageBefore.Enabled = False then
cbNewPageBefore.Enabled := True;
{KeepTogether}
if cbKeepTogether.Enabled = False then
cbKeepTogether.Enabled := True;
end;
{Update the BackgroundColor on the Form}
if Cr.SectionFormat.Item.BackgroundColor = clNone then
begin
cbBackgroundColor.Checked := False;
editRed.Text := '';
editGreen.Text := '';
editBlue.Text := '';
colorboxBackgroundColor.Selected := Cr.SectionFormat.Item.BackgroundColor;
colorboxBackgroundColor.Enabled := False;
end
else
begin
cbBackgroundColor.OnClick := nil;
cbBackgroundColor.Checked := True;
cbBackgroundColor.OnClick := cbCommonClick;
colorboxBackgroundColor.Selected := Cr.SectionFormat.Item.BackgroundColor;
{List the Background color RGB values for the Section}
editRed.Text := IntToStr(Round(GetRValue(Cr.SectionFormat.Item.BackgroundColor)));
editGreen.Text := IntToStr(Round(GetGValue(Cr.SectionFormat.Item.BackgroundColor)));
editBlue.Text := IntToStr(Round(GetBValue(Cr.SectionFormat.Item.BackgroundColor)));
end;
if cbBackgroundColor.Checked then
colorboxBackgroundColor.Enabled := True;
{Determine the section area: Subreports RHb,RFb are same as PH/PF}
if Cr.Subreports.ItemIndex > 0 then
begin
if UpperCase(Cr.SectionFormat.Item.Section) = 'RHB' then
s1 := 'PH';
if UpperCase(Cr.SectionFormat.Item.Section) = 'RFB' then
s1 := 'PF';
end
else
s1 := UpperCase(Cr.SectionFormat.Item.SectionType);
{Set Formula Button glyphs: check first 4 for PH/PF}
{NewPageBefore}
if Pos(s1, 'PHPF') = 0 then
begin
if not sbNewPageBefore.Enabled then
sbNewPageBefore.Enabled := True;
{If the formula has text...}
s2 := RTrimList(Cr.SectionFormat.Item.Formulas.NewPageBefore);
if Length(s2) > 0 then
begin
if sbNewPageBefore.Tag <> 1 then
begin
sbNewPageBefore.Glyph := sbFormulaRed.Glyph;
sbNewPageBefore.Tag := 1;
end;
end
else
begin
if sbNewPageBefore.Tag <> 0 then
begin
sbNewPageBefore.Glyph := sbFormulaBlue.Glyph;
sbNewPageBefore.Tag := 0;
end;
end;
end
else
begin
if sbNewPageBefore.Enabled then
sbNewPageBefore.Enabled := False;
end;
{NewPageAfter}
if Pos(s1, 'PHPF') = 0 then
begin
if not sbNewPageAfter.Enabled then
sbNewPageAfter.Enabled := True;
s2 := RTrimList(Cr.SectionFormat.Item.Formulas.NewPageAfter);
if Length(s2) > 0 then
begin
if sbNewPageAfter.Tag <> 1 then
begin
sbNewPageAfter.Glyph := sbFormulaRed.Glyph;
sbNewPageAfter.Tag := 1;
end;
end
else
begin
if sbNewPageAfter.Tag <> 0 then
begin
sbNewPageAfter.Glyph := sbFormulaBlue.Glyph;
sbNewPageAfter.Tag := 0;
end;
end;
end
else
begin
if sbNewPageAfter.Enabled then
sbNewPageAfter.Enabled := False;
end;
{KeepTogether}
if Pos(s1, 'PHPF') = 0 then
begin
if not sbKeepTogether.Enabled then
sbKeepTogether.Enabled := True;
s2 := RTrimList(Cr.SectionFormat.Item.Formulas.KeepTogether);
if Length(s2) > 0 then
begin
if sbKeepTogether.Tag <> 1 then
begin
sbKeepTogether.Glyph := sbFormulaRed.Glyph;
sbKeepTogether.Tag := 1;
end;
end
else
begin
if sbKeepTogether.Tag <> 0 then
begin
sbKeepTogether.Glyph := sbFormulaBlue.Glyph;
sbKeepTogether.Tag := 0;
end;
end;
end
else
begin
if sbKeepTogether.Enabled then
sbKeepTogether.Enabled := False;
end;
{PrintAtBottomOfPage}
if Pos(s1, 'PHPF') = 0 then
begin
if not sbPrintAtBottomOfPage.Enabled then
sbPrintAtBottomOfPage.Enabled := True;
s2 := RTrimList(Cr.SectionFormat.Item.Formulas.PrintAtBottomOfPage);
if Length(s2) > 0 then
begin
if sbPrintAtBottomOfPage.Tag <> 1 then
begin
sbPrintAtBottomOfPage.Glyph := sbFormulaRed.Glyph;
sbPrintAtBottomOfPage.Tag := 1;
end;
end
else
begin
if sbPrintAtBottomOfPage.Tag <> 0 then
begin
sbPrintAtBottomOfPage.Glyph := sbFormulaBlue.Glyph;
sbPrintAtBottomOfPage.Tag := 0;
end;
end;
end
else
begin
if sbPrintAtBottomOfPage.Enabled then
sbPrintAtBottomOfPage.Enabled := False;
end;
{Suppress}
s2 := RTrimList(Cr.SectionFormat.Item.Formulas.Suppress);
if Length(s2) > 0 then
begin
if sbSuppress.Tag <> 1 then
begin
sbSuppress.Glyph := sbFormulaRed.Glyph;
sbSuppress.Tag := 1;
end;
end
else
begin
if sbSuppress.Tag <> 0 then
begin
sbSuppress.Glyph := sbFormulaBlue.Glyph;
sbSuppress.Tag := 0;
end;
end;
{SuppressBlankSection}
s2 := RTrimList(Cr.SectionFormat.Item.Formulas.SuppressBlankSection);
if Length(s2) > 0 then
begin
if sbSuppressBlankSection.Tag <> 1 then
begin
sbSuppressBlankSection.Glyph := sbFormulaRed.Glyph;
sbSuppressBlankSection.Tag := 1;
end;
end
else
begin
if sbSuppressBlankSection.Tag <> 0 then
begin
sbSuppressBlankSection.Glyph := sbFormulaBlue.Glyph;
sbSuppressBlankSection.Tag := 0;
end;
end;
{ResetPageNAfter}
s2 := RTrimList(Cr.SectionFormat.Item.Formulas.ResetPageNAfter);
if Length(s2) > 0 then
begin
if sbResetPageNAfter.Tag <> 1 then
begin
sbResetPageNAfter.Glyph := sbFormulaRed.Glyph;
sbResetPageNAfter.Tag := 1;
end;
end
else
begin
if sbResetPageNAfter.Tag <> 0 then
begin
sbResetPageNAfter.Glyph := sbFormulaBlue.Glyph;
sbResetPageNAfter.Tag := 0;
end;
end;
{UnderlaySection}
s2 := RTrimList(Cr.SectionFormat.Item.Formulas.UnderlaySection);
if Length(s2) > 0 then
begin
if sbUnderlaySection.Tag <> 1 then
begin
sbUnderlaySection.Glyph := sbFormulaRed.Glyph;
sbUnderlaySection.Tag := 1;
end;
end
else
begin
if sbUnderlaySection.Tag <> 0 then
begin
sbUnderlaySection.Glyph := sbFormulaBlue.Glyph;
sbUnderlaySection.Tag := 0;
end;
end;
{BackgroundColor}
s2 := RTrimList(Cr.SectionFormat.Item.Formulas.BackgroundColor);
if Length(s2) > 0 then
begin
if sbBackgroundColor.Tag <> 1 then
begin
sbBackgroundColor.Glyph := sbFormulaRed.Glyph;
sbBackgroundColor.Tag := 1;
end;
end
else
begin
if sbBackgroundColor.Tag <> 0 then
begin
sbBackgroundColor.Glyph := sbFormulaBlue.Glyph;
sbBackgroundColor.Tag := 0;
end;
end;
{Enable events}
for i := 0 to ComponentCount - 1 do
begin
if Components[i] is TCheckBox then
TCheckBox(Components[i]).OnClick := cbCommonClick;
end;
end;
{------------------------------------------------------------------------------}
{ cbCommonClick procedure }
{ - OnClick event for the SectionFormat checkboxes }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFormatDlg.cbCommonClick(Sender: TObject);
var
i : integer;
begin
if not (Sender is TCheckBox) then Exit;
i := Cr.SectionFormat.ItemIndex;
{Update the VCL}
if TCheckBox(Sender).Name = 'cbFreeFormPlacement' then
Cr.SectionFormat[i].FreeFormPlacement := TCheckBox(Sender).Checked
else if TCheckBox(Sender).Name = 'cbSuppress' then
Cr.SectionFormat[i].Suppress := TCheckBox(Sender).Checked
else if TCheckBox(Sender).Name = 'cbPrintAtBottomOfPage' then
Cr.SectionFormat[i].PrintAtBottomOfPage := TCheckBox(Sender).Checked
else if TCheckBox(Sender).Name = 'cbNewPageBefore' then
Cr.SectionFormat[i].NewPageBefore := TCheckBox(Sender).Checked
else if TCheckBox(Sender).Name = 'cbNewPageAfter' then
Cr.SectionFormat[i].NewPageAfter := TCheckBox(Sender).Checked
else if TCheckBox(Sender).Name = 'cbResetPageNAfter' then
Cr.SectionFormat[i].ResetPageNAfter := TCheckBox(Sender).Checked
else if TCheckBox(Sender).Name = 'cbKeepTogether' then
Cr.SectionFormat[i].KeepTogether := TCheckBox(Sender).Checked
else if TCheckBox(Sender).Name = 'cbSuppressBlankSection' then
Cr.SectionFormat[i].SuppressBlankSection := TCheckBox(Sender).Checked
else if TCheckBox(Sender).Name = 'cbUnderlaySection' then
Cr.SectionFormat[i].UnderlaySection := TCheckBox(Sender).Checked
else if TCheckBox(Sender).Name = 'cbBackgroundColor' then
begin
// if TCheckBox(Sender).Checked then
// Cr.SectionFormat[i].BackgroundColor := clWhite
// else
// Cr.SectionFormat[i].BackgroundColor := clNone;
if TCheckBox(Sender).State <> cbChecked then
begin
editRed.Text := '';
editGreen.Text := '';
editBlue.Text := '';
colorboxBackgroundColor.Enabled := False;
end
else
begin
{List the Background color RGB values for the Section}
editRed.Text := IntToStr(Round(GetRValue(Cr.SectionFormat[i].BackgroundColor)));
editGreen.Text := IntToStr(Round(GetGValue(Cr.SectionFormat[i].BackgroundColor)));
editBlue.Text := IntToStr(Round(GetBValue(Cr.SectionFormat[i].BackgroundColor)));
colorboxBackgroundColor.Enabled := True;
colorboxBackgroundColor.Selected := Cr.SectionFormat[i].BackgroundColor;
end;
end;
end;
{------------------------------------------------------------------------------}
{ colorboxBackgroundColorChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFormatDlg.colorboxBackgroundColorChange(
Sender: TObject);
begin
Cr.SectionFormat.Item.BackgroundColor := colorboxBackgroundColor.Selected;
editRed.Text := IntToStr(Round(GetRValue(colorboxBackgroundColor.Selected)));
editGreen.Text := IntToStr(Round(GetGValue(colorboxBackgroundColor.Selected)));
editBlue.Text := IntToStr(Round(GetBValue(colorboxBackgroundColor.Selected)));
end;
{------------------------------------------------------------------------------}
{ sbFormulaButtonClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFormatDlg.sbFormulaButtonClick(Sender: TObject);
var
xList : TStrings;
begin
if not (Sender is TSpeedButton) then
Exit;
{Set Crpe Formulas to chosen item}
if TSpeedButton(Sender) = sbPrintAtBottomOfPage then
xList := Cr.SectionFormat.Item.Formulas.PrintAtBottomOfPage
else if TSpeedButton(Sender) = sbNewPageBefore then
xList := Cr.SectionFormat.Item.Formulas.NewPageBefore
else if TSpeedButton(Sender) = sbNewPageAfter then
xList := Cr.SectionFormat.Item.Formulas.NewPageAfter
else if TSpeedButton(Sender) = sbResetPageNAfter then
xList := Cr.SectionFormat.Item.Formulas.ResetPageNAfter
else if TSpeedButton(Sender) = sbKeepTogether then
xList := Cr.SectionFormat.Item.Formulas.KeepTogether
else if TSpeedButton(Sender) = sbSuppressBlankSection then
xList := Cr.SectionFormat.Item.Formulas.SuppressBlankSection
else if TSpeedButton(Sender) = sbUnderlaySection then
xList := Cr.SectionFormat.Item.Formulas.UnderlaySection
else if TSpeedButton(Sender) = sbBackgroundColor then
xList := Cr.SectionFormat.Item.Formulas.BackgroundColor
else
{Default to Suppress}
xList := Cr.SectionFormat.Item.Formulas.Suppress;
{Create the Formula editing form}
CrpeFormulaEditDlg := TCrpeFormulaEditDlg.Create(Application);
CrpeFormulaEditDlg.SenderList := xList;
CrpeFormulaEditDlg.Caption := TSpeedButton(Sender).Hint;
CrpeFormulaEditDlg.ShowModal;
{Update the main form}
lbSectionsClick(Self);
end;
{------------------------------------------------------------------------------}
{ btnOkClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFormatDlg.btnOkClick(Sender: TObject);
begin
SaveFormPos(Self);
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose procedure }
{------------------------------------------------------------------------------}
procedure TCrpeSectionFormatDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
bSectionFormat := False;
Release;
end;
end.
|
unit fruFilter;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, dxSkinsCore,
dxSkinOffice2013White, cxLabel, Vcl.ExtCtrls, Vcl.Menus, Vcl.StdCtrls,
cxButtons, Vcl.DBCtrls;
type
TfrFilter = class(TFrame)
Bevel: TBevel;
buFilterClear: TcxButton;
paMain: TPanel;
paFilterClear: TPanel;
laCaption: TLabel;
private
FKeyValue: Variant;
FOnChange: TNotifyEvent;
protected
procedure DoChange();
function GetKeyValue: Variant; virtual;
procedure SetKeyValue(const Value: Variant); virtual;
public
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property KeyValue: Variant read GetKeyValue write SetKeyValue;
end;
implementation
{$R *.dfm}
uses uServiceUtils;
{ TfrFilter }
procedure TfrFilter.DoChange;
begin
if Assigned(FOnChange)
then
begin
FOnChange(Self);
end;
end;
function TfrFilter.GetKeyValue: Variant;
begin
end;
procedure TfrFilter.SetKeyValue(const Value: Variant);
begin
if not VarEquals(FKeyValue, Value)
then
begin
FKeyValue:= Value;
// DoChange();
end;
end;
end.
|
unit PropertyBar;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, LMDCustomComboBox, LMDFontComboBox;
type
TPropertyBarForm = class(TForm)
LMDFontComboBox1: TLMDFontComboBox;
procedure FormCreate(Sender: TObject);
procedure LMDFontComboBox1Change(Sender: TObject);
private
{ Private declarations }
FControl: TControl;
procedure PropertyChange;
procedure SelectionChange(inSender: TObject);
procedure SetControl(const Value: TControl);
public
{ Public declarations }
property Control: TControl read FControl write SetControl;
end;
var
PropertyBarForm: TPropertyBarForm;
implementation
uses
DesignManager;
{$R *.dfm}
type
TCrackedControl = class(TControl)
end;
procedure TPropertyBarForm.FormCreate(Sender: TObject);
begin
DesignMgr.SelectionObservers.Add(SelectionChange);
Height := 24;
end;
procedure TPropertyBarForm.SelectionChange(inSender: TObject);
begin
with DesignMgr do
if (SelectedObject <> nil) and (SelectedObject is TControl) then
Control := TControl(SelectedObject)
else
Control := nil;
end;
procedure TPropertyBarForm.PropertyChange;
begin
DesignMgr.PropertyChange(Self);
end;
procedure TPropertyBarForm.SetControl(const Value: TControl);
begin
FControl := Value;
LMDFontComboBox1.Enabled := Control <> nil;
if Control <> nil then
LMDFontComboBox1.SelectedFont := TCrackedControl(Control).Font.Name;
end;
procedure TPropertyBarForm.LMDFontComboBox1Change(Sender: TObject);
begin
if Control <> nil then
begin
TCrackedControl(Control).Font.Name := LMDFontComboBox1.SelectedFont;
PropertyChange;
end;
end;
end.
|
unit GLDConst;
interface
uses
GL, GLDTypes;
const
GLD_KEY_DELETE = $2E;
GLD_CHAR_MINUS = '-';
GLD_NUM_CHARSET: set of Char = ['0'..'9'];
GLD_INT_CHARSET: set of Char = ['0'..'9', '-'];
GLD_FLOAT_CHARSET: set of Char = ['0'..'9', '-', ','];
GLD_CLOSEMODE_OK = 0;
GLD_CLOSEMODE_CANCEL = 1;
GLD_ALPHA_FUNCS: array[TGLDAlphaFunc] of GLenum =
(GL_NEVER,
GL_LESS,
GL_EQUAL,
GL_LEQUAL,
GL_GREATER,
GL_NOTEQUAL,
GL_GEQUAL,
GL_ALWAYS);
GLD_BLEND_FUNC_SOURCE_FACTORS: array[TGLDBlendFuncSourceFactor] of GLenum =
(GL_ZERO,
GL_ONE,
GL_DST_COLOR,
GL_ONE_MINUS_DST_COLOR,
GL_SRC_ALPHA,
GL_ONE_MINUS_SRC_ALPHA,
GL_DST_ALPHA,
GL_ONE_MINUS_DST_ALPHA,
GL_SRC_ALPHA_SATURATE);
GLD_BLEND_FUNC_DESTINATION_FACTORS: array[TGLDBlendFuncDestinationFactor] of GLenum =
(GL_ZERO,
GL_ONE,
GL_SRC_COLOR,
GL_ONE_MINUS_SRC_COLOR,
GL_SRC_ALPHA,
GL_ONE_MINUS_SRC_ALPHA,
GL_DST_ALPHA,
GL_ONE_MINUS_DST_ALPHA);
GLD_CULL_FACES: array[TGLDCullFace] of GLenum =
(GL_FRONT,
GL_BACK);
GLD_DEPTH_FUNCS: array[TGLDDepthFunc] of GLenum =
(GL_NEVER,
GL_LESS,
GL_EQUAL,
GL_LEQUAL,
GL_GREATER,
GL_NOTEQUAL,
GL_GEQUAL,
GL_ALWAYS);
GLD_FOG_MODES: array[TGLDFogMode] of GLenum =
(GL_LINEAR,
GL_EXP,
GL_EXP2);
GLD_FRONT_FACES: array[TGLDFrontFace] of GLenum =
(GL_CW,
GL_CCW);
GLD_HINT_MODES: array[TGLDHintMode] of GLenum =
(GL_FASTEST,
GL_NICEST,
GL_DONT_CARE);
GLD_LOGIC_OPS: array[TGLDLogicOp] of GLenum =
(GL_CLEAR,
GL_SET,
GL_COPY,
GL_COPY_INVERTED,
GL_NOOP,
GL_INVERT,
GL_AND,
GL_NAND,
GL_OR,
GL_NOR,
GL_XOR,
GL_EQUIV,
GL_AND_REVERSE,
GL_AND_INVERTED,
GL_OR_REVERSE,
GL_OR_INVERTED);
GLD_POLYGON_MODES: array[TGLDPolygonMode] of GLenum =
(GL_POINT,
GL_LINE,
GL_FILL);
GLD_SHADE_MODELS: array[TGLDShadeModel] of GLenum =
(GL_FLAT,
GL_SMOOTH);
GLD_STENCIL_FUNCS: array[TGLDStencilFunc] of GLenum =
(GL_NEVER,
GL_LESS,
GL_LEQUAL,
GL_GREATER,
GL_GEQUAL,
GL_EQUAL,
GL_NOTEQUAL,
GL_ALWAYS);
GLD_STENCIL_OPS: array[TGLDStencilOp] of GLenum =
(GL_KEEP,
GL_ZERO,
GL_REPLACE,
GL_INCR,
GL_DECR,
GL_INVERT);
GLD_SYSTEM_FIRST_DRAWING_STATES: set of TGLDSystemStatus =
[GLD_SYSTEM_STATUS_CREATING_VERTICES,
GLD_SYSTEM_STATUS_CREATING_POLYGONS1,
GLD_SYSTEM_STATUS_CREATING_POLYGONS2,
GLD_SYSTEM_STATUS_PLANE_DRAWING1,
GLD_SYSTEM_STATUS_DISK_DRAWING1,
GLD_SYSTEM_STATUS_RING_DRAWING1,
GLD_SYSTEM_STATUS_BOX_DRAWING1,
GLD_SYSTEM_STATUS_PYRAMID_DRAWING1,
GLD_SYSTEM_STATUS_CYLINDER_DRAWING1,
GLD_SYSTEM_STATUS_CONE_DRAWING1,
GLD_SYSTEM_STATUS_TORUS_DRAWING1,
GLD_SYSTEM_STATUS_SPHERE_DRAWING1,
GLD_SYSTEM_STATUS_TUBE_DRAWING1,
GLD_SYSTEM_STATUS_USERCAMERA_DRAWING1];
GLD_SYSTEM_POLYGON_CREATING_STATES: set of TGLDSystemStatus =
[GLD_SYSTEM_STATUS_CREATING_POLYGONS1,
GLD_SYSTEM_STATUS_CREATING_POLYGONS2];
GLD_SYSTEM_DRAWING_STATES: set of TGLDSystemStatus =
[GLD_SYSTEM_STATUS_CREATING_VERTICES,
GLD_SYSTEM_STATUS_CREATING_POLYGONS1,
GLD_SYSTEM_STATUS_CREATING_POLYGONS2,
GLD_SYSTEM_STATUS_PLANE_DRAWING1,
GLD_SYSTEM_STATUS_PLANE_DRAWING2,
GLD_SYSTEM_STATUS_DISK_DRAWING1,
GLD_SYSTEM_STATUS_DISK_DRAWING2,
GLD_SYSTEM_STATUS_RING_DRAWING1,
GLD_SYSTEM_STATUS_RING_DRAWING2,
GLD_SYSTEM_STATUS_RING_DRAWING3,
GLD_SYSTEM_STATUS_BOX_DRAWING1,
GLD_SYSTEM_STATUS_BOX_DRAWING2,
GLD_SYSTEM_STATUS_BOX_DRAWING3,
GLD_SYSTEM_STATUS_CONE_DRAWING1,
GLD_SYSTEM_STATUS_CONE_DRAWING2,
GLD_SYSTEM_STATUS_CONE_DRAWING3,
GLD_SYSTEM_STATUS_CONE_DRAWING4,
GLD_SYSTEM_STATUS_CYLINDER_DRAWING1,
GLD_SYSTEM_STATUS_CYLINDER_DRAWING2,
GLD_SYSTEM_STATUS_CYLINDER_DRAWING3,
GLD_SYSTEM_STATUS_PYRAMID_DRAWING1,
GLD_SYSTEM_STATUS_PYRAMID_DRAWING2,
GLD_SYSTEM_STATUS_PYRAMID_DRAWING3,
GLD_SYSTEM_STATUS_SPHERE_DRAWING1,
GLD_SYSTEM_STATUS_SPHERE_DRAWING2,
GLD_SYSTEM_STATUS_TORUS_DRAWING1,
GLD_SYSTEM_STATUS_TORUS_DRAWING2,
GLD_SYSTEM_STATUS_TORUS_DRAWING3,
GLD_SYSTEM_STATUS_TORUS_DRAWING4,
GLD_SYSTEM_STATUS_TUBE_DRAWING1,
GLD_SYSTEM_STATUS_TUBE_DRAWING2,
GLD_SYSTEM_STATUS_TUBE_DRAWING3,
GLD_SYSTEM_STATUS_TUBE_DRAWING4,
GLD_SYSTEM_STATUS_USERCAMERA_DRAWING1,
GLD_SYSTEM_STATUS_USERCAMERA_DRAWING2];
GLD_LIGHT0 = 0;
GLD_LIGHT1 = 1;
GLD_LIGHT2 = 2;
GLD_LIGHT3 = 3;
GLD_LIGHT4 = 4;
GLD_LIGHT5 = 5;
GLD_LIGHT6 = 6;
GLD_LIGHT7 = 7;
GLD_MAX_LIGHTS = $000008;
GLD_MAX_CAMERAS = $FFFFFF;
GLD_MAX_MATERIALS = $FFFFFF;
GLD_MAX_OBJECTS = $FFFFFF;
GLD_MIN_FLOAT = -(3.4e+38);
GLD_MAX_FLOAT = 3.4e+38;
GLD_ANGLE_0: GLfloat = 0.0;
GLD_ANGLE_90: GLfloat = 90.0;
GLD_ANGLE_180: GLfloat = 180.0;
GLD_ANGLE_360: GLfloat = 360.0;
GLD_ANGLE_0D: GLdouble = 0.0;
GLD_ANGLE_90D: GLdouble = 90.0;
GLD_ANGLE_180D: GLdouble = 180.0;
GLD_ANGLE_360D: GLdouble = 360.0;
GLD_COLORUB_RED_DEFAULT = $00;
GLD_COLORUB_GREEN_DEFAULT = $00;
GLD_COLORUB_BLUE_DEFAULT = $00;
GLD_COLORUB_ALPHA_DEFAULT = $00;
GLD_COLORF_RED_DEFAULT = 0.0;
GLD_COLORF_GREEN_DEFAULT = 0.0;
GLD_COLORF_BLUE_DEFAULT = 0.0;
GLD_COLORF_ALPHA_DEFAULT = 0.0;
GLD_VECTORF_X_DEFAULT = 0.0;
GLD_VECTORF_Y_DEFAULT = 0.0;
GLD_VECTORF_Z_DEFAULT = 0.0;
GLD_VECTORF_W_DEFAULT = 1.0;
GLD_COLOR3UB_ZERO: TGLDColor3ub = (R: $00; G: $00; B: $00);
GLD_COLOR3UB_BLACK: TGLDColor3ub = (R: $00; G: $00; B: $00);
GLD_COLOR3UB_RED: TGLDColor3ub = (R: $FF; G: $00; B: $00);
GLD_COLOR3UB_GREEN: TGLDColor3ub = (R: $00; G: $FF; B: $00);
GLD_COLOR3UB_BLUE: TGLDColor3ub = (R: $00; G: $00; B: $FF);
GLD_COLOR3UB_YELLOW: TGLDColor3ub = (R: $FF; G: $FF; B: $00);
GLD_COLOR3UB_WHITE: TGLDColor3ub = (R: $FF; G: $FF; B: $FF);
GLD_COLOR3UB_DARKGRAY: TGLDColor3ub = (R: $50; G: $50; B: $50);
GLD_COLOR4UB_ZERO: TGLDColor4ub = (R: $00; G: $00; B: $00; A: $00);
GLD_COLOR4UB_BLACK: TGLDColor4ub = (R: $00; G: $00; B: $00; A: $00);
GLD_COLOR4UB_RED: TGLDColor4ub = (R: $FF; G: $00; B: $00; A: $00);
GLD_COLOR4UB_GREEN: TGLDColor4ub = (R: $00; G: $FF; B: $00; A: $00);
GLD_COLOR4UB_BLUE: TGLDColor4ub = (R: $00; G: $00; B: $FF; A: $00);
GLD_COLOR4UB_YELLOW: TGLDColor4ub = (R: $FF; G: $FF; B: $00; A: $00);
GLD_COLOR4UB_WHITE: TGLDColor4ub = (R: $FF; G: $FF; B: $FF; A: $00);
GLD_COLOR3F_ZERO: TGLDColor3f = (R: 0; G: 0; B: 0);
GLD_COLOR3F_BLACK: TGLDColor3f = (R: 0; G: 0; B: 0);
GLD_COLOR3F_RED: TGLDColor3f = (R: 1; G: 0; B: 0);
GLD_COLOR3F_GREEN: TGLDColor3f = (R: 0; G: 1; B: 0);
GLD_COLOR3F_BLUE: TGLDColor3f = (R: 0; G: 0; B: 1);
GLD_COLOR3F_YELLOW: TGLDColor3f = (R: 1; G: 1; B: 0);
GLD_COLOR3F_WHITE: TGLDColor3f = (R: 1; G: 1; B: 1);
GLD_COLOR4F_ZERO: TGLDColor4f = (R: 0; G: 0; B: 0; A: 0);
GLD_COLOR4F_BLACK: TGLDColor4f = (R: 0; G: 0; B: 0; A: 0);
GLD_COLOR4F_RED: TGLDColor4f = (R: 1; G: 0; B: 0; A: 0);
GLD_COLOR4F_GREEN: TGLDColor4f = (R: 0; G: 1; B: 0; A: 0);
GLD_COLOR4F_BLUE: TGLDColor4f = (R: 0; G: 0; B: 1; A: 0);
GLD_COLOR4F_YELLOW: TGLDColor4f = (R: 1; G: 1; B: 0; A: 0);
GLD_COLOR4F_WHITE: TGLDColor4f = (R: 1; G: 1; B: 1; A: 0);
GLD_VECTOR3F_ZERO: TGLDVector3f = (X: 0; Y: 0; Z: 0);
GLD_VECTOR4F_ZERO: TGLDVector4f = (X: 0; Y: 0; Z: 0; W: 0);
GLD_VECTOR3D_ZERO: TGLDVector3d = (X: 0; Y: 0; Z: 0);
GLD_VECTOR4D_ZERO: TGLDVector4d = (X: 0; Y: 0; Z: 0; W: 0);
GLD_VECTOR3F_IDENTITY: TGLDVector3f = (X: 0; Y: 0; Z: 0);
GLD_VECTOR4F_IDENTITY: TGLDVector4f = (X: 0; Y: 0; Z: 0; W: 1);
GLD_VECTOR3D_IDENTITY: TGLDVector3f = (X: 0; Y: 0; Z: 0);
GLD_VECTOR4D_IDENTITY: TGLDVector4d = (X: 0; Y: 0; Z: 0; W: 1);
GLD_TEXCOORD1F_ZERO: TGLDTexCoord1f = (S: 0);
GLD_TEXCOORD2F_ZERO: TGLDTexCoord2f = (S: 0; T: 0);
GLD_TEXCOORD3F_ZERO: TGLDTexCoord3f = (S: 0; T: 0; R: 0);
GLD_TEXCOORD4F_ZERO: TGLDTexCoord4f = (S: 0; T: 0; R: 0; Q: 0);
GLD_TEXCOORD1D_ZERO: TGLDTexCoord1d = (S: 0);
GLD_TEXCOORD2D_ZERO: TGLDTexCoord2d = (S: 0; T: 0);
GLD_TEXCOORD3D_ZERO: TGLDTexCoord3d = (S: 0; T: 0; R: 0);
GLD_TEXCOORD4D_ZERO: TGLDTexCoord4d = (S: 0; T: 0; R: 0; Q: 0);
GLD_TEXCOORD1F_IDENTITY: TGLDTexCoord1f = (S: 0);
GLD_TEXCOORD2F_IDENTITY: TGLDTexCoord2f = (S: 0; T: 0);
GLD_TEXCOORD3F_IDENTITY: TGLDTexCoord3f = (S: 0; T: 0; R: 0);
GLD_TEXCOORD4F_IDENTITY: TGLDTexCoord4f = (S: 0; T: 0; R: 0; Q: 1);
GLD_TEXCOORD1D_IDENTITY: TGLDTexCoord1d = (S: 0);
GLD_TEXCOORD2D_IDENTITY: TGLDTexCoord2d = (S: 0; T: 0);
GLD_TEXCOORD3D_IDENTITY: TGLDTexCoord3d = (S: 0; T: 0; R: 0);
GLD_TEXCOORD4D_IDENTITY: TGLDTexCoord4d = (S: 0; T: 0; R: 0; Q: 1);
GLD_ROTATION3D_ZERO : TGLDRotation3D = (XAngle: 0; YAngle: 0; ZAngle: 0);
GLD_STD_VECTOR0: TGLDVector3f = (X: 0; Y: 0; Z: 0);
GLD_STD_VECTOR1: TGLDVector3f = (X: 0; Y: 0; Z: 6);
GLD_STD_NORMAL1: TGLDVector3f = (NX: 0; NY: 0; NZ: -1);
GLD_STD_NORMAL2: TGLDVector3f = (NX: 0; NY: 0; NZ: 1);
GLD_STD_NORMAL3: TGLDVector3f = (NX: 1; NY: 0; NZ: 0);
GLD_STD_NORMAL4: TGLDVector3f = (NX: -1; NY: 0; NZ: 0);
GLD_STD_NORMAL5: TGLDVector3f = (NX: 0; NY: 1; NZ: 0);
GLD_STD_NORMAL6: TGLDVector3f = (NX: 0; NY: -1; NZ: 0);
GLD_STD_ROTATION3D: TGLDRotation3D = (XAngle: 0; YAngle: 0; ZAngle: 0);
GLD_STD_VIEWPORT: TGLDViewport = (X: 0; Y: 0; Width: 0; Height: 0);
GLD_NORMAL_POSITIVE_X: TGLDVector3f = (NX: 1; NY: 0; NZ: 0);
GLD_NORMAL_NEGATIVE_X: TGLDVector3f = (NX: -1; NY: 0; NZ: 0);
GLD_NORMAL_POSITIVE_Y: TGLDVector3f = (NX: 0; NY: 1; NZ: 0);
GLD_NORMAL_NEGATIVE_Y: TGLDVector3f = (NX: 0; NY: -1; NZ: 0);
GLD_NORMAL_POSITIVE_Z: TGLDVector3f = (NX: 0; NY: 0; NZ: 1);
GLD_NORMAL_NEGATIVE_Z: TGLDVector3f = (NX: 0; NY: 0; NZ: -1);
GLD_MATERIAL_AMBIENT_DEFAULT: TGLDColor4f = (R: 0.2; G: 0.2; B: 0.2; A: 1.0);
GLD_MATERIAL_DIFFUSE_DEFAULT: TGLDColor4f = (R: 0.8; G: 0.8; B: 0.8; A: 1.0);
GLD_MATERIAL_SPECULAR_DEFAULT: TGLDColor4f = (R: 0.0; G: 0.0; B: 0.0; A: 1.0);
GLD_MATERIAL_EMISSION_DEFAULT: TGLDColor4f = (R: 0.0; G: 0.0; B: 0.0; A: 1.0);
GLD_MATERIAL_SHININESS_DEFAULT = 0;
GLD_LIGHT_AMBIENT_DEFAULT: TGLDColor4f = (R: 0.0; G: 0.0; B: 0.0; A: 1.0);
GLD_LIGHT_DIFFUSE_DEFAULT: TGLDColor4f = (R: 1.0; G: 1.0; B: 1.0; A: 1.0);
GLD_LIGHT_SPECULAR_DEFAULT: TGLDColor4f = (R: 1.0; G: 1.0; B: 1.0; A: 1.0);
GLD_LIGHT_POSITION_DEFAULT: TGLDVector4f = (X: 0.0; Y: 0.0; Z: 1.0; W: 0.0);
GLD_LIGHT_SPOT_DEIRECTION_DEFAULT: TGLDVector3f = (X: 0; Y: 0; Z: -1);
GLD_LIGHT_SPOT_EXPONENT_DEFAULT = 0;
GLD_LIGHT_SPOT_CUTOFF = 180;
GLD_LIGHT_CONSTANT_ATTENUATION_DEFAULT = 1;
GLD_LIGHT_LINEAR_ATTENUATION_DEFAULT = 0;
GLD_LIGHT_QUADRATIC_ATTENUATION_DEFAULT = 0;
GLD_MATRIXF_ZERO: TGLDMatrixf = (
_11: 0; _12: 0; _13: 0; _14: 0;
_21: 0; _22: 0; _23: 0; _24: 0;
_31: 0; _32: 0; _33: 0; _34: 0;
_41: 0; _42: 0; _43: 0; _44: 0);
GLD_MATRIXF_IDENTITY: TGLDMatrixf = (
_11: 1; _12: 0; _13: 0; _14: 0;
_21: 0; _22: 1; _23: 0; _24: 0;
_31: 0; _32: 0; _33: 1; _34: 0;
_41: 0; _42: 0; _43: 0; _44: 1);
GLD_MATRIXD_ZERO: TGLDMatrixd = (
_11: 0; _12: 0; _13: 0; _14: 0;
_21: 0; _22: 0; _23: 0; _24: 0;
_31: 0; _32: 0; _33: 0; _34: 0;
_41: 0; _42: 0; _43: 0; _44: 0);
GLD_MATRIXD_IDENTITY: TGLDMatrixd = (
_11: 1; _12: 0; _13: 0; _14: 0;
_21: 0; _22: 1; _23: 0; _24: 0;
_31: 0; _32: 0; _33: 1; _34: 0;
_41: 0; _42: 0; _43: 0; _44: 1);
GLD_SYSTEMRENDEROPTIONS_RENDERMODE_DEFAULT = rmSmooth;
GLD_SYSTEMRENDEROPTIONS_DRAWEDGES_DEFAULT = False;
GLD_SYSTEMRENDEROPTIONS_ENABLELIGHTING_DEFAULT = True;
GLD_SYSTEMRENDEROPTIONS_TWOSIDEDLIGHTING_DEFAULT = True;
GLD_SYSTEMRENDEROPTIONS_CULLFACING_DEFAULT = False;
GLD_SYSTEMRENDEROPTIONS_CULLFACE_DEFAULT = cfBack;
GLD_STD_SYSTEMRENDEROPTIONSPARAMS: TGLDSystemRenderOptionsParams =
(RenderMode: GLD_SYSTEMRENDEROPTIONS_RENDERMODE_DEFAULT;
DrawEdges: GLD_SYSTEMRENDEROPTIONS_DRAWEDGES_DEFAULT;
EnableLighting: GLD_SYSTEMRENDEROPTIONS_ENABLELIGHTING_DEFAULT;
TwoSidedLighting: GLD_SYSTEMRENDEROPTIONS_TWOSIDEDLIGHTING_DEFAULT;
CullFacing: GLD_SYSTEMRENDEROPTIONS_CULLFACING_DEFAULT;
CullFace: GLD_SYSTEMRENDEROPTIONS_CULLFACE_DEFAULT);
GLD_SMOOTH_NONE = $00;
GLD_SMOOTH_POINT1 = 1 shl 1;
GLD_SMOOTH_POINT2 = 1 shl 2;
GLD_SMOOTH_POINT3 = 1 shl 3;
GLD_SMOOTH_POINT4 = 1 shl 4;
GLD_SMOOTH_ALL = $FF;
GLD_STD_TRIFACE: TGLDTriFace =
(Points: (0, 0, 0);
Smoothing: GLD_SMOOTH_NONE;
Normal1: (NX: 0; NY: 0; NZ: 0);
Normal2: (NX: 0; NY: 0; NZ: 0);
Normal3: (NX: 0; NY: 0; NZ: 0));
GLD_STD_QUADFACE: TGLDQuadFace =
(Points: (0, 0, 0, 0);
Smoothing: GLD_SMOOTH_NONE;
Normal1: (NX: 0; NY: 0; NZ: 0);
Normal2: (NX: 0; NY: 0; NZ: 0);
Normal3: (NX: 0; NY: 0; NZ: 0);
Normal4: (NX: 0; NY: 0; NZ: 0));
GLD_STD_POLYGON: TGLDPolygon =
(Data: nil;
Count: 0);
GLD_DEFAULT_SPOT_EXPONENT = 0;
GLD_DEFAULT_SPOT_CUTOFF = 180;
GLD_DEFAULT_SHININESS = 0;
GLD_STD_LIGHTPARAMS: TGLDLightParams =
(Ambient: (R: $00; G: $00; B: $00);
Diffuse: (R: $FF; G: $FF; B: $FF);
Specular: (R: $FF; G: $FF; B: $FF);
Position: (X: 0; Y: 0; Z: -1);
SpotDirection: (X: 0; Y: 0; Z: 1);
SpotExponent: GLD_DEFAULT_SPOT_EXPONENT;
SpotCutoff: GLD_DEFAULT_SPOT_CUTOFF;
ConstantAttenuation: 1;
LinearAttenuation: 0;
QuadraticAttenuation: 0);
GLD_STD_SIDECAMERAPARAMS: TGLDSideCameraParams =
(Zoom: 6;
Offset: (X: 0; Y: 0; Z: 0));
GLD_FRONTCAMERA_ROTATION_XANGLE_DEFAULT = 0.0;
GLD_FRONTCAMERA_ROTATION_YANGLE_DEFAULT = 0.0;
GLD_FRONTCAMERA_ROTATION_ZANGLE_DEFAULT = 0.0;
GLD_FRONTCAMERA_ROTATION: TGLDRotation3D =
(XAngle: GLD_FRONTCAMERA_ROTATION_XANGLE_DEFAULT;
YAngle: GLD_FRONTCAMERA_ROTATION_YANGLE_DEFAULT;
ZAngle: GLD_FRONTCAMERA_ROTATION_ZANGLE_DEFAULT);
GLD_BACKCAMERA_ROTATION_XANGLE_DEFAULT = 0.0;
GLD_BACKCAMERA_ROTATION_YANGLE_DEFAULT = 180.0;
GLD_BACKCAMERA_ROTATION_ZANGLE_DEFAULT = 0.0;
GLD_BACKCAMERA_ROTATION: TGLDRotation3D =
(XAngle: GLD_BACKCAMERA_ROTATION_XANGLE_DEFAULT;
YAngle: GLD_BACKCAMERA_ROTATION_YANGLE_DEFAULT;
ZAngle: GLD_BACKCAMERA_ROTATION_ZANGLE_DEFAULT);
GLD_LEFTCAMERA_ROTATION_XANGLE_DEFAULT = 0.0;
GLD_LEFTCAMERA_ROTATION_YANGLE_DEFAULT = 90.0;
GLD_LEFTCAMERA_ROTATION_ZANGLE_DEFAULT = 0.0;
GLD_LEFTCAMERA_ROTATION: TGLDRotation3D =
(XAngle: GLD_LEFTCAMERA_ROTATION_XANGLE_DEFAULT;
YAngle: GLD_LEFTCAMERA_ROTATION_YANGLE_DEFAULT;
ZAngle: GLD_LEFTCAMERA_ROTATION_ZANGLE_DEFAULT);
GLD_RIGHTCAMERA_ROTATION_XANGLE_DEFAULT = 0.0;
GLD_RIGHTCAMERA_ROTATION_YANGLE_DEFAULT = -90.0;
GLD_RIGHTCAMERA_ROTATION_ZANGLE_DEFAULT = 0.0;
GLD_RIGHTCAMERA_ROTATION: TGLDRotation3D =
(XAngle: GLD_RIGHTCAMERA_ROTATION_XANGLE_DEFAULT;
YAngle: GLD_RIGHTCAMERA_ROTATION_YANGLE_DEFAULT;
ZAngle: GLD_RIGHTCAMERA_ROTATION_ZANGLE_DEFAULT);
GLD_TOPCAMERA_ROTATION_XANGLE_DEFAULT = 90.0;
GLD_TOPCAMERA_ROTATION_YANGLE_DEFAULT = 0.0;
GLD_TOPCAMERA_ROTATION_ZANGLE_DEFAULT = 0.0;
GLD_TOPCAMERA_ROTATION: TGLDRotation3D =
(XAngle: GLD_TOPCAMERA_ROTATION_XANGLE_DEFAULT;
YAngle: GLD_TOPCAMERA_ROTATION_YANGLE_DEFAULT;
ZAngle: GLD_TOPCAMERA_ROTATION_ZANGLE_DEFAULT);
GLD_BOTTOMCAMERA_ROTATION_XANGLE_DEFAULT = -90.0;
GLD_BOTTOMCAMERA_ROTATION_YANGLE_DEFAULT = 0.0;
GLD_BOTTOMCAMERA_ROTATION_ZANGLE_DEFAULT = 0.0;
GLD_BOTTOMCAMERA_ROTATION: TGLDRotation3D =
(XAngle: GLD_BOTTOMCAMERA_ROTATION_XANGLE_DEFAULT;
YAngle: GLD_BOTTOMCAMERA_ROTATION_YANGLE_DEFAULT;
ZAngle: GLD_BOTTOMCAMERA_ROTATION_ZANGLE_DEFAULT);
GLD_USERCAMERA_TARGET_X_DEFAULT = 0.0;
GLD_USERCAMERA_TARGET_Y_DEFAULT = 0.0;
GLD_USERCAMERA_TARGET_Z_DEFAULT = 0.0;
GLD_USERCAMERA_TARGET_DEFAULT: TGLDVector3f =
(X: GLD_USERCAMERA_TARGET_X_DEFAULT;
Y: GLD_USERCAMERA_TARGET_Y_DEFAULT;
Z: GLD_USERCAMERA_TARGET_Z_DEFAULT);
GLD_USERCAMERA_ROTATION_XANGLE_DEFAULT = 0.0;
GLD_USERCAMERA_ROTATION_YANGLE_DEFAULT = 0.0;
GLD_USERCAMERA_ROTATION_ZANGLE_DEFAULT = 0.0;
GLD_USERCAMERA_ROTATION_DEFAULT: TGLDRotation3D =
(XAngle: GLD_USERCAMERA_ROTATION_XANGLE_DEFAULT;
YAngle: GLD_USERCAMERA_ROTATION_YANGLE_DEFAULT;
ZAngle: GLD_USERCAMERA_ROTATION_ZANGLE_DEFAULT);
GLD_USERCAMERA_ZNEAR_DEFAULT = 0.1;
GLD_USERCAMERA_ZFAR_DEFAULT = 100.0;
GLD_USERCAMERA_PROJECTIONMODE_DEFAULT = GLD_PERSPECTIVE;
GLD_USERCAMERA_ZOOM_DEFAULT = 6.0;
GLD_USERCAMERA_FOV_DEFAULT = 45.0;
GLD_USERCAMERA_ASPECT_DEFAULT = 4 / 3;
GLD_USERCAMERA_PARAMS_DEFAULT: TGLDUserCameraParams =
(Target:
(X: GLD_USERCAMERA_TARGET_X_DEFAULT;
Y: GLD_USERCAMERA_TARGET_Y_DEFAULT;
Z: GLD_USERCAMERA_TARGET_Z_DEFAULT);
Rotation:
(XAngle: GLD_USERCAMERA_ROTATION_XANGLE_DEFAULT;
YAngle: GLD_USERCAMERA_ROTATION_YANGLE_DEFAULT;
ZAngle: GLD_USERCAMERA_ROTATION_ZANGLE_DEFAULT);
ZNear: GLD_USERCAMERA_ZNEAR_DEFAULT;
ZFar: GLD_USERCAMERA_ZFAR_DEFAULT;
ProjectionMode: GLD_USERCAMERA_PROJECTIONMODE_DEFAULT;
Zoom: GLD_USERCAMERA_ZOOM_DEFAULT;
Fov: GLD_USERCAMERA_FOV_DEFAULT;
Aspect: GLD_USERCAMERA_ASPECT_DEFAULT);
GLD_STD_MATERIALPARAMS: TGLDMaterialParams =
(Ambient: (R: $0; G: $00; B: $0);
Diffuse: (R: $FF; G: $FF; B: $0);
Specular: (R: $00; G: $00; B: $FF);
Emission: (R: $00; G: $00; B: $00);
Shininess: 100);
GLD_HOMEGRID_AXIS_DEFAULT = gaXZ;
GLD_HOMEGRID_WIDTHSEGS_DEFAULT = 10;
GLD_HOMEGRID_LENGTHSEGS_DEFAULT = 10;
GLD_HOMEGRID_WIDTHSTEP_DEFAULT = 0.2;
GLD_HOMEGRID_LENGTHSTEP_DEFAULT = 0.2;
GLD_STD_HOMEGRIDPARAMS: TGLDHomeGridParams =
(Axis: GLD_HOMEGRID_AXIS_DEFAULT;
WidthSegs: GLD_HOMEGRID_WIDTHSEGS_DEFAULT;
LengthSegs: GLD_HOMEGRID_LENGTHSEGS_DEFAULT;
WidthStep: GLD_HOMEGRID_WIDTHSTEP_DEFAULT;
LengthStep: GLD_HOMEGRID_LENGTHSTEP_DEFAULT;
Position: (X: 0; Y: 0; Z: 0));
GLD_MINMAXCOORDS_MINX_DEFAULT = 0.0;
GLD_MINMAXCOORDS_MAXX_DEFAULT = 0.0;
GLD_MINMAXCOORDS_MINY_DEFAULT = 0.0;
GLD_MINMAXCOORDS_MAXY_DEFAULT = 0.0;
GLD_MINMAXCOORDS_MINZ_DEFAULT = 0.0;
GLD_MINMAXCOORDS_MAXZ_DEFAULT = 0.0;
GLD_STD_MINMAXCOORDS: TGLDMinMaxCoords =
(MinX: GLD_MINMAXCOORDS_MINX_DEFAULT;
MaxX: GLD_MINMAXCOORDS_MAXX_DEFAULT;
MinY: GLD_MINMAXCOORDS_MINY_DEFAULT;
MaxY: GLD_MINMAXCOORDS_MAXY_DEFAULT;
MinZ: GLD_MINMAXCOORDS_MINZ_DEFAULT;
MaxZ: GLD_MINMAXCOORDS_MAXZ_DEFAULT);
GLD_BOUNDINGBOX_WIDTH_DEFAULT = 0.0;
GLD_BOUNDINGBOX_HEIGHT_DEFAULT = 0.0;
GLD_BOUNDINGBOX_DEPTH_DEFAULT = 0.0;
GLD_BOUNDINGBOX_CENTER_X_DEFAULT = 0.0;
GLD_BOUNDINGBOX_CENTER_Y_DEFAULT = 0.0;
GLD_BOUNDINGBOX_CENTER_Z_DEFAULT = 0.0;
GLD_BOUNDINGBOX_CENTER_DEFAULT: TGLDVector3f =
(X: GLD_BOUNDINGBOX_CENTER_X_DEFAULT;
Y: GLD_BOUNDINGBOX_CENTER_Y_DEFAULT;
Z: GLD_BOUNDINGBOX_CENTER_Z_DEFAULT);
GLD_STD_BOUNDINGBOXPARAMS: TGLDBoundingBoxParams =
(Width: GLD_BOUNDINGBOX_WIDTH_DEFAULT;
Height: GLD_BOUNDINGBOX_HEIGHT_DEFAULT;
Depth: GLD_BOUNDINGBOX_DEPTH_DEFAULT;
Center:
(X: GLD_BOUNDINGBOX_CENTER_X_DEFAULT;
Y: GLD_BOUNDINGBOX_CENTER_Y_DEFAULT;
Z: GLD_BOUNDINGBOX_CENTER_Z_DEFAULT));
GLD_PLANE_LENGTHSEGS_DEFAULT = 2;
GLD_PLANE_WIDTHSEGS_DEFAULT = 2;
GLD_STD_PLANEPARAMS: TGLDPlaneParams =
(Color: (R: 0; G: 0; B: 0);
Length: 2.0;
Width: 2.0;
LengthSegs: GLD_PLANE_LENGTHSEGS_DEFAULT;
WidthSegs: GLD_PLANE_WIDTHSEGS_DEFAULT;
Position: (X: 0; Y: 0; Z: 0);
Rotation: (XAngle: 0; YAngle: 0; ZAngle: 0));
GLD_DISK_SEGMENTS_DEFAULT = 2;
GLD_DISK_SIDES_DEFAULT = 18;
GLD_STD_DISKPARAMS: TGLDDiskParams =
(Color: (R: 255; G: 0; B: 0);
Radius: 0.1;
Segments: GLD_DISK_SEGMENTS_DEFAULT;
Sides: GLD_DISK_SIDES_DEFAULT;
StartAngle: 0.0;
SweepAngle: 360.0;
Position: (X: 0; Y: 0; Z: 0);
Rotation: (XAngle: 0; YAngle: 0; ZAngle: 0));
GLD_RING_SEGMENTS_DEFAULT = 2;
GLD_RING_SIDES_DEFAULT = 18;
GLD_STD_RINGPARAMS: TGLDRingParams =
(Color: (R: 0; G: 0; B: 0);
InnerRadius: 0.5;
OuterRadius: 1.0;
Segments: GLD_RING_SEGMENTS_DEFAULT;
Sides: GLD_RING_SIDES_DEFAULT;
StartAngle: 0.0;
SweepAngle: 360.0;
Position: (X: 0; Y: 0; Z: 0);
Rotation: (XAngle: 0; YAngle: 0; ZAngle: 0));
GLD_BOX_LENGTHSEGS_DEFAULT = 2;
GLD_BOX_WIDTHSEGS_DEFAULT = 2;
GLD_BOX_HEIGHTSEGS_DEFAULT = 2;
GLD_STD_BOXPARAMS: TGLDBoxParams =
(Color: (R: 0; G: 0; B: 0);
Length: 1.0;
Width: 1.0;
Height: 1.0;
LengthSegs: GLD_BOX_LENGTHSEGS_DEFAULT;
WidthSegs: GLD_BOX_WIDTHSEGS_DEFAULT;
HeightSegs: GLD_BOX_HEIGHTSEGS_DEFAULT;
Position: (X: 0; Y: 0; Z: 0);
Rotation: (XAngle: 0; YAngle: 0; ZAngle: 0));
GLD_PYRAMID_WIDTHSEGS_DEFAULT = 2;
GLD_PYRAMID_DEPTHSEGS_DEFAULT = 2;
GLD_PYRAMID_HEIGHTSEGS_DEFAULT = 2;
GLD_STD_PYRAMIDPARAMS: TGLDPyramidParams =
(Color: (R: 0; G: 0; B: 0);
Width: 1.0;
Depth: 1.0;
Height: 2.0;
WidthSegs: GLD_PYRAMID_WIDTHSEGS_DEFAULT;
DepthSegs: GLD_PYRAMID_DEPTHSEGS_DEFAULT;
HeightSegs: GLD_PYRAMID_HEIGHTSEGS_DEFAULT;
Position: (X: 0; Y: 0; Z: 0);
Rotation: (XAngle: 0; YAngle: 0; ZAngle: 0));
GLD_CYLINDER_HEIGHTSEGS_DEFAULT = 2;
GLD_CYLINDER_CAPSEGS_DEFAULT = 2;
GLD_CYLINDER_SIDES_DEFAULT = 18;
GLD_STD_CYLINDERPARAMS: TGLDCylinderParams =
(Color: (R: 0; G: 0; B: 255);
Radius: 0.5;
Height: 2.0;
HeightSegs: GLD_CYLINDER_HEIGHTSEGS_DEFAULT;
CapSegs: GLD_CYLINDER_CAPSEGS_DEFAULT;
Sides: GLD_CYLINDER_SIDES_DEFAULT;
StartAngle: 0.0;
SweepAngle: 360.0;
Position: (X: 0; Y: 0; Z: 0);
Rotation: (XAngle: 0; YAngle: 0; ZAngle: 0));
GLD_CONE_HEIGHTSEGS_DEFAULT = 2;
GLD_CONE_CAPSEGS_DEFAULT = 2;
GLD_CONE_SIDES_DEFAULT = 18;
GLD_STD_CONEPARAMS: TGLDConeParams =
(Color: (R: 0; G: 0; B: 0);
Radius1: 2.0;
Radius2: 1.0;
Height: 2.0;
HeightSegs: 2;
CapSegs: 2;
Sides: 18;
StartAngle: 0.0;
SweepAngle: 360.0;
Position: (X: 0; Y: 0; Z: 0);
Rotation: (XAngle: 0; YAngle: 0; ZAngle: 0));
GLD_TORUS_SEGMENTS_DEFAULT = 18;
GLD_TORUS_SIDES_DEFAULT = 18;
GLD_STD_TORUSPARAMS: TGLDTorusParams =
(Color: (R: 0; G: 0; B: 0);
Radius1: 1.0;
Radius2: 0.25;
Segments: GLD_TORUS_SEGMENTS_DEFAULT;
Sides: GLD_TORUS_SIDES_DEFAULT;
StartAngle1: 0.0;
SweepAngle1: 360.0;
StartAngle2: 0.0;
SweepAngle2: 360.0;
Position: (X: 0; Y: 0; Z: 0);
Rotation: (XAngle: 0; YAngle: 0; ZAngle: 0));
GLD_SPHERE_SEGMENTS_DEFAULT = 36;
GLD_SPHERE_SIDES_DEFAULT = 36;
GLD_STD_SPHEREPARAMS: TGLDSphereParams =
(Color: (R: 0; G: 0; B: 0);
Radius: 1;
Segments: GLD_SPHERE_SEGMENTS_DEFAULT;
Sides: GLD_SPHERE_SIDES_DEFAULT;
StartAngle1: 0.0;
SweepAngle1: 360.0;
StartAngle2: 0.0;
SweepAngle2: 180.0;
Position: (X: 0; Y: 0; Z: 0);
Rotation: (XAngle: 0; YAngle: 0; ZAngle: 0));
GLD_TUBE_HEIGHTSEGS_DEFAULT = 2;
GLD_TUBE_CAPSEGS_DEFAULT = 2;
GLD_TUBE_SIDES_DEFAULT = 18;
GLD_STD_TUBEPARAMS: TGLDTubeParams =
(Color: (R: 0; G: 0; B: 0);
InnerRadius: 0.5;
OuterRadius: 1.0;
Height: 2.0;
HeightSegs: GLD_TUBE_HEIGHTSEGS_DEFAULT;
CapSegs: GLD_TUBE_CAPSEGS_DEFAULT;
Sides: GLD_TUBE_SIDES_DEFAULT;
StartAngle: 0.0;
SweepAngle: 360.0;
Position: (X: 0; Y: 0; Z: 0);
Rotation: (XAngle: 0; YAngle: 0; ZAngle: 0));
GLD_STD_PRIMITIVEPARAMS: TGLDPrimitiveParams =
(PrimitiveType: GL_TRIANGLE_STRIP;
UseNormals: True;
UseVertices: True;
Visible: True);
GLD_BEND_CENTER_X_DEFAULT = -2.0;
GLD_BEND_CENTER_Y_DEFAULT = 0.0;
GLD_BEND_CENTER_Z_DEFAULT = 0.0;
GLD_BEND_CENTER_DEFAULT: TGLDVector3f =
(X: GLD_BEND_CENTER_X_DEFAULT;
Y: GLD_BEND_CENTER_Y_DEFAULT;
Z: GLD_BEND_CENTER_Z_DEFAULT);
GLD_BEND_ANGLE_DEFAULT = 90.0;
GLD_BEND_AXIS_DEFAULT = GLD_AXIS_Z;
GLD_BEND_LIMITEFFECT_DEFAULT = False;
GLD_BEND_UPPERLIMIT_DEFAULT = 0.0;
GLD_BEND_LOWERLIMIT_DEFAULT = 0.0;
GLD_BEND_PARAMS_DEFAULT: TGLDBendParams =
(Center:
(X: GLD_BEND_CENTER_X_DEFAULT;
Y: GLD_BEND_CENTER_X_DEFAULT;
Z: GLD_BEND_CENTER_X_DEFAULT);
Angle: GLD_BEND_ANGLE_DEFAULT;
Axis: GLD_BEND_AXIS_DEFAULT;
LimitEffect: GLD_BEND_LIMITEFFECT_DEFAULT;
UpperLimit: GLD_BEND_UPPERLIMIT_DEFAULT;
LowerLimit: GLD_BEND_LOWERLIMIT_DEFAULT);
GLD_ROTATE_CENTER_X_DEFAULT = 0.0;
GLD_ROTATE_CENTER_Y_DEFAULT = 0.0;
GLD_ROTATE_CENTER_Z_DEFAULT = 0.0;
GLD_ROTATE_CENTER_DEFAULT: TGLDVector3f =
(X: GLD_ROTATE_CENTER_X_DEFAULT;
Y: GLD_ROTATE_CENTER_Y_DEFAULT;
Z: GLD_ROTATE_CENTER_Z_DEFAULT);
GLD_ROTATE_ANGLE_DEFAULT = 0.0;
GLD_ROTATE_AXIS_DEFAULT = GLD_AXIS_Y;
GLD_ROTATE_PARAMS_DEFAULT: TGLDRotateParams =
(Center:
(X: GLD_ROTATE_CENTER_X_DEFAULT;
Y: GLD_ROTATE_CENTER_Y_DEFAULT;
Z: GLD_ROTATE_CENTER_Z_DEFAULT);
Angle: GLD_ROTATE_ANGLE_DEFAULT;
Axis: GLD_ROTATE_AXIS_DEFAULT);
GLD_ROTATEXYZ_CENTER_X_DEFAULT = 0.0;
GLD_ROTATEXYZ_CENTER_Y_DEFAULT = 0.0;
GLD_ROTATEXYZ_CENTER_Z_DEFAULT = 0.0;
GLD_ROTATEXYZ_CENTER_DEFAULT: TGLDVector3f =
(X: GLD_ROTATEXYZ_CENTER_X_DEFAULT;
Y: GLD_ROTATEXYZ_CENTER_Y_DEFAULT;
Z: GLD_ROTATEXYZ_CENTER_Z_DEFAULT);
GLD_ROTATEXYZ_ANGLEX_DEFAULT = 0.0;
GLD_ROTATEXYZ_ANGLEY_DEFAULT = 0.0;
GLD_ROTATEXYZ_ANGLEZ_DEFAULT = 0.0;
GLD_ROTATEXYZ_PARAMS_DEFAULT: TGLDRotateXYZParams =
(Center:
(X: GLD_ROTATEXYZ_CENTER_X_DEFAULT;
Y: GLD_ROTATEXYZ_CENTER_Y_DEFAULT;
Z: GLD_ROTATEXYZ_CENTER_Z_DEFAULT);
AngleX: GLD_ROTATEXYZ_ANGLEX_DEFAULT;
AngleY: GLD_ROTATEXYZ_ANGLEY_DEFAULT;
AngleZ: GLD_ROTATEXYZ_ANGLEZ_DEFAULT);
GLD_SCALE_X_DEFAULT = 1.0;
GLD_SCALE_Y_DEFAULT = 1.0;
GLD_SCALE_Z_DEFAULT = 1.0;
GLD_SCALE_PARAMS_DEFAULT: TGLDScaleParams =
(X: GLD_SCALE_X_DEFAULT;
Y: GLD_SCALE_Y_DEFAULT;
Z: GLD_SCALE_Z_DEFAULT);
GLD_SKEW_CENTER_X_DEFAULT = 0.0;
GLD_SKEW_CENTER_Y_DEFAULT = 0.0;
GLD_SKEW_CENTER_Z_DEFAULT = 0.0;
GLD_SKEW_CENTER_DEFAULT: TGLDVector3f =
(X: GLD_SKEW_CENTER_X_DEFAULT;
Y: GLD_SKEW_CENTER_Y_DEFAULT;
Z: GLD_SKEW_CENTER_Z_DEFAULT);
GLD_SKEW_AMOUNT_DEFAULT = 0.0;
GLD_SKEW_DIRECTION_DEFAULT = 0.0;
GLD_SKEW_AXIS_DEFAULT = GLD_AXIS_Y;
GLD_SKEW_LIMITEFFECT_DEFAULT = False;
GLD_SKEW_UPPERLIMIT_DEFAULT = 0.0;
GLD_SKEW_LOWERLIMIT_DEFAULT = 0.0;
GLD_SKEW_PARAMS_DEFAULT: TGLDSkewParams =
(Center: (
X: GLD_SKEW_CENTER_X_DEFAULT;
Y: GLD_SKEW_CENTER_Y_DEFAULT;
Z: GLD_SKEW_CENTER_Z_DEFAULT);
Amount: GLD_SKEW_AMOUNT_DEFAULT;
Direction: GLD_SKEW_DIRECTION_DEFAULT;
Axis: GLD_SKEW_AXIS_DEFAULT;
LimitEffect: GLD_SKEW_LIMITEFFECT_DEFAULT;
UpperLimit: GLD_SKEW_UPPERLIMIT_DEFAULT;
LowerLimit: GLD_SKEW_LOWERLIMIT_DEFAULT);
GLD_TAPER_EFFECT_SET_DEFAULT = [X, Z];
GLD_TAPER_EFFECT_X = 1 shl 0;
GLD_TAPER_EFFECT_Y = 1 shl 1;
GLD_TAPER_EFFECT_Z = 1 shl 2;
GLD_TAPER_EFFECT_XY = GLD_TAPER_EFFECT_X or
GLD_TAPER_EFFECT_Y;
GLD_TAPER_EFFECT_XZ = GLD_TAPER_EFFECT_X or
GLD_TAPER_EFFECT_Z;
GLD_TAPER_EFFECT_YZ = GLD_TAPER_EFFECT_Y or
GLD_TAPER_EFFECT_Z;
GLD_TAPER_EFFECT_XYZ = GLD_TAPER_EFFECT_X or
GLD_TAPER_EFFECT_Y or
GLD_TAPER_EFFECT_Z;
GLD_TAPER_AMOUNT_DEFAULT = 0.0;
GLD_TAPER_AXIS_DEFAULT = GLD_AXIS_Y;
GLD_TAPER_EFFECT_DEFAULT = GLD_TAPER_EFFECT_XZ;
GLD_TAPER_LIMITEFFECT_DEFAULT = False;
GLD_TAPER_UPPERLIMIT_DEFAULT = 0.0;
GLD_TAPER_LOWERLIMIT_DEFAULT = 0.0;
GLD_TAPER_PARAMS_DEFAULT: TGLDTaperParams =
(Amount: GLD_TAPER_AMOUNT_DEFAULT;
Axis: GLD_TAPER_AXIS_DEFAULT;
Effect: GLD_TAPER_EFFECT_DEFAULT;
LimitEffect: GLD_TAPER_LIMITEFFECT_DEFAULT;
UpperLimit: GLD_TAPER_UPPERLIMIT_DEFAULT;
LowerLimit: GLD_TAPER_LOWERLIMIT_DEFAULT);
GLD_TWIST_CENTER_X_DEFAULT = 0.0;
GLD_TWIST_CENTER_Y_DEFAULT = 0.0;
GLD_TWIST_CENTER_Z_DEFAULT = 0.0;
GLD_TWIST_CENTER_DEFAULT: TGLDVector3f =
(X: GLD_TWIST_CENTER_X_DEFAULT;
Y: GLD_TWIST_CENTER_Y_DEFAULT;
Z: GLD_TWIST_CENTER_Z_DEFAULT);
GLD_TWIST_ANGLE_DEFAULT = 0.0;
GLD_TWIST_AXIS_DEFAULT = GLD_AXIS_Y;
GLD_TWIST_LIMITEFFECT_DEFAULT = False;
GLD_TWIST_UPPERLIMIT_DEFAULT = 0.0;
GLD_TWIST_LOWERLIMIT_DEFAULT = 0.0;
GLD_TWIST_PARAMS_DEFAULT: TGLDTwistParams =
(Center:
(X: GLD_TWIST_CENTER_X_DEFAULT;
Y: GLD_TWIST_CENTER_Y_DEFAULT;
Z: GLD_TWIST_CENTER_Z_DEFAULT);
Angle: GLD_TWIST_ANGLE_DEFAULT;
Axis: GLD_TWIST_AXIS_DEFAULT;
LimitEffect: GLD_TWIST_LIMITEFFECT_DEFAULT;
UpperLimit: GLD_TWIST_UPPERLIMIT_DEFAULT;
LowerLimit: GLD_TWIST_LOWERLIMIT_DEFAULT);
GLD_STANDARD_STR = 'Alap';
GLD_VISUALOBJECT_STR = 'Látható objektum';
GLD_EDITABLEOBJECT_STR = 'Szerkeszthető objektum';
GLD_PLANE_STR = 'Téglalap';
GLD_DISK_STR = 'Korong';
GLD_RING_STR = 'Gyűrű';
GLD_BOX_STR = 'Doboz';
GLD_PYRAMID_STR = 'Gúla';
GLD_CYLINDER_STR = 'Henger';
GLD_CONE_STR = 'Kúp';
GLD_TORUS_STR = 'Tórusz';
GLD_SPHERE_STR = 'Gömb';
GLD_TUBE_STR = 'Cső';
GLD_CUSTOMMESH_STR = 'Háló';
GLD_TRIMESH_STR = 'Háromszögháló';
GLD_QUADMESH_STR = 'Négyszögháló';
GLD_POLYMESH_STR = 'Poligonháló';
GLD_GRID_STR = 'Rács';
GLD_HOMEGRID_STR = GLD_GRID_STR;
GLD_BOUNDINGBOX_STR = 'Befoglaló doboz';
GLD_CAMERA_STR = 'Kamera';
GLD_PERSPECTIVECAMERA_STR = 'Perspektív kamera';
GLD_SIDECAMERA_STR = 'Oldalnézeti kamera';
GLD_FRONTCAMERA_STR = 'Elölnézeti kamera';
GLD_BACKCAMERA_STR = 'Hátulnézeti kamera';
GLD_LEFTCAMERA_STR = 'Baloldali kamera';
GLD_RIGHTCAMERA_STR = 'Jobboldali kamera';
GLD_TOPCAMERA_STR = 'Felülnézeti kamera';
GLD_BOTTOMCAMERA_STR = 'Alulnézeti kamera';
GLD_LIGHT_STR = 'Fény';
GLD_MATERIAL_STR = 'Anyag';
GLD_TEXTURE_STR = 'Textúra';
GLD_OBJECT_STR = 'Objektum';
GLD_MODIFY_STR = 'Módosítás';
GLD_MODIFIER_STR = 'Módosító';
GLD_BEND_STR = 'Hajlítás';
GLD_ROTATE_STR = 'Forgatás';
GLD_ROTATEXYZ_STR = 'ForgatásXYZ';
GLD_SCALE_STR = 'Nyújtás';
GLD_SKEW_STR = 'Ferdítés';
GLD_TAPER_STR = 'Hegyesítés';
GLD_TWIST_STR = 'Csavarás';
GLD_CAMERAS_STR = 'Kamerák';
GLD_LIGHTS_STR = 'Fények';
GLD_MATERIALS_STR = 'Anyagok';
GLD_TEXTURES_STR = 'Textúrák';
GLD_OBJECTS_STR = 'Objektumok';
GLD_MODIFIERS_STR = 'Módosítók';
implementation
end.
|
unit Unit2;
interface
type
TPessoa = class(TObject)
private
FCodigo: integer;
FNome: String;
procedure SetCodigo(const Value: integer);
procedure SetNome(const Value: String);
public
published
/// <summary>
/// <example>Exemplo de atribuição de valor a propriedade Código
/// <code>
/// varPessoa.Codigo := Valor;
/// </code>
/// </example>
/// </summary>
/// <returns>
/// Retorna um valor inteiro com o código da <c>Pessoa</c>
/// </returns>
property Codigo: integer read FCodigo write SetCodigo;
property Nome: String read FNome write SetNome;
/// <summary>
/// <example> Método utilizado para realizar a validacao de uma data qualquer
/// <code>
/// varValidado := varPessoa.ValidarData('01/01/2008');
/// </code>
/// </example>
/// </summary>
///
/// <param name="Data: String">
/// Informe a data para validação
/// </param>
///
/// <returns>
/// Retorna Verdadeiro ou Falso
/// </returns>
///
/// <exception cref="EConvertError">
/// O valor informado não é uma data valida
/// </exception>
///
/// <remarks>
/// A validacao usa <see cref="StrToDateTime" /> durante a operacao de
/// validacao com o parametro <paramref name="Data"/>.
/// </remarks>
function ValidarData(Data: String): boolean;
end;
implementation
{ TPessoa }
procedure TPessoa.SetCodigo(const Value: integer);
begin
FCodigo := Value;
end;
procedure TPessoa.SetNome(const Value: String);
begin
FNome := Value;
end;
function TPessoa.ValidarData(Data: String): boolean;
begin
Result := False;
try
StrToDateTime(Data);
Result := True;
except
on EConvertError do
EConvertError.Create('Data invalida!');
end;
end;
end.
|
unit uAddManExitDekret;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFControl, uLabeledFControl, uSpravControl, uInvisControl,
uLogicCheck, uSimpleCheck, uFormControl, uEnumControl, uCharControl,
uFloatControl, uDateControl, StdCtrls, Buttons, pFIBDatabase, DB,
FIBDataSet, pFIBDataSet;
type
TfmAddManExitDekret = class(TForm)
FormControl: TqFFormControl;
OkButton: TBitBtn;
CancelButton: TBitBtn;
IdOrder: TqFInvisControl;
NumItem: TqFSpravControl;
People: TqFSpravControl;
Post: TqFCharControl;
Order: TqFCharControl;
Holiday: TqFCharControl;
Date_Remove: TqFDateControl;
PrevOrder: TqFInvisControl;
procedure FIOOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: string);
procedure OkButtonClick(Sender: TObject);
procedure PeopleOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
procedure NumItemOpenSprav(Sender: TObject; var Value: Variant;
var DisplayText: String);
private
ReadTransaction: TpFIBTransaction;
Date_Order: TDate;
public
procedure Prepare(tran: TpFIBTransaction; Id_Order: Integer; Date_Order: TDate);
end;
var
fmAddManExitDekret: TfmAddManExitDekret;
implementation
{$R *.dfm}
uses uCommonSp, uSelectForm, qFTools, uDekretPeople;
procedure TfmAddManExitDekret.FIOOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: string);
var
sp: TSprav;
begin
// создать справочник
sp := GetSprav('asup\PCardsList');
if sp <> nil then
begin
// заполнить входные параметры
with sp.Input do
begin
Append;
FieldValues['DBHandle'] := Integer(ReadTransaction.DefaultDatabase.Handle);
FieldValues['ActualDate'] := Date;
FieldValues['SecondDate'] := 0;
FieldValues['ShowWorking'] := True;
FieldValues['CanRemoveFilter'] := True;
FieldValues['AdminMode'] := True;
Post;
end;
// показать справочник и проанализировать результат
sp.Show;
if (sp.Output <> nil) and not sp.Output.IsEmpty then
begin
Value := sp.Output['ID_PCARD'];
DisplayText := sp.Output['FIO'];
end;
sp.Free;
end;
end;
procedure TfmAddManExitDekret.OkButtonClick(Sender: TObject);
begin
FormControl.Ok;
end;
procedure TfmAddManExitDekret.Prepare(tran: TpFIBTransaction;
Id_Order: Integer; Date_Order: TDate);
begin
ReadTransaction := tran;
Self.Date_Order := Date_Order;
Self.IdOrder.Value := Id_Order;
Date_Remove.Value := Date_Order;
end;
procedure TfmAddManExitDekret.PeopleOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: String);
var
form: TfmDekretPeople;
begin
form := TfmDekretPeople.Create(Self, ReadTransaction, Date_Order);
if form.ShowModal = mrOk then
begin
Value := form.DekretPeople['Id_Man_Moving'];
DisplayText := form.DekretPeople['Man_String'];
PrevOrder.Value := form.DekretPeople['Id_Order'];
Post.Value := form.DekretPeople['POST_STRING'];
Order.Value := form.DekretPeople['ORDER_STRING'];
Holiday.Value := form.DekretPeople['Hol_STRING'];
end;
form.Free;
end;
procedure TfmAddManExitDekret.NumItemOpenSprav(Sender: TObject;
var Value: Variant; var DisplayText: String);
var
sp: TSprav;
begin
// создать справочник
sp := GetSprav('Asup\OrderItems');
if sp <> nil then
begin
// заполнить входные параметры
with sp.Input do
begin
Append;
FieldValues['DBHandle'] := Integer(ReadTransaction.DefaultDatabase.Handle);
FieldValues['Id_Order'] := IdOrder.Value;
Post;
end;
// показать справочник и проанализировать результат (выбор одного подр.)
sp.Show;
if (sp.Output <> nil) and not sp.Output.IsEmpty then
begin
Value := sp.Output['Num_Item'];
DisplayText := IntToStr(sp.Output['Num_Item']);
end;
sp.Free;
end;
end;
initialization
RegisterClass(TfmAddManExitDekret);
end.
|
{*
FtermSSH : An SSH implementation in Delphi for FTerm2 by kxn@cic.tsinghua.edu.cn
Cryptograpical code from OpenSSL Project
*}
unit sshdes;
interface
uses sshcipher;
type
DES_KEY = record
cblock: array[0..191] of char;
end;
TSSHDES = class(TSSHCipher)
protected
function Getcode: integer; override;
function GetBlkSize: integer; override;
function GetName: string; override;
function GetKeyBits: integer; override;
private
iv: array [0..7] of char;
key: DES_KEY;
public
constructor Create;
procedure SetIV(Data: Pointer); override;
procedure SetKey(Data: Pointer); override;
procedure Encrypt(Source, Dest: Pointer; Len: integer); override;
procedure Decrypt(Source, Dest: Pointer; Len: integer); override;
end;
TSSHDES3 = class(TSSHCipher)
protected
function Getcode: integer; override;
function GetBlkSize: integer; override;
function GetName: string; override;
function GetKeyBits: integer; override;
private
iv: array [0..7] of char;
key1: DES_KEY;
key2: DES_KEY;
key3: DES_KEY;
public
constructor Create;
procedure SetIV(Data: Pointer); override;
procedure SetKey(Data: Pointer); override;
procedure Encrypt(Source, Dest: Pointer; Len: integer); override;
procedure Decrypt(Source, Dest: Pointer; Len: integer); override;
end;
TSSH1DES3 = class(TSSHCipher)
protected
function Getcode: integer; override;
function GetBlkSize: integer; override;
function GetName: string; override;
function GetKeyBits: integer; override;
private
iv1: array [0..7] of char;
iv2: array [0..7] of char;
iv3: array [0..7] of char;
key1: DES_KEY;
key2: DES_KEY;
key3: DES_KEY;
public
constructor Create;
procedure SetIV(Data: Pointer); override;
procedure SetKey(Data: Pointer); override;
procedure Encrypt(Source, Dest: Pointer; Len: integer); override;
procedure Decrypt(Source, Dest: Pointer; Len: integer); override;
end;
implementation
uses sshconst;
const
DES_ENCRYPT = 1;
DES_DECRYPT = 0;
procedure des_set_key(Data, Key: Pointer); cdecl; external 'libeay32.dll';
procedure des_ncbc_encrypt(Source, Dest: Pointer; Len: integer;
Key, IV: Pointer; Enc: integer); cdecl; external 'libeay32.dll';
procedure des_ede3_cbc_encrypt(Source, Dest: Pointer; Len: integer;
Key1, Key2, Key3, IV: Pointer; Enc: integer); cdecl; external 'libeay32.dll';
{ TSSHDES }
constructor TSSHDES.Create;
begin
FillChar(key, sizeof(key), 0);
Fillchar(iv, sizeof(iv), 0);
end;
procedure TSSHDES.Decrypt(Source, Dest: Pointer; Len: integer);
begin
des_ncbc_encrypt(Source, Dest, Len, @Key, @iv, DES_DECRYPT);
end;
procedure TSSHDES.Encrypt(Source, Dest: Pointer; Len: integer);
begin
des_ncbc_encrypt(Source, Dest, Len, @Key, @iv, DES_ENCRYPT);
end;
function TSSHDES.GetBlkSize: integer;
begin
Result := 8;
end;
function TSSHDES.Getcode: integer;
begin
Result := SSH_CIPHER_DES;
end;
function TSSHDES.GetKeyBits: integer;
begin
Result := 56;
end;
function TSSHDES.GetName: string;
begin
Result := 'des-cbc';
end;
procedure TSSHDES.SetIV(Data: Pointer);
begin
if Data <> nil then
Move(Data^, iv, 8)
else
Fillchar(IV, Sizeof(IV), 0);
end;
procedure TSSHDES.SetKey(Data: Pointer);
begin
des_set_key(Data, @key);
end;
{ TSSHDES3 }
constructor TSSHDES3.Create;
begin
Fillchar(iv, sizeof(iv), 0);
Fillchar(key1, sizeof(key1), 0);
Fillchar(key2, sizeof(key1), 0);
Fillchar(key3, sizeof(key1), 0);
end;
procedure TSSHDES3.Decrypt(Source, Dest: Pointer; Len: integer);
begin
des_ede3_cbc_encrypt(Source, Dest, Len, @Key1, @Key2, @Key3, @IV, DES_DECRYPT);
end;
procedure TSSHDES3.Encrypt(Source, Dest: Pointer; Len: integer);
begin
des_ede3_cbc_encrypt(Source, Dest, Len, @Key1, @Key2, @Key3, @IV, DES_ENCRYPT);
end;
function TSSHDES3.GetBlkSize: integer;
begin
Result := 8;
end;
function TSSHDES3.Getcode: integer;
begin
Result := SSH_CIPHER_3DES;
end;
function TSSHDES3.GetKeyBits: integer;
begin
Result := 168;
end;
function TSSHDES3.GetName: string;
begin
Result := '3des-cbc';
end;
procedure TSSHDES3.SetIV(Data: Pointer);
begin
if Data <> nil then
Move(Data^, IV, sizeof(IV))
else
Fillchar(IV, Sizeof(IV), 0);
end;
procedure TSSHDES3.SetKey(Data: Pointer);
var
P: PChar;
begin
P := Data;
des_set_key(P, @Key1);
Inc(P, 8);
des_set_key(P, @Key2);
Inc(P, 8);
des_set_key(P, @Key3);
end;
{ TSSH1DES3 }
constructor TSSH1DES3.Create;
begin
Fillchar(iv1, sizeof(iv1), 0);
Fillchar(iv2, sizeof(iv2), 0);
Fillchar(iv3, sizeof(iv3), 0);
Fillchar(key1, sizeof(key1), 0);
Fillchar(key2, sizeof(key1), 0);
Fillchar(key3, sizeof(key1), 0);
end;
procedure TSSH1DES3.Decrypt(Source, Dest: Pointer; Len: integer);
begin
des_ncbc_encrypt(Source, Dest, len, @key3, @iv3, DES_DECRYPT);
des_ncbc_encrypt(dest, dest, len, @key2, @iv2, DES_ENCRYPT);
des_ncbc_encrypt(dest, dest, len, @key1, @iv1, DES_DECRYPT);
end;
procedure TSSH1DES3.Encrypt(Source, Dest: Pointer; Len: integer);
begin
des_ncbc_encrypt(Source, Dest, len, @key1, @iv1, DES_ENCRYPT);
des_ncbc_encrypt(dest, dest, len, @key2, @iv2, DES_DECRYPT);
des_ncbc_encrypt(dest, dest, len, @key3, @iv3, DES_ENCRYPT);
end;
function TSSH1DES3.GetBlkSize: integer;
begin
Result := 8;
end;
function TSSH1DES3.Getcode: integer;
begin
Result := SSH_CIPHER_3DES;
end;
function TSSH1DES3.GetKeyBits: integer;
begin
Result := 16;
end;
function TSSH1DES3.GetName: string;
begin
Result := 'des3-cbc';
end;
procedure TSSH1DES3.SetIV(Data: Pointer);
begin
Fillchar(IV1, Sizeof(IV1), 0);
Fillchar(IV2, Sizeof(IV1), 0);
Fillchar(IV3, Sizeof(IV1), 0);
end;
procedure TSSH1DES3.SetKey(Data: Pointer);
var
P: PChar;
begin
P := Data;
des_set_key(P, @Key1);
Inc(P, 8);
des_set_key(P, @Key2);
Inc(P, 8);
des_set_key(P, @Key3);
end;
end.
|
namespace proholz.xsdparser;
interface
type
AttributesVisitor = public abstract class(XsdAnnotatedElementsVisitor)
private
// *
// * The list of {@link XsdAttributeGroup} instances received by this visitor, wrapped in a {@link ReferenceBase} object.
//
//
var attributeGroups: List<ReferenceBase> := new List<ReferenceBase>();
// *
// * The list of {@link XsdAttribute} instances received by this visitor, wrapped in a {@link ReferenceBase} object.
//
//
var attributes: List<ReferenceBase> := new List<ReferenceBase>();
assembly
constructor(owner: XsdAnnotatedElements);
public
method visit(attribute: XsdAttribute); override;
method visit(attributeGroup: XsdAttributeGroup); override;
method setAttributes(values: List<ReferenceBase>); virtual;
method setAttributeGroups(values: List<ReferenceBase>); virtual;
// *
// * @return All the wrapped {@link XsdAttribute} objects received by this visitor.
method getAttributes: List<ReferenceBase>; virtual;
// *
// * @return All the wrapped {@link XsdAttributeGroup} objects received by this visitor.
method getAttributeGroups: List<ReferenceBase>; virtual;
// *
// * @return All the {@link XsdAttribute} objects that are fully resolved by this visitor. The {@link XsdAttribute}
// * objects wrapped in {@link UnsolvedReference} objects are not returned.
method getXsdAttributes: ISequence<XsdAttribute>; virtual;
// *
// * @return All the {@link XsdAttributeGroup} objects that are fully resolved by this visitor. The
// * {@link XsdAttributeGroup} objects wrapped in {@link UnsolvedReference} objects are not returned.
method getXsdAttributeGroup: ISequence<XsdAttributeGroup>; virtual;
// *
// * Tries to match the received {@link NamedConcreteElement} object, with any of the elements present either in
// * {@link AttributesVisitor#attributeGroups} or {@link AttributesVisitor#attributes}. If a match occurs this method
// * performs all the required actions to fully exchange the {@link UnsolvedReference} object with the element parameter.
// * @param element The resolved element that will be match with the contents of this visitor in order to assert if
// * there is anything to replace.
method replaceUnsolvedAttributes(element: NamedConcreteElement); virtual;
end;
implementation
constructor AttributesVisitor(owner: XsdAnnotatedElements);
begin
inherited constructor(owner);
end;
method AttributesVisitor.visit(attribute: XsdAttribute);
begin
inherited visit(attribute);
attributes.Add(ReferenceBase.createFromXsd(attribute));
end;
method AttributesVisitor.visit(attributeGroup: XsdAttributeGroup);
begin
inherited visit(attributeGroup);
attributeGroups.Add(ReferenceBase.createFromXsd(attributeGroup));
end;
method AttributesVisitor.setAttributes(values: List<ReferenceBase>);
begin
self.attributes := values;
end;
method AttributesVisitor.setAttributeGroups(values: List<ReferenceBase>);
begin
self.attributeGroups := values;
end;
method AttributesVisitor.getAttributes: List<ReferenceBase>;
begin
exit attributes;
end;
method AttributesVisitor.getAttributeGroups: List<ReferenceBase>;
begin
exit attributeGroups;
end;
method AttributesVisitor.getXsdAttributes: ISequence<XsdAttribute>;
begin
exit attributes.Where((attribute) -> attribute is ConcreteElement).Where((attribute) -> attribute.getElement() is XsdAttribute).Select((attribute) -> XsdAttribute(attribute.getElement()));
end;
method AttributesVisitor.getXsdAttributeGroup: ISequence<XsdAttributeGroup>;
begin
exit attributeGroups.Where((attributeGroup) -> attributeGroup is ConcreteElement).Select((attributeGroup) -> XsdAttributeGroup(attributeGroup.getElement()));
end;
method AttributesVisitor.replaceUnsolvedAttributes(element: NamedConcreteElement);
begin
if element.getElement() is XsdAttributeGroup then begin
var referenceBase: ReferenceBase := attributeGroups.Where((attributeGroup) -> (attributeGroup is UnsolvedReference) and XsdAbstractElement.compareReference(element, UnsolvedReference(attributeGroup))).FirstOrDefault();
if assigned(referenceBase) then begin
attributeGroups.Remove(referenceBase);
attributeGroups.Add(element);
attributes.Add(element.getElement().getElements());
element.getElement().setParent(getOwner());
end;
end;
if element.getElement() is XsdAttribute then begin
var referenceBase: ReferenceBase := attributes.Where((attribute) -> (attribute is UnsolvedReference) and XsdAbstractElement.compareReference(element, UnsolvedReference(attribute))).FirstOrDefault();
// .ifPresent(referenceBase ->
if assigned(referenceBase) then begin
attributes.Remove(referenceBase);
attributes.Add(element);
element.getElement().setParent(getOwner());
end;
end;
end;
end. |
{ NAME: Jordan Millett
CLASS: Comp Sci 1
DATE: 11/4/2016
PURPOSE: An try at making a rpg.
}
Program rpg;
uses
crt;
Procedure getInt(var ask:string; num : integer);
var
numStr : string;
code : integer;
begin
repeat
write(ask);
readln(numstr);
val(numStr, num, code);
if code <> 0 then
begin
writeln('Not an integer ');
writeln('Press any key to continue');
readkey;
clrscr;
end;
until (code = 0);
end;
procedure F_rat(var hp,dmg,gold,exp,level:integer);
var
hp_rat,dmg_rat,fleechance,expgain:integer;
flee:char;
begin
writeln('You were running through a dark hall when you tripped over something');
writeln('and hit hard on the ground, you look to see a huge rat coming at you');
writeln('so you ready your weapon');
hp_rat:=20;
dmg_rat:=1;
readkey;
repeat
clrscr;
writeln('Would you like to try to run away? (Y/N)');
readln(flee);
flee:=upcase(flee);
until (flee = 'Y') or (flee = 'N');
if (flee = 'Y') then
begin
randomize;
fleechance:=random(2)+1;
if (fleechance = 1) then
begin
writeln('You try to run away but you fall on your face again');
readkey;
clrscr;
flee:='N';
end else
begin
writeln('You ran away safeley');
readkey;
end;
end;
if (flee = 'N') then
begin
repeat
hp_rat:=hp_rat-dmg;
if (hp_rat > 0) then
begin
writeln('You hit the rat for ',dmg,' dmg it now has ',hp_rat,' health');
hp:=hp-dmg_rat;
readkey;
writeln('The rat hit you for ',dmg_rat,' dmg and you have ',hp,' health');
end
else if (hp_rat <= 0) then
begin
writeln('You hit the rat for ',dmg,' dmg and it died');
expgain:=random(10)+1;
exp:=exp+expgain;
writeln('You gained ',expgain,' experience and you now have ',exp,' experience');
end;
readkey;
clrscr;
until(hp_rat <= 0) or (hp <= 0);
end;
clrscr;
end;
procedure initializevar(var hp,dmg,gold,exp,level:integer);
begin
hp:=100;
dmg:=1;
gold:=0;
exp:=0;
level:=0;
end;
procedure loot(var gold:integer);
var
goldgain:integer;
begin
goldgain:=random(10)+1;
gold:=gold+goldgain;
writeln('You found a chest with ',goldgain,' gold');
readkey;
writeln('You now have ',gold,' gold');
readkey;
clrscr;
end;
procedure trader(var gold,hp:integer);
var
choice:char;
begin
repeat
clrscr;
writeln('You walk through a creeky old wooden door and find a old man sitting');
writeln('behind a counter he asks "would you like to spend ten gold to recover 25 hp?"');
readln(choice);
choice:=upcase(choice);
until (choice = 'Y') or (choice = 'N');
if (choice = 'Y') and (gold >= 10) then
begin
gold:=gold-10;
hp:=hp+25;
writeln('You regained 25 hp and you now have ',hp,' hp');
readkey;
end
else if (gold < 10) and (choice = 'Y') then
begin
writeln('You need more gold to purchase my potion!');
readkey;
end;
clrscr;
end;
procedure intro();
begin
writeln('your father has been gone in the doungeons for weeks and is presumed dead.');
delay(1000);
writeln('you found yourself looking through all of his old gear and you found a object');
delay(1000);
writeln('rapped in a silk cloth, as you remove it you recognize it as your fathers old');
delay(1000);
writeln('shortsword, you feel a sense of motavation and you rush off into the doungeons');
delay(1000);
writeln('to find your dad.');
readkey;
clrscr;
end;
var
hp,dmg,gold,exp,level,encounter:integer;
begin {main}
initializevar(hp,dmg,gold,exp,level);
Intro();
repeat
randomize;
encounter:=random(3)+1;
if (encounter = 1) then
F_rat(hp,dmg,gold,exp,level)
else if (encounter = 2) then
loot(gold)
else if (encounter = 3) then
trader(gold,hp);
until(exp > 50)
end. {main}
|
{***************************************************************************}
{ }
{ 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.Console.Logger;
interface
uses
DPM.Core.Types,
DPM.Core.Logging,
DPM.Console.Writer;
type
TDPMConsoleLogger = class(TInterfacedObject, ILogger)
private
FConsole : IConsoleWriter;
FVerbosity : TVerbosity;
protected
procedure Debug(const data: string);
procedure Error(const data: string);
procedure Information(const data: string; const important : boolean = false);
procedure Success(const data: string; const important : boolean = false);
procedure Verbose(const data: string; const important : boolean = false);
procedure Warning(const data: string; const important : boolean = false);
function GetVerbosity : TVerbosity;
procedure SetVerbosity(const value : TVerbosity);
procedure Clear;
procedure NewLine;
public
constructor Create(const console : IConsoleWriter);
end;
implementation
{ TDPMConsoleLogger }
procedure TDPMConsoleLogger.Clear;
begin
//no-op
end;
constructor TDPMConsoleLogger.Create(const console: IConsoleWriter);
begin
FConsole := console;
FVerbosity := TVerbosity.Debug;
end;
procedure TDPMConsoleLogger.Debug(const data: string);
begin
if FVerbosity < TVerbosity.Debug then
exit;
FConsole.SetColour(ccGrey);
FConsole.Write(data);
FConsole.SetColour(ccDefault);
end;
procedure TDPMConsoleLogger.Error(const data: string);
begin
//always log errors
FConsole.SetColour(ccBrightRed);
FConsole.Write(data);
FConsole.SetColour(ccDefault);
end;
function TDPMConsoleLogger.GetVerbosity: TVerbosity;
begin
result := FVerbosity;
end;
procedure TDPMConsoleLogger.Information(const data: string; const important : boolean);
begin
if (FVerbosity < TVerbosity.Normal) and (not important) then
exit;
if important then
FConsole.SetColour(ccBrightWhite)
else
FConsole.SetColour(ccWhite);
FConsole.Write(data);
FConsole.SetColour(ccDefault);
end;
procedure TDPMConsoleLogger.NewLine;
begin
FConsole.WriteLine(' ');
end;
procedure TDPMConsoleLogger.SetVerbosity(const value: TVerbosity);
begin
FVerbosity := value;
end;
procedure TDPMConsoleLogger.Success(const data: string; const important: boolean);
begin
if (FVerbosity < TVerbosity.Normal) and (not important) then
exit;
if important then
FConsole.SetColour(ccBrightGreen)
else
FConsole.SetColour(ccDarkGreen);
FConsole.Write(data);
FConsole.SetColour(ccDefault);
end;
procedure TDPMConsoleLogger.Verbose(const data: string; const important : boolean);
begin
if (FVerbosity < TVerbosity.Detailed) then
exit;
if important then
FConsole.SetColour(ccBrightWhite)
else
FConsole.SetColour(ccWhite);
FConsole.Write(data);
FConsole.SetColour(ccDefault);
end;
procedure TDPMConsoleLogger.Warning(const data: string; const important : boolean);
begin
//always log warnings
if important then
FConsole.SetColour(ccBrightYellow)
else
FConsole.SetColour(ccDarkYellow);
FConsole.Write(data);
FConsole.SetColour(ccDefault);
end;
end.
|
unit Auxo.Storage.Core;
interface
uses
Auxo.Storage.Interfaces, System.Generics.Collections, System.Rtti, System.SysUtils;
type
TStorage = class;
Prop<T> = record
private
FValue: T;
MemberName: string;
Storage: TStorage;
function GetValue: T;
procedure SetValue(const AValue: T);
public
property Value: T read GetValue write SetValue;
constructor Create(AValue: T); overload;
class operator Implicit(AValue: Prop<T>): T;
class operator Equal(ALeft: Prop<T>; ARight: T): Boolean;
class operator NotEqual(ALeft: Prop<T>; ARight: T): Boolean;
class operator GreaterThan(ALeft: Prop<T>; ARight: T): Boolean;
class operator GreaterThanOrEqual(ALeft: Prop<T>; ARight: T): Boolean;
class operator LessThan(ALeft, ARight: Prop<T>): Boolean;
class operator LessThanOrEqual(ALeft, ARight: Prop<T>): Boolean;
end;
Crypt = record
private
FValue: string;
MemberName: string;
Storage: TStorage;
function GetValue: string;
procedure SetValue(const Value: string);
public
constructor Create(Value: string); overload;
property Value: string read GetValue write SetValue;
class operator Implicit(Value: Crypt): string;
class operator Equal(Left: Crypt; Right: string): Boolean;
class operator NotEqual(Left: Crypt; Right: string): Boolean;
class operator GreaterThan(Left: Crypt; Right: string): Boolean;
class operator GreaterThanOrEqual(Left: Crypt; Right: string): Boolean;
class operator LessThan(Left, Right: Crypt): Boolean;
class operator LessThanOrEqual(Left, Right: Crypt): Boolean;
end;
TStorage = class
private
FStorager: IStorager;
FValues: TDictionary<string, string>;
function GetValue<T>(Field: TRttiField): T;
function SetValueType<T>(Field: TRttiField; DefaultValues: Boolean): Boolean;
procedure SetValues(DefaultValues: Boolean);
protected
FDefaultValuesSetting: Boolean;
procedure SetDefaultValues; virtual;
procedure Save(const AMember: string; Value: TValue); virtual;
public
constructor Create(AStorager: IStorager); virtual;
end;
var
EncryptDelegate: TFunc<string, string>;
DecryptDelegate: TFunc<string, string>;
implementation
uses
System.Generics.Defaults, System.TypInfo, System.UITypes;
{ Prop<T> }
constructor Prop<T>.Create(AValue: T);
begin
FValue := Value;
end;
function Prop<T>.GetValue: T;
begin
Result := FValue;
end;
procedure Prop<T>.SetValue(const AValue: T);
begin
FValue := Value;
if Storage <> nil then
Storage.Save(MemberName, TValue.From<T>(Value));
end;
class operator Prop<T>.Equal(ALeft: Prop<T>; ARight: T): Boolean;
begin
Result := TEqualityComparer<T>.Default.Equals(ALeft.FValue, ARight);
end;
class operator Prop<T>.GreaterThan(ALeft: Prop<T>; ARight: T): Boolean;
begin
Result := TComparer<T>.Default.Compare(ALeft, ARight) > 0;
end;
class operator Prop<T>.GreaterThanOrEqual(ALeft: Prop<T>; ARight: T): Boolean;
begin
Result := TComparer<T>.Default.Compare(ALeft, ARight) >= 0;
end;
class operator Prop<T>.Implicit(AValue: Prop<T>): T;
begin
Result := AValue.GetValue;
end;
class operator Prop<T>.LessThan(ALeft, ARight: Prop<T>): Boolean;
begin
Result := TComparer<T>.Default.Compare(ALeft, ARight) < 0;
end;
class operator Prop<T>.LessThanOrEqual(ALeft, ARight: Prop<T>): Boolean;
begin
Result := TComparer<T>.Default.Compare(ALeft, ARight) <= 0;
end;
class operator Prop<T>.NotEqual(ALeft: Prop<T>; ARight: T): Boolean;
begin
Result := not TEqualityComparer<T>.Default.Equals(ALeft.FValue, ARight);
end;
{ Crypt }
constructor Crypt.Create(Value: string);
begin
FValue := Value;
end;
function Crypt.GetValue: string;
begin
if Assigned(DecryptDelegate) then
Result := DecryptDelegate(FValue)
else
raise Exception.Create('public var DecryptDelegate in Auxo Storage.Proxyes not assigned');
end;
procedure Crypt.SetValue(const Value: string);
begin
if Assigned(EncryptDelegate) then
begin
FValue := EncryptDelegate(Value);
Storage.Save(MemberName, FValue);
end
else
raise Exception.Create('public var DecryptDelegate in Auxo Storage.Proxyes not assigned');
end;
class operator Crypt.Equal(Left: Crypt; Right: string): Boolean;
begin
Result := TEqualityComparer<string>.Default.Equals(Left.FValue, Right);
end;
class operator Crypt.GreaterThan(Left: Crypt; Right: string): Boolean;
begin
Result := TComparer<string>.Default.Compare(Left, Right) > 0;
end;
class operator Crypt.GreaterThanOrEqual(Left: Crypt; Right: string): Boolean;
begin
Result := TComparer<string>.Default.Compare(Left, Right) >= 0;
end;
class operator Crypt.Implicit(Value: Crypt): string;
begin
Result := Value.GetValue;
end;
class operator Crypt.LessThan(Left, Right: Crypt): Boolean;
begin
Result := TComparer<string>.Default.Compare(Left, Right) < 0;
end;
class operator Crypt.LessThanOrEqual(Left, Right: Crypt): Boolean;
begin
Result := TComparer<string>.Default.Compare(Left, Right) <= 0;
end;
class operator Crypt.NotEqual(Left: Crypt; Right: string): Boolean;
begin
Result := not TEqualityComparer<string>.Default.Equals(Left.FValue, Right);
end;
{ TStorage }
constructor TStorage.Create(AStorager: IStorager);
begin
FStorager := AStorager;
// FStorager.SetStorage(Self);
SetValues(True);
SetValues(False);
end;
function TStorage.GetValue<T>(Field: TRttiField): T;
var
Hndle: PTypeInfo;
Value: TValue;
begin
Hndle := TypeInfo(T);
if Hndle = TypeInfo(Integer) then
Value := TValue.From<Integer>(StrToIntDef(FValues.Items[Field.Name], 0))
else if Hndle = TypeInfo(string) then
Value := TValue.From<string>(FValues.Items[Field.Name])
else if Hndle = TypeInfo(TDateTime) then
Value := TValue.From<TDateTime>(StrToDateTimeDef(FValues.Items[Field.Name], 0))
else if Hndle = TypeInfo(Word) then
Value := TValue.From<Word>(StrToIntDef(FValues.Items[Field.Name], 0))
else if Hndle = TypeInfo(Boolean) then
Value := TValue.From<Boolean>(StrToBoolDef(FValues.Items[Field.Name], False))
else if Hndle = TypeInfo(TColor) then
Value := TValue.From<TColor>(StrToIntDef(FValues.Items[Field.Name], $7FFFFFFF))
else if Hndle = TypeInfo(Double) then
Value := TValue.From<Double>(StrToFloatDef(FValues.Items[Field.Name], 0))
else
Value := TValue.From<string>(FValues.Items[Field.Name]);
Result := Value.AsType<T>;
end;
procedure TStorage.Save(const AMember: string; Value: TValue);
begin
if not FDefaultValuesSetting then
FStorager.Save(AMember, Value);
end;
procedure TStorage.SetDefaultValues;
begin
end;
procedure TStorage.SetValues(DefaultValues: Boolean);
var
Field: TRttiField;
Ctx: TRttiContext;
Typ: TRttiType;
begin
Ctx := TRttiContext.Create;
Typ := Ctx.GetType(Self.ClassType);
FValues := TDictionary<string, string>.Create;
try
if not DefaultValues then
FStorager.Load(FValues);
for Field in Typ.GetFields do
begin
if SetValueType<Integer>(Field, DefaultValues) then Continue
else if SetValueType<string>(Field, DefaultValues) then Continue
else if SetValueType<TDateTime>(Field, DefaultValues) then Continue
else if SetValueType<Word>(Field, DefaultValues) then Continue
else if SetValueType<Boolean>(Field, DefaultValues) then Continue
else if SetValueType<TColor>(Field, DefaultValues) then Continue
else if SetValueType<Double>(Field, DefaultValues) then Continue
end;
if DefaultValues then
begin
FDefaultValuesSetting := True;
SetDefaultValues;
FDefaultValuesSetting := False;
end;
finally
FValues.Free;
end;
end;
function TStorage.SetValueType<T>(Field: TRttiField; DefaultValues: Boolean): Boolean;
var
cfgCrypt: Crypt;
cfgProp: Prop<T>;
begin
Result := False;
if Field.FieldType.Handle = TypeInfo(Prop<T>) then
begin
cfgProp.Storage := Self;
cfgProp.MemberName := Field.Name;
if FValues.ContainsKey(Field.Name) then
begin
cfgProp.Value := GetValue<T>(Field);
Field.SetValue(Self, TValue.From<Prop<T>>(cfgProp));
end;
if DefaultValues then
Field.SetValue(Self, TValue.From<Prop<T>>(cfgProp));
Result := True;
end
else if Field.FieldType.Handle = TypeInfo(Crypt) then
begin
cfgCrypt.Storage := Self;
cfgCrypt.MemberName := Field.Name;
if FValues.ContainsKey(Field.Name) then
begin
cfgCrypt.FValue := GetValue<string>(Field);
Field.SetValue(Self, TValue.From<Crypt>(cfgCrypt));
end;
if DefaultValues then
Field.SetValue(Self, TValue.From<Crypt>(cfgCrypt));
Result := True;
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.