[kepi] ability to use subkeys. Fixes #6051
[gajim.git] / src / gajim.py
blob941a37211a32807f9fa9b4aeb425a631e3b3cb60
1 # -*- coding:utf-8 -*-
2 ## src/gajim.py
3 ##
4 ## Copyright (C) 2003-2010 Yann Leboulanger <asterix AT lagaule.org>
5 ## Copyright (C) 2004-2005 Vincent Hanquez <tab AT snarc.org>
6 ## Copyright (C) 2005 Alex Podaras <bigpod AT gmail.com>
7 ## Norman Rasmussen <norman AT rasmussen.co.za>
8 ## Stéphan Kochen <stephan AT kochen.nl>
9 ## Copyright (C) 2005-2006 Dimitur Kirov <dkirov AT gmail.com>
10 ## Alex Mauer <hawke AT hawkesnest.net>
11 ## Copyright (C) 2005-2007 Travis Shirk <travis AT pobox.com>
12 ## Nikos Kouremenos <kourem AT gmail.com>
13 ## Copyright (C) 2006 Junglecow J <junglecow AT gmail.com>
14 ## Stefan Bethge <stefan AT lanpartei.de>
15 ## Copyright (C) 2006-2008 Jean-Marie Traissard <jim AT lapin.org>
16 ## Copyright (C) 2007 Lukas Petrovicky <lukas AT petrovicky.net>
17 ## James Newton <redshodan AT gmail.com>
18 ## Copyright (C) 2007-2008 Brendan Taylor <whateley AT gmail.com>
19 ## Julien Pivotto <roidelapluie AT gmail.com>
20 ## Stephan Erb <steve-e AT h3c.de>
21 ## Copyright (C) 2008 Jonathan Schleifer <js-gajim AT webkeks.org>
23 ## This file is part of Gajim.
25 ## Gajim is free software; you can redistribute it and/or modify
26 ## it under the terms of the GNU General Public License as published
27 ## by the Free Software Foundation; version 3 only.
29 ## Gajim is distributed in the hope that it will be useful,
30 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
31 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
32 ## GNU General Public License for more details.
34 ## You should have received a copy of the GNU General Public License
35 ## along with Gajim. If not, see <http://www.gnu.org/licenses/>.
38 from common import demandimport
39 demandimport.enable()
40 demandimport.ignore += ['gobject._gobject', 'libasyncns', 'i18n',
41 'logging.NullHandler', 'dbus.glib', 'dbus.service',
42 'command_system.implementation.standard', 'OpenSSL.SSL', 'OpenSSL.crypto',
43 'common.sleepy', 'DLFCN', 'dl', 'xml.sax', 'xml.sax.handler']
45 import os
46 import sys
48 if os.name == 'nt':
49 import locale
50 import gettext
51 APP = 'gajim'
52 DIR = '../po'
53 lang, enc = locale.getdefaultlocale()
54 os.environ['LANG'] = lang
55 gettext.bindtextdomain(APP, DIR)
56 gettext.textdomain(APP)
57 gettext.install(APP, DIR, unicode=True)
59 locale.setlocale(locale.LC_ALL, '')
60 import ctypes
61 import ctypes.util
62 libintl_path = ctypes.util.find_library('intl')
63 if libintl_path == None:
64 local_intl = os.path.join('gtk', 'bin', 'intl.dll')
65 if os.path.exists(local_intl):
66 libintl_path = local_intl
67 if libintl_path == None:
68 raise ImportError('intl.dll library not found')
69 libintl = ctypes.cdll.LoadLibrary(libintl_path)
70 libintl.bindtextdomain(APP, DIR)
71 libintl.bind_textdomain_codeset(APP, 'UTF-8')
73 import warnings
75 if os.name == 'nt':
76 log_path = os.path.join(os.environ['APPDATA'], 'Gajim')
77 if not os.path.exists(log_path):
78 os.mkdir(log_path, 0700)
79 log_file = os.path.join(log_path, 'gajim.log')
80 fout = open(log_file, 'a')
81 sys.stdout = fout
82 sys.stderr = fout
84 warnings.filterwarnings(action='ignore')
86 if os.path.isdir('gtk'):
87 # Used to create windows installer with GTK included
88 paths = os.environ['PATH']
89 list_ = paths.split(';')
90 new_list = []
91 for p in list_:
92 if p.find('gtk') < 0 and p.find('GTK') < 0:
93 new_list.append(p)
94 new_list.insert(0, 'gtk/lib')
95 new_list.insert(0, 'gtk/bin')
96 os.environ['PATH'] = ';'.join(new_list)
97 os.environ['GTK_BASEPATH'] = 'gtk'
99 if os.name == 'nt':
100 # needed for docutils
101 sys.path.append('.')
103 from common import logging_helpers
104 logging_helpers.init('TERM' in os.environ)
106 import logging
107 # gajim.gui or gajim.gtk more appropriate ?
108 log = logging.getLogger('gajim.gajim')
110 import getopt
111 from common import i18n
113 def parseOpts():
114 profile_ = ''
115 config_path_ = None
117 try:
118 shortargs = 'hqvl:p:c:'
119 longargs = 'help quiet verbose loglevel= profile= config_path='
120 opts = getopt.getopt(sys.argv[1:], shortargs, longargs.split())[0]
121 except getopt.error, msg1:
122 print msg1
123 print 'for help use --help'
124 sys.exit(2)
125 for o, a in opts:
126 if o in ('-h', '--help'):
127 print 'gajim [--help] [--quiet] [--verbose] ' + \
128 '[--loglevel subsystem=level[,subsystem=level[...]]] ' + \
129 '[--profile name] [--config-path]'
130 sys.exit()
131 elif o in ('-q', '--quiet'):
132 logging_helpers.set_quiet()
133 elif o in ('-v', '--verbose'):
134 logging_helpers.set_verbose()
135 elif o in ('-p', '--profile'): # gajim --profile name
136 profile_ = a
137 elif o in ('-l', '--loglevel'):
138 logging_helpers.set_loglevels(a)
139 elif o in ('-c', '--config-path'):
140 config_path_ = a
141 return profile_, config_path_
143 profile, config_path = parseOpts()
144 del parseOpts
146 import locale
147 profile = unicode(profile, locale.getpreferredencoding())
149 import common.configpaths
150 common.configpaths.gajimpaths.init(config_path)
151 del config_path
152 common.configpaths.gajimpaths.init_profile(profile)
153 del profile
155 if os.name == 'nt':
156 class MyStderr(object):
157 _file = None
158 _error = None
159 def write(self, text):
160 fname = os.path.join(common.configpaths.gajimpaths.cache_root,
161 os.path.split(sys.executable)[1]+'.log')
162 if self._file is None and self._error is None:
163 try:
164 self._file = open(fname, 'a')
165 except Exception, details:
166 self._error = details
167 if self._file is not None:
168 self._file.write(text)
169 self._file.flush()
170 def flush(self):
171 if self._file is not None:
172 self._file.flush()
174 sys.stderr = MyStderr()
176 # PyGTK2.10+ only throws a warning
177 warnings.filterwarnings('error', module='gtk')
178 try:
179 import gobject
180 import gtk
181 except Warning, msg2:
182 if str(msg2) == 'could not open display':
183 print >> sys.stderr, _('Gajim needs X server to run. Quiting...')
184 else:
185 print >> sys.stderr, _('importing PyGTK failed: %s') % str(msg2)
186 sys.exit()
187 warnings.resetwarnings()
189 gobject.set_prgname('gajim')
191 if os.name == 'nt':
192 warnings.filterwarnings(action='ignore')
194 pritext = ''
196 from common import exceptions
197 try:
198 from common import gajim
199 except exceptions.DatabaseMalformed:
200 pritext = _('Database Error')
201 sectext = _('The database file (%s) cannot be read. Try to repair it (see '
202 'http://trac.gajim.org/wiki/DatabaseBackup) or remove it (all history '
203 'will be lost).') % common.logger.LOG_DB_PATH
204 else:
205 from common import dbus_support
206 if dbus_support.supported:
207 from music_track_listener import MusicTrackListener
209 from ctypes import CDLL
210 from ctypes.util import find_library
211 import platform
213 sysname = platform.system()
214 if sysname in ('Linux', 'FreeBSD', 'OpenBSD', 'NetBSD'):
215 libc = CDLL(find_library('c'))
217 # The constant defined in <linux/prctl.h> which is used to set the name
218 # of the process.
219 PR_SET_NAME = 15
221 if sysname == 'Linux':
222 libc.prctl(PR_SET_NAME, 'gajim')
223 elif sysname in ('FreeBSD', 'OpenBSD', 'NetBSD'):
224 libc.setproctitle('gajim')
226 if gtk.pygtk_version < (2, 16, 0):
227 pritext = _('Gajim needs PyGTK 2.16 or above')
228 sectext = _('Gajim needs PyGTK 2.16 or above to run. Quiting...')
229 elif gtk.gtk_version < (2, 16, 0):
230 pritext = _('Gajim needs GTK 2.16 or above')
231 sectext = _('Gajim needs GTK 2.16 or above to run. Quiting...')
233 from common import check_paths
235 if os.name == 'nt':
236 try:
237 import winsound # windows-only built-in module for playing wav
238 import win32api # do NOT remove. we req this module
239 except Exception:
240 pritext = _('Gajim needs pywin32 to run')
241 sectext = _('Please make sure that Pywin32 is installed on your '
242 'system. You can get it at %s') % \
243 'http://sourceforge.net/project/showfiles.php?group_id=78018'
245 if pritext:
246 dlg = gtk.MessageDialog(None,
247 gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_MODAL,
248 gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, message_format = pritext)
250 dlg.format_secondary_text(sectext)
251 dlg.run()
252 dlg.destroy()
253 sys.exit()
255 del pritext
257 import gtkexcepthook
259 import signal
260 import gtkgui_helpers
262 gajimpaths = common.configpaths.gajimpaths
264 pid_filename = gajimpaths['PID_FILE']
265 config_filename = gajimpaths['CONFIG_FILE']
267 import traceback
268 import errno
269 import dialogs
271 def pid_alive():
272 try:
273 pf = open(pid_filename)
274 except IOError:
275 # probably file not found
276 return False
278 try:
279 pid = int(pf.read().strip())
280 pf.close()
281 except Exception:
282 traceback.print_exc()
283 # PID file exists, but something happened trying to read PID
284 # Could be 0.10 style empty PID file, so assume Gajim is running
285 return True
287 if os.name == 'nt':
288 try:
289 from ctypes import (windll, c_ulong, c_int, Structure, c_char)
290 from ctypes import (POINTER, pointer, sizeof)
291 except Exception:
292 return True
294 class PROCESSENTRY32(Structure):
295 _fields_ = [
296 ('dwSize', c_ulong, ),
297 ('cntUsage', c_ulong, ),
298 ('th32ProcessID', c_ulong, ),
299 ('th32DefaultHeapID', c_ulong, ),
300 ('th32ModuleID', c_ulong, ),
301 ('cntThreads', c_ulong, ),
302 ('th32ParentProcessID', c_ulong, ),
303 ('pcPriClassBase', c_ulong, ),
304 ('dwFlags', c_ulong, ),
305 ('szExeFile', c_char*512, ),
308 kernel = windll.kernel32
309 kernel.CreateToolhelp32Snapshot.argtypes = c_ulong, c_ulong,
310 kernel.CreateToolhelp32Snapshot.restype = c_int
311 kernel.Process32First.argtypes = c_int, POINTER(PROCESSENTRY32),
312 kernel.Process32First.restype = c_int
313 kernel.Process32Next.argtypes = c_int, POINTER(PROCESSENTRY32),
314 kernel.Process32Next.restype = c_int
316 def get_p(pid_):
317 TH32CS_SNAPPROCESS = 2
318 CreateToolhelp32Snapshot = kernel.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
319 assert CreateToolhelp32Snapshot > 0, 'CreateToolhelp32Snapshot failed'
320 pe32 = PROCESSENTRY32()
321 pe32.dwSize = sizeof( PROCESSENTRY32 )
322 f3 = kernel.Process32First(CreateToolhelp32Snapshot, pointer(pe32))
323 while f3:
324 if pe32.th32ProcessID == pid_:
325 return pe32.szExeFile
326 f3 = kernel.Process32Next(CreateToolhelp32Snapshot, pointer(pe32))
328 if get_p(pid) in ('python.exe', 'gajim.exe'):
329 return True
330 return False
331 try:
332 if not os.path.exists('/proc'):
333 return True # no /proc, assume Gajim is running
335 try:
336 f1 = open('/proc/%d/cmdline'% pid)
337 except IOError, e1:
338 if e1.errno == errno.ENOENT:
339 return False # file/pid does not exist
340 raise
342 n = f1.read().lower()
343 f1.close()
344 if n.find('gajim') < 0:
345 return False
346 return True # Running Gajim found at pid
347 except Exception:
348 traceback.print_exc()
350 # If we are here, pidfile exists, but some unexpected error occured.
351 # Assume Gajim is running.
352 return True
354 if pid_alive():
355 pix = gtkgui_helpers.get_icon_pixmap('gajim', 48)
356 gtk.window_set_default_icon(pix) # set the icon to all newly opened wind
357 pritext = _('Gajim is already running')
358 sectext = _('Another instance of Gajim seems to be running\nRun anyway?')
359 dialog = dialogs.YesNoDialog(pritext, sectext)
360 dialog.popup()
361 if dialog.run() != gtk.RESPONSE_YES:
362 sys.exit(3)
363 dialog.destroy()
364 # run anyway, delete pid and useless global vars
365 if os.path.exists(pid_filename):
366 os.remove(pid_filename)
367 del pix
368 del pritext
369 del sectext
370 dialog.destroy()
372 # Create .gajim dir
373 pid_dir = os.path.dirname(pid_filename)
374 if not os.path.exists(pid_dir):
375 check_paths.create_path(pid_dir)
376 # Create pid file
377 try:
378 f2 = open(pid_filename, 'w')
379 f2.write(str(os.getpid()))
380 f2.close()
381 except IOError, e2:
382 dlg = dialogs.ErrorDialog(_('Disk Write Error'), str(e2))
383 dlg.run()
384 dlg.destroy()
385 sys.exit()
386 del pid_dir
388 def on_exit():
389 # delete pid file on normal exit
390 if os.path.exists(pid_filename):
391 os.remove(pid_filename)
392 # Shutdown GUI and save config
393 if hasattr(gajim.interface, 'roster') and gajim.interface.roster:
394 gajim.interface.roster.prepare_quit()
396 import atexit
397 atexit.register(on_exit)
399 from gui_interface import Interface
401 if __name__ == '__main__':
402 def sigint_cb(num, stack):
403 sys.exit(5)
404 # ^C exits the application normally to delete pid file
405 signal.signal(signal.SIGINT, sigint_cb)
407 log.info("Encodings: d:%s, fs:%s, p:%s", sys.getdefaultencoding(), \
408 sys.getfilesystemencoding(), locale.getpreferredencoding())
410 if os.name != 'nt':
411 # Session Management support
412 try:
413 import gnome.ui
414 raise ImportError
415 except ImportError:
416 pass
417 else:
418 def die_cb(dummy):
419 gajim.interface.roster.quit_gtkgui_interface()
420 gnome.program_init('gajim', gajim.version)
421 cli = gnome.ui.master_client()
422 cli.connect('die', die_cb)
424 path_to_gajim_script = gtkgui_helpers.get_abspath_for_script(
425 'gajim')
427 if path_to_gajim_script:
428 argv = [path_to_gajim_script]
429 try:
430 cli.set_restart_command(argv)
431 except TypeError:
432 # Fedora systems have a broken gnome-python wrapper for this
433 # function.
434 cli.set_restart_command(len(argv), argv)
436 check_paths.check_and_possibly_create_paths()
438 interface = Interface()
439 interface.run()
441 try:
442 if os.name != 'nt':
443 # This makes Gajim unusable under windows, and threads are used only
444 # for GPG, so not under windows
445 gtk.gdk.threads_init()
446 gtk.main()
447 except KeyboardInterrupt:
448 print >> sys.stderr, 'KeyboardInterrupt'