Meltdown – The Computer Lab Prank

I remember that little prank from the days I was a student. You work on an X terminal, and out of the blue, all the display contents gradually disappear’ Pixel after pixel turns black. But don’t worry – you’ll regain control over your display shortly. shortly.
Everyone can access other X terminal display, and mess with it.

How Does It Work?

This program is a simple one using the GDK library, Gnome’s window management package. Including ‘gdk.h’ will also include:

The Program’s Flow

The main function of the program performs the following steps:
1. Initialize GDK.
2. Create a window whose dimensions are the same as those of the root window.
3. Make the window’s background transparent.
4. Make the window a full-screen window.
5. Add an event handler. to handle Expose events.
The event handler will perform the following steps:
1. Create a list of columns and lengths (number of blackened pixels).
2. Create the Graphics Context for the window.
3. Blacken pixels until all pixels are black.
4. Quit the main loop.

Includes And Structures:

#include <stdio.h>
#include <stdlib.h>  
#include <gdk/gdk.h>

GMainLoop *mainloop;
GList *list;

typedef struct col_and_length_t{
  short col;  // Column number
  short len;  // Number of blackened pixels.
} col_and_length;`

The main function:

int main(int argc, char *argv[]){
  gdk_init(NULL, NULL);
  GdkDisplay *disp=gdk_display_get_default();
  GdkScreen *scr = gdk_display_get_default_screen (disp);
  GdkWindow *root = gdk_screen_get_root_window(scr);
  int rootWidth = gdk_window_get_width(root);
  int rootHeight = gdk_window_get_height(root);
  GdkWindowAttr attr;
  attr.width=rootWidth;
  attr.height=rootHeight;
  attr.x=0;
  attr.y=0;
  attr.window_type = GDK_WINDOW_TOPLEVEL;
  attr.wclass=GDK_INPUT_OUTPUT;

  GdkWindow *newWin=gdk_window_new(root,&attr, GDK_WA_X | GDK_WA_Y);
  gdk_event_handler_set (eventFunc, newWin, NULL);
  GdkRGBA color;
  color.alpha=0;

  gdk_window_set_background_rgba(newWin, &color);
  gdk_window_fullscreen(newWin);
  gdk_event_handler_set (eventFunc, newWin, NULL);
  gdk_window_show(newWin);
  mainloop = g_main_new (TRUE);
  g_main_loop_run (mainloop);
  gdk_display_close(disp);

return 0;
}

The event handler

void start_meltdown(GdkWindow *newWin, int height){
  cairo_t *gc=gdk_cairo_create(newWin);
  cairo_set_line_width(gc,2);
  cairo_set_source_rgb (gc, 0, 0, 0);
  int cell_no,size;
  GList *link;
  col_and_length *link_data;
  size=g_list_length(list);

  while(size>0){
    cell_no=random() % size;
    link = g_list_nth(list,cell_no);
    link_data = (col_and_length *)link->data;
    cairo_move_to(gc, link_data->col, link_data->len);
    cairo_rel_line_to(gc, 0, 1);
    cairo_stroke(gc);
    link_data->len++;
    if (link_data->len >= height){
      list=g_list_remove_link(list, link);
      --size;
    }
  }
  g_main_loop_quit(mainloop);
}

void eventFunc(GdkEvent *evt, gpointer data){
  GdkWindow *newWin = (GdkWindow *)data;
  if (gdk_event_get_event_type(evt) == GDK_EXPOSE && gdk_event_get_window (evt) == newWin){
    int width=gdk_window_get_width(newWin);
    int height=gdk_window_get_height(newWin);
    int i;
    for (i=0; i<width;i++){
      col_and_length *cell=(col_and_length *)calloc(sizeof(col_and_length), 1);
      cell->col=i;
      cell->len=0;
      list = g_list_append(list, cell);
    }
    start_meltdown(newWin,height);
  }

}

Compiling

In linux, compiling a program is easy thanks to the pkg-config command.
Run the following from the command line:

gcc meltdown.c `pkg-config --cflags --libs gdk-3.0` -o meltdown

Now, to run the program type:

./meltdown

Written with StackEdit.

Advertisements

Adding Java Classes to Rhino JavaScript

In the post LibreOffice Javascript, I wrote about Rhino Javascript, which is a Javascript interpreter written in Java. This tool has been developed by Mozilla. With this tool you can instantiate Java classes and to access them via Javascript commands ‘importClass’ and ‘importPackage’.

How to ass classes and packages you can load ?

This is not too hard: the ‘rhino’ command is a shell script. In linux, you can find it using the command:

which rhino

You’ll see the response:

/usr/bin/rhino

Then you can look into the file with a text editor or the ‘more’ command, and see that this is a script that performs a Java class. Jar files and classes that a Java programs uses are found in the environment variable ‘CLASSPATH” or after the directive ‘-classpath’. In this script you’ll find that the class path the content of the variable ‘JAVA_CLASSPATH’.

I decided to add the ‘Tidy’ package. In my computer the path of this package is ‘/usr/share/maven-repo/net/sf/jtidy/jtidy/debian/jtidy-debian.jar’, so the script looks like:

#!/bin/sh

JAVA_CMD=”/usr/bin/java”
JAVA_OPTS=””
JAVA_CLASSPATH=”/usr/share/java/js.jar:/usr/share/java/jline.jar:/usr/share/maven-repo/net/sf/jtidy/jtidy/debian/jtidy-debian.jar
JAVA_MAIN=”org.mozilla.javascript.tools.shell.Main”
export LD_LIBRARY_PATH=/home/amity/myWs
##
## Remove bootclasspath overriding for OpenJDK since
## it now use a mangled version of Rhino (in sun.org.mozilla.rhino package)
##
## References:
## <https://bugs.launchpad.net/ubuntu/+source/openjdk-6/+bug/255149&gt;
## <http://icedtea.classpath.org/bugzilla/show_bug.cgi?id=179&gt;
## <http://www.openoffice.org/issues/show_bug.cgi?id=91641&gt;
##

$JAVA_CMD $JAVA_OPTS -classpath $JAVA_CLASSPATH $JAVA_MAIN “$@”

BTW, in Window, environment variables are enclosed by ‘%’ signes. For example: ‘%JAVA_CLASSPATH%’.

PHP CLI – Command Line Interface

If you have installed PHP, you probably have the PHP CLI as well. CLI allows you to run PHP scripts from the command line, without a browser or the definition of a virtual site. You can use it to define a Cron Job or a scheduled task, without learning PERL or other scripting languages. In linux, all you have to do is to put the following first line in your file:

  #!/usr/bin/php

or

  #!/usr/bin/env  php

if the path to ‘php’ is ‘/usr/bin/php’ or the path to ‘env’ is ‘/usr/bin/env’.

You should make your PHP script executable as well.

Superglobals are still defined, but this time are empty hashes, i.e. $_GET[“anyname”] will hold the value null.

 

LibreOffice – The Kakuro Cell Macro

This macro is to be run from the Calc program.

How does it work?

When the user starts the macro, a dialog is opened:

The user insets values for the upper and lower triangles, and clicks the submit button.

Then the macro draws two triangles in the cell selected. Each triangle is empty or contains a numeric value.

The program uses 3 main components:

  • The spreadsheet document.
  • dialog.
  • The draw-page part of the document, since graphics are not part of the cell contents. So, you would use a draw page to draw shapes.

The Code

This macro will create the dialog, add controls, and execute the dialog. A callback function will be attached to the submit button, and will draw the triangles.

Imports are not included; A link to the relevant data type will replace the import.


 // Define the triangle type in the cell
 enum TriangleType {
   UPPER, LOWER
 }

 public class KakuroCell {
   public XNameContainer m_xDlgModelNameContainer = null; // Allows to access controls by name.
   public XControlContainer m_xDlgContainer = null;       // The dialog contains controls, such as buttons, input fields, etc.
   public XMultiServiceFactory m_xMSFDialogModel = null;
   public XControl m_xDialogControl = null;
   public XTopWindow m_xTopWindow;
   public XComponentContext m_xContext;
   public XModel m_doc;
   public XSpreadsheetDocument m_spreadSheetDoc;
   public XMultiServiceFactory doc_multiServiceFactory;

      private void createDialog(XMultiComponentFactory _xMCF) {
      try {
          Object oDialogModel = _xMCF.createInstanceWithContext("com.sun.star.awt.UnoControlDialogModel", m_xContext);

          // The XMultiServiceFactory of the dialog model is needed to instantiate the controls...
          m_xMSFDialogModel = (XMultiServiceFactory) UnoRuntime.queryInterface(XMultiServiceFactory.class, oDialogModel);

          // The named container is used to insert the created controls into...
          m_xDlgModelNameContainer = (XNameContainer) UnoRuntime.queryInterface(XNameContainer.class, oDialogModel);
          String[] sPropertyNames = new String[] {"Height", "Moveable", "Name","PositionX","PositionY", "Step", "TabIndex","Title","Width"};

          Object[] oObjectValues = new Object[] { new Integer(129), Boolean.TRUE, "KakuroDialog", new Integer(95),new Integer(100), new Integer(1), new Short((short) 0), "Kakuro Cell", new Integer(149)};

          setPropertyValues(sPropertyNames, oObjectValues);

          // create the dialog...
          Object oUnoDialog = _xMCF.createInstanceWithContext("com.sun.star.awt.UnoControlDialog", m_xContext);
          m_xDialogControl = (XControl) UnoRuntime.queryInterface(XControl.class, oUnoDialog);

          // The scope of the control container is public...
          m_xDlgContainer = (XControlContainer) UnoRuntime.queryInterface(XControlContainer.class, oUnoDialog);

          m_xTopWindow = (XTopWindow) UnoRuntime.queryInterface(XTopWindow.class, m_xDlgContainer); 

          // link the dialog and its model...
          XControlModel xControlModel = (XControlModel) UnoRuntime.queryInterface(XControlModel.class, oDialogModel);
          m_xDialogControl.setModel(xControlModel);

      } catch (com.sun.star.uno.Exception exception) {
          exception.printStackTrace(System.out);
      }
     } 

      // Define the dialog at the model - keep in mind to pass the property names in alphabetical order!
      public XMultiComponentFactory m_xMCF;
      public XWindowPeer m_xWindowPeer;     // This will ensure a dialog is opened.

      public void setPropertyValues(String[] PropertyNames, Object[] PropertyValues){
      try{
          XMultiPropertySet xMultiPropertySet = (XMultiPropertySet) UnoRuntime.queryInterface(XMultiPropertySet.class, m_xDlgModelNameContainer);
          xMultiPropertySet.setPropertyValues(PropertyNames, PropertyValues);
      } catch (com.sun.star.uno.Exception ex) {
          ex.printStackTrace(System.out);
      }}

      public void insertSubmitButton(String name, String label, short tabIndex, int posX, int posY, int width, int height){
          try {
              Object oSubmitButton = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlButtonModel");
                String[] sPropertyNames= new String[]{ "BackgroundColor", "DefaultButton", "Height", "Label", "Name",   "PositionX", "PositionY", "PushButtonType", "TabIndex", "Toggle",  "Width"};
                Object [] oObjectValues=new Object[]{ new Integer(0x006e7f50), Boolean.FALSE, new Integer(height), label,  name,   new Integer(posX), new Integer(posY), new Short((short)com.sun.star.awt.PushButtonType.STANDARD_value), new Short(tabIndex), Boolean.TRUE, new Integer(width)};
                XMultiPropertySet xSBModelMPSet = (XMultiPropertySet) UnoRuntime.queryInterface(XMultiPropertySet.class, oSubmitButton);
                xSBModelMPSet.setPropertyValues(sPropertyNames, oObjectValues);
                m_xDlgModelNameContainer.insertByName(name, xSBModelMPSet);
                XControl xButtonControl = m_xDlgContainer.getControl(name);
                XButton  xButton = (XButton) UnoRuntime.queryInterface(XButton.class, xButtonControl);
                xButton.addActionListener(new XActionListener() {

                    @Override
                    public void disposing(EventObject evtObj) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void actionPerformed(com.sun.star.awt.ActionEvent evt) {
                        // TODO Auto-generated method stub
                        try {
                          Object src=evt.Source;
                          XControl xControl=UnoRuntime.queryInterface(XXDialogControl.class, src);
                          Object controlModel=xControl.getModel();
                          XPropertySet ctlPropertySet=UnoRuntime.queryInterface(XPropertySet.class, controlModel);
                          String name=(String)ctlPropertySet.getPropertyValue("Name");
                            if (name.equals("Submit")){
                                ctlPropertySet.setPropertyValue("Enabled", Boolean.FALSE);
                                XControl upperCtl=m_xDlgContainer.getControl("UpperValue");
                                XControlModel upperModel = upperCtl.getModel();
                                XPropertySet upperPropertySet = UnoRuntime.queryInterface(XPropertySet.class, upperModel);
                                XControl lowerCtl=m_xDlgContainer.getControl("LowerValue");
                                XControlModel lowerModel = lowerCtl.getModel();
                                XPropertySet lowerPropertySet = UnoRuntime.queryInterface(XPropertySet.class, lowerModel);
                                String upperText = (String)upperPropertySet.getPropertyValue("Text");
                                String lowerText = (String)lowerPropertySet.getPropertyValue("Text");

                                int upperNumericValue = 0;
                                int lowerNumericValue = 0;
                                try {
                                    upperNumericValue=Integer.parseInt(upperText);
                                } catch (NumberFormatException nfe) {
                                    // Leave the numeric value zero
                                }

                                try {
                                    lowerNumericValue=Integer.parseInt(lowerText);
                                } catch (NumberFormatException nfe) {
                                    // Leave the numeric value zero
                                }

                                draw_cell (upperNumericValue, lowerNumericValue);
                                XDialog xDialog = (XDialog) UnoRuntime.queryInterface(XDialog.class, m_xDialogControl);
                                xDialog.endExecute();
                            }
                        } catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }); 
          } catch (Exception e){
             e.printStackTrace();
          }
      }

       // draw_cell - Get the cell's place and size, and draw the 2 triangles over it.
       public void draw_cell (int upperNumericValue, int lowerNumericValue) throws Exception{
          Object xSelection = m_doc.getCurrentSelection();
          XCellRange xCellRange = UnoRuntime.queryInterface(XCellRange.class, xSelection);
          XCell cell=null;
          try {
            cell=xCellRange.getCellByPosition(0, 0);
          } catch (IndexOutOfBoundsException e) {
            // TODO Auto-generated catch block
            throw new Exception("No cells selected.");
          }
          XCellAddressable xCellAddressable=UnoRuntime.queryInterface(XCellAddressable.class, cell);
          CellAddress cellAddress = xCellAddressable.getCellAddress();
          short sheetIx = cellAddress.Sheet;
          XSpreadsheets sheets = m_spreadSheetDoc.getSheets();
          XIndexAccess xIndexAccess = UnoRuntime.queryInterface(XIndexAccess.class, sheets);
          Object currentSheet = xIndexAccess.getByIndex(sheetIx);

          // Get the draw page properties from the spreadsheet
          XDrawPageSupplier xDrawPageSupplier=UnoRuntime.queryInterface(XDrawPageSupplier.class, currentSheet);
          XDrawPage drawPage = xDrawPageSupplier.getDrawPage();
          doc_multiServiceFactory = UnoRuntime.queryInterface(XMultiServiceFactory.class, m_doc);

          XPropertySet cellPropertySet=UnoRuntime.queryInterface(XPropertySet.class, cell);
          // Get the start point and the size of the cell.
          Point pt=(Point)cellPropertySet.getPropertyValue("Position");
          int ptx = pt.X;
          int pty = pt.Y;
          Size sz=(Size)cellPropertySet.getPropertyValue("Size");
          int width = sz.Width;
          int height = sz.Height;
          drawTriangle (drawPage, cell, ptx, pty, width, height, upperNumericValue, TriangleType.UPPER);
          drawTriangle (drawPage, cell, ptx, pty, width, height, lowerNumericValue, TriangleType.LOWER);
      }

      // Draw the triangle according to its coordinates and type, add its numeric value in it.
      private void drawTriangle(XDrawPage drawPage, XCell cell, int ptx, int pty, int width,
            int height, int numericValue, TriangleType triangleType) {
        // TODO Auto-generated method stub
        try {
            Object shapeObj = doc_multiServiceFactory.createInstance("com.sun.star.drawing.ClosedBezierShape");  // This is the type supported for polygons.
            XShape shape=UnoRuntime.queryInterface(XShape.class, shapeObj);
            Point shapePos=new Point(ptx, pty);
            shape.setPosition(shapePos);
            drawPage.add(shape);
            XPropertySet descriptor=UnoRuntime.queryInterface(XPropertySet.class, shape);
            Point[][] points=new Point[1][3];
            points[0][0]=new Point(ptx, pty);
            points[0][1]=triangleType==TriangleType.LOWER ? 
                    /* Yes */ new Point(ptx, pty + height) :
                    /* No  */ new Point(ptx + width, pty);
            points[0][2]=new Point(ptx+width, pty+height);
            PolygonFlags flags[][] = new PolygonFlags[1][3];
            flags[0][0] = flags[0][1] = flags[0][2] = PolygonFlags.NORMAL;      // All points are normal because the shape contains no curves.
            XText shapetext=UnoRuntime.queryInterface(XText.class, shapeObj);
            PolyPolygonBezierCoords coords=new PolyPolygonBezierCoords();
            coords.Flags = flags;
            coords.Coordinates = points;
            descriptor.setPropertyValue("PolyPolygonBezier", coords);
            String shapeString = numericValue!=0 ? Integer.toString(numericValue) : "";
            shapetext.setString(shapeString);
            XPropertySet textPropertySet = UnoRuntime.queryInterface(XPropertySet.class, shapetext);
            textPropertySet.setPropertyValue("CharHeight", 12.0);
            textPropertySet.setPropertyValue("CharColor", new Integer(0xffffff));
            textPropertySet.setPropertyValue("TextHorizontalAdjust", 
                    triangleType == TriangleType.LOWER ? 
                            /* Yes */ TextHorizontalAdjust.LEFT :
                            /* No  */ TextHorizontalAdjust.RIGHT);
            textPropertySet.setPropertyValue("TextVerticalAdjust", 
                    triangleType == TriangleType.LOWER ?
                            /* Yes */ TextVerticalAdjust.BOTTOM :
                            /* No  */ TextVerticalAdjust.TOP);
            textPropertySet.setPropertyValue("CharHeightComplex", 12.0);
            descriptor.setPropertyValue("Visible", true);
            descriptor.setPropertyValue("FillColor", new Integer(0));
            descriptor.setPropertyValue("Anchor", cell);
        } catch (Exception e){
            e.printStackTrace();
        }

    }

    // More dialog controls:
    public void insertNumericField(String name, String label, short tabIndex, int posX, int posY, int width, int height){
          try {
              Object oNumericField = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlEditModel");
                String[] sPropertyNames= new String[]{ "Height", "Name",   "PositionX", "PositionY", "TabIndex", "Width"};
                Object [] oObjectValues=new Object[]{ new Integer(height), name,   new Integer(posX), new Integer(posY), new Short(tabIndex), new Integer(width)};
                XMultiPropertySet xNFModelMPSet = (XMultiPropertySet) UnoRuntime.queryInterface(XMultiPropertySet.class, oNumericField);
                xNFModelMPSet.setPropertyValues(sPropertyNames, oObjectValues);
                m_xDlgModelNameContainer.insertByName(name, xNFModelMPSet);
          } catch (Exception e){
             e.printStackTrace();
          }
      }

      public void insertTextlabel(String name, String label, short tabIndex, int posX, int posY, int width, int height){
          try {
              Object oTextLabel = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlFixedTextModel");
                String[] sPropertyNames= new String[]{ "Height", "Label", "Name",   "PositionX", "PositionY", "TabIndex", "Width", "WritingMode"};
                Object [] oObjectValues=new Object[]{ new Integer(height), label, name,   new Integer(posX), new Integer(posY), new Short(tabIndex), new Integer(width), new Short(com.sun.star.text.WritingMode2.LR_TB)};
                XMultiPropertySet xFTModelMPSet = (XMultiPropertySet) UnoRuntime.queryInterface(XMultiPropertySet.class, oTextLabel);
                xFTModelMPSet.setPropertyValues(sPropertyNames, oObjectValues);
                m_xDlgModelNameContainer.insertByName(name, xFTModelMPSet);
          } catch (Exception e){
              e.printStackTrace();
          }
      }

      public void insertGroupBox (String id, short tabIndex, int posX, int posY, int width, int height){
          try {
            Object oGroupBox=null;
                oGroupBox = m_xMSFDialogModel.createInstance("com.sun.star.awt.UnoControlGroupBoxModel");
            String sName="FrameControl1";
            String[] sPropertyNames= new String[]{ "Height", "Name",   "PositionX", "PositionY", "Width", "WritingMode"};
            Object [] oObjectValues=new Object[]{ new Integer(height), sName,   new Integer(posX), new Integer(posY), new Integer(width), new Short(com.sun.star.text.WritingMode2.LR_TB)};

            XMultiPropertySet xGBModelMPSet = (XMultiPropertySet) UnoRuntime.queryInterface(XMultiPropertySet.class, oGroupBox);
            xGBModelMPSet.setPropertyValues(sPropertyNames, oObjectValues);
            m_xDlgModelNameContainer.insertByName(sName, xGBModelMPSet);
            XPropertySet xGBPSet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, oGroupBox);
            xGBPSet.setPropertyValue("Label", "Kakuro Values");
          } catch (Exception e){
              e.printStackTrace();               
        }
      }

      public short executeDialog() throws Exception{
          XWindow xWindow = (XWindow) UnoRuntime.queryInterface(XWindow.class, m_xDlgContainer);
          // set the dialog invisible until it is executed
          xWindow.setVisible(false);
          Object oToolkit = m_xMCF.createInstanceWithContext("com.sun.star.awt.Toolkit", m_xContext);
          XToolkit xToolkit = (XToolkit) UnoRuntime.queryInterface(XToolkit.class, oToolkit);
          XWindowPeer xWindowParentPeer = xToolkit.getDesktopWindow();
          m_xDialogControl.createPeer(xToolkit, xWindowParentPeer);
          m_xWindowPeer = m_xDialogControl.getPeer();
          XDialog xDialog = (XDialog) UnoRuntime.queryInterface(XDialog.class, m_xDialogControl);
          XComponent xDialogComponent = (XComponent) UnoRuntime.queryInterface(XComponent.class, m_xDialogControl);     
          // the return value contains information about how the dialog has been closed...
          short nReturnValue = xDialog.execute();
          // free the resources...
          xDialogComponent.dispose();
          //xDialogComponent.dispose();
          return nReturnValue;
      }

      // The entry point: this function will be called, when the user runs the macro.
      public  void start(XScriptContext xScriptContext) throws BootstrapException, Exception{
          m_doc=xScriptContext.getDocument();
          m_spreadSheetDoc = UnoRuntime.queryInterface(XSpreadsheetDocument.class, m_doc);
          if (m_spreadSheetDoc == null)
              throw new Exception("Invalid Document Type. Please call from a Calc document.");
          m_xMCF = xScriptContext.getComponentContext().getServiceManager();
          createDialog(m_xMCF);
          insertGroupBox("abc", (short)0, 16, 20, 112, 80);
          insertTextlabel("Label1", "Upper:", (short)-1, 22, 41, 22, 9);
          insertNumericField("UpperValue", "", (short)1, 55, 40, 56, 12);
          insertTextlabel("Label2", "Lower:", (short)-1, 22, 57, 26, 7);
          insertNumericField("LowerValue", "666", (short)2, 55, 56, 56, 12);
          insertSubmitButton("Submit", "Submit", (short)3, 48, 82, 46, 12);

          executeDialog();
      }

}

The Parcel Descriptor

 <?xml version="1.0" encoding="UTF-8"?>
<parcel language="Java" xmlns:parcel="scripting.dtd">
  <script language="Java">
    <locale lang="en">
      <displayname value="Kakuro Cell"/>
      <description>
        Dialog Excercise
      </description>
    </locale>
    <functionname value="KakuroCell.start"/>
    <logicalname value="KakuroCell.start"/>
    <languagedepprops>
        <prop name="classpath" value="kakuro.jar"/>
    </languagedepprops>
  </script>
</parcel>

LibreOffice – Scripting Your Editor

I think using a spreadsheet document for Sudoku and Kakuro puzzles is great because those documents contain cells where you can place your content: numeric value and text. As you probably know, Kakuro puzzles have squares split by diagonal lines into triangles.

A kakuro puzzle copied to a spreadsheet document

The cells split into triangles are not provided by the office suite and should be crated by the user. The best way to create them is by a macro. The macro can be written in any language that accesses UNO(Universal Network Objects) components. For example: Javascript, Java, BeanShell, Python and Basic.
To learn how to write a HelloWorld script in each language, click here.

Files And Directories

A macro needs an entry point. If your macro is written in Java, it mus have a function with a parameter of type ‘XScriptContext’. The path to function name should be found in a file named ‘parcel-descriptor.xml’. The path includes the package name, the class name, and the function name in the format ‘<pacckage-name>.<class-name>.<function-name>, for example:

“hello.HelloWorld.printHW”.

The parcel-descriptor should also contain the location of the jar file (a zipped directory containing Java classes).

The parcel descriptor is located in ‘<path>/Scripts/java/<Script Dir>/’.

Path may be one of

  • a user path, such as’ ${HOME}/.config/libreoffice/3/user/’ – for a specific user.
  • a LibreOffice path, such as ‘/usr/lib/libreoffice/share/’         – for all LibreOffice users

Example:

The function ‘printHW’ is in the class ‘HelloWorld’ in package hello. The package is stored in “${HOME}/.config/libreoffice/3/user/Scripts/java/HelloWorld1/HelloWorld1.jar”

The file “${HOME}/.config/libreoffice/3/user/Scripts/java/HelloWorld1/parcel-descriptor.xml” will look like:

<parcel language=”Java”>

   <script language=”Java”>

      <locale lang=”en”>

         <displayname value=”HelloWorld1″/>

         <description>Prints “Hello World”.</description>

      </locale>

     <functionname value=”hello.HelloWorld.printHW“/>

     <logicalname value=”HelloWorld.printHW“/>

     <languagedepprops>

        <prop name=”classpath” value=”HelloWorld1.jar“/>

     </languagedepprops>

   </script>

</parcel>

Library Files for the Class Path

Your macro will access classes found in JAR files. Some of the jar files can be found in the Java directory (In my Ubuntu 12.04, it is ‘/usr/share/java’) and some in the ‘libreoffice/program/classes’ (‘/usr/lib/libreoffice/program/classes’).

The files are:

  • ridl.jar – in ‘/usr/share/java’
  • unoil.jar – in (‘/usr/lib/libreoffice/program/classes’
  • unoloader.jar – in ‘/usr/share/java’
  • jurt.jar – in ‘/usr/share/java’
  • juh.jar – in ‘/usr/share/java’

Data Types

There are 4 kinds of data types in UNO:

  • Simple and primitive data types, with equivalents in Java, described here.
  • Structures – objects with public attributes, described here
  • Interfaces containing the functions to be used by the programmer, described here.
  • Services which are everything the module (Draw, Writer, etc) provides to the user, a Spreadsheet cell, for example.

The service implements interfaces and other services. To access the service function, get the relevant interface using  ‘UnoRuntime.queryInterface(InterfaceClass, object)’.

To instantiate (or create a Java object from) a service, use the function ‘createInstance’ of the MultiServiceFactory or MultiComponentFactory.

The next post will describe an example macro in java, The Kakuro Cell macro.