""" Bookmarks v.0.1b, python script fo glimmer """
import glimmer
import string
import sys
import os
sys.argv=[]
sys.argv.append("null")
from gtk import *
import _gtk
import _gnome
import _gnomeui
from gnome.ui import *
import gnome.config
#
def dialog(mitem,text="dialog? what?",btCan=FALSE,btOk=TRUE,what=0):
	global current_node
	dlWin = GtkWindow()
	dlWin.set_modal(TRUE)
	dlWin.set_title(text)
	dlWin.set_resize_mode(0)
	dlWin.set_default_size(300,150)
	#
	dlNuttonOK = GtkButton("Ok")
	dlNuttonOK.show()
	#
	dlVBox = GtkVBox(FALSE, 0)
	dlVBox.show()
	
	if what == 0:   ###### message
		dlFrame = GtkFrame()
		dlFrame.show()
		dlLabel = GtkLabel(text)
		dlLabel.show()
		dlFrame.add(dlLabel)
		_gtk.gtk_signal_connect(dlNuttonOK._o, "clicked", dlWin.destroy)
	elif what == 1: ###### add bookmark
		dlFrame = GtkFrame(text)
		dlFrame.show()
		dlTable = GtkTable(2, 2, TRUE)
		dlTable.set_homogeneous(FALSE)
		dlTable.show()
		## name
		dlLblName = GtkLabel("name")
		dlLblName.show()
		dlTable.attach(dlLblName, 0, 1, 0, 1)
		dlEtyName = GtkEntry()
		dlEtyName.show()
		dlTable.attach(dlEtyName, 1, 2, 0, 1)
		## path
		dlLblPath = GtkLabel("path")
		dlLblPath.show()
		dlTable.attach(dlLblPath, 0, 1, 1, 2)
		dlEtyPath = GtkEntry()
		dlEtyPath.show()
		dlTable.attach(dlEtyPath, 1, 2, 1, 2)
		dlFrame.add(dlTable)
		if current_node != None:
			tmp = bmTree.node_get_row_data(current_node)
			if tmp != None:
				if tmp[1] == "dir":
					dlEtyPath.set_text(tmp[0])
					tmp = bmTree.get_node_info(current_node)
					dlEtyName.set_text(tmp[0])
		args = (dlEtyName,dlEtyPath,dlWin)
		_gtk.gtk_signal_connect(dlNuttonOK._o, "clicked", add_bm, args)
	elif what == 4: ###### delete
		dlFrame = GtkFrame()
		dlFrame.show()
		if current_node != None:
			tmp = bmTree.node_get_row_data(current_node)
			if tmp != None:
				if tmp[1] == "bm":
					info = bmTree.get_node_info(current_node)
					dlLabel = GtkLabel("Delete bookmark: '" + info[0] +"'?")
					args = (tmp[4],dlWin,)
					_gtk.gtk_signal_connect(dlNuttonOK._o, "clicked", del_bm, args)
				elif tmp[1] == "bmr":
					dlLabel = GtkLabel("NO!")
					btCan = FALSE
					_gtk.gtk_signal_connect(dlNuttonOK._o, "clicked", dlWin.destroy)
				else:
					dlLabel = GtkLabel("NOT YET!!!")
					btCan = FALSE
					_gtk.gtk_signal_connect(dlNuttonOK._o, "clicked", dlWin.destroy)
			else:
				btCan = FALSE
				dlLabel = GtkLabel("ERRORE!!!!!")
				_gtk.gtk_signal_connect(dlNuttonOK._o, "clicked", dlWin.destroy)
		else:
			btCan = FALSE
			dlLabel = GtkLabel("ERRORE!!!!!")
			_gtk.gtk_signal_connect(dlNuttonOK._o, "clicked", dlWin.destroy)
		dlLabel.show()
		dlFrame.add(dlLabel)
	#
	dlVBox.add(dlFrame)
	dlHBBox = GtkHButtonBox()
	dlHBBox.set_layout(1)
	dlHBBox.show()
	dlVBox.pack_end(dlHBBox,FALSE,TRUE,0)
	#
	if btOk:
		dlHBBox.add(dlNuttonOK)
	if btCan:
		dlNuttonCanc = GtkButton("Cancel")
		dlNuttonCanc.show()
		dlHBBox.add(dlNuttonCanc)
		_gtk.gtk_signal_connect(dlNuttonCanc._o, "clicked", dlWin.destroy)
	#
	dlWin.add(dlVBox)
	dlWin.show()

