From cf3c631cded5a11718206946e44843bc0fa07951 Mon Sep 17 00:00:00 2001 From: "Jasper St. Pierre" Date: Sun, 13 Feb 2011 11:40:20 -0500 Subject: [PATCH] Add a history manager runDialog and lookingGlass both implement a home-made history manager, each working slightly differently than each other in behavior and implementation. Extract the behavior and implementation from runDialog, which reads and saves to GSettings. https://bugzilla.gnome.org/show_bug.cgi?id=642237 --- js/Makefile.am | 1 + js/misc/history.js | 72 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 js/misc/history.js diff --git a/js/Makefile.am b/js/Makefile.am index 7531c4d59..e4a414525 100644 --- a/js/Makefile.am +++ b/js/Makefile.am @@ -7,6 +7,7 @@ nobase_dist_js_DATA = \ misc/fileUtils.js \ misc/format.js \ misc/gnomeSession.js \ + misc/history.js \ misc/params.js \ misc/util.js \ perf/core.js \ diff --git a/js/misc/history.js b/js/misc/history.js new file mode 100644 index 000000000..69f27f9dd --- /dev/null +++ b/js/misc/history.js @@ -0,0 +1,72 @@ +/* -*- mode: js2; js2-basic-offset: 4; indent-tabs-mode: nil -*- */ + +const Lang = imports.lang; +const Signals = imports.signals; + +const DEFAULT_LIMIT = 512; + +function HistoryManager(settings_key) { + this._init(settings_key); +} + +HistoryManager.prototype = { + _init: function(settings_key, limit) { + this._limit = limit || DEFAULT_LIMIT; + this._key = settings_key; + this._history = global.settings.get_strv(settings_key); + this._historyIndex = -1; + + global.settings.connect('changed::' + settings_key, + Lang.bind(this, this._historyChanged)); + }, + + _historyChanged: function() { + this._history = global.settings.get_strv(this._key); + this._historyIndex = this._history.length; + }, + + prevItem: function(text) { + this._setHistory(this._historyIndex--, text); + return this._indexChanged(); + }, + + nextItem: function(text) { + this._setHistory(this._historyIndex++, text); + return this._indexChanged(); + }, + + lastItem: function() { + this._historyIndex = this._history.length; + return this._indexChanged(); + }, + + addItem: function(input) { + if (this._history.length == 0 || + this._history[this._history.length - 1] != input) { + + this._history.push(input); + this._save(); + } + }, + + _indexChanged: function() { + let current = this._history[this._historyIndex] || ''; + this.emit('changed', current); + return current; + }, + + _setHistory: function(index, text) { + this._historyIndex = Math.max(this._historyIndex, 0); + this._historyIndex = Math.min(this._historyIndex, this._history.length); + + if (text) + this._history[index] = text; + }, + + _save: function() { + if (this._history.length > this._limit) + this._history.splice(0, this._history.length - this._key); + global.settings.set_strv(this._key, this._history); + } +}; +Signals.addSignalMethods(HistoryManager.prototype);