Debugger >> process:context:
process: aProcess context: aContext

	interruptedProcess := aProcess.

	self newStack: (aContext stackOfSize: 1).
	contextStackIndex := 1.

Debugger class >> onProcess:context:
onProcess: aProcess context: aContext

	^ self new
		process: aProcess context: aContext;
		yourself

Debugger >> buildFullWith:label:
buildFullWith: builder label: label

	| windowSpec |
	windowSpec := self buildWindowWith: builder specs:
		{(0 @ 0 corner: 1 @ 0.22) -> [self buildContextStackListWith: builder].
		(0 @ 0.22 corner: 1 @ 0.8) -> [self buildCodePaneWith: builder].
		(0 @ 0.8 corner: 0.2 @ 1) ->
			[(self receiverInspector buildFieldListWith: builder)
				help: [self receiverInspectorHelp];
				yourself].
		(0.2 @ 0.8 corner: 0.5 @ 1) ->
			[(self receiverInspector buildValuePaneWith: builder)
				help: [self receiverInspectorValueHelp];
				yourself].
		(0.5 @ 0.8 corner: 0.7 @ 1) ->
			[(self contextVariablesInspector buildFieldListWith: builder)
				help: [self contextVariablesInspectorHelp];
				yourself].
		(0.7 @ 0.8 corner: 1 @ 1) ->
			[(self contextVariablesInspector buildValuePaneWith: builder)
				help: [self contextVariablesInspectorPaneHelp];
				yourself]}.
	windowSpec label: label.
	^ builder build: windowSpec

