2 * This file is part of the libCEC(R) library.
4 * libCEC(R) is Copyright (C) 2011-2012 Pulse-Eight Limited. All rights reserved.
5 * libCEC(R) is an original work, containing original code.
7 * libCEC(R) is a trademark of Pulse-Eight Limited.
9 * This program is dual-licensed; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 * Alternatively, you can license this library under a commercial license,
25 * please contact Pulse-Eight Licensing for more information.
27 * For more information contact:
28 * Pulse-Eight Licensing <license@pulse-eight.com>
29 * http://www.pulse-eight.com/
30 * http://www.pulse-eight.net/
34 using System.Diagnostics;
37 using System.Windows.Forms;
39 using LibCECTray.Properties;
40 using LibCECTray.settings;
41 using Timer = System.Timers.Timer;
43 namespace LibCECTray.controller.applications
46 /// Controls an application on the PC: send key presses, open the application, close it, etc.
48 class ApplicationController
50 public ApplicationController(CECSettings settings, string uiName, string processName, string filename, string workingDirectory)
54 ProcessName = processName;
55 ApplicationFilename = filename;
56 ApplicationWorkingDirectory = workingDirectory;
57 SuppressApplicationStart = false;
61 public static ApplicationController FromString(CECSettings settings, string serialisedConfig)
63 var splitString = serialisedConfig.Split(';');
64 if (splitString.Length != 4)
65 throw new InvalidDataException("incorrect number of parameters");
67 return new ApplicationController(settings, splitString[0], splitString[1], splitString[2], splitString[3]);
70 public string AsString()
72 return string.Format("{0};{1};{2};{3}", UiName, ProcessName, ApplicationFilename, ApplicationWorkingDirectory);
75 public void BindButtonConfiguration(DataGridView gridView, BindingSource bindingSource)
77 CecButtonGridView = gridView;
79 DataGridViewCell buttonCellTemplate = new DataGridViewTextBoxCell();
80 CecButtonGridView.Columns.Add(new DataGridViewColumn(buttonCellTemplate)
82 DataPropertyName = "CecButtonName",
83 Name = Resources.config_cec_button,
88 DataGridViewButtonCell mappedToCellTemplate = new DataGridViewButtonCell();
89 CecButtonGridView.Columns.Add(new DataGridViewColumn(mappedToCellTemplate)
91 DataPropertyName = "MappedButtonName",
92 Name = Resources.config_button_mapped_to,
97 bindingSource.DataSource = ButtonConfig;
98 CecButtonGridView.DataSource = bindingSource;
100 gridView.CellFormatting += delegate(object sender, DataGridViewCellFormattingEventArgs args)
102 DataGridView grid = sender as DataGridView;
103 var data = grid != null ? grid.Rows[args.RowIndex].DataBoundItem as CecButtonConfigItem : null;
104 if (data == null || !data.Enabled)
106 args.CellStyle.ForeColor = Color.Gray;
110 gridView.CellClick += delegate(object sender, DataGridViewCellEventArgs args)
112 var item = args.RowIndex < ButtonConfig.Count ? ButtonConfig[args.RowIndex] : null;
115 (new CecButtonConfigUI(item)).ShowDialog();
118 foreach (var item in _buttonConfig)
120 item.SettingChanged += delegate
127 #region Start and stop the application
129 /// Check if the application is running
131 /// <returns>True when running, false otherwise</returns>
132 public virtual bool IsRunning()
134 return FindInstance() != IntPtr.Zero;
138 /// Start the application if it's not running already, and suppress further starts for 5 seconds
140 /// <returns>True when started or suppressed, false otherwise</returns>
141 public virtual bool Start(bool bExitAfterStarting)
149 if (SuppressApplicationStart)
152 SuppressApplicationStart = true;
153 Timer timer = new Timer {Interval = 5000, AutoReset = false};
154 timer.Elapsed += delegate { SuppressApplicationStart = false; };
160 Process runningProcess = new Process
164 WorkingDirectory = ApplicationWorkingDirectory,
165 FileName = ApplicationFilename
169 // start maximised if the option is enabled
170 if (StartFullScreen.Value)
171 runningProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
173 runningProcess.Start();
181 if (bExitAfterStarting)
188 /// Initialise the controller and autostart the application
190 public virtual void Initialise()
192 Timer timer = new Timer { Interval = 1000, AutoReset = true };
193 timer.Elapsed += delegate { UiControl.SetStartButtonEnabled(true); };
196 if (AutoStartApplication.Value)
201 #region Send input to the application
203 /// Send a keypress to the application if it's running
205 /// <param name="key">The keypress to send</param>
206 /// <param name="isSelectedTab">True when this tab is currently selected in the UI</param>
207 /// <returns>True when sent, false otherwise</returns>
208 public virtual bool SendKey(CecKeypress key, bool isSelectedTab)
211 UiControl.SelectKeypressRow(UiControl, CecButtonGridView, key);
213 if (isSelectedTab && SuppressKeypressWhenSelected.Value)
216 if (!ControlApplication.Value)
219 var mappedButton = ButtonConfig[key];
220 if (mappedButton == null || mappedButton.Value.Empty())
223 var controlWindow = FindInstance();
224 if (controlWindow != IntPtr.Zero && key.Duration == 0)
225 return mappedButton.Value.Transmit(controlWindow);
231 #region Process control
233 /// Make this application the foreground application if it's running
235 public virtual void SetForeground()
237 var wmcInstance = FindInstance();
238 if (wmcInstance != IntPtr.Zero)
239 WindowsAPI.SetForegroundWindow(wmcInstance);
243 /// The main window handle of the application if it's running.
245 /// <returns>The main window handle, or IntPtr.Zero if it's not found</returns>
246 protected virtual IntPtr FindInstance()
248 var processes = Process.GetProcessesByName(ProcessName);
249 return processes.Length > 0 ? processes[0].MainWindowHandle : IntPtr.Zero;
255 /// The name of the process in the process manager
257 public string ProcessName { set; get; }
260 /// The filename of the application
262 public string ApplicationFilename { set; get; }
265 /// The working directory of the application
267 public string ApplicationWorkingDirectory { set; get; }
270 /// Don't start the application while true
272 public bool SuppressApplicationStart { get; private set; }
275 /// The name of the application how it shows up in this application
277 public string UiName { set; get; }
280 /// True when this application should be autostarted when this application is activated, or made the active source
282 public CECSettingBool AutoStartApplication
286 if (!Settings.ContainsKey(ProcessName + "_autostart"))
288 CECSettingBool setting = new CECSettingBool(ProcessName + "_autostart", "Autostart application", false, null);
289 Settings.Load(setting);
290 Settings[ProcessName + "_autostart"] = setting;
292 return Settings[ProcessName + "_autostart"].AsSettingBool;
297 /// True when keypresses should be routed to this application
299 public CECSettingBool ControlApplication
303 if (!Settings.ContainsKey(ProcessName + "_control"))
305 CECSettingBool setting = new CECSettingBool(ProcessName + "_control", "Control application", true, null);
306 Settings.Load(setting);
307 Settings[ProcessName + "_control"] = setting;
309 return Settings[ProcessName + "_control"].AsSettingBool;
314 /// True when this application should be autostarted when this application is activated, or made the active source
316 public CECSettingBool SuppressKeypressWhenSelected
320 if (!Settings.ContainsKey(ProcessName + "_suppress_when_selected"))
322 CECSettingBool setting = new CECSettingBool(ProcessName + "_suppress_when_selected", "Suppress keypress when this tab is selected", true, null);
323 Settings.Load(setting);
324 Settings[ProcessName + "_suppress_when_selected"] = setting;
326 return Settings[ProcessName + "_suppress_when_selected"].AsSettingBool;
331 /// True when the application should be started in full screen mode
333 public CECSettingBool StartFullScreen
337 if (!Settings.ContainsKey(ProcessName + "_start_fullscreen"))
339 CECSettingBool setting = new CECSettingBool(ProcessName + "_start_fullscreen", "Start in full screen mode", true, null);
340 Settings.Load(setting);
341 Settings[ProcessName + "_start_fullscreen"] = setting;
343 return Settings[ProcessName + "_start_fullscreen"].AsSettingBool;
347 protected ControllerTabPage UIControlInternal;
348 public virtual ControllerTabPage UiControl
350 get { return UIControlInternal ?? (UIControlInternal = new ApplicationControllerUI(this)); }
353 private CecButtonConfig _buttonConfig;
354 public CecButtonConfig ButtonConfig
358 if (_buttonConfig == null)
360 _buttonConfig = new CecButtonConfig(this);
361 foreach (CecUserControlCode key in Enum.GetValues(typeof(CecUserControlCode)))
362 _buttonConfig.Add(new CecButtonConfigItem(this, (new CecKeypress { Keycode = key })));
364 _buttonConfig.Load();
366 return _buttonConfig;
370 public CECSettings Settings;
371 protected DataGridView CecButtonGridView;
373 public virtual ApplicationAction DefaultValue(CecKeypress key)
378 public virtual bool HasDefaultValue(CecKeypress key)
380 return DefaultValue(key) != null;
383 public bool IsInternal { protected set; get; }
384 public bool CanConfigureProcess