def got_account_cb (o, r, password, func):
    account = o.create_account_finish (r)
    # Put the password in our credentials store
    try:
        os.makedirs (os.path.join (GLib.get_user_config_dir (), "phoenix"))
    except:
        pass
    authfile = os.path.join (GLib.get_user_config_dir (), "phoenix", "auth")
    f = open (authfile, "a+")
    f.write (account.get_path_suffix() + " " + password + "\n")

    func(account)
Ejemplo n.º 2
0
Archivo: main.py Proyecto: nzinfo/ibus
    def __checkbutton_auto_start_toggled_cb(self, button):
        auto_start_dir = path.join(GLib.get_user_config_dir(), "autostart")
        if not path.isdir(auto_start_dir):
            os.makedirs(auto_start_dir)

        link_file = path.join(GLib.get_user_config_dir(), "autostart/ibus.desktop")
        ibus_desktop = path.join(os.getenv("IBUS_PREFIX"), "share/applications/ibus.desktop")
        # unlink file
        try:
            os.unlink(link_file)
        except:
            pass
        if self.__checkbutton_auto_start.get_active():
            os.symlink(ibus_desktop, link_file)
Ejemplo n.º 3
0
	def _show_warning_dialog(self):
		"""Shows a warning dialog it this is the first time the extension is
		used, and returns True if the user has pressed OK."""
		# Check if this is the first time the extension is used
		conf_dir = GLib.get_user_config_dir() # get "~/.config" path
		conf_file = os.path.join(conf_dir, ".nautilus-admin-warn-shown")
		if os.path.exists(conf_file):
			return True
		else:
			# Show the warning dialog
			self._setup_gettext();
			dialog = Gtk.MessageDialog(self.window, 0, Gtk.MessageType.WARNING,
			                           Gtk.ButtonsType.OK_CANCEL,
			                           gettext("CAUTION!"))
			msg = gettext("Running the File Manager or the Text Editor with Administrator "
			              "privileges <b>is dangerous</b>! <b>You can easily destroy your "
			              "system if you are not careful!</b>\n"
			              "Proceed only if you know what you are doing and understand the risks.")
			dialog.format_secondary_markup(msg)
			response = dialog.run()
			dialog.destroy()

			if response == Gtk.ResponseType.OK:
				# Mark the dialog as shown
				try:
					if not os.path.isdir(conf_dir):
						os.makedirs(conf_dir)
					open(conf_file, "w").close() # create an empty file
				except:
					pass
				return True
			else:
				return False
Ejemplo n.º 4
0
    def on_add_app(self, popup):
        app_dialog = AppChooserDialog()
        app_dialog.set_transient_for(self.list_box.get_toplevel())
        app_dialog.show_all()

        response = app_dialog.run()
        if response == Gtk.ResponseType.OK:
            selected_app = app_dialog.get_selected_app()
            desktop_file_dir = selected_app.get_filename()
            desktop_file_name = self.find_free_basename(os.path.basename(desktop_file_dir))
            if desktop_file_name is None:
                return
            user_autostart_dir = os.path.join(GLib.get_user_config_dir(), "autostart")
            user_desktop_file = os.path.join(user_autostart_dir, desktop_file_name)
            try:
                shutil.copyfile(desktop_file_dir, user_desktop_file)
            except IOError:
                print "Failed to copy desktop file %s" % desktop_file_name

            app = AutostartApp(user_desktop_file, user_position=os.path.dirname(user_desktop_file))

            app.enabled = True

            app.save_mask.add_item("all")

            app.queue_save()

            row = AutostartRow(app)
            self.add_row(row)
            row.show_all()

        app_dialog.destroy()
Ejemplo n.º 5
0
 def ensure_user_autostart_dir(self):
     user_autostart_dir = os.path.join(GLib.get_user_config_dir(), "autostart")
     if not os.path.isdir(user_autostart_dir):
         try:
             os.makedirs(user_autostart_dir)
         except:
             print "Could not create autostart dir: %s" % user_autostart_dir
Ejemplo n.º 6
0
def xdg_config_home(autocreate=True):
    """
    Get the directory for storing the user's pitivi configuration
    """
    default = os.path.join(GLib.get_user_config_dir(), "pitivi")
    path = os.getenv("PITIVI_USER_CONFIG_DIR", default)
    return get_dir(path, autocreate)
