Continuing to give things meaningful names
[gonvert] / src / gonvert_glade.py
1 #!/usr/bin/env python
2 # -*- coding: UTF8 -*-
3
4 import os
5 import pickle
6 import string
7 import sys
8 import gettext
9 import logging
10
11 import gobject
12 import gtk
13 import gtk.glade
14 import gtk.gdk
15
16 import constants
17 import evil_globals
18 import unit_data
19
20
21 _moduleLogger = logging.getLogger("gonvert_glade")
22
23 gettext.bindtextdomain('gonvert', '/usr/share/locale')
24 gettext.textdomain('gonvert')
25 _ = gettext.gettext
26
27
28 def shortlist_changed(a):
29         print "shortlist"
30         if shortlistcheck.get_active():
31                 print "1"
32         else:
33                 print "0"
34
35
36 def edit_shortlist(a):
37         print "edit shortlist"
38         if edit_shortlist1.get_active():
39                 print "1"
40         else:
41                 print "0"
42
43
44 def app_size_changed(a,b):
45         ''"get current size of window as it changes.''"
46         evil_globals.window_size=mainWindow.get_size()
47
48
49 def clear_selections(a):
50         selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
51         os.remove(selectionsDatPath)
52         evil_globals.selected_units={}
53
54
55 def exitprogram(a):
56         """
57         This routine saves the selections to a file, and 
58          should therefore only be called when exiting the program.
59         
60          Update selections dictionary which consists of the following keys:
61          'evil_globals.selected_category': full name of selected category
62          'evil_globals.selected_units': evil_globals.selected_units dictionary which contains:
63                                 [categoryname: #1 displayed unit, #2 displayed unit]
64         """
65         #Determine the contents of the selected category row
66         selected,iter= cat_clist.get_selection().get_selected()
67         evil_globals.selected_category = cat_model.get_value(iter,0)
68
69         selections = {'evil_globals.selected_category':evil_globals.selected_category, 'evil_globals.selected_units':evil_globals.selected_units}
70         selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
71         pickle.dump(selections, open(selectionsDatPath,'w'))
72
73         #Get last size of app and save it
74         window_settings = {'size':evil_globals.window_size}
75         windowDatPath = "/".join((constants._data_path_, "window.dat"))
76         pickle.dump(window_settings, open(windowDatPath,'w'))
77
78         gtk.mainquit
79         sys.exit()
80
81
82 def find_entry_changed(a):
83         #Clear out find results since the user wants to look for something new
84         evil_globals.find_result=[] #empty find result list
85         evil_globals.find_count=0 #default to find result number zero
86         find_label.set_text('') #clear result
87
88
89 def find_key_press(a,b):
90         #Check if the key pressed was an ASCII key
91         if len(b.string)>0:
92                 #Check if the key pressed was the 'Enter' key
93                 if ord(b.string[0])==13:
94                         #Execute the find units function
95                         find_units(1)
96
97
98 def about_clicked(a):
99         about_box.show()
100
101
102 def about_hide(*args):
103         about_box.hide()
104         return gtk.TRUE
105
106
107 def messagebox_ok_clicked(a):
108         messagebox.hide()
109
110
111 def find_units(a):
112         global column1
113         global col
114         #check if 'new find' or 'last find' or 'next-find'
115
116         #new-find = run the find algorithm which also selects the first found unit
117         #         = evil_globals.find_count=0 and evil_globals.find_result=[]
118
119         #last-find = restart from top again
120         #          = evil_globals.find_count=len(evil_globals.find_result)
121
122         #next-find = continue to next found location
123         #           = evil_globals.find_count=0 and len(evil_globals.find_result)>0
124
125         #check for new-find
126         if len(evil_globals.find_result)==0:
127                 find_string = string.lower(string.strip(find_entry.get_text()))
128                 #Make sure that a valid find string has been requested
129                 if len(find_string)>0:
130                         categories = unit_data.list_dic.keys()
131                         categories.sort()
132                         found_a_unit=0 #reset the 'found-a-unit' flag
133                         cat_no=0
134                         for category in categories:
135                                 units=unit_data.list_dic[category].keys()
136                                 units.sort()
137                                 del units[0] # do not display .base_unit description key
138                                 unit_no=0
139                                 for unit in units:
140                                         if string.find(string.lower(unit), find_string)>=0:
141                                                 found_a_unit=1 #indicate that a unit was found
142                                                 #print "'",find_string,"'"," found at category=", category," unit =",unit
143                                                 evil_globals.find_result.append((category,unit,cat_no,unit_no))
144                                         unit_no=unit_no+1
145                                 cat_no=cat_no+1
146
147                         if found_a_unit==1:
148                                 #select the first found unit
149                                 evil_globals.find_count=0
150                                 #check if next find is in a new category (prevent category changes when unnecessary
151                                 if evil_globals.selected_category!=evil_globals.find_result[evil_globals.find_count][0]:
152                                         cat_clist.set_cursor(evil_globals.find_result[0][2],col,False)
153                                         unitsView.set_cursor(evil_globals.find_result[0][3],column1,True)
154                                         if len(evil_globals.find_result)>1:
155                                                 find_label.set_text(('Press Find for next unit. '+ str(len(evil_globals.find_result))+' result(s).'))
156                                         else:
157                                                 find_label.set_text('Text not found') #Display error
158         else: #must be next-find or last-find
159                 #check for last-find
160                 if evil_globals.find_count==len(evil_globals.find_result)-1:
161                         #select first result
162                         evil_globals.find_count=0
163                         cat_clist.set_cursor(evil_globals.find_result[evil_globals.find_count][2],col,False)
164                         unitsView.set_cursor(evil_globals.find_result[evil_globals.find_count][3],column1,True)
165                 else: #must be next-find
166                         evil_globals.find_count=evil_globals.find_count+1
167                         #check if next find is in a new category (prevent category changes when unnecessary
168                         if evil_globals.selected_category!=evil_globals.find_result[evil_globals.find_count][0]:
169                                 cat_clist.set_cursor(evil_globals.find_result[evil_globals.find_count][2],col,False)
170                         unitsView.set_cursor(evil_globals.find_result[evil_globals.find_count][3],column1,True)
171
172
173 def click_column(col):
174         ''"Sort the contents of the column when the user clicks on the title.''"
175         global column1, column2, unit_model
176
177         #Determine which column requires sorting
178         if col.get_title()==_(u"Unit Name"):
179                 selected_column=0
180                 column1.set_sort_indicator(True)
181                 column2.set_sort_indicator(False)
182                 column3.set_sort_indicator(False)
183                 column1.set_sort_order(not evil_globals.unit_sort_direction)
184         elif col.get_title()==_(u"Value"):
185                 selected_column=1
186                 column1.set_sort_indicator(False)
187                 column2.set_sort_indicator(True)
188                 column3.set_sort_indicator(False)
189                 column2.set_sort_order(not evil_globals.value_sort_direction)
190         else:
191                 selected_column=2
192                 column1.set_sort_indicator(False)
193                 column2.set_sort_indicator(False)
194                 column3.set_sort_indicator(True)
195                 column3.set_sort_order(not evil_globals.units_sort_direction)
196
197         #declare a spot to hold the sorted list
198         sorted_list = []
199
200         #point to the first row
201         iter=unit_model.get_iter_first()
202         row=0
203
204         while (iter):
205                 #grab all text from columns for sorting
206
207                 #get the text from each column
208                 unit_text = unit_model.get_value(iter,0)
209                 units_text = unit_model.get_value(iter,2)
210
211                 #do not bother sorting if the value column is empty
212                 if unit_model.get_value(iter,1)=='' and selected_column==1:
213                         return
214
215                 #special sorting exceptions for ascii values (instead of float values)
216                 if evil_globals.selected_category == "Computer Numbers":
217                         value_text = unit_model.get_value(iter,1)
218                 else:
219                         if unit_model.get_value(iter,1)==None or unit_model.get_value(iter,1)=='':
220                                 value_text = ''
221                         else:
222                                 value_text = float(unit_model.get_value(iter,1))
223
224                 if selected_column==0:
225                         sorted_list.append((unit_text,value_text,units_text))
226                 elif selected_column==1:
227                         sorted_list.append((value_text,unit_text,units_text))
228                 else:
229                         sorted_list.append((units_text,value_text,unit_text))
230
231                 #point to the next row in the unit_model
232                 iter=unit_model.iter_next(iter)
233                 row=row+1
234
235         #check if no calculations have been made yet (don't bother sorting)
236         if row==0:
237                 return
238         else:
239                 if selected_column==0:
240                         if not evil_globals.unit_sort_direction:
241                                 sorted_list.sort(lambda (x,xx,xxx), (y,yy,yyy): cmp(string.lower(x),string.lower(y)))
242                                 evil_globals.unit_sort_direction=True
243                         else:
244                                 sorted_list.sort(lambda (x,xx,xxx), (y,yy,yyy): cmp(string.lower(y),string.lower(x)))
245                                 evil_globals.unit_sort_direction=False
246                 elif selected_column==1:
247                         sorted_list.sort()
248                         if not evil_globals.value_sort_direction:
249                                 evil_globals.value_sort_direction=True
250                         else:
251                                 sorted_list.reverse()
252                                 evil_globals.value_sort_direction=False
253                 else:
254                         if not evil_globals.units_sort_direction:
255                                 sorted_list.sort(lambda (x,xx,xxx), (y,yy,yyy): cmp(string.lower(x),string.lower(y)))
256                                 evil_globals.units_sort_direction=True
257                         else:
258                                 sorted_list.sort(lambda (x,xx,xxx), (y,yy,yyy): cmp(string.lower(y),string.lower(x)))
259                                 evil_globals.units_sort_direction=False
260
261                 #Clear out the previous list of units
262                 unit_model = gtk.ListStore(gobject.TYPE_STRING,gobject.TYPE_STRING,gobject.TYPE_STRING)
263                 unitsView.set_model(unit_model)
264
265                 #colourize each row differently for easier reading
266                 unitsView.set_property( 'rules_hint',1)
267
268                 #Clear out the description
269                 text_model = gtk.TextBuffer(None)
270                 unitDescription.set_buffer(text_model)
271
272                 if selected_column==0:
273                         for unit,value,units in sorted_list:
274                                 iter = unit_model.append()
275                                 unit_model.set(iter,0,unit,1,str(value),2,units)
276                 elif selected_column==1:
277                         for value,unit,units in sorted_list:
278                                 iter = unit_model.append()
279                                 unit_model.set(iter,0,unit,1,str(value),2,units)
280                 else:
281                         for units,value,unit in sorted_list:
282                                 iter = unit_model.append()
283                                 unit_model.set(iter,0,unit,1,str(value),2,units)
284         return
285
286
287 def click_category(row):
288         global unit_model, cat_model
289         global unit_dic, list_dic
290
291         #Clear out the previous list of units
292         unit_model = gtk.ListStore(gobject.TYPE_STRING,gobject.TYPE_STRING,gobject.TYPE_STRING)
293         unitsView.set_model(unit_model)
294
295         #Colourize each row alternately for easier reading
296         unitsView.set_property( 'rules_hint',1)
297
298         #Clear out the description
299         text_model = gtk.TextBuffer(None)
300         unitDescription.set_buffer(text_model)
301
302         #Determine the contents of the selected category row
303         selected,iter= row.get_selection().get_selected()
304
305         evil_globals.selected_category = cat_model.get_value(iter,0)
306
307         evil_globals.unit_sort_direction = False
308         evil_globals.value_sort_direction = False
309         evil_globals.units_sort_direction = False
310         column1.set_sort_indicator(False)
311         column2.set_sort_indicator(False)
312         column3.set_sort_indicator(False)
313
314         unit_dic=unit_data.list_dic[selected.get_value(iter,0)]
315         keys = unit_dic.keys()
316         keys.sort()
317         del keys[0] # do not display .base_unit description key
318
319         #Fill up the units descriptions and clear the value cells
320         for key in keys:
321                 iter = unit_model.append()
322                 unit_model.set(iter,0,key,1,'',2,unit_dic[key][1])
323
324         unitName.set_text('')
325         unitValue.set_text('')
326         previousUnitName.set_text('')
327         previousUnitValue.set_text('')
328         unitSymbol.set_text('')
329         previousUnitSymbol.set_text('')
330
331         restore_units()
332
333
334 def restore_units():
335         global unit_dic, list_dic
336
337         # Restore the previous historical settings of previously selected units in this newly selected category
338         #Since category has just been clicked, the list will be sorted already.
339         if evil_globals.selected_units.has_key(evil_globals.selected_category):
340                 if evil_globals.selected_units[evil_globals.selected_category][0]:
341                         ''"debug ''"
342                         #evil_globals.selected_units[evil_globals.selected_category]=[selected_unit,evil_globals.selected_units[evil_globals.selected_category][0]]
343
344                         units=unit_data.list_dic[evil_globals.selected_category].keys()
345                         units.sort()
346                         del units[0] # do not display .base_unit description key
347
348                         #Restore oldest selection first.
349                         if evil_globals.selected_units[evil_globals.selected_category][1]:
350                                 unit_no=0
351                                 for unit in units:
352                                         if unit==evil_globals.selected_units[evil_globals.selected_category][1]:
353                                                 unitsView.set_cursor(unit_no,column1,True)
354                                         unit_no=unit_no+1
355
356                         #Restore newest selection second.
357                         unit_no=0
358                         for unit in units:
359                                 if unit==evil_globals.selected_units[evil_globals.selected_category][0]:
360                                         unitsView.set_cursor(unit_no,column1,True)
361                                 unit_no=unit_no+1
362
363         # select the text so user can start typing right away
364         unitValue.grab_focus()
365         unitValue.select_region(0,-1)
366
367
368 def button_released(row,a):
369         click_unit(row)
370
371
372 def click_unit(row):
373         evil_globals.calcsuppress = 1 #suppress calculations
374
375         #Determine the contents of the selected row.
376         selected,iter= unitsView.get_selection().get_selected()
377
378         selected_unit=selected.get_value(iter,0)
379
380         unit_spec=unit_dic[selected_unit]
381
382         #Clear out the description
383         text_model = gtk.TextBuffer(None)
384         unitDescription.set_buffer(text_model)
385
386         enditer = text_model.get_end_iter()
387         text_model.insert(enditer,unit_spec[2])
388
389         if unitName.get_text() != selected_unit:
390                 previousUnitName.set_text(unitName.get_text())
391                 previousUnitValue.set_text(unitValue.get_text())
392                 if unitSymbol.get() == None:
393                         previousUnitSymbol.set_text('')
394                 else:
395                         previousUnitSymbol.set_text(unitSymbol.get())
396         unitName.set_text(selected_unit)
397
398         unitValue.set_text(selected.get_value(iter,1))
399
400         unitSymbol.set_text(unit_spec[1]) # put units into label text
401         if unitValue.get_text() =='':
402                 if evil_globals.selected_category == "Computer Numbers":
403                         unitValue.set_text("0")
404                 else:
405                         unitValue.set_text("0.0")
406
407         #For historical purposes, record this unit as the most recent one in this category.
408         # Also, if a previous unit exists, then shift that previous unit to oldest unit.
409         if evil_globals.selected_units.has_key(evil_globals.selected_category):
410                 if evil_globals.selected_units[evil_globals.selected_category][0]:
411                         evil_globals.selected_units[evil_globals.selected_category]=[selected_unit,evil_globals.selected_units[evil_globals.selected_category][0]]
412         else:
413                 evil_globals.selected_units[evil_globals.selected_category]=[selected_unit,'']
414
415         # select the text so user can start typing right away
416         unitValue.grab_focus()
417         unitValue.select_region(0,-1)
418
419         evil_globals.calcsuppress = 0 #enable calculations
420
421
422 def write_units(a):
423         ''"Write the list of categories and units to stdout for documentation purposes.''"
424         messagebox_model = gtk.TextBuffer(None)
425         messageboxtext.set_buffer(messagebox_model)
426         messagebox_model.insert_at_cursor(_(u'The units are being written to stdout. You can capture this printout by starting gonvert from the command line as follows:\n$ gonvert > file.txt'),-1)
427         messagebox.show()
428         while gtk.events_pending():
429                 gtk.mainiteration (False)
430         category_keys=unit_data.list_dic.keys()
431         category_keys.sort()
432         total_categories = 0
433         total_units = 0
434         print 'gonvert-%s%s' % (
435                 constants.__version__,
436                 _(u' - Unit Conversion Utility  - Convertible units listing:')
437         )
438         for category_key in category_keys:
439                 total_categories = total_categories + 1
440                 print category_key,":"
441                 unit_dic=unit_data.list_dic[category_key]
442                 unit_keys = unit_dic.keys()
443                 unit_keys.sort()
444                 del unit_keys[0] # do not display .base_unit description key
445                 for unit_key in unit_keys:
446                         total_units = total_units + 1
447                         print "\t",unit_key
448         print total_categories,' categories'
449         print total_units,' units'
450         messagebox_model = gtk.TextBuffer(None)
451         messageboxtext.set_buffer(messagebox_model)
452         messagebox_model.insert_at_cursor(_(u'The units list has been written to stdout. You can capture this printout by starting gonvert from the command line as follows:\n$ gonvert > file.txt'),-1)
453
454
455 class Ccalculate(object):
456
457         def top(self,a):
458                 global unit_model
459                 global testvalue
460
461                 if evil_globals.calcsuppress == 1:
462                         #evil_globals.calcsuppress = 0
463                         return
464                 # determine if value to be calculated is empty
465                 if evil_globals.selected_category == "Computer Numbers":
466                         if unitValue.get_text() =='':
467                                 value = '0'
468                         else:
469                                  value = unitValue.get_text()
470                 else:
471                         if unitValue.get_text() =='':
472                                 value = 0.0
473                         else:
474                                 value = float(unitValue.get_text())
475
476                 if unitName.get_text() != '':
477                         func,arg = unit_dic[unitName.get_text()][0] #retrieve the conversion function and value from the selected unit
478                         base = apply(func.to_base,(value,arg,)) #determine the base unit value
479
480                         keys = unit_dic.keys()
481                         keys.sort()
482                         del keys[0]
483                         row = 0
484
485                         #point to the first row
486                         iter=unit_model.get_iter_first()
487
488                         while (iter):
489                                 #get the formula from the name at the row
490                                 func,arg = unit_dic[unit_model.get_value(iter,0)][0]
491
492                                 #set the result in the value column
493                                 unit_model.set(iter,1,str(apply(func.from_base,(base,arg,))))
494
495                                 #point to the next row in the unit_model
496                                 iter=unit_model.iter_next(iter)
497
498                         # if the second row has a unit then update its value
499                         if previousUnitName.get_text() != '':
500                                 evil_globals.calcsuppress=1
501                                 func,arg = unit_dic[previousUnitName.get_text()][0]
502                                 previousUnitValue.set_text(str(apply(func.from_base,(base,arg,))))
503                                 evil_globals.calcsuppress=0
504
505         def bottom(self,a):
506                 if evil_globals.calcsuppress == 1:
507                         #evil_globals.calcsuppress = 0
508                         return
509                 # determine if value to be calculated is empty
510                 if evil_globals.selected_category == "Computer Numbers":
511                         if previousUnitValue.get_text() =='':
512                                 value = '0'
513                         else:
514                                 value = previousUnitValue.get_text()
515                 else:
516                         if previousUnitValue.get_text() =='':
517                                 value = 0.0
518                         else:
519                                 value = float(previousUnitValue.get_text())
520
521                 if previousUnitName.get_text() != '':
522                         func,arg = unit_dic[previousUnitName.get_text()][0] #retrieve the conversion function and value from the selected unit
523                         base = apply(func.to_base,(value,arg,)) #determine the base unit value
524
525                         keys = unit_dic.keys()
526                         keys.sort()
527                         del keys[0]
528                         row = 0
529
530                         #point to the first row
531                         iter=unit_model.get_iter_first()
532
533                         while (iter):
534                                 #get the formula from the name at the row
535                                 func,arg = unit_dic[unit_model.get_value(iter,0)][0]
536
537                                 #set the result in the value column
538                                 unit_model.set(iter,1,str(apply(func.from_base,(base,arg,))))
539
540                                 #point to the next row in the unit_model
541                                 iter=unit_model.iter_next(iter)
542
543                         # if the second row has a unit then update its value
544                         if unitName.get_text() != '':
545                                 evil_globals.calcsuppress=1
546                                 func,arg = unit_dic[unitName.get_text()][0]
547                                 unitValue.set_text(str(apply(func.from_base,(base,arg,))))
548                                 evil_globals.calcsuppress=0
549
550
551 # cat_clist is categoryView
552 # unitConversionLayout
553 #       selectedUnitLayouta
554 #               unitName
555 #               unitValue
556 #               unitSymbol
557 #       previousSelectedUnitLayout
558 #               previousUnitName
559 #               previousUnitValue
560 #               previousUnitSymbol
561 #       unitsAndDescriptionPane
562 #               unitListScrolledWindow
563 #                       unitsView
564 #               unitDescriptionScrolledWindow
565 #                       unitDescription
566 #       searchLayout is the search box
567 def main():
568         global mainWindow
569         global cat_clist
570         global cat_model
571         global unitValue
572         global unitName
573         global unitSymbol
574         global unitsView
575         global calculate
576         global shortlistcheck
577         global about_box
578         global unitDescription
579         global column1
580         global column2
581         global column3
582         global previousUnitName
583         global previousUnitValue
584         global previousUnitSymbol
585         global find_label
586         global find_entry
587         global col
588         global edit_shortlist1
589
590         logging.basicConfig(level=logging.DEBUG)
591
592         try:
593                 os.makedirs(constants._data_path_)
594         except OSError, e:
595                 if e.errno != 17:
596                         raise
597
598         #check to see if glade file is in current directory (user must be running from download untar directory)
599         _glade_files = [
600                 os.path.join(os.path.dirname(__file__), "gonvert.glade"),
601                 os.path.join(os.path.dirname(__file__), "../data/gonvert.glade"),
602                 os.path.join(os.path.dirname(__file__), "../lib/gonvert.glade"),
603                 '/usr/lib/gonvert/gonvert.glade',
604         ]
605         for gladePath in _glade_files:
606                 if os.path.isfile(gladePath):
607                         homepath = os.path.dirname(gladePath)
608                         pixmapspath = "/".join((homepath, "pixmaps"))
609                         widgets = gtk.glade.XML(gladePath)
610                         break
611         else:
612                 return
613
614         calculate = Ccalculate()
615         mainWindow = widgets.get_widget('mainWindow')
616
617         #Restore window size from previously saved settings if it exists and is valid.
618         windowDatPath = "/".join((constants._data_path_, "window.dat"))
619         if os.path.exists(windowDatPath):
620                 #Retrieving previous window settings from ~/.gonvert/window.dat
621                 saved_window = pickle.load(open(windowDatPath, "r"))
622                 #If the 'size' has been stored, then extract size from saved_window.
623                 if saved_window.has_key('size'):
624                         a, b = saved_window['size']
625                         mainWindow.resize(a, b)
626                 else:
627                         #Maximize if no previous size was found
628                         #mainWindow.maximize()
629                         pass
630         else:
631                 #Maximize if no previous window.dat file was found
632                 #mainWindow.maximize()
633                 pass
634
635         mainWindow.set_title('gonvert- %s - Unit Conversion Utility' % constants.__version__);
636         iconPath = pixmapspath + '/gonvert.png'
637         if os.path.exists(iconPath):
638                 mainWindow.set_icon(gtk.gdk.pixbuf_new_from_file(iconPath))
639         else:
640                 _moduleLogger.warn("Error: Could not find gonvert icon: %s" % iconPath)
641
642         #--------- connections to GUI ----------------
643         dic = {
644                 "on_exitMenuItem_activate": exitprogram,
645                 "on_mainWindow_destroy": exitprogram,
646                 "on_cat_clist_select_row": click_category,
647                 "on_unitsView_click_column": click_column,
648                 "on_unitValue_changed": calculate.top,
649                 "on_previousUnitValue_changed": calculate.bottom,
650                 "on_write_units1_activate": write_units,
651                 "on_find_button_clicked": find_units,
652                 "on_find_entry_key_press_event": find_key_press,
653                 "on_find_entry_changed": find_entry_changed,
654                 "on_about1_activate": about_clicked,
655                 "on_about_close_clicked": about_hide,
656                 "on_messagebox_ok_clicked": messagebox_ok_clicked,
657                 "on_clear_selections1_activate": clear_selections,
658                 "on_unitsView_cursor_changed": click_unit,
659                 "on_unitsView_button_released": button_released,
660                 "on_mainWindow_size_allocate": app_size_changed,
661                 "on_shortlistcheck_toggled": shortlist_changed,
662                 "on_edit_shortlist1_activate": edit_shortlist,
663          }
664
665         widgets.signal_autoconnect (dic);
666         mainWindow.connect("destroy", exitprogram)
667
668         def change_menu_label(labelname,newtext):
669                 item_label = widgets.get_widget(labelname).get_children()[0]
670                 item_label.set_text(newtext)
671         def change_label(labelname,newtext):
672                 item_label = widgets.get_widget(labelname)
673                 item_label.set_text(newtext)
674
675         change_menu_label('fileMenuItem',_('File'))
676         change_menu_label('exitMenuItem',_('Exit'))
677         change_menu_label('toolsMenuItem',_('Tools'))
678         change_menu_label('clear_selections1',_('Clear selections'))
679         change_menu_label('write_units1',_('Write Units'))
680         change_menu_label('helpMenuItem',_('Help'))
681         change_menu_label('aboutMenuItem',_('About'))
682
683         change_menu_label('find_button',_('Find'))
684
685         shortlistcheck = widgets.get_widget('shortlistcheck')
686         edit_shortlist1 = widgets.get_widget('edit_shortlist1')
687
688         cat_clist = widgets.get_widget('cat_clist' )
689
690         unitsView = widgets.get_widget('unitsView')
691         unitsView_selection=unitsView.get_selection()
692
693         unitName = widgets.get_widget('unitName')
694         unitValue = widgets.get_widget('unitValue')
695         previousUnitName = widgets.get_widget('previousUnitName')
696         previousUnitValue = widgets.get_widget('previousUnitValue')
697         about_box = widgets.get_widget('about_box')
698         messagebox = widgets.get_widget('msgbox')
699         messageboxtext = widgets.get_widget('msgboxtext')
700
701         about_image = widgets.get_widget('about_image')
702         about_image.set_from_file(pixmapspath +'gonvert.png')
703         versionlabel = widgets.get_widget('versionlabel')
704         versionlabel.set_text(constants.__version__)
705
706         unitSymbol =widgets.get_widget('unitSymbol')
707         previousUnitSymbol =widgets.get_widget('previousUnitSymbol')
708
709         unitDescription = widgets.get_widget('unitDescription' )
710
711         find_entry = widgets.get_widget('find_entry')
712         find_label = widgets.get_widget('find_label')
713
714         #insert a column into the units list even though the heading will not be seen
715         renderer = gtk.CellRendererText()
716         column1 = gtk.TreeViewColumn( _('Unit Name'), renderer )
717         column1.set_property( 'resizable', 1 )
718         column1.add_attribute( renderer, 'text', 0 )
719         column1.set_clickable(True)
720         column1.connect("clicked",click_column)
721         unitsView.append_column( column1 )
722
723         column2 = gtk.TreeViewColumn( _('Value'), renderer )
724         column2.set_property( 'resizable', 1 )
725         column2.add_attribute( renderer, 'text', 1 )
726         column2.set_clickable(True)
727         column2.connect("clicked",click_column)
728         unitsView.append_column( column2 )
729
730         column3 = gtk.TreeViewColumn( _('Units'), renderer )
731         column3.set_property( 'resizable', 1 )
732         column3.add_attribute( renderer, 'text', 2 )
733         column3.set_clickable(True)
734         column3.connect("clicked",click_column)
735         unitsView.append_column( column3 )
736
737         #Insert a column into the category list even though the heading will not be seen
738         renderer = gtk.CellRendererText()
739         col = gtk.TreeViewColumn( 'Title', renderer )
740         col.set_property( 'resizable', 1 )
741         col.add_attribute( renderer, 'text', 0 )
742         cat_clist.append_column( col )
743
744         cat_model = gtk.ListStore(gobject.TYPE_STRING)
745         cat_clist.set_model(cat_model)
746         #colourize each row differently for easier reading
747         cat_clist.set_property( 'rules_hint',1)
748
749         #Populate the catagories list
750         keys = unit_data.list_dic.keys()
751         keys.sort()
752         for key in keys:
753                 iter = cat_model.append()
754                 cat_model.set(iter,0,key)
755
756         ToolTips=gtk.Tooltips()
757         find_button = widgets.get_widget('find_button')
758         ToolTips.set_tip(find_button,_(u'Find unit (F6)'))
759
760         #Restore selections from previously saved settings if it exists and is valid.
761         historical_catergory_found=False
762         selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
763         if os.path.exists(selectionsDatPath):
764                 #Retrieving previous selections from ~/.gonvert/selections.dat
765                 selections=pickle.load(open(selectionsDatPath,'r'))
766                 #Restoring previous selections.
767                 #
768                 #Make a list of categories to determine which one to select
769                 categories=unit_data.list_dic.keys()
770                 categories.sort()
771                 #
772                 #If the 'selected_unts' has been stored, then extract evil_globals.selected_units from selections.
773                 if selections.has_key('evil_globals.selected_units'):
774                         evil_globals.selected_units=selections['evil_globals.selected_units']
775                 #Make sure that the 'evil_globals.selected_category' has been stored.
776                 if selections.has_key('evil_globals.selected_category'):
777                         #Match an available category to the previously selected category.
778                         for counter in range(len(categories)):
779                                 if selections['evil_globals.selected_category']==categories[counter]:
780                                         # Restore the previously selected category.
781                                         cat_clist.set_cursor(counter, col, False )
782                                         cat_clist.grab_focus()
783                         historical_catergory_found=True
784
785         if not historical_catergory_found:
786                 print "Couldn't find saved category, using default."
787                 #If historical records were not kept then default to 
788                 # put the focus on the first category
789                 cat_clist.set_cursor(0, col, False)
790                 cat_clist.grab_focus()
791
792         restore_units()
793
794         gtk.main()
795
796
797 if __name__ == "__main__":
798         main()