~jaap.karssenberg/zim/pyzim-gtk3

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
#!/usr/bin/env python

import os
import sys
import shutil
import subprocess

try:
	import py2exe
except ImportError:
	py2exe = None

from distutils.core import setup
from distutils.command.sdist import sdist as sdist_class
from distutils.command.build import build as build_class
from distutils.command.build_scripts import build_scripts as build_scripts_class
from distutils.command.install import install as install_class
from distutils import cmd
from distutils import dep_util


from zim import __version__, __url__

import msgfmt # also distributed with zim
import makeman # helper script

try:
	version_info = sys.version_info
	assert version_info >= (2, 6)
	assert version_info < (3, 0)
except:
	print >> sys.stderr, 'zim needs python >= 2.6   (but < 3.0)'
	sys.exit(1)


# Get environment parameter for building for maemo
# We don't use auto-detection here because we want to be able to
# cross-compile a maemo package on another platform
build_target = os.environ.get('ZIM_BUILD_TARGET')
assert build_target in (None, 'maemo'), 'Unknown value for ZIM_BUILD_TARGET: %s' % build_target
if build_target == 'maemo':
	print 'Building for Maemo...'


# Some constants

PO_FOLDER = 'translations'
LOCALE_FOLDER = 'locale'


# Helper routines

def collect_packages():
	# Search for python packages below zim/
	packages = []
	for dir, dirs, files in os.walk('zim'):
		if '__init__.py' in files:
			package = '.'.join(dir.split(os.sep))
			packages.append(package)
	#~ print 'Pakages: ', packages
	return packages


def get_mopath(pofile):
	# Function to determine right locale path for a .po file
	lang = os.path.basename(pofile)[:-3] # len('.po') == 3
	modir = os.path.join(LOCALE_FOLDER, lang, 'LC_MESSAGES')
	mofile = os.path.join(modir, 'zim.mo')
	return modir, mofile


def include_file(file):
	# Check to exclude hidden and temp files
	if file.startswith('.'): return False
	else:
		for ext in ('~', '.bak', '.swp', '.pyc'):
			if file.endswith(ext): return False
	return True


def collect_data_files():
	# Search for data files to be installed in share/
	data_files = [
		('share/man/man1', ['man/zim.1']),
		('share/applications', ['xdg/zim.desktop']),
		('share/mime/packages', ['xdg/zim.xml']),
		('share/pixmaps', ['xdg/hicolor/48x48/apps/zim.png']),
		('share/appdata', ['xdg/zim.appdata.xml']),
	]

	# xdg/hicolor -> PREFIX/share/icons/hicolor
	for dir, dirs, files in os.walk('xdg/hicolor'):
		if files:
			target = os.path.join('share', 'icons', dir[4:])
			files = [os.path.join(dir, f) for f in files]
			data_files.append((target, files))

	# mono icons -> PREFIX/share/icons/ubuntu-mono-light | -dark
	for theme in ('ubuntu-mono-light', 'ubuntu-mono-dark'):
		file = os.path.join('icons', theme, 'zim-panel.svg')
		target = os.path.join('share', 'icons', theme, 'apps', '22')
		data_files.append((target, [file]))

	# data -> PREFIX/share/zim
	for dir, dirs, files in os.walk('data'):
		if '.zim' in dirs:
			dirs.remove('.zim')
		target = os.path.join('share', 'zim', dir[5:])
		if files:
			files = filter(include_file, files)
			files = [os.path.join(dir, f) for f in files]
			data_files.append((target, files))

	if build_target == 'maemo':
		# Remove default .desktop files and replace with our set
		prefix = os.path.join('share', 'zim', 'applications')
		for i in reversed(range(len(data_files))):
			if data_files[i][0].startswith(prefix):
				data_files.pop(i)

		files = ['maemo/applications/%s' % f
				for f in os.listdir('maemo/applications') if f.endswith('.desktop')]
		data_files.append((prefix, files))

	# .po files -> PREFIX/share/locale/..
	for pofile in [f for f in os.listdir(PO_FOLDER) if f.endswith('.po')]:
		pofile = os.path.join(PO_FOLDER, pofile)
		modir, mofile = get_mopath(pofile)
		target = os.path.join('share', modir)
		data_files.append((target, [mofile]))

	#~ import pprint
	#~ print 'Data files: '
	#~ pprint.pprint(data_files)
	return data_files


