-
Notifications
You must be signed in to change notification settings - Fork 32
/
pp_edititem.py
464 lines (364 loc) · 17.9 KB
/
pp_edititem.py
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
from Tkinter import *
from tkColorChooser import *
import ttk
import tkFont
import os
import string
import tkSimpleDialog
import tkFileDialog
from ScrolledText import ScrolledText
from pp_utils import Monitor
class FontChooser( tkSimpleDialog.Dialog ):
BASIC = 1
ALL = 2
def __init__( self, parent, defaultfont=None, showstyles=None ):
self._family = StringVar( value='Century Schoolbook L')
self._sizeString = StringVar( value='20' )
self._weight = StringVar( value=tkFont.NORMAL )
self._slant = StringVar( value=tkFont.ROMAN )
self._isUnderline = BooleanVar( value=False )
self._isOverstrike = BooleanVar( value=False )
if defaultfont:
self._initialize( defaultfont )
self._currentFont = tkFont.Font( font=self.getFontTuple() )
self._showStyles = showstyles
self.sampleText = None
tkSimpleDialog.Dialog.__init__( self, parent, 'Font Chooser' )
def _initialize( self, aFont ):
if not isinstance( aFont, tkFont.Font ):
aFont = tkFont.Font( font=aFont )
fontOpts = aFont.actual( )
self._family.set( fontOpts[ 'family' ] )
self._sizeString.set( fontOpts[ 'size' ] )
self._weight.set( fontOpts[ 'weight' ] )
self._slant.set( fontOpts[ 'slant' ] )
self._isUnderline.set( fontOpts[ 'underline' ] )
self._isOverstrike.set( fontOpts[ 'overstrike' ] )
def body( self, master ):
theRow = 0
Label( master, text="Font Family" ).grid( row=theRow, column=0 )
Label( master, text="Font Size" ).grid( row=theRow, column=2 )
theRow += 1
# Font Families
fontList = ttk.Combobox( master, height=10, textvariable=self._family )
fontList.grid( row=theRow, column=0, columnspan=2, sticky=N+S+E+W, padx=10 )
first = None
rawfamilyList = list(tkFont.families( ))
rawfamilyList.sort()
# print rawfamilyList
familyList=[]
for family in rawfamilyList:
if family[0] == '@':
continue
familyList.append(family)
fontList.configure( values=familyList )
fontList.bind('<<ComboboxSelected>>', self.selectionChanged)
# Font Sizes
sizeList = ttk.Combobox( master, height=10, width=5, textvariable=self._sizeString )
sizeList.grid( row=theRow, column=2, columnspan=2, sticky=N+S+E+W, padx=10 )
sizes=[]
for size in xrange( 10,50 ):
sizes.append( str(size) )
sizeList.configure( values=sizes)
sizeList.bind('<<ComboboxSelected>>', self.selectionChanged)
# Styles
if self._showStyles is not None:
theRow += 1
if self._showStyles in ( FontChooser.ALL, FontChooser.BASIC ):
Label( master, text='Styles', anchor=W ).grid( row=theRow, column=0, pady=10, sticky=W )
theRow += 1
Checkbutton( master, text="bold", command=self.selectionChanged, offvalue='normal', onvalue='bold', variable=self._weight ).grid(row=theRow, column=0)
Checkbutton( master, text="italic", command=self.selectionChanged, offvalue='roman', onvalue='italic', variable=self._slant ).grid(row=theRow, column=1)
if self._showStyles == FontChooser.ALL:
Checkbutton( master, text="underline", command=self.selectionChanged, offvalue=False, onvalue=True, variable=self._isUnderline ).grid(row=theRow, column=2)
Checkbutton( master, text="overstrike", command=self.selectionChanged, offvalue=False, onvalue=True, variable=self._isOverstrike ).grid(row=theRow, column=3)
# Sample Text
theRow += 1
Label( master, text='Sample Text', anchor=W ).grid( row=theRow, column=0, pady=10, sticky=W )
theRow += 1
self.sampleText = Text( master, height=11, width=70 )
self.sampleText.insert( INSERT,'ABC...XYZ\nabc....xyz', 'fontStyle' )
self.sampleText.config( state=DISABLED )
self.sampleText.tag_config( 'fontStyle', font=self._currentFont )
self.sampleText.grid( row=theRow, column=0, columnspan=4, padx=10 )
def apply( self ):
self.result = self.getFontTuple( )
def selectionChanged( self, something=None ):
self._currentFont.configure( family=self._family.get(),
size=self._sizeString.get(),
weight=self._weight.get(),
slant=self._slant.get(),
underline=self._isUnderline.get(),
overstrike=self._isOverstrike.get() )
if self.sampleText:
self.sampleText.tag_config( 'fontStyle', font=self._currentFont )
def getFontString( self ):
family = self._family.get()
size = int(self._sizeString.get())
styleList = [ ]
if self._weight.get() == tkFont.BOLD:
styleList.append( 'bold' )
if self._slant.get() == tkFont.ITALIC:
styleList.append( 'italic' )
if self._isUnderline.get():
styleList.append( 'underline' )
if self._isOverstrike.get():
styleList.append( 'overstrike' )
if len(styleList) == 0:
return family+ ' ' + str(size)
else:
xx=''
for x in styleList:
xx=xx+' '+ x
return family + ' ' +str(size) +' '+xx
def getFontTuple( self ):
family = self._family.get()
size = int(self._sizeString.get())
styleList = [ ]
if self._weight.get() == tkFont.BOLD:
styleList.append( 'bold' )
if self._slant.get() == tkFont.ITALIC:
styleList.append( 'italic' )
if self._isUnderline.get():
styleList.append( 'underline' )
if self._isOverstrike.get():
styleList.append( 'overstrike' )
if len(styleList) == 0:
return family, size
else:
return family, size, ' '.join( styleList )
def askChooseFont( parent, defaultfont=None, showstyles=FontChooser.ALL ):
return FontChooser( parent, defaultfont=defaultfont, showstyles=showstyles ).result
###################################################
# Tabbed interface script
# www.sunjay-varma.com
###################################################
__doc__ = info = '''
This script was written by Sunjay Varma - www.sunjay-varma.com
This script has two main classes:
Tab - Basic tab used by TabBar for main functionality
TabBar - The tab bar that is placed above tab bodies (Tabs)
'''
BASE = RAISED
SELECTED = FLAT
# a base tab class
class Tab(Frame):
def __init__(self, master, name):
Frame.__init__(self, master)
self.tab_name = name
# the bulk of the logic is in the actual tab bar
class TabBar(Frame):
def __init__(self, master=None, init_name=None):
Frame.__init__(self, master)
self.tabs = {}
self.buttons = {}
self.current_tab = None
self.init_name = init_name
def show(self):
# print 'show',self.tabs
self.pack(side=TOP, expand=YES, fill=X)
self.switch_tab(self.init_name or self.tabs.keys()[-1]) # switch the tab to the first tab
def add(self, tab,text):
tab.pack_forget() # hide the tab on init
self.tabs[tab.tab_name] = tab # add it to the list of tabs
b = Button(self, text=text, relief=BASE,font='arial 10',command=(lambda name=tab.tab_name: self.switch_tab(name))) # set the command to switch tabs
b.pack(side=LEFT) # pack the button to the left most of self
self.buttons[tab.tab_name] = b # add it to the list of buttons
# print '\n'
# for xtab in self.tabs:
# print xtab
def delete(self, tabname):
if tabname == self.current_tab:
self.current_tab = None
self.tabs[tabname].pack_forget()
del self.tabs[tabname]
self.switch_tab(self.tabs.keys()[0])
else:
del self.tabs[tabname]
self.buttons[tabname].pack_forget()
del self.buttons[tabname]
def switch_tab(self, name):
if self.current_tab:
self.buttons[self.current_tab].config(relief=RAISED, fg='black')
self.tabs[self.current_tab].pack_forget() # hide the current tab
self.tabs[name].pack(side=BOTTOM) # add the new tab to the display
self.current_tab = name # set the current tab to itself
self.buttons[name].config(relief=FLAT,fg='black') # set it to the selected style
# *************************************
# EDIT SHOW AND TRACK CONTENT
# ************************************
class EditItem(tkSimpleDialog.Dialog):
def __init__(self, parent, title, field_content, record_specs,field_specs,show_refs,initial_media_dir,pp_home_dir,initial_tab):
self.mon=Monitor()
self.mon.on()
#save the extra arg to instance variable
self.field_content = field_content # dictionary - the track parameters to be edited
self.record_specs= record_specs # list of field names and seps/tabs in the order that they appear
self.field_specs=field_specs # disctionary of specs referenced by field name
self.show_refs=show_refs
self.show_refs.append('')
self.initial_media_dir=initial_media_dir
self.pp_home_dir=pp_home_dir
self.initial_tab=initial_tab
# list of stringvars from which to get edited values (for optionmenu only??)
self.entries=[]
#and call the base class _init_which calls body immeadiately and apply on OK pressed
tkSimpleDialog.Dialog.__init__(self, parent, title)
def body(self,root):
self.root=root
bar = TabBar(root, init_name=self.initial_tab)
self.body_fields(root,bar)
# bar.config(bd=1, relief=RIDGE) # add some border
bar.show()
def body_fields(self, master,bar):
# get fields for this record using the record type in the loaded record
record_fields=self.record_specs[self.field_content['type']]
# init results of building the form
self.tab_row=1 # row on form
self.fields=[] # generated by body_fields - list of field objects in record fields order, not for sep or tab
self.field_index=0 # index to self.fields incremented after each field except tab and sep
self.entries=[] # generated by body_fields - list of stringvars in record fields order, used option-menus only
# populate the dialog box using the record fields to determine the order
for field in record_fields:
#get list of values where required
values=[]
if self.field_specs[field]['shape']in("option-menu",'spinbox'):
if self.field_specs[field]['param']in ('sub-show','start-show','controlled-show'):
values=self.show_refs
else:
values=self.field_specs[field]['values']
else:
values=[]
# make the entry
obj=self.make_entry(master,self.field_specs[field],values,bar)
if obj<>None:
self.fields.append(obj)
self.field_index +=1
return None # No initial focus
# create an entry in a dialog box
def make_entry(self,master,field_spec,values,bar):
# print 'make row',self.field_index,field_spec['shape']
if field_spec['shape']=='tab':
self.current_tab = Tab(master, field_spec['name'])
bar.add(self.current_tab,field_spec['text'])
self.tab_row=1
return None
elif field_spec['shape']=='sep':
Label(self.current_tab,text='', anchor=W).grid(row=self.tab_row,column=0,sticky=W)
self.tab_row+=1
return None
else:
# get the name of the field
parameter=field_spec['param']
# print 'content', parameter, self.field_content[field_spec['param']]
# is it in the field content dictionary
if not parameter in self.field_content:
self.mon.log(self,"Value for field not found in opened file: " + parameter)
return None
else:
if field_spec['must']=='yes':
bg='pink'
else:
bg='white'
#write the label
Label(self.current_tab,text=field_spec['text'], anchor=W).grid(row=self.tab_row,column=0,sticky=W)
# make the editable field
if field_spec['shape']in ('entry','colour','browse','font'):
obj=Entry(self.current_tab,bg=bg,width=40,font='arial 11')
obj.insert(END,self.field_content[field_spec['param']])
elif field_spec['shape']=='text':
obj=ScrolledText(self.current_tab,bg=bg,height=8,width=40,font='arial 11')
obj.insert(END,self.field_content[field_spec['param']])
elif field_spec['shape']=='spinbox':
obj=Spinbox(self.current_tab,bg=bg,values=values,wrap=True)
obj.insert(END,self.field_content[field_spec['param']])
elif field_spec['shape']=='option-menu':
self.option_val = StringVar(self.current_tab)
self.option_val.set(self.field_content[field_spec['param']])
obj = apply(OptionMenu, [self.current_tab, self.option_val] + values)
self.entries.append(self.option_val)
else:
self.mon.log(self,"Uknown shape for: " + parameter)
return None
if field_spec['read-only']=='yes':
obj.config(state="readonly",bg='dark grey')
obj.grid(row=self.tab_row,column=1,sticky=W)
#display buttons where required
if field_spec['shape']=='browse':
but=Button(self.current_tab,width=1,height=1,bg='dark grey',command=(lambda o=obj: self.browse(o)))
but.grid(row=self.tab_row,column=2,sticky=W)
elif field_spec['shape']=='colour':
but=Button(self.current_tab,width=1,height=1,bg='dark grey',command=(lambda o=obj: self.pick_colour(o)))
but.grid(row=self.tab_row,column=2,sticky=W)
elif field_spec['shape']=='font':
but=Button(self.current_tab,width=1,height=1,bg='dark grey',command=(lambda o=obj: self.pick_font(o)))
but.grid(row=self.tab_row,column=2,sticky=W)
self.tab_row+=1
return obj
def apply(self):
# get list of fields in the record in the same order as the form was generated
record_fields=self.record_specs[self.field_content['type']]
field_index=0 # index to self.fields - not incremented for tab and sep
entry_index=0 # index of stringvars for option_menu
for field in record_fields:
# get the details of this field
field_spec=self.field_specs[field]
# print 'reading row',field_index,field_spec['shape']
# and get the value
if field_spec['shape']not in ('sep','tab'):
# print field_spec['param']
if field_spec['shape']=='text':
self.field_content[field_spec['param']]=self.fields[field_index].get(1.0,END).rstrip('\n')
elif field_spec['shape']=='option-menu':
self.field_content[field_spec['param']]=self.entries[entry_index].get()
entry_index+=1
else:
self.field_content[field_spec['param']]=self.fields[field_index].get().strip()
# print self.field_content[field_spec['param']]
field_index +=1
self.result=True
return self.result
def pick_colour(self,obj):
rgb,colour=askcolor()
#print rgb,colour
if colour<>None:
obj.delete(0,END)
obj.insert(END,colour)
def pick_font(self,obj):
font=askChooseFont(self.root)
print font
if font<>None:
obj.delete(0,END)
obj.insert(END,font)
def browse(self,obj):
# print "initial directory ", self.options.initial_media_dir
file_path=tkFileDialog.askopenfilename(initialdir=self.initial_media_dir, multiple=False)
if file_path=='':
return
file_path=os.path.normpath(file_path)
#print "file path ", file_path
relpath = os.path.relpath(file_path,self.pp_home_dir)
#print "relative path ",relpath
common = os.path.commonprefix([file_path,self.pp_home_dir])
#print "common ",common
if common.endswith("pp_home") == False:
obj.delete(0,END)
obj.insert(END,file_path)
else:
location = "+" + os.sep + relpath
location = string.replace(location,'\\','/')
#print "location ",location
obj.delete(0,END)
obj.insert(END,location)
def buttonbox(self):
'''add modified button box.
override standard one to get rid of key bindings which cause trouble with text widget
'''
box = Frame(self)
w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE)
w.pack(side=LEFT, padx=5, pady=5)
w = Button(box, text="Cancel", width=10, command=self.cancel)
w.pack(side=LEFT, padx=5, pady=5)
#self.bind("<Return>", self.ok)
#self.bind("<Escape>", self.cancel)
box.pack()