Пример #1
0
        private PSConsoleReadLine()
        {
            _mockableMethods = this;

            _captureKeys = false;
            _savedKeys = new Queue<ConsoleKeyInfo>();
            _demoStrings = new HistoryQueue<string>(100);
            _demoMode = false;

            SetDefaultWindowsBindings();

            _buffer = new StringBuilder(8 * 1024);
            _statusBuffer = new StringBuilder(256);
            _savedCurrentLine = new HistoryItem();
            _queuedKeys = new Queue<ConsoleKeyInfo>();

            _pushedEditGroupCount = new Stack<int>();

            _options = new PSConsoleReadlineOptions();

            _history = new HistoryQueue<HistoryItem>(Options.MaximumHistoryCount);
            _currentHistoryIndex = 0;

            _killIndex = -1;    // So first add indexes 0.
            _killRing = new List<string>(Options.MaximumKillRingCount);
        }
Пример #2
0
        public MarketAnalyzer(BitstampHistoryLoader historyLoader)
        {
            MinTimespan = TimeSpan.FromMinutes(1);

            _bidStat = new Lazy <Statistic>(() => new Statistic(_priceHistory.Select(entry => entry.BidPrice)));
            _askStat = new Lazy <Statistic>(() => new Statistic(_priceHistory.Select(entry => entry.AskPrice)));

            _priceHistory = new LinkedList <Entry>();
            _history      = new HistoryQueue(historyLoader);
        }
Пример #3
0
        static PSConsoleReadLine()
        {
            _singleton = new PSConsoleReadLine();

            _breakHandlerGcHandle = GCHandle.Alloc(new BreakHandler(_singleton.BreakHandler));
            NativeMethods.SetConsoleCtrlHandler((BreakHandler) _breakHandlerGcHandle.Target, true);
            _singleton._readKeyThread = new Thread(_singleton.ReadKeyThreadProc) {IsBackground = true};
            _singleton._readKeyThread.Start();
            _singleton._readKeyWaitHandle = new AutoResetEvent(false);
            _singleton._keyReadWaitHandle = new AutoResetEvent(false);
            _singleton._closingWaitHandle = new AutoResetEvent(false);
            _singleton._waitHandles = new WaitHandle[] { _singleton._keyReadWaitHandle, _singleton._closingWaitHandle };

            // This is only used for post-mortem debugging - 200 keys should be enough to reconstruct most command lines.
            _lastNKeys = new HistoryQueue<ConsoleKeyInfo>(200);
        }
Пример #4
0
        public void OnCapacity()
        {
            const int capacity = 100;

            var history = new HistoryQueue <int>(capacity);

            const int numbersToAdd = 100;

            for (int i = 0; i < numbersToAdd; i++)
            {
                history.Enqueue(i);
            }

            Assert.IsTrue(history.Count == numbersToAdd);
            for (int i = 0; i < numbersToAdd; i++)
            {
                Assert.AreEqual(i, history[i]);
            }
        }
Пример #5
0
        public void OverCapacity()
        {
            const int capacity = 100001;

            var history = new HistoryQueue <int>(capacity);

            const int numbersToAdd = 200002;

            for (int i = 0; i < numbersToAdd; i++)
            {
                history.Enqueue(i);
            }

            Assert.IsTrue(history.Count == capacity);

            for (int i = 0; i < history.Count; i++)
            {
                Assert.AreEqual(numbersToAdd - capacity + i, history[i]);
            }
        }
Пример #6
0
 void Awake()
 {
     if (points == null)
     {
         points       = new List <MousePoint>();
         pointsByType = new Dictionary <MSTIMULUS, List <int> >();
     }
     _occupants = new List <int>();
     mpindex    = points.Count;
     auditTrail = new HistoryQueue <int>(auditTrailLength);
     points.Add(this);
     if (!pointsByType.ContainsKey(type))
     {
         pointsByType[type] = new List <int>();
     }
     pointsByType[type].Add(mpindex);
     if (startActive)
     {
         _active = true;
     }
     Init();
 }
