0% found this document useful (0 votes)
50 views39 pages

JSON-RPC WebSocket Event Handling

Uploaded by

LE Thuc Trinh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views39 pages

JSON-RPC WebSocket Event Handling

Uploaded by

LE Thuc Trinh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

#

# Copyright (c) 2013-Present Arteris and its applicable affiliates, subject to


license from Qualcomm Technologies. All rights reserved.
#

import base64
import decimal
import json
import Queue
import time
import sys
import traceback
from collections import defaultdict
from tempfile import NamedTemporaryFile

from jsonrpc import JSONRPCResponseManager, dispatcher


from [Link] import JSONRPCDispatchException,
JSONRPCInvalidParams
import [Link] as qt
import threading
import [Link]
import [Link]
import [Link]

from [Link] import


Element,Context,StabilizingThread,unstableEvent,View
from [Link] import formatException
from [Link] import theLicenser
from [Link] import dataTypes
import [Link] as bs
import [Link] as app
import [Link] as sb
from [Link] import AttachmentElement
from [Link] import ConnectPElt
from [Link] import PipeNode

ioloop=None

class ExternalEvent([Link]):
def __init__(self,callable,*args):
super(ExternalEvent,self).__init__([Link])
[Link] = handleExceptionsInCallback(callable)
[Link] = args

def __str__(self): return "ExternalEvent:%s"%[Link]

def run(self):
[Link](*[Link])

class EventReceiver([Link]):
# Receive event from the tornado thread and execute them in the qt thread
def customEvent(self,evt):
if isinstance(evt,ExternalEvent):
[Link]()

class FNDispatchException(JSONRPCDispatchException):
def __init__(self,data=None):
super(FNDispatchException,self).__init__([Link],[Link],data)
class importException(FNDispatchException):
CODE = -32004
MESSAGE = "An error occurred while doing the import"

class OpenException(FNDispatchException):
CODE = -32003
MESSAGE = "An error occurred while opening a window"

class LoadException(FNDispatchException):
CODE = -32002
MESSAGE = "An error occurred while loading the pdd"

class ExitException(FNDispatchException):
CODE = -32000
MESSAGE = "Exit error"

class ObjectPathException(FNDispatchException):
CODE = -32001
MESSAGE = "Unknown object"

class RemoteErrorException(FNDispatchException):
CODE = -32005

def __init__(self, message, data=None):


[Link] = message
super(RemoteErrorException, self).__init__(data)

class PauseDialog( [Link] ) :


def __init__( self , parent , message ):
super( PauseDialog , self ).__init__( parent , [Link] |
[Link] | [Link]) #| [Link] )
[Link]("FlexNoC paused")
[Link](200)
hBox = [Link]( self )
[Link]( hBox )
label = [Link]( message )
[Link]( True )
[Link]( label )
[Link]([Link])

def keyPressEvent(self, *args, **kwargs):


return

def keyReleaseEvent(self, *args, **kwargs):


return

def moveEvent(self,event):
return

# globalPoint = [Link]([Link]().center());
# [Link](globalPoint.x() - [Link]() / 2, globalPoint.y() -
[Link]() / 2);

from [Link] import View


from [Link] import Undefined

from [Link] import Enum


def copy_dict(data):
if isinstance(data, tuple):
return tuple([copy_dict(i) for i in data])

elif isinstance(data, list):


return list([copy_dict(i) for i in data])

elif isinstance(data, set):


return tuple(set([copy_dict(i) for i in data]))

elif isinstance(data, Enum):


return [Link]

elif isinstance(data, Element):


return [Link]([Link])

elif isinstance(data, [Link]):


return [Link]()

elif isinstance(data, [Link]):


return float(data)

elif isinstance(data, [Link]):


return tuple(set([i for i in data]))

elif isinstance(data, [Link]):


return str(data)

elif data == Undefined:


return None

elif data == Ellipsis:


return None

elif data is None:


return None

elif not isinstance(data, dict):


return data

output = {}
for key, value in [Link]():
if isinstance(key, Element):
key = [Link]([Link])
elif isinstance(key, [Link]):
key = [Link]().pathname([Link])

if isinstance(value, Element):
value = [Link]([Link])
elif isinstance(value, [Link]):
value = [Link]().pathname([Link])

output[key] = copy_dict(value)

return output

def fromPath(pathname):
"Retrieves an element, out of its pathname. "
path = [Link]('..')
rootItem = [Link].getitem_str(path[0][1:])
scan = rootItem
for z in path[1:]:
if z[0] == '(':
try:
scan = scan[[Link](z)]
except KeyError:
scan = scan[z]

else:
scan = scan[z]

return scan

def handleExceptionsInCallback(func):
def _intern(*args, **kwargs):
try:
func(*args, **kwargs)

except FNDispatchException as error:


[Link](error)

except Exception as error:


exc_type, exc_value, exc_traceback = sys.exc_info()
message = formatException(exc_type, exc_value, exc_traceback)
exception = RemoteErrorException(message=message)
[Link](exception)

return _intern

class RootHandler([Link], View, [Link]):


