Exemplo n.º 1
0
 /// <param name="type">The UIViewType</param>
 /// <param name="v">The IView</param>
 /// <param name="vm">The IViewModel. Might be null because the 2fa view shares the same viewmodel as the login dialog, so it's
 /// set manually in the view outside of this</param>
 public UIPair(UIViewType type, ExportLifetimeContext<IView> v, [AllowNull]ExportLifetimeContext<IViewModel> vm)
 {
     viewType = type;
     view = v;
     viewModel = vm;
     handlers = new CompositeDisposable();
 }
Exemplo n.º 2
0
        void LoadAudioInfo()
        {
            Contract.Ensures(AudioInfo != null);

            using (FileStream fileStream = FileInfo.OpenRead())
            {
                // Try each info decoder that supports this file extension:
                foreach (ExportFactory <IAudioInfoDecoder> decoderFactory in
                         ExtensionProvider.GetFactories <IAudioInfoDecoder>("Extension", FileInfo.Extension))
                {
                    try
                    {
                        using (ExportLifetimeContext <IAudioInfoDecoder> lifetimeContext = decoderFactory.CreateExport())
                            AudioInfo = lifetimeContext.Value.ReadAudioInfo(fileStream);
                        return;
                    }
                    catch (UnsupportedAudioException)
                    {
                        // If a decoder wasn't supported, rewind the stream and try another:
                        fileStream.Position = 0;
                    }
                }
            }

            throw new UnsupportedAudioException(Resources.AudioFileDecodeError);
        }
        public void Initialize(Stream stream, AudioInfo audioInfo, MetadataDictionary metadata, SettingsDictionary settings)
        {
            _encoder = new NativeVorbisEncoder();
            _output  = stream;

            // Load the external gain filter:
            ExportFactory <ISampleFilter> sampleFilterFactory =
                ExtensionProvider.GetFactories <ISampleFilter>("Name", "ReplayGain").SingleOrDefault();

            if (sampleFilterFactory == null)
            {
                throw new ExtensionInitializationException(Resources.SampleEncoderReplayGainFilterError);
            }
            _replayGainFilterLifetime = sampleFilterFactory.CreateExport();
            _replayGainFilterLifetime.Value.Initialize(metadata, settings);

            _oggStream = IntializeOggStream(settings);
            _buffer    = new byte[4096];

            if (!string.IsNullOrEmpty(settings["BitRate"]))
            {
                ConfigureEncoderForBitRate(settings, audioInfo, _encoder);
            }
            else
            {
                ConfigureEncoderForQuality(settings, audioInfo, _encoder);
            }

            WriteHeader(metadata, stream);
        }
Exemplo n.º 4
0
 /// <param name="type">The UIViewType</param>
 /// <param name="v">The IView</param>
 /// <param name="vm">The IViewModel. Might be null because the 2fa view shares the same viewmodel as the login dialog, so it's
 /// set manually in the view outside of this</param>
 public UIPair(UIViewType type, ExportLifetimeContext <IView> v, [AllowNull] ExportLifetimeContext <IViewModel> vm)
 {
     viewType  = type;
     view      = v;
     viewModel = vm;
     handlers  = new CompositeDisposable();
 }
Exemplo n.º 5
0
        /// <summary>
        /// Saves the metadata, using an available <see cref="IMetadataEncoder"/>. If no extensions are able to write
        /// to this file extension, an <see cref="UnsupportedAudioException"/>
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <exception cref="UnsupportedAudioException">
        /// No metadata encoders are able to save metadata in the required format.
        /// </exception>
        public void SaveMetadata(SettingsDictionary settings = null)
        {
            if (settings == null)
            {
                settings = new SettingsDictionary();
            }

            using (FileStream fileStream = FileInfo.Open(FileMode.Open, FileAccess.ReadWrite))
            {
                // Ensure the existing metadata has been loaded:
                if (_metadata == null)
                {
                    LoadMetadata(fileStream);
                    fileStream.Position = 0;
                }

                // Try each encoder that supports the file extension:
                foreach (ExportFactory <IMetadataEncoder> encoderFactory in
                         ExtensionProvider.GetFactories <IMetadataEncoder>("Extension", FileInfo.Extension))
                {
                    using (ExportLifetimeContext <IMetadataEncoder> lifetimeContext = encoderFactory.CreateExport())
                    {
                        IMetadataEncoder encoder = lifetimeContext.Value;
                        ValidateSettings(settings, encoder);
                        encoder.WriteMetadata(fileStream, Metadata, settings);

                        return;
                    }
                }
            }

            throw new UnsupportedAudioException(Resources.TaggedAudioFileUnsupportedError);
        }
