Skip to content
Snippets Groups Projects
gajim.py 131 KiB
Newer Older
3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646
			bus = dbus.SessionBus()
			if not 'com.google.code.Awn' in bus.list_names():
				# Awn is not installed
				return
		except Exception:
			return
		iconset = gajim.config.get('iconset')
		prefix = os.path.join(helpers.get_iconset_path(iconset), '32x32')
		if status in ('chat', 'away', 'xa', 'dnd', 'invisible', 'offline'):
			status = status + '.png'
		elif status == 'online':
			prefix = os.path.join(gajim.DATA_DIR, 'pixmaps')
			status = 'gajim.png'
		path = os.path.join(prefix, status)
		try:
			obj = bus.get_object('com.google.code.Awn', '/com/google/code/Awn')
			awn = dbus.Interface(obj, 'com.google.code.Awn')
			awn.SetTaskIconByName('Gajim', os.path.abspath(path))
		except Exception:
			pass

	def enable_music_listener(self):
		listener = MusicTrackListener.get()
		if not self.music_track_changed_signal:
			self.music_track_changed_signal = listener.connect(
				'music-track-changed', self.music_track_changed)
		track = listener.get_playing_track()
		self.music_track_changed(listener, track)

	def disable_music_listener(self):
		listener = MusicTrackListener.get()
		listener.disconnect(self.music_track_changed_signal)
		self.music_track_changed_signal = None

	def music_track_changed(self, unused_listener, music_track_info, account=''):
		if account == '':
			accounts = gajim.connections.keys()
		else:
			accounts = [account]
		if music_track_info is None:
			artist = ''
			title = ''
			source = ''
		elif hasattr(music_track_info, 'paused') and music_track_info.paused == 0:
			artist = ''
			title = ''
			source = ''
		else:
			artist = music_track_info.artist
			title = music_track_info.title
			source = music_track_info.album
		for acct in accounts:
			if acct not in gajim.connections:
				continue
			if not gajim.account_is_connected(acct):
				continue
			if not gajim.connections[acct].pep_supported:
				continue
			if gajim.connections[acct].music_track_info == music_track_info:
				continue
			pep.user_send_tune(acct, artist, title, source)
			gajim.connections[acct].music_track_info = music_track_info

	def get_bg_fg_colors(self):
		def gdkcolor_to_rgb (gdkcolor):
			return [c / 65535. for c in (gdkcolor.red, gdkcolor.green,
				gdkcolor.blue)]

		def format_rgb (r, g, b):
			return ' '.join([str(c) for c in ('rgb', r, g, b)])

		def format_gdkcolor (gdkcolor):
			return format_rgb (*gdkcolor_to_rgb (gdkcolor))
		
		# get style colors and create string for dvipng
		dummy = gtk.Invisible()
		dummy.ensure_style()
		style = dummy.get_style()
		bg_str = format_gdkcolor(style.base[gtk.STATE_NORMAL])
		fg_str = format_gdkcolor(style.text[gtk.STATE_NORMAL])
		return (bg_str, fg_str)

	def read_sleepy(self):
		'''Check idle status and change that status if needed'''
		if not self.sleeper.poll():
			# idle detection is not supported in that OS
			return False # stop looping in vain
		state = self.sleeper.getState()
		for account in gajim.connections:
			if account not in gajim.sleeper_state or \
			not gajim.sleeper_state[account]:
				continue
			if state == common.sleepy.STATE_AWAKE and \
			gajim.sleeper_state[account] in ('autoaway', 'autoxa'):
				# we go online
				self.roster.send_status(account, 'online',
					gajim.status_before_autoaway[account])
				gajim.status_before_autoaway[account] = ''
				gajim.sleeper_state[account] = 'online'
			elif state == common.sleepy.STATE_AWAY and \
			gajim.sleeper_state[account] == 'online' and \
			gajim.config.get('autoaway'):
				# we save out online status
				gajim.status_before_autoaway[account] = \
					gajim.connections[account].status
				# we go away (no auto status) [we pass True to auto param]
				auto_message = gajim.config.get('autoaway_message')
				if not auto_message:
					auto_message = gajim.connections[account].status
				else:
					auto_message = auto_message.replace('$S','%(status)s')
					auto_message = auto_message.replace('$T','%(time)s')
					auto_message = auto_message % {
						'status': gajim.status_before_autoaway[account],
						'time': gajim.config.get('autoawaytime')
						}
				self.roster.send_status(account, 'away', auto_message, auto=True)
				gajim.sleeper_state[account] = 'autoaway'
			elif state == common.sleepy.STATE_XA and \
			gajim.sleeper_state[account] in ('online', 'autoaway',
			'autoaway-forced') and gajim.config.get('autoxa'):
				# we go extended away [we pass True to auto param]
				auto_message = gajim.config.get('autoxa_message')
				if not auto_message:
					auto_message = gajim.connections[account].status
				else:
					auto_message = auto_message.replace('$S','%(status)s')
					auto_message = auto_message.replace('$T','%(time)s')
					auto_message = auto_message % {
						'status': gajim.status_before_autoaway[account],
						'time': gajim.config.get('autoxatime')
						}
				self.roster.send_status(account, 'xa', auto_message, auto=True)
				gajim.sleeper_state[account] = 'autoxa'
		return True # renew timeout (loop for ever)

	def autoconnect(self):
		'''auto connect at startup'''
		# dict of account that want to connect sorted by status
		shows = {}
		for a in gajim.connections:
			if gajim.config.get_per('accounts', a, 'autoconnect'):
				if gajim.config.get_per('accounts', a, 'restore_last_status'):
					self.roster.send_status(a, gajim.config.get_per('accounts', a,
						'last_status'), helpers.from_one_line(gajim.config.get_per(
						'accounts', a, 'last_status_msg')))
					continue
				show = gajim.config.get_per('accounts', a, 'autoconnect_as')
				if not show in gajim.SHOW_LIST:
					continue
				if not show in shows:
					shows[show] = [a]
				else:
					shows[show].append(a)
		def on_message(message, pep_dict):
			if message is None:
				return
			for a in shows[show]:
				self.roster.send_status(a, show, message)
				self.roster.send_pep(a, pep_dict)
		for show in shows:
			message = self.roster.get_status_message(show, on_message)
		return False

	def show_systray(self):
		self.systray_enabled = True
		self.systray.show_icon()

	def hide_systray(self):
		self.systray_enabled = False
		self.systray.hide_icon()

	def on_launch_browser_mailer(self, widget, url, kind):
		helpers.launch_browser_mailer(kind, url)

	def process_connections(self):
		''' Called each foo (200) miliseconds. Check for idlequeue timeouts.	'''
		try:
			gajim.idlequeue.process()
		except Exception:
			# Otherwise, an exception will stop our loop
			timeout, in_seconds = gajim.idlequeue.PROCESS_TIMEOUT
			if in_seconds:
				gobject.timeout_add_seconds(timeout, self.process_connections)
			else:
				gobject.timeout_add(timeout, self.process_connections)
			raise
		return True # renew timeout (loop for ever)

	def save_config(self):
		err_str = parser.write()
		if err_str is not None:
			print >> sys.stderr, err_str
			# it is good to notify the user
			# in case he or she cannot see the output of the console
			dialogs.ErrorDialog(_('Could not save your settings and preferences'),
				err_str)
			sys.exit()

	def save_avatar_files(self, jid, photo, puny_nick = None, local = False):
		'''Saves an avatar to a separate file, and generate files for dbus notifications. An avatar can be given as a pixmap directly or as an decoded image.'''
		puny_jid = helpers.sanitize_filename(jid)
		path_to_file = os.path.join(gajim.AVATAR_PATH, puny_jid)
		if puny_nick:
			path_to_file = os.path.join(path_to_file, puny_nick)
		# remove old avatars
		for typ in ('jpeg', 'png'):
			if local:
				path_to_original_file = path_to_file + '_local'+  '.' + typ
			else:
				path_to_original_file = path_to_file + '.' + typ
			if os.path.isfile(path_to_original_file):
				os.remove(path_to_original_file)
		if local and photo:
			pixbuf = photo
			typ = 'png'
			extension = '_local.png' # save local avatars as png file
		else:
			pixbuf, typ = gtkgui_helpers.get_pixbuf_from_data(photo, want_type = True)
			if pixbuf is None:
				return
			extension = '.' + typ
			if typ not in ('jpeg', 'png'):
				gajim.log.debug('gtkpixbuf cannot save other than jpeg and png formats. saving %s\'avatar as png file (originaly %s)' % (jid, typ))
				typ = 'png'
				extension = '.png'
		path_to_original_file = path_to_file + extension
		try:
			pixbuf.save(path_to_original_file, typ)
		except Exception, e:
			log.error('Error writing avatar file %s: %s' % (path_to_original_file,
				str(e)))
		# Generate and save the resized, color avatar
		pixbuf = gtkgui_helpers.get_scaled_pixbuf(pixbuf, 'notification')
		if pixbuf:
			path_to_normal_file = path_to_file + '_notif_size_colored' + extension
			try:
				pixbuf.save(path_to_normal_file, 'png')
			except Exception, e:
				log.error('Error writing avatar file %s: %s' % \
					(path_to_original_file, str(e)))
			# Generate and save the resized, black and white avatar
			bwbuf = gtkgui_helpers.get_scaled_pixbuf(
				gtkgui_helpers.make_pixbuf_grayscale(pixbuf), 'notification')
			if bwbuf:
				path_to_bw_file = path_to_file + '_notif_size_bw' + extension
				try:
					bwbuf.save(path_to_bw_file, 'png')
				except Exception, e:
					log.error('Error writing avatar file %s: %s' % \
						(path_to_original_file, str(e)))

	def remove_avatar_files(self, jid, puny_nick = None, local = False):
		'''remove avatar files of a jid'''
		puny_jid = helpers.sanitize_filename(jid)
		path_to_file = os.path.join(gajim.AVATAR_PATH, puny_jid)
		if puny_nick:
			path_to_file = os.path.join(path_to_file, puny_nick)
		for ext in ('.jpeg', '.png'):
			if local:
				ext = '_local' + ext
			path_to_original_file = path_to_file + ext
			if os.path.isfile(path_to_file + ext):
				os.remove(path_to_file + ext)
			if os.path.isfile(path_to_file + '_notif_size_colored' + ext):
				os.remove(path_to_file + '_notif_size_colored' + ext)
			if os.path.isfile(path_to_file + '_notif_size_bw' + ext):
				os.remove(path_to_file + '_notif_size_bw' + ext)

	def auto_join_bookmarks(self, account):
		'''autojoin bookmarked GCs that have 'auto join' on for this account'''
		for bm in gajim.connections[account].bookmarks:
			if bm['autojoin'] in ('1', 'true'):
				jid = bm['jid']
				# Only join non-opened groupchats. Opened one are already
				# auto-joined on re-connection
				if not jid in gajim.gc_connected[account]:
					# we are not already connected
					minimize = bm['minimize'] in ('1', 'true')
					gajim.interface.join_gc_room(account, jid, bm['nick'],
					bm['password'], minimize = minimize)
				elif jid in self.minimized_controls[account]:
					# more or less a hack:
					# On disconnect the minimized gc contact instances
					# were set to offline. Reconnect them to show up in the roster.
					self.roster.add_groupchat(jid, account)

	def add_gc_bookmark(self, account, name, jid, autojoin, minimize, password,
		nick):
		'''add a bookmark for this account, sorted in bookmark list'''
		bm = {
			'name': name,
			'jid': jid,
			'autojoin': autojoin,
			'minimize': minimize,
			'password': password,
			'nick': nick
		}
		place_found = False
		index = 0
		# check for duplicate entry and respect alpha order
		for bookmark in gajim.connections[account].bookmarks:
			if bookmark['jid'] == bm['jid']:
				dialogs.ErrorDialog(
					_('Bookmark already set'),
					_('Group Chat "%s" is already in your bookmarks.') % bm['jid'])
				return
			if bookmark['name'] > bm['name']:
				place_found = True
				break
			index += 1
		if place_found:
			gajim.connections[account].bookmarks.insert(index, bm)
		else:
			gajim.connections[account].bookmarks.append(bm)
		gajim.connections[account].store_bookmarks()
		self.roster.set_actions_menu_needs_rebuild()
		dialogs.InformationDialog(
				_('Bookmark has been added successfully'),
				_('You can manage your bookmarks via Actions menu in your roster.'))


	# does JID exist only within a groupchat?
	def is_pm_contact(self, fjid, account):
		bare_jid = gajim.get_jid_without_resource(fjid)

		gc_ctrl = self.msg_win_mgr.get_gc_control(bare_jid, account)

		if not gc_ctrl and \
		bare_jid in self.minimized_controls[account]:
			gc_ctrl = self.minimized_controls[account][bare_jid]

		return gc_ctrl and gc_ctrl.type_id == message_control.TYPE_GC

	def create_ipython_window(self):
		try:
			from ipython_view import IPythonView
		except ImportError:
			print 'ipython_view not found'
			return
		import pango

		if os.name == 'nt':
			font = 'Lucida Console 9'
		else:
			font = 'Luxi Mono 10'

		window = gtk.Window()
		window.set_size_request(750,550)
		window.set_resizable(True)
		sw = gtk.ScrolledWindow()
		sw.set_policy(gtk.POLICY_AUTOMATIC,gtk.POLICY_AUTOMATIC)
		view = IPythonView()
		view.modify_font(pango.FontDescription(font))
		view.set_wrap_mode(gtk.WRAP_CHAR)
		sw.add(view)
		window.add(sw)
		window.show_all()
		def on_delete(win, event):
			win.hide()
			return True
		window.connect('delete_event',on_delete)
		view.updateNamespace({'gajim': gajim})
		gajim.ipython_window = window

	def run(self):
		if self.systray_capabilities and gajim.config.get('trayicon') != 'never':
			self.show_systray()

		self.roster = roster_window.RosterWindow()
		for account in gajim.connections:
			gajim.connections[account].load_roster_from_db()

		# get instances for windows/dialogs that will show_all()/hide()
		self.instances['file_transfers'] = dialogs.FileTransfersWindow()

		gobject.timeout_add(100, self.autoconnect)
		timeout, in_seconds = gajim.idlequeue.PROCESS_TIMEOUT
		if in_seconds:
			gobject.timeout_add_seconds(timeout, self.process_connections)
		else:
			gobject.timeout_add(timeout, self.process_connections)
		gobject.timeout_add_seconds(gajim.config.get(
			'check_idle_every_foo_seconds'), self.read_sleepy)

		# when using libasyncns we need to process resolver in regular intervals
		if resolver.USE_LIBASYNCNS:
			gobject.timeout_add(200, gajim.resolver.process)

		# setup the indicator
		if gajim.HAVE_INDICATOR:
			notify.setup_indicator_server()

		def remote_init():
			if gajim.config.get('remote_control'):
				try:
					import remote_control
					self.remote_ctrl = remote_control.Remote()
				except Exception:
					pass
		gobject.timeout_add_seconds(5, remote_init)

		for account in gajim.connections:
			if gajim.config.get_per('accounts', account, 'publish_tune') and \
			dbus_support.supported:
				self.enable_music_listener()
				break

	def __init__(self):
		gajim.interface = self
		gajim.thread_interface = ThreadInterface
		# This is the manager and factory of message windows set by the module
		self.msg_win_mgr = None
		self.jabber_state_images = {'16': {}, '32': {}, 'opened': {},
			'closed': {}}
		self.emoticons_menu = None
		# handler when an emoticon is clicked in emoticons_menu
		self.emoticon_menuitem_clicked = None
		self.minimized_controls = {}
		self.status_sent_to_users = {}
		self.status_sent_to_groups = {}
		self.gpg_passphrase = {}
		self.pass_dialog = {}
		self.default_colors = {
			'inmsgcolor': gajim.config.get('inmsgcolor'),
			'outmsgcolor': gajim.config.get('outmsgcolor'),
			'statusmsgcolor': gajim.config.get('statusmsgcolor'),
			'urlmsgcolor': gajim.config.get('urlmsgcolor'),
		}

		cfg_was_read = parser.read()
		gajim.logger.reset_shown_unread_messages()
		# override logging settings from config (don't take care of '-q' option)
		if gajim.config.get('verbose'):
			logging_helpers.set_verbose()

		# Is Gajim default app?
		if os.name != 'nt' and gajim.config.get('check_if_gajim_is_default'):
			gtkgui_helpers.possibly_set_gajim_as_xmpp_handler()

		for account in gajim.config.get_per('accounts'):
			if gajim.config.get_per('accounts', account, 'is_zeroconf'):
				gajim.ZEROCONF_ACC_NAME = account
				break
		# Is gnome configured to activate row on single click ?
		try:
			import gconf
			client = gconf.client_get_default()
			click_policy = client.get_string(
				'/apps/nautilus/preferences/click_policy')
			if click_policy == 'single':
				gajim.single_click = True
		except Exception:
			pass
		# add default status messages if there is not in the config file
		if len(gajim.config.get_per('statusmsg')) == 0:
			default = gajim.config.statusmsg_default
			for msg in default:
				gajim.config.add_per('statusmsg', msg)
				gajim.config.set_per('statusmsg', msg, 'message', default[msg][0])
				gajim.config.set_per('statusmsg', msg, 'activity', default[msg][1])
				gajim.config.set_per('statusmsg', msg, 'subactivity',
					default[msg][2])
				gajim.config.set_per('statusmsg', msg, 'activity_text',
					default[msg][3])
				gajim.config.set_per('statusmsg', msg, 'mood', default[msg][4])
				gajim.config.set_per('statusmsg', msg, 'mood_text', default[msg][5])
		#add default themes if there is not in the config file
		theme = gajim.config.get('roster_theme')
		if not theme in gajim.config.get_per('themes'):
			gajim.config.set('roster_theme', _('default'))
		if len(gajim.config.get_per('themes')) == 0:
			d = ['accounttextcolor', 'accountbgcolor', 'accountfont',
				'accountfontattrs', 'grouptextcolor', 'groupbgcolor', 'groupfont',
				'groupfontattrs', 'contacttextcolor', 'contactbgcolor',
				'contactfont', 'contactfontattrs', 'bannertextcolor',
				'bannerbgcolor']

			default = gajim.config.themes_default
			for theme_name in default:
				gajim.config.add_per('themes', theme_name)
				theme = default[theme_name]
				for o in d:
					gajim.config.set_per('themes', theme_name, o,
						theme[d.index(o)])

		if gajim.config.get('autodetect_browser_mailer') or not cfg_was_read:
			gtkgui_helpers.autodetect_browser_mailer()

		gajim.idlequeue = idlequeue.get_idlequeue()
		# resolve and keep current record of resolved hosts
		gajim.resolver = resolver.get_resolver(gajim.idlequeue)
		gajim.socks5queue = socks5.SocksQueue(gajim.idlequeue,
			self.handle_event_file_rcv_completed,
			self.handle_event_file_progress,
			self.handle_event_file_error)
		gajim.proxy65_manager = proxy65_manager.Proxy65Manager(gajim.idlequeue)
		gajim.default_session_type = ChatControlSession
		self.register_handlers()
		if gajim.config.get_per('accounts', gajim.ZEROCONF_ACC_NAME, 'active') \
		and gajim.HAVE_ZEROCONF:
			gajim.connections[gajim.ZEROCONF_ACC_NAME] = \
				connection_zeroconf.ConnectionZeroconf(gajim.ZEROCONF_ACC_NAME)
		for account in gajim.config.get_per('accounts'):
			if not gajim.config.get_per('accounts', account, 'is_zeroconf') and \
			gajim.config.get_per('accounts', account, 'active'):
				gajim.connections[account] = common.connection.Connection(account)

		# gtk hooks
		gtk.about_dialog_set_email_hook(self.on_launch_browser_mailer, 'mail')
		gtk.about_dialog_set_url_hook(self.on_launch_browser_mailer, 'url')
		gtk.link_button_set_uri_hook(self.on_launch_browser_mailer, 'url')

		self.instances = {}

		for a in gajim.connections:
			self.instances[a] = {'infos': {}, 'disco': {}, 'gc_config': {},
				'search': {}, 'online_dialog': {}}
			# online_dialog contains all dialogs that have a meaning only when we
			# are not disconnected
			self.minimized_controls[a] = {}
			gajim.contacts.add_account(a)
			gajim.groups[a] = {}
			gajim.gc_connected[a] = {}
			gajim.automatic_rooms[a] = {}
			gajim.newly_added[a] = []
			gajim.to_be_removed[a] = []
			gajim.nicks[a] = gajim.config.get_per('accounts', a, 'name')
			gajim.block_signed_in_notifications[a] = True
			gajim.sleeper_state[a] = 0
			gajim.encrypted_chats[a] = []
			gajim.last_message_time[a] = {}
			gajim.status_before_autoaway[a] = ''
			gajim.transport_avatar[a] = {}
			gajim.gajim_optional_features[a] = []
			gajim.caps_hash[a] = ''

		helpers.update_optional_features()

		self.remote_ctrl = None

		if gajim.config.get('networkmanager_support') and dbus_support.supported:
			import network_manager_listener

		# Handle gnome screensaver
		if dbus_support.supported:
			def gnome_screensaver_ActiveChanged_cb(active):
				if not active:
					for account in gajim.connections:
						if gajim.sleeper_state[account] == 'autoaway-forced':
							# We came back online ofter gnome-screensaver autoaway
							self.roster.send_status(account, 'online',
								gajim.status_before_autoaway[account])
							gajim.status_before_autoaway[account] = ''
							gajim.sleeper_state[account] = 'online'
					return
				if not gajim.config.get('autoaway'):
					# Don't go auto away if user disabled the option
					return
				for account in gajim.connections:
					if account not in gajim.sleeper_state or \
							not gajim.sleeper_state[account]:
						continue
					if gajim.sleeper_state[account] == 'online':
						# we save out online status
						gajim.status_before_autoaway[account] = \
							gajim.connections[account].status
						# we go away (no auto status) [we pass True to auto param]
						auto_message = gajim.config.get('autoaway_message')
						if not auto_message:
							auto_message = gajim.connections[account].status
						else:
							auto_message = auto_message.replace('$S','%(status)s')
							auto_message = auto_message.replace('$T','%(time)s')
							auto_message = auto_message % {
								'status': gajim.status_before_autoaway[account],
								'time': gajim.config.get('autoxatime')
							}
						self.roster.send_status(account, 'away', auto_message,
							auto=True)
						gajim.sleeper_state[account] = 'autoaway-forced'

			try:
				bus = dbus.SessionBus()
				bus.add_signal_receiver(gnome_screensaver_ActiveChanged_cb,
					'ActiveChanged', 'org.gnome.ScreenSaver')
			except Exception:
				pass

		self.show_vcard_when_connect = []

		self.sleeper = common.sleepy.Sleepy(
			gajim.config.get('autoawaytime') * 60, # make minutes to seconds
			gajim.config.get('autoxatime') * 60)

		gtkgui_helpers.make_jabber_state_images()

		self.systray_enabled = False
		self.systray_capabilities = False

		if (os.name == 'nt'):
			import statusicon
			self.systray = statusicon.StatusIcon()
			self.systray_capabilities = True
		else: # use ours, not GTK+ one
			# [FIXME: remove this when we migrate to 2.10 and we can do
			# cool tooltips somehow and (not dying to keep) animation]
			import systray
			self.systray_capabilities = systray.HAS_SYSTRAY_CAPABILITIES
			if self.systray_capabilities:
				self.systray = systray.Systray()

		path_to_file = os.path.join(gajim.DATA_DIR, 'pixmaps', 'gajim.png')
		pix = gtk.gdk.pixbuf_new_from_file(path_to_file)
		# set the icon to all windows
		gtk.window_set_default_icon(pix)

		self.init_emoticons()
		self.make_regexps()

		# get transports type from DB
		gajim.transport_type = gajim.logger.get_transports_type()

		# test is dictionnary is present for speller
		if gajim.config.get('use_speller'):
			lang = gajim.config.get('speller_language')
			if not lang:
				lang = gajim.LANG
			tv = gtk.TextView()
			try:
				import gtkspell
				spell = gtkspell.Spell(tv, lang)
			except (ImportError, TypeError, RuntimeError, OSError):
				dialogs.AspellDictError(lang)

		if gajim.config.get('soundplayer') == '':
			# only on first time Gajim starts
			commands = ('aplay', 'play', 'esdplay', 'artsplay', 'ossplay')
			for command in commands:
				if helpers.is_in_path(command):
					if command == 'aplay':
						command += ' -q'
					gajim.config.set('soundplayer', command)
					break

		self.last_ftwindow_update = 0
		self.music_track_changed_signal = None
