File: view_tree.py

package info (click to toggle)
tinyerp-client 3.4.2-3
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 4,832 kB
  • ctags: 1,024
  • sloc: python: 7,566; sh: 2,253; makefile: 81
file content (359 lines) | stat: -rw-r--r-- 9,914 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
##############################################################################
#
# Copyright (c) 2004 TINY SPRL. (http://tiny.be) All Rights Reserved.
#                    Fabien Pinckaers <fp@tiny.Be>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# 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, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

import gtk
import gobject
from xml.parsers import expat

import options
import time

import rpc
import gettext
import parse

import copy

DT_FORMAT = '%Y-%m-%d'
DHM_FORMAT = '%Y-%m-%d %H:%M:%S'

# BUG: ids = []
#
# Tree struct:  [ id, values, childs, childs_id ]
#
#    values: [...]
#    childs: [ tree_struct ]
#            [] for no childs
#            None for undevelopped (with childs!)
#        assert: no childs => []
#
# Node struct: [list of (pos, list) ]
#
class view_tree_model(gtk.GenericTreeModel, gtk.TreeSortable):
	def __init__(self, ids, view, fields, fields_type, context={}, pixbufs={}, treeview=None):
		gtk.GenericTreeModel.__init__(self)
		self.fields = fields
		self.fields_type = fields_type
		self.view = view
		self.roots = ids
		self.context = context
		self.tree = self._node_process(self.roots)
		self.pixbufs = pixbufs
		self.treeview = treeview

	def _read(self, ids, fields):
		c = {}
		c.update(rpc.session.context)
		c.update(self.context)
		try:
			res_ids = rpc.session.rpc_exec_auth_try('/object', 'execute', self.view['model'], 'read', ids, fields, c)
		except:
			res_ids = []
			for id in ids:
				val = {'id':id}
				for f in fields:
					if self.fields_type[f]['type'] in ('one2many','many2many'):
						val[f]=[]
					else:
						val[f]=''
				res_ids.append(val)
		for field in self.fields:
			if self.fields_type[field]['type'] in ('date',):
				for x in res_ids:
					if x[field]:
						date = time.strptime(x[field], DT_FORMAT)
						x[field] = time.strftime('%x', date)
			if self.fields_type[field]['type'] in ('datetime',):
				for x in res_ids:
					if x[field]:
						date = time.strptime(x[field], DHM_FORMAT)
						x[field] = time.strftime('%x %H:%M:%S', date)
			if self.fields_type[field]['type'] in ('one2one','many2one'):
				for x in res_ids:
					if x[field]:
						x[field] = x[field][1]
			if self.fields_type[field]['type'] in ('selection'):
				for x in res_ids:
					if x[field]:
						x[field] = dict(self.fields_type[field]['selection']).get(x[field],'')
		return res_ids

	def _node_process(self, ids):
		tree = []
		if self.view.get('field_parent', False):
			res = self._read(ids, self.fields+[self.view['field_parent']])
			for x in res:
				tree.append( [ x['id'], None, [], x[self.view['field_parent']] ] )
				tree[-1][1] = [ x[ y ] for y in self.fields]
				if len(x[self.view['field_parent']]):
					tree[-1][2] = None
		else:
			res = self._read(ids, self.fields)
			for x in res:
				tree.append( [ x['id'],  [ x[y] for y in self.fields], [] ])
		return tree

	def _node_expand(self, node):
		node[2] = self._node_process(node[3])
		del node[3]

	def on_get_flags(self):
		return 0

	def on_get_n_columns(self):
		return len(self.fields)+1

	def on_get_column_type(self, index):
		if index in self.pixbufs:
			return gtk.gdk.Pixbuf
		fields_list_type = {
			'checkbox': gobject.TYPE_BOOLEAN,
			'integer': gobject.TYPE_INT,
			#'float': gobject.TYPE_FLOAT
		}
		return fields_list_type.get(self.fields_type[self.fields[index-1]]['type'],gobject.TYPE_STRING)

	def on_get_tree_path(self, node):
		'''returns the tree path (a tuple of indices)'''
		return tuple([ x[0] for x in node ])

	def on_get_iter(self, path):
		'''returns the node corresponding to the given path.'''
		node = []
		tree = self.tree
		if self.tree==[]:
			return None
		for x in path:
			node.append( (x, tree) )
			tree = tree[x][2]
		return node

	def on_get_value(self, node, column):
		(n, list) = node[-1]
		if column:
			value = list[n][1][column-1]
		else:
			value = list[n][0]
			
		if value==None or (value==False and type(value)==bool):
			res = ''
		else:
			res = value
		if (column in self.pixbufs) and res:
			return self.treeview.render_icon(stock_id=getattr(gtk, res), size=gtk.ICON_SIZE_MENU, detail=None)
		return res

	def on_iter_next(self, node):
		'''returns the next node at this level of the tree'''
		(n, list) = node[-1]
		if n<len(list)-1:
			node[-1] = (n+1, list)
			return node
		return None

	def on_iter_children(self, node):
		'''returns the first child of this node'''
		if node==None:                    # added
			return [ (0, self.tree) ]     # added
		(n, list) = node[-1]                 
		if list[n][2]==None:
			self._node_expand(list[n])
		if list[n][2]==[]:
			return None
		node.append( (0, list[n][2]) )
		return node

	def on_iter_has_child(self, node):
		'''returns true if this node has children'''
		(n, list) = node[-1]
		return list[n][2]!=[]

	def on_iter_n_children(self, node):
		'''returns the number of children of this node'''
		if node==None:                    # changed
			return len(self.tree)         # changed
		(n, list) = node[-1]
		if list[n][2]==None:
			self._node_expand(list[n])
		return len(list[n][2])

	def on_iter_nth_child(self, node, child):
		'''returns the nth child of this node'''
		if node==None:
			if child<len(self.tree):
				return [ (child, self.tree) ]
			return None
		else:
			(n, list) = node[-1]
			if list[n][2]==None:
				self._node_expand(list[n])
			if child<len(list[n][2]):
				node.append( (child, list[n][2]) )
				return node
			return None

	def on_iter_parent(self, node):
		'''returns the parent of this node'''
		if node==None:
			return None
		return node[:-1]

	def cus_refresh(self):
		tree = self.tree
		tree[0][2] = None

	def _cus_row_find(self, ids_res):
		tree = self.tree
		try:
			ids = ids_res[:]
			while len(ids)>0:
				if ids[-1] in self.roots:
					ids.pop()
					break
				ids.pop()
			path = []
			while ids!=[]:
				path.append(0)
				val = ids.pop()
				i = iter(tree)
				while True:
					node = i.next()
					if node[0]==val:
						break
					path[-1]+=1
				if (node[2]==None) and (ids!=[]):
					return None
				tree = node[2]
			return (tuple(path), node)
		except:
			return None

