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 __init__(self, parent, *args, **kwargs):
     super(BaseTextCtrl, self).__init__(parent, -1, *args, **kwargs)
     self.__data = None
     if operating_system.isGTK() or operating_system.isMac():
         if operating_system.isGTK():
             self.Bind(wx.EVT_KEY_DOWN, self.__on_key_down)
         self.Bind(wx.EVT_KILL_FOCUS, self.__on_kill_focus)
         self.__initial_value = self.GetValue()
         self.__undone_value = None
Example #3
0
 def __init__(self, parent, *args, **kwargs):
     super(BaseTextCtrl, self).__init__(parent, -1, *args, **kwargs)
     self.__data = None
     if operating_system.isGTK() or operating_system.isMac():
         if operating_system.isGTK():
             self.Bind(wx.EVT_KEY_DOWN, self.__on_key_down)
         self.Bind(wx.EVT_KILL_FOCUS, self.__on_kill_focus)
         self.__initial_value = self.GetValue()
         self.__undone_value = None
 def __init__(self):
     if operating_system.isMac():
         self.__binary = 'say'
     elif operating_system.isGTK():
         self.__binary = 'espeak'
     self.__texts_to_say = []
     self.__current_speech_process = None
 def _SetSelection(self, start, end):
     if operating_system.isGTK():  # pragma: no cover
         # By exchanging the start and end parameters we make sure that the 
         # cursor is at the start of the field so that typing overwrites the 
         # current field instead of moving to the next field:
         start, end = end, start
     super(FixOverwriteSelectionMixin, self)._SetSelection(start, end)
    def __init__(self, parent, title, bitmap='edit', 
                 direction=None, *args, **kwargs):
        self._buttonTypes = kwargs.get('buttonTypes', wx.OK | wx.CANCEL)
        super(Dialog, self).__init__(parent, -1, title,
            style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER | wx.MAXIMIZE_BOX | wx.MINIMIZE_BOX)
        self.SetIcon(wx.ArtProvider_GetIcon(bitmap, wx.ART_FRAME_ICON,
            (16, 16)))

        if operating_system.isWindows7_OrNewer():
            # Without this the window has no taskbar icon on Windows, and the focus comes back to the main
            # window instead of this one when returning to Task Coach through Alt+Tab. Which is probably not
            # what we want.
            import win32gui, win32con
            exStyle = win32gui.GetWindowLong(self.GetHandle(), win32con.GWL_EXSTYLE)
            win32gui.SetWindowLong(self.GetHandle(), win32con.GWL_EXSTYLE, exStyle|win32con.WS_EX_APPWINDOW)

        self._panel = self.GetContentsPane()
        self._panel.SetSizerType('vertical')
        self._panel.SetSizerProps(expand=True, proportion=1)
        self._direction = direction
        self._interior = self.createInterior()
        self._interior.SetSizerProps(expand=True, proportion=1)
        self.fillInterior()
        self._buttons = self.createButtons()
        self._panel.Fit()
        self.Fit()
        self.CentreOnParent()
        if not operating_system.isGTK():
            wx.CallAfter(self.Raise)
        wx.CallAfter(self._panel.SetFocus)
 def addBitmapToMenuItem(self, menuItem):
     if self.bitmap2 and self.kind == wx.ITEM_CHECK and not operating_system.isGTK():
         bitmap1 = self.__getBitmap(self.bitmap) 
         bitmap2 = self.__getBitmap(self.bitmap2)
         menuItem.SetBitmaps(bitmap1, bitmap2)
     elif self.bitmap and self.kind == wx.ITEM_NORMAL:
         menuItem.SetBitmap(self.__getBitmap(self.bitmap))
Example #8
0
 def pathToDocumentsDir():
     if operating_system.isWindows():
         from win32com.shell import shell, shellcon
         try:
             return shell.SHGetSpecialFolderPath(None, shellcon.CSIDL_PERSONAL)
         except:
             # Yes, one of the documented ways to get this sometimes fail with "Unspecified error". Not sure
             # this will work either.
             # Update: There are cases when it doesn't work either; see support request #410...
             try:
                 return shell.SHGetFolderPath(None, shellcon.CSIDL_PERSONAL, None, 0) # SHGFP_TYPE_CURRENT not in shellcon
             except:
                 return os.getcwd() # F**k this
     elif operating_system.isMac():
         import Carbon.Folder, Carbon.Folders, Carbon.File
         pathRef = Carbon.Folder.FSFindFolder(Carbon.Folders.kUserDomain, Carbon.Folders.kDocumentsFolderType, True)
         return Carbon.File.pathname(pathRef)
     elif operating_system.isGTK():
         try:
             from PyKDE4.kdeui import KGlobalSettings
         except ImportError:
             pass
         else:
             return unicode(KGlobalSettings.documentPath())
     # Assuming Unix-like
     return os.path.expanduser('~')
Example #9
0
 def __init__(self):
     if operating_system.isMac():
         self.__binary = 'say'
     elif operating_system.isGTK():
         self.__binary = 'espeak'
     self.__texts_to_say = []
     self.__current_speech_process = None
Example #10
0
 def _SetSelection(self, start, end):
     if operating_system.isGTK():  # pragma: no cover
         # By exchanging the start and end parameters we make sure that the
         # cursor is at the start of the field so that typing overwrites the
         # current field instead of moving to the next field:
         start, end = end, start
     super(FixOverwriteSelectionMixin, self)._SetSelection(start, end)
