diff Gtk/gui.py @ 26:16f91684686b default tip

Upgrade to python 3. Keep python 2/3 compatibility
author Miguel Ángel Bárcena Rodríguez <miguelangel@obraencurso.es>
date Tue, 18 Jun 2019 17:50:23 +0200
parents 189f8274aecd
children
line wrap: on
line diff
--- a/Gtk/gui.py	Mon May 20 13:18:33 2019 +0200
+++ b/Gtk/gui.py	Tue Jun 18 17:50:23 2019 +0200
@@ -46,7 +46,26 @@
 
 # python 2/3 compatibility
 from __future__ import absolute_import, division, print_function, unicode_literals
-
+from builtins import str as text
+from six import text_type
+
+def textinp2(textstring):
+    """textinp2(textstring)
+    
+    python2 decode textstring with utf-8
+    python3 raise except and do nothing with textstring
+    
+    return textstring
+    
+    All output gtk string must be passed by textinp2
+    """
+    try:
+        # python2 works, python3 raise except and do nothing with textstring
+        textstring = text(textstring, "utf-8")
+    except TypeError:
+        pass
+    return textstring
+    
 # Standar Modules
 import sys
 import os
@@ -81,20 +100,23 @@
         _pixbufIcon = GdkPixbuf.Pixbuf.new_from_file(_icon_file)
         _pixbufIcons.append(_pixbufIcon)
     else:
-        print(utils.mapping(_("The icon file does not exist. '$1'"),
-          (str(globalVars.getAppPath(_icon)),)) )
+        _tuni = _("The icon file does not exist. '$1'")
+        _uni = utils.mapping(_tuni, (globalVars.getAppPath(_icon),))
+        print(_uni )
 if len(_pixbufIcons) > 0:
     Gtk.Window.set_default_icon_list(_pixbufIcons)
 
 else:
-    print(utils.mapping(_("The icon file does not exist. '$1'"),
-          (str(globalVars.getAppPath("ICON")),)) )
+    _tuni = _("The icon file does not exist. '$1'")
+    _uni = utils.mapping(_tuni, (globalVars.getAppPath("ICON"),))
+    print(_uni )
 
 # Autodetect desktop
 if globalVars.desktop["autodetect"]:
     openwith.autodetect_desktop()
-    print(utils.mapping(_("pyArq-Presupuestos running on $1"),
-                        (globalVars.desktop["desktop"],)))
+    _tuni = _("pyArq-Presupuestos running on $1")
+    _uni = utils.mapping(_tuni, (globalVars.desktop["desktop"],))
+    print(_uni)
 
 
 class App(Gtk.Application):
@@ -659,7 +681,9 @@
             if len(self.__page_list) == 0:
                 self._disable_navigation()
         else:
-            raise IndexError( _("The page is not in the page list") )
+            _tuni =  _("The page is not in the page list") 
+            _str = _tuni.encode("utf-8")
+            raise IndexError(_str)
 
     def _menuitemGoToRoot(self, action, parameter):
         """_menuitemGoToRoot(action, parameter)
@@ -829,9 +853,13 @@
         If the selected file has a bc3 extension 
         _launchProgressWindow is called
         """
-        _file = filename
+        _file = filename # string in python 2, unicode in python 3
         if sys.getfilesystemencoding():
-            _file = _file.decode(sys.getfilesystemencoding())
+            try:
+                # python2 works, python3 raise except and do nothing with _file
+                _file = text(filename, sys.getfilesystemencoding())
+            except TypeError:
+                pass
         self.__file = _file
         _filename = os.path.basename(self.__file)
         _filename_ext = _filename.split(".")[-1]
@@ -1008,7 +1036,7 @@
         
         Sets progress
         """
-        _progress = str(int(round(100 * percent,0)))
+        _progress = text(int(round(100 * percent,0)))
         self.__progress = percent
 
     def readFile_send_message(self, message):
@@ -1094,7 +1122,7 @@
             return False
         else:
             self.__progress_bar.set_fraction(self.__progress)
-            _text = "%s%%" %str(int(round(100 * self.__progress,0)))
+            _text = "%s%%" %text(int(round(100 * self.__progress,0)))
             self.__progress_bar.set_text(_text)
             return True
 
@@ -1460,23 +1488,27 @@
         """
         if pane_path is None:
             pane_path = (0,)
