PageRenderTime 52ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/RELEASE/Projects/WP8 (not working)/OTMA/OTMA/cordovalib/CordovaView.xaml.cs

https://github.com/theliberator/OTMA
C# | 515 lines | 329 code | 85 blank | 101 comment | 37 complexity | cc77285c1a9b357845e93d58b6d45559 MD5 | raw file
Possible License(s): Apache-2.0
  1. /*
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. using System;
  13. using System.Collections.Generic;
  14. using System.Linq;
  15. using System.Net;
  16. using System.Windows;
  17. using System.Windows.Controls;
  18. using System.Windows.Documents;
  19. using System.Windows.Input;
  20. using System.Windows.Media;
  21. using System.Windows.Media.Animation;
  22. using System.Windows.Shapes;
  23. using Microsoft.Phone.Controls;
  24. using System.IO.IsolatedStorage;
  25. using System.Windows.Resources;
  26. using System.Windows.Interop;
  27. using System.Runtime.Serialization.Json;
  28. using System.IO;
  29. using System.ComponentModel;
  30. using System.Xml.Linq;
  31. using WPCordovaClassLib.Cordova.Commands;
  32. using System.Diagnostics;
  33. using System.Text;
  34. using WPCordovaClassLib.Cordova;
  35. using System.Threading;
  36. using Microsoft.Phone.Shell;
  37. using WPCordovaClassLib.Cordova.JSON;
  38. using WPCordovaClassLib.CordovaLib;
  39. namespace WPCordovaClassLib
  40. {
  41. public partial class CordovaView : UserControl
  42. {
  43. /// <summary>
  44. /// Indicates whether web control has been loaded and no additional initialization is needed.
  45. /// Prevents data clearing during page transitions.
  46. /// </summary>
  47. private bool IsBrowserInitialized = false;
  48. /// <summary>
  49. /// Set when the user attaches a back button handler inside the WebBrowser
  50. /// </summary>
  51. private bool OverrideBackButton = false;
  52. /// <summary>
  53. /// Sentinal to keep track of page changes as a result of the hardware back button
  54. /// Set to false when the back-button is pressed, which calls js window.history.back()
  55. /// If the page changes as a result of the back button the event is cancelled.
  56. /// </summary>
  57. private bool PageDidChange = false;
  58. private static string AppRoot = "";
  59. /// <summary>
  60. /// Handles native api calls
  61. /// </summary>
  62. private NativeExecution nativeExecution;
  63. protected BrowserMouseHelper bmHelper;
  64. protected DOMStorageHelper domStorageHelper;
  65. protected OrientationHelper orientationHelper;
  66. private ConfigHandler configHandler;
  67. public System.Windows.Controls.Grid _LayoutRoot
  68. {
  69. get
  70. {
  71. return ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot")));
  72. }
  73. }
  74. public WebBrowser Browser
  75. {
  76. get
  77. {
  78. return CordovaBrowser;
  79. }
  80. }
  81. /*
  82. * Setting StartPageUri only has an effect if called before the view is loaded.
  83. **/
  84. protected Uri _startPageUri = null;
  85. public Uri StartPageUri
  86. {
  87. get
  88. {
  89. if (_startPageUri == null)
  90. {
  91. // default
  92. return new Uri(AppRoot + "www/index.html", UriKind.Relative);
  93. }
  94. else
  95. {
  96. return _startPageUri;
  97. }
  98. }
  99. set
  100. {
  101. if (!this.IsBrowserInitialized)
  102. {
  103. _startPageUri = value;
  104. }
  105. }
  106. }
  107. /// <summary>
  108. /// Gets or sets whether to suppress bouncy scrolling of
  109. /// the WebBrowser control;
  110. /// </summary>
  111. public bool DisableBouncyScrolling
  112. {
  113. get;
  114. set;
  115. }
  116. public CordovaView()
  117. {
  118. InitializeComponent();
  119. if (DesignerProperties.IsInDesignTool)
  120. {
  121. return;
  122. }
  123. StartupMode mode = PhoneApplicationService.Current.StartupMode;
  124. if (mode == StartupMode.Launch)
  125. {
  126. PhoneApplicationService service = PhoneApplicationService.Current;
  127. service.Activated += new EventHandler<Microsoft.Phone.Shell.ActivatedEventArgs>(AppActivated);
  128. service.Launching += new EventHandler<LaunchingEventArgs>(AppLaunching);
  129. service.Deactivated += new EventHandler<DeactivatedEventArgs>(AppDeactivated);
  130. service.Closing += new EventHandler<ClosingEventArgs>(AppClosing);
  131. }
  132. else
  133. {
  134. }
  135. // initializes native execution logic
  136. configHandler = new ConfigHandler();
  137. configHandler.LoadAppPackageConfig();
  138. if (configHandler.ContentSrc != null)
  139. {
  140. if (Uri.IsWellFormedUriString(configHandler.ContentSrc, UriKind.Absolute))
  141. {
  142. this.StartPageUri = new Uri(configHandler.ContentSrc, UriKind.Absolute);
  143. }
  144. else
  145. {
  146. this.StartPageUri = new Uri(AppRoot + "www/" + configHandler.ContentSrc, UriKind.Relative);
  147. }
  148. }
  149. nativeExecution = new NativeExecution(ref this.CordovaBrowser);
  150. bmHelper = new BrowserMouseHelper(ref this.CordovaBrowser);
  151. }
  152. void AppClosing(object sender, ClosingEventArgs e)
  153. {
  154. Debug.WriteLine("AppClosing");
  155. }
  156. void AppDeactivated(object sender, DeactivatedEventArgs e)
  157. {
  158. Debug.WriteLine("INFO: AppDeactivated");
  159. try
  160. {
  161. CordovaBrowser.InvokeScript("eval", new string[] { "cordova.fireDocumentEvent('pause');" });
  162. }
  163. catch (Exception)
  164. {
  165. Debug.WriteLine("ERROR: Pause event error");
  166. }
  167. }
  168. void AppLaunching(object sender, LaunchingEventArgs e)
  169. {
  170. Debug.WriteLine("INFO: AppLaunching");
  171. }
  172. void AppActivated(object sender, Microsoft.Phone.Shell.ActivatedEventArgs e)
  173. {
  174. Debug.WriteLine("INFO: AppActivated");
  175. try
  176. {
  177. CordovaBrowser.InvokeScript("eval", new string[] { "cordova.fireDocumentEvent('resume');" });
  178. }
  179. catch (Exception)
  180. {
  181. Debug.WriteLine("ERROR: Resume event error");
  182. }
  183. }
  184. void CordovaBrowser_Loaded(object sender, RoutedEventArgs e)
  185. {
  186. this.bmHelper.ScrollDisabled = this.DisableBouncyScrolling;
  187. if (DesignerProperties.IsInDesignTool)
  188. {
  189. return;
  190. }
  191. // prevents refreshing web control to initial state during pages transitions
  192. if (this.IsBrowserInitialized) return;
  193. this.domStorageHelper = new DOMStorageHelper(this.CordovaBrowser);
  194. try
  195. {
  196. // Before we possibly clean the ISO-Store, we need to grab our generated UUID, so we can rewrite it after.
  197. string deviceUUID = "";
  198. using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication())
  199. {
  200. try
  201. {
  202. IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream("DeviceID.txt", FileMode.Open, FileAccess.Read, appStorage);
  203. using (StreamReader reader = new StreamReader(fileStream))
  204. {
  205. deviceUUID = reader.ReadLine();
  206. }
  207. }
  208. catch (Exception /*ex*/)
  209. {
  210. deviceUUID = Guid.NewGuid().ToString();
  211. }
  212. Debug.WriteLine("Updating IsolatedStorage for APP:DeviceID :: " + deviceUUID);
  213. IsolatedStorageFileStream file = new IsolatedStorageFileStream("DeviceID.txt", FileMode.Create, FileAccess.Write, appStorage);
  214. using (StreamWriter writeFile = new StreamWriter(file))
  215. {
  216. writeFile.WriteLine(deviceUUID);
  217. writeFile.Close();
  218. }
  219. }
  220. /*
  221. * 11/08/12 Ruslan Kokorev
  222. * Copying files to isolated storage is no more required in WP8. WebBrowser control now works with files located in XAP.
  223. */
  224. //StreamResourceInfo streamInfo = Application.GetResourceStream(new Uri("CordovaSourceDictionary.xml", UriKind.Relative));
  225. //if (streamInfo != null)
  226. //{
  227. // StreamReader sr = new StreamReader(streamInfo.Stream);
  228. // //This will Read Keys Collection for the xml file
  229. // XDocument document = XDocument.Parse(sr.ReadToEnd());
  230. // var files = from results in document.Descendants("FilePath")
  231. // select new
  232. // {
  233. // path = (string)results.Attribute("Value")
  234. // };
  235. // StreamResourceInfo fileResourceStreamInfo;
  236. // using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication())
  237. // {
  238. // foreach (var file in files)
  239. // {
  240. // fileResourceStreamInfo = Application.GetResourceStream(new Uri(file.path, UriKind.Relative));
  241. // if (fileResourceStreamInfo != null)
  242. // {
  243. // using (BinaryReader br = new BinaryReader(fileResourceStreamInfo.Stream))
  244. // {
  245. // byte[] data = br.ReadBytes((int)fileResourceStreamInfo.Stream.Length);
  246. // string strBaseDir = AppRoot + file.path.Substring(0, file.path.LastIndexOf(System.IO.Path.DirectorySeparatorChar));
  247. // if (!appStorage.DirectoryExists(strBaseDir))
  248. // {
  249. // Debug.WriteLine("INFO: Creating Directory :: " + strBaseDir);
  250. // appStorage.CreateDirectory(strBaseDir);
  251. // }
  252. // // This will truncate/overwrite an existing file, or
  253. // using (IsolatedStorageFileStream outFile = appStorage.OpenFile(AppRoot + file.path, FileMode.Create))
  254. // {
  255. // Debug.WriteLine("INFO: Writing data for " + AppRoot + file.path + " and length = " + data.Length);
  256. // using (var writer = new BinaryWriter(outFile))
  257. // {
  258. // writer.Write(data);
  259. // }
  260. // }
  261. // }
  262. // }
  263. // else
  264. // {
  265. // Debug.WriteLine("ERROR: Failed to write file :: " + file.path + " did you forget to add it to the project?");
  266. // }
  267. // }
  268. // }
  269. //}
  270. CordovaBrowser.Navigate(StartPageUri);
  271. IsBrowserInitialized = true;
  272. AttachHardwareButtonHandlers();
  273. }
  274. catch (Exception ex)
  275. {
  276. Debug.WriteLine("ERROR: Exception in CordovaBrowser_Loaded :: {0}", ex.Message);
  277. }
  278. }
  279. void AttachHardwareButtonHandlers()
  280. {
  281. PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
  282. if (frame != null)
  283. {
  284. PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
  285. if (page != null)
  286. {
  287. page.BackKeyPress += new EventHandler<CancelEventArgs>(page_BackKeyPress);
  288. this.orientationHelper = new OrientationHelper(this.CordovaBrowser, page);
  289. }
  290. }
  291. }
  292. void page_BackKeyPress(object sender, CancelEventArgs e)
  293. {
  294. if (OverrideBackButton)
  295. {
  296. try
  297. {
  298. CordovaBrowser.InvokeScript("eval", new string[] { "cordova.fireDocumentEvent('backbutton');" });
  299. e.Cancel = true;
  300. }
  301. catch (Exception ex)
  302. {
  303. Console.WriteLine("Exception while invoking backbutton into cordova view: " + ex.Message);
  304. }
  305. }
  306. else
  307. {
  308. try
  309. {
  310. PageDidChange = false;
  311. Uri uriBefore = this.Browser.Source;
  312. // calling js history.back with result in a page change if history was valid.
  313. CordovaBrowser.InvokeScript("eval", new string[] { "(function(){window.history.back();})()" });
  314. Uri uriAfter = this.Browser.Source;
  315. e.Cancel = PageDidChange || (uriBefore != uriAfter);
  316. }
  317. catch (Exception)
  318. {
  319. e.Cancel = false; // exit the app ... ?
  320. }
  321. }
  322. }
  323. void CordovaBrowser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
  324. {
  325. string[] autoloadPlugs = this.configHandler.AutoloadPlugins;
  326. foreach (string plugName in autoloadPlugs)
  327. {
  328. //nativeExecution.ProcessCommand(commandCallParams);
  329. }
  330. string nativeReady = "(function(){ cordova.require('cordova/channel').onNativeReady.fire()})();";
  331. try
  332. {
  333. CordovaBrowser.InvokeScript("execScript", new string[] { nativeReady });
  334. }
  335. catch (Exception /*ex*/)
  336. {
  337. Debug.WriteLine("Error calling js to fire nativeReady event. Did you include cordova.js in your html script tag?");
  338. }
  339. if (this.CordovaBrowser.Opacity < 1)
  340. {
  341. FadeIn.Begin();
  342. }
  343. }
  344. void CordovaBrowser_Navigating(object sender, NavigatingEventArgs e)
  345. {
  346. if (!configHandler.URLIsAllowed(e.Uri.ToString()))
  347. {
  348. Debug.WriteLine("Whitelist exception: Stopping browser from navigating to :: " + e.Uri.ToString());
  349. e.Cancel = true;
  350. return;
  351. }
  352. this.PageDidChange = true;
  353. this.nativeExecution.ResetAllCommands();
  354. }
  355. /*
  356. * This method does the work of routing commands
  357. * NotifyEventArgs.Value contains a string passed from JS
  358. * If the command already exists in our map, we will just attempt to call the method(action) specified, and pass the args along
  359. * Otherwise, we create a new instance of the command, add it to the map, and call it ...
  360. * This method may also receive JS error messages caught by window.onerror, in any case where the commandStr does not appear to be a valid command
  361. * it is simply output to the debugger output, and the method returns.
  362. *
  363. **/
  364. void CordovaBrowser_ScriptNotify(object sender, NotifyEventArgs e)
  365. {
  366. string commandStr = e.Value;
  367. if (commandStr.IndexOf("DOMStorage") == 0)
  368. {
  369. this.domStorageHelper.HandleStorageCommand(commandStr);
  370. return;
  371. }
  372. else if (commandStr.IndexOf("Orientation") == 0)
  373. {
  374. this.orientationHelper.HandleCommand(commandStr);
  375. return;
  376. }
  377. CordovaCommandCall commandCallParams = CordovaCommandCall.Parse(commandStr);
  378. if (commandCallParams == null)
  379. {
  380. // ERROR
  381. Debug.WriteLine("ScriptNotify :: " + commandStr);
  382. }
  383. else if (commandCallParams.Service == "CoreEvents")
  384. {
  385. switch (commandCallParams.Action.ToLower())
  386. {
  387. case "overridebackbutton":
  388. string arg0 = JsonHelper.Deserialize<string[]>(commandCallParams.Args)[0];
  389. this.OverrideBackButton = (arg0 != null && arg0.Length > 0 && arg0.ToLower() == "true");
  390. break;
  391. }
  392. }
  393. else
  394. {
  395. if (configHandler.IsPluginAllowed(commandCallParams.Service))
  396. {
  397. nativeExecution.ProcessCommand(commandCallParams);
  398. }
  399. else
  400. {
  401. Debug.WriteLine("Error::Plugin not allowed in config.xml. " + commandCallParams.Service);
  402. }
  403. }
  404. }
  405. public void LoadPage(string url)
  406. {
  407. if (this.configHandler.URLIsAllowed(url))
  408. {
  409. this.CordovaBrowser.Navigate(new Uri(url, UriKind.RelativeOrAbsolute));
  410. }
  411. else
  412. {
  413. Debug.WriteLine("Oops, Can't load url based on config.xml :: " + url);
  414. }
  415. }
  416. private void CordovaBrowser_Unloaded(object sender, RoutedEventArgs e)
  417. {
  418. }
  419. private void CordovaBrowser_NavigationFailed(object sender, System.Windows.Navigation.NavigationFailedEventArgs e)
  420. {
  421. Debug.WriteLine("CordovaBrowser_NavigationFailed :: " + e.Uri.ToString());
  422. }
  423. private void CordovaBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
  424. {
  425. Debug.WriteLine("CordovaBrowser_Navigated :: " + e.Uri.ToString());
  426. }
  427. }
  428. }