Example #1
0
    def __init__(self, keyboard_type):
        gobject.GObject.__init__(self)
        settings = AntlerSettings()
        self.set_show_tabs(False)

        use_system = settings.use_system
        use_system.connect("value-changed", self._on_use_system_theme_changed)

        self._app_css_provider = Gtk.CssProvider()
        self._load_style(
            self._app_css_provider, "style.css",
            [glib.get_user_data_dir()] + list(glib.get_system_data_dirs()))

        if not use_system.value:
            Gtk.StyleContext.add_provider_for_screen(
                Gdk.Screen.get_default(), self._app_css_provider,
                Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

        self._user_css_provider = Gtk.CssProvider()
        self._load_style(self._user_css_provider, "user-style.css",
                         [glib.get_user_data_dir()])
        Gtk.StyleContext.add_provider_for_screen(
                Gdk.Screen.get_default(), self._user_css_provider,
                Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION + 1)

        self.scanner = Caribou.Scanner()
        self.set_keyboard_model(keyboard_type)
Example #2
0
    def __init__ (self, textdomain):
        gtk.gdk.threads_init ()

        self.Dead = False
        self.ActiveProfile = None

        # Figure out our installation paths
        self.DATADIR = os.path.join (os.path.dirname (os.path.abspath (
            sys.argv [0])), "share").decode (FNENC)
        if not os.path.exists (self.DATADIR):
            self.DATADIR = os.path.join (os.path.normpath (sys.prefix),
                "share/xpd").decode (FNENC)
            if not os.path.exists (self.DATADIR):
                self.DATADIR = os.path.join (os.path.normpath (os.path.join (
                    os.path.dirname (os.path.abspath (sys.argv [0])), "..")),
                    "share/xpd").decode (FNENC)

        if not os.path.exists (self.DATADIR):
            raise SystemExit, _("FATAL: Could not find data directory")

        self.CONFIGDIR = os.path.join (glib.get_user_data_dir ().decode (FNENC), "xpd")
        if not os.access (self.CONFIGDIR, os.F_OK):
            os.makedirs (self.CONFIGDIR, 0700)

        # Load the widgets from the GtkBuilder file
        self.builder = gtk.Builder ()
        self.builder.set_translation_domain (textdomain);
        try:
            self.builder.add_from_file (self.DATADIR + "/gui.xml")
        except RuntimeError, e:
            raise SystemExit (str (e))
Example #3
0
    def __init__(self, idle_callback=None):
        super(Player, self).__init__()
        
        self._tag_scanner = TagScanner(self._on_tag_scanned)
        self._tags = {}
        
        data_dir = os.path.join(glib.get_user_data_dir(), 'myplay')
        if not os.path.exists(data_dir):
            os.makedirs(data_dir)
        
        self._playlist_path = os.path.join(data_dir, 'playlist')

        self._init_playlist()
        if self._playlist:
            self._tag_scanner.add(self._playlist)
        
        self._player = gst.element_factory_make('playbin2', 'player')
        self._player.set_property('flags', GST_PLAY_FLAG_AUDIO)
        player_bus = self._player.get_bus()
        player_bus.add_signal_watch()
        player_bus.connect('message', self._on_player_message)

        self._state = STATE_READY
        self._idle_callback = idle_callback
        self.idle = True
Example #4
0
def create_lockfile():
    """Create lockfile handler

    # Test mocks
    >>> from mock import Mock
    >>> atexit.register = Mock()
    >>> glib.get_user_data_dir = Mock(return_value="test/xdg_data_home")

    # Make sure there isn't a stale lock from a previous run
    >>> if os.path.exists("%s/bleeter/lock" % glib.get_user_data_dir()):
    ...     os.unlink("%s/bleeter/lock" % glib.get_user_data_dir())

    >>> create_lockfile()
    >>> os.path.exists("%s/bleeter/lock" % glib.get_user_data_dir())
    True
    >>> try:
    ...     create_lockfile()
    ... except IOError:
    ...     pass
    Another instance is running or `test/xdg_data_home/bleeter/lock' is stale
    >>> os.unlink("%s/bleeter/lock" % glib.get_user_data_dir())

    """
    lock_file = "%s/bleeter/lock" % glib.get_user_data_dir()

    # Create directory for state storage
    mkdir(os.path.dirname(lock_file))
    if os.path.exists(lock_file):
        message = "Another instance is running or `%s' is stale" \
            % lock_file
        usage_note(message)
        raise IOError(message)
    open(lock_file, "w").write(str(os.getpid()))
    atexit.register(os.unlink, lock_file)
Example #5
0
 def __init__(self):
     # Command line args
     args = sys.argv[1:]
     testmode = True if "--test" in args else False
     root = os.path.dirname(__path__[0]) if testmode else sys.prefix
     debugmode = True if "--debug" in args else False
     __builtins__['log'] = logm.log_main if debugmode else logm.log_null
     # Directories and localization
     self.locale = locale.getlocale()
     maindir = os.path.join(root, 'share', 'euphorbia')
     datadir = os.path.join(glib.get_user_data_dir(), 'euphorbia')
     confdir = os.path.join(glib.get_user_config_dir(), 'euphorbia')
     cfgfile = os.path.join(confdir, 'euphorbia.cfg')
     locales = os.path.join(root, 'share', 'locale')
     gettext.install('euphorbia', locales)
     # Preferences
     self.prefm = prefs.PrefsManager(cfgfile, testmode)
     self.prefm.set_pref('system_maindir', maindir)
     self.prefm.set_pref('system_datadir', datadir)
     self.prefm.set_pref('system_confdir', confdir)
     # Load application
     self.plugm = exts.PluginsManager(self)
     self.gui = ui.EuphorbiaGUI(self)
     self._load_plugins()
     self.prefm.autoconnect_gtk(self.gui.win)
     # Open files given in command line
     args = [a for a in args if not a.startswith("--")]
     projfile = self.prefm.get_pref('files_lastprj')
     if len(args) > 0:
         for f in args:
             self.gui.do_open(f, 'all')
     elif self.prefm.get_pref('files_reopenprj') and projfile is not None:
         self.gui.do_open(projfile, 'project')
     else:
         self.gui.act_new()
Example #6
0
    def __init__ (self):
        self.Dead = False

        # Figure out our installation paths
        self.DATADIR = os.path.join (os.path.dirname (os.path.abspath (
            sys.argv [0])), "share").decode (FNENC)
        if not os.path.exists (self.DATADIR):
            self.DATADIR = os.path.join (os.path.normpath (sys.prefix),
                "share/xpd").decode (FNENC)
            if not os.path.exists (self.DATADIR):
                self.DATADIR = os.path.join (os.path.normpath (os.path.join (
                    os.path.dirname (os.path.abspath (sys.argv [0])), "..")),
                    "share/xpd").decode (FNENC)

        if not os.path.exists (self.DATADIR):
            raise SystemExit, _("FATAL: Could not find data directory")

        self.CONFIGDIR = os.path.join (glib.get_user_data_dir ().decode (FNENC), "xpd")
        if not os.access (self.CONFIGDIR, os.F_OK):
            os.makedirs (self.CONFIGDIR, 0700)

        # Load the widgets from the Glade file
        try:
            self.glade = gtk.glade.XML(self.DATADIR + "/gui.glade")
        except RuntimeError, msg:
            raise SystemExit, msg
Example #7
0
    def __init__(self):
        self.Dead = False
        self.ActiveProfile = None

        # Figure out our installation paths
        self.DATADIR = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), "share").decode(FNENC)
        if not os.path.exists(self.DATADIR):
            self.DATADIR = os.path.join(os.path.normpath(sys.prefix), "share/xpd").decode(FNENC)
            if not os.path.exists(self.DATADIR):
                self.DATADIR = os.path.join(
                    os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), "..")), "share/xpd"
                ).decode(FNENC)

        if not os.path.exists(self.DATADIR):
            raise SystemExit, _("FATAL: Could not find data directory")

        self.CONFIGDIR = os.path.join(glib.get_user_data_dir(), "xpd").decode("utf-8")
        if not os.access(self.CONFIGDIR, os.F_OK):
            os.makedirs(self.CONFIGDIR, 0700)