Ejemplo n.º 7
0
    def import_old_xml_store(self):
        import xml.etree.ElementTree as et
        userdir = os.getenv('GNOME22_USER_DIR')
        if userdir:
            filename = os.path.join(userdir, 'gedit/gedit-tools.xml')
        else:
            filename = os.path.join(GLib.get_user_config_dir(), 'gedit/gedit-tools.xml')

        if not os.path.isfile(filename):
            return

        print("External tools: importing old tools into the new store...")

        xtree = et.parse(filename)
        xroot = xtree.getroot()

        for xtool in xroot:
            for i in self.tree.tools:
                if i.name == xtool.get('label'):
                    tool = i
                    break
            else:
                tool = Tool(self.tree)
                tool.name = xtool.get('label')
                tool.autoset_filename()
                self.tree.tools.append(tool)
            tool.comment = xtool.get('description')
            tool.shortcut = xtool.get('accelerator')
            tool.applicability = xtool.get('applicability')
            tool.output = xtool.get('output')
            tool.input = xtool.get('input')

            tool.save_with_script(xtool.text)
Ejemplo n.º 8
0
    def getConfigFile(self):
        try:
            from gi.repository import GLib
            configdirs = [GLib.get_user_config_dir()] + GLib.get_system_config_dirs()
            for configdir in configdirs:
                config = os.path.join(configdir, 'mtsend', 'mtsend.ini')
                print("Looking for configuration file %s" % config)
                if os.path.exists(config):
                    break
            assert(os.path.exists(config))
        except:
            try:
                config = os.path.join(os.environ['XDG_CONFIG_HOME'], 'mtsend', 'mtsend.ini');
                print("Looking for configuration file %s" % config)
                assert(os.path.exists(config));
            except:
                try:
                    config = os.path.join(os.environ['HOME'], '.config', 'mtsend', 'mtsend.ini')
                    print("Looking for configuration file %s" % config)
                    assert(os.path.exists(config));
                except:
                    try:
                        config = os.path.join(os.environ['HOME'], '.mtsendrc')
                        print("Looking for configuration file %s" % config)
                        assert(os.path.exists(config))
                    except:
                        config = 'mtsend.ini'
                        print("Looking for configuration file %s" % config)

        if os.access(config, os.R_OK):
            print("Using configuration file %s" % config)
        else:
            raise Exception('Configuration file doesn\'t exist or is not readable')

        return config
Ejemplo n.º 9
0
def check_backend():
    force_ini = os.path.exists(os.path.join(GLib.get_user_config_dir(), "meld", "use-rc-prefs"))
    if force_ini:
        # TODO: Use GKeyfileSettingsBackend once available (see bgo#682702)
        print("Using a flat-file settings backend is not yet supported")
        return None
    return None
Ejemplo n.º 10
0
    def __init__(self, appinfo, autostart_desktop_filename="", exec_cmd="", extra_exec_args=""):
        if appinfo:
            self._desktop_file = appinfo.get_filename()
            self._autostart_desktop_filename = autostart_desktop_filename or os.path.basename(self._desktop_file)
            self._create_file = False
        elif autostart_desktop_filename:
            self._desktop_file = None
            self._autostart_desktop_filename = autostart_desktop_filename
            self._create_file = True
        else:
            raise Exception("Need either an appinfo or a file name")

        self._exec_cmd = exec_cmd
        self._extra_exec_args = " %s\n" % extra_exec_args

        user_autostart_dir = os.path.join(GLib.get_user_config_dir(), "autostart")
        if not os.path.isdir(user_autostart_dir):
            try:
                os.makedirs(user_autostart_dir)
            except:
                logging.critical("Could not create autostart dir: %s" % user_autostart_dir)

        self._user_autostart_file = os.path.join(user_autostart_dir, self._autostart_desktop_filename)

        if self._desktop_file:
            logging.debug("Found desktop file: %s" % self._desktop_file)
        logging.debug("User autostart desktop file: %s" % self._user_autostart_file)
Ejemplo n.º 11
0
    def do_gtk_bookmarks(self):
        if self.showGTKBookmarks:
            bookmarksFile = os.path.join(GLib.get_user_config_dir(), "gtk-3.0", "bookmarks")
            if not os.path.exists(bookmarksFile):
                bookmarksFile = os.path.join(GLib.get_home_dir(), ".gtk-bookmarks")
            if not os.path.exists(bookmarksFile):
                return
            bookmarks = []
            with open(bookmarksFile, "r") as f:
                for line in f:
                    #line = line.replace('file://', '')
                    line = line.rstrip()
                    if not line:
                        continue
                    parts = line.split(' ', 1)

                    if len(parts) == 2:
                        path, name = parts
                    elif len(parts) == 1:
                        path = parts[0]
                        name = os.path.basename(os.path.normpath(path))
                    bookmarks.append((name, path))

            for name, path in bookmarks:
                name = unquote(name)
                currentbutton = easyButton("folder", self.iconsize, [name], -1, -1)
                currentbutton.connect("clicked", self.launch_gtk_bookmark, path)
                currentbutton.show()
                self.placesBtnHolder.pack_start(currentbutton, False, False, 0)
