Guide

From Seeta

Jump to: navigation, search

Contents

[edit] PROGRAMMING OF SOCIALCALC

The programming of SocialCalc has been done in JavaScript. The main sub parts of this programme are as follows.


1. Cell Class: A variable class SocialCalc is declared in the start of the programme. The cell class is an object of this class. The main function of this class is to initialise the properties of the cell values. These include:

i. Coordinates ii. Values Stored iii. Data Type iv. Formula v. Attributes

The various objects in this class include:

i) Cell Properties Class: This class, also an object of SocialCalc, is used to initialize the physical parameters of the cells. These include Cell Value parameters such as Coordinates, Data value, Data Type, Formula, value type, errors, comment, and Physical Parameters such as

    Layout
    Font
    Colour, background colour
    Cell Format
    Non text value format, text value format
    Colour Span, Row Span
    Special properties such as display string, parse info

ii) Table Properties Class: This class is used to initialise the table properties. The main parameters are

     Border style
     Layout Font
     Colour, background colour
     Cell format
     Non text value format, text value format


2. Sheet Class: The main function of loading a new sheet, resetting a sheet, and loading a saved sheet are carried out with the help of this class object. During the loading of a new sheet, the properties are all reset. These properties include Attributes such as last column, last row. Default Layout is called. Sheet Attributes such as height, width Sheet names i.e. Description using blocks Sheet layouts Sheet layout hash Sheet fonts Sheet font hash Sheet colours Sheet colour hash Sheet border styles Sheet border style hash Sheet cell formats


3. Function to Parse Sheet “SocialCalc.ParseSheetSave”: This function is a member function of the Sheet Class. It takes as input parameter, a saved sheet object. The parsing is done using a “for” loop and each line character is parsed till the line length is reached. To break the string into block form parts = line.split(":"); is used. A switch case is used to define the various conditions. The cases possible are:

   Parts[i]	             Case
    Cell	             The next step would be to get assimilate the next cell using the data in the Parts[] array.
    Col	             The coordinates are defined by parts[next]. Also switch is defined for next step: 
                                 “w”=> Column width
                                 “hide” => Column attributes are hidden.
    Row	             Sets the Row attributes. Similar to Col.
    Sheet	             Sheet attributes are set. The various cases are:
                                 "c" => Set Last Column attributes
                                 "r" => Set Last Row attributes
                                 "w" => Set default Column width
                                 "h" => Set default Row width
                                 "tf" => Set default Text format
                                 "ntf" => Set default Non Text format
                                 "layout" => Set default layout
                                 "font" => Set default font
                                 "tvf" => Set default Text value format
                                 "ntvf" => Set default non Text value format
                                 "color" => Set default Colour
                                 "bgcolor" => Set default Background Color
    Name	             Decode name from saved date and convert to Uppercase
    Layout	             Match layout and paint output
    Font	             Sets font and font hash
    Color	             Sets color and color hash
    Border                  Sets border and border hash
    Cell Format             Sets format and format hash
    Value Format	     Decodes value from saved formats and then sets it.


4. Function to Study the String “SocialCalc.CellFromStringParts“: This function takes as input parameter, a sheet, a particular cell and the parts array element. It takes string that has been split by ":" in parts, starting at item j, and fills in cell assuming save format. The next element of the parts array is observed for the switch case. The various cases possible are:

    Parts[t++]	             Case
      “v”                   Text Type
      “t”                   --“--
      “vt”                  --“--
      “vtf”	             --“--
      “vtc”                 --“--
      “e”                   --“--
      “b”                   --“--
      “l”	             Sets Layout
      “f”	             Sets Font
      “c”	             Sets Colour
      “bg”	             Sets Background Colour
      “cf”	             Sets Cell Format
      “ntvf”	             Sets Non Text Value Format
      “tvf”	             Sets Text Value Format
      “colspan”	     Sets Column Span Value
      “rowspan”	     Sets Row Span Value
      “comment”	     Loads comments from saved data


5.Function to Save a Sheet “SocialCalc.CreateSheetSave“: This function creates a text representation of the sheet object data. The input parameters of the function are the sheet objects and the range. The text is accessed row wise and column wise and after converting cell data to strings, it is pushed to save.


