
{*******************************************************}
{                                                       }
{       RichViewActions                                 }
{       Demo project with Ribbon and Glyfz pictures     }
{       You can use it as a basis for your              }
{       applications.                                   }
{                                                       }
{       TRichView (c) Sergey Tkachenko                  }
{       svt@trichview.com                               }
{       http://www.trichview.com                        }
{       Glyz icons (c) glyfz.com                        }
{       http://www.glyfz.com/                           }
{                                                       }
{*******************************************************}


unit RVARibbonFrm;

interface

{$I RV_Defs.inc}          // contains defines about Delphi compiler versions

uses
  Windows, Messages, SysUtils,
  Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, ComCtrls, ActnList,
  ActnMan, ActnCtrls, Ribbon, RibbonLunaStyleActnCtrls,
  ActnMenus, RibbonActnMenus, ScreenTips, RibbonActnCtrls,
  StdActns, ImgList,
  Menus, ShellApi, Printers, ToolWin, RVUni,
  RVScroll, RichView, RVEdit,
  RVStyle, PtblRV, CRVFData, RVTable, RVItem, CRVData, RVFuncs, RVMisc,
  // RVAAddictLanguages,
  RichViewActions, RVALocRuler, RVFontCombos, RVALocalize, Ruler, RVRuler,
  RVARibbonUtils,
  GifImg, RVGifAnimate2007, PngImage,
  RVTypes, ActnPopup, RVAPopupActionBar, RibbonObsidianStyleActnCtrls,
  RibbonSilverStyleActnCtrls, SRVActions, SRVToolWindow, SRVSkinManager,
  SRVToolBar, SRVALocalize,
  SRVTabSet, SRVPageScroll, SclRView, SclRVRuler, ExtCtrls;

type
  TfrmMain = class(TForm)
    RVAControlPanel1: TRVAControlPanel;
    ColorDialog1: TColorDialog;
    Ribbon1: TRibbon;
    ribHome: TRibbonPage;
    ribgClipboard: TRibbonGroup;
    ribAdvanced: TRibbonPage;
    ribTable: TRibbonPage;
    ActionManager1: TActionManager;
    rvActionCut1: TrvActionCut;
    rvActionCopy1: TrvActionCopy;
    rvActionPaste1: TrvActionPaste;
    rvActionPasteAsText1: TrvActionPasteAsText;
    rvActionPasteSpecial1: TrvActionPasteSpecial;
    rvActionUndo1: TrvActionUndo;
    rvActionRedo1: TrvActionRedo;
    rvActionSelectAll1: TrvActionSelectAll;
    rvActionFind1: TrvActionFind;
    rvActionFindNext1: TrvActionFindNext;
    rvActionReplace1: TrvActionReplace;
    RibbonQuickAccessToolbar1: TRibbonQuickAccessToolbar;
    ribgInsert: TRibbonGroup;
    rvActionInsertTable1: TrvActionInsertTable;
    RibbonApplicationMenuBar1: TRibbonApplicationMenuBar;
    rvActionNew1: TrvActionNew;
    rvActionOpen1: TrvActionOpen;
    rvActionSave1: TrvActionSave;
    rvActionExport1: TrvActionExport;
    rvActionSaveAs1: TrvActionSaveAs;
    ScreenTipsManager1: TScreenTipsManager;
    ActionList1: TActionList;
    rvActionInsertFile1: TrvActionInsertFile;
    rvActionInsertPicture1: TrvActionInsertPicture;
    rvActionInsertHLine1: TrvActionInsertHLine;
    rvActionInsertHyperlink1: TrvActionInsertHyperlink;
    rvActionInsertSymbol1: TrvActionInsertSymbol;
    rvActionInsertText1: TrvActionInsertText;
    ribgFont: TRibbonGroup;
    rvActionFonts1: TrvActionFonts;
    rvActionFontEx1: TrvActionFontEx;
    rvActionFontBold1: TrvActionFontBold;
    rvActionFontItalic1: TrvActionFontItalic;
    rvActionFontUnderline1: TrvActionFontUnderline;
    rvActionFontStrikeout1: TrvActionFontStrikeout;
    rvActionFontGrow1: TrvActionFontGrow;
    rvActionFontShrink1: TrvActionFontShrink;
    rvActionFontGrowOnePoint1: TrvActionFontGrowOnePoint;
    rvActionFontShrinkOnePoint1: TrvActionFontShrinkOnePoint;
    rvActionFontAllCaps1: TrvActionFontAllCaps;
    rvActionFontOverline1: TrvActionFontOverline;
    rvActionFontColor1: TrvActionFontColor;
    rvActionFontBackColor1: TrvActionFontBackColor;
    rvActionSubscript1: TrvActionSubscript;
    rvActionSuperscript1: TrvActionSuperscript;
    cmbFont: TRVFontComboBox;
    cmbFontSize: TRVFontSizeComboBox;
    ribgParagraph: TRibbonGroup;
    rvActionParagraph1: TrvActionParagraph;
    rvActionParaBorder1: TrvActionParaBorder;
    rvActionWordWrap1: TrvActionWordWrap;
    rvActionAlignLeft1: TrvActionAlignLeft;
    rvActionAlignRight1: TrvActionAlignRight;
    rvActionAlignCenter1: TrvActionAlignCenter;
    rvActionAlignJustify1: TrvActionAlignJustify;
    rvActionIndentInc1: TrvActionIndentInc;
    rvActionIndentDec1: TrvActionIndentDec;
    rvActionParaColor1: TrvActionParaColor;
    rvActionLineSpacing1001: TrvActionLineSpacing100;
    rvActionLineSpacing1501: TrvActionLineSpacing150;
    rvActionLineSpacing2001: TrvActionLineSpacing200;
    rvActionClearLeft1: TrvActionClearLeft;
    rvActionClearRight1: TrvActionClearRight;
    rvActionClearBoth1: TrvActionClearBoth;
    rvActionClearNone1: TrvActionClearNone;
    rvActionParaList1: TrvActionParaList;
    rvActionParaBullets1: TrvActionParaBullets;
    rvActionParaNumbering1: TrvActionParaNumbering;
    rvActionShowSpecialCharacters1: TrvActionShowSpecialCharacters;
    ribgList: TRibbonGroup;
    actTextSize: TAction;
    actTextFlow: TAction;
    actLineSpacing: TAction;
    actExit: TAction;
    actLanguage: TAction;
    ribgEditing: TRibbonGroup;
    rvActionTableInsertRowsBelow1: TrvActionTableInsertRowsBelow;
    rvActionTableInsertRowsAbove1: TrvActionTableInsertRowsAbove;
    rvActionTableInsertColLeft1: TrvActionTableInsertColLeft;
    rvActionTableInsertColRight1: TrvActionTableInsertColRight;
    rvActionTableDeleteRows1: TrvActionTableDeleteRows;
    rvActionTableDeleteCols1: TrvActionTableDeleteCols;
    rvActionTableDeleteTable1: TrvActionTableDeleteTable;
    rvActionTableMergeCells1: TrvActionTableMergeCells;
    rvActionTableSplitCells1: TrvActionTableSplitCells;
    rvActionTableSelectTable1: TrvActionTableSelectTable;
    rvActionTableSelectRows1: TrvActionTableSelectRows;
    rvActionTableSelectCols1: TrvActionTableSelectCols;
    rvActionTableSelectCell1: TrvActionTableSelectCell;
    rvActionTableCellVAlignTop1: TrvActionTableCellVAlignTop;
    rvActionTableCellVAlignMiddle1: TrvActionTableCellVAlignMiddle;
    rvActionTableCellVAlignBottom1: TrvActionTableCellVAlignBottom;
    rvActionTableCellVAlignDefault1: TrvActionTableCellVAlignDefault;
    rvActionTableCellLeftBorder1: TrvActionTableCellLeftBorder;
    rvActionTableCellRightBorder1: TrvActionTableCellRightBorder;
    rvActionTableCellTopBorder1: TrvActionTableCellTopBorder;
    rvActionTableCellBottomBorder1: TrvActionTableCellBottomBorder;
    rvActionTableCellAllBorders1: TrvActionTableCellAllBorders;
    rvActionTableCellNoBorders1: TrvActionTableCellNoBorders;
    rvActionTableProperties1: TrvActionTableProperties;
    rvActionTableGrid1: TrvActionTableGrid;
    ribgTableInsert: TRibbonGroup;
    ribgTableDelete: TRibbonGroup;
    ribgTableOperations: TRibbonGroup;
    actSelectInTable: TAction;
    ribgTableBorders: TRibbonGroup;
    actAlignCell: TAction;
    rvActionColor1: TrvActionColor;
    rvActionBackground1: TrvActionBackground;
    rvActionFillColor1: TrvActionFillColor;
    rvActionInsertPageBreak1: TrvActionInsertPageBreak;
    rvActionRemovePageBreak1: TrvActionRemovePageBreak;
    rvActionRemoveHyperlinks1: TrvActionRemoveHyperlinks;
    rvActionItemProperties1: TrvActionItemProperties;
    rvActionVAlign1: TrvActionVAlign;
    ribgBackground: TRibbonGroup;
    ribgPageSetup: TRibbonGroup;
    rvActionCharCase1: TrvActionCharCase;
    RVAPopupActionBar1: TRVAPopupActionBar;
    ribView: TRibbonPage;
    ribgDocView: TRibbonGroup;
    srvActionQuickPrint1: TsrvActionQuickPrint;
    srvActionPrint1: TsrvActionPrint;
    srvActionPageSetup1: TsrvActionPageSetup;
    srvActionLayoutPrint1: TsrvActionLayoutPrint;
    srvActionLayoutWeb1: TsrvActionLayoutWeb;
    srvActionLayoutDraft1: TsrvActionLayoutDraft;
    srvActionZoom1: TsrvActionZoom;
    srvActionZoomPageWidth1: TsrvActionZoomPageWidth;
    srvActionZoomFullPage1: TsrvActionZoomFullPage;
    srvActionPreview1: TsrvActionPreview;
    srvActionThumbnails1: TsrvActionThumbnails;
    srvActionOrientationPortrait1: TsrvActionOrientationPortrait;
    srvActionOrientationLandscape1: TsrvActionOrientationLandscape;
    srvActionPageFormatA4: TsrvActionPageFormat;
    srvActionEditHeader1: TsrvActionEditHeader;
    srvActionEditFooter1: TsrvActionEditFooter;
    srvActionEditMain1: TsrvActionEditMain;
    Panel1: TPanel;
    Panel3: TPanel;
    SclRVRuler1: TSclRVRuler;
    Panel4: TPanel;
    RVRulerItemSelector1: TRVRulerItemSelector;
    SclRVRuler2: TSclRVRuler;
    SRichViewEdit1: TSRichViewEdit;
    SRVPageScroll1: TSRVPageScroll;
    SRVTabSet1: TSRVTabSet;
    stat1: TStatusBar;
    ilDocTypes: TImageList;
    SRVSkinManager1: TSRVSkinManager;
    ilMenuV: TImageList;
    ribgZoom: TRibbonGroup;
    actZoomMenu: TAction;
    srvActionZoom2: TsrvActionZoom;
    srvActionZoom3: TsrvActionZoom;
    srvActionZoom4: TsrvActionZoom;
    srvActionZoom5: TsrvActionZoom;
    srvActionZoom6: TsrvActionZoom;
    srvActionZoom7: TsrvActionZoom;
    Splitter1: TSplitter;
    ribgViewOptions: TRibbonGroup;
    cmbUnits: TComboBox;
    fd: TFindDialog;
    rd: TReplaceDialog;
    actClose: TAction;
    actPageOrientation: TAction;
    actPageSize: TAction;
    srvActionPageFormatA5: TsrvActionPageFormat;
    srvActionPageFormatA6: TsrvActionPageFormat;
    srvActionPageFormatLetter: TsrvActionPageFormat;
    srvActionPageFormatLegal: TsrvActionPageFormat;
    pmTable: TPopupActionBar;
    DeleteTable1: TMenuItem;
    ribgHeaderFooter: TRibbonGroup;
    ribgPreview: TRibbonGroup;
    ilMenuH: TImageList;
    ilGlyphs16: TImageList;
    ribgFootnotes: TRibbonGroup;
    srvActionInsertFootnote1: TsrvActionInsertFootnote;
    srvActionInsertEndnote1: TsrvActionInsertEndnote;
    srvActionEditNote1: TsrvActionEditNote;
    srvActionReturnToNote1: TsrvActionReturnToNote;
    srvtwSearch: TSRVToolWindow;
    ilSearchToolWin: TImageList;
    rvActionHide1: TrvActionHide;
    ilBW32: TImageList;
    ilBW16: TImageList;
    ilGlyphs32: TImageList;
    procedure FormCreate(Sender: TObject);
    procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
    procedure cmbFontClick(Sender: TObject);
    procedure cmbFontSizeClick(Sender: TObject);
    procedure RVAControlPanel1MarginsChanged(Sender: TrvAction;
      Edit: TCustomRichViewEdit);
    procedure RVAControlPanel1Download(Sender: TrvAction;
      const Source: String);
    procedure cmbKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure Ribbon1HelpButtonClick(Sender: TObject);
    procedure actExitExecute(Sender: TObject);
    procedure actLanguageExecute(Sender: TObject);
    procedure Ribbon1RecentItemClick(Sender: TObject; FileName: string;
      Index: Integer);
    procedure rvActionSave1DocumentFileChange(Sender: TObject;
      Editor: TCustomRichViewEdit; const FileName: string;
      FileFormat: TrvFileSaveFilter; IsNew: Boolean);
    procedure srvActionThumbnails1Executed(Sender: TObject);
    procedure SRichViewEdit1Jump(Sender: TObject; id: Integer);
    procedure SRichViewEdit1ReadHyperlink(Sender: TCustomRichView; const Target,
      Extras: string; DocFormat: TRVLoadFormat; var StyleNo, ItemTag: Integer;
      var ItemName: TRVRawByteString);
    procedure SRichViewEdit1WriteHyperlink(Sender: TCustomRichView; id: Integer;
      RVData: TCustomRVData; ItemNo: Integer; SaveFormat: TRVSaveFormat;
      var Target, Extras: string);
    procedure SRichViewEdit1KeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure SRichViewEdit1KeyPress(Sender: TObject; var Key: Char);
    procedure SRichViewEdit1CurTextStyleChanged(Sender: TObject);
    procedure RVAControlPanel1BackgroundChange(Sender: TrvAction;
      Edit: TCustomRichViewEdit);
    procedure SRichViewEdit1CurrentPageChange(Sender: TObject);
    procedure SRichViewEdit1CaretMove(Sender: TObject);
    procedure SRichViewEdit1PageScrolled(Sender: TObject);
    procedure SRichViewEdit1ChangeActiveEditor(Sender: TSRichViewEdit;
      ActiveEditor: TRichViewEdit);
    procedure srvtwSearchClickButton(Sender: TObject;
      ToolButton: TSRVToolButton);
    procedure SRichViewEdit1HMenuClickButton(Sender: TObject;
      ToolButton: TSRVToolButton);
    procedure SRichViewEdit1VMenuClickButton(Sender: TObject;
      ToolButton: TSRVToolButton);
    procedure fdFind(Sender: TObject);
    procedure SRichViewEdit1TableIconClick(Sender: TSRichViewEdit;
      Button: TMouseButton; Shift: TShiftState; X, Y, PageNo: Integer);
    procedure SRichViewEdit1Change(Sender: TObject);
    procedure SRVTabSet1Change(Sender: TObject);
    procedure SRVTabSet1CloseTab(Sender: TSRVTabSet; TabIndex: Integer;
      var CanClose: Boolean);
    procedure rvActionNew1Execute(Sender: TObject);
    procedure rvActionOpen1Execute(Sender: TObject);
    procedure SRVTabSet1TabMove(Sender: TSRVTabSet; NewTabIndex,
      OldTabIndex: Integer);
    procedure actCloseExecute(Sender: TObject);
    procedure rvActionInsertTable1Execute(Sender: TObject);
    procedure srvActionLayoutPrint1Executed(Sender: TObject);
    procedure srvActionLayoutWeb1Executed(Sender: TObject);
    procedure srvActionLayoutDraft1Executed(Sender: TObject);
    procedure rvActionVAlign1Execute(Sender: TObject);
    procedure cmbUnitsClick(Sender: TObject);
  private
    { Private declarations }
    VToolButtonIndex: Integer;
    UpdatingCombos: Boolean;
    Editors : array of TSRichViewEdit;
    ActiveEditor: TSRichViewEdit;
    procedure Localize;
    procedure ApplicationHint(Sender: TObject);
    procedure UpdateIcon(Editor: TSRichViewEdit);
    procedure FocusActiveEditor;
    function GetIconIndex(IsNew: Boolean; FileFormat: TrvFileSaveFilter;
      Modified: Boolean): Integer;
    function GetIndexOfEditorByRichViewEdit(rve: TCustomRichViewEdit): Integer;
    function GetDocInfo(rve: TCustomRichViewEdit): TrvaDocumentInfo;
    function GetActiveDocInfo: TrvaDocumentInfo;
    procedure AddEditor;
    procedure SetEditor(Index : Integer);
    procedure RemoveEditor(Index : Integer);
    procedure UpdateCloseAction;
  public
    { Public declarations }

  end;

var
  frmMain: TfrmMain;

implementation

uses Math;

{$R *.dfm}

procedure ShowInfo(const msg,cpt: String);
begin
  Application.MessageBox(PChar(msg),PChar(cpt),MB_OK or MB_ICONINFORMATION);
end;

procedure TfrmMain.FormCreate(Sender: TObject);
begin
  // Tabbed UI support
  SetLength(Editors, 1);
  Editors[0] := SRichViewEdit1;
  ActiveEditor := SRichViewEdit1;
  SRVTabSet1.TabIndex := 0;

  // Almost all these assignments could be done at design time in the Object Inspector
  // But in this demo we do not want to modify srvActionsResource
  // (and we recommend to use a copy of it in your applications)

  rvActionSave1.OnDocumentFileChange := rvActionSave1DocumentFileChange;

  // Index of the last clicked button in search toolwindow
  VToolButtonIndex := -1;

  // Initializing the action for showing/hiding thumbnails
  srvActionThumbnails1.PageScroll := SRVPageScroll1;

  // AutoComplete feature causes OnClick generation when editing combo-box's text.
  // Since in OnClick we move input focus in RichViewEdit1, this effect is
  // undesirable
  cmbFont.AutoComplete := False;
  cmbFontSize.AutoComplete := False;

  // units
  RVA_ConvertToTwips(Self);
  RVAControlPanel1.UnitsProgram := rvstuTwips;
  SRichViewEdit1.ConvertToTwips;
  cmbUnits.ItemIndex := ord(SRichViewEdit1.UnitsProgram);
  RVAControlPanel1.UnitsDisplay := SRichViewEdit1.UnitsProgram;

  // Applying the default language
  Localize;

  // Displaying hints on the status bar
  Application.OnHint := ApplicationHint;

  // Loading initial file via ActionOpen (allowing to update user interface)
  rvActionOpen1.LoadFile(ActiveEditor.RichViewEdit,
    ExtractFilePath(Application.ExeName)+'readme.rvf', ffiRVF);

  {
  // alternative way to start
    rvActionNew1.ExecuteTarget(ActiveEditor.RichViewEdit);
  }


  // Tabbed UI support
  ActiveEditor.RichViewEdit.Modified := False;
  UpdateIcon(ActiveEditor);
  UpdateCloseAction;

  // Enabling additional actions from ActionList1
  actTextSize.DisableIfNoHandler := False;
  actTextFlow.DisableIfNoHandler := False;
  actLineSpacing.DisableIfNoHandler := False;
  actSelectInTable.DisableIfNoHandler := False;
  actAlignCell.DisableIfNoHandler := False;
  actZoomMenu.DisableIfNoHandler := False;
  actPageSize.DisableIfNoHandler := False;
  actPageOrientation.DisableIfNoHandler := False;

  Application.HintPause := 700;


end;

{-------------- Set of events for processing hypertext links ------------------}
// Hyperlink click
procedure TfrmMain.SRichViewEdit1Jump(Sender: TObject; id: Integer);
begin
  rvActionInsertHyperlink1.GoToLink(ActiveEditor.ActiveEditor, id);
end;

// Importing hyperlink
procedure TfrmMain.SRichViewEdit1ReadHyperlink(Sender: TCustomRichView;
  const Target, Extras: string; DocFormat: TRVLoadFormat; var StyleNo,
  ItemTag: Integer; var ItemName: TRVRawByteString);
var URL: String;
begin
  if DocFormat=rvlfURL then
    StyleNo :=
      rvActionInsertHyperlink1.GetHyperlinkStyleNo(
        Sender as TCustomRichViewEdit);
  URL := rvActionInsertHyperlink1.EncodeTarget(Target);
  ItemTag := Integer(StrNew(PChar(URL)));
end;

// Exporting hyperlink to RTF and HTML
procedure TfrmMain.SRichViewEdit1WriteHyperlink(Sender: TCustomRichView;
  id: Integer; RVData: TCustomRVData; ItemNo: Integer;
  SaveFormat: TRVSaveFormat; var Target, Extras: string);
begin
  Target := PChar(RVData.GetItemTag(ItemNo));
end;

// URL detection on typing
procedure TfrmMain.SRichViewEdit1KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if Key in [VK_SPACE, VK_RETURN, VK_TAB] then begin
    {
      // uncomment if you use Addict3
      RVA_Addict3AutoCorrect(ActiveEditor.ActiveEditor);
    }
    rvActionInsertHyperlink1.DetectURL(ActiveEditor.ActiveEditor);
    rvActionInsertHyperlink1.TerminateHyperlink(ActiveEditor.ActiveEditor);
  end;
end;


procedure TfrmMain.SRichViewEdit1KeyPress(Sender: TObject; var Key: Char);
begin
  {
  // uncomment if you use Addict3
  if (Key='''') or ((Key<>' ') and (Pos(Key, ActiveEditor.ActiveEditor.Delimiters)<>0)) then
    RVA_Addict3AutoCorrect(ActiveEditor.ActiveEditor);
  }
end;

{--------------------- Working with font combo-boxes --------------------------}
// Switching focus to the ActiveEditor without accidental applying combos
// (the apply changes on exiting)
procedure TfrmMain.FocusActiveEditor;
begin
  if Visible then begin
    UpdatingCombos := True;
    ActiveEditor.SetFocus;
    UpdatingCombos := False;
  end;
end;

// Current font is changed. Updating the combo-boxes.
procedure TfrmMain.SRichViewEdit1CurTextStyleChanged(Sender: TObject);
var CurStyle: TFontInfo;
    rve: TCustomRichViewEdit;
begin
  UpdatingCombos := True;
  try
    rve := Sender as TCustomRichViewEdit;
    if rve=ActiveEditor.ActiveEditor then begin
      CurStyle := rve.Style.TextStyles[rve.CurTextStyleNo];
      cmbFont.Text := CurStyle.FontName;
      cmbFont.OnClick(Sender);
      cmbFontSize.FontName := CurStyle.FontName;
      cmbFontSize.Text := IntToStr(CurStyle.Size);
    end;
  finally
    UpdatingCombos := False;
  end;
end;

// Applying the font name
procedure TfrmMain.cmbFontClick(Sender: TObject);
var FontName: String;
begin
  if UpdatingCombos then
    exit;
  if cmbFont.ItemIndex<0 then
    FontName := cmbFont.Text
  else
    FontName := cmbFont.Items[cmbFont.ItemIndex];
  UpdatingCombos := True;
  cmbFontSize.FontName := FontName;
  UpdatingCombos := False;
  if cmbFont.ItemIndex<0 then
    cmbFont.ItemIndex := cmbFont.Items.IndexOf(FontName);
  if cmbFont.ItemIndex<0 then begin
      if Visible then beep
    end
  else
    with rvActionFontEx1 do begin
      UserInterface := False;
      ValidProperties := [rvfimFontName];
      Font.Name := FontName;
      ExecuteTarget(ActiveEditor.ActiveEditor);
      UserInterface := True;
    end;
  ActiveEditor.SetFocus;
end;

// Changing the font size
procedure TfrmMain.cmbFontSizeClick(Sender: TObject);
var FontSize: Integer;
begin
  if UpdatingCombos then
    exit;
  try
    FontSize := StrToInt(cmbFontSize.Text);
    with rvActionFontEx1 do begin
      UserInterface := False;
      ValidProperties := [rvfimSize];
      Font.Size := FontSize;
      ExecuteTarget(ActiveEditor.ActiveEditor);
      UserInterface := True;
    end;
  except
    if Visible then beep;
  end;
  ActiveEditor.SetFocus;
end;

procedure TfrmMain.cmbKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if Key=VK_RETURN then begin
    Key := 0;
    TComboBox(Sender).OnClick(Sender);
  end;
end;

{----------------------------- Units combo box --------------------------------}
// Applying units
procedure TfrmMain.cmbUnitsClick(Sender: TObject);
var i: Integer;
begin
  for i := 0 to High(Editors) do
    Editors[i].UnitsProgram := TRVUnits(cmbUnits.ItemIndex);
  RVAControlPanel1.UnitsDisplay := TRVUnits(cmbUnits.ItemIndex);
  SclRVRuler1.UnitsDisplay := TRulerUnits(cmbUnits.ItemIndex);
  SclRVRuler2.UnitsDisplay := TRulerUnits(cmbUnits.ItemIndex);
end;

{------- Synchronizing ScaleRichView after non-editing operations -------------}
procedure TfrmMain.RVAControlPanel1MarginsChanged(Sender: TrvAction;
  Edit: TCustomRichViewEdit);
var WasModified: Boolean;
    SRichViewEdit: TSRichViewEdit;
begin
  SRichViewEdit := Editors[GetIndexOfEditorByRichViewEdit(Edit)];
  WasModified := Edit.Modified;

  Edit.RVData.State := Edit.RVData.State + [rvstSkipFormatting];
  SRichViewEdit.SetRVMargins;

  SclRVRuler1.UnitsDisplay := TRulerUnits(ActiveEditor.UnitsProgram);
  SclRVRuler2.UnitsDisplay := TRulerUnits(ActiveEditor.UnitsProgram);
  SclRVRuler1.checkMargin;
  SclRVRuler2.checkMargin;

  Edit.RVData.State := Edit.RVData.State - [rvstSkipFormatting];
  Edit.Modified := WasModified;
  UpdateIcon(SRichViewEdit);
end;

procedure TfrmMain.RVAControlPanel1BackgroundChange(Sender: TrvAction;
  Edit: TCustomRichViewEdit);
begin
  ActiveEditor.Repaint;
end;
{---------------------------- Localization ------------------------------------}
procedure TfrmMain.actLanguageExecute(Sender: TObject);
begin
  if RVA_ChooseLanguage then
    Localize;
end;

procedure TfrmMain.Localize;
var i: Integer;
begin
  // Localizing all actions on this form
  RVA_LocalizeForm(Self);
  // Assigning alternative captions
  srvActionQuickPrint1.Caption := RVA_GetS(rvam_act_QuickPrint2);
  rvActionInsertTable1.Caption := RVA_GetS(rvam_act_InsertTable2);
  // Localizing ruler
  RVALocalizeRuler(SclRVRuler1);
  RVALocalizeRuler(SclRVRuler2);
  // Localizing the editors
  for i := 0 to High(Editors) do begin
    SRVA_LocalizeSRichViewEdit(Editors[i]);
    TSRVToolButton(Editors[i].MenuHButtons.Items[0]).Hint := RVADeleteAmp(SRVA_GetS(srvam_act_Draft));
    TSRVToolButton(Editors[i].MenuHButtons.Items[1]).Hint := RVADeleteAmp(SRVA_GetS(srvam_act_WebLayout));
    TSRVToolButton(Editors[i].MenuHButtons.Items[2]).Hint := RVADeleteAmp(SRVA_GetS(srvam_act_PrintLayout));
  end;
  // Localizing the search tool window
  SRVA_LocalizeToolWindow(srvtwSearch);
  // Localizing ribbon
  LocalizeRibbonPage(ribHome, rvam_ribt_MainTab1);
  LocalizeRibbonPage(ribAdvanced, rvam_ribt_MainTab2);
  LocalizeRibbonPage(ribView, rvam_ribt_View);
  LocalizeRibbonPage(ribTable, rvam_ribt_Table);
  ribgClipboard.Caption := RVA_GetS(rvam_ribg_Clipboard);
  ribgFont.Caption := RVA_GetS(rvam_ribg_Font);
  ribgParagraph.Caption := RVA_GetS(rvam_ribg_Paragraph);
  ribgList.Caption := RVA_GetS(rvam_ribg_List);
  ribgEditing.Caption := RVA_GetS(rvam_ribg_Edit);
  ribgInsert.Caption := RVA_GetS(rvam_ribg_Insert);
  ribgFootnotes.Caption := RVA_GetS(rvam_ribg_Notes);
  ribgBackground.Caption := RVA_GetS(rvam_ribg_Background);
  ribgPageSetup.Caption := RVA_GetS(rvam_ribg_PageLayout);
  ribgDocView.Caption := RVA_GetS(rvam_ribg_DocumentViews);
  ribgZoom.Caption := RVA_GetS(rvam_ribg_Zoom);
  ribgHeaderFooter.Caption := SRVA_GetS(srvam_ribg_HeaderFooter);
  ribgPreview.Caption := SRVA_GetS(srvam_ribg_Preview);
  ribgViewOptions.Caption := RVA_GetS(rvam_ribg_Options);
  ribgViewOptions.Items[0].Caption := RVA_GetS(rvam_lbl_Units);

  ribgTableInsert.Caption := RVA_GetS(rvam_ribg_TableInsert);
  ribgTableDelete.Caption := RVA_GetS(rvam_ribg_TableDelete);
  ribgTableOperations.Caption := RVA_GetS(rvam_ribg_TableOperations);
  ribgTableBorders.Caption := RVA_GetS(rvam_ribg_TableBorders);
  ActionManager1.ActionBars[2].Items[0].Items[3].Items[0].Caption := RVA_GetS(rvam_rib_SaveAsTitle);
  ActionManager1.ActionBars[2].Items[0].Items[4].Items[0].Caption := RVA_GetS(rvam_rib_PrintTitle);
  Ribbon1.ApplicationMenu.Caption := RVA_GetS(rvam_rib_RecentFiles);
  ScreenTipsManager1.Footer := RVA_GetS(rvam_rib_ScreenTipFooter);

  // Localizing menus
  actTextSize.Caption := RVA_GetS(rvam_menu_FontSize);
  actLineSpacing.Caption := '';
  actTextFlow.Caption := RVA_GetS(rvam_menu_TextFlow);
  actExit.Caption := RVA_GetS(rvam_menu_Exit);
  actSelectInTable.Caption := RVA_GetS(rvam_menu_TableSelect);
  actAlignCell.Caption := RVA_GetS(rvam_menu_TableCellAlign);
  actZoomMenu.Caption := RVA_GetS(rvam_ribg_Zoom);
  actClose.Caption := RVA_GetS(rvam_btn_Close);
  actPageSize.Caption := SRVA_GetS(srvam_menu_PageSize);
  actPageOrientation.Caption := SRVA_GetS(srvam_menu_Orientation);

  // Localizing measuring units
  i := cmbUnits.ItemIndex;
  RVA_TranslateUnits(cmbUnits.Items);
  cmbUnits.ItemIndex := i;

  // Localizing text on the status bar
  SRichViewEdit1CurrentPageChange(ActiveEditor);
  SRichViewEdit1PageScrolled(ActiveEditor);
  SRichViewEdit1CaretMove(ActiveEditor.ActiveEditor);

  {
  // uncomment if you use Addict3. It's assumed that RVAddictSpell31
  // and RVThesaurus31 are on this form.
  RVAddictSpell31.UILanguage := GetAddictSpellLanguage(RVA_GetLanguageName);
  RVThesaurus31.UILanguage := GetAddictThesLanguage(RVA_GetLanguageName);
  }
  FillActionClientContents(ActionManager1);
  RemoveEllipsis(Self);
  ScreenTipsManager1.ScreenTips.Clear;
  ScreenTipsManager1.GenerateScreenTips;
end;

{------------------------------ Status bar ------------------------------------}
// Displaying the index of the edited page
procedure TfrmMain.SRichViewEdit1CurrentPageChange(Sender: TObject);
begin
  if Sender=ActiveEditor then
    stat1.Panels.Items[1].Text := Format(SRVA_GetS(srvam_PageMofN),
      [ActiveEditor.CurrentPage, ActiveEditor.PageCount]);
end;

procedure TfrmMain.SRichViewEdit1PageScrolled(Sender: TObject);
begin
  if Sender=ActiveEditor then
    stat1.Panels.Items[0].Text  := Format(SRVA_GetS(srvam_ViewPageX),
      [ActiveEditor.ScrolledPage]);
end;

// Displaying the current line and column
procedure TfrmMain.SRichViewEdit1CaretMove(Sender: TObject);
var Line, Column : Integer;
begin
  if (ActiveEditor<>nil) and (Sender=ActiveEditor.ActiveEditor) then begin
    ActiveEditor.GetCurrentLineCol(Line, Column);
    stat1.Panels.Items[2].Text := Format(SRVA_GetS(srvam_LineX), [Line]);
    stat1.Panels.Items[3].Text := Format(SRVA_GetS(srvam_ColX), [Column]);
  end;
end;

// switching to header/footer/main
procedure TfrmMain.SRichViewEdit1ChangeActiveEditor(Sender: TSRichViewEdit;
  ActiveEditor: TRichViewEdit);
begin
  SRichViewEdit1CaretMove(ActiveEditor);
end;

// Displaying hints
procedure TfrmMain.ApplicationHint(Sender: TObject);
var s: String;
begin
  s := GetLongHint(Application.Hint);
  stat1.SimplePanel := s<>'';
  stat1.SimpleText := s;
  stat1.Repaint;
end;
{--------------- Buttons on scroll-bars: view modes ---------------------------}
// On horizontal scroll bar (view modes)
procedure TfrmMain.SRichViewEdit1HMenuClickButton(Sender: TObject;
  ToolButton: TSRVToolButton);
begin
  if ToolButton = nil then Exit;
  ActiveEditor.CanUpdate := False;
  case (ToolButton.Index) of
    0 : srvActionLayoutDraft1.Execute;
    1 : srvActionLayoutWeb1.Execute;
    2 : srvActionLayoutPrint1.Execute;
  end;
  ActiveEditor.CanUpdate := True;
end;

// After doc view actions are executed
procedure TfrmMain.srvActionLayoutDraft1Executed(Sender: TObject);
begin
  TSRVToolButton(ActiveEditor.MenuHButtons.Items[0]).Down := True;
end;

procedure TfrmMain.srvActionLayoutWeb1Executed(Sender: TObject);
begin
  TSRVToolButton(ActiveEditor.MenuHButtons.Items[1]).Down := True;
end;

procedure TfrmMain.srvActionLayoutPrint1Executed(Sender: TObject);
begin
  TSRVToolButton(ActiveEditor.MenuHButtons.Items[2]).Down := True;
end;
{------------------ Buttons on scroll-bars: search ---------------------------}
// On vertical scroll bar
procedure TfrmMain.SRichViewEdit1VMenuClickButton(Sender: TObject;
  ToolButton: TSRVToolButton);
var
     sbX, sbY : Integer;
     p : TPoint;
begin
  if ToolButton = nil then Exit;
  case ToolButton.Index of
    0 :  // "Up arrows" button, performs search to the top
      begin
          case VToolButtonIndex of
            SRV_TOOLWIN_PAGE, -1 : ActiveEditor.PriorCurPage;
            SRV_TOOLWIN_TABLE : ActiveEditor.PriorCurItem([rvsTable]);
            SRV_TOOLWIN_PICTURE : ActiveEditor.PriorCurItem([rvsPicture, rvsHotspot, rvsHotPicture]);
            SRV_TOOLWIN_HEADLINE : ActiveEditor.PriorCurHeading;
            SRV_TOOLWIN_HYPERLINK : ActiveEditor.PriorCurHyperlink;
            SRV_TOOLWIN_TEXT :
              begin
                fd.Options := fd.Options - [frDown];
                fdFind(nil);
              end;
          end;
      end;
    1 : // "Circle" button, shows tool window
      begin
        sbX := ActiveEditor.MenuVertical.SRVToolBar.Width;
        sbY := ActiveEditor.MenuVertical.SRVToolBar.Height div 3;

        p := ActiveEditor.MenuVertical.SRVToolBar.ClientToScreen(Point(0, 0));
        p.Y := p.Y + sbY;

        srvtwSearch.Execute(Bounds(p.x, p.y, sbX, sbY));
      end;
    2 : // "Down arrows" button, performs search to the bottom
      begin
          case VToolButtonIndex of
            SRV_TOOLWIN_PAGE, -1 : ActiveEditor.NextCurPage;
            SRV_TOOLWIN_TABLE : ActiveEditor.NextCurItem([rvsTable]);
            SRV_TOOLWIN_PICTURE : ActiveEditor.NextCurItem([rvsPicture, rvsHotspot, rvsHotPicture]);
            SRV_TOOLWIN_HEADLINE : ActiveEditor.NextCurHeading;
            SRV_TOOLWIN_HYPERLINK : ActiveEditor.NextCurHyperlink;
            SRV_TOOLWIN_TEXT :
              begin
                fd.Options := fd.Options + [frDown];
                fdFind(nil);
              end;
          end;
      end;
  end;
end;
// Button on the tool window is clicked
procedure TfrmMain.srvtwSearchClickButton(Sender: TObject;
  ToolButton: TSRVToolButton);
var
     s: String;
     posit: Integer;
begin
  if ToolButton = nil then begin
    VToolButtonIndex := -1;
    Exit;
    end
  else
    VToolButtonIndex := ToolButton.Index;
  if ToolButton.Index = SRV_TOOLWIN_TEXT then // starting text search
    begin
      ActiveEditor.SetFocus;
      fd.CloseDialog;
      if ActiveEditor.RichViewEdit.SelectionExists then
        begin
          s := ActiveEditor.RichViewEdit.GetSelText;
          posit := Pos(#13,s);
          if posit<>0 then
            s := Copy(s,1,posit-1);
          fd.FindText := s;
        end;
      fd.Execute;
    end
  else // starting search
    SRichViewEdit1VMenuClickButton(Sender,
      TSRVToolButton(ActiveEditor.MenuVButtons.Items[2]));
end;
// text search
procedure TfrmMain.fdFind(Sender: TObject);
begin
  if not ActiveEditor.RichViewEdit.SearchText(fd.FindText,GetRVESearchOptions(fd.Options)) then
    ShowInfo(Format(RVA_GetS(rvam_src_NotFound), [fd.FindText]), RVA_GetS(rvam_src_Complete));
  ActiveEditor.Repaint;
end;

{-------------------------------- Misc. ---------------------------------------}
// Event on downloading image
procedure TfrmMain.RVAControlPanel1Download(Sender: TrvAction;
  const Source: String);
begin
  if Source='' then
    Application.Hint := ''
  else
    Application.Hint := 'Downloading '+Source+'...';
end;

// On clicking a table icon
procedure TfrmMain.SRichViewEdit1TableIconClick(Sender: TSRichViewEdit;
  Button: TMouseButton; Shift: TShiftState; X, Y, PageNo: Integer);
begin
  Sender.GetTableIconItem.SelectRows(0, Sender.GetTableIconItem.RowCount);
  Sender.Repaint;
end;

// Showing table insertion widget instead of dialog
procedure TfrmMain.rvActionInsertTable1Execute(Sender: TObject);
begin
  rvActionInsertTable1.ShowTableSizeDialog(ActiveEditor.RichViewEdit,
    rvActionInsertTable1.ActionComponent as TControl);
end;

// Exiting
procedure TfrmMain.actExitExecute(Sender: TObject);
begin
  Close;
end;

// Showing help
procedure TfrmMain.Ribbon1HelpButtonClick(Sender: TObject);
//var HelpFileName: String;
begin
  //HelpFileName := ExtractFilePath(Application.ExeName)+'Help\RichViewActions.chm';
  //RvHtmlHelp(HelpFileName);
end;

// After TsrvActionThumbnails is executed
procedure TfrmMain.srvActionThumbnails1Executed(Sender: TObject);
begin
  Splitter1.Visible := TsrvActionThumbnails(Sender).Checked;
  SRVPageScroll1.Visible := TsrvActionThumbnails(Sender).Checked;
end;

{-------------------------- Tabbed User Interface -----------------------------}
{
  Main variables:
  Editors[] - array of opened editors, in the order of tabs
  ActiveEditor - focused editor (on the active tab). This editor is visible,
    others are hidden.
}

// Returns the index of tab icon depending on IsNew (document was created
// but never saved), FileFormat, Modified (document has unsaved changes)
function TfrmMain.GetIconIndex(IsNew: Boolean; FileFormat: TrvFileSaveFilter; Modified: Boolean): Integer;
begin
  Result := 0;
  if not IsNew then
    case FileFormat of
      ffeRVF:
        Result := 1;
      ffeRTF:
        Result := 2;
      ffeTextANSI, ffeTextUnicode:
        Result := 3;
    end;
  if Modified then
    inc(Result, 4);
end;

// rvActionSave1.OnDocumentFileChange: occurs when document is created, saved, loaded...
// This event occurs on New, SaveAs, Open actions
procedure TfrmMain.rvActionSave1DocumentFileChange(Sender: TObject;
  Editor: TCustomRichViewEdit; const FileName: string;
  FileFormat: TrvFileSaveFilter; IsNew: Boolean);
var s: String;
    Index: Integer;
    TI: TSRVTabItem;
begin
  s := ExtractFileName(FileName);
  srvActionPrint1.Title := s;
  srvActionQuickPrint1.Title := s;
  if IsNew then
    s := s+' (*)';
  if not IsNew then begin
    Index := Ribbon1.AddRecentItem(FileName);
    if Index>=0 then
      Ribbon1.ApplicationMenu.Menu.RecentItems[Index].Tag := ord(FileFormat);
  end;
  Index := GetIndexOfEditorByRichViewEdit(Editor);
  If Index >= 0 then begin
    TI := SRVTabSet1.Tabs[Index];
    TI.Text := s;
    TI.ImageIndex := GetIconIndex(IsNew, FileFormat, False);
  end;
end;

procedure TfrmMain.rvActionVAlign1Execute(Sender: TObject);
begin

end;

// Prompt for saving...
procedure TfrmMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
  While SRVTabSet1.Tabs.Count > 0 do begin
    CanClose := rvActionSave1.CanCloseDoc(ActiveEditor.RichViewEdit);
    If CanClose then
      If SRVTabSet1.Tabs.Count > 1 then begin
        RemoveEditor(SRVTabSet1.TabIndex);
        SRVTabSet1.Tabs[SRVTabSet1.TabIndex].Free;
        SetEditor(SRVTabSet1.Tabs.Count-1);
        UpdateCloseAction;
      end else
        Break
    else
      Break;
  end;
end;

// Returns the index of TSRichViewEdit in Editors[] by its RichViewEdit
function TfrmMain.GetIndexOfEditorByRichViewEdit(rve: TCustomRichViewEdit): Integer;
var i: Integer;
begin
  for i:=0 to High(Editors) do
    If Editors[i].RichViewEdit=rve then begin
      Result := i;
      Exit;
    end;
  Result := -1;
end;

// Returns information about document opened in TRichViewEdit
function TfrmMain.GetDocInfo(rve: TCustomRichViewEdit): TrvaDocumentInfo;
var DocIndex: Integer;
begin
  DocIndex := rvActionSave1.FindDoc(rve);
  if DocIndex>=0 then
    Result := TrvaDocumentInfo(rvActionSave1.Documents[DocIndex])
  else
    Result := nil;
end;

// Returns information about the active document (opened in ActiveEditor)
function TfrmMain.GetActiveDocInfo: TrvaDocumentInfo;
begin
  Result := GetDocInfo(ActiveEditor.RichViewEdit);
end;

// Adds a new tab with editor, making it active
procedure TfrmMain.AddEditor;
var
     srve : TSRichViewEdit;
begin
  SetLength(Editors, Length(Editors)+1);

  srve := TSRichViewEdit.Create(ActiveEditor.Owner);
  srve.Hide;
  srve.Parent := ActiveEditor.Parent;
  srve.Align := alClient;
  srve.BackgroundProperty.Assign(ActiveEditor.BackgroundProperty);
  srve.MenuHorizontal.Assign(ActiveEditor.MenuHorizontal);
  srve.MenuVertical.Assign(ActiveEditor.MenuVertical);
  srve.UnitsProgram := ActiveEditor.UnitsProgram;
  srve.PopupMenu := ActiveEditor.PopupMenu;
  srve.SkinManager := ActiveEditor.SkinManager;
  srve.ViewProperty.MarginsRectVisible := ActiveEditor.ViewProperty.MarginsRectVisible;
  srve.HScrollBarSchemeIndex := ActiveEditor.HScrollBarSchemeIndex;
  srve.VScrollBarSchemeIndex := ActiveEditor.VScrollBarSchemeIndex;
  srve.OnCaretMove := SRichViewEdit1CaretMove;
  srve.OnCurrentPageChange := SRichViewEdit1CurrentPageChange;
  srve.OnCurTextStyleChanged := SRichViewEdit1CurTextStyleChanged;
  srve.OnHMenuClickButton := SRichViewEdit1HMenuClickButton;
  srve.OnJump := SRichViewEdit1Jump;
  srve.OnKeyDown := SRichViewEdit1KeyDown;
  srve.OnCurrentPageChange := SRichViewEdit1CurrentPageChange;
  srve.OnPageScrolled := SRichViewEdit1PageScrolled;
  srve.OnTableIconClick := SRichViewEdit1TableIconClick;
  srve.OnVMenuClickButton := SRichViewEdit1VMenuClickButton;
  srve.OnWriteHyperlink := SRichViewEdit1WriteHyperlink;
  srve.OnReadHyperlink := SRichViewEdit1ReadHyperlink;
  srve.OnChange := SRichViewEdit1Change;
  srve.Loaded;
  srve.ConvertToTwips;
  SRVA_LocalizeSRichViewEdit(srve);

  srve.Show;
  ActiveEditor.Hide;
  ActiveEditor := srve;

  srve.ResetEventRuler;
  SclRVRuler1.SRichViewEdit := srve;
  SclRVRuler2.SRichViewEdit := srve;
  SRVPageScroll1.SRichViewEdit := srve;



  Editors[High(Editors)] := srve;

  SRVTabSet1.Tabs.Add;
  SRVTabSet1.TabIndex := High(Editors); // calls SetEditor
  // Some assignments may set Modified flag, resetting
  srve.RichViewEdit.Modified := False;
  UpdateIcon(srve);
  FocusActiveEditor;
  UpdateCloseAction;
end;

// Makes Editors[Index] active
procedure TfrmMain.SetEditor(Index : Integer);
var DocInfo: TrvaDocumentInfo;
begin
  Index := Min(Max(Index, 0), SRVTabSet1.Tabs.Count-1);

  If SRVTabSet1.TabIndex <> Index then
    SRVTabSet1.TabIndex := Index;

  If ActiveEditor <> Editors[Index] then begin
    if ActiveEditor<>nil then
      ActiveEditor.Hide;
    ActiveEditor := Editors[Index];
    ActiveEditor.Show;
  end;
  RVAControlPanel1.DefaultControl := ActiveEditor.RichViewEdit;
  ActiveEditor.ResetEventRuler;
  SclRVRuler1.SRichViewEdit := ActiveEditor;
  SclRVRuler2.SRichViewEdit := ActiveEditor;
  SRVPageScroll1.SRichViewEdit := ActiveEditor;
  DocInfo := GetActiveDocInfo;
  if DocInfo<>nil then begin
    srvActionPrint1.Title := ExtractFileName(DocInfo.FileName);
    srvActionQuickPrint1.Title := ExtractFileName(DocInfo.FileName);
  end;
  RVAControlPanel1MarginsChanged(nil, ActiveEditor.RichViewEdit);
  SRichViewEdit1CurrentPageChange(ActiveEditor);
  SRichViewEdit1PageScrolled(ActiveEditor);
  FocusActiveEditor;
end;

// Deletes Editors[Index] (but does not deletes its tab)
// Usually this function is used to close the active editor
procedure TfrmMain.RemoveEditor(Index : Integer);
var i: Integer;
begin
  i := rvActionSave1.FindDoc(Editors[Index].RichViewEdit);
  if i>=0 then
    rvActionSave1.Documents.Delete(i);
  if Editors[Index]=ActiveEditor then begin
    SclRVRuler1.SRichViewEdit := nil;
    SclRVRuler2.SRichViewEdit := nil;
    SRVPageScroll1.SRichViewEdit := nil;
    ActiveEditor := nil;
  end;
  Editors[Index].Free;
  for i := Index to High(Editors)-1 do
    Editors[i] := Editors[i+1];
  SetLength(Editors, Length(Editors)-1);
  UpdateCloseAction;
end;

// Open a file from the recent list
procedure TfrmMain.Ribbon1RecentItemClick(Sender: TObject; FileName: string;
  Index: Integer);
var i: Integer;
begin
  Index := 0;
  for i := 0 to Ribbon1.ApplicationMenu.Menu.RecentItems.Count-1 do
    if CompareText(Ribbon1.ApplicationMenu.Menu.RecentItems[i].Caption, FileName)=0 then begin
      Index := i;
      break;
    end;
  rvActionOpen1.LoadFile(ActiveEditor.RichViewEdit, FileName,
    TrvFileOpenFilter(Ribbon1.ApplicationMenu.Menu.RecentItems[Index].Tag));
end;

// SRVTabSet1.OnChange: another tab became active
procedure TfrmMain.SRVTabSet1Change(Sender: TObject);
begin
  SetEditor(SRVTabSet1.TabIndex);
end;

// SRVTabSet1.OnCloseTab: checking if we can close this tab
procedure TfrmMain.SRVTabSet1CloseTab(Sender: TSRVTabSet; TabIndex: Integer;
  var CanClose: Boolean);
begin
  CanClose := rvActionSave1.CanCloseDoc(Editors[TabIndex].RichViewEdit);
  If CanClose then
    RemoveEditor(TabIndex);
end;

procedure TfrmMain.UpdateCloseAction;
begin
  actClose.Enabled := Length(Editors)>1;
end;

// Closing from the menu
procedure TfrmMain.actCloseExecute(Sender: TObject);
var TabIndex: Integer;
begin
  if (SRVTabSet1.Tabs.Count>1) and
    rvActionSave1.CanCloseDoc(ActiveEditor.RichViewEdit) then begin
      TabIndex := SRVTabSet1.TabIndex;
      RemoveEditor(TabIndex);
      SRVTabSet1.Tabs[TabIndex].Free;
      if TabIndex=SRVTabSet1.Tabs.Count then
        dec(TabIndex);
      SetEditor(TabIndex);
    end;
end;

// SRVTabSet1.OnTabMove - exchanging tabs
procedure TfrmMain.SRVTabSet1TabMove(Sender: TSRVTabSet; NewTabIndex,
  OldTabIndex: Integer);
var
  tmp : TSRichViewEdit;
begin
  tmp := Editors[OldTabIndex];
  Editors[OldTabIndex] := Editors[NewTabIndex];
  Editors[NewTabIndex] := tmp;
end;

// rvActionNew1.OnExecute:
procedure TfrmMain.rvActionNew1Execute(Sender: TObject);
begin
  // Instead of applying to the active editor,
  // we creating a new editor, making it active,
  AddEditor;
  // then execute rvActionNew for this new editor
  rvActionNew1.ExecuteTarget(ActiveEditor.RichViewEdit);
  // Some assignments may set Modified flag, resetting
  ActiveEditor.RichViewEdit.Modified := False;
  UpdateIcon(ActiveEditor);
end;

// rvActionOpen1.OnExecute
procedure TfrmMain.rvActionOpen1Execute(Sender: TObject);
var DocInfo: TrvaDocumentInfo;
begin
  // Instead of applying to the active editor,
  // we creating a new editor, making it active,
  AddEditor;
  // then execute rvActionOpen for this new editor
  rvActionOpen1.ExecuteTarget(ActiveEditor.RichViewEdit);
  // Some assignments may set Modified flag, resetting
  ActiveEditor.RichViewEdit.Modified := False;
  UpdateIcon(ActiveEditor);
  // But may be the user pressed "Cancel" in the file opening dialog.
  // In this case, we closing the new tab.
  DocInfo := GetActiveDocInfo;
  if (DocInfo=nil) or not DocInfo.Defined then begin
    RemoveEditor(SRVTabSet1.TabIndex);
    SRVTabSet1.Tabs[SRVTabSet1.TabIndex].Free;
    SetEditor(Max(SRVTabSet1.TabIndex-1, 0));
  end;
end;

// updating tab icon depending on Editor.RichViewEdit.Modified
procedure TfrmMain.UpdateIcon(Editor: TSRichViewEdit);
var EditIndex: Integer;
    TI : TSRVTabItem;
    DocInfo: TrvaDocumentInfo;
begin
  // Updating the tab icon to show a "modified" state
  DocInfo := GetDocInfo(Editor.RichViewEdit);
  if DocInfo=nil then
    exit;
  EditIndex := GetIndexOfEditorByRichViewEdit(DocInfo.rve);
  If EditIndex >= 0 then begin
    TI := SRVTabSet1.Tabs[EditIndex];
    TI.ImageIndex := GetIconIndex(not DocInfo.Defined, DocInfo.FileFormat,
      Editor.RichViewEdit.Modified);
  end;
end;


// OnChange event (usually called for the ActiveEditor)
procedure TfrmMain.SRichViewEdit1Change(Sender: TObject);
begin
  UpdateIcon(Sender as TSRichViewEdit);
end;


{---------------------- Live spelling with Addict 3 ---------------------------}
(*
// Add these events if you use Addict3
// (Assuming that you have RVAddictSpell31: TRVAddictSpell3 on the form)

// RichViewEdit1.OnSpellingCheck event
procedure TForm3.RichViewEdit1SpellingCheck(Sender: TCustomRichView;
  const AWord: String; StyleNo: Integer; var Misspelled: Boolean);
begin
  Misspelled := not RVAddictSpell31.WordAcceptable(AWord);
end;

// RVAddictSpell31.OnParserIgnoreWord: if Ignore All or Add buttons were pressed
// in spellchecker dialog, removing underlines from the ignored word
procedure TForm3.RVAddictSpell31ParserIgnoreWord(Sender: TObject;
  Before: Boolean; State: Integer);
begin
  if not Before and (State in [IgnoreState_IgnoreAll, IgnoreState_Add]) then
    RichViewEdit1.LiveSpellingValidateWord(RVAddictSpell31.CurrentWord);
end;

// Besides, if you want spelling check starting when loading document, call
// RichViewEdit1.StartLiveSpelling in rvActionFileOpen.OnOpenFile event
*)


initialization

  RegisterClass(TGifImage);
  RV_RegisterHTMLGraphicFormat(TGifImage);
  RV_RegisterHTMLGraphicFormat(TPngImage);
  RV_RegisterPngGraphic(TPngImage);
  RegisterClassAlias(TPngImage, 'TPNGObject'); // calls RegisterClass(TPngImage);

// IMPORTANT: allowing RichViewActions and TRVAPopupMenu working with TSRichViewEdit
  RVA_GetRichViewEditFromPopupComponent :=
   SRVGetRichViewEditFromPopupComponent;
  RVA_GetRichViewEdit := SRVGetRichViewEdit;

end.