# 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 os
import glib
import shutil

PROGRAM_NAME = "deepin-individuation"

homedir = os.path.expanduser("~")
lastdir = homedir

data_home = glib.get_user_data_dir()
data_home = os.path.join(data_home, PROGRAM_NAME)

config_home = glib.get_user_config_dir()
config_home = os.path.join(config_home, PROGRAM_NAME)

cache_home = glib.get_user_cache_dir()
cache_home = os.path.join(cache_home, PROGRAM_NAME)

data_dirs = os.getenv("XDG_DATA_DIRS")
if data_dirs == None:
    data_dirs = "/usr/local/share/:/usr/share/"

data_dirs = [os.path.join(d, PROGRAM_NAME) for d in data_dirs.split(":")]

config_dirs = os.getenv("XDG_CONFIG_DIRS")
Example #9
0
import os
import sys
import glib
import logging

APP_NAME = 'Gnotwify'
APP_SHORT_NAME = 'gnotwify'
SRV_NAME = 'twitter'

CONFIG_DIR = os.path.join(glib.get_user_config_dir(), APP_SHORT_NAME)
DATA_DIR = os.path.join(glib.get_user_data_dir(), APP_SHORT_NAME)
CACHE_DIR = os.path.join(glib.get_user_cache_dir(), APP_SHORT_NAME)
CURRENT_DIR = os.path.realpath(os.path.dirname(sys.argv[0]))

CONFIG_FILE = os.path.join(CONFIG_DIR, APP_SHORT_NAME + '.cfg')
LOG_FILENAME = os.path.join(CACHE_DIR, APP_SHORT_NAME + '.log')
LOG_LEVELS = {'debug': logging.DEBUG,
              'info': logging.INFO,
              'warning': logging.WARNING,
              'error': logging.ERROR,
              'critical': logging.CRITICAL}

logging.basicConfig(level=logging.INFO,
                    datefmt='%H:%M',
                    format='[%(asctime)s][%(levelname)s:%(name)s] %(message)s')

from libgnotwify.Message import Message
from libgnotwify.Gnotwify import Gnotwify, GnotwifyError

Example #10
0
def main(datapath, extradata, oldstyle_confpath=None, version=MYPAINT_VERSION):
    """Run MyPaint with `sys.argv`, called from the "mypaint" script.

    :param datapath: The app's read-only data location.
      Where MyPaint should find its static data, e.g. UI definition XML,
      backgrounds, and brush definitions. $PREFIX/share/mypaint is usual.
    :param extradata: Extra search root for finding icons.
      Where to find the defaults for MyPaint's themeable UI icons. This will be
      used in addition to $XDG_DATA_DIRS for the purposes of icon lookup.
      Normally it's $PREFIX/share, to support unusual installations outside the
      usual locations. It should contain an icons/ subdirectory.
    :param oldstyle_confpath: Old-style merged config folder.
      If specified, all user-specific data that MyPaint writes is written here.
      If omitted, this data will be stored under the basedirs returned by
      glib.get_user_config_dir() for settings, and by glib.get_user_data_dir()
      for brushes and backgrounds. On Windows, these will be the same location.
      On POSIX systems, $HOME/.config/mypaint and $HOME/.local/share/mypaint
      are a typical division.
    :param version: full version string for display in the about box.

    The oldstyle_confpath parameter can also be overridden by command-line
    parameters. To support legacy MyPaint configuration dirs, call with
    oldstyle_confpath set to the expansion of ~/.mypaint.

    """

    # Default logfile basename.
    # If it's relative, it's resolved relative to the user config path.
    default_logfile = None
    if sys.platform == 'win32':  # http://gna.org/bugs/?17999
        default_logfile = "mypaint_error.log"

    # Parse command line
    parser = OptionParser('usage: %prog [options] [FILE]')
    parser.add_option(
        '-c',
        '--config',
        metavar='DIR',
        default=oldstyle_confpath,
        help='use old-style merged config directory DIR, e.g. ~/.mypaint')
    parser.add_option(
        '-l',
        '--logfile',
        metavar='FILE',
        default=default_logfile,
        help='log console messages to FILE (rel. to config location)')
    parser.add_option('-t',
                      '--trace',
                      action="store_true",
                      help='print all executed Python statements')
    parser.add_option('-f',
                      '--fullscreen',
                      action="store_true",
                      help='start in fullscreen mode')
    parser.add_option("-V",
                      '--version',
                      action="store_true",
                      help='print version information and exit')
    options, args = parser.parse_args(sys.argv_unicode[1:])

    # XDG support for new users on POSIX platforms
    if options.config is None:
        encoding = 'utf-8'
        appsubdir = u"mypaint"
        basedir = glib.get_user_data_dir().decode(encoding)
        userdatapath = os.path.join(basedir, appsubdir)
        basedir = glib.get_user_config_dir().decode(encoding)
        userconfpath = os.path.join(basedir, appsubdir)
    else:
        userdatapath = options.config
        userconfpath = options.config

    # Log to the specified location
    # Prepend the data path if the user gave a relative location.
    if options.logfile:
        logfilepath = os.path.join(userdatapath, options.logfile)
        logdirpath, logfilebasename = os.path.split(logfilepath)
        if not os.path.isdir(logdirpath):
            os.makedirs(logdirpath)
        logger.info("Copying log messages to %r", logfilepath)
        logfile_fp = open(logfilepath, 'a', 1)
        logfile_handler = logging.StreamHandler(logfile_fp)
        logfile_format = "%(asctime)s;%(levelname)s;%(name)s;%(message)s"
        logfile_handler.setFormatter(logging.Formatter(logfile_format))
        root_logger = logging.getLogger(None)
        root_logger.addHandler(logfile_handler)
        # Classify this as a warning, since this is fairly evil.
        # Note: this hack doesn't catch every type of GTK3 error message.
        logger.warning("Redirecting stdout and stderr to %r", logfilepath)
        sys.stdout = sys.stderr = logfile_fp
        logger.info("Started logging to %r", logfilepath)

    if os.environ.get("MYPAINT_DEBUG", False):
        logger.critical("Test critical message, please ignore")
        warnings.resetwarnings()
        logging.captureWarnings(True)

    if options.version:
        # Output (rather than log) the version
        print "MyPaint version %s" % (version, )
        sys.exit(0)

    def run():
        logger.debug('user_datapath: %r', userdatapath)
        logger.debug('user_confpath: %r', userconfpath)

        app = application.Application(args,
                                      app_datapath=datapath,
                                      app_extradatapath=extradata,
                                      user_datapath=userdatapath,
                                      user_confpath=userconfpath,
                                      version=version,
                                      fullscreen=options.fullscreen)

        settings = gtk.Settings.get_default()
        dark = app.preferences.get("ui.dark_theme_variant", True)
        settings.set_property("gtk-application-prefer-dark-theme", dark)

        import gtkexcepthook
        func = app.filehandler.confirm_destructive_action
        gtkexcepthook.quit_confirmation_func = func

        # temporary workaround for gtk3 Ctrl-C bug:
        # https://bugzilla.gnome.org/show_bug.cgi?id=622084
        import signal
        signal.signal(signal.SIGINT, signal.SIG_DFL)

        gtk.main()

    if options.trace:
        import trace
        tracer = trace.Trace(trace=1, count=0)
        tracer.runfunc(run)
    else:
        run()
