cleaning up a function name
[gonvert] / src / gonvert_glade.py
index b8118de..242a7b0 100755 (executable)
@@ -85,15 +85,9 @@ class Gonvert(object):
                self._unitValue = widgets.get_widget('unitValue')
                self._previousUnitName = widgets.get_widget('previousUnitName')
                self._previousUnitValue = widgets.get_widget('previousUnitValue')
-               self._about_box = widgets.get_widget('about_box')
                messagebox = widgets.get_widget('msgbox')
                messageboxtext = widgets.get_widget('msgboxtext')
 
-               about_image = widgets.get_widget('about_image')
-               about_image.set_from_file(pixmapspath +'gonvert.png')
-               versionlabel = widgets.get_widget('versionlabel')
-               versionlabel.set_text(constants.__version__)
-
                self._unitSymbol = widgets.get_widget('unitSymbol')
                self._previousUnitSymbol = widgets.get_widget('previousUnitSymbol')
 
@@ -102,6 +96,8 @@ class Gonvert(object):
                self._findEntry = widgets.get_widget('findEntry')
                self._findLabel = widgets.get_widget('findLabel')
                findButton = widgets.get_widget('findButton')
+               ToolTips = gtk.Tooltips()
+               ToolTips.set_tip(findButton, _(u'Find unit (F6)'))
 
                #insert a self._categoryColumnumn into the units list even though the heading will not be seen
                renderer = gtk.CellRendererText()
@@ -139,29 +135,23 @@ class Gonvert(object):
                self._categoryView.set_property('rules_hint', 1)
 
                #Populate the catagories list
-               keys = unit_data.list_dic.keys()
-               keys.sort()
-               for key in keys:
+               for key in unit_data.UNIT_CATEGORIES:
                        iter = self._categoryModel.append()
                        self._categoryModel.set(iter, 0, key)
 
