Example #1
0
        public ArtificialIntelligence(UserInterface userInterface, VisualCortex visualCortex)
        {
            if (logicTimer != null)
            {
                logicTimer.Stop();
            }
            // 0 = 40fps when set to 1ms, 8fps screen, 15fps is 7.5fps
            // 1 = 65fps when set to 1ms, 8fps screen, 40fps is 8fps
            // 2 = 1000fps when set to 1ms, 6 fps screen, 60fps is 6.35 fps
            // 3 = 1000fps when set to 1ms, 7.5 fps screen, 60fps is 7.65 fps, 200fps is 8fps
            logicTimer = new ATimer(3, 1, new ATimer.ElapsedTimerDelegate(() => { logic(); }));



            this.userInterface = userInterface;
            this.visualCortex  = visualCortex;

            timerPerformanceStopwatch         = new High_Performance_Timer.Stopwatch();
            screenCapturePerformanceStopWatch = new High_Performance_Timer.Stopwatch();

            basicAI   = new BasicAI();
            autoQueue = new AutoQueueManager();

            logicTimer.Start();
        }
Example #2
0
        public override void LoadContent(ContentManager Content)
        {
            durTimer = new ATimer();
            durTimer.Interval = 3000;
            durTimer.TimerType = ATimerType.MilliSeconds;

            Texture2D texture = Content.Load<Texture2D>("Data\\GFX\\CheckPointText");
            Position = new Vector2(Position.X + 16 - (texture.Width / 2), Position.Y - 32);
            ScreenManagers.GameScreen gs = (ScreenManagers.GameScreen)ScreenManagers.ScreenManager.CurrentScreen;

            if(Position.X < 0 || Position.X + texture.Width > gs.level.Width)
            {
                float x = Position.X;
                float y = Position.Y;

                x = MathHelper.Clamp(x, 0, gs.level.Width * Map.Tile.WIDTH - texture.Width);
                y = MathHelper.Clamp(y, 0, gs.level.Height * Map.Tile.HEIGHT - texture.Height);

                Position = new Vector2(x, y);
            }

            originalPos = Position;
            animation = new Graphics.Animation(texture, Position, texture.Width, texture.Height, 0, 0);
            Rect = new Rectangle((int)Position.X, (int)Position.Y, texture.Width, texture.Height);
            animation.Depth = 1.0f;
        }
Example #3
0
    static void _TimerProc(ATimer t)
    {
        Timer1sOr025s?.Invoke();
        bool needFast = MainForm.Visible;

        if (needFast != (s_timerCounter > 0))
        {
            t.Every(needFast ? 250 : 1000);
        }
        if (needFast)
        {
            Timer025sWhenVisible?.Invoke();
            s_timerCounter++;
            if (MousePosChangedWhenProgramVisible != null)
            {
                var p = AMouse.XY;
                if (p != s_mousePos)
                {
                    s_mousePos = p;
                    MousePosChangedWhenProgramVisible(p);
                }
            }
        }
        else
        {
            s_timerCounter = 0;
        }
        if (0 == (s_timerCounter & 3))
        {
            Timer1s?.Invoke();
        }
    }
Example #4
0
        };                                                                                                                               //Color.BlueViolet

        /// <summary>
        /// Briefly shows standard blinking on-screen rectangle.
        /// </summary>
        public static void ShowOsdRect(RECT r, bool limitToScreen = false)
        {
            var osr = CreateOsdRect();

            r.Inflate(2, 2);             //2 pixels inside, 2 outside
            if (limitToScreen)
            {
                var k = AScreen.Of(r).Bounds;
                r.Intersect(k);
            }
            osr.Rect = r;
            osr.Show();

            int i = 0;

            ATimer.Every(250, t => {
                if (i++ < 5)
                {
                    osr.Color = (i & 1) != 0 ? 0xFFFFFF00 : 0xFF8A2BE2;
                }
                else
                {
                    t.Stop();
                    osr.Dispose();
                }
            });
        }
Example #5
0
 void _OnGotLostFocus(bool got, _SciTextBox tb)
 {
     if (!_cRegex.Checked)
     {
         return;
     }
     if (got)
     {
         //use timer to avoid temporary focus problems, for example when tabbing quickly or closing active Regex window
         ATimer.After(70, _ => { if (tb.Focused)
                                 {
                                     _ShowRegexInfo(tb, false);
                                 }
                      });
     }
     else
     {
         if (_regexWindow.Window.Visible)
         {
             var c = AWnd.ThisThread.FocusedControl;
             if (c == null || (c != _tFind && c != _tReplace && c != _regexWindow.Window && c.TopLevelControl != _regexWindow.Window))
             {
                 _regexWindow.Hide();
             }
         }
     }
 }
Example #6
0
        private void StartAnimation(string status)
        {
            if (!status.Contains("%"))
            {
                status += "%";
            }

            _aStatus = status;
            ATimer.Start();
        }
Example #7
0
        public FlameBowl(Vector2 position)
            : base(position)
        {
            burstTimer = new ATimer();
            burstTimer.TimerType = ATimerType.MilliSeconds;
            burstTimer.Interval = 3000;
            burstTimer.Start();

            Rect = new Rectangle((int)Position.X, (int)Position.Y, DEFAULT_WIDTH, DEFAULT_HEIGHT);
        }
Example #8
0
 public void DestroyOfTime(float t, Action ev = null)
 {
     if (ev is null)
     {
         ATimer.Set(GetInstanceID().ToString(), t, this.Sleep);
     }
     else
     {
         ATimer.Set(GetInstanceID().ToString(), t, () => { this.Sleep(); ev(); });
     }
 }
Example #9
0
 private void OnTriggerStay2D(Collider2D col)
 {
     if (col.CompareTag("Player"))
     {
         if (mOverlapAble)
         {
             OnOverlap();
             mOverlapAble = false;
             ATimer.Set(GetInstanceID() + "OnOverlap", DelayT, () => { mOverlapAble = true; });
         }
     }
 }
