cec-config-gui: read/write the vendor id override setting
[deb_libcec.git] / src / cec-config-gui / CecConfigGUI.cs
index 10a484411cea0d143b390980cdc22081c81d08be..83a83ac43c9564fc93e4688a893fe5c9d9943075 100644 (file)
@@ -10,10 +10,11 @@ using CecSharp;
 using CecConfigGui.actions;
 using System.Globalization;
 using System.IO;
+using System.Xml;
 
 namespace CecConfigGui
 {
-  public partial class CecConfigGUI : Form
+  public partial class CecConfigGUI : AsyncForm
   {
     public CecConfigGUI()
     {
@@ -24,17 +25,156 @@ namespace CecConfigGui
       Config.ClientVersion = CecClientVersion.Version1_5_0;
       Callbacks = new CecCallbackWrapper(this);
       Config.SetCallbacks(Callbacks);
-
-      InitializeComponent();
+      LoadXMLConfiguration(ref Config);
       Lib = new LibCecSharp(Config);
 
+      InitializeComponent();
       LoadButtonConfiguration();
 
-      ActiveProcess = new ConnectToDevice(ref Lib);
+      //TODO read the com port setting from the configuration
+      CecAdapter[] adapters = Lib.FindAdapters(string.Empty);
+      if (adapters.Length == 0 || !Lib.Open(adapters[0].ComPort, 10000))
+      {
+        MessageBox.Show("Could not connect to any CEC adapter. Please check your configuration and try again.", "Pulse-Eight USB-CEC Adapter", MessageBoxButtons.OK);
+        Application.Exit();
+      }
+
+      ActiveProcess = new ConnectToDevice(ref Lib, Config);
       ActiveProcess.EventHandler += new EventHandler<UpdateEvent>(ProcessEventHandler);
       (new Thread(new ThreadStart(ActiveProcess.Run))).Start();
     }
 
+    private bool LoadXMLConfiguration(ref LibCECConfiguration config)
+    {
+      bool gotConfig = false;
+      string xbmcDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\XBMC\userdata\peripheral_data";
+      string defaultDir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
+      string file = defaultDir + @"\usb_2548_1001.xml";
+      if (File.Exists(xbmcDir + @"\usb_2548_1001.xml"))
+        file = xbmcDir + @"\usb_2548_1001.xml";
+
+      if (File.Exists(file))
+      {
+        XmlTextReader reader = new XmlTextReader(file);
+        while (reader.Read())
+        {
+          gotConfig = true;
+          switch (reader.NodeType)
+          {
+            case XmlNodeType.Element:
+              if (reader.Name.ToLower() == "setting")
+              {
+                string name = string.Empty;
+                string value = string.Empty;
+
+                while (reader.MoveToNextAttribute())
+                {
+                  if (reader.Name.ToLower().Equals("id"))
+                    name = reader.Value.ToLower();
+                  if (reader.Name.ToLower().Equals("value"))
+                    value = reader.Value;
+                }
+
+                switch (name)
+                {
+                  case "cec_hdmi_port":
+                    {
+                      byte iPort;
+                      if (byte.TryParse(value, out iPort))
+                        config.HDMIPort = iPort;
+                    }
+                    break;
+                  case "connected_device":
+                    {
+                      ushort iDevice;
+                      if (ushort.TryParse(value, out iDevice))
+                        config.BaseDevice = (CecLogicalAddress)iDevice;
+                    }
+                    break;
+                  case "cec_power_on_startup":
+                    if (value.Equals("1") || value.ToLower().Equals("true") || value.ToLower().Equals("yes"))
+                    {
+                      config.ActivateSource = true;
+                      config.WakeDevices.Set(CecLogicalAddress.Tv);
+                    }
+                    break;
+                  case "cec_power_off_shutdown":
+                    if (value.Equals("1") || value.ToLower().Equals("true") || value.ToLower().Equals("yes"))
+                      config.PowerOffDevices.Set(CecLogicalAddress.Broadcast);
+                    break;
+                  case "cec_standby_screensaver":
+                    config.PowerOffScreensaver = value.Equals("1") || value.ToLower().Equals("true") || value.ToLower().Equals("yes");
+                    break;
+                  case "standby_pc_on_tv_standby":
+                    config.PowerOffOnStandby = value.Equals("1") || value.ToLower().Equals("true") || value.ToLower().Equals("yes");
+                    break;
+                  case "use_tv_menu_language":
+                    config.UseTVMenuLanguage = value.Equals("1") || value.ToLower().Equals("true") || value.ToLower().Equals("yes");
+                    break;
+                  // 1.5.0+ settings
+                  case "physical_address":
+                    {
+                      ushort physicalAddress = 0;
+                      if (ushort.TryParse(value, NumberStyles.AllowHexSpecifier, null, out physicalAddress))
+                        config.PhysicalAddress = physicalAddress;
+                    }
+                    break;
+                  case "device_type":
+                    {
+                      ushort iType;
+                      if (ushort.TryParse(value, out iType))
+                        config.DeviceTypes.Types[0] = (CecDeviceType)iType;
+                    }
+                    break;
+                  case "tv_vendor":
+                    {
+                      UInt64 iVendor;
+                      if (UInt64.TryParse(value, out iVendor))
+                        config.TvVendor = (CecVendorId)iVendor;
+                    }
+                    break;
+                  case "wake_devices":
+                    {
+                      config.WakeDevices.Clear();
+                      string[] split = value.Split(new char[] { ' ' });
+                      foreach (string dev in split)
+                      {
+                        byte iLogicalAddress;
+                        if (byte.TryParse(dev, out iLogicalAddress))
+                          config.WakeDevices.Set((CecLogicalAddress)iLogicalAddress);
+                      }
+                    }
+                    break;
+                  case "standby_devices":
+                    {
+                      config.PowerOffDevices.Clear();
+                      string[] split = value.Split(new char[] { ' ' });
+                      foreach (string dev in split)
+                      {
+                        byte iLogicalAddress;
+                        if (byte.TryParse(dev, out iLogicalAddress))
+                          config.PowerOffDevices.Set((CecLogicalAddress)iLogicalAddress);
+                      }
+                    }
+                    break;
+                  case "enabled":
+                    break;
+                  case "port":
+                    //TODO
+                    break;
+                  default:
+                    break;
+                }
+              }
+              break;
+            default:
+              break;
+          }
+        }
+      }
+      return gotConfig;
+    }
+
     private void LoadButtonConfiguration()
     {
       //TODO load the real configuration
@@ -119,216 +259,6 @@ namespace CecConfigGui
       this.cecButtonConfigBindingSource.Add(new CecButtonConfigItem("(Samsung) Return", (new CecSharp.CecKeypress() { Keycode = 0x91 }), string.Empty));
     }
 
-    public int ReceiveCommand(CecCommand command)
-    {
-      return 1;
-    }
-
-    public int ReceiveKeypress(CecKeypress key)
-    {
-      SelectKeypressRow(key);
-      return 1;
-    }
-
-    delegate void SelectKeypressRowCallback(CecKeypress key);
-    private void SelectKeypressRow(CecKeypress key)
-    {
-      if (dgButtons.InvokeRequired)
-      {
-        SelectKeypressRowCallback d = new SelectKeypressRowCallback(SelectKeypressRow);
-        try
-        {
-          this.Invoke(d, new object[] { key });
-        }
-        catch (Exception) { }
-      }
-      else
-      {
-        int rowIndex = -1;
-        foreach (DataGridViewRow row in dgButtons.Rows)
-        {
-          CecButtonConfigItem item = row.DataBoundItem as CecButtonConfigItem;
-          if (item != null && item.Key.Keycode == key.Keycode)
-          {
-            rowIndex = row.Index;
-            row.Selected = true;
-            item.Enabled = true;
-          }
-          else
-          {
-            row.Selected = false;
-          }
-        }
-        if (rowIndex > -1)
-          dgButtons.FirstDisplayedScrollingRowIndex = rowIndex;
-      }
-    }
-
-    delegate void AddLogMessageCallback(CecLogMessage message);
-    private void AddLogMessage(CecLogMessage message)
-    {
-      if (tbLog.InvokeRequired)
-      {
-        AddLogMessageCallback d = new AddLogMessageCallback(AddLogMessage);
-        try
-        {
-          this.Invoke(d, new object[] { message });
-        }
-        catch (Exception) { }
-      }
-      else
-      {
-        string strLevel = "";
-        bool display = false;
-        switch (message.Level)
-        {
-          case CecLogLevel.Error:
-            strLevel = "ERROR:   ";
-            display = cbLogError.Checked;
-            break;
-          case CecLogLevel.Warning:
-            strLevel = "WARNING: ";
-            display = cbLogWarning.Checked;
-            break;
-          case CecLogLevel.Notice:
-            strLevel = "NOTICE:  ";
-            display = cbLogNotice.Checked;
-            break;
-          case CecLogLevel.Traffic:
-            strLevel = "TRAFFIC: ";
-            display = cbLogTraffic.Checked;
-            break;
-          case CecLogLevel.Debug:
-            strLevel = "DEBUG:   ";
-            display = cbLogDebug.Checked;
-            break;
-          default:
-            break;
-        }
-
-        if (display)
-        {
-          string strLog = string.Format("{0} {1,16} {2}", strLevel, message.Time, message.Message) + System.Environment.NewLine;
-          tbLog.Text += strLog;
-          tbLog.Select(tbLog.Text.Length, 0);
-          tbLog.ScrollToCaret();
-        }
-      }
-    }
-
-    public int ReceiveLogMessage(CecLogMessage message)
-    {
-      AddLogMessage(message);
-      return 1;
-    }
-
-    delegate void SetControlEnabledCallback(Control control, bool val);
-    private void SetControlEnabled(Control control, bool val)
-    {
-      if (control.InvokeRequired)
-      {
-        SetControlEnabledCallback d = new SetControlEnabledCallback(SetControlEnabled);
-        try
-        {
-          this.Invoke(d, new object[] { control, val });
-        }
-        catch (Exception) { }
-      }
-      else
-      {
-        control.Enabled = val;
-      }
-    }
-
-    private void SetControlsEnabled(bool val)
-    {
-      SetControlEnabled(cbPortNumber, val);
-      SetControlEnabled(cbConnectedDevice, cbConnectedDevice.Items.Count > 1 ? val : false);
-      SetControlEnabled(tbPhysicalAddress, val);
-      SetControlEnabled(cbDeviceType, val);
-      SetControlEnabled(cbUseTVMenuLanguage, val);
-      SetControlEnabled(cbPowerOnStartup, val);
-      SetControlEnabled(cbPowerOffShutdown, val);
-      SetControlEnabled(cbPowerOffScreensaver, val);
-      SetControlEnabled(cbPowerOffOnStandby, val);
-      SetControlEnabled(bClose, val);
-      SetControlEnabled(bSave, val);
-    }
-
-    delegate void SetControlTextCallback(Control control, string val);
-    private void SetControlText(Control control, string val)
-    {
-      if (control.InvokeRequired)
-      {
-        SetControlTextCallback d = new SetControlTextCallback(SetControlText);
-        try
-        {
-          this.Invoke(d, new object[] { control, val });
-        }
-        catch (Exception) { }
-      }
-      else
-      {
-        control.Text = val;
-      }
-    }
-
-    delegate void SetCheckboxCheckedCallback(CheckBox control, bool val);
-    private void SetCheckboxChecked(CheckBox control, bool val)
-    {
-      if (control.InvokeRequired)
-      {
-        SetCheckboxCheckedCallback d = new SetCheckboxCheckedCallback(SetCheckboxChecked);
-        try
-        {
-          this.Invoke(d, new object[] { control, val });
-        }
-        catch (Exception) { }
-      }
-      else
-      {
-        control.Checked = val;
-      }
-    }
-
-    delegate void SetProgressValueCallback(ProgressBar control, int val);
-    private void SetProgressValue(ProgressBar control, int val)
-    {
-      if (control.InvokeRequired)
-      {
-        SetProgressValueCallback d = new SetProgressValueCallback(SetProgressValue);
-        try
-        {
-          this.Invoke(d, new object[] { control, val });
-        }
-        catch (Exception) { }
-      }
-      else
-      {
-        control.Value = val;
-      }
-    }
-
-    delegate void SetComboBoxItemsCallback(ComboBox control, string selectedText, object[] val);
-    private void SetComboBoxItems(ComboBox control, string selectedText, object[] val)
-    {
-      if (control.InvokeRequired)
-      {
-        SetComboBoxItemsCallback d = new SetComboBoxItemsCallback(SetComboBoxItems);
-        try
-        {
-          this.Invoke(d, new object[] { control, selectedText, val });
-        }
-        catch (Exception) { }
-      }
-      else
-      {
-        control.Items.Clear();
-        control.Items.AddRange(val);
-        control.Text = selectedText;
-      }
-    }
-
     private void ProcessEventHandler(object src, UpdateEvent updateEvent)
     {
       switch (updateEvent.Type)
@@ -371,16 +301,9 @@ namespace CecConfigGui
           UpdateSelectedDevice();
           break;
         case UpdateEventType.Configuration:
-          Config = updateEvent.ConfigValue;
-          SetControlText(tbPhysicalAddress, string.Format("{0,4:X}", Config.PhysicalAddress));
-          SetControlText(cbConnectedDevice, Config.BaseDevice == CecLogicalAddress.AudioSystem ? AVRVendorString : TVVendorString);
-          SetControlText(cbPortNumber, Config.HDMIPort.ToString());
-          SetCheckboxChecked(cbUseTVMenuLanguage, Config.UseTVMenuLanguage);
-          SetCheckboxChecked(cbPowerOnStartup, Config.PowerOnStartup);
-          SetCheckboxChecked(cbPowerOffShutdown, Config.PowerOffShutdown);
-          SetCheckboxChecked(cbPowerOffScreensaver, Config.PowerOffScreensaver);
-          SetCheckboxChecked(cbPowerOffOnStandby, Config.PowerOffOnStandby);
-          UpdateSelectedDevice();
+          SuppressUpdates = true;
+          ConfigurationChanged(updateEvent.ConfigValue);
+          SuppressUpdates = false;
           break;
         case UpdateEventType.ProcessCompleted:
           ActiveProcess = null;
@@ -389,73 +312,140 @@ namespace CecConfigGui
       }
     }
 
-    private void UpdateSelectedDevice()
+    public void SetPhysicalAddress(ushort physicalAddress)
     {
-      if (HasAVRDevice)
-        SetComboBoxItems(this.cbConnectedDevice, Config.BaseDevice == CecLogicalAddress.AudioSystem ? AVRVendorString : TVVendorString, new object[] { TVVendorString, AVRVendorString });
-      else
-        SetComboBoxItems(this.cbConnectedDevice, TVVendorString, new object[] { TVVendorString });
+      if (!SuppressUpdates && ActiveProcess == null)
+      {
+        SetControlsEnabled(false);
+        SetControlText(cbPortNumber, string.Empty);
+        SetControlText(cbConnectedDevice, string.Empty);
+        ActiveProcess = new UpdatePhysicalAddress(ref Lib, physicalAddress);
+        ActiveProcess.EventHandler += new EventHandler<UpdateEvent>(ProcessEventHandler);
+        (new Thread(new ThreadStart(ActiveProcess.Run))).Start();
+      }
     }
 
-    public string TVVendorString
+    public void SendImageViewOn(CecLogicalAddress address)
     {
-      get
+      if (!SuppressUpdates && ActiveProcess == null)
       {
-        return TVVendor != CecVendorId.Unknown ?
-          "Television (" + Lib.ToString(TVVendor) + ")" :
-          "Television";
+        SetControlsEnabled(false);
+        ActiveProcess = new SendImageViewOn(ref Lib, address);
+        ActiveProcess.EventHandler += new EventHandler<UpdateEvent>(ProcessEventHandler);
+        (new Thread(new ThreadStart(ActiveProcess.Run))).Start();
       }
     }
 
-    public string AVRVendorString
+    public void ActivateSource(CecLogicalAddress address)
     {
-      get
+      if (!SuppressUpdates && ActiveProcess == null)
       {
-        return AVRVendor != CecVendorId.Unknown ?
-          "AVR (" + Lib.ToString(AVRVendor) + ")" :
-          "AVR";
+        SetControlsEnabled(false);
+        ActiveProcess = new SendActivateSource(ref Lib, address);
+        ActiveProcess.EventHandler += new EventHandler<UpdateEvent>(ProcessEventHandler);
+        (new Thread(new ThreadStart(ActiveProcess.Run))).Start();
       }
     }
 
-    protected bool HasAVRDevice;
-    protected CecVendorId TVVendor = CecVendorId.Unknown;
-    protected CecVendorId AVRVendor = CecVendorId.Unknown;
-    protected CecLogicalAddress SelectedConnectedDevice = CecLogicalAddress.Unknown;
-
-    protected LibCECConfiguration Config;
-    protected LibCecSharp Lib;
-    private CecCallbackWrapper Callbacks;
-    private UpdateProcess ActiveProcess = null;
+    public void SendStandby(CecLogicalAddress address)
+    {
+      if (!SuppressUpdates && ActiveProcess == null)
+      {
+        SetControlsEnabled(false);
+        ActiveProcess = new SendStandby(ref Lib, address);
+        ActiveProcess.EventHandler += new EventHandler<UpdateEvent>(ProcessEventHandler);
+        (new Thread(new ThreadStart(ActiveProcess.Run))).Start();
+      }
+    }
 
-    private void connectedDevice_SelectedIndexChanged(object sender, EventArgs e)
+    public void ShowDeviceInfo(CecLogicalAddress address)
     {
-      if (ActiveProcess == null)
+      if (!SuppressUpdates && ActiveProcess == null)
       {
         SetControlsEnabled(false);
-        SelectedConnectedDevice = (this.cbConnectedDevice.Text.Equals(AVRVendorString)) ? CecLogicalAddress.AudioSystem : CecLogicalAddress.Tv;
-        int iPortNumber = 0;
-        if (!int.TryParse(cbPortNumber.Text, out iPortNumber))
-          iPortNumber = 1;
-        ActiveProcess = new UpdateConnectedDevice(ref Lib, cbConnectedDevice.Text.Equals(AVRVendorString) ? CecLogicalAddress.AudioSystem : CecLogicalAddress.Tv, iPortNumber);
+        ActiveProcess = new ShowDeviceInfo(this, ref Lib, address);
         ActiveProcess.EventHandler += new EventHandler<UpdateEvent>(ProcessEventHandler);
         (new Thread(new ThreadStart(ActiveProcess.Run))).Start();
       }
     }
 
-    private void bCancel_Click(object sender, EventArgs e)
+    private void SetControlsEnabled(bool val)
     {
-      this.Dispose();
+      SetControlEnabled(cbPortNumber, val);
+      SetControlEnabled(cbConnectedDevice, cbConnectedDevice.Items.Count > 1 ? val : false);
+      SetControlEnabled(tbPhysicalAddress, val);
+      SetControlEnabled(cbDeviceType, false); // TODO not implemented yet
+      SetControlEnabled(cbUseTVMenuLanguage, val);
+      SetControlEnabled(cbActivateSource, val);
+      SetControlEnabled(cbPowerOffScreensaver, val);
+      SetControlEnabled(cbPowerOffOnStandby, val);
+      SetControlEnabled(cbWakeDevices, false); // TODO not implemented yet
+      SetControlEnabled(cbPowerOffDevices, false); // TODO not implemented yet
+      SetControlEnabled(cbVendorOverride, val);
+      SetControlEnabled(cbVendorId, val && cbVendorOverride.Checked);
+      SetControlEnabled(bClose, val);
+      SetControlEnabled(bSave, val);
+
+      SetControlEnabled(bSendImageViewOn, val);
+      SetControlEnabled(bStandby, val);
+      SetControlEnabled(bActivateSource, val);
+      SetControlEnabled(bScan, val);
+
+      bool enableVolumeButtons = (GetTargetDevice() == CecLogicalAddress.AudioSystem) && val;
+      SetControlEnabled(bVolUp, enableVolumeButtons);
+      SetControlEnabled(bVolDown, enableVolumeButtons);
+      SetControlEnabled(bMute, enableVolumeButtons);
     }
 
-    private void bSave_Click(object sender, EventArgs e)
+    #region Configuration tab
+    private void tbPhysicalAddress_TextChanged(object sender, EventArgs e)
     {
-      SetControlsEnabled(false);
+      if (tbPhysicalAddress.Text.Length != 4)
+        return;
+      ushort physicalAddress = 0;
+      if (!ushort.TryParse(tbPhysicalAddress.Text, NumberStyles.AllowHexSpecifier, null, out physicalAddress))
+        return;
 
-      Config.UseTVMenuLanguage = cbUseTVMenuLanguage.Checked;
-      Config.PowerOnStartup = cbPowerOnStartup.Checked;
-      Config.PowerOffShutdown = cbPowerOffShutdown.Checked;
-      Config.PowerOffScreensaver = cbPowerOffScreensaver.Checked;
-      Config.PowerOffOnStandby = cbPowerOffOnStandby.Checked;
+      SetPhysicalAddress(physicalAddress);
+    }
+
+    private void UpdateSelectedDevice()
+    {
+      if (HasAVRDevice)
+        SetComboBoxItems(this.cbConnectedDevice, Config.BaseDevice == CecLogicalAddress.AudioSystem ? AVRVendorString : TVVendorString, new object[] { TVVendorString, AVRVendorString });
+      else
+        SetComboBoxItems(this.cbConnectedDevice, TVVendorString, new object[] { TVVendorString });
+    }
+
+    public void SetConnectedDevice(CecLogicalAddress address, int portnumber)
+    {
+      if (!SuppressUpdates && ActiveProcess == null)
+      {
+        SetControlsEnabled(false);
+        ActiveProcess = new UpdateConnectedDevice(ref Lib, address, portnumber);
+        ActiveProcess.EventHandler += new EventHandler<UpdateEvent>(ProcessEventHandler);
+        (new Thread(new ThreadStart(ActiveProcess.Run))).Start();
+      }
+    }
+
+    private void connectedDevice_SelectedIndexChanged(object sender, EventArgs e)
+    {
+      SetConnectedDevice(SelectedConnectedDevice, SelectedPortNumber);
+    }
+
+    private void bCancel_Click(object sender, EventArgs e)
+    {
+      this.Dispose();
+    }
+
+    private void bSave_Click(object sender, EventArgs e)
+    {
+      SetControlsEnabled(false);
+
+      Config.UseTVMenuLanguage = cbUseTVMenuLanguage.Checked;
+      Config.ActivateSource = cbActivateSource.Checked;
+      Config.PowerOffScreensaver = cbPowerOffScreensaver.Checked;
+      Config.PowerOffOnStandby = cbPowerOffOnStandby.Checked;
 
       if (!Lib.CanPersistConfiguration())
       {
@@ -476,10 +466,19 @@ namespace CecConfigGui
 
           if (dialog.ShowDialog() == DialogResult.OK)
           {
-            FileStream fs = (FileStream)dialog.OpenFile();
+            FileStream fs = null;
+            string error = string.Empty;
+            try
+            {
+              fs = (FileStream)dialog.OpenFile();
+            }
+            catch (Exception ex)
+            {
+              error = ex.Message;
+            }
             if (fs == null)
             {
-              MessageBox.Show("Cannot open '" + dialog.FileName + "' for writing", "Pulse-Eight USB-CEC Adapter", MessageBoxButtons.OK, MessageBoxIcon.Error);
+              MessageBox.Show("Cannot open '" + dialog.FileName + "' for writing" + (error.Length > 0 ? ": " + error : string.Empty ), "Pulse-Eight USB-CEC Adapter", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
             else
             {
@@ -488,15 +487,31 @@ namespace CecConfigGui
               output.AppendLine("<settings>");
               output.AppendLine("<setting id=\"cec_hdmi_port\" value=\"" + Config.HDMIPort + "\" />");
               output.AppendLine("<setting id=\"connected_device\" value=\"" + (Config.BaseDevice == CecLogicalAddress.AudioSystem ? 5 : 1) + "\" />");
-              output.AppendLine("<setting id=\"physical_address\" value=\"" + string.Format("{0,4:X}", Config.PhysicalAddress) + "\" />");
-              output.AppendLine("<setting id=\"device_type\" value=\"" + (int)Config.DeviceTypes.Types[0] + "\" />");
-              output.AppendLine("<setting id=\"cec_power_on_startup\" value=\"" + (Config.PowerOnStartup ? 1 : 0) + "\" />");
-              output.AppendLine("<setting id=\"cec_power_off_shutdown\" value=\"" + (Config.PowerOffShutdown ? 1 : 0) + "\" />");
+              output.AppendLine("<setting id=\"cec_power_on_startup\" value=\"" + (Config.ActivateSource ? 1 : 0) + "\" />");
+              output.AppendLine("<setting id=\"cec_power_off_shutdown\" value=\"" + (Config.PowerOffDevices.IsSet(CecLogicalAddress.Broadcast) ? 1 : 0) + "\" />");
               output.AppendLine("<setting id=\"cec_standby_screensaver\" value=\"" + (Config.PowerOffScreensaver ? 1 : 0) + "\" />");
               output.AppendLine("<setting id=\"standby_pc_on_tv_standby\" value=\"" + (Config.PowerOffOnStandby ? 1 : 0) + "\" />");
               output.AppendLine("<setting id=\"use_tv_menu_language\" value=\"" + (Config.UseTVMenuLanguage ? 1 : 0) + "\" />");
               output.AppendLine("<setting id=\"enabled\" value=\"1\" />");
               output.AppendLine("<setting id=\"port\" value=\"\" />");
+
+              // only supported by 1.5.0+ clients
+              output.AppendLine("<setting id=\"physical_address\" value=\"" + string.Format("{0,4:X}", Config.PhysicalAddress) + "\" />");
+              output.AppendLine("<setting id=\"device_type\" value=\"" + (int)Config.DeviceTypes.Types[0] + "\" />");
+              output.AppendLine("<setting id=\"tv_vendor\" value=\"" + string.Format("{0,6:X}", (int)Config.TvVendor) + "\" />");
+
+              output.Append("<setting id=\"wake_devices\" value=\"");
+              foreach (CecLogicalAddress addr in Config.WakeDevices.Addresses)
+                if (addr != CecLogicalAddress.Unregistered)
+                  output.Append(" " + addr);
+              output.AppendLine("\" />");
+
+              output.Append("<setting id=\"standby_devices\" value=\"");
+              foreach (CecLogicalAddress addr in Config.PowerOffDevices.Addresses)
+                if (addr != CecLogicalAddress.Unregistered)
+                  output.Append(" " + addr);
+              output.AppendLine("\" />");
+
               output.AppendLine("</settings>");
               writer.Write(output.ToString());
               writer.Close();
@@ -518,21 +533,249 @@ namespace CecConfigGui
       SetControlsEnabled(true);
     }
 
-    private void tbPhysicalAddress_TextChanged(object sender, EventArgs e)
+    private void cbVendorOverride_CheckedChanged(object sender, EventArgs e)
     {
-      if (ActiveProcess == null)
+      if (cbVendorOverride.Checked)
       {
-        if (tbPhysicalAddress.Text.Length != 4)
-          return;
-        ushort physicalAddress = 0;
-        if (!ushort.TryParse(tbPhysicalAddress.Text, NumberStyles.AllowHexSpecifier, null, out physicalAddress))
-          return;
-        SetControlsEnabled(false);
-        SetControlText(cbPortNumber, string.Empty);
-        SetControlText(cbConnectedDevice, string.Empty);
-        ActiveProcess = new UpdatePhysicalAddress(ref Lib, physicalAddress);
-        ActiveProcess.EventHandler += new EventHandler<UpdateEvent>(ProcessEventHandler);
-        (new Thread(new ThreadStart(ActiveProcess.Run))).Start();
+        cbVendorId.Enabled = true;
+        switch (cbVendorId.Text)
+        {
+          case "LG":
+            Config.TvVendor = CecVendorId.LG;
+            break;
+          case "Onkyo":
+            Config.TvVendor = CecVendorId.Onkyo;
+            break;
+          case "Panasonic":
+            Config.TvVendor = CecVendorId.Panasonic;
+            break;
+          case "Philips":
+            Config.TvVendor = CecVendorId.Philips;
+            break;
+          case "Pioneer":
+            Config.TvVendor = CecVendorId.Pioneer;
+            break;
+          case "Samsung":
+            Config.TvVendor = CecVendorId.Samsung;
+            break;
+          case "Sony":
+            Config.TvVendor = CecVendorId.Sony;
+            break;
+          case "Yamaha":
+            Config.TvVendor = CecVendorId.Yamaha;
+            break;
+          default:
+            Config.TvVendor = CecVendorId.Unknown;
+            break;
+        }
+      }
+      else
+      {
+        cbVendorId.Enabled = false;
+        Config.TvVendor = CecVendorId.Unknown;
+      }
+    }
+    #endregion
+
+    #region Key configuration tab
+    delegate void SelectKeypressRowCallback(CecKeypress key);
+    private void SelectKeypressRow(CecKeypress key)
+    {
+      if (dgButtons.InvokeRequired)
+      {
+        SelectKeypressRowCallback d = new SelectKeypressRowCallback(SelectKeypressRow);
+        try
+        {
+          this.Invoke(d, new object[] { key });
+        }
+        catch (Exception) { }
+      }
+      else
+      {
+        int rowIndex = -1;
+        foreach (DataGridViewRow row in dgButtons.Rows)
+        {
+          CecButtonConfigItem item = row.DataBoundItem as CecButtonConfigItem;
+          if (item != null && item.Key.Keycode == key.Keycode)
+          {
+            rowIndex = row.Index;
+            row.Selected = true;
+            item.Enabled = true;
+          }
+          else
+          {
+            row.Selected = false;
+          }
+        }
+        if (rowIndex > -1)
+          dgButtons.FirstDisplayedScrollingRowIndex = rowIndex;
+      }
+    }
+
+    private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
+    {
+      DataGridView grid = sender as DataGridView;
+      CecButtonConfigItem data = grid.Rows[e.RowIndex].DataBoundItem as CecButtonConfigItem;
+      if (data == null || !data.Enabled)
+        e.CellStyle.ForeColor = Color.Gray;
+    }
+    #endregion
+
+    #region CEC Tester tab
+    delegate CecLogicalAddress GetTargetDeviceCallback();
+    private CecLogicalAddress GetTargetDevice()
+    {
+      if (this.cbCommandDestination.InvokeRequired)
+      {
+        GetTargetDeviceCallback d = new GetTargetDeviceCallback(GetTargetDevice);
+        CecLogicalAddress retval = CecLogicalAddress.Unknown;
+        try
+        {
+          retval = (CecLogicalAddress)this.Invoke(d, new object[] { });
+        }
+        catch (Exception) { }
+        return retval;
+      }
+
+      switch (this.cbCommandDestination.Text.Substring(0, 1).ToLower())
+      {
+        case "0":
+          return CecLogicalAddress.Tv;
+        case "1":
+          return CecLogicalAddress.RecordingDevice1;
+        case "2":
+          return CecLogicalAddress.RecordingDevice2;
+        case "3":
+          return CecLogicalAddress.Tuner1;
+        case "4":
+          return CecLogicalAddress.PlaybackDevice1;
+        case "5":
+          return CecLogicalAddress.AudioSystem;
+        case "6":
+          return CecLogicalAddress.Tuner2;
+        case "7":
+          return CecLogicalAddress.Tuner3;
+        case "8":
+          return CecLogicalAddress.PlaybackDevice2;
+        case "9":
+          return CecLogicalAddress.RecordingDevice3;
+        case "a":
+          return CecLogicalAddress.Tuner4;
+        case "b":
+          return CecLogicalAddress.PlaybackDevice3;
+        case "c":
+          return CecLogicalAddress.Reserved1;
+        case "d":
+          return CecLogicalAddress.Reserved2;
+        case "e":
+          return CecLogicalAddress.FreeUse;
+        case "f":
+          return CecLogicalAddress.Broadcast;
+        default:
+          return CecLogicalAddress.Unknown;
+      }
+    }
+
+    private void bSendImageViewOn_Click(object sender, EventArgs e)
+    {
+      SendImageViewOn(GetTargetDevice());
+    }
+
+    private void bStandby_Click(object sender, EventArgs e)
+    {
+      SendStandby(GetTargetDevice());
+    }
+
+    private void bScan_Click(object sender, EventArgs e)
+    {
+      ShowDeviceInfo(GetTargetDevice());
+    }
+
+    private void bActivateSource_Click(object sender, EventArgs e)
+    {
+      ActivateSource(GetTargetDevice());
+    }
+
+    private void cbCommandDestination_SelectedIndexChanged(object sender, EventArgs e)
+    {
+      bool enableVolumeButtons = (GetTargetDevice() == CecLogicalAddress.AudioSystem);
+      this.bVolUp.Enabled = enableVolumeButtons;
+      this.bVolDown.Enabled = enableVolumeButtons;
+      this.bMute.Enabled = enableVolumeButtons;
+    }
+
+    private void bVolUp_Click(object sender, EventArgs e)
+    {
+      SetControlsEnabled(false);
+      Lib.VolumeUp(true);
+      SetControlsEnabled(true);
+    }
+
+    private void bVolDown_Click(object sender, EventArgs e)
+    {
+      SetControlsEnabled(false);
+      Lib.VolumeDown(true);
+      SetControlsEnabled(true);
+    }
+
+    private void bMute_Click(object sender, EventArgs e)
+    {
+      SetControlsEnabled(false);
+      Lib.MuteAudio(true);
+      SetControlsEnabled(true);
+    }
+    #endregion
+
+    #region Log tab
+    delegate void AddLogMessageCallback(CecLogMessage message);
+    private void AddLogMessage(CecLogMessage message)
+    {
+      if (tbLog.InvokeRequired)
+      {
+        AddLogMessageCallback d = new AddLogMessageCallback(AddLogMessage);
+        try
+        {
+          this.Invoke(d, new object[] { message });
+        }
+        catch (Exception) { }
+      }
+      else
+      {
+        string strLevel = "";
+        bool display = false;
+        switch (message.Level)
+        {
+          case CecLogLevel.Error:
+            strLevel = "ERROR:   ";
+            display = cbLogError.Checked;
+            break;
+          case CecLogLevel.Warning:
+            strLevel = "WARNING: ";
+            display = cbLogWarning.Checked;
+            break;
+          case CecLogLevel.Notice:
+            strLevel = "NOTICE:  ";
+            display = cbLogNotice.Checked;
+            break;
+          case CecLogLevel.Traffic:
+            strLevel = "TRAFFIC: ";
+            display = cbLogTraffic.Checked;
+            break;
+          case CecLogLevel.Debug:
+            strLevel = "DEBUG:   ";
+            display = cbLogDebug.Checked;
+            break;
+          default:
+            break;
+        }
+
+        if (display)
+        {
+          string strLog = string.Format("{0} {1,16} {2}", strLevel, message.Time, message.Message) + System.Environment.NewLine;
+          tbLog.Text += strLog;
+          tbLog.Select(tbLog.Text.Length, 0);
+          tbLog.ScrollToCaret();
+        }
       }
     }
 
@@ -570,16 +813,131 @@ namespace CecConfigGui
         }
       }
     }
+    #endregion
 
-    private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
+    #region LibCecSharp callbacks
+    public int ConfigurationChanged(LibCECConfiguration config)
     {
-      DataGridView grid = sender as DataGridView;
-      CecButtonConfigItem data = grid.Rows[e.RowIndex].DataBoundItem as CecButtonConfigItem;
-      if (data == null || !data.Enabled)
-        e.CellStyle.ForeColor = Color.Gray;
+      Config = config;
+      SetControlText(tbPhysicalAddress, string.Format("{0,4:X}", Config.PhysicalAddress));
+      SetControlText(cbConnectedDevice, Config.BaseDevice == CecLogicalAddress.AudioSystem ? AVRVendorString : TVVendorString);
+      SetControlText(cbPortNumber, Config.HDMIPort.ToString());
+      switch (config.DeviceTypes.Types[0])
+      {
+        case CecDeviceType.RecordingDevice:
+          SetControlText(cbDeviceType, "Recorder");
+          break;
+        case CecDeviceType.PlaybackDevice:
+          SetControlText(cbDeviceType, "Player");
+          break;
+        case CecDeviceType.Tuner:
+          SetControlText(cbDeviceType, "Tuner");
+          break;
+        default:
+          SetControlText(cbDeviceType, "Recorder");
+          break;
+      }
+      if (config.TvVendor != CecVendorId.Unknown)
+      {
+        SetCheckboxChecked(cbVendorOverride, true);
+        SetControlText(cbVendorId, Lib.ToString(config.TvVendor));
+      }
+      else
+      {
+        SetCheckboxChecked(cbVendorOverride, false);
+        SetControlText(cbVendorId, Lib.ToString(TVVendor));
+      }
+
+      SetCheckboxChecked(cbUseTVMenuLanguage, Config.UseTVMenuLanguage);
+      SetCheckboxChecked(cbActivateSource, Config.ActivateSource);
+      SetCheckboxChecked(cbPowerOffScreensaver, Config.PowerOffScreensaver);
+      SetCheckboxChecked(cbPowerOffOnStandby, Config.PowerOffOnStandby);
+      UpdateSelectedDevice();
+      return 1;
+    }
+
+    public int ReceiveCommand(CecCommand command)
+    {
+      return 1;
+    }
+
+    public int ReceiveKeypress(CecKeypress key)
+    {
+      SelectKeypressRow(key);
+      return 1;
+    }
+
+    public int ReceiveLogMessage(CecLogMessage message)
+    {
+      AddLogMessage(message);
+      return 1;
+    }
+    #endregion
+
+    #region Class members
+    public bool HasAVRDevice { get; private set; }
+    #region TV Vendor
+    private CecVendorId _tvVendor = CecVendorId.Unknown;
+    public CecVendorId TVVendor
+    {
+      get { return _tvVendor;}
+      private set { _tvVendor = value; }
+    }
+    public string TVVendorString
+    {
+      get
+      {
+        return TVVendor != CecVendorId.Unknown ?
+          "Television (" + Lib.ToString(TVVendor) + ")" :
+          "Television";
+      }
+    }
+    #endregion
+    #region AVR Vendor
+    private CecVendorId _avrVendor = CecVendorId.Unknown;
+    public CecVendorId AVRVendor
+    {
+      get { return _avrVendor; }
+      private set { _avrVendor = value; }
+    }
+    public string AVRVendorString
+    {
+      get
+      {
+        return AVRVendor != CecVendorId.Unknown ?
+          "AVR (" + Lib.ToString(AVRVendor) + ")" :
+          "AVR";
+      }
     }
+    #endregion
+    public CecLogicalAddress SelectedConnectedDevice
+    {
+      get
+      {
+        return (cbConnectedDevice.Text.Equals(AVRVendorString)) ? CecLogicalAddress.AudioSystem : CecLogicalAddress.Tv;
+      }
+    }
+    public int SelectedPortNumber
+    {
+      get
+      {
+        int iPortNumber = 0;
+        if (!int.TryParse(cbPortNumber.Text, out iPortNumber))
+          iPortNumber = 1;
+        return iPortNumber;
+      }
+    }
+    protected LibCECConfiguration Config;
+    protected LibCecSharp Lib;
+    private CecCallbackWrapper Callbacks;
+    private UpdateProcess ActiveProcess = null;
+    private bool SuppressUpdates = false;
+    #endregion
   }
 
+  /// <summary>
+  /// A little wrapper that is needed because we already inherit form
+  /// </summary>
   internal class CecCallbackWrapper : CecCallbackMethods
   {
     public CecCallbackWrapper(CecConfigGUI gui)
@@ -602,6 +960,11 @@ namespace CecConfigGui
       return Gui.ReceiveLogMessage(message);
     }
 
+    public override int ConfigurationChanged(LibCECConfiguration config)
+    {
+      return Gui.ConfigurationChanged(config);
+    }
+
     private CecConfigGUI Gui;
   }
 }