skip_network_requests = True
handlers = []
kindMapping = {
'Specification' : 'specification'
, 'Architecture' : 'switchBasedArchitecture'
, 'Structure' : 'switchBasedStructure'
, 'Scenario' : 'scenario'
, 'Outline' : 'outline'
, 'Area result' : 'structureArea'
, 'Timing result' : ''
, 'Floorplan result' : 'structureFloorplan'
, 'Exploration' : 'switchBasedArchitectureResult'
, 'Exploration2' : 'scenarioResult' # Fake key for another value
, 'Design Composition': 'nocComposition'
}
def __init__(self,*args,**kwargs):
super(RootHandler,self).__init__(*args,**kwargs)
self.skip_delete = []
[Link] = None
[Link] = False
[Link] = [Link](target = [Link],name='Stable
timer')
[Link]=True
[Link]()

self.subscriber_info = {}
self.ALL_UPDATES = True
[Link] = [Link](self)
[Link] = False
[Link][[Link]()] = None
[Link] = True

self._to_delete = []

self._pause_output = False

self._reserved_names = defaultdict(set)

def handleClearProject(self):
notification = {
'jsonrpc': '2.0',
'method': 'clearProject',
'params': [],
}

[Link]('Sending clear project command.', [Link](notification))


global ioloop
ioloop.add_callback(self.write_message, [Link](notification))

def handleReloadProject(self):
notification = {
'jsonrpc': '2.0',
'method': 'reloadProject',
'params': [],
}

[Link]('Sending reload project command.', [Link](notification))


global ioloop
ioloop.add_callback(self.write_message, [Link](notification))

def pauseOutput(self):
self._pause_output = True
yield
self._pause_output = False

def notifyElement(self, deletions , updates, creations, renames,


changed_sb_items):
if self.ws_connection is None:
[Link]()
return

# Filter the updates to only include the items that were directly
updated, i.e.
# not anything that was unstabilized because it was watching something
which was
# modified.
def unpack_shadow(item):
origins = {item,}
if isinstance(item, [Link]):
origins |= unpack_shadow(item._objectOrigin)

return origins

def full_hierarchy(item):
parents = unpack_shadow(item)
while item._parent is not None:
item = item._parent
parents |= unpack_shadow(item)
return parents

changed_sb_items = {j for i in changed_sb_items for j in


full_hierarchy(i)}

def up_to_object(item):
items = unpack_shadow(item)
while isinstance(item, ([Link], [Link])):
item = item._parent
items |= unpack_shadow(item)

return items

updates = {i for i in updates if i._item and up_to_object(i._item) &


changed_sb_items}

params = {
'renames': renames,
'deletions': [],
'updates': [],
'creations': [],
'modified_routes': [],
'deleted_routes': [],
}

def is_route(item):
return [Link]() and [Link]().name() == 'outputEdges'

updates_to_send = set()
filtered_creations = []
for creation in creations:
# We don't want anything from floorplan results.
if [Link]().parent() and
[Link]().parent().kind == 'structureFloorplan':
continue

# If we are creating anything inside the connectivity, make sure


we declare that the connectivity is being updated.
if [Link]() and [Link]().parent() and
[Link]().parent().name() == 'connectivity':

updates_to_send.add([Link]().parent().pathname([Link]))

filtered_creations.append(creation)

filtered_deletions = []
for deletion in deletions:
if deletion in self.skip_delete:
self.skip_delete.remove(deletion)
else:
filtered_deletions.append(deletion)

modified_routes = {
route for i in deletions | updates | creations
if is_route(i) for route in [Link]
}

modified_observers = [i for i in updates if [Link]() == 'observer' and


[Link]().name() in ['reqObservation', 'rspObservation']]
for modified_observer in modified_observers:
modified_routes |= modified_observer.parentObject()['@']
['observation']['info'].routes

for update in updates:


if [Link]() and [Link]().parent() and
[Link]().parent().name() == 'connectivity':
for arch in [i for i in
[Link]('switchBasedArchitecture', False) if [Link]() ==
[Link]()]:
for network in ['datapath', 'service',
'observation']:
if [Link]().key().getElement().parent()
in arch['@'][network + 'Routes']:
if [Link]().getElement().parent() in
arch['@'][network + 'Routes'][[Link]().key().getElement().parent()]:
modified_routes.add(arch['@']
[network + 'Routes'][[Link]().key().getElement().parent()]
[[Link]().getElement().parent()])

# We need to convert the @ routes to $ routes.


# For the deleted ones, we can't use the init flow and targ flow
because they are
# deleted, so we need to hack together the name using split and join.
deleted_routes = {
'..'.join([[Link]['$'][[Link] +
'Route'].pathname()] + [Link]().split('..')[-2:])
for route in modified_routes if [Link]() and not
[Link]()
}
updated_routes = {
[Link]['$'][[Link] + 'Route'][[Link]]
[[Link]].pathname()
for route in modified_routes if not [Link]()
}

# The edges don't always show up when you first add an observer to an
item.
observers = {i for i in updates | creations if [Link]() == 'observer'
and [Link]().name() == 'observation'}
for observer in observers:
if '@' not in [Link]():
continue
[Link]()['@']['observation']['digest'].stabilize()
route_objects = {route for i in getattr([Link]()
['@']['observation']['digest'], 'outputEdges', []) for route in [Link]}
updated_routes |= {[Link]['$'][[Link] +
'Route'][[Link]][[Link]].pathname() for route in route_objects}

for update in updates:


if [Link]() and [Link]().parent() and
[Link]().parent().name() == 'connectivity':

updates_to_send.add([Link]().parent().pathname([Link]))
else:
updates_to_send.add([Link]().pathname([Link]))

# We want the properties of some items to be sent because it


makes detecting what has changed much easier.
if [Link]() in ['clock']:
updates_to_send.add([Link]([Link]))

params['deletions'] += [[Link]([Link]) for i in


filtered_deletions if [Link]]
params['updates'] += list(updates_to_send)
params['creations'] += [[Link]([Link]) for i in
filtered_creations if [Link] or isinstance(i, ConnectPElt)]

params['modified_routes'] += list(updated_routes)
params['deleted_routes'] += list(deleted_routes)

# We didn't add any information to the update, so don't send an empty


update.
if not any(bool(value) for value in [Link]()):
return

notification = {
'jsonrpc': '2.0',
'method': 'notifyElement',
'params': params,
}

[Link]('Sending notification',[Link](notification,
sort_keys=True,indent=4, separators=(',', ': ')))
global ioloop

[Link]([Link],ExternalEvent([Link]
ocused))
ioloop.add_callback(self.write_message, [Link](notification))

def open(self):
[Link](self)

def on_close(self):
[Link](self)

# Allow changes if we get a disconnect. If the connected application


crashed or closed during an operation, we
# want to unlock the FlexNoC gui.
if [Link].block_changes:
[Link]()

def check_origin(self, origin):


return True

def log(self,caption,message):
if [Link]("LaunchDevelopper"):
[Link](caption,message=message)

def on_message(self, message):


# Dispatcher is dictionary {<method_name>: callable}
dispatcher["save"] = [Link]
dispatcher["open"] =
[Link]("opened")
dispatcher["reload"] =
[Link]("reloaded")
dispatcher["openProjectManager"] =
[Link]('ProjectManagerMainActor' , 'openedProjectManager')
dispatcher["openDesignEditor"] =
[Link]('DesignEditorActor' , 'openedDesignEditor')
dispatcher["openImplementationEditor"] =
[Link]('ImplementationEditorActor' , 'openedImplementationEditor')
dispatcher["openExplorationEditor"] =
[Link]('ExplorationEditorActor' , 'openedExplorationEditor')
dispatcher["openDesignCompositionEditor"] =
[Link]('DesignCompositionEditorMainActor' ,
'openedDesignCompositionEditor')
dispatcher["openDesignDiff"] = [Link]
dispatcher["pause"] = [Link]
dispatcher["resume"] = [Link]
dispatcher["stabilize"] = [Link]
dispatcher["importScript"] = [Link]
dispatcher["importOcpRtlConf"] = [Link]
dispatcher["importAreaResults"] = [Link]
dispatcher["importFloorplanResults"] = [Link]
dispatcher["importAttachment"] = [Link]
dispatcher["importPDD"] = [Link]
dispatcher["importVCD"] = [Link]
dispatcher["getSaveState"] = [Link]
dispatcher["setStyle"] = [Link]
dispatcher["exit"] = [Link]
dispatcher["getPddName"] = [Link]

dispatcher["getProjectJson"] = [Link]
dispatcher["getProjectTree"] = [Link]
dispatcher["getIter"] = [Link]
dispatcher["getKeys"] = [Link]
dispatcher["childrenOfKind"] = [Link]
dispatcher["getValue"] = [Link]
dispatcher["getOrigin"] = [Link]
dispatcher["getProjectAncestor"] = [Link]
dispatcher["getChild"] = [Link]
dispatcher["getKind"] = [Link]
dispatcher["getParent"] = [Link]
dispatcher["getFileContents"] = [Link]
dispatcher["getName"] = [Link]
dispatcher["subscribeToChanges"] = [Link]
dispatcher["getSubscriptionUpdates"] = [Link]
dispatcher["getRouteBeforeAndAfter"] = [Link]
dispatcher["deleteItems"] = [Link]
dispatcher["pathExists"] = [Link]
dispatcher["createNewElement"] = [Link]
dispatcher["setValues"] = [Link]
dispatcher["addEntryToList"] = [Link]
dispatcher["bulkDeleteCreateAndUpdate"] =
[Link]
dispatcher["bulkDeleteCreateAndUpdateDebug"] =
[Link]
dispatcher["createAndPopulateOutline"] =
[Link]
dispatcher["showIn"] = [Link]
dispatcher["suggestName"] = [Link]
dispatcher["openCustomizer"] = [Link]
dispatcher["getPipeInfo"] = [Link]

dispatcher["acknowledgeUpdate"] = [Link]
dispatcher["blockChanges"] = [Link]
dispatcher["allowChanges"] = [Link]

response = [Link](message, dispatcher)


if [Link]:
[Link]("Received invalid request",message)
else:
jsonMessage = [Link](message)
# [Link]("Received %s
request"%jsonMessage['method'],[Link](jsonMessage, sort_keys=True,indent=4,
separators=(',', ': ')))

