commit-gnuradio
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Commit-gnuradio] [gnuradio] 84/101: grc: refactor: Moved preferences to


From: git
Subject: [Commit-gnuradio] [gnuradio] 84/101: grc: refactor: Moved preferences to Config.py
Date: Thu, 16 Mar 2017 14:58:12 +0000 (UTC)

This is an automated email from the git hooks/post-receive script.

jcorgan pushed a commit to branch python3
in repository gnuradio.

commit 59f88d3cc03ed0f0c01433252f0d607330c23321
Author: Seth Hitefield <address@hidden>
Date:   Thu Sep 22 13:10:57 2016 -0400

    grc: refactor: Moved preferences to Config.py
---
 grc/gui/ActionHandler.py  |  15 ++--
 grc/gui/Actions.py        |   8 +--
 grc/gui/Bars.py           |   4 +-
 grc/gui/Config.py         | 120 +++++++++++++++++++++++++++++++
 grc/gui/Constants.py      |   1 +
 grc/gui/FileDialogs.py    |  14 ++--
 grc/gui/MainWindow.py     |  32 ++++-----
 grc/gui/Preferences.py    | 176 ----------------------------------------------
 grc/gui/VariableEditor.py |   6 +-
 9 files changed, 163 insertions(+), 213 deletions(-)

diff --git a/grc/gui/ActionHandler.py b/grc/gui/ActionHandler.py
index ad4dc35..0d7a900 100644
--- a/grc/gui/ActionHandler.py
+++ b/grc/gui/ActionHandler.py
@@ -25,7 +25,7 @@ import subprocess
 
 from gi.repository import Gtk, GObject
 
-from . import Dialogs, Preferences, Actions, Executor, FileDialogs, Utils
+from . import Dialogs, Actions, Executor, FileDialogs, Utils
 from .MainWindow import MainWindow
 from .ParserErrorsDialog import ParserErrorsDialog
 from .PropsDialog import PropsDialog
@@ -55,6 +55,7 @@ class ActionHandler(Gtk.Application):
         for action in Actions.get_all_actions(): action.connect('activate', 
self._handle_action)
         #setup the main window
         self.platform = platform
+        self.config = platform.config
 
         #initialize
         self.init_file_paths = [os.path.abspath(file_path) for file_path in 
file_paths]
@@ -121,8 +122,8 @@ class ActionHandler(Gtk.Application):
         # Initialize/Quit
         ##################################################
         if action == Actions.APPLICATION_INITIALIZE:
-            file_path_to_show = Preferences.file_open()
-            for file_path in (self.init_file_paths or 
Preferences.get_open_files()):
+            file_path_to_show = self.config.file_open()
+            for file_path in (self.init_file_paths or 
self.config.get_open_files()):
                 if os.path.exists(file_path):
                     main.new_page(file_path, show=file_path_to_show == 
file_path)
             if not main.current_page:
@@ -517,7 +518,7 @@ class ActionHandler(Gtk.Application):
             if file_paths: # Open a new page for each file, show only the first
                 for i,file_path in enumerate(file_paths):
                     main.new_page(file_path, show=(i==0))
-                    Preferences.add_recent_file(file_path)
+                    self.config.add_recent_file(file_path)
                     main.tool_bar.refresh_submenus()
                     main.menu_bar.refresh_submenus()
         elif action == Actions.FLOW_GRAPH_OPEN_QSS_THEME:
@@ -545,7 +546,7 @@ class ActionHandler(Gtk.Application):
             if file_path is not None:
                 page.file_path = os.path.abspath(file_path)
                 Actions.FLOW_GRAPH_SAVE()
-                Preferences.add_recent_file(file_path)
+                self.config.add_recent_file(file_path)
                 main.tool_bar.refresh_submenus()
                 main.menu_bar.refresh_submenus()
         elif action == Actions.FLOW_GRAPH_SCREEN_CAPTURE:
@@ -576,10 +577,10 @@ class ActionHandler(Gtk.Application):
                 Actions.FLOW_GRAPH_GEN()
                 xterm = self.platform.config.xterm_executable
                 Dialogs.show_missing_xterm(main, xterm)
