Beispiel #1
0
        public static DomainFile CreateEmpty(DirectoryInfo directory, DomainDomain datasource, ISerializer <TData> serializer, Func <FileInfo, bool> pathOk, INodeFactory nodeFactory, Func <IDomainUsage <ConversationNode, TransitionNoduleUIInfo> > domainUsage, Func <IDynamicEnumParameter, object, DynamicEnumParameter.Source> getDocumentSource, UpToDateFile.BackEnd backEnd, DirectoryInfo origin)
        {
            //Create a stream under an available filename
            FileInfo path = null;

            for (int i = 0; path == null; i++)
            {
                path = new FileInfo(directory.FullName + Path.DirectorySeparatorChar + "New Domain " + i + ".dom");
                if (!pathOk(path))
                {
                    path = null;
                }
            }

            using (MemoryStream m = new MemoryStream())
            {
                using (var stream = Util.LoadFileStream(path, FileMode.CreateNew, FileAccess.Write))
                {
                    serializer.Write(SerializationUtils.MakeDomainData(Enumerable.Empty <ConversationNode>(), new ConversationEditorData()), m);
                    m.CopyTo(stream);
                }

                var result = new DomainFile(new List <GraphAndUI <NodeUIData> >(), new List <NodeGroup>(), m, Id <FileInProject> .New(), DocumentPath.FromPath(path, origin), new ReadOnlyCollection <LoadError>(new LoadError[0]), datasource, serializer, nodeFactory, domainUsage, getDocumentSource, new List <IAutoCompletePattern>(), backEnd);
                result.m_file.Save(); //Make sure the file starts life as a valid xml document
                return(result);
            }
        }