def fix_dist():
	# Try to update version info
	if os.path.exists('.bzr/'):
		print 'updating bzr version-info...'
		os.system('bzr version-info --format python > zim/_version.py')

	# Generate man page
	makeman.make()

	# Add the changelog to the manual
	# print 'copying CHANGELOG.txt -> data/manual/Changelog.txt'
	# shutil.copy('CHANGELOG.txt', 'data/manual/Changelog.txt')

	# Copy the zim icons a couple of times
	# Paths for mimeicons taken from xdg-icon-resource
	# xdg-icon-resource installs:
	# /usr/local/share/icons/hicolor/.../mimetypes/gnome-mime-application-x-zim-notebook.png
	# /usr/local/share/icons/hicolor/.../mimetypes/application-x-zim-notebook.png
	# /usr/local/share/icons/hicolor/.../apps/zim.png

	if os.path.exists('xdg/hicolor'):
		shutil.rmtree('xdg/hicolor')
	os.makedirs('xdg/hicolor/scalable/apps')
	os.makedirs('xdg/hicolor/scalable/mimetypes')
	for name in (
		'apps/zim.svg',
		'mimetypes/gnome-mime-application-x-zim-notebook.svg',
		'mimetypes/application-x-zim-notebook.svg'
	):
		shutil.copy('icons/zim48.svg', 'xdg/hicolor/scalable/' + name)
	for size in ('16', '22', '24', '32', '48'):
		dir = size + 'x' + size
		os.makedirs('xdg/hicolor/%s/apps' % dir)
		os.makedirs('xdg/hicolor/%s/mimetypes' % dir)
		for name in (
			'apps/zim.png',
			'mimetypes/gnome-mime-application-x-zim-notebook.png',
			'mimetypes/application-x-zim-notebook.png'
		):
			shutil.copy('icons/zim%s.png' % size, 'xdg/hicolor/'  + dir + '/' + name)


# Overloaded commands

class zim_sdist_class(sdist_class):
	# Command to build source distribution
	# make sure _version.py gets build and included

	def initialize_options(self):
		sdist_class.initialize_options(self)
		self.force_manifest = 1 # always re-generate MANIFEST

	def run(self):
		fix_dist()
		sdist_class.run(self)


class zim_build_trans_class(cmd.Command):
	# Compile mo files

	description = 'Build translation files'
	user_options = []

	def initialize_options(self):
		pass

	def finalize_options(self):
		pass

	def run(self):
		for pofile in [f for f in os.listdir(PO_FOLDER) if f.endswith('.po')]:
			pofile = os.path.join(PO_FOLDER, pofile)
			modir, mofile = get_mopath(pofile)

			if not os.path.isdir(modir):
				os.makedirs(modir)

			if not os.path.isfile(mofile) or dep_util.newer(pofile, mofile):
				print 'compiling %s' % mofile
				msgfmt.make(pofile, mofile)
			else:
				#~ print 'skipping %s - up to date' % mofile
				pass


class zim_build_scripts_class(build_scripts_class):
	# Adjust bin/zim.py -> bin/zim

	def run(self):
		build_scripts_class.run(self)
		if os.name == 'posix' and not self.dry_run:
			for script in self.scripts:
				if script.endswith('.py'):
					file = os.path.join(self.build_dir, script)
					print 'renaming %s to %s' % (file, file[:-3])
					os.rename(file, file[:-3]) # len('.py') == 3


