Update copyright header. Normalize line endings to LF.

This commit is contained in:
Paul Chote
2011-02-13 10:38:57 +13:00
parent ea5e2c0588
commit 094907c1a9
489 changed files with 43614 additions and 43613 deletions

View File

@@ -1,56 +1,56 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using OpenRA.Network;
using OpenRA.Widgets;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class ConnectionDialogsDelegate : IWidgetDelegate
{
[ObjectCreator.UseCtor]
public ConnectionDialogsDelegate(
[ObjectCreator.Param] Widget widget,
[ObjectCreator.Param] string host,
[ObjectCreator.Param] int port )
{
widget.GetWidget("CONNECTION_BUTTON_ABORT").OnMouseUp = mi => {
widget.GetWidget("CONNECTION_BUTTON_ABORT").Parent.Visible = false;
Game.Disconnect();
return true;
};
widget.GetWidget<LabelWidget>("CONNECTING_DESC").GetText = () =>
"Connecting to {0}:{1}...".F(host, port);
}
}
public class ConnectionFailedDelegate : IWidgetDelegate
{
[ObjectCreator.UseCtor]
public ConnectionFailedDelegate(
[ObjectCreator.Param] Widget widget,
[ObjectCreator.Param] OrderManager orderManager)
{
widget.GetWidget("CONNECTION_BUTTON_CANCEL").OnMouseUp = mi => {
widget.GetWidget("CONNECTION_BUTTON_CANCEL").Parent.Visible = false;
Game.Disconnect();
return true;
};
widget.GetWidget("CONNECTION_BUTTON_RETRY").OnMouseUp = mi => {
Game.JoinServer(orderManager.Host, orderManager.Port);
return true;
};
widget.GetWidget<LabelWidget>("CONNECTION_FAILED_DESC").GetText = () => string.IsNullOrEmpty(orderManager.ServerError) ?
"Could not connect to {0}:{1}".F(orderManager.Host, orderManager.Port) : orderManager.ServerError;
}
}
}
#region Copyright & License Information
/*
* Copyright 2007-2011 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using OpenRA.Network;
using OpenRA.Widgets;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class ConnectionDialogsDelegate : IWidgetDelegate
{
[ObjectCreator.UseCtor]
public ConnectionDialogsDelegate(
[ObjectCreator.Param] Widget widget,
[ObjectCreator.Param] string host,
[ObjectCreator.Param] int port )
{
widget.GetWidget("CONNECTION_BUTTON_ABORT").OnMouseUp = mi => {
widget.GetWidget("CONNECTION_BUTTON_ABORT").Parent.Visible = false;
Game.Disconnect();
return true;
};
widget.GetWidget<LabelWidget>("CONNECTING_DESC").GetText = () =>
"Connecting to {0}:{1}...".F(host, port);
}
}
public class ConnectionFailedDelegate : IWidgetDelegate
{
[ObjectCreator.UseCtor]
public ConnectionFailedDelegate(
[ObjectCreator.Param] Widget widget,
[ObjectCreator.Param] OrderManager orderManager)
{
widget.GetWidget("CONNECTION_BUTTON_CANCEL").OnMouseUp = mi => {
widget.GetWidget("CONNECTION_BUTTON_CANCEL").Parent.Visible = false;
Game.Disconnect();
return true;
};
widget.GetWidget("CONNECTION_BUTTON_RETRY").OnMouseUp = mi => {
Game.JoinServer(orderManager.Host, orderManager.Port);
return true;
};
widget.GetWidget<LabelWidget>("CONNECTION_FAILED_DESC").GetText = () => string.IsNullOrEmpty(orderManager.ServerError) ?
"Could not connect to {0}:{1}".F(orderManager.Host, orderManager.Port) : orderManager.ServerError;
}
}
}

View File

@@ -1,50 +1,50 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using System.Linq;
using System.Net;
using OpenRA.Widgets;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class CreateServerMenuDelegate : IWidgetDelegate
{
[ObjectCreator.UseCtor]
public CreateServerMenuDelegate( [ObjectCreator.Param( "widget" )] Widget cs )
{
var settings = Game.Settings;
cs.GetWidget("BUTTON_CANCEL").OnMouseUp = mi => {
Widget.CloseWindow();
return true;
};
cs.GetWidget("BUTTON_START").OnMouseUp = mi => {
var map = Game.modData.AvailableMaps.FirstOrDefault(m => m.Value.Selectable).Key;
settings.Server.Name = cs.GetWidget<TextFieldWidget>("GAME_TITLE").Text;
settings.Server.ListenPort = int.Parse(cs.GetWidget<TextFieldWidget>("LISTEN_PORT").Text);
settings.Server.ExternalPort = int.Parse(cs.GetWidget<TextFieldWidget>("EXTERNAL_PORT").Text);
settings.Save();
Game.CreateAndJoinServer(settings, map);
return true;
};
cs.GetWidget<TextFieldWidget>("GAME_TITLE").Text = settings.Server.Name;
cs.GetWidget<TextFieldWidget>("LISTEN_PORT").Text = settings.Server.ListenPort.ToString();
cs.GetWidget<TextFieldWidget>("EXTERNAL_PORT").Text = settings.Server.ExternalPort.ToString();
cs.GetWidget<CheckboxWidget>("CHECKBOX_ONLINE").Bind(settings.Server, "AdvertiseOnline");
cs.GetWidget<CheckboxWidget>("CHECKBOX_ONLINE").OnChange += _ => settings.Save();
cs.GetWidget<CheckboxWidget>("CHECKBOX_CHEATS").Bind(settings.Server, "AllowCheats");
cs.GetWidget<CheckboxWidget>("CHECKBOX_CHEATS").OnChange += _ => settings.Save();
}
}
}
#region Copyright & License Information
/*
* Copyright 2007-2011 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System.Linq;
using System.Net;
using OpenRA.Widgets;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class CreateServerMenuDelegate : IWidgetDelegate
{
[ObjectCreator.UseCtor]
public CreateServerMenuDelegate( [ObjectCreator.Param( "widget" )] Widget cs )
{
var settings = Game.Settings;
cs.GetWidget("BUTTON_CANCEL").OnMouseUp = mi => {
Widget.CloseWindow();
return true;
};
cs.GetWidget("BUTTON_START").OnMouseUp = mi => {
var map = Game.modData.AvailableMaps.FirstOrDefault(m => m.Value.Selectable).Key;
settings.Server.Name = cs.GetWidget<TextFieldWidget>("GAME_TITLE").Text;
settings.Server.ListenPort = int.Parse(cs.GetWidget<TextFieldWidget>("LISTEN_PORT").Text);
settings.Server.ExternalPort = int.Parse(cs.GetWidget<TextFieldWidget>("EXTERNAL_PORT").Text);
settings.Save();
Game.CreateAndJoinServer(settings, map);
return true;
};
cs.GetWidget<TextFieldWidget>("GAME_TITLE").Text = settings.Server.Name;
cs.GetWidget<TextFieldWidget>("LISTEN_PORT").Text = settings.Server.ListenPort.ToString();
cs.GetWidget<TextFieldWidget>("EXTERNAL_PORT").Text = settings.Server.ExternalPort.ToString();
cs.GetWidget<CheckboxWidget>("CHECKBOX_ONLINE").Bind(settings.Server, "AdvertiseOnline");
cs.GetWidget<CheckboxWidget>("CHECKBOX_ONLINE").OnChange += _ => settings.Save();
cs.GetWidget<CheckboxWidget>("CHECKBOX_CHEATS").Bind(settings.Server, "AllowCheats");
cs.GetWidget<CheckboxWidget>("CHECKBOX_CHEATS").OnChange += _ => settings.Save();
}
}
}

View File

@@ -1,145 +1,145 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using OpenRA.Traits;
using OpenRA.Widgets;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class DiplomacyDelegate : IWidgetDelegate
{
static List<Widget> controls = new List<Widget>();
int validPlayers = 0;
#region Copyright & License Information
/*
* Copyright 2007-2011 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using OpenRA.Traits;
using OpenRA.Widgets;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class DiplomacyDelegate : IWidgetDelegate
{
static List<Widget> controls = new List<Widget>();
int validPlayers = 0;
readonly World world;
[ObjectCreator.UseCtor]
public DiplomacyDelegate( [ObjectCreator.Param] World world )
{
{
this.world = world;
var root = Widget.RootWidget.GetWidget("INGAME_ROOT");
var diplomacyBG = root.GetWidget("DIPLOMACY_BG");
var diplomacy = root.GetWidget("INGAME_DIPLOMACY_BUTTON");
diplomacy.OnMouseUp = mi =>
{
diplomacyBG.Visible = !diplomacyBG.Visible;
if (diplomacyBG.IsVisible())
LayoutDialog(diplomacyBG);
return true;
};
Game.AfterGameStart += _ => validPlayers = world.players.Values.Where(a => a != world.LocalPlayer && !a.NonCombatant).Count();
diplomacy.IsVisible = () => (validPlayers > 0);
}
void LayoutDialog(Widget bg)
{
bg.Children.RemoveAll(w => controls.Contains(w));
controls.Clear();
var y = 50;
var margin = 20;
var labelWidth = (bg.Bounds.Width - 3 * margin) / 3;
var ts = new LabelWidget
{
Bold = true,
Bounds = new Rectangle(margin + labelWidth + 10, y, labelWidth, 25),
Text = "Their Stance",
Align = LabelWidget.TextAlign.Left,
};
bg.AddChild(ts);
controls.Add(ts);
var ms = new LabelWidget
{
Bold = true,
Bounds = new Rectangle(margin + 2 * labelWidth + 20, y, labelWidth, 25),
Text = "My Stance",
Align = LabelWidget.TextAlign.Left,
};
bg.AddChild(ms);
controls.Add(ms);
y += 35;
foreach (var p in world.players.Values.Where(a => a != world.LocalPlayer && !a.NonCombatant))
{
var pp = p;
var label = new LabelWidget
{
Bounds = new Rectangle(margin, y, labelWidth, 25),
Id = "DIPLOMACY_PLAYER_LABEL_{0}".F(p.Index),
Text = p.PlayerName,
Align = LabelWidget.TextAlign.Left,
Bold = true,
};
bg.AddChild(label);
controls.Add(label);
var theirStance = new LabelWidget
{
Bounds = new Rectangle( margin + labelWidth + 10, y, labelWidth, 25),
Id = "DIPLOMACY_PLAYER_LABEL_THEIR_{0}".F(p.Index),
Text = p.PlayerName,
Align = LabelWidget.TextAlign.Left,
Bold = false,
GetText = () => pp.Stances[ world.LocalPlayer ].ToString(),
};
bg.AddChild(theirStance);
controls.Add(theirStance);
var myStance = new DropDownButtonWidget
{
Bounds = new Rectangle( margin + 2 * labelWidth + 20, y, labelWidth, 25),
Id = "DIPLOMACY_PLAYER_LABEL_MY_{0}".F(p.Index),
GetText = () => world.LocalPlayer.Stances[ pp ].ToString(),
};
myStance.OnMouseDown = mi => { ShowDropDown(pp, myStance); return true; };
bg.AddChild(myStance);
controls.Add(myStance);
y += 35;
}
}
void ShowDropDown(Player p, Widget w)
{
DropDownButtonWidget.ShowDropDown(w, Enum.GetValues(typeof(Stance)).OfType<Stance>(),
(s, width) => new LabelWidget
{
Bounds = new Rectangle(0, 0, width, 24),
Text = " {0}".F(s),
OnMouseUp = mi => { SetStance((ButtonWidget)w, p, s); return true; },
});
}
void SetStance(ButtonWidget bw, Player p, Stance ss)
{
if (p.World.LobbyInfo.GlobalSettings.LockTeams)
return; // team changes are banned
world.IssueOrder(new Order("SetStance", world.LocalPlayer.PlayerActor,
false) { TargetLocation = new int2(p.Index, (int)ss) });
bw.Text = ss.ToString();
}
}
}
var root = Widget.RootWidget.GetWidget("INGAME_ROOT");
var diplomacyBG = root.GetWidget("DIPLOMACY_BG");
var diplomacy = root.GetWidget("INGAME_DIPLOMACY_BUTTON");
diplomacy.OnMouseUp = mi =>
{
diplomacyBG.Visible = !diplomacyBG.Visible;
if (diplomacyBG.IsVisible())
LayoutDialog(diplomacyBG);
return true;
};
Game.AfterGameStart += _ => validPlayers = world.players.Values.Where(a => a != world.LocalPlayer && !a.NonCombatant).Count();
diplomacy.IsVisible = () => (validPlayers > 0);
}
void LayoutDialog(Widget bg)
{
bg.Children.RemoveAll(w => controls.Contains(w));
controls.Clear();
var y = 50;
var margin = 20;
var labelWidth = (bg.Bounds.Width - 3 * margin) / 3;
var ts = new LabelWidget
{
Bold = true,
Bounds = new Rectangle(margin + labelWidth + 10, y, labelWidth, 25),
Text = "Their Stance",
Align = LabelWidget.TextAlign.Left,
};
bg.AddChild(ts);
controls.Add(ts);
var ms = new LabelWidget
{
Bold = true,
Bounds = new Rectangle(margin + 2 * labelWidth + 20, y, labelWidth, 25),
Text = "My Stance",
Align = LabelWidget.TextAlign.Left,
};
bg.AddChild(ms);
controls.Add(ms);
y += 35;
foreach (var p in world.players.Values.Where(a => a != world.LocalPlayer && !a.NonCombatant))
{
var pp = p;
var label = new LabelWidget
{
Bounds = new Rectangle(margin, y, labelWidth, 25),
Id = "DIPLOMACY_PLAYER_LABEL_{0}".F(p.Index),
Text = p.PlayerName,
Align = LabelWidget.TextAlign.Left,
Bold = true,
};
bg.AddChild(label);
controls.Add(label);
var theirStance = new LabelWidget
{
Bounds = new Rectangle( margin + labelWidth + 10, y, labelWidth, 25),
Id = "DIPLOMACY_PLAYER_LABEL_THEIR_{0}".F(p.Index),
Text = p.PlayerName,
Align = LabelWidget.TextAlign.Left,
Bold = false,
GetText = () => pp.Stances[ world.LocalPlayer ].ToString(),
};
bg.AddChild(theirStance);
controls.Add(theirStance);
var myStance = new DropDownButtonWidget
{
Bounds = new Rectangle( margin + 2 * labelWidth + 20, y, labelWidth, 25),
Id = "DIPLOMACY_PLAYER_LABEL_MY_{0}".F(p.Index),
GetText = () => world.LocalPlayer.Stances[ pp ].ToString(),
};
myStance.OnMouseDown = mi => { ShowDropDown(pp, myStance); return true; };
bg.AddChild(myStance);
controls.Add(myStance);
y += 35;
}
}
void ShowDropDown(Player p, Widget w)
{
DropDownButtonWidget.ShowDropDown(w, Enum.GetValues(typeof(Stance)).OfType<Stance>(),
(s, width) => new LabelWidget
{
Bounds = new Rectangle(0, 0, width, 24),
Text = " {0}".F(s),
OnMouseUp = mi => { SetStance((ButtonWidget)w, p, s); return true; },
});
}
void SetStance(ButtonWidget bw, Player p, Stance ss)
{
if (p.World.LobbyInfo.GlobalSettings.LockTeams)
return; // team changes are banned
world.IssueOrder(new Order("SetStance", world.LocalPlayer.PlayerActor,
false) { TargetLocation = new int2(p.Index, (int)ss) });
bw.Text = ss.ToString();
}
}
}

View File

@@ -1,221 +1,222 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using System.Collections.Generic;
using OpenRA.FileFormats;
using OpenRA.Network;
using OpenRA.Server;
using OpenRA.Widgets;
using System.Diagnostics;
using System;
using System.Net;
using System.ComponentModel;
using System.IO;
using System.Threading;
using System.Drawing;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class GameInitDelegate : IWidgetDelegate
{
GameInitInfoWidget Info;
[ObjectCreator.UseCtor]
public GameInitDelegate([ObjectCreator.Param] Widget widget)
{
Info = (widget as GameInitInfoWidget);
Game.ConnectionStateChanged += orderManager =>
{
Widget.CloseWindow();
switch( orderManager.Connection.ConnectionState )
{
case ConnectionState.PreConnecting:
Widget.OpenWindow("MAINMENU_BG");
break;
case ConnectionState.Connecting:
Widget.OpenWindow( "CONNECTING_BG",
new Dictionary<string, object> { { "host", orderManager.Host }, { "port", orderManager.Port } } );
break;
case ConnectionState.NotConnected:
Widget.OpenWindow( "CONNECTION_FAILED_BG",
new Dictionary<string, object> { { "orderManager", orderManager } } );
break;
case ConnectionState.Connected:
var lobby = Game.OpenWindow(orderManager.world, "SERVER_LOBBY");
lobby.GetWidget<ChatDisplayWidget>("CHAT_DISPLAY").ClearChat();
lobby.GetWidget("CHANGEMAP_BUTTON").Visible = true;
lobby.GetWidget("LOCKTEAMS_CHECKBOX").Visible = true;
lobby.GetWidget("DISCONNECT_BUTTON").Visible = true;
break;
}
};
if (FileSystem.Exists(Info.TestFile))
ContinueLoading(widget);
else
{
MainMenuButtonsDelegate.DisplayModSelector();
ShowInstallMethodDialog();
}
}
void ShowInstallMethodDialog()
{
var window = Widget.OpenWindow("INIT_CHOOSEINSTALL");
window.GetWidget("DOWNLOAD").OnMouseUp = mi => { ShowDownloadDialog(); return true; };
window.GetWidget("FROMCD").OnMouseUp = mi => PromptForCD();
window.GetWidget("QUIT").OnMouseUp = mi => { Game.Exit(); return true; };
}
bool PromptForCD()
{
Game.Utilities.PromptFilepathAsync("Select MAIN.MIX on the CD", path =>
{
if (!string.IsNullOrEmpty(path))
Game.RunAfterTick(() => InstallFromCD(Path.GetDirectoryName(path)));
});
return true;
}
void InstallFromCD(string path)
{
var window = Widget.OpenWindow("INIT_COPY");
var status = window.GetWidget<LabelWidget>("STATUS");
var progress = window.GetWidget<ProgressBarWidget>("PROGRESS");
progress.Indeterminate = true;
// TODO: Handle cancelling copy
window.GetWidget<ButtonWidget>("CANCEL").IsVisible = () => false;
window.GetWidget("CANCEL").OnMouseUp = mi => { ShowInstallMethodDialog(); return true; };
window.GetWidget("RETRY").OnMouseUp = mi => PromptForCD();
status.GetText = () => "Copying...";
var error = false;
Action<string> parseOutput = s =>
{
if (s.Substring(0,5) == "Error")
{
error = true;
ShowDownloadError(window, s);
}
if (s.Substring(0,6) == "Status")
window.GetWidget<LabelWidget>("STATUS").GetText = () => s.Substring(7).Trim();
};
Action onComplete = () =>
{
if (!error)
Game.RunAfterTick(() => ContinueLoading(Info));
};
if (Info.InstallMode == "ra")
Game.Utilities.InstallRAFilesAsync(path, FileSystem.SpecialPackageRoot+Info.PackagePath, parseOutput, onComplete);
else
ShowDownloadError(window, "Installing from CD not supported");
}
void ShowDownloadDialog()
{
var window = Widget.OpenWindow("INIT_DOWNLOAD");
var status = window.GetWidget<LabelWidget>("STATUS");
status.GetText = () => "Initializing...";
var progress = window.GetWidget<ProgressBarWidget>("PROGRESS");
// Save the package to a temp file
var file = Path.GetTempPath() + Path.DirectorySeparatorChar + Path.GetRandomFileName();
Action<DownloadProgressChangedEventArgs> onDownloadChange = i =>
{
status.GetText = () => "Downloading {1}/{2} kB ({0}%)".F(i.ProgressPercentage, i.BytesReceived/1024, i.TotalBytesToReceive/1024);
progress.Percentage = i.ProgressPercentage;
};
Action<AsyncCompletedEventArgs, bool> onDownloadComplete = (i, cancelled) =>
{
if (i.Error != null)
ShowDownloadError(window, i.Error.Message);
else if (!cancelled)
{
// Automatically extract
status.GetText = () => "Extracting...";
progress.Indeterminate = true;
var error = false;
Action<string> parseOutput = s =>
{
if (s.Substring(0,5) == "Error")
{
error = true;
ShowDownloadError(window, s);
}
if (s.Substring(0,6) == "Status")
window.GetWidget<LabelWidget>("STATUS").GetText = () => s.Substring(7).Trim();
};
Action onComplete = () =>
{
if (!error)
Game.RunAfterTick(() => ContinueLoading(Info));
};
Game.RunAfterTick(() => Game.Utilities.ExtractZipAsync(file, FileSystem.SpecialPackageRoot+Info.PackagePath, parseOutput, onComplete));
}
};
var dl = new Download(Info.PackageURL, file, onDownloadChange, onDownloadComplete);
window.GetWidget("CANCEL").OnMouseUp = mi => { dl.Cancel(); ShowInstallMethodDialog(); return true; };
window.GetWidget("RETRY").OnMouseUp = mi => { dl.Cancel(); ShowDownloadDialog(); return true; };
}
void ShowDownloadError(Widget window, string e)
{
if (window.GetWidget<LabelWidget>("STATUS") != null) /* ugh */
{
window.GetWidget<LabelWidget>("STATUS").GetText = () => e;
window.GetWidget<ButtonWidget>("RETRY").IsVisible = () => true;
window.GetWidget<ButtonWidget>("CANCEL").IsVisible = () => true;
}
}
void ContinueLoading(Widget widget)
{
Game.LoadShellMap();
Widget.RootWidget.RemoveChildren();
Widget.OpenWindow("MAINMENU_BG");
}
// General support methods
public class Download
{
WebClient wc;
bool cancelled;
public Download(string url, string path, Action<DownloadProgressChangedEventArgs> onProgress, Action<AsyncCompletedEventArgs, bool> onComplete)
{
wc = new WebClient();
wc.Proxy = null;
wc.DownloadProgressChanged += (_,a) => onProgress(a);
wc.DownloadFileCompleted += (_,a) => onComplete(a, cancelled);
Game.OnQuit += () => Cancel();
wc.DownloadFileCompleted += (_,a) => {Game.OnQuit -= () => Cancel();};
wc.DownloadFileAsync(new Uri(url), path);
}
public void Cancel()
{
Game.OnQuit -= () => Cancel();
wc.CancelAsync();
cancelled = true;
}
}
}
#region Copyright & License Information
/*
* Copyright 2007-2011 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System.Collections.Generic;
using OpenRA.FileFormats;
using OpenRA.Network;
using OpenRA.Server;
using OpenRA.Widgets;
using System.Diagnostics;
using System;
using System.Net;
using System.ComponentModel;
using System.IO;
using System.Threading;
using System.Drawing;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class GameInitDelegate : IWidgetDelegate
{
GameInitInfoWidget Info;
[ObjectCreator.UseCtor]
public GameInitDelegate([ObjectCreator.Param] Widget widget)
{
Info = (widget as GameInitInfoWidget);
Game.ConnectionStateChanged += orderManager =>
{
Widget.CloseWindow();
switch( orderManager.Connection.ConnectionState )
{
case ConnectionState.PreConnecting:
Widget.OpenWindow("MAINMENU_BG");
break;
case ConnectionState.Connecting:
Widget.OpenWindow( "CONNECTING_BG",
new Dictionary<string, object> { { "host", orderManager.Host }, { "port", orderManager.Port } } );
break;
case ConnectionState.NotConnected:
Widget.OpenWindow( "CONNECTION_FAILED_BG",
new Dictionary<string, object> { { "orderManager", orderManager } } );
break;
case ConnectionState.Connected:
var lobby = Game.OpenWindow(orderManager.world, "SERVER_LOBBY");
lobby.GetWidget<ChatDisplayWidget>("CHAT_DISPLAY").ClearChat();
lobby.GetWidget("CHANGEMAP_BUTTON").Visible = true;
lobby.GetWidget("LOCKTEAMS_CHECKBOX").Visible = true;
lobby.GetWidget("DISCONNECT_BUTTON").Visible = true;
break;
}
};
if (FileSystem.Exists(Info.TestFile))
ContinueLoading(widget);
else
{
MainMenuButtonsDelegate.DisplayModSelector();
ShowInstallMethodDialog();
}
}
void ShowInstallMethodDialog()
{
var window = Widget.OpenWindow("INIT_CHOOSEINSTALL");
window.GetWidget("DOWNLOAD").OnMouseUp = mi => { ShowDownloadDialog(); return true; };
window.GetWidget("FROMCD").OnMouseUp = mi => PromptForCD();
window.GetWidget("QUIT").OnMouseUp = mi => { Game.Exit(); return true; };
}
bool PromptForCD()
{
Game.Utilities.PromptFilepathAsync("Select MAIN.MIX on the CD", path =>
{
if (!string.IsNullOrEmpty(path))
Game.RunAfterTick(() => InstallFromCD(Path.GetDirectoryName(path)));
});
return true;
}
void InstallFromCD(string path)
{
var window = Widget.OpenWindow("INIT_COPY");
var status = window.GetWidget<LabelWidget>("STATUS");
var progress = window.GetWidget<ProgressBarWidget>("PROGRESS");
progress.Indeterminate = true;
// TODO: Handle cancelling copy
window.GetWidget<ButtonWidget>("CANCEL").IsVisible = () => false;
window.GetWidget("CANCEL").OnMouseUp = mi => { ShowInstallMethodDialog(); return true; };
window.GetWidget("RETRY").OnMouseUp = mi => PromptForCD();
status.GetText = () => "Copying...";
var error = false;
Action<string> parseOutput = s =>
{
if (s.Substring(0,5) == "Error")
{
error = true;
ShowDownloadError(window, s);
}
if (s.Substring(0,6) == "Status")
window.GetWidget<LabelWidget>("STATUS").GetText = () => s.Substring(7).Trim();
};
Action onComplete = () =>
{
if (!error)
Game.RunAfterTick(() => ContinueLoading(Info));
};
if (Info.InstallMode == "ra")
Game.Utilities.InstallRAFilesAsync(path, FileSystem.SpecialPackageRoot+Info.PackagePath, parseOutput, onComplete);
else
ShowDownloadError(window, "Installing from CD not supported");
}
void ShowDownloadDialog()
{
var window = Widget.OpenWindow("INIT_DOWNLOAD");
var status = window.GetWidget<LabelWidget>("STATUS");
status.GetText = () => "Initializing...";
var progress = window.GetWidget<ProgressBarWidget>("PROGRESS");
// Save the package to a temp file
var file = Path.GetTempPath() + Path.DirectorySeparatorChar + Path.GetRandomFileName();
Action<DownloadProgressChangedEventArgs> onDownloadChange = i =>
{
status.GetText = () => "Downloading {1}/{2} kB ({0}%)".F(i.ProgressPercentage, i.BytesReceived/1024, i.TotalBytesToReceive/1024);
progress.Percentage = i.ProgressPercentage;
};
Action<AsyncCompletedEventArgs, bool> onDownloadComplete = (i, cancelled) =>
{
if (i.Error != null)
ShowDownloadError(window, i.Error.Message);
else if (!cancelled)
{
// Automatically extract
status.GetText = () => "Extracting...";
progress.Indeterminate = true;
var error = false;
Action<string> parseOutput = s =>
{
if (s.Substring(0,5) == "Error")
{
error = true;
ShowDownloadError(window, s);
}
if (s.Substring(0,6) == "Status")
window.GetWidget<LabelWidget>("STATUS").GetText = () => s.Substring(7).Trim();
};
Action onComplete = () =>
{
if (!error)
Game.RunAfterTick(() => ContinueLoading(Info));
};
Game.RunAfterTick(() => Game.Utilities.ExtractZipAsync(file, FileSystem.SpecialPackageRoot+Info.PackagePath, parseOutput, onComplete));
}
};
var dl = new Download(Info.PackageURL, file, onDownloadChange, onDownloadComplete);
window.GetWidget("CANCEL").OnMouseUp = mi => { dl.Cancel(); ShowInstallMethodDialog(); return true; };
window.GetWidget("RETRY").OnMouseUp = mi => { dl.Cancel(); ShowDownloadDialog(); return true; };
}
void ShowDownloadError(Widget window, string e)
{
if (window.GetWidget<LabelWidget>("STATUS") != null) /* ugh */
{
window.GetWidget<LabelWidget>("STATUS").GetText = () => e;
window.GetWidget<ButtonWidget>("RETRY").IsVisible = () => true;
window.GetWidget<ButtonWidget>("CANCEL").IsVisible = () => true;
}
}
void ContinueLoading(Widget widget)
{
Game.LoadShellMap();
Widget.RootWidget.RemoveChildren();
Widget.OpenWindow("MAINMENU_BG");
}
// General support methods
public class Download
{
WebClient wc;
bool cancelled;
public Download(string url, string path, Action<DownloadProgressChangedEventArgs> onProgress, Action<AsyncCompletedEventArgs, bool> onComplete)
{
wc = new WebClient();
wc.Proxy = null;
wc.DownloadProgressChanged += (_,a) => onProgress(a);
wc.DownloadFileCompleted += (_,a) => onComplete(a, cancelled);
Game.OnQuit += () => Cancel();
wc.DownloadFileCompleted += (_,a) => {Game.OnQuit -= () => Cancel();};
wc.DownloadFileAsync(new Uri(url), path);
}
public void Cancel()
{
Game.OnQuit -= () => Cancel();
wc.CancelAsync();
cancelled = true;
}
}
}
}