Ejemplo n.º 12
0
def get_config_dir():
	"""
	Returns ~/.config, %APPDATA% or whatever has user set as
	configuration directory.
	"""
	if is_portable():
		return os.environ["XDG_CONFIG_HOME"]
	if IS_WINDOWS and not IS_XP:
		try:
			import windows
			return windows.get_unicode_home()
		except Exception:
			pass
	confdir = GLib.get_user_config_dir()
	if confdir is None or IS_XP:
		if IS_WINDOWS:
			if "LOCALAPPDATA" in os.environ:
				# W7 and later
				confdir = os.environ["LOCALAPPDATA"]
			elif "APPDATA" in os.environ:
				# XP
				from ctypes import cdll
				os_encoding = 'cp' + str(cdll.kernel32.GetACP())
				confdir = os.environ["APPDATA"].decode(os_encoding)
			else:
				# 95? :D
				confdir = os.path.expanduser("~/.config")
		else:
			# Linux
			confdir = os.path.expanduser("~/.config")
	return confdir
Ejemplo n.º 13
0
    def __init__(self):
        GObject.GObject.__init__(self)
        self.icons = {}
        self.count = 0

        # Some apps don't put a default icon in the default theme folder, so we will search all themes
        # def createTheme(d):
        #     theme = Gtk.IconTheme()
        #     theme.set_custom_theme(d)
        #     return theme

        # This takes to much time and there are only a very few applications that use icons from different themes
        #self.themes = map( createTheme, [d for d in os.listdir("/usr/share/icons") if os.path.isdir(os.path.join("/usr/share/icons", d))])

        self.defaultTheme = Gtk.IconTheme.get_default()
        #defaultKdeTheme = createTheme("kde.default")

        # Setup and clean up the temp icon dir
        configDir = GLib.get_user_config_dir()
        self.iconDir = os.path.join(configDir, "mintmenu")
        if not os.path.exists(self.iconDir):
            os.makedirs(self.iconDir)
        contents = os.listdir(self.iconDir)
        for fn in contents:
            os.remove(os.path.join(self.iconDir, fn))

        self.defaultTheme.append_search_path(self.iconDir)
        # Themes with the same content as the default them aren't needed
        #self.themes = [theme for theme in self.themes if  theme.list_icons() != defaultTheme.list_icons()]

        #self.themes = [self.defaultTheme, defaultKdeTheme]
        self.themes = [self.defaultTheme]
Ejemplo n.º 14
0
    def __init__(self, **kwargs):
        super(HistoryCombo, self).__init__(**kwargs)

        if sys.platform == "win32":
            pref_dir = os.path.join(os.getenv("APPDATA"), "Meld")
        else:
            pref_dir = os.path.join(GLib.get_user_config_dir(), "meld")

        if not os.path.exists(pref_dir):
            os.makedirs(pref_dir)

        self.history_file = os.path.join(pref_dir, "history.ini")
        self.config = configparser.RawConfigParser()
        if os.path.exists(self.history_file):
            self.config.read(self.history_file)

        self.set_model(Gtk.ListStore(str, str))
        rentext = Gtk.CellRendererText()
        rentext.props.width_chars = 60
        rentext.props.ellipsize = Pango.EllipsizeMode.END
        self.pack_start(rentext, True)
        self.add_attribute(rentext, 'text', 0)

        self.connect('notify::history-id',
                     lambda *args: self._load_history())
        self.connect('notify::history-length',
                     lambda *args: self._load_history())
    def get_autostart(filename, defaults=None):
        if not defaults:
            defaults = {}
        autostart = os.path.join(GLib.get_user_config_dir(), 'autostart')
        if not os.path.exists(autostart):
            os.makedirs(autostart)
        keyfile = GLib.KeyFile.new()

        dirs = [autostart]
        for directory in (GLib.get_system_config_dirs()):
            dirs.append(os.path.join(directory, 'autostart'))

        try:
            keyfile.load_from_dirs(filename, dirs,
                                   GLib.KeyFileFlags.KEEP_TRANSLATIONS)
        except GLib.Error:
            pass

        for key in defaults.keys():
            try:
                if keyfile.get_value("Desktop Entry", key) is None:
                    keyfile.set_value("Desktop Entry", key, defaults[key])
            except GLib.Error:
                keyfile.set_value("Desktop Entry", key, defaults[key])

        return keyfile
