Ubuntu Forums ubuntu.com - launchpad.net - ubuntu help  

Go Back   Ubuntu Forums > The Ubuntu Forum Community > Other Community Discussions > Tutorials & Tips
Register Reset Password Forum Help Forum Council Search Today's Posts Mark Forums Read

Ubuntu 9.10 is out!!!

When downloading Ubuntu 9.10 please consider using bittorrent to get your copy of Ubuntu.

The Ubuntu Developers Summit for Lucid Lynx will be held the week of 16-Nov-2009 till 20-Nov-2009 in Dallas, TX USA. Visit the the Ubuntu wiki for more information about UDS and how to participate remotely.

Tutorials & Tips
The place to find Ubuntu related Tips & Tricks.

 
Thread Tools Display Modes
Old March 27th, 2007   #1
fifo
First Cup of Ubuntu
 
Join Date: Mar 2007
My beans are hidden!
Re: HOWTO: Make folder icons use Folder.jpg (Like Windows XP My Music folder does)

Well this is something that I'd quite like to do, but I can't stand php (sorry) and I wanted to have a go at fixing some of the shortcomings, so I've written my own version in python.

This should handle spaces in directory names (as well as other strange characters, but nautilus' quoting rules seem rather obscure, so maybe there are things I've missed here).

You can specify your own shell-type pattern (--names) for matching the image filename (the default is "[Ff]older.jpg").

There is also a switch (-R) to make it work recursively across nested directories.

Download: custom_icon.py

Code:
$ python custom_icon.py --help
usage: custom_icon.py [options] folder [folder2 ...]

options:
  --version        show program's version number and exit
  -h, --help       show this help message and exit
  --names=NAMES    specification to match image filenames [default:
                   "[Ff]older.jpg"]
  -R, --recursive  set icons for folders recursively

$ python custom_icon.py ~/music
/home/user/music ...
done.

$ nautilus -q
fifo is offline   Reply With Quote
Old June 7th, 2007   #2
TeKniKal
Spilled the Beans
 
Join Date: Oct 2006
Location: Belgium (Europe)
Beans: 12
Ubuntu 7.04 Feisty Fawn
Send a message via MSN to TeKniKal Send a message via Skype™ to TeKniKal
Exclamation Re: HOWTO: Make folder icons use Folder.jpg (Like Windows XP My Music folder does)

Quote:
Originally Posted by fifo View Post
Well this is something that I'd quite like to do, but I can't stand php (sorry) and I wanted to have a go at fixing some of the shortcomings, so I've written my own version in python.

This should handle spaces in directory names (as well as other strange characters, but nautilus' quoting rules seem rather obscure, so maybe there are things I've missed here).

You can specify your own shell-type pattern (--names) for matching the image filename (the default is "[Ff]older.jpg").

There is also a switch (-R) to make it work recursively across nested directories.

Download: Attachment 28357

Code:
$ python custom_icon.py --help
usage: custom_icon.py [options] folder [folder2 ...]

options:
  --version        show program's version number and exit
  -h, --help       show this help message and exit
  --names=NAMES    specification to match image filenames [default:
                   "[Ff]older.jpg"]
  -R, --recursive  set icons for folders recursively

$ python custom_icon.py ~/music
/home/user/music ...
done.

$ nautilus -q
Works quite well, but it doesn't work for folders with an exclamation mark in them, I guess. Anyhow, I ran it on my music folder, and the folder "Weird Al Yankovic - Polka Party!" didn't get a thumb. I will take a look at your source code when I have some time (and more experience with Python).

Already thanks for this script, ignoring this minor bug it works just great
TeKniKal is offline   Reply With Quote
Old December 6th, 2007   #3
dysphasi
A Carafe of Ubuntu
 
Join Date: Oct 2007
Beans: 125
Ubuntu 7.10 Gutsy Gibbon
Re: HOWTO: Make folder icons use Folder.jpg (Like Windows XP My Music folder does)

To be honest, I think this script suits me best, I want to be able to apply folder icons for my video folders etc as well regardless of folder structure.