if __name__ == '__main__':
	def sigint_cb(num, stack):
		sys.exit(5)
	# ^C exits the application normally to delete pid file
	signal.signal(signal.SIGINT, sigint_cb)
	log.info("Encodings: d:%s, fs:%s, p:%s", sys.getdefaultencoding(), \
		sys.getfilesystemencoding(), locale.getpreferredencoding())
junglecow's avatar
junglecow committed

nkour's avatar
nkour committed
		# Session Management support
nkour's avatar
nkour committed
		try:
			import gnome.ui
		except ImportError:
nkour's avatar
nkour committed
		else:
			def die_cb(cli):
				gajim.interface.roster.quit_gtkgui_interface()
nkour's avatar
nkour committed
			gnome.program_init('gajim', gajim.version)
			cli = gnome.ui.master_client()
			cli.connect('die', die_cb)
			path_to_gajim_script = gtkgui_helpers.get_abspath_for_script(
				'gajim')
			if path_to_gajim_script:
nkour's avatar
nkour committed
				argv = [path_to_gajim_script]
				# FIXME: remove this typeerror catch when gnome python is old and
				# not bad patched by distro men [2.12.0 + should not need all that
				# NORMALLY]
				try:
					cli.set_restart_command(argv)
nkour's avatar
nkour committed
					cli.set_restart_command(len(argv), argv)
	check_paths.check_and_possibly_create_paths()
	interface = Interface()
	interface.run()
		if os.name != 'nt':
			# This makes Gajim unusable under windows, and threads are used only
			# for GPG, so not under windows
			gtk.gdk.threads_init()
		gtk.main()
	except KeyboardInterrupt:
		print >> sys.stderr, 'KeyboardInterrupt'