Пример #7
0
        private PSConsoleReadLine()
        {
            _mockableMethods = this;

            _captureKeys = false;
            _savedKeys = new Queue<ConsoleKeyInfo>();
            _demoStrings = new HistoryQueue<string>(100);
            _demoMode = false;

            SetDefaultWindowsBindings();

            _buffer = new StringBuilder(8 * 1024);
            _statusBuffer = new StringBuilder(256);
            _savedCurrentLine = new HistoryItem();
            _queuedKeys = new Queue<ConsoleKeyInfo>();

            string hostName = null;
            try
            {
                var ps = PowerShell.Create(RunspaceMode.CurrentRunspace)
                    .AddCommand("Get-Variable").AddParameter("Name", "host").AddParameter("ValueOnly");
                var results = ps.Invoke();
                dynamic host = results.Count == 1 ? results[0] : null;
                if (host != null)
                {
                    hostName = host.Name as string;
                }
            }
            catch
            {
            }
            if (hostName == null)
            {
                hostName = "PSReadline";
            }
            _options = new PSConsoleReadlineOptions(hostName);
        }
Пример #8
0
        /// <summary>
        /// Executes the action asynchronously, de-bouncing if necessary.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>An awaitable task containing the result.</returns>
        protected override async Task <ScheduledActionResult> DoExecuteAsync(
            CancellationToken cancellationToken = default(CancellationToken))
        {
            // Start stopwatch, and mark time the request was made.
            Stopwatch stopwatch = Stopwatch.StartNew();
            Instant   started   = TimeHelpers.Clock.Now;

            // Combine cancellation token with Timeout to ensure no action runs beyond the Scheduler's limit.
            using (ITokenSource tokenSource = cancellationToken.WithTimeout(MaximumDurationMs))
            {
                // Quick cancellation check.
                // ReSharper disable once PossibleNullReferenceException
                if (tokenSource.IsCancellationRequested)
                {
                    // ReSharper disable once AssignNullToNotNullAttribute
                    return(new ScheduledFunctionResult <T>(
                               NextDue,
                               TimeHelpers.Clock.Now,
                               Duration.Zero,
                               null,
                               true,
                               default(T)));
                }

                // Always yield to ensure tasks run asynchronously.
                await Task.Yield();

                // Wait until the semaphore says we can go.
                using (await _lock.LockAsync(tokenSource.Token).ConfigureAwait(false))
                {
                    // Quick cancellation check.
                    // ReSharper disable once PossibleNullReferenceException
                    if (tokenSource.IsCancellationRequested)
                    {
                        // ReSharper disable once AssignNullToNotNullAttribute
                        return(new ScheduledFunctionResult <T>(
                                   NextDue,
                                   TimeHelpers.Clock.Now,
                                   Duration.Zero,
                                   null,
                                   true,
                                   default(T)));
                    }

                    ScheduledFunctionResult <T> result;
                    // De-bounce - we started before the last execution finished, so return last result, so long as it wasn't cancelled.
                    if (started <= LastExecutionFinished)
                    {
                        result = HistoryQueue.LastOrDefault() as ScheduledFunctionResult <T>;
                        if (result != null &&
                            !result.Cancelled)
                        {
                            return(result);
                        }
                    }

                    // Get the due date, and set to not due.
                    long    ndt = Interlocked.Exchange(ref NextDueTicksInternal, Scheduler.MaxTicks);
                    Instant due = new Instant(ndt);

                    try
                    {
                        // Execute function (ensuring cancellation).
                        // ReSharper disable once AssignNullToNotNullAttribute
                        T r = await _function(due, tokenSource.Token)
                              .WithCancellation(tokenSource.Token)
                              .ConfigureAwait(false);

                        stopwatch.Stop();

                        result = new ScheduledFunctionResult <T>(
                            due,
                            started,
                            Duration.FromTimeSpan(stopwatch.Elapsed),
                            null,
                            tokenSource.IsCancellationRequested,
                            r);
                    }
                    catch (Exception e)
                    {
                        stopwatch.Stop();

                        bool cancelled = tokenSource.IsCancellationRequested ||
                                         e is TaskCanceledException ||
                                         e is OperationCanceledException;

                        // ReSharper disable once AssignNullToNotNullAttribute
                        result = new ScheduledFunctionResult <T>(
                            due,
                            started,
                            Duration.FromTimeSpan(stopwatch.Elapsed),
                            !cancelled ? e : null,
                            cancelled,
                            default(T));
                    }
                    // Increment the execution count.
                    Interlocked.Increment(ref ExecutionCountInternal);

                    // Mark execution finished
                    LastExecutionFinished = TimeHelpers.Clock.Now;

                    // Enqueue history item.
                    HistoryQueue.Enqueue(result);

                    // Recalculate when we're next due.
                    RecalculateNextDue(due);
                    return(result);
                }
            }
        }