class view_tree(object):
	def __init__(self, view_info, ids, res_id=None, sel_multi=False, context={}):
		self.view = gtk.TreeView()
		self.view.set_headers_visible(not options.options['client.modepda'])
		self.view.get_selection().set_mode('single')
		self.context = {}
		self.context.update(rpc.session.context)
		self.context.update(context)
		self.fields = rpc.session.rpc_exec_auth('/object', 'execute', view_info['model'], 'fields_get', False, self.context)
		p = parse.parse(self.fields)
		p.parse(view_info['arch'], self.view)
		self.pixbufs = p.pixbufs
		self.name = p.title
		self.sel_multi = sel_multi

		if sel_multi:
			self.view.get_selection().set_mode(gtk.SELECTION_MULTIPLE)
		else:
			self.view.get_selection().set_mode(gtk.SELECTION_SINGLE)
		self.view.set_expander_column(self.view.get_column(1))
		self.view.set_enable_search(False)
		self.view.get_column(0).set_visible(False)

		self.ids=ids
		self.view_info = view_info
		self.fields_order = p.fields_order
		self.model = None
		self.reload()

		self.view.show_all()
		self.search=[]
		self.next=0

	def reload(self):
		del self.model
		self.model = view_tree_model(self.ids, self.view_info, self.fields_order, self.fields, context=self.context, pixbufs=self.pixbufs, treeview=self.view)
		self.view.set_model(self.model)

	def widget_get(self):
		return self.view

	def sel_ids_get(self):
		sel = self.view.get_selection()
		if not sel:
			return None
		sel = sel.get_selected_rows()
		if not sel:
			return []
		(model, iters) = sel
		return map(lambda x: int(model.get_value(model.get_iter(x), 0)), iters)
		
	def sel_id_get(self):
		sel = self.view.get_selection().get_selected()
		if sel==None:
			return None
		(model, iter) = sel
		if not iter:
			return None
		res = model.get_value(iter, 0)
		if res!=None:
			return int(res)
		return res

	def value_get(self, col):
		sel = self.view.get_selection().get_selected_rows()
		if sel==None:
			return None
		(model, iter) = sel
		if not iter:
			return None
		return model.get_value(iter, col)

	def go(self, id):
		return
		ids = com_rpc.xrpc.exec_auth('res_path_get', id, self.root)
		if not len(ids):
			raise 'IdNotFound'
		self.view.collapse_all()
		model = self.view.get_model()
		iter = model.get_iter_root()
		while len(ids)>0:
			if ids[-1]==model.root:
				break
			ids.pop()
		if ids!=[]:
			ids.pop()
			while ids!=[]:
				val = ids.pop()
				while True:
					if int(model.get_value(iter,0))==val:
						self.view.expand_row( model.get_path(iter), False)
						break
					if not model.iter_next(iter):
						raise 'IdNotFound'
				if ids!=[]:
					iter = model.iter_children(iter)
			self.view.get_selection().select_iter(iter)

fields_list_type = {
	'checkbox': gobject.TYPE_BOOLEAN,
	'integer': gobject.TYPE_INT,
	'float': gobject.TYPE_FLOAT
}