def get_bm_id():
	i = 0
	tmp = gnome.config.get_vector("/glimmer/Bookmarks/bm"+str(i))
	while tmp != ():
		if tmp[0] == "null": return str(i)
		i = i + 1
		tmp = gnome.config.get_vector("/glimmer/Bookmarks/bm"+str(i))
	return str(i)

def add_bm(button, name, path, widget):
	import string
	if os.path.isdir(path.get_text()):
		tmp = []
		tmp.append(name.get_text())
		tmp.append(string.strip(path.get_text()))
		gnome.config.set_vector("/glimmer/Bookmarks/bm"+ get_bm_id(),tmp)
		gnome.config.sync()
		reloadTree(bmMenuReload)
	else:
		dialog(None,"'"+path.get_text()+"' not found",FALSE,TRUE,0)
	widget.destroy()

def del_bm(button, id,widget):
	tmp = []
	tmp.append("null")
	tmp.append("")
	gnome.config.set_vector("/glimmer/Bookmarks/bm" + str(id),tmp)
	gnome.config.sync()
	widget.destroy()
	reloadTree(bmMenuReload)

def rtrim(stringa, ch=1):
	tmp = ""
	i = 0
	if ch < len(stringa):
		while i < (len(stringa)-ch):
			tmp = tmp + stringa[i]
			i = i + 1
	return tmp

def tree_collapse(ctree, ctree_node):
	global current_node
	bmTree.select(ctree_node)
	current_node = ctree_node.parent

def tree_expand(ctree, ctree_node):
	tmp = bmTree.node_get_row_data(ctree_node)
	bmTree.select(ctree_node)
	if tmp[2]== "0":
		if tmp[1] == "bm":
			new = [tmp[0],tmp[1],"1",tmp[3],tmp[4]]
		else:	
			new = [tmp[0],tmp[1],"1",tmp[3]]
		bmTree.node_set_row_data(ctree_node,new)
		readdir(ctree_node, tmp[0],tmp[3])

def tree_select(ctree, node, column):
	global current_node
	current_node = node

def readdir(ctree_node,path, loading=None):
	import dircache
	import string
	if os.path.isdir(path):
		dirlisting = dircache.listdir(path)
		dirlisting = dirlisting[:]
		dircache.annotate(path, dirlisting)
		num = 0
		dlen = len(dirlisting)
		bmTree.freeze()
		while num < dlen:
			if string.count(dirlisting[num], "/") > 0:
				if not bmMenuCheckHidden.active:
					if dirlisting[num][0] != ".":
						hOK = TRUE 
					else: 
						hOK = FALSE
				else:
					hOK = TRUE
				if hOK:
					dname = rtrim(dirlisting[num])
					tmp = [dname,""]
					node = bmTree.insert_node(ctree_node,None,tmp,0,None,None,None,None,FALSE,FALSE)
					lnode = bmTree.insert_node(node,None,["Loading",""])
					if path != "/":
						tmp = path + "/" + dname
					else:
						tmp = path + dname
					tmp = [tmp,"dir","0",lnode]
					bmTree.node_set_row_data(node,tmp)
			num = num + 1
		num = 0
		while num < dlen:
			if string.count(dirlisting[num], "/") <= 0:
				if not bmMenuCheckHidden.active:
					if dirlisting[num][0] != ".": 
						hOK = TRUE 
					else: 
						hOK = FALSE
				else:
					hOK = TRUE
				if hOK:
					tmp = []
					tmp.append(dirlisting[num])
					tmp.append("")
					node = bmTree.insert_node(ctree_node,None,tmp)
					if path != "/":
						tmp = path + "/" + dirlisting[num]
					else:
						tmp = path + dirlisting[num]
					tmp = [tmp,"file","0"]
					bmTree.node_set_row_data(node,tmp)
			num = num + 1
		bmTree.thaw()
		#
		if dlen == 0: 
			bmTree.node_set_text(loading,0,"Empty")
			loading = None
		if loading != None: 
			bmTree.remove_node(loading)
	else:
		bmTree.insert_node(ctree_node,None,["error"]);
		print("errore, ma porc....")
	del dircache
	del string
	