Пример #9
0
        private void SetOptionsInternal(SetPSReadlineOption options)
        {
            if (options.ContinuationPrompt != null)
            {
                Options.ContinuationPrompt = options.ContinuationPrompt;
            }
            if (options._continuationPromptForegroundColor.HasValue)
            {
                Options.ContinuationPromptForegroundColor = options.ContinuationPromptForegroundColor;
            }
            if (options._continuationPromptBackgroundColor.HasValue)
            {
                Options.ContinuationPromptBackgroundColor = options.ContinuationPromptBackgroundColor;
            }
            if (options._emphasisBackgroundColor.HasValue)
            {
                Options.EmphasisBackgroundColor = options.EmphasisBackgroundColor;
            }
            if (options._emphasisForegroundColor.HasValue)
            {
                Options.EmphasisForegroundColor = options.EmphasisForegroundColor;
            }
            if (options._errorBackgroundColor.HasValue)
            {
                Options.ErrorBackgroundColor = options.ErrorBackgroundColor;
            }
            if (options._errorForegroundColor.HasValue)
            {
                Options.ErrorForegroundColor = options.ErrorForegroundColor;
            }
            if (options._historyNoDuplicates.HasValue)
            {
                Options.HistoryNoDuplicates = options.HistoryNoDuplicates;
            }
            if (options._historySearchCursorMovesToEnd.HasValue)
            {
                Options.HistorySearchCursorMovesToEnd = options.HistorySearchCursorMovesToEnd;
            }
            if (options._addToHistoryHandlerSpecified)
            {
                Options.AddToHistoryHandler = options.AddToHistoryHandler;
            }
            if (options._commandValidationHandlerSpecified)
            {
                Options.CommandValidationHandler = options.CommandValidationHandler;
            }
            if (options._maximumHistoryCount.HasValue)
            {
                Options.MaximumHistoryCount = options.MaximumHistoryCount;
                if (_history != null)
                {
                    var newHistory = new HistoryQueue<HistoryItem>(Options.MaximumHistoryCount);
                    while (_history.Count > Options.MaximumHistoryCount)
                    {
                        _history.Dequeue();
                    }
                    while (_history.Count > 0)
                    {
                        newHistory.Enqueue(_history.Dequeue());
                    }
                    _history = newHistory;
                    _currentHistoryIndex = _history.Count;
                }
            }
            if (options._maximumKillRingCount.HasValue)
            {
                Options.MaximumKillRingCount = options.MaximumKillRingCount;
                // TODO - make _killRing smaller
            }
            if (options._editMode.HasValue)
            {
                Options.EditMode = options.EditMode;

                // Switching/resetting modes - clear out chord dispatch table
                _chordDispatchTable.Clear();

                SetDefaultBindings(Options.EditMode);
            }
            if (options._showToolTips.HasValue)
            {
                Options.ShowToolTips = options.ShowToolTips;
            }
            if (options._extraPromptLineCount.HasValue)
            {
                Options.ExtraPromptLineCount = options.ExtraPromptLineCount;
            }
            if (options._dingTone.HasValue)
            {
                Options.DingTone = options.DingTone;
            }
            if (options._dingDuration.HasValue)
            {
                Options.DingDuration = options.DingDuration;
            }
            if (options._bellStyle.HasValue)
            {
                Options.BellStyle = options.BellStyle;
            }
            if (options._completionQueryItems.HasValue)
            {
                Options.CompletionQueryItems = options.CompletionQueryItems;
            }
            if (options.WordDelimiters != null)
            {
                Options.WordDelimiters = options.WordDelimiters;
            }
            if (options._historySearchCaseSensitive.HasValue)
            {
                Options.HistorySearchCaseSensitive = options.HistorySearchCaseSensitive;
            }
            if (options._historySaveStyle.HasValue)
            {
                Options.HistorySaveStyle = options.HistorySaveStyle;
            }
            #region vi
            if (options._viModeIndicator.HasValue)
            {
                Options.ViModeIndicator = options.ViModeIndicator;
            }
            #endregion
            if (options.HistorySavePath != null)
            {
                Options.HistorySavePath = options.HistorySavePath;
                if (_historyFileMutex != null)
                {
                    _historyFileMutex.Dispose();
                }
                _historyFileMutex = new Mutex(false, GetHistorySaveFileMutexName());
                _historyFileLastSavedSize = 0;
            }
            if (options.ResetTokenColors)
            {
                Options.ResetColors();
            }
            if (options._tokenKind.HasValue)
            {
                if (options._foregroundColor.HasValue)
                {
                    Options.SetForegroundColor(options.TokenKind, options.ForegroundColor);
                }
                if (options._backgroundColor.HasValue)
                {
                    Options.SetBackgroundColor(options.TokenKind, options.BackgroundColor);
                }
            }
        }
