#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2010 by VladX, <http://vladx.net>
#
# 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/>.


NANOSHOT_VERSION = '0.2.15'
NANOSHOT_LOCALE_DIR = './locale'
NANOSHOT_ICONS_DIR = './icons'
NANOSHOT_LIB_DIR = './lib'
NANOSHOT_HOSTINGS_DIR = './hostings'
NANOSHOT_BUG_REPORT_URL = 'https://bugs.launchpad.net/nanoshot'
NANOSHOT_TRANSLATE_URL = 'https://translations.launchpad.net/nanoshot'


import os
import time
import tempfile
import pickle
import subprocess
import gettext
import pygtk
pygtk.require('2.0')
import gtk
import glib
import gobject
import dbus
import dbus.service
from dbus.mainloop.glib import DBusGMainLoop

os.sys.path.insert(1, NANOSHOT_LIB_DIR)

import Effects
import Selector
import Imagehosting

try:
	# Don't let pygst show its own help
	_argv, _path = os.sys.argv, os.sys.path
	os.sys.argv = []
	os.sys.path = os.sys.path + []
	import pygst
	pygst.require('0.10')
	import gst as gstreamer
	from gst.extend import discoverer as gstDiscoverer
	# Now return the command-line options back
	os.sys.argv, os.sys.path = _argv, _path
	del _argv, _path
	import Gstsnapshotter
except (ImportError, pygst.RequiredVersionError):
	gstreamer = None

try:
	import webkit
except ImportError:
	webkit = None
	try:
		import gtkmozembed
	except ImportError:
		gtkmozembed = None

try:
	import urllib.request as urllib
except ImportError:
	import urllib

