/
meld
executable file
·463 lines (383 loc) · 15.5 KB
/
meld
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
#!/usr/bin/env python3
# Copyright (C) 2002-2006 Stephen Kennedy <stevek@gnome.org>
# Copyright (C) 2009-2014 Kai Willadsen <kai.willadsen@gmail.com>
#
# This program 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.
#
# This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
import locale
import logging
import os
import signal
import subprocess
import sys
from multiprocessing import freeze_support
# On Windows, pythonw.exe (which doesn't display a console window) supplies
# dummy stdout and stderr streams that silently throw away any output. However,
# these streams seem to have issues with flush() so we just redirect stdout and
# stderr to actual dummy files (the equivalent of /dev/null).
# Regarding pythonw.exe stdout, see also http://bugs.python.org/issue706263
# Also cx_Freeze built with Win32GUI base sets sys.stdout to None
# leading to exceptions in print() and freeze_support() that uses flush()
if sys.executable.endswith("pythonw.exe") or sys.stdout is None:
devnull = open(os.devnull, "w")
sys.stdout = sys.stderr = devnull
# Main module hasn't multiprocessing workers, so not imported in subprocesses.
# This allows skipping '__name__ == "main"' guard, but freezed case is special.
freeze_support()
def disable_stdout_buffering():
class Unbuffered:
def __init__(self, file):
self.file = file
def write(self, arg):
self.file.write(arg)
self.file.flush()
def __getattr__(self, attr):
return getattr(self.file, attr)
sys.stdout = Unbuffered(sys.stdout)
def get_meld_dir():
global frozen
if frozen:
return os.path.dirname(sys.executable)
# Support running from an uninstalled version
self_path = os.path.realpath(__file__)
return os.path.abspath(os.path.join(os.path.dirname(self_path), ".."))
frozen = getattr(sys, 'frozen', False)
melddir = get_meld_dir()
uninstalled = False
if os.path.exists(os.path.join(melddir, "meld.doap")):
sys.path[0:0] = [melddir]
uninstalled = True
devel = os.path.exists(os.path.join(melddir, ".git"))
if uninstalled:
# Import system hackery to import conf.py.in without copying it to
# have a .py suffix. This is entirely so that we can run from a git
# checkout without any user intervention.
import importlib.machinery
import importlib.util
loader = importlib.machinery.SourceFileLoader(
'meld.conf', os.path.join(melddir, 'meld/conf.py.in'))
spec = importlib.util.spec_from_loader(loader.name, loader)
mod = importlib.util.module_from_spec(spec)
loader.exec_module(mod)
import meld
meld.conf = mod
sys.modules['meld.conf'] = mod
import meld.conf # noqa: E402
# Silence warnings on non-devel releases (minor version is divisible by 2)
is_stable = not bool(int(meld.conf.__version__.split('.')[1]) % 2)
if is_stable:
import warnings
warnings.simplefilter("ignore")
if uninstalled:
meld.conf.uninstalled()
elif frozen:
meld.conf.frozen()
# TODO: Possibly move to elib.intl
import gettext # noqa: E402, I100
locale_domain = meld.conf.__package__
locale_dir = meld.conf.LOCALEDIR
gettext.bindtextdomain(locale_domain, locale_dir)
try:
locale.setlocale(locale.LC_ALL, '')
except locale.Error as e:
print("Couldn't set the locale: %s; falling back to 'C' locale" % e)
locale.setlocale(locale.LC_ALL, 'C')
gettext.textdomain(locale_domain)
trans = gettext.translation(
locale_domain, localedir=str(locale_dir), fallback=True)
_ = meld.conf._ = trans.gettext
meld.conf.ngettext = trans.ngettext
try:
if os.name == 'nt':
from ctypes import cdll
if frozen:
libintl = cdll['libintl-8']
else:
try:
libintl = cdll.intl
except FileNotFoundError:
libintl = cdll['libintl-8']
libintl.bindtextdomain(locale_domain, str(locale_dir))
libintl.bind_textdomain_codeset(locale_domain, 'UTF-8')
libintl.textdomain(locale_domain)
del libintl
else:
locale.bindtextdomain(locale_domain, str(locale_dir))
locale.bind_textdomain_codeset(locale_domain, 'UTF-8')
locale.textdomain(locale_domain)
except AttributeError as e:
# Python builds linked without libintl (i.e., OSX) don't have
# bindtextdomain(), which causes Gtk.Builder translations to fail.
print(
"Couldn't bind the translation domain. Some translations won't "
"work.\n{}".format(e))
except locale.Error as e:
print(
"Couldn't bind the translation domain. Some translations won't "
"work.\n{}".format(e))
except WindowsError as e:
# Accessing cdll.intl sometimes fails on Windows for unknown reasons.
# Let's just continue, as translations are non-essential.
print(
"Couldn't bind the translation domain. Some translations won't "
"work.\n{}".format(e))
def show_error_and_exit(error_text):
"""
Show error in a robust way: always print to stdout and try to
display gui message via gtk or tkinter (first available).
Empty toplevel window is used as message box parent since
parentless message box cause toolkit and windowing system problems.
This function is both python 2 and python 3 compatible since it is used
to display wrong python version.
"""
print(error_text)
raise_as_last_resort_to_display = False
try:
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
Gtk.MessageDialog(
message_type=Gtk.MessageType.ERROR,
buttons=Gtk.ButtonsType.CLOSE,
text=error_text,
).run()
except Exception:
# tkinter is imported here only to show a UI warning about
# missing dependencies.
try:
from tkinter import Tk
from tkinter.messagebox import showerror
toplevel = Tk(className="Meld")
toplevel.wait_visibility()
showerror("Meld", error_text, parent=toplevel)
except Exception:
# Displaying with tkinter failed too, just exit if not frozen.
# Frozen app may lack console but be able to show exceptions.
raise_as_last_resort_to_display = frozen
if raise_as_last_resort_to_display:
raise Exception(error_text)
sys.exit(1)
def check_requirements():
import importlib
from typing import NamedTuple, Optional
class Requirement(NamedTuple):
name: str
module: Optional[str]
gi_version: Optional[str]
major_version: int
minor_version: int
def check(self):
if self.gi_version:
import gi
gi.require_version(self.module, self.gi_version)
module = 'gi.repository.{}'.format(self.module)
else:
module = self.module
mod = importlib.import_module(module)
if mod.__name__ == 'gi.repository.Gtk':
version = (mod.get_major_version(), mod.get_minor_version())
elif mod.__name__ == 'gi.repository.GLib':
version = (mod.MAJOR_VERSION, mod.MINOR_VERSION)
elif mod.__name__ == 'gi.repository.GtkSource':
# There's no accessors for GtkSource, so we try a 4.0 API
# call and just set the version so it will pass
mod.init()
version = (self.major_version, self.minor_version)
elif mod.__name__ in ('cairo', 'gi', 'sys'):
version = mod.version_info
if version < (self.major_version, self.minor_version):
raise RuntimeError('Unsupported version')
def __str__(self):
return '{} {}.{}'.format(
self.name, self.major_version, self.minor_version)
# These requirements are kept in both `bin/meld` and `meson.build`. If you
# update one, update the other.
requirements = (
Requirement('Python', 'sys', None, 3, 6),
Requirement('Gtk+', 'Gtk', '3.0', 3, 20),
Requirement('GLib', 'GLib', '2.0', 2, 48),
Requirement('GtkSourceView', 'GtkSource', '4', 4, 0),
Requirement('pygobject', 'gi', None, 3, 30),
Requirement('pycairo', 'cairo', None, 1, 15),
)
try:
for r in requirements:
r.check()
except (AttributeError, ImportError, RuntimeError, ValueError):
show_error_and_exit(_('Meld requires %s or higher.') % str(r))
def setup_resources():
from gi.repository import Gio
from gi.repository import GtkSource
resource_filename = meld.conf.APPLICATION_ID + ".gresource"
resource_file = os.path.join(meld.conf.DATADIR, resource_filename)
if not os.path.exists(resource_file) and uninstalled:
subprocess.call(
[
"glib-compile-resources",
"--target={}".format(resource_file),
"--sourcedir=meld/resources",
"--sourcedir=data/icons/hicolor",
"meld/resources/meld.gresource.xml",
],
cwd=melddir
)
try:
resources = Gio.resource_load(resource_file)
Gio.resources_register(resources)
except Exception:
# Allow resources to be missing when running uninstalled
if not uninstalled:
raise
style_path = os.path.join(meld.conf.DATADIR, "styles")
GtkSource.StyleSchemeManager.get_default().append_search_path(style_path)
# Just copy style schemes to the file ending expected by
# GtkSourceView if we're uninstalled and they're missing
if uninstalled:
for style in {'meld-base', 'meld-dark'}:
path = os.path.join(
style_path, '{}.style-scheme.xml'.format(style))
if not os.path.exists(path):
import shutil
shutil.copyfile(path + '.in', path)
def setup_settings():
import meld.conf
schema_path = os.path.join(meld.conf.DATADIR, "org.gnome.meld.gschema.xml")
compiled_schema_path = os.path.join(meld.conf.DATADIR, "gschemas.compiled")
try:
schema_mtime = os.path.getmtime(schema_path)
compiled_mtime = os.path.getmtime(compiled_schema_path)
have_schema = schema_mtime < compiled_mtime
except OSError:
have_schema = False
if uninstalled and not have_schema:
subprocess.call(["glib-compile-schemas", meld.conf.DATADIR],
cwd=melddir)
import meld.settings
meld.settings.create_settings()
def setup_logging():
log = logging.getLogger()
# If we're running uninstalled and from Git, turn up the logging level
if uninstalled and devel:
log.setLevel(logging.INFO)
else:
log.setLevel(logging.CRITICAL)
if sys.platform == 'win32':
from gi.repository import GLib
log_path = os.path.join(GLib.get_user_data_dir(), "meld.log")
handler = logging.FileHandler(log_path)
log.setLevel(logging.INFO)
# Set excepthook so that we get exceptions on Windows
def logging_except_hook(exc_type, exc_instance, tb):
log.error(
'Unhandled exception', exc_info=(exc_type, exc_instance, tb))
sys.excepthook = logging_except_hook
else:
handler = logging.StreamHandler()
formatter = logging.Formatter("%(asctime)s %(levelname)s "
"%(name)s: %(message)s")
handler.setFormatter(formatter)
log.addHandler(handler)
def setup_glib_logging():
from gi.repository import GLib
levels = {
GLib.LogLevelFlags.LEVEL_DEBUG: logging.DEBUG,
GLib.LogLevelFlags.LEVEL_INFO: logging.INFO,
GLib.LogLevelFlags.LEVEL_MESSAGE: logging.INFO,
GLib.LogLevelFlags.LEVEL_WARNING: logging.WARNING,
GLib.LogLevelFlags.LEVEL_ERROR: logging.ERROR,
GLib.LogLevelFlags.LEVEL_CRITICAL: logging.CRITICAL,
}
level_flag = (
GLib.LogLevelFlags.LEVEL_WARNING |
GLib.LogLevelFlags.LEVEL_ERROR |
GLib.LogLevelFlags.LEVEL_CRITICAL
)
log_domain = "Gtk"
log = logging.getLogger(log_domain)
def silence(message):
if "Drawing a gadget with negative dimensions" in message:
return True
if "resource overlay" in message:
return True
return False
# This logging handler is for "old" glib logging using a simple
# syslog-style API.
def log_adapter(domain, level, message, user_data):
if not silence(message):
log.log(levels.get(level, logging.WARNING), message)
try:
GLib.log_set_handler(log_domain, level_flag, log_adapter, None)
except AttributeError:
# Only present in glib 2.46+
pass
# This logging handler is for new glib logging using a structured
# API. Unfortunately, it was added in such a way that the old
# redirection API became a no-op, so we need to hack both of these
# handlers to get it to work.
def structured_log_adapter(level, fields, field_count, user_data):
# Don't even format the message if it will be discarded
py_logging_level = levels.get(level, logging.WARNING)
if log.isEnabledFor(py_logging_level):
# at least glib 2.52 log_writer_format_fields can raise on win32
try:
message = GLib.log_writer_format_fields(level, fields, True)
if not silence(message):
log.log(py_logging_level, message)
except Exception:
GLib.log_writer_standard_streams(level, fields, user_data)
return GLib.LogWriterOutput.HANDLED
try:
GLib.log_set_writer_func(structured_log_adapter, None)
except AttributeError:
# Only present in glib 2.50+
pass
def environment_hacks():
# MSYSTEM is set by git, and confuses our
# msys-packaged version's library search path -
# for frozen build the lib subdirectory is excluded.
# workaround it by adding as first path element.
# This may confuse vc utils run from meld
# but otherwise meld just crash on start, see #267
global frozen
if frozen and "MSYSTEM" in os.environ:
lib_dir = os.path.join(get_meld_dir(), "lib")
os.environ["PATH"] = lib_dir + os.pathsep + os.environ["PATH"]
# We manage cwd ourselves for git operations, and GIT_DIR in particular
# can mess with this when set.
for var in ('GIT_DIR', 'GIT_WORK_TREE'):
try:
del os.environ[var]
except KeyError:
pass
# Force the fontconfig backend for font fallback and metric handling
if sys.platform == 'win32' and 'PANGOCAIRO_BACKEND' not in os.environ:
os.environ['PANGOCAIRO_BACKEND'] = 'fontconfig'
def run_application():
from meld.meldapp import MeldApp
app = MeldApp()
if sys.platform != 'win32':
from gi.repository import GLib
GLib.unix_signal_add(
GLib.PRIORITY_DEFAULT, signal.SIGINT, lambda *args: app.quit())
return app.run(sys.argv)
def main():
environment_hacks()
setup_logging()
disable_stdout_buffering()
check_requirements()
setup_glib_logging()
setup_resources()
setup_settings()
return run_application()
if __name__ == '__main__':
sys.exit(main())