{==============================================================================}
{
  Mail merge application: part 1 - template editor.
  Editing template and data for fields.

  Template: RVStyle for template (RVStyle2) has two text styles
  (0-th for normal text, 1 - for fields (with special Protection options)
  Other styles can be added dynamically (right-click editor in Delphi,
  "Settings" in the context menu).
  Template is stored in Template.rvf.

  Data for fields: stored in Database.db.
  There are two fields:
  - Code - string field
  - Data - rvf field.
  Styles can be added dynamically in Data editor.
}
{==============================================================================}
unit TEFrm;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
  Dialogs, DB, DBTables, RVScroll, RichView, RVEdit, DBRV, ComCtrls,
  StdCtrls, Mask, DBCtrls, RVStyle, ExtCtrls;

type
  TfrmTE = class(TForm)
    PageControl1: TPageControl;
    TabSheet1: TTabSheet;
    TabSheet2: TTabSheet;
    DBRichViewEdit1: TDBRichViewEdit;
    DataSource1: TDataSource;
    Table1: TTable;
    DBNavigator1: TDBNavigator;
    RVStyle1: TRVStyle;
    DBEdit1: TDBEdit;
    Label1: TLabel;
    Label2: TLabel;
    OpenDialog1: TOpenDialog;
    RVStyle2: TRVStyle;
    RichViewEdit1: TRichViewEdit;
    Button1: TButton;
    Label3: TLabel;
    procedure DataSource1DataChange(Sender: TObject; Field: TField);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  frmTE: TfrmTE;

implementation

{$R *.dfm}

procedure TfrmTE.DataSource1DataChange(Sender: TObject; Field: TField);
begin
  if Table1.RecordCount=0 then
    Label2.Caption := '(empty)'
  else if Table1.RecNo<1 then
    Label2.Caption := '(new)'
  else
    Label2.Caption := Format('Record %d of %d', [Table1.RecNo, Table1.RecordCount]);
end;

procedure TfrmTE.FormCreate(Sender: TObject);
begin
  RichViewEdit1.Clear;
  RichViewEdit1.LoadRVF(ExtractFilePath(Application.ExeName)+'template.rvf');
  RichViewEdit1.Format;
end;

procedure TfrmTE.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  if Table1.State in [dsEdit, dsInsert] then
    Table1.Post;
  RichViewEdit1.SaveRVF(ExtractFilePath(Application.ExeName)+'template.rvf', False);
end;

procedure TfrmTE.Button1Click(Sender: TObject);
var s: String;
begin
  s := '';
  if InputQuery('Insert Field', 'Field code:', s) then begin
    if s='' then
      exit;
    // s must be equal to one of Codes in the database
    RichViewEdit1.SetFocus;
    RichViewEdit1.CurTextStyleNo := 1;
    RichViewEdit1.InsertText(s, False);
  end;
end;

end.
