Forráskód Böngészése

updated PN debugging interface to SCCD

Simon Van Mierlo 9 éve
szülő
commit
f241f945b8

+ 487 - 0
interface/PN/.code.alc

@@ -0,0 +1,487 @@
+include "primitives.alh"
+include "modelling.alh"
+include "object_operations.alh"
+include "transform.alh"
+include "constructors.alh"
+Boolean function reachability_graph(model : Element):
+	Element workset
+	Element transition_vectors_produce
+	Element transition_vectors_consume
+	Element all_transitions
+	Element all_transitions_original
+	Element enabled_transitions_set
+	Element tv
+	Element links
+	Element mappings
+	Element reachable_states
+	Element keys
+	Element enabled_transitions
+	Element enabled_copy
+	Element workset_copy
+	Element curr_workset_el
+	String transition
+	String new_transition
+	String tmp_transition
+	String state
+	String name
+	String link
+	String place
+	String key
+	String curr_transition
+	String bp_name
+	String curr_bp_name
+	String to_construct
+	String disable_on_trigger_str
+	String user_input_s
+	Integer link_weight
+	Integer initial
+	Integer state_id
+	Integer next_id
+	Integer user_input_i
+	Boolean possible
+	Boolean disable_on_trigger
+	Element all_places
+	Element dict_repr
+	Element new_dict_repr
+	Element work_unit
+	Element curr_bp
+	Element bp_keys
+	Boolean bp_triggered
+	Element reachable_keys_copy
+	Element curr_reachable
+	Element new_breakpoint
+	Element curr_bp_function
+	Element breakpoints
+	breakpoints = create_node()
+	Element cache
+	cache = create_node()
+	String user_input
+	user_input = ""
+	String mode
+	mode = "paused"
+	while (True):
+		output('{"msg_type": "enabled_commands", "commands": ["step", "continuous", "manual", "add_breakpoint"]}')
+		output('{"msg_type": "mode_change", "mode": "paused"}')
+		user_input = input()
+		if (user_input == "step"):
+			output('{"msg_type": "enabled_commands", "commands": ["step", "continuous", "manual"]}')
+			break!
+		if (user_input == "continuous"):
+			output('{"msg_type": "enabled_commands", "commands": []}')
+			output('{"msg_type": "mode_change", "mode": "running"}')
+			break!
+		if (user_input == "manual"):
+			output('{"msg_type": "enabled_commands", "commands": ["step", "continuous", "manual"]}')
+			break!
+		if (user_input == "add_breakpoint"):
+			bp_name = ""
+			while (bool_or(bp_name == "", dict_in(breakpoints, bp_name))):
+				output('{"msg_type": "input_required", "name": "breakpoint name", "type": "string"}')
+				bp_name = input()
+				output('{"msg_type": "input_required", "name": "disable on trigger?", "type": "boolean"}')
+				disable_on_trigger_str = input()
+				if (disable_on_trigger_str == "True"):
+					disable_on_trigger = True
+				else:
+					disable_on_trigger = False
+			output('{"msg_type": "input_required", "name": "breakpoint function", "type": "code"}')
+			new_breakpoint = create_node()
+			dict_add_fast(new_breakpoint, "function", construct_function())
+			dict_add_fast(new_breakpoint, "disable_on_trigger", disable_on_trigger)
+			dict_add_fast(new_breakpoint, "enabled", True)
+			dict_add_fast(breakpoints, bp_name, new_breakpoint)
+			output(('{"msg_type": "state_change", "state": "breakpoint_added", "breakpoint_name": "' + bp_name) + '"}')
+	mode = user_input
+	// Create a dictionary representation for each transition
+	transition_vectors_produce = create_node()
+	transition_vectors_consume = create_node()
+	all_transitions = allInstances(model, "PetriNet/Transition")
+	while (read_nr_out(all_transitions) > 0):
+		transition = set_pop(all_transitions)
+		String transition_name
+		transition_name = read_attribute(model, transition, "name")
+		tv = create_node()
+		links = allIncomingAssociationInstances(model, transition, "PetriNet/P2T")
+		while (read_nr_out(links) > 0):
+			link = set_pop(links)
+			name = reverseKeyLookup(model["model"], read_edge_src(model["model"][link]))
+			link_weight = read_attribute(model, link, "weight")
+			dict_add_fast(tv, name, link_weight)
+		dict_add_fast(transition_vectors_consume, transition_name, tv)
+		tv = create_node()
+		links = allOutgoingAssociationInstances(model, transition, "PetriNet/T2P")
+		while (read_nr_out(links) > 0):
+			link = set_pop(links)
+			name = reverseKeyLookup(model["model"], read_edge_dst(model["model"][link]))
+			link_weight = read_attribute(model, link, "weight")
+			dict_add_fast(tv, name, link_weight)
+		dict_add_fast(transition_vectors_produce, transition_name, tv)
+	workset = create_node()
+	all_places = allInstances(model, "PetriNet/Place")
+	dict_repr = create_node()
+	while (read_nr_out(all_places) > 0):
+		place = set_pop(all_places)
+		dict_add_fast(dict_repr, place, read_attribute(model, place, "tokens"))
+	all_transitions_original = allInstances(model, "PetriNet/Transition")
+	mappings = create_node()
+	state_id = 0
+	next_id = 1
+	reachable_states = create_node()
+	dict_add_fast(reachable_states, state_id, dict_repr)
+	dict_add_fast(mappings, state_id, create_node())
+	// And add in the model itself
+	state = instantiate_node(model, "ReachabilityGraph/InitialState", cast_i2s(state_id))
+	instantiate_attribute(model, state, "name", cast_i2s(state_id))
+	instantiate_attribute(model, state, "error", False)
+	keys = dict_keys(dict_repr)
+	while (read_nr_out(keys) > 0):
+		key = set_pop(keys)
+		place = instantiate_node(model, "ReachabilityGraph/Place", "")
+		instantiate_attribute(model, place, "name", read_attribute(model, key, "name"))
+		instantiate_attribute(model, place, "tokens", dict_repr[key])
+		instantiate_link(model, "ReachabilityGraph/Contains", "", state, place)
+	enabled_transitions = create_node()
+	dict_repr = reachable_states[state_id]
+	enabled_transitions_set = create_node()
+	dict_add(enabled_transitions, state_id, enabled_transitions_set)
+	// Compute how the PN behaves with this specific state
+	// For this, we fetch all transitions and check if they are enabled
+	all_transitions = set_copy(all_transitions_original)
+	while (read_nr_out(all_transitions) > 0):
+		transition = set_pop(all_transitions)
+		String transition_name
+		transition_name = read_attribute(model, transition, "name")
+		keys = dict_keys(transition_vectors_consume[transition_name])
+		possible = True
+		while (read_nr_out(keys) > 0):
+			key = set_pop(keys)
+			// Compare the values in the state with those consumed by the transition
+			if (integer_lt(dict_repr[key], transition_vectors_consume[transition_name][key])):
+				// Impossible transition, so discard this one
+				possible = False
+				break!
+		if (possible):
+			set_add(enabled_transitions_set, transition_name)
+	if (read_nr_out(enabled_transitions[state_id]) > 0):
+		set_add(workset, state_id)
+	if (bool_or(mode == "step", mode == "manual")):
+		output('{"msg_type": "state_change", "state": "initialized"}')
+		Element dict_values
+		Element all_values
+		String place
+		dict_values = create_node()
+		all_values = allAssociationDestinations(model, cast_i2s(state_id), "ReachabilityGraph/Contains")
+		while (read_nr_out(all_values) > 0):
+			place = set_pop(all_values)
+			dict_add(dict_values, read_attribute(model, place, "name"), cast_v2s(read_attribute(model, place, "tokens")))
+		String marking
+		marking = dict_to_string(dict_values)
+		output(((('{"msg_type": "node_added", "node_info": {"node_id": ' + cast_v2s(read_attribute(model, cast_i2s(state_id), "name"))) + ', "node_marking": ') + marking) + '}}')
+		if (mode == "step"):
+			mode = "paused"
+			output('{"msg_type": "mode_change", "mode": "paused"}')
+		while (True):
+			if (mode == "manual"):
+				break!
+			output("Please enter your command. Options: continuous, step, manual")
+			user_input = input()
+			if (user_input == "step"):
+				mode = user_input
+				output('{"msg_type": "enabled_commands", "commands": ["step", "continuous", "manual"]}')
+				break!
+			if (user_input == "continuous"):
+				mode = user_input
+				output('{"msg_type": "enabled_commands", "commands": []}')
+				break!
+			if (user_input == "manual"):
+				mode = user_input
+				output('{"msg_type": "enabled_commands", "commands": ["step", "continuous", "manual"]}')
+				break!
+	while (read_nr_out(workset) > 0):
+		if (mode == "manual"):
+			String markings
+			markings = '['
+			workset_copy = set_copy(workset)
+			while (read_nr_out(workset_copy) > 0):
+				curr_workset_el = set_pop(workset_copy)
+				markings = ((markings + '"') + cast_v2s(curr_workset_el)) + '"'
+				if (read_nr_out(workset_copy) > 0):
+					markings = markings + ", "
+			markings = markings + "]"
+			output(('{"msg_type": "unexplored_markings", "markings": ' + markings) + '}')
+			log("Please choose a marking.")
+			while (True):
+				user_input_s = input()
+				if (user_input_s == 'simulation_mode'):
+					mode = input()
+					if (mode != 'manual'):
+						state_id = set_pop(workset)
+						dict_repr = reachable_states[state_id]
+						enabled_transitions_set = enabled_transitions[state_id]
+						transition = set_pop(enabled_transitions_set)
+						if (mode == 'continuous'):
+							output('{"msg_type": "enabled_commands", "commands": []}')
+						if (mode == "step"):
+							output('{"msg_type": "enabled_commands", "commands": ["step", "continuous", "manual"]}')
+						break!
+				elif (user_input_s == 'selected_marking'):
+					user_input_i = cast_s2i(input())
+					if (set_in(workset, user_input_i)):
+						state_id = user_input_i
+						enabled_transitions_set = enabled_transitions[state_id]
+						String enabled_transitions_output
+						enabled_transitions_output = '['
+						enabled_copy = set_copy(enabled_transitions_set)
+						while (read_nr_out(enabled_copy) > 0):
+							curr_transition = set_pop(enabled_copy)
+							enabled_transitions_output = enabled_transitions_output + cast_v2s(curr_transition)
+							if (read_nr_out(enabled_copy) > 0):
+								enabled_transitions_output = enabled_transitions_output + ", "
+						enabled_transitions_output = enabled_transitions_output + "]"
+						output(('{"msg_type": "enabled_transitions", "transitions": ' + enabled_transitions_output) + '}')
+						output("Please choose an enabled transition or another marking.")
+				elif (user_input_s == 'selected_transition'):
+					set_remove(workset, state_id)
+					dict_repr = reachable_states[state_id]
+					user_input_s = input()
+					transition = user_input_s
+					set_remove(enabled_transitions_set, transition)
+					break!
+		else:
+			state_id = set_pop(workset)
+			dict_repr = reachable_states[state_id]
+			enabled_transitions_set = enabled_transitions[state_id]
+			transition = set_pop(enabled_transitions_set)
+		if (read_nr_out(enabled_transitions[state_id]) > 0):
+			set_add(workset, state_id)
+		new_dict_repr = dict_copy(dict_repr)
+		// Transition can execute, so compute and add the new state based on the consume/produce vectors
+		keys = dict_keys(transition_vectors_consume[transition])
+		while (read_nr_out(keys) > 0):
+			key = set_pop(keys)
+			dict_overwrite(new_dict_repr, key, integer_subtraction(new_dict_repr[key], transition_vectors_consume[transition][key]))
+		keys = dict_keys(transition_vectors_produce[transition])
+		while (read_nr_out(keys) > 0):
+			key = set_pop(keys)
+			dict_overwrite(new_dict_repr, key, integer_addition(new_dict_repr[key], transition_vectors_produce[transition][key]))
+		// Check if this state already has an associated ID
+		Integer other_state_id
+		Integer target_id
+		keys = dict_keys(reachable_states)
+		target_id = -1
+		Float start
+		while (read_nr_out(keys) > 0):
+			other_state_id = set_pop(keys)
+			if (dict_eq(reachable_states[other_state_id], new_dict_repr)):
+				target_id = other_state_id
+				break!
+		Boolean new_node
+		new_node = False
+		if (target_id == -1):
+			new_node = True
+			// New state
+			target_id = next_id
+			next_id = next_id + 1
+			// Add to all data structures
+			dict_add_fast(reachable_states, target_id, new_dict_repr)
+			dict_add_fast(mappings, target_id, create_node())
+			// And add in the model itself
+			state = instantiate_node(model, "ReachabilityGraph/State", cast_i2s(target_id))
+			instantiate_attribute(model, state, "name", cast_i2s(target_id))
+			instantiate_attribute(model, state, "error", False)
+			keys = dict_keys(new_dict_repr)
+			Element sub
+			String name
+			while (read_nr_out(keys) > 0):
+				key = set_pop(keys)
+				name = read_attribute(model, key, "name")
+				if (bool_not(dict_in(cache, name))):
+					dict_add_fast(cache, name, create_node())
+				sub = cache[name]
+				if (bool_not(dict_in(sub, new_dict_repr[key]))):
+					place = instantiate_node(model, "ReachabilityGraph/Place", "")
+					instantiate_attribute(model, place, "name", name)
+					instantiate_attribute(model, place, "tokens", new_dict_repr[key])
+					dict_add_fast(sub, new_dict_repr[key], place)
+				else:
+					place = sub[new_dict_repr[key]]
+				instantiate_link(model, "ReachabilityGraph/Contains", "", state, place)
+			// Compute how the PN behaves with this specific state
+			// For this, we fetch all transitions and check if they are enabled
+			enabled_transitions_set = create_node()
+			dict_add(enabled_transitions, target_id, enabled_transitions_set)
+			all_transitions = set_copy(all_transitions_original)
+			while (read_nr_out(all_transitions) > 0):
+				tmp_transition = set_pop(all_transitions)
+				String transition_name
+				transition_name = read_attribute(model, tmp_transition, "name")
+				keys = dict_keys(transition_vectors_consume[transition_name])
+				possible = True
+				while (read_nr_out(keys) > 0):
+					key = set_pop(keys)
+					// Compare the values in the state with those consumed by the transition
+					if (integer_lt(new_dict_repr[key], transition_vectors_consume[transition_name][key])):
+						// Impossible transition, so discard this one
+						possible = False
+						break!
+				if (possible):
+					set_add(enabled_transitions_set, transition_name)
+			if (read_nr_out(enabled_transitions[target_id]) > 0):
+				set_add(workset, target_id)
+		// Anyway, we have found a transition, which we should store
+		dict_add_fast(mappings[state_id], transition, target_id)
+		// And also store it in the model itself
+		new_transition = instantiate_link(model, "ReachabilityGraph/Transition", "", cast_i2s(state_id), cast_i2s(target_id))
+		instantiate_attribute(model, new_transition, "name", transition)
+		if (bool_or(mode == "step", mode == "manual")):
+			if (new_node):
+				Element dict_values
+				Element all_values
+				String place
+				dict_values = create_node()
+				all_values = allAssociationDestinations(model, cast_i2s(target_id), "ReachabilityGraph/Contains")
+				while (read_nr_out(all_values) > 0):
+					place = set_pop(all_values)
+					dict_add(dict_values, read_attribute(model, place, "name"), read_attribute(model, place, "tokens"))
+				String marking
+				marking = dict_to_string(dict_values)
+				output(((('{"msg_type": "node_added", "node_info": {"node_id": ' + cast_v2s(read_attribute(model, cast_i2s(target_id), "name"))) + ', "node_marking": ') + marking) + '}}')
+			String link_output
+			link_output = '{"msg_type": "link_added", "link_info": {'
+			link_output = link_output + '"transition": '
+			link_output = link_output + cast_v2s(transition)
+			link_output = link_output + ', "transition_id": '
+			link_output = link_output + cast_v2s(new_transition)
+			link_output = link_output + ', "source": "'
+			link_output = link_output + cast_v2s(state_id)
+			link_output = link_output + '", "target": "'
+			link_output = link_output + cast_v2s(target_id)
+			link_output = link_output + '"}}'
+			output(link_output)
+			if (mode == "step"):
+				mode = "paused"
+				output('{"msg_type": "mode_change", "mode": "paused"}')
+			output('{"msg_type": "state_change", "state": "step_done"}')
+		bp_keys = dict_keys(breakpoints)
+		bp_triggered = False
+		while (read_nr_out(bp_keys) > 0):
+			curr_bp_name = set_pop(bp_keys)
+			curr_bp = breakpoints[curr_bp_name]
+			curr_bp_function = curr_bp["function"]
+			if (bool_and(curr_bp["enabled"], curr_bp_function(reachable_states, mappings))):
+				output(('{"msg_type": "state_change", "state": "breakpoint_triggered", "breakpoint_name": "' + curr_bp_name) + '"}')
+				bp_triggered = True
+				log(curr_bp["disable_on_trigger"])
+				if (curr_bp["disable_on_trigger"]):
+					dict_delete(curr_bp, "enabled")
+					dict_add_fast(curr_bp, "enabled", False)
+		if (bp_triggered):
+			Element all_states
+			Element curr_state
+			all_states = allInstances(model, "ReachabilityGraph/State")
+			to_construct = '{"msg_type": "reachable_nodes", "nodes": ['
+			while (read_nr_out(all_states) > 0):
+				curr_state = set_pop(all_states)
+				to_construct = to_construct + '{"node_id": '
+				to_construct = to_construct + cast_v2s(curr_state)
+				to_construct = to_construct + ',  "node_marking": '
+				Element dict_values
+				Element all_values
+				String place
+				dict_values = create_node()
+				all_values = allAssociationDestinations(model, curr_state, "ReachabilityGraph/Contains")
+				while (set_len(all_values) > 0):
+					place = set_pop(all_values)
+					dict_add(dict_values, read_attribute(model, place, "name"), read_attribute(model, place, "tokens"))
+				to_construct = to_construct + dict_to_string(dict_values)
+				to_construct = to_construct + "}"
+				if (read_nr_out(all_states) > 0):
+					to_construct = to_construct + ', '
+			to_construct = to_construct + ']}'
+			output(to_construct)
+			Element all_links
+			Element curr_link
+			all_links = allInstances(model, "ReachabilityGraph/Transition")
+			to_construct = '{"msg_type": "node_links", "links": ['
+			while (read_nr_out(all_links) > 0):
+				curr_link = set_pop(all_links)
+				to_construct = to_construct + '{"transition": '
+				to_construct = to_construct + cast_v2s(read_attribute(model, curr_link, "name"))
+				to_construct = to_construct + ', "transition_id": '
+				to_construct = to_construct + cast_v2s(curr_link)
+				to_construct = to_construct + ', "source": '
+				to_construct = to_construct + cast_v2s(reverseKeyLookup(model["model"], read_edge_src(model["model"][curr_link])))
+				to_construct = to_construct + ', "target": '
+				to_construct = to_construct + cast_v2s(reverseKeyLookup(model["model"], read_edge_dst(model["model"][curr_link])))
+				to_construct = to_construct + '}'
+				if (read_nr_out(all_links) > 0):
+					to_construct = to_construct + ', '
+			to_construct = to_construct + ']}'
+			output(to_construct)
+			output('{"msg_type": "enabled_commands", "commands": ["step", "continuous", "manual"]}')
+			if (bool_not(mode == "paused")):
+				mode = "paused"
+				output('{"msg_type": "mode_change", "mode": "paused"}')
+		if (bool_not(mode == "continuous")):
+			while (True):
+				if (mode == "manual"):
+					break!
+				output("Please enter your command. Options: continuous, step, manual")
+				user_input = input()
+				if (user_input == "step"):
+					mode = user_input
+					output('{"msg_type": "enabled_commands", "commands": ["step", "continuous", "manual"]}')
+					break!
+				if (user_input == "continuous"):
+					mode = user_input
+					output('{"msg_type": "enabled_commands", "commands": []}')
+					break!
+				if (user_input == "manual"):
+					mode = user_input
+					output('{"msg_type": "enabled_commands", "commands": ["step", "continuous", "manual"]}')
+					break!
+	Element all_states
+	Element curr_state
+	all_states = allInstances(model, "ReachabilityGraph/State")
+	to_construct = '{"msg_type": "reachable_nodes", "nodes": ['
+	while (read_nr_out(all_states) > 0):
+		curr_state = set_pop(all_states)
+		to_construct = to_construct + '{"node_id": '
+		to_construct = to_construct + cast_v2s(curr_state)
+		to_construct = to_construct + ',  "node_marking": '
+		Element dict_values
+		Element all_values
+		String place
+		dict_values = create_node()
+		all_values = allAssociationDestinations(model, curr_state, "ReachabilityGraph/Contains")
+		while (set_len(all_values) > 0):
+			place = set_pop(all_values)
+			dict_add(dict_values, read_attribute(model, place, "name"), read_attribute(model, place, "tokens"))
+		to_construct = to_construct + dict_to_string(dict_values)
+		to_construct = to_construct + "}"
+		if (read_nr_out(all_states) > 0):
+			to_construct = to_construct + ', '
+	to_construct = to_construct + ']}'
+	output(to_construct)
+	Element all_links
+	Element curr_link
+	all_links = allInstances(model, "ReachabilityGraph/Transition")
+	to_construct = '{"msg_type": "node_links", "links": ['
+	while (read_nr_out(all_links) > 0):
+		curr_link = set_pop(all_links)
+		to_construct = to_construct + '{"transition": '
+		to_construct = to_construct + cast_v2s(read_attribute(model, curr_link, "name"))
+		to_construct = to_construct + ', "transition_id": '
+		to_construct = to_construct + cast_v2s(curr_link)
+		to_construct = to_construct + ', "source": '
+		to_construct = to_construct + cast_v2s(reverseKeyLookup(model["model"], read_edge_src(model["model"][curr_link])))
+		to_construct = to_construct + ', "target": '
+		to_construct = to_construct + cast_v2s(reverseKeyLookup(model["model"], read_edge_dst(model["model"][curr_link])))
+		to_construct = to_construct + '}'
+		if (read_nr_out(all_links) > 0):
+			to_construct = to_construct + ', '
+	to_construct = to_construct + ']}'
+	output(to_construct)
+	output('{"msg_type": "mode_change", "mode": "finished"}')
+	log("# reachable states: " + cast_v2s(next_id))
+	return True!

