Newer
Older
TBO / TBO / UI / tboTK / Application.cs
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace TBO.UI.tboTK
{
    abstract class Application : IContiner
    {

        #region IContiner
        private Dictionary<string, Control> controls = new Dictionary<string, Control>();

        public bool Add(Control c)
        {
            if (c == null)
                return false;
            if (Get(c.Id, true) != null)
                return false;
            controls[c.Id] = c;
            return true;
        }

        public Control Get(string id, bool deep = false)
        {
            Control r;
            if (controls.TryGetValue(id, out r))
                return r;
            if (deep)
                foreach (Control c in controls.Values)
                    if (c is IContiner)
                        return ((IContiner)c).Get(id, deep);
            return null;
        }

        public Control Get(int x, int y, bool deep = false)
        {
            Control result = null;
            foreach (Control c in controls.Values)
            {
                if (c.Bounds.Contains(x, y))
                    result = c;
            }
            if (deep && (result is IContiner))
            {
                Control sub = ((IContiner)result).Get(x, y, deep);
                if (sub != null)
                    result = sub;
            }
            return result;
        }

        public bool Remove(string id)
        {
            return Remove(Get(id));
        }

        public bool Remove(Control c)
        {
            if (c == null)
                return false;
            return controls.Remove(c.Id);
        }

        public void RemoveAll()
        {
            controls.Clear();
        }

        public Control[] Controls => new List<Control>(controls.Values).ToArray();
        #endregion

        public virtual void WhenKey(Shell.Key k, bool down)
        {
        }

        public abstract void ResizeTo(Size size);
        public virtual void Paint(Graphics g, Rectangle clip)
        {
            foreach (Control c in controls.Values)
                if (c.Visible && c.Clips(clip))
                    PaintControl(c, g, clip);
        }
        public abstract void ProcessCommand(string cmd);
        public abstract void Shown();

        private void PaintControl(Control c, Graphics g, Rectangle clip)
        {
            g.Clip = new Region(c.ScreenBounds);
            clip = new Rectangle(clip.Left - c.Left, clip.Top - c.Top, clip.Width, clip.Height);
            GraphicsState gs = g.Save();
            g.TranslateTransform(c.Left, c.Top);
            try
            {
                c.Paint(g, clip);
            }
            finally
            {
                g.Restore(gs);
            }
        }

        public abstract string Id { get; }
        public abstract string Title { get; }
    }
}