示例#1
0
 bool OpenGameButtonHitTest(int x, int y)
 {
     x -= AutoScrollPosition.X;
     y -= AutoScrollPosition.Y;
     DpiMeasurement.DpiXYMeasurement(this);
     return(x > DpiMeasurement.ScaleValueX(3) && x < DpiMeasurement.ScaleValueX(71) && y > DpiMeasurement.ScaleValueY(3) && y < DpiMeasurement.ScaleValueX(71));
 }
示例#2
0
        void BattleListTab_Enter(object sender, EventArgs e)
        {
            Paint -= BattleListTab_Enter;
            SuspendLayout(); //pause
            InitializeComponent();

            if (DesignMode)
            {
                return;
            }
            DpiMeasurement.DpiXYMeasurement(this);
            var lookingGlass = new PictureBox
            {
                Width    = DpiMeasurement.ScaleValueY(20),
                Height   = DpiMeasurement.ScaleValueY(20),
                Image    = ZklResources.search,
                SizeMode = PictureBoxSizeMode.CenterImage,
                Dock     = DockStyle.Left
            };

            Program.ToolTip.SetText(lookingGlass, "Search game, description, map or player");
            Program.ToolTip.SetText(searchBox, "Search game, description, map or player");

            showEmptyBox.Checked    = Program.Conf.ShowEmptyBattles;
            showFullBox.Checked     = Program.Conf.ShowNonJoinableBattles;
            showOfficialBox.Checked = Program.Conf.ShowOfficialBattles;

            // battle list
            battleListControl = new BattleListControl()
            {
                Dock = DockStyle.Fill
            };
            battlePanel.Controls.Add(battleListControl);
            ResumeLayout();
        }
示例#3
0
        void SettingsTab_Load(object sender, EventArgs e)
        {
            RefreshConfig();
            //make sure the split start at 203 (relative to any DPI scale)
            DpiMeasurement.DpiXYMeasurement(this);
            int splitDistance = DpiMeasurement.ScaleValueY(203);//DpiMeasurement is a static class stored in ZeroKLobby\Util.cs

            splitContainerAtMid.SplitterDistance = splitDistance;
        }
        void ShowAdvanced()
        {
            int designHeight = 405;

            DpiMeasurement.DpiXYMeasurement(this);
            Height = DpiMeasurement.ScaleValueY(designHeight);
            advancedOptionsGroup.Visible = true;
            showAdvancedButton.Text      = "Hide Advanced Options";
        }
        void HideAdvanced()
        {
            int designHeight = 235;

            DpiMeasurement.DpiXYMeasurement(this);             //this measurement use cached value. It won't cost anything if another measurement was already done in other control element
            Height = DpiMeasurement.ScaleValueY(designHeight); //DpiMeasurement is a static class stored in ZeroKLobby\Util.cs
            advancedOptionsGroup.Visible = false;
            showAdvancedButton.Text      = "Show Advanced Options";
        }
        void UpdateImage()
        {
            DpiMeasurement.DpiXYMeasurement();
            MakeMinimap();
            RenderPlayers();
            int scaledWidth  = DpiMeasurement.ScaleValueX(Width);
            int scaledHeight = DpiMeasurement.ScaleValueY(Height);

            image = MakeSolidColorBitmap(BackBrush, scaledWidth, scaledHeight);
            using (Graphics g = Graphics.FromImage(image))
            {
                if (disposed)
                {
                    image = MakeSolidColorBitmap(BackBrush, scaledWidth, scaledHeight);
                    return;
                }
                if (finishedMinimap != null)
                {
                    g.DrawImageUnscaled(finishedMinimap, DpiMeasurement.ScaleValueX(3), DpiMeasurement.ScaleValueY(3));
                }
                else
                {
                    g.DrawImage(ZklResources.download,
                                DpiMeasurement.ScaleValueX(4),
                                DpiMeasurement.ScaleValueY(3),
                                DpiMeasurement.ScaleValueX(61),
                                DpiMeasurement.ScaleValueY(64));
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.InterpolationMode = InterpolationMode.Default;
                }
                g.SetClip(new Rectangle(0, 0, scaledWidth, scaledHeight));
                String mod_and_engine_name = string.Format("{0}     {1}{2}", Battle.ModName, Battle.EngineName, Battle.EngineVersion);
                int    y              = DpiMeasurement.ScaleValueY(3);
                int    offset         = DpiMeasurement.ScaleValueY(16);
                int    curMapCellSize = DpiMeasurement.ScaleValueX(MapCellSize.Width);
                g.DrawString(Battle.Title, TitleFont, TextBrush, curMapCellSize, y + offset * 0);
                if (g.MeasureString(mod_and_engine_name, ModFont).Width < scaledWidth - curMapCellSize)
                {
                    g.DrawString(mod_and_engine_name, ModFont, TextBrush, curMapCellSize, y + offset * 1);
                    g.DrawImageUnscaled(playersBoxImage, curMapCellSize, y + offset * 2);
                }
                else
                {
                    int offset_offset  = DpiMeasurement.ScaleValueY(4); //this squishes modName & engine-name and dude-icons together abit
                    int offset_offset2 = DpiMeasurement.ScaleValueY(6); //this squished modName & engine-name into 2 tight lines
                    g.DrawString(Battle.ModName, ModFont, TextBrush, curMapCellSize, y + offset * 1 - offset_offset);
                    g.DrawString(string.Format("{0}{1}", Battle.EngineName, Battle.EngineVersion),
                                 ModFont,
                                 TextBrush,
                                 curMapCellSize,
                                 y + offset * 2 - offset_offset - offset_offset2);
                    g.DrawImageUnscaled(playersBoxImage, curMapCellSize, y + offset * 3 - offset_offset - offset_offset2);
                }
                g.ResetClip();
            }
        }
        // todo: check if this is called when joining twice the same mission

        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);
            if (finishLoad)
            {
                DpiMeasurement.DpiXYMeasurement(this);
                minimapFuncBox.minimapSplitContainer1.SplitterDistance = Math.Min(DpiMeasurement.ScaleValueY(23), minimapFuncBox.minimapSplitContainer1.Height); //always show button fully
                DrawMinimap();
            }
        }
