示例#1
0
  def newasset_action(self, request):
    '''Adds the new asset to the board'''
    if request.getvalue('assetid', ''): # editing
      asset = datagate.get_item(request.getvalue('assetid', ''))
    else: # new item
      game = datagate.get_item(request.getvalue('global_rootid'))
      turns = game.search1(name='turns')
      fileitem = request.form['_icon']
      if not fileitem.filename:
        request.error = 'Assets must have an associated icon.'
        return
      zeroTurn = turns.get_child(turns.childids[0]).search1(name='assetmoves')
      asset = datagate.create_item(parentid=zeroTurn.id, creatorid=request.session.user.id)
      asset.filename = ''
    asset.assetid = GUID.generate()
    asset.name = request.getvalue('name', '')
    asset.width = request.getvalue('width', '')
    asset.height = request.getvalue('height', '')
    asset.row = request.getvalue('row', '')
    asset.col = request.getvalue('col', '')
    asset.striking = request.getvalue('_striking')
    asset.defensive = request.getvalue('_defensive')
    asset.sight = request.getvalue('_sight')
    asset.visibility = request.getvalue('_visibility')
    asset.terrains = request.getlist('_terrains')

    asset.visible_by=[]
    
    asset.move_by=[]
    fileitem = request.form['_icon']
    if fileitem.filename:
      asset.filebytes = fileitem.file.read()
      asset.filetype = fileitem.type
      asset.filename = fileitem.filename
    asset.save()
示例#2
0
 def __init__(self, creatorid='', parentid=''):
   '''Constructor -- called only for new Items'''
   self.id = GUID.generate()
   self.creatorid = creatorid
   self.parentid = parentid
   # ids of my children (in order)
   # do _not_ keep direct references as pickling will serialize entire trees
   self.childids = []
示例#3
0
    def registerDeviceNotification(self, guid, devicetype=DBT_DEVTYP_DEVICEINTERFACE):
        devIF = DEV_BROADCAST_DEVICEINTERFACE()
        devIF.dbcc_size = ctypes.sizeof(DEV_BROADCAST_DEVICEINTERFACE)
        devIF.dbcc_devicetype = devicetype

        if guid:
            devIF.dbcc_classguid = GUID.GUID(guid)
        return RegisterDeviceNotification(self.GetHandle(), ctypes.byref(devIF), 0)
示例#4
0
 def __init__(self, rp, script):
   self.running = 1
   self.id = GUID.generate()
   self.ratingproxy = rp
   self.starttime = time.localtime()
   self.rows = script.split("\n")
   threading.Thread.__init__(self)
   self.setDaemon(1)
   self.current = 0
   self.nextsend = 0
示例#5
0
 def _rewrite_ids(self, parentid, guids):
   '''Helper method for rewrite_ids.  Don't call directly'''
   items_lock.acquire()
   try:
     # rewrite my id, save in cache under new id, and map old guid to new guid
     oldguid = self.id
     self.id = GUID.generate()
     self.parentid = parentid
     items_cache[self.id] = [ threading.RLock(), self ]
     guids[oldguid] = self
     
     # rewrite my children
     for i in range(len(self.childids)):
       child = get_item(self.childids[i])
       child._rewrite_ids(self.id, guids)
       self.childids[i] = child.id # now we have the new childid recorded in our child list
       
   finally:
     items_lock.release()