+ 53 - 0
interface/PN/.model.mvc

@@ -0,0 +1,53 @@
+include "primitives.alh"
+include "object_operations.alh"
+include "modelling.alh"
+SimpleAttribute String {}
+SimpleAttribute Natural {}
+SimpleAttribute Boolean {}
+Class State {
+	name : String
+	error : Boolean
+}
+Class InitialState : State {
+	lower_cardinality = 1
+	upper_cardinality = 1
+}
+Class Place {
+	name : String
+	tokens : Natural
+}
+Association Transition (State, State) {
+	name : String
+}
+Association Contains (State, Place) {}
+GlobalConstraint {
+	global_constraint = $
+		String function constraint(model : Element):
+			Element states
+			Element places
+			String state
+			String place
+			Element expected
+			Element got
+			states = allInstances(model, "State")
+			if (set_len(states) > 0):
+				expected = create_node()
+				state = set_pop(states)
+				places = allAssociationDestinations(model, state, "Contains")
+				while (set_len(places)):
+					place = set_pop(places)
+					set_add(expected, read_attribute(model, place, "name"))
+			else:
+				return "OK"!
+			while (set_len(states) > 0):
+				got = create_node()
+				state = set_pop(states)
+				places = allAssociationDestinations(model, state, "Contains")
+				while (set_len(places) > 0):
+					place = set_pop(places)
+					set_add(got, read_attribute(model, place, "name"))
+				if (bool_not(set_equality(got, expected))):
+					return "States don't all agree on the set of places"!
+			return "OK"!
+		$
+}

