Ejemplo n.º 1
0
        public static string FindAvailableName(string path, Func <string, bool> exists)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }

            if (exists == null)
            {
                throw new ArgumentNullException(nameof(exists));
            }

            var    extension    = Path.GetExtension(path);
            string baseFileName = null;
            int    tries        = 0;

            while (exists(path) && ++tries < 10000)
            {
                if (baseFileName == null)
                {
                    baseFileName = Path.ChangeExtension(path, null);
                }

                path = baseFileName + " (" + tries + ")" + (extension ?? "");
            }

            return(path);
        }
Ejemplo n.º 2
0
        private void ListBoxItem_ViewHtmlDocumentType_OnSelected(object p_sender, RoutedEventArgs p_e)
        {
            if (singleton.DocumentClass is JsonTranslator translatorJson)
            {
                translatorJson.Translate(Translator.FutureDocType.Html);
                Clipboard.SetText(Path.ChangeExtension(translatorJson.FilePath,
                                                       translatorJson.GetFutureDocType(translatorJson
                                                                                       .FutureDocumentType)));
                FilePath = translatorJson.FilePath;
            }

            else if (singleton.DocumentClass is XmlTranslator translatorXml)
            {
                translatorXml.Translate(Translator.FutureDocType.Html);
                Clipboard.SetText(translatorXml.FilePath);
                FilePath = translatorXml.FilePath;
            }

            else if (singleton.DocumentClass is HtmlTranslator translatorHtml)
            {
                translatorHtml.Publish(translatorHtml.FilePath);
                Clipboard.SetText(translatorHtml.FilePath);
                FilePath = translatorHtml.FilePath;
            }

            Clipboard.SetText(FilePath);

            SampleCodePages.Content = new SampleCodePage(FilePath);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Changes the extension of a path string.
        /// </summary>
        /// <param name="path">The path information to modify.</param>
        /// <param name="extension">
        /// The new extension (with or without a leading period). Specify <see langword="null"/> to
        /// remove an existing extension from <paramref name="path"/>.
        /// </param>
        /// <returns>
        /// A string containing the modified path information.
        /// </returns>
        public static string ChangeExtension(string path, string extension)
        {
#if PORTABLE
            throw Portable.NotImplementedException;
#else
            return(BclPath.ChangeExtension(path, extension));
#endif
        }
Ejemplo n.º 4
0
    /// <summary>
    /// Changes the extension of a path string.
    /// </summary>
    /// <param name="path">The path information to modify.</param>
    /// <param name="extension">
    /// The new extension (with or without a leading period). Specify <see langword="null"/> to 
    /// remove an existing extension from <paramref name="path"/>.
    /// </param>
    /// <returns>
    /// A string containing the modified path information. 
    /// </returns>
    public static string ChangeExtension(string path, string extension)
    {

      throw Portable.NotImplementedException;
#else
      return BclPath.ChangeExtension(path, extension);

    }
Ejemplo n.º 5
0
        public static string GetThumbnailName(string path, string thumbSuffix = "_t.jpg")
        {
            if (string.IsNullOrEmpty(path))
            {
                return(path);
            }

            return(Path.ChangeExtension(path, null) + thumbSuffix);
        }
Ejemplo n.º 6
0
        /** Load full path name .st file relative to root by prefix */
        public virtual CompiledTemplate LoadTemplateFile(string prefix, string fileName)
        {
            if (Path.IsPathRooted(fileName))
            {
                throw new ArgumentException();
            }

            //System.out.println("load "+fileName+" from "+root+" prefix="+prefix);
            string templateName = Path.ChangeExtension(fileName, null);
            Uri    f            = null;

            try
            {
                f = new Uri(Path.Combine(root.LocalPath, fileName));
            }
            catch (UriFormatException me)
            {
                ErrorManager.RuntimeError(null, 0, ErrorType.INVALID_TEMPLATE_NAME, me, Path.Combine(root.LocalPath, fileName));
                return(null);
            }

            ANTLRReaderStream fs = null;

            try
            {
                fs = new ANTLRReaderStream(new StreamReader(f.LocalPath, Encoding ?? Encoding.UTF8));
            }
            catch (IOException)
            {
                // doesn't exist; just return null to say not found
                return(null);
            }

            GroupLexer lexer = new GroupLexer(fs);

            fs.name = fileName;
            CommonTokenStream tokens = new CommonTokenStream(lexer);
            GroupParser       parser = new GroupParser(tokens);

            parser.Group = this;
            lexer.group  = this;
            try
            {
                parser.templateDef(prefix);
            }
            catch (RecognitionException re)
            {
                ErrorManager.GroupSyntaxError(ErrorType.SYNTAX_ERROR, Path.GetFileName(f.LocalPath), re, re.Message);
            }

            return(RawGetTemplate(templateName));
        }
Ejemplo n.º 7
0
        /** Load full path name .st file relative to root by prefix */
        public virtual CompiledTemplate LoadTemplateFile(string prefix, string unqualifiedFileName)
        {
            if (Path.IsPathRooted(unqualifiedFileName))
            {
                throw new ArgumentException();
            }

            if (Verbose)
            {
                Console.WriteLine("loadTemplateFile({0}) in groupdir from {1} prefix={2}", unqualifiedFileName, root, prefix);
            }

            string templateName = Path.ChangeExtension(unqualifiedFileName, null);
            Uri    f;

            try
            {
                f = new Uri(root.LocalPath + prefix + unqualifiedFileName);
            }
            catch (UriFormatException me)
            {
                ErrorManager.RuntimeError(null, ErrorType.INVALID_TEMPLATE_NAME, me, Path.Combine(root.LocalPath, unqualifiedFileName));
                return(null);
            }

            ANTLRReaderStream fs = null;

            try
            {
                fs      = new ANTLRReaderStream(new StreamReader(File.OpenRead(f.LocalPath), Encoding));
                fs.name = unqualifiedFileName;
            }
            catch (IOException)
            {
                if (Verbose)
                {
                    Console.WriteLine("{0}/{1} doesn't exist", root, unqualifiedFileName);
                }

                //errMgr.IOError(null, ErrorType.NO_SUCH_TEMPLATE, ioe, unqualifiedFileName);
                return(null);
            }

            return(LoadTemplateFile(prefix, unqualifiedFileName, fs));
        }
Ejemplo n.º 8
0
        } //LoadWav

        void CreateFft()
        {
            if (wavFileName != null)
            {
                saveDialog.FileName = Path.ChangeExtension(wavFileName, DefinitionSet.outputFileType);
            }
            if (saveDialog.ShowDialog() != true)
            {
                return;
            }
            this.result = Main.Processor.Perform(wave.LeftChannel, 2 << (int)this.sliderSize.Value, (int)this.sliderShift.Value);
            this.canvasFrequency.SetData(Main.Processor.GetAmplitude(result), System.Windows.Media.Brushes.Navy, true);
            this.canvasPhase.SetData(Main.Processor.GetPhase(result), System.Windows.Media.Brushes.DarkCyan, true);
            var fileContent = Main.Formatter.Format(result);

            System.IO.File.WriteAllLines(saveDialog.FileName, fileContent);
            this.footer.Text = DefinitionSet.formatFileNames(wavFileName, saveDialog.FileName);
        } //CreateFft
        public void RunWithArguments(Document doc, NameValueMap map)
        {
            // write diagnostics data
            LogInputData(doc, map);

            var pathName = doc.FullFileName;

            LogTrace("Processing " + pathName);

            string[] outputFileName = { "", "ResultSmall", "ResultLarge" };

            try
            {
                var documentType = doc.DocumentType;
                var iRuns        = 1;
                if (documentType == DocumentTypeEnum.kPartDocumentObject)
                {
                    iRuns = 2;
                }
                for (int iRun = 1; iRun <= iRuns; iRun++)
                {
                    // load processing parameters
                    string paramsJson = GetParametersToChange(map, iRun);

                    // update parameters in the doc
                    // start HeartBeat around ChangeParameters, it could be a long operation
                    using (new HeartBeat())
                    {
                        ChangeParameters(doc, paramsJson);
                    }

                    var docDir = Path.GetDirectoryName(doc.FullFileName);

                    if (documentType == DocumentTypeEnum.kPartDocumentObject)
                    {
                        PartDocument part           = (PartDocument)doc;
                        double       mass           = part.ComponentDefinition.MassProperties.Mass;
                        string       imageParamName = "ImageLight";

                        // check the mass of the document and download proper image
                        if (mass > 300.0)
                        {
                            imageParamName = "ImageHeavy";
                        }

                        // get Image from the OnDemand parameter
                        OnDemand.HttpOperation(imageParamName, "", null, "", $"file://{outputFileName[iRun]}.png");
                    }

                    // generate outputs
                    if (documentType == DocumentTypeEnum.kPartDocumentObject)
                    {
                        var fileName = Path.Combine(docDir, $"{outputFileName[iRun]}.ipt"); // the name must be in sync with OutputIpt localName in Activity
                        LogTrace("Saving " + fileName);
                        // start HeartBeat around Save, it could be a long operation
                        using (new HeartBeat())
                        {
                            doc.SaveAs(fileName, false);
                        }
                        LogTrace("Saved as " + fileName);

                        // save an image
                        SaveImageFromPart(Path.Combine(docDir, $"{outputFileName[iRun]}.bmp"), doc as PartDocument);
                    }
                    else // Assembly. That's already validated in ChangeParameters
                    {
                        //Generate drawing document with assembly
                        var idwPath = Path.ChangeExtension(Path.Combine(docDir, doc.DisplayName), "idw");
                        LogTrace($"Generate drawing document");
                        SaveAsIDW(idwPath, doc);

                        // cannot ZIP opened assembly, so close it
                        // start HeartBeat around Save, it could be a long operation
                        using (new HeartBeat())
                        {
                            doc.Save2(true);
                        }
                        doc.Close(true);

                        LogTrace("Zipping up updated Assembly.");

                        // assembly lives in own folder under WorkingDir. Get the WorkingDir
                        var workingDir = Path.GetDirectoryName(docDir);
                        var fileName   = Path.Combine(workingDir, "Result.zip"); // the name must be in sync with OutputIam localName in Activity

                        if (File.Exists(fileName))
                        {
                            File.Delete(fileName);
                        }

                        // start HeartBeat around ZipFile, it could be a long operation
                        using (new HeartBeat())
                        {
                            ZipFile.CreateFromDirectory(Path.GetDirectoryName(pathName), fileName, CompressionLevel.Fastest, false);
                        }

                        LogTrace($"Saved as {fileName}");
                    }
                }
            }
            catch (Exception e)
            {
                LogError("Processing failed. " + e.ToString());
            }
        }
