<commit_before>var xutil = require('./xutil');
var hexy = require('./hexy').hexy;

var valueMask = {
    CreateWindow: {
        backgroundPixmap: 0x00000001,
        backgroundPixel : 0x00000002,
        borderPixmap    : 0x00000004,
        borderPixel     : 0x00000008,
        bitGrawity      : 0x00000010,
        winGravity      : 0x00000020,
        backingStore    : 0x00000040,
        backingPlanes   : 0x00000080,
        backingPixel    : 0x00000100,
        overrideRedirect: 0x00000200,
        saveUnder       : 0x00000400,
        eventMask       : 0x00000800,
      doNotPropagateMask: 0x00001000,
        colormap        : 0x00002000,
        cursor          : 0x00004000
    },
    CreateGC: {
          'function'    : 0x00000001, // TODO: alias? _function?
           planeMask    : 0x00000002,
           foreground   : 0x00000004,
           background   : 0x00000008,
           lineWidth    : 0x00000010,
           lineStyle    : 0x00000020,
           capStyle     : 0x00000040,
           joinStyle    : 0x00000080,
           fillStyle    : 0x00000100,
           fillRule     : 0x00000200,
           tile         : 0x00000400,
           stipple      : 0x00000800,
           tileStippleXOrigin: 0x00001000,
           tileStippleYOrigin: 0x00002000,
           font         : 0x00004000,
           subwindowMode: 0x00008000,
           graphicsExposures: 0x00010000,
           clipXOrigin  : 0x00020000,
           clipYOrigin  : 0x00040000,
           clipMask     : 0x00080000,
           dashOffset   : 0x00100000,
           dashes       : 0x00200000,
           arcMode      : 0x00400000
    }
};

var valueMaskName = {};
for (var req in valueMask) {
    var masks = valueMask[req];
    var names = valueMaskName[req] = {};
    for (var m in masks)
        names[masks[m]] = m;
}

function packValueMask(reqname, values)
{
    var bitmask = 0;
    var masksList = [];
    var reqValueMask = valueMask[reqname];
    var reqValueMaskName = valueMaskName[reqname];

    if (!reqValueMask)
        throw new Error(reqname + ': no value mask description');

    for (var v in values)
    {
        var valueBit = reqValueMask[v];
        if (!valueBit)
            throw new Error(reqname + ': incorrect value param ' + v);
        masksList.push(valueBit);
        bitmask |= valueBit;
    }
    masksList.sort();
    var args = [];
    for (m in masksList)
    {
       valueName = reqValueMaskName[masksList[m]];
       args.push( values[valueName] );
    }
    return [bitmask, args]
}

/*

the way requests are described here

- outgoing request

   1) as function
   client.CreateWindow( params, params ) ->
       req = reqs.CreateWindow[0]( param, param );
       pack_stream.pack(req[0], req[1]);

   2) as array: [format, [opcode, request_length, additional known params]]

   client.MapWindow[0](id) ->
       req = reqs.MwpWindow;
       req[1].push(id);
       pack_stream.pack( req[0], req[1] );

- reply

*/

module.exports = {
   CreateWindow: [
       // create request packet - function OR format string
       function(id, parentId, x, y, width, height, borderWidth, _class, visual, values) {
           // TODO: ??? there is depth field in xproto, but xlib just sets it to zero
           var depth = 0;

           var packetLength = 8 + (values ? Object.keys(values).length : 0);
           // TODO: should be CCSLLssSSSSLL - x,y are signed
           var format = 'CCSLLSSSSSSLL';

           // create bitmask
           var bitmask = 0;
           // TODO: slice from function arguments?
           var args = [1, depth, packetLength, id, parentId, x, y, width, height, borderWidth, _class, visual];

           // TODO: the code is a little bit mess
           // additional values need to be packed in the following way:
           // bitmask (bytes #24 to #31 in the packet) - 32 bit indicating what adittional arguments we supply
           // values list (bytes #32 .. #32+4*num_values) in order of corresponding bits

           // TODO: replace with packValueMask
           var masksList = [];
           for (var v in values)
           {
               var valueBit = valueMask['CreateWindow'][v];
               if (!valueBit)
               {
                   throw new Error('CreateWindow: incorrect value param ' + v);
               }
               masksList.push(valueBit);
               bitmask |= valueBit;
               format += 'L';
           }
           // values packed in order of corresponding bit
           masksList.sort();
           // set bits to indicate additional values we are sending in this request
           args.push(bitmask);
           // add values in the order of the bits
           // TODO: maybe it's better just to scan all 32 bits anstead of sorting parameters we are actually have?
           for (m in masksList)
           {
              valueName = valueMaskName['CreateWindow'][masksList[m]];
              args.push( values[valueName] );
           }
           return [format, args];
       }

   ],

   MapWindow: [
       // 8 - opcode, 2 - length
       [ 'CxSL', [8, 2] ]
   ],

   UnmapWindow: [
       [ 'CxSL', [10, 2] ]
   ],

   // opcode 55
   CreateGC: [
       function(cid, drawable, values) {
           var format = 'CxSLL';
           var packetLength = 8 + (values ? Object.keys(values).length : 0);
           var args = [55, packetLength, cid, drawable];
           var vals = packValueMask('CreateGC', values);
           args.push(vals[0]);     // values bitmask
           var valArr = vals[1];
           for (v in valArr)
           {
               format += 'L'; // TODO: we know format string length in advance and += inefficient for string
               args.push(valArr[v]);
           }
           return [format, args];
        }
   ],

   // opcode 16
   InternAtom: [
       function (returnOnlyIfExist, value)
       {
           var padded = xutil.padded_string(value);
           return ['CCSSxxa', [16, returnOnlyIfExist ? 1 : 0, 2+padded.length/4, value.length, padded] ];
       },

       function(buf) {
	   var res = buf.unpack('L')[0];
           return res;
       }
   ],

   GetAtomName: [
       [ 'CxSL', [17, 2] ],
       function(buf) {
          var nameLen = buf.unpack('S')[0];
          return buf.unpackString(nameLen, 24);
       }
   ],

   PolyFillRectangle: [
      function(drawable, gc, rects) { // x1, y1, w1, h1, x2, y2, w2, h2...
          var format = 'CxSLL';
          var numrects4bytes = rects.len*2;
          var args = [60, 3+numrects4bytes, drawable, gc];
          for (var i=0; i < rects.length; ++i)
          {
              format += 'S';
              args.push(rects[i]);
          }
          return [format, args];
      }
   ]
}
<commit_msg>ben packet length for CreateGC<commit_after>var xutil = require('./xutil');
var hexy = require('./hexy').hexy;

var valueMask = {
    CreateWindow: {
        backgroundPixmap: 0x00000001,
        backgroundPixel : 0x00000002,
        borderPixmap    : 0x00000004,
        borderPixel     : 0x00000008,
        bitGrawity      : 0x00000010,
        winGravity      : 0x00000020,
        backingStore    : 0x00000040,
        backingPlanes   : 0x00000080,
        backingPixel    : 0x00000100,
        overrideRedirect: 0x00000200,
        saveUnder       : 0x00000400,
        eventMask       : 0x00000800,
      doNotPropagateMask: 0x00001000,
        colormap        : 0x00002000,
        cursor          : 0x00004000
    },
    CreateGC: {
          'function'    : 0x00000001, // TODO: alias? _function?
           planeMask    : 0x00000002,
           foreground   : 0x00000004,
           background   : 0x00000008,
           lineWidth    : 0x00000010,
           lineStyle    : 0x00000020,
           capStyle     : 0x00000040,
           joinStyle    : 0x00000080,
           fillStyle    : 0x00000100,
           fillRule     : 0x00000200,
           tile         : 0x00000400,
           stipple      : 0x00000800,
           tileStippleXOrigin: 0x00001000,
           tileStippleYOrigin: 0x00002000,
           font         : 0x00004000,
           subwindowMode: 0x00008000,
           graphicsExposures: 0x00010000,
           clipXOrigin  : 0x00020000,
           clipYOrigin  : 0x00040000,
           clipMask     : 0x00080000,
           dashOffset   : 0x00100000,
           dashes       : 0x00200000,
           arcMode      : 0x00400000
    }
};

var valueMaskName = {};
for (var req in valueMask) {
    var masks = valueMask[req];
    var names = valueMaskName[req] = {};
    for (var m in masks)
        names[masks[m]] = m;
}

function packValueMask(reqname, values)
{
    var bitmask = 0;
    var masksList = [];
    var reqValueMask = valueMask[reqname];
    var reqValueMaskName = valueMaskName[reqname];

    if (!reqValueMask)
        throw new Error(reqname + ': no value mask description');

    for (var v in values)
    {
        var valueBit = reqValueMask[v];
        if (!valueBit)
            throw new Error(reqname + ': incorrect value param ' + v);
        masksList.push(valueBit);
        bitmask |= valueBit;
    }
    masksList.sort();
    var args = [];
    for (m in masksList)
    {
       valueName = reqValueMaskName[masksList[m]];
       args.push( values[valueName] );
    }
    return [bitmask, args]
}

/*

the way requests are described here

- outgoing request

   1) as function
   client.CreateWindow( params, params ) ->
       req = reqs.CreateWindow[0]( param, param );
       pack_stream.pack(req[0], req[1]);

   2) as array: [format, [opcode, request_length, additional known params]]

   client.MapWindow[0](id) ->
       req = reqs.MwpWindow;
       req[1].push(id);
       pack_stream.pack( req[0], req[1] );

- reply

*/

module.exports = {
   CreateWindow: [
       // create request packet - function OR format string
       function(id, parentId, x, y, width, height, borderWidth, _class, visual, values) {
           // TODO: ??? there is depth field in xproto, but xlib just sets it to zero
           var depth = 0;

           var packetLength = 8 + (values ? Object.keys(values).length : 0);
           // TODO: should be CCSLLssSSSSLL - x,y are signed
           var format = 'CCSLLSSSSSSLL';

           // create bitmask
           var bitmask = 0;
           // TODO: slice from function arguments?
           var args = [1, depth, packetLength, id, parentId, x, y, width, height, borderWidth, _class, visual];

           // TODO: the code is a little bit mess
           // additional values need to be packed in the following way:
           // bitmask (bytes #24 to #31 in the packet) - 32 bit indicating what adittional arguments we supply
           // values list (bytes #32 .. #32+4*num_values) in order of corresponding bits

           // TODO: replace with packValueMask
           var masksList = [];
           for (var v in values)
           {
               var valueBit = valueMask['CreateWindow'][v];
               if (!valueBit)
               {
                   throw new Error('CreateWindow: incorrect value param ' + v);
               }
               masksList.push(valueBit);
               bitmask |= valueBit;
               format += 'L';
           }
           // values packed in order of corresponding bit
           masksList.sort();
           // set bits to indicate additional values we are sending in this request
           args.push(bitmask);
           // add values in the order of the bits
           // TODO: maybe it's better just to scan all 32 bits anstead of sorting parameters we are actually have?
           for (m in masksList)
           {
              valueName = valueMaskName['CreateWindow'][masksList[m]];
              args.push( values[valueName] );
           }
           return [format, args];
       }

   ],

   MapWindow: [
       // 8 - opcode, 2 - length
       [ 'CxSL', [8, 2] ]
   ],

   UnmapWindow: [
       [ 'CxSL', [10, 2] ]
   ],

   // opcode 55
   CreateGC: [
       function(cid, drawable, values) {
           var format = 'CxSLL';
           var packetLength = 4 + (values ? Object.keys(values).length : 0);
           var args = [55, packetLength, cid, drawable];
           var vals = packValueMask('CreateGC', values);
           args.push(vals[0]);     // values bitmask
           var valArr = vals[1];
           for (v in valArr)
           {
               format += 'L'; // TODO: we know format string length in advance and += inefficient for string
               args.push(valArr[v]);
           }
           return [format, args];
        }
   ],

   // opcode 16
   InternAtom: [
       function (returnOnlyIfExist, value)
       {
           var padded = xutil.padded_string(value);
           return ['CCSSxxa', [16, returnOnlyIfExist ? 1 : 0, 2+padded.length/4, value.length, padded] ];
       },

       function(buf) {
	   var res = buf.unpack('L')[0];
           return res;
       }
   ],

   GetAtomName: [
       [ 'CxSL', [17, 2] ],
       function(buf) {
          var nameLen = buf.unpack('S')[0];
          return buf.unpackString(nameLen, 24);
       }
   ],

   PolyFillRectangle: [
      function(drawable, gc, coords) { // x1, y1, w1, h1, x2, y2, w2, h2...
          var format = 'CxSLL';
          var numrects4bytes = coords.length/2;
          var args = [70, 3+numrects4bytes, drawable, gc];
          for (var i=0; i < coords.length; ++i)
          {
              format += 'S';
              args.push(coords[i]);
          }
          console.error([format, args]);
          return [format, args];
      }
   ]
}
<|endoftext|>