+ 12 - 0
interface/PN/default_bp.py

@@ -0,0 +1,12 @@
+include "primitives.alh"
+
+Boolean function bp_1(reachable_states: Element, mappings: Element, place_names_to_ids: Element):
+    Element keys
+    Element node
+    String msg
+    keys = dict_keys(reachable_states)
+    while (read_nr_out(keys) > 0):
+        node = reachable_states[set_pop(keys)]
+        if (integer_gt(node[place_names_to_ids["produced"]], 0)):
+            return True!
+    return False!

+ 371 - 0
interface/PN/http_client.py

@@ -0,0 +1,371 @@
+"""
+Generated by Statechart compiler by Glenn De Jonghe, Joeri Exelmans, Simon Van Mierlo, and Yentl Van Tendeloo (for the inspiration)
+
+Date:   Fri Aug 25 15:48:04 2017
+
+Model author: Yentl Van Tendeloo
+Model name:   HTTP client
+Model description:
+HTTP client.
+"""
+
+from sccd.runtime.statecharts_core import *
+import uuid
+
+# package "HTTP client"
+
+class HTTPClient(RuntimeClassBase):
+    def __init__(self, controller):
+        RuntimeClassBase.__init__(self, controller)
+        
+        self.semantics.big_step_maximality = StatechartSemantics.TakeMany
+        self.semantics.internal_event_lifeline = StatechartSemantics.Queue
+        self.semantics.input_event_lifeline = StatechartSemantics.FirstComboStep
+        self.semantics.priority = StatechartSemantics.SourceParent
+        self.semantics.concurrency = StatechartSemantics.Single
+        
+        # build Statechart structure
+        self.build_statechart_structure()
+        
+        # call user defined constructor
+        HTTPClient.user_defined_constructor(self)
+    
+    def user_defined_constructor(self):
+        self.socket = None
+        self.received_data = ""
+        self.send_data = ""
+        self.queue = []
+        self.IDs = []
+    
+    def user_defined_destructor(self):
+        pass
+    
+    
+    # builds Statechart structure
+    def build_statechart_structure(self):
+        
+        # state <root>
+        self.states[""] = State(0, "", self)
+        
+        # state /init
+        self.states["/init"] = State(1, "/init", self)
+        self.states["/init"].setEnter(self._init_enter)
+        
+        # state /waiting
+        self.states["/waiting"] = State(2, "/waiting", self)
+        self.states["/waiting"].setEnter(self._waiting_enter)
+        
+        # state /connecting
+        self.states["/connecting"] = State(3, "/connecting", self)
+        self.states["/connecting"].setEnter(self._connecting_enter)
+        self.states["/connecting"].setExit(self._connecting_exit)
+        
+        # state /connecting/connecting
+        self.states["/connecting/connecting"] = State(4, "/connecting/connecting", self)
+        self.states["/connecting/connecting"].setEnter(self._connecting_connecting_enter)
+        
+        # state /connecting/cooldown
+        self.states["/connecting/cooldown"] = State(5, "/connecting/cooldown", self)
+        self.states["/connecting/cooldown"].setEnter(self._connecting_cooldown_enter)
+        self.states["/connecting/cooldown"].setExit(self._connecting_cooldown_exit)
+        
+        # state /connected
+        self.states["/connected"] = ParallelState(6, "/connected", self)
+        
+        # state /connected/listening
+        self.states["/connected/listening"] = State(7, "/connected/listening", self)
+        
+        # state /connected/listening/listen
+        self.states["/connected/listening/listen"] = State(8, "/connected/listening/listen", self)
+        self.states["/connected/listening/listen"].setEnter(self._connected_listening_listen_enter)
+        
+        # state /connected/listening/close
+        self.states["/connected/listening/close"] = State(9, "/connected/listening/close", self)
+        
+        # state /connected/sending
+        self.states["/connected/sending"] = State(10, "/connected/sending", self)
+        
+        # state /connected/sending/waiting_for_data
+        self.states["/connected/sending/waiting_for_data"] = State(11, "/connected/sending/waiting_for_data", self)
+        
+        # state /connected/sending/transferring
+        self.states["/connected/sending/transferring"] = State(12, "/connected/sending/transferring", self)
+        
+        # state /connected/queueing
+        self.states["/connected/queueing"] = State(13, "/connected/queueing", self)
+        
+        # state /connected/queueing/queueing
+        self.states["/connected/queueing/queueing"] = State(14, "/connected/queueing/queueing", self)
+        self.states["/connected/queueing/queueing"].setEnter(self._connected_queueing_queueing_enter)
+        
+        # state /connected/parsing
+        self.states["/connected/parsing"] = State(15, "/connected/parsing", self)
+        
+        # state /connected/parsing/wait_for_header
+        self.states["/connected/parsing/wait_for_header"] = State(16, "/connected/parsing/wait_for_header", self)
+        
+        # state /connected/parsing/wait_for_payload
+        self.states["/connected/parsing/wait_for_payload"] = State(17, "/connected/parsing/wait_for_payload", self)
+        
+        # add children
+        self.states[""].addChild(self.states["/init"])
+        self.states[""].addChild(self.states["/waiting"])
+        self.states[""].addChild(self.states["/connecting"])
+        self.states[""].addChild(self.states["/connected"])
+        self.states["/connecting"].addChild(self.states["/connecting/connecting"])
+        self.states["/connecting"].addChild(self.states["/connecting/cooldown"])
+        self.states["/connected"].addChild(self.states["/connected/listening"])
+        self.states["/connected"].addChild(self.states["/connected/sending"])
+        self.states["/connected"].addChild(self.states["/connected/queueing"])
+        self.states["/connected"].addChild(self.states["/connected/parsing"])
+        self.states["/connected/listening"].addChild(self.states["/connected/listening/listen"])
+        self.states["/connected/listening"].addChild(self.states["/connected/listening/close"])
+        self.states["/connected/sending"].addChild(self.states["/connected/sending/waiting_for_data"])
+        self.states["/connected/sending"].addChild(self.states["/connected/sending/transferring"])
+        self.states["/connected/queueing"].addChild(self.states["/connected/queueing/queueing"])
+        self.states["/connected/parsing"].addChild(self.states["/connected/parsing/wait_for_header"])
+        self.states["/connected/parsing"].addChild(self.states["/connected/parsing/wait_for_payload"])
+        self.states[""].fixTree()
+        self.states[""].default_state = self.states["/init"]
+        self.states["/connecting"].default_state = self.states["/connecting/connecting"]
+        self.states["/connected/listening"].default_state = self.states["/connected/listening/listen"]
+        self.states["/connected/sending"].default_state = self.states["/connected/sending/waiting_for_data"]
+        self.states["/connected/queueing"].default_state = self.states["/connected/queueing/queueing"]
+        self.states["/connected/parsing"].default_state = self.states["/connected/parsing/wait_for_header"]
+        
+        # transition /init
+        _init_0 = Transition(self, self.states["/init"], [self.states["/waiting"]])
+        _init_0.setAction(self._init_0_exec)
+        _init_0.setTrigger(Event("created_socket", "socket_in"))
+        _init_0.setGuard(self._init_0_guard)
+        self.states["/init"].addTransition(_init_0)
+        
+        # transition /waiting
+        _waiting_0 = Transition(self, self.states["/waiting"], [self.states["/connecting"]])
+        _waiting_0.setAction(self._waiting_0_exec)
+        _waiting_0.setTrigger(Event("connect", "request_in"))
+        self.states["/waiting"].addTransition(_waiting_0)
+        
+        # transition /connecting/connecting
+        _connecting_connecting_0 = Transition(self, self.states["/connecting/connecting"], [self.states["/connecting/cooldown"]])
+        _connecting_connecting_0.setTrigger(Event("error_socket", "socket_in"))
+        self.states["/connecting/connecting"].addTransition(_connecting_connecting_0)
+        _connecting_connecting_1 = Transition(self, self.states["/connecting/connecting"], [self.states["/connected"]])
+        _connecting_connecting_1.setAction(self._connecting_connecting_1_exec)
+        _connecting_connecting_1.setTrigger(Event("connected_socket", "socket_in"))
+        _connecting_connecting_1.setGuard(self._connecting_connecting_1_guard)
+        self.states["/connecting/connecting"].addTransition(_connecting_connecting_1)
+        
+        # transition /connecting/cooldown
+        _connecting_cooldown_0 = Transition(self, self.states["/connecting/cooldown"], [self.states["/connecting/connecting"]])
+        _connecting_cooldown_0.setTrigger(Event("_1after"))
+        self.states["/connecting/cooldown"].addTransition(_connecting_cooldown_0)
+        
+        # transition /connected/listening/listen
+        _connected_listening_listen_0 = Transition(self, self.states["/connected/listening/listen"], [self.states["/connected/listening/listen"]])
+        _connected_listening_listen_0.setAction(self._connected_listening_listen_0_exec)
+        _connected_listening_listen_0.setTrigger(Event("received_socket", "socket_in"))
+        _connected_listening_listen_0.setGuard(self._connected_listening_listen_0_guard)
+        self.states["/connected/listening/listen"].addTransition(_connected_listening_listen_0)
+        _connected_listening_listen_1 = Transition(self, self.states["/connected/listening/listen"], [self.states["/connected/listening/close"]])
+        _connected_listening_listen_1.setTrigger(Event("received_socket", "socket_in"))
+        _connected_listening_listen_1.setGuard(self._connected_listening_listen_1_guard)
+        self.states["/connected/listening/listen"].addTransition(_connected_listening_listen_1)
+        
+        # transition /connected/sending/waiting_for_data
+        _connected_sending_waiting_for_data_0 = Transition(self, self.states["/connected/sending/waiting_for_data"], [self.states["/connected/sending/transferring"]])
+        _connected_sending_waiting_for_data_0.setAction(self._connected_sending_waiting_for_data_0_exec)
+        _connected_sending_waiting_for_data_0.setTrigger(None)
+        _connected_sending_waiting_for_data_0.setGuard(self._connected_sending_waiting_for_data_0_guard)
+        self.states["/connected/sending/waiting_for_data"].addTransition(_connected_sending_waiting_for_data_0)
+        
+        # transition /connected/sending/transferring
+        _connected_sending_transferring_0 = Transition(self, self.states["/connected/sending/transferring"], [self.states["/connected/sending/waiting_for_data"]])
+        _connected_sending_transferring_0.setAction(self._connected_sending_transferring_0_exec)
+        _connected_sending_transferring_0.setTrigger(Event("sent_socket", "socket_in"))
+        _connected_sending_transferring_0.setGuard(self._connected_sending_transferring_0_guard)
+        self.states["/connected/sending/transferring"].addTransition(_connected_sending_transferring_0)
+        
+        # transition /connected/queueing/queueing
+        _connected_queueing_queueing_0 = Transition(self, self.states["/connected/queueing/queueing"], [self.states["/connected/queueing/queueing"]])
+        _connected_queueing_queueing_0.setAction(self._connected_queueing_queueing_0_exec)
+        _connected_queueing_queueing_0.setTrigger(Event("HTTP_input", "request_in"))
+        self.states["/connected/queueing/queueing"].addTransition(_connected_queueing_queueing_0)
+        
+        # transition /connected/parsing/wait_for_header
+        _connected_parsing_wait_for_header_0 = Transition(self, self.states["/connected/parsing/wait_for_header"], [self.states["/connected/parsing/wait_for_payload"]])
+        _connected_parsing_wait_for_header_0.setAction(self._connected_parsing_wait_for_header_0_exec)
+        _connected_parsing_wait_for_header_0.setTrigger(None)
+        _connected_parsing_wait_for_header_0.setGuard(self._connected_parsing_wait_for_header_0_guard)
+        self.states["/connected/parsing/wait_for_header"].addTransition(_connected_parsing_wait_for_header_0)
+        
+        # transition /connected/parsing/wait_for_payload
+        _connected_parsing_wait_for_payload_0 = Transition(self, self.states["/connected/parsing/wait_for_payload"], [self.states["/connected/parsing/wait_for_header"]])
+        _connected_parsing_wait_for_payload_0.setAction(self._connected_parsing_wait_for_payload_0_exec)
+        _connected_parsing_wait_for_payload_0.setTrigger(None)
+        _connected_parsing_wait_for_payload_0.setGuard(self._connected_parsing_wait_for_payload_0_guard)
+        self.states["/connected/parsing/wait_for_payload"].addTransition(_connected_parsing_wait_for_payload_0)
+        _connected_parsing_wait_for_payload_1 = Transition(self, self.states["/connected/parsing/wait_for_payload"], [self.states["/connected/parsing/wait_for_header"]])
+        _connected_parsing_wait_for_payload_1.setAction(self._connected_parsing_wait_for_payload_1_exec)
+        _connected_parsing_wait_for_payload_1.setTrigger(None)
+        _connected_parsing_wait_for_payload_1.setGuard(self._connected_parsing_wait_for_payload_1_guard)
+        self.states["/connected/parsing/wait_for_payload"].addTransition(_connected_parsing_wait_for_payload_1)
+        
+        # transition /connecting
+        _connecting_0 = Transition(self, self.states["/connecting"], [self.states["/waiting"]])
+        _connecting_0.setAction(self._connecting_0_exec)
+        _connecting_0.setTrigger(Event("_0after"))
+        self.states["/connecting"].addTransition(_connecting_0)
+    
+    def _connecting_enter(self):
+        self.addTimer(0, self.timeout)
+    
+    def _connecting_exit(self):
+        self.removeTimer(0)
+    
+    def _init_enter(self):
+        self.ID = str(uuid.uuid4())
+        self.big_step.outputEvent(Event("create_socket", "socket_out", [self.ID]))
+    
+    def _waiting_enter(self):
+        self.big_step.outputEvent(Event("http_client_initialized", "request_out", []))
+    
+    def _connecting_connecting_enter(self):
+        self.big_step.outputEvent(Event("connect_socket", "socket_out", [self.socket, self.address]))
+    
+    def _connecting_cooldown_enter(self):
+        self.addTimer(1, 0.1)
+    
+    def _connecting_cooldown_exit(self):
+        self.removeTimer(1)
+    
+    def _connected_listening_listen_enter(self):
+        self.big_step.outputEvent(Event("recv_socket", "socket_out", [self.socket]))
+    
+    def _connected_queueing_queueing_enter(self):
+        pass
+    
+    def _connecting_0_exec(self, parameters):
+        self.big_step.outputEvent(Event("http_client_timeout", "request_out", []))
+    
+    def _init_0_exec(self, parameters):
+        socket = parameters[0]
+        ID = parameters[1]
+        self.socket = socket
+    
+    def _init_0_guard(self, parameters):
+        socket = parameters[0]
+        ID = parameters[1]
+        return self.ID == ID
+    
+    def _waiting_0_exec(self, parameters):
+        address = parameters[0]
+        timeout = parameters[1]
+        self.address = address
+        self.timeout = timeout
+    
+    def _connecting_connecting_1_exec(self, parameters):
+        socket = parameters[0]
+        self.big_step.outputEvent(Event("http_client_ready", "request_out", []))
+    
+    def _connecting_connecting_1_guard(self, parameters):
+        socket = parameters[0]
+        return self.socket == socket
+    
+    def _connected_listening_listen_0_exec(self, parameters):
+        socket = parameters[0]
+        data = parameters[1]
+        self.received_data += data
+    
+    def _connected_listening_listen_0_guard(self, parameters):
+        socket = parameters[0]
+        data = parameters[1]
+        return (self.socket == socket) and (len(data) > 0)
+    
+    def _connected_listening_listen_1_guard(self, parameters):
+        socket = parameters[0]
+        data = parameters[1]
+        return (self.socket == socket) and (len(data) == 0)
+    
+    def _connected_sending_waiting_for_data_0_exec(self, parameters):
+        self.big_step.outputEvent(Event("send_socket", "socket_out", [self.socket, self.send_data]))
+    
+    def _connected_sending_waiting_for_data_0_guard(self, parameters):
+        return len(self.send_data) > 0
+    
+    def _connected_sending_transferring_0_exec(self, parameters):
+        socket = parameters[0]
+        sent_bytes = parameters[1]
+        self.send_data = self.send_data[sent_bytes:]
+    
+    def _connected_sending_transferring_0_guard(self, parameters):
+        socket = parameters[0]
+        sent_bytes = parameters[1]
+        return self.socket == socket
+    
+    def _connected_queueing_queueing_0_exec(self, parameters):
+        data = parameters[0]
+        ID = parameters[1]
+        self.send_data += "POST / HTTP/1.0\r\n"
+        self.send_data += "Content-Length: %i\r\n" % len(str(data))
+        self.send_data += "\r\n"
+        self.send_data += data
+        self.IDs.append(ID)
+    
+    def _connected_parsing_wait_for_header_0_exec(self, parameters):
+        header, self.received_data = self.received_data.split("\r\n\r\n", 1)
+        header = header.lower()
+        if "content-length" in header:
+            _, after = header.split("content-length:", 1)
+            after, _ = after.split("\r\n", 1)
+            after = after.strip()
+            self.length = int(after)
+        else:
+            self.length = float('inf')
+    
+    def _connected_parsing_wait_for_header_0_guard(self, parameters):
+        return '\r\n\r\n' in self.received_data
+    
+    def _connected_parsing_wait_for_payload_0_exec(self, parameters):
+        data = self.received_data[:self.length]
+        self.received_data = self.received_data[self.length:]
+        self.big_step.outputEvent(Event("HTTP_output", "request_out", [data, self.IDs.pop(0)]))
+    
+    def _connected_parsing_wait_for_payload_0_guard(self, parameters):
+        return len(self.received_data) >= self.length and self.IDs[0] is not None
+    
+    def _connected_parsing_wait_for_payload_1_exec(self, parameters):
+        # Drop data
+        self.received_data = self.received_data[self.length:]
+        self.IDs.pop(0)
+    
+    def _connected_parsing_wait_for_payload_1_guard(self, parameters):
+        return len(self.received_data) >= self.length and self.IDs[0] is None
+    
+    def initializeStatechart(self):
+        # enter default state
+        self.default_targets = self.states["/init"].getEffectiveTargetStates()
+        RuntimeClassBase.initializeStatechart(self)
+
+class ObjectManager(ObjectManagerBase):
+    def __init__(self, controller):
+        ObjectManagerBase.__init__(self, controller)
+    
+    def instantiate(self, class_name, construct_params):
+        if class_name == "HTTPClient":
+            instance = HTTPClient(self.controller)
+            instance.associations = {}
+        else:
+            raise Exception("Cannot instantiate class " + class_name)
+        return instance
+
+class Controller(ThreadsControllerBase):
+    def __init__(self, keep_running = None, behind_schedule_callback = None):
+        if keep_running == None: keep_running = True
+        if behind_schedule_callback == None: behind_schedule_callback = None
+        ThreadsControllerBase.__init__(self, ObjectManager(self), keep_running, behind_schedule_callback)
+        self.addInputPort("socket_in")
+        self.addInputPort("request_in")
+        self.addOutputPort("socket_out")
+        self.addOutputPort("request_out")
+        self.object_manager.createInstance("HTTPClient", [])