-                if Preferences.xterm_missing() != xterm:
+                if self.config.xterm_missing() != xterm:
                     if not os.path.exists(xterm):
                         Dialogs.show_missing_xterm(main, xterm)
-                    Preferences.xterm_missing(xterm)
+                    self.config.xterm_missing(xterm)
                 if page.saved and page.file_path:
                     Executor.ExecFlowGraphThread(
                         flow_graph_page=page,
diff --git a/grc/gui/Actions.py b/grc/gui/Actions.py
index 601d000..ef04385 100644
--- a/grc/gui/Actions.py
+++ b/grc/gui/Actions.py
@@ -23,8 +23,6 @@ import six
 
 from gi.repository import Gtk, Gdk, GObject
 
-from . import Preferences
-
 NO_MODS_MASK = 0
 
 
@@ -166,12 +164,14 @@ class ToggleAction(Gtk.ToggleAction, _ActionBase):
 
     def load_from_preferences(self):
         if self.preference_name is not None:
-            self.set_active(Preferences.entry(
+            config = Gtk.Application.get_default().config
+            self.set_active(config.entry(
                 self.preference_name, default=bool(self.default)))
 
     def save_to_preferences(self):
         if self.preference_name is not None:
-            Preferences.entry(self.preference_name, value=self.get_active())
+            config = Gtk.Application.get_default().config
+            config.entry(self.preference_name, value=self.get_active())
 
 ########################################################################
 # Actions
diff --git a/grc/gui/Bars.py b/grc/gui/Bars.py
index 1c63f01..26fea20 100644
--- a/grc/gui/Bars.py
+++ b/grc/gui/Bars.py
@@ -205,9 +205,9 @@ class SubMenuCreator(object):
 
     def _fill_flow_graph_recent_submenu(self, action):
         """menu showing recent flow-graphs"""
-        from . import Preferences
         menu = Gtk.Menu()
-        recent_files = Preferences.get_recent_files()
+        config = Gtk.Application.get_default().config
+        recent_files = config.get_recent_files()
         if len(recent_files) > 0:
             for i, file_name in enumerate(recent_files):
                 item = Gtk.MenuItem(name="%d. %s" % (i+1, file_name), 
use_underline=False)
diff --git a/grc/gui/Config.py b/grc/gui/Config.py
index 0558892..c4d395c 100644
--- a/grc/gui/Config.py
+++ b/grc/gui/Config.py
@@ -25,6 +25,16 @@ import os
 from ..core.Config import Config as CoreConfig
 from . import Constants
 
+from six.moves import configparser
+
+HEADER = """\
+# This contains only GUI settings for GRC and is not meant for users to edit.
+#
+# GRC settings not accessible through the GUI are in gnuradio.conf under
+# section [grc].
+
+"""
+
 
 class Config(CoreConfig):
 
@@ -38,6 +48,41 @@ class Config(CoreConfig):
         self.install_prefix = install_prefix
         Constants.update_font_size(self.font_size)
 
+        self.parser = configparser.SafeConfigParser()
+        for section in ['main', 'files_open', 'files_recent']:
+            try:
+                self.parser.add_section(section)
+            except Exception as e:
+                print(e)
+        try:
+            self.parser.read(self.gui_prefs_file)
+        except Exception as err:
+            print(err, file=sys.stderr)
+
+    def save(self):
+        try:
+            with open(self.gui_prefs_file, 'w') as fp:
+                fp.write(HEADER)
+                self.parser.write(fp)
+        except Exception as err:
+            print(err, file=sys.stderr)
+
+    def entry(self, key, value=None, default=None):
+        if value is not None:
+            self.parser.set('main', key, str(value))
+            result = value
+        else:
+            _type = type(default) if default is not None else str
+            getter = {
+                bool: self.parser.getboolean,
+                int: self.parser.getint,
+            }.get(_type, self.parser.get)
+            try:
+                result = getter('main', key)
+            except (AttributeError, configparser.Error):
+                result = _type() if default is None else default
+        return result
+
     @property
     def editor(self):
         return self._gr_prefs.get_string('grc', 'editor', '')
@@ -84,3 +129,78 @@ class Config(CoreConfig):
     def default_qss_theme(self, value):
         self._gr_prefs.set_string("qtgui", "qss", value)
         self._gr_prefs.save()
+
+    ##### Originally from Preferences.py #####
+    def main_window_size(self, size=None):
+        if size is None:
+            size = [None, None]
+        w = self.entry('main_window_width', size[0], default=1)
+        h = self.entry('main_window_height', size[1], default=1)
+        return w, h
+
+    def file_open(self, filename=None):
+        return self.entry('file_open', filename, default='')
+
+    def set_file_list(self, key, files):
+        self.parser.remove_section(key)  # clear section
+        self.parser.add_section(key)
+        for i, filename in enumerate(files):
+            self.parser.set(key, '%s_%d' % (key, i), filename)
+
+    def get_file_list(self, key):
+        try:
+            files = [value for name, value in self.parser.items(key)
+                     if name.startswith('%s_' % key)]
+        except (AttributeError, configparser.Error):
+            files = []
+        return files
+
+    def get_open_files(self):
+        return self.get_file_list('files_open')
+
+    def set_open_files(self, files):
+        return self.set_file_list('files_open', files)
+
+    def get_recent_files(self):
+        """ Gets recent files, removes any that do not exist and re-saves it 
"""
+        files = list(filter(os.path.exists, 
self.get_file_list('files_recent')))
+        self.set_recent_files(files)
+        return files
+
+    def set_recent_files(self, files):
+        return self.set_file_list('files_recent', files)
+
+    def add_recent_file(self, file_name):
+        # double check file_name
+        if os.path.exists(file_name):
+            recent_files = self.get_recent_files()
+            if file_name in recent_files:
+                recent_files.remove(file_name)  # Attempt removal
+            recent_files.insert(0, file_name)  # Insert at start
+            self.set_recent_files(recent_files[:10])  # Keep up to 10 files
+
+    def console_window_position(self, pos=None):
+        return self.entry('console_window_position', pos, default=-1) or 1
+
+    def blocks_window_position(self, pos=None):
+        return self.entry('blocks_window_position', pos, default=-1) or 1
+
+    def variable_editor_position(self, pos=None, sidebar=False):
+        # Figure out default
+        if sidebar:
+            w, h = self.main_window_size()
+            return self.entry('variable_editor_sidebar_position', pos, 
default=int(h*0.7))
+        else:
+            return self.entry('variable_editor_position', pos, 
default=int(self.blocks_window_position()*0.5))
+
+    def variable_editor_sidebar(self, pos=None):
+        return self.entry('variable_editor_sidebar', pos, default=False)
+
+    def variable_editor_confirm_delete(self, pos=None):
+        return self.entry('variable_editor_confirm_delete', pos, default=True)
+
+    def xterm_missing(self, cmd=None):
+        return self.entry('xterm_missing', cmd, 
default='INVALID_XTERM_SETTING')
+
+    def screen_shot_background_transparent(self, transparent=None):
+        return self.entry('screen_shot_background_transparent', transparent, 
default=False)
diff --git a/grc/gui/Constants.py b/grc/gui/Constants.py
index 2f0f779..0a555b3 100644
--- a/grc/gui/Constants.py
+++ b/grc/gui/Constants.py
@@ -26,6 +26,7 @@ from ..core.Constants import *
 
 # default path for the open/save dialogs
 DEFAULT_FILE_PATH = os.getcwd()
+FILE_EXTENSION = '.grc'
 
 # name for new/unsaved flow graphs
 NEW_FLOGRAPH_TITLE = 'untitled'
diff --git a/grc/gui/FileDialogs.py b/grc/gui/FileDialogs.py
index cbb7bca..dbcecf9 100644
--- a/grc/gui/FileDialogs.py
+++ b/grc/gui/FileDialogs.py
@@ -23,7 +23,7 @@ from os import path
 
 from gi.repository import Gtk
 
-from . import Constants, Preferences, Utils, Dialogs
+from . import Constants, Utils, Dialogs
 
 
 class FileDialogHelper(Gtk.FileChooserDialog, object):
@@ -59,7 +59,7 @@ class FileDialogHelper(Gtk.FileChooserDialog, object):
 
         self.parent = parent
         self.current_file_path = current_file_path or path.join(
-            Constants.DEFAULT_FILE_PATH, Constants.NEW_FLOGRAPH_TITLE + 
Preferences.file_extension())
+            Constants.DEFAULT_FILE_PATH, Constants.NEW_FLOGRAPH_TITLE + 
Constants.FILE_EXTENSION)
 
         self.set_current_folder(path.dirname(current_file_path))  # current 
directory
         self.setup_filters()
@@ -130,7 +130,7 @@ class OpenFileDialog(FileDialogHelper):
 class OpenFlowGraph(OpenFileDialog):
     title = 'Open a Flow Graph from a File...'
     filter_label = 'Flow Graph Files'
-    filter_ext = Preferences.file_extension()
+    filter_ext = Constants.FILE_EXTENSION
 
     def __init__(self, parent, current_file_path=''):
         super(OpenFlowGraph, self).__init__(parent, current_file_path)
@@ -146,7 +146,7 @@ class OpenQSS(OpenFileDialog):
 class SaveFlowGraph(SaveFileDialog):
     title = 'Save a Flow Graph to a File...'
     filter_label = 'Flow Graph Files'
-    filter_ext = Preferences.file_extension()
+    filter_ext = Constants.FILE_EXTENSION
 
 
 class SaveConsole(SaveFileDialog):
@@ -163,8 +163,10 @@ class SaveScreenShot(SaveFileDialog):
     def __init__(self, parent, current_file_path=''):
         super(SaveScreenShot, self).__init__(parent, current_file_path)
 
+        self.config = Gtk.Application.get_default().config
+
         self._button = button = Gtk.CheckButton(label='Background transparent')
-        
self._button.set_active(Preferences.screen_shot_background_transparent())
+        
self._button.set_active(self.config.screen_shot_background_transparent())
         self.set_extra_widget(button)
 
     def setup_filters(self, filters=None):
@@ -193,6 +195,6 @@ class SaveScreenShot(SaveFileDialog):
             self.show_missing_message(filename)
 
         bg_transparent = self._button.get_active()
-        Preferences.screen_shot_background_transparent(bg_transparent)
+        self.config.screen_shot_background_transparent(bg_transparent)
         self.destroy()
         return filename, bg_transparent
diff --git a/grc/gui/MainWindow.py b/grc/gui/MainWindow.py
index 5eabf33..1caec28 100644
--- a/grc/gui/MainWindow.py
+++ b/grc/gui/MainWindow.py
@@ -23,7 +23,7 @@ import os
 
 from gi.repository import Gtk, Gdk, GObject
 
-from . import Bars, Actions, Preferences, Utils
+from . import Bars, Actions, Utils
 from .BlockTreeWindow import BlockTreeWindow
 from .VariableEditor import VariableEditor
 from .Constants import \
@@ -52,7 +52,7 @@ class MainWindow(Gtk.ApplicationWindow):
         Gtk.ApplicationWindow.__init__(self, title="GNU Radio Companion", 
application=app)
 
         self._platform = platform
-        Preferences.load(platform)
+        self.config = platform.config
 
         # Setup window
         vbox = Gtk.VBox()
@@ -97,7 +97,7 @@ class MainWindow(Gtk.ApplicationWindow):
         self.right = Gtk.VPaned() #orientation=Gtk.Orientation.VERTICAL)
         self.left_subpanel = Gtk.HPaned() 
#orientation=Gtk.Orientation.HORIZONTAL)
 
-        self.variable_panel_sidebar = Preferences.variable_editor_sidebar()
+        self.variable_panel_sidebar = self.config.variable_editor_sidebar()
         if self.variable_panel_sidebar:
             self.left.pack1(self.notebook)
             self.left.pack2(self.console_window, False)
@@ -117,13 +117,13 @@ class MainWindow(Gtk.ApplicationWindow):
         self.main.pack2(self.right, False)
 
         # Load preferences and show the main window
-        self.resize(*Preferences.main_window_size())
-        self.main.set_position(Preferences.blocks_window_position())
-        self.left.set_position(Preferences.console_window_position())
+        self.resize(*self.config.main_window_size())
+        self.main.set_position(self.config.blocks_window_position())
+        self.left.set_position(self.config.console_window_position())
         if self.variable_panel_sidebar:
-            
self.right.set_position(Preferences.variable_editor_position(sidebar=True))
+            
self.right.set_position(self.config.variable_editor_position(sidebar=True))
         else:
-            
self.left_subpanel.set_position(Preferences.variable_editor_position())
+            
self.left_subpanel.set_position(self.config.variable_editor_position())
 
         self.show_all()
         self.console_window.hide()
@@ -279,16 +279,16 @@ class MainWindow(Gtk.ApplicationWindow):
                 break
         if self.notebook.get_n_pages(): return False
         #save state before closing
-        Preferences.set_open_files(open_files)
-        Preferences.file_open(open_file)
-        Preferences.main_window_size(self.get_size())
-        Preferences.console_window_position(self.left.get_position())
-        Preferences.blocks_window_position(self.main.get_position())
+        self.config.set_open_files(open_files)
+        self.config.file_open(open_file)
+        self.config.main_window_size(self.get_size())
+        self.config.console_window_position(self.left.get_position())
+        self.config.blocks_window_position(self.main.get_position())
         if self.variable_panel_sidebar:
-            Preferences.variable_editor_position(self.right.get_position(), 
sidebar=True)
+            self.config.variable_editor_position(self.right.get_position(), 
sidebar=True)
         else:
-            
Preferences.variable_editor_position(self.left_subpanel.get_position())
-        Preferences.save()
+            
self.config.variable_editor_position(self.left_subpanel.get_position())
+        self.config.save()
         return True
 
     def close_page(self, ensure=True):
diff --git a/grc/gui/Preferences.py b/grc/gui/Preferences.py
deleted file mode 100644
index d917537..0000000
--- a/grc/gui/Preferences.py
+++ /dev/null
@@ -1,176 +0,0 @@
-"""
-Copyright 2008 Free Software Foundation, Inc.
-This file is part of GNU Radio
-
-GNU Radio Companion 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.
-
-GNU Radio Companion 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
-"""
-
-from __future__ import absolute_import, print_function
-
-import os
-import sys
-
-from six.moves import configparser
-
-
-HEADER = """\
-# This contains only GUI settings for GRC and is not meant for users to edit.
-#
-# GRC settings not accessible through the GUI are in gnuradio.conf under
-# section [grc].
-
-"""
-
-_platform = None
-_config_parser = configparser.SafeConfigParser()
-
-
-def file_extension():
-    return '.grc'
-
-
-def load(platform):
-    global _platform
-    _platform = platform
-    # create sections
-    for section in ['main', 'files_open', 'files_recent']:
-        try:
-            _config_parser.add_section(section)
-        except Exception as e:
-            print(e)
-    try:
-        _config_parser.read(_platform.get_prefs_file())
-    except Exception as err:
-        print(err, file=sys.stderr)
-
-
-def save():
-    try:
-        with open(_platform.get_prefs_file(), 'w') as fp:
-            fp.write(HEADER)
-            _config_parser.write(fp)
-    except Exception as err:
-        print(err, file=sys.stderr)
-
-
-def entry(key, value=None, default=None):
-    if value is not None:
-        _config_parser.set('main', key, str(value))
-        result = value
-    else:
-        _type = type(default) if default is not None else str
-        getter = {
-            bool: _config_parser.getboolean,
-            int: _config_parser.getint,
-        }.get(_type, _config_parser.get)
-        try:
-            result = getter('main', key)
-        except (AttributeError, configparser.Error):
-            result = _type() if default is None else default
-    return result
-
-
-###########################################################################
-# Special methods for specific program functionalities
-###########################################################################
-
-def main_window_size(size=None):
-    if size is None:
-        size = [None, None]
-    w = entry('main_window_width', size[0], default=1)
-    h = entry('main_window_height', size[1], default=1)
-    return w, h
-
-
-def file_open(filename=None):
-    return entry('file_open', filename, default='')
-
-
-def set_file_list(key, files):
-    _config_parser.remove_section(key)  # clear section
-    _config_parser.add_section(key)
-    for i, filename in enumerate(files):
-        _config_parser.set(key, '%s_%d' % (key, i), filename)
-
-
-def get_file_list(key):
-    try:
-        files = [value for name, value in _config_parser.items(key)
-                 if name.startswith('%s_' % key)]
-    except (AttributeError, configparser.Error):
-        files = []
-    return files
-
-
-def get_open_files():
-    return get_file_list('files_open')
-
-
-def set_open_files(files):
-    return set_file_list('files_open', files)
-
-
-def get_recent_files():
-    """ Gets recent files, removes any that do not exist and re-saves it """
-    files = list(filter(os.path.exists, get_file_list('files_recent')))
-    set_recent_files(files)
-    return files
-
-
-def set_recent_files(files):
-    return set_file_list('files_recent', files)
-
-
-def add_recent_file(file_name):
-    # double check file_name
-    if os.path.exists(file_name):
-        recent_files = get_recent_files()
-        if file_name in recent_files:
-            recent_files.remove(file_name)  # Attempt removal
-        recent_files.insert(0, file_name)  # Insert at start
-        set_recent_files(recent_files[:10])  # Keep up to 10 files
-
-
-def console_window_position(pos=None):
-    return entry('console_window_position', pos, default=-1) or 1
-
-
-def blocks_window_position(pos=None):
-    return entry('blocks_window_position', pos, default=-1) or 1
-
-
-def variable_editor_position(pos=None, sidebar=False):
-    # Figure out default
-    if sidebar:
-        w, h = main_window_size()
-        return entry('variable_editor_sidebar_position', pos, 
default=int(h*0.7))
-    else:
-        return entry('variable_editor_position', pos, 
default=int(blocks_window_position()*0.5))
-
-
-def variable_editor_sidebar(pos=None):
-    return entry('variable_editor_sidebar', pos, default=False)
-
-
-def variable_editor_confirm_delete(pos=None):
-    return entry('variable_editor_confirm_delete', pos, default=True)
-
-
-def xterm_missing(cmd=None):
-    return entry('xterm_missing', cmd, default='INVALID_XTERM_SETTING')
-
-
-def screen_shot_background_transparent(transparent=None):
-    return entry('screen_shot_background_transparent', transparent, 
default=False)
diff --git a/grc/gui/VariableEditor.py b/grc/gui/VariableEditor.py
index d97b9e9..44dd292 100644
--- a/grc/gui/VariableEditor.py
+++ b/grc/gui/VariableEditor.py
@@ -21,7 +21,7 @@ from __future__ import absolute_import
 
 from gi.repository import Gtk, Gdk, GObject
 
-from . import Actions, Preferences, Constants
+from . import Actions, Constants
 
 BLOCK_INDEX = 0
 ID_INDEX = 1
@@ -85,6 +85,8 @@ class VariableEditor(Gtk.VBox):
 
     def __init__(self):
         Gtk.VBox.__init__(self)
+        config = Gtk.Application.get_default().config
+
         self._block = None
         self._mouse_button_pressed = False
         self._imports = []
@@ -150,7 +152,7 @@ class VariableEditor(Gtk.VBox):
 
         # Context menus
         self._context_menu = VariableEditorContextMenu(self)
-        self._confirm_delete = Preferences.variable_editor_confirm_delete()
+        self._confirm_delete = config.variable_editor_confirm_delete()
 
     # Sets cell contents
     def set_icon(self, col, cell, model, iter, data):



reply via email to

[Prev in Thread] Current Thread [Next in Thread]