def numDecode(numSt): numSt = numSt.strip() try: return int(numSt) except ValueError: pass numSt = toUnicode(numSt) tryLangs = digits.keys() if langSh in digits: tryLangs.remove(langSh) tryLangs.insert(0, langSh) for tryLang in tryLangs: tryLangDigits = digits[tryLang] numEn = '' for dig in numSt: if dig=='-': numEn += dig else: try: numEn += str(tryLangDigits.index(dig)) except ValueError as e: print('error in decoding num char %s'%dig) #raise e break else: return int(numEn) raise ValueError('invalid locale number %s'%numSt)
def __init__(self, sep, fields, arrow_select=True, page_inc=10): gtk.SpinButton.__init__(self) #### sep = toUnicode(sep) self.field = ContainerField(sep, *fields) self.arrow_select = arrow_select self.set_editable(True) ### self.digs = locale_man.getDigits() ### #### self.set_direction(gtk.TEXT_DIR_LTR) ## self is a gtk.Entry self.set_width_chars(self.field.getMaxWidth()) self.set_value(0) self.set_digits(0) gtk.SpinButton.set_range(self, -2, 2) self.set_increments(1, page_inc) #self.connect('activate', lambda obj: self.update()) self.connect('activate', self._entry_activate) self.connect('key-press-event', self._key_press) self.connect('scroll-event', self._scroll) self.connect('button-press-event', self._button_press) self.connect('button-release-event', self._button_release) self.connect( 'output', lambda obj: True ) ##Disable auto-numeric-validating(the entry text is not a numebr)
def textNumEncode(st, mode=None, changeSpecialChars=True, changeDot=False): if not enableNumLocale: mode = 'en' if mode==None: mode = langSh elif isinstance(mode, int): if langSh != 'en': try: mode = calTypes[mode].origLang except AttributeError: mode = langSh dig = getLangDigits(mode) res = u'' for c in toUnicode(st): try: i = int(c) except: if enableNumLocale: if c in (',', '_', '%'):## FIXME if changeSpecialChars: c = tr(c) elif c=='.':## FIXME if changeDot: c = tr(c) res += c else: res += dig[i] return res ## .encode('utf8')
def textNumEncode(st, mode=None, changeSpecialChars=True, changeDot=False): if not enableNumLocale: mode = 'en' if mode == None: mode = langSh elif isinstance(mode, int): if langSh != 'en': try: mode = calTypes[mode].origLang except AttributeError: mode = langSh dig = getLangDigits(mode) res = u'' for c in toUnicode(st): try: i = int(c) except: if enableNumLocale: if c in (',', '_', '%'): ## FIXME if changeSpecialChars: c = tr(c) elif c == '.': ## FIXME if changeDot: c = tr(c) res += c else: res += dig[i] return res ## .encode('utf8')
def numDecode(numSt): numSt = numSt.strip() try: return int(numSt) except ValueError: pass numSt = toUnicode(numSt) tryLangs = digits.keys() if langSh in digits: tryLangs.remove(langSh) tryLangs.insert(0, langSh) for tryLang in tryLangs: tryLangDigits = digits[tryLang] numEn = '' for dig in numSt: if dig == '-': numEn += dig else: try: numEn += str(tryLangDigits.index(dig)) except ValueError as e: print('error in decoding num char %s' % dig) #raise e break else: return int(numEn) raise ValueError('invalid locale number %s' % numSt)
def entry_plus(self, p): self.update() pos = self.get_position() self.field.getFieldAt(toUnicode(self.get_text()), self.get_position()).plus(p) self.set_text(self.field.getText()) self.set_position(pos)
def drawBoxText(cr, box, x, y, w, h, widget): ## now draw the text ## how to find the best font size based in the box's width and height, ## and font family? FIXME ## possibly write in many lines? or just in one line and wrap if needed? if box.text: #print(box.text) textW = 0.9 * w textH = 0.9 * h textLen = len(toUnicode(box.text)) #print('textLen=%s'%textLen) avgCharW = float(textW if rotateBoxLabel == 0 else max(textW, textH)) / textLen if avgCharW > 3: ## FIXME font = list(ui.getFont()) layout = widget.create_pango_layout( box.text) ## a pango.Layout object layout.set_font_description(pfontEncode(font)) layoutW, layoutH = layout.get_pixel_size() #print('orig font size: %s'%font[3]) normRatio = min( float(textW) / layoutW, float(textH) / layoutH, ) rotateRatio = min( float(textW) / layoutH, float(textH) / layoutW, ) if rotateBoxLabel != 0 and rotateRatio > normRatio: font[3] *= max(normRatio, rotateRatio) layout.set_font_description(pfontEncode(font)) layoutW, layoutH = layout.get_pixel_size() fillColor(cr, fgColor) ## before cr.move_to #print('x=%s, y=%s, w=%s, h=%s, layoutW=%s, layoutH=%s'\) # %(x,y,w,h,layoutW,layoutH) cr.move_to( x + (w - rotateBoxLabel * layoutH) / 2.0, y + (h + rotateBoxLabel * layoutW) / 2.0, ) cr.rotate(-rotateBoxLabel * pi / 2) cr.show_layout(layout) try: cr.rotate(rotateBoxLabel * pi / 2) except: print('counld not rotate by %s*pi/2 = %s' % ( rotateBoxLabel, rotateBoxLabel * pi / 2, )) else: font[3] *= normRatio layout.set_font_description(pfontEncode(font)) layoutW, layoutH = layout.get_pixel_size() fillColor(cr, fgColor) ## before cr.move_to cr.move_to( x + (w - layoutW) / 2.0, y + (h - layoutH) / 2.0, ) cr.show_layout(layout)
def keyPress(self, obj, gevent): kval = gevent.keyval kname = gdk.keyval_name(gevent.keyval).lower() #print kval, kname if kname in ( 'tab', 'escape', 'backspace', 'delete', 'insert', 'home', 'end', 'control_l', 'control_r', 'iso_next_group', ): return False elif kname == 'return': self.validate() return False elif kname=='up': self.numPlus(1) elif kname=='down': self.numPlus(-1) elif kname=='page_up': self.numPlus(self.page_inc) elif kname=='page_down': self.numPlus(-self.page_inc) elif kname=='left': return False## FIXME elif kname=='right': return False## FIXME #elif kname in ('braceleft', 'bracketleft'): # self.insertText(u'[') #elif kname in ('braceright', 'bracketright'): # self.insertText(u']') elif kname in ('comma', 'arabic_comma'): self.insertText(u', ', False) elif kname=='minus': pos = self.get_position() text = toUnicode(self.get_text()) n = len(text) if pos==n: start = numDecode(text.split(',')[-1].strip()) self.insertText(u'-' + _(start + 2), False) else: self.insertText(u'-', False) elif ord('0') <= kval <= ord('9'): self.insertText(self.digs[kval-ord('0')]) else: uniVal = gtk.gdk.keyval_to_unicode(kval) #print 'uniVal=%r'%uniVal if uniVal!=0: ch = unichr(uniVal) #print 'ch=%r'%ch if ch in self.digs: self.insertText(ch) if gevent.state & gdk.CONTROL_MASK:## Shortcuts like Ctrl + [A, C, X, V] return False else: print kval, kname return True
def drawBoxText(cr, box, x, y, w, h, widget): ## now draw the text ## how to find the best font size based in the box's width and height, ## and font family? FIXME ## possibly write in many lines? or just in one line and wrap if needed? if box.text: #print(box.text) textW = 0.9 * w textH = 0.9 * h textLen = len(toUnicode(box.text)) #print('textLen=%s'%textLen) avgCharW = float(textW if rotateBoxLabel == 0 else max(textW, textH)) / textLen if avgCharW > 3:## FIXME font = list(ui.getFont()) layout = widget.create_pango_layout(box.text) ## a pango.Layout object layout.set_font_description(pfontEncode(font)) layoutW, layoutH = layout.get_pixel_size() #print('orig font size: %s'%font[3]) normRatio = min( float(textW)/layoutW, float(textH)/layoutH, ) rotateRatio = min( float(textW)/layoutH, float(textH)/layoutW, ) if rotateBoxLabel != 0 and rotateRatio > normRatio: font[3] *= max(normRatio, rotateRatio) layout.set_font_description(pfontEncode(font)) layoutW, layoutH = layout.get_pixel_size() fillColor(cr, fgColor)## before cr.move_to #print('x=%s, y=%s, w=%s, h=%s, layoutW=%s, layoutH=%s'\) # %(x,y,w,h,layoutW,layoutH) cr.move_to( x + (w - rotateBoxLabel*layoutH)/2.0, y + (h + rotateBoxLabel*layoutW)/2.0, ) cr.rotate(-rotateBoxLabel*pi/2) cr.show_layout(layout) try: cr.rotate(rotateBoxLabel*pi/2) except: print('counld not rotate by %s*pi/2 = %s'%( rotateBoxLabel, rotateBoxLabel*pi/2, )) else: font[3] *= normRatio layout.set_font_description(pfontEncode(font)) layoutW, layoutH = layout.get_pixel_size() fillColor(cr, fgColor)## before cr.move_to cr.move_to( x + (w-layoutW)/2.0, y + (h-layoutH)/2.0, ) cr.show_layout(layout)
def confStr(self): value = getattr(self.module, self.varName) if isinstance(value, str): value = toUnicode(value) valueStr = repr(value) ## repr of a utf8 string (by Python 2) is not utf8 and not readable correctly from Python 3 ## no simple way you can fix that for strings nested inside other structures ## yet another reason to switch to JSON for config files ## FIXME return '%s=%s\n'%(self.varName, valueStr)
def cutText(text, n): text = toUnicode(text) newText = text[:n] if len(text) > n: if text[n] not in list(string.printable) + [ZWNJ]: try: newText += ZWJ except UnicodeDecodeError: pass return newText
def cutText(text, n): text = toUnicode(text) newText = text[:n] if len(text) > n: if text[n] not in list(string.printable)+[ZWNJ]: try: newText += ZWJ except UnicodeDecodeError: pass return newText
def exportEvent(event): if not event.changeMode(DATE_GREG): return icsData = event.getIcsData(True) if not icsData: return gevent = { 'kind': 'calendar#event', 'summary': toUnicode(event.summary), 'description': toUnicode(event.description), 'attendees': [], 'status': 'confirmed', 'visibility': 'default', 'guestsCanModify': False, 'reminders': { 'overrides': { 'minutes': event.getNotifyBeforeMin(), 'method': 'popup', ## FIXME }, }, 'extendedProperties': { 'shared': { 'starcal_id': event.id, 'starcal_type': event.name, }, } } for key, value in icsData: key = key.upper() if key == 'DTSTART': gevent['start'] = decodeIcsStartEnd(value) elif key == 'DTEND': gevent['end'] = decodeIcsStartEnd(value) elif key in ('RRULE', 'RDATE', 'EXRULE', 'EXDATE'): if not 'recurrence' in gevent: gevent['recurrence'] = [] gevent['recurrence'].append(key + ':' + value) elif key == 'TRANSP': gevent['transparency'] = value.lower() #elif key=='CATEGORIES': return gevent
def insertText(self, s, clearSeceltion=True): selection = self.get_selection_bounds() if selection and clearSeceltion: start, end = selection text = toUnicode(self.get_text()) text = text[:start] + s + text[end:] self.set_text(text) self.set_position(start + len(s)) else: pos = self.get_position() self.insert_text(s, pos) self.set_position(pos + len(s))
def insertText(self, s, clearSeceltion=True): selection = self.get_selection_bounds() if selection and clearSeceltion: start, end = selection text = toUnicode(self.get_text()) text = text[:start] + s + text[end:] self.set_text(text) self.set_position(start+len(s)) else: pos = self.get_position() self.insert_text(s, pos) self.set_position(pos + len(s))
def exportEvent(event): if not event.changeMode(DATE_GREG): return icsData = event.getIcsData(True) if not icsData: return gevent = { 'kind': 'calendar#event', 'summary': toUnicode(event.summary), 'description': toUnicode(event.description), 'attendees': [], 'status': 'confirmed', 'visibility': 'default', 'guestsCanModify': False, 'reminders': { 'overrides': { 'minutes': event.getNotifyBeforeMin(), 'method': 'popup',## FIXME }, }, 'extendedProperties':{ 'shared': { 'starcal_type': event.name, }, } } for key, value in icsData: key = key.upper() if key=='DTSTART': gevent['start'] = decodeIcsStartEnd(value) elif key=='DTEND': gevent['end'] = decodeIcsStartEnd(value) elif key in ('RRULE', 'RDATE', 'EXRULE', 'EXDATE'): if not 'recurrence' in gevent: gevent['recurrence'] = [] gevent['recurrence'].append(key + ':' + value) elif key=='TRANSP': gevent['transparency'] = value.lower() #elif key=='CATEGORIES': return gevent
def textNumDecode(text): ## converts '۱۲:۰۰, ۱۳' to '12:00, 13' text = toUnicode(text) textEn = u'' langDigits = getLangDigits(langSh) for ch in text: try: textEn += unicode(langDigits.index(ch)) except ValueError: for sch in (u',', u'_', u'.'): if ch == tr(sch): ch = sch break textEn += ch return textEn
def textNumDecode(text):## converts '۱۲:۰۰, ۱۳' to '12:00, 13' text = toUnicode(text) textEn = u'' langDigits = getLangDigits(langSh) for ch in text: try: textEn += unicode(langDigits.index(ch)) except ValueError: for sch in (u',', u'_', u'.'): if ch == tr(sch): ch = sch break textEn += ch return textEn
def numPlus(self, plus): pos = self.get_position() text = toUnicode(self.get_text()) n = len(text) commaI = text.rfind(u',', 0, pos) if commaI == -1: startI = 0 else: if text[commaI + 1] == ' ': startI = commaI + 2 else: startI = commaI + 1 nextCommaI = text.find(u',', pos) if nextCommaI == -1: endI = n else: endI = nextCommaI dashI = text.find(u'-', startI, endI) if dashI != -1: #print('dashI=%r'%dashI) if pos < dashI: endI = dashI else: startI = dashI + 1 thisNumStr = text[startI:endI] #print(startI, endI, thisNumStr) if thisNumStr: thisNum = numDecode(thisNumStr) newNum = thisNum + plus if not self._min <= newNum <= self._max: return else: if plus > 0: newNum = self._max else: newNum = self._min newNumStr = _(newNum) newText = text[:startI] + newNumStr + text[endI:] self.set_text(newText) #print('new end index', endI - len(thisNumStr) + len(newNumStr)) self.set_position(pos) self.select_region( startI, endI - len(thisNumStr) + len(newNumStr), )
def numPlus(self, plus): pos = self.get_position() text = toUnicode(self.get_text()) n = len(text) commaI = text.rfind(u',', 0, pos) if commaI == -1: startI = 0 else: if text[commaI+1]==' ': startI = commaI + 2 else: startI = commaI + 1 nextCommaI = text.find(u',', pos) if nextCommaI == -1: endI = n else: endI = nextCommaI dashI = text.find(u'-', startI, endI) if dashI != -1: #print 'dashI=%r'%dashI if pos < dashI: endI = dashI else: startI = dashI + 1 thisNumStr = text[startI:endI] #print startI, endI, thisNumStr if thisNumStr: thisNum = numDecode(thisNumStr) newNum = thisNum + plus if not self._min <= newNum <= self._max: return else: if plus > 0: newNum = self._max else: newNum = self._min newNumStr = _(newNum) newText = text[:startI] + newNumStr + text[endI:] self.set_text(newText) #print 'new end index', endI - len(thisNumStr) + len(newNumStr) self.set_position(pos) self.select_region( startI, endI - len(thisNumStr) + len(newNumStr), )
def __init__(self, sep, fields, arrow_select=True, page_inc=10): gtk.SpinButton.__init__(self) #### sep = toUnicode(sep) self.field = ContainerField(sep, *fields) self.arrow_select = arrow_select self.set_editable(True) ### self.digs = locale_man.getDigits() ### #### self.set_direction(gtk.TEXT_DIR_LTR) ## self is a gtk.Entry self.set_width_chars(self.field.getMaxWidth()) self.set_value(0) self.set_digits(0) gtk.SpinButton.set_range(self, -2, 2) self.set_increments(1, page_inc) #self.connect('activate', lambda obj: self.update()) self.connect('activate', self._entry_activate) self.connect('key-press-event', self._key_press) self.connect('scroll-event', self._scroll) self.connect('button-press-event', self._button_press) self.connect('button-release-event', self._button_release) self.connect('output', lambda obj: True)##Disable auto-numeric-validating(the entry text is not a numebr)
def set_title(self, title): self.setWindowTitle(toUnicode(title))
def copy(self, item): start = self.get_property('selection-bound') end = self.get_property('cursor-position') self.clipboard.set_text(toStr(toUnicode(self.get_text())[start:end]))
def set_license(self, license): self.license = toUnicode(license)
def set_documenters(documenters): self.credits[_('Documented by')] = [toUnicode(a) for a in documenters]
def set_authors(self, authors): self.credits[_('Written by')] = [toUnicode(a) for a in authors]
def update(self): pos = self.get_position() self.field.setText(toUnicode(self.get_text())) self.set_text(self.field.getText()) self.set_position(pos)
def drawBox(self, cr, box): d = box.lineW x = box.x w = box.w y = box.y h = box.h ### cr.rectangle(x, y, w, h) if d == 0: fillColor(cr, box.color) else: try: alpha = box.color[3] except IndexError: alpha = 255 try: fillColor(cr, ( box.color[0], box.color[1], box.color[2], int(alpha*boxInnerAlpha), )) except cairo.Error: return ### cr.set_line_width(0) cr.move_to(x, y) cr.line_to(x+w, y) cr.line_to(x+w, y+h) cr.line_to(x, y+h) cr.line_to(x, y) cr.line_to(x+d, y) cr.line_to(x+d, y+h-d) cr.line_to(x+w-d, y+h-d) cr.line_to(x+w-d, y+d) cr.line_to(x+d, y+d) cr.close_path() fillColor(cr, box.color) ######## Draw Move/Resize Border if box.hasBorder: if w > boxMoveBorder*2 and h > boxMoveBorder: b = boxMoveBorder bd = boxMoveLineW #cr.set_line_width(bd) cr.move_to(x+b, y+h) cr.line_to(x+b, y+b) cr.line_to(x+w-b, y+b) cr.line_to(x+w-b, y+h) cr.line_to(x+w-b-bd, y+h) cr.line_to(x+w-b-bd, y+b+bd) cr.line_to(x+b+bd, y+b+bd) cr.line_to(x+b+bd, y+h) cr.close_path() fillColor(cr, box.color) ### bds = 0.7*bd cr.move_to(x, y) cr.line_to(x+bds, y) cr.line_to(x+b+bds, y+b) cr.line_to(x+b, y+b+bds) cr.line_to(x, y+bds) cr.close_path() fillColor(cr, box.color) ## cr.move_to(x+w, y) cr.line_to(x+w-bds, y) cr.line_to(x+w-b-bds, y+b) cr.line_to(x+w-b, y+b+bds) cr.line_to(x+w, y+bds) cr.close_path() fillColor(cr, box.color) else: box.hasBorder = False ######## ## now draw the text ## how to find the best font size based in the box's width and height, and font family? FIXME ## possibly write in many lines? or just in one line and wrap if needed? if box.text: #print box.text textW = 0.9*w textH = 0.9*h textLen = len(toUnicode(box.text)) #print 'textLen=%s'%textLen if rotateBoxLabel == 0: avgCharW = float(textW) / textLen else: avgCharW = float(max(textW, textH)) / textLen #print 'avgCharW=%s'%avgCharW if avgCharW > 3:## FIXME font = list(ui.getFont()) layout = self.create_pango_layout(box.text) ## a pango.Layout object layout.set_font_description(pfontEncode(font)) layoutW, layoutH = layout.get_pixel_size() #print 'orig font size: %s'%font[3] normRatio = min( float(textW)/layoutW, float(textH)/layoutH, ) rotateRatio = min( float(textW)/layoutH, float(textH)/layoutW, ) if rotateBoxLabel != 0 and rotateRatio > normRatio: font[3] *= max(normRatio, rotateRatio) layout.set_font_description(pfontEncode(font)) layoutW, layoutH = layout.get_pixel_size() fillColor(cr, fgColor)## before cr.move_to #print 'x=%s, y=%s, w=%s, h=%s, layoutW=%s, layoutH=%s'%(x,y,w,h,layoutW,layoutH) cr.move_to( x + (w - rotateBoxLabel*layoutH)/2.0, y + (h + rotateBoxLabel*layoutW)/2.0, ) cr.rotate(-rotateBoxLabel*pi/2) cr.show_layout(layout) try: cr.rotate(rotateBoxLabel*pi/2) except: print 'counld not rotate by %s*pi/2 = %s'%(rotateBoxLabel, rotateBoxLabel*pi/2) else: font[3] *= normRatio layout.set_font_description(pfontEncode(font)) layoutW, layoutH = layout.get_pixel_size() fillColor(cr, fgColor)## before cr.move_to cr.move_to( x + (w-layoutW)/2.0, y + (h-layoutH)/2.0, ) cr.show_layout(layout)
def keyPress(self, obj, gevent): kval = gevent.keyval kname = gdk.keyval_name(gevent.keyval).lower() #print(kval, kname) if kname in ( 'tab', 'escape', 'backspace', 'delete', 'insert', 'home', 'end', 'control_l', 'control_r', 'iso_next_group', ): return False elif kname == 'return': self.validate() return False elif kname == 'up': self.numPlus(1) elif kname == 'down': self.numPlus(-1) elif kname == 'page_up': self.numPlus(self.page_inc) elif kname == 'page_down': self.numPlus(-self.page_inc) elif kname == 'left': return False ## FIXME elif kname == 'right': return False ## FIXME #elif kname in ('braceleft', 'bracketleft'): # self.insertText(u'[') #elif kname in ('braceright', 'bracketright'): # self.insertText(u']') elif kname in ('comma', 'arabic_comma'): self.insertText(u', ', False) elif kname == 'minus': pos = self.get_position() text = toUnicode(self.get_text()) n = len(text) if pos == n: start = numDecode(text.split(',')[-1].strip()) self.insertText(u'-' + _(start + 2), False) else: self.insertText(u'-', False) elif ord('0') <= kval <= ord('9'): self.insertText(self.digs[kval - ord('0')]) else: uniVal = gtk.gdk.keyval_to_unicode(kval) #print('uniVal=%r'%uniVal) if uniVal != 0: ch = unichr(uniVal) #print('ch=%r'%ch) if ch in self.digs: self.insertText(ch) if gevent.state & gdk.CONTROL_MASK: ## Shortcuts like Ctrl + [A, C, X, V] return False else: print(kval, kname) return True
def set_comments(self, comments): self.comments = toUnicode(comments)
def __init__(self, locName, lat, lng): qt.QPushButton.__init__(self, toUnicode(locName)) self.setLocation(locName, lat, lng) self.dialog = LocationDialog() #### self.connect(self, qc.SIGNAL('clicked ()'), self.onClicked)
def set_artists(artists): self.credits[_('Translated by')] = [toUnicode(a) for a in artists]
def set_version(self, version): self.version = toUnicode(version)
def copy(self, item, label): bound = label.get_property('selection-bound') cursor = label.get_property('cursor-position') start = min(bound, cursor) end = max(bound, cursor) setClipboard(toStr(toUnicode(label.get_text())[start:end]))
def onClicked(self): res = self.dialog.run() if res: self.locName, self.lat, self.lng = res self.setText(toUnicode(self.locName))
def copy(self, item, label): bound = label.get_property('selection-bound') cursor = label.get_property('cursor-position') start = min(bound, cursor) end = max(bound, cursor) self.clipboard.set_text(toStr(toUnicode(label.get_text())[start:end]))
def set_logo(self, logo): self.logo = toUnicode(logo) self.setWindowIcon(qt.QIcon(logo))