<commit_before>var xutil = require('./xutil');
var hexy = require('./hexy').hexy;

var valueMask = {
    CreateWindow: {
        backgroundPixmap: 0x00000001,
        backgroundPixel : 0x00000002,
        borderPixmap    : 0x00000004,
        borderPixel     : 0x00000008,
        bitGrawity      : 0x00000010,
        winGravity      : 0x00000020,
        backingStore    : 0x00000040,
        backingPlanes   : 0x00000080,
        backingPixel    : 0x00000100,
        overrideRedirect: 0x00000200,
        saveUnder       : 0x00000400,
        eventMask       : 0x00000800,
      doNotPropagateMask: 0x00001000,
        colormap        : 0x00002000,
        cursor          : 0x00004000
    },
    CreateGC: {
          'function'    : 0x00000001, // TODO: alias? _function?
           planeMask    : 0x00000002,
           foreground   : 0x00000004,
           background   : 0x00000008,
           lineWidth    : 0x00000010,
           lineStyle    : 0x00000020,
           capStyle     : 0x00000040,
           joinStyle    : 0x00000080,
           fillStyle    : 0x00000100,
           fillRule     : 0x00000200,
           tile         : 0x00000400,
           stipple      : 0x00000800,
           tileStippleXOrigin: 0x00001000,
           tileStippleYOrigin: 0x00002000,
           font         : 0x00004000,
           subwindowMode: 0x00008000,
           graphicsExposures: 0x00010000,
           clipXOrigin  : 0x00020000,
           clipYOrigin  : 0x00040000,
           clipMask     : 0x00080000,
           dashOffset   : 0x00100000,
           dashes       : 0x00200000,
           arcMode      : 0x00400000
    }
};

var valueMaskName = {};
for (var req in valueMask) {
    var masks = valueMask[req];
    var names = valueMaskName[req] = {};
    for (var m in masks)
        names[masks[m]] = m;
}

function packValueMask(reqname, values)
{
    var bitmask = 0;
    var masksList = [];
    var reqValueMask = valueMask[reqname];
    var reqValueMaskName = valueMaskName[reqname];

    if (!reqValueMask)
        throw new Error(reqname + ': no value mask description');

    for (var v in values)
    {
        var valueBit = reqValueMask[v];
        if (!valueBit)
            throw new Error(reqname + ': incorrect value param ' + v);
        masksList.push(valueBit);
        bitmask |= valueBit;
    }
    masksList.sort();
    var args = [];
    for (m in masksList)
    {
       valueName = reqValueMaskName[masksList[m]];
       args.push( values[valueName] );
    }
    return [bitmask, args]
}

/*

the way requests are described here

- outgoing request

   1) as function
   client.CreateWindow( params, params ) ->
       req = reqs.CreateWindow[0]( param, param );
       pack_stream.pack(req[0], req[1]);

   2) as array: [format, [opcode, request_length, additional known params]]

   client.MapWindow[0](id) ->
       req = reqs.MwpWindow;
       req[1].push(id);
       pack_stream.pack( req[0], req[1] );

- reply

*/

module.exports = {
   CreateWindow: [
       // create request packet - function OR format string
       function(id, parentId, x, y, width, height, borderWidth, _class, visual, values) {
           // TODO: ??? there is depth field in xproto, but xlib just sets it to zero
           var depth = 0;

           var packetLength = 8 + (values ? Object.keys(values).length : 0);
           // TODO: should be CCSLLssSSSSLL - x,y are signed
           var format = 'CCSLLSSSSSSLL';

           // create bitmask
           var bitmask = 0;
           // TODO: slice from function arguments?
           var args = [1, depth, packetLength, id, parentId, x, y, width, height, borderWidth, _class, visual];

           // TODO: the code is a little bit mess
           // additional values need to be packed in the following way:
           // bitmask (bytes #24 to #31 in the packet) - 32 bit indicating what adittional arguments we supply
           // values list (bytes #32 .. #32+4*num_values) in order of corresponding bits

           // TODO: replace with packValueMask
           var masksList = [];
           for (var v in values)
           {
               var valueBit = valueMask['CreateWindow'][v];
               if (!valueBit)
               {
                   throw new Error('CreateWindow: incorrect value param ' + v);
               }
               masksList.push(valueBit);
               bitmask |= valueBit;
               format += 'L';
           }
           // values packed in order of corresponding bit
           masksList.sort();
           // set bits to indicate additional values we are sending in this request
           args.push(bitmask);
           // add values in the order of the bits
           // TODO: maybe it's better just to scan all 32 bits anstead of sorting parameters we are actually have?
           for (m in masksList)
           {
              valueName = valueMaskName['CreateWindow'][masksList[m]];
              args.push( values[valueName] );
           }
           return [format, args];
       }

   ],

   MapWindow: [
       // 8 - opcode, 2 - length
       [ 'CxSL', [8, 2] ]
   ],

   UnmapWindow: [
       [ 'CxSL', [10, 2] ]
   ],

   // opcode 55
   CreateGC: [
       function(cid, drawable, values) {
           var format = 'CxSLL';
           var packetLength = 4 + (values ? Object.keys(values).length : 0);
           var args = [55, packetLength, cid, drawable];
           var vals = packValueMask('CreateGC', values);
           args.push(vals[0]);     // values bitmask
           var valArr = vals[1];
           for (v in valArr)
           {
               format += 'L'; // TODO: we know format string length in advance and += inefficient for string
               args.push(valArr[v]);
           }
           return [format, args];
        }
   ],

   // opcode 16
   InternAtom: [
       function (returnOnlyIfExist, value)
       {
           var padded = xutil.padded_string(value);
           return ['CCSSxxa', [16, returnOnlyIfExist ? 1 : 0, 2+padded.length/4, value.length, padded] ];
       },

       function(buf) {
	   var res = buf.unpack('L')[0];
           return res;
       }
   ],

   GetAtomName: [
       [ 'CxSL', [17, 2] ],
       function(buf) {
          var nameLen = buf.unpack('S')[0];
          return buf.unpackString(nameLen, 24);
       }
   ],

   PolyFillRectangle: [
      function(drawable, gc, coords) { // x1, y1, w1, h1, x2, y2, w2, h2...
          var format = 'CxSLL';
          var numrects4bytes = coords.length/2;
          var args = [70, 3+numrects4bytes, drawable, gc];
          for (var i=0; i < coords.length; ++i)
          {
              format += 'S';
              args.push(coords[i]);
          }
          console.error([format, args]);
          return [format, args];
      }
   ]
}
<commit_msg>missed format arg vor values mask in CreateGC<commit_after>var xutil = require('./xutil');
var hexy = require('./hexy').hexy;

var valueMask = {
    CreateWindow: {
        backgroundPixmap: 0x00000001,
        backgroundPixel : 0x00000002,
        borderPixmap    : 0x00000004,
        borderPixel     : 0x00000008,
        bitGrawity      : 0x00000010,
        winGravity      : 0x00000020,
        backingStore    : 0x00000040,
        backingPlanes   : 0x00000080,
        backingPixel    : 0x00000100,
        overrideRedirect: 0x00000200,
        saveUnder       : 0x00000400,
        eventMask       : 0x00000800,
      doNotPropagateMask: 0x00001000,
        colormap        : 0x00002000,
        cursor          : 0x00004000
    },
    CreateGC: {
          'function'    : 0x00000001, // TODO: alias? _function?
           planeMask    : 0x00000002,
           foreground   : 0x00000004,
           background   : 0x00000008,
           lineWidth    : 0x00000010,
           lineStyle    : 0x00000020,
           capStyle     : 0x00000040,
           joinStyle    : 0x00000080,
           fillStyle    : 0x00000100,
           fillRule     : 0x00000200,
           tile         : 0x00000400,
           stipple      : 0x00000800,
           tileStippleXOrigin: 0x00001000,
           tileStippleYOrigin: 0x00002000,
           font         : 0x00004000,
           subwindowMode: 0x00008000,
           graphicsExposures: 0x00010000,
           clipXOrigin  : 0x00020000,
           clipYOrigin  : 0x00040000,
           clipMask     : 0x00080000,
           dashOffset   : 0x00100000,
           dashes       : 0x00200000,
           arcMode      : 0x00400000
    }
};

var valueMaskName = {};
for (var req in valueMask) {
    var masks = valueMask[req];
    var names = valueMaskName[req] = {};
    for (var m in masks)
        names[masks[m]] = m;
}

function packValueMask(reqname, values)
{
    var bitmask = 0;
    var masksList = [];
    var reqValueMask = valueMask[reqname];
    var reqValueMaskName = valueMaskName[reqname];

    if (!reqValueMask)
        throw new Error(reqname + ': no value mask description');

    for (var v in values)
    {
        var valueBit = reqValueMask[v];
        if (!valueBit)
            throw new Error(reqname + ': incorrect value param ' + v);
        masksList.push(valueBit);
        bitmask |= valueBit;
    }
    masksList.sort();
    var args = [];
    for (m in masksList)
    {
       valueName = reqValueMaskName[masksList[m]];
       args.push( values[valueName] );
    }
    return [bitmask, args]
}

/*

the way requests are described here

- outgoing request

   1) as function
   client.CreateWindow( params, params ) ->
       req = reqs.CreateWindow[0]( param, param );
       pack_stream.pack(req[0], req[1]);

   2) as array: [format, [opcode, request_length, additional known params]]

   client.MapWindow[0](id) ->
       req = reqs.MwpWindow;
       req[1].push(id);
       pack_stream.pack( req[0], req[1] );

- reply

*/

module.exports = {
   CreateWindow: [
       // create request packet - function OR format string
       function(id, parentId, x, y, width, height, borderWidth, _class, visual, values) {
           // TODO: ??? there is depth field in xproto, but xlib just sets it to zero
           var depth = 0;

           var packetLength = 8 + (values ? Object.keys(values).length : 0);
           // TODO: should be CCSLLssSSSSLL - x,y are signed
           var format = 'CCSLLSSSSSSLL';

           // create bitmask
           var bitmask = 0;
           // TODO: slice from function arguments?
           var args = [1, depth, packetLength, id, parentId, x, y, width, height, borderWidth, _class, visual];

           // TODO: the code is a little bit mess
           // additional values need to be packed in the following way:
           // bitmask (bytes #24 to #31 in the packet) - 32 bit indicating what adittional arguments we supply
           // values list (bytes #32 .. #32+4*num_values) in order of corresponding bits

           // TODO: replace with packValueMask
           var masksList = [];
           for (var v in values)
           {
               var valueBit = valueMask['CreateWindow'][v];
               if (!valueBit)
               {
                   throw new Error('CreateWindow: incorrect value param ' + v);
               }
               masksList.push(valueBit);
               bitmask |= valueBit;
               format += 'L';
           }
           // values packed in order of corresponding bit
           masksList.sort();
           // set bits to indicate additional values we are sending in this request
           args.push(bitmask);
           // add values in the order of the bits
           // TODO: maybe it's better just to scan all 32 bits anstead of sorting parameters we are actually have?
           for (m in masksList)
           {
              valueName = valueMaskName['CreateWindow'][masksList[m]];
              args.push( values[valueName] );
           }
           return [format, args];
       }

   ],

   MapWindow: [
       // 8 - opcode, 2 - length
       [ 'CxSL', [8, 2] ]
   ],

   UnmapWindow: [
       [ 'CxSL', [10, 2] ]
   ],

   // opcode 55
   CreateGC: [
       function(cid, drawable, values) {
           var format = 'CxSLLL';
           var packetLength = 4 + (values ? Object.keys(values).length : 0);
           var args = [55, packetLength, cid, drawable];
           var vals = packValueMask('CreateGC', values);
           args.push(vals[0]);     // values bitmask
           var valArr = vals[1];
           for (v in valArr)
           {
               format += 'L'; // TODO: we know format string length in advance and += inefficient for string
               args.push(valArr[v]);
           }
           return [format, args];
        }
   ],

   // opcode 16
   InternAtom: [
       function (returnOnlyIfExist, value)
       {
           var padded = xutil.padded_string(value);
           return ['CCSSxxa', [16, returnOnlyIfExist ? 1 : 0, 2+padded.length/4, value.length, padded] ];
       },

       function(buf) {
	   var res = buf.unpack('L')[0];
           return res;
       }
   ],

   GetAtomName: [
       [ 'CxSL', [17, 2] ],
       function(buf) {
          var nameLen = buf.unpack('S')[0];
          return buf.unpackString(nameLen, 24);
       }
   ],

   PolyFillRectangle: [
      function(drawable, gc, coords) { // x1, y1, w1, h1, x2, y2, w2, h2...
          var format = 'CxSLL';
          var numrects4bytes = coords.length/2;
          var args = [70, 3+numrects4bytes, drawable, gc];
          for (var i=0; i < coords.length; ++i)
          {
              format += 'S';
              args.push(coords[i]);
          }
          return [format, args];
      }
   ]
}
<|endoftext|>


