PageRenderTime 75ms CodeModel.GetById 39ms RepoModel.GetById 1ms app.codeStats 0ms

/RPS 4/Config.cs

http://github.com/marijnkampf/Visual-C---Random-Photo-Screensaver
C# | 1120 lines | 942 code | 84 blank | 94 comment | 191 complexity | c338654b862653d1a0eeeff7e77c1bcc MD5 | raw file
Possible License(s): GPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Threading;
  9. using System.Windows.Forms;
  10. using System.Diagnostics;
  11. using System.Security.Permissions;
  12. using System.Configuration;
  13. using System.IO;
  14. using System.Data.SQLite;
  15. //using System.Data.SQLite.Linq;
  16. using System.Data.Linq;
  17. using System.Linq;
  18. using System.Data.Linq.Mapping;
  19. using System.Collections;
  20. //using System.DirectoryServices;
  21. //using System.Management;
  22. using Newtonsoft.Json;
  23. using Microsoft.Win32;
  24. using System.Net;
  25. /***
  26. *
  27. * TODO: Reflect changes made in config.html into this.persistant!!!
  28. *
  29. *
  30. *
  31. *
  32. * Consider optimising by storing all values from html in c# array?
  33. * this.folders: takes 0.0002ms - 0.0005ms
  34. * this.browser.Document.GetElementById(id).InnerHtml takes 55.1357ms first request and 0.2303ms - 0.3389ms consequtive requests
  35. *
  36. ***/
  37. namespace RPS {
  38. [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
  39. [System.Runtime.InteropServices.ComVisibleAttribute(true)]
  40. public partial class Config : Form {
  41. public enum Order { Random = 1, Sequential = 0 };
  42. private bool configInitialised = false;
  43. private Dictionary<string, object> persistant;
  44. DBConnector dbConnector;
  45. //SQLiteConnection connection;
  46. private Screensaver screensaver;
  47. private Dictionary<string, object> trackChanges = new Dictionary<string, object>() {
  48. {"folders", null},
  49. {"excludedSubfolders", null},
  50. {"excludeAllSubfolders", null},
  51. {"ignoreHiddenFiles", null},
  52. {"ignoreHiddenFolders", null},
  53. {"imageExtensions", null},
  54. {"videoExtensions", null},
  55. {"rawExtensions", null},
  56. };
  57. public long maxMonitorDimension = 0;
  58. public jsonFolder effects;
  59. private bool checkUpdates = false;
  60. private bool downloadUpdates = false;
  61. private bool newVersionAvailable = false;
  62. private Stopwatch downloadProgress = new Stopwatch();
  63. //private bool installUpdates = false;
  64. //public WebBrowser browser;
  65. //private delegate void AddBrowser();
  66. public Config(Screensaver screensaver) {
  67. this.screensaver = screensaver;
  68. this.InitializeComponent();
  69. this.browser.ObjectForScripting = this;
  70. this.browser.AllowWebBrowserDrop = false;
  71. foreach (Screen screen in Screen.AllScreens) {
  72. this.maxMonitorDimension = Math.Max(Math.Max(this.maxMonitorDimension, screen.Bounds.Width), screen.Bounds.Height);
  73. }
  74. }
  75. public SQLiteConnection connectToDB() {
  76. this.dbConnector = new DBConnector(Constants.selectProgramAppDataFolder(Constants.PersistantConfigFileName), Constants.SettingsDefinition, false);
  77. //return new SQLiteConnection("Data Source=" + path + ";Version=3;");
  78. return this.dbConnector.connection;
  79. }
  80. public void saveDebug() {
  81. string path = this.browser.Url.LocalPath.Replace(Constants.ConfigHtmlFile, "_C_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".html");
  82. File.WriteAllText(path, this.browser.Document.GetElementsByTagName("HTML")[0].OuterHtml);
  83. }
  84. public string jsFileBrowserDialog(string filename, string filter) {
  85. OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog();
  86. if (filename == null) filename = "";
  87. else dialog.InitialDirectory = Path.GetFullPath(filename);
  88. dialog.FileName = Path.GetFileName(filename);
  89. if (filter != null && filter.Length > 0) {
  90. dialog.Filter = filter;
  91. }
  92. if (dialog.ShowDialog() == DialogResult.OK) {
  93. return dialog.FileName;
  94. } else {
  95. return filename;
  96. }
  97. }
  98. public string jsFolderBrowserDialog(string path) {
  99. FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
  100. dialog.SelectedPath = path;
  101. if (dialog.ShowDialog() == DialogResult.OK) {
  102. return dialog.SelectedPath;
  103. } else {
  104. return path;
  105. }
  106. }
  107. public string jsRawConverterAvailable(string path) {
  108. if (File.Exists(path)) return "true";
  109. else return "false";
  110. }
  111. public string jsGetUFRawLocation() {
  112. string path = (string) Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\IntelliPoint\\AppSpecific\\ufraw.exe", "Path", null);
  113. path = path.Replace("ufraw.exe", "ufraw-batch.exe");
  114. if (path != null && path.Length > 0) {
  115. if (File.Exists(path)) {
  116. return path;
  117. }
  118. }
  119. return null;
  120. }
  121. public void jsInputChanged(string id, string value) {
  122. this.setPersistant(id, value, false);
  123. }
  124. public void jsSetSelectedEffects(string jsonEffects) {
  125. this.effects = JsonConvert.DeserializeObject<jsonFolder>(jsonEffects);
  126. this.persistant["effects"] = jsonEffects;
  127. }
  128. public void jsOpenExternalLink(string href) {
  129. Utils.RunTaskScheduler("OpenURL", "explorer.exe", "\"" + href + "\"");
  130. }
  131. public string jsGetSelectedEffects() {
  132. return JsonConvert.SerializeObject(this.effects);
  133. }
  134. public string jsGetFilters() {
  135. try {
  136. return this.getPersistantString("filters");
  137. } catch(System.Collections.Generic.KeyNotFoundException e) {
  138. return null;
  139. }
  140. }
  141. public string jsGetFilterColumns() {
  142. Dictionary<string, ColumnInfo> columns;
  143. columns = Constants.FileNodesDefinition.columns.Union(Constants.MetadataDefinition.columns)
  144. .ToLookup(pair => pair.Key, pair => pair.Value)
  145. .ToDictionary(group => group.Key, group => group.First());
  146. return JsonConvert.SerializeObject(columns/*, Newtonsoft.Json.Formatting.Indented*/);
  147. }
  148. public void jsOpenProgramAppDataFolder() {
  149. if (Utils.RunTaskScheduler(@"OpenInExplorer", "explorer.exe", "\"" + Constants.selectProgramAppDataFolder("") + "\"")) {
  150. //this.monitors[i].showInfoOnMonitor("Opened in Explorer Window", false, true);
  151. }
  152. }
  153. public void setBrowserBodyClasses(WebBrowser browser, Screensaver.Actions action) {
  154. setBrowserBodyClasses(browser, action, null);
  155. }
  156. public static void setBrowserBodyClasses(WebBrowser browser, Screensaver.Actions action, string classes) {
  157. HtmlElementCollection elems = browser.Document.GetElementsByTagName("body");
  158. foreach (HtmlElement elem in elems) {
  159. switch (action) {
  160. case Screensaver.Actions.Preview: classes += " preview"; break;
  161. case Screensaver.Actions.Config: classes += " config"; break;
  162. case Screensaver.Actions.Screensaver: classes += " screensaver"; break;
  163. case Screensaver.Actions.Test: classes += " test"; break;
  164. case Screensaver.Actions.Slideshow: classes += " slideshow"; break;
  165. }
  166. classes += " IE" + browser.Version.Major;
  167. if (browser.Version.Major < 8) classes += " lowIE";
  168. elem.SetAttribute("className", elem.GetAttribute("className") + classes);
  169. }
  170. }
  171. public void loadPersistantConfig() {
  172. if (this.screensaver.monitors != null) this.loadPersistantConfig(this.screensaver.monitors.Length);
  173. else this.loadPersistantConfig(Screen.AllScreens.Length);
  174. }
  175. public void loadPersistantConfig(int nrMonitors) {
  176. #if (DEBUG)
  177. this.screensaver.debugLog.Add("loadPersistantConfig(" + nrMonitors + ")");
  178. #endif
  179. //SQLiteConnection connection =
  180. this.connectToDB();
  181. this.persistant = new Dictionary<string, object>();
  182. DataContext context = new DataContext(this.dbConnector.connection);
  183. var items = context.GetTable<Setting>();
  184. foreach(Setting item in items) {
  185. this.persistant.Add(item.Key, item.Value);
  186. }
  187. if (!this.persistant.ContainsKey("filterNrLines")) this.persistant["filterNrLines"] = 0;
  188. object regvalue = Registry.GetValue("HKEY_CURRENT_USER\\" + Constants.regkeyGPURendering, Constants.regkeyExecutable, 0);
  189. bool gpuRendering = (regvalue != null && (int)regvalue == 1);
  190. if (this.persistant.ContainsKey("gpuRendering")) this.persistant["gpuRendering"] = gpuRendering;
  191. else this.persistant.Add("gpuRendering", gpuRendering);
  192. //this.browser.Document.InvokeScript("initMonitorsAndFilterCount", new string[] { Convert.ToString(Screen.AllScreens.Length), Convert.ToString(this.persistant["filterNrLines"]) });
  193. this.browser.Document.InvokeScript("initMonitors", new string[] { Convert.ToString(Screen.AllScreens.Length) });
  194. if (!this.persistant.ContainsKey("folders") || this.persistant["folders"] == null || this.getPersistantString("folders").Trim().Length == 0) {
  195. string path = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures) + Environment.NewLine +
  196. Environment.GetFolderPath(Environment.SpecialFolder.MyVideos);
  197. if (!this.persistant.ContainsKey("folders")) {
  198. this.persistant.Add("folders", path);
  199. } else {
  200. this.persistant["folders"] = path;
  201. }
  202. }
  203. if (!this.persistant.ContainsKey("rawFolder") || this.persistant["rawFolder"] == null || Convert.ToString(this.persistant["rawFolder"]).Trim().Length == 0) {
  204. string path = Path.Combine(
  205. Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
  206. AppSettings.Name,
  207. Constants.RawCacheFolder
  208. );
  209. if (!this.persistant.ContainsKey("rawFolder")) {
  210. this.persistant.Add("rawFolder", path);
  211. } else {
  212. this.persistant["rawFolder"] = path;
  213. }
  214. }
  215. if (this.persistant.ContainsKey("effects") && this.persistant["effects"] != null && Convert.ToString(this.persistant["effects"]) != "null" && Convert.ToString(this.persistant["effects"]).Trim().Length > 0) {
  216. this.effects = JsonConvert.DeserializeObject<jsonFolder>(Convert.ToString(this.persistant["effects"]));
  217. } else {
  218. this.effects = new jsonFolder();
  219. }
  220. string jsonPath = Constants.getDataFolder(Constants.EffectsJsonFile);
  221. if (File.Exists(jsonPath)) {
  222. //this.effects = new jsonFolder();
  223. JsonSerializer serializer = new JsonSerializer();
  224. serializer.NullValueHandling = NullValueHandling.Ignore;
  225. using (StreamReader sr = new StreamReader(jsonPath))
  226. using (JsonReader reader = new JsonTextReader(sr)) {
  227. jsonFolder newEffects = serializer.Deserialize<jsonFolder>(reader);
  228. this.effects.mergeChildren(newEffects);
  229. }
  230. }
  231. HtmlElementCollection hec = this.GetElementsByTagName("input");
  232. foreach (HtmlElement e in hec) {
  233. if (this.persistant.ContainsKey(e.GetAttribute("id")) || (e.GetAttribute("type") == "radio" && this.persistant.ContainsKey(e.GetAttribute("name")))) {
  234. switch (e.GetAttribute("type")) {
  235. case "checkbox":
  236. if (this.getPersistantBool(e.GetAttribute("id")) == true) {
  237. e.SetAttribute("checked", "true");
  238. } else {
  239. e.SetAttribute("checked", "");
  240. }
  241. break;
  242. case "radio":
  243. if (this.getPersistantString(e.GetAttribute("name")) == e.GetAttribute("value")) {
  244. e.SetAttribute("checked", "true");
  245. }
  246. break;
  247. default:
  248. e.SetAttribute("value", this.getPersistantString(e.GetAttribute("id")));
  249. break;
  250. }
  251. } else {
  252. switch (e.GetAttribute("type")) {
  253. case "checkbox":
  254. this.persistant[e.GetAttribute("id")] = this.getDomCheckboxValue(e.GetAttribute("id"));
  255. break;
  256. case "radio":
  257. this.persistant[e.GetAttribute("name")] = this.getDomRadioValue(e.GetAttribute("name"));
  258. break;
  259. default:
  260. this.persistant[e.GetAttribute("id")] = this.getDomValue(e.GetAttribute("id"));
  261. break;
  262. }
  263. // Set persistant value with default
  264. }
  265. }
  266. hec = this.browser.Document.GetElementsByTagName("textarea");
  267. foreach (HtmlElement e in hec) {
  268. if (this.persistant.ContainsKey(e.GetAttribute("id"))) {
  269. e.SetAttribute("value", Utils.HtmlDecode(Convert.ToString(this.persistant[e.GetAttribute("id")])));
  270. } else {
  271. this.persistant[e.GetAttribute("id")] = Utils.HtmlDecode(this.getDomValue(e.GetAttribute("id")));
  272. }
  273. }
  274. hec = this.browser.Document.GetElementsByTagName("select");
  275. foreach (HtmlElement e in hec) {
  276. if (this.persistant.ContainsKey(e.GetAttribute("id"))) {
  277. e.SetAttribute("value", Convert.ToString(this.persistant[e.GetAttribute("id")]));
  278. } else {
  279. this.persistant[e.GetAttribute("id")] = this.getDomValue(e.GetAttribute("id"));
  280. }
  281. }
  282. string classes = null;
  283. if (nrMonitors > 1) classes += "multi ";
  284. if (this.screensaver.readOnly) classes += "readonly ";
  285. Config.setBrowserBodyClasses(this.browser, this.screensaver.action, classes);
  286. this.browser.Document.InvokeScript("persistantConfigLoaded", new string[] { Convert.ToString(Screen.AllScreens.Length) });
  287. if (this.screensaver.action == Screensaver.Actions.Preview && this.screensaver.monitors != null) {
  288. this.screensaver.monitors[0].defaultShowHide();
  289. }
  290. }
  291. public string jsonAllPersistant() {
  292. if (this.persistant != null) {
  293. return JsonConvert.SerializeObject(this.persistant, Newtonsoft.Json.Formatting.Indented);
  294. }
  295. return null;
  296. }
  297. public bool savePersistantConfig() {
  298. if (this.persistant != null) {
  299. this.persistant["effects"] = JsonConvert.SerializeObject(this.effects);
  300. this.persistant["filters"] = Convert.ToString(this.browser.Document.InvokeScript("getJsonFilters"));
  301. if (this.screensaver.action != Screensaver.Actions.Config) {
  302. for (int i = 0; i < this.screensaver.monitors.Length; i++) {
  303. this.persistant["historyM" + Convert.ToString(i)] = JsonConvert.SerializeObject(this.screensaver.monitors[i].historyLastEntries(Convert.ToInt32(this.getPersistant("rememberLast"))));
  304. this.persistant["historyOffsetM" + Convert.ToString(i)] = Convert.ToString(this.screensaver.monitors[i].offset);
  305. }
  306. }
  307. this.connectToDB();
  308. SQLiteTransaction transaction = null;
  309. try {
  310. transaction = this.dbConnector.connection.BeginTransaction(true);
  311. } catch (System.Data.SQLite.SQLiteException se) {
  312. this.screensaver.showInfoOnMonitors("Error: " + se.Message, true);
  313. return false;
  314. }
  315. foreach (var p in this.persistant) {
  316. SQLiteCommand insertSQL = new SQLiteCommand("INSERT OR REPLACE INTO Setting (key, value) VALUES (@key, @value);", this.dbConnector.connection);
  317. insertSQL.Parameters.AddWithValue("@key", p.Key);
  318. insertSQL.Parameters.AddWithValue("@value", p.Value);
  319. insertSQL.ExecuteNonQuery();
  320. }
  321. transaction.Commit();
  322. }
  323. return true;
  324. }
  325. public void Message(string Text) {
  326. MessageBox.Show(Text);
  327. }
  328. public HtmlElementCollection GetElementsByTagName(string name) {
  329. return (HtmlElementCollection)this.browser.Invoke(new Func<HtmlElementCollection>(() => this.browser.Document.GetElementsByTagName(name)));
  330. }
  331. /****
  332. * Called from config.js
  333. ****/
  334. public void jsApplyFilter(string filter) {
  335. if (this.screensaver.fileNodes != null) {
  336. try {
  337. this.screensaver.fileNodes.setFilterSQL(filter);
  338. } catch (System.Data.SQLite.SQLiteException e) {
  339. this.clearFilter();
  340. this.setDomValue("useFilter", "false");
  341. MessageBox.Show(e.Message + Environment.NewLine + "Correct fault and re-apply filter", "Filter fault", MessageBoxButtons.OK, MessageBoxIcon.Error);
  342. }
  343. }
  344. }
  345. public void jsClearFilter(string jsDummy) {
  346. this.clearFilter();
  347. this.setDomValue("useFilter", "false");
  348. }
  349. public void clearFilter() {
  350. if (this.screensaver.fileNodes != null) this.screensaver.fileNodes.clearFilter();
  351. }
  352. public bool resetWallpaper() {
  353. Wallpaper wallpaper = new Wallpaper(this.screensaver);
  354. wallpaper.resetDefaultWallpaper();
  355. return true;
  356. }
  357. public bool jsSetGPURendering() {
  358. if (this.getPersistantBool("gpuRendering")) {
  359. Registry.SetValue("HKEY_CURRENT_USER\\" + Constants.regkeyGPURendering, Constants.regkeyExecutable, 1, RegistryValueKind.DWord);
  360. Registry.SetValue("HKEY_CURRENT_USER\\" + Constants.regkeyGPURendering, Constants.regkeyLauncher, 1, RegistryValueKind.DWord);
  361. } else {
  362. RegistryKey regKey = Registry.CurrentUser.OpenSubKey(Constants.regkeyGPURendering, true);
  363. if (regKey != null) {
  364. regKey.DeleteValue(Constants.regkeyExecutable, false);
  365. regKey.DeleteValue(Constants.regkeyLauncher, false);
  366. }
  367. }
  368. return false;
  369. }
  370. /****
  371. * Called from config.js
  372. * dumdum variable is used to avoid calling the function when testing with
  373. * if (typeof(window.external.getInitialFoldersJSON) !== "undefined") in JavaScript
  374. ****/
  375. public string getInitialFoldersJSON(bool dumdum) {
  376. List<jsonFolder> folders = new List<jsonFolder>();
  377. //MessageBox.Show("getInitialFoldersJSON()");
  378. // folders.Add(new jsonFolder());
  379. // folders.Add(new jsonFolder(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos)));
  380. /*
  381. jsonFolder network = new jsonFolder("Network");
  382. network.key = "\\";
  383. folders.Add(network);
  384. DirectoryEntry root = new DirectoryEntry("WinNT:");
  385. foreach (DirectoryEntry networkComputers in root.Children) {
  386. foreach (DirectoryEntry networkComputer in networkComputers.Children) {
  387. if (networkComputer.Name != "Schema") {
  388. jsonFolder networked = new jsonFolder(networkComputer.Name);
  389. networked.lazy = true;
  390. network.children.Add(networked);
  391. try {
  392. ManagementObjectSearcher searcher =
  393. new ManagementObjectSearcher("root\\CIMV2",
  394. "SELECT * FROM Win32_Share");
  395. foreach (ManagementObject queryObj in searcher.Get()) {
  396. Debug.WriteLine("-----------------------------------");
  397. Debug.WriteLine("Win32_Share instance");
  398. Debug.WriteLine("-----------------------------------");
  399. Debug.WriteLine("Name: {0}", queryObj["Name"]);
  400. }
  401. } catch (ManagementException e) {
  402. MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
  403. }
  404. //textBox1.Text += computer.Name + "\r\n";
  405. }
  406. }
  407. }
  408. */
  409. jsonFolder computer = new jsonFolder("Computer");
  410. computer.expanded = true;
  411. folders.Add(computer);
  412. DriveInfo[] info = DriveInfo.GetDrives();
  413. foreach (DriveInfo di in info) {
  414. string drive = "(" + di.Name.Replace("\\", "") + ")";
  415. jsonFolder f = new jsonFolder(drive);
  416. f.lazy = true;
  417. f.key = di.Name;
  418. string extraInfo = "";
  419. if (di.IsReady) {
  420. extraInfo += di.VolumeLabel + " ";
  421. } else {
  422. f.unselectable = true;
  423. f.extraClasses = "dim";
  424. }
  425. switch (di.DriveType) {
  426. case DriveType.Removable:
  427. if (extraInfo == "") extraInfo += "Removable Disk ";
  428. break;
  429. }
  430. if (extraInfo != "") f.title = extraInfo + f.title;
  431. computer.children.Add(f);
  432. }
  433. if (this.persistant == null || this.getPersistant("folders") == null) {
  434. this.loadPersistantConfig();
  435. }
  436. foreach (string folder in Convert.ToString(this.getPersistant("folders")).Split(new string[] { Environment.NewLine, "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries)) {
  437. if (folder.Substring(0, 2) == "\\\\") {
  438. string[] parts = folder.Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries);
  439. int i = 0;
  440. jsonFolder network = new jsonFolder("Network");
  441. folders.Add(network);
  442. jsonFolder node = network;
  443. while (i < parts.Length) {
  444. jsonFolder newNode = new jsonFolder(parts[i]);
  445. node.children.Add(newNode);
  446. i++;
  447. if (i == parts.Length) {
  448. newNode.selected = true;
  449. jsonFolder dummy = new jsonFolder("dummy");
  450. dummy.selected = false;
  451. //dummy.unselectable = false;
  452. dummy.extraClasses = "hidden";
  453. node.children.Add(dummy);
  454. }
  455. node = newNode;
  456. }
  457. } else {
  458. jsonFolder node = computer;
  459. string basePath = "";
  460. string[] parts = folder.Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries);
  461. int i = 0;
  462. while (i < parts.Length) {
  463. string key = parts[i].ToLower();
  464. if (key.IndexOf(':') > -1) key = key.ToUpper() + "\\";
  465. jsonFolder newNode = node.hasChild(key);
  466. if (newNode == null) {
  467. // Add children if not found
  468. node.children.AddRange(this.getFolder(basePath));
  469. node = node.hasChild(key);
  470. if (node == null) break; // Escape while loop if still not found
  471. } else {
  472. node = newNode;
  473. }
  474. //node.expanded = true;
  475. node.selected = true;
  476. basePath += parts[i] + "\\";
  477. i++;
  478. }
  479. if (node != null) node.selected = true;
  480. }
  481. }
  482. return JsonConvert.SerializeObject(folders);
  483. }
  484. public List<jsonFolder> getFolder(string folder) {
  485. List<jsonFolder> children = new List<jsonFolder>();
  486. if (!Directory.Exists(folder)) return children;
  487. string[] dirs = Directory.GetDirectories(folder);
  488. foreach (string dir in dirs) {
  489. try {
  490. FileInfo fi = new FileInfo(dir);
  491. if ((fi.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden) {
  492. jsonFolder d = new jsonFolder(fi.Name.ToLower());
  493. d.lazy = (Directory.GetDirectories(dir).Length > 0);
  494. children.Add(d);
  495. }
  496. } catch (Exception e) {
  497. Debug.WriteLine("getFolder " + e.Message);
  498. // No access
  499. }
  500. }
  501. return children;
  502. }
  503. public string getFolderJSON(string folder) {
  504. return JsonConvert.SerializeObject(this.getFolder(folder));
  505. }
  506. public string getEffectsJSON() {
  507. return JsonConvert.SerializeObject(this.effects);
  508. }
  509. public string getRandomEffect() {
  510. string json = null;
  511. if (this.getPersistantBool("useTransitions") && this.effects != null) {
  512. jsonFolder effect = jsonFolder.getRandomSelected(this.effects.children);
  513. jsonFolder direction = null;
  514. if (effect == null) {
  515. json = "{\"effect\":\"fade\", \"duration\":100}";
  516. } else {
  517. json += "{\"effect\":\"" + effect.key + "\"";
  518. if (effect.children.Count > 0) {
  519. direction = jsonFolder.getRandomSelected(effect.children);
  520. if (direction != null) json += ", \"direction\":\"" + direction.title.ToLower() + "\"";
  521. }
  522. json += ", \"duration\":1000}";
  523. }
  524. }
  525. return json;
  526. }
  527. public string InvokeScriptOnMonitor(int monitor, string script, string parameters) {
  528. string s = null;
  529. if (this.screensaver.monitors != null) for (int i = 0; i < this.screensaver.monitors.Length; i++) {
  530. if (monitor == Screensaver.CM_ALL || monitor == i) {
  531. s += Convert.ToString(this.screensaver.monitors[i].InvokeScript(script, parameters.Split(';')));
  532. }
  533. }
  534. return s;
  535. }
  536. private HtmlElement getElementById(string id) {
  537. // Make thread safe
  538. try {
  539. return (HtmlElement)this.browser.Invoke(new Func<HtmlElement>(() => this.browser.Document.GetElementById(id)));
  540. } catch (Exception e) {
  541. Debug.WriteLine("getElementById" + e.Message);
  542. return null;
  543. }
  544. }
  545. /***
  546. * This function assumes that <div id="#name#"> encapsulates
  547. * <input type="radio" name="#name# value=...> lines
  548. ***/
  549. private string getDomRadioValue(string id) {
  550. HtmlElement he = (HtmlElement)this.browser.Invoke(new Func<HtmlElement>(() => this.browser.Document.GetElementById(id)));
  551. if (he != null) {
  552. HtmlElementCollection hec = he.GetElementsByTagName("input");
  553. foreach (HtmlElement e in hec) {
  554. if (e.GetAttribute("type").ToLower() == "radio" && e.GetAttribute("checked").ToLower() == "true") {
  555. return e.GetAttribute("value");
  556. }
  557. }
  558. }
  559. return null;
  560. }
  561. private bool getDomCheckboxValue(string id) {
  562. HtmlElement he = this.getElementById(id);
  563. if (he == null) return false;
  564. switch (he.TagName.ToLower()) {
  565. case "input":
  566. return (bool)he.GetAttribute("checked").ToLower().Equals("true");
  567. break;
  568. default:
  569. Debug.WriteLine("getCheckboxValue called on non checkbox");
  570. break;
  571. }
  572. return false;
  573. }
  574. public bool persistantLoaded() {
  575. return this.persistant != null;
  576. }
  577. public bool hasPersistantKey(string key) {
  578. return this.persistant.ContainsKey(key);
  579. }
  580. public void setPersistant(string key, object value) {
  581. this.setPersistant(key, value, true);
  582. }
  583. public void setPersistant(string key, object value, bool updateDom) {
  584. if (key == null) {
  585. this.screensaver.showInfoOnMonitors("Invalid configuration key: null", true);
  586. } else {
  587. this.persistant[key] = value;
  588. if (updateDom) this.setDomValue(key, Convert.ToString(value));
  589. }
  590. }
  591. public object getPersistant(string key) {
  592. if (this.persistant == null || !this.persistant.ContainsKey(key)) throw new KeyNotFoundException(key);
  593. return persistant[key];
  594. }
  595. public bool getPersistantBool(string key) {
  596. if (!this.persistant.ContainsKey(key)) throw new KeyNotFoundException(key);
  597. if (this.persistant[key].GetType() == typeof(bool)) {
  598. return (bool)this.persistant[key];
  599. }
  600. switch (Convert.ToString(this.persistant[key])) {
  601. case "True": case "true": case "1":
  602. return true;
  603. break;
  604. case "False": case "false": case "0":
  605. return false;
  606. break;
  607. }
  608. throw new Exception("Can't cast keys '" + key + "' value " + this.persistant[key] + key + " to boolean");
  609. }
  610. public string getPersistantString(string key) {
  611. return Convert.ToString(this.getPersistant(key));
  612. }
  613. public bool syncMonitors() {
  614. if (this.persistant == null) return false;
  615. return this.getPersistantBool("syncScreens");
  616. }
  617. public Config.Order changeOrder() {
  618. if (this.getOrder() == Config.Order.Random) {
  619. //this.checkCheckbox("orderSequential");
  620. this.setPersistant("order", Config.Order.Sequential);
  621. return Config.Order.Sequential;
  622. } else {
  623. //this.checkCheckbox("orderRandom");
  624. this.setPersistant("order", Config.Order.Random);
  625. return Config.Order.Random;
  626. }
  627. // return null;
  628. }
  629. public Config.Order getOrder() {
  630. if (this.getPersistant("order").GetType() == typeof(string)) {
  631. switch (this.getPersistantString("order")) {
  632. case "random": case "1":
  633. return Config.Order.Random;
  634. break;
  635. default:
  636. return Config.Order.Sequential;
  637. break;
  638. }
  639. } else {
  640. if ((Config.Order)Enum.Parse(typeof(Config.Order), this.getPersistantString("order")) == Config.Order.Random) return Config.Order.Random;
  641. else return Config.Order.Sequential;
  642. }
  643. }
  644. public void setInnerHTML(string id, string html) {
  645. HtmlElement he = this.getElementById(id);
  646. if (he != null) {
  647. he.InnerHtml = html;
  648. }
  649. }
  650. public void setDomValue(string id, string value) {
  651. HtmlElement he = this.getElementById(id);
  652. if (he != null) {
  653. switch (he.TagName.ToLower()) {
  654. case "textarea":
  655. he.InnerHtml = Utils.HtmlDecode(value);
  656. break;
  657. default:
  658. switch (he.GetAttribute("type").ToLower()) {
  659. case "radio":
  660. //he.SetAttribute("value", value);
  661. if (value == "checked" || value == he.GetAttribute("value").ToLower()) {
  662. he.SetAttribute("checked", "true");
  663. } else {
  664. he.SetAttribute("checked", "");
  665. }
  666. break;
  667. case "checkbox":
  668. if (value == "false") {
  669. he.SetAttribute("checked", "");
  670. } else {
  671. he.SetAttribute("checked", "true");
  672. }
  673. break;
  674. default:
  675. he.SetAttribute("value", value);
  676. break;
  677. }
  678. break;
  679. }
  680. }
  681. }
  682. public string getDomValue(string id) {
  683. HtmlElement he = this.getElementById(id);
  684. if (he == null) return null;
  685. try {
  686. switch (he.TagName.ToLower()) {
  687. case "textarea":
  688. return Utils.HtmlDecode(he.InnerHtml);
  689. //return he.InnerHtml;
  690. break;
  691. default:
  692. return he.GetAttribute("value");
  693. break;
  694. }
  695. } catch (System.Runtime.InteropServices.COMException co) {
  696. //this.screensaver.showInfoOnMonitors("Error getPersistant(" + id + ")\n" + Convert.ToString(co.Message));
  697. return null;
  698. }
  699. return null;
  700. }
  701. public void Config_FormClosing(object sender, FormClosingEventArgs e) {
  702. if (screensaver.action == Screensaver.Actions.Config) {
  703. this.savePersistantConfig();
  704. Application.Exit();
  705. } else if (!this.screensaver.applicationClosing) {
  706. if (!this.syncMonitors()) {
  707. // restart timer in-case sync option has changed.
  708. for (int i = 1; i < this.screensaver.monitors.Length; i++) {
  709. this.screensaver.monitors[i].timer.Start();
  710. }
  711. }
  712. //Console.Beep();
  713. this.Hide();
  714. e.Cancel = true;
  715. }
  716. }
  717. public void ConfigDocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e) {
  718. if (this.screensaver.action == Screensaver.Actions.Wallpaper) {
  719. this.screensaver.initForScreensaverAndWallpaper();
  720. Wallpaper wallpaper = new Wallpaper(this.screensaver);
  721. wallpaper.generateWallpaper();
  722. Application.Exit();
  723. } else {
  724. this.screensaver.initializeMonitors();
  725. if (!this.configInitialised) {
  726. this.setInnerHTML("version", Constants.getNiceVersion());
  727. this.setInnerHTML("versionIE", "(IE:" + this.browser.Version.Major.ToString() + "." + this.browser.Version.Minor.ToString() + ")");
  728. this.browser.Document.InvokeScript("initFancyTreeFolder");
  729. this.browser.Document.InvokeScript("initFancyTreeTransitions");
  730. this.configInitialised = true;
  731. }
  732. }
  733. }
  734. private void setCurrentTrackChanges() {
  735. List<string> keys = new List<string>(this.trackChanges.Keys);
  736. for (int i = 0; i < keys.Count; i++) {
  737. this.trackChanges[keys[i]] = this.getPersistant(keys[i]);
  738. }
  739. }
  740. private bool checkTrackChangesChanged() {
  741. List<string> keys = new List<string>(this.trackChanges.Keys);
  742. for (int i = 0; i < keys.Count; i++) {
  743. if (this.trackChanges[keys[i]] != this.getPersistant(keys[i])) return true;
  744. }
  745. return false;
  746. }
  747. public bool? isUpdateNewer() {
  748. if (this.webUpdateCheck.Document != null) {
  749. HtmlElement he = this.webUpdateCheck.Document.GetElementById("download");
  750. if (he != null) {
  751. Version update = new Version(he.GetAttribute("data-version"));
  752. return (this.screensaver.version.CompareTo(update) < 0);
  753. }
  754. }
  755. return null;
  756. }
  757. public string updateFilename() {
  758. if (this.webUpdateCheck.Document != null) {
  759. HtmlElement he = this.webUpdateCheck.Document.GetElementById("download");
  760. if (he != null) {
  761. return Convert.ToString(Path.Combine(Constants.getUpdateFolder(), Path.GetFileName(he.GetAttribute("href"))));
  762. }
  763. }
  764. return null;
  765. }
  766. public string updateDownloadUrl() {
  767. if (this.webUpdateCheck.Document != null) {
  768. HtmlElement he = this.webUpdateCheck.Document.GetElementById("download");
  769. if (he != null) {
  770. return he.GetAttribute("href");
  771. }
  772. }
  773. return null;
  774. }
  775. public string updateFileMD5() {
  776. if (this.webUpdateCheck.Document != null) {
  777. HtmlElement he = this.webUpdateCheck.Document.GetElementById("download");
  778. if (he != null) {
  779. return Convert.ToString(he.GetAttribute("data-md5"));
  780. }
  781. }
  782. return null;
  783. }
  784. public void installUpdate() {
  785. if (this.webUpdateCheck.Document != null) {
  786. HtmlElement he = this.webUpdateCheck.Document.GetElementById("download");
  787. if (he != null) {
  788. try {
  789. Utils.RunTaskScheduler(@"Run" + AppSettings.Abbr + "Update", Convert.ToString(Path.Combine(Constants.getUpdateFolder(), Path.GetFileName(he.GetAttribute("href")))), null);
  790. this.screensaver.OnExit();
  791. this.showUpdateInfo("Running installer");
  792. } catch (System.ComponentModel.Win32Exception we) {
  793. this.screensaver.showInfoOnMonitors(AppSettings.Abbr + " update cancelled" + Environment.NewLine + we.Message, true, true);
  794. string clickOrKey = "Press 'U' key to update";
  795. if (this.getPersistant("mouseSensitivity") == "none" || this.screensaver.action == Screensaver.Actions.Config) clickOrKey = "Click to install now";
  796. this.screensaver.showUpdateInfo(AppSettings.Abbr + " " + he.GetAttribute("data-version") + " downloaded<br/><a class='exit external' target='_blank' href='file://" + Path.Combine(Constants.getUpdateFolder(), Path.GetFileName(he.GetAttribute("href"))) + "'>" + clickOrKey + "</a>.");
  797. this.screensaver.resetMouseMove();
  798. }
  799. return;
  800. }
  801. }
  802. this.showUpdateInfo("Nothing to install");
  803. }
  804. private void DownloadProgress(object sender, DownloadProgressChangedEventArgs e) {
  805. if (!this.downloadProgress.IsRunning) this.downloadProgress.Start();
  806. if (this.downloadProgress.ElapsedMilliseconds > 250) {
  807. if (this.screensaver.action == Screensaver.Actions.Config) {
  808. //this.downloadProgressIndicator(e.ProgressPercentage);
  809. } else {
  810. this.screensaver.monitors[0].downloadProgressIndicator(e.ProgressPercentage);
  811. }
  812. this.downloadProgress.Reset();
  813. this.downloadProgress.Start();
  814. }
  815. }
  816. void DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) {
  817. //WebBrowser wbCheckUpdate = sender as WebBrowser;
  818. HtmlElement he = this.webUpdateCheck.Document.GetElementById("download");
  819. string updatePath = Path.Combine(Constants.getUpdateFolder(), Path.GetFileName(he.GetAttribute("href")));
  820. if (!Utils.VerifyMD5(updatePath, he.GetAttribute("data-md5"))) {
  821. // <a href='" + he.GetAttribute("href") + "'>
  822. this.showUpdateInfo("Download " + he.GetAttribute("data-version") + " failed<br/>Please U key to start download manually.");
  823. return;
  824. }
  825. if (this.getPersistantString("checkUpdates") == "yes") this.installUpdate();
  826. else {
  827. string message = AppSettings.Abbr + " " + he.GetAttribute("data-version") + " downloaded<br/><a class='exit external' target='_blank' href='file://" + updatePath + "'>";
  828. if (this.getPersistant("mouseSensitivity") == "none" || this.screensaver.action == Screensaver.Actions.Config) {
  829. message += "Click to install now</a>";
  830. } else {
  831. message += "Press 'U' key to update</a><div class='small'>(Ctrl + U to ignores this update)</div>";
  832. }
  833. this.screensaver.showUpdateInfo(message);
  834. }
  835. }
  836. public void showUpdateInfo(string info) {
  837. HtmlElement he = this.browser.Document.GetElementById("update");
  838. he.InnerHtml = info.Replace("<br/>", " ");
  839. if (this.screensaver.action != Screensaver.Actions.Config) {
  840. this.screensaver.showUpdateInfo(info);
  841. }
  842. }
  843. private Uri getUpdateUri() {
  844. string param = "?v=" + Constants.getNiceVersion();
  845. if (this.screensaver.config.getPersistantBool("disableGoAn")) param = "?track=no";
  846. return new Uri(AppSettings.UpdateCheckURL + param);
  847. }
  848. public string getUpdateVersion() {
  849. if (this.webUpdateCheck.Url.Equals(this.getUpdateUri())) {
  850. HtmlElement he = this.webUpdateCheck.Document.GetElementById("download");
  851. return he.GetAttribute("data-version");
  852. }
  853. return null;
  854. }
  855. private void webUpdateCheck_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
  856. if (this.webUpdateCheck.Url.Equals(this.getUpdateUri())) {
  857. HtmlElement he = this.webUpdateCheck.Document.GetElementById("download");
  858. if (he != null) {
  859. Version ignore = null;
  860. Version compareTo = this.screensaver.version;
  861. //he.Get
  862. Version update;
  863. try {
  864. update = new Version(he.GetAttribute("data-version"));
  865. } catch (Exception ex) {
  866. this.screensaver.showInfoOnMonitors("Error detecting latest version" + Environment.NewLine + ex.Message, true, true);
  867. return;
  868. }
  869. if (this.getPersistantBool("ignoreUpdate")) {
  870. try {
  871. ignore = new Version(this.getPersistantString("ignoreVersion"));
  872. } catch (Exception) { }
  873. if (ignore != null && compareTo.CompareTo(ignore) < 0) {
  874. compareTo = ignore;
  875. }
  876. }
  877. if (!this.getPersistantBool("betaVersion")) {
  878. // Revision number = 0 for alpha release,
  879. // Revision number != 0 indicates beta / release candidate version
  880. update = new Version(update.Major, update.Minor, update.Build);
  881. }
  882. this.newVersionAvailable = (compareTo.CompareTo(update) < 0);
  883. if (this.newVersionAvailable) {
  884. if (this.downloadUpdates) {
  885. string downloadedUpdateLocalPath = Path.Combine(Constants.getUpdateFolder(), Path.GetFileName(he.GetAttribute("href")));
  886. if (!File.Exists(downloadedUpdateLocalPath) || !Utils.VerifyMD5(downloadedUpdateLocalPath, he.GetAttribute("data-md5"))) {
  887. if (File.Exists(downloadedUpdateLocalPath)) File.Delete(downloadedUpdateLocalPath);
  888. this.showUpdateInfo("<div class='downloadProgress'><div class='downloadLabel'>Downloading update: " + update.ToString() + "</div><div class='downloadProgress' style='width: 0%'></div>");
  889. Directory.CreateDirectory(Path.GetDirectoryName(downloadedUpdateLocalPath));//.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), Constants.DownloadFolder));
  890. WebClient client = new WebClient();
  891. client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFileCompleted);
  892. client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgress);
  893. client.DownloadFileAsync(new Uri(he.GetAttribute("href")), downloadedUpdateLocalPath);
  894. return;
  895. } else {
  896. this.DownloadFileCompleted(this, null);
  897. }
  898. } else {
  899. this.showUpdateInfo("Update available<br/><a href='" + he.GetAttribute("href") + "'>Download " + AppSettings.Abbr + " " + he.GetAttribute("data -version-text") + "</a>");
  900. }
  901. } else if (this.screensaver.showUpdateStatus) {
  902. this.screensaver.showAllUpToDate();
  903. }
  904. }
  905. }
  906. }
  907. public void timerCheckUpdates_Tick(object sender, EventArgs e) {
  908. this.timerCheckUpdates.Enabled = false;
  909. if (this.screensaver.action != Screensaver.Actions.Preview) {
  910. string update;
  911. try {
  912. update = this.getPersistantString("checkUpdates");
  913. } catch (KeyNotFoundException knfe) {
  914. // Try again in a bit
  915. this.timerCheckUpdates.Interval *= 2;
  916. this.timerCheckUpdates.Enabled = true;
  917. return;
  918. }
  919. switch (update) {
  920. case "yes":
  921. case "download":
  922. this.checkUpdates = true;
  923. this.downloadUpdates = true;
  924. break;
  925. case "notify":
  926. this.checkUpdates = true;
  927. break;
  928. }
  929. if (this.checkUpdates) {
  930. //bgwCheckUpdate.DoWork();
  931. //bgwCheckUpdate.RunWorkerAsync();
  932. this.webUpdateCheck.Url = this.getUpdateUri();
  933. }
  934. }
  935. }
  936. private void Config_VisibleChanged(object sender, EventArgs e) {
  937. if (this.Visible && this.screensaver.action != Screensaver.Actions.Config) {
  938. this.setCurrentTrackChanges();
  939. } else if (this.screensaver.action != Screensaver.Actions.Config) {
  940. // Hiding
  941. if (this.checkTrackChangesChanged()) {
  942. if (this.trackChanges["ignoreHiddenFiles"] != this.getPersistant("ignoreHiddenFiles") || this.trackChanges["ignoreHiddenFolders"] != this.getPersistant("ignoreHiddenFolders")) {
  943. this.screensaver.showInfoOnMonitors("Emptying Media Database", true, false);
  944. this.screensaver.fileNodes.purgeMediaDatabase();
  945. this.screensaver.showInfoOnMonitors("Media Database Emptied", true, true);
  946. } else {
  947. this.screensaver.showInfoOnMonitors("", true, false);
  948. }
  949. this.screensaver.fileNodes.restartBackgroundWorkerImageFolder();
  950. }
  951. }
  952. if (this.Visible) {
  953. Cursor.Show();
  954. } else {
  955. Cursor.Hide();
  956. }
  957. }
  958. /*
  959. private void Config_Resize(object sender, EventArgs e) {

Large files files are truncated, but you can click here to view the full file