Example #11
0
    def quitApplication(self, force=False):
        if not self.iocontroller.close(force=force):
            return False
        # Remember what the user was working on: 
        self.settings.set('file', 'lastfile', self.taskFile.lastFilename())
        self.mainwindow.save_settings()
        self.settings.save()
        if hasattr(self, 'taskBarIcon'):
            self.taskBarIcon.RemoveIcon()
        if self.mainwindow.bonjourRegister is not None:
            self.mainwindow.bonjourRegister.stop()
        from taskcoachlib.domain import date 
        date.Scheduler().shutdown()
        self.__wx_app.ProcessIdle()

        # For PowerStateMixin
        self.mainwindow.OnQuit()

        if operating_system.isGTK() and self.sessionMonitor is not None:
            self.sessionMonitor.stop()

        if isinstance(sys.stdout, RedirectedOutput):
            sys.stdout.summary()

        self.__wx_app.ExitMainLoop()
        return True
Example #12
0
 def __init__(self):
     self.__iconCache = dict()
     if operating_system.isMac():
         self.__iconSizeOnCurrentPlatform = 128
     elif operating_system.isGTK():
         self.__iconSizeOnCurrentPlatform = 48
     else:
         self.__iconSizeOnCurrentPlatform = 16
Example #13
0
 def tearDown(self):
     # TaskEditor uses CallAfter for setting the focus, make sure those 
     # calls are dealt with, otherwise they'll turn up in other tests
     if operating_system.isGTK():
         wx.Yield()  # pragma: no cover 
     super(TaskEditorTestCase, self).tearDown()
     self.taskFile.close()
     self.taskFile.stop()
Example #14
0
 def addBitmapToMenuItem(self, menuItem):
     if self.bitmap2 and self.kind == wx.ITEM_CHECK and not operating_system.isGTK(
     ):
         bitmap1 = self.__getBitmap(self.bitmap)
         bitmap2 = self.__getBitmap(self.bitmap2)
         menuItem.SetBitmaps(bitmap1, bitmap2)
     elif self.bitmap and self.kind == wx.ITEM_NORMAL:
         menuItem.SetBitmap(self.__getBitmap(self.bitmap))
 def setDescription(self, newDescription):
     page = self.editor._interior[0]
     page._descriptionEntry.SetFocus()
     page._descriptionEntry.SetValue(newDescription)
     if operating_system.isGTK(): # pragma: no cover
         page._descriptionSync.onAttributeEdited(DummyEvent())
     else: # pragma: no cover
         page._subjectEntry.SetFocus()
 def __init__(self):
     self.__iconCache = dict()
     if operating_system.isMac():
         self.__iconSizeOnCurrentPlatform = 128
     elif operating_system.isGTK():
         self.__iconSizeOnCurrentPlatform = 48
     else:
         self.__iconSizeOnCurrentPlatform = 16
Example #17
0
 def setDescription(self, newDescription):
     page = self.editor._interior[0]
     page._descriptionEntry.SetFocus()
     page._descriptionEntry.SetValue(newDescription)
     if operating_system.isGTK():  # pragma: no cover
         page._descriptionSync.onAttributeEdited(DummyEvent())
     else:  # pragma: no cover
         page._subjectEntry.SetFocus()
Example #18
0
    def OnInit(self):
        if operating_system.isWindows():
            self.Bind(wx.EVT_QUERY_END_SESSION, self.onQueryEndSession)

        if (operating_system.isMac() and hasattr(sys, 'frozen')) or \
            (operating_system.isGTK() and not sys.stdout.isatty()):
            sys.stdout = sys.stderr = RedirectedOutput()

        return True
Example #19
0
 def __should_create_page(self, page_name):
     if page_name == 'iphone':
         return self.settings.getboolean('feature', 'iphone')
     elif page_name == 'os_darwin':
         return operating_system.isMac()
     elif page_name == 'os_linux':
         return operating_system.isGTK()
     else:
         return True
 def __should_create_page(self, page_name):
     if page_name == 'iphone':
         return self.settings.getboolean('feature', 'iphone')
     elif page_name == 'os_darwin':
         return operating_system.isMac()
     elif page_name == 'os_linux':
         return operating_system.isGTK()
     else:
         return True
Example #21
0
 def checkXFCE4(self):
     if operating_system.isGTK():
         mon = application.Application().sessionMonitor
         if mon is not None and \
                 self.settings.getboolean('feature', 'usesm2') and \
                 self.settings.getboolean('feature', 'showsmwarning') and \
                 mon.vendor == 'xfce4-session':
             dlg = XFCE4WarningDialog(self, self.settings)
             dlg.Show()
 def checkXFCE4(self):
     if operating_system.isGTK():
         mon = application.Application().sessionMonitor
         if mon is not None and \
                 self.settings.getboolean('feature', 'usesm2') and \
                 self.settings.getboolean('feature', 'showsmwarning') and \
                 mon.vendor == 'xfce4-session':
             dlg = XFCE4WarningDialog(self, self.settings)
             dlg.Show()