-        if not isinstance(list_paned , list):
-            raise ValueError( _("The value must be a list") )
+        if not isinstance(list_paned, list):
+            _tuni = _("The value must be a list") 
+            _str = _tuni.encode("utf-8")
+            raise ValueError(_str)
         if list_paned[0] == "v" or  list_paned[0] == "h":
             if len(list_paned) != 3:
-                raise ValueError( _("Incorrect len") )
-            if not isinstance(list_paned[1],list):
+                _tuni = _("Incorrect len") 
+                _str = _tuni.encode("utf-8")
+                raise ValueError(_str)
+            if not isinstance(list_paned[1], list):
                 list_paned[1] = [list_paned[1]]
-            if not isinstance(list_paned[2],list):
+            if not isinstance(list_paned[2], list):
                 list_paned[2] = [list_paned[2]]
-            _item1 = self._itemsFactory(list_paned[1],pane_path + (0,))
-            _item2 = self._itemsFactory(list_paned[2],pane_path + (1,)) 
+            _item1 = self._itemsFactory(list_paned[1], pane_path + (0,))
+            _item2 = self._itemsFactory(list_paned[2], pane_path + (1,)) 
             _item = Paned(list_paned[0], pane_path, _item1, _item2)
         elif list_paned[0] == "DecompositionList":