My only issue, as someone else said was the '!'s stop it working if in the folder name, is there a workaround for this?

One other thing I found was that nautilus -q would close all my windows and would have to issue a 'nautilus' command from the terminal to fire things up again, 'killall nautilus' is more consistent in its behaviour and opens the window again after closing to refresh. I found the most convenient thing to do was ad this command via Nautilus Actions Configuration, allowing me to right click anywhere in the folder and refresh.
Thanks guys for what you've come up with so far

Quote:
Originally Posted by fifo View Post
Well this is something that I'd quite like to do, but I can't stand php (sorry) and I wanted to have a go at fixing some of the shortcomings, so I've written my own version in python.

This should handle spaces in directory names (as well as other strange characters, but nautilus' quoting rules seem rather obscure, so maybe there are things I've missed here).

You can specify your own shell-type pattern (--names) for matching the image filename (the default is "[Ff]older.jpg").

There is also a switch (-R) to make it work recursively across nested directories.

Download: Attachment 28357

Code:
$ python custom_icon.py --help
usage: custom_icon.py [options] folder [folder2 ...]

options:
  --version        show program's version number and exit
  -h, --help       show this help message and exit
  --names=NAMES    specification to match image filenames [default:
                   "[Ff]older.jpg"]
  -R, --recursive  set icons for folders recursively

$ python custom_icon.py ~/music
/home/user/music ...
done.

$ nautilus -q
dysphasi is offline   Reply With Quote
Old January 6th, 2009   #4
Niko_K
First Cup of Ubuntu
 
Join Date: Oct 2006
Beans: 2
Send a message via ICQ to Niko_K Send a message via Skype™ to Niko_K
Question Re: HOWTO: Make folder icons use Folder.jpg (Like Windows XP My Music folder does)

Quote:
Originally Posted by fifo View Post
Well this is something that I'd quite like to do, but I can't stand php (sorry) and I wanted to have a go at fixing some of the shortcomings, so I've written my own version in python.

This should handle spaces in directory names (as well as other strange characters, but nautilus' quoting rules seem rather obscure, so maybe there are things I've missed here).

You can specify your own shell-type pattern (--names) for matching the image filename (the default is "[Ff]older.jpg").

There is also a switch (-R) to make it work recursively across nested directories.

Download: Attachment 28357

Code:
$ python custom_icon.py --help
usage: custom_icon.py [options] folder [folder2 ...]

options:
  --version        show program's version number and exit
  -h, --help       show this help message and exit
  --names=NAMES    specification to match image filenames [default:
                   "[Ff]older.jpg"]
  -R, --recursive  set icons for folders recursively

$ python custom_icon.py ~/music
/home/user/music ...
done.

$ nautilus -q
I really like this script best, because it is able to generate folder icons not only from folder.jpg files, but also from any filename pattern (i personally use '*.png').

However, it does not work for folders, that contain a & in the folder's name (for me it works for folders like "Music/Pop", but not for folder lik "Music/Blues & Jazz").