Ejemplo n.º 10
0
        private async Task LoadAsync(string fileName, bool recreateModelAndMaterialFiles)
        {
            Debug.Assert(_tempDirectoryHelper == null);
            Debug.Assert(_monoGameContent == null);
            Debug.Assert(ModelNode == null);
            Debug.Assert(Model == null);
            Debug.Assert(_assimpScene == null);
            Debug.Assert(State == ModelDocumentState.Loading);

            string extension = Path.GetExtension(fileName);

            IsXnb = string.Compare(extension, ".XNB", StringComparison.OrdinalIgnoreCase) == 0;

            // ----- Build XNB
            string directoryName;

            try
            {
                if (IsXnb)
                {
                    // Get the folder that contains the XNB.
                    directoryName = Path.GetDirectoryName(fileName);
                }
                else if (GameContentBuilder.IsSupportedModelFileExtension(extension))
                {
                    // Build the XNB and get the output folder.
                    var buildResult = await Task.Run(() => BuildXnb(Editor.Services, Editor.ApplicationName, fileName, UseDigitalRuneGraphics, recreateModelAndMaterialFiles));

                    directoryName        = buildResult.Item1;
                    _tempDirectoryHelper = buildResult.Item2;
                }
                else
                {
                    throw new EditorException(Invariant($"Unsupported 3D model file format (file extension \"{extension}\")."));
                }
            }
            catch (Exception)
            {
                if (IsDisposed)
                {
                    // Document was closed during loading.
                    Reset();
                    return;
                }

                State = ModelDocumentState.Error;
                UpdateProperties();
                UpdateOutline();

                // The GameContentBuilder logs to the output service.
                _outputService.Show();

                throw;
            }

            if (IsDisposed)
            {
                // Document was closed during loading.
                Reset();
                return;
            }

            Debug.Assert(directoryName != null);

            // ----- Load XNB
            try
            {
                // Get asset name for use with ContentManager. XNBs and unprocessed models
                // use different folder hierarchies.
                string assetFileName;
                if (IsXnb)
                {
                    // Use absolute path.
                    assetFileName = fileName;
                }
                else
                {
                    // The asset is built relative to the root folder (e.g. "C:\"). The folder
                    // hierarchy (from root to asset) is rebuilt in the temporary output folder.

                    // Make file name relative to root.
                    assetFileName = DRPath.GetRelativePath(Path.GetPathRoot(fileName), fileName);

                    // Get absolute file name relative to temporary output folder.
                    assetFileName = Path.Combine(directoryName, assetFileName);

                    // Change extension. .fbx --> .xnb
                    assetFileName = Path.ChangeExtension(assetFileName, "xnb");
                }

                _monoGameContent = await Task.Run(() => _monoGameService.LoadXnb(directoryName, assetFileName, cacheResult: false));

                if (_monoGameContent.Asset is ModelNode)
                {
                    ModelNode = (ModelNode)_monoGameContent.Asset;
                    UseDigitalRuneGraphics = true;
                    HasAnimations          = ModelNode.GetDescendants()
                                             .OfType <MeshNode>()
                                             .FirstOrDefault()?
                                             .Mesh?
                                             .Animations?
                                             .Count > 0;
                }
                else if (_monoGameContent.Asset is Model)
                {
                    Model = (Model)_monoGameContent.Asset;
                    UseDigitalRuneGraphics = false;
                    HasAnimations          = false;

                    // Enable default lighting.
                    var effects = Model.Meshes
                                  .SelectMany(m => m.Effects)
                                  .OfType <IEffectLights>();
                    foreach (var effect in effects)
                    {
                        effect.EnableDefaultLighting();
                    }
                }
                else
                {
                    throw new EditorException("XNB does not contain ModelNode or Model.");
                }
            }
            catch (Exception exception)
            {
                Reset();

                if (IsDisposed)
                {
                    return;
                }

                State = ModelDocumentState.Error;
                Logger.Error(exception, "XNB could not be loaded.");

                // Let LoadAsync return and fail, then show message box.
                WindowsHelper.BeginInvokeOnUI(() =>
                {
                    var message = Invariant($"XNB could not be loaded:\n\n\"{exception.Message}\"");
                    MessageBox.Show(message, Editor.ApplicationName, MessageBoxButton.OK, MessageBoxImage.Error);
                });

                throw;
            }

            if (IsDisposed)
            {
                // Document was closed during loading.
                Reset();
                return;
            }

            // ----- Load Assimp scene
            try
            {
                if (!IsXnb)
                {
                    _assimpScene = await Task.Run(() => LoadAssimp(fileName));
                }
            }
            catch (Exception exception)
            {
                Logger.Warn(exception, "Assimp could not read model file.");
            }

            if (IsDisposed)
            {
                // Document was closed during loading.
                Reset();
                return;
            }

            State = ModelDocumentState.Loaded;

            // ----- Validate model
            ValidateModelNode();
            // TODO: Validate MonoGame Model.

            // If there are errors or warnings, show Output and Errors window.
            // (Drawback: This steals focus from the document.)
            //if (_errors.Count > 0)
            //{
            //    _outputService?.Show();
            //    _errorService?.Show();
            //}

            // ----- Update outline and properties
            UpdateOutline();
            UpdateProperties();
        }
