; docformat = 'rst'
;+
; Preferences are stored between IDL sessions in SAV files in the directory
; returned by APP_USER_DIR.
;
; :Examples:
; To store a preference::
;
; IDL> prefs = obj_new('mg_prefs', author='mgalloy', application='myapp')
; IDL> prefs->set, 'last_edited', 'myfile.txt'
;
; Then in a later IDL sesson this preference can be retrieved::
;
; IDL> prefs = obj_new('mg_prefs', author='mgalloy', application='myapp')
; IDL> print, prefs->get('last_edited')
; myfile.txt
;-
;+
; Converts a preference to a full path specified filename to store the
; preference.
;
; :Private:
;
; :Returns:
; string
;
; :Params:
; prefname : in, required, type=string
; prefname to convert to a filename
;-
function mg_prefs::_constructFilename, prefname
compile_opt strictarr
return, filepath(idl_validname(prefname, /convert_all) + '.sav', $
root=self.configdir)
end
function mg_prefs::get, prefname, default=default, found=found
compile_opt strictarr
found = 0B
filename = self->_constructFilename(prefname)
if (~file_test(filename)) then begin
return, n_elements(default) eq 0L ? -1L : default
endif
restore, filename=filename
found = 1B
return, prefvalue
end
;+
; Set a preference.
;
; :Params:
; prefname : in, required, type=string
; preference name
; prefvalue : in, required, type=any
; preference value
;-
pro mg_prefs::set, prefname, prefvalue
compile_opt strictarr
save, prefvalue, filename=self->_constructFilename(prefname)
end
;+
; Free resources.
;-
pro mg_prefs::cleanup
compile_opt strictarr
end
;+
; Initialize a preference object.
;
; :Returns:
; 1 for success, 0 for failure
;
; :Keywords:
; author : in, required, type=string
; author name
; application : in, required, type=string
; application name
;-
function mg_prefs::init, author=author, application=application
compile_opt strictarr
on_error, 2
if (n_elements(author) eq 0L) then message, 'AUTHOR required'
if (n_elements(application) eq 0L) then message, 'APPLICATION required'
appdir = app_user_dir(author, 'Author description', $
application, 'Application description', $
'Readme text', 1)
self.configdir = filepath('', subdir='prefs', root=appdir)
if (~file_test(self.configdir)) then file_mkdir, self.configdir
return, 1
end
;+
; Define instance variables.
;
; :Fields:
; configdir
; directory containing preference files
;-
pro mg_prefs__define
compile_opt strictarr
define = { mg_prefs, $
configdir: '' $
}
end