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

/lib/windows/framework/PGView.xaml.cs

https://github.com/sanyaade-mobiledev/phonegap-1
C# | 400 lines | 290 code | 66 blank | 44 comment | 33 complexity | d50fe84b953ea07576c478ee2a62c55d MD5 | raw file
Possible License(s): Apache-2.0, BSD-3-Clause, MIT
  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 WP7GapClassLib.PhoneGap.Commands;
  32. using System.Diagnostics;
  33. using System.Text;
  34. using WP7GapClassLib.PhoneGap;
  35. using System.Threading;
  36. using Microsoft.Phone.Shell;
  37. namespace WP7GapClassLib
  38. {
  39. public partial class PGView : UserControl
  40. {
  41. /// <summary>
  42. /// Indicates whether web control has been loaded and no additional initialization is needed.
  43. /// Prevents data clearing during page transitions.
  44. /// </summary>
  45. private bool IsBrowserInitialized = false;
  46. private bool OverrideBackButton = false;
  47. private static string AppRoot = "/app/";
  48. /// <summary>
  49. /// Handles native api calls
  50. /// </summary>
  51. private NativeExecution nativeExecution;
  52. protected DOMStorageHelper domStorageHelper;
  53. protected OrientationHelper orientationHelper;
  54. public System.Windows.Controls.Grid _LayoutRoot
  55. {
  56. get
  57. {
  58. return ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot")));
  59. }
  60. }
  61. public WebBrowser Browser
  62. {
  63. get
  64. {
  65. return GapBrowser;
  66. }
  67. }
  68. /*
  69. * Setting StartPageUri only has an effect if called before the view is loaded.
  70. **/
  71. protected Uri _startPageUri = null;
  72. public Uri StartPageUri
  73. {
  74. get
  75. {
  76. if (_startPageUri == null)
  77. {
  78. // default
  79. return new Uri( AppRoot + "www/index.html", UriKind.Relative);
  80. }
  81. else
  82. {
  83. return _startPageUri;
  84. }
  85. }
  86. set
  87. {
  88. if (!this.IsBrowserInitialized)
  89. {
  90. _startPageUri = value;
  91. }
  92. }
  93. }
  94. public PGView()
  95. {
  96. InitializeComponent();
  97. if (DesignerProperties.IsInDesignTool)
  98. {
  99. return;
  100. }
  101. StartupMode mode = PhoneApplicationService.Current.StartupMode;
  102. if (mode == StartupMode.Launch)
  103. {
  104. PhoneApplicationService service = PhoneApplicationService.Current;
  105. service.Activated += new EventHandler<Microsoft.Phone.Shell.ActivatedEventArgs>(AppActivated);
  106. service.Launching += new EventHandler<LaunchingEventArgs>(AppLaunching);
  107. service.Deactivated += new EventHandler<DeactivatedEventArgs>(AppDeactivated);
  108. service.Closing += new EventHandler<ClosingEventArgs>(AppClosing);
  109. }
  110. else
  111. {
  112. }
  113. // initializes native execution logic
  114. this.nativeExecution = new NativeExecution(ref this.GapBrowser);
  115. }
  116. void AppClosing(object sender, ClosingEventArgs e)
  117. {
  118. Debug.WriteLine("AppClosing");
  119. }
  120. void AppDeactivated(object sender, DeactivatedEventArgs e)
  121. {
  122. Debug.WriteLine("AppDeactivated");
  123. try
  124. {
  125. GapBrowser.InvokeScript("PhoneGapCommandResult", new string[] { "pause" });
  126. }
  127. catch (Exception)
  128. {
  129. Debug.WriteLine("Pause event error");
  130. }
  131. }
  132. void AppLaunching(object sender, LaunchingEventArgs e)
  133. {
  134. Debug.WriteLine("AppLaunching");
  135. }
  136. void AppActivated(object sender, Microsoft.Phone.Shell.ActivatedEventArgs e)
  137. {
  138. Debug.WriteLine("AppActivated");
  139. try
  140. {
  141. GapBrowser.InvokeScript("PhoneGapCommandResult", new string[] { "resume" });
  142. }
  143. catch (Exception)
  144. {
  145. Debug.WriteLine("Resume event error");
  146. }
  147. }
  148. void GapBrowser_Loaded(object sender, RoutedEventArgs e)
  149. {
  150. if (DesignerProperties.IsInDesignTool)
  151. {
  152. return;
  153. }
  154. // prevents refreshing web control to initial state during pages transitions
  155. if (this.IsBrowserInitialized) return;
  156. this.domStorageHelper = new DOMStorageHelper(this.GapBrowser);
  157. try
  158. {
  159. // Before we possibly clean the ISO-Store, we need to grab our generated UUID, so we can rewrite it after.
  160. string deviceUUID = "";
  161. using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication())
  162. {
  163. try
  164. {
  165. IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream("DeviceID.txt", FileMode.Open, FileAccess.Read, appStorage);
  166. using (StreamReader reader = new StreamReader(fileStream))
  167. {
  168. deviceUUID = reader.ReadLine();
  169. }
  170. }
  171. catch (Exception /*ex*/)
  172. {
  173. deviceUUID = Guid.NewGuid().ToString();
  174. }
  175. Debug.WriteLine("Updating IsolatedStorage for APP:DeviceID :: " + deviceUUID);
  176. IsolatedStorageFileStream file = new IsolatedStorageFileStream("DeviceID.txt", FileMode.Create, FileAccess.Write, appStorage);
  177. using (StreamWriter writeFile = new StreamWriter(file))
  178. {
  179. writeFile.WriteLine(deviceUUID);
  180. writeFile.Close();
  181. }
  182. }
  183. StreamResourceInfo streamInfo = Application.GetResourceStream(new Uri("GapSourceDictionary.xml", UriKind.Relative));
  184. if (streamInfo != null)
  185. {
  186. StreamReader sr = new StreamReader(streamInfo.Stream);
  187. //This will Read Keys Collection for the xml file
  188. XDocument document = XDocument.Parse(sr.ReadToEnd());
  189. var files = from results in document.Descendants("FilePath")
  190. select new
  191. {
  192. path = (string)results.Attribute("Value")
  193. };
  194. StreamResourceInfo fileResourceStreamInfo;
  195. using (IsolatedStorageFile appStorage = IsolatedStorageFile.GetUserStoreForApplication())
  196. {
  197. foreach (var file in files)
  198. {
  199. fileResourceStreamInfo = Application.GetResourceStream(new Uri(file.path, UriKind.Relative));
  200. if (fileResourceStreamInfo != null)
  201. {
  202. using (BinaryReader br = new BinaryReader(fileResourceStreamInfo.Stream))
  203. {
  204. byte[] data = br.ReadBytes((int)fileResourceStreamInfo.Stream.Length);
  205. string strBaseDir = AppRoot + file.path.Substring(0, file.path.LastIndexOf(System.IO.Path.DirectorySeparatorChar));
  206. if(!appStorage.DirectoryExists(strBaseDir))
  207. {
  208. //Debug.WriteLine("Creating Directory :: " + strBaseDir);
  209. appStorage.CreateDirectory(strBaseDir);
  210. }
  211. // This will truncate/overwrite an existing file, or
  212. using (IsolatedStorageFileStream outFile = appStorage.OpenFile(AppRoot + file.path, FileMode.Create))
  213. {
  214. Debug.WriteLine("Writing data for " + AppRoot + file.path + " and length = " + data.Length);
  215. using (var writer = new BinaryWriter(outFile))
  216. {
  217. writer.Write(data);
  218. }
  219. }
  220. }
  221. }
  222. else
  223. {
  224. Debug.WriteLine("Failed to write file :: " + file.path + " did you forget to add it to the project?");
  225. }
  226. }
  227. }
  228. }
  229. GapBrowser.Navigate(StartPageUri);
  230. IsBrowserInitialized = true;
  231. AttachHardwareButtonHandlers();
  232. }
  233. catch (Exception ex)
  234. {
  235. Debug.WriteLine("Exception in GapBrowser_Loaded :: {0}", ex.Message);
  236. }
  237. }
  238. void AttachHardwareButtonHandlers()
  239. {
  240. PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
  241. if (frame != null)
  242. {
  243. PhoneApplicationPage page = frame.Content as PhoneApplicationPage;
  244. if (page != null)
  245. {
  246. page.BackKeyPress += new EventHandler<CancelEventArgs>(page_BackKeyPress);
  247. this.orientationHelper = new OrientationHelper(this.GapBrowser, page);
  248. }
  249. }
  250. }
  251. void page_BackKeyPress(object sender, CancelEventArgs e)
  252. {
  253. if (OverrideBackButton)
  254. {
  255. try
  256. {
  257. GapBrowser.InvokeScript("PhoneGapCommandResult", new string[] { "backbutton" });
  258. e.Cancel = true;
  259. }
  260. catch (Exception)
  261. {
  262. }
  263. }
  264. }
  265. void GapBrowser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
  266. {
  267. this.GapBrowser.Opacity = 1;
  268. }
  269. void GapBrowser_Navigating(object sender, NavigatingEventArgs e)
  270. {
  271. Debug.WriteLine("GapBrowser_Navigating to :: " + e.Uri.ToString());
  272. // TODO: tell any running plugins to stop doing what they are doing.
  273. // TODO: check whitelist / blacklist
  274. // NOTE: Navigation can be cancelled by setting : e.Cancel = true;
  275. }
  276. /*
  277. * This method does the work of routing commands
  278. * NotifyEventArgs.Value contains a string passed from JS
  279. * If the command already exists in our map, we will just attempt to call the method(action) specified, and pass the args along
  280. * Otherwise, we create a new instance of the command, add it to the map, and call it ...
  281. * 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
  282. * it is simply output to the debugger output, and the method returns.
  283. *
  284. **/
  285. void GapBrowser_ScriptNotify(object sender, NotifyEventArgs e)
  286. {
  287. string commandStr = e.Value;
  288. // DOMStorage/Local OR DOMStorage/Session
  289. if (commandStr.IndexOf("DOMStorage") == 0)
  290. {
  291. this.domStorageHelper.HandleStorageCommand(commandStr);
  292. return;
  293. }
  294. else if (commandStr.IndexOf("Orientation") == 0)
  295. {
  296. this.orientationHelper.HandleCommand(commandStr);
  297. return;
  298. }
  299. PhoneGapCommandCall commandCallParams = PhoneGapCommandCall.Parse(commandStr);
  300. if (commandCallParams == null)
  301. {
  302. // ERROR
  303. Debug.WriteLine("ScriptNotify :: " + commandStr);
  304. }
  305. else if (commandCallParams.Service == "CoreEvents")
  306. {
  307. switch (commandCallParams.Action.ToLower())
  308. {
  309. case "overridebackbutton":
  310. string[] args = PhoneGap.JSON.JsonHelper.Deserialize<string[]>(commandCallParams.Args);
  311. this.OverrideBackButton = (args != null && args.Length > 0 && args[0] == "true");
  312. break;
  313. }
  314. }
  315. else
  316. {
  317. this.nativeExecution.ProcessCommand(commandCallParams);
  318. }
  319. }
  320. private void GapBrowser_Unloaded(object sender, RoutedEventArgs e)
  321. {
  322. }
  323. private void GapBrowser_NavigationFailed(object sender, System.Windows.Navigation.NavigationFailedEventArgs e)
  324. {
  325. Debug.WriteLine("GapBrowser_NavigationFailed :: " + e.Uri.ToString());
  326. }
  327. private void GapBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
  328. {
  329. Debug.WriteLine("GapBrowser_Navigated :: " + e.Uri.ToString());
  330. }
  331. }
  332. }