Example #11
0
DEFAULT_HEIGHT = 350  # Dialog's default height at startup
PREVIEW_HEIGHT = 150  # Height of preview area
UNDO_LOG_FILE = '.rlog'  # Name used for Log file
DATA_DIR = '.rdata/'  #
LOG_SEP = ' is converted to '  # Log file separator
REC_PATS = 5  # Remember up to 5 recent patterns
REC_FILE = 'recent_patterns'  # filename for recent patterns
NOTIFICATION_TIMEOUT = -1  # notification timeout, Notify.EXPIRES_DEFAULT
SMALL_FONT_SIZE = Pango.SCALE * 10

# Fake Enums
CASE_NONE, CASE_ALL_CAP, CASE_ALL_LOW, CASE_FIRST_CAP, CASE_EACH_CAP, CASE_CAP_AFTER = range(
    6)

# dir to store application state, recent patterns ...
CONFIG_DIR = os.path.join(glib.get_user_data_dir(), 'nautilus-renamer')
APP = 'nautilus-renamer'

## init gettext
PO_DIR = None
if os.path.exists(os.path.expanduser('~/.gnome2/nautilus-scripts/.rdata/po')):
    # po dir, when it is installed as a user script
    PO_DIR = os.path.expanduser('~/.gnome2/nautilus-scripts/.rdata/po')

gettext.bindtextdomain(APP, PO_DIR)
gettext.textdomain(APP)
lang = gettext.translation(APP, PO_DIR, fallback=True)
_ = lang.gettext
gettext.install(APP, PO_DIR)

Example #12
0
def main(datapath, extradata, oldstyle_confpath=None, version=MYPAINT_VERSION):
    """Run MyPaint with `sys.argv`, called from the "mypaint" script.

    :param datapath: The app's read-only data location.
      Where MyPaint should find its static data, e.g. UI definition XML,
      backgrounds, and brush definitions. $PREFIX/share/mypaint is usual.
    :param extradata: Extra search root for finding icons.
      Where to find the defaults for MyPaint's themeable UI icons. This will be
      used in addition to $XDG_DATA_DIRS for the purposes of icon lookup.
      Normally it's $PREFIX/share, to support unusual installations outside the
      usual locations. It should contain an icons/ subdirectory.
    :param oldstyle_confpath: Old-style merged config folder.
      If specified, all user-specific data that MyPaint writes is written here.
      If omitted, this data will be stored under the basedirs returned by
      glib.get_user_config_dir() for settings, and by glib.get_user_data_dir()
      for brushes and backgrounds. On Windows, these will be the same location.
      On POSIX systems, $HOME/.config/mypaint and $HOME/.local/share/mypaint
      are a typical division.
    :param version: full version string for display in the about box.

    The oldstyle_confpath parameter can also be overridden by command-line
    parameters. To support legacy MyPaint configuration dirs, call with
    oldstyle_confpath set to the expansion of ~/.mypaint.

    """

    # Default logfile basename.
    # If it's relative, it's resolved relative to the user config path.
    default_logfile = None
    if sys.platform == 'win32':   # http://gna.org/bugs/?17999
        default_logfile = "mypaint_error.log"

    # Parse command line
    parser = OptionParser('usage: %prog [options] [FILE]')
    parser.add_option('-c', '--config', metavar='DIR',
      default=oldstyle_confpath,
      help='use old-style merged config directory DIR, e.g. ~/.mypaint')
    parser.add_option('-l', '--logfile', metavar='FILE',
      default=default_logfile,
      help='log console messages to FILE (rel. to config location)')
    parser.add_option('-t', '--trace', action="store_true",
      help='print all executed Python statements')
    parser.add_option('-f', '--fullscreen', action="store_true",
      help='start in fullscreen mode')
    parser.add_option("-V", '--version', action="store_true",
      help='print version information and exit')
    options, args = parser.parse_args(sys.argv_unicode[1:])

    # XDG support for new users on POSIX platforms
    if options.config is None:
        encoding = 'utf-8'
        appsubdir = u"mypaint"
        basedir = glib.get_user_data_dir().decode(encoding)
        userdatapath = os.path.join(basedir, appsubdir)
        basedir = glib.get_user_config_dir().decode(encoding)
        userconfpath = os.path.join(basedir, appsubdir)
    else:
        userdatapath = options.config
        userconfpath = options.config

    # Log to the specified location
    # Prepend the data path if the user gave a relative location.
    if options.logfile:
        logfilepath = os.path.join(userdatapath, options.logfile)
        logdirpath, logfilebasename = os.path.split(logfilepath)
        if not os.path.isdir(logdirpath):
            os.makedirs(logdirpath)
        logger.info("Copying log messages to %r", logfilepath)
        logfile_fp = open(logfilepath, 'a', 1)
        logfile_handler = logging.StreamHandler(logfile_fp)
        logfile_format = "%(asctime)s;%(levelname)s;%(name)s;%(message)s"
        logfile_handler.setFormatter(logging.Formatter(logfile_format))
        root_logger = logging.getLogger(None)
        root_logger.addHandler(logfile_handler)
        # Classify this as a warning, since this is fairly evil.
        # Note: this hack doesn't catch every type of GTK3 error message.
        logger.warning("Redirecting stdout and stderr to %r", logfilepath)
        sys.stdout = sys.stderr = logfile_fp
        logger.info("Started logging to %r", logfilepath)

    if os.environ.get("MYPAINT_DEBUG", False):
        logger.critical("Test critical message, please ignore")

    if options.version:
        # Output (rather than log) the version
        print "MyPaint version %s" % (version,)
        sys.exit(0)

    def run():
        logger.debug('user_datapath: %r', userdatapath)
        logger.debug('user_confpath: %r', userconfpath)

        app = application.Application(args,
                app_datapath=datapath, app_extradatapath=extradata,
                user_datapath=userdatapath, user_confpath=userconfpath,
                version=version, fullscreen=options.fullscreen)

        # Recent gtk versions don't allow changing those menu shortcuts by
        # default. <rant>Sigh. This very useful feature used to be the
        # default behaviour even in the GIMP some time ago. I guess
        # assigning a keyboard shortcut without a complicated dialog
        # clicking marathon must have totally upset the people coming from
        # windows.</rant>
        gtksettings = gtk2compat.gtk.settings_get_default()
        gtksettings.set_property('gtk-can-change-accels', True)

        import gtkexcepthook
        func = app.filehandler.confirm_destructive_action
        gtkexcepthook.quit_confirmation_func = func

        # temporary workaround for gtk3 Ctrl-C bug:
        # https://bugzilla.gnome.org/show_bug.cgi?id=622084
        import signal
        signal.signal(signal.SIGINT, signal.SIG_DFL)

        gtk.main()

    if options.trace:
        import trace
        tracer = trace.Trace(trace=1, count=0)
        tracer.runfunc(run)
    else:
        run()
