private void EnsureState() { if (_state == null) { _state = new CompletionState(); } }
public void Complete( IDbContextTransaction transaction, CompletionState completionState) { try { if (transaction != null && transaction.TransactionId != null && transaction.GetDbTransaction() != null) { if (completionState == CompletionState.Success) { transaction.Commit(); } else { transaction.Rollback(); } } } catch { transaction.Rollback(); } }
/// <summary>Completes the completion task asynchronously.</summary> private void CompleteTaskAsync() { Debug.Assert(ReadyToComplete, "The block must be ready to complete to be here."); ContractAssertMonitorStatus(ValueLock, held: true); // Ensure we only try to complete once, then schedule completion // in order to escape held locks and the caller's context CompletionState cs = EnsureCompletionStateInitialized(); if (!cs.m_completionQueued) { cs.m_completionQueued = true; ThreadPool.QueueUserWorkItem(state => { Debug.Assert(state is ConcurrentExclusiveSchedulerPair); var localThis = (ConcurrentExclusiveSchedulerPair)state; Debug.Assert(!localThis.m_completionState !.IsCompleted, "Completion should only happen once."); List <Exception>?exceptions = localThis.m_completionState.m_exceptions; bool success = (exceptions != null && exceptions.Count > 0) ? localThis.m_completionState.TrySetException(exceptions) : localThis.m_completionState.TrySetResult(); Debug.Assert(success, "Expected to complete completion task."); localThis.m_threadProcessingMode.Dispose(); }, this); } }
/// <summary> /// Sets the task to the completed state. /// </summary> /// <param name="occurredException">An exception that occurred while executing the task. Passing null for /// exception means no error occurred. This is the common case.</param> /// <param name="completedSynchronously">True if the task run synchronously.</param> public void SetAsCompleted( Exception occurredException, bool completedSynchronously) { // Mutex for accessing member fields lock (this) { // Assert completed has not been called yet if (this.completionState != CompletionState.Pending) { throw new InvalidOperationException("You can not set to completed because it is already completed."); } // Set new completion state this.completionState = completedSynchronously ? CompletionState.CompletedSynchronously : CompletionState.CompletedAsynchronously; // Set the exception this.exception = occurredException; } // If the event exists, set it if (this.asyncWaitHandle != null) { this.asyncWaitHandle.Set(); } // If a callback method was set, call it if (this.asyncCallback != null) { this.asyncCallback(this); } }
/// <summary> /// Constructor. MUST use graphics device for creating extra textures, and /// using the viewport /// </summary> /// <param name="theGraphicsDevice"></param> public Level(GraphicsDevice theGraphicsDevice, string levelId) { myGraphicsDevice = theGraphicsDevice; loadedState = LoadingState.uninitialized; runningState = CompletionState.running; myLevelId = levelId; deathStrings = new List<string> {"humiliated", "pwned", "destroyed", "demolished", "embarrassed", "O.J. Simpson'ed", "gutted", "fatalatied", "slapped" }; }
public void UpdateState(CompletionState state) { State = state; Finished = DateTime.UtcNow; CancelToken.Dispose(); CancelToken = null; TaskFactory = null; Task = null; }
void ShowCompletions(string prefix, string [] completions) { // Ensure we have space, determine window size int window_height = System.Math.Min(completions.Length, Console.WindowHeight / 5); int target_line = Console.WindowHeight - window_height - 1; if (Console.CursorTop > target_line) { var saved_left = Console.CursorLeft; var delta = Console.CursorTop - target_line; Console.CursorLeft = 0; Console.CursorTop = Console.WindowHeight - 1; for (int i = 0; i < delta + 1; i++) { for (int c = Console.WindowWidth; c > 0; c--) { Console.Write(" "); // To debug use ("{0}", i%10); } } Console.CursorTop = target_line; Console.CursorLeft = 0; Render(); } const int MaxWidth = 50; int window_width = 12; int plen = prefix.Length; foreach (var s in completions) { window_width = System.Math.Max(plen + s.Length, window_width); } window_width = System.Math.Min(window_width, MaxWidth); if (current_completion == null) { int left = Console.CursorLeft - prefix.Length; if (left + window_width + 1 >= Console.WindowWidth) { left = Console.WindowWidth - window_width - 1; } current_completion = new CompletionState(left, Console.CursorTop + 1, window_width, window_height) { Prefix = prefix, Completions = completions, }; } else { current_completion.Prefix = prefix; current_completion.Completions = completions; } current_completion.Show(); Console.CursorLeft = 0; }
void HideCompletions() { if (current_completion == null) { return; } current_completion.Remove(); current_completion = null; }
/// <summary> /// Constructor. MUST use graphics device for creating extra textures, and /// using the viewport /// </summary> /// <param name="theGraphicsDevice"></param> public Level(GraphicsDevice theGraphicsDevice, string levelId) { myGraphicsDevice = theGraphicsDevice; loadedState = LoadingState.uninitialized; runningState = CompletionState.running; myLevelId = levelId; deathStrings = new List <string> { "humiliated", "pwned", "destroyed", "demolished", "embarrassed", "O.J. Simpson'ed", "gutted", "fatalatied", "slapped" }; }
private void catchPlayerState(object sender, bool isCompleted) { if (!isCompleted) { runningState = CompletionState.dead; } else { runningState = CompletionState.complete; } myPlayer.Changed -= new ChangedEventHandler(catchPlayerState); }
/// <summary> /// Initializes a new instance of <see cref="Completion"/> with the specified text and description. /// </summary> /// <param name="displayText">The text that is to be displayed by an IntelliSense presenter.</param> /// <param name="insertionText">The text that is to be inserted into the buffer if this completion is committed.</param> /// <param name="description">A description that could be displayed with the display text of the completion.</param> /// <param name="iconSource">The icon to describe the completion item.</param> /// <param name="iconAutomationText">The automation name for the icon.</param> public Completion(string displayText, string insertionText, string description, ImageSource iconSource, string iconAutomationText) { _state = new CompletionState(); _state.displayText = displayText; _state.insertionText = insertionText; _state.description = description; _state.iconSource = iconSource; _state.iconAutomationText = iconAutomationText; }
/// <summary>Completes the completion task asynchronously.</summary> private void CompleteTaskAsync() { Debug.Assert(ReadyToComplete, "The block must be ready to complete to be here."); ContractAssertMonitorStatus(ValueLock, held: true); // Ensure we only try to complete once, then schedule completion // in order to escape held locks and the caller's context CompletionState cs = EnsureCompletionStateInitialized(); if (!cs.m_completionQueued) { cs.m_completionQueued = true; ThreadPool.QueueUserWorkItem(static state =>
/// <summary>Initiates scheduler shutdown due to a worker task faulting.</summary> /// <param name="faultedTask">The faulted worker task that's initiating the shutdown.</param> private void FaultWithTask(Task faultedTask) { Debug.Assert(faultedTask != null && faultedTask.IsFaulted && faultedTask.Exception !.InnerExceptions.Count > 0, "Needs a task in the faulted state and thus with exceptions."); ContractAssertMonitorStatus(ValueLock, held: true); // Store the faulted task's exceptions CompletionState cs = EnsureCompletionStateInitialized(); cs.m_exceptions ??= new List <Exception>(); cs.m_exceptions.AddRange(faultedTask.Exception.InnerExceptions); // Now that we're doomed, request completion RequestCompletion(); }
public void Initialize(CompletionState state) { switch (state) { case CompletionState.Won: settings.titleText.text = "LEVEL COMPLETE!"; break; default: settings.titleText.text = "UNKNOWN OUTCOME!"; Debug.LogError($"Unhandled state{state}"); break; } gameObject.GetComponent <Canvas>().enabled = true; }
public void ReportFinished(CompletionState state, Exception error = null) { if (error != null) { _log.Log( $"[ERROR] {state} - Completed {_errorCount + _successCount} journeys in {_journeyTime}" + $" (Success: {_successCount}, Errors: {_errorCount}){Environment.NewLine}" + $"{error}"); } else { _log.Log( $"[INFO] {state} - Completed {_errorCount + _successCount} journeys in {_journeyTime} " + $"(Success: {_successCount}, Errors: {_errorCount})"); } }
/// <summary> /// Flags a finish. /// </summary> /// <param name="commit"></param> /// <param name="failureException"></param> private void FinishOne(bool commit, Exception failureException) { //if(this.Log.IsDebugEnabled) // this.Log.Debug(string.Format("Finished with commit: {0}", commit)); // what now? if (this.CompletionState == CompletionState.NotSet) { if (commit) { _completionState = CompletionState.Commit; } else { _completionState = CompletionState.Rollback; } } else { // if we commit, keep as commit if we were commit... if (commit) { // no-op... because we don't want to overwrite a rollback with a commit... } else { // if we're not committing, force to rollback... _completionState = CompletionState.Rollback; } } // state? //if(this.Log.IsDebugEnabled) // this.Log.Debug(string.Format("\tCompletion state: {0}", this.CompletionState)); // failure? if (!(commit) && failureException != null) { // set... //if(this.Log.IsDebugEnabled) // this.Log.Debug(string.Format("\tAdding failure exception: {0} ({1})", failureException.Message, failureException.GetType())); // add... FailureExceptions.Add(failureException); } }
public async Task <CompletionState> RunAsync(CancellationToken token) { completionState = CompletionState.Failed; while (ShouldRetry()) { completionState = await Task.Factory.StartNew(Try, token); context.Update(); if (ShouldRetry()) { await waitHandler.WaitAsync(NextRetryDelayOrThrowIfNotValid(), token); } } return(completionState); }
public CompletionState Run() { completionState = CompletionState.Failed; while (ShouldRetry()) { completionState = Try(); context.Update(); if (ShouldRetry()) { waitHandler.WaitSync(NextRetryDelayOrThrowIfNotValid()); } } return(completionState); }
/// <summary> /// Constructs a MaterialPreviewRenderer to obtain a preview image /// for one given material. /// </summary> /// <param name="window">Window instance that hosts the primary Gl context</param> /// <param name="scene">Scene instance that the material belongs to</param> /// <param name="material">Material to render a preview image for</param> /// <param name="width">Requested width of the preview image, in pixels</param> /// <param name="height">Requested height of the preview image, in pixels</param> public MaterialPreviewRenderer(MainViewer3DControl window, Scene scene, Material material, uint width, uint height) { Debug.Assert(window != null); Debug.Assert(material != null); Debug.Assert(scene != null); Debug.Assert(width >= 1); Debug.Assert(height >= 1); _scene = scene; _material = material; _width = width; _height = height; _state = CompletionState.Pending; window.Renderer.GlExtraDrawJob += (sender) => { _state = !RenderPreview() ? CompletionState.Failed : CompletionState.Done; OnPreviewAvailable(); }; }
public void Update(GameTime gameTime) { if (loadedState != LoadingState.complete) { return; } if (runningState == CompletionState.dead) { KeyboardState currentKeyboardState = Keyboard.GetState(); GamePadState currentPadState = GamePad.GetState(myPlayer.getPlayerIndex()); if (currentKeyboardState.IsKeyDown(Keys.Enter) || currentPadState.IsButtonDown(Buttons.Start)) { // Reload the level runningState = CompletionState.running; collisionSprites.Clear(); myCollidedSprite = null; failString = null; LoadLevel(myContent); } } else { // Update all the level sprites for the level foreach (Sprite curSprite in myLevelSprites) { curSprite.Update(gameTime, myContent); } foreach (PlayerSprite curPlayer in playerList.list()) { curPlayer.Update(gameTime, myContent); } // TODO detect level detection detectLevelCollisions(); } }
void HideCompletions () { if (current_completion == null) return; current_completion.Remove (); current_completion = null; }
public void Update(GameTime gameTime) { if (loadedState != LoadingState.complete) return; if (runningState == CompletionState.dead) { KeyboardState currentKeyboardState = Keyboard.GetState(); GamePadState currentPadState = GamePad.GetState(myPlayer.getPlayerIndex()); if (currentKeyboardState.IsKeyDown(Keys.Enter) || currentPadState.IsButtonDown(Buttons.Start)) { // Reload the level runningState = CompletionState.running; collisionSprites.Clear(); myCollidedSprite = null; failString = null; LoadLevel(myContent); } } else { // Update all the level sprites for the level foreach (Sprite curSprite in myLevelSprites) curSprite.Update(gameTime, myContent); foreach (PlayerSprite curPlayer in playerList.list()) curPlayer.Update(gameTime, myContent); // TODO detect level detection detectLevelCollisions(); } }
public void SetCompletion(CompletionState state) { CompletionState = state; }
public InstructionItem(string id, string title, string subtitle, string description, string location, int costValue, Priority priority, string owner, ITimelineItem[] dependencies, CompletionState completionState = CompletionState.INCOMPLETE) { Dependencies = new HashSet <ITimelineItem>(dependencies); }
private void catchPlayerState(object sender, bool isCompleted) { if (!isCompleted) runningState = CompletionState.dead; else runningState = CompletionState.complete; myPlayer.Changed -= new ChangedEventHandler(catchPlayerState); }
public void EF_LoadActivities_AtStart_DataHandlerLevel() { context = Start(); var sctx = context.Security; var user1Id = TestUser.User1.Id; var rootEntityId = Id("E01"); // create 30 activities sctx.CreateSecurityEntity(rootEntityId, default(int), user1Id); for (int entityId = rootEntityId + 1; entityId < rootEntityId + 31; entityId++) { sctx.CreateSecurityEntity(entityId, rootEntityId, user1Id); } var lastId = Db().ExecuteTestScript <int>("select top 1 Id from [EFMessages] order by Id desc").First(); // test0: initial int dbId0; var expectedCs0 = new CompletionState { LastActivityId = lastId }; var cs0 = DataHandler.LoadCompletionState(sctx.DataProvider, out dbId0); Assert.AreEqual(lastId, dbId0); Assert.AreEqual(expectedCs0.ToString(), cs0.ToString()); // test1: create unprocessed activities: set "wait" on 4 continuous activity (except last) + 2 gaps before Db().ExecuteTestScript(@"declare @last int select top 1 @last = Id from [EFMessages] order by Id desc UPDATE EFMessages set ExecutionState = 'Executing' where Id in (@last-1, @last-2, @last-3, @last-4, @last-6, @last-9) "); int dbId1; var expectedCs1 = new CompletionState { LastActivityId = lastId, Gaps = new[] { lastId - 9, lastId - 6, lastId - 4, lastId - 3, lastId - 2, lastId - 1 } }; var cs1 = DataHandler.LoadCompletionState(sctx.DataProvider, out dbId1); Assert.AreEqual(dbId1, lastId); Assert.AreEqual(expectedCs1.ToString(), cs1.ToString()); // test2: create unprocessed activities: set "wait" on last 5 continuous activity (except last) + 2 gaps before Db().ExecuteTestScript(@"declare @last int select top 1 @last = Id from [EFMessages] order by Id desc UPDATE EFMessages set ExecutionState = 'Executing' where Id in (@last) "); int dbId2; var expectedCs2 = new CompletionState { LastActivityId = lastId - 5, Gaps = new[] { lastId - 9, lastId - 6 } }; var cs2 = DataHandler.LoadCompletionState(sctx.DataProvider, out dbId2); Assert.AreEqual(dbId2, lastId); Assert.AreEqual(expectedCs2.ToString(), cs2.ToString()); }
public void EF_LoadActivities_AtStart_ActivityQueueLevel() { int lastActivityIdFromDb; CompletionState uncompleted; context = Start(); var sctx = context.Security; var user1Id = TestUser.User1.Id; var rootEntityId = Id("E01"); // create 30 activities sctx.CreateSecurityEntity(rootEntityId, default(int), user1Id); for (int entityId = rootEntityId + 1; entityId < rootEntityId + 31; entityId++) { sctx.CreateSecurityEntity(entityId, rootEntityId, user1Id); } var lastId = Db().ExecuteTestScript <int>("select top 1 Id from [EFMessages] order by Id desc").First(); // test0: initial state var expectedCs = new CompletionState { LastActivityId = lastId }; uncompleted = DataHandler.LoadCompletionState(SecurityContext.General.DataProvider, out lastActivityIdFromDb); SecurityActivityQueue.Startup(uncompleted, lastActivityIdFromDb); var cs0 = SecurityActivityQueue.GetCurrentState().Termination; Assert.AreEqual(expectedCs.ToString(), cs0.ToString()); // test1: create some unprocessed activities: 4 continuous activity (except last) + 2 gaps before // last-2 and last-6 "Wait", the others "Executing" by another appdomain. Db().ExecuteTestScript(@"declare @last int select top 1 @last = Id from [EFMessages] order by Id desc UPDATE EFMessages set ExecutionState = 'Executing', LockedBy = 'AnotherComputer' where Id in (@last-1, @last-3, @last-4, @last-9) UPDATE EFMessages set ExecutionState = 'Wait', LockedBy = null, LockedAt = null where Id in (@last-2, @last-6) "); var expectedIsFromDb1 = String.Join(", ", new[] { lastId - 9, lastId - 4, lastId - 3, lastId - 1, lastId }); uncompleted = DataHandler.LoadCompletionState(SecurityContext.General.DataProvider, out lastActivityIdFromDb); SecurityActivityQueue.Startup(uncompleted, lastActivityIdFromDb); var cs1 = SecurityActivityQueue.GetCurrentState().Termination; var idsFromDb1 = String.Join(", ", Db().GetUnprocessedActivityIds()); Assert.AreEqual(expectedCs.ToString(), cs1.ToString()); Assert.AreEqual(expectedIsFromDb1, idsFromDb1); // test2: create unprocessed activities: last 5 continuous activity + 2 gaps before // last-2 and last-6 "Wait", the others "Executing" by another appdomain. Db().ExecuteTestScript(@"declare @last int select top 1 @last = Id from [EFMessages] order by Id desc UPDATE EFMessages set ExecutionState = 'Executing', LockedBy = 'AnotherComputer' where Id in (@last, @last-1, @last-3, @last-4, @last-9) UPDATE EFMessages set ExecutionState = 'Wait', LockedBy = null, LockedAt = null where Id in (@last-2, @last-6) "); var expectedIsFromDb2 = String.Join(", ", new[] { lastId - 9, lastId - 4, lastId - 3, lastId - 1, lastId, lastId }); uncompleted = DataHandler.LoadCompletionState(SecurityContext.General.DataProvider, out lastActivityIdFromDb); SecurityActivityQueue.Startup(uncompleted, lastActivityIdFromDb); var cs2 = SecurityActivityQueue.GetCurrentState().Termination; var idsFromDb2 = String.Join(", ", Db().GetUnprocessedActivityIds()); Assert.AreEqual(expectedCs.ToString(), cs2.ToString()); Assert.AreEqual(expectedIsFromDb2, idsFromDb2); }
internal static List <XSharpToken> GetTokenListBeforeCaret(XSharpSearchLocation location, out CompletionState state) { var tokens = GetTokenList(location, out state, false); var result = new List <XSharpToken>(); foreach (var token in tokens) { if (token.Position <= location.Position) { result.Add(token); } } return(result); }
internal static List <XSharpToken> GetTokenList(XSharpSearchLocation location, out CompletionState state, bool includeKeywords = false, bool underCursor = false) { location = AdjustStartLineNumber(location); var line = getLineFromBuffer(location); // state = CompletionState.General; if (line.Count == 0) { return(line); } // if the token appears after comma or paren then strip the tokens // now look forward and find the first token that is on or after the triggerpoint var result = new List <XSharpToken>(); var last = XSharpLexer.Eof; bool allowdot = location.Project?.ParseOptions?.AllowDotForInstanceMembers ?? false; var cursorPos = location.Position; var done = false; var list = new XSharpTokenList(line); while (!done && !list.Eoi()) { var token = list.ConsumeAndGet(); int openToken = 0; XSharpToken closeToken = null; bool isHit = token.StartIndex <= cursorPos && token.StopIndex >= cursorPos && underCursor; bool isNotLast = token.StopIndex < location.Position - 1; if (token.StartIndex > cursorPos) { // after the cursor we only include the open tokens // so we can see if the id under the cursor is a method, constructor etc switch (token.Type) { case XSharpLexer.LPAREN: case XSharpLexer.LCURLY: case XSharpLexer.LBRKT: break; case XSharpLexer.LT: // if this is a generic type // then add the complete bool first = true; bool endoflist = false; while (!endoflist) { endoflist = true; if (list.La1 == XSharpLexer.ID || XSharpLexer.IsType(list.La1)) { if (list.La2 == XSharpLexer.GT || list.La2 == XSharpLexer.COMMA) { if (first) { result.Add(token); first = false; } result.Add(list.ConsumeAndGet()); // la1 result.Add(list.ConsumeAndGet()); // la2 endoflist = false; } } } continue; default: done = true; break; } if (done) { continue; } } switch (token.Type) { // after these tokens we "restart" the list case XSharpLexer.EOS: if (token.Position < cursorPos && token != line.Last()) { // an EOS inside a line before the cursor // so there are 2 or more statements on the same line // clear the first statement result.Clear(); state = CompletionState.General; } else { // Exit loop, ignore the rest of the statements done = true; } continue; case XSharpLexer.WS: case XSharpLexer.Eof: continue; case XSharpLexer.TO: case XSharpLexer.UPTO: case XSharpLexer.DOWNTO: case XSharpLexer.IN: if (!isHit) { result.Clear(); if (isNotLast) // there has to be a space after the token { state = CompletionState.General; } else { state = CompletionState.None; } } else { result.Add(token); } break; case XSharpLexer.LCURLY: state = CompletionState.Constructors; result.Add(token); break; case XSharpLexer.LPAREN: state = CompletionState.StaticMembers | CompletionState.InstanceMembers; result.Add(token); break; case XSharpLexer.LBRKT: state = CompletionState.Brackets; result.Add(token); break; case XSharpLexer.ID: case XSharpLexer.NAMEOF: case XSharpLexer.TYPEOF: case XSharpLexer.SIZEOF: result.Add(token); break; case XSharpLexer.RCURLY: case XSharpLexer.RPAREN: case XSharpLexer.RBRKT: bool add = true; if (result.Count > 0 && token == list.LastOrDefault) { var lasttoken = result.Last(); if (lasttoken.Type == XSharpLexer.COLON || lasttoken.Type == XSharpLexer.DOT) { // closing char after colon or dot add = false; done = true; } } if (add) { result.Add(token); // delete everything between parens, curly braces and brackets closing token before cursor pos if (token.Position < location.Position) { closeToken = token; if (token.Type == XSharpLexer.RCURLY) { openToken = XSharpLexer.LCURLY; } else if (token.Type == XSharpLexer.RPAREN) { openToken = XSharpLexer.LPAREN; } else if (token.Type == XSharpLexer.RBRKT) { openToken = XSharpLexer.LBRKT; } } } break; case XSharpLexer.STATIC: // These tokens are all before a namespace of a (namespace dot) type if (isNotLast) // there has to be a space after the token { state = CompletionState.General; } else { state = CompletionState.None; } break; case XSharpLexer.USING: if (isNotLast) // there has to be a space after the token { if (list.Expect(XSharpLexer.STATIC)) { state = CompletionState.Namespaces | CompletionState.Types; result.Clear(); } else if (list.La1 == XSharpLexer.ID) { state = CompletionState.Namespaces; result.Clear(); } } break; case XSharpLexer.MEMBER: if (isNotLast) // there has to be a space after the token { state = CompletionState.StaticMembers; } else { state = CompletionState.None; } break; case XSharpLexer.AS: case XSharpLexer.IS: case XSharpLexer.REF: case XSharpLexer.INHERIT: if (!isHit) { result.Clear(); } else { result.Add(token); } if (isNotLast) // there has to be a space after the token { state = CompletionState.Namespaces | CompletionState.Types; } else { state = CompletionState.None; } break; case XSharpLexer.IMPLEMENTS: result.Clear(); if (isNotLast) { state = CompletionState.Namespaces | CompletionState.Interfaces; } else { state = CompletionState.None; } break; case XSharpLexer.COLON: state = CompletionState.InstanceMembers; result.Add(token); break; case XSharpLexer.DOT: if (!state.HasFlag(CompletionState.Namespaces)) { state = CompletionState.Namespaces | CompletionState.Types | CompletionState.StaticMembers; if (allowdot) { state |= CompletionState.InstanceMembers; } } result.Add(token); break; case XSharpLexer.QMARK: if (result.Count != 0) // when at start of line then do not add. Otherwise it might be a Nullable type or conditional access expression { result.Add(token); } break; case XSharpLexer.QQMARK: if (result.Count != 0) // when at start of line then do not add. Otherwise it might be a binary expression { result.Add(token); } break; case XSharpLexer.BACKSLASH: case XSharpLexer.BACKBACKSLASH: // this should only be seen at start of line // clear the list to be sure result.Clear(); break; case XSharpLexer.NAMESPACE: state = CompletionState.Namespaces; break; case XSharpLexer.COMMA: case XSharpLexer.ASSIGN_OP: case XSharpLexer.COLONCOLON: case XSharpLexer.SELF: case XSharpLexer.SUPER: state = CompletionState.General; result.Add(token); break; default: state = CompletionState.General; if (XSharpLexer.IsOperator(token.Type)) { result.Add(token); } else if (XSharpLexer.IsType(token.Type)) { result.Add(token); } else if (XSharpLexer.IsConstant(token.Type)) { result.Add(token); } else if (XSharpLexer.IsKeyword(token.Type) && includeKeywords) // For code completion we want to include keywords { token.Text = XSettings.FormatKeyword(token.Text); result.Add(token); } break; } last = token.Type; // remove everything between parens, curly braces or brackets when the closing token is before the cursor if (openToken != 0 && closeToken != null) { var iLast = result.Count - 1; int count = 0; while (iLast >= 0 && result[iLast] != closeToken) { iLast--; } int closeType = closeToken.Type; while (iLast >= 0) { var type = result[iLast].Type; if (type == closeType) { count += 1; } else if (type == openToken) { count -= 1; if (count == 0) { if (iLast < result.Count - 1) { result.RemoveRange(iLast + 1, result.Count - iLast - 2); } break; } } iLast -= 1; } } } // when the list ends with a comma, drop the ending comma. Why ? if (result.Count > 0) { var end = result.Last(); if (end.Type == XSharpLexer.COMMA) { result.RemoveAt(result.Count - 1); } } return(result); }
internal static IList <XSharpToken> GetTokensUnderCursor(XSharpSearchLocation location, out CompletionState state) { var tokens = GetTokenList(location, out state, true, true).Where((t) => t.Channel == XSharpLexer.DefaultTokenChannel).ToList(); // Find "current" token if (tokens.Count > 0) { var tokenUnderCursor = tokens.Count - 1; for (int i = tokens.Count - 1; i >= 0; i--) { var token = tokens[i]; if (token.StartIndex <= location.Position && token.StopIndex >= location.Position) { tokenUnderCursor = i; break; } } var selectedToken = tokens[tokenUnderCursor]; var nextToken = tokenUnderCursor < tokens.Count - 1 ? tokens[tokenUnderCursor + 1] : null; bool done = false; switch (selectedToken.Type) { case XSharpLexer.NAMEOF: case XSharpLexer.TYPEOF: case XSharpLexer.SIZEOF: case XSharpLexer.SELF: case XSharpLexer.SUPER: if (nextToken != null && nextToken.Type == XSharpLexer.LPAREN) { return(tokens); } break; default: if (XSharpLexer.IsKeyword(selectedToken.Type)) { tokens.Clear(); tokens.Add(selectedToken); return(tokens); } break; } // When we are not on a Keyword then we need to walk back in the tokenlist to see // if we can evaluate the expression // This could be: // System.String.Compare() // static method cal or method call // SomeVar:MethodCall() // method call // Left(...) // function call // SomeId // local, global etc // SomeType.Id // Static property or normal property // SomeVar:Id // Instance field or property // If the token list contains with a RCURLY, RBRKT or RPAREN // Then strip everything until the matching LCURLY, LBRKT or LPAREN is found var list = new XSharpTokenList(tokens); tokens = new List <XSharpToken>(); while (!list.Eoi()) { var token = list.ConsumeAndGet(); switch (token.Type) { case XSharpLexer.LCURLY: tokens.Add(token); if (list.Contains(XSharpLexer.RCURLY)) { // this may return false when the RCURLY belongs to another LCURLY if (list.ConsumeUntilEndToken(XSharpLexer.RCURLY, out var endToken)) { tokens.Add(endToken); } } break; case XSharpLexer.LPAREN: tokens.Add(token); if (list.Contains(XSharpLexer.RPAREN)) { // this may return false when the RPAREN belongs to another LPAREN if (list.ConsumeUntilEndToken(XSharpLexer.RPAREN, out var endToken)) { tokens.Add(endToken); } } break; case XSharpLexer.LBRKT: tokens.Add(token); if (list.Contains(XSharpLexer.RBRKT)) { // this may return false when the RBRKT belongs to another LBRKT if (list.ConsumeUntilEndToken(XSharpLexer.RBRKT, out var endToken)) { tokens.Add(endToken); } } break; case XSharpLexer.DOT: case XSharpLexer.COLON: case XSharpLexer.SELF: case XSharpLexer.SUPER: tokens.Add(token); break; default: tokens.Add(token); if (XSharpLexer.IsOperator(token.Type)) { done = true; } if (token.Type == XSharpLexer.VAR) { done = true; } else if (XSharpLexer.IsKeyword(token.Type) && !XSharpLexer.IsPositionalKeyword(token.Type) ) { done = true; } break; } } // now result has the list of tokens starting with the cursor // we only keep: // ID, DOT, COLON, LPAREN, LBRKT, RBRKT // when we detect another token we truncate the list there if (tokens.Count > 0) { var lastType = tokens[0].Type; for (int i = tokenUnderCursor + 1; i < tokens.Count && !done; i++) { var token = tokens[i]; switch (token.Type) { case XSharpLexer.ID: case XSharpLexer.DOT: case XSharpLexer.COLON: case XSharpLexer.LPAREN: case XSharpLexer.LCURLY: case XSharpLexer.LBRKT: lastType = tokens[i].Type; break; case XSharpLexer.LT: int gtPos = findTokenInList(tokens, i + 1, XSharpLexer.GT); if (lastType == XSharpLexer.ID && gtPos > 0) { gtPos += 1; tokens.RemoveRange(gtPos, tokens.Count - gtPos); done = true; break; } else { goto default; } default: tokens.RemoveRange(i, tokens.Count - i); done = true; break; } } } } // check for extra lparen, lcurly at the end int count = tokens.Count; if (count > 2 && count < tokens.Count - 2) { if (tokens[count - 2].Type == XSharpLexer.LPAREN) { switch (tokens[count - 1].Type) { case XSharpLexer.LPAREN: case XSharpLexer.LCURLY: tokens.RemoveAt(count - 1); break; } } } return(tokens); }
void ShowCompletions (string prefix, string [] completions) { // Ensure we have space, determine window size int window_height = System.Math.Min (completions.Length, Console.WindowHeight/5); int target_line = Console.WindowHeight-window_height-1; if (Console.CursorTop > target_line){ var saved_left = Console.CursorLeft; var delta = Console.CursorTop-target_line; Console.CursorLeft = 0; Console.CursorTop = Console.WindowHeight-1; for (int i = 0; i < delta+1; i++){ for (int c = Console.WindowWidth; c > 0; c--) Console.Write (" "); // To debug use ("{0}", i%10); } Console.CursorTop = target_line; Console.CursorLeft = 0; Render (); } const int MaxWidth = 50; int window_width = 12; int plen = prefix.Length; foreach (var s in completions) window_width = System.Math.Max (plen + s.Length, window_width); window_width = System.Math.Min (window_width, MaxWidth); if (current_completion == null){ int left = Console.CursorLeft-prefix.Length; if (left + window_width + 1 >= Console.WindowWidth) left = Console.WindowWidth-window_width-1; current_completion = new CompletionState (left, Console.CursorTop+1, window_width, window_height) { Prefix = prefix, Completions = completions, }; } else { current_completion.Prefix = prefix; current_completion.Completions = completions; } current_completion.Show (); Console.CursorLeft = 0; }
/// <summary> /// Initializes a new instance of <see cref="Completion"/> with the specified text and description. /// </summary> /// <param name="displayText">The text that is to be displayed by an IntelliSense presenter.</param> public Completion(string displayText) { _state = new CompletionState(); _state.displayText = displayText; _state.insertionText = displayText; }
/// <summary> /// Constructs a MaterialPreviewRenderer to obtain a preview image /// for one given material. /// </summary> /// <param name="window">Window instance that hosts the primary Gl context</param> /// <param name="scene">Scene instance that the material belongs to</param> /// <param name="material">Material to render a preview image for</param> /// <param name="width">Requested width of the preview image, in pixels</param> /// <param name="height">Requested height of the preview image, in pixels</param> public MaterialPreviewRenderer(MainWindow window, Scene scene, Material material, uint width, uint height) { Debug.Assert(window != null); Debug.Assert(material != null); Debug.Assert(scene != null); Debug.Assert(width >= 1); Debug.Assert(height >= 1); _scene = scene; _material = material; _width = width; _height = height; _state = CompletionState.Pending; window.Renderer.GlExtraDrawJob += (sender) => { _state = !RenderPreview() ? CompletionState.Failed : CompletionState.Done; OnPreviewAvailable(); }; }
/// <summary> /// Complete work in this instance. /// </summary> private void FinishAll() { // usage... _usage--; if (_usage < 0) { throw new InvalidOperationException("Usage has dropped below zero."); } // log... //if(this.Log.IsDebugEnabled) //{ // this.Log.Debug(string.Format("Transaction manager '{0}' disposed - usage is now {1}...", // this.GetHashCode(), this.Usage)); //} // what now? if (_usage == 0) { // commit? bool commit = false; switch (CompletionState) { case CompletionState.NotSet: throw new InvalidOperationException("No 'Commit' or 'Rollback' calls were made."); case CompletionState.Commit: commit = true; break; case CompletionState.Rollback: commit = false; break; default: throw new NotSupportedException(string.Format("Cannot handle '{0}' ({1}).", CompletionState, CompletionState.GetType())); } // failures... Exception[] failureExceptions = (Exception[])this.FailureExceptions.ToArray(typeof(Exception)); // do we need to unbind main? if (this.MainBound) { this.FinishMain(commit, failureExceptions); } // mbr - 09-12-2007 - now do named... this.FinishNamedConnections(commit); // reset... _current = null; } }