# Copyright 2004,2005 Pierre Martineau <pmartino@users.sourceforge.net>
# This file is part of Bibus, a bibliographic database that can
# work together with OpenOffice.org to generate bibliographic indexes.
#
# Bibus 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.
#
# Bibus 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 Bibus; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA.
#
# generated by wxGlade 0.3.4 on Fri Apr  8 01:11:09 2005

import wx
import os.path, cPickle, copy
import BIB, ShortcutEd

class NewCategory(wx.Dialog):
	def __init__(self, categories, *args, **kwds):
		self.categories = categories  # current categories in parent. may be different from BIB.SHORTCUTS
		# begin wxGlade: NewCategory.__init__
		kwds["style"] = wx.DIALOG_MODAL|wx.CAPTION|wx.RESIZE_BORDER|wx.THICK_FRAME
		wx.Dialog.__init__(self, *args, **kwds)
		self.label_1 = wx.StaticText(self, -1, _("Name"))
		self.text_ctrl_name = wx.TextCtrl(self, -1, "")
		self.button_file = wx.Button(self, -1, _("File ..."))
		self.text_ctrl_filen = wx.TextCtrl(self, -1, "")
		self.button_cancel = wx.Button(self, -1, _("Cancel"))
		self.button_ok = wx.Button(self, -1, _("OK"))

		self.__set_properties()
		self.__do_layout()
		# end wxGlade
		self.__set_evt()

	def __set_properties(self):
		# begin wxGlade: NewCategory.__set_properties
		self.SetTitle(_("Create a new category"))
		self.button_ok.SetDefault()
		# end wxGlade

	def __do_layout(self):
		# begin wxGlade: NewCategory.__do_layout
		sizer_4 = wx.BoxSizer(wx.VERTICAL)
		sizer_5 = wx.BoxSizer(wx.HORIZONTAL)
		grid_sizer_1 = wx.FlexGridSizer(2, 2, 5, 5)
		grid_sizer_1.Add(self.label_1, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL, 0)
		grid_sizer_1.Add(self.text_ctrl_name, 0, wx.EXPAND, 0)
		grid_sizer_1.Add(self.button_file, 0, wx.ALIGN_RIGHT, 0)
		grid_sizer_1.Add(self.text_ctrl_filen, 0, wx.EXPAND, 0)
		grid_sizer_1.AddGrowableRow(1)
		grid_sizer_1.AddGrowableCol(1)
		sizer_4.Add(grid_sizer_1, 0, wx.EXPAND, 0)
		sizer_5.Add(self.button_cancel, 0, wx.ALL, 5)
		sizer_5.Add(self.button_ok, 0, wx.ALL, 5)
		sizer_4.Add(sizer_5, 0, wx.ALIGN_RIGHT, 0)
		self.SetAutoLayout(1)
		self.SetSizer(sizer_4)
		sizer_4.Fit(self)
		sizer_4.SetSizeHints(self)
		self.Layout()
		self.Centre()
		# end wxGlade

	def __set_evt(self):
		wx.EVT_BUTTON(self,self.button_ok.GetId(),self.onOK)			# default OK handler
		wx.EVT_BUTTON(self,self.button_cancel.GetId(),self.OnCancel)
		wx.EVT_BUTTON(self,self.button_file.GetId(),self.onFile)

	def OnCancel(self,evt):
		self.EndModal(wx.ID_CANCEL)

	def onFile(self,evt):
		tmpfilen = self.text_ctrl_name.GetValue()
		if not tmpfilen: tmpfilen = 'shortcut'
		filen = wx.FileSelector(_("Choose the file location and name"),default_filename=tmpfilen,parent=self, flags = wx.SAVE )
		if filen:
			self.text_ctrl_filen.SetValue(filen)

	def onOK(self,evt):
		"""We accept only if the file exists and if the category does not exist already"""
		filen = self.text_ctrl_filen.GetValue()
		category = self.text_ctrl_name.GetValue()
		if os.path.exists(os.path.dirname(filen)) and category not in self.categories:
			self.EndModal(wx.ID_OK)
		else:
			self.OnCancel(evt)

	def getSettings(self):
		"""Return the values of the textCtrl as a tuple (category,filename)."""
		return self.text_ctrl_name.GetValue() , self.text_ctrl_filen.GetValue()

# end of class NewCategory