Exemplo n.º 6
0
        void LoadMetadata(Stream stream)
        {
            Contract.Requires(stream != null);
            Contract.Requires(stream.CanRead);
            Contract.Requires(stream.CanSeek);
            Contract.Ensures(_metadata != null);

            // Try each decoder that supports this file extension:
            foreach (ExportFactory <IMetadataDecoder> decoderFactory in
                     ExtensionProvider.GetFactories <IMetadataDecoder>("Extension", FileInfo.Extension))
            {
                try
                {
                    using (ExportLifetimeContext <IMetadataDecoder> lifetimeContext = decoderFactory.CreateExport())
                        _metadata = lifetimeContext.Value.ReadMetadata(stream);
                    return;
                }
                catch (UnsupportedAudioException)
                {
                    // If a decoder wasn't supported, rewind the stream and try another:
                    stream.Position = 0;
                }
            }

            _metadata = new MetadataDictionary();
        }
Exemplo n.º 7
0
        public IObservable <LoadData> SetupUI(UIControllerFlow controllerFlow, [AllowNull] IConnection connection)
        {
            StopUI();

            var factory = TryGetService(typeof(IExportFactoryProvider)) as IExportFactoryProvider;

            currentUIFlow = factory.UIControllerFactory.CreateExport();
            var disposable = currentUIFlow;
            var ui         = currentUIFlow.Value;
            var creation   = ui.SelectFlow(controllerFlow);

            windowController = new UI.WindowController(creation);
            windowController.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
            windowController.Closed += StopUIFlowWhenWindowIsClosedByUser;
            creation.Subscribe(c => {}, () =>
            {
                windowController.Closed -= StopUIFlowWhenWindowIsClosedByUser;
                windowController.Close();
                if (currentUIFlow != disposable)
                {
                    StopUI(disposable);
                }
                else
                {
                    StopUI();
                }
            });
            ui.Start(connection);
            return(creation);
        }
            protected override async Task InitializeCoreAsync(CancellationToken cancellationToken)
            {
                _contextAccessor = await _workspaceProjectContextProvider.CreateProjectContextAsync(_project);

                if (_contextAccessor == null)
                {
                    return;
                }

                _activeWorkspaceProjectContextTracker.RegisterContext(_contextAccessor.ContextId);

                _disposables = new DisposableBag(CancellationToken.None);

                _applyChangesToWorkspaceContext = _applyChangesToWorkspaceContextFactory.CreateExport();
                _applyChangesToWorkspaceContext.Value.Initialize(_contextAccessor.Context);
                _disposables.AddDisposable(_applyChangesToWorkspaceContext);

                _evaluationProgressRegistration = _dataProgressTrackerService.RegisterForIntelliSense(_project, nameof(WorkspaceProjectContextHostInstance) + ".Evaluation");
                _disposables.AddDisposable(_evaluationProgressRegistration);

                _projectBuildProgressRegistration = _dataProgressTrackerService.RegisterForIntelliSense(_project, nameof(WorkspaceProjectContextHostInstance) + ".ProjectBuild");
                _disposables.AddDisposable(_projectBuildProgressRegistration);

                // We avoid suppressing version updates, so that progress tracker doesn't
                // think we're still "in progress" in the case of an empty change
                _disposables.AddDisposable(_projectSubscriptionService.ProjectRuleSource.SourceBlock.LinkToAsyncAction(
                                               target: e => OnProjectChangedAsync(e, evaluation: true),
                                               suppressVersionOnlyUpdates: false,
                                               ruleNames: _applyChangesToWorkspaceContext.Value.GetProjectEvaluationRules()));

                _disposables.AddDisposable(_projectSubscriptionService.ProjectBuildRuleSource.SourceBlock.LinkToAsyncAction(
                                               target: e => OnProjectChangedAsync(e, evaluation: false),
                                               suppressVersionOnlyUpdates: false,
                                               ruleNames: _applyChangesToWorkspaceContext.Value.GetProjectBuildRules()));
            }
