Exemple #1
0
        private bool TryStartEditing(IConnectionViewModel connection)
        {
            _shell.AssertIsOnMainThread();

            // When 'Edit' button is clicked second time, we close the panel.
            // If panel has changes, offer save the changes.
            if (EditedConnection != null && EditedConnection.HasChanges)
            {
                var dialogResult = _shell.ShowMessage(Resources.ConnectionManager_EditedConnectionHasChanges, MessageButtons.YesNoCancel);
                switch (dialogResult)
                {
                case MessageButtons.Yes:
                    Save(EditedConnection);
                    break;

                case MessageButtons.Cancel:
                    return(false);
                }
            }

            var wasEditingConnection = EditedConnection;

            CancelEdit();

            // If it is the same connection that was edited then we came here as a result
            // of a second click on the edit button. Don't start editing it again.
            if (connection != wasEditingConnection)
            {
                EditedConnection     = connection;
                connection.IsEditing = true;
            }
            return(true);
        }
Exemple #2
0
        public void SelectConnection(IConnectionViewModel connection)
        {
            _shell.AssertIsOnMainThread();
            if (connection == _selectedConnection)
            {
                return;
            }

            if (SelectedConnection != null && SelectedConnection.HasChanges)
            {
                var dialogResult = _shell.ShowMessage(Resources.ConnectionManager_ChangedSelection_HasChanges, MessageButtons.YesNoCancel);
                switch (dialogResult)
                {
                case MessageButtons.Yes:
                    SaveSelected();
                    break;

                case MessageButtons.No:
                    CancelSelected();
                    break;

                default:
                    return;
                }
            }

            SelectedConnection = connection;
        }
Exemple #3
0
        public void SelectPackage(IRPackageViewModel package)
        {
            _coreShell.AssertIsOnMainThread();
            if (package == _selectedPackage)
            {
                return;
            }

            SelectedPackage = package;
        }
Exemple #4
0
        public void Assign(IRPlotDevice device)
        {
            _shell.AssertIsOnMainThread();

            _device = device;
            _device.PlotAddedOrUpdated += PlotAddedOrUpdated;
            _device.Cleared            += Cleared;
            _device.DeviceNumChanged   += DeviceNumChanged;
            _device.LocatorModeChanged += DeviceLocatorModeChanged;

            Refresh(_device.ActivePlot);
        }
        private bool TryStartEditing(IConnectionViewModel connection)
        {
            _shell.AssertIsOnMainThread();
            if (connection == EditedConnection)
            {
                return(false);
            }

            if (EditedConnection != null && EditedConnection.HasChanges)
            {
                var dialogResult = _shell.ShowMessage(Resources.ConnectionManager_EditedConnectionHasChanges, MessageButtons.YesNoCancel);
                switch (dialogResult)
                {
                case MessageButtons.Yes:
                    Save(EditedConnection);
                    break;

                case MessageButtons.No:
                    CancelEdit();
                    break;

                default:
                    return(false);
                }
            }
            else
            {
                CancelEdit();
            }

            EditedConnection     = connection;
            connection.IsEditing = true;
            return(true);
        }
Exemple #6
0
        public void SwitchToAvailablePackages()
        {
            _coreShell.AssertIsOnMainThread();
            if (_selectedTab == SelectedTab.AvailablePackages && _availablePackages != null)
            {
                return;
            }

            _selectedTab = SelectedTab.AvailablePackages;
            DispatchOnMainThreadAsync(SwitchToAvailablePackagesAsync);
        }
Exemple #7
0
        /// <summary>
        /// Primary entry point for intellisense. This is where intellisense list is getting created.
        /// </summary>
        /// <param name="session">Completion session</param>
        /// <param name="completionSets">Completion sets to populate</param>
        public void AugmentCompletionSession(ICompletionSession session, IList <CompletionSet> completionSets)
        {
            _shell.AssertIsOnMainThread();

            IREditorDocument doc = REditorDocument.TryFromTextBuffer(_textBuffer);

            if (doc == null)
            {
                return;
            }

            int position = session.GetTriggerPoint(_textBuffer).GetPosition(_textBuffer.CurrentSnapshot);

            if (!doc.EditorTree.IsReady)
            {
                var textView = session.TextView;
                doc.EditorTree.InvokeWhenReady((o) => {
                    RCompletionController controller = ServiceManager.GetService <RCompletionController>(textView);
                    if (controller != null)
                    {
                        controller.ShowCompletion(autoShownCompletion: true);
                        controller.FilterCompletionSession();
                    }
                }, null, this.GetType(), processNow: true);
            }
            else
            {
                PopulateCompletionList(position, session, completionSets, doc.EditorTree.AstRoot);
            }
        }
