Exemplo n.º 1
0
    public async Task AddFilesToProject(PrintElement project, ICollection <string> filesToAdd)
    {
        if (filesToAdd.Count == 0)
        {
            return;
        }

        var progressMessage = _translationManager.GetTranslation(filesToAdd.Count > 1 ? nameof(StringTable.Prog_AddMultipleFilesToProject) : nameof(StringTable.Prog_AddOneFileToProject));
        var failedMessage   = _translationManager.GetTranslation(filesToAdd.Count > 1 ? nameof(StringTable.Fail_AddMultipleFilesToProject) : nameof(StringTable.Fail_AddOneFileToProject));
        var successMessage  = _translationManager.GetTranslation(filesToAdd.Count > 1 ? nameof(StringTable.Suc_AddMultipleFilesToProject) : nameof(StringTable.Suc_AddOneFileToProject));

        await ExecuteLoadingAction(
            progressMessage,
            async() =>
        {
            foreach (var file in filesToAdd.Where(File.Exists))
            {
                var targetPath = Path.Combine(project.DirectoryLocation, Path.GetFileName(file) ?? string.Empty);
                for (int i = 2; File.Exists(targetPath); i++)
                {
                    targetPath = Path.Combine(project.DirectoryLocation, Path.GetFileNameWithoutExtension(file) + $" ({i})" + Path.GetExtension(file));
                }

                await Task.Run(() => File.Copy(file, targetPath));
            }
        },
            successMessage,
            failedMessage);
    }
Exemplo n.º 2
0
 private void ExecuteOpenProjectFolder(PrintElement project)
 {
     Process.Start(new ProcessStartInfo(project.DirectoryLocation)
     {
         UseShellExecute = true,
     });
 }
Exemplo n.º 3
0
    public IEnumerable <PrintElement> GetNewPrintElements(MetadataCache cache, ICollection <PrintElement> elements)
    {
        var printsPath  = cache.PrintsPath;
        var directories = Directory.EnumerateDirectories(printsPath, "*", SearchOption.TopDirectoryOnly);

        foreach (var dir in directories)
        {
            if (!elements.Any(y => string.Equals(y.DirectoryLocation, dir, StringComparison.OrdinalIgnoreCase)))
            {
                var element = new PrintElement(dir);
                if (cache.PrintElements.TryGetValue(element.Name, out var elementCache))
                {
                    element.Metadata = new PrintElementMetadata
                    {
                        IsArchived = elementCache.IsArchived,
                        Tags       = elementCache.Tags?.ToList() ?? new List <string>(),
                    };
                }
                else
                {
                    element.InitializeMetadata();
                }

                yield return(element);
            }
        }
    }
Exemplo n.º 4
0
        public void Print()
        {
            int  numCustomers = 1;
            Font PrintFont    = new Font("Arial", 10);
            Font headFont     = new Font("Arial", 12, System.Drawing.FontStyle.Bold);

            PrintElement Header = new PrintElement(null);

            Header.AddMiddleText("Report", headFont);
            Header.AddHorizontalRule();

            PrintElement Footer = new PrintElement(null);

            Footer.AddHorizontalRule();
            Footer.AddMiddleText("Confidential", headFont);
            PrintEngine _engine = new PrintEngine(Header, Footer);

            for (int n = 0; n < numCustomers; n++)
            {
                Customer theCustomer = new Customer();
                theCustomer.Id        = n + 1;
                theCustomer.FirstName = "Darren";
                theCustomer.LastName  = "Clarke";
                theCustomer.Company   = "Madras inc.";
                theCustomer.Email     = "*****@*****.**";
                theCustomer.Phone     = "602 555 1234";

                _engine.AddPrintObject(theCustomer);
            }
            _engine.Print();
        }
Exemplo n.º 5
0
    public CreateCuraProjectDialog(PrintElement element)
    {
        ServiceContext.GetService(out _translationManager);

        Models      = new ObservableCollection <PrintElementFileSelection>(element?.ModelFiles.Select(x => new PrintElementFileSelection(x)) ?? new List <PrintElementFileSelection>());
        ProjectName = element?.Name ?? _translationManager.GetTranslation(nameof(StringTable.Untitled));

        InitializeComponent();
    }
