unit FormEx;

interface

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

type

  { TFormEx }

  TFormEx = class(TForm)
  private
    FCounter: Integer; static;
    FFirstShow: Boolean;
  protected
    procedure DoShow; override;
    procedure DoCreate; override;
    procedure DoClose(var CloseAction: TCloseAction); override;
    procedure DoDestroy; override;
  public
    FullScreen: Boolean;
    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;
  if not FFirstShow and (not (csDesigning in ComponentState)) then begin
    FFirstShow := True;
    PersistentForm.Load(Self);
    FullScreen := PersistentForm.FormFullScreen;
    ThemeManager.UseTheme(Self);
  end;
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;

  Translator.TranslateComponentRecursive(Self);
  Inc(FCounter);
  inherited;
end;

procedure TFormEx.DoClose(var CloseAction: TCloseAction);
begin
  if (not (csDesigning in ComponentState)) then begin
    PersistentForm.FormFullScreen := FullScreen;
    PersistentForm.Save(Self);
  end;
  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.