View File

@@ -1,33 +1,33 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using OpenRA.Traits;
using OpenRA.Widgets;
#region Copyright & License Information
/*
* Copyright 2007-2011 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using OpenRA.Traits;
using OpenRA.Widgets;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class IngameChromeDelegate : IWidgetDelegate
{
[ObjectCreator.UseCtor]
public IngameChromeDelegate( [ObjectCreator.Param] World world )
{
{
var r = Widget.RootWidget;
var gameRoot = r.GetWidget("INGAME_ROOT");
var gameRoot = r.GetWidget("INGAME_ROOT");
var optionsBG = gameRoot.GetWidget("INGAME_OPTIONS_BG");
r.GetWidget("INGAME_OPTIONS_BUTTON").OnMouseUp = mi => {
r.GetWidget("INGAME_OPTIONS_BUTTON").OnMouseUp = mi => {
optionsBG.Visible = !optionsBG.Visible;
return true;
};
optionsBG.GetWidget("DISCONNECT").OnMouseUp = mi => {
optionsBG.GetWidget("DISCONNECT").OnMouseUp = mi => {
optionsBG.Visible = false;
Game.Disconnect();
return true;
@@ -36,25 +36,25 @@ namespace OpenRA.Mods.RA.Widgets.Delegates
optionsBG.GetWidget("SETTINGS").OnMouseUp = mi => {
Widget.OpenWindow("SETTINGS_MENU");
return true;
};
optionsBG.GetWidget("MUSIC").OnMouseUp = mi => {
Widget.OpenWindow("MUSIC_MENU");
return true;
};
optionsBG.GetWidget("RESUME").OnMouseUp = mi =>
{
optionsBG.Visible = false;
return true;
};
optionsBG.GetWidget("SURRENDER").OnMouseUp = mi =>
{
world.IssueOrder(new Order("Surrender", world.LocalPlayer.PlayerActor, false));
return true;
};
optionsBG.GetWidget("MUSIC").OnMouseUp = mi => {
Widget.OpenWindow("MUSIC_MENU");
return true;
};
optionsBG.GetWidget("RESUME").OnMouseUp = mi =>
{
optionsBG.Visible = false;
return true;
};
optionsBG.GetWidget("SURRENDER").OnMouseUp = mi =>
{
world.IssueOrder(new Order("Surrender", world.LocalPlayer.PlayerActor, false));
return true;
};
optionsBG.GetWidget("SURRENDER").IsVisible = () => (world.LocalPlayer != null && world.LocalPlayer.WinState == WinState.Undefined);
optionsBG.GetWidget("QUIT").OnMouseUp = mi => {
@@ -62,22 +62,22 @@ namespace OpenRA.Mods.RA.Widgets.Delegates
return true;
};
Game.AddChatLine += gameRoot.GetWidget<ChatDisplayWidget>("CHAT_DISPLAY").AddLine;
var postgameBG = gameRoot.GetWidget("POSTGAME_BG");
var postgameText = postgameBG.GetWidget<LabelWidget>("TEXT");
postgameBG.IsVisible = () =>
{
return world.LocalPlayer != null && world.LocalPlayer.WinState != WinState.Undefined;
};
postgameText.GetText = () =>
{
var state = world.LocalPlayer.WinState;
return (state == WinState.Undefined)? "" :
((state == WinState.Lost)? "YOU ARE DEFEATED" : "YOU ARE VICTORIOUS");
Game.AddChatLine += gameRoot.GetWidget<ChatDisplayWidget>("CHAT_DISPLAY").AddLine;
var postgameBG = gameRoot.GetWidget("POSTGAME_BG");
var postgameText = postgameBG.GetWidget<LabelWidget>("TEXT");
postgameBG.IsVisible = () =>
{
return world.LocalPlayer != null && world.LocalPlayer.WinState != WinState.Undefined;
};
}
postgameText.GetText = () =>
{
var state = world.LocalPlayer.WinState;
return (state == WinState.Undefined)? "" :
((state == WinState.Lost)? "YOU ARE DEFEATED" : "YOU ARE VICTORIOUS");
};
}
}
}

View File

@@ -1,33 +1,33 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using OpenRA.Traits;
using OpenRA.Widgets;
#region Copyright & License Information
/*
* Copyright 2007-2011 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using OpenRA.Traits;
using OpenRA.Widgets;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class IngameObserverChromeDelegate : IWidgetDelegate
{
[ObjectCreator.UseCtor]
[ObjectCreator.UseCtor]
public IngameObserverChromeDelegate([ObjectCreator.Param] World world)
{
var r = Widget.RootWidget;
var gameRoot = r.GetWidget("OBSERVER_ROOT");
{
var r = Widget.RootWidget;
var gameRoot = r.GetWidget("OBSERVER_ROOT");
var optionsBG = gameRoot.GetWidget("INGAME_OPTIONS_BG");
r.GetWidget("INGAME_OPTIONS_BUTTON").OnMouseUp = mi => {
r.GetWidget("INGAME_OPTIONS_BUTTON").OnMouseUp = mi => {
optionsBG.Visible = !optionsBG.Visible;
return true;
};
optionsBG.GetWidget("DISCONNECT").OnMouseUp = mi => {
optionsBG.GetWidget("DISCONNECT").OnMouseUp = mi => {
optionsBG.Visible = false;
Game.Disconnect();
return true;
@@ -36,25 +36,25 @@ namespace OpenRA.Mods.RA.Widgets.Delegates
optionsBG.GetWidget("SETTINGS").OnMouseUp = mi => {
Widget.OpenWindow("SETTINGS_MENU");
return true;
};
optionsBG.GetWidget("MUSIC").OnMouseUp = mi => {
Widget.OpenWindow("MUSIC_MENU");
return true;
};
optionsBG.GetWidget("RESUME").OnMouseUp = mi =>
{
optionsBG.Visible = false;
return true;
};
/*
optionsBG.GetWidget("SURRENDER").OnMouseUp = mi =>
{
world.IssueOrder(new Order("Surrender", world.LocalPlayer.PlayerActor));
return true;
};
*/
optionsBG.GetWidget("MUSIC").OnMouseUp = mi => {
Widget.OpenWindow("MUSIC_MENU");
return true;
};
optionsBG.GetWidget("RESUME").OnMouseUp = mi =>
{
optionsBG.Visible = false;
return true;
};
/*
optionsBG.GetWidget("SURRENDER").OnMouseUp = mi =>
{
world.IssueOrder(new Order("Surrender", world.LocalPlayer.PlayerActor));
return true;
};
*/
optionsBG.GetWidget("SURRENDER").IsVisible = () => false;
optionsBG.GetWidget("QUIT").OnMouseUp = mi => {
@@ -62,24 +62,24 @@ namespace OpenRA.Mods.RA.Widgets.Delegates
return true;
};
Game.AddChatLine += gameRoot.GetWidget<ChatDisplayWidget>("CHAT_DISPLAY").AddLine;
/*
var postgameBG = gameRoot.GetWidget("POSTGAME_BG");
var postgameText = postgameBG.GetWidget<LabelWidget>("TEXT");
postgameBG.IsVisible = () =>
{
return world.LocalPlayer != null && world.LocalPlayer.WinState != WinState.Undefined;
};
postgameText.GetText = () =>
{
if (world.LocalPlayer == null)
return "";
var state = world.LocalPlayer.WinState;
return (state == WinState.Undefined)? "" :
((state == WinState.Lost)? "YOU ARE DEFEATED" : "YOU ARE VICTORIOUS");
Game.AddChatLine += gameRoot.GetWidget<ChatDisplayWidget>("CHAT_DISPLAY").AddLine;
/*
var postgameBG = gameRoot.GetWidget("POSTGAME_BG");
var postgameText = postgameBG.GetWidget<LabelWidget>("TEXT");
postgameBG.IsVisible = () =>
{
return world.LocalPlayer != null && world.LocalPlayer.WinState != WinState.Undefined;
};
postgameText.GetText = () =>
{
if (world.LocalPlayer == null)
return "";
var state = world.LocalPlayer.WinState;
return (state == WinState.Undefined)? "" :
((state == WinState.Lost)? "YOU ARE DEFEATED" : "YOU ARE VICTORIOUS");
};*/
}
}
}
}

