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
45 public delegate void OnApplicationRunningChanged(bool running);
48 /// Controls an application on the PC: send key presses, open the application, close it, etc.
50 class ApplicationController
52 public ApplicationController(CECSettings settings, string uiName, string processName, string filename, string workingDirectory)
56 ProcessName = processName;
57 ApplicationFilename = filename;
58 ApplicationWorkingDirectory = workingDirectory;
59 SuppressApplicationStart = false;
63 public static ApplicationController FromString(CECSettings settings, string serialisedConfig)
65 var splitString = serialisedConfig.Split(';');
66 if (splitString.Length != 4)
67 throw new InvalidDataException("incorrect number of parameters");
69 return new ApplicationController(settings, splitString[0], splitString[1], splitString[2], splitString[3]);
72 public string AsString()
74 return string.Format("{0};{1};{2};{3}", UiName, ProcessName, ApplicationFilename, ApplicationWorkingDirectory);
77 public void BindButtonConfiguration(DataGridView gridView, BindingSource bindingSource)
79 CecButtonGridView = gridView;
81 DataGridViewCell buttonCellTemplate = new DataGridViewTextBoxCell();
82 CecButtonGridView.Columns.Add(new DataGridViewColumn(buttonCellTemplate)
84 DataPropertyName = "CecButtonName",
85 Name = Resources.config_cec_button,
90 DataGridViewButtonCell mappedToCellTemplate = new DataGridViewButtonCell();
91 CecButtonGridView.Columns.Add(new DataGridViewColumn(mappedToCellTemplate)
93 DataPropertyName = "MappedButtonName",
94 Name = Resources.config_button_mapped_to,
99 bindingSource.DataSource = ButtonConfig;
100 CecButtonGridView.DataSource = bindingSource;
102 gridView.CellFormatting += delegate(object sender, DataGridViewCellFormattingEventArgs args)
104 DataGridView grid = sender as DataGridView;
105 var data = grid != null ? grid.Rows[args.RowIndex].DataBoundItem as CecButtonConfigItem : null;
106 if (data == null || !data.Enabled)
108 args.CellStyle.ForeColor = Color.Gray;
112 gridView.CellClick += delegate(object sender, DataGridViewCellEventArgs args)
114 var item = args.RowIndex < ButtonConfig.Count ? ButtonConfig[args.RowIndex] : null;
117 (new CecButtonConfigUI(item)).ShowDialog();
120 foreach (var item in _buttonConfig)
122 item.SettingChanged += delegate
129 #region Start and stop the application
131 /// Check if the application is running
133 /// <returns>True when running, false otherwise</returns>
134 public virtual bool IsRunning()
136 return FindInstance() != IntPtr.Zero;
140 /// Start the application if it's not running already, and suppress further starts for 5 seconds
142 /// <returns>True when started or suppressed, false otherwise</returns>
143 public virtual bool Start(bool bExitAfterStarting)
151 if (SuppressApplicationStart)
154 SuppressApplicationStart = true;
155 Timer timer = new Timer {Interval = 5000, AutoReset = false};
156 timer.Elapsed += delegate { SuppressApplicationStart = false; };
162 Process runningProcess = new Process
166 WorkingDirectory = ApplicationWorkingDirectory,
167 FileName = ApplicationFilename
171 // start maximised if the option is enabled
172 if (StartFullScreen.Value)
173 runningProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
175 runningProcess.Start();
183 if (bExitAfterStarting)
190 /// Initialise the controller and autostart the application
192 public virtual void Initialise()
194 Timer timer = new Timer { Interval = 1000, AutoReset = true };
195 timer.Elapsed += delegate { CheckApplicationEnabled(); };
198 if (AutoStartApplication.Value)
202 public event OnApplicationRunningChanged ApplicationRunningChanged;
204 private void CheckApplicationEnabled()
206 var isRunning = IsRunning();
207 if (isRunning != _applicationRunning && ApplicationRunningChanged != null)
208 ApplicationRunningChanged(isRunning);
210 _applicationRunning = isRunning;
211 UiControl.SetStartButtonEnabled(!isRunning && !SuppressApplicationStart);
215 #region Send input to the application
217 /// Send a keypress to the application if it's running
219 /// <param name="key">The keypress to send</param>
220 /// <param name="isSelectedTab">True when this tab is currently selected in the UI</param>
221 /// <returns>True when sent, false otherwise</returns>
222 public virtual bool SendKey(CecKeypress key, bool isSelectedTab)
225 UiControl.SelectKeypressRow(UiControl, CecButtonGridView, key);
227 if (isSelectedTab && SuppressKeypressWhenSelected.Value)
230 if (!ControlApplication.Value)
233 var mappedButton = ButtonConfig[key];
234 if (mappedButton == null || mappedButton.Value.Empty())
237 var controlWindow = FindInstance();
238 if (controlWindow != IntPtr.Zero && key.Duration == 0)
239 return mappedButton.Value.Transmit(controlWindow);
245 #region Process control
247 /// Make this application the foreground application if it's running
249 public virtual void SetForeground()
251 var wmcInstance = FindInstance();
252 if (wmcInstance != IntPtr.Zero)
253 WindowsAPI.SetForegroundWindow(wmcInstance);
257 /// The main window handle of the application if it's running.
259 /// <returns>The main window handle, or IntPtr.Zero if it's not found</returns>
260 protected virtual IntPtr FindInstance()
262 var processes = Process.GetProcessesByName(ProcessName);
263 return processes.Length > 0 ? processes[0].MainWindowHandle : IntPtr.Zero;
269 /// The name of the process in the process manager
271 public string ProcessName { set; get; }
274 /// The filename of the application
276 public string ApplicationFilename { set; get; }
279 /// The working directory of the application
281 public string ApplicationWorkingDirectory { set; get; }
284 /// Don't start the application while true
286 public bool SuppressApplicationStart { get; private set; }
289 /// The name of the application how it shows up in this application
291 public string UiName { set; get; }
294 /// True when this application should be autostarted when this application is activated, or made the active source
296 public CECSettingBool AutoStartApplication
300 if (!Settings.ContainsKey(ProcessName + "_autostart"))
302 CECSettingBool setting = new CECSettingBool(ProcessName + "_autostart", "Autostart application", false, null);
303 Settings.Load(setting);
304 Settings[ProcessName + "_autostart"] = setting;
306 return Settings[ProcessName + "_autostart"].AsSettingBool;
311 /// True when keypresses should be routed to this application
313 public CECSettingBool ControlApplication
317 if (!Settings.ContainsKey(ProcessName + "_control"))
319 CECSettingBool setting = new CECSettingBool(ProcessName + "_control", "Control application", true, null);
320 Settings.Load(setting);
321 Settings[ProcessName + "_control"] = setting;
323 return Settings[ProcessName + "_control"].AsSettingBool;
328 /// True when this application should be autostarted when this application is activated, or made the active source
330 public CECSettingBool SuppressKeypressWhenSelected
334 if (!Settings.ContainsKey(ProcessName + "_suppress_when_selected"))
336 CECSettingBool setting = new CECSettingBool(ProcessName + "_suppress_when_selected", "Suppress keypress when this tab is selected", true, null);
337 Settings.Load(setting);
338 Settings[ProcessName + "_suppress_when_selected"] = setting;
340 return Settings[ProcessName + "_suppress_when_selected"].AsSettingBool;
345 /// True when the application should be started in full screen mode
347 public CECSettingBool StartFullScreen
351 if (!Settings.ContainsKey(ProcessName + "_start_fullscreen"))
353 CECSettingBool setting = new CECSettingBool(ProcessName + "_start_fullscreen", "Start in full screen mode", true, null);
354 Settings.Load(setting);
355 Settings[ProcessName + "_start_fullscreen"] = setting;
357 return Settings[ProcessName + "_start_fullscreen"].AsSettingBool;
361 protected ControllerTabPage UIControlInternal;
362 public virtual ControllerTabPage UiControl
364 get { return UIControlInternal ?? (UIControlInternal = new ApplicationControllerUI(this)); }
367 private CecButtonConfig _buttonConfig;
368 public CecButtonConfig ButtonConfig
370 get { return _buttonConfig ?? (_buttonConfig = new CecButtonConfig(this)); }
373 public CECSettings Settings;
374 protected DataGridView CecButtonGridView;
376 public virtual ApplicationAction DefaultValue(CecKeypress key)
381 public virtual bool HasDefaultValue(CecKeypress key)
383 return DefaultValue(key) != null;
386 public bool IsInternal { protected set; get; }
387 public bool CanConfigureProcess
395 private bool _applicationRunning;