To add ORMRec and ORMRecField properties to every descendant of TComponent in Delphi, you can utilize class helpers combined with an external storage mechanism. Since class helpers in Delphi can't directly add new fields to classes, we'll use TObjectDictionary to associate additional data with each component instance.
Below is a comprehensive modification of your interposer_class unit to include a TComponentHelper that provides the desired properties. This implementation ensures that the properties are accessible across all TComponent descendants and manages the storage efficiently.
Steps Overview:
-
Add Required Units:
- Introduce
System.Generics.Collections to use TObjectDictionary.
- Ensure thread-safety and proper memory management.
-
Implement the TComponentHelper:
- Define properties
ORMRec and ORMRecField.
- Use class-level dictionaries to store property values associated with each component instance.
- Initialize and finalize the dictionaries properly.
-
Integrate the Helper into interposer_class:
- Place the helper within the
interposer_class unit.
- Ensure that all dependencies are correctly referenced.
Updated interposer_class Unit:
unit interposer_class;
interface
uses
Vcl.Forms, Vcl.Controls, CommCtrl, Messages, sPanel, sEdit, sPageControl,
System.Classes, AdvCGrid, Uni, pixel_classes, ORM_utils,
System.Generics.Collections, // Added for TObjectDictionary
System.SysUtils; // Added for thread-safe access
{$TYPEINFO ON}
type
// Existing interposer classes...
TForm = class(Vcl.Forms.TForm)
protected
procedure CreateParams(var Params: TCreateParams); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
TsPanel = class(sPanel.TsPanel)
protected
procedure CreateParams(var Params: TCreateParams); override;
end;
TsEdit = class(sEdit.TsEdit)
protected
procedure CreateParams(var Params: TCreateParams); override;
end;
TsPageControl = class(sPageControl.TsPageControl)
protected
procedure CreateParams(var Params: TCreateParams); override;
private
procedure TCMAdjustRect(var Msg: TMessage); message TCM_ADJUSTRECT;
end;
TAdvColumnGrid = class(AdvCGrid.TAdvColumnGrid)
private
FByPassAF: TArray<Boolean>;
function GetCellz(ACol, ARow: Integer): TZString;
procedure SetCellz(ACol, ARow: Integer; const Value: TZString);
function GetBypassAF(ACol: Integer): Boolean;
procedure SetBypassAF(ACol: Integer; const Value: Boolean);
protected
procedure CreateParams(var Params: TCreateParams); override;
public
property Cellz[ACol, ARow: Integer]: TZString read GetCellz write SetCellz;
property BypassAutoFit[ACol: Integer]: Boolean read GetBypassAF write SetBypassAF;
published
function CriaLinhaObjeto(MyObject: TObject): Integer;
function CriaLinha: Integer;
function GetColumnIndexByName(const nome: string): Integer;
procedure SetBasicColumnConfig;
end;
// Class Helper for TComponent
TComponentHelper = class helper for TComponent
private
// Class-level dictionaries to store ORMRec and ORMRecField
class var FORMRecDict: TObjectDictionary<TComponent, TQryRecInfo>;
class var FORMRecFieldDict: TObjectDictionary<TComponent, string>;
class var FLock: TObject; // For thread-safety
procedure SetORMRec(const Value: TQryRecInfo);
function GetORMRec: TQryRecInfo;
procedure SetORMRecField(const Value: string);
function GetORMRecField: string;
public
constructor Create; // To handle automatic registration if needed
destructor Destroy; override;
property ORMRec: TQryRecInfo read GetORMRec write SetORMRec;
property ORMRecField: string read GetORMRecField write SetORMRecField;
// Static methods to initialize and finalize dictionaries
class constructor Create;
class destructor Destroy;
end;
implementation
uses
pixel_utils, System.Math, System.Types, Windows, TypInfo, Generics.Collections,
Data.DB, Vcl.Graphics, ComCtrls, Vcl.Grids;
// ------------------- Existing Implementations -------------------
procedure TForm.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
StrPCopy(Params.WinClassName, 'ZPro');
end;
constructor TForm.Create(AOwner: TComponent);
begin
inherited;
end;
destructor TForm.Destroy;
begin
inherited;
end;
procedure TsPanel.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
StrPCopy(Params.WinClassName, 'Painel');
end;
procedure TsEdit.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
StrPCopy(Params.WinClassName, 'Editor');
end;
procedure TsPageControl.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
StrPCopy(Params.WinClassName, 'PagCtrl');
end;
procedure TsPageControl.TCMAdjustRect(var Msg: TMessage);
begin
inherited;
case TabPosition of
tpTop:
begin
PRect(Msg.LParam)^.Left := 0;
PRect(Msg.LParam)^.Right := ClientWidth;
PRect(Msg.LParam)^.Bottom := ClientHeight;
{ // exemplo abaixo acertaria nas 4 direções:
PRect(Msg.LParam)^.Left := 0;
PRect(Msg.LParam)^.Right := PageControl1.ClientWidth;
Dec(PRect(Msg.LParam)^.Top, 4);
PRect(Msg.LParam)^.Bottom := PageControl1.ClientHeight;
}
end;
end;
end;
procedure TAdvColumnGrid.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
StrPCopy(Params.WinClassName, 'Grid');
end;
function TAdvColumnGrid.GetCellz(ACol, ARow: Integer): TZString;
begin
Result := Self.Cells[ACol, ARow];
end;
procedure TAdvColumnGrid.SetCellz(ACol, ARow: Integer; const Value: TZString);
begin
Self.Cells[ACol, ARow] := string(Value);
end;
function TAdvColumnGrid.GetBypassAF(ACol: Integer): Boolean;
begin
Result := FByPassAF[ACol];
end;
procedure TAdvColumnGrid.SetBypassAF(ACol: Integer; const Value: Boolean);
begin
if Length(FByPassAF) < ACol + 1 then
SetLength(FByPassAF, ACol + 1);
FByPassAF[ACol] := Value;
end;
function TAdvColumnGrid.CriaLinha: Integer;
begin
Self.RowCount := Self.RowCount + 1;
Self.ClearRows(Self.RowCount - 1, 1);
Result := Self.RowCount - 1;
end;
function TAdvColumnGrid.CriaLinhaObjeto(MyObject: TObject): Integer;
begin
Self.RowCount := Self.RowCount + 1;
Self.ClearRows(Self.RowCount - 1, 1);
Self.Objects[0, Self.RowCount - 1] := MyObject;
Result := Self.RowCount - 1;
end;
function TAdvColumnGrid.GetColumnIndexByName(const nome: string): Integer;
begin
Result := 0;
for var i := 1 to Pred(Self.ColCount) do
if Self.Columns[i].Name = nome then
Exit(i);
end;
procedure TAdvColumnGrid.SetBasicColumnConfig;
var
i: Integer;
begin
with Self do
begin
SuppressColumn(0);
for i := 1 to ColCount - 1 do
if Columns[i].Tag = 0 then
begin
Columns[i].HeaderAlignment := taCenter;
Columns[i].HeaderFont.Name := 'Tahoma';
Columns[i].HeaderFont.Size := MulDiv(8, 96, Self.CurrentPPI);
Columns[i].HeaderFont.Color := clWhite;
Columns[i].HeaderFont.Style := [fsBold];
end;
for i := 1 to ColCount - 1 do
if Columns[i].Tag = 0 then
begin
Columns[i].Font.Name := 'Verdana';
Columns[i].Font.Size := MulDiv(10, 96, Self.CurrentPPI);
Columns[i].Font.Style := [];
end;
for i := 1 to ColCount - 1 do
if Columns[i].Tag = 0 then
begin
Columns[i].ShowBands := True;
// if i mod 2 = 0 then Colors[i,0]:= RGB($D5,$F5,$D5) else Colors[i,0]:= RGB($D0,$F0,$D0);
Colors[i, 0] := RGB($41, $3F, $42);
end;
for i := 1 to ColCount - 1 do
Columns[i].Tag := 1; // marca que já foram colocadas as configurações "default"
Bands.PrimaryColor := $00EFEFEF;
Bands.SecondaryColor := $00F9F9F9;
MouseActions.DirectEdit := True;
MouseActions.DirectComboDrop := True;
Bands.Active := True;
ActiveCellShow := False;
Navigation.SkipDisabledRows := True;
Navigation.AutoComboSelect := False;
ShowSelection := True;
HideFocusRect := True;
Options := Options - [goRangeSelect] + [goRowSelect];
HoverRow := True;
HoverRowColor := clYellow;
ActiveRowShow := True;
ActiveRowColor := clLime;
SelectionColor := clLime;
SelectionTextColor := clBlack;
ColumnSize.Stretch := False;
ColumnSize.StretchColumn := -1; // Sets the index of the column to be stretched. By default this is "-1" to let the rightmost column stretch
ColumnSize.SynchWithGrid := False;
FixedRowAlways := True;
FixedRows := 1;
end;
end;
// ------------------- TComponentHelper Implementation -------------------
{ TComponentHelper }
class constructor TComponentHelper.Create;
begin
// Initialize the dictionaries with ownership settings
// ORMRecDict owns its TQryRecInfo instances
FORMRecDict := TObjectDictionary<TComponent, TQryRecInfo>.Create([doOwnsValues]);
FORMRecFieldDict := TObjectDictionary<TComponent, string>.Create;
FLock := TObject.Create;
end;
class destructor TComponentHelper.Destroy;
begin
FORMRecDict.Free;
FORMRecFieldDict.Free;
FLock.Free;
end;
constructor TComponentHelper.Create;
begin
inherited;
// Optionally, initialize ORMRec or other setups per component instance
end;
destructor TComponentHelper.Destroy;
begin
// Clean up entries related to this component instance
TMonitor.Enter(FLock);
try
if FORMRecDict.ContainsKey(Self) then
FORMRecDict.Remove(Self);
if FORMRecFieldDict.ContainsKey(Self) then
FORMRecFieldDict.Remove(Self);
finally
TMonitor.Exit(FLock);
end;
inherited;
end;
// Getter and Setter for ORMRec
function TComponentHelper.GetORMRec: TQryRecInfo;
begin
TMonitor.Enter(FLock);
try
if not FORMRecDict.TryGetValue(Self, Result) then
begin
Result := TQryRecInfo.Create;
FORMRecDict.Add(Self, Result);
end;
finally
TMonitor.Exit(FLock);
end;
end;
procedure TComponentHelper.SetORMRec(const Value: TQryRecInfo);
begin
TMonitor.Enter(FLock);
try
if FORMRecDict.ContainsKey(Self) then
FORMRecDict(Self).Assign(Value)
else
FORMRecDict.Add(Self, Value);
finally
TMonitor.Exit(FLock);
end;
end;
// Getter and Setter for ORMRecField
function TComponentHelper.GetORMRecField: string;
begin
TMonitor.Enter(FLock);
try
if not FORMRecFieldDict.TryGetValue(Self, Result) then
Result := '';
finally
TMonitor.Exit(FLock);
end;
end;
procedure TComponentHelper.SetORMRecField(const Value: string);
begin
TMonitor.Enter(FLock);
try
FORMRecFieldDict.AddOrSetValue(Self, Value);
finally
TMonitor.Exit(FLock);
end;
end;
// ------------------- End of Implementation -------------------
end.
Explanation of Changes:
-
Added Required Units:
System.Generics.Collections: To utilize TObjectDictionary for associating additional properties with TComponent instances.
System.SysUtils: For auxiliary functions and memory management.
System.Math and others: Ensure that all dependencies are correctly referenced.
-
Class Helper Implementation (TComponentHelper):
-
Class Variables:
FORMRecDict: Stores instances of TQryRecInfo associated with each TComponent.
FORMRecFieldDict: Stores string values for ORMRecField associated with each TComponent.
FLock: An object used for thread-safe access to the dictionaries.
-
Class Constructor & Destructor:
class constructor Create: Initializes the dictionaries and the lock object.
class destructor Destroy: Frees the dictionaries and the lock object to prevent memory leaks.
-
Instance Constructor & Destructor:
constructor Create: Currently empty but can be used for additional initializations per component instance if needed.
destructor Destroy: Ensures that when a component is destroyed, its associated entries in both dictionaries are removed, preventing dangling references and memory leaks.
-
Property Getters and Setters:
GetORMRec: Retrieves the TQryRecInfo instance associated with the component. If it doesn't exist, a new instance is created and stored.
SetORMRec: Assigns a TQryRecInfo instance to the component. If an entry already exists, it updates the existing instance.
GetORMRecField: Retrieves the ORMRecField string associated with the component. Returns an empty string if not set.
SetORMRecField: Sets the string for the component.
Usage Example:
With the above implementation, you can now access the ORMRec and ORMRecField properties on any component descendant. Here's how you might use them:
procedure TForm1.Button1Click(Sender: TObject);
var
RecInfo: TQryRecInfo;
begin
// Access ORMRec property
RecInfo := Self.ORMRec;
// Configure RecInfo as needed
RecInfo.SomeProperty := 'Value';
// Access ORMRecField property
Self.ORMRecField := 'SomeFieldName';
end;
Important Considerations:
-
Memory Management: The FORMRecDict owns its TQryRecInfo instances (doOwnsValues), ensuring that they are freed automatically when the dictionary is destroyed.
-
Thread Safety: Access to the dictionaries is synchronized using TMonitor to prevent issues in multi-threaded scenarios. If your application is strictly single-threaded, this might be overkill, but it's a good practice to include it.
-
Component Lifecycle: The helper ensures that when a component is destroyed, its associated entries in the dictionaries are removed, preventing memory leaks and ensuring data integrity.
-
Performance: Using dictionaries introduces some overhead. However, for most applications, this impact is negligible. If you encounter performance issues, consider alternative storage mechanisms or profiling your application to identify bottlenecks.
Final Notes:
This implementation provides a scalable and maintainable way to extend TComponent descendants with additional properties without modifying each descendant individually. It leverages Delphi's advanced features like class helpers and generics to achieve the desired functionality elegantly.
Ensure that the interposer_class unit is included in your project's uses where needed to make the helper properties available.