Robot Framework Integrated Development Environment (RIDE)
general.py
Go to the documentation of this file.
1 # Copyright 2020- Robot Framework Foundation
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 
15 from functools import lru_cache
16 from os.path import abspath, dirname, join
17 
18 import wx
19 
20 from ..ui.preferences_dialogs import (boolean_editor, PreferencesPanel, IntegerChoiceEditor, SpinChoiceEditor,
21  StringChoiceEditor, PreferencesColorPicker)
22 from .managesettingsdialog import SaveLoadSettings
23 from wx import Colour
24 from ..context import IS_WINDOWS
25 
26 ID_APPLY_TO_PANEL = wx.NewId()
27 ID_RESET = wx.NewId()
28 ID_SAVELOADSETTINGS = wx.NewId()
29 ID_LOAD = 5551
30 ID_SAVE = 5552
31 ID_CANCEL = -1
32 
33 
34 @lru_cache(maxsize=2)
35 
36 def read_fonts(fixed=False):
37  f = wx.FontEnumerator()
38  f.EnumerateFacenames()
39  names = f.GetFacenames(fixedWidthOnly=fixed)
40  names = [n for n in names if not n.startswith('@')]
41  names.sort()
42  return names
43 
44 
46 
47  def __init__(self, settings, *args, **kwargs):
48  super(GeneralPreferences, self).__init__(*args, **kwargs)
49  self._settings_settings = settings
50  self._color_pickers_color_pickers = []
51  self._apply_to_panels_apply_to_panels = self._settings_settings.get('apply to panels', False)
52 
53  # what would make this UI much more usable is if there were a
54  # preview window in the dialog that showed all the colors. I
55  # don't have the time to do that right now, so this will have
56  # to suffice.
57 
58  font_editor = self._create_font_editor_create_font_editor()
59  colors_sizer = self.create_colors_sizercreate_colors_sizer()
60  main_sizer = wx.FlexGridSizer(rows=6, cols=1, vgap=10, hgap=10)
61  buttons_sizer = wx.BoxSizer(orient=wx.HORIZONTAL)
62  reset = wx.Button(self, ID_RESET, 'Reset colors to default')
63  saveloadsettings = wx.Button(self, ID_SAVELOADSETTINGS, 'Save or Load settings')
64  self.cb_apply_to_panelscb_apply_to_panels = wx.CheckBox(self, ID_APPLY_TO_PANEL, label="Apply to Project and File Explorer panels")
65  self.cb_apply_to_panelscb_apply_to_panels.Enable()
66  self.cb_apply_to_panelscb_apply_to_panels.SetValue(self._apply_to_panels_apply_to_panels)
67  if IS_WINDOWS:
68  background_color = Colour("light gray")
69  foreground_color = Colour("black")
70  self.cb_apply_to_panelscb_apply_to_panels.SetForegroundColour(foreground_color)
71  self.cb_apply_to_panelscb_apply_to_panels.SetBackgroundColour(background_color)
72  self.cb_apply_to_panelscb_apply_to_panels.SetOwnBackgroundColour(background_color)
73  self.cb_apply_to_panelscb_apply_to_panels.SetOwnForegroundColour(foreground_color)
74  main_sizer.Add(font_editor)
75  main_sizer.Add(colors_sizer)
76  main_sizer.Add(self.cb_apply_to_panelscb_apply_to_panels)
77  buttons_sizer.Add(reset)
78  buttons_sizer.AddSpacer(10)
79  buttons_sizer.Add(saveloadsettings)
80  main_sizer.Add(buttons_sizer)
81  self.SetSizerAndFit(main_sizer)
82  self.Bind(wx.EVT_BUTTON, self.OnResetOnReset)
83  self.Bind(wx.EVT_BUTTON, self.OnSaveLoadSettingsOnSaveLoadSettings)
84  self.Bind(wx.EVT_CHECKBOX, self.OnCheckBoxOnCheckBox, self.cb_apply_to_panelscb_apply_to_panels)
85 
86  def OnCheckBox(self, event):
87  self._apply_to_panels_apply_to_panels = event.IsChecked()
88  self._settings_settings.set('apply to panels', self._apply_to_panels_apply_to_panels)
89  # print(f"DEBUG: Preferences Checkbox set {str(self._apply_to_panels)}")
90 
91  def OnReset(self, event):
92  if event.GetId() != ID_RESET:
93  event.Skip()
94  return
95  defaults = self._read_defaults_read_defaults()
96  for picker in self._color_pickers_color_pickers:
97  picker.SetColour(defaults[picker.key])
98  # self.Refresh()
99 
100  def OnSaveLoadSettings(self, event):
101  if event.GetId() != ID_SAVELOADSETTINGS:
102  event.Skip()
103  return
104  save_settings_dialog = SaveLoadSettings(self, self._settings_settings) # DEBUG self.__class__.__name__
105  save_settings_dialog.CenterOnParent()
106  value = save_settings_dialog.ShowModal()
107  # print(f"DEBUG: Value returned by SaveLoadSettings: {value}")
108  # print(f"DEBUG: OnSaveLoadSettings: Trying to close parent ")
109  # Does not look nice but closes Preferences window, so it comes recolored on next call
110  # Only working on first use :(
111  # TODO: Only close window when Loading, not when Saving (but return is always 5101)
112  wx.FindWindowByName("RIDE - Preferences").Close(force=True)
113 
114  def _reload_settings(self):
115  import os
116  from ..context import SETTINGS_DIRECTORY
117  self._default_path_default_path = os.path.join(SETTINGS_DIRECTORY, 'settings.cfg')
118  settings = [s.strip() for s in open(self._default_path_default_path, 'r').readlines()]
119  name = '[General]'
120  start_index = settings.index(name) + 1
121  defaults = {}
122  for line in settings[start_index:]:
123  if line.startswith('['):
124  break
125  if not line:
126  continue
127  key, value = [s.strip().strip('\'') for s in line.split("=")]
128  # print(f"DEBUG: Preferences General default value type {type(value)} {value}")
129  if len(value) > 0 and value[0] == '(' and value[-1] == ')':
130  from ast import literal_eval as make_tuple
131  value = make_tuple(value)
132  defaults[key] = value
133  self._settings_settings = defaults
134 
135  for picker in self._color_pickers_color_pickers:
136  picker.SetColour(defaults[picker.key])
137  self.Refresh(True)
138 
139  def _read_defaults(self, plugin=False):
140  settings = [s.strip() for s in open(self._get_path_get_path(), 'r').readlines()]
141  name = ('[[%s]]' if plugin else '[%s]') % self.name
142  start_index = settings.index(name) + 1
143  defaults = {}
144  for line in settings[start_index:]:
145  if line.startswith('['):
146  break
147  if not line:
148  continue
149  key, value = [s.strip().strip('\'') for s in line.split("=")]
150  # print(f"DEBUG: Preferences General default value type {type(value)} {value}")
151  if len(value) > 0 and value[0] == '(' and value[-1] == ')':
152  from ast import literal_eval as make_tuple
153  value = make_tuple(value)
154  defaults[key] = value
155  return defaults
156 
157  def _get_path(self):
158  return join(dirname(abspath(__file__)), 'settings.cfg')
159 
162  self._settings_settings, 'font size', 'Font Size',
163  [str(i) for i in range(8, 16)])
164  sizer = wx.FlexGridSizer(rows=3, cols=2, vgap=10, hgap=30)
165  l_size = f.label(self)
166  if IS_WINDOWS:
167  background_color = Colour("light gray")
168  foreground_color = Colour("black")
169  l_size.SetBackgroundColour(background_color)
170  l_size.SetOwnBackgroundColour(background_color)
171  l_size.SetForegroundColour(foreground_color)
172  l_size.SetOwnForegroundColour(foreground_color)
173  sizer.AddMany([l_size, f.chooser(self)])
174  fixed_font = False
175  if 'zoom factor' in self._settings_settings:
176  z = SpinChoiceEditor(
177  self._settings_settings, 'zoom factor', 'Zoom Factor', (-10, 20))
178  l_zoom = z.label(self)
179  if IS_WINDOWS:
180  l_zoom.SetForegroundColour(foreground_color)
181  l_zoom.SetBackgroundColour(background_color)
182  l_zoom.SetOwnBackgroundColour(background_color)
183  l_zoom.SetOwnForegroundColour(foreground_color)
184  sizer.AddMany([l_zoom, z.chooser(self)])
185  if 'fixed font' in self._settings_settings:
186  l_ff, editor = boolean_editor(self, self._settings_settings, 'fixed font', 'Use fixed width font')
187  if IS_WINDOWS:
188  l_ff.SetForegroundColour(foreground_color)
189  l_ff.SetBackgroundColour(background_color)
190  l_ff.SetOwnBackgroundColour(background_color)
191  l_ff.SetOwnForegroundColour(foreground_color)
192  sizer.AddMany([l_ff, editor])
193  fixed_font = self._settings_settings['fixed font']
194  if 'font face' in self._settings_settings:
195  s = StringChoiceEditor(self._settings_settings, 'font face', 'Font Face', read_fonts(fixed_font))
196  l_font = s.label(self)
197  if IS_WINDOWS:
198  l_font.SetForegroundColour(foreground_color)
199  l_font.SetBackgroundColour(background_color)
200  l_font.SetOwnBackgroundColour(background_color)
201  l_font.SetOwnForegroundColour(foreground_color)
202  sizer.AddMany([l_font, s.chooser(self)])
203  sizer.Layout()
204  return sizer
205 
207  raise NotImplementedError('Implement me')
208 
209 
211  location = ("General",)
212  title = "General Settings"
213  name = "General"
214 
215  def __init__(self, settings, *args, **kwargs):
216  super(DefaultPreferences, self).__init__(settings[self.namename], *args, **kwargs)
217  #PUBLISHER.subscribe(self.OnSettingsChanged, RideSettingsChanged)
218  # print(f"DEBUG: settings_path {settings.get_path()}")
219 
221  container = wx.GridBagSizer()
222  column = 0
223  row = 0
224  settings = (
225  ('foreground', 'Foreground'),
226  ('background', 'Background'),
227  ('secondary foreground', 'Secondary Foreground'),
228  ('secondary background', 'Secondary Background'),
229  ('foreground text', 'Text Foreground'),
230  ('background help', 'Help Background')
231  )
232  if IS_WINDOWS:
233  background_color = Colour("light gray")
234  foreground_color = Colour("black")
235  for settings_key, label_text in settings:
236  if column == 4:
237  column = 0
238  row += 1
239  label = wx.StaticText(self, wx.ID_ANY, label_text)
240  if IS_WINDOWS:
241  label.SetForegroundColour(foreground_color)
242  label.SetBackgroundColour(background_color)
243  label.SetOwnBackgroundColour(background_color)
244  label.SetOwnForegroundColour(foreground_color)
245  button = PreferencesColorPicker(
246  self, wx.ID_ANY, self._settings_settings, settings_key)
247  container.Add(button, (row, column),
248  flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL, border=4)
249  self._color_pickers_color_pickers.append(button)
250  column += 1
251  container.Add(label, (row, column),
252  flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT, border=8)
253  column += 1
254  return container
255 
256  def OnReset(self, event):
257  defaults = self._read_defaults_read_defaults()
258  for picker in self._color_pickers_color_pickers:
259  picker.SetColour(defaults[picker.key])
260  # self.Refresh()
261  wx.FindWindowByName("RIDE - Preferences").Close(force=True)
def __init__(self, settings, *args, **kwargs)
Definition: general.py:215
def __init__(self, settings, *args, **kwargs)
Definition: general.py:47
A colored button that opens a color picker dialog.
Base class for all preference panels used by PreferencesDialog.
def abspath(path, case_normalize=False)
Replacement for os.path.abspath with some enhancements and bug fixes.
Definition: robotpath.py:87
def read_fonts(fixed=False)
Returns list with fixed width fonts.
Definition: general.py:36
def boolean_editor(parent, settings, name, label, help='')