def ctree_event(object, event):
	# popup menu
	global current_node
	if event.type == GDK.BUTTON_PRESS and event.button == 3:
		bmMenu.popup(None,None,None,3,0);
	if event.type == GDK._2BUTTON_PRESS and event.button == 1:
		tmp = bmTree.node_get_row_data(current_node)
		if tmp != None:
			if tmp[1] == "file":
				filename = tmp[0]
				glimmer.open_file(filename)

def Un_Attach(Null):
	if gnome.config.get_bool("/glimmer/Bookmarks/Attached"):
		#
		gnome.config.set_bool("/glimmer/Bookmarks/Attached", FALSE)
		gnome.config.sync()
		#
		bmWindow.remove(bmVBoxContenitore)
		#bmVBoxContenitore.unparent()
		glimmer.add_paned_object(bmVBoxContenitore._o, "Bookmarks", 0);
		bmWindow.hide()
		#
		bmLabelAttach.set_text("Unattach")
	else:
		#
		gnome.config.set_bool("/glimmer/Bookmarks/Attached", TRUE)
		gnome.config.sync()
		#
		glimmer.remove_paned_object("Bookmarks")
		bmWindow.add(bmVBoxContenitore)
		#bmVBoxContenitore.set_parent(bmWindow)
		bmWindow.show()
		#
		bmLabelAttach.set_text("Attach");

def Chiudi(null):
	if gnome.config.get_bool("/glimmer/Bookmarks/Attached"):
		bmWindow.destroy()
	else:
		glimmer.remove_paned_object("Bookmarks")

def set_show_hidden_files(null):
	gnome.config.set_bool("/glimmer/Bookmarks/show_hidden", bmMenuCheckHidden.active)
	gnome.config.sync()
	reloadTree(bmMenuReload)

def reloadTree (object):
	global current_node
	paths = []
	if current_node != None:
		if bmTree.node_get_row_data(current_node)[2] == "1":
			node = current_node
		else:
			node = current_node.parent
		while node != None:
			paths.append(bmTree.node_get_row_data(node)[0])
			node = node.parent
		tmp = []
		for i in paths[:]:
			tmp.insert(0,i)
		paths = tmp
	buildtree()
	nodes = bmTree.base_nodes()
	l = len(paths)
	for i in range(0,l):
		for node in nodes:
			if bmTree.node_get_row_data(node)[0] == paths[i]:
				bmTree.expand(node)
				break
		nodes = node.children

def buildtree():
	# set root bookmark
	bmTree.clear()
	tmp = ["root"]
	node = bmTree.insert_node(None,None,tmp,0,None,None,None,None,FALSE,FALSE)
	lnode = bmTree.insert_node(node,None,["Loading",""])
	tmp = ["/","bmr","0",lnode]
	bmTree.node_set_row_data(node,tmp)
	# set home
	if os.environ.has_key('HOME'):
		tmp = ["home"]
		node = bmTree.insert_node(None,None,tmp,0,None,None,None,None,FALSE,FALSE)
		envHome = os.environ['HOME']
		lnode = bmTree.insert_node(node,None,["Loading",""])
		tmp = [envHome,"bmr","0",lnode]
		bmTree.node_set_row_data(node,tmp)
	# others personal bookmarks
	i = 0
	tmp = gnome.config.get_vector("/glimmer/Bookmarks/bm"+str(i))
	while tmp != ():
		if tmp[0] != "null":
			node = bmTree.insert_node(None,None,[tmp[0]],0,None,None,None,None,FALSE,FALSE)
			if os.path.isdir(tmp[1]):
				lnode = bmTree.insert_node(node,None,["Loading",""])
				tmp = [tmp[1],"bm","0",lnode,str(i)]
				bmTree.node_set_row_data(node,tmp)
			else:
				lnode = bmTree.insert_node(node,None,["path not found",""])
				tmp = [tmp[1],"bm","0",lnode,str(i)]
				bmTree.node_set_row_data(node,tmp)
				print("error! :(")
		i = i + 1
		tmp = gnome.config.get_vector("/glimmer/Bookmarks/bm"+str(i))