Example #10
0
        public override void LoadContent(ContentManager Content)
        {
            Texture2D player = Content.Load<Texture2D>("Data\\GFX\\NPCTemp");
            gossipTexture = Content.Load<Texture2D>("Data\\GFX\\GossipBubble");
            animation = new Graphics.Animation(player, Position, 32, 48, 7, 75);
            animation.Depth = 0.89f;
            CollisionRectangle = new Rectangle((int)Position.X, (int)Position.Y, 32, 48);

            idleLoopTimer = new ATimer();
            idleLoopTimer.Interval = 3000;
            idleLoopTimer.Start();
        }
Example #11
0
        public Alien(Vector2 position, int maxHealth)
            : base(position, maxHealth)
        {
            timerSwitch = new ATimer();
            timerSwitch.Interval = Engine.Randomizer.Next(4000, 8000);
            timerSwitch.TimerType = ATimerType.MilliSeconds;

            Speed = 0.15f;
            State = EntityState.Idle;
            CollisionRectangle = new Rectangle((int)Position.X, (int)Position.Y, Entity.WIDTH, Entity.HEIGHT);
            Owner = ProjectileOwner.Alien;
        }
Example #12
0
    void _ShowPopupHtml(ATimer t)
    {
        var ci   = t.Tag as CiComplItem;
        var html = _compl.GetDescriptionHtml(ci, 0);

        if (html == null)
        {
            return;
        }
        _popupHtml.Html        = html;
        _popupHtml.OnLinkClick = (ph, e) => ph.Html = _compl.GetDescriptionHtml(ci, e.Link.ToInt(1));
        _popupHtml.Show(Panels.Editor.ZActiveDoc, _w.Bounds);
    }
 public void OnHit()
 {
     for (int i = 0; i < SpriteRenderers.Length; i++)
     {
         SpriteRenderers[i].material = Material;
     }
     ATimer.SetAndReset(GetInstanceID() + "HitColorEffect", Time, () => {
         for (int i = 0; i < SpriteRenderers.Length; i++)
         {
             SpriteRenderers[i].material = Origin_Material[i];
         }
     });
 }
 private void Start()
 {
     rb2d            = GetComponent <Rigidbody2D>();
     player          = GetComponent <Player>();
     rayCastManager  = GetComponent <BoxColliderRayCastManager>();
     jumpBufferTimer = new ATimer(jumpBufferTime, (a, e) =>
     {
         jumpRegisteredInAir = false;
     });
     coyoteJumpTimer = new ATimer(coyoteJumpTime, (a, e) =>
     {
         isInCoyoteTime = false;
     });
 }
Example #15
0
    protected override void OnVisibleChanged(EventArgs e)
    {
        //AOutput.Write("OnVisibleChanged", Visible, ((AWnd)this).IsVisible); //true, false
        bool visible = Visible;

        //note: we don't use OnLoad. It's unreliable, sometimes not called, eg when made visible from outside.
        if (visible && Program.Loaded == EProgramState.LoadedWorkspace)
        {
            //APerf.Next();
            _StartProfileOptimization();             //fast
            APerf.Next('v');

            Panels.PanelManager.ZGetPanel(Panels.Output).Visible = true;             //else AOutput.Write would not auto set visible until the user makes it visible, because handle not created if invisible

            var hm = Api.GetSystemMenu(_Hwnd, false);
            Api.AppendMenu(hm, 0, c_menuid_Exit, "&Exit");

            Application.AddMessageFilter(new _AppMessageFilter());

            Panels.Files.ZOpenDocuments();

            Program.Loaded = EProgramState.LoadedUI;
            Load?.Invoke(this, EventArgs.Empty);

            APerf.Next('o');
            CodeInfo.UiLoaded();

#if TRACE
            ATimer.After(1, _ => {
                var s = CommandLine.TestArg;
                if (s != null)
                {
                    AOutput.Write(ATime.PerfMicroseconds - Convert.ToInt64(s));
                }
                //APerf.NW('V');

                //EdDebug.PrintTabOrder(this);
            });
#endif
        }

        if (!visible)
        {
            CodeInfo.Stop();
        }
        UacDragDrop.AdminProcess.Enable(visible);

        base.OnVisibleChanged(e);
    }
Example #16
0
 static void _Hook()
 {
     s_hook = AHookWin.ThreadCbt(m => {
         //AOutput.Write(m.code, m.wParam, m.lParam);
         //switch(m.code) {
         //case HookData.CbtEvent.ACTIVATE:
         //case HookData.CbtEvent.SETFOCUS:
         //	AOutput.Write((AWnd)m.wParam);
         //	AOutput.Write(AWnd.Active);
         //	AOutput.Write(AWnd.ThisThread.Active);
         //	AOutput.Write(AWnd.Focused);
         //	AOutput.Write(AWnd.ThisThread.Focused);
         //	break;
         //}
         if (m.code == HookData.CbtEvent.ACTIVATE)
         {
             var w = (AWnd)m.wParam;
             if (!w.HasExStyle(WS2.NOACTIVATE))
             {
                 //AOutput.Write(w);
                 //AOutput.Write(w.ExStyle);
                 //Api.SetForegroundWindow(w); //does not work
                 ATimer.After(1, _ => {
                     if (s_hook == null)
                     {
                         return;
                     }
                     //AOutput.Write(AWnd.Active);
                     //AOutput.Write(AWnd.ThisThread.Active);
                     bool isActive = w == AWnd.Active, activate = !isActive && w == AWnd.ThisThread.Active;
                     if (isActive || activate)
                     {
                         s_hook.Dispose(); s_hook = null;
                     }
                     if (activate)
                     {
                         Api.SetForegroundWindow(w);
                         //w.ActivateLL(); //no, it's against Windows rules, and works differently with meta outputPath
                         //Before starting task, editor calls AllowSetForegroundWindow. But if clicked etc a window after that:
                         //	SetForegroundWindow fails always or randomly;
                         //	Activate[LL] fails if that window is of higher UAC IL, unless the foreground lock timeout is 0.
                     }
                 });
             }
         }
         return(false);
     });
 }
