using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using FastReport.Controls;
using FastReport.Forms;
using FastReport.Utils;
using FastReport.Design.PageDesigners.Page;
using FastReport.Design.Toolbars;
using FastReport.DevComponents.DotNetBar;

namespace FastReport.Design.StandardDesigner
{
    /// <summary>
    /// Represents standard designer's form.
    /// </summary>
    /// <remarks>
    /// This form contains the <see cref="DesignerControl"/>. Use the <see cref="Designer"/> 
    /// property to get access to this control.
    /// <para/>Usually you don't need to create an instance of this class. The designer can be called
    /// using the <see cref="FastReport.Report.Design()"/> method of 
    /// the <see cref="FastReport.Report"/> instance.
    /// <para/>If you decided to use this class, you need:
    /// <list type="bullet">
    ///   <item>
    ///     <description>create an instance of this class;</description>
    ///   </item>
    ///   <item>
    ///     <description>set the <b>Designer.Report</b> property to report that you need to design;</description>
    ///   </item>
    ///   <item>
    ///     <description>call either <b>ShowModal</b> or <b>Show</b> methods to display a form.</description>
    ///   </item>
    /// </list>
    /// </remarks>
    public partial class DesignerForm : BaseForm, IDesignerPlugin
    {
        #region Fields
        private Dictionary<BaseItem, ItemInfo> ribbonItems = new Dictionary<BaseItem, ItemInfo>();
        #endregion

        #region Properties
        /// <summary>
        /// Gets a reference to the <see cref="Designer"/> control which is actually a designer.
        /// </summary>
        public DesignerControl Designer
        {
            get { return designer; }
        }

        /// <summary>
        /// Gets a list of File menu buttons
        /// </summary>
        public Dictionary<string, ButtonItem> Items
        {
            get
            {
                if (items == null)
                {
                    items = new Dictionary<string, ButtonItem>();
                    items.Add("btnFileNew", this.btnFileNew);
                    items.Add("btnFileOpen", this.btnFileOpen);
                    items.Add("btnFileSave", this.btnFileSave);
                    items.Add("btnFileSaveAs", this.btnFileSaveAs);
                    items.Add("btnFileSaveWithRandomData", this.btnFileSaveWithRandomData);
                    items.Add("btnFileSaveAll", this.btnFileSaveAll);
                    items.Add("btnFilePreview", this.btnFilePreview);
                    items.Add("btnFilePrinterSetup", this.btnFilePrinterSetup);
                    items.Add("btnFileSelectLanguage", this.btnFileSelectLanguage);
                    items.Add("btnWelcome", this.btnWelcome);
                    items.Add("btnHelp", this.btnHelp);
                    items.Add("btnAbout", this.btnAbout);
                    items.Add("btnFileClose", this.btnFileClose);
                }

                return items;
            }
        }

        private ReportWorkspace Workspace
        {
            get
            {
                if (designer.ActiveReportTab != null && designer.ActiveReportTab.ActivePageDesigner is ReportPageDesigner)
                    return (Designer.ActiveReportTab.ActivePageDesigner as ReportPageDesigner).Workspace;
                return null;
            }
        }

        private ReportPageDesigner ReportPageDesigner
        {
            get
            {
                //Fixed try catch 66fcd219-30f1-45e6-8ee5-ce65cfb9d35d
                //rly annoying freezes on designer start
                ReportTab tab = Designer.ActiveReportTab;
                if (tab != null)
                    return tab.ActivePageDesigner as ReportPageDesigner;
                return null;
            }
        }

        private PageBase Page
        {
            get
            {
                //Fixed try catch 66fcd219-30f1-45e6-8ee5-ce65cfb9d35d
                //rly annoying freezes on designer start
                ReportPageDesigner d = ReportPageDesigner;
                if (d != null)
                    return d.Page;
                return null;
            }
        }

        private DesignerControl designer;
        private Dictionary<string, ButtonItem> items;
        private Timer clipboardTimer;
        private Timer previewTimer;
        #endregion

        /// <summary>
        /// Creates a new instance of the <see cref="DesignerForm"/> class with default settings.
        /// </summary>
        public DesignerForm()
        {
            InitDesigner();
        }

        /// <summary>
        /// Creates a new instance of the <see cref="DesignerForm"/> class with default settings.
        /// </summary>
        /// <param name="welcome">enables welcome window</param>
        public DesignerForm(bool welcome)
        {
            InitDesigner();
            if (welcome)
                Shown += ShowWelcomeWindow;
        }

        private void InitDesigner()
        {
            RightToLeft = Config.RightToLeft ? RightToLeft.Yes : RightToLeft.No;
            InitializeComponent();
            if (Config.RightToLeft)
            {
                btnFind.ImagePosition = eImagePosition.Right;
                btnSelectAll.ImagePosition = eImagePosition.Right;
            }

            Font = DrawUtils.DefaultFont;
            Icon = Config.DesignerSettings.Icon;

            designer = new DesignerControl();

            this.ribbonControl.AllowDrop = true;
            this.AllowDrop = true;
            this.ribbonControl.RecalcLayout();

            Controls.Add(designer);
            designer.Dock = DockStyle.Fill;
            designer.BringToFront();
            designer.Plugins.Add(this);
            designer.ShowStatusBar = true;

            SetupControls();

            Localize();
            UpdateDpiDependencies();

            KeyPreview = true;
            KeyDown += DesignerForm_KeyDown;
            designer.UIStyle = Config.UIStyle;
        }

        /// <inheritdoc/>
        protected override void WndProc(ref Message m)
        {
            const int WM_ACTIVATEAPP = 0x001C;
            if (m.Msg == WM_ACTIVATEAPP)
            {
                if (m.WParam == IntPtr.Zero)
                {
                    PopupManager.CloseAllPopups();
                }
            }
            base.WndProc(ref m);
        }

