Beispiel #1
0
def get_download_folder():
    '''获取下载文件夹'''

    download_folder = glib.get_user_special_dir(glib.USER_DIRECTORY_MUSIC)
    if download_folder is None:
        download_folder = os.path.expanduser("~/Music")
    return download_folder
Beispiel #2
0
    def take_picture(self):
        """take_picture - grab a frame from the web cam and save it to
        ~/Pictures/datestamp.png, where datestamp is the current datestamp.
        It's possible to add a prefix to the datestamp by setting the
        filename_prefix property. 

        If play is not called before take_picture,
        an error may occur. If take_picture is called immediately after play,
        the camera may not be fully initialized, and an error may occur.        
    
        Connect to the signal "image-captured" to be alerted when the picture
        is saved.

        This function has no arguments

        returns - a string of the filename used to save the image
        
        """

        stamp = str(datetime.datetime.now())
        extension = ".jpg"  #".png"
        directory = glib.get_user_special_dir(glib.USER_DIRECTORY_PICTURES)
        self.filename = directory + self.filename_prefix + stamp + extension
        self.camerabin.set_property("filename", self.filename)
        self.camerabin.emit("capture-start")
        return self.filename
 def __choose_dir(self, widget, data=None):
     dr = glib.get_user_special_dir(glib.USER_DIRECTORY_PICTURES)
     response, directory = quickly.prompts.choose_directory("Photobomb Choose Directory", dr)
     if response == gtk.RESPONSE_OK:
         self.directory = directory
         self.clear_buttons()
         self.__get_pics()
    def offer_single_export (self, rec, prefs, mult=1, parent=None):
        """Offer to export a single file.

        Return the filename if we have in fact exported said file.
        """
        default_extension = prefs.get('save_recipe_as','html')
        # strip the period if one ended up on our default extension
        if default_extension and default_extension[0]=='.':
            default_extension = default_extension[1:]
        exp_directory = prefs.get('rec_exp_directory',
                                  get_user_special_dir(USER_DIRECTORY_DOCUMENTS)
                                  )
        filename,exp_type = de.saveas_file(_('Save recipe as...'),
                                           filename='%s%s%s%s%s'%(exp_directory,
                                                                  os.path.sep,
                                                                  rec.title,
                                                                  os.path.extsep,
                                                                  default_extension),
                                           filters=self.get_single_filters(),
                                           parent=parent
                                           )
        if not filename: return
        if not exp_type or not self.can_export_type(exp_type):
            de.show_message(label=_('Gourmet cannot export file of type "%s"')%os.path.splitext(filename)[1])
            return
        return self.do_single_export(rec, filename, exp_type, mult)
def copyFileFromServer(strFileName):
    # File resides on server itself
    try:
        FileToBeCopied = open(strFileName+".txt", "r")
    except IOError:
        return "File not found."
    
    # File to be "copied" (downloaded) to Downloads folder
    try:
        # locate Downloads directory on local system
        downloadsDir = glib.get_user_special_dir(glib.USER_DIRECTORY_DOWNLOAD)
        NewFile = open(os.path.join(downloadsDir+"/"+strFileName+".txt"), 'w')
    except IOError:
        return "Error in downloading file."

    # Both files are open, hence begin copying
    string = FileToBeCopied.read()
    NewFile.write(string)
    
    FileToBeCopied.close()
    NewFile.close()
    
    if not FileToBeCopied.closed and not NewFile.closed:
        return "Error in downloading file."
    else:
        return "Download complete."
Beispiel #6
0
    def offer_multiple_export(self, recs, prefs, parent=None, prog=None):
        """Offer user a chance to export multiple recipes at once.

        Return the exporter class capable of doing this and a
        dictionary of arguments for the progress dialog.
        """
        if len(recs) < 950:
            # inelegantly avoid bug that happens when this code runs
            # on large numbers of recipes. The good news is that this
            # that that will almost only ever happen when we're
            # exporting all recipes, which makes this code irrelevant
            # anyway.
            self.app.rd.include_linked_recipes(recs)
        ext = prefs.get("save_recipes_as", "%sxml" % os.path.extsep)
        exp_directory = prefs.get("rec_exp_directory", get_user_special_dir(USER_DIRECTORY_DOCUMENTS))
        fn, exp_type = de.saveas_file(
            _("Export recipes"),
            filename="%s%s%s%s" % (exp_directory, os.path.sep, _("recipes"), ext),
            parent=parent,
            filters=self.get_multiple_filters(),
        )
        if fn:
            prefs["rec_exp_directory"] = os.path.split(fn)[0]
            prefs["save_recipes_as"] = os.path.splitext(fn)[1]
            instance = self.do_multiple_export(recs, fn, exp_type)
            if not instance:
                de.show_message(
                    okay=gtk.STOCK_CLOSE,
                    cancel=False,
                    label=_('Unable to export: unknown filetype "%s"' % fn),
                    sublabel=_("Please make sure to select a filetype from the dropdown menu when saving."),
                    message_type=gtk.MESSAGE_ERROR,
                )
                return
            return instance
Beispiel #7
0
    def show(self, filelist):
        self.filelist = filelist

        self.view.set_model(None)
        self.model.clear()

        self.add(os.path.expanduser('~'))
        self.add(glib.get_user_special_dir(glib.USER_DIRECTORY_DESKTOP))
        self.add('trash:///')
        self.add('computer:///root.link')
        self.add('network:///')

        for l in open('/home/bobrov/.gtk-bookmarks'):
            self.add(l.strip())

        self.view.set_model(self.model)

        self.view.set_cursor((0,))

        w, h = self.view.size_request()
        if h != 0:
            self.sw.set_size_request(-1, max(200, min(h + 5, 300)))

        self.window.resize(*self.window.size_request())
        self.window.set_transient_for(filelist.view.get_toplevel())
        self.window.show()
Beispiel #8
0
    def add_folders_and_bookmarks(self):
        self.applet.icons.destroy_all()

        # Destroy all current local bookmark monitors
        for monitor in self.__monitors:
            monitor.cancel()
        self.__monitors = []

        self.add_folder_icon(_("Home Folder"), "user-home", "file://%s" % user_path)

        # Add Desktop
        desktop_path = glib.get_user_special_dir(glib.USER_DIRECTORY_DESKTOP)
        if desktop_path != user_path:
            self.add_folder_icon(glib.filename_display_basename(desktop_path), "user-desktop", "file://%s" % desktop_path)

        # Add XDG user special folders
        for uri in xdg_user_uris:
            self.add_url_name(uri)

        # Add bookmarks
        if os.path.isfile(bookmarks_file):
            with open(bookmarks_file) as f:
                for url_name in (i.rstrip().split(" ", 1) for i in f):
                    if url_name[0] not in xdg_user_uris:
                        self.add_url_name(*url_name)
Beispiel #9
0
    def offer_single_export(self, rec, prefs, mult=1, parent=None):
        """Offer to export a single file.

        Return the filename if we have in fact exported said file.
        """
        default_extension = prefs.get('save_recipe_as', 'html')
        # strip the period if one ended up on our default extension
        if default_extension and default_extension[0] == '.':
            default_extension = default_extension[1:]
        exp_directory = prefs.get(
            'rec_exp_directory',
            get_user_special_dir(USER_DIRECTORY_DOCUMENTS))
        filename, exp_type = de.saveas_file(
            _('Save recipe as...'),
            filename='%s%s%s%s%s' % (exp_directory, os.path.sep, rec.title,
                                     os.path.extsep, default_extension),
            filters=self.get_single_filters(),
            parent=parent)
        if not filename: return
        if not exp_type or not self.can_export_type(exp_type):
            de.show_message(
                label=_('Gourmet cannot export file of type "%s"') %
                os.path.splitext(filename)[1])
            return
        return self.do_single_export(rec, filename, exp_type, mult)
def get_default_download_path():
    try:
        import glib
    except ImportError:
        base = os.path.expandvars("$HOME/Downloads")
    else:
        base = glib.get_user_special_dir(glib.USER_DIRECTORY_DOWNLOAD)
    return os.path.join(base, "NASA-APOD")