Ejemplo n.º 11
0
 public static string SetExtension(this string π, string ext) => SysPath.ChangeExtension(π, ext);
        public void RunWithArguments(Document doc, NameValueMap map)
        {
            // write diagnostics data
            LogInputData(doc, map);

            var pathName = doc.FullFileName;

            LogTrace("Processing " + pathName);

            try
            {
                // load processing parameters
                string paramsJson = GetParametersToChange(map);

                // update parameters in the doc
                // start HeartBeat around ChangeParameters, it could be a long operation
                using (new HeartBeat())
                {
                    ChangeParameters(doc, paramsJson);
                }

                // generate outputs
                var docDir = Path.GetDirectoryName(doc.FullFileName);

                var documentType = doc.DocumentType;
                if (documentType == DocumentTypeEnum.kPartDocumentObject)
                {
                    var fileName = Path.Combine(docDir, "Result.ipt"); // the name must be in sync with OutputIpt localName in Activity
                    LogTrace("Saving " + fileName);
                    // start HeartBeat around Save, it could be a long operation
                    using (new HeartBeat())
                    {
                        doc.SaveAs(fileName, false);
                    }
                    LogTrace("Saved as " + fileName);

                    // save an image
                    SaveImageFromPart(Path.Combine(docDir, "Result.bmp"), doc as PartDocument);
                }
                else // Assembly. That's already validated in ChangeParameters
                {
                    //Generate drawing document with assembly
                    var idwPath = Path.ChangeExtension(Path.Combine(docDir, doc.DisplayName), "idw");
                    LogTrace($"Generate drawing document");
                    SaveAsIDW(idwPath, doc);

                    // cannot ZIP opened assembly, so close it
                    // start HeartBeat around Save, it could be a long operation
                    using (new HeartBeat())
                    {
                        doc.Save2(true);
                    }
                    doc.Close(true);

                    LogTrace("Zipping up updated Assembly.");

                    // assembly lives in own folder under WorkingDir. Get the WorkingDir
                    var workingDir = Path.GetDirectoryName(docDir);
                    var fileName   = Path.Combine(workingDir, "Result.zip"); // the name must be in sync with OutputIam localName in Activity

                    if (File.Exists(fileName))
                    {
                        File.Delete(fileName);
                    }

                    // start HeartBeat around ZipFile, it could be a long operation
                    using (new HeartBeat())
                    {
                        ZipFile.CreateFromDirectory(Path.GetDirectoryName(pathName), fileName, CompressionLevel.Fastest, false);
                    }

                    LogTrace($"Saved as {fileName}");
                }
            }
            catch (Exception e)
            {
                LogError("Processing failed. " + e.ToString());
            }
        }
Ejemplo n.º 13
0
 public static string ChangeExtension(string path, string extension) =>
 MSIOP.ChangeExtension(path, extension);