{==============================================================================}
{
  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, SclRView;

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;
    Button1: TButton;
    Label3: TLabel;
    srv1: TSRichViewEdit;
    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
  srv1.RichViewEdit.Clear;
  srv1.RichViewEdit.LoadRVF(ExtractFilePath(Application.ExeName)+'template.rvf');
  srv1.RichViewEdit.Format;
end;

procedure TfrmTE.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  if Table1.State in [dsEdit, dsInsert] then
    Table1.Post;
  srv1.RichViewEdit.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
    srv1.RichViewEdit.SetFocus;
    srv1.RichViewEdit.CurTextStyleNo := 1;
    srv1.RichViewEdit.InsertText(s, False);
  end;
end;

end.
