On 21 Jul 2004 19:18:25 -0500
Doug Quale <[EMAIL PROTECTED]> wrote:

> I was imagining a simple system that required the application
> programmer to save the preferences and load them into the appropriate
> widgets by hand.  This would be very tedious, but smarter mechanisms
> could be built on top of those low level facilities.  Maybe this is
> aiming too low.

Well, here's some code that aims even lower -- I use the attached class in my 
applications as a way to remember where a user has positioned a window and the state 
of various widgets (panes, toggles). I haven't yet used it for scrollbars, but it 
should be do-able. I ran into some trouble with adjustable column-widths as I couldn't 
find a reliable way to get and set them while still allowing the user to reset them (I 
believe this has already been commented on). I haven't even thought about touching the 
parts of the TreeView that would require knowing something about the TreeModel.

Tom
#!/usr/bin/env python
import gtk, gtk.gdk

class WidgetSaver:

    """A class to save and load widget properties to/from a
    dictionary. We leave it to whoever hands us the dictionary to save
    the dictionary. dictionary should contain a property name as a key
    and a value as a value. On __init__, we will load these properties
    into the widget and who the widget. Each signal in signals will be
    connected to save_properties"""

    def __init__ (self, widget, dictionary={}, signals=['destroy'], show=True):
        self.w = widget
        self.dictionary = dictionary
        self.signals = signals
        self.load_properties()
        for s in self.signals:
            self.w.connect(s,self.save_properties)
        if show: self.w.show()

    def load_properties (self):
        for p,v in self.dictionary.items():
            self.w.set_property(p,v)

    def save_properties (self, *args):
        for p in self.dictionary.keys():
            self.dictionary[p]=self.w.get_property(p)
        return False # we don't handle any signals
    
class WindowSaver (WidgetSaver):
    def __init__ (self, widget, dictionary={},
                  signals=['configure-event','delete-event'],
                  show=True):
        """We save the position and state of the window
        in dictionary. The dictionary consists of
        {window_size: widget.get_size(),
         position: widget.get_position(),}"""
        widget.set_gravity(gtk.gdk.GRAVITY_STATIC)
        WidgetSaver.__init__(self, widget, dictionary, signals, show)

    def load_properties (self):
        for p,f in ['window_size', self.w.resize],['position',self.w.move]:
            if self.dictionary.has_key(p) and self.dictionary[p]:
                apply(f,self.dictionary[p])
        
    def save_properties (self, *args):
        self.dictionary['window_size']=self.w.get_size()
        self.dictionary['position']=self.w.get_position()
        return False
    
if __name__ == '__main__':
    import os.path, pickle

    # set up a quick preference saver which will save the
    # dictionary quick_prefs.config to the config file
    # ~/.testing/widget_positions and load from that file
    # on startup
    class quick_prefs:
        def __init__ (self, file=os.path.expanduser(os.path.join('~/','.testing','widget_positions'))):
            self.file=file
            self.config={}
            self.load()

        def get_pref (self, key, default=None):
            if not self.config.has_key(key):
                self.config[key]=default
            return self.config[key]

        def save (self):
            if not os.path.exists(os.path.split(self.file)[0]):
                ## if our config directory doesn't exist...
                os.makedirs(os.path.split(self.file)[0])
            ofi=open(self.file,'w')
            pickle.dump(self.config,ofi)
            ofi.close()

        def load (self):
            if os.path.isfile(self.file):
                ifi=open(self.file,'r')
                self.config=pickle.load(ifi)
                return True
            else:
                return False

    prefs = quick_prefs()
    # a list of savers we're using...
    savers=[]
    w = gtk.Window()
    wsaver = WindowSaver(w,prefs.get_pref('window',{}))
    savers.append(wsaver)
    vp=gtk.VPaned()
    vps=WidgetSaver(vp,prefs.get_pref('vpane',{'position':vp.get_position()}))
    savers.append(vps)
    vp.add1(gtk.Label('WidgetSaver can remember where this pane was left'))
    w.add(vp)
    exp=gtk.Expander('Expander')
    exp.add(gtk.Label('WidgetSaver can remember whether this widget is expanded or not.'))
    exps=WidgetSaver(exp,
                     prefs.get_pref('expander',
                               {'expanded':exp.get_expanded()}),
                     signals=['activate'])
    savers.append(exps)
    vb = gtk.VBox()
    vb.add(exp)
    vp.add2(vb)
    tog = gtk.CheckButton("WidgetSaver will remember the state\nof this CheckButton")
    togs=WidgetSaver(tog,
                     prefs.get_pref('toggle',{'active':tog.get_active()}),
                     signals=['toggled'])
    savers.append(togs)
    vb.add(tog)
    
    def quit (*args):
        for s in savers:
            s.save_properties()
            prefs.save()
        w.destroy()
        gtk.main_quit()
        

    w.connect('delete-event',quit)
    dbutton=gtk.Button(stock=gtk.STOCK_QUIT)
    dbutton.connect('clicked',quit)
    vb.add(dbutton)

    w.show_all()
    gtk.main()
            
    
    
                                     

    
	
_______________________________________________
pygtk mailing list   [EMAIL PROTECTED]
http://www.daa.com.au/mailman/listinfo/pygtk
Read the PyGTK FAQ: http://www.async.com.br/faq/pygtk/

Reply via email to