Exemple #8
0
        private async Task SetRootModelAsync(REnvironment env)
        {
            _shell.AssertIsOnMainThread();

            if (env.Kind != REnvironmentKind.Error)
            {
                try {
                    var result = await EvaluateAndDescribeAsync(env);

                    var wrapper = new VariableViewModel(result, _aggregator);
                    _rootNode.Model = new VariableNode(_settings, wrapper);
                } catch (RException ex) {
                    SetRootNode(VariableViewModel.Error(ex.Message));
                } catch (RHostDisconnectedException ex) {
                    SetRootNode(VariableViewModel.Error(ex.Message));
                }
            }
            else
            {
                SetRootNode(VariableViewModel.Error(env.Name));
            }

            // Some of the Variable Explorer tool bar buttons are depend on the R Environment (e.g., Delete all Variables button).
            // This will give those UI elements a chance to update state.
            _shell.UpdateCommandStatus();
        }
Exemple #9
0
        public IRPlotDeviceVisualComponent GetOrCreateVisualComponent(IRPlotDeviceVisualComponentContainerFactory visualComponentContainerFactory, int instanceId)
        {
            _shell.AssertIsOnMainThread();

            IRPlotDeviceVisualComponent component;

            if (_visualComponents.TryGetValue(instanceId, out component))
            {
                return(component);
            }

            component = visualComponentContainerFactory.GetOrCreate(this, _interactiveWorkflow.RSession, instanceId).Component;
            _disposableBag.Add(component);
            _visualComponents[instanceId] = component;
            return(component);
        }
Exemple #10
0
 private void AssertIsOnMainThread()
 {
     if (!_shell.IsUnitTestEnvironment)
     {
         _shell.AssertIsOnMainThread();
     }
 }
Exemple #11
0
        public async Task <bool> TryHandleCommandAsync(IImmutableSet <IProjectTree> nodes, long commandId, bool focused, long commandExecuteOptions, IntPtr variantArgIn, IntPtr variantArgOut)
        {
            _shell.AssertIsOnMainThread();
            if (commandId != RPackageCommandId.icmdSendToRemote)
            {
                return(false);
            }

            var properties = _configuredProject.Services.ExportProvider.GetExportedValue <ProjectProperties>();
            var projectDir = Path.GetDirectoryName(_configuredProject.UnconfiguredProject.FullPath);

            var fileFilterString = await properties.GetFileFilterAsync();

            var matcher = new Matcher(StringComparison.OrdinalIgnoreCase);

            matcher.AddIncludePatterns(fileFilterString.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries));

            var filteredFiles = new List <string>();

            filteredFiles.AddRange(matcher.GetMatchedFiles(nodes.GetAllFolderPaths(_configuredProject.UnconfiguredProject)));

            // Add any file that user specifically selected. This can contain a file ignored by the filter.
            filteredFiles.AddRange(nodes.Where(n => n.IsFile()).Select(n => n.FilePath));

            var projectName = properties.GetProjectName();
            var remotePath  = await properties.GetRemoteProjectPathAsync();

            if (filteredFiles.Count > 0)
            {
                await SendToRemoteAsync(filteredFiles.Distinct(), projectDir, projectName, remotePath);
            }

            return(true);
        }