-               ToolTips = gtk.Tooltips()
-               ToolTips.set_tip(findButton, _(u'Find unit (F6)'))
-
                #--------- connections to GUI ----------------
                dic = {
                        "on_exit_menu_activate": self._on_user_exit,
                        "on_main_window_destroy": self._on_user_exit,
                        "on_categoryView_select_row": self._on_click_category,
                        "on_unitsView__on_click_unit_column": self._on_click_unit_column,
-                       "on_unitValue_changed": self.top,
-                       "on_previousUnitValue_changed": self.bottom,
+                       "on_unitValue_changed": self._on_unit_value_changed,
+                       "on_previousUnitValue_changed": self._on_previous_unit_value_changed,
                        "on_writeUnitsMenuItem_activate": self._on_user_write_units,
                        "on_findButton_clicked": self._on_user_find_units,
-                       "on_findEntry_key_press_event": self._on_find_key_press,
-                       "on_findEntry_changed": self._findEntry_changed,
+                       "on_findEntry_activated": self._on_user_find_units,
+                       "on_findEntry_changed": self._on_findEntry_changed,
                        "on_aboutMenuItem_activate": self._on_about_clicked,
-                       "on_about_close_clicked": self._on_about_hide,
                        "on_messagebox_ok_clicked": self.messagebox_ok_clicked,
                        "on_clearSelectionMenuItem_activate": self._on_user_clear_selections,
                        "on_unitsView_cursor_changed": self._on_click_unit,
@@ -178,6 +168,9 @@ class Gonvert(object):
                else:
                        _moduleLogger.warn("Error: Could not find gonvert icon: %s" % iconPath)
 
+               self._load_settings()
+
+       def _load_settings(self):
                #Restore window size from previously saved settings if it exists and is valid.
                windowDatPath = "/".join((constants._data_path_, "window.dat"))
                if os.path.exists(windowDatPath):
@@ -203,19 +196,14 @@ class Gonvert(object):
                        #Retrieving previous selections from ~/.gonvert/selections.dat
                        selections = pickle.load(open(selectionsDatPath, 'r'))
                        #Restoring previous selections.
-                       #
-                       #Make a list of categories to determine which one to select
-                       categories = unit_data.list_dic.keys()
-                       categories.sort()
-                       #
                        #If the 'selected_unts' has been stored, then extract self._selected_units from selections.
                        if 'selected_units' in selections:
                                self._selected_units = selections['selected_units']
                        #Make sure that the 'self._selected_category' has been stored.
                        if 'selected_category' in selections:
                                #Match an available category to the previously selected category.
-                               for counter in range(len(categories)):
-                                       if selections['selected_category'] == categories[counter]:
+                               for counter in range(len(unit_data.UNIT_CATEGORIES)):
+                                       if selections['selected_category'] == unit_data.UNIT_CATEGORIES[counter]:
                                                # Restore the previously selected category.
                                                self._categoryView.set_cursor(counter, self._categoryColumn, False)
                                                self._categoryView.grab_focus()
@@ -230,26 +218,7 @@ class Gonvert(object):
 
                self.restore_units()
 
-       def _on_shortlist_changed(self, a):
-               print "shortlist"
-               if self._shortlistcheck.get_active():
-                       print "1"
-               else:
-                       print "0"
-
-       def _on_edit_shortlist(self, a):
-               print "edit shortlist"
-               if self._toggleShortList.get_active():
-                       print "1"
-               else:
-                       print "0"
-
-       def _on_user_clear_selections(self, a):
-               selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
-               os.remove(selectionsDatPath)
-               self._selected_units = {}
-
-       def _on_user_exit(self, a):
+       def _save_settings(self):
                """
                This routine saves the selections to a file, and
                should therefore only be called when exiting the program.
@@ -277,91 +246,102 @@ class Gonvert(object):
                windowDatPath = "/".join((constants._data_path_, "window.dat"))
                pickle.dump(window_settings, open(windowDatPath, 'w'))
 
-               gtk.mainquit
-               sys.exit()
+       def _on_shortlist_changed(self, a):
+               raise NotImplementedError("%s" % self._shortlistcheck.get_active())
 
-       def _findEntry_changed(self, a):
-               #Clear out find results since the user wants to look for something new
-               self._find_result = [] #empty find result list
-               self._find_count = 0 #default to find result number zero
-               self._findLabel.set_text('') #clear result
+       def _on_edit_shortlist(self, a):
+               raise NotImplementedError("%s" % self._toggleShortList.get_active())
 
-       def _on_find_key_press(self, a, b):
-               #Check if the key pressed was an ASCII key
-               if len(b.string)>0:
-                       #Check if the key pressed was the 'Enter' key
-                       if ord(b.string[0]) == 13:
-                               #Execute the find units function
-                               _on_user_find_units(1)
+       def _on_user_clear_selections(self, a):
+               selectionsDatPath = "/".join((constants._data_path_, "selections.dat"))
+               os.remove(selectionsDatPath)
+               self._selected_units = {}
 
-       def _on_about_clicked(self, a):
-               self._about_box.show()
+       def _on_user_exit(self, a):
+               try:
+                       self._save_settings()
+               finally:
+                       gtk.main_quit()
 
-       def _on_about_hide(self, *args):
-               self._about_box.hide()
-               return gtk.TRUE
+       def _on_findEntry_changed(self, a):
+               """
+               Clear out find results since the user wants to look for something new
+               """
+               # switch to "new find" state
+               self._find_result = []
+               self._find_count = 0
+
+               # Clear our user message
+               self._findLabel.set_text('')
+
+       def _find_first(self):
+               assert len(self._find_result) == 0
+               assert self._find_count == 0
+               findString = string.lower(string.strip(self._findEntry.get_text()))
+               if not findString:
+                       return
 
-       def messagebox_ok_clicked(self, a):
-               messagebox.hide()
+               # Gather info on all the matching units from all categories
+               for catIndex, category in enumerate(unit_data.UNIT_CATEGORIES):
+                       units = unit_data.get_units(category)
+                       for unitIndex, unit in enumerate(units):
+                               loweredUnit = unit.lower()
+                               if loweredUnit in findString or findString in loweredUnit:
+                                       self._find_result.append((category, unit, catIndex, unitIndex))
 
-       def _on_user_find_units(self, a):
-               #check if 'new find' or 'last find' or 'next-find'
+               if not self._find_result:
+                       return
+
+               self._select_found_unit()
 
-               #new-find = run the find algorithm which also selects the first found unit
-               #         = self._find_count = 0 and self._find_result = []
+       def _find_wrap_around(self):
+               assert 0 < len(self._find_result)
+               assert self._find_count + 1 == len(self._find_result)
+               #select first result
+               self._find_count = 0
+               self._select_found_unit()
 
-               #last-find = restart from top again
-               #          = self._find_count = len(self._find_result)
+       def _find_next(self):
+               assert 0 < len(self._find_result)
+               assert self._find_count + 1 < len(self._find_result)
+               self._find_count += 1
+               self._select_found_unit()
 
-               #next-find = continue to next found location
-               #           = self._find_count = 0 and len(self._find_result)>0
+       def _select_found_unit(self):
+               assert 0 < len(self._find_result)
+               #check if next find is in a new category (prevent category changes when unnecessary
+               if self._selected_category != self._find_result[self._find_count][0]:
+                       self._categoryView.set_cursor(self._find_result[self._find_count][2], self._categoryColumn, False)
+               self._unitsView.set_cursor(self._find_result[self._find_count][3], self._unitNameColumn, True)
 
-               #check for new-find
+       def _on_user_find_units(self, a):
+               """
+               check if 'new find' or 'last find' or 'next-find'
+
+               new-find = run the find algorithm which also selects the first found unit
+                        = self._find_count = 0 and self._find_result = []
+
+               last-find = restart from top again
+                         = self._find_count = len(self._find_result)
+
+               next-find = continue to next found location
+                          = self._find_count = 0 and len(self._find_result)>0
+               """
                if len(self._find_result) == 0:
-                       find_string = string.lower(string.strip(self._findEntry.get_text()))
-                       #Make sure that a valid find string has been requested
-                       if len(find_string)>0:
-                               categories = unit_data.list_dic.keys()
-                               categories.sort()
-                               found_a_unit = 0 #reset the 'found-a-unit' flag
-                               cat_no = 0
-                               for category in categories:
-                                       units = unit_data.list_dic[category].keys()
-                                       units.sort()
-                                       del units[0] # do not display .base_unit description key
-                                       unit_no = 0
-                                       for unit in units:
-                                               if string.find(string.lower(unit), find_string) >= 0:
-                                                       found_a_unit = 1 #indicate that a unit was found
-                                                       #print "'", find_string, "'", " found at category = ", category, " unit = ", unit
-                                                       self._find_result.append((category, unit, cat_no, unit_no))
-                                               unit_no = unit_no+1
-                                       cat_no = cat_no+1
-
-                               if found_a_unit == 1:
-                                       #select the first found unit
-                                       self._find_count = 0
-                                       #check if next find is in a new category (prevent category changes when unnecessary
-                                       if self._selected_category != self._find_result[self._find_count][0]:
-                                               self._categoryView.set_cursor(self._find_result[0][2], self._categoryColumn, False)
-                                               self._unitsView.set_cursor(self._find_result[0][3], self._unitNameColumn, True)
-                                               if len(self._find_result)>1:
-                                                       self._findLabel.set_text(('Press Find for next unit. '+ str(len(self._find_result))+' result(s).'))
-                                               else:
-                                                       self._findLabel.set_text('Text not found') #Display error
-               else: #must be next-find or last-find
-                       #check for last-find
+                       self._find_first()
+               else:
                        if self._find_count == len(self._find_result)-1:
-                               #select first result
-                               self._find_count = 0
-                               self._categoryView.set_cursor(self._find_result[self._find_count][2], self._categoryColumn, False)
-                               self._unitsView.set_cursor(self._find_result[self._find_count][3], self._unitNameColumn, True)
-                       else: #must be next-find
-                               self._find_count = self._find_count+1
-                               #check if next find is in a new category (prevent category changes when unnecessary
-                               if self._selected_category != self._find_result[self._find_count][0]:
-                                       self._categoryView.set_cursor(self._find_result[self._find_count][2], self._categoryColumn, False)
-                               self._unitsView.set_cursor(self._find_result[self._find_count][3], self._unitNameColumn, True)
+                               self._find_wrap_around()
+                       else:
+                               self._find_next()
+
+               if not self._find_result:
+                       self._findLabel.set_text('Text not found')
+               else:
+                       resultsLeft = len(self._find_result) - self._find_count - 1
+                       self._findLabel.set_text(
+                               '%s result(s) left' % (resultsLeft, )
+                       )
 
        def _on_click_unit_column(self, col):
                """
@@ -411,7 +391,7 @@ class Gonvert(object):
                        if self._selected_category == "Computer Numbers":
                                value_text = self._unitModel.get_value(iter, 1)
                        else:
-                               if self._unitModel.get_value(iter, 1) == None or unit_model.get_value(iter, 1) == '':
+                               if self._unitModel.get_value(iter, 1) == None or self._unitModel.get_value(iter, 1) == '':
                                        value_text = ''
                                else:
                                        value_text = float(self._unitModel.get_value(iter, 1))
@@ -502,7 +482,7 @@ class Gonvert(object):
                self._unitValueColumn.set_sort_indicator(False)
                self._unitSymbolColumn.set_sort_indicator(False)
 
-               self._unitDataInCategory = unit_data.list_dic[selected.get_value(iter, 0)]
+               self._unitDataInCategory = unit_data.UNIT_DESCRIPTIONS[selected.get_value(iter, 0)]
                keys = self._unitDataInCategory.keys()
                keys.sort()
                del keys[0] # do not display .base_unit description key
@@ -526,10 +506,9 @@ class Gonvert(object):
                #Since category has just been clicked, the list will be sorted already.
                if self._selected_category in self._selected_units:
                        if self._selected_units[self._selected_category][0]:
-                               ''"debug ''"
                                #self._selected_units[self._selected_category] = [selected_unit, self._selected_units[self._selected_category][0]]
 
-                               units = unit_data.list_dic[self._selected_category].keys()
+                               units = unit_data.UNIT_DESCRIPTIONS[self._selected_category].keys()
                                units.sort()
                                del units[0] # do not display .base_unit description key
 
@@ -604,6 +583,9 @@ class Gonvert(object):
 
                self._calcsuppress = False #enable calculations
 
+       def messagebox_ok_clicked(self, a):
+               messagebox.hide()
+
        def _on_user_write_units(self, a):
                ''"Write the list of categories and units to stdout for documentation purposes.''"
                messagebox_model = gtk.TextBuffer(None)
@@ -612,18 +594,17 @@ class Gonvert(object):
                messagebox.show()
                while gtk.events_pending():
                        gtk.mainiteration(False)
-               category_keys = unit_data.list_dic.keys()
-               category_keys.sort()
+
                total_categories = 0
                total_units = 0
                print 'gonvert-%s%s' % (
                        constants.__version__,
                        _(u' - Unit Conversion Utility  - Convertible units listing: ')
                )
-               for category_key in category_keys:
+               for category_key in unit_data.UNIT_CATEGORIES:
                        total_categories = total_categories + 1
                        print category_key, ": "
-                       self._unitDataInCategory = unit_data.list_dic[category_key]
+                       self._unitDataInCategory = unit_data.UNIT_DESCRIPTIONS[category_key]
                        unit_keys = self._unitDataInCategory.keys()
                        unit_keys.sort()
                        del unit_keys[0] # do not display .base_unit description key
@@ -632,11 +613,8 @@ class Gonvert(object):
                                print "\t", unit_key
                print total_categories, ' categories'
                print total_units, ' units'
-               messagebox_model = gtk.TextBuffer(None)
-               messageboxtext.set_buffer(messagebox_model)
-               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)
 