Ejemplo n.º 16
0
    def set_locations(self, datadir):
        self.locations = []

        if platform.platform() != 'Windows':
            for d in self.get_xdg_data_dirs():
                self.locations.append(os.path.join(d, 'gedit', 'plugins', 'externaltools', 'tools'))

        self.locations.append(datadir)

        # self.locations[0] is where we save the custom scripts
        if platform.platform() == 'Windows':
            toolsdir = os.path.expanduser('~/gedit/tools')
        else:
            userdir = os.getenv('GNOME22_USER_DIR')
            if userdir:
                toolsdir = os.path.join(userdir, 'gedit/tools')
            else:
                toolsdir = os.path.join(GLib.get_user_config_dir(), 'gedit/tools')

        self.locations.insert(0, toolsdir);

        if not os.path.isdir(self.locations[0]):
            os.makedirs(self.locations[0])
            self.tree = ToolDirectory(self, '')
            self.import_old_xml_store()
        else:
            self.tree = ToolDirectory(self, '')
Ejemplo n.º 17
0
    def do_activate(self):
        if platform.platform() == 'Windows':
            userdir = os.path.expanduser('~/gedit/latex')
        else:
            userdir = os.path.join(GLib.get_user_config_dir(), 'gedit/latex')

        #check if running from srcdir and if so, prefer that for all data files
        me = os.path.realpath(os.path.dirname(__file__))
        if os.path.exists(os.path.join(me, "..", "configure.ac")):
            sysdir = os.path.abspath(os.path.join(me, "..", "data"))
        else:
            sysdir = self.plugin_info.get_data_dir()

        Resources().set_dirs(userdir, sysdir)
        
        #The following is needed to support gedit 3.12 new menu api.
        #It adds menus and shortcuts here.
        #Actions and toolbar construction are still done in windowactivatable.py.
        
        self._tool_preferences = ToolPreferences()
        self._tool_preferences.connect("tools-changed", self._on_tools_changed)
        
        self.add_latex_menu()
        self.add_latex_tools_menu()
        self.init_tools()
Ejemplo n.º 18
0
    def save(self):
        if self.user_equals_system():
            old_app = self.app
            self.app = os.path.join(self.system_position, self.basename)
            os.remove(old_app)
            self.key_file = GLib.KeyFile.new()
            if self.key_file.load_from_file(self.app, KEYFILE_FLAGS):
                self.load()
            self.save_done_success()
            return False

        try:
            key_file = GLib.KeyFile.new()

            if self.user_position == None:
                self.user_position = os.path.join(GLib.get_user_config_dir(), "autostart")
                self.path = os.path.join(self.user_position, self.basename)
                key_file.load_from_file(os.path.join(self.system_position, self.basename), KEYFILE_FLAGS)
            else:
                key_file.load_from_file(self.path, KEYFILE_FLAGS)
        except:
            key_file.set_string(D_GROUP, GLib.KEY_FILE_DESKTOP_KEY_TYPE, "Application")
            key_file.set_string(D_GROUP, GLib.KEY_FILE_DESKTOP_KEY_EXEC, "/bin/false")

        if "enabled" in self.save_mask.contents:
            key_file.set_boolean(D_GROUP, "X-GNOME-Autostart-enabled", self.enabled)

        if "no-display" in self.save_mask.contents:
            key_file.set_boolean(D_GROUP, GLib.KEY_FILE_DESKTOP_KEY_NO_DISPLAY, self.no_display)

        if "hidden" in self.save_mask.contents:
            key_file.set_boolean(D_GROUP, GLib.KEY_FILE_DESKTOP_KEY_HIDDEN, self.hidden)

        if "name" in self.save_mask.contents:
            locale = self.get_locale()
            if locale:
                key_file.set_locale_string(D_GROUP, GLib.KEY_FILE_DESKTOP_KEY_NAME, locale, self.name)
            else:
                key_file.set_string(D_GROUP, GLib.KEY_FILE_DESKTOP_KEY_NAME, self.name)

        if "comment" in self.save_mask.contents:
            locale = self.get_locale()
            if locale:
                key_file.set_locale_string(D_GROUP, GLib.KEY_FILE_DESKTOP_KEY_COMMENT, locale, self.comment)
            else:
                key_file.set_string(D_GROUP, GLib.KEY_FILE_DESKTOP_KEY_COMMENT, self.comment)

        if "command" in self.save_mask.contents:
            key_file.set_string(D_GROUP, GLib.KEY_FILE_DESKTOP_KEY_EXEC, self.command)

        if "delay" in self.save_mask.contents:
            key_file.set_string(D_GROUP, "X-GNOME-Autostart-Delay", self.delay)

        key_file.save_to_file(self.path)
        self.app = self.path
        self.key_file = key_file
        self.save_done_success()

        return False
