buypeeb-cs/SettingsWindow.cs

87 lines
No EOL
2.9 KiB
C#

using System;
using System.Collections.Generic;
using Gtk;
namespace Buypeeb {
class SettingsWindow : Window {
private List<Switch> generalSwitches = new List<Switch>();
private List<Entry> updateIntervalEntries = new List<Entry>();
private Settings settings;
private Builder builder;
private List<String> generalSwitchNames = new List<String> { "ShowSecondsInListView", "Autosave", "ShowFavouritesAtTopOfList" };
private List<String> updateIntervalEntryNames = new List<String> { "UpdateInterval", "UpdateIntervalCritical", "FavouriteUpdateInterval", "FavouriteUpdateIntervalCritical" };
public SettingsWindow(Settings settings) : this(new Builder("settings.glade"), settings) { }
private SettingsWindow(Builder builder, Settings settings) : base(builder.GetObject("WindowSettings").Handle) {
this.Title = "Buypeeb - Settings";
this.settings = settings;
this.builder = builder;
builder.Autoconnect(this);
foreach (var name in this.generalSwitchNames) {
var s = (Switch)builder.GetObject($"Switch{name}");
this.generalSwitches.Add(s);
s.Active = GetSetting<bool>(this.PropertyName(name));
}
foreach (var name in this.updateIntervalEntryNames) {
var e = (Entry)builder.GetObject($"Entry{name}");
this.updateIntervalEntries.Add(e);
e.Text = GetSetting<int>(this.PropertyName(name)).ToString();
}
}
private T GetSetting<T>(string property) {
return (T)this.settings.GetType().GetProperty(property).GetValue(this.settings, null);
}
private void SetSetting<T>(string property, T value) {
this.settings.GetType().GetProperty(property).SetValue(this.settings, value);
}
private string PropertyName(string property) {
// replace "PropertyName" with "propertyName";
return property[0].ToString().ToLower() + property.Substring(1);
}
private void ButtonSaveClicked(object sender, EventArgs args) {
// first, validate all the intervals
bool failed = false;
foreach (var name in this.updateIntervalEntryNames) {
var e = (Entry)builder.GetObject($"Entry{name}");
if (!int.TryParse(e.Text, out int result)) {
failed = true;
}
else {
if (result < 30 || result > 6000) {
failed = true;
}
}
if (failed) {
var md = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, "Update intervals must be a whole number between 30 and 6000.");
md.Run();
md.Dispose();
return;
}
}
// validation success!
foreach (var name in this.updateIntervalEntryNames) {
this.SetSetting<int>(PropertyName(name), int.Parse((builder.GetObject($"Entry{name}") as Entry).Text));
}
foreach (var name in this.generalSwitchNames) {
this.SetSetting<bool>(PropertyName(name), (builder.GetObject($"Switch{name}") as Switch).Active);
}
this.Dispose();
}
private void ButtonCancelClicked(object sender, EventArgs args) {
this.Dispose();
}
}
}