def __askOpenUnlocked(self, filename): result = wx.MessageBox(_('Cannot acquire a lock because locking is not ' 'supported\non the location of %s.\n' 'Open %s unlocked?') % (filename, filename), _('%s: file locked') % meta.name, style=wx.YES_NO | wx.ICON_QUESTION | wx.NO_DEFAULT) return result == wx.YES
def __setTooltipText(self): ''' Note that Windows XP and Vista limit the text shown in the tool tip to 64 characters, so we cannot show everything we would like to and have to make choices. ''' textParts = [] trackedTasks = self.__taskList.tasksBeingTracked() if trackedTasks: count = len(trackedTasks) if count == 1: tracking = _('tracking "%s"') % trackedTasks[0].subject() else: tracking = _('tracking effort for %d tasks') % count textParts.append(tracking) else: counts = self.__taskList.nrOfTasksPerStatus() for status, singular, plural in self.toolTipMessages: count = counts[status] if count == 1: textParts.append(singular) elif count > 1: textParts.append(plural % count) textPart = ', '.join(textParts) filename = os.path.basename(self.__window.taskFile.filename()) namePart = u'%s - %s' % (meta.name, filename) if filename else meta.name text = u'%s\n%s' % (namePart, textPart) if textPart else namePart if text != self.__tooltipText: self.__tooltipText = text self.__setIcon() # Update tooltip
def __init__(self, *args, **kwargs): super(IPhoneSyncTypeDialog, self).__init__(*args, **kwargs) vsz = wx.BoxSizer(wx.VERTICAL) vsz.Add(wx.StaticText(self, wx.ID_ANY, _('''An iPhone or iPod Touch device is trying to synchronize with this task file for the first time. What kind of synchronization would you like to use?''')), 1, wx.EXPAND|wx.ALL, 5) hsz = wx.BoxSizer(wx.HORIZONTAL) btn = wx.Button(self, wx.ID_ANY, _('Refresh from desktop')) hsz.Add(btn, 0, wx.ALL, 3) wx.EVT_BUTTON(btn, wx.ID_ANY, self.OnType1) btn = wx.Button(self, wx.ID_ANY, _('Refresh from device')) hsz.Add(btn, 0, wx.ALL, 3) wx.EVT_BUTTON(btn, wx.ID_ANY, self.OnType2) btn = wx.Button(self, wx.ID_ANY, _('Cancel')) hsz.Add(btn, 0, wx.ALL, 3) wx.EVT_BUTTON(btn, wx.ID_ANY, self.OnCancel) vsz.Add(hsz, 0, wx.ALIGN_RIGHT) self.SetSizer(vsz) self.Fit() self.CentreOnScreen() self.RequestUserAttention() self.value = 3 # cancel
def __init__(self, taskBarIcon, settings, taskFile, viewer): super(TaskBarMenu, self).__init__(taskBarIcon) tasks = taskFile.tasks() efforts = taskFile.efforts() self.appendUICommands( uicommand.TaskNew(taskList=tasks, settings=settings)) self.appendMenu(_('New task from &template'), TaskTemplateMenu(taskBarIcon, taskList=tasks, settings=settings), 'newtmpl') self.appendUICommands(None) # Separator self.appendUICommands( uicommand.EffortNew(effortList=efforts, taskList=tasks, settings=settings), uicommand.CategoryNew(categories=taskFile.categories(), settings=settings), uicommand.NoteNew(notes=taskFile.notes(), settings=settings)) self.appendUICommands(None) # Separator label = _('&Start tracking effort') self.appendMenu(label, StartEffortForTaskMenu(taskBarIcon, base.filter.DeletedFilter(tasks), self, label), 'clock_icon') self.appendUICommands(uicommand.EffortStop(viewer=viewer, effortList=efforts, taskList=tasks)) self.appendUICommands( None, uicommand.MainWindowRestore(), uicommand.FileQuit())
def addColorEntry(self): currentColor = self._category.color(recursive=False) self._checkBox = wx.CheckBox(self, label=_("Use this color:")) self._checkBox.SetValue(currentColor is not None) self._colorButton = wx.ColourPickerCtrl(self, -1, currentColor or wx.WHITE, size=(40, -1)) self._colorButton.Bind(wx.EVT_COLOURPICKER_CHANGED, lambda event: self._checkBox.SetValue(True)) self.addEntry(_("Color"), self._checkBox, self._colorButton)
def __init__(self, *args, **kwargs): super(OSXPage, self).__init__(columns=3, *args, **kwargs) self.addBooleanSetting('os_darwin', 'getmailsubject', _('Get e-mail subject from Mail.app'), helpText=_('When dropping an e-mail from Mail.app, try to get its subject.\nThis takes up to 20 seconds.')) self.fit()
def createTemplateEntries(self, pane): panel = self._editPanel = sized_controls.SizedPanel(pane) panel.SetSizerType('form') panel.SetSizerProps(expand=True) label = wx.StaticText(panel, label=_('Subject')) label.SetSizerProps(valign='center') self._subjectCtrl = wx.TextCtrl(panel) label = wx.StaticText(panel, label=_('Planned start date')) label.SetSizerProps(valign='center') self._plannedStartDateTimeCtrl = TimeExpressionEntry(panel) label = wx.StaticText(panel, label=_('Due date')) label.SetSizerProps(valign='center') self._dueDateTimeCtrl = TimeExpressionEntry(panel) label = wx.StaticText(panel, label=_('Completion date')) label.SetSizerProps(valign='center') self._completionDateTimeCtrl = TimeExpressionEntry(panel) label = wx.StaticText(panel, label=_('Reminder')) label.SetSizerProps(valign='center') self._reminderDateTimeCtrl = TimeExpressionEntry(panel) self._taskControls = (self._subjectCtrl, self._plannedStartDateTimeCtrl, self._dueDateTimeCtrl, self._completionDateTimeCtrl, self._reminderDateTimeCtrl) for ctrl in self._taskControls: ctrl.SetSizerProps(valign='center', expand=True) ctrl.Bind(wx.EVT_TEXT, self.onValueChanged) self.enableEditPanel(False) panel.Fit()
def updateRecurrenceLabel(self): recurrenceDict = {0: _('period,'), 1: _('day(s),'), 2: _('week(s),'), 3: _('month(s),'), 4: _('year(s),')} recurrenceLabel = recurrenceDict[self._recurrencePeriodEntry.Selection] self._recurrenceStaticText.SetLabel(recurrenceLabel) self._recurrenceSameWeekdayCheckBox.Enable(self._recurrencePeriodEntry.Selection in (3, 4)) self._recurrenceSizer.Layout()
def __init__(self, *args, **kwargs): super(LinuxPage, self).__init__(columns=3, *args, **kwargs) self.addBooleanSetting('os_linux', 'focustextentry', _('Focus task subject in task editor'), helpText=_('When opening the task editor, select the task subject and focus it.\nThis overwrites the X selection.')) self.fit()
def __init__(self, parent): super(SyncMLWarningDialog, self).__init__(parent, wx.ID_ANY, _("Compatibility warning")) textWidget = wx.StaticText( self, wx.ID_ANY, _( "The SyncML feature is disabled, because the module\n" "could not be loaded. This may be because your platform\n" "is not supported, or under Windows, you may be missing\n" "some mandatory DLLs. Please see the SyncML section of\n" 'the online help for details (under "Troubleshooting").' ), ) self.checkbox = wx.CheckBox(self, wx.ID_ANY, _("Never show this dialog again")) self.checkbox.SetValue(True) button = wx.Button(self, wx.ID_ANY, _("OK")) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(textWidget, 0, wx.ALL, 10) sizer.Add(self.checkbox, 0, wx.ALL, 3) sizer.Add(button, 0, wx.ALL | wx.ALIGN_CENTRE, 3) self.SetSizer(sizer) wx.EVT_BUTTON(button, wx.ID_ANY, self.OnOK) wx.EVT_CLOSE(self, self.OnOK) self.Fit()
def __DisplayBalloon(self): # AuiFloatingFrame is instantiated from framemanager, we can't derive it from BalloonTipManager if self.toolbar.IsShownOnScreen() and hasattr(wx.GetTopLevelParent(self), 'AddBalloonTip'): wx.GetTopLevelParent(self).AddBalloonTip(self.settings, 'customizabletoolbars', self.toolbar, title=_('Toolbars are customizable'), getRect=lambda: self.toolbar.GetToolRect(self.toolbar.getToolIdByCommand('EditToolBarPerspective')), message=_('''Click on the gear icon on the right to add buttons and rearrange them.'''))
def merge(self, filename=None): if not filename: filename = self.__askUserForFile(_('Merge')) if filename: self.__taskFile.merge(filename) self.__messageCallback(_('Merged %(filename)s')%{'filename': filename}) self.__addRecentFile(filename)
def __init__(self, *args, **kwargs): super(SyncMLAccessPage, self).__init__(*args, **kwargs) self.addTextSetting('access', 'syncUrl', _('SyncML server URL')) self.addTextSetting('access', 'username', _('User name/ID')) self.fit()
def __init__(self, url): """url is the internal reference to the mail, as collected through drag-n-drop.""" mt = _RX_MAILBOX.search(url) if mt is None: raise RuntimeError(_('Malformed Thunderbird internal ID: %s. Please file a bug report.') % url) self.url = url # The url has the form # mailbox-message://<username>@<hostname>//<filename>#<id>. Or # so I hope. config = loadPreferences() self.user = unquote(mt.group(1)) self.server = unquote(mt.group(2)) self.path = unquote(mt.group(3)).split('/') self.offset = long(mt.group(4)) for i in xrange(200): base = 'mail.server.server%d' % i if config.has_key('%s.userName' % base): if config['%s.userName' % base] == self.user and config['%s.hostname' % base] == self.server: self.filename = os.path.join(config['%s.directory' % base], *tuple(self.path)) break else: raise RuntimeError(_('Could not find directory for ID %s. Please file a bug report.') % url) self.fp = file(self.filename, 'rb') self.fp.seek(self.offset) self.done = False
def __OnEndDrag(self, event): if event.GetItem() is not None and event.GetItem() != self.__draggedItem: targetItem = event.GetItem() sourceIndex = self.__visibleCommands.GetRootItem().GetChildren().index(self.__draggedItem) uiCommand = self.__visible[sourceIndex] self.__visibleCommands.Delete(self.__draggedItem) del self.__visible[sourceIndex] targetIndex = self.__visibleCommands.GetRootItem().GetChildren().index(targetItem) + 1 if targetItem.PartialHilight() & wx.wx.TREE_HITTEST_ONITEMUPPERPART: targetIndex -= 1 self.__visible.insert(targetIndex, uiCommand) if uiCommand is None: text = _('Separator') img = -1 elif isinstance(uiCommand, int): text = _('Spacer') img = -1 else: text = uiCommand.getHelpText() img = self.__imgListIndex.get(uiCommand.bitmap, -1) item = self.__visibleCommands.InsertItem(self.__visibleCommands.GetRootItem(), targetIndex, text) self.__visibleCommands.SetItemPyData(item, uiCommand) self.__visibleCommands.SetItemImage(item, img) self.__HackPreview() self.__draggedItem = None
def _getMail(self): if self.ssl: cn = imaplib.IMAP4_SSL(self.server, self.port) else: cn = imaplib.IMAP4(self.server, self.port) if self._PASSWORDS.has_key((self.server, self.user, self.port)): pwd = self._PASSWORDS[(self.server, self.user, self.port)] else: pwd = wx.GetPasswordFromUser(_('Please enter password for user %(user)s on %(server)s:%(port)d') % \ dict(user=self.user, server=self.server, port=self.port)) if pwd == '': raise ValueError('User canceled') while True: try: response, params = cn.login(self.user, pwd) except cn.error, e: response = 'KO' errmsg, = e.args if response == 'OK': break pwd = wx.GetPasswordFromUser(_('Login failed (%s). Please try again.') % errmsg) if pwd == '': raise ValueError('User canceled')
def __warn_user_that_ini_file_was_not_loaded(self): from taskcoachlib import meta reason = self.settings.get('file', 'inifileloaderror') wx.MessageBox(\ _("Couldn't load settings from TaskCoach.ini:\n%s") % reason, _('%s file error') % meta.name, style=wx.OK | wx.ICON_ERROR) self.settings.setboolean('file', 'inifileloaded', True) # Reset
def summary(self): if self.__handle is not None: self.close() if operating_system.isWindows(): wx.MessageBox(_('Errors have occured. Please see "taskcoachlog.txt" in your "My Documents" folder.'), _('Error'), wx.OK) else: wx.MessageBox(_('Errors have occured. Please see "%s"') % self.__path, _('Error'), wx.OK)
def SetOptions(self, options): self.options = options if self.interior.GetSizer(): self.interior.GetSizer().Clear(True) for child in self.interior.GetChildren(): self.interior.RemoveChild(child) self.choices = [] gsz = wx.FlexGridSizer(0, 2, 4, 2) gsz.Add(wx.StaticText(self.interior, wx.ID_ANY, _('Column header in CSV file'))) gsz.Add(wx.StaticText(self.interior, wx.ID_ANY, _('%s attribute')%meta.name)) gsz.AddSpacer((3,3)) gsz.AddSpacer((3,3)) tcFieldNames = [field[0] for field in self.fields] for fieldName in options['fields']: gsz.Add(wx.StaticText(self.interior, wx.ID_ANY, fieldName), flag=wx.ALIGN_CENTER_VERTICAL) choice = wx.Choice(self.interior, wx.ID_ANY) for tcFieldName in tcFieldNames: choice.Append(tcFieldName) choice.SetSelection(self.findFieldName(fieldName, tcFieldNames)) self.choices.append(choice) gsz.Add(choice, flag=wx.ALIGN_CENTER_VERTICAL) gsz.AddGrowableCol(1) self.interior.SetSizer(gsz) gsz.Layout()
def AttachmentSelector(**callerKeywordArguments): kwargs = {'message': _('Add attachment'), 'default_path': os.getcwd(), 'wildcard': _('All files (*.*)|*'), 'flags': wx.FD_OPEN} kwargs.update(callerKeywordArguments) return wx.FileSelector(**kwargs) # pylint: disable=W0142
def addDateEntries(self): for label, taskMethodName in [ (_("Start date"), "startDateTime"), (_("Due date"), "dueDateTime"), (_("Completion date"), "completionDateTime"), ]: self.addDateEntry(label, taskMethodName)
def __restore_perspective(self): perspective = self.settings.get('view', 'perspective') for viewer_type in viewer.viewerTypes(): if self.__perspective_and_settings_viewer_count_differ(viewer_type): # Different viewer counts may happen when the name of a viewer # is changed between versions perspective = '' break try: self.manager.LoadPerspective(perspective) except ValueError, reason: # This has been reported to happen. Don't know why. Keep going # if it does. if self.__splash: self.__splash.Destroy() wx.MessageBox(_('''Couldn't restore the pane layout from TaskCoach.ini: %s The default pane layout will be used. If this happens again, please make a copy of your TaskCoach.ini file ''' '''before closing the program, open a bug report, and attach the ''' '''copied TaskCoach.ini file to the bug report.''') % reason, _('%s settings error') % meta.name, style=wx.OK | wx.ICON_ERROR) self.manager.LoadPerspective('')
def validateDrag(self, dropItem, dragItems, columnIndex): if columnIndex == -1 or self.visibleColumns()[columnIndex].name() != 'ordering': return None # Normal behavior # Ordering if not self.isTreeViewer(): return True # Tree mode. Only allow drag if all selected items are siblings. if len(set([item.parent() for item in dragItems])) >= 2: wx.GetTopLevelParent(self).AddBalloonTip(self.settings, 'treemanualordering', self, title=_('Reordering in tree mode'), getRect=lambda: wx.Rect(0, 0, 28, 16), message=_('''When in tree mode, manual ordering is only possible when all selected items are siblings.''')) return False # If they are, only allow drag at the same level if dragItems[0].parent() != (None if dropItem is None else dropItem.parent()): wx.GetTopLevelParent(self).AddBalloonTip(self.settings, 'treechildrenmanualordering', self, title=_('Reordering in tree mode'), getRect=lambda: wx.Rect(0, 0, 28, 16), message=_('''When in tree mode, you can only put objects at the same level (parent).''')) return False return True
def _createColumns(self): # pylint: disable-msg=W0142 kwargs = dict(renderDescriptionCallback=lambda category: category.description(), resizeCallback=self.onResizeColumn) columns = [widgets.Column('subject', _('Subject'), category.Category.subjectChangedEventType(), sortCallback=uicommand.ViewerSortByCommand(viewer=self, value='subject'), imageIndexCallback=self.subjectImageIndex, width=self.getColumnWidth('subject'), **kwargs), widgets.Column('description', _('Description'), category.Category.descriptionChangedEventType(), sortCallback=uicommand.ViewerSortByCommand(viewer=self, value='description'), renderCallback=lambda category: category.description(), width=self.getColumnWidth('description'), **kwargs), widgets.Column('attachments', '', category.Category.attachmentsChangedEventType(), # pylint: disable-msg=E1101 width=self.getColumnWidth('attachments'), alignment=wx.LIST_FORMAT_LEFT, imageIndexCallback=self.attachmentImageIndex, headerImageIndex=self.imageIndex['paperclip_icon'], renderCallback=lambda category: '', **kwargs)] if self.settings.getboolean('feature', 'notes'): columns.append(widgets.Column('notes', '', category.Category.notesChangedEventType(), # pylint: disable-msg=E1101 width=self.getColumnWidth('notes'), alignment=wx.LIST_FORMAT_LEFT, imageIndexCallback=self.noteImageIndex, headerImageIndex=self.imageIndex['note_icon'], renderCallback=lambda category: '', **kwargs)) return columns
def __setTooltipText(self): ''' Note that Windows XP and Vista limit the text shown in the tool tip to 64 characters, so we cannot show everything we would like to and have to make choices. ''' textParts = [] trackedTasks = self.__taskList.tasksBeingTracked() if trackedTasks: count = len(trackedTasks) if count == 1: tracking = _('tracking "%s"')%trackedTasks[0].subject() else: tracking = _('tracking effort for %d tasks')%count textParts.append(tracking) else: for getCountMethodName, singular, plural in self.toolTipMessages: count = getattr(self.__taskList, getCountMethodName)() if count == 1: textParts.append(singular) elif count > 1: textParts.append(plural%count) text = ', '.join(textParts) text = u'%s - %s'%(meta.name, text) if text else meta.name if text != self.__tooltipText: self.__tooltipText = text self.__setIcon() # Update tooltip
def __init__(self, mainwindow, settings, taskFile, viewerContainer): super(ActionMenu, self).__init__(mainwindow) tasks = taskFile.tasks() efforts = taskFile.efforts() categories = taskFile.categories() self.appendUICommands( uicommand.AddAttachment(viewer=viewerContainer, settings=settings), uicommand.OpenAllAttachments(viewer=viewerContainer, settings=settings), None) if settings.getboolean('feature', 'notes'): self.appendUICommands( uicommand.AddNote(viewer=viewerContainer, settings=settings), uicommand.OpenAllNotes(viewer=viewerContainer, settings=settings), None) self.appendUICommands( uicommand.Mail(viewer=viewerContainer), None) self.appendMenu(_('&Toggle category'), ToggleCategoryMenu(mainwindow, categories=categories, viewer=viewerContainer), 'folder_blue_arrow_icon') self.appendUICommands( None, uicommand.TaskToggleCompletion(viewer=viewerContainer)) self.appendMenu(_('Change task &priority'), TaskPriorityMenu(mainwindow, tasks, viewerContainer)) if settings.getboolean('feature', 'effort'): self.appendUICommands( None, uicommand.EffortStart(viewer=viewerContainer, taskList=tasks), uicommand.EffortStop(effortList=efforts, taskList=tasks), uicommand.EditTrackedTasks(taskList=tasks, settings=settings))
def __init__(self, *args, **kwargs): super(TaskReminderPage, self).__init__(columns=3, growableColumn=-1, *args, **kwargs) names = [] # There's at least one, the universal one for name in notify.AbstractNotifier.names(): names.append((name, name)) self.addChoiceSetting('feature', 'notifier', _('Notification system to use for reminders'), '', names, flags=(None, wx.ALL | wx.ALIGN_LEFT)) if operating_system.isMac() or operating_system.isGTK(): self.addBooleanSetting('feature', 'sayreminder', _('Let the computer say the reminder'), _('(Needs espeak)') if operating_system.isGTK() else '', flags=(None, wx.ALL | wx.ALIGN_LEFT, wx.ALL | wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL)) snoozeChoices = [(str(choice[0]), choice[1]) for choice in date.snoozeChoices] self.addChoiceSetting('view', 'defaultsnoozetime', _('Default snooze time to use after reminder'), '', snoozeChoices, flags=(None, wx.ALL | wx.ALIGN_LEFT)) self.addMultipleChoiceSettings('view', 'snoozetimes', _('Snooze times to offer in task reminder dialog'), date.snoozeChoices[1:], flags=(wx.ALIGN_TOP | wx.ALL, None)) # Don't offer "Don't snooze" as a choice self.fit()
def addStartAndStopEntries(self): starthour = self._settings.getint("view", "efforthourstart") endhour = self._settings.getint("view", "efforthourend") interval = self._settings.getint("view", "effortminuteinterval") self._startEntry = widgets.DateTimeCtrl( self, self._effort.getStart(), self.onPeriodChanged, noneAllowed=False, starthour=starthour, endhour=endhour, interval=interval, ) startFromLastEffortButton = wx.Button(self, label=_("Start tracking from last stop time")) self.Bind(wx.EVT_BUTTON, self.onStartFromLastEffort, startFromLastEffortButton) if self._effortList.maxDateTime() is None: startFromLastEffortButton.Disable() self._stopEntry = widgets.DateTimeCtrl( self, self._effort.getStop(), self.onPeriodChanged, noneAllowed=True, starthour=starthour, endhour=endhour, interval=interval, ) flags = [None, wx.ALIGN_RIGHT | wx.ALL, wx.ALIGN_LEFT | wx.ALL, None] self.addEntry(_("Start"), self._startEntry, startFromLastEffortButton, flags=flags) self.addEntry(_("Stop"), self._stopEntry, "", flags=flags)
def fillInterior(self): self._templateList = wx.ListCtrl(self._interior, wx.ID_ANY, style=wx.LC_REPORT) self._templateList.InsertColumn(0, _('Template')) self._templateList.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectionChanged) self._templateList.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnSelectionChanged) self._loadTemplates() for task, name in self.tasks: self._templateList.InsertStringItem(self._templateList.GetItemCount(), task.subject()) self._templateList.SetColumnWidth(0, -1) self._btnDelete = wx.Button(self._interior, wx.ID_ANY, _("Delete")) self._btnDelete.Bind(wx.EVT_BUTTON, self.OnDelete) self._btnDelete.Enable(False) self._btnUp = wx.BitmapButton(self._interior, wx.ID_ANY, wx.ArtProvider.GetBitmap('arrow_up_icon', size=(32, 32))) self._btnUp.Bind(wx.EVT_BUTTON, self.OnUp) self._btnUp.Enable(False) self._btnDown = wx.BitmapButton(self._interior, wx.ID_ANY, wx.ArtProvider.GetBitmap('arrow_down_icon', size=(32, 32))) self._btnDown.Bind(wx.EVT_BUTTON, self.OnDown) self._btnDown.Enable(False) hsz = wx.BoxSizer(wx.HORIZONTAL) hsz.Add(self._templateList, 1, wx.EXPAND|wx.ALL, 3) vsz = wx.BoxSizer(wx.VERTICAL) vsz.Add(self._btnDelete, 0, wx.ALL, 3) vsz.Add(self._btnUp, 0, wx.ALL|wx.ALIGN_CENTRE, 3) vsz.Add(self._btnDown, 0, wx.ALL|wx.ALIGN_CENTRE, 3) hsz.Add(vsz, 0, wx.ALL, 3) self._interior.SetSizer(hsz)
def _getMail(self): if self.ssl: cn = imaplib.IMAP4_SSL(self.server, self.port) else: cn = imaplib.IMAP4(self.server, self.port) if self._PASSWORDS.has_key((self.server, self.user, self.port)): pwd = self._PASSWORDS[(self.server, self.user, self.port)] else: pwd = wx.GetPasswordFromUser(_('Please enter password for user %(user)s on %(server)s:%(port)d') % \ dict(user=self.user, server=self.server, port=self.port)) if pwd == '': raise ThunderbirdCancelled('User canceled') while True: try: if 'AUTH=CRAM-MD5' in cn.capabilities: response, params = cn.login_cram_md5(str(self.user), str(pwd)) else: response, params = cn.login(self.user, pwd) except cn.error, e: response = 'KO' errmsg, = e.args if response == 'OK': break pwd = wx.GetPasswordFromUser(_('Login failed (%s). Please try again.') % errmsg) if pwd == '': raise ThunderbirdCancelled('User canceled')
def onURLClicked(self, event): mouseEvent = event.GetMouseEvent() if mouseEvent.ButtonDown() and self.__webbrowser: url = self.GetRange(event.GetURLStart(), event.GetURLEnd()) try: self.__webbrowser.open(url) except Exception, message: wx.MessageBox(unicode(message), i18n._('Error opening URL'))
def createCategoryFilterCommands(self): categories = self.taskFile.categories() commands = [_('&Categories'), uicommand.ResetCategoryFilter(categories=categories)] if categories: commands.append(None) commands.extend(self.createToggleCategoryFilterCommands(categories.rootItems())) return [tuple(commands)]
def testPlannedStartDateTimeYesterday(self): yesterday = date.Yesterday() self.task.setPlannedStartDateTime(yesterday) self.taskList.append(self.task) self.showColumn('plannedStartDateTime') self.assertEqual( _('Yesterday %s') % render.time(yesterday.time()), self.getItemText(0, 1))
def testPlannedStartDateTimeTomorrow(self): tomorrow = date.Tomorrow() self.task.setPlannedStartDateTime(tomorrow) self.taskList.append(self.task) self.showColumn('plannedStartDateTime') self.assertEqual( _('Tomorrow %s') % render.time(tomorrow.time()), self.getItemText(0, 1))
def testCompletionDateTimeYesterday(self): yesterday = date.Yesterday() self.task.setCompletionDateTime(yesterday) self.taskList.append(self.task) self.showColumn('completionDateTime') self.assertEqual( _('Yesterday %s') % render.time(yesterday.time()), self.getItemText(0, 3))
def testCompletionDateTimeTomorrow(self): tomorrow = date.Tomorrow() self.task.setCompletionDateTime(tomorrow) self.taskList.append(self.task) self.showColumn('completionDateTime') self.assertEqual( _('Tomorrow %s') % render.time(tomorrow.time()), self.getItemText(0, 3))
def init(self): super(FullFromDesktopCategoryState, self).init('i', len(self.categories)) self.disp().log(_('%d categories'), len(self.categories)) if self.categories: self.sendObject()
class EditTaskCommand(base.EditCommand): plural_name = _('Edit tasks') singular_name = _('Edit task "%s"') def __init__(self, *args, **kwargs): super(EditTaskCommand, self).__init__(*args, **kwargs) self.oldCategories = [item.categories() for item in self.items] self.oldPrerequisites = [item.prerequisites() for item in self.items] def do_command(self): super(EditTaskCommand, self).do_command() # pylint: disable-msg=W0201 self.newCategories = [item.categories() for item in self.items] self.updateCategories(self.oldCategories, self.newCategories) self.newPrerequisites = [item.prerequisites() for item in self.items] self.updatePrerequisites(self.oldPrerequisites, self.newPrerequisites) def undo_command(self): super(EditTaskCommand, self).undo_command() self.updateCategories(self.newCategories, self.oldCategories) self.updatePrerequisites(self.newPrerequisites, self.oldPrerequisites) def redo_command(self): super(EditTaskCommand, self).redo_command() self.updateCategories(self.oldCategories, self.newCategories) self.updatePrerequisites(self.oldPrerequisites, self.newPrerequisites) def getItemsToSave(self): return set( [relative for item in self.items for relative in item.family()]) def updateCategories(self, oldCategories, newCategories): for item, categories in zip(self.items, oldCategories): for category in categories: category.removeCategorizable(item) for item, categories in zip(self.items, newCategories): for category in categories: category.addCategorizable(item) def updatePrerequisites(self, oldPrerequisites, newPrerequisites): for item, prerequisites in zip(self.items, oldPrerequisites): for prerequisite in prerequisites: prerequisite.removeDependencies([item]) for item, prerequisites in zip(self.items, newPrerequisites): for prerequisite in prerequisites: prerequisite.addDependencies([item])
def init(self): super(TaskFileNameState, self).init('i', 1) filename = self.disp().iocontroller.filename() if filename: filename = os.path.splitext(os.path.split(filename)[1])[0] self.disp().log(_('Sending file name: %s'), filename) self.pack('z', filename)
def sendObject(self): if self.efforts: effort = self.efforts.pop(0) self.disp().log(_('Send effort %s'), effort.id()) self.pack( 'ssztt', effort.id(), effort.subject(), effort.task().id() if effort.task() is not None else None, effort.getStart(), effort.getStop())
def __showReminderViaNotifier(self, taskWithReminder): notifier = notify.AbstractNotifier.get( self.settings.get('feature', 'notifier')) notifier.notify(_('%s Reminder') % meta.name, taskWithReminder.subject(), wx.ArtProvider.GetBitmap('taskcoach', size=wx.Size(32, 32)), windowId=self.__mainWindow.GetHandle())
def __init__(self, iocontroller, taskFile, settings, *args, **kwargs): self.__splash = kwargs.pop('splash', None) super(MainWindow, self).__init__(None, -1, '', *args, **kwargs) # This prevents the viewers from flickering on Windows 7 when refreshed: if operating_system.isWindows7_OrNewer(): turn_on_double_buffering_on_windows(self) self.__dimensions_tracker = windowdimensionstracker.WindowDimensionsTracker( self, settings) self.iocontroller = iocontroller self.taskFile = taskFile self.settings = settings self.__filename = None self.__dirty = False self.__shutdown = False self.Bind(wx.EVT_CLOSE, self.onClose) self.Bind(wx.EVT_ICONIZE, self.onIconify) self.Bind(wx.EVT_SIZE, self.onResize) self._create_window_components() # Not private for test purposes self.__init_window_components() self.__init_window() self.__register_for_window_component_changes() if settings.getboolean('feature', 'syncml'): try: import taskcoachlib.syncml.core # pylint: disable=W0612,W0404 except ImportError: if settings.getboolean('syncml', 'showwarning'): dlg = widgets.SyncMLWarningDialog(self) try: if dlg.ShowModal() == wx.ID_OK: settings.setboolean('syncml', 'showwarning', False) finally: dlg.Destroy() self.bonjourRegister = None if settings.getboolean('feature', 'iphone'): # pylint: disable=W0612,W0404,W0702 try: from taskcoachlib.thirdparty import pybonjour from taskcoachlib.iphone import IPhoneAcceptor, BonjourServiceRegister acceptor = IPhoneAcceptor(self, settings, iocontroller) self.bonjourRegister = BonjourServiceRegister( settings, acceptor.port) except: from taskcoachlib.gui.dialog.iphone import IPhoneBonjourDialog dlg = IPhoneBonjourDialog(self, wx.ID_ANY, _('Warning')) try: dlg.ShowModal() finally: dlg.Destroy() self._idleController = idlecontroller.IdleController( self, self.settings, self.taskFile.efforts()) wx.CallAfter(self.checkXFCE4)
def __init__(self, domain, username, *args, **kwargs): super(KeychainPasswordWidget, self).__init__(*args, **kwargs) self.domain = domain.encode('UTF-8') self.username = username.encode('UTF-8') pnl = wx.Panel(self, wx.ID_ANY) hsz = wx.BoxSizer(wx.HORIZONTAL) hsz.Add(wx.StaticText(pnl, wx.ID_ANY, _('Password:'******'').decode('UTF-8') self.passwordField = wx.TextCtrl(pnl, wx.ID_ANY, self.password, style=wx.TE_PASSWORD) hsz.Add(self.passwordField, 1, wx.ALL, 3) vsz = wx.BoxSizer(wx.VERTICAL) vsz.Add(hsz, 0, wx.ALL | wx.EXPAND, 3) self.keepInKeychain = wx.CheckBox(pnl, wx.ID_ANY, _('Store in keychain')) self.keepInKeychain.SetValue(bool(password)) vsz.Add(self.keepInKeychain, 0, wx.ALL | wx.EXPAND, 3) hsz = wx.BoxSizer(wx.HORIZONTAL) btnOK = wx.Button(pnl, wx.ID_ANY, _('OK')) hsz.Add(btnOK, 0, wx.ALL, 3) btnCancel = wx.Button(pnl, wx.ID_ANY, _('Cancel')) hsz.Add(btnCancel, 0, wx.ALL, 3) vsz.Add(hsz, 0, wx.ALL | wx.ALIGN_CENTRE, 3) pnl.SetSizer(vsz) sz = wx.BoxSizer(wx.HORIZONTAL) sz.Add(pnl, 1, wx.EXPAND | wx.ALL, 3) self.SetSizer(sz) self.Fit() wx.EVT_BUTTON(btnOK, wx.ID_ANY, self.OnOK) wx.EVT_BUTTON(btnCancel, wx.ID_ANY, self.OnCancel) self.SetDefaultItem(btnOK) wx.CallAfter(self.RequestUserAttention)
def GetPassword(domain, username, reset=False): global _PASSWORDCACHE try: from taskcoachlib.thirdparty.keyring import set_password, get_password except: # Keychain unavailable. if _PASSWORDCACHE is None: import StringIO, traceback bf = StringIO.StringIO() traceback.print_exc(file=bf) wx.MessageBox( _('There was a problem trying to find out your system\'s keychain.\nPlease file a bug report (see the Help menu) and attach a screenshot of this message.\nError was:\n\n%s' ) % bf.getvalue(), _('Error'), wx.OK) _PASSWORDCACHE = dict() if (domain, username) in _PASSWORDCACHE and reset: del _PASSWORDCACHE[(domain, username)] if (domain, username) not in _PASSWORDCACHE: pwd = wx.GetPasswordFromUser(_('Please enter your password.'), domain) if not pwd: return None _PASSWORDCACHE[(domain, username)] = pwd return _PASSWORDCACHE[(domain, username)] if reset: set_password(domain.encode('UTF-8'), username.encode('UTF-8'), '') else: pwd = get_password(domain.encode('UTF-8'), username.encode('UTF-8')) if pwd: return pwd.decode('UTF-8') dlg = KeychainPasswordWidget(domain, username, None, wx.ID_ANY, _('Please enter your password'), style=wx.DEFAULT_DIALOG_STYLE | wx.STAY_ON_TOP) try: dlg.CentreOnScreen() if dlg.ShowModal() == wx.ID_OK: return dlg.password finally: dlg.Destroy()
def __init__(self, task, taskList, settings, *args, **kwargs): kwargs['title'] = kwargs.get('title', meta.name + ' ' + _('Reminder')) super(ReminderDialog, self).__init__(*args, **kwargs) self.SetIcon( wx.ArtProvider_GetIcon('taskcoach', wx.ART_FRAME_ICON, (16, 16))) self.task = task self.taskList = taskList self.settings = settings patterns.Publisher().registerObserver( self.onTaskRemoved, eventType=self.taskList.removeItemEventType(), eventSource=self.taskList) patterns.Publisher().registerObserver( self.onTaskCompletionDateChanged, eventType='task.completionDateTime', eventSource=self.task) self.openTaskAfterClose = self.ignoreSnoozeOption = False pane = self.GetContentsPane() pane.SetSizerType("form") wx.StaticText(pane, label=_('Task') + ':') self.openTask = wx.Button(pane, label=self.task.subject(recursive=True)) self.openTask.Bind(wx.EVT_BUTTON, self.onOpenTask) for label in _('Reminder date/time') + ':', \ render.dateTime(self.task.reminder()), _('Snooze') + ':': wx.StaticText(pane, label=label) self.snoozeOptions = wx.ComboBox(pane) snoozeTimesUserWantsToSee = [0] + eval( self.settings.get('view', 'snoozetimes')) for minutes, label in date.snoozeChoices: if minutes in snoozeTimesUserWantsToSee: self.snoozeOptions.Append(label, date.TimeDelta(minutes=minutes)) self.snoozeOptions.SetSelection(0) buttonSizer = self.CreateStdDialogButtonSizer(wx.OK) self.markCompleted = wx.Button(self, label=_('Mark task completed')) self.markCompleted.Bind(wx.EVT_BUTTON, self.onMarkTaskCompleted) if self.task.completed(): self.markCompleted.Disable() buttonSizer.Add(self.markCompleted) self.SetButtonSizer(buttonSizer) self.Bind(wx.EVT_CLOSE, self.onClose) self.Bind(wx.EVT_BUTTON, self.onOK, id=self.GetAffirmativeId()) self.Fit() self.RequestUserAttention()
def __init__(self, htmlText, settings): super(HTMLPrintout, self).__init__() self.SetHtmlText(htmlText) self.SetFooter(_('Page') + ' @PAGENUM@/@PAGESCNT@', wx.html.PAGE_ALL) self.SetFonts('Arial', 'Courier') printerSettings = PrinterSettings(settings) left, top = printerSettings.pageSetupData.GetMarginTopLeft() right, bottom = printerSettings.pageSetupData.GetMarginBottomRight() self.SetMargins(top, bottom, left, right)
def __init__(self, *args, **kwargs): subject = kwargs.pop('subject', _('New note')) description = kwargs.pop('description', '') attachments = kwargs.pop('attachments', []) categories = kwargs.get('categories', None) super(NewNoteCommand, self).__init__(*args, **kwargs) self.items = self.notes = [note.Note(subject=subject, description=description, categories=categories, attachments=attachments)]
def saveas(self, filename=None, showerror=wx.MessageBox): if not filename: filename = self.__askUserForFile(_('Save as...'), flags=wx.SAVE) if not filename: return False # User didn't enter a filename, cancel save if self._saveSave(self.__taskFile, showerror, filename): return True else: return self.saveas(showerror=showerror) # Try again
def importTemplate(self, showerror=wx.MessageBox): filename = self.__askUserForFile(_('Import template'), fileDialogOpts={ 'default_extension': 'tsktmpl', 'wildcard': _('%s template files (*.tsktmpl)|' '*.tsktmpl') % meta.name }) if filename: templates = persistence.TemplateList( self.__settings.pathToTemplatesDir()) try: templates.copyTemplate(filename) except Exception, reason: # pylint: disable=W0703 errorMessage = _('Cannot import template %s\n%s') % ( filename, ExceptionAsUnicode(reason)) showerror(errorMessage, **self.__errorMessageOptions)
class EditCommand(BaseCommand, SaveStateMixin): # pylint: disable-msg=W0223 plural_name = _('Edit') singular_name = _('Edit "%s"') def __init__(self, *args, **kwargs): super(EditCommand, self).__init__(*args, **kwargs) self.saveStates(self.getItemsToSave()) def getItemsToSave(self): raise NotImplementedError # pragma: no cover def undo_command(self): self.undoStates() super(EditCommand, self).undo_command() def redo_command(self): self.redoStates() super(EditCommand, self).redo_command()
def __init__(self, *args, **kwargs): self.owners = [] self.__attachments = kwargs.get( 'attachments', [attachment.FileAttachment('', subject=_('New attachment'))]) super(AddAttachmentCommand, self).__init__(*args, **kwargs) self.owners = self.items self.items = self.__attachments self.save_modification_datetimes()
def exportAsHTML(self, viewer, selectionOnly=False, openfile=codecs.open, showerror=wx.MessageBox, filename=None): return self.export(_('Export as HTML...'), self.__htmlFileDialogOpts, persistence.HTMLWriter, viewer, selectionOnly, openfile, showerror, filename)
def createHelpInformation(self, parent): width = max([ child.GetSize()[0] for child in [self.separateCSSCheckBox] + list(parent.GetChildren()) ]) info = wx.StaticText(self, label=_('If a CSS file exists for the exported file, %(name)s will not overwrite it. ' \ 'This allows you to change the style information without losing your changes on the next export.') % meta.metaDict) info.Wrap(width)
def __init__(self, *args, **kwargs): super(IPhonePage, self).__init__(columns=3, *args, **kwargs) self.addTextSetting( 'iphone', 'password', _('Password for synchronization with iPhone'), helpText= _('When synchronizing, enter this password on the iPhone to authorize it' )) self.addTextSetting('iphone', 'service', _('Bonjour service name'), helpText='restart') self.addBooleanSetting('iphone', 'synccompleted', _('Upload completed tasks to device')) self.addBooleanSetting('iphone', 'showlog', _('Show the synchronization log')) self.fit()
def synchronize(self, password): synchronizer = sync.Synchronizer(self.__syncReport, self, self.__taskFile, password) try: synchronizer.synchronize() finally: synchronizer.Destroy() self.__messageCallback(_('Finished synchronization'))
def __create_message(self, pane): ''' Create the interior parts of the dialog, i.e. the message for the user. ''' message = wx.StaticText(pane, label=self.__message) message.Wrap(500) url_panel = sized_controls.SizedPanel(pane) url_panel.SetSizerType('horizontal') wx.StaticText(url_panel, label=_('See:')) hyperlink.HyperLinkCtrl(url_panel, label=self.__url)
def __init__(self, *args, **kwargs): subject = kwargs.pop('subject', _('New subcategory')) description = kwargs.pop('description', '') attachments = kwargs.pop('attachments', []) super(NewSubCategoryCommand, self).__init__(*args, **kwargs) self.items = self.createNewCategories(subject=subject, description=description, attachments=attachments) self.save_modification_datetimes()
def OnOptionChanged(self, event): # pylint: disable=W0613 self.escapeChar.Enable(self.escapeQuote.GetValue()) if self.filename is None: self.grid.SetRowLabelSize(0) self.grid.SetColLabelSize(0) if self.grid.GetNumberCols(): self.grid.DeleteRows(0, self.grid.GetNumberRows()) self.grid.DeleteCols(0, self.grid.GetNumberCols()) else: if self.doubleQuote.GetValue(): doublequote = True escapechar = '' else: doublequote = False escapechar = self.escapeChar.GetValue().encode('UTF-8') self.dialect = CSVDialect(delimiter={0: ',', 1: '\t', 2: ' ', 3: ':', 4: ';', 5: '|'}[self.delimiter.GetSelection()], quotechar={0: "'", 1: '"'}[self.quoteChar.GetSelection()], doublequote=doublequote, escapechar=escapechar) fp = tempfile.TemporaryFile() try: fp.write(file(self.filename, 'rU').read().decode(self.encoding).encode('UTF-8')) fp.seek(0) reader = csv.reader(fp, dialect=self.dialect) if self.hasHeaders.GetValue(): self.headers = [header.decode('UTF-8') for header in reader.next()] else: # In some cases, empty fields are omitted if they're at the end... hsize = 0 for line in reader: hsize = max(hsize, len(line)) self.headers = [_('Field #%d') % idx for idx in xrange(hsize)] fp.seek(0) reader = csv.reader(fp, dialect=self.dialect) if self.grid.GetNumberCols(): self.grid.DeleteRows(0, self.grid.GetNumberRows()) self.grid.DeleteCols(0, self.grid.GetNumberCols()) self.grid.InsertCols(0, len(self.headers)) self.grid.SetColLabelSize(20) for idx, header in enumerate(self.headers): self.grid.SetColLabelValue(idx, header) lineno = 0 for line in reader: self.grid.InsertRows(lineno, 1) for idx, value in enumerate(line): if idx < self.grid.GetNumberCols(): self.grid.SetCellValue(lineno, idx, value.decode('UTF-8')) lineno += 1 finally: fp.close()
class DragAndDropTaskCommand(base.DragAndDropCommand): plural_name = _('Drag and drop tasks') def __init__(self, *args, **kwargs): self.__part = kwargs.pop('part', 0) super(DragAndDropTaskCommand, self).__init__(*args, **kwargs) def getItemsToSave(self): toSave = super(DragAndDropTaskCommand, self).getItemsToSave() if self.__part != 0: toSave.extend(self.getSiblings()) return toSave def getSiblings(self): siblings = [] for item in self.list: if item.parent() == self._itemToDropOn.parent( ) and item not in self.items: siblings.append(item) return siblings def do_command(self): if self.__part == 0: super(DragAndDropTaskCommand, self).do_command() else: if self.__part == -1: # Up part. Add dropped items as prerequisites of dropped on item. self._itemToDropOn.addPrerequisites(self.items) self._itemToDropOn.addTaskAsDependencyOf(self.items) else: # Down. Add dropped on item as prerequisite of dropped items. for item in self.items: item.addPrerequisites([self._itemToDropOn]) item.addTaskAsDependencyOf([self._itemToDropOn]) def undo_command(self): if self.__part == 0: super(DragAndDropTaskCommand, self).undo_command() elif self.__part == -1: self._itemToDropOn.removePrerequisites(self.items) self._itemToDropOn.removeTaskAsDependencyOf(self.items) else: for item in self.items: item.removePrerequisites([self._itemToDropOn]) item.removeTaskAsDependencyOf([self._itemToDropOn]) def redo_command(self): if self.__part == 0: super(DragAndDropTaskCommand, self).redo_command() elif self.__part == -1: self._itemToDropOn.addPrerequisites(self.items) self._itemToDropOn.addTaskAsDependencyOf(self.items) else: for item in self.items: item.addPrerequisites([self._itemToDropOn]) item.addTaskAsDependencyOf([self._itemToDropOn])
def __init__(self, *args, **kwargs): super(SyncMLTaskPage, self).__init__(*args, **kwargs) self.addBooleanSetting('task', 'dosync', _('Enable tasks synchronization')) self.addTextSetting('task', 'uri', _('Tasks database name')) self.addChoiceSetting('task', 'preferredsyncmode', _('Preferred synchonization mode'), [('TWO_WAY', _('Two way')), ('SLOW', _('Slow')), ('ONE_WAY_FROM_CLIENT', _('One way from client')), ('REFRESH_FROM_CLIENT', _('Refresh from client')), ('ONE_WAY_FROM_SERVER', _('One way from server')), ('REFRESH_FROM_SERVER', _('Refresh from server'))]) self.fit()