# [Link]("Sending response",[Link]([Link],
sort_keys=True,indent=4, separators=(',', ': ')))

self.write_message([Link])

def acknowledgeUpdate(self):
[Link]([Link],
ExternalEvent([Link]))

def blockChanges(self):
def _blockChanges():
[Link].block_changes = True

[Link]([Link],ExternalEvent(_blockChanges))

def allowChanges(self):
def _allowChanges():
[Link].block_changes = False

[Link]([Link],ExternalEvent(_allowChanges))

def getPddName(self):
return [Link]()

def suggestName(self, path, name):


path = [Link]('utf-8')
name = [Link]('utf-8')

if path == '/':
element = [Link]
else:
try:
element = [Link](path)
except KeyError:
raise JSONRPCInvalidParams(message='No item at path "%s"' %
path)

good_name = element._item.proposeChildName(name)
index = 0
while good_name in self._reserved_names[path]:
good_name = element._item.proposeChildName('%s_%d' % (name,
index))
index += 1

self._reserved_names[path].add(good_name)

return good_name

def showIn(self, paths):


paths = [[Link]('utf-8') for path in paths]

def _deferred_showIn():
elements = [[Link](path) for path in paths]
if not elements:
return

design_editor = [Link]('ViewOpen')
['DesignEditorActor'].trigger(Context([elements[0].projectAncestor()]))
[Link]()
topology_view = design_editor.forcePage(('Datapath Transport',
'Topology'), 'switchBasedArchitecture')
[Link]()
topology_view.doShowIn(Context(elements))
[Link]()

[Link]([Link],
ExternalEvent(_deferred_showIn))
return None

def openCustomizer(self, path):


path = [Link]('utf-8')

def _deferred_openCustomizer():
element = [Link](path)
design_editor =
[Link]('Customize').trigger(Context([element['$']]))

[Link]([Link],
ExternalEvent(_deferred_openCustomizer))
return None

def pipe_info(self, element):


def make_network_dict():
return {
'input': defaultdict(list), # Dict[str, List[Tuple[str,
bool, bool, bool, str]]]
'output': defaultdict(list), # Dict[str, List[Tuple[str,
bool, bool, bool, str]]]
'rx': [], # List[Tuple[str, bool, bool, bool, str]]
'tx': [], # List[Tuple[str, bool, bool, bool, str]]
}
pipe_info = defaultdict(make_network_dict)

def parse_pipe(pipe_node): # -> List[Tuple[str, bool, bool, bool, str]]


pipes = []

if [Link]:
name = [Link] + '.forward'
if isinstance([Link], dict):
locked = True
ref = ''
state = [Link]['state']
modifiable = [Link]['autopipeModifiable']
else:
locked = False
ref = [Link]()
state = [Link]['state'].value()
modifiable =
[Link]['autopipeModifiable'].value()
[Link]((name, state, modifiable, locked, ref))

if [Link]:
name = [Link] + '.backward'
if isinstance([Link], dict):
locked = True
ref = ''
state = [Link]['state']
modifiable = [Link]['autopipeModifiable']
else:
locked = False
ref = [Link]()
state = [Link]['state'].value()
modifiable =
[Link]['autopipeModifiable'].value()
[Link]((name, state, modifiable, locked, ref))

return pipes

for network in ['datapath', 'service', 'observation', 'dvm']:


if network not in element['@'] or 'digest' not in element['@']
[network]:
continue

digest = element['@'][network]['digest']
if [Link]():
for neighbor, nodes in [Link]():
for node in reversed(nodes):
if not isinstance(node, PipeNode):
continue
pipe_info[network]['input']
[[Link]()] += parse_pipe(node)

for neighbor, nodes in [Link]():


for node in nodes:
if not isinstance(node, PipeNode):
continue
pipe_info[network]['output']
[[Link]()] += list(reversed(parse_pipe(node)))

for side in ['rx', 'tx']:


nodes = [Link][side]
if side == 'rx':
nodes = reversed(nodes)
for node in nodes:
if not isinstance(node, PipeNode):
continue

new_pipes = parse_pipe(node)
if side == 'tx':
new_pipes = list(reversed(new_pipes))
pipe_info[network][side] += new_pipes

return pipe_info

def getPipeInfo(self, paths):


info = {}

for path in paths:


path = [Link]('utf-8')
element = [Link](path)
[Link]()

try:
info[path] = self.pipe_info(element)
except Exception as error:
exc_type, exc_value, exc_traceback = sys.exc_info()
message = formatException(exc_type, exc_value,
exc_traceback)
exception = RemoteErrorException(message=message)
raise exception

return info

