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