Example #23
0
 def __isFuse(self, path):
     if operating_system.isGTK() and os.path.exists('/proc/mounts'):
         for line in file('/proc/mounts', 'rb'):
             try:
                 location, mountPoint, fsType, options, a, b = line.strip().split()
             except:
                 pass
             if os.path.abspath(path).startswith(mountPoint) and fsType.startswith('fuse.'):
                 return True
     return False
 def _setLocale(self, language):
     ''' Try to set the locale, trying possibly multiple localeStrings. '''
     if not operating_system.isGTK():
         locale.setlocale(locale.LC_ALL, '')
     # Set the wxPython locale:
     for localeString in self._localeStrings(language):
         languageInfo = wx.Locale.FindLanguageInfo(localeString)
         if languageInfo:
             self.__locale = wx.Locale(languageInfo.Language) # pylint: disable=W0201
             # Add the wxWidgets message catalog. This is really only for 
             # py2exe'ified versions, but it doesn't seem to hurt on other
             # platforms...
             localeDir = os.path.join(wx.StandardPaths_Get().GetResourcesDir(), 'locale')
             self.__locale.AddCatalogLookupPathPrefix(localeDir)
             self.__locale.AddCatalog('wxstd')
             break
     if operating_system.isGTK():
         locale.setlocale(locale.LC_ALL, '')
     self._fixBrokenLocales()
Example #25
0
 def _setLocale(self, language):
     ''' Try to set the locale, trying possibly multiple localeStrings. '''
     if not operating_system.isGTK():
         locale.setlocale(locale.LC_ALL, '')
     # Set the wxPython locale:
     for localeString in self._localeStrings(language):
         languageInfo = wx.Locale.FindLanguageInfo(localeString)
         if languageInfo:
             self.__locale = wx.Locale(languageInfo.Language)  # pylint: disable=W0201
             # Add the wxWidgets message catalog. This is really only for
             # py2exe'ified versions, but it doesn't seem to hurt on other
             # platforms...
             localeDir = os.path.join(
                 wx.StandardPaths_Get().GetResourcesDir(), 'locale')
             self.__locale.AddCatalogLookupPathPrefix(localeDir)
             self.__locale.AddCatalog('wxstd')
             break
     if operating_system.isGTK():
         locale.setlocale(locale.LC_ALL, '')
     self._fixBrokenLocales()
Example #26
0
 def __isFuse(self, path):
     if operating_system.isGTK() and os.path.exists('/proc/mounts'):
         for line in file('/proc/mounts', 'rb'):
             try:
                 location, mountPoint, fsType, options, a, b = line.strip(
                 ).split()
             except:
                 pass
             if os.path.abspath(path).startswith(
                     mountPoint) and fsType.startswith('fuse.'):
                 return True
     return False
    def getIconFromArtProvider(self, iconTitle, iconSize=None):
        size = iconSize or self.__iconSizeOnCurrentPlatform
        # I just spent two hours trying to get rid of garbage in the icon
        # background on KDE. I give up.
        if operating_system.isGTK():
            return wx.ArtProvider_GetIcon(iconTitle, wx.ART_FRAME_ICON, (size, size))

        # wx.ArtProvider_GetIcon doesn't convert alpha to mask, so we do it
        # ourselves:
        bitmap = wx.ArtProvider_GetBitmap(iconTitle, wx.ART_FRAME_ICON, 
                                          (size, size))    
        bitmap = ArtProvider.convertAlphaToMask(bitmap)
        return wx.IconFromBitmap(bitmap)
Example #28
0
 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()
Example #29
0
    def getIconFromArtProvider(self, iconTitle, iconSize=None):
        size = iconSize or self.__iconSizeOnCurrentPlatform
        # I just spent two hours trying to get rid of garbage in the icon
        # background on KDE. I give up.
        if operating_system.isGTK():
            return wx.ArtProvider_GetIcon(iconTitle, wx.ART_FRAME_ICON,
                                          (size, size))

        # wx.ArtProvider_GetIcon doesn't convert alpha to mask, so we do it
        # ourselves:
        bitmap = wx.ArtProvider_GetBitmap(iconTitle, wx.ART_FRAME_ICON,
                                          (size, size))
        bitmap = ArtProvider.convertAlphaToMask(bitmap)
        return wx.IconFromBitmap(bitmap)