I am not that familiar with python (and i can't find the problem)...
... can someone please fix this issue?
Niko_K is offline   Reply With Quote
Old April 6th, 2009   #5
lesqueFM
First Cup of Ubuntu
 
Join Date: Apr 2009
Beans: 1
Re: HOWTO: Make folder icons use Folder.jpg (Like Windows XP My Music folder does)

(sorry for being absolutely dumb on this)

Where do I save the code file? Do I have to edit specific parts of it (where do I "tell" the code the location I use)? And then make it operational with the command at the end of quote?

Quote:
Originally Posted by fifo View Post
Well this is something that I'd quite like to do, but I can't stand php (sorry) and I wanted to have a go at fixing some of the shortcomings, so I've written my own version in python.

This should handle spaces in directory names (as well as other strange characters, but nautilus' quoting rules seem rather obscure, so maybe there are things I've missed here).

You can specify your own shell-type pattern (--names) for matching the image filename (the default is "[Ff]older.jpg").

There is also a switch (-R) to make it work recursively across nested directories.

Download: Attachment 28357

Code:
$ python custom_icon.py --help
usage: custom_icon.py [options] folder [folder2 ...]

options:
  --version        show program's version number and exit
  -h, --help       show this help message and exit
  --names=NAMES    specification to match image filenames [default:
                   "[Ff]older.jpg"]
  -R, --recursive  set icons for folders recursively

$ python custom_icon.py ~/music
/home/user/music ...
done.

$ nautilus -q
lesqueFM is offline   Reply With Quote
Old April 10th, 2009   #6
Keith Hedger
Quad Shot of Ubuntu
 
Keith Hedger's Avatar
 
Join Date: Mar 2006
Location: Devon UK
Beans: 410
Ubuntu 9.04 Jaunty Jackalope
Re: HOWTO: Make folder icons use Folder.jpg (Like Windows XP My Music folder does)

This is a script I used when setting the album art for my music collection, just copy it to your music folder and run it, it is fully recursive, you may want to change line 4 to use whatever file name you use for your albumart, this should set the thumbnail regardless of Artist/Album structure, running this on Hardy 8.04
PHP Code:
#!/bin/bash

MAINWD=$PWD
JPEGNAME="albumart.jpg"

find  . -type d | while read FOLDER
    do
        if [ -e "${FOLDER}/${JPEGNAME}" ];then

            cd "${FOLDER}/../"
            FILENAME="$PWD"
            FILENAME="file:%2F%2F"${FILENAME// /%2520}
            FILENAME=${FILENAME//\//%2F}
            XMLFILE=~/.nautilus/metafiles/${FILENAME}.xml
            BASE=$(basename "$FOLDER")

            if [ ! -e $XMLFILE ];then
                echo "<?xml version="1.0\"?>" $XMLFILE
                
echo "<directory>" >> $XMLFILE
                
echo "</directory>" >> $XMLFILE
            fi

            CNT
=$(wc -l $XMLFILE awk '{ print $1 }')
            
CONTENTS=$(head -$(( $CNT )) $XMLFILE)
            
BASE=${BASE// /%20}
            
BASE=${BASE//&/%26}

            
echo "$CONTENTS" $XMLFILE
            
echo "<file name=\"${BASE}\" custom_icon=\"${JPEGNAME}\"/>" >> $XMLFILE
            
echo "</directory>" >> $XMLFILE

            cd 
"$MAINWD"
        
fi
    done

killall nautilus

exit 0
__________________
In /dev/null no one can hear the kernel panic!
Don't EVER use sudo rm -rf / . if you don't understand a command check it out first!
BACK UP YOUR DATA OR YOU WILL LOSE IT!!
Supergrub - The best thing since sliced bread www.supergrubdisk.org
Keith Hedger is offline   Reply With Quote
Old June 1st, 2009   #7
lilo_booter
First Cup of Ubuntu
 
Join Date: Dec 2005
Beans: 1
Re: HOWTO: Make folder icons use Folder.jpg (Like Windows XP My Music folder does)

Here is my python effort for custom folders on albums - it's a bit dumb and probably needs a little work .

You will probably need to run:

Code:
sudo apt-get install python-beautifulsoup
before attempting to run this script.

It assumes that you run it in the directory above your Music dir (so if you use $HOME/Music, run it from $HOME).

It further assumes you use an Artist/Album subdirectory structure and if it finds multiple files in any Music/<dir1>/<dir2>/ directory and no folder.jpg, it'll use the dir1 and dir2 values to query albumart.org - if that returns nothing, then it uses dir1 alone.

Finally, if you arbitrarily and manually place folder.jpg files in any subdirectory, then this is used in preference to the albumart.org query.

Code:
#!/usr/bin/env python

import BeautifulSoup
import urllib
import os
import xml.dom
import xml.dom.minidom
import time

def albumart( path, query ):
	"""Fire query at albumart.org"""
	base = 'http://www.albumart.org/index.php?srchkey=%s&itempage=1&newsearch=1&searchindex=Music'
	result = ''
	try:
		url = base % urllib.quote( query )
		connection = urllib.urlopen( url )
		tree = BeautifulSoup.BeautifulSoup( connection )
		incidents = tree('div', id = 'main_left' )
		if len( incidents ) == 1:
			images = incidents[ 0 ]( 'img' )
			if len( images ):
				result = images[ 0 ][ 'src' ]
			else:
				print 'No images for', path
		else:
			print 'No div for', path
	except Exception, e:
		print 'Malformed result from', path
	return result

def save_as( url, file ):
	"""Save a url to a file"""
	fd = open( file, 'w' )
	connection = urllib.urlopen( url )
	while True:
		data = connection.read( 16384 )
		if len( data ) == 0: break
		fd.write( data )

def metaname( path ):
	"""Probably broken - attempts to map the path given to the nautilus weirdisms..."""
	full = os.path.dirname( os.path.join( os.getcwd( ), path ) )
	result = ( 'file://' + full ).replace( ' ', '%2520' ).replace( '/', '%2F' )
	return result

# Iterate through the Music subdirectory
for path, dirs, files in os.walk( 'Music' ):

	# Split our path (assumption is that we have a Music/Artist/Album combo for albumart usage
	tokens = path.split( '/' )

	# This is the file we will use
	cover = os.path.join( path, 'folder.jpg' )

	# Crappy check to see that we have some files in this dir - assumption is
	# if files exists, and we have at least 3 levels of subdir, then we have an
	# album in the form 'Music/Artist/Album/' or if the current dir contains
	# a folder.jpg we will use it
	
	if len( files ) == 0:
		continue

	# Obtain an image if one is not available
	if len( tokens ) == 3 and not os.path.exists( cover ):
		url = albumart( path, ( tokens[ 1 ] + ' ' + tokens[ 2 ] ).replace( '\'', '' ) )
		if url == '':
			url = albumart( path, ( tokens[ 1 ] ).replace( '\'', '' ) )
		if url != '':
			save_as( url, cover )

	# If we have no cover image for this dir, continue to the next
	if not os.path.exists( cover ):
		continue

	# Obtains the nautilus metadata file name
	directory = os.path.join( os.getenv( 'HOME' ), '.nautilus', 'metafiles' ) + '/' + metaname( path ) + '.xml'

	# Following are populated below
	exists = False
	doc = None
	dir = None

	# Update or create nautilus metafile for icons
	if os.path.exists( directory ):
		doc = xml.dom.minidom.parse( open( directory, 'r' ) )
		elements = doc.getElementsByTagName( 'directory' )
		if len( elements ) == 1:
			dir = elements[ 0 ]
			files = dir.getElementsByTagName( 'file' )
			for file in files:
				name = file.getAttribute( 'name' )
				if name == urllib.quote( os.path.basename( path ) ):
					file.setAttribute( 'custom_icon', os.path.basename( cover ) )
					exists = True
		elif len( elements ) == 0:
			dir = doc.createElement( 'directory' )
			doc.appendChild( dir )
		else:
			print "Umm - don't think this is supposed to happen"
	else:
		dom = xml.dom.minidom.getDOMImplementation( )
		doc = dom.createDocument( None, None, None )
		dir = doc.createElement( 'directory' )
		doc.appendChild( dir )

	# Create the new file if necessary
	if not exists:
		element = doc.createElement( 'file' )
		element.setAttribute( 'name', urllib.quote( os.path.basename( path ) ) )
		element.setAttribute( 'custom_icon', os.path.basename( cover ) )
		element.setAttribute( 'timestamp', str( int( time.time( ) ) ) )
		dir.appendChild( element )

	# Save the document
	output = open( directory, 'w' )
	doc.writexml( output )
	output.close( )

Last edited by lilo_booter; June 1st, 2009 at 03:10 AM..
lilo_booter is offline   Reply With Quote
Old June 22nd, 2009   #8
jlaroche
First Cup of Ubuntu
 
Join Date: Feb 2009
Beans: 5
Re: HOWTO: Make folder icons use Folder.jpg (Like Windows XP My Music folder does)

I tried the following code and got it working, but I don't like the way the bare jpg files look. In short, I'd like to have the normal folder icons back. How would one do this?

Python Code Used:

<?php

/*
Used in conjunction with nautilus metafile for music folder Folder.jpg replacement!
*/

$time = mktime();
$dir = "/media/500gb/My Music/"; //this is the music directory you wanna change

$filename = $dir . "music.txt";

$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);

$lines = explode ("\n", $contents);



echo "<?xml version=\"1.0\"?>\n<directory>";
foreach ($lines as $value)
{
if ($value)
{
//replace special characters.....this is kind of a dumb way to do things, I bet a more leet php coder would be able to find a better function to do this
$newval = str_replace(" ", "%20", $value); //replace spaces
$newval = str_replace(",", "%2C", $newval); //i have some commas in my album names
$newval = str_replace("&", "%26", $newval); //i noticed an ampersand (&) in certain album titles such as Outkast - Speakerboxxx & The Love Below


$filename = $dir . $value . "/folder.jpg"; //changed Folder.jpg to folder.jpg
$time = mktime(); //Unix time!
if (file_exists($filename)) //we only want to do this if there is actually a Folder.jpg file in there
{
$size = filesize($filename);
if ($size && $size < 1048576) //if the Folder.jpg file is too big we might have problems, so lets limit it to 1 MB
{
echo "<file name=\"" . $newval . "\" timestamp=\"". $time . "\" custom_icon=\"folder.jpg\"/>"; //again changed Folder.jpg to folder.jpg

}
}//end if statment: file_exists

}
} //end foreach

echo "</directory>\n";
clearstatcache(); //not really sure if we need this
exit ();

?>
jlaroche is offline   Reply With Quote
Old June 22nd, 2009   #9
Horizon
A Carafe of Ubuntu
 
Horizon's Avatar
 
Join Date: Apr 2006
Location: London, England
Beans: 99
Ubuntu 7.10 Gutsy Gibbon
Send a message via MSN to Horizon
Re: HOWTO: Make folder icons use Folder.jpg (Like Windows XP My Music folder does)

You'll need to go into
Code:
~/.nautilus/metafiles
and delete the lines from the metafile. There should be one named after your music folder. You can delete the whole thing but then you'll lose anything like emblems and settings you had stored on it. If you want to keep them then inside it should have a file element per folder with an icon inside your music folder, so just delete the lines that you want.

If you want a smarter version then try my bash version on page 1 (read my first post, then use the code in my second post which is just below). It resizes the images to the right size (not the actual cover art, it creates a copy first), creates collages of multiple album covers, and creates a "no cover art" image for folders without it because otherwise your folder looks ugly with images and normal folder icons mixed together. Also handles any language, and any characters that nautilus can display.

I also have a version that adds a border and a shadow (like in the attachment to my post on page 1) if you want it.
__________________
Attached to the footprints in spring, to the Japanese song she taught me,
vaguely, I was influenced by her happiness.

Last edited by Horizon; June 22nd, 2009 at 03:41 AM.. Reason: added extra info
Horizon is offline   Reply With Quote
Old July 26th, 2009   #10
JasperK
First Cup of Ubuntu
 
Join Date: Jul 2009
Beans: 1
Kubuntu Karmic Koala (testing)
Re: HOWTO: Make folder icons use Folder.jpg (Like Windows XP My Music folder does)

The newer versions of nautilus as available in Karmic don't store the metadata in xml files anymore. Instead nautilus now uses the new gio abstraction layer to give files a "metadata::custom_icon" attribute. This attribute contains a filename of a picture that should be used as the file icon.

I changed the python script that was posted before to use gio attributes. I have only tested this on karmic(Nautilus 2.27.4).
Attached Files
File Type: py custom_icon_gio.py (1.6 KB, 36 views)
JasperK is offline   Reply With Quote

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -4. The time now is 09:58 PM.


vBulletin ©2000 - 2009, Jelsoft Enterprises Ltd. Ubuntu Logo, Ubuntu and Canonical © Canonical Ltd. Tango Icons © Tango Desktop Project. bilberry