Example #13
0
import sys
if not (2, 6) <= sys.version_info < (3, ):
    sys.exit(u'Mopidy requires Python >= 2.6, < 3')

import os
import platform
from subprocess import PIPE, Popen

import glib

__version__ = '0.8.0'

DATA_PATH = os.path.join(str(glib.get_user_data_dir()), 'mopidy')
CACHE_PATH = os.path.join(str(glib.get_user_cache_dir()), 'mopidy')
SETTINGS_PATH = os.path.join(str(glib.get_user_config_dir()), 'mopidy')
SETTINGS_FILE = os.path.join(SETTINGS_PATH, 'settings.py')


def get_version():
    try:
        return get_git_version()
    except EnvironmentError:
        return __version__


def get_git_version():
    process = Popen(['git', 'describe'], stdout=PIPE, stderr=PIPE)
    if process.wait() != 0:
        raise EnvironmentError('Execution of "git describe" failed')
    version = process.stdout.read().strip()
    if version.startswith('v'):
Example #14
0
import shutil
import glib

PROGRAM_NAME = 'hotot'
EXT_DIR_NAME = 'ext'
CONF_DIR = os.path.join(glib.get_user_config_dir(), PROGRAM_NAME)
DB_DIR = os.path.join(CONF_DIR, 'db')
CACHE_DIR = os.path.join(glib.get_user_cache_dir(), PROGRAM_NAME)
AVATAR_CACHE_DIR = os.path.join(CACHE_DIR, 'avatar')

DATA_DIRS = []

DATA_BASE_DIRS = [
      '/usr/local/share'
    , '/usr/share'
    , glib.get_user_data_dir()
    ]

DATA_DIRS += [os.path.join(d, PROGRAM_NAME) for d in DATA_BASE_DIRS]
DATA_DIRS.append(os.path.abspath('./data'))

TEMPLATE = 'index.html'

settings = {}

def getconf():
    '''获取 config
    '''
    config = {}
    ##
Example #15
0
    def getHomeDir(mkdir=None):
        """
        Return the "Home dir" of the system (if it exists), or None
        (if mkdir is set : it will create a subFolder "mkdir" if the
        path exist, and will append to it (the newfolder can begins with
        a "." or not))
        """
        maskDir = False
        glibConfDir = glib.get_user_data_dir()

        # Find legacy home dir
        # windows NT,2k,XP,etc.
        if (os.name == "nt") and ("APPDATA" in os.environ):
            home = os.environ['APPDATA']
            if not os.path.isdir(home):
                raise OSError("Missing %APPDATA% directory")
            maskDir = False
        elif ("XDG_CONFIG_HOME" in os.environ):
            home = os.environ['XDG_CONFIG_HOME']
            if not os.path.isdir(home):
                raise OSError("Missing $XDG_CONFIG_HOME directory")
            maskDir = False
        elif (os.path.expanduser("~") != "~"):
            home = os.path.expanduser("~")
            if not os.path.isdir(home):
                raise OSError("Missing ~ directory. Weird.")
            maskDir = True
        elif ("HOME" in os.environ):
            home = os.environ["HOME"]
            if os.path.isdir(home):
                conf = os.path.join(home, ".config")
                if os.path.isdir(conf):
                    home = conf
                    maskDir = False
                else:
                    # keep home
                    maskDir = True
            else:
                raise OSError("Missing $HOME directory.")
        else:
            # What os are people using?
            home = None

        if glibConfDir:
            if mkdir:
                if maskDir:
                    newDir = "." + mkdir
                else:
                    newDir = mkdir

                confDir = os.path.join(glibConfDir, mkdir)
                oldConfDir = os.path.join(home, newDir)
                if not os.path.isdir(confDir):
                    # copy old data if we have them
                    if os.path.isdir(oldConfDir):
                        print "Copying %s to %s" % (oldConfDir, confDir)
                        shutil.copytree(oldConfDir, confDir,
                                        symlinks=True)
                    else:
                        print "Creating new dir %s" % confDir
                        os.mkdir(confDir)

        return confDir
Example #16
0
def _get_rhythmbox_xml_path(xml):
    for base in (glib.get_user_data_dir(),os.path.expanduser("~/.gnome2")):
        path = os.path.join(base,"rhythmbox",xml)
        if os.path.exists(path):
            return path
    return "/dev/null"
Example #17
0
def getUserDataPrefix ():
    return join(get_user_data_dir(), pychess)
Example #18
0
 def test_xdg_subsititution(self):
     self.assertEqual(glib.get_user_data_dir() + b'/foo',
                      path.expand_path(b'$XDG_DATA_DIR/foo'))
Example #19
0
from __future__ import unicode_literals

import logging
import os
import string
import urllib
import urlparse

import glib

logger = logging.getLogger('mopidy.utils.path')

XDG_DIRS = {
    'XDG_CACHE_DIR': glib.get_user_cache_dir(),
    'XDG_CONFIG_DIR': glib.get_user_config_dir(),
    'XDG_DATA_DIR': glib.get_user_data_dir(),
    'XDG_MUSIC_DIR': glib.get_user_special_dir(glib.USER_DIRECTORY_MUSIC),
}

# XDG_MUSIC_DIR can be none, so filter out any bad data.
XDG_DIRS = dict((k, v) for k, v in XDG_DIRS.items() if v is not None)


