コード例 #1
0
ファイル: locale_man.py プロジェクト: greyzero/starcal
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')
コード例 #2
0
ファイル: text_widgets.py プロジェクト: ubuntu-ir/starcal
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()
コード例 #3
0
ファイル: utils.py プロジェクト: goodosuser/starcal
def setClipboard(text, clipboard=None):
    if not clipboard:
        clipboard = gtk.Clipboard.get(gdk.SELECTION_CLIPBOARD)
    clipboard.set_text(
        toStr(text),
        len(toBytes(text)),
    )
コード例 #4
0
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()
コード例 #5
0
ファイル: locale_man.py プロジェクト: iman-salmani/starcal
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")
コード例 #6
0
ファイル: locale_man.py プロジェクト: ilius/starcal
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")
コード例 #7
0
ファイル: locale_man.py プロジェクト: iman-salmani/starcal
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)
コード例 #8
0
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
コード例 #9
0
ファイル: git.py プロジェクト: greyzero/starcal
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
コード例 #10
0
ファイル: locale_man.py プロジェクト: greyzero/starcal
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)
コード例 #11
0
ファイル: __init__.py プロジェクト: ubuntu-ir/starcal
	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)
コード例 #12
0
ファイル: git.py プロジェクト: ilius/starcal
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
コード例 #13
0
ファイル: utils.py プロジェクト: greyzero/starcal
def setClipboard(text, clipboard=None):
    if not clipboard:
        clipboard = gtk.Clipboard.get(gdk.SELECTION_CLIPBOARD)
    clipboard.set_text(
        toStr(text),
        len(toBytes(text)),
    )
コード例 #14
0
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
コード例 #15
0
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')
コード例 #16
0
ファイル: __init__.py プロジェクト: goodosuser/starcal
 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)
コード例 #17
0
ファイル: __init__.py プロジェクト: goodosuser/starcal
 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)
コード例 #18
0
ファイル: timeline_box.py プロジェクト: goodosuser/starcal
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)
コード例 #19
0
ファイル: google.py プロジェクト: greyzero/starcal
 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
コード例 #20
0
ファイル: __init__.py プロジェクト: ilius/starcal
	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)
コード例 #21
0
ファイル: google.py プロジェクト: ubuntu-ir/starcal
 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
コード例 #22
0
ファイル: num_ranges_entry.py プロジェクト: ubuntu-ir/starcal
	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
コード例 #23
0
ファイル: timeline_box.py プロジェクト: ubuntu-ir/starcal
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)
コード例 #24
0
ファイル: num_ranges_entry.py プロジェクト: greyzero/starcal
 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
コード例 #25
0
ファイル: locale_man.py プロジェクト: greyzero/starcal
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
コード例 #26
0
ファイル: locale_man.py プロジェクト: iman-salmani/starcal
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
コード例 #27
0
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
コード例 #28
0
ファイル: google.py プロジェクト: ubuntu-ir/starcal
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
コード例 #29
0
ファイル: google.py プロジェクト: greyzero/starcal
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
コード例 #30
0
ファイル: num_ranges_entry.py プロジェクト: greyzero/starcal
 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))
コード例 #31
0
 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
コード例 #32
0
ファイル: locale_man.py プロジェクト: greyzero/starcal
 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
コード例 #33
0
 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))
コード例 #34
0
ファイル: git.py プロジェクト: ilius/starcal
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())
コード例 #35
0
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())
コード例 #36
0
ファイル: git.py プロジェクト: greyzero/starcal
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())
コード例 #37
0
ファイル: locale_man.py プロジェクト: greyzero/starcal
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
コード例 #38
0
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
コード例 #39
0
ファイル: locale_man.py プロジェクト: iman-salmani/starcal
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
コード例 #40
0
ファイル: locale_man.py プロジェクト: iman-salmani/starcal
 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
コード例 #41
0
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())
コード例 #42
0
ファイル: locale_man.py プロジェクト: ilius/starcal
		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
コード例 #43
0
ファイル: locale_man.py プロジェクト: ilius/starcal
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
コード例 #44
0
ファイル: num_ranges_entry.py プロジェクト: greyzero/starcal
 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),
     )
コード例 #45
0
 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),
     )
コード例 #46
0
ファイル: locale_man.py プロジェクト: greyzero/starcal
    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()

コード例 #47
0
ファイル: text_widgets.py プロジェクト: greyzero/starcal
 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)))
コード例 #48
0
ファイル: text_widgets.py プロジェクト: ilius/starcal
	def copyAll(self, item):
		return setClipboard(toStr(self.get_text()))
コード例 #49
0
ファイル: locale_man.py プロジェクト: iman-salmani/starcal
def addLRM(text):
    return LRM + toStr(text)
コード例 #50
0
 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])
コード例 #51
0
ファイル: __init__.py プロジェクト: ilius/starcal
	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)
コード例 #52
0
ファイル: __init__.py プロジェクト: ubuntu-ir/starcal
	def update(self):
		pos = self.get_position()
		self.field.setText(toStr(self.get_text()))
		self.set_text(self.field.getText())
		self.set_position(pos)
コード例 #53
0
 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)))
コード例 #54
0
 def copy(self, item):
     start = self.get_property("selection-bound")
     end = self.get_property("cursor-position")
     setClipboard(toStr(self.get_text())[start:end])
コード例 #55
0
ファイル: locale_man.py プロジェクト: ilius/starcal
def addLRM(text):
	return LRM + toStr(text)
コード例 #56
0
    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()
コード例 #57
0
ファイル: datelabel.py プロジェクト: ilius/starcal
	def copy(self, item):
		start = self.get_property("selection-bound")
		end = self.get_property("cursor-position")
		setClipboard(toStr(self.get_text())[start:end])
コード例 #58
0
ファイル: __init__.py プロジェクト: goodosuser/starcal
 def update(self):
     pos = self.get_position()
     self.field.setText(toStr(self.get_text()))
     self.set_text(self.field.getText())
     self.set_position(pos)
コード例 #59
0
ファイル: text_widgets.py プロジェクト: greyzero/starcal
 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])
コード例 #60
0
ファイル: num_ranges_entry.py プロジェクト: ilius/starcal
	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