#!/usr/bin/env python
#coding=utf-8
#########################################################
#                                                       #
# This is GNOME Run Dialog v1.7.0                       #
#                                                       #
# Licensed under GNU GENERAL PUBLIC LICENSE v3          #
#                                                       #
# Copyright 2008 - 2009 Christopher Bratusek            #
#                                                       #
#########################################################

MODULES = [ 'os', 'sys', 'gtk', 'gtk.gdk', 'gtk.keysyms', 'gobject',
            'locale', 'gettext', 'gconf', 'subprocess' ]

FAILED = list()

for module in MODULES:
	try:
		globals()[module] =__import__(module)
	except ImportError:
		FAILED.append(module)

if FAILED:
    print "The following modules failed to import: %s" % (" ".join(FAILED))
    sys.exit(1)

_ = gettext.gettext
APP_NAME = "gnome-run-dialog"

gtkbuilder = gtk.Builder()

gdb = gconf.client_get_default()
gkey = "/apps/gnome-settings/gnome-panel/history-gnome-run"

class GRD17:

	def __init__(self):

		langs = []
		lc, encoding = locale.getdefaultlocale()
		if (lc):
			langs = [lc]
		language = os.environ.get('LANGUAGE', None)
		if (language):
			langs += language.split(":")
		langs += ["C"]

		gettext.bindtextdomain(APP_NAME)
		gettext.textdomain(APP_NAME)
		self.lang = gettext.translation(APP_NAME, languages=langs, fallback = True)
		global _
		_ = self.lang.gettext
		gtkbuilder.set_translation_domain(APP_NAME)
		gtkbuilder.add_from_file("/usr/share/gnome-run-dialog/gnome-run-dialog.ui")

		os.chdir(os.getenv("HOME"))

		bindings = gtk.AccelGroup()

		self.window = gtkbuilder.get_object("MainWindow")
		self.window.connect("destroy", gtk.main_quit)
		self.window.add_accel_group(bindings)

		self.run_with = gtkbuilder.get_object("run_with")
		self.run_with.connect("file-set", self.append_file)

		self.run_button = gtkbuilder.get_object("run_button")
		self.run_button.connect("clicked", self.run)
		self.run_button.add_accelerator("clicked", bindings, gtk.keysyms.Return, gtk.gdk.CONTROL_MASK , gtk.ACCEL_LOCKED)

		self.terminal_checkbox = gtkbuilder.get_object("terminal_checkbox")
		self.terminal_checkbox.add_accelerator("clicked", bindings, ord('t'), gtk.gdk.CONTROL_MASK, gtk.ACCEL_LOCKED)

		self.root_checkbox = gtkbuilder.get_object("root_checkbox")
		self.root_checkbox.add_accelerator("clicked", bindings, ord('r'), gtk.gdk.CONTROL_MASK, gtk.ACCEL_LOCKED)

		self.history_list = gtkbuilder.get_object("history_list")
		self.history_list.connect("changed", self.set_history_command)
		self.history_list.add_accelerator("popup", bindings, ord('h'), gtk.gdk.CONTROL_MASK, gtk.ACCEL_LOCKED)

		self.entry_command = gtkbuilder.get_object("entry_command")

		self.clear_button = gtkbuilder.get_object("clear_button")
		self.clear_button.connect("clicked", self.clear_history)
		self.clear_button.add_accelerator("clicked", bindings, ord('c'), gtk.gdk.CONTROL_MASK, gtk.ACCEL_LOCKED)

		self.cancel_button = gtkbuilder.get_object("cancel_button")
		self.cancel_button.connect("clicked", gtk.main_quit)
		self.cancel_button.add_accelerator("clicked", bindings, ord('q'), gtk.gdk.CONTROL_MASK, gtk.ACCEL_LOCKED)

		self.liststore = gtk.ListStore(gobject.TYPE_STRING)
		self.history_list.set_model(self.liststore)
		self.cell = gtk.CellRendererText()
		self.history_list.pack_start(self.cell)
		self.history_list.add_attribute(self.cell, 'text', 0)

		self.history_list.append_text("Command History:")
		self.history_list.set_active(0)

		self.history = []
		self.list = []

		self.history += gdb.get_list("/apps/gnome-settings/gnome-panel/history-gnome-run", "string")

		self.history.sort()

		for command in self.history:
			self.history_list.append_text(command)

		self.completion = gtk.EntryCompletion()
		self.liststore2 = gtk.ListStore(gobject.TYPE_STRING)

		for command in os.listdir("/usr/bin"):
			self.liststore2.append([command])
			self.list.append(command)
		self.completion.set_model(self.liststore2)

		for command in self.history:
			if command not in self.list:
				self.liststore2.append([command])
		self.entry_command.set_completion(self.completion)
		self.completion.set_text_column(0)

		if not os.access('/usr/bin/gksu', os.X_OK) and not os.access('/opt/gnome/bin/gksu', os.X_OK):
			self.root_checkbox.set_sensitive(0)

		self.terminal = gdb.get_string("/desktop/gnome/applications/terminal/exec")
		if self.terminal is "":
			self.terminal = "xterm"

		if not os.access('%s' % self.terminal, os.X_OK) and \
		not os.access('/usr/bin/%s' % self.terminal, os.X_OK):
			self.terminal_checkbox.set_sensitive(0)

	def clear_history(self, data=None):
		self.history_list.set_active(0)
		for command in self.history:
			self.history_list.remove_text(1)
		self.history = []
		gdb.set_list("/apps/gnome-settings/gnome-panel/history-gnome-run", "string", self.history)
		self.entry_command.set_text("")

	def set_history_command(self, data=None):
		self.model = self.history_list.get_model()
		self.active = self.history_list.get_active()
		self.command = self.model[self.active][0]
		if self.active != 0:
			self.entry_command.set_text("%s" % self.command)

	def append_file(self, data=None):
		self.position = self.entry_command.get_position()
		if self.run_with.get_filename() != None:
			self.entry_command.insert_text(" %s" % self.run_with.get_filename(), self.position)

	def run(self, data=None):
		if self.entry_command.get_text() != "":
			use_terminal = self.terminal_checkbox.get_active()
			be_root = self.root_checkbox.get_active()
			cmd = self.entry_command.get_text()
			if use_terminal and be_root:
				subprocess.Popen("gksu -u root " + "\'" + self.terminal + " -e " + cmd + "\'", shell=True)
			elif use_terminal and not be_root:
				subprocess.Popen(self.terminal + " -e " + cmd, shell=True)
			elif not use_terminal and be_root:
				subprocess.Popen("gksu -u root " + cmd, shell=True)
			else:
				subprocess.Popen(cmd, shell=True)
			if cmd not in self.history:
				self.history.append(cmd)
				self.history.sort()
				gdb.set_list(gkey, "string", self.history)
			gtk.main_quit()

		gtkbuilder.connect_signals(self)

if __name__ == "__main__":
	hwg = GRD17()
	gtk.main()
