uiutils/__init__.py
author Pierre-Yves David <pierre-yves.david@logilab.fr>
Fri, 13 Jun 2008 15:37:48 +0200
changeset 5 ee38ef554863
parent 0 7710b138d4eb
permissions -rw-r--r--
remove apycot.ini

# Copyright (c) 2004 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# Copyright (C) 2002-2003 Stephen Kennedy <stevek@gnome.org>
#   The load_pixbuf() function was taken from meld's source code
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
# pylint: disable-msg=W0402

"""uiutils subpackage defines some misc useful functions and classes for
building windows in OoBrother

__init__.py exports misc useful functions, annd also init_treeview_columns,
and all mixins for convenience
"""

__revision__ = '$Id: __init__.py,v 1.6 2005-03-10 15:38:49 adim Exp $'
__metaclass__ = type

import os.path as osp
import pickle
import gtk

from oobrother import get_path
# Export these class directly in __init__.py for convenience
from oobrother.uiutils.trees import init_treeview_columns
from oobrother.uiutils.basemixins import *

def ask_for_message(message):
    """popup a window for the user to type a message"""
    dlg = gtk.MessageDialog(None, gtk.DIALOG_MODAL, 
                            gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, 
                            message)
    scr = gtk.ScrolledWindow()
    scr.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
    text_view = gtk.TextView()
    scr.add(text_view)
    scr.show_all()
    dlg.vbox.pack_start(scr)
    try:
        if dlg.run() == gtk.RESPONSE_OK:
            buf = text_view.get_buffer()
            msg = buf.get_text(*buf.get_bounds())
            return msg.strip()
        return None
    finally:
        dlg.destroy()


def save_session(wdefs, filepath):
    """save session information (window visibility/size/position)

    filepath is the pickle file where session data will be written
    wdefs is a dictionary mapping window identifier to gtk windows
    """
    data = {}
    for wid, window in wdefs.items():
        visible = window.get_property('visible')
        position = window.get_position()
        size = window.get_size()
        data[wid] = (visible, position, size)
    pickle.dump(data, open(filepath, 'w'))


def restore_session(wdefs, filepath):
    """restore session information (window visibility/size/position)

    filepath is the pickle file where session information can be found
    wdefs is a dictionary mapping window identifier to gtk windows
    """
    try:
        data = pickle.load(open(filepath))
    except IOError:
        return
    for wid, window in wdefs.items():
        visible, position, size = data[wid]
        if visible:
            window.show_all()
            window.window.move_resize(*(position+size))
        else:
            window.hide()
            #window.window.move_resize(*(position+size))
            window.resize(*size)


def merge_actions(actions, _path='', _groups=None):
    """merge a list of actions definitions"""
    if _groups is None:
        _groups = {}
    result = []
    for action in actions:
        label, callback = action[0], action[1]
        if not callable(callback):
            assert isinstance(callback, list) or isinstance(callback, tuple)
            if not callback:
                continue
            group_path = '%s/%s' % (_path, label)
            try:
                group_menu = _groups[group_path]
            except KeyError:
                group_menu = []
                result.append( (label, group_menu) )
            group_menu += merge_actions(callback, group_path, _groups)
        else:
            result.append( action )
    return result


def create_popup_menu(actions, thefile):
    """creates a popup menu widget from a list of actions"""
    menu = gtk.Menu()
    for action in actions:
        label, callback = action[0], action[1]
        item = gtk.MenuItem(label)
        if callable(callback):
            item.connect('activate', callback, thefile, *action[2:])
        elif callback:
            # must be a list or a tuple with a sub-menu definition
            group_menu = create_popup_menu(callback, thefile)
            item.set_submenu(group_menu)
        menu.append(item)
    return menu


def load_pixbuf(pix_name, size = 14):
    """Load an image from a file as a pixbuf, with optional resizing

    this code has been adapted from meld/gnomeglade.py
    """
    fname = osp.join(get_path('pixmaps'), pix_name)
    image = gtk.Image()
    image.set_from_file(fname)
    image = image.get_pixbuf()
    if size:
        aspect = float(image.get_height()) / image.get_width()
        image = image.scale_simple(size, int(aspect*size), 2)
    return image

def change_cursor_for_operation(operation, wdg, cursor = gtk.gdk.WATCH):
    """Changes the cursor of the widget during a given operation
    :type operation: callable
    :param operation: the operation to execute

    :type wdg: gtk.Widget
    :param wdg: the widget for which the cursor is changed

    :type cursor: int
    :param cursor: cursor's constant value
    """
    gdk_cursor = gtk.gdk.Cursor(cursor)
    wdg.window.set_cursor(gdk_cursor)
    operation()
    wdg.window.set_cursor(None)