private static void OnShouldStyleParentListBoxChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (!(bool)e.NewValue || d is not FrameworkElement element) { return; } element.WhenLoaded(_ => { // We're styling the parent VS ListBox included inside the tooltip. if (element.FindVisualAncestor(o => o is ItemsControl ic && IsToolTipItemsControl(ic)) is not ItemsControl itemsControl || itemsControl.GetValue(_originalStylesProperty) is not null) { return; } IDocument?document = null; GetDocument(element)?.TryGetTarget(out document); SetItemsControlStyle(itemsControl, document); void OnItemsControlUnloaded(object?sender, RoutedEventArgs args) { itemsControl.Unloaded -= OnItemsControlUnloaded; RestoreOriginalStyles(itemsControl); } itemsControl.Unloaded += OnItemsControlUnloaded; }); }
private async Task <bool?> IsDiscoveryQueueAvailable() { using IDocument? htmlDocument = await Bot.ArchiWebHandler.GetDiscoveryQueuePage().ConfigureAwait(false); if (htmlDocument == null) { return(null); } IElement?htmlNode = htmlDocument.SelectSingleNode("//div[@class='subtext']"); if (htmlNode == null) { // Valid, no cards for exploring the queue available return(false); } string text = htmlNode.TextContent; if (string.IsNullOrEmpty(text)) { Bot.ArchiLogger.LogNullError(nameof(text)); return(null); } if (Debugging.IsUserDebugging) { Bot.ArchiLogger.LogGenericDebug(string.Format(CultureInfo.CurrentCulture, Strings.Content, text)); } // It'd make more sense to check against "Come back tomorrow", but it might not cover out-of-the-event queue return(text.StartsWith("You can get ", StringComparison.Ordinal)); }
/// <summary> /// Gets the menu header of a command for a source element. /// </summary> /// <param name="command">The command.</param> /// <param name="activeDocument">The active document.</param> /// <returns>The header.</returns> protected virtual string GetItemHeader(ICommand command, IDocument?activeDocument) { string ItemHeader; switch (command) { case ActiveDocumentRoutedCommand AsActiveDocumentCommand: if (activeDocument == null) { ItemHeader = AsActiveDocumentCommand.InactiveMenuHeader; } else { string CommandTextFormat = AsActiveDocumentCommand.MenuHeader; ItemHeader = string.Format(CultureInfo.CurrentCulture, CommandTextFormat, activeDocument.Path.HeaderName); } break; case ExtendedRoutedCommand AsExtendedRoutedCommand: ItemHeader = AsExtendedRoutedCommand.MenuHeader; break; case RoutedUICommand AsUICommand: ItemHeader = AsUICommand.Text; break; default: throw new ArgumentOutOfRangeException(nameof(command)); } return(ItemHeader); }
internal static async Task <bool?> IsDiscoveryQueueAvailable(Bot bot) { Uri request = new(SteamStoreURL, "/explore?l=english"); HtmlDocumentResponse?response = await bot.ArchiWebHandler.UrlGetToHtmlDocumentWithSession(request).ConfigureAwait(false); IDocument?htmlDocument = response?.Content; if (htmlDocument == null) { return(null); } IElement?htmlNode = htmlDocument.SelectSingleNode("//div[@class='subtext']"); if (htmlNode == null) { // Valid, no cards for exploring the queue available return(false); } string text = htmlNode.TextContent; if (string.IsNullOrEmpty(text)) { bot.ArchiLogger.LogNullError(nameof(text)); return(null); } bot.ArchiLogger.LogGenericTrace(text); // It'd make more sense to check against "Come back tomorrow", but it might not cover out-of-the-event queue return(text.StartsWith("You can get ", StringComparison.Ordinal)); }
/// <summary> /// Converts from a button command to a menu header. /// </summary> /// <param name="values">The array of values to convert.</param> /// <param name="targetType">The type of the binding target property.</param> /// <param name="parameter">The converter parameter to use.</param> /// <param name="culture">The culture to use in the converter.</param> /// <returns>The converted value.</returns> public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { if (values != null && values.Length >= 1) { if (values[0] == DependencyProperty.UnsetValue) { return(null !); } if (values[0] is ICommand Command) { IDocument?ActiveDocument = null; string? ApplicationName = null; for (int i = 1; i < values.Length; i++) { if (values[i] is IDocument) { ActiveDocument = values[i] as IDocument; } if (values[i] is string) { ApplicationName = values[i] as string; } } return(GetItemHeader(Command, ActiveDocument, ApplicationName)); } } throw new ArgumentOutOfRangeException(nameof(values)); }
private HtmlDocumentResponse(StreamResponse streamResponse, IDocument document) : this(streamResponse) { if ((streamResponse == null) || (document == null)) { throw new ArgumentNullException(nameof(streamResponse) + " || " + nameof(document)); } Content = document; }
/// <summary> /// Creates a new set of document options from the given response with /// the provided configuration. /// </summary> /// <param name="response">The response to pass on.</param> /// <param name="encoding">The optional default encoding.</param> /// <param name="ancestor">The optional import ancestor.</param> public CreateDocumentOptions(IResponse response, Encoding?encoding = null, IDocument?ancestor = null) { var contentType = response.GetContentType(MimeTypeNames.Html); var charset = contentType.GetParameter(AttributeNames.Charset); var defaultEncoding = encoding ?? Encoding.UTF8; var source = new TextSource(response.Content, defaultEncoding); if (charset is { Length : > 0 } && TextEncoding.IsSupported(charset))
protected override async Task ProcessResponseAsync(IResponse response) { var context = new BrowsingContext(_context, Sandboxes.None); var encoding = _context.GetDefaultEncoding(); var options = new CreateDocumentOptions(response, encoding, _parentDocument); var factory = _context.GetFactory <IDocumentFactory>(); ChildDocument = await factory.CreateAsync(context, options, CancellationToken.None).ConfigureAwait(false); }
protected override void OnActiveDocumentChanged(IDocument?activeDocument) { if (activeDocument == null) { mainViewModel.ActiveDocumentView = null; } else { if (activeDocument is RichTextDocument richTextDocument) { mainViewModel.ActiveDocumentView = richTextViewModels[richTextDocument].View; } } }
private async Task <bool> SaveCurrentDocumentAsync(bool showFileDialog) { IDocument?doc = Controller.CurrentDocument; if (doc is null) { return(true); } RefreshData(); if (!doc.Changed) { return(true); } string?fileName = doc.FileName; if (fileName is null) { showFileDialog = true; fileName = $"{Path.GetFileNameWithoutExtension(doc.SourceDocumentPath)}.{doc.TargetLanguage ?? Res.Language}{App.TsltnFileExtension}"; } if (showFileDialog) { if (!GetTsltnOutFileName(ref fileName)) { return(false); } } var task = Task.Run(() => Controller.CurrentDocument?.Save(fileName)); _tasks.Add(task); try { await task.ConfigureAwait(false); } catch (Exception ex) { string errorMessage = string.Format(CultureInfo.InvariantCulture, "The file {0}{1}could not be saved:{1}{2}", fileName, Environment.NewLine, ex.Message); _ = Dispatcher.BeginInvoke(() => ShowMessage(errorMessage, MessageBoxImage.Error), DispatcherPriority.Send); return(false); } return(true); }
private async Task TranslateCurrentDocumentAsync() { IDocument?doc = Controller.CurrentDocument; if (doc is null || !await SaveCurrentDocumentAsync(false)) { return; } string?fileName = doc.SourceDocumentPath; if (GetXmlOutFileName(ref fileName)) { (IList <DataError> Errors, IList <KeyValuePair <long, string> > UnusedTranslations)result; var task = Task.Run(() => doc.Translate(fileName)); _tasks.Add(task); try { result = await task.ConfigureAwait(true); } catch (Exception ex) { ShowMessage(ex.Message, MessageBoxImage.Error); return; } if (result.Errors.Count != 0) { TranslationError?.Invoke(this, new DataErrorEventArgs(result.Errors)); } if (result.UnusedTranslations.Count != 0) { var wnd = new SelectUnusedTranslationsWindow(System.IO.Path.GetFileName(Controller.CurrentDocument !.FileName), result.UnusedTranslations); if (true == wnd.ShowDialog(this)) { foreach (UnusedTranslationUserControl cntr in wnd.Controls) { if (cntr.Remove) { doc.RemoveTranslation(cntr.Kvp.Key); } } } } } }
private async void ShowCurrentDocument() { IDocument?doc = Controller.CurrentDocument; if (doc is null) { _ccContent.Content = null; return; } var cntr = new TsltnControl(this, doc); _ccContent.Content = cntr; _ = cntr._tbOriginal.Focus(); string?fileName = doc.FileName; if (fileName != null) { _tasks.Add(_recentFilesMenu.AddRecentFileAsync(fileName)); } if (doc.HasValidSourceDocument) { doc.PropertyChanged += Doc_PropertyChanged; doc.FileWatcherFailed += Doc_FileWatcherFailed; //doc.SourceDocumentDeleted += Doc_SourceDocumentDeleted; doc.SourceDocumentChanged += Doc_SourceDocumentChanged; } else { string errorMessage = doc.HasSourceDocument ? string.Format( CultureInfo.CurrentCulture, Res.EmptyOrInvalidFile, Environment.NewLine, System.IO.Path.GetFileName(doc.SourceDocumentPath), Res.XmlDocumentationFile) : string.Format(CultureInfo.CurrentCulture, Res.SourceDocumentNotFound, Environment.NewLine, doc.SourceDocumentPath); ShowMessage(errorMessage, MessageBoxImage.Error); if (!await ChangeSourceDocumentAsync().ConfigureAwait(false)) { Controller.CloseCurrentDocument(); } } }
private static async Task <List <NewsEntry> > GetNews(string Url, CancellationToken token) { IDocument?document = null; for (int i = 1; ; i++) { try { document = await BrowsingContext.New(Configuration.Default.WithDefaultLoader()).OpenAsync(Url); break; } catch (Exception ex) { if (i == 1 || i % 100 == 0) { Log.Error(ex, "Fehler beim Laden der News, Versuch {Try}", i); } await Task.Delay(5000, token); } } return(document.QuerySelectorAll <IHtmlDivElement>("div.entrylist > div.entry").Select(x => { NewsEntry entry = new NewsEntry(); entry.Titel = x.QuerySelector <IHtmlDivElement>("div.headline")?.Children.FirstOrDefault()?.TextContent?.Trim(); List <IHtmlDivElement> metaInfos = x.QuerySelectorAll <IHtmlDivElement>("div.meta-infos > div.row > div.cell").ToList(); if (metaInfos.Count % 2 != 0) { Debug.Fail("Meta-Info struktur geändert"); Log.Warning("Meta-Info struktur geändert, Count {Count}", metaInfos.Count); return null; } entry.Version = metaInfos.SkipWhile(m => m.TextContent != "Version:").ElementAtOrDefault(1)?.TextContent.Trim(); string?rawDateString = metaInfos.SkipWhile(m => m.TextContent != "Datum:").ElementAtOrDefault(1)?.TextContent.Trim(); if (!DateTime.TryParseExact(rawDateString, "dd.MM.yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime parsed)) { parsed = DateTime.MinValue; Log.Warning("Fehler beim Parsen der DateTime {DateTime}", rawDateString); } entry.Datum = parsed; return entry; }).NotNull().ToList()); }
public async Task <byte[]?> ToHtml(byte[] contents, CancellationToken cancellationToken) { using var ms = new MemoryStream(contents); MimeMessage?message = await MimeMessage.LoadAsync(ms, cancellationToken); if (message == null) { return(null); } List <MimePartChunk> chunks = message.BodyParts.OfType <MimePart>() .Select(part => { using var outStream = new MemoryStream(); part.Content.DecodeTo(outStream, cancellationToken); return(new MimePartChunk(part.ContentType.MimeType, part.ContentLocation, outStream.ToArray())); }) .ToList(); Uri baseUri = message.Body.ContentLocation ?? new Uri("http://localhost/"); using var bodyLoader = new MhtmlBodyLoader(_logger); IDocument?doc = await bodyLoader.Load(message.Body, cancellationToken); if (doc == null) { return(null); } var processor = new DocumentPostprocessor(_options, doc, baseUri, chunks, _logger); doc = processor.Run(); string html = doc.DocumentElement .ToHtml(_options.CompressHtml ? new MinifyMarkupFormatter { ShouldKeepAttributeQuotes = true } : new PrettyMarkupFormatter() ); return(Encoding.UTF8.GetBytes(html)); }
/// <summary> /// Gets the menu header of a command for a source element. /// </summary> /// <param name="command">The command.</param> /// <param name="activeDocument">The active document.</param> /// <param name="applicationName">The application name.</param> /// <returns>The header.</returns> protected virtual string GetItemHeader(ICommand command, IDocument?activeDocument, string?applicationName) { string ItemHeader; switch (command) { case ActiveDocumentRoutedCommand AsActiveDocumentCommand: if (activeDocument == null) { ItemHeader = AsActiveDocumentCommand.InactiveMenuHeader; } else { string CommandTextFormat = AsActiveDocumentCommand.MenuHeader; ItemHeader = string.Format(CultureInfo.CurrentCulture, CommandTextFormat, activeDocument.Path.HeaderName); } break; case LocalizedRoutedCommand AsLocalizedRoutedCommand: ItemHeader = AsLocalizedRoutedCommand.MenuHeader; if (ItemHeader.Contains(LocalizedRoutedCommand.ApplicationNamePattern) && applicationName != null) { ItemHeader = ItemHeader.Replace(LocalizedRoutedCommand.ApplicationNamePattern, applicationName); } break; case ExtendedRoutedCommand AsExtendedRoutedCommand: ItemHeader = AsExtendedRoutedCommand.MenuHeader; break; case RoutedUICommand AsUICommand: ItemHeader = AsUICommand.Text; break; default: throw new ArgumentOutOfRangeException(nameof(command)); } return(ItemHeader); }
private async Task <bool> ChangeSourceDocumentAsync() { IDocument?doc = Controller.CurrentDocument; if (doc is null) { return(true); } string?sourceFilePath = Controller.CurrentDocument?.SourceDocumentPath; if (!GetXmlInFileName(ref sourceFilePath)) { return(false); } doc.ChangeSourceDocument(sourceFilePath); if (!await SaveCurrentDocumentAsync(false)) { return(false); } Debug.Assert(doc.FileName != null); try { await Task.Run(() => Controller.OpenTsltnDocument(doc.FileName)).ConfigureAwait(false); } catch (Exception ex) { string errorMessage = string.Format(CultureInfo.InvariantCulture, Res.OpenFileFailed, Environment.NewLine, doc.FileName, ex.Message); _ = Dispatcher.BeginInvoke(() => ShowMessage(errorMessage, MessageBoxImage.Error), DispatcherPriority.Send); } return(true); }
public static IContextBoundSettingsStore?TryGetSettings(this IDocument?document) => document is not null && Shell.HasInstance ? document.GetSettings() : null;
internal BrowsingContext(IBrowsingContext parent, Sandboxes security) : this(parent.OriginalServices, security) { _parent = parent; _creator = _parent.Active; }
public DocumentRequestProcessor(IBrowsingContext context) : base(context.GetService <IResourceLoader>() !) { _parentDocument = context.Active; _context = context; }
protected abstract void OnActiveDocumentChanged(IDocument?activeDocument);
private async Task WaitResponse(Task <IDocument> task) { Document = await task.ConfigureAwait(false); }
protected override void OnActiveDocumentChanged(IDocument?activeDocument) => throw new NotSupportedException();