22 _moduleLogger = logging.getLogger("gonvert_glade")
24 gettext.bindtextdomain('gonvert', '/usr/share/locale')
25 gettext.textdomain('gonvert')
29 def shortlist_changed(a):
31 if shortlistcheck.get_active():
37 def edit_shortlist(a):
38 print "edit shortlist"
39 if edit_shortlist1.get_active():
45 def app_size_changed(a,b):
46 ''"get current size of window as it changes.''"
47 evil_globals.window_size=app1.get_size()
50 def clear_selections(a):
51 selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
52 os.remove(selectionsDatPath)
53 evil_globals.selected_units={}
58 This routine saves the selections to a file, and
59 should therefore only be called when exiting the program.
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]
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)
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'))
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'))
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
90 def find_key_press(a,b):
91 #Check if the key pressed was an ASCII key
93 #Check if the key pressed was the 'Enter' key
94 if ord(b.string[0])==13:
95 #Execute the find units function
103 def about_hide(*args):
108 def messagebox_ok_clicked(a):
115 #check if 'new find' or 'last find' or 'next-find'
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=[]
120 #last-find = restart from top again
121 # = evil_globals.find_count=len(evil_globals.find_result)
123 #next-find = continue to next found location
124 # = evil_globals.find_count=0 and len(evil_globals.find_result)>0
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()
133 found_a_unit=0 #reset the 'found-a-unit' flag
135 for category in categories:
136 units=unit_data.list_dic[category].keys()
138 del units[0] # do not display .base_unit description key
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))
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).'))
158 find_label.set_text('Text not found') #Display error
159 else: #must be next-find or last-find
161 if evil_globals.find_count==len(evil_globals.find_result)-1:
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)
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
178 #Determine which column requires sorting
179 if col.get_title()==_(u"Unit Name"):
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"):
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)
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)
198 #declare a spot to hold the sorted list
201 #point to the first row
202 iter=unit_model.get_iter_first()
206 #grab all text from columns for sorting
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)
212 #do not bother sorting if the value column is empty
213 if unit_model.get_value(iter,1)=='' and selected_column==1:
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)
220 if unit_model.get_value(iter,1)==None or unit_model.get_value(iter,1)=='':
223 value_text = float(unit_model.get_value(iter,1))
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))
230 sorted_list.append((units_text,value_text,unit_text))
232 #point to the next row in the unit_model
233 iter=unit_model.iter_next(iter)
236 #check if no calculations have been made yet (don't bother sorting)
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
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:
249 if not evil_globals.value_sort_direction:
250 evil_globals.value_sort_direction=True
252 sorted_list.reverse()
253 evil_globals.value_sort_direction=False
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
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
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)
266 #colourize each row differently for easier reading
267 clist1.set_property( 'rules_hint',1)
269 #Clear out the description
270 text_model = gtk.TextBuffer(None)
271 text1.set_buffer(text_model)
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)
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)
288 def click_category(row):
289 global unit_model, cat_model
290 global unit_dic, list_dic
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)
296 #Colourize each row alternately for easier reading
297 clist1.set_property( 'rules_hint',1)
299 #Clear out the description
300 text_model = gtk.TextBuffer(None)
301 text1.set_buffer(text_model)
303 #Determine the contents of the selected category row
304 selected,iter= row.get_selection().get_selected()
306 evil_globals.selected_category = cat_model.get_value(iter,0)
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)
315 unit_dic=unit_data.list_dic[selected.get_value(iter,0)]
316 keys = unit_dic.keys()
318 del keys[0] # do not display .base_unit description key
320 #Fill up the units descriptions and clear the value cells
322 iter = unit_model.append()
323 unit_model.set(iter,0,key,1,'',2,unit_dic[key][1])
336 global unit_dic, list_dic
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]:
343 #evil_globals.selected_units[evil_globals.selected_category]=[selected_unit,evil_globals.selected_units[evil_globals.selected_category][0]]
345 units=unit_data.list_dic[evil_globals.selected_category].keys()
347 del units[0] # do not display .base_unit description key
349 #Restore oldest selection first.
350 if evil_globals.selected_units[evil_globals.selected_category][1]:
353 if unit==evil_globals.selected_units[evil_globals.selected_category][1]:
354 clist1.set_cursor(unit_no,column1,True)
357 #Restore newest selection second.
360 if unit==evil_globals.selected_units[evil_globals.selected_category][0]:
361 clist1.set_cursor(unit_no,column1,True)
364 # select the text so user can start typing right away
366 entry2.select_region(0,-1)
369 def button_released(row,a):
374 evil_globals.calcsuppress = 1 #suppress calculations
376 #Determine the contents of the selected row.
377 selected,iter= clist1.get_selection().get_selected()
379 selected_unit=selected.get_value(iter,0)
381 unit_spec=unit_dic[selected_unit]
383 #Clear out the description
384 text_model = gtk.TextBuffer(None)
385 text1.set_buffer(text_model)
387 enditer = text_model.get_end_iter()
388 text_model.insert(enditer,unit_spec[2])
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:
396 label2.set_text(label1.get())
397 entry1.set_text(selected_unit)
399 entry2.set_text(selected.get_value(iter,1))
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":
406 entry2.set_text("0.0")
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]]
414 evil_globals.selected_units[evil_globals.selected_category]=[selected_unit,'']
416 # select the text so user can start typing right away
418 entry2.select_region(0,-1)
420 evil_globals.calcsuppress = 0 #enable calculations
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)
429 while gtk.events_pending():
430 gtk.mainiteration (False)
431 category_keys=unit_data.list_dic.keys()
435 print 'gonvert-%s%s' % (
436 constants.__version__,
437 _(u' - Unit Conversion Utility - Convertible units listing:')
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()
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
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)
456 class Ccalculate(object):
462 if evil_globals.calcsuppress == 1:
463 #evil_globals.calcsuppress = 0
465 # determine if value to be calculated is empty
466 if evil_globals.selected_category == "Computer Numbers":
467 if entry2.get_text() =='':
470 value = entry2.get_text()
472 if entry2.get_text() =='':
475 value = float(entry2.get_text())
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
481 keys = unit_dic.keys()
486 #point to the first row
487 iter=unit_model.get_iter_first()
490 #get the formula from the name at the row
491 func,arg = unit_dic[unit_model.get_value(iter,0)][0]
493 #set the result in the value column
494 unit_model.set(iter,1,str(apply(func.from_base,(base,arg,))))
496 #point to the next row in the unit_model
497 iter=unit_model.iter_next(iter)
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
507 if evil_globals.calcsuppress == 1:
508 #evil_globals.calcsuppress = 0
510 # determine if value to be calculated is empty
511 if evil_globals.selected_category == "Computer Numbers":
512 if entry4.get_text() =='':
515 value = entry4.get_text()
517 if entry4.get_text() =='':
520 value = float(entry4.get_text())
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
526 keys = unit_dic.keys()
531 #point to the first row
532 iter=unit_model.get_iter_first()
535 #get the formula from the name at the row
536 func,arg = unit_dic[unit_model.get_value(iter,0)][0]
538 #set the result in the value column
539 unit_model.set(iter,1,str(apply(func.from_base,(base,arg,))))
541 #point to the next row in the unit_model
542 iter=unit_model.iter_next(iter)
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
568 global shortlistcheck
571 logging.basicConfig(level=logging.DEBUG)
574 os.makedirs(constants._data_path_)
579 #check to see if glade file is in current directory (user must be running from download untar directory)
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',
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)
595 calculate = Ccalculate()
596 app1 = widgets.get_widget('app1')
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']
608 #Maximize if no previous size was found
612 #Maximize if no previous window.dat file was found
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))
621 _moduleLogger.warn("Error: Could not find gonvert icon: %s" % iconPath)
623 #--------- connections to GUI ----------------
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,
646 widgets.signal_autoconnect (dic);
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)
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'))
663 change_menu_label('find_button',_('Find'))
665 shortlistcheck = widgets.get_widget('shortlistcheck')
666 edit_shortlist1 = widgets.get_widget('edit_shortlist1')
668 cat_clist = widgets.get_widget('cat_clist' )
670 clist1 = widgets.get_widget('clist1')
671 clist1_selection=clist1.get_selection()
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')
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__)
686 label1 =widgets.get_widget('label1')
687 label2 =widgets.get_widget('label2')
689 text1 = widgets.get_widget('text1' )
691 find_entry = widgets.get_widget('find_entry')
692 find_label = widgets.get_widget('find_label')
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 )
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 )
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 )
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 )
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)
729 #Populate the catagories list
730 keys = unit_data.list_dic.keys()
733 iter = cat_model.append()
734 cat_model.set(iter,0,key)
736 ToolTips=gtk.Tooltips()
737 find_button = widgets.get_widget('find_button')
738 ToolTips.set_tip(find_button,_(u'Find unit (F6)'))
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.
748 #Make a list of categories to determine which one to select
749 categories=unit_data.list_dic.keys()
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
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()
777 if __name__ == "__main__":