Example #30
0
 def __init__(self, *args, **kwargs):
     super(FeaturesPage, self).__init__(columns=3, growableColumn=-1, 
                                        *args, **kwargs)
     self.addEntry(_('All settings on this tab require a restart of %s ' \
                     'to take effect') % meta.name)
     try:
         import taskcoachlib.syncml.core  # pylint: disable=W0404,W0612
     except ImportError:
         pass
     else:
         self.addBooleanSetting('feature', 'syncml', _('Enable SyncML'))
     self.addBooleanSetting('feature', 'iphone', 
                            _('Enable iPhone synchronization'))
     if operating_system.isGTK():
         self.addBooleanSetting('feature', 'usesm2', 
                                _('Use X11 session management'))
     self.addChoiceSetting('view', 'weekstart', _('Start of work week'), ' ',
                           [('monday', _('Monday')), 
                            ('sunday', _('Sunday'))])
     self.addTimeSetting('view', 'efforthourstart',
         _('Hour of start of work day'), helpText=' ')
     self.addTimeSetting('view', 'efforthourend',
         _('Hour of end of work day'), helpText=' ', disabledMessage=_('End of day'),
         disabledValue=24, defaultValue=23)
     self.addBooleanSetting('calendarviewer', 'gradient',
         _('Use gradients in calendar views.\n'
           'This may slow down Task Coach.'))
     self.addChoiceSetting('view', 'effortminuteinterval',
         _('Minutes between suggested times'), 
         _('In popup-menus for time selection (e.g. for setting the start \n'
           'time of an effort) %(name)s will suggest times using this \n'
           'setting. The smaller the number of minutes, the more times \n'
           'are suggested. Of course, you can also enter any time you \n'
           'want beside the suggested times.') % meta.data.metaDict,
         [(minutes, minutes) for minutes in ('5', '6', '10', '15', '20', 
                                             '30')],
         flags=(None, wx.ALL | wx.ALIGN_CENTER_VERTICAL,
                wx.ALL | wx.ALIGN_CENTER_VERTICAL))
     self.addIntegerSetting('feature', 'minidletime', _('Idle time notice'),
         helpText=_('If there is no user input for this amount of time\n'
                    '(in minutes), %(name)s will ask what to do about current '
                    'efforts.') % meta.data.metaDict)
     self.addBooleanSetting('feature', 'decimaltime',
         _('Use decimal times for effort entries.'),
         _('Display one hour, fifteen minutes as 1.25 instead of 1:15\n'
             'This is useful when creating invoices.'))
     self.addBooleanSetting('view', 'descriptionpopups',
         _('Show a popup with the description of an item\n'
           'when hovering over it'))
     self.fit()
Example #31
0
 def __init__(self,
              mainwindow,
              taskList,
              settings,
              defaultBitmap='taskcoach',
              tickBitmap='clock_icon',
              tackBitmap='clock_stopwatch_icon',
              *args,
              **kwargs):
     super(TaskBarIcon, self).__init__(*args, **kwargs)
     self.__window = mainwindow
     self.__taskList = taskList
     self.__settings = settings
     self.__bitmap = self.__defaultBitmap = defaultBitmap
     self.__tooltipText = ''
     self.__tickBitmap = tickBitmap
     self.__tackBitmap = tackBitmap
     self.registerObserver(self.onTaskListChanged,
                           eventType=taskList.addItemEventType(),
                           eventSource=taskList)
     self.registerObserver(self.onTaskListChanged,
                           eventType=taskList.removeItemEventType(),
                           eventSource=taskList)
     pub.subscribe(self.onTrackingChanged,
                   task.Task.trackingChangedEventType())
     pub.subscribe(self.onChangeDueDateTime,
                   task.Task.dueDateTimeChangedEventType())
     # When the user chances the due soon hours preferences it may cause
     # a task to change appearance. That also means the number of due soon
     # tasks has changed, so we need to change the tool tip text.
     # Note that directly subscribing to the setting (behavior.duesoonhours)
     # is not reliable. The TaskBarIcon may get the event before the tasks
     # do. When that happens the tasks haven't changed their status yet and
     # we would use the wrong status count.
     self.registerObserver(self.onChangeDueDateTime_Deprecated,
                           eventType=task.Task.appearanceChangedEventType())
     if operating_system.isGTK():
         events = [wx.EVT_TASKBAR_LEFT_DOWN]
     elif operating_system.isWindows():
         # See http://msdn.microsoft.com/en-us/library/windows/desktop/aa511448.aspx#interaction
         events = [wx.EVT_TASKBAR_LEFT_DOWN, wx.EVT_TASKBAR_LEFT_DCLICK]
     else:
         events = [wx.EVT_TASKBAR_LEFT_DCLICK]
     for event in events:
         self.Bind(event, self.onTaskbarClick)
     self.__setTooltipText()
     self.__setIcon()
Example #32
0
    def __init__(self, options=None, args=None, **kwargs):
        self._options = options
        self._args = args
        self.initTwisted()
        self.__wx_app = wxApp(self.on_end_session,
                              self.on_reopen_app,
                              redirect=False)
        self.registerApp()
        self.init(**kwargs)

        if operating_system.isGTK():
            if self.settings.getboolean('feature', 'usesm2'):
                from taskcoachlib.powermgt import xsm

                class LinuxSessionMonitor(xsm.SessionMonitor):
                    def __init__(self, callback):
                        super(LinuxSessionMonitor, self).__init__()
                        self._callback = callback
                        self.setProperty(xsm.SmCloneCommand, sys.argv)
                        self.setProperty(xsm.SmRestartCommand, sys.argv)
                        self.setProperty(xsm.SmCurrentDirectory, os.getcwd())
                        self.setProperty(xsm.SmProgram, sys.argv[0])
                        self.setProperty(xsm.SmRestartStyleHint,
                                         xsm.SmRestartNever)

                    def saveYourself(self, saveType, shutdown, interactStyle,
                                     fast):  # pylint: disable=W0613
                        if shutdown:
                            wx.CallAfter(self._callback)
                        self.saveYourselfDone(True)

                    def die(self):
                        pass

                    def saveComplete(self):
                        pass

                    def shutdownCancelled(self):
                        pass

                self.sessionMonitor = LinuxSessionMonitor(self.on_end_session)  # pylint: disable=W0201
            else:
                self.sessionMonitor = None

        calendar.setfirstweekday(
            dict(monday=0, sunday=6)[self.settings.get('view', 'weekstart')])
 def __init__(self, window, settings):
     super(WindowDimensionsTracker, self).__init__(window, settings, 
                                                   'window')
     self.__settings = settings
     if self.__start_iconized():
         if operating_system.isMac() or operating_system.isGTK():
             # Need to show the window on Mac OS X first, otherwise it   
             # won't be properly minimized. On wxGTK we need to show the
             # window first, otherwise clicking the task bar icon won't
             # show it.
             self._window.Show()
         self._window.Iconize(True)
         if not operating_system.isMac() and \
             self.get_setting('hidewheniconized'):
             # Seems like hiding the window after it's been
             # iconized actually closes it on Mac OS...
             wx.CallAfter(self._window.Hide)                