示例#8
0
        void MakeMinimap()
        {
            if (resizedMinimap == null)
            {
                return;                   // wait, map is not downloaded
            }
            if (finishedMinimap != null)
            {
                finishedMinimap.Dispose();
            }
            finishedMinimap = new Bitmap(DpiMeasurement.ScaleValueX(ZklResources.border.Width), DpiMeasurement.ScaleValueY(ZklResources.border.Height));

            using (var g = Graphics.FromImage(finishedMinimap))
            {
                g.DrawImage(resizedMinimap, DpiMeasurement.ScaleValueX(6), DpiMeasurement.ScaleValueY(5));
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                var            x        = DpiMeasurement.ScaleValueX(10);
                var            y        = DpiMeasurement.ScaleValueY(minimapSize - 20);
                Action <Image> drawIcon = image =>
                {
                    g.DrawImage(image, x, y, DpiMeasurement.ScaleValueX(20), DpiMeasurement.ScaleValueY(20));
                    x += DpiMeasurement.ScaleValueX(30);
                };


                if (IsInGame)
                {
                    g.DrawImage(ZklResources.boom, DpiMeasurement.ScaleValueX(10), DpiMeasurement.ScaleValueY(10), DpiMeasurement.ScaleValueX(50), DpiMeasurement.ScaleValueY(50));
                }
                if (Battle.IsOfficial() && Battle.Founder.IsSpringieManaged)
                {
                    g.DrawImage(ZklResources.star, DpiMeasurement.ScaleValueX(48), DpiMeasurement.ScaleValueY(8), DpiMeasurement.ScaleValueX(15), DpiMeasurement.ScaleValueY(15));
                }
                if (Battle.IsPassworded)
                {
                    drawIcon(ZklResources._lock);
                }
                if (Battle.IsReplay)
                {
                    drawIcon(ZklResources.replay);
                }
                if (Battle.Rank > 0)
                {
                    drawIcon(Images.GetRank(Battle.Rank));
                }
                if (Battle.IsLocked)
                {
                    var s = DpiMeasurement.ScaleValueX(20);
                    g.DrawImage(ZklResources.redlight, DpiMeasurement.ScaleValueX(minimapSize + 3) - s, DpiMeasurement.ScaleValueY(minimapSize + 3) - s, s, s);
                }

                g.DrawImage(ZklResources.border, 0, 0, DpiMeasurement.ScaleValueX(70), DpiMeasurement.ScaleValueY(70));
            }
        }
示例#9
0
 void PainOpenBattleButton(Graphics g, ref int x, ref int y, int scaledMapCellWidth, int scaledIconWidth)
 {
     g.DrawImage(ZklResources.border,
                 x + DpiMeasurement.ScaleValueX(3),
                 y + DpiMeasurement.ScaleValueY(3),
                 DpiMeasurement.ScaleValueX(70),
                 DpiMeasurement.ScaleValueY(70));
     g.DrawString("Open a new battle.", BattleIcon.TitleFont, BattleIcon.TextBrush, x + scaledMapCellWidth, y + DpiMeasurement.ScaleValueY(3));
     openBattlePosition = new Point(x, y);
     x += scaledIconWidth;
 }
示例#10
0
        protected override void OnPaint(PaintEventArgs pe)
        {
            try
            {
                DpiMeasurement.DpiXYMeasurement();
                int scaledIconWidth    = DpiMeasurement.ScaleValueX(BattleIcon.Width);
                int scaledIconHeight   = DpiMeasurement.ScaleValueY(BattleIcon.Height);
                int scaledMapCellWidth = DpiMeasurement.ScaleValueX(BattleIcon.MapCellSize.Width);

                base.OnPaint(pe);
                var g = pe.Graphics;
                g.TranslateTransform(AutoScrollPosition.X, AutoScrollPosition.Y);
                battleIconPositions.Clear();
                var x = 0;
                var y = 0;


                g.DrawImage(ZklResources.border, x + DpiMeasurement.ScaleValueX(3), DpiMeasurement.ScaleValueY(3), DpiMeasurement.ScaleValueX(70), DpiMeasurement.ScaleValueY(70));
                g.DrawString("Open a new battle.", BattleIcon.TitleFont, BattleIcon.TextBrush, x + scaledMapCellWidth, y + DpiMeasurement.ScaleValueY(3));

                x += scaledIconWidth;

                foreach (var t in view)
                {
                    if (x + scaledIconWidth > Width)
                    {
                        x  = 0;
                        y += scaledIconHeight;
                    }
                    battleIconPositions[t] = new Point(x, y);
                    if (g.VisibleClipBounds.IntersectsWith(new RectangleF(x, y, scaledIconWidth, scaledIconHeight)))
                    {
                        g.DrawImageUnscaled(t.Image, x, y);
                    }
                    x += scaledIconWidth;
                }

                if (view.Count < model.Count())
                {
                    if (x + scaledIconWidth > Width)
                    {
                        x  = 0;
                        y += scaledIconHeight;
                    }
                }

                AutoScrollMinSize = new Size(0, y + scaledIconHeight);
            }
            catch (Exception e)
            {
                Trace.WriteLine("Error in drawing battles: " + e);
            }
        }
示例#11
0
        private void panel1_Resize(object sender, EventArgs e)
        {
            if (Program.MainWindow != null && Program.MainWindow.WindowState == FormWindowState.Minimized)
            {
                return;
            }
            //prevent splitter from being dragged when window resize
            DpiMeasurement.DpiXYMeasurement(this);               //this measurement use cached value. It won't cost anything if another measurement was already done in other control element
            int splitDistance = DpiMeasurement.ScaleValueY(203); //DpiMeasurement is a static class stored in ZeroKLobby\Util.cs

            splitDistance = Math.Min(splitDistance, splitContainerAtMid.Width - splitContainerAtMid.Panel2MinSize);
            splitContainerAtMid.SplitterDistance = splitDistance; //must obey minimum size constraint
        }