Beispiel #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <param name="data"></param>
        /// <param name="conversationNodeFactory"></param>
        /// <param name="domainNodeFactory"></param>
        /// <param name="initialContent">Represents the current contents of the file. Reference is not held. A copy is made.</param>
        /// <param name="projectFile"></param>
        /// <param name="serializer"></param>
        /// <param name="conversationSerializer"></param>
        /// <param name="conversationSerializerDeserializerFactory"></param>
        /// <param name="domainSerializer"></param>
        /// <param name="pluginsConfig"></param>
        /// <param name="audioCustomization"></param>
        public Project(ILocalizationContext context, TData data, INodeFactory conversationNodeFactory, INodeFactory domainNodeFactory, MemoryStream initialData, FileInfo projectFile, ISerializer <TData> serializer, ISerializer <TConversationData> conversationSerializer, ConversationSerializerDeserializerFactory conversationSerializerDeserializerFactory, ISerializer <TDomainData> domainSerializer, PluginsConfig pluginsConfig, Func <IAudioProviderCustomization> audioCustomization, UpToDateFile.BackEnd backend)
        {
            AssertUniqueFileIds(data);
            AssertUniqueLocalizationSetNames(data);
            AssertUniqueFilePaths(data);

            m_upToDateFileBackend = backend;
            Action <Stream> saveTo = stream =>
            {
                Write(GetFilePath, Conversations.Select(x => (x.Id)), LocalizationFiles.Select(x => (x.Id)),
                      DomainFiles.Select(x => (x.Id)), AudioFiles.Select(x => (x.Id)), Localizer.LocalizationSets, stream, m_serializer);
            };

            m_file = new SaveableFileNotUndoable(initialData, projectFile, saveTo, backend);
            ConversationNodeFactory         = conversationNodeFactory;
            DomainNodeFactory               = domainNodeFactory;
            m_serializer                    = serializer;
            ConversationSerializer          = conversationSerializer;
            m_conversationSerializerFactory = conversationSerializerDeserializerFactory;
            m_domainSerializer              = domainSerializer;

            m_filePaths = data.Conversations.Concat(data.Localizations).Concat(data.Domains).Concat(data.Audios).ToDictionary(f => f.Id, f => f.Path);

            IEnumerable <Id <FileInProject> > conversationIds = data.Conversations.Select(f => f.Id);
            IEnumerable <Id <FileInProject> > localizerIds    = data.Localizations.Select(f => f.Id);
            IEnumerable <Id <FileInProject> > domainIds       = data.Domains.Select(f => f.Id);
            IEnumerable <Id <FileInProject> > audioIds        = data.Audios.Select(f => f.Id);

            m_audioProvider = new AudioProvider(new FileInfo(projectFile.FullName), GetFilePath, s => CheckFolder(s, Origin), this, audioCustomization());
            using (m_audioProvider.SuppressUpdates())
            {
                {
                    m_audioProvider.AudioFiles.Load(audioIds);
                }

                {
                    //Dictionary<IDynamicEnumParameter, DynamicEnumParameter.Source> domainEnumSource = new Dictionary<IDynamicEnumParameter, DynamicEnumParameter.Source>();
                    Func <IDynamicEnumParameter, object, DynamicEnumParameter.Source> getDomainEnumSource = (k, o) =>
                    {
                        return(null); //Nothing should need a source (but the system will ask anyway)
                                      //if (!domainEnumSource.ContainsKey(k))
                                      //domainEnumSource[k] = new DynamicEnumParameter.Source();
                                      //return domainEnumSource[k];
                    };

                    m_domainDataSource = new DomainDomain(pluginsConfig);
                    Func <IEnumerable <Tuple <Id <FileInProject>, DocumentPath> >, IEnumerable <IDomainFile> > loader = paths =>
                    {
                        var result = DomainFile.Load(paths, m_domainDataSource, DomainSerializerDeserializer.Make, DomainNodeFactory, () => DomainUsage, getDomainEnumSource, backend).Evaluate();
                        result.ForAll(a => a.ConversationDomainModified += ConversationDatasourceModified);
                        return(result);
                    };
                    Func <DirectoryInfo, DomainFile> makeEmpty = path => DomainFile.CreateEmpty(path, m_domainDataSource, m_domainSerializer, pathOk, DomainNodeFactory, () => DomainUsage, getDomainEnumSource, backend, Origin);
                    m_domainFiles = new ProjectElementList <IDomainFile>(GetFilePath, s => CheckFolder(s, Origin), loader, makeEmpty);
                    m_domainFiles.Load(domainIds);
                }
                m_conversationDataSource = new ConversationDataSource(m_domainFiles.Select(df => df.Data));

                if (m_conversationDataSource.DomainErrors.Any())
                {
                    MessageBox.Show(string.Join("\n", m_conversationDataSource.DomainErrors.Select(error => error.Message)));
                }

                {
                    m_localizer = new LocalizationEngine(GetFilePath, data.LocalizationSets, context, UsedLocalizations, ShouldContract, pathOk, s => CheckFolder(s, Origin), backend, Origin);
                    m_localizer.Localizers.Load(localizerIds);
                    context.CurrentLocalization.Value    = m_localizer.LocalizationSets.FirstOrDefault() ?? Project.TData.LocalizerSetData.Empty;
                    m_localizer.LocalizationSetsChanged += () => { m_file.Change(); };
                }

                {
                    GenerateAudio audio = (c) =>
                    {
                        return(m_audioProvider.Generate(new AudioGenerationParameters(c.File.File, this.File.File)));
                    };

                    //This can be called from multiple threads simultaneously and in arbitrary orders by design of
                    //ConversationDataSource and the underlying ConstantTypeSet and DynamicEnumParameter.Source
                    Func <IDynamicEnumParameter, object, DynamicEnumParameter.Source> getSource = (localEnum, newSourceID) =>
                    {
                        return(m_conversationDataSource.GetSource(localEnum.TypeId, newSourceID));
                    };

                    Func <IEnumerable <Tuple <Id <FileInProject>, DocumentPath> >, IEnumerable <IConversationFile> > loadConversations = files =>
                    {
                        ISerializerDeserializer <XmlGraphData <NodeUIData, ConversationEditorData> > conversationSerializerDeserializer = m_conversationSerializerFactory(m_conversationDataSource);
                        //                                                 _/          _/                           _/                         X        _/             X            _/
                        //return files.Select(file => ConversationFile.Load(file, ConversationNodeFactory, conversationSerializerDeserializer, audio, getSource, m_audioProvider, backend));
                        //TODO: AUDIO: This is ok as long as we're not using audio parameters at all
                        return(ParallelEnumerable.Select(files.AsParallel(), file => ConversationFile.Load(file.Item1, file.Item2, ConversationNodeFactory, conversationSerializerDeserializer, audio, getSource, m_audioProvider, backend)));
                    };
                    Func <DirectoryInfo, ConversationFile> makeEmpty = path => ConversationFile.CreateEmpty(path, this, ConversationNodeFactory, audio, getSource, m_audioProvider, backend, Origin);
                    m_conversations = new ProjectElementList <IConversationFile>(GetFilePath, s => CheckFolder(s, Origin), loadConversations, makeEmpty);
                    m_conversations.Load(conversationIds);
                }

                RefreshCallbacks(m_conversations, m_actionsOnRefreshCallbacksConversations);
                RefreshCallbacks(m_audioProvider.AudioFiles, m_actionsOnRefreshCallbacksAudios);
                RefreshCallbacks(m_localizer.Localizers, m_actionsOnRefreshCallbacksLocalizations);
                RefreshCallbacks(m_domainFiles, m_actionsOnRefreshCallbacksDomains);

                m_conversations.GotChanged            += GotChanged;
                m_audioProvider.AudioFiles.GotChanged += GotChanged;
                m_localizer.Localizers.GotChanged     += GotChanged;
                m_domainFiles.GotChanged += GotChanged;

                m_conversations.GotChanged            += () => RefreshCallbacks(m_conversations, m_actionsOnRefreshCallbacksConversations);
                m_audioProvider.AudioFiles.GotChanged += () => RefreshCallbacks(m_audioProvider.AudioFiles, m_actionsOnRefreshCallbacksAudios);
                m_localizer.Localizers.GotChanged     += () => RefreshCallbacks(m_localizer.Localizers, m_actionsOnRefreshCallbacksLocalizations);
                m_domainFiles.GotChanged += () => RefreshCallbacks(m_domainFiles, m_actionsOnRefreshCallbacksDomains);


                m_domainFiles.GotChanged += ConversationDatasourceModified;
                Action <IDomainFile> MaybeConversationDatasourceModified = file => { if (!file.File.Changed())
                                                                                     {
                                                                                         ConversationDatasourceModified();
                                                                                     }
                };
                m_domainFiles.Added    += argument => { argument.File.SaveStateChanged += () => MaybeConversationDatasourceModified(argument); };
                m_domainFiles.Reloaded += (_, argument) => { argument.File.SaveStateChanged += () => MaybeConversationDatasourceModified(argument); };
                m_domainFiles.ForAll(d => d.File.SaveStateChanged += () => MaybeConversationDatasourceModified(d));
                //m_domainFiles.Added += argument => { argument.File.SaveStateChanged += () => { if (!argument.File.Changed) ReloadDatasource(); }; };
                //m_domainFiles.Reloaded += (from, to) => { to.File.SaveStateChanged += () => { if (!to.File.Changed) ReloadDatasource(); }; };
                //m_domainFiles.ForAll(d => d.File.SaveStateChanged += () => { if (!d.File.Changed) ReloadDatasource(); });

                m_domainFiles.Added                += file => m_filePaths[file.Id] = DocumentPath.FromAbsolutePath(file.File.File.FullName, Origin);
                m_conversations.Added              += file => m_filePaths[file.Id] = DocumentPath.FromAbsolutePath(file.File.File.FullName, Origin);
                m_audioProvider.AudioFiles.Added   += file => m_filePaths[file.Id] = DocumentPath.FromAbsolutePath(file.File.File.FullName, Origin);
                m_localizer.Localizers.Added       += file => m_filePaths[file.Id] = DocumentPath.FromAbsolutePath(file.File.File.FullName, Origin);
                m_domainFiles.Removed              += file => m_filePaths.Remove(file.Id);
                m_conversations.Removed            += file => m_filePaths.Remove(file.Id);
                m_audioProvider.AudioFiles.Removed += file => m_filePaths.Remove(file.Id);
                m_localizer.Localizers.Removed     += file => m_filePaths.Remove(file.Id);
                //Files being moved is setup in RefreshCallbacks()

                DomainUsage = new DomainUsage(this);

                m_audioProvider.UpdateUsage();
            }
        }