Example #34
0
 def __init__(self, window, settings):
     super(WindowDimensionsTracker, self).__init__(window, settings,
                                                   'window')
     self.__settings = settings
     if self.__start_iconized():
         if operating_system.isMac() or operating_system.isGTK():
             # Need to show the window on Mac OS X first, otherwise it
             # won't be properly minimized. On wxGTK we need to show the
             # window first, otherwise clicking the task bar icon won't
             # show it.
             self._window.Show()
         self._window.Iconize(True)
         if not operating_system.isMac() and \
             self.get_setting('hidewheniconized'):
             # Seems like hiding the window after it's been
             # iconized actually closes it on Mac OS...
             wx.CallAfter(self._window.Hide)
Example #35
0
 def pathToConfigDir(self, environ):
     try:
         if operating_system.isGTK():
             from taskcoachlib.thirdparty.xdg import BaseDirectory
             path = BaseDirectory.save_config_path(meta.name)
         elif operating_system.isMac():
             import Carbon.Folder, Carbon.Folders, Carbon.File
             pathRef = Carbon.Folder.FSFindFolder(Carbon.Folders.kUserDomain, Carbon.Folders.kPreferencesFolderType, True)
             path = Carbon.File.pathname(pathRef)
             # XXXFIXME: should we release pathRef ? Doesn't seem so since I get a SIGSEGV if I try.
         elif operating_system.isWindows():
             from win32com.shell import shell, shellcon
             path = os.path.join(shell.SHGetSpecialFolderPath(None, shellcon.CSIDL_APPDATA, True), meta.name)
         else:
             path = self.pathToConfigDir_deprecated(environ=environ)
     except: # Fallback to old dir
         path = self.pathToConfigDir_deprecated(environ=environ)
     return path
Example #36
0
    def __init__(self, options=None, args=None, **kwargs):
        self._options = options
        self._args = args
        self.initTwisted()
        self.__wx_app = wxApp(self.on_end_session, self.on_reopen_app, redirect=False)
        self.registerApp()
        self.init(**kwargs)

        if operating_system.isGTK():
            if self.settings.getboolean('feature', 'usesm2'):
                from taskcoachlib.powermgt import xsm
                
                class LinuxSessionMonitor(xsm.SessionMonitor):
                    def __init__(self, callback):
                        super(LinuxSessionMonitor, self).__init__()
                        self._callback = callback
                        self.setProperty(xsm.SmCloneCommand, sys.argv)
                        self.setProperty(xsm.SmRestartCommand, sys.argv)
                        self.setProperty(xsm.SmCurrentDirectory, os.getcwd())
                        self.setProperty(xsm.SmProgram, sys.argv[0])
                        self.setProperty(xsm.SmRestartStyleHint, 
                                         xsm.SmRestartNever)
                        
                    def saveYourself(self, saveType, shutdown, interactStyle, 
                                     fast):  # pylint: disable=W0613
                        if shutdown:
                            wx.CallAfter(self._callback)
                        self.saveYourselfDone(True)
                        
                    def die(self):
                        pass
                    
                    def saveComplete(self):
                        pass
                    
                    def shutdownCancelled(self):
                        pass
                    
                self.sessionMonitor = LinuxSessionMonitor(self.on_end_session)  # pylint: disable=W0201
            else:
                self.sessionMonitor = None

        calendar.setfirstweekday(dict(monday=0, sunday=6)[self.settings.get('view', 'weekstart')])
Example #37
0
    def _pathToDataDir(self, *args, **kwargs):
        forceGlobal = kwargs.pop('forceGlobal', False)
        if operating_system.isGTK():
            from taskcoachlib.thirdparty.xdg import BaseDirectory
            path = BaseDirectory.save_data_path(meta.name)
        elif operating_system.isMac():
            import Carbon.Folder, Carbon.Folders, Carbon.File
            pathRef = Carbon.Folder.FSFindFolder(
                Carbon.Folders.kUserDomain,
                Carbon.Folders.kApplicationSupportFolderType, True)
            path = Carbon.File.pathname(pathRef)
            # XXXFIXME: should we release pathRef ? Doesn't seem so since I get a SIGSEGV if I try.
            path = os.path.join(path, meta.name)
        elif operating_system.isWindows():
            if self.__iniFileSpecifiedOnCommandLine and not forceGlobal:
                path = self.pathToIniFileSpecifiedOnCommandLine()
            else:
                from win32com.shell import shell, shellcon
                path = os.path.join(
                    shell.SHGetSpecialFolderPath(None, shellcon.CSIDL_APPDATA,
                                                 True), meta.name)

        else:  # Errr...
            path = self.path()

        if operating_system.isWindows():
            # Follow shortcuts.
            from win32com.client import Dispatch
            shell = Dispatch('WScript.Shell')
            for component in args:
                path = os.path.join(path, component)
                if os.path.exists(path + '.lnk'):
                    shortcut = shell.CreateShortcut(path + '.lnk')
                    path = shortcut.TargetPath
        else:
            path = os.path.join(path, *args)

        exists = os.path.exists(path)
        if not exists:
            os.makedirs(path)
        return path, exists