<commit_before>'use strict';

var chalk   = require('chalk');
var crypto  = require('crypto');
var fs      = require('fs-extra');
var path    = require('path');
var keygen  = require('ssh-keygen');
var latest  = require('github-latest');
var request = require('request');
var yeoman  = require('yeoman-generator');
var util    = require('util');

var WordpressGenerator = yeoman.generators.Base.extend({
  init: function() {
    this.pkg      = JSON.parse(this.readFileAsString(path.join(__dirname, '../../package.json')));
    this.prompts  = [];

    this.option('dev', {
      desc: 'Dev-mode for localized development of the generator',
      defaults: false,
    });

    this.on('end', function() {
      this.installDependencies({
        bower:        true,
        npm:          false,
        skipInstall:  this.options['skip-install'],
        skipMessage:  true,
        callback:     function() {
          this.log.write();
          this.log.ok('All done! Run ' + chalk.yellow('vagrant up') + ' to get started!');
        }.bind(this)
      });
    });

    this.sourceRoot(path.join(__dirname, 'templates'));
  },

  welcome: function() {
    var message = this.readFileAsString(path.join(__dirname, 'welcome.txt'));

    message = message.replace(/./g, function(match) {
      return /\w/.test(match) ? chalk.yellow(match) : chalk.cyan(match);
    });

    this.log.writeln(message);
  },

  promptForName: function() {
    var existing = function() {
      try {
        var bower = JSON.parse(this.readFileAsString(path.join(this.env.cwd, 'bower.json')));

        return bower.name;
      } catch(e) {};
    }.bind(this);

    this.prompts.push({
      required: true,
      type:     'text',
      name:     'name',
      message:  'Repository name (e.g. MySite)',
      default:  function() {
        return existing() || path.basename(this.env.cwd);
      }.bind(this)
    });
  },

  promptForDomain: function() {
    this.prompts.push({
      required: true,
      type:     'text',
      name:     'domain',
      message:  'Domain name (e.g. mysite.com)',
      default:  path.basename(this.env.cwd).toLowerCase(),
      validate: function(input) {
        if (/^[\w-]+\.\w+(?:\.\w{2,3})?$/.test(input)) {
          return true;
        } else if (!input) {
          return "Domain is required";
        }

        return chalk.yellow(input) + ' does not appear to be a domain';
      }
    });
  },

  promptForWordPress: function() {
    var existing = function(web) {
      try {
        var file    = this.readFileAsString(path.join(web, 'wp-includes', 'version.php'));
        var version = file.match(/\$wp_version\s=\s['"]([^'"]+)/);

        if (version.length) {
          return version[1];
        }
      } catch(e) {}
    }.bind(this);

    var done = this.async();

    latest('wordpress', 'wordpress', function(err, tag) {
      this.prompts.push({
        type:     'text',
        name:     'wordpress',
        message:  'WordPress version',
        default:  function(answers) {
          return existing(answers.web) || tag || '3.7.1';
        }
      });

      done();
    }.bind(this));
  },

  promptForTablePrefix: function() {
    var existing = function(web) {
      try {
        var config = this.readFileAsString(path.join(web, 'wp-config.php'));
        var prefix = config.match(/\$table_prefix\s*=\s*['"]([^'"]+)/);

        if (prefix.length) {
          return prefix[1];
        }
      } catch(e) {}
    }.bind(this);

    this.prompts.push({
      type:     'text',
      name:     'prefix',
      message:  'WordPress table prefix',
      default:  function(answers) {
        return existing(answers.web) || 'wp_';
      }
    });
  },

  promptForDatabase: function() {
    var done      = this.async();
    var existing  = function(web, constant) {
      try {
        var config = this.readFileAsString(path.join(web, 'wp-config.php'));
        var regex   = new RegExp(constant + '[\'"],\\s*[\'"]([^\'"]+)');
        var matches = regex.exec(config);

        return matches && matches[1];
      } catch(e) {}
    }.bind(this);

    crypto.randomBytes(12, function(err, buffer) {
      this.prompts.push({
        type:     'text',
        name:     'DB_NAME',
        message:  'Database name',
        default:  function(answers) { return existing(answers.web, 'DB_NAME') || 'wordpress'; }
      });

      this.prompts.push({
        type:     'text',
        name:     'DB_USER',
        message:  'Database user',
        default:  function(answers) { return existing(answers.web, 'DB_USER') || 'wordpress'; }
      });

      this.prompts.push({
        type:     'text',
        name:     'DB_PASSWORD',
        message:  'Database password',
        default:  function(answers) { return existing(answers.web, 'DB_PASSWORD') || buffer.toString('base64'); }
      });

      this.prompts.push({
        type:     'text',
        name:     'DB_HOST',
        message:  'Database host',
        default:  function(answers) { return existing(answers.web, 'DB_HOST') || 'localhost'; }
      });

      done();
    }.bind(this));
  },

  promptForIp: function() {
    // Private IP blocks
    var blocks = [
      ['192.168.0.0', '192.168.255.255'],
      ['172.16.0.0',  '172.31.255.255'],
      ['10.0.0.0',    '10.255.255.255']
    ];

    // Long IP ranges
    var ranges = blocks.map(function(block) {
      return block.map(function(ip) {
        var parts = ip.split('.');

        return parts[0] << 24 | parts[1] << 16 | parts[2] << 8 | parts[3] >>> 0;
      });
    });

    // Randomize IP addresses
    var ips = ranges.map(function(range) {
      return Math.random() * (range[1] - range[0]) + range[0];
    }).map(function(ip) {
      return [
        (ip & (0xff << 24)) >>> 24,
        (ip & (0xff << 16)) >>> 16,
        (ip & (0xff << 8)) >>> 8,
        (ip & (0xff << 0)) >>> 0
      ].join('.');
    });

    try {
      var vagrant = this.readFileAsString('Vagrantfile').match(/ip:\s['"]([\d\.]+)['"]/);

      if (vagrant.length) {
        ips.unshift(vagrant[1]);
      }
    } catch(e) {}

    this.prompts.push({
      required: true,
      type:     'list',
      name:     'ip',
      message:  'Vagrant IP',
      pattern:  /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,
      choices:  ips
    });
  },

  ask: function() {
    var done = this.async();

    this.prompt(this.prompts, function(props) {
      this.props = props;

      done();
    }.bind(this));
  },

  prepareReadme: function() {
    try {
      this.readmeFile = this.readFileAsString(path.join(this.env.cwd, 'README.md'));
      this.readmeFile = this.readmeFile
        .replace(/^(?:\[[^\]]+\]){1,2}(?:\([^\)]+\))?[\r\n]+=+[\r\n]+> Powered by \[(?:Genesis|Evolution)[^\r\n]+[\r\n]+/i, '')
        .replace(/\[[^\]]+\]:\s*http[^\r\n]+[\r\n]+\[(?:genesis|evolution)-wordpress\]:\s*http[^\r\n]+[\r\n]*$/i, '')
      ;
    } catch(e) {
      this.readmeFile = '';
    }
  },

  prepareSalts: function() {
    var done = this.async();

    request('https://api.wordpress.org/secret-key/1.1/salt/', function(err, response, salts) {
      if (err) {
        throw err;
      }

      this.props.salts = salts;
      done();
    }.bind(this));
  },

  prepareSshKeys: function() {
    var done      = this.async();
    var location  = path.join(this.env.cwd, 'lib', 'ansible', 'files', 'ssh', 'id_rsa');

    this.log.info('Creating SSH keys...');

    this.mkdir(path.dirname(location));

    keygen({
      location: location,
      comment:  'deploy@' + this.props.domain,
      read: false
    }, done);
  },

  prepareTemplates: function() {
    this.templates = this.expandFiles('**/*', {
      cwd: this.sourceRoot(),
    });
  },

  ready: function() {
    this.log.write('\n');
    this.log.info(chalk.green('Here we go!'));
  },

  symlinkEvolutionWordPress: function() {
    if (!this.options.dev) {
      return false;
    }

    this.log.info(chalk.green('Symlinking local Evolution WordPress as dependency...'));

    var srcpath = '../../../wordpress';
    var dstpath = path.join(this.env.cwd, 'bower_components', 'evolution-wordpress');

    this.mkdir(path.dirname(dstpath));

    fs.symlinkSync(srcpath, dstpath);
  },

  copyBower: function() {
    this.template('bower.json', 'bower.json');
  },

  runBower: function() {
    var done = this.async();

    this.log.info(chalk.green('Installing project dependencies...'));

    this.bowerInstall(null, null, done);
  },

  copyBowerrc: function() {
    this.template('_bowerrc', '.bowerrc');
  },

  runPostInstall: function() {
    var done  = this.async();
    var rc    = JSON.parse(this.readFileAsString('.bowerrc'));
    var cmd   = rc.scripts.postinstall;

    this.log.info(chalk.green('Running Bower `postinstall`...'));

    this.emit('postInstall');

    this
      .spawnCommand(cmd, [], {
        cwd: process.cwd(),
      })
      .on('error', done)
      .on('exit', this.emit.bind(this, 'postInstall:end'))
      .on('exit', function (err) {
        if (err === 127) {
          this.log.error('Could not run post Bower `postinstall`.');
        }

        done(err);
      }.bind(this))
    ;
  },

  prepareWpConfig: function() {
    this.wpConfigFile = this.readFileAsString(path.join(this.env.cwd, 'web', 'wp', 'wp-config-sample.php'));
  },

  scaffold: function() {
    this.log.info(chalk.green('Scaffolding...'));

    this.templates.forEach(function(file) {
      this.template(file, file.replace(/(^|\/)_/, '$1.'));
    }.bind(this));
  },

  generateSslCert: function() {
    var done      = this.async();
    var location  = path.join(this.env.cwd, 'lib', 'ansible', 'files', 'ssl');
    var stages    = ['local', 'staging', 'production'];
    var exited    = function (err) {
      stages.pop();

      if (err || !stages.length) {
        done(err);
      }
    };

    this.log.info('Creating self-signed SSL certificate...');

    this.mkdir(path.dirname(location));

    stages.forEach(function (stage) {
      this.emit('sslInstall'+stage);

      var cert = path.join(location, stage + '.' + this.props.domain + '.pem');
      var cfg  = path.join(location, stage + '.cfg');

      this
        .spawnCommand('openssl', [
          'req',
          '-x509',
          '-nodes',
          '-days',
          '365',
          '-newkey',
          'rsa:2048',
          '-keyout',
          cert,
          '-out',
          cert,
          '-config',
          cfg
        ], {
          cwd: process.cwd(),
        })
        .on('error', exited)
        .on('exit', this.emit.bind(this, 'sslInstall'+stage+':end'))
        .on('exit', function (err) {
          if (err === 127) {
            this.log.error('Could not generate SSL certificate for '+stage);
          }

          exited(err);
        }.bind(this))
      ;
    }.bind(this));
  },

  symlinkBowerComponents: function() {
    this.log.info(chalk.green('Symlinking `bower_components` into `web`...'));

    fs.symlinkSync('../bower_components', path.join(this.env.cwd, 'web', 'bower_components'));
  },

  removeDevFiles: function() {
    if (this.options.dev) {
      return false;
    }

    this.log.info(chalk.red('Removing'), chald.green('dev files...'));

    fs.unlinkSync(path.join(this.env.cwd, 'lib', 'capistrano', 'tasks', 'testing.rake'));
  },

  fixPermissions: function() {
    fs.chmodSync(path.join(this.env.cwd, 'bin', 'provision'), '744');
    fs.chmodSync(path.join(this.env.cwd, 'lib', 'ansible', 'files', 'ssh', 'id_rsa'), '600');
  },

  installGems: function() {
    var done      = this.async();
    var installer = 'bundle';

    this.log.info(chalk.green('Installing Gems...'));

    this.emit(installer + 'Install');

    this
      .spawnCommand(installer, ['install'], done)
      .on('error', done)
      .on('exit', this.emit.bind(this, installer + 'Install:end'))
      .on('exit', function (err) {
        if (err === 127) {
          this.log.error('Could not run bundler. Please install with `sudo ' + installer + ' install`.');
        }

        done(err);
      }.bind(this))
    ;
  },
});

module.exports = WordpressGenerator;
<commit_msg>Clean up postInstall<commit_after>'use strict';

var chalk   = require('chalk');
var crypto  = require('crypto');
var fs      = require('fs-extra');
var path    = require('path');
var keygen  = require('ssh-keygen');
var latest  = require('github-latest');
var request = require('request');
var yeoman  = require('yeoman-generator');
var util    = require('util');

var WordpressGenerator = yeoman.generators.Base.extend({
  init: function() {
    this.pkg      = JSON.parse(this.readFileAsString(path.join(__dirname, '../../package.json')));
    this.prompts  = [];

    this.option('dev', {
      desc: 'Dev-mode for localized development of the generator',
      defaults: false,
    });

    this.on('end', function() {
      this.installDependencies({
        bower:        true,
        npm:          false,
        skipInstall:  this.options['skip-install'],
        skipMessage:  true,
        callback:     function() {
          this.log.write();
          this.log.ok('All done! Run ' + chalk.yellow('vagrant up') + ' to get started!');
        }.bind(this)
      });
    });

    this.sourceRoot(path.join(__dirname, 'templates'));
  },

  welcome: function() {
    var message = this.readFileAsString(path.join(__dirname, 'welcome.txt'));

    message = message.replace(/./g, function(match) {
      return /\w/.test(match) ? chalk.yellow(match) : chalk.cyan(match);
    });

    this.log.writeln(message);
  },

  promptForName: function() {
    var existing = function() {
      try {
        var bower = JSON.parse(this.readFileAsString(path.join(this.env.cwd, 'bower.json')));

        return bower.name;
      } catch(e) {};
    }.bind(this);

    this.prompts.push({
      required: true,
      type:     'text',
      name:     'name',
      message:  'Repository name (e.g. MySite)',
      default:  function() {
        return existing() || path.basename(this.env.cwd);
      }.bind(this)
    });
  },

  promptForDomain: function() {
    this.prompts.push({
      required: true,
      type:     'text',
      name:     'domain',
      message:  'Domain name (e.g. mysite.com)',
      default:  path.basename(this.env.cwd).toLowerCase(),
      validate: function(input) {
        if (/^[\w-]+\.\w+(?:\.\w{2,3})?$/.test(input)) {
          return true;
        } else if (!input) {
          return "Domain is required";
        }

        return chalk.yellow(input) + ' does not appear to be a domain';
      }
    });
  },

  promptForWordPress: function() {
    var existing = function(web) {
      try {
        var file    = this.readFileAsString(path.join(web, 'wp-includes', 'version.php'));
        var version = file.match(/\$wp_version\s=\s['"]([^'"]+)/);

        if (version.length) {
          return version[1];
        }
      } catch(e) {}
    }.bind(this);

    var done = this.async();

    latest('wordpress', 'wordpress', function(err, tag) {
      this.prompts.push({
        type:     'text',
        name:     'wordpress',
        message:  'WordPress version',
        default:  function(answers) {
          return existing(answers.web) || tag || '3.7.1';
        }
      });

      done();
    }.bind(this));
  },

  promptForTablePrefix: function() {
    var existing = function(web) {
      try {
        var config = this.readFileAsString(path.join(web, 'wp-config.php'));
        var prefix = config.match(/\$table_prefix\s*=\s*['"]([^'"]+)/);

        if (prefix.length) {
          return prefix[1];
        }
      } catch(e) {}
    }.bind(this);

    this.prompts.push({
      type:     'text',
      name:     'prefix',
      message:  'WordPress table prefix',
      default:  function(answers) {
        return existing(answers.web) || 'wp_';
      }
    });
  },

  promptForDatabase: function() {
    var done      = this.async();
    var existing  = function(web, constant) {
      try {
        var config = this.readFileAsString(path.join(web, 'wp-config.php'));
        var regex   = new RegExp(constant + '[\'"],\\s*[\'"]([^\'"]+)');
        var matches = regex.exec(config);

        return matches && matches[1];
      } catch(e) {}
    }.bind(this);

    crypto.randomBytes(12, function(err, buffer) {
      this.prompts.push({
        type:     'text',
        name:     'DB_NAME',
        message:  'Database name',
        default:  function(answers) { return existing(answers.web, 'DB_NAME') || 'wordpress'; }
      });

      this.prompts.push({
        type:     'text',
        name:     'DB_USER',
        message:  'Database user',
        default:  function(answers) { return existing(answers.web, 'DB_USER') || 'wordpress'; }
      });

      this.prompts.push({
        type:     'text',
        name:     'DB_PASSWORD',
        message:  'Database password',
        default:  function(answers) { return existing(answers.web, 'DB_PASSWORD') || buffer.toString('base64'); }
      });

      this.prompts.push({
        type:     'text',
        name:     'DB_HOST',
        message:  'Database host',
        default:  function(answers) { return existing(answers.web, 'DB_HOST') || 'localhost'; }
      });

      done();
    }.bind(this));
  },

  promptForIp: function() {
    // Private IP blocks
    var blocks = [
      ['192.168.0.0', '192.168.255.255'],
      ['172.16.0.0',  '172.31.255.255'],
      ['10.0.0.0',    '10.255.255.255']
    ];

    // Long IP ranges
    var ranges = blocks.map(function(block) {
      return block.map(function(ip) {
        var parts = ip.split('.');

        return parts[0] << 24 | parts[1] << 16 | parts[2] << 8 | parts[3] >>> 0;
      });
    });

    // Randomize IP addresses
    var ips = ranges.map(function(range) {
      return Math.random() * (range[1] - range[0]) + range[0];
    }).map(function(ip) {
      return [
        (ip & (0xff << 24)) >>> 24,
        (ip & (0xff << 16)) >>> 16,
        (ip & (0xff << 8)) >>> 8,
        (ip & (0xff << 0)) >>> 0
      ].join('.');
    });

    try {
      var vagrant = this.readFileAsString('Vagrantfile').match(/ip:\s['"]([\d\.]+)['"]/);

      if (vagrant.length) {
        ips.unshift(vagrant[1]);
      }
    } catch(e) {}

    this.prompts.push({
      required: true,
      type:     'list',
      name:     'ip',
      message:  'Vagrant IP',
      pattern:  /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,
      choices:  ips
    });
  },

  ask: function() {
    var done = this.async();

    this.prompt(this.prompts, function(props) {
      this.props = props;

      done();
    }.bind(this));
  },

  prepareReadme: function() {
    try {
      this.readmeFile = this.readFileAsString(path.join(this.env.cwd, 'README.md'));
      this.readmeFile = this.readmeFile
        .replace(/^(?:\[[^\]]+\]){1,2}(?:\([^\)]+\))?[\r\n]+=+[\r\n]+> Powered by \[(?:Genesis|Evolution)[^\r\n]+[\r\n]+/i, '')
        .replace(/\[[^\]]+\]:\s*http[^\r\n]+[\r\n]+\[(?:genesis|evolution)-wordpress\]:\s*http[^\r\n]+[\r\n]*$/i, '')
      ;
    } catch(e) {
      this.readmeFile = '';
    }
  },

  prepareSalts: function() {
    var done = this.async();

    request('https://api.wordpress.org/secret-key/1.1/salt/', function(err, response, salts) {
      if (err) {
        throw err;
      }

      this.props.salts = salts;
      done();
    }.bind(this));
  },

  prepareSshKeys: function() {
    var done      = this.async();
    var location  = path.join(this.env.cwd, 'lib', 'ansible', 'files', 'ssh', 'id_rsa');

    this.log.info('Creating SSH keys...');

    this.mkdir(path.dirname(location));

    keygen({
      location: location,
      comment:  'deploy@' + this.props.domain,
      read: false
    }, done);
  },

  prepareTemplates: function() {
    this.templates = this.expandFiles('**/*', {
      cwd: this.sourceRoot(),
    });
  },

  ready: function() {
    this.log.write('\n');
    this.log.info(chalk.green('Here we go!'));
  },

  symlinkEvolutionWordPress: function() {
    if (!this.options.dev) {
      return false;
    }

    this.log.info(chalk.green('Symlinking local Evolution WordPress as dependency...'));

    var srcpath = '../../../wordpress';
    var dstpath = path.join(this.env.cwd, 'bower_components', 'evolution-wordpress');

    this.mkdir(path.dirname(dstpath));

    fs.symlinkSync(srcpath, dstpath);
  },

  /**
   * Specify project dependencies (e.g. WordPress, Evolution, etc.) via `bower.json`
   */
  copyBower: function() {
    this.template('bower.json', 'bower.json');
    this.template('_bowerrc', '.bowerrc');
  },

  /**
   * Install project dependencies (e.g. WordPress, Evolution) for later usage by the generator
   */
  runBower: function() {
    var done = this.async();

    this.log.info(chalk.green('Installing project dependencies...'));

    this.bowerInstall(null, null, done);
  },

  /**
   * Bower's `postInstall` can only be ran after all other dependencies have been installed
   */
  copyBowerrc: function() {
    this.template('_bowerrc', '.bowerrc');
  },

  prepareWpConfig: function() {
    this.wpConfigFile = this.readFileAsString(path.join(this.env.cwd, 'web', 'wp', 'wp-config-sample.php'));
  },

  scaffold: function() {
    this.log.info(chalk.green('Scaffolding...'));

    this.templates.forEach(function(file) {
      this.template(file, file.replace(/(^|\/)_/, '$1.'));
    }.bind(this));
  },

  generateSslCert: function() {
    var done      = this.async();
    var location  = path.join(this.env.cwd, 'lib', 'ansible', 'files', 'ssl');
    var stages    = ['local', 'staging', 'production'];
    var exited    = function (err) {
      stages.pop();

      if (err || !stages.length) {
        done(err);
      }
    };

    this.log.info('Creating self-signed SSL certificate...');

    this.mkdir(path.dirname(location));

    stages.forEach(function (stage) {
      this.emit('sslInstall'+stage);

      var cert = path.join(location, stage + '.' + this.props.domain + '.pem');
      var cfg  = path.join(location, stage + '.cfg');

      this
        .spawnCommand('openssl', [
          'req',
          '-x509',
          '-nodes',
          '-days',
          '365',
          '-newkey',
          'rsa:2048',
          '-keyout',
          cert,
          '-out',
          cert,
          '-config',
          cfg
        ], {
          cwd: process.cwd(),
        })
        .on('error', exited)
        .on('exit', this.emit.bind(this, 'sslInstall'+stage+':end'))
        .on('exit', function (err) {
          if (err === 127) {
            this.log.error('Could not generate SSL certificate for '+stage);
          }

          exited(err);
        }.bind(this))
      ;
    }.bind(this));
  },

  symlinkBowerComponents: function() {
    this.log.info(chalk.green('Symlinking `bower_components` into `web`...'));

    fs.symlinkSync('../bower_components', path.join(this.env.cwd, 'web', 'bower_components'));
  },

  removeDevFiles: function() {
    if (this.options.dev) {
      return false;
    }

    this.log.info(chalk.red('Removing'), chald.green('dev files...'));

    fs.unlinkSync(path.join(this.env.cwd, 'lib', 'capistrano', 'tasks', 'testing.rake'));
  },

  fixPermissions: function() {
    fs.chmodSync(path.join(this.env.cwd, 'bin', 'provision'), '744');
    fs.chmodSync(path.join(this.env.cwd, 'lib', 'ansible', 'files', 'ssh', 'id_rsa'), '600');
  },

  installGems: function() {
    var done      = this.async();
    var installer = 'bundle';

    this.log.info(chalk.green('Installing Gems...'));

    this.emit(installer + 'Install');

    this
      .spawnCommand(installer, ['install'], done)
      .on('error', done)
      .on('exit', this.emit.bind(this, installer + 'Install:end'))
      .on('exit', function (err) {
        if (err === 127) {
          this.log.error('Could not run bundler. Please install with `sudo ' + installer + ' install`.');
        }

        done(err);
      }.bind(this))
    ;
  },
});

module.exports = WordpressGenerator;
<|endoftext|>


<commit_before>function ComponentCkeditor( id ) {
	var self = new ComponentTextfield(id);

	self.setDefaultState('text-value');
	self.setState('text-value', '');

	self.editor = CKEDITOR.instances[id];
	self.editorIsReady = false;
	self.editorToolbar = 'OneRow';
	self.haveUnsetData = false;

	self.config = {
		skin: 'kama',
		enterMode: ( CKEDITOR.env.gecko ? CKEDITOR.ENTER_BR : CKEDITOR.ENTER_P),
		shiftEnterMode: CKEDITOR.ENTER_P,
		disableNativeSpellChecker: false,
		browserContextMenuOnCtrl: true,
		colorButton_enableMore: false,
		resize_dir: 'both',
		/*resize_enabled: true,*/
		fontSize_sizes:
			'8/8pt;' +
			'9/9pt;' +
			'10/10pt;' +
			'11/11pt;' +
			'12/12pt;' +
			'14/14pt;' +
			'16/16pt;' +
			'18/18pt;' +
			'20/20pt;' +
			'22/22pt;' +
			'24/24pt;' +
			'26/26pt;' +
			'28/28pt;' +
			'36/36pt;' +
			'48/48pt',
		font_names:
			'Arial/Arial, Helvetica, sans-serif;' +
			'Arial black;' +
			'Calibri/Calibri, sans-serif;' +
			'Comic Sans MS/Comic Sans MS, cursive;' +
			'Courier New/Courier New, Courier, monospace;' +
			'Georgia/Georgia, serif;' +
			'Lucida Console/Lucida Console, monospace;' +
			'Lucida Sans Unicode/Lucida Sans Unicode, Lucida Grande, sans-serif;' +
			'Tahoma/Tahoma, Geneva, sans-serif;' +
			'Times New Roman/Times New Roman, Times, serif;' +
			'Trebuchet MS/Trebuchet MS, Helvetica, sans-serif;' +
			'Verdana/Verdana, Geneva, sans-serif',
		toolbar_Empty: [],
		toolbar_SingleRow: [
			[ 'SpellCheckerLanguage' ],
			[ 'SpellChecker' ]
		],
		toolbar_OneRow: [
			[ 'Bold', 'Italic', 'Underline', 'Strike' ],
			[ 'NumberedList', 'BulletedList' ],
			[ 'Indent', 'Outdent', 'Blockquote' ],
			[ 'JustifyLeft', 'JustifyCenter', 'JustifyRight' ],
			[ 'Link', 'Image', 'HorizontalRule' ], [ 'PasteFromWord' ], [ 'Youtube' ],
			[ 'Font' ], [ 'FontSize' ],
			[ 'TextColor', 'BGColor' ],
			[ 'SpellCheckerLanguage' ], [ 'SpellChecker' ], [ 'Resize' ]
		],
		toolbar_TwoRow: [
			[ 'Bold', 'Italic', 'Underline', 'Strike' ],
			[ 'NumberedList', 'BulletedList' ],
			[ 'Indent', 'Outdent', 'Blockquote' ],
			[ 'JustifyLeft', 'JustifyCenter', 'JustifyRight' ], [ 'PasteFromWord' ],
			[ 'Link', 'Image', 'HorizontalRule' ],
			[ 'Font' ], [ 'FontSize' ],'/',
			[ 'TextColor', 'BGColor' ], ['Youtube'],
			[ 'SpellCheckerLanguage' ], [ 'SpellChecker' ], ['Resize']
		],
		toolbar: 'OneRow',
		plugins:
			'basicstyles,' +
			'blockquote,' +
			'clipboard,' +
			'colorbutton,' +
			'contextmenu,' +
			'enterkey,' +
			'font,' +
			'horizontalrule,' +
			'htmlwriter,' +
			'indent,' +
			'justify,' +
			'link,' +
			'list,' +
			'magicline,' +
			'pastetext,' +
			/* 'removeformat,' + */
			'showborders,' +
			'tab,' +
			/*'table,' + */
			/*'tabletools,' + */
			'toolbar,' +
			'undo,' +
			'wysiwygarea,' +
			'cention_spellcheck,' +
			'cention_image,' +
			'pastefromword,' +
			'resize,' +
			'youtube',
		contentsCss: [
			WFServerURI + 'Resources/CSS/jquery.spellchecker.css',
			WFServerURI + 'Resources/Javascript/ckeditor/contents.css',
			WFServerURI + 'Support/Components/Ckeditor/Ckeditor.css',
		],
		spellCheckLanguages: []
	};

	self.setFontSize = function( size ){
		if( size ){
			self.config.fontSize_defaultLabel = ''+size;
			CKEDITOR.addCss( '.cke_editable{ font-size: '+ size +'; }' );
		}
	};

	self.setFontFamily = function( family ){
		if( family ){
			self.config.font_defaultLabel = ''+family;
			CKEDITOR.addCss( '.cke_editable{ font-family: '+ family +'; }' );
		}
	}

	self.setLanguages = function( list ) {
	    self.config.spellCheckLanguages = list;
	};
	self.setImages = function( list ) {
		if( self.editor ) {
			self.editor.___fileArchiveImages = list;
		}
	};
	self.setShowResize = function( resize ) {
	    if( resize == true )
		self.config.resize_enabled = true;
	    else
		self.config.resize_enabled = false;
	};
	self.setItemHeight = function( height ){
		self.config.height = height;
	};
	self.showBasicToolbar = function() { };
	self.showAdvancedToolbar = function() {};
	self.setTwoRowToolbar = function( value ) {
		if( value ) {
			self.editorToolbar = 'TwoRow';
			self.config.toolbar = self.editorToolbar;
		}
	};
	self.setShowToolbar = function( value ) {
		if( !value ) {
			self.editorToolbar = 'Empty';
			self.config.toolbar = self.editorToolbar;
		}
	};
	self.setSimpleToolbar = function( value ) {
		if( !value ) {
			self.editorToolbar = 'SingleRow';
			self.config.toolbar = self.editorToolbar;
		}
	};
	self.setReadOnly = function( value ) {};
	self.setEnabled = function( value ) {};

	self.empty = function() {
		if( self.editor ) {
			if( self.editor.getData() )
				return false;
		}
		return true;
	};

	var previousGetState = self.getState;
	self.getState = function( state ) {
		if( state == 'text-value' ) {
			return self.editor.getData();
		}
		return previousGetState(state);
	};

	var previousSetState = self.setState;
	self.setState = function( state, value ) {
		if( state == 'text-value' ) {
			var dataSet = false;
			self._states['text-value'] = value;
			if( self.editor ) {
				if( self.editorIsReady ) {
					self.editor.setData(value);
					self.editor.updateElement();
					dataSet = true;
				}
			}
			if( !dataSet ) {
				self.haveUnsetData = true;
			}
		} else {
			previousSetState(state, value);
		}
	};

	self.updateVisual = function() {};
	self.updateFormValue = function() {
		if( self.editor ) {
			self.editor.updateElement();
		}
	};

	var previousActivate = self.activate;
	self.activate = function() {
		self.editor = CKEDITOR.replace(self.identifier(), self.config);
		self.editor.on('contentDom', function() {
			self.editorIsReady = true;
			if( self.haveUnsetData ) {
				self.editor.setData(self._states['text-value']);
				self.editor.updateElement();
				self.haveUnsetData = false;
			}
		});

		self.editor.on('contentDomUnload', function() {
			self.editorIsReady = false;
		});
		previousActivate();
	};

	return self;
}

CKEDITOR.addCss('body { margin-left: 5px; margin-right: 5px; margin-top: 3px; margin-bottom: 3px; }');<commit_msg>Move youtube toolbar button to sit next to other insert buttons<commit_after>function ComponentCkeditor( id ) {
	var self = new ComponentTextfield(id);

	self.setDefaultState('text-value');
	self.setState('text-value', '');

	self.editor = CKEDITOR.instances[id];
	self.editorIsReady = false;
	self.editorToolbar = 'OneRow';
	self.haveUnsetData = false;

	self.config = {
		skin: 'kama',
		enterMode: ( CKEDITOR.env.gecko ? CKEDITOR.ENTER_BR : CKEDITOR.ENTER_P),
		shiftEnterMode: CKEDITOR.ENTER_P,
		disableNativeSpellChecker: false,
		browserContextMenuOnCtrl: true,
		colorButton_enableMore: false,
		resize_dir: 'both',
		/*resize_enabled: true,*/
		fontSize_sizes:
			'8/8pt;' +
			'9/9pt;' +
			'10/10pt;' +
			'11/11pt;' +
			'12/12pt;' +
			'14/14pt;' +
			'16/16pt;' +
			'18/18pt;' +
			'20/20pt;' +
			'22/22pt;' +
			'24/24pt;' +
			'26/26pt;' +
			'28/28pt;' +
			'36/36pt;' +
			'48/48pt',
		font_names:
			'Arial/Arial, Helvetica, sans-serif;' +
			'Arial black;' +
			'Calibri/Calibri, sans-serif;' +
			'Comic Sans MS/Comic Sans MS, cursive;' +
			'Courier New/Courier New, Courier, monospace;' +
			'Georgia/Georgia, serif;' +
			'Lucida Console/Lucida Console, monospace;' +
			'Lucida Sans Unicode/Lucida Sans Unicode, Lucida Grande, sans-serif;' +
			'Tahoma/Tahoma, Geneva, sans-serif;' +
			'Times New Roman/Times New Roman, Times, serif;' +
			'Trebuchet MS/Trebuchet MS, Helvetica, sans-serif;' +
			'Verdana/Verdana, Geneva, sans-serif',
		toolbar_Empty: [],
		toolbar_SingleRow: [
			[ 'SpellCheckerLanguage' ],
			[ 'SpellChecker' ]
		],
		toolbar_OneRow: [
			[ 'Bold', 'Italic', 'Underline', 'Strike' ],
			[ 'NumberedList', 'BulletedList' ],
			[ 'Indent', 'Outdent', 'Blockquote' ],
			[ 'JustifyLeft', 'JustifyCenter', 'JustifyRight' ],
			[ 'Link', 'Image', 'Youtube', 'HorizontalRule' ], [ 'PasteFromWord' ],
			[ 'Font' ], [ 'FontSize' ],
			[ 'TextColor', 'BGColor' ],
			[ 'SpellCheckerLanguage' ], [ 'SpellChecker' ], [ 'Resize' ]
		],
		toolbar_TwoRow: [
			[ 'Bold', 'Italic', 'Underline', 'Strike' ],
			[ 'NumberedList', 'BulletedList' ],
			[ 'Indent', 'Outdent', 'Blockquote' ],
			[ 'JustifyLeft', 'JustifyCenter', 'JustifyRight' ], [ 'PasteFromWord' ],
			[ 'Link', 'Image', 'Youtube', 'HorizontalRule' ],
			[ 'Font' ], [ 'FontSize' ],'/',
			[ 'TextColor', 'BGColor' ],
			[ 'SpellCheckerLanguage' ], [ 'SpellChecker' ], ['Resize']
		],
		toolbar: 'OneRow',
		plugins:
			'basicstyles,' +
			'blockquote,' +
			'clipboard,' +
			'colorbutton,' +
			'contextmenu,' +
			'enterkey,' +
			'font,' +
			'horizontalrule,' +
			'htmlwriter,' +
			'indent,' +
			'justify,' +
			'link,' +
			'list,' +
			'magicline,' +
			'pastetext,' +
			/* 'removeformat,' + */
			'showborders,' +
			'tab,' +
			/*'table,' + */
			/*'tabletools,' + */
			'toolbar,' +
			'undo,' +
			'wysiwygarea,' +
			'cention_spellcheck,' +
			'cention_image,' +
			'pastefromword,' +
			'resize,' +
			'youtube',
		contentsCss: [
			WFServerURI + 'Resources/CSS/jquery.spellchecker.css',
			WFServerURI + 'Resources/Javascript/ckeditor/contents.css',
			WFServerURI + 'Support/Components/Ckeditor/Ckeditor.css',
		],
		spellCheckLanguages: []
	};

	self.setFontSize = function( size ){
		if( size ){
			self.config.fontSize_defaultLabel = ''+size;
			CKEDITOR.addCss( '.cke_editable{ font-size: '+ size +'; }' );
		}
	};

	self.setFontFamily = function( family ){
		if( family ){
			self.config.font_defaultLabel = ''+family;
			CKEDITOR.addCss( '.cke_editable{ font-family: '+ family +'; }' );
		}
	}

	self.setLanguages = function( list ) {
	    self.config.spellCheckLanguages = list;
	};
	self.setImages = function( list ) {
		if( self.editor ) {
			self.editor.___fileArchiveImages = list;
		}
	};
	self.setShowResize = function( resize ) {
	    if( resize == true )
		self.config.resize_enabled = true;
	    else
		self.config.resize_enabled = false;
	};
	self.setItemHeight = function( height ){
		self.config.height = height;
	};
	self.showBasicToolbar = function() { };
	self.showAdvancedToolbar = function() {};
	self.setTwoRowToolbar = function( value ) {
		if( value ) {
			self.editorToolbar = 'TwoRow';
			self.config.toolbar = self.editorToolbar;
		}
	};
	self.setShowToolbar = function( value ) {
		if( !value ) {
			self.editorToolbar = 'Empty';
			self.config.toolbar = self.editorToolbar;
		}
	};
	self.setSimpleToolbar = function( value ) {
		if( !value ) {
			self.editorToolbar = 'SingleRow';
			self.config.toolbar = self.editorToolbar;
		}
	};
	self.setReadOnly = function( value ) {};
	self.setEnabled = function( value ) {};

	self.empty = function() {
		if( self.editor ) {
			if( self.editor.getData() )
				return false;
		}
		return true;
	};

	var previousGetState = self.getState;
	self.getState = function( state ) {
		if( state == 'text-value' ) {
			return self.editor.getData();
		}
		return previousGetState(state);
	};

	var previousSetState = self.setState;
	self.setState = function( state, value ) {
		if( state == 'text-value' ) {
			var dataSet = false;
			self._states['text-value'] = value;
			if( self.editor ) {
				if( self.editorIsReady ) {
					self.editor.setData(value);
					self.editor.updateElement();
					dataSet = true;
				}
			}
			if( !dataSet ) {
				self.haveUnsetData = true;
			}
		} else {
			previousSetState(state, value);
		}
	};

	self.updateVisual = function() {};
	self.updateFormValue = function() {
		if( self.editor ) {
			self.editor.updateElement();
		}
	};

	var previousActivate = self.activate;
	self.activate = function() {
		self.editor = CKEDITOR.replace(self.identifier(), self.config);
		self.editor.on('contentDom', function() {
			self.editorIsReady = true;
			if( self.haveUnsetData ) {
				self.editor.setData(self._states['text-value']);
				self.editor.updateElement();
				self.haveUnsetData = false;
			}
		});

		self.editor.on('contentDomUnload', function() {
			self.editorIsReady = false;
		});
		previousActivate();
	};

	return self;
}

CKEDITOR.addCss('body { margin-left: 5px; margin-right: 5px; margin-top: 3px; margin-bottom: 3px; }');<|endoftext|>


<commit_before>import * as api from "../helpers/api";
import {
  getMeasureMOE,
  getTimeDrilldown,
  getValidDimensions,
  getValidDrilldowns,
  getValidMeasures,
  injectCubeInfoOnMeasure,
  reduceLevelsFromDimension,
  preventHierarchyIncompatibility
} from "../helpers/sorting";

/**
 * Returns the first element in the `haystack` whose `_key` annotation
 * matches the `needle` param. If none found, returns the first element
 * from the `haystack`.
 * @param {string} needle The key to match
 * @param {any[]} haystack The array where to search for the object.
 */
export function findByKeyOrFirst(needle, haystack) {
  return needle
    ? haystack.find(item => item.annotations._key === needle) || haystack[0]
    : haystack[0];
}

/**
 * Retrieves the cube list and prepares the initial state for the first query
 * @param {object} locationQuery An object made from key-string pairs, from the parsing of the current Location.search
 */
export function fetchCubes(locationQuery) {
  return api.cubes().then(cubes => {
    locationQuery = locationQuery || {};
    injectCubeInfoOnMeasure(cubes);

    const measures = getValidMeasures(cubes);
    const firstMeasure = findByKeyOrFirst(locationQuery.ms, measures);
    const firstCubeName = firstMeasure.annotations._cb_name;
    const firstCube = cubes.find(cube => cube.name === firstCubeName);
    const firstMoe = getMeasureMOE(firstCube, firstMeasure);
    const timeDrilldown = getTimeDrilldown(firstCube);

    const dimensions = getValidDimensions(firstCube);
    const drilldowns = getValidDrilldowns(dimensions);

    let drilldown, firstDimension, levels;
    if ("dd" in locationQuery) {
      drilldown = findByKeyOrFirst(locationQuery.dd, drilldowns);
      firstDimension = drilldown.hierarchy.dimension;
      levels = reduceLevelsFromDimension([], firstDimension);
    }
    else {
      firstDimension = dimensions[0];
      levels = reduceLevelsFromDimension([], firstDimension);
      drilldown = levels[0];
    }

    preventHierarchyIncompatibility(drilldowns, drilldown);

    return {
      options: {cubes, measures, dimensions, drilldowns, levels},
      query: {
        cube: firstCube,
        measure: firstMeasure,
        moe: firstMoe,
        dimension: firstDimension,
        drilldown,
        timeDrilldown,
        conditions: []
      },
      queryOptions: {
        parents: drilldown.depth > 1
      }
    };
  });
}

/**
 * Retrieves all the members for a certain Level.
 * @param {Level} level A mondrian-rest-client Level object
 */
export function fetchMembers(level) {
  this.setState({loading: true, members: []}, () =>
    api.members(level).then(members => this.setState({loading: false, members}))
  );
}

/**
 * Retrieves the dataset for the query in the current Vizbuilder state.
 */
export function fetchQuery() {
  const {query, queryOptions} = this.props;
  return api.query({
    ...query,
    options: queryOptions
  });
}
<commit_msg>sets default vizbuilder measure to FAF<commit_after>import * as api from "../helpers/api";
import {
  getMeasureMOE,
  getTimeDrilldown,
  getValidDimensions,
  getValidDrilldowns,
  getValidMeasures,
  injectCubeInfoOnMeasure,
  reduceLevelsFromDimension,
  preventHierarchyIncompatibility
} from "../helpers/sorting";

/**
 * Returns the first element in the `haystack` whose `_key` annotation
 * matches the `needle` param. If none found, returns the first element
 * from the `haystack`.
 * @param {string} needle The key to match
 * @param {any[]} haystack The array where to search for the object.
 */
export function findByKeyOrFirst(needle = "20fb9L", haystack) {
  return needle
    ? haystack.find(item => item.annotations._key === needle) || haystack[0]
    : haystack;
}

/**
 * Retrieves the cube list and prepares the initial state for the first query
 * @param {object} locationQuery An object made from key-string pairs, from the parsing of the current Location.search
 */
export function fetchCubes(locationQuery) {
  return api.cubes().then(cubes => {
    locationQuery = locationQuery || {};
    injectCubeInfoOnMeasure(cubes);

    const measures = getValidMeasures(cubes);
    const firstMeasure = findByKeyOrFirst(locationQuery.ms, measures);
    const firstCubeName = firstMeasure.annotations._cb_name;
    const firstCube = cubes.find(cube => cube.name === firstCubeName);
    const firstMoe = getMeasureMOE(firstCube, firstMeasure);
    const timeDrilldown = getTimeDrilldown(firstCube);

    const dimensions = getValidDimensions(firstCube);
    const drilldowns = getValidDrilldowns(dimensions);

    let drilldown, firstDimension, levels;
    if ("dd" in locationQuery) {
      drilldown = findByKeyOrFirst(locationQuery.dd, drilldowns);
      firstDimension = drilldown.hierarchy.dimension;
      levels = reduceLevelsFromDimension([], firstDimension);
    }
    else {
      firstDimension = dimensions[0];
      levels = reduceLevelsFromDimension([], firstDimension);
      drilldown = levels[0];
    }

    preventHierarchyIncompatibility(drilldowns, drilldown);

    return {
      options: {cubes, measures, dimensions, drilldowns, levels},
      query: {
        cube: firstCube,
        measure: firstMeasure,
        moe: firstMoe,
        dimension: firstDimension,
        drilldown,
        timeDrilldown,
        conditions: []
      },
      queryOptions: {
        parents: drilldown.depth > 1
      }
    };
  });
}

/**
 * Retrieves all the members for a certain Level.
 * @param {Level} level A mondrian-rest-client Level object
 */
export function fetchMembers(level) {
  this.setState({loading: true, members: []}, () =>
    api.members(level).then(members => this.setState({loading: false, members}))
  );
}

/**
 * Retrieves the dataset for the query in the current Vizbuilder state.
 */
export function fetchQuery() {
  const {query, queryOptions} = this.props;
  return api.query({
    ...query,
    options: queryOptions
  });
}
<|endoftext|>


<commit_before>

/*
 *  test function, to run a translation (together with testHTML.html)
 *  For now, the JSON is stored and parsed locally in this function
 */
function test (){

  var obj = '{  "START": {    "type": "LIST_ALL",    "link": {      "direction": "TO",      "linkPartner": "Mensch"    }  },  "SUBJECTS": [    {      "alias": "Mensch",      "uri": "/app/mockup/Person.json",      "properties": [        {          "alias": "lebt in",          "uri": "/app/mockup/lebt_in.json",          "type": "OBJECT_PROPERTY",          "isObjectProperty": true,         "propertyType": [            "/app/mockup/Stadt.json",            "/app/mockup/Land.json"          ],          "view": true,          "operator": "MUST",          "link": {            "direction": "TO",            "linkPartner": "Stadt"          },          "arithmetic": {},          "compare": {}        }      ]    },    {      "alias": "Stadt",      "uri": "/app/mockup/Stadt.json",      "properties": [        {          "alias": "Einwohnerzahl",          "uri": "/app/mockup/einwohnerZahl.json",          "type": "DATATYPE_PROPERTY",          "isObjectProperty": false,          "propertyType": [            "http://www.w3.org/2001/XMLSchema#integer"          ],          "view": true,          "operator": "MUST",          "link": {           "direction": "TO",           "linkPartner": ""          },          "arithmetic": {},          "compare": {}        }      ]    }  ]}';
  var json = JSON.parse(obj);

  var erg = translateAll(json);
  alert(erg);
  return erg;
}

function translateAllFromString(string){
  return changeURIs(JSON.parse(string));
}

/*
 * Function to exchange mockup-URIs with dbpedia counterparts
 */
function changeURIs(json) {

  for(var i = 0; i < json.SUBJECTS.length; i++) {

    json.SUBJECTS[i].uri = findURI(json.SUBJECTS[i].uri, json.SUBJECTS[i].label);

    for(var j = 0; j < json.SUBJECTS[i].properties.length; j++) {

      json.SUBJECTS[i].properties[j].uri = findURI(json.SUBJECTS[i].properties[j].uri, json.SUBJECTS[i].label);
    }
  }

  return translateAll(json);
}

/*
 * Helper function for changeURIs to find specific URIs for given mockup URI and label if necessary
 */
function findURI(oldURI, label) {

  if(oldURI === "mockup/Firma.json") return "http://dbpedia.org/ontology/Company";

  if(oldURI === "mockup/heisst.json") return "http://dbpedia.org/property/name";

  if(oldURI === "mockup/beschaeftigtenZahl.json" && label === "Firma") return "http://dbpedia.org/ontology/numberOfEmployees";

  if(oldURI === "mockup/beschaeftigtenZahl.json" && label === "Uni") return "http://dbpedia.org/ontology/numberOfAcademicStaff";

  if(oldURI === "mockup/Land.json") return "http://dbpedia.org/ontology/Country";

  if(oldURI === "mockup/einwohnerZahl.json") return "http://dbpedia.org/ontology/populationTotal";

  if(oldURI === "mockup/flaeche.json") return "http://dbpedia.org/ontology/PopulatedPlace/area";

  if(oldURI === "mockup/Person.json") return "http://dbpedia.org/ontology/Person";

  if(oldURI === "mockup/alter.json") return "http://dbpedia.org/ontology/birthDate";

  if(oldURI === "mockup/gehalt.json") return "http://dbpedia.org/ontology/salary";

  if(oldURI === "mockup/fachsemester.json") return "mockup/fachsemester.json";				// FEHLT

  if(oldURI === "mockup/studiert_an.json") return "http://dbpedia.org/ontology/university";

  if(oldURI === "mockup/arbeitet_bei.json") return "http://dbpedia.org/ontology/employer";

  if(oldURI === "mockup/lebt_in.json") return "http://dbpedia.org/ontology/residence";

  if(oldURI === "mockup/vorname.json") return "http://dbpedia.org/ontology/GivenName";

  if(oldURI === "mockup/nachname.json") return "http://dbpedia.org/ontology/Surname";

  if(oldURI === "mockup/Stadt.json") return "http://dbpedia.org/ontology/Settlement";

  if(oldURI === "mockup/matrikelnummer.json") return "mockup/matrikelnummer.json";			// FEHLT

  if(oldURI === "mockup/studiert.json") return "mockup/studiert.json";						// FEHLT

  if(oldURI === "mockup/gruendungsjahr.json" && label === "Stadt") return "http://dbpedia.org/ontology/foundingYear";

  if(oldURI === "mockup/gruendungsjahr.json" && label === "Uni") return "http://dbpedia.org/ontology/formationYear";

  if(oldURI === "mockup/liegt_in.json" && label === "Stadt") return "http://dbpedia.org/ontology/nation";

  if(oldURI === "mockup/liegt_in.json" && label === "Uni") return "http://dbpedia.org/ontology/locationCity";

  if(oldURI === "mockup/Studiengang.json") return "mockup/Studiengang.json";				// FEHLT

  if(oldURI === "mockup/Universitaet.json") return "http://dbpedia.org/ontology/University";

  if(oldURI === "mockup/bietet_an.json") return "mockup/bietet_an.json";					// FEHLT

  return "";
}

/*
 *  main function, takes a JSON-object, looks for the main class and starts translation there, and in the end adds shown values and SPARQL-'header' (e.g. SELECT DISTINCT..)
 */
function translateAll (json) {

  var shownValues = [];
  var translated = [];
  var SPARQL = "";

  for(var i = 0; i < json.SUBJECTS.length; i++)
  {
    if(json.SUBJECTS[i].alias === json['START'].link.linkPartner)
    {
      SPARQL +=  translateSubject(json.SUBJECTS[i], shownValues, translated, json, "");
    }
  }

  return translateStartpoint(json, shownValues) + "\nwhere {\n" + SPARQL + "\n}";
}

/*
 * Function to translate the beginning of a SPARQL query, including the shown values
 */
function translateStartpoint (json, shownValues) {

  var SPARQLStart = "";

  if(json.START.type === "LIST_ALL")   {
    SPARQLStart = "SELECT DISTINCT ";
  }
  else {
    SPARQLStart = "SELECT ";
  }

  for(var i = 0; i < shownValues.length; i++) {
    SPARQLStart += "?" + shownValues[i] + " ";
  }

  return SPARQLStart
}

/*
 * Function to translate a subject. Calls all translate-property functions for all the subjects properties
 */
function translateSubject (oneSubject, shownValues, translated, json, prefix) {

  var SPARQL = "";

  if(!presentInArray(translated, oneSubject.alias)) {
    SPARQL += "?" + prefix + oneSubject.alias + " a <" + oneSubject.uri + "> .\n";

    if(oneSubject.view) {
      shownValues[shownValues.length] = prefix + oneSubject.alias;
    }

    translated[translated.length] = oneSubject.alias;

    for(i in oneSubject.properties) {

      if(oneSubject.properties[i].type === "OBJECT_PROPERTY") {
        SPARQL += translateObjectProperty(oneSubject, oneSubject.properties[i], shownValues, translated, json, prefix) + '\n';
      }
      else if(oneSubject.properties[i].type === "DATATYPE_PROPERTY") {
        SPARQL += translateDatatypeProperty(oneSubject, oneSubject.properties[i], shownValues, translated, json, prefix) + '\n';
      }
    }
  }

  return SPARQL;
}

/*
 * function to translate Object properties. Checks for operator of property, calls translateSubject when necessary
 */
function translateObjectProperty (itsSubject, eigenschaft, shownValues, translated, json, prefix) {

  var SPARQL = "";

  if(eigenschaft.operator === "MUST" || eigenschaft.operator === "CAN") {

    if(eigenschaft.operator === "CAN") {
      SPARQL += "OPTIONAL { \n";
    }

    SPARQL += "?" + prefix + itsSubject.alias + " <" + eigenschaft.uri + "> ?";

    if(typeof eigenschaft.link.linkPartner != "undefined") {

      SPARQL += itsSubject.alias + "_" + eigenschaft.link.linkPartner + " .\n";

      if(eigenschaft.operator === "CAN") {
        SPARQL += "}\n";
      }

      for(var i = 0; i < json.SUBJECTS.length; i++) {

        if(json.SUBJECTS[i].alias === eigenschaft.link.linkPartner) {
          SPARQL +=  translateSubject(json.SUBJECTS[i], shownValues, translated, json, itsSubject.alias + "_");
        }
      }
    }

    else {
      SPARQL += itsSubject.alias + "_" + eigenschaft.alias  + " .\n"; ;
      if(eigenschaft.operator === "CAN") {
        SPARQL += "}\n";
      }
      shownValues[shownValues.length] = itsSubject.alias + "_" + eigenschaft.alias;
    }

  }

  if(eigenschaft.operator === "MUST_NOT") {

    if(typeof eigenschaft.link.linkPartner != "undefined") {

      for(var i = 0; i < json.SUBJECTS.length; i++) {
        if(json.SUBJECTS[i].alias === eigenschaft.link.linkPartner) {
          SPARQL +=  translateSubject(json.SUBJECTS[i], shownValues, translated, json, itsSubject.alias + "_");
        }
      }

      SPARQL += "FILTER NOT EXIST { ?" + prefix + itsSubject.alias + " <" + eigenschaft.uri + "> ?" + itsSubject.alias + "_" + eigenschaft.link.linkPartner + " } .\n";
    }

    else {
      SPARQL += "FILTER NOT EXIST { ?" + prefix + itsSubject.alias + " <" + eigenschaft.uri + "> ?" + itsSubject.alias + "_" + eigenschaft.alias + " } .\n";
    }
  }

  if(eigenschaft.operator === "IS_OF") {

    SPARQL += prefix + itsSubject.alias + " ^<" + eigenschaft.uri +  "> " + itsSubject.alias + "_" + eigenschaft.link.linkPartner + " .\n";

    for(var i = 0; i < json.SUBJECTS.length; i++) {
      if(json.SUBJECTS[i].alias === eigenschaft.link.linkPartner) {
        SPARQL +=  translateSubject(json.SUBJECTS[i], shownValues, translated, json, itsSubject.alias + "_");
      }
    }

  }

  if(eigenschaft.operator === "IS_NOT_OF") {

    for(var i = 0; i < json.SUBJECTS.length; i++) {
      if(json.SUBJECTS[i].alias === eigenschaft.link.linkPartner) {
        SPARQL +=  translateSubject(json.SUBJECTS[i], shownValues, translated, json, itsSubject.alias + "_");
      }
    }

    SPARQL += "FILTER NOT EXIST { " + prefix + itsSubject.alias + " ^<" + eigenschaft.uri +  "> " + itsSubject.alias + "_" + eigenschaft.link.linkPartner + " } .\n";
  }

  return SPARQL;
}

/*
 * function to translate Datatype properties. Checks for operator of property
 */
function translateDatatypeProperty (itsSubject, eigenschaft, shownValues, translated, json, prefix) {

  var SPARQL = "";

  if(eigenschaft.operator === "MUST" || eigenschaft.operator === "CAN") {

    if(eigenschaft.operator === "CAN") {
      SPARQL += "OPTIONAL { \n";
    }

    if(typeof eigenschaft.arithmetic.operator != "undefined") {

      SPARQL += "?" + prefix + itsSubject.alias + " <" + eigenschaft.uri + "> ?" + prefix + itsSubject.alias + "_" + eigenschaft.alias + "_temp .\n";
      SPARQL += "BIND (( ?" + prefix + itsSubject.alias + "_" + eigenschaft.alias + "_temp " + eigenschaft.arithmetic.operator + " " + eigenschaft.arithmetic.amount + " ) as ?" + prefix + itsSubject.alias + "_" + eigenschaft.alias + ") .\n";
    }
    else {
      SPARQL += "?" + prefix + itsSubject.alias + " <" + eigenschaft.uri + "> ?" + prefix + itsSubject.alias + "_" + eigenschaft.alias + " .\n";
    }

    if(typeof eigenschaft.compare.operator != "undefined") {

      SPARQL += "FILTER ( ?" + prefix + itsSubject.alias + "_" + eigenschaft.alias + " " + eigenschaft.compare.operator + " " + eigenschaft.compare.amount + " ) .\n";
    }

    if(eigenschaft.operator === "CAN") {
      SPARQL += "}\n";
    }
  }

  if(eigenschaft.operator === "MUST_NOT") {
    SPARQL += "FILTER NOT EXIST { ?" + prefix + itsSubject.alias + " <" + eigenschaft.uri + "> ?" + prefix + itsSubject.alias + "_" + eigenschaft.alias + " } .\n";
  }

  if(eigenschaft.view === true) {
    shownValues[shownValues.length] = prefix + itsSubject.alias + "_" + eigenschaft.alias;
  }

  return SPARQL;
}

/*
 * little helper function to check, if an object obj is present in an array arr
 */
function presentInArray(arr, obj) {

  for(var i=0; i<arr.length; i++) {
    if (arr[i] == obj) return true;
  }

  return false;
}<commit_msg>Changed/flagged URI exchange in new translator<commit_after>

/*
 *  test function, to run a translation (together with testHTML.html)
 *  For now, the JSON is stored and parsed locally in this function
 */
function test (){

  var obj = '{  "START": {    "type": "LIST_ALL",    "link": {      "direction": "TO",      "linkPartner": "Mensch"    }  },  "SUBJECTS": [    {      "alias": "Mensch",      "uri": "/app/mockup/Person.json",      "properties": [        {          "alias": "lebt in",          "uri": "/app/mockup/lebt_in.json",          "type": "OBJECT_PROPERTY",          "isObjectProperty": true,         "propertyType": [            "/app/mockup/Stadt.json",            "/app/mockup/Land.json"          ],          "view": true,          "operator": "MUST",          "link": {            "direction": "TO",            "linkPartner": "Stadt"          },          "arithmetic": {},          "compare": {}        }      ]    },    {      "alias": "Stadt",      "uri": "/app/mockup/Stadt.json",      "properties": [        {          "alias": "Einwohnerzahl",          "uri": "/app/mockup/einwohnerZahl.json",          "type": "DATATYPE_PROPERTY",          "isObjectProperty": false,          "propertyType": [            "http://www.w3.org/2001/XMLSchema#integer"          ],          "view": true,          "operator": "MUST",          "link": {           "direction": "TO",           "linkPartner": ""          },          "arithmetic": {},          "compare": {}        }      ]    }  ]}';
  var json = JSON.parse(obj);

  var erg = translateAll(json);
  alert(erg);
  return erg;
}

function translateAllFromString(string){
  return changeURIs(JSON.parse(string));
}

/*
 * Function to exchange mockup-URIs with dbpedia counterparts
 */
function changeURIs(json) {

  for(var i = 0; i < json.SUBJECTS.length; i++) {

    json.SUBJECTS[i].uri = findURI(json.SUBJECTS[i].uri, json.SUBJECTS[i].label);

    for(var j = 0; j < json.SUBJECTS[i].properties.length; j++) {

      json.SUBJECTS[i].properties[j].uri = findURI(json.SUBJECTS[i].properties[j].uri, json.SUBJECTS[i].label);
    }
  }

  return translateAll(json);
}

/*
 * Helper function for changeURIs to find specific URIs for given mockup URI and label if necessary
 */
function findURI(oldURI, label) {

  if(oldURI === "mockup/Firma.json") return "http://dbpedia.org/ontology/Company";

  if(oldURI === "mockup/heisst.json") return "http://dbpedia.org/property/name";

  if(oldURI === "mockup/beschaeftigtenZahl.json" && label === "Firma") return "http://dbpedia.org/ontology/numberOfEmployees";

  if(oldURI === "mockup/beschaeftigtenZahl.json" && label === "Uni") return "http://dbpedia.org/ontology/numberOfAcademicStaff";

  if(oldURI === "mockup/Land.json") return "http://dbpedia.org/ontology/Country";

  if(oldURI === "mockup/einwohnerZahl.json") return "http://dbpedia.org/ontology/populationTotal";	// GEHT NICHT FUER LAND

  if(oldURI === "mockup/flaeche.json") return "http://dbpedia.org/ontology/areaTotal";

  if(oldURI === "mockup/Person.json") return "http://dbpedia.org/ontology/Person";

  if(oldURI === "mockup/alter.json") return "http://dbpedia.org/ontology/birthDate";

  if(oldURI === "mockup/gehalt.json") return "http://dbpedia.org/ontology/salary";

  if(oldURI === "mockup/fachsemester.json") return "mockup/fachsemester.json";				// FEHLT

  if(oldURI === "mockup/studiert_an.json") return "http://dbpedia.org/ontology/university";

  if(oldURI === "mockup/arbeitet_bei.json") return "http://dbpedia.org/ontology/employer";

  if(oldURI === "mockup/lebt_in.json") return "http://dbpedia.org/ontology/residence";

  if(oldURI === "mockup/vorname.json") return "http://dbpedia.org/ontology/GivenName";		// GEHT NICHT

  if(oldURI === "mockup/nachname.json") return "http://dbpedia.org/ontology/Surname";		// GEHT NICHT

  if(oldURI === "mockup/Stadt.json") return "http://dbpedia.org/ontology/Settlement";

  if(oldURI === "mockup/matrikelnummer.json") return "mockup/matrikelnummer.json";			// FEHLT

  if(oldURI === "mockup/studiert.json") return "mockup/studiert.json";						// FEHLT

  if(oldURI === "mockup/gruendungsjahr.json" && label === "Stadt") return "http://dbpedia.org/ontology/foundingYear";

  if(oldURI === "mockup/gruendungsjahr.json" && label === "Uni") return "http://dbpedia.org/ontology/formationYear";

  if(oldURI === "mockup/liegt_in.json" && label === "Stadt") return "http://dbpedia.org/ontology/nation";     // GEHT NICHT

  if(oldURI === "mockup/liegt_in.json" && label === "Uni") return "http://dbpedia.org/ontology/locationCity"; // GEHT NICHT

  if(oldURI === "mockup/Studiengang.json") return "mockup/Studiengang.json";				// FEHLT

  if(oldURI === "mockup/Universitaet.json") return "http://dbpedia.org/ontology/University";

  if(oldURI === "mockup/bietet_an.json") return "mockup/bietet_an.json";					// FEHLT

  return "";
}

/*
 *  main function, takes a JSON-object, looks for the main class and starts translation there, and in the end adds shown values and SPARQL-'header' (e.g. SELECT DISTINCT..)
 */
function translateAll (json) {

  var shownValues = [];
  var translated = [];
  var SPARQL = "";

  for(var i = 0; i < json.SUBJECTS.length; i++)
  {
    if(json.SUBJECTS[i].alias === json['START'].link.linkPartner)
    {
      SPARQL +=  translateSubject(json.SUBJECTS[i], shownValues, translated, json, "");
    }
  }

  return translateStartpoint(json, shownValues) + "\nwhere {\n" + SPARQL + "\n}";
}

/*
 * Function to translate the beginning of a SPARQL query, including the shown values
 */
function translateStartpoint (json, shownValues) {

  var SPARQLStart = "";

  if(json.START.type === "LIST_ALL")   {
    SPARQLStart = "SELECT DISTINCT ";
  }
  else {
    SPARQLStart = "SELECT ";
  }

  for(var i = 0; i < shownValues.length; i++) {
    SPARQLStart += "?" + shownValues[i] + " ";
  }

  return SPARQLStart
}

/*
 * Function to translate a subject. Calls all translate-property functions for all the subjects properties
 */
function translateSubject (oneSubject, shownValues, translated, json, prefix) {

  var SPARQL = "";

  if(!presentInArray(translated, oneSubject.alias)) {
    SPARQL += "?" + prefix + oneSubject.alias + " a <" + oneSubject.uri + "> .\n";

    if(oneSubject.view) {
      shownValues[shownValues.length] = prefix + oneSubject.alias;
    }

    translated[translated.length] = oneSubject.alias;

    for(i in oneSubject.properties) {

      if(oneSubject.properties[i].type === "OBJECT_PROPERTY") {
        SPARQL += translateObjectProperty(oneSubject, oneSubject.properties[i], shownValues, translated, json, prefix) + '\n';
      }
      else if(oneSubject.properties[i].type === "DATATYPE_PROPERTY") {
        SPARQL += translateDatatypeProperty(oneSubject, oneSubject.properties[i], shownValues, translated, json, prefix) + '\n';
      }
    }
  }

  return SPARQL;
}

/*
 * function to translate Object properties. Checks for operator of property, calls translateSubject when necessary
 */
function translateObjectProperty (itsSubject, eigenschaft, shownValues, translated, json, prefix) {

  var SPARQL = "";

  if(eigenschaft.operator === "MUST" || eigenschaft.operator === "CAN") {

    if(eigenschaft.operator === "CAN") {
      SPARQL += "OPTIONAL { \n";
    }

    SPARQL += "?" + prefix + itsSubject.alias + " <" + eigenschaft.uri + "> ?";

    if(typeof eigenschaft.link.linkPartner != "undefined") {

      SPARQL += itsSubject.alias + "_" + eigenschaft.link.linkPartner + " .\n";

      if(eigenschaft.operator === "CAN") {
        SPARQL += "}\n";
      }

      for(var i = 0; i < json.SUBJECTS.length; i++) {

        if(json.SUBJECTS[i].alias === eigenschaft.link.linkPartner) {
          SPARQL +=  translateSubject(json.SUBJECTS[i], shownValues, translated, json, itsSubject.alias + "_");
        }
      }
    }

    else {
      SPARQL += itsSubject.alias + "_" + eigenschaft.alias  + " .\n"; ;
      if(eigenschaft.operator === "CAN") {
        SPARQL += "}\n";
      }
      shownValues[shownValues.length] = itsSubject.alias + "_" + eigenschaft.alias;
    }

  }

  if(eigenschaft.operator === "MUST_NOT") {

    if(typeof eigenschaft.link.linkPartner != "undefined") {

      for(var i = 0; i < json.SUBJECTS.length; i++) {
        if(json.SUBJECTS[i].alias === eigenschaft.link.linkPartner) {
          SPARQL +=  translateSubject(json.SUBJECTS[i], shownValues, translated, json, itsSubject.alias + "_");
        }
      }

      SPARQL += "FILTER NOT EXIST { ?" + prefix + itsSubject.alias + " <" + eigenschaft.uri + "> ?" + itsSubject.alias + "_" + eigenschaft.link.linkPartner + " } .\n";
    }

    else {
      SPARQL += "FILTER NOT EXIST { ?" + prefix + itsSubject.alias + " <" + eigenschaft.uri + "> ?" + itsSubject.alias + "_" + eigenschaft.alias + " } .\n";
    }
  }

  if(eigenschaft.operator === "IS_OF") {

    SPARQL += prefix + itsSubject.alias + " ^<" + eigenschaft.uri +  "> " + itsSubject.alias + "_" + eigenschaft.link.linkPartner + " .\n";

    for(var i = 0; i < json.SUBJECTS.length; i++) {
      if(json.SUBJECTS[i].alias === eigenschaft.link.linkPartner) {
        SPARQL +=  translateSubject(json.SUBJECTS[i], shownValues, translated, json, itsSubject.alias + "_");
      }
    }

  }

  if(eigenschaft.operator === "IS_NOT_OF") {

    for(var i = 0; i < json.SUBJECTS.length; i++) {
      if(json.SUBJECTS[i].alias === eigenschaft.link.linkPartner) {
        SPARQL +=  translateSubject(json.SUBJECTS[i], shownValues, translated, json, itsSubject.alias + "_");
      }
    }

    SPARQL += "FILTER NOT EXIST { " + prefix + itsSubject.alias + " ^<" + eigenschaft.uri +  "> " + itsSubject.alias + "_" + eigenschaft.link.linkPartner + " } .\n";
  }

  return SPARQL;
}

/*
 * function to translate Datatype properties. Checks for operator of property
 */
function translateDatatypeProperty (itsSubject, eigenschaft, shownValues, translated, json, prefix) {

  var SPARQL = "";

  if(eigenschaft.operator === "MUST" || eigenschaft.operator === "CAN") {

    if(eigenschaft.operator === "CAN") {
      SPARQL += "OPTIONAL { \n";
    }

    if(typeof eigenschaft.arithmetic.operator != "undefined") {

      SPARQL += "?" + prefix + itsSubject.alias + " <" + eigenschaft.uri + "> ?" + prefix + itsSubject.alias + "_" + eigenschaft.alias + "_temp .\n";
      SPARQL += "BIND (( ?" + prefix + itsSubject.alias + "_" + eigenschaft.alias + "_temp " + eigenschaft.arithmetic.operator + " " + eigenschaft.arithmetic.amount + " ) as ?" + prefix + itsSubject.alias + "_" + eigenschaft.alias + ") .\n";
    }
    else {
      SPARQL += "?" + prefix + itsSubject.alias + " <" + eigenschaft.uri + "> ?" + prefix + itsSubject.alias + "_" + eigenschaft.alias + " .\n";
    }

    if(typeof eigenschaft.compare.operator != "undefined") {

      SPARQL += "FILTER ( ?" + prefix + itsSubject.alias + "_" + eigenschaft.alias + " " + eigenschaft.compare.operator + " " + eigenschaft.compare.amount + " ) .\n";
    }

    if(eigenschaft.operator === "CAN") {
      SPARQL += "}\n";
    }
  }

  if(eigenschaft.operator === "MUST_NOT") {
    SPARQL += "FILTER NOT EXIST { ?" + prefix + itsSubject.alias + " <" + eigenschaft.uri + "> ?" + prefix + itsSubject.alias + "_" + eigenschaft.alias + " } .\n";
  }

  if(eigenschaft.view === true) {
    shownValues[shownValues.length] = prefix + itsSubject.alias + "_" + eigenschaft.alias;
  }

  return SPARQL;
}

/*
 * little helper function to check, if an object obj is present in an array arr
 */
function presentInArray(arr, obj) {

  for(var i=0; i<arr.length; i++) {
    if (arr[i] == obj) return true;
  }

  return false;
}<|endoftext|>