def get_or_create_dir(dir_path):
    if not isinstance(dir_path, bytes):
        raise ValueError('Path is not a bytestring.')
    dir_path = expand_path(dir_path)
    if os.path.isfile(dir_path):
        raise OSError('A file with the same name as the desired dir, '
                      '"%s", already exists.' % dir_path)
    elif not os.path.isdir(dir_path):
Example #20
0
def main(datapath, extradata, oldstyle_confpath=None, version=MYPAINT_VERSION):
    """Run MyPaint with `sys.argv`, called from the "mypaint" script.

    :param datapath: The app's read-only data location.
      Where MyPaint should find its static data, e.g. UI definition XML,
      backgrounds, and brush definitions. $PREFIX/share/mypaint is usual.
    :param extradata: Extra search root for finding icons.
      Where to find the defaults for MyPaint's themeable UI icons. This will be
      used in addition to $XDG_DATA_DIRS for the purposes of icon lookup.
      Normally it's $PREFIX/share, to support unusual installations outside the
      usual locations. It should contain an icons/ subdirectory.
    :param oldstyle_confpath: Old-style merged config folder.
      If specified, all user-specific data that MyPaint writes is written here.
      If omitted, this data will be stored under the basedirs returned by
      glib.get_user_config_dir() for settings, and by glib.get_user_data_dir()
      for brushes and backgrounds. On Windows, these will be the same location.
      On POSIX systems, $HOME/.config/mypaint and $HOME/.local/share/mypaint
      are a typical division.
    :param version: full version string for display in the about box.

    The oldstyle_confpath parameter can also be overridden by command-line
    parameters. To support legacy MyPaint configuration dirs, call with
    oldstyle_confpath set to the expansion of ~/.mypaint.

    """

    # Default logfile basename.
    # If it's relative, it's resolved relative to the user config path.
    default_logfile = None
    if sys.platform == 'win32':   # http://gna.org/bugs/?17999
        default_logfile = "mypaint_error.log"

    # Parse command line
    parser = OptionParser('usage: %prog [options] [FILE]')
    parser.add_option('-c', '--config', metavar='DIR',
      default=oldstyle_confpath,
      help='use old-style merged config directory DIR, e.g. ~/.mypaint')
    parser.add_option('-l', '--logfile', metavar='FILE',
      default=default_logfile,
      help='append Python stdout and stderr to FILE (rel. to config location)')
    parser.add_option('-t', '--trace', action="store_true",
      help='print all executed Python statements')
    parser.add_option('-f', '--fullscreen', action="store_true",
      help='start in fullscreen mode')
    parser.add_option("-V", '--version', action="store_true",
      help='print version information and exit')
    options, args = parser.parse_args(sys.argv_unicode[1:])

    # XDG support for new users on POSIX platforms
    if options.config is None:
        encoding = 'utf-8'
        appsubdir = u"mypaint"
        basedir = glib.get_user_data_dir().decode(encoding)
        userdatapath = os.path.join(basedir, appsubdir)
        basedir = glib.get_user_config_dir().decode(encoding)
        userconfpath = os.path.join(basedir, appsubdir)
    else:
        userdatapath = options.config
        userconfpath = options.config

    # Log to the specified location
    # Prepend the data path if the user gave a relative location.
    if options.logfile:
        logfilepath = os.path.join(userdatapath, options.logfile)
        logdirpath, logfilebasename = os.path.split(logfilepath)
        if not os.path.isdir(logdirpath):
            os.makedirs(logdirpath)
        print 'Python prints are redirected to %s after this one.' % logfilepath
        sys.stdout = sys.stderr = open(logfilepath, 'a', 1)
        print '--- mypaint log %s ---' % time.strftime('%Y-%m-%d %H:%M:%S')

    if options.version:
        print "MyPaint version %s" % (version,)
        sys.exit(0)

    def run():
        print 'DEBUG: user_datapath:', userdatapath
        print 'DEBUG: user_confpath:', userconfpath

        app = application.Application(args,
                app_datapath=datapath, app_extradatapath=extradata,
                user_datapath=userdatapath, user_confpath=userconfpath,
                version=version, fullscreen=options.fullscreen)

        # Recent gtk versions don't allow changing those menu shortcuts by
        # default. <rant>Sigh. This very useful feature used to be the
        # default behaviour even in the GIMP some time ago. I guess
        # assigning a keyboard shortcut without a complicated dialog
        # clicking marathon must have totally upset the people coming from
        # windows.</rant>
        gtksettings = pygtkcompat.gtk.settings_get_default()
        gtksettings.set_property('gtk-can-change-accels', True)

        import gtkexcepthook
        func = app.filehandler.confirm_destructive_action
        gtkexcepthook.quit_confirmation_func = func
        gtk.main()

    if options.trace:
        import trace
        tracer = trace.Trace(trace=1, count=0)
        tracer.runfunc(run)
    else:
        run()
Example #21
0
DEFAULT_WIDTH   = 550                   # Dialog's default width at startup
DEFAULT_HEIGHT  = 350                   # Dialog's default height at startup
PREVIEW_HEIGHT  = 150                   # Height of preview area
UNDO_LOG_FILE   = '.rlog'               # Name used for Log file
DATA_DIR        = '.rdata/'             #
LOG_SEP         = ' is converted to '   # Log file separator
REC_PATS        = 5                     # Remember up to 5 recent patterns
REC_FILE        = 'recent_patterns'     # filename for recent patterns
NOTIFICATION_TIMEOUT =  -1              # notification timeout, Notify.EXPIRES_DEFAULT
SMALL_FONT_SIZE = Pango.SCALE * 10

# Fake Enums
CASE_NONE, CASE_ALL_CAP, CASE_ALL_LOW, CASE_FIRST_CAP, CASE_EACH_CAP, CASE_CAP_AFTER = range (6)

# dir to store application state, recent patterns ...
CONFIG_DIR = os.path.join (glib.get_user_data_dir (), 'nautilus-renamer')
APP = 'nautilus-renamer'

## init gettext
PO_DIR = None
if os.path.exists(os.path.expanduser('~/.gnome2/nemo-scripts/.rdata/po')):
    # po dir, when it is installed as a user script
    PO_DIR = os.path.expanduser('~/.gnome2/nemo-scripts/.rdata/po')

gettext.bindtextdomain(APP, PO_DIR)
gettext.textdomain(APP)
lang = gettext.translation (APP, PO_DIR, fallback=True)
_ = lang.gettext
gettext.install (APP, PO_DIR)