Example #38
0
 def __init__(self, mainwindow, taskList, settings,
         defaultBitmap='taskcoach', tickBitmap='clock_icon',
         tackBitmap='clock_stopwatch_icon', *args, **kwargs):
     super(TaskBarIcon, self).__init__(*args, **kwargs)
     self.__window = mainwindow
     self.__taskList = taskList
     self.__settings = settings
     self.__bitmap = self.__defaultBitmap = defaultBitmap
     self.__currentBitmap = self.__bitmap
     self.__tooltipText = ''
     self.__currentText = self.__tooltipText
     self.__tickBitmap = tickBitmap
     self.__tackBitmap = tackBitmap
     self.registerObserver(self.onTaskListChanged,
         eventType=taskList.addItemEventType(), eventSource=taskList)
     self.registerObserver(self.onTaskListChanged,
         eventType=taskList.removeItemEventType(), eventSource=taskList)
     pub.subscribe(self.onTrackingChanged,
                   task.Task.trackingChangedEventType())
     pub.subscribe(self.onChangeDueDateTime,
                   task.Task.dueDateTimeChangedEventType())
     # When the user chances the due soon hours preferences it may cause
     # a task to change appearance. That also means the number of due soon
     # tasks has changed, so we need to change the tool tip text.
     # Note that directly subscribing to the setting (behavior.duesoonhours)
     # is not reliable. The TaskBarIcon may get the event before the tasks
     # do. When that happens the tasks haven't changed their status yet and
     # we would use the wrong status count.
     self.registerObserver(self.onChangeDueDateTime_Deprecated,
         eventType=task.Task.appearanceChangedEventType())
     if operating_system.isGTK():
         events = [wx.EVT_TASKBAR_LEFT_DOWN]
     elif operating_system.isWindows():
         # See http://msdn.microsoft.com/en-us/library/windows/desktop/aa511448.aspx#interaction
         events = [wx.EVT_TASKBAR_LEFT_DOWN, wx.EVT_TASKBAR_LEFT_DCLICK]
     else:
         events = [wx.EVT_TASKBAR_LEFT_DCLICK]
     for event in events:
         self.Bind(event, self.onTaskbarClick)
     self.__setTooltipText()
     mainwindow.Bind(wx.EVT_IDLE, self.onIdle)
Example #39
0
    def __init__(self,
                 parent,
                 title,
                 bitmap='edit',
                 direction=None,
                 *args,
                 **kwargs):
        self._buttonTypes = kwargs.get('buttonTypes', wx.OK | wx.CANCEL)
        super(Dialog,
              self).__init__(parent,
                             -1,
                             title,
                             style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER
                             | wx.MAXIMIZE_BOX | wx.MINIMIZE_BOX)
        self.SetIcon(
            wx.ArtProvider_GetIcon(bitmap, wx.ART_FRAME_ICON, (16, 16)))

        if operating_system.isWindows7_OrNewer():
            # Without this the window has no taskbar icon on Windows, and the focus comes back to the main
            # window instead of this one when returning to Task Coach through Alt+Tab. Which is probably not
            # what we want.
            import win32gui, win32con
            exStyle = win32gui.GetWindowLong(self.GetHandle(),
                                             win32con.GWL_EXSTYLE)
            win32gui.SetWindowLong(self.GetHandle(), win32con.GWL_EXSTYLE,
                                   exStyle | win32con.WS_EX_APPWINDOW)

        self._panel = self.GetContentsPane()
        self._panel.SetSizerType('vertical')
        self._panel.SetSizerProps(expand=True, proportion=1)
        self._direction = direction
        self._interior = self.createInterior()
        self._interior.SetSizerProps(expand=True, proportion=1)
        self.fillInterior()
        self._buttons = self.createButtons()
        self._panel.Fit()
        self.Fit()
        self.CentreOnParent()
        if not operating_system.isGTK():
            wx.CallAfter(self.Raise)
        wx.CallAfter(self._panel.SetFocus)
    def tearDown(self):
        super(TaskViewerTestCase, self).tearDown()
        if not operating_system.isGTK():
            locale.setlocale(locale.LC_ALL, self.originalLocale)
        attachment.Attachment.attdir = None
        self.taskFile.close()
        self.taskFile.stop()

        for name in os.listdir('.'):
            if os.path.isdir(name) and name.endswith('_attachments'):
                os.rmdir(name)  # pragma: no cover
        if os.path.isfile('test.mail'):
            os.remove('test.mail')

        if self.viewer:
            self.viewer.detach()
            self.viewer = None

        if self.parentFrame:
            self.parentFrame.Close()
            wx.Yield()