A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 3269 - 0
interface/PN/interface.py


A különbségek nem kerülnek megjelenítésre, a fájl túl nagy
+ 2111 - 0
interface/PN/interface.xml


+ 1 - 1
interface/PN/main.py

@@ -364,7 +364,7 @@ class MarkingToMarkingVis:
         y_coords = sorted([self.m1.y+self.m1.get_height(), self.m2.y])
         self.canvas.coords(self.text, x_coords[0] + (x_coords[1] - x_coords[0]) / 2, y_coords[0] + (y_coords[1] - y_coords[0]) / 2)
 
-class PNInterface(tk.Tk):        
+class PNInterface(tk.Tk):
     MAX_WIDTH = 8192
     MAX_HEIGHT = 8192
     

+ 69 - 0
interface/PN/model.mvc

@@ -0,0 +1,69 @@
+Place Place_5 {
+	tokens = 0
+	name = "consuming"
+}
+Place Place_1 {
+	tokens = 3
+	name = "maximum items"
+}
+Place Place_3 {
+	tokens = 0
+	name = "produced"
+}
+Place Place_2 {
+	tokens = 0
+	name = "producing"
+}
+Place Place_4 {
+	tokens = 2
+	name = "waiting"
+}
+Place Place_0 {
+	tokens = 3
+	name = "free"
+}
+Transition Transition_3 {
+	name = "end consuming"
+}
+Transition Transition_0 {
+	name = "start producing"
+}
+Transition Transition_2 {
+	name = "start consuming"
+}
+Transition Transition_1 {
+	name = "end producing"
+}
+P2T (Place_0, Transition_0) {
+	weight = 1
+}
+P2T (Place_2, Transition_1) {
+	weight = 1
+}
+P2T (Place_4, Transition_2) {
+	weight = 1
+}
+P2T (Place_3, Transition_2) {
+	weight = 1
+}
+P2T (Place_1, Transition_1) {
+	weight = 1
+}
+P2T (Place_5, Transition_3) {
+	weight = 1
+}
+T2P (Transition_1, Place_3) {
+	weight = 1
+}
+T2P (Transition_2, Place_5) {
+	weight = 1
+}
+T2P (Transition_3, Place_4) {
+	weight = 1
+}
+T2P (Transition_0, Place_2) {
+	weight = 1
+}
+T2P (Transition_1, Place_0) {
+	weight = 1
+}