Exemplo n.º 9
0
        public void Analyze(string analyzer, CancellationToken cancelToken, GroupToken groupToken = null)
        {
            Contract.Requires <ArgumentNullException>(!string.IsNullOrEmpty(analyzer));

            var groupTokenOwned = false;

            try
            {
                if (groupToken == null)
                {
                    groupToken      = new GroupToken(1);
                    groupTokenOwned = true;
                }

                ExportFactory <ISampleAnalyzer> analyzerFactory =
                    ExtensionProvider.GetFactories <ISampleAnalyzer>("Name", analyzer).SingleOrDefault();
                if (analyzerFactory == null)
                {
                    throw new ArgumentException(
                              string.Format(CultureInfo.CurrentCulture, Resources.AnalyzableAudioFileFactoryError, analyzer),
                              nameof(analyzer));
                }

                using (ExportLifetimeContext <ISampleAnalyzer> analyzerLifetime = analyzerFactory.CreateExport())
                    DoAnalyze(analyzerLifetime.Value, cancelToken, groupToken);
            }
            finally
            {
                if (groupTokenOwned)
                {
                    groupToken.Dispose();
                }
            }
        }
Exemplo n.º 10
0
        public void Initialize(Stream stream, AudioInfo audioInfo, MetadataDictionary metadata, SettingsDictionary settings)
        {
            Contract.Ensures(_encoder != null);

            // Load the external gain filter:
            ExportFactory <ISampleFilter> sampleFilterFactory =
                ExtensionProvider.GetFactories <ISampleFilter>("Name", "ReplayGain").SingleOrDefault();

            if (sampleFilterFactory == null)
            {
                throw new ExtensionInitializationException(Resources.SampleEncoderReplayGainFilterError);
            }
            _replayGainFilterLifetime = sampleFilterFactory.CreateExport();
            _replayGainFilterLifetime.Value.Initialize(metadata, settings);

            // Call the external ID3 encoder:
            ExportFactory <IMetadataEncoder> metadataEncoderFactory =
                ExtensionProvider.GetFactories <IMetadataEncoder>("Extension", EncoderInfo.FileExtension).Single();

            if (metadataEncoderFactory == null)
            {
                throw new ExtensionInitializationException(string.Format(CultureInfo.CurrentCulture,
                                                                         Resources.SampleEncoderMetadataEncoderError, EncoderInfo.FileExtension));
            }
            using (ExportLifetimeContext <IMetadataEncoder> metadataEncoderLifetime = metadataEncoderFactory.CreateExport())
                metadataEncoderLifetime.Value.WriteMetadata(stream, metadata, settings);

            _encoder = InitializeEncoder(audioInfo, stream);
            ConfigureEncoder(settings, _encoder);
            if (_encoder.InitializeParams() != 0)
            {
                throw new IOException(Resources.SampleEncoderFailedToInitialize);
            }
        }
Exemplo n.º 11
0
        private ILifetime <TPresenter, IPresenterMetadata> CreatePresenter <TPresenter>(string id) where TPresenter : IPresenter
        {
            ExportFactory <IPresenter, IPresenterMetadata> factory = FindPresenterFactory(id);

            ExportLifetimeContext <IPresenter> presenter = factory.CreateExport();

            return(new PresenterLifetime <TPresenter>(presenter, factory.Metadata));
        }
Exemplo n.º 12
0
        protected void SetupViewModel <VM>(IExportFactoryProvider factory, GitHub.Exports.UIViewType type)
            where VM : class, IViewModel
        {
            var v = Substitute.For <VM, INotifyPropertyChanged>();
            var e = new ExportLifetimeContext <IViewModel>(v, () => { });

            factory.GetViewModel(type).Returns(e);
        }