class Nanoshot(dbus.service.Object):
	
	def __init__(self, windowMode, doAtLaunch):
		
		self.config = {
						'delay': 0.1,
						'start-by-printscr': False,
						'associated-action': '-a',
						'prev-tool': 'gnome-screenshot',
						'prev-tool-window': 'gnome-screenshot --window',
						'include-cursor': False
		}
		self.configStoreFile = os.environ['HOME'] + '/.config/Nanoshot/config'
		self.startupDesktopFile = os.environ['HOME'] + '/.config/autostart/Nanoshot.desktop'
		self.lockfile = tempfile.gettempdir() + '/Nanoshot.lock'
		self.screen = wnck.screen_get_default()
		self.screen.force_update()
		self.sessionBus = dbus.SessionBus()
		
		lang = Lang()
		
		if self.is_running():
			gobject.idle_add(self.already_running_handler, doAtLaunch)
			return None
		
		if os.path.isfile(self.configStoreFile):
			try:
				confFile = open(self.configStoreFile, 'r')
				self.config.update(pickle.load(confFile))
			except IOError:
				self.error(lang.get('Unable to read configuration file. Check the file and directory permissions.'))
		
		gtk.icon_theme_add_builtin_icon('Nanoshot-about', 48, gtk.gdk.pixbuf_new_from_file(NANOSHOT_ICONS_DIR + '/Nanoshot-about.svg'))
		gtk.stock_add([ ('dummy-stock', '', 0, 0, '') ])
		
		if windowMode:
			_window = gtk.Window(gtk.WINDOW_TOPLEVEL)
			_window.set_title('Nanoshot')
			_window.set_position(gtk.WIN_POS_CENTER)
			_menuBar = gtk.MenuBar()
			_menuParent = gtk.MenuItem('Nanoshot')
			_menuBar.append(_menuParent)
			_window.add(_menuBar)
		else:
			try:
				import appindicator
				global appindicator
				self.trayIndicator = appindicator.Indicator('Nanoshot', 'nanoshot-status-icon', appindicator.CATEGORY_APPLICATION_STATUS)
				self.trayIndicator.set_status(appindicator.STATUS_ACTIVE)
			except:
				try:
					statusIcon = gtk.status_icon_new_from_icon_name('nanoshot-status-icon')
				except:
					self.error(lang.get('It seems that you have not installed "python-appindicator". Please install and try again.'))
					os.sys.exit(0)
		
		menu = gtk.Menu()
		
		separator = gtk.SeparatorMenuItem
		
		accelGroup = gtk.AccelGroup()
		menu.set_accel_group(accelGroup)
		
		takeScreenOfArea = gtk.ImageMenuItem('dummy-stock', accelGroup)
		takeScreenOfArea.set_image(gtk.image_new_from_icon_name('display-capplet', 'menu'))
		takeScreenOfArea.set_label(lang.get('_Select the screen area'))
		takeScreenOfArea.connect('activate', self.select_area)
		
		takeScreenOfWindow = gtk.ImageMenuItem('dummy-stock', accelGroup)
		takeScreenOfWindow.set_image(gtk.image_new_from_icon_name('preferences-system-windows', 'menu'))
		takeScreenOfWindow.set_label(lang.get('Take a screenshot of _window...'))
		takeScreenOfActiveWindow = gtk.MenuItem(lang.get('_Active window'), True)
		takeScreenOfActiveWindow.connect('activate', self.take_screen_of_window)
		takeScreenOfWindowSubmenu = gtk.Menu()
		takeScreenOfWindowSubmenu.append(separator())
		takeScreenOfWindowSubmenu.append(takeScreenOfActiveWindow)
		takeScreenOfWindow.set_submenu(takeScreenOfWindowSubmenu)
		
		self.update_running_app_list(submenu = takeScreenOfWindowSubmenu)
		self.screen.connect('window-opened', self.update_running_app_list, takeScreenOfWindowSubmenu, menu)
		self.screen.connect('window-closed', self.update_running_app_list, takeScreenOfWindowSubmenu, menu)
		
		takeVideoFrame = gtk.ImageMenuItem('dummy-stock', accelGroup)
		takeVideoFrame.set_image(gtk.image_new_from_icon_name('video-x-generic', 'menu'))
		takeVideoFrame.set_label(lang.get('Take from _video file'))
		takeVideoFrame.connect('activate', self.take_video_frame)
		
		takeScreenOfWebpage = gtk.ImageMenuItem('dummy-stock', accelGroup)
		takeScreenOfWebpage.set_image(gtk.image_new_from_icon_name('applications-internet', 'menu'))
		takeScreenOfWebpage.set_label(lang.get('Take screenshot of a _web page'))
		takeScreenOfWebpage.connect('activate', self.take_webpage_screenshot)
		
		takeScreen = gtk.ImageMenuItem('dummy-stock', accelGroup)
		takeScreen.set_image(gtk.image_new_from_icon_name('camera-photo', 'menu'))
		takeScreen.set_label(lang.get('Take a screenshot'))
		#takeScreen.add_accelerator('activate', accelGroup, ord('T'), gtk.gdk.CONTROL_MASK, gtk.ACCEL_VISIBLE)
		takeScreen.connect('activate', self.take_screen)
		
		if self.is_x_available('gnome-screenshot'):
			self.screenshotProgram = 'gnome-screenshot'
		elif self.is_x_available('ksnapshot'):
			self.screenshotProgram = 'ksnapshot'
		elif self.get_gtk_screen_image():
			''' No gnome-screenshot or Ksnapshot found. Ok, we try to use the built-in screenshot dialog. '''
			self.use_builtin = True
		else:
			takeScreen.set_sensitive(False)
			takeScreen.set_tooltip_text(lang.get('This feature is only available in Gnome and KDE.'))
			takeScreen.set_has_tooltip(True)
		
		chooseDelaySubmenu = gtk.Menu()
		chooseDelay = gtk.MenuItem(lang.get('_Delay...'), True)
		chooseDelay.set_submenu(chooseDelaySubmenu)
		
		radioItem = None
		for delay in [0.1, 1, 5, 10, 15, 20]:
			radioItem = gtk.RadioMenuItem(radioItem, lang.get('%d sec.') % (delay), True)
			if delay == 0.1:
				radioItem.set_label(lang.get('Without delay'))
			if delay == self.config['delay']:
				radioItem.set_active(True)
			radioItem.connect('toggled', lambda c, d: self.config.__setitem__('delay', d), delay)
			chooseDelaySubmenu.append(radioItem)
		
		chooseActionSubmenu = gtk.Menu()
		self.chooseAction = chooseAction = gtk.MenuItem(lang.get('Associated _action...'), True)
		chooseAction.set_submenu(chooseActionSubmenu)
		
		radioItem = None
		for label, action in (('Screen area', '-a'), ('Active window', '-c'), ('Frames from the video', '-f'), ('Web page', '-p'), ('Fullsize screenshot', '-t')):
			radioItem = gtk.RadioMenuItem(radioItem, lang.get(label), True)
			if action == self.config['associated-action']:
				radioItem.set_active(True)
			radioItem.connect('toggled', lambda c, a: (self.config.__setitem__('associated-action', a) or self.start_by_printscr(True)) and self.start_by_printscr(True), action)
			chooseActionSubmenu.append(radioItem)
		
		startByPrintScr = gtk.CheckMenuItem(lang.get('Re_place the standard screenshot tool'), True)
		startByPrintScr.connect('toggled', lambda c: self.start_by_printscr(c.active, c))
		includeCursor = gtk.CheckMenuItem(lang.get('Incl_ude cursor'), True)
		includeCursor.set_active(self.config['include-cursor'])
		includeCursor.connect('toggled', lambda c: self.config.__setitem__('include-cursor', c.active))
		runAtStartup = gtk.CheckMenuItem(lang.get('_Run at startup'), True)
		runAtStartup.connect('toggled', self.run_at_startup)
		
		self.start_by_printscr(self.config['start-by-printscr'], startByPrintScr)
		
		if self.is_run_at_startup():
			runAtStartup.set_active(True)
		
		reportBug = gtk.ImageMenuItem('dummy-stock', accelGroup)
		reportBug.set_image(gtk.image_new_from_icon_name('lpi-bug', 'menu'))
		reportBug.set_label(lang.get('Report _bug'))
		reportBug.connect('activate', self.open_url, NANOSHOT_BUG_REPORT_URL)
		helpTranslate = gtk.ImageMenuItem('dummy-stock', accelGroup)
		helpTranslate.set_image(gtk.image_new_from_icon_name('lpi-translate', 'menu'))
		helpTranslate.set_label(lang.get('Tra_nslate this application'))
		helpTranslate.connect('activate', self.open_url, NANOSHOT_TRANSLATE_URL)
		about = gtk.ImageMenuItem(gtk.STOCK_ABOUT, accelGroup)
		about.connect('activate', self.about)
		exit = gtk.ImageMenuItem(gtk.STOCK_QUIT, accelGroup)
		#exit.add_accelerator('activate', accelGroup, ord('Q'), gtk.gdk.CONTROL_MASK, gtk.ACCEL_VISIBLE)
		exit.connect('activate', self.__del__)
		
		dbus.service.Object.__init__(self, dbus.service.BusName('com.nanoshot.Nanoshot', self.sessionBus), '/com/nanoshot/Nanoshot')
		
		menu.append(takeScreenOfArea)
		menu.append(takeScreenOfWindow)
		menu.append(takeVideoFrame)
		menu.append(takeScreenOfWebpage)
		menu.append(takeScreen)
		menu.append(separator())
		menu.append(startByPrintScr)
		menu.append(chooseAction)
		menu.append(chooseDelay)
		menu.append(includeCursor)
		menu.append(runAtStartup)
		menu.append(separator())
		menu.append(reportBug)
		menu.append(helpTranslate)
		menu.append(about)
		menu.append(exit)
		
		menu.show_all()
		
		if windowMode:
			_menuParent.set_submenu(menu)
			_window.show_all()
		elif hasattr(self, 'trayIndicator'):
			self.trayIndicator.set_menu(menu)
		else:
			callback = lambda s, b, t: menu.popup(None, None, lambda m: gtk.status_icon_position_menu(m, statusIcon), b, t or gtk.get_current_event_time())
			statusIcon.connect('activate', callback, 1, None)
			statusIcon.connect('popup-menu', callback)
		
		if doAtLaunch:
			self.do_at_launch_handler(doAtLaunch)
	
	def __del__(self, widget = None):
		
		try:
			lock = open(self.lockfile, 'r')
			pid = int(lock.read())
			lock.close()
		except IOError:
			pid = os.getpid()
		if pid == os.getpid():
			confDir = os.path.dirname(self.configStoreFile)
			if not os.path.isdir(confDir):
				os.makedirs(confDir, 0o744)
			try:
				confFile = open(self.configStoreFile, 'w')
				pickle.dump(self.config, confFile)
			except IOError:
				self.error(Lang.get('Unable to create / overwrite file \"%s\". Check the file and directory permissions.') % self.configStoreFile)
			try:
				os.remove(self.lockfile)
			except OSError: pass
		gtk.main_quit()
	
	def do_at_launch_handler(self, doAtLaunch):
		
		if doAtLaunch == '-a':
			self.select_area()
		elif doAtLaunch == '-c':
			self.take_screen_of_window()
		elif doAtLaunch == '-f':
			self.take_video_frame()
		elif doAtLaunch == '-p':
			self.take_webpage_screenshot()
		elif doAtLaunch == '-t':
			self.take_screen()
	
	def is_running(self):
		
		try:
			if os.path.exists(self.lockfile):
				lock = open(self.lockfile, 'r')
				pid = lock.read()
				lock.close()
				ps = subprocess.Popen('ps --pid ' + pid, shell = True, stdout = subprocess.PIPE)
				for proc in ps.communicate():
					if not proc:
						continue
					for p in proc.split('\n'):
						if p and p.find(pid) != -1:
							return True
			lock = open(self.lockfile, 'w')
			lock.write(str(os.getpid()))
			lock.close()
		except IOError: pass
		return False
	
	def already_running_handler(self, doAtLaunch):
		
		anotherInstance = self.sessionBus.get_object('com.nanoshot.Nanoshot', '/com/nanoshot/Nanoshot')
		if doAtLaunch == '-a':
			remoteFunction = anotherInstance.get_dbus_method('select_area', 'com.nanoshot.Nanoshot')
			remoteFunction(0)
		elif doAtLaunch == '-c':
			remoteFunction = anotherInstance.get_dbus_method('take_screen_of_window', 'com.nanoshot.Nanoshot')
			remoteFunction(0, 'active')
		elif doAtLaunch == '-f':
			remoteFunction = anotherInstance.get_dbus_method('take_video_frame', 'com.nanoshot.Nanoshot')
			remoteFunction(0)
		elif doAtLaunch == '-p':
			remoteFunction = anotherInstance.get_dbus_method('take_webpage_screenshot', 'com.nanoshot.Nanoshot')
			remoteFunction(0)
		elif doAtLaunch == '-t':
			remoteFunction = anotherInstance.get_dbus_method('take_screen', 'com.nanoshot.Nanoshot')
			remoteFunction(0)
		os.sys.exit(0)
	
	def update_running_app_list(self, eventScreen = None, eventWindow = None, submenu = None, menu = None):
		
		screen = self.screen
		submenuChildrens = submenu.get_children()
		for child in submenuChildrens:
			if hasattr(child, 'appList'):
				child.destroy()
		windows = screen.get_windows()
		for window in windows:
			menuItem = gtk.ImageMenuItem('dummy-stock')
			if window.has_name():
				label = window.get_name()
				if label == 'x-nautilus-desktop':
					label = Lang.get('Desktop area')
				try:
					charset = os.environ['LANG'].split('.')[1]
				except IndexError:
					charset = 'utf-8'
				mbLabel = label.decode(charset)
				if len(mbLabel) > 50:
					label = mbLabel[:50] + '...'
					label = label.encode(charset)
				menuItem.set_label(label)
			else:
				menuItem.set_label(Lang.get('Untitled'))
			miniIcon = gtk.image_new_from_pixbuf(window.get_mini_icon())
			menuItem.set_image(miniIcon)
			menuItem.connect('activate', self.take_screen_of_window, window)
			menuItem.appList = True
			menuItem.show()
			submenu.prepend(menuItem)
	
	def is_pygst_available(self):
		
		return gstreamer is not None
	
	def is_x_available(self, x):
		
		paths = os.getenv('PATH').split(os.pathsep)
		for path in paths:
			if os.access(path + '/' + x, os.X_OK):
				return True
		return False
	
	def get_gtk_screen_image(self, window = None):
		
		time.sleep(self.config['delay'])
		try:
			if window == None:
				window = gtk.gdk.get_default_root_window()
			size = window.get_size()
			pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, size[0], size[1])
			pixbuf = pixbuf.get_from_drawable(window, window.get_colormap(), 0, 0, 0, 0, size[0], size[1])
			if self.config['include-cursor']:
				cursor = gtk.gdk.Cursor(gtk.gdk.LEFT_PTR).get_image()
				xHot, yHot = int(cursor.get_option('x_hot')), int(cursor.get_option('y_hot'))
				x, y, mod = window.get_pointer()
				x, y = x - xHot, y - yHot
				cursor.composite(pixbuf, min(pixbuf.get_width(), max(0, x)), min(pixbuf.get_height(), max(0, y)), cursor.get_width(), cursor.get_height(), x, y, 1, 1, gtk.gdk.INTERP_BILINEAR, 255)
			self.gtk_screen_image = pixbuf
			return True
		except:
			return False
	
	def take_screen_of_area_complete_handler(self, x, y, width, height):
		
		root = gtk.gdk.get_default_root_window()
		pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, width, height)
		pixbuf = pixbuf.get_from_drawable(root, root.get_colormap(), x, y, 0, 0, width, height)
		self.gtk_screen_image = pixbuf
		self.take_screen()
	
	@dbus.service.method('com.nanoshot.Nanoshot')
	def select_area(self, widget = None):
		
		screen = gtk.gdk.screen_get_default()
		root = screen.get_root_window()
		if screen.is_composited():
			Selector.Selector(self.select_area_event_handler)
		else:
			gtk.gdk.flush()
			gc = root.new_gc(foreground = gtk.gdk.color_parse('white'), function = gtk.gdk.INVERT, subwindow_mode = gtk.gdk.INCLUDE_INFERIORS, line_width = 1, line_style = gtk.gdk.LINE_SOLID, cap_style = gtk.gdk.CAP_BUTT, join_style = gtk.gdk.JOIN_ROUND)
			if not gtk.gdk.pointer_is_grabbed() and gtk.gdk.pointer_grab(root, False, gtk.gdk.BUTTON_MOTION_MASK | gtk.gdk.BUTTON1_MOTION_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK, None, gtk.gdk.Cursor(gtk.gdk.CROSSHAIR)) != gtk.gdk.GRAB_SUCCESS:
				return False
			self.selectAreaMotionX = self.selectAreaMotionY = self.selectAreaMotionWidth = self.selectAreaMotionHeight = 0
			self.selectAreaButtonPressed = False
			gtk.gdk.event_handler_set(self.select_area_event_handler_nocomposite, (root, gc))
	
	def select_area_event_handler(self, widget, event, selector):
		
		if event.type == gtk.gdk.MOTION_NOTIFY and selector.makesSelection:
			selector.redraw(event.x, event.y)
		elif event.type == gtk.gdk.MOTION_NOTIFY and selector.moving:
			selector.move(event.x, event.y)
		elif event.type == gtk.gdk.MOTION_NOTIFY and selector.resizing:
			selector.resize(event.x, event.y)
		elif event.type == gtk.gdk.MOTION_NOTIFY:
			selector.cursor_handler(event.x, event.y)
		elif event.type == gtk.gdk.BUTTON_PRESS and event.button == 1 and selector.selected and selector.pointer_on_the_resizing_square(event.x, event.y) != False:
			selector.start_resize(event.x, event.y)
		elif event.type == gtk.gdk.BUTTON_RELEASE and event.button == 1 and selector.resizing:
			selector.stop_resize()
		elif event.type == gtk.gdk.BUTTON_PRESS and event.button == 1 and selector.selected and selector.pointer_in_selection(event.x, event.y):
			selector.start_move(event.x, event.y)
		elif event.type == gtk.gdk.BUTTON_RELEASE and event.button == 1 and selector.moving:
			selector.stop_move()
		elif event.type == gtk.gdk.BUTTON_PRESS and event.button == 1:
			selector.start_selection(event.x, event.y)
		elif event.type == gtk.gdk.BUTTON_RELEASE and event.button == 1:
			selector.stop_selection(event.x, event.y)
		elif event.type == gtk.gdk.KEY_PRESS and event.keyval in [ gtk.gdk.keyval_from_name('Up'), gtk.gdk.keyval_from_name('Down'), gtk.gdk.keyval_from_name('Left'), gtk.gdk.keyval_from_name('Right') ]:
			selector.move_up_down(event.keyval)
		elif (event.type == gtk.gdk.KEY_PRESS and event.keyval == gtk.gdk.keyval_from_name('Return')) or (event.type == gtk.gdk._2BUTTON_PRESS and event.button == 1 and selector.selected and selector.selection_x_start != event.x and selector.pointer_in_selection(event.x, event.y)):
			selector.set_complete_handler(self.take_screen_of_area_complete_handler)
			selector.__del__()
			del selector
		elif event.type == gtk.gdk.KEY_PRESS and event.keyval == gtk.gdk.keyval_from_name('Escape'):
			selector.__del__()
			del selector
	
	def select_area_event_handler_nocomposite(self, event, data):
		
		root, gc = data
		if event.type == gtk.gdk.MOTION_NOTIFY and self.selectAreaButtonPressed:
			x, y = int(min(self.selectAreaMouseX, event.x_root)), int(min(self.selectAreaMouseY, event.y_root))
			width, height = int(abs(self.selectAreaMouseX - event.x_root)), int(abs(self.selectAreaMouseY - event.y_root))
			root.draw_rectangle(gc, False, self.selectAreaMotionX, self.selectAreaMotionY, self.selectAreaMotionWidth, self.selectAreaMotionHeight)
			root.draw_rectangle(gc, False, x, y, width, height)
			self.selectAreaMotionX, self.selectAreaMotionY, self.selectAreaMotionWidth, self.selectAreaMotionHeight = x, y, width, height
		elif event.type == gtk.gdk.BUTTON_PRESS and event.button == 1:
			self.selectAreaMouseX = event.x_root
			self.selectAreaMouseY = event.y_root
			self.selectAreaButtonPressed = True
		elif event.type == gtk.gdk.BUTTON_RELEASE and event.button == 1:
			gtk.gdk.pointer_ungrab()
			gtk.gdk.event_handler_set(lambda event: gtk.main_do_event(event))
			root.draw_rectangle(gc, False, self.selectAreaMotionX, self.selectAreaMotionY, self.selectAreaMotionWidth, self.selectAreaMotionHeight)
			if self.selectAreaMotionWidth > 0 and self.selectAreaMotionHeight > 0:
				self.take_screen_of_area_complete_handler(self.selectAreaMotionX, self.selectAreaMotionY, self.selectAreaMotionWidth, self.selectAreaMotionHeight)
			self.selectAreaButtonPressed = False
		else:
			gtk.main_do_event(event)
	
	@dbus.service.method('com.nanoshot.Nanoshot')
	def take_video_frame(self, widget = None):
		
		def response(dialog, responseId):
			
			if responseId == gtk.RESPONSE_OK and not fileChooser.get_filename():
				self.error(Lang.get('Choose the input video file.'))
				return False
			elif responseId == gtk.RESPONSE_OK and self.is_pygst_available():
				
				def discovered(discoverer, is_media):
					
					if not is_media or not discoverer.is_video:
						self.error(Lang.get('Gstreamer error') + ': ' + Lang.get('Unable to obtain information about the video file.'))
						dialog.action_area.foreach(lambda button: button.set_sensitive(True))
						progress.hide()
						return False
					length = float(discoverer.videolength) / gstreamer.SECOND
					if length < 0:
						self.error(Lang.get('Gstreamer error') + ': ' + Lang.get('Wrong video length.'))
						dialog.action_area.foreach(lambda button: button.set_sensitive(True))
						progress.hide()
						return False
					step = int(round(length / (spin.get_value_as_int() + 1)))
					if step < 0:
						self.error(Lang.get('Gstreamer error') + ': ' + Lang.get('Impossible to divide the video, because the length is too small.'))
						dialog.action_area.foreach(lambda button: button.set_sensitive(True))
						progress.hide()
						return False
					destFilename = ''.join(fileChooser.get_filename().split('.')[:-1])
					destFilename = dirChooser.get_filename() + '/' + os.path.basename(destFilename) + '-'
					gstsnapshotter = Gstsnapshotter.Snapshotter('file://' + fileChooser.get_filename(), destFilename, range(step, int(length), step))
					gstsnapshotter.start()
					dialog.destroy()
				
				dialog.action_area.foreach(lambda button: button.set_sensitive(False))
				table = dialog.vbox.get_children()[0]
				progress = gtk.ProgressBar()
				table.attach(progress, 1, 3, 4, 5)
				progress.show()
				gobject.timeout_add(50, lambda: progress.pulse() or True)
				discoverer = gstDiscoverer.Discoverer(fileChooser.get_filename())
				discoverer.connect('discovered', discovered)
				discoverer.discover()
				return True
			elif responseId == gtk.RESPONSE_OK and self.is_x_available('mplayer'):
				try:
					procMplayer = subprocess.Popen('mplayer -identify "' + fileChooser.get_filename() + '" -ao null -vo null -frames 0', shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
					output = procMplayer.communicate()
				except:
					self.error(Lang.get('MPlayer error') + ': ' + Lang.get('Unable to obtain information about the video file.'))
					return False
				length = -1
				for lines in output:
					lines = lines.split('\n')
					for line in lines:
						if line.startswith('ID_LENGTH'):
							length = float(line.replace('ID_LENGTH', '').strip('= '))
				if length < 0:
					self.error(Lang.get('MPlayer error') + ': ' + Lang.get('Wrong video length.'))
					return False
				step = int(round(length / (spin.get_value_as_int() + 1)))
				if step < 0:
					self.error(Lang.get('MPlayer error') + ': ' + Lang.get('Impossible to divide the video, because the length is too small.'))
					return False
				srcDir = dirChooser.get_filename()
				counter = 1
				for frame in xrange(step, int(length), step):
					procMplayer = subprocess.Popen('mplayer -ss %d -frames 1 -vo png:outdir="%s" -nosound "%s"' % (frame, srcDir, fileChooser.get_filename()), shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
					output = '\n'.join(procMplayer.communicate())
					if not os.path.isfile(srcDir + '/00000001.png') or procMplayer.returncode != 0:
						self.error(Lang.get('MPlayer error') + '(' + str(procMplayer.returncode) + '):\n' + output)
						return False
					destFilename = ''.join(fileChooser.get_filename().split('.')[:-1])
					destFilename = srcDir + '/' + os.path.basename(destFilename) + '-' + str(counter) + '.png'
					os.rename(srcDir + '/00000001.png', destFilename)
					counter += 1
			elif responseId == gtk.RESPONSE_OK:
				self.error(Lang.get('You need to install "python-gstreamer" (recommended) or "mplayer" for this feature.'))
			dialog.destroy()
		
		dialog = gtk.Dialog(Lang.get('Take frames from video file'), None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK, gtk.RESPONSE_OK))
		table = gtk.Table(6, 4)
		table.set_col_spacings(20)
		table.set_row_spacings(10)
		label = gtk.Label(Lang.get('Video file') + ':')
		label.set_alignment(0, 0.5)
		table.attach(label, 1, 2, 1, 2)
		label = gtk.Label(Lang.get('Save in') + ':')
		label.set_alignment(0, 0.5)
		table.attach(label, 1, 2, 3, 4)
		label = gtk.Label(Lang.get('Number of frames') + ':')
		label.set_alignment(0, 0.5)
		table.attach(label, 1, 2, 4, 5)
		fileChooser = gtk.FileChooserButton(Lang.get('Video file'))
		fileChooser.set_width_chars(10)
		fileChooser.set_current_folder(glib.get_user_special_dir(glib.USER_DIRECTORY_DESKTOP))
		table.attach(fileChooser, 2, 3, 1, 2)
		dirChooser = gtk.FileChooserButton(Lang.get('Save in'))
		dirChooser.set_width_chars(10)
		dirChooser.set_current_folder(glib.get_user_special_dir(glib.USER_DIRECTORY_DESKTOP))
		dirChooser.set_action(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER)
		table.attach(dirChooser, 2, 3, 3, 4)
		spin = gtk.SpinButton(gtk.Adjustment(1, 1, 1000, 1, 0, 0))
		table.attach(spin, 2, 3, 4, 5)
		expander = gtk.Expander(Lang.get('Choose from the recently used files'))
		recent = gtk.RecentChooserWidget()
		expander.add(recent)
		recent.connect('item-activated', lambda chooser: fileChooser.set_uri(chooser.get_current_uri()))
		table.attach(expander, 1, 3, 2, 3)
		table.show_all()
		dialog.vbox.pack_start(table)
		dialog.set_resizable(False)
		dialog.connect('response', response)
		responseId = dialog.run()
	
	@dbus.service.method('com.nanoshot.Nanoshot')
	def take_screen_of_window(self, widget = None, window = 'active'):
		
		screen = self.screen
		screenWidth, screenHeight = screen.get_width(), screen.get_height()
		if window == 'active':
			capturedWindow = screen.get_active_window()
		else:
			capturedWindow = window
		capturedWindow = gtk.gdk.window_foreign_new(capturedWindow.get_xid())
		x, y, width, height, depth = capturedWindow.get_geometry()
		xp, yp = 0, 0
		if x < 0:
			width += x
			xp = -x
		if y < 0:
			height += y
			yp = -y
		if x > screenWidth - width:
			width += screenWidth - width - x
		if y > screenHeight - height:
			height += screenHeight - height - y
		gtk_screen_image = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, width, height)
		self.get_gtk_screen_image(capturedWindow)
		self.gtk_screen_image.copy_area(xp, yp, width, height, gtk_screen_image, 0, 0)
		self.gtk_screen_image = gtk_screen_image
		self.take_screen(widget)
	
	@dbus.service.method('com.nanoshot.Nanoshot')
	def take_webpage_screenshot(self, widget = None):
		
		def response(dialog, responseId):
			
			def take_snapshot(button):
				
				window = view.get_snapshot()
				width, height = window.get_size()
				pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, width, height)
				pixbuf = pixbuf.get_from_drawable(window, window.get_colormap(), 0, 0, 0, 0, width, height)
				self.gtk_screen_image = pixbuf
				self.take_screen()
				
			def size_allocate(widget, allocation):
				
				if self.webpageWidth != allocation.width or self.webpageHeight != allocation.height:
					widthEntry.set_text(str(allocation.width))
					heightEntry.set_text(str(allocation.height))
				self.webpageWidth, self.webpageHeight = allocation.width, allocation.height
			
			def update_size(widget, event):
				
				if not event.string.isdigit():
					return False
				try:
					width, height = int(widthEntry.get_text()), int(heightEntry.get_text())
				except: return False
				if width and height:
					w0, h0 = vBox.size_request()
					w1, h1 = view.window.get_size()
					w2, h2 = window.window.get_size()
					width, height = width + w2 - w1, height + h2 - h1
					if width > w0 and height > h0:
						window.resize(width, height)
			
			scrURL = url.get_text()
			if responseId == gtk.RESPONSE_OK and (len(scrURL) < 10 or not scrURL.startswith('http://')):
				self.error(Lang.get('Please enter a valid URL.'))
				return False
			dialog.destroy()
			if responseId != gtk.RESPONSE_OK:
				return False
			self.webpageWidth, self.webpageHeight = 0, 0
			window = gtk.Window(gtk.WINDOW_TOPLEVEL)
			window.set_title('Nanoshot')
			window.set_position(gtk.WIN_POS_CENTER)
			button = gtk.Button(Lang.get('_Take!'))
			button.connect('clicked', take_snapshot)
			alignment = gtk.Alignment(0.5, 0, 0.15, 0)
			alignment.add(button)
			vBox = gtk.VBox(False, 5)
			statusbar = gtk.Statusbar()
			statusbar.set_has_resize_grip(True)
			widthEntry, heightEntry = gtk.Entry(5), gtk.Entry(5)
			widthEntry.set_width_chars(5)
			heightEntry.set_width_chars(5)
			statusbar.pack_start(widthEntry, False)
			statusbar.pack_start(gtk.Label('x'), False)
			statusbar.pack_start(heightEntry, False)
			window.add(vBox)
			window.set_default_size(int(self.screen.get_width() * 0.7), int(self.screen.get_height() * 0.7))
			if webkit != None:
				view = webkit.WebView()
				view.connect('notify::title', lambda w, t: view.props.title and window.set_title(view.props.title))
				view.get_main_frame().load_uri(scrURL)
				scrolled = gtk.ScrolledWindow()
				scrolled.add(view)
				vBox.pack_start(scrolled)
			elif gtkmozembed != None:
				view = gtkmozembed.MozEmbed()
				view.connect('title', lambda moz: window.set_title(moz.get_title()))
				view.load_url(scrURL)
				vBox.pack_start(view)
			else:
				self.error(Lang.get('You need to install "python-webkit" or "python-gtkmozembed" for this feature.'))
				return False
			view.connect('size-allocate', size_allocate)
			widthEntry.connect('key-release-event', update_size)
			heightEntry.connect('key-release-event', update_size)
			vBox.pack_start(alignment, False)
			vBox.pack_start(statusbar, False)
			window.show_all()
		
		dialog = gtk.Dialog(Lang.get('Enter the address of a web page'), None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK, gtk.RESPONSE_OK))
		url = gtk.Entry()
		url.set_text('http://')
		url.set_width_chars(40)
		clipboard = gtk.Clipboard()
		if clipboard.wait_is_text_available():
			text = clipboard.wait_for_text()
			if text.startswith('http://'):
				url.set_text(text)
		paste = gtk.Button(stock = gtk.STOCK_PASTE)
		paste.connect('clicked', lambda button: clipboard.wait_is_text_available() and url.set_text(clipboard.wait_for_text()))
		hbox = gtk.HBox(spacing = 5)
		hbox.pack_start(url)
		hbox.pack_start(paste)
		hbox.show_all()
		dialog.vbox.set_spacing(5)
		dialog.vbox.add(hbox)
		dialog.connect('response', response)
		dialog.run()
	
	@dbus.service.method('com.nanoshot.Nanoshot')
	def take_screen(self, widget = None):
		
		if hasattr(self, 'gtk_screen_image') or hasattr(self, 'use_builtin'):
			
			def response(dialog, resp_id):
				
				if resp_id == gtk.RESPONSE_CANCEL:
					dialog.destroy()
				elif resp_id == gtk.RESPONSE_COPY_TO_CLIPBOARD:
					clipboard = gtk.Clipboard()
					clipboard.set_image(image)
					dialog.destroy()
				elif resp_id == gtk.RESPONSE_EFFECTS:
					if not Effects.Image:
						self.error(Lang.get('You need to install Python Imaging Library (PIL) for this function.'))
						return False
					effectsDialog = gtk.Dialog(title = Lang.get('Effects'), flags = gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, buttons = (gtk.STOCK_OK, gtk.RESPONSE_OK))
					effectsDialog.connect('response', lambda d, r: d.destroy())
					checkButton = gtk.CheckButton(Lang.get('_Stroke'))
					checkButton.set_active('s' in self._effects and self._effects['s'])
					checkButton.connect('toggled', lambda c: self._effects.__setitem__('s', c.get_active()))
					effectsDialog.vbox.pack_start(checkButton)
					checkButton = gtk.CheckButton(Lang.get('Drop sha_dow'))
					checkButton.set_active('d' in self._effects and self._effects['d'])
					checkButton.connect('toggled', lambda c: self._effects.__setitem__('d', c.get_active()))
					effectsDialog.vbox.pack_start(checkButton)
					checkButton = gtk.CheckButton(Lang.get('Refle_ction'))
					checkButton.set_active('r' in self._effects and self._effects['r'])
					checkButton.connect('toggled', lambda c: self._effects.__setitem__('r', c.get_active()))
					effectsDialog.vbox.pack_start(checkButton)
					checkButton = gtk.CheckButton(Lang.get('Gra_yscale'))
					checkButton.set_active('g' in self._effects and self._effects['g'])
					checkButton.connect('toggled', lambda c: self._effects.__setitem__('g', c.get_active()))
					effectsDialog.vbox.pack_start(checkButton)
					effectsDialog.vbox.show_all()
					effectsDialog.run()
				elif resp_id == gtk.RESPONSE_UPLOAD:
					
					def response(dialog, resp_id):
						
						if resp_id != gtk.RESPONSE_OK:
							dialog.destroy()
							return False
						selection = treeview.get_selection()
						for i in xrange(len(iters)):
							if selection.iter_is_selected(iters[i]):
								
								def set_progress():
									
									error = hosting.error()
									if error:
										dialog.destroy()
										return False
									progr, text = hosting.get_progress()
									if not dialog.props.visible:
										return False
									if progr <= 1.0:
										progress.set_fraction(progr)
										progress.set_text(text)
										if progr < 1.0:
											return True
									if not hosting._thread.isAlive():
										dialog.destroy()
										hosting.display()
										return False
									return True
								
								hosting = Imagehosting.hostings[i].Hosting(Effects.Effects(image, self._effects))
								progress = gtk.ProgressBar()
								progress.set_fraction(0.0)
								alignment = gtk.Alignment(0, 0.8, 1, 0)
								alignment.add(progress)
								alignment.show_all()
								dialog.vbox.remove(scrolledWindow)
								dialog.vbox.pack_start(alignment)
								dialog.vbox.set_spacing(10)
								dialog.action_area.foreach(lambda button: button.set_sensitive(False))
								gobject.timeout_add(400, set_progress)
					
					hostingDialog = gtk.Dialog(title = Lang.get('Choose hosting'), flags = gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK, gtk.RESPONSE_OK))
					liststore = gtk.ListStore(gtk.gdk.Pixbuf, str)
					iters = []
					for h in Imagehosting.hostings:
						pixbufIcon = None
						if h.Hosting.HOSTING_ICON != None:
							try:
								pixbufIcon = gtk.gdk.pixbuf_new_from_file(h.Hosting.HOSTING_ICON)
								pixbufIcon = pixbufIcon.scale_simple(16, 16, gtk.gdk.INTERP_BILINEAR)
							except:
								pixbufIcon = gtk.gdk.pixbuf_new_from_file(Imagehosting.ImageHosting.HOSTING_ICON)
						iters.append(liststore.append([ pixbufIcon, h.Hosting.HOSTING_NAME ]))
					textrenderer = gtk.CellRendererText()
					pixbufrenderer = gtk.CellRendererPixbuf()
					column = gtk.TreeViewColumn()
					column.pack_start(pixbufrenderer, False)
					column.pack_start(textrenderer, True)
					column.add_attribute(pixbufrenderer, 'pixbuf', 0)
					column.add_attribute(textrenderer, 'text', 1)
					column.set_sort_column_id(1)
					column.set_sort_indicator(True)
					column.set_sort_order(gtk.SORT_ASCENDING)
					treeview = gtk.TreeView(liststore)
					treeview.append_column(column)
					treeview.set_headers_visible(False)
					treeview.set_rules_hint(True)
					scrolledWindow = gtk.ScrolledWindow()
					scrolledWindow.add(treeview)
					scrolledWindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
					scrolledWindow.set_size_request(-1, 100)
					scrolledWindow.show_all()
					hostingDialog.vbox.pack_start(scrolledWindow)
					hostingDialog.connect('response', response)
					hostingDialog.run()
				elif resp_id == gtk.RESPONSE_SAVE:
					
					def update_preview(widget):
						
						filename = widget.get_preview_filename()
						if not filename:
							widget.set_preview_widget_active(False)
							return False
						fileType = filename.split('.')[-1].lower()
						if fileType in ['png', 'jpg', 'jpeg']:
							try:
								pixbuf = gtk.gdk.pixbuf_new_from_file(filename)
							except:
								widget.set_preview_widget_active(False)
								return False
							pixbuf = pixbuf.scale_simple(150, int(round((150.0 / pixbuf.get_width()) * pixbuf.get_height())), gtk.gdk.INTERP_BILINEAR)
							previewWidget.set_from_pixbuf(pixbuf)
							previewWidget.show()
							widget.set_preview_widget_active(True)
						else:
							widget.set_preview_widget_active(False)
					
					chooser = gtk.FileChooserDialog(title = Lang.get('Save screenshot'), action = gtk.FILE_CHOOSER_ACTION_SAVE, buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK))
					chooser.set_current_name(Lang.get('Screenshot') + '.png')
					chooser.set_current_folder(glib.get_user_special_dir(glib.USER_DIRECTORY_DESKTOP))
					chooser.set_do_overwrite_confirmation(True)
					chooser.set_default_response(gtk.RESPONSE_OK)
					previewWidget = gtk.Image()
					chooser.connect('update-preview', update_preview)
					chooser.set_preview_widget(previewWidget)
					fileFilter = gtk.FileFilter()
					fileFilter.set_name(Lang.get('Images') + ' (*.png, *.jpg)')
					fileFilter.add_mime_type('image/png')
					fileFilter.add_mime_type('image/jpeg')
					fileFilter.add_pattern('*.png')
					fileFilter.add_pattern('*.jpg')
					fileFilter.add_pattern('*.jpeg')
					chooser.add_filter(fileFilter)
					chooserResponse = chooser.run()
					if chooserResponse == gtk.RESPONSE_OK:
						selectedFile = chooser.get_filename()
						selectedFileType = selectedFile.split('.')[-1].lower()
						if selectedFileType == 'jpg':
							selectedFileType = 'jpeg'
						if selectedFileType not in ['png', 'jpeg']:
							selectedFile += '.png'
							selectedFileType = 'png'
						Effects.Effects(image, self._effects).save(selectedFile, selectedFileType)
					chooser.destroy()
			
			def dnd_begin(widget, context):
				
				pixbuf = widget.get_children()[0].get_pixbuf()
				pixbuf = pixbuf.scale_simple(100, 100 * pixbuf.get_height() / pixbuf.get_width(), gtk.gdk.INTERP_BILINEAR)
				context.set_icon_pixbuf(pixbuf, 0, 0)
			
			def dnd_send_data(widget, context, selection, targetType, eventTime):
				
				if targetType == 100:
					selection.set_pixbuf(image)
				elif targetType == 101:
					path = os.path.join(tempfile.gettempdir(), Lang.get('Screenshot')) + '.png'
					image.save(path, 'png')
					selection.set_uris([ 'file://' + urllib.quote(path) ])
			
			if not hasattr(self, 'gtk_screen_image'):
				self.get_gtk_screen_image()
			self._effects = {}
			image = self.gtk_screen_image
			gtk.RESPONSE_COPY_TO_CLIPBOARD = 121
			gtk.RESPONSE_EFFECTS = 124
			gtk.RESPONSE_UPLOAD = 123
			gtk.RESPONSE_SAVE = 122
			gtk.stock_add([ ('srceenshot-effects', Lang.get('_Effects'), 0, 0, '') ])
			gtk.stock_add([ (gtk.STOCK_GO_UP, Lang.get('_Upload'), 0, 0, '') ])
			saveDialog = gtk.Dialog(title = Lang.get('Save screenshot'), flags = gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, buttons = (
			gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
			'srceenshot-effects', gtk.RESPONSE_EFFECTS,
			gtk.STOCK_COPY, gtk.RESPONSE_COPY_TO_CLIPBOARD,
			gtk.STOCK_GO_UP, gtk.RESPONSE_UPLOAD,
			gtk.STOCK_SAVE, gtk.RESPONSE_SAVE))
			previewImageWidth = float(image.get_width())
			previewImageHeight = float(image.get_height())
			if previewImageWidth / previewImageHeight > 3:
				previewImageHeight = int(round((600 / previewImageWidth) * previewImageHeight))
				previewImageWidth = 600
			else:
				previewImageWidth = int(round((300 / previewImageHeight) * previewImageWidth))
				previewImageHeight = 300
			previewImage = image.scale_simple(previewImageWidth, previewImageHeight, gtk.gdk.INTERP_BILINEAR)
			widgetImage = gtk.image_new_from_pixbuf(previewImage)
			widgetFrame = gtk.Frame()
			widgetFrame.set_border_width(2)
			widgetFrame.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color('#999'))
			eeventBox = gtk.EventBox()
			eeventBox.connect('drag_begin', dnd_begin)
			eeventBox.connect('drag_data_get', dnd_send_data)
			eeventBox.connect('realize', lambda w: w.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.FLEUR)))
			eeventBox.drag_source_set(gtk.gdk.BUTTON1_MASK, [ ('image/png', gtk.TARGET_OTHER_APP, 100), ('text/uri-list', gtk.TARGET_OTHER_APP, 101) ], gtk.gdk.ACTION_COPY)
			eeventBox.add(widgetImage)
			widgetFrame.add(eeventBox)
			widgetFrame.show_all()
			saveDialog.vbox.pack_start(widgetFrame)
			saveDialog.connect('response', response)
			saveDialog.run()
			delattr(self, 'gtk_screen_image')
		else:
			time.sleep(self.config['delay'])
			os.system(self.screenshotProgram)
	
	def start_by_printscr(self, value, check = None):
		
		self.config['start-by-printscr'] = value
		self.chooseAction.set_sensitive(value)
		NanoshotPath = os.path.join(os.sys.path[0], os.path.basename(os.sys.argv[0]))
		action = NanoshotPath + ' ' + self.config['associated-action']
		actions = (NanoshotPath + ' -a', NanoshotPath + ' -c', NanoshotPath + ' -f', NanoshotPath + ' -p', NanoshotPath + ' -t')
		if check is not None and check.active != value:
			check.set_active(value)
		try:
			import gconf
		except ImportError:
			gconf = None
		gcpaths = ('/apps/compiz/plugins/gnomecompat/allscreens/options/command_screenshot', '/apps/metacity/keybinding_commands/command_screenshot')
		gcpathsWindow = ('/apps/compiz/plugins/gnomecompat/allscreens/options/command_window_screenshot', '/apps/metacity/keybinding_commands/command_window_screenshot')
		if gconf is not None:
			client = gconf.client_get_default()
			client.add_dir('/apps/metacity/keybinding_commands', gconf.CLIENT_PRELOAD_NONE)
			client.add_dir('/apps/compiz/plugins/gnomecompat/allscreens/options', gconf.CLIENT_PRELOAD_NONE)
			if client.key_is_writable(gcpaths[0]) and client.key_is_writable(gcpathsWindow[0]):
				for path in gcpaths:
					if value:
						if client.get_string(path) not in actions:
							self.config['prev-tool'] = client.get_string(path)
						client.set_string(path, action)
					else:
						if client.get_string(path) == self.config['prev-tool']:
							continue
						elif client.get_string(path) != action:
							self.config['prev-tool'] = client.get_string(path)
						else:
							client.set_string(path, self.config['prev-tool'])
				for path in gcpathsWindow:
					if value:
						if client.get_string(path) == NanoshotPath + ' -c':
							continue
						self.config['prev-tool-window'] = client.get_string(path)
						client.set_string(path, NanoshotPath + ' -c')
					else:
						if client.get_string(path) == self.config['prev-tool-window']:
							continue
						elif client.get_string(path) != NanoshotPath + ' -c':
							self.config['prev-tool-window'] = client.get_string(path)
						else:
							client.set_string(path, self.config['prev-tool-window'])
			else:
				self.config['start-by-printscr'] = not value
				check.set_active(not value)
				check.set_sensitive(False)
				self.chooseAction.set_sensitive(False)
		elif self.is_x_available('gconftool-2'):
			for path in gcpaths:
				if value:
					os.system('gconftool-2 --set "' + path + '" --type string "' + action + '"')
				else:
					os.system('gconftool-2 --set "' + path + '" --type string "' + self.config['prev-tool'] + '"')
			for path in gcpathsWindow:
				if value:
					os.system('gconftool-2 --set "' + path + '" --type string "' + NanoshotPath + ' -c"')
				else:
					os.system('gconftool-2 --set "' + path + '" --type string "' + self.config['prev-tool-window'] + '"')
	
	def is_run_at_startup(self):
		
		startupDesktopFile = self.startupDesktopFile
		if not os.path.isfile(startupDesktopFile):
			return False
		try:
			openedFile = open(startupDesktopFile, 'r')
		except:
			return False
		if openedFile.read().find('X-GNOME-Autostart-enabled=true') != -1:
			return True
		return False
	
	def run_at_startup(self, checkMenuItem):
		
		startupDesktopFile = self.startupDesktopFile
		if checkMenuItem.active:
			if not os.path.isfile(startupDesktopFile) and os.path.exists(startupDesktopFile):
				self.error(Lang.get('Strange, but you have a directory or a block device with the name "%s", which does not allow to create a file with that name in the directory %s.') % ('Nanoshot.desktop', '~/.config/autostart'))
				checkMenuItem.set_active(False)
			else:
				try:
					if os.path.isfile(startupDesktopFile):
						openedFile = open(startupDesktopFile, 'r')
						if openedFile.read().find('X-GNOME-Autostart-enabled=true') != -1:
							openedFile.close()
							return False
						openedFile.close()
					openedFile = open(startupDesktopFile, 'w')
				except IOError:
					self.error(Lang.get('Unable to create / overwrite file \"%s\". Check the file and directory permissions.') % startupDesktopFile)
					checkMenuItem.set_active(False)
					return False;
				openedFile.write('\n[Desktop Entry]\nEncoding=UTF-8\nType=Application\nExec=' + os.path.join(os.sys.path[0], os.path.basename(os.sys.argv[0]))
				 + '\nHidden=false\nX-GNOME-Autostart-enabled=true\nName=Nanoshot\nCategories=Utility\nComment=Fast and convenient way to take a screenshot\nComment[' + os.getenv('LANG').split('.')[0]
				 + ']=' + Lang.get('Fast and convenient way to take a screenshot') + '\nIcon=Nanoshot')
				openedFile.close()
		elif os.path.isfile(startupDesktopFile):
			try:
				openedFile = open(startupDesktopFile, 'r+')
			except IOError:
				self.error(Lang.get('Unable to create / overwrite file \"%s\". Check the file and directory permissions.' % startupDesktopFile))
				checkMenuItem.set_active(True)
				return False
			fileContent = openedFile.read()
			if fileContent.find('X-GNOME-Autostart-enabled=false') != -1:
				openedFile.close()
				return False
			openedFile.seek(0)
			openedFile.write(fileContent.replace('X-GNOME-Autostart-enabled=true', 'X-GNOME-Autostart-enabled=false'))
			openedFile.close()
	
	def open_url(self, widget, url):
		
		try:
			import gnome
			gnome.url_show(url)
			return True
		except:
			try:
				import webbrowser
				webbrowser.open(url)
				return True
			except:
				''' Okay, we'll try to use the first matching browser '''
				paths = os.getenv('PATH').split(os.pathsep)
				for path in paths:
					for browser in ['firefox', 'iceweasel', 'chromium', 'opera', 'konqueror', 'arora', 'epiphany']:
						if os.access(path + '/' + browser, os.X_OK):
							os.system(browser + ' ' + url)
							return True
		self.error(Lang.get('There is no any browsers in your system.'))
	
	def about(self, widget):
		
		aboutDialog = gtk.AboutDialog()
		aboutDialog.set_name('Nanoshot')
		aboutDialog.set_version(NANOSHOT_VERSION)
		aboutDialog.set_copyright('Copyright © 2010')
		aboutDialog.set_comments(Lang.get('Fast and convenient way to take a screenshot'))
		aboutDialog.set_license(Lang.get('This program is free software and licensed under the GNU General Public License (GNU GPL) v2.\nThis means that you can freely use, distribute and modify the program under license GPL.\n\nFor more information about the GNU General Public License v2 see http://www.gnu.org/licenses/gpl-2.0.html'))
		aboutDialog.set_wrap_license(True)
		aboutDialog.set_website('http://vladx.net/')
		aboutDialog.set_authors(['VladX <me@vladx.net>'])
		aboutDialog.set_artists(['VladX <me@vladx.net>'])
		aboutDialog.set_translator_credits(Lang.get('Translator credits'))
		aboutDialog.set_logo_icon_name('Nanoshot-about')
		aboutDialog.connect('response', lambda d, i: d.destroy())
		aboutDialog.show()
	
	def error(self, text):
		
		try:
			errorDialog = gtk.MessageDialog(type = gtk.MESSAGE_ERROR, buttons = gtk.BUTTONS_OK, message_format = text)
			errorDialog.set_title(Lang.get('Some error occurred!'))
			errorDialog.connect('response', lambda d, i: d.destroy())
			errorDialog.run()
		except:
			print(text)
	
	def main(self):
		
		gtk.main()