+ 249 - 228
interface/PN/modelverse.py

@@ -1,13 +1,13 @@
 import urllib
-import urllib2
 import json
 import random
-from urllib2 import URLError
 import sys
 import time
 import threading
+import uuid
 
-COMPILER_PATH = "../../interface/HUTN"
+import sccd.runtime.socket2event as socket2event
+from sccd.runtime.statecharts_core import Event
 
 MODE_UNCONNECTED = 0
 MODE_UNAUTHORIZED = 1
@@ -17,10 +17,6 @@ MODE_DIALOG = 4
 MODE_MANUAL = 5
 MODE_SERVICE = 6
 
-# Bind to the compiler (might have to update path manually!)
-sys.path.append(COMPILER_PATH)
-from hutn_compiler.compiler import main as do_compile
-
 # Exceptions
 class ModelverseException(Exception):
     pass
@@ -60,12 +56,59 @@ class UnknownMetamodellingHierarchy(ModelverseException):
 
 # Helper functions and configuration: do not use yourself!
 taskname = None
-address = None
-last_output = None
 mode = MODE_UNCONNECTED
 prev_mode = None
 current_model = None
 registered_metamodels = {}
+outputs = {}
+ctrl_input = None
+ctrl_output = None
+
+def _output_thread(controller, outp, task):
+    req_out = controller.addOutputListener("request_out")
+    my_id = str(uuid.uuid4())
+
+    try:
+        while 1:
+            controller.addInput(Event("HTTP_input", "request_in", [urllib.urlencode({"op": "get_output", "taskname": task}), my_id]))
+            event = req_out.fetch(-1)
+
+            if event.parameters[1] == my_id:
+                outp[task].append(json.loads(event.parameters[0]))
+    except:
+        raise
+
+def _exec_on_statechart(statechart):
+    def _exec_sc(controller, inport, outport):
+        global taskname
+        op = controller.addOutputListener(outport)
+
+        while 1:
+            if len(outputs[taskname]) > 1:
+                # Is an output message of the Mv, so put it in the SC
+                del outputs[taskname][0]
+                output_event = outputs[taskname][0]
+
+                if output_event == "Success" or output_event == "Failure":
+                    # Is a stop event!
+                    controller.addInput(Event("terminate", inport, []))
+                    break
+                else:
+                    # Is just a normal event!
+                    controller.addInput(Event("input", inport, [output_event]))
+
+            input_event = op.fetch(0)
+            if input_event is not None:
+                # Expand the event and make it HTTP input
+                _input(input_event.parameters)
+                
+            time.sleep(0.02)
+        
+    thrd = threading.Thread(target=_exec_sc, args=statechart)
+    thrd.daemon = True
+    thrd.start()
+
+    return None
 
 def _get_metamodel(model):
     global registered_metamodels
@@ -114,77 +157,47 @@ def _goto_mode(new_mode, model_name=None):
         # Go to a mode that we have no automatic transfer to: raise exception
         raise InvalidMode("Required mode: %s, current mode: %s" % (new_mode, mode))
 
-def _input(value, port=None):
+def _input(value, task=None):
     # Ugly json encoding of primitives
     #print("[IN] %s" % value)
-    if port is None:
-        port = taskname
+    if task is None:
+        task = taskname
     if isinstance(value, type([])):
         value = json.dumps(value)
-        urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "data": value, "taskname": port}))).read()
+        ctrl_input.addInput(Event("HTTP_input", "request_in", [urllib.urlencode({"op": "set_input", "taskname": task, "data": value}), None]))
     else:
         value = json.dumps(value)
-        #print("Set input: " + str(value))
-        urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": value, "taskname": port}))).read()
+        ctrl_input.addInput(Event("HTTP_input", "request_in", [urllib.urlencode({"op": "set_input", "taskname": task, "value": value}), None]))
 
 def _input_raw(value, taskname):
     # Ugly json encoding of primitives
-    urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": value, "taskname": taskname}))).read()
-
-    #TODO check that this is actually a Modelverse!
-
-def _compile_AL(code):
-    # Compile an action language file and send the compiled code
-    code_fragments = code.split("\n")
-    code_fragments = [i for i in code_fragments if i.strip() != ""]
-    code_fragments = [i.replace("    ", "\t") for i in code_fragments]
-    initial_tabs = min([len(i) - len(i.lstrip("\t")) for i in code_fragments])
-    code_fragments = [i[initial_tabs:] for i in code_fragments]
-    code_fragments.append("")
-    code = "\n".join(code_fragments)
-
-    with open(".code.alc", "w") as f:
-        f.write(code)
-        f.flush()
-
-    compiled = do_compile(".code.alc", COMPILER_PATH + "/grammars/actionlanguage.g", "CS")
-    return compiled
-
-def _compile_model(code):
-    # Compile a model and send the compiled graph
-    # First change multiple spaces to a tab
-    code_fragments = code.split("\n")
-    code_fragments = [i for i in code_fragments if i.strip() != ""]
-    code_fragments = [i.replace("    ", "\t") for i in code_fragments]
-    initial_tabs = min([len(i) - len(i.lstrip("\t")) for i in code_fragments])
-    code_fragments = [i[initial_tabs:] for i in code_fragments]
-    code_fragments.append("")
-    code = "\n".join(code_fragments)
-
-    with open(".model.mvc", "w") as f:
-        f.write(code)
-        f.flush()
-
-    return do_compile(".model.mvc", COMPILER_PATH + "/grammars/modelling.g", "M")
-
-def _output(expected=None,port=None):
-    if port is None:
-        port = taskname
+    ctrl_input.addInput(Event("HTTP_input", "request_in", [urllib.urlencode({"op": "set_input", "taskname": taskname, "value": value}), None]))
+
+def _output(expected=None, task=None):
+    if task is None:
+        task = taskname
+
     try:
-        global last_output
-        last_output = json.loads(urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "taskname": port}))).read())
-        #print("[OUT] %s" % last_output)
+        while len(outputs[task]) < 2:
+            time.sleep(0.02)
+
+        del outputs[task][0]
+        #print("[OUT] %s" % outputs[0])
     except:
         raise UnknownError()
-    if expected is not None and last_output != expected:
-        raise InterfaceMismatch(_last_output(), expected)
-    return last_output
 
-def _last_output():
-    return last_output
+    if expected is not None and _last_output(task) != expected:
+        raise InterfaceMismatch(_last_output(task), expected)
+    return _last_output(task)
+
+def _last_output(task=None):
+    if task is None:
+        task = taskname
+
+    return outputs[task][0]
 
 # Raise common exceptions
-def _handle_output(requested=None, split=None):
+def _handle_output(requested=None, split=False):
     value = _output()
     if value.startswith("Model exists: "):
         raise ModelExists(value.split(": ", 1)[1])
@@ -199,14 +212,14 @@ def _handle_output(requested=None, split=None):
     elif value.startswith("Attribute not found: "):
         raise NoSuchAttribute(value.split(": ", 1)[1])
     elif requested is not None and value.startswith(requested):
-        if split is None:
+        if not split:
             return value
         else:
-            splitted = value.strip().split(split, 1)
-            if len(splitted) == 1:
-                return ""
+            splitted = value.strip().split(" ", 1)
+            if len(splitted) > 1:
+                return splitted[1].split("\n")
             else:
-                return splitted[1].rstrip()
+                return []
     else:
         raise InterfaceMismatch(value)
     
@@ -251,25 +264,75 @@ def alter_context(model_name, metamodel_name):
     global registered_metamodels
     registered_metamodels[model_name] = metamodel_name
 
