OpenOffice.org is a cross-platform application - which means that a developer may add a macro to a Calc document in Linux and then, when that same document is opened by a Calc user on a Windows PC, the macro will still run.
However, there are differences between the two operating systems that can cause problems for the unaware programmer. This article sheds a little light on one of those differences - the file structure - and shows how a programmer can make a macro aware of its operating system.
Comparing the Windows and Linux File Structures
It's those tiny differences between operating systems that can cause the programmer problems - the file structure being one; and this difference can be understood better by looking at an example - the user's Document folder:
- on a Linux computer the directory will be something like /home/bainm/Documents
- on a Windows computer the directory will be something like C:\Documents
So to sum up the differences:
- Windows uses C: as it's root directory whereas Linux uses / (that's a forward slash)
- as well as the file structures being different, the slashes used are different - Windows uses a back-slash whilst Linux uses a forward-slash
So, a bit of a show stopper then. Well, not really - it's those very differences that enable a programmer to identify which operating system the macro is running on.
Identifying the Operating System from the File Structure
The programmer knows that:
- the root directory for Windows is C:
- the root directory for Linux is /
and so this information can be used in conjunction with the Dir method (which is used to obtain the contents of a directory):
This will return an empty string in Linux but it will contain information in Windows and can, therefore, be used to see which operating system is being used:
Identifying the Operating System from the Environment
As well as examining the file structure itself, the programmer can obtain environmental variables from the system by using the environ method, and from this the operating system can be deduced; for example a Linux system will return values for the following environ calls, but Windows will not:
- environ("TERM")
- environ("SHELL")
and, as before, these can used to determine the operating system:
An Example of an Operating System Aware Macro
A macro that is aware of its operating system can now be written:
The result of running this macro will depend on the operating system being used:
- Linux will return file:///home/bainm/Documents/Shares.ods
- Windows will return file:///C:/Documents/Shares.ods
Conclusion
Understanding the differences between operating systems is important in any cross-platform application; however, using the simple techniques in this article mean that there need be no problems when using an OpenOffice.org macro on Windows or on Linux.
References
Mark Alexander Bain, Learn OpenOffice.org Spreadsheet Macro Programming: OOoBasic and Calc automation (Packt Publishing, 2006)