Beispiel #11
0
 def __init__(self, parent):
     super(ImageChooser, self).__init__(
         parent, glib.get_user_special_dir(glib.USER_DIRECTORY_PICTURES))
     self.set_title(_("Select an image..."))
     self.add_image_filter()
     image = gtk.image_new_from_stock(gtk.STOCK_CLEAR, gtk.ICON_SIZE_BUTTON)
     buttonclear = self.add_button(_("No image"), self.RESPONSE_CLEAR)
     buttonclear.set_image(image)
     self.add_button(gtk.STOCK_OK, gtk.RESPONSE_OK)
   def __init__(self, FILECHOSEN, FILENAME, CONTAINERCHOICE, AUDIOCODECVALUE, VIDEOCODECVALUE):
       gobject.GObject.__init__(self)
       # create a dictionay taking the Codec/Container values and mapping them with plugin names
       # No asfmux atm, hopefully Soc will solve that

       # Choose plugin based on Codec Name
       audiocaps = codecfinder.codecmap[AUDIOCODECVALUE]
       videocaps = codecfinder.codecmap[VIDEOCODECVALUE]
       self.AudioEncoderPlugin = codecfinder.get_audio_encoder_element(audiocaps)
       self.VideoEncoderPlugin = codecfinder.get_video_encoder_element(videocaps)
       # print "Audio encoder plugin is " + self.AudioEncoderPlugin
       # print "Video encoder plugin is " + self.VideoEncoderPlugin

       # Choose plugin and file suffix based on Container name
       containercaps = codecfinder.containermap[CONTAINERCHOICE]
       self.ContainerFormatPlugin = codecfinder.get_muxer_element(containercaps)
       # print "Container muxer is " + self.ContainerFormatPlugin
       self.ContainerFormatSuffix = codecfinder.csuffixmap[CONTAINERCHOICE]

       # Remove suffix from inbound filename so we can reuse it together with suffix to create outbound filename
       self.FileNameOnly = os.path.splitext(os.path.basename(FILENAME))[0]
       self.VideoDirectory = glib.get_user_special_dir(glib.USER_DIRECTORY_VIDEOS)
       CheckDir = os.path.isdir(self.VideoDirectory)
       if CheckDir == (False):
           os.mkdir(self.VideoDirectory)
       # elif CheckDir == (True):
       #   print "Videos directory exist"
       # print self.VideoDirectory

       # create a variable with a timestamp code
       timeget = datetime.datetime.now()
       text = timeget.strftime("-%H%M%S-%d%m%Y") 
       self.timestamp = str(text)

       self.pipeline = gst.Pipeline("TranscodingPipeline")
       self.pipeline.set_state(gst.STATE_PAUSED)

       self.uridecoder = gst.element_factory_make("uridecodebin", "uridecoder")
       self.uridecoder.set_property("uri", FILECHOSEN)
       # print "File loaded " + FILECHOSEN
       self.uridecoder.connect("pad-added", self.OnDynamicPad)
       self.pipeline.add(self.uridecoder)

       self.containermuxer = gst.element_factory_make(self.ContainerFormatPlugin, "containermuxer")
       self.pipeline.add(self.containermuxer)

       self.transcodefileoutput = gst.element_factory_make("filesink", "transcodefileoutput")
       self.transcodefileoutput.set_property("location", (self.VideoDirectory+self.FileNameOnly+self.timestamp+self.ContainerFormatSuffix))
       self.pipeline.add(self.transcodefileoutput)

       self.containermuxer.link(self.transcodefileoutput)

       self.uridecoder.set_state(gst.STATE_PAUSED)

       self.BusMessages = self.BusWatcher()

       self.uridecoder.connect("no-more-pads", self.noMorePads) # we need to wait on this one before going further
 def __init__ (self,
               title,
               filename=None,
               filters=IMAGE_FILTERS,
               action=gtk.FILE_CHOOSER_ACTION_OPEN,
               set_filter=True,
               buttons=None
               ):
     FileSelectorDialog.__init__(self, title, filename, filters, action, set_filter, buttons)
     self.fsd.set_current_folder(get_user_special_dir(USER_DIRECTORY_PICTURES))
Beispiel #14
0
def set_download_folder():
    downloads_dir = glib.get_user_special_dir(glib.USER_DIRECTORY_DOWNLOAD)
    if downloads_dir:
        # Add any custom folder
        new_path = os.path.join(downloads_dir, CUSTOM_FOLDER)
        if SHOW_DEBUG:
            print "Using automatically detected path:", new_path
    else:
        new_path = DOWNLOAD_PATH
        if SHOW_DEBUG:
            print "Could not determine download folder with GLib. Using default."
    return new_path
Beispiel #15
0
def set_download_folder():
    downloads_dir = glib.get_user_special_dir(glib.USER_DIRECTORY_DOWNLOAD)
    if downloads_dir:
        # Add any custom folder
        new_path = os.path.join(downloads_dir, CUSTOM_FOLDER)
        if SHOW_DEBUG:
            print "Using automatically detected path:", new_path
    else:
        new_path = DOWNLOAD_PATH
        if SHOW_DEBUG:
            print "Could not determine download folder with GLib. Using default."
    return new_path
Beispiel #16
0
def get_old_download_dir():
    if is_windows:
        directory = os.path.join(get_user_home(), "Downloads")
        if os.path.isdir(directory):
            return directory
        # Fallback directory: My documents\Downloads
        mydocs = win32.get_my_documents()  # My Documents
        return os.path.join(mydocs, "Downloads")
    else:
        if GLib:  # GLib should be dependency for POSIX systems
            return GLib.get_user_special_dir(GLib.USER_DIRECTORY_DOWNLOAD)
        return os.path.join(get_user_home(), "Downloads")
def get_old_download_dir():
    if is_windows:
        directory = os.path.join(get_user_home(), "Downloads")
        if os.path.isdir(directory):
            return directory
        # Fallback directory: My documents\Downloads
        mydocs = win32.get_my_documents() # My Documents
        return os.path.join(mydocs, "Downloads")
    else:
        if GLib: # GLib should be dependency for POSIX systems
            return GLib.get_user_special_dir(GLib.USER_DIRECTORY_DOWNLOAD)
        return os.path.join(get_user_home(), "Downloads")
Beispiel #18
0
 def __init__ (self,
               title,
               filename=None,
               filters=IMAGE_FILTERS,
               action=gtk.FILE_CHOOSER_ACTION_OPEN,
               set_filter=True,
               buttons=None
               ):
     FileSelectorDialog.__init__(self, title, filename, filters, action, set_filter, buttons)
     pictures_dir = get_user_special_dir(USER_DIRECTORY_PICTURES)
     if not pictures_dir == None:
         self.fsd.set_current_folder(pictures_dir)
    def download_link(self, push):
        pushes = self.pb.get_pushes(self.last_push)[1]
        if (len(pushes) != 0):
            last_push = pushes[len(pushes)-2]
            if last_push.get("url"):
                url = last_push.get("url")
                filename = self.get_filename_from_url(url)

                downloads_dir = glib.get_user_special_dir(glib.USER_DIRECTORY_DOWNLOAD)
                unique_filename = self.get_unique_filename(filename, downloads_dir)
                unique_filename_full_path = downloads_dir+"/"+unique_filename

                urllib.urlretrieve (url, unique_filename_full_path)
                print "URL: %s Downloaded: %s" % (url, unique_filename_full_path)
            self.last_push = max(self.last_push, last_push.get("created"))
    def __init__(self):
        gobject.GObject.__init__(self)

        if sys.platform == 'win32':
            self.config_dir = os.path.join(os.getenv('APPDATA').decode('mbcs'), 'Reinteract')
        else:
            self.config_dir =  os.path.expanduser(u"~/.reinteract")

        try:
            # Added in pygobject-2.18
            documents_dir = glib.get_user_special_dir(glib.USER_DIRECTORY_DOCUMENTS).decode("UTF-8")
        except AttributeError, e:
            # In a shocking example of cross-platform convergence, ~/Documents
            # is the documents directory on OS X, Windows, and Linux, except
            # when localized
            documents_dir = os.path.expanduser(u"~/Documents")