Example #17
0
    protected override void OnLoad(EventArgs e)
    {
        var z = _sci.Z;

        z.StyleBackColor(Sci.STYLE_DEFAULT, 0xF0F0F0);
        z.StyleFont(Sci.STYLE_DEFAULT, Font);
        z.MarginWidth(1, 4);
        z.StyleClearAll();
        //_sci.Call(Sci.SCI_SETHSCROLLBAR);
        _sci.Call(Sci.SCI_SETVSCROLLBAR);

        Program.MousePosChangedWhenProgramVisible += _MouseInfo;
        ATimer.After(50, _ => { ZSetAboutInfo(); _html.Show(); });

        base.OnLoad(e);
    }
Example #18
0
        public int Show(AWnd owner)
        {
            if (Api.GetFocus() == default)              //prevent activating the menu window on click
            {
                ATimer.After(1, _ => {
                    var w = AWnd.Find("", "#32768", WOwner.ThisThread);                     //find visible classic menu window of this thread
                    if (!w.Is0)
                    {
                        w.SetExStyle(WS2.NOACTIVATE, WSFlags.Add);
                    }
                });
            }
            var p = AMouse.XY;

            return(Api.TrackPopupMenuEx(_h, Api.TPM_RETURNCMD, p.x, p.y, owner));
        }
Example #19
0
    public static void ZRunApplication()
    {
        var f = new FMain();

#if TRACE
        ATimer.After(1, _ => APerf.NW('P'));
#endif
        if (!Program.Settings.runHidden || CommandLine.StartVisible)
        {
            Application.Run(f);
        }
        else
        {
            Application.Run();
        }
    }
Example #20
0
        public Entity(Vector2 position, int maxHealth)
        {
            airTime = new ATimer();
            airTime.Interval = 100f;
            airTime.TimerType = ATimerType.MilliSeconds;
            airTime.Stop();

            startPosition = Vector2.Zero;
            DrawColor = Color.White;
            CollisionRectangle = new Rectangle(0, 0, WIDTH, HEIGHT);
            Health = new GameAttribute(0, maxHealth);
            Position = position;
            Friction = 0.2f;
            HasGravity = true;
            HasWorldCollision = true;
        }
Example #21
0
        private void Editor_LostFocus(object sender, EventArgs e)
        {
            var c = CurrentEditor;

            if (c != null && !ContainsFocus && c.TopLevelControl == Form.ActiveForm)
            {
                //async to avoid a hard-to-debug ObjectDisposedException
                ATimer.After(100, _ =>
                {
                    if (CurrentEditor != null && !ContainsFocus)
                    {
                        CurrentEditorOwner.EndEdit(true);
                        UpdateView();
                    }
                });
            }
        }
Example #22
0
 public bool MoveRandom()
 {
     if (!m_groundDetectionData.isGrounded)
     {
         return(false);
     }
     m_MoveData.State = MobMoveData.eState.Move;
     m_CurAniST       = eMobAniST.Walk;
     ATimer.Tick(this);
     if (!m_bYMoveCoolTime && !m_bJumpStart)
     {
         m_bYMoveCoolTime = ARandom.Get(70) ? true : ARandom.Get(50) ? Jump() : Fall();
         m_bYMoveCoolTime = true;
         ATimer.Set("JumpFall" + GetInstanceID(), m_MoveData.CoolTime, () => { m_bYMoveCoolTime = false; });
     }
     return(true);
 }
Example #23
0
        AdminProcess()
        {
            _timer = new ATimer(_ => _Timer());

            //use hook to detect when drag-drop started
            _hook = new AHookAcc(AccEVENT.SYSTEM_CAPTURESTART, 0, d => {
                _EndedDragMode();
                if (0 == d.wnd.ClassNameIs("CLIPBRDWNDCLASS", "DragWindow"))
                {
                    return;
                }
                _StartedDragMode();
            }, flags: AccHookFlags.SKIPOWNPROCESS);

            //note: we don't use SYSTEM_CAPTUREEND. It's too early and sometimes missing.
            //tested: no EVENT_SYSTEM_DRAGDROPSTART events.
            //info: classname "DragWindow" is of Windows Store, eg Edge.
            //rejected: int pid = d.wnd.ProcessId; using(var u = AUac.OfProcess(pid)) { if(u == null || u.Elevation == UacElevation.Full) return; }
        }
Example #24
0
            internal void InitDockStateFromXML(XElement x)
            {
                Enum.TryParse(x.Attr("state"), out this.DockState);
                bool hide = x.HasAttr("hide"), floating = this.DockState == _DockState.Floating;

                if (hide || floating)
                {
                    this.SavedVisibleDockState = this.DockState;
                    this.DockState             = _DockState.Hidden;
                    switch (this)
                    {
                    case _Panel gp:
                        gp.Content.Visible = false;
                        break;

                    case _Tab gt:
                        foreach (var v in gt.Items)
                        {
                            v.Content.Visible = false;
                        }
                        break;
                    }
                    if (!hide)
                    {
                        PaintEventHandler eh = null;
                        eh = (object sender, PaintEventArgs e) => {
                            _manager.Paint -= eh;
                            //SetDockState(_DockState.Floating);
                            ATimer.After(200, _ => SetDockState(_DockState.Floating));
                        };
                        _manager.Paint += eh;
                    }
                }
                this.SavedFloatingBounds = _RectFromString(x.Attr("rectFloating"));
                if (!this.IsTabbedPanel || floating)
                {
                    Enum.TryParse(x.Attr("captionAt"), out this.CaptionAt);
                }
            }
