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/>.
46 lang
, enc
= locale
.getdefaultlocale()
47 os
.environ
['LANG'] = lang
48 gettext
.bindtextdomain(APP
, DIR
)
49 gettext
.textdomain(APP
)
50 gettext
.install(APP
, DIR
, unicode=True)
52 locale
.setlocale(locale
.LC_ALL
, '')
55 libintl_path
= ctypes
.util
.find_library('intl')
56 if libintl_path
== None:
57 local_intl
= os
.path
.join('gtk', 'bin', 'intl.dll')
58 if os
.path
.exists(local_intl
):
59 libintl_path
= local_intl
60 if libintl_path
== None:
61 raise ImportError('intl.dll library not found')
62 libintl
= ctypes
.cdll
.LoadLibrary(libintl_path
)
63 libintl
.bindtextdomain(APP
, DIR
)
68 log_path
= os
.path
.join(os
.environ
['APPDATA'], 'Gajim')
69 if not os
.path
.exists(log_path
):
70 os
.mkdir(log_path
, 0700)
71 log_file
= os
.path
.join(log_path
, 'gajim.log')
72 fout
= open(log_file
, 'a')
76 warnings
.filterwarnings(action
='ignore')
78 if os
.path
.isdir('gtk'):
79 # Used to create windows installer with GTK included
80 paths
= os
.environ
['PATH']
81 list_
= paths
.split(';')
84 if p
.find('gtk') < 0 and p
.find('GTK') < 0:
86 new_list
.insert(0, 'gtk/lib')
87 new_list
.insert(0, 'gtk/bin')
88 os
.environ
['PATH'] = ';'.join(new_list
)
89 os
.environ
['GTK_BASEPATH'] = 'gtk'
95 from common
import logging_helpers
96 logging_helpers
.init('TERM' in os
.environ
)
99 # gajim.gui or gajim.gtk more appropriate ?
100 log
= logging
.getLogger('gajim.gajim')
103 from common
import i18n
110 shortargs
= 'hqvl:p:c:'
111 longargs
= 'help quiet verbose loglevel= profile= config_path='
112 opts
= getopt
.getopt(sys
.argv
[1:], shortargs
, longargs
.split())[0]
113 except getopt
.error
, msg1
:
115 print 'for help use --help'
118 if o
in ('-h', '--help'):
119 print 'gajim [--help] [--quiet] [--verbose] ' + \
120 '[--loglevel subsystem=level[,subsystem=level[...]]] ' + \
121 '[--profile name] [--config-path]'
123 elif o
in ('-q', '--quiet'):
124 logging_helpers
.set_quiet()
125 elif o
in ('-v', '--verbose'):
126 logging_helpers
.set_verbose()
127 elif o
in ('-p', '--profile'): # gajim --profile name
129 elif o
in ('-l', '--loglevel'):
130 logging_helpers
.set_loglevels(a
)
131 elif o
in ('-c', '--config-path'):
133 return profile_
, config_path_
135 profile
, config_path
= parseOpts()
139 profile
= unicode(profile
, locale
.getpreferredencoding())
141 import common
.configpaths
142 common
.configpaths
.gajimpaths
.init(config_path
)
144 common
.configpaths
.gajimpaths
.init_profile(profile
)
148 class MyStderr(object):
151 def write(self
, text
):
152 fname
= os
.path
.join(common
.configpaths
.gajimpaths
.cache_root
,
153 os
.path
.split(sys
.executable
)[1]+'.log')
154 if self
._file
is None and self
._error
is None:
156 self
._file
= open(fname
, 'a')
157 except Exception, details
:
158 self
._error
= details
159 if self
._file
is not None:
160 self
._file
.write(text
)
163 if self
._file
is not None:
166 sys
.stderr
= MyStderr()
168 # PyGTK2.10+ only throws a warning
169 warnings
.filterwarnings('error', module
='gtk')
173 except Warning, msg2
:
174 if str(msg2
) == 'could not open display':
175 print >> sys
.stderr
, _('Gajim needs X server to run. Quiting...')
177 print >> sys
.stderr
, _('importing PyGTK failed: %s') % str(msg2
)
179 warnings
.resetwarnings()
181 gobject
.set_prgname('gajim')
184 warnings
.filterwarnings(action
='ignore')
188 from common
import exceptions
190 from common
import gajim
191 except exceptions
.DatabaseMalformed
:
192 pritext
= _('Database Error')
193 sectext
= _('The database file (%s) cannot be read. Try to repair it (see '
194 'http://trac.gajim.org/wiki/DatabaseBackup) or remove it (all history '
195 'will be lost).') % common
.logger
.LOG_DB_PATH
197 from common
import dbus_support
198 if dbus_support
.supported
:
199 from music_track_listener
import MusicTrackListener
201 from ctypes
import CDLL
202 from ctypes
.util
import find_library
205 sysname
= platform
.system()
206 if sysname
in ('Linux', 'FreeBSD', 'OpenBSD', 'NetBSD'):
207 libc
= CDLL(find_library('c'))
209 # The constant defined in <linux/prctl.h> which is used to set the name
213 if sysname
== 'Linux':
214 libc
.prctl(PR_SET_NAME
, 'gajim')
215 elif sysname
in ('FreeBSD', 'OpenBSD', 'NetBSD'):
216 libc
.setproctitle('gajim')
218 if gtk
.pygtk_version
< (2, 16, 0):
219 pritext
= _('Gajim needs PyGTK 2.16 or above')
220 sectext
= _('Gajim needs PyGTK 2.16 or above to run. Quiting...')
221 elif gtk
.gtk_version
< (2, 16, 0):
222 pritext
= _('Gajim needs GTK 2.16 or above')
223 sectext
= _('Gajim needs GTK 2.16 or above to run. Quiting...')
225 from common
import check_paths
229 import winsound
# windows-only built-in module for playing wav
230 import win32api
# do NOT remove. we req this module
232 pritext
= _('Gajim needs pywin32 to run')
233 sectext
= _('Please make sure that Pywin32 is installed on your '
234 'system. You can get it at %s') % \
235 'http://sourceforge.net/project/showfiles.php?group_id=78018'
238 dlg
= gtk
.MessageDialog(None,
239 gtk
.DIALOG_DESTROY_WITH_PARENT | gtk
.DIALOG_MODAL
,
240 gtk
.MESSAGE_ERROR
, gtk
.BUTTONS_OK
, message_format
= pritext
)
242 dlg
.format_secondary_text(sectext
)
252 import gtkgui_helpers
254 gajimpaths
= common
.configpaths
.gajimpaths
256 pid_filename
= gajimpaths
['PID_FILE']
257 config_filename
= gajimpaths
['CONFIG_FILE']
265 pf
= open(pid_filename
)
267 # probably file not found
271 pid
= int(pf
.read().strip())
274 traceback
.print_exc()
275 # PID file exists, but something happened trying to read PID
276 # Could be 0.10 style empty PID file, so assume Gajim is running
281 from ctypes
import (windll
, c_ulong
, c_int
, Structure
, c_char
)
282 from ctypes
import (POINTER
, pointer
, sizeof
)
286 class PROCESSENTRY32(Structure
):
288 ('dwSize', c_ulong
, ),
289 ('cntUsage', c_ulong
, ),
290 ('th32ProcessID', c_ulong
, ),
291 ('th32DefaultHeapID', c_ulong
, ),
292 ('th32ModuleID', c_ulong
, ),
293 ('cntThreads', c_ulong
, ),
294 ('th32ParentProcessID', c_ulong
, ),
295 ('pcPriClassBase', c_ulong
, ),
296 ('dwFlags', c_ulong
, ),
297 ('szExeFile', c_char
*512, ),
300 kernel
= windll
.kernel32
301 kernel
.CreateToolhelp32Snapshot
.argtypes
= c_ulong
, c_ulong
,
302 kernel
.CreateToolhelp32Snapshot
.restype
= c_int
303 kernel
.Process32First
.argtypes
= c_int
, POINTER(PROCESSENTRY32
),
304 kernel
.Process32First
.restype
= c_int
305 kernel
.Process32Next
.argtypes
= c_int
, POINTER(PROCESSENTRY32
),
306 kernel
.Process32Next
.restype
= c_int
309 TH32CS_SNAPPROCESS
= 2
310 CreateToolhelp32Snapshot
= kernel
.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS
, 0)
311 assert CreateToolhelp32Snapshot
> 0, 'CreateToolhelp32Snapshot failed'
312 pe32
= PROCESSENTRY32()
313 pe32
.dwSize
= sizeof( PROCESSENTRY32
)
314 f3
= kernel
.Process32First(CreateToolhelp32Snapshot
, pointer(pe32
))
316 if pe32
.th32ProcessID
== pid_
:
317 return pe32
.szExeFile
318 f3
= kernel
.Process32Next(CreateToolhelp32Snapshot
, pointer(pe32
))
320 if get_p(pid
) in ('python.exe', 'gajim.exe'):
324 if not os
.path
.exists('/proc'):
325 return True # no /proc, assume Gajim is running
328 f1
= open('/proc/%d/cmdline'% pid
)
330 if e1
.errno
== errno
.ENOENT
:
331 return False # file/pid does not exist
334 n
= f1
.read().lower()
336 if n
.find('gajim') < 0:
338 return True # Running Gajim found at pid
340 traceback
.print_exc()
342 # If we are here, pidfile exists, but some unexpected error occured.
343 # Assume Gajim is running.
347 pix
= gtkgui_helpers
.get_icon_pixmap('gajim', 48)
348 gtk
.window_set_default_icon(pix
) # set the icon to all newly opened wind
349 pritext
= _('Gajim is already running')
350 sectext
= _('Another instance of Gajim seems to be running\nRun anyway?')
351 dialog
= dialogs
.YesNoDialog(pritext
, sectext
)
353 if dialog
.run() != gtk
.RESPONSE_YES
:
356 # run anyway, delete pid and useless global vars
357 if os
.path
.exists(pid_filename
):
358 os
.remove(pid_filename
)
365 pid_dir
= os
.path
.dirname(pid_filename
)
366 if not os
.path
.exists(pid_dir
):
367 check_paths
.create_path(pid_dir
)
370 f2
= open(pid_filename
, 'w')
371 f2
.write(str(os
.getpid()))
374 dlg
= dialogs
.ErrorDialog(_('Disk Write Error'), str(e2
))
381 # delete pid file on normal exit
382 if os
.path
.exists(pid_filename
):
383 os
.remove(pid_filename
)
384 # Shutdown GUI and save config
385 if hasattr(gajim
.interface
, 'roster') and gajim
.interface
.roster
:
386 gajim
.interface
.roster
.prepare_quit()
389 atexit
.register(on_exit
)
391 from gui_interface
import Interface
393 if __name__
== '__main__':
394 def sigint_cb(num
, stack
):
396 # ^C exits the application normally to delete pid file
397 signal
.signal(signal
.SIGINT
, sigint_cb
)
399 log
.info("Encodings: d:%s, fs:%s, p:%s", sys
.getdefaultencoding(), \
400 sys
.getfilesystemencoding(), locale
.getpreferredencoding())
403 # Session Management support
411 gajim
.interface
.roster
.quit_gtkgui_interface()
412 gnome
.program_init('gajim', gajim
.version
)
413 cli
= gnome
.ui
.master_client()
414 cli
.connect('die', die_cb
)
416 path_to_gajim_script
= gtkgui_helpers
.get_abspath_for_script(
419 if path_to_gajim_script
:
420 argv
= [path_to_gajim_script
]
422 cli
.set_restart_command(argv
)
424 # Fedora systems have a broken gnome-python wrapper for this
426 cli
.set_restart_command(len(argv
), argv
)
428 check_paths
.check_and_possibly_create_paths()
430 interface
= Interface()
435 # This makes Gajim unusable under windows, and threads are used only
436 # for GPG, so not under windows
437 gtk
.gdk
.threads_init()
439 except KeyboardInterrupt:
440 print >> sys
.stderr
, 'KeyboardInterrupt'