示例#12
0
 protected override void OnMeasureItem(MeasureItemEventArgs e)
 {
     base.OnMeasureItem(e);
     DpiMeasurement.DpiXYMeasurement(this);
     if (DesignMode)
     {
         return;
     }
     if (e.Index > -1 && e.Index < base.Items.Count)
     {
         e.ItemHeight = DpiMeasurement.ScaleValueY(((PlayerListItem)base.Items[e.Index]).Height); //GetItemRectangle() will measure the size of item (for drawing). We return a custom Height defined in PlayerListItems.cs
     }
 }
示例#13
0
        void RenderPlayers()
        {
            var currentPlayers = Battle.NonSpectatorCount;
            var maxPlayers     = Battle.MaxPlayers;

            var friends = 0;
            var admins  = 0;
            var mes     = 0; // whether i'm in the battle (can be 0 or 1)

            foreach (var user in Battle.Users)
            {
                if (user.Name == Program.TasClient.UserName)
                {
                    mes++;
                }
                if (Program.FriendManager.Friends.Contains(user.Name))
                {
                    friends++;
                }
                else if (user.LobbyUser.IsAdmin || user.LobbyUser.IsZeroKAdmin)
                {
                    admins++;
                }
            }

            // make sure there aren't more little dudes than non-specs in a battle
            while (admins != 0 && friends + admins + mes > Battle.NonSpectatorCount)
            {
                admins--;
            }
            while (friends != 0 && friends + mes > Battle.NonSpectatorCount)
            {
                friends--;
            }

            if (playersBoxImage != null)
            {
                playersBoxImage.Dispose();
            }

            playersBoxImage = DudeRenderer.GetImage(currentPlayers - friends - admins - mes,
                                                    friends,
                                                    admins,
                                                    0,
                                                    maxPlayers,
                                                    mes > 0,
                                                    DpiMeasurement.ScaleValueX(playersBoxSize.Width),
                                                    DpiMeasurement.ScaleValueY(playersBoxSize.Height));
        }
示例#14
0
        public PlayerListBox()
        {
            DrawMode       = DrawMode.OwnerDrawVariable;
            this.BackColor = Color.DimGray;
            SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.UserPaint, true);
            realItems = new ObservableCollection <PlayerListItem>();
            realItems.CollectionChanged += RealItemsOnCollectionChanged;

            timer = new Timer()
            {
                Interval = stagingMs,
            };
            timer.Tick += (sender, args) =>
            {
                try {
                    BeginUpdate();
                    int currentScroll = base.TopIndex;

                    base.Items.Clear();
                    base.Items.AddRange(realItems.ToArray());

                    base.TopIndex = currentScroll;
                    EndUpdate();

                    timer.Stop();
                } catch (Exception ex) {
                    Trace.TraceError("Error updating list: {0}", ex);
                }
            };
            IntegralHeight = false;         //so that the playerlistBox completely fill the edge (not snap to some item size)

            if (Environment.OSVersion.Platform == PlatformID.Unix)
            {
                //dummy item to fix Mono scrollbar always cutout last 3 line
                //https://bugzilla.novell.com/show_bug.cgi?id=475581
                DpiMeasurement.DpiXYMeasurement(this);
                int numberOfDummy = (int)(DpiMeasurement.scaleUpRatioY * 3 + 0.9d); //similar to Math.Ceiling(scaleUpRatioY*3)

                for (int i = 0; i < numberOfDummy; i++)
                {
                    PlayerListItem dummyItem = new PlayerListItem()
                    {
                        isOfflineMode = true, isDummy = true, Height = 1, UserName = "******" + i.ToString()
                    };                                                                                                                                             //sorted to be last
                    realItems.Add(dummyItem);
                }
            }
        }
示例#15
0
        private void EnterLocalReplay_Event(object sender, EventArgs e)
        {
            InitializeComponent();

            this.OnResize(new EventArgs());             //to fix control not filling the whole window at start
            Paint -= EnterLocalReplay_Event;

            DpiMeasurement.DpiXYMeasurement(this);
            charWidth = DpiMeasurement.ScaleValueX(listBoxDemoList.Font.SizeInPoints);

            ZkData.Utils.StartAsync(ScanDemoFiles);

            listBoxDemoList.SelectedIndexChanged += listBoxDemoList_SelectedIndexChanged;
            listBoxDemoList.KeyDown += listBoxDemoList_KeyDown;
            listBoxDemoList.KeyUp   += listBoxDemoList_KeyUp;
        }
示例#16
0
 private void detailBox_VisibleChanged(object sender, EventArgs e)
 {
     if (DesignMode)
     {
         return;
     }
     if (!detailBox.Visible)
     {
         DpiMeasurement.DpiXYMeasurement();
         Size = new Size(DpiMeasurement.ScaleValueX(formWidth), DpiMeasurement.ScaleValueY(formHeight - detailHeight));
     }
     else
     {
         DpiMeasurement.DpiXYMeasurement();
         Size = new Size(DpiMeasurement.ScaleValueX(formWidth), DpiMeasurement.ScaleValueY(formHeight));
     }
 }
示例#17
0
 Battle GetBattle(int x, int y)
 {
     x -= AutoScrollPosition.X;
     y -= AutoScrollPosition.Y;
     foreach (var kvp in battleIconPositions)
     {
         var battleIcon = kvp.Key;
         var position   = kvp.Value;
         DpiMeasurement.DpiXYMeasurement(this);
         var battleIconRect = new Rectangle(position.X, position.Y, DpiMeasurement.ScaleValueX(BattleIcon.Width), DpiMeasurement.ScaleValueY(BattleIcon.Height));
         if (battleIconRect.Contains(x, y) && battleIcon.HitTest(x - position.X, y - position.Y))
         {
             return(battleIcon.Battle);
         }
     }
     return(null);
 }