        private void DesignerForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 0x9 && e.Control)
            {
                if (e.Shift)
                    Designer.ActiveReportTab.CtrlShiftTab();
                else
                    Designer.ActiveReportTab.CtrlTab();

                e.Handled = true;
            }
        }

        private void ShowWelcomeWindow(object s, EventArgs e)
        {
            Shown -= ShowWelcomeWindow;

            if (Config.WelcomeEnabled &&
                Config.WelcomeShowOnStartup &&
                String.IsNullOrEmpty(designer.Report.FileName))
            {
                Designer.cmdWelcome.Invoke();
            }
        }

        #region Utils

        private void CreateItem(BaseItem item, string textRes)
        {
            CreateItem(item, -1, textRes, textRes, null);
        }

        private void CreateItem(BaseItem item, string textRes, EventHandler click)
        {
            CreateItem(item, -1, textRes, textRes, click);
        }

        private void CreateItem(BaseItem item, int imageIndex, string textRes)
        {
            CreateItem(item, imageIndex, textRes, textRes, null);
        }

        private void CreateItem(BaseItem item, int imageIndex, string textRes, EventHandler click)
        {
            CreateItem(item, imageIndex, textRes, textRes, click);
        }

        private void CreateItem(BaseItem item, int imageIndex, string textRes, string tooltipRes, EventHandler click)
        {
            ribbonItems.Add(item, new ItemInfo(imageIndex, "", textRes, tooltipRes));
            if (click != null)
                item.Click += click;
        }

        private void CreateItem(BaseItem item, string imageRes, string textRes, EventHandler click)
        {
            CreateItem(item, imageRes, textRes, textRes, click);
        }

        private void CreateItem(BaseItem item, string imageRes, string textRes, string tooltipRes, EventHandler click)
        {
            ribbonItems.Add(item, new ItemInfo(-1, imageRes, textRes, tooltipRes));
            if (click != null)
                item.Click += click;
        }

        #endregion

        #region Setup Controls
        private void SetupControls()
        {
            SetupFileControls();
            SetupHomeControls();
            SetupReportControls();
            SetupLayoutControls();
            SetupViewControls();
        }

        private void SetupFileControls()
        {
            Bitmap cap = new Bitmap(32, 32);
            btnFile.PopupOpen += miFile_PopupOpen;

            string res = "Designer,Menu,File,";
            string res1 = "Designer,Toolbar,Standard,";

            CreateItem(btnFileNew, res + "New", Designer.cmdNew.Invoke);
            CreateItem(btnFileOpen, -1, res + "Open", res1 + "Open", Designer.cmdOpen.Invoke);
            CreateItem(btnFileClose, res + "Close", Designer.cmdClose.Invoke);
            CreateItem(btnFileSave, -1, res + "Save", res1 + "Save", Designer.cmdSave.Invoke);
            CreateItem(btnFileSaveAs, res + "SaveAs", Designer.cmdSaveAs.Invoke);
            CreateItem(btnFileSaveWithRandomData, res + "SaveWithRandomData", Designer.cmdSaveWithRandomData.Invoke);
            CreateItem(btnFileSaveAll, -1, res + "SaveAll", res1 + "SaveAll", Designer.cmdSaveAll.Invoke);
            CreateItem(btnFilePrinterSetup, res + "PrinterSetup", Designer.cmdPrinterSetup.Invoke);
            CreateItem(btnFilePreview, res + "Preview", btnPreview_Click);
            btnFilePreview.Image = cap;
            CreateItem(btnFileSelectLanguage, res + "SelectLanguage", Designer.cmdSelectLanguage.Invoke);
            btnFileSelectLanguage.Image = cap;
            CreateItem(btnFileExit, res + "Exit", Designer.Exit);
            CreateItem(btnOptions, "Designer,Menu,View,Options", Designer.cmdOptions.Invoke);
            CreateItem(btnAccount, 257, "Designer,Menu,Help,Account", Designer.cmdAccount.Invoke);
            CreateItem(btnWelcome, "Designer,Welcome,Button", Designer.cmdWelcome.Invoke);
            btnWelcome.Visible = Designer.cmdWelcome.Enabled;
            btnWelcome.Image = cap;
            CreateItem(btnHelp, "Designer,Menu,Help,Contents", Designer.cmdHelpContents.Invoke);
            btnHelp.Image = cap;
            CreateItem(btnAbout, "Designer,Menu,Help,About", Designer.cmdAbout.Invoke);
            btnAbout.Image = cap;
        }

        private void SetupHomeControls()
        {
            string res = "Designer,Menu,Edit,";
            string res1 = "Designer,Toolbar,Standard,";

            //-------------------------------------------------------------------
            // Undo
            //-------------------------------------------------------------------

            CreateItem(btnUndo, 8, res + "Undo", res1 + "Undo", Designer.cmdUndo.Invoke);
            CreateItem(btnRedo, 9, res + "Redo", res1 + "Redo", Designer.cmdRedo.Invoke);

            //-------------------------------------------------------------------
            // Clipboard
            //-------------------------------------------------------------------

            CreateItem(btnCut, 5, res + "Cut", res1 + "Cut", Designer.cmdCut.Invoke);
            CreateItem(btnCopy, 6, res + "Copy", res1 + "Copy", Designer.cmdCopy.Invoke);
            CreateItem(btnPaste, "Ribbon.Paste.png", res + "Paste", res1 + "Paste", Designer.cmdPaste.Invoke);
            CreateItem(btnFormatPainter, 18, res1 + "FormatPainter", Designer.cmdFormatPainter.Invoke);

            clipboardTimer = new Timer();
            clipboardTimer.Interval = 500;
            clipboardTimer.Tick += clipboardTimer_Tick;
            clipboardTimer.Start();

            //-------------------------------------------------------------------
            // Text
            //-------------------------------------------------------------------
            res = "Designer,Toolbar,Text,";
            CreateItem(cbxFontName, res + "Name");
            cbxFontName.FontSelected += cbxName_FontSelected;
            CreateItem(cbxFontSize, res + "Size");
            cbxFontSize.SizeSelected += cbxSize_SizeSelected;
            CreateItem(btnTextColor, 23, res + "Color", btnColor_Click);
            btnTextColor.SetStyle(designer.UIStyle);
            CreateItem(btnBold, 20, res + "Bold", btnBold_Click);
            CreateItem(btnItalic, 21, res + "Italic", btnItalic_Click);
            CreateItem(btnUnderline, 22, res + "Underline", btnUnderline_Click);
            CreateItem(btnAlignLeft, 25, res + "Left", btnLeft_Click);
            CreateItem(btnAlignCenter, 26, res + "Center", btnCenter_Click);
            CreateItem(btnAlignRight, 27, res + "Right", btnRight_Click);
            CreateItem(btnJustify, 28, res + "Justify", btnJustify_Click);
            CreateItem(btnAlignTop, 29, res + "Top", btnTop_Click);
            CreateItem(btnAlignMiddle, 30, res + "Middle", btnMiddle_Click);
            CreateItem(btnAlignBottom, 31, res + "Bottom", btnBottom_Click);
            CreateItem(btnTextRotation, 64, res + "Angle", btnRotation_Click);

            //-------------------------------------------------------------------
            // Border and Fill
            //-------------------------------------------------------------------
            res = "Designer,Toolbar,Border,";
            CreateItem(btnTopLine, 32, res + "Top", btnTopLine_Click);
            CreateItem(btnBottomLine, 33, res + "Bottom", btnBottomLine_Click);
            CreateItem(btnLeftLine, 34, res + "Left", btnLeftLine_Click);
            CreateItem(btnRightLine, 35, res + "Right", btnRightLine_Click);
            CreateItem(btnAllLines, 36, res + "All", btnAll_Click);
            CreateItem(btnNoLines, 37, res + "None", btnNone_Click);
            CreateItem(btnFillColor, 38, res + "FillColor", btnFillColor_Click);
            btnFillColor.DefaultColor = Color.Transparent;
            CreateItem(btnFillProps, 141, res + "FillStyle", btnFillProps_Click);
            CreateItem(btnLineColor, 39, res + "LineColor", btnLineColor_Click);
            btnLineColor.DefaultColor = Color.Black;
            CreateItem(btnLineWidth, 71, res + "Width");
            btnLineWidth.WidthSelected += cbxWidth_WidthSelected;
            CreateItem(btnLineStyle, 85, res + "Style");
            btnLineStyle.StyleSelected += cbxLineStyle_StyleSelected;
            CreateItem(btnBorderProps, 40, res + "Props", btnBorderProps_Click);

            //-------------------------------------------------------------------
            // Format
            //-------------------------------------------------------------------

            CreateItem(btnHighlight, "Ribbon.Highlight.png", "Designer,Toolbar,Text,Highlight", btnHighlight_Click);
            CreateItem(btnFormat, "Ribbon.Format.png", "ComponentMenu,TextObject,Format", btnFormat_Click);

            //-------------------------------------------------------------------
            // Styles
            //-------------------------------------------------------------------

            cbxStyles.StyleSelected += cbxStyle_StyleSelected;
            CreateItem(btnStyles, 87, "Designer,Menu,Report,Styles", Designer.cmdReportStyles.Invoke);

            //-------------------------------------------------------------------
            // Editing
            //-------------------------------------------------------------------
            res = "Designer,Menu,Edit,";
            CreateItem(btnFind, 181, res + "Find", Designer.cmdFind.Invoke);
            CreateItem(btnReplace, "Ribbon.Replace.png", res + "Replace", Designer.cmdReplace.Invoke);
            CreateItem(btnSelectAll, 100, res + "SelectAll", Designer.cmdSelectAll.Invoke);

            //-------------------------------------------------------------------
            // Polygon
            //-------------------------------------------------------------------
            res = "Designer,Toolbar,Polygon,";
            CreateItem(btnPolyMove, 256, res + "MoveScale", Designer.CmdPolySelectMove.Invoke);
            CreateItem(btnPolyPointer, 252, res + "Pointer", Designer.CmdPolySelectPointer.Invoke);
            CreateItem(btnPolyAddPoint, 253, res + "AddPoint", Designer.CmdPolySelectAddPoint.Invoke);
            CreateItem(btnPolyAddBezier, 254, res + "Bezier", Designer.CmdPolySelectBezier.Invoke);
            CreateItem(btnPolyRemovePoint, 255, res + "RemovePoint", Designer.CmdPolySelectRemovePoint.Invoke);
        }

        private void SetupReportControls()
        {
            string res = "";
            CreateItem(btnReportOptions, "Ribbon.Report1.png", "Designer,Menu,Report,Options", Designer.cmdReportSettings.Invoke);
            CreateItem(btnPreview, "Ribbon.Report.png", "Designer,Menu,File,Preview", "Designer,Toolbar,Standard,Preview", btnPreview_Click);

            res = "Designer,Menu,Data,";
            CreateItem(btnDataChoose, "Ribbon.ChooseData.png", res + "Choose", Designer.cmdChooseData.Invoke);
            CreateItem(btnDataAdd, "Ribbon.AddDataSource.png", res + "Add", Designer.cmdAddData.Invoke);

            res = "Designer,Toolbar,Standard,";
            CreateItem(btnAddPage, 10, res + "NewPage", Designer.cmdNewPage.Invoke);
            CreateItem(btnCopyPage, 6, res + "CopyPage", Designer.cmdCopyPage.Invoke);
            CreateItem(btnAddDialog, 11, res + "NewDialog", Designer.cmdNewDialog.Invoke);
            CreateItem(btnDeletePage, 12, res + "DeletePage", Designer.cmdDeletePage.Invoke);
            CreateItem(btnPageSetup, "Ribbon.PageSetup.png", res + "PageSetup", Designer.cmdPageSetup.Invoke);

            res = "Designer,Menu,Report,";
            CreateItem(btnConfigureBands, "Ribbon.Bands.png", res + "Bands", miInsertBands_Click);
            CreateItem(btnGroupExpert, "Ribbon.Grouping.png", res + "GroupExpert", miReportGroupExpert_Click);

            res = "Objects,Bands,";
            CreateItem(btnReportTitle, res + "ReportTitle", miReportTitle_Click);
            CreateItem(btnReportSummary, res + "ReportSummary", miReportSummary_Click);
            CreateItem(btnPageHeader, res + "PageHeader", miPageHeader_Click);
            CreateItem(btnPageFooter, res + "PageFooter", miPageFooter_Click);
            CreateItem(btnColumnHeader, res + "ColumnHeader", miColumnHeader_Click);
            CreateItem(btnColumnFooter, res + "ColumnFooter", miColumnFooter_Click);
            CreateItem(btnOverlay, res + "Overlay", miOverlay_Click);

            previewTimer = new Timer();
            previewTimer.Interval = 20;
            previewTimer.Tick += previewTimer_Tick;
        }

        private void SetupLayoutControls()
        {
            string res = "Designer,Toolbar,Layout,";

            CreateItem(btnAlignToGrid, "Ribbon.AlignToGrid.png", res + "AlignToGrid", btnAlignToGrid_Click);
            CreateItem(btnFitToGrid, "Ribbon.FitToGrid.png", res + "SizeToGrid", btnSizeToGrid_Click);
            CreateItem(btnAlignLefts, 41, res + "Left", btnAlignLefts_Click);
            CreateItem(btnAlignCenters, 42, res + "Center", btnAlignCenters_Click);
            CreateItem(btnAlignRights, 45, res + "Right", btnAlignRights_Click);
            CreateItem(btnAlignTops, 46, res + "Top", btnAlignTops_Click);
            CreateItem(btnAlignMiddles, 47, res + "Middle", btnAlignMiddles_Click);
            CreateItem(btnAlignBottoms, 50, res + "Bottom", btnAlignBottoms_Click);
            CreateItem(btnSameWidth, 83, res + "SameWidth", btnSameWidth_Click);
            CreateItem(btnSameHeight, 84, res + "SameHeight", btnSameHeight_Click);
            CreateItem(btnSameSize, 91, res + "SameSize", btnSameSize_Click);
            CreateItem(btnSpaceHorizontally, 44, res + "SpaceHorizontally", btnSpaceHorizontally_Click);
            CreateItem(btnIncreaseHorizontalSpacing, 92, res + "IncreaseHorizontalSpacing", btnIncreaseHorizontalSpacing_Click);
            CreateItem(btnDecreaseHorizontalSpacing, 93, res + "DecreaseHorizontalSpacing", btnDecreaseHorizontalSpacing_Click);
            CreateItem(btnRemoveHorizontalSpacing, 94, res + "RemoveHorizontalSpacing", btnRemoveHorizontalSpacing_Click);
            CreateItem(btnSpaceVertically, 49, res + "SpaceVertically", btnSpaceVertically_Click);
            CreateItem(btnIncreaseVerticalSpacing, 95, res + "IncreaseVerticalSpacing", btnIncreaseVerticalSpacing_Click);
            CreateItem(btnDecreaseVerticalSpacing, 96, res + "DecreaseVerticalSpacing", btnDecreaseVerticalSpacing_Click);
            CreateItem(btnRemoveVerticalSpacing, 97, res + "RemoveVerticalSpacing", btnRemoveVerticalSpacing_Click);
            CreateItem(btnCenterHorizontally, 43, res + "CenterHorizontally", btnCenterHorizontally_Click);
            CreateItem(btnCenterVertically, 48, res + "CenterVertically", btnCenterVertically_Click);
            CreateItem(btnBringToFront, "Ribbon.BringToFront.png", res + "BringToFront", Designer.cmdBringToFront.Invoke);
            CreateItem(btnSendToBack, "Ribbon.SendToBack.png", res + "SendToBack", Designer.cmdSendToBack.Invoke);

            CreateItem(btnAlignment, "Ribbon.AlignMenu.png", "", null);
            CreateItem(btnSize, "Ribbon.SizeMenu.png", "", null);
            CreateItem(btnSpacing, "Ribbon.SpacingMenu.png", "", null);

            res = "Designer,Toolbar,Standard,";
            CreateItem(btnGroup, "Ribbon.Group.png", res + "Group", Designer.cmdGroup.Invoke);
            CreateItem(btnUngroup, "Ribbon.Ungroup.png", res + "Ungroup", Designer.cmdUngroup.Invoke);
        }

        private void SetupViewControls()
        {
            string res = "Designer,Menu,View,";
            CreateItem(btnViewGrid, "Ribbon.ViewGridlines.png", res + "Grid", MenuViewGrid_Click);
            CreateItem(btnViewGuides, "Ribbon.ViewGuides.png", res + "Guides", MenuViewGuides_Click);
            CreateItem(btnAutoGuides, res + "AutoGuides", MenuViewAutoGuides_Click);
            CreateItem(btnDeleteHGuides, res + "DeleteHGuides", MenuViewDeleteHGuides_Click);
            CreateItem(btnDeleteVGuides, res + "DeleteVGuides", MenuViewDeleteVGuides_Click);

            res = "Designer,ToolWindow,";
            CreateItem(btnPanels, "Ribbon.Panels.png", "", null);
            CreateItem(btnProperties, 68, res + "Properties", BtnProperties_Click);
            CreateItem(btnData, 72, res + "Dictionary", BtnData_Click);
            CreateItem(btnReportTree, 189, res + "ReportTree", BtnReportTree_Click);
            CreateItem(btnMessages, 70, res + "Messages", BtnMessages_Click);
            CreateItem(btnValidate, 70, res + "Validator", BtnValidate_Click);

            designer.PropertiesWindow.VisibleChanged += (object s, EventArgs e) =>
            {
                btnProperties.Checked = designer.PropertiesWindow.Visible;
            };
            designer.DataWindow.VisibleChanged += (object s, EventArgs e) =>
            {
                btnData.Checked = designer.DataWindow.Visible;
            };
            designer.ReportTreeWindow.VisibleChanged += (object s, EventArgs e) =>
            {
                btnReportTree.Checked = designer.ReportTreeWindow.Visible;
            };
            designer.MessagesWindow.VisibleChanged += (object s, EventArgs e) =>
            {
                btnMessages.Checked = designer.MessagesWindow.Visible;
            };

            designer.ValidatorWindow.VisibleChanged += (object s, EventArgs e) =>
            {
                btnValidate.Checked = designer.ValidatorWindow.Visible;
            };


            res = "Forms,ReportPageOptions,";
            CreateItem(btnUnits, "Ribbon.Page.png", "Designer,Menu,View,Units", null);
            CreateItem(btnUnitsMillimeters, res + "Millimeters", miViewUnits_Click);
            CreateItem(btnUnitsCentimeters, res + "Centimeters", miViewUnits_Click);
            CreateItem(btnUnitsInches, res + "Inches", miViewUnits_Click);
            CreateItem(btnUnitsHundrethsOfInch, res + "HundrethsOfInch", miViewUnits_Click);
        }

        #endregion

        #region Update Controls

        private void UpdateControls()
        {
            UpdateFileControls();
            UpdateHomeControls();
            UpdateReportControls();
            UpdateLayoutControls();
            UpdateViewControls();
        }

        private void UpdateFileControls()
        {
            btnFileNew.Enabled = Designer.cmdNew.Enabled;
            btnFileOpen.Enabled = Designer.cmdOpen.Enabled;
            btnFileClose.Enabled = Designer.cmdClose.Enabled;
            btnFileClose.Visible = Designer.MdiMode;
            btnFileSave.Enabled = Designer.cmdSave.Enabled;
            btnFileSaveAs.Enabled = Designer.cmdSaveAs.Enabled;
            btnFileSaveWithRandomData.Enabled = Designer.cmdSaveWithRandomData.Enabled;
            btnFileSaveAll.Visible = Designer.MdiMode;
            btnFileSaveAll.Enabled = Designer.cmdSaveAll.Enabled;
            //btnFilePageSetup.Enabled = Designer.cmdPageSetup.Enabled;
            btnFilePrinterSetup.Enabled = Designer.cmdPrinterSetup.Enabled;
            btnFilePreview.Enabled = Designer.cmdPreview.Enabled;
            btnWelcome.Enabled = Designer.cmdWelcome.Enabled;
            btnHelp.Enabled = Designer.cmdHelpContents.Enabled;
        }

        private void UpdateHomeControls()
        {
            //-------------------------------------------------------------------
            // Undo
            //-------------------------------------------------------------------

            btnUndo.Enabled = Designer.cmdUndo.Enabled;
            btnRedo.Enabled = Designer.cmdRedo.Enabled;

            //-------------------------------------------------------------------
            // Clipboard
            //-------------------------------------------------------------------

            btnCut.Enabled = Designer.cmdCut.Enabled;
            btnCopy.Enabled = Designer.cmdCopy.Enabled;
            btnPaste.Enabled = Designer.cmdPaste.Enabled;
            btnFormatPainter.Enabled = Designer.cmdFormatPainter.Enabled;
            btnFormatPainter.Checked = Designer.FormatPainter;

            //-------------------------------------------------------------------
            // Text
            //-------------------------------------------------------------------

            bool enabled = Designer.SelectedTextObjects.Enabled;

            cbxFontName.Enabled = enabled;
            cbxFontSize.Enabled = enabled;
            btnBold.Enabled = enabled;
            btnItalic.Enabled = enabled;
            btnUnderline.Enabled = enabled;
            btnAlignLeft.Enabled = enabled;
            btnAlignCenter.Enabled = enabled;
            btnAlignRight.Enabled = enabled;
            btnJustify.Enabled = enabled;
            btnAlignTop.Enabled = enabled;
            btnAlignMiddle.Enabled = enabled;
            btnAlignBottom.Enabled = enabled;
            btnTextColor.Enabled = enabled;
            btnTextRotation.Enabled = enabled;

            if (enabled)
            {
                TextObject text = Designer.SelectedTextObjects.First;

                cbxFontName.FontName = text.Font.Name;
                cbxFontSize.FontSize = text.Font.Size;
                btnBold.Checked = text.Font.Bold;
                btnItalic.Checked = text.Font.Italic;
                btnUnderline.Checked = text.Font.Underline;
                btnAlignLeft.Checked = text.HorzAlign == HorzAlign.Left;
                btnAlignCenter.Checked = text.HorzAlign == HorzAlign.Center;
                btnAlignRight.Checked = text.HorzAlign == HorzAlign.Right;
                btnJustify.Checked = text.HorzAlign == HorzAlign.Justify;
                btnAlignTop.Checked = text.VertAlign == VertAlign.Top;
                btnAlignMiddle.Checked = text.VertAlign == VertAlign.Center;
                btnAlignBottom.Checked = text.VertAlign == VertAlign.Bottom;
                if (text.TextFill is SolidFill)
                    btnTextColor.Color = (text.TextFill as SolidFill).Color;
            }
            else
            {
                btnBold.Checked = false;
                btnItalic.Checked = false;
                btnUnderline.Checked = false;
                btnAlignLeft.Checked = false;
                btnAlignCenter.Checked = false;
                btnAlignRight.Checked = false;
                btnJustify.Checked = false;
                btnAlignTop.Checked = false;
                btnAlignMiddle.Checked = false;
                btnAlignBottom.Checked = false;
            }

            //-------------------------------------------------------------------
            // Border and Fill
            //-------------------------------------------------------------------

            enabled = Designer.SelectedReportComponents.Enabled;
            bool simple = Designer.SelectedReportComponents.SimpleBorder;
            bool useBorder = Designer.SelectedReportComponents.BorderEnabled;

            bool borderEnabled = enabled && !simple && useBorder;
            btnTopLine.Enabled = borderEnabled;
            btnBottomLine.Enabled = borderEnabled;
            btnLeftLine.Enabled = borderEnabled;
            btnRightLine.Enabled = borderEnabled;
            btnAllLines.Enabled = borderEnabled;
            btnNoLines.Enabled = borderEnabled;
            btnFillColor.Enabled = enabled && Designer.SelectedReportComponents.FillEnabled;
            btnFillProps.Enabled = enabled && Designer.SelectedReportComponents.FillEnabled;
            btnLineColor.Enabled = enabled && useBorder;
            btnLineWidth.Enabled = enabled && useBorder;
            btnLineStyle.Enabled = enabled && useBorder;
            btnBorderProps.Enabled = borderEnabled;

            if (enabled)
            {
                Border border = Designer.SelectedReportComponents.First.Border;
                btnTopLine.Checked = (border.Lines & BorderLines.Top) != 0;
                btnBottomLine.Checked = (border.Lines & BorderLines.Bottom) != 0;
                btnLeftLine.Checked = (border.Lines & BorderLines.Left) != 0;
                btnRightLine.Checked = (border.Lines & BorderLines.Right) != 0;
                btnLineColor.Color = border.Color;
                if (Designer.SelectedReportComponents.First.Fill is SolidFill)
                    btnFillColor.Color = (Designer.SelectedReportComponents.First.Fill as SolidFill).Color;
                btnLineWidth.LineWidth = border.Width;
                btnLineStyle.LineStyle = border.Style;
            }

            //-------------------------------------------------------------------
            // Format
            //-------------------------------------------------------------------

            btnHighlight.Enabled = Designer.SelectedTextObjects.Enabled;
            btnFormat.Enabled = Designer.SelectedTextObjects.Enabled;

            //-------------------------------------------------------------------
            // Editing
            //-------------------------------------------------------------------

            btnFind.Enabled = Designer.cmdFind.Enabled;
            btnReplace.Enabled = Designer.cmdReplace.Enabled;
            btnSelectAll.Enabled = Designer.cmdSelectAll.Enabled;

            //-------------------------------------------------------------------
            // Styles
            //-------------------------------------------------------------------

            enabled = Designer.SelectedReportComponents.Enabled;

            cbxStyles.Enabled = enabled;
            cbxStyles.Report = Designer.ActiveReport;
            if (enabled)
                cbxStyles.Style = Designer.SelectedReportComponents.First.Style;


            //-------------------------------------------------------------------
            // Polygon
            //-------------------------------------------------------------------

            enabled = (Designer.SelectedObjects.Count == 1) && (Designer.SelectedObjects[0] is PolyLineObject);

            btnPolyMove.Enabled = enabled;
            btnPolyPointer.Enabled = enabled;
            btnPolyAddBezier.Enabled = enabled;
            btnPolyAddPoint.Enabled = enabled;
            btnPolyRemovePoint.Enabled = enabled;
            if (!enabled)
                selectBtn(PolyLineObject.PolygonSelectionMode.MoveAndScale);
            else
            {
                PolyLineObject plobj = (Designer.SelectedObjects[0] as PolyLineObject);
                selectBtn(plobj.SelectionMode);
            }


            //-------------------------------------------------------------------
        }

        private void selectBtn(PolyLineObject.PolygonSelectionMode index)
        {
            PolyLineObject plobj = null;
            if ((Designer.SelectedObjects.Count == 1) && (Designer.SelectedObjects[0] is PolyLineObject))
                plobj = (Designer.SelectedObjects[0] as PolyLineObject);
            btnPolyMove.Checked = false;
            btnPolyPointer.Checked = false;
            btnPolyAddBezier.Checked = false;
            btnPolyAddPoint.Checked = false;
            btnPolyRemovePoint.Checked = false;
            switch (index)
            {
                case PolyLineObject.PolygonSelectionMode.Normal:
                    btnPolyPointer.Checked = true;
                    break;
                case PolyLineObject.PolygonSelectionMode.AddBezier:
                    btnPolyAddBezier.Checked = true;
                    break;
                case PolyLineObject.PolygonSelectionMode.AddToLine:
                    btnPolyAddPoint.Checked = true;
                    break;
                case PolyLineObject.PolygonSelectionMode.Delete:
                    btnPolyRemovePoint.Checked = true;
                    break;
                case PolyLineObject.PolygonSelectionMode.MoveAndScale:
                    btnPolyMove.Checked = true;
                    break;
            }
        }

        private void UpdateReportControls()
        {
            btnPreview.Enabled = Designer.cmdPreview.Enabled;
            btnReportOptions.Enabled = Designer.cmdReportSettings.Enabled;
            btnDataChoose.Enabled = Designer.cmdChooseData.Enabled;
            btnDataAdd.Enabled = Designer.cmdAddData.Enabled;

            btnAddPage.Enabled = Designer.cmdNewPage.Enabled;
            btnCopyPage.Enabled = Designer.cmdCopyPage.Enabled;
            btnAddDialog.Enabled = Designer.cmdNewDialog.Enabled;
            btnDeletePage.Enabled = Designer.cmdDeletePage.Enabled;
            btnPageSetup.Enabled = Designer.cmdPageSetup.Enabled;

            bool bandsEnabled = Designer.cmdInsertBand.Enabled;
            btnConfigureBands.Enabled = bandsEnabled;
            btnGroupExpert.Enabled = bandsEnabled;

            ReportPage page = null;

            try
            {
                //see fix # 66fcd219-30f1-45e6-8ee5-ce65cfb9d35d
                //rly annoying freezes on designer start
                page = Page as ReportPage;
            }
            catch
            {

            }

            if (page != null)
            {
                bool isSubreport = page.Subreport != null;

                btnReportTitle.Enabled = bandsEnabled && !isSubreport;
                btnReportSummary.Enabled = bandsEnabled && !isSubreport;
                btnPageHeader.Enabled = bandsEnabled && !isSubreport;
                btnPageFooter.Enabled = bandsEnabled && !isSubreport;
                btnColumnHeader.Enabled = bandsEnabled && !isSubreport;
                btnColumnFooter.Enabled = bandsEnabled && !isSubreport;
                btnOverlay.Enabled = bandsEnabled && !isSubreport;

                btnReportTitle.Checked = page.ReportTitle != null;
                btnReportSummary.Checked = page.ReportSummary != null;
                btnPageHeader.Checked = page.PageHeader != null;
                btnPageFooter.Checked = page.PageFooter != null;
                btnColumnHeader.Checked = page.ColumnHeader != null;
                btnColumnFooter.Checked = page.ColumnFooter != null;
                btnOverlay.Checked = page.Overlay != null;
            }
            else
            {
                btnReportTitle.Enabled = false;
                btnReportSummary.Enabled = false;
                btnPageHeader.Enabled = false;
                btnPageFooter.Enabled = false;
                btnColumnHeader.Enabled = false;
                btnColumnFooter.Enabled = false;
                btnOverlay.Enabled = false;
            }
        }

        private void UpdateLayoutControls()
        {
            bool oneObjSelected = Designer.SelectedComponents.Count > 0;
            bool threeObjSelected = Designer.SelectedComponents.Count >= 3;
            bool severalObjSelected = Designer.SelectedComponents.Count > 1;
            bool canChangeOrder = Designer.SelectedComponents.Count > 0 &&
                Designer.SelectedComponents.First.HasFlag(Flags.CanChangeOrder);
            bool canMove = Designer.SelectedComponents.Count > 0 && Designer.SelectedComponents.First.HasFlag(Flags.CanMove);
            bool canResize = Designer.SelectedComponents.Count > 0 &&
                Designer.SelectedComponents.First.HasFlag(Flags.CanResize);

            btnAlignToGrid.Enabled = oneObjSelected && canMove;
            btnAlignLefts.Enabled = severalObjSelected && canMove;
            btnAlignCenters.Enabled = severalObjSelected && canMove;
            btnAlignRights.Enabled = severalObjSelected && canMove;
            btnAlignTops.Enabled = severalObjSelected && canMove;
            btnAlignMiddles.Enabled = severalObjSelected && canMove;
            btnAlignBottoms.Enabled = severalObjSelected && canMove;
            btnSameWidth.Enabled = severalObjSelected && canResize;
            btnSameHeight.Enabled = severalObjSelected && canResize;
            btnSameSize.Enabled = severalObjSelected && canResize;
            btnFitToGrid.Enabled = oneObjSelected && canResize;
            btnSpaceHorizontally.Enabled = threeObjSelected && canMove;
            btnIncreaseHorizontalSpacing.Enabled = severalObjSelected && canMove;
            btnDecreaseHorizontalSpacing.Enabled = severalObjSelected && canMove;
            btnRemoveHorizontalSpacing.Enabled = severalObjSelected && canMove;
            btnSpaceVertically.Enabled = threeObjSelected && canMove;
            btnIncreaseVerticalSpacing.Enabled = severalObjSelected && canMove;
            btnDecreaseVerticalSpacing.Enabled = severalObjSelected && canMove;
            btnRemoveVerticalSpacing.Enabled = severalObjSelected && canMove;
            btnCenterHorizontally.Enabled = oneObjSelected && canMove;
            btnCenterVertically.Enabled = oneObjSelected && canMove;
            btnBringToFront.Enabled = canChangeOrder;
            btnSendToBack.Enabled = canChangeOrder;

            btnGroup.Enabled = Designer.cmdGroup.Enabled;
            btnUngroup.Enabled = Designer.cmdUngroup.Enabled;
        }

        private void UpdateViewControls()
        {
            if (Workspace != null)
            {
                btnViewGrid.Enabled = true;
                btnViewGuides.Enabled = true;
                btnViewGrid.Checked = ReportWorkspace.ShowGrid;
                btnViewGuides.Checked = ReportWorkspace.ShowGuides;

                btnAutoGuides.Enabled = true;
                bool autoGuides = ReportWorkspace.AutoGuides;
                btnAutoGuides.Checked = autoGuides;
                btnDeleteHGuides.Enabled = !autoGuides;
                btnDeleteVGuides.Enabled = !autoGuides;
            }
            else
            {
                btnViewGrid.Enabled = false;
                btnViewGuides.Enabled = false;
                btnAutoGuides.Enabled = false;
                btnDeleteHGuides.Enabled = false;
                btnDeleteVGuides.Enabled = false;
            }

            btnProperties.Checked = designer.PropertiesWindow.Visible;
            btnData.Checked = designer.DataWindow.Visible;
            btnReportTree.Checked = designer.ReportTreeWindow.Visible;
            btnMessages.Checked = designer.MessagesWindow.Visible;
            btnValidate.Checked = designer.ValidatorWindow.Visible;

            btnUnitsMillimeters.Checked = ReportWorkspace.Grid.GridUnits == PageUnits.Millimeters;
            btnUnitsCentimeters.Checked = ReportWorkspace.Grid.GridUnits == PageUnits.Centimeters;
            btnUnitsInches.Checked = ReportWorkspace.Grid.GridUnits == PageUnits.Inches;
            btnUnitsHundrethsOfInch.Checked = ReportWorkspace.Grid.GridUnits == PageUnits.HundrethsOfInch;
        }

        #endregion Update Controls

        #region Images
        /// <inheritdoc/>
        public override void UpdateDpiDependencies()
        {
            base.UpdateDpiDependencies();
            Designer.UpdateDpiDependencies(this);

            ribbonControl.SuspendLayout();
            foreach (KeyValuePair<BaseItem, ItemInfo> kv in ribbonItems)
            {
                if (kv.Key is ButtonItem)
                {
                    if (kv.Value.ImageIndex != -1)
                        (kv.Key as ButtonItem).Image = GetImage(kv.Value.ImageIndex);
                    if (!String.IsNullOrEmpty(kv.Value.ImageResource))
                        (kv.Key as ButtonItem).Image = GetImage(kv.Value.ImageResource);
                }
            }

            cbxFontName.Owner = this;
            cbxFontName.UpdateDpiDependencies();
            cbxFontName.ComboWidth = this.LogicalToDevice(110);

            cbxFontSize.ComboWidth = this.LogicalToDevice(45);
            cbxFontSize.DropDownHeight = this.LogicalToDevice(300);
            cbxFontSize.ItemHeight = this.LogicalToDevice(14);

            cbxStyles.ComboWidth = this.LogicalToDevice(120);
            cbxStyles.DropDownHeight = this.LogicalToDevice(300);
            cbxStyles.DropDownWidth = this.LogicalToDevice(150);
            cbxStyles.ItemHeight = this.LogicalToDevice(14);

            // this will recalc layout
            barText.Width++;
            barStyles.Width++;
            ribbonControl.ResumeLayout();
        }

        #endregion

        #region Methods
        #region Form Methods
        private void DesignerForm_Load(object sender, EventArgs e)
        {
            // bug/inconsistent behavior in .Net: if we set WindowState to Maximized, the
            // Load event will be fired *after* the form is shown.
            bool maximized = Config.RestoreFormState(this, true);
            // under some circumstances, the config file may contain wrong winodw position (-32000)
            if (!maximized && (Left < -10 || Top < -10))
                maximized = true;
            Designer.RestoreConfig();
            if (maximized)
                WindowState = FormWindowState.Maximized;

            Config.DesignerSettings.OnDesignerLoaded(Designer, EventArgs.Empty);
            Designer.StartAutoSave();
        }

        private void DesignerForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!Designer.CloseAll())
            {
                e.Cancel = true;
            }
            else
            {
                Config.SaveFormState(this);
                Designer.SaveConfig();
            }
            designer.ValidatorWindow.CancelUpdateErrors();
        }

        private void DesignerForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Config.DesignerSettings.OnDesignerClosed(Designer, EventArgs.Empty);
            Designer.StopAutoSave();
        }

        #endregion
        #region File Methods
        private void miFile_PopupOpen(object sender, PopupOpenEventArgs e)
        {
            // clear existing recent items
            for (int i = 0; i < itemContainer23.SubItems.Count; i++)
            {
                BaseItem item = itemContainer23.SubItems[i];

                if (item is ButtonItem)
                {
                    item.Dispose();
                    itemContainer23.SubItems.Remove(item);
                    i--;
                }
            }

            // add new items
            if (Designer.cmdRecentFiles.Enabled && Designer.RecentFiles.Count > 0)
            {
                foreach (string file in Designer.RecentFiles)
                {
                    ButtonItem menuItem = new ButtonItem();
                    menuItem.Text = Path.GetFileName(file);
                    menuItem.Tag = file;
                    menuItem.Tooltip = file;
                    menuItem.Click += recentFile_Click;
                    itemContainer23.SubItems.Insert(1, menuItem);
                }
            }
        }

        private void recentFile_Click(object sender, EventArgs e)
        {
            Designer.UpdatePlugins(null);
            Designer.cmdOpen.LoadFile((sender as ButtonItem).Tag as string);
        }
        #endregion
        #region Home Methods
        //-------------------------------------------------------------------
        // Clipboard
        //-------------------------------------------------------------------

        private void clipboardTimer_Tick(object sender, EventArgs e)
        {
            btnPaste.Enabled = Designer.cmdPaste.Enabled;
        }

        //-------------------------------------------------------------------
        // Text
        //-------------------------------------------------------------------

        private void cbxName_FontSelected(object sender, EventArgs e)
        {
            (Designer.ActiveReportTab.ActivePageDesigner as ReportPageDesigner).Workspace.Focus();
            Designer.SelectedTextObjects.SetFontName(cbxFontName.FontName);
        }

        private void cbxSize_SizeSelected(object sender, EventArgs e)
        {
            (Designer.ActiveReportTab.ActivePageDesigner as ReportPageDesigner).Workspace.Focus();
            Designer.SelectedTextObjects.SetFontSize(cbxFontSize.FontSize);
        }

        private void btnBold_Click(object sender, EventArgs e)
        {
            btnBold.Checked = !btnBold.Checked;
            Designer.SelectedTextObjects.ToggleFontStyle(FontStyle.Bold, btnBold.Checked);
        }

        private void btnItalic_Click(object sender, EventArgs e)
        {
            btnItalic.Checked = !btnItalic.Checked;
            Designer.SelectedTextObjects.ToggleFontStyle(FontStyle.Italic, btnItalic.Checked);
        }

        private void btnUnderline_Click(object sender, EventArgs e)
        {
            btnUnderline.Checked = !btnUnderline.Checked;
            Designer.SelectedTextObjects.ToggleFontStyle(FontStyle.Underline, btnUnderline.Checked);
        }

        private void btnLeft_Click(object sender, EventArgs e)
        {
            Designer.SelectedTextObjects.SetHAlign(HorzAlign.Left);
        }

        private void btnCenter_Click(object sender, EventArgs e)
        {
            Designer.SelectedTextObjects.SetHAlign(HorzAlign.Center);
        }

        private void btnRight_Click(object sender, EventArgs e)
        {
            Designer.SelectedTextObjects.SetHAlign(HorzAlign.Right);
        }

        private void btnJustify_Click(object sender, EventArgs e)
        {
            Designer.SelectedTextObjects.SetHAlign(HorzAlign.Justify);
        }

        private void btnTop_Click(object sender, EventArgs e)
        {
            Designer.SelectedTextObjects.SetVAlign(VertAlign.Top);
        }

        private void btnMiddle_Click(object sender, EventArgs e)
        {
            Designer.SelectedTextObjects.SetVAlign(VertAlign.Center);
        }

        private void btnBottom_Click(object sender, EventArgs e)
        {
            Designer.SelectedTextObjects.SetVAlign(VertAlign.Bottom);
        }

        private void btnColor_Click(object sender, EventArgs e)
        {
            Designer.SelectedTextObjects.SetTextColor(btnTextColor.DefaultColor);
        }

        private void btnRotation_Click(object sender, EventArgs e)
        {
            AnglePopup popup = new AnglePopup(Designer.FindForm());
            popup.Angle = Designer.SelectedTextObjects.First.Angle;
            popup.AngleChanged += popup_RotationChanged;
            popup.Show(this, barText.Right, barText.Bottom);
        }

        private void popup_RotationChanged(object sender, EventArgs e)
        {
            Designer.SelectedTextObjects.SetAngle((sender as AnglePopup).Angle);
        }

        //-------------------------------------------------------------------
        // Border and Fill
        //-------------------------------------------------------------------

        private void btnTopLine_Click(object sender, EventArgs e)
        {
            btnTopLine.Checked = !btnTopLine.Checked;
            Designer.SelectedReportComponents.ToggleLine(BorderLines.Top, btnTopLine.Checked);
        }

        private void btnBottomLine_Click(object sender, EventArgs e)
        {
            btnBottomLine.Checked = !btnBottomLine.Checked;
            Designer.SelectedReportComponents.ToggleLine(BorderLines.Bottom, btnBottomLine.Checked);
        }

        private void btnLeftLine_Click(object sender, EventArgs e)
        {
            btnLeftLine.Checked = !btnLeftLine.Checked;
            Designer.SelectedReportComponents.ToggleLine(BorderLines.Left, btnLeftLine.Checked);
        }

        private void btnRightLine_Click(object sender, EventArgs e)
        {
            btnRightLine.Checked = !btnRightLine.Checked;
            Designer.SelectedReportComponents.ToggleLine(BorderLines.Right, btnRightLine.Checked);
        }

        private void btnAll_Click(object sender, EventArgs e)
        {
            Designer.SelectedReportComponents.ToggleLine(BorderLines.All, true);
        }

        private void btnNone_Click(object sender, EventArgs e)
        {
            Designer.SelectedReportComponents.ToggleLine(BorderLines.All, false);
        }

        private void btnLineColor_Click(object sender, EventArgs e)
        {
            Designer.SelectedReportComponents.SetLineColor(btnLineColor.DefaultColor);
        }

        private void btnFillColor_Click(object sender, EventArgs e)
        {
            Designer.SelectedReportComponents.SetColor(btnFillColor.DefaultColor);
        }

        private void btnFillProps_Click(object sender, EventArgs e)
        {
            Designer.SelectedReportComponents.InvokeFillEditor();
        }

        private void cbxWidth_WidthSelected(object sender, EventArgs e)
        {
            Designer.SelectedReportComponents.SetWidth(btnLineWidth.LineWidth);
        }

        private void cbxLineStyle_StyleSelected(object sender, EventArgs e)
        {
            Designer.SelectedReportComponents.SetLineStyle(btnLineStyle.LineStyle);
        }

        private void btnBorderProps_Click(object sender, EventArgs e)
        {
            Designer.SelectedReportComponents.InvokeBorderEditor();
        }

        //-------------------------------------------------------------------
        // Format
        //-------------------------------------------------------------------

        private void btnHighlight_Click(object sender, EventArgs e)
        {
            Designer.SelectedTextObjects.InvokeHighlightEditor();
        }

        private void btnFormat_Click(object sender, EventArgs e)
        {
            using (FormatEditorForm form = new FormatEditorForm())
            {
                SelectedTextBaseObjects FTextObjects = new SelectedTextBaseObjects(designer);
                FTextObjects.Update();

                form.TextObject = FTextObjects.First;
                if (form.ShowDialog() == DialogResult.OK)
                {
                    FTextObjects.SetFormat(form.Formats);
                    Designer.SetModified(null, "Change");
                    //Change();
                }
            }
        }

        //-------------------------------------------------------------------
        // Styles
        //-------------------------------------------------------------------

        private void cbxStyle_StyleSelected(object sender, EventArgs e)
        {
            (Designer.ActiveReportTab.ActivePageDesigner as ReportPageDesigner).Workspace.Focus();
            Designer.SelectedReportComponents.SetStyle(cbxStyles.Style);
        }

        //-------------------------------------------------------------------
        #endregion
        #region Report Methods

        private void btnPreview_Click(object sender, EventArgs e)
        {
            previewTimer.Start();
        }

        private void previewTimer_Tick(object sender, EventArgs e)
        {
            previewTimer.Stop();
            Designer.cmdPreview.Invoke(sender, e);
        }

        private void miInsertBands_Click(object sender, EventArgs e)
        {
            using (ConfigureBandsForm form = new ConfigureBandsForm(Designer))
            {
                form.Page = Page as ReportPage;
                form.ShowDialog();
            }
        }

        private void miReportGroupExpert_Click(object sender, EventArgs e)
        {
            using (GroupExpertForm form = new GroupExpertForm(Designer))
            {
                if (form.ShowDialog() == DialogResult.OK)
                    Designer.SetModified(null, "ChangeReport");
            }
        }

        private void miReportTitle_Click(object sender, EventArgs e)
        {
            ReportPage page = Page as ReportPage;
            if ((sender as CheckBoxItem).Checked)
            {
                page.ReportTitle = new ReportTitleBand();
                ReportPageDesigner.SetDefaults(page.ReportTitle);
            }
            else
            {
                page.ReportTitle = null;
            }
            ReportPageDesigner.Change();
        }

        private void miReportSummary_Click(object sender, EventArgs e)
        {
            ReportPage page = Page as ReportPage;
            if ((sender as CheckBoxItem).Checked)
            {
                page.ReportSummary = new ReportSummaryBand();
                ReportPageDesigner.SetDefaults(page.ReportSummary);
            }
            else
            {
                page.ReportSummary = null;
            }
            ReportPageDesigner.Change();
        }

        private void miPageHeader_Click(object sender, EventArgs e)
        {
            ReportPage page = Page as ReportPage;
            if ((sender as CheckBoxItem).Checked)
            {
                page.PageHeader = new PageHeaderBand();
                ReportPageDesigner.SetDefaults(page.PageHeader);
            }
            else
            {
                page.PageHeader = null;
            }
            ReportPageDesigner.Change();
        }

        private void miPageFooter_Click(object sender, EventArgs e)
        {
            ReportPage page = Page as ReportPage;
            if ((sender as CheckBoxItem).Checked)
            {
                page.PageFooter = new PageFooterBand();
                ReportPageDesigner.SetDefaults(page.PageFooter);
            }
            else
            {
                page.PageFooter = null;
            }
            ReportPageDesigner.Change();
        }

        private void miColumnHeader_Click(object sender, EventArgs e)
        {
            ReportPage page = Page as ReportPage;
            if ((sender as CheckBoxItem).Checked)
            {
                page.ColumnHeader = new ColumnHeaderBand();
                ReportPageDesigner.SetDefaults(page.ColumnHeader);
            }
            else
            {
                page.ColumnHeader = null;
            }
            ReportPageDesigner.Change();
        }

        private void miColumnFooter_Click(object sender, EventArgs e)
        {
            ReportPage page = Page as ReportPage;
            if ((sender as CheckBoxItem).Checked)
            {
                page.ColumnFooter = new ColumnFooterBand();
                ReportPageDesigner.SetDefaults(page.ColumnFooter);
            }
            else
            {
                page.ColumnFooter = null;
            }
            ReportPageDesigner.Change();
        }

        private void miOverlay_Click(object sender, EventArgs e)
        {
            ReportPage page = Page as ReportPage;
            if ((sender as CheckBoxItem).Checked)
            {
                page.Overlay = new OverlayBand();
                ReportPageDesigner.SetDefaults(page.Overlay);
            }
            else
            {
                page.Overlay = null;
            }
            ReportPageDesigner.Change();
        }

        #endregion
        #region Layout Methods
        private void btnAlignToGrid_Click(object sender, EventArgs e)
        {
            Designer.SelectedComponents.AlignToGrid();
        }

        private void btnAlignLefts_Click(object sender, EventArgs e)
        {
            Designer.SelectedComponents.AlignLeft();
        }

        private void btnAlignCenters_Click(object sender, EventArgs e)
        {
            Designer.SelectedComponents.AlignCenter();
        }

        private void btnAlignRights_Click(object sender, EventArgs e)
        {
            Designer.SelectedComponents.AlignRight();
        }

        private void btnAlignTops_Click(object sender, EventArgs e)
        {
            Designer.SelectedComponents.AlignTop();
        }

        private void btnAlignMiddles_Click(object sender, EventArgs e)
        {
            Designer.SelectedComponents.AlignMiddle();
        }

        private void btnAlignBottoms_Click(object sender, EventArgs e)
        {
            Designer.SelectedComponents.AlignBottom();
        }

        private void btnSameWidth_Click(object sender, EventArgs e)
        {
            Designer.SelectedComponents.SameWidth();
        }

        private void btnSameHeight_Click(object sender, EventArgs e)
        {
            Designer.SelectedComponents.SameHeight();
        }

        private void btnSameSize_Click(object sender, EventArgs e)
        {
            Designer.SelectedComponents.SameSize();
        }

        private void btnCenterHorizontally_Click(object sender, EventArgs e)
        {
            Designer.SelectedComponents.CenterHorizontally();
        }

        private void btnCenterVertically_Click(object sender, EventArgs e)
        {
            Designer.SelectedComponents.CenterVertically();
        }

        private void btnSizeToGrid_Click(object sender, EventArgs e)
        {
            Designer.SelectedComponents.SizeToGrid();
        }

        private void btnSpaceHorizontally_Click(object sender, EventArgs e)
        {
            Designer.SelectedComponents.SpaceHorizontally();
        }

        private void btnIncreaseHorizontalSpacing_Click(object sender, EventArgs e)
        {
            Designer.SelectedComponents.IncreaseHorizontalSpacing();
        }

        private void btnDecreaseHorizontalSpacing_Click(object sender, EventArgs e)
        {
            Designer.SelectedComponents.DecreaseHorizontalSpacing();
        }

        private void btnRemoveHorizontalSpacing_Click(object sender, EventArgs e)
        {
            Designer.SelectedComponents.RemoveHorizontalSpacing();
        }

        private void btnSpaceVertically_Click(object sender, EventArgs e)
        {
            Designer.SelectedComponents.SpaceVertically();
        }

        private void btnIncreaseVerticalSpacing_Click(object sender, EventArgs e)
        {
            Designer.SelectedComponents.IncreaseVerticalSpacing();
        }

        private void btnDecreaseVerticalSpacing_Click(object sender, EventArgs e)
        {
            Designer.SelectedComponents.DecreaseVerticalSpacing();
        }

        private void btnRemoveVerticalSpacing_Click(object sender, EventArgs e)
        {
            Designer.SelectedComponents.RemoveVerticalSpacing();
        }
        #endregion
        #region View Methods
        private void MenuViewGrid_Click(object sender, EventArgs e)
        {
            ReportWorkspace.ShowGrid = btnViewGrid.Checked;
            Workspace.Refresh();
        }

        private void MenuViewGuides_Click(object sender, EventArgs e)
        {
            ReportWorkspace.ShowGuides = btnViewGuides.Checked;
            Workspace.Refresh();
        }

        private void MenuViewAutoGuides_Click(object sender, EventArgs e)
        {
            ReportWorkspace.AutoGuides = btnAutoGuides.Checked;
            Workspace.Refresh();
            UpdateControls();
        }

        private void MenuViewDeleteHGuides_Click(object sender, EventArgs e)
        {
            Workspace.DeleteHGuides();
        }

        private void MenuViewDeleteVGuides_Click(object sender, EventArgs e)
        {
            Workspace.DeleteVGuides();
        }

        private void BtnMessages_Click(object sender, EventArgs e)
        {
            if (designer.MessagesWindow.Visible)
                designer.MessagesWindow.Hide();
            else
                designer.MessagesWindow.Show();
        }

        private void BtnValidate_Click(object sender, EventArgs e)
        {
            if (designer.ValidatorWindow.Visible)
            {
                designer.ValidatorWindow.Hide();
                designer.ValidatorWindow.CancelUpdateErrors();
            }
            else
            {
                designer.ValidatorWindow.Show();
                designer.ValidatorWindow.UpdateErrors(!ReportWorkspace.EnableBacklightIntersectingObjects);
            }
        }

        private void BtnReportTree_Click(object sender, EventArgs e)
        {
            if (designer.ReportTreeWindow.Visible)
                designer.ReportTreeWindow.Hide();
            else
                designer.ReportTreeWindow.Show();
        }

        private void BtnData_Click(object sender, EventArgs e)
        {
            if (designer.DataWindow.Visible)
                designer.DataWindow.Hide();
            else
                designer.DataWindow.Show();
        }

        private void BtnProperties_Click(object sender, EventArgs e)
        {
            if (designer.PropertiesWindow.Visible)
                designer.PropertiesWindow.Hide();
            else
                designer.PropertiesWindow.Show();
        }
        private void miViewUnits_Click(object sender, EventArgs e)
        {
            if (sender == btnUnitsMillimeters)
                ReportWorkspace.Grid.GridUnits = PageUnits.Millimeters;
            else if (sender == btnUnitsCentimeters)
                ReportWorkspace.Grid.GridUnits = PageUnits.Centimeters;
            else if (sender == btnUnitsInches)
                ReportWorkspace.Grid.GridUnits = PageUnits.Inches;
            else
                ReportWorkspace.Grid.GridUnits = PageUnits.HundrethsOfInch;

            UpdateContent();
        }

        private void openfrx_DragEnter(object sender, DragEventArgs e)
        {
            string[] objects = (string[])e.Data.GetData(DataFormats.FileDrop);
            if (objects != null) 
            if (objects.Length == 1)
            {
                if (Path.GetExtension(objects[0]).ToLower() == ".frx")
                {
                    e.Effect = DragDropEffects.Move;
                }
            }
        }

        private void openfrx_DragDrop(object sender, DragEventArgs e)
        {
            string[] objects = (string[])e.Data.GetData(DataFormats.FileDrop);
            if (objects.Length == 1)
            {
                if (Path.GetExtension(objects[0]).ToLower() == ".frx")
                {
                    Designer.cmdOpen.LoadFile(objects[0]);
                }
            }
        }
        #endregion
        #endregion

        #region IDesignerPlugin
        /// <inheritdoc/>
        public string PluginName
        {
            get { return Name; }
        }

        /// <inheritdoc/>
        public void SaveState()
        {
        }

        /// <inheritdoc/>
        public void RestoreState()
        {
        }

        /// <inheritdoc/>
        public void SelectionChanged()
        {
            UpdateContent();
        }

        /// <inheritdoc/>
        public void UpdateContent()
        {
            UpdateControls();
        }

        /// <inheritdoc/>
        public void Lock()
        {
        }

        /// <inheritdoc/>
        public void Unlock()
        {
            UpdateContent();
        }

        /// <inheritdoc/>
        public override void Localize()
        {
            foreach (KeyValuePair<BaseItem, ItemInfo> kv in ribbonItems)
            {
                kv.Key.Text = Res.Get(kv.Value.TextResource);
                kv.Key.Tooltip = Res.Get(kv.Value.TooltipResource);
            }

            MyRes res = new MyRes("Designer,Ribbon");

            btnFile.Text = res.Get("File");
            tabHome.Text = res.Get("Home");
            tabReport.Text = res.Get("Report");
            tabLayout.Text = res.Get("Layout");
            tabView.Text = res.Get("View");

            lblRecent.Text = res.Get("Recent");
            barReport.Text = res.Get("Report");
            barLayout.Text = res.Get("Layout");
            barView.Text = res.Get("View");
            barClipboard.Text = res.Get("Clipboard");
            barText.Text = res.Get("Text");
            barBorderAndFill.Text = res.Get("BorderAndFill");
            barFormat.Text = res.Get("Format");
            barStyles.Text = res.Get("Styles");
            barPolygon.Text = Res.Get("Designer,Toolbar,Polygon");
            barEditing.Text = res.Get("Editing");
            barData.Text = res.Get("Data");
            barPages.Text = res.Get("Pages");
            barBands.Text = res.Get("Bands");
            btnAlignment.Text = res.Get("Alignment");
            btnSize.Text = res.Get("Size");
            btnSpacing.Text = res.Get("Spacing");
            btnPanels.Text = res.Get("Panels");
            
            UpdateContent();
        }

        /// <inheritdoc/>
        public DesignerOptionsPage GetOptionsPage()
        {
            return null;
        }

        /// <inheritdoc/>
        public void UpdateUIStyle()
        {
            if (Config.UseRibbon)
            {
                designer.ShowMainMenu = false;
                ribbonControl.Visible = true;

                foreach (Bar bar in designer.DotNetBarManager.Bars)
                    if (bar is ToolbarBase)
                        bar.Hide();
            }
            else
            {
                designer.ShowMainMenu = true;
                ribbonControl.Visible = false;
            }

            btnTextColor.SetStyle(designer.UIStyle);
            btnFillColor.SetStyle(designer.UIStyle);
            btnLineColor.SetStyle(designer.UIStyle);
        }

        #endregion

        #region Private classes
        
        private class ItemInfo
        {
            public int ImageIndex { get; set; }
            public string ImageResource { get; set; }
            public string TextResource { get; set; }
            public string TooltipResource { get; set; }

            public ItemInfo(int imageIndex, string imageRes, string textRes, string tooltipRes)
            {
                ImageIndex = imageIndex;
                ImageResource = imageRes;
                TextResource = textRes;
                TooltipResource = tooltipRes;
            }
        }
        #endregion
    }
}