Exemple #12
0
        public async Task <IInteractiveWindowVisualComponent> GetOrCreateVisualComponent(IInteractiveWindowComponentContainerFactory componentContainerFactory, int instanceId = 0)
        {
            // Right now only one instance of interactive window is allowed
            if (ActiveWindow != null)
            {
                throw new InvalidOperationException("Right now only one instance of interactive window is allowed");
            }

            _coreShell.AssertIsOnMainThread();

            var evaluator = RInstallationHelper.VerifyRIsInstalled(_coreShell, _settings.RBasePath)
                ? new RInteractiveEvaluator(RSession, History, _coreShell, _settings)
                : (IInteractiveEvaluator) new NullInteractiveEvaluator();

            ActiveWindow = componentContainerFactory.Create(instanceId, evaluator);
            var interactiveWindow = ActiveWindow.InteractiveWindow;

            interactiveWindow.TextView.Closed += (_, __) => evaluator.Dispose();
            _operations.InteractiveWindow      = interactiveWindow;

            await interactiveWindow.InitializeAsync();

            ActiveWindow.Container.UpdateCommandStatus(true);
            return(ActiveWindow);
        }
        private async Task ProjectUnloading(object sender, EventArgs args)
        {
            _coreShell.AssertIsOnMainThread();

            _unconfiguredProject.ProjectRenamedOnWriter -= ProjectRenamedOnWriter;
            _unconfiguredProject.ProjectUnloading       -= ProjectUnloading;
            _fileWatcher.Dispose();

            if (!_coreShell.Services.FileSystem.DirectoryExists(_projectDirectory))
            {
                return;
            }

            if (_toolsSettings.AlwaysSaveHistory)
            {
                _history.TrySaveToFile(Path.Combine(_projectDirectory, DefaultRHistoryName));
            }

            var rdataPath            = Path.Combine(_projectDirectory, DefaultRDataName);
            var saveDefaultWorkspace = await GetSaveDefaultWorkspace(rdataPath);

            if (!_session.IsHostRunning)
            {
                return;
            }

            Task.Run(async() => {
                if (saveDefaultWorkspace)
                {
                    await _session.SaveWorkspaceAsync(rdataPath);
                }
                await _session.SetDefaultWorkingDirectoryAsync();
            }).SilenceException <RException>().DoNotWait();
        }
Exemple #14
0
        public Credentials GetUserCredentials(string authority, string workspaceName, CancellationToken cancellationToken = default(CancellationToken))
        {
            _coreShell.AssertIsOnMainThread();

            var credentials = Credentials.ReadSavedCredentials(authority) ?? GetUserCredentials(workspaceName, cancellationToken);

            return(credentials);
        }
Exemple #15
0
        public ISearchControl Create(FrameworkElement host, ISearchHandler handler, SearchControlSettings settings)
        {
            _coreShell.AssertIsOnMainThread();

            var vsWindowSearchHost = _factoryLazy.Value.CreateWindowSearchHost(host);

            return(new VsSearchControl(vsWindowSearchHost, handler, settings));
        }
Exemple #16
0
        public IDisposable AddItem(UIElement element)
        {
            _shell.AssertIsOnMainThread();
            EnsureItemsControlCreated();

            _itemsControl.Items.Insert(0, element);
            return(Disposable.Create(() => _shell.MainThread().Post(() => _itemsControl.Items.Remove(element))));
        }
Exemple #17
0
        public static void CheckInstall(ICoreShell coreShell)
        {
            coreShell.AssertIsOnMainThread();
            var connections = coreShell.ExportProvider.GetExportedValue <IRInteractiveWorkflowProvider>().GetOrCreate().Connections;

            string rClientPath = CheckMicrosoftRClientInstall(coreShell);

            if (rClientPath != null)
            {
                connections.GetOrAddConnection("Microsoft R Client", rClientPath, string.Empty);
            }
        }
Exemple #18
0
        internal static string CheckMicrosoftRClientInstall(ICoreShell coreShell, IRegistry registry = null) {
            coreShell.AssertIsOnMainThread();
            registry = registry ?? new RegistryImpl();

            var rClientPath = SqlRClientInstallation.GetRClientPath(registry);
            if (!string.IsNullOrEmpty(rClientPath) && AskUserSwitchToRClient(registry)) {
                // Get R Client path
                if (MessageButtons.Yes == coreShell.ShowMessage(Resources.Prompt_MsRClientJustInstalled, MessageButtons.YesNo)) {
                    return rClientPath;
                }
            }
            return null;
        }
Exemple #19
0
        public static void CheckInstall(ICoreShell coreShell)
        {
            coreShell.AssertIsOnMainThread();

            string rClientPath = CheckMicrosoftRClientInstall(coreShell);

            if (rClientPath != null)
            {
                RToolsSettings.Current.RBasePath = rClientPath;
                using (var p = RPackage.Current.GetDialogPage(typeof(RToolsOptionsPage)) as RToolsOptionsPage) {
                    p.SaveSettings();
                }
            }
        }
