#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2003, 2004 Zuza Software Foundation
#
# This file is part of the translate-toolkit
#
# translate is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# translate is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with translate; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""tool for building multilingual openoffice.org setup files"""
try:
from translate.misc import sparse
except ImportError:
import sparse
try:
from translate import __version__
except ImportError:
class __version__:
ver = "standalone"
import sys
import operator
import os
import copy
import datetime
class SetupParser(sparse.SimpleParser):
def __init__(self):
sparse.SimpleParser.__init__(self)
self.defaulttokenlist.extend(';\n')
self.whitespacechars = " \t\r"
self.quotechars = ('"', '{')
self.endquotechars = {'"':'"', '{':'}'}
self.stringescaping = 0
self.sectiontypes = ('ConfigurationItem', 'Custom', 'DataCarrier', 'Directory',
'File', 'Folder', 'FolderItem', 'Function', 'HelpText', 'Installation', 'Module', 'Procedure',
'Profile', 'ProfileItem', 'RegistryItem', 'Shortcut', 'StarRegistry', 'StarRegistryItem')
self.definitions = {}
self.bytype = {}
self.referrals = []
# insert after the given tokennums
self.insertions = {}
for sectiontype in self.sectiontypes:
self.bytype[sectiontype] = {}
def parse(self, contents):
self.tokenize(contents)
self.originaltokens = self.tokens[:]
tokennum = 0
while tokennum < len(self.tokens):
tokennum = self.parsesection(tokennum)
def parsesection(self, tokennum):
sectiontype = self.tokens[tokennum]
if sectiontype not in self.sectiontypes:
print >>sys.stderr, "unknown sectiontype....", sectiontype
if sectiontype not in self.bytype:
self.bytype[sectiontype] = {}
sectionname = self.tokens[tokennum + 1]
section = {}
if sectionname in self.definitions:
print >>sys.stderr, "duplicate", sectionname
self.definitions[sectionname] = section
self.bytype[sectiontype][sectionname] = section
section['type'] = sectiontype
section['tokennums'] = {'start':tokennum}
tokennum += 2
while self.tokens[tokennum] == '\n':
tokennum += 1
while self.tokens[tokennum].lower() != 'end':
varname = self.tokens[tokennum]
if self.tokens[tokennum+1] != '=':
print >>sys.stderr, "expected =...", sectiontype, sectionname, varname
startvardef = tokennum+2
nestlevel = 0
while self.tokens[tokennum] != '\n' or nestlevel > 0:
varpart = self.tokens[tokennum]
if varpart.lower().startswith('gid_'):
self.referrals.append((varpart, tokennum))
if varpart == '(':
nestlevel += 1
elif varpart == ')':
nestlevel -= 1
tokennum += 1
value = "".join(self.tokens[startvardef:tokennum])
if value.endswith(";"): value = value[:-1]
section[varname] = value
section['tokennums'][varname] = startvardef - section['tokennums']['start']
section['tokennums'][varname+" end"] = tokennum - section['tokennums']['start']
tokennum = tokennum + 1
section['tokennums']['end'] = tokennum - section['tokennums']['start']
tokennum += 1
while tokennum < len(self.tokens) and self.tokens[tokennum] == '\n':
tokennum += 1
return tokennum
def rename(self, sectionname, newname):
section = self.definitions[sectionname]
tokennum = section['tokennums']['start']
self.tokens[tokennum+1] = newname
for varpart, tokennum in self.referrals:
if varpart.lower() == sectionname.lower():
self.tokens[tokennum] = newname
def insertforeignsection(self, aftersection, sectionname, section, index, tokenrange):
tokennum = self.getsectionendtokennum(aftersection)
while self.tokens[tokennum+1] == '\n':
tokennum += 1
self.definitions[sectionname] = copy.deepcopy(section)
self.definitions[sectionname]['tokennums']['start'] = tokennum
if tokennum in self.insertions:
self.insertions[tokennum].append((index, tokenrange))
else:
self.insertions[tokennum] = [(index, tokenrange)]
def insertforeignvalue(self, sectionname, index, tokenrange):
tokennum = self.getsectionendtokennum(sectionname) - 1
if self.tokens[tokennum] == "\n":
tokennum -= 1
if tokennum in self.insertions:
self.insertions[tokennum].append((index, tokenrange))
else:
self.insertions[tokennum] = [(index, tokenrange)]
def getsource(self, start=None, end=None):
sourceparts = []
if start is None:
start = 0
if end is None:
end = len(self.tokens)
tokenpos = 0
for tokennum in range(start+1):
tokenpos = self.source.find(self.originaltokens[tokennum], tokenpos)
for tokennum in range(start, end):
originaltoken = self.originaltokens[tokennum]
nexttokenpos = self.source.find(originaltoken, tokenpos)
sourceparts.append(self.source[tokenpos:nexttokenpos])
sourceparts.append(self.tokens[tokennum])
tokenpos = nexttokenpos + len(originaltoken)
if tokennum in self.insertions:
for index, tokenrange in self.insertions[tokennum]:
foreignstart, foreignend = tokenrange
foreignsource = index.getsource(foreignstart, foreignend)
sourceparts.append(foreignsource)
if end == len(self.tokens):
sourceparts.append(self.source[tokenpos:end])
return "".join(sourceparts)
def getfieldvalue(self, sectionname, fieldname, default=None):
section = self.definitions[sectionname]
return section.get(fieldname, default)
def getfieldtokennum(self, sectionname, fieldname):
section = self.definitions[sectionname]
return section['tokennums'][fieldname] + section['tokennums']['start']
def getsectionendtokennum(self, sectionname):
section = self.definitions[sectionname]
return section['tokennums']['end'] + section['tokennums']['start']
def setfieldvalue(self, sectionname, fieldname, fieldvalue):
fieldtokennum = self.getfieldtokennum(sectionname, fieldname)
self.tokens[fieldtokennum] = fieldvalue
def renamefield(self, sectionname, fieldname, newfieldname):
fieldtokennum = self.getfieldtokennum(sectionname, fieldname)
self.tokens[fieldtokennum - 2] = newfieldname
def getsectiontokenrange(self, sectionname):
section = self.definitions[sectionname]
start, end = section['tokennums']['start'], section['tokennums']['end']+1
while self.tokens[start+end] == '\n' and start+end < len(self.tokens)-1:
end += 1
return (start, start+end)
def getfieldtokenrange(self, sectionname, fieldname):
section = self.definitions[sectionname]
sectionstart = section['tokennums']['start']
start, end = section['tokennums'][fieldname]-2, section['tokennums'][fieldname+' end']
while self.tokens[sectionstart+end] == '\n' and sectionstart+end < len(self.tokens)-1:
end += 1
if self.tokens[sectionstart+start-1] == '\n' and start > 0:
start -= 1
if self.tokens[sectionstart+end-1] == '\n':
end -= 1
return (sectionstart+start, sectionstart+end)
def getmoduleentrytokennum(self, modulename, fileentry):
start, end = self.getsectiontokenrange(modulename)
for tokennum in range(start, end):
if self.originaltokens[tokennum] == fileentry:
return tokennum
return None
class SetupIndex(SetupParser):
def __init__(self, filename=None):
SetupParser.__init__(self)
self.manualfiles = []
self.filemodules = {}
self.directorychildren = {}
self.directoryfiles = {}
if filename is not None:
self.readfile(filename)
def readfile(self, filename):
self.filename = filename
# f = codecs.open(self.filename, 'r', encoding='utf8')
f = open(self.filename, 'r')
contents = f.read()
f.close()
self.parse(contents)
def parse(self, contents):
SetupParser.parse(self, contents)
self.languagename = sparse.stringeval(self.getfieldvalue('gid_Dir_Config_Language', 'HostName'))
self.isocode = sparse.stringeval(self.getfieldvalue('gid_Dir_Share_Registry_Res_Lang', 'HostName'))
if self.isocode.find("-") == -1:
self.shortisocode = self.isocode
else:
self.shortisocode = self.isocode[:self.isocode.find("-")]
self.dialingcode = sparse.stringeval(self.getfieldvalue('gid_Installation', 'DefaultLanguage'))
def keymunge(self, keyname):
"""munges a keyname and removes invalid entries"""
return keyname.replace("-", "_")
def islocalizefile(self, filename):
"""returns whether a file is part of localization"""
# handle resource files
if filename.endswith("%s.res" % self.dialingcode):
return True
# handle README and LICENSE files
if filename in [(template % self.dialingcode) for template in \
("README%s", "LICENSE%s", "README%s.html", "LICENSE%s.html")]:
return True
# everything else is normal...
return False
def merge(self, otherindexes):
"""merges this with another index... hmmm ...."""
indexes = [self] + otherindexes
languages = [index.getfieldvalue('gid_Installation', 'Languages') for index in indexes]
languages = [sparse.stringeval(languagevalues).split(",") for languagevalues in languages]
languages = reduce(operator.add, languages)
languages.sort()
languages = ",".join(languages)
# support for Languages is needed in setup2/source/ui/pages/plang.*
self.setfieldvalue('gid_Installation', 'Languages', '"%s"' % languages)
directoriestorename = {}
for index in indexes:
for directory in index.bytype["Directory"]:
hostname = index.getfieldvalue(directory, 'HostName')
hostname = sparse.stringeval(hostname)
if hostname in (index.languagename, index.isocode, index.shortisocode):
directoriestorename[directory] = 1
parentid = index.getfieldvalue(directory, 'ParentID')
if parentid not in index.directorychildren:
index.directorychildren[parentid] = [directory]
else:
index.directorychildren[parentid].append(directory)
# make sure that if a directory is renamed, all its child directories are too...
recursecount = 1
while recursecount:
recursecount = 0
for directory in directoriestorename.keys():
for child in index.directorychildren.get(directory, []):
if not child in directoriestorename:
directoriestorename[child] = 1
recursecount += 1
# make an index of which files go in which directory
for fileentry in index.bytype["File"]:
directory = index.getfieldvalue(fileentry, 'Dir')
if directory not in index.directoryfiles:
index.directoryfiles[directory] = [fileentry]
else:
index.directoryfiles[directory].append(fileentry)
# make an index of which modules files belong to...
for module in index.bytype["Module"]:
filelist = index.getfieldvalue(module, 'Files', None)
if filelist is None:
# not all modules have a file list
continue
filelist = [fileentry.strip() for fileentry in filelist[1:-1].split(",")]
for fileentry in filelist:
if fileentry not in index.filemodules:
index.filemodules[fileentry] = [module]
else:
index.filemodules[fileentry].append(module)
for index in indexes:
suffix = self.keymunge("_" + index.isocode)
for directory in directoriestorename:
if directory.find('_Language') != -1:
newname = directory.replace("_Language", suffix)
elif directory.find('_Lang') != -1:
newname = directory.replace("_Lang", suffix)
elif directory.find('_Isolanguage') != -1:
newname = directory.replace("_Isolanguage", suffix)
else: newname = directory + suffix
index.renamedirectory(directory, newname, suffix)
if index != self:
directorysection = index.definitions[directory]
tokenrange = index.getsectiontokenrange(directory)
self.insertforeignsection(directory, newname, directorysection, index, tokenrange)
if directory in index.directoryfiles:
for fileentry in index.directoryfiles[directory]:
self.addforeignfile(index, fileentry, suffix)
for fileentry in index.bytype["File"]:
filename = sparse.stringeval(index.getfieldvalue(fileentry, 'Name'))
if index.islocalizefile(filename):
index.rename(fileentry, fileentry + suffix)
packedname = sparse.stringeval(index.getfieldvalue(fileentry, "PackedName"))
newpackedname = packedname + suffix
index.setfieldvalue(fileentry, "PackedName", '"%s"' % newpackedname)
if index != self:
self.addforeignfile(index, fileentry, suffix)
for configitem in index.bytype["ConfigurationItem"]:
key = sparse.stringeval(index.getfieldvalue(configitem, 'Key'))
# TODO: when <sequence_languages> is working correctly, remove this code - i#33113
# if configitem == "gid_Configurationitem_Setup_Office_Locales":
# wierdness. the setup program will put in a comma-separated attribute if its all alpha
# but if there's a - it won't, so we need to check for this...
# isocodes = ",".join([eachindex.isocode for eachindex in indexes if eachindex.isocode.isalpha()])
# index.setfieldvalue(configitem, "Value", '"%s"' % isocodes)
if key == index.isocode:
index.rename(configitem, configitem + suffix)
if index != self:
self.addforeignconfigitem(index, configitem, suffix)
for helpitem in index.bytype["HelpText"]:
index.renamefield(helpitem, "Text", "Text(%s)" % index.dialingcode)
if index != self:
self.addforeignhelptext(index, helpitem)
for moduleitem in index.bytype["Module"]:
index.renamefield(moduleitem, "Name", "Name(%s)" % index.dialingcode)
index.renamefield(moduleitem, "Description", "Description(%s)" % index.dialingcode)
if index != self:
self.addforeignmoduletext(index, moduleitem)
def addmanualshortcut(self, shortcutentry, fileentry, iconid, baseentry):
"""Inserts a manual shortcut into the build system"""
shortcutsectionlines = ["FolderItem %s" % shortcutentry]
def addparam(paramname, paramstr):
shortcutsectionlines.append(" %s%s = %s;" % (paramname, " "*(16-len(paramname)), paramstr))
addparam("ModuleID", self.getfieldvalue(baseentry, "ModuleID"))
addparam("Name", '"Change language"')
addparam("FolderID", self.getfieldvalue(baseentry, "FolderID"))
addparam("FileID", fileentry)
addparam("IconFile", fileentry)
addparam("IconID", "%d" % iconid)
addparam("Styles", self.getfieldvalue(baseentry, "Styles"))
shortcutsectionlines.append("End")
shortcutsectionlines.extend(["", "", ""])
shortcutsectionstr = "\r\n".join(shortcutsectionlines)
dummysetup = SetupParser()
dummysetup.parse(shortcutsectionstr)
shortcutentrysection = dummysetup.definitions[shortcutentry]
tokenrange = dummysetup.getsectiontokenrange(shortcutentry)
self.insertforeignsection(baseentry, shortcutentry, shortcutentrysection, dummysetup, tokenrange)
def addtozipfile(self, destdirectory, zipfileentry, filename, filecontents=None):
"""adds a filename to a zip file. filecontents=None means read from file, otherwise create with contents and remove after"""
packedname = sparse.stringeval(self.getfieldvalue(zipfileentry, "PackedName"))
packedpath = os.path.join(destdirectory, packedname)
if filecontents is not None:
open(filename, 'w').write(filecontents)
print "doing zipfile", packedpath, filename
os.system('mv %s %s.zip' % (packedpath, packedpath))
os.system('zip %s.zip %s' % (packedpath, filename))
os.system('mv %s.zip %s' % (packedpath, packedpath))
if filecontents is not None:
os.remove(filename)
fileinfo = os.stat_result(os.stat(packedpath))
filedate = datetime.datetime.fromtimestamp(fileinfo.st_mtime)
self.setfieldvalue(zipfileentry, "Size", "%d" % fileinfo.st_size)
self.setfieldvalue(zipfileentry, "Date", filedate.strftime('"%d%m%Y"'))
self.setfieldvalue(zipfileentry, "Time", filedate.strftime('"%H%M"'))
def readfromzipfile(self, zipfileentry, filename):
"""reads contents of a file from a zip file"""
packedname = sparse.stringeval(self.getfieldvalue(zipfileentry, "PackedName"))
srcdirectory = os.path.dirname(self.filename)
packedpath = os.path.join(srcdirectory, packedname)
return os.popen('unzip -p %s %s' % (packedpath, filename)).read()
def addmanualfile(self, fileentry, filename, packedname, baseentry):
"""Inserts an external file into the build system"""
fileinfo = os.stat_result(os.stat(filename))
filedate = datetime.datetime.fromtimestamp(fileinfo.st_mtime)
direntry = self.getfieldvalue(baseentry, "Dir")
filesectionlines = ["File %s" % fileentry]
def addparam(paramname, paramstr):
filesectionlines.append(" %s%s = %s;" % (paramname, " "*(16-len(paramname)), paramstr))
addparam("Name", '"%s"' % os.path.basename(filename))
addparam("PackedName", '"%s"' % packedname)
addparam("Size", "%d" % fileinfo.st_size)
addparam("Dir", "%s" % direntry)
addparam("Carrier", "gid_DataCarrier")
addparam("UnixRights", ("%o" % fileinfo.st_mode)[-3:])
addparam("Date", filedate.strftime('"%d%m%Y"'))
addparam("Time", filedate.strftime('"%H%M"'))
addparam("Styles", "(PACKED)")
filesectionlines.append("End")
filesectionlines.extend(["", "", ""])
filesectionstr = "\r\n".join(filesectionlines)
dummysetup = SetupParser()
dummysetup.parse(filesectionstr)
fileentrysection = dummysetup.definitions[fileentry]
tokenrange = dummysetup.getsectiontokenrange(fileentry)
self.insertforeignsection(baseentry, fileentry, fileentrysection, dummysetup, tokenrange)
if baseentry in self.filemodules:
for modulename in self.filemodules[baseentry]:
self.addfiletomodule(modulename, fileentry, baseentry)
self.manualfiles.append((filename, packedname))
def addforeignconfigitem(self, index, configitem, suffix):
"""adds the foreign config item and updates the modules list..."""
tokenrange = index.getsectiontokenrange(configitem)
configitemsection = index.definitions[configitem]
# the config item will already have been renamed by the index.renamedirectory
self.insertforeignsection(configitem, configitem + suffix, configitemsection, index, tokenrange)
def addforeignhelptext(self, index, helpitem):
"""adds the foreign helpitem's text to the corresponding item in self"""
# see http://installation.openoffice.org/pics/scpitem_helptext.html
tokenrange = index.getfieldtokenrange(helpitem, "Text")
# the help item field will already have been renamed
self.insertforeignvalue(helpitem, index, tokenrange)
def addforeignmoduletext(self, index, moduleitem):
"""adds the foreign modules's text to the corresponding item in self"""
# the module item fields will already have been renamed, but not in the lookup dicts
tokenrange = index.getfieldtokenrange(moduleitem, "Name")
self.insertforeignvalue(moduleitem, index, tokenrange)
tokenrange = index.getfieldtokenrange(moduleitem, "Description")
self.insertforeignvalue(moduleitem, index, tokenrange)
def addforeignfile(self, index, fileentry, suffix):
"""adds the foreign file entry and updates the modules list..."""
tokenrange = index.getsectiontokenrange(fileentry)
fileentrysection = index.definitions[fileentry]
# the file will already have been renamed by the index.renamedirectory
self.insertforeignsection(fileentry, fileentry + suffix, fileentrysection, index, tokenrange)
if fileentry in self.filemodules:
for modulename in self.filemodules[fileentry]:
self.addfiletomodule(modulename, fileentry + suffix, fileentry)
def addfiletomodule(self, modulename, fileentry, afterfileentry):
"""adds the given fileentry to module modulename using the definition from the index"""
tokennum = self.getmoduleentrytokennum(modulename, afterfileentry)
dummysetuplines = ["Module %s" % modulename, " Files = (dummy, %s);" % fileentry, "End", ""]
dummyparser = SetupParser()
dummyparser.parse("\r\n".join(dummysetuplines))
dummytokennum = dummyparser.getmoduleentrytokennum(modulename, fileentry)
insertion = (dummyparser, (dummytokennum - 1, dummytokennum + 1))
if tokennum not in self.insertions:
self.insertions[tokennum] = [insertion]
else:
self.insertions[tokennum].append(insertion)
def renamedirectory(self, directory, newname, suffix):
self.rename(directory, newname)
if directory in self.directorychildren:
for child in self.directorychildren[directory]:
self.renamedirectory(child, child + suffix, suffix)
if directory in self.directoryfiles:
for fileentry in self.directoryfiles[directory]:
self.rename(fileentry, fileentry + suffix)
packedname = sparse.stringeval(self.getfieldvalue(fileentry, "PackedName", '""'))
if packedname:
self.setfieldvalue(fileentry, "PackedName", '"%s"' % (packedname+suffix))
def makepackedname(self, prefix, offset=1):
"""finds a new packedname starting with prefix in the sequence"""
packednames = [self.getfieldvalue(fileentry, "PackedName", '""') for fileentry in self.bytype['File']]
packednames = map(sparse.stringeval, packednames)
packednames = [packedname.replace(prefix,"",1) for packedname in packednames if packedname.startswith(prefix)]
packednums = [filter(str.isdigit, packedname) for packedname in packednames]
formatstring = '%s%0' + str(max(map(len, packednums))) + 'd'
packednums = map(int, packednums)
return formatstring % (prefix, max(packednums)+offset)
def copyfiles(self, srcdirectory, destdirectory, onlychanged=0):
"""copy all the [changed] files listed in this setup file from srcdirectory to destdirectory"""
for fileentry in self.bytype['File']:
fileentrysection = self.definitions[fileentry]
if 'PackedName' not in fileentrysection: continue
packedtokennum = self.getfieldtokennum(fileentry, "PackedName")
originalpackedname = sparse.stringeval(self.originaltokens[packedtokennum])
packedname = sparse.stringeval(self.tokens[packedtokennum])
if not onlychanged or packedname != originalpackedname:
srcfile = os.path.join(srcdirectory, originalpackedname)
destfile = os.path.join(destdirectory, packedname)
if packedname != originalpackedname:
print '%s -> %s' % (srcfile, destfile)
os.system('cp -p %s %s' % (srcfile, destfile))
for filename, packedname in self.manualfiles:
packedpath = os.path.join(destdirectory, packedname)
os.system('zip -j %s.zip %s' % (packedpath, filename))
os.system('mv %s.zip %s' % (packedpath, packedpath))
def adddesktopentries(self, desktopentries, outputdir):
"""add desktop (menu) entries and icons for KDE and Gnome"""
# add desktop (menu) entries and icons for KDE
# icons require file icons/ooo_languageselector.png
if "gid_File_Extra_Kdeapplnk" in self.definitions:
self.addtozipfile(outputdir, "gid_File_Extra_Kdeapplnk", "languageselector.desktop", desktopentries["kde"])
if "gid_File_Extra_Kdeicons" in self.definitions and os.path.exists("icons/ooo_languageselector.png"):
os.system("for f in hicolor/{16x16,22x22,32x32,48x48} locolor/{16x16,22x22,32x32} ; do mkdir -p share/icons/$f/apps ; convert icons/ooo_languageselector.png -scale `basename $f` share/icons/$f/apps/ooo_languageselector.xpm ; done")
for scale in [16,22,32,48]:
xpmfilename = os.path.join("share", "icons", "hicolor", "%dx%d" % (scale, scale), "apps", "ooo_languageselector.xpm")
self.addtozipfile(outputdir, "gid_File_Extra_Kdeicons", xpmfilename)
for scale in [16,22,32]:
xpmfilename = os.path.join("share", "icons", "locolor", "%dx%d" % (scale, scale), "apps", "ooo_languageselector.xpm")
self.addtozipfile(outputdir, "gid_File_Extra_Kdeicons", xpmfilename)
# add desktop (menu) entries and icons for Gnome and Gnome2
if "gid_File_Extra_Gnome_Apps" in self.definitions:
ordercontents = self.readfromzipfile("gid_File_Extra_Gnome_Apps", ".order")
ordercontents += "languageselector.desktop\n"
self.addtozipfile(outputdir, "gid_File_Extra_Gnome_Apps", "languageselector.desktop", desktopentries["gnome"])
self.addtozipfile(outputdir, "gid_File_Extra_Gnome_Apps", ".order", ordercontents)
if "gid_File_Extra_Gnome_Icons" in self.definitions and os.path.exists("icons/ooo_languageselector.png"):
self.addtozipfile(outputdir, "gid_File_Extra_Gnome_Icons", "icons/ooo_languageselector.png")
if "gid_File_Extra_Gnome2_Apps" in self.definitions:
self.addtozipfile(outputdir, "gid_File_Extra_Gnome2_Apps", "ooo645_languageselector.desktop", desktopentries["gnome2"])
setuplaunchscript = """#!/bin/bash
# this is a script to launch OpenOffice.org setup in the appropriate language
# name it setup-nn where nn is the ISO code for the language
scriptpath=$0
setupdir=`dirname $0`
scriptname=`basename $0`
LANG=${scriptname/setup-/}
LANGUAGE=$LANG
LC_MESSAGES=$LANG
export LANG LANGUAGE LC_MESSAGES
$setupdir/setup
"""
desktopentries = {
"kde" :
"""[Desktop Entry]
Version=0.92
Encoding=UTF-8
MultipleArgs=false
Terminal=0
Icon=ooo_languageselector.xpm
Exec="<progpath_utf8>/program/ooswitchlang"
Type=Application
Name=<productname> Language Selector
Name[en]=<productname> Language Selector
""",
"gnome" :
"""[Desktop Entry]
Version=0.92
Encoding=Legacy-Mixed
Name=<singleproductname> Language Selector
Name[en]=<singleproductname> Language Selector
MultipleArgs=false
Terminal=false
Icon=<progpath>/share/icons/ooo_languageselector.png
Exec=<progpath>/program/ooswitchlang
Type=Application
""",
"gnome2":
"""[Desktop Entry]
Version=1.0
Encoding=UTF-8
Terminal=false
Categories=Application;Office;
Icon=<progpath>/share/icons/ooo_languageselector.png
Exec=<progpath_utf8>/program/ooswitchlang
Type=Application
Name=<productname> Language Selector
StartupNotify=false
Name[en]=<productname> Language Selector
"""
}
if __name__ == '__main__':
try:
import psyco
psyco.full()
except:
pass
import optparse
setupfiles = {}
optparser = optparse.OptionParser(version="%prog "+__version__.ver, description=__doc__)
optparser.set_usage("%prog maindir [--switchlangexe ooswitchlang.exe] [otherdirs] outputdir")
optparser.add_option("", "--switchlangexe", dest="switchlangexe", default=None,
help="add SWITCHLANGEXE to program", metavar="SWITCHLANGEXE")
options, args = optparser.parse_args()
if len(args) < 2:
optparser.error("need at least one inputdir and an outputdir")
maindir = args[0]
otherdirs = args[1:-1]
outputdir = args[-1]
if os.path.isfile(os.path.join(maindir, 'setup.ins')):
setupname = 'setup.ins'
elif os.path.isfile(os.path.join(maindir, 'setup.inf')):
setupname = 'setup.inf'
else:
print >>sys.stderr, "could not find setup.ins or setup.inf in main input directory %s" % maindir
sys.exit()
mainsetupfile = SetupIndex(os.path.join(maindir, setupname))
othersetupfiles = []
for otherdir in otherdirs:
othersetupfiles.append(SetupIndex(os.path.join(otherdir, setupname)))
mainsetupfile.merge(othersetupfiles)
if options.switchlangexe is not None:
packedname = mainsetupfile.makepackedname("f_")
mainsetupfile.addmanualfile("gid_File_Bin_Switchlang", options.switchlangexe, packedname, "gid_File_Bin_Setofficelang")
if "gid_Folderitem_Opendocument" in mainsetupfile.definitions:
mainsetupfile.addmanualshortcut("gid_Folderitem_Switchlang", "gid_File_Bin_Switchlang", 0, "gid_Folderitem_Opendocument")
if not os.path.isdir(outputdir):
os.mkdir(outputdir)
mainsetupfile.copyfiles(maindir, outputdir)
if options.switchlangexe is not None:
mainsetupfile.adddesktopentries(desktopentries, outputdir)
open(os.path.join(outputdir, setupname), 'w').write(mainsetupfile.getsource())
for dirnum in range(len(otherdirs)):
otherdir = otherdirs[dirnum]
othersetupfile = othersetupfiles[dirnum]
othersetupfile.copyfiles(otherdir, outputdir, 1)
# copy other unmodified files
for filename in os.listdir(maindir):
checkname = filename.lower()
if checkname.startswith('f') or checkname == setupname:
continue
srcfile = os.path.join(maindir, filename)
destfile = os.path.join(outputdir, filename)
print '%s -> %s' % (srcfile, destfile)
os.system('cp -p %s %s' % (srcfile, destfile))
# also copy the following files to language-specific names
if checkname.startswith("readme") or checkname.startswith("license") or checkname.endswith("html"):
extpos = filename.rfind(os.extsep)
if extpos == -1:
destname = filename + "-" + mainsetupfile.isocode
else:
destname = filename[:extpos] + "-" + mainsetupfile.isocode + filename[extpos:]
destfile = os.path.join(outputdir, destname)
print '%s -> %s' % (srcfile, destfile)
os.system('cp -p %s %s' % (srcfile, destfile))
for dirnum in range(len(otherdirs)):
otherdir = otherdirs[dirnum]
setupfile = othersetupfiles[dirnum]
for filename in os.listdir(otherdir):
checkname = filename.lower()
if checkname.startswith('f') or checkname == setupname:
continue
# we want readmes in every language...
if checkname.startswith("readme") or checkname.startswith("license") or checkname.endswith("html"):
srcfile = os.path.join(otherdir, filename)
extpos = filename.rfind(os.extsep)
if extpos == -1:
destname = filename + "-" + setupfile.isocode
else:
destname = filename[:extpos] + "-" + setupfile.isocode + filename[extpos:]
destfile = os.path.join(outputdir, destname)
print '%s -> %s' % (srcfile, destfile)
os.system('cp -p %s %s' % (srcfile, destfile))
# on posix, create setup-lang scripts
if os.path.exists(os.path.join(outputdir, "setup")):
for setupfile in [mainsetupfile] + othersetupfiles:
destfile = os.path.join(outputdir, "setup-%s" % setupfile.isocode)
open(destfile, 'w').write(setuplaunchscript)
os.system('chmod a+x %s' % destfile)