Exemplo n.º 13
0
        /// <param name="type">The UIViewType</param>
        /// <param name="v">The IView</param>
        /// <param name="vm">The IViewModel. Might be null because the 2fa view shares the same viewmodel as the login dialog, so it's
        /// set manually in the view outside of this</param>
        public UIPair(UIViewType type, ExportLifetimeContext <IView> v, ExportLifetimeContext <IViewModel> vm)
        {
            Guard.ArgumentNotNull(v, nameof(v));

            viewType  = type;
            view      = v;
            viewModel = vm;
            handlers  = new CompositeDisposable();
        }
            protected override async Task InitializeCoreAsync(CancellationToken cancellationToken)
            {
                _contextAccessor = await _workspaceProjectContextProvider.CreateProjectContextAsync(_project);

                if (_contextAccessor == null)
                {
                    return;
                }

                _activeWorkspaceProjectContextTracker.RegisterContext(_contextAccessor.ContextId);

                _applyChangesToWorkspaceContext = _applyChangesToWorkspaceContextFactory.CreateExport();
                _applyChangesToWorkspaceContext.Value.Initialize(_contextAccessor.Context);

                _evaluationProgressRegistration   = _dataProgressTrackerService.RegisterForIntelliSense(this, _project, nameof(WorkspaceProjectContextHostInstance) + ".Evaluation");
                _projectBuildProgressRegistration = _dataProgressTrackerService.RegisterForIntelliSense(this, _project, nameof(WorkspaceProjectContextHostInstance) + ".ProjectBuild");
                _sourceItemsProgressRegistration  = _dataProgressTrackerService.RegisterForIntelliSense(this, _project, nameof(WorkspaceProjectContextHostInstance) + ".SourceItems");

                _disposables = new DisposableBag
                {
                    _applyChangesToWorkspaceContext,
                    _evaluationProgressRegistration,
                    _projectBuildProgressRegistration,
                    _sourceItemsProgressRegistration,

                    ProjectDataSources.SyncLinkTo(
                        _activeConfiguredProjectProvider.ActiveConfiguredProjectBlock.SyncLinkOptions(),
                        _projectSubscriptionService.ProjectRuleSource.SourceBlock.SyncLinkOptions(GetProjectEvaluationOptions()),
                        target: DataflowBlockFactory.CreateActionBlock <IProjectVersionedValue <ValueTuple <ConfiguredProject, IProjectSubscriptionUpdate> > >(e =>
                                                                                                                                                               OnProjectChangedAsync(new ProjectChange(e), WorkspaceContextHandlerType.Evaluation),
                                                                                                                                                               _project.UnconfiguredProject,
                                                                                                                                                               ProjectFaultSeverity.LimitedFunctionality),
                        linkOptions: DataflowOption.PropagateCompletion,
                        cancellationToken: cancellationToken),

                    ProjectDataSources.SyncLinkTo(
                        _activeConfiguredProjectProvider.ActiveConfiguredProjectBlock.SyncLinkOptions(),
                        _projectSubscriptionService.ProjectBuildRuleSource.SourceBlock.SyncLinkOptions(GetProjectBuildOptions()),
                        _projectBuildSnapshotService.SourceBlock.SyncLinkOptions(),
                        target: DataflowBlockFactory.CreateActionBlock <IProjectVersionedValue <ValueTuple <ConfiguredProject, IProjectSubscriptionUpdate, IProjectBuildSnapshot> > >(e =>
                                                                                                                                                                                      OnProjectChangedAsync(new ProjectChange(e), WorkspaceContextHandlerType.ProjectBuild),
                                                                                                                                                                                      _project.UnconfiguredProject,
                                                                                                                                                                                      ProjectFaultSeverity.LimitedFunctionality),
                        linkOptions: DataflowOption.PropagateCompletion,
                        cancellationToken: cancellationToken),

                    ProjectDataSources.SyncLinkTo(
                        _activeConfiguredProjectProvider.ActiveConfiguredProjectBlock.SyncLinkOptions(),
                        _projectSubscriptionService.SourceItemsRuleSource.SourceBlock.SyncLinkOptions(),
                        target: DataflowBlockFactory.CreateActionBlock <IProjectVersionedValue <ValueTuple <ConfiguredProject, IProjectSubscriptionUpdate> > >(e =>
                                                                                                                                                               OnProjectChangedAsync(new ProjectChange(e), WorkspaceContextHandlerType.SourceItems),
                                                                                                                                                               _project.UnconfiguredProject,
                                                                                                                                                               ProjectFaultSeverity.LimitedFunctionality),
                        linkOptions: DataflowOption.PropagateCompletion,
                        cancellationToken: cancellationToken),
                };
            }