Beispiel #3
0
        internal static IEnumerable <IDomainFile> Load(IEnumerable <Tuple <Id <FileInProject>, DocumentPath> > paths, DomainDomain source, Func <DomainDomain, DomainSerializerDeserializer> serializerdeserializer, INodeFactory nodeFactory, Func <IDomainUsage <ConversationNode, TransitionNoduleUIInfo> > domainUsage, Func <IDynamicEnumParameter, object, DynamicEnumParameter.Source> getDocumentSource, UpToDateFile.BackEnd backend)
        {
            var streamsAndPaths = paths.Select((x) =>
            {
                var fileId        = x.Item1;
                DocumentPath path = x.Item2;
                try
                {
                    using (var stream = Util.LoadFileStream(path.FileInfo, FileMode.Open, FileAccess.Read))
                    {
                        return((Either <Tuple <MemoryStream, Id <FileInProject>, DocumentPath>, MissingDomainFile>)Tuple.Create(StreamUtil.Copy(stream), fileId, path));
                    }
                }
                catch (MyFileLoadException e)
                {
                    Console.Out.WriteLine(e.Message);
                    Console.Out.WriteLine(e.StackTrace);
                    Console.Out.WriteLine(e.InnerException.Message);
                    Console.Out.WriteLine(e.InnerException.StackTrace);
                    if (path.Exists)
                    {
                        MessageBox.Show("File: " + path.AbsolutePath + " could not be accessed");
                    }
                    else
                    {
                        MessageBox.Show("File: " + path.AbsolutePath + " does not exist");
                    }

                    MissingDomainFile temp = null;
                    try
                    {
                        temp = new MissingDomainFile(fileId, path);
                        Either <Tuple <MemoryStream, Id <FileInProject>, DocumentPath>, MissingDomainFile> result = temp;
                        return(result);
                    }
                    catch
                    {
                        temp?.Dispose();
                        throw;
                    }
                }
            }).Evaluate();

            var validStreamsAndPaths = Either.Split(streamsAndPaths).Item1; //TODO: Use this in the below cases where we currently use streamsAndPaths
            IReadOnlyCollection <Guid> nonUniqueGuids = serializerdeserializer(source).CheckUniqueIds(validStreamsAndPaths.Select(x => x.Item1));

            if (nonUniqueGuids.Any())
            {
                //TODO: Provide feedback to the user as to why these failed to load.
                //TODO: Unit test this
                return(streamsAndPaths.Select(x => x.Transformed(a => new MissingDomainFile(a.Item2, a.Item3), a => a)));
            }

            //We make the, hopefully, valid assumption here that the deserializers for the various concepts within a domain file have the same version requirements.
            Dictionary <DocumentPath, DeserializerVersionMismatchException> failedToParseFiles = new Dictionary <DocumentPath, DeserializerVersionMismatchException>();

            foreach (var sp in streamsAndPaths)
            {
                sp.Do(stream =>
                {
                    try
                    {
                        var categoryData = serializerdeserializer(source).CategoriesDeserializer.Read(stream.Item1);
                        DomainFile.AddToData(categoryData.Nodes.Select(n => n.GraphData), source);
                    }
                    catch (DeserializerVersionMismatchException e)
                    {
                        failedToParseFiles[stream.Item3] = e;
                    }
                }, a => { });
            }
            foreach (var sp in streamsAndPaths)
            {
                sp.Do(stream =>
                {
                    try
                    {
                        var typeData = serializerdeserializer(source).TypesDeserializer.Read(stream.Item1);
                        DomainFile.AddToData(typeData.Nodes.Select(n => n.GraphData), source);
                    }
                    catch (DeserializerVersionMismatchException e)
                    {
                        failedToParseFiles[stream.Item3] = e;
                    }
                }, a => { });
            }
            foreach (var sp in streamsAndPaths)
            {
                sp.Do(stream =>
                {
                    try
                    {
                        var connectorData = serializerdeserializer(source).ConnectorsDeserializer.Read(stream.Item1);
                        DomainFile.AddToData(connectorData.Nodes.Select(n => n.GraphData), source);
                    }
                    catch (DeserializerVersionMismatchException e)
                    {
                        failedToParseFiles[stream.Item3] = e;
                    }
                }, a => { });
            }
            foreach (var sp in streamsAndPaths)
            {
                sp.Do(stream =>
                {
                    try
                    {
                        var nodeData = serializerdeserializer(source).NodesDeserializer.Read(stream.Item1);
                        DomainFile.AddToData(nodeData.Nodes.Select(n => n.GraphData), source);
                    }
                    catch (DeserializerVersionMismatchException e)
                    {
                        failedToParseFiles[stream.Item3] = e;
                    }
                }, a => { });
            }

            {
                var result = streamsAndPaths.Select(a => a.Transformed <IDomainFile>(stream =>
                {
                    try
                    {
                        var editorData = serializerdeserializer(source).EditorDataDeserializer.Read(stream.Item1);
                        DomainFile.AddToData(editorData.Nodes.Select(n => n.GraphData), source);
                        var allData = serializerdeserializer(source).EverythingDeserializer.Read(stream.Item1);

                        List <IAutoCompletePattern> autoCompletePatterns = new List <IAutoCompletePattern>();
                        var nodeData = serializerdeserializer(source).AutoCompleteSuggestionsDeserializer.Read(stream.Item1);
                        autoCompletePatterns.AddRange(AutoCompletePattern.Generate(nodeData, source));

                        return(new DomainFile(allData.Nodes.ToList(), editorData.EditorData.Groups.ToList(), stream.Item1, stream.Item2, stream.Item3, allData.Errors, source, serializerdeserializer(source).Serializer, nodeFactory, domainUsage, getDocumentSource, autoCompletePatterns, backend));
                    }
                    catch (DeserializerVersionMismatchException e)
                    {
                        failedToParseFiles[stream.Item3] = e;
                        return(new MissingDomainFile(stream.Item2, stream.Item3));
                    }
                }, b => b));

                if (failedToParseFiles.Any())
                {
                    //TODO: expose this to the user in a consistent way with other errors (missing files, duplicated or missing guids)
                    StringBuilder message = new StringBuilder("Failed to parse files:\n");
                    foreach (var kvp in failedToParseFiles)
                    {
                        message.Append("\n");
                        message.Append(kvp.Key.RelativePath);
                        message.Append(": ");
                        message.Append(kvp.Value.Message);
                    }
                    MessageBox.Show(message.ToString());
                }

                return(result);
            }
        }