Exemple #20
0
        public async Task <bool> TryHandleCommandAsync(IImmutableSet <IProjectTree> nodes, long commandId, bool focused, long commandExecuteOptions, IntPtr variantArgIn, IntPtr variantArgOut)
        {
            _coreShell.AssertIsOnMainThread();
            if (commandId != RPackageCommandId.icmdSetAsStartUpRScript)
            {
                return(false);
            }
            var properties   = _configuredProject.Services.ExportProvider.GetExportedValue <ProjectProperties>();
            var path         = nodes.GetSingleNodePath();
            var relativePath = _configuredProject.UnconfiguredProject.MakeRelative(path);
            await properties.SetStartupFileAsync(relativePath);

            return(true);
        }
Exemple #21
0
        public void DecreaseThumbnailSize()
        {
            _shell.AssertIsOnMainThread();

            if (ThumbnailSize > MinThumbnailSize)
            {
                ThumbnailSize -= ThumbnailSizeIncrement;
            }
        }
        public Task AssignAsync(IRPlotDevice device)
        {
            _shell.AssertIsOnMainThread();

            _device = device;
            _device.PlotAddedOrUpdated += PlotAddedOrUpdated;
            _device.Cleared            += Cleared;
            _device.DeviceNumChanged   += DeviceNumChanged;

            Refresh(_device.ActivePlot);

            return(Task.CompletedTask);
        }
Exemple #23
0
        internal static string CheckMicrosoftRClientInstall(ICoreShell coreShell)
        {
            coreShell.AssertIsOnMainThread();

            var rClientPath = GetRClientPath();

            if (!string.IsNullOrEmpty(rClientPath) && AskUserSwitchToRClient())
            {
                // Get R Client path
                if (MessageButtons.Yes == coreShell.ShowMessage(Resources.Prompt_MsRClientJustInstalled, MessageButtons.YesNo))
                {
                    return(rClientPath);
                }
            }
            return(null);
        }
Exemple #24
0
        private void ProcessReplacement()
        {
            _coreShell.AssertIsOnMainThread();
            // Writing messages in the same line (via simulated CR)

            var m = _messagePos;

            _messagePos = null;

            // Replace last written placeholder with the actual message.
            // Pad text as necessary by spaces to match original length.
            var extra       = m.PlaceholderLength - m.Text.Length;
            var replacement = m.Text + (extra > 0 ? new string(' ', extra) : string.Empty);

            _interactiveWindow.OutputBuffer.Replace(new Span(m.Position, m.PlaceholderLength), replacement);
        }
        public async Task <bool> TryHandleCommandAsync(IImmutableSet <IProjectTree> nodes, long commandId, bool focused, long commandExecuteOptions, IntPtr variantArgIn, IntPtr variantArgOut)
        {
            _coreShell.AssertIsOnMainThread();
            if (commandId != RPackageCommandId.icmdCopyRemoteItemPath)
            {
                return(false);
            }

            var    properties          = _configuredProject.Services.ExportProvider.GetExportedValue <ProjectProperties>();
            var    path                = nodes.GetSingleNodePath();
            var    projectRelativePath = _configuredProject.UnconfiguredProject.MakeRelative(path);
            string fullRemotePath      = await properties.ToRRemotePathAsync(projectRelativePath);

            if (!string.IsNullOrEmpty(fullRemotePath))
            {
                fullRemotePath.CopyToClipboard();
            }

            return(true);
        }