Example #41
0
    def tearDown(self):
        super(TaskViewerTestCase, self).tearDown()
        if not operating_system.isGTK():
            locale.setlocale(locale.LC_ALL, self.originalLocale)
        attachment.Attachment.attdir = None
        self.taskFile.close()
        self.taskFile.stop()

        for name in os.listdir('.'):
            if os.path.isdir(name) and name.endswith('_attachments'):
                os.rmdir(name)  # pragma: no cover
        if os.path.isfile('test.mail'):
            os.remove('test.mail')

        if self.viewer:
            self.viewer.detach()
            self.viewer = None

        if self.parentFrame:
            self.parentFrame.Close()
            wx.Yield()
Example #42
0
 def setUp(self):
     super(TaskViewerTestCase, self).setUp()
     task.Task.settings = self.settings = config.Settings(load=False)
     self.task = task.Task(subject='task', plannedStartDateTime=date.Now())
     self.child = task.Task(subject='child', plannedStartDateTime=date.Now())
     self.child.setParent(self.task)
     self.taskFile = persistence.TaskFile()
     self.taskList = self.taskFile.tasks()
     self.parentFrame = wx.Frame(self.frame, wx.ID_ANY, '')
     self.viewer = TaskViewerUnderTest(self.parentFrame, self.taskFile, 
                                       self.settings)
     self.viewer.sortBy('subject')
     self.viewer.setSortOrderAscending()
     self.viewer.setSortByTaskStatusFirst(True)
     self.settings.setboolean(self.viewer.settingsSection(), 'treemode', 
                              self.treeMode)
     self.newColor = (100, 200, 100, 255)
     attachment.Attachment.attdir = os.getcwd()
     if not operating_system.isGTK():
         self.originalLocale = locale.getlocale(locale.LC_ALL)
         tmpLocale = os.environ['LC_ALL'] if 'LC_ALL' in os.environ else ('en_US' if operating_system.isMac() else '')
         locale.setlocale(locale.LC_ALL, tmpLocale)
 def setUp(self):
     super(TaskViewerTestCase, self).setUp()
     task.Task.settings = self.settings = config.Settings(load=False)
     self.task = task.Task(subject='task', plannedStartDateTime=date.Now())
     self.child = task.Task(subject='child', plannedStartDateTime=date.Now())
     self.child.setParent(self.task)
     self.taskFile = persistence.TaskFile()
     self.taskList = self.taskFile.tasks()
     self.parentFrame = wx.Frame(self.frame, wx.ID_ANY, '')
     self.viewer = TaskViewerUnderTest(self.parentFrame, self.taskFile, 
                                       self.settings)
     self.viewer.sortBy('subject')
     self.viewer.setSortOrderAscending()
     self.viewer.setSortByTaskStatusFirst(True)
     self.settings.setboolean(self.viewer.settingsSection(), 'treemode', 
                              self.treeMode)
     self.newColor = (100, 200, 100, 255)
     attachment.Attachment.attdir = os.getcwd()
     if not operating_system.isGTK():
         self.originalLocale = locale.getlocale(locale.LC_ALL)
         tmpLocale = os.environ['LC_ALL'] if 'LC_ALL' in os.environ else ('en_US' if operating_system.isMac() else '')
         locale.setlocale(locale.LC_ALL, tmpLocale)
    def _pathToDataDir(self, *args, **kwargs):
        forceGlobal = kwargs.pop('forceGlobal', False)
        if operating_system.isGTK():
            from taskcoachlib.thirdparty.xdg import BaseDirectory
            path = BaseDirectory.save_data_path(meta.name)
        elif operating_system.isMac():
            import Carbon.Folder, Carbon.Folders, Carbon.File
            pathRef = Carbon.Folder.FSFindFolder(Carbon.Folders.kUserDomain, Carbon.Folders.kApplicationSupportFolderType, True)
            path = Carbon.File.pathname(pathRef)
            # XXXFIXME: should we release pathRef ? Doesn't seem so since I get a SIGSEGV if I try.
            path = os.path.join(path, meta.name)
        elif operating_system.isWindows():
            if self.__iniFileSpecifiedOnCommandLine and not forceGlobal:
                path = self.pathToIniFileSpecifiedOnCommandLine()
            else:
                from win32com.shell import shell, shellcon
                path = os.path.join(shell.SHGetSpecialFolderPath(None, shellcon.CSIDL_APPDATA, True), meta.name)

        else: # Errr...
            path = self.path()

        if operating_system.isWindows():
            # Follow shortcuts.
            from win32com.client import Dispatch
            shell = Dispatch('WScript.Shell')
            for component in args:
                path = os.path.join(path, component)
                if os.path.exists(path + '.lnk'):
                    shortcut = shell.CreateShortcut(path + '.lnk')
                    path = shortcut.TargetPath
        else:
            path = os.path.join(path, *args)

        exists = os.path.exists(path)
        if not exists:
            os.makedirs(path)
        return path, exists