Exemplo n.º 15
0
 protected override void ProcessRecord()
 {
     foreach (ExportFactory <ISampleEncoder> encoderFactory in string.IsNullOrEmpty(Name)
         ? ExtensionProvider.GetFactories <ISampleEncoder>()
         : ExtensionProvider.GetFactories <ISampleEncoder>("Name", Name))
     {
         using (ExportLifetimeContext <ISampleEncoder> encoderLifetime = encoderFactory.CreateExport())
             WriteObject(encoderLifetime.Value.EncoderInfo);
     }
 }
Exemplo n.º 16
0
 protected override void ProcessRecord()
 {
     foreach (ExportFactory <IMetadataEncoder> factory in string.IsNullOrEmpty(Extension)
         ? ExtensionProvider.GetFactories <IMetadataEncoder>()
         : ExtensionProvider.GetFactories <IMetadataEncoder>("Extension", Extension))
     {
         using (ExportLifetimeContext <IMetadataEncoder> encoderLifetime = factory.CreateExport())
             WriteObject(encoderLifetime.Value.EncoderInfo);
     }
 }
Exemplo n.º 17
0
 /// <summary>
 /// Закрыть главное окно
 /// </summary>
 private void CloseMainViewModel()
 {
     if (_mainViewModel != null)
     {
         _mainViewModel.Dispose();
         _mainViewModel.Close();
         _mainViewModelExport.Dispose();
         _mainViewModel       = null;
         _mainViewModelExport = null;
     }
 }
Exemplo n.º 18
0
        public void StopUI()
        {
            if (!Initialized)
            {
                log.Error("ExportProvider is not initialized, cannot stop UI.");
                return;
            }

            StopUI(currentUIFlow);
            currentUIFlow = null;
        }
 /// <summary>
 /// Закрыть главное окно
 /// </summary>
 private void CloseMainViewModel()
 {
     if (_mainViewModel != null)
     {
         _mainViewModel.Dispose();
         _mainViewModel.Close();
         _mainViewModelExport.Dispose();
         _mainViewModel = null;
         _mainViewModelExport = null;
     }
 }
Exemplo n.º 20
0
        protected void SetupView <VM>(IExportFactoryProvider factory, GitHub.Exports.UIViewType type)
            where VM : class, IViewModel
        {
            var view      = Substitute.For <IView, IViewFor <VM> >();
            var viewModel = factory.GetViewModel(type).Value;

            view.ViewModel.Returns(viewModel);

            var e = new ExportLifetimeContext <IView>(view, () => { });

            factory.GetView(type).Returns(e);
        }
Exemplo n.º 21
0
        void GameChanged(Game x)
        {
            var previousContext = _activeGameContext;

            _activeGameContext = Factory.CreateGame(x);

            ActiveGame = x == null ? null : _activeGameContext.Value;

            if (previousContext != null)
            {
                previousContext.Dispose();
            }
        }
Exemplo n.º 22
0
        protected void SetupViewModel <VM>(IExportFactoryProvider factory, GitHub.Exports.UIViewType type)
            where VM : class, IViewModel
        {
            var v      = Substitute.For <IDialogViewModel, VM, INotifyPropertyChanged>();
            var done   = new ReplaySubject <Unit>();
            var cancel = ReactiveCommand.Create();

            v.Done.Returns(_ => done);
            v.Cancel.Returns(cancel);
            ((IHasCancel)v).Cancel.Returns(cancel.SelectUnit());

            var e = new ExportLifetimeContext <IViewModel>(v, () => { });

            factory.GetViewModel(type).Returns(e);
        }
        void Run()
        {
            var catalog   = new DirectoryCatalog(".");
            var container = new CompositionContainer(catalog);

            container.ComposeParts(this);

            ExportLifetimeContext <ICarContract> carA = carFactory.CreateExport();
            ExportLifetimeContext <ICarContract> carB = carFactory.CreateExport();

            carA.Value.DoSomething("carA");
            carB.Value.DoSomething("carB");

            carA.Dispose();
            carB.Dispose();
        }
Exemplo n.º 24
0
 static void StopUI(ExportLifetimeContext <IUIController> disposable)
 {
     try {
         if (disposable != null && disposable.Value != null)
         {
             if (!disposable.Value.IsStopped)
             {
                 disposable.Value.Stop();
             }
             disposable.Dispose();
         }
     }
     catch (Exception ex)
     {
         log.Error("Failed to dispose UI. {0}", ex);
     }
 }