Example #25
0
    static void _Main(string[] args)
    {
        //Test(); return;
        //Process.GetCurrentProcess().ProcessorAffinity = (IntPtr)1; //test how works with 1 CPU
        //Task.Run(() => { while(true) { Thread.Sleep(1000); GC.Collect(); } });

        if (CommandLine.OnProgramStarted(args))
        {
            return;
        }

        OutputServer.NoNewline = true;
        OutputServer.Start();

        Api.SetErrorMode(Api.GetErrorMode() | Api.SEM_FAILCRITICALERRORS);         //disable some error message boxes, eg when removable media not found; MSDN recommends too.
        Api.SetSearchPathMode(Api.BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE);        //let SearchPath search in current directory after system directories

        //Application.SetHighDpiMode(HighDpiMode.SystemAware); //no, we have manifest
        //Application.EnableVisualStyles(); //no, we have manifest
        Application.SetCompatibleTextRenderingDefault(false);

        Settings = ProgramSettings.Load();

        UserGuid = Settings.user; if (UserGuid == null)
        {
            Settings.user = UserGuid = Guid.NewGuid().ToString();
        }

        ATimer.Every(1000, t => _TimerProc(t));
        //note: timer can make Process Hacker/Explorer show CPU usage, even if we do nothing. Eg 0.02 if 250, 0.01 if 500, <0.01 if 1000.
        //Timer1s += () => AOutput.Write("1 s");
        //Timer1sOr025s += () => AOutput.Write("0.25 s");

        FMain.ZRunApplication();

        OutputServer.Stop();
    }
Example #26
0
    public static void OnProgramLoaded()
    {
        AWnd.More.UacEnableMessages(Api.WM_COPYDATA, Api.WM_USER, Api.WM_CLOSE);
        AWnd.More.RegisterWindowClass("Au.Editor.Msg", _WndProc);
        _msgWnd = AWnd.More.CreateMessageOnlyWindow("Au.Editor.Msg");

        if (_importWorkspace != null || _importFiles != null)
        {
            ATimer.After(10, _ => {
                try {
                    Program.MainForm.ZShowAndActivate();
                    if (_importWorkspace != null)
                    {
                        Program.Model.ImportWorkspace(_importWorkspace);
                    }
                    else
                    {
                        Program.Model.ImportFiles(_importFiles);
                    }
                }
                catch (Exception ex) { AOutput.Write(ex.Message); }
            });
        }
    }
Example #27
0
    ///// <summary>
    ///// The child list control.
    ///// </summary>
    //public AuListControl ListControl => _list;

    public CiPopupList(CiCompletion compl)
    {
        _compl = compl;

        _w = new _Window(this);
        _w.SuspendLayout();
        _w.Size = Au.Util.ADpi.ScaleSize((300, 360));

        _list = new _FastListBox();
        _list.SuspendLayout();
        _list.AccessibleName         = _list.Name = "Codein_list";
        _list.Dock                   = DockStyle.Fill;
        _list.BackColor              = Color.White;
        _list.ZItemClick            += _list_ItemClick;
        _list.ZSelectedIndexChanged += _list_SelectedIndexChanged;

        _tb = new Au.Util.AToolStrip();
        _tb.SuspendLayout();
        _tb.AccessibleName = _tb.Name = "Codein_listFilter";
        _tb.Renderer       = new AuDockPanel.ZDockedToolStripRenderer();
        _tb.GripStyle      = ToolStripGripStyle.Hidden;
        _tb.LayoutStyle    = ToolStripLayoutStyle.VerticalStackWithOverflow;
        int tbWidth = 0;

        var kindNames = CiUtil.ItemKindNames;

        _nKindButtons = kindNames.Length;
        for (int i = 0; i < kindNames.Length; i++)
        {
            _AddButton(kindNames[i], CiUtil.GetKindImage((CiItemKind)i));
        }
        _tb.Items.Add(new ToolStripSeparator());
        _groupButton = _AddButton("Group by namespace or inheritance", EdResources.GetImageNoCacheDpi(nameof(Au.Editor.Resources.Resources.ciGroupBy)));
        if (Program.Settings.ci_complGroup)
        {
            _groupButton.Checked = true;
        }

        ToolStripButton _AddButton(string text, Image image)
        {
            var b = _tb.Items.Add(image) as ToolStripButton;

            b.DisplayStyle = ToolStripItemDisplayStyle.Image;
            b.ImageScaling = ToolStripItemImageScaling.None;
            b.Name         = b.AccessibleName = b.ToolTipText = text;
            b.Margin       = new Padding(1, 1, 0, 0);
            if (tbWidth == 0)
            {
                tbWidth = 4 + b.ContentRectangle.Left * 2 + image.Width;
            }
            return(b);
        }

        _tb.Width        = tbWidth; _tb.AutoSize = false;  //does not work well with autosize, eg width too small when high DPI
        _tb.Dock         = DockStyle.Left;
        _tb.ItemClicked += _tb_ItemClicked;

        _w.Controls.Add(_list);
        _w.Controls.Add(_tb);
        _tb.ResumeLayout();
        _list.ResumeLayout();
        _w.ResumeLayout(true);

        _imgStatic   = EdResources.GetImageNoCacheDpi(nameof(Au.Editor.Resources.Resources.ciOverlayStatic));
        _imgAbstract = EdResources.GetImageNoCacheDpi(nameof(Au.Editor.Resources.Resources.ciOverlayAbstract));

        _popupHtml  = new CiPopupHtml(CiPopupHtml.UsedBy.PopupList);
        _popupTimer = new ATimer(_ShowPopupHtml);
    }
 public void DestroyObj(float DistroyTime)
 {
     ATimer.SetAndReset(GetInstanceID() + "DestroyObj", DistroyTime, SetOff);
 }
 void OnDestroy()
 {
     ATimer.Pop(GetInstanceID() + "DestroyObj");
 }
 public void DestroyObj()
 {
     ATimer.Pop(GetInstanceID() + "DestroyObj");
     SetOff();
 }