示例#6
0
  def handle_request(self, request, viewname):
    '''Handles the main request.'''
    # send the common javascript that every view enjoys
    request.writeln('''
      <script language='JavaScript' type='text/javascript'>
        /* Clears an input field (the first time it is entered) */
        function clearField(field) {
          if (!field.cleared) { // only clear once
            field.value = '';
          }
          field.cleared = true;
        }
        
        /* Confirms a url given a message before going to it in a target frame */
        function confirm_target_url(msg, frame, urlst) {
          if (confirm(msg)) {
            frame.location.href = urlst;
          }
        }
        
        /* Confirms a url given a message before going to it */    
        function confirm_url(msg, urlst) {
          confirm_target_url(msg, window, urlst);
        }
        
        /* Retrieves the text children of an XML node */
        function getNodeText(node) {
          var text = "";
          for (var i = 0; i < node.childNodes.length; i++) {
            if (node.childNodes[i].nodeType == 3) { // IE doesn't recognize the TEXT_NODE constant
              text += node.childNodes[i].nodeValue;
            }
          }
          return text;
        }
        
        /* Translates the evt object to get a cross-browser event source element.
           Note that this is a JavaScript event, and it has nothing to do with the
           server-side event system! */
        function getEventSource(evt) {
          // this code is taken from Dynamic HTML Reference by Danny Goodman
          evt = (evt) ? evt : ((event) ? event : null);
          if (evt) {
            var elem = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
            if (elem) {
              return elem;
            }
          }
          return null;
        }
        
        /* Replaces all occurances of one string within another string (JavaScript's replace only does one - this ensures consistencies across DOM implementations) */
        function replaceAll(st, oldSt, newSt) {
          // short circuit
          if (st == null || oldSt == null || newSt == null) {
            return st;
          }//if
          var buf = "";
          // step through and replace each occurance
          var current = 0;
          var pos;
          while ((pos = st.indexOf(oldSt, current)) >= 0) {
            buf += st.substring(current, pos);
            buf += newSt;
            current = pos + oldSt.length;
          }//while
      
          // add any remaining text at the end
          buf += st.substring(current, st.length);
          return buf;  
        }
         
        /* Convenience method to get the first child with nodeName=name (case insensitive) for an element */
        function xmlGetChild(node, name) {
          for (var i = 0; i < node.childNodes.length; i++) {
            var child = node.childNodes.item(i);
            if (child.nodeName.toLowerCase() == name.toLowerCase()) {
              return child;
            }
          }
        }
        /* Convenience method to get a list of children with nodeName=name (case insensitive) for an element */
        function xmlGetChildren(node, name) {
          var children = new Array();
          for (var i = 0; i < node.childNodes.length; i++) {
            var child = node.childNodes.item(i);
            if (child.nodeName.toLowerCase() == name.toLowerCase()) {
              children[children.length] = child;
            }
          }
          return children;
        }
        /* Convenience function to clear all children of an XML element */
        function xmlClear(node) {
          while (node.firstChild != null) { 
            node.removeChild(node.firstChild);
          }
        }
            
        /*
         * Javascript's native encodeURI and encodeURIComponent does not handle all characters,
         * (and base64 doesn't work either because it uses reserved characters in the url,)
         * so I have a homegrown solution that does everything except the following chars:
         */
        var alphanumeric = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        var qualifier = "_";
        var base = 16;
        var pad = 4;
        function encode(st) {
          var newst = "";
          for (var i = 0; i < st.length; i++) {
            if (alphanumeric.indexOf(st.charAt(i)) >= 0) {
              newst += st.charAt(i);
            }else{
              newst += qualifier;
              var h = st.charCodeAt(i).toString(base);
              for (var j = h.length; j < pad; j++) {
                newst += '0';
              }
              newst += h;
            }
          }
          return newst;
        }
        function html(st) {
           ''' + html_conversions + '''
           return st;
        }
        function decode(st) {
          var newst = "";
          for (var i = 0; i < st.length; i++) {
            if (st.charAt(i) == qualifier && st.length >= i + pad + 1) {
              newst += String.fromCharCode(parseInt(st.substring(i+1,i+pad+1), 16));
              i += pad;
            }else{
              newst += st.charAt(i);
            }
          }
          return newst;
        }      

        </script>
    ''')     

    if self.interactive:
      # register for events on this item
      request.windowid = GUID.generate()
      rootid = request.getvalue('global_rootid', '')
      request.session.add_event_queue(request.windowid, rootid) 
      Events.add_listener(request.session, rootid)
      
      # send the initial events for this view to the event system
      for event in self.get_initial_events(request, rootid):
        request.session.process(rootid, event, request.windowid)
        
      # send the interactive code
      request.writeln('''
        <script language='JavaScript' type='text/javascript'>
          var refreshEnabled = false;
          var timerid = -1;
          var eventsRequest = null;
          
          /** Sends a change action to the server.  This function takes the action_method to be called,
              then a variable number of arguments to be sent to the server as part of the call. */
          function sendEvent(action_method) {
            // short circuit if we're already in a call -- we don't allow two calls at once
            if (eventsRequest != null || !refreshEnabled) {
              return;
            }

            // clear the timer (just in case we were called directly)
            if (timerid) {
              clearTimeout(timerid);
            }

            // create the eventsRequest object
            if (window.XMLHttpRequest) { // Mozilla, Safari,...
              eventsRequest = new XMLHttpRequest();
              if (eventsRequest.overrideMimeType) {
                eventsRequest.overrideMimeType('text/xml');
              }
            }else if (window.ActiveXObject) { // IE
              try {
                eventsRequest = new ActiveXObject("Msxml2.XMLHTTP");
              }catch (e) {
                try {
                  eventsRequest = new ActiveXObject("Microsoft.XMLHTTP");
                }catch (e2) {
                  alert("Your browser does not support AJAX.  Please upgrade your browser to run this application");
                  return;
                }
              }
            }

            // wrap up the arguments
            var args = [];
            var debugargs = [];
      ''')
      for key, value in request.get_global_parameters({'gm_contenttype':'text/xml', 
                                                       'gm_internal_action':'send_events_xml',
                                                       'global_windowid': request.windowid,
                                                      }):
        request.writeln('            args[args.length] = "' + key + '=' + value + '";')
      request.writeln('''
      
            // is there an action to encode with this call?
            if (action_method != null) {
              args[args.length] = "gm_action=" + action_method;
              for (var i = 1; i < sendEvent.arguments.length; i++) {
                var arg = sendEvent.arguments[i];
                args[args.length] = "gm_arg" + i + "=" + event_arg_encode(arg);
                debugargs[debugargs.length] = arg;
              }
            }
            
            // show the event in the debugger, if open
            if (top.showDebugEvent) {
              if (action_method == null) {  // a normal update
                //took this out because it causes too much traffic in the events window
                //top.showDebugEvent("QueuePop", "\xA0", "\xA0", "#99FF99");
              }else{
                top.showDebugEvent("Send", action_method, debugargs, "#99CCFF");
              }
            }
            
            // send the request
            eventsRequest.open('POST', "''' + CGI_PROGRAM_URL + '''", true);
            eventsRequest.onreadystatechange = receiveRefreshResponse;
            eventsRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            eventsRequest.send(args.join('&'));
          }//sendEvent function
          
          /** Recursively encodes an argument, including Array types. */
          function event_arg_encode(arg) {
            if (arg instanceof Array && arg.length) { // regular array/python list
              encodedarg = "a";
              for (var i = 0; i < arg.length; i++) {
                encodedarg += event_arg_encode(arg[i]);
              }
              encodedarg += '-';
              return encodedarg;
            }else if (arg instanceof Array) { // associative array/python dictionary
              encodedarg = "d";
              for (key in arg) {
                encodedarg += event_arg_encode(key) + event_arg_encode(arg[key]);
              }
              encodedarg += '-';
              return encodedarg;
            }else if (typeof arg == 'number') {
              if (arg % 1 == 0) {
                return "i" + encode(arg + "") + '-';
              }else{
                return "f" + encode(arg + "") + '-';
              }
            }else if (typeof arg == 'boolean') {
              return "b" + encode(arg ? 'True' : 'False') + '-';
            }else {
              return "s" + encode(arg + "") + '-';
            }          
          }
          
          /** Automatically called by the XMLHttpRequest object with the refresh response from the server */
          function receiveRefreshResponse() {
            // ensure everything is here and we have a good response (this gets called whenever data comes, so it happens multiple times)
            try {
              if (eventsRequest.readyState != 4 || eventsRequest.status != 200) {
                // don't reset anything -- this method will get called again when status == 200 (i.e. everything's here)
                return;
              }
            }catch (e) {  
              // we have to reset everything or else the pop events call won't work next time
              eventsRequest = null;  // reset for next call
              if (timerid) {
                clearTimeout(timerid);
              }
              timerid = setTimeout('sendEvent(null)', ''' + str(POLLING_TIME_IN_SECONDS * 1000) + ''');
              return;
            }

            try {
              // get the XML and free up the eventsRequest object for another call
              var xmldoc = eventsRequest.responseXML;
  
              // get the xml and call the handler function for each event node
              var events = xmldoc.firstChild.childNodes;
              for (var i = 0; i < events.length; i++ ) {
                var event = events[i];
                if (event.nodeName == 'event') {
                  // get the arguments
                  var args = [];
                  for (var j = 0; j < event.childNodes.length; j++) {
                    args[args.length] = event_arg_decode(event.childNodes[j]);
                  }
                  
                  // show the event in the debugger, if open
                  if (top.showDebugEvent) {
                    top.showDebugEvent("Receive", event.getAttribute('handler'), args, "#CCCC99");
                  }

                  // call the function
                  var handler = window[event.getAttribute('handler')];
                  handler.apply(null, args);
                }
              }

            }finally{
              // reset the eventsRequest and timer for another call
              eventsRequest = null;  // reset for next call
              if (timerid) {
                clearTimeout(timerid);
              }
              timerid = setTimeout('sendEvent(null)', ''' + str(POLLING_TIME_IN_SECONDS * 1000) + ''');
            }
          }//receiveRefreshResponse function


          /** Recursively decodes xml-encoded arguments, including Array types. 
              See Events.process_argument for the creator this xml. */
          function event_arg_decode(argnode) {
            if (argnode.nodeName == 'argument') {
              if (argnode.getAttribute('type') == 'list') {
                var args = [];
                for (var j = 0; j < argnode.childNodes.length; j++) {
                  args[args.length] = event_arg_decode(argnode.childNodes[j]);
                }
                return args;
              
              }else if (argnode.getAttribute('type') == 'dict') {
                var args = new Array();
                for (var j = 0; j < argnode.childNodes.length; j += 2) {
                  args[event_arg_decode(argnode.childNodes[j])] = event_arg_decode(argnode.childNodes[j+1]);
                }
                return args;

              }else{
                var value = argnode.firstChild.nodeValue; // CDATA section
                if (argnode.getAttribute('type') == 'bool') {
                  return (value == 'True');
                }else if (argnode.getAttribute('type') == 'int') {
                  return parseInt(value);
                }else if (argnode.getAttribute('type') == 'float') {
                  return parseFloat(value);
                }else {
                  return value;
                }
              }
            }
          }
          
          
          /** Starts the event loop.  Subclasses must call this when they are finished setting up.
              if we started pulling events before the web page is set up, we might call functions that
              don't exist yet.  Because views might be made up of multiple frames, there is no way
              to automatically know when the page is ready (onLoad doesn't work).  Therefore, 
              subclasses MUST call this method when they are done setting up to start the event loop. */
          function startEventLoop() {
            refreshEnabled = true;
            sendEvent(null);
          }
          
          
          /** Disables the refreshing of events from the server.  Call this when you
              want to stop events from happening, such as when the user is entering
              a comment.  Don't forget to enableRefresh() when done! */
          function disableRefresh() {
            refreshEnabled = false;
            if (timerid) {
              clearTimeout(timerid);
            }
          }
          
          
          /** Enables the refreshing of events */
          function enableRefresh() {
            refreshEnabled = true;
            sendEvent(null);
          }
          
          /** Refreshes the events now */
          function refreshEvents() {
            enableRefresh();
          }
          
          /** Tells the client to log in again */
          function gm_loginAgain() {
            alert('Your session has timed out.  Please log in again.');
            window.location.replace("''' + CGI_PROGRAM_URL + '''");
          }
          
        </script>
      ''')
    
    # let the subclass send it's content
    self.send_content(request)
示例#7
0
 def __init__(self, user):
   self.id = GUID.generate()
   self.started = time.time()
   self.user = user
   self.listeners = {}    # windows that are listening for events
   self.lock = threading.RLock()
示例#8
0
        flags["olg_path"] = val
    elif key == '-E':
        flags["exe_path"] = val
    elif key == '-T':
        flags["time"] = int(val)
    elif key == '-h':
        usage()
        sys.exit(0)

try:
    hostname = socket.gethostname().split('.')[0]
    args=[flags["exe_path"], 
          '-o', flags["olg_path"], 
          '-D', "LANDMARK=\"" + LANDMARK_NODEID + ":" + PORT + "\"",
          '-D', "LOCALADDRESS=\"" + hostname + ":" + PORT + "\"",
          '-n', hostname,
          '-p', PORT,
          '-D', "NODEID=0x" + GUID.generate() + "I",
          '2>&1']
    p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)
except OSError, e:
    print "Execution failed"
    print e
    sys.exit(0)


if os.getpid() != p.pid:
    t = threading.Timer(flags["time"], kill_pid, [p.stdout, p.pid])
    t.start()
    sys.exit(0)