"""
Gnome Python Tools: FileSelectionDialog, Progressbar, TipWindow, OptionMenu, ErrorDialog, QuestionDialog,
InfoDialog, WarningDialog, InputDialog
"""
from os import environ
from sys import platform
# It is necessary to check the DISPLAY environment variable on non win32 machines
if (platform != "win32") and (not environ.has_key("DISPLAY")):
raise ImportError, "DISPLAY environment variable not set"
try:
import pygtk
pygtk.require('2.0')
except:
pass
import gtk
import gobject
from time import sleep
from os import listdir, stat, getcwd, chmod, mkdir
from string import join, split, lower, upper, zfill, strip, atoi, find, replace
from time import localtime, asctime, time
from ConfigParser import ConfigParser
from re import sub
from tempfile import mktemp
from random import choice
from ConfigParser import ConfigParser
from types import StringType
try:
from log4py import Logger
log4pyavailable = gtk.TRUE
except ImportError:
log4pyavailable = gtk.FALSE
import os
# Dicitionary caching common used GdkColors
GdkColorCache = {}
# Drag & Drop target definition
targets = [('text/plain', 0, 1),
('text/uri-list', 0, 2),
('STRING', 0, 3)]
# Constants for various file-types
ALL_FILES = ("All Files", ["*"])
AUDIO_FILES = ("Audio Files", ["mp3", "ogg", "wav"])
EROASTER_PROJECTS = ("ERoaster Projects", ["erp"])
ISO_IMAGES = ("ISO Images", ["iso", "img"])
XMMS_PLAYLISTS = ("XMMS Playlists", ["m3u"])
WINGIDE_PROJECTS = ("WingIDE Projects", ["wpr"])
CUE_SHEETS = ("Cuesheets", ["cue", "CUE"])
BIN_FILES = ("BIN files", ["bin", "BIN"])
# Short cuts (default)
SHORTCUTS = [ [ "HOME", "$HOME" ],
[ "DESKTOP", "$DESKTOP" ],
[ "START", "$CWD" ],
[ "HARDDISK", "/"],
[ "", ""],
[ "", ""]
]
# Dictionary containing icons for different filetypes
ICONS = {}
ICONS["DIRECTORY"] = "folder.xpm" # DO NOT CHANGE THIS ONE !
ICONS["UNKNOWN"] = "unknown.xpm" # DO NOT CHANGE THIS ONE !
ICONS["HOME"] = "gnome-fs-home.png" # These icons are for the shortcuts
ICONS["DESKTOP"] = "gnome-fs-desktop.png"
ICONS["START"] = "gnome-fs-directory-accept.png"
ICONS["CDROM"] = "gnome-dev-cdrom.png"
ICONS["HARDDISK"] = "gnome-dev-harddisk.png"
ICONS["NETWORK"] = "gnome-fs-network.png"
ICONS["LINK"] = "link.xpm"
ICONS["DOC"] = "doc.xpm" # These icons are compared to file extensions
ICONS["GZ"] = "compressed.xpm"
ICONS["BZ2"] = "compressed.xpm"
ICONS["GIF"] = "image.xpm"
ICONS["JPG"] = "image.xpm"
ICONS["BMP"] = "image.xpm"
ICONS["PNG"] = "image.xpm"
ICONS["XPM"] = "image.xpm"
ICONS["PATCH"] = "patch.xpm"
ICONS["PS"] = "ps.xpm"
ICONS["MP3"] = "sound.xpm"
ICONS["WAV"] = "sound.xpm"
ICONS["OGG"] = "sound.xpm"
ICONS["TAR"] = "tar.xpm"
ICONS["TXT"] = "text.xpm"
def create_pixmap(widget, xpm):
return gtk.gdk.pixmap_colormap_create_from_xpm(None, widget.get_colormap(), None, xpm)
def create_image(widget, xpm):
pix, mask = create_pixmap(widget, xpm)
image = gtk.Image()
image.set_from_pixmap(pix, mask)
return image
def lng2str(number, prettyprint = gtk.TRUE):
""" Returns a string representation of a number (with a pretty-print option). """
if (prettyprint == gtk.TRUE):
number = list(str(number))
if number[-1] == "L":
number = number[:-1]
number.reverse()
dots = divmod(len(number) - 1, 3)[0]
for i in range(dots):
number.insert(3 + (i * 3) + i, ".")
number.reverse()
return join(number, "")
else:
return str(number)
def hex2gdkcolor(widget, color):
""" Converts RGB value to a GdkColor. """
global GdkColorCache
if (color[0] == "#"):
color = color[1:]
if (GdkColorCache.has_key(color)):
return GdkColorCache[color]
else:
red = eval("0x%s" % color[0:2]) * 257
green = eval("0x%s" % color[2:4]) * 257
blue = eval("0x%s" % color[4:6]) * 257
color_map = widget.get_colormap()
gdkcolor = color_map.alloc_color(red, green, blue)
if (not GdkColorCache.has_key(color)):
GdkColorCache[color] = gdkcolor
return gdkcolor
def indexof(dict, elem):
for i in range(len(dict)):
if (dict[i] == elem):
return i
def _get_icon_for_filename(filename):
if (os.path.islink(filename)):
filename = "LINK"
elif (os.path.isdir(filename)):
filename = "DIRECTORY"
if (filename in [ "LINK", "DIRECTORY", "HOME", "DESKTOP", "START", "CDROM", "HARDDISK", "NETWORK" ]):
return ICONS[filename]
else:
extension = upper(os.path.splitext(filename)[1])
if (len(extension) > 0):
extension = extension[1:]
if (ICONS.has_key(extension)):
return ICONS[extension]
else:
return ICONS["UNKNOWN"]
def get_file_icon(filename, window, icondir):
xpmname = _get_icon_for_filename(filename)
if (len(icondir) > 0):
if (icondir[-1] != os.sep):
icondir = "%s%s" % (icondir, os.sep)
icon, mask = create_pixmap(window, "%s%s" % (icondir, xpmname))
return (icon, mask)
else:
return None
def get_file_pixbuf(filename, icondir):
image_filename = _get_icon_for_filename(filename)
if (len(icondir) > 0):
if (icondir[-1] != os.sep):
icondir = "%s%s" % (icondir, os.sep)
return gtk.gdk.pixbuf_new_from_file("%s%s" % (icondir, image_filename))
def format_duration(seconds):
hours = int(divmod(seconds, (60 * 60))[0])
seconds = seconds - (hours * (60 * 60))
minutes = int(divmod(seconds, 60)[0])
seconds = str(seconds - (minutes * 60))
splitted = split(seconds, ".")
seconds = zfill(splitted[0], 2)
if (len(splitted) > 1):
milliseconds = splitted[1][:3]
else:
milliseconds = ""
while (len(milliseconds) < 3):
milliseconds = "%s0" % milliseconds
return "%s:%s:%s.%s" % (zfill(hours, 2), zfill(minutes, 2), seconds, milliseconds)
def iso2utf(text):
return unicode(text, "iso8859-15").encode("utf-8")
def utf2iso(text):
return unicode(text, "utf-8").encode("iso8859-15")
def get_homedirectory():
if (platform == "win32"):
if (environ.has_key("USERPROFILE")):
return environ["USERPROFILE"]
else:
return "C:\\"
else:
if (environ.has_key("HOME")):
return environ["HOME"]
else:
# No home directory set
return ""
class FileSelectionDialog:
""" Advanced file selection dialog. """
def __init__(self, path = getcwd(), showhiddenfiles = gtk.FALSE, multiselection = gtk.TRUE, filetypes = [ALL_FILES], icondir = "", windowtitle = "Open File", loglevel = 1 << 1):
self.filelist = []
self.path = path
self.showhiddenfiles = showhiddenfiles
self.filetypes = filetypes
self.currentextension = filetypes[0][1]
self.icondir = icondir
self.windowtitle = windowtitle
if (len(self.icondir) > 0):
if (self.icondir[-1] != os.sep):
self.icondir = "%s%s" % (self.icondir, os.sep)
if (multiselection == gtk.TRUE):
self.selectiontype = gtk.SELECTION_EXTENDED
else:
self.selectiontype = gtk.SELECTION_SINGLE
self.selectedfiles = []
self.__GnomeFileSelection__lastdirectory = ""
self.__GnomeFileSelection_lastdirectoryread = ""
self.__GnomeFileSelection__shortcuts = SHORTCUTS
if (log4pyavailable == gtk.TRUE):
self.log4py = Logger().get_instance(self)
self.log4py.set_loglevel(loglevel)
self.log4py.debug("GnomeFileSelection initialized")
else:
self.log4py = None
self.__GnomeFileSelection_drawwindow()
def __GnomeFileSelection_drawwindow(self):
self.window = gtk.Window()
self.window.set_title(self.windowtitle)
self.window.set_border_width(5)
lookinlabel = gtk.Label("Look in:")
lookinlabel.show()
self.lookinpath = gtk.Entry()
self.lookinpath.connect("key_press_event", self.__GnomeFileSelection_changedirectorymanually)
self.lookinpath.set_text(iso2utf(self.path))
self.lookinpath.show()
if (self.icondir != ""):
# Create a button to go on directory up
btnUpOneDir = gtk.Button()
imageUpOneDir = gtk.Image()
imageUpOneDir.set_from_pixbuf(gtk.gdk.pixbuf_new_from_file("%sstock_up-one-dir.png" % self.icondir))
imageUpOneDir.show()
btnUpOneDir.add(imageUpOneDir)
# Create a button to create a new directory
btnNewDir = gtk.Button()
imageNewDir = gtk.Image()
imageNewDir.set_from_pixbuf(gtk.gdk.pixbuf_new_from_file("%sstock_new-dir.png" % self.icondir))
imageNewDir.show()
btnNewDir.add(imageNewDir)
# Create a button to go back one directory
btnBackDir = gtk.Button()
imageBackDir = gtk.Image()
imageBackDir.set_from_pixbuf(gtk.gdk.pixbuf_new_from_file("%sstock_back-dir.png" % self.icondir))
imageBackDir.show()
btnBackDir.add(imageBackDir)
else:
btnUpOneDir = gtk.Button(" .. ")
btnNewDir = gtk.Button(" New ")
btnBackDir = gtk.Button(" Back ")
btnUpOneDir.connect("clicked", self.__GnomeFileSelection_changetoparentdir)
btnUpOneDir.show()
btnBackDir.connect("clicked", self.__FileSelectionDialog_changelastdir)
btnBackDir.show()
btnNewDir.connect("clicked", self.__FileSelectionDialog_createdirectory)
btnNewDir.show()
lookinbox = gtk.HBox(spacing = 5)
lookinbox.pack_start(lookinlabel, expand = gtk.FALSE)
lookinbox.pack_start(self.lookinpath)
lookinbox.pack_start(btnUpOneDir, expand = gtk.FALSE)
lookinbox.pack_start(btnBackDir, expand = gtk.FALSE)
lookinbox.pack_start(btnNewDir, expand = gtk.FALSE)
lookinbox.show()
if (self.icondir != ""):
self.fileclist = gtk.CList(4, ["", " Name ", " Size ", " Last modified "])
self.fileclist.set_column_width(0, 18)
self.fileclist.set_column_width(1, 132)
self.fileclist.set_column_width(2, 80)
self.fileclist.set_column_width(3, 155)
self.fileclist.set_column_justification(2, gtk.JUSTIFY_RIGHT)
self.fileclist.set_column_justification(3, gtk.JUSTIFY_RIGHT)
else:
self.fileclist = gtk.CList(3, [" Name ", " Size ", " Last modified "])
self.fileclist.set_column_width(0, 150)
self.fileclist.set_column_width(1, 80)
self.fileclist.set_column_width(2, 155)
self.fileclist.set_column_justification(1, gtk.JUSTIFY_RIGHT)
self.fileclist.set_column_justification(2, gtk.JUSTIFY_RIGHT)
self.fileclist.set_size_request(440, 245)
self.fileclist.set_selection_mode(self.selectiontype)
self.fileclist.connect("key_press_event", self.__GnomeFileSelection_changedirectorykeyboard)
self.fileclist.connect("button_press_event", self.__GnomeFileSelection_changedirectory)
self.fileclist.connect("select_row", self.__GnomeFileSelection_updatefileselection)
self.fileclist.connect("unselect_row", self.__GnomeFileSelection_updatefileselection)
self.fileclist.show()
filescrolledwin = gtk.ScrolledWindow()
filescrolledwin.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
filescrolledwin.add(self.fileclist)
filescrolledwin.show()
filenamelabel = gtk.Label("Filename:")
filenamelabel.set_alignment(0, 0.5)
filenamelabel.show()
self.filename = gtk.Entry()
self.filename.show()
filetypeoptionmenu = gtk.OptionMenu()
self.filetypemenu = gtk.Menu()
self.filetypemenu.show()
self.filetypeitems = {}
for i in range(len(self.filetypes)):
description = self.filetypes[i][0] + " ("
for j in range(len(self.filetypes[i][1])):
extension = self.filetypes[i][1][j]
if (extension == "*"):
description = "%s%s; " % (description, extension)
else:
description = "%s*.%s; " % (description, extension)
description = "%s)" % description[:-2]
self.filetypeitems[i] = gtk.MenuItem(description)
self.filetypeitems[i].connect("activate", self.__GnomeFileSelection_activatefiletype)
self.filetypeitems[i].show()
self.filetypemenu.append(self.filetypeitems[i])
self.__GnomeFileSelection__updateonactivate = gtk.FALSE
self.filetypemenu.activate_item(self.filetypeitems[0], gtk.TRUE)
self.__GnomeFileSelection__updateonactivate = gtk.TRUE
filetypeoptionmenu.set_menu(self.filetypemenu)
filetypeoptionmenu.show()
filetypelabel = gtk.Label("Files of type: ")
filetypelabel.set_alignment(0, 0.5)
filetypelabel.show()
filetable = gtk.Table(2, 2)
filetable.attach(filenamelabel, 0, 1, 0, 1, gtk.FILL, 0)
filetable.attach(self.filename, 1, 2, 0, 1)
filetable.attach(filetypelabel, 0, 1, 1, 2, gtk.FILL, 0)
filetable.attach(filetypeoptionmenu, 1, 2, 1, 2, gtk.FILL, 0)
filetable.show()
self.hidden = gtk.CheckButton("Show hidden files and directories")
self.hidden.set_active(self.showhiddenfiles)
self.hidden.connect("clicked", self.__GnomeFileSelection_changehiddenfiles)
self.hidden.show()
dummy = gtk.Label("")
dummy.show()
self.ok_button = gtk.Button(stock="gtk-ok")
self.ok_button.set_size_request(75, -1)
self.ok_button.show()
self.close_button = gtk.Button(stock="gtk-close")
self.close_button.set_size_request(75, -1)
self.close_button.show()
buttonbox = gtk.HBox(spacing = 5)
buttonbox.pack_start(self.hidden, expand = gtk.FALSE)
buttonbox.pack_start(dummy)
buttonbox.pack_start(self.ok_button, expand = gtk.FALSE)
buttonbox.pack_start(self.close_button, expand = gtk.FALSE)
buttonbox.show()
tvShortcuts = gtk.TreeView()
self.__FileSelectionDialog_addshortcuts()
tvShortcuts.set_model(self.__FileSelectionDialog_shortcut_store)
cell = gtk.CellRendererPixbuf()
col = gtk.TreeViewColumn(' Shortcuts ', cell, pixbuf=0)
tvShortcuts.append_column(col)
tvShortcuts.connect("row-activated", self.__FileSelectionDialog_changeshortcut)
tvShortcuts.show()
rightbox = gtk.VBox(spacing = 5)
rightbox.pack_start(filescrolledwin, expand = gtk.TRUE, fill = gtk.TRUE)
rightbox.pack_start(filetable, expand = gtk.FALSE)
rightbox.pack_start(buttonbox, expand = gtk.FALSE)
rightbox.show()
shortfilebox = gtk.HBox(spacing = 5)
shortfilebox.pack_start(tvShortcuts, expand = gtk.FALSE)
shortfilebox.pack_start(rightbox, expand = gtk.TRUE, fill = gtk.TRUE)
shortfilebox.show()
openfilebox = gtk.VBox(spacing = 5)
openfilebox.pack_start(lookinbox, expand = gtk.FALSE)
openfilebox.pack_start(shortfilebox)
openfilebox.show()
self.window.add(openfilebox)
def __FileSelectionDialog_addshortcuts(self):
""" Create a liststore and add shortcuts from the shortcut file. """
self.__FileSelectionDialog_shortcut_store = gtk.ListStore(gtk.gdk.Pixbuf)
for i in range(len(self.__GnomeFileSelection__shortcuts)):
# add dummy entry to the store
self.__FileSelectionDialog_shortcut_store.append(None)
tuple = self.__GnomeFileSelection__shortcuts[i]
# set store value
self.__GnomeFileSelection_setshortcutbyindex(i, tuple[0], tuple[1])
def __GnomeFileSelection_getfreeshortcutindex(self):
index = 0
for i in range(len(self.__GnomeFileSelection__shortcuts)):
if (self.__GnomeFileSelection__shortcuts[i][0] != ""):
index = (i + 1)
else:
return index
return index
def __GnomeFileSelection_getlastshortcutindex(self):
return self.__GnomeFileSelection_getfreeshortcutindex() - 1
def __GnomeFileSelection_setshortcutbyindex(self, index, identifier, target):
shortcut = self.__GnomeFileSelection__shortcuts[index]
shortcut[0] = identifier
target = sub("\$HOME", replace(get_homedirectory(), "\\", "\\\\"), target)
# Check wether the GNOME Desktop directory exists
if (os.path.exists("%s%s.gnome-desktop" % (get_homedirectory(), os.sep))):
target = sub("\$DESKTOP", replace("%s%s.gnome-desktop" % (get_homedirectory(), os.sep), "\\", "\\\\"), target)
# Check wether the KDE Desktop directory exists
elif (os.path.exists("%s%sDesktop" % (get_homedirectory(), os.sep))):
target = sub("\$DESKTOP", replace("%s%sDesktop" % (get_homedirectory(), os.sep), "\\", "\\\\"), target)
# Use the HOME directory
else:
target = sub("\$DESKTOP", replace(get_homedirectory(), "\\", "\\\\"), target)
target = sub("\$CWD", getcwd(), target)
shortcut[1] = target
self.__GnomeFileSelection__shortcuts[index] = shortcut
if (identifier != "") and (self.icondir != ""):
iter_child = self.__FileSelectionDialog_shortcut_store.iter_nth_child(None, index)
pixbuf = get_file_pixbuf(identifier, self.icondir)
self.__FileSelectionDialog_shortcut_store.set(iter_child, 0, pixbuf)
def __GnomeFileSelection_readdirectory(self, filterchanged = gtk.FALSE):
if (self.path == self.__GnomeFileSelection_lastdirectoryread) and (filterchanged == gtk.FALSE):
return
self.fileclist.clear()
self.filename.set_text("")
self.fileclist.freeze()
if (self.log4py != None):
self.log4py.debug("Reading directory: %s" % self.path)
if (not (os.path.exists(self.path))):
if (self.log4py != None):
self.log4py.error("Error: Directory %s doesn't exist - using $HOME" % self.path)
self.path = get_homedirectory()
self.lookinpath.set_text(iso2utf(self.path))
try:
files = listdir(self.path)
except (OSError), detail:
files = []
ErrorDialog("%s" % detail)
files.sort()
linenumber = 0
# First show all directories
for i in range(len(files)):
filename = "%s%s%s" % (self.path, os.sep, files[i])
showfile = not ((self.showhiddenfiles == gtk.FALSE) and (files[i][0] == "."))
if (os.path.exists(filename)) and (os.path.isdir(filename)) and (showfile == gtk.TRUE):
statinfo = stat(filename)
if (self.icondir != ""):
self.fileclist.append(["", iso2utf(files[i]), lng2str(statinfo[6]), asctime(localtime(statinfo[8]))])
icon, mask = get_file_icon("DIRECTORY", self.window, self.icondir)
self.fileclist.set_pixmap(linenumber, 0, icon, mask)
else:
self.fileclist.append([iso2utf(files[i]), lng2str(statinfo[6]), asctime(localtime(statinfo[8]))])
if (divmod(linenumber, 2)[1] == 0):
gdkcolor = hex2gdkcolor(self.window, "#f6f6f6")
if (gdkcolor != None):
self.fileclist.set_background(linenumber, gdkcolor)
linenumber = linenumber + 1
# And now all other files and symlinks
for i in range(len(files)):
filename = "%s%s%s" % (self.path, os.sep, files[i])
showfile = not ((self.showhiddenfiles == gtk.FALSE) and (files[i][0] == "."))
if (showfile == gtk.TRUE):
extensionok = gtk.FALSE
for j in range(len(self.currentextension)):
extension = lower(self.currentextension[j])
if (extension == "*") or ((len(files[i]) >= len(extension)) and (extension == files[i][len(files[i])-(len(extension)):])):
extensionok = gtk.TRUE
if (os.path.exists(filename)) and (not os.path.isdir(filename)) and (showfile == gtk.TRUE) and (extensionok == gtk.TRUE):
statinfo = stat(filename)
if (self.icondir != ""):
self.fileclist.append(["", iso2utf(files[i]), lng2str(statinfo[6]), asctime(localtime(statinfo[8]))])
icon, mask = get_file_icon(files[i], self.window, self.icondir)
self.fileclist.set_pixmap(linenumber, 0, icon, mask)
else:
self.fileclist.append([iso2utf(files[i]), lng2str(statinfo[6]), asctime(localtime(statinfo[8]))])
if (divmod(linenumber, 2)[1] == 0):
gdkcolor = hex2gdkcolor(self.window, "#f6f6f6")
if (gdkcolor != None):
self.fileclist.set_background(linenumber, gdkcolor)
linenumber = linenumber + 1
self.fileclist.thaw()
self.__GnomeFileSelection_lastdirectoryread = self.path
def __GnomeFileSelection_changetoparentdir(self, args):
if (self.path != os.sep):
self.path = join(split(self.path, os.sep)[:-1], os.sep)
if (self.path == ""):
self.path = os.sep
# Replace C: by C:\
elif ((platform == "win32") and (self.path[-1] == ":")):
self.path = "%s%s" % (self.path, os.sep)
self.lookinpath.set_text(iso2utf(self.path))
self.__GnomeFileSelection_readdirectory()
def __FileSelectionDialog_changelastdir(self, args):
self.path = self.__GnomeFileSelection__lastdirectory
self.lookinpath.set_text(iso2utf(self.path))
self.__GnomeFileSelection_readdirectory()
def __FileSelectionDialog_createdirectory(self, args):
""" Create a new directory and automatically change into it. """
input_dialog = InputDialog(self.window, "Create new directory", "Directory name:", width=200, type=gtk.MESSAGE_QUESTION)
result = input_dialog.get_result()
if (result != ""):
current_directory = utf2iso(self.lookinpath.get_text())
new_directory = "%s%s%s" % (current_directory, os.sep, result)
mkdir(new_directory)
self.path = new_directory
self.lookinpath.set_text(iso2utf(new_directory))
self.__GnomeFileSelection_readdirectory()
def __GnomeFileSelection_changedirectorykeyboard(self, clist, event):
""" Add a file by pressing Enter on the keyboard. """
if ((event.keyval == 65293) or (event.keyval == 65421)):
self.ok_button.emit("clicked")
def __GnomeFileSelection_changedirectory(self, clist, event):
if (event.type == gtk.gdk._2BUTTON_PRESS): # Double click
try:
row = self.fileclist.get_selection_info(int(event.x), int(event.y))[0]
if (self.icondir != ""):
columnnr = 1
else:
columnnr = 0
directory = utf2iso(self.fileclist.get_text(row, columnnr))
if (self.path[-1] == os.sep):
tmppath = "%s%s" % (self.path, directory)
else:
tmppath = "%s%s%s" % (self.path, os.sep, directory)
if (os.path.isdir(tmppath)):
self.path = tmppath
self.lookinpath.set_text(iso2utf(self.path))
self.__GnomeFileSelection_readdirectory()
else:
self.ok_button.emit("clicked")
except:
row = -1
def __GnomeFileSelection_updatefileselection(self, clist, row, column, event):
if (self.icondir != ""):
columnnr = 1
else:
columnnr = 0
if (len(self.fileclist.selection) == 1):
filenames = utf2iso(self.fileclist.get_text(self.fileclist.selection[0], columnnr))
else:
filenames = ""
for i in range(len(self.fileclist.selection)):
filename = utf2iso(self.fileclist.get_text(self.fileclist.selection[i], columnnr))
filenames = "%s\"%s\" " % (filenames, filename)
if (len(filenames) > 0):
filenames = filenames[:-1]
self.filename.set_text(iso2utf(filenames))
def __GnomeFileSelection_changedirectoryselection(self, clist, clistitem):
path = utf2iso(self.lookinpath.get_text())
if (os.path.isdir(path)):
if (self.path != path):
self.path = path
self.__GnomeFileSelection_readdirectory()
else:
gnome.ui.ErrorDialog("Error - %s is not a valid directory !" % path)
def __GnomeFileSelection_changedirectorymanually(self, entry, event):
if ((event.keyval == 65293) or (event.keyval == 65421)):
# path = self.lookinpath.gtk_entry().get_text()
path = utf2iso(self.lookinpath.get_text())
if (os.path.isdir(path)):
if (self.path != path):
self.path = path
self.__GnomeFileSelection_readdirectory()
else:
gnome.ui.ErrorDialog("Error - %s is not a valid directory !" % path)
def __GnomeFileSelection_changehiddenfiles(self, args):
self.showhiddenfiles = self.hidden.get_active()
self.__GnomeFileSelection_readdirectory(gtk.TRUE)
def __GnomeFileSelection_activatefiletype(self, args):
self.currentextension = self.filetypes[indexof(self.filetypeitems, self.filetypemenu.get_active())][1]
if (self.__GnomeFileSelection__updateonactivate == gtk.TRUE):
self.__GnomeFileSelection_readdirectory(gtk.TRUE)
def __FileSelectionDialog_changeshortcut(self, path, view_column, args):
row = view_column[0]
if (self.__GnomeFileSelection__shortcuts[row][1] != ""):
self.path = self.__GnomeFileSelection__shortcuts[row][1]
self.lookinpath.set_text(iso2utf(self.path))
self.__GnomeFileSelection_readdirectory()
def __GnomeFileSelection_loadlastdirectory(self):
if (os.path.exists(self.__GnomeFileSelection__lastdirectoryfilename)):
file = open(self.__GnomeFileSelection__lastdirectoryfilename, "r")
self.__GnomeFileSelection__lastdirectory = strip(file.readline())
file.close()
if (self.log4py != None):
self.log4py.debug("Last directory %s loaded from %s" % (self.__GnomeFileSelection__lastdirectory, self.__GnomeFileSelection__lastdirectoryfilename))
self.path = self.__GnomeFileSelection__lastdirectory
# FIXME: self.lookinpath.gtk_entry().set_text(self.__GnomeFileSelection__lastdirectory)
self.lookinpath.set_text(iso2utf(self.__GnomeFileSelection__lastdirectory))
def __GnomeFileSelection_savelastdirectory(self):
file = open(self.__GnomeFileSelection__lastdirectoryfilename, "w")
file.write("%s\n" % utf2iso(self.lookinpath.get_text()))
file.close()
def show(self):
self.__GnomeFileSelection_readdirectory()
self.window.show()
def destroy(self, args = None):
if (self.__GnomeFileSelection__lastdirectoryfilename != ""):
self.__GnomeFileSelection_savelastdirectory()
self.window.destroy()
def get_filenames(self):
utf_filenames = self.get_filenames_utf()
if (type(utf_filenames) == StringType):
return utf2iso(utf_filenames)
else:
return map(utf2iso, utf_filenames)
def get_filenames_utf(self):
if (self.selectiontype == gtk.SELECTION_SINGLE):
return self.filename.get_text()
else:
if (len(self.filename.get_text()) > 0):
if (self.filename.get_text()[0] != "\""):
filenames = [self.filename.get_text()]
else:
filenames = self.filename.get_text()
filenames = filenames[1:-1]
filenames = split(filenames, "\" \"")
else:
filenames = []
return filenames
def get_directory_utf(self):
return self.lookinpath.get_text()
def get_directory(self):
return utf2iso(self.get_directory_utf())
def clear_shortcuts(self):
for i in range(len(self.__GnomeFileSelection__shortcuts)):
iter_child = self.__FileSelectionDialog_shortcut_store.iter_nth_child(None, i)
self.__FileSelectionDialog_shortcut_store.set(iter_child, 0, None)
def append_shortcut(self, identifier, target):
freeindex = self.__GnomeFileSelection_getfreeshortcutindex()
self.__GnomeFileSelection_setshortcutbyindex(freeindex, identifier, target)
def remove_shortcut(self):
lastindex = self.__GnomeFileSelection_getlastshortcutindex()
self.__GnomeFileSelection__shortcuts[lastindex][0] = ""
self.__GnomeFileSelection__shortcuts[lastindex][1] = ""
self.shortcuts.set_text(lastindex, 0, "")
def load_shortcuts_from_file(self, filename):
if (not os.path.exists(filename)):
if (self.log4py != None):
self.log4py.error("Shortcut file %s doesn't exist." % filename)
return
self.clear_shortcuts()
parser = ConfigParser()
parser.read(filename)
section = "shortcuts"
for i in range(len(parser.options(section))):
option = lower(parser.options(section)[i])
if (option[:8] == "shortcut"):
value = strip(parser.get(section, option, 1))
if (value != ""):
if (find(value, ":") == -1):
if (self.log4py != None):
self.log4py.error("Invalid entry #%d in %s: %s" % (atoi(option[8:]), filename, value))
else:
splitted = split(value, ":")
index = atoi(option[8:])
self.__GnomeFileSelection_setshortcutbyindex(index, upper(strip(splitted[0])), strip(splitted[1]))
def use_lastdirectory(self, filename):
self.__GnomeFileSelection__lastdirectoryfilename = filename
if (self.__GnomeFileSelection__lastdirectoryfilename != ""):
self.__GnomeFileSelection_loadlastdirectory()
class ProgressBar:
def __init__(self, title, description, maxvalue, minvalue = 0.0):
imgInfo = gtk.image_new_from_stock(gtk.STOCK_DIALOG_INFO, gtk.ICON_SIZE_DIALOG)
imgInfo.show()
labDescription = gtk.Label(description)
# labDescription.set_size_request(150, -1)
labDescription.set_alignment(0, 0.5)
labDescription.show()
self.__ProgressBar_value = minvalue
self.__ProgressBar_maxvalue = maxvalue
self.progressbar = gtk.ProgressBar()
self.progressbar.set_text("%d of %d (%2d%%)" % (self.__ProgressBar_value, self.__ProgressBar_maxvalue, self.__ProgressBar_value / self.__ProgressBar_maxvalue))
self.progressbar.show()
status_table = gtk.Table(2, 2)
status_table.attach(imgInfo, 0, 1, 0, 2, 0, 0, 3, 3)
status_table.attach(labDescription, 1, 2, 0, 1, gtk.FILL, 0, 3, 3)
status_table.attach(self.progressbar, 1, 2, 1, 2, gtk.FILL, 0, 3, 3)
status_table.show()
self.window = gtk.Window()
self.window.set_title(title)
self.window.set_border_width(3)
self.window.add(status_table)
self.window.show()
self.redraw()
def redraw(self):
while (gtk.events_pending()):
gtk.mainiteration(0)
def update(self, step = 1):
self.__ProgressBar_value = self.__ProgressBar_value + step
self.progressbar.set_fraction(self.__ProgressBar_value / self.__ProgressBar_maxvalue)
self.progressbar.set_text("%d of %d (%2d%%)" % (self.__ProgressBar_value, self.__ProgressBar_maxvalue, self.progressbar.get_fraction() * 100))
self.redraw()
def close(self):
self.redraw()
sleep(0.3)
self.window.destroy()
self.window = None
# Pixmap: easier, faster and more flexible way to access pixmaps
class Pixmap:
def __init__(self, window, pixmap, label = None):
icon, mask = create_pixmap(window, pixmap)
self.__Pixmap_pixmap = gtk.Image()
self.__Pixmap_pixmap.set_from_pixmap(icon, mask)
self.__Pixmap_pixmap.show()
if (label != None):
self.__Pixmap_label = gtk.Label(label)
self.__Pixmap_label.set_padding(2, 2)
self.__Pixmap_label.show()
self.__Pixmap_hbox = gtk.HBox()
self.__Pixmap_hbox.add(self.__Pixmap_pixmap)
self.__Pixmap_hbox.add(self.__Pixmap_label)
self.__Pixmap_hbox.show()
self.__Pixmap_object = self.__Pixmap_hbox
else:
self.__Pixmap_label = None
self.__Pixmap_hbox = None
self.__Pixmap_object = self.__Pixmap_pixmap
def show(self):
self.__Pixmap_object.show()
def hide(self):
self.__Pixmap_object.hide()
def get_pixmap(self):
return self.__Pixmap_pixmap
def get_hbox(self):
return self.__Pixmap_hbox
# OptionMenu is an easy way to build OptionMenus
class OptionMenu:
def __init__(self, loglevel = 1 << 1):
self.__GnomeOptionMenu_optionmenu = gtk.OptionMenu()
self.__GnomeOptionMenu_menu = gtk.Menu()
self.__GnomeOptionMenu_menu.show()
self.__GnomeOptionMenu_previousitem = None
self.__GnomeOptionMenu_items = {}
if (log4pyavailable == gtk.TRUE):
self.log4py = Logger().get_instance(self)
self.log4py.set_loglevel(loglevel)
else:
self.log4py = None
def get_active_item(self):
for i in range(len(self.__GnomeOptionMenu_items.keys())):
key = self.__GnomeOptionMenu_items.keys()[i]
if (self.__GnomeOptionMenu_items[key].active):
return key
return None
def activate_item(self, key):
if (self.__GnomeOptionMenu_items.has_key(key)):
item = self.__GnomeOptionMenu_items[key]
self.__GnomeOptionMenu_menu.select_item(item)
self.__GnomeOptionMenu_menu.activate_item(item, gtk.TRUE)
else:
if (self.log4py != None):
self.log4py.error("Item %s doesn't exist." % key)
def get_gtkoptionmenu(self):
return self.__GnomeOptionMenu_optionmenu
def append_item(self, item):
self.__GnomeOptionMenu_items[item] = gtk.RadioMenuItem(self.__GnomeOptionMenu_previousitem, item)
self.__GnomeOptionMenu_items[item].show()
self.__GnomeOptionMenu_menu.append(self.__GnomeOptionMenu_items[item])
self.__GnomeOptionMenu_previousitem = self.__GnomeOptionMenu_items[item]
def append_itemlist(self, itemlist):
for i in range(len(itemlist)):
self.append_item(itemlist[i])
def show(self):
self.__GnomeOptionMenu_optionmenu.set_menu(self.__GnomeOptionMenu_menu)
self.__GnomeOptionMenu_optionmenu.show()
class TipWindow:
def __init__(self, config_file, tips, icondir, application_name, boolshowtipalways = gtk.FALSE):
""" Initialize the window and show a random tip. """
self.__GnomeTip_current_tip = -1
self.__GnomeTip_config_file = config_file
self.__GnomeTip_load_config()
if (self.__GnomeTip_show_window == gtk.FALSE) and (boolshowtipalways == gtk.FALSE):
self.window = None
return # Somehow the user doesn't like tips ...
self.__GnomeTip_all_tips = tips
self.window = gtk.Window()
if (application_name != ""):
self.window.set_title("%s - Tip of the Day" % application_name)
else:
self.window.set_title("Tip of the Day")
self.window.connect("destroy", self.__GnomeTip_close)
self.tip = gtk.Label("")
self.__GnomeTip_set_tip(self.__GnomeTip_get_random_tip())
self.tip.show()
tipBox = gtk.HBox(spacing = 5)
if (os.path.exists("%s%sgnome-hint.xpm" % (icondir, os.sep))):
icon, mask = create_pixmap(self.window, "%s%sgnome-hint.xpm" % (icondir, os.sep))
pixmap = gtk.Image()
pixmap.set_from_pixmap(icon, mask)
pixmap.show()
tipBox.pack_start(pixmap, expand = gtk.FALSE)
tipBox.pack_start(self.tip)
tipBox.show()
closeButton = gtk.Button(stock="gtk-close")
closeButton.connect("clicked", self.__GnomeTip_close)
closeButton.show()
nextTipButton = gtk.Button(" Next Tip ")
nextTipButton.connect("clicked", self.__GnomeTip_next_tip)
nextTipButton.show()
previousTipButton = gtk.Button(" Previous Tip ")
previousTipButton.connect("clicked", self.__GnomeTip_previous_tip)
previousTipButton.show()
self.showTipOnStartUp = gtk.CheckButton("Show tips on startup")
self.showTipOnStartUp.set_active(self.__GnomeTip_show_window)
self.showTipOnStartUp.show()
dummyLabel = gtk.Label("")
dummyLabel.show()
buttonBar = gtk.HBox(spacing = 3)
buttonBar.pack_start(self.showTipOnStartUp, expand = gtk.FALSE)
buttonBar.pack_start(dummyLabel)
buttonBar.pack_start(previousTipButton, expand = gtk.FALSE)
buttonBar.pack_start(nextTipButton, expand = gtk.FALSE)
buttonBar.pack_start(closeButton, expand = gtk.FALSE)
buttonBar.show()
fullBox = gtk.VBox()
fullBox.pack_start(tipBox, expand = gtk.FALSE)
fullBox.pack_start(buttonBar, expand = gtk.FALSE)
fullBox.show()
self.window.set_border_width(3)
self.window.add(fullBox)
def __GnomeTip_set_tip(self, tip):
""" Set a new tip. """
self.__GnomeTip_current_tip = self.__GnomeTip_all_tips.index(tip)
text = "Tip %d: %s" % (self.__GnomeTip_current_tip + 1, tip)
self.tip.set_text(text)
def __GnomeTip_next_tip(self, args):
""" Move on to the next tip. """
if (len(self.__GnomeTip_all_tips) >= (self.__GnomeTip_current_tip + 2)):
self.__GnomeTip_set_tip(self.__GnomeTip_all_tips[self.__GnomeTip_current_tip + 1])
else:
self.__GnomeTip_set_tip(self.__GnomeTip_all_tips[0])
def __GnomeTip_previous_tip(self, args):
""" Show the previous tip. """
if (self.__GnomeTip_current_tip > 0):
self.__GnomeTip_set_tip(self.__GnomeTip_all_tips[self.__GnomeTip_current_tip - 1])
else:
self.__GnomeTip_set_tip(self.__GnomeTip_all_tips[len(self.__GnomeTip_all_tips) - 1])
def __GnomeTip_close(self, args):
""" Close the GnomeTip window. """
self.__GnomeTip_save_config()
self.window.destroy()
def __GnomeTip_get_random_tip(self):
""" Returns a random tip (for startup). """
tip = choice(self.__GnomeTip_all_tips)
return tip
def __GnomeTip_load_config(self):
""" Load the configuration file. """
if (os.path.exists(self.__GnomeTip_config_file)):
parser = ConfigParser()
parser.read(self.__GnomeTip_config_file)
self.__GnomeTip_show_window = parser.getboolean("GnomeTip", "ShowGnomeTipWindow")
else:
self.__GnomeTip_show_window = gtk.TRUE
def __GnomeTip_save_config(self):
""" Save the configuration file. """
file = open(self.__GnomeTip_config_file, "w")
file.write("[GnomeTip]\n")
file.write("ShowGnomeTipWindow: %d\n" % self.showTipOnStartUp.get_active())
file.close()
def show(self):
""" Show the GnomeTip window. """
if (self.window != None):
self.window.show()
class ErrorDialog:
def __init__(self, message):
dialog = gtk.MessageDialog(None,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
gtk.MESSAGE_ERROR, gtk.BUTTONS_OK,
message)
dialog.run()
dialog.destroy()
class InfoDialog:
def __init__(self, message):
dialog = gtk.MessageDialog(None,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
gtk.MESSAGE_INFO, gtk.BUTTONS_OK,
message)
dialog.run()
dialog.destroy()
class WarningDialog:
def __init__(self, message):
dialog = gtk.MessageDialog(None,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
gtk.MESSAGE_WARNING, gtk.BUTTONS_OK,
message)
dialog.run()
dialog.destroy()
class QuestionDialog:
def __init__(self, message, buttons_type = gtk.BUTTONS_YES_NO):
dialog = gtk.MessageDialog(None,
gtk.DIALOG_DESTROY_WITH_PARENT,
gtk.MESSAGE_QUESTION, buttons_type,
message)
self.__QuestionDialog_result = dialog.run()
dialog.destroy()
def get_result(self):
return self.__QuestionDialog_result
class InputDialog:
def __init__(self, parent, title, message, text = "", width = -1, type = gtk.MESSAGE_INFO):
# Create a image for the message type
if (type == gtk.MESSAGE_INFO):
messageTypeImage = gtk.image_new_from_stock(gtk.STOCK_DIALOG_INFO, gtk.ICON_SIZE_DIALOG)
elif (type == gtk.MESSAGE_WARNING):
messageTypeImage = gtk.image_new_from_stock(gtk.STOCK_DIALOG_WARNING, gtk.ICON_SIZE_DIALOG)
elif (type == gtk.MESSAGE_QUESTION):
messageTypeImage = gtk.image_new_from_stock(gtk.STOCK_DIALOG_QUESTION, gtk.ICON_SIZE_DIALOG)
elif (type == gtk.MESSAGE_ERROR):
messageTypeImage = gtk.image_new_from_stock(gtk.STOCK_DIALOG_ERROR, gtk.ICON_SIZE_DIALOG)
messageTypeImage.show()
# Create the text label with the message
label = gtk.Label(" %s " % message)
label.set_alignment(0, 0.5)
label.show()
# Create an entry field
entry = gtk.Entry()
entry.set_size_request(width, -1)
entry.set_text(text)
entry.show()
# Create a table with the icon, label and entry field
dialog_table = gtk.Table(2, 2)
dialog_table.attach(messageTypeImage, 0, 1, 0, 2, 0, 0, 3, 3)
dialog_table.attach(label, 1, 2, 0, 1, gtk.FILL, 0, 3, 3)
dialog_table.attach(entry, 1, 2, 1, 2, 0, 0, 3, 3)
dialog_table.show()
buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OK, gtk.RESPONSE_OK)
dialog = gtk.Dialog(title, parent, gtk.DIALOG_DESTROY_WITH_PARENT or gtk.DIALOG_MODAL, buttons)
dialog.set_default_response(gtk.RESPONSE_OK)
dialog.vbox.pack_start(dialog_table)
# dialog.vbox.pack_start(entry)
dialog.show()
self.__InputDialog_result = dialog.run()
self.__InputDialog_text = entry.get_text()
dialog.destroy()
def get_result(self):
if (self.__InputDialog_result == gtk.RESPONSE_OK):
return self.__InputDialog_text
else:
return ""
syntax highlighted by Code2HTML, v. 0.9.1