Example #31
0
            internal void ShowContextMenu(Point p)
            {
                var  gp    = this as _Panel;
                bool isTab = this is _Tab gt;
                var  state = this.DockState;
                var  m     = new AMenu();

                m.Control.Text = "Menu";

                //dock state
                m.Add("Float\tD-click, drag", o => this.SetDockState(_DockState.Floating)).Enabled      = state != _DockState.Floating;
                m.Add("Dock    \tD-click, Alt+drag", o => this.SetDockState(_DockState.Docked)).Enabled = state != _DockState.Docked;
                //menu.Add("Auto Hide", o => this.SetDockState(_DockState.AutoHide)).Enabled = state != _DockState.AutoHide && !isTab; //not implemented
                m["Hide\tM-click"] = o => this.SetDockState(_DockState.Hidden);

                m.Separator();
                using (m.Submenu("Show Panel")) _manager.ZAddShowPanelsToMenu(m.LastMenuItem.DropDown, false);
                using (m.Submenu("Show Toolbar")) _manager.ZAddShowPanelsToMenu(m.LastMenuItem.DropDown, true);

                m.Separator();
                var k = (!this.IsTabbedPanel || this.IsFloating) ? this : gp.ParentTab;

                //caption edge
                using (m.Submenu("Caption At")) {
                    m["Top"] = o => k._SetCaptionEdge(CaptionEdge.Top); if (k.CaptionAt == CaptionEdge.Top)
                    {
                        m.LastMenuItem.Checked = true;
                    }
                    m["Bottom"] = o => k._SetCaptionEdge(CaptionEdge.Bottom); if (k.CaptionAt == CaptionEdge.Bottom)
                    {
                        m.LastMenuItem.Checked = true;
                    }
                    m["Left"] = o => k._SetCaptionEdge(CaptionEdge.Left); if (k.CaptionAt == CaptionEdge.Left)
                    {
                        m.LastMenuItem.Checked = true;
                    }
                    m["Right"] = o => k._SetCaptionEdge(CaptionEdge.Right); if (k.CaptionAt == CaptionEdge.Right)
                    {
                        m.LastMenuItem.Checked = true;
                    }
                }
                //fixed width/height
                if (this.IsDockedOn(_manager))
                {
                    _AddFixedSize(k.ParentSplit, k);
                    void _AddFixedSize(_Split gs, _Node gn)
                    {
                        if (gs.IsSplitterVisible)
                        {
                            bool fixedSize = gs.IsChildFixedSize(gn);
                            m.Add(gs.IsVerticalSplit ? "Fixed Width" : "Fixed Height", o => gs.SetChildFixedSize(gn, !fixedSize)).Checked = fixedSize;
                        }
                        var gs2 = gs.ParentSplit;

                        if (gs2 != null)
                        {
                            using (m.Submenu("Container")) {
                                m.LastMenuItem.DropDown.Opened += (unu, sed) => {
                                    var osd = new AOsdRect {
                                        Rect = _manager.RectangleToScreen(gs.Bounds), Color = 0x00c000
                                    };
                                    osd.Show();
                                    ATimer.After(1000, _ => osd.Dispose());
                                };
                                _AddFixedSize(gs2, gs);
                            }
                        }
                    }
                }

                //test
                //m.Separator();
                //m["test"] = o =>
                //{
                //};

                //custom
                _manager.ZPanelContextMenu?.Invoke(new ZContextMenuEventArgs(gp, m));

                m.Show(this.ParentControl, p.X, p.Y);
            }