Exemplo n.º 25
0
        private Lifetime<ICommand> CreateCommand(string id, out bool cache)
        {
            ExportFactory<ICommand, ICommandMetadata> factory =  _commands.Where(c => c.Metadata.Id == id)
                                                                          .SingleOrDefault();
            cache = false;
            if (factory == null)
                return null;

            ExportLifetimeContext<ICommand> context = factory.CreateExport();
            if (factory.Metadata.IsReusable)
            {
                cache = true;
                return new Lifetime<ICommand>(() => context.Value, (Action)null);
            }

            // Don't catch non-reusable commands, they are created for every request to FindCommand
            return new Lifetime<ICommand>(() => context.Value, () => context.Dispose());
        }
Exemplo n.º 26
0
        protected void SetupView <VM>(IExportFactoryProvider factory, GitHub.Exports.UIViewType type)
            where VM : class, IViewModel
        {
            IView view;

            //if (type == GitHub.Exports.UIViewType.PRList)
            //    view = Substitutes.For<IView, IViewFor<VM>, IHasCreationView, IHasDetailView>();
            //else
            view = Substitute.For <IView, IViewFor <VM> >();

            view.Done.Returns(new ReplaySubject <ViewWithData>());
            view.Cancel.Returns(new ReplaySubject <ViewWithData>());

            //(view as IHasDetailView)?.Open.Returns(new ReplaySubject<ViewWithData>());
            //(view as IHasCreationView)?.Create.Returns(new ReplaySubject<ViewWithData>());

            var e = new ExportLifetimeContext <IView>(view, () => { });

            factory.GetView(type).Returns(e);
        }
            protected override async Task InitializeCoreAsync(CancellationToken cancellationToken)
            {
                _context = await _workspaceProjectContextProvider.CreateProjectContextAsync(_project);

                if (_context == null)
                {
                    return;
                }

                _applyChangesToWorkspaceContext = _applyChangesToWorkspaceContextFactory.CreateExport();
                _applyChangesToWorkspaceContext.Value.Initialize(_context);

                _subscriptions = new DisposableBag(CancellationToken.None);
                _subscriptions.AddDisposable(_projectSubscriptionService.ProjectRuleSource.SourceBlock.LinkToAsyncAction(
                                                 target: e => OnProjectChangedAsync(e, evaluation: true),
                                                 ruleNames: _applyChangesToWorkspaceContext.Value.GetProjectEvaluationRules()));

                _subscriptions.AddDisposable(_projectSubscriptionService.ProjectBuildRuleSource.SourceBlock.LinkToAsyncAction(
                                                 target: e => OnProjectChangedAsync(e, evaluation: false),
                                                 ruleNames: _applyChangesToWorkspaceContext.Value.GetProjectBuildRules()));
            }
Exemplo n.º 28
0
        void Run()
        {
            // var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
            // var container = new CompositionContainer(catalog);

            var managerCatalog = new TypeCatalog(typeof(CarManager));
            var partCatalog    = new TypeCatalog(typeof(CarHost), typeof(CarMercedes), typeof(CarBMW), typeof(CarGarage));

            var scope = new CompositionScopeDefinition(
                managerCatalog,
                new[] { new CompositionScopeDefinition(partCatalog, null) });

            var container = new CompositionContainer(scope);

            var carManager = container.GetExportedValue <CarManager>();

            ExportLifetimeContext <CarHost> carHostContextA = carManager.CreateCarHost();

            Console.WriteLine("");

            ExportLifetimeContext <CarHost> carHostContextB = carManager.CreateCarHost();

            Console.WriteLine("");

            foreach (ICarContract carParts in carHostContextA.Value.CarParts)
            {
                Console.WriteLine(carParts.DoSomething());
            }
            carHostContextA.Dispose();
            Console.WriteLine("");

            foreach (ICarContract carParts in carHostContextB.Value.CarParts)
            {
                Console.WriteLine(carParts.DoSomething());
            }
            carHostContextB.Dispose();
            Console.WriteLine("");

            Console.ReadLine();
        }