Exemplo n.º 6
0
 private void ExecuteOpenProjectWebsite(PrintElement project)
 {
     if (!string.IsNullOrEmpty(project.Metadata.Website))
     {
         Process.Start(new ProcessStartInfo(project.Metadata.Website)
         {
             UseShellExecute = true,
         });
     }
 }
        public static void ApplyBaseStyles(this TextWriter result, PrintElement element)
        {
            if (element.Font != null)
            {
                if (!string.IsNullOrWhiteSpace(element.Font.Family))
                {
                    result.Write("font-family:");
                    result.Write(element.Font.Family);
                    result.Write(";");
                }

                if (element.Font.Size != null)
                {
                    result.Write("font-size:");
                    result.WriteInvariant(element.Font.Size.Value);
                    result.Write("px;");
                }

                if (element.Font.Style != null)
                {
                    result.Write("font-style:");
                    result.Write(GetFontStyle(element.Font.Style.Value));
                    result.Write(";");
                }

                if (element.Font.Stretch != null)
                {
                    result.Write("font-stretch:");
                    result.Write(GetFontStretch(element.Font.Stretch.Value));
                    result.Write(";");
                }

                if (element.Font.Weight != null)
                {
                    result.Write("font-weight:");
                    result.Write(GetFontWeight(element.Font.Weight.Value));
                    result.Write(";");
                }
            }

            if (!string.IsNullOrWhiteSpace(element.Background))
            {
                result.Write("background-color:");
                result.Write(element.Background.TryToRgba());
                result.Write(";");
            }

            if (!string.IsNullOrWhiteSpace(element.Foreground))
            {
                result.Write("color:");
                result.Write(element.Foreground.TryToRgba());
                result.Write(";");
            }
        }
        public void Build(PrintElement element, TextWriter result)
        {
            if (element != null)
            {
                IHtmlBuilder builder;

                if (_builders.TryGetValue(element.GetType(), out builder))
                {
                    builder.Build(this, element, result);
                }
            }
        }
Exemplo n.º 9
0
    private async Task ExecuteAddFilesToProject(PrintElement project)
    {
        var ofd = new OpenFileDialog
        {
            Multiselect = true,
        };

        if (ofd.ShowDialog(Application.Current.MainWindow) == true)
        {
            await AddFilesToProject(project, ofd.FileNames);
        }
    }
Exemplo n.º 10
0
 partial void OnSelectedElementChanged(PrintElement previous, PrintElement value)
 {
     Task.Run(() =>
     {
         Thread.Sleep(100);
         Application.Current.Dispatcher.Invoke(() =>
         {
             if (value?.Initialize() == true)
             {
                 AvailableTags.AddIfNotExists(value.Tags);
             }
         });
     });
 }
Exemplo n.º 11
0
 private void ExecuteOpenProjectFile(PrintElementFile file)
 {
     if (PrintElement.IsCuraProjectFile(file.FilePath))
     {
         _curaService.OpenCuraProject(file.FilePath);
     }
     else
     {
         Process.Start(new ProcessStartInfo(file.FilePath)
         {
             UseShellExecute = true,
         });
     }
 }
Exemplo n.º 12
0
    private void ExecuteCreateTag(PrintElement project)
    {
        var dialog = new RenameDialog(_translationManager.GetTranslation(nameof(StringTable.Title_CreateTag)), _translationManager.GetTranslation(nameof(StringTable.Desc_CreateTag)), string.Empty, s => null)
        {
            CustomIcon = new IconPresenter {
                Icon = new MaterialDesignIcon(MaterialDesignIconCode.Plus)
            },
            SubmitButtonContent = _translationManager.GetTranslation(nameof(StringTable.Create)),
        };

        if (dialog.ShowDialog() == true)
        {
            AvailableTags.AddIfNotExists(dialog.NewName);
            project.Tags.AddIfNotExists(dialog.NewName);
        }
    }
Exemplo n.º 13
0
        public static void ApplySubOrSupSlash(this TextWriter result, PrintElement element)
        {
            if (element.Font != null && element.Font.Variant != null)
            {
                switch (element.Font.Variant)
                {
                case PrintElementFontVariant.Subscript:
                    result.Write("</sub>");
                    break;

                case PrintElementFontVariant.Superscript:
                    result.Write("</sup>");
                    break;
                }
            }
        }