Example #32
0
        /// <summary>
        /// Creates a menu or toolbar item.
        /// </summary>
        /// <param name="x">XML element containing item properties.</param>
        /// <param name="isMenu">false if toolbar item, true if menu item (also if menu bar item).</param>
        ToolStripItem _CreateChildItem(XElement x, bool isMenu)
        {
            string s, tag = x.Name.LocalName;

            if (tag == "sep")
            {
                return new ToolStripSeparator()
                       {
                           Tag = x
                       }
            }
            ;

            ToolStripItem item; ToolStripMenuItem mi;
            bool          isControl = false, needHandler = false;

            if (isMenu)
            {
                mi = new ToolStripMenuItem();

                item = mi;
                if (x.HasElements || x.HasAttr("dd"))
                {
                    _Submenu(x, mi, tag);
                }
                else
                {
                    needHandler = true;
                }
            }
            else if (x.HasAttr("type"))
            {
                isControl = true;
                string cue = x.Attr("cue");
                s = x.Attr("type");
                switch (s)
                {
                case "edit":
                    var ed = new ToolStripSpringTextBox();
                    if (cue != null)
                    {
                        ed.ZSetCueBanner(cue);
                    }
                    item = ed;
                    break;

                case "combo":
                    var combo = new ToolStripSpringComboBox();
                    if (cue != null)
                    {
                        combo.ZSetCueBanner(cue);
                    }
                    item = combo;
                    break;

                default:
                    Debug.Assert(false);
                    return(null);
                }
                if (cue != null)
                {
                    item.AccessibleName = cue;
                }
            }
            else if (x.HasElements || x.HasAttr("dd"))
            {
                ToolStripDropDownItem ddi;
                var handler = _callbacks.GetClickHandler(tag);
                if (handler != null)
                {
                    var sb = new ToolStripSplitButton();
                    sb.ButtonClick += handler;
                    ddi             = sb;
                }
                else
                {
                    ddi = new ToolStripDropDownButton();
                }
                item = ddi;
                _Submenu(x, ddi, tag);
            }
            else
            {
                needHandler = true;
                var b = new ToolStripButton();
                item = b;
            }

            item.Name = tag;
            item.Tag  = x;

            _SetItemProperties(x, item, isMenu, isControl);

            if (needHandler)
            {
                var handler = _callbacks.GetClickHandler(tag);
                if (handler != null)
                {
                    item.Click += handler;
                }
                else
                {
                    ADebug.Print("no handler of " + tag);
                    //return null;
                    //item.Enabled = false;
                    item.Visible = false;
                }
            }

            return(item);
        }

        void _Submenu(XElement x, ToolStripDropDownItem ddItem, string tag)
        {
            var s = x.Attr("dd");

            if (!s.NE())
            {
                ddItem.DropDown = Submenus[s];
            }
            else
            {
                var dd = ddItem.DropDown as ToolStripDropDownMenu;                 //note: not ddItem.DropDown=new ToolStripDropDownMenu(). Then eg hotkeys don't work.
                dd.Name = tag;
                dd.Tag  = x;
                Submenus.Add(tag, dd);

                if (s != null)                              //attribute dd="". Will be filled later, eg on Opening event.
                {
                    dd.Items.Add(new ToolStripSeparator()); //else no drop arrow and no Opening event
                    return;
                }
#if !LAZY_MENUS
                dd.SuspendLayout();                 //with this don't need lazy menus
                _AddChildItems(x, dd, true);
                dd.ResumeLayout(false);
#else
                //Fill menu items later. This saves ~50 ms of startup time if not using dd.SuspendLayout. With dd.SuspendLayout - just 5 ms.
                //Can do it with Opening event or with timer. With timer easier. With event users cannot use MSAA etc to automate clicking menu items (with timer cannot use it only the first 1-2 seconds).
#if true
                ATimer.After(500, t =>
                {
                    dd.SuspendLayout();
                    _AddChildItems(x, dd, true);
                    dd.ResumeLayout(false);
                });
#else
                dd.Items.Add(new ToolStripSeparator());
                CancelEventHandler eh = null;
                eh = (sender, e) =>
                {
                    dd.Opening -= eh;
                    dd.Items.Clear();
                    _AddChildItems(x, dd, true);
                };
                dd.Opening += eh;
#endif
#endif
            }
        }

        void _SetItemProperties(XElement x, ToolStripItem item, bool isMenu, bool isControl)
        {
            string s, defaultText = null;

            var tt = x.Attr("tt");             //tooltip

            item.ToolTipText = tt ?? (isMenu ? null : (defaultText = _GetDefaultItemText(x)));

            if (!isMenu)
            {
                if (x.HasAttr("hide"))
                {
                    item.Overflow = ToolStripItemOverflow.Always;
                }
                else if (!_inBuildAll)
                {
                    item.Overflow = ToolStripItemOverflow.AsNeeded;
                }
            }
            if (isControl)
            {
                return;
            }

            Image im = null;

            if (x.Attr(out s, "i2"))              //custom image as icon file
            {
                im = AIcon.GetFileIconImage(s);
                if (im == null)
                {
                    AOutput.Write($"Failed to get {(isMenu ? "menu item" : "toolbar button")} {x.Name} icon from file {s}\n\tTo fix this, right-click it and select Properties...");
                }
                //SHOULDDO: async or cache
            }
            if (im == null && x.Attr(out s, "i"))
            {
                im = _callbacks.GetImage(s);                                              //image from resources
            }
            item.Image = im;

            if (x.Attr(out s, "color") && ColorInt.FromString(s, out var color))
            {
                item.ForeColor = (Color)color;
            }
            else if (!_inBuildAll)
            {
                item.ForeColor = Color.FromKnownColor(KnownColor.ControlText);
            }

            bool hasCustomText = x.Attr(out s, "t2");             //custom text

            item.Text = s ?? defaultText ?? _GetDefaultItemText(x);

            if (isMenu)
            {
                var mi = item as ToolStripMenuItem;
                if (!_inBuildAll)
                {
                    mi.ShortcutKeys             = 0;
                    mi.ShortcutKeyDisplayString = null;
                }
                if (x.Attr(out s, "hk"))
                {
                    bool ok = AKeys.More.ParseHotkeyString(s, out var hk);
                    if (ok)
                    {
                        try { mi.ShortcutKeys = hk; } catch { ok = false; }
                    }
                    if (!ok)
                    {
                        ADebug.Print("Invalid hotkey: " + s);
                    }
                }
                if (x.Attr(out string ss, "hkText"))
                {
                    mi.ShortcutKeyDisplayString = (s == null) ? ss : s + ", " + ss;
                }
            }
            else
            {
                var style = item.Image == null ? ToolStripItemDisplayStyle.ImageAndText : (ToolStripItemDisplayStyle)x.Attr("style", 0);
                if (style == 0)
                {
                    style = hasCustomText ? ToolStripItemDisplayStyle.ImageAndText : ToolStripItemDisplayStyle.Image;                            //0 is ToolStripItemDisplayStyle.None
                }
                item.DisplayStyle = style;
            }
        }

        /// <summary>
        /// If x has attribute t, gets its value.
        /// Else gets its name and converts to text, eg "File_OneTwo" to "One Two".
        /// </summary>
        string _GetDefaultItemText(XElement x)
        {
            if (!x.Attr(out string s, "t"))
            {
                string tag = x.Name.LocalName;
                s = tag.Remove(0, tag.LastIndexOf('_') + 1);                 //eg "Edit_Copy" -> "Copy"
                s = s.RegexReplace("(?<=[^A-Z])(?=[A-Z])", " ");             //"OneTwoThree" -> "One Two Three". //speed: don't need to optimize.
            }
            return(s);
        }

        /// <summary>
        /// Merges custom attributes into default menubar or toolbar XML.
        /// Reorders toolbar buttons if need.
        /// </summary>
        /// <param name="xCustom">Root element of customizations file.</param>
        /// <param name="xtsDef">Default menustrip or toolstrip. For custom toolbars the function can replace it.</param>
        /// <param name="name">xtsDef name, just to avoid getting it again.</param>
        /// <param name="isMenu"></param>
        void _MergeCustom(XElement xCustom, ref XElement xtsDef, string name, bool isMenu)
        {
            var xtsCust = xCustom.Element(xtsDef.Name); if (xtsCust == null)

            {
                return;
            }

            if (isMenu)
            {
            }
            else if (name.Starts("Custom"))
            {
                var xc = xCustom.Element(name); if (xc == null)
                {
                    return;
                }
                xc.Remove();
                xtsDef.ReplaceWith(xc);
                xtsDef = xc;
                return;
                //MSDN: "if the new content has no parent, then the objects are simply attached to the XML tree. If the new content already is parented and is part of another XML tree, then the new content is cloned". Tested, it's true.
            }
            else
            {
                //reorder toolbar buttons
                if (xtsCust.Attr(out string s, "order"))
                {
                    xtsDef.Elements("sep").Remove();                     //remove all default <sep/>, because all separators now are in the 'order' attribute
                    var a = s.SegSplit(" ");
                    for (int i = a.Length - 1; i >= 0; i--)
                    {
                        if (a[i] == "sep")
                        {
                            xtsDef.AddFirst(new XElement("sep"));
                        }
                        else
                        {
                            var xb = xtsDef.Element(a[i]); if (xb == null)
                            {
                                continue;
                            }
                            xb.Remove(); xtsDef.AddFirst(xb);
                        }
                    }
                }
            }

            foreach (var xCust in xtsCust.Elements())
            {
                foreach (var xDef in xtsDef.Descendants(xCust.Name))
                {
                    foreach (var att in xCust.Attributes())
                    {
                        xDef.SetAttributeValue(att.Name, att.Value);
                    }
                }
            }
        }

        /// <summary>
        /// Extracts differences between _xmlFileDefault and _xStrips and saves to _xmlFileCustom.
        /// </summary>
        void _DiffCustom()
        {
            var    xStripsDefault = AExtXml.LoadElem(_xmlFileDefault);
            var    xStripsCustom  = new XElement("strips");
            string s;

            //menus
            _DiffDescendants(MenuBar.Tag as XElement, true);

            //standard toolbars
            foreach (var ts in Toolbars.Values)
            {
                if (ts == _tsCustom1 || ts == _tsCustom2)
                {
                    continue;
                }
                _DiffDescendants(ts.Tag as XElement, false);
            }

            void _DiffDescendants(XElement xts, bool isMenu)
            {
                XElement xtsDef = xStripsDefault.Element(xts.Name), xtsCust = null;

                foreach (var x in xts.Descendants())
                {
                    var name = x.Name; if (name == "sep")
                    {
                        continue;
                    }
                    XElement xDef = xtsDef.Desc(name), xCust = null;
                    foreach (var att in x.Attributes())
                    {
                        var aname = att.Name;
                        if (att.Value == xDef.Attr(aname))
                        {
                            continue;
                        }
                        if (xtsCust == null)
                        {
                            xStripsCustom.Add(xtsCust = new XElement(xts.Name));
                        }
                        if (xCust == null)
                        {
                            xtsCust.Add(xCust = new XElement(name));
                        }
                        xCust.SetAttributeValue(aname, att.Value);
                    }
                }
                if (isMenu)
                {
                    return;
                }
                //order
                var s1 = new StringBuilder();
                var s2 = new StringBuilder();

                foreach (var x in xts.Elements())
                {
                    if (s1.Length > 0)
                    {
                        s1.Append(' ');
                    }
                    s1.Append(x.Name);
                }
                foreach (var x in xtsDef.Elements())
                {
                    if (s2.Length > 0)
                    {
                        s2.Append(' ');
                    }
                    s2.Append(x.Name);
                }
                s = s1.ToString();
                if (s != s2.ToString())
                {
                    if (xtsCust == null)
                    {
                        xStripsCustom.Add(xtsCust = new XElement(xts.Name));
                    }
                    xtsCust.SetAttributeValue("order", s);
                }
            }

            //custom toolbars. Temporarily move them from _xStrips to xCustom.
            var xCust1 = _tsCustom1.Tag as XElement;
            var xCust2 = _tsCustom2.Tag as XElement;

            if (xCust1.HasElements)
            {
                xCust1.Remove(); xStripsCustom.Add(xCust1);
            }
            if (xCust2.HasElements)
            {
                xCust2.Remove(); xStripsCustom.Add(xCust2);
            }

            //AOutput.Clear();
            //AOutput.Write(xStripsCustom);
#if true
            //save
            try {
                AFile.CreateDirectoryFor(_xmlFileCustom);
                xStripsCustom.SaveElem(_xmlFileCustom);
            }
            catch (Exception e) {
                AOutput.Write("Failed to save XML file", _xmlFileCustom, e.Message);
            }
#endif

            if (xCust1.HasElements)
            {
                xCust1.Remove(); _xStrips.Add(xCust1);
            }
            if (xCust2.HasElements)
            {
                xCust2.Remove(); _xStrips.Add(xCust2);
            }
        }