View File

@@ -1,467 +1,467 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using OpenRA.FileFormats;
using OpenRA.Network;
using OpenRA.Traits;
using OpenRA.Widgets;
using OpenRA.Graphics;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class LobbyDelegate : IWidgetDelegate
{
Widget LocalPlayerTemplate, RemotePlayerTemplate, EmptySlotTemplate, EmptySlotTemplateHost;
ScrollPanelWidget Players;
Dictionary<string, string> CountryNames;
string MapUid;
Map Map;
public static ColorRamp CurrentColorPreview;
readonly OrderManager orderManager;
readonly WorldRenderer worldRenderer;
[ObjectCreator.UseCtor]
internal LobbyDelegate( [ObjectCreator.Param( "widget" )] Widget lobby, [ObjectCreator.Param] OrderManager orderManager, [ObjectCreator.Param] WorldRenderer worldRenderer)
{
this.orderManager = orderManager;
this.worldRenderer = worldRenderer;
Game.LobbyInfoChanged += UpdateCurrentMap;
UpdateCurrentMap();
CurrentColorPreview = Game.Settings.Player.ColorRamp;
Players = lobby.GetWidget<ScrollPanelWidget>("PLAYERS");
LocalPlayerTemplate = Players.GetWidget("TEMPLATE_LOCAL");
RemotePlayerTemplate = Players.GetWidget("TEMPLATE_REMOTE");
EmptySlotTemplate = Players.GetWidget("TEMPLATE_EMPTY");
EmptySlotTemplateHost = Players.GetWidget("TEMPLATE_EMPTY_HOST");
var mapPreview = lobby.GetWidget<MapPreviewWidget>("LOBBY_MAP_PREVIEW");
mapPreview.Map = () => Map;
mapPreview.OnMouseDown = mi =>
{
var map = mapPreview.Map();
if (map == null || mi.Button != MouseButton.Left
|| orderManager.LocalClient.State == Session.ClientState.Ready)
return false;
var p = map.SpawnPoints
.Select((sp, i) => Pair.New(mapPreview.ConvertToPreview(map, sp), i))
.Where(a => (a.First - mi.Location).LengthSquared < 64)
.Select(a => a.Second + 1)
.FirstOrDefault();
var owned = orderManager.LobbyInfo.Clients.Any(c => c.SpawnPoint == p);
if (p == 0 || !owned)
orderManager.IssueOrder(Order.Command("spawn {0}".F(p)));
return true;
};
mapPreview.SpawnColors = () =>
{
var spawns = Map.SpawnPoints;
var sc = new Dictionary<int2, Color>();
for (int i = 1; i <= spawns.Count(); i++)
{
var client = orderManager.LobbyInfo.Clients.FirstOrDefault(c => c.SpawnPoint == i);
if (client == null)
continue;
sc.Add(spawns.ElementAt(i - 1), client.ColorRamp.GetColor(0));
}
return sc;
};
CountryNames = Rules.Info["world"].Traits.WithInterface<OpenRA.Traits.CountryInfo>().ToDictionary(a => a.Race, a => a.Name);
CountryNames.Add("random", "Random");
var mapButton = lobby.GetWidget("CHANGEMAP_BUTTON");
mapButton.OnMouseUp = mi =>
{
Widget.OpenWindow( "MAP_CHOOSER", new Dictionary<string, object> { { "orderManager", orderManager }, { "mapName", MapUid } } );
return true;
};
mapButton.IsVisible = () => mapButton.Visible && Game.IsHost;
var disconnectButton = lobby.GetWidget("DISCONNECT_BUTTON");
disconnectButton.OnMouseUp = mi =>
{
Game.Disconnect();
return true;
};
var lockTeamsCheckbox = lobby.GetWidget<CheckboxWidget>("LOCKTEAMS_CHECKBOX");
lockTeamsCheckbox.IsChecked = () => orderManager.LobbyInfo.GlobalSettings.LockTeams;
lockTeamsCheckbox.OnChange += _ =>
{
if (Game.IsHost)
orderManager.IssueOrder(Order.Command(
"lockteams {0}".F(!orderManager.LobbyInfo.GlobalSettings.LockTeams)));
};
var startGameButton = lobby.GetWidget("START_GAME_BUTTON");
startGameButton.OnMouseUp = mi =>
{
mapButton.Visible = false;
disconnectButton.Visible = false;
lockTeamsCheckbox.Visible = false;
orderManager.IssueOrder(Order.Command("startgame"));
return true;
};
// Todo: Only show if the map requirements are met for player slots
startGameButton.IsVisible = () => Game.IsHost;
Game.LobbyInfoChanged += UpdatePlayerList;
Game.AddChatLine += lobby.GetWidget<ChatDisplayWidget>("CHAT_DISPLAY").AddLine;
bool teamChat = false;
var chatLabel = lobby.GetWidget<LabelWidget>("LABEL_CHATTYPE");
var chatTextField = lobby.GetWidget<TextFieldWidget>("CHAT_TEXTFIELD");
chatTextField.OnEnterKey = () =>
{
if (chatTextField.Text.Length == 0)
return true;
var order = (teamChat) ? Order.TeamChat(chatTextField.Text) : Order.Chat(chatTextField.Text);
orderManager.IssueOrder(order);
chatTextField.Text = "";
return true;
};
chatTextField.OnTabKey = () =>
{
teamChat ^= true;
chatLabel.Text = (teamChat) ? "Team:" : "Chat:";
return true;
};
}
void UpdatePlayerColor(float hf, float sf, float lf, float r)
{
var ramp = new ColorRamp((byte) (hf*255), (byte) (sf*255), (byte) (lf*255), (byte)(r*255));
Game.Settings.Player.ColorRamp = ramp;
Game.Settings.Save();
orderManager.IssueOrder(Order.Command("color {0}".F(ramp)));
}
void UpdateColorPreview(float hf, float sf, float lf, float r)
{
CurrentColorPreview = new ColorRamp((byte)(hf * 255), (byte)(sf * 255), (byte)(lf * 255), (byte)(r * 255));
}
void UpdateCurrentMap()
{
if (MapUid == orderManager.LobbyInfo.GlobalSettings.Map) return;
MapUid = orderManager.LobbyInfo.GlobalSettings.Map;
Map = new Map(Game.modData.AvailableMaps[MapUid].Path);
var title = Widget.RootWidget.GetWidget<LabelWidget>("LOBBY_TITLE");
title.Text = "OpenRA Multiplayer Lobby - " + orderManager.LobbyInfo.GlobalSettings.ServerName;
}
Session.Client GetClientInSlot(Session.Slot slot)
{
return orderManager.LobbyInfo.ClientInSlot( slot );
}
bool ShowSlotDropDown(Session.Slot slot, ButtonWidget name, bool showBotOptions)
{
var dropDownOptions = new List<Pair<string, Action>>
{
new Pair<string, Action>( "Open",
() => orderManager.IssueOrder( Order.Command( "slot_open " + slot.Index ) )),
new Pair<string, Action>( "Closed",
() => orderManager.IssueOrder( Order.Command( "slot_close " + slot.Index ) )),
};
if (showBotOptions)
{
var bots = Rules.Info["player"].Traits.WithInterface<IBotInfo>().Select(t => t.Name);
bots.Do(bot =>
dropDownOptions.Add(new Pair<string, Action>("Bot: {0}".F(bot),
() => orderManager.IssueOrder(Order.Command("slot_bot {0} {1}".F(slot.Index, bot))))));
}
DropDownButtonWidget.ShowDropDown( name,
dropDownOptions,
(ac, w) => new LabelWidget
{
Bounds = new Rectangle(0, 0, w, 24),
Text = " {0}".F(ac.First),
OnMouseUp = mi => { ac.Second(); return true; },
});
return true;
}
bool ShowRaceDropDown(Session.Slot s, ButtonWidget race)
{
if (Map.Players[s.MapPlayer].LockRace)
return false;
var dropDownOptions = new List<Pair<string, Action>>();
foreach (var c in CountryNames)
{
var cc = c;
dropDownOptions.Add(new Pair<string, Action>( cc.Key,
() => orderManager.IssueOrder( Order.Command("race "+cc.Key) )) );
};
DropDownButtonWidget.ShowDropDown( race,
dropDownOptions,
(ac, w) =>
{
var ret = new LabelWidget
{
Bounds = new Rectangle(0, 0, w, 24),
Text = " {0}".F(CountryNames[ac.First]),
OnMouseUp = mi => { ac.Second(); return true; },
};
ret.AddChild(new ImageWidget
{
Bounds = new Rectangle(5, 5, 40, 15),
GetImageName = () => ac.First,
GetImageCollection = () => "flags",
});
return ret;
});
return true;
}
bool ShowTeamDropDown(ButtonWidget team)
{
var dropDownOptions = new List<Pair<string, Action>>();
for (int i = 0; i <= Map.PlayerCount; i++)
{
var ii = i;
dropDownOptions.Add(new Pair<string, Action>( ii == 0 ? "-" : ii.ToString(),
() => orderManager.IssueOrder( Order.Command("team "+ii) )) );
};
DropDownButtonWidget.ShowDropDown( team,
dropDownOptions,
(ac, w) => new LabelWidget
{
Bounds = new Rectangle(0, 0, w, 24),
Text = " {0}".F(ac.First),
OnMouseUp = mi => { ac.Second(); return true; },
});
return true;
}
bool ShowColorDropDown(Session.Slot s, ButtonWidget color)
{
if (Map.Players[s.MapPlayer].LockColor)
return false;
var colorChooser = Game.modData.WidgetLoader.LoadWidget( new Dictionary<string,object>() { {"worldRenderer", worldRenderer} }, null, "COLOR_CHOOSER" );
var hueSlider = colorChooser.GetWidget<SliderWidget>("HUE_SLIDER");
hueSlider.SetOffset(orderManager.LocalClient.ColorRamp.H / 255f);
var satSlider = colorChooser.GetWidget<SliderWidget>("SAT_SLIDER");
satSlider.SetOffset(orderManager.LocalClient.ColorRamp.S / 255f);
var lumSlider = colorChooser.GetWidget<SliderWidget>("LUM_SLIDER");
lumSlider.SetOffset(orderManager.LocalClient.ColorRamp.L / 255f);
var rangeSlider = colorChooser.GetWidget<SliderWidget>("RANGE_SLIDER");
rangeSlider.SetOffset(orderManager.LocalClient.ColorRamp.R / 255f);
hueSlider.OnChange += _ => UpdateColorPreview(hueSlider.GetOffset(), satSlider.GetOffset(), lumSlider.GetOffset(), rangeSlider.GetOffset());
satSlider.OnChange += _ => UpdateColorPreview(hueSlider.GetOffset(), satSlider.GetOffset(), lumSlider.GetOffset(), rangeSlider.GetOffset());
lumSlider.OnChange += _ => UpdateColorPreview(hueSlider.GetOffset(), satSlider.GetOffset(), lumSlider.GetOffset(), rangeSlider.GetOffset());
rangeSlider.OnChange += _ => UpdateColorPreview(hueSlider.GetOffset(), satSlider.GetOffset(), lumSlider.GetOffset(), rangeSlider.GetOffset());
UpdateColorPreview(hueSlider.GetOffset(), satSlider.GetOffset(), lumSlider.GetOffset(), rangeSlider.GetOffset());
DropDownButtonWidget.ShowDropPanel(color, colorChooser, new List<Widget>() {colorChooser.GetWidget("BUTTON_OK")}, () => {
UpdateColorPreview(hueSlider.GetOffset(), satSlider.GetOffset(), lumSlider.GetOffset(), rangeSlider.GetOffset());
UpdatePlayerColor(hueSlider.GetOffset(), satSlider.GetOffset(), lumSlider.GetOffset(), rangeSlider.GetOffset());
return true;
});
return true;
}
void UpdatePlayerList()
{
// This causes problems for people who are in the process of editing their names (the widgets vanish from beneath them)
// Todo: handle this nicer
Players.RemoveChildren();
foreach (var slot in orderManager.LobbyInfo.Slots)
{
var s = slot;
var c = GetClientInSlot(s);
Widget template;
if (c == null)
{
if (Game.IsHost)
{
if (slot.Spectator)
{
template = EmptySlotTemplateHost.Clone();
var name = template.GetWidget<ButtonWidget>("NAME");
name.GetText = () => s.Closed ? "Closed" : "Open";
name.OnMouseDown = _ => ShowSlotDropDown(s, name, false);
var btn = template.GetWidget<ButtonWidget>("JOIN");
btn.GetText = () => "Spectate in this slot";
}
else
{
template = EmptySlotTemplateHost.Clone();
var name = template.GetWidget<ButtonWidget>("NAME");
name.GetText = () => s.Closed ? "Closed" : (s.Bot == null) ? "Open" : s.Bot;
name.OnMouseDown = _ => ShowSlotDropDown(s, name, Map.Players[ s.MapPlayer ].AllowBots);
}
}
else
{
template = EmptySlotTemplate.Clone();
var name = template.GetWidget<LabelWidget>("NAME");
name.GetText = () => s.Closed ? "Closed" : (s.Bot == null) ? "Open" : s.Bot;
if (slot.Spectator)
{
var btn = template.GetWidget<ButtonWidget>("JOIN");
btn.GetText = () => "Spectate in this slot";
}
}
var join = template.GetWidget<ButtonWidget>("JOIN");
if (join != null)
{
join.OnMouseUp = _ => { orderManager.IssueOrder(Order.Command("slot " + s.Index)); return true; };
join.IsVisible = () => !s.Closed && s.Bot == null && orderManager.LocalClient.State != Session.ClientState.Ready;
}
var bot = template.GetWidget<LabelWidget>("BOT");
if (bot != null)
bot.IsVisible = () => s.Bot != null;
}
else if (c.Index == orderManager.LocalClient.Index && c.State != Session.ClientState.Ready)
{
template = LocalPlayerTemplate.Clone();
var name = template.GetWidget<TextFieldWidget>("NAME");
name.Text = c.Name;
name.OnEnterKey = () =>
{
name.Text = name.Text.Trim();
if (name.Text.Length == 0)
name.Text = c.Name;
name.LoseFocus();
if (name.Text == c.Name)
return true;
orderManager.IssueOrder(Order.Command("name " + name.Text));
Game.Settings.Player.Name = name.Text;
Game.Settings.Save();
return true;
};
name.OnLoseFocus = () => name.OnEnterKey();
var color = template.GetWidget<ButtonWidget>("COLOR");
color.OnMouseUp = _ => ShowColorDropDown(s, color);
var colorBlock = color.GetWidget<ColorBlockWidget>("COLORBLOCK");
colorBlock.GetColor = () => c.ColorRamp.GetColor(0);
var faction = template.GetWidget<ButtonWidget>("FACTION");
faction.OnMouseDown = _ => ShowRaceDropDown(s, faction);
var factionname = faction.GetWidget<LabelWidget>("FACTIONNAME");
factionname.GetText = () => CountryNames[c.Country];
var factionflag = faction.GetWidget<ImageWidget>("FACTIONFLAG");
factionflag.GetImageName = () => c.Country;
factionflag.GetImageCollection = () => "flags";
var team = template.GetWidget<ButtonWidget>("TEAM");
team.OnMouseDown = _ => ShowTeamDropDown(team);
team.GetText = () => (c.Team == 0) ? "-" : c.Team.ToString();
var status = template.GetWidget<CheckboxWidget>("STATUS");
status.IsChecked = () => c.State == Session.ClientState.Ready;
status.OnChange += CycleReady;
var spectator = template.GetWidget<LabelWidget>("SPECTATOR");
Session.Slot slot1 = slot;
color.IsVisible = () => !slot1.Spectator;
colorBlock.IsVisible = () => !slot1.Spectator;
faction.IsVisible = () => !slot1.Spectator;
factionname.IsVisible = () => !slot1.Spectator;
factionflag.IsVisible = () => !slot1.Spectator;
team.IsVisible = () => !slot1.Spectator;
spectator.IsVisible = () => slot1.Spectator || slot1.Bot != null;
}
else
{
template = RemotePlayerTemplate.Clone();
template.GetWidget<LabelWidget>("NAME").GetText = () => c.Name;
var color = template.GetWidget<ColorBlockWidget>("COLOR");
color.GetColor = () => c.ColorRamp.GetColor(0);
var faction = template.GetWidget<LabelWidget>("FACTION");
var factionname = faction.GetWidget<LabelWidget>("FACTIONNAME");
factionname.GetText = () => CountryNames[c.Country];
var factionflag = faction.GetWidget<ImageWidget>("FACTIONFLAG");
factionflag.GetImageName = () => c.Country;
factionflag.GetImageCollection = () => "flags";
var team = template.GetWidget<LabelWidget>("TEAM");
team.GetText = () => (c.Team == 0) ? "-" : c.Team.ToString();
var status = template.GetWidget<CheckboxWidget>("STATUS");
status.IsChecked = () => c.State == Session.ClientState.Ready;
if (c.Index == orderManager.LocalClient.Index)
status.OnChange += CycleReady;
var spectator = template.GetWidget<LabelWidget>("SPECTATOR");
Session.Slot slot1 = slot;
color.IsVisible = () => !slot1.Spectator;
faction.IsVisible = () => !slot1.Spectator;
factionname.IsVisible = () => !slot1.Spectator;
factionflag.IsVisible = () => !slot1.Spectator;
team.IsVisible = () => !slot1.Spectator;
spectator.IsVisible = () => slot1.Spectator || slot1.Bot != null;
var kickButton = template.GetWidget<ButtonWidget>("KICK");
kickButton.IsVisible = () => Game.IsHost && c.Index != orderManager.LocalClient.Index;
kickButton.OnMouseUp = mi =>
{
orderManager.IssueOrder(Order.Command("kick " + c.Slot));
return true;
};
}
template.Id = "SLOT_{0}".F(s.Index);
template.IsVisible = () => true;
Players.AddChild(template);
}
}
bool SpawnPointAvailable(int index) { return (index == 0) || orderManager.LobbyInfo.Clients.All(c => c.SpawnPoint != index); }
void CycleReady(bool ready)
{
orderManager.IssueOrder(Order.Command("ready"));
}
}
}
#region Copyright & License Information
/*
* Copyright 2007-2011 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using OpenRA.FileFormats;
using OpenRA.Network;
using OpenRA.Traits;
using OpenRA.Widgets;
using OpenRA.Graphics;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class LobbyDelegate : IWidgetDelegate
{
Widget LocalPlayerTemplate, RemotePlayerTemplate, EmptySlotTemplate, EmptySlotTemplateHost;
ScrollPanelWidget Players;
Dictionary<string, string> CountryNames;
string MapUid;
Map Map;
public static ColorRamp CurrentColorPreview;
readonly OrderManager orderManager;
readonly WorldRenderer worldRenderer;
[ObjectCreator.UseCtor]
internal LobbyDelegate( [ObjectCreator.Param( "widget" )] Widget lobby, [ObjectCreator.Param] OrderManager orderManager, [ObjectCreator.Param] WorldRenderer worldRenderer)
{
this.orderManager = orderManager;
this.worldRenderer = worldRenderer;
Game.LobbyInfoChanged += UpdateCurrentMap;
UpdateCurrentMap();
CurrentColorPreview = Game.Settings.Player.ColorRamp;
Players = lobby.GetWidget<ScrollPanelWidget>("PLAYERS");
LocalPlayerTemplate = Players.GetWidget("TEMPLATE_LOCAL");
RemotePlayerTemplate = Players.GetWidget("TEMPLATE_REMOTE");
EmptySlotTemplate = Players.GetWidget("TEMPLATE_EMPTY");
EmptySlotTemplateHost = Players.GetWidget("TEMPLATE_EMPTY_HOST");
var mapPreview = lobby.GetWidget<MapPreviewWidget>("LOBBY_MAP_PREVIEW");
mapPreview.Map = () => Map;
mapPreview.OnMouseDown = mi =>
{
var map = mapPreview.Map();
if (map == null || mi.Button != MouseButton.Left
|| orderManager.LocalClient.State == Session.ClientState.Ready)
return false;
var p = map.SpawnPoints
.Select((sp, i) => Pair.New(mapPreview.ConvertToPreview(map, sp), i))
.Where(a => (a.First - mi.Location).LengthSquared < 64)
.Select(a => a.Second + 1)
.FirstOrDefault();
var owned = orderManager.LobbyInfo.Clients.Any(c => c.SpawnPoint == p);
if (p == 0 || !owned)
orderManager.IssueOrder(Order.Command("spawn {0}".F(p)));
return true;
};
mapPreview.SpawnColors = () =>
{
var spawns = Map.SpawnPoints;
var sc = new Dictionary<int2, Color>();
for (int i = 1; i <= spawns.Count(); i++)
{
var client = orderManager.LobbyInfo.Clients.FirstOrDefault(c => c.SpawnPoint == i);
if (client == null)
continue;
sc.Add(spawns.ElementAt(i - 1), client.ColorRamp.GetColor(0));
}
return sc;
};
CountryNames = Rules.Info["world"].Traits.WithInterface<OpenRA.Traits.CountryInfo>().ToDictionary(a => a.Race, a => a.Name);
CountryNames.Add("random", "Random");
var mapButton = lobby.GetWidget("CHANGEMAP_BUTTON");
mapButton.OnMouseUp = mi =>
{
Widget.OpenWindow( "MAP_CHOOSER", new Dictionary<string, object> { { "orderManager", orderManager }, { "mapName", MapUid } } );
return true;
};
mapButton.IsVisible = () => mapButton.Visible && Game.IsHost;
var disconnectButton = lobby.GetWidget("DISCONNECT_BUTTON");
disconnectButton.OnMouseUp = mi =>
{
Game.Disconnect();
return true;
};
var lockTeamsCheckbox = lobby.GetWidget<CheckboxWidget>("LOCKTEAMS_CHECKBOX");
lockTeamsCheckbox.IsChecked = () => orderManager.LobbyInfo.GlobalSettings.LockTeams;
lockTeamsCheckbox.OnChange += _ =>
{
if (Game.IsHost)
orderManager.IssueOrder(Order.Command(
"lockteams {0}".F(!orderManager.LobbyInfo.GlobalSettings.LockTeams)));
};
var startGameButton = lobby.GetWidget("START_GAME_BUTTON");
startGameButton.OnMouseUp = mi =>
{
mapButton.Visible = false;
disconnectButton.Visible = false;
lockTeamsCheckbox.Visible = false;
orderManager.IssueOrder(Order.Command("startgame"));
return true;
};
// Todo: Only show if the map requirements are met for player slots
startGameButton.IsVisible = () => Game.IsHost;
Game.LobbyInfoChanged += UpdatePlayerList;
Game.AddChatLine += lobby.GetWidget<ChatDisplayWidget>("CHAT_DISPLAY").AddLine;
bool teamChat = false;
var chatLabel = lobby.GetWidget<LabelWidget>("LABEL_CHATTYPE");
var chatTextField = lobby.GetWidget<TextFieldWidget>("CHAT_TEXTFIELD");
chatTextField.OnEnterKey = () =>
{
if (chatTextField.Text.Length == 0)
return true;
var order = (teamChat) ? Order.TeamChat(chatTextField.Text) : Order.Chat(chatTextField.Text);
orderManager.IssueOrder(order);
chatTextField.Text = "";
return true;
};
chatTextField.OnTabKey = () =>
{
teamChat ^= true;
chatLabel.Text = (teamChat) ? "Team:" : "Chat:";
return true;
};
}
void UpdatePlayerColor(float hf, float sf, float lf, float r)
{
var ramp = new ColorRamp((byte) (hf*255), (byte) (sf*255), (byte) (lf*255), (byte)(r*255));
Game.Settings.Player.ColorRamp = ramp;
Game.Settings.Save();
orderManager.IssueOrder(Order.Command("color {0}".F(ramp)));
}
void UpdateColorPreview(float hf, float sf, float lf, float r)
{
CurrentColorPreview = new ColorRamp((byte)(hf * 255), (byte)(sf * 255), (byte)(lf * 255), (byte)(r * 255));
}
void UpdateCurrentMap()
{
if (MapUid == orderManager.LobbyInfo.GlobalSettings.Map) return;
MapUid = orderManager.LobbyInfo.GlobalSettings.Map;
Map = new Map(Game.modData.AvailableMaps[MapUid].Path);
var title = Widget.RootWidget.GetWidget<LabelWidget>("LOBBY_TITLE");
title.Text = "OpenRA Multiplayer Lobby - " + orderManager.LobbyInfo.GlobalSettings.ServerName;
}
Session.Client GetClientInSlot(Session.Slot slot)
{
return orderManager.LobbyInfo.ClientInSlot( slot );
}
bool ShowSlotDropDown(Session.Slot slot, ButtonWidget name, bool showBotOptions)
{
var dropDownOptions = new List<Pair<string, Action>>
{
new Pair<string, Action>( "Open",
() => orderManager.IssueOrder( Order.Command( "slot_open " + slot.Index ) )),
new Pair<string, Action>( "Closed",
() => orderManager.IssueOrder( Order.Command( "slot_close " + slot.Index ) )),
};
if (showBotOptions)
{
var bots = Rules.Info["player"].Traits.WithInterface<IBotInfo>().Select(t => t.Name);
bots.Do(bot =>
dropDownOptions.Add(new Pair<string, Action>("Bot: {0}".F(bot),
() => orderManager.IssueOrder(Order.Command("slot_bot {0} {1}".F(slot.Index, bot))))));
}
DropDownButtonWidget.ShowDropDown( name,
dropDownOptions,
(ac, w) => new LabelWidget
{
Bounds = new Rectangle(0, 0, w, 24),
Text = " {0}".F(ac.First),
OnMouseUp = mi => { ac.Second(); return true; },
});
return true;
}
bool ShowRaceDropDown(Session.Slot s, ButtonWidget race)
{
if (Map.Players[s.MapPlayer].LockRace)
return false;
var dropDownOptions = new List<Pair<string, Action>>();
foreach (var c in CountryNames)
{
var cc = c;
dropDownOptions.Add(new Pair<string, Action>( cc.Key,
() => orderManager.IssueOrder( Order.Command("race "+cc.Key) )) );
};
DropDownButtonWidget.ShowDropDown( race,
dropDownOptions,
(ac, w) =>
{
var ret = new LabelWidget
{
Bounds = new Rectangle(0, 0, w, 24),
Text = " {0}".F(CountryNames[ac.First]),
OnMouseUp = mi => { ac.Second(); return true; },
};
ret.AddChild(new ImageWidget
{
Bounds = new Rectangle(5, 5, 40, 15),
GetImageName = () => ac.First,
GetImageCollection = () => "flags",
});
return ret;
});
return true;
}
bool ShowTeamDropDown(ButtonWidget team)
{
var dropDownOptions = new List<Pair<string, Action>>();
for (int i = 0; i <= Map.PlayerCount; i++)
{
var ii = i;
dropDownOptions.Add(new Pair<string, Action>( ii == 0 ? "-" : ii.ToString(),
() => orderManager.IssueOrder( Order.Command("team "+ii) )) );
};
DropDownButtonWidget.ShowDropDown( team,
dropDownOptions,
(ac, w) => new LabelWidget
{
Bounds = new Rectangle(0, 0, w, 24),
Text = " {0}".F(ac.First),
OnMouseUp = mi => { ac.Second(); return true; },
});
return true;
}
bool ShowColorDropDown(Session.Slot s, ButtonWidget color)
{
if (Map.Players[s.MapPlayer].LockColor)
return false;
var colorChooser = Game.modData.WidgetLoader.LoadWidget( new Dictionary<string,object>() { {"worldRenderer", worldRenderer} }, null, "COLOR_CHOOSER" );
var hueSlider = colorChooser.GetWidget<SliderWidget>("HUE_SLIDER");
hueSlider.SetOffset(orderManager.LocalClient.ColorRamp.H / 255f);
var satSlider = colorChooser.GetWidget<SliderWidget>("SAT_SLIDER");
satSlider.SetOffset(orderManager.LocalClient.ColorRamp.S / 255f);
var lumSlider = colorChooser.GetWidget<SliderWidget>("LUM_SLIDER");
lumSlider.SetOffset(orderManager.LocalClient.ColorRamp.L / 255f);
var rangeSlider = colorChooser.GetWidget<SliderWidget>("RANGE_SLIDER");
rangeSlider.SetOffset(orderManager.LocalClient.ColorRamp.R / 255f);
hueSlider.OnChange += _ => UpdateColorPreview(hueSlider.GetOffset(), satSlider.GetOffset(), lumSlider.GetOffset(), rangeSlider.GetOffset());
satSlider.OnChange += _ => UpdateColorPreview(hueSlider.GetOffset(), satSlider.GetOffset(), lumSlider.GetOffset(), rangeSlider.GetOffset());
lumSlider.OnChange += _ => UpdateColorPreview(hueSlider.GetOffset(), satSlider.GetOffset(), lumSlider.GetOffset(), rangeSlider.GetOffset());
rangeSlider.OnChange += _ => UpdateColorPreview(hueSlider.GetOffset(), satSlider.GetOffset(), lumSlider.GetOffset(), rangeSlider.GetOffset());
UpdateColorPreview(hueSlider.GetOffset(), satSlider.GetOffset(), lumSlider.GetOffset(), rangeSlider.GetOffset());
DropDownButtonWidget.ShowDropPanel(color, colorChooser, new List<Widget>() {colorChooser.GetWidget("BUTTON_OK")}, () => {
UpdateColorPreview(hueSlider.GetOffset(), satSlider.GetOffset(), lumSlider.GetOffset(), rangeSlider.GetOffset());
UpdatePlayerColor(hueSlider.GetOffset(), satSlider.GetOffset(), lumSlider.GetOffset(), rangeSlider.GetOffset());
return true;
});
return true;
}
void UpdatePlayerList()
{
// This causes problems for people who are in the process of editing their names (the widgets vanish from beneath them)
// Todo: handle this nicer
Players.RemoveChildren();
foreach (var slot in orderManager.LobbyInfo.Slots)
{
var s = slot;
var c = GetClientInSlot(s);
Widget template;
if (c == null)
{
if (Game.IsHost)
{
if (slot.Spectator)
{
template = EmptySlotTemplateHost.Clone();
var name = template.GetWidget<ButtonWidget>("NAME");
name.GetText = () => s.Closed ? "Closed" : "Open";
name.OnMouseDown = _ => ShowSlotDropDown(s, name, false);
var btn = template.GetWidget<ButtonWidget>("JOIN");
btn.GetText = () => "Spectate in this slot";
}
else
{
template = EmptySlotTemplateHost.Clone();
var name = template.GetWidget<ButtonWidget>("NAME");
name.GetText = () => s.Closed ? "Closed" : (s.Bot == null) ? "Open" : s.Bot;
name.OnMouseDown = _ => ShowSlotDropDown(s, name, Map.Players[ s.MapPlayer ].AllowBots);
}
}
else
{
template = EmptySlotTemplate.Clone();
var name = template.GetWidget<LabelWidget>("NAME");
name.GetText = () => s.Closed ? "Closed" : (s.Bot == null) ? "Open" : s.Bot;
if (slot.Spectator)
{
var btn = template.GetWidget<ButtonWidget>("JOIN");
btn.GetText = () => "Spectate in this slot";
}
}
var join = template.GetWidget<ButtonWidget>("JOIN");
if (join != null)
{
join.OnMouseUp = _ => { orderManager.IssueOrder(Order.Command("slot " + s.Index)); return true; };
join.IsVisible = () => !s.Closed && s.Bot == null && orderManager.LocalClient.State != Session.ClientState.Ready;
}
var bot = template.GetWidget<LabelWidget>("BOT");
if (bot != null)
bot.IsVisible = () => s.Bot != null;
}
else if (c.Index == orderManager.LocalClient.Index && c.State != Session.ClientState.Ready)
{
template = LocalPlayerTemplate.Clone();
var name = template.GetWidget<TextFieldWidget>("NAME");
name.Text = c.Name;
name.OnEnterKey = () =>
{
name.Text = name.Text.Trim();
if (name.Text.Length == 0)
name.Text = c.Name;
name.LoseFocus();
if (name.Text == c.Name)
return true;
orderManager.IssueOrder(Order.Command("name " + name.Text));
Game.Settings.Player.Name = name.Text;
Game.Settings.Save();
return true;
};
name.OnLoseFocus = () => name.OnEnterKey();
var color = template.GetWidget<ButtonWidget>("COLOR");
color.OnMouseUp = _ => ShowColorDropDown(s, color);
var colorBlock = color.GetWidget<ColorBlockWidget>("COLORBLOCK");
colorBlock.GetColor = () => c.ColorRamp.GetColor(0);
var faction = template.GetWidget<ButtonWidget>("FACTION");
faction.OnMouseDown = _ => ShowRaceDropDown(s, faction);
var factionname = faction.GetWidget<LabelWidget>("FACTIONNAME");
factionname.GetText = () => CountryNames[c.Country];
var factionflag = faction.GetWidget<ImageWidget>("FACTIONFLAG");
factionflag.GetImageName = () => c.Country;
factionflag.GetImageCollection = () => "flags";
var team = template.GetWidget<ButtonWidget>("TEAM");
team.OnMouseDown = _ => ShowTeamDropDown(team);
team.GetText = () => (c.Team == 0) ? "-" : c.Team.ToString();
var status = template.GetWidget<CheckboxWidget>("STATUS");
status.IsChecked = () => c.State == Session.ClientState.Ready;
status.OnChange += CycleReady;
var spectator = template.GetWidget<LabelWidget>("SPECTATOR");
Session.Slot slot1 = slot;
color.IsVisible = () => !slot1.Spectator;
colorBlock.IsVisible = () => !slot1.Spectator;
faction.IsVisible = () => !slot1.Spectator;
factionname.IsVisible = () => !slot1.Spectator;
factionflag.IsVisible = () => !slot1.Spectator;
team.IsVisible = () => !slot1.Spectator;
spectator.IsVisible = () => slot1.Spectator || slot1.Bot != null;
}
else
{
template = RemotePlayerTemplate.Clone();
template.GetWidget<LabelWidget>("NAME").GetText = () => c.Name;
var color = template.GetWidget<ColorBlockWidget>("COLOR");
color.GetColor = () => c.ColorRamp.GetColor(0);
var faction = template.GetWidget<LabelWidget>("FACTION");
var factionname = faction.GetWidget<LabelWidget>("FACTIONNAME");
factionname.GetText = () => CountryNames[c.Country];
var factionflag = faction.GetWidget<ImageWidget>("FACTIONFLAG");
factionflag.GetImageName = () => c.Country;
factionflag.GetImageCollection = () => "flags";
var team = template.GetWidget<LabelWidget>("TEAM");
team.GetText = () => (c.Team == 0) ? "-" : c.Team.ToString();
var status = template.GetWidget<CheckboxWidget>("STATUS");
status.IsChecked = () => c.State == Session.ClientState.Ready;
if (c.Index == orderManager.LocalClient.Index)
status.OnChange += CycleReady;
var spectator = template.GetWidget<LabelWidget>("SPECTATOR");
Session.Slot slot1 = slot;
color.IsVisible = () => !slot1.Spectator;
faction.IsVisible = () => !slot1.Spectator;
factionname.IsVisible = () => !slot1.Spectator;
factionflag.IsVisible = () => !slot1.Spectator;
team.IsVisible = () => !slot1.Spectator;
spectator.IsVisible = () => slot1.Spectator || slot1.Bot != null;
var kickButton = template.GetWidget<ButtonWidget>("KICK");
kickButton.IsVisible = () => Game.IsHost && c.Index != orderManager.LocalClient.Index;
kickButton.OnMouseUp = mi =>
{
orderManager.IssueOrder(Order.Command("kick " + c.Slot));
return true;
};
}
template.Id = "SLOT_{0}".F(s.Index);
template.IsVisible = () => true;
Players.AddChild(template);
}
}
bool SpawnPointAvailable(int index) { return (index == 0) || orderManager.LobbyInfo.Clients.All(c => c.SpawnPoint != index); }
void CycleReady(bool ready)
{
orderManager.IssueOrder(Order.Command("ready"));
}
}
}

View File

@@ -1,90 +1,90 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using System.Collections.Generic;
using OpenRA.FileFormats;
using OpenRA.Network;
using OpenRA.Server;
using OpenRA.Widgets;
using System;
using System.Drawing;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class MainMenuButtonsDelegate : IWidgetDelegate
{
[ObjectCreator.UseCtor]
public MainMenuButtonsDelegate([ObjectCreator.Param] Widget widget)
{
Game.modData.WidgetLoader.LoadWidget( new Dictionary<string,object>(), Widget.RootWidget, "PERF_BG" );
widget.GetWidget("MAINMENU_BUTTON_JOIN").OnMouseUp = mi => { Widget.OpenWindow("JOINSERVER_BG"); return true; };
widget.GetWidget("MAINMENU_BUTTON_CREATE").OnMouseUp = mi => { Widget.OpenWindow("CREATESERVER_BG"); return true; };
widget.GetWidget("MAINMENU_BUTTON_SETTINGS").OnMouseUp = mi => { Widget.OpenWindow("SETTINGS_MENU"); return true; };
widget.GetWidget("MAINMENU_BUTTON_MUSIC").OnMouseUp = mi => { Widget.OpenWindow("MUSIC_MENU"); return true; };
widget.GetWidget("MAINMENU_BUTTON_REPLAY_VIEWER").OnMouseUp = mi => { Widget.OpenWindow("REPLAYBROWSER_BG"); return true; };
widget.GetWidget("MAINMENU_BUTTON_QUIT").OnMouseUp = mi => { Game.Exit(); return true; };
DisplayModSelector();
}
public static void DisplayModSelector()
{
var selector = Game.modData.WidgetLoader.LoadWidget( new Dictionary<string,object>(), Widget.RootWidget, "QUICKMODSWITCHER" );
var switcher = selector.GetWidget<ButtonWidget>("SWITCHER");
switcher.OnMouseDown = _ => ShowModsDropDown(switcher);
switcher.GetText = ActiveModTitle;
selector.GetWidget<LabelWidget>("VERSION").GetText = ActiveModVersion;
}
static string ActiveModTitle()
{
var mod = Game.modData.Manifest.Mods[0];
return Mod.AllMods[mod].Title;
}
static string ActiveModVersion()
{
var mod = Game.modData.Manifest.Mods[0];
return Mod.AllMods[mod].Version;
}
static bool ShowModsDropDown(ButtonWidget selector)
{
var dropDownOptions = new List<Pair<string, Action>>();
foreach (var kv in Mod.AllMods)
{
var modList = new List<string>() { kv.Key };
var m = kv.Key;
while (!string.IsNullOrEmpty(Mod.AllMods[m].Requires))
{
m = Mod.AllMods[m].Requires;
modList.Add(m);
}
dropDownOptions.Add(new Pair<string, Action>( kv.Value.Title,
() => Game.RunAfterTick(() => Game.InitializeWithMods( modList.ToArray() ) )));
}
DropDownButtonWidget.ShowDropDown( selector,
dropDownOptions,
(ac, w) => new LabelWidget
{
Bounds = new Rectangle(0, 0, w, 24),
Text = " {0}".F(ac.First),
OnMouseUp = mi => { ac.Second(); return true; },
});
return true;
}
}
}
#region Copyright & License Information
/*
* Copyright 2007-2011 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System.Collections.Generic;
using OpenRA.FileFormats;
using OpenRA.Network;
using OpenRA.Server;
using OpenRA.Widgets;
using System;
using System.Drawing;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class MainMenuButtonsDelegate : IWidgetDelegate
{
[ObjectCreator.UseCtor]
public MainMenuButtonsDelegate([ObjectCreator.Param] Widget widget)
{
Game.modData.WidgetLoader.LoadWidget( new Dictionary<string,object>(), Widget.RootWidget, "PERF_BG" );
widget.GetWidget("MAINMENU_BUTTON_JOIN").OnMouseUp = mi => { Widget.OpenWindow("JOINSERVER_BG"); return true; };
widget.GetWidget("MAINMENU_BUTTON_CREATE").OnMouseUp = mi => { Widget.OpenWindow("CREATESERVER_BG"); return true; };
widget.GetWidget("MAINMENU_BUTTON_SETTINGS").OnMouseUp = mi => { Widget.OpenWindow("SETTINGS_MENU"); return true; };
widget.GetWidget("MAINMENU_BUTTON_MUSIC").OnMouseUp = mi => { Widget.OpenWindow("MUSIC_MENU"); return true; };
widget.GetWidget("MAINMENU_BUTTON_REPLAY_VIEWER").OnMouseUp = mi => { Widget.OpenWindow("REPLAYBROWSER_BG"); return true; };
widget.GetWidget("MAINMENU_BUTTON_QUIT").OnMouseUp = mi => { Game.Exit(); return true; };
DisplayModSelector();
}
public static void DisplayModSelector()
{
var selector = Game.modData.WidgetLoader.LoadWidget( new Dictionary<string,object>(), Widget.RootWidget, "QUICKMODSWITCHER" );
var switcher = selector.GetWidget<ButtonWidget>("SWITCHER");
switcher.OnMouseDown = _ => ShowModsDropDown(switcher);
switcher.GetText = ActiveModTitle;
selector.GetWidget<LabelWidget>("VERSION").GetText = ActiveModVersion;
}
static string ActiveModTitle()
{
var mod = Game.modData.Manifest.Mods[0];
return Mod.AllMods[mod].Title;
}
static string ActiveModVersion()
{
var mod = Game.modData.Manifest.Mods[0];
return Mod.AllMods[mod].Version;
}
static bool ShowModsDropDown(ButtonWidget selector)
{
var dropDownOptions = new List<Pair<string, Action>>();
foreach (var kv in Mod.AllMods)
{
var modList = new List<string>() { kv.Key };
var m = kv.Key;
while (!string.IsNullOrEmpty(Mod.AllMods[m].Requires))
{
m = Mod.AllMods[m].Requires;
modList.Add(m);
}
dropDownOptions.Add(new Pair<string, Action>( kv.Value.Title,
() => Game.RunAfterTick(() => Game.InitializeWithMods( modList.ToArray() ) )));
}
DropDownButtonWidget.ShowDropDown( selector,
dropDownOptions,
(ac, w) => new LabelWidget
{
Bounds = new Rectangle(0, 0, w, 24),
Text = " {0}".F(ac.First),
OnMouseUp = mi => { ac.Second(); return true; },
});
return true;
}
}
}

View File

@@ -1,116 +1,116 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
#region Copyright & License Information
/*
* Copyright 2007-2011 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System.Drawing;
using System.Linq;
using OpenRA.FileFormats;
using OpenRA.Network;
using OpenRA.Widgets;
using System.IO;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class MapChooserDelegate : IWidgetDelegate
{
Map Map = null;
Widget scrollpanel;
Widget itemTemplate;
[ObjectCreator.UseCtor]
internal MapChooserDelegate(
[ObjectCreator.Param( "widget" )] Widget bg,
[ObjectCreator.Param] OrderManager orderManager,
[ObjectCreator.Param] string mapName )
{
if (mapName != null)
Map = Game.modData.AvailableMaps[mapName];
else
Map = Game.modData.AvailableMaps.FirstOrDefault(m => m.Value.Selectable).Value;
bg.GetWidget<MapPreviewWidget>("MAPCHOOSER_MAP_PREVIEW").Map = () => Map;
bg.GetWidget<LabelWidget>("CURMAP_TITLE").GetText = () => Map.Title;
bg.GetWidget<LabelWidget>("CURMAP_AUTHOR").GetText = () => Map.Author;
bg.GetWidget<LabelWidget>("CURMAP_DESC").GetText = () => Map.Description;
bg.GetWidget<LabelWidget>("CURMAP_DESC_LABEL").IsVisible = () => Map.Description != null;
bg.GetWidget<LabelWidget>("CURMAP_SIZE").GetText = () => "{0}x{1}".F(Map.Bounds.Width, Map.Bounds.Height);
bg.GetWidget<LabelWidget>("CURMAP_THEATER").GetText = () => Rules.TileSets[Map.Tileset].Name;
bg.GetWidget<LabelWidget>("CURMAP_PLAYERS").GetText = () => Map.PlayerCount.ToString();
bg.GetWidget<ButtonWidget>("BUTTON_OK").OnMouseUp = mi =>
{
orderManager.IssueOrder(Order.Command("map " + Map.Uid));
Widget.CloseWindow();
return true;
};
bg.GetWidget<ButtonWidget>("BUTTON_CANCEL").OnMouseUp = mi =>
{
Widget.CloseWindow();
return true;
};
bg.GetWidget("BUTTON_INSTALL").IsVisible = () => false;
//bg.GetWidget<ButtonWidget>("BUTTON_INSTALL").OnMouseUp = mi => InstallMap();
scrollpanel = bg.GetWidget<ScrollPanelWidget>("MAP_LIST");
itemTemplate = scrollpanel.GetWidget<ContainerWidget>("MAP_TEMPLATE");
EnumerateMaps();
}
void EnumerateMaps()
{
scrollpanel.RemoveChildren();
foreach (var kv in Game.modData.AvailableMaps.OrderBy(kv => kv.Value.Title).OrderBy(kv => kv.Value.PlayerCount))
{
var map = kv.Value;
if (!map.Selectable)
continue;
var template = itemTemplate.Clone() as ContainerWidget;
template.Id = "MAP_{0}".F(map.Uid);
template.GetBackground = () => ((Map == map) ? "dialog2" : null);
template.OnMouseDown = mi => { if (mi.Button != MouseButton.Left) return false; Map = map; return true; };
template.IsVisible = () => true;
template.GetWidget<LabelWidget>("TITLE").GetText = () => map.Title;
template.GetWidget<LabelWidget>("PLAYERS").GetText = () => "{0}".F(map.PlayerCount);
template.GetWidget<LabelWidget>("TYPE").GetText = () => map.Type;
scrollpanel.AddChild(template);
}
}
bool InstallMap()
{
Game.Utilities.PromptFilepathAsync("Select an OpenRA map file", path =>
{
if (!string.IsNullOrEmpty(path))
Game.RunAfterTick(() => InstallMapInner(path));
});
return true;
}
void InstallMapInner(string path)
{
var toPath = "{0}{1}maps{1}{2}{1}{3}"
.F(Game.SupportDir,Path.DirectorySeparatorChar,
Game.modData.Manifest.Mods[0],
Path.GetFileName(path));
// Create directory if required
var dir = Path.GetDirectoryName(toPath);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
// TODO: Attempt to mount the map and verify that
// it is a valid Game.modData.Manifest.Mods[0] map.
File.Copy(path, toPath, true);
Game.modData.ReloadMaps();
EnumerateMaps();
}
}
using OpenRA.FileFormats;
using OpenRA.Network;
using OpenRA.Widgets;
using System.IO;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class MapChooserDelegate : IWidgetDelegate
{
Map Map = null;
Widget scrollpanel;
Widget itemTemplate;
[ObjectCreator.UseCtor]
internal MapChooserDelegate(
[ObjectCreator.Param( "widget" )] Widget bg,
[ObjectCreator.Param] OrderManager orderManager,
[ObjectCreator.Param] string mapName )
{
if (mapName != null)
Map = Game.modData.AvailableMaps[mapName];
else
Map = Game.modData.AvailableMaps.FirstOrDefault(m => m.Value.Selectable).Value;
bg.GetWidget<MapPreviewWidget>("MAPCHOOSER_MAP_PREVIEW").Map = () => Map;
bg.GetWidget<LabelWidget>("CURMAP_TITLE").GetText = () => Map.Title;
bg.GetWidget<LabelWidget>("CURMAP_AUTHOR").GetText = () => Map.Author;
bg.GetWidget<LabelWidget>("CURMAP_DESC").GetText = () => Map.Description;
bg.GetWidget<LabelWidget>("CURMAP_DESC_LABEL").IsVisible = () => Map.Description != null;
bg.GetWidget<LabelWidget>("CURMAP_SIZE").GetText = () => "{0}x{1}".F(Map.Bounds.Width, Map.Bounds.Height);
bg.GetWidget<LabelWidget>("CURMAP_THEATER").GetText = () => Rules.TileSets[Map.Tileset].Name;
bg.GetWidget<LabelWidget>("CURMAP_PLAYERS").GetText = () => Map.PlayerCount.ToString();
bg.GetWidget<ButtonWidget>("BUTTON_OK").OnMouseUp = mi =>
{
orderManager.IssueOrder(Order.Command("map " + Map.Uid));
Widget.CloseWindow();
return true;
};
bg.GetWidget<ButtonWidget>("BUTTON_CANCEL").OnMouseUp = mi =>
{
Widget.CloseWindow();
return true;
};
bg.GetWidget("BUTTON_INSTALL").IsVisible = () => false;
//bg.GetWidget<ButtonWidget>("BUTTON_INSTALL").OnMouseUp = mi => InstallMap();
scrollpanel = bg.GetWidget<ScrollPanelWidget>("MAP_LIST");
itemTemplate = scrollpanel.GetWidget<ContainerWidget>("MAP_TEMPLATE");
EnumerateMaps();
}
void EnumerateMaps()
{
scrollpanel.RemoveChildren();
foreach (var kv in Game.modData.AvailableMaps.OrderBy(kv => kv.Value.Title).OrderBy(kv => kv.Value.PlayerCount))
{
var map = kv.Value;
if (!map.Selectable)
continue;
var template = itemTemplate.Clone() as ContainerWidget;
template.Id = "MAP_{0}".F(map.Uid);
template.GetBackground = () => ((Map == map) ? "dialog2" : null);
template.OnMouseDown = mi => { if (mi.Button != MouseButton.Left) return false; Map = map; return true; };
template.IsVisible = () => true;
template.GetWidget<LabelWidget>("TITLE").GetText = () => map.Title;
template.GetWidget<LabelWidget>("PLAYERS").GetText = () => "{0}".F(map.PlayerCount);
template.GetWidget<LabelWidget>("TYPE").GetText = () => map.Type;
scrollpanel.AddChild(template);
}
}
bool InstallMap()
{
Game.Utilities.PromptFilepathAsync("Select an OpenRA map file", path =>
{
if (!string.IsNullOrEmpty(path))
Game.RunAfterTick(() => InstallMapInner(path));
});
return true;
}
void InstallMapInner(string path)
{
var toPath = "{0}{1}maps{1}{2}{1}{3}"
.F(Game.SupportDir,Path.DirectorySeparatorChar,
Game.modData.Manifest.Mods[0],
Path.GetFileName(path));
// Create directory if required
var dir = Path.GetDirectoryName(toPath);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
// TODO: Attempt to mount the map and verify that
// it is a valid Game.modData.Manifest.Mods[0] map.
File.Copy(path, toPath, true);
Game.modData.ReloadMaps();
EnumerateMaps();
}
}
}

View File

@@ -1,162 +1,162 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
#region Copyright & License Information
/*
* Copyright 2007-2011 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System.Drawing;
using System.Linq;
using OpenRA.FileFormats;
using OpenRA.Support;
using OpenRA.Widgets;
using System.Linq;
using OpenRA.FileFormats;
using OpenRA.Support;
using OpenRA.Widgets;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class MusicPlayerDelegate : IWidgetDelegate
{
string CurrentSong = null;
public MusicPlayerDelegate()
{
var bg = Widget.RootWidget.GetWidget("MUSIC_MENU");
CurrentSong = GetNextSong();
bg.GetWidget("BUTTON_CLOSE").OnMouseUp = mi => {
Game.Settings.Save();
Widget.CloseWindow();
return true;
};
var installed = Rules.Music.Count(m => m.Value.Exists) > 1;
/*
// Hack around some mix packages including hellmarch for ra
bg.GetWidget("BUTTON_INSTALL").IsVisible = () => !installed;
bg.GetWidget("BUTTON_INSTALL").OnMouseUp = mi => {
return true;
};
*/
bg.GetWidget("BUTTON_INSTALL").IsVisible = () => false;
bg.GetWidget("BUTTON_PLAY").OnMouseUp = mi =>
{
if (CurrentSong == null)
return true;
Sound.PlayMusicThen(Rules.Music[CurrentSong].Filename,
() => bg.GetWidget(Game.Settings.Sound.Repeat ? "BUTTON_PLAY" : "BUTTON_NEXT").OnMouseUp(new MouseInput()));
bg.GetWidget("BUTTON_PLAY").Visible = false;
bg.GetWidget("BUTTON_PAUSE").Visible = true;
return true;
};
bg.GetWidget("BUTTON_PAUSE").OnMouseUp = mi =>
{
Sound.PauseMusic();
bg.GetWidget("BUTTON_PAUSE").Visible = false;
bg.GetWidget("BUTTON_PLAY").Visible = true;
return true;
};
bg.GetWidget("BUTTON_STOP").OnMouseUp = mi =>
{
Sound.StopMusic();
bg.GetWidget("BUTTON_PAUSE").Visible = false;
bg.GetWidget("BUTTON_PLAY").Visible = true;
return true;
};
bg.GetWidget("BUTTON_NEXT").OnMouseUp = mi =>
{
CurrentSong = GetNextSong();
return bg.GetWidget("BUTTON_PLAY").OnMouseUp(mi);
};
bg.GetWidget("BUTTON_PREV").OnMouseUp = mi =>
{
CurrentSong = GetPrevSong();
return bg.GetWidget("BUTTON_PLAY").OnMouseUp(mi);
};
bg.GetWidget<CheckboxWidget>("SHUFFLE").Bind(Game.Settings.Sound, "Shuffle");
bg.GetWidget<CheckboxWidget>("REPEAT").Bind(Game.Settings.Sound, "Repeat");
bg.GetWidget<LabelWidget>("TIME").GetText = () =>
{
if (CurrentSong == null)
return "";
return "{0:D2}:{1:D2} / {2:D2}:{3:D2}".F((int)Sound.MusicSeekPosition / 60, (int)Sound.MusicSeekPosition % 60,
Rules.Music[CurrentSong].Length / 60, Rules.Music[CurrentSong].Length % 60);
};
var ml = bg.GetWidget<ScrollPanelWidget>("MUSIC_LIST");
var itemTemplate = ml.GetWidget<LabelWidget>("MUSIC_TEMPLATE");
if (!Rules.Music.Where(m => m.Value.Exists).Any())
{
itemTemplate.IsVisible = () => true;
itemTemplate.GetWidget<LabelWidget>("TITLE").GetText = () => "No Music Installed";
itemTemplate.GetWidget<LabelWidget>("TITLE").Align = LabelWidget.TextAlign.Center;
}
foreach (var kv in Rules.Music.Where(m => m.Value.Exists))
{
var song = kv.Key;
if (CurrentSong == null)
CurrentSong = song;
var template = itemTemplate.Clone() as LabelWidget;
template.Id = "SONG_{0}".F(song);
template.GetBackground = () => ((song == CurrentSong) ? "dialog2" : null);
template.OnMouseDown = mi =>
{
if (mi.Button != MouseButton.Left) return false;
CurrentSong = song;
bg.GetWidget("BUTTON_PLAY").OnMouseUp(mi);
return true;
};
template.IsVisible = () => true;
template.GetWidget<LabelWidget>("TITLE").GetText = () => " " + Rules.Music[song].Title;
template.GetWidget<LabelWidget>("LENGTH").GetText = () => "{0:D1}:{1:D2}".F(Rules.Music[song].Length / 60, Rules.Music[song].Length % 60);
ml.AddChild(template);
}
}
string GetNextSong()
{
var songs = Rules.Music.Where(a => a.Value.Exists)
.Select(a => a.Key);
if (!songs.Any())
return null;
if (Game.Settings.Sound.Shuffle)
return songs.Random(Game.CosmeticRandom);
return songs.SkipWhile(m => m != CurrentSong)
.Skip(1).FirstOrDefault() ?? songs.FirstOrDefault();
}
string GetPrevSong()
{
var songs = Rules.Music.Where(a => a.Value.Exists)
.Select(a => a.Key).Reverse();
if (!songs.Any())
return null;
if (Game.Settings.Sound.Shuffle)
return songs.Random(Game.CosmeticRandom);
return songs.SkipWhile(m => m != CurrentSong)
.Skip(1).FirstOrDefault() ?? songs.FirstOrDefault();
}
{
public class MusicPlayerDelegate : IWidgetDelegate
{
string CurrentSong = null;
public MusicPlayerDelegate()
{
var bg = Widget.RootWidget.GetWidget("MUSIC_MENU");
CurrentSong = GetNextSong();
bg.GetWidget("BUTTON_CLOSE").OnMouseUp = mi => {
Game.Settings.Save();
Widget.CloseWindow();
return true;
};
var installed = Rules.Music.Count(m => m.Value.Exists) > 1;
/*
// Hack around some mix packages including hellmarch for ra
bg.GetWidget("BUTTON_INSTALL").IsVisible = () => !installed;
bg.GetWidget("BUTTON_INSTALL").OnMouseUp = mi => {
return true;
};
*/
bg.GetWidget("BUTTON_INSTALL").IsVisible = () => false;
bg.GetWidget("BUTTON_PLAY").OnMouseUp = mi =>
{
if (CurrentSong == null)
return true;
Sound.PlayMusicThen(Rules.Music[CurrentSong].Filename,
() => bg.GetWidget(Game.Settings.Sound.Repeat ? "BUTTON_PLAY" : "BUTTON_NEXT").OnMouseUp(new MouseInput()));
bg.GetWidget("BUTTON_PLAY").Visible = false;
bg.GetWidget("BUTTON_PAUSE").Visible = true;
return true;
};
bg.GetWidget("BUTTON_PAUSE").OnMouseUp = mi =>
{
Sound.PauseMusic();
bg.GetWidget("BUTTON_PAUSE").Visible = false;
bg.GetWidget("BUTTON_PLAY").Visible = true;
return true;
};
bg.GetWidget("BUTTON_STOP").OnMouseUp = mi =>
{
Sound.StopMusic();
bg.GetWidget("BUTTON_PAUSE").Visible = false;
bg.GetWidget("BUTTON_PLAY").Visible = true;
return true;
};
bg.GetWidget("BUTTON_NEXT").OnMouseUp = mi =>
{
CurrentSong = GetNextSong();
return bg.GetWidget("BUTTON_PLAY").OnMouseUp(mi);
};
bg.GetWidget("BUTTON_PREV").OnMouseUp = mi =>
{
CurrentSong = GetPrevSong();
return bg.GetWidget("BUTTON_PLAY").OnMouseUp(mi);
};
bg.GetWidget<CheckboxWidget>("SHUFFLE").Bind(Game.Settings.Sound, "Shuffle");
bg.GetWidget<CheckboxWidget>("REPEAT").Bind(Game.Settings.Sound, "Repeat");
bg.GetWidget<LabelWidget>("TIME").GetText = () =>
{
if (CurrentSong == null)
return "";
return "{0:D2}:{1:D2} / {2:D2}:{3:D2}".F((int)Sound.MusicSeekPosition / 60, (int)Sound.MusicSeekPosition % 60,
Rules.Music[CurrentSong].Length / 60, Rules.Music[CurrentSong].Length % 60);
};
var ml = bg.GetWidget<ScrollPanelWidget>("MUSIC_LIST");
var itemTemplate = ml.GetWidget<LabelWidget>("MUSIC_TEMPLATE");
if (!Rules.Music.Where(m => m.Value.Exists).Any())
{
itemTemplate.IsVisible = () => true;
itemTemplate.GetWidget<LabelWidget>("TITLE").GetText = () => "No Music Installed";
itemTemplate.GetWidget<LabelWidget>("TITLE").Align = LabelWidget.TextAlign.Center;
}
foreach (var kv in Rules.Music.Where(m => m.Value.Exists))
{
var song = kv.Key;
if (CurrentSong == null)
CurrentSong = song;
var template = itemTemplate.Clone() as LabelWidget;
template.Id = "SONG_{0}".F(song);
template.GetBackground = () => ((song == CurrentSong) ? "dialog2" : null);
template.OnMouseDown = mi =>
{
if (mi.Button != MouseButton.Left) return false;
CurrentSong = song;
bg.GetWidget("BUTTON_PLAY").OnMouseUp(mi);
return true;
};
template.IsVisible = () => true;
template.GetWidget<LabelWidget>("TITLE").GetText = () => " " + Rules.Music[song].Title;
template.GetWidget<LabelWidget>("LENGTH").GetText = () => "{0:D1}:{1:D2}".F(Rules.Music[song].Length / 60, Rules.Music[song].Length % 60);
ml.AddChild(template);
}
}
string GetNextSong()
{
var songs = Rules.Music.Where(a => a.Value.Exists)
.Select(a => a.Key);
if (!songs.Any())
return null;
if (Game.Settings.Sound.Shuffle)
return songs.Random(Game.CosmeticRandom);
return songs.SkipWhile(m => m != CurrentSong)
.Skip(1).FirstOrDefault() ?? songs.FirstOrDefault();
}
string GetPrevSong()
{
var songs = Rules.Music.Where(a => a.Value.Exists)
.Select(a => a.Key).Reverse();
if (!songs.Any())
return null;
if (Game.Settings.Sound.Shuffle)
return songs.Random(Game.CosmeticRandom);
return songs.SkipWhile(m => m != CurrentSong)
.Skip(1).FirstOrDefault() ?? songs.FirstOrDefault();
}
}
}