class Pref_Shortcuts(wx.Panel):
	def __init__(self, db, *args, **kwds):
		self.db = db							# database connection
		self.categories = BIB.SHORTCUTS[:]		# categories in self.list_categories
		self.short = copy.deepcopy(BIB.SHORT)	# self.short[category] = [list shortcuts]
		# begin wxGlade: Pref_Shortcuts.__init__
		kwds["style"] = wx.TAB_TRAVERSAL
		wx.Panel.__init__(self, *args, **kwds)
		self.list_categories = wx.ListCtrl(self, -1, style=wx.LC_REPORT|wx.LC_EDIT_LABELS|wx.LC_NO_HEADER|wx.LC_SINGLE_SEL|wx.SUNKEN_BORDER)
		self.button_up = wx.Button(self, -1, _("Up"))
		self.button_down = wx.Button(self, -1, _("Down"))
		self.button_new = wx.Button(self, -1, _("New ..."))
		self.button_edit = wx.Button(self, -1, _("Edit ..."))
		self.button_remove = wx.Button(self, -1, _("Remove"))

		self.__set_properties()
		self.__do_layout()
		# end wxGlade
		self.__set_evt()

	def __set_properties(self):
		# begin wxGlade: Pref_Shortcuts.__set_properties
		pass
		# end wxGlade
		self.list_categories.InsertColumn(0,'shortcuts')
		for index in xrange(len(self.categories)):
			self.list_categories.InsertStringItem(index,self.categories[index])

	def __do_layout(self):
		# begin wxGlade: Pref_Shortcuts.__do_layout
		sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
		sizer_1 = wx.BoxSizer(wx.VERTICAL)
		sizer_2.Add(self.list_categories, 1, wx.ALL|wx.EXPAND, 5)
		sizer_1.Add(self.button_up, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 2)
		sizer_1.Add(self.button_down, 0, wx.ALIGN_CENTER_HORIZONTAL, 0)
		sizer_1.Add(self.button_new, 0, wx.TOP|wx.ALIGN_CENTER_HORIZONTAL, 10)
		sizer_1.Add(self.button_edit, 0, wx.TOP|wx.ALIGN_CENTER_HORIZONTAL, 2)
		sizer_1.Add(self.button_remove, 0, wx.TOP|wx.ALIGN_CENTER_HORIZONTAL, 2)
		sizer_2.Add(sizer_1, 0, wx.RIGHT|wx.ALIGN_CENTER_VERTICAL, 5)
		self.SetAutoLayout(1)
		self.SetSizer(sizer_2)
		sizer_2.Fit(self)
		sizer_2.SetSizeHints(self)
		# end wxGlade

	def __set_evt(self):
		wx.EVT_LIST_END_LABEL_EDIT(self,self.list_categories.GetId(),self.onRename)
		wx.EVT_LIST_ITEM_ACTIVATED(self,self.list_categories.GetId(),self.onEditShort)
		wx.EVT_BUTTON(self,self.button_new.GetId(),self.onNew)
		wx.EVT_BUTTON(self,self.button_remove.GetId(),self.onRemove)
		wx.EVT_BUTTON(self,self.button_up.GetId(),self.onUp)
		wx.EVT_BUTTON(self,self.button_down.GetId(),self.onDown)
		wx.EVT_BUTTON(self,self.button_edit.GetId(),self.onEditShort)
		wx.EVT_SIZE(self,self.onSize)

	def onRemove(self,evt):
		index = self.list_categories.GetFirstSelected()
		if index != -1:
			self.list_categories.DeleteItem(index)
			del self.categories[index]

	def onUp(self,evt):
		index = self.list_categories.GetFirstSelected()
		if index >= 1:
			previous = self.list_categories.GetItemText(index -1)
			self.list_categories.SetItemText(index -1,self.list_categories.GetItemText(index) )
			self.list_categories.SetItemText(index , previous)
			self.list_categories.Select(index - 1, True)
			self.categories[index -1] = self.categories[index]
			self.categories[index] = previous

	def onDown(self,evt):
		index = self.list_categories.GetFirstSelected()
		if index != -1 and index < self.list_categories.GetItemCount() -1:
			nextitem = self.list_categories.GetItemText(index +1)
			self.list_categories.SetItemText(index +1, self.list_categories.GetItemText(index) )
			self.list_categories.SetItemText(index , nextitem)
			self.list_categories.Select(index +1, True)
			self.categories[index +1] = self.categories[index]
			self.categories[index] = nextitem

	def onRename(self,evt):
		if evt.GetText() in self.categories:
			evt.Veto()	# the new name must not be already present
		else:
			self.categories[evt.GetIndex()] = evt.GetText()

	def onSize(self,evt):
		self.Layout()
		self.list_categories.SetColumnWidth(0,self.list_categories.GetClientSizeTuple()[0])

	def onNew(self,evt):
		categories = []
		for index in xrange(self.list_categories.GetItemCount()):
			categories.append( self.list_categories.GetItemText(index) )
		#
		dlg = wx.GetTextFromUser(_("Please, enter the new menu name"),_("New shortcut menu"),BIB.SHORTCUT_DEFAULT)
		if dlg != '':
			if dlg not in categories:
				self.categories.append( dlg )
				self.list_categories.Append( [dlg] )	# add to the list

	def onEditShort(self,evt):
		#index = evt.GetIndex()
		index = self.list_categories.GetFirstSelected()
		if not self.short.has_key( self.categories[index] ):
			self.short[self.categories[index]] = self.__getShort(self.categories[index])
		shEd = ShortcutEd.ShortcutEd(self.categories[index],self.short[self.categories[index]],self.db,self,-1,'')
		if shEd.ShowModal() == wx.ID_OK:
			pass	# nothing to do, self.short[self.categories[index]] modified in shEd.onOK
		shEd.Destroy()

	def __getShort(self,category):
		try:
			f = file( os.path.join( wx.StandardPaths.Get().GetUserDataDir(), "Shortcuts", category), 'r' )
			short = cPickle.load(f)		# we unpickle the file and check that it is a list of strings
			f.close()
			if type(short) != list: raise TypeError('notalist')
			else:
				for i in short:
					if type(i) not in (unicode,str): raise TypeError('notastring')
		except:
			short = []
		return short

	def getSettings(self):
		"""return the current values"""
		# getting the list of shortcuts from self.sort if exist or the files. Create the files if needed.
		for index in xrange(len(self.categories)):
			if not self.short.has_key( self.categories[index] ):
				self.short[ self.categories[index] ] = self.__getShort( self.categories[index] )
		return self.categories, self.short

# end of class Pref_Shortcuts