-       def top(self, a):
+       def _on_unit_value_changed(self, a):
                if self._calcsuppress:
                        #self._calcsuppress = False
                        return
@@ -681,7 +659,7 @@ class Gonvert(object):
                                self._previousUnitValue.set_text(str(apply(func.from_base, (base, arg, ))))
                                self._calcsuppress = False
 
-       def bottom(self, a):
+       def _on_previous_unit_value_changed(self, a):
                if self._calcsuppress == True:
                        #self._calcsuppress = False
                        return
@@ -726,6 +704,17 @@ class Gonvert(object):
                                self._unitValue.set_text(str(apply(func.from_base, (base, arg, ))))
                                self._calcsuppress = False
 
+       def _on_about_clicked(self, a):
+               dlg = gtk.AboutDialog()
+               dlg.set_name(constants.__pretty_app_name__)
+               dlg.set_version("%s-%d" % (constants.__version__, constants.__build__))
+               dlg.set_copyright("Copyright 2009 - GPL")
+               dlg.set_comments("")
+               dlg.set_website("http://unihedron.com/projects/gonvert/gonvert.php")
+               dlg.set_authors(["Anthony Tekatch <anthony@unihedron.com>", "Ed Page <edpage@byu.net>"])
+               dlg.run()
+               dlg.destroy()
+
 
 def main():
        logging.basicConfig(level = logging.DEBUG)