class zim_build_class(build_class):
	# Generate _version.py etc. and call build_trans as a subcommand
	# Also set PLATFORM in zim/__init__.py
	# And put list of default plugins in zim/plugins/__init__.py

	sub_commands = build_class.sub_commands + [('build_trans', None)]

	def run(self):
		fix_dist()
		build_class.run(self)

		file = os.path.join(self.build_lib, 'zim', '__init__.py')
		print 'Setting PLATFORM in %s' % file
		assert os.path.isfile(file)
		fh = open(file)
		lines = fh.readlines()
		fh.read()

		for i, line in enumerate(lines):
			if line.startswith('PLATFORM = '):
				if build_target is None:
					lines[i] = 'PLATFORM = None\n'
				else:
					lines[i] = 'PLATFORM = "%s"\n' % build_target
				break
		else:
			assert False, 'Missed line for PLATFORM'

		fh = open(file, 'w')
		fh.writelines(lines)
		fh.close()

		## Set default plugins
		plugins = []
		for name in os.listdir('./zim/plugins'):
			if name.startswith('_') or name == 'base':
				continue
			elif '.' in name:
				if name.endswith('.py'):
					name, x = name.rsplit('.', 1)
					plugins.append(name)
				else:
					continue
			else:
				plugins.append(name)
		assert len(plugins) > 20, 'Did not find plugins'


		file = os.path.join(self.build_lib, 'zim', 'plugins', '__init__.py')
		print 'Setting plugin list in %s' % file
		assert os.path.isfile(file)
		fh = open(file)
		lines = fh.readlines()
		fh.read()

		for i, line in enumerate(lines):
			if line.startswith('\t\tplugins = set('):
				lines[i] = '\t\tplugins = set(%r) # DEFAULT PLUGINS COMPILED IN BY SETUP.PY\n' % plugins
				break
		else:
			assert False, 'Missed line for plugin list'

		fh = open(file, 'w')
		fh.writelines(lines)
		fh.close()



class zim_install_class(install_class):

	user_options = install_class.user_options + \
		[('skip-xdg-cmd', None, "don't run XDG update commands (for packaging)")]

	boolean_options = install_class.boolean_options + \
		['skip-xdg-cmd']

	def initialize_options(self):
		install_class.initialize_options(self)
		self.skip_xdg_cmd = 0

	def run(self):
		install_class.run(self)

		if not self.skip_xdg_cmd:
			# Try XDG tools
			mimedir = os.path.join(self.install_data, 'share', 'mime')
			for cmd in (
				('update-desktop-database',),
				('update-mime-database', mimedir),
			):
				print 'Trying: ' + ' '.join(cmd)
				subprocess.call(cmd)



# Distutils parameters, and main function

dependencies = ['gobject', 'gtk', 'xdg']
if version_info == (2, 5):
	dependencies.append('simplejson')

if build_target == 'maemo':
	scripts = ['zim.py', 'maemo/modest-mailto.sh']
else:
	scripts = ['zim.py']

if py2exe:
	py2exeoptions = {
		'windows': [ {
			"script": "zim.py",
			"icon_resources": [(1, "icons/zim.ico")]
				# Windows 16x16, 32x32, and 48x48 icon based on PNG
		} ],
		'zipfile': None,
		'options': {
			"py2exe": {
				"compressed": 1,
				"optimize": 2,
				"ascii": 1,
				"bundle_files": 3,
				"packages": ["encodings", "cairo", "atk", "pangocairo", "zim"],
			}
		}
	}
else:
	py2exeoptions = {}


setup(
	# wire overload commands
	cmdclass = {
		'sdist': zim_sdist_class,
		'build': zim_build_class,
		'build_trans': zim_build_trans_class,
		'build_scripts': zim_build_scripts_class,
		'install': zim_install_class,
	},

	# provide package properties
	name         = 'zim',
	version      = __version__,
	description  = 'Zim desktop wiki',
	author       = 'Jaap Karssenberg',
	author_email = 'jaap.karssenberg@gmail.com',
	license      = 'GPL v2+',
	url          = __url__,
	scripts      = scripts,
	packages     = collect_packages(),
	data_files   = collect_data_files(),
	requires     = dependencies,

	**py2exeoptions
)