julen / translate forked from egparedes/translate

Toolkit assisting in the localization of software

julen (author)
Sat Nov 22 04:54:00 -0800 2008
commit  e05b7b25a7dc733353b233b66ed4789bc6b78000
tree    2f35d4167f20124a704660e993e241f231ced101
parent  24c466f4605dc7f61b1fc4d02b9a312e1dc81aee
translate / tools / oosetupmerge
100755 679 lines (638 sloc) 31.201 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
#!/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)