Exemplo n.º 14
0
    private async Task ExecuteNewCuraProject(PrintElement project)
    {
        var settings = _settingsService.LoadSettings();

        if (!_curaService.AreCuraPathsCorrect(settings))
        {
            MessageBox.Show(_translationManager.GetTranslation(nameof(StringTable.Msg_CuraPathsNotConfigured)), "CuraManager", AlertButton.Ok, AlertImage.Warning);
        }
        else
        {
            await ExecuteLoadingAction(
                _translationManager.GetTranslation(nameof(StringTable.Prog_CreateCuraProject)),
                async() => await _curaService.CreateCuraProject(project),
                _translationManager.GetTranslation(nameof(StringTable.Suc_CreateCuraProject)),
                _translationManager.GetTranslation(nameof(StringTable.Fail_CreateCuraProject)));
        }
    }
Exemplo n.º 15
0
        public object Build(PrintElement element, PrintElementMetadataMap elementMetadataMap)
        {
            if (element != null)
            {
                IFlowElementBuilder builder;

                if (_builders.TryGetValue(element.GetType(), out builder))
                {
                    var flowElement = builder.Build(this, element, elementMetadataMap);

                    elementMetadataMap.RemapElement(element, flowElement);

                    return(flowElement);
                }
            }

            return(null);
        }
Exemplo n.º 16
0
    public async Task <PrintElement> CreateProject()
    {
        var result = new PrintElement(Path.Combine(_targetPath, ProjectName));
        await Task.Run(() => Directory.CreateDirectory(Path.Combine(result.DirectoryLocation)));

        foreach (var file in Files)
        {
            var targetPath = Path.Combine(result.DirectoryLocation, Path.GetFileName(file.FilePath) ?? string.Empty);
            for (int i = 2; File.Exists(targetPath); i++)
            {
                targetPath = Path.Combine(result.DirectoryLocation, Path.GetFileNameWithoutExtension(file.FilePath) + $" ({i})" + Path.GetExtension(file.FilePath));
            }

            await Task.Run(() => File.Copy(file.FilePath, targetPath));
        }

        return(result);
    }
Exemplo n.º 17
0
    private void ExecuteRenameProject(PrintElement project)
    {
        string Validation(string newName)
        {
            if (string.Equals(project.Name, newName, StringComparison.OrdinalIgnoreCase))
            {
                return(null);
            }

            var path = Path.Combine(Path.GetDirectoryName(project.DirectoryLocation), newName);

            if (Directory.Exists(path))
            {
                return(string.Format(_translationManager.GetTranslation(nameof(StringTable.Msg_ProjectAlreadyExists)), newName));
            }

            return(null);
        }

        var dialog = new RenameDialog(
            _translationManager.GetTranslation(nameof(StringTable.Title_RenameProject)),
            string.Format(_translationManager.GetTranslation(nameof(StringTable.Desc_RenameProject)), project.Name),
            project.Name,
            Validation)
        {
            Owner = Application.Current.MainWindow,
        };

        if (dialog.ShowDialog() == true)
        {
            var newPath = Path.Combine(Path.GetDirectoryName(project.DirectoryLocation), dialog.NewName);

            SelectedElement = null;
            PrintElements.Remove(project);
            project.Dispose();

            Directory.Move(project.DirectoryLocation, newPath);

            var newProject = new PrintElement(newPath);
            PrintElements.Add(newProject);
            SelectedElement = newProject;
        }
    }
Exemplo n.º 18
0
    public async Task <bool> CreateCuraProject(PrintElement element)
    {
        var dialog = new CreateCuraProjectDialog(element)
        {
            Owner = Application.Current.MainWindow
        };

        if (dialog.ShowDialog() == true)
        {
            var modelFiles = from x in dialog.Models
                             where x.IsEnabled && x.Amount > 0
                             from m in Enumerable.Range(0, x.Amount)
                             select x.Element.FilePath;
            await Task.Run(() => OpenCura(element, dialog.ProjectName, modelFiles));

            return(true);
        }

        return(false);
    }
