-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
Main.cs
323 lines (282 loc) · 11.5 KB
/
Main.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
using Newtonsoft.Json;
using PKHeX.Core;
using SysBot.Base;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json.Serialization;
using SysBot.Pokemon.Z3;
namespace SysBot.Pokemon.WinForms
{
public sealed partial class Main : Form
{
private readonly List<PokeBotState> Bots = new();
private readonly IPokeBotRunner RunningEnvironment;
private readonly ProgramConfig Config;
public Main()
{
InitializeComponent();
PokeTradeBot.SeedChecker = new Z3SeedSearchHandler<PK8>();
if (File.Exists(Program.ConfigPath))
{
var lines = File.ReadAllText(Program.ConfigPath);
Config = JsonConvert.DeserializeObject<ProgramConfig>(lines, GetSettings()) ?? new ProgramConfig();
RunningEnvironment = GetRunner(Config);
foreach (var bot in Config.Bots)
{
bot.Initialize();
AddBot(bot);
}
}
else
{
Config = new ProgramConfig();
RunningEnvironment = GetRunner(Config);
Config.Hub.Folder.CreateDefaults(Program.WorkingDirectory);
}
RTB_Logs.MaxLength = 32_767; // character length
LoadControls();
Text = $"{Text} ({Config.Mode})";
Task.Run(BotMonitor);
#if NETFRAMEWORK
InitUtil.InitializeStubs(Config.Mode);
#endif
}
private static IPokeBotRunner GetRunner(ProgramConfig cfg) => cfg.Mode switch
{
ProgramMode.SWSH => new PokeBotRunnerImpl<PK8>(cfg.Hub, new BotFactory8()),
ProgramMode.BDSP => new PokeBotRunnerImpl<PB8>(cfg.Hub, new BotFactory8BS()),
ProgramMode.LA => new PokeBotRunnerImpl<PA8>(cfg.Hub, new BotFactory8LA()),
ProgramMode.SCVI => new PokeBotRunnerImpl<PK9>(cfg.Hub, new BotFactory9SV()),
_ => throw new IndexOutOfRangeException("Unsupported mode."),
};
private async Task BotMonitor()
{
while (!Disposing)
{
try
{
foreach (var c in FLP_Bots.Controls.OfType<BotController>())
c.ReadState();
}
catch
{
// Updating the collection by adding/removing bots will change the iterator
// Can try a for-loop or ToArray, but those still don't prevent concurrent mutations of the array.
// Just try, and if failed, ignore. Next loop will be fine. Locks on the collection are kinda overkill, since this task is not critical.
}
await Task.Delay(2_000).ConfigureAwait(false);
}
}
private void LoadControls()
{
MinimumSize = Size;
PG_Hub.SelectedObject = RunningEnvironment.Config;
var routines = ((PokeRoutineType[])Enum.GetValues(typeof(PokeRoutineType))).Where(z => RunningEnvironment.SupportsRoutine(z));
var list = routines.Select(z => new ComboItem(z.ToString(), (int)z)).ToArray();
CB_Routine.DisplayMember = nameof(ComboItem.Text);
CB_Routine.ValueMember = nameof(ComboItem.Value);
CB_Routine.DataSource = list;
CB_Routine.SelectedValue = (int)PokeRoutineType.FlexTrade; // default option
var protocols = (SwitchProtocol[])Enum.GetValues(typeof(SwitchProtocol));
var listP = protocols.Select(z => new ComboItem(z.ToString(), (int)z)).ToArray();
CB_Protocol.DisplayMember = nameof(ComboItem.Text);
CB_Protocol.ValueMember = nameof(ComboItem.Value);
CB_Protocol.DataSource = listP;
CB_Protocol.SelectedIndex = (int)SwitchProtocol.WiFi; // default option
LogUtil.Forwarders.Add(AppendLog);
}
private void AppendLog(string message, string identity)
{
var line = $"[{DateTime.Now:HH:mm:ss}] - {identity}: {message}{Environment.NewLine}";
if (InvokeRequired)
Invoke((MethodInvoker)(() => UpdateLog(line)));
else
UpdateLog(line);
}
private readonly object _logLock = new();
private void UpdateLog(string line)
{
lock (_logLock)
{
// ghetto truncate
var rtb = RTB_Logs;
var text = rtb.Text;
var max = rtb.MaxLength;
if (text.Length + line.Length + 2 >= max)
rtb.Text = text[(max / 4)..];
rtb.AppendText(line);
rtb.ScrollToCaret();
}
}
private ProgramConfig GetCurrentConfiguration()
{
Config.Bots = Bots.ToArray();
return Config;
}
private void Main_FormClosing(object sender, FormClosingEventArgs e)
{
SaveCurrentConfig();
var bots = RunningEnvironment;
if (!bots.IsRunning)
return;
async Task WaitUntilNotRunning()
{
while (bots.IsRunning)
await Task.Delay(10).ConfigureAwait(false);
}
// Try to let all bots hard-stop before ending execution of the entire program.
WindowState = FormWindowState.Minimized;
ShowInTaskbar = false;
bots.StopAll();
Task.WhenAny(WaitUntilNotRunning(), Task.Delay(5_000)).ConfigureAwait(true).GetAwaiter().GetResult();
}
private void SaveCurrentConfig()
{
var cfg = GetCurrentConfiguration();
var lines = JsonConvert.SerializeObject(cfg, GetSettings());
File.WriteAllText(Program.ConfigPath, lines);
}
private static JsonSerializerSettings GetSettings() => new()
{
Formatting = Formatting.Indented,
DefaultValueHandling = DefaultValueHandling.Include,
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new SerializableExpandableContractResolver(),
};
// https://stackoverflow.com/a/36643545
private sealed class SerializableExpandableContractResolver : DefaultContractResolver
{
protected override JsonContract CreateContract(Type objectType)
{
if (TypeDescriptor.GetAttributes(objectType).Contains(new TypeConverterAttribute(typeof(ExpandableObjectConverter))))
return CreateObjectContract(objectType);
return base.CreateContract(objectType);
}
}
private void B_Start_Click(object sender, EventArgs e)
{
SaveCurrentConfig();
LogUtil.LogInfo("Starting all bots...", "Form");
RunningEnvironment.InitializeStart();
SendAll(BotControlCommand.Start);
Tab_Logs.Select();
if (Bots.Count == 0)
WinFormsUtil.Alert("No bots configured, but all supporting services have been started.");
}
private void SendAll(BotControlCommand cmd)
{
foreach (var c in FLP_Bots.Controls.OfType<BotController>())
c.SendCommand(cmd, false);
EchoUtil.Echo($"All bots have been issued a command to {cmd}.");
}
private void B_Stop_Click(object sender, EventArgs e)
{
var env = RunningEnvironment;
if (!env.IsRunning && (ModifierKeys & Keys.Alt) == 0)
{
WinFormsUtil.Alert("Nothing is currently running.");
return;
}
var cmd = BotControlCommand.Stop;
if ((ModifierKeys & Keys.Control) != 0 || (ModifierKeys & Keys.Shift) != 0) // either, because remembering which can be hard
{
if (env.IsRunning)
{
WinFormsUtil.Alert("Commanding all bots to Idle.", "Press Stop (without a modifier key) to hard-stop and unlock control, or press Stop with the modifier key again to resume.");
cmd = BotControlCommand.Idle;
}
else
{
WinFormsUtil.Alert("Commanding all bots to resume their original task.", "Press Stop (without a modifier key) to hard-stop and unlock control.");
cmd = BotControlCommand.Resume;
}
}
SendAll(cmd);
}
private void B_New_Click(object sender, EventArgs e)
{
var cfg = CreateNewBotConfig();
if (!AddBot(cfg))
{
WinFormsUtil.Alert("Unable to add bot; ensure details are valid and not duplicate with an already existing bot.");
return;
}
System.Media.SystemSounds.Asterisk.Play();
}
private bool AddBot(PokeBotState cfg)
{
if (!cfg.IsValid())
return false;
if (Bots.Any(z => z.Connection.Equals(cfg.Connection)))
return false;
PokeRoutineExecutorBase newBot;
try
{
Console.WriteLine($"Current Mode ({Config.Mode}) does not support this type of bot ({cfg.CurrentRoutineType}).");
newBot = RunningEnvironment.CreateBotFromConfig(cfg);
}
catch
{
return false;
}
try
{
RunningEnvironment.Add(newBot);
}
catch (ArgumentException ex)
{
WinFormsUtil.Error(ex.Message);
return false;
}
AddBotControl(cfg);
Bots.Add(cfg);
return true;
}
private void AddBotControl(PokeBotState cfg)
{
var row = new BotController { Width = FLP_Bots.Width };
row.Initialize(RunningEnvironment, cfg);
FLP_Bots.Controls.Add(row);
FLP_Bots.SetFlowBreak(row, true);
row.Click += (s, e) =>
{
var details = cfg.Connection;
TB_IP.Text = details.IP;
NUD_Port.Value = details.Port;
CB_Protocol.SelectedIndex = (int)details.Protocol;
CB_Routine.SelectedValue = (int)cfg.InitialRoutine;
};
row.Remove += (s, e) =>
{
Bots.Remove(row.State);
RunningEnvironment.Remove(row.State, !RunningEnvironment.Config.SkipConsoleBotCreation);
FLP_Bots.Controls.Remove(row);
};
}
private PokeBotState CreateNewBotConfig()
{
var ip = TB_IP.Text;
var port = (int)NUD_Port.Value;
var cfg = BotConfigUtil.GetConfig<SwitchConnectionConfig>(ip, port);
cfg.Protocol = (SwitchProtocol)WinFormsUtil.GetIndex(CB_Protocol);
var pk = new PokeBotState {Connection = cfg};
var type = (PokeRoutineType)WinFormsUtil.GetIndex(CB_Routine);
pk.Initialize(type);
return pk;
}
private void FLP_Bots_Resize(object sender, EventArgs e)
{
foreach (var c in FLP_Bots.Controls.OfType<BotController>())
c.Width = FLP_Bots.Width;
}
private void CB_Protocol_SelectedIndexChanged(object sender, EventArgs e)
{
TB_IP.Visible = CB_Protocol.SelectedIndex == 0;
}
}
}