示例#18
0
 void BattleIconManager_BattleChanged(object sender, EventArgs <BattleIcon> e)
 {
     if (e.Data.Battle == Program.TasClient.MyBattle)
     {
         DpiMeasurement.DpiXYMeasurement(this);
         int scaledIconHeight = DpiMeasurement.ScaleValueY(BattleIcon.Height);
         int scaledIconWidth  = DpiMeasurement.ScaleValueX(BattleIcon.Width);
         if (gameBox.Image == null)
         {
             gameBox.Image = new Bitmap(scaledIconWidth, scaledIconHeight);
         }
         using (var g = Graphics.FromImage(gameBox.Image)) {
             g.FillRectangle(Brushes.White, 0, 0, scaledIconWidth, scaledIconHeight);
             g.DrawImageUnscaled(e.Data.Image, 0, 0);
             gameBox.Invalidate();
         }
     }
 }
示例#19
0
        public NotifyBarContainer(INotifyBar barContent)
        {
            SuspendLayout(); //suspend layout until all bar element is finish set up
            BarContent = barContent;
            InitializeComponent();
            btnDetail.Click += detail_Click;
            btnStop.Click   += stop_Click;
            btnStop.Image    = ZklResources.Remove;
            var control = barContent.GetControl();

            //Note: control-element is already DPI-scaled and might be DPI-scaled again, and we dont need more scaling
            //Set size to control-element's maximum size (if defined in Program.cs). If not defined then use current height (hopefully the control-element is only used once)
            Height  = (control.MaximumSize.Height > 0 ? control.MaximumSize.Height : control.Height) + DpiMeasurement.ScaleValueY(28);
            lbTitle = new Label()
            {
                Font = new Font("Microsoft Sans Serif", 13.25F, FontStyle.Bold), ForeColor = Color.DarkCyan, AutoSize = true
            };
            tableLayoutPanel1.Controls.Add(lbTitle, 1, 0);

            tableLayoutPanel1.Controls.Add(control, 1, 1);
            control.Dock = DockStyle.Fill;
            Dock         = DockStyle.Top;
            BarContent.AddedToContainer(this);
            ResumeLayout();
        }
示例#20
0
        void MakeMinimap()
        {
            if (resizedMinimap == null)
            {
                return;                         // wait, map is not downloaded
            }
            if (finishedMinimap != null)
            {
                finishedMinimap.Dispose();
            }
            finishedMinimap = new Bitmap(DpiMeasurement.ScaleValueX(ZklResources.border.Width), DpiMeasurement.ScaleValueY(ZklResources.border.Height));

            using (Graphics g = Graphics.FromImage(finishedMinimap))
            {
                g.DrawImage(resizedMinimap, DpiMeasurement.ScaleValueX(6), DpiMeasurement.ScaleValueY(5));
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                int            x        = DpiMeasurement.ScaleValueX(10);
                int            y        = DpiMeasurement.ScaleValueY(minimapSize - 20);
                Action <Image> drawIcon = image =>
                {
                    g.DrawImage(image, x, y, DpiMeasurement.ScaleValueX(20), DpiMeasurement.ScaleValueY(20));
                    x += DpiMeasurement.ScaleValueX(30);
                };

                if (IsInGame)
                {
                    g.DrawImage(ZklResources.boom,
                                DpiMeasurement.ScaleValueX(10),
                                DpiMeasurement.ScaleValueY(10),
                                DpiMeasurement.ScaleValueX(50),
                                DpiMeasurement.ScaleValueY(50));
                }
                if (Battle.IsOfficial() && Battle.IsSpringieManaged && !Battle.IsQueue)
                {
                    g.DrawImage(ZklResources.star,
                                DpiMeasurement.ScaleValueX(48),
                                DpiMeasurement.ScaleValueY(8),
                                DpiMeasurement.ScaleValueX(15),
                                DpiMeasurement.ScaleValueY(15));
                }
                if (Battle.IsOfficial() && Battle.IsQueue)
                {
                    g.DrawStringWithOutline(Battle.QueueName.Replace(' ', '\n'),
                                            QueueFont,
                                            QueueBrush,
                                            QueueBrushOutline,
                                            new Rectangle(4, 4, DpiMeasurement.ScaleValueX(62), DpiMeasurement.ScaleValueY(62)),
                                            new StringFormat()
                    {
                        Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center
                    },
                                            3);
                }

                if (Battle.IsPassworded)
                {
                    drawIcon(ZklResources._lock);
                }

                g.DrawImage(ZklResources.border, 0, 0, DpiMeasurement.ScaleValueX(70), DpiMeasurement.ScaleValueY(70));
            }
        }