Ejemplo n.º 19
0
	def get_app_config_directory (self):
		data_dir = GLib.get_user_config_dir()
		app_dir = data_dir+"/test-app"

		if not os.path.isdir(app_dir):
			os.mkdir (app_dir)

		return app_dir
Ejemplo n.º 20
0
def get_config_dir():
    """Return the directory where the user's config is stored. This varies
    depending on platform."""

    config_dir = os.path.join(GLib.get_user_config_dir(), "gaphor")
    os.makedirs(config_dir, exist_ok=True)

    return config_dir
 def start_load_config(self):
     confdir = GLib.get_user_config_dir()
     if not confdir: confdir = os.path.expanduser("~/.config")
     conffile = os.path.join(confdir, "syncthing", "config.xml")
     if not os.path.isfile(conffile):
         print "Couldn't find config file."
     f = Gio.file_new_for_path(conffile)
     f.load_contents_async(None, self.finish_load_config)
    def __init__(self, assistant):
        Page.__init__(self, assistant)

        config_dir = GLib.get_user_config_dir()
        self.repositories = os.path.join(
                config_dir, 'baserock-installer', 'repos')

        self.worker = None
        self.idle_id = 0
        self.download_completed = False

        self.title, box = self.start_section('Downloading Release')
        text = self.create_text(
                'Depending on your internet connection, this may take '
                'some time. You will, however, get a Baserock system that '
                'provides a traceable and controlled runtime or development '
                'environment. Among many other things, this helps in '
                'spotting, diagnosing and fixing problems as at any time '
                'it is clear how exactly the system is configured.')
        box.pack_start(text, False, False, 0)

        grid = Gtk.Grid()
        grid.set_column_spacing(12)
        grid.set_row_spacing(6)
        grid.show()
        box.pack_start(grid, False, True, 0)

        label = Gtk.Label('Current File:')
        label.set_halign(Gtk.Align.START)
        label.show()
        grid.attach(label, 0, 1, 1, 1)

        self.item_progress = Gtk.ProgressBar()
        self.item_progress.set_hexpand(True)
        self.item_progress.show()
        grid.attach(self.item_progress, 0, 2, 1, 1)

        label = Gtk.Label('Total:')
        label.set_halign(Gtk.Align.START)
        label.show()
        grid.attach(label, 0, 3, 1, 1)

        self.total_progress = Gtk.ProgressBar()
        self.total_progress.show()
        grid.attach(self.total_progress, 0, 4, 1, 1)

        self.numbers_label = Gtk.Label()
        self.numbers_label.set_halign(Gtk.Align.START)
        self.numbers_label.show()
        grid.attach(self.numbers_label, 0, 5, 1, 1)

        self.downloader = FileDownload()
        self.downloader.connect('download-error', self.download_error)
        self.downloader.connect('download-progress', self.download_progress)
        self.downloader.connect('download-finished', self.download_finished)
        self.downloader.excluded_mime_types.add('text/html')

        self.reset()
Ejemplo n.º 23
0
 def __edit_lua_cb(self, widget):
     import shutil
     path = os.path.join(GLib.get_user_config_dir(), "ibus", "libpinyin")
     os.path.exists(path) or os.makedirs(path)
     path = os.path.join(path, "user.lua")
     if not os.path.exists(path):
         src = os.path.join(pkgdatadir, "user.lua")
         shutil.copyfile(src, path)
     os.system("xdg-open %s" % path)
Ejemplo n.º 24
0
 def __edit_symbol_cb(self, widget, filename):
     import shutil
     path = os.path.join(GLib.get_user_config_dir(), "ibus", "libzhuyin")
     os.path.exists(path) or os.makedirs(path)
     path = os.path.join(path, filename)
     if not os.path.exists(path):
         src = os.path.join(pkgdatadir, filename)
         shutil.copyfile(src, path)
     os.system("xdg-open %s" % path)
Ejemplo n.º 25
0
def get_config_dir():
	"""
	Returns ~/.config, %APPDATA% or whatever has user set as
	configuration directory.
	"""
	confdir = GLib.get_user_config_dir()
	if confdir is None:
		confdir = os.path.expanduser("~/.config")
	return confdir