Beispiel #21
0
    def offer_multiple_export(self, recs, prefs, parent=None, prog=None):
        """Offer user a chance to export multiple recipes at once.

        Return the exporter class capable of doing this and a
        dictionary of arguments for the progress dialog.
        """
        if len(recs) < 950:
            # inelegantly avoid bug that happens when this code runs
            # on large numbers of recipes. The good news is that this
            # that that will almost only ever happen when we're
            # exporting all recipes, which makes this code irrelevant
            # anyway.
            self.app.rd.include_linked_recipes(recs)
        ext = prefs.get('save_recipes_as', '%sxml' % os.path.extsep)
        exp_directory = prefs.get(
            'rec_exp_directory',
            get_user_special_dir(USER_DIRECTORY_DOCUMENTS))
        fn, exp_type = de.saveas_file(
            _("Export recipes"),
            filename="%s%s%s%s" %
            (exp_directory, os.path.sep, _('recipes'), ext),
            parent=parent,
            filters=self.get_multiple_filters())
        if fn:
            prefs['rec_exp_directory'] = os.path.split(fn)[0]
            prefs['save_recipes_as'] = os.path.splitext(fn)[1]
            instance = self.do_multiple_export(recs, fn, exp_type)
            if not instance:
                de.show_message(
                    okay=gtk.STOCK_CLOSE,
                    cancel=False,
                    label=_('Unable to export: unknown filetype "%s"' % fn),
                    sublabel=
                    _('Please make sure to select a filetype from the dropdown menu when saving.'
                      ),
                    message_type=gtk.MESSAGE_ERROR,
                )
                return
            import gourmet.GourmetRecipeManager
            main_app = gourmet.GourmetRecipeManager.get_application()
            print 'Connect', instance, 'to show dialog when done'
            instance.connect(
                'completed',
                lambda *args: main_app.offer_url('Export complete!',
                                                 'Recipes exported to %s' % fn,
                                                 url='file:///%s' % fn))
            return instance
    def offer_multiple_export (self, recs, prefs, parent=None, prog=None):
        """Offer user a chance to export multiple recipes at once.

        Return the exporter class capable of doing this and a
        dictionary of arguments for the progress dialog.
        """
        if len(recs) < 950:
            # inelegantly avoid bug that happens when this code runs
            # on large numbers of recipes. The good news is that this
            # that that will almost only ever happen when we're
            # exporting all recipes, which makes this code irrelevant
            # anyway.
            self.app.rd.include_linked_recipes(recs)
        ext = prefs.get('save_recipes_as','%sxml'%os.path.extsep)
        exp_directory = prefs.get('rec_exp_directory',
                                  get_user_special_dir(USER_DIRECTORY_DOCUMENTS)
                                  )
        fn,exp_type=de.saveas_file(_("Export recipes"),
                                     filename="%s%s%s%s"%(exp_directory,
                                                          os.path.sep,
                                                          _('recipes'),
                                                          ext),
                                     parent=parent,
                                     filters=self.get_multiple_filters())
        if fn:
            prefs['rec_exp_directory']=os.path.split(fn)[0]
            prefs['save_recipes_as']=os.path.splitext(fn)[1]
            instance = self.do_multiple_export(recs, fn, exp_type)
            if not instance:
                de.show_message(
                    okay=gtk.STOCK_CLOSE,
                    cancel=False,
                    label=_('Unable to export: unknown filetype "%s"'%fn),
                    sublabel=_('Please make sure to select a filetype from the dropdown menu when saving.'),
                    message_type=gtk.MESSAGE_ERROR,
                    )
                return
            import gourmet.GourmetRecipeManager
            main_app =  gourmet.GourmetRecipeManager.get_application()
            print 'Connect',instance,'to show dialog when done'
            instance.connect('completed',
                             lambda *args: main_app.offer_url('Export complete!',
                                                              'Recipes exported to %s'%fn,
                                                              url='file:///%s'%fn))
            return instance
    def __init__(self):
        gobject.GObject.__init__(self)

        if sys.platform == 'win32':
            self.config_dir = os.path.join(
                os.getenv('APPDATA').decode('mbcs'), 'Reinteract')
        else:
            self.config_dir = os.path.expanduser(u"~/.reinteract")

        try:
            # Added in pygobject-2.18
            documents_dir = glib.get_user_special_dir(
                glib.USER_DIRECTORY_DOCUMENTS).decode("UTF-8")
        except AttributeError, e:
            # In a shocking example of cross-platform convergence, ~/Documents
            # is the documents directory on OS X, Windows, and Linux, except
            # when localized
            documents_dir = os.path.expanduser(u"~/Documents")
Beispiel #24
0
    def download_link(self, push):
        pushes = self.pb.get_pushes(self.last_push)[1]
        if (len(pushes) != 0):
            last_push = pushes[len(pushes) - 2]
            if last_push.get("url"):
                url = last_push.get("url")
                filename = self.get_filename_from_url(url)

                downloads_dir = glib.get_user_special_dir(
                    glib.USER_DIRECTORY_DOWNLOAD)
                unique_filename = self.get_unique_filename(
                    filename, downloads_dir)
                unique_filename_full_path = downloads_dir + "/" + unique_filename

                urllib.urlretrieve(url, unique_filename_full_path)
                print "URL: %s Downloaded: %s" % (url,
                                                  unique_filename_full_path)
            self.last_push = max(self.last_push, last_push.get("created"))
Beispiel #25
0
def get_download_dir():
    "Return the path to the user's default downloads directory"
    if is_windows:
        # WinVista Win7 and so on:
        # Win32 API does not provides IDs for its new
        # SHGetKnownFolderPath, but it seems the folder name is
        # locale unaware (at least in Win7).
        directory = os.path.join(get_user_home(), "Downloads")
        if os.path.isdir(directory):
            return directory
        # Fallback directory: My documents\Downloads
        mydocs = win32.get_my_documents()  # My Documents
        return mydocs
    else:
        if GLib:  # GLib should be dependency for POSIX systems
            ddir = GLib.get_user_special_dir(GLib.USER_DIRECTORY_DOWNLOAD)
            if ddir:
                return ddir
        return get_user_home()
def get_download_dir():
    "Return the path to the user's default downloads directory"
    if is_windows:
        # WinVista Win7 and so on:
        # Win32 API does not provides IDs for its new
        # SHGetKnownFolderPath, but it seems the folder name is
        # locale unaware (at least in Win7).
        directory = os.path.join(get_user_home(), "Downloads")
        if os.path.isdir(directory):
            return directory
        # Fallback directory: My documents\Downloads
        mydocs = win32.get_my_documents() # My Documents
        return mydocs
    else:
        if GLib: # GLib should be dependency for POSIX systems
            ddir = GLib.get_user_special_dir(GLib.USER_DIRECTORY_DOWNLOAD)
            if ddir:
                return ddir
        return get_user_home()
    def set_album_art(self, button):
        tburl = self.webview.get_main_frame().get_title()

        if not tburl:
            return
        print "Url: " + tburl
        filep = tburl.split('/')
        filepath = filep[len(filep) - 1]
        (filen, filextn) = os.path.splitext(filepath)
        request = urllib2.Request(tburl)
        opener = urllib2.build_opener()
        image = None
        try:
            image = opener.open(request).read()
        except:
            print "Failed to download image"

        save_filename = self.current_artist + " - " + self.current_album + ".jpg"

        if (self.mode == self.MODE_PICTURES):
            covers_folder = glib.get_user_special_dir(
                glib.USER_DIRECTORY_PICTURES)
            filename = covers_folder + "/" + save_filename

        if (self.mode == self.MODE_RHYTHM):
            covers_folder = os.environ['HOME'] + "/.cache/rhythmbox/covers/"
            filename = covers_folder + save_filename
            if (os.path.isdir(covers_folder) == False):
                os.mkdir(covers_folder)

        if (self.mode == self.MODE_FOLDER):
            location_path_improper = urllib2.url2pathname(
                self.current_location)
            location_path_arr = location_path_improper.split("//")
            location_path = location_path_arr[1]
            filename = location_path.rsplit("/",
                                            1)[0] + "/cover"  #+ save_filename

        output = open(filename, 'w')
        output.write(image)
        output.close()
	def set_album_art(self, button) :
		tburl = self.webview.get_main_frame().get_title()
                
		if not tburl:
			return
		print "Url: " + tburl
		filep = tburl.split('/')
		filepath = filep[len(filep)-1]
		(filen, filextn) = os.path.splitext(filepath)
		request = urllib2.Request(tburl)
		opener = urllib2.build_opener()
		image = None
		try:
			image = opener.open(request).read()
		except:
			print "Failed to download image"
		
		save_filename=self.current_artist + " - " + self.current_album + ".jpg"

                if(self.mode == self.MODE_PICTURES):
			covers_folder = glib.get_user_special_dir(glib.USER_DIRECTORY_PICTURES)
			filename = covers_folder + "/" + save_filename

		if(self.mode == self.MODE_RHYTHM):
                        covers_folder=os.environ['HOME']+"/.cache/rhythmbox/covers/"
			filename = covers_folder + save_filename
                        if (os.path.isdir(covers_folder) == False):
                           os.mkdir(covers_folder)

                if(self.mode == self.MODE_FOLDER):
			location_path_improper = urllib2.url2pathname(self.current_location)
			location_path_arr = location_path_improper.split("//")
			location_path = location_path_arr[1]
			filename = location_path.rsplit("/",1)[0] + "/cover" #+ save_filename

		output = open(filename, 'w')
		output.write(image)
		output.close()
Beispiel #29
0
 def get_default_download_dir(self):
     USER_DIRECTORY_DOWNLOAD = glib.get_user_special_dir(glib.USER_DIRECTORY_DOWNLOAD)
     if USER_DIRECTORY_DOWNLOAD == None:
         USER_DIRECTORY_DOWNLOAD = "~/Downloads"
         print _("USER_DIRECTORY_DOWNLOAD variable not found, Defaults to ~/Downloads")
     return USER_DIRECTORY_DOWNLOAD
def get_images_dir():
    return glib.get_user_special_dir(glib.USER_DIRECTORY_PICTURES)