Debugger >> openWithLabel:contents:fullView:
openWithLabel: labelString contents: contentsStringOrNil fullView: full
	"Open the receiver in a window. Note that we cannot rely on the default #buildWith: callback because debuggers can be compact (i.e. the notifier) or full, which we must decide here."
	
	| window |
	window := self
		buildWithLabel: labelString
		contents: contentsStringOrNil
		fullView: full.
	Project current
		addDeferredUIMessage: [
			"Make sure to refresh GUI elements that depend on certain process state."
			self changed: #interruptedProcessShouldResume.
			self changed: #interruptedProcessIsReady];
		debugProcess: interruptedProcess "may not yet be suspended"
		inWindow: window.
	
	"Answer the receiver, but only if active process is not the process-to-debug. So in tests, use a helper process if you want to access the debugger itself."
	"self assert: [Processor activeProcess ~~ interruptedProcess]. -- works only if not simulated"

Debugger >> stepInto
stepInto

	self send.

Debugger >> stepOver
stepOver

	self doStep.

Debugger >> stepThrough
stepThrough

	self stepIntoBlock.

Debugger >> proceed
proceed
	"Proceed from the interrupted state of the currently selected context. The argument is the topView of the receiver. That view is closed. The active process usually suspends (or terminates) after this call."

	| processToResume canResume |

	Smalltalk okayToProceedEvenIfSpaceIsLow ifFalse: [^ self].
	
	self okToChange ifFalse: [^ self].
	self checkContextSelection.
	
	processToResume := interruptedProcess.
	canResume := self interruptedProcessShouldResume.
	
	interruptedProcess := nil. "Before delete, so release doesn't terminate it"
	self close.
	
	Smalltalk installLowSpaceWatcher. "restart low space handler"
	
	canResume
		ifTrue: [self resumeProcess: processToResume]
		ifFalse: [self notify: 'This process should not resume.\Debugger will close now.' translated withCRs].

Debugger >> restart
restart
	"Proceed from the initial state of the currently selected context. The 
	argument is a controller on a view of the receiver. That view is closed."
	"Closing now depends on a preference #restartAlsoProceeds - hmm 9/7/2001 16:46"

	| unwindError |
	self okToChange ifFalse: [^ self].
	interruptedProcess isSuspended ifFalse: [^ self shouldNotStep].
	self checkContextSelection.
	unwindError := self tryRestartFrom: self selectedContext.
	((Preferences restartAlsoProceeds
		and: [unwindError not])
		and: [self interruptedProcessShouldResume])
			ifTrue: [self proceed].

Debugger >> contents:notifying:
contents: aText notifying: aController
	"Accept new method source of the selected context."

	| selector classOfMethod category ctxt newMethod |
	self hasContextSelected ifFalse: [^ false].
	
	"First, handle some edge cases"
	selector := self selectedClass newParser parseSelector: aText.
	"selector isDoIt ifTrue: [
		currentCompiledMethod := self compileDoIt: aText]."
	self flag: #todo. "ct: Recompile doIt method *without* creating method litters! See Compiler>>#evaluateCue:ifFail:."
	selector = self selectedMessageName ifFalse: [
		"Different message compiled, delegating to super"
		^ super contents: aText notifying: aController].
	
	self selectedContext isClosureContext ifTrue: [
		"If we are in a block context, we need to rewind the stack before ."
		| home |
		home := self selectedContext activeHome.
		home ifNil: [
			(self confirm: 'Method for block not found on stack, can''t edit and continue. Update method anyway?' translated) ifFalse: [
				^ false].
			^ (super contents: aText notifying: aController) = true
				ifTrue: [
					contents := nil. self contentsChanged.
					self inform: 'Method was updated, but cannot revert the stack to it.' translated];
				yourself].
		(self confirm: 'I will have to revert to the method from\which this block originated. Is that OK?' translated withCRs) ifFalse: [
			^ false].
		
		self resetContext: home changeContents: false.
		"N.B. Only reset the contents if the compilation succeeds. If contents would be reset when compilation fails, both compiler error message and modifications were lost."
		^ (self contents: aText notifying: aController) = true
			ifTrue: [self contentsChanged];
			yourself].
	
	classOfMethod := self selectedClass.
	category := self selectedMessageCategoryName.
	
	"Do the actual compilation"
	selector := classOfMethod
		compile: aText
		classified: category
		notifying: aController.
	selector ifNil: [^ false]. "compilation cancelled"
	
	"Update views"
	contents := aText.
	newMethod := classOfMethod compiledMethodAt: selector.
	newMethod isQuick ifTrue: [
		self cutBackExecutionToSenderContext].
	ctxt := interruptedProcess popTo: self selectedContext.
	ctxt == self selectedContext
		ifFalse: [self inform: 'Method saved, but current context unchanged\because of unwind error. Click OK to see error' translated withCRs]
		ifTrue: [
			newMethod isQuick ifFalse: [
				interruptedProcess restartTopWith: newMethod.
				ctxt := self stepToStatement].
			contextVariablesInspector object: nil].
	self resetContext: ctxt.
	
	Project current addDeferredUIMessage: [
		self changed: #contentsSelection].
	^ true

Debugger >> buildControlButtons
buildControlButtons

	| builder |
	builder := ToolBuilder default.
	^ (self buildControlButtonsWith: builder)
		collect: [:spec | builder build: spec]

Debugger >> contextStackIndex:oldContextWas:
contextStackIndex: anInteger oldContextWas: oldContext 
	"Change the context stack index to anInteger, perhaps in response to user selection."

	| isNewMethod newContext cviClass |
	self saveReceiverInspectorState.
	self saveContextVariablesInspectorState.
	contextStackIndex := anInteger.
	anInteger = 0 ifTrue:
		[currentCompiledMethod := contents := nil.
		 self changed: #contextStackIndex.
		 self decorateButtons.
		 self contentsChanged.
		 contextVariablesInspector
			changeInspectorClassTo: DebuggerProcessInspector;
			object: self interruptedProcess.
		 self restoreContextVariablesInspectorState.
		 receiverInspector
			context: nil;
			inspectObject: self receiver.
		 self restoreReceiverInspectorState.
		 ^self].
	isNewMethod := oldContext isNil
		or: [oldContext home method ~= (currentCompiledMethod := self selectedContext home method)].
	isNewMethod ifTrue:
		[contents := self selectedMessage.
		 self contentsChanged.
		 self pcRange].
	self changed: #contextStackIndex.
	self decorateButtons.
	
	newContext := self selectedContext.
	cviClass := newContext contextVariablesInspectorClass.
	(contextVariablesInspector isKindOf: cviClass) ifFalse:
		[contextVariablesInspector
			object: nil;
			changeInspectorClassTo: cviClass].
	contextVariablesInspector object == newContext
		ifFalse: [contextVariablesInspector object: newContext]
		ifTrue: [contextVariablesInspector update]. "ct: this fixes missing context variable updates when stepping from non-top context"
	self restoreContextVariablesInspectorState.
	receiverInspector context: newContext.
	receiverInspector object == self receiver
		ifFalse: [receiverInspector inspectCarefully: self receiver]
		ifTrue: [receiverInspector update].
	self restoreReceiverInspectorState.
	
	isNewMethod ifFalse:
		[self changed: #contentsSelection]

Debugger >> receiverInspector
receiverInspector
	"Answer the instance of Inspector that is providing a view of the 
	variables of the selected context's receiver."

	^receiverInspector

Debugger >> contextVariablesInspector
contextVariablesInspector
	"Answer the instance of Inspector that is providing a view of the 
	variables of the selected context."

	^contextVariablesInspector

Process class >> forMethod:receiver:arguments:runUntil:
forMethod: aCompiledMethod receiver: anObject arguments: someArguments runUntil: aConditionBlock

	^ self
		forBlock: [aCompiledMethod valueWithReceiver: anObject arguments: someArguments]
		runUntil: aConditionBlock

Process >> runUntil:
runUntil: aConditionBlock
	"Simulate code execution until the provided condition is fulfilled."
	
	[(aConditionBlock isNil
		or: [self isTerminated])
		or: [aConditionBlock value: self suspendedContext]
	] whileFalse: [self step].

	"If we are already at a send, this next call should do nothing."
	self stepToSendOrReturn.

Process >> step
step

	^Processor activeProcess
		evaluate: [suspendedContext := suspendedContext step]
		onBehalfOf: self

Process >> completeStep:
completeStep: aContext 
	"Resume self until aContext is on top, or if already on top, complete next step"

	| callee |
	self isTerminated ifTrue:
		[^ nil].
	self suspendedContext == aContext ifFalse:
		[^ self complete: (self calleeOf: aContext)].
	callee := self step.
	callee == aContext ifTrue: [^ callee].
	aContext isDead ifTrue: [^ self suspendedContext].  "returned"
	^ self complete: callee  "finish send"

Process >> restartTop
restartTop
	"Rollback top context and replace with new method.  Assumes self is suspended"

	suspendedContext privRefresh

Context >> runUntilErrorOrReturnFrom:
runUntilErrorOrReturnFrom: aSender 
	"ASSUMES aSender is a sender of self.  Execute self's stack until aSender returns or an unhandled exception is raised.  Return a pair containing the new top context and a possibly nil exception.  The exception is not nil if it was raised before aSender returned and it was not handled.  The exception is returned rather than openning the debugger, giving the caller the choice of how to handle it."
	"Self is run by jumping directly to it (the active process abandons thisContext and executes self).  However, before jumping to self we insert an ensure block under aSender that jumps back to thisContext when evaluated.  We also insert an exception handler under aSender that jumps back to thisContext when an unhandled exception is raised.  In either case, the inserted ensure and exception handler are removed once control jumps back to thisContext."

	| error ctxt here topContext |
	here := thisContext.

	"Insert ensure and exception handler contexts under aSender"
	error := nil.
	ctxt := aSender insertSender: (Context
		contextOn: UnhandledError do: [:ex |
			error ifNil: [
				error := ex exception.
				topContext := thisContext.
				ex resumeUnchecked: here jump]
			ifNotNil: [ex pass]
		]).
	ctxt := ctxt insertSender: (Context
		contextEnsure: [error ifNil: [
				topContext := thisContext.
				here jump]
		]).
	self jump.  "Control jumps to self"

	"Control resumes here once above ensure block or exception handler is executed"
	^ error ifNil: [
		"No error was raised, remove ensure context by stepping until popped"
		[ctxt isDead or: [topContext isNil]] whileFalse: [topContext := topContext stepToSenderOrNil].
		{topContext. nil}

	] ifNotNil: [
		"Error was raised, remove inserted above contexts then return signaler context"
		aSender terminateTo: ctxt sender.  "remove above ensure and handler contexts"
		{topContext. error}
	]

Inspector class >> openOn:withLabel:
openOn: anObject withLabel: label
	"Open an inspector with a specific label. Use this to set the inspector into context to explain why that object is inspected."

	^ ToolBuilder open: (self on: anObject) label: label

Browser class >> fullOnClass:selector:
fullOnClass: aClass selector: aSelector
	"Open a new full browser set to the class and selector."
	"Browser fullOnClass: Browser selector: #defaultWindowColor"

	^ self new
			setClass: aClass selector: aSelector;
			buildAndOpenFullBrowser

TestRunner class >> newForSuite:
newForSuite: aSuite

	| runner classes categories |
	runner := TestRunner new.
	classes := aSuite tests asSet collect: #class.
	categories := classes collect: #category.
	^ runner
		filterCategoriesBy: ((categories collect: #asString) asArray joinSeparatedBy: $;);
		filterClassesBy: ((classes collect: #asString) asArray joinSeparatedBy: $;);
		yourself

TestRunner >> runSuite:
runSuite: aTestSuite
	self basicRunSuite: aTestSuite do: [ :each | self runTest: each ].
	self updateResults