Exemplo n.º 19
0
    private async Task ExecuteDeleteProject(PrintElement project)
    {
        if (MessageBox.Show(string.Format(_translationManager.GetTranslation(nameof(StringTable.Msg_ConfirmProjectDeletion)), project.Name), "CuraManager", AlertButton.YesNo, AlertImage.Question) == AlertResult.No)
        {
            return;
        }

        await ExecuteLoadingAction(
            string.Format(_translationManager.GetTranslation(nameof(StringTable.Prog_DeleteProject)), project.Name),
            async() =>
        {
            project.Dispose();
            PrintElements.Remove(project);
            await Task.Run(() => Directory.Delete(project.DirectoryLocation, true));
            if (SelectedElement == project)
            {
                SelectedElement = null;
            }
        },
            string.Format(_translationManager.GetTranslation(nameof(StringTable.Suc_DeleteProject)), project.Name),
            string.Format(_translationManager.GetTranslation(nameof(StringTable.Fail_DeleteProject)), project.Name));
    }
Exemplo n.º 20
0
    public async Task DownloadFiles(Uri webAddress, PrintElement printElement)
    {
        var zipFilePath = Path.GetTempFileName();
        var fileUri     = await GetResponseUri(webAddress);

        using (var response = await _httpClient.GetAsync(fileUri))
            using (var fs = new FileStream(zipFilePath, FileMode.Create))
                await response.Content.CopyToAsync(fs);

        if (Path.GetExtension(fileUri.ToString()).ToLower() == ".zip")
        {
            using var zipFile = ZipFile.OpenRead(zipFilePath);
            await CreateProjectFromArchiveDialog.GetFilesToExtract(zipFile, printElement.DirectoryLocation)
            .Where(x => !x.Entry.Name.ToLower().In("license.html", "readme.pdf") && !x.Entry.Name.ToLower().EndsWith("-attribution.pdf"))
            .ForEachAsync(x => Task.Run(() => x.Entry.ExtractToFile(x.TargetPath)));
        }
        else
        {
            File.Copy(zipFilePath, Path.Combine(printElement.DirectoryLocation, Path.GetFileName(fileUri.ToString())));
        }

        File.Delete(zipFilePath);
    }
    public async Task <PrintElement> CreateProject()
    {
        var result = new PrintElement(Path.Combine(_targetPath, ProjectName));
        await Task.Run(() => Directory.CreateDirectory(result.DirectoryLocation));

        using (var zipFile = ZipFile.OpenRead(ArchivePath))
        {
            if (zipFile.Entries.TryFirst(x => x.FullName == "attribution_card.html", out var htmlEntry))
            {
                var tempFile = Path.GetTempFileName();
                htmlEntry.ExtractToFile(tempFile, true);
                var doc = new HtmlDocument();
                doc.Load(tempFile);
                result.Metadata.Website = doc.DocumentNode.SelectSingleNode("//h3")?.InnerText;
                result.SaveMetadata();
                File.Delete(tempFile);
            }

            await GetFilesToExtract(zipFile, result.DirectoryLocation)
            .ForEachAsync(x => Task.Run(() => x.Entry.ExtractToFile(x.TargetPath)));
        }

        return(result);
    }
Exemplo n.º 22
0
 public TResult Build <TResult>(PrintElement element, PrintElementMetadataMap elementMetadataMap) where TResult : TextElement
 {
     return((TResult)Build(element, elementMetadataMap));
 }
Exemplo n.º 23
0
        public static void ApplyBaseStyles(dynamic elementContent, PrintElement element)
        {
            if (!string.IsNullOrWhiteSpace(element.Name))
            {
                elementContent.Name = element.Name;
            }

            if (element.Font != null)
            {
                if (!string.IsNullOrWhiteSpace(element.Font.Family))
                {
                    elementContent.FontFamily = new FontFamily(element.Font.Family);
                }

                if (element.Font.Size != null)
                {
                    elementContent.FontSize = element.Font.Size.Value;
                }

                if (element.Font.Style != null)
                {
                    elementContent.FontStyle = GetFontStyle(element.Font.Style.Value);
                }

                if (element.Font.Stretch != null)
                {
                    elementContent.FontStretch = GetFontStretch(element.Font.Stretch.Value);
                }

                if (element.Font.Weight != null)
                {
                    elementContent.FontWeight = GetFontWeight(element.Font.Weight.Value);
                }

                if (element.Font.Variant != null)
                {
                    elementContent.Typography.Variants = GetFontVariant(element.Font.Variant.Value);
                }
            }

            var converter = new BrushConverter();

            if (!string.IsNullOrWhiteSpace(element.Foreground))
            {
                try
                {
                    elementContent.Foreground = (Brush)converter.ConvertFromString(element.Foreground);
                }
                catch
                {
                    // ignored
                }
            }

            if (!string.IsNullOrWhiteSpace(element.Background))
            {
                try
                {
                    elementContent.Background = (Brush)converter.ConvertFromString(element.Background);
                }
                catch
                {
                    // ignored
                }
            }
        }