# Get BingXML file which contains the URL of the Bing Photo of the day
# idx = Number days previous the present day. 0 means current day, 1 means yesterday, etc
# n = Number of images predious the day given by idx
# mkt denotes your location. e.g. en-US means United States. Put in your country code
BingXML_URL = "http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=en-GB"
page        = urllib2.urlopen(BingXML_URL)
BingXML     = BeautifulSoup(page, "lxml")

# For extracting complete URL of the image
Images    = BingXML.find_all('image')
ImageURL  = "https://www.bing.com" + Images[0].urlbase.text + '_1920x1080.jpg'
ImageName = Images[0].startdate.text+".jpg"

# All the images will be saved in '/home/[user]/[Pictures accordind user language]/BingWallpapers/'
import glib
ruta = glib.get_user_special_dir(glib.USER_DIRECTORY_PICTURES)
path = ruta + '/BingWallpapers/'

if not os.path.exists(path):
	os.makedirs(path)
os.chdir(path)
if not os.path.isfile(ImageName):
	urllib.urlretrieve(ImageURL, ImageName)
	#gsettings_path = os.system('which gsettings')
	#if not os.system("/usr/bin/gsettings set org.gnome.desktop.background picture-uri file:" + path + ImageName ):
	if not os.system("xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/workspace0/last-image -s " + path + ImageName ):
		os.system('notify-send "'+'Bing Wallpaper updated successfully'+'" "'+ Images[0].copyright.text.encode('utf-8') +'"')
		os._exit(1)
else:
	os.system('notify-send "'+'Bing Wallpaper unchanged'+'" "'+ Images[0].copyright.text.encode('utf-8') + ' Wallpaper already exists in wallpaper directory!'  +'"')
	os._exit(1)
Beispiel #32
0
    def initializeBitmaps(self):

        try:
            self.path = glib.get_user_special_dir(
                glib.USER_DIRECTORY_MUSIC) + "/audiobooks/"

            files = os.listdir(self.path)
            files.remove('fake_cover.png')
            files.sort(
                key=lambda f: os.path.getmtime(os.path.join(self.path, f)))

            self.existingLogos, self.existingMedia = [], []
            for item in files:
                fileExtension = item[item.rfind('.') + 1:]
                if fileExtension == 'png' or fileExtension == 'jpg' or fileExtension == 'jpeg':
                    self.existingLogos.append(item)
                elif fileExtension == 'mp3':
                    self.existingMedia.append(item)

            self.existingLogos = sorted(
                self.existingLogos,
                key=lambda name: int(name.split('_', 2)[0]))
            self.existingMedia = sorted(
                self.existingMedia,
                key=lambda name: int(name.split('_', 2)[0]))

            if len(self.existingMedia) > 0:
                self.numberOfPanels = 1 + (len(self.existingMedia) - 1) / (
                    (self.numberOfRows[0] - 1) * self.numberOfColumns[0])
            else:
                self.numberOfPanels = 1

            self.newHeight = 0.9 * self.winHeight / self.numberOfRows[0]

            self.panels = {}

            for number in range(self.numberOfPanels):
                logoNames = self.existingLogos[number *
                                               (self.numberOfRows[0] - 1) *
                                               self.numberOfColumns[0]:
                                               (number + 1) *
                                               (self.numberOfRows[0] - 1) *
                                               self.numberOfColumns[0]]
                logoPaths = [self.path + name for name in logoNames]

                logos = [
                    wx.ImageFromStream(open(logo, "rb")) for logo in logoPaths
                ]
                logos = [
                    logo.Rescale(
                        logo.GetSize()[0] *
                        (self.newHeight / float(logo.GetSize()[1])),
                        self.newHeight, wx.IMAGE_QUALITY_HIGH)
                    for logo in logos
                ]
                logoBitmaps = [wx.BitmapFromImage(logo) for logo in logos]

                self.panels[number + 1] = [logoNames, logoBitmaps]

        except OSError:
            self.panels = {1: [[], []]}
            self.numberOfPanels = 1
            print "Błąd w strukturze plików."

        self.functionButtonPath = [
            wx.BitmapFromImage(
                wx.ImageFromStream(
                    open(self.pathToAP + 'icons/volume down.png', 'rb'))),
            wx.BitmapFromImage(
                wx.ImageFromStream(
                    open(self.pathToAP + 'icons/volume up.png', 'rb'))),
            wx.BitmapFromImage(
                wx.ImageFromStream(open(self.pathToAP + 'icons/show.png',
                                        'rb'))),
            wx.BitmapFromImage(
                wx.ImageFromStream(
                    open(self.pathToAP + 'icons/delete.png', 'rb'))),
            wx.BitmapFromImage(
                wx.ImageFromStream(open(self.pathToAP + 'icons/back.png',
                                        'rb')))
        ]

        self.functionButtonName = [
            'volume_down', 'volume_up', 'show', 'delete', 'back'
        ]

        if self.numberOfPanels == 1:
            self.flag = 'row'
        else:
            self.flag = 'panel'
Beispiel #33
0
import urllib
import urlparse

import glib

from mopidy import compat, exceptions
from mopidy.compat import queue
from mopidy.utils import encoding

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)
    elif not os.path.isdir(dir_path):
        logger.info('Creating dir %s', dir_path)