class RenameApplication(Gtk.Application):
Example #22
0
def freedesktop_thumbnail(filename, pixbuf=None):
    """
    Fetch or (re-)generate the thumbnail in ~/.thumbnails.

    If there is no thumbnail for the specified filename, a new
    thumbnail will be generated and stored according to the FDO spec.
    A thumbnail will also get regenerated if the MTimes (as in "modified")
    of thumbnail and original image do not match.

    When pixbuf is given, it will be scaled and used as thumbnail
    instead of reading the file itself. In this case the file is still
    accessed to get its mtime, so this method must not be called if
    the file is still open.

    Returns the thumbnail.
    """

    uri = filename2uri(filename)
    file_hash = hashlib.md5(uri).hexdigest()

    if sys.platform == 'win32':
        import glib
        base_directory = os.path.join(glib.get_user_data_dir().decode('utf-8'), 'mypaint', 'thumbnails')
    else:
        base_directory = expanduser_unicode(u'~/.thumbnails')

    directory = os.path.join(base_directory, 'normal')
    tb_filename_normal = os.path.join(directory, file_hash) + '.png'

    if not os.path.exists(directory):
        os.makedirs(directory, 0700)
    directory = os.path.join(base_directory, 'large')
    tb_filename_large = os.path.join(directory, file_hash) + '.png'
    if not os.path.exists(directory):
        os.makedirs(directory, 0700)

    file_mtime = str(int(os.stat(filename).st_mtime))

    save_thumbnail = True

    if filename.lower().endswith('.ora'):
        # don't bother with normal (128x128) thumbnails when we can
        # get a large one (256x256) from the file in an instant
        acceptable_tb_filenames = [tb_filename_large]
    else:
        # prefer the large thumbnail, but accept the normal one if
        # available, for the sake of performance
        acceptable_tb_filenames = [tb_filename_large, tb_filename_normal]

    for fn in acceptable_tb_filenames:
        if not pixbuf and os.path.isfile(fn):
            # use the largest stored thumbnail that isn't obsolete
            pixbuf = gdk.pixbuf_new_from_file(fn)
            if file_mtime == pixbuf.get_option("tEXt::Thumb::MTime"):
                save_thumbnail = False
            else:
                pixbuf = None

    if not pixbuf:
        # try to load a pixbuf from the file
        pixbuf = get_pixbuf(filename)

    if pixbuf:
        pixbuf = scale_proportionally(pixbuf, 256, 256)
        if save_thumbnail:
            png_opts = {"tEXt::Thumb::MTime": file_mtime,
                        "tEXt::Thumb::URI": uri}
            pygtkcompat.gdk.pixbuf.save(pixbuf, tb_filename_large,
                                        'png', **png_opts)
            # save normal size too, in case some implementations don't
            # bother with large thumbnails
            pixbuf_normal = scale_proportionally(pixbuf, 128, 128)
            pygtkcompat.gdk.pixbuf.save(pixbuf_normal, tb_filename_normal,
                                        'png', **png_opts)

    return pixbuf