Example #33
0
        public UITimer(float interval)
        {
            timer = new ATimer();
            timer.Interval = 20;
            timer.TimerType = ATimerType.MilliSeconds;

            startTimer = new ATimer();
            startTimer.Interval = interval;
            startTimer.TimerType = ATimerType.MilliSeconds;

            Alpha = 0f;
        }
Example #34
0
            /// <summary>
            /// Starts or stops capturing.
            /// Does nothing if already in that state.
            /// </summary>
            public void StartStop(bool start)
            {
                if (start == Capturing)
                {
                    return;
                }
                var wForm = (AWnd)_form;

                if (start)
                {
                    //let other forms stop capturing
                    wForm.Prop.Set(c_propName, 1);
                    AWnd.Find(null, "WindowsForms*", also: o => {
                        if (o != wForm && o.Prop[c_propName] == 1)
                        {
                            o.Send(c_stopMessage);
                        }
                        return(false);
                    });

                    if (!Api.RegisterHotKey(wForm, 1, 0, KKey.F3))
                    {
                        ADialog.ShowError("Failed to register hotkey F3", owner: _form);
                        return;
                    }
                    Capturing = true;

                    //set timer that shows AO rect
                    if (_timer == null)
                    {
                        _osr   = TUtil.CreateOsdRect();
                        _timer = new ATimer(t => {
                            //Don't capture too frequently.
                            //	Eg if the callback is very slow. Or if multiple timer messages are received without time interval (possible in some conditions).
                            long t1 = ATime.PerfMilliseconds, t2 = t1 - _prevTime; _prevTime = t1; if (t2 < 100)
                            {
                                return;
                            }

                            //show rect of UI object from mouse
                            AWnd w = AWnd.FromMouse(WXYFlags.NeedWindow);
                            RECT?r = default;
                            if (!(w.Is0 || w == wForm || w.OwnerWindow == wForm))
                            {
                                r = _cbGetRect();
                            }
                            if (r.HasValue)
                            {
                                var rr = r.GetValueOrDefault();
                                rr.Inflate(2, 2);                                 //2 pixels inside, 2 outside
                                _osr.Rect = rr;
                                _osr.Show();
                            }
                            else
                            {
                                _osr.Visible = false;
                            }
                        });
                    }
                    _timer.Every(250);
                }
                else
                {
                    Capturing = false;
                    Api.UnregisterHotKey(wForm, 1);
                    wForm.Prop.Remove(c_propName);
                    _timer.Stop();
                    _osr.Hide();
                }
            }
