Пример #1
0
        /// <summary>
        /// This method is called before a resource is loaded, if a valid resource handler
        /// is returned then this resource handler would serve the response of web request.
        /// </summary>
        public override IResourceHandler GetResourceHandler(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request)
        {
            try
            {
                DefaultResourceHandlerFactoryItem handlerItem;
#if DEBUG
                if (logger != null)
                {
                    logger.Log("Requested URL", request.Url);
                }
#endif
                if (!Handlers.TryGetValue(request.Url, out handlerItem))
                {
                    IResourceHandler handler = this.GetResourceHandler(request);
                    // TODO - verify bool param - determines whether or not the handler
                    // should be used once(true) or until manually unregistered
                    handlerItem = new DefaultResourceHandlerFactoryItem(handler, false);
                }

                return(handlerItem.Handler);
            }
            finally
            {
                request.Dispose();
            }
        }
        /// <summary>
        /// This method is called before a resource is loaded, if a valid resource handler
        /// is returned then this resource handler would serve the response of web request.
        /// </summary>
        public override IResourceHandler GetResourceHandler(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request)
        {
            try
            {
                DefaultResourceHandlerFactoryItem handlerItem;
#if DEBUG
                if (logger != null)
                {
                    logger.Log("Requested URL", request.Url);
                }
#endif
                // Create a handlerItem for the new resource,
                // if the resource has already been loaded don't load it again
                if (!Handlers.TryGetValue(request.Url, out handlerItem))
                {
                    IResourceHandler handler = this.GetResourceHandler(request);

                    // Make sure the handler is unregistered after use
                    // See: https://cefsharp.github.io/api/63.0.0/html/T_CefSharp_DefaultResourceHandlerFactoryItem.htm
                    handlerItem = new DefaultResourceHandlerFactoryItem(handler, true);
                }

                return(handlerItem.Handler);
            }
            finally
            {
                request.Dispose();
            }
        }