Ejemplo n.º 26
0
 def on_menu_button_clicked(self, widget):
     if self.advanced_mode:
         self.mode_button.set_label(AdvancedMode)
         self.on_normal_mode()
     else:
         self.mode_button.set_label(NormalMode)
         self.on_advanced_mode()
     touch(os.path.join(GLib.get_user_config_dir(), ".cs_no_default"))
     return True
 def start_load_config(self):
     confdir = GLib.get_user_config_dir()
     if not confdir:
         confdir = os.path.expanduser('~/.config')
     conffile = os.path.join(confdir, 'syncthing', 'config.xml')
     if not os.path.isfile(conffile):
         log.error('start_load_config: Couldn\'t find config file.')
     f = Gio.file_new_for_path(conffile)
     f.load_contents_async(None, self.finish_load_config)
Ejemplo n.º 28
0
def xdg_get_config_home():
    if os.name == "nt":
        from gi.repository import GLib
        return glib2fsn(GLib.get_user_config_dir())

    data_home = os.getenv("XDG_CONFIG_HOME")
    if data_home:
        return os.path.abspath(data_home)
    else:
        return os.path.join(os.path.expanduser("~"), ".config")
Ejemplo n.º 29
0
        def do_activate(self):
                # Initialize snippets library
                library = Library()

                if platform.system() == 'Windows':
                        snippetsdir = os.path.expanduser('~/gedit/snippets')
                else:
                        snippetsdir = os.path.join(GLib.get_user_config_dir(), 'gedit/snippets')

                library.set_dirs(snippetsdir, self.system_dirs())
Ejemplo n.º 30
0
    def do_activate(self):
        self._path = os.path.dirname(__file__)

        if not self._path in sys.path:
            sys.path.insert(0, self._path)

        commands.Commands().set_dirs([
            os.path.join(GLib.get_user_config_dir(), 'gedit/commander/modules'),
            os.path.join(self.plugin_info.get_data_dir(), 'modules')
        ])
Ejemplo n.º 31
0
gettext.install('pyfbdown', localedir=get_correct_path('locale'))

authors_ = ["Youssef Sourani <*****@*****.**>"]
version_ = "1.0"
copyright_ = "Copyright © 2020 Youssef Sourani"
comments_ = "Facebook Videos Downloader"
website_ = "https://github.com/yucefsourani/pyfbdown"
translators_ = "Arabic Yucef Sourani"
appname = "pyfbdown"
appwindowtitle = "PyFBDown"
appid = "com.github.yucefsourani.pyfbdown"
icon_ = get_correct_path("pixmaps/com.github.yucefsourani.pyfbdown.png")
if not os.path.isfile(icon_):
    icon_ = None

default_metadata_file_name = os.path.join(GLib.get_user_config_dir(),
                                          "pyfbdown.json")


def get_metadata_info():
    if not os.path.isfile(default_metadata_file_name):
        default_metadata_dict = json.loads(default_metadata)
        with open(default_metadata_file_name, "w", encoding="utf-8") as mf:
            json.dump(default_metadata_dict, mf, indent=4)
        return get_metadata_info()
    try:
        with open(default_metadata_file_name, encoding="utf-8") as mf:
            result = json.load(mf)
    except Exception as e:
        print(e)
        return False
Ejemplo n.º 32
0
 def get_user_autostart_files():
     return glob.glob(
         os.path.join(GLib.get_user_config_dir(), "autostart", "*.desktop"))
Ejemplo n.º 33
0
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    OCRFeeder is distributed in the hope that it will be useful,
    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 OCRFeeder.  If not, see <http://www.gnu.org/licenses/>.