Exemplo n.º 29
0
        public IObservable <LoadData> SetupUI(UIControllerFlow controllerFlow, [AllowNull] IConnection connection)
        {
            if (!Initialized)
            {
                log.Error("ExportProvider is not initialized, cannot setup UI.");
                return(Observable.Empty <LoadData>());
            }

            StopUI();

            var factory = GetService <IExportFactoryProvider>();

            currentUIFlow = factory.UIControllerFactory.CreateExport();
            var disposable = currentUIFlow;
            var ui         = currentUIFlow.Value;
            var creation   = ui.SelectFlow(controllerFlow);

            windowController = new UI.WindowController(creation);
            windowController.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
            windowController.Closed += StopUIFlowWhenWindowIsClosedByUser;
            creation.Subscribe(c => {}, () =>
            {
                windowController.Closed -= StopUIFlowWhenWindowIsClosedByUser;
                windowController.Close();
                if (currentUIFlow != disposable)
                {
                    StopUI(disposable);
                }
                else
                {
                    StopUI();
                }
            });
            ui.Start(connection);
            return(creation);
        }
Exemplo n.º 30
0
        void DoAnalyze(ISampleAnalyzer sampleAnalyzer, CancellationToken cancelToken, GroupToken groupToken)
        {
            Contract.Requires(sampleAnalyzer != null);
            Contract.Requires(groupToken != null);

            sampleAnalyzer.Initialize(AudioInfo, groupToken);

            using (FileStream fileStream = FileInfo.OpenRead())
            {
                // Try each decoder that supports this file extension:
                foreach (ExportFactory <ISampleDecoder> decoderFactory in
                         ExtensionProvider.GetFactories <ISampleDecoder>("Extension", FileInfo.Extension))
                {
                    try
                    {
                        using (ExportLifetimeContext <ISampleDecoder> decoderLifetime = decoderFactory.CreateExport())
                        {
                            ISampleDecoder sampleDecoder = decoderLifetime.Value;

                            sampleDecoder.Initialize(fileStream);
                            sampleDecoder.ReadWriteParallel(sampleAnalyzer, cancelToken,
                                                            sampleAnalyzer.ManuallyFreesSamples);
                            sampleAnalyzer.GetResult().CopyTo(Metadata);
                            return;
                        }
                    }
                    catch (UnsupportedAudioException)
                    {
                        // If a decoder wasn't supported, rewind the stream and try another:
                        fileStream.Position = 0;
                    }
                }
            }

            throw new UnsupportedAudioException(Resources.AudioFileDecodeError);
        }
Exemplo n.º 31
0
        void DoExport(ISampleEncoder encoder, Stream outputStream, SettingsDictionary settings, CancellationToken cancelToken)
        {
            Contract.Requires(encoder != null);
            Contract.Requires(outputStream != null);
            Contract.Requires(settings != null);

            encoder.Initialize(outputStream, AudioInfo, Metadata, settings);

            using (FileStream inputStream = FileInfo.OpenRead())
            {
                // Try each decoder that supports this file extension:
                foreach (ExportFactory <ISampleDecoder> decoderFactory in
                         ExtensionProvider.GetFactories <ISampleDecoder>("Extension", FileInfo.Extension))
                {
                    try
                    {
                        using (ExportLifetimeContext <ISampleDecoder> decoderLifetime = decoderFactory.CreateExport())
                        {
                            ISampleDecoder sampleDecoder = decoderLifetime.Value;

                            sampleDecoder.Initialize(inputStream);
                            sampleDecoder.ReadWriteParallel(encoder, cancelToken, encoder.ManuallyFreesSamples);

                            return;
                        }
                    }
                    catch (UnsupportedAudioException)
                    {
                        // If a decoder wasn't supported, rewind the stream and try another:
                        inputStream.Position = 0;
                    }
                }

                throw new UnsupportedAudioException(Resources.AudioFileDecodeError);
            }
        }
 /// <summary>
 /// Инициализировать главное окно
 /// </summary>
 private void InitializeMainViewModel()
 {
     _mainViewModelExport = _mainViewModelExportFactory.CreateExport();
     _mainViewModel = _mainViewModelExport.Value;
     _mainViewModel.Initialize();
 }
Exemplo n.º 33
0
 async Task DownloadFilesAsync(StatusRepo sr,
     IDictionary<KeyValuePair<string, Func<IAbsoluteFilePath, bool>>, ITransferStatus> transferStatuses,
     IAbsoluteDirectoryPath destinationPath, ExportLifetimeContext<IMirrorSelector> scoreMirrorSelector) {
     destinationPath.MakeSurePathExists();
     sr.Total = transferStatuses.Count;
     using (var multiMirrorFileDownloader = _createMultiMirrorFileDownloader(scoreMirrorSelector.Value))
     using (var multi = _createQueueDownloader(multiMirrorFileDownloader.Value)) {
         await multi.Value
             .DownloadAsync(CreateFileQueueSpec(transferStatuses, destinationPath), sr.CancelToken)
             .ConfigureAwait(false);
     }
 }