View File

@@ -1,24 +1,24 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* Copyright 2007-2011 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
* see COPYING.
*/
#endregion
using OpenRA;
using OpenRA.Mods.RA.Orders;
#endregion
using OpenRA;
using OpenRA.Mods.RA.Orders;
using OpenRA.Widgets;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class OrderButtonsChromeDelegate : IWidgetDelegate
{
{
[ObjectCreator.UseCtor]
public OrderButtonsChromeDelegate( [ObjectCreator.Param] World world )
{
{
var r = Widget.RootWidget;
var gameRoot = r.GetWidget("INGAME_ROOT");

View File

@@ -1,35 +1,35 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#region Copyright & License Information
/*
* Copyright 2007-2011 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using OpenRA.Support;
using OpenRA.Widgets;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class PerfDebugDelegate : IWidgetDelegate
{
public PerfDebugDelegate()
{
var r = Widget.RootWidget;
var perfRoot = r.GetWidget("PERF_BG");
perfRoot.IsVisible = () => perfRoot.Visible && Game.Settings.Debug.PerfGraph;
// Perf text
var perfText = perfRoot.GetWidget<LabelWidget>("TEXT");
perfText.GetText = () => "Render {0} ({5}={2:F1} ms)\nTick {4} ({3:F1} ms)".F(
Game.RenderFrame,
Game.NetFrameNumber,
PerfHistory.items["render"].LastValue,
PerfHistory.items["tick_time"].LastValue,
Game.LocalTick,
PerfHistory.items["batches"].LastValue);
}
}
using OpenRA.Support;
using OpenRA.Widgets;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class PerfDebugDelegate : IWidgetDelegate
{
public PerfDebugDelegate()
{
var r = Widget.RootWidget;
var perfRoot = r.GetWidget("PERF_BG");
perfRoot.IsVisible = () => perfRoot.Visible && Game.Settings.Debug.PerfGraph;
// Perf text
var perfText = perfRoot.GetWidget<LabelWidget>("TEXT");
perfText.GetText = () => "Render {0} ({5}={2:F1} ms)\nTick {4} ({3:F1} ms)".F(
Game.RenderFrame,
Game.NetFrameNumber,
PerfHistory.items["render"].LastValue,
PerfHistory.items["tick_time"].LastValue,
Game.LocalTick,
PerfHistory.items["batches"].LastValue);
}
}
}

View File

@@ -1,150 +1,150 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using System;
using System.Drawing;
using System.IO;
using System.Linq;
using OpenRA.FileFormats;
using OpenRA.Network;
using OpenRA.Widgets;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class ReplayBrowserDelegate : IWidgetDelegate
{
Widget widget;
[ObjectCreator.UseCtor]
public ReplayBrowserDelegate( [ObjectCreator.Param] Widget widget )
{
this.widget = widget;
widget.GetWidget("CANCEL_BUTTON").OnMouseUp = mi =>
{
Widget.CloseWindow();
return true;
};
/* find some replays? */
var rl = widget.GetWidget<ScrollPanelWidget>("REPLAY_LIST");
var replayDir = Path.Combine(Game.SupportDir, "Replays");
var template = widget.GetWidget<LabelWidget>("REPLAY_TEMPLATE");
CurrentReplay = null;
rl.RemoveChildren();
foreach (var replayFile in Directory.GetFiles(replayDir, "*.rep").Reverse())
AddReplay(rl, replayFile, template);
widget.GetWidget("WATCH_BUTTON").OnMouseUp = mi =>
{
if (currentReplay != null)
{
Widget.CloseWindow();
Game.JoinReplay(CurrentReplay);
}
return true;
};
widget.GetWidget("REPLAY_INFO").IsVisible = () => currentReplay != null;
}
Map MapFromSummary(ReplaySummary rs)
{
if (rs.LobbyInfo == null)
return null;
var map = rs.LobbyInfo.GlobalSettings.Map;
if (!Game.modData.AvailableMaps.ContainsKey(map))
return null;
return Game.modData.AvailableMaps[map];
}
string currentReplay = null;
string CurrentReplay
{
get { return currentReplay; }
set
{
currentReplay = value;
if (currentReplay != null)
{
try
{
var summary = new ReplaySummary(currentReplay);
var mapStub = MapFromSummary(summary);
widget.GetWidget<LabelWidget>("DURATION").GetText =
() => WidgetUtils.FormatTime(summary.Duration * 3 /* todo: 3:1 ratio isnt always true. */);
widget.GetWidget<MapPreviewWidget>("MAP_PREVIEW").Map = () => mapStub;
widget.GetWidget<LabelWidget>("MAP_TITLE").GetText =
() => mapStub != null ? mapStub.Title : "(Unknown Map)";
}
catch(Exception e)
{
Log.Write("debug", "Exception while parsing replay: {0}", e.ToString());
currentReplay = null;
}
}
}
}
void AddReplay(ScrollPanelWidget list, string filename, LabelWidget template)
{
var entry = template.Clone() as LabelWidget;
entry.Id = "REPLAY_";
entry.GetText = () => " {0}".F(Path.GetFileName(filename));
entry.GetBackground = () => (CurrentReplay == filename) ? "dialog2" : null;
entry.OnMouseDown = mi => { if (mi.Button != MouseButton.Left) return false; CurrentReplay = filename; return true; };
entry.IsVisible = () => true;
list.AddChild(entry);
}
}
/* a maze of twisty little hacks,... */
class ReplaySummary
{
public readonly int Duration;
public readonly Session LobbyInfo;
public ReplaySummary(string filename)
{
var lastFrame = 0;
var hasSeenGameStart = false;
var lobbyInfo = null as Session;
using (var conn = new ReplayConnection(filename))
conn.Receive((client, packet) =>
{
var frame = BitConverter.ToInt32(packet, 0);
if (packet.Length == 5 && packet[4] == 0xBF)
return; // disconnect
else if (packet.Length >= 5 && packet[4] == 0x65)
return; // sync
else if (frame == 0)
{
/* decode this to recover lobbyinfo, etc */
var orders = packet.ToOrderList(null);
foreach (var o in orders)
if (o.OrderString == "StartGame")
hasSeenGameStart = true;
else if (o.OrderString == "SyncInfo" && !hasSeenGameStart)
lobbyInfo = Session.Deserialize(o.TargetString);
}
else
lastFrame = Math.Max(lastFrame, frame);
});
Duration = lastFrame;
LobbyInfo = lobbyInfo;
}
}
}
#region Copyright & License Information
/*
* Copyright 2007-2011 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System;
using System.Drawing;
using System.IO;
using System.Linq;
using OpenRA.FileFormats;
using OpenRA.Network;
using OpenRA.Widgets;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class ReplayBrowserDelegate : IWidgetDelegate
{
Widget widget;
[ObjectCreator.UseCtor]
public ReplayBrowserDelegate( [ObjectCreator.Param] Widget widget )
{
this.widget = widget;
widget.GetWidget("CANCEL_BUTTON").OnMouseUp = mi =>
{
Widget.CloseWindow();
return true;
};
/* find some replays? */
var rl = widget.GetWidget<ScrollPanelWidget>("REPLAY_LIST");
var replayDir = Path.Combine(Game.SupportDir, "Replays");
var template = widget.GetWidget<LabelWidget>("REPLAY_TEMPLATE");
CurrentReplay = null;
rl.RemoveChildren();
foreach (var replayFile in Directory.GetFiles(replayDir, "*.rep").Reverse())
AddReplay(rl, replayFile, template);
widget.GetWidget("WATCH_BUTTON").OnMouseUp = mi =>
{
if (currentReplay != null)
{
Widget.CloseWindow();
Game.JoinReplay(CurrentReplay);
}
return true;
};
widget.GetWidget("REPLAY_INFO").IsVisible = () => currentReplay != null;
}
Map MapFromSummary(ReplaySummary rs)
{
if (rs.LobbyInfo == null)
return null;
var map = rs.LobbyInfo.GlobalSettings.Map;
if (!Game.modData.AvailableMaps.ContainsKey(map))
return null;
return Game.modData.AvailableMaps[map];
}
string currentReplay = null;
string CurrentReplay
{
get { return currentReplay; }
set
{
currentReplay = value;
if (currentReplay != null)
{
try
{
var summary = new ReplaySummary(currentReplay);
var mapStub = MapFromSummary(summary);
widget.GetWidget<LabelWidget>("DURATION").GetText =
() => WidgetUtils.FormatTime(summary.Duration * 3 /* todo: 3:1 ratio isnt always true. */);
widget.GetWidget<MapPreviewWidget>("MAP_PREVIEW").Map = () => mapStub;
widget.GetWidget<LabelWidget>("MAP_TITLE").GetText =
() => mapStub != null ? mapStub.Title : "(Unknown Map)";
}
catch(Exception e)
{
Log.Write("debug", "Exception while parsing replay: {0}", e.ToString());
currentReplay = null;
}
}
}
}
void AddReplay(ScrollPanelWidget list, string filename, LabelWidget template)
{
var entry = template.Clone() as LabelWidget;
entry.Id = "REPLAY_";
entry.GetText = () => " {0}".F(Path.GetFileName(filename));
entry.GetBackground = () => (CurrentReplay == filename) ? "dialog2" : null;
entry.OnMouseDown = mi => { if (mi.Button != MouseButton.Left) return false; CurrentReplay = filename; return true; };
entry.IsVisible = () => true;
list.AddChild(entry);
}
}
/* a maze of twisty little hacks,... */
class ReplaySummary
{
public readonly int Duration;
public readonly Session LobbyInfo;
public ReplaySummary(string filename)
{
var lastFrame = 0;
var hasSeenGameStart = false;
var lobbyInfo = null as Session;
using (var conn = new ReplayConnection(filename))
conn.Receive((client, packet) =>
{
var frame = BitConverter.ToInt32(packet, 0);
if (packet.Length == 5 && packet[4] == 0xBF)
return; // disconnect
else if (packet.Length >= 5 && packet[4] == 0x65)
return; // sync
else if (frame == 0)
{
/* decode this to recover lobbyinfo, etc */
var orders = packet.ToOrderList(null);
foreach (var o in orders)
if (o.OrderString == "StartGame")
hasSeenGameStart = true;
else if (o.OrderString == "SyncInfo" && !hasSeenGameStart)
lobbyInfo = Session.Deserialize(o.TargetString);
}
else
lastFrame = Math.Max(lastFrame, frame);
});
Duration = lastFrame;
LobbyInfo = lobbyInfo;
}
}
}