#
current_node = None
#
Attached = gnome.config.get_bool("/glimmer/Bookmarks/Attached")
bmWindow = GtkWindow()
bmWindow.set_title("Bookmarks")
bmWindow.set_default_size(160,290)
#
bmVBoxContenitore = GtkVBox(FALSE, 0)
bmVBoxContenitore.show()
# create bmHBoxComandi
bmHBoxComandi = GtkHBox()
bmHBoxComandi.show()
#create Attach Button
bmButtonAttach = GtkButton()
bmLabelAttach = GtkLabel()
bmLabelAttach.show()
bmButtonAttach.add(bmLabelAttach)
bmButtonAttach.set_usize(70,20)
bmButtonAttach.show()
#create  close button
bmButtonChiudi = GtkButton("Close")
bmButtonChiudi.set_usize(50,20)
bmButtonChiudi.show()
# add buttons to bmHBoxComandi
bmHBoxComandi.pack_start(bmButtonAttach, FALSE, TRUE, 0)
bmHBoxComandi.pack_start(bmButtonChiudi, FALSE, TRUE, 0)
# add bmHBoxComandi to bmVBoxContenitore
bmVBoxContenitore.pack_start(bmHBoxComandi, FALSE, FALSE, 2)
# create bmTreeWindow
bmTreeWindow = GtkScrolledWindow()
bmTreeWindow.set_usize(140, 100)
bmTreeWindow.show()
# create bmTree
bmTree = GtkCTree()
bmTree.set_line_style(CTREE_LINES_NONE)
bmTree.set_expander_style(CTREE_EXPANDER_TRIANGLE)
#bmTree.set_indent(4)
bmTree.show()
# insert bmTree into bmTreeWindow
bmTreeWindow.add(bmTree)
# add bmTreeWindow into bmVBoxContenitore
bmVBoxContenitore.pack_start(bmTreeWindow, TRUE, TRUE, 2)
# create popup menu							
bmMenu = GtkMenu()
bmMenuNewBookmark = GtkMenuItem("New BookMark")
bmMenu.append(bmMenuNewBookmark)
bmMenuNewBookmark.show()

bmMenuDelete = GtkMenuItem("Delete")
bmMenuDelete.show()
bmMenu.append(bmMenuDelete)

bmMenuCheckHidden = GtkCheckMenuItem("Show Hidden Files")
bmMenu.append(bmMenuCheckHidden)
bmMenuCheckHidden.set_active(gnome.config.get_bool("/glimmer/Bookmarks/show_hidden"))
bmMenuCheckHidden.show()

bmMenuReload = GtkMenuItem("Reload Tree")
bmMenuReload.show()
bmMenu.append(bmMenuReload)

bmMenu.show()

if Attached:
	bmWindow.add(bmVBoxContenitore)
	bmLabelAttach.set_text("Attach")
	bmWindow.show()
else:
	bmLabelAttach.set_text("Unattach")
	glimmer.add_paned_object(bmVBoxContenitore._o, "Bookmarks", 0);

# area test
buildtree()
# signals:
_gtk.gtk_signal_connect(bmButtonChiudi._o, "clicked", Chiudi)

_gtk.gtk_signal_connect(bmButtonAttach._o, "clicked", Un_Attach)

_gtk.gtk_signal_connect(bmTree._o, "event", ctree_event)

_gtk.gtk_signal_connect(bmMenuCheckHidden._o, "toggled", set_show_hidden_files)

_gtk.gtk_signal_connect(bmTree._o, "tree_select_row",tree_select)

_gtk.gtk_signal_connect(bmTree._o, "tree_expand",tree_expand)

_gtk.gtk_signal_connect(bmTree._o, "tree_collapse",tree_collapse)

args = ("New Boormark",TRUE,TRUE,1,)
_gtk.gtk_signal_connect(bmMenuNewBookmark._o, "activate", dialog, args)

args = ("Delete",TRUE,TRUE,4)
_gtk.gtk_signal_connect(bmMenuDelete._o, "activate", dialog, args)

_gtk.gtk_signal_connect(bmMenuReload._o, "activate", reloadTree)