unit FormEx;

interface

uses
  Classes, SysUtils, Forms, PersistentForm, Theme, Translator, ScaleDPI;

type

  { TFormEx }

  TFormEx = class(TForm)
  private
    FCounter: Integer; static;
  protected
    procedure DoShow; override;
    procedure DoCreate; override;
    procedure DoClose(var CloseAction: TCloseAction); override;
    procedure DoDestroy; override;
  public
    PersistentForm: TPersistentForm; static;
    ThemeManager: TThemeManager; static;
    Translator: TTranslator; static;
    ScaleDPI: TScaleDPI; static;
    OwnsPersistentForm: Boolean; static;
    OwnsThemeManager: Boolean; static;
    OwnsTranslator: Boolean; static;
    OwnsScaleDPI: Boolean; static;
  end;

procedure Register;


implementation

procedure Register;
begin
  RegisterNoIcon([TFormEx]);
end;

{ TFormEx }

procedure TFormEx.DoShow;
begin
  inherited;
  PersistentForm.Load(Self);
end;

procedure TFormEx.DoCreate;
begin
  if not Assigned(PersistentForm) then begin
    OwnsPersistentForm := True;
    PersistentForm := TPersistentForm.Create(nil);
  end;
  if not Assigned(ThemeManager) then begin
    OwnsThemeManager := True;
    ThemeManager := TThemeManager.Create(nil);
  end;
  if not Assigned(Translator) then begin
    Translator := TTranslator.Create(nil);
    Translator.POFilesFolder := 'Languages';
    Translator.Language := Translator.Languages.SearchByCode('');
    OwnsTranslator := True;
  end;
  if not Assigned(ScaleDPI) then begin
    OwnsScaleDPI := True;
    ScaleDPI := TScaleDPI.Create(nil);
  end;

  PersistentForm.Load(Self);
  Translator.TranslateComponentRecursive(Self);
  ThemeManager.UseTheme(Self);
  Inc(FCounter);
  inherited;
end;

procedure TFormEx.DoClose(var CloseAction: TCloseAction);
begin
  PersistentForm.Save(Self);
  inherited;
end;

procedure TFormEx.DoDestroy;
begin
  Dec(FCounter);
  if FCounter <= 0 then begin
    if OwnsPersistentForm then begin
      FreeAndNil(PersistentForm);
      OwnsPersistentForm := False;
    end;
    if OwnsThemeManager then begin
      FreeAndNil(ThemeManager);
      OwnsThemeManager := False;
    end;
    if OwnsTranslator then begin
      FreeAndNil(Translator);
      OwnsTranslator := False;
    end;
    if OwnsScaleDPI then begin
      FreeAndNil(ScaleDPI);
      OwnsScaleDPI := False;
    end;
  end;
  inherited;
end;

end.