def _createAndPopulateOutline(self, name, origin, defaults, restrictions,


image_data):
new_references = {}
with [Link]('Creating and populating
outline.', network_request=True):
with [Link]('Create outline.',
network_request=True):
parent_obj = [Link]
origin_item = [Link](origin)._item
kind = 'outline'

if name in self._reserved_names['/']:
self._reserved_names['/'].remove(name)

new_outline_item = [Link](parent_obj._item,
name, kind, origin_item)

for key, value in defaults:


[Link](new_outline_item, key,
value)

new_outline = new_outline_item.getElement()

new_restriction_items = {}
with [Link]('Create restrictions.',
network_request=True):
for restriction_name, restriction_values in
[Link]():
new_restriction_items[restriction_name] =
[Link](new_outline_item, restriction_name, 'restriction')

for key, value in


restriction_values['defaults']:

[Link](new_restriction_items[restriction_name], key, value)


new_references[restriction_name] = []
zones =
[Link](new_restriction_items[restriction_name]['$'], 'zones')

for i, zone in
enumerate(restriction_values['zones']):
new_subregion_item = [Link](zones,
str(i))
[Link](new_subregion_item, 'x',
zone['x'])
[Link](new_subregion_item, 'y',
zone['y'])
[Link](new_subregion_item, 'w',
zone['w'])
[Link](new_subregion_item, 'h',
zone['h'])

new_references[restriction_name].append(new_subregion_item)

if image_data is not None:


with [Link]('Create image
entry.', network_request=True):
with NamedTemporaryFile(suffix='.png') as
open_file:
open_file.write(''.join([chr(i) for i in
image_data]))
open_file.seek(0)
attachment = [Link](
parent=parent_obj,
name='%s.floorplan_image' % name,
fileName=open_file.name,
)
with [Link]('Set image data.',
network_request=True):
new_outline['$']['background']
['image'].assign(attachment)

new_outline['$']['bounding'].stabilize()
new_outline['$']['background']['box']
['w'].assign(new_outline['$']['bounding']['w'].value())
new_outline['$']['background']['box']
['h'].assign(new_outline['$']['bounding']['h'].value())

new_outline.stabilize()

return new_outline, new_references

def createAndPopulateOutline(self, name, origin, defaults, restrictions,


image_data):
name = self._decode_value_payload(name)
origin = self._decode_value_payload(origin)
defaults = self._decode_value_payload(defaults)
restrictions = self._decode_value_payload(restrictions)

def _deferred_createAndPopulateOutline():
new_outline, new_references =
self._createAndPopulateOutline(name, origin, defaults, restrictions, image_data)
[Link]((new_outline.pathname([Link]), {k:
[[Link]().pathname([Link]) for i in v] for k, v in
new_references.items()}))

[Link]([Link],
ExternalEvent(_deferred_createAndPopulateOutline))
return [Link]() # send response when stabilization is
finished

def bulkDeleteCreateAndUpdate(self, changes):


return self._bulkDeleteCreateAndUpdate(changes, False)

def bulkDeleteCreateAndUpdateDebug(self, changes):


return self._bulkDeleteCreateAndUpdate(changes, True)

def _bulkDeleteCreateAndUpdate(self, changes, trigger_return_updates):


def _deferred_bulkDeleteCreateAndUpdate():
updated_objects = set()
created_items = {}
with [Link]('Perform mass delete, create, and
update. trigger_return_updates=%s' % str(trigger_return_updates),
network_request=not trigger_return_updates, call_sys_excepthook=False):
for change_type, change in changes:
if change_type == 'delete':
item =
fromPath(self._decode_value_payload(change))
with [Link]('Delete item
%s' % [Link](), network_request=not trigger_return_updates):
[Link](item)

elif change_type == 'rename':


ref, new_name =
self._decode_value_payload(change)
item = fromPath(ref)
with [Link]('',
network_request=not trigger_return_updates):
[Link](item, new_name)

elif change_type == 'create':


parent, name, kind, origin, default_values =
self._decode_value_payload(change)

# Clear the entry in the reserved names,


because the normal mechanisms for getting
# non-conflicting names will work now that the
item is created.
if name in self._reserved_names[parent]:
self._reserved_names[parent].remove(name)

if parent in ('', '/'):


parent_obj = [Link]._item
else:
parent_obj = fromPath(parent)

if origin:
origin_item = fromPath(origin)
else:
origin_item = None

with [Link]('Create item %s


in %s' % (name, parent_obj.path()), network_request=not trigger_return_updates):
if kind == 'attachment':
default_values =
dict(default_values)

with
NamedTemporaryFile(suffix=default_values.pop('extension')) as open_file:

open_file.write(''.join([chr(i) for i in default_values.pop('data')]))


open_file.seek(0)
new_item =
[Link](

parent=parent_obj.getElement(),
name=name,
fileName=open_file.name,
)
else:
if isinstance(parent_obj,
[Link]):
new_item =
[Link](parent_obj, name, kind, origin_item)
else:
new_item =
[Link](parent_obj, name)
created_items[(parent, name)] = new_item

with [Link]('Assign
defaults for %s' % name, network_request=not trigger_return_updates):
for key, value in
self._decode_value_payload(default_values):
if isinstance(value, Element):
try:
abstraction =
[Link]([Link](parent))
except KeyError:
abstraction = None

if abstraction is not None:


value = abstraction

if isinstance(key, Element):
key = key._item
elif isinstance(key, list):
key = [i._item if
isinstance(i, Element) else i for i in key]

[Link](new_item,
key, value)

elif change_type == 'create_entry':


parent, name, value, default_values =
self._decode_value_payload(change)

# Clear the entry in the reserved names,


because the normal mechanisms for getting
# non-conflicting names will work now that the
item is created.
if name in self._reserved_names[parent]:
self._reserved_names[parent].remove(name)

if parent in ('', '/'):


parent_obj = [Link]._item
else:
parent_obj = fromPath(parent)

with [Link]('Create item %s


in %s' % (name, parent_obj.path()), network_request=not trigger_return_updates):
key = name
if isinstance(key, Element):
key = key._item

new_item = [Link](
parent=parent_obj,
key=key,
)
if value is not None:
[Link](new_item, [],
value)

created_items[(parent, name)] = new_item

with [Link]('Assign
defaults for %s' % name, network_request=not trigger_return_updates):
for key, value in
self._decode_value_payload(default_values):
if isinstance(value, Element):
abstraction =
[Link]([Link](parent))
if abstraction is not None:
value = abstraction
if isinstance(key, list):
key = [i._item if
isinstance(i, Element) else i for i in key]
elif isinstance(key, Element):
key = key._item

[Link](new_item,
key, value)

elif change_type == 'update':


path, value =
self._decode_value_payload(change)
element = [Link](path)
updated_objects.add(element)
if isinstance(value, Element):
abstraction =
[Link]([Link]())
if abstraction is not None:
value = abstraction

with [Link]('Set value %s


to %s.' % (path, value), network_request=not trigger_return_updates):
[Link](value)

[Link]()

elif change_type == 'delete_custom':


path = self._decode_value_payload(change)
item = fromPath(path)
with [Link]('',
network_request=not trigger_return_updates):
[Link](item)

elif change_type == 'create_custom':


parent, name, attributes =
self._decode_value_payload(change)
parent_obj = fromPath(parent)
with [Link]('',
network_request=not trigger_return_updates):
created_items[(parent, name)] =
[Link](parent_obj, name, attributes)

elif change_type == 'update_custom':


path, value =
self._decode_value_payload(change)
obj_to_update = fromPath(path)
obj_to_update.attributes = value

elif change_type == 'create_and_populate_outline':


name, origin, defaults, restrictions,
image_data = self._decode_value_payload(change)
self._createAndPopulateOutline(name, origin,
defaults, restrictions, image_data)

else:
raise Exception('Unknown change type: %s' %
change_type)

# # Wait for all creations to finish.


# for track, _, _, _, _ in
[Link]._subscriptions.values():
# if track._thread:
# track._thread.join()

def make_path(item):
"""
Make the full path of an item in a way that is compatible
with Element.
"""
output = ''

separator = '/'
for part in [Link]()[1:]:
# Once we hit the properties, everything is separated
by two dots.
if [Link]() == '$':
separator = '..'
output += separator + [Link]()

return output

for item in created_items.values():


if isinstance(item, [Link]):
continue

if [Link]() in [None, Ellipsis]:


parent = item._parent
while parent is not None and [Link]() in
[None, Ellipsis]:
parent = parent._parent
if parent is not None:
[Link]().stabilize()

# Stabilize all updates just to be sure.


# for element in updated_objects:
# [Link]()

[Link]({('%s/%s' % (parent, name)): make_path(item)


for (parent, name), item in created_items.items()})

[Link]([Link],
ExternalEvent(_deferred_bulkDeleteCreateAndUpdate))
# Returns a mapping of created names to full paths.
resp = [Link]() # send response when stabilization is
finished
if isinstance(resp, Exception):
raise resp

return resp

def deleteItems(self, paths):


paths = [[Link]('utf-8') for path in paths]

def _deferredDeleteItems():
ctx = Context([[Link](path) for path in paths])
self.skip_delete += [i for i in ctx]

[Link]('ProjectManagement').[Link]
(ctx)
[Link](('deleted', paths))

[Link]([Link],
ExternalEvent(_deferredDeleteItems))
action, elements = [Link]() # send response when
stabilization is finished

@staticmethod
def _decode_value_payload(obj):
if isinstance(obj, dict) and '__type__' in obj:
if obj['__type__'] == 'eHdrPenalty':
from [Link] import eHdrPenalty
return eHdrPenalty(obj['__value__'])

elif obj['__type__'] == 'eObservation':


from [Link] import eObservation
return eObservation(obj['__value__'])

elif obj['__type__'] == 'eDebugOutput':


from [Link] import eDebugOutput
return eDebugOutput(obj['__value__'])

elif obj['__type__'] == 'eSocketProtocol':


from [Link] import eSocketProtocol
return eSocketProtocol(obj['__value__'])
elif obj['__type__'] == 'eWireOrientation':
from [Link] import eWireOrientation
return eWireOrientation(obj['__value__'])

elif obj['__type__'] == '[Link]':


from [Link] import eVersion
return eVersion(obj['__value__'])

elif obj['__type__'] == '[Link]':


from [Link] import eVersion
return eVersion(obj['__value__'])

elif obj['__type__'] == '[Link]':


from [Link] import eVersion
return eVersion(obj['__value__'])

elif obj['__type__'] == '[Link]':


from [Link] import eVersion
return eVersion(obj['__value__'])

elif obj['__type__'] == '[Link]':


from [Link] import eApbVersion
return eApbVersion(obj['__value__'])

elif obj['__type__'] == '[Link]':


from [Link] import eOcpVersion
return eOcpVersion(obj['__value__'])

elif obj['__type__'] == 'eExportOptionType':


from [Link] import eExportOptionType
return eExportOptionType(obj['__value__'])

elif obj['__type__'] == 'eSimulator':


from [Link] import eSimulator
return eSimulator(obj['__value__'])

elif obj['__type__'] == 'enum':


module = __import__(obj['__module__'])
for part in obj['__module__'].split('.')[1:]:
module = getattr(module, part)
return getattr(module, obj['__name__'])(obj['__value__'])

elif obj['__type__'] == 'reference':


if obj['__value__'] is None:
return None
return
[Link](RootHandler._decode_value_payload(obj['__value__']))

elif obj['__type__'] == 'reference_item':


val = [Link]._item
for part in obj['__value__'].split('/'):
if not part:
continue
val = val[part]

return val

elif obj['__type__'] == 'lazy_reference':


return {
'__type__': 'reference_item',
'__value__': obj['__value__'],
}

elif obj['__type__'] == 'decimal':


dec = [Link](obj['__value__'])

if '__precision__' in obj:
dec =
[Link]([Link](obj['__precision__']))

return dec

elif obj['__type__'] == 'tuple':


return tuple([RootHandler._decode_value_payload(i) for i in
obj['__value__']])

else:
raise Exception('Unkown type to decode: "%s"' %
obj['__type__'])

elif isinstance(obj, dict):


obj = {RootHandler._decode_value_payload(k):
RootHandler._decode_value_payload(v) for k, v in [Link]()}

elif isinstance(obj, unicode):


obj = [Link]('utf-8')

# I think that json will actually turn all tuples into lists, so this
might never be called.
elif isinstance(obj, tuple):
obj = tuple([RootHandler._decode_value_payload(i) for i in obj])

elif isinstance(obj, list):


obj = [RootHandler._decode_value_payload(i) for i in obj]

return obj

def createNewElement(self, parent, name, kind, origin, default_values):


parent = [Link]('utf-8')
name = [Link]('utf-8')
kind = [Link]('utf-8')
origin = [Link]('utf-8')

default_values = self._decode_value_payload(default_values)

def _deferredCreateItemAndAddToRoutes():
with [Link]('Add new item.',
network_request=True):
with [Link]('Create %s %s.' % (kind,
name), network_request=True):
if parent == '':
parent_obj = [Link]
else:
parent_obj = [Link](parent)

if origin:
origin_item =
[Link](origin)._item
else:
origin_item = None

new_item = [Link](parent_obj._item, name,


kind, origin_item)

for key, value in default_values:


if isinstance(value, Element):
abstraction =
[Link]([Link](parent))
if abstraction is not None:
value = abstraction
[Link](new_item, key, value)

[Link](new_item.getElement().pathname([Link]))

[Link]([Link],
ExternalEvent(_deferredCreateItemAndAddToRoutes))
return [Link]() # send response when stabilization is
finished

def addEntryToList(self, path):


path = [Link]('utf-8')

def _deferred_addEntryToList():
array = [Link](path)

with [Link]('Add entry to the end of %s.' %


[Link](), network_request=True):
value = [Link]()
[Link](Undefined)
[Link](value)

[Link]()

[Link]([i for i in array][-1].pathname())

[Link]([Link],
ExternalEvent(_deferred_addEntryToList))
return [Link]() # send response when stabilization is
finished

def setValues(self, paths_and_values):


# List[Tuple[path: str, value: Any]]
paths_and_values = self._decode_value_payload(paths_and_values)

def _deferredSetValues():
with [Link]('Set values.',
network_request=True):
for path, value in paths_and_values:
element = [Link](path)
if isinstance(value, Element):
abstraction =
[Link]([Link](parent))
if abstraction is not None:
value = abstraction
with [Link]('Set value %s to %s.'
% (path, value), network_request=True):
[Link](value)

[Link](None)

[Link]([Link],
ExternalEvent(_deferredSetValues))
return [Link]() # send response when stabilization is
finished

def getRouteBeforeAndAfter(self, path):


path = [Link]('utf-8')

try:
obj = [Link](path)
except KeyError:
raise JSONRPCInvalidParams(message='No item at path "%s"' % path)

if not hasattr(obj, 'network') or 'info' not in obj['@'][[Link]]:


return {}

info = obj['@'][[Link]]['info']

all_routes = set()
route_preceeding = {}
route_successing = {}
for item, routes in [Link]():
for route in routes:
all_routes.add(route)
route_preceeding[route] = item

for item, routes in [Link]():


for route in routes:
all_routes.add(route)
route_successing[route] = item
return copy_dict({route: (route_preceeding.get(route, None),
route_successing.get(route, None)) for route in all_routes})

def subscribeToChanges(self, uuid):


self.subscriber_info[uuid] = {}

def getSubscriptionUpdates(self, uuid):


updates = self.subscriber_info[uuid].copy()
self.subscriber_info[uuid].clear()

return updates

def getFileContents(self, path):


path = [Link]('utf-8')
obj = [Link](path)
if hasattr(obj, 'file'):
return base64.b64encode([Link]().read())

return None

def getParent(self, path):


path = [Link]('utf-8')
obj = [Link](path)
return [Link]().pathname([Link])

def getName(self, path):


path = [Link]('utf-8')
obj = [Link](path)

if obj in [None, Ellipsis]:


obj = fromPath(path)

return [Link]()

def getKind(self, path):


path = [Link]('utf-8')

try:
obj = [Link](path)
except KeyError:
obj = None

if obj in [None, Ellipsis]:


item = fromPath(path)
if isinstance(item, [Link]):
return [Link]._xmlElementName
obj = [Link]()

return getattr(obj, 'kind', None)

def getOrigin(self, path):


path = [Link]('utf-8')
origin = [Link](path).origin()
if origin is not None:
origin = [Link]([Link])

return origin

def getProjectAncestor(self, path):


path = [Link]('utf-8')
ancestor = [Link](path).projectAncestor()
return [Link]([Link])

def getProjectJson(self):

def recursive_fill(element, container):


serialized = {
'__name__': [Link](),
'__fullpath__': [Link]() if isinstance(element,
[Link]) else [Link]([Link]),
'__children__': {},
}

if '__children__' in container:
container['__children__'][[Link]()] = serialized
else:
container[[Link]()] = serialized

if isinstance(element, [Link]):
if 'value' in [Link]:
serialized['__value__'] =
copy_dict([Link]['value'])

serialized['__kind__'] = 'arterisCustom'

for child in element:


recursive_fill(child, serialized)

return

if getattr(element, 'kind', None) is not None:


serialized['__kind__'] = [Link]

if [Link]() is not None and [Link]() is not None:


serialized['__origin__'] = copy_dict([Link]())

if hasattr(element, 'value') and [Link]() != '$':


if not element._status:
[Link]()
serialized['__value__'] = copy_dict([Link]())

if hasattr(element, 'file'):
serialized['__file__'] =
base64.b64encode([Link]().read())

# We don't care about any children of the structure. We only want


it for going
# from the floorplan to the architecture through the origin.
if getattr(element, 'kind', None) in ['switchBasedStructure',
'flow']:
return

parameter_whitelist = set()
if [Link]() == '$':
kind = getattr([Link](), 'kind', '')

if kind == 'switchBasedArchitecture':
parameter_whitelist.add('datapathRoute')
parameter_whitelist.add('serviceRoute')
parameter_whitelist.add('observationRoute')
parameter_whitelist.add('dvmRoute')

elif kind == 'outline':


parameter_whitelist.add('background')
parameter_whitelist.add('bounding')
parameter_whitelist.add('resolution')
parameter_whitelist.add('technology')

elif kind == 'restriction':


parameter_whitelist.add('exclusive')
parameter_whitelist.add('zones')

elif kind == 'structureFloorplan':


parameter_whitelist.add('results')

elif kind == 'specification':


parameter_whitelist.add('connectivity')
parameter_whitelist.add('dependencies')

elif kind in ['target', 'initiator', 'socket']:


parameter_whitelist.add('clock')
parameter_whitelist.add('protocol')
parameter_whitelist.add('common')
parameter_whitelist.add('performance')
parameter_whitelist.add('datapath')
parameter_whitelist.add('service')
parameter_whitelist.add('dvm')
parameter_whitelist.add('observation')
parameter_whitelist.add('position')
parameter_whitelist.add('synthesisPosition')
parameter_whitelist.add('inputPipe')
parameter_whitelist.add('outputPipe')
parameter_whitelist.add('axiPipes')
parameter_whitelist.add('genericPipes')
parameter_whitelist.add('internalPipes')
parameter_whitelist.add('conversion')
parameter_whitelist.add('serialization')

elif kind == 'observer':


parameter_whitelist.add('clock')
parameter_whitelist.add('position')
parameter_whitelist.add('synthesisPosition')
parameter_whitelist.add('debugOutput')
parameter_whitelist.add('observation')
parameter_whitelist.add('serialization')

elif kind[0:3] in ['dtp', 'srv', 'obs', 'dvm', 'swb']:


parameter_whitelist.add('common')
parameter_whitelist.add('synthesisPosition')
parameter_whitelist.add('inputPipe')
parameter_whitelist.add('outputPipe')
parameter_whitelist.add('inputPipes')
parameter_whitelist.add('outputPipes')
parameter_whitelist.add({
'dtp': 'datapath',
'srv': 'service',
'obs': 'observation',
'dvm': 'dvm',
'swb': 'dvm',
}[kind[0:3]])
parameter_whitelist.add('serialization')

for child in element:


# Skip compiled elements and issues.
if [Link]() in [
'@',
'!',
'customTopologyColor',
'domainCrossings',
'comment',
'reqObservation',
'rspObservation',
]:
continue

if parameter_whitelist and [Link]() not in


parameter_whitelist:
continue
recursive_fill(child, serialized)

# If no sub-parameters were serialized, then there is no


point in serializing
# this properties element.
if [Link]() == '$' and not serialized['__children__']
['$'].get('__children__', None):
serialized['__children__'].pop('$')

if element._item:
custom_items = [i for i in element._item if isinstance(i,
[Link])]
for item in custom_items:
recursive_fill(item, serialized)

# If we don't have any children, then don't keep it in the


dictionary because it
# will take space in the serialization.
if not serialized['__children__']:
[Link]('__children__')

output = {}
for child in [Link]:
if getattr(child, 'kind', None) in ['scenario', 'scenarioResult',
'nocComposition', 'exportOption']:
continue

recursive_fill(child, output)

return output

def getProjectTree(self):
output = {}

def recursive_fill(node):
node_name = '/'.join([str(i) for i in [Link]() if i is
not None])
output[node_name] = {
'children': ['/'.join([str(i) for i in [Link]()
if i is not None]) for child in node],
}

if getattr(node, 'kind', None):


output[node_name]['kind'] = [Link]

for child in node:


recursive_fill(child)

recursive_fill([Link])

return output

def getValue(self, path):


path = [Link]('utf-8')

try:
element = [Link](path)
except KeyError:
element = None

if element in [None, Ellipsis]:


item = fromPath(path)
if isinstance(item, [Link]):
# We need to build a value dict from the children.
def recursive_fill(node):
# The item has a value, so just return that.
if 'value' in [Link] and
[Link]['value'] != '':
return copy_dict([Link]['value'])

# The item does not have a direct value, so build a


dict with the children and
# their values.
output = {}
for child in node:
output[[Link]()] = recursive_fill(child)

return output

return copy_dict(recursive_fill(item) or None)

element = [Link]()

elif [Link]:
try:
item = fromPath(path)
value = [Link]()
return copy_dict(value)
except KeyError:
pass

if not element._status:
[Link]()

return copy_dict([Link]())

def pathExists(self, path):


path = [Link]('utf-8')
try:
[Link](path)
except KeyError:
return False

return True

def getChild(self, path, childname):


path = [Link]('utf-8')
childname = [Link]('utf-8')

if path =='/':
child = [Link](path + childname)
else:
try:
parent = [Link](path)
except KeyError:
parent = None
if parent in [None, Ellipsis]:
parent_item = fromPath(path)
if isinstance(parent_item, [Link]) and
childname in parent_item:
return parent_item[childname].path()

parent = parent_item.getElement()

if not parent._status:
[Link]()
try:
child = parent[childname]
except KeyError:
child = None

if child in [None, Ellipsis]:


try:
child = [Link](path + '/' +
childname)
except KeyError:
child = None

if child in [None, Ellipsis]:


child = fromPath(path + '/' + childname)

if isinstance(child, [Link]):
return [Link]()

return [Link]([Link])

def getKeys(self, path):


path = [Link]('utf-8')
if path == '/':
return [[Link]() for i in [Link]]

try:
item = fromPath(path)
if isinstance(item, [Link]):
return [[Link]() for i in item if isinstance(i,
[Link])]
except KeyError:
pass

try:
element = [Link](path)
if not element._status:
[Link]()
return [[Link]() for i in element] + [[Link]() for i in
element._item if isinstance(i, [Link])]

except:
pass

return []

def getIter(self, path):


path = [Link]('utf-8')
if path == '/':
return [[Link]([Link]) for i in [Link]] +
[[Link]() for i in [Link]._item if isinstance(i, [Link])]

try:
element = [Link](path)
except KeyError:
element = None

if element in [None, Ellipsis]:


item = fromPath(path)
if isinstance(item, [Link]):
return [[Link]() for i in item if isinstance(i,
[Link])]

element = [Link]()

if not element._status:
[Link]()

result = [[Link]([Link]) for i in element]


if element._item:
result += [[Link]() for i in element._item if isinstance(i,
[Link])]

return result

def childrenOfKind(self, path, kind):


path = [Link]('utf-8')
if path == '/':
return [[Link]([Link]) for i in [Link] if
getattr(i, 'kind', None) == kind]

return [[Link]([Link]) for i in


[Link](path) if getattr(i, 'kind', None) == kind]

# Requests
def savePdd(self,XMLFile):
def save():

[Link]('SaveProjectAs').trigger(pddName=XMLFile,fromJsonServer=True)
[Link](('saved',None))
[Link]([Link],ExternalEvent(save))
action,_ = [Link]()
return {}

def getOpenPddFunc(self,message):
def openPdd(XMLFile):
def open():
error = [Link]('OpenProject').trigger(XMLFile)
if not error:
[Link]()
[Link](('opened',None))
else:
[Link](('error',None))
[Link]([Link],ExternalEvent(open))
action,_ = [Link]()

if action == 'error':
raise LoadException()
else:
# Create list of object status
def getChildObject(element):
childObjects = filter(lambda e : [Link], element)
return childObjects + reduce(list.__add__,
map(getChildObject,childObjects), [])

objectStatus = {[Link]():[Link]() for


element in getChildObject([Link])}

return {
"objectStatus" : objectStatus
}
return openPdd
def _getViewOpenKwargs(self,element,hiddenEntries):
hiddenPages = []
kwargs = {}
if element is not None and [Link] in [Link]():
kwargs['shownKind'] = [Link]
for name in hiddenEntries:
tab,pageName = [Link](':')
if tab in [Link] and [Link][tab] !=
[Link]: continue
[Link] ( [Link]('.') )
kwargs['hiddenPages'] = hiddenPages
return kwargs

def openEditor(self,actor,responseMessage):
def openViewEditor(objectPath=None,hiddenEntries=None):
if objectPath is not None:
try:
element = [Link](objectPath)
except Exception, e:
raise ObjectPathException()
else:
element = None
if hiddenEntries is None:
hiddenEntries = []

kwargs = self._getViewOpenKwargs(element,hiddenEntries)

def _openEditor():
if objectPath is not None:
element = [Link](objectPath)
[Link]()
context = Context((element,))
else:
context = Context(([Link](),))

r = [Link]('ViewOpen')[actor].trigger(context,**kwargs)
if r is None:
[Link](('error',None))
else:
[Link]((responseMessage,None))

[Link]([Link],ExternalEvent(_openEditor))
action,_ = [Link]()
if action == 'error':
raise OpenException()
return {}
return openViewEditor
def openDesignDiff(self):
def _openDesignDiff():
r = [Link]('DesignDiff').trigger()
if r is None:
[Link](('error',None))
else:
[Link](('openedDesignDiff',None))

[Link]([Link],ExternalEvent(_openDesignDiff))
action,_ = [Link]()

if action == 'error':
raise OpenException()
return {}

def pause(self,string):
def pause():
if [Link] is None:
mainWindow = [Link]('Gui').mainWindow
[Link] = PauseDialog(mainWindow,string)
#[Link].exec_()
[Link]([Link],ExternalEvent(pause))
# Wait until the dialog is instantiated before handling further
commands. Otherwise if we
# receive a resume command and handle it immediately the dialog box
does not exits yet and is not closed.
while not [Link]:
[Link](0.1)
return {}

def resume(self):
if [Link]:
[Link]([Link],[Link]())
[Link] = None
return {}

def stabilize(self,object):
def stabilize():
element = [Link](object)
[Link]()
[Link](('stabilized',element))

try:
element = [Link](object)
except Exception, e:
raise ObjectPathException()

[Link]([Link],ExternalEvent(stabilize))
action,element = [Link]() # send response when
stabilization is finished

def getIssuesList(element):
def getIssues(element):
childIssues = reduce(list.__add__, map(getIssues,
filter(lambda e:[Link], list(element))), [])
return list(element['!']) + childIssues

issueList = []
for issue in getIssues(element):
[Link]({
'pathname' : [Link]().pathname()
, 'code' : [Link]()
, 'shortMsg' : [Link]()
, 'longMsg' : [Link]()
, 'reason' : [Link]()
})
return issueList
result = {
"objectStatus": [Link]()
, "issueList": getIssuesList(element)
}

return result

def exit(self,force):
def exit():
error = False
error |= force == 1 and [Link]()

if not error:
[Link]('Quit').trigger(force)
[Link](('exited',None))
else:
[Link](('error',None))

[Link]([Link],ExternalEvent(exit))
action,path = [Link]()
if action == 'error':
raise ExitException()
return {}

def importPDD(self,file,folderName=None):
return
self._importWithFolderName(file,folderName,"ImportPdd",'importedPDD')
def importOcpRtlConf(self,file,folderName=None):
return
self._importWithFolderName(file,folderName,"ImportRtlConf",'importedOcpRtlConf')
def importAreaResults(self,file,folderName=None):
return
self._importWithFolderName(file,folderName,"ImportAreaResult",'importedAreaResults'
)
def importFloorplanResults(self,file,folderName=None):
return
self._importWithFolderName(file,folderName,"ImportFloorplanResult",'importedFloorpl
anResults')
def
_importWithFolderName(self,filename,folderName,actionName,responseMessage='imported
'):
if folderName is None:
folderName = 'import'
def import_():
importResult =
[Link](actionName).trigger(filename ,folderName=folderName)
[Link]((responseMessage,importResult))

[Link]([Link],ExternalEvent(import_))
message,importResult = [Link]()
if not importResult:
raise ImportException()
return {}
def importScript(self,file):
return self.import_(file,"ImportScript")
def importVCD(self,VCDFile):
return self.import_(VCDFile,"ImportVCD")

def import_(self,filename,actionName,responseMessage='imported'):
def import_():
importResult =
[Link](actionName).trigger(filename ,fromJsonServer=False)
[Link]((responseMessage,importResult))

[Link]([Link],ExternalEvent(import_))
message,(importResult,errorInfo) = [Link]()

result = errorInfo
return result

def importAttachment(self,file,folderName=None):
if folderName is None:
folderName = 'import'
folderName = [Link]('.','_')
def import_():
name = str([Link](file).replace('.','_').replace('
',''))
with [Link]( "Importing attachment
from \"%s\"." % file ):
try:
folderItem = [Link]('/%s'%folderName)._item
except KeyError:
folderItem =
[Link]([Link]._item,folderName,'folder')
elt=[Link](folderItem,name,
open(unicode(file)) , file , [Link]() , "------" )
[Link](('importedAttachment',None))

[Link]([Link],ExternalEvent(import_))
message,importResult = [Link]()
return {}

def getSaveState(self):
return {
"state": "modified" if [Link]() else
"unmodified"
}
def setStyle(self,style):
def _setStyle():
st = [Link](style)
[Link](st)
[Link](('styleSet',None))
[Link]([Link],ExternalEvent(_setStyle))
action,_ = [Link]()
return {}

# Notifications
def sendNotification(self,methodName,**params):
notification = {"jsonrpc": "2.0", "method": methodName}
if params: notification['params'] = params

# [Link]("Sending notification",[Link](notification,
sort_keys=True,indent=4, separators=(',', ': ')))
global ioloop
ioloop.add_callback(self.write_message,[Link](notification))

def projectSaved(self,filename):
[Link]("saved",XMLFile=filename)

def raise_(self):
[Link]('raise')

def projectModified(self,filename):
[Link]("modified", XMLFile=filename)
def stable(self):
f=lambda x: x.is_alive() and isinstance(x,StabilizingThread)
j=lambda x: [Link]()
[Link]()
while(self.ws_connection is not None):
[Link]()
[Link]("unstable")
map(j,filter(f,[Link]()))
[Link]()
[Link]("stable")
def userExit(self):
[Link]("userExit")
def userImportScript(self, result, infos):
[Link]("userImportScript", **infos)
def userImportVCD(self, result, infos):
[Link]("userImportVCD",**infos)

from [Link].utf8write import utf8write


from [Link] import ErrorReportListener
from [Link] import LogFileManager
import sys
from [Link] import pyqtSignal, QObject, QEvent

# class JsonReport(object):
# def __init__(self,activate=True):
# self._activate = activate
# self._installed = None
# self._logFileManager = LogFileManager("JSON-RPC")
# def __enter__(self):
# if self._activate :
# assert not self._installed
# filename = self._logFileManager.getNewLogFilename()
# if filename is None: return #The log dir could not be created
# f = open(filename,'w')
# utf8write(f,'**************************** FLEXNOC JSON-RCP log
***************************************\n')
# for s in nsVersion : utf8write(f,'%s\n'%s)
#
# l = [Link]()
# [Link](filename)
# self._installed = ErrorReportListener(l,f)
# def __exit__(self,excType,excValue,excTb):
# if self._installed :
# self._installed.__swig_destroy__(self._installed)
# self._installed = None

class Server(View, QObject):


def __init__(self,port):
super( Server , self ).__init__()
[Link] = port
[Link] = (port == -1)
[Link] = None
[Link] = None
[Link] = None
self._block_changes = False
[Link] = [Link]()
# since the handler is run in another thread, it cannot connects to qt
signals. Connect here and forward to the
# handlers
done=pyqtSignal('PyQt_PyObject',name="done")

[Link]('SaveProjectAs').connect([Link]('SaveProjectAs'),done,[Link]
)

[Link]('SaveProject' ).connect([Link]('SaveProject' ),done,[Link]


)

[Link]('ImportScript' ).connect([Link]('ImportScript' ),done,[Link]


ted)

[Link]('ImportVCD' ).connect([Link]('ImportVCD' ),done,[Link]


)

[Link]('ChanceToSave' ).connect([Link]('ChanceToSave' ),done,[Link]


)
[Link] = [Link]()
[Link] = [Link](self)
[Link][[Link]] = None
[Link] = EventReceiver([Link])
[Link] = [Link](target = [Link],name='JSON server')
[Link] = []
[Link].stack_set = set()
[Link]._poison = False
[Link].__logStack__ = [ [Link]() ]
[Link]=True
[Link]=False
[Link](self)

[Link] = [Link](
'Sending Updates',
[Link](),
0,
0,
None,
)
[Link](True)
[Link](False)
[Link]([Link].WA_DeleteOnClose, False)

@property
def block_changes(self):
return self._block_changes

@block_changes.setter
def block_changes(self, value):
self._block_changes = value

if value and app.window_active:


[Link]()
elif not value and [Link]():
[Link]()

def showProgressIfFocused(self):
if app.window_active:
[Link]()

def closeProgressBar(self):
[Link]()

def eventFilter(self, obj, event):


if [Link]() == [Link]:
app.window_active = False
elif [Link]() == [Link]:
# if app.window_active is False and [Link]:
# from [Link] import
SwitchArchitectureEditorView
# for view, _ in [Link]._subscriptions.items():
# if isinstance(view, SwitchArchitectureEditorView):
# import ipdb; ipdb.set_trace()
# [Link](view)
# [Link](view)
# app.window_active = True
# print("deactive app_window True", app.window_active)
if self.block_changes and not [Link]():
print("block changed")
[Link]()

return False

def __dtor__(self):
[Link](self)
def notifyElement(self, deletions , updates, creations, renames,
changed_sb_items):
pass
def notifyStableRoot(self):
if not [Link]:
[Link]=True
[Link]()
def notifyCompletion(self):
if [Link]():
for handler in [Link]:
[Link]([Link]())
def raise_(self):
for handler in [Link]:
handler.raise_()
def notifyDeletedRoot(self):
[Link](self)

def saved(self,result):
if not result:
for handler in [Link]:
[Link]([Link]())

def userExit(self):
for handler in [Link]:
[Link]()

def scriptImported(self,result):
# The user canceled the import.
if result is False:
return

for handler in [Link]:


[Link](*result)

def vcdImported(self,result):
# The user canceled the import.
if result is False:
return

for handler in [Link]:


[Link](*result)

def run(self):
server = [Link]([
(r"/", RootHandler)
])

if [Link] == -1:
sockets = [Link].bind_sockets(0, '[Link]')
[Link] = sockets[0].getsockname()[:2][1]
http_server = [Link](server)
http_server.add_sockets(sockets)

else:
[Link]([Link])

if __options__.notifyAfterServerStart or [Link]:
print 'Websocket server has been started at port %d.' % [Link]
[Link]()

global ioloop
ioloop=[Link]()
[Link]()

def stop(self):
global ioloop
if [Link]:
[Link]()

def startServer(port):
import [Link] as app
[Link] = Server(port)

You might also like