6.Function to change cell data to string in order to facilitate saving of a Sheet ”SocialCalc.CellToString”: This function is used to convert the entire cell information into an encoded string form so that it can be saved. The encoding function is called for the relevant information. The data which is converted to a string value include:

       Data Type
       Formula
       Layout
       Font
       Colour
       Background Colour 
       Format
       Text Value Format and non text value format
       Column Span and Row Span 
       Comments


7. Function to Encode Cell data for saving as string “SocialCalc.EncodeCellAttribute“: This function takes as input parameters, the sheet and the coordinates of the cell which is being saved. Each of the above mentioned parameters is saved in the string form and returned to the CellToString function. It returns the cell's attributes in an object, each in the following form of attribname: {def: true/false, val: full-value}


8. Function to Encode Sheet data “SocialCalc.EncodeSheetAttributes”: In a manner similar to the above function, to facilitate saving the entire sheet, encoding of its various attributes is required. This is achieved using this function. It returns the sheet attributes in an object, each in the form of attribname: {def: true/false, val: full-value}


9. Function to decode Cell data “SocialCalc.DecodeCellAttributes”: When the saved sheet is reloaded, the encoded cell attributes need to be decoded and loaded according to their different functions. This function is used for the purpose of decoding the cell attributes. It takes cell attributes in an object, each in the following form: attribname: {def: true/false, val: full-value} and executes sheet commands to make the actual attributes correspond. It returns true if any commands were executed, false otherwise. If a range is provided, the commands are executed on the whole range. After execution, the function checks for any changes in the attributes of the cell and then returns true if performed.


10. Function to decode Sheet data “SocialCalc.DecodeSheetAttributes”: This function works similar to the above function. When a saved sheet is reloaded, the encoded sheet attributes are decoded using this function.


11. Function to execute Sheet commands “SocialCalc.ExecuteSheetCommand”: This function executes commands that modify the sheet data. The input –parameter cmd string may be multiple commands, separated by newlines. In that case only one "step" is put on the undo stack representing all the commands. The commands are in the forms:

        set sheet attributename value (plus lastcol and lastrow)
        set 22 attributename value
        set B attributename value
        set A1 attributename value1 value2...
        set A1:B5 attributename value1 value2...
        erase/copy/cut/paste/fillright/filldown A1:B5 all/formulas/format
        loadclipboard save-encoded-clipboard-data
        clearclipboard
        merge C3:F3
        unmerge C3
        insertcol/insertrow C5
        deletecol/deleterow C5:E7
        name define NAME definition
        name desc NAME description
        name delete NAME
        Using a switch-case, with the cmd variable as the decision variable, each of the command signal cases is examined and the execution steps in each case are defined. 


12. Function to undo Sheet commands “SocialCalc.SheetUndo”: All the sheet operations are undone backwards, starting from the last operation. To achieve this, using a for loop, undo command is called using the following statement:

       sheet.ExecuteSheetCommand(tos.undo[i], false);

This way the sheet commands are undone.


13. Function to redo Sheet commands “SocialCalc.SheetRedo”: To redo the executed operation, which has just been undone, in a manner similar to the above function, a for loop is used. The command used is:

sheet.ExecuteSheetCommand(tos.command[i], false);


14. Function to create Audit String “SocialCalc.CreateAuditString”


15. Function “SocialCalc.GetStyleNum”


16. Function “SocialCalc.GetStyleString”


17. Function to update the formula “SocialCalc.OffsetFormulaCoords”: This function is used to update the formula and change relative cell references by offsets even those to other worksheets so fill, paste and sort work as expected.


18. Function to change cell coordinates with updated formula “SocialCalc.AdjustFormulaCoords“: This function takes as input parameters the current formula, column offset, and row offset. All the cell references to cells starting with columns/rows by offsets are adjusted with respect to the updated formula. This updated formula is returned.


19. Function to recalculate the sheet “SocialCalc.RecalcSheet”: This function is used to recalculate the sheet values and save memory and clear out for name lookup formula evaluation. It saves into memory the recalculations that have been performed.


20. Function to check and recalculate “SocialCalc.CheckAndCalcCell”: This function recalculates one cell after making sure dependencies are calculated too. If circular reference is found, it returns non-null. Circular references are detected by using sheet.checked[coord]:

      null or undefined - not evaluated
      1 - cell is being recursed into -- if get back here => circular reference
      2 - cell was fully recursed into and calculated this recalc cycle

