public override async Task Execute(params object[] args) { using (var one = new OneNote(out var page, out _)) { if (!page.ConfirmBodyContext()) { UIHelper.ShowError(Resx.Error_BodyContext); return; } } var path = args[0] as string; var snippet = await new SnippetsProvider().Load(path); if (snippet == null) { UIHelper.ShowMessage(string.Format(Resx.InsertSnippets_CouldNotLoad, path)); return; } await SingleThreaded.Invoke(() => { Win.Clipboard.SetText(snippet, Win.TextDataFormat.Html); }); // both SetText and SendWait are very unpredictable so wait a little await Task.Delay(200); //SendKeys.SendWait("^(v)"); new InputSimulator().Keyboard .ModifiedKeyStroke(VirtualKeyCode.CONTROL, VirtualKeyCode.VK_V); }
private void CopyTime(object sender, EventArgs e) { var stamp = TimeSpan.FromSeconds(++Seconds).ToString("c"); SingleThreaded.Invoke(() => { Win.Clipboard.SetText(stamp, Win.TextDataFormat.Text); }); }
public override async Task Execute(params object[] args) { using (var one = new OneNote(out var page, out var ns)) { var elements = page.Root.Descendants(ns + "T") .Where(e => e.Attribute("selected")?.Value == "all"); var text = await SingleThreaded.Invoke(() => { if (Win.Clipboard.ContainsText(Win.TextDataFormat.Text)) { return(Win.Clipboard.GetText(Win.TextDataFormat.Text)); } else { return(null); } }); if (string.IsNullOrEmpty(text)) { return; } var content = new XElement(ns + "T", new XCData(text)); if (elements == null) { // empty page so add new content page.AddNextParagraph(content); } else if (elements.Count() > 1) { // selected multiple runs so replace them all page.ReplaceSelectedWithContent(content); } else { var line = elements.First(); if (line.Value.Length == 0) { // empty cdata, unselected cursor so just insert line.GetCData().Value = text; } else { // something is selected so replace it page.ReplaceSelectedWithContent(content); } } await one.Update(page); } }
public override async Task Execute(params object[] args) { using (var one = new OneNote(out var page, out _)) { if (page.GetTextCursor() != null) { UIHelper.ShowMessage(Resx.SaveSnippet_NeedSelection); return; } // since the Hotkey message loop is watching all input, explicitly setting // focus on the OneNote main window provides a direct path for SendKeys Native.SetForegroundWindow(one.WindowHandle); //SendKeys.SendWait("^(c)"); new InputSimulator().Keyboard .ModifiedKeyStroke(VirtualKeyCode.CONTROL, VirtualKeyCode.VK_C); // SendWait can be very unpredictable so wait a little await Task.Delay(200); } var html = await SingleThreaded.Invoke(() => { if (Win.Clipboard.ContainsText(Win.TextDataFormat.Html)) { return(Win.Clipboard.GetText(Win.TextDataFormat.Html)); } else { return(null); } }); if (html == null || html.Length == 0) { return; } using (var dialog = new SaveSnippetDialog()) { if (dialog.ShowDialog(Owner) != DialogResult.OK) { return; } await new SnippetsProvider().Save(html, dialog.SnippetName); ribbon.InvalidateControl("ribFavoritesMenu"); } }
private async void ImportWebDialog_Load(object sender, System.EventArgs e) { var clipboard = await SingleThreaded.Invoke(() => { return(Win.Clipboard.ContainsText(Win.TextDataFormat.Text) ? Win.Clipboard.GetText(Win.TextDataFormat.Text) : null); }); if (Uri.IsWellFormedUriString(clipboard, UriKind.Absolute)) { addressBox.Text = clipboard; } }
// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = // Markdown... private async Task ImportMarkdown(string filepath) { try { var text = File.ReadAllText(filepath); var deep = new Markdown { MaxImageWidth = 800, ExtraMode = true, UrlBaseLocation = Path.GetDirectoryName(filepath) }; var body = deep.Transform(text); if (!string.IsNullOrEmpty(body)) { var builder = new StringBuilder(); builder.AppendLine("<html>"); builder.AppendLine("<body>"); builder.AppendLine("<!--StartFragment-->"); builder.AppendLine(body); builder.AppendLine("<!--EndFragment-->"); builder.AppendLine("</body>"); builder.AppendLine("</html>"); var html = PasteRtfCommand.AddHtmlPreamble(builder.ToString()); // paste HTML await SingleThreaded.Invoke(() => { Win.Clipboard.SetText(html, Win.TextDataFormat.Html); }); // both SetText and SendWait are very unpredictable so wait a little await Task.Delay(200); //SendKeys.SendWait("^(v)"); new InputSimulator().Keyboard .ModifiedKeyStroke(VirtualKeyCode.CONTROL, VirtualKeyCode.VK_V); } } catch (Exception exc) { logger.WriteLine(exc); UIHelper.ShowMessage("Could not import. See log file for details"); } }
public override async Task Execute(params object[] args) { var path = args[0] as string; var snippet = await new SnippetsProvider().Load(path); if (snippet == null) { UIHelper.ShowMessage(string.Format(Resx.InsertSnippets_CouldNotLoad, path)); return; } await SingleThreaded.Invoke(() => { Win.Clipboard.SetText(snippet, Win.TextDataFormat.Html); }); // both SetText and SendWait are very unpredictable so wait a little await Task.Delay(200); SendKeys.SendWait("^(v)"); }
private async Task <Page> GetSourcePage() { // the Clipboard will contain HTML of the copied cells wrapped in a <table> var content = await SingleThreaded.Invoke(() => { return(Win.Clipboard.ContainsText(Win.TextDataFormat.Html) ? Win.Clipboard.GetText(Win.TextDataFormat.Html) : null); }); if (string.IsNullOrEmpty(content)) { return(null); } if (!ValidateClipboardContent(content)) { return(null); } return(await CreateTemplatePage()); }
private async void BrowseFile(object sender, EventArgs e) { try { // OpenFileDialog must run in an STA thread var path = await SingleThreaded.Invoke(() => { using (var dialog = new OpenFileDialog() { AddExtension = true, CheckFileExists = true, DefaultExt = ".docx", Filter = Resx.ImportDialog_OpenFileFilter, InitialDirectory = pathBox.Text, Multiselect = false, Title = Resx.ImportDialog_OpenFileTitle }) { // cannot use owner parameter here or it will hang! cross-threading if (dialog.ShowDialog() == DialogResult.OK) { return(dialog.FileName); } } return(null); }); if (path != null) { pathBox.Text = path; } } catch (Exception exc) { Logger.Current.WriteLine("error running OpenFileDialog", exc); } }
public override async Task Execute(params object[] args) { var scope = args[0] as string; using (one = new OneNote()) { bookScope = scope == "notebook"; hierarchy = bookScope ? one.GetNotebook(one.CurrentNotebookId, OneNote.Scope.Pages) : one.GetSection(one.CurrentSectionId); var ns = one.GetNamespace(hierarchy); totalCount = hierarchy.Descendants(ns + "Page").Count(); if (totalCount == 0) { UIHelper.ShowMessage(Resx.ArchiveCommand_noPages); return; } var topName = hierarchy.Attribute("name").Value; zipPath = await SingleThreaded.Invoke(() => { // OpenFileDialog must run in STA thread return(ChooseLocation(topName)); }); if (zipPath == null) { return; } var progressDialog = new UI.ProgressDialog(Execute); await progressDialog.RunModeless(); } }
// https://github.com/LanderVe/WPF_PDFDocument/blob/master/WPF_PDFDocument/WPF_PDFDocument.csproj // https://blogs.u2u.be/lander/post/2018/01/23/Creating-a-PDF-Viewer-in-WPF-using-Windows-10-APIs // https://docs.microsoft.com/en-us/uwp/api/windows.data.pdf.pdfdocument.getpage?view=winrt-20348 private async Task ImportImages(ProgressDialog progress, CancellationToken token) { logger.Start(); logger.StartClock(); progress.SetMaximum(4); progress.SetMessage($"Importing {address}..."); var pdfFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); // WebView2 needs to run in an STA thread await SingleThreaded.Invoke(() => { // WebView2 needs a message pump so host in its own invisible worker dialog using (var form = new WebViewWorkerDialog( new WebViewWorker(async(webview) => { webview.Source = new Uri(address); progress.Increment(); await Task.Yield(); return(true); }), new WebViewWorker(async(webview) => { progress.Increment(); await Task.Delay(2000); await webview.CoreWebView2.PrintToPdfAsync(pdfFile); progress.Increment(); return(true); }))) { form.ShowDialog(progress); } }); if (token.IsCancellationRequested) { return; } if (!File.Exists(pdfFile)) { logger.WriteLine($"PDF file not found, {pdfFile}"); return; } // convert PDF pages to images... logger.WriteLine("rendering images"); try { Page page = null; using (var one = new OneNote()) { page = target == ImportWebTarget.Append ? one.GetPage() : await CreatePage(one, target == ImportWebTarget.ChildPage?one.GetPage() : null, address); } var ns = page.Namespace; var container = page.EnsureContentContainer(); var file = await StorageFile.GetFileFromPathAsync(pdfFile); var doc = await Windows.Data.Pdf.PdfDocument.LoadFromFileAsync(file); await file.DeleteAsync(); progress.SetMaximum((int)doc.PageCount); for (int i = 0; i < doc.PageCount; i++) { progress.SetMessage($"Rasterizing image {i} of {doc.PageCount}"); progress.Increment(); //logger.WriteLine($"rasterizing page {i}"); var pdfpage = doc.GetPage((uint)i); using (var stream = new InMemoryRandomAccessStream()) { await pdfpage.RenderToStreamAsync(stream); using (var image = new Bitmap(stream.AsStream())) { var data = Convert.ToBase64String( (byte[])new ImageConverter().ConvertTo(image, typeof(byte[])) ); container.Add(new XElement(ns + "OE", new XElement(ns + "Image", new XAttribute("format", "png"), new XElement(ns + "Size", new XAttribute("width", $"{image.Width}.0"), new XAttribute("height", $"{image.Height}.0")), new XElement(ns + "Data", data) )), new Paragraph(ns, " ") ); } } } progress.SetMessage($"Updating page"); using (var one = new OneNote()) { await one.Update(page); } } catch (Exception exc) { logger.WriteLine(exc.Message, exc); } logger.WriteTime("import complete"); logger.End(); }
// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = private async Task <WebPageInfo> DownloadWebContent(Uri uri) { // This JavaScript copies the HTML of the entire web page to the clipboard // and returns the text of the page <title> const string javascript = @"var range = document.createRange(); range.selectNodeContents(document.body); var selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range); document.execCommand('copy'); document.getElementsByTagName('title')[0].innerText;"; string content = null; string title = null; // WebView2 needs to run in an STA thread await SingleThreaded.Invoke(() => { // WebView2 needs a message pump so host in its own invisible worker dialog using (var form = new WebViewWorkerDialog( startup: new WebViewWorker(async(webview) => { //logger.WriteLine($"starting up webview with {uri}"); webview.Source = uri; await Task.Yield(); return(true); }), work: new WebViewWorker(async(webview) => { //logger.WriteLine("getting webview content"); await Task.Delay(200); title = await webview.ExecuteScriptAsync(javascript); //logger.WriteLine($"title=[{title}]"); await Task.Delay(100); if (Win.Clipboard.ContainsText(Win.TextDataFormat.Html)) { content = Win.Clipboard.GetText(Win.TextDataFormat.Html); var index = content.IndexOf( "<html", StringComparison.InvariantCultureIgnoreCase); if (index > 0) { content = content.Substring(index); } } else { content = null; } //logger.WriteLine($"content=[{content}]"); await Task.Yield(); return(true); }))) { form.ShowDialog(); } }); if (title != null && title.Length > 1 && title[0] == '"' && title[title.Length - 1] == '"') { title = title.Substring(1, title.Length - 2); } var bycount = content == null ? 0 : content.Length; logger.WriteLine($"retrieved {bycount} bytes from {title} ({uri.AbsoluteUri})"); return(new WebPageInfo { Content = content, Title = title }); }