Exemple #26
0
        public override T GetService <T>(Type type = null)
        {
            type = type ?? typeof(T);

            if (type == typeof(ExportProvider))
            {
                return(ExportProvider as T);
            }
            if (type == typeof(ICompositionService))
            {
                return(CompositionService as T);
            }
            if (type == typeof(ICompositionCatalog))
            {
                return((T)(ICompositionCatalog) new CompositionCatalog(CompositionService, ExportProvider));
            }

            // First try internal services
            var service = base.GetService <T>(type);

            if (service == null)
            {
                // First try MEF
                service = ExportProvider.GetExportedValueOrDefault <T>();
                if (service == null)
                {
                    // Now try VS services. Only allowed on UI thread.
                    if (_shell.IsUnitTestEnvironment)
                    {
                        service = RPackage.Current != null?RPackage.Current.GetService(type) as T : null;
                    }
                    else
                    {
                        _shell.AssertIsOnMainThread();
                        service = VsPackage.GetGlobalService(type) as T;
                    }
                }
            }
            return(service);
        }
        public void ReloadItems()
        {
            _coreShell.AssertIsOnMainThread();
            switch (_selectedTab)
            {
            case SelectedTab.AvailablePackages:
                //LoadAvailablePackages();
                break;

            case SelectedTab.InstalledPackages:
                //LoadInstalledPackages();
                break;

            case SelectedTab.LoadedPackages:
                break;

            case SelectedTab.None:
                return;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Exemple #28
0
 private void UnadviseWindowFrameEvents()
 {
     _coreShell.AssertIsOnMainThread();
     _uiShell.UnadviseWindowFrameEvents(_cookie);
     _cookie = 0;
 }
Exemple #29
0
        public Task <Credentials> GetUserCredentialsAsync(string authority, string workspaceName, CancellationToken cancellationToken = default(CancellationToken))
        {
            _coreShell.AssertIsOnMainThread();

            var credentials = SecurityUtilities.ReadCredentials(authority);

            if (credentials != null)
            {
                return(Task.FromResult(credentials));
            }

            var credui = new CREDUI_INFO {
                cbSize         = Marshal.SizeOf(typeof(CREDUI_INFO)),
                hwndParent     = _coreShell.AppConstants.ApplicationWindowHandle,
                pszCaptionText = Resources.Info_ConnectingTo.FormatInvariant(workspaceName)
            };
            uint           authPkg     = 0;
            IntPtr         credStorage = IntPtr.Zero;
            uint           credSize;
            bool           save  = true;
            CredUIWinFlags flags = CredUIWinFlags.CREDUIWIN_CHECKBOX;
            // For password, use native memory so it can be securely freed.
            IntPtr passwordStorage = SecurityUtilities.CreatePasswordBuffer();
            int    inCredSize      = 1024;
            IntPtr inCredBuffer    = Marshal.AllocCoTaskMem(inCredSize);

            try {
                if (!CredPackAuthenticationBuffer(0, WindowsIdentity.GetCurrent().Name, "", inCredBuffer, ref inCredSize))
                {
                    int error = Marshal.GetLastWin32Error();
                    throw new Win32Exception(error);
                }

                var err = CredUIPromptForWindowsCredentials(ref credui, 0, ref authPkg, inCredBuffer, (uint)inCredSize, out credStorage, out credSize, ref save, flags);
                if (err != 0)
                {
                    throw new OperationCanceledException();
                }

                StringBuilder userNameBuilder = new StringBuilder(CRED_MAX_USERNAME_LENGTH);
                int           userNameLen     = CRED_MAX_USERNAME_LENGTH;
                StringBuilder domainBuilder   = new StringBuilder(CRED_MAX_USERNAME_LENGTH);
                int           domainLen       = CRED_MAX_USERNAME_LENGTH;
                int           passLen         = CREDUI_MAX_PASSWORD_LENGTH;
                if (!CredUnPackAuthenticationBuffer(CRED_PACK_PROTECTED_CREDENTIALS, credStorage, credSize, userNameBuilder, ref userNameLen, domainBuilder, ref domainLen, passwordStorage, ref passLen))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                return(Task.FromResult(Credentials.CreateCredentails(userNameBuilder.ToString(), SecurityUtilities.SecureStringFromNativeBuffer(passwordStorage), save)));
            } finally {
                if (inCredBuffer != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(inCredBuffer);
                }

                if (credStorage != IntPtr.Zero)
                {
                    Marshal.ZeroFreeCoTaskMemUnicode(credStorage);
                }

                if (passwordStorage != IntPtr.Zero)
                {
                    Marshal.ZeroFreeCoTaskMemUnicode(passwordStorage);
                }
            }
        }
Exemple #30
0
 public void RefreshDeviceName()
 {
     _shell.AssertIsOnMainThread();
     DeviceName = string.Format(CultureInfo.CurrentCulture, Resources.Plots_DeviceName, _plot.ParentDevice.DeviceNum);
 }
Exemple #31
0
 public Credentials GetUserCredentials(string authority, string workspaceName)
 {
     _coreShell.AssertIsOnMainThread();
     return(ReadSavedCredentials(authority) ?? PromptForWindowsCredentials(authority, workspaceName));
 }