21. The Parse Class: This class is used to describe the variables and functions which are used for parsing through the sheet.

       SocialCalc.Parse = function(str) : Constructor
       SocialCalc.Parse.prototype.NextToken: Returns substring after checking for delimiter positions.
       SocialCalc.Parse.prototype.RestOfString: Returns end of line substring
       SocialCalc.Parse.prototype.RestOfStringNoMove:
       SocialCalc.Parse.prototype.NextLine: Returns pointer to next line.
       SocialCalc.Parse.prototype.EOF: Detects end of file.

22. The UndoStack Class: This class implements the behaviour needed for a normal application's undo/redo stack. New change sequence can be added with PushChange. The type argument is a string that can be used to look upsome general string like "typing" or "setting attribute" for the menu prompts for undo/redo. The "do" steps can be added with AddDo. The non-null, non-undefined arguments are joined together with " " to make a command string to be saved. You add the undo steps as commands for the most recent change with AddUndo. The non-null, non-undefined arguments are joined together with " " to make a command string to be saved. The Undo and Redo functions move the Top of Stack pointer through the changes stack so you can undo and redo. Doing a new PushChange removes all undone items after TOS.


23. The Clipboard Object: This is a single object which stores the clipboard, which is shared by all active sheets. Like the undo stack, it does not persist from one editing session to another. Hence, it is not static.


24. The RenderContext Class: This class is used to render various parameters of the activity. It renders physical properties, constants and default values for cells using the following functions:

      SocialCalc.PrecomputeSheetFontsAndLayouts
      SocialCalc.CalculateCellSkipData
      SocialCalc.CalculateColWidthData
      SocialCalc.InitializeTable
      SocialCalc.RenderSheet
      SocialCalc.RenderRow
      SocialCalc.RenderSpacingRow
      SocialCalc.RenderColHeaders
      SocialCalc.RenderColGroup
      SocialCalc.RenderSizingRow
      SocialCalc.RenderCell 
      SocialCalc.CellInPane
      SocialCalc.CreatePseudoElement 

The rendering assumes fixed column widths, even though SocialCalc allows "auto". There may be issues with "auto" and it is hard to make it work cross-browser with border-collapse, etc. This and the RenderSheet routine are where in the code the specifics of table attributes and column size definitions are set. As the browsers settle down and when we decide if we don't need auto width, we may want to revisit the way the code does this (e.g., use table-layout:fixed).


25. Other Miscellaneous Functions:

      SocialCalc.rcColname: Each column has a characteristic name comprised of characters. This function uses for loops to access that name and returns it.
      SocialCalc.crToCoord: Changes the (c,r) notation to coordinates notation.
      SocialCalc.ParseRange: Decides the parse rabge, by calling the coordinates to (c,r) change function.
      SocialCalc.decodeFromAjax: Used specially for Ajax commands.
      SocialCalc.special_chars: Returns string where &, <, >, " are HTML escaped
      SocialCalc.Lookup: Look up table for values from a list
      SocialCalc.setStyles: Used for css styling of the sheet
      SocialCalc.GetViewportInfo: Returns object with viewport width and height, and scroll offsets
      SocialCalc.AssignID: Optionally assigns an ID with a prefix to the element
      SocialCalc.GetCellContents: Returns the contents (value, formula, constant, etc.) of a cell with appropriate prefix ("'", "=", etc.)
      SocialCalc.FormatValueForDisplay: Returns a string, in HTML, for the contents of a cell. 
      SocialCalc.format_text_for_display: Similar to above function 
      SocialCalc.format_number_for_display: Similar to above function 
      SocialCalc.DetermineValueType: Takes a value and looks for special formatting like $, %, numbers, etc. 
      SocialCalc.default_expand_markup
      SocialCalc.ConvertSaveToOtherFormat: Returns a string converted from the specified format: "scsave", "csv", "tab" (tab delimited)
      SocialCalc.ConvertOtherFormatToSave: Returns a string converted from the specified format: "scsave", "csv", "tab" (tab delimited)
      SocialCalc.SetConvertedCell: Sets the cell cr with a value and type determined from raw value


[edit] Communication between Javascript and Python