View File

@@ -1,215 +1,215 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using OpenRA.FileFormats;
using OpenRA.Server;
using OpenRA.Widgets;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class ServerBrowserDelegate : IWidgetDelegate
{
static List<Widget> GameButtons = new List<Widget>();
GameServer currentServer = null;
Widget ServerTemplate;
[ObjectCreator.UseCtor]
public ServerBrowserDelegate( [ObjectCreator.Param] Widget widget )
{
var bg = widget.GetWidget("JOINSERVER_BG");
MasterServerQuery.OnComplete += games => RefreshServerList(games);
bg.GetWidget("JOINSERVER_PROGRESS_TITLE").Visible = true;
bg.GetWidget<LabelWidget>("JOINSERVER_PROGRESS_TITLE").Text = "Fetching game list...";
bg.Children.RemoveAll(a => GameButtons.Contains(a));
GameButtons.Clear();
MasterServerQuery.Refresh(Game.Settings.Server.MasterServer);
bg.GetWidget("SERVER_INFO").IsVisible = () => currentServer != null;
var preview = bg.GetWidget<MapPreviewWidget>("MAP_PREVIEW");
preview.Map = () => CurrentMap();
preview.IsVisible = () => CurrentMap() != null;
bg.GetWidget<LabelWidget>("SERVER_IP").GetText = () => currentServer.Address;
bg.GetWidget<LabelWidget>("SERVER_MODS").GetText = () => GenerateModsLabel();
bg.GetWidget<LabelWidget>("MAP_TITLE").GetText = () => (CurrentMap() != null) ? CurrentMap().Title : "Unknown";
bg.GetWidget<LabelWidget>("MAP_PLAYERS").GetText = () =>
{
if (currentServer == null)
return "";
string ret = currentServer.Players.ToString();
if (CurrentMap() != null)
ret += "/" + CurrentMap().PlayerCount.ToString();
return ret;
};
var sl = bg.GetWidget<ScrollPanelWidget>("SERVER_LIST");
ServerTemplate = sl.GetWidget<LabelWidget>("SERVER_TEMPLATE");
bg.GetWidget("REFRESH_BUTTON").OnMouseUp = mi =>
{
bg.GetWidget("JOINSERVER_PROGRESS_TITLE").Visible = true;
bg.GetWidget<LabelWidget>("JOINSERVER_PROGRESS_TITLE").Text = "Fetching game list...";
bg.Children.RemoveAll(a => GameButtons.Contains(a));
GameButtons.Clear();
MasterServerQuery.Refresh(Game.Settings.Server.MasterServer);
return true;
};
bg.GetWidget("CANCEL_BUTTON").OnMouseUp = mi =>
{
Widget.CloseWindow();
return true;
};
bg.GetWidget("DIRECTCONNECT_BUTTON").OnMouseUp = mi =>
{
Widget.CloseWindow();
Widget.OpenWindow("DIRECTCONNECT_BG");
return true;
};
bg.GetWidget("JOIN_BUTTON").OnMouseUp = mi =>
{
if (currentServer == null)
return false;
Widget.CloseWindow();
Game.JoinServer(currentServer.Address.Split(':')[0], int.Parse(currentServer.Address.Split(':')[1]));
return true;
};
}
Map CurrentMap()
{
return (currentServer == null || !Game.modData.AvailableMaps.ContainsKey(currentServer.Map))
? null : Game.modData.AvailableMaps[currentServer.Map];
}
string GenerateModsLabel()
{
return string.Join("\n", currentServer.Mods
.Select( m => m.Split('@')[0] )
.Select(m =>
Mod.AllMods.ContainsKey(m) ? string.Format("{0} ({1})", Mod.AllMods[m].Title, Mod.AllMods[m].Version)
: string.Format("Unknown Mod: {0}",m)).ToArray());
}
void RefreshServerList(IEnumerable<GameServer> games)
{
var r = Widget.RootWidget;
var bg = r.GetWidget("JOINSERVER_BG");
if (bg == null) // We got a MasterServer reply AFTER the browser is gone, just return to prevent crash - Gecko
return;
var sl = bg.GetWidget<ScrollPanelWidget>("SERVER_LIST");
sl.RemoveChildren();
currentServer = null;
if (games == null)
{
r.GetWidget("JOINSERVER_PROGRESS_TITLE").Visible = true;
r.GetWidget<LabelWidget>("JOINSERVER_PROGRESS_TITLE").Text = "Failed to contact master server.";
return;
}
var gamesWaiting = games.Where(g => CanJoin(g));
if (gamesWaiting.Count() == 0)
{
r.GetWidget("JOINSERVER_PROGRESS_TITLE").Visible = true;
r.GetWidget<LabelWidget>("JOINSERVER_PROGRESS_TITLE").Text = "No games found.";
return;
}
r.GetWidget("JOINSERVER_PROGRESS_TITLE").Visible = false;
int i = 0;
foreach (var loop in gamesWaiting)
{
var game = loop;
var template = ServerTemplate.Clone() as LabelWidget;
template.Id = "JOIN_GAME_{0}".F(i);
template.GetText = () => " {0} ({1})".F( /* /8 = hack */
game.Name,
game.Address);
template.GetBackground = () => (currentServer == game) ? "dialog2" : null;
template.OnMouseDown = mi => { if (mi.Button != MouseButton.Left) return false; currentServer = game; return true; };
template.IsVisible = () => true;
sl.AddChild(template);
if (i == 0) currentServer = game;
i++;
}
}
bool CanJoin(GameServer game)
{
//"waiting for players"
if (game.State != 1)
return false;
// Mods won't match if there are a different number
if (Game.CurrentMods.Count != game.Mods.Count())
return false;
return game.Mods.All( m => m.Contains('@')) && game.Mods.Select( m => Pair.New(m.Split('@')[0], m.Split('@')[1]))
.All(kv => Game.CurrentMods.ContainsKey(kv.First) &&
(kv.Second == "{DEV_VERSION}" || Game.CurrentMods[kv.First].Version == "{DEV_VERSION}" || kv.Second == Game.CurrentMods[kv.First].Version));
}
}
public class DirectConnectDelegate : IWidgetDelegate
{
[ObjectCreator.UseCtor]
public DirectConnectDelegate( [ObjectCreator.Param] Widget widget )
{
var dc = widget.GetWidget("DIRECTCONNECT_BG");
dc.GetWidget<TextFieldWidget>("SERVER_ADDRESS").Text = Game.Settings.Player.LastServer;
dc.GetWidget("JOIN_BUTTON").OnMouseUp = mi =>
{
var address = dc.GetWidget<TextFieldWidget>("SERVER_ADDRESS").Text;
var cpts = address.Split(':').ToArray();
if (cpts.Length != 2)
return true;
Game.Settings.Player.LastServer = address;
Game.Settings.Save();
Widget.CloseWindow();
Game.JoinServer(cpts[0], int.Parse(cpts[1]));
return true;
};
dc.GetWidget("CANCEL_BUTTON").OnMouseUp = mi =>
{
Widget.CloseWindow();
Widget.OpenWindow("MAINMENU_BG");
return true;
};
}
}
}
#region Copyright & License Information
/*
* Copyright 2007-2011 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using OpenRA.FileFormats;
using OpenRA.Server;
using OpenRA.Widgets;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class ServerBrowserDelegate : IWidgetDelegate
{
static List<Widget> GameButtons = new List<Widget>();
GameServer currentServer = null;
Widget ServerTemplate;
[ObjectCreator.UseCtor]
public ServerBrowserDelegate( [ObjectCreator.Param] Widget widget )
{
var bg = widget.GetWidget("JOINSERVER_BG");
MasterServerQuery.OnComplete += games => RefreshServerList(games);
bg.GetWidget("JOINSERVER_PROGRESS_TITLE").Visible = true;
bg.GetWidget<LabelWidget>("JOINSERVER_PROGRESS_TITLE").Text = "Fetching game list...";
bg.Children.RemoveAll(a => GameButtons.Contains(a));
GameButtons.Clear();
MasterServerQuery.Refresh(Game.Settings.Server.MasterServer);
bg.GetWidget("SERVER_INFO").IsVisible = () => currentServer != null;
var preview = bg.GetWidget<MapPreviewWidget>("MAP_PREVIEW");
preview.Map = () => CurrentMap();
preview.IsVisible = () => CurrentMap() != null;
bg.GetWidget<LabelWidget>("SERVER_IP").GetText = () => currentServer.Address;
bg.GetWidget<LabelWidget>("SERVER_MODS").GetText = () => GenerateModsLabel();
bg.GetWidget<LabelWidget>("MAP_TITLE").GetText = () => (CurrentMap() != null) ? CurrentMap().Title : "Unknown";
bg.GetWidget<LabelWidget>("MAP_PLAYERS").GetText = () =>
{
if (currentServer == null)
return "";
string ret = currentServer.Players.ToString();
if (CurrentMap() != null)
ret += "/" + CurrentMap().PlayerCount.ToString();
return ret;
};
var sl = bg.GetWidget<ScrollPanelWidget>("SERVER_LIST");
ServerTemplate = sl.GetWidget<LabelWidget>("SERVER_TEMPLATE");
bg.GetWidget("REFRESH_BUTTON").OnMouseUp = mi =>
{
bg.GetWidget("JOINSERVER_PROGRESS_TITLE").Visible = true;
bg.GetWidget<LabelWidget>("JOINSERVER_PROGRESS_TITLE").Text = "Fetching game list...";
bg.Children.RemoveAll(a => GameButtons.Contains(a));
GameButtons.Clear();
MasterServerQuery.Refresh(Game.Settings.Server.MasterServer);
return true;
};
bg.GetWidget("CANCEL_BUTTON").OnMouseUp = mi =>
{
Widget.CloseWindow();
return true;
};
bg.GetWidget("DIRECTCONNECT_BUTTON").OnMouseUp = mi =>
{
Widget.CloseWindow();
Widget.OpenWindow("DIRECTCONNECT_BG");
return true;
};
bg.GetWidget("JOIN_BUTTON").OnMouseUp = mi =>
{
if (currentServer == null)
return false;
Widget.CloseWindow();
Game.JoinServer(currentServer.Address.Split(':')[0], int.Parse(currentServer.Address.Split(':')[1]));
return true;
};
}
Map CurrentMap()
{
return (currentServer == null || !Game.modData.AvailableMaps.ContainsKey(currentServer.Map))
? null : Game.modData.AvailableMaps[currentServer.Map];
}
string GenerateModsLabel()
{
return string.Join("\n", currentServer.Mods
.Select( m => m.Split('@')[0] )
.Select(m =>
Mod.AllMods.ContainsKey(m) ? string.Format("{0} ({1})", Mod.AllMods[m].Title, Mod.AllMods[m].Version)
: string.Format("Unknown Mod: {0}",m)).ToArray());
}
void RefreshServerList(IEnumerable<GameServer> games)
{
var r = Widget.RootWidget;
var bg = r.GetWidget("JOINSERVER_BG");
if (bg == null) // We got a MasterServer reply AFTER the browser is gone, just return to prevent crash - Gecko
return;
var sl = bg.GetWidget<ScrollPanelWidget>("SERVER_LIST");
sl.RemoveChildren();
currentServer = null;
if (games == null)
{
r.GetWidget("JOINSERVER_PROGRESS_TITLE").Visible = true;
r.GetWidget<LabelWidget>("JOINSERVER_PROGRESS_TITLE").Text = "Failed to contact master server.";
return;
}
var gamesWaiting = games.Where(g => CanJoin(g));
if (gamesWaiting.Count() == 0)
{
r.GetWidget("JOINSERVER_PROGRESS_TITLE").Visible = true;
r.GetWidget<LabelWidget>("JOINSERVER_PROGRESS_TITLE").Text = "No games found.";
return;
}
r.GetWidget("JOINSERVER_PROGRESS_TITLE").Visible = false;
int i = 0;
foreach (var loop in gamesWaiting)
{
var game = loop;
var template = ServerTemplate.Clone() as LabelWidget;
template.Id = "JOIN_GAME_{0}".F(i);
template.GetText = () => " {0} ({1})".F( /* /8 = hack */
game.Name,
game.Address);
template.GetBackground = () => (currentServer == game) ? "dialog2" : null;
template.OnMouseDown = mi => { if (mi.Button != MouseButton.Left) return false; currentServer = game; return true; };
template.IsVisible = () => true;
sl.AddChild(template);
if (i == 0) currentServer = game;
i++;
}
}
bool CanJoin(GameServer game)
{
//"waiting for players"
if (game.State != 1)
return false;
// Mods won't match if there are a different number
if (Game.CurrentMods.Count != game.Mods.Count())
return false;
return game.Mods.All( m => m.Contains('@')) && game.Mods.Select( m => Pair.New(m.Split('@')[0], m.Split('@')[1]))
.All(kv => Game.CurrentMods.ContainsKey(kv.First) &&
(kv.Second == "{DEV_VERSION}" || Game.CurrentMods[kv.First].Version == "{DEV_VERSION}" || kv.Second == Game.CurrentMods[kv.First].Version));
}
}
public class DirectConnectDelegate : IWidgetDelegate
{
[ObjectCreator.UseCtor]
public DirectConnectDelegate( [ObjectCreator.Param] Widget widget )
{
var dc = widget.GetWidget("DIRECTCONNECT_BG");
dc.GetWidget<TextFieldWidget>("SERVER_ADDRESS").Text = Game.Settings.Player.LastServer;
dc.GetWidget("JOIN_BUTTON").OnMouseUp = mi =>
{
var address = dc.GetWidget<TextFieldWidget>("SERVER_ADDRESS").Text;
var cpts = address.Split(':').ToArray();
if (cpts.Length != 2)
return true;
Game.Settings.Player.LastServer = address;
Game.Settings.Save();
Widget.CloseWindow();
Game.JoinServer(cpts[0], int.Parse(cpts[1]));
return true;
};
dc.GetWidget("CANCEL_BUTTON").OnMouseUp = mi =>
{
Widget.CloseWindow();
Widget.OpenWindow("MAINMENU_BG");
return true;
};
}
}
}