Example #23
0
Module for holding constants (and some variables with "fixed" values) used
all over the program.
"""

import os.path

import glib
from constant_constants import *

# Path of the program (bad assumption)
TV_PATH = "/usr/bin/tunesviewer"
TV_VERSION = "1.5" #also needs changing in debian conf file somewhere

# Directory under which we write configuration files
USER_PREFS_DIR = glib.get_user_config_dir()
PREFS_DIR = os.path.join(USER_PREFS_DIR, "tunesviewer")
PREFS_FILE = os.path.join(PREFS_DIR, "tunesviewer.conf")

# Directory under which we write state data
USER_DATA_DIR = glib.get_user_data_dir()
DATA_DIR = os.path.join(USER_DATA_DIR, "tunesviewer")
DATA_FILE = os.path.join(DATA_DIR, "state") # Holds current downloads, in case of crash, resumes.
DATA_SOCKET = os.path.join(DATA_DIR, "tunesviewerLOCK") # Holds socket, so second app calls first instance with url.

# Directory under which we write downloaded files
DOWNLOADS_DIR = os.path.expanduser("~")

# connection programs
DEFAULT_OPENER = "vlc --http-user-agent=%s --http-caching=10000" % (USER_AGENT, )

Example #24
0
        '.'.join(map(str, sys.version_info[:3])))

if (isinstance(pykka.__version__, basestring)
        and not SV('1.0') <= SV(pykka.__version__) < SV('2.0')):
    sys.exit(
        u'Mopidy requires Pykka >= 1.0, < 2, but found %s' % pykka.__version__)

import os
import platform
from subprocess import PIPE, Popen

import glib

__version__ = '0.8.1'

DATA_PATH = os.path.join(str(glib.get_user_data_dir()), 'mopidy')
CACHE_PATH = os.path.join(str(glib.get_user_cache_dir()), 'mopidy')
SETTINGS_PATH = os.path.join(str(glib.get_user_config_dir()), 'mopidy')
SETTINGS_FILE = os.path.join(SETTINGS_PATH, 'settings.py')

def get_version():
    try:
        return get_git_version()
    except EnvironmentError:
        return __version__

def get_git_version():
    process = Popen(['git', 'describe'], stdout=PIPE, stderr=PIPE)
    if process.wait() != 0:
        raise EnvironmentError('Execution of "git describe" failed')
    version = process.stdout.read().strip()
Example #25
0
import stat
import string
import threading
import urllib
import urlparse

import glib


logger = logging.getLogger(__name__)


XDG_DIRS = {
    'XDG_CACHE_DIR': glib.get_user_cache_dir(),
    'XDG_CONFIG_DIR': glib.get_user_config_dir(),
    'XDG_DATA_DIR': glib.get_user_data_dir(),
    'XDG_MUSIC_DIR': glib.get_user_special_dir(glib.USER_DIRECTORY_MUSIC),
}

# XDG_MUSIC_DIR can be none, so filter out any bad data.
XDG_DIRS = dict((k, v) for k, v in XDG_DIRS.items() if v is not None)


def get_or_create_dir(dir_path):
    if not isinstance(dir_path, bytes):
        raise ValueError('Path is not a bytestring.')
    dir_path = expand_path(dir_path)
    if os.path.isfile(dir_path):
        raise OSError(
            'A file with the same name as the desired dir, '
            '"%s", already exists.' % dir_path)
Example #26
0
from desktopagnostic import fdo, vfs

try:
    import dbus
    from dbus.mainloop.glib import DBusGMainLoop
    DBusGMainLoop(set_as_default=True)
except ImportError:
    dbus = None

import gio
import glib
import gmenu

# TODO Remove the check and the else as soon as Ubuntu Moaning Monkey is not supported anymore
if awnlib.is_required_version(glib.pyglib_version, (2, 26, 0)):
    xdg_data_dirs = [glib.get_user_data_dir()] + list(glib.get_system_data_dirs())
else:
    xdg_data_dirs = [os.path.expanduser("~/.local/share")]
    if "XDG_DATA_DIRS" in os.environ:
        xdg_data_dirs += os.environ["XDG_DATA_DIRS"].split(":")

applet_name = _("YAMA")
applet_description = _("Main menu with places and recent documents")

# Applet's themed icon, also shown in the GTK About dialog
applet_logo = "start-here"

menu_editor_apps = ("alacarte", "gmenu-simple-editor")

# Describes the pattern used to try to decode URLs
url_pattern = re.compile("^[a-z]+://(?:[^@]+@)?([^/]+)/(.*)$")
Example #27
0
import logging
import os
import re
# pylint: disable = W0402
import string
# pylint: enable = W0402
import sys
import urllib

import glib

logger = logging.getLogger('mopidy.utils.path')

XDG_CACHE_DIR = glib.get_user_cache_dir().decode('utf-8')
XDG_CONFIG_DIR = glib.get_user_config_dir().decode('utf-8')
XDG_DATA_DIR = glib.get_user_data_dir().decode('utf-8')
XDG_MUSIC_DIR = glib.get_user_special_dir(glib.USER_DIRECTORY_MUSIC)
if XDG_MUSIC_DIR:
    XDG_MUSIC_DIR = XDG_MUSIC_DIR.decode('utf-8')
XDG_DIRS = {
    'XDG_CACHE_DIR': XDG_CACHE_DIR,
    'XDG_CONFIG_DIR': XDG_CONFIG_DIR,
    'XDG_DATA_DIR': XDG_DATA_DIR,
    'XDG_MUSIC_DIR': XDG_MUSIC_DIR,
}
DATA_PATH = os.path.join(unicode(XDG_DATA_DIR), 'mopidy')
SETTINGS_PATH = os.path.join(unicode(XDG_CONFIG_DIR), 'mopidy')
SETTINGS_FILE = os.path.join(unicode(SETTINGS_PATH), 'settings.py')


def get_or_create_folder(folder):
Example #28
0
 def test_xdg_subsititution(self):
     self.assertEqual(glib.get_user_data_dir() + b"/foo", path.expand_path(b"$XDG_DATA_DIR/foo"))
Example #29
0
class ClipboardProtector(object):

    PASTIE_DATA_DIR = os.path.join(glib.get_user_data_dir(), 'pastie/')
    HISTORY_FILE = os.path.join(PASTIE_DATA_DIR, 'clipboard_history')

    PASTIE_CONFIG_DIR = os.path.join(glib.get_user_config_dir(), 'pastie/')
    PASTIE_ICON = os.path.join(PASTIE_CONFIG_DIR, 'pastie.svg')

    def __init__(self):
        # try to load custom icon from ~/.pastie/
        pastieDir = os.path.join(os.path.expanduser('~'), '.pastie/')
        pastieIcon = os.path.expanduser('~/.pastie/pastie.svg')
        if os.path.isfile(pastieIcon) == True:
            self.indicator = appindicator.Indicator(
                "pastie", "pastie", appindicator.CATEGORY_OTHER, pastieDir)
        else:
            self.indicator = appindicator.Indicator(
                "pastie", "gtk-paste", appindicator.CATEGORY_OTHER)
        # set the indicator as active (pastie must be always shown)
        self.indicator.set_status(appindicator.STATUS_ACTIVE)

        # get the clipboard gdk atom
        self.clipboard = gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD)

        self.primary = gtk.clipboard_get(gtk.gdk.SELECTION_PRIMARY)

        # we use this to check if clipboard contents changed on special cases
        self.specials_text = ""
        self.primary_text = ""

        # create the history data strucure
        self.history = history.HistoryMenuItemCollector()
        # the menu will be updated when the "item-lenght-adjusted" signal in the history object is emitted
        self.history.connect("length-adjusted", self.update_menu)
        # ... and when data changes
        self.history.connect("data-change", self.update_menu)

        # load history if existent
        self.history.set_payload(self.recover_history())
        # pastie might have been loaded after some contents were added to the X clipboard.
        # we check if ther's any.
        self.check()
        # select the first item in the history.
        if len(self.history) > 0:
            self.history[0].set_as_current()

        # set the gconf_client
        self.gconf_client = prefs.PrefsGConfClient()

        # register gconf preferences changes callback functions
        self.gconf_client.notify_add('show_quit_on_menu', self.update_menu)
        self.gconf_client.notify_add('show_preferences_on_menu',
                                     self.update_menu)
        self.gconf_client.notify_add('item_length', self.update_menu)
        self.gconf_client.notify_add('history_size',
                                     self.history.adjust_maxlen)
        self.gconf_client.notify_add('use_primary', self.toggle_primary)
        self.gconf_client.notify_add('sel_dialog_key',
                                     self.change_s_dialog_key)
        self.gconf_client.notify_add('prefs_dialog_key',
                                     self.change_prefs_dialog_key)

        # check clipboard changes on owner-change event
        self.clipboard.connect("owner-change", self.check)
        self.toggle_primary()

        # run an auxiloary loop for special cases (e.g., gvim)
        gobject.timeout_add(500, self.check_specials)

        # create the selection dialog and set the keyboard shortcut for it
        self.s_dialog = seldiag.SelectionDialog(self)
        self.prev_sel_dialog_key = prefs.get_sel_dialog_key()
        self.change_s_dialog_key()

        # set the preferences dialog's keyboard shortcut
        self.prev_prefs_dialog_key = prefs.get_prefs_dialog_key()
        self.change_prefs_dialog_key()

    # activate/deactivate primary selection
    def toggle_primary(self, a=None, b=None, c=None, d=None):
        if prefs.get_use_primary() == True:
            gobject.timeout_add(500, self.check_primary)

    # change the binding of the selection dialog
    def change_s_dialog_key(self,
                            gconfclient=None,
                            gconfentry=None,
                            gconfvalue=None,
                            d=None):
        try:
            keybinder.unbind(self.prev_sel_dialog_key)
        except:
            pass

        keybinder.bind(prefs.get_sel_dialog_key(),
                       lambda: self.s_dialog.show())
        self.prev_sel_dialog_key = prefs.get_sel_dialog_key()

    # change the binding of the preferences dialog
    def change_prefs_dialog_key(self,
                                gconfclient=None,
                                gconfentry=None,
                                gconfvalue=None,
                                d=None):
        try:
            keybinder.unbind(self.prev_prefs_dialog_key)
        except:
            pass

        keybinder.bind(prefs.get_prefs_dialog_key(),
                       lambda: prefs.PreferencesDialog())
        self.prev_prefs_dialog_key = prefs.get_prefs_dialog_key()

    # returns a list of history items from a XML file.
    def recover_history(self, input_file=HISTORY_FILE):
        tmp_list = []

        try:
            history_tree = tree.parse(input_file)
        except IOError:  # file doesn't exist
            return tmp_list
        except ExpatError:  # file is empty or malformed
            return tmp_list
        except ParseError:  # file is empty (not element found)
            return tmp_list

        for item in history_tree.findall("item"):
            if item.get("type") == "text":
                history_item = history.TextHistoryMenuItem(item.text)
            elif item.get("type") == "file":
                history_item = history.FileHistoryMenuItem(item.text)
            elif item.get("type") == "image":
                data = base64.b64decode(item.text)
                has_alpha = bool(item.get("has_alpha"))
                width = int(item.get("width"))
                height = int(item.get("height"))
                rowstride = int(item.get("rowstride"))
                pixbuf = gtk.gdk.pixbuf_new_from_data(data, gtk.gdk.COLORSPACE_RGB, \
                has_alpha, 8, width, height, rowstride)
                history_item = history.ImageHistoryMenuItem(pixbuf)
            else:
                history_item = history.TextHistoryMenuItem(item.text)

            tmp_list.append(history_item)

        return tmp_list

    # saves the clipboard history to a XML file. called on program termination.
    def save_history(self, output_file=HISTORY_FILE):
        history_tree_root = tree.Element("clipboard")

        for item in self.history.data:
            history_tree_item = tree.SubElement(history_tree_root, "item")
            history_tree_item.set("id", hashlib.md5(item.payload).hexdigest())

            if isinstance(item, history.TextHistoryMenuItem):
                item_type = "text"
            elif isinstance(item, history.FileHistoryMenuItem):
                item_type = "file"
            elif isinstance(item, history.ImageHistoryMenuItem):
                item_type = "image"
            else:
                item_type = "text"

            history_tree_item.set("type", item_type)

            if item_type == "image":
                history_tree_item.set("has_alpha",
                                      str(item.pixbuf.props.has_alpha))
                history_tree_item.set("width", str(item.pixbuf.props.width))
                history_tree_item.set("height", str(item.pixbuf.props.height))
                history_tree_item.set("rowstride",
                                      str(item.pixbuf.props.rowstride))
                history_tree_item.text = base64.b64encode(item.payload)
            else:
                history_tree_item.text = item.payload

        history_tree = tree.ElementTree(history_tree_root)
        history_tree.write(output_file, "UTF-8")

    # erase the clipboard history. the current contents of the clipoard will remain.
    def clean_history(self, event=None):
        self.history.empty(full=True)
        self.check()
        self.save_history()
        self.update_menu()

    def delete_current(self, event=None):
        self.clipboard.clear()
        self.history.delete_top()
        self.save_history()
        self.update_menu()

    def replace_current(self, data, event=None):
        self.clipboard.clear()
        self.history.replace_top(history.TextHistoryMenuItem(data))
        self.save_history()
        self.update_menu()

    # check clipboard contents.
    def check(self, clipboard=None, event=None):
        if not self.clipboard.wait_for_targets():
            # some programs (JEdit) don't set the targets, but still set the text...
            no_targetted_text = self.clipboard.wait_for_text()
            if no_targetted_text != None:  # ... if that's the case, we add it
                self.history.add(
                    history.TextHistoryMenuItem(no_targetted_text))
                self.save_history()
            else:
                if self.history[0] != None:
                    self.history[0].set_as_current()
        elif self.clipboard.wait_is_text_available():
            clipboard_tmp = self.clipboard.wait_for_text()
            if clipboard_tmp not in ("", None):
                if 'PASS_TIMEOUT' in self.clipboard.wait_for_targets():
                    timeout = int(
                        self.clipboard.wait_for_contents(
                            'PASS_TIMEOUT').data) * 1000
                    self.history.add(
                        history.PasswordHistoryMenuItem(clipboard_tmp))
                    gobject.timeout_add(timeout, self.delete_current)
                elif self.clipboard.wait_is_uris_available():
                    self.history.add(
                        history.FileHistoryMenuItem(clipboard_tmp))
                else:
                    self.history.add(
                        history.TextHistoryMenuItem(clipboard_tmp))
                self.save_history()
        elif self.clipboard.wait_is_image_available():
            clipboard_contents = self.clipboard.wait_for_image()
            self.history.add(history.ImageHistoryMenuItem(clipboard_contents))
            self.save_history()

    def check_specials(self):
        targets = self.clipboard.wait_for_targets()
        # if there are no targets, we simply return True
        if targets != None:
            # vim doesn't set the timestamp target, so we have to check for its changes.
            if '_VIM_TEXT' in targets:
                clipboard_tmp = self.clipboard.wait_for_text()
                if clipboard_tmp not in (
                        "", None) and clipboard_tmp != self.specials_text:
                    self.history.add(
                        history.TextHistoryMenuItem(clipboard_tmp))
                    self.specials_text = clipboard_tmp
                    self.save_history()
        return True

    def check_primary(self):
        if prefs.get_use_primary() == True:
            mouse_modifiers = gtk.gdk.Display(
                None).get_pointer()[3].value_names
            if 'GDK_BUTTON1_MASK' not in mouse_modifiers:
                if 'GDK_SHIFT_MASK' not in mouse_modifiers:
                    primary_targets = self.primary.wait_for_targets()
                    if primary_targets != None:
                        primary_tmp = self.primary.wait_for_text()
                        if primary_tmp not in (
                                "", None) and primary_tmp != self.primary_text:
                            self.history.add(
                                history.PrimaryHistoryMenuItem(primary_tmp))
                            if prefs.get_synch_primary() == True:
                                gtk.clipboard_get().set_text(primary_tmp)
                                gtk.clipboard_get().store()
                            self.primary_specials_text = primary_tmp
                            self.save_history()
            return True
        else:
            return False

    def create_edit_dialog(self, event):
        edit_dialog = edit.ClipboardEditorDialog(self)

    def create_prefs_dialog(self, event):
        prefs_dialog = prefs.PreferencesDialog()

    # create and show the menu
    def update_menu(self,
                    gconfclient=None,
                    gconfentry=None,
                    gconfvalue=None,
                    d=None):
        menu = gtk.Menu()

        if len(self.history) > 0:
            for i in self.history:
                label = i.get_label()
                item = gtk.MenuItem(label, use_underline=False)
                item.connect("activate", i.set_as_current)
                menu.append(item)
            menu.append(gtk.SeparatorMenuItem())
            if isinstance(self.history[0], history.TextHistoryMenuItem):
                edit_clipboard_menu = gtk.MenuItem(_("Edit clipboard"))
                edit_clipboard_menu.connect("activate",
                                            self.create_edit_dialog)
                menu.append(edit_clipboard_menu)
            if isinstance(self.history[0], history.ImageHistoryMenuItem) or \
             isinstance(self.history[0], history.FileHistoryMenuItem):
                delete_current_menu = gtk.MenuItem(_("Remove current"))
                delete_current_menu.connect("activate", self.delete_current)
                menu.append(delete_current_menu)
            clean_menu = gtk.MenuItem(_("Clean history"))
            clean_menu.connect("activate", self.clean_history)
            menu.append(clean_menu)
        else:
            nothing_to_show_menu = gtk.MenuItem(
                _("Nothing in history or clipboards"))
            menu.append(nothing_to_show_menu)

        if prefs.get_show_prefs() == True:
            prefs_menu = gtk.MenuItem(_("Preferences") + u'\u2026')
            prefs_menu.connect("activate", self.create_prefs_dialog)
            menu.append(prefs_menu)

        if prefs.get_show_quit() == True:
            quit_menu = gtk.MenuItem(_("Quit"))
            quit_menu.connect("activate", lambda q: gtk.main_quit())
            menu.append(quit_menu)

        menu.show_all()
        # attach this menu to the indicator
        self.indicator.set_menu(menu)