XOCOM package: The XOCOM package is a library for running DHTML activities in the sugar development environment. The basic utility of the package is in its ability to help integrate JavaScript codes with Python codes, hence, ensuring a flexible and robust communication between both. This is especially useful in the xo activity development arena because of the common use of Python and the future scope that JavaScript promises.

CODE FOR XOCOM XOCOM PYTHON FILE XOCOM package is built in Python and uses the XPCOM library for support and implementation. It imports its viewing package from Hulahop. The class XOCOM consists of the following functions:

1. Constructor: This function “def __init__(self, uri=None)” gets the URI of the file and grants it full or partial access to XPCOM as required by the application. By default it grants full access.

2. Access Function: This function “def give_full_xpcom_access(self)” helps in accessing XPCOM. This function decides its preference class as typical to xpcom programming and then, using the components.interface command, it gains the required services. Also, in the same function, the character and Boolean preferences of the file characters are set.

3. Web View Function: This function “def create_webview(self)” uses a wrapper method to create a new webview embedded browser component. It uses hulahop's WebView. It assumes that you'll want to serve web/index.html relative to your activity directory.

4. Browser Function: This function, “def send_to_browser(self, command, parameter=None)” is the most important part of the browser communication. It uses an xo.js JavaScript file and issues a callback to it using XPCOM. The command will execute a JavaScript method registered with the same name and return any value received from the JavaScript. During the execution of this function an Instance class of a Mutable array is defined. This array is used to save any parameters that JavaScript returns. The parameters are then passed to the JS file. If an event occurs, the Observer class is used to send data to the JS Observer. Finally, the Mutable array is checked to see if the JS observer had returned any parameters. The result is then printed.


[edit] XOCOM JAVASCRIPT FILE

The XOCom Javascript Source creates a global XO object that communicates with the python XPCom code running this activity. The HTML file should register several callbacks with the XO object to handle requests from the activity. For example, as in the case of a simple Read-Write Activity, a handler for the activity read_file and write_file must be written in the HTML file.

<script type="text/javascript">
     XO.register('read', function(content) {
         // Your code to consume the supplied content
     }
    XO.register('write', function() {
         // Your code to return the content to save
          return 'monkey'
      })
 </script>

The JavaScript file needs access to use the XPCom functions from the Python file. To obtain that, a "UniversalXPConnect" object is declared and the XPCom objects are unwrapped to get at the data passed to us. Next the JavaScript file declares its own Mutable Array and preference class. While executing the registered callbacks, these objects are used to wrap the return object into an XPCom object. A try-catch statement is used to registers the XO observer to receive commands from the python XPCom code.

[edit] USING XOCOM IN ACTIVITY

While XOCOM has been used in SocialCalc merely to declare the browser elements and to send data to this browser, a more comprehensive way of using xocom is in the form of toolbars. Every activity has a toolbar.py Python file which houses a class holding all data related to the toolbar. This class is simply included in the main activity function. A One Page Wiki Activity has been executed with toolbars using the XOCOM.

1. Toolbar.py File: In this file, the statement from XOCom import XOCom is included to import all the elements of XOCOM. Then in the constructor of the toolbar class, instead of the usual call to a web view, we use the xocom functions to get a webview. This is done using the following commands:

self._activity = activity

       self.set_canvas( xocom.create_webview() )
       self._activity_toolbar = toolbox.get_activity_toolbar()
      

Once the canvas has been set, the toolbar is designed and displayed. A separate view tool bar class is used to define viewing specifications.


2. Activity Python File: In this file the toolbar class is included using

from toolbar import SpreadSheetActivityToolbar, ViewToolbar The XOCOM library is also included. In the main class of the activity, in the constructor, the XOCom object helps us communicate with the browser. This uses web/index.html as the default page to load.

       self.xocom = XOCom()

To load the toolbars

       toolbox = activity.ActivityToolbox(self)
       self.set_toolbox(toolbox)
       toolbox.show()
       self.set_canvas( self.xocom.create_webview() )
       activity_toolbar_ext = SpreadSheetActivityToolbar(toolbox, self.set_canvas, self)

In order to view thee toolbar the view toolbar class is declared

       view_toolbar = ViewToolbar (self.set_canvas)
       self.set_canvas.show()

The write and read commands are declared within separate functions. In each of these functions, the xocom.send_to_browser function of the xocom is used.