Beispiel #34
0
         tmpdict['saving.scrap_prefix'] = dummyobj['save_scrap_prefix']
         tmpdict['input.device_mode'] = dummyobj['input_devices_mode']
         tmpdict['input.global_pressure_mapping'] = dummyobj['global_pressure_mapping']
     return tmpdict
 def get_json_config():
     settingspath = join(self.confpath, 'settings.json')
     jsonstr = open(settingspath).read()
     try:
         return helpers.json_loads(jsonstr)
     except Exception, e:
         print "settings.json: %s" % (str(e),)
         print "warning: failed to load settings.json, using defaults"
         return {}
 if sys.platform == 'win32':
     import glib
     scrappre = join(glib.get_user_special_dir(glib.USER_DIRECTORY_DOCUMENTS).decode('utf-8'),'MyPaint','scrap')
 else:
     scrappre = '~/MyPaint/scrap'
 DEFAULT_CONFIG = {
     'saving.scrap_prefix': scrappre,
     'input.device_mode': 'screen',
     'input.global_pressure_mapping': [(0.0, 1.0), (1.0, 0.0)],
     'view.default_zoom': 1.0,
     'view.high_quality_zoom': True,
     'ui.hide_menubar_in_fullscreen': True,
     'ui.hide_toolbar_in_fullscreen': True,
     'ui.hide_subwindows_in_fullscreen': True,
     'ui.parts': dict(main_toolbar=True, menubar=False),
     'ui.feedback.scale': True,
     'ui.feedback.last_pos': False,
     'ui.toolbar_items': dict(
Beispiel #35
0
	def _get_tmpl_dir(self):
		tmpl_dir = glib.get_user_special_dir(glib.USER_DIRECTORY_TEMPLATES)
		if not tmpl_dir:
			tmpl_dir = os.path.expanduser(DEFAULT_TMPL_DIR)
		return tmpl_dir
Beispiel #36
0
def copy_to_desktop(source, confirm_dialog_factory):
    basename = os.path.basename(source)
    desktop = glib.get_user_special_dir(glib.USER_DIRECTORY_DESKTOP)
    dest = desktop + "/" + basename

    restore_to(source, dest, confirm_dialog_factory)
Beispiel #37
0
def find_pictures_dir():
    """find_pictures_dir() -> gio.File
	Returns the user's pictures folder.
	"""
    return gio.File(path=glib.get_user_special_dir(glib.USER_DIRECTORY_PICTURES))
Beispiel #38
0
def get_home_video():
    return glib.get_user_special_dir(glib.USER_DIRECTORY_VIDEOS)
Beispiel #39
0
class Application (object):
    """Main application singleton.

    This class serves as a global container for everything that needs
    to be shared in the GUI. Its constructor is the last part of the
    initialization, called by main.py or by the testing scripts.

    Access via `gui.application.get_app()`.

    """

    #: Singleton instance
    _INSTANCE = None


    def __init__(self, filenames, app_datapath, app_extradatapath,
                 user_datapath, user_confpath, version, fullscreen=False):
        """Construct, but do not run.

        :params filenames: The list of files to load.
          Note: only the first is used.
        :param app_datapath: App-specific read-only data area.
          Path used for UI definition XML, and the default sets of backgrounds,
          palettes, and brush defintions. Often $PREFIX/share/.
        :param app_extradatapath: Extra search path for 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 user_datapath: Location of the user's app-specific data.
          For MyPaint, this means the user's brushes, backgrounds, and
          scratchpads. Commonly $XDG_DATA_HOME/mypaint, i.e.
          ~/.local/share/mypaint
        :param user_confpath: Location of the user's app-specific config area.
          This is where MyPaint will save user preferences data and the
          keyboard accelerator map. Commonly $XDG_CONFIG_HOME/mypaint, i.e.
          ~/.config/mypaint
        :param version: Version string for the about dialog.
        :param fullscreen: Go fullscreen after starting.

        """
        assert Application._INSTANCE is None
        super(Application, self).__init__()
        Application._INSTANCE = self

        self.user_confpath = user_confpath #: User configs (see __init__)
        self.user_datapath = user_datapath #: User data (see __init__)

        self.datapath = app_datapath

        self.version = version  #: version string for the app.

        # create config directory, and subdirs where the user might drop files
        for basedir in [self.user_confpath, self.user_datapath]:
            if not os.path.isdir(basedir):
                os.mkdir(basedir)
                logger.info('Created basedir %r', basedir)
        for datasubdir in ['backgrounds', 'brushes', 'scratchpads']:
            datadir = os.path.join(self.user_datapath, datasubdir)
            if not os.path.isdir(datadir):
                os.mkdir(datadir)
                logger.info('Created data subdir %r', datadir)


        # Default location for our icons. The user's theme can override these.
        icon_theme = Gtk.IconTheme.get_default()
        icon_theme.append_search_path(join(app_extradatapath, "icons"))

        # Icon sanity check
        if not icon_theme.has_icon('mypaint') \
                or not icon_theme.has_icon('mypaint-tool-brush'):
            logger.error('Error: Where have my icons gone?')
            logger.error('Icon search path: %r', icon_theme.get_search_path())
            logger.error("Mypaint can't run sensibly without its icons; "
                         "please check your installation. See "
                         "https://gna.org/bugs/?18460 for possible solutions")
            sys.exit(1)

        Gtk.Window.set_default_icon_name('mypaint')

        # Core actions and menu structure
        resources_xml = join(self.datapath, "gui", "resources.xml")
        self.builder = Gtk.Builder()
        self.builder.set_translation_domain("mypaint")
        self.builder.add_from_file(resources_xml)

        self.ui_manager = self.builder.get_object("app_ui_manager")
        signal_callback_objs = []

        Gdk.set_program_class('MyPaint')

        self.pixmaps = PixbufDirectory(join(self.datapath, 'pixmaps'))
        self.cursor_color_picker = Gdk.Cursor.new_from_pixbuf(
                Gdk.Display.get_default(),
                self.pixmaps.cursor_color_picker,
                1, 30
                )
        self.cursors = CursorCache(self)

        # unmanaged main brush; always the same instance (we can attach settings_observers)
        # this brush is where temporary changes (color, size...) happen
        self.brush = brush.BrushInfo()
        self.brush.load_defaults()

        # Global pressure mapping function, ignored unless set
        self.pressure_mapping = None

        self.preferences = {}
        self.load_settings()

        # Keyboard manager
        self.kbm = keyboard.KeyboardManager(self)

        # File I/O
        self.filehandler = filehandling.FileHandler(self)

        # Load the main interface
        mypaint_main_xml = join(self.datapath, "gui", "mypaint.glade")
        self.builder.add_from_file(mypaint_main_xml)

        # Main drawing window
        self.drawWindow = self.builder.get_object("drawwindow")
        signal_callback_objs.append(self.drawWindow)

        # Workspace widget. Manages layout of toolwindows, and autohide in
        # fullscreen.
        workspace = self.builder.get_object("app_workspace")
        workspace.build_from_layout(self.preferences["workspace.layout"])
        workspace.floating_window_created += self._floating_window_created_cb
        fs_autohide_action = self.builder.get_object("FullscreenAutohide")
        fs_autohide_action.set_active(workspace.autohide_enabled)
        self.workspace = workspace

        # Working document: viewer widget
        app_canvas = self.builder.get_object("app_canvas")

        # Working document: model and controller
        model = lib.document.Document(self.brush)
        self.doc = document.Document(self, app_canvas, model)
        app_canvas.set_model(model)

        signal_callback_objs.append(self.doc)
        signal_callback_objs.append(self.doc.modes)

        self.scratchpad_filename = ""
        scratchpad_model = lib.document.Document(self.brush, painting_only=True)
        scratchpad_tdw = tileddrawwidget.TiledDrawWidget()
        scratchpad_tdw.set_model(scratchpad_model)
        self.scratchpad_doc = document.Document(self, scratchpad_tdw,
                                                scratchpad_model,
                                                leader=self.doc)
        self.brushmanager = brushmanager.BrushManager(
                join(app_datapath, 'brushes'),
                join(user_datapath, 'brushes'),
                self)
        signal_callback_objs.append(self.filehandler)
        self.brushmodifier = brushmodifier.BrushModifier(self)
        signal_callback_objs.append(self.brushmodifier)
        self.line_mode_settings = linemode.LineModeSettings(self)

        # Button press mapping
        self.button_mapping = ButtonMapping()

        # Monitors changes of input device & saves device-specific brushes
        self.device_monitor = DeviceUseMonitor(self)

        if not self.preferences.get("scratchpad.last_opened_scratchpad", None):
            self.preferences["scratchpad.last_opened_scratchpad"] = self.filehandler.get_scratchpad_autosave()
        self.scratchpad_filename = self.preferences["scratchpad.last_opened_scratchpad"]

        self.brush_color_manager = BrushColorManager(self)
        self.brush_color_manager.set_picker_cursor(self.cursor_color_picker)
        self.brush_color_manager.set_data_path(self.datapath)

        #: Mapping of setting cname to a GtkAdjustment which controls the base
        #: value of that setting for the app's current brush.
        self.brush_adjustment = {}
        self.init_brush_adjustments()

        # Connect signals defined in mypaint.xml
        callback_finder = CallbackFinder(signal_callback_objs)
        self.builder.connect_signals(callback_finder)

        self.kbm.start_listening()
        self.filehandler.doc = self.doc
        self.filehandler.filename = None
        Gtk.AccelMap.load(join(self.user_confpath, 'accelmap.conf'))

        # Load the default background image if one exists
        layer_stack = self.doc.model.layer_stack
        inited_background = False
        for datapath in [self.user_datapath, self.datapath]:
            bg_path = join(datapath, backgroundwindow.BACKGROUNDS_SUBDIR,
                           backgroundwindow.DEFAULT_BACKGROUND)
            if not os.path.exists(bg_path):
                continue
            bg, errors = backgroundwindow.load_background(bg_path)
            if bg:
                layer_stack.set_background(bg, make_default=True)
                inited_background = True
                break
            else:
                logger.warning("Failed to load default background image %r",
                               bg_path)
                if errors:
                    for error in errors:
                        logger.warning("warning: %r", error)

        # Otherwise, set a fallback background colour which depends on the UI
        # brightness and isn't too glaringly odd if the user's theme doesn't
        # have dark/light variants.
        if not inited_background:
            if self.preferences["ui.dark_theme_variant"]:
                bg_color = 153, 153, 153
            else:
                bg_color = 204, 204, 204
            layer_stack.set_background(bg_color, make_default=True)
            inited_background = True

        # Non-dockable subwindows
        # Loading is deferred as late as possible
        self._subwindow_classes = {
            # action-name: action-class
            "BackgroundWindow": backgroundwindow.BackgroundWindow,
            "BrushEditorWindow": brusheditor.BrushEditorWindow,
            "PreferencesWindow": preferenceswindow.PreferencesWindow,
            "InputTestWindow": inputtestwindow.InputTestWindow,
            "BrushIconEditorWindow": brushiconeditor.BrushIconEditorWindow,
            }
        self._subwindows = {}

        # Show main UI.
        self.drawWindow.show_all()
        GObject.idle_add(self._at_application_start, filenames, fullscreen)


    def _at_application_start(self, filenames, fullscreen):
        col = self.brush_color_manager.get_color()
        self.brushmanager.select_initial_brush()
        self.brush_color_manager.set_color(col)
        if filenames:
            # Open only the first file, no matter how many has been specified
            # If the file does not exist just set it as the file to save to
            fn = filenames[0].replace('file:///', '/')
            # ^ some filebrowsers do this (should only happen with outdated
            #   mypaint.desktop)
            if not os.path.exists(fn):
                self.filehandler.filename = fn
            else:
                self.filehandler.open_file(fn)

        # Load last scratchpad
        sp_autosave_key = "scratchpad.last_opened_scratchpad"
        autosave_name = self.preferences[sp_autosave_key]
        if not autosave_name:
            autosave_name = self.filehandler.get_scratchpad_autosave()
            self.preferences[sp_autosave_key] = autosave_name
            self.scratchpad_filename = autosave_name
        if os.path.isfile(autosave_name):
            try:
                self.filehandler.open_scratchpad(autosave_name)
            except AttributeError:
                pass

        self.apply_settings()
        if not self.pressure_devices:
            logger.warning('No pressure sensitive devices found.')
        self.drawWindow.present()

        # Handle fullscreen command line option
        if fullscreen:
            self.drawWindow.fullscreen_cb()


    def save_settings(self):
        """Saves the current settings to persistent storage."""
        self.brushmanager.save_brushes_for_devices()
        self.brushmanager.save_brush_history()
        self.filehandler.save_scratchpad(self.scratchpad_filename)
        settingspath = join(self.user_confpath, 'settings.json')
        jsonstr = helpers.json_dumps(self.preferences)
        f = open(settingspath, 'w')
        f.write(jsonstr)
        f.close()


    def apply_settings(self):
        """Applies the current settings.
        """
        self.update_input_mapping()
        self.update_input_devices()
        self.update_button_mapping()
        self.preferences_window.update_ui()


    def load_settings(self):
        """Loads the settings from persistent storage.

        Uses defaults if not explicitly configured.

        """
        def get_json_config():
            settingspath = join(self.user_confpath, 'settings.json')
            jsonstr = open(settingspath).read()
            try:
                return helpers.json_loads(jsonstr)
            except Exception, e:
                logger.warning("settings.json: %s", str(e))
                logger.warning("Failed to load settings: using defaults")
                return {}
        if sys.platform == 'win32':
            import glib
            scrappre = join(glib.get_user_special_dir(glib.USER_DIRECTORY_DOCUMENTS).decode('utf-8'),'MyPaint','scrap')
        else:
            scrappre = '~/MyPaint/scrap'
        DEFAULT_CONFIG = {
            'saving.scrap_prefix': scrappre,
            'input.device_mode': 'screen',
            'input.global_pressure_mapping': [(0.0, 1.0), (1.0, 0.0)],
            'view.default_zoom': 1.0,
            'view.high_quality_zoom': True,
            'ui.hide_menubar_in_fullscreen': True,
            'ui.hide_toolbar_in_fullscreen': True,
            'ui.hide_subwindows_in_fullscreen': True,
            'ui.parts': dict(main_toolbar=True, menubar=True),
            'ui.feedback.scale': False,
            'ui.feedback.last_pos': False,
            'ui.feedback.symmetry': True,
            'ui.toolbar_items': dict(
                toolbar1_file=True,
                toolbar1_scrap=False,
                toolbar1_edit=True,
                toolbar1_blendmodes=False,
                toolbar1_linemodes=True,
                toolbar1_view_modes=True,
                toolbar1_view_manips=False,
                toolbar1_view_resets=True,
                toolbar1_subwindows=True,
            ),
            'ui.toolbar_icon_size': 'large',
            'ui.dark_theme_variant': True,
            'saving.default_format': 'openraster',
            'brushmanager.selected_brush' : None,
            'brushmanager.selected_groups' : [],
            'frame.color_rgba': (0.12, 0.12, 0.12, 0.92),
            'misc.context_restores_color': True,

            "scratchpad.last_opened_scratchpad": "",

            # Initial main window positions
            "workspace.layout": {
                "position": dict(x=50, y=32, w=-50, h=-100),
                "autohide": True,
            },

            # Linux defaults.
            # Alt is the normal window resizing/moving key these days,
            # so provide a Ctrl-based equivalent for all alt actions.
            'input.button_mapping': {
                # Note that space is treated as a fake Button2
                '<Shift>Button1':          'StraightMode',
                '<Control>Button1':        'ColorPickMode',
                '<Alt>Button1':            'ColorPickMode',
                'Button2':                 'PanViewMode',
                '<Shift>Button2':          'RotateViewMode',
                '<Control>Button2':        'ZoomViewMode',
                '<Alt>Button2':            'ZoomViewMode',
                '<Control><Shift>Button2': 'FrameEditMode',
                '<Alt><Shift>Button2':     'FrameEditMode',
                'Button3':                 'ShowPopupMenu',
            },
        }
        if sys.platform == 'win32':
            # The Linux wacom driver inverts the button numbers of the
            # pen flip button, because middle-click is the more useful
            # action on Linux. However one of the two buttons is often
            # accidentally hit with the thumb while painting. We want
            # to assign panning to this button by default.
            linux_mapping = DEFAULT_CONFIG["input.button_mapping"]
            DEFAULT_CONFIG["input.button_mapping"] = {}
            for bp, actname in linux_mapping.iteritems():
                bp = bp.replace("Button2", "ButtonTMP")
                bp = bp.replace("Button3", "Button2")
                bp = bp.replace("ButtonTMP", "Button3")
                DEFAULT_CONFIG["input.button_mapping"][bp] = actname

        self.preferences = DEFAULT_CONFIG.copy()
        try:
            user_config = get_json_config()
        except IOError:
            user_config = {}
        self.preferences.update(user_config)
        if 'ColorPickerPopup' in self.preferences["input.button_mapping"].values():
            # old config file; users who never assigned any buttons would
            # end up with Ctrl-Click color picker broken after upgrade
            self.preferences["input.button_mapping"] = DEFAULT_CONFIG["input.button_mapping"]
Beispiel #40
0
def get_home_music():
    return glib.get_user_special_dir(glib.USER_DIRECTORY_MUSIC)
Beispiel #41
0
# Get BingXML file which contains the URL of the Bing Photo of the day
# idx = Number days previous the present day. 0 means current day, 1 means yesterday, etc
# n = Number of images predious the day given by idx
# mkt denotes your location. e.g. en-US means United States. Put in your country code
BingXML_URL = "http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=en-GB"
page = urllib2.urlopen(BingXML_URL)
BingXML = BeautifulSoup(page, "lxml")

# For extracting complete URL of the image
Images = BingXML.find_all('image')
ImageURL = "https://www.bing.com" + Images[0].urlbase.text + '_1920x1080.jpg'
ImageName = Images[0].startdate.text + ".jpg"

# All the images will be saved in '/home/[user]/[Pictures accordind user language]/BingWallpapers/'
import glib
ruta = glib.get_user_special_dir(glib.USER_DIRECTORY_PICTURES)
path = ruta + '/BingWallpapers/'

if not os.path.exists(path):
    os.makedirs(path)
os.chdir(path)
if not os.path.isfile(ImageName):
    urllib.urlretrieve(ImageURL, ImageName)
    #gsettings_path = os.system('which gsettings')
    #if not os.system("/usr/bin/gsettings set org.gnome.desktop.background picture-uri file:" + path + ImageName ):
    if not os.system(
            "xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/workspace0/last-image -s "
            + path + ImageName):
        os.system('notify-send "' + 'Bing Wallpaper updated successfully' +
                  '" "' + Images[0].copyright.text.encode('utf-8') + '"')
        os._exit(1)
Beispiel #42
0
		def get_special_dir(opt):
			if opt in specialdirs:
				return glib.get_user_special_dir(specialdirs[opt])
Beispiel #43
0
from mopidy import settings, DATA_PATH
from mopidy.backends.base import (Backend, CurrentPlaylistController,
    LibraryController, BaseLibraryProvider, PlaybackController,
    BasePlaybackProvider, StoredPlaylistsController,
    BaseStoredPlaylistsProvider)
from mopidy.models import Playlist, Track, Album
from mopidy.gstreamer import GStreamer

from .translator import parse_m3u, parse_mpd_tag_cache

logger = logging.getLogger(u'mopidy.backends.local')

DEFAULT_PLAYLIST_PATH = os.path.join(DATA_PATH, 'playlists')
DEFAULT_TAG_CACHE_FILE = os.path.join(DATA_PATH, 'tag_cache')
DEFAULT_MUSIC_PATH = glib.get_user_special_dir(glib.USER_DIRECTORY_MUSIC)

if not DEFAULT_MUSIC_PATH or DEFAULT_MUSIC_PATH == os.path.expanduser(u'~'):
    DEFAULT_MUSIC_PATH = os.path.expanduser(u'~/music')


class LocalBackend(ThreadingActor, Backend):
    """
    A backend for playing music from a local music archive.

    **Issues:** https://github.com/mopidy/mopidy/issues?labels=backend-local

    **Dependencies:**

    - None
Beispiel #44
0
    def initializeBitmaps(self):

        try:
            self.path = glib.get_user_special_dir(
                glib.USER_DIRECTORY_MUSIC) + "/"

            directories = [
                directory for directory in os.listdir(self.path)
                if os.path.isdir(os.path.join(self.path, directory))
            ]

            if 'audiobooks' in directories:
                directories.remove('audiobooks')

            #directories.sort( key=lambda directory: os.path.getmtime( os.path.join(self.path, directory) ) )
            try:
                directories = sorted(directories,
                                     key=lambda x: int(x.split("_")[0]))
            except ValueError:
                pass

            self.existingLogos, self.existingMedia = [], []

            for item in directories:

                itemPath = self.path + item + "/"

                if 'playlist.m3u' in os.listdir(itemPath):

                    self.existingMedia.append(itemPath + 'playlist.m3u')
                    self.existingLogos.append([
                        itemPath + f for f in os.listdir(itemPath)
                        if f.startswith("cover")
                    ][0])

                else:
                    ositem = item.replace(' ',
                                          '\ ').replace('(', '\(').replace(
                                              ')', '\)').replace('&', '\&')

                    os.system(
                        'ls -d -1 -I %s/*.mp* -I %s/*.ogg* > %s/playlist.m3u' %
                        (self.path.replace(' ', '\ ') + ositem,
                         self.path.replace(' ', '\ ') + ositem,
                         self.path.replace(' ', '\ ') + ositem))

                    self.existingMedia.append(itemPath + 'playlist.m3u')
                    self.existingLogos.append([
                        itemPath + f for f in os.listdir(itemPath)
                        if f.startswith("cover")
                    ][0])

            self.existingLogos = [
                item.decode('utf-8') for item in self.existingLogos
            ]
            self.existingMedia = [
                item.decode('utf-8') for item in self.existingMedia
            ]

            if len(self.existingMedia) > 0:
                self.numberOfPanels = 1 + (len(self.existingMedia) - 1) / (
                    (self.numberOfRows[0] - 1) * self.numberOfColumns[0])
            else:
                self.numberOfPanels = 1

            self.newHeight = 0.9 * self.winHeight / self.numberOfRows[0]

            self.panels = {}

            for number in range(self.numberOfPanels):
                logoNames = self.existingLogos[number *
                                               (self.numberOfRows[0] - 1) *
                                               self.numberOfColumns[0]:
                                               (number + 1) *
                                               (self.numberOfRows[0] - 1) *
                                               self.numberOfColumns[0]]

                logos = [
                    wx.ImageFromStream(open(logo, "rb")) for logo in logoNames
                ]
                logos = [
                    logo.Rescale(
                        logo.GetSize()[0] *
                        (self.newHeight / float(logo.GetSize()[1])),
                        self.newHeight, wx.IMAGE_QUALITY_HIGH)
                    for logo in logos
                ]

                logoBitmaps = [wx.BitmapFromImage(logo) for logo in logos]

                self.panels[number + 1] = [logoNames, logoBitmaps]

        except OSError:
            self.panels = {1: [[], []]}
            self.numberOfPanels = 1
            print "Błąd w strukturze plików."

        self.functionButtonPath = [
            wx.BitmapFromImage(
                wx.ImageFromStream(
                    open(self.pathToAP + 'icons/volume down.png', 'rb'))),
            wx.BitmapFromImage(
                wx.ImageFromStream(
                    open(self.pathToAP + 'icons/volume up.png', 'rb'))),
            wx.BitmapFromImage(
                wx.ImageFromStream(open(self.pathToAP + 'icons/show.png',
                                        'rb'))),
            wx.BitmapFromImage(
                wx.ImageFromStream(
                    open(self.pathToAP + 'icons/delete.png', 'rb'))),
            wx.BitmapFromImage(
                wx.ImageFromStream(open(self.pathToAP + 'icons/back.png',
                                        'rb')))
        ]

        self.functionButtonName = [
            'volume_down', 'volume_up', 'show', 'delete', 'back'
        ]

        if self.numberOfPanels == 1:
            self.flag = 'row'
        else:
            self.flag = 'panel'
    def create_places_submenu(self, parent_menu):
        item = self.append_menu_item(parent_menu, _("Places"), "folder", None)

        menu = gtk.Menu()
        item.set_submenu(menu)

        user_path = os.path.expanduser("~/")

        home_item = self.append_menu_item(menu, _("Home Folder"), "user-home", _("Open your personal folder"))
        home_item.connect("activate", self.open_folder_cb, "file://%s" % user_path)

        # Add Desktop
        desktop_path = glib.get_user_special_dir(glib.USER_DIRECTORY_DESKTOP)
        if desktop_path != user_path:
            label = glib.filename_display_basename(desktop_path)
            desktop_item = self.append_menu_item(menu, label, "user-desktop", _("Open the contents of your desktop in a folder"))
            desktop_item.connect("activate", self.open_folder_cb, "file://%s" % desktop_path)

        """ Bookmarks """
        self.places_menu = menu
        self.bookmarks_items = []
        self.append_bookmarks()

        # Monitor bookmarks file for changes
        bookmarks_file = os.path.expanduser("~/.gtk-bookmarks")
        self.__bookmarks_monitor = gio.File(bookmarks_file).monitor_file()  # keep a reference to avoid getting it garbage collected
        def bookmarks_changed_cb(monitor, file, other_file, event):
            if event == gio.FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
                with self.__rebuild_lock:
                    self.append_bookmarks()
                    # Refresh menu to re-initialize the widget
                    self.places_menu.show_all()
        self.__bookmarks_monitor.connect("changed", bookmarks_changed_cb)

        menu.append(gtk.SeparatorMenuItem())

        """ Devices """
        added = False
        added |= self.append_awn_desktop(menu, "nautilus-computer")
        added |= self.append_awn_desktop(menu, "nautilus-cd-burner")

        # Set up volumes and mounts monitor
        self.__volumes_mounts_monitor = gio.volume_monitor_get()

        self.__volumes_index = len(self.places_menu) - len(self.bookmarks_items)
        self.volume_items = []
        self.append_volumes()
        # TODO if added is False and no volumes, then their are two separators

        if added:
            menu.append(gtk.SeparatorMenuItem())

        added = False
        added |= self.append_awn_desktop(menu, "network-scheme")

        self.__mounts_index = len(self.places_menu) - len(self.volume_items) - len(self.bookmarks_items)
        self.mount_items = []
        self.append_mounts()
        # TODO if added is False and no mounts, then there are two separators

        # Connect signals after having initialized volumes and mounts
        for signal in ("volume-added", "volume-changed", "volume-removed", "mount-added", "mount-changed", "mount-removed"):
            self.__volumes_mounts_monitor.connect(signal, self.refresh_volumes_mounts_cb)

        ncs_exists = os.path.exists(commands.getoutput("which nautilus-connect-server"))
        if ncs_exists:
            connect_item = self.append_menu_item(menu, _("Connect to Server..."), "applications-internet", _("Connect to a remote computer or shared disk"))
            connect_item.connect("activate", lambda w: subprocess.Popen("nautilus-connect-server"))
        added |= ncs_exists

        if added:
            menu.append(gtk.SeparatorMenuItem())

        self.append_awn_desktop(menu, "mate-search-tool")

        """ Recent Documents """
        self.create_documents_submenu(menu)
Beispiel #46
0
    def create_places_submenu(self, parent_menu):
        item = self.append_menu_item(parent_menu, _("Places"), "folder", None)

        menu = gtk.Menu()
        item.set_submenu(menu)

        user_path = os.path.expanduser("~/")

        home_item = self.append_menu_item(menu, _("Home Folder"), "user-home", _("Open your personal folder"))
        home_item.connect("activate", self.open_folder_cb, "file://%s" % user_path)

        # Add Desktop
        desktop_path = glib.get_user_special_dir(glib.USER_DIRECTORY_DESKTOP)
        if desktop_path != user_path:
            label = glib.filename_display_basename(desktop_path)
            desktop_item = self.append_menu_item(menu, label, "user-desktop", _("Open the contents of your desktop in a folder"))
            desktop_item.connect("activate", self.open_folder_cb, "file://%s" % desktop_path)

        """ Bookmarks """
        self.places_menu = menu
        self.bookmarks_items = []
        self.append_bookmarks()

        # Monitor bookmarks file for changes
        bookmarks_file = os.path.expanduser("~/.gtk-bookmarks")
        self.__bookmarks_monitor = gio.File(bookmarks_file).monitor_file()  # keep a reference to avoid getting it garbage collected
        def bookmarks_changed_cb(monitor, file, other_file, event):
            if event == gio.FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
                with self.__rebuild_lock:
                    self.append_bookmarks()
                    # Refresh menu to re-initialize the widget
                    self.places_menu.show_all()
        self.__bookmarks_monitor.connect("changed", bookmarks_changed_cb)

        menu.append(gtk.SeparatorMenuItem())

        """ Devices """
        added = False
        added |= self.append_awn_desktop(menu, "nautilus-computer")
        added |= self.append_awn_desktop(menu, "nautilus-cd-burner")

        # Set up volumes and mounts monitor
        self.__volumes_mounts_monitor = gio.volume_monitor_get()

        self.__volumes_index = len(self.places_menu) - len(self.bookmarks_items)
        self.volume_items = []
        self.append_volumes()
        # TODO if added is False and no volumes, then their are two separators

        if added:
            menu.append(gtk.SeparatorMenuItem())

        added = False
        added |= self.append_awn_desktop(menu, "network-scheme")

        self.__mounts_index = len(self.places_menu) - len(self.volume_items) - len(self.bookmarks_items)
        self.mount_items = []
        self.append_mounts()
        # TODO if added is False and no mounts, then there are two separators

        # Connect signals after having initialized volumes and mounts
        for signal in ("volume-added", "volume-changed", "volume-removed", "mount-added", "mount-changed", "mount-removed"):
            self.__volumes_mounts_monitor.connect(signal, self.refresh_volumes_mounts_cb)

        ncs_exists = os.path.exists(commands.getoutput("which nautilus-connect-server"))
        if ncs_exists:
            connect_item = self.append_menu_item(menu, _("Connect to Server..."), "applications-internet", _("Connect to a remote computer or shared disk"))
            connect_item.connect("activate", lambda w: subprocess.Popen("nautilus-connect-server"))
        added |= ncs_exists

        if added:
            menu.append(gtk.SeparatorMenuItem())

        self.append_awn_desktop(menu, "gnome-search-tool")

        """ Recent Documents """
        self.create_documents_submenu(menu)
Beispiel #47
0
def get_images_dir():
    return glib.get_user_special_dir(glib.USER_DIRECTORY_PICTURES)
def get_home_music():
    return glib.get_user_special_dir(glib.USER_DIRECTORY_MUSIC)
Beispiel #49
0
   def __init__(self):
       #Set up i18n
       for module in gtk.glade, gettext:
           module.bindtextdomain("transmageddon","../../share/locale")
           module.textdomain("transmageddon")

       #Set the Glade file
       self.gladefile = "transmageddon.glade"
       gtk.glade.XML.__init__ (self, self.gladefile)

       #Define functionality of our button and main window
       self.TopWindow = self.get_widget("TopWindow")
       self.FileChooser = self.get_widget("FileChooser")
       self.videoinformation = self.get_widget("videoinformation")
       self.audioinformation = self.get_widget("audioinformation")
       self.CodecBox = self.get_widget("CodecBox")
       self.presetchoice = self.get_widget("presetchoice")
       self.containerchoice = self.get_widget("containerchoice")
       self.codec_buttons = dict()
       for c in supported_audio_codecs:
           self.codec_buttons[c] = self.get_widget(c+"button")
           self.codec_buttons[c].connect("clicked",
                                         self.on_audiobutton_pressed, c)
       for c in supported_video_codecs:
           self.codec_buttons[c] = self.get_widget(c+"button")
           self.codec_buttons[c].connect("clicked",
                                         self.on_videobutton_pressed, c)

       self.transcodebutton = self.get_widget("transcodebutton")
       self.ProgressBar = self.get_widget("ProgressBar")
       self.cancelbutton = self.get_widget("cancelbutton")
       self.StatusBar = self.get_widget("StatusBar")

       self.TopWindow.connect("destroy", gtk.main_quit)

       self.signal_autoconnect(self) # Initialize User Interface

       # Set the Videos XDG UserDir as the default directory for the filechooser, 
       # also make sure directory exists
       if 'get_user_special_dir' in glib.__dict__:
           self.VideoDirectory = glib.get_user_special_dir(glib.USER_DIRECTORY_VIDEOS)
       else:
           self.VideoDirectory = os.getenv('HOME')

       CheckDir = os.path.isdir(self.VideoDirectory)
       if CheckDir == (False):
           os.mkdir(self.VideoDirectory)
       self.FileChooser.set_current_folder(self.VideoDirectory)

       # Setting AppIcon
       FileExist = os.path.isfile("../../share/pixmaps/transmageddon.png")
       if FileExist:
           self.TopWindow.set_icon_from_file("../../share/pixmaps/transmageddon.png")
       else:
           try:
               self.TopWindow.set_icon_from_file("transmageddon.png")
           except:
               print "failed to find appicon"

       # default all but top box to insensitive by default
       # self.containerchoice.set_sensitive(False)
       self.CodecBox.set_sensitive(False)
       self.transcodebutton.set_sensitive(False)
       self.cancelbutton.set_sensitive(False)
       self.presetchoice.set_sensitive(False)

       # set default values for various variables
       self.AudioCodec = "vorbis"
       self.VideoCodec = "theora"
       self.ProgressBar.set_text(_("Transcoding Progress"))

       self.p_duration = gst.CLOCK_TIME_NONE
       self.p_time = gst.FORMAT_TIME

       # Populate the Container format combobox
       self.lst = supported_containers
       for i in self.lst:
           self.containerchoice.append_text(i)
      
       # Populate presets combobox
       selected = 0
       for x, (id, device) in enumerate(sorted(presets.get().items(),
                                   lambda x, y: cmp(x[1].make + x[1].model,
                                                    y[1].make + y[1].model))):
           iter = self.presetchoice.append_text(str(device))
           if id == "computer":
               selected = x
       self.presetchoice.prepend_text("No Presets")
def set_download_folder():
    downloads_dir = glib.get_user_special_dir(glib.USER_DIRECTORY_DOWNLOAD)
    # use equivalent to /home/user/Downloads/NASA-APOD
    new_path = os.path.join(downloads_dir, "NASA-APOD")
    return new_path
Beispiel #51
0
class FolderTwoWay(FileDataProvider.FolderTwoWay, AutoSync.AutoSync):
    """
    TwoWay dataprovider for synchronizing a folder
    """

    _name_ = _("Folder")
    _description_ = _("Synchronize folders")
    _configurable_ = True

    DEFAULT_FOLDER = "file://" + glib.get_user_special_dir(
        glib.USER_DIRECTORY_DOCUMENTS)
    DEFAULT_GROUP = "Home"
    DEFAULT_HIDDEN = False
    DEFAULT_COMPARE_IGNORE_MTIME = False
    DEFAULT_FOLLOW_SYMLINKS = False

    def __init__(self, *args):
        FileDataProvider.FolderTwoWay.__init__(
            self, self.DEFAULT_FOLDER, self.DEFAULT_GROUP, self.DEFAULT_HIDDEN,
            self.DEFAULT_COMPARE_IGNORE_MTIME, self.DEFAULT_FOLLOW_SYMLINKS)
        self.update_configuration(
            folder=self.DEFAULT_FOLDER,
            includeHidden=self.DEFAULT_HIDDEN,
            compareIgnoreMtime=self.DEFAULT_COMPARE_IGNORE_MTIME,
            followSymlinks=self.DEFAULT_FOLLOW_SYMLINKS,
        )
        AutoSync.AutoSync.__init__(self)

        self._monitor = VfsFile.MultipleFileMonitor()
        self._monitor.connect("changed", self._monitor_folder_cb)

        self.update_configuration(
            folder=(self.DEFAULT_FOLDER, self._set_folder,
                    lambda: self.folder),
            includeHidden=self.DEFAULT_HIDDEN,
            compareIgnoreMtime=self.DEFAULT_COMPARE_IGNORE_MTIME,
            followSymlinks=self.DEFAULT_FOLLOW_SYMLINKS)

    def __del__(self):
        self._monitor.cancel()

    def _set_folder(self, f):
        log.debug("Setting folder: %s" % f)
        self.folder = f
        self._monitor.add(f, self._monitor.MONITOR_DIRECTORY)

    def config_setup(self, config):
        config.add_item(
            "Select folder",
            "filebutton",
            order=1,
            config_name="folder",
            directory=True,
        )
        config.add_section("Advanced")
        config.add_item("Include hidden files",
                        "check",
                        config_name="includeHidden")
        config.add_item("Ignore file modification times",
                        'check',
                        config_name="compareIgnoreMtime")
        config.add_item("Follow symbolic links",
                        'check',
                        config_name="followSymlinks")

    def get_UID(self):
        return self.folder

    def get_name(self):
        return Vfs.uri_get_filename(self.folder)

    def _monitor_folder_cb(self, sender, event_uri, event):
        """
        Called when a file in the current folder is changed, added or deleted
        """
        # supported events = CHANGED, DELETED, CREATED
        if event == self._monitor.MONITOR_EVENT_CREATED:
            self.handle_added(event_uri)
        elif event == self._monitor.MONITOR_EVENT_CHANGED:
            self.handle_modified(event_uri)
        elif event == self._monitor.MONITOR_EVENT_DELETED:
            self.handle_deleted(event_uri)
Beispiel #52
0
 def load(self, directory = glib.get_user_special_dir(glib.USER_DIRECTORY_PICTURES)):
     self.directory = directory
     self.__get_pics()
Beispiel #53
0
		def get_special_dir(opt):
			if opt in specialdirs:
				return glib.get_user_special_dir(specialdirs[opt])
Beispiel #54
0
def find_pictures_dir():
    """find_pictures_dir() -> gio.File
	Returns the user's pictures folder.
	"""
    return gio.File(
        path=glib.get_user_special_dir(glib.USER_DIRECTORY_PICTURES))
def get_home_video():
    return glib.get_user_special_dir(glib.USER_DIRECTORY_VIDEOS)
Beispiel #56
0
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):
    folder = os.path.expanduser(folder)