Example #45
0
 def __init__(self, *args, **kwargs):
     super(FeaturesPage, self).__init__(columns=3,
                                        growableColumn=-1,
                                        *args,
                                        **kwargs)
     self.addEntry(_('All settings on this tab require a restart of %s ' \
                     'to take effect') % meta.name)
     self.addBooleanSetting('feature', 'effort',
                            _('Allow for tracking effort'))
     self.addBooleanSetting('feature', 'notes', _('Allow for taking notes'))
     try:
         import taskcoachlib.syncml.core  # pylint: disable=W0404,W0612
     except ImportError:
         pass
     else:
         self.addBooleanSetting('feature', 'syncml', _('Enable SyncML'))
     self.addBooleanSetting('feature', 'iphone',
                            _('Enable iPhone synchronization'))
     if operating_system.isGTK():
         self.addBooleanSetting('feature', 'usesm2',
                                _('Use X11 session management'))
     self.addChoiceSetting('view', 'weekstart', _('Start of work week'),
                           ' ', [('monday', _('Monday')),
                                 ('sunday', _('Sunday'))])
     self.addTimeSetting('view',
                         'efforthourstart',
                         _('Hour of start of work day'),
                         helpText=' ')
     self.addTimeSetting('view',
                         'efforthourend',
                         _('Hour of end of work day'),
                         helpText=' ',
                         disabledMessage=_('End of day'),
                         disabledValue=24,
                         defaultValue=23)
     self.addBooleanSetting(
         'calendarviewer', 'gradient',
         _('Use gradients in calendar views.\n'
           'This may slow down Task Coach.'))
     self.addChoiceSetting(
         'view',
         'effortminuteinterval',
         _('Minutes between suggested times'),
         _('In popup-menus for time selection (e.g. for setting the start \n'
           'time of an effort) %(name)s will suggest times using this \n'
           'setting. The smaller the number of minutes, the more times \n'
           'are suggested. Of course, you can also enter any time you \n'
           'want beside the suggested times.') % meta.data.metaDict,
         [(minutes, minutes)
          for minutes in ('5', '6', '10', '15', '20', '30')],
         flags=(None, wx.ALL | wx.ALIGN_CENTER_VERTICAL,
                wx.ALL | wx.ALIGN_CENTER_VERTICAL))
     self.addIntegerSetting(
         'feature',
         'minidletime',
         _('Idle time notice'),
         helpText=_(
             'If there is no user input for this amount of time\n'
             '(in minutes), %(name)s will ask what to do about current '
             'efforts.') % meta.data.metaDict)
     self.fit()
Example #46
0
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

import sys, threading, time
from taskcoachlib import operating_system
from ctypes import *

#==============================================================================
# Linux/BSD

if operating_system.isGTK():

    class XScreenSaverInfo(Structure):
        _fields_ = [('window', c_ulong), ('state', c_int), ('kind', c_int),
                    ('til_or_since', c_ulong), ('idle', c_ulong),
                    ('event_mask', c_ulong)]

    class LinuxIdleQuery(object):
        def __init__(self):
            _x11 = CDLL('libX11.so.6')

            self.XOpenDisplay = CFUNCTYPE(c_ulong,
                                          c_char_p)(('XOpenDisplay', _x11))
            self.XCloseDisplay = CFUNCTYPE(c_int,
                                           c_ulong)(('XCloseDisplay', _x11))
            self.XRootWindow = CFUNCTYPE(c_ulong, c_ulong,
Example #47
0
 def AppendText(self, *args, **kwargs):
     super(BaseTextCtrl, self).AppendText(*args, **kwargs)
     if operating_system.isGTK() or operating_system.isMac():
         self.__initial_value = self.GetValue()
Example #48
0
 def setUp(self):
     super(MainWindowIconizedTest, self).setUp()
     if operating_system.isGTK():
         wx.SafeYield()  # pragma: no cover
        if self.__step == 10:
            self.Stop()

    def __OnClose(self, event):
        self.Stop()
        event.Skip()


#==============================================================================
# Notifications

if operating_system.isWindows():
    class _NotifyBase(wx.MiniFrame):
        pass
elif operating_system.isGTK():
    class _NotifyBase(wx.PopupWindow):
        def __init__(self, parent, id_, title, style=0): # pylint: disable=W0613,E1003
            super(_NotifyBase, self).__init__(parent, id_) # No style

        def Close(self): # pylint: disable=W0221,E1003
            # Strange...
            super(_NotifyBase, self).Close()
            self.Destroy()
else:
    class _NotifyBase(wx.Frame):
        """FIXME: steals focus..."""


class NotificationFrameBase(_NotifyBase):
    """
Example #50
0
 def setDescription(self, newDescription):
     page = super(TaskEditorBySettingFocusMixin, self).setDescription(newDescription)
     if operating_system.isGTK(): 
         page._descriptionSync.onAttributeEdited(dummy.Event())  # pragma: no cover
     else:
         page._subjectEntry.SetFocus()  # pragma: no cover
Example #51
0
 def __init__(self, *args, **kwargs):
     super(HyperTreeList, self).__init__(*args, **kwargs)
     if operating_system.isGTK():
         self.Bind(wx.EVT_TREE_ITEM_COLLAPSED, self.__on_item_collapsed)
Example #52
0
 def __shiftDown(self, event):
     if operating_system.isGTK():
         return ord('A') <= event.GetKeyCode() <= ord('Z')
     return event.ShiftDown()
 def setUp(self):
     super(MainWindowIconizedTest, self).setUp()        
     if operating_system.isGTK():
         wx.SafeYield() # pragma: no cover
Example #54
0
 def __shiftDown(self, event):
     if operating_system.isGTK():
         return ord('A') <= event.GetKeyCode() <= ord('Z')
     return event.ShiftDown()