Exemplo n.º 24
0
 public void Build(HtmlBuilderContext context, PrintElement element, TextWriter result)
 {
     Build(context, (TElement)element, result);
 }
 public object Build(FlowElementBuilderContext context, PrintElement element, PrintElementMetadataMap elementMetadataMap)
 {
     return(Build(context, (TElement)element, elementMetadataMap));
 }
Exemplo n.º 26
0
    public Task DownloadFiles(Uri webAddress, PrintElement printElement)
    {
        var provider = GetProvider(webAddress);

        return(provider.DownloadFiles(webAddress, printElement));
    }
Exemplo n.º 27
0
    public void OpenCura(PrintElement element, string printName, IEnumerable <string> modelsToAdd)
    {
        var settings = _settingsService.LoadSettings();

        SetCuraSaveDialogPath(element.DirectoryLocation, settings);

        var curaPath     = GetCuraExecutableFilePath(settings) ?? throw new FileNotFoundException("Could not find cura executable.");
        var curaFileName = Path.GetFileNameWithoutExtension(curaPath);

        var p = Process.Start(new ProcessStartInfo
        {
            FileName  = curaPath,
            Arguments = $"\"{string.Join("\" \"", modelsToAdd)}\"",
        });

        p.WaitForInputIdle();

        if (curaFileName == "Cura")
        {
            SetName4x();
        }
        else
        {
            SetName5x();
        }

        void SetName4x()
        {
            if (TryFindChild(AutomationElement.RootElement, CheckWindow, TimeSpan.FromMinutes(5), out var curaWindow) &&
                TryFindChild(curaWindow, CheckEditNameButton, TimeSpan.FromSeconds(30), out var editNameButton) &&
                editNameButton.TryGetCurrentPattern(InvokePattern.Pattern, out var objInvokePattern) && objInvokePattern is InvokePattern invokePattern)
            {
                invokePattern.Invoke();
                SendKeys.SendWait($"{printName}{{ENTER}}");
            }

            bool CheckWindow(TreeWalker treeWalker, AutomationElement e)
            {
                return(e.Current.ProcessId == p.Id &&
                       e.Current.Name?.Contains("Ultimaker Cura") == true);
            }

            bool CheckEditNameButton(TreeWalker treeWalker, AutomationElement e)
            {
                return(ReferenceEquals(e.Current.ControlType, ControlType.Button) &&
                       string.IsNullOrEmpty(e.Current.Name) &&
                       !e.Current.IsOffscreen &&
                       ReferenceEquals(treeWalker.GetNextSibling(e)?.Current.ControlType, ControlType.Edit));
            }
        }

        void SetName5x()
        {
            if (TryFindChild(AutomationElement.RootElement, CheckWindow, TimeSpan.FromMinutes(5), out var curaWindow) &&
                TryFindChild(curaWindow, CheckEditNameButton, TimeSpan.FromSeconds(30), out var editNameButton) &&
                editNameButton.TryGetCurrentPattern(ValuePattern.Pattern, out var objValuePattern) && objValuePattern is ValuePattern valuePattern)
            {
                valuePattern.SetValue(printName);
            }

            bool CheckWindow(TreeWalker treeWalker, AutomationElement e)
            {
                return(e.Current.ProcessId == p.Id &&
                       e.Current.Name?.Contains("Ultimaker Cura") == true);
            }

            bool CheckEditNameButton(TreeWalker treeWalker, AutomationElement e)
            {
                return(ReferenceEquals(e.Current.ControlType, ControlType.Edit) && !e.Current.IsOffscreen);
            }
        }
    }