+def _start_http_client(addr, port, timeout):
+    import http_client
+    ctrl = http_client.Controller()
+    listener = ctrl.addOutputListener("request_out")
+    socket2event.boot_translation_service(ctrl)
+    thrd = threading.Thread(target=ctrl.start)
+    thrd.daemon = True
+    thrd.start()
+
+    evt = listener.fetch(-1)
+    if evt.name != "http_client_initialized":
+        raise Exception("HTTP client did not behave as expected during init: " + str(evt.name))
+
+    ctrl.addInput(Event("connect", "request_in", [(addr, port), timeout]))
+
+    evt = listener.fetch(-1)
+
+    if evt.name == "http_client_timeout":
+        raise Exception("HTTP client timeout")
+    if evt.name != "http_client_ready":
+        raise Exception("HTTP client did not behave as expected during connect: " + str(evt.name))
+
+    return ctrl
+
 # Main MvC operations
-def init(address_param="http://127.0.0.1:8001", timeout=20.0):
+def init(address_param="127.0.0.1:8001", timeout=20.0):
     """Starts up the connection to the Modelverse."""
-    global mode
+    # Start up the HTTP Client SC
+    global ctrl_input
+    global ctrl_output
+
+    if ctrl_input is not None:
+        ctrl_input.stop()
+    if ctrl_output is not None:
+        ctrl_output.stop()
+
     global address
-    global taskname
-    address = address_param
+    global port
+
+    address, port = address_param.split(":", 1)
+    port = int(port)
+    
+    ctrl_input = _start_http_client(address, port, timeout)
+    ctrl_output = _start_http_client(address, port, timeout) 
+    controllers = [ctrl_input, ctrl_output]
+
+    global mode
     start_time = time.time()
-    taskname = random.random()
-    while 1:
-        try:
-            _input_raw('"%s"' % taskname, "task_manager")
-            mode = MODE_UNAUTHORIZED
-            break
-        except URLError as e:
-            if time.time() - start_time > timeout:
-                raise ConnectionError(e.reason)
-            else:
-                time.sleep(0.1)
+    task = str(random.random())
+
+    _input_raw('"%s"' % task, "task_manager")
+
+    mode = MODE_UNAUTHORIZED
+
+    global outputs
+    global taskname
+    taskname = task
+    outputs = {}
+
+    _listen_to_output(ctrl_output, task)
+
+def _listen_to_output(controller, task):
+    global outputs
+    outputs[task] = [None]
+
+    # This re-assign also diconnects the previous get_output connections to the outputs variable
+    thrd = threading.Thread(target=_output_thread, args=[controller, outputs, task])
+    thrd.daemon = True
+    thrd.start()
 
 def login(username, password):
     """Log in a user, if user doesn't exist, it is created."""
@@ -305,34 +368,20 @@ def login(username, password):
     else:
         raise InterfaceMismatch(_last_output())
 
-def model_add(model_name, metamodel_name, model_code=None):
+def model_add(model_name, metamodel_name, model_code=""):
     """Instantiate a new model."""
     _goto_mode(MODE_MODELLING)
 
-    # Do this before creating the model, as otherwise compilation errors would make us inconsistent
-    if model_code is not None:
-        try:
-            compiled = _compile_model(model_code)
-        except Exception as e:
-            raise CompilationError(e)
-    else:
-        compiled = [0]
-
     _input(["model_add", metamodel_name, model_name])
     _handle_output("Waiting for model constructors...")
-    _input(compiled)
+    _input(model_code)
     _output("Success")
 
     global registered_metamodels
     registered_metamodels[model_name] = metamodel_name
 
 def upload_code(code):
-    try:
-        compiled = _compile_AL(code)
-    except Exception as e:
-        raise CompilationError(e)
-
-    _input(compiled)
+    _input(code)
 
 def model_delete(model_name):
     """Delete an existing model."""
@@ -345,19 +394,16 @@ def model_list(location):
     """List all models."""
     _goto_mode(MODE_MODELLING)
     _input(["model_list", location])
-    return set(_handle_output("Success: ", split=" ").split("\n"))
+    return set(_handle_output("Success: ", split=True))
 
 def model_list_full(location):
     """List full information on all models."""
     _goto_mode(MODE_MODELLING)
     _input(["model_list_full", location])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
+    output = _handle_output("Success: ", split=True)
 
     lst = set([])
-    value = output.strip().split("\n")
-    for v in value:
+    for v in output:
         m = v.strip()
         perm, own, grp, m = m.split(" ", 3)
         lst.add((m, own, grp, perm))
@@ -372,23 +418,15 @@ def verify(model_name, metamodel_name=None):
         metamodel_name = _get_metamodel(model_name)
 
     _input(["verify", model_name, metamodel_name])
-    return _handle_output("Success: ", split=" ")
+    return _handle_output("Success: ", split=True)[0]
 
-def model_overwrite(model_name, new_model=None, metamodel_name=None):
+def model_overwrite(model_name, new_model="", metamodel_name=None):
     """Upload a new model and overwrite an existing model."""
     _goto_mode(MODE_MODIFY, model_name)
 
-    if new_model is not None:
-        try:
-            compiled = _compile_model(new_model)
-        except Exception as e:
-            raise CompilationError(e)
-    else:
-        compiled = [0]
-
     _input("upload")
     _handle_output("Waiting for model constructors...")
-    _input(compiled)
+    _input(new_model)
     _output("Success")
 
     if metamodel_name is not None:
@@ -414,30 +452,19 @@ def model_render(model_name, mapper_name):
     _goto_mode(MODE_MODELLING)
 
     _input(["model_render", model_name, mapper_name])
-    return json.loads(_handle_output("Success: ", split=" "))
+    return json.loads(_handle_output("Success: ", split=True)[0])
 
 def transformation_between(source, target):
     _goto_mode(MODE_MODELLING)
 
     _input(["transformation_between", source, target])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
-    return set([v for v in output.split("\n")])
+    output = _handle_output("Success: ", split=True)
+    return set(output)
 
 def transformation_add_MT(source_metamodels, target_metamodels, operation_name, code, callback=lambda: None):
     """Create a new model transformation."""
     global mode
     _goto_mode(MODE_MODELLING)
-    import time
-
-    start = time.time()
-    try:
-        compiled = _compile_model(code)
-    except Exception as e:
-        raise CompilationError(e)
-    #print("Compilation took: %ss" % (time.time() - start))
-    start = time.time()
 
     mv_dict_rep = _dict_to_list(source_metamodels) + [""] + _dict_to_list(target_metamodels) + [""]
     _input(["transformation_add_MT"] + mv_dict_rep + [operation_name])
@@ -449,25 +476,17 @@ def transformation_add_MT(source_metamodels, target_metamodels, operation_name,
         callback()
         _input("exit")
         mode = MODE_MODELLING
-    #print("Callbacks took: %ss" % (time.time() - start))
-    start = time.time()
 
     # Done, so RAMify and upload the model
     _handle_output("Waiting for model constructors...")
-    _input(compiled)
+    _input(code)
     _handle_output("Success")
-    #print("Upload and RAMify took: %ss" % (time.time() - start))
 
 def transformation_add_AL(source_metamodels, target_metamodels, operation_name, code, callback=lambda: None):
     """Create a new action language model, which can be executed."""
     global mode
     _goto_mode(MODE_MODELLING)
 
-    try:
-        compiled = _compile_AL(code)
-    except Exception as e:
-        raise CompilationError(e)
-
     mv_dict_rep = _dict_to_list(source_metamodels) + [""] + _dict_to_list(target_metamodels) + [""]
     _input(["transformation_add_AL"] + mv_dict_rep + [operation_name])
 
@@ -480,7 +499,7 @@ def transformation_add_AL(source_metamodels, target_metamodels, operation_name,
         mode = MODE_MODELLING
 
     _handle_output("Waiting for code constructors...")
-    _input(compiled)
+    _input(code)
     _output("Success")
 
 def transformation_add_MANUAL(source_metamodels, target_metamodels, operation_name, callback=lambda: None):
@@ -501,7 +520,7 @@ def transformation_add_MANUAL(source_metamodels, target_metamodels, operation_na
 
     _handle_output("Success")
 
-def transformation_execute_AL(operation_name, input_models_dict, output_models_dict, callback=lambda i: None):
+def transformation_execute_AL(operation_name, input_models_dict, output_models_dict, statechart=None):
     """Execute an existing model operation."""
     global mode
     _goto_mode(MODE_MODELLING)
@@ -511,19 +530,21 @@ def transformation_execute_AL(operation_name, input_models_dict, output_models_d
     _input(["transformation_execute", operation_name] + mv_dict_rep)
     _handle_output("Success: ready for AL execution")
 
-    # We are now executing, so everything we get is part of the dialog, except if it is the string for transformation termination
-    while _output() not in ["Success", "Failure"]:
+    if statechart is not None:
+        # We are to delegate this information to another statechart, which wants interaction
+        # As such, we continue on a different thread, where we pipe the information, and let this call return immediately
         mode = MODE_DIALOG
-        reply = callback(_last_output())
+        _exec_on_statechart(statechart)
         mode = MODE_MODELLING
-        if reply is not None:
-            _input(reply)
-
-    # Got termination message, so we are done!
-    if _last_output() == "Success":
-        return True
+        return None
     else:
-        return False
+        # No statechart associated, so just wait until we are finished
+        while _output() not in ["Success", "Failure"]:
+            pass
+        if _last_output() == "Success":
+            return True
+        else:
+            return False
 
 def transformation_execute_MANUAL(operation_name, input_models_dict, output_models_dict, callback=lambda i: None):
     """Execute an existing model operation."""
@@ -552,7 +573,7 @@ def transformation_execute_MANUAL(operation_name, input_models_dict, output_mode
     else:
         return False
 
-def transformation_execute_MT(operation_name, input_models_dict, output_models_dict, callback=lambda i: None):
+def transformation_execute_MT(operation_name, input_models_dict, output_models_dict, statechart=None):
     """Execute an existing model operation."""
     global mode
     _goto_mode(MODE_MODELLING)
@@ -562,32 +583,31 @@ def transformation_execute_MT(operation_name, input_models_dict, output_models_d
     _input(["transformation_execute", operation_name] + mv_dict_rep)
     _handle_output("Success: ready for MT execution")
 
-    # We are now executing, so everything we get is part of the dialog, except if it is the string for transformation termination
-    while _output() not in ["Success", "Failure"]:
+    if statechart is not None:
+        # We are to delegate this information to another statechart, which wants interaction
+        # As such, we continue on a different thread, where we pipe the information, and let this call return immediately
         mode = MODE_DIALOG
-        reply = callback(_last_output())
+        _exec_on_statechart(statechart)
         mode = MODE_MODELLING
-        if reply is not None:
-            _input(reply)
-
-    # Got termination message, so we are done!
-    if _last_output() == "Success":
-        return True
+        return None
     else:
-        return False
+        # No statechart associated, so just wait until we are finished
+        while _output() not in ["Success", "Failure"]:
+            pass
+        if _last_output() == "Success":
+            return True
+        else:
+            return False
 
 def transformation_list():
     """List existing model operations."""
     _goto_mode(MODE_MODELLING)
 
     _input("transformation_list")
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
+    output = _handle_output("Success: ", split=True)
 
     lst = set([])
-    value = output.strip().split("\n")
-    for v in value:
+    for v in output:
         t, m = v.strip().split(" ", 1)
         t = t[1:-1].strip()
         m = m.strip().split(":")[0].strip()
@@ -709,10 +729,8 @@ def element_list(model_name):
 
     _input("list_full")
     lst = set([])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
-    for v in output.split("\n"):
+    output = _handle_output("Success: ", split=True)
+    for v in output:
         m, mm = v.split(":")
         m = m.strip()
         mm = mm.strip()
@@ -725,10 +743,8 @@ def types(model_name):
 
     _input("types")
     lst = set([])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
-    for v in output.split("\n"):
+    output = _handle_output("Success: ", split=True)
+    for v in output:
         m, mm = v.split(":")
         m = m.strip()
         lst.add(m)
@@ -740,10 +756,8 @@ def types_full(model_name):
 
     _input("types")
     lst = set([])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
-    for v in output.split("\n"):
+    output = _handle_output("Success: ", split=True)
+    for v in output:
         m, mm = v.split(":")
         m = m.strip()
         mm = mm.strip()
@@ -755,8 +769,7 @@ def read(model_name, ID):
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["read", ID])
-    output = _handle_output("Success: ", split=" ")
-    v = output.split("\n")
+    v = _handle_output("Success: ", split=True)
     t = v[1].split(":")[1].strip()
     if (not v[2].startswith("Source:")):
         rval = (t, None)
@@ -771,11 +784,10 @@ def read_attrs(model_name, ID):
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["read", ID])
-    output = _handle_output("Success: ", split=" ")
-    v = output.split("\n")
+    output = _handle_output("Success: ", split=True)
     searching = True
     rval = {}
-    for r in v:
+    for r in output:
         if searching:
             if r == "Attributes:":
                 # Start working on attributes
@@ -804,7 +816,7 @@ def instantiate(model_name, typename, edge=None, ID=""):
         _input(["instantiate_node", typename, ID])
     else:
         _input(["instantiate_edge", typename, ID, edge[0], edge[1]])
-    return _handle_output("Success: ", split=" ")
+    return _handle_output("Success: ", split=True)[0]
 
 def delete_element(model_name, ID):
     """Delete the element with the given ID"""
@@ -824,16 +836,12 @@ def attr_assign(model_name, ID, attr, value):
 def attr_assign_code(model_name, ID, attr, code):
     """Assign a piece of Action Language code to the attribute"""
     _check_type(code)
-    try:
-        compiled = _compile_AL(code)
-    except Exception as e:
-        raise CompilationError(e)
 
     _goto_mode(MODE_MODIFY, model_name)
 
-    _input(["attr_add", ID, attr])
+    _input(["attr_add_code", ID, attr])
     _handle_output("Waiting for code constructors...")
-    _input(compiled)
+    _input(code)
     _output("Success")
 
 def attr_delete(model_name, ID, attr):
@@ -848,45 +856,47 @@ def read_outgoing(model_name, ID, typename):
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["read_outgoing", ID, typename])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
-    else:
-        return set(output.split("\n"))
+    output = _handle_output("Success: ", split=True)
+    return set(output)
 
 def read_incoming(model_name, ID, typename):
     """Returns a list of all incoming associations of a specific type ("" = all)"""
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["read_incoming", ID, typename])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
-    else:
-        return set(output.split("\n"))
+    output = _handle_output("Success: ", split=True)
+    return set(output)
 
 def read_association_source(model_name, ID):
     """Returns the source of an association."""
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["read_association_source", ID])
-    return _handle_output("Success: ", split=" ")
+    return _handle_output("Success: ", split=True)[0]
 
 def read_association_destination(model_name, ID):
     """Returns the destination of an association."""
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["read_association_destination", ID])
-    return _handle_output("Success: ", split=" ")
+    return _handle_output("Success: ", split=True)[0]
 
 ##### To document:
 
 def service_register(name, function):
     """Register a function as a service with a specific name."""
 