class Lang:
	
	def __init__(self):
		
		gettext.bindtextdomain('Nanoshot', NANOSHOT_LOCALE_DIR)
		gettext.textdomain('Nanoshot')
	
	@staticmethod
	def get(text):
		
		return gettext.gettext(text)


def parse_argv(args):
	
	localeDir = NANOSHOT_LOCALE_DIR
	iconsDir = NANOSHOT_ICONS_DIR
	hostingsDir = NANOSHOT_HOSTINGS_DIR
	windowMode = False
	doAtLaunch = None
	for i, arg in enumerate(args):
		if arg == '-h' or arg == '--help':
			print('\nUsage: %s [options...]' % os.path.basename(args[0]))
			print('\nOptions:\n  -h, --help    \tShow this message\n  -v, --version   \tShow version number\n  -a, --area      \tStart the selection of the area during launch\n  -c, --window    \tCapture the active window during launch\n  -f, --video     \tCapture frames from a video during launch\n  -p, --web-page  \tTake a screenshot of a web page during launch\n  -t, --take      \tTake a screenshot during launch\n  -l, --locale-dir\tSet the directory with the localization .mo files\n  -i, --icons-dir\tSet the directory with icons\n  -H, --hostings-dir\tSet the hostings directory\n  -w, --window-mode\tRun program in window mode (for developers)\n\nCopyright (c) 2010, <http://vladx.net>')
			os.sys.exit(0)
		elif arg == '-v' or arg == '--version':
			print('Nanoshot ' + NANOSHOT_VERSION)
			os.sys.exit(0)
		elif (arg == '-l' or arg == '--locale-dir') and i < len(args) - 1:
			localeDir = args[i + 1]
		elif (arg == '-i' or arg == '--icons-dir') and i < len(args) - 1:
			iconsDir = args[i + 1]
		elif (arg == '-H' or arg == '--hostings-dir') and i < len(args) - 1:
			hostingsDir = args[i + 1]
		elif arg == '-w' or arg == '--window-mode':
			windowMode = True
		elif arg in ('-a', '--area', '-c', '--window', '-f', '--video', '-p', '--web-page', '-t', '--take'):
			map(lambda s, r: arg == r and args.__setitem__(i, s), ('-a', '-c', '-f', '-p', '-t'), ('--area', '--window', '--video', '--web-page', '--take'))
			doAtLaunch = args[i]
	return localeDir, iconsDir, hostingsDir, windowMode, doAtLaunch

if __name__ == '__main__':
	windowMode = False
	doAtLaunch = None
	if len(os.sys.argv) > 1:
		localeDir, iconsDir, hostingsDir, windowMode, doAtLaunch = parse_argv(os.sys.argv)
		NANOSHOT_LOCALE_DIR = localeDir
		NANOSHOT_ICONS_DIR = iconsDir
		NANOSHOT_HOSTINGS_DIR = hostingsDir
	import wnck
	DBusGMainLoop(set_as_default = True)
	Imagehosting.load(NANOSHOT_HOSTINGS_DIR)
	nanoshot = Nanoshot(windowMode, doAtLaunch)
	nanoshot.main()