View File

@@ -1,146 +1,146 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
*/
#endregion
using System;
using OpenRA.FileFormats.Graphics;
using OpenRA.GameRules;
using OpenRA.Widgets;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class SettingsMenuDelegate : IWidgetDelegate
{
Widget bg;
public SettingsMenuDelegate()
{
bg = Widget.RootWidget.GetWidget<BackgroundWidget>("SETTINGS_MENU");
var tabs = bg.GetWidget<ContainerWidget>("TAB_CONTAINER");
//Tabs
tabs.GetWidget<ButtonWidget>("GENERAL").OnMouseUp = mi => FlipToTab("GENERAL_PANE");
tabs.GetWidget<ButtonWidget>("AUDIO").OnMouseUp = mi => FlipToTab("AUDIO_PANE");
tabs.GetWidget<ButtonWidget>("DISPLAY").OnMouseUp = mi => FlipToTab("DISPLAY_PANE");
tabs.GetWidget<ButtonWidget>("DEBUG").OnMouseUp = mi => FlipToTab("DEBUG_PANE");
FlipToTab("GENERAL_PANE");
//General
var general = bg.GetWidget("GENERAL_PANE");
var name = general.GetWidget<TextFieldWidget>("NAME");
name.Text = Game.Settings.Player.Name;
name.OnLoseFocus = () =>
{
name.Text = name.Text.Trim();
if (name.Text.Length == 0)
name.Text = Game.Settings.Player.Name;
else
Game.Settings.Player.Name = name.Text;
};
name.OnEnterKey = () => { name.LoseFocus(); return true; };
general.GetWidget<CheckboxWidget>("EDGE_SCROLL").Bind(Game.Settings.Game, "ViewportEdgeScroll");
// Added scroll sensitivity - Gecko
var edgeScrollSlider = general.GetWidget<SliderWidget>("EDGE_SCROLL_AMOUNT");
if (edgeScrollSlider != null) // Backwards compatible - Gecko
{
edgeScrollSlider.SetOffset(Game.Settings.Game.ViewportEdgeScrollStep);
edgeScrollSlider.OnChange += _ => { Game.Settings.Game.ViewportEdgeScrollStep = edgeScrollSlider.GetOffset(); };
Game.Settings.Game.ViewportEdgeScrollStep = edgeScrollSlider.GetOffset();
}
general.GetWidget<CheckboxWidget>("INVERSE_SCROLL").Bind(Game.Settings.Game, "InverseDragScroll");
general.GetWidget<CheckboxWidget>("TEAMCHAT_TOGGLE").Bind(Game.Settings.Game, "TeamChatToggle");
// Audio
var audio = bg.GetWidget("AUDIO_PANE");
var soundslider = audio.GetWidget<SliderWidget>("SOUND_VOLUME");
soundslider.OnChange += x => { Sound.SoundVolume = x; };
soundslider.GetOffset = () => { return Sound.SoundVolume; };
soundslider.SetOffset(Sound.SoundVolume);
var musicslider = audio.GetWidget<SliderWidget>("MUSIC_VOLUME");
musicslider.OnChange += x => { Sound.MusicVolume = x; };
musicslider.GetOffset = () => { return Sound.MusicVolume; };
musicslider.SetOffset(Sound.MusicVolume);
// Display
var display = bg.GetWidget("DISPLAY_PANE");
display.GetWidget<CheckboxWidget>("FULLSCREEN_CHECKBOX").Bind(Game.Settings.Game, "TeamChatToggle");
var fullscreen = display.GetWidget<CheckboxWidget>("FULLSCREEN_CHECKBOX");
fullscreen.IsChecked = () => Game.Settings.Graphics.Mode != WindowMode.Windowed;
fullscreen.OnChange += c => Game.Settings.Graphics.Mode = (Game.Settings.Graphics.Mode == WindowMode.Windowed) ? WindowMode.PseudoFullscreen : WindowMode.Windowed;
var width = display.GetWidget<TextFieldWidget>("SCREEN_WIDTH");
Game.Settings.Graphics.WindowedSize.X = (Game.Settings.Graphics.WindowedSize.X < Game.Settings.Graphics.MinResolution.X)?
Game.Settings.Graphics.MinResolution.X : Game.Settings.Graphics.WindowedSize.X;
width.Text = Game.Settings.Graphics.WindowedSize.X.ToString();
width.OnLoseFocus = () =>
{
try {
var w = int.Parse(width.Text);
if (w > Game.Settings.Graphics.MinResolution.X)
Game.Settings.Graphics.WindowedSize = new int2(w, Game.Settings.Graphics.WindowedSize.Y);
}
catch (FormatException) {
width.Text = Game.Settings.Graphics.WindowedSize.X.ToString();
}
};
width.OnEnterKey = () => { width.LoseFocus(); return true; };
var height = display.GetWidget<TextFieldWidget>("SCREEN_HEIGHT");
Game.Settings.Graphics.WindowedSize.Y = (Game.Settings.Graphics.WindowedSize.Y < Game.Settings.Graphics.MinResolution.Y)?
Game.Settings.Graphics.MinResolution.Y : Game.Settings.Graphics.WindowedSize.Y;
height.Text = Game.Settings.Graphics.WindowedSize.Y.ToString();
height.OnLoseFocus = () =>
{
try {
var h = int.Parse(height.Text);
if (h > Game.Settings.Graphics.MinResolution.Y)
Game.Settings.Graphics.WindowedSize = new int2(Game.Settings.Graphics.WindowedSize.X, h);
else
height.Text = Game.Settings.Graphics.WindowedSize.Y.ToString();
}
catch (FormatException) {
height.Text = Game.Settings.Graphics.WindowedSize.Y.ToString();
}
};
height.OnEnterKey = () => { height.LoseFocus(); return true; };
// Debug
var debug = bg.GetWidget("DEBUG_PANE");
debug.GetWidget<CheckboxWidget>("PERFDEBUG_CHECKBOX").Bind(Game.Settings.Debug, "PerfGraph");
debug.GetWidget<CheckboxWidget>("GAMETIME_CHECKBOX").Bind(Game.Settings.Game, "MatchTimer");
debug.GetWidget<CheckboxWidget>("CHECKUNSYNCED_CHECKBOX").Bind(Game.Settings.Debug, "SanityCheckUnsyncedCode");
bg.GetWidget("BUTTON_CLOSE").OnMouseUp = mi => {
Game.Settings.Save();
Widget.CloseWindow();
return true;
};
}
string open = null;
bool FlipToTab(string id)
{
if (open != null)
bg.GetWidget(open).Visible = false;
open = id;
bg.GetWidget(open).Visible = true;
return true;
}
}
}
#region Copyright & License Information
/*
* Copyright 2007-2011 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System;
using OpenRA.FileFormats.Graphics;
using OpenRA.GameRules;
using OpenRA.Widgets;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class SettingsMenuDelegate : IWidgetDelegate
{
Widget bg;
public SettingsMenuDelegate()
{
bg = Widget.RootWidget.GetWidget<BackgroundWidget>("SETTINGS_MENU");
var tabs = bg.GetWidget<ContainerWidget>("TAB_CONTAINER");
//Tabs
tabs.GetWidget<ButtonWidget>("GENERAL").OnMouseUp = mi => FlipToTab("GENERAL_PANE");
tabs.GetWidget<ButtonWidget>("AUDIO").OnMouseUp = mi => FlipToTab("AUDIO_PANE");
tabs.GetWidget<ButtonWidget>("DISPLAY").OnMouseUp = mi => FlipToTab("DISPLAY_PANE");
tabs.GetWidget<ButtonWidget>("DEBUG").OnMouseUp = mi => FlipToTab("DEBUG_PANE");
FlipToTab("GENERAL_PANE");
//General
var general = bg.GetWidget("GENERAL_PANE");
var name = general.GetWidget<TextFieldWidget>("NAME");
name.Text = Game.Settings.Player.Name;
name.OnLoseFocus = () =>
{
name.Text = name.Text.Trim();
if (name.Text.Length == 0)
name.Text = Game.Settings.Player.Name;
else
Game.Settings.Player.Name = name.Text;
};
name.OnEnterKey = () => { name.LoseFocus(); return true; };
general.GetWidget<CheckboxWidget>("EDGE_SCROLL").Bind(Game.Settings.Game, "ViewportEdgeScroll");
// Added scroll sensitivity - Gecko
var edgeScrollSlider = general.GetWidget<SliderWidget>("EDGE_SCROLL_AMOUNT");
if (edgeScrollSlider != null) // Backwards compatible - Gecko
{
edgeScrollSlider.SetOffset(Game.Settings.Game.ViewportEdgeScrollStep);
edgeScrollSlider.OnChange += _ => { Game.Settings.Game.ViewportEdgeScrollStep = edgeScrollSlider.GetOffset(); };
Game.Settings.Game.ViewportEdgeScrollStep = edgeScrollSlider.GetOffset();
}
general.GetWidget<CheckboxWidget>("INVERSE_SCROLL").Bind(Game.Settings.Game, "InverseDragScroll");
general.GetWidget<CheckboxWidget>("TEAMCHAT_TOGGLE").Bind(Game.Settings.Game, "TeamChatToggle");
// Audio
var audio = bg.GetWidget("AUDIO_PANE");
var soundslider = audio.GetWidget<SliderWidget>("SOUND_VOLUME");
soundslider.OnChange += x => { Sound.SoundVolume = x; };
soundslider.GetOffset = () => { return Sound.SoundVolume; };
soundslider.SetOffset(Sound.SoundVolume);
var musicslider = audio.GetWidget<SliderWidget>("MUSIC_VOLUME");
musicslider.OnChange += x => { Sound.MusicVolume = x; };
musicslider.GetOffset = () => { return Sound.MusicVolume; };
musicslider.SetOffset(Sound.MusicVolume);
// Display
var display = bg.GetWidget("DISPLAY_PANE");
display.GetWidget<CheckboxWidget>("FULLSCREEN_CHECKBOX").Bind(Game.Settings.Game, "TeamChatToggle");
var fullscreen = display.GetWidget<CheckboxWidget>("FULLSCREEN_CHECKBOX");
fullscreen.IsChecked = () => Game.Settings.Graphics.Mode != WindowMode.Windowed;
fullscreen.OnChange += c => Game.Settings.Graphics.Mode = (Game.Settings.Graphics.Mode == WindowMode.Windowed) ? WindowMode.PseudoFullscreen : WindowMode.Windowed;
var width = display.GetWidget<TextFieldWidget>("SCREEN_WIDTH");
Game.Settings.Graphics.WindowedSize.X = (Game.Settings.Graphics.WindowedSize.X < Game.Settings.Graphics.MinResolution.X)?
Game.Settings.Graphics.MinResolution.X : Game.Settings.Graphics.WindowedSize.X;
width.Text = Game.Settings.Graphics.WindowedSize.X.ToString();
width.OnLoseFocus = () =>
{
try {
var w = int.Parse(width.Text);
if (w > Game.Settings.Graphics.MinResolution.X)
Game.Settings.Graphics.WindowedSize = new int2(w, Game.Settings.Graphics.WindowedSize.Y);
}
catch (FormatException) {
width.Text = Game.Settings.Graphics.WindowedSize.X.ToString();
}
};
width.OnEnterKey = () => { width.LoseFocus(); return true; };
var height = display.GetWidget<TextFieldWidget>("SCREEN_HEIGHT");
Game.Settings.Graphics.WindowedSize.Y = (Game.Settings.Graphics.WindowedSize.Y < Game.Settings.Graphics.MinResolution.Y)?
Game.Settings.Graphics.MinResolution.Y : Game.Settings.Graphics.WindowedSize.Y;
height.Text = Game.Settings.Graphics.WindowedSize.Y.ToString();
height.OnLoseFocus = () =>
{
try {
var h = int.Parse(height.Text);
if (h > Game.Settings.Graphics.MinResolution.Y)
Game.Settings.Graphics.WindowedSize = new int2(Game.Settings.Graphics.WindowedSize.X, h);
else
height.Text = Game.Settings.Graphics.WindowedSize.Y.ToString();
}
catch (FormatException) {
height.Text = Game.Settings.Graphics.WindowedSize.Y.ToString();
}
};
height.OnEnterKey = () => { height.LoseFocus(); return true; };
// Debug
var debug = bg.GetWidget("DEBUG_PANE");
debug.GetWidget<CheckboxWidget>("PERFDEBUG_CHECKBOX").Bind(Game.Settings.Debug, "PerfGraph");
debug.GetWidget<CheckboxWidget>("GAMETIME_CHECKBOX").Bind(Game.Settings.Game, "MatchTimer");
debug.GetWidget<CheckboxWidget>("CHECKUNSYNCED_CHECKBOX").Bind(Game.Settings.Debug, "SanityCheckUnsyncedCode");
bg.GetWidget("BUTTON_CLOSE").OnMouseUp = mi => {
Game.Settings.Save();
Widget.CloseWindow();
return true;
};
}
string open = null;
bool FlipToTab(string id)
{
if (open != null)
bg.GetWidget(open).Visible = false;
open = id;
bg.GetWidget(open).Visible = true;
return true;
}
}
}

View File

@@ -1,17 +1,17 @@
#region Copyright & License Information
/*
* Copyright 2007-2010 The OpenRA Developers (see AUTHORS)
* Copyright 2007-2011 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see LICENSE.
* see COPYING.
*/
#endregion
using System.Drawing;
#endregion
using System.Drawing;
using OpenRA.FileFormats;
using OpenRA.Widgets;
using OpenRA.Widgets;
namespace OpenRA.Mods.RA.Widgets.Delegates
{
public class VideoPlayerDelegate : IWidgetDelegate
@@ -63,9 +63,9 @@ namespace OpenRA.Mods.RA.Widgets.Delegates
var video = kv.Key;
var title = kv.Value;
if (!FileSystem.Exists(video))
continue;
if (Selected == null)
continue;
if (Selected == null)
player.Load(Selected = video);
var template = itemTemplate.Clone() as LabelWidget;