PageRenderTime 48ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/windows-phone/wp7/template/cordovalib/CordovaView.xaml.cs

https://github.com/bramhe/phonegap
C# | 517 lines | 375 code | 84 blank | 58 comment | 37 complexity | b5ba6d7acd75fb0f398dc3a93bbb3848 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. /// Sentinel 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 = "/app/";
  59. /// <summary>
  60. /// Handles native api calls
  61. /// </summary>
  62. private NativeExecution nativeExecution;
  63. protected BrowserMouseHelper bmHelper;
  64. private ConfigHandler configHandler;
  65. private Dictionary<string, IBrowserDecorator> browserDecorators;
  66. public System.Windows.Controls.Grid _LayoutRoot
  67. {
  68. get
  69. {
  70. return ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot")));
  71. }
  72. }
  73. public WebBrowser Browser
  74. {
  75. get
  76. {
  77. return CordovaBrowser;
  78. }
  79. }
  80. /*
  81. * Setting StartPageUri only has an effect if called before the view is loaded.
  82. **/
  83. protected Uri _startPageUri = null;
  84. public Uri StartPageUri
  85. {
  86. get
  87. {
  88. if (_startPageUri == null)
  89. {
  90. // default
  91. return new Uri(AppRoot + "www/index.html", UriKind.Relative);
  92. }
  93. else
  94. {
  95. return _startPageUri;
  96. }
  97. }
  98. set
  99. {
  100. if (!this.IsBrowserInitialized)
  101. {
  102. _startPageUri = value;
  103. }
  104. }
  105. }
  106. public CordovaView()
  107. {
  108. InitializeComponent();
  109. if (DesignerProperties.IsInDesignTool)
  110. {
  111. return;
  112. }
  113. StartupMode mode = PhoneApplicationService.Current.StartupMode;
  114. if (mode == StartupMode.Launch)
  115. {
  116. PhoneApplicationService service = PhoneApplicationService.Current;
  117. service.Activated += new EventHandler<Microsoft.Phone.Shell.ActivatedEventArgs>(AppActivated);
  118. service.Launching += new EventHandler<LaunchingEventArgs>(AppLaunching);
  119. service.Deactivated += new EventHandler<DeactivatedEventArgs>(AppDeactivated);
  120. service.Closing += new EventHandler<ClosingEventArgs>(AppClosing);
  121. }
  122. else
  123. {
  124. }
  125. configHandler = new ConfigHandler();
  126. configHandler.LoadAppPackageConfig();
  127. if (configHandler.ContentSrc != null)
  128. {
  129. if (Uri.IsWellFormedUriString(configHandler.ContentSrc, UriKind.Absolute))
  130. {
  131. this.StartPageUri = new Uri(configHandler.ContentSrc, UriKind.Absolute);
  132. }
  133. else
  134. {
  135. this.StartPageUri = new Uri(AppRoot + "www/" + configHandler.ContentSrc, UriKind.Relative);
  136. }
  137. }
  138. browserDecorators = new Dictionary<string, IBrowserDecorator>();
  139. // initializes native execution logic
  140. nativeExecution = new NativeExecution(ref this.CordovaBrowser);
  141. bmHelper = new BrowserMouseHelper(ref this.CordovaBrowser);
  142. CreateDecorators();
  143. }
  144. /*
  145. * browserDecorators are a collection of plugin-like classes (IBrowserDecorator) that add some bit of functionality to the browser.
  146. * These are somewhat different than plugins in that they are usually not async and patch a browser feature that we would
  147. * already expect to have. Essentially these are browser polyfills that are patched from the outside in.
  148. * */
  149. void CreateDecorators()
  150. {
  151. XHRHelper xhrProxy = new XHRHelper();
  152. xhrProxy.Browser = CordovaBrowser;
  153. browserDecorators.Add("XHRLOCAL", xhrProxy);
  154. OrientationHelper orientHelper = new OrientationHelper();
  155. orientHelper.Browser = CordovaBrowser;
  156. browserDecorators.Add("Orientation", orientHelper);
  157. DOMStorageHelper storageHelper = new DOMStorageHelper();
  158. storageHelper.Browser = CordovaBrowser;
  159. browserDecorators.Add("DOMStorage", storageHelper);
  160. ConsoleHelper console = new ConsoleHelper();
  161. console.Browser = CordovaBrowser;
  162. browserDecorators.Add("ConsoleLog", console);
  163. }
  164. void AppClosing(object sender, ClosingEventArgs e)
  165. {
  166. //Debug.WriteLine("AppClosing");
  167. }
  168. void AppDeactivated(object sender, DeactivatedEventArgs e)
  169. {
  170. Debug.WriteLine("INFO: AppDeactivated");
  171. try
  172. {
  173. CordovaBrowser.InvokeScript("eval", new string[] { "cordova.fireDocumentEvent('pause');" });
  174. }
  175. catch (Exception)
  176. {
  177. Debug.WriteLine("ERROR: Pause event error");
  178. }
  179. }
  180. void AppLaunching(object sender, LaunchingEventArgs e)
  181. {
  182. //Debug.WriteLine("INFO: AppLaunching");
  183. }
  184. void AppActivated(object sender, Microsoft.Phone.Shell.ActivatedEventArgs e)
  185. {
  186. Debug.WriteLine("INFO: AppActivated");
  187. try
  188. {
  189. CordovaBrowser.InvokeScript("eval", new string[] { "cordova.fireDocumentEvent('resume');" });
  190. }
  191. catch (Exception)
  192. {
  193. Debug.WriteLine("ERROR: Resume event error");
  194. }
  195. }
  196. void GapBrowser_Loaded(object sender, RoutedEventArgs e)
  197. {
  198. if (DesignerProperties.IsInDesignTool)
  199. {
  200. return;
  201. }
  202. // prevents refreshing web control to initial state during pages transitions
  203. if (this.IsBrowserInitialized) return;
  204. try
  205. {
  206. // Before we possibly clean the ISO-Store, we need to grab our generated UUID, so we can rewrite it after.
  207. string deviceUUID = "";
  208. using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication())
  209. {
  210. try
  211. {
  212. IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream("DeviceID.txt", FileMode.Open, FileAccess.Read, appStorage);
  213. using (StreamReader reader = new StreamReader(fileStream))
  214. {
  215. deviceUUID = reader.ReadLine();
  216. }
  217. }
  218. catch (Exception /*ex*/)
  219. {
  220. deviceUUID = Guid.NewGuid().ToString();
  221. Debug.WriteLine("Updating IsolatedStorage for APP:DeviceID :: " + deviceUUID);
  222. IsolatedStorageFileStream file = new IsolatedStorageFileStream("DeviceID.txt", FileMode.Create, FileAccess.Write, appStorage);
  223. using (StreamWriter writeFile = new StreamWriter(file))
  224. {
  225. writeFile.WriteLine(deviceUUID);
  226. writeFile.Close();
  227. }
  228. }
  229. }
  230. StreamResourceInfo streamInfo = Application.GetResourceStream(new Uri("CordovaSourceDictionary.xml", UriKind.Relative));
  231. if (streamInfo != null)
  232. {
  233. StreamReader sr = new StreamReader(streamInfo.Stream);
  234. //This will Read Keys Collection for the xml file
  235. XDocument document = XDocument.Parse(sr.ReadToEnd());
  236. var files = from results in document.Descendants("FilePath")
  237. select new
  238. {
  239. path = (string)results.Attribute("Value")
  240. };
  241. StreamResourceInfo fileResourceStreamInfo;
  242. using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication())
  243. {
  244. foreach (var file in files)
  245. {
  246. fileResourceStreamInfo = Application.GetResourceStream(new Uri(file.path, UriKind.Relative));
  247. if (fileResourceStreamInfo != null)
  248. {
  249. using (BinaryReader br = new BinaryReader(fileResourceStreamInfo.Stream))
  250. {
  251. byte[] data = br.ReadBytes((int)fileResourceStreamInfo.Stream.Length);
  252. string strBaseDir = AppRoot + file.path.Substring(0, file.path.LastIndexOf(System.IO.Path.DirectorySeparatorChar));
  253. if (!appStorage.DirectoryExists(strBaseDir))
  254. {
  255. Debug.WriteLine("INFO: Creating Directory :: " + strBaseDir);
  256. appStorage.CreateDirectory(strBaseDir);
  257. }
  258. // This will truncate/overwrite an existing file, or
  259. using (IsolatedStorageFileStream outFile = appStorage.OpenFile(AppRoot + file.path, FileMode.Create))
  260. {
  261. Debug.WriteLine("INFO: Writing data for " + AppRoot + file.path + " and length = " + data.Length);
  262. using (var writer = new BinaryWriter(outFile))
  263. {
  264. writer.Write(data);
  265. }
  266. }
  267. }
  268. }
  269. else
  270. {
  271. Debug.WriteLine("ERROR: Failed to write file :: " + file.path + " did you forget to add it to the project?");
  272. }
  273. }
  274. }
  275. }
  276. CordovaBrowser.Navigate(StartPageUri);
  277. IsBrowserInitialized = true;
  278. AttachHardwareButtonHandlers();
  279. }
  280. catch (Exception ex)
  281. {
  282. Debug.WriteLine("ERROR: Exception in GapBrowser_Loaded :: {0}", ex.Message);
  283. }
  284. }
  285. void AttachHardwareButtonHandlers()
  286. {
  287. PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
  288. if (frame != null)
  289. {
  290. PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
  291. if (page != null)
  292. {
  293. page.BackKeyPress += new EventHandler<CancelEventArgs>(page_BackKeyPress);
  294. }
  295. }
  296. }
  297. void page_BackKeyPress(object sender, CancelEventArgs e)
  298. {
  299. if (OverrideBackButton)
  300. {
  301. try
  302. {
  303. CordovaBrowser.InvokeScript("eval", new string[] { "cordova.fireDocumentEvent('backbutton', {}, true);" });
  304. e.Cancel = true;
  305. }
  306. catch (Exception ex)
  307. {
  308. Console.WriteLine("Exception while invoking backbutton into cordova view: " + ex.Message);
  309. }
  310. }
  311. else
  312. {
  313. try
  314. {
  315. PageDidChange = false;
  316. Uri uriBefore = this.Browser.Source;
  317. // calling js history.back with result in a page change if history was valid.
  318. CordovaBrowser.InvokeScript("eval", new string[] { "(function(){window.history.back();})()" });
  319. Uri uriAfter = this.Browser.Source;
  320. e.Cancel = PageDidChange || (uriBefore != uriAfter);
  321. }
  322. catch (Exception)
  323. {
  324. e.Cancel = false; // exit the app ... ?
  325. }
  326. }
  327. }
  328. void GapBrowser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
  329. {
  330. string nativeReady = "(function(){ window.setTimeout(function(){cordova.require('cordova/channel').onNativeReady.fire()},0) })();";
  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. this.CordovaBrowser.Opacity = 1;
  342. RotateIn.Begin();
  343. }
  344. }
  345. void GapBrowser_Navigating(object sender, NavigatingEventArgs e)
  346. {
  347. if (!configHandler.URLIsAllowed(e.Uri.ToString()))
  348. {
  349. e.Cancel = true;
  350. return;
  351. }
  352. this.PageDidChange = true;
  353. // Debug.WriteLine("GapBrowser_Navigating to :: " + e.Uri.ToString());
  354. this.nativeExecution.ResetAllCommands();
  355. // TODO: check whitelist / blacklist
  356. // NOTE: Navigation can be cancelled by setting : e.Cancel = true;
  357. }
  358. /*
  359. * This method does the work of routing commands
  360. * NotifyEventArgs.Value contains a string passed from JS
  361. * If the command already exists in our map, we will just attempt to call the method(action) specified, and pass the args along
  362. * Otherwise, we create a new instance of the command, add it to the map, and call it ...
  363. * 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
  364. * it is simply output to the debugger output, and the method returns.
  365. *
  366. **/
  367. void GapBrowser_ScriptNotify(object sender, NotifyEventArgs e)
  368. {
  369. string commandStr = e.Value;
  370. string commandName = commandStr.Split('/').FirstOrDefault();
  371. if (browserDecorators.ContainsKey(commandName))
  372. {
  373. browserDecorators[commandName].HandleCommand(commandStr);
  374. return;
  375. }
  376. CordovaCommandCall commandCallParams = CordovaCommandCall.Parse(commandStr);
  377. if (commandCallParams == null)
  378. {
  379. // ERROR
  380. Debug.WriteLine("ScriptNotify :: " + commandStr);
  381. }
  382. else if (commandCallParams.Service == "CoreEvents")
  383. {
  384. switch (commandCallParams.Action.ToLower())
  385. {
  386. case "overridebackbutton":
  387. string arg0 = JsonHelper.Deserialize<string[]>(commandCallParams.Args)[0];
  388. this.OverrideBackButton = (arg0 != null && arg0.Length > 0 && arg0.ToLower() == "true");
  389. break;
  390. }
  391. }
  392. else
  393. {
  394. if (configHandler.IsPluginAllowed(commandCallParams.Service))
  395. {
  396. nativeExecution.ProcessCommand(commandCallParams);
  397. }
  398. else
  399. {
  400. Debug.WriteLine("Error::Plugin not allowed in config.xml. " + commandCallParams.Service);
  401. }
  402. }
  403. }
  404. public void LoadPage(string url)
  405. {
  406. try
  407. {
  408. Uri newLoc = new Uri(url,UriKind.RelativeOrAbsolute);
  409. CordovaBrowser.Navigate(newLoc);
  410. }
  411. catch(Exception)
  412. {
  413. }
  414. }
  415. private void GapBrowser_Unloaded(object sender, RoutedEventArgs e)
  416. {
  417. }
  418. private void GapBrowser_NavigationFailed(object sender, System.Windows.Navigation.NavigationFailedEventArgs e)
  419. {
  420. Debug.WriteLine("GapBrowser_NavigationFailed :: " + e.Uri.ToString());
  421. }
  422. private void GapBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
  423. {
  424. Debug.WriteLine("GapBrowser_Navigated :: " + e.Uri.ToString());
  425. foreach (IBrowserDecorator iBD in browserDecorators.Values)
  426. {
  427. iBD.InjectScript();
  428. }
  429. }
  430. }
  431. }