diff --git a/docs/releases/upcoming/1760.feature.rst b/docs/releases/upcoming/1760.feature.rst new file mode 100644 index 000000000..25a2132a4 --- /dev/null +++ b/docs/releases/upcoming/1760.feature.rst @@ -0,0 +1 @@ +Used Black to ensure a uniform codestyle for TraitsUI. (#1760) \ No newline at end of file diff --git a/docs/source/conf.py b/docs/source/conf.py index c6bb58641..db9bba836 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -19,7 +19,7 @@ # If your extensions are in another directory, add it here. If the directory # is relative to the documentation root, use os.path.abspath to make it # absolute, like shown here. -#sys.path.append(os.path.abspath('some/directory')) +# sys.path.append(os.path.abspath('some/directory')) # General configuration # --------------------- @@ -51,30 +51,30 @@ # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: -#today = '' +# today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. -#unused_docs = [] +# unused_docs = [] # List of directories, relative to source directories, that shouldn't be searched # for source files. -#exclude_dirs = [] +# exclude_dirs = [] # The reST default role (used for this markup: `text`) to use for all documents. -#default_role = None +# default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True +# add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). -#add_module_names = True +# add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. -#show_authors = False +# show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' @@ -86,29 +86,28 @@ # The style sheet to use for HTML and HTML Help pages. A file of that name # must exist either in Sphinx' static/ path, or in one of the custom paths # given in html_static_path. -#html_style = 'default.css' +# html_style = 'default.css' # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". html_title = "TraitsUI {} Documentation".format(version.split('.')[0]) # A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None +# html_short_title = None # The name of an image file (within the static path) to place at the top of # the sidebar. -#html_logo = "e-logo-rev.png" +# html_logo = "e-logo-rev.png" # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. -#html_favicon = "favicon.ico" +# html_favicon = "favicon.ico" # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static', - os.path.join('tutorials', 'code_snippets')] +html_static_path = ['_static', os.path.join('tutorials', 'code_snippets')] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. @@ -119,31 +118,31 @@ html_use_smartypants = True # Custom sidebar templates, maps document names to template names. -#html_sidebars = {} +# html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. -#html_additional_pages = {} +# html_additional_pages = {} # If false, no module index is generated. html_use_modindex = False # If false, no index is generated. -#html_use_index = False +# html_use_index = False # If true, the index is split into individual pages for each letter. -#html_split_index = False +# html_split_index = False # If true, the reST sources are included in the HTML build as _sources/. -#html_copy_source = True +# html_copy_source = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. -#html_use_opensearch = '' +# html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = '' +# html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'Traitsuidoc' @@ -156,6 +155,7 @@ html_theme = 'enthought' except ImportError as exc: import warnings + msg = '''Can't find Enthought Sphinx Theme, using default. Exception was: {} Enthought Sphinx Theme can be downloaded from @@ -174,24 +174,32 @@ # #html_theme = 'classic' # Useful aliases to avoid repeating long URLs. -extlinks = {'github-demo': ( - f'https://github.com/enthought/traitsui/tree/{version}/traitsui/examples/demo/%s', - 'github-demo') +extlinks = { + 'github-demo': ( + f'https://github.com/enthought/traitsui/tree/{version}/traitsui/examples/demo/%s', + 'github-demo', + ) } # Options for LaTeX output # ------------------------ # The paper size ('letter' or 'a4'). -#latex_paper_size = 'letter' +# latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). -#latex_font_size = '10pt' +# latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). latex_documents = [ - ('index', 'TraitsUI.tex', 'TraitsUI 4 User Manual', 'Enthought, Inc.', 'manual'), + ( + 'index', + 'TraitsUI.tex', + 'TraitsUI 4 User Manual', + 'Enthought, Inc.', + 'manual', + ), ] # The name of an image file (relative to this directory) to place at the top of @@ -201,21 +209,19 @@ # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. -#latex_use_parts = False +# latex_use_parts = False # Additional stuff for the LaTeX preamble. -#latex_preamble = '' +# latex_preamble = '' # Documents to append as an appendix to all manuals. -#latex_appendices = [] +# latex_appendices = [] # If false, no module index is generated. -#latex_use_modindex = True +# latex_use_modindex = True # Autodoc options -autodo_mock_imports = [ - "wx", "PySide", "PyQt", "PyQt5" -] +autodo_mock_imports = ["wx", "PySide", "PyQt", "PyQt5"] # Intersphinx configuration intersphinx_mapping = { diff --git a/docs/source/traitsui_user_manual/examples/handler_override.py b/docs/source/traitsui_user_manual/examples/handler_override.py index 000782d0c..47eabeaa3 100644 --- a/docs/source/traitsui_user_manual/examples/handler_override.py +++ b/docs/source/traitsui_user_manual/examples/handler_override.py @@ -16,7 +16,6 @@ class TC_Handler(Handler): - def setattr(self, info, object, name, value): Handler.setattr(self, info, object, name, value) info.object._updated = True diff --git a/docs/source/traitsui_user_manual/examples/key_bindings.py b/docs/source/traitsui_user_manual/examples/key_bindings.py index 6b393e217..84885008d 100644 --- a/docs/source/traitsui_user_manual/examples/key_bindings.py +++ b/docs/source/traitsui_user_manual/examples/key_bindings.py @@ -34,7 +34,7 @@ class CodeHandler(Handler): - """ Handler class for bound methods. """ + """Handler class for bound methods.""" def save_file(self, info): info.object.status = "save file" diff --git a/docs/source/traitsui_user_manual/examples/mixed_styles.py b/docs/source/traitsui_user_manual/examples/mixed_styles.py index 08a5a0e95..8ef7cc813 100644 --- a/docs/source/traitsui_user_manual/examples/mixed_styles.py +++ b/docs/source/traitsui_user_manual/examples/mixed_styles.py @@ -22,17 +22,17 @@ class MixedStyles(HasTraits): position_type = Enum("Full-Time", "Part-Time", "Contract") traits_view = View( - Group( - Item(name='first_name'), - Item(name='last_name'), - Group( - Item(name='department'), - Item(name='position_type', style='custom'), - style='simple', - ), - ), - title='Mixed Styles', - style='readonly', + Group( + Item(name='first_name'), + Item(name='last_name'), + Group( + Item(name='department'), + Item(name='position_type', style='custom'), + style='simple', + ), + ), + title='Mixed Styles', + style='readonly', ) diff --git a/docs/source/traitsui_user_manual/examples/tree_editor.py b/docs/source/traitsui_user_manual/examples/tree_editor.py index 603591a55..b7d08142e 100644 --- a/docs/source/traitsui_user_manual/examples/tree_editor.py +++ b/docs/source/traitsui_user_manual/examples/tree_editor.py @@ -12,11 +12,25 @@ from traits.api import HasTraits, Instance, List, Str, Regex from traitsui.api import ( - Action, Group, Handler, HGroup, Item, Menu, Separator, TreeEditor, - TreeNode, View, VSplit, + Action, + Group, + Handler, + HGroup, + Item, + Menu, + Separator, + TreeEditor, + TreeNode, + View, + VSplit, ) from traitsui.editors.tree_editor import ( - NewAction, CopyAction, CutAction, PasteAction, DeleteAction, RenameAction, + NewAction, + CopyAction, + CutAction, + PasteAction, + DeleteAction, + RenameAction, ) @@ -88,7 +102,6 @@ class Owner(HasTraits): class TreeHandler(Handler): - def employee_department(self, editor, object): dept = editor.get_parent(object) print(f'{object.name} works in the {dept.name} department.') @@ -176,8 +189,8 @@ def employee_department(self, editor, object): handler=TreeHandler(), buttons=['Undo', 'OK', 'Cancel'], resizable=True, - width=.3, - height=.3, + width=0.3, + height=0.3, ) if __name__ == '__main__': diff --git a/docs/source/traitsui_user_manual/scripts/regenerate_example_screenshots.py b/docs/source/traitsui_user_manual/scripts/regenerate_example_screenshots.py index cfdd9b522..28e463de4 100644 --- a/docs/source/traitsui_user_manual/scripts/regenerate_example_screenshots.py +++ b/docs/source/traitsui_user_manual/scripts/regenerate_example_screenshots.py @@ -31,7 +31,7 @@ def _is_python_file(path): - """ Return true if the given path is (public) non-test Python file.""" + """Return true if the given path is (public) non-test Python file.""" _, basename = os.path.split(path) _, ext = os.path.splitext(basename) return ( @@ -42,7 +42,7 @@ def _is_python_file(path): def get_python_files(directory): - """ Report Python files to be run or to be skipped. + """Report Python files to be run or to be skipped. Returns ------- @@ -82,8 +82,7 @@ def replaced_configure_traits( screenshot_name=None, **args, ): - """ Mocked configure_traits to launch then close the GUI. - """ + """Mocked configure_traits to launch then close the GUI.""" ui_kwargs = dict( view=view, parent=None, @@ -102,14 +101,14 @@ def replaced_configure_traits( "source", "traitsui_user_manual", "images", - screenshot_name + screenshot_name, ) ) @contextlib.contextmanager def replace_configure_traits(screenshot_name): - """ Context manager to temporarily replace HasTraits.configure_traits + """Context manager to temporarily replace HasTraits.configure_traits with a mocked version such that GUI launched are closed soon after they are open. """ @@ -124,7 +123,7 @@ def replace_configure_traits(screenshot_name): def run_file(file_path): - """ Execute a given Python file. + """Execute a given Python file. Parameters ---------- @@ -140,8 +139,9 @@ def run_file(file_path): "__name__": "__main__", "__file__": file_path, } - with replace_configure_traits(screenshot_name), \ - mock.patch("sys.argv", [file_path]): + with replace_configure_traits(screenshot_name), mock.patch( + "sys.argv", [file_path] + ): # Mock argv: Some example reads sys.argv to allow more arguments # But all examples should support being run without additional # arguments. diff --git a/docs/source/tutorials/code_snippets/code_block0.py b/docs/source/tutorials/code_snippets/code_block0.py index 03e57ec26..176f5eb2a 100644 --- a/docs/source/tutorials/code_snippets/code_block0.py +++ b/docs/source/tutorials/code_snippets/code_block0.py @@ -2,16 +2,17 @@ from numpy import cos, sin + class Point(object): - """ 3D Points objects """ - x = 0. - y = 0. - z = 0. + """3D Points objects""" + + x = 0.0 + y = 0.0 + z = 0.0 def rotate_z(self, theta): - """ rotate the point around the Z axis """ - xtemp = cos(theta) * self.x + sin(theta) * self.y + """rotate the point around the Z axis""" + xtemp = cos(theta) * self.x + sin(theta) * self.y ytemp = -sin(theta) * self.x + cos(theta) * self.y self.x = xtemp self.y = ytemp - diff --git a/docs/source/tutorials/code_snippets/code_block1.py b/docs/source/tutorials/code_snippets/code_block1.py index b15fa8059..6998574cc 100644 --- a/docs/source/tutorials/code_snippets/code_block1.py +++ b/docs/source/tutorials/code_snippets/code_block1.py @@ -2,22 +2,32 @@ from traits.api import CInt, Enum, HasTraits + class Camera(HasTraits): - """ Camera object """ - gain = Enum(1, 2, 3, - desc="the gain index of the camera", - label="gain", ) - exposure = CInt(10, - desc="the exposure time, in ms", - label="Exposure", ) + """Camera object""" + + gain = Enum( + 1, + 2, + 3, + desc="the gain index of the camera", + label="gain", + ) + exposure = CInt( + 10, + desc="the exposure time, in ms", + label="Exposure", + ) - def capture(self): - """ Captures an image on the camera and returns it """ - print("capturing an image at %i ms exposure, gain: %i" % ( - self.exposure, self.gain )) + def capture(self): + """Captures an image on the camera and returns it""" + print( + "capturing an image at %i ms exposure, gain: %i" + % (self.exposure, self.gain) + ) -if __name__ == "__main__": - camera = Camera() - camera.configure_traits() - camera.capture() +if __name__ == "__main__": + camera = Camera() + camera.configure_traits() + camera.capture() diff --git a/docs/source/tutorials/code_snippets/container.py b/docs/source/tutorials/code_snippets/container.py index 2ea641864..2d511bc1b 100644 --- a/docs/source/tutorials/code_snippets/container.py +++ b/docs/source/tutorials/code_snippets/container.py @@ -3,22 +3,29 @@ from traits.api import CInt, Enum, HasTraits, Instance, String from traitsui.api import Item, View + class Camera(HasTraits): - """ Camera object """ + """Camera object""" - gain = Enum(1, 2, 3, + gain = Enum( + 1, + 2, + 3, desc="the gain index of the camera", - label="gain", ) + label="gain", + ) - exposure = CInt(10, + exposure = CInt( + 10, desc="the exposure time, in ms", - label="Exposure", ) + label="Exposure", + ) class Display(HasTraits): string = String() - view= View( Item('string', show_label=False, springy=True, style='custom' )) + view = View(Item('string', show_label=False, springy=True, style='custom')) class Container(HasTraits): @@ -26,10 +33,17 @@ class Container(HasTraits): display = Instance(Display, ()) view = View( - Item('camera', style='custom', show_label=False, ), - Item('display', style='custom', show_label=False, ), - ) + Item( + 'camera', + style='custom', + show_label=False, + ), + Item( + 'display', + style='custom', + show_label=False, + ), + ) Container().configure_traits() - diff --git a/docs/source/tutorials/code_snippets/echo_box.py b/docs/source/tutorials/code_snippets/echo_box.py index ec887ba0b..a0c1ffad3 100644 --- a/docs/source/tutorials/code_snippets/echo_box.py +++ b/docs/source/tutorials/code_snippets/echo_box.py @@ -2,12 +2,13 @@ from traits.api import HasTraits, Str + class EchoBox(HasTraits): - input = Str() + input = Str() output = Str() def _input_changed(self): self.output = self.input -EchoBox().configure_traits() +EchoBox().configure_traits() diff --git a/docs/source/tutorials/code_snippets/event_loop.py b/docs/source/tutorials/code_snippets/event_loop.py index d81ce2c70..fa1b97db5 100644 --- a/docs/source/tutorials/code_snippets/event_loop.py +++ b/docs/source/tutorials/code_snippets/event_loop.py @@ -3,8 +3,10 @@ from traits.api import HasTraits, Int from pyface.api import GUI + class Counter(HasTraits): - value = Int() + value = Int() + Counter().edit_traits() GUI().start_event_loop() diff --git a/docs/source/tutorials/code_snippets/interactive.py b/docs/source/tutorials/code_snippets/interactive.py index 41fe132c6..e519249c3 100644 --- a/docs/source/tutorials/code_snippets/interactive.py +++ b/docs/source/tutorials/code_snippets/interactive.py @@ -3,14 +3,16 @@ from traits.api import HasTraits, Int, Button, observe from traitsui.api import View, Item, ButtonEditor + class Counter(HasTraits): - value = Int() + value = Int() add_one = Button() @observe('add_one') def _increment_value(self, event): - self.value +=1 + self.value += 1 + + view = View('value', Item('add_one', show_label=False)) - view = View('value', Item('add_one', show_label=False )) Counter().configure_traits() diff --git a/docs/source/tutorials/code_snippets/mpl_figure_editor.py b/docs/source/tutorials/code_snippets/mpl_figure_editor.py index 43349d506..ad0e6084f 100644 --- a/docs/source/tutorials/code_snippets/mpl_figure_editor.py +++ b/docs/source/tutorials/code_snippets/mpl_figure_editor.py @@ -3,6 +3,7 @@ import wx import matplotlib + # We want matplotlib to use a wxPython backend matplotlib.use('WXAgg') from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas @@ -13,9 +14,10 @@ from traitsui.wx.editor import Editor from traitsui.wx.basic_editor_factory import BasicEditorFactory + class _MPLFigureEditor(Editor): - scrollable = True + scrollable = True def init(self, parent): self.control = self._create_canvas(parent) @@ -25,7 +27,7 @@ def update_editor(self): pass def _create_canvas(self, parent): - """ Create the MPL canvas. """ + """Create the MPL canvas.""" # The panel lets us add additional controls. panel = wx.Panel(parent, -1, style=wx.CLIP_CHILDREN) sizer = wx.BoxSizer(wx.VERTICAL) @@ -38,6 +40,7 @@ def _create_canvas(self, parent): self.value.canvas.SetMinSize((10, 10)) return panel + class MPLFigureEditor(BasicEditorFactory): klass = _MPLFigureEditor @@ -53,17 +56,20 @@ class Test(HasTraits): figure = Instance(Figure, ()) - view = View(Item('figure', editor=MPLFigureEditor(), - show_label=False), - width=400, - height=300, - resizable=True) + view = View( + Item('figure', editor=MPLFigureEditor(), show_label=False), + width=400, + height=300, + resizable=True, + ) def __init__(self): super().__init__() axes = self.figure.add_subplot(111) - t = linspace(0, 2*pi, 200) - axes.plot(sin(t)*(1+0.5*cos(11*t)), cos(t)*(1+0.5*cos(11*t))) + t = linspace(0, 2 * pi, 200) + axes.plot( + sin(t) * (1 + 0.5 * cos(11 * t)), + cos(t) * (1 + 0.5 * cos(11 * t)), + ) Test().configure_traits() - diff --git a/docs/source/tutorials/code_snippets/thread_example.py b/docs/source/tutorials/code_snippets/thread_example.py index 40a1e802f..159c8350c 100644 --- a/docs/source/tutorials/code_snippets/thread_example.py +++ b/docs/source/tutorials/code_snippets/thread_example.py @@ -3,13 +3,14 @@ from threading import Thread from time import sleep + class MyThread(Thread): def run(self): sleep(2) print("MyThread done") + my_thread = MyThread() my_thread.start() print("Main thread done") - diff --git a/docs/source/tutorials/code_snippets/traits_thread.py b/docs/source/tutorials/code_snippets/traits_thread.py index ab3417033..af21a82e6 100644 --- a/docs/source/tutorials/code_snippets/traits_thread.py +++ b/docs/source/tutorials/code_snippets/traits_thread.py @@ -17,10 +17,11 @@ def run(self): self.display.string = 'Camera started\n' + self.display.string n_img = 0 while not self.wants_abort: - sleep(.5) + sleep(0.5) n_img += 1 - self.display.string = ('%d image captured\n' % n_img - + self.display.string) + self.display.string = ( + '%d image captured\n' % n_img + self.display.string + ) self.display.string = 'Camera stopped\n' + self.display.string @@ -52,5 +53,6 @@ def _camera_default(self): view = View('display', 'camera', style="custom", resizable=True) + if __name__ == '__main__': MainWindow().configure_traits() diff --git a/ets-demo/etsdemo/app.py b/ets-demo/etsdemo/app.py index f2a69be43..44525069b 100644 --- a/ets-demo/etsdemo/app.py +++ b/ets-demo/etsdemo/app.py @@ -137,8 +137,8 @@ def extract_docstring_from_source(source): source_lines = source.splitlines() # Extract module docstring lines and recombine - docstring = eval("\n".join(source_lines[tstart[0] - 1: tend[0]])) - source_lines = source_lines[: tstart[0] - 1] + source_lines[tend[0]:] + docstring = eval("\n".join(source_lines[tstart[0] - 1 : tend[0]])) + source_lines = source_lines[: tstart[0] - 1] + source_lines[tend[0] :] source = "\n".join(source_lines) source = source.strip() @@ -168,8 +168,7 @@ def parse_source(file_name): def _read_file(path, mode='r', encoding='utf8'): - """ Returns the contents of a specified text file. - """ + """Returns the contents of a specified text file.""" with open(path, mode, encoding=encoding) as fh: result = fh.read() return result @@ -179,6 +178,7 @@ def _read_file(path, mode='r', encoding='utf8'): # 'DemoFileHandler' class: # ------------------------------------------------------------------------- + @contextlib.contextmanager def _set_stdout(std_out): stdout, stderr = sys.stdout, sys.stderr @@ -215,8 +215,7 @@ def init(self, info): return True def closed(self, info, is_ok): - """ Closes the view. - """ + """Closes the view.""" demo_file = info.object if hasattr(demo_file, 'demo'): demo_file.demo = None @@ -318,8 +317,7 @@ class DemoTreeNodeObject(TreeNodeObject): # ------------------------------------------------------------------------- def tno_allows_children(self, node): - """ Returns whether chidren of this object are allowed or not. - """ + """Returns whether chidren of this object are allowed or not.""" return self.allows_children # ------------------------------------------------------------------------- @@ -327,8 +325,7 @@ def tno_allows_children(self, node): # ------------------------------------------------------------------------- def tno_has_children(self, node=None): - """ Returns whether or not the object has children. - """ + """Returns whether or not the object has children.""" if self._has_children is None: self._has_children = self.has_children() @@ -339,8 +336,7 @@ def tno_has_children(self, node=None): # ------------------------------------------------------------------------- def tno_get_children(self, node): - """ Gets the object's children. - """ + """Gets the object's children.""" if self._get_children is None: self._get_children = self.get_children() @@ -351,8 +347,7 @@ def tno_get_children(self, node): # ------------------------------------------------------------------------- def has_children(self, node): - """ Returns whether or not the object has children. - """ + """Returns whether or not the object has children.""" raise NotImplementedError # ------------------------------------------------------------------------- @@ -360,8 +355,7 @@ def has_children(self, node): # ------------------------------------------------------------------------- def get_children(self): - """ Gets the object's children. - """ + """Gets the object's children.""" raise NotImplementedError @@ -432,13 +426,11 @@ def _set_nice_name(self, value): # ------------------------------------------------------------------------- def has_children(self): - """ Returns whether or not the object has children. - """ + """Returns whether or not the object has children.""" return False def get_children(self): - """ Gets the demo file's children. - """ + """Gets the demo file's children.""" return [] @@ -461,8 +453,7 @@ def init(self): self.run_code() def run_code(self): - """ Runs the code associated with this demo file. - """ + """Runs the code associated with this demo file.""" try: # Get the execution context dictionary: locals = self.parent.init_dic @@ -507,7 +498,6 @@ def _get_object(self, name, dic): class DemoContentFile(DemoFileBase): - def init(self): super().init() file_str = _read_file(self.path) @@ -515,7 +505,6 @@ def init(self): class DemoImageFile(DemoFileBase): - def init(self): super().init() rst_content = ".. image:: {}".format(self.name) @@ -523,8 +512,7 @@ def init(self): class DemoPath(DemoTreeNodeObject): - """ This class represents a directory. - """ + """This class represents a directory.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -588,7 +576,7 @@ def __file_factory_default(self): ".png": DemoImageFile, ".py": DemoFile, ".rst": DemoContentFile, - ".txt": DemoContentFile + ".txt": DemoContentFile, } # ------------------------------------------------------------------------- @@ -662,8 +650,7 @@ def _get_init_dic(self): # ------------------------------------------------------------------------- def has_children(self): - """ Returns whether or not the object has children. - """ + """Returns whether or not the object has children.""" path = self.path for name in listdir(path): cur_path = join(path, name) @@ -684,8 +671,7 @@ def has_children(self): # ------------------------------------------------------------------------- def get_children(self): - """ Gets the object's children. - """ + """Gets the object's children.""" if self.config_dict or self.config_filename: children = self.get_children_from_config() else: @@ -696,8 +682,7 @@ def get_children(self): # Gets the object's children based on the filesystem structure. # ------------------------------------------------------------------------- def get_children_from_datastructure(self): - """ Gets the object's children based on the filesystem structure. - """ + """Gets the object's children based on the filesystem structure.""" dirs = [] files = [] @@ -710,7 +695,7 @@ def get_children_from_datastructure(self): DemoPath( parent=self, name=name, - css_filename=join('..', self.css_filename) + css_filename=join('..', self.css_filename), ) ) elif self.use_files: @@ -781,7 +766,8 @@ def get_children_from_config(self): demoobj.nice_name = keyword demoobj.config_dict = config_dict demoobj.css_filename = os.path.join( - "..", self.css_filename) + "..", self.css_filename + ) dirs.append(demoobj) elif len(names) == 1: try: @@ -816,8 +802,7 @@ def has_py_files(self, path): return False def _handle_file(self, filename): - """ Process a file based on its extension. - """ + """Process a file based on its extension.""" _, ext = splitext(filename) file_factory = self._file_factory[ext] demo_file = file_factory(parent=self, name=filename) @@ -825,7 +810,7 @@ def _handle_file(self, filename): class DemoVirtualDirectory(DemoTreeNodeObject): - """ A class to represent a virtual directory that can contain + """A class to represent a virtual directory that can contain many other demo resources as nested objects, without actually requiring the resources to be hosted in a common directory. """ @@ -899,17 +884,16 @@ def get_children(self): "log", style="readonly", editor=CodeEditor( - show_line_numbers=False, - selected_color=0xFFFFFF + show_line_numbers=False, selected_color=0xFFFFFF ), label="Output", - show_label=False + show_label=False, ), Item( "locals", editor=ShellEditor(share=True), label="Shell", - show_label=False + show_label=False, ), visible_when='demo is not None', ), @@ -918,17 +902,16 @@ def get_children(self): "log", style="readonly", editor=CodeEditor( - show_line_numbers=False, - selected_color=0xFFFFFF + show_line_numbers=False, selected_color=0xFFFFFF ), label="Output", - show_label=False + show_label=False, ), Item( "locals", editor=ShellEditor(share=True), label="Shell", - show_label=False + show_label=False, ), visible_when='demo is None', ), @@ -974,19 +957,15 @@ def get_children(self): view=demo_path_view, ), ObjectTreeNode( - node_for=[DemoFile], - label="nice_name", - view=demo_file_view + node_for=[DemoFile], label="nice_name", view=demo_file_view ), ObjectTreeNode( node_for=[DemoContentFile], label="nice_name", - view=demo_content_view + view=demo_content_view, ), ObjectTreeNode( - node_for=[DemoImageFile], - label="nice_name", - view=demo_content_view + node_for=[DemoImageFile], label="nice_name", view=demo_content_view ), ObjectTreeNode( node_for=[DemoVirtualDirectory], @@ -1021,7 +1000,7 @@ def get_children(self): tooltip="Go to next file", action="do_parent", enabled_when="(selected_node is not None) and " - "(object.selected_node.parent is not None)", + "(object.selected_node.parent is not None)", ) @@ -1133,7 +1112,7 @@ def default_traits_view(self): def _get_settings(css_path=None): - """ Helper function to make settings dictionary + """Helper function to make settings dictionary consumable by docutils Parameters @@ -1155,7 +1134,7 @@ def _get_settings(css_path=None): def publish_html_str(rst_str, css_path=None): - """ Format RST string to html using `docutils` if available. + """Format RST string to html using `docutils` if available. Otherwise, return the input `rst_str`. Parameters @@ -1176,13 +1155,13 @@ def publish_html_str(rst_str, css_path=None): return rst_str settings = _get_settings(css_path) - return publish_string(rst_str, - writer_name='html', - settings_overrides=settings) + return publish_string( + rst_str, writer_name='html', settings_overrides=settings + ) def publish_html_file(rst_file_path, html_out_path, css_path=None): - """ Format reStructuredText in `rst_file_path` to html using `docutils` + """Format reStructuredText in `rst_file_path` to html using `docutils` if available. Otherwise, does nothing. Parameters @@ -1204,10 +1183,12 @@ def publish_html_file(rst_file_path, html_out_path, css_path=None): return settings = _get_settings(css_path) - publish_file(source_path=rst_file_path, - destination_path=html_out_path, - writer_name='html', - settings_overrides=settings) + publish_file( + source_path=rst_file_path, + destination_path=html_out_path, + writer_name='html', + settings_overrides=settings, + ) # ------------------------------------------------------------------------- diff --git a/ets-demo/etsdemo/info.py b/ets-demo/etsdemo/info.py index b0c3f52af..e214a9e00 100644 --- a/ets-demo/etsdemo/info.py +++ b/ets-demo/etsdemo/info.py @@ -16,7 +16,7 @@ def info(): - """ Provides information to the "eam" package. """ + """Provides information to the "eam" package.""" return { "name": "ETS Demo", "description": "Application for browsing ETS examples and demos", diff --git a/ets-demo/etsdemo/loader.py b/ets-demo/etsdemo/loader.py index 736380dae..666fbca57 100644 --- a/ets-demo/etsdemo/loader.py +++ b/ets-demo/etsdemo/loader.py @@ -29,7 +29,7 @@ def get_responses(): - """ Load entry points and return the responses. + """Load entry points and return the responses. Version 1 response should have the following format: { @@ -73,7 +73,7 @@ def get_responses(): def response_to_node(response): - """ Convert a response to an instance of DemoTreeNodeObject + """Convert a response to an instance of DemoTreeNodeObject Parameters ---------- @@ -111,7 +111,7 @@ def response_to_node(response): class _Response(HasTraits): - """ Object for normalizing the validating responses returned by entry + """Object for normalizing the validating responses returned by entry points. """ @@ -125,8 +125,7 @@ class _Response(HasTraits): root = Directory(exists=True) def to_node(self): - """ Return an instance of DemoTreeNodeObject from this response. - """ + """Return an instance of DemoTreeNodeObject from this response.""" return DemoPath( nice_name=self.name, name=self.root, diff --git a/ets-demo/etsdemo/main.py b/ets-demo/etsdemo/main.py index 5f42ddeaf..0d844c83b 100644 --- a/ets-demo/etsdemo/main.py +++ b/ets-demo/etsdemo/main.py @@ -30,7 +30,7 @@ @contextlib.contextmanager def _set_logger(logger, level): - """ Context manager for setting logging. + """Context manager for setting logging. Parameters ---------- @@ -55,7 +55,7 @@ def _set_logger(logger, level): def _parse_command_line(): - """ Parse command line arguments for the main function. + """Parse command line arguments for the main function. Returns ------- @@ -72,7 +72,8 @@ def _parse_command_line(): default=logging.WARNING, ) parser.add_argument( - '-v', '--verbose', + '-v', + '--verbose', help="Log information to console.", action="store_const", dest="log_level", @@ -82,7 +83,7 @@ def _parse_command_line(): def _create_demo(infos=None, title=_TITLE): - """ Create the demo object with everything setup ready to be launched. + """Create the demo object with everything setup ready to be launched. Parameters ---------- @@ -102,10 +103,7 @@ def _create_demo(infos=None, title=_TITLE): if infos is None: infos = get_responses() - resources = [ - response_to_node(response) - for response in infos - ] + resources = [response_to_node(response) for response in infos] logger.info("Found %r resource(s).", len(resources)) return Demo( title=title, @@ -114,7 +112,7 @@ def _create_demo(infos=None, title=_TITLE): def main(infos=None, title=_TITLE): - """ Main function for launching the demo application. + """Main function for launching the demo application. Parameters ---------- diff --git a/ets-demo/etsdemo/tests/test_app.py b/ets-demo/etsdemo/tests/test_app.py index 362562124..075aa1dbf 100644 --- a/ets-demo/etsdemo/tests/test_app.py +++ b/ets-demo/etsdemo/tests/test_app.py @@ -36,7 +36,7 @@ def get_html_tag(tag): def get_action_enabled(action, model_view): - """ Helper funciton to return if a tool is enabled. + """Helper funciton to return if a tool is enabled. Parameters ---------- @@ -53,7 +53,7 @@ def get_action_enabled(action, model_view): class TestDemo(unittest.TestCase): - """ Test actions on the Demo class. """ + """Test actions on the Demo class.""" def test_demo_previous_button_default(self): # Make sure the previous button behaves in the default state. @@ -108,7 +108,6 @@ def test_demo_init_no_children_to_be_set(self): class TestDemoImageFile(unittest.TestCase): - def test_description_contains_file_uri(self): with tempfile.NamedTemporaryFile() as file_obj: dirname, basename = os.path.split(file_obj.name) @@ -129,7 +128,7 @@ def test_description_contains_file_uri(self): class TestDemoPathDescription(unittest.TestCase): - """ Test ``DemoPath.description`` """ + """Test ``DemoPath.description``""" def test_description_with_empty_directory(self): # If the directory is empty, the content of the description should @@ -141,7 +140,7 @@ def test_description_with_empty_directory(self): tree = ET.fromstring(model.description) body_node = next(tree.iter(get_html_tag("body"))) - div_node, = list(body_node) + (div_node,) = list(body_node) self.assertEqual(list(div_node), []) def test_use_index_rst(self): @@ -172,7 +171,7 @@ def test_description_use_css(self): class TestDemoPathInitLocals(unittest.TestCase): - """ Test ``DemoPath.init_dic`` """ + """Test ``DemoPath.init_dic``""" def test_init_dict_with_empty_directory(self): with tempfile.TemporaryDirectory() as directory: @@ -199,8 +198,7 @@ def test_init_dict_with_init_py(self): class TestDemoPathChildren(unittest.TestCase): - """ Integration test with DemoPath and its children - """ + """Integration test with DemoPath and its children""" def test_init_dict_used_by_children(self): # Test the __init__.py in a directory (if exists) is visible @@ -236,10 +234,10 @@ def test_init_dict_used_by_children(self): # In that subdirectory, there is one Python file that is not # __init__.py - subdir_node, = children + (subdir_node,) = children file_nodes = subdir_node.get_children() self.assertEqual(len(file_nodes), 1) - example, = file_nodes + (example,) = file_nodes self.assertEqual(example.name, "example.py") # This is the test objective: The __init__.py and traits api are @@ -251,7 +249,6 @@ def test_init_dict_used_by_children(self): class TestDemoVirtualDirectory(unittest.TestCase): - def test_no_resources(self): node = DemoVirtualDirectory(resources=[]) self.assertFalse(node.tno_has_children(None)) @@ -266,7 +263,6 @@ def test_some_resources(self): class TestParseSource(unittest.TestCase): - def test_extract_docstring_from_source(self): source_code = b"" with self.assertRaises(TypeError): diff --git a/ets-demo/etsdemo/tests/test_info.py b/ets-demo/etsdemo/tests/test_info.py index 153a72b32..f438a3c0e 100644 --- a/ets-demo/etsdemo/tests/test_info.py +++ b/ets-demo/etsdemo/tests/test_info.py @@ -16,7 +16,7 @@ import unittest try: - import eam # noqa: #F401 + import eam # noqa: #F401 except ImportError: EAM_EXISTS = False else: @@ -26,7 +26,6 @@ class TestInfoForEAM(unittest.TestCase): - @unittest.skipUnless(EAM_EXISTS, "eam is not available.") def test_etsdemo_info(self): output = subprocess.check_output( @@ -37,7 +36,7 @@ def test_etsdemo_info(self): def test_etsdemo_icon_exists(self): metadata = info() - command, = metadata["commands"] + (command,) = metadata["commands"] icon = command["icon"] self.assertTrue( os.path.exists(icon), "Expected icon file to exist. Not found." diff --git a/ets-demo/etsdemo/tests/test_loader.py b/ets-demo/etsdemo/tests/test_loader.py index baea03c7c..e0d0950ff 100644 --- a/ets-demo/etsdemo/tests/test_loader.py +++ b/ets-demo/etsdemo/tests/test_loader.py @@ -53,7 +53,7 @@ def misbehaving_demo_response(request): class TestResponseToNode(unittest.TestCase): - """ Test conversion from response to node. """ + """Test conversion from response to node.""" def test_good_response_to_node(self): with tempfile.TemporaryDirectory() as temp_dir: @@ -82,9 +82,10 @@ def test_good_response_but_nonexisting_root_to_node(self): self.assertEqual(resource.nice_name, "Amazing Demo") self.assertFalse(resource.has_children()) self.assertIn( - "Unable to load data.", resource.description, + "Unable to load data.", + resource.description, ) - log_content, = watcher.output + (log_content,) = watcher.output self.assertIn("TraitError", log_content) def test_bad_response_replaced(self): @@ -95,11 +96,8 @@ def test_bad_response_replaced(self): self.assertFalse(resource.has_children()) self.assertEqual(resource.nice_name, "(Empty)") - self.assertIn( - "Unable to load data.", - resource.description - ) - log_content, = watcher.output + self.assertIn("Unable to load data.", resource.description) + (log_content,) = watcher.output self.assertIn("KeyError", log_content) def test_bad_response_type_error(self): @@ -116,11 +114,8 @@ def test_bad_response_type_error(self): self.assertFalse(resource.has_children()) self.assertEqual(resource.nice_name, "(Empty)") - self.assertIn( - "Unable to load data.", - resource.description - ) - log_content, = watcher.output + self.assertIn("Unable to load data.", resource.description) + (log_content,) = watcher.output self.assertIn("TypeError", log_content) def test_bad_response_missing_name(self): @@ -134,7 +129,7 @@ def test_bad_response_missing_name(self): self.assertFalse(resource.has_children()) self.assertEqual(resource.nice_name, "(Empty)") - log_content, = watcher.output + (log_content,) = watcher.output self.assertIn("KeyError: \'name\'", log_content) def test_bad_response_missing_version(self): @@ -147,7 +142,7 @@ def test_bad_response_missing_version(self): resource = response_to_node(response) self.assertFalse(resource.has_children()) - log_content, = watcher.output + (log_content,) = watcher.output self.assertIn("KeyError: \'version\'", log_content) def test_bad_response_bad_version(self): @@ -161,7 +156,7 @@ def test_bad_response_bad_version(self): resource = response_to_node(response) self.assertFalse(resource.has_children()) - log_content, = watcher.output + (log_content,) = watcher.output self.assertIn("TraitError", log_content) def test_bad_response_bad_name_type(self): @@ -175,12 +170,12 @@ def test_bad_response_bad_name_type(self): resource = response_to_node(response) self.assertFalse(resource.has_children()) - log_content, = watcher.output + (log_content,) = watcher.output self.assertIn("TraitError", log_content) class TestGetResponse(unittest.TestCase): - """ Test the routine to obtain resources from entry points.""" + """Test the routine to obtain resources from entry points.""" def test_load_good_entry_points(self): with mock_iter_entry_points(GOOD_ENTRY_POINTS): @@ -207,7 +202,7 @@ def test_load_errored_entry_points(self): resources = get_responses() self.assertEqual(len(resources), 1) - log_output, = watcher.output + (log_output,) = watcher.output self.assertIn("Failed to obtain data from", log_output) def test_load_import_error(self): @@ -226,5 +221,5 @@ def test_load_import_error(self): resources = get_responses() self.assertEqual(len(resources), 1) - log_output, = watcher.output + (log_output,) = watcher.output self.assertIn("Failed to load entry point", log_output) diff --git a/ets-demo/etsdemo/tests/test_main.py b/ets-demo/etsdemo/tests/test_main.py index 3e80c3c74..e59d15287 100644 --- a/ets-demo/etsdemo/tests/test_main.py +++ b/ets-demo/etsdemo/tests/test_main.py @@ -35,14 +35,14 @@ def fake_configure_traits(instance): def mock_demo_launch(): - """ Mock Demo.configure_traits so that we can open and then close the UI + """Mock Demo.configure_traits so that we can open and then close the UI for testing the main function. """ return mock.patch.object(Demo, "configure_traits", fake_configure_traits) class TestMain(unittest.TestCase): - """ Test main function.""" + """Test main function.""" @require_gui def test_main(self): @@ -50,12 +50,15 @@ def test_main(self): # In normal running situation, no loggings should be emitted argv = ["etsdemo"] mocked_io = io.StringIO() - with mock_iter_entry_points({}), \ - mock_demo_launch(), \ - mocked_io, \ - mock.patch("sys.stdout", mocked_io), \ - mock.patch("sys.stderr", mocked_io), \ - mock.patch("sys.argv", argv): + with mock_iter_entry_points( + {} + ), mock_demo_launch(), mocked_io, mock.patch( + "sys.stdout", mocked_io + ), mock.patch( + "sys.stderr", mocked_io + ), mock.patch( + "sys.argv", argv + ): main_module.main() console_output = mocked_io.getvalue() @@ -66,12 +69,15 @@ def test_main_with_log(self): # Test logging configuration with the main function. argv = ["etsdemo", "-v"] mocked_io = io.StringIO() - with mock_iter_entry_points({}), \ - mock_demo_launch(), \ - mocked_io, \ - mock.patch("sys.stdout", mocked_io), \ - mock.patch("sys.stderr", mocked_io), \ - mock.patch("sys.argv", argv): + with mock_iter_entry_points( + {} + ), mock_demo_launch(), mocked_io, mock.patch( + "sys.stdout", mocked_io + ), mock.patch( + "sys.stderr", mocked_io + ), mock.patch( + "sys.argv", argv + ): main_module.main() console_output = mocked_io.getvalue() @@ -79,7 +85,7 @@ def test_main_with_log(self): class TestCreateDemo(unittest.TestCase): - """ Test _create_demo """ + """Test _create_demo""" def test_create_demo_default_entry_points(self): # This does not require GUI and it should not fail. @@ -99,7 +105,7 @@ def test_create_demo_with_specific_info(self): "version": 1, "name": "Delicious Demo", "root": temp_dir, - } + }, ] demo = main_module._create_demo(infos) children = demo.model.get_children() diff --git a/ets-demo/etsdemo/tests/testing.py b/ets-demo/etsdemo/tests/testing.py index 85dc1d9ce..bf4c036fa 100644 --- a/ets-demo/etsdemo/tests/testing.py +++ b/ets-demo/etsdemo/tests/testing.py @@ -15,11 +15,11 @@ def require_gui(func): - """ Decorator for tests that require a non-null GUI toolkit. - """ + """Decorator for tests that require a non-null GUI toolkit.""" # Defer GUI import side-effect. # The toolkit is not resolved until we import pyface.api from pyface.api import GUI + try: GUI() except NotImplementedError: @@ -28,7 +28,7 @@ def require_gui(func): def create_iter_entry_points(fake_entry_points): - """ Return a new callable that mocks the interface of + """Return a new callable that mocks the interface of pkg_resources.iter_entry_points with the given entry point data. Currently the behaviour of a given non-None value for ``name`` is not @@ -61,7 +61,7 @@ def iter_entry_points(group, name=None): def mock_iter_entry_points(fake_entry_points): - """ Mock pkg_resources.iter_entry_points with the given entry point data. + """Mock pkg_resources.iter_entry_points with the given entry point data. Currently the behaviour of a given non-None value for ``name`` is not supported. @@ -72,6 +72,7 @@ def mock_iter_entry_points(fake_entry_points): Mapping from distribution names to entry point definitions. """ return mock.patch.object( - pkg_resources, "iter_entry_points", - create_iter_entry_points(fake_entry_points) + pkg_resources, + "iter_entry_points", + create_iter_entry_points(fake_entry_points), ) diff --git a/ets-demo/etstool.py b/ets-demo/etstool.py index 639b514a1..313d2170a 100644 --- a/ets-demo/etstool.py +++ b/ets-demo/etstool.py @@ -191,9 +191,7 @@ def cli(): help="Install main package in 'editable' mode? [default: --not-editable]", ) def install(runtime, toolkit, environment, editable): - """ Install project and dependencies into a clean EDM environment. - - """ + """Install project and dependencies into a clean EDM environment.""" parameters = get_parameters(runtime, toolkit, environment) packages = ' '.join( dependencies @@ -208,30 +206,32 @@ def install(runtime, toolkit, environment, editable): # edm commands to setup the development environment if sys.platform == 'linux': - commands = ["edm environments create {environment} --platform=rh6-x86_64 --force --version={runtime}"] # noqa: E501 + commands = [ + "edm environments create {environment} --platform=rh6-x86_64 --force --version={runtime}" + ] # noqa: E501 else: - commands = ["edm environments create {environment} --force --version={runtime}"] # noqa: E501 - - commands.extend([ - "edm install -y -e {environment} " + packages, - "edm run -e {environment} -- python setup.py clean --all", - install_here, - ]) + commands = [ + "edm environments create {environment} --force --version={runtime}" + ] # noqa: E501 + + commands.extend( + [ + "edm install -y -e {environment} " + packages, + "edm run -e {environment} -- python setup.py clean --all", + install_here, + ] + ) # pip install pyside2, because we don't have it in EDM yet if toolkit == 'pyside2': - commands.append( - "edm run -e {environment} -- pip install pyside2" - ) + commands.append("edm run -e {environment} -- pip install pyside2") elif toolkit == 'wx': if sys.platform != 'linux': - commands.append( - "edm run -e {environment} -- pip install wxPython" - ) + commands.append("edm run -e {environment} -- pip install wxPython") else: # XXX this is mainly for TravisCI workers; need a generic solution commands.append( - "edm run -e {environment} -- pip install -f https://extras.wxpython.org/wxPython4/extras/linux/gtk3/ubuntu-16.04 wxPython" # noqa: E501 + "edm run -e {environment} -- pip install -f https://extras.wxpython.org/wxPython4/extras/linux/gtk3/ubuntu-16.04 wxPython" # noqa: E501 ) click.echo("Creating environment '{environment}'".format(**parameters)) @@ -244,7 +244,7 @@ def install(runtime, toolkit, environment, editable): @click.option('--toolkit', default=DEFAULT_TOOLKIT) @click.option('--environment', default=None) def shell(runtime, toolkit, environment): - """ Create a shell into the EDM development environment + """Create a shell into the EDM development environment (aka 'activate' it). """ @@ -260,9 +260,7 @@ def shell(runtime, toolkit, environment): @click.option('--toolkit', default=DEFAULT_TOOLKIT) @click.option('--environment', default=None) def test(runtime, toolkit, environment): - """ Run the test suite in a given environment with the specified toolkit. - - """ + """Run the test suite in a given environment with the specified toolkit.""" parameters = get_parameters(runtime, toolkit, environment) environ = environment_vars.get(toolkit, {}).copy() environ['PYTHONUNBUFFERED'] = "1" @@ -271,8 +269,7 @@ def test(runtime, toolkit, environment): "python -m unittest discover -v " + PACKAGE_NAME, ] commands = [ - "edm run -e {environment} -- " + command - for command in commands + "edm run -e {environment} -- " + command for command in commands ] # We run in a tempdir to avoid accidentally picking up wrong code from a @@ -289,13 +286,12 @@ def test(runtime, toolkit, environment): @click.option('--toolkit', default=DEFAULT_TOOLKIT) @click.option('--environment', default=None) def cleanup(runtime, toolkit, environment): - """ Remove a development environment. - - """ + """Remove a development environment.""" parameters = get_parameters(runtime, toolkit, environment) commands = [ "edm run -e {environment} -- python setup.py clean", - "edm environments remove {environment} --purge -y"] + "edm environments remove {environment} --purge -y", + ] click.echo("Cleaning up environment '{environment}'".format(**parameters)) execute(commands, parameters) click.echo('Done cleanup') @@ -305,9 +301,7 @@ def cleanup(runtime, toolkit, environment): @click.option('--runtime', default=DEFAULT_RUNTIME) @click.option('--toolkit', default=DEFAULT_TOOLKIT) def test_clean(runtime, toolkit): - """ Run tests in a clean environment, cleaning up afterwards - - """ + """Run tests in a clean environment, cleaning up afterwards""" args = ['--toolkit={}'.format(toolkit), '--runtime={}'.format(runtime)] try: install(args=args, standalone_mode=False) @@ -318,15 +312,13 @@ def test_clean(runtime, toolkit): @cli.command() def test_all(): - """ Run test_clean across all supported environment combinations. - - """ + """Run test_clean across all supported environment combinations.""" failed_command = False for runtime, toolkits in supported_combinations.items(): for toolkit in toolkits: args = [ '--toolkit={}'.format(toolkit), - '--runtime={}'.format(runtime) + '--runtime={}'.format(runtime), ] try: test_clean(args, standalone_mode=True) @@ -343,9 +335,7 @@ def test_all(): "--environment", default=None, help="Name of EDM environment to check." ) def flake8(runtime, toolkit, environment): - """ Run a flake8 check in a given environment. - - """ + """Run a flake8 check in a given environment.""" parameters = get_parameters(runtime, toolkit, environment) commands = ["edm run -e {environment} -- python -m flake8"] execute(commands, parameters) @@ -353,18 +343,14 @@ def flake8(runtime, toolkit, environment): @cli.command(name="generate-bundles") def generate_bundles(): - """ Generate application bundles for each supported platform. - """ + """Generate application bundles for each supported platform.""" for platform in PLATFORMS: bundle_dir = os.path.join("bundle", platform) if not os.path.exists(bundle_dir): os.makedirs(bundle_dir) - bundle_file = os.path.join( - bundle_dir, - BUNDLE_NAME - ) + bundle_file = os.path.join(bundle_dir, BUNDLE_NAME) click.echo("Generating bundle {}".format(bundle_file)) @@ -390,14 +376,11 @@ def generate_bundles(): @cli.command(name="upload-bundles") @click.option('--repository', default=DEFAULT_REPOSITORY) def upload_bundles(repository): - """ Upload the generated bundles """ + """Upload the generated bundles""" BUNDLES = [] for platform in PLATFORMS: bundle_dir = os.path.join("bundle", platform) - bundle_file = os.path.join( - bundle_dir, - BUNDLE_NAME - ) + bundle_file = os.path.join(bundle_dir, BUNDLE_NAME) if os.path.exists(bundle_file): BUNDLES.append((bundle_file, platform)) @@ -409,7 +392,7 @@ def upload_bundles(repository): "enthought", repository, platform, - bundle + bundle, ] try: subprocess.check_call(cmd) @@ -421,27 +404,30 @@ def upload_bundles(repository): # Utility routines # ---------------------------------------------------------------------------- + def get_parameters(runtime, toolkit, environment): - """ Set up parameters dictionary for format() substitution """ + """Set up parameters dictionary for format() substitution""" parameters = { 'runtime': runtime, 'toolkit': toolkit, 'environment': environment, } if toolkit not in supported_combinations[runtime]: - msg = ("Python {runtime} and toolkit {toolkit} not supported by " + - "test environments") + msg = ( + "Python {runtime} and toolkit {toolkit} not supported by " + + "test environments" + ) raise RuntimeError(msg.format(**parameters)) if environment is None: - parameters['environment'] = ( - PACKAGE_NAME + '-test-{runtime}-{toolkit}'.format(**parameters) - ) + parameters[ + 'environment' + ] = PACKAGE_NAME + '-test-{runtime}-{toolkit}'.format(**parameters) return parameters @contextmanager def do_in_tempdir(files=(), capture_files=()): - """ Create a temporary directory, cleaning up after done. + """Create a temporary directory, cleaning up after done. Creates the temporary directory, and changes into it. On exit returns to original directory and removes temporary dir. @@ -478,8 +464,9 @@ def execute(commands, parameters): for command in commands: click.echo("[EXECUTING] {}".format(command.format(**parameters))) try: - subprocess.check_call([arg.format(**parameters) - for arg in command.split()]) + subprocess.check_call( + [arg.format(**parameters) for arg in command.split()] + ) except subprocess.CalledProcessError as exc: click.echo(str(exc)) sys.exit(1) diff --git a/ets-demo/setup.py b/ets-demo/setup.py index 89cd8d76e..7b1851631 100644 --- a/ets-demo/setup.py +++ b/ets-demo/setup.py @@ -115,7 +115,8 @@ def write_version_file(version, git_revision): with open(VERSION_FILE, "w", encoding="utf-8") as version_file: version_file.write( VERSION_FILE_TEMPLATE.format( - version=version, git_revision=git_revision, + version=version, + git_revision=git_revision, ) ) @@ -234,7 +235,7 @@ def resolve_version(): def get_long_description(): - """ Read long description from README.rst. """ + """Read long description from README.rst.""" with open("README.rst", "r", encoding="utf-8") as readme: return readme.read() @@ -260,7 +261,9 @@ def get_long_description(): url="https://github.com/enthought/traitsui", author="Enthought", author_email="info@enthought.com", - classifiers=[c.strip() for c in """\ + classifiers=[ + c.strip() + for c in """\ Development Status :: 1 - Planning Intended Audience :: Developers Intended Audience :: Science/Research @@ -277,7 +280,9 @@ def get_long_description(): Programming Language :: Python :: 3.8 Topic :: Scientific/Engineering Topic :: Software Development - """.splitlines() if len(c.strip()) > 0], + """.splitlines() + if len(c.strip()) > 0 + ], description="Enthought Tool Suite Demo Application", long_description=get_long_description(), long_description_content_type="text/x-rst", diff --git a/etstool.py b/etstool.py index 999052491..b790d7ebf 100644 --- a/etstool.py +++ b/etstool.py @@ -158,7 +158,7 @@ # Test dependencies also applied to installation from PYPI 'test': { 'packaging', - } + }, } # Dependencies for CI jobs using this file. @@ -198,6 +198,7 @@ # Location of the Changelog file. CHANGELOG_PATH = os.path.join(HERE, "CHANGES.txt") + def normalize(name): return name.replace("_", "-") @@ -225,9 +226,7 @@ def cli(): ) @click.option('--source/--no-source', default=False) def install(runtime, toolkit, environment, editable, source): - """ Install project and dependencies into a clean EDM environment. - - """ + """Install project and dependencies into a clean EDM environment.""" parameters = get_parameters(runtime, toolkit, environment) packages = ( dependencies @@ -238,29 +237,30 @@ def install(runtime, toolkit, environment, editable, source): | ci_dependencies ) - # edm commands to setup the development environment if sys.platform == 'linux': - commands = ["edm environments create {environment} --platform=rh6-x86_64 --force --version={runtime}"] + commands = [ + "edm environments create {environment} --platform=rh6-x86_64 --force --version={runtime}" + ] else: - commands = ["edm environments create {environment} --force --version={runtime}"] + commands = [ + "edm environments create {environment} --force --version={runtime}" + ] - commands.extend([ - "edm install -y -e {environment} " + " ".join(packages), - "edm run -e {environment} -- pip install --force-reinstall -r ci-src-requirements.txt --no-dependencies", - "edm run -e {environment} -- python setup.py clean --all", - ]) + commands.extend( + [ + "edm install -y -e {environment} " + " ".join(packages), + "edm run -e {environment} -- pip install --force-reinstall -r ci-src-requirements.txt --no-dependencies", + "edm run -e {environment} -- python setup.py clean --all", + ] + ) # pip install pyqt5 and pyside2, because we don't have them in EDM yet if toolkit == 'pyside2': - commands.append( - "edm run -e {environment} -- pip install pyside2" - ) + commands.append("edm run -e {environment} -- pip install pyside2") elif toolkit == 'wx': if sys.platform != 'linux': - commands.append( - "edm run -e {environment} -- pip install wxPython" - ) + commands.append("edm run -e {environment} -- pip install wxPython") else: # XXX this is mainly for TravisCI workers; need a generic solution commands.append( @@ -271,8 +271,12 @@ def install(runtime, toolkit, environment, editable, source): execute(commands, parameters) if source: - cmd_fmt = "edm plumbing remove-package --environment {environment} --force " - commands = [cmd_fmt+dependency for dependency in source_dependencies.keys()] + cmd_fmt = ( + "edm plumbing remove-package --environment {environment} --force " + ) + commands = [ + cmd_fmt + dependency for dependency in source_dependencies.keys() + ] execute(commands, parameters) source_pkgs = source_dependencies.values() # Without the --no-dependencies flag such that new dependencies on @@ -281,7 +285,9 @@ def install(runtime, toolkit, environment, editable, source): "python -m pip install --force-reinstall {pkg}".format(pkg=pkg) for pkg in source_pkgs ] - commands = ["edm run -e {environment} -- " + command for command in commands] + commands = [ + "edm run -e {environment} -- " + command for command in commands + ] execute(commands, parameters) # Always install local source again with no dependencies @@ -303,7 +309,7 @@ def install(runtime, toolkit, environment, editable, source): @click.option('--toolkit', default=DEFAULT_TOOLKIT) @click.option('--environment', default=None) def shell(runtime, toolkit, environment): - """ Create a shell into the EDM development environment + """Create a shell into the EDM development environment (aka 'activate' it). """ @@ -319,9 +325,7 @@ def shell(runtime, toolkit, environment): @click.option('--toolkit', default=DEFAULT_TOOLKIT) @click.option('--environment', default=None) def test(runtime, toolkit, environment): - """ Run the test suite in a given environment with the specified toolkit. - - """ + """Run the test suite in a given environment with the specified toolkit.""" parameters = get_parameters(runtime, toolkit, environment) environ = environment_vars.get(toolkit, {}).copy() environ['PYTHONUNBUFFERED'] = "1" @@ -351,13 +355,12 @@ def test(runtime, toolkit, environment): @click.option('--toolkit', default=DEFAULT_TOOLKIT) @click.option('--environment', default=None) def cleanup(runtime, toolkit, environment): - """ Remove a development environment. - - """ + """Remove a development environment.""" parameters = get_parameters(runtime, toolkit, environment) commands = [ "edm run -e {environment} -- python setup.py clean", - "edm environments remove {environment} --purge -y"] + "edm environments remove {environment} --purge -y", + ] click.echo("Cleaning up environment '{environment}'".format(**parameters)) execute(commands, parameters) click.echo('Done cleanup') @@ -367,9 +370,7 @@ def cleanup(runtime, toolkit, environment): @click.option('--runtime', default=DEFAULT_RUNTIME) @click.option('--toolkit', default=DEFAULT_TOOLKIT) def test_clean(runtime, toolkit): - """ Run tests in a clean environment, cleaning up afterwards - - """ + """Run tests in a clean environment, cleaning up afterwards""" args = ['--toolkit={}'.format(toolkit), '--runtime={}'.format(runtime)] try: install(args=args, standalone_mode=False) @@ -383,12 +384,9 @@ def test_clean(runtime, toolkit): @click.option('--toolkit', default=DEFAULT_TOOLKIT) @click.option('--environment', default=None) def update(runtime, toolkit, environment): - """ Update/Reinstall package into environment. - - """ + """Update/Reinstall package into environment.""" parameters = get_parameters(runtime, toolkit, environment) - commands = [ - "edm run -e {environment} -- python setup.py install"] + commands = ["edm run -e {environment} -- python setup.py install"] click.echo("Re-installing in '{environment}'".format(**parameters)) execute(commands, parameters) click.echo('Done update') @@ -399,17 +397,18 @@ def update(runtime, toolkit, environment): @click.option('--toolkit', default=DEFAULT_TOOLKIT) @click.option('--environment', default=None) def docs(runtime, toolkit, environment): - """ Autogenerate documentation - - """ + """Autogenerate documentation""" parameters = get_parameters(runtime, toolkit, environment) packages = ' '.join(doc_dependencies) ignore = " ".join(doc_ignore) commands = [ "edm install -y -e {environment} " + packages, ] - click.echo("Installing documentation tools in '{environment}'".format( - **parameters)) + click.echo( + "Installing documentation tools in '{environment}'".format( + **parameters + ) + ) execute(commands, parameters) click.echo('Done installing documentation tools') @@ -424,9 +423,7 @@ def docs(runtime, toolkit, environment): "-e " "-M " "--no-toc " - "-o " + output_path - + " traitsui " - + ignore + "-o " + output_path + " traitsui " + ignore ] execute(commands, parameters) click.echo("Done regenerating API docs") @@ -438,7 +435,9 @@ def docs(runtime, toolkit, environment): "source " "build/html" ) - click.echo("Building documentation in '{environment}'".format(**parameters)) + click.echo( + "Building documentation in '{environment}'".format(**parameters) + ) try: execute([command], parameters) finally: @@ -448,15 +447,13 @@ def docs(runtime, toolkit, environment): @cli.command() def test_all(): - """ Run test_clean across all supported environment combinations. - - """ + """Run test_clean across all supported environment combinations.""" failed_command = False for runtime, toolkits in supported_combinations.items(): for toolkit in toolkits: args = [ '--toolkit={}'.format(toolkit), - '--runtime={}'.format(runtime) + '--runtime={}'.format(runtime), ] try: test_clean(args, standalone_mode=True) @@ -478,9 +475,7 @@ def test_all(): help="Use strict configuration for flake8 [default: --not-strict]", ) def flake8(runtime, toolkit, environment, strict): - """ Run a flake8 check in a given environment. - - """ + """Run a flake8 check in a given environment.""" parameters = get_parameters(runtime, toolkit, environment) config = "" if strict: @@ -494,7 +489,7 @@ def flake8(runtime, toolkit, environment, strict): @cli.group("changelog") @click.pass_context def changelog(ctx): - """ Group of commands related to creating changelog.""" + """Group of commands related to creating changelog.""" ctx.obj = { # Mapping from news fragment type to their description in @@ -514,17 +509,15 @@ def changelog(ctx): @changelog.command("create") @click.pass_context def create_news_fragment(ctx): - """ Create a news fragment for your PR.""" + """Create a news fragment for your PR.""" pr_number = click.prompt('Please enter the PR number', type=int) type_ = click.prompt( "Choose a fragment type:", - type=click.Choice(ctx.obj["type_to_description"]) + type=click.Choice(ctx.obj["type_to_description"]), ) - filepath = os.path.join( - NEWS_FRAGMENT_DIR, f"{pr_number}.{type_}.rst" - ) + filepath = os.path.join(NEWS_FRAGMENT_DIR, f"{pr_number}.{type_}.rst") if os.path.exists(filepath): click.echo("FAILED: File {} already exists.".format(filepath)) @@ -546,7 +539,7 @@ def create_news_fragment(ctx): @changelog.command("build") @click.pass_context def build_changelog(ctx): - """ Build Changelog created from all the news fragments.""" + """Build Changelog created from all the news fragments.""" # This is a rather simple first-cut generation of the changelog. # It removes the laborious concatenation, but the end results might # still require some tweaking. @@ -582,9 +575,7 @@ def build_changelog(ctx): click.echo(f"Changelog is updated. Please review it at {CHANGELOG_PATH}") # Optionally clean up collected news fragments. - should_clean = click.confirm( - "Do you want to remove the news fragments?" - ) + should_clean = click.confirm("Do you want to remove the news fragments?") if should_clean: for file_path in handled_file_paths: os.remove(file_path) @@ -597,25 +588,35 @@ def build_changelog(ctx): click.echo("Done") + # ---------------------------------------------------------------------------- # Utility routines # ---------------------------------------------------------------------------- + def get_parameters(runtime, toolkit, environment): - """ Set up parameters dictionary for format() substitution """ - parameters = {'runtime': runtime, 'toolkit': toolkit, 'environment': environment} + """Set up parameters dictionary for format() substitution""" + parameters = { + 'runtime': runtime, + 'toolkit': toolkit, + 'environment': environment, + } if toolkit not in supported_combinations[runtime]: - msg = ("Python {runtime} and toolkit {toolkit} not supported by " + - "test environments") + msg = ( + "Python {runtime} and toolkit {toolkit} not supported by " + + "test environments" + ) raise RuntimeError(msg.format(**parameters)) if environment is None: - parameters['environment'] = 'traitsui-test-{runtime}-{toolkit}'.format(**parameters) + parameters['environment'] = 'traitsui-test-{runtime}-{toolkit}'.format( + **parameters + ) return parameters @contextmanager def do_in_tempdir(files=(), capture_files=()): - """ Create a temporary directory, cleaning up after done. + """Create a temporary directory, cleaning up after done. Creates the temporary directory, and changes into it. On exit returns to original directory and removes temporary dir. @@ -652,8 +653,9 @@ def execute(commands, parameters): for command in commands: click.echo("[EXECUTING] {}".format(command.format(**parameters))) try: - subprocess.check_call([arg.format(**parameters) - for arg in command.split()]) + subprocess.check_call( + [arg.format(**parameters) for arg in command.split()] + ) except subprocess.CalledProcessError as exc: click.echo(str(exc)) sys.exit(1) diff --git a/examples/tutorials/doc_examples/examples/override_editor.py b/examples/tutorials/doc_examples/examples/override_editor.py index d5c65c346..3161fa9a3 100644 --- a/examples/tutorials/doc_examples/examples/override_editor.py +++ b/examples/tutorials/doc_examples/examples/override_editor.py @@ -8,8 +8,7 @@ class Polygon(HasTraits): - line_color = Trait(Color((0, 0, 0)), - editor=ColorEditor()) + line_color = Trait(Color((0, 0, 0)), editor=ColorEditor()) Polygon().configure_traits() diff --git a/examples/tutorials/doc_examples/examples/view_multi_object.py b/examples/tutorials/doc_examples/examples/view_multi_object.py index 924eea810..6692a274a 100644 --- a/examples/tutorials/doc_examples/examples/view_multi_object.py +++ b/examples/tutorials/doc_examples/examples/view_multi_object.py @@ -18,15 +18,13 @@ class Company(HasTraits): # Standalone View object referencing objects in the UI context -employee_view = View('e.first_name', 'e.last_name', - 'c.company_name') +employee_view = View('e.first_name', 'e.last_name', 'c.company_name') bill = Person(first_name='Bill') acme = Company(company_name='Acme Products') class TraitApp(wx.App): - def __init__(self, obj1, obj2, view): self.obj1 = obj1 self.obj2 = obj2 diff --git a/examples/tutorials/doc_examples/examples/view_standalone.py b/examples/tutorials/doc_examples/examples/view_standalone.py index 85ebc27a2..74f16975c 100644 --- a/examples/tutorials/doc_examples/examples/view_standalone.py +++ b/examples/tutorials/doc_examples/examples/view_standalone.py @@ -23,7 +23,6 @@ class Person(HasTraits): class TraitApp(wx.App): - def __init__(self, object, view): self.object = object self.view = view diff --git a/examples/tutorials/traitsui_4.0/buttons.py b/examples/tutorials/traitsui_4.0/buttons.py index a0c545987..c6eef94d8 100644 --- a/examples/tutorials/traitsui_4.0/buttons.py +++ b/examples/tutorials/traitsui_4.0/buttons.py @@ -1,7 +1,7 @@ # Copyright (c) 2007, Enthought, Inc. # License: BSD Style. -#--(View Default Button Changes)------------------------------------------ +# --(View Default Button Changes)------------------------------------------ """ View Default Button Changes =========================== @@ -45,12 +45,12 @@ removed from the **View** class. """ -#---------------------------------------------------------------- +# ---------------------------------------------------------------- from traits.api import Float, HasTraits, Property from traitsui.api import Item, View -#--[Adder Class]---------------------------------------------------------- +# --[Adder Class]---------------------------------------------------------- # Click the run button to view the pop-up dialog... @@ -67,13 +67,14 @@ class Adder(HasTraits): '_', Item('sum', style='readonly'), title='Adding Machine', - buttons=['OK'] + buttons=['OK'], ) def _get_sum(self): - return (self.value_1 + self.value_2) + return self.value_1 + self.value_2 -#---------------------------------------------------------------- + +# ---------------------------------------------------------------- popup = Adder() diff --git a/examples/tutorials/traitsui_4.0/deferred.py b/examples/tutorials/traitsui_4.0/deferred.py index 31b593b4a..cdca4217d 100644 --- a/examples/tutorials/traitsui_4.0/deferred.py +++ b/examples/tutorials/traitsui_4.0/deferred.py @@ -1,7 +1,7 @@ # Copyright (c) 2007, Enthought, Inc. # License: BSD Style. -#--(Deferred UI Notifications)-------------------------------------------- +# --(Deferred UI Notifications)-------------------------------------------- """ Deferred UI Notifications ========================= @@ -32,12 +32,12 @@ number of screen updates. """ -#---------------------------------------------------------------- +# ---------------------------------------------------------------- from traits.api import Button, HasTraits, Int from traitsui.api import Item, View -#--[Count Class]---------------------------------------------------------- +# --[Count Class]---------------------------------------------------------- class Count(HasTraits): @@ -45,10 +45,7 @@ class Count(HasTraits): count = Int() go = Button('Count') - view = View( - Item('count', style='readonly'), - Item('go', show_label=False) - ) + view = View(Item('count', style='readonly'), Item('go', show_label=False)) def _go_changed(self): # Even though the 'count' trait (which is visible in the UI) is being @@ -60,7 +57,8 @@ def _go_changed(self): for i in range(10000): self.count += 1 -#--------------------------------------------------------------- + +# --------------------------------------------------------------- demo = Count() diff --git a/examples/tutorials/traitsui_4.0/editors/animated_gif.py b/examples/tutorials/traitsui_4.0/editors/animated_gif.py index 05e1185f8..2631830d0 100644 --- a/examples/tutorials/traitsui_4.0/editors/animated_gif.py +++ b/examples/tutorials/traitsui_4.0/editors/animated_gif.py @@ -1,4 +1,4 @@ -#--(Animated GIF Editor)-------------------------------------------------- +# --(Animated GIF Editor)-------------------------------------------------- """ Animated GIF Editor =================== @@ -19,21 +19,17 @@ provided by this editor, it is display only. """ -#--[Imports]-------------------------------------------------------------- +# --[Imports]-------------------------------------------------------------- -from os.path \ - import join, dirname +from os.path import join, dirname -from traits.api \ - import HasTraits, File, Bool, Int +from traits.api import HasTraits, File, Bool, Int -from traitsui.api \ - import View, VGroup, HGroup, Item, EnumEditor +from traitsui.api import View, VGroup, HGroup, Item, EnumEditor -from traitsui.wx.animated_gif_editor \ - import AnimatedGIFEditor +from traitsui.wx.animated_gif_editor import AnimatedGIFEditor -#--[Setup]---------------------------------------------------------------- +# --[Setup]---------------------------------------------------------------- # Some sample animated GIF files: import traitsui as ui @@ -44,10 +40,10 @@ files = [ join(base_path, 'logo_64x64.gif'), join(base_path, 'logo_48x48.gif'), - join(base_path, 'logo_32x32.gif') + join(base_path, 'logo_32x32.gif'), ] -#--[AnimatedGIFDemo Class]------------------------------------------------ +# --[AnimatedGIFDemo Class]------------------------------------------------ class AnimatedGIFDemo(HasTraits): @@ -62,22 +58,24 @@ class AnimatedGIFDemo(HasTraits): view = View( VGroup( HGroup( - Item('gif_file', - editor=AnimatedGIFEditor(playing='playing'), - show_label=False), + Item( + 'gif_file', + editor=AnimatedGIFEditor(playing='playing'), + show_label=False, + ), Item('playing'), ), '_', - Item('gif_file', - label='GIF File', - editor=EnumEditor(values=files) - ) + Item( + 'gif_file', label='GIF File', editor=EnumEditor(values=files) + ), ), title='Animated GIF Demo', resizable=True, - buttons=['OK'] + buttons=['OK'], ) -#--------------------------------------------------------------- + +# --------------------------------------------------------------- demo = AnimatedGIFDemo() diff --git a/examples/tutorials/traitsui_4.0/editors/flash.py b/examples/tutorials/traitsui_4.0/editors/flash.py index 7d702397b..2dd0c5f18 100644 --- a/examples/tutorials/traitsui_4.0/editors/flash.py +++ b/examples/tutorials/traitsui_4.0/editors/flash.py @@ -1,4 +1,4 @@ -#--(Flash Editor (Windows Only))------------------------------------------ +# --(Flash Editor (Windows Only))------------------------------------------ """ Flash Editor (Windows Only) =========================== @@ -21,18 +21,15 @@ the Flash file defined by the new value of the trait. """ -#--[Imports]-------------------------------------------------------------- +# --[Imports]-------------------------------------------------------------- -from traitsui.wx.extra.windows.flash_editor \ - import FlashEditor +from traitsui.wx.extra.windows.flash_editor import FlashEditor -from traits.api \ - import HasTraits, Enum +from traits.api import HasTraits, Enum -from traitsui.api \ - import View, HGroup, Item +from traitsui.api import View, HGroup, Item -#--[FlashDemo Class]------------------------------------------------------ +# --[FlashDemo Class]------------------------------------------------------ class FlashDemo(HasTraits): @@ -48,20 +45,17 @@ class FlashDemo(HasTraits): 'http://www.ianag.com/arcade/swf/f-1416.swf', 'http://www.ianag.com/arcade/swf/mah_jongg.swf', 'http://www.ianag.com/arcade/swf/game_e4fe4e55fedc2f502be627ee6df716c5.swf', - 'http://www.ianag.com/arcade/swf/rhumb.swf') + 'http://www.ianag.com/arcade/swf/rhumb.swf', + ) # The view to display: view = View( - HGroup( - Item('flash', label='Pick a game to play') - ), + HGroup(Item('flash', label='Pick a game to play')), '_', - Item('flash', - show_label=False, - editor=FlashEditor() - ) + Item('flash', show_label=False, editor=FlashEditor()), ) -#--------------------------------------------------------------- + +# --------------------------------------------------------------- demo = FlashDemo() diff --git a/examples/tutorials/traitsui_4.0/editors/ie_html.py b/examples/tutorials/traitsui_4.0/editors/ie_html.py index bd7f1fc69..7fc520131 100644 --- a/examples/tutorials/traitsui_4.0/editors/ie_html.py +++ b/examples/tutorials/traitsui_4.0/editors/ie_html.py @@ -1,4 +1,4 @@ -#--(Internet Explorer HTML Editor (Windows Only))------------------------- +# --(Internet Explorer HTML Editor (Windows Only))------------------------- """ Internet Explorer HTML Editor (Windows Only) ============================================ @@ -76,18 +76,23 @@ the browser to display the page defined by the new value of the trait. """ -#--[Imports]-------------------------------------------------------------- +# --[Imports]-------------------------------------------------------------- -from traitsui.wx.extra.windows.ie_html_editor \ - import IEHTMLEditor +from traitsui.wx.extra.windows.ie_html_editor import IEHTMLEditor -from traits.api \ - import HasTraits, Str, List, Button +from traits.api import HasTraits, Str, List, Button -from traitsui.api \ - import View, VGroup, HGroup, Item, TextEditor, ListEditor, spring +from traitsui.api import ( + View, + VGroup, + HGroup, + Item, + TextEditor, + ListEditor, + spring, +) -#--[WebPage Class]-------------------------------------------------------- +# --[WebPage Class]-------------------------------------------------------- class WebPage(HasTraits): @@ -111,21 +116,35 @@ class WebPage(HasTraits): # The view to display: view = View( - HGroup('back', 'forward', 'home', 'stop', 'refresh', 'search', '_', - Item('status', style='readonly'), - show_labels=False - ), - Item('url', - show_label=False, - editor=IEHTMLEditor( - home='home', back='back', - forward='forward', stop='stop', - refresh='refresh', search='search', - title='title', status='status') - ) + HGroup( + 'back', + 'forward', + 'home', + 'stop', + 'refresh', + 'search', + '_', + Item('status', style='readonly'), + show_labels=False, + ), + Item( + 'url', + show_label=False, + editor=IEHTMLEditor( + home='home', + back='back', + forward='forward', + stop='stop', + refresh='refresh', + search='search', + title='title', + status='status', + ), + ), ) -#--[InternetExplorerDemo Class]------------------------------------------- + +# --[InternetExplorerDemo Class]------------------------------------------- class InternetExplorerDemo(HasTraits): @@ -139,27 +158,32 @@ class InternetExplorerDemo(HasTraits): # The view to display: view = View( VGroup( - Item('url', - label='Location', - editor=TextEditor(auto_set=False, enter_set=True) - ) + Item( + 'url', + label='Location', + editor=TextEditor(auto_set=False, enter_set=True), + ) + ), + Item( + 'pages', + show_label=False, + style='custom', + editor=ListEditor( + use_notebook=True, + deletable=True, + dock_style='tab', + export='DockWindowShell', + page_name='.title', + ), ), - Item('pages', - show_label=False, - style='custom', - editor=ListEditor(use_notebook=True, - deletable=True, - dock_style='tab', - export='DockWindowShell', - page_name='.title') - ) ) # Event handlers: def _url_changed(self, url): self.pages.append(WebPage(url=url.strip())) -#--(Demo Notes)----------------------------------------------------------- + +# --(Demo Notes)----------------------------------------------------------- """ Demo Notes @@ -171,8 +195,11 @@ def _url_changed(self, url): - Then, just for fun, try dragging it back... """ -#--------------------------------------------------------------- +# --------------------------------------------------------------- demo = InternetExplorerDemo( - pages=[WebPage(url='http://code.enthought.com/traits/'), - WebPage(url='http://dmorrill.com')]) + pages=[ + WebPage(url='http://code.enthought.com/traits/'), + WebPage(url='http://dmorrill.com'), + ] +) diff --git a/examples/tutorials/traitsui_4.0/editors/led.py b/examples/tutorials/traitsui_4.0/editors/led.py index aed843647..56c5f13b0 100644 --- a/examples/tutorials/traitsui_4.0/editors/led.py +++ b/examples/tutorials/traitsui_4.0/editors/led.py @@ -1,4 +1,4 @@ -#--(LED Editor)----------------------------------------------------------- +# --(LED Editor)----------------------------------------------------------- """ LED Editor ========== @@ -23,24 +23,19 @@ or float value. """ -#--[Imports]-------------------------------------------------------------- +# --[Imports]-------------------------------------------------------------- -from threading \ - import Thread +from threading import Thread -from time \ - import sleep +from time import sleep -from traits.api \ - import HasTraits, Instance, Int, Float, Bool +from traits.api import HasTraits, Instance, Int, Float, Bool -from traitsui.api \ - import View, Item, HGroup, Handler, UIInfo, spring +from traitsui.api import View, Item, HGroup, Handler, UIInfo, spring -from traitsui.wx.extra.led_editor \ - import LEDEditor +from traitsui.wx.extra.led_editor import LEDEditor -#--[LEDDemoHandler Class]------------------------------------------------- +# --[LEDDemoHandler Class]------------------------------------------------- # Handler class for the LEDDemo class view: @@ -64,16 +59,17 @@ def init(self, info): def closed(self, info, is_ok): self.running = False while self.alive: - sleep(.05) + sleep(0.05) def _update_counter(self): while self.running: self.info.object.counter1 += 1 - self.info.object.counter2 += .001 - sleep(.01) + self.info.object.counter2 += 0.001 + sleep(0.01) self.alive = False -#--[LEDDemo Class]-------------------------------------------------------- + +# --[LEDDemo Class]-------------------------------------------------------- # The main demo class: @@ -88,57 +84,66 @@ class LEDDemo(HasTraits): # The traits view: view = View( - Item('counter1', - label='Left aligned', - editor=LEDEditor(alignment='left') - ), - Item('counter1', - label='Center aligned', - editor=LEDEditor(alignment='center') - ), - Item('counter1', - label='Right aligned', - editor=LEDEditor() # default = 'right' aligned - ), - Item('counter2', - label='Float value', - editor=LEDEditor(format_str='%.3f') - ), + Item( + 'counter1', + label='Left aligned', + editor=LEDEditor(alignment='left'), + ), + Item( + 'counter1', + label='Center aligned', + editor=LEDEditor(alignment='center'), + ), + Item( + 'counter1', + label='Right aligned', + editor=LEDEditor(), # default = 'right' aligned + ), + Item( + 'counter2', + label='Float value', + editor=LEDEditor(format_str='%.3f'), + ), '_', HGroup( - Item('counter1', - label='Left', - height=-40, - width=120, - editor=LEDEditor(alignment='left') - ), + Item( + 'counter1', + label='Left', + height=-40, + width=120, + editor=LEDEditor(alignment='left'), + ), spring, - Item('counter1', - label='Center', - height=-40, - width=120, - editor=LEDEditor(alignment='center') - ), + Item( + 'counter1', + label='Center', + height=-40, + width=120, + editor=LEDEditor(alignment='center'), + ), spring, - Item('counter1', - label='Right', - height=-40, - width=120, - editor=LEDEditor() # default = 'right' aligned - ), + Item( + 'counter1', + label='Right', + height=-40, + width=120, + editor=LEDEditor(), # default = 'right' aligned + ), spring, - Item('counter2', - label='Float', - height=-40, - width=120, - editor=LEDEditor(format_str='%.3f') - ) + Item( + 'counter2', + label='Float', + height=-40, + width=120, + editor=LEDEditor(format_str='%.3f'), + ), ), title='LED Editor Demo', buttons=['OK'], - handler=LEDDemoHandler + handler=LEDDemoHandler, ) -#--------------------------------------------------------------- + +# --------------------------------------------------------------- demo = LEDDemo() diff --git a/examples/tutorials/traitsui_4.0/editors/tabular_editor/numpy_array.py b/examples/tutorials/traitsui_4.0/editors/tabular_editor/numpy_array.py index 3bae0501e..548ca634a 100644 --- a/examples/tutorials/traitsui_4.0/editors/tabular_editor/numpy_array.py +++ b/examples/tutorials/traitsui_4.0/editors/tabular_editor/numpy_array.py @@ -1,4 +1,4 @@ -#--(NumPy Array Example)-------------------------------------------------- +# --(NumPy Array Example)-------------------------------------------------- """ This lesson demonstrates how the **TabularEditor** can be used to display (large) NumPy arrays. In this example, the array consists of 100,000 random 3D @@ -20,41 +20,32 @@ cube's center (the *index_image* property). """ -#---------------------------------------------------------------- +# ---------------------------------------------------------------- -from os.path \ - import join, dirname +from os.path import join, dirname -from numpy \ - import sqrt +from numpy import sqrt -from numpy.random \ - import random +from numpy.random import random -from traits.api \ - import HasTraits, Property, Array +from traits.api import HasTraits, Property, Array -from traitsui.api \ - import View, Item, TabularEditor +from traitsui.api import View, Item, TabularEditor -from traitsui.tabular_adapter \ - import TabularAdapter +from traitsui.tabular_adapter import TabularAdapter -from traitsui.menu \ - import NoButtons +from traitsui.menu import NoButtons -from pyface.image_resource \ - import ImageResource +from pyface.image_resource import ImageResource -#-------------------------------------------------------------- +# -------------------------------------------------------------- # Necessary because of the dynamic way in which the demos are loaded: import traitsui.api -search_path = [join(dirname(traitsui.api.__file__), - 'demo', 'Advanced')] +search_path = [join(dirname(traitsui.api.__file__), 'demo', 'Advanced')] -#--[Tabular Adapter Definition]------------------------------------------- +# --[Tabular Adapter Definition]------------------------------------------- class ArrayAdapter(TabularAdapter): @@ -76,14 +67,15 @@ def _get_index_image(self): return 'red_flag' return None -#--[Tabular Editor Definition]-------------------------------------------- + +# --[Tabular Editor Definition]-------------------------------------------- tabular_editor = TabularEditor( adapter=ArrayAdapter(), - images=[ImageResource('red_flag', search_path=search_path)] + images=[ImageResource('red_flag', search_path=search_path)], ) -#--[ShowArray Class]------------------------------------------------------ +# --[ShowArray Class]------------------------------------------------------ class ShowArray(HasTraits): @@ -96,9 +88,10 @@ class ShowArray(HasTraits): width=0.3, height=0.8, resizable=True, - buttons=NoButtons + buttons=NoButtons, ) -#--[Example Code*]-------------------------------------------------------- + +# --[Example Code*]-------------------------------------------------------- demo = ShowArray(data=random((100000, 3))) diff --git a/examples/tutorials/traitsui_4.0/editors/tabular_editor/python_source_browser.py b/examples/tutorials/traitsui_4.0/editors/tabular_editor/python_source_browser.py index 766aafec2..f0be88b76 100644 --- a/examples/tutorials/traitsui_4.0/editors/tabular_editor/python_source_browser.py +++ b/examples/tutorials/traitsui_4.0/editors/tabular_editor/python_source_browser.py @@ -1,4 +1,4 @@ -#--(Python Source Browser Example)---------------------------------------- +# --(Python Source Browser Example)---------------------------------------- """ This lesson shows a combination of the **DirectoryEditor**, the **TabularEditor** and the **CodeEditor** used together to create a very simple @@ -35,42 +35,52 @@ related trait and property definitions in the adapter class itself. """ -#---------------------------------------------------------------- +# ---------------------------------------------------------------- import traits import traitsui import wx -from time \ - import localtime, strftime +from time import localtime, strftime -from os \ - import listdir +from os import listdir -from os.path \ - import getsize, getmtime, isfile, join, splitext, basename, dirname +from os.path import ( + getsize, + getmtime, + isfile, + join, + splitext, + basename, + dirname, +) -from traits.api \ - import HasPrivateTraits, Str, Float, List, Directory, File, Code, \ - Instance, Property, cached_property +from traits.api import ( + HasPrivateTraits, + Str, + Float, + List, + Directory, + File, + Code, + Instance, + Property, + cached_property, +) -from traitsui.api \ - import View, Item, HSplit, VSplit, TabularEditor +from traitsui.api import View, Item, HSplit, VSplit, TabularEditor -from traitsui.tabular_adapter \ - import TabularAdapter +from traitsui.tabular_adapter import TabularAdapter -from pyface.image_resource \ - import ImageResource +from pyface.image_resource import ImageResource -#-------------------------------------------------------------- +# -------------------------------------------------------------- # Necessary because of the dynamic way in which the demos are loaded: -search_path = [join(dirname(traitsui.api.__file__), - 'demo', 'Applications')] +search_path = [join(dirname(traitsui.api.__file__), 'demo', 'Applications')] -#--[FileInfo Class]------------------------------------------------------- +# --[FileInfo Class]------------------------------------------------------- class FileInfo(HasPrivateTraits): @@ -91,24 +101,25 @@ def _get_size(self): @cached_property def _get_time(self): - return strftime('%I:%M:%S %p', - localtime(getmtime(self.file_name))) + return strftime('%I:%M:%S %p', localtime(getmtime(self.file_name))) @cached_property def _get_date(self): - return strftime('%m/%d/%Y', - localtime(getmtime(self.file_name))) + return strftime('%m/%d/%Y', localtime(getmtime(self.file_name))) + -#--[FileInfoAdapter Class]------------------------------------------------ +# --[FileInfoAdapter Class]------------------------------------------------ class FileInfoAdapter(TabularAdapter): - columns = [('File Name', 'name'), - ('Size', 'size'), - ('', 'big'), - ('Time', 'time'), - ('Date', 'date')] + columns = [ + ('File Name', 'name'), + ('Size', 'size'), + ('', 'big'), + ('Time', 'time'), + ('Date', 'date'), + ] even_bg_color = wx.Colour(201, 223, 241) font = 'Courier 10' @@ -126,18 +137,21 @@ def _get_big_image(self): return (None, 'blue_ball')[size > 16384] -#--[Tabular Editor Definition]-------------------------------------------- + +# --[Tabular Editor Definition]-------------------------------------------- tabular_editor = TabularEditor( editable=False, selected='file_info', adapter=FileInfoAdapter(), operations=[], - images=[ImageResource('blue_ball', search_path=search_path), - ImageResource('red_ball', search_path=search_path)] + images=[ + ImageResource('blue_ball', search_path=search_path), + ImageResource('red_ball', search_path=search_path), + ], ) -#--[PythonBrowser Class]-------------------------------------------------- +# --[PythonBrowser Class]-------------------------------------------------- class PythonBrowser(HasPrivateTraits): @@ -153,21 +167,23 @@ class PythonBrowser(HasPrivateTraits): VSplit( Item('files', editor=tabular_editor), Item('code', style='readonly'), - show_labels=False), - show_labels=False + show_labels=False, + ), + show_labels=False, ), resizable=True, width=0.75, - height=0.75 + height=0.75, ) - #-- Event Handlers ------------------------------------------------------- + # -- Event Handlers ------------------------------------------------------- def _dir_changed(self, dir): - self.files = [FileInfo(file_name=join(dir, name)) - for name in listdir(dir) - if ((splitext(name)[1] == '.py') and - isfile(join(dir, name)))] + self.files = [ + FileInfo(file_name=join(dir, name)) + for name in listdir(dir) + if ((splitext(name)[1] == '.py') and isfile(join(dir, name))) + ] def _file_info_changed(self, file_info): fh = None @@ -180,6 +196,7 @@ def _file_info_changed(self, file_info): if fh is not None: fh.close() -#--[Example*]------------------------------------------------------------- + +# --[Example*]------------------------------------------------------------- demo = PythonBrowser(dir=dirname(traits.api.__file__)) diff --git a/examples/tutorials/traitsui_4.0/editors/tabular_editor/sm_person_example.py b/examples/tutorials/traitsui_4.0/editors/tabular_editor/sm_person_example.py index b730bd2a9..cf27dcb4b 100644 --- a/examples/tutorials/traitsui_4.0/editors/tabular_editor/sm_person_example.py +++ b/examples/tutorials/traitsui_4.0/editors/tabular_editor/sm_person_example.py @@ -1,4 +1,4 @@ -#--(Single/Married Person Example)---------------------------------------- +# --(Single/Married Person Example)---------------------------------------- """ This lesson contains a tabular editor example based upon the **Person** and **MarriedPerson** example presented in the *Tabular Editor Introduction* @@ -41,39 +41,31 @@ right arrow keys. """ -#---------------------------------------------------------------- +# ---------------------------------------------------------------- -from os.path \ - import join, dirname +from os.path import join, dirname -from random \ - import randint, choice, shuffle +from random import randint, choice, shuffle -from traits.api \ - import HasTraits, Str, Int, List, Instance, Property, Constant +from traits.api import HasTraits, Str, Int, List, Instance, Property, Constant -from traitsui.api \ - import View, Group, Item, Margin, TabularEditor, Color +from traitsui.api import View, Group, Item, Margin, TabularEditor, Color -from traitsui.tabular_adapter \ - import TabularAdapter +from traitsui.tabular_adapter import TabularAdapter -from traitsui.menu \ - import NoButtons +from traitsui.menu import NoButtons -from pyface.image_resource \ - import ImageResource +from pyface.image_resource import ImageResource -#-------------------------------------------------------------- +# -------------------------------------------------------------- # Necessary because of the dynamic way in which the demos are loaded: import traitsui.api -search_path = [join(dirname(traitsui.api.__file__), - 'demo', 'Advanced')] +search_path = [join(dirname(traitsui.api.__file__), 'demo', 'Advanced')] -#--[Person Class]--------------------------------------------------------- +# --[Person Class]--------------------------------------------------------- class Person(HasTraits): @@ -82,22 +74,26 @@ class Person(HasTraits): address = Str() age = Int() -#--[MarriedPerson Class]-------------------------------------------------- + +# --[MarriedPerson Class]-------------------------------------------------- class MarriedPerson(Person): partner = Instance(Person) -#--[Tabular Adapter Definition]------------------------------------------- + +# --[Tabular Adapter Definition]------------------------------------------- class ReportAdapter(TabularAdapter): - columns = [('Name', 'name'), - ('Age', 'age'), - ('Address', 'address'), - ('Spouse', 'spouse')] + columns = [ + ('Name', 'name'), + ('Age', 'age'), + ('Address', 'address'), + ('Spouse', 'spouse'), + ] font = 'Courier 10' age_alignment = Constant('right') @@ -114,7 +110,8 @@ def _get_MarriedPerson_age_image(self): def _get_MarriedPerson_spouse_text(self): return self.item.partner.name -#--[Tabular Editor Definition]-------------------------------------------- + +# --[Tabular Editor Definition]-------------------------------------------- tabular_editor = TabularEditor( adapter=ReportAdapter(), @@ -122,7 +119,7 @@ def _get_MarriedPerson_spouse_text(self): images=[ImageResource('red_flag', search_path=search_path)], ) -#--[Report Class]--------------------------------------------------------- +# --[Report Class]--------------------------------------------------------- class Report(HasTraits): @@ -139,11 +136,11 @@ class Report(HasTraits): width=0.60, height=0.75, resizable=True, - buttons=NoButtons + buttons=NoButtons, ) -#-------------------------------------------------------- +# -------------------------------------------------------- male_names = [ 'Michael', @@ -181,7 +178,8 @@ class Report(HasTraits): 'Walter', 'Woodrow', 'Dylan', - 'Elmer'] + 'Elmer', +] female_names = [ 'Leah', @@ -219,7 +217,8 @@ class Report(HasTraits): 'Jennifer', 'Rita', 'Rena', - 'Rianna'] + 'Rianna', +] all_names = male_names + female_names @@ -228,129 +227,152 @@ class Report(HasTraits): any_name = lambda: choice(all_names) age = lambda: randint(15, 72) -family_name = lambda: choice(['Jones', - 'Smith', - 'Thompson', - 'Hayes', - 'Thomas', - 'Boyle', - "O'Reilly", - 'Lebowski', - 'Lennon', - 'Starr', - 'McCartney', - 'Harrison', - 'Harrelson', - 'Steinbeck', - 'Rand', - 'Hemingway', - 'Zhivago', - 'Clemens', - 'Heinlien', - 'Farmer', - 'Niven', - 'Van Vogt', - 'Sturbridge', - 'Washington', - 'Adams', - 'Bush', - 'Kennedy', - 'Ford', - 'Lincoln', - 'Jackson', - 'Johnson', - 'Eisenhower', - 'Truman', - 'Roosevelt', - 'Wilson', - 'Coolidge', - 'Mack', - 'Moon', - 'Monroe', - 'Springsteen', - 'Rigby', - "O'Neil", - 'Philips', - 'Clinton', - 'Clapton', - 'Santana', - 'Midler', - 'Flack', - 'Conner', - 'Bond', - 'Seinfeld', - 'Costanza', - 'Kramer', - 'Falk', - 'Moore', - 'Cramdon', - 'Baird', - 'Baer', - 'Spears', - 'Simmons', - 'Roberts', - 'Michaels', - 'Stuart', - 'Montague', - 'Miller']) - -address = lambda: '%d %s %s' % (randint(11, - 999), - choice(['Spring', - 'Summer', - 'Moonlight', - 'Winding', - 'Windy', - 'Whispering', - 'Falling', - 'Roaring', - 'Hummingbird', - 'Mockingbird', - 'Bluebird', - 'Robin', - 'Babbling', - 'Cedar', - 'Pine', - 'Ash', - 'Maple', - 'Oak', - 'Birch', - 'Cherry', - 'Blossom', - 'Rosewood', - 'Apple', - 'Peach', - 'Blackberry', - 'Strawberry', - 'Starlight', - 'Wilderness', - 'Dappled', - 'Beaver', - 'Acorn', - 'Pecan', - 'Pheasant', - 'Owl']), - choice(['Way', - 'Lane', - 'Boulevard', - 'Street', - 'Drive', - 'Circle', - 'Avenue', - 'Trail'])) - -people = [Person(name='%s %s' % (any_name(), family_name()), - age=age(), - address=address()) for i in range(5000)] - -marrieds = [(MarriedPerson(name='%s %s' % (female_name(), last_name), - age=age(), - address=address), - MarriedPerson(name='%s %s' % (male_name(), last_name), - age=age(), - address=address)) - for last_name, address in - [(family_name(), address()) for i in range(2500)]] +family_name = lambda: choice( + [ + 'Jones', + 'Smith', + 'Thompson', + 'Hayes', + 'Thomas', + 'Boyle', + "O'Reilly", + 'Lebowski', + 'Lennon', + 'Starr', + 'McCartney', + 'Harrison', + 'Harrelson', + 'Steinbeck', + 'Rand', + 'Hemingway', + 'Zhivago', + 'Clemens', + 'Heinlien', + 'Farmer', + 'Niven', + 'Van Vogt', + 'Sturbridge', + 'Washington', + 'Adams', + 'Bush', + 'Kennedy', + 'Ford', + 'Lincoln', + 'Jackson', + 'Johnson', + 'Eisenhower', + 'Truman', + 'Roosevelt', + 'Wilson', + 'Coolidge', + 'Mack', + 'Moon', + 'Monroe', + 'Springsteen', + 'Rigby', + "O'Neil", + 'Philips', + 'Clinton', + 'Clapton', + 'Santana', + 'Midler', + 'Flack', + 'Conner', + 'Bond', + 'Seinfeld', + 'Costanza', + 'Kramer', + 'Falk', + 'Moore', + 'Cramdon', + 'Baird', + 'Baer', + 'Spears', + 'Simmons', + 'Roberts', + 'Michaels', + 'Stuart', + 'Montague', + 'Miller', + ] +) + +address = lambda: '%d %s %s' % ( + randint(11, 999), + choice( + [ + 'Spring', + 'Summer', + 'Moonlight', + 'Winding', + 'Windy', + 'Whispering', + 'Falling', + 'Roaring', + 'Hummingbird', + 'Mockingbird', + 'Bluebird', + 'Robin', + 'Babbling', + 'Cedar', + 'Pine', + 'Ash', + 'Maple', + 'Oak', + 'Birch', + 'Cherry', + 'Blossom', + 'Rosewood', + 'Apple', + 'Peach', + 'Blackberry', + 'Strawberry', + 'Starlight', + 'Wilderness', + 'Dappled', + 'Beaver', + 'Acorn', + 'Pecan', + 'Pheasant', + 'Owl', + ] + ), + choice( + [ + 'Way', + 'Lane', + 'Boulevard', + 'Street', + 'Drive', + 'Circle', + 'Avenue', + 'Trail', + ] + ), +) + +people = [ + Person( + name='%s %s' % (any_name(), family_name()), + age=age(), + address=address(), + ) + for i in range(5000) +] + +marrieds = [ + ( + MarriedPerson( + name='%s %s' % (female_name(), last_name), + age=age(), + address=address, + ), + MarriedPerson( + name='%s %s' % (male_name(), last_name), age=age(), address=address + ), + ) + for last_name, address in [(family_name(), address()) for i in range(2500)] +] for female, male in marrieds: female.partner = male @@ -359,6 +381,6 @@ class Report(HasTraits): shuffle(people) -#--[Example Code*]-------------------------------------------------------- +# --[Example Code*]-------------------------------------------------------- demo = Report(people=people) diff --git a/examples/tutorials/traitsui_4.0/items.py b/examples/tutorials/traitsui_4.0/items.py index 50ea1e538..fa4b21314 100644 --- a/examples/tutorials/traitsui_4.0/items.py +++ b/examples/tutorials/traitsui_4.0/items.py @@ -1,7 +1,7 @@ # Copyright (c) 2007, Enthought, Inc. # License: BSD Style. -#--(Extended Traits UI Item and Editor References)------------------------ +# --(Extended Traits UI Item and Editor References)------------------------ """ Extended Traits UI Item and Editor References ============================================= @@ -82,17 +82,30 @@ model is set up. """ -#---------------------------------------------------------------- +# ---------------------------------------------------------------- from traits.api import ( - Button, HasTraits, Instance, Int, List, Property, Str, cached_property, + Button, + HasTraits, + Instance, + Int, + List, + Property, + Str, + cached_property, ) from traitsui.api import ( - HGroup, Item, ModelView, ObjectColumn, TableEditor, View, VGroup, + HGroup, + Item, + ModelView, + ObjectColumn, + TableEditor, + View, + VGroup, ) -#--[Player Class]--------------------------------------------------------- +# --[Player Class]--------------------------------------------------------- # Define a baseball player: @@ -105,7 +118,8 @@ class Player(HasTraits): # The number of hits the player made this season: hits = Int() -#--[Team Class]----------------------------------------------------------- + +# --[Team Class]----------------------------------------------------------- # Define a baseball team: @@ -122,11 +136,11 @@ class Team(HasTraits): num_players = Property(observe='players') def _get_num_players(self): - """ Implementation of the 'num_players' property. - """ + """Implementation of the 'num_players' property.""" return len(self.players) -#--[League Class]--------------------------------------------------------- + +# --[League Class]--------------------------------------------------------- # Define a baseball league model: @@ -139,7 +153,8 @@ class League(HasTraits): # The teams in the league: teams = List(Instance(Team)) -#--[LeagueModelView Class]----------------------------------------------------- + +# --[LeagueModelView Class]----------------------------------------------------- # Define a ModelView for a League model: @@ -160,8 +175,7 @@ class LeagueModelView(ModelView): @cached_property def _get_total_hits(self): - """ Returns the total number of hits across all teams and players. - """ + """Returns the total number of hits across all teams and players.""" return sum(sum(p.hits for p in t.players) for t in self.model.teams) view = View( @@ -169,101 +183,122 @@ def _get_total_hits(self): HGroup( Item('total_hits', style='readonly'), label='League Statistics', - show_border=True + show_border=True, ), VGroup( - Item('model.teams', - show_label=False, - editor=TableEditor( - columns=[ObjectColumn(name='name', - width=0.70), - ObjectColumn(name='num_players', - label='# Players', - editable=False, - width=0.29)], - selected='object.team', - auto_add=True, - row_factory=Team, - configurable=False, - sortable=False) - ), + Item( + 'model.teams', + show_label=False, + editor=TableEditor( + columns=[ + ObjectColumn(name='name', width=0.70), + ObjectColumn( + name='num_players', + label='# Players', + editable=False, + width=0.29, + ), + ], + selected='object.team', + auto_add=True, + row_factory=Team, + configurable=False, + sortable=False, + ), + ), label='League Teams', - show_border=True + show_border=True, ), VGroup( - Item('object.team.players', # <-- Extended Item name - show_label=False, - editor=TableEditor( - columns=[ObjectColumn(name='name', - width=0.70), - ObjectColumn(name='hits', - editable=False, - width=0.29)], - selected='object.player', - auto_add=True, - row_factory=Player, - configurable=False, - sortable=False) - ), + Item( + 'object.team.players', # <-- Extended Item name + show_label=False, + editor=TableEditor( + columns=[ + ObjectColumn(name='name', width=0.70), + ObjectColumn( + name='hits', editable=False, width=0.29 + ), + ], + selected='object.player', + auto_add=True, + row_factory=Player, + configurable=False, + sortable=False, + ), + ), '_', HGroup( - Item('got_hit', - show_label=False, - enabled_when='player is not None' - ) + Item( + 'got_hit', + show_label=False, + enabled_when='player is not None', + ) ), label='Team Players', show_labels=False, - show_border=True - ) + show_border=True, + ), ), - resizable=True + resizable=True, ) def _model_changed(self, model): - """ Handles the 'league' model being initialized. - """ + """Handles the 'league' model being initialized.""" if len(model.teams) > 0: self.team = model.teams[0] def _got_hit_changed(self): - """ Handles the currently selected player making a hit. - """ + """Handles the currently selected player making a hit.""" self.player.hits += 1 def _team_changed(self, team): - """ Handles a new team being selected. - """ + """Handles a new team being selected.""" if len(team.players) > 0: self.player = team.players[0] else: self.player = None + # Function to add two numbers (used with 'reduce'): add = lambda a, b: a + b -#--[Example*]------------------------------------------------------------- +# --[Example*]------------------------------------------------------------- # Define some sample teams and players: -blue_birds = Team(name='Blue Birds', players=[ - Player(name='Mike Scott', hits=25), - Player(name='Willy Shofield', hits=37), - Player(name='Tony Barucci', hits=19)]) +blue_birds = Team( + name='Blue Birds', + players=[ + Player(name='Mike Scott', hits=25), + Player(name='Willy Shofield', hits=37), + Player(name='Tony Barucci', hits=19), + ], +) -chicken_hawks = Team(name='Chicken Hawks', players=[ - Player(name='Jimmy Domore', hits=34), - Player(name='Bill Janks', hits=16), - Player(name='Tim Saunders', hits=27)]) +chicken_hawks = Team( + name='Chicken Hawks', + players=[ + Player(name='Jimmy Domore', hits=34), + Player(name='Bill Janks', hits=16), + Player(name='Tim Saunders', hits=27), + ], +) -eagles = Team(name='Eagles', players=[ - Player(name='Joe Peppers', hits=33), - Player(name='Sam Alone', hits=12), - Player(name='Roger Clemson', hits=23)]) +eagles = Team( + name='Eagles', + players=[ + Player(name='Joe Peppers', hits=33), + Player(name='Sam Alone', hits=12), + Player(name='Roger Clemson', hits=23), + ], +) # Create a league and its corresponding model view: demo = LeagueModelView( - League(name='National Baseball Conference', - teams=[blue_birds, chicken_hawks, eagles]) + League( + name='National Baseball Conference', + teams=[blue_birds, chicken_hawks, eagles], + ) ) diff --git a/examples/tutorials/traitsui_4.0/model_view.py b/examples/tutorials/traitsui_4.0/model_view.py index 702f7b2a7..5e6366af1 100644 --- a/examples/tutorials/traitsui_4.0/model_view.py +++ b/examples/tutorials/traitsui_4.0/model_view.py @@ -1,7 +1,7 @@ # Copyright (c) 2007, Enthought, Inc. # License: BSD Style. -#--(ModelView and Controller Classes)------------------------------------- +# --(ModelView and Controller Classes)------------------------------------- """ ModelView and Controller Classes ================================ @@ -95,14 +95,19 @@ for an example of a related **Controller** based design. """ -#---------------------------------------------------------------- +# ---------------------------------------------------------------- from traits.api import ( - HasTraits, Instance, List, Property, PrototypedFrom, Str, + HasTraits, + Instance, + List, + Property, + PrototypedFrom, + Str, ) from traitsui.api import Item, ModelView, ObjectColumn, TableEditor, View -#--[Parent Class]--------------------------------------------------------- +# --[Parent Class]--------------------------------------------------------- class Parent(HasTraits): @@ -110,7 +115,8 @@ class Parent(HasTraits): first_name = Str() last_name = Str() -#--[Child Class]---------------------------------------------------------- + +# --[Child Class]---------------------------------------------------------- class Child(HasTraits): @@ -121,7 +127,8 @@ class Child(HasTraits): first_name = Str() last_name = PrototypedFrom('father') -#--[ChildModelView Class]------------------------------------------------- + +# --[ChildModelView Class]------------------------------------------------- class ChildModelView(ModelView): @@ -132,19 +139,25 @@ class ChildModelView(ModelView): # Define a view showing the family as a table: view = View( - Item('family', - show_label=False, - editor=TableEditor( - columns=[ObjectColumn(name='first_name'), - ObjectColumn(name='last_name')])), - resizable=True + Item( + 'family', + show_label=False, + editor=TableEditor( + columns=[ + ObjectColumn(name='first_name'), + ObjectColumn(name='last_name'), + ] + ), + ), + resizable=True, ) # Implementation of the 'family' property: def _get_family(self): return [self.model.father, self.model.mother, self.model] -#--[Example*]------------------------------------------------------------- + +# --[Example*]------------------------------------------------------------- # Create a sample family: mom = Parent(first_name='Julia', last_name='Wilson') diff --git a/integrationtests/styled_date_editor_test.py b/integrationtests/styled_date_editor_test.py index 02db226bb..3d759c0af 100644 --- a/integrationtests/styled_date_editor_test.py +++ b/integrationtests/styled_date_editor_test.py @@ -30,8 +30,10 @@ class Foo(HasTraits): style="custom", show_label=False, editor=StyledDateEditor( - dates_trait="dates", - styles_trait="styles"))) + dates_trait="dates", styles_trait="styles" + ), + ) + ) def __init__(self, *args, **kw): HasTraits.__init__(self, *args, **kw) @@ -41,15 +43,15 @@ def __init__(self, *args, **kw): } self.fast_dates = [ - date( - 2010, 7, 4), date( - 2010, 7, 3), date( - 2010, 7, 2)] + date(2010, 7, 4), + date(2010, 7, 3), + date(2010, 7, 2), + ] self.slow_dates = [ - date( - 2010, 6, 28), date( - 2010, 6, 27), date( - 2010, 6, 24)] + date(2010, 6, 28), + date(2010, 6, 27), + date(2010, 6, 24), + ] @observe("fast_dates,slow_dates") def _update_dates_dict(self, event): diff --git a/integrationtests/test_all_examples.py b/integrationtests/test_all_examples.py index 7bfefa800..cec053497 100644 --- a/integrationtests/test_all_examples.py +++ b/integrationtests/test_all_examples.py @@ -38,7 +38,7 @@ class ExampleSearcher: - """ This object collects and reports example files to be tested.""" + """This object collects and reports example files to be tested.""" def __init__(self, source_dirs): """ @@ -51,7 +51,7 @@ def __init__(self, source_dirs): self.files_may_be_skipped = {} def skip_file_if(self, filepath, condition, reason): - """ Mark a file to be skipped for a given condition. + """Mark a file to be skipped for a given condition. Parameters ---------- @@ -66,7 +66,7 @@ def skip_file_if(self, filepath, condition, reason): self.files_may_be_skipped[filepath] = (condition, reason) def is_skipped(self, filepath): - """ Return if the Python file should be skipped in test. + """Return if the Python file should be skipped in test. Parameters ---------- @@ -87,7 +87,7 @@ def is_skipped(self, filepath): return condition(), reason def validate(self): - """ Validate configuration. Currently this checks all files that may + """Validate configuration. Currently this checks all files that may be skipped still exist. """ for filepath in self.files_may_be_skipped: @@ -96,7 +96,7 @@ def validate(self): @staticmethod def _is_python_file(path): - """ Return true if the given path is (public) non-test Python file.""" + """Return true if the given path is (public) non-test Python file.""" _, basename = os.path.split(path) _, ext = os.path.splitext(basename) return ( @@ -106,7 +106,7 @@ def _is_python_file(path): ) def get_python_files(self): - """ Report Python files to be tested or to be skipped. + """Report Python files to be tested or to be skipped. Returns ------- @@ -141,7 +141,12 @@ def get_python_files(self): # Tutorial files are not part of the package data TUTORIALS = os.path.join( - HERE, "..", "examples", "tutorials", "doc_examples", "examples", + HERE, + "..", + "examples", + "tutorials", + "doc_examples", + "examples", ) # Demo files are part of the package data. @@ -163,27 +168,33 @@ def get_python_files(self): ) SEARCHER.skip_file_if( os.path.join(DEMO, "Advanced", "Table_editor_with_progress_column.py"), - is_wx, "ProgressRenderer is not implemented in wx.", + is_wx, + "ProgressRenderer is not implemented in wx.", ) SEARCHER.skip_file_if( os.path.join(DEMO, "Advanced", "Scrubber_editor_demo.py"), - is_qt, "ScrubberEditor is not implemented in qt.", + is_qt, + "ScrubberEditor is not implemented in qt.", ) SEARCHER.skip_file_if( os.path.join(DEMO, "Extras", "animated_GIF.py"), - lambda: not is_wx(), "Only support wx", + lambda: not is_wx(), + "Only support wx", ) SEARCHER.skip_file_if( os.path.join(DEMO, "Extras", "Tree_editor_with_TreeNodeRenderer.py"), - lambda: not is_qt(), "Only support Qt", + lambda: not is_qt(), + "Only support Qt", ) SEARCHER.skip_file_if( os.path.join(DEMO, "Extras", "windows", "flash.py"), - lambda: not is_wx(), "Only support wx", + lambda: not is_wx(), + "Only support wx", ) SEARCHER.skip_file_if( os.path.join(DEMO, "Extras", "windows", "internet_explorer.py"), - lambda: not is_wx(), "Only support wx", + lambda: not is_wx(), + "Only support wx", ) SEARCHER.skip_file_if( os.path.join(DEMO, "Misc", "demo_group_size.py"), @@ -193,15 +204,17 @@ def get_python_files(self): SEARCHER.skip_file_if( os.path.join(DEMO, "Standard_Editors", "VideoEditor_demo.py"), lambda: not is_qt5(), - "Only supported on Qt5" + "Only supported on Qt5", ) SEARCHER.skip_file_if( os.path.join(TUTORIALS, "view_multi_object.py"), - lambda: True, "Require wx and is blocking.", + lambda: True, + "Require wx and is blocking.", ) SEARCHER.skip_file_if( os.path.join(TUTORIALS, "view_standalone.py"), - lambda: True, "Require wx and is blocking.", + lambda: True, + "Require wx and is blocking.", ) # Validate configuration. @@ -214,19 +227,18 @@ def get_python_files(self): def replaced_configure_traits( - instance, - filename=None, - view=None, - kind=None, - edit=True, - context=None, - handler=None, - id="", - scrollable=None, - **args + instance, + filename=None, + view=None, + kind=None, + edit=True, + context=None, + handler=None, + id="", + scrollable=None, + **args, ): - """ Mocked configure_traits to launch then close the GUI. - """ + """Mocked configure_traits to launch then close the GUI.""" ui_kwargs = dict( view=view, parent=None, @@ -243,7 +255,7 @@ def replaced_configure_traits( @contextlib.contextmanager def replace_configure_traits(): - """ Context manager to temporarily replace HasTraits.configure_traits + """Context manager to temporarily replace HasTraits.configure_traits with a mocked version such that GUI launched are closed soon after they are open. """ @@ -256,7 +268,7 @@ def replace_configure_traits(): def run_file(file_path): - """ Execute a given Python file. + """Execute a given Python file. Parameters ---------- @@ -270,9 +282,9 @@ def run_file(file_path): "__name__": "__main__", "__file__": file_path, } - with replace_configure_traits(), \ - mock.patch("sys.stdout", new_callable=io.StringIO), \ - mock.patch("sys.argv", [file_path]): + with replace_configure_traits(), mock.patch( + "sys.stdout", new_callable=io.StringIO + ), mock.patch("sys.argv", [file_path]): # Mock stdout: Examples typically print educational information. # They are expected but they should not pollute test output. # Mock argv: Some example reads sys.argv to allow more arguments @@ -287,7 +299,7 @@ def run_file(file_path): def load_tests(loader, tests, pattern): - """ Implement load_tests protocol so that when unittest discover is run + """Implement load_tests protocol so that when unittest discover is run with this test module, the tests in the demo folder (not a package) are also loaded. @@ -322,9 +334,9 @@ def load_tests(loader, tests, pattern): # Test cases # ============================================================================= + @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestExample(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) diff --git a/integrationtests/ui/array_editor_test.py b/integrationtests/ui/array_editor_test.py index 44b3c9df5..e2e96ee43 100644 --- a/integrationtests/ui/array_editor_test.py +++ b/integrationtests/ui/array_editor_test.py @@ -8,42 +8,52 @@ # # Thanks for using Enthought open source! -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Imports: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- -from traits.api \ - import HasPrivateTraits, Array +from traits.api import HasPrivateTraits, Array -from traitsui.api \ - import View, ArrayEditor +from traitsui.api import View, ArrayEditor -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'Test' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Test(HasPrivateTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- three = Array(int, (3, 3)) four = Array(float, (4, 4), editor=ArrayEditor(width=-50)) - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definitions: - #------------------------------------------------------------------------- - - view = View('three', '_', 'three', '_', 'three~', '_', - 'four', '_', 'four', '_', 'four~', - title='ArrayEditor Test Case', - resizable=True) - -#------------------------------------------------------------------------- + # ------------------------------------------------------------------------- + + view = View( + 'three', + '_', + 'three', + '_', + 'three~', + '_', + 'four', + '_', + 'four', + '_', + 'four~', + title='ArrayEditor Test Case', + resizable=True, + ) + + +# ------------------------------------------------------------------------- # Run the test case: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- if __name__ == '__main__': Test().configure_traits() diff --git a/integrationtests/ui/buttons_test.py b/integrationtests/ui/buttons_test.py index 91c75a296..5b0ea96d7 100644 --- a/integrationtests/ui/buttons_test.py +++ b/integrationtests/ui/buttons_test.py @@ -10,87 +10,105 @@ from traits.api import Int, Regex, Str from traitsui.api import ( - Action, CancelButton, Group, Handler, LiveButtons, ModalButtons, OKButton, + Action, + CancelButton, + Group, + Handler, + LiveButtons, + ModalButtons, + OKButton, View, ) -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'Person' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Person(Handler): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- name = Str() age = Int() phone = Regex(value='000-0000', regex=r'\d\d\d[-]\d\d\d\d') notes = Str() - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Handles the 'Annoy' button being clicked: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- def _annoy_clicked(self, info): - self.edit_traits(view=View(title='Annoying', - kind='modal', - buttons=['OK'])) + self.edit_traits( + view=View(title='Annoying', kind='modal', buttons=['OK']) + ) -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # Run the tests: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- if __name__ == '__main__': - AnnoyButton = Action(name='Annoy', - tooltip='Click me to be annoyed', - enabled_when='age >= 40') + AnnoyButton = Action( + name='Annoy', + tooltip='Click me to be annoyed', + enabled_when='age >= 40', + ) person = Person(name='Bill', age=42, phone='555-1212') fields = Group('name', 'age', 'phone', 'notes~') - person.notes = ("Should have 6 standard 'live' buttons: Undo, Redo, " - "Revert, OK, Cancel, Help") - person.configure_traits(view=View(fields, - kind='livemodal', - buttons=LiveButtons)) + person.notes = ( + "Should have 6 standard 'live' buttons: Undo, Redo, " + "Revert, OK, Cancel, Help" + ) + person.configure_traits( + view=View(fields, kind='livemodal', buttons=LiveButtons) + ) - person.notes = ("Should have 5 standard 'modal' buttons: Apply, Revert, " - "OK, Cancel, Help") - person.configure_traits(view=View(fields, - buttons=ModalButtons)) + person.notes = ( + "Should have 5 standard 'modal' buttons: Apply, Revert, " + "OK, Cancel, Help" + ) + person.configure_traits(view=View(fields, buttons=ModalButtons)) person.notes = "Should have 2 standard buttons: OK, Cancel" person.configure_traits( - view=View(fields, - buttons=[OKButton, CancelButton])) + view=View(fields, buttons=[OKButton, CancelButton]) + ) person.notes = "Should have 1 standard button: OK (enabled when age >= 40)" person.configure_traits( - view=View(fields, - buttons=[Action(name='OK', - enabled_when='age >= 40')])) + view=View( + fields, buttons=[Action(name='OK', enabled_when='age >= 40')] + ) + ) person.notes = "Should have 1 standard button: OK (visible when age >= 40)" person.configure_traits( - view=View(fields, - buttons=[Action(name='OK', - visible_when='age >= 40')])) + view=View( + fields, buttons=[Action(name='OK', visible_when='age >= 40')] + ) + ) - person.notes = ("Should have 2 standard buttons: OK, Help (defined when " - "age >= 50)") + person.notes = ( + "Should have 2 standard buttons: OK, Help (defined when " "age >= 50)" + ) person.configure_traits( - view=View(fields, - buttons=['OK', Action(name='Help', - defined_when='age >= 50')])) + view=View( + fields, + buttons=['OK', Action(name='Help', defined_when='age >= 50')], + ) + ) person.notes = ( "Should have 1 user and 5 standard buttons: Annoy (enabled " - "when age >= 40), Apply, Revert, OK, Cancel, Help") + "when age >= 40), Apply, Revert, OK, Cancel, Help" + ) person.configure_traits( - view=View(fields, - buttons=[AnnoyButton] + ModalButtons)) + view=View(fields, buttons=[AnnoyButton] + ModalButtons) + ) diff --git a/integrationtests/ui/check_list_editor_test.py b/integrationtests/ui/check_list_editor_test.py index 810deca49..512575bab 100644 --- a/integrationtests/ui/check_list_editor_test.py +++ b/integrationtests/ui/check_list_editor_test.py @@ -8,43 +8,51 @@ # # Thanks for using Enthought open source! -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Imports: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- -from traits.api \ - import Enum, List +from traits.api import Enum, List -from traitsui.api \ - import Handler, View, Item, CheckListEditor +from traitsui.api import Handler, View, Item, CheckListEditor -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Constants: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'] -numbers = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', - 'nine', 'ten'] - -#------------------------------------------------------------------------- +numbers = [ + 'one', + 'two', + 'three', + 'four', + 'five', + 'six', + 'seven', + 'eight', + 'nine', + 'ten', +] + +# ------------------------------------------------------------------------- # 'CheckListTest' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class CheckListTest(Handler): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- case = Enum('Colors', 'Numbers') value = List(editor=CheckListEditor(values=colors, cols=5)) - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Event handlers: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- def object_case_changed(self, info): if self.case == 'Colors': @@ -52,15 +60,14 @@ def object_case_changed(self, info): else: info.value.factory.values = numbers -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # Run the tests: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- if __name__ == '__main__': clt = CheckListTest() - clt.configure_traits( - view=View('case', '_', Item('value', id='value'))) + clt.configure_traits(view=View('case', '_', Item('value', id='value'))) print('value:', clt.value) - clt.configure_traits( - view=View('case', '_', Item('value@', id='value'))) + clt.configure_traits(view=View('case', '_', Item('value@', id='value'))) print('value:', clt.value) diff --git a/integrationtests/ui/check_list_editor_test2.py b/integrationtests/ui/check_list_editor_test2.py index c6c00fd52..12f4b581f 100644 --- a/integrationtests/ui/check_list_editor_test2.py +++ b/integrationtests/ui/check_list_editor_test2.py @@ -8,57 +8,56 @@ # # Thanks for using Enthought open source! -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Imports: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- -from traits.api \ - import Enum, List, Str +from traits.api import Enum, List, Str -from traitsui.api \ - import Handler, View, Item, CheckListEditor +from traitsui.api import Handler, View, Item, CheckListEditor -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'CheckListTest' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class CheckListTest(Handler): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- value = List(editor=CheckListEditor(name='values', cols=5)) values = List(Str) values_text = Str('red orange yellow green blue indigo violet') - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- simple_view = View('value', 'values_text@') custom_view = View('value@', 'values_text@') - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # 'Initializes the object: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- def __init__(self, **traits): super().__init__(**traits) self._values_text_changed() - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Event handlers: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- def _values_text_changed(self): self.values = self.values_text.split() -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # Run the tests: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- if __name__ == '__main__': clt = CheckListTest() diff --git a/integrationtests/ui/code_editor_test.py b/integrationtests/ui/code_editor_test.py index 05081d3ba..8eae18434 100644 --- a/integrationtests/ui/code_editor_test.py +++ b/integrationtests/ui/code_editor_test.py @@ -10,45 +10,42 @@ """ Test using a KeyBindings object with the traits CodeEditor.""" -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Imports: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- -from traits.api \ - import HasPrivateTraits, Code, Str +from traits.api import HasPrivateTraits, Code, Str -from traitsui.api \ - import View, Item, Handler, CodeEditor +from traitsui.api import View, Item, Handler, CodeEditor -from traitsui.key_bindings \ - import KeyBinding, KeyBindings +from traitsui.key_bindings import KeyBinding, KeyBindings -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Define a KeyBindings object: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- key_bindings = KeyBindings( - - KeyBinding(binding1='Ctrl-s', - description='Save to a file', - method_name='save_file'), - - KeyBinding(binding1='Ctrl-r', - description='Run script', - method_name='run_script'), - - KeyBinding(binding1='Ctrl-q', - description='Edit key bindings', - method_name='edit_bindings') + KeyBinding( + binding1='Ctrl-s', + description='Save to a file', + method_name='save_file', + ), + KeyBinding( + binding1='Ctrl-r', description='Run script', method_name='run_script' + ), + KeyBinding( + binding1='Ctrl-q', + description='Edit key bindings', + method_name='edit_bindings', + ), ) -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'CodeHandler' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class CodeHandler(Handler): - def save_file(self, info): info.object.status = "save file" @@ -59,9 +56,10 @@ def edit_bindings(self, info): info.object.status = "edit bindings" key_bindings.edit_traits() -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # 'TestCode' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class TestCode(HasPrivateTraits): @@ -70,22 +68,28 @@ class TestCode(HasPrivateTraits): status = Str() view = View( - [Item('code', - style='custom', - resizable=True, - editor=CodeEditor(key_bindings=key_bindings)), - 'status~', - '|<>'], + [ + Item( + 'code', + style='custom', + resizable=True, + editor=CodeEditor(key_bindings=key_bindings), + ), + 'status~', + '|<>', + ], id='traitsui.tests.test_code_editor.TestCode', title='Sample Code Editor', width=0.4, height=0.4, resizable=True, - handler=CodeHandler()) + handler=CodeHandler(), + ) + -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Run the test: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- if __name__ == '__main__': TestCode().configure_traits() diff --git a/integrationtests/ui/enum_dynamic_test.py b/integrationtests/ui/enum_dynamic_test.py index c8f33e8da..bd41ec136 100644 --- a/integrationtests/ui/enum_dynamic_test.py +++ b/integrationtests/ui/enum_dynamic_test.py @@ -24,10 +24,10 @@ class Team(HasTraits): captain_editor = EnumEditor(name='players', evaluate=evaluate_value) - view = View(Item('captain', editor=captain_editor), - '_', - 'players@', - height=200) + view = View( + Item('captain', editor=captain_editor), '_', 'players@', height=200 + ) + if __name__ == '__main__': team = Team() diff --git a/integrationtests/ui/enum_editor_test.py b/integrationtests/ui/enum_editor_test.py index 7a6839f00..707a04db5 100644 --- a/integrationtests/ui/enum_editor_test.py +++ b/integrationtests/ui/enum_editor_test.py @@ -8,34 +8,32 @@ # # Thanks for using Enthought open source! -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Imports: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- -from traits.api \ - import HasTraits, Trait, Enum, Range +from traits.api import HasTraits, Trait, Enum, Range -from traitsui.api \ - import View, Item, EnumEditor +from traitsui.api import View, Item, EnumEditor -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Trait definitions: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- values = ['one', 'two', 'three', 'four'] enum = Enum(*values) range = Range(1, 4) -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'TestEnumEditor' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class TestEnumEditor(HasTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- value = Trait(1, enum, range) other_value = Range(0, 4) @@ -46,9 +44,10 @@ class TestEnumEditor(HasTraits): resizable=True, ) -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # Run the test: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- if __name__ == '__main__': test = TestEnumEditor() diff --git a/integrationtests/ui/html_editor_test.py b/integrationtests/ui/html_editor_test.py index 20b5ee2d7..4fb905bf5 100644 --- a/integrationtests/ui/html_editor_test.py +++ b/integrationtests/ui/html_editor_test.py @@ -8,19 +8,17 @@ # # Thanks for using Enthought open source! -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Imports: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- -from traits.api \ - import HasPrivateTraits, Code +from traits.api import HasPrivateTraits, Code -from traitsui.api \ - import View, Group, Item, HTMLEditor +from traitsui.api import View, Group, Item, HTMLEditor -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Constants: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- sample = """This is a code block: @@ -46,37 +44,41 @@ def foo ( bar ): * 2.2 """ -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'TestHTML' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class TestHTML(HasPrivateTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Text string to display as HTML: html = Code(sample) - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definitions: - #------------------------------------------------------------------------- - - view = View(Group( - [Item('html#@', editor=HTMLEditor(format_text=True)), '|<>'], - ['{Enter formatted text and/or HTML below:}@', - 'html#@', '|<>'], - '|<>', layout='split'), + # ------------------------------------------------------------------------- + + view = View( + Group( + [Item('html#@', editor=HTMLEditor(format_text=True)), '|<>'], + ['{Enter formatted text and/or HTML below:}@', 'html#@', '|<>'], + '|<>', + layout='split', + ), title='HTML Editor Test', resizable=True, width=0.4, - height=0.6) + height=0.6, + ) + -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Run the test: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- if __name__ == '__main__': TestHTML().configure_traits() diff --git a/integrationtests/ui/instance_drag_test.py b/integrationtests/ui/instance_drag_test.py index d1f9809f7..0bffd43b4 100644 --- a/integrationtests/ui/instance_drag_test.py +++ b/integrationtests/ui/instance_drag_test.py @@ -8,29 +8,38 @@ # # Thanks for using Enthought open source! -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Imports: -#------------------------------------------------------------------------- - -from traits.api \ - import HasTraits, Str, Regex, List, Instance - -from traitsui.api \ - import TreeEditor, TreeNode, View, Group, Item, Handler, InstanceEditor +# ------------------------------------------------------------------------- + +from traits.api import HasTraits, Str, Regex, List, Instance + +from traitsui.api import ( + TreeEditor, + TreeNode, + View, + Group, + Item, + Handler, + InstanceEditor, +) -from traitsui.instance_choice \ - import InstanceDropChoice +from traitsui.instance_choice import InstanceDropChoice -from traitsui.menu \ - import Menu, Action, Separator +from traitsui.menu import Menu, Action, Separator -from traitsui.editors.tree_editor \ - import NewAction, CopyAction, CutAction, PasteAction, DeleteAction, \ - RenameAction +from traitsui.editors.tree_editor import ( + NewAction, + CopyAction, + CutAction, + PasteAction, + DeleteAction, + RenameAction, +) -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'Employee' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Employee(HasTraits): @@ -43,9 +52,10 @@ class Employee(HasTraits): def default_title(self): self.title = 'Senior Engineer' -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # 'Department' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Department(HasTraits): @@ -54,9 +64,10 @@ class Department(HasTraits): view = View(['employees', '|<>']) -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # 'Company' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Company(HasTraits): @@ -64,9 +75,10 @@ class Company(HasTraits): departments = List(Department) employees = List(Employee) -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # 'Partner' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Partner(HasTraits): @@ -75,165 +87,171 @@ class Partner(HasTraits): eom = Instance(Employee) dom = Instance(Department) -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # Create a hierarchy: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- -jason = Employee( - name='Jason', - title='Sr. Engineer', - phone='536-1057') +jason = Employee(name='Jason', title='Sr. Engineer', phone='536-1057') -mike = Employee( - name='Mike', - title='Sr. Engineer', - phone='536-1057') +mike = Employee(name='Mike', title='Sr. Engineer', phone='536-1057') -dave = Employee( - name='Dave', - title='Sr. Engineer', - phone='536-1057') +dave = Employee(name='Dave', title='Sr. Engineer', phone='536-1057') -martin = Employee( - name='Martin', - title='Sr. Engineer', - phone='536-1057') +martin = Employee(name='Martin', title='Sr. Engineer', phone='536-1057') -duncan = Employee( - name='Duncan', - title='Sr. Engineer') +duncan = Employee(name='Duncan', title='Sr. Engineer') partner = Partner( name='eric', company=Company( name='Enthought, Inc.', departments=[ - Department( - name='Business', - employees=[jason, mike] - ), - Department( - name='Scientific', - employees=[dave, martin, duncan] - ) + Department(name='Business', employees=[jason, mike]), + Department(name='Scientific', employees=[dave, martin, duncan]), ], - employees=[dave, martin, mike, duncan, jason] - ) + employees=[dave, martin, mike, duncan, jason], + ), ) -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Define the tree trait editor: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- no_view = View() tree_editor = TreeEditor( editable=False, nodes=[ - TreeNode(node_for=[Company], - auto_open=True, - children='', - label='name', - view=View(['name', '|<'])), - TreeNode(node_for=[Company], - auto_open=True, - children='departments', - label='=Departments', - view=no_view, - add=[Department]), - TreeNode(node_for=[Company], - auto_open=True, - children='employees', - label='=Employees', - view=no_view, - add=[Employee]), - TreeNode(node_for=[Department], - auto_open=True, - children='employees', - label='name', - menu=Menu(NewAction, - Separator(), - DeleteAction, - Separator(), - RenameAction, - Separator(), - CopyAction, - CutAction, - PasteAction), - view=View(['name', '|<']), - add=[Employee]), - TreeNode(node_for=[Employee], - auto_open=True, - label='name', - menu=Menu(NewAction, - Separator(), - Action(name='Default title', - action='object.default_title'), - Action(name='Department', - action='handler.employee_department(editor,object)'), - Separator(), - CopyAction, - CutAction, - PasteAction, - Separator(), - DeleteAction, - Separator(), - RenameAction), - view=View(['name', 'title', 'phone', '|<'])) - ] + TreeNode( + node_for=[Company], + auto_open=True, + children='', + label='name', + view=View(['name', '|<']), + ), + TreeNode( + node_for=[Company], + auto_open=True, + children='departments', + label='=Departments', + view=no_view, + add=[Department], + ), + TreeNode( + node_for=[Company], + auto_open=True, + children='employees', + label='=Employees', + view=no_view, + add=[Employee], + ), + TreeNode( + node_for=[Department], + auto_open=True, + children='employees', + label='name', + menu=Menu( + NewAction, + Separator(), + DeleteAction, + Separator(), + RenameAction, + Separator(), + CopyAction, + CutAction, + PasteAction, + ), + view=View(['name', '|<']), + add=[Employee], + ), + TreeNode( + node_for=[Employee], + auto_open=True, + label='name', + menu=Menu( + NewAction, + Separator(), + Action(name='Default title', action='object.default_title'), + Action( + name='Department', + action='handler.employee_department(editor,object)', + ), + Separator(), + CopyAction, + CutAction, + PasteAction, + Separator(), + DeleteAction, + Separator(), + RenameAction, + ), + view=View(['name', 'title', 'phone', '|<']), + ), + ], ) -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'TreeHandler' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class TreeHandler(Handler): - def employee_department(self, editor, object): dept = editor.get_parent(object) print('%s works in the %s department.' % (object.name, dept.name)) -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # Define the View to use: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- view = View( Group( - [Item('company', - editor=tree_editor, - resizable=True), - '|<>'], + [Item('company', editor=tree_editor, resizable=True), '|<>'], Group( - ['{Employee of the Month}@', - Item('eom@', - editor=InstanceEditor(values=[ - InstanceDropChoice(klass=Employee, - selectable=True)]), - resizable=True), - '|<>'], - ['{Department of the Month}@', - Item('dom@', - editor=InstanceEditor(values=[ - InstanceDropChoice(klass=Department)]), - resizable=True), - '|<>'], + [ + '{Employee of the Month}@', + Item( + 'eom@', + editor=InstanceEditor( + values=[ + InstanceDropChoice(klass=Employee, selectable=True) + ] + ), + resizable=True, + ), + '|<>', + ], + [ + '{Department of the Month}@', + Item( + 'dom@', + editor=InstanceEditor( + values=[InstanceDropChoice(klass=Department)] + ), + resizable=True, + ), + '|<>', + ], show_labels=False, - layout='split'), + layout='split', + ), orientation='horizontal', show_labels=False, - layout='split'), + layout='split', + ), title='Company Structure', handler=TreeHandler(), buttons=['OK', 'Cancel'], resizable=True, - width=.5, - height=.5 + width=0.5, + height=0.5, ) -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Edit it: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- if __name__ == '__main__': partner.configure_traits(view=view) diff --git a/integrationtests/ui/instance_editor_test.py b/integrationtests/ui/instance_editor_test.py index 9e40044d8..23e4f2615 100644 --- a/integrationtests/ui/instance_editor_test.py +++ b/integrationtests/ui/instance_editor_test.py @@ -11,30 +11,31 @@ from traits.api import HasStrictTraits, Instance, Int, List, Regex, Str from traitsui.api import InstanceEditor, Item, View -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'Person' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Person(HasStrictTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- name = Str() age = Int() phone = Regex(value='000-0000', regex=r'\d\d\d[-]\d\d\d\d') - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definition: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- traits_view = View('name', 'age', 'phone') -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # Sample data: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- people = [ Person(name='Dave', age=39, phone='555-1212'), @@ -44,38 +45,39 @@ class Person(HasStrictTraits): Person(name='Dick', age=63, phone='555-3895'), Person(name='Harry', age=46, phone='555-3285'), Person(name='Sally', age=43, phone='555-8797'), - Person(name='Fields', age=31, phone='555-3547') + Person(name='Fields', age=31, phone='555-3547'), ] -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'Team' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Team(HasStrictTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- name = Str() captain = Instance(Person) roster = List(Instance(Person)) - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- + + traits_view = View( + 'name', + '_', + Item('captain@', editor=InstanceEditor(name='roster')), + buttons=['Undo', 'OK', 'Cancel'], + ) - traits_view = View('name', '_', - Item('captain@', - editor=InstanceEditor(name='roster')), - buttons=['Undo', 'OK', 'Cancel']) -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Run the test: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- if __name__ == '__main__': - Team(name='Vultures', - captain=people[0], - roster=people).configure_traits() + Team(name='Vultures', captain=people[0], roster=people).configure_traits() diff --git a/integrationtests/ui/instance_editor_test2.py b/integrationtests/ui/instance_editor_test2.py index a5590dcf6..0929f80d6 100644 --- a/integrationtests/ui/instance_editor_test2.py +++ b/integrationtests/ui/instance_editor_test2.py @@ -11,30 +11,31 @@ from traits.api import HasStrictTraits, Instance, Int, List, Regex, Str from traitsui.api import InstanceEditor, InstanceFactoryChoice, Item, View -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'Person' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Person(HasStrictTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- name = Str() age = Int() phone = Regex(value='000-0000', regex=r'\d\d\d[-]\d\d\d\d') - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definition: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- traits_view = View('name', 'age', 'phone') -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # Sample data: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- people = [ Person(name='Dave', age=39, phone='555-1212'), @@ -44,40 +45,46 @@ class Person(HasStrictTraits): Person(name='Dick', age=63, phone='555-3895'), Person(name='Harry', age=46, phone='555-3285'), Person(name='Sally', age=43, phone='555-8797'), - Person(name='Fields', age=31, phone='555-3547') + Person(name='Fields', age=31, phone='555-3547'), ] -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'Team' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Team(HasStrictTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- name = Str() captain = Instance(Person) roster = List(Instance(Person)) - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- traits_view = View( - 'name', '_', Item( - 'captain@', editor=InstanceEditor( - name='roster', values=[ - InstanceFactoryChoice( - klass=Person, name='Non player')]))) - -#------------------------------------------------------------------------- + 'name', + '_', + Item( + 'captain@', + editor=InstanceEditor( + name='roster', + values=[ + InstanceFactoryChoice(klass=Person, name='Non player') + ], + ), + ), + ) + + +# ------------------------------------------------------------------------- # Run the test: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- if __name__ == '__main__': - Team(name='Vultures', - captain=people[0], - roster=people).configure_traits() + Team(name='Vultures', captain=people[0], roster=people).configure_traits() diff --git a/integrationtests/ui/instance_editor_test3.py b/integrationtests/ui/instance_editor_test3.py index 5dc3ab6a3..058f772df 100644 --- a/integrationtests/ui/instance_editor_test3.py +++ b/integrationtests/ui/instance_editor_test3.py @@ -11,30 +11,31 @@ from traits.api import HasStrictTraits, Instance, Int, List, Regex, Str from traitsui.api import InstanceEditor, Item, View -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'Person' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Person(HasStrictTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- name = Str() age = Int() phone = Regex(value='000-0000', regex=r'\d\d\d[-]\d\d\d\d') - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definition: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- traits_view = View('name', 'age', 'phone') -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # Sample data: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- people = [ Person(name='Dave', age=39, phone='555-1212'), @@ -44,38 +45,40 @@ class Person(HasStrictTraits): Person(name='Dick', age=63, phone='555-3895'), Person(name='Harry', age=46, phone='555-3285'), Person(name='Sally', age=43, phone='555-8797'), - Person(name='Fields', age=31, phone='555-3547') + Person(name='Fields', age=31, phone='555-3547'), ] -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'Team' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Team(HasStrictTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- name = Str() captain = Instance(Person) roster = List(Instance(Person)) - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- + + traits_view = View( + 'name', + '_', + Item('captain@', editor=InstanceEditor(name='roster')), + '_', + 'roster', + ) - traits_view = View('name', '_', - Item('captain@', - editor=InstanceEditor(name='roster')), '_', - 'roster') -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Run the test: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- if __name__ == '__main__': - Team(name='Vultures', - captain=people[0], - roster=people).configure_traits() + Team(name='Vultures', captain=people[0], roster=people).configure_traits() diff --git a/integrationtests/ui/instance_editor_test4.py b/integrationtests/ui/instance_editor_test4.py index 3f91fc87f..0e72a06a8 100644 --- a/integrationtests/ui/instance_editor_test4.py +++ b/integrationtests/ui/instance_editor_test4.py @@ -11,30 +11,31 @@ from traits.api import HasStrictTraits, Instance, Int, List, Regex, Str from traitsui.api import InstanceEditor, Item, View -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'Person' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Person(HasStrictTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- name = Str() age = Int() phone = Regex(value='000-0000', regex=r'\d\d\d[-]\d\d\d\d') - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definition: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- traits_view = View('name', 'age', 'phone') -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # Sample data: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- people = [ Person(name='Dave', age=39, phone='555-1212'), @@ -44,39 +45,40 @@ class Person(HasStrictTraits): Person(name='Dick', age=63, phone='555-3895'), Person(name='Harry', age=46, phone='555-3285'), Person(name='Sally', age=43, phone='555-8797'), - Person(name='Fields', age=31, phone='555-3547') + Person(name='Fields', age=31, phone='555-3547'), ] -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'Team' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Team(HasStrictTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- name = Str() captain = Instance(Person) roster = List(Person) - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- + + traits_view = View( + 'name', + '_', + Item('captain@', editor=InstanceEditor(name='roster', editable=False)), + '_', + 'roster', + ) - traits_view = View('name', '_', - Item('captain@', - editor=InstanceEditor(name='roster', - editable=False)), - '_', 'roster') -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Run the test: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- if __name__ == '__main__': - Team(name='Vultures', - captain=people[0], - roster=people).configure_traits() + Team(name='Vultures', captain=people[0], roster=people).configure_traits() diff --git a/integrationtests/ui/instance_editor_test5.py b/integrationtests/ui/instance_editor_test5.py index b20b48181..6690a097c 100644 --- a/integrationtests/ui/instance_editor_test5.py +++ b/integrationtests/ui/instance_editor_test5.py @@ -11,31 +11,32 @@ from traits.api import HasStrictTraits, Instance, Int, List, Regex, Str from traitsui.api import InstanceEditor, InstanceFactoryChoice, Item, View -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'Person' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Person(HasStrictTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- name = Str() age = Int() phone = Regex(value='000-0000', regex=r'\d\d\d[-]\d\d\d\d') - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definition: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- traits_view = View('name~', 'age~', 'phone~') edit_view = View('name', 'age', 'phone') -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # Sample data: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- people = [ Person(name='Dave', age=39, phone='555-1212'), @@ -45,46 +46,58 @@ class Person(HasStrictTraits): Person(name='Dick', age=63, phone='555-3895'), Person(name='Harry', age=46, phone='555-3285'), Person(name='Sally', age=43, phone='555-8797'), - Person(name='Fields', age=31, phone='555-3547') + Person(name='Fields', age=31, phone='555-3547'), ] -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'Team' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Team(HasStrictTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- name = Str() captain = Instance(Person) roster = List(Person) - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definitions: - #------------------------------------------------------------------------- - - traits_view = View([['name', '_', - Item('captain@', - editor=InstanceEditor(name='roster', - editable=False, - values=[ - InstanceFactoryChoice( - klass=Person, - name='Non player', - view='edit_view')])), - '_'], - ['captain@', '|<>']]) - -#------------------------------------------------------------------------- + # ------------------------------------------------------------------------- + + traits_view = View( + [ + [ + 'name', + '_', + Item( + 'captain@', + editor=InstanceEditor( + name='roster', + editable=False, + values=[ + InstanceFactoryChoice( + klass=Person, + name='Non player', + view='edit_view', + ) + ], + ), + ), + '_', + ], + ['captain@', '|<>'], + ] + ) + + +# ------------------------------------------------------------------------- # Run the test: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- if __name__ == '__main__': - t = Team(name='Vultures', - captain=people[0], - roster=people) + t = Team(name='Vultures', captain=people[0], roster=people) t.configure_traits() diff --git a/integrationtests/ui/instance_editor_test6.py b/integrationtests/ui/instance_editor_test6.py index 8506b28c6..cb3fc1d78 100644 --- a/integrationtests/ui/instance_editor_test6.py +++ b/integrationtests/ui/instance_editor_test6.py @@ -11,31 +11,31 @@ from traits.api import HasStrictTraits, Instance, Int, List, Regex, Str from traitsui.api import InstanceEditor, InstanceFactoryChoice, Item, View -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'Person' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Person(HasStrictTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- name = Str() age = Int() phone = Regex(value='000-0000', regex=r'\d\d\d[-]\d\d\d\d') - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definition: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- - traits_view = View('name', 'age', 'phone', - buttons=['OK', 'Cancel']) + traits_view = View('name', 'age', 'phone', buttons=['OK', 'Cancel']) -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # Sample data: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- people = [ Person(name='Dave', age=39, phone='555-1212'), @@ -45,44 +45,52 @@ class Person(HasStrictTraits): Person(name='Dick', age=63, phone='555-3895'), Person(name='Harry', age=46, phone='555-3285'), Person(name='Sally', age=43, phone='555-8797'), - Person(name='Fields', age=31, phone='555-3547') + Person(name='Fields', age=31, phone='555-3547'), ] -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'Team' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Team(HasStrictTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- name = Str() captain = Instance(Person) roster = List(Person) - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definitions: - #------------------------------------------------------------------------- - - traits_view = View(['name', '_', - Item('captain', - editor=InstanceEditor(name='roster', - label='Edit...', - values=[ - InstanceFactoryChoice( - klass=Person, - name='Non player', - view='edit_view')]))], - buttons=['OK', 'Cancel']) - -#------------------------------------------------------------------------- + # ------------------------------------------------------------------------- + + traits_view = View( + [ + 'name', + '_', + Item( + 'captain', + editor=InstanceEditor( + name='roster', + label='Edit...', + values=[ + InstanceFactoryChoice( + klass=Person, name='Non player', view='edit_view' + ) + ], + ), + ), + ], + buttons=['OK', 'Cancel'], + ) + + +# ------------------------------------------------------------------------- # Run the test: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- if __name__ == '__main__': - Team(name='Vultures', - captain=people[0], - roster=people).configure_traits() + Team(name='Vultures', captain=people[0], roster=people).configure_traits() diff --git a/integrationtests/ui/large_range_editor.py b/integrationtests/ui/large_range_editor.py index b8d69790c..4af16108e 100644 --- a/integrationtests/ui/large_range_editor.py +++ b/integrationtests/ui/large_range_editor.py @@ -19,26 +19,33 @@ class TestRangeEditor(HasTraits): x = Float() low = Float(123.123) high = Float(1123.123) - list = List(Float( - editor=RangeEditor(low_name='low', - high_name='high', - # These force the large range - # slider to be used. - low=100.0, - high=10000.123) + list = List( + Float( + editor=RangeEditor( + low_name='low', + high_name='high', + # These force the large range + # slider to be used. + low=100.0, + high=10000.123, + ) + ) ) + view = View( + Item( + name='x', + editor=RangeEditor( + low_name='low', + high_name='high', + # These force the large range + # slider to be used. + low=100.0, + high=10000.123, + ), + ), + Item('list'), + resizable=True, ) - view = View(Item(name='x', - editor=RangeEditor(low_name='low', - high_name='high', - # These force the large range - # slider to be used. - low=100.0, - high=10000.123) - ), - Item('list'), - resizable=True - ) def test(): @@ -49,4 +56,5 @@ def test(): assert a.x == 500 assert a.list[0] == 500 + test() diff --git a/integrationtests/ui/list_traits_ui_test.py b/integrationtests/ui/list_traits_ui_test.py index fed2b2a46..2d719c4a2 100644 --- a/integrationtests/ui/list_traits_ui_test.py +++ b/integrationtests/ui/list_traits_ui_test.py @@ -8,49 +8,51 @@ # # Thanks for using Enthought open source! -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Imports: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- -from traits.api \ - import HasStrictTraits, Str, Int, Regex, List, Instance +from traits.api import HasStrictTraits, Str, Int, Regex, List, Instance -from traitsui.api \ - import View, Item, VSplit, TableEditor, ListEditor +from traitsui.api import View, Item, VSplit, TableEditor, ListEditor -from traitsui.table_column \ - import ObjectColumn +from traitsui.table_column import ObjectColumn -from traitsui.table_filter \ - import TableFilter, RuleTableFilter, RuleFilterTemplate, \ - MenuFilterTemplate, EvalFilterTemplate +from traitsui.table_filter import ( + TableFilter, + RuleTableFilter, + RuleFilterTemplate, + MenuFilterTemplate, + EvalFilterTemplate, +) -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'Person' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Person(HasStrictTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- name = Str() age = Int() phone = Regex(value='000-0000', regex=r'\d\d\d[-]\d\d\d\d') - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definition: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- + + traits_view = View( + 'name', 'age', 'phone', width=0.18, buttons=['OK', 'Cancel'] + ) - traits_view = View('name', 'age', 'phone', - width=0.18, - buttons=['OK', 'Cancel']) -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Sample data: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- people = [ Person(name='Dave', age=39, phone='555-1212'), @@ -60,74 +62,80 @@ class Person(HasStrictTraits): Person(name='Dick', age=63, phone='555-3895'), Person(name='Harry', age=46, phone='555-3285'), Person(name='Sally', age=43, phone='555-8797'), - Person(name='Fields', age=31, phone='555-3547') + Person(name='Fields', age=31, phone='555-3547'), ] -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Table editor definition: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- filters = [EvalFilterTemplate, MenuFilterTemplate, RuleFilterTemplate] table_editor = TableEditor( - columns=[ObjectColumn(name='name'), - ObjectColumn(name='age'), - ObjectColumn(name='phone')], + columns=[ + ObjectColumn(name='name'), + ObjectColumn(name='age'), + ObjectColumn(name='phone'), + ], editable=True, deletable=True, sortable=True, sort_model=True, filters=filters, search=RuleTableFilter(), - row_factory=Person + row_factory=Person, ) -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'ListTraitTest' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class ListTraitTest(HasStrictTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- people = List(Person) - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- traits_view = View( VSplit( - Item('people', - id='table', - editor=table_editor), - Item('people@', - id='list', - editor=ListEditor(style='custom', - rows=5)), - Item('people@', - id='notebook', - editor=ListEditor(use_notebook=True, - deletable=True, - export='DockShellWindow', - dock_style='tab', - page_name='.name')), + Item('people', id='table', editor=table_editor), + Item( + 'people@', id='list', editor=ListEditor(style='custom', rows=5) + ), + Item( + 'people@', + id='notebook', + editor=ListEditor( + use_notebook=True, + deletable=True, + export='DockShellWindow', + dock_style='tab', + page_name='.name', + ), + ), id='splitter', - show_labels=False), + show_labels=False, + ), title='List Trait Editor Test', id='traitsui.tests.list_traits_ui_test', dock='horizontal', - width=.4, - height=.6, + width=0.4, + height=0.6, resizable=True, - kind='live') + kind='live', + ) + -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Run the tests: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- if __name__ == '__main__': ListTraitTest(people=people).configure_traits() diff --git a/integrationtests/ui/set_dynamic_test.py b/integrationtests/ui/set_dynamic_test.py index 1a91ad02a..fb48d9629 100644 --- a/integrationtests/ui/set_dynamic_test.py +++ b/integrationtests/ui/set_dynamic_test.py @@ -17,11 +17,14 @@ class Team(HasTraits): batting_order = List(Str) roster = List(['Tom', 'Dick', 'Harry', 'Sally'], Str) - view = View(Item('batting_order', editor=SetEditor(name='roster', - ordered=True)), - '_', 'roster@', - height=500, - resizable=True) + view = View( + Item('batting_order', editor=SetEditor(name='roster', ordered=True)), + '_', + 'roster@', + height=500, + resizable=True, + ) + if __name__ == '__main__': Team().configure_traits() diff --git a/integrationtests/ui/shell_editor_test.py b/integrationtests/ui/shell_editor_test.py index 9fbbfac10..32575e849 100644 --- a/integrationtests/ui/shell_editor_test.py +++ b/integrationtests/ui/shell_editor_test.py @@ -11,16 +11,16 @@ from traits.api import Dict, Float, HasPrivateTraits, Int, Str from traitsui.api import Item, ShellEditor, View -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'ShellTest' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class ShellTest(HasPrivateTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- name = Str() age = Int() @@ -28,21 +28,27 @@ class ShellTest(HasPrivateTraits): shell_1 = Str() shell_2 = Dict() - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definitions: - #------------------------------------------------------------------------- - - view = View('name', 'age', 'weight', '_', - Item('shell_1', editor=ShellEditor()), - Item('shell_2', editor=ShellEditor()), - id='traitsui.tests.shell_editor_test', - resizable=True, - width=0.3, - height=0.3) - -#------------------------------------------------------------------------- + # ------------------------------------------------------------------------- + + view = View( + 'name', + 'age', + 'weight', + '_', + Item('shell_1', editor=ShellEditor()), + Item('shell_2', editor=ShellEditor()), + id='traitsui.tests.shell_editor_test', + resizable=True, + width=0.3, + height=0.3, + ) + + +# ------------------------------------------------------------------------- # Run the test: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- if __name__ == '__main__': ShellTest().configure_traits() diff --git a/integrationtests/ui/table_editor_color_test.py b/integrationtests/ui/table_editor_color_test.py index 518596f3f..c6aeeeba4 100644 --- a/integrationtests/ui/table_editor_color_test.py +++ b/integrationtests/ui/table_editor_color_test.py @@ -8,29 +8,26 @@ # # Thanks for using Enthought open source! -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Imports: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- -from traits.api \ - import HasTraits, List +from traits.api import HasTraits, List -from traitsui.api \ - import View, Item, TableEditor +from traitsui.api import View, Item, TableEditor -from traitsui.color_column \ - import ColorColumn +from traitsui.color_column import ColorColumn -from enable.api \ - import ColorTrait +from enable.api import ColorTrait class Thingy(HasTraits): color = ColorTrait('black') -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # Sample data: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- colors = [ Thingy(color='red'), @@ -47,42 +44,41 @@ class Thingy(HasTraits): class TableTest(HasTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- colors = List(Thingy) table_editor = TableEditor( - columns=[ColorColumn(name='color'), - ], - + columns=[ + ColorColumn(name='color'), + ], editable=True, deletable=True, - sortable=True, # + sortable=True, # sort_model=True, - show_lines=True, # + show_lines=True, # orientation='vertical', - show_column_labels=True, # - row_factory=Thingy + show_column_labels=True, # + row_factory=Thingy, ) traits_view = View( - [Item('colors', - id='colors', - editor=table_editor), - '|[]<>'], + [Item('colors', id='colors', editor=table_editor), '|[]<>'], title='Table Editor Test', id='traitsui.tests.table_editor_color_test', dock='horizontal', - width=.4, - height=.3, + width=0.4, + height=0.3, resizable=True, - kind='live') + kind='live', + ) + -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Run the tests: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- if __name__ == '__main__': tt = TableTest(colors=colors) diff --git a/integrationtests/ui/table_editor_focus_bug.py b/integrationtests/ui/table_editor_focus_bug.py index 1804dc780..c65b6df8a 100644 --- a/integrationtests/ui/table_editor_focus_bug.py +++ b/integrationtests/ui/table_editor_focus_bug.py @@ -10,8 +10,7 @@ from traits.api import HasTraits, Str, List from traitsui.api import Group, Item, TableEditor, View -from traitsui.table_column \ - import ObjectColumn +from traitsui.table_column import ObjectColumn class Word(HasTraits): @@ -41,10 +40,11 @@ def _input_changed(self): return table_editor = TableEditor( - columns=[ObjectColumn(name='word')], - editable=True) + columns=[ObjectColumn(name='word')], editable=True + ) - help = Str("""Type in the 'input' box before clicking the Parsed tab. + help = Str( + """Type in the 'input' box before clicking the Parsed tab. The first non-whitespace character will cause changes to the parsed trait and therefore changes to the table rows. That is expected. @@ -53,30 +53,39 @@ def _input_changed(self): If you click the 'Parsed' tab, to view the table, and then the 'Inputs' tab the focus will stay with the 'input' box. -""") +""" + ) traits_view = View( - Group(Item('help', style='readonly'), - Item('input'), - label='Input'), - Group(Item('parsed', editor=table_editor), - label='Parsed'), + Group(Item('help', style='readonly'), Item('input'), label='Input'), + Group(Item('parsed', editor=table_editor), label='Parsed'), dock='tab', resizable=True, width=320, - height=240 + height=240, ) + if __name__ == '__main__': # simple test of the model foo = Foo() foo.input = 'these words in the list' - assert([word.word for word in foo.parsed] == [ - 'these', 'words', 'in', 'the', 'list']) + assert [word.word for word in foo.parsed] == [ + 'these', + 'words', + 'in', + 'the', + 'list', + ] foo.input = 'these dudes in the bar' - assert([word.word for word in foo.parsed] == [ - 'these', 'in', 'the', 'dudes', 'bar']) + assert [word.word for word in foo.parsed] == [ + 'these', + 'in', + 'the', + 'dudes', + 'bar', + ] foo.configure_traits(kind='modal') print(foo.input, [word.word for word in foo.parsed]) diff --git a/integrationtests/ui/table_editor_test.py b/integrationtests/ui/table_editor_test.py index aaa7554fe..78d39fc65 100644 --- a/integrationtests/ui/table_editor_test.py +++ b/integrationtests/ui/table_editor_test.py @@ -8,51 +8,58 @@ # # Thanks for using Enthought open source! -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Imports: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- -from traits.api \ - import HasStrictTraits, Str, Int, Regex, List, Instance +from traits.api import HasStrictTraits, Str, Int, Regex, List, Instance -from traitsui.api \ - import View, Group, Item, TableEditor, EnumEditor +from traitsui.api import View, Group, Item, TableEditor, EnumEditor -from traitsui.table_column \ - import ObjectColumn +from traitsui.table_column import ObjectColumn -from traitsui.table_filter \ - import TableFilter, RuleTableFilter, RuleFilterTemplate, \ - MenuFilterTemplate, EvalFilterTemplate +from traitsui.table_filter import ( + TableFilter, + RuleTableFilter, + RuleFilterTemplate, + MenuFilterTemplate, + EvalFilterTemplate, +) -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'Person' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Person(HasStrictTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- name = Str() age = Int() phone = Regex(value='000-0000', regex=r'\d\d\d[-]\d\d\d\d') state = Str() - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definition: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- + + traits_view = View( + 'name', + 'age', + 'phone', + 'state', + title='Create new person', + width=0.18, + buttons=['OK', 'Cancel'], + ) - traits_view = View('name', 'age', 'phone', 'state', - title='Create new person', - width=0.18, - buttons=['OK', 'Cancel']) -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Sample data: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- people = [ Person(name='Dave', age=39, phone='555-1212'), @@ -62,99 +69,95 @@ class Person(HasStrictTraits): Person(name='Dick', age=63, phone='555-3895'), Person(name='Harry', age=46, phone='555-3285'), Person(name='Sally', age=43, phone='555-8797'), - Person(name='Fields', age=31, phone='555-3547') + Person(name='Fields', age=31, phone='555-3547'), ] -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'AgeFilter' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class AgeFilter(TableFilter): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- name = "Age filter" _name = "Age filter" age = Int(0) - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- - #filter_view = Group( 'age{Age >=}' ) + # filter_view = Group( 'age{Age >=}' ) - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Returns whether an object passes the filter or not: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- def filter(self, person): - """ Returns whether an object passes the filter or not. - """ - return (person.age >= self.age) + """Returns whether an object passes the filter or not.""" + return person.age >= self.age - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Returns a user readable description of what the filter does: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- def description(self): - """ Returns a user readable description of what the filter does. - """ + """Returns a user readable description of what the filter does.""" return 'Age >= %d' % self.age def _age_changed(self, old, new): self.name = self.description() print('AgeFilter _age_changed', self.name) -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # 'NameFilter' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class NameFilter(TableFilter): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- mname = Str() - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- filter_view = Group('mname{Name contains}') - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Returns whether an object passes the filter or not: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- def filter(self, person): - """ Returns whether an object passes the filter or not. - """ - return (person.name.lower().find(self.mname.lower()) >= 0) + """Returns whether an object passes the filter or not.""" + return person.name.lower().find(self.mname.lower()) >= 0 - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Returns a user readable description of what the filter does: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- def description(self): - """ Returns a user readable description of what the filter does. - """ + """Returns a user readable description of what the filter does.""" return "Name contains '%s'" % self.mname -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # Table editor definition: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- filters = [ - AgeFilter( - age=30), - NameFilter( - mname='d'), + AgeFilter(age=30), + NameFilter(mname='d'), EvalFilterTemplate, MenuFilterTemplate, RuleFilterTemplate, @@ -164,38 +167,41 @@ def description(self): def evaluate_value(v): print('evaluate_value', v) return str(v) -#------------------------------------------------------------------------- + + +# ------------------------------------------------------------------------- # 'TableTest' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class TableTest(HasStrictTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- - #people = Instance( Person ) + # people = Instance( Person ) people = List(Person) - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- _valid_states = List(["AL", "AR", "AZ", "AK"]) _state_editor = EnumEditor( name="_valid_states", evaluate=evaluate_value, - object='table_editor_object' + object='table_editor_object', ) table_editor = TableEditor( - columns=[ObjectColumn(name='name'), - ObjectColumn(name='age'), - ObjectColumn(name='phone'), - ObjectColumn(name='state', - editor=_state_editor), ], + columns=[ + ObjectColumn(name='name'), + ObjectColumn(name='age'), + ObjectColumn(name='phone'), + ObjectColumn(name='state', editor=_state_editor), + ], editable=True, deletable=True, sortable=True, @@ -203,30 +209,29 @@ class TableTest(HasStrictTraits): show_lines=True, orientation='vertical', show_column_labels=True, - edit_view=View(['name', 'age', 'phone', 'state', '|[]'], - resizable=True), + edit_view=View( + ['name', 'age', 'phone', 'state', '|[]'], resizable=True + ), filter=None, filters=filters, - row_factory=Person + row_factory=Person, ) traits_view = View( - [Item('people', - id='people', - editor=table_editor), - '|[]<>'], + [Item('people', id='people', editor=table_editor), '|[]<>'], title='Table Editor Test', id='traitsui.tests.table_editor_test', dock='horizontal', - width=.4, - height=.3, + width=0.4, + height=0.3, resizable=True, - kind='live') + kind='live', + ) -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Run the tests: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- if __name__ == '__main__': tt = TableTest(people=people) diff --git a/integrationtests/ui/table_editor_test2.py b/integrationtests/ui/table_editor_test2.py index 173a0a779..ce2d2f45a 100644 --- a/integrationtests/ui/table_editor_test2.py +++ b/integrationtests/ui/table_editor_test2.py @@ -8,65 +8,74 @@ # # Thanks for using Enthought open source! -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Imports: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- -from traits.api \ - import HasStrictTraits, Str, Int, Regex, List +from traits.api import HasStrictTraits, Str, Int, Regex, List -from traitsui.api \ - import View +from traitsui.api import View -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'Person' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Person(HasStrictTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- name = Str() age = Int() phone = Regex(value='000-0000', regex=r'\d\d\d[-]\d\d\d\d') - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definition: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- - traits_view = View('name', 'age', 'phone', - title='Create new person', - width=0.18, - buttons=['OK', 'Cancel']) + traits_view = View( + 'name', + 'age', + 'phone', + title='Create new person', + width=0.18, + buttons=['OK', 'Cancel'], + ) -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # 'WorkingPerson' class -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class WorkingPerson(Person): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- job = Str() - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definition: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- + + traits_view = View( + 'name', + 'age', + 'phone', + 'job', + title='Create new working person.........', + width=0.18, + buttons=['OK', 'Cancel'], + ) - traits_view = View('name', 'age', 'phone', 'job', - title='Create new working person.........', - width=0.18, - buttons=['OK', 'Cancel']) -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Sample data: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- people = [ Person(name='Dave', age=39, phone='555-1212'), @@ -76,31 +85,32 @@ class WorkingPerson(Person): Person(name='Dick', age=63, phone='555-3895'), Person(name='Harry', age=46, phone='555-3285'), WorkingPerson(name='Sally', age=43, phone='555-8797', job='Soldier'), - Person(name='Fields', age=31, phone='555-3547') + Person(name='Fields', age=31, phone='555-3547'), ] -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'TableTest' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class TableTest(HasStrictTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- people = List(Person) - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- traits_view = View(['people#', '|<>'], resizable=True) -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # Run the tests: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- if __name__ == '__main__': tt = TableTest(people=people) diff --git a/integrationtests/ui/table_list_editor_test.py b/integrationtests/ui/table_list_editor_test.py index 0681187d7..2c53201eb 100644 --- a/integrationtests/ui/table_list_editor_test.py +++ b/integrationtests/ui/table_list_editor_test.py @@ -11,25 +11,21 @@ """ TableEditor test case for Traits UI which tests editing of lists instead of editing of objects.""" -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Imports: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- -from traits.api \ - import HasStrictTraits, List +from traits.api import HasStrictTraits, List -from traitsui.api \ - import View, Item, TableEditor +from traitsui.api import View, Item, TableEditor -from traitsui.table_column \ - import ListColumn +from traitsui.table_column import ListColumn -from traitsui.table_filter \ - import TableFilter +from traitsui.table_filter import TableFilter -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Sample data: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- people = [ ['Dave', 39, '555-1212'], @@ -39,51 +35,53 @@ ['Dick', 63, '555-3895'], ['Harry', 46, '555-3285'], ['Sally', 43, '555-8797'], - ['Fields', 31, '555-3547'] + ['Fields', 31, '555-3547'], ] -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Table editor definition: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- table_editor = TableEditor( - columns=[ListColumn(index=0, label='Name'), - ListColumn(index=1, label='Age'), - ListColumn(index=2, label='Phone')], + columns=[ + ListColumn(index=0, label='Name'), + ListColumn(index=1, label='Age'), + ListColumn(index=2, label='Phone'), + ], editable=False, - show_column_labels=True, # + show_column_labels=True, # ) -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'TableTest' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class TableTest(HasStrictTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- people = List() - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Traits view definitions: - #------------------------------------------------------------------------- - - traits_view = View([Item('people', - editor=table_editor, - resizable=True), - '|[]<>'], - title='Table Editor Test', - width=.17, - height=.23, - buttons=['OK', 'Cancel'], - kind='live') - -#------------------------------------------------------------------------- + # ------------------------------------------------------------------------- + + traits_view = View( + [Item('people', editor=table_editor, resizable=True), '|[]<>'], + title='Table Editor Test', + width=0.17, + height=0.23, + buttons=['OK', 'Cancel'], + kind='live', + ) + + +# ------------------------------------------------------------------------- # Run the tests: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- if __name__ == '__main__': tt = TableTest(people=people) diff --git a/integrationtests/ui/test_ui.py b/integrationtests/ui/test_ui.py index b71cead25..2b21b6275 100644 --- a/integrationtests/ui/test_ui.py +++ b/integrationtests/ui/test_ui.py @@ -8,181 +8,299 @@ # # Thanks for using Enthought open source! -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Imports: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- import wx -from traits.api \ - import Trait, HasTraits, Str, Int, Range, List, Event, File, Directory, \ - Bool, Enum +from traits.api import ( + Trait, + HasTraits, + Str, + Int, + Range, + List, + Event, + File, + Directory, + Bool, + Enum, +) -from traitsui.api \ - import View, Handler, Item, CheckListEditor, ButtonEditor, FileEditor, \ - DirectoryEditor, ImageEnumEditor, Color, Font +from traitsui.api import ( + View, + Handler, + Item, + CheckListEditor, + ButtonEditor, + FileEditor, + DirectoryEditor, + ImageEnumEditor, + Color, + Font, +) -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Constants: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- origin_values = ['top left', 'top right', 'bottom left', 'bottom right'] -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'Instance' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Instance(HasTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- integer_text = Int(1) - enumeration = Enum('one', 'two', 'three', 'four', 'five', 'six', - cols=3) + enumeration = Enum('one', 'two', 'three', 'four', 'five', 'six', cols=3) float_range = Range(0.0, 10.0, 10.0) int_range = Range(1, 5) boolean = Bool(True) - view = View('integer_text', 'enumeration', 'float_range', - 'int_range', 'boolean') + view = View( + 'integer_text', 'enumeration', 'float_range', 'int_range', 'boolean' + ) + -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'TraitsTest' class -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class TraitsTest(HasTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- integer_text = Int(1) - enumeration = Enum('one', 'two', 'three', 'four', 'five', 'six', - cols=3) + enumeration = Enum('one', 'two', 'three', 'four', 'five', 'six', cols=3) float_range = Range(0.0, 10.0, 10.0) int_range = Range(1, 6) int_range2 = Range(1, 50) - compound = Trait(1, Range(1, 6), - 'one', 'two', 'three', 'four', 'five', 'six') + compound = Trait( + 1, Range(1, 6), 'one', 'two', 'three', 'four', 'five', 'six' + ) boolean = Bool(True) instance = Trait(Instance()) color = Color font = Font - check_list = List(editor=CheckListEditor( - values=['one', 'two', 'three', 'four'], - cols=4)) - list = List(Str, ['East of Eden', 'The Grapes of Wrath', - 'Of Mice and Men']) + check_list = List( + editor=CheckListEditor(values=['one', 'two', 'three', 'four'], cols=4) + ) + list = List( + Str, ['East of Eden', 'The Grapes of Wrath', 'Of Mice and Men'] + ) button = Event(0, editor=ButtonEditor(label='Click')) file = File() directory = Directory() - image_enum = Trait(editor=ImageEnumEditor(values=origin_values, - suffix='_origin', - cols=4, - klass=Instance), - *origin_values) + image_enum = Trait( + editor=ImageEnumEditor( + values=origin_values, suffix='_origin', cols=4, klass=Instance + ), + *origin_values, + ) - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # View definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- view = View( - ('|{Enum}', - ('|<[Enumeration]', 'enumeration[Simple]', '_', - 'enumeration[Custom]@', '_', - 'enumeration[Text]*', '_', - 'enumeration[Readonly]~'), - ('|<[Check List]', 'check_list[Simple]', '_', - 'check_list[Custom]@', '_', - 'check_list[Text]*', '_', - 'check_list[Readonly]~') - ), - ('|{Range}', - ('|<[Float Range]', 'float_range[Simple]', '_', - 'float_range[Custom]@', '_', - 'float_range[Text]*', '_', - 'float_range[Readonly]~'), - ('|<[Int Range]', 'int_range[Simple]', '_', - 'int_range[Custom]@', '_', - 'int_range[Text]*', '_', - 'int_range[Readonly]~'), - ('|<[Int Range 2]', 'int_range2[Simple]', '_', - 'int_range2[Custom]@', '_', - 'int_range2[Text]*', '_', - 'int_range2[Readonly]~') - ), - ('|{Misc}', - ('|<[Integer Text]', 'integer_text[Simple]', '_', - 'integer_text[Custom]@', '_', - 'integer_text[Text]*', '_', - 'integer_text[Readonly]~'), - ('|<[Compound]', 'compound[Simple]', '_', - 'compound[Custom]@', '_', - 'compound[Text]*', '_', - 'compound[Readonly]~'), - ('|<[Boolean]', 'boolean[Simple]', '_', - 'boolean[Custom]@', '_', - 'boolean[Text]*', '_', - 'boolean[Readonly]~') - ), - ('|{Color/Font}', - ('|<[Color]', 'color[Simple]', '_', - 'color[Custom]@', '_', - 'color[Text]*', '_', - 'color[Readonly]~'), - ('|<[Font]', 'font[Simple]', '_', - 'font[Custom]@', '_', - 'font[Text]*', '_', - 'font[Readonly]~') - ), - ('|{List}', - ('|<[List]', 'list[Simple]', '_', - 'list[Custom]@', '_', - 'list[Text]*', '_', - 'list[Readonly]~') - ), - ('|{Button}', - ('|<[Button]', 'button[Simple]', '_', - 'button[Custom]@'), - # 'button[Text]*', - # 'button[Readonly]~' ), - ('|<[Image Enum]', 'image_enum[Simple]', '_', - 'image_enum[Custom]@', '_', - 'image_enum[Text]*', '_', - 'image_enum[Readonly]~'), - ('|<[Instance]', 'instance[Simple]', '_', - 'instance[Custom]@', '_', - 'instance[Text]*', '_', - 'instance[Readonly]~'), - ), - ('|{File}', - - ('|<[File]', 'file[Simple]', '_', - 'file[Custom]@', '_', - 'file[Text]*', '_', - 'file[Readonly]~', ), - ('|<[Directory]', 'directory[Simple]', '_', - 'directory[Custom]@', '_', - 'directory[Text]*', '_', - 'directory[Readonly]~') - ), - buttons=['Apply', 'Revert', 'Undo', 'OK'] + ( + '|{Enum}', + ( + '|<[Enumeration]', + 'enumeration[Simple]', + '_', + 'enumeration[Custom]@', + '_', + 'enumeration[Text]*', + '_', + 'enumeration[Readonly]~', + ), + ( + '|<[Check List]', + 'check_list[Simple]', + '_', + 'check_list[Custom]@', + '_', + 'check_list[Text]*', + '_', + 'check_list[Readonly]~', + ), + ), + ( + '|{Range}', + ( + '|<[Float Range]', + 'float_range[Simple]', + '_', + 'float_range[Custom]@', + '_', + 'float_range[Text]*', + '_', + 'float_range[Readonly]~', + ), + ( + '|<[Int Range]', + 'int_range[Simple]', + '_', + 'int_range[Custom]@', + '_', + 'int_range[Text]*', + '_', + 'int_range[Readonly]~', + ), + ( + '|<[Int Range 2]', + 'int_range2[Simple]', + '_', + 'int_range2[Custom]@', + '_', + 'int_range2[Text]*', + '_', + 'int_range2[Readonly]~', + ), + ), + ( + '|{Misc}', + ( + '|<[Integer Text]', + 'integer_text[Simple]', + '_', + 'integer_text[Custom]@', + '_', + 'integer_text[Text]*', + '_', + 'integer_text[Readonly]~', + ), + ( + '|<[Compound]', + 'compound[Simple]', + '_', + 'compound[Custom]@', + '_', + 'compound[Text]*', + '_', + 'compound[Readonly]~', + ), + ( + '|<[Boolean]', + 'boolean[Simple]', + '_', + 'boolean[Custom]@', + '_', + 'boolean[Text]*', + '_', + 'boolean[Readonly]~', + ), + ), + ( + '|{Color/Font}', + ( + '|<[Color]', + 'color[Simple]', + '_', + 'color[Custom]@', + '_', + 'color[Text]*', + '_', + 'color[Readonly]~', + ), + ( + '|<[Font]', + 'font[Simple]', + '_', + 'font[Custom]@', + '_', + 'font[Text]*', + '_', + 'font[Readonly]~', + ), + ), + ( + '|{List}', + ( + '|<[List]', + 'list[Simple]', + '_', + 'list[Custom]@', + '_', + 'list[Text]*', + '_', + 'list[Readonly]~', + ), + ), + ( + '|{Button}', + ('|<[Button]', 'button[Simple]', '_', 'button[Custom]@'), + # 'button[Text]*', + # 'button[Readonly]~' ), + ( + '|<[Image Enum]', + 'image_enum[Simple]', + '_', + 'image_enum[Custom]@', + '_', + 'image_enum[Text]*', + '_', + 'image_enum[Readonly]~', + ), + ( + '|<[Instance]', + 'instance[Simple]', + '_', + 'instance[Custom]@', + '_', + 'instance[Text]*', + '_', + 'instance[Readonly]~', + ), + ), + ( + '|{File}', + ( + '|<[File]', + 'file[Simple]', + '_', + 'file[Custom]@', + '_', + 'file[Text]*', + '_', + 'file[Readonly]~', + ), + ( + '|<[Directory]', + 'directory[Simple]', + '_', + 'directory[Custom]@', + '_', + 'directory[Text]*', + '_', + 'directory[Readonly]~', + ), + ), + buttons=['Apply', 'Revert', 'Undo', 'OK'], ) -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # 'TraitSheetApp' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class TraitSheetApp(wx.App): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Initialize the object: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- def __init__(self, object): self.object = object @@ -190,9 +308,9 @@ def __init__(self, object): wx.App.__init__(self, 1, 'debug.log') self.MainLoop() - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Handle application initialization: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- def OnInit(self): ui = self.object.edit_traits(kind='modal') @@ -202,9 +320,10 @@ def OnInit(self): self.SetTopWindow(ui.control) return True -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # Main program: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- if __name__ == '__main__': TraitSheetApp(TraitsTest()) diff --git a/integrationtests/ui/test_ui2.py b/integrationtests/ui/test_ui2.py index e95ef0be6..2472cdb31 100644 --- a/integrationtests/ui/test_ui2.py +++ b/integrationtests/ui/test_ui2.py @@ -8,41 +8,44 @@ # # Thanks for using Enthought open source! -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Imports: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- import wx -from kiva.traits.kiva_font_trait \ - import KivaFont +from kiva.traits.kiva_font_trait import KivaFont -from enable.traits.api \ - import RGBAColor +from enable.traits.api import RGBAColor -from traits.api \ - import Trait, HasTraits, Str, Int, Range, List, Event, Bool +from traits.api import Trait, HasTraits, Str, Int, Range, List, Event, Bool -from traitsui.api \ - import View, Handler, Item, CheckListEditor, ButtonEditor, FileEditor, \ - DirectoryEditor, ImageEnumEditor +from traitsui.api import ( + View, + Handler, + Item, + CheckListEditor, + ButtonEditor, + FileEditor, + DirectoryEditor, + ImageEnumEditor, +) -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Constants: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- origin_values = ['top left', 'top right', 'bottom left', 'bottom right'] -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'PersonHandler' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class PersonHandler(Handler): - def object_zip_changed(self, info): obj = info.object - enabled = (obj.zip >= 10000) + enabled = obj.zip >= 10000 info.street.enabled = enabled info.city.enabled = enabled info.state.enabled = enabled @@ -54,13 +57,13 @@ def object_zip_changed(self, info): def object_call_changed(self, info): print('You called?') -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # 'WizardHandler' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class WizardHandler(Handler): - def object_sex_changed(self, info): if info.object.sex == 'Female': info.p1.next = 'p3' @@ -69,104 +72,174 @@ def object_sex_changed(self, info): info.p2.next = None def object_name_changed(self, info): - info.p2.enabled = info.p3.enabled = (info.object.name != '') + info.p2.enabled = info.p3.enabled = info.object.name != '' if not info.p2.enabled: info.p2.msg = info.p3.msg = 'You must enter a valid name.' -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # 'Employer' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Employer(HasTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- company = Str() boss = Str() view = View('company', 'boss') -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # 'Person' class -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Person(HasTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- name = Str('David Morrill') age = Int(39) sex = Trait('Male', 'Female') coolness = Range(0.0, 10.0, 10.0) - number = Trait(1, Range(1, 6), - 'one', 'two', 'three', 'four', 'five', 'six') + number = Trait( + 1, Range(1, 6), 'one', 'two', 'three', 'four', 'five', 'six' + ) human = Bool(True) employer = Trait(Employer(company='Enthought, Inc.', boss='eric')) eye_color = RGBAColor - set = List(editor=CheckListEditor( - values=['one', 'two', 'three', 'four'], - cols=4)) + set = List( + editor=CheckListEditor(values=['one', 'two', 'three', 'four'], cols=4) + ) font = KivaFont street = Str() city = Str() state = Str() zip = Int(78663) password = Str() - books = List(Str, ['East of Eden', 'The Grapes of Wrath', - 'Of Mice and Men']) + books = List( + Str, ['East of Eden', 'The Grapes of Wrath', 'Of Mice and Men'] + ) call = Event(0, editor=ButtonEditor(label='Click to call')) info = Str(editor=FileEditor()) location = Str(editor=DirectoryEditor()) - origin = Trait(editor=ImageEnumEditor(values=origin_values, - suffix='_origin', - cols=4, - klass=Employer), - *origin_values) + origin = Trait( + editor=ImageEnumEditor( + values=origin_values, suffix='_origin', cols=4, klass=Employer + ), + *origin_values, + ) nm = Item('name', enabled_when='object.age >= 21') pw = Item('password', defined_when='object.zip == 78664') - view = View(((nm, 'age', 'coolness', - '_', 'eye_color', 'eye_color@', 'eye_color*', 'eye_color~', - '_', 'font', 'font@', 'font*', 'font~', - '_', 'set', 'set@', 'set*', 'set~', - '_', 'sex', 'sex@', 'sex*', 'sex~', - '_', 'human', 'human@', 'human*', 'human~', - '_', 'number', 'number@', 'number*', 'number~', - '_', 'books', '_', 'books@', '_', 'books*', '_', 'books~', - '_', 'info', 'location', 'origin', 'origin@', 'call', - 'employer', 'employer[]@', 'employer*', 'employer~', - pw, - '|<[Person:]'), - (' ', 'street', 'city', 'state', 'zip', '|<[Address:]'), - (nm, nm, nm, nm, nm, nm, nm, nm, nm, nm, nm, nm, nm, nm, - '|<[Names:]'), - '|'), - title='Traits 2 User Interface Test', - handler=PersonHandler(), - buttons=['Apply', 'Revert', 'Undo', 'OK'], - height=0.5) - - wizard = View(('|p1:', 'name', 'age', 'sex'), - ('|p2:', 'street', 'city', 'state', 'zip'), - ('|p3:', 'eye_color', 'origin', 'human'), - handler=WizardHandler()) - -#------------------------------------------------------------------------- + view = View( + ( + ( + nm, + 'age', + 'coolness', + '_', + 'eye_color', + 'eye_color@', + 'eye_color*', + 'eye_color~', + '_', + 'font', + 'font@', + 'font*', + 'font~', + '_', + 'set', + 'set@', + 'set*', + 'set~', + '_', + 'sex', + 'sex@', + 'sex*', + 'sex~', + '_', + 'human', + 'human@', + 'human*', + 'human~', + '_', + 'number', + 'number@', + 'number*', + 'number~', + '_', + 'books', + '_', + 'books@', + '_', + 'books*', + '_', + 'books~', + '_', + 'info', + 'location', + 'origin', + 'origin@', + 'call', + 'employer', + 'employer[]@', + 'employer*', + 'employer~', + pw, + '|<[Person:]', + ), + (' ', 'street', 'city', 'state', 'zip', '|<[Address:]'), + ( + nm, + nm, + nm, + nm, + nm, + nm, + nm, + nm, + nm, + nm, + nm, + nm, + nm, + nm, + '|<[Names:]', + ), + '|', + ), + title='Traits 2 User Interface Test', + handler=PersonHandler(), + buttons=['Apply', 'Revert', 'Undo', 'OK'], + height=0.5, + ) + + wizard = View( + ('|p1:', 'name', 'age', 'sex'), + ('|p2:', 'street', 'city', 'state', 'zip'), + ('|p3:', 'eye_color', 'origin', 'human'), + handler=WizardHandler(), + ) + + +# ------------------------------------------------------------------------- # 'TraitSheetApp' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class TraitSheetApp(wx.App): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Initialize the object: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- def __init__(self, object): self.object = object @@ -175,18 +248,19 @@ def __init__(self, object): self.MainLoop() object.print_traits() - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Handle application initialization: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- def OnInit(self): - #ui = self.object.edit_traits( 'view', kind = 'live' ) + # ui = self.object.edit_traits( 'view', kind = 'live' ) ui = self.object.edit_traits('wizard', kind='wizard') self.SetTopWindow(ui.control) return True -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # Main program: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- TraitSheetApp(Person()) diff --git a/integrationtests/ui/test_ui3.py b/integrationtests/ui/test_ui3.py index 1bb23ab44..d0b73eefb 100644 --- a/integrationtests/ui/test_ui3.py +++ b/integrationtests/ui/test_ui3.py @@ -8,18 +8,18 @@ # # Thanks for using Enthought open source! -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Imports: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- import wx from traits.api import Trait, HasTraits, Str, Int from traitsui.api import Color, View, Group -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Model/View classes: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Employer(HasTraits): @@ -57,25 +57,26 @@ class EmployedPerson(LocatedPerson): extra = Group('employer', '') -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # 'TraitSheetApp' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class TraitSheetApp(wx.App): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Initialize the object: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- def __init__(self): wx.InitAllImageHandlers() wx.App.__init__(self, 1, 'debug.log') self.MainLoop() - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Handle application initialization: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- def OnInit(self): Person().edit_traits() @@ -84,8 +85,9 @@ def OnInit(self): EmployedPerson().edit_traits() return True -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # Main program: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- TraitSheetApp() diff --git a/integrationtests/ui/test_ui4.py b/integrationtests/ui/test_ui4.py index dc3b59c78..fe313461f 100644 --- a/integrationtests/ui/test_ui4.py +++ b/integrationtests/ui/test_ui4.py @@ -8,18 +8,18 @@ # # Thanks for using Enthought open source! -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Imports: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- import wx from traits.api import Trait, HasTraits, Str, Int from traitsui.api import Color, View, Group -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Model classes: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Employer(HasTraits): @@ -49,9 +49,10 @@ class LocatedPerson(Person): class EmployedPerson(LocatedPerson): employer = Trait(Employer()) -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # View classes: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class PersonView(HasTraits): @@ -69,25 +70,26 @@ class LocatedPersonView(PersonView): class EmployedPersonView(LocatedPersonView): extra = Group('employer', '') -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # 'TraitSheetApp' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class TraitSheetApp(wx.App): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Initialize the object: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- def __init__(self): wx.InitAllImageHandlers() wx.App.__init__(self, 1, 'debug.log') self.MainLoop() - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Handle application initialization: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- def OnInit(self): PersonView().edit_traits(context=Person()) @@ -96,8 +98,9 @@ def OnInit(self): EmployedPersonView().edit_traits(context=EmployedPerson()) return True -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # Main program: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- TraitSheetApp() diff --git a/integrationtests/ui/test_ui5.py b/integrationtests/ui/test_ui5.py index d77cf6818..c46bfadc9 100644 --- a/integrationtests/ui/test_ui5.py +++ b/integrationtests/ui/test_ui5.py @@ -11,196 +11,314 @@ """ Traits Test case """ -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Imports: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- import wx -from traits.api \ - import Trait, HasTraits, Str, Int, Range, List, Event, File, Directory, Bool - -from traitsui.api \ - import View, Handler, Item, CheckListEditor, ButtonEditor, FileEditor, \ - DirectoryEditor, ImageEnumEditor, Color, Font - - -#------------------------------------------------------------------------- +from traits.api import ( + Trait, + HasTraits, + Str, + Int, + Range, + List, + Event, + File, + Directory, + Bool, +) + +from traitsui.api import ( + View, + Handler, + Item, + CheckListEditor, + ButtonEditor, + FileEditor, + DirectoryEditor, + ImageEnumEditor, + Color, + Font, +) + + +# ------------------------------------------------------------------------- # Constants: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- origin_values = ['top left', 'top right', 'bottom left', 'bottom right'] -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'Instance' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Instance(HasTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- integer_text = Int(1) - enumeration = Trait('one', 'two', 'three', 'four', 'five', 'six', - cols=3) + enumeration = Trait('one', 'two', 'three', 'four', 'five', 'six', cols=3) float_range = Range(0.0, 10.0, 10.0) int_range = Range(1, 5) boolean = Bool(True) - view = View('integer_text', 'enumeration', 'float_range', - 'int_range', 'boolean') + view = View( + 'integer_text', 'enumeration', 'float_range', 'int_range', 'boolean' + ) + -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'TraitsTestHandler' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class TraitsTestHandler(Handler): - def object_enabled_changed(self, info): enabled = info.object.enabled for i in range(1, 63): getattr(info, 'f%d' % i).enabled = enabled -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # 'TraitsTest' class -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class TraitsTest(HasTraits): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Trait definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- enabled = Bool(True) integer_text = Int(1) - enumeration = Trait('one', 'two', 'three', 'four', 'five', 'six', - cols=3) + enumeration = Trait('one', 'two', 'three', 'four', 'five', 'six', cols=3) float_range = Range(0.0, 10.0, 10.0) int_range = Range(1, 6) int_range2 = Range(1, 50) - compound = Trait(1, Range(1, 6), - 'one', 'two', 'three', 'four', 'five', 'six') + compound = Trait( + 1, Range(1, 6), 'one', 'two', 'three', 'four', 'five', 'six' + ) boolean = Bool(True) instance = Trait(Instance()) color = Color('cyan') font = Font() - check_list = List(editor=CheckListEditor( - values=['one', 'two', 'three', 'four'], - cols=4)) - list = List(Str, ['East of Eden', 'The Grapes of Wrath', - 'Of Mice and Men']) + check_list = List( + editor=CheckListEditor(values=['one', 'two', 'three', 'four'], cols=4) + ) + list = List( + Str, ['East of Eden', 'The Grapes of Wrath', 'Of Mice and Men'] + ) button = Event(0, editor=ButtonEditor(label='Click')) file = File() directory = Directory() - image_enum = Trait(editor=ImageEnumEditor(values=origin_values, - suffix='_origin', - cols=4, - klass=Instance), - *origin_values) + image_enum = Trait( + editor=ImageEnumEditor( + values=origin_values, suffix='_origin', cols=4, klass=Instance + ), + *origin_values, + ) - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # View definitions: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- view = View( - ('|{Enum}', - ('enabled', ), - ('|<[Enumeration]', 'f1:enumeration[Simple]', '_', - 'f2:enumeration[Custom]@', '_', - 'f3:enumeration[Text]*', '_', - 'f4:enumeration[Readonly]~'), - ('|<[Check List]', 'f5:check_list[Simple]', '_', - 'f6:check_list[Custom]@', '_', - 'f7:check_list[Text]*', '_', - 'f8:check_list[Readonly]~') - ), - ('|{Range}', - ('|<[Float Range]', 'f9:float_range[Simple]', '_', - 'f10:float_range[Custom]@', '_', - 'f11:float_range[Text]*', '_', - 'f12:float_range[Readonly]~'), - ('|<[Int Range]', 'f13:int_range[Simple]', '_', - 'f14:int_range[Custom]@', '_', - 'f15:int_range[Text]*', '_', - 'f16:int_range[Readonly]~'), - ('|<[Int Range 2]', 'f17:int_range2[Simple]', '_', - 'f18:int_range2[Custom]@', '_', - 'f19:int_range2[Text]*', '_', - 'f20:int_range2[Readonly]~') - ), - ('|{Misc}', - ('|<[Integer Text]', 'f21:integer_text[Simple]', '_', - 'f22:integer_text[Custom]@', '_', - 'f23:integer_text[Text]*', '_', - 'f24:integer_text[Readonly]~'), - ('|<[Compound]', 'f25:compound[Simple]', '_', - 'f26:compound[Custom]@', '_', - 'f27:compound[Text]*', '_', - 'f28:compound[Readonly]~'), - ('|<[Boolean]', 'f29:boolean[Simple]', '_', - 'f30:boolean[Custom]@', '_', - 'f31:boolean[Text]*', '_', - 'f32:boolean[Readonly]~') - ), - ('|{Color/Font}', - ('|<[Color]', 'f33:color[Simple]', '_', - 'f34:color[Custom]@', '_', - 'f35:color[Text]*', '_', - 'f36:color[Readonly]~'), - ('|<[Font]', 'f37:font[Simple]', '_', - 'f38:font[Custom]@', '_', - 'f39:font[Text]*', '_', - 'f40:font[Readonly]~') - ), - ('|{List}', - ('|<[List]', 'f41:list[Simple]', '_', - 'f42:list[Custom]@', '_', - 'f43:list[Text]*', '_', - 'f44:list[Readonly]~') - ), - ('|{Button}', - ('|<[Button]', 'f45:button[Simple]', '_', - 'f46:button[Custom]@'), - # 'button[Text]*', - # 'button[Readonly]~' ), - ('|<[Image Enum]', 'f47:image_enum[Simple]', '_', - 'f48:image_enum[Custom]@', '_', - 'f49:image_enum[Text]*', '_', - 'f50:image_enum[Readonly]~'), - ('|<[Instance]', 'f51:instance[Simple]', '_', - 'f52:instance[Custom]@', '_', - 'f53:instance[Text]*', '_', - 'f54:instance[Readonly]~'), - ), - ('|{File}', - - ('|<[File]', 'f55:file[Simple]', '_', - 'f56:file[Custom]@', '_', - 'f57:file[Text]*', '_', - 'f58:file[Readonly]~', ), - ('|<[Directory]', 'f59:directory[Simple]', '_', - 'f60:directory[Custom]@', '_', - 'f61:directory[Text]*', '_', - 'f62:directory[Readonly]~') - ), + ( + '|{Enum}', + ('enabled',), + ( + '|<[Enumeration]', + 'f1:enumeration[Simple]', + '_', + 'f2:enumeration[Custom]@', + '_', + 'f3:enumeration[Text]*', + '_', + 'f4:enumeration[Readonly]~', + ), + ( + '|<[Check List]', + 'f5:check_list[Simple]', + '_', + 'f6:check_list[Custom]@', + '_', + 'f7:check_list[Text]*', + '_', + 'f8:check_list[Readonly]~', + ), + ), + ( + '|{Range}', + ( + '|<[Float Range]', + 'f9:float_range[Simple]', + '_', + 'f10:float_range[Custom]@', + '_', + 'f11:float_range[Text]*', + '_', + 'f12:float_range[Readonly]~', + ), + ( + '|<[Int Range]', + 'f13:int_range[Simple]', + '_', + 'f14:int_range[Custom]@', + '_', + 'f15:int_range[Text]*', + '_', + 'f16:int_range[Readonly]~', + ), + ( + '|<[Int Range 2]', + 'f17:int_range2[Simple]', + '_', + 'f18:int_range2[Custom]@', + '_', + 'f19:int_range2[Text]*', + '_', + 'f20:int_range2[Readonly]~', + ), + ), + ( + '|{Misc}', + ( + '|<[Integer Text]', + 'f21:integer_text[Simple]', + '_', + 'f22:integer_text[Custom]@', + '_', + 'f23:integer_text[Text]*', + '_', + 'f24:integer_text[Readonly]~', + ), + ( + '|<[Compound]', + 'f25:compound[Simple]', + '_', + 'f26:compound[Custom]@', + '_', + 'f27:compound[Text]*', + '_', + 'f28:compound[Readonly]~', + ), + ( + '|<[Boolean]', + 'f29:boolean[Simple]', + '_', + 'f30:boolean[Custom]@', + '_', + 'f31:boolean[Text]*', + '_', + 'f32:boolean[Readonly]~', + ), + ), + ( + '|{Color/Font}', + ( + '|<[Color]', + 'f33:color[Simple]', + '_', + 'f34:color[Custom]@', + '_', + 'f35:color[Text]*', + '_', + 'f36:color[Readonly]~', + ), + ( + '|<[Font]', + 'f37:font[Simple]', + '_', + 'f38:font[Custom]@', + '_', + 'f39:font[Text]*', + '_', + 'f40:font[Readonly]~', + ), + ), + ( + '|{List}', + ( + '|<[List]', + 'f41:list[Simple]', + '_', + 'f42:list[Custom]@', + '_', + 'f43:list[Text]*', + '_', + 'f44:list[Readonly]~', + ), + ), + ( + '|{Button}', + ('|<[Button]', 'f45:button[Simple]', '_', 'f46:button[Custom]@'), + # 'button[Text]*', + # 'button[Readonly]~' ), + ( + '|<[Image Enum]', + 'f47:image_enum[Simple]', + '_', + 'f48:image_enum[Custom]@', + '_', + 'f49:image_enum[Text]*', + '_', + 'f50:image_enum[Readonly]~', + ), + ( + '|<[Instance]', + 'f51:instance[Simple]', + '_', + 'f52:instance[Custom]@', + '_', + 'f53:instance[Text]*', + '_', + 'f54:instance[Readonly]~', + ), + ), + ( + '|{File}', + ( + '|<[File]', + 'f55:file[Simple]', + '_', + 'f56:file[Custom]@', + '_', + 'f57:file[Text]*', + '_', + 'f58:file[Readonly]~', + ), + ( + '|<[Directory]', + 'f59:directory[Simple]', + '_', + 'f60:directory[Custom]@', + '_', + 'f61:directory[Text]*', + '_', + 'f62:directory[Readonly]~', + ), + ), buttons=['Apply', 'Revert', 'Undo', 'OK'], - handler=TraitsTestHandler() + handler=TraitsTestHandler(), ) -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # 'TraitSheetApp' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class TraitSheetApp(wx.App): - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Initialize the object: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- def __init__(self, object): self.object = object @@ -208,9 +326,9 @@ def __init__(self, object): wx.App.__init__(self, 1, 'debug.log') self.MainLoop() - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- # Handle application initialization: - #------------------------------------------------------------------------- + # ------------------------------------------------------------------------- def OnInit(self): ui = self.object.edit_traits(kind='live') @@ -220,8 +338,9 @@ def OnInit(self): self.SetTopWindow(ui.control) return True -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # Main program: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- TraitSheetApp(TraitsTest()) diff --git a/integrationtests/ui/tree_editor_test.py b/integrationtests/ui/tree_editor_test.py index 4626cb002..8112523c4 100644 --- a/integrationtests/ui/tree_editor_test.py +++ b/integrationtests/ui/tree_editor_test.py @@ -10,21 +10,35 @@ """ Test case for the traits tree editor.""" -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Imports: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- from traits.api import HasTraits, Str, Regex, List, Instance -from traitsui.api import TreeEditor, TreeNode, View, Item, VSplit, \ - HGroup, Handler, spring +from traitsui.api import ( + TreeEditor, + TreeNode, + View, + Item, + VSplit, + HGroup, + Handler, + spring, +) from traitsui.menu import Menu, Action, Separator -from traitsui.editors.tree_editor import NewAction, CopyAction, \ - CutAction, PasteAction, DeleteAction, RenameAction +from traitsui.editors.tree_editor import ( + NewAction, + CopyAction, + CutAction, + PasteAction, + DeleteAction, + RenameAction, +) -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'Employee' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Employee(HasTraits): @@ -35,18 +49,20 @@ class Employee(HasTraits): def default_title(self): self.title = 'Senior Engineer' -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # 'Department' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Department(HasTraits): name = Str('') employees = List(Employee) -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # 'Company' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Company(HasTraits): @@ -54,160 +70,163 @@ class Company(HasTraits): departments = List(Department) employees = List(Employee) -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # 'Partner' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class Partner(HasTraits): name = Str('') company = Instance(Company) -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # Create a hierarchy: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- -jason = Employee( - name='Jason', - title='Sr. Engineer', - phone='536-1057') +jason = Employee(name='Jason', title='Sr. Engineer', phone='536-1057') -mike = Employee( - name='Mike', - title='Sr. Engineer', - phone='536-1057') +mike = Employee(name='Mike', title='Sr. Engineer', phone='536-1057') -dave = Employee( - name='Dave', - title='Sr. Engineer', - phone='536-1057') +dave = Employee(name='Dave', title='Sr. Engineer', phone='536-1057') -martin = Employee( - name='Martin', - title='Sr. Engineer', - phone='536-1057') +martin = Employee(name='Martin', title='Sr. Engineer', phone='536-1057') -duncan = Employee( - name='Duncan', - title='Sr. Engineer') +duncan = Employee(name='Duncan', title='Sr. Engineer') partner = Partner( name='eric', company=Company( name='Enthought, Inc.', departments=[ - Department( - name='Business', - employees=[jason, mike] - ), - Department( - name='Scientific', - employees=[dave, martin, duncan] - ) + Department(name='Business', employees=[jason, mike]), + Department(name='Scientific', employees=[dave, martin, duncan]), ], - employees=[dave, martin, mike, duncan, jason] - ) + employees=[dave, martin, mike, duncan, jason], + ), ) -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # Define the tree trait editor: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- no_view = View() tree_editor = TreeEditor( nodes=[ - TreeNode(node_for=[Company], - auto_open=True, - children='', - label='name', - view=View(['name', '|<'])), - TreeNode(node_for=[Company], - auto_open=True, - children='departments', - label='=Departments', - view=no_view, - add=[Department]), - TreeNode(node_for=[Company], - auto_open=True, - children='employees', - label='=Employees', - view=no_view, - add=[Employee]), - TreeNode(node_for=[Department], - auto_open=True, - children='employees', - label='name', - menu=Menu(NewAction, - Separator(), - DeleteAction, - Separator(), - RenameAction, - Separator(), - CopyAction, - CutAction, - PasteAction), - view=View(['name', '|<']), - add=[Employee]), - TreeNode(node_for=[Employee], - auto_open=True, - label='name', - menu=Menu(NewAction, - Separator(), - Action(name='Default title', - action='object.default_title'), - Action(name='Department', - action='handler.employee_department(editor,object)'), - Separator(), - CopyAction, - CutAction, - PasteAction, - Separator(), - DeleteAction, - Separator(), - RenameAction), - view=View(VSplit(HGroup('3', 'name'), - HGroup('9', 'title'), - HGroup('phone'), - spring, - id='vsplit'), - id='traitsui.test.tree_editor_test.employee', - dock='vertical')) + TreeNode( + node_for=[Company], + auto_open=True, + children='', + label='name', + view=View(['name', '|<']), + ), + TreeNode( + node_for=[Company], + auto_open=True, + children='departments', + label='=Departments', + view=no_view, + add=[Department], + ), + TreeNode( + node_for=[Company], + auto_open=True, + children='employees', + label='=Employees', + view=no_view, + add=[Employee], + ), + TreeNode( + node_for=[Department], + auto_open=True, + children='employees', + label='name', + menu=Menu( + NewAction, + Separator(), + DeleteAction, + Separator(), + RenameAction, + Separator(), + CopyAction, + CutAction, + PasteAction, + ), + view=View(['name', '|<']), + add=[Employee], + ), + TreeNode( + node_for=[Employee], + auto_open=True, + label='name', + menu=Menu( + NewAction, + Separator(), + Action(name='Default title', action='object.default_title'), + Action( + name='Department', + action='handler.employee_department(editor,object)', + ), + Separator(), + CopyAction, + CutAction, + PasteAction, + Separator(), + DeleteAction, + Separator(), + RenameAction, + ), + view=View( + VSplit( + HGroup('3', 'name'), + HGroup('9', 'title'), + HGroup('phone'), + spring, + id='vsplit', + ), + id='traitsui.test.tree_editor_test.employee', + dock='vertical', + ), + ), ] ) -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- # 'TreeHandler' class: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- class TreeHandler(Handler): - def employee_department(self, editor, object): dept = editor.get_parent(object) print('%s works in the %s department.' % (object.name, dept.name)) -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # Define the View to use: -#------------------------------------------------------------------------- - -view = View([Item(name='company', - id='company', - editor=tree_editor, - resizable=True), '|<>'], - title='Company Structure', - id='traitsui.tests.tree_editor_test', - dock='horizontal', - drop_class=HasTraits, - handler=TreeHandler(), - buttons=['Undo', 'OK', 'Cancel'], - resizable=True, - width=.3, - height=.3) - -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- + +view = View( + [ + Item(name='company', id='company', editor=tree_editor, resizable=True), + '|<>', + ], + title='Company Structure', + id='traitsui.tests.tree_editor_test', + dock='horizontal', + drop_class=HasTraits, + handler=TreeHandler(), + buttons=['Undo', 'OK', 'Cancel'], + resizable=True, + width=0.3, + height=0.3, +) + +# ------------------------------------------------------------------------- # Edit it: -#------------------------------------------------------------------------- +# ------------------------------------------------------------------------- if __name__ == '__main__': partner.configure_traits(view=view) diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 000000000..f658121cd --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,4 @@ +[tool.black] +line-length = 79 +target-version = ['py36', 'py37', 'py38'] +skip-string-normalization = true diff --git a/setup.cfg b/setup.cfg index bc5b25304..05611d446 100644 --- a/setup.cfg +++ b/setup.cfg @@ -7,5 +7,4 @@ ignore = # codes we are ignoring pending clean-up F401,F841 # codes for formatting pending clean-up - E116,E121,E123,E126,E127,E128,E203,E226,E241,E251,E265,E272,E302,E303,E305,E306,E501 - W291,W293,W504 + E203,E265,E501,W291 diff --git a/setup.py b/setup.py index 0e2caba9a..01ba2bd83 100644 --- a/setup.py +++ b/setup.py @@ -71,7 +71,7 @@ def read_module(module, package='traitsui'): - """ Read a simple .py file from traitsui in a safe way. + """Read a simple .py file from traitsui in a safe way. It would be simpler to import the file, but that can be problematic in an unknown system, so we exec the file instead and extract the variables. @@ -81,7 +81,7 @@ def read_module(module, package='traitsui'): """ base_dir = os.path.dirname(__file__) module_name = package + '.' + module - path = os.path.join(base_dir, package, module+'.py') + path = os.path.join(base_dir, package, module + '.py') with open(path, 'r', encoding='utf-8') as fp: code = compile(fp.read(), module_name, 'exec') context = {} @@ -109,6 +109,7 @@ def _git_info(): If Git is available, but the version command fails (most likely because there's no Git repository here). """ + def _minimal_ext_cmd(cmd): # construct minimal environment env = {} @@ -121,7 +122,9 @@ def _minimal_ext_cmd(cmd): env['LANG'] = 'C' env['LC_ALL'] = 'C' out = subprocess.Popen( - cmd, stdout=subprocess.PIPE, env=env, + cmd, + stdout=subprocess.PIPE, + env=env, ).communicate()[0] return out @@ -308,7 +311,9 @@ def additional_commands(): version=__version__, author='David C. Morrill, et. al.', author_email='dmorrill@enthought.com', - classifiers=[c.strip() for c in """\ + classifiers=[ + c.strip() + for c in """\ Development Status :: 5 - Production/Stable Intended Audience :: Developers Intended Audience :: Science/Research @@ -326,7 +331,9 @@ def additional_commands(): Topic :: Scientific/Engineering Topic :: Software Development Topic :: Software Development :: Libraries - """.splitlines() if len(c.strip()) > 0], + """.splitlines() + if len(c.strip()) > 0 + ], description='traitsui: traits-capable user interfaces', long_description=LONG_DESCRIPTION, long_description_content_type="text/x-rst", @@ -348,7 +355,8 @@ def additional_commands(): 'wx/images/*', 'qt4/images/*', 'testing/data/*', - ]), + ] + ), packages=find_packages(), entry_points={ 'traitsui.toolkits': [ @@ -359,7 +367,7 @@ def additional_commands(): ], 'etsdemo_data': [ 'demo = traitsui.extras._demo_info:info', - ] + ], }, platforms=["Windows", "Linux", "Mac OS-X", "Unix", "Solaris"], python_requires=">=3.6", diff --git a/traitsui/__init__.py b/traitsui/__init__.py index 2c7bf48f3..e381c4456 100644 --- a/traitsui/__init__.py +++ b/traitsui/__init__.py @@ -23,12 +23,13 @@ "docs": ["enthought-sphinx-theme", "sphinx"], "demo": [ # to be deprecated, see enthought/traitsui#950 - "configobj", "docutils", + "configobj", + "docutils", ], "examples": [ # Dependencies for examples "apptools", - "chaco", # for a very simple example, see enthought/traitsui#1139 + "chaco", # for a very simple example, see enthought/traitsui#1139 "h5py", "numpy", "pandas", @@ -38,20 +39,20 @@ # Optional dependencies for certain editors which may not be needed by # projects. If they are absent, ``traitsui.api``` should still be # importable and the relevant tests should be skipped. - "numpy", # For ArrayEditor and DataFrameEditor + "numpy", # For ArrayEditor and DataFrameEditor "pandas", # For DataFrameEditor ], "test": [ # Dependencies for running test suites. "packaging", - "numpy" + "numpy", ], } # ============================= Test Loader ================================== def load_tests(loader, standard_tests, pattern): - """ Custom test loading function that enables test filtering using regex + """Custom test loading function that enables test filtering using regex exclusion pattern. Parameters @@ -76,6 +77,7 @@ def load_tests(loader, standard_tests, pattern): # Make sure the right toolkit is up and running before importing tests from traitsui.toolkit import toolkit + toolkit() if ETSConfig.toolkit.startswith("qt"): diff --git a/traitsui/api.py b/traitsui/api.py index 1bc05d9ba..96ce8439c 100644 --- a/traitsui/api.py +++ b/traitsui/api.py @@ -443,7 +443,7 @@ def raise_to_debug(): - """ When we would otherwise silently swallow an exception, call this instead + """When we would otherwise silently swallow an exception, call this instead to allow people to set the TRAITS_DEBUG environment variable and get the exception. """ diff --git a/traitsui/base_panel.py b/traitsui/base_panel.py index 0b7e78544..557143a7d 100644 --- a/traitsui/base_panel.py +++ b/traitsui/base_panel.py @@ -17,7 +17,7 @@ class BasePanel(ActionController): - """ Base class for Traits UI panels and dialog boxes. + """Base class for Traits UI panels and dialog boxes. Concrete subclasses of BasePanel are the Python-side owners of the top-level toolkit control for a UI. They also implement the Pyface @@ -31,13 +31,13 @@ class BasePanel(ActionController): ui = Instance("traitsui.ui.UI") def default_icon(self): - """ Return a default icon for a TraitsUI dialog. """ + """Return a default icon for a TraitsUI dialog.""" from pyface.image_resource import ImageResource return ImageResource("frame.png") def check_button(self, buttons, action): - """ Adds *action* to the system buttons list for this dialog, if it is + """Adds *action* to the system buttons list for this dialog, if it is not already in the list. """ name = action.name @@ -47,15 +47,13 @@ def check_button(self, buttons, action): buttons.append(action) def is_button(self, action, name): - """ Returns whether a specified action button is a system button. - """ + """Returns whether a specified action button is a system button.""" if isinstance(action, str): return action == name return action.name == name def coerce_button(self, action): - """ Coerces a string to an Action if necessary. - """ + """Coerces a string to an Action if necessary.""" if isinstance(action, str): return Action( name=action, action="" if action in SystemButtons else "?" @@ -65,26 +63,22 @@ def coerce_button(self, action): # Button handlers -------------------------------------------------------- def _on_undo(self, event=None): - """ Handles an "Undo" change request. - """ + """Handles an "Undo" change request.""" self.ui.history.undo() def _on_redo(self, event=None): - """ Handles a "Redo" change request. - """ + """Handles a "Redo" change request.""" self.ui.history.redo() def _on_revert(self, event=None): - """ Handles a request to revert all changes. - """ + """Handles a request to revert all changes.""" ui = self.ui if ui.history is not None: ui.history.revert() ui.handler.revert(ui.info) def _on_help(self, event=None): - """ Handles the user clicking the Help button. - """ + """Handles the user clicking the Help button.""" self.ui.handler.show_help(self.ui.info) # ------------------------------------------------------------------------ @@ -92,7 +86,7 @@ def _on_help(self, event=None): # ------------------------------------------------------------------------ def perform(self, action, event): - """ Dispatches the action to be handled by the handler. + """Dispatches the action to be handled by the handler. Parameters ---------- @@ -110,7 +104,7 @@ def perform(self, action, event): self.ui.do_undoable(handler.perform, self.ui.info, action, event) def add_to_menu(self, menu_item): - """ Adds a menu item to the menu bar being constructed. + """Adds a menu item to the menu bar being constructed. The bulk of the back-end work is done in Pyface. This code is simply responsible for hooking up radio groups, checkboxes, and enabled @@ -141,7 +135,7 @@ def add_to_menu(self, menu_item): self.ui.add_checked(action.checked_when, menu_item) def add_to_toolbar(self, toolbar_item): - """ Adds a menu item to the menu bar being constructed. + """Adds a menu item to the menu bar being constructed. The bulk of the back-end work is done in Pyface. This code is simply responsible for hooking up radio groups, checkboxes, and enabled @@ -158,7 +152,7 @@ def add_to_toolbar(self, toolbar_item): self.add_to_menu(toolbar_item) def can_add_to_menu(self, action): - """ Should the toolbar action be defined in the user interface. + """Should the toolbar action be defined in the user interface. This simply calls the analagous menu as logic and APIs are identical. @@ -179,7 +173,7 @@ def can_add_to_menu(self, action): return self.ui.eval_when(action.defined_when) def can_add_to_toolbar(self, action): - """ Should the toolbar action be defined in the user interface. + """Should the toolbar action be defined in the user interface. This simply calls the analagous menu as logic and APIs are identical. diff --git a/traitsui/basic_editor_factory.py b/traitsui/basic_editor_factory.py index a528da595..169ddbcc6 100644 --- a/traitsui/basic_editor_factory.py +++ b/traitsui/basic_editor_factory.py @@ -18,8 +18,8 @@ class BasicEditorFactory(EditorFactory): - """ Base class for editor factories that use the same class for creating - all editor styles. + """Base class for editor factories that use the same class for creating + all editor styles. """ # ------------------------------------------------------------------------- @@ -34,28 +34,28 @@ class BasicEditorFactory(EditorFactory): # ------------------------------------------------------------------------- def _get_simple_editor_class(self): - """ Returns the editor class to use for "simple" style views. + """Returns the editor class to use for "simple" style views. Overridden to return the value of the 'klass' trait. """ return self.klass def _get_custom_editor_class(self): - """ Returns the editor class to use for "custom" style views. + """Returns the editor class to use for "custom" style views. Overridden to return the value of the 'klass' trait. """ return self.klass def _get_text_editor_class(self): - """ Returns the editor class to use for "text" style views. + """Returns the editor class to use for "text" style views. Overridden to return the value of the 'klass' trait. """ return self.klass def _get_readonly_editor_class(self): - """ Returns the editor class to use for "readonly" style views. + """Returns the editor class to use for "readonly" style views. Overridden to return the value of the 'klass' trait. """ diff --git a/traitsui/color_column.py b/traitsui/color_column.py index 7bdf22313..320ec5654 100644 --- a/traitsui/color_column.py +++ b/traitsui/color_column.py @@ -15,7 +15,7 @@ class ColorColumn(ObjectColumn): - """ Table column object for RGBColor traits. """ + """Table column object for RGBColor traits.""" #: For display by default. style = "readonly" @@ -23,8 +23,8 @@ class ColorColumn(ObjectColumn): # -- ObjectColumn Overrides ----------------------------------------------- def get_cell_color(self, object): - """ Returns the cell background color for the column for a specified - object. + """Returns the cell background color for the column for a specified + object. """ color_values = getattr(object, self.name + "_", None) if color_values is None: @@ -36,8 +36,7 @@ def get_cell_color(self, object): return tk_color def get_value(self, object): - """ Gets the value of the column for a specified object. - """ + """Gets the value of the column for a specified object.""" value = getattr(self.get_object(object), self.name, "") if isinstance(value, tuple): value = self._float_rgb_tuple_to_str(value) @@ -48,10 +47,10 @@ def get_value(self, object): # -- Private Methods ------------------------------------------------------ def _as_int_rgb_tuple(self, color_values): - """ Returns object color as RGB integers. """ + """Returns object color as RGB integers.""" return tuple(int(255 * v + 0.5) for v in color_values) def _float_rgb_tuple_to_str(self, color_values): - """ Returns object color as RGB floats. """ + """Returns object color as RGB floats.""" csv = ", ".join("{:5.3f}".format(x) for x in color_values) return "({})".format(csv) diff --git a/traitsui/context_value.py b/traitsui/context_value.py index 8bd5b5623..4e56812a7 100644 --- a/traitsui/context_value.py +++ b/traitsui/context_value.py @@ -63,7 +63,7 @@ class MyObject(HasTraits): class ContextValue(HasStrictTraits): - """ Defines the name of a context value that can be bound to an editor + """Defines the name of a context value that can be bound to an editor Resolution of the name follows the same rules as for context values in Item objects: if there is no dot in it then it is treated as an @@ -92,7 +92,7 @@ def __init__(self, name): def CVType(type, **metadata): - """ Factory that creates a union of a trait type and a ContextValue trait. + """Factory that creates a union of a trait type and a ContextValue trait. This also sets up one-way synchronization to the editor if no other synchronization is specified. diff --git a/traitsui/delegating_handler.py b/traitsui/delegating_handler.py index c392ac44c..2604ebf84 100644 --- a/traitsui/delegating_handler.py +++ b/traitsui/delegating_handler.py @@ -29,8 +29,8 @@ class DelegatingHandler(Handler): - """ A handler that delegates the handling of events to a set of - sub-handlers. + """A handler that delegates the handling of events to a set of + sub-handlers. """ # -- Public 'DelegatingHandler' Interface --------------------------------- @@ -50,16 +50,16 @@ class DelegatingHandler(Handler): # -- Public Methods ------------------------------------------------------- def closed(self, info, is_ok): - """ Handles the user interface being closed by the user. + """Handles the user interface being closed by the user. - This method is overridden here to unregister any dispatchers that - were set up in the *init()* method. + This method is overridden here to unregister any dispatchers that + were set up in the *init()* method. """ for d in self._dispatchers: d.remove() def init(self, info): - """ Initializes the controls of a user interface. + """Initializes the controls of a user interface. This method is called after all user interface elements have been created, but before the user interface is displayed. Use this method to @@ -103,7 +103,7 @@ def init(self, info): "\tto method [%s] on handler[%s]", name, h ) method = getattr(h, name) - trait_name = prefix[col + 1:] + trait_name = prefix[col + 1 :] self._dispatchers.append( Dispatcher(method, info, object, trait_name) ) @@ -143,8 +143,7 @@ def init(self, info): return True def _create_delegate(self, h, name): - """ Quick fix for handler methods that are currently left out! - """ + """Quick fix for handler methods that are currently left out!""" def delegate(*args, **kw): method = getattr(h, name) diff --git a/traitsui/dock_window_theme.py b/traitsui/dock_window_theme.py index d95ecb6a7..f7cf7a1bd 100644 --- a/traitsui/dock_window_theme.py +++ b/traitsui/dock_window_theme.py @@ -18,8 +18,7 @@ class DockWindowTheme(HasPrivateTraits): - """ Defines the theme style information for a DockWindow and its components. - """ + """Defines the theme style information for a DockWindow and its components.""" # -- Public Trait Definitions --------------------------------------------- @@ -96,8 +95,7 @@ def _get_tab_hover_edge_bitmap(self): def dock_window_theme(theme=None): - """ Get or set the default DockWindow theme. - """ + """Get or set the default DockWindow theme.""" global _dock_window_theme if _dock_window_theme is None: diff --git a/traitsui/dockable_view_element.py b/traitsui/dockable_view_element.py index aad1b4fd2..593d85072 100644 --- a/traitsui/dockable_view_element.py +++ b/traitsui/dockable_view_element.py @@ -30,8 +30,8 @@ class DockableViewElement(HasPrivateTraits, IDockable): - """ Allows Traits UIs and Traits UI elements to be docked in external - Pyface DockWindow windows. + """Allows Traits UIs and Traits UI elements to be docked in external + Pyface DockWindow windows. """ # ------------------------------------------------------------------------- @@ -50,8 +50,8 @@ class DockableViewElement(HasPrivateTraits, IDockable): # -- IDockable interface -------------------------------------------------- def dockable_should_close(self): - """ Should the current DockControl be closed before creating the new - one? + """Should the current DockControl be closed before creating the new + one? """ element = self.element if element is None: @@ -86,8 +86,7 @@ def dockable_should_close(self): return self.should_close or (self.element is None) def dockable_get_control(self, parent): - """ Gets a control that can be docked into a DockWindow. - """ + """Gets a control that can be docked into a DockWindow.""" # Create the new UI: ui = self._view.ui( self._context, @@ -108,8 +107,7 @@ def dockable_get_control(self, parent): return ui.control def dockable_init_dockcontrol(self, dock_control): - """ Allows the object to override the default DockControl settings. - """ + """Allows the object to override the default DockControl settings.""" dockable = self if self.element is not None: dockable = DockableViewElement( @@ -122,8 +120,7 @@ def dockable_init_dockcontrol(self, dock_control): ) def close_dock_control(self, dock_control, abort): - """ Handles the closing of a DockControl containing a Traits UI. - """ + """Handles the closing of a DockControl containing a Traits UI.""" ui = self.ui # Ask the traits UI handler if it is OK to close the window: diff --git a/traitsui/editor.py b/traitsui/editor.py index 72fba284a..4aaab2850 100644 --- a/traitsui/editor.py +++ b/traitsui/editor.py @@ -49,8 +49,8 @@ class Editor(HasPrivateTraits): - """ Represents an editing control for an object trait in a Traits-based - user interface. + """Represents an editing control for an object trait in a Traits-based + user interface. """ #: The UI (user interface) this editor is part of: @@ -134,7 +134,7 @@ class Editor(HasPrivateTraits): # -- Abstract methods --------------------------------------------------- def init(self, parent): - """ Create and initialize the underlying toolkit widget. + """Create and initialize the underlying toolkit widget. This method must be overriden by subclasses. Implementations must ensure that the :attr:`control` trait is set to an appropriate @@ -148,14 +148,14 @@ def init(self, parent): raise NotImplementedError("This method must be overriden.") def update_editor(self): - """ Updates the editor when the value changes externally to the editor. + """Updates the editor when the value changes externally to the editor. This should normally be overridden in a subclass. """ pass def error(self, excp): - """ Handles an error that occurs while setting the object's trait value. + """Handles an error that occurs while setting the object's trait value. This should normally be overridden in a subclass. @@ -167,14 +167,14 @@ def error(self, excp): pass def set_focus(self): - """ Assigns focus to the editor's underlying toolkit widget. + """Assigns focus to the editor's underlying toolkit widget. This method must be overriden by subclasses. """ raise NotImplementedError("This method must be overriden.") def set_tooltip_text(self, control, text): - """ Sets the tooltip for a toolkit control to the provided text. + """Sets the tooltip for a toolkit control to the provided text. This method must be overriden by subclasses. @@ -188,7 +188,7 @@ def set_tooltip_text(self, control, text): raise NotImplementedError("This method must be overriden.") def string_value(self, value, format_func=None): - """ Returns the text representation of a specified object trait value. + """Returns the text representation of a specified object trait value. This simply delegates to the factory's `string_value` method. Sub-classes may choose to override the default implementation. @@ -203,7 +203,7 @@ def string_value(self, value, format_func=None): return self.factory.string_value(value, format_func) def restore_prefs(self, prefs): - """ Restores saved user preference information for the editor. + """Restores saved user preference information for the editor. Editors with state may choose to override this. It will only be used if the editor has an `id` value. @@ -216,7 +216,7 @@ def restore_prefs(self, prefs): pass def save_prefs(self): - """ Returns any user preference information for the editor. + """Returns any user preference information for the editor. Editors with state may choose to override this. It will only be used if the editor has an `id` value. @@ -232,7 +232,7 @@ def save_prefs(self): # -- Editor life-cycle methods ------------------------------------------ def prepare(self, parent): - """ Finish setting up the editor. + """Finish setting up the editor. Parameters ---------- @@ -249,7 +249,7 @@ def prepare(self, parent): self.update_editor() def dispose(self): - """ Disposes of the contents of an editor. + """Disposes of the contents of an editor. This disconnects any synchronised values and resets references to other objects. @@ -279,7 +279,7 @@ def dispose(self): # -- Undo/redo methods -------------------------------------------------- def log_change(self, undo_factory, *undo_args): - """ Logs a change made in the editor with undo/redo history. + """Logs a change made in the editor with undo/redo history. Parameters ---------- @@ -305,7 +305,7 @@ def log_change(self, undo_factory, *undo_args): history.extend(item) def get_undo_item(self, object, name, old_value, new_value): - """ Creates an undo history entry. + """Creates an undo history entry. Can be overridden in a subclass for special value types. @@ -334,7 +334,7 @@ def sync_value( is_list=False, is_event=False, ): - """ Synchronize an editor trait and a user object trait. + """Synchronize an editor trait and a user object trait. Also sets the initial value of the editor trait from the user object trait (for modes 'from' and 'both'), and the initial @@ -397,7 +397,7 @@ def sync_value( # -- Utility methods ----------------------------------------------------- def parse_extended_name(self, name): - """ Extract the object, name and a getter from an extended name + """Extract the object, name and a getter from an extended name Parameters ---------- @@ -421,7 +421,7 @@ def parse_extended_name(self, name): return (object, name, partial(xgetattr, object, name)) def set_tooltip(self, control=None): - """ Sets the tooltip for a specified toolkit control. + """Sets the tooltip for a specified toolkit control. This uses the tooltip_text method to get the text to use. @@ -448,7 +448,7 @@ def set_tooltip(self, control=None): return True def tooltip_text(self): - """ Get the text for a tooltip, checking various sources. + """Get the text for a tooltip, checking various sources. This checks for text from, in order: @@ -482,7 +482,7 @@ def tooltip_text(self): @contextmanager def no_trait_update(self, name): - """ Context manager that blocks updates from the named trait. """ + """Context manager that blocks updates from the named trait.""" if name in self._no_trait_update: yield return @@ -495,7 +495,7 @@ def no_trait_update(self, name): @contextmanager def raise_to_debug(self): - """ Context manager that uses raise to debug to raise exceptions. """ + """Context manager that uses raise to debug to raise exceptions.""" try: yield except Exception: @@ -505,7 +505,7 @@ def raise_to_debug(self): @contextmanager def updating_value(self): - """ Context manager to handle updating value. """ + """Context manager to handle updating value.""" if self.updating: yield return @@ -521,8 +521,7 @@ def updating_value(self): # ------------------------------------------------------------------------ def __init__(self, parent, **traits): - """ Initializes the editor object. - """ + """Initializes the editor object.""" super().__init__(**traits) try: self.old_value = getattr(self.object, self.name) @@ -542,7 +541,7 @@ def __init__(self, parent, **traits): # ------------------------------------------------------------------------ def _update_editor(self, object, name, old_value, new_value): - """ Performs updates when the object trait changes. + """Performs updates when the object trait changes. This is designed to be used as a trait listener. """ @@ -589,7 +588,7 @@ def _update_editor(self, object, name, old_value, new_value): self.update_editor() def _sync_values(self): - """ Initialize and synchronize editor and factory traits + """Initialize and synchronize editor and factory traits Initializes and synchronizes (as needed) editor traits with the value of corresponding factory traits. The name of the factory @@ -650,7 +649,7 @@ def _sync_values(self): setattr(self, name, value) def _bind_from(self, key, user_object, xuser_name, editor_name, is_list): - """ Bind trait change handlers from a user object to the editor. + """Bind trait change handlers from a user object to the editor. Parameters ---------- @@ -686,7 +685,7 @@ def user_list_modified(event): with self.no_trait_update(key), self.raise_to_debug(): n = event.index getattr(self, editor_name)[ - n:n + len(event.removed) + n : n + len(event.removed) ] = event.added items = xuser_name + "_items" @@ -694,7 +693,7 @@ def user_list_modified(event): self._user_to.append((user_object, items, user_list_modified)) def _bind_to(self, key, user_object, xuser_name, editor_name, is_list): - """ Bind trait change handlers from a user object to the editor. + """Bind trait change handlers from a user object to the editor. Parameters ---------- @@ -728,7 +727,7 @@ def editor_list_modified(event): with self.no_trait_update(key), self.raise_to_debug(): n = event.index value = xgetattr(user_object, xuser_name) - value[n:n + len(event.removed)] = event.added + value[n : n + len(event.removed)] = event.added self.on_trait_change(editor_list_modified, editor_name + "_items") self._user_from.append( @@ -736,7 +735,7 @@ def editor_list_modified(event): ) def __set_value(self, value): - """ Set the value of the trait the editor is editing. + """Set the value of the trait the editor is editing. This calls the appropriate setattr method on the handler to perform the actual change. @@ -760,7 +759,7 @@ def __set_value(self, value): @cached_property def _get_context_object(self): - """ Returns the context object the editor is using + """Returns the context object the editor is using In some cases a proxy object is edited rather than an object directly in the context, in which case we return ``self.object``. @@ -776,22 +775,19 @@ def _get_context_object(self): @cached_property def _get_extended_name(self): - """ Returns the extended trait name being edited. - """ + """Returns the extended trait name being edited.""" return ("%s.%s" % (self.object_name, self.name)).split(".", 1)[1] def _get_value_trait(self): - """ Returns the trait the editor is editing (Property implementation). - """ + """Returns the trait the editor is editing (Property implementation).""" return self.object.trait(self.name) def _get_value(self): - """ Returns the value of the trait the editor is editing. - """ + """Returns the value of the trait the editor is editing.""" return getattr(self.object, self.name, Undefined) def _set_value(self, value): - """ Set the value of the trait the editor is editing. + """Set the value of the trait the editor is editing. Dispatches via the TraitsUI Undo/Redo mechanisms to make change reversible, if desired. @@ -800,6 +796,5 @@ def _set_value(self, value): self.ui.do_undoable(self.__set_value, value) def _get_str_value(self): - """ Returns the text representation of the object trait. - """ + """Returns the text representation of the object trait.""" return self.string_value(getattr(self.object, self.name, Undefined)) diff --git a/traitsui/editor_factory.py b/traitsui/editor_factory.py index 86b7ef6b0..8c971aab5 100644 --- a/traitsui/editor_factory.py +++ b/traitsui/editor_factory.py @@ -34,8 +34,8 @@ class EditorFactory(HasPrivateTraits): - """ Represents a factory for creating the Editor objects in a Traits-based - user interface. + """Represents a factory for creating the Editor objects in a Traits-based + user interface. """ # ------------------------------------------------------------------------- @@ -77,20 +77,19 @@ class EditorFactory(HasPrivateTraits): readonly_editor_class = Property() def __init__(self, *args, **traits): - """ Initializes the factory object. - """ + """Initializes the factory object.""" HasPrivateTraits.__init__(self, **traits) self.init(*args) def init(self): - """ Performs any initialization needed after all constructor traits - have been set. + """Performs any initialization needed after all constructor traits + have been set. """ pass def named_value(self, name, ui): - """ Returns the value of a specified extended name of the form: name or - context_object_name.name[.name...]: + """Returns the value of a specified extended name of the form: name or + context_object_name.name[.name...]: """ names = name.split(".") @@ -114,8 +113,7 @@ def named_value(self, name, ui): # ------------------------------------------------------------------------- def simple_editor(self, ui, object, name, description, parent): - """ Generates an editor using the "simple" style. - """ + """Generates an editor using the "simple" style.""" return self.simple_editor_class( parent, factory=self, @@ -126,8 +124,7 @@ def simple_editor(self, ui, object, name, description, parent): ) def custom_editor(self, ui, object, name, description, parent): - """ Generates an editor using the "custom" style. - """ + """Generates an editor using the "custom" style.""" return self.custom_editor_class( parent, factory=self, @@ -138,8 +135,7 @@ def custom_editor(self, ui, object, name, description, parent): ) def text_editor(self, ui, object, name, description, parent): - """ Generates an editor using the "text" style. - """ + """Generates an editor using the "text" style.""" return self.text_editor_class( parent, factory=self, @@ -150,8 +146,7 @@ def text_editor(self, ui, object, name, description, parent): ) def readonly_editor(self, ui, object, name, description, parent): - """ Generates an "editor" that is read-only. - """ + """Generates an "editor" that is read-only.""" return self.readonly_editor_class( parent, factory=self, @@ -188,7 +183,7 @@ def _get_toolkit_editor(cls, class_name): return None def string_value(self, value, format_func=None): - """ Returns the text representation of a specified object trait value. + """Returns the text representation of a specified object trait value. If the **format_func** attribute is set on the editor factory, then this method calls that function to do the formatting. If the @@ -212,7 +207,7 @@ def string_value(self, value, format_func=None): # ------------------------------------------------------------------------- def _get_simple_editor_class(self): - """ Returns the editor class to use for "simple" style views. + """Returns the editor class to use for "simple" style views. The default implementation tries to import the SimpleEditor class in the editor file in the backend package, and if such a class is not to found it returns the SimpleEditor class defined in editor_factory @@ -228,7 +223,7 @@ def _get_simple_editor_class(self): return SimpleEditor def _get_custom_editor_class(self): - """ Returns the editor class to use for "custom" style views. + """Returns the editor class to use for "custom" style views. The default implementation tries to import the CustomEditor class in the editor file in the backend package, and if such a class is not to found it returns simple_editor_class. @@ -243,7 +238,7 @@ def _get_custom_editor_class(self): return CustomEditor def _get_text_editor_class(self): - """ Returns the editor class to use for "text" style views. + """Returns the editor class to use for "text" style views. The default implementation tries to import the TextEditor class in the editor file in the backend package, and if such a class is not found it returns the TextEditor class declared in the editor_factory module @@ -259,7 +254,7 @@ def _get_text_editor_class(self): return TextEditor def _get_readonly_editor_class(self): - """ Returns the editor class to use for "readonly" style views. + """Returns the editor class to use for "readonly" style views. The default implementation tries to import the ReadonlyEditor class in the editor file in the backend package, and if such a class is not found it returns the ReadonlyEditor class declared in the @@ -281,8 +276,7 @@ def _get_readonly_editor_class(self): class EditorWithListFactory(EditorFactory): - """ Base class for factories of editors for objects that contain lists. - """ + """Base class for factories of editors for objects that contain lists.""" # ------------------------------------------------------------------------- # Trait definitions: diff --git a/traitsui/editors/array_editor.py b/traitsui/editors/array_editor.py index bb9f6235d..bcf4c1530 100644 --- a/traitsui/editors/array_editor.py +++ b/traitsui/editors/array_editor.py @@ -23,8 +23,7 @@ class ArrayEditor(EditorFactory): - """ Editor factory for array editors. - """ + """Editor factory for array editors.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -53,8 +52,7 @@ class ArrayStructure(HasTraits): view = Instance(View) def __init__(self, editor): - """ Initializes the object. - """ + """Initializes the object.""" super().__init__(editor=editor) # Set up the field width for each item: @@ -157,8 +155,7 @@ def _two_dim_view(self, object, style, width, trait): return View(Group(show_labels=False, *content)) def _field_changed(self): - """ Updates the underlying array when any field changes value. - """ + """Updates the underlying array when any field changes value.""" if not self.editor._busy: # Get the array we are mirroring: @@ -185,8 +182,7 @@ def _field_changed(self): class SimpleEditor(Editor): - """ Simple style of editor for arrays. - """ + """Simple style of editor for arrays.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -196,8 +192,8 @@ class SimpleEditor(Editor): readonly = Bool(False) def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self._as = _as = ArrayStructure(self) ui = _as.view.ui(_as, parent, kind="subpanel") @@ -205,8 +201,8 @@ def init(self, parent): self.control = ui.control def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ if not self._busy: @@ -228,8 +224,7 @@ def update_editor(self): self._busy = False def update_array(self, value): - """ Updates the array value associated with the editor. - """ + """Updates the array value associated with the editor.""" self._busy = True self.value = value self._busy = False diff --git a/traitsui/editors/boolean_editor.py b/traitsui/editors/boolean_editor.py index 9db1942e2..33d8acfa7 100644 --- a/traitsui/editors/boolean_editor.py +++ b/traitsui/editors/boolean_editor.py @@ -39,8 +39,7 @@ class BooleanEditor(TextEditor): - """ Editor factory for Boolean editors. - """ + """Editor factory for Boolean editors.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -61,7 +60,7 @@ class BooleanEditor(TextEditor): # ------------------------------------------------------------------------- def _get_custom_editor_class(self): - """ Returns the editor class to use for "custom" style views. + """Returns the editor class to use for "custom" style views. Overridden to return the simple_editor_class (instead of the CustomEditor class for the text editor's factory, which this class inherits from). diff --git a/traitsui/editors/button_editor.py b/traitsui/editors/button_editor.py index 88cfc689d..958be6f57 100644 --- a/traitsui/editors/button_editor.py +++ b/traitsui/editors/button_editor.py @@ -20,8 +20,7 @@ class ButtonEditor(EditorFactory): - """ Editor factory for buttons. - """ + """Editor factory for buttons.""" # ------------------------------------------------------------------------- # Trait definitions: diff --git a/traitsui/editors/check_list_editor.py b/traitsui/editors/check_list_editor.py index bffa35f9b..feb5e4dff 100644 --- a/traitsui/editors/check_list_editor.py +++ b/traitsui/editors/check_list_editor.py @@ -33,8 +33,7 @@ class CheckListEditor(EditorWithListFactory): - """ Editor factory for checklists. - """ + """Editor factory for checklists.""" # ------------------------------------------------------------------------- # Trait definitions: diff --git a/traitsui/editors/code_editor.py b/traitsui/editors/code_editor.py index 0bf3eb3c1..31bd73276 100644 --- a/traitsui/editors/code_editor.py +++ b/traitsui/editors/code_editor.py @@ -19,8 +19,7 @@ class CodeEditor(EditorFactory): - """ Editor factory for code editors. - """ + """Editor factory for code editors.""" # ------------------------------------------------------------------------- # Trait definitions: diff --git a/traitsui/editors/color_editor.py b/traitsui/editors/color_editor.py index 0376905eb..9e518aa2a 100644 --- a/traitsui/editors/color_editor.py +++ b/traitsui/editors/color_editor.py @@ -23,8 +23,7 @@ class ToolkitEditorFactory(EditorFactory): - """ Editor factory for color editors. - """ + """Editor factory for color editors.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -49,7 +48,7 @@ class ToolkitEditorFactory(EditorFactory): # in traitsui..color_editor, and if none is found, the # ToolkitEditorFactory declared here is returned. def ColorEditor(*args, **traits): - r""" Returns an instance of the toolkit-specific editor factory declared in + r"""Returns an instance of the toolkit-specific editor factory declared in traitsui..color_editor. If such an editor factory cannot be located, an instance of the abstract ToolkitEditorFactory declared in traitsui.editors.color_editor is returned. diff --git a/traitsui/editors/compound_editor.py b/traitsui/editors/compound_editor.py index 934e0a62f..9140e766f 100644 --- a/traitsui/editors/compound_editor.py +++ b/traitsui/editors/compound_editor.py @@ -24,8 +24,7 @@ class CompoundEditor(EditorFactory): - """ Editor factory for compound editors. - """ + """Editor factory for compound editors.""" # ------------------------------------------------------------------------- # Trait definitions: diff --git a/traitsui/editors/csv_list_editor.py b/traitsui/editors/csv_list_editor.py index d1f67b502..e1d311eb8 100644 --- a/traitsui/editors/csv_list_editor.py +++ b/traitsui/editors/csv_list_editor.py @@ -153,7 +153,7 @@ def _validate_range_value(range_object, object, name, value): def _prepare_method(cls, parent): - """ Unbound implementation of the prepare editor method to add a + """Unbound implementation of the prepare editor method to add a change notification hook in the items of the list before calling the parent prepare method of the parent class. @@ -167,7 +167,7 @@ def _prepare_method(cls, parent): def _dispose_method(cls): - """ Unbound implementation of the dispose editor method to remove + """Unbound implementation of the dispose editor method to remove the change notification hook in the items of the list before calling the parent dispose method of the parent class. @@ -342,8 +342,7 @@ def _funcs(self, object, name): return evaluate, fmt_func def simple_editor(self, ui, object, name, description, parent): - """ Generates an editor using the "simple" style. - """ + """Generates an editor using the "simple" style.""" self.evaluate, self.format_func = self._funcs(object, name) return self.simple_editor_class( parent, @@ -355,8 +354,7 @@ def simple_editor(self, ui, object, name, description, parent): ) def custom_editor(self, ui, object, name, description, parent): - """ Generates an editor using the "custom" style. - """ + """Generates an editor using the "custom" style.""" self.evaluate, self.format_func = self._funcs(object, name) return self.custom_editor_class( parent, @@ -368,8 +366,7 @@ def custom_editor(self, ui, object, name, description, parent): ) def text_editor(self, ui, object, name, description, parent): - """ Generates an editor using the "text" style. - """ + """Generates an editor using the "text" style.""" self.evaluate, self.format_func = self._funcs(object, name) return self.text_editor_class( parent, @@ -381,8 +378,7 @@ def text_editor(self, ui, object, name, description, parent): ) def readonly_editor(self, ui, object, name, description, parent): - """ Generates an "editor" that is read-only. - """ + """Generates an "editor" that is read-only.""" self.evaluate, self.format_func = self._funcs(object, name) return self.readonly_editor_class( parent, diff --git a/traitsui/editors/custom_editor.py b/traitsui/editors/custom_editor.py index f6fd1f365..6c07421d9 100644 --- a/traitsui/editors/custom_editor.py +++ b/traitsui/editors/custom_editor.py @@ -18,8 +18,7 @@ class CustomEditor(BasicEditorFactory): - """ Editor factory for custom editors. - """ + """Editor factory for custom editors.""" #: Editor class to be instantiated. klass = Property() @@ -40,8 +39,7 @@ def __init__(self, *args, **traits): # Property getters # ------------------------------------------------------------------------- def _get_klass(self): - """ Returns the editor class to be created. - """ + """Returns the editor class to be created.""" return toolkit_object("custom_editor:CustomEditor") diff --git a/traitsui/editors/date_editor.py b/traitsui/editors/date_editor.py index a029e1b13..b11466bc0 100644 --- a/traitsui/editors/date_editor.py +++ b/traitsui/editors/date_editor.py @@ -18,7 +18,7 @@ class CellFormat(object): - """ Styling attributes for calendar widget cells. + """Styling attributes for calendar widget cells. Encapsulates some common visual attributes to set on the cells of a calendar widget. All attributes default to None, which means that they @@ -53,8 +53,7 @@ def __init__(self, **args): class DateEditor(EditorFactory): - """ Editor factory for date/time editors. - """ + """Editor factory for date/time editors.""" # ------------------------------------------------------------------------- # Trait definitions: diff --git a/traitsui/editors/date_range_editor.py b/traitsui/editors/date_range_editor.py index ca6572da3..c96e751b1 100644 --- a/traitsui/editors/date_range_editor.py +++ b/traitsui/editors/date_range_editor.py @@ -14,7 +14,7 @@ class DateRangeEditor(DateEditor): - """ Editor for a date range. The target value should be a tuple + """Editor for a date range. The target value should be a tuple containing two dates (start date, end date) """ diff --git a/traitsui/editors/datetime_editor.py b/traitsui/editors/datetime_editor.py index b6afc1e63..7b3bb27d0 100644 --- a/traitsui/editors/datetime_editor.py +++ b/traitsui/editors/datetime_editor.py @@ -19,8 +19,8 @@ class DatetimeEditor(EditorFactory): - """ Editor factory for the datetime editor. - """ + """Editor factory for the datetime editor.""" + # ------------------------------------------------------------------------- # Trait definitions: # ------------------------------------------------------------------------- diff --git a/traitsui/editors/directory_editor.py b/traitsui/editors/directory_editor.py index ddee011a8..e1ebdef71 100644 --- a/traitsui/editors/directory_editor.py +++ b/traitsui/editors/directory_editor.py @@ -15,8 +15,7 @@ class DirectoryEditor(FileEditor): - """ Editor factory for directory editors. - """ + """Editor factory for directory editors.""" pass diff --git a/traitsui/editors/dnd_editor.py b/traitsui/editors/dnd_editor.py index 1dc277951..49dd12d22 100644 --- a/traitsui/editors/dnd_editor.py +++ b/traitsui/editors/dnd_editor.py @@ -20,8 +20,7 @@ class DNDEditor(EditorFactory): - """ Editor factory for drag-and-drop editors. - """ + """Editor factory for drag-and-drop editors.""" # ------------------------------------------------------------------------- # Trait definitions: diff --git a/traitsui/editors/drop_editor.py b/traitsui/editors/drop_editor.py index 9d33bdc49..4494664e5 100644 --- a/traitsui/editors/drop_editor.py +++ b/traitsui/editors/drop_editor.py @@ -19,8 +19,7 @@ class DropEditor(TextEditor): - """ Editor factory for drop editors. - """ + """Editor factory for drop editors.""" # ------------------------------------------------------------------------- # Trait definitions: diff --git a/traitsui/editors/enum_editor.py b/traitsui/editors/enum_editor.py index e27e6b129..8c25305af 100644 --- a/traitsui/editors/enum_editor.py +++ b/traitsui/editors/enum_editor.py @@ -32,8 +32,7 @@ class EnumEditor(EditorWithListFactory): - """ Editor factory for enumeration editors. - """ + """Editor factory for enumeration editors.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -59,7 +58,7 @@ class EnumEditor(EditorWithListFactory): # ------------------------------------------------------------------------- def _get_custom_editor_class(self): - """ Returns the editor class to use for "custom" style views. + """Returns the editor class to use for "custom" style views. Overridden to return the editor class for the specified mode. """ editor_file_name = os.path.basename( diff --git a/traitsui/editors/file_editor.py b/traitsui/editors/file_editor.py index 1cbc9d87c..3c802dac9 100644 --- a/traitsui/editors/file_editor.py +++ b/traitsui/editors/file_editor.py @@ -26,8 +26,7 @@ class FileEditor(TextEditor): - """ Editor factory for file editors. - """ + """Editor factory for file editors.""" # ------------------------------------------------------------------------- # Trait definitions: diff --git a/traitsui/editors/font_editor.py b/traitsui/editors/font_editor.py index 69aebfd79..e37667c3d 100644 --- a/traitsui/editors/font_editor.py +++ b/traitsui/editors/font_editor.py @@ -20,8 +20,7 @@ class ToolkitEditorFactory(EditorFactory): - """ Editor factory for font editors. - """ + """Editor factory for font editors.""" pass @@ -31,7 +30,7 @@ class ToolkitEditorFactory(EditorFactory): # in traitsui..font_editor, and if none is found, the # ToolkitEditorFactory declared here is returned. def FontEditor(*args, **traits): - r""" Returns an instance of the toolkit-specific editor factory declared in + r"""Returns an instance of the toolkit-specific editor factory declared in traitsui..font_editor. If such an editor factory cannot be located, an instance of the abstract ToolkitEditorFactory declared in traitsui.editors.font_editor is returned. diff --git a/traitsui/editors/html_editor.py b/traitsui/editors/html_editor.py index 9e0ee207a..2396d84d7 100644 --- a/traitsui/editors/html_editor.py +++ b/traitsui/editors/html_editor.py @@ -39,8 +39,7 @@ def html_editor(*args, **traits): class ToolkitEditorFactory(BasicEditorFactory): - """ Editor factory for HTML editors. - """ + """Editor factory for HTML editors.""" # -------------------------------------------------------------------------- # Trait definitions: @@ -59,8 +58,8 @@ class ToolkitEditorFactory(BasicEditorFactory): open_externally = Bool(False) def parse_text(self, text): - """ Parses the contents of a formatted text string into the - corresponding HTML. + """Parses the contents of a formatted text string into the + corresponding HTML. """ text = text.replace("\r\n", "\n") lines = [("." + line).strip()[1:] for line in text.split("\n")] @@ -96,8 +95,7 @@ def parse_text(self, text): return "\n".join(paragraphs) def parse_block(self, lines, i): - """ Parses a code block. - """ + """Parses a code block.""" m = 1000 n = len(lines) j = i @@ -120,12 +118,11 @@ def parse_block(self, lines, i): return (j, block_template % "\n
".join(temp)) def parse_list(self, lines, i): - """ Parses a list. - """ + """Parses a list.""" line = lines[i] m = self.indent(line) kind = line[m] - result = ["
  • " + line[m + 1:].strip()] + result = ["
  • " + line[m + 1 :].strip()] n = len(lines) j = i + 1 while j < n: @@ -136,7 +133,7 @@ def parse_list(self, lines, i): if k == m: if line[k] != kind: break - result.append("
  • " + line[k + 1:].strip()) + result.append("
  • " + line[k + 1 :].strip()) j += 1 elif line[k] in "-*": j, line = self.parse_list(lines, j) @@ -148,8 +145,7 @@ def parse_list(self, lines, i): return (j, list_template % (style, "\n".join(result), style)) def indent(self, line): - """ Calculates the amount of white space at the beginning of a line. - """ + """Calculates the amount of white space at the beginning of a line.""" return len(line) - len((line + ".").strip()) + 1 diff --git a/traitsui/editors/image_editor.py b/traitsui/editors/image_editor.py index b6f74e4da..4c3718545 100644 --- a/traitsui/editors/image_editor.py +++ b/traitsui/editors/image_editor.py @@ -47,6 +47,5 @@ class ImageEditor(BasicEditorFactory): allow_clipping = Bool() def _get_klass(self): - """ Returns the editor class to be instantiated. - """ + """Returns the editor class to be instantiated.""" return toolkit_object("image_editor:_ImageEditor") diff --git a/traitsui/editors/image_enum_editor.py b/traitsui/editors/image_enum_editor.py index 4655cfe07..a0f0e89ee 100644 --- a/traitsui/editors/image_enum_editor.py +++ b/traitsui/editors/image_enum_editor.py @@ -22,8 +22,7 @@ class ImageEnumEditor(EnumEditor): - """ Editor factory for image enumeration editors. - """ + """Editor factory for image enumeration editors.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -44,16 +43,15 @@ class ImageEnumEditor(EnumEditor): module = Module def init(self): - """ Performs any initialization needed after all constructor traits - have been set. + """Performs any initialization needed after all constructor traits + have been set. """ super().init() self._update_path() @observe("path, klass, module") def _update_path(self, event=None): - """ Handles one of the items defining the path being updated. - """ + """Handles one of the items defining the path being updated.""" if self.path != "": self._image_path = self.path elif self.klass is not None: diff --git a/traitsui/editors/instance_editor.py b/traitsui/editors/instance_editor.py index a98782b35..6b2ab4f55 100644 --- a/traitsui/editors/instance_editor.py +++ b/traitsui/editors/instance_editor.py @@ -21,8 +21,7 @@ class InstanceEditor(EditorFactory): - """ Editor factory for instance editors. - """ + """Editor factory for instance editors.""" # ------------------------------------------------------------------------- # Trait definitions: diff --git a/traitsui/editors/list_editor.py b/traitsui/editors/list_editor.py index 35583c1de..4e11759e2 100644 --- a/traitsui/editors/list_editor.py +++ b/traitsui/editors/list_editor.py @@ -52,8 +52,7 @@ class ListEditor(EditorFactory): - """ Editor factory for list editors. - """ + """Editor factory for list editors.""" # ------------------------------------------------------------------------- # Trait definitions: diff --git a/traitsui/editors/list_str_editor.py b/traitsui/editors/list_str_editor.py index 403072443..02fcf81a1 100644 --- a/traitsui/editors/list_str_editor.py +++ b/traitsui/editors/list_str_editor.py @@ -23,8 +23,7 @@ class ListStrEditor(BasicEditorFactory): - """ Editor factory for list of string editors. - """ + """Editor factory for list of string editors.""" # -- Trait Definitions ---------------------------------------------------- @@ -102,6 +101,5 @@ class ListStrEditor(BasicEditorFactory): menu = Any() def _get_klass(self): - """ Returns the editor class to be created. - """ + """Returns the editor class to be created.""" return toolkit_object("list_str_editor:_ListStrEditor") diff --git a/traitsui/editors/popup_editor.py b/traitsui/editors/popup_editor.py index 102171847..f3145851f 100644 --- a/traitsui/editors/popup_editor.py +++ b/traitsui/editors/popup_editor.py @@ -26,13 +26,11 @@ class _PopupEditor(UIEditor): def init_ui(self, parent): - """ Creates the traits UI for the editor. - """ + """Creates the traits UI for the editor.""" return self.object.edit_traits(view=self.base_view(), parent=parent) def base_view(self): - """ Returns the View that allows the popup view to be displayed. - """ + """Returns the View that allows the popup view to be displayed.""" return View( Item( self.name, @@ -45,8 +43,7 @@ def base_view(self): ) def popup_view(self): - """ Returns the popup View. - """ + """Returns the popup View.""" factory = self.factory item = Item( self.name, @@ -94,6 +91,5 @@ class PopupEditor(BasicEditorFactory): width = Float(-1.0) def _get_klass(self): - """ The class used to construct editor objects. - """ + """The class used to construct editor objects.""" return toolkit_object("popup_editor:_PopupEditor") diff --git a/traitsui/editors/progress_editor.py b/traitsui/editors/progress_editor.py index aa29edcfc..ed8376553 100644 --- a/traitsui/editors/progress_editor.py +++ b/traitsui/editors/progress_editor.py @@ -17,8 +17,7 @@ class ProgressEditor(EditorFactory): - """ Editor factory for code editors. - """ + """Editor factory for code editors.""" # ------------------------------------------------------------------------- # Trait definitions: diff --git a/traitsui/editors/range_editor.py b/traitsui/editors/range_editor.py index 4cc03d81b..832344298 100644 --- a/traitsui/editors/range_editor.py +++ b/traitsui/editors/range_editor.py @@ -33,8 +33,7 @@ class RangeEditor(EditorFactory): - """ Editor factory for range editors. - """ + """Editor factory for range editors.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -113,8 +112,8 @@ class RangeEditor(EditorFactory): ) def init(self, handler=None): - """ Performs any initialization needed after all constructor traits - have been set. + """Performs any initialization needed after all constructor traits + have been set. """ if handler is not None: if isinstance(handler, CTrait): @@ -147,9 +146,7 @@ def _set_low(self, low): if self.is_float is Undefined: self.is_float = isinstance(low, float) - if (self.low_label == "") or ( - self.low_label == str(old_low) - ): + if (self.low_label == "") or (self.low_label == str(old_low)): self.low_label = str(low) def _get_high(self): @@ -161,9 +158,7 @@ def _set_high(self, high): if self.is_float is Undefined: self.is_float = isinstance(high, float) - if (self.high_label == "") or ( - self.high_label == str(old_high) - ): + if (self.high_label == "") or (self.high_label == str(old_high)): self.high_label = str(high) def _cast(self, value): @@ -178,8 +173,7 @@ def _cast(self, value): # -- Private Methods ------------------------------------------------------ def _get_low_high(self, ui): - """ Returns the low and high values used to determine the initial range. - """ + """Returns the low and high values used to determine the initial range.""" low, high = self.low, self.high if (low is None) and (self.low_name != ""): @@ -218,7 +212,7 @@ def _set_format(self, format_string): self.format_str = format_string def _get_simple_editor_class(self): - """ Returns the editor class to use for a simple style. + """Returns the editor class to use for a simple style. The type of editor depends on the type and extent of the range being edited: @@ -251,7 +245,7 @@ def _get_simple_editor_class(self): return toolkit_object("range_editor:SimpleSpinEditor") def _get_custom_editor_class(self): - """ Creates a custom style of range editor + """Creates a custom style of range editor The type of editor depends on the type and extent of the range being edited: @@ -277,8 +271,7 @@ def _get_custom_editor_class(self): return toolkit_object("range_editor:CustomEnumEditor") def _get_text_editor_class(self): - """Returns the editor class to use for a text style. - """ + """Returns the editor class to use for a text style.""" return toolkit_object("range_editor:RangeTextEditor") # ------------------------------------------------------------------------- @@ -286,7 +279,7 @@ def _get_text_editor_class(self): # ------------------------------------------------------------------------- def simple_editor(self, ui, object, name, description, parent): - """ Generates an editor using the "simple" style. + """Generates an editor using the "simple" style. Overridden to set the values of the _low_value, _high_value and is_float traits. @@ -297,7 +290,7 @@ def simple_editor(self, ui, object, name, description, parent): return super().simple_editor(ui, object, name, description, parent) def custom_editor(self, ui, object, name, description, parent): - """ Generates an editor using the "custom" style. + """Generates an editor using the "custom" style. Overridden to set the values of the _low_value, _high_value and is_float traits. diff --git a/traitsui/editors/rgb_color_editor.py b/traitsui/editors/rgb_color_editor.py index 29811c5c8..12ee2e301 100644 --- a/traitsui/editors/rgb_color_editor.py +++ b/traitsui/editors/rgb_color_editor.py @@ -22,8 +22,7 @@ class ToolkitEditorFactory(EditorFactory): - """ Factory for editors for RGB colors. - """ + """Factory for editors for RGB colors.""" pass @@ -35,7 +34,7 @@ class ToolkitEditorFactory(EditorFactory): def RGBColorEditor(*args, **traits): - r""" Returns an instance of the toolkit-specific editor factory declared in + r"""Returns an instance of the toolkit-specific editor factory declared in traitsui..rgb_color_editor. If such an editor factory cannot be located, an instance of the abstract ToolkitEditorFactory declared in traitsui.editors.rgb_color_editor is returned. diff --git a/traitsui/editors/scrubber_editor.py b/traitsui/editors/scrubber_editor.py index f88953301..955082628 100644 --- a/traitsui/editors/scrubber_editor.py +++ b/traitsui/editors/scrubber_editor.py @@ -58,6 +58,5 @@ class ScrubberEditor(BasicEditorFactory): text_color = Color("black") def _get_klass(self): - """ Returns the toolkit-specific editor class to be instantiated. - """ + """Returns the toolkit-specific editor class to be instantiated.""" return toolkit_object("scrubber_editor:_ScrubberEditor") diff --git a/traitsui/editors/search_editor.py b/traitsui/editors/search_editor.py index ed87616e1..8895751c8 100644 --- a/traitsui/editors/search_editor.py +++ b/traitsui/editors/search_editor.py @@ -19,8 +19,8 @@ class SearchEditor(BasicEditorFactory): - """ A single line text widget that supports functionality common to native - search widgets. + """A single line text widget that supports functionality common to native + search widgets. """ #: The editor class to be created: @@ -46,6 +46,5 @@ class SearchEditor(BasicEditorFactory): search_event_trait = Str() def _get_klass(self): - """ Returns the toolkit-specific editor class to be instantiated. - """ + """Returns the toolkit-specific editor class to be instantiated.""" return toolkit_object("search_editor:SearchEditor") diff --git a/traitsui/editors/set_editor.py b/traitsui/editors/set_editor.py index 2470dc1ba..d2cf44210 100644 --- a/traitsui/editors/set_editor.py +++ b/traitsui/editors/set_editor.py @@ -17,8 +17,7 @@ class SetEditor(EditorWithListFactory): - """ Editor factory for editors for sets. - """ + """Editor factory for editors for sets.""" # ------------------------------------------------------------------------- # Trait definitions: diff --git a/traitsui/editors/shell_editor.py b/traitsui/editors/shell_editor.py index fdbf2cc7c..a7142fd43 100644 --- a/traitsui/editors/shell_editor.py +++ b/traitsui/editors/shell_editor.py @@ -20,8 +20,7 @@ class _ShellEditor(Editor): - """ Base class for an editor that displays an interactive Python shell. - """ + """Base class for an editor that displays an interactive Python shell.""" #: An event fired to execute a command in the shell. command_to_execute = Event() @@ -37,8 +36,8 @@ class _ShellEditor(Editor): # ------------------------------------------------------------------------- def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ # Moving the import here, since PythonShell is implemented in the # Pyface backend packages, and we want to delay loading this toolkit @@ -66,7 +65,7 @@ def init(self, parent): object.observe( self.update_any, match(self._any_trait_observer), - dispatch="ui" + dispatch="ui", ) else: self._base_locals = locals = {} @@ -84,8 +83,7 @@ def init(self, parent): self.set_tooltip() def update_object(self, event): - """ Handles the user entering input data in the edit control. - """ + """Handles the user entering input data in the edit control.""" locals = self._shell.interpreter().locals base_locals = self._base_locals if base_locals is None: @@ -108,8 +106,8 @@ def update_object(self, event): self.command_executed = True def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ if self.factory.share: value = self.value @@ -128,8 +126,8 @@ def update_editor(self): locals[name] = value def update_any(self, event): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ name, new = event.name, event.new locals = self._shell.interpreter().locals @@ -139,25 +137,27 @@ def update_any(self, event): self.value[name] = new def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" if not (self.factory.share and isinstance(self.value, dict)): self._shell.observe( - self.update_object, "command_executed", remove=True, dispatch="ui" + self.update_object, + "command_executed", + remove=True, + dispatch="ui", ) if self._base_locals is None: self.object.observe( self.update_any, match(self._any_trait_observer), remove=True, - dispatch="ui" + dispatch="ui", ) super().dispose() def restore_prefs(self, prefs): - """ Restores any saved user preference information associated with the - editor. + """Restores any saved user preference information associated with the + editor. """ shell = self._shell try: @@ -168,8 +168,7 @@ def restore_prefs(self, prefs): pass def save_prefs(self): - """ Returns any user preference information associated with the editor. - """ + """Returns any user preference information associated with the editor.""" history, history_index = self._shell.get_history() return {"history": history, "history_index": history_index} @@ -181,8 +180,7 @@ def save_prefs(self): @observe("command_to_execute") def _execute_command(self, event): - """ Handles the 'command_to_execute' trait being fired. - """ + """Handles the 'command_to_execute' trait being fired.""" # Show the command. A 'hidden' command should be executed directly on # the namespace trait! command = event.new @@ -190,7 +188,7 @@ def _execute_command(self, event): class ShellEditor(BasicEditorFactory): - """ Editor factory for shell editors. """ + """Editor factory for shell editors.""" #: The editor class to be instantiated. klass = Property() @@ -207,8 +205,7 @@ class ShellEditor(BasicEditorFactory): command_executed = Str() def _get_klass(self): - """ Returns the toolkit-specific editor class to be used in the UI. - """ + """Returns the toolkit-specific editor class to be used in the UI.""" return toolkit_object("shell_editor:_ShellEditor") diff --git a/traitsui/editors/styled_date_editor.py b/traitsui/editors/styled_date_editor.py index f38b745f1..c74f7b347 100644 --- a/traitsui/editors/styled_date_editor.py +++ b/traitsui/editors/styled_date_editor.py @@ -14,8 +14,7 @@ class StyledDateEditor(DateEditor): - """ A DateEditor that can show sets of dates in different styles. - """ + """A DateEditor that can show sets of dates in different styles.""" #: The name of a dictionary on the object that maps names to groups #: (list/tuples) of datetime.date objects. Each of these groups can be diff --git a/traitsui/editors/table_editor.py b/traitsui/editors/table_editor.py index 2e646759b..c5cf1e069 100644 --- a/traitsui/editors/table_editor.py +++ b/traitsui/editors/table_editor.py @@ -51,8 +51,7 @@ class TableEditor(EditorFactory): - """ Editor factory for table editors. - """ + """Editor factory for table editors.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -385,7 +384,7 @@ class TableEditor(EditorFactory): # ------------------------------------------------------------------------- def readonly_editor(self, ui, object, name, description, parent): - """ Generates an "editor" that is read-only. + """Generates an "editor" that is read-only. Overridden to set the value of the editable trait to False before generating the editor. @@ -399,8 +398,8 @@ def readonly_editor(self, ui, object, name, description, parent): @observe("filters.items") def _update_filter_editor(self, event): - """ Handles the set of filters associated with the editor's factory - being changed. + """Handles the set of filters associated with the editor's factory + being changed. """ values = {None: "000:No filter"} i = 0 @@ -424,8 +423,7 @@ def _update_filter_editor(self, event): class BaseTableEditor(object): - """ Base class for toolkit-specific editors. - """ + """Base class for toolkit-specific editors.""" # ------------------------------------------------------------------------- # Interface for toolkit-specific editors: @@ -433,7 +431,7 @@ class BaseTableEditor(object): def set_menu_context(self, selection, object, column): """Call before creating a context menu for a cell, then set self as the - controller for the menu. + controller for the menu. """ self._menu_context = { "selection": selection, @@ -449,20 +447,17 @@ def set_menu_context(self, selection, object, column): # ------------------------------------------------------------------------- def add_to_menu(self, menu_item): - """ Adds a menu item to the menu bar being constructed. - """ + """Adds a menu item to the menu bar being constructed.""" action = menu_item.item.action self.eval_when(action.enabled_when, menu_item, "enabled") self.eval_when(action.checked_when, menu_item, "checked") def add_to_toolbar(self, toolbar_item): - """ Adds a toolbar item to the toolbar being constructed. - """ + """Adds a toolbar item to the toolbar being constructed.""" self.add_to_menu(toolbar_item) def can_add_to_menu(self, action): - """ Returns whether the action should be defined in the user interface. - """ + """Returns whether the action should be defined in the user interface.""" if action.defined_when != "": if not eval(action.defined_when, globals(), self._menu_context): return False @@ -474,14 +469,13 @@ def can_add_to_menu(self, action): return True def can_add_to_toolbar(self, action): - """ Returns whether the toolbar action should be defined in the user - interface. + """Returns whether the toolbar action should be defined in the user + interface. """ return self.can_add_to_menu(action) def perform(self, action, action_event=None): - """ Performs the action described by a specified Action object. - """ + """Performs the action described by a specified Action object.""" self.ui.do_undoable(self._perform, action) def _perform(self, action): @@ -518,7 +512,7 @@ def _perform(self, action): # ------------------------------------------------------------------------- def eval_when(self, condition, object, trait): - """ Evaluates a condition within a defined context and sets a specified + """Evaluates a condition within a defined context and sets a specified object trait based on the result, which is assumed to be a Boolean. """ if condition != "": @@ -532,20 +526,18 @@ def eval_when(self, condition, object, trait): class ReversedList(object): - """ A list whose order is the reverse of its input. - """ + """A list whose order is the reverse of its input.""" def __init__(self, list): self.list = list def insert(self, index, value): - """ Inserts a value at a specified index in the list. - """ + """Inserts a value at a specified index in the list.""" return self.list.insert(self._index(index - 1), value) def index(self, value): - """ Returns the index of the first occurrence of the specified value in - the list. + """Returns the index of the first occurrence of the specified value in + the list. """ list = self.list[:] list.reverse() @@ -553,28 +545,23 @@ def index(self, value): return list.index(value) def __len__(self): - """ Returns the length of the list. - """ + """Returns the length of the list.""" return len(self.list) def __getitem__(self, index): - """ Returns the value at a specified index in the list. - """ + """Returns the value at a specified index in the list.""" return self.list[self._index(index)] def __setslice__(self, i, j, values): - """ Sets a slice of a list to the contents of a specified sequence. - """ + """Sets a slice of a list to the contents of a specified sequence.""" return self.list.__setslice__(self._index(i), self._index(j), values) def __delitem__(self, index): - """ Deletes the item at a specified index. - """ + """Deletes the item at a specified index.""" return self.list.__delitem__(self._index(index)) def _index(self, index): - """ Returns the "reversed" value for a specified index. - """ + """Returns the "reversed" value for a specified index.""" if index < 0: return -1 - index diff --git a/traitsui/editors/tabular_editor.py b/traitsui/editors/tabular_editor.py index a7c7033ed..708cd62fa 100644 --- a/traitsui/editors/tabular_editor.py +++ b/traitsui/editors/tabular_editor.py @@ -22,8 +22,7 @@ class TabularEditor(BasicEditorFactory): - """ Editor factory for tabular editors. - """ + """Editor factory for tabular editors.""" # -- Trait Definitions ---------------------------------------------------- @@ -153,8 +152,7 @@ class TabularEditor(BasicEditorFactory): images = List(Image) def _get_klass(self): - """ Returns the toolkit-specific editor class to be instantiated. - """ + """Returns the toolkit-specific editor class to be instantiated.""" return toolkit_object("tabular_editor:TabularEditor") def _get_scroll_to_row_hint(self): diff --git a/traitsui/editors/text_editor.py b/traitsui/editors/text_editor.py index 1d75ba145..e0d37ccc7 100644 --- a/traitsui/editors/text_editor.py +++ b/traitsui/editors/text_editor.py @@ -24,8 +24,7 @@ class _Identity(object): - """ A simple identity mapping. - """ + """A simple identity mapping.""" def __call__(self, value): return value @@ -43,8 +42,7 @@ def __call__(self, value): class TextEditor(EditorFactory): - """ Editor factory for text editors. - """ + """Editor factory for text editors.""" # ------------------------------------------------------------------------- # Trait definitions: diff --git a/traitsui/editors/time_editor.py b/traitsui/editors/time_editor.py index 538828115..fd9ca1897 100644 --- a/traitsui/editors/time_editor.py +++ b/traitsui/editors/time_editor.py @@ -18,8 +18,7 @@ class TimeEditor(EditorFactory): - """ Editor factory for time editors. - """ + """Editor factory for time editors.""" # ------------------------------------------------------------------------- # Trait definitions: diff --git a/traitsui/editors/title_editor.py b/traitsui/editors/title_editor.py index 2daaa76cb..d58c2bc51 100644 --- a/traitsui/editors/title_editor.py +++ b/traitsui/editors/title_editor.py @@ -18,13 +18,12 @@ class TitleEditor(EditorFactory): - """ Editor factory for Title editors. - """ + """Editor factory for Title editors.""" allow_selection = Bool(False) def _get_simple_editor_class(self): - """ Returns the editor class to use for "simple" style views. + """Returns the editor class to use for "simple" style views. The default implementation tries to import the SimpleEditor class in the editor file in the backend package, and if such a class is not to found it returns the SimpleEditor class defined in editor_factory diff --git a/traitsui/editors/tree_editor.py b/traitsui/editors/tree_editor.py index 1f192f0e3..62c12c976 100644 --- a/traitsui/editors/tree_editor.py +++ b/traitsui/editors/tree_editor.py @@ -61,8 +61,7 @@ class TreeEditor(EditorFactory): - """ Editor factory for tree editors. - """ + """Editor factory for tree editors.""" # ------------------------------------------------------------------------- # Trait definitions: diff --git a/traitsui/editors/tuple_editor.py b/traitsui/editors/tuple_editor.py index a07d2d86a..ba9b4e63c 100644 --- a/traitsui/editors/tuple_editor.py +++ b/traitsui/editors/tuple_editor.py @@ -31,8 +31,7 @@ class TupleEditor(EditorFactory): - """ Editor factory for tuple editors. - """ + """Editor factory for tuple editors.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -62,15 +61,15 @@ class TupleEditor(EditorFactory): class SimpleEditor(Editor): - """ Simple style of editor for tuples. + """Simple style of editor for tuples. The editor displays an editor for each of the fields in the tuple, based on the type of each field. """ def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self._ts = ts = TupleStructure(self) self._ui = ui = ts.view.ui(ts, parent, kind="subpanel").trait_set( @@ -80,22 +79,20 @@ def init(self, parent): self.set_tooltip() def update_editor(self): - """ Updates the editor when the object trait changes external to the - editor. + """Updates the editor when the object trait changes external to the + editor. """ ts = self._ts for i, value in enumerate(self.value): setattr(ts, "f%d" % i, value) def get_error_control(self): - """ Returns the editor's control for indicating error status. - """ + """Returns the editor's control for indicating error status.""" return self._ui.get_error_controls() class TupleStructure(HasTraits): - """ Creates a view containing items for each field in a tuple. - """ + """Creates a view containing items for each field in a tuple.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -111,8 +108,7 @@ class TupleStructure(HasTraits): fields = Int() def __init__(self, editor): - """ Initializes the object. - """ + """Initializes the object.""" super().__init__(editor=editor) factory = editor.factory @@ -187,8 +183,7 @@ def __init__(self, editor): self.view = View(Group(show_labels=(len_labels != 0), *content)) def _field_changed(self, name, old, new): - """ Updates the underlying tuple when any field changes value. - """ + """Updates the underlying tuple when any field changes value.""" index = int(name[1:]) value = self.editor.value if new != value[index]: diff --git a/traitsui/editors/value_editor.py b/traitsui/editors/value_editor.py index c0bc0dc8d..50ee7d1b1 100644 --- a/traitsui/editors/value_editor.py +++ b/traitsui/editors/value_editor.py @@ -26,8 +26,7 @@ class _ValueEditor(Editor): - """ Simple style of editor for values, which displays a tree. - """ + """Simple style of editor for values, which displays a tree.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -43,8 +42,8 @@ class _ValueEditor(Editor): scrollable = True def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.update_editor() editor = TreeEditor( @@ -63,27 +62,24 @@ def init(self, parent): self.control = self._ui.control def update_editor(self): - """ Updates the editor when the object trait changes external to the - editor. + """Updates the editor when the object trait changes external to the + editor. """ self.root = RootNode(name="", value=self.value, readonly=self.readonly) def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" self._ui.dispose() super().dispose() def get_error_control(self): - """ Returns the editor's control for indicating error status. - """ + """Returns the editor's control for indicating error status.""" return self._ui.get_error_controls() class ValueEditor(EditorFactory): - """ Editor factory for tree-based value editors. - """ + """Editor factory for tree-based value editors.""" # ------------------------------------------------------------------------- # Trait definitions: diff --git a/traitsui/editors/video_editor.py b/traitsui/editors/video_editor.py index edaac096e..f6f9e8b5d 100644 --- a/traitsui/editors/video_editor.py +++ b/traitsui/editors/video_editor.py @@ -19,8 +19,15 @@ AspectRatio = Enum('keep', 'ignore', 'expand') PlayerState = Enum('stopped', 'playing', 'paused') MediaStatus = Enum( - 'unknown', 'no_media', 'loading', 'loaded', 'stalled', 'buffering', - 'buffered', 'end', 'invalid', + 'unknown', + 'no_media', + 'loading', + 'loaded', + 'stalled', + 'buffering', + 'buffered', + 'end', + 'invalid', ) @@ -57,21 +64,25 @@ class VideoEditor(BasicEditorFactory): position = CVType(Float, default_value=0.0, sync_value='both') #: Duration of the loaded video in seconds - duration = Instance(ContextValue, args=('',), - allow_none=False, sync_value='to') + duration = Instance( + ContextValue, args=('',), allow_none=False, sync_value='to' + ) #: The status of the loaded video (see ``MediaStatus``) - media_status = Instance(ContextValue, args=('',), - allow_none=False, sync_value='to') + media_status = Instance( + ContextValue, args=('',), allow_none=False, sync_value='to' + ) #: An integer percentage representing how much of the player's buffer #: is filled. - buffer = Instance(ContextValue, args=('',), - allow_none=False, sync_value='to') + buffer = Instance( + ContextValue, args=('',), allow_none=False, sync_value='to' + ) #: A string describing an error encountered by the player - video_error = Instance(ContextValue, args=('',), - allow_none=False, sync_value='to') + video_error = Instance( + ContextValue, args=('',), allow_none=False, sync_value='to' + ) #: Callable to apply to video frames. Takes ref to new frame and a size #: tuple. Must return a QImage and a numpy array. @@ -82,6 +93,5 @@ class VideoEditor(BasicEditorFactory): notify_interval = CVType(Float, default_value=1.0, sync_value='from') def _get_klass(self): - """ Returns the editor class to be instantiated. - """ + """Returns the editor class to be instantiated.""" return toolkit_object('video_editor:VideoEditor') diff --git a/traitsui/examples/demo/Advanced/Adapted_tree_editor_demo.py b/traitsui/examples/demo/Advanced/Adapted_tree_editor_demo.py index 940ebf4b6..910801da3 100644 --- a/traitsui/examples/demo/Advanced/Adapted_tree_editor_demo.py +++ b/traitsui/examples/demo/Advanced/Adapted_tree_editor_demo.py @@ -33,56 +33,60 @@ tree view. """ -#-- Imports -------------------------------------------------------------- +# -- Imports -------------------------------------------------------------- from os import getcwd from traits.api import ( - HasTraits, Property, Directory, property_depends_on, register_factory + HasTraits, + Property, + Directory, + property_depends_on, + register_factory, ) from traitsui.api import ( - View, VGroup, Item, TreeEditor, ITreeNode, ITreeNodeAdapter + View, + VGroup, + Item, + TreeEditor, + ITreeNode, + ITreeNodeAdapter, ) from apptools.io.api import File -#-- FileAdapter Class ---------------------------------------------------- +# -- FileAdapter Class ---------------------------------------------------- + class FileAdapter(ITreeNodeAdapter): - #-- ITreeNodeAdapter Method Overrides ------------------------------------ + # -- ITreeNodeAdapter Method Overrides ------------------------------------ def allows_children(self): - """ Returns whether this object can have children. - """ + """Returns whether this object can have children.""" return self.adaptee.is_folder def has_children(self): - """ Returns whether the object has children. - """ + """Returns whether the object has children.""" children = self.adaptee.children - return ((children is not None) and (len(children) > 0)) + return (children is not None) and (len(children) > 0) def get_children(self): - """ Gets the object's children. - """ + """Gets the object's children.""" return self.adaptee.children def get_label(self): - """ Gets the label to display for a specified object. - """ + """Gets the label to display for a specified object.""" return self.adaptee.name + self.adaptee.ext def get_tooltip(self): - """ Gets the tooltip to display for a specified object. - """ + """Gets the tooltip to display for a specified object.""" return self.adaptee.absolute_path def get_icon(self, is_expanded): - """ Returns the icon for a specified object. - """ + """Returns the icon for a specified object.""" if self.adaptee.is_file: return '' @@ -92,12 +96,13 @@ def get_icon(self, is_expanded): return '' def can_auto_close(self): - """ Returns whether the object's children should be automatically - closed. + """Returns whether the object's children should be automatically + closed. """ return True -#-- FileTreeDemo Class --------------------------------------------------- + +# -- FileTreeDemo Class --------------------------------------------------- class FileTreeDemo(HasTraits): @@ -112,28 +117,27 @@ class FileTreeDemo(HasTraits): view = View( VGroup( Item('root_path'), - Item('root', - editor=TreeEditor(editable=False, auto_open=1) - ), - show_labels=False + Item('root', editor=TreeEditor(editable=False, auto_open=1)), + show_labels=False, ), width=0.33, height=0.50, - resizable=True + resizable=True, ) - #-- Traits Default Value Methods ----------------------------------------- + # -- Traits Default Value Methods ----------------------------------------- def _root_path_default(self): return getcwd() - #-- Property Implementations --------------------------------------------- + # -- Property Implementations --------------------------------------------- @property_depends_on('root_path') def _get_root(self): return File(path=self.root_path) -#-- Create and run the demo ---------------------------------------------- + +# -- Create and run the demo ---------------------------------------------- register_factory(FileAdapter, File, ITreeNode) diff --git a/traitsui/examples/demo/Advanced/Apply_Revert_handler_demo.py b/traitsui/examples/demo/Advanced/Apply_Revert_handler_demo.py index d22bcda27..07b7bcb0a 100644 --- a/traitsui/examples/demo/Advanced/Apply_Revert_handler_demo.py +++ b/traitsui/examples/demo/Advanced/Apply_Revert_handler_demo.py @@ -24,7 +24,6 @@ class ApplyRevert_Handler(Handler): - def apply(self, info): print('apply called...') object = info.object @@ -47,43 +46,45 @@ class ApplyRevertDemo(HasTraits): traits_view = View( VGroup( VGroup( - Item('input', - show_label=False, - editor=TextEditor(auto_set=True) - ), + Item( + 'input', show_label=False, editor=TextEditor(auto_set=True) + ), label='Input', - show_border=True + show_border=True, ), HGroup( VGroup( - Item('stack', - show_label=False, - height=50, - width=100, - style='readonly' - ), + Item( + 'stack', + show_label=False, + height=50, + width=100, + style='readonly', + ), label='Stack', - show_border=True + show_border=True, ), VGroup( - Item('queue', - show_label=False, - height=50, - width=100, - style='readonly' - ), + Item( + 'queue', + show_label=False, + height=50, + width=100, + style='readonly', + ), label='Queue', - show_border=True - ) - ) + show_border=True, + ), + ), ), resizable=True, height=300, title='Apply/Revert example', buttons=['Apply', 'Revert'], - handler=ApplyRevert_Handler + handler=ApplyRevert_Handler, ) + # Create the demo: modal_popup = ApplyRevertDemo() diff --git a/traitsui/examples/demo/Advanced/Auto_editable_readonly_table_cells.py b/traitsui/examples/demo/Advanced/Auto_editable_readonly_table_cells.py index 80498898b..fda63de26 100644 --- a/traitsui/examples/demo/Advanced/Auto_editable_readonly_table_cells.py +++ b/traitsui/examples/demo/Advanced/Auto_editable_readonly_table_cells.py @@ -32,21 +32,25 @@ trait. """ -#-- Imports -------------------------------------------------------------- +# -- Imports -------------------------------------------------------------- from operator import attrgetter -from traits.api \ - import HasTraits, Int, List, Range, Property, property_depends_on +from traits.api import ( + HasTraits, + Int, + List, + Range, + Property, + property_depends_on, +) -from traitsui.api \ - import View, VGroup, Item, TableEditor +from traitsui.api import View, VGroup, Item, TableEditor -from traitsui.table_column \ - import ObjectColumn +from traitsui.table_column import ObjectColumn -#-- Integer Class -------------------------------------------------------- +# -- Integer Class -------------------------------------------------------- class Integer(HasTraits): @@ -54,7 +58,8 @@ class Integer(HasTraits): # The value: n = Int() -#-- Factor Class --------------------------------------------------------- + +# -- Factor Class --------------------------------------------------------- class Factor(HasTraits): @@ -83,29 +88,30 @@ def _get_factors(self): return result -#-- The table editor used for the pop-up view ---------------------------- + +# -- The table editor used for the pop-up view ---------------------------- factor_table_editor = TableEditor( columns=[ - ObjectColumn(name='n', - width=1.0, - editable=False, - horizontal_alignment='center') + ObjectColumn( + name='n', width=1.0, editable=False, horizontal_alignment='center' + ) ], sortable=False, auto_size=False, show_toolbar=False, - show_column_labels=False + show_column_labels=False, ) -#-- The table editor used for the main view ------------------------------ +# -- The table editor used for the main view ------------------------------ factors_view = View( - Item('factors', - id='factors', - show_label=False, - editor=factor_table_editor, - ), + Item( + 'factors', + id='factors', + show_label=False, + editor=factor_table_editor, + ), id='traits.examples.demo.Advanced.factors_view', kind='info', height=0.30, @@ -113,24 +119,25 @@ def _get_factors(self): factors_table_editor = TableEditor( columns=[ - ObjectColumn(name='n', - width=0.5, - editable=False, - horizontal_alignment='center'), - ObjectColumn(name='factors', - width=0.5, - editable=False, - horizontal_alignment='center', - auto_editable=True, - format_func=lambda f: '%s factors' % len(f), - view=factors_view), + ObjectColumn( + name='n', width=0.5, editable=False, horizontal_alignment='center' + ), + ObjectColumn( + name='factors', + width=0.5, + editable=False, + horizontal_alignment='center', + auto_editable=True, + format_func=lambda f: '%s factors' % len(f), + view=factors_view, + ), ], sortable=False, auto_size=False, - show_toolbar=False + show_toolbar=False, ) -#-- Factors Class -------------------------------------------------------- +# -- Factors Class -------------------------------------------------------- class Factors(HasTraits): @@ -148,26 +155,24 @@ class Factors(HasTraits): Item('max_n'), show_labels=False, show_border=True, - label='Maximum Number' + label='Maximum Number', ), VGroup( - Item('factors', - show_label=False, - editor=factors_table_editor - ), - ) + Item('factors', show_label=False, editor=factors_table_editor), + ), ), title='List of numbers and their factors', width=0.2, height=0.4, - resizable=True + resizable=True, ) @property_depends_on('max_n') def _get_factors(self): return [Factor(n=i + 1) for i in range(self.max_n)] -#-- Create and run the demo ---------------------------------------------- + +# -- Create and run the demo ---------------------------------------------- # Create the demo: demo = Factors() diff --git a/traitsui/examples/demo/Advanced/Auto_update_TabularEditor_demo.py b/traitsui/examples/demo/Advanced/Auto_update_TabularEditor_demo.py index b2ce7df9c..6f6b73052 100644 --- a/traitsui/examples/demo/Advanced/Auto_update_TabularEditor_demo.py +++ b/traitsui/examples/demo/Advanced/Auto_update_TabularEditor_demo.py @@ -41,7 +41,12 @@ from traits.api import HasTraits, Str, Float, List, Instance, Button from traitsui.api import ( - View, HGroup, Item, TabularAdapter, TabularEditor, spring + View, + HGroup, + Item, + TabularAdapter, + TabularEditor, + spring, ) @@ -77,8 +82,8 @@ class Company(HasTraits): adapter=EmployeeAdapter(), selected='employee', auto_resize=True, - auto_update=True - ) + auto_update=True, + ), ), HGroup( spring, @@ -86,13 +91,13 @@ class Company(HasTraits): Item( 'give_raise', show_label=False, - enabled_when='employee is not None' - ) + enabled_when='employee is not None', + ), ), title='Auto Update Tabular Editor demo', height=0.25, width=0.30, - resizable=True + resizable=True, ) def _give_raise_changed(self): @@ -109,8 +114,8 @@ def _give_raise_changed(self): Employee(name='Jim', salary=39000), Employee(name='Helen', salary=41000), Employee(name='George', salary=49000), - Employee(name='Betty', salary=46000) - ] + Employee(name='Betty', salary=46000), + ], ) # Run the demo (if invoked from the command line): diff --git a/traitsui/examples/demo/Advanced/Date_editor_demo.py b/traitsui/examples/demo/Advanced/Date_editor_demo.py index 24b061be0..df7ea2dfa 100644 --- a/traitsui/examples/demo/Advanced/Date_editor_demo.py +++ b/traitsui/examples/demo/Advanced/Date_editor_demo.py @@ -28,11 +28,14 @@ class DateEditorDemo(HasTraits): - """ Demo class to show Date editors. """ + """Demo class to show Date editors.""" + single_date = Date() multi_date = List(Date) - info_string = Str('The editors for Traits Date objects. Showing both ' - 'the defaults, and one with alternate options.') + info_string = Str( + 'The editors for Traits Date objects. Showing both ' + 'the defaults, and one with alternate options.' + ) multi_select_editor = DateEditor( allow_future=False, @@ -54,35 +57,35 @@ class DateEditorDemo(HasTraits): style='readonly', editor=DateEditor( strftime='You picked %B %d %Y', - message='Click a date above.' + message='Click a date above.', ), - label='ReadOnly editor' + label='ReadOnly editor', ), - label='Default settings for editors' + label='Default settings for editors', ), Group( Item( 'multi_date', editor=multi_select_editor, style='custom', - label='Multi-select custom editor' + label='Multi-select custom editor', ), label='More customized editor: multi-select; disallow ' - 'future; selection style; etc.' + 'future; selection style; etc.', ), - resizable=True + resizable=True, ) def _multi_date_changed(self): - """ Print each time the date value is changed in the editor. """ + """Print each time the date value is changed in the editor.""" print(self.multi_date) def _simple_date_changed(self): - """ Print each time the date value is changed in the editor. """ + """Print each time the date value is changed in the editor.""" print(self.simple_date, self.single_date) def _single_date_changed(self): - """ Print each time the date value is changed in the editor. """ + """Print each time the date value is changed in the editor.""" print(self.single_date) diff --git a/traitsui/examples/demo/Advanced/Date_range_editor_demo.py b/traitsui/examples/demo/Advanced/Date_range_editor_demo.py index 853e9639f..87937d042 100644 --- a/traitsui/examples/demo/Advanced/Date_range_editor_demo.py +++ b/traitsui/examples/demo/Advanced/Date_range_editor_demo.py @@ -22,7 +22,8 @@ class DateRangeEditorDemo(HasTraits): - """ Demo class to show DateRangeEditor. """ + """Demo class to show DateRangeEditor.""" + date_range = Tuple(Date, Date) traits_view = View( @@ -31,11 +32,11 @@ class DateRangeEditorDemo(HasTraits): 'date_range', editor=DateRangeEditor(), style='custom', - label='Date range' + label='Date range', ), - label='Date range' + label='Date range', ), - resizable=True + resizable=True, ) def _date_range_changed(self): diff --git a/traitsui/examples/demo/Advanced/Dynamic_EnumEditor_demo.py b/traitsui/examples/demo/Advanced/Dynamic_EnumEditor_demo.py index 619b008f7..b8f2934b4 100644 --- a/traitsui/examples/demo/Advanced/Dynamic_EnumEditor_demo.py +++ b/traitsui/examples/demo/Advanced/Dynamic_EnumEditor_demo.py @@ -60,10 +60,15 @@ from traits.api import Enum, HasPrivateTraits, Instance, List from traitsui.api import ( - View, Item, VGroup, HSplit, EnumEditor, CheckListEditor + View, + Item, + VGroup, + HSplit, + EnumEditor, + CheckListEditor, ) -#-- The list of possible entrees ----------------------------------------- +# -- The list of possible entrees ----------------------------------------- possible_entrees = [ 'Chicken Fried Steak', @@ -74,10 +79,10 @@ 'Beef Tacos', 'Club Sandwich', 'Ceasar Salad', - 'Cobb Salad' + 'Cobb Salad', ] -#-- The KitchenCapabilities class ---------------------------------------- +# -- The KitchenCapabilities class ---------------------------------------- class KitchenCapabilities(HasPrivateTraits): @@ -85,10 +90,11 @@ class KitchenCapabilities(HasPrivateTraits): # The current set of entrees the kitchen can make (based on its larder): available = List(possible_entrees) + # The KitchenCapabilities are shared by all waitstaff taking orders: kitchen_capabilities = KitchenCapabilities() -#-- The OrderMenu class -------------------------------------------------- +# -- The OrderMenu class -------------------------------------------------- class OrderMenu(HasPrivateTraits): @@ -106,33 +112,36 @@ def _capabilities_default(self): view = View( HSplit( VGroup( - Item('entree', - editor=EnumEditor( - name='object.capabilities.available', - evaluate=str, - completion_mode='popup', - ) - ), + Item( + 'entree', + editor=EnumEditor( + name='object.capabilities.available', + evaluate=str, + completion_mode='popup', + ), + ), label='Order', show_border=True, - dock='tab' + dock='tab', ), VGroup( - Item('object.capabilities.available', - show_label=False, - style='custom', - editor=CheckListEditor(values=possible_entrees) - ), + Item( + 'object.capabilities.available', + show_label=False, + style='custom', + editor=CheckListEditor(values=possible_entrees), + ), label='Kitchen', show_border=True, - dock='tab' - ) + dock='tab', + ), ), title='Dynamic EnumEditor Demo', resizable=True, ) -#------------------------------------------------------------------------- + +# ------------------------------------------------------------------------- # Create the demo: demo = OrderMenu() diff --git a/traitsui/examples/demo/Advanced/Dynamic_range_trait_and_editor.py b/traitsui/examples/demo/Advanced/Dynamic_range_trait_and_editor.py index ffa9ab112..9aa0f5b56 100644 --- a/traitsui/examples/demo/Advanced/Dynamic_range_trait_and_editor.py +++ b/traitsui/examples/demo/Advanced/Dynamic_range_trait_and_editor.py @@ -59,24 +59,31 @@ 'plan'. """ -#-- Imports -------------------------------------------------------------- +# -- Imports -------------------------------------------------------------- import logging import sys -from random \ - import choice +from random import choice -from traits.api \ - import HasPrivateTraits, Str, Enum, Range, List, Button, Instance, \ - Property, cached_property, observe +from traits.api import ( + HasPrivateTraits, + Str, + Enum, + Range, + List, + Button, + Instance, + Property, + cached_property, + observe, +) -from traitsui.api \ - import View, VGroup, HGroup, Item, ListEditor, spring +from traitsui.api import View, VGroup, HGroup, Item, ListEditor, spring logging.basicConfig(stream=sys.stderr) -#-- The Hotel class ------------------------------------------------------ +# -- The Hotel class ------------------------------------------------------ class Hotel(HasPrivateTraits): @@ -100,40 +107,42 @@ class Hotel(HasPrivateTraits): view = View( VGroup( HGroup( - Item('season'), '20', + Item('season'), + '20', Item('fuel_cost', width=300), spring, Item('add_guest', show_label=False), show_border=True, - label='Hotel Information' + label='Hotel Information', ), VGroup( - Item('guests', - style='custom', - editor=ListEditor(use_notebook=True, - deletable=True, - dock_style='tab', - page_name='.name') - ), + Item( + 'guests', + style='custom', + editor=ListEditor( + use_notebook=True, + deletable=True, + dock_style='tab', + page_name='.name', + ), + ), show_labels=False, show_border=True, - label='Guests' - ) + label='Guests', + ), ), title='The Belmont Hotel Dashboard', width=0.6, height=0.2, - resizable=True + resizable=True, ) # Property implementations: @cached_property def _get_min_temperature(self): - return ({'Winter': 32, - 'Spring': 40, - 'Summer': 45, - 'Fall': 40}[self.season] + - min(int(60.00 / self.fuel_cost), 15)) + return {'Winter': 32, 'Spring': 40, 'Summer': 45, 'Fall': 40}[ + self.season + ] + min(int(60.00 / self.fuel_cost), 15) # Event handlers: @observe('guests.items') @@ -150,7 +159,8 @@ def _guests_modified(self, event): def _add_guest_changed(self): self.guests.append(Guest(hotel=self)) -#-- The Guest class ------------------------------------------------------ + +# -- The Guest class ------------------------------------------------------ class Guest(HasPrivateTraits): @@ -171,27 +181,40 @@ class Guest(HasPrivateTraits): temperature = Range('hotel.min_temperature', 'max_temperature') # The view of the guest: - view = View( - Item('plan'), - Item('temperature') - ) + view = View(Item('plan'), Item('temperature')) # Property implementations: @cached_property def _get_max_temperature(self): - return {'Flop house': 62, - 'Cheap': 66, - 'Cozy': 75, - 'Deluxe': 85}[self.plan] + return {'Flop house': 62, 'Cheap': 66, 'Cozy': 75, 'Deluxe': 85}[ + self.plan + ] # Default values: def _name_default(self): return choice( - ['Leah', 'Vibha', 'Janet', 'Jody', 'Dave', 'Evan', 'Ilan', 'Gael', - 'Peter', 'Robert', 'Judah', 'Eric', 'Travis', 'Mike', 'Bryce', - 'Chris']) - -#-- Create the demo ------------------------------------------------------ + [ + 'Leah', + 'Vibha', + 'Janet', + 'Jody', + 'Dave', + 'Evan', + 'Ilan', + 'Gael', + 'Peter', + 'Robert', + 'Judah', + 'Eric', + 'Travis', + 'Mike', + 'Bryce', + 'Chris', + ] + ) + + +# -- Create the demo ------------------------------------------------------ # Create the demo object: demo = Hotel(guests=[Guest() for i in range(5)]) diff --git a/traitsui/examples/demo/Advanced/Dynamic_views_demo.py b/traitsui/examples/demo/Advanced/Dynamic_views_demo.py index dfa3fe4ba..4e22c13c7 100644 --- a/traitsui/examples/demo/Advanced/Dynamic_views_demo.py +++ b/traitsui/examples/demo/Advanced/Dynamic_views_demo.py @@ -20,13 +20,12 @@ class HasFooView(HasDynamicViews): - """ A base class declaring the existence of the 'foo' dynamic view. - """ + """A base class declaring the existence of the 'foo' dynamic view.""" def __init__(self, *args, **traits): - """ Constructor. + """Constructor. - Extended to declare our dynamic foo view. + Extended to declare our dynamic foo view. """ super().__init__(*args, **traits) @@ -48,14 +47,12 @@ def __init__(self, *args, **traits): class MyInfoHandler(Handler): - def object_first_changed(self, info): info.object.derived = info.object.first class BaseFoo(HasFooView): - """ A base class that puts some content in the 'foo' dynamic view. - """ + """A base class that puts some content in the 'foo' dynamic view.""" first = Str('My first name') last = Str('My last name') @@ -65,14 +62,16 @@ class BaseFoo(HasFooView): derived = Str() ui_person = Group( - Item(label='On this tab, notice how the sub-handler keeps\n' - 'the derived value equal to the first name.\n\n' - 'On the next tab, change the selection in order to\n' - 'control which tabs are visible when the ui is \n' - 'displayed for the 2nd time.' - ), + Item( + label='On this tab, notice how the sub-handler keeps\n' + 'the derived value equal to the first name.\n\n' + 'On the next tab, change the selection in order to\n' + 'control which tabs are visible when the ui is \n' + 'displayed for the 2nd time.' + ), spring, - 'first', 'last', + 'first', + 'last', spring, 'derived', label='My Info', @@ -83,17 +82,16 @@ class BaseFoo(HasFooView): class FatherInfoHandler(Handler): - def object_father_first_name_changed(self, info): info.object.father_derived = info.object.father_first_name class DerivedFoo(BaseFoo): - """ A derived class that puts additional content in the 'foo' dynamic view. - Note that the additional content could also have been added via a traits - category contribution, or even dynamic manipulation of metadata on a UI - subelement. The key is what the metadata represents when the view is - *created* + """A derived class that puts additional content in the 'foo' dynamic view. + Note that the additional content could also have been added via a traits + category contribution, or even dynamic manipulation of metadata on a UI + subelement. The key is what the metadata represents when the view is + *created* """ knows_mother = Bool(False) @@ -147,22 +145,24 @@ def _knows_father_changed(self, old, new): class FooDemo(HasTraits): - """ Defines a class to run the demo. - """ + """Defines a class to run the demo.""" foo = Instance(DerivedFoo, ()) configure = Button('Configure') view = View( - Label("Try configuring several times, each time changing the items " - "on the 'Parents?' tab."), + Label( + "Try configuring several times, each time changing the items " + "on the 'Parents?' tab." + ), '_', - HGroup(spring, Item('configure', show_label=False)) + HGroup(spring, Item('configure', show_label=False)), ) def _configure_changed(self): self.foo.configure_traits() + # Create the demo: popup = FooDemo() diff --git a/traitsui/examples/demo/Advanced/Dynamically_changing_buttons_demo.py b/traitsui/examples/demo/Advanced/Dynamically_changing_buttons_demo.py index 04895b9ed..49326266b 100644 --- a/traitsui/examples/demo/Advanced/Dynamically_changing_buttons_demo.py +++ b/traitsui/examples/demo/Advanced/Dynamically_changing_buttons_demo.py @@ -27,16 +27,14 @@ InstanceEditor, Item, UItem, - View + View, ) import traitsui.extras class ImageChoice(InstanceChoice): def get_view(self): - return View( - UItem('name', editor=ImageEditor(image=self.object)) - ) + return View(UItem('name', editor=ImageEditor(image=self.object))) class ButtonEditorDemo(HasTraits): @@ -53,8 +51,8 @@ class ButtonEditorDemo(HasTraits): ImageResource("previous", [traitsui.extras]), ImageResource("next", [traitsui.extras]), ImageResource("parent", [traitsui.extras]), - ImageResource("reload", [traitsui.extras]) - ] + ImageResource("reload", [traitsui.extras]), + ], ) def _my_button_image_default(self): @@ -67,20 +65,20 @@ def _my_button_image_default(self): editor=ButtonEditor( label_value="my_button_label", image_value="my_button_image", - orientation="horizontal" - ) + orientation="horizontal", + ), ), Item("my_button_label"), Item( "my_button_image", editor=InstanceEditor( - name="my_button_image_options", - adapter=ImageChoice + name="my_button_image_options", adapter=ImageChoice ), - style="custom" - ) + style="custom", + ), ) + # Create the demo: demo = ButtonEditorDemo() diff --git a/traitsui/examples/demo/Advanced/HDF5_tree_demo.py b/traitsui/examples/demo/Advanced/HDF5_tree_demo.py index fa1d4f2f7..ae7c8b9a5 100644 --- a/traitsui/examples/demo/Advanced/HDF5_tree_demo.py +++ b/traitsui/examples/demo/Advanced/HDF5_tree_demo.py @@ -63,16 +63,22 @@ class Hdf5FileNode(HasTraits): arrays = List(Hdf5ArrayNode) groups_and_arrays = List() + # Recursively build tree, there is probably a better way of doing this. def _get_sub_arrays(group, h5file): """Return a list of all arrays immediately below a group in an HDF5 file.""" - return [Hdf5ArrayNode(name=array._v_name, - path=array._v_pathname, - parent_path=array._v_parent._v_pathname) - for array in group if isinstance(array, (tb.Array, tb.Table))] # More pythonic - # for array in h5file.iter_nodes(group, classname='Array')] # Old call + return [ + Hdf5ArrayNode( + name=array._v_name, + path=array._v_pathname, + parent_path=array._v_parent._v_pathname, + ) + for array in group + if isinstance(array, (tb.Array, tb.Table)) + ] # More pythonic + # for array in h5file.iter_nodes(group, classname='Array')] # Old call def _get_sub_groups(group, h5file): @@ -82,13 +88,16 @@ def _get_sub_groups(group, h5file): for subgroup in h5file.iter_nodes(group, classname='Group'): subsubgroups = _get_sub_groups(subgroup, h5file) subsubarrays = _get_sub_arrays(subgroup, h5file) - subgroups.append(Hdf5GroupNode(name=subgroup._v_name, - path=subgroup._v_pathname, - parent_path=subgroup._v_parent._v_pathname, - groups=subsubgroups, - arrays=subsubarrays, - groups_and_arrays=subsubgroups + subsubarrays) - ) + subgroups.append( + Hdf5GroupNode( + name=subgroup._v_name, + path=subgroup._v_pathname, + parent_path=subgroup._v_parent._v_pathname, + groups=subsubgroups, + arrays=subsubarrays, + groups_and_arrays=subsubgroups + subsubarrays, + ) + ) return subgroups @@ -98,13 +107,16 @@ def _hdf5_tree(filename): with tb.open_file(filename, 'r') as h5file: subgroups = _get_sub_groups(h5file.root, h5file) subarrays = _get_sub_arrays(h5file.root, h5file) - h5_tree = Hdf5FileNode(name=filename, - groups=subgroups, - arrays=subarrays, - groups_and_arrays=subgroups + subarrays) + h5_tree = Hdf5FileNode( + name=filename, + groups=subgroups, + arrays=subarrays, + groups_and_arrays=subgroups + subarrays, + ) return h5_tree + # Get a tree editor @@ -145,18 +157,19 @@ class ATree(HasTraits): traits_view = View( Group( - Item('h5_tree', - editor=_hdf5_tree_editor(selected='node'), - resizable=True, - show_label=False, - ), + Item( + 'h5_tree', + editor=_hdf5_tree_editor(selected='node'), + resizable=True, + show_label=False, + ), orientation='vertical', ), title='HDF5 Tree Example', buttons=['Undo', 'OK', 'Cancel'], resizable=True, - width=.3, - height=.3 + width=0.3, + height=0.3, ) def _node_changed(self): @@ -169,49 +182,83 @@ def make_test_datasets(): import numpy as np import pandas as pd # pandas uses pytables to store datasets in hdf5 format. from random import randrange + n = 100 - df = pd.DataFrame(dict([("int{0}".format(i), np.random.randint(0, 10, size=n)) - for i in range(5)])) + df = pd.DataFrame( + dict( + [ + ("int{0}".format(i), np.random.randint(0, 10, size=n)) + for i in range(5) + ] + ) + ) df['float'] = np.random.randn(n) for i in range(10): - df["object_1_{0}".format(i)] = ['%08x' % randrange(16**8) for _ in range(n)] + df["object_1_{0}".format(i)] = [ + '%08x' % randrange(16 ** 8) for _ in range(n) + ] for i in range(7): - df["object_2_{0}".format(i)] = ['%15x' % randrange(16**15) for _ in range(n)] + df["object_2_{0}".format(i)] = [ + '%15x' % randrange(16 ** 15) for _ in range(n) + ] df.info() df.to_hdf('test_fixed.h5', 'data', format='fixed') df.to_hdf('test_table_no_dc.h5', 'data', format='table') df.to_hdf('test_table_dc.h5', 'data', format='table', data_columns=True) - df.to_hdf('test_fixed_compressed.h5', 'data', format='fixed', complib='blosc', complevel=9) + df.to_hdf( + 'test_fixed_compressed.h5', + 'data', + format='fixed', + complib='blosc', + complevel=9, + ) # h5py dataset time = np.arange(n) x = np.linspace(-7, 7, n) - axes_latlon = [('time', time), ('coordinate', np.array(['lat', 'lon'], dtype='S3'))] - axes_mag = [('time', time), ('direction', np.array(['x', 'y', 'z'], dtype='S1'))] - latlon = np.vstack((np.linspace(-0.0001, 0.00001, n) + 23.8, - np.zeros(n) - 82.3)).T - mag_data = np.vstack((-(1 - np.tanh(x)**2) * np.sin(2 * x), - -(1 - np.tanh(x)**2) * np.sin(2 * x), - -(1 - np.tanh(x)**2))).T - datasets = axes_mag + axes_latlon + [('magnetic_3_axial', mag_data), ('latlon', latlon)] + axes_latlon = [ + ('time', time), + ('coordinate', np.array(['lat', 'lon'], dtype='S3')), + ] + axes_mag = [ + ('time', time), + ('direction', np.array(['x', 'y', 'z'], dtype='S1')), + ] + latlon = np.vstack( + (np.linspace(-0.0001, 0.00001, n) + 23.8, np.zeros(n) - 82.3) + ).T + mag_data = np.vstack( + ( + -(1 - np.tanh(x) ** 2) * np.sin(2 * x), + -(1 - np.tanh(x) ** 2) * np.sin(2 * x), + -(1 - np.tanh(x) ** 2), + ) + ).T + datasets = ( + axes_mag + + axes_latlon + + [('magnetic_3_axial', mag_data), ('latlon', latlon)] + ) with h5py.File(os.path.join(ROOT, 'test_h5pydata.h5'), "a") as h5file: h5group = h5file.require_group("run1_test1") for data_name, data in datasets: - h5group.require_dataset(name=data_name, - dtype=data.dtype, - shape=data.shape, - data=data, - # **options - ) + h5group.require_dataset( + name=data_name, + dtype=data.dtype, + shape=data.shape, + data=data, + # **options + ) def main(): import sys + filename = os.path.join(ROOT, 'test_fixed.h5') filename = os.path.join(ROOT, 'test_table_no_dc.h5') if len(sys.argv) > 1: diff --git a/traitsui/examples/demo/Advanced/HDF5_tree_demo2.py b/traitsui/examples/demo/Advanced/HDF5_tree_demo2.py index d0ccf9f8b..e2714dcab 100644 --- a/traitsui/examples/demo/Advanced/HDF5_tree_demo2.py +++ b/traitsui/examples/demo/Advanced/HDF5_tree_demo2.py @@ -73,16 +73,19 @@ class Hdf5FilesNode(api.HasTraits): files = api.List(Hdf5FileNode) groups_and_arrays = api.List() + # Recursively build tree, there is probably a better way of doing this. def _get_sub_arrays(group, parent_path): """Return a list of all arrays immediately below a group in an HDF5 file.""" - return [Hdf5ArrayNode(name=name, - path=parent_path + name, - parent_path=parent_path) - for name, array in group.items() - if isinstance(array, h5py.Dataset)] + return [ + Hdf5ArrayNode( + name=name, path=parent_path + name, parent_path=parent_path + ) + for name, array in group.items() + if isinstance(array, h5py.Dataset) + ] def _get_sub_groups(group, parent_path): @@ -94,27 +97,34 @@ def _get_sub_groups(group, parent_path): path = parent_path + name + '/' subsubarrays = _get_sub_arrays(subgroup, path) subsubgroups = _get_sub_groups(subgroup, path) - subgroups.append(Hdf5GroupNode(name=name, - path=path, - parent_path=parent_path, - arrays=subsubarrays, - subgroups=subsubgroups, - groups_and_arrays=subsubgroups + subsubarrays) - ) + subgroups.append( + Hdf5GroupNode( + name=name, + path=path, + parent_path=parent_path, + arrays=subsubarrays, + subgroups=subsubgroups, + groups_and_arrays=subsubgroups + subsubarrays, + ) + ) return subgroups def _hdf5_tree(filename): with h5py.File(filename, 'r') as h5file: - path = filename + '#' # separate dataset name from name of hdf5-filename + path = ( + filename + '#' + ) # separate dataset name from name of hdf5-filename subgroups = _get_sub_groups(h5file, path) subarrays = _get_sub_arrays(h5file, path) - file_tree = Hdf5FileNode(name=os.path.basename(filename), - path=filename, - groups=subgroups, - arrays=subarrays, - groups_and_arrays=subgroups + subarrays) + file_tree = Hdf5FileNode( + name=os.path.basename(filename), + path=filename, + groups=subgroups, + arrays=subarrays, + groups_and_arrays=subgroups + subarrays, + ) return file_tree @@ -130,8 +140,11 @@ def _hdf5_trees(filenames): for filename in filenames: folder = os.path.dirname(filename) if folder != root: - warnings.warn("Expected same folder for all files, but got {} != {}".format(root, - folder)) + warnings.warn( + "Expected same folder for all files, but got {} != {}".format( + root, folder + ) + ) file_tree = _hdf5_tree(filename) files_tree.files.append(file_tree) @@ -144,34 +157,40 @@ def _hdf5_trees(filenames): def _hdf5_tree_editor(selected=''): """Return a ui.TreeEditor specifically for HDF5 file trees.""" - return ui.TreeEditor(nodes=[ui.TreeNode(node_for=[Hdf5FilesNode], - auto_open=True, - children='files', - label='name', - view=no_view, - ), - ui.TreeNode(node_for=[Hdf5FileNode], - auto_open=True, - children='groups_and_arrays', - label='name', - view=no_view, - ), - ui.TreeNode(node_for=[Hdf5GroupNode], - auto_open=False, - children='groups_and_arrays', - label='name', - view=no_view, - ), - ui.TreeNode(node_for=[Hdf5ArrayNode], - auto_open=False, - children='', - label='name', - view=no_view, - ), - ], - editable=False, - selected=selected, - ) + return ui.TreeEditor( + nodes=[ + ui.TreeNode( + node_for=[Hdf5FilesNode], + auto_open=True, + children='files', + label='name', + view=no_view, + ), + ui.TreeNode( + node_for=[Hdf5FileNode], + auto_open=True, + children='groups_and_arrays', + label='name', + view=no_view, + ), + ui.TreeNode( + node_for=[Hdf5GroupNode], + auto_open=False, + children='groups_and_arrays', + label='name', + view=no_view, + ), + ui.TreeNode( + node_for=[Hdf5ArrayNode], + auto_open=False, + children='', + label='name', + view=no_view, + ), + ], + editable=False, + selected=selected, + ) class _H5Tree(api.HasTraits): @@ -179,19 +198,22 @@ class _H5Tree(api.HasTraits): node = api.Any() path = api.Str() - traits_view = ui.View(ui.Group(ui.Item('h5_tree', - editor=_hdf5_tree_editor(selected='node'), - resizable=True - ), - ui.Item('path', label='Selected node'), - orientation='vertical', - ), - title='HDF5 Tree Example', - buttons=['OK', 'Cancel'], - resizable=True, - width=.3, - height=.3 - ) + traits_view = ui.View( + ui.Group( + ui.Item( + 'h5_tree', + editor=_hdf5_tree_editor(selected='node'), + resizable=True, + ), + ui.Item('path', label='Selected node'), + orientation='vertical', + ), + title='HDF5 Tree Example', + buttons=['OK', 'Cancel'], + resizable=True, + width=0.3, + height=0.3, + ) def _node_changed(self): self.path = self.node.path @@ -203,19 +225,22 @@ class _H5Trees(api.HasTraits): node = api.Any() path = api.Str() - traits_view = ui.View(ui.Group(ui.Item('h5_trees', - editor=_hdf5_tree_editor(selected='node'), - resizable=True - ), - ui.Item('path', label='Selected node'), - orientation='vertical', - ), - title='Multiple HDF5 file Tree Example', - buttons=['OK', 'Cancel'], - resizable=True, - width=.3, - height=.3 - ) + traits_view = ui.View( + ui.Group( + ui.Item( + 'h5_trees', + editor=_hdf5_tree_editor(selected='node'), + resizable=True, + ), + ui.Item('path', label='Selected node'), + orientation='vertical', + ), + title='Multiple HDF5 file Tree Example', + buttons=['OK', 'Cancel'], + resizable=True, + width=0.3, + height=0.3, + ) def _node_changed(self): self.path = self.node.path @@ -233,50 +258,88 @@ def make_test_datasets(): import numpy as np import pandas as pd # pandas uses pytables to store datasets in hdf5 format. from random import randrange + n = 100 - df = pd.DataFrame(dict([("int{0}".format(i), np.random.randint(0, 10, size=n)) - for i in range(5)])) + df = pd.DataFrame( + dict( + [ + ("int{0}".format(i), np.random.randint(0, 10, size=n)) + for i in range(5) + ] + ) + ) df['float'] = np.random.randn(n) for i in range(10): - df["object_1_{0}".format(i)] = ['%08x' % randrange(16**8) for _ in range(n)] + df["object_1_{0}".format(i)] = [ + '%08x' % randrange(16 ** 8) for _ in range(n) + ] for i in range(7): - df["object_2_{0}".format(i)] = ['%15x' % randrange(16**15) for _ in range(n)] + df["object_2_{0}".format(i)] = [ + '%15x' % randrange(16 ** 15) for _ in range(n) + ] df.info() df.to_hdf('test_fixed.h5', 'data', format='fixed') df.to_hdf('test_table_no_dc.h5', 'data', format='table') df.to_hdf('test_table_dc.h5', 'data', format='table', data_columns=True) - df.to_hdf('test_fixed_compressed.h5', 'data', format='fixed', complib='blosc', complevel=9) + df.to_hdf( + 'test_fixed_compressed.h5', + 'data', + format='fixed', + complib='blosc', + complevel=9, + ) # h5py dataset time = np.arange(n) x = np.linspace(-7, 7, n) - axes_latlon = [('time', time), ('coordinate', np.array(['lat', 'lon'], dtype='S3'))] - axes_mag = [('time', time), ('direction', np.array(['x', 'y', 'z'], dtype='S1'))] - latlon = np.vstack((np.linspace(-0.0001, 0.00001, n) + 23.8, - np.zeros(n) - 82.3)).T - mag_data = np.vstack((-(1 - np.tanh(x)**2) * np.sin(2 * x), - -(1 - np.tanh(x)**2) * np.sin(2 * x), - -(1 - np.tanh(x)**2))).T - datasets = axes_mag + axes_latlon + [('magnetic_3_axial', mag_data), ('latlon', latlon)] + axes_latlon = [ + ('time', time), + ('coordinate', np.array(['lat', 'lon'], dtype='S3')), + ] + axes_mag = [ + ('time', time), + ('direction', np.array(['x', 'y', 'z'], dtype='S1')), + ] + latlon = np.vstack( + (np.linspace(-0.0001, 0.00001, n) + 23.8, np.zeros(n) - 82.3) + ).T + mag_data = np.vstack( + ( + -(1 - np.tanh(x) ** 2) * np.sin(2 * x), + -(1 - np.tanh(x) ** 2) * np.sin(2 * x), + -(1 - np.tanh(x) ** 2), + ) + ).T + datasets = ( + axes_mag + + axes_latlon + + [('magnetic_3_axial', mag_data), ('latlon', latlon)] + ) with h5py.File(os.path.join(ROOT, 'test_h5pydata.h5'), "a") as h5file: h5group = h5file.require_group("run1_test1") for data_name, data in datasets: - h5group.require_dataset(name=data_name, - dtype=data.dtype, - shape=data.shape, - data=data, - # **options - ) + h5group.require_dataset( + name=data_name, + dtype=data.dtype, + shape=data.shape, + data=data, + # **options + ) def main(): - filenames = ['test_fixed.h5', 'test_table_no_dc.h5', 'test_table_dc.h5', - 'test_fixed_compressed.h5', 'test_h5pydata.h5'] + filenames = [ + 'test_fixed.h5', + 'test_table_no_dc.h5', + 'test_table_dc.h5', + 'test_fixed_compressed.h5', + 'test_h5pydata.h5', + ] fullfiles = [os.path.join(ROOT, fname) for fname in filenames] h5_trees = hdf5_tree(fullfiles) return h5_trees diff --git a/traitsui/examples/demo/Advanced/History_demo.py b/traitsui/examples/demo/Advanced/History_demo.py index 6ec5883bd..21a8c04e0 100644 --- a/traitsui/examples/demo/Advanced/History_demo.py +++ b/traitsui/examples/demo/Advanced/History_demo.py @@ -28,15 +28,13 @@ value it had when the demo was run the previous time. """ -#-- Imports -------------------------------------------------------------- +# -- Imports -------------------------------------------------------------- -from traits.api \ - import HasTraits, Str, File, Directory +from traits.api import HasTraits, Str, File, Directory -from traitsui.api \ - import View, Item, FileEditor, DirectoryEditor, HistoryEditor +from traitsui.api import View, Item, FileEditor, DirectoryEditor, HistoryEditor -#-- HistoryDemo Class ---------------------------------------------------- +# -- HistoryDemo Class ---------------------------------------------------- class HistoryDemo(HasTraits): @@ -46,30 +44,24 @@ class HistoryDemo(HasTraits): directory = Directory() view = View( - Item('name', - id='name', - editor=HistoryEditor(entries=5) - ), - Item('file', - id='file1', - editor=FileEditor(entries=10) - ), - Item('file', - id='file2', - editor=FileEditor(entries=10, - filter=['All files (*.*)|*.*', - 'Python files (*.py)|*.py']) - ), - Item('directory', - id='directory', - editor=DirectoryEditor(entries=10) - ), + Item('name', id='name', editor=HistoryEditor(entries=5)), + Item('file', id='file1', editor=FileEditor(entries=10)), + Item( + 'file', + id='file2', + editor=FileEditor( + entries=10, + filter=['All files (*.*)|*.*', 'Python files (*.py)|*.py'], + ), + ), + Item('directory', id='directory', editor=DirectoryEditor(entries=10)), title='History Editor Demo', id='enthought.test.history_demo.HistoryDemo', width=0.33, - resizable=True + resizable=True, ) + # Create the demo: demo = HistoryDemo() diff --git a/traitsui/examples/demo/Advanced/Invalid_state_handling.py b/traitsui/examples/demo/Advanced/Invalid_state_handling.py index a5b519fe1..f675dd0a4 100644 --- a/traitsui/examples/demo/Advanced/Invalid_state_handling.py +++ b/traitsui/examples/demo/Advanced/Invalid_state_handling.py @@ -64,15 +64,21 @@ normal color. """ -#-- Imports -------------------------------------------------------------- +# -- Imports -------------------------------------------------------------- -from traits.api \ - import HasTraits, Range, Float, Bool, Str, Property, property_depends_on +from traits.api import ( + HasTraits, + Range, + Float, + Bool, + Str, + Property, + property_depends_on, +) -from traitsui.api \ - import View, VGroup, Item +from traitsui.api import View, VGroup, Item -#-- System Class --------------------------------------------------------- +# -- System Class --------------------------------------------------------- class System(HasTraits): @@ -88,8 +94,8 @@ class System(HasTraits): # The current error status of the system: error = Property( - Bool, - sync_to_view='mass.invalid, velocity.invalid, status.invalid') + Bool, sync_to_view='mass.invalid, velocity.invalid, status.invalid' + ) # The current status of the system: status = Property(Str) @@ -99,19 +105,14 @@ class System(HasTraits): VGroup( Item('mass'), Item('velocity'), - Item('kinetic_energy', - style='readonly', - format_str='%.0f' - ), + Item('kinetic_energy', style='readonly', format_str='%.0f'), label='System', - show_border=True), + show_border=True, + ), VGroup( - Item('status', - style='readonly', - show_label=False - ), + Item('status', style='readonly', show_label=False), label='Status', - show_border=True + show_border=True, ), ) ) @@ -122,7 +123,7 @@ def _get_kinetic_energy(self): @property_depends_on('kinetic_energy') def _get_error(self): - return (self.kinetic_energy > 50000.0) + return self.kinetic_energy > 50000.0 @property_depends_on('error') def _get_status(self): @@ -131,7 +132,8 @@ def _get_status(self): return '' -#-- Create and run the demo ---------------------------------------------- + +# -- Create and run the demo ---------------------------------------------- # Create the demo: demo = System() diff --git a/traitsui/examples/demo/Advanced/ListStrEditor_demo.py b/traitsui/examples/demo/Advanced/ListStrEditor_demo.py index 679b956a3..8bdecfcf1 100644 --- a/traitsui/examples/demo/Advanced/ListStrEditor_demo.py +++ b/traitsui/examples/demo/Advanced/ListStrEditor_demo.py @@ -19,7 +19,7 @@ from traits.api import HasTraits, List, Str from traitsui.api import View, Item, ListStrEditor -#-- ShoppingListDemo Class ----------------------------------------------- +# -- ShoppingListDemo Class ----------------------------------------------- class ShoppingListDemo(HasTraits): @@ -27,33 +27,37 @@ class ShoppingListDemo(HasTraits): # The list of things to buy at the store: shopping_list = List(Str) - #-- Traits View Definitions ---------------------------------------------- + # -- Traits View Definitions ---------------------------------------------- view = View( - Item('shopping_list', - show_label=False, - editor=ListStrEditor(title='Shopping List', auto_add=True) - ), + Item( + 'shopping_list', + show_label=False, + editor=ListStrEditor(title='Shopping List', auto_add=True), + ), title='Shopping List', width=0.2, height=0.5, - resizable=True + resizable=True, ) -#-- Set up the Demo ------------------------------------------------------ - -demo = ShoppingListDemo(shopping_list=[ - 'Carrots', - 'Potatoes (5 lb. bag)', - 'Cocoa Puffs', - 'Ice Cream (French Vanilla)', - 'Peanut Butter', - 'Whole wheat bread', - 'Ground beef (2 lbs.)', - 'Paper towels', - 'Soup (3 cans)', - 'Laundry detergent' -]) + +# -- Set up the Demo ------------------------------------------------------ + +demo = ShoppingListDemo( + shopping_list=[ + 'Carrots', + 'Potatoes (5 lb. bag)', + 'Cocoa Puffs', + 'Ice Cream (French Vanilla)', + 'Peanut Butter', + 'Whole wheat bread', + 'Ground beef (2 lbs.)', + 'Paper towels', + 'Soup (3 cans)', + 'Laundry detergent', + ] +) # Run the demo (in invoked from the command line): if __name__ == '__main__': diff --git a/traitsui/examples/demo/Advanced/List_editor_notebook_selection_demo.py b/traitsui/examples/demo/Advanced/List_editor_notebook_selection_demo.py index 877c26a06..f0c0f56e8 100644 --- a/traitsui/examples/demo/Advanced/List_editor_notebook_selection_demo.py +++ b/traitsui/examples/demo/Advanced/List_editor_notebook_selection_demo.py @@ -34,7 +34,7 @@ from traits.api import HasStrictTraits, Str, Int, Regex, List, Instance, Range from traitsui.api import View, VGroup, Item, ListEditor -#-- Person Class --------------------------------------------------------- +# -- Person Class --------------------------------------------------------- class Person(HasStrictTraits): @@ -45,11 +45,12 @@ class Person(HasStrictTraits): phone = Regex(value='000-0000', regex=r'\d\d\d[-]\d\d\d\d') # Traits view definition: - traits_view = View('name', 'age', 'phone', - width=0.18, - buttons=['OK', 'Cancel']) + traits_view = View( + 'name', 'age', 'phone', width=0.18, buttons=['OK', 'Cancel'] + ) + -#-- Sample Data ---------------------------------------------------------- +# -- Sample Data ---------------------------------------------------------- people = [ Person(name='Dave Chomsky', age=39, phone='555-1212'), @@ -59,15 +60,15 @@ class Person(HasStrictTraits): Person(name='Dick Van Der Hooten', age=63, phone='555-3895'), Person(name='Harry McCallum', age=46, phone='555-3285'), Person(name='Sally Johnson', age=43, phone='555-8797'), - Person(name='Fields Timberlawn', age=31, phone='555-3547') + Person(name='Fields Timberlawn', age=31, phone='555-3547'), ] -#-- ListEditorNotebookSelectionDemo Class -------------------------------- +# -- ListEditorNotebookSelectionDemo Class -------------------------------- class ListEditorNotebookSelectionDemo(HasStrictTraits): - #-- Trait Definitions ---------------------------------------------------- + # -- Trait Definitions ---------------------------------------------------- # List of people: people = List(Person) @@ -78,28 +79,32 @@ class ListEditorNotebookSelectionDemo(HasStrictTraits): # The index of the currently selected person: index = Range(0, 7, mode='spinner') - #-- Traits View Definitions ---------------------------------------------- + # -- Traits View Definitions ---------------------------------------------- traits_view = View( Item('index'), '_', VGroup( - Item('people', - id='notebook', - show_label=False, - style='custom', - editor=ListEditor(use_notebook=True, - deletable=False, - selected='selected', - export='DockWindowShell', - page_name='.name') - ) + Item( + 'people', + id='notebook', + show_label=False, + style='custom', + editor=ListEditor( + use_notebook=True, + deletable=False, + selected='selected', + export='DockWindowShell', + page_name='.name', + ), + ) ), id='traitsui.demo.Traits UI Demo.Advanced.' 'List_editor_notebook_selection_demo', - dock='horizontal') + dock='horizontal', + ) - #-- Trait Event Handlers ------------------------------------------------- + # -- Trait Event Handlers ------------------------------------------------- def _selected_changed(self, selected): self.index = self.people.index(selected) @@ -107,7 +112,8 @@ def _selected_changed(self, selected): def _index_changed(self, index): self.selected = self.people[index] -#-- Set Up The Demo ------------------------------------------------------ + +# -- Set Up The Demo ------------------------------------------------------ demo = ListEditorNotebookSelectionDemo(people=people) diff --git a/traitsui/examples/demo/Advanced/List_editors_demo.py b/traitsui/examples/demo/Advanced/List_editors_demo.py index 0fe542f77..dfab08b9d 100644 --- a/traitsui/examples/demo/Advanced/List_editors_demo.py +++ b/traitsui/examples/demo/Advanced/List_editors_demo.py @@ -31,11 +31,19 @@ from traits.api import HasStrictTraits, Str, Int, Regex, List, Instance from traitsui.api import ( - Item, ListEditor, ObjectColumn, RuleTableFilter, Tabbed, TableEditor, View + Item, + ListEditor, + ObjectColumn, + RuleTableFilter, + Tabbed, + TableEditor, + View, ) from traitsui.table_filter import ( - RuleFilterTemplate, MenuFilterTemplate, EvalFilterTemplate + RuleFilterTemplate, + MenuFilterTemplate, + EvalFilterTemplate, ) @@ -49,9 +57,7 @@ class Person(HasStrictTraits): # Traits view definition: traits_view = View( - 'name', 'age', 'phone', - width=0.18, - buttons=['OK', 'Cancel'] + 'name', 'age', 'phone', width=0.18, buttons=['OK', 'Cancel'] ) @@ -64,7 +70,7 @@ class Person(HasStrictTraits): Person(name='Dick', age=63, phone='555-3895'), Person(name='Harry', age=46, phone='555-3285'), Person(name='Sally', age=43, phone='555-8797'), - Person(name='Fields', age=31, phone='555-3547') + Person(name='Fields', age=31, phone='555-3547'), ] # Table editor definition: @@ -74,7 +80,7 @@ class Person(HasStrictTraits): columns=[ ObjectColumn(name='name', width=0.4), ObjectColumn(name='age', width=0.2), - ObjectColumn(name='phone', width=0.4) + ObjectColumn(name='phone', width=0.4), ], editable=True, deletable=True, @@ -84,7 +90,7 @@ class Person(HasStrictTraits): filters=filters, search=RuleTableFilter(), row_factory=Person, - show_toolbar=True + show_toolbar=True, ) @@ -103,7 +109,7 @@ class ListTraitTest(HasStrictTraits): label='List', id='list', style='custom', - editor=ListEditor(style='custom', rows=5) + editor=ListEditor(style='custom', rows=5), ), Item( 'people', @@ -114,15 +120,15 @@ class ListTraitTest(HasStrictTraits): use_notebook=True, deletable=True, export='DockShellWindow', - page_name='.name' - ) + page_name='.name', + ), ), id='splitter', - show_labels=False + show_labels=False, ), id='traitsui.demo.Traits UI Demo.Advanced.List_editors_demo', dock='horizontal', - width=600 + width=600, ) diff --git a/traitsui/examples/demo/Advanced/MVC_demo.py b/traitsui/examples/demo/Advanced/MVC_demo.py index 67ba89d64..71e96ba5a 100644 --- a/traitsui/examples/demo/Advanced/MVC_demo.py +++ b/traitsui/examples/demo/Advanced/MVC_demo.py @@ -31,16 +31,15 @@ class MyModel(HasTraits): - """ Define a simple model containing a single string, 'myname' - """ + """Define a simple model containing a single string, 'myname'""" # Simple model data: myname = Str() class MyViewController(Controller): - """ Define a combined controller/view class that validates that - MyModel.myname is consistent with the 'allow_empty_string' flag. + """Define a combined controller/view class that validates that + MyModel.myname is consistent with the 'allow_empty_string' flag. """ # When False, the model.myname trait is not allowed to be empty: @@ -53,25 +52,25 @@ class MyViewController(Controller): view = View( VGroup( HGroup( - Item('myname', springy=True), '10', - Item('controller.allow_empty_string', label='Allow Empty') + Item('myname', springy=True), + '10', + Item('controller.allow_empty_string', label='Allow Empty'), ), - # Add an empty vertical group so the above items don't end up # centered vertically: - VGroup() + VGroup(), ), - resizable=True + resizable=True, ) - #-- Handler Interface ---------------------------------------------------- + # -- Handler Interface ---------------------------------------------------- def myname_setattr(self, info, object, traitname, value): - """ Validate the request to change the named trait on object to the - specified value. Validation errors raise TraitError, which by - default causes the editor's entry field to be shown in red. - (This is a specially named method _setattr, - which is available inside a Controller.) + """Validate the request to change the named trait on object to the + specified value. Validation errors raise TraitError, which by + default causes the editor's entry field to be shown in red. + (This is a specially named method _setattr, + which is available inside a Controller.) """ self.last_name = value if (not self.allow_empty_string) and (value.strip() == ''): @@ -79,17 +78,18 @@ def myname_setattr(self, info, object, traitname, value): return super().setattr(info, object, traitname, value) - #-- Event handlers ------------------------------------------------------- + # -- Event handlers ------------------------------------------------------- def controller_allow_empty_string_changed(self, info): - """ 'allow_empty_string' has changed, check the myname trait to ensure - that it is consistent with the current setting. + """'allow_empty_string' has changed, check the myname trait to ensure + that it is consistent with the current setting. """ if (not self.allow_empty_string) and (self.model.myname == ''): self.model.myname = '?' else: self.model.myname = self.last_name + # Create the model and (demo) view/controller: demo = MyViewController(MyModel()) diff --git a/traitsui/examples/demo/Advanced/Multi_select_string_list.py b/traitsui/examples/demo/Advanced/Multi_select_string_list.py index f4fed36b2..8c063e041 100644 --- a/traitsui/examples/demo/Advanced/Multi_select_string_list.py +++ b/traitsui/examples/demo/Advanced/Multi_select_string_list.py @@ -32,8 +32,7 @@ class MultiSelectAdapter(TabularAdapter): - """ This adapter is used by both the left and right tables - """ + """This adapter is used by both the left and right tables""" # Titles and column names for each column of a table. # In this example, each table has only one column. @@ -51,8 +50,8 @@ def _get_myvalue_text(self): class MultiSelect(HasPrivateTraits): - """ This is the class used to view two tables - """ + """This is the class used to view two tables""" + # FIXME (TraitsUI defect #14): When multi-select is done by keyboard # (shift+arrow), the 'selected' trait list does not update. @@ -72,29 +71,37 @@ class MultiSelect(HasPrivateTraits): selected='selected', editable=False, multi_select=True, - adapter=MultiSelectAdapter() - ) + adapter=MultiSelectAdapter(), + ), ), UItem( 'selected', editor=TabularEditor( show_titles=True, editable=False, - adapter=MultiSelectAdapter() - ) - ) + adapter=MultiSelectAdapter(), + ), + ), ), resizable=True, width=200, - height=300 + height=300, ) # Create the demo: demo = MultiSelect( choices=[ - 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', - 'ten' + 'one', + 'two', + 'three', + 'four', + 'five', + 'six', + 'seven', + 'eight', + 'nine', + 'ten', ] ) diff --git a/traitsui/examples/demo/Advanced/Multi_thread_demo.py b/traitsui/examples/demo/Advanced/Multi_thread_demo.py index cdbd940ab..26459e6d7 100644 --- a/traitsui/examples/demo/Advanced/Multi_thread_demo.py +++ b/traitsui/examples/demo/Advanced/Multi_thread_demo.py @@ -48,17 +48,18 @@ class ThreadDemo(HasTraits): Item('thread_2', style='readonly'), ), '_', - Item('start', show_label=False, - enabled_when='running == 0'), + Item('start', show_label=False, enabled_when='running == 0'), resizable=True, width=250, - title='Monitoring threads' + title='Monitoring threads', ) def _start_changed(self): for i in range(3): - Thread(target=self.counter, - args=('thread_%d' % i, (i * 10 + 10) / 1000.0)).start() + Thread( + target=self.counter, + args=('thread_%d' % i, (i * 10 + 10) / 1000.0), + ).start() def counter(self, name, interval): self.running += 1 @@ -69,6 +70,7 @@ def counter(self, name, interval): sleep(interval) self.running -= 1 + # Create the demo: demo = ThreadDemo() diff --git a/traitsui/examples/demo/Advanced/Multi_thread_demo_2.py b/traitsui/examples/demo/Advanced/Multi_thread_demo_2.py index 7eb954385..235f9ed68 100644 --- a/traitsui/examples/demo/Advanced/Multi_thread_demo_2.py +++ b/traitsui/examples/demo/Advanced/Multi_thread_demo_2.py @@ -30,7 +30,7 @@ from traits.api import HasTraits, Int, Button, List from traitsui.api import View, Item, ListEditor -#-- The Counter objects used to keep track of the current count ---------- +# -- The Counter objects used to keep track of the current count ---------- class Counter(HasTraits): @@ -40,7 +40,8 @@ class Counter(HasTraits): view = View(Item('count', style='readonly')) -#-- The main 'ThreadDemo' class ------------------------------------------ + +# -- The main 'ThreadDemo' class ------------------------------------------ class ThreadDemo(HasTraits): @@ -54,14 +55,16 @@ class ThreadDemo(HasTraits): view = View( Item('create', show_label=False), '_', - Item('counters', style='custom', - show_label=False, - editor=ListEditor(use_notebook=True, - dock_style='tab')), + Item( + 'counters', + style='custom', + show_label=False, + editor=ListEditor(use_notebook=True, dock_style='tab'), + ), resizable=True, width=300, height=150, - title='Dynamic threads' + title='Dynamic threads', ) def __init__(self, **traits): @@ -72,8 +75,8 @@ def __init__(self, **traits): self.on_trait_change(self.count, 'create', dispatch='new') def count(self): - """ This method is dispatched on a new thread each time the - 'Create Thread' button is pressed. + """This method is dispatched on a new thread each time the + 'Create Thread' button is pressed. """ counter = Counter() self.counters.append(counter) @@ -82,6 +85,7 @@ def count(self): sleep(0.030) self.counters.remove(counter) + # Create the demo: demo = ThreadDemo() diff --git a/traitsui/examples/demo/Advanced/NumPy_array_tabular_editor_demo.py b/traitsui/examples/demo/Advanced/NumPy_array_tabular_editor_demo.py index 5eccbcae9..2a87f6bba 100644 --- a/traitsui/examples/demo/Advanced/NumPy_array_tabular_editor_demo.py +++ b/traitsui/examples/demo/Advanced/NumPy_array_tabular_editor_demo.py @@ -48,6 +48,7 @@ def _get_index_image(self): return None + # -- ShowArray Class Definition ------------------------------------------- @@ -65,13 +66,13 @@ class ShowArray(HasTraits): # Do not allow any kind of editing of the array: editable=False, operations=[], - drag_move=False - ) + drag_move=False, + ), ), title='Array Viewer', width=0.3, height=0.8, - resizable=True + resizable=True, ) diff --git a/traitsui/examples/demo/Advanced/NumPy_array_view_editor_demo.py b/traitsui/examples/demo/Advanced/NumPy_array_view_editor_demo.py index a4179fd26..56ee12efa 100644 --- a/traitsui/examples/demo/Advanced/NumPy_array_view_editor_demo.py +++ b/traitsui/examples/demo/Advanced/NumPy_array_view_editor_demo.py @@ -54,7 +54,7 @@ from traitsui.api import View, Item from traitsui.ui_editors.array_view_editor import ArrayViewEditor -#-- ShowArray demo class ------------------------------------------------- +# -- ShowArray demo class ------------------------------------------------- class ShowArray(HasTraits): @@ -62,22 +62,25 @@ class ShowArray(HasTraits): data = Array view = View( - Item('data', - show_label=False, - editor=ArrayViewEditor(titles=['x', 'y', 'z'], - format='%.4f', - # Font fails with wx in OSX; - # see traitsui issue #13: - # font = 'Arial 8' - ) - ), + Item( + 'data', + show_label=False, + editor=ArrayViewEditor( + titles=['x', 'y', 'z'], + format='%.4f', + # Font fails with wx in OSX; + # see traitsui issue #13: + # font = 'Arial 8' + ), + ), title='Array Viewer', width=0.3, height=0.8, - resizable=True + resizable=True, ) -#-- Run the demo --------------------------------------------------------- + +# -- Run the demo --------------------------------------------------------- # Create the demo: demo = ShowArray(data=random((100000, 3))) diff --git a/traitsui/examples/demo/Advanced/Popup_Dialog_demo.py b/traitsui/examples/demo/Advanced/Popup_Dialog_demo.py index eacd45bf2..808f37278 100644 --- a/traitsui/examples/demo/Advanced/Popup_Dialog_demo.py +++ b/traitsui/examples/demo/Advanced/Popup_Dialog_demo.py @@ -37,15 +37,13 @@ conflict). """ -#-- Imports -------------------------------------------------------------- +# -- Imports -------------------------------------------------------------- -from traits.api \ - import HasPrivateTraits, Str, Int, Enum, Instance, Button +from traits.api import HasPrivateTraits, Str, Int, Enum, Instance, Button -from traitsui.api \ - import View, HGroup, Item, Handler, UIInfo, spring +from traitsui.api import View, HGroup, Item, Handler, UIInfo, spring -#-- The PersonHandler class ---------------------------------------------- +# -- The PersonHandler class ---------------------------------------------- class PersonHandler(Handler): @@ -62,7 +60,7 @@ class PersonHandler(Handler): spring, Item('cancel', show_label=False), ), - kind='popup' + kind='popup', ) # Event handlers: @@ -76,7 +74,8 @@ def _cancel_changed(self): object.gender = ['Male', 'Female'][object.gender == 'Male'] self._ui.dispose() -#-- The Person class ----------------------------------------------------- + +# -- The Person class ----------------------------------------------------- class Person(HasPrivateTraits): @@ -92,10 +91,11 @@ class Person(HasPrivateTraits): Item('age'), Item('gender'), title='Button Popup Demo', - handler=PersonHandler + handler=PersonHandler, ) -#-- Create and run the demo ---------------------------------------------- + +# -- Create and run the demo ---------------------------------------------- # Create the demo: demo = Person(name='Mike Thomas', age=32) diff --git a/traitsui/examples/demo/Advanced/Property_List_demo.py b/traitsui/examples/demo/Advanced/Property_List_demo.py index e7e4cb881..fc034fa84 100644 --- a/traitsui/examples/demo/Advanced/Property_List_demo.py +++ b/traitsui/examples/demo/Advanced/Property_List_demo.py @@ -42,8 +42,15 @@ from time import sleep from traits.api import ( - HasStrictTraits, HasPrivateTraits, Str, Int, Enum, List, Event, Property, - cached_property + HasStrictTraits, + HasPrivateTraits, + Str, + Int, + Enum, + List, + Event, + Property, + cached_property, ) from traitsui.api import ObjectColumn, Item, TableEditor, View @@ -51,8 +58,7 @@ # -- Person Class --------------------------------------------------------- class Person(HasStrictTraits): - """ Defines some sample data to display in the TableEditor. - """ + """Defines some sample data to display in the TableEditor.""" name = Str() age = Int() @@ -61,9 +67,9 @@ class Person(HasStrictTraits): # -- PropertyListDemo Class ----------------------------------------------- class PropertyListDemo(HasPrivateTraits): - """ Displays a random list of Person objects in a TableEditor that is - refreshed every 3 seconds by a background thread. - """ + """Displays a random list of Person objects in a TableEditor that is + refreshed every 3 seconds by a background thread. + """ # An event used to trigger a Property value update: ticker = Event() @@ -84,40 +90,39 @@ class PropertyListDemo(HasPrivateTraits): columns=[ ObjectColumn(name='name', editable=False, width=0.50), ObjectColumn(name='age', editable=False, width=0.15), - ObjectColumn(name='gender', editable=False, width=0.35) + ObjectColumn(name='gender', editable=False, width=0.35), ], auto_size=False, show_toolbar=False, sortable=False, - ) - ), + ), + ), title='Property List Demo', width=0.25, height=0.33, - resizable=True + resizable=True, ) # -- Property Implementations --------------------------------------------- @cached_property def _get_people(self): - """ Returns the value for the 'people' property. - """ + """Returns the value for the 'people' property.""" return [ Person( - name='%s %s' % ( + name='%s %s' + % ( choice(['Tom', 'Dick', 'Harry', 'Alice', 'Lia', 'Vibha']), - choice(['Thomas', 'Jones', 'Smith', 'Adams', 'Johnson']) + choice(['Thomas', 'Jones', 'Smith', 'Adams', 'Johnson']), ), age=randint(21, 75), - gender=choice(['Male', 'Female']) + gender=choice(['Male', 'Female']), ) for i in range(randint(10, 20)) ] # -- Default Value Implementations ---------------------------------------- def _begin_default(self): - """ Starts the background thread running. - """ + """Starts the background thread running.""" thread = Thread(target=self._timer) thread.daemon = True thread.start() @@ -127,8 +132,7 @@ def _begin_default(self): # -- Private Methods ------------------------------------------------------ def _timer(self): - """ Triggers a property update every 3 seconds for 30 seconds. - """ + """Triggers a property update every 3 seconds for 30 seconds.""" for i in range(10): sleep(3) self.ticker = True diff --git a/traitsui/examples/demo/Advanced/Scrubber_editor_demo.py b/traitsui/examples/demo/Advanced/Scrubber_editor_demo.py index 2eceb40a6..80bc185b3 100644 --- a/traitsui/examples/demo/Advanced/Scrubber_editor_demo.py +++ b/traitsui/examples/demo/Advanced/Scrubber_editor_demo.py @@ -100,22 +100,21 @@ their default editors. """ -#-- Imports -------------------------------------------------------------- +# -- Imports -------------------------------------------------------------- -from traits.api \ - import HasTraits, Range, Float +from traits.api import HasTraits, Range, Float -from traitsui.api \ - import View, VGroup, HGroup, Item, ScrubberEditor, spring +from traitsui.api import View, VGroup, HGroup, Item, ScrubberEditor, spring -#-- Shared Item Definition ---------------------------------------- +# -- Shared Item Definition ---------------------------------------- class TItem(Item): editor = ScrubberEditor() -#-- ScrubberDemo Class --------------------------------------------------- + +# -- ScrubberDemo Class --------------------------------------------------- class ScrubberDemo(HasTraits): @@ -132,20 +131,26 @@ class ScrubberDemo(HasTraits): view = View( HGroup( VGroup( - Item('simple_integer', - editor=ScrubberEditor()), - Item('rollover_float', - editor=ScrubberEditor(hover_color=0xFFFFFF, - active_color=0xA0CD9E)), - Item('bordered_unbounded', - editor=ScrubberEditor(hover_color=0xFFFFFF, - active_color=0xA0CD9E, - border_color=0x808080)), + Item('simple_integer', editor=ScrubberEditor()), + Item( + 'rollover_float', + editor=ScrubberEditor( + hover_color=0xFFFFFF, active_color=0xA0CD9E + ), + ), + Item( + 'bordered_unbounded', + editor=ScrubberEditor( + hover_color=0xFFFFFF, + active_color=0xA0CD9E, + border_color=0x808080, + ), + ), Item('dynamic_low', editor=ScrubberEditor()), Item('dynamic_high', editor=ScrubberEditor()), Item('dynamic_value', editor=ScrubberEditor()), show_border=True, - label='Scrubber Editors' + label='Scrubber Editors', ), VGroup( Item('simple_integer'), @@ -155,14 +160,15 @@ class ScrubberDemo(HasTraits): Item('dynamic_high'), Item('dynamic_value'), show_border=True, - label='Default Editors' + label='Default Editors', ), - spring + spring, ), - title='Scrubber Editor Demo' + title='Scrubber Editor Demo', ) -#-- Create and run the demo ---------------------------------------------- + +# -- Create and run the demo ---------------------------------------------- # Create the demo: demo = ScrubberDemo() diff --git a/traitsui/examples/demo/Advanced/Settable_cached_property.py b/traitsui/examples/demo/Advanced/Settable_cached_property.py index 6f0a48940..0b843bd35 100644 --- a/traitsui/examples/demo/Advanced/Settable_cached_property.py +++ b/traitsui/examples/demo/Advanced/Settable_cached_property.py @@ -75,7 +75,7 @@ from traits.api import HasTraits, Int, Range, Property, cached_property from traitsui.api import View, Item, RangeEditor -#-- Demo Class ----------------------------------------------------------- +# -- Demo Class ----------------------------------------------------------- class SettableCachedProperty(HasTraits): @@ -89,19 +89,17 @@ class SettableCachedProperty(HasTraits): Item('a'), Item('b'), '_', - Item('c', - editor=RangeEditor(low=1, high=100, mode='slider')), + Item('c', editor=RangeEditor(low=1, high=100, mode='slider')), Item('c'), '_', - Item('d', - editor=RangeEditor(low=1, high=400, mode='slider')), + Item('d', editor=RangeEditor(low=1, high=400, mode='slider')), Item('d'), - width=0.3 + width=0.3, ) @cached_property def _get_c(self): - return (self.a * self.b) + return self.a * self.b def _set_c(self, value): self.a = int(sqrt(value)) @@ -109,9 +107,10 @@ def _set_c(self, value): @cached_property def _get_d(self): - return (self.c + self.c) + return self.c + self.c -#-- Run the demo --------------------------------------------------------- + +# -- Run the demo --------------------------------------------------------- # Create the demo: demo = SettableCachedProperty() diff --git a/traitsui/examples/demo/Advanced/Statusbar_demo.py b/traitsui/examples/demo/Advanced/Statusbar_demo.py index f9efa8518..6e9b10af7 100644 --- a/traitsui/examples/demo/Advanced/Statusbar_demo.py +++ b/traitsui/examples/demo/Advanced/Statusbar_demo.py @@ -33,7 +33,7 @@ from traits.api import HasPrivateTraits, Str, Property from traitsui.api import View, Item, StatusItem, Label -#-- The demo class ------------------------------------------------------- +# -- The demo class ------------------------------------------------------- class TextEditor(HasPrivateTraits): @@ -56,16 +56,18 @@ class TextEditor(HasPrivateTraits): width=0.4, height=0.4, resizable=True, - statusbar=[StatusItem(name='length', width=0.5), - StatusItem(name='time', width=85)] + statusbar=[ + StatusItem(name='length', width=0.5), + StatusItem(name='time', width=85), + ], ) - #-- Property Implementations --------------------------------------------- + # -- Property Implementations --------------------------------------------- def _get_length(self): - return ('Length: %d characters' % len(self.text)) + return 'Length: %d characters' % len(self.text) - #-- Default Trait Values ------------------------------------------------- + # -- Default Trait Values ------------------------------------------------- def _time_default(self): thread = Thread(target=self._clock) @@ -74,15 +76,15 @@ def _time_default(self): return '' - #-- Private Methods ------------------------------------------------------ + # -- Private Methods ------------------------------------------------------ def _clock(self): - """ Update the statusbar time once every second. - """ + """Update the statusbar time once every second.""" while True: self.time = strftime('%I:%M:%S %p') sleep(1.0) + # Create the demo object: popup = TextEditor() diff --git a/traitsui/examples/demo/Advanced/String_list_ui_editor.py b/traitsui/examples/demo/Advanced/String_list_ui_editor.py index 44d4e96a1..cd37ef663 100644 --- a/traitsui/examples/demo/Advanced/String_list_ui_editor.py +++ b/traitsui/examples/demo/Advanced/String_list_ui_editor.py @@ -30,7 +30,12 @@ from traits.etsconfig.api import ETSConfig from traitsui.api import ( - BasicEditorFactory, HGroup, Item, TabularAdapter, TabularEditor, View + BasicEditorFactory, + HGroup, + Item, + TabularAdapter, + TabularEditor, + View, ) if ETSConfig.toolkit == 'wx': @@ -76,11 +81,11 @@ class _StringListEditor(UIEditor): selected='selected', editable=False, multi_select=True, - adapter=MultiSelectAdapter() - ) + adapter=MultiSelectAdapter(), + ), ), id='string_list_editor', - resizable=True + resizable=True, ) def init_ui(self, parent): @@ -107,8 +112,8 @@ class StringListEditor(BasicEditorFactory): # -- Define the demo class ---------------------------------------------------- class MultiSelect(HasPrivateTraits): - """ This class demonstrates using the StringListEditor to select a set - of string values from a set of choices. + """This class demonstrates using the StringListEditor to select a set + of string values from a set of choices. """ # The list of choices to select from: @@ -128,26 +133,34 @@ class MultiSelect(HasPrivateTraits): Item( 'selected', show_label=False, - editor=StringListEditor(choices='choices') + editor=StringListEditor(choices='choices'), ), Item( 'result', show_label=False, - editor=StringListEditor(choices='selected') - ) + editor=StringListEditor(choices='selected'), + ), ), width=0.20, - height=0.25 + height=0.25, ) # Create the demo: demo = MultiSelect( choices=[ - 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', - 'ten' + 'one', + 'two', + 'three', + 'four', + 'five', + 'six', + 'seven', + 'eight', + 'nine', + 'ten', ], - selected=['two', 'five', 'nine'] + selected=['two', 'five', 'nine'], ) # Run the demo (if invoked from the command line): diff --git a/traitsui/examples/demo/Advanced/Table_editor_with_checkbox_column.py b/traitsui/examples/demo/Advanced/Table_editor_with_checkbox_column.py index 16494fac7..d46bbd6dc 100644 --- a/traitsui/examples/demo/Advanced/Table_editor_with_checkbox_column.py +++ b/traitsui/examples/demo/Advanced/Table_editor_with_checkbox_column.py @@ -48,7 +48,7 @@ def get_text_color(self, object): name='name', editable=False, width=0.24, - horizontal_alignment='left' + horizontal_alignment='left', ), PlayerColumn(name='at_bats', label='AB'), PlayerColumn(name='strike_outs', label='SO'), @@ -58,12 +58,9 @@ def get_text_color(self, object): PlayerColumn(name='home_runs', label='HR'), PlayerColumn(name='walks', label='W'), PlayerColumn( - name='average', - label='Ave', - editable=False, - format='%0.3f' - ) - ] + name='average', label='Ave', editable=False, format='%0.3f' + ), + ], ) @@ -82,13 +79,14 @@ class Player(HasStrictTraits): average = Property(Float) def _get_average(self): - """ Computes the player's batting average from the current statistics. - """ + """Computes the player's batting average from the current statistics.""" if self.at_bats == 0: return 0.0 - return float(self.singles + self.doubles + - self.triples + self.home_runs) / self.at_bats + return ( + float(self.singles + self.doubles + self.triples + self.home_runs) + / self.at_bats + ) class Team(HasStrictTraits): @@ -104,13 +102,12 @@ class Team(HasStrictTraits): title='Baseball Team Roster Demo', width=0.5, height=0.5, - resizable=True + resizable=True, ) def random_player(name): - """ Generates and returns a random player. - """ + """Generates and returns a random player.""" p = Player( name=name, strike_outs=randint(0, 50), @@ -118,12 +115,16 @@ def random_player(name): doubles=randint(0, 20), triples=randint(0, 5), home_runs=randint(0, 30), - walks=randint(0, 50) + walks=randint(0, 50), ) return p.trait_set( at_bats=( - p.strike_outs + p.singles + p.doubles + p.triples + p.home_runs + - randint(100, 200) + p.strike_outs + + p.singles + + p.doubles + + p.triples + + p.home_runs + + randint(100, 200) ) ) @@ -131,9 +132,17 @@ def random_player(name): # Create the demo: demo = Team( players=[ - random_player(name) for name in [ - 'Dave', 'Mike', 'Joe', 'Tom', 'Dick', 'Harry', 'Dirk', 'Fields', - 'Stretch' + random_player(name) + for name in [ + 'Dave', + 'Mike', + 'Joe', + 'Tom', + 'Dick', + 'Harry', + 'Dirk', + 'Fields', + 'Stretch', ] ] ) diff --git a/traitsui/examples/demo/Advanced/Table_editor_with_context_menu_demo.py b/traitsui/examples/demo/Advanced/Table_editor_with_context_menu_demo.py index c63f4954c..bcdf058c7 100644 --- a/traitsui/examples/demo/Advanced/Table_editor_with_context_menu_demo.py +++ b/traitsui/examples/demo/Advanced/Table_editor_with_context_menu_demo.py @@ -36,8 +36,10 @@ class AffectsAverageColumn(ObjectColumn): # Define the context menu for the column: - menu = Menu(Action(name='Add', action='column.add(object)'), - Action(name='Sub', action='column.sub(object)')) + menu = Menu( + Action(name='Add', action='column.add(object)'), + Action(name='Sub', action='column.sub(object)'), + ) # Right-align numeric values (override): horizontal_alignment = 'center' @@ -51,13 +53,11 @@ class AffectsAverageColumn(ObjectColumn): # Action methods for the context menu items: def add(self, object): - """ Increment the affected player statistic. - """ + """Increment the affected player statistic.""" setattr(object, self.name, getattr(object, self.name) + 1) def sub(self, object): - """ Decrement the affected player statistic. - """ + """Decrement the affected player statistic.""" setattr(object, self.name, getattr(object, self.name) - 1) @@ -81,9 +81,9 @@ def sub(self, object): editable=False, width=0.09, horizontal_alignment='center', - format='%0.3f' - ) - ] + format='%0.3f', + ), + ], ) @@ -102,17 +102,17 @@ class Player(HasStrictTraits): average = Property(Float) def _get_average(self): - """ Computes the player's batting average from the current statistics. - """ + """Computes the player's batting average from the current statistics.""" if self.at_bats == 0: return 0.0 - return float(self.singles + self.doubles + - self.triples + self.home_runs) / self.at_bats + return ( + float(self.singles + self.doubles + self.triples + self.home_runs) + / self.at_bats + ) def _affects_average_changed(self): - """ Handles an event that affects the player's batting average. - """ + """Handles an event that affects the player's batting average.""" self.at_bats += 1 @@ -127,13 +127,12 @@ class Team(HasStrictTraits): title='Baseball Scoring Demo', width=0.5, height=0.5, - resizable=True + resizable=True, ) def random_player(name): - """ Generates and returns a random player. - """ + """Generates and returns a random player.""" p = Player( name=name, strike_outs=randint(0, 50), @@ -141,12 +140,16 @@ def random_player(name): doubles=randint(0, 20), triples=randint(0, 5), home_runs=randint(0, 30), - walks=randint(0, 50) + walks=randint(0, 50), ) return p.trait_set( at_bats=( - p.strike_outs + p.singles + p.doubles + p.triples + p.home_runs + - randint(100, 200) + p.strike_outs + + p.singles + + p.doubles + + p.triples + + p.home_runs + + randint(100, 200) ) ) @@ -154,9 +157,17 @@ def random_player(name): # Create the demo: demo = Team( players=[ - random_player(name) for name in [ - 'Dave', 'Mike', 'Joe', 'Tom', 'Dick', 'Harry', 'Dirk', 'Fields', - 'Stretch' + random_player(name) + for name in [ + 'Dave', + 'Mike', + 'Joe', + 'Tom', + 'Dick', + 'Harry', + 'Dirk', + 'Fields', + 'Stretch', ] ] ) diff --git a/traitsui/examples/demo/Advanced/Table_editor_with_live_search_and_cell_editor.py b/traitsui/examples/demo/Advanced/Table_editor_with_live_search_and_cell_editor.py index 0ed15088a..a9440eab1 100644 --- a/traitsui/examples/demo/Advanced/Table_editor_with_live_search_and_cell_editor.py +++ b/traitsui/examples/demo/Advanced/Table_editor_with_live_search_and_cell_editor.py @@ -80,43 +80,58 @@ table. """ -#-- Imports -------------------------------------------------------------- - -from os \ - import walk, listdir - -from os.path \ - import basename, dirname, splitext, join - -from traits.api \ - import HasTraits, File, Directory, Str, Bool, Int, Enum, Instance, \ - Property, Any, property_depends_on - -from traitsui.api \ - import View, VGroup, VSplit, HGroup, Item, TableEditor, CodeEditor, \ - TitleEditor, HistoryEditor, DNDEditor - -from traitsui.table_column \ - import ObjectColumn +# -- Imports -------------------------------------------------------------- + +from os import walk, listdir + +from os.path import basename, dirname, splitext, join + +from traits.api import ( + HasTraits, + File, + Directory, + Str, + Bool, + Int, + Enum, + Instance, + Property, + Any, + property_depends_on, +) + +from traitsui.api import ( + View, + VGroup, + VSplit, + HGroup, + Item, + TableEditor, + CodeEditor, + TitleEditor, + HistoryEditor, + DNDEditor, +) + +from traitsui.table_column import ObjectColumn from io import open -#-- Constants ------------------------------------------------------------ +# -- Constants ------------------------------------------------------------ FileTypes = { 'Python': ['.py'], 'C': ['.c', '.h'], 'C++': ['.cpp', '.h'], 'Java': ['.java'], - 'Ruby': ['.rb'] + 'Ruby': ['.rb'], } DEFAULT_ROOT = dirname(__file__) -#-- The Live Search table editor definition ------------------------------ +# -- The Live Search table editor definition ------------------------------ class MatchesColumn1(ObjectColumn): - def get_value(self, object): n = len(self.get_raw_value(object)) if n == 0: @@ -126,16 +141,15 @@ def get_value(self, object): class MatchesColumn2(ObjectColumn): - def is_editable(self, object): - return (len(object.matches) > 0) + return len(object.matches) > 0 class FileColumn(ObjectColumn): - def get_drag_value(self, object): return object.full_name + table_editor = TableEditor( columns=[ MatchesColumn1( @@ -143,37 +157,34 @@ def get_drag_value(self, object): label='#', editable=False, width=0.05, - horizontal_alignment='center'), + horizontal_alignment='center', + ), MatchesColumn2( name='matches', width=0.35, - format_func=lambda x: ( - x + [''])[0].strip(), + format_func=lambda x: (x + [''])[0].strip(), editor=CodeEditor( line='object.live_search.selected_match', - selected_line='object.live_search.selected_match'), + selected_line='object.live_search.selected_match', + ), style='readonly', edit_width=0.95, - edit_height=0.33), - FileColumn( - name='base_name', - label='Name', - width=0.30, - editable=False), + edit_height=0.33, + ), + FileColumn(name='base_name', label='Name', width=0.30, editable=False), ObjectColumn( - name='ext_path', - label='Path', - width=0.30, - editable=False), + name='ext_path', label='Path', width=0.30, editable=False + ), ], filter_name='filter', auto_size=False, show_toolbar=False, selected='selected', selection_color=0x000000, - selection_bg_color=0xFBD391) + selection_bg_color=0xFBD391, +) -#-- LiveSearch class ----------------------------------------------------- +# -- LiveSearch class ----------------------------------------------------- class LiveSearch(HasTraits): @@ -220,70 +231,69 @@ class LiveSearch(HasTraits): # Summary of current number of files and matches: summary = Property # Str - #-- Traits UI Views ------------------------------------------------------ + # -- Traits UI Views ------------------------------------------------------ view = View( VGroup( HGroup( - Item('root', - id='root', - label='Path', - width=0.5 - ), + Item('root', id='root', label='Path', width=0.5), Item('recursive'), Item('file_type', label='Type'), - Item('search', - id='search', - width=0.5, - editor=HistoryEditor(auto_set=True) - ), - Item('case_sensitive') + Item( + 'search', + id='search', + width=0.5, + editor=HistoryEditor(auto_set=True), + ), + Item('case_sensitive'), ), VSplit( VGroup( - Item('summary', - editor=TitleEditor() - ), - Item('source_files', - id='source_files', - editor=table_editor - ), + Item('summary', editor=TitleEditor()), + Item( + 'source_files', id='source_files', editor=table_editor + ), dock='horizontal', - show_labels=False + show_labels=False, ), VGroup( HGroup( - Item('selected_full_name', - editor=TitleEditor(), - springy=True - ), - Item('selected_full_name', - editor=DNDEditor(), - tooltip='Drag this file' - ), - show_labels=False + Item( + 'selected_full_name', + editor=TitleEditor(), + springy=True, + ), + Item( + 'selected_full_name', + editor=DNDEditor(), + tooltip='Drag this file', + ), + show_labels=False, + ), + Item( + 'selected_contents', + style='readonly', + editor=CodeEditor( + mark_lines='mark_lines', + line='selected_line', + selected_line='selected_line', + ), ), - Item('selected_contents', - style='readonly', - editor=CodeEditor(mark_lines='mark_lines', - line='selected_line', - selected_line='selected_line') - ), dock='horizontal', - show_labels=False + show_labels=False, ), - id='splitter' - ) + id='splitter', + ), ), title='Live File Search', id='enthought.examples.demo.Advanced.' 'Table_editor_with_live_search_and_cell_editor.LiveSearch', width=0.75, height=0.67, - resizable=True + resizable=True, ) - #-- Property Implementations --------------------------------------------- + # -- Property Implementations --------------------------------------------- @property_depends_on('search, case_sensitive') def _get_filter(self): @@ -304,15 +314,19 @@ def _get_source_files(self): for dir_path, dir_names, file_names in walk(root): for file_name in file_names: if splitext(file_name)[1] in file_types: - result.append(SourceFile( - live_search=self, - full_name=join(dir_path, file_name))) + result.append( + SourceFile( + live_search=self, + full_name=join(dir_path, file_name), + ) + ) return result - return [SourceFile(live_search=self, - full_name=join(root, file_name)) - for file_name in listdir(root) - if splitext(file_name)[1] in file_types] + return [ + SourceFile(live_search=self, full_name=join(root, file_name)) + for file_name in listdir(root) + if splitext(file_name)[1] in file_types + ] @property_depends_on('selected') def _get_selected_contents(self): @@ -326,8 +340,7 @@ def _get_mark_lines(self): if self.selected is None: return [] - return [int(match.split(':', 1)[0]) - for match in self.selected.matches] + return [int(match.split(':', 1)[0]) for match in self.selected.matches] @property_depends_on('selected, selected_match') def _get_selected_line(self): @@ -335,8 +348,7 @@ def _get_selected_line(self): if (selected is None) or (len(selected.matches) == 0): return 1 - return int(selected.matches[self.selected_match - 1 - ].split(':', 1)[0]) + return int(selected.matches[self.selected_match - 1].split(':', 1)[0]) @property_depends_on('selected') def _get_selected_full_name(self): @@ -361,9 +373,12 @@ def _get_summary(self): matches += n return 'A total of %d files with %d files containing %d matches.' % ( - len(source_files), files, matches) + len(source_files), + files, + matches, + ) - #-- Traits Event Handlers ------------------------------------------------ + # -- Traits Event Handlers ------------------------------------------------ def _selected_changed(self): self.selected_match = 1 @@ -374,7 +389,8 @@ def _source_files_changed(self): else: self.selected = None -#-- SourceFile class ----------------------------------------------------- + +# -- SourceFile class ----------------------------------------------------- class SourceFile(HasTraits): @@ -397,7 +413,7 @@ class SourceFile(HasTraits): # The list of matches for the current search criteria: matches = Property # List( Str ) - #-- Property Implementations --------------------------------------------- + # -- Property Implementations --------------------------------------------- @property_depends_on('full_name') def _get_base_name(self): @@ -405,7 +421,7 @@ def _get_base_name(self): @property_depends_on('full_name') def _get_ext_path(self): - return dirname(self.full_name)[len(self.live_search.root):] + return dirname(self.full_name)[len(self.live_search.root) :] @property_depends_on('full_name') def _get_contents(self): @@ -424,16 +440,21 @@ def _get_matches(self): case_sensitive = self.live_search.case_sensitive if case_sensitive: - return ['%5d: %s' % ((i + 1), line.strip()) - for i, line in enumerate(self.contents) - if line.find(search) >= 0] + return [ + '%5d: %s' % ((i + 1), line.strip()) + for i, line in enumerate(self.contents) + if line.find(search) >= 0 + ] search = search.lower() - return ['%5d: %s' % ((i + 1), line.strip()) - for i, line in enumerate(self.contents) - if line.lower().find(search) >= 0] + return [ + '%5d: %s' % ((i + 1), line.strip()) + for i, line in enumerate(self.contents) + if line.lower().find(search) >= 0 + ] + -#-- Set up and run the demo ---------------------------------------------- +# -- Set up and run the demo ---------------------------------------------- # Create the demo object: demo = LiveSearch() diff --git a/traitsui/examples/demo/Advanced/Table_editor_with_progress_column.py b/traitsui/examples/demo/Advanced/Table_editor_with_progress_column.py index 88fcc05c8..5b6f2bc38 100644 --- a/traitsui/examples/demo/Advanced/Table_editor_with_progress_column.py +++ b/traitsui/examples/demo/Advanced/Table_editor_with_progress_column.py @@ -36,14 +36,14 @@ class JobManager(HasTraits): def populate(self): self.jobs = [ - Job(name='job %02d' % i, percent_complete=0) - for i in range(1, 25) + Job(name='job %02d' % i, percent_complete=0) for i in range(1, 25) ] def process(self): for job in self.jobs: job.percent_complete = min( - job.percent_complete + random.randint(0, 3), 100) + job.percent_complete + random.randint(0, 3), 100 + ) if any(job.percent_complete < 100 for job in self.jobs): GUI.invoke_after(100, self.process) @@ -61,7 +61,7 @@ def _populate_and_process(self, event): ObjectColumn(name='name'), ProgressColumn(name='percent_complete'), ] - ) + ), ), UItem('start'), resizable=True, diff --git a/traitsui/examples/demo/Advanced/Tabular_editor_demo.py b/traitsui/examples/demo/Advanced/Tabular_editor_demo.py index c453c73b4..af2eda2ab 100644 --- a/traitsui/examples/demo/Advanced/Tabular_editor_demo.py +++ b/traitsui/examples/demo/Advanced/Tabular_editor_demo.py @@ -122,7 +122,12 @@ from traits.api import HasTraits, Str, Int, List, Instance, Property, Constant from traits.etsconfig.api import ETSConfig from traitsui.api import ( - View, Group, Item, TabularAdapter, TabularEditor, Color + View, + Group, + Item, + TabularAdapter, + TabularEditor, + Color, ) @@ -134,8 +139,7 @@ class Person(HasTraits): age = Int() # surname is displayed in qt-only row label: - surname = Property(fget=lambda self: self.name.split()[-1], - observe='name') + surname = Property(fget=lambda self: self.name.split()[-1], observe='name') # -- MarriedPerson Class Definition --------------------------------------- @@ -146,14 +150,17 @@ class MarriedPerson(Person): # -- Tabular Adapter Definition ------------------------------------------- class ReportAdapter(TabularAdapter): - """ The tabular adapter interfaces between the tabular editor and the data + """The tabular adapter interfaces between the tabular editor and the data being displayed. For more details, please refer to the traitsUI user guide. """ + # List of (Column labels, Column ID). - columns = [('Name', 'name'), - ('Age', 'age'), - ('Address', 'address'), - ('Spouse', 'spouse')] + columns = [ + ('Name', 'name'), + ('Age', 'age'), + ('Address', 'address'), + ('Spouse', 'spouse'), + ] row_label_name = 'surname' @@ -200,31 +207,93 @@ class Report(HasTraits): traits_view = View( Group( Item('people', id='table', editor=tabular_editor), - show_labels=False + show_labels=False, ), title='Tabular Editor Demo', id='traitsui.demo.Applications.tabular_editor_demo', width=0.60, height=0.75, - resizable=True + resizable=True, ) # -- Generate 10,000 random single and married people --------------------- male_names = [ - 'Michael', 'Edward', 'Timothy', 'James', 'George', 'Ralph', 'David', - 'Martin', 'Bryce', 'Richard', 'Eric', 'Travis', 'Robert', 'Bryan', 'Alan', - 'Harold', 'John', 'Stephen', 'Gael', 'Frederic', 'Eli', 'Scott', 'Samuel', - 'Alexander', 'Tobias', 'Sven', 'Peter', 'Albert', 'Thomas', 'Horatio', - 'Julius', 'Henry', 'Walter', 'Woodrow', 'Dylan', 'Elmer' + 'Michael', + 'Edward', + 'Timothy', + 'James', + 'George', + 'Ralph', + 'David', + 'Martin', + 'Bryce', + 'Richard', + 'Eric', + 'Travis', + 'Robert', + 'Bryan', + 'Alan', + 'Harold', + 'John', + 'Stephen', + 'Gael', + 'Frederic', + 'Eli', + 'Scott', + 'Samuel', + 'Alexander', + 'Tobias', + 'Sven', + 'Peter', + 'Albert', + 'Thomas', + 'Horatio', + 'Julius', + 'Henry', + 'Walter', + 'Woodrow', + 'Dylan', + 'Elmer', ] female_names = [ - 'Leah', 'Jaya', 'Katrina', 'Vibha', 'Diane', 'Lisa', 'Jean', 'Alice', - 'Rebecca', 'Delia', 'Christine', 'Marie', 'Dorothy', 'Ellen', 'Victoria', - 'Elizabeth', 'Margaret', 'Joyce', 'Sally', 'Ethel', 'Esther', 'Suzanne', - 'Monica', 'Hortense', 'Samantha', 'Tabitha', 'Judith', 'Ariel', 'Helen', - 'Mary', 'Jane', 'Janet', 'Jennifer', 'Rita', 'Rena', 'Rianna' + 'Leah', + 'Jaya', + 'Katrina', + 'Vibha', + 'Diane', + 'Lisa', + 'Jean', + 'Alice', + 'Rebecca', + 'Delia', + 'Christine', + 'Marie', + 'Dorothy', + 'Ellen', + 'Victoria', + 'Elizabeth', + 'Margaret', + 'Joyce', + 'Sally', + 'Ethel', + 'Esther', + 'Suzanne', + 'Monica', + 'Hortense', + 'Samantha', + 'Tabitha', + 'Judith', + 'Ariel', + 'Helen', + 'Mary', + 'Jane', + 'Janet', + 'Jennifer', + 'Rita', + 'Rena', + 'Rianna', ] all_names = male_names + female_names @@ -236,35 +305,129 @@ class Report(HasTraits): def family_name(): - return choice([ - 'Jones', 'Smith', 'Thompson', 'Hayes', 'Thomas', 'Boyle', "O'Reilly", - 'Lebowski', 'Lennon', 'Starr', 'McCartney', 'Harrison', 'Harrelson', - 'Steinbeck', 'Rand', 'Hemingway', 'Zhivago', 'Clemens', 'Heinlien', - 'Farmer', 'Niven', 'Van Vogt', 'Sturbridge', 'Washington', 'Adams', - 'Bush', 'Kennedy', 'Ford', 'Lincoln', 'Jackson', 'Johnson', - 'Eisenhower', 'Truman', 'Roosevelt', 'Wilson', 'Coolidge', 'Mack', - 'Moon', 'Monroe', 'Springsteen', 'Rigby', "O'Neil", 'Philips', - 'Clinton', 'Clapton', 'Santana', 'Midler', 'Flack', 'Conner', 'Bond', - 'Seinfeld', 'Costanza', 'Kramer', 'Falk', 'Moore', 'Cramdon', 'Baird', - 'Baer', 'Spears', 'Simmons', 'Roberts', 'Michaels', 'Stuart', - 'Montague', 'Miller' - ]) + return choice( + [ + 'Jones', + 'Smith', + 'Thompson', + 'Hayes', + 'Thomas', + 'Boyle', + "O'Reilly", + 'Lebowski', + 'Lennon', + 'Starr', + 'McCartney', + 'Harrison', + 'Harrelson', + 'Steinbeck', + 'Rand', + 'Hemingway', + 'Zhivago', + 'Clemens', + 'Heinlien', + 'Farmer', + 'Niven', + 'Van Vogt', + 'Sturbridge', + 'Washington', + 'Adams', + 'Bush', + 'Kennedy', + 'Ford', + 'Lincoln', + 'Jackson', + 'Johnson', + 'Eisenhower', + 'Truman', + 'Roosevelt', + 'Wilson', + 'Coolidge', + 'Mack', + 'Moon', + 'Monroe', + 'Springsteen', + 'Rigby', + "O'Neil", + 'Philips', + 'Clinton', + 'Clapton', + 'Santana', + 'Midler', + 'Flack', + 'Conner', + 'Bond', + 'Seinfeld', + 'Costanza', + 'Kramer', + 'Falk', + 'Moore', + 'Cramdon', + 'Baird', + 'Baer', + 'Spears', + 'Simmons', + 'Roberts', + 'Michaels', + 'Stuart', + 'Montague', + 'Miller', + ] + ) def address(): number = randint(11, 999) - text_1 = choice([ - 'Spring', 'Summer', 'Moonlight', 'Winding', 'Windy', 'Whispering', - 'Falling', 'Roaring', 'Hummingbird', 'Mockingbird', 'Bluebird', - 'Robin', 'Babbling', 'Cedar', 'Pine', 'Ash', 'Maple', 'Oak', 'Birch', - 'Cherry', 'Blossom', 'Rosewood', 'Apple', 'Peach', 'Blackberry', - 'Strawberry', 'Starlight', 'Wilderness', 'Dappled', 'Beaver', 'Acorn', - 'Pecan', 'Pheasant', 'Owl' - ]) - text_2 = choice([ - 'Way', 'Lane', 'Boulevard', 'Street', 'Drive', 'Circle', 'Avenue', - 'Trail' - ]) + text_1 = choice( + [ + 'Spring', + 'Summer', + 'Moonlight', + 'Winding', + 'Windy', + 'Whispering', + 'Falling', + 'Roaring', + 'Hummingbird', + 'Mockingbird', + 'Bluebird', + 'Robin', + 'Babbling', + 'Cedar', + 'Pine', + 'Ash', + 'Maple', + 'Oak', + 'Birch', + 'Cherry', + 'Blossom', + 'Rosewood', + 'Apple', + 'Peach', + 'Blackberry', + 'Strawberry', + 'Starlight', + 'Wilderness', + 'Dappled', + 'Beaver', + 'Acorn', + 'Pecan', + 'Pheasant', + 'Owl', + ] + ) + text_2 = choice( + [ + 'Way', + 'Lane', + 'Boulevard', + 'Street', + 'Drive', + 'Circle', + 'Avenue', + 'Trail', + ] + ) return '%d %s %s' % (number, text_1, text_2) @@ -272,7 +435,7 @@ def address(): Person( name='%s %s' % (any_name(), family_name()), age=age(), - address=address() + address=address(), ) for i in range(5000) ] @@ -282,17 +445,13 @@ def address(): MarriedPerson( name='%s %s' % (female_name(), last_name), age=age(), - address=address + address=address, ), MarriedPerson( - name='%s %s' % (male_name(), last_name), - age=age(), - address=address - ) + name='%s %s' % (male_name(), last_name), age=age(), address=address + ), ) - for last_name, address in [ - (family_name(), address()) for i in range(2500) - ] + for last_name, address in [(family_name(), address()) for i in range(2500)] ] for female, male in marrieds: diff --git a/traitsui/examples/demo/Advanced/Tabular_editor_with_context_menu_demo.py b/traitsui/examples/demo/Advanced/Tabular_editor_with_context_menu_demo.py index b68f66cb7..374960894 100644 --- a/traitsui/examples/demo/Advanced/Tabular_editor_with_context_menu_demo.py +++ b/traitsui/examples/demo/Advanced/Tabular_editor_with_context_menu_demo.py @@ -38,7 +38,12 @@ from random import randint from traits.api import HasStrictTraits, Str, Int, Float, List, Property from traitsui.api import ( - Action, Item, Menu, TabularAdapter, TabularEditor, View + Action, + Item, + Menu, + TabularAdapter, + TabularEditor, + View, ) @@ -54,14 +59,8 @@ def get_menu(self, object, trait, row, column): column_name = self.column_map[column] if column_name not in ['name', 'average']: menu = Menu( - Action( - name='Add', - action='editor.adapter.add(item, column)' - ), - Action( - name='Sub', - action='editor.adapter.sub(item, column)' - ) + Action(name='Add', action='editor.adapter.add(item, column)'), + Action(name='Sub', action='editor.adapter.sub(item, column)'), ) return menu else: @@ -75,14 +74,12 @@ def get_format(self, object, trait, row, column): return super().get_format(object, trait, row, column) def add(self, object, column): - """ Increment the affected player statistic. - """ + """Increment the affected player statistic.""" column_name = self.column_map[column] setattr(object, column_name, getattr(object, column_name) + 1) def sub(self, object, column): - """ Decrement the affected player statistic. - """ + """Decrement the affected player statistic.""" column_name = self.column_map[column] setattr(object, column_name, getattr(object, column_name) - 1) @@ -125,17 +122,17 @@ class Player(HasStrictTraits): average = Property(Float) def _get_average(self): - """ Computes the player's batting average from the current statistics. - """ + """Computes the player's batting average from the current statistics.""" if self.at_bats == 0: return 0.0 - return float(self.singles + self.doubles + - self.triples + self.home_runs) / self.at_bats + return ( + float(self.singles + self.doubles + self.triples + self.home_runs) + / self.at_bats + ) def _affects_average_changed(self): - """ Handles an event that affects the player's batting average. - """ + """Handles an event that affects the player's batting average.""" self.at_bats += 1 @@ -150,13 +147,12 @@ class Team(HasStrictTraits): title='Baseball Scoring Demo', width=0.5, height=0.5, - resizable=True + resizable=True, ) def random_player(name): - """ Generates and returns a random player. - """ + """Generates and returns a random player.""" p = Player( name=name, strike_outs=randint(0, 50), @@ -164,12 +160,16 @@ def random_player(name): doubles=randint(0, 20), triples=randint(0, 5), home_runs=randint(0, 30), - walks=randint(0, 50) + walks=randint(0, 50), ) return p.trait_set( at_bats=( - p.strike_outs + p.singles + p.doubles + p.triples + p.home_runs + - randint(100, 200) + p.strike_outs + + p.singles + + p.doubles + + p.triples + + p.home_runs + + randint(100, 200) ) ) @@ -177,9 +177,17 @@ def random_player(name): # Create the demo: demo = Team( players=[ - random_player(name) for name in [ - 'Dave', 'Mike', 'Joe', 'Tom', 'Dick', 'Harry', 'Dirk', 'Fields', - 'Stretch' + random_player(name) + for name in [ + 'Dave', + 'Mike', + 'Joe', + 'Tom', + 'Dick', + 'Harry', + 'Dirk', + 'Fields', + 'Stretch', ] ] ) diff --git a/traitsui/examples/demo/Advanced/Time_editor_demo.py b/traitsui/examples/demo/Advanced/Time_editor_demo.py index c90c79d13..18ce52ff9 100644 --- a/traitsui/examples/demo/Advanced/Time_editor_demo.py +++ b/traitsui/examples/demo/Advanced/Time_editor_demo.py @@ -25,7 +25,8 @@ class TimeEditorDemo(HasTraits): - """ Demo class. """ + """Demo class.""" + time = Time(datetime.time(12, 0, 0)) traits_view = View( @@ -35,13 +36,13 @@ class TimeEditorDemo(HasTraits): label='Readonly Editor', style='readonly', # Show 24-hour mode instead of default 12 hour. - editor=TimeEditor(strftime='%H:%M:%S') + editor=TimeEditor(strftime='%H:%M:%S'), ), - resizable=True + resizable=True, ) def _time_changed(self): - """ Print each time the time value is changed in the editor. """ + """Print each time the time value is changed in the editor.""" print(self.time) diff --git a/traitsui/examples/demo/Advanced/Tree_editor_required_traits_demo.py b/traitsui/examples/demo/Advanced/Tree_editor_required_traits_demo.py index 7ecf0b71a..7d1a3d189 100644 --- a/traitsui/examples/demo/Advanced/Tree_editor_required_traits_demo.py +++ b/traitsui/examples/demo/Advanced/Tree_editor_required_traits_demo.py @@ -28,7 +28,7 @@ class Employee(HasRequiredTraits): - """ Defines a company employee. """ + """Defines a company employee.""" name = Str('') title = Str() @@ -43,14 +43,14 @@ def create_default_employee(): class Department(HasTraits): - """ Defines a department with employees. """ + """Defines a department with employees.""" name = Str('') employees = List(Employee) class Company(HasTraits): - """ Defines a company with departments and employees. """ + """Defines a company with departments and employees.""" name = Str('') departments = List(Department) @@ -70,7 +70,7 @@ class Company(HasTraits): # child nodes are children='', label='name', # label with Company name - view=View(['name']) + view=View(['name']), ), TreeNode( node_for=[Company], @@ -79,35 +79,35 @@ class Company(HasTraits): label='=Departments', # constant label view=no_view, add=[Department], - ), + ), TreeNode( node_for=[Company], auto_open=True, children='employees', - label='=Employees', # constant label + label='=Employees', # constant label view=no_view, - add=[(Employee, True, create_default_employee)] + add=[(Employee, True, create_default_employee)], ), TreeNode( node_for=[Department], auto_open=True, children='employees', - label='name', # label with Department name + label='name', # label with Department name view=View(['name']), - add=[(Employee, True, create_default_employee)] + add=[(Employee, True, create_default_employee)], ), TreeNode( node_for=[Employee], auto_open=True, - label='name', # label with Employee name - view=View(['name', 'title', 'phone']) - ) + label='name', # label with Employee name + view=View(['name', 'title', 'phone']), + ), ] ) class Partner(HasTraits): - """ Defines a business partner.""" + """Defines a business partner.""" name = Str('') company = Instance(Company) @@ -118,8 +118,8 @@ class Partner(HasTraits): buttons=['OK'], resizable=True, style='custom', - width=.3, - height=500 + width=0.3, + height=500, ) @@ -137,16 +137,10 @@ class Partner(HasTraits): name='Enthought', employees=[dave, martin, duncan, jason, mike], departments=[ - Department( - name='Business', - employees=[jason, mike] - ), - Department( - name='Scientific', - employees=[dave, martin, duncan] - ) - ] - ) + Department(name='Business', employees=[jason, mike]), + Department(name='Scientific', employees=[dave, martin, duncan]), + ], + ), ) # Run the demo (if invoked from the command line): diff --git a/traitsui/examples/demo/Advanced/tests/test_List_editor_notebook_selection_demo.py b/traitsui/examples/demo/Advanced/tests/test_List_editor_notebook_selection_demo.py index e505f76bf..7af4b2034 100644 --- a/traitsui/examples/demo/Advanced/tests/test_List_editor_notebook_selection_demo.py +++ b/traitsui/examples/demo/Advanced/tests/test_List_editor_notebook_selection_demo.py @@ -30,7 +30,6 @@ class TestListEditorNotebookSelectionDemo(unittest.TestCase): - def test_list_editor_notebook_selection_demo(self): demo = runpy.run_path(DEMO_PATH)["demo"] @@ -49,5 +48,6 @@ def test_list_editor_notebook_selection_demo(self): # Run the test(s) unittest.TextTestRunner().run( unittest.TestLoader().loadTestsFromTestCase( - TestListEditorNotebookSelectionDemo) + TestListEditorNotebookSelectionDemo + ) ) diff --git a/traitsui/examples/demo/Applications/Python_source_browser.py b/traitsui/examples/demo/Applications/Python_source_browser.py index ba342c68c..6a63b30f0 100644 --- a/traitsui/examples/demo/Applications/Python_source_browser.py +++ b/traitsui/examples/demo/Applications/Python_source_browser.py @@ -26,38 +26,50 @@ - Blue ball if the file size > 16KB. """ -from time \ - import localtime, strftime - -from os \ - import listdir - -from os.path \ - import getsize, getmtime, isfile, join, splitext, basename, dirname +from time import localtime, strftime + +from os import listdir + +from os.path import ( + getsize, + getmtime, + isfile, + join, + splitext, + basename, + dirname, +) -from traits.api \ - import HasPrivateTraits, Str, Float, List, Directory, File, Code, \ - Instance, Property, cached_property +from traits.api import ( + HasPrivateTraits, + Str, + Float, + List, + Directory, + File, + Code, + Instance, + Property, + cached_property, +) import traitsui.api -from traitsui.api \ - import View, Item, HSplit, VSplit, TabularEditor, Font +from traitsui.api import View, Item, HSplit, VSplit, TabularEditor, Font -from traitsui.tabular_adapter \ - import TabularAdapter +from traitsui.tabular_adapter import TabularAdapter -from pyface.image_resource \ - import ImageResource +from pyface.image_resource import ImageResource from io import open -#-- Constants ------------------------------------------------------------ +# -- Constants ------------------------------------------------------------ # The images folder is in the same folder as this file: search_path = [dirname(__file__)] -#-- FileInfo Class Definition -------------------------------------------- +# -- FileInfo Class Definition -------------------------------------------- + class FileInfo(HasPrivateTraits): @@ -77,24 +89,25 @@ def _get_size(self): @cached_property def _get_time(self): - return strftime('%I:%M:%S %p', - localtime(getmtime(self.file_name))) + return strftime('%I:%M:%S %p', localtime(getmtime(self.file_name))) @cached_property def _get_date(self): - return strftime('%m/%d/%Y', - localtime(getmtime(self.file_name))) + return strftime('%m/%d/%Y', localtime(getmtime(self.file_name))) + -#-- Tabular Adapter Definition ------------------------------------------- +# -- Tabular Adapter Definition ------------------------------------------- class FileInfoAdapter(TabularAdapter): - columns = [('File Name', 'name'), - ('Size', 'size'), - ('', 'big'), - ('Time', 'time'), - ('Date', 'date')] + columns = [ + ('File Name', 'name'), + ('Size', 'size'), + ('', 'big'), + ('Time', 'time'), + ('Date', 'date'), + ] even_bg_color = (201, 223, 241) # FIXME: Font fails with wx in OSX; see traitsui issue #13: @@ -113,30 +126,33 @@ def _get_big_image(self): return (None, ImageResource('blue_ball'))[size > 16384] -#-- Tabular Editor Definition -------------------------------------------- + +# -- Tabular Editor Definition -------------------------------------------- tabular_editor = TabularEditor( editable=False, selected='file_info', adapter=FileInfoAdapter(), operations=[], - images=[ImageResource('blue_ball', search_path=search_path), - ImageResource('red_ball', search_path=search_path)] + images=[ + ImageResource('blue_ball', search_path=search_path), + ImageResource('red_ball', search_path=search_path), + ], ) -#-- PythonBrowser Class Definition --------------------------------------- +# -- PythonBrowser Class Definition --------------------------------------- class PythonBrowser(HasPrivateTraits): - #-- Trait Definitions ---------------------------------------------------- + # -- Trait Definitions ---------------------------------------------------- dir = Directory() files = List(FileInfo) file_info = Instance(FileInfo) code = Code() - #-- Traits View Definitions ---------------------------------------------- + # -- Traits View Definitions ---------------------------------------------- view = View( HSplit( @@ -144,22 +160,24 @@ class PythonBrowser(HasPrivateTraits): VSplit( Item('files', editor=tabular_editor), Item('code', style='readonly'), - show_labels=False), - show_labels=False + show_labels=False, + ), + show_labels=False, ), resizable=True, width=0.75, - height=0.75 + height=0.75, ) - #-- Event Handlers ------------------------------------------------------- + # -- Event Handlers ------------------------------------------------------- def _dir_changed(self, dir): if dir != '': - self.files = [FileInfo(file_name=join(dir, name)) - for name in listdir(dir) - if ((splitext(name)[1] == '.py') and - isfile(join(dir, name)))] + self.files = [ + FileInfo(file_name=join(dir, name)) + for name in listdir(dir) + if ((splitext(name)[1] == '.py') and isfile(join(dir, name))) + ] else: self.files = [] @@ -174,6 +192,7 @@ def _file_info_changed(self, file_info): if fh is not None: fh.close() + # Create the demo: demo = PythonBrowser(dir=dirname(dirname(__file__))) diff --git a/traitsui/examples/demo/Applications/converter.py b/traitsui/examples/demo/Applications/converter.py index df36dda14..ab8661300 100644 --- a/traitsui/examples/demo/Applications/converter.py +++ b/traitsui/examples/demo/Applications/converter.py @@ -44,14 +44,19 @@ """ # Units trait maps all units to centimeters: -Units = Trait('inches', {'inches': 2.54, - 'feet': (12 * 2.54), - 'yards': (36 * 2.54), - 'miles': (5280 * 12 * 2.54), - 'millimeters': 0.1, - 'centimeters': 1.0, - 'meters': 100.0, - 'kilometers': 100000.0}) +Units = Trait( + 'inches', + { + 'inches': 2.54, + 'feet': (12 * 2.54), + 'yards': (36 * 2.54), + 'miles': (5280 * 12 * 2.54), + 'millimeters': 0.1, + 'centimeters': 1.0, + 'meters': 100.0, + 'kilometers': 100000.0, + }, +) # Converter Class: @@ -61,9 +66,10 @@ class Converter(HasStrictTraits): # Trait definitions: input_amount = CFloat(12.0, desc="the input quantity") input_units = Units('inches', desc="the input quantity's units") - output_amount = Property(observe=['input_amount', 'input_units', - 'output_units'], - desc="the output quantity") + output_amount = Property( + observe=['input_amount', 'input_units', 'output_units'], + desc="the output quantity", + ) output_units = Units('feet', desc="the output quantity's units") # User interface views: @@ -73,23 +79,24 @@ class Converter(HasStrictTraits): Item('input_amount', springy=True), Item('input_units', show_label=False), label='Input', - show_border=True + show_border=True, ), HGroup( Item('output_amount', style='readonly', springy=True), Item('output_units', show_label=False), label='Output', - show_border=True + show_border=True, ), - help=ViewHelp + help=ViewHelp, ), title='Units Converter', - buttons=['Undo', 'OK', 'Help'] + buttons=['Undo', 'OK', 'Help'], ) # Property implementations def _get_output_amount(self): - return ((self.input_amount * self.input_units_) / self.output_units_) + return (self.input_amount * self.input_units_) / self.output_units_ + # Create the demo: popup = Converter() diff --git a/traitsui/examples/demo/Applications/tests/test_converter.py b/traitsui/examples/demo/Applications/tests/test_converter.py index 2117a4649..0abc39449 100644 --- a/traitsui/examples/demo/Applications/tests/test_converter.py +++ b/traitsui/examples/demo/Applications/tests/test_converter.py @@ -20,7 +20,11 @@ import unittest from traitsui.testing.api import ( - DisplayedText, KeyClick, KeySequence, MouseClick, UITester + DisplayedText, + KeyClick, + KeySequence, + MouseClick, + UITester, ) #: Filename of the demo script diff --git a/traitsui/examples/demo/Dynamic_Forms/dynamic_form_using_instances.py b/traitsui/examples/demo/Dynamic_Forms/dynamic_form_using_instances.py index 2aa630f39..4802bc7ef 100644 --- a/traitsui/examples/demo/Dynamic_Forms/dynamic_form_using_instances.py +++ b/traitsui/examples/demo/Dynamic_Forms/dynamic_form_using_instances.py @@ -45,39 +45,37 @@ class Spec(HasTraits): - """ An empty class from which all age-specific trait list classes are - derived. + """An empty class from which all age-specific trait list classes are + derived. """ + pass class ChildSpec(Spec): - """ Trait list for children (assigned to 'misc' for a Person when age < 18). - """ + """Trait list for children (assigned to 'misc' for a Person when age < 18).""" + legal_guardian = Str() school = Str() grade = Range(1, 12) - traits_view = View('legal_guardian', - 'school', - 'grade') + traits_view = View('legal_guardian', 'school', 'grade') class AdultSpec(Spec): - """ Trait list for adults (assigned to 'misc' for a Person when age >= 18). - """ + """Trait list for adults (assigned to 'misc' for a Person when age >= 18).""" marital_status = Enum('single', 'married', 'divorced', 'widowed') registered_voter = Bool() military_service = Bool() - traits_view = View('marital_status', - 'registered_voter', - 'military_service') + traits_view = View( + 'marital_status', 'registered_voter', 'military_service' + ) class PersonHandler(Handler): - """ Handler class to perform restructuring action when conditions are met. + """Handler class to perform restructuring action when conditions are met. The restructuring consists of replacing a ChildSpec instance by an AdultSpec instance, or vice-versa. We would not need a handler to listen for a change in age, but we do need a Handler so that Traits UI will @@ -86,17 +84,19 @@ class PersonHandler(Handler): """ def object_age_changed(self, info): - if ((info.object.age >= 18) and - (not isinstance(info.object.misc, AdultSpec))): + if (info.object.age >= 18) and ( + not isinstance(info.object.misc, AdultSpec) + ): info.object.misc = AdultSpec() - elif ((info.object.age < 18) and - (not isinstance(info.object.misc, ChildSpec))): + elif (info.object.age < 18) and ( + not isinstance(info.object.misc, ChildSpec) + ): info.object.misc = ChildSpec() class Person(HasTraits): - """ Demo class for demonstrating dynamic interface restructuring. - """ + """Demo class for demonstrating dynamic interface restructuring.""" + first_name = Str() last_name = Str() age = Range(0, 120) @@ -108,17 +108,14 @@ class Person(HasTraits): Item(name='last_name'), Item(name='age'), label='General Info', - show_border=True + show_border=True, ) # Interface for attributes that depend on the value of 'age': spec_group = Group( - Group( - Item(name='misc', style='custom'), - show_labels=False - ), + Group(Item(name='misc', style='custom'), show_labels=False), label='Additional Info', - show_border=True + show_border=True, ) # A simple View is enough as long as the right handler is specified: @@ -128,20 +125,20 @@ class Person(HasTraits): '10', Label("Using Instances and a Handler:"), '10', - spec_group + spec_group, ), title='Personal Information', buttons=['OK'], resizable=True, width=300, - handler=PersonHandler() + handler=PersonHandler(), ) + # Create the demo: -demo = Person(first_name="Samuel", - last_name="Johnson", - age=18, - misc=AdultSpec()) +demo = Person( + first_name="Samuel", last_name="Johnson", age=18, misc=AdultSpec() +) # Run the demo (if invoked from the command line): if __name__ == '__main__': diff --git a/traitsui/examples/demo/Dynamic_Forms/dynamic_range_editor.py b/traitsui/examples/demo/Dynamic_Forms/dynamic_range_editor.py index c7f874087..93ed9e4d6 100644 --- a/traitsui/examples/demo/Dynamic_Forms/dynamic_range_editor.py +++ b/traitsui/examples/demo/Dynamic_Forms/dynamic_range_editor.py @@ -46,8 +46,8 @@ class DynamicRangeEditor(HasPrivateTraits): - """ Defines an editor for dynamic ranges (i.e. ranges whose bounds can be - changed at run time). + """Defines an editor for dynamic ranges (i.e. ranges whose bounds can be + changed at run time). """ # The value with the dynamic range: @@ -70,66 +70,78 @@ class DynamicRangeEditor(HasPrivateTraits): # Traits view definitions: traits_view = View( - # Dynamic simple slider demo: Group( - Item('value', - editor=RangeEditor(low_name='low', - high_name='high', - format='%.1f', - label_width=28, - mode='auto') - ), + Item( + 'value', + editor=RangeEditor( + low_name='low', + high_name='high', + format='%.1f', + label_width=28, + mode='auto', + ), + ), '_', Item('low'), Item('high'), '_', - Label('Move the Low and High sliders to change the range of ' - 'Value.'), - label='Simple Slider' + Label( + 'Move the Low and High sliders to change the range of ' + 'Value.' + ), + label='Simple Slider', ), - # Dynamic large range slider demo: Group( - Item('value', - editor=RangeEditor(low_name='low', - high_name='high', - format='%.1f', - label_width=28, - mode='xslider') - ), + Item( + 'value', + editor=RangeEditor( + low_name='low', + high_name='high', + format='%.1f', + label_width=28, + mode='xslider', + ), + ), '_', Item('low'), Item('high'), '_', - Label('Move the Low and High sliders to change the range of ' - 'Value.'), - label='Large Range Slider' + Label( + 'Move the Low and High sliders to change the range of ' + 'Value.' + ), + label='Large Range Slider', ), - # Dynamic spinner demo: Group( - Item('int_value', - editor=RangeEditor(low=0, - high=20, - low_name='int_low', - high_name='int_high', - format='%d', - is_float=False, - label_width=28, - mode='spinner') - ), + Item( + 'int_value', + editor=RangeEditor( + low=0, + high=20, + low_name='int_low', + high_name='int_high', + format='%d', + is_float=False, + label_width=28, + mode='spinner', + ), + ), '_', Item('int_low'), Item('int_high'), '_', - Label('Move the Low and High sliders to change the range of ' - 'Value.'), - label='Spinner' + Label( + 'Move the Low and High sliders to change the range of ' + 'Value.' + ), + label='Spinner', ), title='Dynamic Range Editor Demonstration', buttons=['OK'], - resizable=True + resizable=True, ) diff --git a/traitsui/examples/demo/Dynamic_Forms/dynamic_selector.py b/traitsui/examples/demo/Dynamic_Forms/dynamic_selector.py index f4a52c1b1..eadabac5b 100644 --- a/traitsui/examples/demo/Dynamic_Forms/dynamic_selector.py +++ b/traitsui/examples/demo/Dynamic_Forms/dynamic_selector.py @@ -41,7 +41,7 @@ cities = { 'GA': ['Athens', 'Atlanta', 'Macon', 'Marietta', 'Savannah'], 'TX': ['Austin', 'Amarillo', 'Dallas', 'Houston', 'San Antonio', 'Waco'], - 'OR': ['Albany', 'Eugene', 'Portland'] + 'OR': ['Albany', 'Eugene', 'Portland'], } @@ -72,8 +72,7 @@ def object_state_changed(self, info): class Address(HasTraits): - """ Demo class for demonstrating dynamic redefinition of valid trait values. - """ + """Demo class for demonstrating dynamic redefinition of valid trait values.""" street_address = Str() state = Enum(list(cities.keys())[0], list(cities.keys())) @@ -82,13 +81,14 @@ class Address(HasTraits): view = View( Item(name='street_address'), Item(name='state'), - Item(name='city', - editor=EnumEditor(name='handler.cities'), - ), + Item( + name='city', + editor=EnumEditor(name='handler.cities'), + ), title='Address Information', buttons=['OK'], resizable=True, - handler=AddressHandler + handler=AddressHandler, ) diff --git a/traitsui/examples/demo/Dynamic_Forms/enabled_when.py b/traitsui/examples/demo/Dynamic_Forms/enabled_when.py index 9450a1d91..c6a400a5d 100644 --- a/traitsui/examples/demo/Dynamic_Forms/enabled_when.py +++ b/traitsui/examples/demo/Dynamic_Forms/enabled_when.py @@ -34,8 +34,7 @@ class Person(HasTraits): - """ Example of enabling/disabling components of a user interface. - """ + """Example of enabling/disabling components of a user interface.""" # General traits: first_name = Str() @@ -58,7 +57,7 @@ class Person(HasTraits): Item(name='last_name'), Item(name='age'), label='General Info', - show_border=True + show_border=True, ) # Interface for attributes of Persons under 18: @@ -90,19 +89,16 @@ class Person(HasTraits): Label("Using 'enabled_when':"), '10', child_group, - adult_group + adult_group, ), title='Personal Information', resizable=True, - buttons=['OK'] + buttons=['OK'], ) + # Create the demo: -demo = Person( - first_name="Samuel", - last_name="Johnson", - age=16 -) +demo = Person(first_name="Samuel", last_name="Johnson", age=16) # Run the demo (if invoked from the command line): if __name__ == '__main__': diff --git a/traitsui/examples/demo/Dynamic_Forms/tests/test_visible_when.py b/traitsui/examples/demo/Dynamic_Forms/tests/test_visible_when.py index a708d10f1..ba27844ca 100644 --- a/traitsui/examples/demo/Dynamic_Forms/tests/test_visible_when.py +++ b/traitsui/examples/demo/Dynamic_Forms/tests/test_visible_when.py @@ -20,9 +20,7 @@ import runpy import unittest -from traitsui.testing.api import ( - IsVisible, UITester -) +from traitsui.testing.api import IsVisible, UITester #: Filename of the demo script FILENAME = "visible_when.py" @@ -32,7 +30,6 @@ class TestVisibleWhenDemo(unittest.TestCase): - def test_visible_when_demo(self): demo = runpy.run_path(DEMO_PATH)["demo"] @@ -45,7 +42,7 @@ def test_visible_when_demo(self): legal_guardian_field = tester.find_by_name(ui, 'legal_guardian') self.assertFalse(marital_status_field.inspect(IsVisible())) self.assertTrue(legal_guardian_field.inspect(IsVisible())) - + # UITester is yet to support SimpleSpinEditor so we change the # value of the trait directly demo.age = 20 diff --git a/traitsui/examples/demo/Dynamic_Forms/visible_when.py b/traitsui/examples/demo/Dynamic_Forms/visible_when.py index 2438f5a3d..c569e1fbf 100644 --- a/traitsui/examples/demo/Dynamic_Forms/visible_when.py +++ b/traitsui/examples/demo/Dynamic_Forms/visible_when.py @@ -36,8 +36,7 @@ class Person(HasTraits): - """ Example of restructuring a user interface by controlling visibility. - """ + """Example of restructuring a user interface by controlling visibility.""" # General traits: first_name = Str() @@ -60,7 +59,7 @@ class Person(HasTraits): Item(name='last_name'), Item(name='age'), label='General Info', - show_border=True + show_border=True, ) # Interface for attributes of Persons under 18: @@ -91,19 +90,16 @@ class Person(HasTraits): Label("Using 'visible_when':"), '10', child_group, - adult_group + adult_group, ), title='Personal Information', resizable=True, - buttons=['OK'] + buttons=['OK'], ) + # Create the demo: -demo = Person( - first_name="Samuel", - last_name="Johnson", - age=16 -) +demo = Person(first_name="Samuel", last_name="Johnson", age=16) # Run the demo (if invoked from the command line): if __name__ == '__main__': diff --git a/traitsui/examples/demo/Extras/Image_editor_demo.py b/traitsui/examples/demo/Extras/Image_editor_demo.py index 6954fe754..81bad6c1b 100644 --- a/traitsui/examples/demo/Extras/Image_editor_demo.py +++ b/traitsui/examples/demo/Extras/Image_editor_demo.py @@ -14,17 +14,13 @@ """ # Imports: -from os.path \ - import join, dirname +from os.path import join, dirname -from traits.api \ - import HasTraits, Str +from traits.api import HasTraits, Str -from traitsui.api \ - import View, VGroup, Item, ImageEditor +from traitsui.api import View, VGroup, Item, ImageEditor -from pyface.image_resource \ - import ImageResource +from pyface.image_resource import ImageResource # Constants: @@ -45,33 +41,40 @@ class Employee(HasTraits): view = View( VGroup( VGroup( - Item('name', - show_label=False, - editor=ImageEditor( - image=ImageResource('info', - search_path=search_path))) + Item( + 'name', + show_label=False, + editor=ImageEditor( + image=ImageResource('info', search_path=search_path) + ), + ) ), VGroup( Item('name'), Item('dept'), Item('email'), - Item('picture', - editor=ImageEditor( - scale=True, - preserve_aspect_ratio=True, - allow_upscaling=True), - springy=True), - ) + Item( + 'picture', + editor=ImageEditor( + scale=True, + preserve_aspect_ratio=True, + allow_upscaling=True, + ), + springy=True, + ), + ), ), - resizable=True + resizable=True, ) + # Create the demo: -popup = Employee(name='William Murchison', - dept='Receiving', - email='wmurchison@acme.com', - picture=ImageResource('e-logo-rev', - search_path=search_path)) +popup = Employee( + name='William Murchison', + dept='Receiving', + email='wmurchison@acme.com', + picture=ImageResource('e-logo-rev', search_path=search_path), +) # Run the demo (if invoked form the command line): if __name__ == '__main__': diff --git a/traitsui/examples/demo/Extras/LED_display.py b/traitsui/examples/demo/Extras/LED_display.py index 11282cfc8..c608e44b8 100644 --- a/traitsui/examples/demo/Extras/LED_display.py +++ b/traitsui/examples/demo/Extras/LED_display.py @@ -13,7 +13,7 @@ using a simulated LED display control. """ -from threading import Thread +from threading import Thread from time import sleep @@ -22,6 +22,7 @@ from traitsui.api import View, Item, HGroup, Handler, UIInfo, spring from traits.etsconfig.api import ETSConfig + if ETSConfig.toolkit == 'wx': from traitsui.wx.extra.led_editor import LEDEditor else: @@ -49,15 +50,16 @@ def init(self, info): def closed(self, info, is_ok): self.running = False while self.alive: - sleep(.05) + sleep(0.05) def _update_counter(self): while self.running: self.info.object.counter1 += 1 - self.info.object.counter2 += .001 - sleep(.01) + self.info.object.counter2 += 0.001 + sleep(0.01) self.alive = False + # The main demo class: @@ -71,57 +73,66 @@ class LEDDemo(HasTraits): # The traits view: view = View( - Item('counter1', - label='Left aligned', - editor=LEDEditor(alignment='left') - ), - Item('counter1', - label='Center aligned', - editor=LEDEditor(alignment='center') - ), - Item('counter1', - label='Right aligned', - editor=LEDEditor() # default = 'right' aligned - ), - Item('counter2', - label='Float value', - editor=LEDEditor(format_str='%.3f') - ), + Item( + 'counter1', + label='Left aligned', + editor=LEDEditor(alignment='left'), + ), + Item( + 'counter1', + label='Center aligned', + editor=LEDEditor(alignment='center'), + ), + Item( + 'counter1', + label='Right aligned', + editor=LEDEditor(), # default = 'right' aligned + ), + Item( + 'counter2', + label='Float value', + editor=LEDEditor(format_str='%.3f'), + ), '_', HGroup( - Item('counter1', - label='Left', - height=-40, - width=120, - editor=LEDEditor(alignment='left') - ), + Item( + 'counter1', + label='Left', + height=-40, + width=120, + editor=LEDEditor(alignment='left'), + ), spring, - Item('counter1', - label='Center', - height=-40, - width=120, - editor=LEDEditor(alignment='center') - ), + Item( + 'counter1', + label='Center', + height=-40, + width=120, + editor=LEDEditor(alignment='center'), + ), spring, - Item('counter1', - label='Right', - height=-40, - width=120, - editor=LEDEditor() # default = 'right' aligned - ), + Item( + 'counter1', + label='Right', + height=-40, + width=120, + editor=LEDEditor(), # default = 'right' aligned + ), spring, - Item('counter2', - label='Float', - height=-40, - width=120, - editor=LEDEditor(format_str='%.3f') - ) + Item( + 'counter2', + label='Float', + height=-40, + width=120, + editor=LEDEditor(format_str='%.3f'), + ), ), title='LED Editor Demo', buttons=['OK'], - handler=LEDDemoHandler + handler=LEDDemoHandler, ) + # Create the demo: demo = LEDDemo() diff --git a/traitsui/examples/demo/Extras/Tree_editor_with_TreeNodeRenderer.py b/traitsui/examples/demo/Extras/Tree_editor_with_TreeNodeRenderer.py index 0ce4c50e0..93019ac67 100644 --- a/traitsui/examples/demo/Extras/Tree_editor_with_TreeNodeRenderer.py +++ b/traitsui/examples/demo/Extras/Tree_editor_with_TreeNodeRenderer.py @@ -22,9 +22,7 @@ import numpy as np from pyface.qt import QtCore, QtGui, qt_api -from traits.api import ( - Array, Float, HasTraits, Instance, Int, List, Str -) +from traits.api import Array, Float, HasTraits, Instance, Int, List, Str from traitsui.api import TreeEditor, TreeNode, UItem, View, RGBColor from traitsui.tree_node_renderer import AbstractTreeNodeRenderer @@ -32,7 +30,7 @@ class MyDataElement(HasTraits): - """ A node in a tree of data. """ + """A node in a tree of data.""" #: Some text to display. text = Str() @@ -51,7 +49,7 @@ def _color_default(self): class MyData(HasTraits): - """ The root node for a tree of data. """ + """The root node for a tree of data.""" #: The name of the root node. name = Str('Rooty McRootface') @@ -72,7 +70,7 @@ def _elements_default(self): class SparklineRenderer(AbstractTreeNodeRenderer): - """ Renderer that draws sparklines into a cell. """ + """Renderer that draws sparklines into a cell.""" #: This renderer handles all rendering. handles_all = True @@ -91,14 +89,16 @@ def paint(self, editor, node, column, object, paint_context): painter, option, index = paint_context data = self.get_data(object) - xs = np.linspace(0, option.rect.width(), len(data)) + option.rect.left() - ys = (data.max() - data)/self.y_scale + option.rect.top() + xs = ( + np.linspace(0, option.rect.width(), len(data)) + option.rect.left() + ) + ys = (data.max() - data) / self.y_scale + option.rect.top() height = option.rect.height() plot_height = ys.ptp() extra = height - plot_height if bool(option.displayAlignment & QtCore.Qt.AlignVCenter): - ys += extra/2 + ys += extra / 2 elif bool(option.displayAlignment & QtCore.Qt.Bottom): ys += extra @@ -124,11 +124,11 @@ def get_data(self, object): def size(self, editor, node, column, object, size_context): data = self.get_data(object) - return (100, data.ptp()/self.y_scale + self.extra_space) + return (100, data.ptp() / self.y_scale + self.extra_space) class SparklineTreeNode(TreeNode): - """ A TreeNode that renders sparklines in column index 1 """ + """A TreeNode that renders sparklines in column index 1""" #: static instance of SparklineRenderer #: (it has no state, so this is fine) @@ -149,7 +149,7 @@ def get_icon(self, object, is_expanded): class SparklineTreeView(HasTraits): - """ Class that views the data with sparklines. """ + """Class that views the data with sparklines.""" #: The root of the tree. root = Instance(MyData, args=()) diff --git a/traitsui/examples/demo/Extras/animated_GIF.py b/traitsui/examples/demo/Extras/animated_GIF.py index dcbaa474d..15d4a8cb3 100644 --- a/traitsui/examples/demo/Extras/animated_GIF.py +++ b/traitsui/examples/demo/Extras/animated_GIF.py @@ -28,7 +28,7 @@ files = [ abspath(join(base_path, 'logo_64x64.gif')), abspath(join(base_path, 'logo_48x48.gif')), - abspath(join(base_path, 'logo_32x32.gif')) + abspath(join(base_path, 'logo_32x32.gif')), ] @@ -44,21 +44,23 @@ class AnimatedGIFDemo(HasTraits): view = View( VGroup( HGroup( - Item('gif_file', - editor=AnimatedGIFEditor(playing='playing'), - show_label=False), + Item( + 'gif_file', + editor=AnimatedGIFEditor(playing='playing'), + show_label=False, + ), Item('playing'), ), '_', - Item('gif_file', - label='GIF File', - editor=EnumEditor(values=files) - ) + Item( + 'gif_file', label='GIF File', editor=EnumEditor(values=files) + ), ), title='Animated GIF Demo', - buttons=['OK'] + buttons=['OK'], ) + # Create the demo: demo = AnimatedGIFDemo() diff --git a/traitsui/examples/demo/Extras/tests/test_Image_editor_demo.py b/traitsui/examples/demo/Extras/tests/test_Image_editor_demo.py index d8c4de0e9..c1837c472 100644 --- a/traitsui/examples/demo/Extras/tests/test_Image_editor_demo.py +++ b/traitsui/examples/demo/Extras/tests/test_Image_editor_demo.py @@ -23,9 +23,8 @@ class TestImageEditorDemo(unittest.TestCase): - def test_image_path_exists(self): - search_path, = runpy.run_path(DEMO_PATH)["search_path"] + (search_path,) = runpy.run_path(DEMO_PATH)["search_path"] self.assertTrue(os.path.exists(search_path)) diff --git a/traitsui/examples/demo/Extras/windows/flash.py b/traitsui/examples/demo/Extras/windows/flash.py index b92027852..880742c88 100644 --- a/traitsui/examples/demo/Extras/windows/flash.py +++ b/traitsui/examples/demo/Extras/windows/flash.py @@ -12,14 +12,11 @@ """ # Imports: -from traitsui.wx.extra.windows.flash_editor \ - import FlashEditor +from traitsui.wx.extra.windows.flash_editor import FlashEditor -from traits.api \ - import Enum, HasTraits +from traits.api import Enum, HasTraits -from traitsui.api \ - import View, HGroup, Item +from traitsui.api import View, HGroup, Item # The demo class: @@ -37,20 +34,17 @@ class FlashDemo(HasTraits): 'http://www.ianag.com/arcade/swf/f-1416.swf', 'http://www.ianag.com/arcade/swf/mah_jongg.swf', 'http://www.ianag.com/arcade/swf/game_e4fe4e55fedc2f502be627ee6df716c5.swf', - 'http://www.ianag.com/arcade/swf/rhumb.swf') + 'http://www.ianag.com/arcade/swf/rhumb.swf', + ) # The view to display: view = View( - HGroup( - Item('flash', label='Pick a game to play') - ), + HGroup(Item('flash', label='Pick a game to play')), '_', - Item('flash', - show_label=False, - editor=FlashEditor() - ) + Item('flash', show_label=False, editor=FlashEditor()), ) + # Create the demo: demo = FlashDemo() diff --git a/traitsui/examples/demo/Extras/windows/internet_explorer.py b/traitsui/examples/demo/Extras/windows/internet_explorer.py index a6d7111d2..da2268fb7 100644 --- a/traitsui/examples/demo/Extras/windows/internet_explorer.py +++ b/traitsui/examples/demo/Extras/windows/internet_explorer.py @@ -12,14 +12,11 @@ """ # Imports: -from traitsui.wx.extra.windows.ie_html_editor \ - import IEHTMLEditor +from traitsui.wx.extra.windows.ie_html_editor import IEHTMLEditor -from traits.api \ - import Str, List, Button, HasTraits +from traits.api import Str, List, Button, HasTraits -from traitsui.api \ - import View, VGroup, HGroup, Item, TextEditor, ListEditor +from traitsui.api import View, VGroup, HGroup, Item, TextEditor, ListEditor # The web page class: @@ -45,20 +42,34 @@ class WebPage(HasTraits): # The view to display: view = View( - HGroup('back', 'forward', 'home', 'stop', 'refresh', 'search', '_', - Item('status', style='readonly'), - show_labels=False - ), - Item('url', - show_label=False, - editor=IEHTMLEditor( - home='home', back='back', - forward='forward', stop='stop', - refresh='refresh', search='search', - title='title', status='status') - ) + HGroup( + 'back', + 'forward', + 'home', + 'stop', + 'refresh', + 'search', + '_', + Item('status', style='readonly'), + show_labels=False, + ), + Item( + 'url', + show_label=False, + editor=IEHTMLEditor( + home='home', + back='back', + forward='forward', + stop='stop', + refresh='refresh', + search='search', + title='title', + status='status', + ), + ), ) + # The demo class: @@ -73,30 +84,38 @@ class InternetExplorerDemo(HasTraits): # The view to display: view = View( VGroup( - Item('url', - label='Location', - editor=TextEditor(auto_set=False, enter_set=True) - ) + Item( + 'url', + label='Location', + editor=TextEditor(auto_set=False, enter_set=True), + ) + ), + Item( + 'pages', + show_label=False, + style='custom', + editor=ListEditor( + use_notebook=True, + deletable=True, + dock_style='tab', + export='DockWindowShell', + page_name='.title', + ), ), - Item('pages', - show_label=False, - style='custom', - editor=ListEditor(use_notebook=True, - deletable=True, - dock_style='tab', - export='DockWindowShell', - page_name='.title') - ) ) # Event handlers: def _url_changed(self, url): self.pages.append(WebPage(url=url.strip())) + # Create the demo: demo = InternetExplorerDemo( - pages=[WebPage(url='http://code.enthought.com/projects/traits/'), - WebPage(url='http://dmorrill.com')]) + pages=[ + WebPage(url='http://code.enthought.com/projects/traits/'), + WebPage(url='http://dmorrill.com'), + ] +) # Run the demo (if invoked from the command line): if __name__ == '__main__': diff --git a/traitsui/examples/demo/Misc/demo_group_size.py b/traitsui/examples/demo/Misc/demo_group_size.py index 3cecfd135..68799c4c8 100644 --- a/traitsui/examples/demo/Misc/demo_group_size.py +++ b/traitsui/examples/demo/Misc/demo_group_size.py @@ -25,21 +25,31 @@ """ from numpy import linspace, pi, sin from traits.api import HasTraits, Instance, Str, Int + # UItem is Unlabeled Item -from traitsui.api import View, Item, UItem, HSplit, InstanceEditor, \ - VGroup, HGroup +from traitsui.api import ( + View, + Item, + UItem, + HSplit, + InstanceEditor, + VGroup, + HGroup, +) from chaco.api import Plot, AbstractPlotData, ArrayPlotData from enable.component_editor import ComponentEditor class InstanceUItem(UItem): """Convenience class for including an Instance in a View""" + style = Str('custom') editor = Instance(InstanceEditor, ()) class PlotView(HasTraits): """Defines a sub-view whose size we wish to explicitly control.""" + n = Int(123) data = Instance(AbstractPlotData) plot1 = Instance(Plot) @@ -62,6 +72,7 @@ def _data_changed(self): class VerticalBar(HasTraits): """Defines a sub-view whose size we wish to explicitly control.""" + a = Str('abcdefg') b = Int(123) view = View( @@ -81,6 +92,7 @@ class BigView(HasTraits): their own views, the resizing becomes possible, because they are loaded as Items now. """ + bar = Instance(VerticalBar, ()) plot = Instance(PlotView) view = View( @@ -96,6 +108,7 @@ class BigView(HasTraits): resizable=True, ) + x = linspace(-2 * pi, 2 * pi, 100) pv = PlotView(data=ArrayPlotData(x=x, y1=sin(x))) bv = BigView(plot=pv) diff --git a/traitsui/examples/demo/Misc/using_springs.py b/traitsui/examples/demo/Misc/using_springs.py index a80c982f6..11108a0a7 100644 --- a/traitsui/examples/demo/Misc/using_springs.py +++ b/traitsui/examples/demo/Misc/using_springs.py @@ -41,36 +41,56 @@ class SpringDemo(HasTraits): '10', Label(label='Spring in a horizontal group moves widget right:'), '10', - HGroup(button, button, - show_border=True, - label='Left justified (no springs)'), - HGroup(spring, button, button, - show_border=True, - label='Right justified with a spring ' - 'before any buttons'), - HGroup(button, spring, button, - show_border=True, - label='Left and right justified with a ' - 'spring between buttons'), - HGroup(button, button, spring, - button, button, spring, - button, button, - show_border=True, - label='Left, center and right justified ' - 'with springs after the 2nd and 4th ' - 'buttons'), + HGroup( + button, + button, + show_border=True, + label='Left justified (no springs)', + ), + HGroup( + spring, + button, + button, + show_border=True, + label='Right justified with a spring ' 'before any buttons', + ), + HGroup( + button, + spring, + button, + show_border=True, + label='Left and right justified with a ' + 'spring between buttons', + ), + HGroup( + button, + button, + spring, + button, + button, + spring, + button, + button, + show_border=True, + label='Left, center and right justified ' + 'with springs after the 2nd and 4th ' + 'buttons', + ), spring, - Label('Spring in vertical group moves widget down ' - '(does not work on Wx backend).'), - button + Label( + 'Spring in vertical group moves widget down ' + '(does not work on Wx backend).' + ), + button, ), width=600, height=600, resizable=True, title='Spring Demo', - buttons=['OK'] + buttons=['OK'], ) + demo = SpringDemo() if __name__ == '__main__': diff --git a/traitsui/examples/demo/Standard_Editors/ArrayEditor_demo.py b/traitsui/examples/demo/Standard_Editors/ArrayEditor_demo.py index a7f7cc7be..23057bf43 100644 --- a/traitsui/examples/demo/Standard_Editors/ArrayEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/ArrayEditor_demo.py @@ -22,7 +22,9 @@ class ArrayEditorTest(HasPrivateTraits): three = Array(np.int, (3, 3)) four = Array( - np.float, (4, 4), editor=ArrayEditor(width=-50), + np.float, + (4, 4), + editor=ArrayEditor(width=-50), ) view = View( diff --git a/traitsui/examples/demo/Standard_Editors/BooleanEditor_demo.py b/traitsui/examples/demo/Standard_Editors/BooleanEditor_demo.py index 418691b99..151477a53 100644 --- a/traitsui/examples/demo/Standard_Editors/BooleanEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/BooleanEditor_demo.py @@ -26,9 +26,9 @@ # Demo Class # ------------------------------------------------------------------------- + class BooleanEditorDemo(HasTraits): - """ This class specifies the details of the BooleanEditor demo. - """ + """This class specifies the details of the BooleanEditor demo.""" # To demonstrate any given Trait editor, an appropriate Trait is required. boolean_trait = Bool() @@ -43,15 +43,12 @@ class BooleanEditorDemo(HasTraits): Item('_'), Item( 'boolean_trait', style='readonly', label='ReadOnly', id='readonly' - ) + ), ) # Demo view traits_view = View( - bool_group, - title='BooleanEditor', - buttons=['OK'], - width=300 + bool_group, title='BooleanEditor', buttons=['OK'], width=300 ) diff --git a/traitsui/examples/demo/Standard_Editors/BooleanEditor_simple_demo.py b/traitsui/examples/demo/Standard_Editors/BooleanEditor_simple_demo.py index 53674d075..d6cc1d231 100644 --- a/traitsui/examples/demo/Standard_Editors/BooleanEditor_simple_demo.py +++ b/traitsui/examples/demo/Standard_Editors/BooleanEditor_simple_demo.py @@ -31,7 +31,7 @@ class BooleanEditorDemo(HasTraits): - """ Defines the main BooleanEditor demo class. """ + """Defines the main BooleanEditor demo class.""" # a boolean trait to view: my_boolean_trait = Bool() @@ -46,34 +46,29 @@ def _my_boolean_trait_changed(self): # Demo view traits_view = View( '10', # vertical space - Item('my_boolean_trait', style='simple', id='simple'), - '10', # vertical space - # We put this label in its own group so that it will be left justified. # Otherwise it will line up with other edit fields (indented): Group( - Label('The same Boolean trait can also be displayed and edited as ' - 'text (True/False):') + Label( + 'The same Boolean trait can also be displayed and edited as ' + 'text (True/False):' + ) ), - '10', # vertical space - Item( 'my_boolean_trait', style='readonly', label='Read-only style', - id='readonly' + id='readonly', ), Item('my_boolean_trait', style='text', label='Text style', id='text'), - '10', 'count_changes', - title='Boolean trait', buttons=['OK'], - resizable=True + resizable=True, ) diff --git a/traitsui/examples/demo/Standard_Editors/ButtonEditor_demo.py b/traitsui/examples/demo/Standard_Editors/ButtonEditor_demo.py index a19ad3565..75dab9ef3 100644 --- a/traitsui/examples/demo/Standard_Editors/ButtonEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/ButtonEditor_demo.py @@ -27,9 +27,9 @@ # Demo Class # ------------------------------------------------------------------------- + class ButtonEditorDemo(HasTraits): - """ This class specifies the details of the ButtonEditor demo. - """ + """This class specifies the details of the ButtonEditor demo.""" # To demonstrate any given Trait editor, an appropriate Trait is required. fire_event = Button('Click Me') @@ -47,15 +47,12 @@ def _button_clicked_message(self, event): Item('_'), Item(label='[text style unavailable]'), Item('_'), - Item(label='[readonly style unavailable]') + Item(label='[readonly style unavailable]'), ) # Demo view traits_view = View( - event_group, - title='ButtonEditor', - buttons=['OK'], - width=250 + event_group, title='ButtonEditor', buttons=['OK'], width=250 ) diff --git a/traitsui/examples/demo/Standard_Editors/ButtonEditor_simple_demo.py b/traitsui/examples/demo/Standard_Editors/ButtonEditor_simple_demo.py index d143106b9..a4f2185b7 100644 --- a/traitsui/examples/demo/Standard_Editors/ButtonEditor_simple_demo.py +++ b/traitsui/examples/demo/Standard_Editors/ButtonEditor_simple_demo.py @@ -27,7 +27,7 @@ class ButtonEditorDemo(HasTraits): - """ Defines the main ButtonEditor demo class. """ + """Defines the main ButtonEditor demo class.""" # Define a Button trait: my_button_trait = Button('Click Me') @@ -44,7 +44,7 @@ def _increment_counter(self, event): Item('click_counter', style='readonly'), title='ButtonEditor', buttons=['OK'], - resizable=True + resizable=True, ) diff --git a/traitsui/examples/demo/Standard_Editors/CSVListEditor_demo.py b/traitsui/examples/demo/Standard_Editors/CSVListEditor_demo.py index 5e6adfcf0..74dc29056 100644 --- a/traitsui/examples/demo/Standard_Editors/CSVListEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/CSVListEditor_demo.py @@ -21,11 +21,28 @@ """ from traits.api import ( - HasTraits, List, Int, Float, Enum, Range, Str, Button, Property, observe + HasTraits, + List, + Int, + Float, + Enum, + Range, + Str, + Button, + Property, + observe, ) from traitsui.api import ( - View, Item, Label, Heading, VGroup, HGroup, UItem, spring, TextEditor, - CSVListEditor + View, + Item, + Label, + Heading, + VGroup, + HGroup, + UItem, + spring, + TextEditor, + CSVListEditor, ) @@ -64,85 +81,126 @@ class CSVListEditorDemo(HasTraits): 'list1', label="List(Int)", editor=CSVListEditor(ignore_trailing_sep=False), - tooltip='options: ignore_trailing_sep=False' + tooltip='options: ignore_trailing_sep=False', ), Item( 'list1', label="List(Int)", style='readonly', - editor=CSVListEditor() + editor=CSVListEditor(), ), Item( 'list2', label="List(Float)", editor=CSVListEditor(enter_set=True, auto_set=False), - tooltip='options: enter_set=True, auto_set=False' + tooltip='options: enter_set=True, auto_set=False', ), Item( 'list3', label="List(Str, maxlen=3)", - editor=CSVListEditor() + editor=CSVListEditor(), ), Item( 'list4', label="List(Enum('red', 'green', 'blue', 2, 3))", editor=CSVListEditor(sep=None), - tooltip='options: sep=None' + tooltip='options: sep=None', ), Item( 'list5', label="List(Range(low=0.0, high=10.0))", - editor=CSVListEditor() + editor=CSVListEditor(), ), Item( 'list6', label="List(Range(low=-1.0, high='high'))", - editor=CSVListEditor() + editor=CSVListEditor(), ), Item( 'list7', label="List(Range(low='low', high='high'))", - editor=CSVListEditor() + editor=CSVListEditor(), ), springy=True, ), # This VGroup forms the right column; it will display the # Python str representation of the lists. VGroup( - UItem('list1str', editor=TextEditor(), - enabled_when='False', width=240), - UItem('list1str', editor=TextEditor(), - enabled_when='False', width=240), - UItem('list2', editor=TextEditor(), - enabled_when='False', width=240), - UItem('list3', editor=TextEditor(), - enabled_when='False', width=240), - UItem('list4', editor=TextEditor(), - enabled_when='False', width=240), - UItem('list5', editor=TextEditor(), - enabled_when='False', width=240), - UItem('list6', editor=TextEditor(), - enabled_when='False', width=240), - UItem('list7', editor=TextEditor(), - enabled_when='False', width=240), + UItem( + 'list1str', + editor=TextEditor(), + enabled_when='False', + width=240, + ), + UItem( + 'list1str', + editor=TextEditor(), + enabled_when='False', + width=240, + ), + UItem( + 'list2', + editor=TextEditor(), + enabled_when='False', + width=240, + ), + UItem( + 'list3', + editor=TextEditor(), + enabled_when='False', + width=240, + ), + UItem( + 'list4', + editor=TextEditor(), + enabled_when='False', + width=240, + ), + UItem( + 'list5', + editor=TextEditor(), + enabled_when='False', + width=240, + ), + UItem( + 'list6', + editor=TextEditor(), + enabled_when='False', + width=240, + ), + UItem( + 'list7', + editor=TextEditor(), + enabled_when='False', + width=240, + ), ), ), '_', HGroup('low', 'high', spring, UItem('pop1'), UItem('sort1')), Heading("Notes"), - Label("Hover over a list to see which editor options are set, " - "if any."), - Label("The editor of the first list, List(Int), uses " - "ignore_trailing_sep=False, so a trailing comma is " - "an error."), + Label( + "Hover over a list to see which editor options are set, " "if any." + ), + Label( + "The editor of the first list, List(Int), uses " + "ignore_trailing_sep=False, so a trailing comma is " + "an error." + ), Label("The second list is a read-only view of the first list."), - Label("The editor of the List(Float) example has enter_set=True " - "and auto_set=False; press Enter to validate."), + Label( + "The editor of the List(Float) example has enter_set=True " + "and auto_set=False; press Enter to validate." + ), Label("The List(Str) example will accept at most 3 elements."), - Label("The editor of the List(Enum(...)) example uses sep=None, " - "i.e. whitespace acts as a separator."), - Label("The last three List(Range(...)) examples take neither, one or " - "both of their limits from the Low and High fields below."), + Label( + "The editor of the List(Enum(...)) example uses sep=None, " + "i.e. whitespace acts as a separator." + ), + Label( + "The last three List(Range(...)) examples take neither, one or " + "both of their limits from the Low and High fields below." + ), width=720, title="CSVListEditor Demonstration", ) diff --git a/traitsui/examples/demo/Standard_Editors/CheckListEditor_demo.py b/traitsui/examples/demo/Standard_Editors/CheckListEditor_demo.py index f5b530cef..5eba5c203 100644 --- a/traitsui/examples/demo/Standard_Editors/CheckListEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/CheckListEditor_demo.py @@ -26,28 +26,19 @@ # Define the demo class: class CheckListEditorDemo(HasTraits): - """ Define the main CheckListEditor demo class. """ + """Define the main CheckListEditor demo class.""" # Define a trait for each of three formations: checklist_4col = List( - editor=CheckListEditor( - values=['one', 'two', 'three', 'four'], - cols=4 - ) + editor=CheckListEditor(values=['one', 'two', 'three', 'four'], cols=4) ) checklist_2col = List( - editor=CheckListEditor( - values=['one', 'two', 'three', 'four'], - cols=2 - ) + editor=CheckListEditor(values=['one', 'two', 'three', 'four'], cols=2) ) checklist_1col = List( - editor=CheckListEditor( - values=['one', 'two', 'three', 'four'], - cols=1 - ) + editor=CheckListEditor(values=['one', 'two', 'three', 'four'], cols=1) ) # CheckListEditor display with four columns: @@ -59,7 +50,7 @@ class CheckListEditorDemo(HasTraits): Item('checklist_4col', style='text', label='Text'), Item('_'), Item('checklist_4col', style='readonly', label='ReadOnly'), - label='4-column' + label='4-column', ) # CheckListEditor display with two columns: @@ -71,7 +62,7 @@ class CheckListEditorDemo(HasTraits): Item('checklist_2col', style='text', label='Text'), Item('_'), Item('checklist_2col', style='readonly', label='ReadOnly'), - label='2-column' + label='2-column', ) # CheckListEditor display with one column: @@ -83,7 +74,7 @@ class CheckListEditorDemo(HasTraits): Item('checklist_1col', style='text', label='Text'), Item('_'), Item('checklist_1col', style='readonly', label='ReadOnly'), - label='1-column' + label='1-column', ) # The view includes one group per column formation. These will be @@ -94,7 +85,7 @@ class CheckListEditorDemo(HasTraits): cl_1_group, title='CheckListEditor', buttons=['OK'], - resizable=True + resizable=True, ) diff --git a/traitsui/examples/demo/Standard_Editors/CheckListEditor_simple_demo.py b/traitsui/examples/demo/Standard_Editors/CheckListEditor_simple_demo.py index de043d645..65b9bcdaa 100644 --- a/traitsui/examples/demo/Standard_Editors/CheckListEditor_simple_demo.py +++ b/traitsui/examples/demo/Standard_Editors/CheckListEditor_simple_demo.py @@ -37,13 +37,12 @@ class CheckListEditorDemo(HasTraits): - """ Define the main CheckListEditor simple demo class. """ + """Define the main CheckListEditor simple demo class.""" # Specify the strings to be displayed in the checklist: checklist = List( editor=CheckListEditor( - values=['one', 'two', 'three', 'four', 'five', 'six'], - cols=2 + values=['one', 'two', 'three', 'four', 'five', 'six'], cols=2 ) ) @@ -52,9 +51,13 @@ class CheckListEditorDemo(HasTraits): '10', # insert vertical space (10 empty pixels) Label('The custom style lets you select items from a checklist:'), UItem('checklist', style='custom', id="custom"), - '10', '_', '10', # horizontal line with vertical space above and below - Label('The readonly style shows you which items are selected, ' - 'as a Python list:'), + '10', + '_', + '10', # horizontal line with vertical space above and below + Label( + 'The readonly style shows you which items are selected, ' + 'as a Python list:' + ), UItem('checklist', style='readonly', id="readonly"), ) @@ -62,7 +65,7 @@ class CheckListEditorDemo(HasTraits): checklist_group, title='CheckListEditor', buttons=['OK'], - resizable=True + resizable=True, ) diff --git a/traitsui/examples/demo/Standard_Editors/CodeEditor_demo.py b/traitsui/examples/demo/Standard_Editors/CodeEditor_demo.py index cdcd7aa73..41a89dbac 100644 --- a/traitsui/examples/demo/Standard_Editors/CodeEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/CodeEditor_demo.py @@ -25,8 +25,7 @@ # The main demo class: class CodeEditorDemo(HasTraits): - """ Defines the CodeEditor demo class. - """ + """Defines the CodeEditor demo class.""" # Define a trait to view: code_sample = Code('import sys\n\nsys.print("hello world!")') @@ -39,16 +38,12 @@ class CodeEditorDemo(HasTraits): Item('_'), Item('code_sample', style='text', label='Text'), Item('_'), - Item('code_sample', style='readonly', label='ReadOnly') + Item('code_sample', style='readonly', label='ReadOnly'), ) # Demo view: traits_view = View( - code_group, - title='CodeEditor', - width=600, - height=600, - buttons=['OK'] + code_group, title='CodeEditor', width=600, height=600, buttons=['OK'] ) diff --git a/traitsui/examples/demo/Standard_Editors/ColorEditor_demo.py b/traitsui/examples/demo/Standard_Editors/ColorEditor_demo.py index e5ee10722..51f80c4b7 100644 --- a/traitsui/examples/demo/Standard_Editors/ColorEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/ColorEditor_demo.py @@ -35,7 +35,7 @@ # Demo class definition: class ColorEditorDemo(HasTraits): - """ Defines the main ColorEditor demo. """ + """Defines the main ColorEditor demo.""" # Define a Color trait to view: color_trait = Color() @@ -48,15 +48,12 @@ class ColorEditorDemo(HasTraits): Item('_'), Item('color_trait', style='text', label='Text'), Item('_'), - Item('color_trait', style='readonly', label='ReadOnly') + Item('color_trait', style='readonly', label='ReadOnly'), ) # Demo view traits_view = View( - color_group, - title='ColorEditor', - buttons=['OK'], - resizable=True + color_group, title='ColorEditor', buttons=['OK'], resizable=True ) diff --git a/traitsui/examples/demo/Standard_Editors/CompoundEditor_demo.py b/traitsui/examples/demo/Standard_Editors/CompoundEditor_demo.py index f04fd4e8c..2404b8ca8 100644 --- a/traitsui/examples/demo/Standard_Editors/CompoundEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/CompoundEditor_demo.py @@ -34,8 +34,7 @@ # Define the demo class: class CompoundEditorDemo(HasTraits): - """ Defines the main CompoundEditor demo class. - """ + """Defines the main CompoundEditor demo class.""" # Define a compound trait to view: compound_trait = Union( @@ -50,15 +49,12 @@ class CompoundEditorDemo(HasTraits): Item('_'), Item('compound_trait', style='text', label='Text'), Item('_'), - Item('compound_trait', style='readonly', label='ReadOnly') + Item('compound_trait', style='readonly', label='ReadOnly'), ) # Demo view: traits_view = View( - comp_group, - title='CompoundEditor', - buttons=['OK'], - resizable=True + comp_group, title='CompoundEditor', buttons=['OK'], resizable=True ) diff --git a/traitsui/examples/demo/Standard_Editors/DataFrameEditor_demo.py b/traitsui/examples/demo/Standard_Editors/DataFrameEditor_demo.py index e83c30689..5f72f1209 100644 --- a/traitsui/examples/demo/Standard_Editors/DataFrameEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/DataFrameEditor_demo.py @@ -52,13 +52,13 @@ class DataFrameEditorDemo(HasTraits): 'BoxOfficeRevenueInMillions': '%d', 'AcademyAwardNominations': '%d', 'AcademyAwardWins': '%d', - 'RottenTomatoesScore': '%.2f' + 'RottenTomatoesScore': '%.2f', } - ) + ), ), title="DataFrameEditor", resizable=True, - id='traitsui.demo.Applications.data_frame_editor_demo' + id='traitsui.demo.Applications.data_frame_editor_demo', ) @@ -72,7 +72,7 @@ class DataFrameEditorDemo(HasTraits): [462.0, 675, 2932.0, 7, 1, 66.33333333], [169, 200, 1021.0, 3, 1, 64.0], [161, 217, 958.4, 3, 0, 75.0], - [144, 250, 956.0, 1, 0, 60.0] + [144, 250, 956.0, 1, 0, 60.0], ] ) @@ -82,8 +82,8 @@ class DataFrameEditorDemo(HasTraits): 'BoxOfficeRevenueInMillions', 'AcademyAwardNominations', 'AcademyAwardWins', - 'RottenTomatoesScore' - ] + 'RottenTomatoesScore', +] index_names = [ 'The Lord of the Rings Series', @@ -93,7 +93,7 @@ class DataFrameEditorDemo(HasTraits): 'The Hobbit Series', 'The Unexpected Journey', 'The Desolation of Smaug', - 'The Battle of the Five Armies' + 'The Battle of the Five Armies', ] # Create & run the demo diff --git a/traitsui/examples/demo/Standard_Editors/DatetimeEditor_demo.py b/traitsui/examples/demo/Standard_Editors/DatetimeEditor_demo.py index fbb99e419..e50b5ae3a 100644 --- a/traitsui/examples/demo/Standard_Editors/DatetimeEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/DatetimeEditor_demo.py @@ -32,7 +32,8 @@ class DateEditorDemo(HasTraits): - """ Demo class to show Datetime editors. """ + """Demo class to show Datetime editors.""" + datetime = Datetime() info_string = Str('The editors for Traits Datetime objects.') @@ -58,15 +59,13 @@ class DateEditorDemo(HasTraits): ) def _datetime_changed(self): - """ Print each time the date value is changed in the editor. """ + """Print each time the date value is changed in the editor.""" print(self.datetime) # -- Set Up The Demo ------------------------------------------------------ -demo = DateEditorDemo( - datetime=datetime.datetime.now() -) +demo = DateEditorDemo(datetime=datetime.datetime.now()) if __name__ == "__main__": demo.configure_traits() diff --git a/traitsui/examples/demo/Standard_Editors/DirectoryEditor_demo.py b/traitsui/examples/demo/Standard_Editors/DirectoryEditor_demo.py index 0c764fa76..cf48bf65a 100644 --- a/traitsui/examples/demo/Standard_Editors/DirectoryEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/DirectoryEditor_demo.py @@ -34,7 +34,7 @@ # Define the demo class: class DirectoryEditorDemo(HasTraits): - """ Define the main DirectoryEditor demo class. """ + """Define the main DirectoryEditor demo class.""" # Define a Directory trait to view: dir_name = Directory() @@ -47,7 +47,7 @@ class DirectoryEditorDemo(HasTraits): Item('_'), Item('dir_name', style='text', label='Text'), Item('_'), - Item('dir_name', style='readonly', label='ReadOnly') + Item('dir_name', style='readonly', label='ReadOnly'), ) # Demo view: @@ -57,7 +57,7 @@ class DirectoryEditorDemo(HasTraits): width=400, height=600, buttons=['OK'], - resizable=True + resizable=True, ) diff --git a/traitsui/examples/demo/Standard_Editors/EnumEditor_demo.py b/traitsui/examples/demo/Standard_Editors/EnumEditor_demo.py index 7887fc61d..d2a39fdd5 100644 --- a/traitsui/examples/demo/Standard_Editors/EnumEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/EnumEditor_demo.py @@ -40,57 +40,56 @@ class EnumEditorDemo(HasTraits): - """ Defines the main EnumEditor demo class. """ + """Defines the main EnumEditor demo class.""" # Define an Enum trait to view. - name_list = Enum('A-495', 'A-498', 'R-1226', 'TS-17', 'TS-18', - 'Foo', 12345, (11, 7), None) + name_list = Enum( + 'A-495', + 'A-498', + 'R-1226', + 'TS-17', + 'TS-18', + 'Foo', + 12345, + (11, 7), + None, + ) # Items are used to define the display, one Item per editor style: enum_group = Group( Item('name_list', style='simple', label='Simple', id="simple"), Item('_'), - # The simple style also supports text entry: Item( 'name_list', style='simple', label='Simple (text entry)', editor=EnumEditor( - values=name_list, - completion_mode='popup', - evaluate=True + values=name_list, completion_mode='popup', evaluate=True ), - id="simple_text" + id="simple_text", ), Item('_'), - # The custom style defaults to radio button mode: Item('name_list', style='custom', label='Custom radio', id="radio"), Item('_'), - # The custom style can also display in list mode, with extra work: Item( 'name_list', style='custom', label='Custom list', editor=EnumEditor(values=name_list, mode='list'), - id="list" + id="list", ), Item('_'), - Item('name_list', style='text', label='Text', id="text"), Item('_'), - - Item('name_list', style='readonly', label='ReadOnly', id="readonly") + Item('name_list', style='readonly', label='ReadOnly', id="readonly"), ) # Demo view: traits_view = View( - enum_group, - title='EnumEditor', - buttons=['OK'], - resizable=True + enum_group, title='EnumEditor', buttons=['OK'], resizable=True ) diff --git a/traitsui/examples/demo/Standard_Editors/FileEditor_demo.py b/traitsui/examples/demo/Standard_Editors/FileEditor_demo.py index 48db9c4f9..676afe2d1 100644 --- a/traitsui/examples/demo/Standard_Editors/FileEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/FileEditor_demo.py @@ -34,7 +34,7 @@ # Define the demo class: class FileEditorDemo(HasTraits): - """ Defines the main FileEditor demo class. """ + """Defines the main FileEditor demo class.""" # Define a File trait to view: file_name = File() @@ -47,7 +47,7 @@ class FileEditorDemo(HasTraits): Item('_'), Item('file_name', style='text', label='Text'), Item('_'), - Item('file_name', style='readonly', label='ReadOnly') + Item('file_name', style='readonly', label='ReadOnly'), ) # Demo view: @@ -57,7 +57,7 @@ class FileEditorDemo(HasTraits): width=400, height=600, buttons=['OK'], - resizable=True + resizable=True, ) diff --git a/traitsui/examples/demo/Standard_Editors/File_Dialog/File_Open.py b/traitsui/examples/demo/Standard_Editors/File_Dialog/File_Open.py index 481b14a4e..acbcbd9b2 100644 --- a/traitsui/examples/demo/Standard_Editors/File_Dialog/File_Open.py +++ b/traitsui/examples/demo/Standard_Editors/File_Dialog/File_Open.py @@ -93,16 +93,15 @@ class FileDialogDemo(HasTraits): HGroup( Item('open', show_label=False), '_', - Item('file_name', style='readonly', springy=True) + Item('file_name', style='readonly', springy=True), ), - width=0.5 + width=0.5, ) # -- Traits Event Handlers ------------------------------------------------ def _open_changed(self): - """ Handles the user clicking the 'Open...' button. - """ + """Handles the user clicking the 'Open...' button.""" file_name = open_file() if file_name != '': self.file_name = file_name diff --git a/traitsui/examples/demo/Standard_Editors/File_Dialog/File_Open_with_Custom_Extension.py b/traitsui/examples/demo/Standard_Editors/File_Dialog/File_Open_with_Custom_Extension.py index 74fb878e2..a9e0c2a00 100644 --- a/traitsui/examples/demo/Standard_Editors/File_Dialog/File_Open_with_Custom_Extension.py +++ b/traitsui/examples/demo/Standard_Editors/File_Dialog/File_Open_with_Custom_Extension.py @@ -36,8 +36,8 @@ # -- LineCountInfo Class -------------------------------------------------- class LineCountInfo(MFileDialogModel): - """ Defines a file dialog extension that displays the number of text lines - in the currently selected file. + """Defines a file dialog extension that displays the number of text lines + in the currently selected file. """ # The number of text lines in the currently selected file: @@ -49,7 +49,7 @@ class LineCountInfo(MFileDialogModel): VGroup( Item('lines', style='readonly'), label='Line Count Info', - show_border=True + show_border=True, ) ) @@ -69,7 +69,7 @@ def _get_lines(self): if (data.find('\x00') >= 0) or (data.find('\xFF') >= 0): return 'File contains binary data...' - return ('{:n} lines'.format(len(data.splitlines()))) + return '{:n} lines'.format(len(data.splitlines())) # -- FileDialogDemo Class ------------------------------------------------- @@ -92,16 +92,15 @@ class FileDialogDemo(HasTraits): HGroup( Item('open', show_label=False), '_', - Item('file_name', style='readonly', springy=True) + Item('file_name', style='readonly', springy=True), ), - width=0.5 + width=0.5, ) # -- Traits Event Handlers ------------------------------------------------ def _open_changed(self): - """ Handles the user clicking the 'Open...' button. - """ + """Handles the user clicking the 'Open...' button.""" file_name = open_file(extensions=LineCountInfo(), id=demo_id) if file_name != '': self.file_name = file_name diff --git a/traitsui/examples/demo/Standard_Editors/File_Dialog/File_Open_with_FileInfo_Extension.py b/traitsui/examples/demo/Standard_Editors/File_Dialog/File_Open_with_FileInfo_Extension.py index ad49b3dbf..1abeaf279 100644 --- a/traitsui/examples/demo/Standard_Editors/File_Dialog/File_Open_with_FileInfo_Extension.py +++ b/traitsui/examples/demo/Standard_Editors/File_Dialog/File_Open_with_FileInfo_Extension.py @@ -59,16 +59,15 @@ class FileDialogDemo(HasTraits): HGroup( Item('open', show_label=False), '_', - Item('file_name', style='readonly', springy=True) + Item('file_name', style='readonly', springy=True), ), - width=0.5 + width=0.5, ) # -- Traits Event Handlers ------------------------------------------------ def _open_changed(self): - """ Handles the user clicking the 'Open...' button. - """ + """Handles the user clicking the 'Open...' button.""" file_name = open_file(extensions=FileInfo(), id=demo_id) if file_name != '': self.file_name = file_name diff --git a/traitsui/examples/demo/Standard_Editors/File_Dialog/File_Open_with_ImageInfo_Extension.py b/traitsui/examples/demo/Standard_Editors/File_Dialog/File_Open_with_ImageInfo_Extension.py index 9bf5aa988..84d5a842b 100644 --- a/traitsui/examples/demo/Standard_Editors/File_Dialog/File_Open_with_ImageInfo_Extension.py +++ b/traitsui/examples/demo/Standard_Editors/File_Dialog/File_Open_with_ImageInfo_Extension.py @@ -49,7 +49,7 @@ 'PNG file (*.png)|*.png', 'GIF file (*.gif)|*.gif', 'JPG file (*.jpg)|*.jpg', - 'JPEG file (*.jpeg)|*.jpeg' + 'JPEG file (*.jpeg)|*.jpeg', ] @@ -67,19 +67,18 @@ class FileDialogDemo(HasTraits): HGroup( Item('open', show_label=False), '_', - Item('file_name', style='readonly', springy=True) + Item('file_name', style='readonly', springy=True), ), - width=0.5 + width=0.5, ) # -- Traits Event Handlers ------------------------------------------------ def _open_changed(self): - """ Handles the user clicking the 'Open...' button. - """ - file_name = open_file(extensions=ImageInfo(), - filter=filters, - id=demo_id) + """Handles the user clicking the 'Open...' button.""" + file_name = open_file( + extensions=ImageInfo(), filter=filters, id=demo_id + ) if file_name != '': self.file_name = file_name diff --git a/traitsui/examples/demo/Standard_Editors/File_Dialog/File_Open_with_Multiple_Extensions.py b/traitsui/examples/demo/Standard_Editors/File_Dialog/File_Open_with_Multiple_Extensions.py index 111e72a5d..331721c85 100644 --- a/traitsui/examples/demo/Standard_Editors/File_Dialog/File_Open_with_Multiple_Extensions.py +++ b/traitsui/examples/demo/Standard_Editors/File_Dialog/File_Open_with_Multiple_Extensions.py @@ -64,16 +64,15 @@ class FileDialogDemo(HasTraits): HGroup( Item('open', show_label=False), '_', - Item('file_name', style='readonly', springy=True) + Item('file_name', style='readonly', springy=True), ), - width=0.5 + width=0.5, ) # -- Traits Event Handlers ------------------------------------------------ def _open_changed(self): - """ Handles the user clicking the 'Open...' button. - """ + """Handles the user clicking the 'Open...' button.""" file_name = open_file(extensions=extensions, id=demo_id) if file_name != '': self.file_name = file_name diff --git a/traitsui/examples/demo/Standard_Editors/File_Dialog/File_Open_with_TextInfo_Extension.py b/traitsui/examples/demo/Standard_Editors/File_Dialog/File_Open_with_TextInfo_Extension.py index d590226c9..ec8975e24 100644 --- a/traitsui/examples/demo/Standard_Editors/File_Dialog/File_Open_with_TextInfo_Extension.py +++ b/traitsui/examples/demo/Standard_Editors/File_Dialog/File_Open_with_TextInfo_Extension.py @@ -59,19 +59,18 @@ class FileDialogDemo(HasTraits): HGroup( Item('open', show_label=False), '_', - Item('file_name', style='readonly', springy=True) + Item('file_name', style='readonly', springy=True), ), - width=0.5 + width=0.5, ) # -- Traits Event Handlers ------------------------------------------------ def _open_changed(self): - """ Handles the user clicking the 'Open...' button. - """ - file_name = open_file(extensions=TextInfo(), - filter='Python file (*.py)|*.py', - id=demo_id) + """Handles the user clicking the 'Open...' button.""" + file_name = open_file( + extensions=TextInfo(), filter='Python file (*.py)|*.py', id=demo_id + ) if file_name != '': self.file_name = file_name diff --git a/traitsui/examples/demo/Standard_Editors/FontEditor_demo.py b/traitsui/examples/demo/Standard_Editors/FontEditor_demo.py index b10e7f55c..7eef31485 100644 --- a/traitsui/examples/demo/Standard_Editors/FontEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/FontEditor_demo.py @@ -36,7 +36,7 @@ class FontEditorDemo(HasTraits): - """ Defines the main FontEditor demo class. """ + """Defines the main FontEditor demo class.""" # Define a Font trait to view: my_font_trait = Font() @@ -49,15 +49,12 @@ class FontEditorDemo(HasTraits): Item('_'), Item('my_font_trait', style='text', label='Text'), Item('_'), - Item('my_font_trait', style='readonly', label='ReadOnly') + Item('my_font_trait', style='readonly', label='ReadOnly'), ) # Demo view: traits_view = View( - font_group, - title='FontEditor', - buttons=['OK'], - resizable=True + font_group, title='FontEditor', buttons=['OK'], resizable=True ) diff --git a/traitsui/examples/demo/Standard_Editors/HTMLEditor_demo.py b/traitsui/examples/demo/Standard_Editors/HTMLEditor_demo.py index ad0a1575f..8e149c5f7 100644 --- a/traitsui/examples/demo/Standard_Editors/HTMLEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/HTMLEditor_demo.py @@ -37,12 +37,13 @@ # Sample text to display as HTML: header, plus module docstring, plus # some lists. The docstring and lists will be auto-formatted # (format_text=True). -sample_text = (""" +sample_text = ( + """

    HTMLEditor example

    -""" + - __doc__ + - """ +""" + + __doc__ + + """ Here are some lists formatted in this way: Numbered list: @@ -54,11 +55,12 @@ - eat - drink - be merry -""") +""" +) class HTMLEditorDemo(HasTraits): - """ Defines the main HTMLEditor demo class. """ + """Defines the main HTMLEditor demo class.""" # Define a HTML trait to view my_html_trait = HTML(sample_text) @@ -68,13 +70,13 @@ class HTMLEditorDemo(HasTraits): UItem( 'my_html_trait', # we specify the editor explicitly in order to set format_text: - editor=HTMLEditor(format_text=True) + editor=HTMLEditor(format_text=True), ), title='HTMLEditor', buttons=['OK'], width=800, height=600, - resizable=True + resizable=True, ) diff --git a/traitsui/examples/demo/Standard_Editors/ImageEnumEditor_demo.py b/traitsui/examples/demo/Standard_Editors/ImageEnumEditor_demo.py index f6dd495c1..bb10915b4 100644 --- a/traitsui/examples/demo/Standard_Editors/ImageEnumEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/ImageEnumEditor_demo.py @@ -39,16 +39,15 @@ class Dummy(HasTraits): - """ Dummy class for ImageEnumEditor - """ + """Dummy class for ImageEnumEditor""" + x = Str() traits_view = View() class ImageEnumEditorDemo(HasTraits): - """ Defines the ImageEnumEditor demo class. - """ + """Defines the ImageEnumEditor demo class.""" # Define a trait to view: image_from_list = Enum( @@ -58,8 +57,8 @@ class ImageEnumEditorDemo(HasTraits): prefix='@icons:', suffix='_origin', cols=4, - klass=Dummy - ) + klass=Dummy, + ), ) # Items are used to define the demo display, one Item per editor style: @@ -70,15 +69,12 @@ class ImageEnumEditorDemo(HasTraits): Item('_'), Item('image_from_list', style='readonly', label='ReadOnly'), Item('_'), - Item('image_from_list', style='custom', label='Custom') + Item('image_from_list', style='custom', label='Custom'), ) # Demo view: traits_view = View( - img_group, - title='ImageEnumEditor', - buttons=['OK'], - resizable=True + img_group, title='ImageEnumEditor', buttons=['OK'], resizable=True ) diff --git a/traitsui/examples/demo/Standard_Editors/InstanceEditor_demo.py b/traitsui/examples/demo/Standard_Editors/InstanceEditor_demo.py index d5c59065e..214712590 100644 --- a/traitsui/examples/demo/Standard_Editors/InstanceEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/InstanceEditor_demo.py @@ -39,9 +39,9 @@ # Classes: # ------------------------------------------------------------------------- + class SampleClass(HasTraits): - """ This Sample class is used to demonstrate the InstanceEditor demo. - """ + """This Sample class is used to demonstrate the InstanceEditor demo.""" # The actual attributes don't matter here; we just need an assortment # to demonstrate the InstanceEditor's capabilities.: @@ -57,8 +57,7 @@ class SampleClass(HasTraits): class InstanceEditorDemo(HasTraits): - """ This class specifies the details of the InstanceEditor demo. - """ + """This class specifies the details of the InstanceEditor demo.""" # Create an Instance trait to view: sample_instance = Instance(SampleClass, ()) @@ -71,15 +70,12 @@ class InstanceEditorDemo(HasTraits): Item('_'), Item('sample_instance', style='text', label='Text'), Item('_'), - Item('sample_instance', style='readonly', label='ReadOnly') + Item('sample_instance', style='readonly', label='ReadOnly'), ) # Demo View: traits_view = View( - inst_group, - title='InstanceEditor', - buttons=['OK'], - resizable=True + inst_group, title='InstanceEditor', buttons=['OK'], resizable=True ) diff --git a/traitsui/examples/demo/Standard_Editors/ListEditor_demo.py b/traitsui/examples/demo/Standard_Editors/ListEditor_demo.py index 16dbbf106..d1628ac94 100644 --- a/traitsui/examples/demo/Standard_Editors/ListEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/ListEditor_demo.py @@ -25,7 +25,7 @@ # Define the demo class: class ListEditorDemo(HasTraits): - """ Defines the main ListEditor demo class. """ + """Defines the main ListEditor demo class.""" # Define a List trait to display: play_list = List(Str, ["The Merchant of Venice", "Hamlet", "MacBeth"]) @@ -40,7 +40,7 @@ class ListEditorDemo(HasTraits): Item('_'), Item('play_list', style='text', label='Text', id='text'), Item('_'), - Item('play_list', style='readonly', label='ReadOnly', id='readonly') + Item('play_list', style='readonly', label='ReadOnly', id='readonly'), ) # Demo view: @@ -50,7 +50,7 @@ class ListEditorDemo(HasTraits): buttons=['OK'], height=600, width=400, - resizable=True + resizable=True, ) diff --git a/traitsui/examples/demo/Standard_Editors/RGBColorEditor_demo.py b/traitsui/examples/demo/Standard_Editors/RGBColorEditor_demo.py index b0ef8a562..5c0987237 100644 --- a/traitsui/examples/demo/Standard_Editors/RGBColorEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/RGBColorEditor_demo.py @@ -34,7 +34,7 @@ # Demo class definition: class RGBColorEditorDemo(HasTraits): - """ Defines the main RGBColorEditor demo. """ + """Defines the main RGBColorEditor demo.""" # Define a Color trait to view: color_trait = RGBColor() @@ -47,15 +47,12 @@ class RGBColorEditorDemo(HasTraits): Item('_'), Item('color_trait', style='text', label='Text'), Item('_'), - Item('color_trait', style='readonly', label='ReadOnly') + Item('color_trait', style='readonly', label='ReadOnly'), ) # Demo view traits_view = View( - color_group, - title='RGBColorEditor', - buttons=['OK'], - resizable=True + color_group, title='RGBColorEditor', buttons=['OK'], resizable=True ) diff --git a/traitsui/examples/demo/Standard_Editors/RangeEditor_demo.py b/traitsui/examples/demo/Standard_Editors/RangeEditor_demo.py index 0c5097de4..59b9cd778 100644 --- a/traitsui/examples/demo/Standard_Editors/RangeEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/RangeEditor_demo.py @@ -33,8 +33,7 @@ class RangeEditorDemo(HasTraits): - """ Defines the RangeEditor demo class. - """ + """Defines the RangeEditor demo class.""" # Define a trait for each of four range variants: small_int_range = Range(1, 16) @@ -48,14 +47,14 @@ class RangeEditorDemo(HasTraits): 'small_int_range', style='simple', label='Simple', - id='simple_small' + id='simple_small', ), Item('_'), Item( 'small_int_range', style='custom', label='Custom', - id='custom_small' + id='custom_small', ), Item('_'), Item('small_int_range', style='text', label='Text', id='text_small'), @@ -64,9 +63,9 @@ class RangeEditorDemo(HasTraits): 'small_int_range', style='readonly', label='ReadOnly', - id='readonly_small' + id='readonly_small', ), - label='Small Int' + label='Small Int', ) # RangeEditor display for medium-width integer Range traits (17 to 100): @@ -75,14 +74,14 @@ class RangeEditorDemo(HasTraits): 'medium_int_range', style='simple', label='Simple', - id='simple_medium' + id='simple_medium', ), Item('_'), Item( 'medium_int_range', style='custom', label='Custom', - id='custom_medium' + id='custom_medium', ), Item('_'), Item('medium_int_range', style='text', label='Text', id='text_medium'), @@ -91,9 +90,9 @@ class RangeEditorDemo(HasTraits): 'medium_int_range', style='readonly', label='ReadOnly', - id='readonly_medium' + id='readonly_medium', ), - label='Medium Int' + label='Medium Int', ) # RangeEditor display for wide integer Range traits (> 100): @@ -102,14 +101,14 @@ class RangeEditorDemo(HasTraits): 'large_int_range', style='simple', label='Simple', - id='simple_large' + id='simple_large', ), Item('_'), Item( 'large_int_range', style='custom', label='Custom', - id='custom_large' + id='custom_large', ), Item('_'), Item('large_int_range', style='text', label='Text', id='text_large'), @@ -118,9 +117,9 @@ class RangeEditorDemo(HasTraits): 'large_int_range', style='readonly', label='ReadOnly', - id='readonly_large' + id='readonly_large', ), - label='Large Int' + label='Large Int', ) # RangeEditor display for float Range traits: @@ -135,9 +134,9 @@ class RangeEditorDemo(HasTraits): 'float_range', style='readonly', label='ReadOnly', - id='readonly_float' + id='readonly_float', ), - label='Float' + label='Float', ) # The view includes one group per data type. These will be displayed @@ -149,7 +148,7 @@ class RangeEditorDemo(HasTraits): float_range_group, title='RangeEditor', buttons=['OK'], - resizable=True + resizable=True, ) diff --git a/traitsui/examples/demo/Standard_Editors/SetEditor_demo.py b/traitsui/examples/demo/Standard_Editors/SetEditor_demo.py index 7b4c7c482..6ff2337f2 100644 --- a/traitsui/examples/demo/Standard_Editors/SetEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/SetEditor_demo.py @@ -30,8 +30,7 @@ # Define the main demo class: class SetEditorDemo(HasTraits): - """ Defines the SetEditor demo class. - """ + """Defines the SetEditor demo class.""" # Define a trait each for four SetEditor variants: unord_nma_set = List( @@ -39,7 +38,7 @@ class SetEditorDemo(HasTraits): values=['kumquats', 'pomegranates', 'kiwi'], left_column_title='Available Fruit', right_column_title='Exotic Fruit Bowl', - can_move_all=False + can_move_all=False, ) ) @@ -47,7 +46,7 @@ class SetEditorDemo(HasTraits): editor=SetEditor( values=['kumquats', 'pomegranates', 'kiwi'], left_column_title='Available Fruit', - right_column_title='Exotic Fruit Bowl' + right_column_title='Exotic Fruit Bowl', ) ) @@ -57,7 +56,7 @@ class SetEditorDemo(HasTraits): left_column_title='Available Fruit', right_column_title='Fruit Bowl', ordered=True, - can_move_all=False + can_move_all=False, ) ) @@ -66,7 +65,7 @@ class SetEditorDemo(HasTraits): values=['apples', 'berries', 'cantaloupe'], left_column_title='Available Fruit', right_column_title='Fruit Bowl', - ordered=True + ordered=True, ) ) @@ -74,28 +73,24 @@ class SetEditorDemo(HasTraits): no_nma_group = Group( Item('unord_nma_set', style='simple'), label='Unord I', - show_labels=False + show_labels=False, ) # SetEditor display, unordered, move-all buttons: no_ma_group = Group( Item('unord_ma_set', style='simple'), label='Unord II', - show_labels=False + show_labels=False, ) # SetEditor display, ordered, no move-all buttons: o_nma_group = Group( - Item('ord_nma_set', style='simple'), - label='Ord I', - show_labels=False + Item('ord_nma_set', style='simple'), label='Ord I', show_labels=False ) # SetEditor display, ordered, move-all buttons: o_ma_group = Group( - Item('ord_ma_set', style='simple'), - label='Ord II', - show_labels=False + Item('ord_ma_set', style='simple'), label='Ord II', show_labels=False ) # The view includes one group per data type. These will be displayed @@ -106,7 +101,7 @@ class SetEditorDemo(HasTraits): o_nma_group, o_ma_group, title='SetEditor', - buttons=['OK'] + buttons=['OK'], ) diff --git a/traitsui/examples/demo/Standard_Editors/TableEditor_demo.py b/traitsui/examples/demo/Standard_Editors/TableEditor_demo.py index 5ecb34730..21afaf2f1 100644 --- a/traitsui/examples/demo/Standard_Editors/TableEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/TableEditor_demo.py @@ -31,11 +31,18 @@ from traits.api import HasTraits, HasStrictTraits, Str, Int, Regex, List from traitsui.api import ( - View, Group, Item, TableEditor, ObjectColumn, ExpressionColumn, - EvalTableFilter + View, + Group, + Item, + TableEditor, + ObjectColumn, + ExpressionColumn, + EvalTableFilter, ) from traitsui.table_filter import ( - EvalFilterTemplate, MenuFilterTemplate, RuleFilterTemplate + EvalFilterTemplate, + MenuFilterTemplate, + RuleFilterTemplate, ) @@ -47,10 +54,13 @@ class Employee(HasTraits): phone = Regex(value='000-0000', regex=r'\d\d\d[-]\d\d\d\d') traits_view = View( - 'first_name', 'last_name', 'age', 'phone', + 'first_name', + 'last_name', + 'age', + 'phone', title='Create new employee', width=0.18, - buttons=['OK', 'Cancel'] + buttons=['OK', 'Cancel'], ) @@ -63,11 +73,10 @@ class Employee(HasTraits): ExpressionColumn( label='Full Name', width=0.30, - expression="'%s %s' % (object.first_name, " - "object.last_name )" + expression="'%s %s' % (object.first_name, " "object.last_name )", ), ObjectColumn(name='age', width=0.10, horizontal_alignment='center'), - ObjectColumn(name='phone', width=0.20) + ObjectColumn(name='phone', width=0.20), ], deletable=True, sort_model=True, @@ -75,7 +84,7 @@ class Employee(HasTraits): orientation='vertical', edit_view=View( Group('first_name', 'last_name', 'age', 'phone', show_border=True), - resizable=True + resizable=True, ), filters=[EvalFilterTemplate, MenuFilterTemplate, RuleFilterTemplate], search=EvalTableFilter(), @@ -91,34 +100,27 @@ class Department(HasStrictTraits): traits_view = View( Group( - Item( - 'employees', - show_label=False, - editor=table_editor - ), + Item('employees', show_label=False, editor=table_editor), show_border=True, ), title='Department Personnel', - width=.4, - height=.4, + width=0.4, + height=0.4, resizable=True, buttons=['OK'], - kind='live' + kind='live', ) # Create some employees: employees = [ - Employee(first_name='Jason', last_name='Smith', - age=32, phone='555-1111'), - Employee(first_name='Mike', last_name='Tollan', - age=34, phone='555-2222'), - Employee(first_name='Dave', last_name='Richards', - age=42, phone='555-3333'), - Employee(first_name='Lyn', last_name='Spitz', - age=40, phone='555-4444'), - Employee(first_name='Greg', last_name='Andrews', - age=45, phone='555-5555') + Employee(first_name='Jason', last_name='Smith', age=32, phone='555-1111'), + Employee(first_name='Mike', last_name='Tollan', age=34, phone='555-2222'), + Employee( + first_name='Dave', last_name='Richards', age=42, phone='555-3333' + ), + Employee(first_name='Lyn', last_name='Spitz', age=40, phone='555-4444'), + Employee(first_name='Greg', last_name='Andrews', age=45, phone='555-5555'), ] # Create the demo: diff --git a/traitsui/examples/demo/Standard_Editors/TextEditor_demo.py b/traitsui/examples/demo/Standard_Editors/TextEditor_demo.py index b5fc6b9ce..c5098f094 100644 --- a/traitsui/examples/demo/Standard_Editors/TextEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/TextEditor_demo.py @@ -33,8 +33,7 @@ # The main demo class: class TextEditorDemo(HasTraits): - """ Defines the TextEditor demo class. - """ + """Defines the TextEditor demo class.""" # Define a trait for each of three TextEditor variants: string_trait = Str("sample string") @@ -50,7 +49,7 @@ class TextEditorDemo(HasTraits): Item('string_trait', style='text', label='Text'), Item('_'), Item('string_trait', style='readonly', label='ReadOnly'), - label='String' + label='String', ) # TextEditor display without multi-line capability (for an integer): @@ -62,9 +61,12 @@ class TextEditorDemo(HasTraits): Item('int_trait', style='text', label='Text', id="text_int"), Item('_'), Item( - 'int_trait', style='readonly', label='ReadOnly', id="readonly_int", + 'int_trait', + style='readonly', + label='ReadOnly', + id="readonly_int", ), - label='Integer' + label='Integer', ) # TextEditor display with secret typing capability (for Password traits): @@ -76,7 +78,7 @@ class TextEditorDemo(HasTraits): Item('password', style='text', label='Text'), Item('_'), Item('password', style='readonly', label='ReadOnly'), - label='Password' + label='Password', ) # The view includes one group per data type. These will be displayed @@ -86,7 +88,7 @@ class TextEditorDemo(HasTraits): text_pass_group, text_int_group, title='TextEditor', - buttons=['OK'] + buttons=['OK'], ) diff --git a/traitsui/examples/demo/Standard_Editors/TitleEditor_demo.py b/traitsui/examples/demo/Standard_Editors/TitleEditor_demo.py index 032493fe6..d8bb11549 100644 --- a/traitsui/examples/demo/Standard_Editors/TitleEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/TitleEditor_demo.py @@ -43,7 +43,7 @@ class TitleEditorDemo(HasTraits): 'Select a new title from the drop down list below', 'This is the TitleEditor demonstration', 'Acme Widgets Sales for Each Quarter', - 'This is Not Intended to be a Real Application' + 'This is Not Intended to be a Real Application', ) # A user settable version of the title: @@ -60,39 +60,42 @@ class TitleEditorDemo(HasTraits): VGroup( VGroup( HGroup( - Item('title', - show_label=False, - springy=True, - editor=TitleEditor() - ) + Item( + 'title', + show_label=False, + springy=True, + editor=TitleEditor(), + ) ), Item('title'), - show_border=True + show_border=True, ), VGroup( HGroup( - Item('title_2', - show_label=False, - springy=True, - editor=TitleEditor() - ) + Item( + 'title_2', + show_label=False, + springy=True, + editor=TitleEditor(), + ) ), Item('title_2', label='Title'), - show_border=True + show_border=True, ), VGroup( HGroup( - Item('title_3', - show_label=False, - springy=True, - editor=TitleEditor() - ) + Item( + 'title_3', + show_label=False, + springy=True, + editor=TitleEditor(), + ) ), Item('value'), - show_border=True - ) + show_border=True, + ), ), - width=0.4 + width=0.4, ) # -- Property Implementations --------------------------------------------- @@ -100,16 +103,12 @@ class TitleEditorDemo(HasTraits): @cached_property def _get_title_3(self): if self.value >= 0: - return ( - 'The square root of {} is {}'.format( - self.value, self.value ** 0.5 - ) + return 'The square root of {} is {}'.format( + self.value, self.value ** 0.5 ) else: - return ( - 'The square root of {} is {}i'.format( - self.value, (-self.value) ** 0.5 - ) + return 'The square root of {} is {}i'.format( + self.value, (-self.value) ** 0.5 ) diff --git a/traitsui/examples/demo/Standard_Editors/TreeEditor_demo.py b/traitsui/examples/demo/Standard_Editors/TreeEditor_demo.py index 9113aa6f7..118e9d5ae 100644 --- a/traitsui/examples/demo/Standard_Editors/TreeEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/TreeEditor_demo.py @@ -52,7 +52,7 @@ class Employee(HasTraits): - """ Defines a company employee. """ + """Defines a company employee.""" name = Str('') title = Str() @@ -63,14 +63,14 @@ def default_title(self): class Department(HasTraits): - """ Defines a department with employees. """ + """Defines a department with employees.""" name = Str('') employees = List(Employee) class Company(HasTraits): - """ Defines a company with departments and employees. """ + """Defines a company with departments and employees.""" name = Str('') departments = List(Department) @@ -90,7 +90,7 @@ class Company(HasTraits): # child nodes are children='', label='name', # label with Company name - view=View(['name']) + view=View(['name']), ), TreeNode( node_for=[Company], @@ -99,35 +99,35 @@ class Company(HasTraits): label='=Departments', # constant label view=no_view, add=[Department], - ), + ), TreeNode( node_for=[Company], auto_open=True, children='employees', - label='=Employees', # constant label + label='=Employees', # constant label view=no_view, - add=[Employee] + add=[Employee], ), TreeNode( node_for=[Department], auto_open=True, children='employees', - label='name', # label with Department name + label='name', # label with Department name view=View(['name']), - add=[Employee] + add=[Employee], ), TreeNode( node_for=[Employee], auto_open=True, - label='name', # label with Employee name - view=View(['name', 'title', 'phone']) - ) + label='name', # label with Employee name + view=View(['name', 'title', 'phone']), + ), ] ) class Partner(HasTraits): - """ Defines a business partner.""" + """Defines a business partner.""" name = Str('') company = Instance(Company) @@ -138,8 +138,8 @@ class Partner(HasTraits): buttons=['OK'], resizable=True, style='custom', - width=.3, - height=500 + width=0.3, + height=500, ) @@ -157,16 +157,10 @@ class Partner(HasTraits): name='Enthought', employees=[dave, martin, duncan, jason, mike], departments=[ - Department( - name='Business', - employees=[jason, mike] - ), - Department( - name='Scientific', - employees=[dave, martin, duncan] - ) - ] - ) + Department(name='Business', employees=[jason, mike]), + Department(name='Scientific', employees=[dave, martin, duncan]), + ], + ), ) # Run the demo (if invoked from the command line): diff --git a/traitsui/examples/demo/Standard_Editors/TupleEditor_demo.py b/traitsui/examples/demo/Standard_Editors/TupleEditor_demo.py index de731d80c..d0bbd2be1 100644 --- a/traitsui/examples/demo/Standard_Editors/TupleEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/TupleEditor_demo.py @@ -34,8 +34,7 @@ # The main demo class: class TupleEditorDemo(HasTraits): - """ Defines the TupleEditor demo class. - """ + """Defines the TupleEditor demo class.""" # Define a trait to view: tuple = Tuple(Color, Range(1, 4), Str) @@ -48,15 +47,12 @@ class TupleEditorDemo(HasTraits): Item('_'), Item('tuple', style='text', label='Text'), Item('_'), - Item('tuple', style='readonly', label='ReadOnly') + Item('tuple', style='readonly', label='ReadOnly'), ) # Demo view traits_view = View( - tuple_group, - title='TupleEditor', - buttons=['OK'], - resizable=True + tuple_group, title='TupleEditor', buttons=['OK'], resizable=True ) diff --git a/traitsui/examples/demo/Standard_Editors/VideoEditor_demo.py b/traitsui/examples/demo/Standard_Editors/VideoEditor_demo.py index ad7c06161..fd6862a32 100644 --- a/traitsui/examples/demo/Standard_Editors/VideoEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/VideoEditor_demo.py @@ -19,20 +19,28 @@ from PIL import Image from pyface.qt.QtGui import QImage from traits.api import ( - Bool, Button, Callable, Float, HasTraits, Range, Str, observe + Bool, + Button, + Callable, + Float, + HasTraits, + Range, + Str, + observe, ) from traitsui.api import ButtonEditor, ContextValue, HGroup, Item, UItem, View from traitsui.editors.video_editor import MediaStatus, PlayerState, VideoEditor def QImage_from_np(image): - assert (np.max(image) <= 255) + assert np.max(image) <= 255 image8 = image.astype(np.uint8, order='C', casting='unsafe') height, width, colors = image8.shape bytesPerLine = 4 * width - image = QImage(image8.data, width, height, bytesPerLine, - QImage.Format_RGB32) + image = QImage( + image8.data, width, height, bytesPerLine, QImage.Format_RGB32 + ) return image @@ -40,9 +48,11 @@ def np_from_QImage(qimage): # Creates a numpy array from a pyqt(5) QImage object width, height = qimage.width(), qimage.height() channels = qimage.pixelFormat().channelCount() - return np.array( - qimage.bits().asarray(width * height * channels) - ).reshape(height, width, channels).astype('u1') + return ( + np.array(qimage.bits().asarray(width * height * channels)) + .reshape(height, width, channels) + .astype('u1') + ) def qimage_function(antialiasing=True): @@ -51,6 +61,7 @@ def antialias_func(image_func): Turns an image function into a QImage function, bound within the viewing frames box. """ + def qimage_conv_func(image, box_dims): _np_image = image_func(np_from_QImage(image)) pil_image = Image.fromarray(_np_image) @@ -61,7 +72,9 @@ def qimage_conv_func(image, box_dims): _np_image = np.array(pil_image) image = QImage_from_np(_np_image) return image, _np_image + return qimage_conv_func + return antialias_func diff --git a/traitsui/examples/demo/Standard_Editors/tests/test_BooleanEditor_demo.py b/traitsui/examples/demo/Standard_Editors/tests/test_BooleanEditor_demo.py index 6a8e62510..adc65f08a 100644 --- a/traitsui/examples/demo/Standard_Editors/tests/test_BooleanEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/tests/test_BooleanEditor_demo.py @@ -21,7 +21,11 @@ import unittest from traitsui.testing.api import ( - DisplayedText, KeyClick, KeySequence, MouseClick, UITester + DisplayedText, + KeyClick, + KeySequence, + MouseClick, + UITester, ) #: Filename of the demo script @@ -32,7 +36,6 @@ class TestBooleanEditorDemo(unittest.TestCase): - def test_boolean_editor_demo(self): demo = runpy.run_path(DEMO_PATH)["demo"] diff --git a/traitsui/examples/demo/Standard_Editors/tests/test_BooleanEditor_simple_demo.py b/traitsui/examples/demo/Standard_Editors/tests/test_BooleanEditor_simple_demo.py index be35bc837..ff3eb986b 100644 --- a/traitsui/examples/demo/Standard_Editors/tests/test_BooleanEditor_simple_demo.py +++ b/traitsui/examples/demo/Standard_Editors/tests/test_BooleanEditor_simple_demo.py @@ -21,7 +21,12 @@ import unittest from traitsui.testing.api import ( - DisplayedText, IsChecked, KeyClick, KeySequence, MouseClick, UITester + DisplayedText, + IsChecked, + KeyClick, + KeySequence, + MouseClick, + UITester, ) #: Filename of the demo script @@ -32,7 +37,6 @@ class TestBooleanEditorSimpleDemo(unittest.TestCase): - def test_boolean_editor_simple_demo(self): demo = runpy.run_path(DEMO_PATH)["demo"] diff --git a/traitsui/examples/demo/Standard_Editors/tests/test_ButtonEditor_demo.py b/traitsui/examples/demo/Standard_Editors/tests/test_ButtonEditor_demo.py index 59883dbad..2d8f655da 100644 --- a/traitsui/examples/demo/Standard_Editors/tests/test_ButtonEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/tests/test_ButtonEditor_demo.py @@ -41,7 +41,6 @@ @unittest.skipIf(no_modal_dialog_tester, "ModalDialogTester unavailable") class TestButtonEditorDemo(unittest.TestCase): - def test_button_editor_demo(self): demo = runpy.run_path(DEMO_PATH)["demo"] diff --git a/traitsui/examples/demo/Standard_Editors/tests/test_ButtonEditor_simple_demo.py b/traitsui/examples/demo/Standard_Editors/tests/test_ButtonEditor_simple_demo.py index 8314c7695..a4b089653 100644 --- a/traitsui/examples/demo/Standard_Editors/tests/test_ButtonEditor_simple_demo.py +++ b/traitsui/examples/demo/Standard_Editors/tests/test_ButtonEditor_simple_demo.py @@ -30,7 +30,6 @@ class TestButtonEditorSimpleDemo(unittest.TestCase): - def test_button_editor_simple_demo(self): demo = runpy.run_path(DEMO_PATH)["demo"] diff --git a/traitsui/examples/demo/Standard_Editors/tests/test_CheckListEditor_simple_demo.py b/traitsui/examples/demo/Standard_Editors/tests/test_CheckListEditor_simple_demo.py index afe2d9458..53fb9d005 100644 --- a/traitsui/examples/demo/Standard_Editors/tests/test_CheckListEditor_simple_demo.py +++ b/traitsui/examples/demo/Standard_Editors/tests/test_CheckListEditor_simple_demo.py @@ -30,7 +30,6 @@ class TestCheckListEditorSimpleDemo(unittest.TestCase): - def test_checklist_editor_simple_demo(self): demo = runpy.run_path(DEMO_PATH)["demo"] diff --git a/traitsui/examples/demo/Standard_Editors/tests/test_EnumEditor_demo.py b/traitsui/examples/demo/Standard_Editors/tests/test_EnumEditor_demo.py index cc18919da..2ce4e7af1 100644 --- a/traitsui/examples/demo/Standard_Editors/tests/test_EnumEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/tests/test_EnumEditor_demo.py @@ -27,7 +27,7 @@ KeySequence, MouseClick, SelectedText, - UITester + UITester, ) #: Filename of the demo script @@ -38,7 +38,6 @@ class TestEnumEditorDemo(unittest.TestCase): - def test_enum_editor_demo(self): demo = runpy.run_path(DEMO_PATH)["demo"] @@ -83,8 +82,12 @@ def test_enum_editor_demo(self): displayed_readonly = readonly.inspect(DisplayedText()) displayed_selected = [ - displayed_simple, disp_simple_text, selected_radio, - selected_list, displayed_text, displayed_readonly + displayed_simple, + disp_simple_text, + selected_radio, + selected_list, + displayed_text, + displayed_readonly, ] for text in displayed_selected: self.assertEqual(text, 'Foo') diff --git a/traitsui/examples/demo/Standard_Editors/tests/test_FileEditor_demo.py b/traitsui/examples/demo/Standard_Editors/tests/test_FileEditor_demo.py index d7a68f769..5bcd62c16 100644 --- a/traitsui/examples/demo/Standard_Editors/tests/test_FileEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/tests/test_FileEditor_demo.py @@ -20,9 +20,7 @@ import runpy import unittest -from traitsui.testing.api import ( - DisplayedText, KeyClick, KeySequence, UITester -) +from traitsui.testing.api import DisplayedText, KeyClick, KeySequence, UITester #: Filename of the demo script FILENAME = "FileEditor_demo.py" @@ -32,7 +30,6 @@ class TestFileEditorDemo(unittest.TestCase): - def test_run_demo(self): demo = runpy.run_path(DEMO_PATH)["demo"] diff --git a/traitsui/examples/demo/Standard_Editors/tests/test_InstanceEditor_demo.py b/traitsui/examples/demo/Standard_Editors/tests/test_InstanceEditor_demo.py index be55f0c10..01f1810b7 100644 --- a/traitsui/examples/demo/Standard_Editors/tests/test_InstanceEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/tests/test_InstanceEditor_demo.py @@ -21,7 +21,11 @@ import unittest from traitsui.testing.api import ( - DisplayedText, KeyClick, KeySequence, MouseClick, UITester + DisplayedText, + KeyClick, + KeySequence, + MouseClick, + UITester, ) #: Filename of the demo script @@ -32,7 +36,6 @@ class TestInstanceEditorDemo(unittest.TestCase): - def test_instance_editor_demo(self): demo = runpy.run_path(DEMO_PATH)["demo"] diff --git a/traitsui/examples/demo/Standard_Editors/tests/test_ListEditor_demo.py b/traitsui/examples/demo/Standard_Editors/tests/test_ListEditor_demo.py index 198685043..e8636277a 100644 --- a/traitsui/examples/demo/Standard_Editors/tests/test_ListEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/tests/test_ListEditor_demo.py @@ -29,7 +29,6 @@ class TestListEditorDemo(unittest.TestCase): - def test_list_editor_demo(self): demo = runpy.run_path(DEMO_PATH)["demo"] @@ -43,7 +42,7 @@ def test_list_editor_demo(self): item1.perform(KeyClick("Enter")) self.assertEqual( demo.play_list, - ["The Merchant of Venice", "Othello", "MacBeth"] + ["The Merchant of Venice", "Othello", "MacBeth"], ) diff --git a/traitsui/examples/demo/Standard_Editors/tests/test_RangeEditor_demo.py b/traitsui/examples/demo/Standard_Editors/tests/test_RangeEditor_demo.py index eb18e6712..ebf90266d 100644 --- a/traitsui/examples/demo/Standard_Editors/tests/test_RangeEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/tests/test_RangeEditor_demo.py @@ -28,7 +28,7 @@ MouseClick, Slider, Textbox, - UITester + UITester, ) #: Filename of the demo script @@ -39,7 +39,6 @@ class TestRangeEditorDemo(unittest.TestCase): - def test_run_demo(self): demo = runpy.run_path(DEMO_PATH)["demo"] diff --git a/traitsui/examples/demo/Standard_Editors/tests/test_TextEditor_demo.py b/traitsui/examples/demo/Standard_Editors/tests/test_TextEditor_demo.py index 1643af6ec..349b81323 100644 --- a/traitsui/examples/demo/Standard_Editors/tests/test_TextEditor_demo.py +++ b/traitsui/examples/demo/Standard_Editors/tests/test_TextEditor_demo.py @@ -20,9 +20,7 @@ import runpy import unittest -from traitsui.testing.api import ( - DisplayedText, KeyClick, KeySequence, UITester -) +from traitsui.testing.api import DisplayedText, KeyClick, KeySequence, UITester #: Filename of the demo script FILENAME = "TextEditor_demo.py" @@ -32,7 +30,6 @@ class TestTextEditorDemo(unittest.TestCase): - def test_run_demo(self): demo = runpy.run_path(DEMO_PATH)["demo"] diff --git a/traitsui/extras/_demo_info.py b/traitsui/extras/_demo_info.py index 5456fd932..7cd07c421 100644 --- a/traitsui/extras/_demo_info.py +++ b/traitsui/extras/_demo_info.py @@ -16,7 +16,7 @@ def info(request): - """ Return a configuration for contributing demo examples to the + """Return a configuration for contributing demo examples to the Demo application. Parameters diff --git a/traitsui/extras/_demo_legacy.py b/traitsui/extras/_demo_legacy.py index f88d5b5d5..921e377e7 100644 --- a/traitsui/extras/_demo_legacy.py +++ b/traitsui/extras/_demo_legacy.py @@ -141,8 +141,8 @@ def extract_docstring_from_source(source): source_lines = source.splitlines() # Extract module docstring lines and recombine - docstring = eval("\n".join(source_lines[tstart[0] - 1: tend[0]])) - source_lines = source_lines[: tstart[0] - 1] + source_lines[tend[0]:] + docstring = eval("\n".join(source_lines[tstart[0] - 1 : tend[0]])) + source_lines = source_lines[: tstart[0] - 1] + source_lines[tend[0] :] source = "\n".join(source_lines) source = source.strip() @@ -172,8 +172,7 @@ def parse_source(file_name): def _read_file(path, mode='r', encoding='utf8'): - """ Returns the contents of a specified text file. - """ + """Returns the contents of a specified text file.""" with open(path, mode, encoding=encoding) as fh: result = fh.read() return result @@ -183,6 +182,7 @@ def _read_file(path, mode='r', encoding='utf8'): # 'DemoFileHandler' class: # ------------------------------------------------------------------------- + @contextlib.contextmanager def _set_stdout(std_out): stdout, stderr = sys.stdout, sys.stderr @@ -219,8 +219,7 @@ def init(self, info): return True def closed(self, info, is_ok): - """ Closes the view. - """ + """Closes the view.""" demo_file = info.object if hasattr(demo_file, 'demo'): demo_file.demo = None @@ -322,8 +321,7 @@ class DemoTreeNodeObject(TreeNodeObject): # ------------------------------------------------------------------------- def tno_allows_children(self, node): - """ Returns whether chidren of this object are allowed or not. - """ + """Returns whether chidren of this object are allowed or not.""" return self.allows_children # ------------------------------------------------------------------------- @@ -331,8 +329,7 @@ def tno_allows_children(self, node): # ------------------------------------------------------------------------- def tno_has_children(self, node=None): - """ Returns whether or not the object has children. - """ + """Returns whether or not the object has children.""" if self._has_children is None: self._has_children = self.has_children() @@ -343,8 +340,7 @@ def tno_has_children(self, node=None): # ------------------------------------------------------------------------- def tno_get_children(self, node): - """ Gets the object's children. - """ + """Gets the object's children.""" if self._get_children is None: self._get_children = self.get_children() @@ -355,8 +351,7 @@ def tno_get_children(self, node): # ------------------------------------------------------------------------- def has_children(self, node): - """ Returns whether or not the object has children. - """ + """Returns whether or not the object has children.""" raise NotImplementedError # ------------------------------------------------------------------------- @@ -364,8 +359,7 @@ def has_children(self, node): # ------------------------------------------------------------------------- def get_children(self): - """ Gets the object's children. - """ + """Gets the object's children.""" raise NotImplementedError @@ -436,13 +430,11 @@ def _set_nice_name(self, value): # ------------------------------------------------------------------------- def has_children(self): - """ Returns whether or not the object has children. - """ + """Returns whether or not the object has children.""" return False def get_children(self): - """ Gets the demo file's children. - """ + """Gets the demo file's children.""" return [] @@ -465,8 +457,7 @@ def init(self): self.run_code() def run_code(self): - """ Runs the code associated with this demo file. - """ + """Runs the code associated with this demo file.""" try: # Get the execution context dictionary: locals = self.parent.init_dic @@ -523,7 +514,6 @@ def _get_object(self, name, dic): class DemoContentFile(DemoFileBase): - def init(self): super().init() file_str = _read_file(self.path) @@ -531,15 +521,13 @@ def init(self): class DemoImageFile(DemoFileBase): - def init(self): super().init() self.description = _image_template.format(self.css_filename, self.path) class DemoPath(DemoTreeNodeObject): - """ This class represents a directory. - """ + """This class represents a directory.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -603,7 +591,7 @@ def __file_factory_default(self): ".png": DemoImageFile, ".py": DemoFile, ".rst": DemoContentFile, - ".txt": DemoContentFile + ".txt": DemoContentFile, } # ------------------------------------------------------------------------- @@ -677,8 +665,7 @@ def _get_init_dic(self): # ------------------------------------------------------------------------- def has_children(self): - """ Returns whether or not the object has children. - """ + """Returns whether or not the object has children.""" path = self.path for name in listdir(path): cur_path = join(path, name) @@ -699,8 +686,7 @@ def has_children(self): # ------------------------------------------------------------------------- def get_children(self): - """ Gets the object's children. - """ + """Gets the object's children.""" if self.config_dict or self.config_filename: children = self.get_children_from_config() else: @@ -711,8 +697,7 @@ def get_children(self): # Gets the object's children based on the filesystem structure. # ------------------------------------------------------------------------- def get_children_from_datastructure(self): - """ Gets the object's children based on the filesystem structure. - """ + """Gets the object's children based on the filesystem structure.""" dirs = [] files = [] @@ -725,7 +710,7 @@ def get_children_from_datastructure(self): DemoPath( parent=self, name=name, - css_filename=join('..', self.css_filename) + css_filename=join('..', self.css_filename), ) ) elif self.use_files: @@ -796,7 +781,8 @@ def get_children_from_config(self): demoobj.nice_name = keyword demoobj.config_dict = config_dict demoobj.css_filename = os.path.join( - "..", self.css_filename) + "..", self.css_filename + ) dirs.append(demoobj) elif len(names) == 1: try: @@ -831,8 +817,7 @@ def has_py_files(self, path): return False def _handle_file(self, filename): - """ Process a file based on its extension. - """ + """Process a file based on its extension.""" _, ext = splitext(filename) file_factory = self._file_factory[ext] demo_file = file_factory(parent=self, name=filename) @@ -882,17 +867,16 @@ def _handle_file(self, filename): "log", style="readonly", editor=CodeEditor( - show_line_numbers=False, - selected_color=0xFFFFFF + show_line_numbers=False, selected_color=0xFFFFFF ), label="Output", - show_label=False + show_label=False, ), Item( "locals", editor=ShellEditor(share=True), label="Shell", - show_label=False + show_label=False, ), UItem( "demo", @@ -932,23 +916,18 @@ def _handle_file(self, filename): view=demo_path_view, ), ObjectTreeNode( - node_for=[DemoFile], - label="nice_name", - view=demo_file_view + node_for=[DemoFile], label="nice_name", view=demo_file_view ), ObjectTreeNode( node_for=[DemoContentFile], label="nice_name", - view=demo_content_view + view=demo_content_view, ), ObjectTreeNode( - node_for=[DemoImageFile], - label="nice_name", - view=demo_content_view + node_for=[DemoImageFile], label="nice_name", view=demo_content_view ), ], selected='selected_node', - ) @@ -974,7 +953,7 @@ def _handle_file(self, filename): tooltip="Go to next file", action="do_parent", enabled_when="(selected_node is not None) and " - "(object.selected_node.parent is not None)", + "(object.selected_node.parent is not None)", ) @@ -1079,7 +1058,7 @@ def default_traits_view(self): def _get_settings(css_path=None): - """ Helper function to make settings dictionary + """Helper function to make settings dictionary consumable by docutils Parameters @@ -1101,7 +1080,7 @@ def _get_settings(css_path=None): def publish_html_str(rst_str, css_path=None): - """ Format RST string to html using `docutils` if available. + """Format RST string to html using `docutils` if available. Otherwise, return the input `rst_str`. Parameters @@ -1122,13 +1101,13 @@ def publish_html_str(rst_str, css_path=None): return rst_str settings = _get_settings(css_path) - return publish_string(rst_str, - writer_name='html', - settings_overrides=settings) + return publish_string( + rst_str, writer_name='html', settings_overrides=settings + ) def publish_html_file(rst_file_path, html_out_path, css_path=None): - """ Format reStructuredText in `rst_file_path` to html using `docutils` + """Format reStructuredText in `rst_file_path` to html using `docutils` if available. Otherwise, does nothing. Parameters @@ -1150,10 +1129,12 @@ def publish_html_file(rst_file_path, html_out_path, css_path=None): return settings = _get_settings(css_path) - publish_file(source_path=rst_file_path, - destination_path=html_out_path, - writer_name='html', - settings_overrides=settings) + publish_file( + source_path=rst_file_path, + destination_path=html_out_path, + writer_name='html', + settings_overrides=settings, + ) # ------------------------------------------------------------------------- diff --git a/traitsui/extras/api.py b/traitsui/extras/api.py index 7b5e45016..615246c41 100644 --- a/traitsui/extras/api.py +++ b/traitsui/extras/api.py @@ -12,11 +12,12 @@ """ - from .checkbox_column import CheckboxColumn from .edit_column import EditColumn from .has_dynamic_views import ( - DynamicView, DynamicViewSubElement, HasDynamicViews + DynamicView, + DynamicViewSubElement, + HasDynamicViews, ) from .progress_column import ProgressColumn from .saving import CanSaveMixin, SaveHandler diff --git a/traitsui/extras/checkbox_column.py b/traitsui/extras/checkbox_column.py index b12f32474..50a2b0c0d 100644 --- a/traitsui/extras/checkbox_column.py +++ b/traitsui/extras/checkbox_column.py @@ -12,7 +12,6 @@ """ - from traits.etsconfig.api import ETSConfig from ..table_column import ObjectColumn @@ -27,24 +26,22 @@ class CheckboxColumn(ObjectColumn): def __init__(self, **traits): - """ Initializes the object. - """ + """Initializes the object.""" super().__init__(**traits) # force the renderer to be a checkbox renderer self.renderer = CheckboxRenderer() def get_cell_color(self, object): - """ Returns the cell background color for the column for a specified - object. + """Returns the cell background color for the column for a specified + object. """ # Override the parent class to ALWAYS provide the standard color: return self.cell_color_ def is_editable(self, object): - """ Returns whether the column is editable for a specified object. - """ + """Returns whether the column is editable for a specified object.""" # Although a checkbox column is always editable, we return this # to keep a standard editor from appearing. The editing is handled diff --git a/traitsui/extras/edit_column.py b/traitsui/extras/edit_column.py index 2efde7e2d..f7e6e8eaa 100644 --- a/traitsui/extras/edit_column.py +++ b/traitsui/extras/edit_column.py @@ -13,33 +13,29 @@ """ - from ..table_column import ObjectColumn class EditColumn(ObjectColumn): def __init__(self, **traits): - """ Initializes the object. - """ + """Initializes the object.""" super().__init__(**traits) from traitsui.toolkit import toolkit_object - EditRenderer = toolkit_object( - 'extra.edit_renderer:EditRenderer' - ) + + EditRenderer = toolkit_object('extra.edit_renderer:EditRenderer') self.renderer = EditRenderer() self.label = "" def get_cell_color(self, object): - """ Returns the cell background color for the column for a specified - object. + """Returns the cell background color for the column for a specified + object. """ # Override the parent class to ALWAYS provide the standard color: return self.cell_color_ def is_editable(self, object): - """ Returns whether the column is editable for a specified object. - """ + """Returns whether the column is editable for a specified object.""" return False diff --git a/traitsui/extras/has_dynamic_views.py b/traitsui/extras/has_dynamic_views.py index 21e874878..7c784a8b2 100644 --- a/traitsui/extras/has_dynamic_views.py +++ b/traitsui/extras/has_dynamic_views.py @@ -178,9 +178,9 @@ class HasDynamicViews(HasTraits): # -- Public Interface ------------------------------------------------------- def trait_view(self, name=None, view_element=None): - """ Gets or sets a ViewElement associated with an object's class. + """Gets or sets a ViewElement associated with an object's class. - Extended here to build dynamic views and sub-elements. + Extended here to build dynamic views and sub-elements. """ result = None @@ -219,17 +219,17 @@ def trait_view(self, name=None, view_element=None): # -- Public Interface ------------------------------------------------------- def declare_dynamic_view(self, declaration): - """ A convenience method to add a new dynamic view declaration to this - instance. + """A convenience method to add a new dynamic view declaration to this + instance. """ self._dynamic_view_registry[declaration.name] = declaration # -- Protected Interface ---------------------------------------------------- def _build_dynamic_sub_element(self, definition, sub_elements): - """ Returns the fully composed ViewSubElement from the sub-element - contributions to the dynamic sub-element identified by the - definition. + """Returns the fully composed ViewSubElement from the sub-element + contributions to the dynamic sub-element identified by the + definition. """ logger.debug( "\tBuilding dynamic sub-element [%s] with elements [%s]", @@ -240,11 +240,11 @@ def _build_dynamic_sub_element(self, definition, sub_elements): return definition.klass(*sub_elements, **definition.keywords) def _build_dynamic_view(self, declaration, sub_elements, handler): - """ Returns a Traits View representing the specified dynamic view - composed out of the provided view sub-elements. + """Returns a Traits View representing the specified dynamic view + composed out of the provided view sub-elements. - Implemented as a separate method to allow implementors to override - the way in which the instantiated view is configured. + Implemented as a separate method to allow implementors to override + the way in which the instantiated view is configured. """ logger.debug( "\tBuilding dynamic view [%s] with elements [%s]", @@ -262,12 +262,11 @@ def _build_dynamic_view(self, declaration, sub_elements, handler): # Build the view out of the sub-elements: *sub_elements, # Include the declaration's keywords. - **declaration.keywords + **declaration.keywords, ) def _compose_dynamic_sub_element(self, definition): - """ Returns a dynamic UI element composed from its contributed parts. - """ + """Returns a dynamic UI element composed from its contributed parts.""" logger.debug( "Composing dynamic sub-element named [%s] for [%s]", definition.name, @@ -281,8 +280,7 @@ def _compose_dynamic_sub_element(self, definition): return self._build_dynamic_sub_element(definition, elements) def _compose_dynamic_view(self, name): - """ Returns a dynamic view composed from its contributed parts. - """ + """Returns a dynamic view composed from its contributed parts.""" logger.debug("Composing dynamic view [%s] for [%s]", name, self) # Retrieve the declaration of this dynamic view: @@ -302,9 +300,9 @@ def _compose_dynamic_view(self, name): return self._build_dynamic_view(declaration, elements, handler) def _get_dynamic_elements(self, name): - """ Returns a list of the current elements meant to go into the - composition of a dynamic view or subelement with the specified - name. + """Returns a list of the current elements meant to go into the + composition of a dynamic view or subelement with the specified + name. """ # Determine the metadata names used to find the sub-elements included @@ -355,8 +353,8 @@ def _get_dynamic_elements(self, name): return elements def _get_dynamic_handlers(self, name, elements): - """ Return a list of the handlers associated with the current elements - meant to go into the dynamic view of the specified name. + """Return a list of the handlers associated with the current elements + meant to go into the dynamic view of the specified name. """ # Determine the metadata name used to declare a handler: diff --git a/traitsui/extras/progress_column.py b/traitsui/extras/progress_column.py index 5f6b13a6d..cfdbe0b56 100644 --- a/traitsui/extras/progress_column.py +++ b/traitsui/extras/progress_column.py @@ -16,7 +16,7 @@ class ProgressColumn(ObjectColumn): - """ A column which displays trait values as a progress bar + """A column which displays trait values as a progress bar Progress values must be an integer value between the maximum and minimum values. By default it is assumed to be a percentage. @@ -39,6 +39,7 @@ def __init__(self, **traits): super().__init__(**traits) from traitsui.toolkit import toolkit_object + ProgressRenderer = toolkit_object( 'extra.progress_renderer:ProgressRenderer' ) @@ -46,8 +47,7 @@ def __init__(self, **traits): self.renderer = ProgressRenderer() def is_editable(self, object): - """ Returns whether the column is editable for a specified object. - """ + """Returns whether the column is editable for a specified object.""" # Progress columns are always read-only return False @@ -58,7 +58,7 @@ def get_maximum(self, object): return self.maximum def get_text_visible(self): - """ Whether or not to display text in column. + """Whether or not to display text in column. Note, may not render on some platforms (eg. OS X) due to the rendering style. diff --git a/traitsui/extras/saving.py b/traitsui/extras/saving.py index c7ec99253..c1e70b267 100644 --- a/traitsui/extras/saving.py +++ b/traitsui/extras/saving.py @@ -30,10 +30,10 @@ class CanSaveMixin(HasTraits): - """ A mixin-class for objects that wish to support GUI saving via a - SaveHandler. It is the responsiblity of the child class to manage - its dirty flag, which describes whether its information has changed - since its last save. + """A mixin-class for objects that wish to support GUI saving via a + SaveHandler. It is the responsiblity of the child class to manage + its dirty flag, which describes whether its information has changed + since its last save. """ filepath = Str() @@ -44,8 +44,8 @@ class CanSaveMixin(HasTraits): # ----------------------------------------------------------------- def __getstate__(self): - """ We don't want to pickle the filepath because this can change, - obviously, if the user moves around the pickled file. + """We don't want to pickle the filepath because this can change, + obviously, if the user moves around the pickled file. """ state = super().__getstate__() del state["filepath"] @@ -57,25 +57,24 @@ def __getstate__(self): # ----------------------------------------------------------------- def validate(self): - """ Returns whether the information in the object is valid to be saved - in tuple form. The first item is the validation state (boolean) and - the second item is the message to display if the object did not - validate. + """Returns whether the information in the object is valid to be saved + in tuple form. The first item is the validation state (boolean) and + the second item is the message to display if the object did not + validate. - By default, an object always validates. + By default, an object always validates. """ return (True, "") def save(self): - """ Saves the object to the path specified by its 'filepath' trait. This - method should also reset the dirty flag on this object. + """Saves the object to the path specified by its 'filepath' trait. This + method should also reset the dirty flag on this object. """ raise NotImplementedError class SaveHandler(Handler): - """ A Handler that facilates adding saving to a Traits UI application. - """ + """A Handler that facilates adding saving to a Traits UI application.""" #: The object which is to be saved (subclass of CanSaveMixin). It is assigned #: to info.object in the 'init' method, which in many cases is what you want. @@ -119,14 +118,14 @@ class SaveHandler(Handler): # ----------------------------------------------------------------- def init(self, info): - """ Set the default save object (the object being handled). Also, - perform a questionable hack by which we remove the handled - object from the keybinding's controllers. This means that a - keybinding to 'save' only calls this object, not the object - being edited as well. (For reasons unclear, the KeyBinding handler - API is radically different from the Action API, which is the reason - that this problem exists. Keybindings are a UI concept--they should - *not* call the model by default.) + """Set the default save object (the object being handled). Also, + perform a questionable hack by which we remove the handled + object from the keybinding's controllers. This means that a + keybinding to 'save' only calls this object, not the object + being edited as well. (For reasons unclear, the KeyBinding handler + API is radically different from the Action API, which is the reason + that this problem exists. Keybindings are a UI concept--they should + *not* call the model by default.) """ keybindings = info.ui.key_bindings if keybindings is not None: @@ -136,8 +135,8 @@ def init(self, info): return True def close(self, info, is_ok): - """ Called when the user requests to close the interface. Returns a - boolean indicating whether the window should be allowed to close. + """Called when the user requests to close the interface. Returns a + boolean indicating whether the window should be allowed to close. """ if self.promptOnExit: return self.promptForSave(info) @@ -145,8 +144,8 @@ def close(self, info, is_ok): return True def closed(self, info, is_ok): - """ Called after the window is destroyed. Makes sure that the autosave - timer is stopped. + """Called after the window is destroyed. Makes sure that the autosave + timer is stopped. """ if self._timer: self._timer.Stop() @@ -156,16 +155,16 @@ def closed(self, info, is_ok): # ----------------------------------------------------------------- def exit(self, info): - """ Closes the UI unless a save prompt is cancelled. Provided for - convenience to be used with a Menu action. + """Closes the UI unless a save prompt is cancelled. Provided for + convenience to be used with a Menu action. """ if self.close(info, True): info.ui.dispose() def save(self, info): - """ Saves the object to its current filepath. If this is not specified, - opens a dialog to select this path. Returns whether the save - actually occurred. + """Saves the object to its current filepath. If this is not specified, + opens a dialog to select this path. Returns whether the save + actually occurred. """ if self.saveObject.filepath == "": return self.saveAs(info) @@ -173,8 +172,8 @@ def save(self, info): return self._validateAndSave() def saveAs(self, info): - """ Saves the object to a new path, and sets this as the 'filepath' on - the object. Returns whether the save actually occurred. + """Saves the object to a new path, and sets this as the 'filepath' on + the object. Returns whether the save actually occurred. """ fileDialog = FileDialog( action="save as", @@ -196,8 +195,8 @@ def saveAs(self, info): return self._validateAndSave() def promptForSave(self, info, cancel=True): - """ Prompts the user to save the object, if appropriate. Returns whether - the user canceled the action that invoked this prompt. + """Prompts the user to save the object, if appropriate. Returns whether + the user canceled the action that invoked this prompt. """ if self.saveObject.dirty: code = confirm( @@ -214,8 +213,7 @@ def promptForSave(self, info, cancel=True): return True def _autosave(self): - """ Called by the timer when an autosave should take place. - """ + """Called by the timer when an autosave should take place.""" if self.saveObject.dirty and self.saveObject.filepath != "": success, message = self.saveObject.validate() if success or ( @@ -225,8 +223,7 @@ def _autosave(self): @observe("autosave, autosaveInterval, saveObject") def _configure_timer(self, event): - """ Creates, replaces, or destroys the autosave timer. - """ + """Creates, replaces, or destroys the autosave timer.""" if self._timer: self._timer.Stop() if self.autosave and self.saveObject: @@ -235,8 +232,8 @@ def _configure_timer(self, event): self._timer = None def _validateAndSave(self): - """ Try to save to the current filepath. Returns whether whether the - validation was successful/overridden (and the object saved). + """Try to save to the current filepath. Returns whether whether the + validation was successful/overridden (and the object saved). """ success, message = self.saveObject.validate() if success: diff --git a/traitsui/file_dialog.py b/traitsui/file_dialog.py index 5685ba03f..f18822939 100644 --- a/traitsui/file_dialog.py +++ b/traitsui/file_dialog.py @@ -13,7 +13,6 @@ """ - from os import R_OK, W_OK, access, mkdir from os.path import ( @@ -88,8 +87,7 @@ class IFileDialogModel(Interface): - """ Defines a model extension to a file dialog. - """ + """Defines a model extension to a file dialog.""" #: The name of the currently selected file: file_name = File() @@ -101,8 +99,7 @@ class IFileDialogModel(Interface): class IFileDialogView(Interface): - """ Defines a visual extension to a file dialog. - """ + """Defines a visual extension to a file dialog.""" #: The view to display: view = AView @@ -117,8 +114,8 @@ class IFileDialogView(Interface): class IFileDialogExtension(IFileDialogModel, IFileDialogView): - """ Defines a (convenience) union of the IFileDialogModel and - IFileDialogView interfaces. + """Defines a (convenience) union of the IFileDialogModel and + IFileDialogView interfaces. """ @@ -140,8 +137,7 @@ class MFileDialogModel(HasPrivateTraits): class MFileDialogView(HasPrivateTraits): - """ Defines a visual extension to a file dialog. - """ + """Defines a visual extension to a file dialog.""" #: The view to display: view = AView @@ -155,14 +151,13 @@ class MFileDialogView(HasPrivateTraits): class MFileDialogExtension(MFileDialogModel, MFileDialogView): - """ Defines a (convenience) union of the MFileDialogModel and - MFileDialogView mix-in classes. + """Defines a (convenience) union of the MFileDialogModel and + MFileDialogView mix-in classes. """ class FileInfo(MFileDialogModel): - """ Defines a file dialog extension that display various file information. - """ + """Defines a file dialog extension that display various file information.""" #: The size of the file: size = Property(observe="file_name") @@ -227,8 +222,7 @@ def _get_ctime(self): class TextInfo(MFileDialogModel): - """ Defines a file dialog extension that displays a file's contents as text. - """ + """Defines a file dialog extension that displays a file's contents as text.""" #: The file's text content: text = Property(observe="file_name") @@ -259,8 +253,8 @@ def _get_text(self): class ImageInfo(MFileDialogModel): - """ Defines a file dialog extension that display an image file's dimensions - and content. + """Defines a file dialog extension that display an image file's dimensions + and content. """ #: The ImageResource object for the current file: @@ -319,8 +313,7 @@ def _get_height(self): class CreateDirHandler(Handler): - """ Controller for the 'create new directory' popup. - """ + """Controller for the 'create new directory' popup.""" #: The name for the new directory to be created: dir_name = Str() @@ -361,8 +354,7 @@ class CreateDirHandler(Handler): # -- Handler Event Handlers ----------------------------------------------- def handler_ok_changed(self, info): - """ Handles the user clicking the OK button. - """ + """Handles the user clicking the OK button.""" dir = info.object.file_name if not isdir(dir): dir = dirname(dir) @@ -386,14 +378,12 @@ def handler_ok_changed(self, info): ) def handler_cancel_changed(self, info): - """ Handles the user clicking the Cancel button. - """ + """Handles the user clicking the Cancel button.""" info.ui.dispose(False) class FileExistsHandler(Handler): - """ Controller for the 'file already exists' popup. - """ + """Controller for the 'file already exists' popup.""" #: The current status message: message = Str() @@ -427,21 +417,18 @@ class FileExistsHandler(Handler): # -- Handler Event Handlers ----------------------------------------------- def handler_ok_changed(self, info): - """ Handles the user clicking the OK button. - """ + """Handles the user clicking the OK button.""" parent = info.ui.parent info.ui.dispose(True) parent.dispose(True) def handler_cancel_changed(self, info): - """ Handles the user clicking the Cancel button. - """ + """Handles the user clicking the Cancel button.""" info.ui.dispose(False) class OpenFileDialog(Handler): - """ Defines the model and handler for the open file dialog. - """ + """Defines the model and handler for the open file dialog.""" #: The starting and current file path: file_name = File() @@ -492,8 +479,7 @@ class OpenFileDialog(Handler): # -- Handler Class Method Overrides --------------------------------------- def init_info(self, info): - """ Handles the UIInfo object being initialized during view start-up. - """ + """Handles the UIInfo object being initialized during view start-up.""" self.info = info # -- Property Implementations --------------------------------------------- @@ -511,21 +497,18 @@ def _get_can_create_dir(self): # -- Handler Event Handlers ----------------------------------------------- def object_ok_changed(self, info): - """ Handles the user clicking the OK button. - """ + """Handles the user clicking the OK button.""" if self.is_save_file and exists(self.file_name): do_later(self._file_already_exists) else: info.ui.dispose(True) def object_cancel_changed(self, info): - """ Handles the user clicking the Cancel button. - """ + """Handles the user clicking the Cancel button.""" info.ui.dispose(False) def object_create_changed(self, info): - """ Handles the user clicking the create directory button. - """ + """Handles the user clicking the create directory button.""" if not isdir(self.file_name): self.file_name = dirname(self.file_name) @@ -536,16 +519,14 @@ def object_create_changed(self, info): # -- Traits Event Handlers ------------------------------------------------ def _dclick_changed(self): - """ Handles the user double-clicking a file name in the file tree view. - """ + """Handles the user double-clicking a file name in the file tree view.""" if self.is_valid_file: self.object_ok_changed(self.info) # -- Private Methods ------------------------------------------------------ def open_file_view(self): - """ Returns the file dialog view to use. - """ + """Returns the file dialog view to use.""" # Set up the default file dialog view and size information: item = Item( "file_name", @@ -661,8 +642,8 @@ def open_file_view(self): ) def _file_already_exists(self): - """ Handles prompting the user when the selected file already exists, - and the dialog is a 'save file' dialog. + """Handles prompting the user when the selected file already exists, + and the dialog is a 'save file' dialog. """ feh = FileExistsHandler( message=( @@ -683,8 +664,8 @@ def _file_already_exists(self): def open_file(**traits): - """ Returns a file name to open or an empty string if the user cancels the - operation. + """Returns a file name to open or an empty string if the user cancels the + operation. """ fd = OpenFileDialog(**traits) if fd.edit_traits(view="open_file_view").result: @@ -694,10 +675,10 @@ def open_file(**traits): def save_file(**traits): - """ Returns a file name to save to or an empty string if the user cancels - the operation. In the case where the file selected already exists, the - user will be prompted if they want to overwrite the file before the - selected file name is returned. + """Returns a file name to save to or an empty string if the user cancels + the operation. In the case where the file selected already exists, the + user will be prompted if they want to overwrite the file before the + selected file name is returned. """ traits.setdefault("title", "Save File") traits["is_save_file"] = True diff --git a/traitsui/group.py b/traitsui/group.py index 250e9fd59..bb1a47b0c 100644 --- a/traitsui/group.py +++ b/traitsui/group.py @@ -13,7 +13,6 @@ """ - from traits.api import ( Bool, Delegate, @@ -51,8 +50,7 @@ class Group(ViewSubElement): - """ Represents a grouping of items in a user interface view. - """ + """Represents a grouping of items in a user interface view.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -196,8 +194,7 @@ class Group(ViewSubElement): height = Property(Float, observe="content") def __init__(self, *values, **traits): - """ Initializes the group object. - """ + """Initializes the group object.""" super().__init__(**traits) content = self.content @@ -237,21 +234,20 @@ def _dock_theme_default(self): return dock_window_theme() def get_label(self, ui): - """ Gets the label to use this group. - """ + """Gets the label to use this group.""" if self.label != "": return self.label return "Group" def is_includable(self): - """ Returns a Boolean value indicating whether the object is replacable + """Returns a Boolean value indicating whether the object is replacable by an Include object. """ return self.id != "" def replace_include(self, view_elements): - """ Replaces any items that have an **id** attribute with an Include + """Replaces any items that have an **id** attribute with an Include object with the same ID value, and puts the object with the ID into the specified ViewElements object. @@ -272,7 +268,7 @@ def replace_include(self, view_elements): item.replace_include(view_elements) def get_shadow(self, ui): - """ Returns a ShadowGroup object for the current Group object, which + """Returns a ShadowGroup object for the current Group object, which recursively resolves all embedded Include objects and which replaces each embedded Group object with a corresponding ShadowGroup. """ @@ -301,21 +297,18 @@ def get_shadow(self, ui): return ShadowGroup(shadow=self, content=content, groups=groups) def set_container(self): - """ Sets the correct container for the content. - """ + """Sets the correct container for the content.""" for item in self.content: item.container = self def _defined_when(self, ui, value): - """ Should the object be defined in the user interface? - """ + """Should the object be defined in the user interface?""" if value.defined_when == "": return True return ui.eval_when(value.defined_when) def _parse(self, value): - """ Parses Group options specified as a string. - """ + """Parses Group options specified as a string.""" # Override the defaults, since we only allow 'True' values to be # specified: self.show_border = self.show_labels = self.show_left = False @@ -341,13 +334,11 @@ def _parse(self, value): self.object = value def _parsed_label(self): - """ Handles a label being found in the string definition. - """ + """Handles a label being found in the string definition.""" self.show_border = True def __repr__(self): - """ Returns a "pretty print" version of the Group. - """ + """Returns a "pretty print" version of the Group.""" result = [] items = ",\n".join([item.__repr__() for item in self.content]) if len(items) > 0: @@ -381,8 +372,7 @@ def __repr__(self): @cached_property def _get_width(self): - """ Returns the requested width of the Group. - """ + """Returns the requested width of the Group.""" width = 0.0 for item in self.content: if item.width >= 1: @@ -398,8 +388,7 @@ def _get_width(self): @cached_property def _get_height(self): - """ Returns the requested height of the Group. - """ + """Returns the requested height of the Group.""" height = 0.0 for item in self.content: if item.height >= 1: @@ -415,8 +404,7 @@ def _get_height(self): class HGroup(Group): - """ A group whose items are laid out horizontally. - """ + """A group whose items are laid out horizontally.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -428,8 +416,7 @@ class HGroup(Group): class VGroup(Group): - """ A group whose items are laid out vertically. - """ + """A group whose items are laid out vertically.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -441,8 +428,7 @@ class VGroup(Group): class VGrid(VGroup): - """ A group whose items are laid out in 2 columns. - """ + """A group whose items are laid out in 2 columns.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -453,7 +439,7 @@ class VGrid(VGroup): class HFlow(HGroup): - """ A group in which items are laid out horizontally, and "wrap" when + """A group in which items are laid out horizontally, and "wrap" when they exceed the available horizontal space.. """ @@ -468,7 +454,7 @@ class HFlow(HGroup): class VFlow(VGroup): - """ A group in which items are laid out vertically, and "wrap" when they + """A group in which items are laid out vertically, and "wrap" when they exceed the available vertical space. """ @@ -482,8 +468,8 @@ class VFlow(VGroup): class VFold(VGroup): - """ A group in which items are laid out vertically and can be collapsed - (i.e. 'folded') by clicking their title. + """A group in which items are laid out vertically and can be collapsed + (i.e. 'folded') by clicking their title. """ # ------------------------------------------------------------------------- @@ -497,8 +483,7 @@ class VFold(VGroup): class HSplit(Group): - """ A horizontal group with splitter bars to separate it from other groups. - """ + """A horizontal group with splitter bars to separate it from other groups.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -511,8 +496,7 @@ class HSplit(Group): class VSplit(Group): - """ A vertical group with splitter bars to separate it from other groups. - """ + """A vertical group with splitter bars to separate it from other groups.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -525,8 +509,7 @@ class VSplit(Group): class Tabbed(Group): - """ A group that is shown as a tabbed notebook. - """ + """A group that is shown as a tabbed notebook.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -539,9 +522,9 @@ class Tabbed(Group): class ShadowGroup(Group): - """ Corresponds to a Group object, but with all embedded Include - objects resolved, and with all embedded Group objects replaced by - corresponding ShadowGroup objects. + """Corresponds to a Group object, but with all embedded Include + objects resolved, and with all embedded Group objects replaced by + corresponding ShadowGroup objects. """ def __init__(self, shadow, **traits): @@ -631,7 +614,7 @@ def __init__(self, shadow, **traits): style_sheet = ShadowDelegate def get_content(self, allow_groups=True): - """ Returns the contents of the Group within a specified context for + """Returns the contents of the Group within a specified context for building a user interface. This method makes sure that all Group types are of the same type (i.e., @@ -670,21 +653,18 @@ def get_content(self, allow_groups=True): return result def get_id(self): - """ Returns an ID for the group. - """ + """Returns an ID for the group.""" if self.id != "": return self.id return ":".join([item.get_id() for item in self.get_content()]) def set_container(self): - """ Sets the correct container for the content. - """ + """Sets the correct container for the content.""" pass def _flush_items(self, content, items): - """ Creates a sub-group for any items contained in a specified list. - """ + """Creates a sub-group for any items contained in a specified list.""" if len(items) > 0: content.append( # Set shadow before hand to prevent delegation errors @@ -702,6 +682,5 @@ def _flush_items(self, content, items): del items[:] def __repr__(self): - """ Returns a "pretty print" version of the Group. - """ + """Returns a "pretty print" version of the Group.""" return repr(self.shadow) diff --git a/traitsui/handler.py b/traitsui/handler.py index bafd5cdc9..a48c826a9 100644 --- a/traitsui/handler.py +++ b/traitsui/handler.py @@ -29,8 +29,7 @@ def close_dock_control(dock_control): - """ Closes a DockControl (if allowed by the associated Traits UI Handler). - """ + """Closes a DockControl (if allowed by the associated Traits UI Handler).""" # Retrieve the traits UI object set when we created the DockControl: ui = dock_control.data @@ -47,23 +46,23 @@ def close_dock_control(dock_control): class Handler(HasPrivateTraits): - """ Provides access to and control over the run-time workings of a + """Provides access to and control over the run-time workings of a Traits-based user interface. """ def init_info(self, info): - """ Informs the handler what the UIInfo object for a View will be. + """Informs the handler what the UIInfo object for a View will be. - This method is called before the UI for the View has been - constructed. It is provided so that the handler can save the - reference to the UIInfo object in case it exposes viewable traits - whose values are properties that depend upon items in the context - being edited. + This method is called before the UI for the View has been + constructed. It is provided so that the handler can save the + reference to the UIInfo object in case it exposes viewable traits + whose values are properties that depend upon items in the context + being edited. """ pass def init(self, info): - """ Initializes the controls of a user interface. + """Initializes the controls of a user interface. This method is called after all user interface elements have been created, but before the user interface is displayed. Override this @@ -86,7 +85,7 @@ def init(self, info): return True def position(self, info): - """ Positions a dialog-based user interface on the display. + """Positions a dialog-based user interface on the display. This method is called after the user interface is initialized (by calling init()), but before the user interface is displayed. Override @@ -105,7 +104,7 @@ def position(self, info): toolkit().position(info.ui) def close(self, info, is_ok): - """ Handles the user attempting to close a dialog-based user interface. + """Handles the user attempting to close a dialog-based user interface. This method is called when the user attempts to close a window, by clicking an **OK** or **Cancel** button, or clicking a Close control @@ -133,7 +132,7 @@ def close(self, info, is_ok): return True def closed(self, info, is_ok): - """ Handles a dialog-based user interface being closed by the user. + """Handles a dialog-based user interface being closed by the user. This method is called *after* the window is destroyed. Override this method to perform any clean-up tasks needed by the application. @@ -149,17 +148,15 @@ def closed(self, info, is_ok): return def revert(self, info): - """ Handles the **Revert** button being clicked. - """ + """Handles the **Revert** button being clicked.""" return def apply(self, info): - """ Handles the **Apply** button being clicked. - """ + """Handles the **Apply** button being clicked.""" return def show_help(self, info, control=None): - """ Shows the help associated with the view. + """Shows the help associated with the view. This method is called when the user clicks a **Help** button in a Traits user interface. The method calls the global help handler, which @@ -179,7 +176,7 @@ def show_help(self, info, control=None): on_help_call()(info, control) def perform(self, info, action, event): - """ Perform computation for an action. + """Perform computation for an action. The default method looks for a method matching ``action.action`` and calls it (sniffing the signature to determine how to call it for @@ -226,7 +223,7 @@ def perform(self, info, action, event): action.perform(event) def get_perform_handlers(self, info): - """ Return a list of objects which can handle actions. + """Return a list of objects which can handle actions. This method may be overridden by sub-classes to return a more relevant set of objects. @@ -252,7 +249,7 @@ def get_perform_handlers(self, info): return handlers def setattr(self, info, object, name, value): - """ Handles the user setting a specified object trait's value. + """Handles the user setting a specified object trait's value. This method is called when an editor attempts to set a new value for a specified object trait attribute. Use this method to control what @@ -279,8 +276,7 @@ def setattr(self, info, object, name, value): setattr(object, name, value) def trait_view_for(self, info, view, object, object_name, trait_name): - """ Gets a specified View object. - """ + """Gets a specified View object.""" # If a view element was passed instead of a name or None, return it: if isinstance(view, ViewElement): return view @@ -326,8 +322,7 @@ def trait_view_for(self, info, view, object, object_name, trait_name): # -- 'DockWindowHandler' interface implementation ------------------------- def can_drop(self, info, object): - """ Can the specified object be inserted into the view? - """ + """Can the specified object be inserted into the view?""" from pyface.dock.api import DockControl if isinstance(object, DockControl): @@ -340,8 +335,7 @@ def can_import(self, info, category): return category in info.ui.view.imports def dock_control_for(self, info, parent, object): - """ Returns the DockControl object for a specified object. - """ + """Returns the DockControl object for a specified object.""" from pyface.dock.api import IDockable, DockControl from .dockable_view_element import DockableViewElement @@ -400,15 +394,13 @@ def dock_control_for(self, info, parent, object): return dc def open_view_for(self, control, use_mouse=True): - """ Creates a new view of a specified control. - """ + """Creates a new view of a specified control.""" from pyface.dock.api import DockWindowShell DockWindowShell(control, use_mouse=use_mouse) def dock_window_empty(self, dock_window): - """ Handles a DockWindow becoming empty. - """ + """Handles a DockWindow becoming empty.""" if dock_window.auto_close: dock_window.control.GetParent.Destroy() @@ -423,10 +415,9 @@ def edit_traits( handler=None, id="", scrollable=None, - **args + **args, ): - """ Edits the object's traits. - """ + """Edits the object's traits.""" if context is None: context = self @@ -454,10 +445,9 @@ def configure_traits( handler=None, id="", scrollable=None, - **args + **args, ): - """ Configures the object's traits. - """ + """Configures the object's traits.""" return super().configure_traits( filename, view, @@ -467,33 +457,29 @@ def configure_traits( handler or self, id, scrollable, - **args + **args, ) # -- Private Methods: ----------------------------------------------------- def _on_undo(self, info): - """ Handles an "Undo" change request. - """ + """Handles an "Undo" change request.""" if info.ui.history is not None: info.ui.history.undo() def _on_redo(self, info): - """ Handles a "Redo" change request. - """ + """Handles a "Redo" change request.""" if info.ui.history is not None: info.ui.history.redo() def _on_revert(self, info): - """ Handles a "Revert all changes" request. - """ + """Handles a "Revert all changes" request.""" if info.ui.history is not None: info.ui.history.revert() self.revert(info) def _on_close(self, info): - """ Handles a "Close" request. - """ + """Handles a "Close" request.""" if (info.ui.owner is not None) and self.close(info, True): info.ui.owner.close() @@ -506,7 +492,7 @@ def _on_close(self, info): def default_handler(handler=None): - """ Returns the global default handler. + """Returns the global default handler. If *handler* is an instance of Handler, this function sets it as the global default handler. @@ -519,13 +505,13 @@ def default_handler(handler=None): class Controller(Handler): - """ Defines a handler class which provides a view and controller for a - specified model. + """Defines a handler class which provides a view and controller for a + specified model. - This class is used when implementing a standard MVC-based design. The - **model** trait contains most, if not all, of the data being viewed, - and can be referenced in a Controller instance's View definition using - unadorned trait names. (e.g., ``Item('name')``). + This class is used when implementing a standard MVC-based design. The + **model** trait contains most, if not all, of the data being viewed, + and can be referenced in a Controller instance's View definition using + unadorned trait names. (e.g., ``Item('name')``). """ # -- Trait Definitions ---------------------------------------------------- @@ -539,22 +525,21 @@ class Controller(Handler): # -- HasTraits Method Overrides ------------------------------------------- def __init__(self, model=None, **metadata): - """ Initializes the object and sets the model (if supplied). - """ + """Initializes the object and sets the model (if supplied).""" super().__init__(**metadata) if model is not None: self.model = model def trait_context(self): - """ Returns the default context to use for editing or configuring - traits. + """Returns the default context to use for editing or configuring + traits. """ return {"object": self.model, "controller": self, "handler": self} # -- Handler Method Overrides --------------------------------------------- def get_perform_handlers(self, info): - """ Return a list of objects which can handle actions. + """Return a list of objects which can handle actions. By default this returns the Controller instance and the model. @@ -571,33 +556,32 @@ def get_perform_handlers(self, info): return [self, self.model] def init_info(self, info): - """ Informs the handler what the UIInfo object for a View will be. - """ + """Informs the handler what the UIInfo object for a View will be.""" self.info = info class ModelView(Controller): - """ Defines a handler class which provides a view and controller for a - specified model. - - This class is useful when creating a variant of the standard MVC-based - design. A subclass of ModelView reformulates a number of traits on - its **model** object as properties on the ModelView subclass itself, - usually in order to convert them into a more user-friendly format. In - this design, the ModelView subclass supplies not only the view and - the controller, but also, in effect, the model (as a set of properties - wrapped around the original model). Because of this, the ModelView - context dictionary specifies the ModelView instance itself as the - special *object* value, and assigns the original model object as the - *model* value. Thus, the traits of the ModelView object can be - referenced in its View definition using unadorned trait names. + """Defines a handler class which provides a view and controller for a + specified model. + + This class is useful when creating a variant of the standard MVC-based + design. A subclass of ModelView reformulates a number of traits on + its **model** object as properties on the ModelView subclass itself, + usually in order to convert them into a more user-friendly format. In + this design, the ModelView subclass supplies not only the view and + the controller, but also, in effect, the model (as a set of properties + wrapped around the original model). Because of this, the ModelView + context dictionary specifies the ModelView instance itself as the + special *object* value, and assigns the original model object as the + *model* value. Thus, the traits of the ModelView object can be + referenced in its View definition using unadorned trait names. """ # -- HasTraits Method Overrides ------------------------------------------- def trait_context(self): - """ Returns the default context to use for editing or configuring - traits. + """Returns the default context to use for editing or configuring + traits. """ return {"object": self, "handler": self, "model": self.model} diff --git a/traitsui/help.py b/traitsui/help.py index 0fd181cd5..9b65a3507 100644 --- a/traitsui/help.py +++ b/traitsui/help.py @@ -13,13 +13,11 @@ """ - from .toolkit import toolkit def default_show_help(info, control): - """ Default handler for showing the help associated with a view. - """ + """Default handler for showing the help associated with a view.""" toolkit().show_help(info.ui, control) @@ -28,7 +26,7 @@ def default_show_help(info, control): def on_help_call(new_show_help=None): - """ Sets a new global help provider function. + """Sets a new global help provider function. The help provider function must have a signature of *function*(*info*, *control*), where *info* is a UIInfo object for the diff --git a/traitsui/help_template.py b/traitsui/help_template.py index 67da575ea..3dd98b325 100644 --- a/traitsui/help_template.py +++ b/traitsui/help_template.py @@ -74,8 +74,7 @@ class HelpTemplate(HasStrictTraits): - """ Contains HTML templates for displaying help. - """ + """Contains HTML templates for displaying help.""" item_html = Str(ItemHTML) # Item popup help window HTML document group_html = Str(GroupHTML) # Group help window HTML document @@ -92,8 +91,7 @@ class HelpTemplate(HasStrictTraits): def help_template(template=None): - """ Gets or sets the current HelpTemplate in use. - """ + """Gets or sets the current HelpTemplate in use.""" global _help_template if template is not None: diff --git a/traitsui/helper.py b/traitsui/helper.py index 34f8960f7..f5da969cd 100644 --- a/traitsui/helper.py +++ b/traitsui/helper.py @@ -29,8 +29,7 @@ def user_name_for(name): - """ Returns a "user-friendly" name for a specified trait. - """ + """Returns a "user-friendly" name for a specified trait.""" name = name.replace("_", " ") name = name[:1].upper() + name[1:] result = "" @@ -44,12 +43,12 @@ def user_name_for(name): def commatize(value): - """ Formats a specified value as an integer string with embedded commas. - For example: commatize( 12345 ) returns "12,345". + """Formats a specified value as an integer string with embedded commas. + For example: commatize( 12345 ) returns "12,345". """ s = str(abs(value)) s = s.rjust(((len(s) + 2) / 3) * 3) - result = ",".join([s[i: i + 3] for i in range(0, len(s), 3)]).lstrip() + result = ",".join([s[i : i + 3] for i in range(0, len(s), 3)]).lstrip() if value >= 0: return result @@ -57,8 +56,7 @@ def commatize(value): def enum_values_changed(values, strfunc=str): - """ Recomputes the mappings for a new set of enumeration values. - """ + """Recomputes the mappings for a new set of enumeration values.""" if isinstance(values, dict): data = [(strfunc(v), n) for n, v in values.items()] @@ -92,7 +90,7 @@ def enum_values_changed(values, strfunc=str): def compute_column_widths(available_space, requested, min_widths, user_widths): - """ Distribute column space amongst columns based on requested space. + """Distribute column space amongst columns based on requested space. Widths requests can be specified as one of the following: diff --git a/traitsui/include.py b/traitsui/include.py index 7f63240cd..a42210bb9 100644 --- a/traitsui/include.py +++ b/traitsui/include.py @@ -13,14 +13,13 @@ """ - from traits.api import Str from .view_element import ViewSubElement class Include(ViewSubElement): - """ A substitutable user interface element, i.e., a placeholder in a view + """A substitutable user interface element, i.e., a placeholder in a view definition. When a view object constructs an attribute-editing window, any Include @@ -64,12 +63,10 @@ class LocatedPerson(Person): id = Str() def __init__(self, id, **traits): - """ Initializes the Include object. - """ + """Initializes the Include object.""" super().__init__(**traits) self.id = id def __repr__(self): - """ Returns a "pretty print" version of the Include object. - """ + """Returns a "pretty print" version of the Include object.""" return "<%s>" % self.id diff --git a/traitsui/instance_choice.py b/traitsui/instance_choice.py index 01d5fe18f..03557a9e7 100644 --- a/traitsui/instance_choice.py +++ b/traitsui/instance_choice.py @@ -14,13 +14,15 @@ from abc import abstractmethod -from traits.api import (ABCHasStrictTraits, - Str, - Any, - Dict, - Tuple, - Callable, - Bool) +from traits.api import ( + ABCHasStrictTraits, + Str, + Any, + Dict, + Tuple, + Callable, + Bool, +) from .ui_traits import AView @@ -43,35 +45,29 @@ class InstanceChoiceItem(ABCHasStrictTraits): is_factory = Bool(False) def get_name(self, object=None): - """ Returns the name of the item. - """ + """Returns the name of the item.""" return self.name def get_view(self): - """ Returns the view associated with the object. - """ + """Returns the view associated with the object.""" return self.view @abstractmethod def get_object(self): - """ Returns the object associated with the item. - """ + """Returns the object associated with the item.""" pass @abstractmethod def is_compatible(self, object): - """ Indicates whether a specified object is compatible with the item. - """ + """Indicates whether a specified object is compatible with the item.""" pass def is_selectable(self): - """ Indicates whether the item can be selected by the user. - """ + """Indicates whether the item can be selected by the user.""" return True def is_droppable(self): - """ Indicates whether the item supports drag and drop. - """ + """Indicates whether the item supports drag and drop.""" return False @@ -88,8 +84,7 @@ class InstanceChoice(InstanceChoiceItem): name_trait = Str("name") def get_name(self, object=None): - """ Returns the name of the item. - """ + """Returns the name of the item.""" if self.name != "": return self.name @@ -100,13 +95,11 @@ def get_name(self, object=None): return user_name_for(self.object.__class__.__name__) def get_object(self): - """ Returns the object associated with the item. - """ + """Returns the object associated with the item.""" return self.object def is_compatible(self, object): - """ Indicates whether a specified object is compatible with the item. - """ + """Indicates whether a specified object is compatible with the item.""" return object is self.object @@ -137,8 +130,7 @@ class InstanceFactoryChoice(InstanceChoiceItem): is_factory = True def get_name(self, object=None): - """ Returns the name of the item. - """ + """Returns the name of the item.""" if self.name != "": return self.name @@ -154,25 +146,21 @@ def get_name(self, object=None): return user_name_for(klass.__name__) def get_object(self): - """ Returns the object associated with the item. - """ + """Returns the object associated with the item.""" return self.klass(*self.args, **self.kw_args) def is_droppable(self): - """ Indicates whether the item supports drag and drop. - """ + """Indicates whether the item supports drag and drop.""" return self.droppable def is_compatible(self, object): - """ Indicates whether a specified object is compatible with the item. - """ + """Indicates whether a specified object is compatible with the item.""" if issubclass(type(self.klass), type): return isinstance(object, self.klass) return isinstance(object, self.get_object().__class__) def is_selectable(self): - """ Indicates whether the item can be selected by the user. - """ + """Indicates whether the item can be selected by the user.""" return self.selectable diff --git a/traitsui/item.py b/traitsui/item.py index 8a3dd1d14..0e5a34463 100644 --- a/traitsui/item.py +++ b/traitsui/item.py @@ -13,7 +13,6 @@ """ - import re from traits.api import ( @@ -38,7 +37,6 @@ from .editor_factory import EditorFactory - # Pattern of all digits: all_digits = re.compile(r"\d+") @@ -64,7 +62,7 @@ class Item(ViewSubElement): - """ An element in a Traits-based user interface. + """An element in a Traits-based user interface. Magic: @@ -260,8 +258,7 @@ class Item(ViewSubElement): invalid = Str() def __init__(self, value=None, **traits): - """ Initializes the item object. - """ + """Initializes the item object.""" super().__init__(**traits) if value is None: @@ -290,14 +287,13 @@ def __init__(self, value=None, **traits): self.name = value def is_includable(self): - """ Returns a Boolean indicating whether the object is replaceable by an - Include object. + """Returns a Boolean indicating whether the object is replaceable by an + Include object. """ return self.id != "" def is_spacer(self): - """ Returns True if the item represents a spacer or separator. - """ + """Returns True if the item represents a spacer or separator.""" name = self.name.strip() return ( @@ -307,8 +303,7 @@ def is_spacer(self): ) def get_help(self, ui): - """ Gets the help text associated with the Item in a specified UI. - """ + """Gets the help text associated with the Item in a specified UI.""" # Return 'None' if the Item is a separator or spacer: if self.is_spacer(): return None @@ -322,7 +317,7 @@ def get_help(self, ui): return object.base_trait(self.name).get_help() def get_label(self, ui): - """ Gets the label to use for a specified Item. + """Gets the label to use for a specified Item. If not specified, the label is set as the name of the corresponding trait, replacing '_' with ' ', and capitalizing @@ -364,16 +359,14 @@ def get_label(self, ui): return tlabel(object, name, label) def get_id(self): - """ Returns an ID used to identify the item. - """ + """Returns an ID used to identify the item.""" if self.id != "": return self.id return self.name def _parse_size(self, value): - """ Parses a '' value from the string definition. - """ + """Parses a '' value from the string definition.""" match = size_pat.match(value) if match is not None: data = match.group(2) @@ -388,8 +381,7 @@ def _parse_size(self, value): return value def _parse_tooltip(self, value): - """ Parses a *tooltip* value from the string definition. - """ + """Parses a *tooltip* value from the string definition.""" match = tooltip_pat.match(value) if match is not None: self.tooltip = match.group(2) @@ -398,15 +390,13 @@ def _parse_tooltip(self, value): return value def _set_float(self, name, value): - """ Sets a specified trait to a specified string converted to a float. - """ + """Sets a specified trait to a specified string converted to a float.""" value = value.strip() if value != "": setattr(self, name, float(value)) def __repr__(self): - """ Returns a "pretty print" version of the Item. - """ + """Returns a "pretty print" version of the Item.""" options = self._repr_options( "id", "object", "label", "style", "show_label", "width", "height" @@ -426,8 +416,7 @@ def __repr__(self): class UItem(Item): - """ An Item that has no label. - """ + """An Item that has no label.""" show_label = Bool(False) @@ -438,8 +427,7 @@ class UItem(Item): class Custom(Item): - """ An Item using a 'custom' style. - """ + """An Item using a 'custom' style.""" style = EditorStyle("custom") @@ -450,8 +438,7 @@ class Custom(Item): class UCustom(Custom): - """ An Item using a 'custom' style with no label. - """ + """An Item using a 'custom' style with no label.""" show_label = Bool(False) @@ -462,8 +449,7 @@ class UCustom(Custom): class Readonly(Item): - """ An Item using a 'readonly' style. - """ + """An Item using a 'readonly' style.""" style = EditorStyle("readonly") @@ -474,8 +460,7 @@ class Readonly(Item): class UReadonly(Readonly): - """ An Item using a 'readonly' style with no label. - """ + """An Item using a 'readonly' style with no label.""" show_label = Bool(False) @@ -486,8 +471,7 @@ class UReadonly(Readonly): class Label(Item): - """ An item that is a label. - """ + """An item that is a label.""" def __init__(self, label, **traits): super().__init__(label=label, **traits) @@ -499,8 +483,7 @@ def __init__(self, label, **traits): class Heading(Label): - """ An item that is a fancy label. - """ + """An item that is a fancy label.""" #: Override the 'style' trait to default to the fancy 'custom' style: style = Constant("custom") @@ -512,8 +495,7 @@ class Heading(Label): class Spring(Item): - """ An item that is a layout "spring". - """ + """An item that is a layout "spring".""" # ------------------------------------------------------------------------- # Trait definitions: diff --git a/traitsui/key_bindings.py b/traitsui/key_bindings.py index 746cd6632..0e86ef069 100644 --- a/traitsui/key_bindings.py +++ b/traitsui/key_bindings.py @@ -39,8 +39,7 @@ class KeyBinding(HasStrictTraits): - """ Binds one or two keystrokes to a method. - """ + """Binds one or two keystrokes to a method.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -80,8 +79,7 @@ def _binding_changed(self): class KeyBindings(HasPrivateTraits): - """ A set of key bindings. - """ + """A set of key bindings.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -152,8 +150,7 @@ def __init__(self, *bindings, **traits): self.bindings = [binding.trait_set(owner=self) for binding in bindings] def do(self, event, controllers=[], *args, **kw): - """ Processes a keyboard event. - """ + """Processes a keyboard event.""" if isinstance(controllers, dict): controllers = list(controllers.values()) elif not isinstance(controllers, SequenceTypes): @@ -169,8 +166,7 @@ def do(self, event, controllers=[], *args, **kw): ) def merge(self, key_bindings): - """ Merges another set of key bindings into this set. - """ + """Merges another set of key bindings into this set.""" binding_dic = {} for binding in self.bindings: binding_dic[binding.method_name] = binding @@ -182,15 +178,13 @@ def merge(self, key_bindings): binding2.binding2 = binding.binding2 def clone(self, **traits): - """ Returns a clone of the KeyBindings object. - """ + """Returns a clone of the KeyBindings object.""" return self.__class__(*self.bindings, **traits).trait_set( **self.trait_get("prefix", "suffix") ) def dispose(self): - """ Dispose of the object. - """ + """Dispose of the object.""" if self.parent is not None: self.parent.children.remove(self) @@ -201,15 +195,13 @@ def dispose(self): self.parent = self._root = self.focus_owner = None def edit(self): - """ Edits a possibly hierarchical set of KeyBindings. - """ + """Edits a possibly hierarchical set of KeyBindings.""" bindings = list(set(self.root._get_bindings([]))) bindings.sort(key=lambda x: "%s%02d" % (x.binding1[-1:], x.binding1)) KeyBindings(bindings).edit_traits() def key_binding_for(self, binding, key_name): - """ Returns the current binding for a specified key (if any). - """ + """Returns the current binding for a specified key (if any).""" if key_name != "": for a_binding in self.bindings: if (a_binding is not binding) and ( @@ -233,8 +225,7 @@ def _get_root(self): # -- Event Handlers ------------------------------------------------------- def _binding_modified_changed(self, binding): - """ Handles a binding being changed. - """ + """Handles a binding being changed.""" binding1 = binding.binding1 binding2 = binding.binding2 for a_binding in self.bindings: @@ -249,15 +240,13 @@ def _binding_modified_changed(self, binding): a_binding.binding2 = "" def _focus_owner_changed(self, old, new): - """ Handles the focus owner being changed. - """ + """Handles the focus owner being changed.""" if old is not None: old.border_size = 0 @observe("children.items") def _children_modified(self, event): - """ Handles child KeyBindings being added to the object. - """ + """Handles child KeyBindings being added to the object.""" # the full children list is changed if isinstance(event.object, KeyBindings): for item in event.new: @@ -270,8 +259,7 @@ def _children_modified(self, event): # -- object Method Overrides ---------------------------------------------- def __setstate__(self, state): - """ Restores the state of a previously pickled object. - """ + """Restores the state of a previously pickled object.""" n = len(state["bindings"]) self.add_trait("bindings", List(KeyBinding, minlen=n, maxlen=n)) self.__dict__.update(state) @@ -280,8 +268,7 @@ def __setstate__(self, state): # -- Private Methods ------------------------------------------------------ def _get_bindings(self, bindings): - """ Returns all of the bindings of this object and all of its children. - """ + """Returns all of the bindings of this object and all of its children.""" bindings.extend(self.bindings) for child in self.children: child._get_bindings(bindings) @@ -289,8 +276,8 @@ def _get_bindings(self, bindings): return bindings def _do(self, key_name, controllers, args, recursive): - """ Process the specified key for the specified set of controllers for - this KeyBindings object and all of its children. + """Process the specified key for the specified set of controllers for + this KeyBindings object and all of its children. """ # Search through our own bindings for a match: for binding in self.bindings: diff --git a/traitsui/list_str_adapter.py b/traitsui/list_str_adapter.py index 23e9696ce..473728273 100644 --- a/traitsui/list_str_adapter.py +++ b/traitsui/list_str_adapter.py @@ -83,8 +83,8 @@ class AnIListStrAdapter(HasPrivateTraits): class ListStrAdapter(HasPrivateTraits): - """ The base class for adapting list items to values that can be edited - by a ListStrEditor. + """The base class for adapting list items to values that can be edited + by a ListStrEditor. """ # Trait Definitions ------------------------------------------------------ @@ -146,76 +146,74 @@ class ListStrAdapter(HasPrivateTraits): # -- Adapter methods that are sensitive to item type ---------------------- def get_can_edit(self, object, trait, index): - """ Returns whether the user can edit a specified *object.trait[index]* - list item. A True result indicates the value can be edited, while - a False result indicates that it cannot be edited. + """Returns whether the user can edit a specified *object.trait[index]* + list item. A True result indicates the value can be edited, while + a False result indicates that it cannot be edited. """ return self._result_for("get_can_edit", object, trait, index) def get_drag(self, object, trait, index): - """ Returns the 'drag' value for a specified *object.trait[index]* - list item. A result of *None* means that the item cannot be - dragged. + """Returns the 'drag' value for a specified *object.trait[index]* + list item. A result of *None* means that the item cannot be + dragged. """ return self._result_for("get_drag", object, trait, index) def get_can_drop(self, object, trait, index, value): - """ Returns whether the specified *value* can be dropped on the - specified *object.trait[index]* list item. A value of **True** - means the *value* can be dropped; and a value of **False** - indicates that it cannot be dropped. + """Returns whether the specified *value* can be dropped on the + specified *object.trait[index]* list item. A value of **True** + means the *value* can be dropped; and a value of **False** + indicates that it cannot be dropped. """ return self._result_for("get_can_drop", object, trait, index, value) def get_dropped(self, object, trait, index, value): - """ Returns how to handle a specified *value* being dropped on a - specified *object.trait[index]* list item. The possible return - values are: - - 'before' - Insert the specified *value* before the dropped on item. - 'after' - Insert the specified *value* after the dropped on item. + """Returns how to handle a specified *value* being dropped on a + specified *object.trait[index]* list item. The possible return + values are: + + 'before' + Insert the specified *value* before the dropped on item. + 'after' + Insert the specified *value* after the dropped on item. """ return self._result_for("get_dropped", object, trait, index, value) def get_text_color(self, object, trait, index): - """ Returns the text color for a specified *object.trait[index]* list - item. A result of None means use the default list item text color. + """Returns the text color for a specified *object.trait[index]* list + item. A result of None means use the default list item text color. """ return self._result_for("get_text_color", object, trait, index) def get_bg_color(self, object, trait, index): - """ Returns the background color for a specified *object.trait[index]* - list item. A result of None means use the default list item - background color. + """Returns the background color for a specified *object.trait[index]* + list item. A result of None means use the default list item + background color. """ return self._result_for("get_bg_color", object, trait, index) def get_image(self, object, trait, index): - """ Returns the name of the image to use for a specified - *object.trait[index]* list item. A result of None means no image - should be used. Otherwise, the result should either be the name of - the image, or an ImageResource item specifying the image to use. + """Returns the name of the image to use for a specified + *object.trait[index]* list item. A result of None means no image + should be used. Otherwise, the result should either be the name of + the image, or an ImageResource item specifying the image to use. """ return self._result_for("get_image", object, trait, index) def get_item(self, object, trait, index): - """ Returns the value of the *object.trait[index]* list item. - """ + """Returns the value of the *object.trait[index]* list item.""" return self._result_for("get_item", object, trait, index) def get_text(self, object, trait, index): - """ Returns the text to display for a specified *object.trait[index]* - list item. + """Returns the text to display for a specified *object.trait[index]* + list item. """ return self._result_for("get_text", object, trait, index) # -- Adapter methods that are not sensitive to item type ------------------ def len(self, object, trait): - """ Returns the number of items in the specified *object.trait* list. - """ + """Returns the number of items in the specified *object.trait* list.""" # Sometimes, during shutdown, the object has been set to None. if object is None: return 0 @@ -223,46 +221,42 @@ def len(self, object, trait): return len(getattr(object, trait)) def get_default_value(self, object, trait): - """ Returns a new default value for the specified *object.trait* list. - """ + """Returns a new default value for the specified *object.trait* list.""" return self.default_value def get_default_text(self, object, trait): - """ Returns the default text for the specified *object.trait* list. - """ + """Returns the default text for the specified *object.trait* list.""" return self.default_text def get_default_image(self, object, trait): - """ Returns the default image for the specified *object.trait* list. - """ + """Returns the default image for the specified *object.trait* list.""" return self.image def get_default_bg_color(self, object, trait): - """ Returns the default background color for the specified - *object.trait* list. + """Returns the default background color for the specified + *object.trait* list. """ return self._get_bg_color() def get_default_text_color(self, object, trait): - """ Returns the default text color for the specified *object.trait* - list. + """Returns the default text color for the specified *object.trait* + list. """ return self._get_text_color() def set_text(self, object, trait, index, text): - """ Sets the text for a specified *object.trait[index]* list item to - *text*. + """Sets the text for a specified *object.trait[index]* list item to + *text*. """ getattr(object, trait)[index] = text def delete(self, object, trait, index): - """ Deletes the specified *object.trait[index]* list item. - """ + """Deletes the specified *object.trait[index]* list item.""" del getattr(object, trait)[index] def insert(self, object, trait, index, value): - """ Inserts a new value at the specified *object.trait[index]* list - index. + """Inserts a new value at the specified *object.trait[index]* list + index. """ getattr(object, trait)[index:index] = [value] @@ -304,8 +298,8 @@ def _get_text(self): # -- Private Methods ------------------------------------------------------ def _result_for(self, name, object, trait, index, value=None): - """ Returns/Sets the value of the specified *name* attribute for the - specified *object.trait[index]* list item. + """Returns/Sets the value of the specified *name* attribute for the + specified *object.trait[index]* list item. """ self.index = index self.value = value @@ -353,7 +347,6 @@ def _result_for(self, name, object, trait, index, value=None): @observe("adapters.items.+update") def _flush_cache(self, event): - """ Flushes the cache when any trait on any adapter changes. - """ + """Flushes the cache when any trait on any adapter changes.""" self.cache = {} self.cache_flushed = True diff --git a/traitsui/menu.py b/traitsui/menu.py index d4be17951..2d332b556 100644 --- a/traitsui/menu.py +++ b/traitsui/menu.py @@ -27,8 +27,7 @@ class Action(PyFaceAction): - """ An action on a menu bar in a Traits UI window or panel. - """ + """An action on a menu bar in a Traits UI window or panel.""" # ------------------------------------------------------------------------- # Trait definitions: diff --git a/traitsui/message.py b/traitsui/message.py index c684a4430..86e8099e6 100644 --- a/traitsui/message.py +++ b/traitsui/message.py @@ -42,7 +42,7 @@ class Message(HasPrivateTraits): def message(message="", title="Message", buttons=["OK"], parent=None): - """ Displays a message to the user as a model window with the specified + """Displays a message to the user as a model window with the specified title and buttons. If *buttons* is not specified, a single **OK** button is used, which is @@ -60,7 +60,7 @@ def message(message="", title="Message", buttons=["OK"], parent=None): def error(message="", title="Message", buttons=["OK", "Cancel"], parent=None): - """ Displays a message to the user as a modal window with the specified + """Displays a message to the user as a modal window with the specified title and buttons. If *buttons* is not specified, **OK** and **Cancel** buttons are used, @@ -92,8 +92,7 @@ class AutoCloseMessage(HasPrivateTraits): time = Float(2.0) def show(self, parent=None, title=""): - """ Display the wait message for a limited duration. - """ + """Display the wait message for a limited duration.""" view = View( HGroup( spring, @@ -118,9 +117,9 @@ def show(self, parent=None, title=""): def auto_close_message( message="Please wait", time=2.0, title="Please wait", parent=None ): - """ Displays a message to the user as a modal window with no buttons. The - window closes automatically after a specified time interval (specified - in seconds). + """Displays a message to the user as a modal window with no buttons. The + window closes automatically after a specified time interval (specified + in seconds). """ msg = AutoCloseMessage(message=message, time=time) msg.show(parent=parent, title=title) diff --git a/traitsui/null/color_trait.py b/traitsui/null/color_trait.py index cd862642f..accff48cb 100644 --- a/traitsui/null/color_trait.py +++ b/traitsui/null/color_trait.py @@ -12,7 +12,6 @@ """ - from traits.api import Trait, TraitError # ------------------------------------------------------------------------- @@ -21,8 +20,7 @@ def convert_to_color(object, name, value): - """ Converts a number into a wxColour object. - """ + """Converts a number into a wxColour object.""" if isinstance(value, int): return value & 0xFFFFFF diff --git a/traitsui/null/font_trait.py b/traitsui/null/font_trait.py index 79c2a4606..982388e13 100644 --- a/traitsui/null/font_trait.py +++ b/traitsui/null/font_trait.py @@ -12,7 +12,6 @@ """ - from traits.api import Trait, TraitHandler, TraitError # ------------------------------------------------------------------------------ @@ -38,14 +37,13 @@ class TraitFont(TraitHandler): - """ Ensures that values assigned to a trait attribute are valid font + """Ensures that values assigned to a trait attribute are valid font descriptor strings; the value actually assigned is the corresponding canonical font descriptor string. """ def validate(self, object, name, value): - """ Validates that the value is a valid font descriptor string. - """ + """Validates that the value is a valid font descriptor string.""" try: point_size = family = style = weight = underline = "" facename = [""] diff --git a/traitsui/null/rgb_color_trait.py b/traitsui/null/rgb_color_trait.py index 11be65a66..0b23f8fde 100644 --- a/traitsui/null/rgb_color_trait.py +++ b/traitsui/null/rgb_color_trait.py @@ -14,7 +14,6 @@ """ - from traits.api import Trait, TraitError from traits.trait_base import SequenceTypes @@ -25,7 +24,7 @@ def range_check(value): - """ Checks that *value* can be converted to a value in the range 0.0 to 1.0. + """Checks that *value* can be converted to a value in the range 0.0 to 1.0. If so, it returns the floating point value; otherwise, it raises a TraitError. """ @@ -36,7 +35,7 @@ def range_check(value): def convert_to_color(object, name, value): - """ Converts a tuple or an integer to an RGB color value, or raises a + """Converts a tuple or an integer to an RGB color value, or raises a TraitError if that is not possible. """ if (type(value) in SequenceTypes) and (len(value) == 3): diff --git a/traitsui/null/toolkit.py b/traitsui/null/toolkit.py index 8d422a37e..1c6c155d0 100644 --- a/traitsui/null/toolkit.py +++ b/traitsui/null/toolkit.py @@ -13,7 +13,6 @@ """ - from ..toolkit import Toolkit diff --git a/traitsui/qt4/array_editor.py b/traitsui/qt4/array_editor.py index 3c173f028..6d74ed6a6 100644 --- a/traitsui/qt4/array_editor.py +++ b/traitsui/qt4/array_editor.py @@ -22,8 +22,7 @@ class SimpleEditor(BaseSimpleEditor, Editor): - """ Simple style of editor for arrays. - """ + """Simple style of editor for arrays.""" # FIXME: This class has been re-defined here simply so it inherits from the # PyQt Editor class. diff --git a/traitsui/qt4/boolean_editor.py b/traitsui/qt4/boolean_editor.py index 4fd6fdf73..6bbef70bc 100644 --- a/traitsui/qt4/boolean_editor.py +++ b/traitsui/qt4/boolean_editor.py @@ -37,12 +37,11 @@ class SimpleEditor(Editor): - """ Simple style of editor for Boolean values, which displays a check box. - """ + """Simple style of editor for Boolean values, which displays a check box.""" def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = QtGui.QCheckBox() self.control.stateChanged.connect(self.update_object) @@ -54,13 +53,12 @@ def dispose(self): super().dispose() def update_object(self, state): - """ Handles the user clicking the checkbox. - """ + """Handles the user clicking the checkbox.""" self.value = bool(state) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ if self.value: self.control.setCheckState(QtCore.Qt.Checked) @@ -69,13 +67,13 @@ def update_editor(self): class ReadonlyEditor(Editor): - """ Read-only style of editor for Boolean values, which displays static text + """Read-only style of editor for Boolean values, which displays static text of either "True" or "False". """ def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = QtGui.QLineEdit() self.control.setReadOnly(True) @@ -91,8 +89,8 @@ def init(self, parent): # ------------------------------------------------------------------------- def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ if self.value: self.control.setText("True") diff --git a/traitsui/qt4/button_editor.py b/traitsui/qt4/button_editor.py index 33578b242..19aa476ea 100644 --- a/traitsui/qt4/button_editor.py +++ b/traitsui/qt4/button_editor.py @@ -33,8 +33,7 @@ class SimpleEditor(Editor): - """ Simple style editor for a button. - """ + """Simple style editor for a button.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -50,8 +49,8 @@ class SimpleEditor(Editor): selected_item = Str() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ label = self.factory.label or self.item.get_label(self.ui) @@ -78,13 +77,13 @@ def init(self, parent): # widgets may not repaint properly in response to a button click. # See enthought/traitsui#1308 self.control.clicked.connect( - self.update_object, type=QtCore.Qt.QueuedConnection, + self.update_object, + type=QtCore.Qt.QueuedConnection, ) self.set_tooltip() def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" if self.factory.values_trait: self.object.observe( @@ -116,8 +115,8 @@ def _menu_selected(self, item_name): self.label = item_name def update_object(self): - """ Handles the user clicking the button by setting the factory value - on the object. + """Handles the user clicking the button by setting the factory value + on the object. """ if self.control is None: return @@ -133,15 +132,15 @@ def update_object(self): ) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ pass class CustomEditor(SimpleEditor): - """ Custom style editor for a button, which can contain an image. - """ + """Custom style editor for a button, which can contain an image.""" + #: The button image image = Image() @@ -153,8 +152,8 @@ class CustomEditor(SimpleEditor): } def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ # FIXME: We ignore orientation, width_padding and height_padding. @@ -181,8 +180,7 @@ def _image_updated(self, event): self.control.setIcon(image.create_icon()) def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" if self.control is not None: self.control.clicked.disconnect(self.update_object) diff --git a/traitsui/qt4/check_list_editor.py b/traitsui/qt4/check_list_editor.py index 799ca51b9..4d99024f4 100644 --- a/traitsui/qt4/check_list_editor.py +++ b/traitsui/qt4/check_list_editor.py @@ -25,7 +25,6 @@ """ - import logging from pyface.qt import QtCore, QtGui @@ -37,7 +36,6 @@ from .editor import EditorWithList - logger = logging.getLogger(__name__) # ------------------------------------------------------------------------- @@ -46,8 +44,7 @@ class SimpleEditor(EditorWithList): - """ Simple style of editor for checklists, which displays a combo box. - """ + """Simple style of editor for checklists, which displays a combo box.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -60,29 +57,26 @@ class SimpleEditor(EditorWithList): values = List() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.create_control(parent) super().init(parent) def create_control(self, parent): - """ Creates the initial editor control. - """ + """Creates the initial editor control.""" self.control = QtGui.QComboBox() self.control.activated[int].connect(self.update_object) def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" if self.control is not None: self.control.activated[int].disconnect(self.update_object) super().dispose() def list_updated(self, values): - """ Handles updates to the list of legal checklist values. - """ + """Handles updates to the list of legal checklist values.""" sv = self.string_value if (len(values) > 0) and isinstance(values[0], str): values = [(x, sv(x, str.capitalize)) for x in values] @@ -112,8 +106,7 @@ def list_updated(self, values): self.rebuild_editor() def rebuild_editor(self): - """ Rebuilds the editor after its definition is modified. - """ + """Rebuilds the editor after its definition is modified.""" control = self.control control.clear() for name in self.names: @@ -121,16 +114,15 @@ def rebuild_editor(self): self.update_editor() def update_object(self, index): - """ Handles the user selecting a new value from the combo box. - """ + """Handles the user selecting a new value from the combo box.""" value = self.values[index] if not isinstance(self.value, str): value = [value] self.value = value def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ try: self.control.setCurrentIndex( @@ -141,8 +133,8 @@ def update_editor(self): class CustomEditor(SimpleEditor): - """ Custom style of editor for checklists, which displays a set of check - boxes. + """Custom style of editor for checklists, which displays a set of check + boxes. """ #: List of tuple(signal, slot) to be disconnected while rebuilding the @@ -150,15 +142,14 @@ class CustomEditor(SimpleEditor): _connections_to_rebuild = List(Tuple(Any, Callable)) def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.create_control(parent) EditorWithList.init(self, parent) def create_control(self, parent): - """ Creates the initial editor control. - """ + """Creates the initial editor control.""" self.control = QtGui.QWidget() layout = QtGui.QGridLayout(self.control) layout.setContentsMargins(0, 0, 0, 0) @@ -167,8 +158,7 @@ def create_control(self, parent): self._mapper.mapped[str].connect(self.update_object) def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" while self._connections_to_rebuild: signal, handler = self._connections_to_rebuild.pop() signal.disconnect(handler) @@ -182,8 +172,7 @@ def dispose(self): EditorWithList.dispose(self) def rebuild_editor(self): - """ Rebuilds the editor after its definition is modified. - """ + """Rebuilds the editor after its definition is modified.""" while self._connections_to_rebuild: signal, handler = self._connections_to_rebuild.pop() signal.disconnect(handler) @@ -239,8 +228,7 @@ def rebuild_editor(self): n -= 1 def update_object(self, label): - """ Handles the user clicking one of the custom check boxes. - """ + """Handles the user clicking one of the custom check boxes.""" cb = self._mapper.mapping(label) cur_value = parse_value(self.value) if cb.checkState() == QtCore.Qt.Checked: @@ -254,8 +242,8 @@ def update_object(self, label): self.value = cur_value def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ new_values = parse_value(self.value) for cb in self.control.findChildren(QtGui.QCheckBox, None): @@ -266,12 +254,10 @@ def update_editor(self): class TextEditor(BaseTextEditor): - """ Text style of editor for checklists, which displays a text field. - """ + """Text style of editor for checklists, which displays a text field.""" def update_object(self, event=None): - """ Handles the user changing the contents of the edit control. - """ + """Handles the user changing the contents of the edit control.""" try: value = str(self.control.text()) value = eval(value) @@ -289,8 +275,7 @@ def update_object(self, event=None): def parse_value(value): - """ Parses a value into a list. - """ + """Parses a value into a list.""" if value is None: return [] if not isinstance(value, str): diff --git a/traitsui/qt4/clipboard.py b/traitsui/qt4/clipboard.py index 39c0849ba..67b3234f8 100644 --- a/traitsui/qt4/clipboard.py +++ b/traitsui/qt4/clipboard.py @@ -35,8 +35,7 @@ class _Clipboard(HasTraits): - """ The _Clipboard class provides a wrapper around the PyQt clipboard. - """ + """The _Clipboard class provides a wrapper around the PyQt clipboard.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -59,8 +58,7 @@ class _Clipboard(HasTraits): # ------------------------------------------------------------------------- def _get_instance(self): - """ The instance getter. - """ + """The instance getter.""" md = PyMimeData.coerce(self.clipboard.mimeData()) if md is None: return None @@ -68,18 +66,15 @@ def _get_instance(self): return md.instance() def _set_instance(self, data): - """ The instance setter. - """ + """The instance setter.""" self.clipboard.setMimeData(PyMimeData(data)) def _get_has_instance(self): - """ The has_instance getter. - """ + """The has_instance getter.""" return self.clipboard.mimeData().hasFormat(PyMimeData.MIME_TYPE) def _get_instance_type(self): - """ The instance_type getter. - """ + """The instance_type getter.""" md = PyMimeData.coerce(self.clipboard.mimeData()) if md is None: return None @@ -91,8 +86,7 @@ def _get_instance_type(self): # ------------------------------------------------------------------------- def _clipboard_default(self): - """ Initialise the clipboard. - """ + """Initialise the clipboard.""" return QtGui.QApplication.clipboard() diff --git a/traitsui/qt4/code_editor.py b/traitsui/qt4/code_editor.py index 1c0b6d840..6131d7da5 100644 --- a/traitsui/qt4/code_editor.py +++ b/traitsui/qt4/code_editor.py @@ -46,7 +46,6 @@ from .helper import pixmap_cache - # Marker line constants: MARK_MARKER = 0 # Marks a marked line SEARCH_MARKER = 1 # Marks a line matching the current search @@ -54,8 +53,7 @@ class SourceEditor(Editor): - """ Editor for source code which uses the advanced code widget. - """ + """Editor for source code which uses the advanced code widget.""" # ------------------------------------------------------------------------- # Pyface PythonEditor interface: @@ -116,8 +114,8 @@ class SourceEditor(Editor): # widget: # ------------------------------------------------------------------------- def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = QtGui.QWidget() layout = QtGui.QVBoxLayout(self.control) @@ -179,8 +177,7 @@ def init(self, parent): self.set_tooltip() def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" # Make sure that the editor does not try to update as the control is # being destroyed: if not self.factory.auto_set: @@ -189,8 +186,7 @@ def dispose(self): super().dispose() def update_object(self): - """ Handles the user entering input data in the edit control. - """ + """Handles the user entering input data in the edit control.""" if not self._locked: try: value = str(self._widget.code.toPlainText()) @@ -201,8 +197,8 @@ def update_object(self): pass def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ self._locked = True new_value = self.value @@ -221,15 +217,14 @@ def update_editor(self): self._locked = False def error(self, excp): - """ Handles an error that occurs while setting the object's trait value. - """ + """Handles an error that occurs while setting the object's trait value.""" pass # -- UI preference save/restore interface --------------------------------- def restore_prefs(self, prefs): - """ Restores any saved user preference information associated with the - editor. + """Restores any saved user preference information associated with the + editor. """ if self.factory.key_bindings is not None: key_bindings = prefs.get("key_bindings") @@ -237,13 +232,11 @@ def restore_prefs(self, prefs): self.factory.key_bindings.merge(key_bindings) def save_prefs(self): - """ Returns any user preference information associated with the editor. - """ + """Returns any user preference information associated with the editor.""" return {"key_bindings": self.factory.key_bindings} def _mark_lines_changed(self): - """ Handles the set of marked lines being changed. - """ + """Handles the set of marked lines being changed.""" # FIXME: Not implemented at this time. return @@ -251,9 +244,7 @@ def _mark_lines_items_changed(self): self._mark_lines_changed() def _selection_changed(self): - self.selected_text = str( - self._widget.code.textCursor().selectedText() - ) + self.selected_text = str(self._widget.code.textCursor().selectedText()) start = self._widget.code.textCursor().selectionStart() end = self._widget.code.textCursor().selectionEnd() @@ -264,8 +255,7 @@ def _selection_changed(self): self.selected_end_pos = end def _selected_line_changed(self): - """ Handles a change in which line is currently selected. - """ + """Handles a change in which line is currently selected.""" control = self._widget line = max(1, min(control.lines(), self.selected_line)) _, column = control.get_line_column() @@ -286,8 +276,7 @@ def _column_changed(self, column): self._widget.set_line_column(line, column) def _position_changed(self): - """ Handles the cursor position being changed. - """ + """Handles the cursor position being changed.""" control = self._widget self._locked = True self.line, self.column = control.get_line_column() @@ -297,8 +286,7 @@ def _position_changed(self): self._widget.centerCursor() def _key_pressed_changed(self, event): - """ Handles a key being pressed within the editor. - """ + """Handles a key being pressed within the editor.""" key_bindings = self.factory.key_bindings if key_bindings: processed = key_bindings.do( diff --git a/traitsui/qt4/color_editor.py b/traitsui/qt4/color_editor.py index 4635392c5..6e2d027f6 100644 --- a/traitsui/qt4/color_editor.py +++ b/traitsui/qt4/color_editor.py @@ -24,7 +24,6 @@ """ - from pyface.qt import QtCore, QtGui from traitsui.editors.color_editor import ( @@ -40,7 +39,6 @@ from .editor import Editor - # Standard color samples: color_samples = [] @@ -55,25 +53,21 @@ class ToolkitEditorFactory(BaseToolkitEditorFactory): - """ PyQt editor factory for color editors. - """ + """PyQt editor factory for color editors.""" def to_qt4_color(self, editor): - """ Gets the PyQt color equivalent of the object trait. - """ + """Gets the PyQt color equivalent of the object trait.""" if self.mapped: return getattr(editor.object, editor.name + "_") return getattr(editor.object, editor.name) def from_qt4_color(self, color): - """ Gets the application equivalent of a PyQt value. - """ + """Gets the application equivalent of a PyQt value.""" return color def str_color(self, color): - """ Returns the text representation of a specified color value. - """ + """Returns the text representation of a specified color value.""" if isinstance(color, QtGui.QColor): alpha = color.alpha() if alpha == 255: @@ -94,14 +88,13 @@ def str_color(self, color): class SimpleColorEditor(BaseSimpleEditor): - """ Simple style of color editor, which displays a text field whose + """Simple style of color editor, which displays a text field whose background color is the color value. Selecting the text field displays a dialog box for selecting a new color value. """ def popup_editor(self): - """ Invokes the pop-up editor for an object trait. - """ + """Invokes the pop-up editor for an object trait.""" color = self.factory.to_qt4_color(self) options = QtGui.QColorDialog.ShowAlphaChannel if not self.factory.use_native_dialog: @@ -115,101 +108,93 @@ def popup_editor(self): self.update_editor() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ super().update_editor() set_color(self) def string_value(self, color): - """ Returns the text representation of a specified color value. - """ + """Returns the text representation of a specified color value.""" return self.factory.str_color(color) class CustomColorEditor(Editor): - """ Custom style of color editor, which displays a color editor panel. - """ + """Custom style of color editor, which displays a color editor panel.""" def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control, self._simple_field = color_editor_for(self, parent) def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" if getattr(self, "_simple_field", None) is not None: self._simple_field.dispose() self._simple_field = None super().dispose() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ self._simple_field.update_editor() def update_object_from_swatch(self, color_text): - """ Updates the object trait when a color swatch is clicked. - """ + """Updates the object trait when a color swatch is clicked.""" color = QtGui.QColor(*[int(part) for part in color_text.split(",")]) self.value = self.factory.from_qt4_color(color) self.update_editor() def string_value(self, color): - """ Returns the text representation of a specified color value. - """ + """Returns the text representation of a specified color value.""" return self.factory.str_color(color) class TextColorEditor(BaseTextEditor): - """ Text style of color editor, which displays a text field whose + """Text style of color editor, which displays a text field whose background color is the color value. """ def update_object(self): - """ Handles the user changing the contents of the edit control. - """ + """Handles the user changing the contents of the edit control.""" self.value = str(self.control.text()) set_color(self) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ super().update_editor() set_color(self) def string_value(self, color): - """ Returns the text representation of a specified color value. - """ + """Returns the text representation of a specified color value.""" return self.factory.str_color(color) class ReadonlyColorEditor(BaseReadonlyEditor): - """ Read-only style of color editor, which displays a read-only text field + """Read-only style of color editor, which displays a read-only text field whose background color is the color value. """ def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = QtGui.QLineEdit() self.control.setReadOnly(True) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ super().update_editor() set_color(self) def string_value(self, color): - """ Returns the text representation of a specified color value. - """ + """Returns the text representation of a specified color value.""" return self.factory.str_color(color) @@ -219,8 +204,7 @@ def string_value(self, color): def set_color(editor): - """ Sets the color of the specified color control. - """ + """Sets the color of the specified color control.""" color = editor.factory.to_qt4_color(editor) pal = QtGui.QPalette(editor.control.palette()) @@ -240,7 +224,7 @@ def set_color(editor): class FixedButton(QtGui.QPushButton): - """ Override to work around a bug in Qt 4.7 on Macs. + """Override to work around a bug in Qt 4.7 on Macs. https://bugreports.qt-project.org/browse/QTBUG-15936 """ @@ -250,8 +234,7 @@ def hitButton(self, pos): def color_editor_for(editor, parent): - """ Creates a custom color editor panel for a specified editor. - """ + """Creates a custom color editor panel for a specified editor.""" # Create the colour samples if it hasn't already been done. if len(color_samples) == 0: color_choices = (0, 128, 192, 255) diff --git a/traitsui/qt4/color_trait.py b/traitsui/qt4/color_trait.py index 06c9d5ebc..8f75b52e0 100644 --- a/traitsui/qt4/color_trait.py +++ b/traitsui/qt4/color_trait.py @@ -29,10 +29,8 @@ from traits.api import Trait, TraitError - def convert_to_color(object, name, value): - """ Converts a number into a QColor object. - """ + """Converts a number into a QColor object.""" # Try the toolkit agnostic format. try: tup = eval(value) @@ -101,8 +99,7 @@ def get_color_editor(*args, **traits): def PyQtColor(default="white", allow_none=False, **metadata): - """ Defines PyQt-specific color traits. - """ + """Defines PyQt-specific color traits.""" if default is None: allow_none = True @@ -113,7 +110,7 @@ def PyQtColor(default="white", allow_none=False, **metadata): standard_colors, convert_to_color, editor=get_color_editor, - **metadata + **metadata, ) return Trait( @@ -121,5 +118,5 @@ def PyQtColor(default="white", allow_none=False, **metadata): standard_colors, convert_to_color, editor=get_color_editor, - **metadata + **metadata, ) diff --git a/traitsui/qt4/compound_editor.py b/traitsui/qt4/compound_editor.py index 413597c54..49b7f1b8f 100644 --- a/traitsui/qt4/compound_editor.py +++ b/traitsui/qt4/compound_editor.py @@ -33,7 +33,7 @@ class CompoundEditor(Editor): - """ Editor for compound traits, which displays editors for each of the + """Editor for compound traits, which displays editors for each of the combined traits, in the appropriate style. """ @@ -45,8 +45,8 @@ class CompoundEditor(Editor): kind = Str() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = QtGui.QWidget() layout = QtGui.QVBoxLayout(self.control) @@ -63,14 +63,13 @@ def init(self, parent): editors.append(editor) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ pass def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" for editor in self._editors: editor.dispose() diff --git a/traitsui/qt4/csv_list_editor.py b/traitsui/qt4/csv_list_editor.py index 4970b8449..33e478800 100644 --- a/traitsui/qt4/csv_list_editor.py +++ b/traitsui/qt4/csv_list_editor.py @@ -21,21 +21,21 @@ class SimpleEditor(QtSimpleEditor): - """ Simple Editor style for CSVListEditor. """ + """Simple Editor style for CSVListEditor.""" prepare = _prepare_method dispose = _dispose_method class CustomEditor(QtCustomEditor): - """ Custom Editor style for CSVListEditor. """ + """Custom Editor style for CSVListEditor.""" prepare = _prepare_method dispose = _dispose_method class ReadonlyEditor(QtReadonlyEditor): - """ Readonly Editor style for CSVListEditor. """ + """Readonly Editor style for CSVListEditor.""" prepare = _prepare_method dispose = _dispose_method diff --git a/traitsui/qt4/custom_editor.py b/traitsui/qt4/custom_editor.py index 7e4a9e918..ba462c89f 100644 --- a/traitsui/qt4/custom_editor.py +++ b/traitsui/qt4/custom_editor.py @@ -35,8 +35,7 @@ class CustomEditor(Editor): - """ Wrapper for a custom editor control - """ + """Wrapper for a custom editor control""" # ------------------------------------------------------------------------- # Finishes initializing the editor by creating the underlying toolkit @@ -44,8 +43,8 @@ class CustomEditor(Editor): # ------------------------------------------------------------------------- def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory.factory if factory is not None: @@ -63,7 +62,7 @@ def init(self, parent): # ------------------------------------------------------------------------- def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ pass diff --git a/traitsui/qt4/data_frame_editor.py b/traitsui/qt4/data_frame_editor.py index 90101a895..6d6b6a5fe 100644 --- a/traitsui/qt4/data_frame_editor.py +++ b/traitsui/qt4/data_frame_editor.py @@ -16,6 +16,6 @@ class _DataFrameEditor(BaseDataFrameEditor, UIEditor): - """ Qt Toolkit implementation of the DataFrameEditor """ + """Qt Toolkit implementation of the DataFrameEditor""" pass diff --git a/traitsui/qt4/date_editor.py b/traitsui/qt4/date_editor.py index f5fba27dd..c102005d0 100644 --- a/traitsui/qt4/date_editor.py +++ b/traitsui/qt4/date_editor.py @@ -12,7 +12,6 @@ """ - import datetime from pyface.qt import QtCore, QtGui @@ -23,15 +22,12 @@ from traitsui.editors.date_editor import CellFormat - - class SimpleEditor(Editor): - """ Simple Traits UI date editor that wraps QDateEdit. - """ + """Simple Traits UI date editor that wraps QDateEdit.""" def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = QtGui.QDateEdit() if hasattr(self.factory, "qt_date_format"): @@ -71,14 +67,14 @@ def init(self, parent): self.control.dateChanged.connect(self.update_object) def dispose(self): - """ Disposes of the contents of an editor.""" + """Disposes of the contents of an editor.""" if self.control is not None: self.control.dateChanged.disconnect(self.update_object) super().dispose() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ value = self.value if value: @@ -86,14 +82,12 @@ def update_editor(self): self.control.setDate(q_date) def update_object(self, q_date): - """ Handles the user entering input data in the edit control. - """ + """Handles the user entering input data in the edit control.""" self.value = datetime.date(q_date.year(), q_date.month(), q_date.day()) class CustomEditor(Editor): - """ Custom Traits UI date editor that wraps QCalendarWidget. - """ + """Custom Traits UI date editor that wraps QCalendarWidget.""" #: Style used for when a date is unselected. #: Mapping from datetime.date to CellFormat @@ -103,8 +97,8 @@ class CustomEditor(Editor): _selected = Set(Date) def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = QtGui.QCalendarWidget() @@ -114,14 +108,14 @@ def init(self, parent): self.control.clicked.connect(self.update_object) def dispose(self): - """ Disposes of the contents of an editor.""" + """Disposes of the contents of an editor.""" if self.control is not None: self.control.clicked.disconnect(self.update_object) super().dispose() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ value = self.value if value: @@ -135,8 +129,7 @@ def update_editor(self): self._selected = set(value) def update_object(self, q_date): - """ Handles the user entering input data in the edit control. - """ + """Handles the user entering input data in the edit control.""" value = datetime.date(q_date.year(), q_date.month(), q_date.day()) if self.factory.multi_select: if value in self.value: @@ -158,7 +151,7 @@ def select_date(self, date): self.apply_style(self.factory.selected_style, date) def set_unselected_style(self, style, date): - """ Set the style used for a date when it is not selected.""" + """Set the style used for a date when it is not selected.""" self._unselected_styles[date] = style if self.factory.multi_select: if date not in self.value: @@ -167,14 +160,14 @@ def set_unselected_style(self, style, date): self.apply_style(style, date) def apply_style(self, style, date): - """ Apply a given style to a given date.""" + """Apply a given style to a given date.""" qdt = QtCore.QDate(date) textformat = self.control.dateTextFormat(qdt) _apply_cellformat(style, textformat) self.control.setDateTextFormat(qdt, textformat) def apply_unselected_style(self, date): - """ Apply the style for when a date is unselected.""" + """Apply the style for when a date is unselected.""" # Resets the text format on the given dates textformat = QtGui.QTextCharFormat() if date in self._unselected_styles: @@ -183,8 +176,7 @@ def apply_unselected_style(self, date): self.control.setDateTextFormat(qdt, textformat) def apply_unselected_style_to_all(self): - """ Make all the selected dates appear unselected. - """ + """Make all the selected dates appear unselected.""" for date in self._selected: self.apply_unselected_style(date) @@ -195,12 +187,10 @@ def apply_unselected_style_to_all(self): class ReadonlyEditor(BaseReadonlyEditor): - """ Readonly Traits UI date editor that uses a QLabel for the view. - """ + """Readonly Traits UI date editor that uses a QLabel for the view.""" def _get_str_value(self): - """ Replace the default string value with our own date verision. - """ + """Replace the default string value with our own date verision.""" if not self.value: return self.factory.message else: @@ -213,7 +203,7 @@ def _get_str_value(self): def _apply_cellformat(cf, textformat): - """ Applies the formatting in the cellformat cf to the QTextCharFormat + """Applies the formatting in the cellformat cf to the QTextCharFormat object provided. """ if cf.italics is not None: @@ -237,7 +227,7 @@ def _apply_cellformat(cf, textformat): def _textformat_to_cellformat(textformat): - """ Convert QTextCharFormat to a CellFormat """ + """Convert QTextCharFormat to a CellFormat""" bg_brush = textformat.background() fg_brush = textformat.foreground() return CellFormat( @@ -250,7 +240,7 @@ def _textformat_to_cellformat(textformat): def _color_to_brush(color): - """ Returns a QBrush with the color specified in **color** """ + """Returns a QBrush with the color specified in **color**""" brush = QtGui.QBrush() if isinstance(color, str) and hasattr(QtCore.Qt, color): col = getattr(QtCore.Qt, color) diff --git a/traitsui/qt4/date_range_editor.py b/traitsui/qt4/date_range_editor.py index fcd9a59e2..a9c927597 100644 --- a/traitsui/qt4/date_range_editor.py +++ b/traitsui/qt4/date_range_editor.py @@ -18,7 +18,6 @@ from .date_editor import CustomEditor as DateCustomEditor - class CustomEditor(DateCustomEditor): def init(self, parent): if not self.factory.multi_select: @@ -27,8 +26,8 @@ def init(self, parent): super().init(parent) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ start_date, end_date = self.value if start_date is not None and end_date is not None: @@ -42,8 +41,7 @@ def update_editor(self): ) def update_object(self, q_date): - """ Handles the user entering input data in the edit control. - """ + """Handles the user entering input data in the edit control.""" value = datetime.date(q_date.year(), q_date.month(), q_date.day()) start_date, end_date = self.value diff --git a/traitsui/qt4/datetime_editor.py b/traitsui/qt4/datetime_editor.py index 0f0450dc1..03c4e7721 100644 --- a/traitsui/qt4/datetime_editor.py +++ b/traitsui/qt4/datetime_editor.py @@ -21,8 +21,7 @@ class SimpleEditor(Editor): - """ Simple Traits UI time editor that wraps QDateTimeEdit. - """ + """Simple Traits UI time editor that wraps QDateTimeEdit.""" #: the earliest datetime allowed by the editor minimum_datetime = Datetime @@ -31,8 +30,8 @@ class SimpleEditor(Editor): maximum_datetime = Datetime def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ # set min and max early, don't wait for editor sync self.minimum_datetime = self.factory.minimum_datetime @@ -44,15 +43,14 @@ def init(self, parent): self.update_maximum_datetime() def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" if self.control is not None: self.control.dateTimeChanged.disconnect(self.update_object) super().dispose() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ value = self.value if value: @@ -68,8 +66,7 @@ def update_editor(self): self.value = value def update_object(self, q_datetime): - """ Handles the user entering input data in the edit control. - """ + """Handles the user entering input data in the edit control.""" try: if qt_api == 'pyside2': self.value = q_datetime.toPython() @@ -81,15 +78,17 @@ def update_object(self, q_datetime): @observe('minimum_datetime') def update_minimum_datetime(self, event=None): # sanity checking of values - if (self.minimum_datetime is not None - and self.maximum_datetime is not None - and self.minimum_datetime > self.maximum_datetime): + if ( + self.minimum_datetime is not None + and self.maximum_datetime is not None + and self.minimum_datetime > self.maximum_datetime + ): self.maximum_datetime = self.minimum_datetime if self.control is not None: if self.minimum_datetime is not None: self.control.setMinimumDateTime( - QDateTime(self.minimum_datetime) + QDateTime(self.minimum_datetime) ) else: self.control.clearMinimumDateTime() @@ -97,9 +96,11 @@ def update_minimum_datetime(self, event=None): @observe('maximum_datetime') def update_maximum_datetime(self, event=None): # sanity checking of values - if (self.minimum_datetime is not None - and self.maximum_datetime is not None - and self.minimum_datetime > self.maximum_datetime): + if ( + self.minimum_datetime is not None + and self.maximum_datetime is not None + and self.minimum_datetime > self.maximum_datetime + ): self.minimum_datetime = self.maximum_datetime if self.control is not None: @@ -112,12 +113,10 @@ def update_maximum_datetime(self, event=None): class ReadonlyEditor(BaseReadonlyEditor): - """ Readonly Traits UI time editor that uses a QLabel for the view. - """ + """Readonly Traits UI time editor that uses a QLabel for the view.""" def _get_str_value(self): - """ Replace the default string value with our own time version. - """ + """Replace the default string value with our own time version.""" if not self.value: return self.factory.message else: diff --git a/traitsui/qt4/directory_editor.py b/traitsui/qt4/directory_editor.py index 72da79689..d9128b126 100644 --- a/traitsui/qt4/directory_editor.py +++ b/traitsui/qt4/directory_editor.py @@ -28,15 +28,13 @@ ) - class SimpleEditor(SimpleFileEditor): - """ Simple style of editor for directories, which displays a text field - and a **Browse** button that opens a directory-selection dialog box. + """Simple style of editor for directories, which displays a text field + and a **Browse** button that opens a directory-selection dialog box. """ def _create_file_dialog(self): - """ Creates the correct type of file dialog. - """ + """Creates the correct type of file dialog.""" dlg = QtGui.QFileDialog(self.control) dlg.selectFile(self._file_name.text()) dlg.setFileMode(QtGui.QFileDialog.Directory) @@ -46,8 +44,8 @@ def _create_file_dialog(self): class CustomEditor(CustomFileEditor): - """ Custom style of editor for directories, which displays a tree view of - the file system. + """Custom style of editor for directories, which displays a tree view of + the file system. """ def init(self, parent): @@ -56,8 +54,7 @@ def init(self, parent): self._model.setNameFilters([""]) def update_object(self, idx): - """ Handles the user changing the contents of the edit control. - """ + """Handles the user changing the contents of the edit control.""" if self.control is not None: if self._model.isDir(idx): self.value = str(self._model.filePath(idx)) @@ -65,7 +62,6 @@ def update_object(self, idx): # Trait change handlers -------------------------------------------------- def _filter_changed(self): - """ Handles the 'filter' trait being changed. - """ + """Handles the 'filter' trait being changed.""" # name filters don't apply to directories pass diff --git a/traitsui/qt4/drop_editor.py b/traitsui/qt4/drop_editor.py index 2c84fc43f..b0ba5fd9c 100644 --- a/traitsui/qt4/drop_editor.py +++ b/traitsui/qt4/drop_editor.py @@ -34,7 +34,7 @@ class SimpleEditor(Editor): - """ Simple style of drop editor, which displays a read-only text field that + """Simple style of drop editor, which displays a read-only text field that contains the string representation of the object trait's value. """ @@ -42,8 +42,8 @@ class SimpleEditor(Editor): ok_color = DropColor def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ if self.factory.readonly: self.control = QtGui.QLineEdit(self.str_value) @@ -63,8 +63,7 @@ def init(self, parent): self.control._qt4_editor = self def dispose(self): - """ Disposes of the content of an editor. - """ + """Disposes of the content of an editor.""" if self.factory.readonly: # enthought/traitsui#884 _BaseEditor.dispose(self) @@ -72,15 +71,13 @@ def dispose(self): super().dispose() def string_value(self, value): - """ Returns the text representation of a specified object trait value. - """ + """Returns the text representation of a specified object trait value.""" if value is None: return "" return str(value) def error(self, excp): - """ Handles an error that occurs while setting the object's trait value. - """ + """Handles an error that occurs while setting the object's trait value.""" pass @@ -94,8 +91,7 @@ def eventFilter(self, source, event): return super().eventFilter(source, event) def dropEvent(self, e): - """ Handles a Python object being dropped on the tree. - """ + """Handles a Python object being dropped on the tree.""" editor = self.parent()._qt4_editor klass = editor.factory.klass @@ -122,8 +118,7 @@ def dropEvent(self, e): e.acceptProposedAction() def dragEnterEvent(self, e): - """ Handles a Python object being dragged over the tree. - """ + """Handles a Python object being dragged over the tree.""" editor = self.parent()._qt4_editor if editor.factory.binding: diff --git a/traitsui/qt4/editor.py b/traitsui/qt4/editor.py index 7144c8575..a73e65158 100644 --- a/traitsui/qt4/editor.py +++ b/traitsui/qt4/editor.py @@ -34,12 +34,10 @@ class Editor(UIEditor): - """ Base class for PyQt editors for Traits-based UIs. - """ + """Base class for PyQt editors for Traits-based UIs.""" def clear_layout(self): - """ Delete the contents of a control's layout. - """ + """Delete the contents of a control's layout.""" layout = self.control.layout() while True: itm = layout.takeAt(0) @@ -49,29 +47,26 @@ def clear_layout(self): itm.widget().setParent(None) def _control_changed(self, control): - """ Handles the **control** trait being set. - """ + """Handles the **control** trait being set.""" # FIXME: Check we actually make use of this. if control is not None: control._editor = self def set_focus(self): - """ Assigns focus to the editor's underlying toolkit widget. - """ + """Assigns focus to the editor's underlying toolkit widget.""" if self.control is not None: self.control.setFocus() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ new_value = self.str_value if self.control.text() != new_value: self.control.setText(new_value) def error(self, excp): - """ Handles an error that occurs while setting the object's trait value. - """ + """Handles an error that occurs while setting the object's trait value.""" # Make sure the control is a widget rather than a layout. if isinstance(self.control, QtGui.QLayout): control = self.control.parentWidget() @@ -83,20 +78,18 @@ def error(self, excp): self.description + " value error", str(excp), buttons=QtGui.QMessageBox.Ok, - parent=control + parent=control, ) message_box.setTextFormat(QtCore.Qt.PlainText) message_box.setEscapeButton(QtGui.QMessageBox.Ok) message_box.exec_() def set_tooltip_text(self, control, text): - """ Sets the tooltip for a specified control. - """ + """Sets the tooltip for a specified control.""" control.setToolTip(text) def _enabled_changed(self, enabled): - """Handles the **enabled** state of the editor being changed. - """ + """Handles the **enabled** state of the editor being changed.""" if self.control is not None: self._enabled_changed_helper(self.control, enabled) if self.label_control is not None: @@ -104,7 +97,7 @@ def _enabled_changed(self, enabled): def _enabled_changed_helper(self, control, enabled): """A helper that allows the control to be a layout and recursively - manages all its widgets. + manages all its widgets. """ if isinstance(control, QtGui.QWidget): control.setEnabled(enabled) @@ -116,8 +109,7 @@ def _enabled_changed_helper(self, control, enabled): ) def _visible_changed(self, visible): - """Handles the **visible** state of the editor being changed. - """ + """Handles the **visible** state of the editor being changed.""" if self.label_control is not None: self.label_control.setVisible(visible) if self.control is None: @@ -173,7 +165,7 @@ def _visible_changed(self, visible): def _visible_changed_helper(self, control, visible): """A helper that allows the control to be a layout and recursively - manages all its widgets. + manages all its widgets. """ if isinstance(control, QtGui.QWidget): control.setVisible(visible) @@ -185,18 +177,15 @@ def _visible_changed_helper(self, control, visible): ) def get_error_control(self): - """ Returns the editor's control for indicating error status. - """ + """Returns the editor's control for indicating error status.""" return self.control def in_error_state(self): - """ Returns whether or not the editor is in an error state. - """ + """Returns whether or not the editor is in an error state.""" return False def set_error_state(self, state=None, control=None): - """ Sets the editor's current error state. - """ + """Sets the editor's current error state.""" if state is None: state = self.invalid state = state or self.in_error_state() @@ -226,13 +215,11 @@ def set_error_state(self, state=None, control=None): item.setPalette(pal) def _invalid_changed(self, state): - """ Handles the editor's invalid state changing. - """ + """Handles the editor's invalid state changing.""" self.set_error_state() def perform(self, action, action_event=None): - """ Performs the action described by a specified Action object. - """ + """Performs the action described by a specified Action object.""" self.ui.do_undoable(self._perform, action) def _perform(self, action): @@ -266,7 +253,7 @@ def _perform(self, action): action.perform(selection) def eval_when(self, condition, object, trait): - """ Evaluates a condition within a defined context, and sets a + """Evaluates a condition within a defined context, and sets a specified object trait based on the result, which is assumed to be a Boolean. """ @@ -282,15 +269,13 @@ def eval_when(self, condition, object, trait): setattr(object, trait, value) def add_to_menu(self, menu_item): - """ Adds a menu item to the menu bar being constructed. - """ + """Adds a menu item to the menu bar being constructed.""" action = menu_item.item.action self.eval_when(action.enabled_when, menu_item, "enabled") self.eval_when(action.checked_when, menu_item, "checked") def can_add_to_menu(self, action): - """ Returns whether the action should be defined in the user interface. - """ + """Returns whether the action should be defined in the user interface.""" if action.defined_when != "": try: @@ -319,7 +304,7 @@ def can_add_to_menu(self, action): # TODO: move this method, it should be part of ui_panel or some other # place that is responsible for setting up the Qt layout. def set_size_policy(self, direction, resizable, springy, stretch): - """ Set the size policy of the editor's controller. + """Set the size policy of the editor's controller. Based on the "direction" of the group that contains this editor (VGroup or HGroup), set the stretch factor and the resizing @@ -366,8 +351,7 @@ def set_size_policy(self, direction, resizable, springy, stretch): class EditorWithList(Editor): - """ Editor for an object that contains a list. - """ + """Editor for an object that contains a list.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -383,14 +367,15 @@ class EditorWithList(Editor): list_value = Callable() def init(self, parent): - """ Initializes the object. - """ + """Initializes the object.""" factory = self.factory name = factory.name if name != "": - self.list_object, self.list_name, self.list_value = self.parse_extended_name( - name - ) + ( + self.list_object, + self.list_name, + self.list_value, + ) = self.parse_extended_name(name) else: self.list_object, self.list_name = factory, "values" self.list_value = lambda: factory.values @@ -405,8 +390,7 @@ def init(self, parent): self._list_updated() def dispose(self): - """ Disconnects the listeners set up by the constructor. - """ + """Disconnects the listeners set up by the constructor.""" self.list_object.on_trait_change( self._list_updated, self.list_name, remove=True ) @@ -417,23 +401,19 @@ def dispose(self): super().dispose() def _list_updated(self): - """ Handles the monitored trait being updated. - """ + """Handles the monitored trait being updated.""" self.list_updated(self.list_value()) def list_updated(self, values): - """ Handles the monitored list being updated. - """ + """Handles the monitored list being updated.""" raise NotImplementedError class EditorFromView(Editor): - """ An editor generated from a View object. - """ + """An editor generated from a View object.""" def init(self, parent): - """ Initializes the object. - """ + """Initializes the object.""" self._ui = ui = self.init_ui(parent) if ui.history is None: ui.history = self.ui.history @@ -441,22 +421,21 @@ def init(self, parent): self.control = ui.control def init_ui(self, parent): - """ Creates and returns the traits UI defined by this editor. - (Must be overridden by a subclass). + """Creates and returns the traits UI defined by this editor. + (Must be overridden by a subclass). """ raise NotImplementedError def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ # Normally nothing needs to be done here, since it should all be handled # by the editor's internally created traits UI: pass def dispose(self): - """ Disposes of the editor. - """ + """Disposes of the editor.""" self._ui.dispose() super().dispose() diff --git a/traitsui/qt4/editor_factory.py b/traitsui/qt4/editor_factory.py index 0bc23000f..f2a273b0f 100644 --- a/traitsui/qt4/editor_factory.py +++ b/traitsui/qt4/editor_factory.py @@ -33,15 +33,15 @@ class SimpleEditor(Editor): - """ Base class for simple style editors, which displays a text field + """Base class for simple style editors, which displays a text field containing the text representation of the object trait value. Clicking in the text field displays an editor-specific dialog box for changing the value. """ def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = _SimpleField(self) self.set_tooltip() @@ -53,34 +53,31 @@ def init(self, parent): # ------------------------------------------------------------------------- def popup_editor(self): - """ Invokes the pop-up editor for an object trait. - """ + """Invokes the pop-up editor for an object trait.""" pass class TextEditor(Editor): - """ Base class for text style editors, which displays an editable text + """Base class for text style editors, which displays an editable text field, containing a text representation of the object trait value. """ def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = QtGui.QLineEdit(self.str_value) self.control.editingFinished.connect(self.update_object) self.set_tooltip() def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" if self.control is not None: self.control.editingFinished.disconnect(self.update_object) super().dispose() def update_object(self): - """ Handles the user changing the contents of the edit control. - """ + """Handles the user changing the contents of the edit control.""" if self.control is None: return try: @@ -90,7 +87,7 @@ def update_object(self): class ReadonlyEditor(Editor): - """ Base class for read-only style editors, which displays a read-only text + """Base class for read-only style editors, which displays a read-only text field, containing a text representation of the object trait value. """ @@ -111,8 +108,8 @@ class ReadonlyEditor(Editor): } def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = QtGui.QLabel(self.str_value) @@ -134,8 +131,8 @@ def init(self, parent): self.set_tooltip() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ self.control.setText(self.str_value) diff --git a/traitsui/qt4/enum_editor.py b/traitsui/qt4/enum_editor.py index d56c5fdc9..a9a18a4e8 100644 --- a/traitsui/qt4/enum_editor.py +++ b/traitsui/qt4/enum_editor.py @@ -27,7 +27,6 @@ from functools import reduce - from pyface.qt import QtCore, QtGui from traits.api import Bool, Property @@ -43,8 +42,7 @@ class BaseEditor(Editor): - """ Base class for enumeration editors. - """ + """Base class for enumeration editors.""" #: Current set of enumeration names: names = Property() @@ -60,18 +58,20 @@ class BaseEditor(Editor): # ------------------------------------------------------------------------- def values_changed(self): - """ Recomputes the cached data based on the underlying enumeration model - or the values of the factory. + """Recomputes the cached data based on the underlying enumeration model + or the values of the factory. """ - self._names, self._mapping, self._inverse_mapping = enum_values_changed( - self._value(), self.string_value - ) + ( + self._names, + self._mapping, + self._inverse_mapping, + ) = enum_values_changed(self._value(), self.string_value) def rebuild_editor(self): - """ Rebuilds the contents of the editor whenever the original factory - object's **values** trait changes. + """Rebuilds the contents of the editor whenever the original factory + object's **values** trait changes. - This is not needed for the Qt backends. + This is not needed for the Qt backends. """ raise NotImplementedError @@ -80,8 +80,8 @@ def rebuild_editor(self): # ------------------------------------------------------------------------- def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory if factory.name != "": @@ -92,7 +92,7 @@ def init(self, parent): self._object.observe( self._update_values_and_rebuild_editor, self._name + '.items', - dispatch="ui" + dispatch="ui", ) else: self._value = lambda: self.factory.values @@ -102,21 +102,20 @@ def init(self, parent): ) def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" if self._object is not None: self._object.observe( self._update_values_and_rebuild_editor, self._name + '.items', remove=True, - dispatch="ui" + dispatch="ui", ) else: self.factory.observe( self._update_values_and_rebuild_editor, "values", remove=True, - dispatch="ui" + dispatch="ui", ) super().dispose() @@ -128,41 +127,37 @@ def dispose(self): # Trait default handlers ------------------------------------------------- def _get_names(self): - """ Gets the current set of enumeration names. - """ + """Gets the current set of enumeration names.""" return self._names def _get_mapping(self): - """ Gets the current mapping. - """ + """Gets the current mapping.""" return self._mapping def _get_inverse_mapping(self): - """ Gets the current inverse mapping. - """ + """Gets the current inverse mapping.""" return self._inverse_mapping # Trait change handlers -------------------------------------------------- def _update_values_and_rebuild_editor(self, event): - """ Handles the underlying object model's enumeration set or factory's - values being changed. + """Handles the underlying object model's enumeration set or factory's + values being changed. """ self.values_changed() self.rebuild_editor() class SimpleEditor(BaseEditor): - """ Simple style of enumeration editor, which displays a combo box. - """ + """Simple style of enumeration editor, which displays a combo box.""" # ------------------------------------------------------------------------- # Editor Interface # ------------------------------------------------------------------------- def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ super().init(parent) @@ -188,8 +183,8 @@ def init(self, parent): self.set_tooltip() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ if self._no_enum_update == 0: self._no_enum_update += 1 @@ -207,13 +202,12 @@ def update_editor(self): self._no_enum_update -= 1 def error(self, excp): - """ Handles an error that occurs while setting the object's trait value. - """ + """Handles an error that occurs while setting the object's trait value.""" self._set_background(ErrorColor) def rebuild_editor(self): - """ Rebuilds the contents of the editor whenever the original factory - object's **values** trait changes. + """Rebuilds the contents of the editor whenever the original factory + object's **values** trait changes. """ self.control.blockSignals(True) try: @@ -239,8 +233,7 @@ def set_size_policy(self, direction, resizable, springy, stretch): # ------------------------------------------------------------------------- def create_combo_box(self): - """ Returns the QComboBox used for the editor control. - """ + """Returns the QComboBox used for the editor control.""" control = QtGui.QComboBox() control.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToContents) control.setSizePolicy( @@ -257,8 +250,7 @@ def _set_background(self, col): # Signal handlers ------------------------------------------------------- def update_object(self, text): - """ Handles the user selecting a new value from the combo box. - """ + """Handles the user selecting a new value from the combo box.""" if self._no_enum_update == 0: self._no_enum_update += 1 try: @@ -270,8 +262,7 @@ def update_object(self, text): self._no_enum_update -= 1 def update_text_object(self, text): - """ Handles the user typing text into the combo box text entry field. - """ + """Handles the user typing text into the combo box text entry field.""" if self._no_enum_update == 0: value = str(text) @@ -302,8 +293,8 @@ def update_autoset_text_object(self): class RadioEditor(BaseEditor): - """ Enumeration editor, used for the "custom" style, that displays radio - buttons. + """Enumeration editor, used for the "custom" style, that displays radio + buttons. """ #: Is the button layout row-major or column-major? @@ -314,8 +305,8 @@ class RadioEditor(BaseEditor): # ------------------------------------------------------------------------- def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ super().init(parent) @@ -329,8 +320,8 @@ def init(self, parent): self.rebuild_editor() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ layout = self.control.layout() value = self.value @@ -339,8 +330,8 @@ def update_editor(self): rb.setChecked(rb.value == value) def rebuild_editor(self): - """ Rebuilds the contents of the editor whenever the original factory - object's **values** trait changes. + """Rebuilds the contents of the editor whenever the original factory + object's **values** trait changes. """ # Clear any existing content: self.clear_layout() @@ -401,16 +392,14 @@ def rebuild_editor(self): # ------------------------------------------------------------------------- def create_button(self, name): - """ Returns the QAbstractButton used for the radio button. - """ + """Returns the QAbstractButton used for the radio button.""" label = self.string_value(name, str.capitalize) return QtGui.QRadioButton(label) # Signal handlers ------------------------------------------------------- def update_object(self, index): - """ Handles the user clicking one of the custom radio buttons. - """ + """Handles the user clicking one of the custom radio buttons.""" try: self.value = self.mapping[self.names[index]] except Exception: @@ -418,8 +407,8 @@ def update_object(self, index): class ListEditor(BaseEditor): - """ Enumeration editor, used for the "custom" style, that displays a list - box. + """Enumeration editor, used for the "custom" style, that displays a list + box. """ # ------------------------------------------------------------------------- @@ -427,8 +416,8 @@ class ListEditor(BaseEditor): # ------------------------------------------------------------------------- def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ super().init(parent) @@ -439,8 +428,8 @@ def init(self, parent): self.set_tooltip() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ control = self.control try: @@ -457,8 +446,8 @@ def update_editor(self): pass def rebuild_editor(self): - """ Rebuilds the contents of the editor whenever the original factory - object's **values** trait changes. + """Rebuilds the contents of the editor whenever the original factory + object's **values** trait changes. """ self.control.blockSignals(True) @@ -476,8 +465,7 @@ def rebuild_editor(self): # Signal handlers ------------------------------------------------------- def update_object(self, text): - """ Handles the user selecting a list box item. - """ + """Handles the user selecting a list box item.""" value = str(text) try: value = self.mapping[value] diff --git a/traitsui/qt4/extra/bounds_editor.py b/traitsui/qt4/extra/bounds_editor.py index 40cd68088..06788227b 100644 --- a/traitsui/qt4/extra/bounds_editor.py +++ b/traitsui/qt4/extra/bounds_editor.py @@ -17,7 +17,6 @@ from traitsui.qt4.extra.range_slider import RangeSlider - class _BoundsEditor(Editor): evaluate = Any() @@ -29,8 +28,8 @@ class _BoundsEditor(Editor): format = Str() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory if not factory.low_name: diff --git a/traitsui/qt4/extra/checkbox_renderer.py b/traitsui/qt4/extra/checkbox_renderer.py index 975f8aeed..c2057999c 100644 --- a/traitsui/qt4/extra/checkbox_renderer.py +++ b/traitsui/qt4/extra/checkbox_renderer.py @@ -20,8 +20,8 @@ class CheckboxRenderer(TableDelegate): - """ A renderer which displays a checked-box for a True value and an - unchecked box for a false value. + """A renderer which displays a checked-box for a True value and an + unchecked box for a false value. """ # ------------------------------------------------------------------------- @@ -29,8 +29,7 @@ class CheckboxRenderer(TableDelegate): # ------------------------------------------------------------------------- def editorEvent(self, event, model, option, index): - """ Reimplemented to handle mouse button clicks. - """ + """Reimplemented to handle mouse button clicks.""" if ( event.type() == QtCore.QEvent.MouseButtonRelease and event.button() == QtCore.Qt.LeftButton @@ -44,8 +43,7 @@ def editorEvent(self, event, model, option, index): return False def paint(self, painter, option, index): - """ Reimplemented to paint the checkbox. - """ + """Reimplemented to paint the checkbox.""" # Determine whether the checkbox is check or unchecked column = index.model()._editor.columns[index.column()] obj = index.data(QtCore.Qt.UserRole) @@ -111,8 +109,7 @@ def paint(self, painter, option, index): painter.restore() def sizeHint(self, option, index): - """ Reimplemented to provide size hint based on a checkbox - """ + """Reimplemented to provide size hint based on a checkbox""" box = QtGui.QStyleOptionButton() style = QtGui.QApplication.instance().style() return style.sizeFromContents( diff --git a/traitsui/qt4/extra/progress_renderer.py b/traitsui/qt4/extra/progress_renderer.py index 1b05ad332..34e8273eb 100644 --- a/traitsui/qt4/extra/progress_renderer.py +++ b/traitsui/qt4/extra/progress_renderer.py @@ -18,15 +18,14 @@ class ProgressRenderer(TableDelegate): - """ A renderer which displays a progress bar. - """ + """A renderer which displays a progress bar.""" # ------------------------------------------------------------------------- # QAbstractItemDelegate interface # ------------------------------------------------------------------------- def paint(self, painter, option, index): - """ Paint the progressbar. """ + """Paint the progressbar.""" # Get the column and object column = index.model()._editor.columns[index.column()] obj = index.data(QtCore.Qt.UserRole) diff --git a/traitsui/qt4/extra/qt_view.py b/traitsui/qt4/extra/qt_view.py index 12e92b4e4..4a3699dc5 100644 --- a/traitsui/qt4/extra/qt_view.py +++ b/traitsui/qt4/extra/qt_view.py @@ -28,8 +28,7 @@ class QtView(View): - """ A View that allows the specification of Qt style sheets. - """ + """A View that allows the specification of Qt style sheets.""" #: An optional string containing a Qt style sheet. style_sheet = Str() diff --git a/traitsui/qt4/extra/range_slider.py b/traitsui/qt4/extra/range_slider.py index 2d90fd1d8..830b920a0 100644 --- a/traitsui/qt4/extra/range_slider.py +++ b/traitsui/qt4/extra/range_slider.py @@ -12,14 +12,14 @@ class RangeSlider(QtGui.QSlider): - """ A slider for ranges. + """A slider for ranges. - This class provides a dual-slider for ranges, where there is a defined - maximum and minimum, as is a normal slider, but instead of having a - single slider value, there are 2 slider values. + This class provides a dual-slider for ranges, where there is a defined + maximum and minimum, as is a normal slider, but instead of having a + single slider value, there are 2 slider values. - This class emits the same signals as the QSlider base class, with the - exception of valueChanged + This class emits the same signals as the QSlider base class, with the + exception of valueChanged """ def __init__(self, *args): diff --git a/traitsui/qt4/extra/table_image_renderer.py b/traitsui/qt4/extra/table_image_renderer.py index 1f08056ee..6dd074d19 100644 --- a/traitsui/qt4/extra/table_image_renderer.py +++ b/traitsui/qt4/extra/table_image_renderer.py @@ -21,8 +21,8 @@ class TableImageRenderer(TableDelegate): - """ A renderer which will display a cell-specific image in addition to some - text displayed in the same way the default renderer would. + """A renderer which will display a cell-specific image in addition to some + text displayed in the same way the default renderer would. """ #: Should the image be scaled to the size of the cell @@ -33,8 +33,8 @@ class TableImageRenderer(TableDelegate): # ------------------------------------------------------------------------- def get_image_for_obj(self, value, row, col): - """ Return the image for the cell given the raw cell value and the row - and column numbers. + """Return the image for the cell given the raw cell value and the row + and column numbers. """ return None @@ -43,8 +43,7 @@ def get_image_for_obj(self, value, row, col): # ------------------------------------------------------------------------- def paint(self, painter, option, index): - """ Overriden to draw images. - """ + """Overriden to draw images.""" # First draw any text/background by delegating to our superclass QtGui.QStyledItemDelegate.paint(self, painter, option, index) @@ -67,8 +66,8 @@ def paint(self, painter, option, index): painter.drawPixmap(target, image) def sizeHint(self, option, index): - """ Overriden to take image size into account when providing a size - hint. + """Overriden to take image size into account when providing a size + hint. """ size = QtGui.QStyledItemDelegate.sizeHint(self, option, index) diff --git a/traitsui/qt4/file_editor.py b/traitsui/qt4/file_editor.py index b545ea075..235f20441 100644 --- a/traitsui/qt4/file_editor.py +++ b/traitsui/qt4/file_editor.py @@ -30,15 +30,14 @@ from .helper import IconButton - # Wildcard filter: filter_trait = List(Str) class SimpleEditor(SimpleTextEditor): - """ Simple style of file editor, consisting of a text field and a **Browse** - button that opens a file-selection dialog box. The user can also drag - and drop a file onto this control. + """Simple style of file editor, consisting of a text field and a **Browse** + button that opens a file-selection dialog box. The user can also drag + and drop a file onto this control. """ #: List of tuple(signal, slot) to be removed in dispose. @@ -47,8 +46,8 @@ class SimpleEditor(SimpleTextEditor): _connections_to_remove = List(Tuple(Any(), Callable())) def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = QtGui.QWidget() layout = QtGui.QHBoxLayout(self.control) @@ -76,8 +75,7 @@ def init(self, parent): self.set_tooltip(control) def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" while self._connections_to_remove: signal, handler = self._connections_to_remove.pop() signal.disconnect(handler) @@ -89,8 +87,7 @@ def dispose(self): Editor.dispose(self) def update_object(self): - """ Handles the user changing the contents of the edit control. - """ + """Handles the user changing the contents of the edit control.""" if self.control is not None: file_name = str(self._file_name.text()) try: @@ -102,14 +99,13 @@ def update_object(self): self._file_name.setText(self.value) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ self._file_name.setText(self.str_value) def show_file_dialog(self): - """ Displays the pop-up file dialog. - """ + """Displays the pop-up file dialog.""" # We don't used the canned functions because we don't know how the # file name is to be used (ie. an existing one to be opened or a new # one to be created). @@ -128,15 +124,13 @@ def show_file_dialog(self): self.update_editor() def get_error_control(self): - """ Returns the editor's control for indicating error status. - """ + """Returns the editor's control for indicating error status.""" return self._file_name # -- Private Methods ------------------------------------------------------ def _create_file_dialog(self): - """ Creates the correct type of file dialog. - """ + """Creates the correct type of file dialog.""" dlg = QtGui.QFileDialog(self.control) dlg.selectFile(self._file_name.text()) @@ -152,8 +146,7 @@ def _create_file_dialog(self): class CustomEditor(SimpleTextEditor): - """ Custom style of file editor, consisting of a file system tree view. - """ + """Custom style of file editor, consisting of a file system tree view.""" #: Is the file editor scrollable? This value overrides the default. scrollable = True @@ -171,8 +164,8 @@ class CustomEditor(SimpleTextEditor): dclick = Event() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ control = _TreeView(self) control.doubleClicked.connect(self._on_dclick) @@ -230,8 +223,7 @@ def init(self, parent): header.setStretchLastSection(False) def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" self._model.beginResetModel() self._model.endResetModel() @@ -242,8 +234,7 @@ def dispose(self): Editor.dispose(self) def update_object(self, idx): - """ Handles the user changing the contents of the edit control. - """ + """Handles the user changing the contents of the edit control.""" if self.control is not None: path = str(self._model.filePath(idx)) @@ -254,8 +245,8 @@ def update_object(self, idx): self.value = path def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ if exists(self.str_value): index = self._model.index(abspath(self.str_value)) @@ -265,20 +256,17 @@ def update_editor(self): # -- Private Methods ------------------------------------------------------ def _on_dclick(self, idx): - """ Handles the user double-clicking on a file name. - """ + """Handles the user double-clicking on a file name.""" self.dclick = str(self._model.filePath(idx)) # Trait change handlers -------------------------------------------------- def _filter_changed(self): - """ Handles the 'filter' trait being changed. - """ + """Handles the 'filter' trait being changed.""" self._model.setNameFilters(self.filter) def _root_path_changed(self): - """ Handles the 'root_path' trait being changed. - """ + """Handles the 'root_path' trait being changed.""" path = self.root_path if not path: path = QtCore.QDir.homePath() @@ -286,14 +274,13 @@ def _root_path_changed(self): self.control.setRootIndex(self._model.index(path)) def _reload_changed(self): - """ Handles the 'reload' trait being changed. - """ + """Handles the 'reload' trait being changed.""" self._model.refresh() class _TreeView(QtGui.QTreeView): - """ This is an internal class needed because QAbstractItemView doesn't - provide a signal for when the current index changes. + """This is an internal class needed because QAbstractItemView doesn't + provide a signal for when the current index changes. """ def __init__(self, editor): @@ -321,7 +308,6 @@ def keyPressEvent(self, keyevent): QtGui.QTreeView.keyPressEvent(self, keyevent) def currentChanged(self, current, previous): - """ Reimplemented to tell the editor when the current index has changed. - """ + """Reimplemented to tell the editor when the current index has changed.""" super().currentChanged(current, previous) self._editor.update_object(current) diff --git a/traitsui/qt4/font_editor.py b/traitsui/qt4/font_editor.py index 4e71e57d9..e05c09942 100644 --- a/traitsui/qt4/font_editor.py +++ b/traitsui/qt4/font_editor.py @@ -40,7 +40,6 @@ from .editor import Editor - # Standard font point sizes PointSizes = [ "8", @@ -69,23 +68,20 @@ class ToolkitEditorFactory(BaseToolkitEditorFactory): - """ PyQt editor factory for font editors. - """ + """PyQt editor factory for font editors.""" def to_qt4_font(self, editor): - """ Returns a QFont object corresponding to a specified object's font + """Returns a QFont object corresponding to a specified object's font trait. """ return QtGui.QFont(editor.value) def from_qt4_font(self, font): - """ Gets the application equivalent of a QFont value. - """ + """Gets the application equivalent of a QFont value.""" return font def str_font(self, font): - """ Returns the text representation of the specified object trait value. - """ + """Returns the text representation of the specified object trait value.""" weight = {QtGui.QFont.Light: " Light", QtGui.QFont.Bold: " Bold"}.get( font.weight(), "" ) @@ -102,14 +98,13 @@ def str_font(self, font): class SimpleFontEditor(BaseSimpleEditor): - """ Simple style of font editor, which displays a text field that contains + """Simple style of font editor, which displays a text field that contains a text representation of the font value (using that font if possible). Clicking the field displays a font selection dialog box. """ def popup_editor(self): - """ Invokes the pop-up editor for an object trait. - """ + """Invokes the pop-up editor for an object trait.""" fnt, ok = QtGui.QFontDialog.getFont( self.factory.to_qt4_font(self), self.control ) @@ -119,30 +114,29 @@ def popup_editor(self): self.update_editor() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ super().update_editor() set_font(self) def string_value(self, font): - """ Returns the text representation of a specified font value. - """ + """Returns the text representation of a specified font value.""" return self.factory.str_font(font) class CustomFontEditor(Editor): - """ Custom style of font editor, which displays the following: + """Custom style of font editor, which displays the following: - * A text field containing the text representation of the font value - (using that font if possible). - * A combo box containing all available type face names. - * A combo box containing the available type sizes. + * A text field containing the text representation of the font value + (using that font if possible). + * A combo box containing all available type face names. + * A combo box containing the available type sizes. """ def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = QtGui.QWidget() layout = QtGui.QVBoxLayout(self.control) @@ -172,15 +166,13 @@ def init(self, parent): layout.addLayout(layout2) def update_object(self): - """ Handles the user changing the contents of the font text control. - """ + """Handles the user changing the contents of the font text control.""" self.value = str(self._font.text()) self._set_font(self.factory.to_qt4_font(self)) self.update_editor() def update_object_parts(self): - """ Handles the user modifying one of the font components. - """ + """Handles the user modifying one of the font components.""" fnt = self._facename.currentFont() fnt.setBold(self._bold) @@ -195,8 +187,8 @@ def update_object_parts(self): self._set_font(fnt) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ font = self.factory.to_qt4_font(self) @@ -213,64 +205,58 @@ def update_editor(self): self._point_size.setCurrentIndex(idx) def string_value(self, font): - """ Returns the text representation of a specified font value. - """ + """Returns the text representation of a specified font value.""" return self.factory.str_font(font) def get_error_control(self): - """ Returns the editor's control for indicating error status. - """ + """Returns the editor's control for indicating error status.""" return [self._font, self._facename, self._point_size] # -- Private Methods ------------------------------------------------------ def _set_font(self, font): - """ Sets the font used by the text control to the specified font. - """ + """Sets the font used by the text control to the specified font.""" font.setPointSize(min(10, font.pointSize())) self._font.setFont(font) class TextFontEditor(BaseTextEditor): - """ Text style of font editor, which displays an editable text field + """Text style of font editor, which displays an editable text field containing a text representation of the font value (using that font if possible). """ def update_object(self): - """ Handles the user changing the contents of the edit control. - """ + """Handles the user changing the contents of the edit control.""" self.value = str(self.control.text()) def update_editor(self): - """ Updates the editor when the object trait changes external to the - editor. + """Updates the editor when the object trait changes external to the + editor. """ super().update_editor() set_font(self) def string_value(self, font): - """ Returns the text representation of a specified font value. - """ + """Returns the text representation of a specified font value.""" return self.factory.str_font(font) class ReadonlyFontEditor(BaseReadonlyEditor): - """ Read-only style of font editor, which displays a read-only text field + """Read-only style of font editor, which displays a read-only text field containing a text representation of the font value (using that font if possible). """ def update_editor(self): - """ Updates the editor when the object trait changes external to the - editor. + """Updates the editor when the object trait changes external to the + editor. """ super().update_editor() set_font(self) def string_value(self, font): - """ Returns the text representation of a specified font value. - """ + """Returns the text representation of a specified font value.""" return self.factory.str_font(font) @@ -280,8 +266,7 @@ def string_value(self, font): def set_font(editor): - """ Sets the editor control's font to match a specified font. - """ + """Sets the editor control's font to match a specified font.""" editor.control.setFont(editor.factory.to_qt4_font(editor)) diff --git a/traitsui/qt4/font_trait.py b/traitsui/qt4/font_trait.py index e7f80541b..5fb8f3812 100644 --- a/traitsui/qt4/font_trait.py +++ b/traitsui/qt4/font_trait.py @@ -57,8 +57,7 @@ def font_to_str(font): - """ Converts a QFont into a string description of itself. - """ + """Converts a QFont into a string description of itself.""" weight = {QtGui.QFont.Light: " Light", QtGui.QFont.Bold: " Bold"}.get( font.weight(), "" ) @@ -79,8 +78,7 @@ def font_to_str(font): def create_traitsfont(value): - """ Create a TraitFont object from a string description. - """ + """Create a TraitFont object from a string description.""" if isinstance(value, QtGui.QFont): return TraitsFont(value) @@ -133,17 +131,14 @@ def create_traitsfont(value): class TraitsFont(QtGui.QFont): - """ A Traits-specific QFont. - """ + """A Traits-specific QFont.""" def __reduce_ex__(self, protocol): - """ Returns the pickleable form of a TraitsFont object. - """ + """Returns the pickleable form of a TraitsFont object.""" return (create_traitsfont, (font_to_str(self),)) def __str__(self): - """ Returns a printable form of the font. - """ + """Returns a printable form of the font.""" return font_to_str(self) @@ -153,13 +148,13 @@ def __str__(self): class TraitPyQtFont(TraitHandler): - """ Ensures that values assigned to a trait attribute are valid font + """Ensures that values assigned to a trait attribute are valid font descriptor strings; the value actually assigned is the corresponding TraitsFont. """ def validate(self, object, name, value): - """ Validates that the value is a valid font descriptor string. If so, + """Validates that the value is a valid font descriptor string. If so, it returns the corresponding TraitsFont; otherwise, it raises a TraitError. """ diff --git a/traitsui/qt4/helper.py b/traitsui/qt4/helper.py index e9d07c6a9..962fdfc7a 100644 --- a/traitsui/qt4/helper.py +++ b/traitsui/qt4/helper.py @@ -33,7 +33,6 @@ from traitsui.ui_traits import SequenceTypes - is_pyqt = qt_api in {"pyqt", "pyqt5"} @@ -45,7 +44,7 @@ def pixmap_cache(name, path=None): - """ Convert an image file name to a cached QPixmap + """Convert an image file name to a cached QPixmap Returns the QPixmap corresponding to a filename. If the filename does not contain a path component, 'path' is used (or if 'path' is not specified, @@ -81,8 +80,8 @@ def pixmap_cache(name, path=None): def position_window(window, width=None, height=None, parent=None): - """ Positions a window on the screen with a specified width and height so - that the window completely fits on the screen if possible. + """Positions a window on the screen with a specified width and height so + that the window completely fits on the screen if possible. """ # Get the available geometry of the screen containing the window. sgeom = QtGui.QApplication.desktop().availableGeometry(window) @@ -133,28 +132,26 @@ def position_window(window, width=None, height=None, parent=None): def restore_window(ui): - """ Restores the user preference items for a specified UI. - """ + """Restores the user preference items for a specified UI.""" prefs = ui.restore_prefs() if prefs is not None: ui.control.setGeometry(*prefs) def save_window(ui): - """ Saves the user preference items for a specified UI. - """ + """Saves the user preference items for a specified UI.""" geom = ui.control.geometry() ui.save_prefs((geom.x(), geom.y(), geom.width(), geom.height())) class IconButton(QtGui.QPushButton): - """ The IconButton class is a push button that contains a small image or a - standard icon provided by the current style. + """The IconButton class is a push button that contains a small image or a + standard icon provided by the current style. """ def __init__(self, icon, slot): - """ Initialise the button. icon is either the name of an image file or - one of the QtGui.QStyle.SP_* values. + """Initialise the button. icon is either the name of an image file or + one of the QtGui.QStyle.SP_* values. """ QtGui.QPushButton.__init__(self) @@ -189,7 +186,7 @@ def __init__(self, icon, slot): self.clicked.connect(slot) def sizeHint(self): - """ Reimplement sizeHint to return a recommended button size based on + """Reimplement sizeHint to return a recommended button size based on the size of the icon. Returns @@ -207,13 +204,14 @@ def sizeHint(self): ) return size + # ------------------------------------------------------------------------ # Text Rendering helpers # ------------------------------------------------------------------------ def wrap_text_with_elision(text, font, width, height): - """ Wrap paragraphs to fit inside a given size, eliding if too long. + """Wrap paragraphs to fit inside a given size, eliding if too long. Parameters ---------- diff --git a/traitsui/qt4/history_editor.py b/traitsui/qt4/history_editor.py index 67fe900f0..cd4aa40f2 100644 --- a/traitsui/qt4/history_editor.py +++ b/traitsui/qt4/history_editor.py @@ -18,11 +18,10 @@ from .editor import Editor - class _HistoryEditor(Editor): - """ Simple style text editor, which displays a text field and maintains a - history of previously entered values, the maximum number of which is - specified by the 'entries' trait of the HistoryEditor factory. + """Simple style text editor, which displays a text field and maintains a + history of previously entered values, the maximum number of which is + specified by the 'entries' trait of the HistoryEditor factory. """ # ------------------------------------------------------------------------- @@ -30,8 +29,8 @@ class _HistoryEditor(Editor): # ------------------------------------------------------------------------- def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = control = QtGui.QComboBox() control.setEditable(True) @@ -48,14 +47,13 @@ def init(self, parent): self.set_tooltip() def update_object(self, text): - """ Handles the user entering input data in the edit control. - """ + """Handles the user entering input data in the edit control.""" if not self._no_update: self.value = str(text) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ self._no_update = True self.control.setEditText(self.str_value) @@ -64,8 +62,8 @@ def update_editor(self): # -- UI preference save/restore interface --------------------------------- def restore_prefs(self, prefs): - """ Restores any saved user preference information associated with the - editor. + """Restores any saved user preference information associated with the + editor. """ history = prefs.get("history") if history: @@ -78,8 +76,7 @@ def restore_prefs(self, prefs): self._no_update = False def save_prefs(self): - """ Returns any user preference information associated with the editor. - """ + """Returns any user preference information associated with the editor.""" history = [ str(self.control.itemText(index)) for index in range(self.control.count()) @@ -99,8 +96,8 @@ def save_prefs(self): # ------------------------------------------------------------------------- def _truncate(self, parent, start, end): - """ Handle items being added to the combo box. If there are too many, - remove items at the end. + """Handle items being added to the combo box. If there are too many, + remove items at the end. """ diff = self.control.count() - self.factory.entries if diff > 0: diff --git a/traitsui/qt4/html_editor.py b/traitsui/qt4/html_editor.py index a31ff0aed..cb09f772a 100644 --- a/traitsui/qt4/html_editor.py +++ b/traitsui/qt4/html_editor.py @@ -28,7 +28,7 @@ # Subclass of QWebPage for QtWebEngine support class ExternallyOpeningWebPage(QtWebKit.QWebPage): - """ QWebEnginePage subclass that opens links in system browser + """QWebEnginePage subclass that opens links in system browser This subclass is only used when we are given a QWebEnginePage which is pretending to be a QWebPage and we want the open_external feature @@ -60,8 +60,7 @@ def acceptNavigationRequest(self, url, type, isMainFrame): class SimpleEditor(Editor): - """ Simple style editor for HTML. - """ + """Simple style editor for HTML.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -74,8 +73,8 @@ class SimpleEditor(Editor): base_url = Str() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = WebView() self.control.setSizePolicy( @@ -106,8 +105,7 @@ def init(self, parent): self.sync_value(self.factory.base_url_name, "base_url", "from") def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" if self.control is not None and self.factory.open_externally: if HAS_WEB_VIEW: page = self.control.page() @@ -121,8 +119,8 @@ def dispose(self): super().dispose() def update_editor(self): - """ Updates the editor when the object trait changes external to the - editor. + """Updates the editor when the object trait changes external to the + editor. """ text = self.str_value if self.factory.format_text: diff --git a/traitsui/qt4/image_editor.py b/traitsui/qt4/image_editor.py index 16cc56c15..44b56d3a5 100644 --- a/traitsui/qt4/image_editor.py +++ b/traitsui/qt4/image_editor.py @@ -12,7 +12,6 @@ """ - from pyface.qt.QtGui import QFrame, QPainter, QPalette from pyface.image_resource import ImageResource @@ -33,14 +32,14 @@ class QImageView(QFrame): - """ A custom QFrame that will paint a QPixmap as an image. The + """A custom QFrame that will paint a QPixmap as an image. The api is similar to QLabel, but with a few more options to control how the image scales. """ def __init__(self, parent=None): - """ Initialize a QImageView. + """Initialize a QImageView. Parameters ---------- @@ -61,7 +60,7 @@ def __init__(self, parent=None): # Private API # -------------------------------------------------------------------------- def paintEvent(self, event): - """ A custom paint event handler which draws the image according + """A custom paint event handler which draws the image according to the current size constraints. """ @@ -124,7 +123,7 @@ def paintEvent(self, event): # Public API # -------------------------------------------------------------------------- def sizeHint(self): - """ Returns a appropriate size hint for the image based on the + """Returns a appropriate size hint for the image based on the underlying QPixmap. """ @@ -134,7 +133,7 @@ def sizeHint(self): return super().sizeHint() def minimumSizeHint(self): - """ Returns a appropriate minimum size hint for the image based on the + """Returns a appropriate minimum size hint for the image based on the underlying QPixmap. """ @@ -148,13 +147,11 @@ def minimumSizeHint(self): return super().sizeHint() def pixmap(self): - """ Returns the underlying pixmap for the image view. - - """ + """Returns the underlying pixmap for the image view.""" return self._pixmap def setPixmap(self, pixmap): - """ Set the pixmap to use as the image in the widget. + """Set the pixmap to use as the image in the widget. Parameters ---------- @@ -166,14 +163,14 @@ def setPixmap(self, pixmap): self.update() def scaledContents(self): - """ Returns whether or not the contents scale with the widget + """Returns whether or not the contents scale with the widget size. """ return self._scaled_contents def setScaledContents(self, scaled): - """ Set whether the contents scale with the widget size. + """Set whether the contents scale with the widget size. Parameters ---------- @@ -187,14 +184,14 @@ def setScaledContents(self, scaled): self.update() def allowUpscaling(self): - """ Returns whether or not the image can be scaled greater than + """Returns whether or not the image can be scaled greater than its natural size. """ return self._allow_upscaling def setAllowUpscaling(self, allow): - """ Set whether or not to allow the image to be scaled beyond + """Set whether or not to allow the image to be scaled beyond its natural size. Parameters @@ -210,14 +207,14 @@ def setAllowUpscaling(self, allow): self.update() def preserveAspectRatio(self): - """ Returns whether or not the aspect ratio of the image is + """Returns whether or not the aspect ratio of the image is maintained during a resize. """ return self._preserve_aspect_ratio def setPreserveAspectRatio(self, preserve): - """ Set whether or not to preserve the image aspect ratio. + """Set whether or not to preserve the image aspect ratio. Parameters ---------- @@ -231,13 +228,11 @@ def setPreserveAspectRatio(self, preserve): self.update() def allowClipping(self): - """ Returns whether or not the image should be clipped in the view. - - """ + """Returns whether or not the image should be clipped in the view.""" return self._preserve_aspect_ratio def setAllowClipping(self, allow): - """ Set whether or not the image should be clipped in the view. + """Set whether or not the image should be clipped in the view. Parameters ---------- @@ -256,12 +251,11 @@ def setAllowClipping(self, allow): class _ImageEditor(Editor): - """ Traits UI 'display only' image editor. - """ + """Traits UI 'display only' image editor.""" def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ image = self.factory.image if image is None: @@ -277,8 +271,8 @@ def init(self, parent): self.set_tooltip() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ if self.factory.image is None: value = self.value diff --git a/traitsui/qt4/image_enum_editor.py b/traitsui/qt4/image_enum_editor.py index 0f56ec533..c2daf75f5 100644 --- a/traitsui/qt4/image_enum_editor.py +++ b/traitsui/qt4/image_enum_editor.py @@ -23,12 +23,10 @@ class BaseEditor(object): - """ The base class for the different styles of ImageEnumEditor. - """ + """The base class for the different styles of ImageEnumEditor.""" def get_pixmap(self, name): - """ Get a pixmap representing a possible object traits value. - """ + """Get a pixmap representing a possible object traits value.""" if name is None: return None factory = self.factory @@ -37,13 +35,13 @@ def get_pixmap(self, name): class ReadonlyEditor(BaseEditor, BaseEnumEditor): - """ Read-only style of image enumeration editor, which displays a single - static image representing the object trait's value. + """Read-only style of image enumeration editor, which displays a single + static image representing the object trait's value. """ def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ super().init(parent) @@ -52,25 +50,23 @@ def init(self, parent): self.set_tooltip() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ self.control.setPixmap(self.get_pixmap(self.str_value)) def rebuild_editor(self): - """ Rebuilds the contents of the editor whenever the original factory - object's **values** trait changes. + """Rebuilds the contents of the editor whenever the original factory + object's **values** trait changes. """ pass class SimpleEditor(BaseEditor, SimpleEnumEditor): - """ Simple style of image enumeration editor, which displays a combo box. - """ + """Simple style of image enumeration editor, which displays a combo box.""" def create_combo_box(self): - """ Returns the QComboBox used for the editor control. - """ + """Returns the QComboBox used for the editor control.""" control = ImageEnumComboBox(self) control.setSizePolicy( QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Maximum @@ -82,8 +78,8 @@ def dispose(self): super().dispose() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ if self._no_enum_update == 0: self._no_enum_update += 1 @@ -100,23 +96,21 @@ def update_editor(self): self._no_enum_update -= 1 def rebuild_editor(self): - """ Rebuilds the contents of the editor whenever the original factory - object's **values** trait changes. + """Rebuilds the contents of the editor whenever the original factory + object's **values** trait changes. """ self.control.model().reset() class CustomEditor(BaseEditor, CustomEnumEditor): - """ Simple style of image enumeration editor, which displays a combo box. - """ + """Simple style of image enumeration editor, which displays a combo box.""" #: Is the button layout row-major or column-major? This value overrides the #: default. row_major = True def create_button(self, name): - """ Returns the QAbstractButton used for the radio button. - """ + """Returns the QAbstractButton used for the radio button.""" button = QtGui.QToolButton() button.setAutoExclusive(True) button.setCheckable(True) @@ -134,13 +128,12 @@ def create_button(self, name): class ImageEnumComboBox(QtGui.QComboBox): - """ A combo box which displays images instead of text. - """ + """A combo box which displays images instead of text.""" def __init__(self, editor, parent=None): - """ Reimplemented to store the editor and set a delegate for drawing the - items in the popup menu. If there is more than one column, use a - TableView instead of ListView for the popup. + """Reimplemented to store the editor and set a delegate for drawing the + items in the popup menu. If there is more than one column, use a + TableView instead of ListView for the popup. """ QtGui.QComboBox.__init__(self, parent) self._editor = editor @@ -163,8 +156,7 @@ def __init__(self, editor, parent=None): self.setItemDelegate(delegate) def _dispose(self): - """ Dispose objects on this widget. To be called by editors. - """ + """Dispose objects on this widget. To be called by editors.""" # Replace the model with the standard one. # After the editor has disposed itself, the widget may not have been # garbage collected and the model still reacts to events fired @@ -175,8 +167,8 @@ def _dispose(self): self.setModel(QtGui.QStandardItemModel()) def paintEvent(self, event): - """ Reimplemented to draw the ComboBox frame and paint the image - centered in it. + """Reimplemented to draw the ComboBox frame and paint the image + centered in it. """ painter = QtGui.QStylePainter(self) painter.setPen(self.palette().color(QtGui.QPalette.Text)) @@ -203,8 +195,8 @@ def paintEvent(self, event): painter.drawPixmap(target, pixmap) def sizeHint(self): - """ Reimplemented to set a size hint based on the size of the larget - image. + """Reimplemented to set a size hint based on the size of the larget + image. """ size = QtCore.QSize() for name in self._editor.names: @@ -220,8 +212,7 @@ def sizeHint(self): class ImageEnumTablePopupView(QtGui.QTableView): def __init__(self, parent): - """ Configure the appearence of the table view. - """ + """Configure the appearence of the table view.""" QtGui.QTableView.__init__(self, parent) hheader = self.horizontalHeader() if is_qt5: @@ -239,23 +230,19 @@ def __init__(self, parent): class ImageEnumItemDelegate(QtGui.QStyledItemDelegate): - """ An item delegate which draws only images. - """ + """An item delegate which draws only images.""" def __init__(self, editor, parent): - """ Reimplemented to store the editor. - """ + """Reimplemented to store the editor.""" QtGui.QStyledItemDelegate.__init__(self, parent) self._editor = editor def displayText(self, value, locale): - """ Reimplemented to display nothing. - """ + """Reimplemented to display nothing.""" return "" def paint(self, painter, option, mi): - """ Reimplemented to draw images. - """ + """Reimplemented to draw images.""" # Delegate to our superclass to draw the background QtGui.QStyledItemDelegate.paint(self, painter, option, mi) @@ -272,8 +259,7 @@ def paint(self, painter, option, mi): painter.drawPixmap(target, pixmap) def sizeHint(self, option, mi): - """ Reimplemented to define a size hint based on the size of the pixmap. - """ + """Reimplemented to define a size hint based on the size of the pixmap.""" name = mi.data(QtCore.Qt.DisplayRole) pixmap = self._get_pixmap(name) if pixmap is None: @@ -285,30 +271,25 @@ def _get_pixmap(self, name): class ImageEnumModel(QtCore.QAbstractTableModel): - """ A table model for use with the 'simple' style ImageEnumEditor. - """ + """A table model for use with the 'simple' style ImageEnumEditor.""" def __init__(self, editor, parent): - """ Reimplemented to store the editor. - """ + """Reimplemented to store the editor.""" super().__init__(parent) self._editor = editor def rowCount(self, mi): - """ Reimplemented to return the number of rows. - """ + """Reimplemented to return the number of rows.""" cols = self._editor.factory.cols result = (len(self._editor.names) + cols - 1) / cols return result def columnCount(self, mi): - """ Reimplemented to return the number of columns. - """ + """Reimplemented to return the number of columns.""" return self._editor.factory.cols def data(self, mi, role): - """ Reimplemented to return the data. - """ + """Reimplemented to return the data.""" if role == QtCore.Qt.DisplayRole: index = mi.row() * self._editor.factory.cols + mi.column() if index < len(self._editor.names): diff --git a/traitsui/qt4/instance_editor.py b/traitsui/qt4/instance_editor.py index 261919e08..88dd29a30 100644 --- a/traitsui/qt4/instance_editor.py +++ b/traitsui/qt4/instance_editor.py @@ -48,7 +48,7 @@ class CustomEditor(Editor): - """ Custom style of editor for instances. If selection among instances is + """Custom style of editor for instances. If selection among instances is allowed, the editor displays a combo box listing instances that can be selected. If the current instance is editable, the editor displays a panel containing trait editors for all the instance's traits. @@ -74,8 +74,8 @@ class CustomEditor(Editor): view = AView def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory if factory.name != "": @@ -111,9 +111,7 @@ def init(self, parent): self.rebuild_items, self._name + ".items", dispatch="ui" ) - factory.observe( - self.rebuild_items, "values.items", dispatch="ui" - ) + factory.observe(self.rebuild_items, "values.items", dispatch="ui") self.rebuild_items() @@ -162,14 +160,12 @@ def init(self, parent): self.sync_value(factory.view_name, "view", "from") def create_editor(self, parent, layout): - """ Creates the editor control. - """ + """Creates the editor control.""" self._panel = QtGui.QWidget() layout.addWidget(self._panel) def _get_items(self): - """ Gets the current list of InstanceChoiceItem items. - """ + """Gets the current list of InstanceChoiceItem items.""" if self._items is not None: return self._items @@ -189,7 +185,7 @@ def _get_items(self): value.object.observe( self.rebuild_items, trait(value.name_trait, optional=True), - dispatch="ui" + dispatch="ui", ) items.append(value) @@ -198,8 +194,7 @@ def _get_items(self): return items def rebuild_items(self, event=None): - """ Rebuilds the object selector list. - """ + """Rebuilds the object selector list.""" # Clear the current cached values: self._items = None @@ -226,8 +221,7 @@ def rebuild_items(self, event=None): pass def item_for(self, object): - """ Returns the InstanceChoiceItem for a specified object. - """ + """Returns the InstanceChoiceItem for a specified object.""" for item in self.items: if item.is_compatible(object): return item @@ -235,8 +229,7 @@ def item_for(self, object): return None def view_for(self, object, item): - """ Returns the view to use for a specified object. - """ + """Returns the view to use for a specified object.""" view = "" if item is not None: view = item.get_view() @@ -249,8 +242,7 @@ def view_for(self, object, item): ) def update_object(self, index): - """ Handles the user selecting a new value from the combo box. - """ + """Handles the user selecting a new value from the combo box.""" item = self.items[index] id_item = id(item) object = self._object_cache.get(id_item) @@ -267,8 +259,8 @@ def update_object(self, index): self.resynch_editor() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ # Synchronize the editor contents: self.resynch_editor() @@ -294,9 +286,8 @@ def update_editor(self): if isinstance(choice, QtGui.QComboBox): choice.setCurrentIndex(-1) - def resynch_editor(self): - """ Resynchronizes the contents of the editor when the object trait + """Resynchronizes the contents of the editor when the object trait changes externally to the editor. """ panel = self._panel @@ -351,8 +342,7 @@ def resynch_editor(self): layout.addWidget(control) def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" # Make sure we aren't hanging on to any object refs: self._object_cache = None @@ -368,41 +358,38 @@ def dispose(self): self.rebuild_items, self._name + ".items", remove=True, - dispatch="ui" + dispatch="ui", ) self.factory.observe( self.rebuild_items, "values.items", remove=True, - dispatch="ui" + dispatch="ui", ) super().dispose() def error(self, excp): - """ Handles an error that occurs while setting the object's trait value. - """ + """Handles an error that occurs while setting the object's trait value.""" pass def get_error_control(self): - """ Returns the editor's control for indicating error status. - """ + """Returns the editor's control for indicating error status.""" return self._choice or self.control # -- UI preference save/restore interface --------------------------------- def restore_prefs(self, prefs): - """ Restores any saved user preference information associated with the - editor. + """Restores any saved user preference information associated with the + editor. """ ui = self._ui if (ui is not None) and (prefs.get("id") == ui.id): ui.set_prefs(prefs.get("prefs")) def save_prefs(self): - """ Returns any user preference information associated with the editor. - """ + """Returns any user preference information associated with the editor.""" ui = self._ui if (ui is not None) and (ui.id != ""): return {"id": ui.id, "prefs": ui.get_prefs()} @@ -416,7 +403,7 @@ def _view_changed(self, view): class SimpleEditor(CustomEditor): - """ Simple style of editor for instances, which displays a button. Clicking + """Simple style of editor for instances, which displays a button. Clicking the button displays a dialog box in which the instance can be edited. """ @@ -428,8 +415,7 @@ class SimpleEditor(CustomEditor): extra = 2 def create_editor(self, parent, layout): - """ Creates the editor control (a button). - """ + """Creates the editor control (a button).""" self._button = QtGui.QPushButton() self._button.setAutoDefault(False) layout.addWidget(self._button) @@ -438,8 +424,8 @@ def create_editor(self, parent, layout): self._button.destroyed.connect(self._parent_closed) def edit_instance(self): - """ Edit the contents of the object trait when the user clicks the - button. + """Edit the contents of the object trait when the user clicks the + button. """ # Create the user interface: factory = self.factory @@ -465,8 +451,8 @@ def edit_instance(self): self._dialog_ui = None def resynch_editor(self): - """ Resynchronizes the contents of the editor when the object trait - changes externally to the editor. + """Resynchronizes the contents of the editor when the object trait + changes externally to the editor. """ button = self._button if button is not None: diff --git a/traitsui/qt4/key_binding_editor.py b/traitsui/qt4/key_binding_editor.py index 97b50cea8..3864868f4 100644 --- a/traitsui/qt4/key_binding_editor.py +++ b/traitsui/qt4/key_binding_editor.py @@ -36,8 +36,7 @@ class KeyBindingEditor(Editor): - """ An editor for modifying bindings of keys to controls. - """ + """An editor for modifying bindings of keys to controls.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -53,14 +52,13 @@ class KeyBindingEditor(Editor): clear = Event() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = KeyBindingCtrl(self) def update_object(self, event): - """ Handles the user entering input data in the edit control. - """ + """Handles the user entering input data in the edit control.""" try: self.value = value = key_event_to_name(event) self._binding.text = value @@ -68,21 +66,19 @@ def update_object(self, event): pass def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ self.control.setText(self.value) def update_focus(self, has_focus): - """ Updates the current focus setting of the control. - """ + """Updates the current focus setting of the control.""" if has_focus: self._binding.border_size = 1 self.object.owner.focus_owner = self._binding def _key_changed(self, event): - """ Handles a keyboard event. - """ + """Handles a keyboard event.""" binding = self.object key_name = key_event_to_name(event) cur_binding = binding.owner.key_binding_for(binding, key_name) @@ -104,14 +100,12 @@ def _key_changed(self, event): self.value = key_name def _clear_changed(self): - """ Handles a clear field event. - """ + """Handles a clear field event.""" self.value = "" class KeyBindingCtrl(QtGui.QLabel): - """ PyQt control for editing key bindings. - """ + """PyQt control for editing key bindings.""" def __init__(self, editor, parent=None): super().__init__(parent) @@ -132,15 +126,13 @@ def __init__(self, editor, parent=None): editor.has_focus = False def keyPressEvent(self, event): - """ Handle keyboard keys being pressed. - """ + """Handle keyboard keys being pressed.""" # Ignore presses of the control and shift keys. if event.key() not in (QtCore.Qt.Key_Control, QtCore.Qt.Key_Shift): self.editor.key = event def paintEvent(self, event): - """ Updates the screen. - """ + """Updates the screen.""" QtGui.QLabel.paintEvent(self, event) w = self.width() @@ -160,18 +152,15 @@ def paintEvent(self, event): p.end() def focusInEvent(self, event): - """ Handles getting the focus. - """ + """Handles getting the focus.""" self.editor.has_focus = True self.update() def focusOutEvent(self, event): - """ Handles losing the focus. - """ + """Handles losing the focus.""" self.editor.has_focus = False self.update() def mouseDoubleClickEvent(self, event): - """ Handles the user double clicking the control to clear its contents. - """ + """Handles the user double clicking the control to clear its contents.""" self.editor.clear = True diff --git a/traitsui/qt4/key_event_to_name.py b/traitsui/qt4/key_event_to_name.py index c9786956f..d71cbad86 100644 --- a/traitsui/qt4/key_event_to_name.py +++ b/traitsui/qt4/key_event_to_name.py @@ -145,8 +145,7 @@ def key_event_to_name(event): - """ Converts a keystroke event into a corresponding key name. - """ + """Converts a keystroke event into a corresponding key name.""" key_code = event.key() modifiers = event.modifiers() if modifiers & QtCore.Qt.KeypadModifier: diff --git a/traitsui/qt4/list_editor.py b/traitsui/qt4/list_editor.py index 376643526..b8c3843e7 100644 --- a/traitsui/qt4/list_editor.py +++ b/traitsui/qt4/list_editor.py @@ -29,7 +29,14 @@ from pyface.api import ImageResource from traits.api import ( - Any, Bool, Callable, Dict, Instance, List, Str, TraitError + Any, + Bool, + Callable, + Dict, + Instance, + List, + Str, + TraitError, ) from traits.trait_base import user_name_for, xgetattr @@ -41,7 +48,7 @@ class SimpleEditor(Editor): - """ Simple style of editor for lists, which displays a list box with only + """Simple style of editor for lists, which displays a list box with only one item visible at a time. A icon next to the list box displays a menu of operations on the list. @@ -101,8 +108,8 @@ class SimpleEditor(Editor): """ def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ # Initialize the trait handler to use: trait_handler = self.factory.trait_handler @@ -150,8 +157,7 @@ def init(self, parent): self.set_tooltip() def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" self._dispose_items() extended_name = self.extended_name.replace(".", ":") @@ -162,8 +168,8 @@ def dispose(self): super().dispose() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ self.mapper = QtCore.QSignalMapper(self.control) # Disconnect the editor from any control about to be destroyed: @@ -229,7 +235,7 @@ def update_editor(self): self.control.setWidget(list_pane) def update_editor_item(self, event): - """ Updates the editor when an item in the object trait changes + """Updates the editor when an item in the object trait changes externally to the editor. """ # If this is not a simple, single item update, rebuild entire editor: @@ -249,8 +255,7 @@ def update_editor_item(self, event): break def empty_list(self): - """ Creates an empty list entry (so the user can add a new item). - """ + """Creates an empty list entry (so the user can add a new item).""" # Connecting the new button to the mapper control = IconButton("list_editor.png", self.mapper.map) # Setting the mapping and asking it to send the index of the sender to @@ -271,21 +276,18 @@ def empty_list(self): layout.addWidget(pcontrol, 0, 0) def get_info(self): - """ Returns the associated object list and current item index. - """ + """Returns the associated object list and current item index.""" proxy = self._cur_control.proxy return (proxy.list, proxy.index) def popup_empty_menu(self, index): - """ Displays the empty list editor popup menu. - """ + """Displays the empty list editor popup menu.""" self._cur_control = control = self.buttons[index] menu = MakeMenu(self.empty_list_menu, self, True, control).menu menu.exec_(control.mapToGlobal(QtCore.QPoint(4, 24))) def popup_menu(self, index): - """ Displays the list editor popup menu. - """ + """Displays the list editor popup menu.""" self._cur_control = sender = self.buttons[index] proxy = sender.proxy @@ -304,15 +306,14 @@ def popup_menu(self, index): menu.exec_(sender.mapToGlobal(QtCore.QPoint(4, 24))) def add_item(self, offset): - """ Adds a new value at the specified list index. - """ + """Adds a new value at the specified list index.""" list, index = self.get_info() index += offset item_trait = self._trait_handler.item_trait if self.factory.item_factory: value = self.factory.item_factory( *self.factory.item_factory_args, - **self.factory.item_factory_kwargs + **self.factory.item_factory_kwargs, ) else: value = item_trait.default_value_for(self.object, self.name) @@ -322,35 +323,31 @@ def add_item(self, offset): # traits will still give an error message, but we don't want to crash except TraitError: from traitsui.api import raise_to_debug + raise_to_debug() self.update_editor() def add_before(self): - """ Inserts a new item before the current item. - """ + """Inserts a new item before the current item.""" self.add_item(0) def add_after(self): - """ Inserts a new item after the current item. - """ + """Inserts a new item after the current item.""" self.add_item(1) def add_empty(self): - """ Adds a new item when the list is empty. - """ + """Adds a new item when the list is empty.""" list, index = self.get_info() self.add_item(0) def delete_item(self): - """ Delete the current item. - """ + """Delete the current item.""" list, index = self.get_info() self.value = list[:index] + list[index + 1 :] self.update_editor() def move_up(self): - """ Move the current item up one in the list. - """ + """Move the current item up one in the list.""" list, index = self.get_info() self.value = ( list[: index - 1] @@ -360,8 +357,7 @@ def move_up(self): self.update_editor() def move_down(self): - """ Moves the current item down one in the list. - """ + """Moves the current item down one in the list.""" list, index = self.get_info() self.value = ( list[:index] + [list[index + 1], list[index]] + list[index + 2 :] @@ -369,15 +365,13 @@ def move_down(self): self.update_editor() def move_top(self): - """ Moves the current item to the top of the list. - """ + """Moves the current item to the top of the list.""" list, index = self.get_info() self.value = [list[index]] + list[:index] + list[index + 1 :] self.update_editor() def move_bottom(self): - """ Moves the current item to the bottom of the list. - """ + """Moves the current item to the bottom of the list.""" list, index = self.get_info() self.value = list[:index] + list[index + 1 :] + [list[index]] self.update_editor() @@ -385,8 +379,7 @@ def move_bottom(self): # -- Private Methods ------------------------------------------------------ def _dispose_items(self): - """ Disposes of each current list item. - """ + """Disposes of each current list item.""" layout = self._list_pane.layout() child = layout.takeAt(0) while child is not None: @@ -403,20 +396,19 @@ def _dispose_items(self): # -- Trait initializers ---------------------------------------------------- def _kind_default(self): - """ Returns a default value for the 'kind' trait. - """ + """Returns a default value for the 'kind' trait.""" return self.factory.style + "_editor" def _mutable_default(self): - """ Trait handler to set the mutable trait from the factory. - """ + """Trait handler to set the mutable trait from the factory.""" return self.factory.mutable def _scrollable_default(self): return self.factory.scrollable + class CustomEditor(SimpleEditor): - """ Custom style of editor for lists, which displays the items as a series + """Custom style of editor for lists, which displays the items as a series of text fields. If the list is editable, an icon next to each item displays a menu of operations on the list. """ @@ -445,7 +437,7 @@ class ReadonlyEditor(CustomEditor): class NotebookEditor(Editor): - """ An editor for lists that displays the list as a "notebook" of tabbed + """An editor for lists that displays the list as a "notebook" of tabbed pages. """ @@ -472,8 +464,8 @@ class NotebookEditor(Editor): selected = Any() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self._uis = [] @@ -522,8 +514,8 @@ def init(self, parent): self.sync_value(self.factory.selected, "selected") def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ # Destroy the views on each current notebook page: self.close_all() @@ -539,8 +531,7 @@ def update_editor(self): self._selected_changed(self.selected) def update_editor_item(self, event): - """ Handles an update to some subset of the trait's list. - """ + """Handles an update to some subset of the trait's list.""" index = event.index # Delete the page corresponding to each removed item: @@ -580,8 +571,7 @@ def update_editor_item(self, event): self.control.setCurrentWidget(first_page) def close_current(self, force=False): - """ Closes the currently selected tab: - """ + """Closes the currently selected tab:""" widget = self.control.currentWidget() for i in range(len(self._uis)): page, ui, _, _ = self._uis[i] @@ -608,8 +598,7 @@ def close_current(self, force=False): return def close_all(self): - """ Closes all currently open notebook pages. - """ + """Closes all currently open notebook pages.""" page_name = self.factory.page_name[1:] for _, ui, view_object, monitoring in self._uis: @@ -626,8 +615,7 @@ def close_all(self): self.control.clear() def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" self.context_object.on_trait_change( self.update_editor_item, self.name + "_items?", remove=True ) @@ -636,8 +624,7 @@ def dispose(self): super().dispose() def update_page_name(self, object, name, old, new): - """ Handles the trait defining a particular page's name being changed. - """ + """Handles the trait defining a particular page's name being changed.""" for i, value in enumerate(self._uis): page, ui, _, _ = value if object is ui.info.object: @@ -728,8 +715,8 @@ def _create_page(self, object): return (ui, view_object, monitoring) def _tab_activated(self, idx): - """ Handles a notebook tab being "activated" (i.e. clicked on) by the - user. + """Handles a notebook tab being "activated" (i.e. clicked on) by the + user. """ widget = self.control.widget(idx) for page, ui, _, _ in self._uis: @@ -738,8 +725,7 @@ def _tab_activated(self, idx): break def _selected_changed(self, selected): - """ Handles the **selected** trait being changed. - """ + """Handles the **selected** trait being changed.""" for page, ui, _, _ in self._uis: if ui.info and selected is ui.info.object: self.control.setCurrentWidget(page) @@ -754,7 +740,7 @@ def _context_menu_requested(self, event): self._context_menu.popup(self.control.mapToGlobal(event)) def _menu_action(self, event, name=""): - """ Qt signal handler for when a item in a context menu is actually + """Qt signal handler for when a item in a context menu is actually selected. Not that we get this even after the underlying value has already changed. """ diff --git a/traitsui/qt4/list_str_editor.py b/traitsui/qt4/list_str_editor.py index 6d0028b02..1b53ec713 100644 --- a/traitsui/qt4/list_str_editor.py +++ b/traitsui/qt4/list_str_editor.py @@ -37,8 +37,7 @@ class _ListStrEditor(Editor): - """ Traits UI editor for editing lists of strings. - """ + """Traits UI editor for editing lists of strings.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -98,8 +97,8 @@ class _ListStrEditor(Editor): # ------------------------------------------------------------------------- def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory @@ -180,23 +179,20 @@ def init(self, parent): self._add_image(image_resource) # Refresh the editor whenever the adapter changes: - self.observe( - self.refresh_editor, "adapter.+update", dispatch="ui" - ) + self.observe(self.refresh_editor, "adapter.+update", dispatch="ui") # Set the list control's tooltip: self.set_tooltip() def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" self.model.beginResetModel() self.model.endResetModel() self.context_object.observe( self.update_editor, self.extended_name + ".items", remove=True, - dispatch="ui" + dispatch="ui", ) self.observe( @@ -211,8 +207,8 @@ def dispose(self): super().dispose() def update_editor(self, event=None): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ if not self._no_update: self.model.beginResetModel() @@ -228,13 +224,11 @@ def update_editor(self, event=None): # ------------------------------------------------------------------------- def refresh_editor(self, event=None): - """ Requests that the underlying list widget to redraw itself. - """ + """Requests that the underlying list widget to redraw itself.""" self.list_view.viewport().update() def callx(self, func, *args, **kw): - """ Call a function without allowing the editor to update. - """ + """Call a function without allowing the editor to update.""" old = self._no_update self._no_update = True try: @@ -243,8 +237,7 @@ def callx(self, func, *args, **kw): self._no_update = old def setx(self, **keywords): - """ Set one or more attributes without allowing the editor to update. - """ + """Set one or more attributes without allowing the editor to update.""" old = self._no_notify self._no_notify = True try: @@ -254,8 +247,7 @@ def setx(self, **keywords): self._no_notify = old def get_image(self, image): - """ Converts a user specified image to a QIcon. - """ + """Converts a user specified image to a QIcon.""" if isinstance(image, ImageResource): result = self.image_resources.get(image) if result is not None: @@ -266,8 +258,8 @@ def get_image(self, image): return self.images.get(image) def is_auto_add(self, index): - """ Returns whether or not the index is the special 'auto add' item at - the end of the list. + """Returns whether or not the index is the special 'auto add' item at + the end of the list. """ return self.factory.auto_add and ( index >= self.adapter.len(self.object, self.name) @@ -278,8 +270,7 @@ def is_auto_add(self, index): # ------------------------------------------------------------------------- def _add_image(self, image_resource): - """ Adds a new image to the image map. - """ + """Adds a new image to the image map.""" image = image_resource.create_icon() self.image_resources[image_resource] = image @@ -295,8 +286,7 @@ def _get_item_count(self): # -- Trait Event Handlers ------------------------------------------------- def _selected_changed(self, selected): - """ Handles the editor's 'selected' trait being changed. - """ + """Handles the editor's 'selected' trait being changed.""" if not self._no_update: try: selected_index = self.value.index(selected) @@ -306,8 +296,7 @@ def _selected_changed(self, selected): self._selected_index_changed(selected_index) def _selected_index_changed(self, selected_index): - """ Handles the editor's 'selected_index' trait being changed. - """ + """Handles the editor's 'selected_index' trait being changed.""" if not self._no_update: smodel = self.list_view.selectionModel() if selected_index == -1: @@ -318,8 +307,7 @@ def _selected_index_changed(self, selected_index): self.list_view.scrollTo(mi) def _multi_selected_changed(self, selected): - """ Handles the editor's 'multi_selected' trait being changed. - """ + """Handles the editor's 'multi_selected' trait being changed.""" if not self._no_update: indices = [] for item in selected: @@ -330,8 +318,7 @@ def _multi_selected_changed(self, selected): self._multi_selected_indices_changed(indices) def _multi_selected_items_changed(self, event): - """ Handles the editor's 'multi_selected' trait being modified. - """ + """Handles the editor's 'multi_selected' trait being modified.""" if not self._no_update: try: added = [self.value.index(item) for item in event.added] @@ -339,16 +326,11 @@ def _multi_selected_items_changed(self, event): except ValueError: pass else: - event = TraitListEvent( - index=0, - added=added, - removed=removed - ) + event = TraitListEvent(index=0, added=added, removed=removed) self._multi_selected_indices_items_changed(event) def _multi_selected_indices_changed(self, selected_indices): - """ Handles the editor's 'multi_selected_indices' trait being changed. - """ + """Handles the editor's 'multi_selected_indices' trait being changed.""" if not self._no_update: smodel = self.list_view.selectionModel() smodel.clearSelection() @@ -361,8 +343,7 @@ def _multi_selected_indices_changed(self, selected_indices): self.list_view.scrollTo(self.model.index(selected_indices[-1])) def _multi_selected_indices_items_changed(self, event): - """ Handles the editor's 'multi_selected_indices' trait being modified. - """ + """Handles the editor's 'multi_selected_indices' trait being modified.""" if not self._no_update: smodel = self.list_view.selectionModel() for selected_index in event.removed: @@ -379,14 +360,12 @@ def _multi_selected_indices_items_changed(self, event): # -- List Control Event Handlers ------------------------------------------ def _on_activate(self, mi): - """ Handle a cell being activated. - """ + """Handle a cell being activated.""" self.activated_index = index = mi.row() self.activated = self.adapter.get_item(self.object, self.name, index) def _on_mouse_right_click(self, point): - """ Handle a mouse right click event - """ + """Handle a mouse right click event""" mi = self.list_view.indexAt(point) if mi.isValid(): self.right_clicked_index = index = mi.row() @@ -395,8 +374,7 @@ def _on_mouse_right_click(self, point): ) def _on_row_selection(self, added, removed): - """ Handle the row selection being changed. - """ + """Handle the row selection being changed.""" self._no_update = True try: indices = self.list_view.selectionModel().selectedRows() @@ -412,8 +390,7 @@ def _on_row_selection(self, added, removed): self._no_update = False def _on_rows_selection(self, added, removed): - """ Handle the rows selection being changed. - """ + """Handle the rows selection being changed.""" self._no_update = True try: indices = self.list_view.selectionModel().selectedRows() @@ -459,19 +436,17 @@ def _on_context_menu(self, pos): class _ItemDelegate(QtGui.QStyledItemDelegate): - """ A QStyledItemDelegate which optionally draws horizontal gridlines. - (QListView does not support gridlines). + """A QStyledItemDelegate which optionally draws horizontal gridlines. + (QListView does not support gridlines). """ def __init__(self, editor, parent=None): - """ Save the editor - """ + """Save the editor""" QtGui.QStyledItemDelegate.__init__(self, parent) self._editor = editor def paint(self, painter, option, index): - """ Overrident to draw gridlines. - """ + """Overrident to draw gridlines.""" QtGui.QStyledItemDelegate.paint(self, painter, option, index) if self._editor.factory.horizontal_lines: painter.save() @@ -483,12 +458,10 @@ def paint(self, painter, option, index): class _ListView(QtGui.QListView): - """ A QListView configured to behave as expected by TraitsUI. - """ + """A QListView configured to behave as expected by TraitsUI.""" def __init__(self, editor): - """ Initialise the object. - """ + """Initialise the object.""" QtGui.QListView.__init__(self) self._editor = editor @@ -520,20 +493,18 @@ def __init__(self, editor): self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) def _dispose(self): - """ Clean up states in this view. - """ + """Clean up states in this view.""" self.setModel(None) def mouseReleaseEvent(self, event): - """ Reimplemented to support listening to right clicked item.""" + """Reimplemented to support listening to right clicked item.""" if event.button() == QtCore.Qt.RightButton: event.accept() self._editor._on_mouse_right_click(event.pos()) super().mouseReleaseEvent(event) def keyPressEvent(self, event): - """ Reimplemented to support edit, insert, and delete by keyboard. - """ + """Reimplemented to support edit, insert, and delete by keyboard.""" editor = self._editor factory = editor.factory diff --git a/traitsui/qt4/list_str_model.py b/traitsui/qt4/list_str_model.py index 6fd1c312d..27804eb7d 100644 --- a/traitsui/qt4/list_str_model.py +++ b/traitsui/qt4/list_str_model.py @@ -12,24 +12,20 @@ """ - from pyface.qt import QtCore, QtGui from traitsui.ui_traits import SequenceTypes - # MIME type for internal table drag/drop operations mime_type = "traits-ui-list-str-editor" class ListStrModel(QtCore.QAbstractListModel): - """ A model for lists of strings. - """ + """A model for lists of strings.""" def __init__(self, editor, parent=None): - """ Initialise the object. - """ + """Initialise the object.""" QtCore.QAbstractListModel.__init__(self, parent) self._editor = editor @@ -39,8 +35,7 @@ def __init__(self, editor, parent=None): # ------------------------------------------------------------------------- def rowCount(self, mi): - """ Reimplemented to return items in the list. - """ + """Reimplemented to return items in the list.""" editor = self._editor n = editor.adapter.len(editor.object, editor.name) if editor.factory.auto_add: @@ -48,17 +43,14 @@ def rowCount(self, mi): return n def data(self, mi, role): - """ Reimplemented to return the data. - """ + """Reimplemented to return the data.""" editor = self._editor adapter = editor.adapter index = mi.row() if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole: if editor.is_auto_add(index): - text = adapter.get_default_text( - editor.object, editor.name - ) + text = adapter.get_default_text(editor.object, editor.name) else: text = adapter.get_text(editor.object, editor.name, index) if role == QtCore.Qt.DisplayRole and text == "": @@ -68,9 +60,7 @@ def data(self, mi, role): elif role == QtCore.Qt.DecorationRole: if editor.is_auto_add(index): - image = adapter.get_default_image( - editor.object, editor.name - ) + image = adapter.get_default_image(editor.object, editor.name) else: image = adapter.get_image(editor.object, editor.name, index) image = editor.get_image(image) @@ -110,8 +100,7 @@ def data(self, mi, role): return None def setData(self, mi, value, role): - """ Reimplmented to allow for modification of the object trait. - """ + """Reimplmented to allow for modification of the object trait.""" editor = self._editor if editor.is_auto_add(mi.row()): method = editor.adapter.insert @@ -122,8 +111,7 @@ def setData(self, mi, value, role): return True def setItemData(self, mi, roles): - """ Reimplmented to reject all setItemData calls. - """ + """Reimplmented to reject all setItemData calls.""" # FIXME: This is a hack to prevent the QListView from clearing out the # old row after a move operation. (The QTableView doesn't do this, for # some reason). This behavior is not overridable so far as I can tell, @@ -133,8 +121,7 @@ def setItemData(self, mi, roles): return False def flags(self, mi): - """ Reimplemented to set editable status and movable status. - """ + """Reimplemented to set editable status and movable status.""" editor = self._editor index = mi.row() @@ -158,8 +145,7 @@ def flags(self, mi): return flags def headerData(self, section, orientation, role): - """ Reimplemented to return title for vertical header data. - """ + """Reimplemented to return title for vertical header data.""" if ( orientation != QtCore.Qt.Horizontal or role != QtCore.Qt.DisplayRole @@ -169,8 +155,8 @@ def headerData(self, section, orientation, role): return self._editor.title def insertRow(self, row, parent=QtCore.QModelIndex(), obj=None): - """ Reimplemented to allow creation of new rows. Added an optional - arg to allow the insertion of an existing row object. + """Reimplemented to allow creation of new rows. Added an optional + arg to allow the insertion of an existing row object. """ editor = self._editor adapter = editor.adapter @@ -185,8 +171,7 @@ def insertRow(self, row, parent=QtCore.QModelIndex(), obj=None): return True def insertRows(self, row, count, parent=QtCore.QModelIndex()): - """ Reimplemented to allow creation of new items. - """ + """Reimplemented to allow creation of new items.""" editor = self._editor adapter = editor.adapter @@ -200,8 +185,8 @@ def insertRows(self, row, count, parent=QtCore.QModelIndex()): return True def removeRows(self, row, count, parent=QtCore.QModelIndex()): - """ Reimplemented to allow row deletion, as well as reordering via drag - and drop. + """Reimplemented to allow row deletion, as well as reordering via drag + and drop. """ editor = self._editor adapter = editor.adapter @@ -213,14 +198,14 @@ def removeRows(self, row, count, parent=QtCore.QModelIndex()): return True def mimeTypes(self): - """ Reimplemented to expose our internal MIME type for drag and drop - operations. + """Reimplemented to expose our internal MIME type for drag and drop + operations. """ return [mime_type] def mimeData(self, indexes): - """ Reimplemented to generate MIME data containing the rows of the - current selection. + """Reimplemented to generate MIME data containing the rows of the + current selection. """ mime_data = QtCore.QMimeData() rows = list({index.row() for index in indexes}) @@ -231,8 +216,7 @@ def mimeData(self, indexes): return mime_data def dropMimeData(self, mime_data, action, row, column, parent): - """ Reimplemented to allow items to be moved. - """ + """Reimplemented to allow items to be moved.""" if action == QtCore.Qt.IgnoreAction: return False @@ -245,8 +229,7 @@ def dropMimeData(self, mime_data, action, row, column, parent): return True def supportedDropActions(self): - """ Reimplemented to allow items to be moved. - """ + """Reimplemented to allow items to be moved.""" return QtCore.Qt.MoveAction # ------------------------------------------------------------------------- @@ -254,13 +237,12 @@ def supportedDropActions(self): # ------------------------------------------------------------------------- def moveRow(self, old_row, new_row): - """ Convenience method to move a single row. - """ + """Convenience method to move a single row.""" return self.moveRows([old_row], new_row) def moveRows(self, current_rows, new_row): - """ Moves a sequence of rows (provided as a list of row indexes) to a - new row. + """Moves a sequence of rows (provided as a list of row indexes) to a + new row. """ editor = self._editor diff --git a/traitsui/qt4/menu.py b/traitsui/qt4/menu.py index b56299e02..239ca7046 100644 --- a/traitsui/qt4/menu.py +++ b/traitsui/qt4/menu.py @@ -53,24 +53,20 @@ """ - import re from pyface.qt import QtGui - help_pat = re.compile(r"(.*){(.*)}(.*)") options_pat = re.compile(r"(.*)\[(.*)\](.*)") class MakeMenu: - """ Manages creation of menus. - """ + """Manages creation of menus.""" def __init__(self, desc, owner, popup=False, window=None): - """ Initializes the object. - """ + """Initializes the object.""" self.owner = owner if window is None: window = owner @@ -88,8 +84,7 @@ def __init__(self, desc, owner, popup=False, window=None): window.setMenuBar(menu) def parse(self, menu, indent): - """ Recursively parses menu items from the description. - """ + """Recursively parses menu items from the description.""" while True: @@ -201,8 +196,7 @@ def parse(self, menu, indent): act.setStatusTip(help) def get_body(self, indent): - """ Returns the body of an inline method. - """ + """Returns the body of an inline method.""" result = [] while self.index < len(self.desc): line = self.desc[self.index] @@ -216,16 +210,14 @@ def get_body(self, indent): return " pass" def get_action(self, name): - """ Returns the QAction associated with a specified name. - """ + """Returns the QAction associated with a specified name.""" if isinstance(name, str): return self.names[name] return name def checked(self, name, check=None): - """ Checks (or unchecks) a menu item specified by name. - """ + """Checks (or unchecks) a menu item specified by name.""" act = self.get_action(name) if check is None: @@ -234,8 +226,7 @@ def checked(self, name, check=None): act.setChecked(check) def enabled(self, name, enable=None): - """ Enables (or disables) a menu item specified by name. - """ + """Enables (or disables) a menu item specified by name.""" act = self.get_action(name) if enable is None: @@ -244,8 +235,7 @@ def enabled(self, name, enable=None): act.setEnabled(enable) def label(self, name, label=None): - """ Gets or sets the label for a menu item. - """ + """Gets or sets the label for a menu item.""" act = self.get_action(name) if label is None: @@ -255,8 +245,7 @@ def label(self, name, label=None): class MakeMenuItem: - """ A menu item for a menu managed by MakeMenu. - """ + """A menu item for a menu managed by MakeMenu.""" def __init__(self, menu, act): self.menu = menu @@ -284,7 +273,7 @@ def label(self, label=None): def option_check(test, string): - """ Determines whether a string contains any specified option characters, + """Determines whether a string contains any specified option characters, and removes them if it does. """ result = [] diff --git a/traitsui/qt4/null_editor.py b/traitsui/qt4/null_editor.py index f92b8733c..3062e4327 100644 --- a/traitsui/qt4/null_editor.py +++ b/traitsui/qt4/null_editor.py @@ -18,17 +18,16 @@ class NullEditor(Editor): - """ A completely empty editor. - """ + """A completely empty editor.""" def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = QtGui.QWidget() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ pass diff --git a/traitsui/qt4/progress_editor.py b/traitsui/qt4/progress_editor.py index b9d28b9c3..b6af9eee1 100644 --- a/traitsui/qt4/progress_editor.py +++ b/traitsui/qt4/progress_editor.py @@ -19,8 +19,7 @@ class _ProgressDialog(ProgressDialog): def close(self): - """ Overwritten to disable closing. - """ + """Overwritten to disable closing.""" pass @@ -44,8 +43,8 @@ class SimpleEditor(Editor): # -- Editor interface ------------------------------------------------------ def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = self.create_control(parent) factory = self.factory diff --git a/traitsui/qt4/range_editor.py b/traitsui/qt4/range_editor.py index f32f6ad92..d247e894a 100644 --- a/traitsui/qt4/range_editor.py +++ b/traitsui/qt4/range_editor.py @@ -46,8 +46,8 @@ class BaseRangeEditor(Editor): - """ The base class for Range editors. Using an evaluate trait, if specified, - when assigning numbers the object trait. + """The base class for Range editors. Using an evaluate trait, if specified, + when assigning numbers the object trait. """ # ------------------------------------------------------------------------- @@ -64,7 +64,7 @@ def _set_value(self, value): class SimpleSliderEditor(BaseRangeEditor): - """ Simple style of range editor that displays a slider and a text field. + """Simple style of range editor that displays a slider and a text field. The user can set a value either by moving the slider or by typing a value in the text field. @@ -84,8 +84,8 @@ class SimpleSliderEditor(BaseRangeEditor): format = Str() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory if not factory.low_name: @@ -166,8 +166,7 @@ def init(self, parent): self.set_tooltip(text) def update_object_on_scroll(self, pos): - """ Handles the user changing the current slider value. - """ + """Handles the user changing the current slider value.""" value = self._convert_from_slider(pos) self.control.text.setText(self.string_value(value)) try: @@ -178,8 +177,7 @@ def update_object_on_scroll(self, pos): raise_to_debug() def update_object_on_enter(self): - """ Handles the user pressing the Enter key in the text field. - """ + """Handles the user pressing the Enter key in the text field.""" # It is possible the event is processed after the control is removed # from the editor if self.control is None: @@ -212,8 +210,8 @@ def update_object_on_enter(self): pass def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ value = self.value low = self.low @@ -236,8 +234,7 @@ def update_editor(self): self.control.slider.blockSignals(blocked) def get_error_control(self): - """ Returns the editor's control for indicating error status. - """ + """Returns the editor's control for indicating error status.""" return self.control.text def _low_changed(self, low): @@ -263,8 +260,7 @@ def _high_changed(self, high): self.update_editor() def _convert_to_slider(self, value): - """ Returns the slider setting corresponding to the user-supplied value. - """ + """Returns the slider setting corresponding to the user-supplied value.""" if self.high > self.low: ivalue = int( (float(value - self.low) / (self.high - self.low)) * 10000.0 @@ -277,7 +273,7 @@ def _convert_to_slider(self, value): return ivalue def _convert_from_slider(self, ivalue): - """ Returns the float or integer value corresponding to the slider + """Returns the float or integer value corresponding to the slider setting. """ value = self.low + ((float(ivalue) / 10000.0) * (self.high - self.low)) @@ -289,12 +285,10 @@ def _convert_from_slider(self, ivalue): # ------------------------------------------------------------------------- class LogRangeSliderEditor(SimpleSliderEditor): # ------------------------------------------------------------------------- - """ A slider editor for log-spaced values - """ + """A slider editor for log-spaced values""" def _convert_to_slider(self, value): - """ Returns the slider setting corresponding to the user-supplied value. - """ + """Returns the slider setting corresponding to the user-supplied value.""" value = max(value, self.low) ivalue = int( (log10(value) - log10(self.low)) @@ -304,7 +298,7 @@ def _convert_to_slider(self, value): return ivalue def _convert_from_slider(self, ivalue): - """ Returns the float or integer value corresponding to the slider + """Returns the float or integer value corresponding to the slider setting. """ value = float(ivalue) / 10000.0 * (log10(self.high) - log10(self.low)) @@ -317,7 +311,7 @@ def _convert_from_slider(self, ivalue): class LargeRangeSliderEditor(BaseRangeEditor): - """ A slider editor for large ranges. + """A slider editor for large ranges. The editor displays a slider and a text field. A subset of the total range is displayed in the slider; arrow buttons at each end of the slider let @@ -344,8 +338,8 @@ class LargeRangeSliderEditor(BaseRangeEditor): ui_changing = Bool(False) def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory @@ -437,8 +431,7 @@ def init(self, parent): self.update_range_ui() def update_object_on_scroll(self, pos): - """ Handles the user changing the current slider value. - """ + """Handles the user changing the current slider value.""" value = self.cur_low + ( (float(pos) / 10000.0) * (self.cur_high - self.cur_low) ) @@ -451,8 +444,7 @@ def update_object_on_scroll(self, pos): self.value = int(value) def update_object_on_enter(self): - """ Handles the user pressing the Enter key in the text field. - """ + """Handles the user pressing the Enter key in the text field.""" # It is possible the event is processed after the control is removed # from the editor if self.control is None: @@ -463,8 +455,8 @@ def update_object_on_enter(self): pass def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ value = self.value low = self.low @@ -481,8 +473,7 @@ def update_editor(self): self.update_range_ui() def update_range_ui(self): - """ Updates the slider range controls. - """ + """Updates the slider range controls.""" low, high = self.cur_low, self.cur_high value = self.value self._set_format() @@ -504,8 +495,7 @@ def update_range_ui(self): self.control.button_hi.setEnabled(high != self.high) def init_range(self): - """ Initializes the slider range controls. - """ + """Initializes the slider range controls.""" value = self.value low, high = self.low, self.high if (high is None) and (low is not None): @@ -523,8 +513,7 @@ def init_range(self): self.cur_low, self.cur_high = cur_low, cur_high def reduce_range(self): - """ Reduces the extent of the displayed range. - """ + """Reduces the extent of the displayed range.""" low, high = self.low, self.high if abs(self.cur_low) < 10: self.cur_low = max(-10, low) @@ -542,8 +531,7 @@ def reduce_range(self): self.update_range_ui() def increase_range(self): - """ Increased the extent of the displayed range. - """ + """Increased the extent of the displayed range.""" low, high = self.low, self.high if abs(self.cur_high) < 10: self.cur_low = max(-10, low) @@ -574,8 +562,7 @@ def _set_format(self): self._format = "%.3f" def get_error_control(self): - """ Returns the editor's control for indicating error status. - """ + """Returns the editor's control for indicating error status.""" return self.control.text def _low_changed(self, low): @@ -600,8 +587,7 @@ def _high_changed(self, high): class SimpleSpinEditor(BaseRangeEditor): - """ A simple style of range editor that displays a spin box control. - """ + """A simple style of range editor that displays a spin box control.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -614,8 +600,8 @@ class SimpleSpinEditor(BaseRangeEditor): high = Any() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory if not factory.low_name: @@ -637,8 +623,7 @@ def init(self, parent): self.set_tooltip() def update_object(self, value): - """ Handles the user selecting a new value in the spin box. - """ + """Handles the user selecting a new value in the spin box.""" self._locked = True try: self.value = value @@ -646,8 +631,8 @@ def update_object(self, value): self._locked = False def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ if not self._locked: blocked = self.control.blockSignals(True) @@ -684,7 +669,7 @@ def _high_changed(self, high): class RangeTextEditor(TextEditor): - """ Editor for ranges that displays a text field. If the user enters a + """Editor for ranges that displays a text field. If the user enters a value that is outside the allowed range, the background of the field changes color to indicate an error. """ @@ -703,8 +688,8 @@ class RangeTextEditor(TextEditor): evaluate = Any() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ TextEditor.init(self, parent) @@ -726,8 +711,7 @@ def init(self, parent): self.value = self.low def update_object(self): - """ Handles the user entering input data in the edit control. - """ + """Handles the user entering input data in the edit control.""" try: value = eval(str(self.control.text())) if self.evaluate is not None: @@ -739,7 +723,7 @@ def update_object(self): else: col = OKColor - self.value = value + self.value = value except Exception: col = ErrorColor @@ -754,9 +738,7 @@ def update_object(self): # ------------------------------------------------------------------------- -def SimpleEnumEditor( - parent, factory, ui, object, name, description, **kwargs -): +def SimpleEnumEditor(parent, factory, ui, object, name, description, **kwargs): return CustomEnumEditor( parent, factory, ui, object, name, description, "simple" ) @@ -765,7 +747,7 @@ def SimpleEnumEditor( def CustomEnumEditor( parent, factory, ui, object, name, description, style="custom", **kwargs ): - """ Factory adapter that returns a enumeration editor of the specified + """Factory adapter that returns a enumeration editor of the specified style. """ if factory._enum is None: diff --git a/traitsui/qt4/rgb_color_editor.py b/traitsui/qt4/rgb_color_editor.py index 41d8baf82..8acdb2338 100644 --- a/traitsui/qt4/rgb_color_editor.py +++ b/traitsui/qt4/rgb_color_editor.py @@ -42,12 +42,10 @@ class ToolkitEditorFactory(BaseColorToolkitEditorFactory): - """ PyQt editor factory for color editors. - """ + """PyQt editor factory for color editors.""" def to_qt4_color(self, editor): - """ Gets the PyQt color equivalent of the object trait. - """ + """Gets the PyQt color equivalent of the object trait.""" try: color = getattr(editor.object, editor.name + "_") except AttributeError: @@ -59,13 +57,11 @@ def to_qt4_color(self, editor): return c def from_qt4_color(self, color): - """ Gets the application equivalent of a PyQt value. - """ + """Gets the application equivalent of a PyQt value.""" return (color.redF(), color.greenF(), color.blueF()) def str_color(self, color): - """ Returns the text representation of a specified color value. - """ + """Returns the text representation of a specified color value.""" if type(color) in SequenceTypes: return "(%d,%d,%d)" % ( int(color[0] * 255.0), diff --git a/traitsui/qt4/rgb_color_trait.py b/traitsui/qt4/rgb_color_trait.py index aaa48f32e..cf16b120d 100644 --- a/traitsui/qt4/rgb_color_trait.py +++ b/traitsui/qt4/rgb_color_trait.py @@ -25,10 +25,10 @@ def range_check(value): - """ Checks that *value* can be converted to a value in the range 0.0 to 1.0. + """Checks that *value* can be converted to a value in the range 0.0 to 1.0. - If so, it returns the floating point value; otherwise, it raises a - TraitError. + If so, it returns the floating point value; otherwise, it raises a + TraitError. """ value = float(value) if 0.0 <= value <= 1.0: @@ -37,8 +37,8 @@ def range_check(value): def convert_to_color(object, name, value): - """ Converts a tuple or an integer to an RGB color value, or raises a - TraitError if that is not possible. + """Converts a tuple or an integer to an RGB color value, or raises a + TraitError if that is not possible. """ if isinstance(value, SequenceTypes) and len(value) == 3: return ( diff --git a/traitsui/qt4/search_editor.py b/traitsui/qt4/search_editor.py index 7c8d86a97..328f7098b 100644 --- a/traitsui/qt4/search_editor.py +++ b/traitsui/qt4/search_editor.py @@ -15,21 +15,19 @@ from .editor import Editor - class SearchWidget(QtGui.QLineEdit): # FIXME: This widget needs a search button and a cancel button like the # wxWidgets SearchControl. def __init__(self, desc): - """ Store the descriptive text for the widget. - """ + """Store the descriptive text for the widget.""" super().__init__() self._desc = str(desc) self._set_descriptive_text() def focusInEvent(self, event): - """ Handles accepting focus. + """Handles accepting focus. If the text box contains the default description string, reset the text color and clear the box. @@ -44,7 +42,7 @@ def focusInEvent(self, event): super().focusInEvent(event) def focusOutEvent(self, event): - """ Handles losing focus. + """Handles losing focus. When focus is lost, if the user had typed something, keep that text, otherwise replace it with the default description string. @@ -55,8 +53,7 @@ def focusOutEvent(self, event): super().focusOutEvent(event) def _set_descriptive_text(self): - """ Sets the greyed-out descriptive text. - """ + """Sets the greyed-out descriptive text.""" palette = QtGui.QApplication.instance().palette() palette.setColor( QtGui.QPalette.Text, palette.color(QtGui.QPalette.Dark) @@ -68,8 +65,8 @@ def _set_descriptive_text(self): class SearchEditor(Editor): def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ if QtCore.__version_info__ < (4, 7, 0): control = self.control = SearchWidget(self.factory.text) @@ -83,16 +80,15 @@ def init(self, parent): control.editingFinished.connect(self.update_object) def update_object(self, event=None): - """ Handles the user entering input data in the edit control. - """ + """Handles the user entering input data in the edit control.""" if not self._no_update: self.value = str(self.control.text()) if self.factory.search_event_trait != "": setattr(self.object, self.factory.search_event_trait, True) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ if str(self.control.text()) != self.value: self._no_update = True diff --git a/traitsui/qt4/set_editor.py b/traitsui/qt4/set_editor.py index 921431e7b..9f09526f4 100644 --- a/traitsui/qt4/set_editor.py +++ b/traitsui/qt4/set_editor.py @@ -33,9 +33,8 @@ from traits.api import Instance, Property - class SimpleEditor(Editor): - """ Simple style of editor for sets. + """Simple style of editor for sets. The editor displays two list boxes, with buttons for moving the selected items from left to right, or vice versa. If **can_move_all** on the factory @@ -64,8 +63,8 @@ class SimpleEditor(Editor): scrollable = True def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = QtGui.QWidget() self.root_layout = QtGui.QGridLayout(self.control) @@ -125,23 +124,19 @@ def init(self, parent): ) def _get_names(self): - """ Gets the current set of enumeration names. - """ + """Gets the current set of enumeration names.""" return self._names def _get_mapping(self): - """ Gets the current mapping. - """ + """Gets the current mapping.""" return self._mapping def _get_inverse_mapping(self): - """ Gets the current inverse mapping. - """ + """Gets the current inverse mapping.""" return self._inverse_mapping def _create_listbox(self, col, handler1, handler2, title): - """Creates a list box. - """ + """Creates a list box.""" # Add the column title in emphasized text: title_widget = QtGui.QLabel(title) font = QtGui.QFont(title_widget.font()) @@ -161,8 +156,7 @@ def _create_listbox(self, col, handler1, handler2, title): return list def _create_button(self, label, layout, handler): - """ Creates a button. - """ + """Creates a button.""" button = QtGui.QPushButton(label) # The connection type is set to workaround Qt5 + MacOSX issue with # event dispatching. See enthought/traitsui#1308 @@ -171,23 +165,25 @@ def _create_button(self, label, layout, handler): return button def values_changed(self): - """ Recomputes the cached data based on the underlying enumeration model - or the values of the factory. + """Recomputes the cached data based on the underlying enumeration model + or the values of the factory. """ - self._names, self._mapping, self._inverse_mapping = enum_values_changed( - self._value(), self.string_value - ) + ( + self._names, + self._mapping, + self._inverse_mapping, + ) = enum_values_changed(self._value(), self.string_value) def _values_changed(self): - """ Handles the underlying object model's enumeration set or factory's - values being changed. + """Handles the underlying object model's enumeration set or factory's + values being changed. """ self.values_changed() self.update_editor() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ # Check for any items having been deleted from the enumeration that are # still present in the object value: @@ -254,8 +250,7 @@ def update_editor(self): self._check_left_right() def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" if self._object is not None: self._object.on_trait_change( self._values_changed, self._name, remove=True @@ -272,8 +267,7 @@ def dispose(self): super().dispose() def get_error_control(self): - """ Returns the editor's control for indicating error status. - """ + """Returns the editor's control for indicating error status.""" return [self._unused, self._used] def _on_value(self): @@ -315,8 +309,7 @@ def _on_down(self): self._move_item(1) def _transfer_all(self, list_from, list_to, values_from, values_to): - """ Transfers all items from one list to another. - """ + """Transfers all items from one list to another.""" values_from = values_from[:] values_to = values_to[:] @@ -338,8 +331,7 @@ def _transfer_all(self, list_from, list_to, values_from, values_to): return (values_from, values_to) def _transfer_items(self, list_from, list_to, values_from, values_to): - """ Transfers the selected item from one list to another. - """ + """Transfers the selected item from one list to another.""" values_from = values_from[:] values_to = values_to[:] index_from = max(self._get_first_selection(list_from), 0) @@ -389,8 +381,7 @@ def _transfer_items(self, list_from, list_to, values_from, values_to): return (values_from, values_to) def _move_item(self, direction): - """ Moves an item up or down within the "used" list. - """ + """Moves an item up or down within the "used" list.""" # Move the item up/down within the list: listbox = self._used index_from = self._get_first_selection(listbox) @@ -413,8 +404,7 @@ def _move_item(self, direction): self.value = value[:index] + values + value[index + 2 :] def _check_up_down(self): - """ Sets the proper enabled state for the up and down buttons. - """ + """Sets the proper enabled state for the up and down buttons.""" if self.factory.ordered: selected = self._used.selectedItems() self._up.setEnabled( @@ -426,8 +416,7 @@ def _check_up_down(self): ) def _check_left_right(self): - """ Sets the proper enabled state for the left and right buttons. - """ + """Sets the proper enabled state for the left and right buttons.""" self._use.setEnabled( self._unused.count() > 0 and self._get_first_selection(self._unused) >= 0 @@ -452,8 +441,7 @@ def _check_left_right(self): # ------------------------------------------------------------------------- def _get_selected_strings(self, listbox): - """ Returns a list of the selected strings in the given *listbox*. - """ + """Returns a list of the selected strings in the given *listbox*.""" return [str(itm.text()) for itm in listbox.selectedItems()] # ------------------------------------------------------------------------- @@ -461,8 +449,7 @@ def _get_selected_strings(self, listbox): # ------------------------------------------------------------------------- def _get_first_selection(self, listbox): - """ Returns the index of the first (or only) selected item. - """ + """Returns the index of the first (or only) selected item.""" select_list = listbox.selectedItems() if len(select_list) == 0: return -1 diff --git a/traitsui/qt4/shell_editor.py b/traitsui/qt4/shell_editor.py index f85ab8b23..6dd974b9b 100644 --- a/traitsui/qt4/shell_editor.py +++ b/traitsui/qt4/shell_editor.py @@ -22,8 +22,7 @@ class _ShellEditor(BaseShellEditor, Editor): - """ Editor that displays an interactive Python shell. - """ + """Editor that displays an interactive Python shell.""" def init(self, parent): super().init(None) diff --git a/traitsui/qt4/styled_date_editor.py b/traitsui/qt4/styled_date_editor.py index c426e1e12..7d804732f 100644 --- a/traitsui/qt4/styled_date_editor.py +++ b/traitsui/qt4/styled_date_editor.py @@ -93,13 +93,13 @@ def _styles_items_changed(self, event): # ------------------------------------------------------------------------ def _apply_style(self, style, dates): - """ **style** is a CellFormat, **dates** is a list of datetime.date """ + """**style** is a CellFormat, **dates** is a list of datetime.date""" for dt in dates: self.set_unselected_style(style, dt) return def _apply_styles(self, style_dict, date_dict): - """ Applies the proper style out of style_dict to every (name,date_list) + """Applies the proper style out of style_dict to every (name,date_list) in date_dict. """ if not style_dict or not date_dict: diff --git a/traitsui/qt4/table_editor.py b/traitsui/qt4/table_editor.py index 6edd4a93f..d900d8596 100644 --- a/traitsui/qt4/table_editor.py +++ b/traitsui/qt4/table_editor.py @@ -25,7 +25,6 @@ """ - from pyface.qt import QtCore, QtGui, is_qt5 from pyface.image_resource import ImageResource from pyface.timer.api import do_later @@ -71,7 +70,6 @@ from .table_model import TableModel, SortFilterTableModel - if is_qt5: def set_qheader_section_resize_mode(header): @@ -85,9 +83,9 @@ def set_qheader_section_resize_mode(header): class TableEditor(Editor, BaseTableEditor): - """ Editor that presents data in a table. Optionally, tables can have - a set of filters that reduce the set of data displayed, according to - their criteria. + """Editor that presents data in a table. Optionally, tables can have + a set of filters that reduce the set of data displayed, according to + their criteria. """ # ------------------------------------------------------------------------- @@ -337,7 +335,7 @@ def init(self, parent): self._update_columns() def dispose(self): - """ Disposes of the contents of an editor.""" + """Disposes of the contents of an editor.""" self.model.beginResetModel() self.model.endResetModel() @@ -393,16 +391,15 @@ def update_editor(self): self.table_view.setUpdatesEnabled(True) def restore_prefs(self, prefs): - """ Restores any saved user preference information associated with the - editor. + """Restores any saved user preference information associated with the + editor. """ header = self.table_view.horizontalHeader() if header is not None and "column_state" in prefs: header.restoreState(prefs["column_state"]) def save_prefs(self): - """ Returns any user preference information associated with the editor. - """ + """Returns any user preference information associated with the editor.""" prefs = {} header = self.table_view.horizontalHeader() if header is not None: @@ -576,8 +573,7 @@ def _update_filtering(self): self.filter_summary = "%i of %i items" % (len(fi), num_items) def _add_image(self, image_resource): - """ Adds a new image to the image map. - """ + """Adds a new image to the image map.""" image = image_resource.create_icon() self.image_resources[image_resource] = image @@ -586,8 +582,7 @@ def _add_image(self, image_resource): return image def _get_image(self, image): - """ Converts a user specified image to a QIcon. - """ + """Converts a user specified image to a QIcon.""" if isinstance(image, str): self.image = image image = self.image @@ -692,8 +687,7 @@ def _selected_changed(self, new): self.set_selection(self.selected, notify=False) def _update_filter_changed(self): - """ The filter has changed internally. - """ + """The filter has changed internally.""" self._filter_changed(self.filter, self.filter) # -- Event Handlers ------------------------------------------------------- @@ -848,11 +842,10 @@ def _on_context_move_down(self): class TableDelegate(QtGui.QStyledItemDelegate): - """ A QStyledItemDelegate which fetches Traits UI editors. - """ + """A QStyledItemDelegate which fetches Traits UI editors.""" def createEditor(self, parent, option, index): - """ Reimplemented to return the editor for a given index.""" + """Reimplemented to return the editor for a given index.""" model = index.model() index = model.mapToSource(index) @@ -895,8 +888,7 @@ def createEditor(self, parent, option, index): return control def updateEditorGeometry(self, editor, option, index): - """ Update the editor's geometry. - """ + """Update the editor's geometry.""" editor.setGeometry(option.rect) def paint(self, painter, option, index): @@ -1158,7 +1150,7 @@ def sizeHintForColumn(self, column_index): return requested_width def resizeColumnsToContents(self): - """ Support proportional column width specifications. """ + """Support proportional column width specifications.""" # TODO: The proportional size specification approach found in the # TableColumns is not entirely compatible with the ability to @@ -1212,7 +1204,7 @@ def closeEditor(self, control, hint): return super().closeEditor(control, hint) def _update_header_sizing(self): - """ Header section sizing can be done only after a valid model is set. + """Header section sizing can be done only after a valid model is set. Otherwise results in segfault with Qt5. """ editor = self._editor @@ -1268,8 +1260,7 @@ def _update_header_sizing(self): class TableFilterEditor(HasTraits): - """ An editor that manages table filters. - """ + """An editor that manages table filters.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -1377,8 +1368,7 @@ def _editor_changed(self): @observe('add_button') def _create_and_select_new_filter(self, event): - """ Create a new filter based on the selected template and select it. - """ + """Create a new filter based on the selected template and select it.""" new_filter = self.selected_template.clone_traits() new_filter.template = False new_filter.name = new_filter._name = "New filter" @@ -1387,8 +1377,7 @@ def _create_and_select_new_filter(self, event): @observe("remove_button") def _delete_selected_filter(self, event): - """ Delete the currently selected filter. - """ + """Delete the currently selected filter.""" if self.selected_template == self.selected_filter: self.selected_template = self.templates[0] @@ -1401,8 +1390,8 @@ def _delete_selected_filter(self, event): @observe("selected_filter:name") def _update_filter_list(self, event): - """ A hack to make the EnumEditor watching the list of filters refresh - their text when the name of the selected filter changes. + """A hack to make the EnumEditor watching the list of filters refresh + their text when the name of the selected filter changes. """ filters = self.filters self.filters = [] diff --git a/traitsui/qt4/table_model.py b/traitsui/qt4/table_model.py index 065cb0548..fc12e03f5 100644 --- a/traitsui/qt4/table_model.py +++ b/traitsui/qt4/table_model.py @@ -23,7 +23,6 @@ """ - import logging from pyface.qt import QtCore, QtGui @@ -33,7 +32,6 @@ from .clipboard import PyMimeData - # set up logging for the module logger = logging.getLogger(__name__) @@ -57,8 +55,7 @@ def as_qcolor(color): - """ Convert a color specification (maybe a tuple) into a QColor. - """ + """Convert a color specification (maybe a tuple) into a QColor.""" if isinstance(color, SequenceTypes): return QtGui.QColor(*color) else: @@ -356,28 +353,28 @@ def supportedDropActions(self): # ------------------------------------------------------------------------- def _get_columns_drag_value(self, columns): - """ Returns the value to use when the specified columns are dragged or - copied and pasted. The parameter *cols* is a list of column indexes. + """Returns the value to use when the specified columns are dragged or + copied and pasted. The parameter *cols* is a list of column indexes. """ return [self._get_column_data(column) for column in columns] def _get_column_data(self, column): - """ Return the model data for the column as a list """ + """Return the model data for the column as a list""" editor = self._editor column_obj = editor.columns[column] return [column_obj.get_value(item) for item in editor.items()] def _get_rows_drag_value(self, rows): - """ Returns the value to use when the specified rows are dragged or - copied and pasted. The parameter *rows* is a list of row indexes. - Return a list of objects. + """Returns the value to use when the specified rows are dragged or + copied and pasted. The parameter *rows* is a list of row indexes. + Return a list of objects. """ items = self._editor.items() return [items[row] for row in rows] def _get_cell_drag_value(self, row, column): - """ Returns the value to use when the specified cell is dragged or - copied and pasted. + """Returns the value to use when the specified cell is dragged or + copied and pasted. """ editor = self._editor item = editor.items()[row] @@ -440,7 +437,7 @@ def __init__(self, editor, parent=None): # ------------------------------------------------------------------------- def filterAcceptsRow(self, source_row, source_parent): - """"Reimplemented to use a TableFilter for filtering rows.""" + """ "Reimplemented to use a TableFilter for filtering rows.""" if self._editor._filtered_cache is None: return True diff --git a/traitsui/qt4/tabular_editor.py b/traitsui/qt4/tabular_editor.py index 9b588e45a..2296df9db 100644 --- a/traitsui/qt4/tabular_editor.py +++ b/traitsui/qt4/tabular_editor.py @@ -13,7 +13,6 @@ """ - from contextlib import contextmanager from pyface.qt import QtCore, QtGui, is_qt5 @@ -61,8 +60,8 @@ def eventFilter(self, obj, event): class TabularEditor(Editor): - """ A traits UI editor for editing tabular data (arrays, list of tuples, - lists of objects, etc). + """A traits UI editor for editing tabular data (arrays, list of tuples, + lists of objects, etc). """ # -- Trait Definitions ---------------------------------------------------- @@ -149,8 +148,8 @@ class TabularEditor(Editor): # ------------------------------------------------------------------------- def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory adapter = self.adapter = factory.adapter @@ -251,8 +250,7 @@ def init(self, parent): ) def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" self.model.beginResetModel() self.model.endResetModel() @@ -277,8 +275,8 @@ def dispose(self): super().dispose() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ if not self._no_update: self.model.beginResetModel() @@ -293,13 +291,11 @@ def update_editor(self): # ------------------------------------------------------------------------- def refresh_editor(self): - """ Requests the table view to redraw itself. - """ + """Requests the table view to redraw itself.""" self.control.viewport().update() def callx(self, func, *args, **kw): - """ Call a function without allowing the editor to update. - """ + """Call a function without allowing the editor to update.""" old = self._no_update self._no_update = True try: @@ -308,8 +304,7 @@ def callx(self, func, *args, **kw): self._no_update = old def setx(self, **keywords): - """ Set one or more attributes without allowing the editor to update. - """ + """Set one or more attributes without allowing the editor to update.""" old = self._no_notify self._no_notify = True try: @@ -323,8 +318,8 @@ def setx(self, **keywords): # ------------------------------------------------------------------------- def restore_prefs(self, prefs): - """ Restores any saved user preference information associated with the - editor. + """Restores any saved user preference information associated with the + editor. """ cws = prefs.get("cached_widths") num_columns = len(self.adapter.columns) @@ -333,8 +328,7 @@ def restore_prefs(self, prefs): self.control.setColumnWidth(column, cws[column]) def save_prefs(self): - """ Returns any user preference information associated with the editor. - """ + """Returns any user preference information associated with the editor.""" widths = [ self.control.columnWidth(column) for column in range(len(self.adapter.columns)) @@ -346,8 +340,7 @@ def save_prefs(self): # ------------------------------------------------------------------------- def _add_image(self, image_resource): - """ Adds a new image to the image map. - """ + """Adds a new image to the image map.""" image = image_resource.create_icon() self.image_resources[image_resource] = image @@ -356,8 +349,7 @@ def _add_image(self, image_resource): return image def _get_image(self, image): - """ Converts a user specified image to a QIcon. - """ + """Converts a user specified image to a QIcon.""" if isinstance(image, str): self.image = image image = self.image @@ -371,8 +363,8 @@ def _get_image(self, image): return self.images.get(image) def _mouse_click(self, index, trait): - """ Generate a TabularEditorEvent event for a specified model index and - editor trait name. + """Generate a TabularEditorEvent event for a specified model index and + editor trait name. """ event = TabularEditorEvent( editor=self, row=index.row(), column=index.column() @@ -382,29 +374,30 @@ def _mouse_click(self, index, trait): # -- Trait Event Handlers ------------------------------------------------- def _clicked_changed(self): - """ When mouse is clicked on a specific cell, update the selected - indices first + """When mouse is clicked on a specific cell, update the selected + indices first """ if not self.factory.multi_select: self.selected_row = self.clicked.row self.selected_column = self.clicked.column def _column_clicked_changed(self): - """ When column is clicked, update selected column first - """ + """When column is clicked, update selected column first""" if not self.factory.multi_select: self.selected_column = self.column_clicked.column def _adapter_columns_updated(self): - """ Update the view when the adapter columns trait changes. + """Update the view when the adapter columns trait changes. Note that this change handler is added after the UI is instantiated, and removed when the UI is disposed. """ # Invalidate internal state of the view related to the columns n_columns = len(self.adapter.columns) - if (self.control is not None - and self.control._user_widths is not None - and len(self.control._user_widths) != n_columns): + if ( + self.control is not None + and self.control._user_widths is not None + and len(self.control._user_widths) != n_columns + ): self.control._user_widths = None self.update_editor() @@ -462,11 +455,7 @@ def _multi_selected_items_changed(self, event): except: pass else: - list_event = TraitListEvent( - index=0, - added=added, - removed=removed - ) + list_event = TraitListEvent(index=0, added=added, removed=removed) self._multi_selected_rows_items_changed(list_event) def _multi_selected_rows_changed(self, selected_rows): @@ -515,22 +504,18 @@ def _selected_column_changed(self, selected_column): self.scroll_to_column = selected_column def _scroll_to_row_changed(self, row): - """ Scroll to the given row. - """ + """Scroll to the given row.""" scroll_hint = SCROLL_TO_POSITION_HINT_MAP.get( - self.factory.scroll_to_position_hint, - self.control.EnsureVisible + self.factory.scroll_to_position_hint, self.control.EnsureVisible ) self.control.scrollTo( self.model.index(row, max(self.selected_column, 0)), scroll_hint ) def _scroll_to_column_changed(self, column): - """ Scroll to the given column. - """ + """Scroll to the given column.""" scroll_hint = SCROLL_TO_POSITION_HINT_MAP.get( - self.factory.scroll_to_position_hint, - self.control.EnsureVisible + self.factory.scroll_to_position_hint, self.control.EnsureVisible ) self.control.scrollTo( self.model.index(max(self.selected_row, 0), column), scroll_hint @@ -539,19 +524,16 @@ def _scroll_to_column_changed(self, column): # -- Table Control Event Handlers ----------------------------------------- def _on_activate(self, index): - """ Handle a cell being activated. - """ + """Handle a cell being activated.""" self.activated_row = row = index.row() self.activated = self.adapter.get_item(self.object, self.name, row) def _on_click(self, index): - """ Handle a cell being clicked. - """ + """Handle a cell being clicked.""" self._mouse_click(index, "clicked") def _on_dclick(self, index): - """ Handle a cell being double clicked. - """ + """Handle a cell being double clicked.""" self._mouse_click(index, "dclicked") def _on_column_click(self, column): @@ -567,8 +549,7 @@ def _on_column_right_click(self, column): setattr(self, "column_right_clicked", event) def _on_row_selection(self, added, removed): - """ Handle the row selection being changed. - """ + """Handle the row selection being changed.""" self._no_update = True try: indexes = self.control.selectionModel().selectedRows() @@ -584,8 +565,7 @@ def _on_row_selection(self, added, removed): self._no_update = False def _on_rows_selection(self, added, removed): - """ Handle the rows selection being changed. - """ + """Handle the rows selection being changed.""" self._no_update = True try: indexes = self.control.selectionModel().selectedRows() @@ -672,21 +652,19 @@ def _get_item(self): class _ItemDelegate(QtGui.QStyledItemDelegate): - """ A QStyledItemDelegate which draws its owns gridlines so that we can - choose to draw only the horizontal or only the vertical gridlines if - appropriate. + """A QStyledItemDelegate which draws its owns gridlines so that we can + choose to draw only the horizontal or only the vertical gridlines if + appropriate. """ def __init__(self, table_view): - """ Store which grid lines to draw. - """ + """Store which grid lines to draw.""" QtGui.QStyledItemDelegate.__init__(self, table_view) self._horizontal_lines = table_view._editor.factory.horizontal_lines self._vertical_lines = table_view._editor.factory.vertical_lines def paint(self, painter, option, index): - """ Overrident to draw gridlines. - """ + """Overrident to draw gridlines.""" QtGui.QStyledItemDelegate.paint(self, painter, option, index) painter.save() @@ -707,12 +685,10 @@ def paint(self, painter, option, index): class _TableView(QtGui.QTableView): - """ A QTableView configured to behave as expected by TraitsUI. - """ + """A QTableView configured to behave as expected by TraitsUI.""" def __init__(self, editor): - """ Initialise the object. - """ + """Initialise the object.""" QtGui.QTableView.__init__(self) self._user_widths = None @@ -786,8 +762,7 @@ def __init__(self, editor): self.setDropIndicatorShown(True) def keyPressEvent(self, event): - """ Reimplemented to support edit, insert, and delete by keyboard. - """ + """Reimplemented to support edit, insert, and delete by keyboard.""" editor = self._editor factory = editor.factory @@ -843,8 +818,7 @@ def keyPressEvent(self, event): QtGui.QTableView.keyPressEvent(self, event) def sizeHint(self): - """ Reimplemented to define a reasonable size hint. - """ + """Reimplemented to define a reasonable size hint.""" sh = QtGui.QTableView.sizeHint(self) width = 0 @@ -855,25 +829,24 @@ def sizeHint(self): return sh def resizeEvent(self, event): - """ Reimplemented to size the table columns when the size of the table - changes. Because the layout algorithm requires that the available - space be known, we have to wait until the UI that contains this - table gives it its initial size. + """Reimplemented to size the table columns when the size of the table + changes. Because the layout algorithm requires that the available + space be known, we have to wait until the UI that contains this + table gives it its initial size. """ super().resizeEvent(event) parent = self.parent() - if ( - parent - and (self.isVisible() or isinstance(parent, QtGui.QMainWindow)) + if parent and ( + self.isVisible() or isinstance(parent, QtGui.QMainWindow) ): self.resizeColumnsToContents() def sizeHintForColumn(self, column): - """ Reimplemented to support absolute width specification via - TabularAdapters and to avoid scanning all data to determine the size - hint. (TabularEditor, unlike TableEditor, is expected to handle very - large data sets.) + """Reimplemented to support absolute width specification via + TabularAdapters and to avoid scanning all data to determine the size + hint. (TabularEditor, unlike TableEditor, is expected to handle very + large data sets.) """ editor = self._editor if editor.factory.auto_resize: @@ -887,7 +860,7 @@ def sizeHintForColumn(self, column): return self.horizontalHeader().sectionSizeHint(column) def resizeColumnsToContents(self): - """ Reimplemented to support proportional column width specifications. + """Reimplemented to support proportional column width specifications. The core part of the computation is carried out in :func:`traitsui.helpers.compute_column_widths` @@ -916,7 +889,7 @@ def resizeColumnsToContents(self): hheader.resizeSection(column, width) def columnResized(self, index, old, new): - """ Handle user-driven resizing of columns. + """Handle user-driven resizing of columns. This affects the column widths when not using auto-sizing. """ @@ -924,13 +897,15 @@ def columnResized(self, index, old, new): if self._user_widths is None: self._user_widths = [None] * len(self._editor.adapter.columns) self._user_widths[index] = new - if (self._editor.factory is not None - and not self._editor.factory.auto_resize): + if ( + self._editor.factory is not None + and not self._editor.factory.auto_resize + ): self.resizeColumnsToContents() @contextmanager def _resizing(self): - """ Context manager that guards against recursive column resizing. """ + """Context manager that guards against recursive column resizing.""" self._is_resizing = True try: yield diff --git a/traitsui/qt4/tabular_model.py b/traitsui/qt4/tabular_model.py index e3d6d9f8a..47f178df1 100644 --- a/traitsui/qt4/tabular_model.py +++ b/traitsui/qt4/tabular_model.py @@ -12,7 +12,6 @@ """ - import logging from pyface.qt import QtCore, QtGui @@ -36,11 +35,10 @@ class TabularModel(QtCore.QAbstractTableModel): - """ The model for tabular data.""" + """The model for tabular data.""" def __init__(self, editor, parent=None): - """ Initialise the object. - """ + """Initialise the object.""" QtCore.QAbstractTableModel.__init__(self, parent) self._editor = editor @@ -50,8 +48,7 @@ def __init__(self, editor, parent=None): # ------------------------------------------------------------------------- def data(self, mi, role): - """ Reimplemented to return the data. - """ + """Reimplemented to return the data.""" editor = self._editor adapter = editor.adapter obj, name = editor.object, editor.name @@ -103,8 +100,7 @@ def data(self, mi, role): return None def setData(self, mi, value, role): - """ Reimplmented to allow for modification for the object trait. - """ + """Reimplmented to allow for modification for the object trait.""" if role != QtCore.Qt.EditRole: return False @@ -117,8 +113,7 @@ def setData(self, mi, value, role): return True def flags(self, mi): - """ Reimplemented to set editable status and movable status. - """ + """Reimplemented to set editable status and movable status.""" editor = self._editor row = mi.row() column = mi.column() @@ -160,8 +155,7 @@ def flags(self, mi): return flags def headerData(self, section, orientation, role): - """ Reimplemented to return the header data. - """ + """Reimplemented to return the header data.""" if role != QtCore.Qt.DisplayRole: return None @@ -176,20 +170,18 @@ def headerData(self, section, orientation, role): return label def rowCount(self, mi): - """ Reimplemented to return the number of rows. - """ + """Reimplemented to return the number of rows.""" editor = self._editor return editor.adapter.len(editor.object, editor.name) def columnCount(self, mi): - """ Reimplemented to return the number of columns. - """ + """Reimplemented to return the number of columns.""" editor = self._editor return len(editor.adapter.columns) def insertRow(self, row, parent=QtCore.QModelIndex(), obj=None): - """ Reimplemented to allow creation of new rows. Added an optional - arg to allow the insertion of an existing row object. + """Reimplemented to allow creation of new rows. Added an optional + arg to allow the insertion of an existing row object. """ editor = self._editor adapter = editor.adapter @@ -204,8 +196,7 @@ def insertRow(self, row, parent=QtCore.QModelIndex(), obj=None): return True def insertRows(self, row, count, parent=QtCore.QModelIndex()): - """ Reimplemented to allow creation of new items. - """ + """Reimplemented to allow creation of new items.""" editor = self._editor adapter = editor.adapter @@ -219,8 +210,8 @@ def insertRows(self, row, count, parent=QtCore.QModelIndex()): return True def removeRows(self, row, count, parent=QtCore.QModelIndex()): - """ Reimplemented to allow row deletion, as well as reordering via drag - and drop. + """Reimplemented to allow row deletion, as well as reordering via drag + and drop. """ editor = self._editor adapter = editor.adapter @@ -237,8 +228,8 @@ def removeRows(self, row, count, parent=QtCore.QModelIndex()): return True def mimeTypes(self): - """ Reimplemented to expose our internal MIME type for drag and drop - operations. + """Reimplemented to expose our internal MIME type for drag and drop + operations. """ return [ tabular_mime_type, @@ -247,8 +238,8 @@ def mimeTypes(self): ] def mimeData(self, indexes): - """ Reimplemented to generate MIME data containing the rows of the - current selection. + """Reimplemented to generate MIME data containing the rows of the + current selection. """ rows = sorted({index.row() for index in indexes}) items = [ @@ -265,8 +256,7 @@ def mimeData(self, indexes): return mime_data def dropMimeData(self, mime_data, action, row, column, parent): - """ Reimplemented to allow items to be moved. - """ + """Reimplemented to allow items to be moved.""" if action == QtCore.Qt.IgnoreAction: return False @@ -310,8 +300,7 @@ def dropMimeData(self, mime_data, action, row, column, parent): return False def supportedDropActions(self): - """ Reimplemented to allow items to be moved. - """ + """Reimplemented to allow items to be moved.""" return QtCore.Qt.MoveAction | QtCore.Qt.CopyAction # ------------------------------------------------------------------------- @@ -319,7 +308,7 @@ def supportedDropActions(self): # ------------------------------------------------------------------------- def dropItem(self, item, row): - """ Handle a Python object being dropped onto a row """ + """Handle a Python object being dropped onto a row""" editor = self._editor object = editor.object name = editor.name @@ -332,13 +321,12 @@ def dropItem(self, item, row): adapter.insert(object, name, row, item) def moveRow(self, old_row, new_row): - """ Convenience method to move a single row. - """ + """Convenience method to move a single row.""" return self.moveRows([old_row], new_row) def moveRows(self, current_rows, new_row): - """ Moves a sequence of rows (provided as a list of row indexes) to a - new row. + """Moves a sequence of rows (provided as a list of row indexes) to a + new row. """ editor = self._editor @@ -347,7 +335,8 @@ def moveRows(self, current_rows, new_row): # model. See ``QAbstractItemModel.checkIndex``` for Qt 5.11+ # This is a last resort to prevent segmentation faults. logger.debug( - "Received invalid row %d. Adjusting to the last row.", new_row) + "Received invalid row %d. Adjusting to the last row.", new_row + ) new_row = max(0, self.rowCount(None) - 1) # Sort rows in descending order so they can be removed without diff --git a/traitsui/qt4/tests/test_tabular_model.py b/traitsui/qt4/tests/test_tabular_model.py index 3aa361b1a..431876fed 100644 --- a/traitsui/qt4/tests/test_tabular_model.py +++ b/traitsui/qt4/tests/test_tabular_model.py @@ -25,6 +25,7 @@ reraise_exceptions, ToolkitName, ) + try: from pyface.qt import QtCore except ImportError: @@ -51,7 +52,6 @@ def get_view(adapter): @requires_toolkit([ToolkitName.qt]) class TestTabularModel(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -62,9 +62,8 @@ def test_drop_mime_data_below_list(self): # Test dragging an item in the list and drop it below the last item obj = DummyHasTraits(names=["A", "B", "C", "D"]) view = get_view(TabularAdapter(columns=["Name"])) - with reraise_exceptions(), \ - create_ui(obj, dict(view=view)) as ui: - editor, = ui.get_editors("names") + with reraise_exceptions(), create_ui(obj, dict(view=view)) as ui: + (editor,) = ui.get_editors("names") model = editor.model # sanity check @@ -77,12 +76,17 @@ def test_drop_mime_data_below_list(self): # when # dropped below the list, the "parent" is invalid. - parent = QtCore.QModelIndex() # invalid index object + parent = QtCore.QModelIndex() # invalid index object model.dropMimeData(mime_data, QtCore.Qt.MoveAction, -1, -1, parent) # then mime_data = model.mimeData( - [model.createIndex(i, 0) for i in range(model.rowCount(None),)] + [ + model.createIndex(i, 0) + for i in range( + model.rowCount(None), + ) + ] ) content = mime_data.instance() self.assertEqual(content, ["A", "C", "D", "B"]) @@ -94,9 +98,8 @@ def test_drop_mime_data_within_list(self): obj = DummyHasTraits(names=["A", "B", "C", "D"]) view = get_view(TabularAdapter(columns=["Name"])) - with reraise_exceptions(), \ - create_ui(obj, dict(view=view)) as ui: - editor, = ui.get_editors("names") + with reraise_exceptions(), create_ui(obj, dict(view=view)) as ui: + (editor,) = ui.get_editors("names") model = editor.model # sanity check @@ -114,7 +117,12 @@ def test_drop_mime_data_within_list(self): # then mime_data = model.mimeData( - [model.createIndex(i, 0) for i in range(model.rowCount(None),)] + [ + model.createIndex(i, 0) + for i in range( + model.rowCount(None), + ) + ] ) content = mime_data.instance() self.assertEqual(content, ["B", "C", "A", "D"]) @@ -125,9 +133,8 @@ def test_copy_item(self): obj = DummyHasTraits(names=["A", "B", "C"]) view = get_view(TabularAdapter(columns=["Name"], can_drop=True)) - with reraise_exceptions(), \ - create_ui(obj, dict(view=view)) as ui: - editor, = ui.get_editors("names") + with reraise_exceptions(), create_ui(obj, dict(view=view)) as ui: + (editor,) = ui.get_editors("names") model = editor.model # sanity check @@ -146,7 +153,12 @@ def test_copy_item(self): # then self.assertEqual(model.rowCount(None), 4) mime_data = model.mimeData( - [model.createIndex(i, 0) for i in range(model.rowCount(None),)] + [ + model.createIndex(i, 0) + for i in range( + model.rowCount(None), + ) + ] ) content = mime_data.instance() self.assertEqual(content, ["A", "B", "C", "A"]) @@ -158,9 +170,8 @@ def test_move_rows_invalid_index(self): obj = DummyHasTraits(names=["A", "B", "C"]) view = get_view(TabularAdapter(columns=["Name"])) - with reraise_exceptions(), \ - create_ui(obj, dict(view=view)) as ui: - editor, = ui.get_editors("names") + with reraise_exceptions(), create_ui(obj, dict(view=view)) as ui: + (editor,) = ui.get_editors("names") model = editor.model # sanity check @@ -172,7 +183,12 @@ def test_move_rows_invalid_index(self): # then mime_data = model.mimeData( - [model.createIndex(i, 0) for i in range(model.rowCount(None),)] + [ + model.createIndex(i, 0) + for i in range( + model.rowCount(None), + ) + ] ) content = mime_data.instance() self.assertEqual(content, ["A", "C", "B"]) diff --git a/traitsui/qt4/tests/test_ui_base.py b/traitsui/qt4/tests/test_ui_base.py index 906e697e8..4e7fb3cd6 100644 --- a/traitsui/qt4/tests/test_ui_base.py +++ b/traitsui/qt4/tests/test_ui_base.py @@ -25,21 +25,17 @@ class ObjectWithNumber(HasTraits): @requires_toolkit([ToolkitName.qt]) class TestStickyDialog(unittest.TestCase): - """ Test _StickyDialog used by the UI's Qt backend. - """ + """Test _StickyDialog used by the UI's Qt backend.""" def test_sticky_dialog_with_parent(self): obj = ObjectWithNumber() obj2 = ObjectWithNumber() parent_view = View(Item("number"), title="Parent") - nested = View( - Item("number"), - resizable=True, - title="Nested" - ) + nested = View(Item("number"), resizable=True, title="Nested") with create_ui(obj, dict(view=parent_view)) as ui: with create_ui(obj2, dict(parent=ui.control, view=nested)) as ui2: from pyface.qt import QtCore + self.assertFalse( ui2.control.windowFlags() & QtCore.Qt.WindowMaximized ) diff --git a/traitsui/qt4/tests/test_ui_panel.py b/traitsui/qt4/tests/test_ui_panel.py index 5f111632a..053979d79 100644 --- a/traitsui/qt4/tests/test_ui_panel.py +++ b/traitsui/qt4/tests/test_ui_panel.py @@ -122,13 +122,13 @@ def default_traits_view(self): Item("bar"), scrollable=True, visible_when="enabled=='Yes'", - id='bar_group' + id='bar_group', ), VGroup( Item("baz"), scrollable=True, visible_when="enabled=='No'", - id='baz_group' + id='baz_group', ), ), ) @@ -227,7 +227,6 @@ def test_scrollable_group_visible_when(self): @requires_toolkit([ToolkitName.qt]) class TestPanelLayout(unittest.TestCase): - def test_scrollable_group_typical(self): from pyface.qt import QtGui diff --git a/traitsui/qt4/text_editor.py b/traitsui/qt4/text_editor.py index 44c981a94..0459d8097 100644 --- a/traitsui/qt4/text_editor.py +++ b/traitsui/qt4/text_editor.py @@ -37,8 +37,7 @@ class SimpleEditor(Editor): - """ Simple style text editor, which displays a text field. - """ + """Simple style text editor, which displays a text field.""" #: Flag for window styles: base_style = QtGui.QLineEdit @@ -60,8 +59,8 @@ class SimpleEditor(Editor): _connections_to_remove = List(Tuple(Any, Callable)) def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory wtype = self.base_style @@ -86,13 +85,15 @@ def init(self, parent): if wtype == QtGui.QTextEdit: control.textChanged.connect(self.update_object) self._connections_to_remove.append( - (control.textChanged, self.update_object)) + (control.textChanged, self.update_object) + ) else: # QLineEdit if factory.auto_set and not factory.is_grid_cell: control.textEdited.connect(self.update_object) self._connections_to_remove.append( - (control.textEdited, self.update_object)) + (control.textEdited, self.update_object) + ) else: control.editingFinished.connect(self.update_object) self._connections_to_remove.append( @@ -119,8 +120,7 @@ def init(self, parent): self.set_tooltip() def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" while self._connections_to_remove: signal, handler = self._connections_to_remove.pop() signal.disconnect(handler) @@ -128,8 +128,7 @@ def dispose(self): super().dispose() def update_object(self): - """ Handles the user entering input data in the edit control. - """ + """Handles the user entering input data in the edit control.""" if (not self._no_update) and (self.control is not None): try: self.value = self._get_user_value() @@ -144,8 +143,8 @@ def update_object(self): pass def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ user_value = self._get_user_value() try: @@ -165,8 +164,7 @@ def update_editor(self): self.set_error_state(False) def _get_user_value(self): - """ Gets the actual value corresponding to what the user typed. - """ + """Gets the actual value corresponding to what the user typed.""" try: value = self.control.text() except AttributeError: @@ -188,8 +186,7 @@ def _get_user_value(self): return ret def error(self, excp): - """ Handles an error that occurs while setting the object's trait value. - """ + """Handles an error that occurs while setting the object's trait value.""" if self._error is None: self._error = True self.ui.errors += 1 @@ -197,14 +194,12 @@ def error(self, excp): self.set_error_state(True) def in_error_state(self): - """ Returns whether or not the editor is in an error state. - """ + """Returns whether or not the editor is in an error state.""" return self.invalid or self._error class CustomEditor(SimpleEditor): - """ Custom style of text editor, which displays a multi-line text field. - """ + """Custom style of text editor, which displays a multi-line text field.""" #: FIXME: The wx version exposes a wx constant. #: Flag for window style. This value overrides the default. @@ -212,8 +207,7 @@ class CustomEditor(SimpleEditor): class ReadonlyEditor(BaseReadonlyEditor): - """ Read-only style of text editor, which displays a read-only text field. - """ + """Read-only style of text editor, which displays a read-only text field.""" def init(self, parent): super().init(parent) @@ -226,8 +220,8 @@ def init(self, parent): self.control.setTextInteractionFlags(flags) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ new_value = self.str_value diff --git a/traitsui/qt4/time_editor.py b/traitsui/qt4/time_editor.py index 99dc0510d..b984bdf0e 100644 --- a/traitsui/qt4/time_editor.py +++ b/traitsui/qt4/time_editor.py @@ -12,7 +12,6 @@ """ - import datetime from pyface.qt import QtCore, QtGui @@ -22,20 +21,19 @@ class SimpleEditor(Editor): - """ Simple Traits UI time editor that wraps QTimeEdit. - """ + """Simple Traits UI time editor that wraps QTimeEdit.""" def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = QtGui.QTimeEdit() self.control.timeChanged.connect(self.update_object) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ value = self.value if value: @@ -43,8 +41,7 @@ def update_editor(self): self.control.setTime(q_date) def update_object(self, q_time): - """ Handles the user entering input data in the edit control. - """ + """Handles the user entering input data in the edit control.""" hour = q_time.hour() minute = q_time.minute() second = q_time.second() @@ -61,12 +58,10 @@ def update_object(self, q_time): class ReadonlyEditor(BaseReadonlyEditor): - """ Readonly Traits UI time editor that uses a QLabel for the view. - """ + """Readonly Traits UI time editor that uses a QLabel for the view.""" def _get_str_value(self): - """ Replace the default string value with our own time verision. - """ + """Replace the default string value with our own time verision.""" if not self.value: return self.factory.message else: diff --git a/traitsui/qt4/title_editor.py b/traitsui/qt4/title_editor.py index 890ab295e..2d6cd2633 100644 --- a/traitsui/qt4/title_editor.py +++ b/traitsui/qt4/title_editor.py @@ -21,7 +21,6 @@ # ------------------------------------------------------------------------------ - from pyface.qt import QtCore from .editor import Editor @@ -31,8 +30,8 @@ class SimpleEditor(Editor): def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self._control = HeadingText(None) self.control = self._control.control @@ -45,8 +44,8 @@ def init(self, parent): self.set_tooltip() def update_editor(self): - """ Updates the editor when the object trait changes external to the - editor. + """Updates the editor when the object trait changes external to the + editor. """ self._control.text = self.str_value diff --git a/traitsui/qt4/toolkit.py b/traitsui/qt4/toolkit.py index f316a910d..407f3fc88 100644 --- a/traitsui/qt4/toolkit.py +++ b/traitsui/qt4/toolkit.py @@ -24,7 +24,6 @@ """ - # Make sure that importing from this backend is OK: from traitsui.toolkit import assert_toolkit_import @@ -51,8 +50,8 @@ class _CallAfter(QtCore.QObject): - """ This class dispatches a handler so that it executes in the main GUI - thread (similar to the wx function). + """This class dispatches a handler so that it executes in the main GUI + thread (similar to the wx function). """ # The list of pending calls. @@ -62,8 +61,7 @@ class _CallAfter(QtCore.QObject): _calls_mutex = QtCore.QMutex() def __init__(self, handler, *args, **kwds): - """ Initialise the call. - """ + """Initialise the call.""" QtCore.QObject.__init__(self) # Save the details of the call. @@ -86,8 +84,7 @@ def __init__(self, handler, *args, **kwds): QtGui.QApplication.instance().postEvent(self, event) def event(self, event): - """ QObject event handler. - """ + """QObject event handler.""" if event.type() == _QT_TRAITS_EVENT: # Invoke the handler self._handler(*self._args, **self._kwds) @@ -102,16 +99,15 @@ def event(self, event): return QtCore.QObject.event(self, event) def _finished(self): - """ Remove the call from the list, so it can be garbage collected. - """ + """Remove the call from the list, so it can be garbage collected.""" self._calls_mutex.lock() del self._calls[self._calls.index(self)] self._calls_mutex.unlock() def ui_handler(handler, *args, **kwds): - """ Handles UI notification handler requests that occur on a thread other - than the UI thread. + """Handles UI notification handler requests that occur on a thread other + than the UI thread. """ _CallAfter(handler, *args, **kwds) @@ -137,60 +133,59 @@ def eventFilter(self, object, event): class GUIToolkit(Toolkit): - """ Implementation class for PyQt toolkit. - """ + """Implementation class for PyQt toolkit.""" def ui_panel(self, ui, parent): - """ Creates a PyQt panel-based user interface using information - from the specified UI object. + """Creates a PyQt panel-based user interface using information + from the specified UI object. """ from . import ui_panel ui_panel.ui_panel(ui, parent) def ui_subpanel(self, ui, parent): - """ Creates a PyQt subpanel-based user interface using information - from the specified UI object. + """Creates a PyQt subpanel-based user interface using information + from the specified UI object. """ from . import ui_panel ui_panel.ui_subpanel(ui, parent) def ui_livemodal(self, ui, parent): - """ Creates a PyQt modal "live update" dialog user interface using - information from the specified UI object. + """Creates a PyQt modal "live update" dialog user interface using + information from the specified UI object. """ from . import ui_live ui_live.ui_livemodal(ui, parent) def ui_live(self, ui, parent): - """ Creates a PyQt non-modal "live update" window user interface - using information from the specified UI object. + """Creates a PyQt non-modal "live update" window user interface + using information from the specified UI object. """ from . import ui_live ui_live.ui_live(ui, parent) def ui_modal(self, ui, parent): - """ Creates a PyQt modal dialog user interface using information - from the specified UI object. + """Creates a PyQt modal dialog user interface using information + from the specified UI object. """ from . import ui_modal ui_modal.ui_modal(ui, parent) def ui_nonmodal(self, ui, parent): - """ Creates a PyQt non-modal dialog user interface using - information from the specified UI object. + """Creates a PyQt non-modal dialog user interface using + information from the specified UI object. """ from . import ui_modal ui_modal.ui_nonmodal(ui, parent) def ui_wizard(self, ui, parent): - """ Creates a PyQt wizard dialog user interface using information - from the specified UI object. + """Creates a PyQt wizard dialog user interface using information + from the specified UI object. """ import ui_wizard @@ -206,7 +201,7 @@ def view_application( scrollable=None, args=None, ): - """ Creates a PyQt modal dialog user interface that + """Creates a PyQt modal dialog user interface that runs as a complete application, using information from the specified View object. @@ -244,8 +239,7 @@ def view_application( ) def position(self, ui): - """ Positions the associated dialog window on the display. - """ + """Positions the associated dialog window on the display.""" view = ui.view window = ui.control @@ -324,50 +318,44 @@ def position(self, ui): window.setGeometry(max(0, x), max(0, y), width, height) def show_help(self, ui, control): - """ Shows a help window for a specified UI and control. - """ + """Shows a help window for a specified UI and control.""" from . import ui_panel ui_panel.show_help(ui, control) def save_window(self, ui): - """ Saves user preference information associated with a UI window. - """ + """Saves user preference information associated with a UI window.""" from . import helper helper.save_window(ui) def rebuild_ui(self, ui): - """ Rebuilds a UI after a change to the content of the UI. - """ + """Rebuilds a UI after a change to the content of the UI.""" if ui.control is not None: ui.recycle() ui.info.ui = ui ui.rebuild(ui, ui.parent) def set_title(self, ui): - """ Sets the title for the UI window. - """ + """Sets the title for the UI window.""" ui.control.setWindowTitle(ui.title) def set_icon(self, ui): - """ Sets the icon for the UI window. - """ + """Sets the icon for the UI window.""" from pyface.image_resource import ImageResource if isinstance(ui.icon, ImageResource): ui.control.setWindowIcon(ui.icon.create_icon()) def key_event_to_name(self, event): - """ Converts a keystroke event into a corresponding key name. - """ + """Converts a keystroke event into a corresponding key name.""" from . import key_event_to_name return key_event_to_name.key_event_to_name(event) def hook_events(self, ui, control, events=None, handler=None): - """ Hooks all specified events for all controls in a UI so that they - can be routed to the correct event handler. + """Hooks all specified events for all controls in a UI so that they + can be routed to the correct event handler. """ if events is None: # FIXME: Implement drag and drop events ala toolkit.py for wx @@ -381,14 +369,13 @@ def hook_events(self, ui, control, events=None, handler=None): control.installEventFilter(ui._key_event_hook) def skip_event(self, event): - """ Indicates that an event should continue to be processed by the - toolkit. + """Indicates that an event should continue to be processed by the + toolkit. """ event.ignore() def destroy_control(self, control): - """ Destroys a specified GUI toolkit control. - """ + """Destroys a specified GUI toolkit control.""" # Block signals to prevent any editors from being updated (the control # will not be deleted immediately). control.blockSignals(True) @@ -399,8 +386,8 @@ def destroy_control(self, control): control.deleteLater() def destroy_children(self, control): - """ Destroys all of the child controls of a specified GUI toolkit - control. + """Destroys all of the child controls of a specified GUI toolkit + control. """ for w in control.children(): # Only destroy widgets. @@ -410,18 +397,18 @@ def destroy_children(self, control): w.deleteLater() def image_size(self, image): - """ Returns a ( width, height ) tuple containing the size of a - specified toolkit image. + """Returns a ( width, height ) tuple containing the size of a + specified toolkit image. """ return (image.width(), image.height()) def constants(self): - """ Returns a dictionary of useful constants. + """Returns a dictionary of useful constants. - Currently, the dictionary should have the following key/value pairs: + Currently, the dictionary should have the following key/value pairs: - - 'WindowColor': the standard window background color in the toolkit - specific color format. + - 'WindowColor': the standard window background color in the toolkit + specific color format. """ return { "WindowColor": QtGui.QApplication.palette().color( diff --git a/traitsui/qt4/tree_editor.py b/traitsui/qt4/tree_editor.py index 0161d1d4c..f12c560f3 100644 --- a/traitsui/qt4/tree_editor.py +++ b/traitsui/qt4/tree_editor.py @@ -24,7 +24,6 @@ """ - import copy import collections.abc from functools import partial @@ -61,7 +60,6 @@ from .tree_node_renderers import WordWrapRenderer - logger = logging.getLogger(__name__) @@ -70,8 +68,7 @@ class SimpleEditor(Editor): - """ Simple style of tree editor. - """ + """Simple style of tree editor.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -103,8 +100,8 @@ class SimpleEditor(Editor): refresh = Event() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory @@ -208,8 +205,7 @@ def init(self, parent): self.sync_value(factory.veto, "veto", "from") def _selection_changed(self, selection): - """ Handles the **selection** event. - """ + """Handles the **selection** event.""" try: tree = self._tree if not isinstance(selection, str) and isinstance( @@ -233,24 +229,20 @@ def _selection_changed(self, selection): raise_to_debug() def _selected_changed(self, selected): - """ Handles the **selected** trait being changed. - """ + """Handles the **selected** trait being changed.""" if not self._no_update_selected: self._selection_changed(selected) def _veto_changed(self): - """ Handles the 'veto' event being fired. - """ + """Handles the 'veto' event being fired.""" self._veto = True def _refresh_changed(self): - """ Update the viewport. - """ + """Update the viewport.""" self._tree.viewport().update() def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" if self._tree is not None: # Stop the chatter (specifically about the changing selection). self._tree.blockSignals(True) @@ -262,8 +254,7 @@ def dispose(self): super().dispose() def expand_levels(self, nid, levels, expand=True): - """ Expands from the specified node the specified number of sub-levels. - """ + """Expands from the specified node the specified number of sub-levels.""" if levels > 0: expanded, node, object = self._get_node_data(nid) if self._has_children(node, object): @@ -274,7 +265,7 @@ def expand_levels(self, nid, levels, expand=True): self.expand_levels(cnid, levels - 1) def expand_all(self): - """ Expands all expandable nodes in the tree. + """Expands all expandable nodes in the tree. Warning: If the Tree contains a large number of items, this function will be very slow. @@ -291,8 +282,8 @@ def expand_all(self): iterator += 1 def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ tree = self._tree if tree is None: @@ -336,8 +327,7 @@ def update_editor(self): # FIXME: Clear the current editor (if any)... def get_error_control(self): - """ Returns the editor's control for indicating error status. - """ + """Returns the editor's control for indicating error status.""" return self._tree def _get_brush(self, color): @@ -348,7 +338,7 @@ def _get_brush(self, color): return QtGui.QBrush(q_color) def _set_column_labels(self, nid, node, object): - """ Set the column labels. """ + """Set the column labels.""" column_labels = node.get_column_labels(object) for i, (header, label) in enumerate( @@ -362,10 +352,10 @@ def _set_column_labels(self, nid, node, object): nid.setText(i, label) def _create_item(self, nid, node, object, index=None): - """ Create a new TreeWidgetItem as per word_wrap policy. + """Create a new TreeWidgetItem as per word_wrap policy. Index is the index of the new node in the parent: - None implies append the child to the end. """ + None implies append the child to the end.""" if index is None: cnid = QtGui.QTreeWidgetItem(nid) else: @@ -393,7 +383,7 @@ def _create_item(self, nid, node, object, index=None): return cnid def _set_label(self, nid, col=0): - """ Set the label of the specified item """ + """Set the label of the specified item""" if col != 0: # these are handled by _set_column_labels return @@ -406,13 +396,12 @@ def _set_label(self, nid, col=0): nid.setText(col, node.get_label(object)) def _append_node(self, nid, node, object): - """ Appends a new node to the specified node. - """ + """Appends a new node to the specified node.""" return self._insert_node(nid, None, node, object) def _insert_node(self, nid, index, node, object): - """ Inserts a new node before a specified index into the children of the - specified node. + """Inserts a new node before a specified index into the children of the + specified node. """ cnid = self._create_item(nid, node, object, index) @@ -439,8 +428,7 @@ def _insert_node(self, nid, index, node, object): return cnid def _delete_node(self, nid): - """ Deletes a specified tree node and all its children. - """ + """Deletes a specified tree node and all its children.""" for cnid in self._nodes_for(nid): self._delete_node(cnid) @@ -483,8 +471,7 @@ def _delete_node(self, nid): self._clear_editor() def _expand_node(self, nid): - """ Expands the contents of a specified node (if required). - """ + """Expands the contents of a specified node (if required).""" expanded, node, object = self._get_node_data(nid) # Lazily populate the item's children: @@ -504,8 +491,7 @@ def _expand_node(self, nid): self._set_node_data(nid, (True, node, object)) def _nodes_for(self, nid): - """ Returns all child node ids of a specified node id. - """ + """Returns all child node ids of a specified node id.""" return [nid.child(i) for i in range(nid.childCount())] def _node_index(self, nid): @@ -525,8 +511,7 @@ def _node_index(self, nid): return (None, None, None) def _has_children(self, node, object): - """ Returns whether a specified object has any children. - """ + """Returns whether a specified object has any children.""" return node.allows_children(object) and node.has_children(object) # ------------------------------------------------------------------------- @@ -540,8 +525,7 @@ def _has_children(self, node, object): } def _get_icon(self, node, object, is_expanded=False): - """ Returns the index of the specified object icon. - """ + """Returns the index of the specified object icon.""" if not self.factory.show_icons: return QtGui.QIcon() @@ -588,14 +572,13 @@ def _get_icon(self, node, object, is_expanded=False): return QtGui.QIcon(pixmap_cache(file_name)) def _icon_from_color(self, color): - """ Create a square icon filled with the given color. """ + """Create a square icon filled with the given color.""" pixmap = QtGui.QPixmap(self._tree.iconSize()) pixmap.fill(color) return QtGui.QIcon(pixmap) def _add_listeners(self, node, object): - """ Adds the event listeners for a specified object. - """ + """Adds the event listeners for a specified object.""" if node.allows_children(object): node.when_children_replaced(object, self._children_replaced, False) @@ -607,8 +590,7 @@ def _add_listeners(self, node, object): ) def _remove_listeners(self, node, object): - """ Removes any event listeners from a specified object. - """ + """Removes any event listeners from a specified object.""" if node.allows_children(object): node.when_children_replaced(object, self._children_replaced, True) @@ -620,8 +602,8 @@ def _remove_listeners(self, node, object): ) def _object_info(self, object, name=""): - """ Returns the tree node data for a specified object in the form - ( expanded, node, nid ). + """Returns the tree node data for a specified object in the form + ( expanded, node, nid ). """ info = self._map[id(object)] for name2, nid in info: @@ -635,8 +617,8 @@ def _object_info(self, object, name=""): return (expanded, node, nid) def _object_info_for(self, object, name=""): - """ Returns the tree node data for a specified object as a list of the - form: [ ( expanded, node, nid ), ... ]. + """Returns the tree node data for a specified object as a list of the + form: [ ( expanded, node, nid ), ... ]. """ result = [] for name2, nid in self._map[id(object)]: @@ -647,8 +629,7 @@ def _object_info_for(self, object, name=""): return result def _node_for(self, object): - """ Returns the TreeNode associated with a specified object. - """ + """Returns the TreeNode associated with a specified object.""" if ( (isinstance(object, tuple)) and (len(object) == 2) @@ -703,16 +684,14 @@ def _node_for(self, object): return (object, multi_node) def _node_for_class(self, klass): - """ Returns the TreeNode associated with a specified class. - """ + """Returns the TreeNode associated with a specified class.""" for node in self.factory.nodes: if issubclass(klass, tuple(node.node_for)): return node return None def _update_icon(self, nid): - """ Updates the icon for a specified node. - """ + """Updates the icon for a specified node.""" expanded, node, object = self._get_node_data(nid) renderer = node.get_renderer(object) if renderer is None or not renderer.handles_icon: @@ -721,8 +700,7 @@ def _update_icon(self, nid): nid.setIcon(0, QtGui.QIcon()) def _begin_undo(self): - """ Begins an "undoable" transaction. - """ + """Begins an "undoable" transaction.""" ui = self.ui self._undoable.append(ui._undoable) if (ui._undoable == -1) and (ui.history is not None): @@ -742,8 +720,7 @@ def _get_undo_item(self, object, name, event): ) def _undoable_append(self, node, object, data, make_copy=True): - """ Performs an undoable append operation. - """ + """Performs an undoable append operation.""" try: self._begin_undo() if make_copy: @@ -753,8 +730,7 @@ def _undoable_append(self, node, object, data, make_copy=True): self._end_undo() def _undoable_insert(self, node, object, index, data, make_copy=True): - """ Performs an undoable insert operation. - """ + """Performs an undoable insert operation.""" try: self._begin_undo() if make_copy: @@ -764,8 +740,7 @@ def _undoable_insert(self, node, object, index, data, make_copy=True): self._end_undo() def _undoable_delete(self, node, object, index): - """ Performs an undoable delete operation. - """ + """Performs an undoable delete operation.""" try: self._begin_undo() node.delete_child(object, index) @@ -773,8 +748,7 @@ def _undoable_delete(self, node, object, index): self._end_undo() def _get_object_nid(self, object, name=""): - """ Gets the ID associated with a specified object (if any). - """ + """Gets the ID associated with a specified object (if any).""" info = self._map.get(id(object)) if info is None: return None @@ -785,8 +759,7 @@ def _get_object_nid(self, object, name=""): return info[0][1] def _clear_editor(self): - """ Clears the current editor pane (if any). - """ + """Clears the current editor pane (if any).""" editor = self._editor if editor._node_ui is not None: editor.setWidget(None) @@ -799,24 +772,23 @@ def _clear_editor(self): @staticmethod def _get_node_data(nid): - """ Gets the node specific data. """ + """Gets the node specific data.""" return nid._py_data @staticmethod def _set_node_data(nid, data): - """ Sets the node specific data. """ + """Sets the node specific data.""" nid._py_data = data # ----- User callable methods: -------------------------------------------- def get_object(self, nid): - """ Gets the object associated with a specified node. - """ + """Gets the object associated with a specified node.""" return self._get_node_data(nid)[2] def get_parent(self, object, name=""): - """ Returns the object that is the immmediate parent of a specified - object in the tree. + """Returns the object that is the immmediate parent of a specified + object in the tree. """ nid = self._get_object_nid(object, name) if nid is not None: @@ -826,8 +798,7 @@ def get_parent(self, object, name=""): return None def get_node(self, object, name=""): - """ Returns the node associated with a specified object. - """ + """Returns the node associated with a specified object.""" nid = self._get_object_nid(object, name) if nid is not None: return self._get_node_data(nid)[1] @@ -836,8 +807,7 @@ def get_node(self, object, name=""): # ----- Tree event handlers: ---------------------------------------------- def _on_item_expanded(self, nid): - """ Handles a tree node being expanded. - """ + """Handles a tree node being expanded.""" expanded, node, object = self._get_node_data(nid) # If 'auto_close' requested for this node type, close all of the node's @@ -857,13 +827,11 @@ def _on_item_expanded(self, nid): self._update_icon(nid) def _on_item_collapsed(self, nid): - """ Handles a tree node being collapsed. - """ + """Handles a tree node being collapsed.""" self._update_icon(nid) def _on_item_clicked(self, nid, col): - """ Handles a tree item being clicked. - """ + """Handles a tree item being clicked.""" _, node, object = self._get_node_data(nid) if node.click(object) is True and self.factory.on_click is not None: @@ -873,8 +841,7 @@ def _on_item_clicked(self, nid, col): self.click = object def _on_item_dclicked(self, nid, col): - """ Handles a tree item being double-clicked. - """ + """Handles a tree item being double-clicked.""" _, node, object = self._get_node_data(nid) if node.dclick(object) is True: @@ -888,8 +855,7 @@ def _on_item_dclicked(self, nid, col): self.dclick = object def _on_item_activated(self, nid, col): - """ Handles a tree item being activated. - """ + """Handles a tree item being activated.""" _, node, object = self._get_node_data(nid) if node.activated(object) is True: @@ -903,8 +869,7 @@ def _on_item_activated(self, nid, col): self.activated = object def _on_tree_sel_changed(self): - """ Handles a tree node being selected. - """ + """Handles a tree node being selected.""" # Get the new selection: nids = self._tree.selectedItems() @@ -983,8 +948,7 @@ def _on_tree_sel_changed(self): editor.setUpdatesEnabled(True) def _on_context_menu(self, pos): - """ Handles the user requesting a context menuright clicking on a tree node. - """ + """Handles the user requesting a context menuright clicking on a tree node.""" nid = self._tree.itemAt(pos) if nid is None: @@ -1045,8 +1009,7 @@ def _on_context_menu(self, pos): ) = self._menu_parent_node = self._menu_parent_object = None def _standard_menu(self, node, object): - """ Returns the standard contextual pop-up menu. - """ + """Returns the standard contextual pop-up menu.""" actions = [ CutAction, CopyAction, @@ -1065,8 +1028,7 @@ def _standard_menu(self, node, object): return Menu(*actions) def _new_actions(self, node, object): - """ Returns a list of Actions that will create new objects. - """ + """Returns a list of Actions that will create new objects.""" object = self._data[1] items = [] add = node.get_add(object) @@ -1091,11 +1053,11 @@ def _new_actions(self, node, object): name = class_name if factory is None: factory = klass + def perform_add(object, factory, prompt): self._menu_new_node(factory, prompt) - on_perform = partial( - perform_add, factory=factory, prompt=prompt - ) + + on_perform = partial(perform_add, factory=factory, prompt=prompt) items.append(Action(name=name, on_perform=on_perform)) return items @@ -1155,16 +1117,14 @@ def _is_renameable(self, object): return can_rename def _is_droppable(self, node, object, add_object, for_insert): - """ Returns whether a given object is droppable on the node. - """ + """Returns whether a given object is droppable on the node.""" if for_insert and (not node.can_insert(object)): return False return node.can_add(object, add_object) def _drop_object(self, node, object, dropped_object, make_copy=True): - """ Returns a droppable version of a specified object. - """ + """Returns a droppable version of a specified object.""" new_object = node.drop_object(object, dropped_object) if (new_object is not dropped_object) or (not make_copy): return new_object @@ -1174,20 +1134,17 @@ def _drop_object(self, node, object, dropped_object, make_copy=True): # ----- pyface.action 'controller' interface implementation: -------------- def add_to_menu(self, menu_item): - """ Adds a menu item to the menu bar being constructed. - """ + """Adds a menu item to the menu bar being constructed.""" action = menu_item.item.action self.eval_when(action.enabled_when, menu_item, "enabled") self.eval_when(action.checked_when, menu_item, "checked") def add_to_toolbar(self, toolbar_item): - """ Adds a toolbar item to the toolbar being constructed. - """ + """Adds a toolbar item to the toolbar being constructed.""" self.add_to_menu(toolbar_item) def can_add_to_menu(self, action): - """ Returns whether the action should be defined in the user interface. - """ + """Returns whether the action should be defined in the user interface.""" if action.defined_when != "": if not eval(action.defined_when, globals(), self._context): return False @@ -1199,14 +1156,13 @@ def can_add_to_menu(self, action): return True def can_add_to_toolbar(self, action): - """ Returns whether the toolbar action should be defined in the user - interface. + """Returns whether the toolbar action should be defined in the user + interface. """ return self.can_add_to_menu(action) def perform(self, action, action_event=None): - """ Performs the action described by a specified Action object. - """ + """Performs the action described by a specified Action object.""" self.ui.do_undoable(self._perform, action) def _perform(self, action): @@ -1247,7 +1203,7 @@ def _perform(self, action): # ----- Menu support methods: --------------------------------------------- def eval_when(self, condition, object, trait): - """ Evaluates a condition within a defined context, and sets a + """Evaluates a condition within a defined context, and sets a specified object trait based on the result, which is assumed to be a Boolean. """ @@ -1266,30 +1222,27 @@ def eval_when(self, condition, object, trait): # ----- Menu event handlers: ---------------------------------------------- def _menu_copy_node(self): - """ Copies the current tree node object to the paste buffer. - """ + """Copies the current tree node object to the paste buffer.""" clipboard.instance = self._data[1] self._data = None def _menu_cut_node(self): - """ Cuts the current tree node object into the paste buffer. - """ + """Cuts the current tree node object into the paste buffer.""" node, object, nid = self._data clipboard.instance = object self._data = None self._undoable_delete(*self._node_index(nid)) def _menu_paste_node(self): - """ Pastes the current contents of the paste buffer into the current - node. + """Pastes the current contents of the paste buffer into the current + node. """ node, object, nid = self._data self._data = None self._undoable_append(node, object, clipboard.instance, True) def _menu_delete_node(self): - """ Deletes the current node from the tree. - """ + """Deletes the current node from the tree.""" node, object, nid = self._data self._data = None rc = node.confirm_delete(object) @@ -1310,15 +1263,13 @@ def _menu_delete_node(self): self._undoable_delete(*self._node_index(nid)) def _menu_rename_node(self): - """ Rename the current node. - """ + """Rename the current node.""" _, _, nid = self._data self._data = None self._tree.editItem(nid) def _on_nid_changed(self, nid, col): - """ Handle changes to a widget item. - """ + """Handle changes to a widget item.""" # The node data may not have been set up for the nid yet. Ignore it if # it hasn't. try: @@ -1336,8 +1287,7 @@ def _on_nid_changed(self, nid, col): self._set_label(nid, col) def _menu_new_node(self, factory, prompt=False): - """ Adds a new object to the current node. - """ + """Adds a new object to the current node.""" node, object, nid = self._data self._data = None new_object = factory() @@ -1354,8 +1304,7 @@ def _menu_new_node(self, factory, prompt=False): # ----- Model event handlers: --------------------------------------------- def _children_replaced(self, object, name="", new=None): - """ Handles the children of a node being completely replaced. - """ + """Handles the children of a node being completely replaced.""" tree = self._tree for expanded, node, nid in self._object_info_for(object, name): children = node.get_children(object) @@ -1387,8 +1336,7 @@ def _children_replaced(self, object, name="", new=None): nid.setExpanded(True) def _children_updated(self, object, name, event): - """ Handles the children of a node being changed. - """ + """Handles the children of a node being changed.""" # Log the change that was made made (removing '_items' from the end of # the name): name = name[:-6] @@ -1443,8 +1391,7 @@ def _children_updated(self, object, name, event): nid.setExpanded(True) def _label_updated(self, object, name, label): - """ Handles the label of an object being changed. - """ + """Handles the label of an object being changed.""" # Prevent the itemChanged() signal from being emitted. blk = self._tree.blockSignals(True) try: @@ -1463,8 +1410,7 @@ def _label_updated(self, object, name, label): self._tree.blockSignals(blk) def _column_labels_updated(self, object, name, new): - """ Handles the column labels of an object being changed. - """ + """Handles the column labels of an object being changed.""" # Prevent the itemChanged() signal from being emitted. blk = self._tree.blockSignals(True) try: @@ -1480,8 +1426,8 @@ def _column_labels_updated(self, object, name, new): # -- UI preference save/restore interface --------------------------------- def restore_prefs(self, prefs): - """ Restores any saved user preference information associated with the - editor. + """Restores any saved user preference information associated with the + editor. """ if isinstance(self.control, QtGui.QSplitter): if isinstance(prefs, dict): @@ -1497,8 +1443,7 @@ def restore_prefs(self, prefs): header.restoreState(prefs["column_state"]) def save_prefs(self): - """ Returns any user preference information associated with the editor. - """ + """Returns any user preference information associated with the editor.""" prefs = {} if isinstance(self.control, QtGui.QSplitter): prefs["structure"] = self.control.saveState().data() @@ -1513,14 +1458,13 @@ def save_prefs(self): class _TreeWidget(QtGui.QTreeWidget): - """ The _TreeWidget class is a specialised QTreeWidget that reimplements - the drag'n'drop support so that it hooks into the provided Traits - support. + """The _TreeWidget class is a specialised QTreeWidget that reimplements + the drag'n'drop support so that it hooks into the provided Traits + support. """ def __init__(self, editor, parent=None): - """ Initialise the tree widget. - """ + """Initialise the tree widget.""" QtGui.QTreeWidget.__init__(self, parent) self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) @@ -1566,7 +1510,7 @@ def __init__(self, editor, parent=None): self._dragging = None def resizeEvent(self, event): - """ Overridden to emit sizeHintChanged() of items for word wrapping """ + """Overridden to emit sizeHintChanged() of items for word wrapping""" if self._editor.factory.word_wrap: for i in range(self.topLevelItemCount()): mi = self.indexFromItem(self.topLevelItem(i)) @@ -1575,8 +1519,7 @@ def resizeEvent(self, event): super(self.__class__, self).resizeEvent(event) def startDrag(self, actions): - """ Reimplemented to start the drag of a tree widget item. - """ + """Reimplemented to start the drag of a tree widget item.""" nid = self.currentItem() if nid is None: return @@ -1620,8 +1563,8 @@ def startDrag(self, actions): drag.exec_(actions) def dragEnterEvent(self, e): - """ Reimplemented to see if the current drag can be handled by the - tree. + """Reimplemented to see if the current drag can be handled by the + tree. """ # Assume the drag is invalid. e.ignore() @@ -1636,8 +1579,8 @@ def dragEnterEvent(self, e): e.acceptProposedAction() def dragMoveEvent(self, e): - """ Reimplemented to see if the current drag can be handled by the - particular tree widget item underneath the cursor. + """Reimplemented to see if the current drag can be handled by the + particular tree widget item underneath the cursor. """ # Assume the drag is invalid. e.ignore() @@ -1648,8 +1591,7 @@ def dragMoveEvent(self, e): e.acceptProposedAction() def dropEvent(self, e): - """ Reimplemented to update the model and tree. - """ + """Reimplemented to update the model and tree.""" # Assume the drop is invalid. e.ignore() @@ -1711,8 +1653,7 @@ def dropEvent(self, e): e.acceptProposedAction() def _get_action(self, event): - """ Work out what action on what object to perform for a drop event - """ + """Work out what action on what object to perform for a drop event""" # default values to return action = None to_node = None @@ -1742,8 +1683,9 @@ def _get_action(self, event): data = PyMimeData.coerce(event.mimeData()).instance() _, node, object = editor._get_node_data(nid) - if event.proposedAction() == QtCore.Qt.MoveAction and editor._is_droppable( - node, object, data, False + if ( + event.proposedAction() == QtCore.Qt.MoveAction + and editor._is_droppable(node, object, data, False) ): # append to node being dropped on action = "append" @@ -1770,7 +1712,7 @@ def _get_action(self, event): class TreeItemDelegate(QtGui.QStyledItemDelegate): - """ A delegate class to draw wrapped text labels """ + """A delegate class to draw wrapped text labels""" # FIXME: sizeHint() should return the size required by the label, # which is dependent on the width available, which is different for @@ -1782,7 +1724,7 @@ class TreeItemDelegate(QtGui.QStyledItemDelegate): # TODO: add ability to override editor in item delegate def sizeHint(self, option, index): - """ returns area taken by the text. """ + """returns area taken by the text.""" column = index.column() item = self.editor._tree.itemFromIndex(index) expanded, node, instance = self.editor._get_node_data(item) @@ -1800,12 +1742,11 @@ def sizeHint(self, option, index): return QtCore.QSize(*size) def updateEditorGeometry(self, editor, option, index): - """ Update the editor's geometry. - """ + """Update the editor's geometry.""" editor.setGeometry(option.rect) def paint(self, painter, option, index): - """ Render the contents of the item. """ + """Render the contents of the item.""" item = self.editor._tree.itemFromIndex(index) expanded, node, instance = self.editor._get_node_data(item) column = index.column() diff --git a/traitsui/qt4/tree_node_renderers.py b/traitsui/qt4/tree_node_renderers.py index 9c644cbe4..6bb2779a1 100644 --- a/traitsui/qt4/tree_node_renderers.py +++ b/traitsui/qt4/tree_node_renderers.py @@ -18,7 +18,7 @@ class WordWrapRenderer(AbstractTreeNodeRenderer): - """ A renderer that wraps the label text across multiple lines. """ + """A renderer that wraps the label text across multiple lines.""" #: The padding around the text. padding = HasBorder(0) @@ -34,7 +34,7 @@ class WordWrapRenderer(AbstractTreeNodeRenderer): extra_space = Int(8) def paint(self, editor, node, column, object, paint_context): - """ Paint word-wrapped text with elision. """ + """Paint word-wrapped text with elision.""" painter, option, index = paint_context text = self.get_label(node, object, column) @@ -69,7 +69,7 @@ def paint(self, editor, node, column, object, paint_context): painter.setPen(old_pen) def size(self, editor, node, column, object, size_context): - """ Return the preferred size for the word-wrapped text + """Return the preferred size for the word-wrapped text Parameters ---------- diff --git a/traitsui/qt4/tuple_editor.py b/traitsui/qt4/tuple_editor.py index 7cabc21a1..77d1905cc 100644 --- a/traitsui/qt4/tuple_editor.py +++ b/traitsui/qt4/tuple_editor.py @@ -34,7 +34,7 @@ class SimpleEditor(BaseSimpleEditor, Editor): - """ Simple style of editor for tuples. + """Simple style of editor for tuples. The editor displays an editor for each of the fields in the tuple, based on the type of each field. diff --git a/traitsui/qt4/ui_base.py b/traitsui/qt4/ui_base.py index d5c15d741..9ab2507f6 100644 --- a/traitsui/qt4/ui_base.py +++ b/traitsui/qt4/ui_base.py @@ -36,8 +36,7 @@ class ButtonEditor(Editor): - """ Editor for buttons. - """ + """Editor for buttons.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -51,15 +50,13 @@ def __init__(self, **traits): HasPrivateTraits.__init__(self, **traits) def perform(self): - """ Handles the associated button being clicked. - """ + """Handles the associated button being clicked.""" handler = self.ui.handler self.ui.do_undoable(handler.perform, self.ui.info, self.action, None) class BasePanel(_BasePanel): - """Base class for Traits UI panels. - """ + """Base class for Traits UI panels.""" def add_button( self, @@ -71,8 +68,7 @@ def add_button( name=None, default=False, ): - """ Creates a button. - """ + """Creates a button.""" ui = self.ui if (action.defined_when != "") and ( not ui.eval_when(action.defined_when) @@ -106,20 +102,17 @@ def add_button( return button def _on_undoable(self, event): - """Handles a change to the "undoable" state of the undo history - """ + """Handles a change to the "undoable" state of the undo history""" state = event.new self.undo.setEnabled(state) def _on_redoable(self, event): - """Handles a change to the "redoable" state of the undo history. - """ + """Handles a change to the "redoable" state of the undo history.""" state = event.new self.redo.setEnabled(state) def _on_revertable(self, event): - """ Handles a change to the "revert" state. - """ + """Handles a change to the "revert" state.""" state = event.new self.revert.setEnabled(state) @@ -197,8 +190,7 @@ def keyPressEvent(self, e): QtGui.QDialog.keyPressEvent(self, e) def sizeHint(self): - """Reimplemented to provide an appropriate size hint for the window. - """ + """Reimplemented to provide an appropriate size hint for the window.""" size = QtGui.QDialog.sizeHint(self) view = self._ui.view if view.width > 0: @@ -339,8 +331,7 @@ def _on_error(self, event): self.ok.setEnabled(errors == 0) def _add_menubar(self): - """Adds a menu bar to the dialog. - """ + """Adds a menu bar to the dialog.""" menubar = self.ui.view.menubar if menubar is not None: self._last_group = self._last_parent = None @@ -350,8 +341,7 @@ def _add_menubar(self): self._last_group = self._last_parent = None def _add_toolbar(self): - """ Adds a toolbar to the dialog. - """ + """Adds a toolbar to the dialog.""" toolbar = self.ui.view.toolbar if toolbar is not None: self._last_group = self._last_parent = None @@ -361,8 +351,7 @@ def _add_toolbar(self): self._last_group = self._last_parent = None def _add_statusbar(self): - """ Adds a statusbar to the dialog. - """ + """Adds a statusbar to the dialog.""" if self.ui.view.statusbar is not None: control = QtGui.QStatusBar() control.setSizeGripEnabled(self.ui.view.resizable) @@ -397,8 +386,7 @@ def _add_statusbar(self): self.ui._statusbar = listeners def _set_status_text(self, control): - """ Helper function for _add_statusbar. - """ + """Helper function for _add_statusbar.""" def set_status_text(event): text = event.new diff --git a/traitsui/qt4/ui_editor.py b/traitsui/qt4/ui_editor.py index dfd59454f..7ac58d9b6 100644 --- a/traitsui/qt4/ui_editor.py +++ b/traitsui/qt4/ui_editor.py @@ -23,7 +23,6 @@ class UIEditor(BaseUIEditor, Editor): - """ An editor that creates an embedded Traits UI. - """ + """An editor that creates an embedded Traits UI.""" pass diff --git a/traitsui/qt4/ui_live.py b/traitsui/qt4/ui_live.py index 360cb1f88..5d14b90dc 100644 --- a/traitsui/qt4/ui_live.py +++ b/traitsui/qt4/ui_live.py @@ -48,27 +48,24 @@ def ui_live(ui, parent): - """Creates a live, non-modal PyQt user interface for a specified UI object. - """ + """Creates a live, non-modal PyQt user interface for a specified UI object.""" _ui_dialog(ui, parent, BaseDialog.NONMODAL) def ui_livemodal(ui, parent): - """Creates a live, modal PyQt user interface for a specified UI object. - """ + """Creates a live, modal PyQt user interface for a specified UI object.""" _ui_dialog(ui, parent, BaseDialog.MODAL) def ui_popup(ui, parent): """Creates a live, modal popup PyQt user interface for a specified UI - object. + object. """ _ui_dialog(ui, parent, BaseDialog.POPUP) def _ui_dialog(ui, parent, style): - """Creates a live PyQt user interface for a specified UI object. - """ + """Creates a live PyQt user interface for a specified UI object.""" if ui.owner is None: ui.owner = _LiveWindow() @@ -76,14 +73,13 @@ def _ui_dialog(ui, parent, style): class _LiveWindow(BaseDialog): - """User interface window that immediately updates its underlying object(s). - """ + """User interface window that immediately updates its underlying object(s).""" def init(self, ui, parent, style): """Initialise the object. - FIXME: Note that we treat MODAL and POPUP as equivalent until we - have an example that demonstrates how POPUP is supposed to work. + FIXME: Note that we treat MODAL and POPUP as equivalent until we + have an example that demonstrates how POPUP is supposed to work. """ self.ui = ui self.control = ui.control @@ -235,15 +231,13 @@ def init(self, ui, parent, style): self.add_contents(panel(ui), bbox) def close(self, rc=True): - """Close the dialog and set the given return code. - """ + """Close the dialog and set the given return code.""" super().close(rc) self.undo = self.redo = self.revert = None def _on_finished(self, result): - """Handles the user finishing with the dialog. - """ + """Handles the user finishing with the dialog.""" accept = bool(result) if not accept and self.ui.history is not None: diff --git a/traitsui/qt4/ui_modal.py b/traitsui/qt4/ui_modal.py index fac5d6398..3d31ad1ca 100644 --- a/traitsui/qt4/ui_modal.py +++ b/traitsui/qt4/ui_modal.py @@ -45,23 +45,21 @@ def ui_modal(ui, parent): - """Creates a modal PyQt user interface for a specified UI object. - """ + """Creates a modal PyQt user interface for a specified UI object.""" _ui_dialog(ui, parent, BaseDialog.MODAL) def ui_nonmodal(ui, parent): - """Creates a non-modal PyQt user interface for a specified UI object. - """ + """Creates a non-modal PyQt user interface for a specified UI object.""" _ui_dialog(ui, parent, BaseDialog.NONMODAL) def _ui_dialog(ui, parent, style): """Creates a PyQt dialog box for a specified UI object. - Changes are not immediately applied to the underlying object. The user - must click **Apply** or **OK** to apply changes. The user can revert - changes by clicking **Revert** or **Cancel**. + Changes are not immediately applied to the underlying object. The user + must click **Apply** or **OK** to apply changes. The user can revert + changes by clicking **Revert** or **Cancel**. """ if ui.owner is None: ui.owner = _ModalDialog() @@ -70,12 +68,10 @@ def _ui_dialog(ui, parent, style): class _ModalDialog(BaseDialog): - """Modal dialog box for Traits-based user interfaces. - """ + """Modal dialog box for Traits-based user interfaces.""" def init(self, ui, parent, style): - """Initialise the object. - """ + """Initialise the object.""" self.ui = ui self.control = ui.control view = ui.view @@ -133,9 +129,7 @@ def init(self, ui, parent, style): enabled=apply, default=default, ) - ui.observe( - self._on_applyable, "modified", dispatch="ui" - ) + ui.observe(self._on_applyable, "modified", dispatch="ui") elif self.is_button(button, "Revert"): self.revert = self.add_button( @@ -189,15 +183,13 @@ def init(self, ui, parent, style): self.add_contents(panel(ui), bbox) def close(self, rc=True): - """Close the dialog and set the given return code. - """ + """Close the dialog and set the given return code.""" super().close(rc) self.apply = self.revert = self.help = None def _copy_context(self, context): - """Creates a copy of a *context* dictionary. - """ + """Creates a copy of a *context* dictionary.""" result = {} for name, value in context.items(): if value is not None: @@ -208,8 +200,7 @@ def _copy_context(self, context): return result def _apply_context(self, from_context, to_context): - """Applies the traits in the *from_context* to the *to_context*. - """ + """Applies the traits in the *from_context* to the *to_context*.""" for name, value in from_context.items(): if value is not None: to_context[name].copy_traits(value) @@ -222,8 +213,7 @@ def _apply_context(self, from_context, to_context): on_apply() def _on_finished(self, result): - """Handles the user finishing with the dialog. - """ + """Handles the user finishing with the dialog.""" accept = bool(result) if accept: @@ -234,8 +224,7 @@ def _on_finished(self, result): self.close(accept) def _on_apply(self): - """Handles a request to apply changes. - """ + """Handles a request to apply changes.""" ui = self.ui self._apply_context(ui.context, ui._context) self.revert.setEnabled(True) @@ -243,14 +232,12 @@ def _on_apply(self): ui.modified = False def _on_applyable(self, event): - """Handles a change to the "modified" state of the user interface . - """ + """Handles a change to the "modified" state of the user interface .""" state = event.new self.apply.setEnabled(state) def _on_revert(self): - """Handles a request to revert changes. - """ + """Handles a request to revert changes.""" ui = self.ui self._apply_context(ui._revert, ui.context) self._apply_context(ui._revert, ui._context) diff --git a/traitsui/qt4/ui_panel.py b/traitsui/qt4/ui_panel.py index 18fb0466f..eef8cf91b 100644 --- a/traitsui/qt4/ui_panel.py +++ b/traitsui/qt4/ui_panel.py @@ -60,22 +60,20 @@ def ui_panel(ui, parent): - """Creates a panel-based PyQt user interface for a specified UI object. - """ + """Creates a panel-based PyQt user interface for a specified UI object.""" _ui_panel_for(ui, parent, False) def ui_subpanel(ui, parent): """Creates a subpanel-based PyQt user interface for a specified UI object. - A subpanel does not allow control buttons (other than those specified in - the UI object) and does not show headers for view titles. + A subpanel does not allow control buttons (other than those specified in + the UI object) and does not show headers for view titles. """ _ui_panel_for(ui, parent, True) def _ui_panel_for(ui, parent, is_subpanel): - """Creates a panel-based PyQt user interface for a specified UI object. - """ + """Creates a panel-based PyQt user interface for a specified UI object.""" ui.control = control = _Panel(ui, parent, is_subpanel).control control._parent = parent @@ -96,12 +94,10 @@ def _ui_panel_for(ui, parent, is_subpanel): class _Panel(BasePanel): - """PyQt user interface panel for Traits-based user interfaces. - """ + """PyQt user interface panel for Traits-based user interfaces.""" def __init__(self, ui, parent, is_subpanel): - """Initialise the object. - """ + """Initialise the object.""" super().__init__(ui=ui) history = ui.history @@ -233,8 +229,7 @@ def __init__(self, ui, parent, is_subpanel): self.control.sizeHint = _size_hint_wrapper(self.control.sizeHint, ui) def _add_toolbar(self, parent): - """ Adds a toolbar to the `parent` (QtWindow) - """ + """Adds a toolbar to the `parent` (QtWindow)""" if not isinstance(parent, QtGui.QMainWindow): # toolbar cannot be added to non-MainWindow widget return @@ -249,7 +244,7 @@ def _add_toolbar(self, parent): def can_add_to_toolbar(self, action): """Returns whether the toolbar action should be defined in the user - interface. + interface. """ if action.defined_when == "": return True @@ -259,8 +254,8 @@ def can_add_to_toolbar(self, action): def panel(ui): """Creates a panel-based PyQt user interface for a specified UI object. - This function does not modify the UI object passed to it. The object - returned may be either a widget, a layout or None. + This function does not modify the UI object passed to it. The object + returned may be either a widget, a layout or None. """ # Bind the context values to the 'info' object: ui.info.bind_context() @@ -295,8 +290,7 @@ def panel(ui): def _fill_panel(panel, content, ui, item_handler=None): - """Fill a page based container panel with content. - """ + """Fill a page based container panel with content.""" active = 0 for index, item in enumerate(content): @@ -346,8 +340,7 @@ def _fill_panel(panel, content, ui, item_handler=None): def _size_hint_wrapper(f, ui): - """Wrap an existing sizeHint method with sizes from a UI object. - """ + """Wrap an existing sizeHint method with sizes from a UI object.""" def sizeHint(): size = f() @@ -362,8 +355,7 @@ def sizeHint(): def show_help(ui, button): - """ Displays a help window for the specified UI's active Group. - """ + """Displays a help window for the specified UI's active Group.""" group = ui._groups[ui._active_group] template = help_template() if group.help != "": @@ -385,8 +377,7 @@ def show_help(ui, button): def show_help_popup(event): - """ Displays a pop-up help window for a single trait. - """ + """Displays a pop-up help window for a single trait.""" control = event.GetEventObject() template = help_template() @@ -400,23 +391,21 @@ def show_help_popup(event): class _GroupSplitter(QtGui.QSplitter): - """ A splitter for a Traits UI Group with layout='split'. - """ + """A splitter for a Traits UI Group with layout='split'.""" def __init__(self, group): - """ Store the group. - """ + """Store the group.""" QtGui.QSplitter.__init__(self) self._group = group self._initialized = False def resizeEvent(self, event): - """ Overridden to position the splitter based on the Group when the - application is initializing. + """Overridden to position the splitter based on the Group when the + application is initializing. - Because the splitter layout algorithm requires that the available - space be known, we have to wait until the UI that contains this - splitter gives it its initial size. + Because the splitter layout algorithm requires that the available + space be known, we have to wait until the UI that contains this + splitter gives it its initial size. """ QtGui.QSplitter.resizeEvent(self, event) @@ -430,16 +419,15 @@ def resizeEvent(self, event): self._resize_items() def showEvent(self, event): - """ Wait for the show event to resize items if necessary. - """ + """Wait for the show event to resize items if necessary.""" QtGui.QSplitter.showEvent(self, event) if not self._initialized: self._initialized = True self._resize_items() def _resize_items(self): - """ Size the splitter based on the 'width' or 'height' attributes - of the Traits UI view elements. + """Size the splitter based on the 'width' or 'height' attributes + of the Traits UI view elements. """ use_widths = self.orientation() == QtCore.Qt.Horizontal @@ -493,12 +481,11 @@ def _resize_items(self): class _GroupPanel(object): """A sub-panel for a single group of items. It may be either a layout or a - widget. + widget. """ def __init__(self, group, ui, suppress_label=False): - """Initialise the object. - """ + """Initialise the object.""" # Get the contents of the group: content = group.get_content() @@ -655,8 +642,7 @@ def __init__(self, group, ui, suppress_label=False): self.sub_control = sub def _add_splitter_items(self, content, splitter): - """Adds a set of groups or items separated by splitter bars. - """ + """Adds a set of groups or items separated by splitter bars.""" for item in content: # Get a panel for the Item or Group. @@ -683,8 +669,7 @@ def _add_splitter_items(self, content, splitter): splitter.addWidget(panel) def _setup_editor(self, group, editor): - """Setup the editor for a group. - """ + """Setup the editor for a group.""" if group.id != "": self.ui.info.bind(group.id, editor) @@ -695,13 +680,12 @@ def _setup_editor(self, group, editor): self.ui.add_enabled(group.enabled_when, editor) def _add_page_item(self, item, layout): - """Adds a single Item to a page based panel. - """ + """Adds a single Item to a page based panel.""" self._add_items([item], layout) def _add_groups(self, content, outer): """Adds a list of Group objects to the panel, creating a layout if - needed. Return the outermost layout. + needed. Return the outermost layout. """ # Use the existing layout if there is one. if outer is None: @@ -724,15 +708,15 @@ def _add_groups(self, content, outer): def _label_when(self): """Set the visible and enabled states of all labels as controlled by - a 'visible_when' or 'enabled_when' expression. + a 'visible_when' or 'enabled_when' expression. """ self._evaluate_label_condition(self._label_enabled_whens, "enabled") self._evaluate_label_condition(self._label_visible_whens, "visible") - + def _evaluate_label_condition(self, conditions, kind): """Evaluates a list of (eval, widget) pairs and calls the appropriate - method on the label widget to toggle whether it is visible/enabled - as needed. + method on the label widget to toggle whether it is visible/enabled + as needed. """ context = self.ui._get_context(self.ui.context) @@ -751,7 +735,7 @@ def _evaluate_label_condition(self, conditions, kind): def _add_items(self, content, outer=None): """Adds a list of Item objects, creating a layout if needed. Return - the outermost layout. + the outermost layout. """ # Get local references to various objects we need: ui = self.ui @@ -816,12 +800,14 @@ def _add_items(self, content, outer=None): # Check if is a label: if name == "": label = item.label - if label != "": + if label != "": self._add_label_item(item, inner, row, col, show_labels) # Check if it is a separator: elif name == "_": - self._add_separator_item(item, columns, inner, row, col, show_labels) + self._add_separator_item( + item, columns, inner, row, col, show_labels + ) # Check if it is a spacer: elif all_digits.match(name): @@ -862,7 +848,9 @@ def _add_items(self, content, outer=None): editor_factory.invalid = item.invalid # Create the requested type of editor from the editor factory: - factory_method = getattr(editor_factory, item.style + "_editor") + factory_method = getattr( + editor_factory, item.style + "_editor" + ) editor = factory_method( ui, object, name, item.tooltip, None ).trait_set(item=item, object_name=item.object) @@ -906,7 +894,9 @@ def _add_items(self, content, outer=None): item_width = item.width item_height = item.height if (item_width != -1) or (item_height != -1): - is_horizontal = self.direction == QtGui.QBoxLayout.LeftToRight + is_horizontal = ( + self.direction == QtGui.QBoxLayout.LeftToRight + ) min_size = control.minimumSizeHint() width = min_size.width() @@ -981,9 +971,13 @@ def _add_items(self, content, outer=None): if item.enabled_when != "": ui.add_enabled(item.enabled_when, editor) - if (len(self._label_enabled_whens) + len(self._label_visible_whens)) > 0: + if ( + len(self._label_enabled_whens) + len(self._label_visible_whens) + ) > 0: for object in self.ui.context.values(): - object.on_trait_change(lambda: self._label_when(), dispatch="ui") + object.on_trait_change( + lambda: self._label_when(), dispatch="ui" + ) self._label_when() return outer @@ -1015,7 +1009,6 @@ def _add_separator_item(self, item, columns, inner, row, col, show_labels): if col > 0: col = 0 - # Allow for the columns. if show_labels: cols *= 2 @@ -1054,7 +1047,7 @@ def _add_spacer_item(self, item, name, inner, row, col, show_labels): self._add_widget(inner, spacer, row, col, show_labels) def _set_item_size_policy(self, editor, item, label, stretch): - """ Set size policy of an item and its label (if any). + """Set size policy of an item and its label (if any). How it is set: @@ -1115,7 +1108,7 @@ def _set_item_size_policy(self, editor, item, label, stretch): return stretch def _make_label_h_stretchable(self, label, stretch): - """ Set size policies of a QLabel to be stretchable horizontally. + """Set size policies of a QLabel to be stretchable horizontally. :attr:`stretch` is the stretch factor that Qt uses to distribute the total size to individual elements @@ -1135,7 +1128,7 @@ def _add_widget( label_alignment=QtCore.Qt.AlignmentFlag(0), ): """Adds a widget to a layout taking into account the orientation and - the position of any labels. + the position of any labels. """ # If the widget really is a widget then remove any margin so that it # fills the cell. @@ -1236,8 +1229,7 @@ def _create_label(self, item, ui, desc, suffix=":"): return label_control def _add_emphasis(self, control): - """Adds emphasis to a specified control's font. - """ + """Adds emphasis to a specified control's font.""" # Set the foreground colour. pal = QtGui.QPalette(control.palette()) pal.setColor(QtGui.QPalette.WindowText, QtGui.QColor(0, 0, 127)) @@ -1251,12 +1243,10 @@ def _add_emphasis(self, control): class GroupEditor(Editor): - """ A pseudo-editor that allows a group to be managed. - """ + """A pseudo-editor that allows a group to be managed.""" def __init__(self, **traits): - """ Initialise the object. - """ + """Initialise the object.""" # We intentionally don't want to call Editor.__init__ here as # GroupEditor does its own thing. However, we still want Traits # machinery to be set up properly. @@ -1265,8 +1255,7 @@ def __init__(self, **traits): class SplitterGroupEditor(GroupEditor): - """ A pseudo-editor that allows a group with a 'split' layout to be managed. - """ + """A pseudo-editor that allows a group with a 'split' layout to be managed.""" #: The QSplitter for the group splitter = Instance(_GroupSplitter) @@ -1274,8 +1263,8 @@ class SplitterGroupEditor(GroupEditor): # -- UI preference save/restore interface --------------------------------- def restore_prefs(self, prefs): - """ Restores any saved user preference information associated with the - editor. + """Restores any saved user preference information associated with the + editor. """ if isinstance(prefs, dict): structure = prefs.get("structure") @@ -1286,14 +1275,13 @@ def restore_prefs(self, prefs): self.splitter.restoreState(structure) def save_prefs(self): - """ Returns any user preference information associated with the editor. - """ + """Returns any user preference information associated with the editor.""" return {"structure": self.splitter.saveState().data()} class TabbedFoldGroupEditor(GroupEditor): - """ A pseudo-editor that allows a group with a 'tabbed' or 'fold' layout to - be managed. + """A pseudo-editor that allows a group with a 'tabbed' or 'fold' layout to + be managed. """ #: The QTabWidget or QToolBox for the group @@ -1302,8 +1290,8 @@ class TabbedFoldGroupEditor(GroupEditor): # -- UI preference save/restore interface --------------------------------- def restore_prefs(self, prefs): - """ Restores any saved user preference information associated with the - editor. + """Restores any saved user preference information associated with the + editor. """ if isinstance(prefs, dict): current_index = prefs.get("current_index") @@ -1313,8 +1301,7 @@ def restore_prefs(self, prefs): self.container.setCurrentIndex(int(current_index)) def save_prefs(self): - """ Returns any user preference information associated with the editor. - """ + """Returns any user preference information associated with the editor.""" return {"current_index": str(self.container.currentIndex())} @@ -1324,12 +1311,10 @@ def save_prefs(self): class HTMLHelpWindow(QtGui.QDialog): - """ Window for displaying Traits-based help text with HTML formatting. - """ + """Window for displaying Traits-based help text with HTML formatting.""" def __init__(self, parent, html_content, scale_dx, scale_dy): - """ Initializes the object. - """ + """Initializes the object.""" # Local import to avoid a WebKit dependency when one isn't needed. from pyface.qt import QtWebKit @@ -1365,8 +1350,7 @@ def __init__(self, parent, html_content, scale_dx, scale_dy): def heading_text(*args, **kw): - """Create a Pyface HeadingText control. - """ + """Create a Pyface HeadingText control.""" global HeadingText if HeadingText is None: diff --git a/traitsui/qt4/value_editor.py b/traitsui/qt4/value_editor.py index 7b4691696..69f4900ff 100644 --- a/traitsui/qt4/value_editor.py +++ b/traitsui/qt4/value_editor.py @@ -19,16 +19,14 @@ class SimpleEditor(_ValueEditor, Editor): - """ Returns the editor to use for simple style views. - """ + """Returns the editor to use for simple style views.""" #: Override the value of the readonly trait. readonly = False class ReadonlyEditor(_ValueEditor, Editor): - """ Returns the editor to use for readonly style views. - """ + """Returns the editor to use for readonly style views.""" #: Override the value of the readonly trait. readonly = True diff --git a/traitsui/qt4/video_editor.py b/traitsui/qt4/video_editor.py index fa081468d..bc5f256cc 100644 --- a/traitsui/qt4/video_editor.py +++ b/traitsui/qt4/video_editor.py @@ -11,9 +11,14 @@ """Traits UI 'display only' video editor.""" from pyface.qt.QtCore import QPoint, Qt, QUrl, Signal from pyface.qt.QtGui import QImage, QPainter, QPalette, QSizePolicy -from pyface.qt.QtMultimedia import (QAbstractVideoBuffer, - QAbstractVideoSurface, QAudio, - QMediaContent, QMediaPlayer, QVideoFrame) +from pyface.qt.QtMultimedia import ( + QAbstractVideoBuffer, + QAbstractVideoSurface, + QAudio, + QMediaContent, + QMediaPlayer, + QVideoFrame, +) from pyface.qt.QtMultimediaWidgets import QVideoWidget from traits.api import Bool, Callable, Float, Instance, Range, Str, observe from traitsui.editors.video_editor import AspectRatio, MediaStatus, PlayerState @@ -52,19 +57,22 @@ class ImageWidget(QVideoWidget): - """ Paints a QImage to the window body. """ + """Paints a QImage to the window body.""" def __init__(self, parent=None, image_func=None): import numpy as np + super().__init__(parent) self.image = QImage() self._np_image = np.zeros(shape=(0, 0, 4)) self.painter = None self.resizeEvent(None) if image_func is None: + def I_fun(image, bbox): # Don't bother with creating an ndarray version return image, self._np_image + self.image_func = I_fun else: self.image_func = image_func @@ -109,7 +117,7 @@ def present(self, frame): cloned_frame.width(), cloned_frame.height(), cloned_frame.bytesPerLine(), - QVideoFrame.imageFormatFromPixelFormat(cloned_frame.pixelFormat()) + QVideoFrame.imageFormatFromPixelFormat(cloned_frame.pixelFormat()), ) self.frameAvailable.emit(image) return True @@ -260,32 +268,43 @@ def _connect_signals(self): if self.media_player is not None: self.media_player.stateChanged.connect(self._state_changed_emitted) self.media_player.positionChanged.connect( - self._position_changed_emitted) + self._position_changed_emitted + ) self.media_player.durationChanged.connect( - self._duration_changed_emitted) + self._duration_changed_emitted + ) self.media_player.error.connect(self._error_emitted) self.media_player.mediaStatusChanged.connect( - self._media_status_changed_emitted) + self._media_status_changed_emitted + ) self.media_player.bufferStatusChanged.connect( - self._buffer_status_changed_emitted) + self._buffer_status_changed_emitted + ) self.media_player.notifyIntervalChanged.connect( - self._notify_interval_changed_emitted) + self._notify_interval_changed_emitted + ) def _disconnect_signals(self): if self.media_player is not None: self.media_player.stateChanged.disconnect( - self._state_changed_emitted) + self._state_changed_emitted + ) self.media_player.positionChanged.disconnect( - self._position_changed_emitted) + self._position_changed_emitted + ) self.media_player.durationChanged.disconnect( - self._duration_changed_emitted) + self._duration_changed_emitted + ) self.media_player.error.disconnect(self._error_emitted) self.media_player.mediaStatusChanged.disconnect( - self._media_status_changed_emitted) + self._media_status_changed_emitted + ) self.media_player.bufferStatusChanged.disconnect( - self._buffer_status_changed_emitted) + self._buffer_status_changed_emitted + ) self.media_player.notifyIntervalChanged.disconnect( - self._notify_interval_changed_emitted) + self._notify_interval_changed_emitted + ) def _set_video_url(self): qurl = QUrl.fromUserInput(self.value) @@ -396,14 +415,14 @@ def _update_state(self): w = s.width() h = s.height() self.media_player.play() - self.control.resize(w+1, h+1) + self.control.resize(w + 1, h + 1) self.control.resize(w, h) elif self.state == 'paused': self.media_player.pause() def _update_volume(self): linear_volume = QAudio.convertVolume( - self.volume/100.0, + self.volume / 100.0, QAudio.LogarithmicVolumeScale, QAudio.LinearVolumeScale, ) diff --git a/traitsui/qt4/view_application.py b/traitsui/qt4/view_application.py index ce7a833b0..05af457ff 100644 --- a/traitsui/qt4/view_application.py +++ b/traitsui/qt4/view_application.py @@ -42,8 +42,7 @@ def on_ui_destroyed(object, name, old, destroyed): - """ Remove the UI object from KEEP_ALIVE_UIS. - """ + """Remove the UI object from KEEP_ALIVE_UIS.""" assert name == "destroyed" if destroyed: assert object in KEEP_ALIVE_UIS @@ -58,7 +57,7 @@ def on_ui_destroyed(object, name, old, destroyed): def view_application(context, view, kind, handler, id, scrollable, args): - """ Creates a stand-alone PyQt application to display a specified traits UI + """Creates a stand-alone PyQt application to display a specified traits UI View. Parameters @@ -112,12 +111,10 @@ def view_application(context, view, kind, handler, id, scrollable, args): class ViewApplication(object): - """ Modal window that contains a stand-alone application. - """ + """Modal window that contains a stand-alone application.""" def __init__(self, context, view, kind, handler, id, scrollable, args): - """ Initializes the object. - """ + """Initializes the object.""" self.context = context self.view = view self.kind = kind diff --git a/traitsui/table_column.py b/traitsui/table_column.py index d25caf4da..85c6aacee 100644 --- a/traitsui/table_column.py +++ b/traitsui/table_column.py @@ -51,8 +51,7 @@ class TableColumn(HasPrivateTraits): - """ Represents a column in a table editor. - """ + """Represents a column in a table editor.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -153,133 +152,119 @@ class TableColumn(HasPrivateTraits): # ------------------------------------------------------------------------- def get_object(self, object): - """ Returns the actual object being edited. - """ + """Returns the actual object being edited.""" return object def get_label(self): - """ Gets the label of the column. - """ + """Gets the label of the column.""" return self.label def get_width(self): - """ Returns the width of the column. - """ + """Returns the width of the column.""" return self.width def get_edit_width(self, object): - """ Returns the edit width of the column. - """ + """Returns the edit width of the column.""" return self.edit_width def get_edit_height(self, object): - """ Returns the height of the column cell's row while it is being - edited. + """Returns the height of the column cell's row while it is being + edited. """ return self.edit_height def get_type(self, object): - """ Gets the type of data for the column for a specified object. - """ + """Gets the type of data for the column for a specified object.""" return self.type def get_text_color(self, object): - """ Returns the text color for the column for a specified object. - """ + """Returns the text color for the column for a specified object.""" return self.text_color_ def get_text_font(self, object): - """ Returns the text font for the column for a specified object. - """ + """Returns the text font for the column for a specified object.""" return self.text_font def get_cell_color(self, object): - """ Returns the cell background color for the column for a specified - object. + """Returns the cell background color for the column for a specified + object. """ if self.is_editable(object): return self.cell_color_ return self.read_only_cell_color_ def get_graph_color(self, object): - """ Returns the cell background graph color for the column for a - specified object. + """Returns the cell background graph color for the column for a + specified object. """ return self.graph_color_ def get_horizontal_alignment(self, object): - """ Returns the horizontal alignment for the column for a specified - object. + """Returns the horizontal alignment for the column for a specified + object. """ return self.horizontal_alignment def get_vertical_alignment(self, object): - """ Returns the vertical alignment for the column for a specified - object. + """Returns the vertical alignment for the column for a specified + object. """ return self.vertical_alignment def get_image(self, object): - """ Returns the image to display for the column for a specified object. - """ + """Returns the image to display for the column for a specified object.""" return self.image def get_renderer(self, object): - """ Returns the renderer for the column of a specified object. - """ + """Returns the renderer for the column of a specified object.""" return self.renderer def is_editable(self, object): - """ Returns whether the column is editable for a specified object. - """ + """Returns whether the column is editable for a specified object.""" return self.editable def is_auto_editable(self, object): - """ Returns whether the column is automatically edited/viewed for a - specified object. + """Returns whether the column is automatically edited/viewed for a + specified object. """ return self.auto_editable def is_droppable(self, object, value): - """ Returns whether a specified value is valid for dropping on the - column for a specified object. + """Returns whether a specified value is valid for dropping on the + column for a specified object. """ return self.droppable def get_menu(self, object): - """ Returns the context menu to display when the user right-clicks on - the column for a specified object. + """Returns the context menu to display when the user right-clicks on + the column for a specified object. """ return self.menu def get_tooltip(self, object): - """ Returns the tooltip to display when the user mouses over the column - for a specified object. + """Returns the tooltip to display when the user mouses over the column + for a specified object. """ return self.tooltip def get_view(self, object): - """ Returns the view to display when clicking a non-editable cell. - """ + """Returns the view to display when clicking a non-editable cell.""" return self.view def get_maximum(self, object): - """ Returns the maximum value a numeric column can have. - """ + """Returns the maximum value a numeric column can have.""" return self.maximum def on_click(self, object): - """ Called when the user clicks on the column. - """ + """Called when the user clicks on the column.""" pass def on_dclick(self, object): - """ Called when the user clicks on the column. - """ + """Called when the user clicks on the column.""" pass def cmp(self, object1, object2): - """ Returns the result of comparing the column of two different objects. + """Returns the result of comparing the column of two different objects. This is deprecated. """ @@ -288,14 +273,12 @@ def cmp(self, object1, object2): ) def __str__(self): - """ Returns the string representation of the table column. - """ + """Returns the string representation of the table column.""" return self.get_label() class ObjectColumn(TableColumn): - """ A column for editing objects. - """ + """A column for editing objects.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -349,8 +332,7 @@ class ObjectColumn(TableColumn): ) def _get_label(self): - """ Gets the label of the column. - """ + """Gets the label of the column.""" if self._label is not None: return self._label return user_name_for(self.name) @@ -361,8 +343,7 @@ def _set_label(self, label): self.trait_property_changed("label", old, label) def get_raw_value(self, object): - """ Gets the unformatted value of the column for a specified object. - """ + """Gets the unformatted value of the column for a specified object.""" try: return xgetattr(self.get_object(object), self.name) except Exception as e: @@ -372,8 +353,7 @@ def get_raw_value(self, object): return None def get_value(self, object): - """ Gets the formatted value of the column for a specified object. - """ + """Gets the formatted value of the column for a specified object.""" try: if self.format_func is not None: return self.format_func(self.get_raw_value(object)) @@ -387,19 +367,16 @@ def get_value(self, object): return "Format!" def get_drag_value(self, object): - """Returns the drag value for the column. - """ + """Returns the drag value for the column.""" return self.get_raw_value(object) def set_value(self, object, value): - """ Sets the value of the column for a specified object. - """ + """Sets the value of the column for a specified object.""" target, name = self.target_name(object) setattr(target, name, value) def get_editor(self, object): - """ Gets the editor for the column of a specified object. - """ + """Gets the editor for the column of a specified object.""" if self.editor is not None: return self.editor @@ -408,18 +385,16 @@ def get_editor(self, object): return target.base_trait(name).get_editor() def get_style(self, object): - """ Gets the editor style for the column of a specified object. - """ + """Gets the editor style for the column of a specified object.""" return self.style def key(self, object): - """ Returns the value to use for sorting. - """ + """Returns the value to use for sorting.""" return self.get_raw_value(object) def is_droppable(self, object, value): - """ Returns whether a specified value is valid for dropping on the - column for a specified object. + """Returns whether a specified value is valid for dropping on the + column for a specified object. """ if self.droppable: try: @@ -432,8 +407,7 @@ def is_droppable(self, object, value): return False def target_name(self, object): - """ Returns the target object and name for the column. - """ + """Returns the target object and name for the column.""" object = self.get_object(object) name = self.name col = name.rfind(".") @@ -444,8 +418,7 @@ def target_name(self, object): class ExpressionColumn(ObjectColumn): - """ A column for displaying computed values. - """ + """A column for displaying computed values.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -462,8 +435,7 @@ class ExpressionColumn(ObjectColumn): globals = Dict() def get_raw_value(self, object): - """ Gets the unformatted value of the column for a specified object. - """ + """Gets the unformatted value of the column for a specified object.""" try: return eval(self.expression_, self.globals, {"object": object}) except Exception: @@ -475,8 +447,7 @@ def get_raw_value(self, object): class NumericColumn(ObjectColumn): - """ A column for editing Numeric arrays. - """ + """A column for editing Numeric arrays.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -502,8 +473,7 @@ class NumericColumn(ObjectColumn): horizontal_alignment = "center" def _get_label(self): - """ Gets the label of the column. - """ + """Gets the label of the column.""" if self._label is not None: return self._label return self.name @@ -514,27 +484,24 @@ def _set_label(self, label): self.trait_property_changed("label", old, label) def get_type(self, object): - """ Gets the type of data for the column for a specified object row. - """ + """Gets the type of data for the column for a specified object row.""" return self.type def get_text_color(self, object): - """ Returns the text color for the column for a specified object row. - """ + """Returns the text color for the column for a specified object row.""" if self._is_selected(object): return self.selected_text_color_ return self.text_color_ def get_text_font(self, object): - """ Returns the text font for the column for a specified object row. - """ + """Returns the text font for the column for a specified object row.""" if self._is_selected(object): return self.selected_text_font return self.text_font def get_cell_color(self, object): - """ Returns the cell background color for the column for a specified - object row. + """Returns the cell background color for the column for a specified + object row. """ if self.is_editable(object): if self._is_selected(object): @@ -543,37 +510,35 @@ def get_cell_color(self, object): return self.read_only_cell_color_ def get_horizontal_alignment(self, object): - """ Returns the horizontal alignment for the column for a specified - object row. + """Returns the horizontal alignment for the column for a specified + object row. """ return self.horizontal_alignment def get_vertical_alignment(self, object): - """ Returns the vertical alignment for the column for a specified - object row. + """Returns the vertical alignment for the column for a specified + object row. """ return self.vertical_alignment def is_editable(self, object): - """ Returns whether the column is editable for a specified object row. - """ + """Returns whether the column is editable for a specified object row.""" return self.editable def is_droppable(self, object, row, value): - """ Returns whether a specified value is valid for dropping on the - column for a specified object row. + """Returns whether a specified value is valid for dropping on the + column for a specified object row. """ return self.droppable def get_menu(self, object, row): - """ Returns the context menu to display when the user right-clicks on - the column for a specified object row. + """Returns the context menu to display when the user right-clicks on + the column for a specified object row. """ return self.menu def get_value(self, object): - """ Gets the value of the column for a specified object row. - """ + """Gets the value of the column for a specified object row.""" try: value = getattr(object, self.name) try: @@ -584,24 +549,20 @@ def get_value(self, object): return "Undefined!" def set_value(self, object, row, value): - """ Sets the value of the column for a specified object row. - """ + """Sets the value of the column for a specified object row.""" column = self.get_data_column(object) column[row] = type(column[row])(value) def get_editor(self, object): - """ Gets the editor for the column of a specified object row. - """ + """Gets the editor for the column of a specified object row.""" return super().get_editor(object) def get_data_column(self, object): - """ Gets the entire contents of the specified object column. - """ + """Gets the entire contents of the specified object column.""" return getattr(object, self.name) def _is_selected(self, object): - """ Returns whether a specified object row is selected. - """ + """Returns whether a specified object row is selected.""" if ( hasattr(object, "model_selection") and object.model_selection is not None @@ -611,8 +572,7 @@ def _is_selected(self, object): class ListColumn(TableColumn): - """ A column for editing lists. - """ + """A column for editing lists.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -639,8 +599,7 @@ class ListColumn(TableColumn): ) def _get_label(self): - """ Gets the label of the column. - """ + """Gets the label of the column.""" if self._label is not None: return self._label return "Column %d" % (self.index + 1) @@ -651,21 +610,17 @@ def _set_label(self, label): self.trait_property_changed("label", old, label) def get_value(self, object): - """ Gets the value of the column for a specified object. - """ + """Gets the value of the column for a specified object.""" return str(object[self.index]) def set_value(self, object, value): - """ Sets the value of the column for a specified object. - """ + """Sets the value of the column for a specified object.""" object[self.index] = value def get_editor(self, object): - """ Gets the editor for the column of a specified object. - """ + """Gets the editor for the column of a specified object.""" return None def key(self, object): - """ Returns the value to use for sorting. - """ + """Returns the value to use for sorting.""" return object[self.index] diff --git a/traitsui/table_filter.py b/traitsui/table_filter.py index 1f8658980..8a3ce1ebd 100644 --- a/traitsui/table_filter.py +++ b/traitsui/table_filter.py @@ -12,7 +12,6 @@ """ - from traits.api import ( Any, Bool, @@ -56,8 +55,7 @@ class TableFilter(HasPrivateTraits): - """ Filter for items displayed in a table. - """ + """Filter for items displayed in a table.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -131,24 +129,23 @@ class TableFilter(HasPrivateTraits): filter_view = Group() def filter(self, object): - """ Returns whether a specified object meets the filter or search + """Returns whether a specified object meets the filter or search criteria. """ return self.allowed(object) def description(self): - """ Returns a user-readable description of what kind of object + """Returns a user-readable description of what kind of object satisfies the filter. """ return self.desc def edit(self, object): - """ Edits the contents of the filter. - """ + """Edits the contents of the filter.""" return self.edit_traits(view=self.edit_view(object), kind="livemodal") def edit_view(self, object): - """ Return a view to use for editing the filter. + """Return a view to use for editing the filter. The ''object'' parameter is a sample object for the table that the filter will be applied to. It is supplied in case the filter needs to @@ -176,8 +173,7 @@ def _anytrait_changed(self, name, old, new): class EvalTableFilter(TableFilter): - """ A table filter based on evaluating an expression. - """ + """A table filter based on evaluating an expression.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -196,26 +192,27 @@ class EvalTableFilter(TableFilter): filter_view = Group("expression") def filter(self, object): - """ Returns whether a specified object meets the filter or search + """Returns whether a specified object meets the filter or search criteria. """ if self._traits is None: self._traits = object.trait_names() try: - return eval(self.expression_, globals(), object.trait_get(*self._traits)) + return eval( + self.expression_, globals(), object.trait_get(*self._traits) + ) except: return False def description(self): - """ Returns a user readable description of what kind of object - satisfies the filter. + """Returns a user readable description of what kind of object + satisfies the filter. """ return self.expression class GenericTableFilterRule(HasPrivateTraits): - """ A general rule used by a table filter. - """ + """A general rule used by a table filter.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -262,8 +259,7 @@ def __init__(self, **traits): self.enabled = False def _name_changed(self, name): - """ Handles a change to the value of the **name** trait. - """ + """Handles a change to the value of the **name** trait.""" filter = self.filter if (filter is not None) and (filter._object is not None): self.value = filter._name_to_value.get(name) @@ -280,7 +276,7 @@ def _anytrait_changed(self, name, old, new): self.enabled = True def clone_traits(self, traits=None, memo=None, copy=None, **metadata): - """ Clones a new object from this one, optionally copying only a + """Clones a new object from this one, optionally copying only a specified set of traits.""" return ( super() @@ -289,13 +285,11 @@ def clone_traits(self, traits=None, memo=None, copy=None, **metadata): ) def description(self): - """ Returns a description of the filter. - """ + """Returns a description of the filter.""" return "%s %s %s" % (self.name, self.operation, self.value) def is_true(self, object): - """ Returns whether the rule is true for a specified object. - """ + """Returns whether the rule is true for a specified object.""" try: value1 = getattr(object, self.name) type1 = type(value1) @@ -339,12 +333,10 @@ def ends_with(self, value1, value2): class GenericTableFilterRuleEnabledColumn(ObjectColumn): - """ Table column that indicates whether a filter rule is enabled. - """ + """Table column that indicates whether a filter rule is enabled.""" def get_value(self, object): - """ Returns the traits editor of the column for a specified object. - """ + """Returns the traits editor of the column for a specified object.""" if hasattr(object, "enabled") and object.enabled: return "\N{HEAVY CHECK MARK}" else: @@ -352,35 +344,30 @@ def get_value(self, object): class GenericTableFilterRuleAndOrColumn(ObjectColumn): - """ Table column that displays whether a filter rule is conjoining ('and') - or disjoining ('or'). + """Table column that displays whether a filter rule is conjoining ('and') + or disjoining ('or'). """ def get_value(self, object): - """ Returns the traits editor of the column for a specified object. - """ + """Returns the traits editor of the column for a specified object.""" if object.and_or == "or": return "or" return "" class GenericTableFilterRuleNameColumn(ObjectColumn): - """ Table column for the name of an object trait. - """ + """Table column for the name of an object trait.""" def get_editor(self, object): - """ Returns the traits editor of the column for a specified object. - """ + """Returns the traits editor of the column for a specified object.""" return object.name_editor class GenericTableFilterRuleValueColumn(ObjectColumn): - """ Table column for the value of an object trait. - """ + """Table column for the value of an object trait.""" def get_editor(self, object): - """ Returns the traits editor of the column for a specified object. - """ + """Returns the traits editor of the column for a specified object.""" return object.value_editor @@ -398,8 +385,7 @@ def get_editor(self, object): class RuleTableFilter(TableFilter): - """ A table filter based on rules. - """ + """A table filter based on rules.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -439,7 +425,7 @@ class RuleTableFilter(TableFilter): ) def filter(self, object): - """ Returns whether a specified object meets the filter or search + """Returns whether a specified object meets the filter or search criteria. """ is_first = is_true = True @@ -454,8 +440,8 @@ def filter(self, object): return is_true def description(self): - """ Returns a user-readable description of the kind of object that - satisfies the filter. + """Returns a user-readable description of the kind of object that + satisfies the filter. """ ors = [] ands = [] @@ -479,7 +465,7 @@ def description(self): return super().description() def edit_view(self, object): - """ Return a view to use for editing the filter. + """Return a view to use for editing the filter. The ''object'' parameter is a sample object for the table that the filter will be applied to. It is supplied in case the filter needs to @@ -514,8 +500,7 @@ def edit_view(self, object): ) def _get_table_editor(self, names): - """ Returns a table editor to use for editing the filter. - """ + """Returns a table editor to use for editing the filter.""" from traitsui.api import TableEditor from traitsui.editors.api import EnumEditor @@ -535,7 +520,7 @@ def _get_table_editor(self, names): ) def __getstate__(self): - """ Returns the state to be pickled. + """Returns the state to be pickled. This definition overrides **object**. """ @@ -546,8 +531,7 @@ def __getstate__(self): return dict def _rules_changed(self, rules): - """ Handles a change to the **rules** trait. - """ + """Handles a change to the **rules** trait.""" for rule in rules: rule.filter = self @@ -566,8 +550,7 @@ def _rules_changed(self, rules): class MenuTableFilter(RuleTableFilter): - """ A table filter based on a menu of rules. - """ + """A table filter based on a menu of rules.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -580,7 +563,7 @@ class MenuTableFilter(RuleTableFilter): view_id = Str("traitsui.table_filter.MenuTableFilter") def filter(self, object): - """ Returns whether a specified object meets the filter or search + """Returns whether a specified object meets the filter or search criteria. """ for rule in self.rules: @@ -589,8 +572,8 @@ def filter(self, object): return True def description(self): - """ Returns a user8readable description of what kind of object - satisfies the filter. + """Returns a user8readable description of what kind of object + satisfies the filter. """ result = " and ".join( [rule.description() for rule in self.rules if rule.enabled] @@ -600,8 +583,7 @@ def description(self): return "All items" def _get_table_editor(self, names): - """ Returns a table editor to use for editing the filter. - """ + """Returns a table editor to use for editing the filter.""" from .api import TableEditor from .editors.api import EnumEditor diff --git a/traitsui/tabular_adapter.py b/traitsui/tabular_adapter.py index cb7d5d148..09df9c97b 100644 --- a/traitsui/tabular_adapter.py +++ b/traitsui/tabular_adapter.py @@ -12,9 +12,6 @@ """ - - - from traits.api import ( Any, Bool, @@ -99,8 +96,8 @@ class AnITabularAdapter(HasPrivateTraits): class TabularAdapter(HasPrivateTraits): - """ The base class for adapting list items to values that can be edited - by a TabularEditor. + """The base class for adapting list items to values that can be edited + by a TabularEditor. """ # -- Public Trait Definitions --------------------------------------------- @@ -246,14 +243,13 @@ class TabularAdapter(HasPrivateTraits): # ------------------------------------------------------------------------- def cleanup(self): - """ Clean up the adapter to remove references to objects. - """ + """Clean up the adapter to remove references to objects.""" self.trait_setq(object=None, item=None, value=None) # -- Adapter methods that are sensitive to item type ---------------------- def get_alignment(self, object, trait, column): - """ Returns the alignment style to use for a specified column. + """Returns the alignment style to use for a specified column. The possible values that can be returned are: ``'left'``, ``'center'`` or ``'right'``. All table items share the same alignment for a @@ -262,7 +258,7 @@ def get_alignment(self, object, trait, column): return self._result_for("get_alignment", object, trait, 0, column) def get_width(self, object, trait, column): - """ Returns the width to use for a specified column. + """Returns the width to use for a specified column. If the value is <= 0, the column will have a *default* width, which is the same as specifying a width of 0.1. @@ -291,7 +287,7 @@ def get_width(self, object, trait, column): return self._result_for("get_width", object, trait, 0, column) def get_can_edit(self, object, trait, row): - """ Returns whether the user can edit a specified row. + """Returns whether the user can edit a specified row. A ``True`` result indicates that the value can be edited, while a ``False`` result indicates that it cannot. @@ -299,7 +295,7 @@ def get_can_edit(self, object, trait, row): return self._result_for("get_can_edit", object, trait, row, 0) def get_drag(self, object, trait, row): - """ Returns the value to be *dragged* for a specified row. + """Returns the value to be *dragged* for a specified row. A result of ``None`` means that the item cannot be dragged. Note that the value returned does not have to be the actual row item. It can be @@ -314,7 +310,7 @@ def get_drag(self, object, trait, row): return self._result_for("get_drag", object, trait, row, 0) def get_can_drop(self, object, trait, row, value): - """ Returns whether the specified ``value`` can be dropped on the specified row. + """Returns whether the specified ``value`` can be dropped on the specified row. A value of ``True`` means the ``value`` can be dropped; and a value of ``False`` indicates that it cannot be dropped. @@ -328,7 +324,7 @@ def get_can_drop(self, object, trait, row, value): return self._result_for("get_can_drop", object, trait, row, 0, value) def get_dropped(self, object, trait, row, value): - """ Returns how to handle a specified ``value`` being dropped on a specified row. + """Returns how to handle a specified ``value`` being dropped on a specified row. The possible return values are: @@ -342,7 +338,7 @@ def get_dropped(self, object, trait, row, value): return self._result_for("get_dropped", object, trait, row, 0, value) def get_font(self, object, trait, row, column=0): - """ Returns the font to use for displaying a specified row or cell. + """Returns the font to use for displaying a specified row or cell. A result of ``None`` means use the default font; otherwise a toolkit font object should be returned. Note that all columns for the specified @@ -351,7 +347,7 @@ def get_font(self, object, trait, row, column=0): return self._result_for("get_font", object, trait, row, column) def get_text_color(self, object, trait, row, column=0): - """ Returns the text color to use for a specified row or cell. + """Returns the text color to use for a specified row or cell. A result of ``None`` means use the default text color; otherwise a toolkit-compatible color should be returned. Note that all columns for @@ -360,7 +356,7 @@ def get_text_color(self, object, trait, row, column=0): return self._result_for("get_text_color", object, trait, row, column) def get_bg_color(self, object, trait, row, column=0): - """ Returns the background color to use for a specified row or cell. + """Returns the background color to use for a specified row or cell. A result of ``None`` means use the default background color; otherwise a toolkit-compatible color should be returned. Note that all columns @@ -370,7 +366,7 @@ def get_bg_color(self, object, trait, row, column=0): return self._result_for("get_bg_color", object, trait, row, column) def get_image(self, object, trait, row, column): - """ Returns the image to display for a specified cell. + """Returns the image to display for a specified cell. A result of ``None`` means no image will be displayed in the specified table cell. Otherwise the result should either be the name of the @@ -386,7 +382,7 @@ def get_image(self, object, trait, row, column): return self._result_for("get_image", object, trait, row, column) def get_format(self, object, trait, row, column): - """ Returns the Python formatting string to apply to the specified cell. + """Returns the Python formatting string to apply to the specified cell. The resulting of formatting with this string will be used as the text to display it in the table. @@ -397,7 +393,7 @@ def get_format(self, object, trait, row, column): return self._result_for("get_format", object, trait, row, column) def get_text(self, object, trait, row, column): - """ Returns a string containing the text to display for a specified cell. + """Returns a string containing the text to display for a specified cell. If the underlying data representation for a specified item is not a string, then it is your responsibility to convert it to one before @@ -406,12 +402,11 @@ def get_text(self, object, trait, row, column): return self._result_for("get_text", object, trait, row, column) def get_content(self, object, trait, row, column): - """ Returns the content to display for a specified cell. - """ + """Returns the content to display for a specified cell.""" return self._result_for("get_content", object, trait, row, column) def set_text(self, object, trait, row, column, text): - """ Sets the value for the specified cell. + """Sets the value for the specified cell. This method is called when the user completes an editing operation on a table cell. @@ -424,7 +419,7 @@ def set_text(self, object, trait, row, column, text): self._result_for("set_text", object, trait, row, column, text) def get_tooltip(self, object, trait, row, column): - """ Returns a string containing the tooltip to display for a specified cell. + """Returns a string containing the tooltip to display for a specified cell. You should return the empty string if you do not wish to display a tooltip. @@ -432,19 +427,17 @@ def get_tooltip(self, object, trait, row, column): return self._result_for("get_tooltip", object, trait, row, column) def get_menu(self, object, trait, row, column): - """ Returns the context menu for a specified cell. - """ + """Returns the context menu for a specified cell.""" return self._result_for("get_menu", object, trait, row, column) def get_column_menu(self, object, trait, row, column): - """ Returns the context menu for a specified column. - """ + """Returns the context menu for a specified column.""" return self._result_for("get_column_menu", object, trait, row, column) # -- Adapter methods that are not sensitive to item type ------------------ def get_item(self, object, trait, row): - """ Returns the specified row item. + """Returns the specified row item. The value returned should be the value that exists (or *logically* exists) at the specified ``row`` in your data. If your data is not @@ -467,7 +460,7 @@ def get_item(self, object, trait, row): return None def len(self, object, trait): - """ Returns the number of row items in the specified ``object.trait``. + """Returns the number of row items in the specified ``object.trait``. The result should be an integer greater than or equal to 0. @@ -483,7 +476,7 @@ def len(self, object, trait): return len(getattr(object, trait)) def get_default_value(self, object, trait): - """ Returns a new default value for the specified ``object.trait`` list. + """Returns a new default value for the specified ``object.trait`` list. This method is called when *insert* or *append* operations are allowed and the user requests that a new item be added to the table. The result @@ -496,7 +489,7 @@ def get_default_value(self, object, trait): return self.default_value def delete(self, object, trait, row): - """ Deletes the specified row item. + """Deletes the specified row item. This method is only called if the *delete* operation is specified in the :py:class:`~traitsui.editors.tabular_editor.TabularEditor` @@ -513,7 +506,7 @@ def delete(self, object, trait, row): del getattr(object, trait)[row] def insert(self, object, trait, row, value): - """ Inserts ``value`` at the specified ``object.trait[row]`` index. + """Inserts ``value`` at the specified ``object.trait[row]`` index. The specified ``value`` can be: @@ -533,8 +526,7 @@ def insert(self, object, trait, row, value): getattr(object, trait)[row:row] = [value] def get_column(self, object, trait, index): - """ Returns the column id corresponding to a specified column index. - """ + """Returns the column id corresponding to a specified column index.""" self.object, self.name = object, trait return self.column_map[index] @@ -666,8 +658,8 @@ def _get_adapter_column_map(self): # -- Private Methods ------------------------------------------------------ def _result_for(self, name, object, trait, row, column, value=None): - """ Returns/Sets the value of the specified *name* attribute for the - specified *object.trait[row].column* item. + """Returns/Sets the value of the specified *name* attribute for the + specified *object.trait[row].column* item. """ self.object = object self.name = trait @@ -739,8 +731,8 @@ def _result_for(self, name, object, trait, row, column, value=None): return handler() def _get_handler_for(self, name, prefix): - """ Returns the handler for a specified trait name (or None if not - found). + """Returns the handler for a specified trait name (or None if not + found). """ if self.trait(name) is not None: if prefix == "get_": @@ -752,8 +744,8 @@ def _get_handler_for(self, name, prefix): @observe("columns,adapters.items.+update") def _flush_cache(self, event): - """ Flushes the cache when the columns or any trait on any adapter - changes. + """Flushes the cache when the columns or any trait on any adapter + changes. """ self.cache = {} self.cache_flushed = True diff --git a/traitsui/testing/_exception_handling.py b/traitsui/testing/_exception_handling.py index ff66d3776..5ba1340d8 100644 --- a/traitsui/testing/_exception_handling.py +++ b/traitsui/testing/_exception_handling.py @@ -22,20 +22,20 @@ def _serialize_exception(exc_type, value, tb): - """ Serialize exception and traceback for reporting. + """Serialize exception and traceback for reporting. This is such that the stack frame is not prevented from being garbage collected. """ return ( str(exc_type), str(value), - str("".join(traceback.format_exception(exc_type, value, tb))) + str("".join(traceback.format_exception(exc_type, value, tb))), ) @contextmanager def reraise_exceptions(logger=_TRAITSUI_LOGGER): - """ Context manager to capture all exceptions occurred in the context and + """Context manager to capture all exceptions occurred in the context and then reraise a RuntimeError if there are any exceptions captured. Depending on the GUI toolkit backend, unexpected exceptions occurred in the @@ -55,8 +55,7 @@ def excepthook(type, value, tb): serialized = _serialize_exception(type, value, tb) serialized_exceptions.append(serialized) logger.error( - "Unexpected error captured in sys excepthook. \n%s", - serialized[-1] + "Unexpected error captured in sys excepthook. \n%s", serialized[-1] ) sys.excepthook = excepthook diff --git a/traitsui/testing/_gui.py b/traitsui/testing/_gui.py index c2044b871..9224a31f8 100644 --- a/traitsui/testing/_gui.py +++ b/traitsui/testing/_gui.py @@ -15,7 +15,7 @@ def process_cascade_events(): - """ Process all posted events, and attempt to process new events posted by + """Process all posted events, and attempt to process new events posted by the processed events. Cautions: @@ -32,9 +32,11 @@ def process_cascade_events(): """ if ETSConfig.toolkit.startswith("qt"): from pyface.qt import QtCore + event_loop = QtCore.QEventLoop() while event_loop.processEvents(QtCore.QEventLoop.AllEvents): pass else: from pyface.api import GUI + GUI.process_events() diff --git a/traitsui/testing/api.py b/traitsui/testing/api.py index 0ff24d81b..298c931bf 100644 --- a/traitsui/testing/api.py +++ b/traitsui/testing/api.py @@ -61,11 +61,7 @@ from .tester.ui_tester import UITester # Interactions (for changing GUI states) -from .tester.command import ( - MouseClick, - KeyClick, - KeySequence -) +from .tester.command import MouseClick, KeyClick, KeySequence # Interactions (for getting GUI states) from .tester.query import ( @@ -73,17 +69,11 @@ IsChecked, IsEnabled, IsVisible, - SelectedText + SelectedText, ) # Locations (for locating GUI elements) -from .tester.locator import ( - Index, - TargetById, - TargetByName, - Textbox, - Slider -) +from .tester.locator import Index, TargetById, TargetByName, Textbox, Slider # Advanced usage from .tester.target_registry import TargetRegistry @@ -93,5 +83,5 @@ Disabled, InteractionNotSupported, LocationNotSupported, - TesterError + TesterError, ) diff --git a/traitsui/testing/tester/_abstract_target_registry.py b/traitsui/testing/tester/_abstract_target_registry.py index 921fa5916..002ce4776 100644 --- a/traitsui/testing/tester/_abstract_target_registry.py +++ b/traitsui/testing/tester/_abstract_target_registry.py @@ -18,13 +18,13 @@ class AbstractTargetRegistry(abc.ABC): - """ Abstract base class which defines the registry interface expected + """Abstract base class which defines the registry interface expected by :class:`~traitsui.testing.tester.ui_wrapper.UIWrapper`. """ @abc.abstractmethod def _get_handler(self, target, interaction): - """ Return a callable for handling an interaction for a given target. + """Return a callable for handling an interaction for a given target. This is a protected method expected to be implemented by a subclass. @@ -49,7 +49,7 @@ def _get_handler(self, target, interaction): @abc.abstractmethod def _get_interactions(self, target): - """ Returns all the interactions supported for the given target. + """Returns all the interactions supported for the given target. This is a protected method expected to be implemented by a subclass. @@ -66,7 +66,7 @@ def _get_interactions(self, target): @abc.abstractmethod def _get_interaction_doc(self, target, interaction_class): - """ Return the documentation for the given target and interaction type. + """Return the documentation for the given target and interaction type. This is a protected method expected to be implemented by a subclass. @@ -90,7 +90,7 @@ def _get_interaction_doc(self, target, interaction_class): @abc.abstractmethod def _get_solver(self, target, location): - """ Return a callable registered for resolving a location for the + """Return a callable registered for resolving a location for the given target and location. This is a protected method expected to be implemented by a subclass. @@ -110,7 +110,7 @@ def _get_solver(self, target, location): @abc.abstractmethod def _get_locations(self, target): - """ Returns all the location types supported for the given target. + """Returns all the location types supported for the given target. This is a protected method expected to be implemented by a subclass. @@ -127,7 +127,7 @@ def _get_locations(self, target): @abc.abstractmethod def _get_location_doc(self, target, locator_class): - """ Return the documentation for the given target and locator type. + """Return the documentation for the given target and locator type. This is a protected method expected to be implemented by a subclass. diff --git a/traitsui/testing/tester/_dynamic_target_registry.py b/traitsui/testing/tester/_dynamic_target_registry.py index b1cb0e786..7e915fce5 100644 --- a/traitsui/testing/tester/_dynamic_target_registry.py +++ b/traitsui/testing/tester/_dynamic_target_registry.py @@ -23,7 +23,7 @@ class DynamicTargetRegistry(AbstractTargetRegistry): - """ Registry to support testing targets that satisfy a given criterion. + """Registry to support testing targets that satisfy a given criterion. An instance of this registry can be used with ``UITester`` and ``UIWrapper`` such that all given interactions and handlers will be @@ -63,7 +63,7 @@ def __init__(self, *, can_support, interaction_to_handler): self.interaction_to_handler = interaction_to_handler def _get_handler(self, target, interaction): - """ Return a callable for handling an interaction for a given target. + """Return a callable for handling an interaction for a given target. This is an implementation for an abstract method. @@ -94,7 +94,7 @@ def _get_handler(self, target, interaction): return self.interaction_to_handler[interaction.__class__] def _get_interactions(self, target): - """ Returns all the interactions supported for the given target. + """Returns all the interactions supported for the given target. This is an implementation for an abstract method. @@ -113,7 +113,7 @@ def _get_interactions(self, target): return set() def _get_interaction_doc(self, target, interaction_class): - """ Return the documentation for the given target and interaction type. + """Return the documentation for the given target and interaction type. This is an implementation for an abstract method. @@ -143,7 +143,7 @@ def _get_interaction_doc(self, target, interaction_class): return inspect.getdoc(interaction_class) def _get_solver(self, target, location): - """ Return a callable registered for resolving a location for the + """Return a callable registered for resolving a location for the given target and location. This is an implementation for an abstract method. @@ -167,7 +167,7 @@ def _get_solver(self, target, location): ) def _get_locations(self, target): - """ Returns all the location types supported for the given target. + """Returns all the location types supported for the given target. This is an implementation for an abstract method. @@ -184,7 +184,7 @@ def _get_locations(self, target): return set() def _get_location_doc(self, target, locator_class): - """ Return the documentation for the given target and locator type. + """Return the documentation for the given target and locator type. This is an implementation for an abstract method. diff --git a/traitsui/testing/tester/_ui_tester_registry/_common_ui_targets.py b/traitsui/testing/tester/_ui_tester_registry/_common_ui_targets.py index e837c1ea4..12fe270c3 100644 --- a/traitsui/testing/tester/_ui_tester_registry/_common_ui_targets.py +++ b/traitsui/testing/tester/_ui_tester_registry/_common_ui_targets.py @@ -17,7 +17,7 @@ class BaseSourceWithLocation: - """ Wrapper base class to hold locator information together with a source + """Wrapper base class to hold locator information together with a source (typically an editor). This is useful for cases in which the location information is still necessary when performing actions such as a mouse click or key click. @@ -55,7 +55,7 @@ def __init__(self, source, location): @classmethod def register(cls, registry): - """ Class method to register interactions on a + """Class method to register interactions on a _SourceWithLocation for the given registry. It is expected that this class method will be called by subclasses, and thus interactions would be registered to subclasses rather than the base class. @@ -76,5 +76,5 @@ class method will be called by subclasses, and thus interactions would registry.register_interaction( target_class=cls, interaction_class=interaction_class, - handler=handler + handler=handler, ) diff --git a/traitsui/testing/tester/_ui_tester_registry/_compat.py b/traitsui/testing/tester/_ui_tester_registry/_compat.py index 58980f0a2..b584f2c20 100644 --- a/traitsui/testing/tester/_ui_tester_registry/_compat.py +++ b/traitsui/testing/tester/_ui_tester_registry/_compat.py @@ -14,7 +14,7 @@ def check_key_compat(key): - """ Check if the given key is a unicode character within the range of + """Check if the given key is a unicode character within the range of values currently supported for emulating key sequences on both Qt and Wx textboxes. diff --git a/traitsui/testing/tester/_ui_tester_registry/_layout.py b/traitsui/testing/tester/_ui_tester_registry/_layout.py index 28f4d35a9..f22dedf24 100644 --- a/traitsui/testing/tester/_ui_tester_registry/_layout.py +++ b/traitsui/testing/tester/_ui_tester_registry/_layout.py @@ -15,7 +15,7 @@ def column_major_to_row_major(index, n, num_rows, num_cols): - """ Helper function to convert an index of a grid layout so that the + """Helper function to convert an index of a grid layout so that the index counts over the grid in the correct direction. In TraitsUI, grids are typically populated in row major order, however, the elements can be assigned to each entry in the grid so that when @@ -87,8 +87,9 @@ def column_major_to_row_major(index, n, num_rows, num_cols): new_index = index - num_entries_grid1 i2 = new_index % (num_rows - 1) j2 = new_index // (num_rows - 1) - return (num_cols - num_empty_entries_last_row)*(i2+1) + \ - (i2 * num_empty_entries_last_row + j2) + return (num_cols - num_empty_entries_last_row) * (i2 + 1) + ( + i2 * num_empty_entries_last_row + j2 + ) else: i = index % num_rows j = index // num_rows diff --git a/traitsui/testing/tester/_ui_tester_registry/_traitsui_ui.py b/traitsui/testing/tester/_ui_tester_registry/_traitsui_ui.py index 0f623c791..3ff18f452 100644 --- a/traitsui/testing/tester/_ui_tester_registry/_traitsui_ui.py +++ b/traitsui/testing/tester/_ui_tester_registry/_traitsui_ui.py @@ -12,7 +12,7 @@ def _get_editor_by_name(ui, name): - """ Return a single Editor from an instance of traitsui.ui.UI with + """Return a single Editor from an instance of traitsui.ui.UI with a given extended name. Raise if zero or many editors are found. Parameters @@ -36,14 +36,13 @@ def _get_editor_by_name(ui, name): "Found these: {!r}".format(name, all_names) ) if len(editors) > 1: - raise ValueError( - "Found multiple editors with name {!r}.".format(name)) - editor, = editors + raise ValueError("Found multiple editors with name {!r}.".format(name)) + (editor,) = editors return editor def _get_editor_by_id(ui, id): - """ Return single Editor from an instance of traitsui.ui.UI with + """Return single Editor from an instance of traitsui.ui.UI with the given identifier. Parameters @@ -63,13 +62,14 @@ def _get_editor_by_id(ui, id): except AttributeError: raise ValueError( "No editors found with id {!r}. Got these: {!r}".format( - id, ui._names) + id, ui._names ) + ) return editor def register_traitsui_ui_solvers(registry, target_class, traitsui_ui_getter): - """ Function to register solvers for obtaining nested targets inside a + """Function to register solvers for obtaining nested targets inside a traitsui.ui.UI inside a (parent) target. For example, an instance of TreeEditor may contain a nested diff --git a/traitsui/testing/tester/_ui_tester_registry/default_registry.py b/traitsui/testing/tester/_ui_tester_registry/default_registry.py index c21ed6b5d..2a313ffcc 100644 --- a/traitsui/testing/tester/_ui_tester_registry/default_registry.py +++ b/traitsui/testing/tester/_ui_tester_registry/default_registry.py @@ -20,7 +20,7 @@ def get_default_registries(): - """ Creates a default registry for UITester that is toolkit specific. + """Creates a default registry for UITester that is toolkit specific. Returns ------- @@ -30,14 +30,15 @@ def get_default_registries(): """ # side-effect to determine current toolkit from pyface.toolkit import toolkit_object # noqa + if ETSConfig.toolkit == "null": registries = [] else: toolkit = {'wx': 'wx', 'qt4': 'qt4', 'qt': 'qt4'}[ETSConfig.toolkit] this_package, _ = __name__.rsplit(".", 1) module = importlib.import_module( - ".default_registry", - this_package + '.' + toolkit) + ".default_registry", this_package + '.' + toolkit + ) registries = module.get_default_registries() ui_registry = TargetRegistry() diff --git a/traitsui/testing/tester/_ui_tester_registry/qt4/_control_widget_registry.py b/traitsui/testing/tester/_ui_tester_registry/qt4/_control_widget_registry.py index e1b22b742..6b7a04297 100644 --- a/traitsui/testing/tester/_ui_tester_registry/qt4/_control_widget_registry.py +++ b/traitsui/testing/tester/_ui_tester_registry/qt4/_control_widget_registry.py @@ -20,7 +20,7 @@ def _handle_is_enabled(wrapper, interaction): - """ Return true if the target's control is enabled. + """Return true if the target's control is enabled. Parameters ---------- @@ -33,7 +33,7 @@ def _handle_is_enabled(wrapper, interaction): def _handle_is_visible(wrapper, interaction): - """ Return true if the target's control is visible. + """Return true if the target's control is visible. Parameters ---------- @@ -46,7 +46,7 @@ def _handle_is_visible(wrapper, interaction): def _is_target_control_a_qt_widget(target): - """ Return true if the target is accepted by the registry. + """Return true if the target is accepted by the registry. Parameters ---------- @@ -57,14 +57,13 @@ def _is_target_control_a_qt_widget(target): ------- is_accepted : bool """ - return ( - hasattr(target, "control") - and isinstance(target.control, QtGui.QWidget) + return hasattr(target, "control") and isinstance( + target.control, QtGui.QWidget ) def get_widget_registry(): - """ Return a registry to support any target with an attribute 'control' + """Return a registry to support any target with an attribute 'control' that is an instance of QWidget. Returns @@ -77,5 +76,5 @@ def get_widget_registry(): interaction_to_handler={ IsEnabled: _handle_is_enabled, IsVisible: _handle_is_visible, - } + }, ) diff --git a/traitsui/testing/tester/_ui_tester_registry/qt4/_interaction_helpers.py b/traitsui/testing/tester/_ui_tester_registry/qt4/_interaction_helpers.py index c87eed15a..c034b8d14 100644 --- a/traitsui/testing/tester/_ui_tester_registry/qt4/_interaction_helpers.py +++ b/traitsui/testing/tester/_ui_tester_registry/qt4/_interaction_helpers.py @@ -13,14 +13,14 @@ from pyface.qt.QtTest import QTest from traitsui.testing.tester._ui_tester_registry._compat import ( - check_key_compat + check_key_compat, ) from traitsui.testing.tester.exceptions import Disabled from traitsui.qt4.key_event_to_name import key_map as _KEY_MAP def key_click(widget, key, delay): - """ Performs a key click of the given key on the given widget after + """Performs a key click of the given key on the given widget after a delay. Parameters @@ -40,7 +40,8 @@ def key_click(widget, key, delay): raise ValueError( "Unknown key {!r}. Expected one of these: {!r}".format( key, sorted(mapping) - )) + ) + ) QTest.keyClick( widget, mapping[key], @@ -50,7 +51,7 @@ def key_click(widget, key, delay): def check_q_model_index_valid(index): - """ Checks if a given QModelIndex is valid. + """Checks if a given QModelIndex is valid. Parameters ---------- @@ -66,7 +67,8 @@ def check_q_model_index_valid(index): column = index.column() raise LookupError( "Unabled to locate item with row {!r} and column {!r}.".format( - row, column, + row, + column, ) ) @@ -75,7 +77,7 @@ def check_q_model_index_valid(index): def displayed_text_qobject(widget): - ''' Helper function to define handlers for various Qwidgets to handle + '''Helper function to define handlers for various Qwidgets to handle query.DisplayedText interactions. Parameters @@ -99,7 +101,7 @@ def displayed_text_qobject(widget): def mouse_click_qwidget(control, delay): - """ Performs a mouce click on a Qt widget. + """Performs a mouce click on a Qt widget. Parameters ---------- @@ -125,7 +127,7 @@ def mouse_click_qwidget(control, delay): def mouse_click_tab_index(tab_widget, index, delay): - """ Performs a mouse click on a tab at an index in a QtGui.QTabWidget. + """Performs a mouse click on a tab at an index in a QtGui.QTabWidget. Parameters ---------- @@ -155,7 +157,7 @@ def mouse_click_tab_index(tab_widget, index, delay): def mouse_click_qlayout(layout, index, delay): - """ Performs a mouse click on a widget at an index in a QLayout. + """Performs a mouse click on a widget at an index in a QLayout. Parameters ---------- @@ -176,7 +178,7 @@ def mouse_click_qlayout(layout, index, delay): def mouse_click_item_view(model, view, index, delay): - """ Perform mouse click on the given QAbstractItemModel (model) and + """Perform mouse click on the given QAbstractItemModel (model) and QAbstractItemView (view) with the given row and column. Parameters @@ -206,7 +208,7 @@ def mouse_click_item_view(model, view, index, delay): def mouse_click_combobox(combobox, index, delay): - """ Perform a mouse click on a QComboBox at a given index. + """Perform a mouse click on a QComboBox at a given index. Paramters --------- @@ -228,9 +230,7 @@ def mouse_click_combobox(combobox, index, delay): delay=delay, ) # Otherwise the click won't get registered. - key_click( - combobox.view().viewport(), key="Enter", delay=delay - ) + key_click(combobox.view().viewport(), key="Enter", delay=delay) else: warnings.warn( "Attempted to click on a non-existant combobox. Nothing was " @@ -239,7 +239,7 @@ def mouse_click_combobox(combobox, index, delay): def key_sequence_qwidget(control, interaction, delay): - """ Performs simulated typing of a sequence of keys on the given widget + """Performs simulated typing of a sequence of keys on the given widget after a delay. Parameters @@ -264,7 +264,7 @@ def key_sequence_qwidget(control, interaction, delay): def key_sequence_textbox(control, interaction, delay): - """ Performs simulated typing of a sequence of keys on a widget that is + """Performs simulated typing of a sequence of keys on a widget that is a textbox. The keys are restricted to values also supported for testing wx.TextCtrl. @@ -288,7 +288,7 @@ def key_sequence_textbox(control, interaction, delay): def key_click_qwidget(control, interaction, delay): - """ Performs simulated typing of a key on the given widget after a delay. + """Performs simulated typing of a key on the given widget after a delay. Parameters ---------- @@ -311,7 +311,7 @@ def key_click_qwidget(control, interaction, delay): def key_click_qslider(control, interaction, delay): - """ Performs simulated typing of a key on the given slider after a delay. + """Performs simulated typing of a key on the given slider after a delay. Only allowed keys are: "Left", "Right", "Up", "Down", "Page Up", "Page Down" Also, note that up related keys correspond to an increment on the slider, diff --git a/traitsui/testing/tester/_ui_tester_registry/qt4/_registry_helper.py b/traitsui/testing/tester/_ui_tester_registry/qt4/_registry_helper.py index 2a1f10952..6aae24178 100644 --- a/traitsui/testing/tester/_ui_tester_registry/qt4/_registry_helper.py +++ b/traitsui/testing/tester/_ui_tester_registry/qt4/_registry_helper.py @@ -19,12 +19,12 @@ ) from traitsui.testing.tester.query import DisplayedText from traitsui.testing.tester._ui_tester_registry.qt4 import ( - _interaction_helpers + _interaction_helpers, ) def register_editable_textbox_handlers(registry, target_class, widget_getter): - """ Register common interactions for an editable textbox (in Qt) + """Register common interactions for an editable textbox (in Qt) Parameters ---------- @@ -38,20 +38,36 @@ def register_editable_textbox_handlers(registry, target_class, widget_getter): or QTextEdit. """ handlers = [ - (KeySequence, - (lambda wrapper, interaction: - _interaction_helpers.key_sequence_textbox( - widget_getter(wrapper), interaction, wrapper.delay))), - (KeyClick, - (lambda wrapper, interaction: - _interaction_helpers.key_click_qwidget( - widget_getter(wrapper), interaction, wrapper.delay))), - (MouseClick, - (lambda wrapper, _: _interaction_helpers.mouse_click_qwidget( - widget_getter(wrapper), wrapper.delay))), - (DisplayedText, + ( + KeySequence, + ( + lambda wrapper, interaction: _interaction_helpers.key_sequence_textbox( + widget_getter(wrapper), interaction, wrapper.delay + ) + ), + ), + ( + KeyClick, + ( + lambda wrapper, interaction: _interaction_helpers.key_click_qwidget( + widget_getter(wrapper), interaction, wrapper.delay + ) + ), + ), + ( + MouseClick, + ( + lambda wrapper, _: _interaction_helpers.mouse_click_qwidget( + widget_getter(wrapper), wrapper.delay + ) + ), + ), + ( + DisplayedText, lambda wrapper, _: _interaction_helpers.displayed_text_qobject( - widget_getter(wrapper))), + widget_getter(wrapper) + ), + ), ] for interaction_class, handler in handlers: registry.register_interaction( diff --git a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/boolean_editor.py b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/boolean_editor.py index 29a45086d..13df7ab90 100644 --- a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/boolean_editor.py +++ b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/boolean_editor.py @@ -11,13 +11,13 @@ from traitsui.testing.tester.command import MouseClick from traitsui.testing.tester.query import DisplayedText, IsChecked from traitsui.testing.tester._ui_tester_registry.qt4 import ( - _interaction_helpers + _interaction_helpers, ) from traitsui.qt4.boolean_editor import ReadonlyEditor, SimpleEditor def register(registry): - """ Register solvers/handlers specific to qt Boolean Editors + """Register solvers/handlers specific to qt Boolean Editors for the given registry. If there are any conflicts, an error will occur. @@ -31,13 +31,13 @@ def register(registry): interaction_class=MouseClick, handler=lambda wrapper, _: _interaction_helpers.mouse_click_qwidget( control=wrapper._target.control, delay=wrapper.delay - ) + ), ) registry.register_interaction( target_class=SimpleEditor, interaction_class=IsChecked, - handler=lambda wrapper, _: wrapper._target.control.isChecked() + handler=lambda wrapper, _: wrapper._target.control.isChecked(), ) registry.register_interaction( @@ -45,5 +45,5 @@ def register(registry): interaction_class=DisplayedText, handler=lambda wrapper, _: _interaction_helpers.displayed_text_qobject( widget=wrapper._target.control - ) + ), ) diff --git a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/button_editor.py b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/button_editor.py index 0f2299032..a309d04c9 100644 --- a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/button_editor.py +++ b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/button_editor.py @@ -11,13 +11,13 @@ from traitsui.testing.tester.command import MouseClick from traitsui.testing.tester.query import DisplayedText from traitsui.testing.tester._ui_tester_registry.qt4 import ( - _interaction_helpers + _interaction_helpers, ) from traitsui.qt4.button_editor import CustomEditor, SimpleEditor def register(registry): - """ Register solvers/handlers specific to qt Button Editors + """Register solvers/handlers specific to qt Button Editors for the given registry. If there are any conflicts, an error will occur. @@ -28,11 +28,13 @@ def register(registry): """ handlers = [ - (MouseClick, + ( + MouseClick, lambda wrapper, _: _interaction_helpers.mouse_click_qwidget( - wrapper._target.control, wrapper.delay)), - (DisplayedText, - lambda wrapper, _: wrapper._target.control.text()), + wrapper._target.control, wrapper.delay + ), + ), + (DisplayedText, lambda wrapper, _: wrapper._target.control.text()), ] for target_class in [SimpleEditor, CustomEditor]: @@ -40,5 +42,5 @@ def register(registry): registry.register_interaction( target_class=target_class, interaction_class=interaction_class, - handler=handler + handler=handler, ) diff --git a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/check_list_editor.py b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/check_list_editor.py index e16c8e915..0ce4fd162 100644 --- a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/check_list_editor.py +++ b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/check_list_editor.py @@ -12,34 +12,40 @@ from traitsui.testing.tester.command import MouseClick from traitsui.testing.tester.locator import Index from traitsui.testing.tester._ui_tester_registry._common_ui_targets import ( - BaseSourceWithLocation + BaseSourceWithLocation, ) from traitsui.testing.tester._ui_tester_registry._layout import ( - column_major_to_row_major + column_major_to_row_major, ) from traitsui.testing.tester._ui_tester_registry.qt4 import ( - _interaction_helpers + _interaction_helpers, ) class _IndexedCustomCheckListEditor(BaseSourceWithLocation): - """ Wrapper for CheckListEditor + locator.Index """ + """Wrapper for CheckListEditor + locator.Index""" + source_class = CustomEditor locator_class = Index handlers = [ - (MouseClick, - (lambda wrapper, _: _interaction_helpers.mouse_click_qlayout( - layout=wrapper._target.source.control.layout(), - index=convert_index( + ( + MouseClick, + ( + lambda wrapper, _: _interaction_helpers.mouse_click_qlayout( layout=wrapper._target.source.control.layout(), - index=wrapper._target.location.index, - ), - delay=wrapper.delay))), + index=convert_index( + layout=wrapper._target.source.control.layout(), + index=wrapper._target.location.index, + ), + delay=wrapper.delay, + ) + ), + ), ] def convert_index(layout, index): - """ Helper function to convert an index for a QGridLayout so that the + """Helper function to convert an index for a QGridLayout so that the index counts over the grid in the correct direction. The grid is always populated in row major order, but it is done so in such a way that the entries appear in column major order. @@ -61,7 +67,7 @@ def convert_index(layout, index): def register(registry): - """ Register interactions for the given registry. + """Register interactions for the given registry. If there are any conflicts, an error will occur. diff --git a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/directory_editor.py b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/directory_editor.py index 0bb39e3ed..52bd5ac4c 100644 --- a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/directory_editor.py +++ b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/directory_editor.py @@ -15,7 +15,7 @@ def register(registry): - """ Register interactions for the given registry. + """Register interactions for the given registry. If there are any conflicts, an error will occur. diff --git a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/editor_factory.py b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/editor_factory.py index ba7d0e25e..e4676a508 100644 --- a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/editor_factory.py +++ b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/editor_factory.py @@ -16,7 +16,7 @@ def register(registry): - """ Register interactions for the given registry. + """Register interactions for the given registry. If there are any conflicts, an error will occur. @@ -34,5 +34,5 @@ def register(registry): registry.register_interaction( target_class=ReadonlyEditor, interaction_class=DisplayedText, - handler=lambda wrapper, _: wrapper._target.control.text() + handler=lambda wrapper, _: wrapper._target.control.text(), ) diff --git a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/enum_editor.py b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/enum_editor.py index 587970c72..e5b91b811 100644 --- a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/enum_editor.py +++ b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/enum_editor.py @@ -21,52 +21,63 @@ from traitsui.testing.tester.locator import Index from traitsui.testing.tester.query import DisplayedText, SelectedText from traitsui.testing.tester._ui_tester_registry._common_ui_targets import ( - BaseSourceWithLocation + BaseSourceWithLocation, ) from traitsui.testing.tester._ui_tester_registry.qt4 import ( - _interaction_helpers + _interaction_helpers, ) from traitsui.testing.tester._ui_tester_registry._layout import ( - column_major_to_row_major + column_major_to_row_major, ) class _IndexedListEditor(BaseSourceWithLocation): - """ Wrapper class for EnumListEditor and Index. - """ + """Wrapper class for EnumListEditor and Index.""" + source_class = ListEditor locator_class = Index handlers = [ - (MouseClick, - (lambda wrapper, _: _interaction_helpers.mouse_click_item_view( - model=wrapper._target.source.control.model(), - view=wrapper._target.source.control, - index=wrapper._target.source.control.model().index( - wrapper._target.location.index, 0), - delay=wrapper.delay))), + ( + MouseClick, + ( + lambda wrapper, _: _interaction_helpers.mouse_click_item_view( + model=wrapper._target.source.control.model(), + view=wrapper._target.source.control, + index=wrapper._target.source.control.model().index( + wrapper._target.location.index, 0 + ), + delay=wrapper.delay, + ) + ), + ), ] class _IndexedRadioEditor(BaseSourceWithLocation): - """ Wrapper class for EnumRadioEditor and Index. - """ + """Wrapper class for EnumRadioEditor and Index.""" + source_class = RadioEditor locator_class = Index handlers = [ - (MouseClick, - (lambda wrapper, _: _interaction_helpers.mouse_click_qlayout( - layout=wrapper._target.source.control.layout(), - index=convert_index( + ( + MouseClick, + ( + lambda wrapper, _: _interaction_helpers.mouse_click_qlayout( layout=wrapper._target.source.control.layout(), - index=wrapper._target.location.index, - row_major=wrapper._target.source.row_major - ), - delay=wrapper.delay))), + index=convert_index( + layout=wrapper._target.source.control.layout(), + index=wrapper._target.location.index, + row_major=wrapper._target.source.row_major, + ), + delay=wrapper.delay, + ) + ), + ), ] def convert_index(layout, index, row_major): - """ Helper function to convert an index for a QGridLayout so that the + """Helper function to convert an index for a QGridLayout so that the index counts over the grid in the correct direction. The grid is always populated in row major order. The row_major trait of a Radio Enum Editor simply changes what elements are assigned to each entry @@ -94,21 +105,26 @@ def convert_index(layout, index, row_major): class _IndexedSimpleEditor(BaseSourceWithLocation): - """ Wrapper class for Simple EnumEditor and Index. - """ + """Wrapper class for Simple EnumEditor and Index.""" + source_class = SimpleEditor locator_class = Index handlers = [ - (MouseClick, - (lambda wrapper, _: _interaction_helpers.mouse_click_combobox( - combobox=wrapper._target.source.control, - index=wrapper._target.location.index, - delay=wrapper.delay))), + ( + MouseClick, + ( + lambda wrapper, _: _interaction_helpers.mouse_click_combobox( + combobox=wrapper._target.source.control, + index=wrapper._target.location.index, + delay=wrapper.delay, + ) + ), + ), ] def radio_selected_text_handler(wrapper, interaction): - """ Handler function used to query SelectedText for EnumRadioEditor. + """Handler function used to query SelectedText for EnumRadioEditor. Parameters ---------- @@ -126,7 +142,7 @@ def radio_selected_text_handler(wrapper, interaction): def register(registry): - """ Registry location and interaction handlers for EnumEditor. + """Registry location and interaction handlers for EnumEditor. Parameters ---------- @@ -137,29 +153,41 @@ def register(registry): _IndexedSimpleEditor.register(registry) simple_editor_text_handlers = [ - (KeyClick, - (lambda wrapper, interaction: - _interaction_helpers.key_click_qwidget( + ( + KeyClick, + ( + lambda wrapper, interaction: _interaction_helpers.key_click_qwidget( control=wrapper._target.control, interaction=interaction, - delay=wrapper.delay))), - (KeySequence, - (lambda wrapper, interaction: - _interaction_helpers.key_sequence_qwidget( + delay=wrapper.delay, + ) + ), + ), + ( + KeySequence, + ( + lambda wrapper, interaction: _interaction_helpers.key_sequence_qwidget( control=wrapper._target.control, interaction=interaction, - delay=wrapper.delay))), - (DisplayedText, - lambda wrapper, _: wrapper._target.control.currentText()), - (SelectedText, - lambda wrapper, _: wrapper._target.control.currentText()) + delay=wrapper.delay, + ) + ), + ), + ( + DisplayedText, + lambda wrapper, _: wrapper._target.control.currentText(), + ), + ( + SelectedText, + lambda wrapper, _: wrapper._target.control.currentText(), + ), ] for interaction_class, handler in simple_editor_text_handlers: registry.register_interaction( target_class=SimpleEditor, interaction_class=interaction_class, - handler=handler + handler=handler, ) registry.register_interaction( @@ -171,6 +199,5 @@ def register(registry): registry.register_interaction( target_class=ListEditor, interaction_class=SelectedText, - handler=lambda wrapper, _: - wrapper._target.control.currentItem().text(), + handler=lambda wrapper, _: wrapper._target.control.currentItem().text(), ) diff --git a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/file_editor.py b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/file_editor.py index 03292248e..eddc0e776 100644 --- a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/file_editor.py +++ b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/file_editor.py @@ -15,7 +15,7 @@ def register(registry): - """ Register interactions for the given registry. + """Register interactions for the given registry. If there are any conflicts, an error will occur. diff --git a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/font_editor.py b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/font_editor.py index 60749a1d4..7b18a9143 100644 --- a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/font_editor.py +++ b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/font_editor.py @@ -15,7 +15,7 @@ def register(registry): - """ Register interactions pertaining to (Qt) FontEditor for the given + """Register interactions pertaining to (Qt) FontEditor for the given registry. Parameters diff --git a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/instance_editor.py b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/instance_editor.py index c77656071..ed59805d0 100644 --- a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/instance_editor.py +++ b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/instance_editor.py @@ -12,22 +12,20 @@ from traitsui.testing.tester.locator import Index from traitsui.testing.tester.query import SelectedText from traitsui.testing.tester._ui_tester_registry._common_ui_targets import ( - BaseSourceWithLocation + BaseSourceWithLocation, ) from traitsui.testing.tester._ui_tester_registry.qt4._interaction_helpers import ( # noqa - mouse_click_combobox, mouse_click_qwidget + mouse_click_combobox, + mouse_click_qwidget, ) from traitsui.testing.tester._ui_tester_registry._traitsui_ui import ( register_traitsui_ui_solvers, ) -from traitsui.qt4.instance_editor import ( - CustomEditor, - SimpleEditor -) +from traitsui.qt4.instance_editor import CustomEditor, SimpleEditor def _get_nested_ui_simple(target): - """ Obtains a nested UI within a Simple Instance Editor. + """Obtains a nested UI within a Simple Instance Editor. Parameters ---------- @@ -37,7 +35,7 @@ def _get_nested_ui_simple(target): def _get_nested_ui_custom(target): - """ Obtains a nested UI within a Custom Instance Editor. + """Obtains a nested UI within a Custom Instance Editor. Parameters ---------- @@ -47,7 +45,7 @@ def _get_nested_ui_custom(target): def _get_combobox(target): - """ Obtains a nested combobox within an Instance Editor. + """Obtains a nested combobox within an Instance Editor. Parameters ---------- @@ -69,8 +67,8 @@ def _get_combobox_text(wrapper, _): class _IndexedCustomEditor(BaseSourceWithLocation): - """ Wrapper class for CustomEditors with a selection. - """ + """Wrapper class for CustomEditors with a selection.""" + source_class = CustomEditor locator_class = Index handlers = [ @@ -79,7 +77,7 @@ class _IndexedCustomEditor(BaseSourceWithLocation): def register(registry): - """ Register interactions for the given registry. + """Register interactions for the given registry. If there are any conflicts, an error will occur. @@ -95,7 +93,7 @@ def register(registry): interaction_class=MouseClick, handler=lambda wrapper, _: ( mouse_click_qwidget(wrapper._target._button, delay=wrapper.delay) - ) + ), ) register_traitsui_ui_solvers(registry, SimpleEditor, _get_nested_ui_simple) diff --git a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/list_editor.py b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/list_editor.py index d01891ac4..76401e46c 100644 --- a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/list_editor.py +++ b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/list_editor.py @@ -11,37 +11,38 @@ from traitsui.testing.tester.command import MouseClick from traitsui.testing.tester.locator import Index from traitsui.testing.tester._ui_tester_registry._common_ui_targets import ( - BaseSourceWithLocation + BaseSourceWithLocation, ) from traitsui.testing.tester._ui_tester_registry._traitsui_ui import ( register_traitsui_ui_solvers, ) from traitsui.testing.tester._ui_tester_registry.qt4 import ( - _interaction_helpers -) -from traitsui.qt4.list_editor import ( - CustomEditor, - NotebookEditor, - SimpleEditor + _interaction_helpers, ) +from traitsui.qt4.list_editor import CustomEditor, NotebookEditor, SimpleEditor class _IndexedNotebookEditor(BaseSourceWithLocation): - """ Wrapper for a ListEditor (Notebook) with an index. - """ + """Wrapper for a ListEditor (Notebook) with an index.""" + source_class = NotebookEditor locator_class = Index handlers = [ - (MouseClick, - (lambda wrapper, _: _interaction_helpers.mouse_click_tab_index( - tab_widget=wrapper._target.source.control, - index=wrapper._target.location.index, - delay=wrapper.delay))), + ( + MouseClick, + ( + lambda wrapper, _: _interaction_helpers.mouse_click_tab_index( + tab_widget=wrapper._target.source.control, + index=wrapper._target.location.index, + delay=wrapper.delay, + ) + ), + ), ] @classmethod def register(cls, registry): - """ Class method to register interactions on a _IndexedNotebookEditor + """Class method to register interactions on a _IndexedNotebookEditor for the given registry. If there are any conflicts, an error will occur. @@ -55,18 +56,18 @@ def register(cls, registry): register_traitsui_ui_solvers( registry=registry, target_class=cls, - traitsui_ui_getter=lambda target: target._get_nested_ui() + traitsui_ui_getter=lambda target: target._get_nested_ui(), ) def _get_nested_ui(self): - """ Method to get the nested ui corresponding to the List element at + """Method to get the nested ui corresponding to the List element at the given index. """ return self.source._uis[self.location.index][1] def _get_next_target(list_editor, index): - """ Gets the target at a given index from a Custom List Editor. + """Gets the target at a given index from a Custom List Editor. Parameters ---------- @@ -83,7 +84,7 @@ def _get_next_target(list_editor, index): row, column = divmod(index, list_editor.factory.columns) # there are two columns for each list item (one for the item itself, # and another for the list menu button) - column = 2*column + column = 2 * column grid_layout = list_editor._list_pane.layout() item = grid_layout.itemAtPosition(row, column) if item is None: @@ -94,7 +95,7 @@ def _get_next_target(list_editor, index): def register(registry): - """ Register interactions for the given registry. + """Register interactions for the given registry. If there are any conflicts, an error will occur. @@ -111,7 +112,7 @@ def register(registry): locator_class=Index, solver=lambda wrapper, location: ( _get_next_target(wrapper._target, location.index) - ) + ), ) # SimpleEditor registry.register_location( @@ -119,5 +120,5 @@ def register(registry): locator_class=Index, solver=lambda wrapper, location: ( _get_next_target(wrapper._target, location.index) - ) + ), ) diff --git a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/range_editor.py b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/range_editor.py index 68beffdcf..8c3aab604 100644 --- a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/range_editor.py +++ b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/range_editor.py @@ -19,12 +19,12 @@ from traitsui.testing.tester.locator import Slider, Textbox from traitsui.testing.tester._ui_tester_registry.qt4 import ( _interaction_helpers, - _registry_helper + _registry_helper, ) class LocatedTextbox: - """ Wrapper class for a located Textbox in Qt. + """Wrapper class for a located Textbox in Qt. Parameters ---------- @@ -36,7 +36,7 @@ def __init__(self, textbox): @classmethod def register(cls, registry): - """ Class method to register interactions on a LocatedTextbox for the + """Class method to register interactions on a LocatedTextbox for the given registry. If there are any conflicts, an error will occur. @@ -54,7 +54,7 @@ def register(cls, registry): class LocatedSlider: - """ Wrapper class for a located Slider in Qt. + """Wrapper class for a located Slider in Qt. Parameters ---------- @@ -66,7 +66,7 @@ def __init__(self, slider): @classmethod def register(cls, registry): - """ Class method to register interactions on a LocatedSlider for the + """Class method to register interactions on a LocatedSlider for the given registry. If there are any conflicts, an error will occur. @@ -79,14 +79,14 @@ def register(cls, registry): registry.register_interaction( target_class=cls, interaction_class=KeyClick, - handler=lambda wrapper, interaction: - _interaction_helpers.key_click_qslider( - wrapper._target.slider, interaction, wrapper.delay) + handler=lambda wrapper, interaction: _interaction_helpers.key_click_qslider( + wrapper._target.slider, interaction, wrapper.delay + ), ) def register(registry): - """ Register interactions for the given registry. + """Register interactions for the given registry. If there are any conflicts, an error will occur. @@ -96,21 +96,25 @@ def register(registry): The registry being registered to. """ - targets = [SimpleSliderEditor, - LogRangeSliderEditor, - LargeRangeSliderEditor] + targets = [ + SimpleSliderEditor, + LogRangeSliderEditor, + LargeRangeSliderEditor, + ] for target_class in targets: registry.register_location( target_class=target_class, locator_class=Textbox, solver=lambda wrapper, _: LocatedTextbox( - textbox=wrapper._target.control.text), + textbox=wrapper._target.control.text + ), ) registry.register_location( target_class=target_class, locator_class=Slider, solver=lambda wrapper, _: LocatedSlider( - slider=wrapper._target.control.slider), + slider=wrapper._target.control.slider + ), ) _registry_helper.register_editable_textbox_handlers( registry=registry, diff --git a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/text_editor.py b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/text_editor.py index f91ce1b26..50b2a24f5 100644 --- a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/text_editor.py +++ b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/text_editor.py @@ -10,7 +10,7 @@ from traitsui.testing.tester.query import DisplayedText from traitsui.testing.tester._ui_tester_registry.qt4 import ( - _interaction_helpers + _interaction_helpers, ) from traitsui.testing.tester._ui_tester_registry.qt4._registry_helper import ( register_editable_textbox_handlers, @@ -19,7 +19,7 @@ def register(registry): - """ Register interactions for the given registry. + """Register interactions for the given registry. If there are any conflicts, an error will occur. @@ -40,5 +40,6 @@ def register(registry): target_class=ReadonlyEditor, interaction_class=DisplayedText, handler=lambda wrapper, _: _interaction_helpers.displayed_text_qobject( - wrapper._target.control), + wrapper._target.control + ), ) diff --git a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/ui_base.py b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/ui_base.py index 6c8c1a08e..e3ca3c3b5 100644 --- a/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/ui_base.py +++ b/traitsui/testing/tester/_ui_tester_registry/qt4/_traitsui/ui_base.py @@ -12,12 +12,12 @@ from traitsui.testing.tester.command import MouseClick from traitsui.testing.tester.query import DisplayedText from traitsui.testing.tester._ui_tester_registry.qt4 import ( - _interaction_helpers + _interaction_helpers, ) def register(registry): - """ Register solvers/handlers specific to qt ui_base Editors + """Register solvers/handlers specific to qt ui_base Editors for the given registry. If there are any conflicts, an error will occur. @@ -27,15 +27,19 @@ def register(registry): registry : TargetRegistry """ handlers = [ - (MouseClick, - (lambda wrapper, _: _interaction_helpers.mouse_click_qwidget( - wrapper._target.control, wrapper.delay))), - (DisplayedText, - lambda wrapper, _: wrapper._target.control.text()), + ( + MouseClick, + ( + lambda wrapper, _: _interaction_helpers.mouse_click_qwidget( + wrapper._target.control, wrapper.delay + ) + ), + ), + (DisplayedText, lambda wrapper, _: wrapper._target.control.text()), ] for interaction_class, handler in handlers: registry.register_interaction( target_class=ButtonEditor, interaction_class=interaction_class, - handler=handler + handler=handler, ) diff --git a/traitsui/testing/tester/_ui_tester_registry/qt4/default_registry.py b/traitsui/testing/tester/_ui_tester_registry/qt4/default_registry.py index f386f2aa3..b6c726a53 100644 --- a/traitsui/testing/tester/_ui_tester_registry/qt4/default_registry.py +++ b/traitsui/testing/tester/_ui_tester_registry/qt4/default_registry.py @@ -28,7 +28,7 @@ def get_default_registries(): - """ Creates the default registries for UITester that are qt specific. + """Creates the default registries for UITester that are qt specific. Returns ------- diff --git a/traitsui/testing/tester/_ui_tester_registry/qt4/tests/test_control_widget_registry.py b/traitsui/testing/tester/_ui_tester_registry/qt4/tests/test_control_widget_registry.py index cb2b5ae66..ffdc16363 100644 --- a/traitsui/testing/tester/_ui_tester_registry/qt4/tests/test_control_widget_registry.py +++ b/traitsui/testing/tester/_ui_tester_registry/qt4/tests/test_control_widget_registry.py @@ -29,13 +29,13 @@ if is_qt(): raise else: - from traitsui.testing.tester._ui_tester_registry.qt4._control_widget_registry import ( # noqa: E501 + from traitsui.testing.tester._ui_tester_registry.qt4._control_widget_registry import ( # noqa: E501 get_widget_registry, ) class TargetWithControl: - """ An object holding a control attribute.""" + """An object holding a control attribute.""" def __init__(self, control): self.control = control @@ -43,8 +43,7 @@ def __init__(self, control): @requires_toolkit([ToolkitName.qt]) class TestQtControlWidgetRegistry(unittest.TestCase): - """ Test the interface of AbstractTargetRegistry for QWidget's registry - """ + """Test the interface of AbstractTargetRegistry for QWidget's registry""" def setUp(self): self.widget = QtGui.QWidget() @@ -73,7 +72,7 @@ def test_is_invisible(self): def test_get_interactions_good_target(self): self.assertEqual( self.registry._get_interactions(self.target), - set([IsEnabled, IsVisible]) + set([IsEnabled, IsVisible]), ) def test_get_interactions_bad_target(self): diff --git a/traitsui/testing/tester/_ui_tester_registry/qt4/tests/test_interaction_helpers.py b/traitsui/testing/tester/_ui_tester_registry/qt4/tests/test_interaction_helpers.py index ef828d229..ad689adf2 100644 --- a/traitsui/testing/tester/_ui_tester_registry/qt4/tests/test_interaction_helpers.py +++ b/traitsui/testing/tester/_ui_tester_registry/qt4/tests/test_interaction_helpers.py @@ -19,7 +19,7 @@ from traitsui.testing.tester import command from traitsui.testing.tester.exceptions import Disabled from traitsui.testing.tester._ui_tester_registry.qt4 import ( - _interaction_helpers + _interaction_helpers, ) try: @@ -31,7 +31,6 @@ @requires_toolkit([ToolkitName.qt]) class TestInteractions(unittest.TestCase): - def test_mouse_click(self): button = QtGui.QPushButton() click_slot = mock.Mock() @@ -70,7 +69,8 @@ def test_key_sequence(self): # when _interaction_helpers.key_sequence_qwidget( - textbox, command.KeySequence("abc"), 0) + textbox, command.KeySequence("abc"), 0 + ) # then if i == 0: @@ -83,7 +83,8 @@ def test_key_sequence(self): # for a QLabel, one can try a key sequence and nothing will happen textbox = QtGui.QLabel() _interaction_helpers.key_sequence_qwidget( - textbox, command.KeySequence("abc"), 0) + textbox, command.KeySequence("abc"), 0 + ) self.assertEqual(textbox.text(), "") def test_key_sequence_textbox_with_unicode(self): @@ -175,7 +176,8 @@ def test_key_sequence_disabled(self): # cursor on the widget to type anything with self.assertRaises(Disabled): _interaction_helpers.key_sequence_qwidget( - textbox, command.KeySequence("abc"), 0) + textbox, command.KeySequence("abc"), 0 + ) def test_key_click(self): textbox = QtGui.QLineEdit() @@ -184,11 +186,13 @@ def test_key_click(self): # sanity check on editingFinished signal _interaction_helpers.key_sequence_qwidget( - textbox, command.KeySequence("abc"), 0) + textbox, command.KeySequence("abc"), 0 + ) self.assertEqual(change_slot.call_count, 0) _interaction_helpers.key_click_qwidget( - textbox, command.KeyClick("Enter"), 0) + textbox, command.KeyClick("Enter"), 0 + ) self.assertEqual(change_slot.call_count, 1) # test on a different Qwidget object - QtGui.QTextEdit() @@ -197,14 +201,16 @@ def test_key_click(self): # Now "Enter" should not finish editing, but instead go to next line textbox.textChanged.connect(change_slot) _interaction_helpers.key_click_qwidget( - textbox, command.KeyClick("Enter"), 0) + textbox, command.KeyClick("Enter"), 0 + ) self.assertEqual(change_slot.call_count, 1) self.assertEqual(textbox.toPlainText(), "\n") # for a QLabel, one can try a key click and nothing will happen textbox = QtGui.QLabel() _interaction_helpers.key_click_qwidget( - textbox, command.KeyClick("A"), 0) + textbox, command.KeyClick("A"), 0 + ) self.assertEqual(textbox.text(), "") def test_key_click_disabled(self): @@ -215,7 +221,8 @@ def test_key_click_disabled(self): with self.assertRaises(Disabled): _interaction_helpers.key_click_qwidget( - textbox, command.KeyClick("Enter"), 0) + textbox, command.KeyClick("Enter"), 0 + ) self.assertEqual(change_slot.call_count, 0) def test_check_q_model_index_valid(self): @@ -234,8 +241,9 @@ def test_key_click_q_slider_helpful_err(self): slider = QtGui.QSlider() with self.assertRaises(ValueError) as exc: _interaction_helpers.key_click_qslider( - slider, command.KeyClick("Enter"), 0) + slider, command.KeyClick("Enter"), 0 + ) self.assertIn( "['Down', 'Left', 'Page Down', 'Page Up', 'Right', 'Up']", - str(exc.exception) + str(exc.exception), ) diff --git a/traitsui/testing/tester/_ui_tester_registry/tests/test_default_registry.py b/traitsui/testing/tester/_ui_tester_registry/tests/test_default_registry.py index abdb2524a..fe515c466 100644 --- a/traitsui/testing/tester/_ui_tester_registry/tests/test_default_registry.py +++ b/traitsui/testing/tester/_ui_tester_registry/tests/test_default_registry.py @@ -14,12 +14,11 @@ AbstractTargetRegistry, ) from traitsui.testing.tester._ui_tester_registry.default_registry import ( - get_default_registries + get_default_registries, ) class TestDefaultRegistry(unittest.TestCase): - def test_load_default_registries(self): registries = get_default_registries() for registry in registries: diff --git a/traitsui/testing/tester/_ui_tester_registry/tests/test_layout.py b/traitsui/testing/tester/_ui_tester_registry/tests/test_layout.py index cabfa6734..ea51af985 100644 --- a/traitsui/testing/tester/_ui_tester_registry/tests/test_layout.py +++ b/traitsui/testing/tester/_ui_tester_registry/tests/test_layout.py @@ -11,12 +11,11 @@ import unittest from traitsui.testing.tester._ui_tester_registry._layout import ( - column_major_to_row_major + column_major_to_row_major, ) class TestLayout(unittest.TestCase): - def test_column_major_index_too_large(self): # Test when the index is too large for the total number of elements # The indices would look like: diff --git a/traitsui/testing/tester/_ui_tester_registry/wx/_control_widget_registry.py b/traitsui/testing/tester/_ui_tester_registry/wx/_control_widget_registry.py index a9acaaa9b..bd5e432ea 100644 --- a/traitsui/testing/tester/_ui_tester_registry/wx/_control_widget_registry.py +++ b/traitsui/testing/tester/_ui_tester_registry/wx/_control_widget_registry.py @@ -20,7 +20,7 @@ def _handle_is_enabled(wrapper, interaction): - """ Return true if the target's control is enabled. + """Return true if the target's control is enabled. Parameters ---------- @@ -33,7 +33,7 @@ def _handle_is_enabled(wrapper, interaction): def _handle_is_visible(wrapper, interaction): - """ Return true if the target's control is visible. + """Return true if the target's control is visible. Parameters ---------- @@ -46,7 +46,7 @@ def _handle_is_visible(wrapper, interaction): def _is_target_control_a_wx_window(target): - """ Return true if the target has a control that is an instance of + """Return true if the target has a control that is an instance of wx.Window Parameters @@ -58,14 +58,11 @@ def _is_target_control_a_wx_window(target): ------- is_accepted : bool """ - return ( - hasattr(target, "control") - and isinstance(target.control, wx.Window) - ) + return hasattr(target, "control") and isinstance(target.control, wx.Window) def get_widget_registry(): - """ Return a registry to support any target with an attribute 'control' + """Return a registry to support any target with an attribute 'control' that is an instance of wx.Window. Returns @@ -78,5 +75,5 @@ def get_widget_registry(): interaction_to_handler={ IsEnabled: _handle_is_enabled, IsVisible: _handle_is_visible, - } + }, ) diff --git a/traitsui/testing/tester/_ui_tester_registry/wx/_interaction_helpers.py b/traitsui/testing/tester/_ui_tester_registry/wx/_interaction_helpers.py index 31924c160..a0c3acd48 100644 --- a/traitsui/testing/tester/_ui_tester_registry/wx/_interaction_helpers.py +++ b/traitsui/testing/tester/_ui_tester_registry/wx/_interaction_helpers.py @@ -12,13 +12,13 @@ import wx from traitsui.testing.tester._ui_tester_registry._compat import ( - check_key_compat + check_key_compat, ) from traitsui.testing.tester.exceptions import Disabled def _create_event(event_type, control): - """ Creates a wxEvent of a given type + """Creates a wxEvent of a given type Parameters ---------- @@ -33,15 +33,13 @@ def _create_event(event_type, control): The created event, of the given type, with the given control set as the event object. """ - event = wx.CommandEvent( - event_type, control.GetId() - ) + event = wx.CommandEvent(event_type, control.GetId()) event.SetEventObject(control) return event def mouse_click(func): - """ Decorator function for mouse clicks. Decorated functions will return + """Decorator function for mouse clicks. Decorated functions will return if they are not enabled. Additionally, this handles the delay for the click. @@ -55,8 +53,9 @@ def mouse_click(func): callable The decorated function. """ + def mouse_click_handler(*, control, delay, **kwargs): - """ Defines the decorated function. + """Defines the decorated function. Paramters --------- @@ -73,12 +72,13 @@ def mouse_click_handler(*, control, delay, **kwargs): return wx.MilliSleep(delay) func(control=control, delay=delay, **kwargs) + return mouse_click_handler @mouse_click def mouse_click_button(control, delay): - """ Performs a mouce click on a wx button. + """Performs a mouce click on a wx button. Parameters ---------- @@ -93,7 +93,7 @@ def mouse_click_button(control, delay): @mouse_click def mouse_click_checkbox(control, delay): - """ Performs a mouce click on a wx check box. + """Performs a mouce click on a wx check box. Parameters ---------- @@ -109,7 +109,7 @@ def mouse_click_checkbox(control, delay): @mouse_click def mouse_click_combobox_or_choice(control, index, delay): - """ Performs a mouce click on either a wx combo box or a wx choice on the + """Performs a mouce click on either a wx combo box or a wx choice on the entry at the given index. Parameters @@ -160,7 +160,7 @@ def mouse_click_listbox(control, index, delay): @mouse_click def mouse_click_radiobutton(control, delay): - """ Performs a mouce click on a wx radio button. + """Performs a mouce click on a wx radio button. Parameters ---------- @@ -176,7 +176,7 @@ def mouse_click_radiobutton(control, delay): @mouse_click def mouse_click_object(control, delay): - """ Performs a mouce click on a wxTextCtrl. + """Performs a mouce click on a wxTextCtrl. Parameters ---------- @@ -192,7 +192,7 @@ def mouse_click_object(control, delay): def mouse_click_notebook_tab_index(control, index, delay): - """ Performs a mouseclick on a Noteboook List Editor on the tab specified + """Performs a mouseclick on a Noteboook List Editor on the tab specified by index. Parameters @@ -210,22 +210,18 @@ def mouse_click_notebook_tab_index(control, index, delay): # find the boundaries of the tab to be clicked bx, by, bdx, bdy = controls_list[index].drag_bounds # find the center - tab_center = wx.Point(bx + bdx//2, by + bdy//2) + tab_center = wx.Point(bx + bdx // 2, by + bdy // 2) - click_down_event = wx.MouseEvent( - wx.wxEVT_LEFT_DOWN - ) + click_down_event = wx.MouseEvent(wx.wxEVT_LEFT_DOWN) click_down_event.SetPosition(tab_center) - click_up_event = wx.MouseEvent( - wx.wxEVT_LEFT_UP - ) + click_up_event = wx.MouseEvent(wx.wxEVT_LEFT_UP) click_up_event.SetPosition(tab_center) control.ProcessEvent(click_down_event) control.ProcessEvent(click_up_event) def mouse_click_checkbox_child_in_panel(control, index, delay): - """ Performs a mouce click on a child of a Wx Panel. + """Performs a mouce click on a child of a Wx Panel. Parameters ---------- @@ -249,7 +245,7 @@ def mouse_click_checkbox_child_in_panel(control, index, delay): def mouse_click_radiobutton_child_in_panel(control, index, delay): - """ Performs a mouce click on a child of a Wx Panel. + """Performs a mouce click on a child of a Wx Panel. Parameters ---------- @@ -273,10 +269,12 @@ def mouse_click_radiobutton_child_in_panel(control, index, delay): def key_click_text_entry( - control, interaction, delay, - get_selection=lambda control: control.GetSelection() + control, + interaction, + delay, + get_selection=lambda control: control.GetSelection(), ): - """ Performs simulated typing of a key on the given wxObject + """Performs simulated typing of a key on the given wxObject after a delay. Parameters @@ -321,7 +319,7 @@ def key_click_text_entry( def key_click_combobox(control, interaction, delay): - """ Performs simulated typing of a key on the given wxComboBox + """Performs simulated typing of a key on the given wxComboBox after a delay. Parameters @@ -335,13 +333,15 @@ def key_click_combobox(control, interaction, delay): Time delay (in ms) in which the key click will be performed. """ key_click_text_entry( - control, interaction, delay, + control, + interaction, + delay, get_selection=lambda control: control.GetTextSelection(), ) def key_sequence_text_ctrl(control, interaction, delay): - """ Performs simulated typing of a sequence of keys on the given wxObject + """Performs simulated typing of a sequence of keys on the given wxObject after a delay. Parameters @@ -376,7 +376,7 @@ def key_sequence_text_ctrl(control, interaction, delay): def key_click_slider(control, interaction, delay): - """ Performs simulated typing of a key on the given wxSlider + """Performs simulated typing of a key on the given wxSlider after a delay. Only allowed keys are: "Left", "Right", "Up", "Down", "Page Up", "Page Down" Also, note that up related keys correspond to an increment on the slider, @@ -419,14 +419,12 @@ def key_click_slider(control, interaction, delay): ) wx.MilliSleep(delay) control.SetValue(position) - event = wx.ScrollEvent( - wx.wxEVT_SCROLL_CHANGED, control.GetId(), position - ) + event = wx.ScrollEvent(wx.wxEVT_SCROLL_CHANGED, control.GetId(), position) wx.PostEvent(control, event) def readonly_textbox_displayed_text(control): - ''' Extracts the displayed text in a wx textbox (either a wx.TextCtrl or + '''Extracts the displayed text in a wx textbox (either a wx.TextCtrl or wx.StaticText). Parameters @@ -443,6 +441,8 @@ def readonly_textbox_displayed_text(control): return control.GetValue() elif isinstance(control, wx.StaticText): return control.GetLabel() - raise TypeError("readonly_textbox_displayed_text expected a control" - " of either wx.TextCtrl, or wx.StaticText." - " {} was found".format(control)) + raise TypeError( + "readonly_textbox_displayed_text expected a control" + " of either wx.TextCtrl, or wx.StaticText." + " {} was found".format(control) + ) diff --git a/traitsui/testing/tester/_ui_tester_registry/wx/_registry_helper.py b/traitsui/testing/tester/_ui_tester_registry/wx/_registry_helper.py index cdff339c5..35162b75d 100644 --- a/traitsui/testing/tester/_ui_tester_registry/wx/_registry_helper.py +++ b/traitsui/testing/tester/_ui_tester_registry/wx/_registry_helper.py @@ -12,17 +12,13 @@ and location solvers for common Wx GUI components. """ -from traitsui.testing.tester.command import ( - KeyClick, - KeySequence, - MouseClick -) +from traitsui.testing.tester.command import KeyClick, KeySequence, MouseClick from traitsui.testing.tester.query import DisplayedText from traitsui.testing.tester._ui_tester_registry.wx import _interaction_helpers def register_editable_textbox_handlers(registry, target_class, widget_getter): - """ Register common interactions for an editable textbox (in Wx) + """Register common interactions for an editable textbox (in Wx) Parameters ---------- @@ -35,19 +31,31 @@ def register_editable_textbox_handlers(registry, target_class, widget_getter): A callable to return a wx.TextCtrl """ handlers = [ - (KeySequence, - (lambda wrapper, interaction: - _interaction_helpers.key_sequence_text_ctrl( - widget_getter(wrapper), interaction, wrapper.delay))), - (KeyClick, - (lambda wrapper, interaction: - _interaction_helpers.key_click_text_entry( - widget_getter(wrapper), interaction, wrapper.delay))), - (MouseClick, - (lambda wrapper, _: _interaction_helpers.mouse_click_object( - control=widget_getter(wrapper), delay=wrapper.delay))), - (DisplayedText, - lambda wrapper, _: widget_getter(wrapper).GetValue()), + ( + KeySequence, + ( + lambda wrapper, interaction: _interaction_helpers.key_sequence_text_ctrl( + widget_getter(wrapper), interaction, wrapper.delay + ) + ), + ), + ( + KeyClick, + ( + lambda wrapper, interaction: _interaction_helpers.key_click_text_entry( + widget_getter(wrapper), interaction, wrapper.delay + ) + ), + ), + ( + MouseClick, + ( + lambda wrapper, _: _interaction_helpers.mouse_click_object( + control=widget_getter(wrapper), delay=wrapper.delay + ) + ), + ), + (DisplayedText, lambda wrapper, _: widget_getter(wrapper).GetValue()), ] for interaction_class, handler in handlers: registry.register_interaction( diff --git a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/boolean_editor.py b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/boolean_editor.py index 7acb88ffb..15125c172 100644 --- a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/boolean_editor.py +++ b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/boolean_editor.py @@ -15,7 +15,7 @@ def register(registry): - """ Register solvers/handlers specific to wx Boolean Editors + """Register solvers/handlers specific to wx Boolean Editors for the given registry. If there are any conflicts, an error will occur. @@ -27,21 +27,23 @@ def register(registry): registry.register_interaction( target_class=SimpleEditor, interaction_class=MouseClick, - handler=(lambda wrapper, _: _interaction_helpers.mouse_click_checkbox( - control=wrapper._target.control, delay=wrapper.delay)) + handler=( + lambda wrapper, _: _interaction_helpers.mouse_click_checkbox( + control=wrapper._target.control, delay=wrapper.delay + ) + ), ) registry.register_interaction( target_class=SimpleEditor, interaction_class=IsChecked, - handler=lambda wrapper, _: wrapper._target.control.GetValue() + handler=lambda wrapper, _: wrapper._target.control.GetValue(), ) registry.register_interaction( target_class=ReadonlyEditor, interaction_class=DisplayedText, - handler=lambda wrapper, _: - _interaction_helpers.readonly_textbox_displayed_text( - control=wrapper._target.control - ) + handler=lambda wrapper, _: _interaction_helpers.readonly_textbox_displayed_text( + control=wrapper._target.control + ), ) diff --git a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/button_editor.py b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/button_editor.py index de13284b1..e6f945e56 100644 --- a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/button_editor.py +++ b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/button_editor.py @@ -17,7 +17,7 @@ def mouse_click_ImageButton(wrapper, interaction): - """ Performs a mouce click on an pyface.ui.wx.ImageButton object. + """Performs a mouce click on an pyface.ui.wx.ImageButton object. Parameters ---------- @@ -35,18 +35,14 @@ def mouse_click_ImageButton(wrapper, interaction): return wx.MilliSleep(wrapper.delay) - left_down_event = wx.MouseEvent( - wx.wxEVT_LEFT_DOWN - ) - left_up_event = wx.MouseEvent( - wx.wxEVT_LEFT_UP - ) + left_down_event = wx.MouseEvent(wx.wxEVT_LEFT_DOWN) + left_up_event = wx.MouseEvent(wx.wxEVT_LEFT_UP) control.ProcessEvent(left_down_event) control.ProcessEvent(left_up_event) def register(registry): - """ Register solvers/handlers specific to wx Button Editors + """Register solvers/handlers specific to wx Button Editors for the given registry. If there are any conflicts, an error will occur. @@ -59,24 +55,27 @@ def register(registry): registry.register_interaction( target_class=SimpleEditor, interaction_class=MouseClick, - handler=(lambda wrapper, _: _interaction_helpers.mouse_click_button( - control=wrapper._target.control, delay=wrapper.delay)) + handler=( + lambda wrapper, _: _interaction_helpers.mouse_click_button( + control=wrapper._target.control, delay=wrapper.delay + ) + ), ) registry.register_interaction( target_class=SimpleEditor, interaction_class=DisplayedText, - handler=lambda wrapper, _: wrapper._target.control.GetLabel() + handler=lambda wrapper, _: wrapper._target.control.GetLabel(), ) registry.register_interaction( target_class=CustomEditor, interaction_class=MouseClick, - handler=mouse_click_ImageButton + handler=mouse_click_ImageButton, ) registry.register_interaction( target_class=CustomEditor, interaction_class=DisplayedText, - handler=lambda wrapper, _: wrapper._target.control.GetLabel() + handler=lambda wrapper, _: wrapper._target.control.GetLabel(), ) diff --git a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/check_list_editor.py b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/check_list_editor.py index d21b330ee..07d807bdd 100644 --- a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/check_list_editor.py +++ b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/check_list_editor.py @@ -14,34 +14,38 @@ from traitsui.testing.tester.command import MouseClick from traitsui.testing.tester.locator import Index from traitsui.testing.tester._ui_tester_registry._common_ui_targets import ( - BaseSourceWithLocation + BaseSourceWithLocation, ) from traitsui.testing.tester._ui_tester_registry._layout import ( - column_major_to_row_major + column_major_to_row_major, ) from traitsui.testing.tester._ui_tester_registry.wx import _interaction_helpers class _IndexedCustomCheckListEditor(BaseSourceWithLocation): - """ Wrapper for CheckListEditor + Index - """ + """Wrapper for CheckListEditor + Index""" + source_class = CustomEditor locator_class = Index handlers = [ - (MouseClick, - (lambda wrapper, _: - _interaction_helpers.mouse_click_checkbox_child_in_panel( + ( + MouseClick, + ( + lambda wrapper, _: _interaction_helpers.mouse_click_checkbox_child_in_panel( control=wrapper._target.source.control, index=convert_index( source=wrapper._target.source, - index=wrapper._target.location.index + index=wrapper._target.location.index, ), - delay=wrapper.delay))), + delay=wrapper.delay, + ) + ), + ), ] def convert_index(source, index): - """ Helper function to convert an index for a GridSizer so that the + """Helper function to convert an index for a GridSizer so that the index counts over the grid in the correct direction. The grid is always populated in row major order, however, the elements are assigned to each entry in the grid so that when displayed they appear @@ -68,7 +72,7 @@ def convert_index(source, index): def register(registry): - """ Register interactions for the given registry. + """Register interactions for the given registry. If there are any conflicts, an error will occur. diff --git a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/directory_editor.py b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/directory_editor.py index ab40738c8..51b94a258 100644 --- a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/directory_editor.py +++ b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/directory_editor.py @@ -15,7 +15,7 @@ def register(registry): - """ Register interactions for the given registry. + """Register interactions for the given registry. If there are any conflicts, an error will occur. diff --git a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/editor_factory.py b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/editor_factory.py index bf2a3a9c9..5fd0d93cb 100644 --- a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/editor_factory.py +++ b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/editor_factory.py @@ -17,7 +17,7 @@ def register(registry): - """ Register interactions for the given registry. + """Register interactions for the given registry. If there are any conflicts, an error will occur. @@ -34,7 +34,7 @@ def register(registry): registry.register_interaction( target_class=ReadonlyEditor, interaction_class=DisplayedText, - handler=lambda wrapper, _: - _interaction_helpers.readonly_textbox_displayed_text( - wrapper._target.control), + handler=lambda wrapper, _: _interaction_helpers.readonly_textbox_displayed_text( + wrapper._target.control + ), ) diff --git a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/enum_editor.py b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/enum_editor.py index 316f2e83f..b909bddd0 100644 --- a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/enum_editor.py +++ b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/enum_editor.py @@ -23,49 +23,57 @@ from traitsui.testing.tester.locator import Index from traitsui.testing.tester.query import DisplayedText, SelectedText from traitsui.testing.tester._ui_tester_registry._common_ui_targets import ( - BaseSourceWithLocation + BaseSourceWithLocation, ) from traitsui.testing.tester._ui_tester_registry.wx import _interaction_helpers from traitsui.testing.tester._ui_tester_registry._layout import ( - column_major_to_row_major + column_major_to_row_major, ) class _IndexedListEditor(BaseSourceWithLocation): - """ Wrapper class for EnumListEditor and Index. - """ + """Wrapper class for EnumListEditor and Index.""" + source_class = ListEditor locator_class = Index handlers = [ - (MouseClick, - (lambda wrapper, _: - _interaction_helpers.mouse_click_listbox( + ( + MouseClick, + ( + lambda wrapper, _: _interaction_helpers.mouse_click_listbox( control=wrapper._target.source.control, index=wrapper._target.location.index, - delay=wrapper.delay))), + delay=wrapper.delay, + ) + ), + ), ] class _IndexedRadioEditor(BaseSourceWithLocation): - """ Wrapper class for EnumRadioEditor and Index. - """ + """Wrapper class for EnumRadioEditor and Index.""" + source_class = RadioEditor locator_class = Index handlers = [ - (MouseClick, - (lambda wrapper, _: - _interaction_helpers.mouse_click_radiobutton_child_in_panel( + ( + MouseClick, + ( + lambda wrapper, _: _interaction_helpers.mouse_click_radiobutton_child_in_panel( control=wrapper._target.source.control, index=convert_index( source=wrapper._target.source, - index=wrapper._target.location.index + index=wrapper._target.location.index, ), - delay=wrapper.delay))), + delay=wrapper.delay, + ) + ), + ), ] def convert_index(source, index): - """ Helper function to convert an index for a GridSizer so that the + """Helper function to convert an index for a GridSizer so that the index counts over the grid in the correct direction. The grid is always populated in row major order, however, the elements are assigned to each entry in the grid so that when displayed they appear @@ -92,22 +100,26 @@ def convert_index(source, index): class _IndexedSimpleEditor(BaseSourceWithLocation): - """ Wrapper class for Simple EnumEditor and Index. - """ + """Wrapper class for Simple EnumEditor and Index.""" + source_class = SimpleEditor locator_class = Index handlers = [ - (MouseClick, - (lambda wrapper, _: - _interaction_helpers.mouse_click_combobox_or_choice( + ( + MouseClick, + ( + lambda wrapper, _: _interaction_helpers.mouse_click_combobox_or_choice( control=wrapper._target.source.control, index=wrapper._target.location.index, - delay=wrapper.delay))), + delay=wrapper.delay, + ) + ), + ), ] def simple_displayed_selected_text_handler(wrapper, interaction): - """ Handler function used to query DisplayedText for Simple Enum Editor. + """Handler function used to query DisplayedText for Simple Enum Editor. Note that depending on the factories evaluaute trait, the control for a Simple Enum Editor can either be a wx.ComboBox or a wx.Choice. @@ -127,7 +139,7 @@ def simple_displayed_selected_text_handler(wrapper, interaction): def radio_selected_text_handler(wrapper, interaction): - """ Handler function used to query SelectedText for EnumRadioEditor. + """Handler function used to query SelectedText for EnumRadioEditor. Parameters ---------- @@ -145,7 +157,7 @@ def radio_selected_text_handler(wrapper, interaction): def register(registry): - """ Registry location and interaction handlers for EnumEditor. + """Registry location and interaction handlers for EnumEditor. Parameters ---------- @@ -156,27 +168,35 @@ def register(registry): _IndexedSimpleEditor.register(registry) simple_editor_text_handlers = [ - (KeyClick, - (lambda wrapper, interaction: - _interaction_helpers.key_click_combobox( + ( + KeyClick, + ( + lambda wrapper, interaction: _interaction_helpers.key_click_combobox( control=wrapper._target.control, interaction=interaction, - delay=wrapper.delay))), - (KeySequence, - (lambda wrapper, interaction: - _interaction_helpers.key_sequence_text_ctrl( + delay=wrapper.delay, + ) + ), + ), + ( + KeySequence, + ( + lambda wrapper, interaction: _interaction_helpers.key_sequence_text_ctrl( control=wrapper._target.control, interaction=interaction, - delay=wrapper.delay))), + delay=wrapper.delay, + ) + ), + ), (DisplayedText, simple_displayed_selected_text_handler), - (SelectedText, simple_displayed_selected_text_handler) + (SelectedText, simple_displayed_selected_text_handler), ] for interaction_class, handler in simple_editor_text_handlers: registry.register_interaction( target_class=SimpleEditor, interaction_class=interaction_class, - handler=handler + handler=handler, ) registry.register_interaction( @@ -188,5 +208,6 @@ def register(registry): target_class=ListEditor, interaction_class=SelectedText, handler=lambda wrapper, _: wrapper._target.control.GetString( - wrapper._target.control.GetSelection()), + wrapper._target.control.GetSelection() + ), ) diff --git a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/file_editor.py b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/file_editor.py index 8c138e467..a6116c8ba 100644 --- a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/file_editor.py +++ b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/file_editor.py @@ -15,7 +15,7 @@ def register(registry): - """ Register interactions for the given registry. + """Register interactions for the given registry. If there are any conflicts, an error will occur. diff --git a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/font_editor.py b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/font_editor.py index 81fd42c2a..b07ff0b0c 100644 --- a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/font_editor.py +++ b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/font_editor.py @@ -15,7 +15,7 @@ def register(registry): - """ Register interactions pertaining to (wx) FontEditor for the given + """Register interactions pertaining to (wx) FontEditor for the given registry. Parameters diff --git a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/instance_editor.py b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/instance_editor.py index 0ecfab28b..d916c7197 100644 --- a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/instance_editor.py +++ b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/instance_editor.py @@ -12,22 +12,20 @@ from traitsui.testing.tester.locator import Index from traitsui.testing.tester.query import SelectedText from traitsui.testing.tester._ui_tester_registry._common_ui_targets import ( - BaseSourceWithLocation + BaseSourceWithLocation, ) from traitsui.testing.tester._ui_tester_registry._traitsui_ui import ( register_traitsui_ui_solvers, ) from traitsui.testing.tester._ui_tester_registry.wx._interaction_helpers import ( # noqa - mouse_click_combobox_or_choice, mouse_click_button -) -from traitsui.wx.instance_editor import ( - CustomEditor, - SimpleEditor + mouse_click_combobox_or_choice, + mouse_click_button, ) +from traitsui.wx.instance_editor import CustomEditor, SimpleEditor def _get_nested_ui_simple(target): - """ Obtains a nested UI within a Simple Instance Editor. + """Obtains a nested UI within a Simple Instance Editor. Parameters ---------- @@ -37,7 +35,7 @@ def _get_nested_ui_simple(target): def _get_nested_ui_custom(target): - """ Obtains a nested UI within a Custom Instance Editor. + """Obtains a nested UI within a Custom Instance Editor. Parameters ---------- @@ -47,7 +45,7 @@ def _get_nested_ui_custom(target): def _get_choice(target): - """ Obtains a nested choice within an Instance Editor. + """Obtains a nested choice within an Instance Editor. Parameters ---------- @@ -57,7 +55,7 @@ def _get_choice(target): def _click_choice_index(wrapper, _): - """ Perform a click on a choice based on the index. """ + """Perform a click on a choice based on the index.""" return mouse_click_combobox_or_choice( control=_get_choice(wrapper._target.source), index=wrapper._target.location.index, @@ -66,14 +64,14 @@ def _click_choice_index(wrapper, _): def _get_choice_text(wrapper, _): - """ Get the currently displayed text of a choice. """ + """Get the currently displayed text of a choice.""" control = _get_choice(wrapper._target) return control.GetString(control.GetSelection()) class _IndexedCustomEditor(BaseSourceWithLocation): - """ Wrapper class for CustomEditors with a selection. - """ + """Wrapper class for CustomEditors with a selection.""" + source_class = CustomEditor locator_class = Index handlers = [ @@ -82,7 +80,7 @@ class _IndexedCustomEditor(BaseSourceWithLocation): def register(registry): - """ Register interactions for the given registry. + """Register interactions for the given registry. If there are any conflicts, an error will occur. @@ -97,8 +95,9 @@ def register(registry): target_class=SimpleEditor, interaction_class=MouseClick, handler=lambda wrapper, _: mouse_click_button( - control=wrapper._target._button, delay=wrapper.delay, - ) + control=wrapper._target._button, + delay=wrapper.delay, + ), ) register_traitsui_ui_solvers(registry, SimpleEditor, _get_nested_ui_simple) diff --git a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/list_editor.py b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/list_editor.py index aea1f5e37..7f1c1f066 100644 --- a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/list_editor.py +++ b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/list_editor.py @@ -11,36 +11,36 @@ from traitsui.testing.tester.command import MouseClick from traitsui.testing.tester.locator import Index from traitsui.testing.tester._ui_tester_registry._common_ui_targets import ( - BaseSourceWithLocation + BaseSourceWithLocation, ) from traitsui.testing.tester._ui_tester_registry._traitsui_ui import ( register_traitsui_ui_solvers, ) from traitsui.testing.tester._ui_tester_registry.wx import _interaction_helpers -from traitsui.wx.list_editor import ( - CustomEditor, - NotebookEditor, - SimpleEditor -) +from traitsui.wx.list_editor import CustomEditor, NotebookEditor, SimpleEditor class _IndexedNotebookEditor(BaseSourceWithLocation): - """ Wrapper for a ListEditor (Notebook) with an index. - """ + """Wrapper for a ListEditor (Notebook) with an index.""" + source_class = NotebookEditor locator_class = Index handlers = [ - (MouseClick, - (lambda wrapper, _: - _interaction_helpers.mouse_click_notebook_tab_index( + ( + MouseClick, + ( + lambda wrapper, _: _interaction_helpers.mouse_click_notebook_tab_index( control=wrapper._target.source.control, index=wrapper._target.location.index, - delay=wrapper.delay))), + delay=wrapper.delay, + ) + ), + ), ] @classmethod def register(cls, registry): - """ Class method to register interactions on a _IndexedNotebookEditor + """Class method to register interactions on a _IndexedNotebookEditor for the given registry. If there are any conflicts, an error will occur. @@ -54,18 +54,18 @@ def register(cls, registry): register_traitsui_ui_solvers( registry=registry, target_class=cls, - traitsui_ui_getter=lambda target: target._get_nested_ui() + traitsui_ui_getter=lambda target: target._get_nested_ui(), ) def _get_nested_ui(self): - """ Method to get the nested ui corresponding to the List element at + """Method to get the nested ui corresponding to the List element at the given index. """ return self.source._uis[self.location.index][0].dockable.ui def _get_next_target(list_editor, index): - """ Gets the target at a given index from a Custom List Editor. + """Gets the target at a given index from a Custom List Editor. Parameters ---------- @@ -84,14 +84,14 @@ def _get_next_target(list_editor, index): # item itself. Thus, index is actually an index over the odd elements # of the list of children corresponding to items in the list we would # want to interact with - new_index = 2*index + 1 + new_index = 2 * index + 1 WindowList = list_editor.control.GetChildren() item = WindowList[new_index] return item._editor def register(registry): - """ Register interactions for the given registry. + """Register interactions for the given registry. If there are any conflicts, an error will occur. @@ -108,7 +108,7 @@ def register(registry): locator_class=Index, solver=lambda wrapper, location: ( _get_next_target(wrapper._target, location.index) - ) + ), ) # SimpleEditor registry.register_location( @@ -116,5 +116,5 @@ def register(registry): locator_class=Index, solver=lambda wrapper, location: ( _get_next_target(wrapper._target, location.index) - ) + ), ) diff --git a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/range_editor.py b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/range_editor.py index 8372d8f82..59e7dbe8b 100644 --- a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/range_editor.py +++ b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/range_editor.py @@ -19,12 +19,12 @@ from traitsui.testing.tester.locator import Slider, Textbox from traitsui.testing.tester._ui_tester_registry.wx import ( _interaction_helpers, - _registry_helper + _registry_helper, ) class LocatedTextbox: - """ Wrapper class for a located Textbox in Wx. + """Wrapper class for a located Textbox in Wx. Parameters ---------- @@ -36,7 +36,7 @@ def __init__(self, textbox): @classmethod def register(cls, registry): - """ Class method to register interactions on a LocatedTextbox for the + """Class method to register interactions on a LocatedTextbox for the given registry. If there are any conflicts, an error will occur. @@ -54,7 +54,7 @@ def register(cls, registry): class LocatedSlider: - """ Wrapper class for a located Textbox in Wx. + """Wrapper class for a located Textbox in Wx. Parameters ---------- @@ -66,7 +66,7 @@ def __init__(self, slider): @classmethod def register(cls, registry): - """ Class method to register interactions on a LocatedSlider for the + """Class method to register interactions on a LocatedSlider for the given registry. If there are any conflicts, an error will occur. @@ -79,14 +79,14 @@ def register(cls, registry): registry.register_interaction( target_class=cls, interaction_class=KeyClick, - handler=lambda wrapper, interaction: - _interaction_helpers.key_click_slider( - wrapper._target.slider, interaction, wrapper.delay) + handler=lambda wrapper, interaction: _interaction_helpers.key_click_slider( + wrapper._target.slider, interaction, wrapper.delay + ), ) def register(registry): - """ Register interactions for the given registry. + """Register interactions for the given registry. If there are any conflicts, an error will occur. @@ -96,21 +96,25 @@ def register(registry): The registry being registered to. """ - targets = [SimpleSliderEditor, - LogRangeSliderEditor, - LargeRangeSliderEditor] + targets = [ + SimpleSliderEditor, + LogRangeSliderEditor, + LargeRangeSliderEditor, + ] for target_class in targets: registry.register_location( target_class=target_class, locator_class=Textbox, solver=lambda wrapper, _: LocatedTextbox( - textbox=wrapper._target.control.text), + textbox=wrapper._target.control.text + ), ) registry.register_location( target_class=target_class, locator_class=Slider, solver=lambda wrapper, _: LocatedSlider( - slider=wrapper._target.control.slider), + slider=wrapper._target.control.slider + ), ) _registry_helper.register_editable_textbox_handlers( registry=registry, diff --git a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/text_editor.py b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/text_editor.py index 6991683a2..9aa8f1872 100644 --- a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/text_editor.py +++ b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/text_editor.py @@ -17,7 +17,7 @@ def register(registry): - """ Register interactions for the given registry. + """Register interactions for the given registry. If there are any conflicts, an error will occur. @@ -36,7 +36,7 @@ def register(registry): registry.register_interaction( target_class=ReadonlyEditor, interaction_class=DisplayedText, - handler=lambda wrapper, _: - _interaction_helpers.readonly_textbox_displayed_text( - wrapper._target.control), + handler=lambda wrapper, _: _interaction_helpers.readonly_textbox_displayed_text( + wrapper._target.control + ), ) diff --git a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/ui_base.py b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/ui_base.py index 2c90e6545..42a2a87e4 100644 --- a/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/ui_base.py +++ b/traitsui/testing/tester/_ui_tester_registry/wx/_traitsui/ui_base.py @@ -15,7 +15,7 @@ def register(registry): - """ Register solvers/handlers specific to wx Button Editors + """Register solvers/handlers specific to wx Button Editors for the given registry. If there are any conflicts, an error will occur. @@ -28,12 +28,15 @@ def register(registry): registry.register_interaction( target_class=ButtonEditor, interaction_class=MouseClick, - handler=(lambda wrapper, _: _interaction_helpers.mouse_click_button( - control=wrapper._target.control, delay=wrapper.delay)) + handler=( + lambda wrapper, _: _interaction_helpers.mouse_click_button( + control=wrapper._target.control, delay=wrapper.delay + ) + ), ) registry.register_interaction( target_class=ButtonEditor, interaction_class=DisplayedText, - handler=lambda wrapper, _: wrapper._target.control.GetLabel() + handler=lambda wrapper, _: wrapper._target.control.GetLabel(), ) diff --git a/traitsui/testing/tester/_ui_tester_registry/wx/default_registry.py b/traitsui/testing/tester/_ui_tester_registry/wx/default_registry.py index c88f991cf..abdf31257 100644 --- a/traitsui/testing/tester/_ui_tester_registry/wx/default_registry.py +++ b/traitsui/testing/tester/_ui_tester_registry/wx/default_registry.py @@ -28,7 +28,7 @@ def get_default_registries(): - """ Creates the default registries for UITester that are wx specific. + """Creates the default registries for UITester that are wx specific. Returns ------- diff --git a/traitsui/testing/tester/_ui_tester_registry/wx/tests/test_control_widget_registry.py b/traitsui/testing/tester/_ui_tester_registry/wx/tests/test_control_widget_registry.py index 61026efd6..3205cb058 100644 --- a/traitsui/testing/tester/_ui_tester_registry/wx/tests/test_control_widget_registry.py +++ b/traitsui/testing/tester/_ui_tester_registry/wx/tests/test_control_widget_registry.py @@ -30,13 +30,13 @@ if is_wx(): raise else: - from traitsui.testing.tester._ui_tester_registry.wx._control_widget_registry import ( # noqa: E501 + from traitsui.testing.tester._ui_tester_registry.wx._control_widget_registry import ( # noqa: E501 get_widget_registry, ) class TargetWithControl: - """ An object holding a control attribute.""" + """An object holding a control attribute.""" def __init__(self, control): self.control = control @@ -44,7 +44,6 @@ def __init__(self, control): @requires_toolkit([ToolkitName.wx]) class TestWxControlWidgetRegistry(unittest.TestCase): - def setUp(self): self.widget = wx.Window() self.registry = get_widget_registry() @@ -69,7 +68,7 @@ def test_is_invisible(self): def test_get_interactions_good_target(self): self.assertEqual( self.registry._get_interactions(self.target), - set([IsEnabled, IsVisible]) + set([IsEnabled, IsVisible]), ) def test_get_interactions_bad_target(self): diff --git a/traitsui/testing/tester/_ui_tester_registry/wx/tests/test_interaction_helpers.py b/traitsui/testing/tester/_ui_tester_registry/wx/tests/test_interaction_helpers.py index 4afd2361b..5cb92aa41 100644 --- a/traitsui/testing/tester/_ui_tester_registry/wx/tests/test_interaction_helpers.py +++ b/traitsui/testing/tester/_ui_tester_registry/wx/tests/test_interaction_helpers.py @@ -30,7 +30,6 @@ @requires_toolkit([ToolkitName.wx]) class TestInteractions(unittest.TestCase): - def setUp(self): self.frame = wx.Frame(None) self.frame.Show() @@ -75,7 +74,8 @@ def test_key_sequence(self): textbox.Bind(wx.EVT_TEXT, handler) _interaction_helpers.key_sequence_text_ctrl( - textbox, command.KeySequence("abc"), 0) + textbox, command.KeySequence("abc"), 0 + ) self.assertEqual(textbox.GetValue(), "123abc") self.assertEqual(handler.call_count, 3) @@ -120,7 +120,8 @@ def test_key_sequence_disabled(self): with self.assertRaises(Disabled): _interaction_helpers.key_sequence_text_ctrl( - textbox, command.KeySequence("abc"), 0) + textbox, command.KeySequence("abc"), 0 + ) def test_key_click(self): textbox = wx.TextCtrl(self.frame) @@ -128,7 +129,8 @@ def test_key_click(self): textbox.Bind(wx.EVT_TEXT, handler) _interaction_helpers.key_click_text_entry( - textbox, command.KeyClick("A"), 0) + textbox, command.KeyClick("A"), 0 + ) self.assertEqual(textbox.Value, "A") self.assertEqual(handler.call_count, 1) @@ -140,7 +142,8 @@ def test_key_click_backspace(self): textbox.Bind(wx.EVT_TEXT, handler) _interaction_helpers.key_click_text_entry( - textbox, command.KeyClick("Backspace"), 0) + textbox, command.KeyClick("Backspace"), 0 + ) self.assertEqual(textbox.Value, "") self.assertEqual(handler.call_count, 1) @@ -157,7 +160,8 @@ def test_key_click_backspace_with_selection(self): textbox.Bind(wx.EVT_TEXT, handler) _interaction_helpers.key_click_text_entry( - textbox, command.KeyClick("Backspace"), 0) + textbox, command.KeyClick("Backspace"), 0 + ) self.assertEqual(textbox.Value, "E") self.assertEqual(handler.call_count, 1) @@ -171,9 +175,11 @@ def test_key_click_end(self): self.assertEqual(textbox.GetInsertionPoint(), 0) _interaction_helpers.key_click_text_entry( - textbox, command.KeyClick("End"), 0) + textbox, command.KeyClick("End"), 0 + ) _interaction_helpers.key_click_text_entry( - textbox, command.KeyClick("F"), 0) + textbox, command.KeyClick("F"), 0 + ) self.assertEqual(textbox.Value, "ABCDEF") @@ -183,14 +189,16 @@ def test_key_click_disabled(self): with self.assertRaises(Disabled): _interaction_helpers.key_click_text_entry( - textbox, command.KeyClick("Enter"), 0) + textbox, command.KeyClick("Enter"), 0 + ) def test_key_click_slider_helpful_err(self): slider = wx.Slider() with self.assertRaises(ValueError) as exc: _interaction_helpers.key_click_slider( - slider, command.KeyClick("Enter"), 0) + slider, command.KeyClick("Enter"), 0 + ) self.assertIn( "['Down', 'Left', 'Page Down', 'Page Up', 'Right', 'Up']", - str(exc.exception) + str(exc.exception), ) diff --git a/traitsui/testing/tester/command.py b/traitsui/testing/tester/command.py index 6a9030997..cbf119722 100644 --- a/traitsui/testing/tester/command.py +++ b/traitsui/testing/tester/command.py @@ -17,18 +17,19 @@ class MouseClick: - """ An object representing the user clicking a mouse button. + """An object representing the user clicking a mouse button. Currently the left mouse button is assumed. In most circumstances, a widget can still be clicked on even if it is disabled. Therefore unlike key events, if the widget is disabled, implementations should not raise an exception. """ + pass class KeySequence: - """ An object representing the user typing a sequence of keys. + """An object representing the user typing a sequence of keys. Implementations should raise ``Disabled`` if the widget is disabled. @@ -44,7 +45,7 @@ def __init__(self, sequence): class KeyClick: - """ An object representing the user clicking a key on the keyboard. + """An object representing the user clicking a key on the keyboard. Implementations should raise ``Disabled`` if the widget is disabled. diff --git a/traitsui/testing/tester/exceptions.py b/traitsui/testing/tester/exceptions.py index 2a23654f0..56fb5db78 100644 --- a/traitsui/testing/tester/exceptions.py +++ b/traitsui/testing/tester/exceptions.py @@ -13,18 +13,19 @@ class TesterError(Exception): - """ Custom exception for UITester/UIWrapper. """ + """Custom exception for UITester/UIWrapper.""" + pass class Disabled(TesterError): - """ Raised when a simulation fails because the widget is disabled. - """ + """Raised when a simulation fails because the widget is disabled.""" + pass class InteractionNotSupported(TesterError): - """ Raised when an interaction is not supported by a wrapper. + """Raised when an interaction is not supported by a wrapper. Parameters ---------- @@ -51,7 +52,7 @@ def __str__(self): class LocationNotSupported(TesterError): - """ Raised when attempt to resolve a location on a UI fails + """Raised when attempt to resolve a location on a UI fails because the location type is not supported. """ diff --git a/traitsui/testing/tester/locator.py b/traitsui/testing/tester/locator.py index ea08e510c..febf25459 100644 --- a/traitsui/testing/tester/locator.py +++ b/traitsui/testing/tester/locator.py @@ -18,7 +18,7 @@ class Index: - """ A locator for locating a target that is uniquely specified by a single + """A locator for locating a target that is uniquely specified by a single 0-based index. Attributes @@ -32,34 +32,36 @@ def __init__(self, index): class TargetByName: - """ A locator for locating the next UI target using a name. + """A locator for locating the next UI target using a name. Attributes ---------- name : str """ + def __init__(self, name): self.name = name class TargetById: - """ A locator for locating the next UI target using an id. + """A locator for locating the next UI target using an id. Attributes ---------- id : str """ + def __init__(self, id): self.id = id class Slider: - """ A locator for locating a nested slider widget within a UI. - """ + """A locator for locating a nested slider widget within a UI.""" + pass class Textbox: - """ A locator for locating a nested textbox widget within a UI. - """ + """A locator for locating a nested textbox widget within a UI.""" + pass diff --git a/traitsui/testing/tester/query.py b/traitsui/testing/tester/query.py index ab0b1a5c1..7c441c7de 100644 --- a/traitsui/testing/tester/query.py +++ b/traitsui/testing/tester/query.py @@ -17,7 +17,7 @@ class SelectedText: - """ An object representing an interaction to obtain the displayed (echoed) + """An object representing an interaction to obtain the displayed (echoed) plain text which is currently selected. E.g. For a Enum List, with one entry currently selected, the displayed @@ -25,11 +25,12 @@ class SelectedText: Implementations should return a ``str``, or None if nothing is selected. """ + pass class DisplayedText: - """ An object representing an interaction to obtain the displayed (echoed) + """An object representing an interaction to obtain the displayed (echoed) plain text. E.g. For a textbox using a password styling, the displayed text should @@ -37,31 +38,35 @@ class DisplayedText: Implementations should return a ``str``. """ + pass class IsChecked: - """ An object representing an interaction to obtain whether a checkable + """An object representing an interaction to obtain whether a checkable widget (e.g. checkbox) is checked or not. Implementations should return True if checked and False if not. """ + pass class IsEnabled: - """ An object representing an interaction to obtain whether a widget is + """An object representing an interaction to obtain whether a widget is enabled or not. Implementations should return True if enabled and False if not. """ + pass class IsVisible: - """ An object representing an interaction to obtain whether a widget is + """An object representing an interaction to obtain whether a widget is visible or not. Implementations should return True if visible and False if not. """ + pass diff --git a/traitsui/testing/tester/target_registry.py b/traitsui/testing/tester/target_registry.py index 4619b775a..4e265a449 100644 --- a/traitsui/testing/tester/target_registry.py +++ b/traitsui/testing/tester/target_registry.py @@ -25,14 +25,14 @@ class _TargetToKeyRegistry: - """ Perform the mapping from target to a key to a callable. + """Perform the mapping from target to a key to a callable. Internally this is a dict(type, dict(type, callable)), but expose a few methods for better error reporting. """ def __init__(self, exception_maker): - """ Initializer + """Initializer Parameters ---------- @@ -65,7 +65,7 @@ def get_value(self, target_class, key): return action_to_handler[key] def get_keys(self, target_class): - """ Return all the keys for the given target. + """Return all the keys for the given target. Parameters ---------- @@ -80,7 +80,7 @@ def get_keys(self, target_class): class TargetRegistry(AbstractTargetRegistry): - """ An object for registering interaction and location resolution logic + """An object for registering interaction and location resolution logic for different UI target types. ``register_interaction`` supports extending ``UIWrapper.perform`` and @@ -116,7 +116,7 @@ def __init__(self): ) def register_interaction(self, target_class, interaction_class, handler): - """ Register a handler for a given target type and interaction type. + """Register a handler for a given target type and interaction type. Parameters ---------- @@ -141,7 +141,7 @@ def register_interaction(self, target_class, interaction_class, handler): ) def _get_handler(self, target, interaction): - """ Return a callable for handling an interaction for a given target. + """Return a callable for handling an interaction for a given target. Parameters ---------- @@ -167,7 +167,7 @@ def _get_handler(self, target, interaction): ) def _get_interactions(self, target): - """ Returns all the interactions supported for the given target. + """Returns all the interactions supported for the given target. Parameters ---------- @@ -184,7 +184,7 @@ def _get_interactions(self, target): ) def _get_interaction_doc(self, target, interaction_class): - """ Return the documentation for the given target and interaction type. + """Return the documentation for the given target and interaction type. Parameters ---------- @@ -211,7 +211,7 @@ def _get_interaction_doc(self, target, interaction_class): return inspect.getdoc(interaction_class) def register_location(self, target_class, locator_class, solver): - """ Register a solver for resolving the next UI target for the given + """Register a solver for resolving the next UI target for the given target type and locator type. Parameters @@ -237,7 +237,7 @@ def register_location(self, target_class, locator_class, solver): ) def _get_solver(self, target, location): - """ Return a callable registered for resolving a location for the + """Return a callable registered for resolving a location for the given target and location. Parameters @@ -258,7 +258,7 @@ def _get_solver(self, target, location): ) def _get_locations(self, target): - """ Returns all the location types supported for the given target. + """Returns all the location types supported for the given target. Parameters ---------- @@ -273,7 +273,7 @@ def _get_locations(self, target): return self._location_registry.get_keys(target_class=target.__class__) def _get_location_doc(self, target, locator_class): - """ Return the documentation for the given target and locator type. + """Return the documentation for the given target and locator type. Parameters ---------- diff --git a/traitsui/testing/tester/tests/test_registry.py b/traitsui/testing/tester/tests/test_registry.py index 415bab98a..a2e855b10 100644 --- a/traitsui/testing/tester/tests/test_registry.py +++ b/traitsui/testing/tester/tests/test_registry.py @@ -20,9 +20,7 @@ class TestInteractionRegistry(unittest.TestCase): - def test_registry_empty(self): - class SpecificTarget: pass @@ -92,7 +90,7 @@ def handler(wrapper, interaction): # then self.assertEqual( registry._get_interactions(SpecificEditor()), - {UserAction, UserAction2} + {UserAction, UserAction2}, ) def test_action_not_supported_report_supported_action(self): @@ -154,9 +152,9 @@ def test_error_get_interaction_doc(self): registry._get_interaction_doc(2.1, int) def test_get_default_interaction_doc(self): - class Action: """Some action.""" + pass def handler(wrapper, interaction): @@ -170,15 +168,14 @@ def handler(wrapper, interaction): ) actual = registry._get_interaction_doc( - target=21.2, interaction_class=Action, + target=21.2, + interaction_class=Action, ) self.assertEqual(actual, "Some action.") class TestLocationRegistry(unittest.TestCase): - def test_location_registry_empty(self): - class SpecificTarget: pass @@ -197,24 +194,24 @@ class Locator: ) def test_register_location(self): - def solver(wrapper, location): return 1 registry = TargetRegistry() registry.register_location( - target_class=float, locator_class=str, solver=solver) + target_class=float, locator_class=str, solver=solver + ) self.assertIs(registry._get_solver(2.1, "dummy"), solver) def test_register_location_report_existing(self): - def solver(wrapper, location): return 1 registry = TargetRegistry() registry.register_location( - target_class=float, locator_class=str, solver=solver) + target_class=float, locator_class=str, solver=solver + ) with self.assertRaises(LocationNotSupported) as exception_context: registry._get_solver(3.4, None) @@ -251,14 +248,13 @@ def solver(wrapper, location): # then self.assertEqual( - registry._get_locations(SpecificEditor()), - {Locator1, Locator2} + registry._get_locations(SpecificEditor()), {Locator1, Locator2} ) def test_get_location_help_default(self): - class Locator: - """ Some default documentation.""" + """Some default documentation.""" + pass registry = TargetRegistry() @@ -269,7 +265,8 @@ class Locator: ) help_text = registry._get_location_doc( - target=2.345, locator_class=Locator, + target=2.345, + locator_class=Locator, ) self.assertEqual(help_text, "Some default documentation.") diff --git a/traitsui/testing/tester/tests/test_ui_tester.py b/traitsui/testing/tester/tests/test_ui_tester.py index 5866a8610..02e1efa73 100644 --- a/traitsui/testing/tester/tests/test_ui_tester.py +++ b/traitsui/testing/tester/tests/test_ui_tester.py @@ -13,7 +13,10 @@ from pyface.api import GUI from traits.api import ( - Button, Instance, HasTraits, Str, + Button, + Instance, + HasTraits, + Str, ) from traitsui.api import Item, ModelView, View from traitsui.tests._tools import ( @@ -50,8 +53,7 @@ class SimpleApplication(ModelView): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestUITesterCreateUI(unittest.TestCase): - """ Test UITester.create_ui - """ + """Test UITester.create_ui""" def test_ui_disposed(self): tester = UITester() @@ -66,8 +68,9 @@ def test_create_ui_reraise_exception(self): order = Order() view = View(Item("submit_button")) - with self.assertRaises(RuntimeError), \ - self.assertLogs("traitsui", level="ERROR"): + with self.assertRaises(RuntimeError), self.assertLogs( + "traitsui", level="ERROR" + ): with tester.create_ui(order, dict(view=view)) as ui: @@ -99,7 +102,7 @@ def test_create_ui_respect_auto_process_events_flag(self): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestUITesterRegistry(unittest.TestCase): - """ Test maintaining registries.""" + """Test maintaining registries.""" def test_traitsui_registry_added(self): # Even if we have a custom registry list, the builtin TraitsUI @@ -127,7 +130,7 @@ def test_traitsui_registry_added(self): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestUITesterFindEditor(unittest.TestCase): - """ Test logic for finding a target.""" + """Test logic for finding a target.""" def test_interactor_found_if_editor_found(self): tester = UITester() @@ -136,7 +139,7 @@ def test_interactor_found_if_editor_found(self): wrapper = tester.find_by_name(ui, "submit_button") self.assertIsInstance(wrapper, UIWrapper) - expected, = ui.get_editors("submit_button") + (expected,) = ui.get_editors("submit_button") self.assertEqual(wrapper._target, expected) self.assertEqual( wrapper._registries, @@ -152,7 +155,8 @@ def test_no_editors_found(self): tester.find_by_name(ui, "submit_n_events") self.assertIn( - "No editors can be found", str(exception_context.exception), + "No editors can be found", + str(exception_context.exception), ) def test_multiple_editors_found(self): @@ -165,15 +169,16 @@ def test_multiple_editors_found(self): tester.find_by_name(ui, "submit_button") self.assertIn( - "Found multiple editors", str(exception_context.exception), + "Found multiple editors", + str(exception_context.exception), ) def test_delay_persisted(self): - tester = UITester(delay=.01) + tester = UITester(delay=0.01) view = View(Item("submit_button")) with tester.create_ui(Order(), dict(view=view)) as ui: wrapped = tester.find_by_name(ui, "submit_button") - self.assertEqual(wrapped.delay, .01) + self.assertEqual(wrapped.delay, 0.01) def test_find_by_id(self): tester = UITester(delay=123) @@ -213,7 +218,7 @@ def test_auto_process_events_skipped(self): class TestUITesterGuiFree(unittest.TestCase): - """ Test GUI free interface on UITester.""" + """Test GUI free interface on UITester.""" def test_auto_process_events_readonly(self): # auto_process_events can be inspected, but it cannot be changed. diff --git a/traitsui/testing/tester/tests/test_ui_wrapper.py b/traitsui/testing/tester/tests/test_ui_wrapper.py index eab688733..2b4201ba5 100644 --- a/traitsui/testing/tester/tests/test_ui_wrapper.py +++ b/traitsui/testing/tester/tests/test_ui_wrapper.py @@ -38,7 +38,7 @@ def example_ui_wrapper(**kwargs): - """ Return an instance of UIWrapper for testing purposes. + """Return an instance of UIWrapper for testing purposes. Parameters ---------- @@ -58,18 +58,17 @@ def example_ui_wrapper(**kwargs): class StubRegistry(AbstractTargetRegistry): - """ A stub implementation of the AbstractTargetRegistry for testing - """ + """A stub implementation of the AbstractTargetRegistry for testing""" def __init__( - self, - handler=None, - solver=None, - supported_interaction_classes=(), - supported_locator_classes=(), - interaction_doc="", - location_doc="", - ): + self, + handler=None, + solver=None, + supported_interaction_classes=(), + supported_locator_classes=(), + interaction_doc="", + location_doc="", + ): self.handler = handler self.solver = solver self.supported_interaction_classes = supported_interaction_classes @@ -111,8 +110,7 @@ def _get_location_doc(self, target, locator_class): # Use of perform/inspect requires the GUI event loop @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestUIWrapperInteractionRegistries(unittest.TestCase): - """ Test the logic regarding the order of (interaction) registries. - """ + """Test the logic regarding the order of (interaction) registries.""" def test_registry_priority(self): # If two registries have a handler for the same target and interaction @@ -134,9 +132,7 @@ def test_registry_priority(self): self.assertEqual(value, 2) # reverse order - wrapper = example_ui_wrapper( - registries=[registry1, registry2] - ) + wrapper = example_ui_wrapper(registries=[registry1, registry2]) value = wrapper.inspect("some other string") self.assertEqual(value, 1) @@ -182,7 +178,7 @@ def test_registry_all_declined(self): # Use of locate requires the GUI event loop @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestUIWrapperLocationRegistry(unittest.TestCase): - """ Test the use of registries with locate. """ + """Test the use of registries with locate.""" def test_location_registry_priority(self): registry1 = StubRegistry( @@ -254,20 +250,21 @@ def test_registry_all_declined(self): class TestUIWrapperHelp(unittest.TestCase): - """ Test calling UIWrapper.help """ + """Test calling UIWrapper.help""" def test_help_message(self): - class Action: - """ Say hello. + """Say hello. Say bye. """ + pass class Locator: - """ Return anything you like. + """Return anything you like. Good day! """ + pass registry1 = TargetRegistry() @@ -295,7 +292,8 @@ class Locator: # then self.assertEqual( stream.getvalue(), - textwrap.dedent(f"""\ + textwrap.dedent( + f"""\ Interactions ------------ {Action!r} @@ -308,7 +306,8 @@ class Locator: Return anything you like. Good day! - """) + """ + ), ) def test_help_message_priority_interactions(self): @@ -343,7 +342,8 @@ def test_help_message_priority_interactions(self): # then self.assertEqual( stream.getvalue(), - textwrap.dedent(f"""\ + textwrap.dedent( + f"""\ Interactions ------------ {float!r} @@ -354,7 +354,8 @@ def test_help_message_priority_interactions(self): {str!r} Location: I get a higher priority. - """) + """ + ), ) def test_help_message_nothing_is_supported(self): @@ -369,7 +370,8 @@ def test_help_message_nothing_is_supported(self): # then self.assertEqual( stream.getvalue(), - textwrap.dedent("""\ + textwrap.dedent( + """\ Interactions ------------ No interactions are supported. @@ -378,7 +380,8 @@ def test_help_message_nothing_is_supported(self): --------- No locations are supported. - """) + """ + ), ) @@ -388,7 +391,7 @@ class NumberHasTraits(HasTraits): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestUIWrapperEventProcessed(unittest.TestCase, UnittestTools): - """ Test GUI events are processed and exceptions from the GUI event + """Test GUI events are processed and exceptions from the GUI event loop are handled. """ diff --git a/traitsui/testing/tester/ui_tester.py b/traitsui/testing/tester/ui_tester.py index c782754f6..eb7dee151 100644 --- a/traitsui/testing/tester/ui_tester.py +++ b/traitsui/testing/tester/ui_tester.py @@ -16,13 +16,13 @@ from traitsui.testing._gui import process_cascade_events from traitsui.testing._exception_handling import reraise_exceptions from traitsui.testing.tester._ui_tester_registry.default_registry import ( - get_default_registries + get_default_registries, ) from traitsui.testing.tester.ui_wrapper import UIWrapper class UITester: - """ UITester assists testing of GUI applications developed using TraitsUI. + """UITester assists testing of GUI applications developed using TraitsUI. See :ref:`testing-traitsui-applications` Section in the User Manual for further details. @@ -68,7 +68,7 @@ def __init__(self, *, registries=None, delay=0, auto_process_events=True): @property def auto_process_events(self): - """ Flag to indicate whether to process (cascade) GUI events + """Flag to indicate whether to process (cascade) GUI events automatically. This is propagated through to :class:`~traitsui.testing.tester.ui_wrapper.UIWrapper` instances created from this tester. @@ -82,7 +82,7 @@ def auto_process_events(self): @contextlib.contextmanager def create_ui(self, object, ui_kwargs=None): - """ Context manager to create a UI and dispose it upon exit. + """Context manager to create a UI and dispose it upon exit. This method does not modify the states of the :class:`UITester` and is not a requirement for using other methods on the tester. @@ -123,7 +123,7 @@ def create_ui(self, object, ui_kwargs=None): process_cascade_events() def find_by_name(self, ui, name): - """ Find the TraitsUI editor with the given name and return a new + """Find the TraitsUI editor with the given name and return a new ``UIWrapper`` object for further interactions with the editor. ``name`` is typically a value defined on @@ -144,7 +144,7 @@ def find_by_name(self, ui, name): return self._get_wrapper(ui).find_by_name(name=name) def find_by_id(self, ui, id): - """ Find the TraitsUI editor with the given identifier and return a new + """Find the TraitsUI editor with the given identifier and return a new ``UIWrapper`` object for further interactions with the editor. ``id`` is typically a value defined on :attr:`traitsui.item.Item.id` @@ -165,7 +165,7 @@ def find_by_id(self, ui, id): return self._get_wrapper(ui).find_by_id(id=id) def _get_wrapper(self, ui): - """ Return a new UIWrapper wrapping the given traitsui.ui.UI. + """Return a new UIWrapper wrapping the given traitsui.ui.UI. Parameters ---------- diff --git a/traitsui/testing/tester/ui_wrapper.py b/traitsui/testing/tester/ui_wrapper.py index bc338cc08..9702f3e0f 100644 --- a/traitsui/testing/tester/ui_wrapper.py +++ b/traitsui/testing/tester/ui_wrapper.py @@ -83,14 +83,15 @@ class UIWrapper: """ def __init__( - self, target, *, registries, delay=0, auto_process_events=True): + self, target, *, registries, delay=0, auto_process_events=True + ): self._target = target self._registries = registries self._auto_process_events = auto_process_events self.delay = delay def help(self): - """ Print help messages. + """Print help messages. (This function is intended for interactive use.) """ # mapping from interaction types to their documentation @@ -133,9 +134,7 @@ def help(self): for locator_type in sorted(location_to_doc, key=repr): print(repr(locator_type)) print( - textwrap.indent( - location_to_doc[locator_type], prefix=" " - ) + textwrap.indent(location_to_doc[locator_type], prefix=" ") ) print() @@ -144,7 +143,7 @@ def help(self): print() def locate(self, location): - """ Attempt to resolve the given location and return a new + """Attempt to resolve the given location and return a new UIWrapper. Parameters @@ -175,7 +174,7 @@ def locate(self, location): ) def find_by_name(self, name): - """ Find a target inside the current target using a name. + """Find a target inside the current target using a name. This is equivalent to calling ``locate(TargetByName(name=name))``. @@ -201,7 +200,7 @@ def find_by_name(self, name): return self.locate(locator.TargetByName(name=name)) def find_by_id(self, id): - """ Find a target inside the current target using an id. + """Find a target inside the current target using an id. This is equivalent to calling ``locate(TargetById(id=id))``. @@ -227,7 +226,7 @@ def find_by_id(self, id): return self.locate(locator.TargetById(id=id)) def perform(self, interaction): - """ Perform a user interaction that causes side effects. + """Perform a user interaction that causes side effects. Parameters ---------- @@ -248,7 +247,7 @@ def perform(self, interaction): self._perform_or_inspect(interaction) def inspect(self, interaction): - """ Return a value or values for inspection. + """Return a value or values for inspection. Parameters ---------- @@ -277,7 +276,7 @@ def inspect(self, interaction): # Private methods ######################################################### def _perform_or_inspect(self, interaction): - """ Perform a user interaction or a user inspection. + """Perform a user interaction or a user inspection. Parameters ---------- @@ -306,7 +305,8 @@ def _perform_or_inspect(self, interaction): continue else: context = ( - _event_processed if self._auto_process_events + _event_processed + if self._auto_process_events else _nullcontext ) with context(): @@ -319,7 +319,7 @@ def _perform_or_inspect(self, interaction): ) def _get_next_target(self, location): - """ Return the next UI target from the given location. + """Return the next UI target from the given location. Parameters ---------- @@ -360,7 +360,7 @@ def _get_next_target(self, location): @contextmanager def _event_processed(): - """ Context manager to ensure GUI events are processed upon entering + """Context manager to ensure GUI events are processed upon entering and exiting the context. """ with _reraise_exceptions(): @@ -373,5 +373,5 @@ def _event_processed(): @contextmanager def _nullcontext(): - """ Equivalent to contextlib.nullcontext() in Python >= 3.7""" + """Equivalent to contextlib.nullcontext() in Python >= 3.7""" yield diff --git a/traitsui/testing/tests/test_api.py b/traitsui/testing/tests/test_api.py index a6966e02f..f35a7cbb4 100644 --- a/traitsui/testing/tests/test_api.py +++ b/traitsui/testing/tests/test_api.py @@ -14,7 +14,6 @@ class TestApi(unittest.TestCase): - def test_tester_import(self): from traitsui.testing.api import UITester # noqa: F401 diff --git a/traitsui/testing/tests/test_exception_handling.py b/traitsui/testing/tests/test_exception_handling.py index c66d2dfbc..33705bf6b 100644 --- a/traitsui/testing/tests/test_exception_handling.py +++ b/traitsui/testing/tests/test_exception_handling.py @@ -22,10 +22,8 @@ class TestExceptionHandling(unittest.TestCase): - @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) def test_error_from_gui_captured_and_raise(self): - def raise_error_1(): raise ZeroDivisionError() @@ -38,8 +36,9 @@ def raise_error_2(): # - with Wx, the traceback is printed and the test passes. # With the context manager, the exception is always reraised. gui = GUI() - with self.assertRaises(RuntimeError) as exception_context, \ - self.assertLogs("traitsui") as watcher: + with self.assertRaises( + RuntimeError + ) as exception_context, self.assertLogs("traitsui") as watcher: with reraise_exceptions(): gui.invoke_later(raise_error_1) gui.invoke_later(raise_error_2) diff --git a/traitsui/testing/tests/test_gui.py b/traitsui/testing/tests/test_gui.py index b971c8528..72555811c 100644 --- a/traitsui/testing/tests/test_gui.py +++ b/traitsui/testing/tests/test_gui.py @@ -33,7 +33,6 @@ from pyface.qt import QtCore class DummyQObject(QtCore.QObject): - def __init__(self, max_n_events): super().__init__() self.max_n_events = max_n_events @@ -62,7 +61,6 @@ def event(self, event): NewEvent, EVT_SOME_NEW_EVENT = wx.lib.newevent.NewEvent() class DummyWxHandler(wx.EvtHandler): - def __init__(self, max_n_events): super().__init__() self.max_n_events = max_n_events @@ -80,7 +78,7 @@ def post_event(self): class TestProcessEventsRepeated(unittest.TestCase): - """ Test process_events actually processes all events, including the events + """Test process_events actually processes all events, including the events posted by the processed events. """ @@ -160,7 +158,6 @@ def cleanup(q_object): @requires_toolkit([ToolkitName.wx]) def test_wx_process_events_process_all(self): - def cleanup(wx_handler): # In case of test failure, always flush the GUI event queue. GUI.process_events() diff --git a/traitsui/tests/_tools.py b/traitsui/tests/_tools.py index 42e127b9d..4f9ecd88d 100644 --- a/traitsui/tests/_tools.py +++ b/traitsui/tests/_tools.py @@ -38,37 +38,36 @@ class ToolkitName(enum.Enum): def is_wx(): - """ Return true if the toolkit backend is wx. """ + """Return true if the toolkit backend is wx.""" return ETSConfig.toolkit == ToolkitName.wx.name def is_qt(): - """ Return true if the toolkit backend is Qt + """Return true if the toolkit backend is Qt (that includes Qt4 or Qt5, etc.) """ return ETSConfig.toolkit.startswith(ToolkitName.qt.name) def is_qt5(): - """ Return true if the toolkit backend is Qt5. - """ + """Return true if the toolkit backend is Qt5.""" if not is_qt(): return False # Only AFTER confirming Qt's availability... # We lean on Pyface here since the check is complicated. import pyface.qt + return pyface.qt.is_qt5 def is_null(): - """ Return true if the toolkit backend is null. - """ + """Return true if the toolkit backend is null.""" return ETSConfig.toolkit == ToolkitName.null.name def requires_toolkit(toolkits): - """ Decorator factory for skipping tests if the current toolkit is not + """Decorator factory for skipping tests if the current toolkit is not one of the given values. Parameters @@ -83,7 +82,7 @@ def requires_toolkit(toolkits): } return skipIf( not any(mapping[toolkit]() for toolkit in toolkits), - "Test requires one of these toolkits: {}".format(toolkits) + "Test requires one of these toolkits: {}".format(toolkits), ) @@ -124,7 +123,7 @@ def filter_tests(test_suite, exclusion_pattern): def create_ui(object, ui_kwargs=None): - """ Context manager for creating a UI and then dispose it when exiting + """Context manager for creating a UI and then dispose it when exiting the context. Parameters @@ -243,12 +242,12 @@ def get_all_button_status(control): return button_status + # ######### Debug tools def apply_on_children(func, node, _level=0): - """Print the result of applying a function on `node` and its children. - """ + """Print the result of applying a function on `node` and its children.""" print("-" * _level + str(node)) print(" " * _level + str(func(node)) + "\n") for child in get_children(node): @@ -329,7 +328,7 @@ class GuiTestAssistant(object): class BaseTestMixin: - """ This is a mixin class for all test cases in TraitsUI, regardless of + """This is a mixin class for all test cases in TraitsUI, regardless of whether GUI is involved. Not to be used externally. diff --git a/traitsui/tests/editors/test_animatedGIF_editor.py b/traitsui/tests/editors/test_animatedGIF_editor.py index 0f9135c0e..651181cc9 100644 --- a/traitsui/tests/editors/test_animatedGIF_editor.py +++ b/traitsui/tests/editors/test_animatedGIF_editor.py @@ -36,7 +36,6 @@ class AnimatedGIF(HasTraits): @requires_toolkit([ToolkitName.wx]) class TestAnimatedGIFEditor(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -45,6 +44,7 @@ def tearDown(self): def test_animated_gif_editor(self): from traitsui.wx.animated_gif_editor import AnimatedGIFEditor + # Regression test for enthought/traitsui#1071 obj1 = AnimatedGIF() view = View( diff --git a/traitsui/tests/editors/test_boolean_editor.py b/traitsui/tests/editors/test_boolean_editor.py index 780012616..0fe9dcbc5 100644 --- a/traitsui/tests/editors/test_boolean_editor.py +++ b/traitsui/tests/editors/test_boolean_editor.py @@ -19,7 +19,12 @@ ) from traitsui.testing.api import ( - DisplayedText, IsChecked, KeyClick, KeySequence, MouseClick, UITester + DisplayedText, + IsChecked, + KeyClick, + KeySequence, + MouseClick, + UITester, ) @@ -32,7 +37,6 @@ class BoolModel(HasTraits): # BooleanEditor @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestBooleanEditor(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) diff --git a/traitsui/tests/editors/test_button_editor.py b/traitsui/tests/editors/test_button_editor.py index 6c2ae5928..748def922 100644 --- a/traitsui/tests/editors/test_button_editor.py +++ b/traitsui/tests/editors/test_button_editor.py @@ -23,12 +23,7 @@ reraise_exceptions, ToolkitName, ) -from traitsui.testing.api import ( - DisplayedText, - IsEnabled, - MouseClick, - UITester -) +from traitsui.testing.api import DisplayedText, IsEnabled, MouseClick, UITester class ButtonTextEdit(HasTraits): @@ -37,9 +32,7 @@ class ButtonTextEdit(HasTraits): play_button_label = Str("I'm a play button") - play_button_image = Image( - ImageResource("run", [traitsui.extras]) - ) + play_button_image = Image(ImageResource("run", [traitsui.extras])) values = List() @@ -77,7 +70,6 @@ class ButtonTextEdit(HasTraits): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestButtonEditor(BaseTestMixin, unittest.TestCase, UnittestTools): - def setUp(self): BaseTestMixin.setUp(self) @@ -119,7 +111,8 @@ def check_button_fired_event(self, view): button = tester.find_by_name(ui, "play_button") with self.assertTraitChanges( - button_text_edit, "play_button", count=1): + button_text_edit, "play_button", count=1 + ): button.perform(MouseClick()) def test_simple_button_editor_clicked(self): @@ -147,13 +140,15 @@ def check_button_disabled(self, style): self.assertFalse(button.inspect(IsEnabled())) with self.assertTraitDoesNotChange( - button_text_edit, "play_button"): + button_text_edit, "play_button" + ): button.perform(MouseClick()) button_text_edit.button_enabled = True self.assertTrue(button.inspect(IsEnabled())) with self.assertTraitChanges( - button_text_edit, "play_button", count=1): + button_text_edit, "play_button", count=1 + ): button.perform(MouseClick()) def test_simple_button_editor_disabled(self): @@ -166,8 +161,9 @@ def test_custom_image_value(self): button_text_edit = ButtonTextEdit() tester = UITester() - with tester.create_ui(button_text_edit, dict(view=custom_image_view)) \ - as ui: + with tester.create_ui( + button_text_edit, dict(view=custom_image_view) + ) as ui: button = tester.find_by_name(ui, "play_button") default_image = button._target.image self.assertIsInstance(default_image, ImageResource) @@ -181,7 +177,7 @@ def test_custom_image_value(self): @requires_toolkit([ToolkitName.qt]) class TestButtonEditorValuesTrait(BaseTestMixin, unittest.TestCase): - """ The values_trait is only supported by Qt. + """The values_trait is only supported by Qt. See discussion enthought/traitsui#879 """ diff --git a/traitsui/tests/editors/test_check_list_editor.py b/traitsui/tests/editors/test_check_list_editor.py index 56a690d57..5b4d3d2d6 100644 --- a/traitsui/tests/editors/test_check_list_editor.py +++ b/traitsui/tests/editors/test_check_list_editor.py @@ -24,11 +24,7 @@ reraise_exceptions, ToolkitName, ) -from traitsui.testing.api import ( - Index, - MouseClick, - UITester -) +from traitsui.testing.api import Index, MouseClick, UITester class ListModel(HasTraits): @@ -45,7 +41,7 @@ def get_view(style): ), style=style, ), - resizable=True + resizable=True, ) @@ -59,7 +55,7 @@ def get_view_custom_cols(cols): ), style="custom", ), - resizable=True + resizable=True, ) @@ -72,12 +68,12 @@ def get_mapped_view(style): ), style=style, ), - resizable=True + resizable=True, ) def get_combobox_text(combobox): - """ Return the text given a combobox control. """ + """Return the text given a combobox control.""" if is_wx(): return combobox.GetString(combobox.GetSelection()) @@ -89,8 +85,8 @@ def get_combobox_text(combobox): def set_combobox_index(editor, idx): - """ Set the choice index of a combobox control given editor and index - number. """ + """Set the choice index of a combobox control given editor and index + number.""" if is_wx(): import wx @@ -111,7 +107,7 @@ def set_combobox_index(editor, idx): def set_text_in_line_edit(line_edit, text): - """ Set text in text widget and complete editing. """ + """Set text in text widget and complete editing.""" if is_wx(): import wx @@ -129,7 +125,6 @@ def set_text_in_line_edit(line_edit, text): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestCheckListEditorMapping(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -155,8 +150,9 @@ def check_checklist_mappings_value_change(self, style): ) model = ListModel() - with reraise_exceptions(), \ - self.setup_ui(model, formatted_view) as editor: + with reraise_exceptions(), self.setup_ui( + model, formatted_view + ) as editor: self.assertEqual(editor.names, ["ONE", "TWO"]) @@ -178,8 +174,9 @@ def check_checklist_mappings_tuple_value_change(self, style): ) model = ListModel() - with reraise_exceptions(), \ - self.setup_ui(model, formatted_view) as editor: + with reraise_exceptions(), self.setup_ui( + model, formatted_view + ) as editor: # FIXME issue enthought/traitsui#841 with self.assertRaises(AssertionError): @@ -211,8 +208,9 @@ class ListModel(HasTraits): ) model = ListModel() - with reraise_exceptions(), \ - self.setup_ui(model, formatted_view) as editor: + with reraise_exceptions(), self.setup_ui( + model, formatted_view + ) as editor: self.assertEqual(editor.names, ["ONE", "TWO"]) @@ -238,8 +236,9 @@ class ListModel(HasTraits): ) model = ListModel() - with reraise_exceptions(), \ - self.setup_ui(model, formatted_view) as editor: + with reraise_exceptions(), self.setup_ui( + model, formatted_view + ) as editor: # FIXME issue enthought/traitsui#841 with self.assertRaises(AssertionError): @@ -339,7 +338,6 @@ def test_custom_editor_checklist_values_change_dispose(self): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestSimpleCheckListEditor(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -356,8 +354,9 @@ def setup_gui(self, model, view): def test_simple_check_list_editor_text(self): list_edit = ListModel(value=["one"]) - with reraise_exceptions(), \ - self.setup_gui(list_edit, get_view("simple")) as editor: + with reraise_exceptions(), self.setup_gui( + list_edit, get_view("simple") + ) as editor: self.assertEqual(get_combobox_text(editor.control), "One") @@ -370,8 +369,7 @@ def test_simple_check_list_editor_text_mapped(self): view = get_mapped_view("simple") list_edit = ListModel(value=[1]) - with reraise_exceptions(), \ - self.setup_gui(list_edit, view) as editor: + with reraise_exceptions(), self.setup_gui(list_edit, view) as editor: # FIXME issue enthought/traitsui#841 with self.assertRaises(AssertionError): @@ -389,8 +387,9 @@ def test_simple_check_list_editor_text_mapped(self): def test_simple_check_list_editor_index(self): list_edit = ListModel(value=["one"]) - with reraise_exceptions(), \ - self.setup_gui(list_edit, get_view("simple")) as editor: + with reraise_exceptions(), self.setup_gui( + list_edit, get_view("simple") + ) as editor: self.assertEqual(list_edit.value, ["one"]) @@ -407,8 +406,9 @@ def test_simple_check_list_editor_index(self): def test_simple_check_list_editor_invalid_current_values(self): list_edit = ListModel(value=[1, "two", "a", object(), "one"]) - with reraise_exceptions(), \ - self.setup_gui(list_edit, get_view("simple")): + with reraise_exceptions(), self.setup_gui( + list_edit, get_view("simple") + ): self.assertEqual(list_edit.value, ["two", "one"]) @@ -418,15 +418,15 @@ class StrModel(HasTraits): str_edit = StrModel(value="alpha, \ttwo, beta,\n lambda, one") - with reraise_exceptions(), \ - self.setup_gui(str_edit, get_view("simple")): + with reraise_exceptions(), self.setup_gui( + str_edit, get_view("simple") + ): self.assertEqual(str_edit.value, "two,one") @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestCustomCheckListEditor(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -443,12 +443,13 @@ def setup_gui(self, model, view): def test_custom_check_list_editor_button_update(self): list_edit = ListModel() - with reraise_exceptions(), \ - self.setup_gui(list_edit, get_view("custom")) as editor: + with reraise_exceptions(), self.setup_gui( + list_edit, get_view("custom") + ) as editor: self.assertEqual( get_all_button_status(editor.control), - [False, False, False, False] + [False, False, False, False], ) list_edit.value = ["two", "four"] @@ -456,7 +457,7 @@ def test_custom_check_list_editor_button_update(self): self.assertEqual( get_all_button_status(editor.control), - [False, True, False, True] + [False, True, False, True], ) list_edit.value = ["one", "four"] @@ -464,7 +465,7 @@ def test_custom_check_list_editor_button_update(self): self.assertEqual( get_all_button_status(editor.control), - [True, False, False, True] + [True, False, False, True], ) def test_custom_check_list_editor_click(self): @@ -527,7 +528,6 @@ def test_custom_check_list_editor_grid_layout(self): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestTextCheckListEditor(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -545,8 +545,9 @@ def setup_gui(self, model, view): def test_text_check_list_object_list(self): list_edit = ListModel() - with reraise_exceptions(), \ - self.setup_gui(list_edit, get_view("text")) as editor: + with reraise_exceptions(), self.setup_gui( + list_edit, get_view("text") + ) as editor: self.assertEqual(list_edit.value, []) @@ -561,8 +562,9 @@ class StrModel(HasTraits): str_edit = StrModel(value="three, four") - with reraise_exceptions(), \ - self.setup_gui(str_edit, get_view("text")) as editor: + with reraise_exceptions(), self.setup_gui( + str_edit, get_view("text") + ) as editor: self.assertEqual(str_edit.value, "three, four") diff --git a/traitsui/tests/editors/test_code_editor.py b/traitsui/tests/editors/test_code_editor.py index 59dbdb421..c9400dc6e 100644 --- a/traitsui/tests/editors/test_code_editor.py +++ b/traitsui/tests/editors/test_code_editor.py @@ -48,7 +48,6 @@ def default_traits_view(self): class TestCodeEditor(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -57,8 +56,7 @@ def tearDown(self): @requires_toolkit([ToolkitName.qt]) def test_code_editor_show_line_numbers(self): - """ CodeEditor should honor the `show_line_numbers` setting - """ + """CodeEditor should honor the `show_line_numbers` setting""" def is_line_numbers_visible(ui): from pyface import qt @@ -78,8 +76,7 @@ def test_line_numbers_visibility(show=True): @requires_toolkit([ToolkitName.qt]) def test_code_editor_readonly(self): - """ Test readonly editor style for CodeEditor - """ + """Test readonly editor style for CodeEditor""" from pyface import qt code_model = CodeModel() diff --git a/traitsui/tests/editors/test_csv_editor.py b/traitsui/tests/editors/test_csv_editor.py index 4b5facbbc..7fb738114 100644 --- a/traitsui/tests/editors/test_csv_editor.py +++ b/traitsui/tests/editors/test_csv_editor.py @@ -44,7 +44,6 @@ class ListOfFloatsWithCSVEditor(ModelView): class TestCSVEditor(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) diff --git a/traitsui/tests/editors/test_date_editor.py b/traitsui/tests/editors/test_date_editor.py index e638236a8..f01c8fcae 100644 --- a/traitsui/tests/editors/test_date_editor.py +++ b/traitsui/tests/editors/test_date_editor.py @@ -68,7 +68,6 @@ def multi_select_selected_color_view(): @requires_toolkit([ToolkitName.qt]) class TestDateEditorCustomQt(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -129,7 +128,7 @@ def test_custom_selected_color(self): def launch_editor(self, view_factory): foo = Foo() with create_ui(foo, dict(view=view_factory())) as ui: - editor, = ui._editors + (editor,) = ui._editors yield foo, editor def check_select_status(self, editor, date, selected): @@ -183,11 +182,10 @@ def check_date_bgcolor(self, editor, date, expected): # Run this test case against wx too once enthought/traitsui#752 is fixed. @requires_toolkit([ToolkitName.qt]) class TestDateEditorInitDispose(unittest.TestCase): - """ Test the init and dispose of date editor.""" + """Test the init and dispose of date editor.""" def check_init_and_dispose(self, view): - with reraise_exceptions(), \ - create_ui(Foo(), dict(view=view)): + with reraise_exceptions(), create_ui(Foo(), dict(view=view)): pass def test_simple_date_editor(self): diff --git a/traitsui/tests/editors/test_date_range_editor.py b/traitsui/tests/editors/test_date_range_editor.py index 7eed504c1..41aa5099f 100644 --- a/traitsui/tests/editors/test_date_range_editor.py +++ b/traitsui/tests/editors/test_date_range_editor.py @@ -34,7 +34,7 @@ class Foo(HasTraits): def default_custom_view(): - """ Default view of DateRangeEditor """ + """Default view of DateRangeEditor""" view = View( Item(name="date_range", style="custom", editor=DateRangeEditor()) ) @@ -42,7 +42,7 @@ def default_custom_view(): def custom_view_allow_no_range(): - """ DateRangeEditor with allow_no_selection set to True.""" + """DateRangeEditor with allow_no_selection set to True.""" view = View( Item( name="date_range", @@ -54,7 +54,7 @@ def custom_view_allow_no_range(): class TestDateRangeEditorGeneric(BaseTestMixin, unittest.TestCase): - """ Tests that are not GUI backend specific.""" + """Tests that are not GUI backend specific.""" def setUp(self): BaseTestMixin.setUp(self) @@ -69,7 +69,6 @@ def test_date_range_multi_select_is_constant(self): @requires_toolkit([ToolkitName.qt]) class TestDateRangeEditorQt(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -228,7 +227,7 @@ def test_allow_no_range(self): def launch_editor(self, view_factory): foo = Foo() with create_ui(foo, dict(view=view_factory())) as ui: - editor, = ui._editors + (editor,) = ui._editors yield foo, editor def check_select_status(self, editor, date, selected): diff --git a/traitsui/tests/editors/test_datetime_editor.py b/traitsui/tests/editors/test_datetime_editor.py index dd1d4a4bc..f4fcc87ab 100644 --- a/traitsui/tests/editors/test_datetime_editor.py +++ b/traitsui/tests/editors/test_datetime_editor.py @@ -27,7 +27,8 @@ class InstanceWithDatetime(HasTraits): - """ Demo class to show Datetime editors. """ + """Demo class to show Datetime editors.""" + date_time = Datetime() @@ -52,7 +53,7 @@ def get_date_time_simple_view(editor_factory): @requires_toolkit([ToolkitName.qt]) @unittest.skipIf(no_gui_test_assistant, "No GuiTestAssistant") class TestDatetimeEditorQt(BaseTestMixin, GuiTestAssistant, unittest.TestCase): - """ Tests for DatetimeEditor using Qt. """ + """Tests for DatetimeEditor using Qt.""" def setUp(self): BaseTestMixin.setUp(self) @@ -66,8 +67,7 @@ def test_datetime_editor_simple(self): view = get_date_time_simple_view(DatetimeEditor()) date_time = datetime.datetime(2000, 1, 2, 1, 2, 3) instance = InstanceWithDatetime(date_time=date_time) - with reraise_exceptions(), \ - self.launch_editor(instance, view): + with reraise_exceptions(), self.launch_editor(instance, view): pass def test_datetime_editor_simple_with_minimum_datetime(self): @@ -78,8 +78,9 @@ def test_datetime_editor_simple_with_minimum_datetime(self): ) view = get_date_time_simple_view(editor_factory) instance = InstanceWithDatetime() - with reraise_exceptions(), \ - self.launch_editor(instance, view) as editor: + with reraise_exceptions(), self.launch_editor( + instance, view + ) as editor: q_minimum_datetime = editor.control.minimumDateTime() actual_minimum_datetime = to_datetime(q_minimum_datetime) @@ -94,8 +95,9 @@ def test_datetime_editor_simple_with_minimum_datetime_out_of_bound(self): ) view = get_date_time_simple_view(editor_factory) instance = InstanceWithDatetime() - with reraise_exceptions(), \ - self.launch_editor(instance, view) as editor: + with reraise_exceptions(), self.launch_editor( + instance, view + ) as editor: instance.date_time = datetime.datetime(1980, 1, 1) # does not seem needed to flush the event loop, but just in case. @@ -114,8 +116,9 @@ def test_datetime_editor_mutate_minimum_datetime_after_init(self): ) view = get_date_time_simple_view(editor_factory) instance = InstanceWithDatetime() - with reraise_exceptions(), \ - self.launch_editor(instance, view) as editor: + with reraise_exceptions(), self.launch_editor( + instance, view + ) as editor: # This value is in-range instance.date_time = datetime.datetime(2001, 1, 1) @@ -142,8 +145,9 @@ def test_datetime_editor_mutate_minimum_datetime_bad_order(self): ) view = get_date_time_simple_view(editor_factory) instance = InstanceWithDatetime() - with reraise_exceptions(), \ - self.launch_editor(instance, view) as editor: + with reraise_exceptions(), self.launch_editor( + instance, view + ) as editor: # This value is in-range instance.date_time = datetime.datetime(2001, 1, 1) @@ -170,8 +174,9 @@ def test_datetime_editor_simple_with_maximum_datetime(self): ) view = get_date_time_simple_view(editor_factory) instance = InstanceWithDatetime() - with reraise_exceptions(), \ - self.launch_editor(instance, view) as editor: + with reraise_exceptions(), self.launch_editor( + instance, view + ) as editor: q_maximum_datetime = editor.control.maximumDateTime() # does not seem needed to flush the event loop, but just in case. @@ -188,8 +193,9 @@ def test_datetime_editor_simple_with_maximum_datetime_out_of_bound(self): ) view = get_date_time_simple_view(editor_factory) instance = InstanceWithDatetime() - with reraise_exceptions(), \ - self.launch_editor(instance, view) as editor: + with reraise_exceptions(), self.launch_editor( + instance, view + ) as editor: # out-of-bound instance.date_time = datetime.datetime(2020, 1, 1) @@ -209,8 +215,9 @@ def test_datetime_editor_mutate_maximum_datetime_after_init(self): ) view = get_date_time_simple_view(editor_factory) instance = InstanceWithDatetime() - with reraise_exceptions(), \ - self.launch_editor(instance, view) as editor: + with reraise_exceptions(), self.launch_editor( + instance, view + ) as editor: # This value is in-range instance.date_time = datetime.datetime(1999, 1, 1) @@ -235,8 +242,9 @@ def test_datetime_editor_python_datetime_out_of_bound(self): view = get_date_time_simple_view(editor_factory) init_datetime = datetime.datetime(1900, 1, 1) instance = InstanceWithDatetime(date_time=init_datetime) - with reraise_exceptions(), \ - self.launch_editor(instance, view) as editor: + with reraise_exceptions(), self.launch_editor( + instance, view + ) as editor: # This value is too early and is not supported by Qt # But the editor should not crash new_value = datetime.datetime(1, 1, 1) @@ -258,11 +266,13 @@ def test_datetime_editor_qt_datetime_out_of_bound(self): view = get_date_time_simple_view(editor_factory) init_datetime = datetime.datetime(1900, 1, 1) instance = InstanceWithDatetime(date_time=init_datetime) - with reraise_exceptions(), \ - self.launch_editor(instance, view) as editor: + with reraise_exceptions(), self.launch_editor( + instance, view + ) as editor: # the user set the datetime on the Qt widget to a value # too large for Python from pyface.qt.QtCore import QDateTime, QDate, QTime + q_datetime = QDateTime( QDate(datetime.MAXYEAR + 1, 1, 1), QTime(0, 0) ) @@ -276,5 +286,5 @@ def test_datetime_editor_qt_datetime_out_of_bound(self): @contextlib.contextmanager def launch_editor(self, object, view): with create_ui(object, dict(view=view)) as ui: - editor, = ui._editors + (editor,) = ui._editors yield editor diff --git a/traitsui/tests/editors/test_default_override.py b/traitsui/tests/editors/test_default_override.py index 0ff06f3eb..82fbab42c 100644 --- a/traitsui/tests/editors/test_default_override.py +++ b/traitsui/tests/editors/test_default_override.py @@ -47,7 +47,6 @@ class Dummy(HasTraits): class TestDefaultOverride(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -55,8 +54,15 @@ def tearDown(self): BaseTestMixin.tearDown(self) def test_simple_override(self): - editor_name, editor, ui, obj, name, description, parent = \ - do.simple_editor("ui", dummy_object, "x", "description", "parent") + ( + editor_name, + editor, + ui, + obj, + name, + description, + parent, + ) = do.simple_editor("ui", dummy_object, "x", "description", "parent") self.assertEqual(editor_name, "simple_editor") self.assertEqual(editor.x, 15) self.assertEqual(editor.y, 25) @@ -66,8 +72,15 @@ def test_simple_override(self): self.assertEqual(parent, "parent") def test_text_override(self): - editor_name, editor, ui, obj, name, description, parent = \ - do.text_editor("ui", dummy_object, "x", "description", "parent") + ( + editor_name, + editor, + ui, + obj, + name, + description, + parent, + ) = do.text_editor("ui", dummy_object, "x", "description", "parent") self.assertEqual(editor_name, "text_editor") self.assertEqual(editor.x, 15) self.assertEqual(editor.y, 25) @@ -77,8 +90,15 @@ def test_text_override(self): self.assertEqual(parent, "parent") def test_custom_override(self): - editor_name, editor, ui, obj, name, description, parent = \ - do.custom_editor("ui", dummy_object, "x", "description", "parent") + ( + editor_name, + editor, + ui, + obj, + name, + description, + parent, + ) = do.custom_editor("ui", dummy_object, "x", "description", "parent") self.assertEqual(editor_name, "custom_editor") self.assertEqual(editor.x, 15) self.assertEqual(editor.y, 25) @@ -88,10 +108,17 @@ def test_custom_override(self): self.assertEqual(parent, "parent") def test_readonly_override(self): - editor_name, editor, ui, obj, name, description, parent = \ - do.readonly_editor( - "ui", dummy_object, "x", "description", "parent" - ) + ( + editor_name, + editor, + ui, + obj, + name, + description, + parent, + ) = do.readonly_editor( + "ui", dummy_object, "x", "description", "parent" + ) self.assertEqual(editor_name, "readonly_editor") self.assertEqual(editor.x, 15) self.assertEqual(editor.y, 25) diff --git a/traitsui/tests/editors/test_directory_editor.py b/traitsui/tests/editors/test_directory_editor.py index 6cf6e5a68..466721b68 100644 --- a/traitsui/tests/editors/test_directory_editor.py +++ b/traitsui/tests/editors/test_directory_editor.py @@ -30,7 +30,7 @@ class DirectoryModel(HasTraits): # Run this against wx too when enthought/traitsui#752 is also fixed. @requires_toolkit([ToolkitName.qt]) class TestDirectoryEditor(BaseTestMixin, unittest.TestCase): - """ Test DirectoryEditor. """ + """Test DirectoryEditor.""" def setUp(self): BaseTestMixin.setUp(self) diff --git a/traitsui/tests/editors/test_drop_editor.py b/traitsui/tests/editors/test_drop_editor.py index b670eb59e..5ac093472 100644 --- a/traitsui/tests/editors/test_drop_editor.py +++ b/traitsui/tests/editors/test_drop_editor.py @@ -29,7 +29,7 @@ class Model(HasTraits): # Run this test against wx when enthought/traitsui#752 is fixed. @requires_toolkit([ToolkitName.qt]) class TestDropEditor(BaseTestMixin, unittest.TestCase): - """ Test DropEditor. """ + """Test DropEditor.""" def setUp(self): BaseTestMixin.setUp(self) diff --git a/traitsui/tests/editors/test_enum_editor.py b/traitsui/tests/editors/test_enum_editor.py index 7380b98d6..d64264b44 100644 --- a/traitsui/tests/editors/test_enum_editor.py +++ b/traitsui/tests/editors/test_enum_editor.py @@ -31,7 +31,7 @@ KeySequence, MouseClick, SelectedText, - UITester + UITester, ) @@ -82,7 +82,6 @@ def get_radio_view(cols=1): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestEnumEditorMapping(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -101,7 +100,7 @@ class IntEnumModel(HasTraits): enum_editor_factory = EnumEditor( values=[0, 1], format_func=lambda v: str(bool(v)).upper(), - mode=mode + mode=mode, ) formatted_view = View( UItem( @@ -111,22 +110,19 @@ class IntEnumModel(HasTraits): ) ) - with reraise_exceptions(), \ - self.setup_ui(IntEnumModel(), formatted_view) as editor: + with reraise_exceptions(), self.setup_ui( + IntEnumModel(), formatted_view + ) as editor: self.assertEqual(editor.names, ["FALSE", "TRUE"]) self.assertEqual(editor.mapping, {"FALSE": 0, "TRUE": 1}) - self.assertEqual( - editor.inverse_mapping, {0: "FALSE", 1: "TRUE"} - ) + self.assertEqual(editor.inverse_mapping, {0: "FALSE", 1: "TRUE"}) enum_editor_factory.values = [1, 0] self.assertEqual(editor.names, ["TRUE", "FALSE"]) self.assertEqual(editor.mapping, {"TRUE": 1, "FALSE": 0}) - self.assertEqual( - editor.inverse_mapping, {1: "TRUE", 0: "FALSE"} - ) + self.assertEqual(editor.inverse_mapping, {1: "TRUE", 0: "FALSE"}) def check_enum_mappings_name_change(self, style, mode): class IntEnumModel(HasTraits): @@ -139,29 +135,26 @@ class IntEnumModel(HasTraits): editor=EnumEditor( name="object.possible_values", format_func=lambda v: str(bool(v)).upper(), - mode=mode + mode=mode, ), style=style, ) ) model = IntEnumModel() - with reraise_exceptions(), \ - self.setup_ui(model, formatted_view) as editor: + with reraise_exceptions(), self.setup_ui( + model, formatted_view + ) as editor: self.assertEqual(editor.names, ["FALSE", "TRUE"]) self.assertEqual(editor.mapping, {"FALSE": 0, "TRUE": 1}) - self.assertEqual( - editor.inverse_mapping, {0: "FALSE", 1: "TRUE"} - ) + self.assertEqual(editor.inverse_mapping, {0: "FALSE", 1: "TRUE"}) model.possible_values = [1, 0] self.assertEqual(editor.names, ["TRUE", "FALSE"]) self.assertEqual(editor.mapping, {"TRUE": 1, "FALSE": 0}) - self.assertEqual( - editor.inverse_mapping, {1: "TRUE", 0: "FALSE"} - ) + self.assertEqual(editor.inverse_mapping, {1: "TRUE", 0: "FALSE"}) def test_simple_editor_mapping_values(self): self.check_enum_mappings_value_change("simple", "radio") @@ -198,7 +191,6 @@ def test_list_editor_mapping_name(self): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestSimpleEnumEditor(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -340,7 +332,6 @@ def test_simple_editor_disabled(self): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestRadioEnumEditor(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -396,7 +387,6 @@ def test_radio_enum_none_selected(self): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestListEnumEditor(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) diff --git a/traitsui/tests/editors/test_file_editor.py b/traitsui/tests/editors/test_file_editor.py index 61c64458f..9a1b571ea 100644 --- a/traitsui/tests/editors/test_file_editor.py +++ b/traitsui/tests/editors/test_file_editor.py @@ -31,7 +31,7 @@ class FileModel(HasTraits): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestSimpleFileEditor(BaseTestMixin, unittest.TestCase): - """ Test FileEditor (simple style). """ + """Test FileEditor (simple style).""" def setUp(self): BaseTestMixin.setUp(self) @@ -104,7 +104,7 @@ def test_simple_editor_reset_text_if_validation_error(self): # Run this against wx too when enthought/traitsui#752 is also fixed. @requires_toolkit([ToolkitName.qt]) class TestCustomFileEditor(BaseTestMixin, unittest.TestCase): - """ Test FileEditor (custom style). """ + """Test FileEditor (custom style).""" def setUp(self): BaseTestMixin.setUp(self) diff --git a/traitsui/tests/editors/test_font_editor.py b/traitsui/tests/editors/test_font_editor.py index ef903788f..0a126f365 100644 --- a/traitsui/tests/editors/test_font_editor.py +++ b/traitsui/tests/editors/test_font_editor.py @@ -18,10 +18,7 @@ requires_toolkit, ToolkitName, ) -from traitsui.testing.api import ( - MouseClick, - UITester -) +from traitsui.testing.api import MouseClick, UITester class ObjectWithFont(HasTraits): @@ -30,7 +27,6 @@ class ObjectWithFont(HasTraits): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestFontEditor(unittest.TestCase): - def test_create_and_dispose_text_style(self): # Setting focus on the widget and then disposing the widget # should not cause errors. diff --git a/traitsui/tests/editors/test_html_editor.py b/traitsui/tests/editors/test_html_editor.py index 85c90469a..167161527 100644 --- a/traitsui/tests/editors/test_html_editor.py +++ b/traitsui/tests/editors/test_html_editor.py @@ -13,10 +13,12 @@ try: from pyface.qt import QtWebkit # noqa: F401 + NO_WEBKIT_OR_WEBENGINE = False except ImportError: try: from pyface.qt import QtWebEngine # noqa: F401 + NO_WEBKIT_OR_WEBENGINE = False except ImportError: NO_WEBKIT_OR_WEBENGINE = True @@ -32,7 +34,7 @@ class HTMLModel(HasTraits): - """ Dummy class for testing HTMLEditor.""" + """Dummy class for testing HTMLEditor.""" content = Str() @@ -46,20 +48,21 @@ def get_view(base_url_name): editor=HTMLEditor( format_text=True, base_url_name=base_url_name, - ) + ), ) ) class HTMLContent: - """ Action to retrieve the HTML content currently displayed. + """Action to retrieve the HTML content currently displayed. Implementation should return a str, whose content conforms to HTML markup. """ + pass def _is_webkit_page(page): - """ Return true if the given page is a QWebPage from QtWebKit. + """Return true if the given page is a QWebPage from QtWebKit. Intended for handling the compatibility between QtWebKit and QtWebEngine. @@ -71,7 +74,7 @@ def _is_webkit_page(page): def qt_get_page_html_content(page): - """ Return the HTML content currently being viewed. + """Return the HTML content currently being viewed. Parameters ---------- @@ -92,7 +95,7 @@ def qt_get_page_html_content(page): def wait_for_qt_signal(qt_signal, timeout): - """ Wait for the given Qt signal to fire, or timeout. + """Wait for the given Qt signal to fire, or timeout. A mock implementation of QSignalSpy.wait, which is one of the missing bindings in PySide2, and is not available in Qt4. @@ -134,7 +137,7 @@ def exit(*args, **kwargs): def qt_allow_view_to_load(loadable, timeout=0.5): - """ Allow QWebView/QWebPage/QWebEngineView/QWebEnginePage to finish + """Allow QWebView/QWebPage/QWebEngineView/QWebEnginePage to finish loading. Out of context, this function does not know if the page has started @@ -160,7 +163,7 @@ def qt_allow_view_to_load(loadable, timeout=0.5): def qt_mouse_click_web_view(view, delay): - """ Perform a mouse click at the center of the web view. + """Perform a mouse click at the center of the web view. Note that the page is allowed time to load before and after the mouse click. @@ -193,7 +196,7 @@ def qt_mouse_click_web_view(view, delay): def qt_target_registry(): - """ Return an instance of TargetRegistry for testing Qt + HTMLEditor + """Return an instance of TargetRegistry for testing Qt + HTMLEditor Returns ------- @@ -207,20 +210,20 @@ def qt_target_registry(): interaction_class=MouseClick, handler=lambda wrapper, _: qt_mouse_click_web_view( wrapper._target.control, wrapper.delay - ) + ), ) registry.register_interaction( target_class=SimpleEditor, interaction_class=HTMLContent, handler=lambda wrapper, _: ( qt_get_page_html_content(wrapper._target.control.page()) - ) + ), ) return registry def get_custom_ui_tester(): - """ Return an instance of UITester that contains extended testing + """Return an instance of UITester that contains extended testing functionality for HTMLEditor. These implementations are used by TraitsUI only, are more ad hoc than they would have been if they were made public. @@ -236,7 +239,7 @@ def get_custom_ui_tester(): NO_WEBKIT_OR_WEBENGINE, "Tests require either QtWebKit or QtWebEngine" ) class TestHTMLEditor(BaseTestMixin, unittest.TestCase): - """ Test HTMLEditor """ + """Test HTMLEditor""" def setUp(self): BaseTestMixin.setUp(self) @@ -267,7 +270,8 @@ def test_open_internal_link(self): # this test requires Qt because it relies on the link filling up # the entire page through the use of CSS, which isn't supported # by Wx. - model = HTMLModel(content=""" + model = HTMLModel( + content=""" - """) - view = View( - Item("content", editor=HTMLEditor()) + """ ) + view = View(Item("content", editor=HTMLEditor())) with self.tester.create_ui(model, dict(view=view)) as ui: html_view = self.tester.find_by_name(ui, "content") @@ -295,7 +298,8 @@ def test_open_external_link(self): # this test requires Qt because it relies on the link filling up # the entire page through the use of CSS, which isn't supported # by Wx. - model = HTMLModel(content=""" + model = HTMLModel( + content=""" - """) - view = View( - Item("content", editor=HTMLEditor()) + """ ) + view = View(Item("content", editor=HTMLEditor())) with self.tester.create_ui(model, dict(view=view)) as ui: html_view = self.tester.find_by_name(ui, "content") @@ -329,7 +332,8 @@ def test_open_internal_link_externally(self): # this test requires Qt because it relies on the link filling up # the entire page through the use of CSS, which isn't supported # by Wx. - model = HTMLModel(content=""" + model = HTMLModel( + content=""" - """) - view = View( - Item("content", editor=HTMLEditor(open_externally=True)) + """ ) + view = View(Item("content", editor=HTMLEditor(open_externally=True))) with self.tester.create_ui(model, dict(view=view)) as ui: html_view = self.tester.find_by_name(ui, "content") @@ -356,7 +359,8 @@ def test_open_internal_link_externally(self): @requires_toolkit([ToolkitName.qt]) def test_open_external_link_externally(self): - model = HTMLModel(content=""" + model = HTMLModel( + content=""" - """) - view = View( - Item("content", editor=HTMLEditor(open_externally=True)) + """ ) + view = View(Item("content", editor=HTMLEditor(open_externally=True))) with self.tester.create_ui(model, dict(view=view)) as ui: html_view = self.tester.find_by_name(ui, "content") diff --git a/traitsui/tests/editors/test_image_enum_editor.py b/traitsui/tests/editors/test_image_enum_editor.py index a33cbdaf0..3a46da6a2 100644 --- a/traitsui/tests/editors/test_image_enum_editor.py +++ b/traitsui/tests/editors/test_image_enum_editor.py @@ -29,12 +29,14 @@ # Import needed bitmap/pixmap cache and prepare for patching if is_wx(): from traitsui.wx.helper import bitmap_cache as image_cache + cache_to_patch = "traitsui.wx.image_enum_editor.bitmap_cache" elif is_qt(): from traitsui.qt4.helper import pixmap_cache as image_cache + cache_to_patch = "traitsui.qt4.image_enum_editor.pixmap_cache" -is_linux = (sys.platform == 'linux') +is_linux = sys.platform == 'linux' class EnumModel(HasTraits): @@ -48,7 +50,10 @@ def get_view(style): 'value', editor=ImageEnumEditor( values=[ - 'top left', 'top right', 'bottom left', 'bottom right' + 'top left', + 'top right', + 'bottom left', + 'bottom right', ], prefix='@icons:', suffix='_origin', @@ -61,7 +66,7 @@ def get_view(style): def click_on_image(image_control): - """ Click on the image controlled by given image_control.""" + """Click on the image controlled by given image_control.""" if is_wx(): import wx @@ -80,7 +85,7 @@ def click_on_image(image_control): def get_button_strings(control): - """ Return the list of strings associated with the buttons under given + """Return the list of strings associated with the buttons under given control. Assumes all sizer children (wx) or layout items (qt) are buttons. """ button_strings = [] @@ -103,7 +108,7 @@ def get_button_strings(control): def get_all_button_selected_status(control): - """ Return a list with selected (wx) or checked (qt) button status under + """Return a list with selected (wx) or checked (qt) button status under given control. Assumes all sizer children (wx) or layout items (qt) are buttons. """ @@ -125,7 +130,7 @@ def get_all_button_selected_status(control): def get_button_control(control, button_idx): - """ Get button control from a specified parent control given a button index. + """Get button control from a specified parent control given a button index. Assumes all sizer children (wx) or layout items (qt) are buttons. """ if is_wx(): @@ -140,7 +145,6 @@ def get_button_control(control, button_idx): @requires_toolkit([ToolkitName.qt]) class TestImageEnumEditorMapping(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -169,17 +173,18 @@ def check_enum_mappings_value_change(self, style): ) ) - with reraise_exceptions(), \ - self.setup_ui(EnumModel(), formatted_view) as editor: + with reraise_exceptions(), self.setup_ui( + EnumModel(), formatted_view + ) as editor: self.assertEqual(editor.names, ["TOP LEFT", "TOP RIGHT"]) self.assertEqual( editor.mapping, - {"TOP LEFT": "top left", "TOP RIGHT": "top right"} + {"TOP LEFT": "top left", "TOP RIGHT": "top right"}, ) self.assertEqual( editor.inverse_mapping, - {"top left": "TOP LEFT", "top right": "TOP RIGHT"} + {"top left": "TOP LEFT", "top right": "TOP RIGHT"}, ) image_enum_editor_factory.values = ["top right", "top left"] @@ -187,11 +192,11 @@ def check_enum_mappings_value_change(self, style): self.assertEqual(editor.names, ["TOP RIGHT", "TOP LEFT"]) self.assertEqual( editor.mapping, - {"TOP RIGHT": "top right", "TOP LEFT": "top left"} + {"TOP RIGHT": "top right", "TOP LEFT": "top left"}, ) self.assertEqual( editor.inverse_mapping, - {"top right": "TOP RIGHT", "top left": "TOP LEFT"} + {"top right": "TOP RIGHT", "top left": "TOP LEFT"}, ) def check_enum_mappings_name_change(self, style): @@ -214,17 +219,18 @@ class PossibleEnumModel(HasTraits): ) model = PossibleEnumModel() - with reraise_exceptions(), \ - self.setup_ui(model, formatted_view) as editor: + with reraise_exceptions(), self.setup_ui( + model, formatted_view + ) as editor: self.assertEqual(editor.names, ["TOP LEFT", "TOP RIGHT"]) self.assertEqual( editor.mapping, - {"TOP LEFT": "top left", "TOP RIGHT": "top right"} - ) + {"TOP LEFT": "top left", "TOP RIGHT": "top right"}, + ) self.assertEqual( editor.inverse_mapping, - {"top left": "TOP LEFT", "top right": "TOP RIGHT"} + {"top left": "TOP LEFT", "top right": "TOP RIGHT"}, ) model.possible_values = ["top right", "top left"] @@ -232,11 +238,11 @@ class PossibleEnumModel(HasTraits): self.assertEqual(editor.names, ["TOP RIGHT", "TOP LEFT"]) self.assertEqual( editor.mapping, - {"TOP RIGHT": "top right", "TOP LEFT": "top left"} + {"TOP RIGHT": "top right", "TOP LEFT": "top left"}, ) self.assertEqual( editor.inverse_mapping, - {"top right": "TOP RIGHT", "top left": "TOP LEFT"} + {"top right": "TOP RIGHT", "top left": "TOP LEFT"}, ) @unittest.skip("Issue enthought/traitsui#844") @@ -276,8 +282,9 @@ class PossibleEnumModel(HasTraits): ) model = PossibleEnumModel() - with reraise_exceptions(), \ - self.setup_ui(model, formatted_view) as editor: + with reraise_exceptions(), self.setup_ui( + model, formatted_view + ) as editor: # Readonly editor doesn't set up full mapping, only check that # str_value is mapped as expected @@ -286,7 +293,6 @@ class PossibleEnumModel(HasTraits): class TestSimpleImageEnumEditor(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -308,7 +314,10 @@ def test_simple_editor_more_cols(self): 'value', editor=ImageEnumEditor( values=[ - 'top left', 'top right', 'bottom left', 'bottom right' + 'top left', + 'top right', + 'bottom left', + 'bottom right', ], prefix='@icons:', suffix='_origin', @@ -327,8 +336,9 @@ def test_simple_editor_more_cols(self): def test_simple_editor_popup_editor(self): enum_edit = EnumModel() - with reraise_exceptions(), \ - self.setup_gui(enum_edit, get_view("simple")) as editor: + with reraise_exceptions(), self.setup_gui( + enum_edit, get_view("simple") + ) as editor: self.assertEqual(enum_edit.value, 'top left') @@ -337,12 +347,12 @@ def test_simple_editor_popup_editor(self): process_cascade_events() # Check created buttons - image_grid_control = ( - editor.control.GetChildren()[0].GetChildren()[0] - ) + image_grid_control = editor.control.GetChildren()[0].GetChildren()[ + 0 + ] self.assertEqual( get_button_strings(image_grid_control), - ['top left', 'top right', 'bottom left', 'bottom right'] + ['top left', 'top right', 'bottom left', 'bottom right'], ) # Select new image @@ -358,8 +368,9 @@ def test_simple_editor_popup_editor(self): def test_simple_editor_combobox(self): enum_edit = EnumModel() - with reraise_exceptions(), \ - self.setup_gui(enum_edit, get_view("simple")) as editor: + with reraise_exceptions(), self.setup_gui( + enum_edit, get_view("simple") + ) as editor: self.assertEqual(enum_edit.value, 'top left') @@ -376,7 +387,6 @@ def test_simple_editor_combobox(self): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestCustomImageEnumEditor(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -397,7 +407,10 @@ def test_custom_editor_more_cols(self): 'value', editor=ImageEnumEditor( values=[ - 'top left', 'top right', 'bottom left', 'bottom right' + 'top left', + 'top right', + 'bottom left', + 'bottom right', ], prefix='@icons:', suffix='_origin', @@ -409,24 +422,24 @@ def test_custom_editor_more_cols(self): resizable=True, ) - with reraise_exceptions(), \ - self.setup_gui(enum_edit, view): + with reraise_exceptions(), self.setup_gui(enum_edit, view): pass def test_custom_editor_selection(self): enum_edit = EnumModel() - with reraise_exceptions(), \ - self.setup_gui(enum_edit, get_view("custom")) as editor: + with reraise_exceptions(), self.setup_gui( + enum_edit, get_view("custom") + ) as editor: self.assertEqual( get_button_strings(editor.control), - ['top left', 'top right', 'bottom left', 'bottom right'] + ['top left', 'top right', 'bottom left', 'bottom right'], ) self.assertEqual(enum_edit.value, 'top left') self.assertEqual( get_all_button_selected_status(editor.control), - [True, False, False, False] + [True, False, False, False], ) click_on_image(get_button_control(editor.control, 1)) @@ -437,17 +450,18 @@ def test_custom_editor_selection(self): def test_custom_editor_value_changed(self): enum_edit = EnumModel() - with reraise_exceptions(), \ - self.setup_gui(enum_edit, get_view("custom")) as editor: + with reraise_exceptions(), self.setup_gui( + enum_edit, get_view("custom") + ) as editor: self.assertEqual( get_button_strings(editor.control), - ['top left', 'top right', 'bottom left', 'bottom right'] + ['top left', 'top right', 'bottom left', 'bottom right'], ) self.assertEqual(enum_edit.value, 'top left') self.assertEqual( get_all_button_selected_status(editor.control), - [True, False, False, False] + [True, False, False, False], ) enum_edit.value = 'top right' @@ -455,13 +469,12 @@ def test_custom_editor_value_changed(self): self.assertEqual( get_all_button_selected_status(editor.control), - [False, True, False, False] + [False, True, False, False], ) @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestReadOnlyImageEnumEditor(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -472,8 +485,11 @@ def test_readonly_editor_value_changed(self): enum_edit = EnumModel() with reraise_exceptions(): - with patch(cache_to_patch, wraps=image_cache) as patched_cache, \ - create_ui(enum_edit, dict(view=get_view("readonly"))): + with patch( + cache_to_patch, wraps=image_cache + ) as patched_cache, create_ui( + enum_edit, dict(view=get_view("readonly")) + ): self.assertEqual(enum_edit.value, 'top left') self.assertEqual( diff --git a/traitsui/tests/editors/test_instance_editor.py b/traitsui/tests/editors/test_instance_editor.py index 298e1c79a..a4651e5d7 100644 --- a/traitsui/tests/editors/test_instance_editor.py +++ b/traitsui/tests/editors/test_instance_editor.py @@ -28,7 +28,7 @@ MouseClick, SelectedText, TargetByName, - UITester + UITester, ) ModalDialogTester = toolkit_object( @@ -45,11 +45,7 @@ class EditedInstance(HasTraits): class NamedInstance(HasTraits): name = Str() value = Str() - traits_view = View( - Item("name"), - Item("value"), - buttons=["OK"] - ) + traits_view = View(Item("name"), Item("value"), buttons=["OK"]) class ObjectWithInstance(HasTraits): @@ -135,11 +131,7 @@ class ObjectWithValidatedInstance(HasTraits): something = Instance(ValidatedEditedInstance, args=()) traits_view = View( - Item( - 'something', - editor=InstanceEditor(), - style='custom' - ), + Item('something', editor=InstanceEditor(), style='custom'), buttons=["OK", "Cancel"], ) @@ -157,7 +149,6 @@ def _inst_list_default(self): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestInstanceEditor(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -326,16 +317,10 @@ def test_propagate_errors(self): instance_editor_ui = something_ui._target._ui instance_editor_ui_parent = something_ui._target._ui.parent - self.assertNotEqual( - instance_editor_ui, ui - ) - self.assertEqual( - instance_editor_ui_parent, ui - ) + self.assertNotEqual(instance_editor_ui, ui) + self.assertEqual(instance_editor_ui_parent, ui) - self.assertEqual( - instance_editor_ui.errors, ui.errors - ) + self.assertEqual(instance_editor_ui.errors, ui.errors) self.assertFalse(ok_button.inspect(IsEnabled())) def test_propagate_errors_switch_selection(self): @@ -356,16 +341,10 @@ def test_propagate_errors_switch_selection(self): instance_editor_ui = something_ui._target._ui instance_editor_ui_parent = something_ui._target._ui.parent - self.assertNotEqual( - instance_editor_ui, ui - ) - self.assertEqual( - instance_editor_ui_parent, ui - ) + self.assertNotEqual(instance_editor_ui, ui) + self.assertEqual(instance_editor_ui_parent, ui) - self.assertEqual( - instance_editor_ui.errors, ui.errors - ) + self.assertEqual(instance_editor_ui.errors, ui.errors) self.assertFalse(ok_button.inspect(IsEnabled())) # change to a different selected that is not in an error state diff --git a/traitsui/tests/editors/test_list_editor.py b/traitsui/tests/editors/test_list_editor.py index 900ee61d0..ac84f9d56 100644 --- a/traitsui/tests/editors/test_list_editor.py +++ b/traitsui/tests/editors/test_list_editor.py @@ -13,7 +13,13 @@ from pyface.toolkit import toolkit_object from traits.api import ( - Directory, HasStrictTraits, Instance, Int, List, Str, TraitError + Directory, + HasStrictTraits, + Instance, + Int, + List, + Str, + TraitError, ) from traitsui.api import Item, ListEditor, View @@ -25,7 +31,7 @@ LocationNotSupported, MouseClick, Textbox, - UITester + UITester, ) from traitsui.tests._tools import ( requires_toolkit, @@ -45,11 +51,7 @@ class Person(HasStrictTraits): age = Int() # Traits view definition: - traits_view = View( - 'name', 'age', - width=0.18, - buttons=['OK', 'Cancel'] - ) + traits_view = View('name', 'age', width=0.18, buttons=['OK', 'Cancel']) def get_people(): @@ -62,7 +64,7 @@ def get_people(): Person(name='Dick', age=63), Person(name='Harry', age=46), Person(name='Sally', age=43), - Person(name='Fields', age=31) + Person(name='Fields', age=31), ] @@ -84,7 +86,7 @@ def default_traits_view(self): style=self.style, editor=ListEditor(style=self.style, columns=self.num_columns), ), - resizable=True + resizable=True, ) return view @@ -104,7 +106,6 @@ class Phonebook(HasStrictTraits): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestCustomListEditor(unittest.TestCase): - def test_locate_element_and_edit(self): # varying the number of columns in the view tests the logic for # getting the correct nested ui @@ -144,7 +145,6 @@ def test_index_out_of_range(self): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestSimpleListEditor(unittest.TestCase): - def test_locate_element_and_edit(self): obj = ListTraitTest(people=get_people(), style="simple") tester = UITester() @@ -182,7 +182,6 @@ def test_index_out_of_range(self): # regression test for enthought/traitsui#1154 @requires_toolkit([ToolkitName.qt]) def test_add_item_fails(self): - class Foo(HasStrictTraits): dirs = List(Directory(exists=True)) @@ -218,10 +217,7 @@ def test_callable(): class Foo(HasStrictTraits): dirs = List(Directory(exists=True)) view = View( - Item( - "dirs", - editor=ListEditor(item_factory=test_callable) - ) + Item("dirs", editor=ListEditor(item_factory=test_callable)) ) obj = Foo() @@ -250,8 +246,8 @@ class TestFoo(HasStrictTraits): editor=ListEditor( item_factory=test_callable, item_factory_args=(7,), - item_factory_kwargs={'baz': "python"} - ) + item_factory_kwargs={'baz': "python"}, + ), ) ) @@ -268,7 +264,6 @@ class TestFoo(HasStrictTraits): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestNotebookListEditor(unittest.TestCase): - def test_modify_person_name(self): phonebook = Phonebook( people=get_people(), @@ -305,6 +300,6 @@ def test_index_out_of_bound(self): tester = UITester() with tester.create_ui(phonebook, dict(view=notebook_view)) as ui: with self.assertRaises(IndexError): - tester.find_by_name(ui, "people").\ - locate(Index(0)).\ - perform(MouseClick()) + tester.find_by_name(ui, "people").locate(Index(0)).perform( + MouseClick() + ) diff --git a/traitsui/tests/editors/test_liststr_editor.py b/traitsui/tests/editors/test_liststr_editor.py index 6e9c6fded..74dafa989 100644 --- a/traitsui/tests/editors/test_liststr_editor.py +++ b/traitsui/tests/editors/test_liststr_editor.py @@ -24,7 +24,6 @@ class TraitObject(HasTraits): class TestListStrAdapter(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) diff --git a/traitsui/tests/editors/test_liststr_editor_selection.py b/traitsui/tests/editors/test_liststr_editor_selection.py index d118d4d12..8ba310bba 100644 --- a/traitsui/tests/editors/test_liststr_editor_selection.py +++ b/traitsui/tests/editors/test_liststr_editor_selection.py @@ -91,10 +91,10 @@ def get_view(**kwargs): def get_selected_indices(editor): - """ Returns a list of the indices of all currently selected list items. - """ + """Returns a list of the indices of all currently selected list items.""" if is_wx(): import wx + # "item" in this context means "index of the item" item = -1 selected = [] @@ -116,8 +116,7 @@ def get_selected_indices(editor): def set_selected_single(editor, index): - """ Selects a specified item in an editor with multi_select=False. - """ + """Selects a specified item in an editor with multi_select=False.""" if is_wx(): editor.control.Select(index) @@ -133,7 +132,7 @@ def set_selected_single(editor, index): def set_selected_multiple(editor, indices): - """ Clears old selection and selects specified items in an editor with + """Clears old selection and selects specified items in an editor with multi_select=True. """ if is_wx(): @@ -155,8 +154,7 @@ def set_selected_multiple(editor, indices): def clear_selection(editor): - """ Clears existing selection. - """ + """Clears existing selection.""" if is_wx(): import wx @@ -175,8 +173,7 @@ def clear_selection(editor): def right_click_item(editor, index): - """ Right clicks on the specified item. - """ + """Right clicks on the specified item.""" if is_wx(): import wx @@ -191,6 +188,7 @@ def right_click_item(editor, index): elif is_qt(): from pyface.qt import QtCore from pyface.qt.QtTest import QTest + view = editor.list_view q_model_index = view.model().index(index, 0) view.scrollTo(q_model_index) @@ -206,8 +204,7 @@ def right_click_item(editor, index): def right_click_center(editor): - """ Right click the middle of the widget. - """ + """Right click the middle of the widget.""" if is_wx(): import wx @@ -221,6 +218,7 @@ def right_click_center(editor): elif is_qt(): from pyface.qt import QtCore from pyface.qt.QtTest import QTest + view = editor.list_view rect = view.rect() QTest.mouseClick( @@ -236,7 +234,6 @@ def right_click_center(editor): @unittest.skipIf(is_wx(), "Issue enthought/traitsui#752") @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestListStrEditor(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -251,8 +248,9 @@ def setup_gui(self, model, view): yield editor def test_list_str_editor_single_selection(self): - with reraise_exceptions(), \ - self.setup_gui(ListStrModel(), get_view()) as editor: + with reraise_exceptions(), self.setup_gui( + ListStrModel(), get_view() + ) as editor: if is_qt(): # No initial selection self.assertEqual(editor.selected_index, -1) @@ -282,8 +280,9 @@ def test_list_str_editor_single_selection(self): def test_list_str_editor_multi_selection(self): view = get_view(multi_select=True) - with reraise_exceptions(), \ - self.setup_gui(ListStrModel(), view) as editor: + with reraise_exceptions(), self.setup_gui( + ListStrModel(), view + ) as editor: self.assertEqual(editor.multi_selected_indices, []) self.assertEqual(editor.multi_selected, []) @@ -307,8 +306,9 @@ def test_list_str_editor_multi_selection(self): self.assertEqual(editor.multi_selected, []) def test_list_str_editor_single_selection_changed(self): - with reraise_exceptions(), \ - self.setup_gui(ListStrModel(), get_view()) as editor: + with reraise_exceptions(), self.setup_gui( + ListStrModel(), get_view() + ) as editor: if is_qt(): # No initial selection self.assertEqual(get_selected_indices(editor), []) @@ -350,8 +350,9 @@ def test_list_str_editor_single_selection_changed(self): def test_list_str_editor_multi_selection_changed(self): view = get_view(multi_select=True) - with reraise_exceptions(), \ - self.setup_gui(ListStrModel(), view) as editor: + with reraise_exceptions(), self.setup_gui( + ListStrModel(), view + ) as editor: self.assertEqual(get_selected_indices(editor), []) @@ -389,8 +390,9 @@ def test_list_str_editor_multi_selection_changed(self): def test_list_str_editor_multi_selection_items_changed(self): view = get_view(multi_select=True) - with reraise_exceptions(), \ - self.setup_gui(ListStrModel(), view) as editor: + with reraise_exceptions(), self.setup_gui( + ListStrModel(), view + ) as editor: self.assertEqual(get_selected_indices(editor), []) @@ -424,23 +426,26 @@ def test_list_str_editor_item_count(self): model = ListStrModel() # Without auto_add - with reraise_exceptions(), \ - create_ui(model, dict(view=get_view())) as ui: + with reraise_exceptions(), create_ui( + model, dict(view=get_view()) + ) as ui: process_cascade_events() editor = ui.get_editors("value")[0] self.assertEqual(editor.item_count, 3) # With auto_add - with reraise_exceptions(), \ - create_ui(model, dict(view=get_view(auto_add=True))) as ui: + with reraise_exceptions(), create_ui( + model, dict(view=get_view(auto_add=True)) + ) as ui: process_cascade_events() editor = ui.get_editors("value")[0] self.assertEqual(editor.item_count, 3) def test_list_str_editor_refresh_editor(self): # Smoke test for refresh_editor/refresh_ - with reraise_exceptions(), \ - self.setup_gui(ListStrModel(), get_view()) as editor: + with reraise_exceptions(), self.setup_gui( + ListStrModel(), get_view() + ) as editor: if is_qt(): editor.refresh_editor() elif is_wx(): @@ -452,8 +457,7 @@ def test_list_str_editor_update_editor_single_qt(self): # QT editor uses selected items as the source of truth when updating model = ListStrModel() - with reraise_exceptions(), \ - self.setup_gui(model, get_view()) as editor: + with reraise_exceptions(), self.setup_gui(model, get_view()) as editor: set_selected_single(editor, 0) process_cascade_events() @@ -484,8 +488,7 @@ def test_list_str_editor_update_editor_single_wx(self): # WX editor uses selected indices as the source of truth when updating model = ListStrModel() - with reraise_exceptions(), \ - self.setup_gui(model, get_view()) as editor: + with reraise_exceptions(), self.setup_gui(model, get_view()) as editor: set_selected_single(editor, 0) process_cascade_events() @@ -517,8 +520,7 @@ def test_list_str_editor_update_editor_multi_qt(self): model = ListStrModel() view = get_view(multi_select=True) - with reraise_exceptions(), \ - self.setup_gui(model, view) as editor: + with reraise_exceptions(), self.setup_gui(model, view) as editor: set_selected_multiple(editor, [0]) process_cascade_events() @@ -550,8 +552,7 @@ def test_list_str_editor_update_editor_multi_wx(self): model = ListStrModel() view = get_view(multi_select=True) - with reraise_exceptions(), \ - self.setup_gui(model, view) as editor: + with reraise_exceptions(), self.setup_gui(model, view) as editor: set_selected_multiple(editor, [0]) process_cascade_events() @@ -585,8 +586,7 @@ def test_list_str_editor_callx(self): def change_value(model, value): model.value = value - with reraise_exceptions(), \ - self.setup_gui(model, get_view()) as editor: + with reraise_exceptions(), self.setup_gui(model, get_view()) as editor: set_selected_single(editor, 0) process_cascade_events() @@ -605,8 +605,9 @@ def change_value(model, value): # wx editor doesn't have a `setx` method @requires_toolkit([ToolkitName.qt]) def test_list_str_editor_setx(self): - with reraise_exceptions(), \ - self.setup_gui(ListStrModel(), get_view()) as editor: + with reraise_exceptions(), self.setup_gui( + ListStrModel(), get_view() + ) as editor: set_selected_single(editor, 0) process_cascade_events() @@ -630,14 +631,14 @@ def test_list_str_editor_setx(self): def test_list_str_editor_horizontal_lines(self): # Smoke test for painting horizontal lines view = get_view(horizontal_lines=True) - with reraise_exceptions(), \ - self.setup_gui(ListStrModel(), view): + with reraise_exceptions(), self.setup_gui(ListStrModel(), view): pass def test_list_str_editor_title(self): # Smoke test for adding a title - with reraise_exceptions(), \ - self.setup_gui(ListStrModel(), get_view(title="testing")): + with reraise_exceptions(), self.setup_gui( + ListStrModel(), get_view(title="testing") + ): pass def test_list_str_editor_right_click(self): @@ -652,8 +653,7 @@ class ListStrModelRightClick(HasTraits): right_clicked_index="object.right_clicked_index", ) - with reraise_exceptions(), \ - self.setup_gui(model, view) as editor: + with reraise_exceptions(), self.setup_gui(model, view) as editor: self.assertEqual(model.right_clicked, "") self.assertEqual(model.right_clicked_index, 0) @@ -675,8 +675,7 @@ class ListStrModelRightClick(HasTraits): right_clicked="object.right_clicked", right_clicked_index="object.right_clicked_index", ) - with reraise_exceptions(), \ - self.setup_gui(model, view) as editor: + with reraise_exceptions(), self.setup_gui(model, view) as editor: self.assertEqual(model.right_clicked, "") self.assertEqual(model.right_clicked_index, 0) @@ -689,7 +688,6 @@ class ListStrModelRightClick(HasTraits): class TestListStrEditorSelection(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -703,8 +701,9 @@ def test_wx_list_str_selected_index(self): obj = ListStrEditorWithSelectedIndex( values=["value1", "value2"], selected_index=1 ) - with reraise_exceptions(), \ - create_ui(obj, dict(view=single_select_view)) as ui: + with reraise_exceptions(), create_ui( + obj, dict(view=single_select_view) + ) as ui: editor = ui.get_editors("values")[0] # the following is equivalent to setting the text in the text # control, then pressing OK @@ -725,8 +724,9 @@ def test_wx_list_str_multi_selected_index(self): obj = ListStrEditorWithSelectedIndex( values=["value1", "value2"], selected_indices=[1] ) - with reraise_exceptions(), \ - create_ui(obj, dict(view=multi_select_view)) as ui: + with reraise_exceptions(), create_ui( + obj, dict(view=multi_select_view) + ) as ui: editor = ui.get_editors("values")[0] # the following is equivalent to setting the text in the text # control, then pressing OK @@ -742,7 +742,7 @@ def test_wx_list_str_multi_selected_index(self): @requires_toolkit([ToolkitName.qt]) def test_selection_listener_disconnected(self): - """ Check that selection listeners get correctly disconnected """ + """Check that selection listeners get correctly disconnected""" from pyface.qt.QtGui import QApplication, QItemSelectionModel from pyface.ui.qt4.util.testing import event_loop @@ -758,8 +758,9 @@ def test_selection_listener_disconnected(self): pass # now run again and change the selection - with create_ui(obj, dict(view=single_select_item_view)) as ui, \ - event_loop(): + with create_ui( + obj, dict(view=single_select_item_view) + ) as ui, event_loop(): editor = ui.get_editors("values")[0] list_view = editor.list_view diff --git a/traitsui/tests/editors/test_range_editor.py b/traitsui/tests/editors/test_range_editor.py index 46651f4df..7b500d9e4 100644 --- a/traitsui/tests/editors/test_range_editor.py +++ b/traitsui/tests/editors/test_range_editor.py @@ -20,7 +20,7 @@ Slider, TargetRegistry, Textbox, - UITester + UITester, ) from traitsui.tests._tools import ( BaseTestMixin, @@ -33,7 +33,7 @@ def _register_simple_spin(registry): - """ Register interactions for the given registry for a SimpleSpinEditor. + """Register interactions for the given registry for a SimpleSpinEditor. If there are any conflicts, an error will occur. @@ -47,7 +47,7 @@ def _register_simple_spin(registry): The registry being registered to. """ from traitsui.testing.tester._ui_tester_registry.qt4 import ( - _registry_helper + _registry_helper, ) from traitsui.qt4.range_editor import SimpleSpinEditor @@ -66,7 +66,6 @@ class RangeModel(HasTraits): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestRangeEditor(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -80,9 +79,10 @@ def check_range_enum_editor_format_func(self, style): UItem( "value", editor=RangeEditor( - low=1, high=3, + low=1, + high=3, format_func=lambda v: "{:02d}".format(v), - mode="enum" + mode="enum", ), style=style, ) @@ -95,9 +95,7 @@ def check_range_enum_editor_format_func(self, style): # No formatting - simple strings self.assertEqual(editor.names[:3], ["1", "2", "3"]) self.assertEqual(editor.mapping, {"1": 1, "2": 2, "3": 3}) - self.assertEqual( - editor.inverse_mapping, {1: "1", 2: "2", 3: "3"} - ) + self.assertEqual(editor.inverse_mapping, {1: "1", 2: "2", 3: "3"}) def test_simple_editor_format_func(self): self.check_range_enum_editor_format_func("simple") @@ -108,10 +106,7 @@ def test_custom_editor_format_func(self): def check_slider_set_with_text_valid(self, mode): model = RangeModel() view = View( - Item( - "value", - editor=RangeEditor(low=1, high=12, mode=mode) - ) + Item("value", editor=RangeEditor(low=1, high=12, mode=mode)) ) tester = UITester() with tester.create_ui(model, dict(view=view)) as ui: @@ -137,10 +132,7 @@ def test_log_range_slider_editor_set_with_text_valid(self): def test_range_text_editor_set_with_text_valid(self): model = RangeModel() view = View( - Item( - "value", - editor=RangeEditor(low=1, high=12, mode="text") - ) + Item("value", editor=RangeEditor(low=1, high=12, mode="text")) ) tester = UITester() with tester.create_ui(model, dict(view=view)) as ui: @@ -163,10 +155,7 @@ def test_range_text_editor_set_with_text_valid(self): def test_simple_spin_editor_set_with_text_valid(self): model = RangeModel() view = View( - Item( - "value", - editor=RangeEditor(low=1, high=12, mode="spinner") - ) + Item("value", editor=RangeEditor(low=1, high=12, mode="spinner")) ) LOCAL_REGISTRY = TargetRegistry() _register_simple_spin(LOCAL_REGISTRY) @@ -186,10 +175,7 @@ def test_simple_spin_editor_set_with_text_valid(self): def check_slider_set_with_text_after_empty(self, mode): model = RangeModel() view = View( - Item( - "value", - editor=RangeEditor(low=1, high=12, mode=mode) - ) + Item("value", editor=RangeEditor(low=1, high=12, mode=mode)) ) tester = UITester() with tester.create_ui(model, dict(view=view)) as ui: @@ -219,10 +205,7 @@ def test_log_range_slider_editor_set_with_text_after_empty(self): def test_range_text_editor_set_with_text_after_empty(self): model = RangeModel() view = View( - Item( - "value", - editor=RangeEditor(low=1, high=12, mode="text") - ) + Item("value", editor=RangeEditor(low=1, high=12, mode="text")) ) tester = UITester() with tester.create_ui(model, dict(view=view)) as ui: @@ -241,10 +224,7 @@ def test_range_text_editor_set_with_text_after_empty(self): def test_simple_spin_editor_set_with_text_after_empty(self): model = RangeModel() view = View( - Item( - "value", - editor=RangeEditor(low=1, high=12, mode="spinner") - ) + Item("value", editor=RangeEditor(low=1, high=12, mode="spinner")) ) LOCAL_REGISTRY = TargetRegistry() _register_simple_spin(LOCAL_REGISTRY) @@ -264,10 +244,7 @@ def test_simple_spin_editor_set_with_text_after_empty(self): def check_modify_slider(self, mode): model = RangeModel(value=0) view = View( - Item( - "value", - editor=RangeEditor(low=0, high=10, mode=mode) - ) + Item("value", editor=RangeEditor(low=0, high=10, mode=mode)) ) tester = UITester() with tester.create_ui(model, dict(view=view)) as ui: @@ -300,7 +277,7 @@ def test_modify_slider_log_range_slider(self): view = View( Item( "float_value", - editor=RangeEditor(low=.1, high=1000000000, mode='logslider') + editor=RangeEditor(low=0.1, high=1000000000, mode='logslider'), ) ) tester = UITester() @@ -322,7 +299,6 @@ def test_modify_slider_log_range_slider(self): self.assertEqual(displayed, str(model.float_value)) def test_format_func(self): - def num_to_time(num): minutes = int(num / 60) if minutes < 10: @@ -338,10 +314,7 @@ def num_to_time(num): model = RangeModel() view = View( - Item( - "float_value", - editor=RangeEditor(format_func=num_to_time) - ) + Item("float_value", editor=RangeEditor(format_func=num_to_time)) ) tester = UITester() with tester.create_ui(model, dict(view=view)) as ui: @@ -359,10 +332,7 @@ def test_editor_factory_format(self): model = RangeModel() with self.assertWarns(DeprecationWarning): view = View( - Item( - "float_value", - editor=RangeEditor(format="%s ...") - ) + Item("float_value", editor=RangeEditor(format="%s ...")) ) tester = UITester() with tester.create_ui(model, dict(view=view)) as ui: @@ -380,10 +350,7 @@ def test_editor_format(self): model = RangeModel() with self.assertWarns(DeprecationWarning): view = View( - Item( - "float_value", - editor=RangeEditor(format="%s ...") - ) + Item("float_value", editor=RangeEditor(format="%s ...")) ) tester = UITester() with tester.create_ui(model, dict(view=view)) as ui: @@ -400,8 +367,7 @@ def test_set_text_out_of_range(self): model = RangeModel() view = View( Item( - 'float_value', - editor=RangeEditor(mode='text', low=0.0, high=1) + 'float_value', editor=RangeEditor(mode='text', low=0.0, high=1) ), ) tester = UITester() diff --git a/traitsui/tests/editors/test_range_editor_spinner.py b/traitsui/tests/editors/test_range_editor_spinner.py index 7af4192c9..bea9335c8 100644 --- a/traitsui/tests/editors/test_range_editor_spinner.py +++ b/traitsui/tests/editors/test_range_editor_spinner.py @@ -37,8 +37,7 @@ class NumberWithSpinnerEditor(HasTraits): - """Dialog containing a RangeEditor in 'spinner' mode for an Int. - """ + """Dialog containing a RangeEditor in 'spinner' mode for an Int.""" number = Int() @@ -50,7 +49,6 @@ class NumberWithSpinnerEditor(HasTraits): class TestRangeEditorSpinner(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) diff --git a/traitsui/tests/editors/test_range_editor_text.py b/traitsui/tests/editors/test_range_editor_text.py index 1db4de1ed..b20688165 100644 --- a/traitsui/tests/editors/test_range_editor_text.py +++ b/traitsui/tests/editors/test_range_editor_text.py @@ -31,8 +31,7 @@ class NumberWithRangeEditor(HasTraits): - """Dialog containing a RangeEditor in 'spinner' mode for an Int. - """ + """Dialog containing a RangeEditor in 'spinner' mode for an Int.""" number = Int() @@ -44,8 +43,7 @@ class NumberWithRangeEditor(HasTraits): class FloatWithRangeEditor(HasTraits): - """Dialog containing a RangeEditor in 'spinner' mode for an Int. - """ + """Dialog containing a RangeEditor in 'spinner' mode for an Int.""" number = Float(5.0) @@ -55,7 +53,6 @@ class FloatWithRangeEditor(HasTraits): class TestRangeEditorText(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) diff --git a/traitsui/tests/editors/test_set_editor.py b/traitsui/tests/editors/test_set_editor.py index 474733da1..1112d77fb 100644 --- a/traitsui/tests/editors/test_set_editor.py +++ b/traitsui/tests/editors/test_set_editor.py @@ -47,7 +47,7 @@ def get_view(can_move_all=True, ordered=False): def get_list_items(list_widget): - """ Return a list of strings from the list widget. """ + """Return a list of strings from the list widget.""" items = [] if is_wx(): @@ -65,7 +65,7 @@ def get_list_items(list_widget): def click_on_item(editor, item_idx, in_used=False): - """ Simulate a click on an item in a specified list. + """Simulate a click on an item in a specified list. The function deselects all items in both used and unused lists, then selects an item at index item_idx either in the used list (if @@ -111,7 +111,7 @@ def click_on_item(editor, item_idx, in_used=False): def double_click_on_item(editor, item_idx, in_used=False): - """ Simulate a double click on an item in a specified list. + """Simulate a double click on an item in a specified list. The function deselects all items in both used and unused lists, then selects an item at index item_idx either in the used list (if @@ -158,7 +158,6 @@ def double_click_on_item(editor, item_idx, in_used=False): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestSetEditorMapping(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -175,8 +174,7 @@ class IntListModel(HasTraits): value = List() set_editor_factory = SetEditor( - values=[0, 1], - format_func=lambda v: str(bool(v)).upper() + values=[0, 1], format_func=lambda v: str(bool(v)).upper() ) formatted_view = View( UItem( @@ -186,22 +184,19 @@ class IntListModel(HasTraits): ) ) - with reraise_exceptions(), \ - self.setup_ui(IntListModel(), formatted_view) as editor: + with reraise_exceptions(), self.setup_ui( + IntListModel(), formatted_view + ) as editor: self.assertEqual(editor.names, ["FALSE", "TRUE"]) self.assertEqual(editor.mapping, {"FALSE": 0, "TRUE": 1}) - self.assertEqual( - editor.inverse_mapping, {0: "FALSE", 1: "TRUE"} - ) + self.assertEqual(editor.inverse_mapping, {0: "FALSE", 1: "TRUE"}) set_editor_factory.values = [1, 0] self.assertEqual(editor.names, ["TRUE", "FALSE"]) self.assertEqual(editor.mapping, {"TRUE": 1, "FALSE": 0}) - self.assertEqual( - editor.inverse_mapping, {1: "TRUE", 0: "FALSE"} - ) + self.assertEqual(editor.inverse_mapping, {1: "TRUE", 0: "FALSE"}) def test_simple_editor_mapping_name(self): class IntListModel(HasTraits): @@ -220,27 +215,23 @@ class IntListModel(HasTraits): ) model = IntListModel() - with reraise_exceptions(), \ - self.setup_ui(model, formatted_view) as editor: + with reraise_exceptions(), self.setup_ui( + model, formatted_view + ) as editor: self.assertEqual(editor.names, ["FALSE", "TRUE"]) self.assertEqual(editor.mapping, {"FALSE": 0, "TRUE": 1}) - self.assertEqual( - editor.inverse_mapping, {0: "FALSE", 1: "TRUE"} - ) + self.assertEqual(editor.inverse_mapping, {0: "FALSE", 1: "TRUE"}) model.possible_values = [1, 0] self.assertEqual(editor.names, ["TRUE", "FALSE"]) self.assertEqual(editor.mapping, {"TRUE": 1, "FALSE": 0}) - self.assertEqual( - editor.inverse_mapping, {1: "TRUE", 0: "FALSE"} - ) + self.assertEqual(editor.inverse_mapping, {1: "TRUE", 0: "FALSE"}) @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestSimpleSetEditor(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -255,8 +246,7 @@ def setup_gui(self, model, view): def test_simple_set_editor_use_button(self): # Initiate with non-alphabetical list model = ListModel(value=["two", "one"]) - with reraise_exceptions(), \ - self.setup_gui(model, get_view()) as editor: + with reraise_exceptions(), self.setup_gui(model, get_view()) as editor: self.assertEqual(get_list_items(editor._unused), ["four", "three"]) # Used list is sorted alphabetically @@ -279,8 +269,9 @@ def test_simple_set_editor_use_button(self): self.assertEqual(editor._get_selected_strings(editor._used), []) def test_simple_set_editor_unuse_button(self): - with reraise_exceptions(), \ - self.setup_gui(ListModel(), get_view()) as editor: + with reraise_exceptions(), self.setup_gui( + ListModel(), get_view() + ) as editor: self.assertEqual(get_list_items(editor._unused), ["four", "three"]) self.assertEqual(get_list_items(editor._used), ["one", "two"]) @@ -301,8 +292,9 @@ def test_simple_set_editor_unuse_button(self): self.assertEqual(get_list_items(editor._used), ["two"]) def test_simple_set_editor_use_dclick(self): - with reraise_exceptions(), \ - self.setup_gui(ListModel(), get_view()) as editor: + with reraise_exceptions(), self.setup_gui( + ListModel(), get_view() + ) as editor: self.assertEqual(get_list_items(editor._unused), ["four", "three"]) self.assertEqual(get_list_items(editor._used), ["one", "two"]) @@ -318,8 +310,9 @@ def test_simple_set_editor_use_dclick(self): self.assertEqual(editor._get_selected_strings(editor._used), []) def test_simple_set_editor_unuse_dclick(self): - with reraise_exceptions(), \ - self.setup_gui(ListModel(), get_view()) as editor: + with reraise_exceptions(), self.setup_gui( + ListModel(), get_view() + ) as editor: self.assertEqual(get_list_items(editor._unused), ["four", "three"]) self.assertEqual(get_list_items(editor._used), ["one", "two"]) @@ -334,8 +327,9 @@ def test_simple_set_editor_unuse_dclick(self): self.assertEqual(get_list_items(editor._used), ["two"]) def test_simple_set_editor_use_all(self): - with reraise_exceptions(), \ - self.setup_gui(ListModel(), get_view()) as editor: + with reraise_exceptions(), self.setup_gui( + ListModel(), get_view() + ) as editor: self.assertEqual(get_list_items(editor._unused), ["four", "three"]) self.assertEqual(get_list_items(editor._used), ["one", "two"]) @@ -356,8 +350,9 @@ def test_simple_set_editor_use_all(self): ) def test_simple_set_editor_unuse_all(self): - with reraise_exceptions(), \ - self.setup_gui(ListModel(), get_view()) as editor: + with reraise_exceptions(), self.setup_gui( + ListModel(), get_view() + ) as editor: self.assertEqual(get_list_items(editor._unused), ["four", "three"]) self.assertEqual(get_list_items(editor._used), ["one", "two"]) @@ -378,8 +373,9 @@ def test_simple_set_editor_unuse_all(self): self.assertEqual(get_list_items(editor._used), []) def test_simple_set_editor_move_up(self): - with reraise_exceptions(), \ - self.setup_gui(ListModel(), get_view(ordered=True)) as editor: + with reraise_exceptions(), self.setup_gui( + ListModel(), get_view(ordered=True) + ) as editor: self.assertEqual(get_list_items(editor._unused), ["four", "three"]) self.assertEqual(get_list_items(editor._used), ["one", "two"]) @@ -397,8 +393,9 @@ def test_simple_set_editor_move_up(self): self.assertEqual(get_list_items(editor._used), ["two", "one"]) def test_simple_set_editor_move_down(self): - with reraise_exceptions(), \ - self.setup_gui(ListModel(), get_view(ordered=True)) as editor: + with reraise_exceptions(), self.setup_gui( + ListModel(), get_view(ordered=True) + ) as editor: self.assertEqual(get_list_items(editor._unused), ["four", "three"]) self.assertEqual(get_list_items(editor._used), ["one", "two"]) @@ -416,8 +413,9 @@ def test_simple_set_editor_move_down(self): self.assertEqual(get_list_items(editor._used), ["two", "one"]) def test_simple_set_editor_use_all_button(self): - with reraise_exceptions(), \ - self.setup_gui(ListModel(), get_view()) as editor: + with reraise_exceptions(), self.setup_gui( + ListModel(), get_view() + ) as editor: self.assertEqual(get_list_items(editor._unused), ["four", "three"]) self.assertEqual(get_list_items(editor._used), ["one", "two"]) @@ -438,8 +436,9 @@ def test_simple_set_editor_use_all_button(self): ) def test_simple_set_editor_unuse_all_button(self): - with reraise_exceptions(), \ - self.setup_gui(ListModel(), get_view()) as editor: + with reraise_exceptions(), self.setup_gui( + ListModel(), get_view() + ) as editor: self.assertEqual(get_list_items(editor._unused), ["four", "three"]) self.assertEqual(get_list_items(editor._used), ["one", "two"]) @@ -460,8 +459,9 @@ def test_simple_set_editor_unuse_all_button(self): self.assertEqual(get_list_items(editor._used), []) def test_simple_set_editor_default_selection_unused(self): - with reraise_exceptions(), \ - self.setup_gui(ListModel(), get_view()) as editor: + with reraise_exceptions(), self.setup_gui( + ListModel(), get_view() + ) as editor: self.assertEqual(get_list_items(editor._unused), ["four", "three"]) self.assertEqual(get_list_items(editor._used), ["one", "two"]) @@ -470,9 +470,7 @@ def test_simple_set_editor_default_selection_unused(self): process_cascade_events() # Button inserts at the top - self.assertEqual( - get_list_items(editor._unused), ["three"] - ) + self.assertEqual(get_list_items(editor._unused), ["three"]) self.assertEqual( get_list_items(editor._used), ["four", "one", "two"] ) @@ -481,12 +479,14 @@ def test_simple_set_editor_default_selection_used(self): # When all items are used, top used item is selected by default list_edit = ListModel(value=["one", "two", "three", "four"]) - with reraise_exceptions(), \ - self.setup_gui(list_edit, get_view()) as editor: + with reraise_exceptions(), self.setup_gui( + list_edit, get_view() + ) as editor: self.assertEqual(get_list_items(editor._unused), []) self.assertEqual( - get_list_items(editor._used), ["four", "one", "three", "two"]) + get_list_items(editor._used), ["four", "one", "three", "two"] + ) click_button(editor._unuse) process_cascade_events() @@ -499,11 +499,16 @@ def test_simple_set_editor_default_selection_used(self): def test_simple_set_editor_deleted_valid_values(self): editor_factory = SetEditor(values=["one", "two", "three", "four"]) - view = View(UItem("value", editor=editor_factory, style="simple",)) + view = View( + UItem( + "value", + editor=editor_factory, + style="simple", + ) + ) list_edit = ListModel() - with reraise_exceptions(), \ - self.setup_gui(list_edit, view) as editor: + with reraise_exceptions(), self.setup_gui(list_edit, view) as editor: self.assertEqual(get_list_items(editor._unused), ["four", "three"]) self.assertEqual(get_list_items(editor._used), ["one", "two"]) @@ -524,8 +529,9 @@ def test_simple_set_editor_deleted_valid_values(self): def test_simple_set_editor_use_ordered_selected(self): # Initiate with non-alphabetical list model = ListModel(value=["two", "one"]) - with reraise_exceptions(), \ - self.setup_gui(model, get_view(ordered=True)) as editor: + with reraise_exceptions(), self.setup_gui( + model, get_view(ordered=True) + ) as editor: self.assertEqual(get_list_items(editor._unused), ["four", "three"]) # Used list maintains the order @@ -550,16 +556,16 @@ def test_simple_set_editor_use_ordered_selected(self): ) def test_simple_set_editor_unordeder_button_existence(self): - with reraise_exceptions(), \ - self.setup_gui(ListModel(), get_view()) as editor: + with reraise_exceptions(), self.setup_gui( + ListModel(), get_view() + ) as editor: self.assertIsNone(editor._up) self.assertIsNone(editor._down) def test_simple_set_editor_cant_move_all_button_existence(self): view = get_view(can_move_all=False) - with reraise_exceptions(), \ - self.setup_gui(ListModel(), view) as editor: + with reraise_exceptions(), self.setup_gui(ListModel(), view) as editor: self.assertIsNone(editor._use_all) self.assertIsNone(editor._unuse_all) diff --git a/traitsui/tests/editors/test_shell_editor.py b/traitsui/tests/editors/test_shell_editor.py index 0717f56c5..a54c96565 100644 --- a/traitsui/tests/editors/test_shell_editor.py +++ b/traitsui/tests/editors/test_shell_editor.py @@ -45,7 +45,6 @@ def get_dict_view(share=False): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestShellEditor(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) diff --git a/traitsui/tests/editors/test_styled_date_editor.py b/traitsui/tests/editors/test_styled_date_editor.py index 725f5ab06..5dcce05f3 100644 --- a/traitsui/tests/editors/test_styled_date_editor.py +++ b/traitsui/tests/editors/test_styled_date_editor.py @@ -46,7 +46,6 @@ def get_example_model(): # StyledDateEditor is currently only implemented for Qt @requires_toolkit([ToolkitName.qt]) class TestStyledDateEditor(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -66,6 +65,5 @@ def test_init_and_dispose(self): style="custom", ) ) - with reraise_exceptions(), \ - create_ui(instance, dict(view=view)): + with reraise_exceptions(), create_ui(instance, dict(view=view)): pass diff --git a/traitsui/tests/editors/test_table_editor.py b/traitsui/tests/editors/test_table_editor.py index 6cd0fbc72..c29c86d29 100644 --- a/traitsui/tests/editors/test_table_editor.py +++ b/traitsui/tests/editors/test_table_editor.py @@ -14,7 +14,12 @@ from traits.api import HasTraits, Instance, Int, List, Str, Tuple from traitsui.api import ( - Action, EvalTableFilter, Item, ObjectColumn, TableEditor, View, + Action, + EvalTableFilter, + Item, + ObjectColumn, + TableEditor, + View, ) from traitsui.tests._tools import ( BaseTestMixin, @@ -29,7 +34,7 @@ class ListItem(HasTraits): - """ Items to visualize in a table editor """ + """Items to visualize in a table editor""" value = Str() other_value = Int() @@ -273,7 +278,6 @@ class ObjectList(HasTraits): class TestTableEditor(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -286,8 +290,9 @@ def test_table_editor(self): values=[ListItem(value=str(i ** 2)) for i in range(10)] ) - with reraise_exceptions(), \ - create_ui(object_list, dict(view=simple_view)): + with reraise_exceptions(), create_ui( + object_list, dict(view=simple_view) + ): process_cascade_events() @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) @@ -296,8 +301,9 @@ def test_filtered_table_editor(self): values=[ListItem(value=str(i ** 2)) for i in range(10)] ) - with reraise_exceptions(), \ - create_ui(object_list, dict(view=filtered_view)) as ui: + with reraise_exceptions(), create_ui( + object_list, dict(view=filtered_view) + ) as ui: process_cascade_events() filter = ui.get_editors("values")[0].filter @@ -313,8 +319,9 @@ def test_table_editor_select_row(self): ) object_list.selected = object_list.values[5] - with reraise_exceptions(), \ - create_ui(object_list, dict(view=select_row_view)) as ui: + with reraise_exceptions(), create_ui( + object_list, dict(view=select_row_view) + ) as ui: editor = ui.get_editors("values")[0] process_cascade_events() if is_qt(): @@ -333,8 +340,9 @@ def test_table_editor_select_rows(self): ) object_list.selections = object_list.values[5:7] - with reraise_exceptions(), \ - create_ui(object_list, dict(view=select_rows_view)) as ui: + with reraise_exceptions(), create_ui( + object_list, dict(view=select_rows_view) + ) as ui: editor = ui.get_editors("values")[0] process_cascade_events() if is_qt(): @@ -353,8 +361,9 @@ def test_table_editor_select_row_index(self): ) object_list.selected_index = 5 - with reraise_exceptions(), \ - create_ui(object_list, dict(view=select_row_index_view)) as ui: + with reraise_exceptions(), create_ui( + object_list, dict(view=select_row_index_view) + ) as ui: editor = ui.get_editors("values")[0] process_cascade_events() if is_qt(): @@ -374,8 +383,9 @@ def test_table_editor_select_row_indices(self): object_list.selected_indices = [5, 7, 8] view = select_row_indices_view - with reraise_exceptions(), \ - create_ui(object_list, dict(view=view)) as ui: + with reraise_exceptions(), create_ui( + object_list, dict(view=view) + ) as ui: editor = ui.get_editors("values")[0] process_cascade_events() if is_qt(): @@ -394,8 +404,9 @@ def test_table_editor_select_column(self): ) object_list.selected_column = "value" - with reraise_exceptions(), \ - create_ui(object_list, dict(view=select_column_view)) as ui: + with reraise_exceptions(), create_ui( + object_list, dict(view=select_column_view) + ) as ui: editor = ui.get_editors("values")[0] process_cascade_events() if is_qt(): @@ -414,8 +425,9 @@ def test_table_editor_select_columns(self): ) object_list.selected_columns = ["value", "other_value"] - with reraise_exceptions(), \ - create_ui(object_list, dict(view=select_columns_view)) as ui: + with reraise_exceptions(), create_ui( + object_list, dict(view=select_columns_view) + ) as ui: editor = ui.get_editors("values")[0] process_cascade_events() if is_qt(): @@ -435,8 +447,9 @@ def test_table_editor_select_column_index(self): object_list.selected_index = 1 view = select_column_index_view - with reraise_exceptions(), \ - create_ui(object_list, dict(view=view)) as ui: + with reraise_exceptions(), create_ui( + object_list, dict(view=view) + ) as ui: editor = ui.get_editors("values")[0] process_cascade_events() if is_qt(): @@ -456,8 +469,9 @@ def test_table_editor_select_column_indices(self): object_list.selected_indices = [0, 1] view = select_column_indices_view - with reraise_exceptions(), \ - create_ui(object_list, dict(view=view)) as ui: + with reraise_exceptions(), create_ui( + object_list, dict(view=view) + ) as ui: editor = ui.get_editors("values")[0] process_cascade_events() if is_qt(): @@ -476,8 +490,9 @@ def test_table_editor_select_cell(self): ) object_list.selected_cell = (object_list.values[5], "value") - with reraise_exceptions(), \ - create_ui(object_list, dict(view=select_cell_view)) as ui: + with reraise_exceptions(), create_ui( + object_list, dict(view=select_cell_view) + ) as ui: editor = ui.get_editors("values")[0] process_cascade_events() if is_qt(): @@ -500,8 +515,9 @@ def test_table_editor_select_cells(self): (object_list.values[8], "value"), ] - with reraise_exceptions(), \ - create_ui(object_list, dict(view=select_cells_view)) as ui: + with reraise_exceptions(), create_ui( + object_list, dict(view=select_cells_view) + ) as ui: editor = ui.get_editors("values")[0] process_cascade_events() if is_qt(): @@ -511,11 +527,14 @@ def test_table_editor_select_cells(self): process_cascade_events() - self.assertEqual(selected, [ - (object_list.values[5], "value"), - (object_list.values[6], "other value"), - (object_list.values[8], "value"), - ]) + self.assertEqual( + selected, + [ + (object_list.values[5], "value"), + (object_list.values[6], "other value"), + (object_list.values[8], "value"), + ], + ) @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) def test_table_editor_select_cell_index(self): @@ -525,8 +544,9 @@ def test_table_editor_select_cell_index(self): object_list.selected_cell_index = (5, 1) view = select_cell_index_view - with reraise_exceptions(), \ - create_ui(object_list, dict(view=view)) as ui: + with reraise_exceptions(), create_ui( + object_list, dict(view=view) + ) as ui: editor = ui.get_editors("values")[0] process_cascade_events() if is_qt(): @@ -546,8 +566,9 @@ def test_table_editor_select_cell_indices(self): object_list.selected_cell_indices = [(5, 0), (6, 1), (8, 0)] view = select_cell_indices_view - with reraise_exceptions(), \ - create_ui(object_list, dict(view=view)) as ui: + with reraise_exceptions(), create_ui( + object_list, dict(view=view) + ) as ui: editor = ui.get_editors("values")[0] process_cascade_events() if is_qt(): @@ -580,8 +601,9 @@ def test_progress_column(self): values=[ListItem(value=str(i ** 2)) for i in range(10)] ) - with reraise_exceptions(), \ - create_ui(object_list, dict(view=progress_view)): + with reraise_exceptions(), create_ui( + object_list, dict(view=progress_view) + ): process_cascade_events() @requires_toolkit([ToolkitName.qt]) @@ -594,8 +616,9 @@ def test_on_perform_action(self): mock_function = Mock() action = Action(on_perform=mock_function) - with reraise_exceptions(), \ - create_ui(object_list, dict(view=simple_view)) as ui: + with reraise_exceptions(), create_ui( + object_list, dict(view=simple_view) + ) as ui: editor = ui.get_editors("values")[0] process_cascade_events() editor.set_menu_context(None, None, None) diff --git a/traitsui/tests/editors/test_tabular_editor.py b/traitsui/tests/editors/test_tabular_editor.py index 89ab28b7c..388f6ddb2 100644 --- a/traitsui/tests/editors/test_tabular_editor.py +++ b/traitsui/tests/editors/test_tabular_editor.py @@ -89,10 +89,10 @@ def get_view(multi_select=False): def get_selected_rows(editor): - """ Returns a list of all currently selected rows. - """ + """Returns a list of all currently selected rows.""" if is_wx(): import wx + # "item" in this context means "row number" item = -1 selected = [] @@ -114,8 +114,7 @@ def get_selected_rows(editor): def set_selected_single(editor, row): - """ Selects a specified row in an editor with multi_select=False. - """ + """Selects a specified row in an editor with multi_select=False.""" if is_wx(): editor.control.Select(row) @@ -134,7 +133,7 @@ def set_selected_single(editor, row): def set_selected_multiple(editor, rows): - """ Clears old selection and selects specified rows in an editor + """Clears old selection and selects specified rows in an editor with multi_select=True. """ if is_wx(): @@ -159,8 +158,7 @@ def set_selected_multiple(editor, rows): def clear_selection(editor): - """ Clears existing selection. - """ + """Clears existing selection.""" if is_wx(): import wx @@ -180,7 +178,6 @@ def clear_selection(editor): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestTabularEditor(BaseTestMixin, UnittestTools, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -190,8 +187,10 @@ def tearDown(self): @unittest.skipIf(is_wx(), "Issue enthought/traitsui#752") def test_tabular_editor_single_selection(self): - with reraise_exceptions(), \ - self.report_and_editor(get_view()) as (report, editor): + with reraise_exceptions(), self.report_and_editor(get_view()) as ( + report, + editor, + ): process_cascade_events() people = report.people @@ -216,8 +215,10 @@ def test_tabular_editor_single_selection(self): def test_tabular_editor_multi_selection(self): view = get_view(multi_select=True) - with reraise_exceptions(), \ - self.report_and_editor(view) as (report, editor): + with reraise_exceptions(), self.report_and_editor(view) as ( + report, + editor, + ): process_cascade_events() people = report.people @@ -245,8 +246,10 @@ def test_tabular_editor_multi_selection(self): @unittest.skipIf(is_wx(), "Issue enthought/traitsui#752") def test_tabular_editor_single_selection_changed(self): - with reraise_exceptions(), \ - self.report_and_editor(get_view()) as (report, editor): + with reraise_exceptions(), self.report_and_editor(get_view()) as ( + report, + editor, + ): process_cascade_events() people = report.people @@ -282,8 +285,10 @@ def test_tabular_editor_single_selection_changed(self): def test_tabular_editor_multi_selection_changed(self): view = get_view(multi_select=True) - with reraise_exceptions(), \ - self.report_and_editor(view) as (report, editor): + with reraise_exceptions(), self.report_and_editor(view) as ( + report, + editor, + ): process_cascade_events() people = report.people @@ -320,8 +325,10 @@ def test_tabular_editor_multi_selection_changed(self): def test_tabular_editor_multi_selection_items_changed(self): view = get_view(multi_select=True) - with reraise_exceptions(), \ - self.report_and_editor(view) as (report, editor): + with reraise_exceptions(), self.report_and_editor(view) as ( + report, + editor, + ): process_cascade_events() people = report.people @@ -393,12 +400,15 @@ def test_event_synchronization(self): @unittest.skipIf(is_wx(), "Issue enthought/traitsui#752") def test_adapter_columns_changes(self): # Regression test for enthought/traitsui#894 - with reraise_exceptions(), \ - self.report_and_editor(get_view()) as (report, editor): + with reraise_exceptions(), self.report_and_editor(get_view()) as ( + report, + editor, + ): # Reproduce the scenario when the column count is reduced. editor.adapter.columns = [ - ("Name", "name"), ("Age", "age"), + ("Name", "name"), + ("Age", "age"), ] # Recalculating column widths take into account the user defined # widths, cached in the view. The cache should be invalidated @@ -413,8 +423,10 @@ def test_view_column_resized_attribute_error_workaround(self): # using it while resizing the columns. # The resize event is processed after UI.dispose is called. # Maybe related to enthought/traits#431 - with reraise_exceptions(), \ - self.report_and_editor(get_view()) as (_, editor): + with reraise_exceptions(), self.report_and_editor(get_view()) as ( + _, + editor, + ): editor.adapter.columns = [("Name", "name")] @contextlib.contextmanager @@ -431,5 +443,5 @@ def report_and_editor(self, view): ] ) with create_ui(report, dict(view=view)) as ui: - editor, = ui.get_editors("people") + (editor,) = ui.get_editors("people") yield report, editor diff --git a/traitsui/tests/editors/test_text_editor.py b/traitsui/tests/editors/test_text_editor.py index 479e0f10f..05c4bed8c 100644 --- a/traitsui/tests/editors/test_text_editor.py +++ b/traitsui/tests/editors/test_text_editor.py @@ -25,7 +25,7 @@ KeySequence, MouseClick, InteractionNotSupported, - UITester + UITester, ) from traitsui.tests._tools import ( BaseTestMixin, @@ -44,7 +44,7 @@ class Foo(HasTraits): def get_view(style, auto_set): - """ Return the default view for the Foo object. + """Return the default view for the Foo object. Parameters ---------- @@ -62,8 +62,9 @@ def get_view(style, auto_set): @requires_toolkit([ToolkitName.qt]) @unittest.skipIf(no_gui_test_assistant, "No GuiTestAssistant") class TestTextEditorQt( - BaseTestMixin, GuiTestAssistant, UnittestTools, unittest.TestCase): - """ Test on TextEditor with Qt backend.""" + BaseTestMixin, GuiTestAssistant, UnittestTools, unittest.TestCase +): + """Test on TextEditor with Qt backend.""" def setUp(self): BaseTestMixin.setUp(self) @@ -82,7 +83,7 @@ def test_text_editor_placeholder_text(self): tester = UITester() with tester.create_ui(foo, dict(view=view)) as ui: - name_editor, = ui.get_editors("name") + (name_editor,) = ui.get_editors("name") self.assertEqual( name_editor.control.placeholderText(), "Enter name", @@ -98,7 +99,7 @@ def test_text_editor_placeholder_text_and_readonly(self): view = View(Item(name="name", editor=editor)) tester = UITester() with tester.create_ui(foo, dict(view=view)) as ui: - name_editor, = ui.get_editors("name") + (name_editor,) = ui.get_editors("name") self.assertEqual( name_editor.control.placeholderText(), "Enter name", @@ -108,7 +109,7 @@ def test_text_editor_default_view(self): foo = Foo() tester = UITester() with tester.create_ui(foo) as ui: - name_editor, = ui.get_editors("name") + (name_editor,) = ui.get_editors("name") self.assertEqual( name_editor.control.placeholderText(), "", @@ -117,14 +118,16 @@ def test_text_editor_default_view(self): def test_text_editor_custom_style_placeholder(self): # Test against CustomEditor using QTextEdit foo = Foo() - view = View(Item( - name="name", - style="custom", - editor=TextEditor(placeholder="Enter name"), - )) + view = View( + Item( + name="name", + style="custom", + editor=TextEditor(placeholder="Enter name"), + ) + ) tester = UITester() with tester.create_ui(foo, dict(view=view)) as ui: - name_editor, = ui.get_editors("name") + (name_editor,) = ui.get_editors("name") try: placeholder = name_editor.control.placeholderText() except AttributeError: @@ -144,7 +147,7 @@ def test_cancel_button(self): ) tester = UITester() with tester.create_ui(foo, dict(view=view)) as ui: - name_editor, = ui.get_editors("name") + (name_editor,) = ui.get_editors("name") # isClearButtonEnabled is introduced to QLineEdit since Qt 5.2 if hasattr(name_editor.control, 'isClearButtonEnabled'): self.assertTrue(name_editor.control.isClearButtonEnabled()) @@ -154,9 +157,10 @@ def test_cancel_button(self): # Not running them now to avoid test interaction. See enthought/traitsui#752 @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestTextEditor(BaseTestMixin, unittest.TestCase, UnittestTools): - """ Tests that can be run with any toolkit as long as there is an + """Tests that can be run with any toolkit as long as there is an implementation for simulating user interactions. """ + def setUp(self): BaseTestMixin.setUp(self) @@ -231,12 +235,10 @@ def test_simple_auto_set_false_do_not_update_qt(self): def test_simple_auto_set_false_do_not_update_wx(self): foo = Foo(name="") view = View( - Item("name", - editor=TextEditor(auto_set=False), - style="simple"), - Item("nickname", - editor=TextEditor(auto_set=False), - style="simple") + Item("name", editor=TextEditor(auto_set=False), style="simple"), + Item( + "nickname", editor=TextEditor(auto_set=False), style="simple" + ), ) tester = UITester() with tester.create_ui(foo, dict(view=view)) as ui: @@ -287,12 +289,10 @@ def test_custom_auto_set_false_update_text(self): def test_custom_auto_set_false_do_not_update_wx(self): foo = Foo(name="") view = View( - Item("name", - editor=TextEditor(auto_set=False), - style="custom"), - Item("nickname", - editor=TextEditor(auto_set=False), - style="custom") + Item("name", editor=TextEditor(auto_set=False), style="custom"), + Item( + "nickname", editor=TextEditor(auto_set=False), style="custom" + ), ) tester = UITester() with tester.create_ui(foo, dict(view=view)) as ui: @@ -335,32 +335,32 @@ def check_format_func_used(self, style): ) tester = UITester() with tester.create_ui(foo, dict(view=view)) as ui: - display_name = ( - tester.find_by_name(ui, "name").inspect(DisplayedText()) + display_name = tester.find_by_name(ui, "name").inspect( + DisplayedText() ) - display_nickname = ( - tester.find_by_name(ui, "nickname").inspect(DisplayedText()) + display_nickname = tester.find_by_name(ui, "nickname").inspect( + DisplayedText() ) self.assertEqual(display_name, "WILLIAM") self.assertEqual(display_nickname, "bill") @unittest.skipUnless( Version(TRAITS_VERSION) >= Version("6.1.0"), - "This test requires traits >= 6.1.0" + "This test requires traits >= 6.1.0", ) def test_format_func_used_simple(self): self.check_format_func_used(style='simple') @unittest.skipUnless( Version(TRAITS_VERSION) >= Version("6.1.0"), - "This test requires traits >= 6.1.0" + "This test requires traits >= 6.1.0", ) def test_format_func_used_custom(self): self.check_format_func_used(style='custom') @unittest.skipUnless( Version(TRAITS_VERSION) >= Version("6.1.0"), - "This test requires traits >= 6.1.0" + "This test requires traits >= 6.1.0", ) def test_format_func_used_readonly(self): self.check_format_func_used(style='readonly') diff --git a/traitsui/tests/editors/test_tree_editor.py b/traitsui/tests/editors/test_tree_editor.py index 433d3fd14..a0cba751a 100644 --- a/traitsui/tests/editors/test_tree_editor.py +++ b/traitsui/tests/editors/test_tree_editor.py @@ -33,13 +33,13 @@ class BogusWrap(HasTraits): - """ A bogus class representing a bogus tree. """ + """A bogus class representing a bogus tree.""" name = Str("Totally bogus") class Bogus(HasTraits): - """ A bogus class representing a bogus tree. """ + """A bogus class representing a bogus tree.""" name = Str("Bogus") @@ -58,7 +58,7 @@ def object_expand_all_changed(self, info): class BogusTreeView(HasTraits): - """ A traitsui view visualizing Bogus objects as trees. """ + """A traitsui view visualizing Bogus objects as trees.""" bogus = Instance(Bogus) @@ -73,7 +73,7 @@ class BogusTreeView(HasTraits): def _nodes_default(self): return [ TreeNode(node_for=[Bogus], children="bogus_list", label="=Bogus"), - TreeNode(node_for=[BogusWrap], label='name') + TreeNode(node_for=[BogusWrap], label='name'), ] def default_traits_view(self): @@ -95,7 +95,7 @@ def default_traits_view(self): class BogusTreeNodeObject(TreeNodeObject): - """ A bogus tree node. """ + """A bogus tree node.""" name = Str("Bogus") @@ -103,7 +103,7 @@ class BogusTreeNodeObject(TreeNodeObject): class BogusTreeNodeObjectView(HasTraits): - """ A traitsui view visualizing Bogus objects as trees. """ + """A traitsui view visualizing Bogus objects as trees.""" bogus = Instance(BogusTreeNodeObject) @@ -133,7 +133,6 @@ def default_traits_view(self): class TestTreeView(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -159,8 +158,9 @@ def test_tree_editor_with_nested_ui(self): bogus_list = [Bogus()] object_view = BogusTreeView(bogus=Bogus(bogus_list=bogus_list)) view = View(Item("bogus", id="tree", editor=tree_editor)) - with reraise_exceptions(), \ - create_ui(object_view, dict(view=view)) as ui: + with reraise_exceptions(), create_ui( + object_view, dict(view=view) + ) as ui: editor = ui.info.tree editor.selected = bogus_list[0] GUI.process_events() @@ -168,7 +168,7 @@ def test_tree_editor_with_nested_ui(self): def _test_tree_editor_releases_listeners( self, hide_root, nodes=None, trait="bogus_list", expected_listeners=1 ): - """ The TreeEditor should release the listener to the root node's children + """The TreeEditor should release the listener to the root node's children when it's disposed of. """ @@ -190,7 +190,7 @@ def _test_tree_editor_releases_listeners( def _test_tree_node_object_releases_listeners( self, hide_root, nodes=None, trait="bogus_list", expected_listeners=1 ): - """ The TreeEditor should release the listener to the root node's children + """The TreeEditor should release the listener to the root node's children when it's disposed of. """ diff --git a/traitsui/tests/editors/test_tuple_editor.py b/traitsui/tests/editors/test_tuple_editor.py index cca98b091..dc9a30cf6 100644 --- a/traitsui/tests/editors/test_tuple_editor.py +++ b/traitsui/tests/editors/test_tuple_editor.py @@ -24,8 +24,7 @@ class TupleEditor(HasTraits): - """Dialog containing a Tuple of two Int's. - """ + """Dialog containing a Tuple of two Int's.""" tup = Tuple(Int, Int, Str) @@ -35,7 +34,6 @@ class TupleEditor(HasTraits): class TestTupleEditor(BaseTestMixin, unittest.TestCase, UnittestTools): - def setUp(self): BaseTestMixin.setUp(self) diff --git a/traitsui/tests/editors/test_video_editor.py b/traitsui/tests/editors/test_video_editor.py index 8b4b93571..e8d5cb52a 100644 --- a/traitsui/tests/editors/test_video_editor.py +++ b/traitsui/tests/editors/test_video_editor.py @@ -40,7 +40,6 @@ class MovieTheater(HasTraits): @unittest.skipIf(not is_qt5(), 'Requires Qt5') class TestVideoEditor(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) diff --git a/traitsui/tests/null_backend/test_font_trait.py b/traitsui/tests/null_backend/test_font_trait.py index 24043feb3..e1fcc415c 100644 --- a/traitsui/tests/null_backend/test_font_trait.py +++ b/traitsui/tests/null_backend/test_font_trait.py @@ -17,7 +17,6 @@ class TestFontTrait(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) diff --git a/traitsui/tests/null_backend/test_null_toolkit.py b/traitsui/tests/null_backend/test_null_toolkit.py index aecc063c3..8d5124666 100644 --- a/traitsui/tests/null_backend/test_null_toolkit.py +++ b/traitsui/tests/null_backend/test_null_toolkit.py @@ -15,7 +15,6 @@ class TestNullToolkit(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -24,7 +23,7 @@ def tearDown(self): @requires_toolkit([ToolkitName.null]) def test_configure_traits_error(self): - """ Verify that configure_traits fails with NotImplementedError. """ + """Verify that configure_traits fails with NotImplementedError.""" class Test(HasTraits): x = Int() diff --git a/traitsui/tests/test_actions.py b/traitsui/tests/test_actions.py index 1e8e33d35..68c86962c 100644 --- a/traitsui/tests/test_actions.py +++ b/traitsui/tests/test_actions.py @@ -67,6 +67,7 @@ def test_clicked(self): # ----- qt4 helper functions + def _qt_trigger_action(container_class, ui): toolbar = ui.control.findChild(container_class) action = toolbar.actions()[0] @@ -82,7 +83,6 @@ def _qt_click_button(ui): class TestActions(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -90,8 +90,7 @@ def tearDown(self): BaseTestMixin.tearDown(self) def _test_actions(self, trigger_action_func): - """Template test for wx, qt4, menu, and toolbar testing. - """ + """Template test for wx, qt4, menu, and toolbar testing.""" # Behavior: when clicking on a menu or toolbar action, # the corresponding function should be executed diff --git a/traitsui/tests/test_color_column.py b/traitsui/tests/test_color_column.py index 6304209e2..ed7d279dc 100644 --- a/traitsui/tests/test_color_column.py +++ b/traitsui/tests/test_color_column.py @@ -50,7 +50,6 @@ class MyData(HasTraits): class TestColorColumn(BaseTestMixin, TestCase): - def setUp(self): BaseTestMixin.setUp(self) diff --git a/traitsui/tests/test_context_value.py b/traitsui/tests/test_context_value.py index 1a941a4ae..146e4c85a 100644 --- a/traitsui/tests/test_context_value.py +++ b/traitsui/tests/test_context_value.py @@ -29,7 +29,6 @@ class CVExample(HasTraits): class TestContextvalue(BaseTestMixin, UnittestTools, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) diff --git a/traitsui/tests/test_controller.py b/traitsui/tests/test_controller.py index 77fc69231..3ef446848 100644 --- a/traitsui/tests/test_controller.py +++ b/traitsui/tests/test_controller.py @@ -24,7 +24,7 @@ class FooModel(HasTraits): class FooController(Controller): - """ Test dialog that does nothing useful.""" + """Test dialog that does nothing useful.""" model = Instance(FooModel) @@ -33,7 +33,6 @@ def _model_default(self): class TestController(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) diff --git a/traitsui/tests/test_editor.py b/traitsui/tests/test_editor.py index 456354e51..1e8cf4551 100644 --- a/traitsui/tests/test_editor.py +++ b/traitsui/tests/test_editor.py @@ -12,7 +12,15 @@ from pyface.toolkit import toolkit_object from traits.api import ( - Any, Bool, Event, Float, HasTraits, Int, List, Range, Undefined + Any, + Bool, + Event, + Float, + HasTraits, + Int, + List, + Range, + Undefined, ) from traits.trait_base import xgetattr @@ -21,9 +29,7 @@ from traitsui.editor_factory import EditorFactory from traitsui.handler import default_handler from traitsui.ui import UI -from traitsui.testing.api import ( - KeyClick, KeySequence, Textbox, UITester -) +from traitsui.testing.api import KeyClick, KeySequence, Textbox, UITester from traitsui.tests._tools import ( BaseTestMixin, GuiTestAssistant, @@ -40,7 +46,7 @@ class FakeControl(HasTraits): - """ A pure Traits object that fakes being a control. + """A pure Traits object that fakes being a control. It can aither hold a value (mimicking a field), or have an event which is listened to (mimicking a button or similar control). @@ -57,7 +63,7 @@ class FakeControl(HasTraits): class StubEditorFactory(EditorFactory): - """ A minimal editor factory + """A minimal editor factory This simply holds state that may or may not be copied to the editor. No attempt is made to handle custom/readonly/etc. @@ -84,7 +90,7 @@ def _auxiliary_cv_float_default(self): class StubEditor(Editor): - """ A minimal editor implementaton for a StubEditorFactory. + """A minimal editor implementaton for a StubEditorFactory. The editor creates a FakeControl instance as its control object and keeps values synchronized either to `control_value` or @@ -152,7 +158,7 @@ def set_focus(self, parent): class UserObject(HasTraits): - """ A simple HasTraits class with a variety of state. """ + """A simple HasTraits class with a variety of state.""" #: The value being edited. user_value = Any("test") @@ -177,12 +183,12 @@ class UserObject(HasTraits): def create_editor( - context=None, - object_name="object", - name="user_value", - factory=None, - is_event=False, - description="", + context=None, + object_name="object", + name="user_value", + factory=None, + is_event=False, + description="", ): if context is None: user_object = UserObject() @@ -213,7 +219,6 @@ def create_editor( @unittest.skipIf(no_gui_test_assistant, "No GuiTestAssistant") class TestEditor(BaseTestMixin, GuiTestAssistant, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) GuiTestAssistant.setUp(self) @@ -286,9 +291,7 @@ def test_lifecycle(self): def test_context_object(self): user_object = UserObject(user_value="other_test") context = {"object": UserObject(), "other_object": user_object} - editor = create_editor( - context=context, object_name="other_object" - ) + editor = create_editor(context=context, object_name="other_object") self.assertEqual(editor.old_value, "other_test") self.assertEqual(editor.name, "user_value") @@ -812,7 +815,7 @@ def test_sync_value_to_chained(self): editor.auxiliary_value = 20 with self.assertTraitChanges( - user_object.user_auxiliary, "user_value", count=1 + user_object.user_auxiliary, "user_value", count=1 ): editor.sync_value( "object.user_auxiliary.user_value", "auxiliary_value", "to" @@ -821,7 +824,7 @@ def test_sync_value_to_chained(self): self.assertEqual(user_object.user_auxiliary.user_value, 20) with self.assertTraitChanges( - user_object.user_auxiliary, "user_value", count=1 + user_object.user_auxiliary, "user_value", count=1 ): editor.auxiliary_value = 11 @@ -830,7 +833,7 @@ def test_sync_value_to_chained(self): editor.dispose() with self.assertTraitDoesNotChange( - user_object.user_auxiliary, "user_value" + user_object.user_auxiliary, "user_value" ): editor.auxiliary_value = 12 @@ -939,7 +942,7 @@ def test_sync_value_both(self): @unittest.skipIf(no_modal_dialog_tester, "ModalDialogTester unavailable") @unittest.skipIf( is_mac_os, - "There is a separate issue on OSX. See enthought/traitsui#1550" + "There is a separate issue on OSX. See enthought/traitsui#1550", ) def test_editor_error_msg(self): from pyface.qt import QtCore, QtGui @@ -968,15 +971,15 @@ def check_and_close(mdtester): self.assertTrue( mdtester.has_widget( text="The 'x' trait of a Foo instance must be " - "0.0 < a floating point number <= 1.0, " - "but a value of 0.0 was " - "specified.", + "0.0 < a floating point number <= 1.0, " + "but a value of 0.0 was " + "specified.", type_=QtGui.QMessageBox, ) ) self.assertEqual( mdtester.get_dialog_widget().textFormat(), - QtCore.Qt.PlainText + QtCore.Qt.PlainText, ) finally: mdtester.close(accept=True) diff --git a/traitsui/tests/test_handler.py b/traitsui/tests/test_handler.py index 6c17010e6..d18d0765b 100644 --- a/traitsui/tests/test_handler.py +++ b/traitsui/tests/test_handler.py @@ -129,7 +129,6 @@ def _action_click(self): class TestHandler(BaseTestMixin, TestCase): - def setUp(self): BaseTestMixin.setUp(self) diff --git a/traitsui/tests/test_helper.py b/traitsui/tests/test_helper.py index 7ed53bb80..5ba6cc1d3 100644 --- a/traitsui/tests/test_helper.py +++ b/traitsui/tests/test_helper.py @@ -15,7 +15,6 @@ class TestComputeColumnWidths(BaseTestMixin, TestCase): - def setUp(self): BaseTestMixin.setUp(self) diff --git a/traitsui/tests/test_labels.py b/traitsui/tests/test_labels.py index 95bbc07f3..ee278219b 100644 --- a/traitsui/tests/test_labels.py +++ b/traitsui/tests/test_labels.py @@ -34,8 +34,7 @@ class ShowRightLabelsDialog(HasTraits): - """ Dialog with labels on the left/right to test the label text. - """ + """Dialog with labels on the left/right to test the label text.""" bool_item = Bool(True) @@ -48,7 +47,7 @@ class ShowRightLabelsDialog(HasTraits): class HResizeTestDialog(HasTraits): - """ Dialog with checkbox and text elements and labels on the right. + """Dialog with checkbox and text elements and labels on the right. We test the separation between element and label in HGroups. """ @@ -67,7 +66,7 @@ class HResizeTestDialog(HasTraits): class VResizeTestDialog(HasTraits): - """ Dialog with checkbox and text elements and labels on the right. + """Dialog with checkbox and text elements and labels on the right. We test the separation between element and label in VGroups. """ @@ -86,8 +85,7 @@ class VResizeTestDialog(HasTraits): class NoLabelResizeTestDialog(HasTraits): - """ Test the combination show_label=False, show_left=False. - """ + """Test the combination show_label=False, show_left=False.""" bool_item = Bool(True) @@ -101,7 +99,7 @@ class NoLabelResizeTestDialog(HasTraits): class EnableWhenDialog(HasTraits): - """ Test labels for enable when. """ + """Test labels for enable when.""" bool_item = Bool(True) @@ -122,7 +120,6 @@ class EnableWhenDialog(HasTraits): class TestLabels(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -135,9 +132,9 @@ def test_qt_show_labels_right_without_colon(self): # that are shown to the *right* of the corresponding elements from pyface import qt + dialog = ShowRightLabelsDialog() - with reraise_exceptions(), \ - create_ui(dialog) as ui: + with reraise_exceptions(), create_ui(dialog) as ui: # get reference to label objects labels = ui.control.findChildren(qt.QtGui.QLabel) @@ -159,8 +156,7 @@ def _test_qt_labels_right_resizing(self, dialog_class): from pyface import qt - with reraise_exceptions(), \ - create_ui(dialog_class()) as ui: + with reraise_exceptions(), create_ui(dialog_class()) as ui: # all labels labels = ui.control.findChildren(qt.QtGui.QLabel) @@ -203,8 +199,7 @@ def test_labels_enabled_when(self): # Behaviour: label should enable/disable along with editor dialog = EnableWhenDialog() - with reraise_exceptions(), \ - create_ui(dialog) as ui: + with reraise_exceptions(), create_ui(dialog) as ui: labelled_editor = ui.get_editors("labelled_item")[0] @@ -223,7 +218,7 @@ def test_labels_enabled_when(self): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestAnyToolkit(BaseTestMixin, unittest.TestCase): - """ Toolkit-agnostic tests for labels with different orientations.""" + """Toolkit-agnostic tests for labels with different orientations.""" def setUp(self): BaseTestMixin.setUp(self) @@ -232,31 +227,26 @@ def tearDown(self): BaseTestMixin.tearDown(self) def test_group_show_right_labels(self): - with reraise_exceptions(), \ - create_ui(ShowRightLabelsDialog()): + with reraise_exceptions(), create_ui(ShowRightLabelsDialog()): pass def test_horizontal_resizable_and_labels(self): - with reraise_exceptions(), \ - create_ui(HResizeTestDialog()): + with reraise_exceptions(), create_ui(HResizeTestDialog()): pass def test_all_resizable_with_labels(self): - with reraise_exceptions(), \ - create_ui(VResizeTestDialog()): + with reraise_exceptions(), create_ui(VResizeTestDialog()): pass def test_show_right_with_no_label(self): # Bug: If one set show_left=False, show_label=False on a non-resizable # item like a checkbox, the Qt backend tried to set the label's size # policy and failed because label=None. - with reraise_exceptions(), \ - create_ui(NoLabelResizeTestDialog()): + with reraise_exceptions(), create_ui(NoLabelResizeTestDialog()): pass def test_enable_when_flag(self): - with reraise_exceptions(), \ - create_ui(EnableWhenDialog()): + with reraise_exceptions(), create_ui(EnableWhenDialog()): pass diff --git a/traitsui/tests/test_layout.py b/traitsui/tests/test_layout.py index 32d59b5c2..9d17e9bc5 100644 --- a/traitsui/tests/test_layout.py +++ b/traitsui/tests/test_layout.py @@ -35,7 +35,7 @@ class MultipleTrait(HasTraits): - """ An object with multiple traits to test layout and alignments.""" + """An object with multiple traits to test layout and alignments.""" txt1 = Str("text1") txt2 = Str("text2") @@ -83,7 +83,6 @@ def default_traits_view(self): class TestLayout(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -96,9 +95,8 @@ def test_qt_resizable_in_vgroup(self): # along the non-layout axis of its group. In a VGroup, resizing should # work only in the horizontal direction. - with reraise_exceptions(), \ - create_ui(VResizeDialog()) as ui: - editor, = ui.get_editors("txt") + with reraise_exceptions(), create_ui(VResizeDialog()) as ui: + (editor,) = ui.get_editors("txt") text = editor.control # horizontal size should be large @@ -113,10 +111,9 @@ def test_qt_resizable_in_hgroup(self): # along the non-layout axis of its group. In a HGroup, resizing should # work only in the vertical direction. - with reraise_exceptions(), \ - create_ui(HResizeDialog()) as ui: + with reraise_exceptions(), create_ui(HResizeDialog()) as ui: - editor, = ui.get_editors("txt") + (editor,) = ui.get_editors("txt") text = editor.control # vertical size should be large @@ -139,17 +136,16 @@ def test_qt_resizable_readonly_item(self): # vertical direction self.assertLess( resizable_readonly_item._target.control.height(), - _DIALOG_HEIGHT + _DIALOG_HEIGHT, ) self.assertEqual( - resizable_readonly_item._target.control.width(), - _DIALOG_WIDTH + resizable_readonly_item._target.control.width(), _DIALOG_WIDTH ) @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestOrientation(BaseTestMixin, unittest.TestCase): - """ Toolkit-agnostic tests on the layout orientations.""" + """Toolkit-agnostic tests on the layout orientations.""" def setUp(self): BaseTestMixin.setUp(self) @@ -164,8 +160,9 @@ def test_vertical_layout(self): Item("txt2"), ) ) - with reraise_exceptions(), \ - create_ui(MultipleTrait(), ui_kwargs=dict(view=view)): + with reraise_exceptions(), create_ui( + MultipleTrait(), ui_kwargs=dict(view=view) + ): pass def test_horizontal_layout(self): @@ -176,8 +173,9 @@ def test_horizontal_layout(self): Item("txt2"), ) ) - with reraise_exceptions(), \ - create_ui(MultipleTrait(), ui_kwargs=dict(view=view)): + with reraise_exceptions(), create_ui( + MultipleTrait(), ui_kwargs=dict(view=view) + ): pass diff --git a/traitsui/tests/test_regression.py b/traitsui/tests/test_regression.py index 672fe2599..0691279ef 100644 --- a/traitsui/tests/test_regression.py +++ b/traitsui/tests/test_regression.py @@ -31,7 +31,6 @@ class Child(HasTraits): class TestRegression(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -39,8 +38,7 @@ def tearDown(self): BaseTestMixin.tearDown(self) def test_editor_on_delegates_to_event(self): - """ Make sure that DelegatesTo on Events passes Editor creation. - """ + """Make sure that DelegatesTo on Events passes Editor creation.""" child = Child(parent=Parent()) editor = Editor( None, factory=TextEditor(), object=child, name="button" @@ -48,8 +46,7 @@ def test_editor_on_delegates_to_event(self): self.assertIs(editor.old_value, Undefined) def test_attribute_error(self): - """ Make sure genuine AttributeErrors raise on Editor creation. - """ + """Make sure genuine AttributeErrors raise on Editor creation.""" self.assertRaises( AttributeError, Editor, diff --git a/traitsui/tests/test_shadow_group.py b/traitsui/tests/test_shadow_group.py index a93bf9209..818bb20fa 100644 --- a/traitsui/tests/test_shadow_group.py +++ b/traitsui/tests/test_shadow_group.py @@ -20,7 +20,6 @@ class TestShadowGroup(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) diff --git a/traitsui/tests/test_splitter_prefs_restored.py b/traitsui/tests/test_splitter_prefs_restored.py index 3d17e1c30..5dc6cb57a 100644 --- a/traitsui/tests/test_splitter_prefs_restored.py +++ b/traitsui/tests/test_splitter_prefs_restored.py @@ -33,32 +33,27 @@ def init(self, ui_info): return True def reset_prefs(self, ui_info): - """ Reset the split to be equally wide. - """ + """Reset the split to be equally wide.""" control = getattr(ui_info, "h_split").control width = control.width() control.moveSplitter(width // 2, 1) def restore_prefs(self, ui_info): - """ Apply the last saved ui preferences. - """ + """Apply the last saved ui preferences.""" ui_info.ui.set_prefs(self._prefs) def save_prefs(self, ui_info): - """ Save the current ui preferences. - """ + """Save the current ui preferences.""" self._prefs = ui_info.ui.get_prefs() def collapse_right(self, ui_info): - """ Collapse the split to the right. - """ + """Collapse the split to the right.""" control = getattr(ui_info, "h_split").control width = control.width() control.moveSplitter(width, 1) def collapse_left(self, ui_info): - """ Collapse the split to the left. - """ + """Collapse the split to the left.""" control = getattr(ui_info, "h_split").control control.moveSplitter(0, 1) @@ -83,7 +78,6 @@ def collapse_left(self, ui_info): class TestSplitterPrefsRestored(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -96,8 +90,7 @@ def test_splitter_prefs_are_restored(self): splitter_keys = ("h_split", "structure") def _get_nattr(obj, attr_names=splitter_keys): - """ Utility function to get a value from a nested dict. - """ + """Utility function to get a value from a nested dict.""" if obj is None or len(attr_names) == 0: return obj return _get_nattr( diff --git a/traitsui/tests/test_theme.py b/traitsui/tests/test_theme.py index ca763b47f..b18375346 100644 --- a/traitsui/tests/test_theme.py +++ b/traitsui/tests/test_theme.py @@ -17,7 +17,6 @@ class TestTheme(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) self.theme = Theme() @@ -32,6 +31,7 @@ def test_theme_pickling(self): @requires_toolkit([ToolkitName.wx]) def test_theme_content_color_default(self): import wx + self.assertEqual(self.theme.content_color, wx.BLACK) def test_theme_content_color_setter_getter(self): @@ -41,6 +41,7 @@ def test_theme_content_color_setter_getter(self): @requires_toolkit([ToolkitName.wx]) def test_theme_label_color_default(self): import wx + self.assertEqual(self.theme.label_color, wx.BLACK) def test_theme_label_color_setter_getter(self): diff --git a/traitsui/tests/test_toolkit.py b/traitsui/tests/test_toolkit.py index 3e1cc899b..21026f0b2 100644 --- a/traitsui/tests/test_toolkit.py +++ b/traitsui/tests/test_toolkit.py @@ -19,7 +19,7 @@ @contextmanager def clear_toolkit(): - """ If a toolkit has been selected, clear it, resetting on exit """ + """If a toolkit has been selected, clear it, resetting on exit""" old_ETS_toolkit = ETSConfig._toolkit old_traitsui_toolkit = traitsui.toolkit._toolkit ETSConfig._toolkit = "" @@ -32,7 +32,6 @@ def clear_toolkit(): class TestToolkit(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) diff --git a/traitsui/tests/test_tree_node.py b/traitsui/tests/test_tree_node.py index f5d0e6ee1..3ed391bde 100644 --- a/traitsui/tests/test_tree_node.py +++ b/traitsui/tests/test_tree_node.py @@ -22,8 +22,7 @@ class DummyModel(HasStrictTraits): - """ Dummy model with children. - """ + """Dummy model with children.""" name = Str() @@ -31,7 +30,6 @@ class DummyModel(HasStrictTraits): class TestTreeNode(BaseTestMixin, UnittestTools, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) diff --git a/traitsui/tests/test_ui.py b/traitsui/tests/test_ui.py index d1e540d51..f94eceebb 100644 --- a/traitsui/tests/test_ui.py +++ b/traitsui/tests/test_ui.py @@ -48,8 +48,7 @@ class FooDialog(HasTraits): class DisallowNewTraits(HasStrictTraits): - """ Make sure no extra traits are added. - """ + """Make sure no extra traits are added.""" x = Int(10) @@ -62,16 +61,13 @@ class MaybeInvalidTrait(HasTraits): name_is_invalid = Property(observe="name") - traits_view = View( - Item("name", invalid="name_is_invalid") - ) + traits_view = View(Item("name", invalid="name_is_invalid")) def _get_name_is_invalid(self): return len(self.name) < 10 class TestUI(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -136,9 +132,7 @@ def test_reset_without_destroy_wx(self): self.assertIsInstance( ui._editors[0], traitsui.wx.text_editor.SimpleEditor ) - self.assertIsInstance( - ui._editors[0].control, wx.TextCtrl - ) + self.assertIsInstance(ui._editors[0].control, wx.TextCtrl) ui.reset(destroy=False) @@ -241,7 +235,7 @@ def test_invalid_state(self): # Regression test for enthought/traitsui#983 obj = MaybeInvalidTrait(name="Name long enough to be valid") with create_ui(obj) as ui: - editor, = ui.get_editors("name") + (editor,) = ui.get_editors("name") self.assertFalse(editor.invalid) obj.name = "too short" @@ -264,7 +258,6 @@ class DummyObject(HasTraits): from pyface.qt import QtGui, QtCore class CustomWidget(QtGui.QWidget): - def __init__(self, editor, parent=None): super().__init__() self._some_editor = editor @@ -279,7 +272,6 @@ def sizeHint(self): return super().sizeHint() class EditorWithCustomWidget(ToolkitSpecificEditor): - def init(self, parent): self.control = QtGui.QSplitter(QtCore.Qt.Horizontal) @@ -316,7 +308,6 @@ def update_editor(self): from traitsui.wx.helper import TraitsUIPanel class DummyButtonEditor(ToolkitSpecificEditor): - def init(self, parent): self.control = wx.Button(parent, -1, "Dummy") self.control.Bind(wx.EVT_BUTTON, self.update_object) @@ -333,7 +324,6 @@ def update_editor(self): pass class EditorWithCustomWidget(ToolkitSpecificEditor): # noqa: F811 - def init(self, parent): self.control = TraitsUIPanel(parent, -1) @@ -365,7 +355,7 @@ def dispose_inner_ui(self): class TestUIDispose(BaseTestMixin, unittest.TestCase): - """ Test disposal of UI.""" + """Test disposal of UI.""" def setUp(self): BaseTestMixin.setUp(self) @@ -405,7 +395,7 @@ def test_dispose_inner_ui(self): ), ) ui = obj.edit_traits(view=view) - editor, = ui.get_editors("number") + (editor,) = ui.get_editors("number") gui = GUI() with ensure_destroyed(ui): @@ -430,7 +420,7 @@ def test_dispose_inner_ui(self): @contextlib.contextmanager def ensure_destroyed(ui): - """ Ensure the widget is destroyed in the event when test fails.""" + """Ensure the widget is destroyed in the event when test fails.""" try: yield finally: @@ -441,7 +431,7 @@ def ensure_destroyed(ui): def close_control(control): - """ Close the widget.""" + """Close the widget.""" if is_qt(): control.close() elif is_wx(): diff --git a/traitsui/tests/test_ui_panel.py b/traitsui/tests/test_ui_panel.py index 71fc6fcb9..172ef36e0 100644 --- a/traitsui/tests/test_ui_panel.py +++ b/traitsui/tests/test_ui_panel.py @@ -15,12 +15,15 @@ from pyface.toolkit import toolkit_object from pyface.constant import OK + try: from pyface.qt import QtWebkit # noqa: F401 + NO_WEBKIT_OR_WEBENGINE = False except ImportError: try: from pyface.qt import QtWebEngine # noqa: F401 + NO_WEBKIT_OR_WEBENGINE = False except ImportError: NO_WEBKIT_OR_WEBENGINE = True @@ -59,7 +62,6 @@ def default_traits_view(self): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) class TestUIPanel(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) diff --git a/traitsui/tests/test_ui_traits.py b/traitsui/tests/test_ui_traits.py index fa17e8ff3..cc72af636 100644 --- a/traitsui/tests/test_ui_traits.py +++ b/traitsui/tests/test_ui_traits.py @@ -26,7 +26,6 @@ class ObjectWithUITraits(HasStrictTraits): class TestUITraits(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -60,7 +59,6 @@ def test_an_object(self): class TestStatusItem(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -85,7 +83,6 @@ def test_init_with_name_and_value(self): class TestViewStatus(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -97,6 +94,6 @@ def test_init(self): obj.view_status = "some_name" self.assertEqual(len(obj.view_status), 1) - status, = obj.view_status + (status,) = obj.view_status self.assertIsInstance(status, ui_traits.StatusItem) self.assertEqual(status.name, "some_name") diff --git a/traitsui/tests/test_undo.py b/traitsui/tests/test_undo.py index 55e5b52b7..f9d0879ee 100644 --- a/traitsui/tests/test_undo.py +++ b/traitsui/tests/test_undo.py @@ -43,7 +43,6 @@ class SimpleExample(HasTraits): class DummyCommand(AbstractCommand): - def do(self): self.data = "do" @@ -55,7 +54,6 @@ def redo(self): class LegacyUndoItem(AbstractUndoItem): - def undo(self): pass @@ -64,7 +62,6 @@ def redo(self): class TestAbstractUndoItem(UnittestTools, unittest.TestCase): - def test_merge_undo_deprecated(self): undo_item = LegacyUndoItem() other_item = LegacyUndoItem() @@ -79,7 +76,6 @@ def test_merge_undo_deprecated(self): class TestUndoItem(UnittestTools, unittest.TestCase): - def test_undo(self): example = SimpleExample(value=11) @@ -487,7 +483,6 @@ def test_merge_unhandled_type(self): class TestListUndoItem(UnittestTools, unittest.TestCase): - def test_undo(self): example = SimpleExample(list_value=['foo', 'wombat', 'baz']) @@ -553,7 +548,7 @@ def test_merge_equal(self): name='list_value', index=1, added=[['wombat'], 'baz'], - removed=removed.copy() + removed=removed.copy(), ) next_undo_item = ListUndoItem( object=example, @@ -665,9 +660,8 @@ def test_merge_different_index(self): class TestUndoHistory(UnittestTools, unittest.TestCase): - def _populate_history(self, history): - """ Add some simple hostory items. """ + """Add some simple hostory items.""" self._example = SimpleExample() history.add( UndoItem( @@ -908,7 +902,9 @@ def test_undo_last(self): with self.assertTraitDoesNotChange(history, 'undoable'): with self.assertTraitChanges(history, 'redoable', count=1): - with self.assertTraitChanges(self._example, 'anytrait', count=1): # noqa: E501 + with self.assertTraitChanges( + self._example, 'anytrait', count=1 + ): # noqa: E501 history.undo() self.assertEqual(history.now, 2) @@ -923,7 +919,9 @@ def test_undo_first(self): with self.assertTraitDoesNotChange(history, 'redoable'): with self.assertTraitChanges(history, 'undoable', count=1): - with self.assertTraitChanges(self._example, 'anytrait', count=1): # noqa: E501 + with self.assertTraitChanges( + self._example, 'anytrait', count=1 + ): # noqa: E501 history.undo() self.assertEqual(history.now, 0) @@ -937,7 +935,9 @@ def test_undo_middle(self): with self.assertTraitDoesNotChange(history, 'redoable'): with self.assertTraitDoesNotChange(history, 'undoable'): - with self.assertTraitChanges(self._example, 'anytrait', count=1): # noqa: E501 + with self.assertTraitChanges( + self._example, 'anytrait', count=1 + ): # noqa: E501 history.undo() self.assertEqual(history.now, 1) @@ -951,7 +951,9 @@ def test_redo_last(self): with self.assertTraitChanges(history, 'redoable', count=1): with self.assertTraitDoesNotChange(history, 'undoable'): - with self.assertTraitChanges(self._example, 'anytrait', count=1): # noqa: E501 + with self.assertTraitChanges( + self._example, 'anytrait', count=1 + ): # noqa: E501 history.redo() self.assertEqual(history.now, 3) @@ -966,7 +968,9 @@ def test_redo_middle(self): with self.assertTraitDoesNotChange(history, 'redoable'): with self.assertTraitDoesNotChange(history, 'undoable'): - with self.assertTraitChanges(self._example, 'anytrait', count=1): # noqa: E501 + with self.assertTraitChanges( + self._example, 'anytrait', count=1 + ): # noqa: E501 history.redo() self.assertEqual(history.now, 2) @@ -982,7 +986,9 @@ def test_redo_first(self): with self.assertTraitDoesNotChange(history, 'redoable'): with self.assertTraitChanges(history, 'undoable', count=1): - with self.assertTraitChanges(self._example, 'anytrait', count=1): # noqa: E501 + with self.assertTraitChanges( + self._example, 'anytrait', count=1 + ): # noqa: E501 history.redo() self.assertEqual(history.now, 1) @@ -995,7 +1001,9 @@ def test_revert_end(self): with self.assertTraitChanges(history, 'redoable', count=2): with self.assertTraitChanges(history, 'undoable', count=1): - with self.assertTraitChanges(self._example, 'anytrait', count=3): # noqa: E501 + with self.assertTraitChanges( + self._example, 'anytrait', count=3 + ): # noqa: E501 history.revert() self.assertEqual(history.now, 0) @@ -1010,7 +1018,9 @@ def test_revert_middle(self): with self.assertTraitChanges(history, 'redoable', count=1): with self.assertTraitChanges(history, 'undoable', count=1): - with self.assertTraitChanges(self._example, 'anytrait', count=1): # noqa: E501 + with self.assertTraitChanges( + self._example, 'anytrait', count=1 + ): # noqa: E501 history.revert() self.assertEqual(history.now, 0) @@ -1144,7 +1154,6 @@ def test_general_command_do(self): @unittest.skipIf(no_gui_test_assistant, "No GuiTestAssistant") class TestEditorUndo(BaseTestMixin, GuiTestAssistant, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) GuiTestAssistant.setUp(self) @@ -1153,8 +1162,9 @@ def tearDown(self): GuiTestAssistant.tearDown(self) BaseTestMixin.tearDown(self) - def check_history(self, editor, expected_history_now, - expected_history_length): + def check_history( + self, editor, expected_history_now, expected_history_length + ): # XXX this is testing private state return ( editor.ui.history.now == expected_history_now @@ -1185,21 +1195,31 @@ def test_undo(self): self.undo(editor) # Expect 2 items in history and pointer at first item - self.assertEventuallyTrue(editor, "ui", - functools.partial(self.check_history, - expected_history_now=1, - expected_history_length=2), - timeout=5.0) + self.assertEventuallyTrue( + editor, + "ui", + functools.partial( + self.check_history, + expected_history_now=1, + expected_history_length=2, + ), + timeout=5.0, + ) # Perform a REDO self.redo(editor) # Expect 2 items in history and pointer at second item - self.assertEventuallyTrue(editor, "ui", - functools.partial(self.check_history, - expected_history_now=2, - expected_history_length=2), - timeout=5.0) + self.assertEventuallyTrue( + editor, + "ui", + functools.partial( + self.check_history, + expected_history_now=2, + expected_history_length=2, + ), + timeout=5.0, + ) # Enter 'three' with editor.updating_value(): @@ -1209,11 +1229,16 @@ def test_undo(self): self.undo(editor) # Expect 3 items in history and pointer at second item - self.assertEventuallyTrue(editor, "ui", - functools.partial(self.check_history, - expected_history_now=2, - expected_history_length=3), - timeout=5.0) + self.assertEventuallyTrue( + editor, + "ui", + functools.partial( + self.check_history, + expected_history_now=2, + expected_history_length=3, + ), + timeout=5.0, + ) # Enter 'four' with editor.updating_value(): @@ -1223,11 +1248,16 @@ def test_undo(self): # Expect 3 items in history and pointer at second item # Note: Modifying the history after an UNDO, clears the future, # hence, we expect 3 items in the history, not 4 - self.assertEventuallyTrue(editor, "ui", - functools.partial(self.check_history, - expected_history_now=3, - expected_history_length=3), - timeout=5.0) + self.assertEventuallyTrue( + editor, + "ui", + functools.partial( + self.check_history, + expected_history_now=3, + expected_history_length=3, + ), + timeout=5.0, + ) # The following sequence after modifying the history had caused # the application to hang, verify it. @@ -1238,8 +1268,13 @@ def test_undo(self): self.redo(editor) # Expect 3 items in history and pointer at second item - self.assertEventuallyTrue(editor, "ui", - functools.partial(self.check_history, - expected_history_now=2, - expected_history_length=3), - timeout=5.0) + self.assertEventuallyTrue( + editor, + "ui", + functools.partial( + self.check_history, + expected_history_now=2, + expected_history_length=3, + ), + timeout=5.0, + ) diff --git a/traitsui/tests/test_view_application.py b/traitsui/tests/test_view_application.py index f97d40a2f..a356941a1 100644 --- a/traitsui/tests/test_view_application.py +++ b/traitsui/tests/test_view_application.py @@ -15,7 +15,10 @@ from traitsui.api import Handler, Item, UIInfo, View, toolkit from ._tools import ( - BaseTestMixin, GuiTestAssistant, is_qt, no_gui_test_assistant + BaseTestMixin, + GuiTestAssistant, + is_qt, + no_gui_test_assistant, ) diff --git a/traitsui/tests/test_visible_when_layout.py b/traitsui/tests/test_visible_when_layout.py index 09c6d6d7f..e1ebf1666 100644 --- a/traitsui/tests/test_visible_when_layout.py +++ b/traitsui/tests/test_visible_when_layout.py @@ -74,7 +74,6 @@ class VisibleWhenProblem(HasTraits): class TestVisibleWhenLayout(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) diff --git a/traitsui/tests/ui_editors/test_data_frame_editor.py b/traitsui/tests/ui_editors/test_data_frame_editor.py index 708e93133..c964a337f 100644 --- a/traitsui/tests/ui_editors/test_data_frame_editor.py +++ b/traitsui/tests/ui_editors/test_data_frame_editor.py @@ -100,7 +100,6 @@ def sample_text_data(): class TestDataFrameEditor(BaseTestMixin, unittest.TestCase): - def setUp(self): BaseTestMixin.setUp(self) @@ -344,8 +343,9 @@ class AlternateAdapter(DataFrameAdapter): ) ) viewer = sample_data() - with reraise_exceptions(), \ - create_ui(viewer, dict(view=alternate_adapter_view)): + with reraise_exceptions(), create_ui( + viewer, dict(view=alternate_adapter_view) + ): pass @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) @@ -363,22 +363,23 @@ def test_data_frame_editor_text_data(self): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) def test_data_frame_editor_format_mapping(self): viewer = sample_data() - with reraise_exceptions(), \ - create_ui(viewer, dict(view=format_mapping_view)): + with reraise_exceptions(), create_ui( + viewer, dict(view=format_mapping_view) + ): pass @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) def test_data_frame_editor_font_mapping(self): viewer = sample_data() - with reraise_exceptions(), \ - create_ui(viewer, dict(view=font_mapping_view)): + with reraise_exceptions(), create_ui( + viewer, dict(view=font_mapping_view) + ): pass @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) def test_data_frame_editor_columns(self): viewer = sample_data() - with reraise_exceptions(), \ - create_ui(viewer, dict(view=columns_view)): + with reraise_exceptions(), create_ui(viewer, dict(view=columns_view)): pass @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) @@ -393,7 +394,7 @@ class DataFrameViewer(HasTraits): df = DataFrame( DATA, index=["one", "two", "three", "four"], - columns=["X", "Y", "Z"] + columns=["X", "Y", "Z"], ) viewer = DataFrameViewer(data=df) with reraise_exceptions(), create_ui(viewer): @@ -411,7 +412,7 @@ class DataFrameViewer(HasTraits): df = DataFrame( DATA, index=["one", "two", "three", "four"], - columns=["X", "Y", "Z"] + columns=["X", "Y", "Z"], ) viewer = DataFrameViewer(data=df) with reraise_exceptions(), create_ui(viewer): @@ -423,8 +424,7 @@ def test_data_frame_editor_multi_select(self): Item("data", editor=DataFrameEditor(multi_select=True), width=400) ) viewer = sample_data() - with reraise_exceptions(), \ - create_ui(viewer, dict(view=view)): + with reraise_exceptions(), create_ui(viewer, dict(view=view)): pass @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) @@ -457,10 +457,9 @@ def test_adapter_set_text_invalid(self): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) def test_adapter_set_index_text(self): viewer = sample_data() - columns = ( - [('', 'index')] + - [(column, column) for column in viewer.data.columns] - ) + columns = [('', 'index')] + [ + (column, column) for column in viewer.data.columns + ] adapter = DataFrameAdapter(columns=columns) adapter.set_text(viewer, 'data', 0, 0, 'NewIndex') @@ -474,10 +473,9 @@ def test_adapter_set_index_text(self): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) def test_adapter_set_index_text_numeric(self): viewer = sample_data_numerical_index() - columns = ( - [('', 'index')] + - [(column, column) for column in viewer.data.columns] - ) + columns = [('', 'index')] + [ + (column, column) for column in viewer.data.columns + ] adapter = DataFrameAdapter(columns=columns) adapter.set_text(viewer, 'data', 0, 0, 100) @@ -491,10 +489,9 @@ def test_adapter_set_index_text_numeric(self): @requires_toolkit([ToolkitName.qt, ToolkitName.wx]) def test_adapter_set_index_text_numeric_invalid(self): viewer = sample_data_numerical_index() - columns = ( - [('', 'index')] + - [(column, column) for column in viewer.data.columns] - ) + columns = [('', 'index')] + [ + (column, column) for column in viewer.data.columns + ] adapter = DataFrameAdapter(columns=columns) adapter.set_text(viewer, 'data', 0, 0, 'invalid') diff --git a/traitsui/theme.py b/traitsui/theme.py index c02f23a09..86bd72727 100644 --- a/traitsui/theme.py +++ b/traitsui/theme.py @@ -48,8 +48,7 @@ class Theme(HasPrivateTraits): # -- Constructor ---------------------------------------------------------- def __init__(self, image=None, **traits): - """ Initializes the object. - """ + """Initializes the object.""" if image is not None: self.image = image diff --git a/traitsui/toolkit.py b/traitsui/toolkit.py index bdb80eee2..fc4d2cc4a 100644 --- a/traitsui/toolkit.py +++ b/traitsui/toolkit.py @@ -32,7 +32,7 @@ def assert_toolkit_import(names): - """ Raise an error if a toolkit with the given name should not be allowed + """Raise an error if a toolkit with the given name should not be allowed to be imported. """ if ETSConfig.toolkit and ETSConfig.toolkit not in names: @@ -43,7 +43,7 @@ def assert_toolkit_import(names): def toolkit_object(name, raise_exceptions=False): - """ Return the toolkit specific object with the given name. + """Return the toolkit specific object with the given name. Parameters ---------- @@ -78,7 +78,7 @@ def toolkit_object(name, raise_exceptions=False): def toolkit(*toolkits): - """ Selects and returns a low-level GUI toolkit. + """Selects and returns a low-level GUI toolkit. Use this function to get a reference to the current toolkit. @@ -112,84 +112,83 @@ def toolkit(*toolkits): class Toolkit(Toolkit): - """ Abstract base class for GUI toolkits. - """ + """Abstract base class for GUI toolkits.""" def ui_panel(self, ui, parent): - """ Creates a GUI-toolkit-specific panel-based user interface using - information from the specified UI object. + """Creates a GUI-toolkit-specific panel-based user interface using + information from the specified UI object. """ raise NotImplementedError( not_implemented_message.format(ETSConfig.toolkit) ) def ui_subpanel(self, ui, parent): - """ Creates a GUI-toolkit-specific subpanel-based user interface using - information from the specified UI object. + """Creates a GUI-toolkit-specific subpanel-based user interface using + information from the specified UI object. """ raise NotImplementedError( not_implemented_message.format(ETSConfig.toolkit) ) def ui_livemodal(self, ui, parent): - """ Creates a GUI-toolkit-specific modal "live update" dialog user - interface using information from the specified UI object. + """Creates a GUI-toolkit-specific modal "live update" dialog user + interface using information from the specified UI object. """ raise NotImplementedError( not_implemented_message.format(ETSConfig.toolkit) ) def ui_live(self, ui, parent): - """ Creates a GUI-toolkit-specific non-modal "live update" window user - interface using information from the specified UI object. + """Creates a GUI-toolkit-specific non-modal "live update" window user + interface using information from the specified UI object. """ raise NotImplementedError( not_implemented_message.format(ETSConfig.toolkit) ) def ui_modal(self, ui, parent): - """ Creates a GUI-toolkit-specific modal dialog user interface using - information from the specified UI object. + """Creates a GUI-toolkit-specific modal dialog user interface using + information from the specified UI object. """ raise NotImplementedError( not_implemented_message.format(ETSConfig.toolkit) ) def ui_nonmodal(self, ui, parent): - """ Creates a GUI-toolkit-specific non-modal dialog user interface using - information from the specified UI object. + """Creates a GUI-toolkit-specific non-modal dialog user interface using + information from the specified UI object. """ raise NotImplementedError( not_implemented_message.format(ETSConfig.toolkit) ) def ui_popup(self, ui, parent): - """ Creates a GUI-toolkit-specific temporary "live update" popup dialog - user interface using information from the specified UI object. + """Creates a GUI-toolkit-specific temporary "live update" popup dialog + user interface using information from the specified UI object. """ raise NotImplementedError( not_implemented_message.format(ETSConfig.toolkit) ) def ui_popover(self, ui, parent): - """ Creates a GUI-toolkit-specific temporary "live update" popup dialog - user interface using information from the specified UI object. + """Creates a GUI-toolkit-specific temporary "live update" popup dialog + user interface using information from the specified UI object. """ raise NotImplementedError( not_implemented_message.format(ETSConfig.toolkit) ) def ui_info(self, ui, parent): - """ Creates a GUI-toolkit-specific temporary "live update" popup dialog - user interface using information from the specified UI object. + """Creates a GUI-toolkit-specific temporary "live update" popup dialog + user interface using information from the specified UI object. """ raise NotImplementedError( not_implemented_message.format(ETSConfig.toolkit) ) def ui_wizard(self, ui, parent): - """ Creates a GUI-toolkit-specific wizard dialog user interface using - information from the specified UI object. + """Creates a GUI-toolkit-specific wizard dialog user interface using + information from the specified UI object. """ raise NotImplementedError( not_implemented_message.format(ETSConfig.toolkit) @@ -205,7 +204,7 @@ def view_application( scrollable=None, args=None, ): - """ Creates a GUI-toolkit-specific modal dialog user interface that + """Creates a GUI-toolkit-specific modal dialog user interface that runs as a complete application using information from the specified View object. @@ -241,108 +240,99 @@ def view_application( ) def position(self, ui): - """ Positions the associated dialog window on the display. - """ + """Positions the associated dialog window on the display.""" raise NotImplementedError( not_implemented_message.format(ETSConfig.toolkit) ) def show_help(self, ui, control): - """ Shows a Help window for a specified UI and control. - """ + """Shows a Help window for a specified UI and control.""" raise NotImplementedError( not_implemented_message.format(ETSConfig.toolkit) ) def set_title(self, ui): - """ Sets the title for the UI window. - """ + """Sets the title for the UI window.""" raise NotImplementedError( not_implemented_message.format(ETSConfig.toolkit) ) def set_icon(self, ui): - """ Sets the icon for the UI window. - """ + """Sets the icon for the UI window.""" raise NotImplementedError( not_implemented_message.format(ETSConfig.toolkit) ) def save_window(self, ui): - """ Saves user preference information associated with a UI window. - """ + """Saves user preference information associated with a UI window.""" raise NotImplementedError( not_implemented_message.format(ETSConfig.toolkit) ) def rebuild_ui(self, ui): - """ Rebuilds a UI after a change to the content of the UI. - """ + """Rebuilds a UI after a change to the content of the UI.""" raise NotImplementedError( not_implemented_message.format(ETSConfig.toolkit) ) def key_event_to_name(self, event): - """ Converts a keystroke event into a corresponding key name. - """ + """Converts a keystroke event into a corresponding key name.""" raise NotImplementedError( not_implemented_message.format(ETSConfig.toolkit) ) def hook_events(self, ui, control, events=None, handler=None): - """ Hooks all specified events for all controls in a UI so that they - can be routed to the correct event handler. + """Hooks all specified events for all controls in a UI so that they + can be routed to the correct event handler. """ raise NotImplementedError( not_implemented_message.format(ETSConfig.toolkit) ) def route_event(self, ui, event): - """ Routes a "hooked" event to the corrent handler method. - """ + """Routes a "hooked" event to the corrent handler method.""" raise NotImplementedError( not_implemented_message.format(ETSConfig.toolkit) ) def skip_event(self, event): - """ Indicates that an event should continue to be processed by the - toolkit. + """Indicates that an event should continue to be processed by the + toolkit. """ raise NotImplementedError( not_implemented_message.format(ETSConfig.toolkit) ) def destroy_control(self, control): - """ Destroys a specified GUI toolkit control. - """ + """Destroys a specified GUI toolkit control.""" raise NotImplementedError( not_implemented_message.format(ETSConfig.toolkit) ) def destroy_children(self, control): - """ Destroys all of the child controls of a specified GUI toolkit - control. + """Destroys all of the child controls of a specified GUI toolkit + control. """ raise NotImplementedError( not_implemented_message.format(ETSConfig.toolkit) ) def image_size(self, image): - """ Returns a ( width, height ) tuple containing the size of a - specified toolkit image. + """Returns a ( width, height ) tuple containing the size of a + specified toolkit image. """ raise NotImplementedError( not_implemented_message.format(ETSConfig.toolkit) ) def constants(self): - """ Returns a dictionary of useful constants. + """Returns a dictionary of useful constants. - Currently, the dictionary should have the following key/value - pairs: + Currently, the dictionary should have the following key/value + pairs: - - WindowColor': the standard window background color in the toolkit - specific color format. + - WindowColor': the standard window background color in the toolkit + specific color format. """ raise NotImplementedError( not_implemented_message.format(ETSConfig.toolkit) diff --git a/traitsui/toolkit_traits.py b/traitsui/toolkit_traits.py index f868fc070..ff135d0cf 100644 --- a/traitsui/toolkit_traits.py +++ b/traitsui/toolkit_traits.py @@ -14,7 +14,7 @@ def ColorTrait(*args, **traits): - """ Returns a trait whose value is a GUI toolkit-specific color. + """Returns a trait whose value is a GUI toolkit-specific color. A number of different values are accepted for setting the value, including: @@ -44,7 +44,7 @@ def ColorTrait(*args, **traits): def RGBColorTrait(*args, **traits): - """ Returns a trait whose value is a RGB tuple with values from 0 to 1. + """Returns a trait whose value is a RGB tuple with values from 0 to 1. A number of different values are accepted for setting the value, including: @@ -64,7 +64,7 @@ def RGBColorTrait(*args, **traits): def FontTrait(*args, **traits): - """ Returns a trait whose value is a GUI toolkit-specific font. + """Returns a trait whose value is a GUI toolkit-specific font. This trait accepts either a toolkit-specific font object, or a string containing a font description. The string description can contain: diff --git a/traitsui/tree_node.py b/traitsui/tree_node.py index 1f88bb768..bf9fa49ae 100644 --- a/traitsui/tree_node.py +++ b/traitsui/tree_node.py @@ -48,8 +48,8 @@ class TreeNode(HasPrivateTraits): - """ Represents a tree node. Used by the tree editor and tree editor factory - classes. + """Represents a tree node. Used by the tree editor and tree editor factory + classes. """ # ------------------------------------------------------------------------- @@ -203,39 +203,33 @@ def _get_node_for_interface(self): # -- Overridable Methods: ------------------------------------------------- def allows_children(self, object): - """ Returns whether this object can have children. - """ + """Returns whether this object can have children.""" return self.children != "" def has_children(self, object): - """ Returns whether the object has children. - """ + """Returns whether the object has children.""" return len(self.get_children(object)) > 0 def get_children(self, object): - """ Gets the object's children. - """ + """Gets the object's children.""" return getattr(object, self.children, None) def get_children_id(self, object): - """ Gets the object's children identifier. - """ + """Gets the object's children identifier.""" return self.children def append_child(self, object, child): - """ Appends a child to the object's children. - """ + """Appends a child to the object's children.""" children = self.get_children(object) children.append(child) def insert_child(self, object, index, child): - """ Inserts a child into the object's children. - """ + """Inserts a child into the object's children.""" children = self.get_children(object) children[index:index] = [child] def confirm_delete(self, object): - """ Checks whether a specified object can be deleted. + """Checks whether a specified object can be deleted. The following return values are possible: @@ -247,12 +241,11 @@ def confirm_delete(self, object): return None def delete_child(self, object, index): - """ Deletes a child at a specified index from the object's children. - """ + """Deletes a child at a specified index from the object's children.""" del self.get_children(object)[index] def when_children_replaced(self, object, listener, remove): - """ Sets up or removes a listener for children being replaced on a + """Sets up or removes a listener for children being replaced on a specified object. """ object.on_trait_change( @@ -260,7 +253,7 @@ def when_children_replaced(self, object, listener, remove): ) def when_children_changed(self, object, listener, remove): - """ Sets up or removes a listener for children being changed on a + """Sets up or removes a listener for children being changed on a specified object. """ object.on_trait_change( @@ -271,8 +264,7 @@ def when_children_changed(self, object, listener, remove): ) def get_label(self, object): - """ Gets the label to display for a specified object. - """ + """Gets the label to display for a specified object.""" label = self.label if label[:1] == "=": return label[1:] @@ -285,14 +277,13 @@ def get_label(self, object): return self.formatter(object, label) def set_label(self, object, label): - """ Sets the label for a specified object. - """ + """Sets the label for a specified object.""" label_name = self.label if label_name[:1] != "=": xsetattr(object, label_name, label) def when_label_changed(self, object, listener, remove): - """ Sets up or removes a listener for the label being changed on a + """Sets up or removes a listener for the label being changed on a specified object. """ label = self.label @@ -301,7 +292,7 @@ def when_label_changed(self, object, listener, remove): if not remove: def wrapped_listener(target, name, new): - """ Ensure listener gets called with correct object. """ + """Ensure listener gets called with correct object.""" return listener(object, name, new) self._listener_cache[memo] = wrapped_listener @@ -315,14 +306,11 @@ def wrapped_listener(target, name, new): ) def get_column_labels(self, object): - """ Get the labels for any columns that have been defined. - """ + """Get the labels for any columns that have been defined.""" trait = self.column_labels labels = xgetattr(object, trait, []) formatted = [] - for formatter, label in zip_longest( - self.column_formatters, labels - ): + for formatter, label in zip_longest(self.column_formatters, labels): # If the list of column formatters is shorter than the list of # labels, then zip_longest() will extend it with Nones. Just pass # the label as preformatted. Similarly, explicitly using None in @@ -334,7 +322,7 @@ def get_column_labels(self, object): return formatted def when_column_labels_change(self, object, listener, remove): - """ Sets up or removes a listener for the column labels being changed on + """Sets up or removes a listener for the column labels being changed on a specified object. This will fire when either the list is reassigned or when it is @@ -348,7 +336,7 @@ def when_column_labels_change(self, object, listener, remove): if not remove: def wrapped_listener(target, name, new): - """ Ensure listener gets called with correct object. """ + """Ensure listener gets called with correct object.""" return listener(object, name, new) self._listener_cache[memo] = wrapped_listener @@ -368,8 +356,7 @@ def wrapped_listener(target, name, new): ) def get_tooltip(self, object): - """ Gets the tooltip to display for a specified object. - """ + """Gets the tooltip to display for a specified object.""" tooltip = self.tooltip if tooltip == "": return tooltip @@ -385,8 +372,7 @@ def get_tooltip(self, object): return self.tooltip_formatter(object, tooltip) def get_icon(self, object, is_expanded): - """ Returns the icon for a specified object. - """ + """Returns the icon for a specified object.""" if not self.allows_children(object): return self.icon_item @@ -396,24 +382,21 @@ def get_icon(self, object, is_expanded): return self.icon_group def get_icon_path(self, object): - """ Returns the path used to locate an object's icon. - """ + """Returns the path used to locate an object's icon.""" return self.icon_path def get_name(self, object): - """ Returns the name to use when adding a new object instance - (displayed in the "New" submenu). + """Returns the name to use when adding a new object instance + (displayed in the "New" submenu). """ return self.name def get_view(self, object): - """ Gets the view to use when editing an object. - """ + """Gets the view to use when editing an object.""" return self.view def get_menu(self, object): - """ Returns the right-click context menu for an object. - """ + """Returns the right-click context menu for an object.""" return self.menu def get_background(self, object): @@ -429,62 +412,55 @@ def get_foreground(self, object): return foreground def get_renderer(self, object, column=0): - """ Return the renderer for the object and column. """ + """Return the renderer for the object and column.""" return self.renderer def can_rename(self, object): - """ Returns whether the object's children can be renamed. - """ + """Returns whether the object's children can be renamed.""" return self.rename def can_rename_me(self, object): - """ Returns whether the object can be renamed. - """ + """Returns whether the object can be renamed.""" return self.rename_me def can_copy(self, object): - """ Returns whether the object's children can be copied. - """ + """Returns whether the object's children can be copied.""" return self.copy def can_delete(self, object): - """ Returns whether the object's children can be deleted. - """ + """Returns whether the object's children can be deleted.""" return self.delete def can_delete_me(self, object): - """ Returns whether the object can be deleted. - """ + """Returns whether the object can be deleted.""" return self.delete_me def can_insert(self, object): - """ Returns whether the object's children can be inserted (vs. + """Returns whether the object's children can be inserted (vs. appended). """ return self.insert def can_auto_open(self, object): - """ Returns whether the object's children should be automatically + """Returns whether the object's children should be automatically opened. """ return self.auto_open def can_auto_close(self, object): - """ Returns whether the object's children should be automatically + """Returns whether the object's children should be automatically closed. """ return self.auto_close def is_node_for(self, object): - """ Returns whether this is the node that handles a specified object. - """ + """Returns whether this is the node that handles a specified object.""" return isinstance( object, self.node_for_class ) or object.has_traits_interface(*self.node_for_interface) def can_add(self, object, add_object): - """ Returns whether a given object is droppable on the node. - """ + """Returns whether a given object is droppable on the node.""" klass = self._class_for(add_object) if self.is_addable(klass): return True @@ -498,18 +474,15 @@ def can_add(self, object, add_object): return False def get_add(self, object): - """ Returns the list of classes that can be added to the object. - """ + """Returns the list of classes that can be added to the object.""" return self.add def get_drag_object(self, object): - """ Returns a draggable version of a specified object. - """ + """Returns a draggable version of a specified object.""" return object def drop_object(self, object, dropped_object): - """ Returns a droppable version of a specified object. - """ + """Returns a droppable version of a specified object.""" klass = self._class_for(dropped_object) if self.is_addable(klass): return dropped_object @@ -524,8 +497,7 @@ def drop_object(self, object, dropped_object): return dropped_object def select(self, object): - """ Handles an object being selected. - """ + """Handles an object being selected.""" if self.on_select is not None: self.on_select(object) return None @@ -533,8 +505,7 @@ def select(self, object): return True def click(self, object): - """ Handles an object being clicked. - """ + """Handles an object being clicked.""" if self.on_click is not None: self.on_click(object) return None @@ -542,8 +513,7 @@ def click(self, object): return True def dclick(self, object): - """ Handles an object being double-clicked. - """ + """Handles an object being double-clicked.""" if self.on_dclick is not None: self.on_dclick(object) return None @@ -551,8 +521,7 @@ def dclick(self, object): return True def activated(self, object): - """ Handles an object being activated. - """ + """Handles an object being activated.""" if self.on_activated is not None: self.on_activated(object) return None @@ -560,8 +529,7 @@ def activated(self, object): return True def is_addable(self, klass): - """ Returns whether a specified object class can be added to the node. - """ + """Returns whether a specified object class can be added to the node.""" for item in self.add: if type(item) in SequenceTypes: item = item[0] @@ -572,8 +540,7 @@ def is_addable(self, klass): return False def _class_for(self, object): - """ Returns the class of an object. - """ + """Returns the class of an object.""" if isinstance(object, type): return object @@ -587,31 +554,25 @@ def _class_for(self, object): class ITreeNode(Interface): def allows_children(self): - """ Returns whether this object can have children. - """ + """Returns whether this object can have children.""" def has_children(self): - """ Returns whether the object has children. - """ + """Returns whether the object has children.""" def get_children(self): - """ Gets the object's children. - """ + """Gets the object's children.""" def get_children_id(self): - """ Gets the object's children identifier. - """ + """Gets the object's children identifier.""" def append_child(self, child): - """ Appends a child to the object's children. - """ + """Appends a child to the object's children.""" def insert_child(self, index, child): - """ Inserts a child into the object's children. - """ + """Inserts a child into the object's children.""" def confirm_delete(self): - """ Checks whether a specified object can be deleted. + """Checks whether a specified object can be deleted. The following return values are possible: @@ -622,38 +583,34 @@ def confirm_delete(self): """ def delete_child(self, index): - """ Deletes a child at a specified index from the object's children. - """ + """Deletes a child at a specified index from the object's children.""" def when_children_replaced(self, listener, remove): - """ Sets up or removes a listener for children being replaced on a - specified object. + """Sets up or removes a listener for children being replaced on a + specified object. """ def when_children_changed(self, listener, remove): - """ Sets up or removes a listener for children being changed on a - specified object. + """Sets up or removes a listener for children being changed on a + specified object. """ def get_label(self): - """ Gets the label to display for a specified object. - """ + """Gets the label to display for a specified object.""" def set_label(self, label): - """ Sets the label for a specified object. - """ + """Sets the label for a specified object.""" def when_label_changed(self, listener, remove): - """ Sets up or removes a listener for the label being changed on a - specified object. + """Sets up or removes a listener for the label being changed on a + specified object. """ def get_column_labels(self, object): - """ Get the labels for any columns that have been defined. - """ + """Get the labels for any columns that have been defined.""" def when_column_labels_change(self, object, listener, remove): - """ Sets up or removes a listener for the column labels being changed + """Sets up or removes a listener for the column labels being changed on a specified object. This will fire when either the list is reassigned or when it is @@ -663,96 +620,78 @@ def when_column_labels_change(self, object, listener, remove): """ def get_tooltip(self): - """ Gets the tooltip to display for a specified object. - """ + """Gets the tooltip to display for a specified object.""" def get_icon(self, is_expanded): - """ Returns the icon for a specified object. - """ + """Returns the icon for a specified object.""" def get_icon_path(self): - """ Returns the path used to locate an object's icon. - """ + """Returns the path used to locate an object's icon.""" def get_name(self): - """ Returns the name to use when adding a new object instance - (displayed in the "New" submenu). + """Returns the name to use when adding a new object instance + (displayed in the "New" submenu). """ def get_view(self): - """ Gets the view to use when editing an object. - """ + """Gets the view to use when editing an object.""" def get_menu(self): - """ Returns the right-click context menu for an object. - """ + """Returns the right-click context menu for an object.""" def can_rename(self): - """ Returns whether the object's children can be renamed. - """ + """Returns whether the object's children can be renamed.""" def can_rename_me(self): - """ Returns whether the object can be renamed. - """ + """Returns whether the object can be renamed.""" def can_copy(self): - """ Returns whether the object's children can be copied. - """ + """Returns whether the object's children can be copied.""" def can_delete(self): - """ Returns whether the object's children can be deleted. - """ + """Returns whether the object's children can be deleted.""" def can_delete_me(self): - """ Returns whether the object can be deleted. - """ + """Returns whether the object can be deleted.""" def can_insert(self): - """ Returns whether the object's children can be inserted (vs. - appended). + """Returns whether the object's children can be inserted (vs. + appended). """ def can_auto_open(self): - """ Returns whether the object's children should be automatically - opened. + """Returns whether the object's children should be automatically + opened. """ def can_auto_close(self): - """ Returns whether the object's children should be automatically - closed. + """Returns whether the object's children should be automatically + closed. """ def can_add(self, add_object): - """ Returns whether a given object is droppable on the node. - """ + """Returns whether a given object is droppable on the node.""" def get_add(self): - """ Returns the list of classes that can be added to the object. - """ + """Returns the list of classes that can be added to the object.""" def get_drag_object(self): - """ Returns a draggable version of a specified object. - """ + """Returns a draggable version of a specified object.""" def drop_object(self, dropped_object): - """ Returns a droppable version of a specified object. - """ + """Returns a droppable version of a specified object.""" def select(self): - """ Handles an object being selected. - """ + """Handles an object being selected.""" def click(self): - """ Handles an object being clicked. - """ + """Handles an object being clicked.""" def dclick(self): - """ Handles an object being double-clicked. - """ + """Handles an object being double-clicked.""" def activated(self): - """ Handles an object being activated. - """ + """Handles an object being activated.""" # ------------------------------------------------------------------------- @@ -761,7 +700,7 @@ def activated(self): class ITreeNodeAdapter(Adapter): - """ Abstract base class for an adapter that implements the ITreeNode + """Abstract base class for an adapter that implements the ITreeNode interface. Usage: @@ -783,37 +722,31 @@ class ITreeNodeAdapter(Adapter): """ def allows_children(self): - """ Returns whether this object can have children. - """ + """Returns whether this object can have children.""" return False def has_children(self): - """ Returns whether the object has children. - """ + """Returns whether the object has children.""" return False def get_children(self): - """ Gets the object's children. - """ + """Gets the object's children.""" return [] def get_children_id(self): - """ Gets the object's children identifier. - """ + """Gets the object's children identifier.""" return "" def append_child(self, child): - """ Appends a child to the object's children. - """ + """Appends a child to the object's children.""" pass def insert_child(self, index, child): - """ Inserts a child into the object's children. - """ + """Inserts a child into the object's children.""" pass def confirm_delete(self): - """ Checks whether a specified object can be deleted. + """Checks whether a specified object can be deleted. The following return values are possible: @@ -825,45 +758,41 @@ def confirm_delete(self): return False def delete_child(self, index): - """ Deletes a child at a specified index from the object's children. - """ + """Deletes a child at a specified index from the object's children.""" pass def when_children_replaced(self, listener, remove): - """ Sets up or removes a listener for children being replaced on a - specified object. + """Sets up or removes a listener for children being replaced on a + specified object. """ pass def when_children_changed(self, listener, remove): - """ Sets up or removes a listener for children being changed on a - specified object. + """Sets up or removes a listener for children being changed on a + specified object. """ pass def get_label(self): - """ Gets the label to display for a specified object. - """ + """Gets the label to display for a specified object.""" return "No label specified" def set_label(self, label): - """ Sets the label for a specified object. - """ + """Sets the label for a specified object.""" pass def when_label_changed(self, listener, remove): - """ Sets up or removes a listener for the label being changed on a - specified object. + """Sets up or removes a listener for the label being changed on a + specified object. """ pass def get_column_labels(self): - """ Get the labels for any columns that have been defined. - """ + """Get the labels for any columns that have been defined.""" return [] def when_column_labels_change(self, listener, remove): - """ Sets up or removes a listener for the column labels being changed + """Sets up or removes a listener for the column labels being changed on a specified object. This will fire when either the list is reassigned or when it is @@ -874,12 +803,11 @@ def when_column_labels_change(self, listener, remove): pass def get_tooltip(self): - """ Gets the tooltip to display for a specified object. - """ + """Gets the tooltip to display for a specified object.""" return "" def get_icon(self, is_expanded): - """ Returns the icon for a specified object. + """Returns the icon for a specified object. Valid values are '' (file looking icon), '' (closed folder looking icon) and '' (open folder looking icon). @@ -887,122 +815,103 @@ def get_icon(self, is_expanded): return "" def get_icon_path(self): - """ Returns the path used to locate an object's icon. - """ + """Returns the path used to locate an object's icon.""" return "" def get_name(self): - """ Returns the name to use when adding a new object instance - (displayed in the "New" submenu). + """Returns the name to use when adding a new object instance + (displayed in the "New" submenu). """ return "" def get_view(self): - """ Gets the view to use when editing an object. - """ + """Gets the view to use when editing an object.""" return None def get_menu(self): - """ Returns the right-click context menu for an object. - """ + """Returns the right-click context menu for an object.""" return None def get_background(self): - """ Returns the background for object - """ + """Returns the background for object""" return None def get_foreground(self): - """ Returns the foreground for object - """ + """Returns the foreground for object""" return None def get_renderer(self, column=0): - """ Returns the renderer for object - """ + """Returns the renderer for object""" return None def can_rename(self): - """ Returns whether the object's children can be renamed. - """ + """Returns whether the object's children can be renamed.""" return False def can_rename_me(self): - """ Returns whether the object can be renamed. - """ + """Returns whether the object can be renamed.""" return False def can_copy(self): - """ Returns whether the object's children can be copied. - """ + """Returns whether the object's children can be copied.""" return False def can_delete(self): - """ Returns whether the object's children can be deleted. - """ + """Returns whether the object's children can be deleted.""" return False def can_delete_me(self): - """ Returns whether the object can be deleted. - """ + """Returns whether the object can be deleted.""" return False def can_insert(self): - """ Returns whether the object's children can be inserted (vs. - appended). + """Returns whether the object's children can be inserted (vs. + appended). """ return False def can_auto_open(self): - """ Returns whether the object's children should be automatically - opened. + """Returns whether the object's children should be automatically + opened. """ return False def can_auto_close(self): - """ Returns whether the object's children should be automatically - closed. + """Returns whether the object's children should be automatically + closed. """ return False def can_add(self, add_object): - """ Returns whether a given object is droppable on the node. - """ + """Returns whether a given object is droppable on the node.""" return False def get_add(self): - """ Returns the list of classes that can be added to the object. - """ + """Returns the list of classes that can be added to the object.""" return [] def get_drag_object(self): - """ Returns a draggable version of a specified object. - """ + """Returns a draggable version of a specified object.""" return self.adaptee def drop_object(self, dropped_object): - """ Returns a droppable version of a specified object. - """ + """Returns a droppable version of a specified object.""" return dropped_object def select(self): - """ Handles an object being selected. - """ + """Handles an object being selected.""" pass def click(self): - """ Handles an object being clicked. - """ + """Handles an object being clicked.""" pass def dclick(self): - """ Handles an object being double-clicked. - """ + """Handles an object being double-clicked.""" pass def activated(self): - """ Handles an object being activated. - """ + """Handles an object being activated.""" pass @@ -1012,9 +921,9 @@ def activated(self): class ITreeNodeAdapterBridge(HasPrivateTraits): - """ Private class for use by a toolkit-specific implementation of the - TreeEditor to allow bridging the TreeNode interface used by the editor - to the ITreeNode interface used by object adapters. + """Private class for use by a toolkit-specific implementation of the + TreeEditor to allow bridging the TreeNode interface used by the editor + to the ITreeNode interface used by object adapters. """ #: The ITreeNode adapter being bridged: @@ -1023,37 +932,31 @@ class ITreeNodeAdapterBridge(HasPrivateTraits): # -- TreeNode implementation ---------------------------------------------- def allows_children(self, object): - """ Returns whether this object can have children. - """ + """Returns whether this object can have children.""" return self.adapter.allows_children() def has_children(self, object): - """ Returns whether the object has children. - """ + """Returns whether the object has children.""" return self.adapter.has_children() def get_children(self, object): - """ Gets the object's children. - """ + """Gets the object's children.""" return self.adapter.get_children() def get_children_id(self, object): - """ Gets the object's children identifier. - """ + """Gets the object's children identifier.""" return self.adapter.get_children_id() def append_child(self, object, child): - """ Appends a child to the object's children. - """ + """Appends a child to the object's children.""" return self.adapter.append_child(child) def insert_child(self, object, index, child): - """ Inserts a child into the object's children. - """ + """Inserts a child into the object's children.""" return self.adapter.insert_child(index, child) def confirm_delete(self, object): - """ Checks whether a specified object can be deleted. + """Checks whether a specified object can be deleted. The following return values are possible: @@ -1065,45 +968,41 @@ def confirm_delete(self, object): return self.adapter.confirm_delete() def delete_child(self, object, index): - """ Deletes a child at a specified index from the object's children. - """ + """Deletes a child at a specified index from the object's children.""" return self.adapter.delete_child(index) def when_children_replaced(self, object, listener, remove): - """ Sets up or removes a listener for children being replaced on a - specified object. + """Sets up or removes a listener for children being replaced on a + specified object. """ return self.adapter.when_children_replaced(listener, remove) def when_children_changed(self, object, listener, remove): - """ Sets up or removes a listener for children being changed on a - specified object. + """Sets up or removes a listener for children being changed on a + specified object. """ return self.adapter.when_children_changed(listener, remove) def get_label(self, object): - """ Gets the label to display for a specified object. - """ + """Gets the label to display for a specified object.""" return self.adapter.get_label() def set_label(self, object, label): - """ Sets the label for a specified object. - """ + """Sets the label for a specified object.""" return self.adapter.set_label(label) def when_label_changed(self, object, listener, remove): - """ Sets up or removes a listener for the label being changed on a - specified object. + """Sets up or removes a listener for the label being changed on a + specified object. """ return self.adapter.when_label_changed(listener, remove) def get_column_labels(self, object): - """ Get the labels for any columns that have been defined. - """ + """Get the labels for any columns that have been defined.""" return self.adapter.get_column_labels() def when_column_labels_change(self, object, listener, remove): - """ Sets up or removes a listener for the column labels being changed + """Sets up or removes a listener for the column labels being changed on a specified object. This will fire when either the list is reassigned or when it is @@ -1114,132 +1013,111 @@ def when_column_labels_change(self, object, listener, remove): return self.adapter.when_column_labels_change(listener, remove) def get_tooltip(self, object): - """ Gets the tooltip to display for a specified object. - """ + """Gets the tooltip to display for a specified object.""" return self.adapter.get_tooltip() def get_icon(self, object, is_expanded): - """ Returns the icon for a specified object. - """ + """Returns the icon for a specified object.""" return self.adapter.get_icon(is_expanded) def get_icon_path(self, object): - """ Returns the path used to locate an object's icon. - """ + """Returns the path used to locate an object's icon.""" return self.adapter.get_icon_path() def get_name(self, object): - """ Returns the name to use when adding a new object instance - (displayed in the "New" submenu). + """Returns the name to use when adding a new object instance + (displayed in the "New" submenu). """ return self.adapter.get_name() def get_view(self, object): - """ Gets the view to use when editing an object. - """ + """Gets the view to use when editing an object.""" return self.adapter.get_view() def get_menu(self, object): - """ Returns the right-click context menu for an object. - """ + """Returns the right-click context menu for an object.""" return self.adapter.get_menu() def get_background(self, object): - """ Returns the background for object - """ + """Returns the background for object""" return self.adapter.get_background() def get_foreground(self, object): - """ Returns the foreground for object - """ + """Returns the foreground for object""" return self.adapter.get_foreground() def get_renderer(self, object, column=0): - """ Returns the renderer for object - """ + """Returns the renderer for object""" return self.adapter.get_renderer(column) def can_rename(self, object): - """ Returns whether the object's children can be renamed. - """ + """Returns whether the object's children can be renamed.""" return self.adapter.can_rename() def can_rename_me(self, object): - """ Returns whether the object can be renamed. - """ + """Returns whether the object can be renamed.""" return self.adapter.can_rename_me() def can_copy(self, object): - """ Returns whether the object's children can be copied. - """ + """Returns whether the object's children can be copied.""" return self.adapter.can_copy() def can_delete(self, object): - """ Returns whether the object's children can be deleted. - """ + """Returns whether the object's children can be deleted.""" return self.adapter.can_delete() def can_delete_me(self, object): - """ Returns whether the object can be deleted. - """ + """Returns whether the object can be deleted.""" return self.adapter.can_delete_me() def can_insert(self, object): - """ Returns whether the object's children can be inserted (vs. - appended). + """Returns whether the object's children can be inserted (vs. + appended). """ return self.adapter.can_insert() def can_auto_open(self, object): - """ Returns whether the object's children should be automatically - opened. + """Returns whether the object's children should be automatically + opened. """ return self.adapter.can_auto_open() def can_auto_close(self, object): - """ Returns whether the object's children should be automatically - closed. + """Returns whether the object's children should be automatically + closed. """ return self.adapter.can_auto_close() def can_add(self, object, add_object): - """ Returns whether a given object is droppable on the node. - """ + """Returns whether a given object is droppable on the node.""" return self.adapter.can_add(add_object) def get_add(self, object): - """ Returns the list of classes that can be added to the object. - """ + """Returns the list of classes that can be added to the object.""" return self.adapter.get_add() def get_drag_object(self, object): - """ Returns a draggable version of a specified object. - """ + """Returns a draggable version of a specified object.""" return self.adapter.get_drag_object() def drop_object(self, object, dropped_object): - """ Returns a droppable version of a specified object. - """ + """Returns a droppable version of a specified object.""" return self.adapter.drop_object(dropped_object) def select(self, object): - """ Handles an object being selected. - """ + """Handles an object being selected.""" return self.adapter.select() def click(self, object): - """ Handles an object being clicked. - """ + """Handles an object being clicked.""" return self.adapter.click() def dclick(self, object): - """ Handles an object being double-clicked. - """ + """Handles an object being double-clicked.""" return self.adapter.dclick() def activated(self, object): - """ Handles an object being activated. - """ + """Handles an object being activated.""" return self.adapter.activated() @@ -1253,37 +1131,31 @@ def activated(self, object): class ObjectTreeNode(TreeNode): def allows_children(self, object): - """ Returns whether this object can have children. - """ + """Returns whether this object can have children.""" return object.tno_allows_children(self) def has_children(self, object): - """ Returns whether the object has children. - """ + """Returns whether the object has children.""" return object.tno_has_children(self) def get_children(self, object): - """ Gets the object's children. - """ + """Gets the object's children.""" return object.tno_get_children(self) def get_children_id(self, object): - """ Gets the object's children identifier. - """ + """Gets the object's children identifier.""" return object.tno_get_children_id(self) def append_child(self, object, child): - """ Appends a child to the object's children. - """ + """Appends a child to the object's children.""" return object.tno_append_child(self, child) def insert_child(self, object, index, child): - """ Inserts a child into the object's children. - """ + """Inserts a child into the object's children.""" return object.tno_insert_child(self, index, child) def confirm_delete(self, object): - """ Checks whether a specified object can be deleted. + """Checks whether a specified object can be deleted. The following return values are possible: @@ -1295,115 +1167,102 @@ def confirm_delete(self, object): return object.tno_confirm_delete(self) def delete_child(self, object, index): - """ Deletes a child at a specified index from the object's children. - """ + """Deletes a child at a specified index from the object's children.""" return object.tno_delete_child(self, index) def when_children_replaced(self, object, listener, remove): - """ Sets up or removes a listener for children being replaced on a - specified object. + """Sets up or removes a listener for children being replaced on a + specified object. """ return object.tno_when_children_replaced(self, listener, remove) def when_children_changed(self, object, listener, remove): - """ Sets up or removes a listener for children being changed on a - specified object. + """Sets up or removes a listener for children being changed on a + specified object. """ return object.tno_when_children_changed(self, listener, remove) def get_label(self, object): - """ Gets the label to display for a specified object. - """ + """Gets the label to display for a specified object.""" return object.tno_get_label(self) def set_label(self, object, label): - """ Sets the label for a specified object. - """ + """Sets the label for a specified object.""" return object.tno_set_label(self, label) def when_label_changed(self, object, listener, remove): - """ Sets up or removes a listener for the label being changed on a - specified object. + """Sets up or removes a listener for the label being changed on a + specified object. """ return object.tno_when_label_changed(self, listener, remove) def get_tooltip(self, object): - """ Gets the tooltip to display for a specified object. - """ + """Gets the tooltip to display for a specified object.""" return object.tno_get_tooltip(self) def get_icon(self, object, is_expanded): - """ Returns the icon for a specified object. - """ + """Returns the icon for a specified object.""" return object.tno_get_icon(self, is_expanded) def get_icon_path(self, object): - """ Returns the path used to locate an object's icon. - """ + """Returns the path used to locate an object's icon.""" return object.tno_get_icon_path(self) def get_name(self, object): - """ Returns the name to use when adding a new object instance - (displayed in the "New" submenu). + """Returns the name to use when adding a new object instance + (displayed in the "New" submenu). """ return object.tno_get_name(self) def get_view(self, object): - """ Gets the view to use when editing an object. - """ + """Gets the view to use when editing an object.""" return object.tno_get_view(self) def get_menu(self, object): - """ Returns the right-click context menu for an object. - """ + """Returns the right-click context menu for an object.""" return object.tno_get_menu(self) def can_rename(self, object): - """ Returns whether the object's children can be renamed. - """ + """Returns whether the object's children can be renamed.""" return object.tno_can_rename(self) def can_rename_me(self, object): - """ Returns whether the object can be renamed. - """ + """Returns whether the object can be renamed.""" return object.tno_can_rename_me(self) def can_copy(self, object): - """ Returns whether the object's children can be copied. - """ + """Returns whether the object's children can be copied.""" return object.tno_can_copy(self) def can_delete(self, object): - """ Returns whether the object's children can be deleted. - """ + """Returns whether the object's children can be deleted.""" return object.tno_can_delete(self) def can_delete_me(self, object): - """ Returns whether the object can be deleted. - """ + """Returns whether the object can be deleted.""" return object.tno_can_delete_me(self) def can_insert(self, object): - """ Returns whether the object's children can be inserted (vs. + """Returns whether the object's children can be inserted (vs. appended). """ return object.tno_can_insert(self) def can_auto_open(self, object): - """ Returns whether the object's children should be automatically - opened. + """Returns whether the object's children should be automatically + opened. """ return object.tno_can_auto_open(self) def can_auto_close(self, object): - """ Returns whether the object's children should be automatically - closed. + """Returns whether the object's children should be automatically + closed. """ return object.tno_can_auto_close(self) def is_node_for(self, object): - """ Returns whether this is the node that should handle a - specified object. + """Returns whether this is the node that should handle a + specified object. """ if isinstance(object, TreeNodeObject): return object.tno_is_node_for(self) @@ -1411,86 +1270,71 @@ def is_node_for(self, object): return False def can_add(self, object, add_object): - """ Returns whether a given object is droppable on the node. - """ + """Returns whether a given object is droppable on the node.""" return object.tno_can_add(self, add_object) def get_add(self, object): - """ Returns the list of classes that can be added to the object. - """ + """Returns the list of classes that can be added to the object.""" return object.tno_get_add(self) def get_drag_object(self, object): - """ Returns a draggable version of a specified object. - """ + """Returns a draggable version of a specified object.""" return object.tno_get_drag_object(self) def drop_object(self, object, dropped_object): - """ Returns a droppable version of a specified object. - """ + """Returns a droppable version of a specified object.""" return object.tno_drop_object(self, dropped_object) def select(self, object): - """ Handles an object being selected. - """ + """Handles an object being selected.""" return object.tno_select(self) def click(self, object): - """ Handles an object being clicked. - """ + """Handles an object being clicked.""" return object.tno_click(self) def dclick(self, object): - """ Handles an object being double-clicked. - """ + """Handles an object being double-clicked.""" return object.tno_dclick(self) def activated(self, object): - """ Handles an object being activated. - """ + """Handles an object being activated.""" return object.tno_activated(self) class TreeNodeObject(HasPrivateTraits): - """ Represents the object that corresponds to a tree node. - """ + """Represents the object that corresponds to a tree node.""" #: A cache for listeners that need to keep state. _listener_cache = Dict() def tno_allows_children(self, node): - """ Returns whether this object allows children. - """ + """Returns whether this object allows children.""" return node.children != "" def tno_has_children(self, node): - """ Returns whether this object has children. - """ + """Returns whether this object has children.""" return len(self.tno_get_children(node)) > 0 def tno_get_children(self, node): - """ Gets the object's children. - """ + """Gets the object's children.""" return getattr(self, node.children, None) def tno_get_children_id(self, node): - """ Gets the object's children identifier. - """ + """Gets the object's children identifier.""" return node.children def tno_append_child(self, node, child): - """ Appends a child to the object's children. - """ + """Appends a child to the object's children.""" self.tno_get_children(node).append(child) def tno_insert_child(self, node, index, child): - """ Inserts a child into the object's children. - """ + """Inserts a child into the object's children.""" children = self.tno_get_children(node) children[index:index] = [child] def tno_confirm_delete(self, node): - """ Checks whether a specified object can be deleted. + """Checks whether a specified object can be deleted. The following return values are possible: @@ -1502,13 +1346,12 @@ def tno_confirm_delete(self, node): return None def tno_delete_child(self, node, index): - """ Deletes a child at a specified index from the object's children. - """ + """Deletes a child at a specified index from the object's children.""" del self.tno_get_children(node)[index] def tno_when_children_replaced(self, node, listener, remove): - """ Sets up or removes a listener for children being replaced on a + """Sets up or removes a listener for children being replaced on a specified object. """ self.on_trait_change( @@ -1516,7 +1359,7 @@ def tno_when_children_replaced(self, node, listener, remove): ) def tno_when_children_changed(self, node, listener, remove): - """ Sets up or removes a listener for children being changed on a + """Sets up or removes a listener for children being changed on a specified object. """ self.on_trait_change( @@ -1527,8 +1370,7 @@ def tno_when_children_changed(self, node, listener, remove): ) def tno_get_label(self, node): - """ Gets the label to display for a specified object. - """ + """Gets the label to display for a specified object.""" label = node.label if label[:1] == "=": return label[1:] @@ -1541,14 +1383,13 @@ def tno_get_label(self, node): return node.formatter(self, label) def tno_set_label(self, node, label): - """ Sets the label for a specified object. - """ + """Sets the label for a specified object.""" label_name = node.label if label_name[:1] != "=": xsetattr(self, label_name, label) def tno_when_label_changed(self, node, listener, remove): - """ Sets up or removes a listener for the label being changed on a + """Sets up or removes a listener for the label being changed on a specified object. """ label = node.label @@ -1557,7 +1398,7 @@ def tno_when_label_changed(self, node, listener, remove): if not remove: def wrapped_listener(target, name, new): - """ Ensure listener gets called with correct object. """ + """Ensure listener gets called with correct object.""" return listener(self, name, new) self._listener_cache[memo] = wrapped_listener @@ -1571,8 +1412,7 @@ def wrapped_listener(target, name, new): ) def tno_get_tooltip(self, node): - """ Gets the tooltip to display for a specified object. - """ + """Gets the tooltip to display for a specified object.""" tooltip = node.tooltip if tooltip == "": return tooltip @@ -1588,8 +1428,7 @@ def tno_get_tooltip(self, node): return node.tooltip_formatter(self, tooltip) def tno_get_icon(self, node, is_expanded): - """ Returns the icon for a specified object. - """ + """Returns the icon for a specified object.""" if not self.tno_allows_children(node): return node.icon_item @@ -1599,80 +1438,71 @@ def tno_get_icon(self, node, is_expanded): return node.icon_group def tno_get_icon_path(self, node): - """ Returns the path used to locate an object's icon. - """ + """Returns the path used to locate an object's icon.""" return node.icon_path def tno_get_name(self, node): - """ Returns the name to use when adding a new object instance - (displayed in the "New" submenu). + """Returns the name to use when adding a new object instance + (displayed in the "New" submenu). """ return node.name def tno_get_view(self, node): - """ Gets the view to use when editing an object. - """ + """Gets the view to use when editing an object.""" return node.view def tno_get_menu(self, node): - """ Returns the right-click context menu for an object. - """ + """Returns the right-click context menu for an object.""" return node.menu def tno_can_rename(self, node): - """ Returns whether the object's children can be renamed. - """ + """Returns whether the object's children can be renamed.""" return node.rename def tno_can_rename_me(self, node): - """ Returns whether the object can be renamed. - """ + """Returns whether the object can be renamed.""" return node.rename_me def tno_can_copy(self, node): - """ Returns whether the object's children can be copied. - """ + """Returns whether the object's children can be copied.""" return node.copy def tno_can_delete(self, node): - """ Returns whether the object's children can be deleted. - """ + """Returns whether the object's children can be deleted.""" return node.delete def tno_can_delete_me(self, node): - """ Returns whether the object can be deleted. - """ + """Returns whether the object can be deleted.""" return node.delete_me def tno_can_insert(self, node): - """ Returns whether the object's children can be inserted (vs. + """Returns whether the object's children can be inserted (vs. appended). """ return node.insert def tno_can_auto_open(self, node): - """ Returns whether the object's children should be automatically + """Returns whether the object's children should be automatically opened. """ return node.auto_open def tno_can_auto_close(self, node): - """ Returns whether the object's children should be automatically + """Returns whether the object's children should be automatically closed. """ return node.auto_close def tno_is_node_for(self, node): - """ Returns whether this is the node that should handle a - specified object. + """Returns whether this is the node that should handle a + specified object. """ return isinstance( self, node.node_for_class ) or self.has_traits_interface(*node.node_for_interface) def tno_can_add(self, node, add_object): - """ Returns whether a given object is droppable on the node. - """ + """Returns whether a given object is droppable on the node.""" klass = node._class_for(add_object) if node.is_addable(klass): return True @@ -1686,18 +1516,15 @@ def tno_can_add(self, node, add_object): return False def tno_get_add(self, node): - """ Returns the list of classes that can be added to the object. - """ + """Returns the list of classes that can be added to the object.""" return node.add def tno_get_drag_object(self, node): - """ Returns a draggable version of a specified object. - """ + """Returns a draggable version of a specified object.""" return self def tno_drop_object(self, node, dropped_object): - """ Returns a droppable version of a specified object. - """ + """Returns a droppable version of a specified object.""" if node.is_addable(dropped_object): return dropped_object @@ -1710,8 +1537,7 @@ def tno_drop_object(self, node, dropped_object): return dropped_object def tno_select(self, node): - """ Handles an object being selected. - """ + """Handles an object being selected.""" if node.on_select is not None: node.on_select(self) return None @@ -1719,8 +1545,7 @@ def tno_select(self, node): return True def tno_click(self, node): - """ Handles an object being clicked. - """ + """Handles an object being clicked.""" if node.on_click is not None: node.on_click(self) return None @@ -1728,8 +1553,7 @@ def tno_click(self, node): return True def tno_dclick(self, node): - """ Handles an object being double-clicked. - """ + """Handles an object being double-clicked.""" if node.on_dclick is not None: node.on_dclick(self) return None @@ -1737,8 +1561,7 @@ def tno_dclick(self, node): return True def tno_activated(self, node): - """ Handles an object being activated. - """ + """Handles an object being activated.""" if node.on_activated is not None: node.on_activated(self) return None @@ -1764,162 +1587,143 @@ class MultiTreeNode(TreeNode): nodes = List(TreeNode) def allows_children(self, object): - """ Returns whether this object can have children (True for this + """Returns whether this object can have children (True for this class). """ return True def has_children(self, object): - """ Returns whether this object has children (True for this class). - """ + """Returns whether this object has children (True for this class).""" return True def get_children(self, object): - """ Gets the object's children. - """ + """Gets the object's children.""" return [(object, node) for node in self.nodes] def get_children_id(self, object): - """ Gets the object's children identifier. - """ + """Gets the object's children identifier.""" return "" def when_children_replaced(self, object, listener, remove): - """ Sets up or removes a listener for children being replaced on a + """Sets up or removes a listener for children being replaced on a specified object. """ pass def when_children_changed(self, object, listener, remove): - """ Sets up or removes a listener for children being changed on a + """Sets up or removes a listener for children being changed on a specified object. """ pass def get_label(self, object): - """ Gets the label to display for a specified object. - """ + """Gets the label to display for a specified object.""" return self.root_node.get_label(object) def set_label(self, object, label): - """ Sets the label for a specified object. - """ + """Sets the label for a specified object.""" return self.root_node.set_label(object, label) def when_label_changed(self, object, listener, remove): - """ Sets up or removes a listener for the label being changed on a + """Sets up or removes a listener for the label being changed on a specified object. """ return self.root_node.when_label_changed(object, listener, remove) def get_icon(self, object, is_expanded): - """ Returns the icon for a specified object. - """ + """Returns the icon for a specified object.""" return self.root_node.get_icon(object, is_expanded) def get_icon_path(self, object): - """ Returns the path used to locate an object's icon. - """ + """Returns the path used to locate an object's icon.""" return self.root_node.get_icon_path(object) def get_name(self, object): - """ Returns the name to use when adding a new object instance - (displayed in the "New" submenu). + """Returns the name to use when adding a new object instance + (displayed in the "New" submenu). """ return self.root_node.get_name(object) def get_view(self, object): - """ Gets the view to use when editing an object. - """ + """Gets the view to use when editing an object.""" return self.root_node.get_view(object) def get_menu(self, object): - """ Returns the right-click context menu for an object. - """ + """Returns the right-click context menu for an object.""" return self.root_node.get_menu(object) def can_rename(self, object): - """ Returns whether the object's children can be renamed (False for + """Returns whether the object's children can be renamed (False for this class). """ return False def can_rename_me(self, object): - """ Returns whether the object can be renamed (False for this class). - """ + """Returns whether the object can be renamed (False for this class).""" return False def can_copy(self, object): - """ Returns whether the object's children can be copied. - """ + """Returns whether the object's children can be copied.""" return self.root_node.can_copy(object) def can_delete(self, object): - """ Returns whether the object's children can be deleted (False for + """Returns whether the object's children can be deleted (False for this class). """ return False def can_delete_me(self, object): - """ Returns whether the object can be deleted (True for this class). - """ + """Returns whether the object can be deleted (True for this class).""" return True def can_insert(self, object): - """ Returns whether the object's children can be inserted (False, + """Returns whether the object's children can be inserted (False, meaning that children are appended, for this class). """ return False def can_auto_open(self, object): - """ Returns whether the object's children should be automatically + """Returns whether the object's children should be automatically opened. """ return self.root_node.can_auto_open(object) def can_auto_close(self, object): - """ Returns whether the object's children should be automatically + """Returns whether the object's children should be automatically closed. """ return self.root_node.can_auto_close(object) def can_add(self, object, add_object): - """ Returns whether a given object is droppable on the node (False for + """Returns whether a given object is droppable on the node (False for this class). """ return False def get_add(self, object): - """ Returns the list of classes that can be added to the object. - """ + """Returns the list of classes that can be added to the object.""" return [] def get_drag_object(self, object): - """ Returns a draggable version of a specified object. - """ + """Returns a draggable version of a specified object.""" return self.root_node.get_drag_object(object) def drop_object(self, object, dropped_object): - """ Returns a droppable version of a specified object. - """ + """Returns a droppable version of a specified object.""" return self.root_node.drop_object(object, dropped_object) def select(self, object): - """ Handles an object being selected. - """ + """Handles an object being selected.""" return self.root_node.select(object) def click(self, object): - """ Handles an object being clicked. - """ + """Handles an object being clicked.""" return self.root_node.click(object) def dclick(self, object): - """ Handles an object being double-clicked. - """ + """Handles an object being double-clicked.""" return self.root_node.dclick(object) def activated(self, object): - """ Handles an object being activated. - """ + """Handles an object being activated.""" return self.root_node.activated(object) diff --git a/traitsui/tree_node_renderer.py b/traitsui/tree_node_renderer.py index e7a11e6c4..c44480525 100644 --- a/traitsui/tree_node_renderer.py +++ b/traitsui/tree_node_renderer.py @@ -14,7 +14,7 @@ class AbstractTreeNodeRenderer(ABCHasStrictTraits): - """ Abstract base class for renderers of tree node items. + """Abstract base class for renderers of tree node items. This is currently only supported for Qt. """ @@ -30,7 +30,7 @@ class AbstractTreeNodeRenderer(ABCHasStrictTraits): @abstractmethod def paint(self, node, column, object, paint_context): - """ Render the node. + """Render the node. Parameters ---------- @@ -53,7 +53,7 @@ def paint(self, node, column, object, paint_context): @abstractmethod def size(self, node, column, object, size_context): - """ Return the preferred size for the item + """Return the preferred size for the item Parameters ---------- @@ -73,7 +73,7 @@ def size(self, node, column, object, size_context): raise NotImplementedError() def get_label(self, node, object, column=0): - """ Get the label associated with an item and column. """ + """Get the label associated with an item and column.""" if column == 0: return node.get_label(object) else: diff --git a/traitsui/ui.py b/traitsui/ui.py index 908295744..155679f1c 100644 --- a/traitsui/ui.py +++ b/traitsui/ui.py @@ -56,8 +56,7 @@ class UI(HasPrivateTraits): - """ Information about the user interface for a View. - """ + """Information about the user interface for a View.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -221,14 +220,12 @@ class UI(HasPrivateTraits): ] def traits_init(self): - """ Initializes the traits object. - """ + """Initializes the traits object.""" self.info = UIInfo(ui=self) self.handler.init_info(self.info) def ui(self, parent, kind): - """ Creates a user interface from the associated View template object. - """ + """Creates a user interface from the associated View template object.""" if (parent is None) and (kind in kind_must_have_parent): kind = "live" self.view.on_trait_change( @@ -238,8 +235,7 @@ def ui(self, parent, kind): self.rebuild(self, parent) def dispose(self, result=None, abort=False): - """ Disposes of the contents of a user interface. - """ + """Disposes of the contents of a user interface.""" if self.parent is not None: self.parent.errors -= self.errors @@ -256,8 +252,7 @@ def dispose(self, result=None, abort=False): self.finish() def recycle(self): - """ Recycles the user interface prior to rebuilding it. - """ + """Recycles the user interface prior to rebuilding it.""" # Reset all user interface editors: self.reset(destroy=False) @@ -268,8 +263,7 @@ def recycle(self): self.reset_traits(self.recyclable_traits) def finish(self): - """ Finishes disposing of a user interface. - """ + """Finishes disposing of a user interface.""" # Destroy the control early to silence cascade events when the UI # enters an inconsistent state. toolkit().destroy_control(self.control) @@ -306,8 +300,7 @@ def finish(self): self.destroyed = True def reset(self, destroy=True): - """ Resets the contents of a user interface. - """ + """Resets the contents of a user interface.""" for editor in self._editors: if editor._ui is not None: # Propagate result to enclosed ui objects: @@ -332,8 +325,8 @@ def reset(self, destroy=True): dispatcher.remove() def find(self, include): - """ Finds the definition of the specified Include object in the current - user interface building context. + """Finds the definition of the specified Include object in the current + user interface building context. """ context = self.context result = None @@ -373,18 +366,16 @@ def find(self, include): return result def push_level(self): - """ Returns the current search stack level. - """ + """Returns the current search stack level.""" return len(self._search) def pop_level(self, level): - """ Restores a previously pushed search stack level. - """ + """Restores a previously pushed search stack level.""" del self._search[: len(self._search) - level] def prepare_ui(self): - """ Performs all processing that occurs after the user interface is - created. + """Performs all processing that occurs after the user interface is + created. """ # Invoke all of the editor 'name_defined' methods we've accumulated: info = self.info.trait_set(initialized=False) @@ -433,7 +424,7 @@ def prepare_ui(self): object = context.get(prefix[:col]) if object is not None: method = getattr(handler, name) - trait_name = prefix[col + 1:] + trait_name = prefix[col + 1 :] self._dispatchers.append( Dispatcher(method, info, object, trait_name) ) @@ -456,8 +447,7 @@ def prepare_ui(self): info.initialized = True def sync_view(self): - """ Synchronize context object traits with view editor traits. - """ + """Synchronize context object traits with view editor traits.""" for name, object in self.context.items(): self._sync_view(name, object, "sync_to_view", "from") self._sync_view(name, object, "sync_from_view", "to") @@ -493,8 +483,7 @@ def _sync_view(self, name, object, metadata, direction): ) def get_extended_value(self, name): - """ Gets the current value of a specified extended trait name. - """ + """Gets the current value of a specified extended trait name.""" names = name.split(".") if len(names) > 1: value = self.context[names[0]] @@ -508,7 +497,7 @@ def get_extended_value(self, name): return value def restore_prefs(self): - """ Retrieves and restores any saved user preference information + """Retrieves and restores any saved user preference information associated with the UI. """ id = self.id @@ -525,8 +514,7 @@ def restore_prefs(self): return None def set_prefs(self, prefs): - """ Sets the values of user preferences for the UI. - """ + """Sets the values of user preferences for the UI.""" if isinstance(prefs, dict): info = self.info for name in self._names: @@ -546,8 +534,7 @@ def set_prefs(self, prefs): return None def save_prefs(self, prefs=None): - """ Saves any user preference information associated with the UI. - """ + """Saves any user preference information associated with the UI.""" if prefs is None: toolkit().save_window(self) return @@ -560,8 +547,7 @@ def save_prefs(self, prefs=None): db.close() def get_prefs(self, prefs=None): - """ Gets the preferences to be saved for the user interface. - """ + """Gets the preferences to be saved for the user interface.""" ui_prefs = {} if prefs is not None: ui_prefs[""] = prefs @@ -580,8 +566,7 @@ def get_prefs(self, prefs=None): return ui_prefs def get_ui_db(self, mode="r"): - """ Returns a reference to the Traits UI preference database. - """ + """Returns a reference to the Traits UI preference database.""" try: return shelve.open( os.path.join(traits_home(), "traits_ui"), @@ -592,13 +577,12 @@ def get_ui_db(self, mode="r"): return None def get_editors(self, name): - """ Returns a list of editors for the given trait name. - """ + """Returns a list of editors for the given trait name.""" return [editor for editor in self._editors if editor.name == name] def get_error_controls(self): - """ Returns the list of editor error controls contained by the user - interface. + """Returns the list of editor error controls contained by the user + interface. """ controls = [] for editor in self._editors: @@ -611,14 +595,14 @@ def get_error_controls(self): return controls def add_defined(self, method): - """ Adds a Handler method to the list of methods to be called once the - user interface has been constructed. + """Adds a Handler method to the list of methods to be called once the + user interface has been constructed. """ self._defined.append(method) def add_visible(self, visible_when, editor): - """ Adds a conditionally enabled Editor object to the list of monitored - 'visible_when' objects. + """Adds a conditionally enabled Editor object to the list of monitored + 'visible_when' objects. """ try: self._visible.append( @@ -629,8 +613,8 @@ def add_visible(self, visible_when, editor): # fixme: Log an error here... def add_enabled(self, enabled_when, editor): - """ Adds a conditionally enabled Editor object to the list of monitored - 'enabled_when' objects. + """Adds a conditionally enabled Editor object to the list of monitored + 'enabled_when' objects. """ try: self._enabled.append( @@ -641,8 +625,8 @@ def add_enabled(self, enabled_when, editor): # fixme: Log an error here... def add_checked(self, checked_when, editor): - """ Adds a conditionally enabled (menu) Editor object to the list of - monitored 'checked_when' objects. + """Adds a conditionally enabled (menu) Editor object to the list of + monitored 'checked_when' objects. """ try: self._checked.append( @@ -653,8 +637,7 @@ def add_checked(self, checked_when, editor): # fixme: Log an error here... def do_undoable(self, action, *args, **kw): - """ Performs an action that can be undone. - """ + """Performs an action that can be undone.""" undoable = self._undoable try: if (undoable == -1) and (self.history is not None): @@ -666,13 +649,11 @@ def do_undoable(self, action, *args, **kw): self._undoable = -1 def route_event(self, event): - """ Routes a "hooked" event to the correct handler method. - """ + """Routes a "hooked" event to the correct handler method.""" toolkit().route_event(self, event) def key_handler(self, event, skip=True): - """ Handles key events. - """ + """Handles key events.""" key_bindings = self.key_bindings handled = (key_bindings is not None) and key_bindings.do( event, [], self.info, recursive=(self.parent is None) @@ -687,8 +668,7 @@ def key_handler(self, event, skip=True): return handled def evaluate(self, function, *args, **kw_args): - """ Evaluates a specified function in the UI's **context**. - """ + """Evaluates a specified function in the UI's **context**.""" if function is None: return None @@ -701,8 +681,8 @@ def evaluate(self, function, *args, **kw_args): return eval(function, globals(), context)(*args, **kw_args) def eval_when(self, when, result=True): - """ Evaluates an expression in the UI's **context** and returns the - result. + """Evaluates an expression in the UI's **context** and returns the + result. """ context = self._get_context(self.context) try: @@ -717,8 +697,7 @@ def eval_when(self, when, result=True): return result def _get_context(self, context): - """ Gets the context to use for evaluating an expression. - """ + """Gets the context to use for evaluating an expression.""" name = "object" n = len(context) if (n == 2) and ("handler" in context): @@ -740,14 +719,14 @@ def _get_context(self, context): return context2 def _evaluate_when(self): - """ Set the 'visible', 'enabled', and 'checked' states for all Editors - controlled by a 'visible_when', 'enabled_when' or 'checked_when' - expression. + """Set the 'visible', 'enabled', and 'checked' states for all Editors + controlled by a 'visible_when', 'enabled_when' or 'checked_when' + expression. """ self._do_evaluate_when(at_init=False) def _do_evaluate_when(self, at_init=False): - """ Set the 'visible', 'enabled', and 'checked' states for all Editors. + """Set the 'visible', 'enabled', and 'checked' states for all Editors. This function does the job of _evaluate_when. We define it here to work around the traits dispatching mechanism that automatically @@ -762,7 +741,7 @@ def _do_evaluate_when(self, at_init=False): self._evaluate_condition(self._checked, "checked", at_init) def _evaluate_condition(self, conditions, trait, at_init=False): - """ Evaluates a list of (eval, editor) pairs and sets a specified trait + """Evaluates a list of (eval, editor) pairs and sets a specified trait on each editor to reflect the Boolean value of the expression. 1) All conditions are evaluated @@ -830,7 +809,7 @@ def _evaluate_condition(self, conditions, trait, at_init=False): setattr(editor, trait, True) def _get__groups(self): - """ Returns the top-level Groups for the view (after resolving + """Returns the top-level Groups for the view (after resolving Includes. (Implements the **_groups** property.) """ if self._groups_cache is None: @@ -910,8 +889,7 @@ def _pvc_changed(self, event): class Dispatcher(object): def __init__(self, method, info, object, method_name): - """ Initializes the object. - """ + """Initializes the object.""" self.method = method self.info = info self.object = object @@ -919,13 +897,11 @@ def __init__(self, method, info, object, method_name): object.on_trait_change(self.dispatch, method_name, dispatch="ui") def dispatch(self): - """ Dispatches the method. - """ + """Dispatches the method.""" self.method(self.info) def remove(self): - """ Removes the dispatcher. - """ + """Removes the dispatcher.""" self.object.on_trait_change( self.dispatch, self.method_name, remove=True ) diff --git a/traitsui/ui_editor.py b/traitsui/ui_editor.py index a4d9255f0..20a0b0570 100644 --- a/traitsui/ui_editor.py +++ b/traitsui/ui_editor.py @@ -25,8 +25,7 @@ class UIEditor(Editor): - """ An editor that creates an embedded Traits UI. - """ + """An editor that creates an embedded Traits UI.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -36,15 +35,14 @@ class UIEditor(Editor): editor_ui = Instance(UI) def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.editor_ui = self.init_ui(parent).trait_set(parent=self.ui) self.control = self.editor_ui.control def init_ui(self, parent): - """ Creates the traits UI for the editor. - """ + """Creates the traits UI for the editor.""" return self.value.edit_traits( view=self.trait_view(), context={"object": self.value, "editor": self}, @@ -52,16 +50,15 @@ def init_ui(self, parent): ) def update_editor(self): - """ Updates the editor when the object trait changes external to the - editor. + """Updates the editor when the object trait changes external to the + editor. """ # Do nothing, since the embedded traits UI should handle the updates # itself, without our meddling: pass def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" # Make sure the embedded traits UI is disposed of properly: if self.editor_ui is not None: self.editor_ui.dispose() @@ -69,19 +66,17 @@ def dispose(self): super().dispose() def get_error_control(self): - """ Returns the editor's control for indicating error status. - """ + """Returns the editor's control for indicating error status.""" return self.editor_ui.get_error_controls() # -- UI preference save/restore interface --------------------------------- def restore_prefs(self, prefs): - """ Restores any saved user preference information associated with the - editor. + """Restores any saved user preference information associated with the + editor. """ self.editor_ui.set_prefs(prefs) def save_prefs(self): - """ Returns any user preference information associated with the editor. - """ + """Returns any user preference information associated with the editor.""" return self.editor_ui.get_prefs() diff --git a/traitsui/ui_editors/array_view_editor.py b/traitsui/ui_editors/array_view_editor.py index f1f33f70c..92ff0a310 100644 --- a/traitsui/ui_editors/array_view_editor.py +++ b/traitsui/ui_editors/array_view_editor.py @@ -46,8 +46,7 @@ def _get_content(self): return self.item def get_item(self, object, trait, row): - """ Returns the value of the *object.trait[row]* item. - """ + """Returns the value of the *object.trait[row]* item.""" if self.is_2d: if self.transpose: return getattr(object, trait)[:, row] @@ -57,8 +56,7 @@ def get_item(self, object, trait, row): return getattr(object, trait)[row] def len(self, object, trait): - """ Returns the number of items in the specified *object.trait* list. - """ + """Returns the number of items in the specified *object.trait* list.""" if self.transpose: return getattr(object, trait).shape[1] @@ -83,8 +81,7 @@ class _ArrayViewEditor(UIEditor): # -- Private Methods ------------------------------------------------------ def _array_view(self): - """ Return the view used by the editor. - """ + """Return the view used by the editor.""" return View( Item( "object.object." + self.name, @@ -101,8 +98,7 @@ def _array_view(self): ) def init_ui(self, parent): - """ Creates the Traits UI for displaying the array. - """ + """Creates the Traits UI for displaying the array.""" # Make sure that the value is an array of the correct shape: shape = self.value.shape len_shape = len(shape) @@ -180,6 +176,5 @@ class ArrayViewEditor(BasicEditorFactory): font = Font("Courier 10") def _get_klass(self): - """ The class used to construct editor objects. - """ + """The class used to construct editor objects.""" return toolkit_object("array_view_editor:_ArrayViewEditor") diff --git a/traitsui/ui_editors/data_frame_editor.py b/traitsui/ui_editors/data_frame_editor.py index bb88f3e04..777689d9f 100644 --- a/traitsui/ui_editors/data_frame_editor.py +++ b/traitsui/ui_editors/data_frame_editor.py @@ -33,13 +33,11 @@ from traitsui.view import View - logger = logging.getLogger(__name__) class DataFrameAdapter(TabularAdapter): - """ Generic tabular adapter for data frames - """ + """Generic tabular adapter for data frames""" #: The text to use for a generic entry. text = Property() @@ -116,7 +114,7 @@ def _set_text(self, value): value, self.column, self.row, - exc_info=True + exc_info=True, ) def _get_index_text(self): @@ -130,15 +128,13 @@ def _set_index_text(self, value): index.values[self.row] = value except Exception: logger.debug( - "User entered invalid value %r for index", - value, - exc_info=True + "User entered invalid value %r for index", value, exc_info=True ) # ---- Adapter methods that are not sensitive to item type ---------------- def get_item(self, object, trait, row): - """ Override the base implementation to work with DataFrames + """Override the base implementation to work with DataFrames This returns a dataframe with one row, rather than a series, since using a dataframe preserves dtypes. @@ -147,7 +143,7 @@ def get_item(self, object, trait, row): return getattr(object, trait).iloc[row : row + 1] def delete(self, object, trait, row): - """ Override the base implementation to work with DataFrames + """Override the base implementation to work with DataFrames Unavoidably does a copy of the data, setting the trait with the new value. @@ -164,7 +160,7 @@ def delete(self, object, trait, row): setattr(object, trait, new_df) def insert(self, object, trait, row, value): - """ Override the base implementation to work with DataFrames + """Override the base implementation to work with DataFrames Unavoidably does a copy of the data, setting the trait with the new value. @@ -182,7 +178,7 @@ def insert(self, object, trait, row, value): class _DataFrameEditor(UIEditor): - """ TraitsUI-based editor implementation for data frames """ + """TraitsUI-based editor implementation for data frames""" #: Indicate that the editor is scrollable/resizable: scrollable = True @@ -202,8 +198,7 @@ def _target_name(self, name): return "" def _data_frame_view(self): - """ Return the view used by the editor. - """ + """Return the view used by the editor.""" return View( Item( @@ -255,8 +250,7 @@ def _data_frame_view(self): ) def init_ui(self, parent): - """ Creates the Traits UI for displaying the array. - """ + """Creates the Traits UI for displaying the array.""" factory = self.factory if factory.columns != []: columns = [] @@ -297,7 +291,7 @@ def init_ui(self, parent): class DataFrameEditor(BasicEditorFactory): - """ Editor factory for basic data frame editor """ + """Editor factory for basic data frame editor""" #: The editor implementation class. klass = Property() @@ -399,10 +393,9 @@ class DataFrameEditor(BasicEditorFactory): adapter = Instance(DataFrameAdapter) def _get_klass(self): - """ The class used to construct editor objects. - """ + """The class used to construct editor objects.""" return toolkit_object("data_frame_editor:_DataFrameEditor") - + def _get_scroll_to_row_hint(self): warnings.warn( "Use of scroll_to_row_hint trait is deprecated. " @@ -410,7 +403,7 @@ def _get_scroll_to_row_hint(self): DeprecationWarning, ) return self.scroll_to_position_hint - + def _set_scroll_to_row_hint(self, hint): warnings.warn( "Use of scroll_to_row_hint trait is deprecated. " diff --git a/traitsui/ui_info.py b/traitsui/ui_info.py index c38acce30..a639617f5 100644 --- a/traitsui/ui_info.py +++ b/traitsui/ui_info.py @@ -16,7 +16,7 @@ class UIInfo(HasPrivateTraits): - """ Represents the object and editor content of an active Traits-based + """Represents the object and editor content of an active Traits-based user interface """ @@ -31,15 +31,14 @@ class UIInfo(HasPrivateTraits): initialized = Bool(False) def bind_context(self): - """ Binds all of the associated context objects as traits of the - object. + """Binds all of the associated context objects as traits of the + object. """ for name, value in self.ui.context.items(): self.bind(name, value) def bind(self, name, value, id=None): - """ Binds a name to a value if it is not already bound. - """ + """Binds a name to a value if it is not already bound.""" if id is None: id = name diff --git a/traitsui/ui_traits.py b/traitsui/ui_traits.py index 5e9a55973..794267d7c 100644 --- a/traitsui/ui_traits.py +++ b/traitsui/ui_traits.py @@ -48,7 +48,8 @@ # Styles for user interface elements: EditorStyle = style_trait = PrefixList( - ("simple", "custom", "text", "readonly"), cols=4) + ("simple", "custom", "text", "readonly"), cols=4 +) # Group layout trait: Layout = PrefixList(("normal", "split", "tabbed", "flow", "fold")) @@ -114,8 +115,7 @@ class StatusItem(HasStrictTraits): width = Float(0.5) def __init__(self, value=None, **traits): - """ Initializes the item object. - """ + """Initializes the item object.""" super().__init__(**traits) if value is not None: @@ -128,8 +128,8 @@ def __init__(self, value=None, **traits): class ViewStatus(TraitType): - """ Defines a trait whose value must be a single StatusItem instance or a - list of StatusItem instances. + """Defines a trait whose value must be a single StatusItem instance or a + list of StatusItem instances. """ #: Define the default value for the trait: @@ -142,8 +142,7 @@ class ViewStatus(TraitType): ) def validate(self, object, name, value): - """ Validates that a specified value is valid for this trait. - """ + """Validates that a specified value is valid for this trait.""" if isinstance(value, str): return [StatusItem(name=value)] @@ -174,8 +173,7 @@ def validate(self, object, name, value): def convert_theme(value, level=3): - """ Converts a specified value to a Theme if possible. - """ + """Converts a specified value to a Theme if possible.""" if not isinstance(value, str): return value @@ -196,8 +194,8 @@ def convert_theme(value, level=3): class ATheme(TraitType): - """ Defines a trait whose value must be a traits UI Theme or a string that - can be converted to one. + """Defines a trait whose value must be a traits UI Theme or a string that + can be converted to one. """ #: Define the default value for the trait: @@ -207,7 +205,7 @@ class ATheme(TraitType): info_text = "a Theme or string that can be used to define one" def __init__(self, value=None, **metadata): - """ Creates an ATheme trait. + """Creates an ATheme trait. Parameters ---------- @@ -218,8 +216,7 @@ def __init__(self, value=None, **metadata): super().__init__(convert_theme(value), **metadata) def validate(self, object, name, value): - """ Validates that a specified value is valid for this trait. - """ + """Validates that a specified value is valid for this trait.""" from .theme import Theme if value is None: diff --git a/traitsui/undo.py b/traitsui/undo.py index 3d80a1a7c..3cb5e615a 100644 --- a/traitsui/undo.py +++ b/traitsui/undo.py @@ -30,8 +30,12 @@ observe, ) from pyface.undo.api import ( - AbstractCommand, CommandStack, ICommand, ICommandStack, IUndoManager, - UndoManager + AbstractCommand, + CommandStack, + ICommand, + ICommandStack, + IUndoManager, + UndoManager, ) @@ -40,7 +44,7 @@ class AbstractUndoItem(AbstractCommand): - """ Abstract base class for undo items. + """Abstract base class for undo items. This class is deprecated and will be removed in TraitsUI 8. Any custom subclasses of this class should either subclass from AbstractCommand, or @@ -51,27 +55,25 @@ class AbstractUndoItem(AbstractCommand): name = "Edit" def do(self): - """ Does nothing. - + """Does nothing. + All undo items log events after they have happened, so by default they do not do anything when added to the history. """ pass def undo(self): - """ Undoes the change. - """ + """Undoes the change.""" raise NotImplementedError def redo(self): - """ Re-does the change. - """ + """Re-does the change.""" raise NotImplementedError def merge(self, other): - """ Merges two undo items if possible. - """ + """Merges two undo items if possible.""" import warnings + warnings.warn( "'merge_undo' is deprecated and will be removed in TraitsUI 8, " "use 'merge' instead", @@ -80,7 +82,7 @@ def merge(self, other): return self.merge_undo(other) def merge_undo(self, undo_item): - """ Merges two undo items if possible. + """Merges two undo items if possible. This method is deprecated. """ @@ -88,8 +90,7 @@ def merge_undo(self, undo_item): class UndoItem(AbstractUndoItem): - """ A change to an object trait, which can be undone. - """ + """A change to an object trait, which can be undone.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -124,8 +125,7 @@ def _set_new_value(self, value): self._new_value = value def undo(self): - """ Undoes the change. - """ + """Undoes the change.""" try: setattr(self.object, self.name, self.old_value) except Exception: @@ -134,8 +134,7 @@ def undo(self): raise_to_debug() def redo(self): - """ Re-does the change. - """ + """Re-does the change.""" try: setattr(self.object, self.name, self.new_value) except Exception: @@ -144,8 +143,7 @@ def redo(self): raise_to_debug() def merge(self, undo_item): - """ Merges two undo items if possible. - """ + """Merges two undo items if possible.""" # Undo items are potentially mergeable only if they are of the same # class and refer to the same object trait, so check that first: if ( @@ -171,7 +169,7 @@ def merge(self, undo_item): i = 0 while (i < n) and (v1[i] == v2[i]): i += 1 - if v1[i + (n2 <= n1):] == v2[i + (n2 >= n1):]: + if v1[i + (n2 <= n1) :] == v2[i + (n2 >= n1) :]: self.new_value = v2 return True @@ -212,15 +210,14 @@ def merge(self, undo_item): return False def merge_undo(self, undo_item): - """ Merges two undo items if possible. + """Merges two undo items if possible. This is deprecated. """ return self.merge(undo_item) def __repr__(self): - """ Returns a "pretty print" form of the object. - """ + """Returns a "pretty print" form of the object.""" n = self.name cn = self.object.__class__.__name__ return "undo( %s.%s = %s )\nredo( %s.%s = %s )" % ( @@ -234,8 +231,7 @@ def __repr__(self): class ListUndoItem(AbstractUndoItem): - """ A change to a list, which can be undone. - """ + """A change to a list, which can be undone.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -257,8 +253,7 @@ class ListUndoItem(AbstractUndoItem): removed = List() def undo(self): - """ Undoes the change. - """ + """Undoes the change.""" try: list = getattr(self.object, self.name) list[self.index : (self.index + len(self.added))] = self.removed @@ -268,8 +263,7 @@ def undo(self): raise_to_debug() def redo(self): - """ Re-does the change. - """ + """Re-does the change.""" try: list = getattr(self.object, self.name) list[self.index : (self.index + len(self.removed))] = self.added @@ -279,8 +273,7 @@ def redo(self): raise_to_debug() def merge(self, undo_item): - """ Merges two undo items if possible. - """ + """Merges two undo items if possible.""" # Discard undo items that are identical to us. This is to eliminate # the same undo item being created by multiple listeners monitoring the # same list for changes: @@ -307,15 +300,14 @@ def merge(self, undo_item): return False def merge_undo(self, undo_item): - """ Merges two undo items if possible. + """Merges two undo items if possible. This is deprecated. """ return self.merge(undo_item) def __repr__(self): - """ Returns a 'pretty print' form of the object. - """ + """Returns a 'pretty print' form of the object.""" return "undo( %s.%s[%d:%d] = %s )" % ( self.object.__class__.__name__, self.name, @@ -326,7 +318,7 @@ def __repr__(self): class _MultiUndoItem(AbstractCommand): - """ The _MultiUndoItem class is an internal command that unifies commands. """ + """The _MultiUndoItem class is an internal command that unifies commands.""" name = "Edit" @@ -334,7 +326,7 @@ class _MultiUndoItem(AbstractCommand): commands = List(Instance(ICommand)) def push(self, command): - """ Append a command, merging if possible. """ + """Append a command, merging if possible.""" if len(self.commands) > 0: merged = self.commands[-1].merge(command) if merged: @@ -343,25 +335,24 @@ def push(self, command): self.commands.append(command) def merge(self, other): - """ Try and merge a command. """ + """Try and merge a command.""" return False def redo(self): - """ Redo the sub-commands. """ + """Redo the sub-commands.""" for cmd in self.commands: cmd.redo() def undo(self): - """ Undo the sub-commands. """ + """Undo the sub-commands.""" for cmd in self.commands: cmd.undo() class UndoHistory(HasStrictTraits): - """ Manages a list of undoable changes. - """ + """Manages a list of undoable changes.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -399,8 +390,7 @@ class UndoHistory(HasStrictTraits): _can_redo = Bool() def add(self, undo_item, extend=False): - """ Adds an UndoItem to the history. - """ + """Adds an UndoItem to the history.""" if extend: self.extend(undo_item) else: @@ -408,7 +398,7 @@ def add(self, undo_item, extend=False): self.stack.push(undo_item) def extend(self, undo_item): - """ Extends the undo history. + """Extends the undo history. If possible the method merges the new UndoItem with the last item in the history; otherwise, it appends the new item. @@ -429,36 +419,32 @@ def extend(self, undo_item): command.push(undo_item) def undo(self): - """ Undoes an operation. - """ + """Undoes an operation.""" if self.can_undo: self.manager.undo() def redo(self): - """ Redoes an operation. - """ + """Redoes an operation.""" if self.can_redo: self.manager.redo() def revert(self): - """ Reverts all changes made so far and clears the history. - """ + """Reverts all changes made so far and clears the history.""" # undo everything self.manager.active_stack = self.stack self.stack.undo(sequence_nr=-1) self.clear() def clear(self): - """ Clears the undo history. - """ + """Clears the undo history.""" self.manager.active_stack = self.stack self.stack.clear() @observe('manager.stack_updated') def _observe_stack_updated(self, event): - """ Update undo/redo state. """ - self._can_undo = (self.manager and self.manager.undo_name != "") - self._can_redo = (self.manager and self.manager.redo_name != "") + """Update undo/redo state.""" + self._can_undo = self.manager and self.manager.undo_name != "" + self._can_redo = self.manager and self.manager.redo_name != "" @observe('_can_undo') def _observe_can_undo(self, event): @@ -474,7 +460,7 @@ def _get_now(self): def _get_can_undo(self): return self._can_undo - + def _get_can_redo(self): return self._can_redo @@ -488,8 +474,7 @@ def _stack_default(self): class UndoHistoryUndoItem(AbstractUndoItem): - """ An undo item for the undo history. - """ + """An undo item for the undo history.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -499,8 +484,7 @@ class UndoHistoryUndoItem(AbstractUndoItem): history = Instance(UndoHistory) def undo(self): - """ Undoes the change. - """ + """Undoes the change.""" history = self.history for i in range(history.now - 1, -1, -1): items = history.history[i] @@ -508,8 +492,7 @@ def undo(self): items[j].undo() def redo(self): - """ Re-does the change. - """ + """Re-does the change.""" history = self.history for i in range(0, history.now): for item in history.history[i]: diff --git a/traitsui/value_tree.py b/traitsui/value_tree.py index 06eba2c5a..9b6c04d49 100644 --- a/traitsui/value_tree.py +++ b/traitsui/value_tree.py @@ -32,8 +32,7 @@ class SingleValueTreeNodeObject(TreeNodeObject): - """ A tree node for objects of types that have a single value. - """ + """A tree node for objects of types that have a single value.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -55,55 +54,51 @@ class SingleValueTreeNodeObject(TreeNodeObject): readonly = Bool(False) def tno_allows_children(self, node): - """ Returns whether this object can have children (False for this + """Returns whether this object can have children (False for this class). """ return False def tno_has_children(self, node): - """ Returns whether the object has children (False for this class). - """ + """Returns whether the object has children (False for this class).""" return False def tno_can_rename(self, node): - """ Returns whether the object's children can be renamed (False for + """Returns whether the object's children can be renamed (False for this class). """ return False def tno_can_copy(self, node): - """ Returns whether the object's children can be copied (True for this + """Returns whether the object's children can be copied (True for this class). """ return True def tno_can_delete(self, node): - """ Returns whether the object's children can be deleted (False for + """Returns whether the object's children can be deleted (False for this class). """ return False def tno_can_insert(self, node): - """ Returns whether the object's children can be inserted (False, + """Returns whether the object's children can be inserted (False, meaning children are appended, for this class). """ return False def tno_get_icon(self, node, is_expanded): - """ Returns the icon for a specified object. - """ + """Returns the icon for a specified object.""" return "@icons:%s_node" % self.__class__.__name__[:-4].lower() def tno_set_label(self, node, label): - """ Sets the label for a specified object. - """ + """Sets the label for a specified object.""" if label == "?": label = "" self.label = label def tno_get_label(self, node): - """ Gets the label to display for a specified object. - """ + """Gets the label to display for a specified object.""" if self.label != "": return self.label @@ -113,13 +108,11 @@ def tno_get_label(self, node): return "%s: %s" % (self.name, self.format_value(self.value)) def format_value(self, value): - """ Returns the formatted version of the value. - """ + """Returns the formatted version of the value.""" return repr(value) def node_for(self, name, value): - """ Returns the correct node type for a specified value. - """ + """Returns the correct node type for a specified value.""" for type, node in basic_types(): if isinstance(value, type): break @@ -137,27 +130,22 @@ def node_for(self, name, value): class MultiValueTreeNodeObject(SingleValueTreeNodeObject): - """ A tree node for objects of types that have multiple values. - """ + """A tree node for objects of types that have multiple values.""" def tno_allows_children(self, node): - """ Returns whether this object can have children (True for this class). - """ + """Returns whether this object can have children (True for this class).""" return True def tno_has_children(self, node): - """ Returns whether the object has children (True for this class). - """ + """Returns whether the object has children (True for this class).""" return True class StringNode(SingleValueTreeNodeObject): - """ A tree node for strings. - """ + """A tree node for strings.""" def format_value(self, value): - """ Returns the formatted version of the value. - """ + """Returns the formatted version of the value.""" n = len(value) if len(value) > 80: value = "%s...%s" % (value[:42], value[-35:]) @@ -166,42 +154,37 @@ def format_value(self, value): class NoneNode(SingleValueTreeNodeObject): - """ A tree node for None values. - """ + """A tree node for None values.""" pass class BoolNode(SingleValueTreeNodeObject): - """ A tree node for Boolean values. - """ + """A tree node for Boolean values.""" pass class IntNode(SingleValueTreeNodeObject): - """ A tree node for integer values. - """ + """A tree node for integer values.""" pass class FloatNode(SingleValueTreeNodeObject): - """ A tree node for floating point values. - """ + """A tree node for floating point values.""" pass class ComplexNode(SingleValueTreeNodeObject): - """ A tree node for complex number values. - """ + """A tree node for complex number values.""" pass class OtherNode(SingleValueTreeNodeObject): - """ A tree node for single-value types for which there is not another + """A tree node for single-value types for which there is not another node type. """ @@ -209,23 +192,20 @@ class OtherNode(SingleValueTreeNodeObject): class TupleNode(MultiValueTreeNodeObject): - """ A tree node for tuples. - """ + """A tree node for tuples.""" def format_value(self, value): - """ Returns the formatted version of the value. - """ + """Returns the formatted version of the value.""" return "Tuple(%d)" % len(value) def tno_has_children(self, node): - """ Returns whether the object has children, based on the length of - the tuple. + """Returns whether the object has children, based on the length of + the tuple. """ return len(self.value) > 0 def tno_get_children(self, node): - """ Gets the object's children. - """ + """Gets the object's children.""" node_for = self.node_for value = self.value if len(value) > 500: @@ -239,58 +219,48 @@ def tno_get_children(self, node): class ListNode(TupleNode): - """ A tree node for lists. - """ + """A tree node for lists.""" def format_value(self, value): - """ Returns the formatted version of the value. - """ + """Returns the formatted version of the value.""" return "List(%d)" % len(value) def tno_can_delete(self, node): - """ Returns whether the object's children can be deleted. - """ + """Returns whether the object's children can be deleted.""" return not self.readonly def tno_can_insert(self, node): - """ Returns whether the object's children can be inserted (vs. + """Returns whether the object's children can be inserted (vs. appended). """ return not self.readonly class SetNode(ListNode): - """ A tree node for sets. - """ + """A tree node for sets.""" def format_value(self, value): - """ Returns the formatted version of the value. - """ + """Returns the formatted version of the value.""" return "Set(%d)" % len(value) class ArrayNode(TupleNode): - """ A tree node for arrays. - """ + """A tree node for arrays.""" def format_value(self, value): - """ Returns the formatted version of the value. - """ + """Returns the formatted version of the value.""" return "Array(%s)" % ",".join([str(n) for n in value.shape]) class DictNode(TupleNode): - """ A tree node for dictionaries. - """ + """A tree node for dictionaries.""" def format_value(self, value): - """ Returns the formatted version of the value. - """ + """Returns the formatted version of the value.""" return "Dict(%d)" % len(value) def tno_get_children(self, node): - """ Gets the object's children. - """ + """Gets the object's children.""" node_for = self.node_for items = [(repr(k), v) for k, v in self.value.items()] items.sort(key=itemgetter(0)) @@ -304,18 +274,15 @@ def tno_get_children(self, node): return [node_for("[%s]" % k, v) for k, v in items] def tno_can_delete(self, node): - """ Returns whether the object's children can be deleted. - """ + """Returns whether the object's children can be deleted.""" return not self.readonly class FunctionNode(SingleValueTreeNodeObject): - """ A tree node for functions - """ + """A tree node for functions""" def format_value(self, value): - """ Returns the formatted version of the value. - """ + """Returns the formatted version of the value.""" return "Function %s()" % (value.__name__) @@ -326,8 +293,7 @@ def format_value(self, value): class MethodNode(MultiValueTreeNodeObject): def format_value(self, value): - """ Returns the formatted version of the value. - """ + """Returns the formatted version of the value.""" type = "B" if value.__self__ is None: type = "Unb" @@ -339,23 +305,19 @@ def format_value(self, value): ) def tno_has_children(self, node): - """ Returns whether the object has children. - """ + """Returns whether the object has children.""" return self.value.__func__ is not None def tno_get_children(self, node): - """ Gets the object's children. - """ + """Gets the object's children.""" return [self.node_for("Object", self.value.__self__)] class ObjectNode(MultiValueTreeNodeObject): - """ A tree node for objects. - """ + """A tree node for objects.""" def format_value(self, value): - """ Returns the formatted version of the value. - """ + """Returns the formatted version of the value.""" try: klass = value.__class__.__name__ except: @@ -363,43 +325,36 @@ def format_value(self, value): return "%s(0x%08X)" % (klass, id(value)) def tno_has_children(self, node): - """ Returns whether the object has children. - """ + """Returns whether the object has children.""" try: return len(self.value.__dict__) > 0 except: return False def tno_get_children(self, node): - """ Gets the object's children. - """ + """Gets the object's children.""" items = [(k, v) for k, v in self.value.__dict__.items()] items.sort(key=itemgetter(0)) return [self.node_for("." + k, v) for k, v in items] class ClassNode(ObjectNode): - """ A tree node for classes. - """ + """A tree node for classes.""" def format_value(self, value): - """ Returns the formatted version of the value. - """ + """Returns the formatted version of the value.""" return value.__name__ class TraitsNode(ObjectNode): - """ A tree node for traits. - """ + """A tree node for traits.""" def tno_has_children(self, node): - """ Returns whether the object has children. - """ + """Returns whether the object has children.""" return len(self._get_names()) > 0 def tno_get_children(self, node): - """ Gets the object's children. - """ + """Gets the object's children.""" names = sorted(self._get_names()) value = self.value node_for = self.node_for @@ -414,8 +369,7 @@ def tno_get_children(self, node): return nodes def _get_names(self): - """ Gets the names of all defined traits or attributes. - """ + """Gets the names of all defined traits or attributes.""" value = self.value names = {} for name in value.trait_names(type=lambda x: x != "event"): @@ -425,7 +379,7 @@ def _get_names(self): return list(names.keys()) def tno_when_children_replaced(self, node, listener, remove): - """ Sets up or removes a listener for children being replaced on a + """Sets up or removes a listener for children being replaced on a specified object. """ self._listener = listener @@ -437,24 +391,21 @@ def _children_replaced(self): self._listener(self) def tno_when_children_changed(self, node, listener, remove): - """ Sets up or removes a listener for children being changed on a + """Sets up or removes a listener for children being changed on a specified object. """ pass class RootNode(MultiValueTreeNodeObject): - """ A root node. - """ + """A root node.""" def format_value(self, value): - """ Returns the formatted version of the value. - """ + """Returns the formatted version of the value.""" return "" def tno_get_children(self, node): - """ Gets the object's children. - """ + """Gets the object's children.""" return [self.node_for("", self.value)] diff --git a/traitsui/view.py b/traitsui/view.py index 38e4470d0..36927c3a1 100644 --- a/traitsui/view.py +++ b/traitsui/view.py @@ -13,7 +13,6 @@ """ - from pyface.ui_traits import Image from traits.api import ( Any, @@ -155,12 +154,12 @@ class View(ViewElement): - """ A Traits-based user interface for one or more objects. + """A Traits-based user interface for one or more objects. - The attributes of the View object determine the contents and layout of - an attribute-editing window. A View object contains a set of Group, - Item, and Include objects. A View object can be an attribute of an - object derived from HasTraits, or it can be a standalone object. + The attributes of the View object determine the contents and layout of + an attribute-editing window. A View object contains a set of Group, + Item, and Include objects. A View object can be an attribute of an + object derived from HasTraits, or it can be a standalone object. """ # ------------------------------------------------------------------------- @@ -334,14 +333,12 @@ class View(ViewElement): help = Bool(False) def __init__(self, *values, **traits): - """ Initializes the object. - """ + """Initializes the object.""" ViewElement.__init__(self, **traits) self.set_content(*values) def set_content(self, *values): - """ Sets the content of a view. - """ + """Sets the content of a view.""" content = [] accum = [] for value in values: @@ -380,7 +377,7 @@ def ui( scrollable=None, args=None, ): - """ Creates a **UI** object, which generates the actual GUI window or + """Creates a **UI** object, which generates the actual GUI window or panel from a set of view elements. Parameters @@ -455,16 +452,15 @@ def ui( return ui def replace_include(self, view_elements): - """ Replaces any items that have an ID with an Include object with - the same ID, and puts the object with the ID into the specified - ViewElements object. + """Replaces any items that have an ID with an Include object with + the same ID, and puts the object with the ID into the specified + ViewElements object. """ if self.content is not None: self.content.replace_include(view_elements) def __repr__(self): - """ Returns a "pretty print" version of the View. - """ + """Returns a "pretty print" version of the View.""" if self.content is None: return "()" return "( %s )" % ", ".join( diff --git a/traitsui/view_element.py b/traitsui/view_element.py index a0121e447..c1d760700 100644 --- a/traitsui/view_element.py +++ b/traitsui/view_element.py @@ -35,11 +35,10 @@ class ViewElement(HasPrivateTraits): - """ An element of a view. - """ + """An element of a view.""" def replace_include(self, view_elements): - """ Searches the current object's **content** attribute for objects that + """Searches the current object's **content** attribute for objects that have an **id** attribute, and replaces each one with an Include object with the same **id** value, and puts the replaced object into the specified ViewElements object. @@ -52,14 +51,13 @@ def replace_include(self, view_elements): pass # Normally overridden in a subclass def is_includable(self): - """ Returns whether the object is replacable by an Include object. - """ + """Returns whether the object is replacable by an Include object.""" return False # Normally overridden in a subclass class DefaultViewElement(ViewElement): - """ A view element that can be used as a default value for traits whose - value is a view element. + """A view element that can be used as a default value for traits whose + value is a view element. """ # ------------------------------------------------------------------------- @@ -98,8 +96,7 @@ class DefaultViewElement(ViewElement): class ViewSubElement(ViewElement): - """ Abstract class representing elements that can be contained in a view. - """ + """Abstract class representing elements that can be contained in a view.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -112,31 +109,28 @@ class ViewSubElement(ViewElement): help_id = HelpId def _split(self, name, value, char, finder, assign, result): - """ Splits a string at a specified character. - """ + """Splits a string at a specified character.""" col = finder(value, char) if col < 0: return value - items = (value[:col].strip(), value[col + 1:].strip()) + items = (value[:col].strip(), value[col + 1 :].strip()) if items[assign] != "": setattr(self, name, items[assign]) return items[result] def _option(self, string, option, name, value): - """ Sets a object trait if a specified option string is found. - """ + """Sets a object trait if a specified option string is found.""" col = string.find(option) if col >= 0: - string = string[:col] + string[col + len(option):] + string = string[:col] + string[col + len(option) :] setattr(self, name, value) return string def _parse_style(self, value): - """ Parses any of the one-character forms of the **style** trait. - """ + """Parses any of the one-character forms of the **style** trait.""" value = self._option(value, "$", "style", "simple") value = self._option(value, "@", "style", "custom") value = self._option(value, "*", "style", "text") @@ -146,8 +140,7 @@ def _parse_style(self, value): return value def _parse_label(self, value): - """ Parses a '[label]' value from the string definition. - """ + """Parses a '[label]' value from the string definition.""" match = label_pat.match(value) if match is not None: self._parsed_label() @@ -163,21 +156,18 @@ def _parse_label(self, value): return (value, empty) def _parsed_label(self): - """ Handles a label being found in the string definition. - """ + """Handles a label being found in the string definition.""" pass def _repr_value(self, value, prefix="", suffix="", ignore=""): - """ Returns a "pretty print" version of a specified Item trait value. - """ + """Returns a "pretty print" version of a specified Item trait value.""" if value == ignore: return "" return "%s%s%s" % (prefix, value, suffix) def _repr_options(self, *names): - """ Returns a 'pretty print' version of a list of traits. - """ + """Returns a 'pretty print' version of a list of traits.""" result = [] for name in names: value = getattr(self, name) @@ -193,8 +183,7 @@ def _repr_options(self, *names): return None def _indent(self, string, indent=" "): - """ Indents each line in a specified string by 4 spaces. - """ + """Indents each line in a specified string by 4 spaces.""" return "\n".join([indent + s for s in string.split("\n")]) diff --git a/traitsui/view_elements.py b/traitsui/view_elements.py index 9b33fa59e..f7142a9cf 100644 --- a/traitsui/view_elements.py +++ b/traitsui/view_elements.py @@ -30,8 +30,7 @@ class ViewElements(HasStrictTraits): - """ Defines a hierarchical name space of related ViewElement objects. - """ + """Defines a hierarchical name space of related ViewElement objects.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -41,8 +40,8 @@ class ViewElements(HasStrictTraits): content = content_trait def find(self, name, stack=None): - """ Finds a specified ViewElement within the specified (optional) search - context. + """Finds a specified ViewElement within the specified (optional) search + context. """ # Assume search starts from the beginning the of the search order: i = 0 @@ -74,8 +73,8 @@ def find(self, name, stack=None): return None def filter_by(self, klass=None): - """ Returns a sorted list of all names accessible from the ViewElements - object that are of a specified (ViewElement) type. + """Returns a sorted list of all names accessible from the ViewElements + object that are of a specified (ViewElement) type. """ if klass is None: from . import view @@ -145,8 +144,7 @@ def _merge(self, seqs): del seq[0] def __repr__(self): - """ Returns a "pretty print" version of the ViewElements object. - """ + """Returns a "pretty print" version of the ViewElements object.""" return self.content.__repr__() diff --git a/traitsui/wx/animated_gif_editor.py b/traitsui/wx/animated_gif_editor.py index 69af88ba4..96165b765 100644 --- a/traitsui/wx/animated_gif_editor.py +++ b/traitsui/wx/animated_gif_editor.py @@ -22,8 +22,7 @@ class _AnimatedGIFEditor(Editor): - """ Editor that displays an animated GIF file. - """ + """Editor that displays an animated GIF file.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -33,8 +32,8 @@ class _AnimatedGIFEditor(Editor): playing = Bool(True) def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self._animate = Animation(self.value) self.control = GenericAnimationCtrl(parent, -1, self._animate) @@ -43,8 +42,8 @@ def init(self, parent): self.set_tooltip() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ if not self.playing: self.control.Stop() diff --git a/traitsui/wx/array_editor.py b/traitsui/wx/array_editor.py index c16e23efa..d5f026b3a 100644 --- a/traitsui/wx/array_editor.py +++ b/traitsui/wx/array_editor.py @@ -22,8 +22,7 @@ class SimpleEditor(BaseSimpleEditor, Editor): - """ Simple style of editor for arrays. - """ + """Simple style of editor for arrays.""" # FIXME: This class has been re-defined here simply so it inherits from the # wx Editor class. diff --git a/traitsui/wx/boolean_editor.py b/traitsui/wx/boolean_editor.py index c9364f409..de8f31c6d 100644 --- a/traitsui/wx/boolean_editor.py +++ b/traitsui/wx/boolean_editor.py @@ -25,12 +25,11 @@ class SimpleEditor(Editor): - """ Simple style of editor for Boolean values, which displays a check box. - """ + """Simple style of editor for Boolean values, which displays a check box.""" def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = wx.CheckBox(parent, -1, "") self.control.Bind(wx.EVT_CHECKBOX, self.update_object) @@ -40,25 +39,24 @@ def dispose(self): self.control.Unbind(wx.EVT_CHECKBOX) def update_object(self, event): - """ Handles the user clicking the checkbox. - """ + """Handles the user clicking the checkbox.""" self.value = self.control.GetValue() != 0 def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ self.control.SetValue(self.value) class ReadonlyEditor(Editor): - """ Read-only style of editor for Boolean values, which displays static text + """Read-only style of editor for Boolean values, which displays static text of either "True" or "False". """ def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = wx.TextCtrl(parent, -1, "", style=wx.TE_READONLY) self.control.SetBackgroundColour(ReadonlyColor) @@ -70,8 +68,8 @@ def init(self, parent): # ------------------------------------------------------------------------- def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ if self.value: self.control.SetValue("True") diff --git a/traitsui/wx/button_editor.py b/traitsui/wx/button_editor.py index 37e36d401..03fa3d806 100644 --- a/traitsui/wx/button_editor.py +++ b/traitsui/wx/button_editor.py @@ -25,8 +25,7 @@ class SimpleEditor(Editor): - """ Simple style editor for a button. - """ + """Simple style editor for a button.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -36,8 +35,8 @@ class SimpleEditor(Editor): label = Str() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ label = self.factory.label or self.item.get_label(self.ui) self.control = wx.Button(parent, -1, self.string_value(label)) @@ -49,8 +48,8 @@ def _label_changed(self, label): self.control.SetLabel(self.string_value(label)) def update_object(self, event): - """ Handles the user clicking the button by setting the factory value - on the object. + """Handles the user clicking the button by setting the factory value + on the object. """ factory = self.factory self.value = factory.value @@ -60,27 +59,26 @@ def update_object(self, event): self.object.edit_traits(view=factory.view, parent=self.control) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ pass def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" self.control.Unbind(wx.EVT_BUTTON) super().dispose() class CustomEditor(SimpleEditor): - """ Custom style editor for a button, which can contain an image. - """ + """Custom style editor for a button, which can contain an image.""" + #: The button image image = Image() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ from pyface.ui.wx.image_button import ImageButton @@ -116,8 +114,7 @@ def _image_updated(self, event): self._control.image = image def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" self._control.on_trait_change( self.update_object, "clicked", remove=True ) diff --git a/traitsui/wx/check_list_editor.py b/traitsui/wx/check_list_editor.py index a683286e5..9ff9a563d 100644 --- a/traitsui/wx/check_list_editor.py +++ b/traitsui/wx/check_list_editor.py @@ -35,8 +35,7 @@ class SimpleEditor(EditorWithList): - """ Simple style of editor for checklists, which displays a combo box. - """ + """Simple style of editor for checklists, which displays a combo box.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -49,8 +48,8 @@ class SimpleEditor(EditorWithList): values = List() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.create_control(parent) super().init(parent) @@ -61,16 +60,14 @@ def dispose(self): super().dispose() def create_control(self, parent): - """ Creates the initial editor control. - """ + """Creates the initial editor control.""" self.control = wx.Choice( parent, -1, wx.Point(0, 0), wx.Size(100, 20), [] ) self.control.Bind(wx.EVT_CHOICE, self.update_object) def list_updated(self, values): - """ Handles updates to the list of legal checklist values. - """ + """Handles updates to the list of legal checklist values.""" sv = self.string_value if (len(values) > 0) and isinstance(values[0], str): values = [(x, sv(x, str.capitalize)) for x in values] @@ -100,8 +97,7 @@ def list_updated(self, values): self.rebuild_editor() def rebuild_editor(self): - """ Rebuilds the editor after its definition is modified. - """ + """Rebuilds the editor after its definition is modified.""" control = self.control control.Clear() for name in self.names: @@ -110,8 +106,7 @@ def rebuild_editor(self): self.update_editor() def update_object(self, event): - """ Handles the user selecting a new value from the combo box. - """ + """Handles the user selecting a new value from the combo box.""" value = self.values[self.names.index(event.GetString())] if not isinstance(self.value, str): value = [value] @@ -119,8 +114,8 @@ def update_object(self, event): self.value = value def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ try: self.control.SetSelection( @@ -136,19 +131,17 @@ def update_editor(self): class CustomEditor(SimpleEditor): - """ Custom style of editor for checklists, which displays a set of check - boxes. + """Custom style of editor for checklists, which displays a set of check + boxes. """ def create_control(self, parent): - """ Creates the initial editor control. - """ + """Creates the initial editor control.""" # Create a panel to hold all of the check boxes self.control = panel = TraitsUIPanel(parent, -1) def rebuild_editor(self): - """ Rebuilds the editor after its definition is modified. - """ + """Rebuilds the editor after its definition is modified.""" panel = self.control panel.SetSizer(None) panel.DestroyChildren() @@ -190,7 +183,9 @@ def rebuild_editor(self): control = wx.CheckBox(panel, -1, label) control.value = value = values[index] control.SetValue(value in cur_value) - panel.Bind(wx.EVT_CHECKBOX, self.update_object, id=control.GetId()) + panel.Bind( + wx.EVT_CHECKBOX, self.update_object, id=control.GetId() + ) index += incr[j] n -= 1 else: @@ -217,8 +212,7 @@ def rebuild_editor(self): panel.Refresh() def update_object(self, event): - """ Handles the user clicking one of the custom check boxes. - """ + """Handles the user clicking one of the custom check boxes.""" control = event.GetEventObject() cur_value = parse_value(self.value) if control.GetValue(): @@ -230,8 +224,8 @@ def update_object(self, event): self.value = cur_value def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ new_values = parse_value(self.value) for control in self.control.GetChildren(): @@ -240,12 +234,10 @@ def update_editor(self): class TextEditor(BaseTextEditor): - """ Text style of editor for checklists, which displays a text field. - """ + """Text style of editor for checklists, which displays a text field.""" def update_object(self, event): - """ Handles the user changing the contents of the edit control. - """ + """Handles the user changing the contents of the edit control.""" try: value = self.control.GetValue() value = eval(value) @@ -263,8 +255,7 @@ def update_object(self, event): def parse_value(value): - """ Parses a value into a list. - """ + """Parses a value into a list.""" if value is None: return [] diff --git a/traitsui/wx/code_editor.py b/traitsui/wx/code_editor.py index 335d16312..11f576400 100644 --- a/traitsui/wx/code_editor.py +++ b/traitsui/wx/code_editor.py @@ -46,8 +46,7 @@ class SourceEditor(Editor): - """ Editor for source code, which displays a Pyface PythonEditor. - """ + """Editor for source code, which displays a Pyface PythonEditor.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -90,8 +89,8 @@ class SourceEditor(Editor): squiggle_color = Str() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory self._editor = editor = PythonEditor( @@ -195,14 +194,12 @@ def init(self, parent): self.set_tooltip() def wx_update_object(self, event): - """ Handles the user entering input data in the edit control. - """ + """Handles the user entering input data in the edit control.""" self.update_object() event.Skip() def update_object(self): - """ Handles the user entering input data in the edit control. - """ + """Handles the user entering input data in the edit control.""" if not self._locked: try: value = self.control.GetText() @@ -215,8 +212,8 @@ def update_object(self): pass def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ self._locked = True new_value = self.value @@ -242,8 +239,7 @@ def _calltip_clicked(self, event): self.calltip_clicked = True def _mark_lines_changed(self): - """ Handles the set of marked lines being changed. - """ + """Handles the set of marked lines being changed.""" lines = self.mark_lines control = self.control lc = control.GetLineCount() @@ -259,8 +255,7 @@ def _mark_lines_items_changed(self): self._mark_lines_changed() def _selected_line_changed(self): - """ Handles a change in which line is currently selected. - """ + """Handles a change in which line is currently selected.""" line = self.selected_line control = self.control line = max(1, min(control.GetLineCount(), line)) - 1 @@ -283,8 +278,7 @@ def _column_changed(self, column): control.GotoPos(control.PositionFromLine(line) + column - 1) def _position_changed(self, event): - """ Handles the cursor position being changed. - """ + """Handles the cursor position being changed.""" control = self.control pos = control.GetCurrentPos() line = control.LineFromPosition(pos) @@ -295,8 +289,7 @@ def _position_changed(self, event): self.selected_text = control.GetSelectedText() def key_pressed(self, event): - """ Handles a key being pressed within the editor. - """ + """Handles a key being pressed within the editor.""" self.factory.key_bindings.do( event.event, self.ui.handler, self.ui.info ) @@ -314,16 +307,15 @@ def _squiggle_color_changed(self): @observe("dim_lines, squiggle_lines") def _style_document(self, event=None): - """ Force the STC to fire a STC_STYLENEEDED event for the entire - document. + """Force the STC to fire a STC_STYLENEEDED event for the entire + document. """ self.control.ClearDocumentStyle() self.control.Colourise(0, -1) self.control.Refresh() def _style_needed(self, event): - """ Handles an STC request for styling for some area. - """ + """Handles an STC request for styling for some area.""" position = self.control.GetEndStyled() start_line = self.control.LineFromPosition(position) end = event.GetPosition() @@ -364,14 +356,12 @@ def _style_needed(self, event): self.control.SetStyling(style_length, stc.STC_STYLE_DEFAULT) def error(self, excp): - """ Handles an error that occurs while setting the object's trait value. - """ + """Handles an error that occurs while setting the object's trait value.""" self.control.SetBackgroundColour(ErrorColor) self.control.Refresh() def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" if self.control is not None: if self.factory.auto_set: self._editor.on_trait_change( @@ -397,8 +387,8 @@ def dispose(self): # -- UI preference save/restore interface --------------------------------- def restore_prefs(self, prefs): - """ Restores any saved user preference information associated with the - editor. + """Restores any saved user preference information associated with the + editor. """ if self.factory.key_bindings is not None: key_bindings = prefs.get("key_bindings") @@ -406,8 +396,7 @@ def restore_prefs(self, prefs): self.factory.key_bindings.merge(key_bindings) def save_prefs(self): - """ Returns any user preference information associated with the editor. - """ + """Returns any user preference information associated with the editor.""" return {"key_bindings": self.factory.key_bindings} diff --git a/traitsui/wx/color_editor.py b/traitsui/wx/color_editor.py index 8d12edf1e..9533f6f8e 100644 --- a/traitsui/wx/color_editor.py +++ b/traitsui/wx/color_editor.py @@ -12,7 +12,6 @@ """ - import sys import wx @@ -40,12 +39,10 @@ class ToolkitEditorFactory(BaseToolkitEditorFactory): - """ Wx editor factory for color editors. - """ + """Wx editor factory for color editors.""" def to_wx_color(self, editor, color=None): - """ Gets the wxPython color equivalent of the object trait. - """ + """Gets the wxPython color equivalent of the object trait.""" if color is None: if self.mapped: color = getattr(editor.object, editor.name + "_") @@ -57,13 +54,11 @@ def to_wx_color(self, editor, color=None): return color def from_wx_color(self, color): - """ Gets the application equivalent of a wxPython value. - """ + """Gets the application equivalent of a wxPython value.""" return color.Red(), color.Green(), color.Blue() def str_color(self, color): - """ Returns the text representation of a specified color value. - """ + """Returns the text representation of a specified color value.""" if isinstance(color, ColorTypes): alpha = color.Alpha() if alpha == 255: @@ -89,7 +84,6 @@ def str_color(self, color): class ColorComboBox(wx.adv.OwnerDrawnComboBox): - def OnDrawItem(self, dc, rect, item, flags): r = wx.Rect(rect.x, rect.y, rect.width, rect.height) @@ -125,7 +119,7 @@ def OnDrawItem(self, dc, rect, item, flags): class SimpleColorEditor(BaseSimpleEditor): - """ Simple style of color editor, which displays a text field whose + """Simple style of color editor, which displays a text field whose background color is the color value. Selecting the text field displays a dialog box for selecting a new color value. """ @@ -137,8 +131,7 @@ class SimpleColorEditor(BaseSimpleEditor): choices = List() def _choices_default(self): - """ by default, uses the W3C 16 color names. - """ + """by default, uses the W3C 16 color names.""" return [ "aqua", "black", @@ -184,8 +177,8 @@ def dispose(self): super().dispose() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ current_color = self.factory.to_wx_color(self) self.control.SetValue(self.string_value(current_color)) @@ -215,8 +208,7 @@ def color_selected(self, event): return def string_value(self, color): - """ Returns the text representation of a specified color value. - """ + """Returns the text representation of a specified color value.""" color_name = w3c_color_database.FindName(color) if color_name != "": return color_name @@ -230,7 +222,7 @@ def string_value(self, color): class CustomColorEditor(BaseSimpleEditor): - """ Simple style of color editor, which displays a text field whose + """Simple style of color editor, which displays a text field whose background color is the color value. Selecting the text field displays a dialog box for selecting a new color value. """ @@ -247,11 +239,15 @@ def init(self, parent): parent, -1, self.str_value, style=wx.TE_PROCESS_ENTER ) text_control.Bind(wx.EVT_KILL_FOCUS, self.update_object) - parent.Bind(wx.EVT_TEXT_ENTER, self.update_object, id=text_control.GetId()) + parent.Bind( + wx.EVT_TEXT_ENTER, self.update_object, id=text_control.GetId() + ) # 'button_control' shows the 'Edit' button. button_control = wx.Button(parent, label="Edit", style=wx.BU_EXACTFIT) - button_control.Bind(wx.EVT_BUTTON, self.open_color_dialog, id=button_control.GetId()) + button_control.Bind( + wx.EVT_BUTTON, self.open_color_dialog, id=button_control.GetId() + ) sizer.Add(text_control, wx.ALIGN_LEFT) sizer.AddSpacer(8) @@ -266,8 +262,7 @@ def init(self, parent): return def update_object(self, event): - """ Handles the user changing the contents of the edit control. - """ + """Handles the user changing the contents of the edit control.""" if not isinstance(event, wx._core.CommandEvent): event.Skip() return @@ -288,14 +283,13 @@ def set_color(self): self._text_control.SetValue(self.string_value(color)) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ self.set_color() def open_color_dialog(self, event): - """ Opens the color dialog and sets the value upon return - """ + """Opens the color dialog and sets the value upon return""" color_data = wx.ColourData() color_data.SetColour(self.value) @@ -321,8 +315,7 @@ def color_selected(self, event): return def string_value(self, color): - """ Returns the text representation of a specified color value. - """ + """Returns the text representation of a specified color value.""" color_name = w3c_color_database.FindName(color) if color_name != "": return color_name @@ -336,27 +329,26 @@ def string_value(self, color): class ReadonlyColorEditor(BaseReadonlyEditor): - """ Read-only style of color editor, which displays a read-only text field + """Read-only style of color editor, which displays a read-only text field whose background color is the color value. """ def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = wx.TextCtrl(parent, style=wx.TE_READONLY) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ # super().update_editor() self.control.SetValue(self.string_value(self.value)) set_color(self) def string_value(self, color): - """ Returns the text representation of a specified color value. - """ + """Returns the text representation of a specified color value.""" color_name = w3c_color_database.FindName(color) if color_name != "": return color_name @@ -370,20 +362,19 @@ def string_value(self, color): class TextColorEditor(BaseTextEditor): - """ Text style of color editor, which displays a text field + """Text style of color editor, which displays a text field whose background color is the color value. """ def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ self.control.SetValue(self.string_value(self.value)) set_color(self) def update_object(self, event): - """ Handles the user changing the contents of the edit control. - """ + """Handles the user changing the contents of the edit control.""" if not isinstance(event, wx._core.CommandEvent): return try: @@ -393,8 +384,7 @@ def update_object(self, event): pass def string_value(self, color): - """ Returns the text representation of a specified color value. - """ + """Returns the text representation of a specified color value.""" color_name = w3c_color_database.FindName(color) if color_name != "": return color_name @@ -408,8 +398,7 @@ def string_value(self, color): def set_color(editor): - """ Sets the color of the specified color control. - """ + """Sets the color of the specified color control.""" color = editor.factory.to_wx_color(editor) editor.control.SetBackgroundColour(color) diff --git a/traitsui/wx/color_trait.py b/traitsui/wx/color_trait.py index ef7e849dd..274d817c8 100644 --- a/traitsui/wx/color_trait.py +++ b/traitsui/wx/color_trait.py @@ -31,14 +31,14 @@ class ColourPtr(object): class W3CColourDatabase(object): - """ Proxy for the ColourDatabase which allows for finding W3C colors. + """Proxy for the ColourDatabase which allows for finding W3C colors. - This class is necessary because the wx 'green' is the W3C 'lime', - and we need some means to lookup the color names since wx has - only a few hardcoded. + This class is necessary because the wx 'green' is the W3C 'lime', + and we need some means to lookup the color names since wx has + only a few hardcoded. - This class is a proxy because AddColour expects a wx.ColourDatabase - instance, not an instance of a subclass + This class is a proxy because AddColour expects a wx.ColourDatabase + instance, not an instance of a subclass """ _database = wx.ColourDatabase() @@ -109,8 +109,7 @@ def tuple_to_wxcolor(tup): def convert_to_color(object, name, value): - """ Converts a number into a wxColour object. - """ + """Converts a number into a wxColour object.""" if isinstance(value, tuple): return tuple_to_wxcolor(value) @@ -253,8 +252,7 @@ def get_color_editor(*args, **traits): def WxColor(default="white", allow_none=False, **metadata): - """ Defines wxPython-specific color traits. - """ + """Defines wxPython-specific color traits.""" if default is None: allow_none = True @@ -265,7 +263,7 @@ def WxColor(default="white", allow_none=False, **metadata): standard_colors, convert_to_color, editor=get_color_editor, - **metadata + **metadata, ) return Trait( @@ -273,5 +271,5 @@ def WxColor(default="white", allow_none=False, **metadata): standard_colors, convert_to_color, editor=get_color_editor, - **metadata + **metadata, ) diff --git a/traitsui/wx/compound_editor.py b/traitsui/wx/compound_editor.py index 58068cd8c..ee0ebf85d 100644 --- a/traitsui/wx/compound_editor.py +++ b/traitsui/wx/compound_editor.py @@ -27,7 +27,7 @@ class CompoundEditor(Editor): - """ Editor for compound traits, which displays editors for each of the + """Editor for compound traits, which displays editors for each of the combined traits, in the appropriate style. """ @@ -39,8 +39,8 @@ class CompoundEditor(Editor): kind = Str() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ # Create a panel to hold all of the component trait editors: self.control = panel = TraitsUIPanel(parent, -1) @@ -64,14 +64,13 @@ def init(self, parent): self.set_tooltip() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ pass def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" for editor in self._editors: editor.dispose() diff --git a/traitsui/wx/csv_list_editor.py b/traitsui/wx/csv_list_editor.py index 39ecaa95f..ac2ff4ffa 100644 --- a/traitsui/wx/csv_list_editor.py +++ b/traitsui/wx/csv_list_editor.py @@ -22,21 +22,21 @@ class SimpleEditor(WXSimpleEditor): - """ Simple Editor style for CSVListEditor. """ + """Simple Editor style for CSVListEditor.""" prepare = _prepare_method dispose = _dispose_method class CustomEditor(WXCustomEditor): - """ Custom Editor style for CSVListEditor. """ + """Custom Editor style for CSVListEditor.""" prepare = _prepare_method dispose = _dispose_method class ReadonlyEditor(WXReadonlyEditor): - """ Readonly Editor style for CSVListEditor. """ + """Readonly Editor style for CSVListEditor.""" prepare = _prepare_method dispose = _dispose_method diff --git a/traitsui/wx/custom_editor.py b/traitsui/wx/custom_editor.py index 29ffad43b..e9206949d 100644 --- a/traitsui/wx/custom_editor.py +++ b/traitsui/wx/custom_editor.py @@ -23,12 +23,11 @@ class CustomEditor(Editor): - """ Wrapper for a custom editor control - """ + """Wrapper for a custom editor control""" def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory.factory if factory is not None: @@ -45,7 +44,7 @@ def init(self, parent): self.set_tooltip() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ pass diff --git a/traitsui/wx/data_frame_editor.py b/traitsui/wx/data_frame_editor.py index 9f5bfe4ce..90f181585 100644 --- a/traitsui/wx/data_frame_editor.py +++ b/traitsui/wx/data_frame_editor.py @@ -16,6 +16,6 @@ class _DataFrameEditor(BaseDataFrameEditor, UIEditor): - """ Wx Toolkit implementation of the DataFrameEditor """ + """Wx Toolkit implementation of the DataFrameEditor""" pass diff --git a/traitsui/wx/date_editor.py b/traitsui/wx/date_editor.py index 0a8e3a427..946612151 100644 --- a/traitsui/wx/date_editor.py +++ b/traitsui/wx/date_editor.py @@ -45,7 +45,9 @@ def init(self, parent): self.control = date_widget( parent, size=(120, -1), - style=wx.adv.DP_DROPDOWN | wx.adv.DP_SHOWCENTURY | wx.adv.DP_ALLOWNONE, + style=wx.adv.DP_DROPDOWN + | wx.adv.DP_SHOWCENTURY + | wx.adv.DP_ALLOWNONE, ) self.control.Bind(wx.adv.EVT_DATE_CHANGED, self.day_selected) return @@ -64,7 +66,9 @@ def day_selected(self, event): try: self.value = datetime.date(year, month, day) except ValueError: - logger.exception("Invalid date: %d-%d-%d (y-m-d)", (year, month, day)) + logger.exception( + "Invalid date: %d-%d-%d (y-m-d)", (year, month, day) + ) raise return @@ -270,7 +274,7 @@ def __init__( months, padding, *args, - **kwargs + **kwargs, ): super().__init__(parent, ID, *args, **kwargs) @@ -363,7 +367,7 @@ def shift_datetime(self, old_date, months): return new_date def selected_list_changed(self, evt=None): - """ Update the date colors of the days in the widgets. """ + """Update the date colors of the days in the widgets.""" for cal in self.cal_ctrls: cur_month = cal.GetDate().GetMonth() + 1 cur_year = cal.GetDate().GetYear() @@ -381,14 +385,10 @@ def selected_list_changed(self, evt=None): try: paint_day = datetime.date(cur_year, cur_month, day) if not self.allow_future and paint_day > self.today: - attr = wx.adv.CalendarDateAttr( - colText=UNAVAILABLE_FG - ) + attr = wx.adv.CalendarDateAttr(colText=UNAVAILABLE_FG) cal.SetAttr(day, attr) elif paint_day in selected_days: - attr = wx.adv.CalendarDateAttr( - colText=SELECTED_FG - ) + attr = wx.adv.CalendarDateAttr(colText=SELECTED_FG) cal.SetAttr(day, attr) else: cal.ResetAttr(day) @@ -460,9 +460,7 @@ def unhighlight_days(self, days): (date.year, date.month, date.day) > (self.today.year, self.today.month, self.today.day) ): - attr = wx.adv.CalendarDateAttr( - colText=UNAVAILABLE_FG - ) + attr = wx.adv.CalendarDateAttr(colText=UNAVAILABLE_FG) else: attr = wx.adv.CalendarDateAttr( colText=NORMAL_HIGHLIGHT_FG, @@ -594,7 +592,7 @@ def single_select_day(self, dt): return def _shift_drag_update(self, event): - """ Shift-drag in progress. """ + """Shift-drag in progress.""" cal = event.GetEventObject() result, dt, weekday = cal.HitTest(event.GetPosition()) @@ -643,7 +641,7 @@ def _process_box_select(self, event): self._box_select = [] def _weekday_clicked(self, evt): - """ A day on the weekday bar has been clicked. Select all days. """ + """A day on the weekday bar has been clicked. Select all days.""" evt.Skip() weekday = evt.GetWeekDay() cal = evt.GetEventObject() @@ -668,7 +666,7 @@ def _weekday_clicked(self, evt): return def _left_down(self, event): - """ Handle user selection of days. """ + """Handle user selection of days.""" event.Skip() cal = event.GetEventObject() result, dt, weekday = cal.HitTest(event.GetPosition()) @@ -693,7 +691,7 @@ def _left_down(self, event): return def _left_up(self, event): - """ Handle the end of a possible run-selection. """ + """Handle the end of a possible run-selection.""" event.Skip() cal = event.GetEventObject() result, dt, weekday = cal.HitTest(event.GetPosition()) @@ -727,7 +725,7 @@ def _left_up(self, event): return def _mouse_drag(self, event): - """ Called when the mouse in being dragged within the main panel. """ + """Called when the mouse in being dragged within the main panel.""" event.Skip() cal = event.GetEventObject() if not cal.selecting and self._first_date: @@ -840,12 +838,11 @@ class TextEditor(SimpleEditor): pass - class ReadonlyEditor(TextReadonlyEditor): - """ Use a TextEditor for the view. """ + """Use a TextEditor for the view.""" def _get_str_value(self): - """ Replace the default string value with our own date verision. """ + """Replace the default string value with our own date verision.""" if not self.value: return self.factory.message else: diff --git a/traitsui/wx/directory_editor.py b/traitsui/wx/directory_editor.py index eef850b58..49f8a4382 100644 --- a/traitsui/wx/directory_editor.py +++ b/traitsui/wx/directory_editor.py @@ -28,20 +28,18 @@ class SimpleEditor(SimpleFileEditor): - """ Simple style of editor for directories, which displays a text field - and a **Browse** button that opens a directory-selection dialog box. + """Simple style of editor for directories, which displays a text field + and a **Browse** button that opens a directory-selection dialog box. """ def _create_file_dialog(self): - """ Creates the correct type of file dialog. - """ + """Creates the correct type of file dialog.""" dlg = wx.DirDialog(self.control, message="Select a Directory") dlg.SetPath(self._file_name.GetValue()) return dlg def _create_file_popup(self): - """ Creates the correct type of file popup. - """ + """Creates the correct type of file popup.""" return PopupDirectory( control=self.control, file_name=self.str_value, @@ -51,18 +49,16 @@ def _create_file_popup(self): class CustomEditor(CustomFileEditor): - """ Custom style of editor for directories, which displays a tree view of - the file system. + """Custom style of editor for directories, which displays a tree view of + the file system. """ def get_style(self): - """ Returns the basic style to use for the control. - """ + """Returns the basic style to use for the control.""" return wx.DIRCTRL_DIR_ONLY | wx.DIRCTRL_EDIT_LABELS def update_object(self, event): - """ Handles the user changing the contents of the edit control. - """ + """Handles the user changing the contents of the edit control.""" if self.control is not None: path = self.control.GetPath() if isdir(path): @@ -71,11 +67,9 @@ def update_object(self, event): class PopupDirectory(PopupFile): def get_style(self): - """ Returns the basic style to use for the popup. - """ + """Returns the basic style to use for the popup.""" return wx.DIRCTRL_DIR_ONLY | wx.DIRCTRL_EDIT_LABELS def is_valid(self, path): - """ Returns whether or not the path is valid. - """ + """Returns whether or not the path is valid.""" return isdir(path) diff --git a/traitsui/wx/dnd_editor.py b/traitsui/wx/dnd_editor.py index 12003e2ce..bff499264 100644 --- a/traitsui/wx/dnd_editor.py +++ b/traitsui/wx/dnd_editor.py @@ -63,8 +63,8 @@ class SimpleEditor(Editor): - """ Simply style of editor for a drag-and-drop editor, which is both a drag - source and a drop target. + """Simply style of editor for a drag-and-drop editor, which is both a drag + source and a drop target. """ # ------------------------------------------------------------------------- @@ -78,8 +78,8 @@ class SimpleEditor(Editor): drag_source = Bool(True) def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ # Determine the drag/drop type: value = self.value @@ -131,8 +131,7 @@ def init(self, parent): control.Bind(wx.EVT_PAINT, self._on_paint) def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" control = self.control control.Unbind(wx.EVT_LEFT_DOWN) control.Unbind(wx.EVT_LEFT_UP) @@ -142,16 +141,15 @@ def dispose(self): super().dispose() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ return # -- Private Methods ------------------------------------------------------ def _get_drag_data(self, data): - """ Returns the processed version of a drag request's data. - """ + """Returns the processed version of a drag request's data.""" if isinstance(data, list): if Binding is not None and isinstance(data[0], Binding): @@ -181,8 +179,7 @@ def _get_drag_data(self, data): return data def _unpickle(self, file_name): - """ Returns the unpickled version of a specified file (if possible). - """ + """Returns the unpickled version of a specified file (if possible).""" with open(file_name, "rb") as fh: try: object = load(fh) @@ -194,8 +191,7 @@ def _unpickle(self, file_name): # -- wxPython Event Handlers ---------------------------------------------- def _on_paint(self, event): - """ Called when the control needs repainting. - """ + """Called when the control needs repainting.""" image = self._image control = self.control if not control.IsEnabled(): @@ -210,8 +206,7 @@ def _on_paint(self, event): ) def _left_down(self, event): - """ Handles the left mouse button being pressed. - """ + """Handles the left mouse button being pressed.""" if self.control.IsEnabled() and self.drag_source: self._x, self._y = event.GetX(), event.GetY() self.control.CaptureMouse() @@ -219,8 +214,7 @@ def _left_down(self, event): event.Skip() def _left_up(self, event): - """ Handles the left mouse button being released. - """ + """Handles the left mouse button being released.""" if self._x is not None: self._x = None self.control.ReleaseMouse() @@ -228,8 +222,7 @@ def _left_up(self, event): event.Skip() def _mouse_move(self, event): - """ Handles the mouse being moved. - """ + """Handles the mouse being moved.""" if self._x is not None: if ( abs(self._x - event.GetX()) + abs(self._y - event.GetY()) @@ -246,8 +239,7 @@ def _mouse_move(self, event): # ----- Drag and drop event handlers: ------------------------------------- def wx_dropped_on(self, x, y, data, drag_result): - """ Handles a Python object being dropped on the tree. - """ + """Handles a Python object being dropped on the tree.""" try: self.value = self._get_drag_data(data) return drag_result @@ -255,8 +247,7 @@ def wx_dropped_on(self, x, y, data, drag_result): return wx.DragNone def wx_drag_over(self, x, y, data, drag_result): - """ Handles a Python object being dragged over the tree. - """ + """Handles a Python object being dragged over the tree.""" try: self.object.base_trait(self.name).validate( self.object, self.name, self._get_drag_data(data) @@ -267,8 +258,7 @@ def wx_drag_over(self, x, y, data, drag_result): class CustomEditor(SimpleEditor): - """ Custom style of drag-and-drop editor, which is not a drag source. - """ + """Custom style of drag-and-drop editor, which is not a drag source.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -279,8 +269,7 @@ class CustomEditor(SimpleEditor): class ReadonlyEditor(SimpleEditor): - """ Read-only style of drag-and-drop editor, which is not a drop target. - """ + """Read-only style of drag-and-drop editor, which is not a drop target.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -291,12 +280,10 @@ class ReadonlyEditor(SimpleEditor): class FileDropSource(wx.DropSource): - """ Represents a draggable file. - """ + """Represents a draggable file.""" def __init__(self, source, files): - """ Initializes the object. - """ + """Initializes the object.""" self.handler = None self.allow_move = True @@ -318,5 +305,5 @@ def __init__(self, source, files): self.result = self.DoDragDrop(True) def on_dropped(self, drag_result): - """ Called when the data has been dropped. """ + """Called when the data has been dropped.""" return diff --git a/traitsui/wx/drop_editor.py b/traitsui/wx/drop_editor.py index 0a4dee764..c9fbde39f 100644 --- a/traitsui/wx/drop_editor.py +++ b/traitsui/wx/drop_editor.py @@ -27,7 +27,7 @@ class SimpleEditor(Editor): - """ Simple style of drop editor, which displays a read-only text field that + """Simple style of drop editor, which displays a read-only text field that contains the string representation of the object trait's value. """ @@ -35,8 +35,8 @@ class SimpleEditor(Editor): ok_color = DropColor def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ if self.factory.readonly: self.control = wx.TextCtrl( @@ -49,22 +49,19 @@ def init(self, parent): self.control.SetDropTarget(PythonDropTarget(self)) def string_value(self, value): - """ Returns the text representation of a specified object trait value. - """ + """Returns the text representation of a specified object trait value.""" if value is None: return "" return str(value) def error(self, excp): - """ Handles an error that occurs while setting the object's trait value. - """ + """Handles an error that occurs while setting the object's trait value.""" pass # ----- Drag and drop event handlers: ------------------------------------- def wx_dropped_on(self, x, y, data, drag_result): - """ Handles a Python object being dropped on the tree. - """ + """Handles a Python object being dropped on the tree.""" klass = self.factory.klass value = data if self.factory.binding: @@ -87,8 +84,7 @@ def wx_dropped_on(self, x, y, data, drag_result): return wx.DragNone def wx_drag_over(self, x, y, data, drag_result): - """ Handles a Python object being dragged over the tree. - """ + """Handles a Python object being dragged over the tree.""" if self.factory.binding: data = getattr(clipboard, "node", None) try: diff --git a/traitsui/wx/editor.py b/traitsui/wx/editor.py index 0b4cc39e3..53ee5e1a5 100644 --- a/traitsui/wx/editor.py +++ b/traitsui/wx/editor.py @@ -31,8 +31,7 @@ class Editor(UIEditor): - """ Base class for wxPython editors for Traits-based UIs. - """ + """Base class for wxPython editors for Traits-based UIs.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -45,28 +44,25 @@ class Editor(UIEditor): border_size = Int(4) def _control_changed(self, control): - """ Handles the **control** trait being set. - """ + """Handles the **control** trait being set.""" if control is not None: control._editor = self def set_focus(self): - """ Assigns focus to the editor's underlying toolkit widget. - """ + """Assigns focus to the editor's underlying toolkit widget.""" if self.control is not None: self.control.SetFocus() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ new_value = self.str_value if self.control.GetValue() != new_value: self.control.SetValue(new_value) def error(self, excp): - """ Handles an error that occurs while setting the object's trait value. - """ + """Handles an error that occurs while setting the object's trait value.""" dlg = wx.MessageDialog( self.control, str(excp), @@ -77,13 +73,11 @@ def error(self, excp): dlg.Destroy() def set_tooltip_text(self, control, text): - """ Sets the tooltip for a specified control. - """ + """Sets the tooltip for a specified control.""" control.SetToolTip(text) def _enabled_changed(self, enabled): - """ Handles the **enabled** state of the editor being changed. - """ + """Handles the **enabled** state of the editor being changed.""" control = self.control if control is not None: control.Enable(enabled) @@ -93,8 +87,7 @@ def _enabled_changed(self, enabled): self.label_control.Refresh() def _visible_changed(self, visible): - """ Handles the **visible** state of the editor being changed. - """ + """Handles the **visible** state of the editor being changed.""" control = self.control parent = control.GetParent() @@ -123,18 +116,15 @@ def _visible_changed(self, visible): parent.Layout() def get_error_control(self): - """ Returns the editor's control for indicating error status. - """ + """Returns the editor's control for indicating error status.""" return self.control def in_error_state(self): - """ Returns whether or not the editor is in an error state. - """ + """Returns whether or not the editor is in an error state.""" return False def set_error_state(self, state=None, control=None): - """ Sets the editor's current error state. - """ + """Sets the editor's current error state.""" if state is None: state = self.invalid state = state or self.in_error_state() @@ -161,14 +151,12 @@ def set_error_state(self, state=None, control=None): item.Refresh() def _invalid_changed(self, state): - """ Handles the editor's invalid state changing. - """ + """Handles the editor's invalid state changing.""" self.set_error_state() class EditorWithList(Editor): - """ Editor for an object that contains a list. - """ + """Editor for an object that contains a list.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -184,14 +172,15 @@ class EditorWithList(Editor): list_value = Callable() def init(self, parent): - """ Initializes the object. - """ + """Initializes the object.""" factory = self.factory name = factory.name if name != "": - self.list_object, self.list_name, self.list_value = self.parse_extended_name( - name - ) + ( + self.list_object, + self.list_name, + self.list_value, + ) = self.parse_extended_name(name) else: self.list_object, self.list_name = factory, "values" self.list_value = lambda: factory.values @@ -203,8 +192,7 @@ def init(self, parent): self._list_updated() def dispose(self): - """ Disconnects the listeners set up by the constructor. - """ + """Disconnects the listeners set up by the constructor.""" self.list_object.on_trait_change( self._list_updated, self.list_name + "[]", remove=True ) @@ -212,23 +200,19 @@ def dispose(self): super().dispose() def _list_updated(self): - """ Handles the monitored trait being updated. - """ + """Handles the monitored trait being updated.""" self.list_updated(self.list_value()) def list_updated(self, values): - """ Handles the monitored list being updated. - """ + """Handles the monitored list being updated.""" raise NotImplementedError class EditorFromView(Editor): - """ An editor generated from a View object. - """ + """An editor generated from a View object.""" def init(self, parent): - """ Initializes the object. - """ + """Initializes the object.""" self._ui = ui = self.init_ui(parent) if ui.history is None: ui.history = self.ui.history @@ -236,22 +220,21 @@ def init(self, parent): self.control = ui.control def init_ui(self, parent): - """ Creates and returns the traits UI defined by this editor. - (Must be overridden by a subclass). + """Creates and returns the traits UI defined by this editor. + (Must be overridden by a subclass). """ raise NotImplementedError def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ # Normally nothing needs to be done here, since it should all be handled # by the editor's internally created traits UI: pass def dispose(self): - """ Disposes of the editor. - """ + """Disposes of the editor.""" self._ui.dispose() super().dispose() diff --git a/traitsui/wx/editor_factory.py b/traitsui/wx/editor_factory.py index d9efd48b6..40424a83f 100644 --- a/traitsui/wx/editor_factory.py +++ b/traitsui/wx/editor_factory.py @@ -25,18 +25,18 @@ class SimpleEditor(Editor): - """ Base class for simple style editors, which displays a text field - containing the text representation of the object trait value. Clicking - in the text field displays an editor-specific dialog box for changing - the value. + """Base class for simple style editors, which displays a text field + containing the text representation of the object trait value. Clicking + in the text field displays an editor-specific dialog box for changing + the value. """ #: Has the left mouse button been pressed: left_down = Bool(False) def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = self.create_control(parent) self.control.Bind(wx.EVT_LEFT_DOWN, self._enable_popup_editor) @@ -44,8 +44,7 @@ def init(self, parent): self.set_tooltip() def create_control(self, parent): - """ Creates the control to use for the simple editor. - """ + """Creates the control to use for the simple editor.""" return wx.TextCtrl(parent, -1, self.str_value, style=wx.TE_READONLY) # ------------------------------------------------------------------------- @@ -55,18 +54,16 @@ def create_control(self, parent): # ------------------------------------------------------------------------- def popup_editor(self, event): - """ Invokes the pop-up editor for an object trait. - """ + """Invokes the pop-up editor for an object trait.""" pass def _enable_popup_editor(self, event): - """ Mark the left mouse button as being pressed currently. - """ + """Mark the left mouse button as being pressed currently.""" self.left_down = True def _show_popup_editor(self, event): - """ Display the popup editor if the left mouse button was pressed - previously. + """Display the popup editor if the left mouse button was pressed + previously. """ if self.left_down: self.left_down = False @@ -74,25 +71,26 @@ def _show_popup_editor(self, event): class TextEditor(Editor): - """ Base class for text style editors, which displays an editable text - field, containing a text representation of the object trait value. + """Base class for text style editors, which displays an editable text + field, containing a text representation of the object trait value. """ def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = wx.TextCtrl( parent, -1, self.str_value, style=wx.TE_PROCESS_ENTER ) self.control.Bind(wx.EVT_KILL_FOCUS, self.update_object) - parent.Bind(wx.EVT_TEXT_ENTER, self.update_object, id=self.control.GetId()) + parent.Bind( + wx.EVT_TEXT_ENTER, self.update_object, id=self.control.GetId() + ) self.set_tooltip() def dispose(self): - """ Disposes of the contents of an editor. - """ - if self.control is not None: # just in-case + """Disposes of the contents of an editor.""" + if self.control is not None: # just in-case parent = self.control.GetParent() parent.Unbind( wx.EVT_TEXT_ENTER, @@ -103,8 +101,7 @@ def dispose(self): super().dispose() def update_object(self, event): - """ Handles the user changing the contents of the edit control. - """ + """Handles the user changing the contents of the edit control.""" if isinstance(event, wx.FocusEvent): event.Skip() try: @@ -114,8 +111,8 @@ def update_object(self, event): class ReadonlyEditor(Editor): - """ Base class for read-only style editors, which displays a read-only text - field, containing a text representation of the object trait value. + """Base class for read-only style editors, which displays a read-only text + field, containing a text representation of the object trait value. """ # ------------------------------------------------------------------------- @@ -125,8 +122,8 @@ class ReadonlyEditor(Editor): # layout_style = 0 # Style for imbedding control in a sizer (override) def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ if (self.item.resizable is True) or (self.item.height != -1.0): self.control = wx.TextCtrl( @@ -145,8 +142,8 @@ def init(self, parent): self.set_tooltip() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ new_value = self.str_value if (self.item.resizable is True) or (self.item.height != -1.0): diff --git a/traitsui/wx/enum_editor.py b/traitsui/wx/enum_editor.py index d092dd75d..ccdf5bd9a 100644 --- a/traitsui/wx/enum_editor.py +++ b/traitsui/wx/enum_editor.py @@ -36,8 +36,7 @@ class BaseEditor(Editor): - """ Base class for enumeration editors. - """ + """Base class for enumeration editors.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -53,8 +52,8 @@ class BaseEditor(Editor): inverse_mapping = Property() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory if factory.name != "": @@ -73,44 +72,42 @@ def init(self, parent): ) def _get_names(self): - """ Gets the current set of enumeration names. - """ + """Gets the current set of enumeration names.""" return self._names def _get_mapping(self): - """ Gets the current mapping. - """ + """Gets the current mapping.""" return self._mapping def _get_inverse_mapping(self): - """ Gets the current inverse mapping. - """ + """Gets the current inverse mapping.""" return self._inverse_mapping def rebuild_editor(self): - """ Rebuilds the contents of the editor whenever the original factory - object's **values** trait changes. + """Rebuilds the contents of the editor whenever the original factory + object's **values** trait changes. """ raise NotImplementedError def values_changed(self): - """ Recomputes the cached data based on the underlying enumeration model - or the values of the factory. + """Recomputes the cached data based on the underlying enumeration model + or the values of the factory. """ - self._names, self._mapping, self._inverse_mapping = enum_values_changed( - self._value(), self.string_value - ) + ( + self._names, + self._mapping, + self._inverse_mapping, + ) = enum_values_changed(self._value(), self.string_value) def _values_changed(self): - """ Handles the underlying object model's enumeration set or factory's - values being changed. + """Handles the underlying object model's enumeration set or factory's + values being changed. """ self.values_changed() self.rebuild_editor() def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" if self._object is not None: self._object.on_trait_change( self._values_changed, " " + self._name, remove=True @@ -129,12 +126,11 @@ def dispose(self): class SimpleEditor(BaseEditor): - """ Simple style of enumeration editor, which displays a combo box. - """ + """Simple style of enumeration editor, which displays a combo box.""" def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ super().init(parent) @@ -144,7 +140,9 @@ def init(self, parent): self.control = control = wx.Choice( parent, -1, wx.Point(0, 0), wx.Size(-1, -1), self.names ) - parent.Bind(wx.EVT_CHOICE, self.update_object, id=self.control.GetId()) + parent.Bind( + wx.EVT_CHOICE, self.update_object, id=self.control.GetId() + ) else: self.control = control = wx.ComboBox( parent, @@ -155,19 +153,24 @@ def init(self, parent): self.names, style=wx.CB_DROPDOWN, ) - parent.Bind(wx.EVT_COMBOBOX, self.update_object, id=control.GetId()) - parent.Bind(wx.EVT_TEXT_ENTER, self.update_text_object, id=control.GetId()) + parent.Bind( + wx.EVT_COMBOBOX, self.update_object, id=control.GetId() + ) + parent.Bind( + wx.EVT_TEXT_ENTER, self.update_text_object, id=control.GetId() + ) control.Bind(wx.EVT_KILL_FOCUS, self.on_kill_focus) if (not factory.is_grid_cell) and factory.auto_set: - parent.Bind(wx.EVT_TEXT, self.update_text_object, id=control.GetId()) + parent.Bind( + wx.EVT_TEXT, self.update_text_object, id=control.GetId() + ) self._no_enum_update = 0 self.set_tooltip() def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" disconnect( self.control, wx.EVT_COMBOBOX, wx.EVT_TEXT_ENTER, wx.EVT_TEXT ) @@ -177,8 +180,7 @@ def dispose(self): super().dispose() def update_object(self, event): - """ Handles the user selecting a new value from the combo box. - """ + """Handles the user selecting a new value from the combo box.""" self._no_enum_update += 1 try: new_value = self.mapping[event.GetString()] @@ -204,8 +206,7 @@ def update_object(self, event): self._no_enum_update -= 1 def update_text_object(self, event): - """ Handles the user typing text into the combo box text entry field. - """ + """Handles the user typing text into the combo box text entry field.""" if self._no_enum_update == 0: value = self.control.GetValue() try: @@ -227,14 +228,13 @@ def update_text_object(self, event): self._no_enum_update -= 1 def on_kill_focus(self, event): - """ Handles the control losing the keyboard focus. - """ + """Handles the control losing the keyboard focus.""" self.update_text_object(event) event.Skip() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ if self._no_enum_update == 0: if self.factory.evaluate is None: @@ -251,14 +251,13 @@ def update_editor(self): pass def error(self, excp): - """ Handles an error that occurs while setting the object's trait value. - """ + """Handles an error that occurs while setting the object's trait value.""" self.control.SetBackgroundColour(ErrorColor) self.control.Refresh() def rebuild_editor(self): - """ Rebuilds the contents of the editor whenever the original factory - object's **values** trait changes. + """Rebuilds the contents of the editor whenever the original factory + object's **values** trait changes. """ # Note: This code is unnecessarily complex due to a strange bug in # wxWidgets implementation of the wx.Combobox control that has strange @@ -304,13 +303,13 @@ def rebuild_editor(self): class RadioEditor(BaseEditor): - """ Enumeration editor, used for the "custom" style, that displays radio - buttons. + """Enumeration editor, used for the "custom" style, that displays radio + buttons. """ def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ super().init(parent) @@ -319,16 +318,15 @@ def init(self, parent): self.rebuild_editor() def update_object(self, event): - """ Handles the user clicking one of the custom radio buttons. - """ + """Handles the user clicking one of the custom radio buttons.""" try: self.value = event.GetEventObject().value except: pass def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ value = self.value for button in self.control.GetChildren(): @@ -338,8 +336,8 @@ def update_editor(self): button.SetFocus() def rebuild_editor(self): - """ Rebuilds the contents of the editor whenever the original factory - object's **values** trait changes. + """Rebuilds the contents of the editor whenever the original factory + object's **values** trait changes. """ # Clear any existing content: panel = self.control @@ -385,7 +383,11 @@ def rebuild_editor(self): control.value = mapping[name] style = 0 control.SetValue(name == cur_name) - panel.Bind(wx.EVT_RADIOBUTTON, self.update_object, id= control.GetId()) + panel.Bind( + wx.EVT_RADIOBUTTON, + self.update_object, + id=control.GetId(), + ) self.set_tooltip(control) index += incr[j] n -= 1 @@ -400,13 +402,13 @@ def rebuild_editor(self): class ListEditor(BaseEditor): - """ Enumeration editor, used for the "custom" style, that displays a list - box. + """Enumeration editor, used for the "custom" style, that displays a list + box. """ def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ super().init(parent) @@ -419,19 +421,19 @@ def init(self, parent): self.names, style=wx.LB_SINGLE | wx.LB_NEEDED_SB, ) - parent.Bind(wx.EVT_LISTBOX, self.update_object, id=self.control.GetId()) + parent.Bind( + wx.EVT_LISTBOX, self.update_object, id=self.control.GetId() + ) self.set_tooltip() def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" disconnect(self.control, wx.EVT_LISTBOX) super().dispose() def update_object(self, event): - """ Handles the user selecting a list box item. - """ + """Handles the user selecting a list box item.""" if not self._ignore_update: value = self.control.GetStringSelection() try: @@ -447,8 +449,8 @@ def update_object(self, event): pass def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ control = self.control try: @@ -459,8 +461,8 @@ def update_editor(self): pass def rebuild_editor(self): - """ Rebuilds the contents of the editor whenever the original factory - object's **values** trait changes. + """Rebuilds the contents of the editor whenever the original factory + object's **values** trait changes. """ self._ignore_update = True self.control.Clear() diff --git a/traitsui/wx/extra/bounds_editor.py b/traitsui/wx/extra/bounds_editor.py index da728c31c..fa70689d8 100644 --- a/traitsui/wx/extra/bounds_editor.py +++ b/traitsui/wx/extra/bounds_editor.py @@ -16,7 +16,6 @@ from traitsui.wx.helper import TraitsUIPanel, Slider - class _BoundsEditor(Editor): evaluate = Any() @@ -28,8 +27,8 @@ class _BoundsEditor(Editor): format = Str() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory if not factory.low_name: diff --git a/traitsui/wx/extra/led_editor.py b/traitsui/wx/extra/led_editor.py index 7cce8240b..700ee2f51 100644 --- a/traitsui/wx/extra/led_editor.py +++ b/traitsui/wx/extra/led_editor.py @@ -35,20 +35,19 @@ class _LEDEditor(Editor): - """ Traits UI 'display only' LED numeric editor. - """ + """Traits UI 'display only' LED numeric editor.""" def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = LEDNumberCtrl(parent, -1) self.control.SetAlignment(LEDStyles[self.factory.alignment]) self.set_tooltip() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ self.control.SetValue(self.str_value) diff --git a/traitsui/wx/extra/windows/flash_editor.py b/traitsui/wx/extra/windows/flash_editor.py index e96a2d9ef..204e99dc8 100644 --- a/traitsui/wx/extra/windows/flash_editor.py +++ b/traitsui/wx/extra/windows/flash_editor.py @@ -23,8 +23,7 @@ class _FlashEditor(Editor): - """ Traits UI Flash editor. - """ + """Traits UI Flash editor.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -34,15 +33,15 @@ class _FlashEditor(Editor): scrollable = True def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = FlashWindow(parent) self.set_tooltip() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ value = self.str_value.strip() if value.find("://") < 0: diff --git a/traitsui/wx/extra/windows/ie_html_editor.py b/traitsui/wx/extra/windows/ie_html_editor.py index f0995719d..e18458db8 100644 --- a/traitsui/wx/extra/windows/ie_html_editor.py +++ b/traitsui/wx/extra/windows/ie_html_editor.py @@ -43,8 +43,7 @@ class _IEHTMLEditor(Editor): - """ Traits UI MS Internet Explorer editor. - """ + """Traits UI MS Internet Explorer editor.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -87,8 +86,8 @@ class _IEHTMLEditor(Editor): html = Property() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = ie = iewin.IEHtmlWindow( parent, -1, style=wx.NO_FULL_REPAINT_ON_RESIZE @@ -111,13 +110,15 @@ def init(self, parent): parent.Bind(iewin.EVT_StatusTextChange, ie, id=self._status_modified) parent.Bind(iewin.EVT_TitleChange, ie, id=self._title_modified) - parent.Bind(iewin.EVT_DocumentComplete, ie, id=self._page_loaded_modified) + parent.Bind( + iewin.EVT_DocumentComplete, ie, id=self._page_loaded_modified + ) parent.Bind(iewin.EVT_NewWindow2, ie, id=self._new_window_modified) parent.Bind(iewin.EVT_BeforeNavigate2, ie, id=self._navigate_requested) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ value = self.str_value.strip() diff --git a/traitsui/wx/file_editor.py b/traitsui/wx/file_editor.py index 3f22b5e27..6e95cd449 100644 --- a/traitsui/wx/file_editor.py +++ b/traitsui/wx/file_editor.py @@ -35,9 +35,9 @@ class SimpleEditor(SimpleTextEditor): - """ Simple style of file editor, consisting of a text field and a **Browse** - button that opens a file-selection dialog box. The user can also drag - and drop a file onto this control. + """Simple style of file editor, consisting of a text field and a **Browse** + button that opens a file-selection dialog box. The user can also drag + and drop a file onto this control. """ #: The history control (used if the factory 'entries' > 0): @@ -47,8 +47,8 @@ class SimpleEditor(SimpleTextEditor): popup = Any() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = panel = TraitsUIPanel(parent, -1) sizer = wx.BoxSizer(wx.HORIZONTAL) @@ -66,7 +66,9 @@ def init(self, parent): else: if factory.enter_set: control = wx.TextCtrl(panel, -1, "", style=wx.TE_PROCESS_ENTER) - panel.Bind(wx.EVT_TEXT_ENTER, self.update_object, id=control.GetId()) + panel.Bind( + wx.EVT_TEXT_ENTER, self.update_object, id=control.GetId() + ) else: control = wx.TextCtrl(panel, -1, "") @@ -91,8 +93,7 @@ def init(self, parent): self.set_tooltip(control) def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" panel = self.control panel.Unbind(wx.EVT_BUTTON, id=self._button.GetId()) self._button = None @@ -110,22 +111,20 @@ def dispose(self): @observe("history:value") def _history_value_changed(self, event): - """ Handles the history 'value' trait being changed. - """ + """Handles the history 'value' trait being changed.""" value = event.new if not self._no_update: self._update(value) def update_object(self, event): - """ Handles the user changing the contents of the edit control. - """ + """Handles the user changing the contents of the edit control.""" if isinstance(event, wx.FocusEvent): event.Skip() self._update(self._file_name.GetValue()) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ if self.history is not None: self._no_update = True @@ -135,8 +134,7 @@ def update_editor(self): self._file_name.SetValue(self.str_value) def show_file_dialog(self, event): - """ Displays the pop-up file dialog. - """ + """Displays the pop-up file dialog.""" if self.history is not None: self.popup = self._create_file_popup() else: @@ -152,16 +150,14 @@ def show_file_dialog(self, event): self.update_editor() def get_error_control(self): - """ Returns the editor's control for indicating error status. - """ + """Returns the editor's control for indicating error status.""" return self._file_name # -- Traits Event Handlers ------------------------------------------------ @observe("popup:value") def _popup_value_changed(self, event): - """ Handles the popup value being changed. - """ + """Handles the popup value being changed.""" file_name = event.new if self.factory.truncate_ext: file_name = splitext(file_name)[0] @@ -173,15 +169,14 @@ def _popup_value_changed(self, event): @observe("popup:closed") def _popup_closed_changed(self, event): - """ Handles the popup control being closed. - """ + """Handles the popup control being closed.""" self.popup = None # -- UI preference save/restore interface --------------------------------- def restore_prefs(self, prefs): - """ Restores any saved user preference information associated with the - editor. + """Restores any saved user preference information associated with the + editor. """ if self.history is not None: self.history.history = prefs.get("history", [])[ @@ -189,8 +184,7 @@ def restore_prefs(self, prefs): ] def save_prefs(self): - """ Returns any user preference information associated with the editor. - """ + """Returns any user preference information associated with the editor.""" if self.history is not None: return {"history": self.history.history[:]} @@ -199,8 +193,7 @@ def save_prefs(self): # -- Private Methods ------------------------------------------------------ def _create_file_dialog(self): - """ Creates the correct type of file dialog. - """ + """Creates the correct type of file dialog.""" if len(self.factory.filter) > 0: wildcard = "|".join(self.factory.filter[:]) else: @@ -227,8 +220,7 @@ def _create_file_dialog(self): return dlg def _create_file_popup(self): - """ Creates the correct type of file popup. - """ + """Creates the correct type of file popup.""" return PopupFile( control=self.control, file_name=self.str_value, @@ -237,8 +229,7 @@ def _create_file_popup(self): ) def _update(self, file_name): - """ Updates the editor value with a specified file name. - """ + """Updates the editor value with a specified file name.""" try: if self.factory.truncate_ext: file_name = splitext(file_name)[0] @@ -248,8 +239,7 @@ def _update(self, file_name): pass def _get_value(self): - """ Returns the current file name from the edit control. - """ + """Returns the current file name from the edit control.""" if self.history is not None: return self.history.value @@ -257,8 +247,7 @@ def _get_value(self): class CustomEditor(SimpleTextEditor): - """ Custom style of file editor, consisting of a file system tree view. - """ + """Custom style of file editor, consisting of a file system tree view.""" #: Is the file editor scrollable? This value overrides the default. scrollable = True @@ -273,8 +262,8 @@ class CustomEditor(SimpleTextEditor): dclick = Event() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ style = self.get_style() factory = self.factory @@ -296,8 +285,7 @@ def init(self, parent): self.set_tooltip() def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" tree, self._tree = self._tree, None tree.Unbind(wx.EVT_TREE_SEL_CHANGED) @@ -306,8 +294,7 @@ def dispose(self): super().dispose() def update_object(self, event): - """ Handles the user changing the contents of the edit control. - """ + """Handles the user changing the contents of the edit control.""" if self.control is not None: path = self.control.GetPath() if self.factory.allow_dir or isfile(path): @@ -317,41 +304,35 @@ def update_object(self, event): self.value = path def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ if exists(self.str_value): self.control.SetPath(self.str_value) def get_style(self): - """ Returns the basic style to use for the control. - """ + """Returns the basic style to use for the control.""" return wx.DIRCTRL_EDIT_LABELS def get_error_control(self): - """ Returns the editor's control for indicating error status. - """ + """Returns the editor's control for indicating error status.""" return self._tree def _filter_changed(self): - """ Handles the 'filter' trait being changed. - """ + """Handles the 'filter' trait being changed.""" self.control.SetFilter("|".join(self.filter[:])) def _on_dclick(self, event): - """ Handles the user double-clicking on a file name. - """ + """Handles the user double-clicking on a file name.""" self.dclick = self.control.GetPath() def _on_tooltip(self, event): - """ Handles the user hovering on a file name for a tooltip. - """ + """Handles the user hovering on a file name for a tooltip.""" text = self._tree.GetItemText(event.GetItem()) event.SetToolTip(text) def _reload_changed(self): - """ Handles the 'reload' trait being changed. - """ + """Handles the 'reload' trait being changed.""" self.control.ReCreateTree() @@ -369,8 +350,7 @@ class PopupFile(PopupControl): # -- PopupControl Method Overrides ---------------------------------------- def create_control(self, parent): - """ Creates the file control and gets it ready for use. - """ + """Creates the file control and gets it ready for use.""" style = self.get_style() if len(self.filter) > 0: style |= wx.DIRCTRL_SHOW_FILTERS @@ -387,20 +367,17 @@ def dispose(self): self._tree = self._files = None def get_style(self): - """ Returns the base style for this type of popup. - """ + """Returns the base style for this type of popup.""" return wx.DIRCTRL_EDIT_LABELS def is_valid(self, path): - """ Returns whether or not the path is valid. - """ + """Returns whether or not the path is valid.""" return isfile(path) # -- Private Methods ------------------------------------------------------ def _select_file(self, event): - """ Handles a file being selected in the file control. - """ + """Handles a file being selected in the file control.""" path = self._files.GetPath() # We have to make sure the selected path is different than the original @@ -422,8 +399,7 @@ def _select_file(self, event): class FileDropTarget(wx.FileDropTarget): - """ A target for a drag and drop operation, which accepts a file. - """ + """A target for a drag and drop operation, which accepts a file.""" def __init__(self, editor): wx.FileDropTarget.__init__(self) diff --git a/traitsui/wx/font_editor.py b/traitsui/wx/font_editor.py index bf27d2ccc..efca89ed0 100644 --- a/traitsui/wx/font_editor.py +++ b/traitsui/wx/font_editor.py @@ -69,14 +69,13 @@ class ToolkitEditorFactory(BaseToolkitEditorFactory): - """ wxPython editor factory for font editors. - """ + """wxPython editor factory for font editors.""" show_style = Bool(False) show_weight = Bool(False) def to_wx_font(self, editor): - """ Returns a wxFont object corresponding to a specified object's font + """Returns a wxFont object corresponding to a specified object's font trait. """ font = editor.value @@ -90,13 +89,11 @@ def to_wx_font(self, editor): ) def from_wx_font(self, font): - """ Gets the application equivalent of a wxPython Font value. - """ + """Gets the application equivalent of a wxPython Font value.""" return font def str_font(self, font): - """ Returns the text representation of the specified object trait value. - """ + """Returns the text representation of the specified object trait value.""" weight = { wx.FONTWEIGHT_LIGHT: " Light", wx.FONTWEIGHT_BOLD: " Bold", @@ -113,8 +110,7 @@ def str_font(self, font): ) def all_facenames(self): - """ Returns a list of all available font facenames. - """ + """Returns a list of all available font facenames.""" global facenames if facenames is None: @@ -128,14 +124,13 @@ def all_facenames(self): class SimpleFontEditor(BaseSimpleEditor): - """ Simple style of font editor, which displays a text field that contains - a text representation of the font value (using that font if possible). - Clicking the field displays a font selection dialog box. + """Simple style of font editor, which displays a text field that contains + a text representation of the font value (using that font if possible). + Clicking the field displays a font selection dialog box. """ def popup_editor(self, event): - """ Invokes the pop-up editor for an object trait. - """ + """Invokes the pop-up editor for an object trait.""" font_data = wx.FontData() font_data.SetInitialFont(self.factory.to_wx_font(self)) dialog = wx.FontDialog(self.control, font_data) @@ -148,29 +143,28 @@ def popup_editor(self, event): dialog.Destroy() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ super().update_editor() set_font(self) def string_value(self, font): - """ Returns the text representation of a specified font value. - """ + """Returns the text representation of a specified font value.""" return self.factory.str_font(font) class CustomFontEditor(Editor): - """ Custom style of font editor, which displays the following: + """Custom style of font editor, which displays the following: - * A combo box containing all available type face names. - * A combo box containing the available type sizes. - * A combo box containing the available type styles + * A combo box containing all available type face names. + * A combo box containing the available type sizes. + * A combo box containing the available type styles """ def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ # Create a panel to hold all of the buttons: self.control = panel = TraitsUIPanel(parent, -1) @@ -197,14 +191,20 @@ def init(self, parent): panel, -1, wx.Point(0, 0), wx.Size(-1, -1), Styles ) sizer2.Add(self._style, 1, wx.EXPAND | wx.LEFT, 3) - panel.Bind(wx.EVT_CHOICE, self.update_object_parts, id=self._style.GetId()) + panel.Bind( + wx.EVT_CHOICE, self.update_object_parts, id=self._style.GetId() + ) if self.factory.show_weight: self._weight = wx.Choice( panel, -1, wx.Point(0, 0), wx.Size(-1, -1), Weights ) sizer2.Add(self._weight, 1, wx.EXPAND | wx.LEFT, 3) - panel.Bind(wx.EVT_CHOICE, self.update_object_parts, id=self._weight.GetId()) + panel.Bind( + wx.EVT_CHOICE, + self.update_object_parts, + id=self._weight.GetId(), + ) sizer.Add(sizer2, 0, wx.EXPAND) @@ -214,8 +214,7 @@ def init(self, parent): self.set_tooltip() def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" disconnect(self._facename, wx.EVT_CHOICE) disconnect(self._point_size, wx.EVT_CHOICE) if self.factory.show_style: @@ -226,8 +225,7 @@ def dispose(self): super().dispose() def update_object_parts(self, event): - """ Handles the user modifying one of the font components. - """ + """Handles the user modifying one of the font components.""" point_size = int(self._point_size.GetStringSelection()) facename = self._facename.GetStringSelection() @@ -245,8 +243,8 @@ def update_object_parts(self, event): self.value = self.factory.from_wx_font(font) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ font = self.factory.to_wx_font(self) @@ -261,8 +259,7 @@ def update_editor(self): self._point_size.SetSelection(0) def string_value(self, font): - """ Returns the text representation of a specified font value. - """ + """Returns the text representation of a specified font value.""" return self.factory.str_font(font) @@ -272,45 +269,42 @@ def string_value(self, font): class TextFontEditor(BaseTextEditor): - """ Text style of font editor, which displays an editable text field - containing a text representation of the font value (using that font if - possible). + """Text style of font editor, which displays an editable text field + containing a text representation of the font value (using that font if + possible). """ def update_object(self, event): - """ Handles the user changing the contents of the edit control. - """ + """Handles the user changing the contents of the edit control.""" self.value = self.control.GetValue() def update_editor(self): - """ Updates the editor when the object trait changes external to the - editor. + """Updates the editor when the object trait changes external to the + editor. """ super().update_editor() set_font(self) def string_value(self, font): - """ Returns the text representation of a specified font value. - """ + """Returns the text representation of a specified font value.""" return self.factory.str_font(font) class ReadonlyFontEditor(BaseReadonlyEditor): - """ Read-only style of font editor, which displays a read-only text field - containing a text representation of the font value (using that font if - possible). + """Read-only style of font editor, which displays a read-only text field + containing a text representation of the font value (using that font if + possible). """ def update_editor(self): - """ Updates the editor when the object trait changes external to the - editor. + """Updates the editor when the object trait changes external to the + editor. """ super().update_editor() set_font(self) def string_value(self, font): - """ Returns the text representation of a specified font value. - """ + """Returns the text representation of a specified font value.""" return self.factory.str_font(font) @@ -320,27 +314,23 @@ def string_value(self, font): def set_font(editor): - """ Sets the editor control's font to match a specified font. - """ + """Sets the editor control's font to match a specified font.""" font = editor.factory.to_wx_font(editor) font.SetPointSize(min(10, font.GetPointSize())) editor.control.SetFont(font) class FontEnumerator(wx.FontEnumerator): - """ An enumeration of fonts. - """ + """An enumeration of fonts.""" def facenames(self): - """ Returns a list of all available font facenames. - """ + """Returns a list of all available font facenames.""" self._facenames = [] self.EnumerateFacenames() return self._facenames def OnFacename(self, facename): - """ Adds a facename to the list of facenames. - """ + """Adds a facename to the list of facenames.""" self._facenames.append(facename) return True diff --git a/traitsui/wx/font_trait.py b/traitsui/wx/font_trait.py index 614278eba..72dd7fe0e 100644 --- a/traitsui/wx/font_trait.py +++ b/traitsui/wx/font_trait.py @@ -41,8 +41,7 @@ def font_to_str(font): - """ Converts a wx.Font into a string description of itself. - """ + """Converts a wx.Font into a string description of itself.""" weight = {wx.FONTWEIGHT_LIGHT: " Light", wx.FONTWEIGHT_BOLD: " Bold"}.get( font.GetWeight(), "" ) @@ -62,8 +61,7 @@ def font_to_str(font): def create_traitsfont(value): - """ Create a TraitFont object from a string description. - """ + """Create a TraitFont object from a string description.""" if isinstance(value, wx.Font): value = font_to_str(value) @@ -97,17 +95,14 @@ def create_traitsfont(value): class TraitsFont(wx.Font): - """ A Traits-specific wx.Font. - """ + """A Traits-specific wx.Font.""" def __reduce_ex__(self, protocol): - """ Returns the pickleable form of a TraitsFont object. - """ + """Returns the pickleable form of a TraitsFont object.""" return (create_traitsfont, (font_to_str(self),)) def __str__(self): - """ Returns a printable form of the font. - """ + """Returns a printable form of the font.""" return font_to_str(self) @@ -117,13 +112,13 @@ def __str__(self): class TraitWXFont(TraitHandler): - """ Ensures that values assigned to a trait attribute are valid font + """Ensures that values assigned to a trait attribute are valid font descriptor strings; the value actually assigned is the corresponding TraitsFont. """ def validate(self, object, name, value): - """ Validates that the value is a valid font descriptor string. If so, + """Validates that the value is a valid font descriptor string. If so, it returns the corresponding TraitsFont; otherwise, it raises a TraitError. """ diff --git a/traitsui/wx/helper.py b/traitsui/wx/helper.py index 7a92c9e2b..92943777a 100644 --- a/traitsui/wx/helper.py +++ b/traitsui/wx/helper.py @@ -67,8 +67,7 @@ def bitmap_cache(name, standard_size, path=None): - """ Converts an image file name to a cached bitmap. - """ + """Converts an image file name to a cached bitmap.""" global app_path, traits_path if name[:1] == "@": @@ -123,22 +122,20 @@ def bitmap_cache(name, standard_size, path=None): def choice_width(values): - """ Returns an appropriate width for a wxChoice widget based upon the list - of values it contains: + """Returns an appropriate width for a wxChoice widget based upon the list + of values it contains: """ return max([len(x) for x in values]) * 6 def save_window(ui): - """ Saves the user preference items for a specified UI. - """ + """Saves the user preference items for a specified UI.""" control = ui.control ui.save_prefs(control.GetPosition() + control.GetSize()) def restore_window(ui, is_popup=False): - """ Restores the user preference items for a specified UI. - """ + """Restores the user preference items for a specified UI.""" prefs = ui.restore_prefs() if prefs is not None: x, y, dx, dy = prefs @@ -161,11 +158,11 @@ def restore_window(ui, is_popup=False): def find_closest_display(x, y): - """ For a virtual screen position, find the closest display. - There are a few reasons to use this function: - * the number of displays changed - * the size of the displays changed - * the orientation of one or more displays changed. + """For a virtual screen position, find the closest display. + There are a few reasons to use this function: + * the number of displays changed + * the size of the displays changed + * the orientation of one or more displays changed. """ closest = None for display_num in range(wx.Display.GetCount()): @@ -188,8 +185,8 @@ def _distance(x, y, display): def get_position_for_display(x, y, dx, dy, display): - """ calculates a valid position and size for a window to fit - inside a display + """calculates a valid position and size for a window to fit + inside a display """ dis_x, dis_y, dis_w, dis_h = display.GetGeometry() dx = min(dx, dis_w) @@ -209,8 +206,8 @@ def get_position_for_display(x, y, dx, dy, display): def position_window(window, width=None, height=None, parent=None): - """ Positions a window on the screen with a specified width and height so - that the window completely fits on the screen if possible. + """Positions a window on the screen with a specified width and height so + that the window completely fits on the screen if possible. """ dx, dy = window.GetSize() width = width or dx @@ -225,7 +222,7 @@ def position_window(window, width=None, height=None, parent=None): (SystemMetrics().screen_width - width) // 2, (SystemMetrics().screen_height - height) // 2, width, - height + height, ) return @@ -253,8 +250,7 @@ def position_window(window, width=None, height=None, parent=None): def top_level_window_for(control): - """ Returns the top-level window for a specified control. - """ + """Returns the top-level window for a specified control.""" parent = control.GetParent() while parent is not None: control = parent @@ -264,16 +260,14 @@ def top_level_window_for(control): def disconnect(control, *events): - """ Disconnects a wx event handle from its associated control. - """ + """Disconnects a wx event handle from its associated control.""" id = control.GetId() for event in events: control.Unbind(event, id=id) def disconnect_no_id(control, *events): - """ Disconnects a wx event handle from its associated control. - """ + """Disconnects a wx event handle from its associated control.""" for event in events: control.Unbind(event) @@ -286,8 +280,8 @@ def disconnect_no_id(control, *events): class TraitsUIPanel(wx.Panel): def __init__(self, parent, *args, **kw): - """ Creates a wx.Panel that correctly sets its background color to be - the same as its parents. + """Creates a wx.Panel that correctly sets its background color to be + the same as its parents. """ bg_color = kw.pop("bg_color", None) wx.Panel.__init__(self, parent, *args, **kw) @@ -302,15 +296,15 @@ def __init__(self, parent, *args, **kw): self.SetBackgroundColour(attr.colBg) def OnChildFocus(self, event): - """ If the ChildFocusEvent contains one of the Panel's direct children, - then we will Skip it to let it pass up the widget hierarchy. - - Otherwise, we consume the event to make sure it doesn't go any - farther. This works around a problem in wx 2.8.8.1 where each Panel - in a nested hierarchy generates many events that might consume too - many resources. We do, however, let one event bubble up to the top - so that it may inform a top-level ScrolledPanel that a descendant - has acquired focus. + """If the ChildFocusEvent contains one of the Panel's direct children, + then we will Skip it to let it pass up the widget hierarchy. + + Otherwise, we consume the event to make sure it doesn't go any + farther. This works around a problem in wx 2.8.8.1 where each Panel + in a nested hierarchy generates many events that might consume too + many resources. We do, however, let one event bubble up to the top + so that it may inform a top-level ScrolledPanel that a descendant + has acquired focus. """ if event.GetWindow() in self.GetChildren(): event.Skip() @@ -324,12 +318,13 @@ def Destroy(self): # 'ChildFocusOverride' class: # ------------------------------------------------------------------------- + class ChildFocusOverride(wx.EvtHandler): - """ Override the scroll-to-focus behaviour in wx 2.8.8's ScrolledWindow - C++ implementation for ScrolledPanel. + """Override the scroll-to-focus behaviour in wx 2.8.8's ScrolledWindow + C++ implementation for ScrolledPanel. - Instantiating this class with the ScrolledPanel will register the - new instance as the event handler for the panel. + Instantiating this class with the ScrolledPanel will register the + new instance as the event handler for the panel. """ def __init__(self, window): @@ -376,11 +371,12 @@ def __init__( def Destroy(self): from traitsui.wx.toolkit import _popEventHandlers + _popEventHandlers(self, ChildFocusOverride) super().Destroy() def OnChildFocus(self, event): - """ Handle a ChildFocusEvent. + """Handle a ChildFocusEvent. Returns a boolean so it can be used as a library call, too. """ @@ -389,9 +385,9 @@ def OnChildFocus(self, event): return True def ScrollChildIntoView(self, child): - """ Scrolls the panel such that the specified child window is in view. - This method overrides the original in the base class so that - nested subpanels are handled correctly. + """Scrolls the panel such that the specified child window is in view. + This method overrides the original in the base class so that + nested subpanels are handled correctly. """ if child is None: return @@ -472,8 +468,8 @@ def ScrollChildIntoView(self, child): def init_wx_handlers(control, object, prefix=""): - """ Initializes a standard set of wx event handlers for a specified control - and object using a specified prefix. + """Initializes a standard set of wx event handlers for a specified control + and object using a specified prefix. """ global handlers @@ -485,8 +481,7 @@ def init_wx_handlers(control, object, prefix=""): class GroupEditor(Editor): def __init__(self, **traits): - """ Initializes the object. - """ + """Initializes the object.""" self.trait_set(**traits) @@ -522,8 +517,7 @@ class PopupControl(HasPrivateTraits): # -- Public Methods ------------------------------------------------------- def __init__(self, **traits): - """ Initializes the object. - """ + """Initializes the object.""" super().__init__(**traits) style = wx.SIMPLE_BORDER @@ -537,31 +531,29 @@ def __init__(self, **traits): popup.Show() def create_control(self): - """ Creates the control. + """Creates the control. - Must be overridden by a subclass. + Must be overridden by a subclass. """ raise NotImplementedError def dispose(self): - """ Called when the popup is being closed to allow any custom clean-up. + """Called when the popup is being closed to allow any custom clean-up. - Can be overridden by a subclass. + Can be overridden by a subclass. """ pass # -- Event Handlers ------------------------------------------------------- def _value_changed(self, value): - """ Handles the 'value' being changed. - """ + """Handles the 'value' being changed.""" do_later(self._close_popup) # -- Private Methods ------------------------------------------------------ def _position_control(self): - """ Initializes the popup control's initial position and size. - """ + """Initializes the popup control's initial position and size.""" # Calculate the desired size of the popup control: px, cy = self.control.ClientToScreen(0, 0) cdx, cdy = self.control.GetSize() @@ -584,14 +576,12 @@ def _position_control(self): self.popup.SetSize(px, py, pdx, pdy) def _on_close_popup(self, event): - """ Closes the popup control when it is deactivated. - """ + """Closes the popup control when it is deactivated.""" if not event.GetActive(): self._close_popup() def _close_popup(self): - """ Closes the dialog. - """ + """Closes the dialog.""" self.popup.Unbind(wx.EVT_ACTIVATE) self.dispose() self.closed = True @@ -600,11 +590,11 @@ def _close_popup(self): class BufferDC(wx.MemoryDC): - """ An off-screen buffer class. + """An off-screen buffer class. - This class implements a off-screen output buffer. Data is meant to - be drawn in the buffer and then blitted directly to the output device - context. + This class implements a off-screen output buffer. Data is meant to + be drawn in the buffer and then blitted directly to the output device + context. """ def __init__(self, dc, width=None, height=None): @@ -625,8 +615,8 @@ def __init__(self, dc, width=None, height=None): self.SetFont(dc.GetFont()) def copy(self, x=0, y=0): - """ Performs the blit of the buffer contents to the specified device - context location. + """Performs the blit of the buffer contents to the specified device + context location. """ self.dc.Blit( x, y, self.bitmap.GetWidth(), self.bitmap.GetHeight(), self, 0, 0 @@ -634,9 +624,9 @@ def copy(self, x=0, y=0): class Slider(wx.Slider): - """ This is a 'fixed' version of the wx.Slider control which does not - erase its background, which can cause a lot of update flicker and is - completely unnecessary. + """This is a 'fixed' version of the wx.Slider control which does not + erase its background, which can cause a lot of update flicker and is + completely unnecessary. """ def __init__(self, *args, **kw): diff --git a/traitsui/wx/history_control.py b/traitsui/wx/history_control.py index 93824b517..969312955 100644 --- a/traitsui/wx/history_control.py +++ b/traitsui/wx/history_control.py @@ -49,8 +49,7 @@ class HistoryControl(HasPrivateTraits): # -- Public Methods ------------------------------------------------------- def create_control(self, parent): - """ Creates the control. - """ + """Creates the control.""" self.control = control = wx.ComboBox( parent, -1, @@ -62,15 +61,18 @@ def create_control(self, parent): ) parent.Bind(wx.EVT_COMBOBOX, self._update_value, id=control.GetId()) control.Bind(wx.EVT_KILL_FOCUS, self._kill_focus) - parent.Bind(wx.EVT_TEXT_ENTER, self._update_text_value, id=control.GetId()) + parent.Bind( + wx.EVT_TEXT_ENTER, self._update_text_value, id=control.GetId() + ) if self.auto_set: - parent.Bind(wx.EVT_TEXT, self._update_value_only, id=control.GetId()) + parent.Bind( + wx.EVT_TEXT, self._update_value_only, id=control.GetId() + ) return control def dispose(self): - """ Disposes of the control at the end of its life cycle. - """ + """Disposes of the control at the end of its life cycle.""" control, self.control = self.control, None parent = control.GetParent() parent.Bind(wx.EVT_COMBOBOX, None, id=control.GetId()) @@ -78,15 +80,13 @@ def dispose(self): control.Unbind(wx.EVT_KILL_FOCUS) def set_value(self, value): - """ Sets the specified value and adds it to the history. - """ + """Sets the specified value and adds it to the history.""" self._update(value) # -- Traits Event Handlers ------------------------------------------------ def _value_changed(self, value): - """ Handles the 'value' trait being changed. - """ + """Handles the 'value' trait being changed.""" if not self._no_update: control = self.control if control is not None: @@ -94,8 +94,7 @@ def _value_changed(self, value): self._restore = False def _history_changed(self): - """ Handles the 'history' being changed. - """ + """Handles the 'history' being changed.""" if not self._no_update: if self._first_time is None: self._first_time = False @@ -105,8 +104,7 @@ def _history_changed(self): self._load_history(select=False) def _error_changed(self, error): - """ Handles the 'error' trait being changed. - """ + """Handles the 'error' trait being changed.""" if error: self.control.SetBackgroundColour(ErrorColor) else: @@ -117,36 +115,33 @@ def _error_changed(self, error): # -- Wx Event Handlers ---------------------------------------------------- def _update_value(self, event): - """ Handles the user selecting something from the drop-down list of the - combobox. + """Handles the user selecting something from the drop-down list of the + combobox. """ self._update(event.GetString()) def _update_value_only(self, event): - """ Handles the user typing into the text field in 'auto_set' mode. - """ + """Handles the user typing into the text field in 'auto_set' mode.""" self._no_update = True self.value = event.GetString() self._no_update = False def _update_text_value(self, event, select=True): - """ Handles the user typing something into the text field of the - combobox. + """Handles the user typing something into the text field of the + combobox. """ if not self._no_update: self._update(self.control.GetValue(), select) def _kill_focus(self, event): - """ Handles the combobox losing focus. - """ + """Handles the combobox losing focus.""" self._update_text_value(event, False) event.Skip() # -- Private Methods ------------------------------------------------------ def _update(self, value, select=True): - """ Updates the value and history list based on a specified value. - """ + """Updates the value and history list based on a specified value.""" self._no_update = True if value.strip() != "": @@ -163,8 +158,7 @@ def _update(self, value, select=True): self._no_update = False def _load_history(self, restore=None, select=True): - """ Loads the current history list into the control. - """ + """Loads the current history list into the control.""" control = self.control control.Freeze() @@ -179,8 +173,7 @@ def _load_history(self, restore=None, select=True): do_later(self._thaw_value, restore, select) def _thaw_value(self, restore, select): - """ Restores the value of the combobox control. - """ + """Restores the value of the combobox control.""" control = self.control if control is not None: if self._restore: diff --git a/traitsui/wx/history_editor.py b/traitsui/wx/history_editor.py index f57352375..6b977dc95 100644 --- a/traitsui/wx/history_editor.py +++ b/traitsui/wx/history_editor.py @@ -27,9 +27,9 @@ class _HistoryEditor(Editor): - """ Simple style text editor, which displays a text field and maintains a - history of previously entered values, the maximum number of which is - specified by the 'entries' trait of the HistoryEditor factory. + """Simple style text editor, which displays a text field and maintains a + history of previously entered values, the maximum number of which is + specified by the 'entries' trait of the HistoryEditor factory. """ # ------------------------------------------------------------------------- @@ -40,8 +40,8 @@ class _HistoryEditor(Editor): history = Any() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.history = history = HistoryControl( value=self.value, @@ -53,8 +53,7 @@ def init(self, parent): self.set_tooltip() def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" self.history.dispose() self.history = None @@ -62,8 +61,7 @@ def dispose(self): @observe("history:value") def _value_changed(self, event): - """ Handles the history object's 'value' trait being changed. - """ + """Handles the history object's 'value' trait being changed.""" if not self._dont_update: history = self.history try: @@ -76,8 +74,8 @@ def _value_changed(self, event): do_later(self.trait_set, _dont_update=False) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ if not self._dont_update: self._dont_update = True @@ -86,21 +84,19 @@ def update_editor(self): self._dont_update = False def error(self, excp): - """ Handles an error that occurs while setting the object's trait value. - """ + """Handles an error that occurs while setting the object's trait value.""" pass # -- UI preference save/restore interface --------------------------------- def restore_prefs(self, prefs): - """ Restores any saved user preference information associated with the - editor. + """Restores any saved user preference information associated with the + editor. """ self.history.history = prefs.get("history", [])[: self.factory.entries] def save_prefs(self): - """ Returns any user preference information associated with the editor. - """ + """Returns any user preference information associated with the editor.""" # If the view closed successfully, try to update the history with the # current value: if self.ui.result: diff --git a/traitsui/wx/html_editor.py b/traitsui/wx/html_editor.py index c66ec312d..4dca1a661 100644 --- a/traitsui/wx/html_editor.py +++ b/traitsui/wx/html_editor.py @@ -25,8 +25,8 @@ class URLResolvingHtmlWindow(wh.HtmlWindow): - """ Overrides OnOpeningURL method of HtmlWindow to append the base URL - local links. + """Overrides OnOpeningURL method of HtmlWindow to append the base URL + local links. """ def __init__(self, parent, open_externally, base_url): @@ -35,8 +35,7 @@ def __init__(self, parent, open_externally, base_url): self.base_url = base_url def OnLinkClicked(self, link_info): - """ Handle the base url and opening in a new browser window for links. - """ + """Handle the base url and opening in a new browser window for links.""" if self.open_externally: url = link_info.GetHref() if self.base_url and not url.startswith(("http://", "https://")): @@ -46,10 +45,10 @@ def OnLinkClicked(self, link_info): webbrowser.open_new(url) def OnOpeningURL(self, url_type, url): - """ According to the documentation, this method is supposed to be called - for both images and link clicks, but it appears to only be called - for image loading, hence the base url handling code in - OnLinkClicked. + """According to the documentation, this method is supposed to be called + for both images and link clicks, but it appears to only be called + for image loading, hence the base url handling code in + OnLinkClicked. """ if ( self.base_url @@ -62,8 +61,7 @@ def OnOpeningURL(self, url_type, url): class SimpleEditor(Editor): - """ Simple style of editor for HTML, which displays interpreted HTML. - """ + """Simple style of editor for HTML, which displays interpreted HTML.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -76,8 +74,8 @@ class SimpleEditor(Editor): base_url = Str() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = URLResolvingHtmlWindow( parent, self.factory.open_externally, self.base_url @@ -88,8 +86,8 @@ def init(self, parent): self.sync_value(self.factory.base_url_name, "base_url", "from") def update_editor(self): - """ Updates the editor when the object trait changes external to the - editor. + """Updates the editor when the object trait changes external to the + editor. """ text = self.str_value if self.factory.format_text: diff --git a/traitsui/wx/image_control.py b/traitsui/wx/image_control.py index 65c197baa..07791bd9c 100644 --- a/traitsui/wx/image_control.py +++ b/traitsui/wx/image_control.py @@ -17,8 +17,8 @@ class ImageControl(wx.Window): - """ A wxPython control that displays an image, which can be selected or - unselected by mouse clicks. + """A wxPython control that displays an image, which can be selected or + unselected by mouse clicks. """ #: Pens used to draw the 'selection' marker: @@ -33,8 +33,7 @@ class ImageControl(wx.Window): def __init__( self, parent, bitmap, selected=None, handler=None, padding=10 ): - """ Initializes the object. - """ + """Initializes the object.""" wx.Window.__init__( self, parent, @@ -59,8 +58,7 @@ def __init__( self.Bind(wx.EVT_LEAVE_WINDOW, self._on_leave) def Selected(self, selected=None): - """ Gets or sets the selection state of the image. - """ + """Gets or sets the selection state of the image.""" if selected is not None: selected = selected != 0 if selected != self._selected: @@ -79,8 +77,7 @@ def Selected(self, selected=None): return self._selected def Bitmap(self, bitmap=None): - """ Gets or sets the bitmap image. - """ + """Gets or sets the bitmap image.""" if bitmap is not None: if bitmap != self._bitmap: self._bitmap = bitmap @@ -89,8 +86,7 @@ def Bitmap(self, bitmap=None): return self._bitmap def Handler(self, handler=None): - """ Gets or sets the click handler. - """ + """Gets or sets the click handler.""" if handler is not None: if handler != self._handler: self._handler = handler @@ -99,30 +95,26 @@ def Handler(self, handler=None): return self._handler def _on_enter(self, event=None): - """ Handles the mouse entering the control. - """ + """Handles the mouse entering the control.""" if self._selected is not None: self._mouse_over = True self.Refresh() def _on_leave(self, event=None): - """ Handles the mouse leaving the control. - """ + """Handles the mouse leaving the control.""" if self._mouse_over: self._mouse_over = False self.Refresh() def _on_left_down(self, event=None): - """ Handles the user pressing the mouse button. - """ + """Handles the user pressing the mouse button.""" if self._selected is not None: self.CaptureMouse() self._button_down = True self.Refresh() def _on_left_up(self, event=None): - """ Handles the user clicking the control. - """ + """Handles the user clicking the control.""" need_refresh = self._button_down if need_refresh: self.ReleaseMouse() @@ -145,8 +137,7 @@ def _on_left_up(self, event=None): self.Refresh() def _on_paint(self, event=None): - """ Handles the control being re-painted. - """ + """Handles the control being re-painted.""" wdc = wx.PaintDC(self) wdx, wdy = self.GetClientSize() bitmap = self._bitmap diff --git a/traitsui/wx/image_editor.py b/traitsui/wx/image_editor.py index 55f28023f..74afbae41 100644 --- a/traitsui/wx/image_editor.py +++ b/traitsui/wx/image_editor.py @@ -31,12 +31,11 @@ class _ImageEditor(Editor): - """ Traits UI 'display only' image editor. - """ + """Traits UI 'display only' image editor.""" def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ image = self.factory.image if image is None: @@ -47,8 +46,8 @@ def init(self, parent): self.set_tooltip() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ if self.factory.image is None: value = self.value diff --git a/traitsui/wx/image_enum_editor.py b/traitsui/wx/image_enum_editor.py index a22480e88..d9f269570 100644 --- a/traitsui/wx/image_enum_editor.py +++ b/traitsui/wx/image_enum_editor.py @@ -34,13 +34,13 @@ class ReadonlyEditor(Editor): - """ Read-only style of image enumeration editor, which displays a single + """Read-only style of image enumeration editor, which displays a single ImageControl, representing the object trait's value. """ def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = ImageControl( parent, @@ -53,8 +53,8 @@ def init(self, parent): ) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ self.control.Bitmap( bitmap_cache( @@ -67,15 +67,15 @@ def update_editor(self): class SimpleEditor(ReadonlyEditor): - """ Simple style of image enumeration editor, which displays an + """Simple style of image enumeration editor, which displays an ImageControl, representing the object trait's value. Clicking an image displays a dialog box for selecting an image corresponding to a different value. """ def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ super().init(parent) self.control.Selected(True) @@ -83,14 +83,14 @@ def init(self, parent): self.set_tooltip() def popup_editor(self, control): - """ Handles the user clicking the ImageControl to display the pop-up - dialog. + """Handles the user clicking the ImageControl to display the pop-up + dialog. """ ImageEnumDialog(self) class CustomEditor(BaseEnumEditor): - """ Custom style of image enumeration editor, which displays a grid of + """Custom style of image enumeration editor, which displays a grid of ImageControls. The user can click an image to select the corresponding value. """ @@ -102,8 +102,8 @@ class CustomEditor(BaseEnumEditor): update_handler = Any # Callback to call when any button clicked def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ super().init(parent) @@ -119,8 +119,7 @@ def rebuild_editor(self): self._create_image_grid() def _create_image_grid(self): - """ Populates a specified window with a grid of image buttons. - """ + """Populates a specified window with a grid of image buttons.""" panel = self.control # Create the main sizer: @@ -152,15 +151,14 @@ def _create_image_grid(self): panel.SetSizerAndFit(sizer) def update_object(self, control): - """ Handles the user clicking on an ImageControl to set an object value. - """ + """Handles the user clicking on an ImageControl to set an object value.""" self.value = control.value if self.update_handler is not None: self.update_handler() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ value = self.value for control in self.control.GetChildren(): @@ -168,12 +166,10 @@ def update_editor(self): class ImageEnumDialog(wx.Frame): - """ Dialog box for selecting an ImageControl - """ + """Dialog box for selecting an ImageControl""" def __init__(self, editor): - """ Initializes the object. - """ + """Initializes the object.""" wx.Frame.__init__(self, editor.control, -1, "", style=wx.SIMPLE_BORDER) self.SetBackgroundColour(WindowColor) self.Bind(wx.EVT_ACTIVATE, self._on_close_dialog) @@ -201,14 +197,12 @@ def __init__(self, editor): self.Show() def _on_close_dialog(self, event): - """ Closes the dialog. - """ + """Closes the dialog.""" if not event.GetActive(): self._close_dialog() def _close_dialog(self): - """ Closes the dialog. - """ + """Closes the dialog.""" if not self._closed: self._closed = True self.Destroy() diff --git a/traitsui/wx/image_slice.py b/traitsui/wx/image_slice.py index 270dc6df6..634c2c4b4 100644 --- a/traitsui/wx/image_slice.py +++ b/traitsui/wx/image_slice.py @@ -37,8 +37,8 @@ def paint_parent(dc, window): - """ Recursively paint the parent's background if they have an associated - image slice. + """Recursively paint the parent's background if they have an associated + image slice. """ parent = window.GetParent() slice = getattr(parent, "_image_slice", None) @@ -127,8 +127,8 @@ class ImageSlice(HasPrivateTraits): # -- Public Methods ------------------------------------------------------- def fill(self, dc, x, y, dx, dy, transparent=False): - """ 'Stretch fill' the specified region of a device context with the - sliced image. + """'Stretch fill' the specified region of a device context with the + sliced image. """ # Create the source image dc: idc = wx.MemoryDC() @@ -233,8 +233,7 @@ def fill(self, dc, x, y, dx, dy, transparent=False): # -- Event Handlers ------------------------------------------------------- def _image_changed(self, image): - """ Handles the 'image' trait being changed. - """ + """Handles the 'image' trait being changed.""" # Save the original bitmap as the transparent version: self.transparent_bitmap = ( bitmap @@ -263,8 +262,7 @@ def _image_changed(self, image): # -- Private Methods ------------------------------------------------------ def _analyze_bitmap(self): - """ Analyzes the bitmap. - """ + """Analyzes the bitmap.""" # Get the image data: threshold = self.threshold bitmap = self.opaque_bitmap @@ -358,8 +356,8 @@ def _analyze_bitmap(self): ) def _fill(self, idc, ix, iy, idx, idy, dc, x, y, dx, dy): - """ Performs a stretch fill of a region of an image into a region of a - window device context. + """Performs a stretch fill of a region of an image into a region of a + window device context. """ last_x, last_y = x + dx, y + dy while y < last_y: @@ -372,8 +370,8 @@ def _fill(self, idc, ix, iy, idx, idy, dc, x, y, dx, dy): y += ddy def _calculate_dxy(self, d, matches): - """ Calculate the size of all image slices for a specified set of - matches. + """Calculate the size of all image slices for a specified set of + matches. """ if len(matches) == 1: d1, d2 = matches[0] @@ -386,9 +384,9 @@ def _calculate_dxy(self, d, matches): return (d - d2 - d4, [d1, d2, d3 - d1 - d2, d4, d - d3 - d4]) def _find_best_borders(self, data): - """ Find the best set of image slice border sizes (e.g. for images with - rounded corners, there should exist a better set of borders than - the ones computed by the image slice algorithm. + """Find the best set of image slice border sizes (e.g. for images with + rounded corners, there should exist a better set of borders than + the ones computed by the image slice algorithm. """ # Make sure the image size is worth bothering about: dx, dy = self.dx, self.dy @@ -489,8 +487,8 @@ def _find_best_borders(self, data): self.xbottom = min(self.bottom, dy - bottom - 1) def _find_best_color(self, data, x, y): - """ Find the best contrasting text color for a specified pixel - coordinate. + """Find the best contrasting text color for a specified pixel + coordinate. """ r, g, b = data[y, x] h, l, s = rgb_to_hls(r / 255.0, g / 255.0, b / 255.0) @@ -501,8 +499,8 @@ def _find_best_color(self, data, x, y): return text_color def _is_equal(self, data, x0, y0, x1, y1, dx, dy): - """ Determines if two identically sized regions of an image array are - 'the same' (i.e. within some slight color variance of each other). + """Determines if two identically sized regions of an image array are + 'the same' (i.e. within some slight color variance of each other). """ return ( abs( @@ -521,8 +519,7 @@ def _is_equal(self, data, x0, y0, x1, y1, dx, dy): def image_slice_for(image): - """ Returns a (possibly cached) ImageSlice. - """ + """Returns a (possibly cached) ImageSlice.""" global image_slice_cache result = image_slice_cache.get(image) diff --git a/traitsui/wx/instance_editor.py b/traitsui/wx/instance_editor.py index e223f5a03..cf371a95f 100644 --- a/traitsui/wx/instance_editor.py +++ b/traitsui/wx/instance_editor.py @@ -41,7 +41,7 @@ class CustomEditor(Editor): - """ Custom style of editor for instances. If selection among instances is + """Custom style of editor for instances. If selection among instances is allowed, the editor displays a combo box listing instances that can be selected. If the current instance is editable, the editor displays a panel containing trait editors for all the instance's traits. @@ -71,8 +71,8 @@ class CustomEditor(Editor): view = AView def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory if factory.name != "": @@ -153,7 +153,9 @@ def init(self, parent): self._choice = choice = wx.Choice( parent, -1, wx.Point(0, 0), wx.Size(-1, -1), [] ) - choice.Bind(wx.EVT_CHOICE, self.update_object, id=choice.GetId()) + choice.Bind( + wx.EVT_CHOICE, self.update_object, id=choice.GetId() + ) self.control = self._choice else: sizer = wx.BoxSizer(orientation) @@ -167,8 +169,7 @@ def init(self, parent): self.sync_value(factory.view_name, "view", "from") def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" # Make sure we aren't hanging on to any object refs: self._object_cache = None @@ -198,14 +199,12 @@ def dispose(self): super().dispose() def create_editor(self, parent, sizer): - """ Creates the editor control. - """ + """Creates the editor control.""" self._panel = TraitsUIPanel(parent, -1) sizer.Add(self._panel, 1, wx.EXPAND) def _get_items(self): - """ Gets the current list of InstanceChoiceItem items. - """ + """Gets the current list of InstanceChoiceItem items.""" if self._items is not None: return self._items @@ -227,8 +226,7 @@ def _get_items(self): return items def rebuild_items(self): - """ Rebuilds the object selector list. - """ + """Rebuilds the object selector list.""" # Clear the current cached values: self._items = None @@ -255,8 +253,7 @@ def rebuild_items(self): pass def item_for(self, object): - """ Returns the InstanceChoiceItem for a specified object. - """ + """Returns the InstanceChoiceItem for a specified object.""" for item in self.items: if item.is_compatible(object): return item @@ -264,8 +261,7 @@ def item_for(self, object): return None def view_for(self, object, item): - """ Returns the view to use for a specified object. - """ + """Returns the view to use for a specified object.""" view = "" if item is not None: view = item.get_view() @@ -278,8 +274,7 @@ def view_for(self, object, item): ) def update_object(self, event): - """ Handles the user selecting a new value from the combo box. - """ + """Handles the user selecting a new value from the combo box.""" name = event.GetString() for item in self.items: if name == item.get_name(): @@ -299,8 +294,8 @@ def update_object(self, event): break def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ # Attach the current object value to the control (for use by # DockWindowFeature): @@ -330,7 +325,7 @@ def update_editor(self): choice.SetValue(name) def resynch_editor(self): - """ Resynchronizes the contents of the editor when the object trait + """Resynchronizes the contents of the editor when the object trait changes externally to the editor. """ panel = self._panel @@ -411,28 +406,25 @@ def resynch_editor(self): parent.SendSizeEvent() def error(self, excp): - """ Handles an error that occurs while setting the object's trait value. - """ + """Handles an error that occurs while setting the object's trait value.""" pass def get_error_control(self): - """ Returns the editor's control for indicating error status. - """ + """Returns the editor's control for indicating error status.""" return self._choice or self.control # -- UI preference save/restore interface --------------------------------- def restore_prefs(self, prefs): - """ Restores any saved user preference information associated with the - editor. + """Restores any saved user preference information associated with the + editor. """ ui = self._ui if (ui is not None) and (prefs.get("id") == ui.id): ui.set_prefs(prefs.get("prefs")) def save_prefs(self): - """ Returns any user preference information associated with the editor. - """ + """Returns any user preference information associated with the editor.""" ui = self._ui if (ui is not None) and (ui.id != ""): return {"id": ui.id, "prefs": ui.get_prefs()} @@ -442,8 +434,7 @@ def save_prefs(self): # -- Drag and drop event handlers ----------------------------------------- def wx_dropped_on(self, x, y, data, drag_result): - """ Handles a Python object being dropped on the tree. - """ + """Handles a Python object being dropped on the tree.""" for item in self.items: if item.is_droppable() and item.is_compatible(data): if self._object_cache is not None: @@ -454,8 +445,7 @@ def wx_dropped_on(self, x, y, data, drag_result): return wx.DragNone def wx_drag_over(self, x, y, data, drag_result): - """ Handles a Python object being dragged over the tree. - """ + """Handles a Python object being dragged over the tree.""" for item in self.items: if item.is_droppable() and item.is_compatible(data): return drag_result @@ -469,7 +459,7 @@ def _view_changed(self, view): class SimpleEditor(CustomEditor): - """ Simple style of editor for instances, which displays a button. Clicking + """Simple style of editor for instances, which displays a button. Clicking the button displays a dialog box in which the instance can be edited. """ @@ -481,15 +471,13 @@ class SimpleEditor(CustomEditor): _dialog_ui = Instance("traitsui.ui.UI") def create_editor(self, parent, sizer): - """ Creates the editor control (a button). - """ + """Creates the editor control (a button).""" self._button = button = wx.Button(parent, -1, "") sizer.Add(button, 1, wx.EXPAND | wx.LEFT, 5) button.Bind(wx.EVT_BUTTON, self.edit_instance, id=button.GetId()) def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" button = self._button if button is not None: button.Bind(wx.EVT_BUTTON, None, id=button.GetId()) @@ -501,8 +489,8 @@ def dispose(self): super().dispose() def edit_instance(self, event): - """ Edit the contents of the object trait when the user clicks the - button. + """Edit the contents of the object trait when the user clicks the + button. """ # Create the user interface: factory = self.factory @@ -526,8 +514,8 @@ def edit_instance(self, event): self._dialog_ui = ui def resynch_editor(self): - """ Resynchronizes the contents of the editor when the object trait - changes externally to the editor. + """Resynchronizes the contents of the editor when the object trait + changes externally to the editor. """ button = self._button if button is not None: diff --git a/traitsui/wx/key_binding_editor.py b/traitsui/wx/key_binding_editor.py index 97d27f707..bc9adf344 100644 --- a/traitsui/wx/key_binding_editor.py +++ b/traitsui/wx/key_binding_editor.py @@ -30,8 +30,7 @@ class KeyBindingEditor(Editor): - """ An editor for modifying bindings of keys to controls. - """ + """An editor for modifying bindings of keys to controls.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -47,14 +46,13 @@ class KeyBindingEditor(Editor): clear = Event() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = KeyBindingCtrl(self, parent, size=wx.Size(160, 19)) def update_object(self, event): - """ Handles the user entering input data in the edit control. - """ + """Handles the user entering input data in the edit control.""" try: self.value = value = key_event_to_name(event) self._binding.text = value @@ -62,21 +60,19 @@ def update_object(self, event): pass def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ self.control.Refresh() def update_focus(self, has_focus): - """ Updates the current focus setting of the control. - """ + """Updates the current focus setting of the control.""" if has_focus: self._binding.border_size = 1 self.object.owner.focus_owner = self._binding def _key_changed(self, event): - """ Handles a keyboard event. - """ + """Handles a keyboard event.""" binding = self.object key_name = key_event_to_name(event) cur_binding = binding.owner.key_binding_for(binding, key_name) @@ -96,14 +92,12 @@ def _key_changed(self, event): self.value = key_name def _clear_changed(self): - """ Handles a clear field event. - """ + """Handles a clear field event.""" self.value = "" class KeyBindingCtrl(wx.Window): - """ wxPython control for editing key bindings. - """ + """wxPython control for editing key bindings.""" def __init__( self, @@ -141,16 +135,14 @@ def __init__( self.Bind(wx.EVT_CHAR, self._on_char) def _on_char(self, event): - """ Handle keyboard keys being pressed. - """ + """Handle keyboard keys being pressed.""" self.editor.key = event def _on_erase_background(self, event): pass def _paint(self, event): - """ Updates the screen. - """ + """Updates the screen.""" wdc = wx.PaintDC(self) dx, dy = self.GetSize() if self.editor.has_focus: @@ -164,23 +156,19 @@ def _paint(self, event): wdc.DrawText(self.editor.str_value, 5, 3) def _set_focus(self, event): - """ Sets the keyboard focus to this window. - """ + """Sets the keyboard focus to this window.""" self.SetFocus() def _get_focus(self, event): - """ Handles getting the focus. - """ + """Handles getting the focus.""" self.editor.has_focus = True self.Refresh() def _lose_focus(self, event): - """ Handles losing the focus. - """ + """Handles losing the focus.""" self.editor.has_focus = False self.Refresh() def _clear_contents(self, event): - """ Handles the user double clicking the control to clear its contents. - """ + """Handles the user double clicking the control to clear its contents.""" self.editor.clear = True diff --git a/traitsui/wx/key_event_to_name.py b/traitsui/wx/key_event_to_name.py index 528464121..46f3416b6 100644 --- a/traitsui/wx/key_event_to_name.py +++ b/traitsui/wx/key_event_to_name.py @@ -97,8 +97,7 @@ def key_event_to_name(event): - """ Converts a keystroke event into a corresponding key name. - """ + """Converts a keystroke event into a corresponding key name.""" key_code = event.GetKeyCode() if event.ControlDown() and (1 <= key_code <= 26): key = chr(key_code + 96) diff --git a/traitsui/wx/list_editor.py b/traitsui/wx/list_editor.py index 04491c19f..0c02940bb 100644 --- a/traitsui/wx/list_editor.py +++ b/traitsui/wx/list_editor.py @@ -17,7 +17,13 @@ import wx.lib.scrolledpanel as wxsp from traits.api import ( - Any, Bool, cached_property, Instance, Property, Str, TraitError + Any, + Bool, + cached_property, + Instance, + Property, + Str, + TraitError, ) from traits.trait_base import user_name_for, xgetattr @@ -40,14 +46,13 @@ from .image_control import ImageControl - # ------------------------------------------------------------------------- # 'SimpleEditor' class: # ------------------------------------------------------------------------- class SimpleEditor(Editor): - """ Simple style of editor for lists, which displays a scrolling list box + """Simple style of editor for lists, which displays a scrolling list box with only one item visible at a time. A icon next to the list box displays a menu of operations on the list. """ @@ -101,8 +106,8 @@ class SimpleEditor(Editor): """ def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ # Initialize the trait handler to use: trait_handler = self.factory.trait_handler @@ -133,8 +138,7 @@ def init(self, parent): self.set_tooltip() def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" extended_name = self.extended_name.replace(".", ":") self.context_object.on_trait_change( self.update_editor_item, extended_name + "_items?", remove=True @@ -144,8 +148,8 @@ def dispose(self): super().dispose() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ # Disconnect the editor from any control about to be destroyed: self._dispose_items() @@ -257,7 +261,7 @@ def update_editor(self): list_pane.GetParent().Layout() def update_editor_item(self, obj, name, event): - """ Updates the editor when an item in the object trait changes + """Updates the editor when an item in the object trait changes externally to the editor. """ # If this is not a simple, single item update, rebuild entire editor: @@ -274,8 +278,7 @@ def update_editor_item(self, obj, name, event): break def empty_list(self): - """ Creates an empty list entry (so the user can add a new item). - """ + """Creates an empty list entry (so the user can add a new item).""" control = ImageControl( self.control, self.bitmap, -1, self.popup_empty_menu ) @@ -286,8 +289,8 @@ def empty_list(self): self.reload_sizer([(control, pcontrol)]) def reload_sizer(self, controls, extra=0): - """ Reloads the layout from the specified list of ( button, proxy ) - pairs. + """Reloads the layout from the specified list of ( button, proxy ) + pairs. """ sizer = self.control.GetSizer() for i in range(2 * len(controls) + extra): @@ -302,22 +305,19 @@ def reload_sizer(self, controls, extra=0): self.control.SetVirtualSize(sizer.GetMinSize()) def get_info(self): - """ Returns the associated object list and current item index. - """ + """Returns the associated object list and current item index.""" proxy = self._cur_control.proxy return (proxy.list, proxy.index) def popup_empty_menu(self, control): - """ Displays the empty list editor popup menu. - """ + """Displays the empty list editor popup menu.""" self._cur_control = control menu = MakeMenu(self.empty_list_menu, self, True, self.control).menu self.control.PopupMenu(menu, control.GetPosition()) menu.Destroy() def popup_menu(self, control): - """ Displays the list editor popup menu. - """ + """Displays the list editor popup menu.""" self._cur_control = control # Makes sure that any text that was entered get's added (Pressure # #145): @@ -340,15 +340,14 @@ def popup_menu(self, control): menu.Destroy() def add_item(self, offset): - """ Adds a new value at the specified list index. - """ + """Adds a new value at the specified list index.""" list, index = self.get_info() index += offset item_trait = self._trait_handler.item_trait if self.factory.item_factory: value = self.factory.item_factory( *self.factory.item_factory_args, - **self.factory.item_factory_kwargs + **self.factory.item_factory_kwargs, ) else: value = item_trait.default_value_for(self.object, self.name) @@ -358,35 +357,31 @@ def add_item(self, offset): # traits will still give an error message, but we don't want to crash except TraitError: from traitsui.api import raise_to_debug + raise_to_debug() wx.CallAfter(self.update_editor) def add_before(self): - """ Inserts a new item before the current item. - """ + """Inserts a new item before the current item.""" self.add_item(0) def add_after(self): - """ Inserts a new item after the current item. - """ + """Inserts a new item after the current item.""" self.add_item(1) def add_empty(self): - """ Adds a new item when the list is empty. - """ + """Adds a new item when the list is empty.""" list, index = self.get_info() self.add_item(0) def delete_item(self): - """ Delete the current item. - """ + """Delete the current item.""" list, index = self.get_info() self.value = list[:index] + list[index + 1 :] wx.CallAfter(self.update_editor) def move_up(self): - """ Move the current item up one in the list. - """ + """Move the current item up one in the list.""" list, index = self.get_info() self.value = ( list[: index - 1] @@ -396,8 +391,7 @@ def move_up(self): wx.CallAfter(self.update_editor) def move_down(self): - """ Moves the current item down one in the list. - """ + """Moves the current item down one in the list.""" list, index = self.get_info() self.value = ( list[:index] + [list[index + 1], list[index]] + list[index + 2 :] @@ -405,15 +399,13 @@ def move_down(self): wx.CallAfter(self.update_editor) def move_top(self): - """ Moves the current item to the top of the list. - """ + """Moves the current item to the top of the list.""" list, index = self.get_info() self.value = [list[index]] + list[:index] + list[index + 1 :] wx.CallAfter(self.update_editor) def move_bottom(self): - """ Moves the current item to the bottom of the list. - """ + """Moves the current item to the bottom of the list.""" list, index = self.get_info() self.value = list[:index] + list[index + 1 :] + [list[index]] wx.CallAfter(self.update_editor) @@ -427,8 +419,7 @@ def _get_bitmap(self): # -- Private Methods ------------------------------------------------------ def _dispose_items(self): - """ Disposes of each current list item. - """ + """Disposes of each current list item.""" for control in self.control.GetChildren(): editor = getattr(control, "_editor", None) if editor is not None: @@ -441,17 +432,16 @@ def _dispose_items(self): # -- Trait initializers ---------------------------------------------------- def _kind_default(self): - """ Returns a default value for the 'kind' trait. - """ + """Returns a default value for the 'kind' trait.""" return self.factory.style + "_editor" def _mutable_default(self): - """ Trait handler to set the mutable trait from the factory. """ + """Trait handler to set the mutable trait from the factory.""" return self.factory.mutable class CustomEditor(SimpleEditor): - """ Custom style of editor for lists, which displays the items as a series + """Custom style of editor for lists, which displays the items as a series of text fields. If the list is editable, an icon next to each item displays a menu of operations on the list. """ @@ -492,8 +482,8 @@ class ReadonlyEditor(CustomEditor): class NotebookEditor(Editor): - """ An editor for lists that displays the list as a "notebook" of tabbed - pages. + """An editor for lists that displays the list as a "notebook" of tabbed + pages. """ # ------------------------------------------------------------------------- @@ -507,8 +497,8 @@ class NotebookEditor(Editor): selected = Any() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self._uis = [] @@ -533,8 +523,8 @@ def init(self, parent): self.sync_value(self.factory.selected, "selected") def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ # Make sure the DockWindow is in a correct state: self._sizer.Reset(self.control) @@ -558,8 +548,7 @@ def update_editor(self): self.update_layout() def update_editor_item(self, event): - """ Handles an update to some subset of the trait's list. - """ + """Handles an update to some subset of the trait's list.""" # Make sure the DockWindow is in a correct state: self._sizer.Reset(self.control) @@ -594,8 +583,7 @@ def update_editor_item(self, event): self.update_layout() def close_all(self): - """ Closes all currently open notebook pages. - """ + """Closes all currently open notebook pages.""" page_name = self.factory.page_name[1:] for dock_control, object, view_object, monitoring in self._uis: if monitoring: @@ -609,8 +597,7 @@ def close_all(self): self._pages = {} def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" self.context_object.on_trait_change( self.update_editor_item, self.name + "_items?", remove=True ) @@ -619,8 +606,7 @@ def dispose(self): super().dispose() def add_controls(self, controls): - """ Adds a group of new DockControls to the view. - """ + """Adds a group of new DockControls to the view.""" if len(controls) > 0: section = self.control.GetSizer().GetContents() if (len(section.contents) == 0) or ( @@ -635,14 +621,12 @@ def add_controls(self, controls): self._selected_changed(None, self.selected) def update_layout(self): - """ Updates the layout of the DockWindow. - """ + """Updates the layout of the DockWindow.""" self.control.Layout() self.control.Refresh() def update_page_name(self): - """ Handles the trait defining a particular page's name being changed. - """ + """Handles the trait defining a particular page's name being changed.""" changed = False for i, value in enumerate(self._uis): dock_control, user_object, view_object, monitoring = value @@ -670,8 +654,7 @@ def update_page_name(self): self.update_layout() def _create_page(self, object): - """ Creates a DockControl for a specified object. - """ + """Creates a DockControl for a specified object.""" # Create the view for the object: view_object = object factory = self.factory @@ -739,7 +722,7 @@ def _create_page(self, object): # the editor is changed. # ------------------------------------------------------------------------- def _selected_changed(self, old, new): - """ Activates the corresponding dock window when the 'selected' trait + """Activates the corresponding dock window when the 'selected' trait of the editor is changed. """ for i, value in enumerate(self._uis): @@ -759,13 +742,11 @@ class DockableListElement(DockableViewElement): editor = Instance(NotebookEditor) def dockable_close(self, dock_control, force): - """ Returns whether it is OK to close the control. - """ + """Returns whether it is OK to close the control.""" return self.close_dock_control(dock_control, force) def close_dock_control(self, dock_control, abort): - """ Closes a DockControl. - """ + """Closes a DockControl.""" if abort: return super().close_dock_control(dock_control, False) @@ -777,7 +758,7 @@ def close_dock_control(self, dock_control, abort): return False def dockable_tab_activated(self, dock_control, activated): - """ Handles a notebook tab being activated or deactivated. + """Handles a notebook tab being activated or deactivated. Sets the value of the editor's selected trait to the activated dock_control's object. diff --git a/traitsui/wx/list_str_editor.py b/traitsui/wx/list_str_editor.py index d735ce0da..c7cff4d16 100644 --- a/traitsui/wx/list_str_editor.py +++ b/traitsui/wx/list_str_editor.py @@ -51,12 +51,10 @@ class wxListCtrl(wx.ListCtrl): - """ Subclass of wx.ListCtrl to provide correct virtual list behavior. - """ + """Subclass of wx.ListCtrl to provide correct virtual list behavior.""" def OnGetItemAttr(self, index): - """ Returns the display attributes to use for the specified list item. - """ + """Returns the display attributes to use for the specified list item.""" # fixme: There appears to be a bug in wx in that they do not correctly # manage the reference count for the returned object, and it seems to be # gc'ed before they finish using it. So we store an object reference to @@ -81,8 +79,7 @@ def OnGetItemAttr(self, index): return attr def OnGetItemImage(self, index): - """ Returns the image index to use for the specified list item. - """ + """Returns the image index to use for the specified list item.""" editor = self._editor if editor._is_auto_add(index): image = editor.adapter.get_default_image( @@ -98,8 +95,7 @@ def OnGetItemImage(self, index): return -1 def OnGetItemText(self, index, column): - """ Returns the text to use for the specified list item. - """ + """Returns the text to use for the specified list item.""" editor = self._editor if editor._is_auto_add(index): @@ -109,8 +105,7 @@ def OnGetItemText(self, index, column): class _ListStrEditor(Editor): - """ Traits UI editor for editing lists of strings. - """ + """Traits UI editor for editing lists of strings.""" # -- Trait Definitions ---------------------------------------------------- @@ -160,8 +155,8 @@ class _ListStrEditor(Editor): search = Str() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory @@ -257,8 +252,7 @@ def init(self, parent): self.set_tooltip() def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" disconnect_no_id( self.control, wx.EVT_SIZE, @@ -281,8 +275,8 @@ def dispose(self): super().dispose() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ control = self.control top = control.GetTopItem() @@ -328,9 +322,13 @@ def update_editor(self): return if 0 <= (index - top) < pn: - control.EnsureVisible(min(top + pn - 2, control.GetItemCount() - 1)) + control.EnsureVisible( + min(top + pn - 2, control.GetItemCount() - 1) + ) elif index < top: - control.EnsureVisible(min(index + pn - 1, control.GetItemCount() - 1)) + control.EnsureVisible( + min(index + pn - 1, control.GetItemCount() - 1) + ) else: control.EnsureVisible(index) @@ -351,15 +349,13 @@ def _get_item_count(self): # -- Trait Event Handlers ------------------------------------------------- def _title_changed(self, title): - """ Handles the editor title being changed. - """ + """Handles the editor title being changed.""" list_item = wx.ListItem() list_item.SetText(title) self.control.SetColumn(0, list_item) def _selected_changed(self, selected): - """ Handles the editor's 'selected' trait being changed. - """ + """Handles the editor's 'selected' trait being changed.""" if not self._no_update: try: self.control.SetItemState( @@ -371,8 +367,7 @@ def _selected_changed(self, selected): pass def _selected_index_changed(self, selected_index): - """ Handles the editor's 'selected_index' trait being changed. - """ + """Handles the editor's 'selected_index' trait being changed.""" if not self._no_update: try: self.control.SetItemState( @@ -384,8 +379,7 @@ def _selected_index_changed(self, selected_index): pass def _multi_selected_changed(self, selected): - """ Handles the editor's 'multi_selected' trait being changed. - """ + """Handles the editor's 'multi_selected' trait being changed.""" if not self._no_update: values = self.value try: @@ -396,8 +390,7 @@ def _multi_selected_changed(self, selected): pass def _multi_selected_items_changed(self, event): - """ Handles the editor's 'multi_selected' trait being modified. - """ + """Handles the editor's 'multi_selected' trait being modified.""" values = self.value try: self._multi_selected_indices_items_changed( @@ -411,8 +404,7 @@ def _multi_selected_items_changed(self, event): pass def _multi_selected_indices_changed(self, selected_indices): - """ Handles the editor's 'multi_selected_indices' trait being changed. - """ + """Handles the editor's 'multi_selected_indices' trait being changed.""" if not self._no_update: control = self.control selected = self._get_selected() @@ -436,8 +428,7 @@ def _multi_selected_indices_changed(self, selected_indices): control.SetItemState(index, 0, wx.LIST_STATE_SELECTED) def _multi_selected_indices_items_changed(self, event): - """ Handles the editor's 'multi_selected_indices' trait being modified. - """ + """Handles the editor's 'multi_selected_indices' trait being modified.""" control = self.control # Remove all items that are no longer selected: @@ -453,8 +444,8 @@ def _multi_selected_indices_items_changed(self, event): # -- List Control Event Handlers ------------------------------------------ def _begin_drag(self, event): - """ Handles the user beginning a drag operation with the left mouse - button. + """Handles the user beginning a drag operation with the left mouse + button. """ if PythonDropSource is not None: adapter = self.adapter @@ -500,8 +491,7 @@ def _begin_drag(self, event): self._drag_local = False def _begin_label_edit(self, event): - """ Handles the user starting to edit an item label. - """ + """Handles the user starting to edit an item label.""" index = event.GetIndex() if (not self._is_auto_add(index)) and ( @@ -510,13 +500,11 @@ def _begin_label_edit(self, event): event.Veto() def _end_label_edit(self, event): - """ Handles the user finishing editing an item label. - """ + """Handles the user finishing editing an item label.""" self._set_text_current(event.GetIndex(), event.GetText()) def _item_selected(self, event): - """ Handles an item being selected. - """ + """Handles an item being selected.""" self._no_update = True try: get_item = self.adapter.get_item @@ -537,8 +525,7 @@ def _item_selected(self, event): self._no_update = False def _item_activated(self, event): - """ Handles an item being activated (double-clicked or enter pressed). - """ + """Handles an item being activated (double-clicked or enter pressed).""" self.activated_index = event.GetIndex() if "edit" in self.factory.operations: self._edit_current() @@ -548,8 +535,7 @@ def _item_activated(self, event): ) def _right_clicked(self, event): - """ Handles an item being right clicked. - """ + """Handles an item being right clicked.""" index = event.GetIndex() if index == -1: return @@ -595,15 +581,13 @@ def _key_pressed(self, event): event.Skip() def _size_modified(self, event): - """ Handles the size of the list control being changed. - """ + """Handles the size of the list control being changed.""" dx, dy = self.control.GetClientSize() self.control.SetColumnWidth(0, dx - 1) event.Skip() def _left_down(self, event): - """ Handles the user pressing the left mouse button. - """ + """Handles the user pressing the left mouse button.""" index, flags = self.control.HitTest( wx.Point(event.GetX(), event.GetY()) ) @@ -616,8 +600,7 @@ def _left_down(self, event): # -- Drag and Drop Event Handlers ----------------------------------------- def wx_dropped_on(self, x, y, data, drag_result): - """ Handles a Python object being dropped on the list control. - """ + """Handles a Python object being dropped on the list control.""" index, flags = self.control.HitTest(wx.Point(x, y)) # If the user dropped it on an empty list, set the target as past the @@ -653,8 +636,8 @@ def wx_dropped_on(self, x, y, data, drag_result): return wx.DragNone def _wx_dropped_on(self, index, item): - """ Helper method for handling a single item dropped on the list - control. + """Helper method for handling a single item dropped on the list + control. """ adapter = self.adapter object, name = self.object, self.name @@ -681,8 +664,7 @@ def _wx_dropped_on(self, index, item): indices[i] += 1 def wx_drag_over(self, x, y, data, drag_result): - """ Handles a Python object being dragged over the tree. - """ + """Handles a Python object being dragged over the tree.""" if isinstance(data, list): rc = wx.DragNone for item in data: @@ -716,13 +698,11 @@ def wx_drag_over(self, x, y, data, drag_result): # -- Private Methods ------------------------------------------------------ def _refresh(self): - """ Refreshes the contents of the editor's list control. - """ + """Refreshes the contents of the editor's list control.""" self.control.RefreshItems(0, len(self.value) - 1) def _add_image(self, image_resource): - """ Adds a new image to the wx.ImageList and its associated mapping. - """ + """Adds a new image to the wx.ImageList and its associated mapping.""" bitmap = image_resource.create_image().ConvertToBitmap() image_list = self._image_list @@ -739,8 +719,7 @@ def _add_image(self, image_resource): return index def _get_image(self, image): - """ Converts a user specified image to a wx.ListCtrl image index. - """ + """Converts a user specified image to a wx.ListCtrl image index.""" if isinstance(image, ImageResource): result = self.image_resources.get(image) if result is not None: @@ -751,8 +730,7 @@ def _get_image(self, image): return self.images.get(image) def _get_selected(self): - """ Returns a list of the indices of all currently selected list items. - """ + """Returns a list of the indices of all currently selected list items.""" selected = [] item = -1 control = self.control @@ -768,8 +746,7 @@ def _get_selected(self): return selected def _search_for_string(self, increment=0): - """ Searches for the next occurrence of the current search string. - """ + """Searches for the next occurrence of the current search string.""" selected = self._get_selected() if len(selected) > 1: return @@ -795,8 +772,7 @@ def _search_for_string(self, increment=0): break def _append_new(self): - """ Append a new item to the end of the list control. - """ + """Append a new item to the end of the list control.""" if "append" in self.factory.operations: self.edit = True adapter = self.adapter @@ -814,8 +790,7 @@ def _append_new(self): ) def _copy_current(self): - """ Copies the currently selected list control item to the clipboard. - """ + """Copies the currently selected list control item to the clipboard.""" selected = self._get_selected() if len(selected) == 1: index = selected[0] @@ -832,8 +807,8 @@ def _copy_current(self): pass def _cut_current(self): - """ Cuts the currently selected list control item and places its value - in the clipboard. + """Cuts the currently selected list control item and places its value + in the clipboard. """ ops = self.factory.operations if ("insert" in ops) and ("delete" in ops): @@ -855,8 +830,8 @@ def _cut_current(self): pass def _paste_current(self): - """ Pastes the clipboard contents into the currently selected list - control item. + """Pastes the clipboard contents into the currently selected list + control item. """ if "insert" in self.factory.operations: selected = self._get_selected() @@ -873,8 +848,7 @@ def _paste_current(self): pass def _insert_current(self): - """ Inserts a new item after the currently selected list control item. - """ + """Inserts a new item after the currently selected list control item.""" if "insert" in self.factory.operations: selected = self._get_selected() if len(selected) == 1: @@ -889,8 +863,7 @@ def _insert_current(self): ) def _delete_current(self): - """ Deletes the currently selected items from the list control. - """ + """Deletes the currently selected items from the list control.""" if "delete" in self.factory.operations: selected = self._get_selected() if len(selected) == 0: @@ -905,8 +878,7 @@ def _delete_current(self): delete(self.object, self.name, index) def _move_up_current(self): - """ Moves the currently selected item up one line in the list control. - """ + """Moves the currently selected item up one line in the list control.""" if "move" in self.factory.operations: selected = self._get_selected() if len(selected) == 1: @@ -921,8 +893,7 @@ def _move_up_current(self): adapter.insert(object, name, index - 1, item) def _move_down_current(self): - """ Moves the currently selected item down one line in the list control. - """ + """Moves the currently selected item down one line in the list control.""" if "move" in self.factory.operations: selected = self._get_selected() if len(selected) == 1: @@ -937,24 +908,22 @@ def _move_down_current(self): adapter.insert(object, name, index + 1, item) def _edit_current(self): - """ Allows the user to edit the current item in the list control. - """ + """Allows the user to edit the current item in the list control.""" if "edit" in self.factory.operations: selected = self._get_selected() if len(selected) == 1: self.control.EditLabel(selected[0]) def _is_auto_add(self, index): - """ Returns whether or not the index is the special 'auto add' item at - the end of the list. + """Returns whether or not the index is the special 'auto add' item at + the end of the list. """ return self.factory.auto_add and ( index >= self.adapter.len(self.object, self.name) ) def _set_text_current(self, index, text, insert=False): - """ Sets the text value of the specified list control item. - """ + """Sets the text value of the specified list control item.""" if text.strip() != "": object, name, adapter = self.object, self.name, self.adapter if insert or self._is_auto_add(index): diff --git a/traitsui/wx/menu.py b/traitsui/wx/menu.py index 4db2c4bd4..00910c709 100644 --- a/traitsui/wx/menu.py +++ b/traitsui/wx/menu.py @@ -79,15 +79,13 @@ class MakeMenu: - """ Manages creation of menus. - """ + """Manages creation of menus.""" #: Initialize the globally unique menu ID: cur_id = 1000 def __init__(self, desc, owner, popup=False, window=None): - """ Initializes the object. - """ + """Initializes the object.""" self.owner = owner if window is None: window = owner @@ -108,8 +106,7 @@ def __init__(self, desc, owner, popup=False, window=None): window.SetAcceleratorTable(wx.AcceleratorTable(self.keys)) def parse(self, menu, indent): - """ Recursively parses menu items from the description. - """ + """Recursively parses menu items from the description.""" while True: @@ -245,8 +242,7 @@ def parse(self, menu, indent): menu.Append(submenu, label) def get_body(self, indent): - """ Returns the body of an inline method. - """ + """Returns the body of an inline method.""" result = [] while self.index < len(self.desc): line = self.desc[self.index] @@ -260,37 +256,32 @@ def get_body(self, indent): return " pass" def get_id(self, name): - """ Returns the ID associated with a specified name. - """ + """Returns the ID associated with a specified name.""" if isinstance(name, str): return self.names[name] return name def checked(self, name, check=None): - """ Checks (or unchecks) a menu item specified by name. - """ + """Checks (or unchecks) a menu item specified by name.""" if check is None: return self.menu.IsChecked(self.get_id(name)) self.menu.Check(self.get_id(name), check) def enabled(self, name, enable=None): - """ Enables (or disables) a menu item specified by name. - """ + """Enables (or disables) a menu item specified by name.""" if enable is None: return self.menu.IsEnabled(self.get_id(name)) self.menu.Enable(self.get_id(name), enable) def label(self, name, label=None): - """ Gets or sets the label for a menu item. - """ + """Gets or sets the label for a menu item.""" if label is None: return self.menu.GetLabel(self.get_id(name)) self.menu.SetLabel(self.get_id(name), label) class MakeMenuItem: - """ A menu item for a menu managed by MakeMenu. - """ + """A menu item for a menu managed by MakeMenu.""" def __init__(self, menu, id): self.menu = menu @@ -318,7 +309,7 @@ def label(self, label=None): def option_check(test, string): - """ Determines whether a string contains any specified option characters, + """Determines whether a string contains any specified option characters, and removes them if it does. """ result = [] diff --git a/traitsui/wx/null_editor.py b/traitsui/wx/null_editor.py index 2e92cb6bd..73b39b029 100644 --- a/traitsui/wx/null_editor.py +++ b/traitsui/wx/null_editor.py @@ -18,18 +18,17 @@ class NullEditor(Editor): - """ A completely empty editor. - """ + """A completely empty editor.""" def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = control = wx.Window(parent, -1, size=wx.Size(1, 1)) control.SetBackgroundColour(parent.GetBackgroundColour()) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ pass diff --git a/traitsui/wx/progress_editor.py b/traitsui/wx/progress_editor.py index 014fdaa86..6a74475bb 100644 --- a/traitsui/wx/progress_editor.py +++ b/traitsui/wx/progress_editor.py @@ -17,8 +17,7 @@ class _ProgressDialog(ProgressDialog): def close(self): - """ Overwritten to disable closing. - """ + """Overwritten to disable closing.""" pass @@ -42,8 +41,8 @@ class SimpleEditor(Editor): # -- Editor interface ------------------------------------------------------ def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self.control = self.create_control(parent) factory = self.factory diff --git a/traitsui/wx/range_editor.py b/traitsui/wx/range_editor.py index d09966bd9..0b610ba2c 100644 --- a/traitsui/wx/range_editor.py +++ b/traitsui/wx/range_editor.py @@ -40,8 +40,8 @@ class BaseRangeEditor(Editor): - """ The base class for Range editors. Using an evaluate trait, if specified, - when assigning numbers the object trait. + """The base class for Range editors. Using an evaluate trait, if specified, + when assigning numbers the object trait. """ # ------------------------------------------------------------------------- @@ -58,7 +58,7 @@ def _set_value(self, value): class SimpleSliderEditor(BaseRangeEditor): - """ Simple style of range editor that displays a slider and a text field. + """Simple style of range editor that displays a slider and a text field. The user can set a value either by moving the slider or by typing a value in the text field. @@ -81,8 +81,8 @@ class SimpleSliderEditor(BaseRangeEditor): ui_changing = Bool(False) def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory if not factory.low_name: @@ -148,7 +148,9 @@ def init(self, parent): size=wx.Size(56, 20), style=wx.TE_PROCESS_ENTER, ) - panel.Bind(wx.EVT_TEXT_ENTER, self.update_object_on_enter, id=text.GetId()) + panel.Bind( + wx.EVT_TEXT_ENTER, self.update_object_on_enter, id=text.GetId() + ) text.Bind(wx.EVT_KILL_FOCUS, self.update_object_on_enter) sizer.Add(text, 0, wx.LEFT | wx.EXPAND, 4) @@ -172,8 +174,7 @@ def init(self, parent): panel.SetSizerAndFit(sizer) def update_object_on_scroll(self, event): - """ Handles the user changing the current slider value. - """ + """Handles the user changing the current slider value.""" value = self._convert_from_slider(event.GetPosition()) event_type = event.GetEventType() if ( @@ -197,8 +198,7 @@ def update_object_on_scroll(self, event): self.ui_changing = False def update_object_on_enter(self, event): - """ Handles the user pressing the Enter key in the text field. - """ + """Handles the user pressing the Enter key in the text field.""" if isinstance(event, wx.FocusEvent): event.Skip() @@ -237,8 +237,7 @@ def update_object_on_enter(self, event): pass def error(self, excp): - """ Handles an error that occurs while setting the object's trait value. - """ + """Handles an error that occurs while setting the object's trait value.""" if self._error is None: self._error = True self.ui.errors += 1 @@ -246,8 +245,8 @@ def error(self, excp): self.set_error_state(True) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ value = self.value try: @@ -262,8 +261,7 @@ def update_editor(self): self.control.slider.SetValue(ivalue) def _convert_to_slider(self, value): - """ Returns the slider setting corresponding to the user-supplied value. - """ + """Returns the slider setting corresponding to the user-supplied value.""" if self.high > self.low: ivalue = int( (float(value - self.low) / (self.high - self.low)) * 10000.0 @@ -273,7 +271,7 @@ def _convert_to_slider(self, value): return ivalue def _convert_from_slider(self, ivalue): - """ Returns the float or integer value corresponding to the slider + """Returns the float or integer value corresponding to the slider setting. """ value = self.low + ((float(ivalue) / 10000.0) * (self.high - self.low)) @@ -282,8 +280,7 @@ def _convert_from_slider(self, ivalue): return value def get_error_control(self): - """ Returns the editor's control for indicating error status. - """ + """Returns the editor's control for indicating error status.""" return self.control.text def _low_changed(self, low): @@ -312,12 +309,10 @@ def _high_changed(self, high): # ------------------------------------------------------------------------- class LogRangeSliderEditor(SimpleSliderEditor): # ------------------------------------------------------------------------- - """ A slider editor for log-spaced values - """ + """A slider editor for log-spaced values""" def _convert_to_slider(self, value): - """ Returns the slider setting corresponding to the user-supplied value. - """ + """Returns the slider setting corresponding to the user-supplied value.""" value = max(value, self.low) ivalue = int( (log10(value) - log10(self.low)) @@ -327,7 +322,7 @@ def _convert_to_slider(self, value): return ivalue def _convert_from_slider(self, ivalue): - """ Returns the float or integer value corresponding to the slider + """Returns the float or integer value corresponding to the slider setting. """ value = float(ivalue) / 10000.0 * (log10(self.high) - log10(self.low)) @@ -340,11 +335,11 @@ def _convert_from_slider(self, ivalue): class LargeRangeSliderEditor(BaseRangeEditor): - """ A slider editor for large ranges. + """A slider editor for large ranges. - The editor displays a slider and a text field. A subset of the total - range is displayed in the slider; arrow buttons at each end of the - slider let the user move the displayed range higher or lower. + The editor displays a slider and a text field. A subset of the total + range is displayed in the slider; arrow buttons at each end of the + slider let the user move the displayed range higher or lower. """ # ------------------------------------------------------------------------- @@ -367,8 +362,8 @@ class LargeRangeSliderEditor(BaseRangeEditor): ui_changing = Bool(False) def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory @@ -463,7 +458,9 @@ def init(self, parent): size=wx.Size(56, 20), style=wx.TE_PROCESS_ENTER, ) - panel.Bind(wx.EVT_TEXT_ENTER, self.update_object_on_enter, id=text.GetId()) + panel.Bind( + wx.EVT_TEXT_ENTER, self.update_object_on_enter, id=text.GetId() + ) text.Bind(wx.EVT_KILL_FOCUS, self.update_object_on_enter) sizer.Add(text, 0, wx.LEFT | wx.EXPAND, 4) @@ -481,8 +478,7 @@ def init(self, parent): self.update_range_ui() def update_object_on_scroll(self, event): - """ Handles the user changing the current slider value. - """ + """Handles the user changing the current slider value.""" low = self.cur_low high = self.cur_high value = low + ((float(event.GetPosition()) / 10000.0) * (high - low)) @@ -509,8 +505,7 @@ def update_object_on_scroll(self, event): self.ui_changing = False def update_object_on_enter(self, event): - """ Handles the user pressing the Enter key in the text field. - """ + """Handles the user pressing the Enter key in the text field.""" if isinstance(event, wx.FocusEvent): event.Skip() # It is possible the event is processed after the control is removed @@ -549,8 +544,7 @@ def update_object_on_enter(self, event): pass def error(self, excp): - """ Handles an error that occurs while setting the object's trait value. - """ + """Handles an error that occurs while setting the object's trait value.""" if self._error is None: self._error = True self.ui.errors += 1 @@ -558,8 +552,8 @@ def error(self, excp): self.set_error_state(True) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ value = self.value low = self.low @@ -576,8 +570,7 @@ def update_editor(self): self.update_range_ui() def update_range_ui(self): - """ Updates the slider range controls. - """ + """Updates the slider range controls.""" low, high = self.cur_low, self.cur_high value = self.value self._set_format() @@ -604,8 +597,7 @@ def update_range_ui(self): self.control.button_hi.Enable() def init_range(self): - """ Initializes the slider range controls. - """ + """Initializes the slider range controls.""" value = self.value factory = self.factory low, high = self.low, self.high @@ -624,8 +616,7 @@ def init_range(self): self.cur_low, self.cur_high = cur_low, cur_high def reduce_range(self, event): - """ Reduces the extent of the displayed range. - """ + """Reduces the extent of the displayed range.""" factory = self.factory low, high = self.low, self.high if abs(self.cur_low) < 10: @@ -644,8 +635,7 @@ def reduce_range(self, event): self.update_range_ui() def increase_range(self, event): - """ Increased the extent of the displayed range. - """ + """Increased the extent of the displayed range.""" factory = self.factory low, high = self.low, self.high if abs(self.cur_high) < 10: @@ -677,8 +667,7 @@ def _set_format(self): self._format = "%.3f" def get_error_control(self): - """ Returns the editor's control for indicating error status. - """ + """Returns the editor's control for indicating error status.""" return self.control.text def _low_changed(self, low): @@ -703,8 +692,7 @@ def _high_changed(self, high): class SimpleSpinEditor(BaseRangeEditor): - """ A simple style of range editor that displays a spin box control. - """ + """A simple style of range editor that displays a spin box control.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -717,8 +705,8 @@ class SimpleSpinEditor(BaseRangeEditor): high = Any() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory if not factory.low_name: @@ -734,12 +722,13 @@ def init(self, parent): self.control = wx.SpinCtrl( parent, -1, self.str_value, min=low, max=high, initial=self.value ) - parent.Bind(wx.EVT_SPINCTRL, self.update_object, id=self.control.GetId()) + parent.Bind( + wx.EVT_SPINCTRL, self.update_object, id=self.control.GetId() + ) self.set_tooltip() def update_object(self, event): - """ Handles the user selecting a new value in the spin box. - """ + """Handles the user selecting a new value in the spin box.""" if self.control is None: return self._locked = True @@ -749,8 +738,8 @@ def update_object(self, event): self._locked = False def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ if not self._locked: try: @@ -780,9 +769,9 @@ def _high_changed(self, high): class RangeTextEditor(TextEditor): - """ Editor for ranges that displays a text field. If the user enters a - value that is outside the allowed range, the background of the field - changes color to indicate an error. + """Editor for ranges that displays a text field. If the user enters a + value that is outside the allowed range, the background of the field + changes color to indicate an error. """ # ------------------------------------------------------------------------- @@ -799,8 +788,8 @@ class RangeTextEditor(TextEditor): evaluate = Any() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ if not self.factory.low_name: self.low = self.factory.low @@ -815,7 +804,9 @@ def init(self, parent): control = wx.TextCtrl( parent, -1, self.str_value, style=wx.TE_PROCESS_ENTER ) - parent.Bind(wx.EVT_TEXT_ENTER, self.update_object, id=control.GetId()) + parent.Bind( + wx.EVT_TEXT_ENTER, self.update_object, id=control.GetId() + ) else: control = wx.TextCtrl(parent, -1, self.str_value) @@ -831,8 +822,7 @@ def init(self, parent): self.set_tooltip() def update_object(self, event): - """ Handles the user entering input data in the edit control. - """ + """Handles the user entering input data in the edit control.""" if isinstance(event, wx.FocusEvent): event.Skip() @@ -875,8 +865,7 @@ def update_object(self, event): pass def error(self, excp): - """ Handles an error that occurs while setting the object's trait value. - """ + """Handles an error that occurs while setting the object's trait value.""" if self._error is None: self._error = True self.ui.errors += 1 @@ -902,9 +891,7 @@ def _high_changed(self, high): self.control.SetValue(int(self.value)) -def SimpleEnumEditor( - parent, factory, ui, object, name, description, **kwargs -): +def SimpleEnumEditor(parent, factory, ui, object, name, description, **kwargs): return CustomEnumEditor( parent, factory, ui, object, name, description, "simple" ) @@ -913,8 +900,8 @@ def SimpleEnumEditor( def CustomEnumEditor( parent, factory, ui, object, name, description, style="custom", **kwargs ): - """ Factory adapter that returns a enumeration editor of the specified - style. + """Factory adapter that returns a enumeration editor of the specified + style. """ if factory._enum is None: import traitsui.editors.enum_editor as enum_editor diff --git a/traitsui/wx/rgb_color_editor.py b/traitsui/wx/rgb_color_editor.py index cb5ba4dc9..1d29ae127 100644 --- a/traitsui/wx/rgb_color_editor.py +++ b/traitsui/wx/rgb_color_editor.py @@ -30,12 +30,10 @@ class ToolkitEditorFactory(BaseColorToolkitEditorFactory): - """ wxPython editor factory for color editors. - """ + """wxPython editor factory for color editors.""" def to_wx_color(self, editor, color=None): - """ Gets the wxPython color equivalent of the object trait. - """ + """Gets the wxPython color equivalent of the object trait.""" if color is None: try: color = getattr(editor.object, editor.name + "_") @@ -50,8 +48,7 @@ def to_wx_color(self, editor, color=None): return color def from_wx_color(self, color): - """ Gets the application equivalent of a wxPython value. - """ + """Gets the application equivalent of a wxPython value.""" return ( color.Red() / 255.0, color.Green() / 255.0, @@ -59,8 +56,7 @@ def from_wx_color(self, color): ) def str_color(self, color): - """ Returns the text representation of a specified color value. - """ + """Returns the text representation of a specified color value.""" if type(color) in SequenceTypes: return "(%d,%d,%d)" % ( int(color[0] * 255.0), diff --git a/traitsui/wx/rgb_color_trait.py b/traitsui/wx/rgb_color_trait.py index 1093eb9d1..3faac59df 100644 --- a/traitsui/wx/rgb_color_trait.py +++ b/traitsui/wx/rgb_color_trait.py @@ -33,10 +33,10 @@ def range_check(value): - """ Checks that *value* can be converted to a value in the range 0.0 to 1.0. + """Checks that *value* can be converted to a value in the range 0.0 to 1.0. - If so, it returns the floating point value; otherwise, it raises a - TraitError. + If so, it returns the floating point value; otherwise, it raises a + TraitError. """ value = float(value) if 0.0 <= value <= 1.0: @@ -45,8 +45,8 @@ def range_check(value): def convert_to_color(object, name, value): - """ Converts a tuple or an integer to an RGB color value, or raises a - TraitError if that is not possible. + """Converts a tuple or an integer to an RGB color value, or raises a + TraitError if that is not possible. """ if (type(value) in SequenceTypes) and (len(value) == 3): return ( @@ -57,7 +57,8 @@ def convert_to_color(object, name, value): if isinstance(value, int): num = int(value) return ( - (num // 0x10000) / 255.0, ((num // 0x100) & 0xFF) / 255.0, + (num // 0x10000) / 255.0, + ((num // 0x100) & 0xFF) / 255.0, (num & 0xFF) / 255.0, ) if isinstance(value, wx.Colour): diff --git a/traitsui/wx/scrubber_editor.py b/traitsui/wx/scrubber_editor.py index ff121633f..9e8256ff4 100644 --- a/traitsui/wx/scrubber_editor.py +++ b/traitsui/wx/scrubber_editor.py @@ -45,8 +45,7 @@ class _ScrubberEditor(Editor): - """ Traits UI simple, scrubber-based integer or float value editor. - """ + """Traits UI simple, scrubber-based integer or float value editor.""" #: The low end of the slider range: low = Any() @@ -72,8 +71,8 @@ class _ScrubberEditor(Editor): } def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory @@ -137,8 +136,7 @@ def init(self, parent): self._reset_scrubber() def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" # Remove all of the wx event handlers: disconnect_no_id( self.control, @@ -160,8 +158,8 @@ def dispose(self): super().dispose() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ self.text = self.string_value(self.value) self._text_size = None @@ -170,8 +168,7 @@ def update_editor(self): self._enum_completed() def update_object(self, value): - """ Updates the object when the scrubber value changes. - """ + """Updates the object when the scrubber value changes.""" if self.mapping is not None: value = self.mapping[int(value)] @@ -186,23 +183,20 @@ def update_object(self, value): self.update_editor() def error(self, excp): - """ Handles an error that occurs while setting the object's trait value. - """ + """Handles an error that occurs while setting the object's trait value.""" pass # -- Trait Event Handlers ------------------------------------------------- def _mapping_changed(self, mapping): - """ Handles the Enum mapping being changed. - """ + """Handles the Enum mapping being changed.""" self.high = len(mapping) - 1 # -- Private Methods ------------------------------------------------------ @observe("low, high") def _reset_scrubber(self, event=None): - """ Sets the the current tooltip. - """ + """Sets the the current tooltip.""" low, high = self.low, self.high if self._can_set_tooltip: if self.mapping is not None: @@ -233,8 +227,8 @@ def _reset_scrubber(self, event=None): self.update_editor() def _get_text_bounds(self): - """ Get the window bounds of where the current text should be - displayed. + """Get the window bounds of where the current text should be + displayed. """ tdx, tdy, descent, leading = self._get_text_size() wdx, wdy = self.control.GetClientSize() @@ -250,8 +244,7 @@ def _get_text_bounds(self): return (tx, ty, tdx, tdy) def _get_text_size(self): - """ Returns the text size information for the window. - """ + """Returns the text size information for the window.""" if self._text_size is None: self._text_size = self.control.GetFullTextExtent( self.text.strip() or "M" @@ -260,14 +253,13 @@ def _get_text_size(self): return self._text_size def _refresh(self): - """ Refreshes the contents of the control. - """ + """Refreshes the contents of the control.""" if self.control is not None: self.control.Refresh() def _set_scrubber_position(self, event, delta): - """ Calculates a new scrubber value for a specified mouse position - change. + """Calculates a new scrubber value for a specified mouse position + change. """ clicks = 3 increment = self.increment @@ -288,13 +280,12 @@ def _set_scrubber_position(self, event, delta): self.update_object(value) def _delayed_click(self): - """ Handle a delayed click response. - """ + """Handle a delayed click response.""" self._pending = False def _pop_up_editor(self): - """ Pop-up a text control to allow the user to enter a value using - the keyboard. + """Pop-up a text control to allow the user to enter a value using + the keyboard. """ self.control.SetCursor(wx.Cursor(wx.CURSOR_ARROW)) @@ -343,8 +334,7 @@ def _pop_up_text(self): text.Bind(wx.EVT_CHAR, self._key_entered) def _destroy_text(self): - """ Destroys the current text control. - """ + """Destroys the current text control.""" self._ignore_focus = self._in_text_window self._disconnect_text() @@ -354,8 +344,7 @@ def _destroy_text(self): self._text = None def _disconnect_text(self): - """ Disconnects the event handlers for the pop up text editor. - """ + """Disconnects the event handlers for the pop up text editor.""" if self._text is not None: disconnect(self._text, wx.EVT_TEXT_ENTER) disconnect_no_id( @@ -367,8 +356,8 @@ def _disconnect_text(self): ) def _init_value(self): - """ Initializes the current value when the user begins a drag or moves - the mouse wheel. + """Initializes the current value when the user begins a drag or moves + the mouse wheel. """ if self.mapping is not None: try: @@ -381,13 +370,11 @@ def _init_value(self): # --- wxPython Event Handlers --------------------------------------------- def _erase_background(self, event): - """ Do not erase the background here (do it in the 'on_paint' handler). - """ + """Do not erase the background here (do it in the 'on_paint' handler).""" pass def _on_paint(self, event): - """ Paint the background using the associated ImageSlice object. - """ + """Paint the background using the associated ImageSlice object.""" control = self.control dc = BufferDC(control) @@ -430,14 +417,12 @@ def _on_paint(self, event): dc.copy() def _resize(self, event): - """ Handles the control being resized. - """ + """Handles the control being resized.""" if self._text is not None: self._text.SetSize(self.control.GetSize()) def _set_focus(self, event): - """ Handle the control getting the keyboard focus. - """ + """Handle the control getting the keyboard focus.""" if ( (not self._ignore_focus) and (self._x is None) @@ -447,17 +432,16 @@ def _set_focus(self, event): event.Skip() def _enter_window(self, event): - """ Handles the mouse entering the window. - """ + """Handles the mouse entering the window.""" self._hover = True self.control.SetCursor(wx.Cursor(wx.CURSOR_HAND)) - + if not self._ignore_focus: self._ignore_focus = True self.control.SetFocus() self._ignore_focus = False - + if self._x is not None: if self.factory.active_color_ != self.factory.color_: self.control.Refresh() @@ -465,16 +449,14 @@ def _enter_window(self, event): self.control.Refresh() def _leave_window(self, event): - """ Handles the mouse leaving the window. - """ + """Handles the mouse leaving the window.""" self._hover = False if self.factory.hover_color_ != self.factory.color_: self.control.Refresh() def _left_down(self, event): - """ Handles the left mouse being pressed. - """ + """Handles the left mouse being pressed.""" self._x, self._y = event.GetX(), event.GetY() self._pending = True @@ -488,8 +470,7 @@ def _left_down(self, event): do_after(200, self._delayed_click) def _left_up(self, event): - """ Handles the left mouse button being released. - """ + """Handles the left mouse button being released.""" self.control.ReleaseMouse() if self._pending: self._pop_up_editor() @@ -500,8 +481,7 @@ def _left_up(self, event): self.control.Refresh() def _motion(self, event): - """ Handles the mouse moving. - """ + """Handles the mouse moving.""" if self._x is not None: x, y = event.GetX(), event.GetY() dx = x - self._x @@ -521,19 +501,19 @@ def _motion(self, event): self._set_scrubber_position(event, delta) def _mouse_wheel(self, event): - """ Handles the mouse wheel moving. - """ + """Handles the mouse wheel moving.""" if self._hover: self._init_value() clicks = 3 if event.ShiftDown(): clicks = 7 - delta = clicks * (event.GetWheelRotation() // event.GetWheelDelta()) + delta = clicks * ( + event.GetWheelRotation() // event.GetWheelDelta() + ) self._set_scrubber_position(event, delta) def _update_value(self, event): - """ Updates the object value from the current text control value. - """ + """Updates the object value from the current text control value.""" control = event.GetEventObject() try: self.update_object(float(control.GetValue())) @@ -547,26 +527,22 @@ def _update_value(self, event): return False def _enter_text(self, event): - """ Handles the mouse entering the pop-up text control. - """ + """Handles the mouse entering the pop-up text control.""" self._in_text_window = True def _leave_text(self, event): - """ Handles the mouse leaving the pop-up text control. - """ + """Handles the mouse leaving the pop-up text control.""" self._in_text_window = False def _text_completed(self, event): - """ Handles the user pressing the 'Enter' key in the text control. - """ + """Handles the user pressing the 'Enter' key in the text control.""" if isinstance(event, wx.FocusEvent): event.Skip() if self._update_value(event): self._destroy_text() def _enum_completed(self, event=None): - """ Handles the Enum drop-down control losing focus. - """ + """Handles the Enum drop-down control losing focus.""" if self._ui is not None: self._ignore_focus = True disconnect_no_id( @@ -576,8 +552,7 @@ def _enum_completed(self, event=None): del self._ui def _key_entered(self, event): - """ Handles individual key strokes while the text control is active. - """ + """Handles individual key strokes while the text control is active.""" key_code = event.GetKeyCode() if key_code == wx.WXK_ESCAPE: self._destroy_text() diff --git a/traitsui/wx/search_editor.py b/traitsui/wx/search_editor.py index 9db3e2af8..72af09b86 100644 --- a/traitsui/wx/search_editor.py +++ b/traitsui/wx/search_editor.py @@ -17,8 +17,8 @@ class SearchEditor(Editor): def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ style = 0 @@ -45,17 +45,21 @@ def dispose(self): self.control.Unbind(wx.EVT_TEXT, handler=self.update_object) if self.factory.enter_set: - self.control.Unbind(wx.EVT_TEXT_ENTER, handler=self.update_object) + self.control.Unbind( + wx.EVT_TEXT_ENTER, handler=self.update_object + ) - self.control.Unbind(wx.EVT_SEARCHCTRL_SEARCH_BTN, handler=self.update_object) - self.control.Unbind(wx.EVT_SEARCHCTRL_CANCEL_BTN, handler=self.clear_text) + self.control.Unbind( + wx.EVT_SEARCHCTRL_SEARCH_BTN, handler=self.update_object + ) + self.control.Unbind( + wx.EVT_SEARCHCTRL_CANCEL_BTN, handler=self.clear_text + ) super().dispose() - def update_object(self, event): - """ Handles the user entering input data in the edit control. - """ + """Handles the user entering input data in the edit control.""" if not self._no_update: self.value = self.control.GetValue() @@ -63,8 +67,7 @@ def update_object(self, event): setattr(self.object, self.factory.search_event_trait, True) def clear_text(self, event): - """ Handles the user pressing the cancel search button. - """ + """Handles the user pressing the cancel search button.""" if not self._no_update: self.control.SetValue("") @@ -73,8 +76,8 @@ def clear_text(self, event): setattr(self.object, self.factory.search_event_trait, True) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ if self.control.GetValue() != self.value: diff --git a/traitsui/wx/set_editor.py b/traitsui/wx/set_editor.py index 216fdfafe..0ecac71cf 100644 --- a/traitsui/wx/set_editor.py +++ b/traitsui/wx/set_editor.py @@ -31,13 +31,13 @@ class SimpleEditor(Editor): - """ Simple style of editor for sets. + """Simple style of editor for sets. - The editor displays two list boxes, with buttons for moving the selected - items from left to right, or vice versa. If **can_move_all** on the - factory is True, then buttons are displayed for moving all the items to - one box or the other. If the set is ordered, buttons are displayed for - moving the selected item up or down in right-side list box. + The editor displays two list boxes, with buttons for moving the selected + items from left to right, or vice versa. If **can_move_all** on the + factory is True, then buttons are displayed for moving all the items to + one box or the other. If the set is ordered, buttons are displayed for + moving the selected item up or down in right-side list box. """ # ------------------------------------------------------------------------- @@ -57,8 +57,8 @@ class SimpleEditor(Editor): scrollable = True def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory if factory.name != "": @@ -128,23 +128,19 @@ def init(self, parent): self.set_tooltip() def _get_names(self): - """ Gets the current set of enumeration names. - """ + """Gets the current set of enumeration names.""" return self._names def _get_mapping(self): - """ Gets the current mapping. - """ + """Gets the current mapping.""" return self._mapping def _get_inverse_mapping(self): - """ Gets the current inverse mapping. - """ + """Gets the current inverse mapping.""" return self._inverse_mapping def _create_listbox(self, parent, sizer, handler1, handler2, title): - """ Creates a list box. - """ + """Creates a list box.""" column_sizer = wx.BoxSizer(wx.VERTICAL) # Add the column title in emphasized text: @@ -170,8 +166,7 @@ def _create_listbox(self, parent, sizer, handler1, handler2, title): return list def _create_button(self, label, parent, sizer, space_before, handler): - """ Creates a button. - """ + """Creates a button.""" button = wx.Button(parent, -1, label, style=wx.BU_EXACTFIT) sizer.AddSpacer(space_before) sizer.Add(button, 0, wx.EXPAND | wx.BOTTOM, 8) @@ -179,23 +174,25 @@ def _create_button(self, label, parent, sizer, space_before, handler): return button def values_changed(self): - """ Recomputes the cached data based on the underlying enumeration model - or the values of the factory. + """Recomputes the cached data based on the underlying enumeration model + or the values of the factory. """ - self._names, self._mapping, self._inverse_mapping = enum_values_changed( - self._value(), self.string_value - ) + ( + self._names, + self._mapping, + self._inverse_mapping, + ) = enum_values_changed(self._value(), self.string_value) def _values_changed(self): - """ Handles the underlying object model's enumeration set or factory's - values being changed. + """Handles the underlying object model's enumeration set or factory's + values being changed. """ self.values_changed() self.update_editor() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ # Check for any items having been deleted from the enumeration that are # still present in the object value: @@ -263,8 +260,7 @@ def update_editor(self): self._check_left_right() def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" if self._object is not None: self._object.on_trait_change( self._values_changed, self._name, remove=True @@ -281,8 +277,7 @@ def dispose(self): super().dispose() def get_error_control(self): - """ Returns the editor's control for indicating error status. - """ + """Returns the editor's control for indicating error status.""" return [self._unused, self._used] # ------------------------------------------------------------------------- @@ -336,14 +331,12 @@ def _on_down(self, event): # ------------------------------------------------------------------------- def _clear_selection(self, box): - """ Unselects all items in the given ListBox - """ + """Unselects all items in the given ListBox""" for i in box.GetSelections(): box.Deselect(i) def _transfer_all(self, list_from, list_to, values_from, values_to): - """ Transfers all items from one list to another. - """ + """Transfers all items from one list to another.""" values_from = values_from[:] values_to = values_to[:] @@ -365,8 +358,7 @@ def _transfer_all(self, list_from, list_to, values_from, values_to): return (values_from, values_to) def _transfer_items(self, list_from, list_to, values_from, values_to): - """ Transfers the selected item from one list to another. - """ + """Transfers the selected item from one list to another.""" values_from = values_from[:] values_to = values_to[:] indices_from = list_from.GetSelections() @@ -410,8 +402,7 @@ def _transfer_items(self, list_from, list_to, values_from, values_to): return (values_from, values_to) def _move_item(self, direction): - """ Moves an item up or down within the "used" list. - """ + """Moves an item up or down within the "used" list.""" # Move the item up/down within the list: listbox = self._used index_from = self._get_first_selection(listbox) @@ -436,8 +427,7 @@ def _move_item(self, direction): self.value = value[:index] + values + value[index + 2 :] def _check_up_down(self): - """ Sets the proper enabled state for the up and down buttons. - """ + """Sets the proper enabled state for the up and down buttons.""" if self.factory.ordered: index_selected = self._used.GetSelections() self._up.Enable( @@ -449,8 +439,7 @@ def _check_up_down(self): ) def _check_left_right(self): - """ Sets the proper enabled state for the left and right buttons. - """ + """Sets the proper enabled state for the left and right buttons.""" self._use.Enable( self._unused.GetCount() > 0 and self._get_first_selection(self._unused) >= 0 @@ -475,8 +464,7 @@ def _check_left_right(self): # ------------------------------------------------------------------------- def _get_selected_strings(self, listbox): - """ Returns a list of the selected strings in the given *listbox*. - """ + """Returns a list of the selected strings in the given *listbox*.""" stringlist = [] for label_index in listbox.GetSelections(): stringlist.append(listbox.GetString(label_index)) @@ -488,8 +476,7 @@ def _get_selected_strings(self, listbox): # ------------------------------------------------------------------------- def _get_first_selection(self, listbox): - """ Returns the index of the first (or only) selected item. - """ + """Returns the index of the first (or only) selected item.""" select_list = listbox.GetSelections() if len(select_list) == 0: return -1 diff --git a/traitsui/wx/shell_editor.py b/traitsui/wx/shell_editor.py index d4021a473..d346d5046 100644 --- a/traitsui/wx/shell_editor.py +++ b/traitsui/wx/shell_editor.py @@ -22,7 +22,6 @@ class _ShellEditor(BaseShellEditor, Editor): - """ Editor that displays an interactive Python shell. - """ + """Editor that displays an interactive Python shell.""" pass diff --git a/traitsui/wx/table_editor.py b/traitsui/wx/table_editor.py index ea2c20180..84eaa5150 100644 --- a/traitsui/wx/table_editor.py +++ b/traitsui/wx/table_editor.py @@ -82,16 +82,16 @@ def _get_color(color, default_color): - """ Return the color if it is not None, otherwise use default. """ + """Return the color if it is not None, otherwise use default.""" if color is not None: return color return default_color class TableEditor(Editor, BaseTableEditor): - """ Editor that presents data in a table. Optionally, tables can have - a set of filters that reduce the set of data displayed, according to - their criteria. + """Editor that presents data in a table. Optionally, tables can have + a set of filters that reduce the set of data displayed, according to + their criteria. """ # ------------------------------------------------------------------------- @@ -163,8 +163,8 @@ class TableEditor(Editor, BaseTableEditor): auto_add = Bool(False) def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory @@ -309,8 +309,7 @@ def init(self, parent): panel.SetSizer(sizer) def _create_grid(self, parent, sizer): - """ Creates the associated grid control used to implement the table. - """ + """Creates the associated grid control used to implement the table.""" factory = self.factory selection_mode = GridModes[factory.selection_mode] if factory.selection_bg_color is None: @@ -405,8 +404,7 @@ def clear_minimum_height(info): return grid.control def _create_toolbar(self, parent, sizer): - """ Creates the table editing toolbar. - """ + """Creates the table editing toolbar.""" factory = self.factory if not factory.show_toolbar: @@ -449,8 +447,7 @@ def _create_toolbar(self, parent, sizer): sizer.Add(tb_sizer, 0, wx.EXPAND) def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" if self.toolbar_ui is not None: self.toolbar_ui.dispose() @@ -476,20 +473,18 @@ def dispose(self): super().dispose() def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ # fixme: Do we need to override this method? pass def refresh(self): - """ Refreshes the editor control. - """ + """Refreshes the editor control.""" self.grid._grid.Refresh() def set_selection(self, objects=[], notify=True): - """ Sets the current selection to a set of specified objects. - """ + """Sets the current selection to a set of specified objects.""" if not isinstance(objects, SequenceTypes): objects = [objects] @@ -499,8 +494,8 @@ def set_selection(self, objects=[], notify=True): ) def set_extended_selection(self, *pairs): - """ Sets the current selection to a set of specified object/column - pairs. + """Sets the current selection to a set of specified object/column + pairs. """ if (len(pairs) == 1) and isinstance(pairs[0], list): pairs = pairs[0] @@ -512,8 +507,7 @@ def set_extended_selection(self, *pairs): self.grid.set_selection(grid_selections) def create_new_row(self): - """ Creates a new row object using the provided factory. - """ + """Creates a new row object using the provided factory.""" factory = self.factory kw = factory.row_factory_kw.copy() if "__table_editor__" in kw: @@ -524,8 +518,7 @@ def create_new_row(self): ) def add_row(self, object=None, index=None): - """ Adds a specified object as a new row after the specified index. - """ + """Adds a specified object as a new row after the specified index.""" filtered_items = self.model.get_filtered_items if index is None: @@ -573,8 +566,8 @@ def add_row(self, object=None, index=None): self.set_selection(items) def move_column(self, from_column, to_column): - """ Moves the specified **from_column** from its current position to - just preceding the specified **to_column**. + """Moves the specified **from_column** from its current position to + just preceding the specified **to_column**. """ columns = self.columns frm = columns.index(from_column) @@ -661,8 +654,8 @@ def _get_in_column_mode(self): # -- UI preference save/restore interface --------------------------------- def restore_prefs(self, prefs): - """ Restores any saved user preference information associated with the - editor. + """Restores any saved user preference information associated with the + editor. """ factory = self.factory try: @@ -702,8 +695,7 @@ def restore_prefs(self, prefs): pass def save_prefs(self): - """ Returns any user preference information associated with the editor. - """ + """Returns any user preference information associated with the editor.""" get_col_size = self.grid._grid.GetColSize result = { "filters": [f for f in self.factory.filters if not f.template], @@ -719,8 +711,8 @@ def save_prefs(self): # -- Public Methods ------------------------------------------------------- def filter_modified(self): - """ Handles updating the selection when some aspect of the current - filter has changed. + """Handles updating the selection when some aspect of the current + filter has changed. """ values = self.selected_values if len(values) > 0: @@ -735,8 +727,8 @@ def filter_modified(self): # -- Event Handlers ------------------------------------------------------- def _selection_row_updated(self, event): - """ Handles the user selecting items (rows, columns, cells) in the - table. + """Handles the user selecting items (rows, columns, cells) in the + table. """ gfi = self.model.get_filtered_item rio = self.model.raw_index_of @@ -772,8 +764,7 @@ def _selection_row_updated(self, event): self.ui.evaluate(self.factory.on_select, row) def _selection_rows_updated(self, event): - """ Handles multiple row selection changes. - """ + """Handles multiple row selection changes.""" gfi = self.model.get_filtered_item rio = self.model.raw_index_of tl = self.grid._grid.GetSelectionBlockTopLeft() @@ -808,8 +799,7 @@ def _selection_rows_updated(self, event): self.ui.evaluate(self.factory.on_select, rows) def _selection_column_updated(self, event): - """ Handles single column selection changes. - """ + """Handles single column selection changes.""" cols = self.columns tl = self.grid._grid.GetSelectionBlockTopLeft() br = iter(self.grid._grid.GetSelectionBlockBottomRight()) @@ -836,8 +826,7 @@ def _selection_column_updated(self, event): self.ui.evaluate(self.factory.on_select, column) def _selection_columns_updated(self, event): - """ Handles multiple column selection changes. - """ + """Handles multiple column selection changes.""" cols = self.columns tl = self.grid._grid.GetSelectionBlockTopLeft() br = iter(self.grid._grid.GetSelectionBlockBottomRight()) @@ -864,8 +853,7 @@ def _selection_columns_updated(self, event): self.ui.evaluate(self.factory.on_select, columns) def _selection_cell_updated(self, event): - """ Handles single cell selection changes. - """ + """Handles single cell selection changes.""" tl = self.grid._grid.GetSelectionBlockTopLeft() if len(tl) == 0: return @@ -902,8 +890,7 @@ def _selection_cell_updated(self, event): self.ui.evaluate(self.factory.on_select, cell) def _selection_cells_updated(self, event): - """ Handles multiple cell selection changes. - """ + """Handles multiple cell selection changes.""" gfi = self.model.get_filtered_item rio = self.model.raw_index_of cols = self.columns @@ -1004,8 +991,7 @@ def _selected_cell_indices_changed(self, pairs): self.set_extended_selection(new_selection) def _update_toolbar(self, has_selection): - """ Updates the toolbar after a selection change. - """ + """Updates the toolbar after a selection change.""" toolbar = self.toolbar if toolbar is not None: no_filter = self.filter is None @@ -1036,8 +1022,7 @@ def _update_toolbar(self, has_selection): ) = toolbar.move_down.enabled = False def _model_sorted(self): - """ Handles the contents of the model being resorted. - """ + """Handles the contents of the model being resorted.""" if self.toolbar is not None: self.toolbar.no_sort.enabled = True @@ -1046,8 +1031,7 @@ def _model_sorted(self): do_later(self.set_extended_selection, values) def _filter_changed(self, old_filter, new_filter): - """ Handles the current filter being changed. - """ + """Handles the current filter being changed.""" if new_filter is customize_filter: do_later(self._customize_filters, old_filter) @@ -1066,8 +1050,7 @@ def _refresh_filters(self, filters): factory.filters = filters def _customize_filters(self, filter): - """ Allows the user to customize the current set of table filters. - """ + """Allows the user to customize the current set of table filters.""" factory = self.factory filter_editor = TableFilterEditor(editor=self, filter=filter) enum_editor = EnumEditor(values=factory.filters[:], mode="list") @@ -1098,8 +1081,7 @@ def _customize_filters(self, filter): self.filter = filter def on_no_sort(self): - """ Handles the user requesting that columns not be sorted. - """ + """Handles the user requesting that columns not be sorted.""" self.model.no_column_sort() self.toolbar.no_sort.enabled = False values = self.selected_values @@ -1107,8 +1089,7 @@ def on_no_sort(self): self.set_extended_selection(values) def on_move_up(self): - """ Handles the user requesting to move the current item up one row. - """ + """Handles the user requesting to move the current item up one row.""" model = self.model objects = [] for index in self.selected_indices: @@ -1124,8 +1105,7 @@ def on_move_up(self): self.set_extended_selection(self.selected_values) def on_move_down(self): - """ Handles the user requesting to move the current item down one row. - """ + """Handles the user requesting to move the current item down one row.""" model = self.model objects = [] indices = self.selected_indices[:] @@ -1142,8 +1122,7 @@ def on_move_down(self): self.set_extended_selection(self.selected_values) def on_search(self): - """ Handles the user requesting a table search. - """ + """Handles the user requesting a table search.""" self.factory.search.edit_traits( parent=self.control, view="searchable_view", @@ -1151,13 +1130,12 @@ def on_search(self): ) def on_add(self): - """ Handles the user requesting to add a new row to the table. - """ + """Handles the user requesting to add a new row to the table.""" self.add_row() def on_delete(self): - """ Handles the user requesting to delete the currently selected items - of the table. + """Handles the user requesting to delete the currently selected items + of the table. """ # Get the selected row indices: indices = self.selected_indices[:] @@ -1202,8 +1180,8 @@ def on_delete(self): self._update_toolbar(False) def on_prefs(self): - """ Handles the user requesting to set the user preference items for the - table. + """Handles the user requesting to set the user preference items for the + table. """ columns = self.columns[:] columns.extend( @@ -1236,8 +1214,7 @@ def on_prefs(self): ) def prepare_menu(self, row, column): - """ Prepares to have a context menu action called. - """ + """Prepares to have a context menu action called.""" object = self.model.get_filtered_item(row) selection = [x.obj for x in self.grid.get_selection()] if object not in selection: @@ -1246,8 +1223,7 @@ def prepare_menu(self, row, column): self.set_menu_context(selection, object, column) def setx(self, **keywords): - """ Set one or more attributes without notifying the grid model. - """ + """Set one or more attributes without notifying the grid model.""" self._no_notify = True for name, value in keywords.items(): @@ -1264,8 +1240,7 @@ def _add_undo(self, undo_item, extend=False): class TableFilterEditor(Handler): - """ Editor that manages table filters. - """ + """Editor that manages table filters.""" #: TableEditor this editor is associated with editor = Instance(TableEditor) @@ -1290,8 +1265,7 @@ class TableFilterEditor(Handler): # ------------------------------------------------------------------------- def init(self, info): - """ Initializes the controls of a user interface. - """ + """Initializes the controls of a user interface.""" # Save both the original filter object reference and its contents: if self.filter is None: self.filter = info.filter.factory.values[0] @@ -1300,8 +1274,7 @@ def init(self, info): return True def closed(self, info, is_ok): - """ Handles a dialog-based user interface being closed by the user. - """ + """Handles a dialog-based user interface being closed by the user.""" if not is_ok: # Restore the contents of the original filter: self._filter.copy_traits(self._filter_copy) @@ -1311,8 +1284,7 @@ def closed(self, info, is_ok): # ------------------------------------------------------------------------- def object_filter_changed(self, info): - """ Handles a new filter being selected. - """ + """Handles a new filter being selected.""" filter = info.object.filter info.edit.enabled = not filter.template info.delete.enabled = (not filter.template) and ( @@ -1320,8 +1292,7 @@ def object_filter_changed(self, info): ) def object_edit_changed(self, info): - """ Handles the user clicking the **Edit** button. - """ + """Handles the user clicking the **Edit** button.""" if info.initialized: items = self.editor.model.get_filtered_items() if len(items) > 0: @@ -1335,8 +1306,7 @@ def object_edit_changed(self, info): self._refresh_filters(info) def object_new_changed(self, info): - """ Handles the user clicking the **New** button. - """ + """Handles the user clicking the **New** button.""" if info.initialized: # Get list of available filters and find the current filter in it: factory = info.filter.factory @@ -1361,16 +1331,14 @@ def object_new_changed(self, info): do_later(self._delayed_edit, info) def object_apply_changed(self, info): - """ Handles the user clicking the **Apply** button. - """ + """Handles the user clicking the **Apply** button.""" if info.initialized: self.init(info) self.editor._refresh_filters(info.filter.factory.values) self.editor.filter = self.filter def object_delete_changed(self, info): - """ Handles the user clicking the **Delete** button. - """ + """Handles the user clicking the **Delete** button.""" # Get the list of available filters: filters = info.filter.factory.values @@ -1390,15 +1358,14 @@ def object_delete_changed(self, info): # ------------------------------------------------------------------------- def _refresh_filters(self, info): - """ Refresh the filter editor's list of filters. - """ + """Refresh the filter editor's list of filters.""" factory = info.filter.factory values, factory.values = factory.values, [] factory.values = values def _delayed_edit(self, info): - """ Edits the current filter, and deletes it if the user cancels the - edit. + """Edits the current filter, and deletes it if the user cancels the + edit. """ ui = self.filter.edit(self.editor.model.get_filtered_item(0)) if not ui.result: @@ -1412,8 +1379,7 @@ def _delayed_edit(self, info): class TableEditorToolbar(HasPrivateTraits): - """ Toolbar displayed in table editors. - """ + """Toolbar displayed in table editors.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -1537,7 +1503,7 @@ def __init__(self, parent=None, **traits): image_size=(16, 16), show_tool_names=False, show_divider=False, - *actions + *actions, ) self.control = toolbar.create_tool_bar(parent, self) self.control.SetBackgroundColour(parent.GetBackgroundColour()) @@ -1552,35 +1518,30 @@ def __init__(self, parent=None, **traits): # ------------------------------------------------------------------------- def add_to_menu(self, menu_item): - """ Adds a menu item to the menu bar being constructed. - """ + """Adds a menu item to the menu bar being constructed.""" pass def add_to_toolbar(self, toolbar_item): - """ Adds a toolbar item to the too bar being constructed. - """ + """Adds a toolbar item to the too bar being constructed.""" pass def can_add_to_menu(self, action): - """ Returns whether the action should be defined in the user interface. - """ + """Returns whether the action should be defined in the user interface.""" return True def can_add_to_toolbar(self, action): - """ Returns whether the toolbar action should be defined in the user - interface. + """Returns whether the toolbar action should be defined in the user + interface. """ return True def perform(self, action, action_event=None): - """ Performs the action described by a specified Action object. - """ + """Performs the action described by a specified Action object.""" getattr(self.editor, action.action)() class TableSearchHandler(Handler): - """ Handler for saerching a table. - """ + """Handler for saerching a table.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -1605,8 +1566,7 @@ class TableSearchHandler(Handler): status = Str() def handler_find_next_changed(self, info): - """ Handles the user clicking the **Find** button. - """ + """Handles the user clicking the **Find** button.""" if info.initialized: editor = self.editor items = editor.model.get_filtered_items() @@ -1621,8 +1581,7 @@ def handler_find_next_changed(self, info): self.status = "No more matches found" def handler_find_previous_changed(self, info): - """ Handles the user clicking the **Find previous** button. - """ + """Handles the user clicking the **Find previous** button.""" if info.initialized: editor = self.editor items = editor.model.get_filtered_items() @@ -1637,8 +1596,7 @@ def handler_find_previous_changed(self, info): self.status = "No more matches found" def handler_select_changed(self, info): - """ Handles the user clicking the **Select** button. - """ + """Handles the user clicking the **Select** button.""" if info.initialized: editor = self.editor filter = info.object.filter @@ -1655,8 +1613,7 @@ def handler_select_changed(self, info): self.status = "%d items selected" % len(items) def handler_OK_changed(self, info): - """ Handles the user clicking the OK button. - """ + """Handles the user clicking the OK button.""" if info.initialized: self.close(info, True) diff --git a/traitsui/wx/table_model.py b/traitsui/wx/table_model.py index 15a2aa6e9..65a7872d3 100644 --- a/traitsui/wx/table_model.py +++ b/traitsui/wx/table_model.py @@ -49,8 +49,7 @@ class TraitGridSelection(HasPrivateTraits): - """ Structure for holding specification information. - """ + """Structure for holding specification information.""" #: The selected object obj = Any() @@ -60,8 +59,7 @@ class TraitGridSelection(HasPrivateTraits): class TableModel(GridModel): - """ Model for table data. - """ + """Model for table data.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -86,8 +84,7 @@ class TableModel(GridModel): auto_add_row = Any() def __init__(self, **traits): - """ Initializes the object. - """ + """Initializes the object.""" super().__init__(**traits) # Attach trait handlers to the list object: @@ -119,8 +116,7 @@ def __init__(self, **traits): # -- TableModel Interface ------------------------------------------------- def dispose(self): - """ Disposes of the model when it is no longer needed. - """ + """Disposes of the model when it is no longer needed.""" editor = self.editor object = editor.context_object name = " " + editor.extended_name @@ -145,26 +141,26 @@ def dispose(self): self.editor = None def get_filtered_items(self): - """ Returns all model items matching the current filter. - """ + """Returns all model items matching the current filter.""" return self.__filtered_items() def get_filtered_item(self, index=0): - """ Returns a single specified item from those items matching the - current filter. + """Returns a single specified item from those items matching the + current filter. """ try: return self.__filtered_items()[index] except Exception: logger.exception( "TableModel error: Request for invalid row %d out of %d", - index, len(self.__filtered_items()) + index, + len(self.__filtered_items()), ) return None def raw_index_of(self, row): - """ Returns the raw, unfiltered index corresponding to a specified - filtered index. + """Returns the raw, unfiltered index corresponding to a specified + filtered index. """ if self._filtered_cache is None: return row @@ -172,8 +168,7 @@ def raw_index_of(self, row): return self.editor.filtered_indices[row] def insert_filtered_item_after(self, index, item): - """ Inserts an object after a specified filtered index. - """ + """Inserts an object after a specified filtered index.""" mapped_index = 0 n = len(self.editor.filtered_indices) if index >= n: @@ -189,8 +184,7 @@ def insert_filtered_item_after(self, index, item): return (mapped_index, sorted) def delete_filtered_item_at(self, index): - """ Deletes the object at the specified filtered index. - """ + """Deletes the object at the specified filtered index.""" if index >= len(self.editor.filtered_indices): raise IndexError @@ -202,15 +196,13 @@ def delete_filtered_item_at(self, index): return (mapped_index, object) def update_columns(self): - """ Updates the table view when columns have been changed. - """ + """Updates the table view when columns have been changed.""" self._columns = None self.fire_structure_changed() self.editor.refresh() def no_column_sort(self): - """ Resets any sorting being performed on the underlying model. - """ + """Resets any sorting being performed on the underlying model.""" self._sorter = self._filtered_cache = None self.column_sorted = GridSortEvent(index=-1) # self.fire_structure_changed() @@ -219,15 +211,13 @@ def no_column_sort(self): @observe(trait("filter").match(lambda name, ctrait: True)) def _filter_modified(self, event): - """ Handles the contents of the filter being changed. - """ + """Handles the contents of the filter being changed.""" self._filtered_cache = None self.fire_structure_changed() self.editor.filter_modified() def _click_changed(self, event): - """ Handles the grid firing a 'click' event. - """ + """Handles the grid firing a 'click' event.""" row, col = event # Fire the same event on the editor after mapping it to a model object @@ -247,8 +237,7 @@ def _click_changed(self, event): column.on_click(object) def _dclick_changed(self, event): - """ Handles the grid firing a 'dclick' event. - """ + """Handles the grid firing a 'dclick' event.""" row, col = event # Fire the same event on the editor after mapping it to a model object @@ -261,8 +250,7 @@ def _dclick_changed(self, event): column.on_dclick(object) def on_auto_add_row(self): - """ Handles the user modifying the current 'auto_add' mode row. - """ + """Handles the user modifying the current 'auto_add' mode row.""" object = self.auto_add_row object.on_trait_change(self.on_auto_add_row, remove=True) @@ -277,31 +265,29 @@ def on_auto_add_row(self): # -- GridModel Interface -------------------------------------------------- def get_column_count(self): - """ Returns the number of columns for this table. - """ + """Returns the number of columns for this table.""" return len(self.__get_columns()) def get_column_name(self, index): - """ Returns the label of the column specified by the (zero-based) index. - """ + """Returns the label of the column specified by the (zero-based) index.""" return self.__get_column(index).get_label() def get_column_size(self, index): - """ Returns the size in pixels of the column indexed by *index*. - A value of -1 or None means to use the default. + """Returns the size in pixels of the column indexed by *index*. + A value of -1 or None means to use the default. """ return self.__get_column(index).get_width() def get_cols_drag_value(self, cols): - """ Returns the value to use when the specified columns are dragged or - copied and pasted. The parameter *cols* is a list of column indexes. + """Returns the value to use when the specified columns are dragged or + copied and pasted. The parameter *cols* is a list of column indexes. """ return [self.__get_data_column(col) for col in cols] def get_cols_selection_value(self, cols): - """ Returns a list of TraitGridSelection objects containing the - objects corresponding to the grid rows and the traits corresponding - to the specified columns. + """Returns a list of TraitGridSelection objects containing the + objects corresponding to the grid rows and the traits corresponding + to the specified columns. """ values = [] for obj in self.__items(False): @@ -316,8 +302,7 @@ def get_cols_selection_value(self, cols): return values def sort_by_column(self, col, reverse=False): - """ Sorts the model data by the column indexed by *col*. - """ + """Sorts the model data by the column indexed by *col*.""" # Make sure we allow sorts by column: factory = self.editor.factory if not factory.sortable: @@ -339,46 +324,43 @@ def sort_by_column(self, col, reverse=False): self.column_sorted = GridSortEvent(index=col, reversed=reverse) def is_column_read_only(self, index): - """ Returns True if the column specified by the zero-based *index* is - read-only. + """Returns True if the column specified by the zero-based *index* is + read-only. """ return not self.__get_column(index).editable def get_row_count(self): - """ Return the number of rows for this table. - """ + """Return the number of rows for this table.""" return len(self.__filtered_items()) def get_row_name(self, index): - """ Return the name of the row specified by the (zero-based) *index*. - """ + """Return the name of the row specified by the (zero-based) *index*.""" return "" def get_rows_drag_value(self, rows): - """ Returns the value to use when the specified rows are dragged or - copied and pasted. The parameter *rows* is a list of row indexes. - If there is only one row listed, then return the corresponding trait - object. If more than one row is listed, then return a list of objects. + """Returns the value to use when the specified rows are dragged or + copied and pasted. The parameter *rows* is a list of row indexes. + If there is only one row listed, then return the corresponding trait + object. If more than one row is listed, then return a list of objects. """ items = self.__filtered_items() return [items[row] for row in rows] def get_rows_selection_value(self, rows): - """ Returns a list of TraitGridSelection objects containing the - object corresponding to the selected rows. + """Returns a list of TraitGridSelection objects containing the + object corresponding to the selected rows. """ items = self.__filtered_items() return [TraitGridSelection(obj=items[row]) for row in rows] def is_row_read_only(self, index): - """ Returns True if the row specified by the zero-based *index* is - read-only. + """Returns True if the row specified by the zero-based *index* is + read-only. """ return False def get_cell_editor(self, row, col): - """ Returns the editor for the specified cell. - """ + """Returns the editor for the specified cell.""" if self.editor is None: return None @@ -404,33 +386,32 @@ def get_cell_editor(self, row, col): ) def get_cell_renderer(self, row, col): - """ Returns the renderer for the specified cell. - """ + """Returns the renderer for the specified cell.""" return self.__get_column(col).get_renderer(self.get_filtered_item(row)) def get_cell_drag_value(self, row, col): - """ Returns the value to use when the specified cell is dragged or - copied and pasted. + """Returns the value to use when the specified cell is dragged or + copied and pasted. """ return self.__get_column(col).get_drag_value( self.get_filtered_item(row) ) def get_cell_selection_value(self, row, col): - """ Returns a TraitGridSelection object specifying the data stored - in the table at (*row*, *col*). + """Returns a TraitGridSelection object specifying the data stored + in the table at (*row*, *col*). """ return TraitGridSelection( obj=self.get_filtered_item(row), name=self.__get_column_name(col) ) def resolve_selection(self, selection_list): - """ Returns a list of (row, col) grid-cell coordinates that - correspond to the objects in *selection_list*. For each coordinate, - if the row is -1, it indicates that the entire column is selected. - Likewise coordinates with a column of -1 indicate an entire row - that is selected. For the TableModel, the objects in - *selection_list* must be TraitGridSelection objects. + """Returns a list of (row, col) grid-cell coordinates that + correspond to the objects in *selection_list*. For each coordinate, + if the row is -1, it indicates that the entire column is selected. + Likewise coordinates with a column of -1 indicate an entire row + that is selected. For the TableModel, the objects in + *selection_list* must be TraitGridSelection objects. """ items = self.__filtered_items() cells = [] @@ -453,8 +434,8 @@ def resolve_selection(self, selection_list): return cells def get_cell_context_menu(self, row, col): - """ Returns a Menu object that generates the appropriate context - menu for this cell. + """Returns a Menu object that generates the appropriate context + menu for this cell. """ column = self.__get_column(col) menu = column.get_menu(self.get_filtered_item(row)) @@ -476,8 +457,7 @@ def get_cell_context_menu(self, row, col): return None def get_value(self, row, col): - """ Returns the value stored in the table at (*row*, *col*). - """ + """Returns the value stored in the table at (*row*, *col*).""" object = self.get_filtered_item(row) if object is self.auto_add_row: return "" @@ -499,73 +479,72 @@ def get_value(self, row, col): return value def is_valid_cell_value(self, row, col, value): - """ Tests whether *value* is valid for the cell at (*row*, *col*). - Returns True if value is acceptable, and False otherwise. """ + """Tests whether *value* is valid for the cell at (*row*, *col*). + Returns True if value is acceptable, and False otherwise.""" return self.__get_column(col).is_droppable( self.get_filtered_item(row), value ) def is_cell_empty(self, row, col): - """ Returns True if the cell at (*row*, *col*) has a None value, and - False otherwise. + """Returns True if the cell at (*row*, *col*) has a None value, and + False otherwise. """ return self.get_value(row, col) is None def is_cell_read_only(self, row, col): - """ Returns True if the cell at (*row*, *col*) is read-only, and False - otherwise. + """Returns True if the cell at (*row*, *col*) is read-only, and False + otherwise. """ return not self.__get_column(col).is_editable( self.get_filtered_item(row) ) def get_cell_bg_color(self, row, col): - """ Returns a wxColour object specifying the background color - of the specified cell. + """Returns a wxColour object specifying the background color + of the specified cell. """ return self.__get_column(col).get_cell_color( self.get_filtered_item(row) ) def get_cell_text_color(self, row, col): - """ Returns a wxColour object specifying the text color of the - specified cell. + """Returns a wxColour object specifying the text color of the + specified cell. """ column = self.__get_column(col) item = self.get_filtered_item(row) return column.get_text_color(item) def get_cell_font(self, row, col): - """ Returns a wxFont object specifying the font of the specified cell. - """ + """Returns a wxFont object specifying the font of the specified cell.""" return self.__get_column(col).get_text_font( self.get_filtered_item(row) ) def get_cell_halignment(self, row, col): - """ Returns a string specifying the horizontal alignment of the - specified cell. + """Returns a string specifying the horizontal alignment of the + specified cell. - Returns 'left' for left alignment, 'right' for right alignment, - or 'center' for center alignment. + Returns 'left' for left alignment, 'right' for right alignment, + or 'center' for center alignment. """ return self.__get_column(col).get_horizontal_alignment( self.get_filtered_item(row) ) def get_cell_valignment(self, row, col): - """ Returns a string specifying the vertical alignment of the - specified cell. + """Returns a string specifying the vertical alignment of the + specified cell. - Returns 'top' for top alignment, 'bottom' for bottom alignment, - or 'center' for center alignment. + Returns 'top' for top alignment, 'bottom' for bottom alignment, + or 'center' for center alignment. """ return self.__get_column(col).get_vertical_alignment( self.get_filtered_item(row) ) def _insert_rows(self, pos, num_rows): - """ Inserts *num_rows* at *pos*; fires an event only if a factory + """Inserts *num_rows* at *pos*; fires an event only if a factory method for new rows is defined or the model is not empty. Otherwise, it returns 0. """ @@ -590,8 +569,7 @@ def _insert_rows(self, pos, num_rows): return count def _delete_rows(self, pos, num_rows): - """ Removes rows *pos* through *pos* + *num_rows* from the model. - """ + """Removes rows *pos* through *pos* + *num_rows* from the model.""" row_count = self.get_rows_count() if (pos + num_rows) > row_count: num_rows = row_count - pos @@ -599,10 +577,10 @@ def _delete_rows(self, pos, num_rows): return self._delete_rows_from_model(pos, num_rows) def _set_value(self, row, col, value): - """ Sets the value of the cell at (*row*, *col*) to *value*. + """Sets the value of the cell at (*row*, *col*) to *value*. - Raises a ValueError if the value is vetoed or the cell at - the specified position does not exist. + Raises a ValueError if the value is vetoed or the cell at + the specified position does not exist. """ new_rows = 0 column = self.__get_column(col) @@ -627,8 +605,8 @@ def _set_value(self, row, col, value): return new_rows def _move_column(self, frm, to): - """ Moves a specified **frm** column to before the specified **to** - column. Returns **True** if successful; **False** otherwise. + """Moves a specified **frm** column to before the specified **to** + column. Returns **True** if successful; **False** otherwise. """ to_column = None if to < len(self.__get_columns()): @@ -637,21 +615,19 @@ def _move_column(self, frm, to): return self.editor.move_column(self.__get_column(frm), to_column) def _set_data_on_row(self, row, column, value): - """ Sets the cell specified by (*row*, *col*) to *value, which - can be either a member of the row object, or a no-argument method - on that object. + """Sets the cell specified by (*row*, *col*) to *value, which + can be either a member of the row object, or a no-argument method + on that object. """ column.set_value(row, value) def _insert_rows_into_model(self, pos, new_data): - """ Inserts the given new rows into the model. - """ + """Inserts the given new rows into the model.""" raw_pos = self.raw_index_of(pos) self.__items()[raw_pos:raw_pos] = new_data def _delete_rows_from_model(self, pos, num_rows): - """ Deletes the specified rows from the model. - """ + """Deletes the specified rows from the model.""" raw_rows = sorted( [self.raw_index_of(i) for i in range(pos, pos + num_rows)] ) @@ -663,16 +639,14 @@ def _delete_rows_from_model(self, pos, num_rows): return num_rows def _on_data_changed(self): - """ Forces the grid to refresh when the underlying list changes. - """ + """Forces the grid to refresh when the underlying list changes.""" # Invalidate the current cache (if any): self._filtered_cache = None self.fire_structure_changed() def _mouse_cell_changed(self, new): - """ Handles the user mousing over a specified cell. - """ + """Handles the user mousing over a specified cell.""" row, col = new column = self.__get_column(col) object = self.get_filtered_item(row) @@ -708,8 +682,8 @@ def _mouse_cell_changed(self, new): ) def _bounds_for(self, row, col): - """ Returns the coordinates and size of the specified cell in the form: - ( x, y, dx, dy ). + """Returns the coordinates and size of the specified cell in the form: + ( x, y, dx, dy ). """ grid = self.editor.grid coords = wxg.GridCellCoords(row, col) @@ -719,8 +693,7 @@ def _bounds_for(self, row, col): return (x, y, dx, dy) def _sort_model(self): - """ Sorts the underlying model if that is what the user requested. - """ + """Sorts the underlying model if that is what the user requested.""" editor = self.editor sorted = editor.factory.sort_model and (self._sorter is not None) if sorted: @@ -732,8 +705,7 @@ def _sort_model(self): return sorted def __items(self, ordered=True): - """ Returns the raw list of model objects. - """ + """Returns the raw list of model objects.""" result = self.editor.value if not isinstance(result, SequenceTypes): return [result] @@ -744,8 +716,7 @@ def __items(self, ordered=True): return result def __filtered_items(self): - """ Returns the list of all model objects that pass the current filter. - """ + """Returns the list of all model objects that pass the current filter.""" fc = self._filtered_cache if fc is None: items = self.__items() @@ -777,8 +748,7 @@ def __filtered_items(self): return fc def __get_data_column(self, col): - """ Returns a list of model data from the column indexed by *col*. - """ + """Returns a list of model data from the column indexed by *col*.""" column = self.__get_column(col) return [column.get_value(item) for item in self.__filtered_items()] diff --git a/traitsui/wx/tabular_editor.py b/traitsui/wx/tabular_editor.py index 454316ea8..30111ab84 100644 --- a/traitsui/wx/tabular_editor.py +++ b/traitsui/wx/tabular_editor.py @@ -58,8 +58,7 @@ class TextEditMixin(listmix.TextEditMixin): def __init__(self, edit_labels): - """ edit_labels controls whether the first column is editable - """ + """edit_labels controls whether the first column is editable""" self.edit_labels = edit_labels listmix.TextEditMixin.__init__(self) @@ -71,8 +70,7 @@ def OpenEditor(self, col, row): class wxListCtrl(wx.ListCtrl, TextEditMixin): - """ Subclass of wx.ListCtrl to provide correct virtual list behavior. - """ + """Subclass of wx.ListCtrl to provide correct virtual list behavior.""" def __init__( self, @@ -135,8 +133,7 @@ def SetVirtualData(self, row, col, text): # row, col, text ) def OnGetItemAttr(self, row): - """ Returns the display attributes to use for the specified list item. - """ + """Returns the display attributes to use for the specified list item.""" # fixme: There appears to be a bug in wx in that they do not correctly # manage the reference count for the returned object, and it seems to be # gc'ed before they finish using it. So we store an object reference to @@ -160,8 +157,7 @@ def OnGetItemAttr(self, row): return attr def OnGetItemImage(self, row): - """ Returns the image index to use for the specified list item. - """ + """Returns the image index to use for the specified list item.""" editor = self._editor image = editor._get_image( editor.adapter.get_image(editor.object, editor.name, row, 0) @@ -172,8 +168,7 @@ def OnGetItemImage(self, row): return -1 def OnGetItemColumnImage(self, row, column): - """ Returns the image index to use for the specified list item. - """ + """Returns the image index to use for the specified list item.""" editor = self._editor image = editor._get_image( editor.adapter.get_image(editor.object, editor.name, row, column) @@ -184,15 +179,14 @@ def OnGetItemColumnImage(self, row, column): return -1 def OnGetItemText(self, row, column): - """ Returns the text to use for the specified list item. - """ + """Returns the text to use for the specified list item.""" editor = self._editor return editor.adapter.get_text(editor.object, editor.name, row, column) class TabularEditor(Editor): - """ A traits UI editor for editing tabular data (arrays, list of tuples, - lists of objects, etc). + """A traits UI editor for editing tabular data (arrays, list of tuples, + lists of objects, etc). """ # -- Trait Definitions ---------------------------------------------------- @@ -257,8 +251,8 @@ class TabularEditor(Editor): _update_visible = Bool(False) def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory @@ -300,14 +294,18 @@ def init(self, parent): # Set up the list control's event handlers: id = control.GetId() parent.Bind(wx.EVT_LIST_BEGIN_DRAG, self._begin_drag, id=id) - parent.Bind(wx.EVT_LIST_BEGIN_LABEL_EDIT, self._begin_label_edit, id=id) + parent.Bind( + wx.EVT_LIST_BEGIN_LABEL_EDIT, self._begin_label_edit, id=id + ) parent.Bind(wx.EVT_LIST_END_LABEL_EDIT, self._end_label_edit, id=id) parent.Bind(wx.EVT_LIST_ITEM_SELECTED, self._item_selected, id=id) parent.Bind(wx.EVT_LIST_ITEM_DESELECTED, self._item_selected, id=id) parent.Bind(wx.EVT_LIST_KEY_DOWN, self._key_down, id=id) parent.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self._item_activated, id=id) parent.Bind(wx.EVT_LIST_COL_END_DRAG, self._size_modified, id=id) - parent.Bind(wx.EVT_LIST_COL_RIGHT_CLICK, self._column_right_clicked, id=id) + parent.Bind( + wx.EVT_LIST_COL_RIGHT_CLICK, self._column_right_clicked, id=id + ) parent.Bind(wx.EVT_LIST_COL_CLICK, self._column_clicked, id=id) control.Bind(wx.EVT_LEFT_DOWN, self._left_down) control.Bind(wx.EVT_LEFT_DCLICK, self._left_dclick) @@ -388,8 +386,7 @@ def init(self, parent): self.set_tooltip() def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" # Remove all of the wx event handlers: control = self.control parent = control.GetParent() @@ -426,8 +423,7 @@ def dispose(self): super().dispose() def _update_changed(self, event): - """ Handles the 'update' event being fired. - """ + """Handles the 'update' event being fired.""" if event is True: self.update_editor() elif isinstance(event, int): @@ -436,13 +432,11 @@ def _update_changed(self, event): self._refresh_editor(event) def refresh_editor(self, item, name, old, new): - """ Handles a table item attribute being changed. - """ + """Handles a table item attribute being changed.""" self._refresh_editor(item) def _refresh_editor(self, item): - """ Handles a table item being changed. - """ + """Handles a table item being changed.""" adapter = self.adapter object, name = self.object, self.name agi = adapter.get_item @@ -454,23 +448,22 @@ def _refresh_editor(self, item): self.update_editor() def _refresh_row(self, row): - """ Updates the editor control when a specified table row changes. - """ + """Updates the editor control when a specified table row changes.""" self.control.RefreshRect( self.control.GetItemRect(row, wx.LIST_RECT_BOUNDS) ) def _update_editor(self, object, name, old_value, new_value): - """ Performs updates when the object trait changes. - Overloads traitsui.editor.UIEditor + """Performs updates when the object trait changes. + Overloads traitsui.editor.UIEditor """ self._update_visible = True super()._update_editor(object, name, old_value, new_value) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ control = self.control n = self.adapter.len(self.object, self.name) @@ -505,9 +498,13 @@ def update_editor(self): return if 0 <= (row - top) < pn: - control.EnsureVisible(min(top + pn - 2, control.GetItemCount() - 1)) + control.EnsureVisible( + min(top + pn - 2, control.GetItemCount() - 1) + ) elif row < top: - control.EnsureVisible(min(row + pn - 1, control.GetItemCount() - 1)) + control.EnsureVisible( + min(row + pn - 1, control.GetItemCount() - 1) + ) else: control.EnsureVisible(row) @@ -523,8 +520,7 @@ def update_editor(self): # -- Trait Event Handlers ------------------------------------------------- def _selected_changed(self, selected): - """ Handles the editor's 'selected' trait being changed. - """ + """Handles the editor's 'selected' trait being changed.""" if not self._no_update: if selected is None: for row in self._get_selected(): @@ -540,8 +536,7 @@ def _selected_changed(self, selected): pass def _selected_row_changed(self, old, new): - """ Handles the editor's 'selected_index' trait being changed. - """ + """Handles the editor's 'selected_index' trait being changed.""" if not self._no_update: if new < 0: if old >= 0: @@ -552,8 +547,7 @@ def _selected_row_changed(self, old, new): ) def _multi_selected_changed(self, selected): - """ Handles the editor's 'multi_selected' trait being changed. - """ + """Handles the editor's 'multi_selected' trait being changed.""" if not self._no_update: values = self.value try: @@ -564,8 +558,7 @@ def _multi_selected_changed(self, selected): pass def _multi_selected_items_changed(self, event): - """ Handles the editor's 'multi_selected' trait being modified. - """ + """Handles the editor's 'multi_selected' trait being modified.""" values = self.value try: self._multi_selected_rows_items_changed( @@ -579,8 +572,7 @@ def _multi_selected_items_changed(self, event): pass def _multi_selected_rows_changed(self, selected_rows): - """ Handles the editor's 'multi_selected_rows' trait being changed. - """ + """Handles the editor's 'multi_selected_rows' trait being changed.""" if not self._no_update: control = self.control selected = self._get_selected() @@ -599,8 +591,7 @@ def _multi_selected_rows_changed(self, selected_rows): control.SetItemState(row, 0, wx.LIST_STATE_SELECTED) def _multi_selected_rows_items_changed(self, event): - """ Handles the editor's 'multi_selected_rows' trait being modified. - """ + """Handles the editor's 'multi_selected_rows' trait being modified.""" control = self.control # Remove all items that are no longer selected: @@ -619,28 +610,24 @@ def _refresh_changed(self): # -- List Control Event Handlers ------------------------------------------ def _left_down(self, event): - """ Handles the left mouse button being pressed. - """ + """Handles the left mouse button being pressed.""" self._mouse_click(event, "clicked") def _left_dclick(self, event): - """ Handles the left mouse button being double clicked. - """ + """Handles the left mouse button being double clicked.""" self._mouse_click(event, "dclicked") def _right_down(self, event): - """ Handles the right mouse button being pressed. - """ + """Handles the right mouse button being pressed.""" self._mouse_click(event, "right_clicked") def _right_dclick(self, event): - """ Handles the right mouse button being double clicked. - """ + """Handles the right mouse button being double clicked.""" self._mouse_click(event, "right_dclicked") def _begin_drag(self, event): - """ Handles the user beginning a drag operation with the left mouse - button. + """Handles the user beginning a drag operation with the left mouse + button. """ if PythonDropSource is not None: adapter = self.adapter @@ -685,16 +672,14 @@ def _begin_drag(self, event): self._drag_local = False def _begin_label_edit(self, event): - """ Handles the user starting to edit an item label. - """ + """Handles the user starting to edit an item label.""" if not self.adapter.get_can_edit( self.object, self.name, event.GetIndex() ): event.Veto() def _end_label_edit(self, event): - """ Handles the user finishing editing an item label. - """ + """Handles the user finishing editing an item label.""" self.adapter.set_text( self.object, self.name, @@ -705,8 +690,7 @@ def _end_label_edit(self, event): self.row = event.GetIndex() + 1 def _item_selected(self, event): - """ Handles an item being selected. - """ + """Handles an item being selected.""" self._no_update = True try: get_item = self.adapter.get_item @@ -727,16 +711,14 @@ def _item_selected(self, event): self._no_update = False def _item_activated(self, event): - """ Handles an item being activated (double-clicked or enter pressed). - """ + """Handles an item being activated (double-clicked or enter pressed).""" self.activated_row = event.GetIndex() self.activated = self.adapter.get_item( self.object, self.name, self.activated_row ) def _key_down(self, event): - """ Handles the user pressing a key in the list control. - """ + """Handles the user pressing a key in the list control.""" key = event.GetKeyCode() if key == wx.WXK_PAGEDOWN: self._append_new() @@ -754,8 +736,7 @@ def _key_down(self, event): event.Skip() def _column_right_clicked(self, event): - """ Handles the user right-clicking a column header. - """ + """Handles the user right-clicking a column header.""" column = event.GetColumn() if (self._cached_widths is not None) and ( 0 <= column < len(self._cached_widths) @@ -764,8 +745,7 @@ def _column_right_clicked(self, event): self._size_modified(event) def _column_clicked(self, event): - """ Handles the right mouse button being double clicked. - """ + """Handles the right mouse button being double clicked.""" editor_event = TabularEditorEvent( editor=self, row=0, column=event.GetColumn() ) @@ -774,8 +754,7 @@ def _column_clicked(self, event): event.Skip() def _size_modified(self, event): - """ Handles the size of the list control being changed. - """ + """Handles the size of the list control being changed.""" control = self.control n = control.GetColumnCount() if n == 1: @@ -787,8 +766,7 @@ def _size_modified(self, event): event.Skip() def _motion(self, event): - """ Handles the user moving the mouse. - """ + """Handles the user moving the mouse.""" x = event.GetX() column = self._get_column(x) row, flags = self.control.HitTest(wx.Point(x, event.GetY())) @@ -809,8 +787,7 @@ def _motion(self, event): # -- Drag and Drop Event Handlers ----------------------------------------- def wx_dropped_on(self, x, y, data, drag_result): - """ Handles a Python object being dropped on the list control. - """ + """Handles a Python object being dropped on the list control.""" row, flags = self.control.HitTest(wx.Point(x, y)) # If the user dropped it on an empty list, set the target as past the @@ -846,8 +823,8 @@ def wx_dropped_on(self, x, y, data, drag_result): return wx.DragNone def _wx_dropped_on(self, row, item): - """ Helper method for handling a single item dropped on the list - control. + """Helper method for handling a single item dropped on the list + control. """ adapter = self.adapter object, name = self.object, self.name @@ -874,8 +851,7 @@ def _wx_dropped_on(self, row, item): rows[i] += 1 def wx_drag_over(self, x, y, data, drag_result): - """ Handles a Python object being dragged over the tree. - """ + """Handles a Python object being dragged over the tree.""" if isinstance(data, list): rc = wx.DragNone for item in data: @@ -909,8 +885,8 @@ def wx_drag_over(self, x, y, data, drag_result): # -- UI preference save/restore interface --------------------------------- def restore_prefs(self, prefs): - """ Restores any saved user preference information associated with the - editor. + """Restores any saved user preference information associated with the + editor. """ self._cached_widths = cws = prefs.get("cached_widths") if cws is not None: @@ -920,8 +896,7 @@ def restore_prefs(self, prefs): set_column_width(i, width) def save_prefs(self): - """ Returns any user preference information associated with the editor. - """ + """Returns any user preference information associated with the editor.""" cws = self._cached_widths if cws is not None: cws = [cw if cw is not None and cw >= 0 else None for cw in cws] @@ -931,15 +906,13 @@ def save_prefs(self): # -- Private Methods ------------------------------------------------------ def _refresh(self): - """ Refreshes the contents of the editor's list control. - """ + """Refreshes the contents of the editor's list control.""" n = self.adapter.len(self.object, self.name) if n > 0: self.control.RefreshItems(0, n - 1) def _rebuild(self): - """ Rebuilds the contents of the editor's list control. - """ + """Rebuilds the contents of the editor's list control.""" control = self.control control.ClearAll() adapter, object, name = self.adapter, self.object, self.name @@ -957,15 +930,14 @@ def _rebuild(self): self._set_column_widths() def _rebuild_all(self): - """ Rebuilds the structure of the list control, then refreshes its - contents. + """Rebuilds the structure of the list control, then refreshes its + contents. """ self._rebuild() self.update_editor() def _set_column_widths(self): - """ Set the column widths for the current set of columns. - """ + """Set the column widths for the current set of columns.""" control = self.control if control is None: return @@ -1023,8 +995,7 @@ def _set_column_widths(self): control.Thaw() def _add_image(self, image_resource): - """ Adds a new image to the wx.ImageList and its associated mapping. - """ + """Adds a new image to the wx.ImageList and its associated mapping.""" bitmap = image_resource.create_image().ConvertToBitmap() image_list = self._image_list @@ -1041,8 +1012,7 @@ def _add_image(self, image_resource): return row def _get_image(self, image): - """ Converts a user specified image to a wx.ListCtrl image index. - """ + """Converts a user specified image to a wx.ListCtrl image index.""" if isinstance(image, str): self.image = image image = self.image @@ -1057,8 +1027,7 @@ def _get_image(self, image): return self.images.get(image) def _get_selected(self): - """ Returns a list of the rows of all currently selected list items. - """ + """Returns a list of the rows of all currently selected list items.""" selected = [] item = -1 control = self.control @@ -1079,8 +1048,7 @@ def _get_selected(self): return selected def _append_new(self): - """ Append a new item to the end of the list control. - """ + """Append a new item to the end of the list control.""" if "append" in self.factory.operations: adapter = self.adapter self.row = self.control.GetItemCount() @@ -1093,8 +1061,7 @@ def _append_new(self): ) def _insert_current(self): - """ Inserts a new item after the currently selected list control item. - """ + """Inserts a new item after the currently selected list control item.""" if "insert" in self.factory.operations: selected = self._get_selected() if len(selected) == 1: @@ -1109,8 +1076,7 @@ def _insert_current(self): self.edit = True def _delete_current(self): - """ Deletes the currently selected items from the list control. - """ + """Deletes the currently selected items from the list control.""" if "delete" in self.factory.operations: selected = self._get_selected() if len(selected) == 0: @@ -1130,8 +1096,7 @@ def _delete_current(self): self.multi_selected_rows = [] def _move_up_current(self): - """ Moves the currently selected item up one line in the list control. - """ + """Moves the currently selected item up one line in the list control.""" if "move" in self.factory.operations: selected = self._get_selected() if len(selected) == 1: @@ -1145,8 +1110,7 @@ def _move_up_current(self): self.row = row - 1 def _move_down_current(self): - """ Moves the currently selected item down one line in the list control. - """ + """Moves the currently selected item down one line in the list control.""" if "move" in self.factory.operations: selected = self._get_selected() if len(selected) == 1: @@ -1160,16 +1124,14 @@ def _move_down_current(self): self.row = row + 1 def _edit_current(self): - """ Allows the user to edit the current item in the list control. - """ + """Allows the user to edit the current item in the list control.""" if "edit" in self.factory.operations and self.factory.editable_labels: selected = self._get_selected() if len(selected) == 1: self.control.EditLabel(selected[0]) def _get_column(self, x, translate=False): - """ Returns the column index corresponding to a specified x position. - """ + """Returns the column index corresponding to a specified x position.""" if x >= 0: control = self.control for i in range(control.GetColumnCount()): @@ -1185,8 +1147,8 @@ def _get_column(self, x, translate=False): return None def _mouse_click(self, event, trait): - """ Generate a TabularEditorEvent event for a specified mouse event and - editor trait name. + """Generate a TabularEditorEvent event for a specified mouse event and + editor trait name. """ x = event.GetX() row, flags = self.control.HitTest(wx.Point(x, event.GetY())) diff --git a/traitsui/wx/text_editor.py b/traitsui/wx/text_editor.py index 22f9c8f67..3af372d1f 100644 --- a/traitsui/wx/text_editor.py +++ b/traitsui/wx/text_editor.py @@ -31,8 +31,7 @@ class SimpleEditor(Editor): - """ Simple style text editor, which displays a text field. - """ + """Simple style text editor, which displays a text field.""" #: Flag for window styles: base_style = 0 @@ -48,8 +47,8 @@ class SimpleEditor(Editor): evaluate = evaluate_trait def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory style = self.base_style @@ -70,7 +69,9 @@ def init(self, parent): control = wx.TextCtrl( parent, -1, self.str_value, style=style | wx.TE_PROCESS_ENTER ) - parent.Bind(wx.EVT_TEXT_ENTER, self.update_object, id=control.GetId()) + parent.Bind( + wx.EVT_TEXT_ENTER, self.update_object, id=control.GetId() + ) else: control = wx.TextCtrl(parent, -1, self.str_value, style=style) @@ -86,8 +87,7 @@ def init(self, parent): self.set_tooltip() def update_object(self, event): - """ Handles the user entering input data in the edit control. - """ + """Handles the user entering input data in the edit control.""" if isinstance(event, wx.FocusEvent): # Ensure that the base class' focus event handlers are run, some # built-in behavior may break on some platforms otherwise. @@ -107,8 +107,8 @@ def update_object(self, event): pass def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ user_value = self._get_user_value() try: @@ -128,8 +128,7 @@ def update_editor(self): self.set_error_state(False) def _get_user_value(self): - """ Gets the actual value corresponding to what the user typed. - """ + """Gets the actual value corresponding to what the user typed.""" value = self.control.GetValue() try: value = self.evaluate(value) @@ -145,8 +144,7 @@ def _get_user_value(self): return ret def error(self, excp): - """ Handles an error that occurs while setting the object's trait value. - """ + """Handles an error that occurs while setting the object's trait value.""" if self._error is None: self._error = True self.ui.errors += 1 @@ -154,26 +152,23 @@ def error(self, excp): self.set_error_state(True) def in_error_state(self): - """ Returns whether or not the editor is in an error state. - """ + """Returns whether or not the editor is in an error state.""" return self.invalid or self._error class CustomEditor(SimpleEditor): - """ Custom style of text editor, which displays a multi-line text field. - """ + """Custom style of text editor, which displays a multi-line text field.""" #: Flag for window style. This value overrides the default. base_style = wx.TE_MULTILINE class ReadonlyEditor(BaseReadonlyEditor): - """ Read-only style of text editor, which displays a read-only text field. - """ + """Read-only style of text editor, which displays a read-only text field.""" def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ super().init(parent) @@ -185,8 +180,8 @@ def init(self, parent): control.Bind(wx.EVT_LEFT_UP, self._left_up) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ control = self.control new_value = self.str_value @@ -203,8 +198,7 @@ def update_editor(self): control.SetLabel(new_value) def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" if self.factory.view is not None: control = self.control control.Unbind(wx.EVT_ENTER_WINDOW) diff --git a/traitsui/wx/time_editor.py b/traitsui/wx/time_editor.py index b5588917f..ab2550ae0 100644 --- a/traitsui/wx/time_editor.py +++ b/traitsui/wx/time_editor.py @@ -78,10 +78,10 @@ class CustomEditor(SimpleEditor): class ReadonlyEditor(TextReadonlyEditor): - """ Use a TextEditor for the view. """ + """Use a TextEditor for the view.""" def _get_str_value(self): - """ Replace the default string value with our own time version. """ + """Replace the default string value with our own time version.""" if self.value is None: return self.factory.message else: diff --git a/traitsui/wx/title_editor.py b/traitsui/wx/title_editor.py index 917ad8a2d..cfc361901 100644 --- a/traitsui/wx/title_editor.py +++ b/traitsui/wx/title_editor.py @@ -35,8 +35,8 @@ class _TitleEditor(Editor): # ------------------------------------------------------------------------- def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ self._control = HeadingText(parent) self.control = self._control.control @@ -47,8 +47,8 @@ def init(self, parent): # ------------------------------------------------------------------------- def update_editor(self): - """ Updates the editor when the object trait changes external to the - editor. + """Updates the editor when the object trait changes external to the + editor. """ self._control.text = self.str_value diff --git a/traitsui/wx/toolkit.py b/traitsui/wx/toolkit.py index cad5423ef..3730ae08b 100644 --- a/traitsui/wx/toolkit.py +++ b/traitsui/wx/toolkit.py @@ -65,9 +65,10 @@ # Traits UI dispatch infrastructure # ------------------------------------------------------------------------- + def ui_handler(handler, *args): - """ Handles UI notification handler requests that occur on a thread other - than the UI thread. + """Handles UI notification handler requests that occur on a thread other + than the UI thread. """ wx.CallAfter(handler, *args) @@ -80,85 +81,85 @@ def ui_handler(handler, *args): # Wx Toolkit Implementation # ------------------------------------------------------------------------- + class GUIToolkit(Toolkit): - """ Implementation class for wxPython toolkit. - """ + """Implementation class for wxPython toolkit.""" def ui_panel(self, ui, parent): - """ Creates a wxPython panel-based user interface using information - from the specified UI object. + """Creates a wxPython panel-based user interface using information + from the specified UI object. """ from . import ui_panel ui_panel.ui_panel(ui, parent) def ui_subpanel(self, ui, parent): - """ Creates a wxPython subpanel-based user interface using information - from the specified UI object. + """Creates a wxPython subpanel-based user interface using information + from the specified UI object. """ from . import ui_panel ui_panel.ui_subpanel(ui, parent) def ui_livemodal(self, ui, parent): - """ Creates a wxPython modal "live update" dialog user interface using - information from the specified UI object. + """Creates a wxPython modal "live update" dialog user interface using + information from the specified UI object. """ from . import ui_live ui_live.ui_livemodal(ui, parent) def ui_live(self, ui, parent): - """ Creates a wxPython non-modal "live update" window user interface - using information from the specified UI object. + """Creates a wxPython non-modal "live update" window user interface + using information from the specified UI object. """ from . import ui_live ui_live.ui_live(ui, parent) def ui_modal(self, ui, parent): - """ Creates a wxPython modal dialog user interface using information - from the specified UI object. + """Creates a wxPython modal dialog user interface using information + from the specified UI object. """ from . import ui_modal ui_modal.ui_modal(ui, parent) def ui_nonmodal(self, ui, parent): - """ Creates a wxPython non-modal dialog user interface using - information from the specified UI object. + """Creates a wxPython non-modal dialog user interface using + information from the specified UI object. """ from . import ui_modal ui_modal.ui_nonmodal(ui, parent) def ui_popup(self, ui, parent): - """ Creates a wxPython temporary "live update" popup dialog user - interface using information from the specified UI object. + """Creates a wxPython temporary "live update" popup dialog user + interface using information from the specified UI object. """ from . import ui_live ui_live.ui_popup(ui, parent) def ui_popover(self, ui, parent): - """ Creates a wxPython temporary "live update" popup dialog user - interface using information from the specified UI object. + """Creates a wxPython temporary "live update" popup dialog user + interface using information from the specified UI object. """ from . import ui_live ui_live.ui_popover(ui, parent) def ui_info(self, ui, parent): - """ Creates a wxPython temporary "live update" popup dialog user - interface using information from the specified UI object. + """Creates a wxPython temporary "live update" popup dialog user + interface using information from the specified UI object. """ from . import ui_live ui_live.ui_info(ui, parent) def ui_wizard(self, ui, parent): - """ Creates a wxPython wizard dialog user interface using information - from the specified UI object. + """Creates a wxPython wizard dialog user interface using information + from the specified UI object. """ from . import ui_wizard @@ -174,7 +175,7 @@ def view_application( scrollable=None, args=None, ): - """ Creates a wxPython modal dialog user interface that + """Creates a wxPython modal dialog user interface that runs as a complete application, using information from the specified View object. @@ -212,8 +213,7 @@ def view_application( ) def position(self, ui): - """ Positions the associated dialog window on the display. - """ + """Positions the associated dialog window on the display.""" view = ui.view window = ui.control @@ -295,22 +295,19 @@ def position(self, ui): window.SetSize(max(0, x), max(0, y), width, height) def show_help(self, ui, control): - """ Shows a help window for a specified UI and control. - """ + """Shows a help window for a specified UI and control.""" from . import ui_panel ui_panel.show_help(ui, control) def save_window(self, ui): - """ Saves user preference information associated with a UI window. - """ + """Saves user preference information associated with a UI window.""" from . import helper helper.save_window(ui) def rebuild_ui(self, ui): - """ Rebuilds a UI after a change to the content of the UI. - """ + """Rebuilds a UI after a change to the content of the UI.""" parent = size = None if ui.control is not None: @@ -330,28 +327,25 @@ def rebuild_ui(self, ui): sizer.Add(ui.control, 1, wx.EXPAND) def set_title(self, ui): - """ Sets the title for the UI window. - """ + """Sets the title for the UI window.""" ui.control.SetTitle(ui.title) def set_icon(self, ui): - """ Sets the icon for the UI window. - """ + """Sets the icon for the UI window.""" from pyface.image_resource import ImageResource if isinstance(ui.icon, ImageResource): ui.control.SetIcon(ui.icon.create_icon()) def key_event_to_name(self, event): - """ Converts a keystroke event into a corresponding key name. - """ + """Converts a keystroke event into a corresponding key name.""" from . import key_event_to_name return key_event_to_name.key_event_to_name(event) def hook_events(self, ui, control, events=None, handler=None): - """ Hooks all specified events for all controls in a UI so that they - can be routed to the correct event handler. + """Hooks all specified events for all controls in a UI so that they + can be routed to the correct event handler. """ if events is None: events = ( @@ -392,8 +386,7 @@ def hook_events(self, ui, control, events=None, handler=None): self.hook_events(ui, child, events, handler) def route_event(self, ui, event): - """ Routes a hooked event to the correct handler method. - """ + """Routes a hooked event to the correct handler method.""" suffix = EventSuffix[event.GetEventType()] control = event.GetEventObject() handler = ui.handler @@ -414,14 +407,13 @@ def route_event(self, ui, event): event.Skip() def skip_event(self, event): - """ Indicates that an event should continue to be processed by the - toolkit. + """Indicates that an event should continue to be processed by the + toolkit. """ event.Skip() def destroy_control(self, control): - """ Destroys a specified GUI toolkit control. - """ + """Destroys a specified GUI toolkit control.""" _popEventHandlers(control) def _destroy_control(control): @@ -429,31 +421,32 @@ def _destroy_control(control): control.Destroy() except Exception: logger.exception( - "Wx control %r not destroyed cleanly", control) + "Wx control %r not destroyed cleanly", control + ) wx.CallAfter(_destroy_control, control) def destroy_children(self, control): - """ Destroys all of the child controls of a specified GUI toolkit - control. + """Destroys all of the child controls of a specified GUI toolkit + control. """ for child in control.GetChildren(): _popEventHandlers(child) wx.CallAfter(control.DestroyChildren) def image_size(self, image): - """ Returns a ( width, height ) tuple containing the size of a - specified toolkit image. + """Returns a ( width, height ) tuple containing the size of a + specified toolkit image. """ return (image.GetWidth(), image.GetHeight()) def constants(self): - """ Returns a dictionary of useful constants. + """Returns a dictionary of useful constants. - Currently, the dictionary should have the following key/value pairs: + Currently, the dictionary should have the following key/value pairs: - - WindowColor': the standard window background color in the toolkit - specific color format. + - WindowColor': the standard window background color in the toolkit + specific color format. """ return {"WindowColor": WindowColor} @@ -478,8 +471,7 @@ def font_trait(self, *args, **traits): class DragHandler(HasPrivateTraits): - """ Handler for drag events. - """ + """Handler for drag events.""" # ------------------------------------------------------------------------- # Traits definitions: @@ -494,23 +486,19 @@ class DragHandler(HasPrivateTraits): # -- Drag and drop event handlers: ---------------------------------------- def wx_dropped_on(self, x, y, data, drag_result): - """ Handles a Python object being dropped on the window. - """ + """Handles a Python object being dropped on the window.""" return self._drag_event("dropped_on", x, y, data, drag_result) def wx_drag_over(self, x, y, data, drag_result): - """ Handles a Python object being dragged over the tree. - """ + """Handles a Python object being dragged over the tree.""" return self._drag_event("drag_over", x, y, data, drag_result) def wx_drag_leave(self, data): - """ Handles a dragged Python object leaving the window. - """ + """Handles a dragged Python object leaving the window.""" return self._drag_event("drag_leave") def _drag_event(self, suffix, x=None, y=None, data=None, drag_result=None): - """ Handles routing a drag event to the appropriate handler. - """ + """Handles routing a drag event to the appropriate handler.""" control = self.control handler = self.ui.handler method = None @@ -537,15 +525,16 @@ def _drag_event(self, suffix, x=None, y=None, data=None, drag_result=None): class EventHandlerWrapper(wx.EvtHandler): - """ Simple wrapper around wx.EvtHandler used to determine which event + """Simple wrapper around wx.EvtHandler used to determine which event handlers were added by traitui. """ + pass def _popEventHandlers(ctrl, handler_type=EventHandlerWrapper): - """ Pop any event handlers that have been pushed on to a window and its - children. + """Pop any event handlers that have been pushed on to a window and its + children. """ # FIXME: have to special case URLResolvingHtmlWindow because it doesn't # want its EvtHandler cleaned up. See issue #752. diff --git a/traitsui/wx/tree_editor.py b/traitsui/wx/tree_editor.py index c1b8bd777..9d2aaaefd 100644 --- a/traitsui/wx/tree_editor.py +++ b/traitsui/wx/tree_editor.py @@ -67,8 +67,7 @@ class SimpleEditor(Editor): - """ Simple style of tree editor. - """ + """Simple style of tree editor.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -97,8 +96,8 @@ class SimpleEditor(Editor): veto = Event() def init(self, parent): - """ Finishes initializing the editor by creating the underlying toolkit - widget. + """Finishes initializing the editor by creating the underlying toolkit + widget. """ factory = self.factory style = self._get_style() @@ -256,8 +255,7 @@ def init(self, parent): tree.SetDropTarget(PythonDropTarget(self)) def dispose(self): - """ Disposes of the contents of an editor. - """ + """Disposes of the contents of an editor.""" tree = self._tree if tree is not None: tree.Unbind(wx.EVT_LEFT_DOWN) @@ -285,27 +283,23 @@ def dispose(self): super().dispose() def _selection_changed(self, selection): - """ Handles the **selection** event. - """ + """Handles the **selection** event.""" try: self._tree.SelectItem(self._object_info(selection)[2]) except Exception: pass def _selected_changed(self, selected): - """ Handles the **selected** trait being changed. - """ + """Handles the **selected** trait being changed.""" if not self._no_update_selected: self._selection_changed(selected) def _veto_changed(self): - """ Handles the 'veto' event being fired. - """ + """Handles the 'veto' event being fired.""" self._veto = True def _get_style(self): - """ Returns the style settings used for displaying the wx tree. - """ + """Returns the style settings used for displaying the wx tree.""" factory = self.factory style = wx.TR_EDIT_LABELS | wx.TR_HAS_BUTTONS | wx.CLIP_CHILDREN @@ -324,8 +318,7 @@ def _get_style(self): return style def update_object(self, event): - """ Handles the user entering input data in the edit control. - """ + """Handles the user entering input data in the edit control.""" try: self.value = self._get_value() self.control.SetBackgroundColour(OKColor) @@ -372,8 +365,7 @@ def _restore_state(self, state): nodes_to_do.append(cnid) def expand_all(self): - """ Expands all nodes, starting from the selected node. - """ + """Expands all nodes, starting from the selected node.""" tree = self._tree def _do_expand(nid): @@ -394,8 +386,7 @@ def _do_expand(nid): nodes_to_do.append(n) def expand_levels(self, nid, levels, expand=True): - """ Expands from the specified node the specified number of sub-levels. - """ + """Expands from the specified node the specified number of sub-levels.""" if levels > 0: expanded, node, object = self._get_node_data(nid) if self._has_children(node, object): @@ -407,8 +398,8 @@ def expand_levels(self, nid, levels, expand=True): self.expand_levels(cnid, levels - 1) def update_editor(self): - """ Updates the editor when the object trait changes externally to the - editor. + """Updates the editor when the object trait changes externally to the + editor. """ tree = self._tree saved_state = {} @@ -442,18 +433,16 @@ def update_editor(self): # fixme: Clear the current editor (if any)... def get_error_control(self): - """ Returns the editor's control for indicating error status. - """ + """Returns the editor's control for indicating error status.""" return self._tree def _append_node(self, nid, node, object): - """ Appends a new node to the specified node. - """ + """Appends a new node to the specified node.""" return self._insert_node(nid, None, node, object) def _insert_node(self, nid, index, node, object): - """ Inserts a new node before a specified index into the children of the - specified node. + """Inserts a new node before a specified index into the children of the + specified node. """ tree = self._tree icon = self._get_icon(node, object) @@ -478,8 +467,7 @@ def _insert_node(self, nid, index, node, object): return cnid def _delete_node(self, nid): - """ Deletes a specified tree node and all of its children. - """ + """Deletes a specified tree node and all of its children.""" for cnid in self._nodes_for(nid): self._delete_node(cnid) @@ -508,8 +496,7 @@ def _delete_node(self, nid): self._clear_editor() def _expand_node(self, nid): - """ Expands the contents of a specified node (if required). - """ + """Expands the contents of a specified node (if required).""" expanded, node, object = self._get_node_data(nid) # Lazily populate the item's children: @@ -523,8 +510,7 @@ def _expand_node(self, nid): self._set_node_data(nid, (True, node, object)) def _nodes(self, nid): - """ Returns each of the child nodes of a specified node. - """ + """Returns each of the child nodes of a specified node.""" tree = self._tree cnid, cookie = tree.GetFirstChild(nid) while cnid.IsOk(): @@ -532,8 +518,7 @@ def _nodes(self, nid): cnid, cookie = tree.GetNextChild(nid, cookie) def _nodes_for(self, nid): - """ Returns all child node ids of a specified node id. - """ + """Returns all child node ids of a specified node id.""" return [cnid for cnid in self._nodes(nid)] def _node_index(self, nid): @@ -548,21 +533,18 @@ def _node_index(self, nid): return (pnode, pobject, i) def _has_children(self, node, object): - """ Returns whether a specified object has any children. - """ + """Returns whether a specified object has any children.""" return node.allows_children(object) and node.has_children(object) def _is_droppable(self, node, object, add_object, for_insert): - """ Returns whether a given object is droppable on the node. - """ + """Returns whether a given object is droppable on the node.""" if for_insert and (not node.can_insert(object)): return False return node.can_add(object, add_object) def _drop_object(self, node, object, dropped_object, make_copy=True): - """ Returns a droppable version of a specified object. - """ + """Returns a droppable version of a specified object.""" new_object = node.drop_object(object, dropped_object) if (new_object is not dropped_object) or (not make_copy): return new_object @@ -570,8 +552,7 @@ def _drop_object(self, node, object, dropped_object, make_copy=True): return copy.deepcopy(new_object) def _get_icon(self, node, object, is_expanded=False): - """ Returns the index of the specified object icon. - """ + """Returns the index of the specified object icon.""" if self._image_list is None: return -1 @@ -603,8 +584,7 @@ def _get_icon(self, node, object, is_expanded=False): return self._image_list.GetIndex(image) def _add_listeners(self, node, object): - """ Adds the event listeners for a specified object. - """ + """Adds the event listeners for a specified object.""" if node.allows_children(object): node.when_children_replaced(object, self._children_replaced, False) node.when_children_changed(object, self._children_updated, False) @@ -612,8 +592,7 @@ def _add_listeners(self, node, object): node.when_label_changed(object, self._label_updated, False) def _remove_listeners(self, node, object): - """ Removes any event listeners from a specified object. - """ + """Removes any event listeners from a specified object.""" if node.allows_children(object): node.when_children_replaced(object, self._children_replaced, True) node.when_children_changed(object, self._children_updated, True) @@ -621,8 +600,8 @@ def _remove_listeners(self, node, object): node.when_label_changed(object, self._label_updated, True) def _object_info(self, object, name=""): - """ Returns the tree node data for a specified object in the form - ( expanded, node, nid ). + """Returns the tree node data for a specified object in the form + ( expanded, node, nid ). """ info = self._map[id(object)] for name2, nid in info: @@ -636,8 +615,8 @@ def _object_info(self, object, name=""): return (expanded, node, nid) def _object_info_for(self, object, name=""): - """ Returns the tree node data for a specified object as a list of the - form: [ ( expanded, node, nid ), ... ]. + """Returns the tree node data for a specified object as a list of the + form: [ ( expanded, node, nid ), ... ]. """ result = [] for name2, nid in self._map[id(object)]: @@ -648,8 +627,7 @@ def _object_info_for(self, object, name=""): return result def _node_for(self, object): - """ Returns the TreeNode associated with a specified object. - """ + """Returns the TreeNode associated with a specified object.""" if ( (isinstance(object, tuple)) and (len(object) == 2) @@ -708,21 +686,18 @@ def _node_for(self, object): return (object, multi_node) def _node_for_class(self, klass): - """ Returns the TreeNode associated with a specified class. - """ + """Returns the TreeNode associated with a specified class.""" for node in self.factory.nodes: if issubclass(klass, tuple(node.node_for)): return node return None def _update_icon(self, event, is_expanded): - """ Updates the icon for a specified node. - """ + """Updates the icon for a specified node.""" self._update_icon_for_nid(event.GetItem()) def _update_icon_for_nid(self, nid): - """ Updates the icon for a specified node ID. - """ + """Updates the icon for a specified node ID.""" if self._image_list is not None: expanded, node, object = self._get_node_data(nid) icon = self._get_icon(node, object, expanded) @@ -730,8 +705,7 @@ def _update_icon_for_nid(self, nid): self._tree.SetItemImage(nid, icon, wx.TreeItemIcon_Selected) def _unpack_event(self, event): - """ Unpacks an event to see whether a tree item was involved. - """ + """Unpacks an event to see whether a tree item was involved.""" try: point = event.GetPosition() except: @@ -750,16 +724,14 @@ def _unpack_event(self, event): return (None, None, None, nid, point) def _hit_test(self, point): - """ Returns information about the node at a specified point. - """ + """Returns information about the node at a specified point.""" nid, flags = self._tree.HitTest(point) if nid.IsOk(): return self._get_node_data(nid) + (nid, point) return (None, None, None, nid, point) def _begin_undo(self): - """ Begins an "undoable" transaction. - """ + """Begins an "undoable" transaction.""" ui = self.ui self._undoable.append(ui._undoable) if (ui._undoable == -1) and (ui.history is not None): @@ -779,8 +751,7 @@ def _get_undo_item(self, object, name, event): ) def _undoable_append(self, node, object, data, make_copy=True): - """ Performs an undoable append operation. - """ + """Performs an undoable append operation.""" try: self._begin_undo() if make_copy: @@ -790,8 +761,7 @@ def _undoable_append(self, node, object, data, make_copy=True): self._end_undo() def _undoable_insert(self, node, object, index, data, make_copy=True): - """ Performs an undoable insert operation. - """ + """Performs an undoable insert operation.""" try: self._begin_undo() if make_copy: @@ -801,8 +771,7 @@ def _undoable_insert(self, node, object, index, data, make_copy=True): self._end_undo() def _undoable_delete(self, node, object, index): - """ Performs an undoable delete operation. - """ + """Performs an undoable delete operation.""" try: self._begin_undo() node.delete_child(object, index) @@ -810,8 +779,7 @@ def _undoable_delete(self, node, object, index): self._end_undo() def _get_object_nid(self, object, name=""): - """ Gets the ID associated with a specified object (if any). - """ + """Gets the ID associated with a specified object (if any).""" info = self._map.get(id(object)) if info is None: return None @@ -823,8 +791,7 @@ def _get_object_nid(self, object, name=""): return info[0][1] def _clear_editor(self): - """ Clears the current editor pane (if any). - """ + """Clears the current editor pane (if any).""" editor = self._editor if editor._node_ui is not None: editor.SetSizer(None) @@ -832,16 +799,14 @@ def _clear_editor(self): editor._node_ui = editor._editor_nid = None def _get_node_data(self, nid): - """ Gets the node specific data. - """ + """Gets the node specific data.""" if nid == self._root_nid: return self._root_nid_data return self._tree.GetItemData(nid) def _set_node_data(self, nid, data): - """ Sets the node specific data. - """ + """Sets the node specific data.""" if nid == self._root_nid: self._root_nid_data = data else: @@ -850,13 +815,12 @@ def _set_node_data(self, nid, data): # ----- User callable methods: -------------------------------------------- def get_object(self, nid): - """ Gets the object associated with a specified node. - """ + """Gets the object associated with a specified node.""" return self._get_node_data(nid)[2] def get_parent(self, object, name=""): - """ Returns the object that is the immmediate parent of a specified - object in the tree. + """Returns the object that is the immmediate parent of a specified + object in the tree. """ nid = self._get_object_nid(object, name) if nid is not None: @@ -867,8 +831,7 @@ def get_parent(self, object, name=""): return None def get_node(self, object, name=""): - """ Returns the node associated with a specified object. - """ + """Returns the node associated with a specified object.""" nid = self._get_object_nid(object, name) if nid is not None: return self._get_node_data(nid)[1] @@ -878,8 +841,7 @@ def get_node(self, object, name=""): # -- Tree Event Handlers: ------------------------------------------------- def _on_tree_item_expanding(self, event): - """ Handles a tree node expanding. - """ + """Handles a tree node expanding.""" if self._veto: self._veto = False event.Veto() @@ -910,25 +872,21 @@ def _on_tree_item_expanding(self, event): self._expand_node(nid) def _on_tree_item_expanded(self, event): - """ Handles a tree node being expanded. - """ + """Handles a tree node being expanded.""" self._update_icon(event, True) def _on_tree_item_collapsing(self, event): - """ Handles a tree node collapsing. - """ + """Handles a tree node collapsing.""" if self._veto: self._veto = False event.Veto() def _on_tree_item_collapsed(self, event): - """ Handles a tree node being collapsed. - """ + """Handles a tree node being collapsed.""" self._update_icon(event, False) def _on_tree_sel_changed(self, event=None): - """ Handles a tree node being selected. - """ + """Handles a tree node being selected.""" if self._locked: return @@ -1017,8 +975,7 @@ def _on_tree_sel_changed(self, event=None): editor.Thaw() def _on_hover(self, event): - """ Handles the mouse moving over a tree node - """ + """Handles the mouse moving over a tree node""" id, flags = self._tree.HitTest(event.GetPosition()) if flags & wx.TREE_HITTEST_ONITEMLABEL: expanded, node, object = self._get_node_data(id) @@ -1032,8 +989,7 @@ def _on_hover(self, event): event.Skip(True) def _on_tree_item_activated(self, event): - """ Handles a tree item being activated. - """ + """Handles a tree item being activated.""" expanded, node, object = self._get_node_data(event.GetItem()) if node.activated(object) is True: @@ -1051,8 +1007,7 @@ def _on_tree_item_activated(self, event): self.dclick = object def _on_tree_begin_label_edit(self, event): - """ Handles the user starting to edit a tree node label. - """ + """Handles the user starting to edit a tree node label.""" item = event.GetItem() parent = self._tree.GetItemParent(item) can_rename = True @@ -1068,8 +1023,7 @@ def _on_tree_begin_label_edit(self, event): event.Veto() def _on_tree_end_label_edit(self, event): - """ Handles the user completing tree node label editing. - """ + """Handles the user completing tree node label editing.""" label = event.GetLabel() if len(label) > 0: expanded, node, object = self._get_node_data(event.GetItem()) @@ -1084,8 +1038,7 @@ def _on_tree_end_label_edit(self, event): event.Veto() def _on_tree_begin_drag(self, event): - """ Handles a drag operation starting on a tree node. - """ + """Handles a drag operation starting on a tree node.""" if PythonDropSource is not None: expanded, node, object, nid, point = self._unpack_event(event) if node is not None: @@ -1096,8 +1049,7 @@ def _on_tree_begin_drag(self, event): self._dragging = None def _on_tree_item_gettooltip(self, event): - """ Handles a tooltip request on a tree node. - """ + """Handles a tooltip request on a tree node.""" nid = event.GetItem() if nid.IsOk(): node_data = self._get_node_data(nid) @@ -1110,8 +1062,7 @@ def _on_tree_item_gettooltip(self, event): event.Skip() def _on_left_dclick(self, event): - """ Handle left mouse dclick to emit dclick event for associated node. - """ + """Handle left mouse dclick to emit dclick event for associated node.""" # Determine what node (if any) was clicked on: expanded, node, object, nid, point = self._unpack_event(event) @@ -1133,8 +1084,7 @@ def _on_left_dclick(self, event): event.Skip() def _on_left_down(self, event): - """ Handles the user right clicking on a tree node. - """ + """Handles the user right clicking on a tree node.""" # Determine what node (if any) was clicked on: expanded, node, object, nid, point = self._unpack_event(event) @@ -1152,8 +1102,7 @@ def _on_left_down(self, event): event.Skip() def _on_right_down(self, event): - """ Handles the user right clicking on a tree node. - """ + """Handles the user right clicking on a tree node.""" expanded, node, object, nid, point = self._unpack_event(event) if node is not None: @@ -1211,8 +1160,7 @@ def _on_right_down(self, event): ) = self._menu_parent_node = self._menu_parent_object = None def _standard_menu(self, node, object): - """ Returns the standard contextual pop-up menu. - """ + """Returns the standard contextual pop-up menu.""" actions = [ CutAction, CopyAction, @@ -1231,8 +1179,7 @@ def _standard_menu(self, node, object): return Menu(*actions) def _new_actions(self, node, object): - """ Returns a list of Actions that will create new objects. - """ + """Returns a list of Actions that will create new objects.""" object = self._data[1] items = [] add = node.get_add(object) @@ -1257,11 +1204,11 @@ def _new_actions(self, node, object): name = class_name if not factory: factory = klass + def perform_add(object, factory, prompt): self._menu_new_node(factory, prompt) - on_perform = partial( - perform_add, factory=factory, prompt=prompt - ) + + on_perform = partial(perform_add, factory=factory, prompt=prompt) items.append(Action(name=name, on_perform=on_perform)) return items @@ -1311,8 +1258,7 @@ def _is_renameable(self, object): # ----- Drag and drop event handlers: ------------------------------------- def wx_dropped_on(self, x, y, data, drag_result): - """ Handles a Python object being dropped on the tree. - """ + """Handles a Python object being dropped on the tree.""" if isinstance(data, list): rc = wx.DragNone for item in data: @@ -1377,8 +1323,7 @@ def wx_dropped_on(self, x, y, data, drag_result): return wx.DragNone def wx_drag_over(self, x, y, data, drag_result): - """ Handles a Python object being dragged over the tree. - """ + """Handles a Python object being dragged over the tree.""" expanded, node, object, nid, point = self._hit_test(wx.Point(x, y)) insert = False @@ -1413,20 +1358,17 @@ def _is_drag_ok(self, snid, source, target): # ----- pyface.action 'controller' interface implementation: -------------- def add_to_menu(self, menu_item): - """ Adds a menu item to the menu bar being constructed. - """ + """Adds a menu item to the menu bar being constructed.""" action = menu_item.item.action self.eval_when(action.enabled_when, menu_item, "enabled") self.eval_when(action.checked_when, menu_item, "checked") def add_to_toolbar(self, toolbar_item): - """ Adds a toolbar item to the toolbar being constructed. - """ + """Adds a toolbar item to the toolbar being constructed.""" self.add_to_menu(toolbar_item) def can_add_to_menu(self, action): - """ Returns whether the action should be defined in the user interface. - """ + """Returns whether the action should be defined in the user interface.""" if action.defined_when != "": if not eval(action.defined_when, globals(), self._context): return False @@ -1438,14 +1380,13 @@ def can_add_to_menu(self, action): return True def can_add_to_toolbar(self, action): - """ Returns whether the toolbar action should be defined in the user - interface. + """Returns whether the toolbar action should be defined in the user + interface. """ return self.can_add_to_menu(action) def perform(self, action, action_event=None): - """ Performs the action described by a specified Action object. - """ + """Performs the action described by a specified Action object.""" self.ui.do_undoable(self._perform, action) def _perform(self, action): @@ -1487,7 +1428,7 @@ def _perform(self, action): # ----- Menu support methods: --------------------------------------------- def eval_when(self, condition, object, trait): - """ Evaluates a condition within a defined context, and sets a + """Evaluates a condition within a defined context, and sets a specified object trait based on the result, which is assumed to be a Boolean. """ @@ -1500,16 +1441,14 @@ def eval_when(self, condition, object, trait): # ----- Menu event handlers: ---------------------------------------------- def _menu_copy_node(self): - """ Copies the current tree node object to the paste buffer. - """ + """Copies the current tree node object to the paste buffer.""" from pyface.wx.clipboard import clipboard clipboard.data = self._data[1] self._data = None def _menu_cut_node(self): - """ Cuts the current tree node object into the paste buffer. - """ + """Cuts the current tree node object into the paste buffer.""" from pyface.wx.clipboard import clipboard node, object, nid = self._data @@ -1518,8 +1457,8 @@ def _menu_cut_node(self): self._undoable_delete(*self._node_index(nid)) def _menu_paste_node(self): - """ Pastes the current contents of the paste buffer into the current - node. + """Pastes the current contents of the paste buffer into the current + node. """ from pyface.wx.clipboard import clipboard @@ -1528,8 +1467,7 @@ def _menu_paste_node(self): self._undoable_append(node, object, clipboard.object_data, False) def _menu_delete_node(self): - """ Deletes the current node from the tree. - """ + """Deletes the current node from the tree.""" node, object, nid = self._data self._data = None rc = node.confirm_delete(object) @@ -1550,8 +1488,7 @@ def _menu_delete_node(self): self._undoable_delete(*self._node_index(nid)) def _menu_rename_node(self): - """ Renames the current tree node. - """ + """Renames the current tree node.""" node, object, nid = self._data self._data = None object_label = ObjectLabel(label=node.get_label(object)) @@ -1561,8 +1498,7 @@ def _menu_rename_node(self): node.set_label(object, label) def _menu_new_node(self, factory, prompt=False): - """ Adds a new object to the current node. - """ + """Adds a new object to the current node.""" node, object, nid = self._data self._data = None new_object = factory() @@ -1579,8 +1515,7 @@ def _menu_new_node(self, factory, prompt=False): # -- Model event handlers ------------------------------------------------- def _children_replaced(self, object, name="", new=None): - """ Handles the children of a node being completely replaced. - """ + """Handles the children of a node being completely replaced.""" tree = self._tree for expanded, node, nid in self._object_info_for(object, name): children = node.get_children(object) @@ -1606,8 +1541,7 @@ def _children_replaced(self, object, name="", new=None): tree.Expand(nid) def _children_updated(self, object, name, event): - """ Handles the children of a node being changed. - """ + """Handles the children of a node being changed.""" # Log the change that was made (removing '_items' from the end of the # name): name = name[:-6] @@ -1651,8 +1585,7 @@ def _children_updated(self, object, name, event): tree.Expand(nid) def _label_updated(self, object, name, label): - """ Handles the label of an object being changed. - """ + """Handles the label of an object being changed.""" nids = {} for name2, nid in self._map[id(object)]: if nid not in nids: @@ -1664,8 +1597,8 @@ def _label_updated(self, object, name, label): # -- UI preference save/restore interface --------------------------------- def restore_prefs(self, prefs): - """ Restores any saved user preference information associated with the - editor. + """Restores any saved user preference information associated with the + editor. """ if self._is_dock_window: if isinstance(prefs, dict): @@ -1675,8 +1608,7 @@ def restore_prefs(self, prefs): self.control.GetSizer().SetStructure(self.control, structure) def save_prefs(self): - """ Returns any user preference information associated with the editor. - """ + """Returns any user preference information associated with the editor.""" if self._is_dock_window: return {"structure": self.control.GetSizer().GetStructure()} @@ -1687,8 +1619,7 @@ def save_prefs(self): class ObjectLabel(HasStrictTraits): - """ An editable label for an object. - """ + """An editable label for an object.""" # ------------------------------------------------------------------------- # Trait definitions: diff --git a/traitsui/wx/tuple_editor.py b/traitsui/wx/tuple_editor.py index 95769df98..50831c21c 100644 --- a/traitsui/wx/tuple_editor.py +++ b/traitsui/wx/tuple_editor.py @@ -22,10 +22,10 @@ class SimpleEditor(BaseSimpleEditor, Editor): - """ Simple style of editor for tuples. + """Simple style of editor for tuples. - The editor displays an editor for each of the fields in the tuple, - based on the type of each field. + The editor displays an editor for each of the fields in the tuple, + based on the type of each field. """ pass diff --git a/traitsui/wx/ui_base.py b/traitsui/wx/ui_base.py index f1afc5a9c..8b739e7fe 100644 --- a/traitsui/wx/ui_base.py +++ b/traitsui/wx/ui_base.py @@ -23,8 +23,7 @@ class ButtonEditor(Editor): - """ Editor for buttons. - """ + """Editor for buttons.""" # Action associated with the button action = Instance(Action) @@ -34,15 +33,13 @@ def __init__(self, **traits): HasPrivateTraits.__init__(self, **traits) def perform(self, event): - """ Handles the associated button being clicked. - """ + """Handles the associated button being clicked.""" handler = self.ui.handler self.ui.do_undoable(handler.perform, self.ui.info, self.action, event) class BaseDialog(_BasePanel): - """ Base class for Traits UI dialog boxes. - """ + """Base class for Traits UI dialog boxes.""" # The different dialog styles. NONMODAL = 0 @@ -91,14 +88,13 @@ def display_ui(ui, parent, style): ui.control.Show() def default_icon(self): - """ Return a default icon for a TraitsUI dialog. """ + """Return a default icon for a TraitsUI dialog.""" from pyface.image_resource import ImageResource return ImageResource("frame.ico") def set_icon(self, icon=None): - """ Sets the frame's icon. - """ + """Sets the frame's icon.""" from pyface.image_resource import ImageResource if not isinstance(icon, ImageResource): @@ -106,8 +102,7 @@ def set_icon(self, icon=None): self.control.SetIcon(icon.create_icon()) def add_statusbar(self): - """ Adds a status bar to the dialog. - """ + """Adds a status bar to the dialog.""" ui = self.ui statusbar = ui.view.statusbar context = ui.context @@ -147,8 +142,7 @@ def set_status_text(event): return set_status_text def add_menubar(self): - """ Adds a menu bar to the dialog. - """ + """Adds a menu bar to the dialog.""" menubar = self.ui.view.menubar if menubar is not None: self._last_group = self._last_parent = None @@ -158,8 +152,7 @@ def add_menubar(self): self._last_group = self._last_parent = None def add_toolbar(self): - """ Adds a toolbar to the dialog. - """ + """Adds a toolbar to the dialog.""" toolbar = self.ui.view.toolbar if toolbar is not None: self._last_group = self._last_parent = None @@ -177,8 +170,7 @@ def add_button( name=None, default=False, ): - """ Creates a button. - """ + """Creates a button.""" ui = self.ui if (action.defined_when != "") and ( not ui.eval_when(action.defined_when) diff --git a/traitsui/wx/ui_editor.py b/traitsui/wx/ui_editor.py index cae3eb9d6..062872bb9 100644 --- a/traitsui/wx/ui_editor.py +++ b/traitsui/wx/ui_editor.py @@ -23,8 +23,7 @@ class UIEditor(BaseUIEditor, Editor): - """ An editor that creates an embedded Traits UI. - """ + """An editor that creates an embedded Traits UI.""" pass diff --git a/traitsui/wx/ui_live.py b/traitsui/wx/ui_live.py index b397b1dae..d76e82b5e 100644 --- a/traitsui/wx/ui_live.py +++ b/traitsui/wx/ui_live.py @@ -41,42 +41,40 @@ def ui_live(ui, parent): - """ Creates a live, non-modal wxPython user interface for a specified UI + """Creates a live, non-modal wxPython user interface for a specified UI object. """ _ui_dialog(ui, parent, BaseDialog.NONMODAL) def ui_livemodal(ui, parent): - """ Creates a live, modal wxPython user interface for a specified UI object. - """ + """Creates a live, modal wxPython user interface for a specified UI object.""" _ui_dialog(ui, parent, BaseDialog.MODAL) def ui_popup(ui, parent): - """ Creates a live, temporary popup wxPython user interface for a specified - UI object. + """Creates a live, temporary popup wxPython user interface for a specified + UI object. """ _ui_dialog(ui, parent, BaseDialog.POPUP) def ui_popover(ui, parent): - """ Creates a live, temporary popup wxPython user interface for a specified - UI object. + """Creates a live, temporary popup wxPython user interface for a specified + UI object. """ _ui_dialog(ui, parent, BaseDialog.POPOVER) def ui_info(ui, parent): - """ Creates a live, temporary popup wxPython user interface for a specified - UI object. + """Creates a live, temporary popup wxPython user interface for a specified + UI object. """ _ui_dialog(ui, parent, BaseDialog.INFO) def _ui_dialog(ui, parent, style): - """ Creates a live wxPython user interface for a specified UI object. - """ + """Creates a live wxPython user interface for a specified UI object.""" if ui.owner is None: ui.owner = LiveWindow() @@ -84,8 +82,7 @@ def _ui_dialog(ui, parent, style): class LiveWindow(BaseDialog): - """ User interface window that immediately updates its underlying object(s). - """ + """User interface window that immediately updates its underlying object(s).""" def init(self, ui, parent, style): self.is_modal = style == self.MODAL @@ -292,8 +289,7 @@ def init(self, ui, parent, style): window.Fit() def close(self, rc=wx.ID_OK): - """ Closes the dialog window. - """ + """Closes the dialog window.""" ui = self.ui ui.result = rc == wx.ID_OK save_window(ui) @@ -307,16 +303,14 @@ def close(self, rc=wx.ID_OK): self.ui = self.undo = self.redo = self.revert = self.control = None def _on_close_page(self, event): - """ Handles the user clicking the window/dialog "close" button/icon. - """ + """Handles the user clicking the window/dialog "close" button/icon.""" if not self.ui.view.close_result: self._on_cancel(event) else: self._on_ok(event) def _on_close_popup(self, event): - """ Handles the user giving focus to another window for a 'popup' view. - """ + """Handles the user giving focus to another window for a 'popup' view.""" if not event.GetActive(): self.close_popup() @@ -327,8 +321,7 @@ def close_popup(self): self._monitor.Stop() def _on_ok(self, event=None): - """ Handles the user clicking the **OK** button. - """ + """Handles the user clicking the **OK** button.""" if self.ui is None or self.control is None: return True @@ -340,46 +333,40 @@ def _on_ok(self, event=None): return False def _on_key(self, event): - """ Handles the user pressing the Escape key. - """ + """Handles the user pressing the Escape key.""" if event.GetKeyCode() == 0x1B: self._on_close_page(event) def _on_cancel(self, event): - """ Handles a request to cancel all changes. - """ + """Handles a request to cancel all changes.""" if self.ui.handler.close(self.ui.info, False): self._on_revert(event) self.close(wx.ID_CANCEL) def _on_error(self, event): - """ Handles editing errors. - """ + """Handles editing errors.""" errors = event.new self.ok.Enable(errors == 0) def _on_undoable(self, event): - """ Handles a change to the "undoable" state of the undo history - """ + """Handles a change to the "undoable" state of the undo history""" state = event.new self.undo.Enable(state) def _on_redoable(self, event): - """ Handles a change to the "redoable state of the undo history. - """ + """Handles a change to the "redoable state of the undo history.""" state = event.new self.redo.Enable(state) def _on_revertable(self, event): - """ Handles a change to the "revert" state. - """ + """Handles a change to the "revert" state.""" state = event.new self.revert.Enable(state) class MouseMonitor(wx.Timer): - """ Monitors a specified window and closes it the first time the mouse - pointer leaves the window. + """Monitors a specified window and closes it the first time the mouse + pointer leaves the window. """ def __init__(self, ui): diff --git a/traitsui/wx/ui_modal.py b/traitsui/wx/ui_modal.py index 76a3bad7f..c7145cd0d 100644 --- a/traitsui/wx/ui_modal.py +++ b/traitsui/wx/ui_modal.py @@ -34,19 +34,17 @@ def ui_modal(ui, parent): - """ Creates a modal wxPython user interface for a specified UI object. - """ + """Creates a modal wxPython user interface for a specified UI object.""" _ui_dialog(ui, parent, BaseDialog.MODAL) def ui_nonmodal(ui, parent): - """ Creates a non-modal wxPython user interface for a specified UI object. - """ + """Creates a non-modal wxPython user interface for a specified UI object.""" _ui_dialog(ui, parent, BaseDialog.NONMODAL) def _ui_dialog(ui, parent, style): - """ Creates a wxPython dialog box for a specified UI object. + """Creates a wxPython dialog box for a specified UI object. Changes are not immediately applied to the underlying object. The user must click **Apply** or **OK** to apply changes. The user can revert changes by @@ -59,8 +57,7 @@ def _ui_dialog(ui, parent, style): class ModalDialog(BaseDialog): - """ Modal dialog box for Traits-based user interfaces. - """ + """Modal dialog box for Traits-based user interfaces.""" def init(self, ui, parent, style): self.is_modal = style == self.MODAL @@ -163,9 +160,7 @@ def init(self, ui, parent, style): self.apply = self.add_button( button, b_sizer, self._on_apply, apply, default=default ) - ui.observe( - self._on_applyable, "modified", dispatch="ui" - ) + ui.observe(self._on_applyable, "modified", dispatch="ui") elif self.is_button(button, "Revert"): self.revert = self.add_button( @@ -206,8 +201,7 @@ def init(self, ui, parent, style): window.SetSizerAndFit(sw_sizer) def close(self, rc=wx.ID_OK): - """ Closes the dialog window. - """ + """Closes the dialog window.""" ui = self.ui ui.result = rc == wx.ID_OK save_window(ui) @@ -221,8 +215,7 @@ def close(self, rc=wx.ID_OK): self.ui = self.apply = self.revert = self.help = self.control = None def _copy_context(self, context): - """ Creates a copy of a *context* dictionary. - """ + """Creates a copy of a *context* dictionary.""" result = {} for name, value in context.items(): if value is not None: @@ -233,8 +226,7 @@ def _copy_context(self, context): return result def _apply_context(self, from_context, to_context): - """ Applies the traits in the *from_context* to the *to_context*. - """ + """Applies the traits in the *from_context* to the *to_context*.""" for name, value in from_context.items(): if value is not None: to_context[name].copy_traits(value) @@ -247,36 +239,31 @@ def _apply_context(self, from_context, to_context): on_apply() def _on_close_page(self, event): - """ Handles the user clicking the window/dialog "close" button/icon. - """ + """Handles the user clicking the window/dialog "close" button/icon.""" if self.ui.view.close_result: self._on_ok(event) else: self._on_cancel(event) def _on_ok(self, event=None): - """ Closes the window and saves changes (if allowed by the handler). - """ + """Closes the window and saves changes (if allowed by the handler).""" if self.ui.handler.close(self.ui.info, True): self._apply_context(self.ui.context, self.ui._context) self.close(wx.ID_OK) def _on_cancel(self, event=None): - """ Closes the window and discards changes (if allowed by the handler). - """ + """Closes the window and discards changes (if allowed by the handler).""" if self.ui.handler.close(self.ui.info, False): self._apply_context(self.ui._revert, self.ui._context) self.close(wx.ID_CANCEL) def _on_key(self, event): - """ Handles the user pressing the Escape key. - """ + """Handles the user pressing the Escape key.""" if event.GetKeyCode() == 0x1B: self._on_close_page(event) def _on_apply(self, event): - """ Handles a request to apply changes. - """ + """Handles a request to apply changes.""" ui = self.ui self._apply_context(ui.context, ui._context) if hasattr(self, "revert"): @@ -285,8 +272,7 @@ def _on_apply(self, event): ui.modified = False def _on_revert(self, event): - """ Handles a request to revert changes. - """ + """Handles a request to revert changes.""" ui = self.ui self._apply_context(ui._revert, ui.context) self._apply_context(ui._revert, ui._context) @@ -295,13 +281,11 @@ def _on_revert(self, event): ui.modified = False def _on_applyable(self, event): - """ Handles a change to the "modified" state of the user interface . - """ + """Handles a change to the "modified" state of the user interface .""" state = event.new self.apply.Enable(state) def _on_error(self, event): - """ Handles editing errors. - """ + """Handles editing errors.""" errors = event.new self.ok.Enable(errors == 0) diff --git a/traitsui/wx/ui_panel.py b/traitsui/wx/ui_panel.py index 10c8f8268..69184a33a 100644 --- a/traitsui/wx/ui_panel.py +++ b/traitsui/wx/ui_panel.py @@ -65,22 +65,20 @@ def ui_panel(ui, parent): - """ Creates a panel-based wxPython user interface for a specified UI object. - """ + """Creates a panel-based wxPython user interface for a specified UI object.""" ui_panel_for(ui, parent, True) def ui_subpanel(ui, parent): - """ Creates a subpanel-based wxPython user interface for a specified UI - object. A subpanel does not allow control buttons (other than those - specified in the UI object). + """Creates a subpanel-based wxPython user interface for a specified UI + object. A subpanel does not allow control buttons (other than those + specified in the UI object). """ ui_panel_for(ui, parent, False) def ui_panel_for(ui, parent, buttons): - """ Creates a panel-based wxPython user interface for a specified UI object. - """ + """Creates a panel-based wxPython user interface for a specified UI object.""" # Disable screen updates on the parent control while we build the view: parent.Freeze() @@ -105,12 +103,10 @@ def ui_panel_for(ui, parent, buttons): class Panel(BaseDialog): - """ wxPython user interface panel for Traits-based user interfaces. - """ + """wxPython user interface panel for Traits-based user interfaces.""" def __init__(self, ui, parent, allow_buttons): - """ Initializes the object. - """ + """Initializes the object.""" self.ui = ui history = None view = ui.view @@ -218,26 +214,22 @@ def __init__(self, ui, parent, allow_buttons): cpanel.SetSizerAndFit(sw_sizer) def _on_undoable(self, event): - """ Handles a change to the "undoable" state of the undo history. - """ + """Handles a change to the "undoable" state of the undo history.""" state = event.new self.undo.Enable(state) def _on_redoable(self, event): - """ Handles a change to the "redoable" state of the undo history. - """ + """Handles a change to the "redoable" state of the undo history.""" state = event.new self.redo.Enable(state) def _on_revertable(self, event): - """ Handles a change to the "revert" state. - """ + """Handles a change to the "revert" state.""" state = event.new self.revert.Enable(state) def add_toolbar(self, sizer): - """ Adds an optional toolbar to the dialog. - """ + """Adds an optional toolbar to the dialog.""" toolbar = self.ui.view.toolbar if toolbar is not None: self._last_group = self._last_parent = None @@ -255,9 +247,9 @@ def add_toolbar(self, sizer): def panel(ui, parent): - """ Creates a panel-based wxPython user interface for a specified UI object. + """Creates a panel-based wxPython user interface for a specified UI object. - This function does not modify the UI object passed to it + This function does not modify the UI object passed to it """ # Bind the context values to the 'info' object: ui.info.bind_context() @@ -304,8 +296,8 @@ def panel(ui, parent): def create_notebook_for_items( content, ui, parent, group, item_handler=None, is_dock_window=False ): - """ Creates a notebook and adds a list of groups or items to it as separate - pages. + """Creates a notebook and adds a list of groups or items to it as separate + pages. """ if is_dock_window: nb = parent @@ -384,8 +376,7 @@ def _page_changed(event): def show_help(ui, button): - """ Displays a help window for the specified UI's active Group. - """ + """Displays a help window for the specified UI's active Group.""" group = ui._groups[ui._active_group] template = help_template() if group.help != "": @@ -404,8 +395,7 @@ def show_help(ui, button): def show_help_popup(event): - """ Displays a pop-up help window for a single trait. - """ + """Displays a pop-up help window for a single trait.""" control = event.GetEventObject() template = help_template() @@ -426,8 +416,8 @@ def fill_panel_for_group( is_dock_window=False, create_panel=False, ): - """ Builds the user interface for a specified Group within a specified - Panel. + """Builds the user interface for a specified Group within a specified + Panel. """ fp = FillPanel( panel, group, ui, suppress_label, is_dock_window, create_panel @@ -436,14 +426,12 @@ def fill_panel_for_group( class FillPanel(object): - """ A subpanel for a single group of items. - """ + """A subpanel for a single group of items.""" def __init__( self, panel, group, ui, suppress_label, is_dock_window, create_panel ): - """ Initializes the object. - """ + """Initializes the object.""" # Get the contents of the group: content = group.get_content() @@ -606,8 +594,8 @@ def __init__( ) def add_dock_window_splitter_items(self, window, content, group): - """ Adds a set of groups or items separated by splitter bars to a - DockWindow. + """Adds a set of groups or items separated by splitter bars to a + DockWindow. """ contents = [ self.add_dock_window_splitter_item(window, item, group) @@ -626,8 +614,7 @@ def add_dock_window_splitter_items(self, window, content, group): return result def add_dock_window_splitter_item(self, window, item, group): - """ Adds a single group or item to a DockWindow. - """ + """Adds a single group or item to a DockWindow.""" if isinstance(item, Group): sizer, resizable, contents = fill_panel_for_group( window, item, self.ui, suppress_label=True, is_dock_window=True @@ -661,14 +648,13 @@ def add_dock_window_splitter_item(self, window, item, group): ) def create_fold_for_items(self, window, content): - """ Adds a set of groups or items as vertical notebook pages to a - vertical notebook. + """Adds a set of groups or items as vertical notebook pages to a + vertical notebook. """ raise NotImplementedError("VFold is not implemented for Wx backend") def create_fold_for_item(self, notebook, item): - """ Adds a single group or item to a vertical notebook. - """ + """Adds a single group or item to a vertical notebook.""" # Create a new notebook page: page = notebook.create_page() @@ -695,13 +681,11 @@ def create_fold_for_item(self, notebook, item): return page def add_notebook_item(self, item, parent, sizer): - """ Adds a single Item to a notebook. - """ + """Adds a single Item to a notebook.""" self.add_items([item], parent, sizer) def add_groups(self, content, panel): - """ Adds a list of Group objects to the panel. - """ + """Adds a list of Group objects to the panel.""" sizer = self.sizer # Process each group: @@ -730,15 +714,15 @@ def add_groups(self, content, panel): def _label_when(self): """Set the visible and enabled states of all labels as controlled by - a 'visible_when' or 'enabled_when' expression. + a 'visible_when' or 'enabled_when' expression. """ self._evaluate_label_condition(self._label_enabled_whens, "enabled") self._evaluate_label_condition(self._label_visible_whens, "visible") def _evaluate_label_condition(self, conditions, kind): """Evaluates a list of (eval, widget) pairs and calls the appropriate - method on the label widget to toggle whether it is visible/enabled - as needed. + method on the label widget to toggle whether it is visible/enabled + as needed. """ context = self.ui._get_context(self.ui.context) @@ -756,8 +740,7 @@ def _evaluate_label_condition(self, conditions, kind): raise_to_debug() def add_items(self, content, panel, sizer): - """ Adds a list of Item objects to the panel. - """ + """Adds a list of Item objects to the panel.""" # Get local references to various objects we need: ui = self.ui info = ui.info @@ -835,9 +818,13 @@ def add_items(self, content, panel, sizer): self._add_emphasis(label) if item.visible_when: - self._label_visible_whens.append((item.visible_when, label)) + self._label_visible_whens.append( + (item.visible_when, label) + ) if item.enabled_when: - self._label_enabled_whens.append((item.enabled_when, label)) + self._label_enabled_whens.append( + (item.enabled_when, label) + ) # Continue on to the next Item in the list: continue @@ -1069,9 +1056,13 @@ def add_items(self, content, panel, sizer): # Save the reference to the label control (if any) in the editor: editor.label_control = label - if (len(self._label_enabled_whens) + len(self._label_visible_whens)) > 0: + if ( + len(self._label_enabled_whens) + len(self._label_visible_whens) + ) > 0: for object in self.ui.context.values(): - object.on_trait_change(lambda: self._label_when(), dispatch="ui") + object.on_trait_change( + lambda: self._label_when(), dispatch="ui" + ) # If we created a grid sizer, add it to the original sizer: if item_sizer is not sizer: @@ -1092,8 +1083,7 @@ def create_label( pad_side=wx.LEFT, border=False, ): - """ Creates an item label. - """ + """Creates an item label.""" label = item.get_label(ui) if (label == "") or (label[-1:] in "?=:;,.<>/\\\"'-+#|"): suffix = "" @@ -1128,15 +1118,13 @@ def create_label( return control def dummy_label(self, parent, sizer): - """ Creates an item label. - """ + """Creates an item label.""" control = wx.StaticText(parent, -1, "", style=wx.ALIGN_RIGHT) sizer.Add(control, 0) return control def _add_emphasis(self, control): - """ Adds emphasis to a specified control's font. - """ + """Adds emphasis to a specified control's font.""" global emphasis_font control.SetForegroundColour(emphasis_color) @@ -1157,8 +1145,7 @@ def _set_owner(self, control, owner): class DockWindowGroupEditor(GroupEditor): - """ Editor for a group which displays a DockWindow. - """ + """Editor for a group which displays a DockWindow.""" # ------------------------------------------------------------------------- # Trait definitions: @@ -1170,8 +1157,8 @@ class DockWindowGroupEditor(GroupEditor): # -- UI preference save/restore interface --------------------------------- def restore_prefs(self, prefs): - """ Restores any saved user preference information associated with the - editor. + """Restores any saved user preference information associated with the + editor. """ if isinstance(prefs, dict): structure = prefs.get("structure") @@ -1181,20 +1168,17 @@ def restore_prefs(self, prefs): self.dock_window.Layout() def save_prefs(self): - """ Returns any user preference information associated with the editor. - """ + """Returns any user preference information associated with the editor.""" return {"structure": self.dock_window.GetSizer().GetStructure()} # -- End UI preference save/restore interface ----------------------------- class HTMLHelpWindow(wx.Frame): - """ Window for displaying Traits-based help text with HTML formatting. - """ + """Window for displaying Traits-based help text with HTML formatting.""" def __init__(self, parent, html_content, scale_dx, scale_dy): - """ Initializes the object. - """ + """Initializes the object.""" wx.Frame.__init__(self, parent, -1, "Help", style=wx.SIMPLE_BORDER) self.SetBackgroundColour(WindowColor) @@ -1212,8 +1196,10 @@ def __init__(self, parent, html_content, scale_dx, scale_dy): sizer.Add(b_sizer, 0, wx.ALIGN_RIGHT | wx.ALL, 5) self.SetSizer(sizer) self.SetSize( - wx.Size(int(scale_dx * SystemMetrics().screen_width), - int(scale_dy * SystemMetrics().screen_height)) + wx.Size( + int(scale_dx * SystemMetrics().screen_width), + int(scale_dy * SystemMetrics().screen_height), + ) ) # Position and show the dialog: @@ -1221,8 +1207,7 @@ def __init__(self, parent, html_content, scale_dx, scale_dy): self.Show() def _on_ok(self, event): - """ Handles the window being closed. - """ + """Handles the window being closed.""" self.Unbind(wx.EVT_BUTTON) self.Destroy() @@ -1235,8 +1220,7 @@ def _on_ok(self, event): def heading_text(*args, **kw): - """ Creates a Pyface HeadingText control. - """ + """Creates a Pyface HeadingText control.""" global HeadingText if HeadingText is None: diff --git a/traitsui/wx/ui_window.py b/traitsui/wx/ui_window.py index be4c7a5da..1c3716ed1 100644 --- a/traitsui/wx/ui_window.py +++ b/traitsui/wx/ui_window.py @@ -24,8 +24,7 @@ class UIWindow(HasPrivateTraits): - """ A base class for creating custom Traits UI windows. - """ + """A base class for creating custom Traits UI windows.""" #: The wx.Window associated with this custom window: control = Instance(wx.Window) @@ -42,8 +41,7 @@ class UIWindow(HasPrivateTraits): # -- Public Methods ------------------------------------------------------- def __init__(self, parent, **traits): - """ Creates and initializes the window. - """ + """Creates and initializes the window.""" super().__init__(**traits) self.control = wx.Window( parent, -1, size=self.size, style=wx.FULL_REPAINT_ON_RESIZE @@ -51,8 +49,7 @@ def __init__(self, parent, **traits): init_wx_handlers(self.control, self) def refresh(self, x=None, y=None, dx=None, dy=None): - """ Refreshes the contents of the window. - """ + """Refreshes the contents of the window.""" if self.control is not None: if x is None: self.control.Refresh() @@ -60,32 +57,28 @@ def refresh(self, x=None, y=None, dx=None, dy=None): self.control.Refresh(x, y, dx, dy) def capture(self): - """ Capture the mouse. - """ + """Capture the mouse.""" self.control.CaptureMouse() def release(self): - """ Release the mouse. - """ + """Release the mouse.""" self.control.ReleaseMouse() # -- wxPython Event Handlers ---------------------------------------------- def _erase_background(self, event): - """ Never, ever, do anything in this handler. - """ + """Never, ever, do anything in this handler.""" pass def _paint(self, event): - """ Paints the contents of the window. - """ + """Paints the contents of the window.""" dc = BufferDC(self.control) self._paint_dc(dc) dc.copy() def _paint_dc(self, dc): - """ This method should be overridden by sub-classes to do the actual - window painting. + """This method should be overridden by sub-classes to do the actual + window painting. """ pass diff --git a/traitsui/wx/ui_wizard.py b/traitsui/wx/ui_wizard.py index 9a16bdd7e..a715611ee 100644 --- a/traitsui/wx/ui_wizard.py +++ b/traitsui/wx/ui_wizard.py @@ -33,13 +33,15 @@ def ui_wizard(ui, parent): - """ Creates a wizard-based wxPython user interface for a specified UI + """Creates a wizard-based wxPython user interface for a specified UI object. """ # Create the copy of the 'context' we will need while editing: ui._context = context = ui.context - new_context = {name: None if value is None else value.clone_traits() - for name, value in context.items()} + new_context = { + name: None if value is None else value.clone_traits() + for name, value in context.items() + } ui.context = new_context # Now bind the context values to the 'info' object: @@ -151,8 +153,7 @@ def ui_wizard(ui, parent): def page_changing(event): - """ Handles the user attempting to change the current wizard page. - """ + """Handles the user attempting to change the current wizard page.""" # Get the page the user is trying to go to: page = event.GetPage() if event.GetDirection(): @@ -161,9 +162,11 @@ def page_changing(event): new_page = page.GetPrev() # If the page has a disabled PageGroupEditor object, veto the page change: - if ((new_page is not None) - and (new_page.editor is not None) - and (not new_page.editor.enabled)): + if ( + (new_page is not None) + and (new_page.editor is not None) + and (not new_page.editor.enabled) + ): event.Veto() # If their is a message associated with the editor, display it: @@ -173,8 +176,7 @@ def page_changing(event): class UIWizardPage(wz.WizardPage): - """ A page within a wizard interface. - """ + """A page within a wizard interface.""" def __init__(self, wizard, pages): super().__init__(wizard) @@ -182,18 +184,15 @@ def __init__(self, wizard, pages): self.pages = pages def SetNext(self, page): - """ Sets the next page after this one. - """ + """Sets the next page after this one.""" self.next = page def SetPrev(self, page): - """ Sets the previous page to this one. - """ + """Sets the previous page to this one.""" self.previous = page def GetNext(self): - """ Returns the next page after this one. - """ + """Returns the next page after this one.""" editor = self.editor if (editor is not None) and (editor.next != ""): next_ = editor.next @@ -205,8 +204,7 @@ def GetNext(self): return self.next def GetPrev(self): - """ Returns the previous page to this one. - """ + """Returns the previous page to this one.""" editor = self.editor if (editor is not None) and (editor.previous != ""): previous = editor.previous @@ -219,8 +217,7 @@ def GetPrev(self): class PageGroupEditor(GroupEditor): - """ Editor for a group, which displays a page. - """ + """Editor for a group, which displays a page.""" # ------------------------------------------------------------------------- # Trait definitions: diff --git a/traitsui/wx/value_editor.py b/traitsui/wx/value_editor.py index 7b4691696..69f4900ff 100644 --- a/traitsui/wx/value_editor.py +++ b/traitsui/wx/value_editor.py @@ -19,16 +19,14 @@ class SimpleEditor(_ValueEditor, Editor): - """ Returns the editor to use for simple style views. - """ + """Returns the editor to use for simple style views.""" #: Override the value of the readonly trait. readonly = False class ReadonlyEditor(_ValueEditor, Editor): - """ Returns the editor to use for readonly style views. - """ + """Returns the editor to use for readonly style views.""" #: Override the value of the readonly trait. readonly = True diff --git a/traitsui/wx/view_application.py b/traitsui/wx/view_application.py index 7cdee4a16..a16ffea01 100644 --- a/traitsui/wx/view_application.py +++ b/traitsui/wx/view_application.py @@ -36,8 +36,7 @@ def on_ui_destroyed(object, name, old, destroyed): - """ Remove the UI object from KEEP_ALIVE_UIS. - """ + """Remove the UI object from KEEP_ALIVE_UIS.""" assert name == "destroyed" if destroyed: assert object in KEEP_ALIVE_UIS @@ -51,7 +50,7 @@ def on_ui_destroyed(object, name, old, destroyed): def view_application(context, view, kind, handler, id, scrollable, args): - """ Creates a stand-alone wx Application to display a specified traits UI + """Creates a stand-alone wx Application to display a specified traits UI View. Parameters @@ -108,12 +107,10 @@ def view_application(context, view, kind, handler, id, scrollable, args): class ViewApplication(wx.App): - """ Modal window that contains a stand-alone application. - """ + """Modal window that contains a stand-alone application.""" def __init__(self, context, view, kind, handler, id, scrollable, args): - """ Initializes the object. - """ + """Initializes the object.""" self.context = context self.view = view self.kind = kind @@ -134,8 +131,7 @@ def __init__(self, context, view, kind, handler, id, scrollable, args): logger.exception("Event loop failed to close cleanly:") def OnInit(self): - """ Handles application initialization. - """ + """Handles application initialization.""" self.ui = self.view.ui( self.context, kind=self.kind,