示例#21
0
        protected override void OnPaint(PaintEventArgs pe)
        {
            try
            {
                DpiMeasurement.DpiXYMeasurement();
                int scaledIconWidth    = DpiMeasurement.ScaleValueX(BattleIcon.Width);
                int scaledIconHeight   = DpiMeasurement.ScaleValueY(BattleIcon.Height);
                int scaledMapCellWidth = DpiMeasurement.ScaleValueX(BattleIcon.MapCellSize.Width);

                base.OnPaint(pe);
                Graphics g = pe.Graphics;
                g.TranslateTransform(AutoScrollPosition.X, AutoScrollPosition.Y);
                battleIconPositions.Clear();
                int x = 0;
                int y = 0;


                if (view.Any(b => b.Battle.IsQueue && !b.IsInGame))
                {
                    PaintDivider(g, ref x, ref y, "Match maker queues");
                    foreach (BattleIcon t in view.Where(b => b.Battle.IsQueue && !b.IsInGame))
                    {
                        if (x + scaledIconWidth > Width)
                        {
                            x  = 0;
                            y += scaledIconHeight;
                        }
                        PainBattle(t, g, ref x, ref y, scaledIconWidth, scaledIconHeight);
                    }

                    x  = 0;
                    y += scaledIconHeight;
                }

                PaintDivider(g, ref x, ref y, "Custom battles");
                PainOpenBattleButton(g, ref x, ref y, scaledMapCellWidth, scaledIconWidth);

                foreach (BattleIcon t in view.Where(b => !b.Battle.IsQueue && !b.IsInGame))
                {
                    if (x + scaledIconWidth > Width)
                    {
                        x  = 0;
                        y += scaledIconHeight;
                    }
                    PainBattle(t, g, ref x, ref y, scaledIconWidth, scaledIconHeight);
                }
                x  = 0;
                y += scaledIconHeight;

                PaintDivider(g, ref x, ref y, "Games in progress");

                foreach (BattleIcon t in view.Where(b => b.IsInGame))
                {
                    if (x + scaledIconWidth > Width)
                    {
                        x  = 0;
                        y += scaledIconHeight;
                    }
                    PainBattle(t, g, ref x, ref y, scaledIconWidth, scaledIconHeight);
                }


                AutoScrollMinSize = new Size(0, y + scaledIconHeight);
            }
            catch (Exception e)
            {
                Trace.WriteLine("Error in drawing battles: " + e);
            }
        }