Пример #10
0
        private void SetOptionsInternal(SetPSReadlineOption options)
        {
            if (options.ContinuationPrompt != null)
            {
                Options.ContinuationPrompt = options.ContinuationPrompt;
            }
            if (options._continuationPromptForegroundColor.HasValue)
            {
                Options.ContinuationPromptForegroundColor = options.ContinuationPromptForegroundColor;
            }
            if (options._continuationPromptBackgroundColor.HasValue)
            {
                Options.ContinuationPromptBackgroundColor = options.ContinuationPromptBackgroundColor;
            }
            if (options._emphasisBackgroundColor.HasValue)
            {
                Options.EmphasisBackgroundColor = options.EmphasisBackgroundColor;
            }
            if (options._emphasisForegroundColor.HasValue)
            {
                Options.EmphasisForegroundColor = options.EmphasisForegroundColor;
            }
            if (options._historyNoDuplicates.HasValue)
            {
                Options.HistoryNoDuplicates = options.HistoryNoDuplicates;
                if (Options.HistoryNoDuplicates)
                {
                    _hashedHistory.Clear();
                    _history.OnEnqueue = null;
                    _history.OnDequeue = null;
                    var newHistory = new HistoryQueue<HistoryItem>(Options.MaximumHistoryCount);
                    while (_history.Count > 0)
                    {
                        var item = _history.Dequeue();
                        var itemStr = item._line;
                        if (!_hashedHistory.Contains(itemStr))
                        {
                            newHistory.Enqueue(item);
                            _hashedHistory.Add(itemStr);
                        }
                    }
                    _history = newHistory;
                    _history.OnEnqueue = HistoryOnEnqueueHandler;
                    _history.OnDequeue = HistoryOnDequeueHandler;
                    _currentHistoryIndex = _history.Count;
                }
            }
            if (options._historySearchCursorMovesToEnd.HasValue)
            {
                Options.HistorySearchCursorMovesToEnd = options.HistorySearchCursorMovesToEnd;
            }
            if (options._addToHistoryHandlerSpecified)
            {
                Options.AddToHistoryHandler = options.AddToHistoryHandler;
            }
            if (options._maximumHistoryCount.HasValue)
            {
                Options.MaximumHistoryCount = options.MaximumHistoryCount;
                var newHistory = new HistoryQueue<HistoryItem>(Options.MaximumHistoryCount);
                while (_history.Count > Options.MaximumHistoryCount)
                {
                    _history.Dequeue();
                }
                _history.OnEnqueue = null;
                _history.OnDequeue = null;
                while (_history.Count > 0)
                {
                    newHistory.Enqueue(_history.Dequeue());
                }
                _history = newHistory;
                _history.OnEnqueue = HistoryOnEnqueueHandler;
                _history.OnDequeue = HistoryOnDequeueHandler;
                _currentHistoryIndex = _history.Count;
            }
            if (options._maximumKillRingCount.HasValue)
            {
                Options.MaximumKillRingCount = options.MaximumKillRingCount;
                // TODO - make _killRing smaller
            }
            if (options._editMode.HasValue)
            {
                Options.EditMode = options.EditMode;

                // Switching/resetting modes - clear out chord dispatch table
                _chordDispatchTable.Clear();

                switch (options._editMode)
                {
                case EditMode.Emacs:
                    SetDefaultEmacsBindings();
                    break;
            #if FALSE
                case EditMode.Vi:
                    //TODO: _dispatchTable = _viKeyMap;
                    break;
            #endif
                case EditMode.Windows:
                    SetDefaultWindowsBindings();
                    break;
                }
            }
            if (options._showToolTips.HasValue)
            {
                Options.ShowToolTips = options.ShowToolTips;
            }
            if (options._extraPromptLineCount.HasValue)
            {
                Options.ExtraPromptLineCount = options.ExtraPromptLineCount;
            }
            if (options._dingTone.HasValue)
            {
                Options.DingTone = options.DingTone;
            }
            if (options._dingDuration.HasValue)
            {
                Options.DingDuration = options.DingDuration;
            }
            if (options._bellStyle.HasValue)
            {
                Options.BellStyle = options.BellStyle;
            }
            if (options._completionQueryItems.HasValue)
            {
                Options.CompletionQueryItems = options.CompletionQueryItems;
            }
            if (options.WordDelimiters != null)
            {
                Options.WordDelimiters = options.WordDelimiters;
            }
            if (options._historySearchCaseSensitive.HasValue)
            {
                Options.HistorySearchCaseSensitive = options.HistorySearchCaseSensitive;
            }
            if (options.ResetTokenColors)
            {
                Options.ResetColors();
            }
            if (options._tokenKind.HasValue)
            {
                if (options._foregroundColor.HasValue)
                {
                    Options.SetForegroundColor(options.TokenKind, options.ForegroundColor);
                }
                if (options._backgroundColor.HasValue)
                {
                    Options.SetBackgroundColor(options.TokenKind, options.BackgroundColor);
                }
            }
        }
Пример #11
0
        private void DelayedOneTimeInitialize()
        {
            // Delayed initialization is needed so that options can be set
            // after the constuctor but have an affect before the user starts
            // editing their first command line.  For example, if the user
            // specifies a custom history save file, we don't want to try reading
            // from the default one.

            _historyFileMutex = new Mutex(false, GetHistorySaveFileMutexName());

            _history = new HistoryQueue<HistoryItem>(Options.MaximumHistoryCount);
            _currentHistoryIndex = 0;

            ReadHistoryFile();

            _killIndex = -1; // So first add indexes 0.
            _killRing = new List<string>(Options.MaximumKillRingCount);
        }
Пример #12
0
        public void EmptyQueue()
        {
            var history = new HistoryQueue <string>(10);

            Assert.IsTrue(history.Count == 0);
        }
Пример #13
0
 public void BadCapacity()
 {
     var history = new HistoryQueue <string>(-1);
 }