Пример #3
0
        internal static void RequestPythonResetHandler(string pythonEngine)
        {
            //check if python engine request is for this engine, and engine is currently started
            if (PythonEngine.IsInitialized && pythonEngine == "CPython3")
            {
                DynamoLogger?.Log("attempting reload of cpython3 modules", LogLevel.Console);
                using (Py.GIL())
                {
                    //the following is inspired by:
                    //https://github.com/ipython/ipython/blob/master/IPython/extensions/autoreload.py
                    var global = PyScopeManager.Global.Get(CPythonEvaluator.globalScopeName);
                    global?.Exec(@"import sys
import importlib
import importlib.util
import os
## Reloading sys, __main__, builtins and other key modules is not recommended.
## don't reload modules without file attributes
def should_reload(module):
    if not hasattr(module, '__file__') or module.__file__ is None:
        return None
## don't reload modules that are currently running ie __main__, __mp_main__ is renamed by multiprocessing module.
    if getattr(module, '__name__', None) in [None, '__mp_main__', '__main__']:
        # we cannot reload(__main__) or reload(__mp_main__)
        return None

    filename = module.__file__
    path, ext = os.path.splitext(filename)
## only reload .py files.
    if ext.lower() == '.py':
        py_filename = filename
    else:
        try:
            py_filename = importlib.util.source_from_cache(filename)
        except ValueError:
            return None
    return py_filename

## copy sys.modules so it's not modified during reload.
for modname,mod in sys.modules.copy().items():
    print('considering', modname)
    file = should_reload(mod)
    if file is None:
        continue
    print('reloading', modname)
    try:
        importlib.reload(mod)
    except Exception as inst:
        print('failed to reload', modname, inst)

");
                }
                Analytics.TrackEvent(
                    Dynamo.Logging.Actions.Start,
                    Dynamo.Logging.Categories.PythonOperations,
                    "CPythonReset");
            }
        }
        /// <summary>
        /// Attempt to create a HelixWatch3DViewModel. If one cannot be created,
        /// fall back to creating a DefaultWatch3DViewModel and log the exception.
        /// </summary>
        /// <param name="model">The NodeModel to associate with the returned view model.</param>
        /// <param name="parameters">A Watch3DViewModelStartupParams object.</param>
        /// <param name="logger">A logger to be used to log the exception.</param>
        /// <returns></returns>
        public static DefaultWatch3DViewModel TryCreateHelixWatch3DViewModel(NodeModel model, Watch3DViewModelStartupParams parameters, DynamoLogger logger)
        {
            try
            {
                var vm = new HelixWatch3DViewModel(model, parameters);
                return(vm);
            }
            catch (Exception ex)
            {
                logger.Log(Resources.BackgroundPreviewCreationFailureMessage, LogLevel.Console);
                logger.Log(ex.Message, LogLevel.File);

                var vm = new DefaultWatch3DViewModel(model, parameters)
                {
                    Active         = false,
                    CanBeActivated = false
                };
                return(vm);
            }
        }
Пример #5
0
        /// <summary>
        /// This method is called before a resource is loaded, if a valid resource handler
        /// is returned then this resource handler would serve the response of web request.
        /// </summary>
        public override IResourceHandler GetResourceHandler(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request)
        {
            try
            {
                IResourceHandler handler;
                if (logger != null)
                {
                    logger.Log("Requested URL", request.Url);
                }

                if (!Handlers.TryGetValue(request.Url, out handler))
                {
                    handler = this.GetResourceHandler(request);
                }

                return(handler);
            }
            finally
            {
                request.Dispose();
            }
        }
Пример #6
0
        protected DynamoModel(IStartConfiguration config)
        {
            ClipBoard = new ObservableCollection<ModelBase>();

            pathManager = new PathManager(new PathManagerParams
            {
                CorePath = config.DynamoCorePath,
                PathResolver = config.PathResolver
            });

            // Ensure we have all directories in place.
            var exceptions = new List<Exception>();
            pathManager.EnsureDirectoryExistence(exceptions);

            Context = config.Context;
            IsTestMode = config.StartInTestMode;
            DebugSettings = new DebugSettings();
            Logger = new DynamoLogger(DebugSettings, pathManager.LogDirectory);

            foreach (var exception in exceptions)
            {
                Logger.Log(exception); // Log all exceptions.
            }

            MigrationManager = new MigrationManager(DisplayFutureFileMessage, DisplayObsoleteFileMessage);
            MigrationManager.MessageLogged += LogMessage;
            MigrationManager.MigrationTargets.Add(typeof(WorkspaceMigrations));

            var thread = config.SchedulerThread ?? new DynamoSchedulerThread();
            Scheduler = new DynamoScheduler(thread, IsTestMode);
            Scheduler.TaskStateChanged += OnAsyncTaskStateChanged;

            geometryFactoryPath = config.GeometryFactoryPath;

            IPreferences preferences = CreateOrLoadPreferences(config.Preferences);
            var settings = preferences as PreferenceSettings;
            if (settings != null)
            {
                PreferenceSettings = settings;
                PreferenceSettings.PropertyChanged += PreferenceSettings_PropertyChanged;
            }

            InitializePreferences(preferences);
            InitializeInstrumentationLogger();

            if (!isTestMode && this.PreferenceSettings.IsFirstRun)
            {
                DynamoMigratorBase migrator = null;

                try
                {
                    migrator = DynamoMigratorBase.MigrateBetweenDynamoVersions(pathManager, config.PathResolver);
                }
                catch (Exception e)
                {
                    Logger.Log(e.Message);
                }

                if (migrator != null)
                {
                    var isFirstRun = this.PreferenceSettings.IsFirstRun;
                    this.PreferenceSettings = migrator.PreferenceSettings;

                    // Preserve the preference settings for IsFirstRun as this needs to be set 
                    // only by UsageReportingManager
                    this.PreferenceSettings.IsFirstRun = isFirstRun;
                }
            }

            // At this point, pathManager.PackageDirectories only has 1 element which is the directory
            // in AppData. If list of PackageFolders is empty, add the folder in AppData to the list since there
            // is no additional location specified. Otherwise, update pathManager.PackageDirectories to include
            // PackageFolders
            if (PreferenceSettings.CustomPackageFolders.Count == 0)
                PreferenceSettings.CustomPackageFolders = new List<string> {pathManager.UserDataDirectory};
            else
                pathManager.LoadCustomPackageFolders(PreferenceSettings.CustomPackageFolders);


            SearchModel = new NodeSearchModel();
            SearchModel.ItemProduced +=
                node => ExecuteCommand(new CreateNodeCommand(node, 0, 0, true, true));

            NodeFactory = new NodeFactory();
            NodeFactory.MessageLogged += LogMessage;

            CustomNodeManager = new CustomNodeManager(NodeFactory, MigrationManager);
            InitializeCustomNodeManager();

            extensionManager = new ExtensionManager();
            extensionManager.MessageLogged += LogMessage;
            var extensions = config.Extensions ?? ExtensionManager.ExtensionLoader.LoadDirectory(pathManager.ExtensionsDirectory);

            Loader = new NodeModelAssemblyLoader();
            Loader.MessageLogged += LogMessage;

            DisposeLogic.IsShuttingDown = false;

            // Create a core which is used for parsing code and loading libraries
            var libraryCore =
                new ProtoCore.Core(new Options { RootCustomPropertyFilterPathName = string.Empty });

            libraryCore.Compilers.Add(Language.kAssociative, new Compiler(libraryCore));
            libraryCore.Compilers.Add(Language.kImperative, new ProtoImperative.Compiler(libraryCore));
            libraryCore.ParsingMode = ParseMode.AllowNonAssignment;

            LibraryServices = new LibraryServices(libraryCore, pathManager);
            LibraryServices.MessageLogged += LogMessage;
            LibraryServices.LibraryLoaded += LibraryLoaded;

            ResetEngineInternal();

            AddHomeWorkspace();

            AuthenticationManager = new AuthenticationManager(config.AuthProvider);

            UpdateManager = config.UpdateManager ?? new DefaultUpdateManager(null);
            UpdateManager.Log += UpdateManager_Log;
            if (!IsTestMode)
            {
                DefaultUpdateManager.CheckForProductUpdate(UpdateManager);
            }
            
            Logger.Log(string.Format("Dynamo -- Build {0}", 
                                        Assembly.GetExecutingAssembly().GetName().Version));

            InitializeNodeLibrary(preferences);

            if (extensions.Any())
            {
                var startupParams = new StartupParams(config.AuthProvider,
                    pathManager, new ExtensionLibraryLoader(this), 
                    CustomNodeManager, GetType().Assembly.GetName().Version);

                foreach (var ext in extensions)
                {
                    var logSource = ext as ILogSource;
                    if (logSource != null)
                        logSource.MessageLogged += LogMessage;

                    ext.Startup(startupParams);
                    ext.Load(preferences, pathManager);
                    ExtensionManager.Add(ext);
                }
            }

            LogWarningMessageEvents.LogWarningMessage += LogWarningMessage;

            StartBackupFilesTimer();

            TraceReconciliationProcessor = this; 
            
            foreach (var ext in ExtensionManager.Extensions)
            {
                try
                {
                    ext.Ready(new ReadyParams(this));
                }
                catch (Exception ex)
                {
                    Logger.Log(ex.Message);
                }
            }
        }
Пример #7
0
        protected DynamoModel(StartConfiguration configuration)
        {
            string context = configuration.Context;
            IPreferences preferences = configuration.Preferences;
            string corePath = configuration.DynamoCorePath;
            DynamoRunner runner = configuration.Runner;
            bool isTestMode = configuration.StartInTestMode;

            DynamoPathManager.Instance.InitializeCore(corePath);
            UsageReportingManager.Instance.InitializeCore(this);

            Runner = runner;
            Context = context;
            IsTestMode = isTestMode;
            Logger = new DynamoLogger(this, DynamoPathManager.Instance.Logs);
            DebugSettings = new DebugSettings();

#if ENABLE_DYNAMO_SCHEDULER
            var thread = configuration.SchedulerThread ?? new DynamoSchedulerThread();
            scheduler = new DynamoScheduler(thread);
#endif

            if (preferences is PreferenceSettings)
            {
                this.PreferenceSettings = preferences as PreferenceSettings;
                PreferenceSettings.PropertyChanged += PreferenceSettings_PropertyChanged;
            }

            InitializePreferences(preferences);
            InitializeInstrumentationLogger();

            UpdateManager.UpdateManager.Instance.CheckForProductUpdate(new UpdateRequest(new Uri(Configurations.UpdateDownloadLocation)));

            SearchModel = new SearchModel(this);

            InitializeCurrentWorkspace();

            this.CustomNodeManager = new CustomNodeManager(this, DynamoPathManager.Instance.UserDefinitions);
            this.Loader = new DynamoLoader(this);

            this.Loader.PackageLoader.DoCachedPackageUninstalls();
            this.Loader.PackageLoader.LoadPackages();

            DisposeLogic.IsShuttingDown = false;

            this.EngineController = new EngineController(this, DynamoPathManager.Instance.GeometryFactory);
            this.CustomNodeManager.RecompileAllNodes(EngineController);

            // Reset virtual machine to avoid a race condition by causing a 
            // thread join inside the vm exec. Since DynamoModel is being called 
            // on the main/idle thread, it is safe to call ResetEngineInternal 
            // directly (we cannot call virtual method ResetEngine here).
            // 
            ResetEngineInternal();
            Nodes.ForEach(n => n.RequiresRecalc = true);

            Logger.Log(String.Format(
                "Dynamo -- Build {0}",
                Assembly.GetExecutingAssembly().GetName().Version));

            this.Loader.ClearCachedAssemblies();
            this.Loader.LoadNodeModels();

            MigrationManager.Instance.MigrationTargets.Add(typeof(WorkspaceMigrations));

            PackageManagerClient = new PackageManagerClient(this);
        }