示例#22
0
        /// <summary>
        /// singleton, dont use, internal for designer
        /// </summary>
        internal BattleBar()
        {
            InitializeComponent();

            picoChat.ChatBackgroundColor = TextColor.background; //same color as Program.Conf.BgColor
            picoChat.IRCForeColor        = 14;                   //mirc grey. Unknown use

            picoChat.DefaultTooltip = "Last lines from room chat, click to enter full screen chat";

            client = Program.TasClient;
            spring = new Spring(Program.SpringPaths);


            try
            {
                // silly way to create speech and voice engines on runtime - needed due to mono crash
                speech = Activator.CreateInstance(Type.GetType("ZeroKLobby.ChatToSpeech"), spring);
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("Failed to init VoiceCommands:{0}", ex.Message);
            }

            spring.SpringExited += (s, e) =>
            {
                client.ChangeMyUserStatus(isInGame: false);

                if (e.Data)
                {
                    Program.MainWindow.InvokeFunc(() =>
                    {
                        var defaultButton = MessageBoxDefaultButton.Button2;
                        var icon          = MessageBoxIcon.None;
                        if (
                            MessageBox.Show("Do you want me to set Low details?\n(will effect: lups.cfg and springsettings.cfg)\n\nIf you wish to file a bug report, please include a copy of infolog.txt in your game data folder (accessible through Settings).\nUpload it to a text sharing site such as pastebin.com.",
                                            "Spring engine has crashed, update your video and audio drivers please!",
                                            MessageBoxButtons.YesNo,
                                            icon,
                                            defaultButton) == DialogResult.Yes)
                        {
                            Program.Conf.UseSafeMode = true;
                            Program.EngineConfigurator.Configure(true, 0);
                        }
                    });
                }
            };

            spring.SpringStarted += (s, e) => { client.ChangeMyUserStatus(isInGame: true); };

            client.Rang += (s, e) =>
            {
                if (e.User == GlobalConst.NightwatchName)
                {
                    //Nightwatch RING is from UserController.cs (website code)
                    MainWindow.Instance.NotifyUser("chat/zkadmin", "New report arrive at zkadmin channel", true, true);
                }
                else
                {
                    MainWindow.Instance.NotifyUser("chat/battle", "Someone demands your attention in battle room!", true, true);
                    AutoRespond();
                }
            };

            client.BattleJoined += (s, e) =>
            {
                if (!isVisible)
                {
                    ManualBattleStarted();
                }
                if (IsHostGameRunning())
                {
                    barContainer.btnDetail.Text = "Rejoin";
                }
                else
                {
                    barContainer.btnDetail.Text = "Start";
                }
                //client.ChangeMyUserStatus(false, false);
                var battle = client.MyBattle;
                lastBattleFounder = battle.Founder.Name;

                if (battle.Founder.Name.StartsWith("PlanetWars") || battle.Founder.Name.StartsWith("Zk"))
                {
                    ChangeDesiredSpectatorState(false);                                                                                           // TODO pw unpsec hack, remove later
                }
                if (battle.IsQueue)
                {
                    barContainer.Title             = string.Format("Joined {0} Quick Match Queue", battle.QueueName);
                    barContainer.TitleTooltip      = "Please await people, game will start automatically";
                    lbQueue.Visible                = true;
                    radioPlay.Visible              = false;
                    radioSpec.Visible              = false;
                    barContainer.btnDetail.Visible = false;
                }
                else
                {
                    barContainer.Title             = string.Format("Joined battle room hosted by {0}", battle.Founder.Name);
                    barContainer.TitleTooltip      = "Use button on the left side to start a game";
                    lbQueue.Visible                = false;
                    radioPlay.Visible              = true;
                    radioSpec.Visible              = true;
                    barContainer.btnDetail.Visible = true;
                }

                Program.Downloader.GetResource(DownloadType.MAP, battle.MapName);
                Program.Downloader.GetResource(DownloadType.MOD, battle.ModName);
                engineVersionNeeded = battle.EngineVersion;
                if (engineVersionNeeded != Program.SpringPaths.SpringVersion)
                {
                    Program.Downloader.GetAndSwitchEngine(engineVersionNeeded);
                }
                else
                {
                    engineVersionNeeded = null;
                }

                if (gameBox.Image != null)
                {
                    gameBox.Image.Dispose();
                }
                DpiMeasurement.DpiXYMeasurement(this);
                int scaledIconHeight = DpiMeasurement.ScaleValueY(BattleIcon.Height);
                int scaledIconWidth  = DpiMeasurement.ScaleValueX(BattleIcon.Width);
                gameBox.Image = new Bitmap(scaledIconWidth, scaledIconHeight);
                using (var g = Graphics.FromImage(gameBox.Image))
                {
                    g.FillRectangle(Brushes.White, 0, 0, scaledIconWidth, scaledIconHeight);
                    var bi = Program.BattleIconManager.GetBattleIcon(battle.BattleID);
                    g.DrawImageUnscaled(bi.Image, 0, 0);
                }
                gameBox.Invalidate();

                RefreshTooltip();


                var alliance =
                    Enumerable.Range(0, TasClient.MaxAlliances - 1)
                    .FirstOrDefault(allyTeam => !battle.Users.Values.Any(user => user.AllyNumber == allyTeam));
                var team = battle.GetFreeTeamID(client.UserName);

                client.ChangeMyBattleStatus(desiredSpectatorState, HasAllResources() ? SyncStatuses.Synced : SyncStatuses.Unsynced, alliance, team);
            };


            client.MyBattleMapChanged += (s, e) =>
            {
                if (client.MyBattle != null && !Program.SpringScanner.HasResource(client.MyBattle.MapName))
                {
                    client.ChangeMyBattleStatus(syncStatus: SyncStatuses.Unsynced);
                    Program.Downloader.GetResource(DownloadType.MAP, client.MyBattle.MapName);
                }
                RefreshTooltip();
            };

            client.MyBattleHostExited += (s, e) => { barContainer.btnDetail.Text = "Start"; };

            client.MyBattleStarted += (s, e) =>
            {
                try
                {
                    barContainer.btnDetail.Text = "Rejoin";
                    if (client.MyBattleStatus.SyncStatus == SyncStatuses.Synced)
                    {
                        if (Utils.VerifySpringInstalled())
                        {
                            if (spring.IsRunning)
                            {
                                spring.ExitGame();
                            }
                            lastScript = spring.StartGame(client, null, null, null, Program.Conf.UseSafeMode, client.MyBattleStatus.IsSpectator ? Program.Conf.UseMtEngine : false);     //use MT tag when in spectator slot
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error starting spring: " + ex.Message);
                }
                RefreshTooltip();
            };

            client.BattleMyUserStatusChanged += (s, e) =>
            {
                if (client.MyBattleStatus != null)
                {
                    barContainer.btnDetail.Enabled = client.MyBattleStatus.SyncStatus == SyncStatuses.Synced;

                    if (client.MyBattleStatus.IsSpectator && radioPlay.Checked)
                    {
                        ChangeGuiSpectatorWithoutEvent(false);                                                             // i was spectated
                    }
                    if (!client.MyBattleStatus.IsSpectator && radioSpec.Checked)
                    {
                        ChangeGuiSpectatorWithoutEvent(true);                                                              //i was unspectated
                    }
                }
            };

            client.BattleClosed += (s, e) =>
            {
                barContainer.btnDetail.Text = "Start";
                if (gameBox.Image != null)
                {
                    gameBox.Image.Dispose();
                }
                gameBox.Image = null;
                RefreshTooltip();
                Stop();
            };

            client.MyBattleRemoved += (s, e) =>
            {
                var t        = new Timer();
                var tryCount = 0;
                t.Interval = 1000;
                t.Tick    += (s2, e2) =>
                {
                    tryCount++;
                    if (tryCount > 15)
                    {
                        t.Stop();
                        t.Dispose();
                    }
                    else if (client.IsLoggedIn && client.MyBattle == null)
                    {
                        var bat = client.ExistingBattles.Values.FirstOrDefault(x => x.Founder.Name == lastBattleFounder && !x.IsPassworded);
                        if (bat != null)
                        {
                            ActionHandler.JoinBattle(bat.BattleID, null);
                            t.Stop();
                            t.Dispose();
                        }
                    }
                };
                t.Start();
            };

            client.ConnectionLost += (s, e) =>
            {
                if (gameBox.Image != null)
                {
                    gameBox.Image.Dispose();
                }
                gameBox.Image = null;
                RefreshTooltip();
                Stop();
            };


            // process special queue message to display in label
            client.Said += (s, e) =>
            {
                if (e.Place == SayPlace.Battle && client.MyBattle != null && client.MyBattle.Founder.Name == e.UserName && e.Text.StartsWith("Queue"))
                {
                    var t = e.Text.Substring(6);
                    queueLabelFormatter = Regex.Replace(t,
                                                        "([0-9]+)s",
                                                        m =>
                    {
                        var queueSeconds = int.Parse(m.Groups[1].Value);
                        queueTarget      = DateTime.Now.AddSeconds(queueSeconds);
                        return("{0}s");
                    });
                    lbQueue.Text = string.Format(queueLabelFormatter, Math.Round(queueTarget.Subtract(DateTime.Now).TotalSeconds));
                }
            };


            timer.Tick += (s, e) =>
            {
                if (client.IsLoggedIn)
                {
                    if (WindowsApi.IdleTime.TotalMinutes > Program.Conf.IdleTime)
                    {
                        if (!client.MyUser.IsAway)
                        {
                            client.ChangeMyUserStatus(isAway: true);
                        }
                    }
                    else
                    {
                        if (client.MyUser.IsAway)
                        {
                            client.ChangeMyUserStatus(isAway: false);
                        }
                    }
                    CheckMyBattle();
                }
                if (client.MyBattle != null && client.MyBattle.IsQueue)
                {
                    lbQueue.Text = string.Format(queueLabelFormatter, Math.Round(queueTarget.Subtract(DateTime.Now).TotalSeconds));
                }
            };
            timer.Interval = 1000;
            timer.Start();

            Program.BattleIconManager.BattleChanged += BattleIconManager_BattleChanged;

            //picoChat.Font = new Font(Program.Conf.ChatFont.FontFamily, Program.Conf.ChatFont.Size*0.8f);
            picoChat.ShowHistory   = false;
            picoChat.ShowJoinLeave = false;
            //picoChat.HideScroll = true;

            BattleChatControl.BattleLine += (s, e) => picoChat.AddLine(e.Data);

            picoChat.MouseClick += (s, e) => NavigationControl.Instance.Path = "chat/battle";
        }
示例#23
0
        /// <summary>
        /// singleton, dont use, internal for designer
        /// </summary>
        internal BattleBar()
        {
            InitializeComponent();

            picoChat.ChatBackgroundColor = TextColor.background; //same color as Program.Conf.BgColor
            picoChat.IRCForeColor        = 14;                   //mirc grey. Unknown use

            Program.ToolTip.SetText(cbSide, "Choose the faction you wish to play.");

            client = Program.TasClient;
            spring = new Spring(Program.SpringPaths);

            try {
                // silly way to create speech and voice engines on runtime - needed due to mono crash
                speech = Activator.CreateInstance(Type.GetType("ZeroKLobby.ChatToSpeech"), spring);
                if (Program.Conf.EnableVoiceCommands)
                {
                    voice = Activator.CreateInstance(Type.GetType("ZeroKLobby.VoiceCommand.VoiceCommandEngine"), client, spring);
                }
            } catch (Exception ex) {
                Trace.TraceWarning("Failed to init VoiceCommands:{0}", ex.Message);
            }

            spring.SpringExited += (s, e) =>
            {
                client.ChangeMyUserStatus(isInGame: false);
                client.ChangeMyBattleStatus(ready: true);

                if (e.Data)
                {
                    Program.MainWindow.InvokeFunc(() =>
                    {
                        var defaultButton = MessageBoxDefaultButton.Button2;
                        var icon          = MessageBoxIcon.None;
                        if (
                            MessageBox.Show("Do you want me to set Low details?\n(will effect: lups.cfg and springsettings.cfg)\n\nIf you wish to file a bug report, please include a copy of infolog.txt in your game data folder (accessible through Settings).\nUpload it to a text sharing site such as pastebin.com.",
                                            "Spring engine has crashed, update your video and audio drivers please!",
                                            MessageBoxButtons.YesNo,
                                            icon,
                                            defaultButton) == DialogResult.Yes)
                        {
                            Program.Conf.UseSafeMode = true;
                            Program.EngineConfigurator.Configure(true, 0);
                        }
                    });
                }
            };

            spring.SpringStarted += (s, e) => { client.ChangeMyUserStatus(isInGame: true); };

            client.Rang += (s, e) =>
            {
                MainWindow.Instance.NotifyUser("chat/battle", "Someone demands your attention in battle room!", true, true);
                AutoRespond();
            };

            client.BattleJoined += (s, e) =>
            {
                if (!isVisible)
                {
                    ManualBattleStarted();
                }
                if (IsHostGameRunning())
                {
                    barContainer.btnDetail.Text = "Rejoin";
                }
                else
                {
                    barContainer.btnDetail.Text = "Start";
                }
                //client.ChangeMyUserStatus(false, false);
                var battle = client.MyBattle;
                lastBattleFounder = battle.Founder.Name;

                if (battle.Founder.Name.StartsWith("PlanetWars"))
                {
                    ChangeDesiredSpectatorState(false);                                                   // TODO pw unpsec hack, remove later
                }
                Program.SpringScanner.MetaData.GetModAsync(battle.ModName,
                                                           (mod) =>
                {
                    if (!Program.CloseOnNext)
                    {
                        Program.MainWindow.InvokeFunc(() =>
                        {
                            var previousSide = cbSide.SelectedItem != null
                                                                                                          ? cbSide.SelectedItem.ToString()
                                                                                                          : null;
                            cbSide.Items.Clear();
                            var cnt = 0;
                            foreach (var side in mod.Sides)
                            {
                                cbSide.Items.Add(new SideItem(side, mod.SideIcons[cnt++]));
                            }
                            var pickedItem =
                                cbSide.Items.OfType <SideItem>()
                                .FirstOrDefault(x => x.Side == previousSide);

                            suppressSideChangeEvent = true;
                            cbSide.Visible          = mod.Sides.Length > 1;
                            if (cbSide.Visible)
                            {
                                if (pickedItem != null)
                                {
                                    cbSide.SelectedItem = pickedItem;
                                }
                                else
                                {
                                    cbSide.SelectedIndex = random.Next(cbSide.Items.Count);
                                }
                            }
                            suppressSideChangeEvent = false;
                        });
                    }
                },
                                                           (ex) => { },
                                                           Program.SpringPaths.SpringVersion);

                Program.Downloader.GetResource(DownloadType.MAP, battle.MapName);
                Program.Downloader.GetResource(DownloadType.MOD, battle.ModName);
                engineVersionNeeded = battle.EngineVersion;
                if (engineVersionNeeded != Program.SpringPaths.SpringVersion)
                {
                    Program.Downloader.GetAndSwitchEngine(engineVersionNeeded);
                }
                else
                {
                    engineVersionNeeded = null;
                }

                if (battle != previousBattle)
                {
                    previousBattle = battle;
                    if (gameBox.Image != null)
                    {
                        gameBox.Image.Dispose();
                    }
                    DpiMeasurement.DpiXYMeasurement(this);
                    int scaledIconHeight = DpiMeasurement.ScaleValueY(BattleIcon.Height);
                    int scaledIconWidth  = DpiMeasurement.ScaleValueX(BattleIcon.Width);
                    gameBox.Image = new Bitmap(scaledIconWidth, scaledIconHeight);
                    using (var g = Graphics.FromImage(gameBox.Image)) {
                        g.FillRectangle(Brushes.White, 0, 0, scaledIconWidth, scaledIconHeight);
                        var bi = Program.BattleIconManager.GetBattleIcon(battle.BattleID);
                        g.DrawImageUnscaled(bi.Image, 0, 0);
                    }
                    gameBox.Invalidate();
                }
                RefreshTooltip();
            };

            cbSide.DrawMode  = DrawMode.OwnerDrawFixed;
            cbSide.DrawItem += cbSide_DrawItem;

            client.MyBattleMapChanged += (s, e) =>
            {
                if (client.MyBattle != null && !Program.SpringScanner.HasResource(client.MyBattle.MapName))
                {
                    client.ChangeMyBattleStatus(syncStatus: SyncStatuses.Unsynced);
                    Program.Downloader.GetResource(DownloadType.MAP, client.MyBattle.MapName);
                }
                RefreshTooltip();
            };

            client.MyBattleHostExited += (s, e) => { barContainer.btnDetail.Text = "Start"; };

            client.RequestBattleStatus += (s, e) =>
            {
                var battle = client.MyBattle;

                var alliance =
                    Enumerable.Range(0, TasClient.MaxAlliances - 1)
                    .FirstOrDefault(allyTeam => !battle.Users.Any(user => user.AllyNumber == allyTeam));
                var team = battle.GetFreeTeamID(client.UserName);

                /*				if (battle)
                 * {
                 *          var b = tas.MyBattle;
                 * return hostedMod.MissionSlots.Where(x => x.IsHuman).OrderByDescending(x => x.IsRequired).Where(
                 * x => !b.Users.Any(y => y.AllyNumber == x.AllyID && y.TeamNumber == x.TeamID && !y.IsSpectator));
                 *
                 * var slot = GetFreeSlots().FirstOrDefault();
                 * if (slot != null)
                 * {
                 * tas.ForceAlly(u.Name, slot.AllyID);
                 * tas.ForceTeam(u.Name, slot.TeamID);
                 * }
                 * else tas.ForceSpectator(u.Name);
                 * }*/

                var status = new UserBattleStatus
                {
                    AllyNumber  = alliance,
                    TeamNumber  = team,
                    SyncStatus  = HasAllResources() ? SyncStatuses.Synced : SyncStatuses.Unsynced,
                    IsSpectator = desiredSpectatorState,
                    Side        = cbSide.SelectedIndex >= 0 ? cbSide.SelectedIndex : 0,
                    TeamColor   = Program.Conf.DefaultPlayerColorInt,
                    IsReady     = true,
                };
                client.SendMyBattleStatus(status);
            };

            client.MyBattleStarted += (s, e) =>
            {
                try {
                    barContainer.btnDetail.Text = "Rejoin";
                    if (client.MyBattleStatus.SyncStatus == SyncStatuses.Synced)
                    {
                        if (Utils.VerifySpringInstalled())
                        {
                            if (spring.IsRunning)
                            {
                                spring.ExitGame();
                            }
                            lastScript = spring.StartGame(client, null, null, null, Program.Conf.UseSafeMode, client.MyBattleStatus.IsSpectator?Program.Conf.UseMtEngine:false);     //use MT tag when in spectator slot
                        }
                    }
                } catch (Exception ex) {
                    MessageBox.Show("Error starting spring: " + ex.Message);
                }
                RefreshTooltip();
            };

            client.BattleMyUserStatusChanged += (s, e) =>
            {
                if (client.MyBattleStatus != null)
                {
                    barContainer.btnDetail.Enabled = client.MyBattleStatus.SyncStatus == SyncStatuses.Synced;

                    if (client.MyBattleStatus.IsSpectator && radioPlay.Checked)
                    {
                        ChangeGuiSpectatorWithoutEvent(false);                                                             // i was spectated
                    }
                    if (!client.MyBattleStatus.IsSpectator && radioSpec.Checked)
                    {
                        ChangeGuiSpectatorWithoutEvent(true);                                                              //i was unspectated
                    }
                }
            };

            client.BattleClosed += (s, e) =>
            {
                barContainer.btnDetail.Text = "Start";
                if (gameBox.Image != null)
                {
                    gameBox.Image.Dispose();
                }
                gameBox.Image  = null;
                cbSide.Visible = false;
                RefreshTooltip();
                Stop();
            };

            client.MyBattleEnded += (s, e) =>
            {
                var t        = new Timer();
                var tryCount = 0;
                t.Interval = 1000;
                t.Tick    += (s2, e2) =>
                {
                    tryCount++;
                    if (tryCount > 15)
                    {
                        t.Stop();
                    }
                    else if (client.IsLoggedIn && client.MyBattle == null)
                    {
                        var bat = client.ExistingBattles.Values.FirstOrDefault(x => x.Founder.Name == lastBattleFounder && !x.IsPassworded);
                        if (bat != null)
                        {
                            ActionHandler.JoinBattle(bat.BattleID, null);
                            t.Stop();
                        }
                    }
                };
                t.Start();
            };

            client.ConnectionLost += (s, e) =>
            {
                if (gameBox.Image != null)
                {
                    gameBox.Image.Dispose();
                }
                gameBox.Image  = null;
                cbSide.Visible = false;
                RefreshTooltip();
                Stop();
            };


            timer.Tick += (s, e) =>
            {
                if (client.IsLoggedIn)
                {
                    if (WindowsApi.IdleTime.TotalMinutes > Program.Conf.IdleTime)
                    {
                        client.ChangeMyUserStatus(isAway: true);
                    }
                    else
                    {
                        client.ChangeMyUserStatus(isAway: false);
                    }
                    CheckMyBattle();
                }
            };
            timer.Interval = 2500;
            timer.Start();

            Program.BattleIconManager.BattleChanged += BattleIconManager_BattleChanged;

            //picoChat.Font = new Font(Program.Conf.ChatFont.FontFamily, Program.Conf.ChatFont.Size*0.8f);
            picoChat.ShowHistory   = false;
            picoChat.ShowJoinLeave = false;
            //picoChat.HideScroll = true;

            BattleChatControl.BattleLine += (s, e) => picoChat.AddLine(e.Data);

            picoChat.MouseClick += (s, e) => NavigationControl.Instance.Path = "chat/battle";
        }