-            _item = View( "DecompositionList", self.__budget,
+            _item = View("DecompositionList", self.__budget,
                 weakref.ref(self), pane_path, self.__active_path_record, True)
         elif list_paned[0] == "RecordDescription":
-            _item = View( "RecordDescription", self.__budget,weakref.ref(self),
+            _item = View("RecordDescription", self.__budget,weakref.ref(self),
                 pane_path, self.__active_path_record, True)
         elif list_paned[0] == "Measure":
             _item = View("Measure", self.__budget, weakref.ref(self),
@@ -1484,7 +1516,7 @@
         elif list_paned[0] == "Sheet of Conditions":
             _item  = View("Sheet of Conditions",
                           self.__budget, weakref.ref(self), pane_path,
-                self.__active_path_record)
+                          self.__active_path_record)
         elif list_paned[0] == "FileView":
             _item  = View("FileView", self.__budget, weakref.ref(self),
                           pane_path, self.__active_path_record)
@@ -1493,8 +1525,10 @@
                           pane_path, self.__active_path_record)
         else:
             _item = None
-            raise ValueError( utils.mapping(_("Incorrect item $1"),
-                  (str(list_paned[0]),)) )
+            _tuni = _("Incorrect item $1")
+            _uni = utils.mapping(_tuni, (text(list_paned[0]),))
+            _str = _uni.encode("utf-8")
+            raise ValueError(_str)
         return _item
 
     def _setActivePathRecord(self, path_record):
@@ -1509,8 +1543,10 @@
                 self.__active_path_record = path_record
                 self._appendHistory(path_record)
             else:
-                raise ValueError( utils.mapping(_("The budget does not have "\
-                    "the path record: $1"), (str(path_record),)) )
+                _tuni = _("The budget does not have the path record: $1")
+                _uni = utils.mapping(_tuni, (text(path_record),))
+                _str = _uni.encode("utf-8")
+                raise ValueError(_str)
 
     def _appendHistory(self, path):
         """_appendHistory(path))
@@ -1644,7 +1680,7 @@
         _code = self.budget.getCode(record_path)
         _record = self.budget.getRecord(_code)
         _summary = _record.summary
-        _text = _code.decode("utf8") + " " + _summary.decode("utf8")
+        _text = _code + " " + _summary
         if len(_text) > 30:
             _text = _text[:27] + "..."
         _icon = self._getImage(_record)
@@ -1925,8 +1961,10 @@
             _view_icon = Gtk.Image()
             _view_icon.set_from_file(globalVars.getAppPath("COMPANY-ICON"))
         else:
-            raise ValueError( _(utils.mapping("Invalid type of View: $1",
-                  view_type)) )
+            _tuni = _("Invalid type of View: $1")
+            _uni = utils.mapping(_tuni, view_type)
+            _str = _uni.encode("utf-8")
+            raise ValueError(_str)
         _view_icon.show()
         _combobox.connect("changed", self._change_combo)
         _combobox.show()
@@ -2258,7 +2296,9 @@
         self.__orientation = orientation
         if not isinstance(item1.widget, Gtk.Widget) or \
            not isinstance(item2.widget, Gtk.Widget):
-            raise ValueError( _("The item must be a widget object.") )
+            _tuni = _("The item must be a widget object.")
+            _str = _tuni.encode("utf-8")
+            raise ValueError(_str)
         if orientation == "v":
             self.__widget = Gtk.Paned.new(Gtk.Orientation(1))
             self.__widget.set_wide_handle(True) 
@@ -2266,7 +2306,9 @@
             self.__widget = Gtk.Paned.new(Gtk.Orientation(0))
             self.__widget.set_wide_handle(True) 
         else:
-            raise ValueError( _("Invalid orientation.") )
+            _tuni = _("Invalid orientation.")
+            _str = _tuni.encode("utf-8")
+            raise ValueError(_str)
         self.__widget.pack1(item1.widget,True,False)
         self.__widget.pack2(item2.widget,True,False)
         self.__widget.show()
@@ -2638,7 +2680,9 @@
         # TODO: to group all columns in a dicctionary
         # Budget
         if not isinstance(budget, base.Budget):
-            raise ValueError( _("Argument must be a Budget object") )
+            _tuni = _("Argument must be a Budget object")
+            _str = _tuni.encode("utf-8")
+            raise ValueError(_str)
         self.__budget = budget
         self.__wr_page = wr_page
         self.__pane_path = pane_path
@@ -2905,19 +2949,19 @@
             _parent_code = self.budget.getCode(self.__active_path_record[:-1])
             _parent_record = self.__budget.getRecord(_parent_code)
             _amount = _budget.getStrAmount(self.__active_path_record)
-        _str = _("Code") + chr(10) + "[" + _code.decode("utf8") + "]"
+        _str = _("Code") + chr(10) + "[" + _code + "]"
         self.__code_column.set_title(_str)
-        _str = _("Unit") + chr(10) + "[" + _unit.decode("utf8") + "]"
+        _str = _("Unit") + chr(10) + "[" + _unit + "]"
         self.__unit_column.set_title(_str)
         _str = _("Description") + chr(10) + "[" + \
-               _description.decode("utf8") + "]"
+               _description + "]"
         self.__description_column.set_title(_str)
         self.__measure_column.set_title(
             _("Measure") + chr(10) + "[" + _stryield + "]")
         self.__price_column.set_title(
             _("Price") + chr(10) + "[" + _price + "]")
         self.__amount_column.set_title(
-            _("Amount") + chr(10) + "[" + str(_amount) + "]")
+            _("Amount") + chr(10) + "[" + text(_amount) + "]")
 
     def _setListstoreValues(self, path_record):
         """_setListstoreValues(path_record)
@@ -2928,7 +2972,9 @@
         self.__liststore.clear()
         _budget = self.__budget
         if not _budget.hasPath(path_record):
-            raise ValueError( _("Invalid path") )
+            _tuni = _("Invalid path")
+            _str = _tuni.encode("utf-8")
+            raise ValueError(_str)
         else:
             _parent_code = _budget.getCode(path_record)
             for N,_code in enumerate(_budget.getchildren(_parent_code)):
@@ -2977,7 +3023,7 @@
         _number = _row_path[-1]
         _record = tree_model[_row_path][0]
         if column is self.__index_column:
-            cell_renderer.set_property('text', str(_number + 1))
+            cell_renderer.set_property('text', text(_number + 1))
             self.__index_column.get_cells()[1].set_property(
                 'cell-background', lcolor[_number % 2])
         elif column is self.__code_column:
@@ -3008,7 +3054,7 @@
             _parent_record = self.__budget.getRecord(_parent_code)
             _amount = self.budget.getStrAmount(
                         self.__active_path_record + (_number,))
-            cell_renderer.set_property('text', str(_amount))
+            cell_renderer.set_property('text', text(_amount))
         elif column is self.__type_column:
             _hierarchy = tree_model[_row_path][0].recordType.hierarchy
             _type = tree_model[_row_path][0].recordType.type
@@ -3272,7 +3318,9 @@
         if path_record is None:
             path_record = (0,)
         if not isinstance(budget, base.Budget):
-            raise ValueError( _("Argument must be a Budget object") )
+            _tuni = _("Argument must be a Budget object")
+            _str = _tuni.encode("utf-8")
+            raise ValueError(_str)
         self.__budget = budget
         self.__wr_page = page
         self.__pane_path = pane_path
@@ -3527,7 +3575,7 @@
         _measure = self.__budget.getMeasure(self.__active_path_record)
         _DS = self.__budget.getDecimals("DS")
         _total = _measure.measure
-        _total_str = ("%." + str(abs(_DS)) + "f" ) % _total
+        _total_str = ("%." + text(abs(_DS)) + "f" ) % _total
         self.columns[1].set_title(_("Type"))  # Σ parcial Σ total
         self.columns[2].set_title(_("Comment"))
         self.columns[3].set_title(_("N\n(a)"))
@@ -3547,7 +3595,9 @@
         self.__liststore.clear()
         _budget = self.__budget
         if not _budget.hasPath(path_record):
-            raise ValueError( _("Invalid path") )
+            _tuni = _("Invalid path")
+            _str = _tuni.encode("utf-8")
+            raise ValueError(_str)
         else:
             _measure = _budget.getMeasure(path_record)
             if isinstance(_measure, base.Measure):
@@ -3556,8 +3606,10 @@
                     _values = [ _line ]
                     _treeiter = self.__liststore.append(_values)
             else:
-                raise ValueError( utils.mapping(_("measure must be a Measure "\
-                      "object. Type: $1"), (str(type(_measure)),)) )
+                _tuni = _("measure must be a Measure object. Type: $1")
+                _uni = utils.mapping(_tuni, (text(type(_measure)),))
+                _str = _tuni.encode("utf-8")
+                raise ValueError(_str)
 
     def _colorCell(self, column, cell_renderer, tree_model, iter, lcolor):
         """_colorCell(column, cell_renderer, tree_model, iter, lcolor)
@@ -3587,7 +3639,7 @@
         _row_path = tree_model.get_path(iter)
         _number = _row_path[-1]
         if column is self.__index_column:
-            cell_renderer.set_property('text', str(_number + 1))
+            cell_renderer.set_property('text', text(_number + 1))
             self.__index_column.get_cells()[1].set_property(
                 'cell-background', lcolor[_number % 2])
         elif column is self.__linetype_column:
@@ -3605,35 +3657,35 @@
                         self.__calculatedline_icon)
         elif column is self.__comment_column:
             _measure = tree_model[_row_path][0]
-            _comment = str(_measure.comment)
+            _comment = text(_measure.comment)
             cell_renderer.set_property('text', _comment)
         elif column is self.__units_column:
             _measure = tree_model[_row_path][0]
             _units = _measure.units
             if isinstance(_units, float):
                 _DN = self.__budget.getDecimals("DN")
-                _units = ("%." + str(abs(_DN)) + "f" ) % _units
+                _units = ("%." + text(abs(_DN)) + "f" ) % _units
             cell_renderer.set_property('text', _units)
         elif column is self.__length_column:
             _measure = tree_model[_row_path][0]
             _length = _measure.length
             if isinstance(_length, float):
                 _DD = self.__budget.getDecimals("DD")
-                _length = ("%." + str(abs(_DD)) + "f" ) % _length
+                _length = ("%." + text(abs(_DD)) + "f" ) % _length
             cell_renderer.set_property('text', _length)
         elif column is self.__width_column:
             _measure = tree_model[_row_path][0]
             _width = _measure.width
             if isinstance(_width, float):
                 _DD = self.__budget.getDecimals("DD")
-                _width = ("%." + str(abs(_DD)) + "f" ) % _width
+                _width = ("%." + text(abs(_DD)) + "f" ) % _width
             cell_renderer.set_property('text', _width)
         elif column is self.__height_column:
             _measure = tree_model[_row_path][0]
             _height = _measure.height
             if isinstance(_height, float):
                 _DD = self.__budget.getDecimals("DD")
-                _height = ("%." + str(abs(_DD)) + "f" ) % _height
+                _height = ("%." + text(abs(_DD)) + "f" ) % _height
             cell_renderer.set_property('text', _height)
         elif column is self.__formula_column:
             _measure = tree_model[_row_path][0]
@@ -3648,7 +3700,7 @@
             else:
                 if isinstance(_parcial, float):
                     _DS = self.__budget.getDecimals("DS")
-                    _parcial = ("%." + str(abs(_DS)) + "f" ) % _parcial
+                    _parcial = ("%." + text(abs(_DS)) + "f" ) % _parcial
             cell_renderer.set_property('text', _parcial)
         elif column is self.__subtotal_column:
             _measure_line = tree_model[_row_path][0]
@@ -3663,7 +3715,7 @@
                 lcolor = [_color, _color]
                 if isinstance(_subtotal, float):
                     _DS = self.__budget.getDecimals("DS")
-                    _subtotal= ("%." + str(abs(_DS)) + "f" ) % _subtotal
+                    _subtotal= ("%." + text(abs(_DS)) + "f" ) % _subtotal
                 cell_renderer.set_property('text', _subtotal)
             else:
                 cell_renderer.set_property('text', "")
@@ -3854,9 +3906,10 @@
         _textview.show()
         _vbox = Gtk.Grid()
         _vbox.set_orientation(Gtk.Orientation(1)) # 1 Vertical
-        self.__label = Gtk.Label(utils.mapping(_("Description text of the "\
-                     "record $1"), (str(self.__budget.getCode(
-                    self.__active_path_record)),)))
+        _tuni = _("Description text of the record $1")
+        _ucode = self.__budget.getCode(self.__active_path_record)
+        _uni = utils.mapping(_tuni, (_ucode,))
+        self.__label = Gtk.Label(_uni)
         self.__label.set_alignment(0, 0)
         self.__label.show()
         _vbox.add(self.__label)
@@ -3875,8 +3928,9 @@
         _budget = self.__budget
         self.__active_path_record = path_record
         _code = _budget.getCode(self.__active_path_record)
-        self.__label.set_text(utils.mapping(_("Description text of the record "\
-            "$1"), (_code.decode("utf8"),)))
+        _tuni = _("Description text of the record $1")
+        _uni = utils.mapping(_tuni, (_code,))
+        self.__label.set_text(_uni)
         _text = _budget.getRecord(_code).text
         self.__textbuffer.set_text(_text)
 
@@ -4029,9 +4083,10 @@
         _budget = budget
         _main_box = Gtk.Grid()
         _main_box.set_orientation(Gtk.Orientation(1)) # 1 Vertical
-        self.__label = Gtk.Label(utils.mapping(_("Sheet of Conditions of the "\
-                       "record $1"), (self.__budget.getCode(
-                       self.__active_path_record),)))
+        _tuni = _("Sheet of Conditions of the record $1")
+        _ucode = self.__budget.getCode(self.__active_path_record)
+        _uni = utils.mapping(_tuni, (_ucode,))
+        self.__label = Gtk.Label(_uni)
         self.__label.set_xalign(0)
         self.__label.set_yalign(0)
         self.__label.show()
@@ -4237,8 +4292,9 @@
         _budget = self.__budget
         self.__active_path_record = path_record
         _code = _budget.getCode(self.__active_path_record)
-        self.__label.set_text(utils.mapping(_("Sheet2 of Conditions of the "\
-                     "record $1"), (_code,)))
+        _tuni = _("Sheet2 of Conditions of the record $1")
+        _uni = utils.mapping(_tuni, (_code,))
+        self.__label.set_text(_uni)
         self._setFields()
 
     def runMessage(self, message, pane_path, arg=None):
@@ -4697,7 +4753,9 @@
         self.__selection = None
         # Seting init args
         if not isinstance(budget, base.Budget):
-            raise ValueError( _("Argument must be a Budget object") )
+            _tuni = _("Argument must be a Budget object")
+            _str = _tuni.encode("utf-8")
+            raise ValueError(_str)
         self.__budget = budget
         self.__wr_page = wr_page
         self.__pane_path = pane_path
@@ -4836,12 +4894,14 @@
         if len(path) == 1:
             # The selection is a company
             _company_key = self.__treestore[path][0]
+            _company_key = textinp2(_company_key)
             _company = self.__budget.getCompany(_company_key)
             _selection = "company"
             _values = _company.values
         else:
             # The selection is a office
             _company_key = self.__treestore[path[:1]][0]
+            _company_key = textinp2(_company_key)
             _company = self.__budget.getCompany(_company_key)
             _selection = "office"
             _office = _company.offices[path[1]]
@@ -4877,7 +4937,7 @@
         if message == "change_active":
             if _budget.hasPath(arg):
                 _path_record = arg
-                self._showMessageRecord( _path_record)
+                self._showMessageRecord(_path_record)
             pass
         elif message == "clear":
             self._clear()
@@ -4910,7 +4970,7 @@
         _row_path = tree_model.get_path(iter)
         _number = _row_path[-1]
         if column is self.__index_column:
-            cell_renderer.set_property('text', str(_number + 1))
+            cell_renderer.set_property('text', text(_number + 1))
             self.__index_column.get_cells()[1].set_property(
                 'cell-background', lcolor[_number % 2])
         if self.__treeview.get_cursor() == (_row_path,column):
@@ -5271,11 +5331,8 @@
                     _option_name = _option[1]
                     _option_type = _option[2]
                     _option_description = _option[3]
-                    #-# str and unicode
-                    if (isinstance(_option_key, str) or \
-                        isinstance(_option_key, unicode)) and \
-                       (isinstance(_option_name, str) or\
-                       isinstance(_option_name, unicode))and \
+                    if isinstance(_option_key, text_type) and \
+                       isinstance(_option_name, text_type) and \
                        _option_type in self.__option_types.keys():
                         self.__liststore.append([_option_key, _option_name, "",
                             _option_type, _option_description])
@@ -5297,7 +5354,7 @@
         Sets the Options values
         """
         if isinstance(values, dict):
-            for _option, _value in values.iteritems():
+            for (_option, _value) in values.items():
                 if _option in self.__option_dict:
                     _type = self.__option_dict[_option][2]
                     if _type == "boolean":
@@ -5319,7 +5376,7 @@
                             self.__liststore.set_value(_iter, 2, _value)
                             self.__option_dict[_option][1] = _value
                     elif _type == "string":
-                        if isinstance(_value, str):
+                        if isinstance(_value, text_type):
                             _num = self.__option_list.index(_option)
                             _iter = self.__liststore.get_iter((_num,))
                             self.__liststore.set_value(_iter, 2, _value)
@@ -5340,7 +5397,7 @@
                         else:
                             print(_("Icorrect type, must be list") )
                     elif _type == "color":
-                        if isinstance(_value, str):
+                        if isinstance(_value, text_type):
                             if Gdk.RGBA().parse(_value):
                                 print(_("Icorrect type, must be a parseable " \
                                         "color") )