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 = '' for c in toStr(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')
class ReadOnlyTextWidget: copyAll = lambda self, item: setClipboard(toStr(self.get_text())) def has_selection(): raise NotImplementedError def onPopup(self, widget, menu): # instead of creating a new menu, we should remove all the current items from current menu for item in menu.get_children(): menu.remove(item) #### menu.add( labelStockMenuItem( 'Copy _All', gtk.STOCK_COPY, self.copyAll, )) #### itemCopy = labelStockMenuItem( '_Copy', gtk.STOCK_COPY, self.copy, ) if not self.has_selection(): itemCopy.set_sensitive(False) menu.add(itemCopy) #### menu.show_all() self.tmpMenu = menu ui.updateFocusTime()
def setClipboard(text, clipboard=None): if not clipboard: clipboard = gtk.Clipboard.get(gdk.SELECTION_CLIPBOARD) clipboard.set_text( toStr(text), len(toBytes(text)), )
class ReadOnlyTextWidget: copyAll = lambda self, item: setClipboard(toStr(self.get_text())) def has_selection(): raise NotImplementedError def labelMenuAddCopyItems(self, menu): menu.add( labelStockMenuItem( 'Copy _All', gtk.STOCK_COPY, self.copyAll, )) #### itemCopy = labelStockMenuItem( '_Copy', gtk.STOCK_COPY, self.copy, ) if not self.has_selection(): itemCopy.set_sensitive(False) menu.add(itemCopy) def onPopup(self, widget, menu): menu = gtk.Menu() self.labelMenuAddCopyItems(menu) #### menu.show_all() self.tmpMenu = menu menu.popup(None, None, None, None, 3, 0) ui.updateFocusTime()
def textNumEncode(st, mode=None, changeSpecialChars=True, changeDot=False): if not enableNumLocale: mode = "en" if mode is None: mode = langSh elif isinstance(mode, int): if langSh != "en": module, ok = calTypes[mode] if not ok: raise RuntimeError("cal type %r not found" % mode) try: mode = module.origLang except AttributeError: mode = langSh dig = getLangDigits(mode) res = "" for c in toStr(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 is None: mode = langSh elif isinstance(mode, int): if langSh != "en": module, ok = calTypes[mode] if not ok: raise RuntimeError("cal type %r not found" % mode) try: mode = module.origLang except AttributeError: mode = langSh dig = getLangDigits(mode) res = "" for c in toStr(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 = toStr(numSt) tryLangs = list(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 getCommitList(obj, startJd=None, endJd=None): ''' returns a list of (epoch, commit_id) tuples ''' cmd = [ 'git', '--git-dir', join(obj.vcsDir, '.git'), 'log', '--format=%ct %H', ## or '--format=%ct %H' ] if startJd is not None: cmd += [ '--since', encodeJd(startJd), ] if endJd is not None: cmd += [ '--until', encodeJd(endJd), ] data = [] for line in Popen(cmd, stdout=PIPE).stdout: line = toStr(line) parts = line.strip().split(' ') data.append(( int(parts[0]), parts[1], )) return data
def getCommitList(obj, startJd=None, endJd=None): ''' returns a list of (epoch, commit_id) tuples ''' cmd = [ 'git', '--git-dir', join(obj.vcsDir, '.git'), 'log', '--format=%ct %H',## or '--format=%ct %H' ] if startJd is not None: cmd += [ '--since', encodeJd(startJd), ] if endJd is not None: cmd += [ '--until', encodeJd(endJd), ] data = [] for line in Popen(cmd, stdout=PIPE).stdout: line = toStr(line) parts = line.strip().split(' ') data.append(( int(parts[0]), parts[1], )) return data
def numDecode(numSt): numSt = numSt.strip() try: return int(numSt) except ValueError: pass numSt = toStr(numSt) tryLangs = list(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 = toStr(sep) self.field = ContainerField(sep, *fields) self.arrow_select = arrow_select self.set_editable(True) ### self.digs = locale_man.getDigits() ### #### self.set_direction(gtk.TextDirection.LTR) ## self is a gtk.Entry self.set_width_chars(self.field.getMaxWidth()) #print(self.__class__.__name__, 'value=', value) gtk.SpinButton.set_value(self, 0) gtk.SpinButton.set_range(self, -2, 2) self.set_digits(0) 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 getCommitList(obj, startJd=None, endJd=None): """ returns a list of (epoch, commit_id) tuples """ cmd = [ "git", "--git-dir", join(obj.vcsDir, ".git"), "log", "--format=%ct %H",## or "--format=%ct %H" ] if startJd is not None: cmd += [ "--since", encodeJd(startJd), ] if endJd is not None: cmd += [ "--until", encodeJd(endJd), ] data = [] for line in Popen(cmd, stdout=PIPE).stdout: line = toStr(line) parts = line.strip().split(" ") data.append(( int(parts[0]), parts[1], )) return data
def getCommitList(obj, startJd=None, endJd=None): """ returns a list of (epoch, commit_id) tuples """ cmd = [ "git", "--git-dir", join(obj.vcsDir, ".git"), "log", "--format=%ct %H", ## or "--format=%ct %H" ] if startJd is not None: cmd += [ "--since", encodeJd(startJd), ] if endJd is not None: cmd += [ "--until", encodeJd(endJd), ] data = [] for line in Popen(cmd, stdout=PIPE).stdout: line = toStr(line) parts = line.strip().split(" ") data.append(( int(parts[0]), parts[1], )) return data
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 = '' for c in toStr(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 entry_plus(self, p): self.update() pos = self.get_position() self.field.getFieldAt(toStr(self.get_text()), self.get_position()).plus(p) self.set_text(self.field.getText()) self.set_position(pos)
def __init__(self, sep, fields, arrow_select=True, page_inc=10): gtk.SpinButton.__init__(self) #### sep = toStr(sep) self.field = ContainerField(sep, *fields) self.arrow_select = arrow_select self.set_editable(True) ### self.digs = locale_man.getDigits() ### #### self.set_direction(gtk.TextDirection.LTR) ## self is a gtk.Entry self.set_width_chars(self.field.getMaxWidth()) #print(self.__class__.__name__, 'value=', value) gtk.SpinButton.set_value(self, 0) gtk.SpinButton.set_range(self, -2, 2) self.set_digits(0) 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 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(toStr(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) show_layout(cr, 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, ) show_layout(cr, layout)
def getHttp(self): credentials = self.authenticate() if not credentials: return False http = credentials.authorize(httplib2.Http()) http.request = lambda uri, *args, **kwargs:\ httplib2.Http.request(http, toStr(uri), *args, **kwargs) #http.request('google.com') return http
def entry_plus(self, p): self.update() pos = self.entry.get_position() self.field.getFieldAt( toStr(self.entry.get_text()), self.entry.get_position() ).plus(p) self.entry.set_text(self.field.getText()) self.entry.set_position(pos)
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(', ', False) elif kname=='minus': pos = self.get_position() text = toStr(self.get_text()) n = len(text) if pos==n: start = numDecode(text.split(',')[-1].strip()) self.insertText('-' + _(start + 2), False) else: self.insertText('-', False) elif ord('0') <= kval <= ord('9'): self.insertText(self.digs[kval-ord('0')]) else: uniVal = gdk.keyval_to_unicode(kval) #print('uniVal=%r'%uniVal) if uniVal!=0: ch = chr(uniVal) #print('ch=%r'%ch) if ch in self.digs: self.insertText(ch) if gevent.get_state() & gdk.ModifierType.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(toStr(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) show_layout(cr, 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, ) show_layout(cr, layout)
def cutText(text, n): text = toStr(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 = toStr(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": toStr(event.summary), "description": toStr(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 "recurrence" not in gevent: gevent["recurrence"] = [] gevent["recurrence"].append(key + ":" + value) elif key == "TRANSP": gevent["transparency"] = value.lower() # elif key=="CATEGORIES": return gevent
def exportEvent(event): if not event.changeMode(DATE_GREG): return icsData = event.getIcsData(True) if not icsData: return gevent = { 'kind': 'calendar#event', 'summary': toStr(event.summary), 'description': toStr(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 exportEvent(event): if not event.changeMode(DATE_GREG): return icsData = event.getIcsData(True) if not icsData: return gevent = { 'kind': 'calendar#event', 'summary': toStr(event.summary), 'description': toStr(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 = toStr(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 tr(s, *a, **ka): if isinstance(s, (int, float)): s = numEncode(s, *a, **ka) else: s = toStr(transObj.gettext(s)) if ui_is_qt: s = s.replace('_', '&') if a: s = s % a if ka: s = s % ka return s
def insertText(self, s, clearSeceltion=True): selection = self.get_selection_bounds() if selection and clearSeceltion: start, end = selection text = toStr(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 getShortStatLine(obj, prevId, thisId): """ returns str """ cmd = [ "git", "--git-dir", join(obj.vcsDir, ".git"), "diff", "--shortstat", prevId, thisId, ] return toStr(Popen(cmd, stdout=PIPE).stdout.read().strip())
def getShortStatLine(obj, prevId, thisId): ''' returns str ''' cmd = [ 'git', '--git-dir', join(obj.vcsDir, '.git'), 'diff', '--shortstat', prevId, thisId, ] return toStr(Popen(cmd, stdout=PIPE).stdout.read().strip())
def textNumDecode(text):## converts '۱۲:۰۰, ۱۳' to '12:00, 13' text = toStr(text) textEn = '' langDigits = getLangDigits(langSh) for ch in text: try: textEn += str(langDigits.index(ch)) except ValueError: for sch in (',', '_', '.'): if ch == tr(sch): ch = sch break textEn += ch return textEn
def textNumDecode(text): ## converts '۱۲:۰۰, ۱۳' to '12:00, 13' text = toStr(text) textEn = '' langDigits = getLangDigits(langSh) for ch in text: try: textEn += str(langDigits.index(ch)) except ValueError: for sch in (',', '_', '.'): if ch == tr(sch): ch = sch break textEn += ch return textEn
def textNumDecode(text): ## converts "۱۲:۰۰, ۱۳" to "12:00, 13" text = toStr(text) textEn = "" langDigits = getLangDigits(langSh) for ch in text: try: textEn += str(langDigits.index(ch)) except ValueError: for sch in (",", "_", "."): if ch == tr(sch): ch = sch break textEn += ch return textEn
def tr(s, *a, nums=False, **ka): if isinstance(s, (int, float)): s = numEncode(s, *a, **ka) else: s = toStr(transObj.gettext(s)) if ui_is_qt: s = s.replace("_", "&") if a: s = s % a if ka: s = s % ka if nums: s = textNumEncode(s) return s
def textNumDecode(text):## converts "۱۲:۰۰, ۱۳" to "12:00, 13" text = toStr(text) textEn = "" langDigits = getLangDigits(langSh) for ch in text: try: textEn += str(langDigits.index(ch)) except ValueError: for sch in (",", "_", "."): if ch == tr(sch): ch = sch break textEn += ch return textEn
def numPlus(self, plus): pos = self.get_position() text = toStr(self.get_text()) n = len(text) commaI = text.rfind(',', 0, pos) if commaI == -1: startI = 0 else: if text[commaI+1]==' ': startI = commaI + 2 else: startI = commaI + 1 nextCommaI = text.find(',', pos) if nextCommaI == -1: endI = n else: endI = nextCommaI dashI = text.find('-', 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 = toStr(self.get_text()) n = len(text) commaI = text.rfind(',', 0, pos) if commaI == -1: startI = 0 else: if text[commaI + 1] == ' ': startI = commaI + 2 else: startI = commaI + 1 nextCommaI = text.find(',', pos) if nextCommaI == -1: endI = n else: endI = nextCommaI dashI = text.find('-', 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), )
numEncode(year, fillZero=4) + '/' + \ numEncode(month, fillZero=2) + '/' + \ numEncode(day, fillZero=2) def cutText(text, n): text = toStr(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 addLRM = lambda text: LRM + toStr(text) def popenDefaultLang(*args, **kwargs): global sysLangDefault, lang from subprocess import Popen os.environ['LANG'] = sysLangDefault p = Popen(*args, **kwargs) os.environ['LANG'] = lang return p ############################################## prepareLanguage() loadTranslator()
def copy(self, item): buf = self.get_buffer() start_iter, end_iter = buf.get_selection_bounds() setClipboard(toStr(buf.get_text(start_iter, end_iter, True)))
def copyAll(self, item): return setClipboard(toStr(self.get_text()))
def addLRM(text): return LRM + toStr(text)
def copy(self, item): bound = self.get_selection_bound() cursor = self.get_cursor_position() start = min(bound, cursor) end = max(bound, cursor) setClipboard(toStr(self.get_text())[start:end])
def __init__(self, sep, fields, arrow_select=True, step_inc=1, page_inc=10): gtk.HBox.__init__(self) self.entry = gtk.Entry() ## self.step_inc = step_inc self.page_inc = page_inc ## button_size = gtk.IconSize.SMALL_TOOLBAR # FIXME # 0 = IconSize.INVALID # 1 = IconSize.MENU # 2 = IconSize.SMALL_TOOLBAR # 3 = IconSize.LARGE_TOOLBAR # 4 = IconSize.BUTTON # 5 = IconSize.DND # 6 = IconSize.DIALOG ### # in Gtk's sourc code, icon names are "value-decrease-symbolic" and "value-increase-symbolic" # but I can not find these icons (and my Gtk does not either) # instead "list-remove-symbolic" and "list-add-symbolic" used in this patch, work perfectly # https://gitlab.gnome.org/GNOME/gtk/commit/5fd936beef7a999828e5e3625506ea6708188762 ### self.down_button = gtk.Button() self.down_button.add(gtk.Image.new_from_icon_name("list-remove-symbolic", button_size)) self.down_button.get_style_context().add_class("image-button") self.down_button.set_can_focus(False) self.down_button.get_style_context().add_class("down") self.down_button.connect("button-press-event", self.down_button_pressed) self.down_button.connect("button-release-event", self._button_release) ### self.up_button = gtk.Button() self.up_button.add(gtk.Image.new_from_icon_name("list-add-symbolic", button_size)) self.up_button.get_style_context().add_class("image-button") self.up_button.set_can_focus(False) self.up_button.get_style_context().add_class("up") self.up_button.connect("button-press-event", self.up_button_pressed) self.up_button.connect("button-release-event", self._button_release) ### pack(self, self.entry, expand=True, fill=True) pack(self, self.down_button) pack(self, self.up_button) #### # priv->down_button = gtk_button_new (); # gtk_container_add (GTK_CONTAINER (priv->down_button), gtk_image_new_from_icon_name ("value-decrease-symbolic")); # gtk_style_context_add_class (gtk_widget_get_style_context (priv->down_button), "image-button"); # gtk_widget_set_can_focus (priv->down_button, FALSE); # gtk_style_context_add_class (gtk_widget_get_style_context (priv->down_button), "down"); # gtk_container_add (GTK_CONTAINER (priv->box), priv->down_button); # gesture = gtk_gesture_multi_press_new (); # gtk_gesture_single_set_button (GTK_GESTURE_SINGLE (gesture), 0); # gtk_gesture_single_set_touch_only (GTK_GESTURE_SINGLE (gesture), FALSE); # gtk_event_controller_set_propagation_phase (GTK_EVENT_CONTROLLER (gesture), # GTK_PHASE_CAPTURE); # g_signal_connect (gesture, "pressed", G_CALLBACK (button_pressed_cb), spin_button); # g_signal_connect (gesture, "released", G_CALLBACK (button_released_cb), spin_button); # gtk_widget_add_controller (GTK_WIDGET (priv->down_button), GTK_EVENT_CONTROLLER (gesture)); #### sep = toStr(sep) self.field = ContainerField(sep, *fields) self.arrow_select = arrow_select self.entry.set_editable(True) ### self.digs = locale_man.getDigits() ### #### self.entry.set_direction(gtk.TextDirection.LTR) self.set_width_chars(self.field.getMaxWidth()) #print(self.__class__.__name__, "value=", value) self.entry.connect("changed", self._entry_changed) #self.connect("activate", lambda obj: self.update()) self.entry.connect("activate", self._entry_activate) for widget in (self, self.entry, self.down_button, self.up_button): widget.connect("key-press-event", self._key_press) self.entry.connect("scroll-event", self._scroll)
def update(self): pos = self.get_position() self.field.setText(toStr(self.get_text())) self.set_text(self.field.getText()) self.set_position(pos)
def copy(self, item): start = self.get_property("selection-bound") end = self.get_property("cursor-position") setClipboard(toStr(self.get_text())[start:end])
numEncode(day, fillZero=2) def cutText(text, n): text = toStr(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 addLRM = lambda text: LRM + toStr(text) def popenDefaultLang(*args, **kwargs): global sysLangDefault, lang from subprocess import Popen os.environ['LANG'] = sysLangDefault p = Popen(*args, **kwargs) os.environ['LANG'] = lang return p ############################################## prepareLanguage() loadTranslator()
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(", ", False) elif kname == "minus": pos = self.get_position() text = toStr(self.get_text()) n = len(text) if pos == n: start = numDecode(text.split(",")[-1].strip()) self.insertText("-" + _(start + 2), False) else: self.insertText("-", False) elif ord("0") <= kval <= ord("9"): self.insertText(self.digs[kval - ord("0")]) else: uniVal = gdk.keyval_to_unicode(kval) #print("uniVal=%r"%uniVal) if uniVal != 0: ch = chr(uniVal) #print("ch=%r"%ch) if ch in self.digs: self.insertText(ch) if gevent.get_state() & gdk.ModifierType.CONTROL_MASK: # Shortcuts like Ctrl + [A, C, X, V] return False else: print(kval, kname) return True