Example #35
0
    void _InfoInit()
    {
        const string c_script = @"This file is a C# script. There are several ways to run a script:
1. Click the Run button or menu item.
2. Add script name in Options -> General -> Run scripts when this workspace loaded.
3. Call <help>ATask.Run<> from another script. Example: <code>ATask.Run(""Script8.cs"");</code>
4. <help editor/Command line>Command line<>. Example: <code>Au.CL.exe ""Script8.cs""</code>
5. An output link. Example: <code>AOutput.Write(""<>Click to run <script>Script8.cs<>."");</code>

In script code you can add <help Au.Triggers.ActionTriggers>triggers<> (hotkey etc) to execute parts of script code when it is running. There are no such triggers to launch scripts.
";
        const string c_class  = "This file is a C# class file.";

        _info.Z.SetText(
            @"C# file properties here are similar to C# project properties in Visual Studio. This program does not use project files. A C# file is like a project. Its properties are saved in <c green>/*/ meta comments /*/<> at the very start of code. Can be changed here or in the code editor.

" + (_isClass ? c_class : c_script));

        _infoDict = new Dictionary <string, string>(32);
        _Add(_bAddNet,
             @"<b>Assembly<> - add one or more .NET assemblies (.dll files) as references.
Adds meta <c green>r FileName<>.

Don't need to add Au.dll and .NET Core runtime dlls.
To use 'extern alias', edit in the code editor like this: <c green>r Alias=Assembly<>
To remove, delete the line in the code editor.

If the file is in <link>%AFolders.ThisApp%<> or its subfolders, use file name or relative path, else need full path. If role of the script is not miniProgram, at run time the file must be directly in AFolders.ThisApp or AFolders.ThisApp\Libraries. If role is editorExtension, may need to restart editor.
");
        const string c_com = @" COM component's type library to an <i>interop assembly<>.
Adds meta <c green>com FileName.dll<>. Saves the assembly file in <link>%AFolders.Workspace%\.interop<>.

An interop assembly is a .NET assembly without real code. Not used at run time. At run time is used the COM component (registered native dll or exe file). Set prefer32bit true if 64-bit dll unavailable.

To remove, delete the line in the code editor. Optionally delete unused interop assemblies.
";

        _Add(_bAddComRegistry,
             @"<b>COM<> - convert a registered" + c_com);
        _Add(_bAddComBrowse,
             @"<b>...<> - convert a" + c_com);
        _Add(_bAddLibraryProject,
             @"<b>Library project<> - add a reference to a class library created in this workspace.
Adds meta <c green>pr File.cs<>. The compiler will compile it if need and use the created dll file as a reference.

The recommended outputPath of the library project is <link>%AFolders.ThisApp%\Libraries<>. Else may not find the dll at run time.

To remove, delete the line in the code editor. Optionally delete unused dll files.
");
        _Add(_bAddClass,
             @"<b>Class file<> - add a C# code file that contains some classes/functions used by this file.
Adds meta <c green>c File.cs<>. The compiler will compile all code files and create single assembly.

If this file is in a project, don't need to add class files that are in the project folder.
Can be added only files that are in this workspace. Import files if need, for example drag/drop.
Can be path relative to this file (examples: Class5.cs, Folder\Class5.cs, ..\Folder\Class5.cs) or path in the workspace (examples: \Class5.cs, \Folder\Class5.cs).
To remove, delete the line in the code editor.
");
        _Add(_bAddResource,
             @"<b>Resource<> - add an image or other file as a managed resource.
Adds meta <c green>resource File<>. The compiler will add the file to the output assembly.

Resource type: .png, .bmp, .jpg, .jpeg, .gif, .tif, .tiff - Bitmap. .ico - Icon. Other - byte[].
To add a text file as string, in the code editor edit like this: <c green>resource file.txt /string<>
To add multiple strings, add a 2-column CSV file. Edit: <c green>resource file.csv /strings<>

Need to add resource files even if they are in project folder.
Can be added only files that are in this workspace. Import files if need, for example drag/drop.
Can be path relative to this file (examples: File.png, Folder\File.png, ..\Folder\File.png) or path in the workspace (examples: \File.png, \Folder\File.png).
To remove, delete the line in the code editor.

Examples of loading resources at run time:
<code>var bitmap = Au.Util.AResources.GetAppResource(""file.png"") as Bitmap;</code>
<code>var icon = new Icon(Au.Util.AResources.GetAppResource(""file.ico"") as Icon, 16, 16);</code>
<code>var cursor = Au.Util.ACursor.LoadCursorFromMemory(Au.Util.AResources.GetAppResource(""file.cur"") as byte[]);</code>
");
        _Add(_tFindInList,
             @"<b>Find in lists<> - in the drop-down lists show only items containing this text.
");

        void _Add(Control c, string s) => _infoDict.Add(c.Name, s);

        _infoRow             = -1;
        _infoTimer           = new ATimer(_ => _SetInfoText(_infoText));
        _grid.ZShowEditInfo += (cc, rowInfo) => { _SetInfoText(rowInfo); _gridEditMode = rowInfo != null; };

        void _SetInfoText(string infoText)
        {
            if (infoText == null || _gridEditMode || infoText == _infoTextPrev)
            {
                return;
            }
            _infoTextPrev = infoText;
            _info.Z.SetText(infoText);
        }
    }
Example #36
0
 void OnDestroy()
 {
     ATimer.Pop(GetInstanceID() + "FindCeiling");
 }