Exemplo n.º 34
0
 async Task DownloadFileAsync(string remoteFile, IAbsoluteDirectoryPath destinationPath,
     ExportLifetimeContext<IMirrorSelector> scoreMirrorSelector, CancellationToken token,
     Func<IAbsoluteFilePath, bool> confirmValidity, int zsyncHttpFallbackAfter) {
     destinationPath.MakeSurePathExists();
     using (var dl = _createMultiMirrorFileDownloader(scoreMirrorSelector.Value)) {
         await
             dl.Value.DownloadAsync(new MultiMirrorFileDownloadSpec(remoteFile,
                 destinationPath.GetChildFileWithName(remoteFile), confirmValidity) {
                     CancellationToken = token,
                     Progress = new TransferStatus(remoteFile) {ZsyncHttpFallbackAfter = zsyncHttpFallbackAfter}
                 },
                 token).ConfigureAwait(false);
     }
 }
Exemplo n.º 35
0
        public void Submit(SampleCollection samples)
        {
            Contract.Ensures(_buffer != null);

            if (_buffer == null)
            {
                _buffer = new int[samples.SampleCount * samples.Channels];
            }

            if (!samples.IsLast)
            {
                var index = 0;
                for (var sample = 0; sample < samples.SampleCount; sample++)
                {
                    for (var channel = 0; channel < samples.Channels; channel++)
                    {
                        _buffer[index++] = (int)Math.Round(samples[channel][sample] * _multiplier);
                    }
                }

                GCHandle handle = GCHandle.Alloc(_buffer, GCHandleType.Pinned);

                try
                {
                    var bufferList = new AudioBufferList
                    {
                        NumberBuffers = 1,
                        Buffers       = new AudioBuffer[1]
                    };
                    bufferList.Buffers[0].NumberChannels = (uint)samples.Channels;
                    bufferList.Buffers[0].DataByteSize   = (uint)(index * Marshal.SizeOf <int>());
                    bufferList.Buffers[0].Data           = handle.AddrOfPinnedObject();

                    ExtendedAudioFileStatus status = _audioFile.Write(bufferList, (uint)samples.SampleCount);
                    if (status != ExtendedAudioFileStatus.Ok)
                    {
                        throw new IOException(string.Format(CultureInfo.CurrentCulture,
                                                            Resources.SampleEncoderWriteError, status));
                    }
                }
                finally
                {
                    handle.Free();
                }
            }
            else
            {
                _audioFile.Dispose();

                // Call an external MP4 encoder for writing iTunes-compatible atoms:
                _stream.Position = 0;

                ExportFactory <IMetadataEncoder> metadataEncoderFactory =
                    ExtensionProvider.GetFactories <IMetadataEncoder>("Extension", EncoderInfo.FileExtension)
                    .SingleOrDefault();
                if (metadataEncoderFactory == null)
                {
                    throw new ExtensionInitializationException(string.Format(CultureInfo.CurrentCulture,
                                                                             Resources.SampleEncoderMetadataEncoderError, EncoderInfo.FileExtension));
                }

                using (ExportLifetimeContext <IMetadataEncoder> metadataEncoderLifetime = metadataEncoderFactory.CreateExport())
                    metadataEncoderLifetime.Value.WriteMetadata(_stream, _metadata, _settings);
            }
        }
Exemplo n.º 36
0
 async Task DownloadFileAsync(string remoteFile, IAbsoluteDirectoryPath destinationPath,
     ExportLifetimeContext<IMirrorSelector> scoreMirrorSelector, CancellationToken token) {
     destinationPath.MakeSurePathExists();
     using (var dl = _createMultiMirrorFileDownloader(scoreMirrorSelector.Value)) {
         await
             dl.Value.DownloadAsync(new MultiMirrorFileDownloadSpec(remoteFile,
                 destinationPath.GetChildFileWithName(remoteFile)) {CancellationToken = token}, token)
                 .ConfigureAwait(false);
     }
 }