-    def service_process(port):
+    def service_process(service_task):
+        global address
+        global port
+
+        ctrl = _start_http_client(address, port, 10.0) 
+        _listen_to_output(ctrl, service_task)
         while 1:
-            thrd = threading.Thread(target=function, args=[service_get(port)])
+            client_task = service_get(service_task)
+            ctrl = _start_http_client(address, port, 10.0) 
+            _listen_to_output(ctrl, client_task)
+            thrd = threading.Thread(target=function, args=[client_task])
             thrd.daemon = True
             thrd.start()
 
@@ -897,10 +907,12 @@ def service_register(name, function):
 
     # Now we are in service-mode
     mode = MODE_SERVICE
-    port = _handle_output("Success: ", split=" ")
+    task = _handle_output("Success: ", split=True)[0]
 
     # Process events in the background!
-    threading.Thread(target=service_process, args=[port]).start()
+    thrd = threading.Thread(target=service_process, args=[task])
+    thrd.daemon = True
+    thrd.start()
 
 def service_stop():
     """Stop the currently executing process."""
@@ -911,18 +923,19 @@ def service_stop():
     global mode
     mode = MODE_MODELLING
 
-def service_get(port):
-    """Get the values on the specified port."""
+def service_get(task):
+    """Get the values on the specified task."""
     _goto_mode(MODE_SERVICE)
 
-    return _output(port=port)
+    val = _output(task=task)
+    return val
 
-def service_set(port, value):
-    """Set a value on a specified port."""
+def service_set(task, value):
+    """Set a value on a specified task."""
     _check_type_list(value)
     _goto_mode(MODE_SERVICE)
 
-    _input(value, port=port)
+    _input(value, task=task)
 
 def user_password(user, password):
     """Change a user's password."""
@@ -938,7 +951,7 @@ def element_list_nice(model_name):
 
     _input(["element_list_nice", model_name, _get_metamodel(model_name)])
 
-    data = _handle_output("Success: ", split=" ")
+    data = _handle_output("Success: ", split=True)[0]
     try:
         return json.loads(data)
     except:
@@ -950,29 +963,23 @@ def connections_between(model_name, source_element, target_element):
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["connections_between", source_element, target_element])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
-    else:
-        return set(output.split("\n"))
+    output = _handle_output("Success: ", split=True)
+    return set(output)
 
 def define_attribute(model_name, node, attr_name, attr_type):
     """Create a new attribute, which can be instantiated one meta-level below."""
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["define_attribute", node, attr_name, attr_type])
-    return _handle_output("Success: ", split=" ")
+    return _handle_output("Success: ", split=True)[0]
 
 def all_instances(model_name, type_name):
     """Returns a list of all elements of a specific type."""
     _goto_mode(MODE_MODIFY, model_name)
 
     _input(["all_instances", type_name])
-    output = _handle_output("Success: ", split=" ")
-    if output == "":
-        return set([])
-    else:
-        return set(output.split("\n"))
+    output = _handle_output("Success: ", split=True)
+    return set(output)
 
 def service_poll(port):
     """Checks whether or not the Modelverse side has any input ready to be processed."""
@@ -996,6 +1003,20 @@ def add_conformance(model_name, metamodel_name, partial_type_mapping=None):
     _handle_output("Success")
 
 def folder_create(folder_name):
+    """Create a new folder."""
     _goto_mode(MODE_MODELLING)
     _input(["folder_create", folder_name])
     _handle_output("Success")
+
+def model_types(model_name):
+    """Fetch all typings defined for this specific model."""
+    _goto_mode(MODE_MODELLING)
+    _input(["model_types", model_name])
+    output = _handle_output("Success: ", split=True)
+    return set(output)
+
+import atexit
+def _close_model():
+    if mode == MODE_MODIFY:
+        _model_exit()
+atexit.register(_close_model)

+ 14 - 0
interface/PN/runner.py

@@ -0,0 +1,14 @@
+from interface import Controller
+import Tkinter as tk
+from sccd.runtime.statecharts_core import Event
+from sccd.runtime.tkinter_eventloop import *
+from widget import Widget
+from modelverse import *
+
+window = tk.Tk()
+window.withdraw()
+controller = Controller(TkEventLoop(window))
+Widget.controller = controller
+controller.start()
+
+window.mainloop()

+ 130 - 0
interface/PN/widget.py

@@ -0,0 +1,130 @@
+'''
+Created on 27-jul.-2014
+
+@author: Simon
+'''
+import Tkinter as tk
+from sccd.runtime.statecharts_core import Event
+
+class Widget:
+    controller = None
+
+    def __init__(self, configure_later=False):
+        if not configure_later:
+            self.set_bindable_and_tagorid(None, None)
+
+    def set_bindable_and_tagorid(self, bindable=None, tagorid=None):
+        if bindable is None:
+            bindable = self
+        self.bindable = bindable
+        self.mytagorid = tagorid
+        if isinstance(self, tk.Toplevel):
+            self.protocol("WM_DELETE_WINDOW", self.window_close)
+        if tagorid is not None:
+            if not isinstance(tagorid, list):
+                tagorid = [tagorid]
+            for t in tagorid:
+                self.bindable.tag_bind(t, "<Button>", self.on_click)
+                self.bindable.tag_bind(t, "<ButtonRelease>", self.on_release)
+                self.bindable.tag_bind(t, "<Motion>", self.on_motion)
+                self.bindable.tag_bind(t, "<Enter>", self.on_enter)
+                self.bindable.tag_bind(t, "<Leave>", self.on_leave)
+                self.bindable.tag_bind(t, "<Key>", self.on_key)
+                self.bindable.tag_bind(t, "<KeyRelease>", self.on_key_release)
+        else:
+            self.bindable.bind("<Button>", self.on_click)
+            self.bindable.bind("<ButtonRelease>", self.on_release)
+            self.bindable.bind("<Motion>", self.on_motion)
+            self.bindable.bind("<Enter>", self.on_enter)
+            self.bindable.bind("<Leave>", self.on_leave)
+            self.bindable.bind("<Key>", self.on_key)
+            self.bindable.bind("<KeyRelease>", self.on_key_release)
+        self.last_x = 50
+        self.last_y = 50
+        self.selected_type = None
+
+    def on_click(self, event):
+        ''' Prevent event propagation from canvas elements to canvas... '''
+        if isinstance(self.bindable, tk.Canvas) and self.mytagorid is None:
+            if hasattr(event.widget, 'clicked'):
+                if event.widget.clicked:
+                    event.widget.clicked = False
+                    return
+        else:
+            event.widget.clicked = True
+        event_name = None
+
+        if event.num == 1:
+            event_name = "left-click"
+        elif event.num == 2:
+            event_name = "middle-click"
+        elif event.num == 3:
+            event_name = "right-click"
+
+        if event_name:
+            self.last_x = event.x
+            self.last_y = event.y
+            Widget.controller.addInput(Event(event_name, "input", [id(self)]))
+
+    def on_release(self, event):
+        event_name = None
+
+        if event.num == 1:
+            event_name = "left-release"
+        elif event.num == 2:
+            event_name = "middle-release"
+        elif event.num == 3:
+            event_name = "right-release"
+
+        if event_name:
+            self.last_x = event.x
+            self.last_y = event.y
+            Widget.controller.addInput(Event(event_name, "input", [id(self)]))
+
+    def on_motion(self, event):
+        self.last_x = event.x
+        self.last_y = event.y
+        Widget.controller.addInput(Event("motion", "input", [id(self)]))
+
+    def on_enter(self, event):
+        Widget.controller.addInput(Event("enter", "input", [id(self)]))
+
+    def on_leave(self, event):
+        Widget.controller.addInput(Event("leave", "input", [id(self)]))
+
+    def on_key(self, event):
+        event_name = None
+
+        if event.keysym == 'Escape':
+            event_name = "escape"
+        elif event.keysym == 'Return':
+            event_name = "return"
+        elif event.keysym == 'Delete':
+            event_name = "delete"
+        elif event.keysym == 'Shift_L':
+            event_name = "shift"
+        elif event.keysym == 'Control_L':
+            event_name = "control"
+
+        if event_name:
+            Widget.controller.addInput(Event(event_name, "input", [id(self)]))
+
+    def on_key_release(self, event):
+        event_name = None
+
+        if event.keysym == 'Escape':
+            event_name = "escape-release"
+        elif event.keysym == 'Return':
+            event_name = "return-release"
+        elif event.keysym == 'Delete':
+            event_name = "delete-release"
+        elif event.keysym == 'Shift_L':
+            event_name = "shift-release"
+        elif event.keysym == 'Control_L':
+            event_name = "control-release"
+
+        if event_name:
+            Widget.controller.addInput(Event(event_name, "input", [id(self)]))
+
+    def window_close(self):
+        Widget.controller.addInput(Event("window-close", "input", [id(self)]))

