Adding some more global statements to fix search and stuff
[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                                         clist1.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                         clist1.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                         clist1.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                 clist1.set_model(unit_model)
264
265                 #colourize each row differently for easier reading
266                 clist1.set_property( 'rules_hint',1)
267
268                 #Clear out the description
269                 text_model = gtk.TextBuffer(None)
270                 text1.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         clist1.set_model(unit_model)
294
295         #Colourize each row alternately for easier reading
296         clist1.set_property( 'rules_hint',1)
297
298         #Clear out the description
299         text_model = gtk.TextBuffer(None)
300         text1.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         entry3.set_text('')
327         entry4.set_text('')
328         unitSymbol.set_text('')
329         label2.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                                                 clist1.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                                         clist1.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= clist1.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         text1.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                 entry3.set_text(unitName.get_text())
391                 entry4.set_text(unitValue.get_text())
392                 if unitSymbol.get() == None:
393                         label2.set_text('')
394                 else:
395                         label2.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 entry3.get_text() != '':
500                                 evil_globals.calcsuppress=1
501                                 func,arg = unit_dic[entry3.get_text()][0]
502                                 entry4.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 entry4.get_text() =='':
512                                 value = '0'
513                         else:
514                                 value = entry4.get_text()
515                 else:
516                         if entry4.get_text() =='':
517                                 value = 0.0
518                         else:
519                                 value = float(entry4.get_text())
520
521                 if entry3.get_text() != '':
522                         func,arg = unit_dic[entry3.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 # vbox2 is mainLayout
552 # scrolledwindow4 is categoryScrolledWindow
553 # cat_clist is categoryView
554 # vbox1 is unitConversionLayout
555 #       hbox1 is selectedUnitLayouta
556 #               unitName is the unit name
557 #               unitValue is the value
558 #               unitSymbol is the unit
559 #       hbox2 is previousSelectedUnitLayouta
560 #               entry3 is the unit name
561 #               entry4 is the value
562 #               label2 is the unit
563 #       vpand1 is unitsAndDescriptionPane
564 #               scrolledWindow1 is unitListScrolledWindow
565 #                       clist1 is unitsView
566 #               scrolledWindow2 is unitDescriptionScrolledWindow
567 #                       text1 is unitDescription
568 #       hbox3 is the search box
569 def main():
570         global mainWindow
571         global cat_clist
572         global cat_model
573         global unitValue
574         global unitName
575         global unitSymbol
576         global clist1
577         global calculate
578         global shortlistcheck
579         global about_box
580         global text1
581         global column1
582         global column2
583         global column3
584         global entry3
585         global entry4
586         global label2
587         global find_label
588         global find_entry
589         global col
590         global edit_shortlist1
591
592         logging.basicConfig(level=logging.DEBUG)
593
594         try:
595                 os.makedirs(constants._data_path_)
596         except OSError, e:
597                 if e.errno != 17:
598                         raise
599
600         #check to see if glade file is in current directory (user must be running from download untar directory)
601         _glade_files = [
602                 os.path.join(os.path.dirname(__file__), "gonvert.glade"),
603                 os.path.join(os.path.dirname(__file__), "../data/gonvert.glade"),
604                 os.path.join(os.path.dirname(__file__), "../lib/gonvert.glade"),
605                 '/usr/lib/gonvert/gonvert.glade',
606         ]
607         for gladePath in _glade_files:
608                 if os.path.isfile(gladePath):
609                         homepath = os.path.dirname(gladePath)
610                         pixmapspath = "/".join((homepath, "pixmaps"))
611                         widgets = gtk.glade.XML(gladePath)
612                         break
613         else:
614                 return
615
616         calculate = Ccalculate()
617         mainWindow = widgets.get_widget('mainWindow')
618
619         #Restore window size from previously saved settings if it exists and is valid.
620         windowDatPath = "/".join((constants._data_path_, "window.dat"))
621         if os.path.exists(windowDatPath):
622                 #Retrieving previous window settings from ~/.gonvert/window.dat
623                 saved_window = pickle.load(open(windowDatPath, "r"))
624                 #If the 'size' has been stored, then extract size from saved_window.
625                 if saved_window.has_key('size'):
626                         a, b = saved_window['size']
627                         mainWindow.resize(a, b)
628                 else:
629                         #Maximize if no previous size was found
630                         #mainWindow.maximize()
631                         pass
632         else:
633                 #Maximize if no previous window.dat file was found
634                 #mainWindow.maximize()
635                 pass
636
637         mainWindow.set_title('gonvert- %s - Unit Conversion Utility' % constants.__version__);
638         iconPath = pixmapspath + '/gonvert.png'
639         if os.path.exists(iconPath):
640                 mainWindow.set_icon(gtk.gdk.pixbuf_new_from_file(iconPath))
641         else:
642                 _moduleLogger.warn("Error: Could not find gonvert icon: %s" % iconPath)
643
644         #--------- connections to GUI ----------------
645         dic = {
646                 "on_exitMenuItem_activate": exitprogram,
647                 "on_mainWindow_destroy": exitprogram,
648                 "on_cat_clist_select_row": click_category,
649                 "on_clist1_click_column": click_column,
650                 "on_unitValue_changed": calculate.top,
651                 "on_entry4_changed": calculate.bottom,
652                 "on_write_units1_activate": write_units,
653                 "on_find_button_clicked": find_units,
654                 "on_find_entry_key_press_event": find_key_press,
655                 "on_find_entry_changed": find_entry_changed,
656                 "on_about1_activate": about_clicked,
657                 "on_about_close_clicked": about_hide,
658                 "on_messagebox_ok_clicked": messagebox_ok_clicked,
659                 "on_clear_selections1_activate": clear_selections,
660                 "on_clist1_cursor_changed": click_unit,
661                 "on_clist1_button_released": button_released,
662                 "on_mainWindow_size_allocate": app_size_changed,
663                 "on_shortlistcheck_toggled": shortlist_changed,
664                 "on_edit_shortlist1_activate": edit_shortlist,
665          }
666
667         widgets.signal_autoconnect (dic);
668         mainWindow.connect("destroy", exitprogram)
669
670         def change_menu_label(labelname,newtext):
671                 item_label = widgets.get_widget(labelname).get_children()[0]
672                 item_label.set_text(newtext)
673         def change_label(labelname,newtext):
674                 item_label = widgets.get_widget(labelname)
675                 item_label.set_text(newtext)
676
677         change_menu_label('fileMenuItem',_('File'))
678         change_menu_label('exitMenuItem',_('Exit'))
679         change_menu_label('toolsMenuItem',_('Tools'))
680         change_menu_label('clear_selections1',_('Clear selections'))
681         change_menu_label('write_units1',_('Write Units'))
682         change_menu_label('helpMenuItem',_('Help'))
683         change_menu_label('aboutMenuItem',_('About'))
684
685         change_menu_label('find_button',_('Find'))
686
687         shortlistcheck = widgets.get_widget('shortlistcheck')
688         edit_shortlist1 = widgets.get_widget('edit_shortlist1')
689
690         cat_clist = widgets.get_widget('cat_clist' )
691
692         clist1 = widgets.get_widget('clist1')
693         clist1_selection=clist1.get_selection()
694
695         unitName = widgets.get_widget('unitName')
696         unitValue = widgets.get_widget('unitValue')
697         entry3 = widgets.get_widget('entry3')
698         entry4 = widgets.get_widget('entry4')
699         about_box = widgets.get_widget('about_box')
700         messagebox = widgets.get_widget('msgbox')
701         messageboxtext = widgets.get_widget('msgboxtext')
702
703         about_image = widgets.get_widget('about_image')
704         about_image.set_from_file(pixmapspath +'gonvert.png')
705         versionlabel = widgets.get_widget('versionlabel')
706         versionlabel.set_text(constants.__version__)
707
708         unitSymbol =widgets.get_widget('unitSymbol')
709         label2 =widgets.get_widget('label2')
710
711         text1 = widgets.get_widget('text1' )
712
713         find_entry = widgets.get_widget('find_entry')
714         find_label = widgets.get_widget('find_label')
715
716         #insert a column into the units list even though the heading will not be seen
717         renderer = gtk.CellRendererText()
718         column1 = gtk.TreeViewColumn( _('Unit Name'), renderer )
719         column1.set_property( 'resizable', 1 )
720         column1.add_attribute( renderer, 'text', 0 )
721         column1.set_clickable(True)
722         column1.connect("clicked",click_column)
723         clist1.append_column( column1 )
724
725         column2 = gtk.TreeViewColumn( _('Value'), renderer )
726         column2.set_property( 'resizable', 1 )
727         column2.add_attribute( renderer, 'text', 1 )
728         column2.set_clickable(True)
729         column2.connect("clicked",click_column)
730         clist1.append_column( column2 )
731
732         column3 = gtk.TreeViewColumn( _('Units'), renderer )
733         column3.set_property( 'resizable', 1 )
734         column3.add_attribute( renderer, 'text', 2 )
735         column3.set_clickable(True)
736         column3.connect("clicked",click_column)
737         clist1.append_column( column3 )
738
739         #Insert a column into the category list even though the heading will not be seen
740         renderer = gtk.CellRendererText()
741         col = gtk.TreeViewColumn( 'Title', renderer )
742         col.set_property( 'resizable', 1 )
743         col.add_attribute( renderer, 'text', 0 )
744         cat_clist.append_column( col )
745
746         cat_model = gtk.ListStore(gobject.TYPE_STRING)
747         cat_clist.set_model(cat_model)
748         #colourize each row differently for easier reading
749         cat_clist.set_property( 'rules_hint',1)
750
751         #Populate the catagories list
752         keys = unit_data.list_dic.keys()
753         keys.sort()
754         for key in keys:
755                 iter = cat_model.append()
756                 cat_model.set(iter,0,key)
757
758         ToolTips=gtk.Tooltips()
759         find_button = widgets.get_widget('find_button')
760         ToolTips.set_tip(find_button,_(u'Find unit (F6)'))
761
762         #Restore selections from previously saved settings if it exists and is valid.
763         historical_catergory_found=False
764         selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
765         if os.path.exists(selectionsDatPath):
766                 #Retrieving previous selections from ~/.gonvert/selections.dat
767                 selections=pickle.load(open(selectionsDatPath,'r'))
768                 #Restoring previous selections.
769                 #
770                 #Make a list of categories to determine which one to select
771                 categories=unit_data.list_dic.keys()
772                 categories.sort()
773                 #
774                 #If the 'selected_unts' has been stored, then extract evil_globals.selected_units from selections.
775                 if selections.has_key('evil_globals.selected_units'):
776                         evil_globals.selected_units=selections['evil_globals.selected_units']
777                 #Make sure that the 'evil_globals.selected_category' has been stored.
778                 if selections.has_key('evil_globals.selected_category'):
779                         #Match an available category to the previously selected category.
780                         for counter in range(len(categories)):
781                                 if selections['evil_globals.selected_category']==categories[counter]:
782                                         # Restore the previously selected category.
783                                         cat_clist.set_cursor(counter, col, False )
784                                         cat_clist.grab_focus()
785                         historical_catergory_found=True
786
787         if not historical_catergory_found:
788                 print "Couldn't find saved category, using default."
789                 #If historical records were not kept then default to 
790                 # put the focus on the first category
791                 cat_clist.set_cursor(0, col, False)
792                 cat_clist.grab_focus()
793
794         restore_units()
795
796         gtk.main()
797
798
799 if __name__ == "__main__":
800         main()