"""
OCRFEEDER_STUDIO_COMMENTS = 'The complete OCR suite.'

# DIRECTORIES
USER_CONFIG_DIR = os.path.join(GLib.get_user_config_dir(),
                               OCRFEEDER_COMPACT_NAME)
DEFAULT_SYSTEM_APP_DIR = os.path.join('/usr/local', 'share', 'ocrfeeder')
APP_DIR = DEFAULT_SYSTEM_APP_DIR
RESOURCES_DIR = APP_DIR

# If the path does not exist (devel setup) set the
# APP_DIR and RESOURCES_DIR to local paths
_dirname = os.path.abspath(os.path.dirname(__file__))
if not os.path.exists(APP_DIR) or not _dirname.startswith('/usr/local'):
    APP_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
    RESOURCES_DIR = os.path.join(APP_DIR, '../../resources')
RESOURCES_DIR = os.path.abspath(RESOURCES_DIR)

# I18N
DEFAULT_LANGUAGES = os.environ.get('LANGUAGE', '').split(':')
Ejemplo n.º 34
0
from gi.repository import GLib, GObject

import util
import prefs

day = datetime.timedelta(1, 0, 0)
EXPIRE_TIME = 30 * day

DEFAULT_GROUP_CODE = "Warpinator"
KEYFILE_GROUP_NAME = "warpinator"
KEYFILE_CODE_KEY = "code"
KEYFILE_UUID_KEY = "connect_id"
CONFIG_FILE_NAME = ".group"

CONFIG_FOLDER = os.path.join(GLib.get_user_config_dir(), "warpinator")

singleton = None


def get_singleton():
    global singleton

    if singleton == None:
        singleton = AuthManager()

    return singleton


class AuthManager(GObject.Object):
    __gsignals__ = {
Ejemplo n.º 35
0
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import os
from ConfigParser import ConfigParser

from gi.repository import Gtk, GLib, Gio, Gdk

import ui.style
from ui.window import Window
from fakegarmin import FakeGarmin
from garmin import Garmin
from devicequeue import GarminQueue

CONFIG_PATH = os.path.join(GLib.get_user_config_dir(), 'fuga', 'fuga.ini')


class Fuga(Gtk.Application):
    def __init__(self):
        Gtk.Application.__init__(self,
                                 application_id='com.jonnylamb.Fuga',
                                 flags=Gio.ApplicationFlags.FLAGS_NONE)

        GLib.set_application_name('Fuga')

        self.connect('activate', self.activate_cb)

        self.config = self.create_config()

        ui.style.setup()
Ejemplo n.º 36
0
	def missing_host_key(self, client, hostname, key):
		host_key_fingerprint = 'sha256:' + base64.b64encode(hashlib.new('sha256', key.asbytes()).digest()).decode('utf-8')
		host_keys = paramiko.hostkeys.HostKeys()
		host_keys_modified = False
		known_hosts_file = self.application.config.get('ssh_known_hosts_file', os.path.join(GLib.get_user_config_dir(), 'king-phisher', 'known_hosts'))

		if os.access(known_hosts_file, os.R_OK):
			host_keys.load(known_hosts_file)

		if host_keys.lookup(hostname):
			if host_keys.check(hostname, key):
				self.logger.debug("accepting known ssh host key {0} {1} {2}".format(hostname, key.get_name(), host_key_fingerprint))
				return
			self.logger.warning("ssh host key does not match known value for {0}".format(hostname))
			dialog = HostKeyWarnDialog(self.application, hostname, key)
			if dialog.interact() != Gtk.ResponseType.ACCEPT:
				raise errors.KingPhisherAbortError('bad ssh host key for ' + hostname)
		else:
			dialog = HostKeyAcceptDialog(self.application, hostname, key)
			if dialog.interact() != Gtk.ResponseType.ACCEPT:
				raise errors.KingPhisherAbortError('unknown ssh host key not accepted by the user for ' + hostname)
			host_keys.add(hostname, key.get_name(), key)
			host_keys_modified = True

		if host_keys_modified:
			try:
				host_keys.save(known_hosts_file)
				os.chmod(known_hosts_file, 0o600)
			except (IOError if its.py_v2 else PermissionError):
				self.logger.warning('failed to save the known_hosts file and set its permissions')
Ejemplo n.º 37
0
class GrammalecteConfig(DictConfig):
    """
    A Grammalecte configuration for a given document.

    This configuration inherits from user and system configuration, if
    available.

    :Example:

    >>> config = GrammalecteConfig()

    >>> config.get_value(GrammalecteConfig.ANALYZE_WAIT_TICKS)
    12

    >>> config.set_value("top/sub", ["zero", {"1st": "1", "other": "yes"}])

    >>> config.get_value("top/sub/1/other")
    'yes'
    """
    __gtype_name__ = "GrammalecteConfig"

    ############
    # ALL CONFIGURATION CONSTANTS ARE HERE
    ############
    LOCALE_DIR = "locale-dir"
    ANALYZE_OPTIONS = "analyze-options"
    AUTO_ANALYZE_ACTIVE = "auto-analyze-active"
    ANALYZE_PARALLEL_COUNT = "analyze-parallel-count"
    ANALYZE_WAIT_TICKS = "analyze-wait-ticks"
    IGNORED_RULES = "ign-rules"
    IGNORED_ERRORS = "ign-errors"
    CONCAT_LINES = "concat-lines"

    __DEFAULT_CONFIG = {
        ANALYZE_OPTIONS: {},
        AUTO_ANALYZE_ACTIVE: False,
        ANALYZE_PARALLEL_COUNT: 1,
        ANALYZE_WAIT_TICKS: 12,
        IGNORED_RULES: [],
        IGNORED_ERRORS: [],
        CONCAT_LINES: True,
    }

    __GEDIT_CONFIG_FILE = "/gedit/grammalecte.conf"
    __SYSTEM_CONFIG_FILE = "/etc" + __GEDIT_CONFIG_FILE
    __USER_CONFIG_FILE = GLib.get_user_config_dir() + __GEDIT_CONFIG_FILE

    __globalInstance: Optional[DictConfig] = None

    def __init__(self, selfConfig: Optional[SelfConfigContainer] = None) -> None:
        """
        Initialize the plugin configuration.

        :param selfConfig: (optional) the selfConfig container.
        """
        # Initialize global instance
        if GrammalecteConfig.__globalInstance is None:
            defaultConfig = DictConfig(GrammalecteConfig.__DEFAULT_CONFIG)
            systemConfig = DictConfig(
                GrammalecteConfig.__SYSTEM_CONFIG_FILE, defaultConfig)
            GrammalecteConfig.__globalInstance = DictConfig(
                GrammalecteConfig.__USER_CONFIG_FILE, systemConfig)

        # Initialize local instance
        DictConfig.__init__(
            self, selfConfig, GrammalecteConfig.__globalInstance)

    @staticmethod
    def terminate() -> None:
        """
        Terminate usage of all configurations.

        This will save global configuration files if needed.
        """
        if GrammalecteConfig.__globalInstance is not None:
            GrammalecteConfig.__globalInstance.save()
            GrammalecteConfig.__globalInstance = None
 def save_screensaver_autostart(self):
     filename = os.path.join(GLib.get_user_config_dir(), 'autostart',
                             'screensaver-settings.desktop')
     autostart = self.get_screensaver_autostart()
     autostart.save_to_file(filename)
Ejemplo n.º 39
0
import os
import xml.dom.minidom
import gi

gi.require_version('Gtk', '3.0')
gi.require_version('MateMenu', '2.0')
from gi.repository import GLib, Gtk, Gdk, GdkPixbuf

print("user data dir: " + GLib.get_user_data_dir())
print("user config dir: " + GLib.get_user_config_dir())
Ejemplo n.º 40
0
# -*- coding: utf-8 -*-
# SPDX-FileCopyrightText: 2016-2022 Mufeed Ali <*****@*****.**>
# SPDX-License-Identifier: GPL-3.0-or-later
"""utils contains a few global variables and essential functions."""
import logging
import os
import traceback

from gi.repository import GLib

RES_PATH = "/com/github/fushinari/Wordbook"

CONFIG_DIR = os.path.join(GLib.get_user_config_dir(), "wordbook")
CONFIG_FILE = os.path.join(CONFIG_DIR, "wordbook.conf")
DATA_DIR = os.path.join(GLib.get_user_data_dir(), "wordbook")
CDEF_DIR = os.path.join(DATA_DIR, "cdef")
WN_DIR = os.path.join(DATA_DIR, "wn")

logging.basicConfig(
    format=
    "%(asctime)s - [%(levelname)s] [%(threadName)s] (%(module)s:%(lineno)d) %(message)s"
)
LOGGER = logging.getLogger()


def boot_to_str(boolean):
    """Convert boolean to string for configuration parser."""
    if boolean is True:
        return "yes"
    return "no"
Ejemplo n.º 41
0
def xdg_config_home():
    return os.path.join(GLib.get_user_config_dir(), "flowblade")
 def save_light_locker_autostart(self):
     filename = os.path.join(GLib.get_user_config_dir(), 'autostart',
                             'light-locker.desktop')
     autostart = self.get_light_locker_autostart()
     autostart.save_to_file(filename)
Ejemplo n.º 43
0
def get_user_config_dir():
    """Like g_get_user_config_dir(), but always unicode"""
    d_fs = GLib.get_user_config_dir()
    return filename_to_unicode(d_fs)
Ejemplo n.º 44
0
#!/usr/bin/python3

import os
import json
import time
import re

from gi.repository import GLib, GObject, Gtk

CONFIG_DIR = os.path.join(GLib.get_user_config_dir(), 'sticky')
CONFIG_PATH = os.path.join(CONFIG_DIR, 'notes.json')
SAVE_DELAY = 3

backup_file_name = re.compile(r"\Abackup-[0-9]{10,}\.json$", re.IGNORECASE)


class FileHandler(GObject.Object):
    @GObject.Signal(flags=GObject.SignalFlags.RUN_LAST,
                    return_type=bool,
                    arg_types=(str, ),
                    accumulator=GObject.signal_accumulator_true_handled)
    def group_changed(self, group_name):
        pass

    @GObject.Signal(flags=GObject.SignalFlags.RUN_LAST,
                    return_type=bool,
                    accumulator=GObject.signal_accumulator_true_handled)
    def lists_changed(self):
        pass

    def __init__(self, settings):