+ 67 - 56
models/reachability.alc

@@ -3,6 +3,7 @@ include "modelling.alh"
 include "object_operations.alh"
 include "transform.alh"
 include "constructors.alh"
+include "compiler.alh"
 
 Boolean function reachability_graph(model : Element):
     Element workset
@@ -52,6 +53,7 @@ Boolean function reachability_graph(model : Element):
     Element curr_reachable
     Element new_breakpoint
     Element curr_bp_function
+    Element place_names_to_ids
     
     Element breakpoints
     breakpoints = create_node()
@@ -67,35 +69,41 @@ Boolean function reachability_graph(model : Element):
     while (True):
         output('{"msg_type": "enabled_commands", "commands": ["step", "continuous", "manual", "add_breakpoint"]}')
         output('{"msg_type": "mode_change", "mode": "paused"}')
+        log('waiting for user input')
         user_input = input()
-        if (user_input == "step"):
-            output('{"msg_type": "enabled_commands", "commands": ["step", "continuous", "manual"]}')
-            break!
-        if (user_input == "continuous"):
-            output('{"msg_type": "enabled_commands", "commands": []}')
-            output('{"msg_type": "mode_change", "mode": "running"}')
-            break!
-        if (user_input == "manual"):
-            output('{"msg_type": "enabled_commands", "commands": ["step", "continuous", "manual"]}')
-            break!
-        if (user_input == "add_breakpoint"):
-            bp_name = ""
-            while (bool_or(bp_name == "", dict_in(breakpoints, bp_name))):
-                output('{"msg_type": "input_required", "name": "breakpoint name", "type": "string"}')
-                bp_name = input()
-                output('{"msg_type": "input_required", "name": "disable on trigger?", "type": "boolean"}')
-                disable_on_trigger_str = input()
-                if (disable_on_trigger_str == "True"):
-                    disable_on_trigger = True
-                else:
-                    disable_on_trigger = False
-            output('{"msg_type": "input_required", "name": "breakpoint function", "type": "code"}')
-            new_breakpoint = create_node()
-            dict_add_fast(new_breakpoint, "function", construct_function())
-            dict_add_fast(new_breakpoint, "disable_on_trigger", disable_on_trigger)
-            dict_add_fast(new_breakpoint, "enabled", True)
-            dict_add_fast(breakpoints, bp_name, new_breakpoint)
-            output(('{"msg_type": "state_change", "state": "breakpoint_added", "breakpoint_name": "' + bp_name) + '"}')
+        log(user_input)
+        if (user_input == "simulation_mode"):
+            user_input = input()
+            if (user_input == "step"):
+                output('{"msg_type": "enabled_commands", "commands": ["step", "continuous", "manual"]}')
+                break!
+            if (user_input == "continuous"):
+                output('{"msg_type": "enabled_commands", "commands": []}')
+                output('{"msg_type": "mode_change", "mode": "running"}')
+                break!
+            if (user_input == "manual"):
+                output('{"msg_type": "enabled_commands", "commands": ["step", "continuous", "manual"]}')
+                break!
+            if (user_input == "add_breakpoint"):
+                bp_name = ""
+                while (bool_or(bp_name == "", dict_in(breakpoints, bp_name))):
+                    output('{"msg_type": "input_required", "name": "breakpoint name", "type": "string"}')
+                    bp_name = input()
+                    output('{"msg_type": "input_required", "name": "disable on trigger?", "type": "boolean"}')
+                    disable_on_trigger_str = input()
+                    if (disable_on_trigger_str == "True"):
+                        disable_on_trigger = True
+                    else:
+                        disable_on_trigger = False
+                output('{"msg_type": "input_required", "name": "breakpoint function", "type": "code"}')
+                new_breakpoint = create_node()
+                String bp_code
+                bp_code = input()
+                dict_add_fast(new_breakpoint, "function", compile_code(bp_code))
+                dict_add_fast(new_breakpoint, "disable_on_trigger", disable_on_trigger)
+                dict_add_fast(new_breakpoint, "enabled", True)
+                dict_add_fast(breakpoints, bp_name, new_breakpoint)
+                output(('{"msg_type": "state_change", "state": "breakpoint_added", "breakpoint_name": "' + bp_name) + '"}')
     mode = user_input
 
     // Create a dictionary representation for each transition
@@ -129,9 +137,11 @@ Boolean function reachability_graph(model : Element):
 
     all_places = allInstances(model, "PetriNet/Place")
     dict_repr = create_node()
+    place_names_to_ids = create_node()
     while (read_nr_out(all_places) > 0):
         place = set_pop(all_places)
         dict_add_fast(dict_repr, place, read_attribute(model, place, "tokens"))
+        dict_add_fast(place_names_to_ids, read_attribute(model, place, "name"), place)
 
     all_transitions_original = allInstances(model, "PetriNet/Transition")
 
@@ -205,20 +215,21 @@ Boolean function reachability_graph(model : Element):
         while (True):
             if (mode == "manual"):
                 break!
-            output("Please enter your command. Options: continuous, step, manual")
             user_input = input()
-            if (user_input == "step"):
-                mode = user_input
-                output('{"msg_type": "enabled_commands", "commands": ["step", "continuous", "manual"]}')
-                break!
-            if (user_input == "continuous"):
-                mode = user_input
-                output('{"msg_type": "enabled_commands", "commands": []}')
-                break!
-            if (user_input == "manual"):
-                mode = user_input
-                output('{"msg_type": "enabled_commands", "commands": ["step", "continuous", "manual"]}')
-                break!
+            if (user_input == "simulation_mode"):
+                user_input = input()
+                if (user_input == "step"):
+                    mode = user_input
+                    output('{"msg_type": "enabled_commands", "commands": ["step", "continuous", "manual"]}')
+                    break!
+                if (user_input == "continuous"):
+                    mode = user_input
+                    output('{"msg_type": "enabled_commands", "commands": []}')
+                    break!
+                if (user_input == "manual"):
+                    mode = user_input
+                    output('{"msg_type": "enabled_commands", "commands": ["step", "continuous", "manual"]}')
+                    break!
 
     while (read_nr_out(workset) > 0):
         if (mode == "manual"):
@@ -265,7 +276,6 @@ Boolean function reachability_graph(model : Element):
                                 enabled_transitions_output = enabled_transitions_output + ", "
                         enabled_transitions_output = enabled_transitions_output + "]"
                         output(('{"msg_type": "enabled_transitions", "transitions": ' + enabled_transitions_output) + '}')
-                        output("Please choose an enabled transition or another marking.")
                 elif (user_input_s == 'selected_transition'):
                     set_remove(workset, state_id)
                     dict_repr = reachable_states[state_id]
@@ -419,7 +429,7 @@ Boolean function reachability_graph(model : Element):
             curr_bp_name = set_pop(bp_keys)
             curr_bp = breakpoints[curr_bp_name]
             curr_bp_function = curr_bp["function"]
-            if (bool_and(curr_bp["enabled"], curr_bp_function(reachable_states, mappings))):
+            if (bool_and(curr_bp["enabled"], curr_bp_function(reachable_states, mappings, place_names_to_ids))):
                 output(('{"msg_type": "state_change", "state": "breakpoint_triggered", "breakpoint_name": "' + curr_bp_name) + '"}')
                 bp_triggered = True
                 log(curr_bp["disable_on_trigger"])
@@ -480,20 +490,21 @@ Boolean function reachability_graph(model : Element):
             while (True):
                 if (mode == "manual"):
                     break!
-                output("Please enter your command. Options: continuous, step, manual")
                 user_input = input()
-                if (user_input == "step"):
-                    mode = user_input
-                    output('{"msg_type": "enabled_commands", "commands": ["step", "continuous", "manual"]}')
-                    break!
-                if (user_input == "continuous"):
-                    mode = user_input
-                    output('{"msg_type": "enabled_commands", "commands": []}')
-                    break!
-                if (user_input == "manual"):
-                    mode = user_input
-                    output('{"msg_type": "enabled_commands", "commands": ["step", "continuous", "manual"]}')
-                    break!
+                if (user_input == "simulation_mode"):
+                    user_input = input()
+                    if (user_input == "step"):
+                        mode = user_input
+                        output('{"msg_type": "enabled_commands", "commands": ["step", "continuous", "manual"]}')
+                        break!
+                    if (user_input == "continuous"):
+                        mode = user_input
+                        output('{"msg_type": "enabled_commands", "commands": []}')
+                        break!
+                    if (user_input == "manual"):
+                        mode = user_input
+                        output('{"msg_type": "enabled_commands", "commands": ["step", "continuous", "manual"]}')
+                        break!
 
     Element all_states
     Element curr_state