We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Clipboard implementation leads to wrong logs when choosing sdl2 or gtk3
https://gist.github.com/anonymous/1dfd55b91a319b2e1393
Courtesy Dessant for reporting.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `kivy/core/clipboard/__init__.py`
Content:
```
1 '''
2 Clipboard
3 =========
4 
5 Core class for accessing the Clipboard. If we are not able to access the
6 system clipboard, a fake one will be used.
7 
8 Usage example::
9 
10     >>> from kivy.core.clipboard import Clipboard
11     >>> Clipboard.get_types()
12     ['TIMESTAMP', 'TARGETS', 'MULTIPLE', 'SAVE_TARGETS', 'UTF8_STRING',
13     'COMPOUND_TEXT', 'TEXT', 'STRING', 'text/plain;charset=utf-8',
14     'text/plain']
15     >>> Clipboard.get('TEXT')
16     'Hello World'
17     >>> Clipboard.put('Great', 'UTF8_STRING')
18     >>> Clipboard.get_types()
19     ['UTF8_STRING']
20     >>> Clipboard.get('UTF8_STRING')
21     'Great'
22 
23 .. note:: The main implementation relies on Pygame and works well with
24           text/strings. Anything else might not work the same on all platforms.
25 '''
26 
27 __all__ = ('ClipboardBase', 'Clipboard')
28 
29 from kivy import Logger
30 from kivy.core import core_select_lib
31 from kivy.utils import platform
32 from kivy.setupconfig import USE_SDL2
33 
34 
35 class ClipboardBase(object):
36 
37     def get(self, mimetype):
38         '''Get the current data in clipboard, using the mimetype if possible.
39         You not use this method directly. Use :meth:`paste` instead.
40         '''
41         return None
42 
43     def put(self, data, mimetype):
44         '''Put data on the clipboard, and attach a mimetype.
45         You should not use this method directly. Use :meth:`copy` instead.
46         '''
47         pass
48 
49     def get_types(self):
50         '''Return a list of supported mimetypes
51         '''
52         return []
53 
54     def _ensure_clipboard(self):
55         ''' Ensure that the clipboard has been properly initialised.
56         '''
57 
58         if hasattr(self, '_clip_mime_type'):
59             return
60 
61         if platform == 'win':
62             self._clip_mime_type = 'text/plain;charset=utf-8'
63             # windows clipboard uses a utf-16 little endian encoding
64             self._encoding = 'utf-16-le'
65         elif platform == 'linux':
66             self._clip_mime_type = 'text/plain;charset=utf-8'
67             self._encoding = 'utf-8'
68         else:
69             self._clip_mime_type = 'text/plain'
70             self._encoding = 'utf-8'
71 
72     def copy(self, data=''):
73         ''' Copy the value provided in argument `data` into current clipboard.
74         If data is not of type string it will be converted to string.
75 
76         .. versionadded:: 1.9.0
77 
78         '''
79         if data:
80             self._copy(data)
81 
82     def paste(self):
83         ''' Get text from the system clipboard and return it a usable string.
84 
85         .. versionadded:: 1.9.0
86 
87         '''
88         return self._paste()
89 
90     def _copy(self, data):
91         # explicitly terminate strings with a null character
92         # so as to avoid putting spurious data after the end.
93         # MS windows issue.
94         self._ensure_clipboard()
95         if not isinstance(data, bytes):
96             data = data.encode(self._encoding)
97         if platform == 'win':
98             data += b'\x00'
99         self.put(data, self._clip_mime_type)
100 
101     def _paste(self):
102         self._ensure_clipboard()
103         _clip_types = Clipboard.get_types()
104 
105         mime_type = self._clip_mime_type
106         if mime_type not in _clip_types:
107             mime_type = 'text/plain'
108 
109         data = self.get(mime_type)
110         if data is not None:
111             # decode only if we don't have unicode
112             # we would still need to decode from utf-16 (windows)
113             # data is of type bytes in PY3
114             if isinstance(data, bytes):
115                 data = data.decode(self._encoding, 'ignore')
116             # remove null strings mostly a windows issue
117             data = data.replace(u'\x00', u'')
118             return data
119         return u''
120 
121 
122 # load clipboard implementation
123 _clipboards = []
124 if platform == 'android':
125     _clipboards.append(
126         ('android', 'clipboard_android', 'ClipboardAndroid'))
127 elif platform == 'macosx':
128     _clipboards.append(
129         ('nspaste', 'clipboard_nspaste', 'ClipboardNSPaste'))
130 elif platform == 'win':
131     _clipboards.append(
132         ('winctypes', 'clipboard_winctypes', 'ClipboardWindows'))
133 elif platform == 'linux':
134     _clipboards.append(
135         ('dbusklipper', 'clipboard_dbusklipper', 'ClipboardDbusKlipper'))
136     _clipboards.append(
137         ('gtk3', 'clipboard_gtk3', 'ClipboardGtk3'))
138     _clipboards.append(
139         ('xclip', 'clipboard_xclip', 'ClipboardXclip'))
140     _clipboards.append(
141         ('xsel', 'clipboard_xsel', 'ClipboardXsel'))
142 
143 if USE_SDL2:
144     _clipboards.append(
145         ('sdl2', 'clipboard_sdl2', 'ClipboardSDL2'))
146 else:
147     _clipboards.append(
148         ('pygame', 'clipboard_pygame', 'ClipboardPygame'))
149 
150 _clipboards.append(
151     ('dummy', 'clipboard_dummy', 'ClipboardDummy'))
152 
153 Clipboard = core_select_lib('clipboard', _clipboards, True)
154 CutBuffer = None
155 
156 if platform == 'linux':
157     _cutbuffers = [
158         ('xclip', 'clipboard_xclip', 'ClipboardXclip'),
159         ('xsel', 'clipboard_xsel', 'ClipboardXsel'),
160     ]
161 
162     if Clipboard.__class__.__name__ in (c[2] for c in _cutbuffers):
163         CutBuffer = Clipboard
164     else:
165         CutBuffer = core_select_lib('clipboard', _cutbuffers, True)
166 
167     if CutBuffer:
168         Logger.info('CutBuffer: cut buffer support enabled')
169
```

Path: `kivy/core/__init__.py`
Content:
```
1 '''
2 Core Abstraction
3 ================
4 
5 This module defines the abstraction layers for our core providers and their
6 implementations. For further information, please refer to
7 :ref:`architecture` and the :ref:`providers` section of the documentation.
8 
9 In most cases, you shouldn't directly use a library that's already covered
10 by the core abstraction. Always try to use our providers first.
11 In case we are missing a feature or method, please let us know by
12 opening a new Bug report instead of relying on your library.
13 
14 .. warning::
15     These are **not** widgets! These are just abstractions of the respective
16     functionality. For example, you cannot add a core image to your window.
17     You have to use the image **widget** class instead. If you're really
18     looking for widgets, please refer to :mod:`kivy.uix` instead.
19 '''
20 
21 
22 import os
23 import sys
24 import traceback
25 import kivy
26 from kivy.logger import Logger
27 
28 
29 class CoreCriticalException(Exception):
30     pass
31 
32 
33 def core_select_lib(category, llist, create_instance=False, base='kivy.core'):
34     if 'KIVY_DOC' in os.environ:
35         return
36     category = category.lower()
37     libs_ignored = []
38     errs = []
39     for option, modulename, classname in llist:
40         try:
41             # module activated in config ?
42             try:
43                 if option not in kivy.kivy_options[category]:
44                     libs_ignored.append(modulename)
45                     Logger.debug(
46                         '{0}: Provider <{1}> ignored by config'.format(
47                             category.capitalize(), option))
48                     continue
49             except KeyError:
50                 pass
51 
52             # import module
53             mod = __import__(name='{2}.{0}.{1}'.format(
54                 category, modulename, base),
55                 globals=globals(),
56                 locals=locals(),
57                 fromlist=[modulename], level=0)
58             cls = mod.__getattribute__(classname)
59 
60             # ok !
61             Logger.info('{0}: Provider: {1}{2}'.format(
62                 category.capitalize(), option,
63                 '({0} ignored)'.format(libs_ignored) if libs_ignored else ''))
64             if create_instance:
65                 cls = cls()
66             return cls
67 
68         except ImportError as e:
69             errs.append((option, e, sys.exc_info()[2]))
70             libs_ignored.append(modulename)
71             Logger.debug('{0}: Ignored <{1}> (import error)'.format(
72                 category.capitalize(), option))
73             Logger.trace('', exc_info=e)
74 
75         except CoreCriticalException as e:
76             errs.append((option, e, sys.exc_info()[2]))
77             Logger.error('{0}: Unable to use {1}'.format(
78                 category.capitalize(), option))
79             Logger.error(
80                 '{0}: The module raised an important error: {1!r}'.format(
81                     category.capitalize(), e.message))
82             raise
83 
84         except Exception as e:
85             errs.append((option, e, sys.exc_info()[2]))
86             libs_ignored.append(modulename)
87             Logger.trace('{0}: Unable to use {1}'.format(
88                 category.capitalize(), option, category))
89             Logger.trace('', exc_info=e)
90 
91     err = '\n'.join(['{} - {}: {}\n{}'.format(opt, e.__class__.__name__, e,
92                    ''.join(traceback.format_tb(tb))) for opt, e, tb in errs])
93     Logger.critical(
94         '{0}: Unable to find any valuable {0} provider at all!\n{1}'.format(
95             category.capitalize(), err))
96 
97 
98 def core_register_libs(category, libs, base='kivy.core'):
99     if 'KIVY_DOC' in os.environ:
100         return
101     category = category.lower()
102     kivy_options = kivy.kivy_options[category]
103     libs_loadable = {}
104     libs_ignored = []
105 
106     for option, lib in libs:
107         # module activated in config ?
108         if option not in kivy_options:
109             Logger.debug('{0}: option <{1}> ignored by config'.format(
110                 category.capitalize(), option))
111             libs_ignored.append(lib)
112             continue
113         libs_loadable[option] = lib
114 
115     libs_loaded = []
116     for item in kivy_options:
117         try:
118             # import module
119             try:
120                 lib = libs_loadable[item]
121             except KeyError:
122                 continue
123             __import__(name='{2}.{0}.{1}'.format(category, lib, base),
124                        globals=globals(),
125                        locals=locals(),
126                        fromlist=[lib],
127                        level=0)
128 
129             libs_loaded.append(lib)
130 
131         except Exception as e:
132             Logger.trace('{0}: Unable to use <{1}> as loader!'.format(
133                 category.capitalize(), option))
134             Logger.trace('', exc_info=e)
135             libs_ignored.append(lib)
136 
137     Logger.info('{0}: Providers: {1} {2}'.format(
138         category.capitalize(),
139         ', '.join(libs_loaded),
140         '({0} ignored)'.format(
141             ', '.join(libs_ignored)) if libs_ignored else ''))
142     return libs_loaded
143
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/kivy/core/__init__.py b/kivy/core/__init__.py
--- a/kivy/core/__init__.py
+++ b/kivy/core/__init__.py
@@ -30,10 +30,11 @@
     pass
 
 
-def core_select_lib(category, llist, create_instance=False, base='kivy.core'):
+def core_select_lib(category, llist, create_instance=False, base='kivy.core', basemodule=None):
     if 'KIVY_DOC' in os.environ:
         return
     category = category.lower()
+    basemodule = basemodule or category
     libs_ignored = []
     errs = []
     for option, modulename, classname in llist:
@@ -51,7 +52,7 @@
 
             # import module
             mod = __import__(name='{2}.{0}.{1}'.format(
-                category, modulename, base),
+                basemodule, modulename, base),
                 globals=globals(),
                 locals=locals(),
                 fromlist=[modulename], level=0)
diff --git a/kivy/core/clipboard/__init__.py b/kivy/core/clipboard/__init__.py
--- a/kivy/core/clipboard/__init__.py
+++ b/kivy/core/clipboard/__init__.py
@@ -162,7 +162,7 @@
     if Clipboard.__class__.__name__ in (c[2] for c in _cutbuffers):
         CutBuffer = Clipboard
     else:
-        CutBuffer = core_select_lib('clipboard', _cutbuffers, True)
+        CutBuffer = core_select_lib('cutbuffer', _cutbuffers, True, basemodule='clipboard')
 
     if CutBuffer:
         Logger.info('CutBuffer: cut buffer support enabled')

{"golden_diff": "diff --git a/kivy/core/__init__.py b/kivy/core/__init__.py\n--- a/kivy/core/__init__.py\n+++ b/kivy/core/__init__.py\n@@ -30,10 +30,11 @@\n     pass\n \n \n-def core_select_lib(category, llist, create_instance=False, base='kivy.core'):\n+def core_select_lib(category, llist, create_instance=False, base='kivy.core', basemodule=None):\n     if 'KIVY_DOC' in os.environ:\n         return\n     category = category.lower()\n+    basemodule = basemodule or category\n     libs_ignored = []\n     errs = []\n     for option, modulename, classname in llist:\n@@ -51,7 +52,7 @@\n \n             # import module\n             mod = __import__(name='{2}.{0}.{1}'.format(\n-                category, modulename, base),\n+                basemodule, modulename, base),\n                 globals=globals(),\n                 locals=locals(),\n                 fromlist=[modulename], level=0)\ndiff --git a/kivy/core/clipboard/__init__.py b/kivy/core/clipboard/__init__.py\n--- a/kivy/core/clipboard/__init__.py\n+++ b/kivy/core/clipboard/__init__.py\n@@ -162,7 +162,7 @@\n     if Clipboard.__class__.__name__ in (c[2] for c in _cutbuffers):\n         CutBuffer = Clipboard\n     else:\n-        CutBuffer = core_select_lib('clipboard', _cutbuffers, True)\n+        CutBuffer = core_select_lib('cutbuffer', _cutbuffers, True, basemodule='clipboard')\n \n     if CutBuffer:\n         Logger.info('CutBuffer: cut buffer support enabled')\n", "issue": "Clipboard implementation leads to wrong logs when choosing sdl2 or gtk3\nhttps://gist.github.com/anonymous/1dfd55b91a319b2e1393\nCourtesy Dessant for reporting.\n\n", "before_files": [{"content": "'''\nClipboard\n=========\n\nCore class for accessing the Clipboard. If we are not able to access the\nsystem clipboard, a fake one will be used.\n\nUsage example::\n\n    >>> from kivy.core.clipboard import Clipboard\n    >>> Clipboard.get_types()\n    ['TIMESTAMP', 'TARGETS', 'MULTIPLE', 'SAVE_TARGETS', 'UTF8_STRING',\n    'COMPOUND_TEXT', 'TEXT', 'STRING', 'text/plain;charset=utf-8',\n    'text/plain']\n    >>> Clipboard.get('TEXT')\n    'Hello World'\n    >>> Clipboard.put('Great', 'UTF8_STRING')\n    >>> Clipboard.get_types()\n    ['UTF8_STRING']\n    >>> Clipboard.get('UTF8_STRING')\n    'Great'\n\n.. note:: The main implementation relies on Pygame and works well with\n          text/strings. Anything else might not work the same on all platforms.\n'''\n\n__all__ = ('ClipboardBase', 'Clipboard')\n\nfrom kivy import Logger\nfrom kivy.core import core_select_lib\nfrom kivy.utils import platform\nfrom kivy.setupconfig import USE_SDL2\n\n\nclass ClipboardBase(object):\n\n    def get(self, mimetype):\n        '''Get the current data in clipboard, using the mimetype if possible.\n        You not use this method directly. Use :meth:`paste` instead.\n        '''\n        return None\n\n    def put(self, data, mimetype):\n        '''Put data on the clipboard, and attach a mimetype.\n        You should not use this method directly. Use :meth:`copy` instead.\n        '''\n        pass\n\n    def get_types(self):\n        '''Return a list of supported mimetypes\n        '''\n        return []\n\n    def _ensure_clipboard(self):\n        ''' Ensure that the clipboard has been properly initialised.\n        '''\n\n        if hasattr(self, '_clip_mime_type'):\n            return\n\n        if platform == 'win':\n            self._clip_mime_type = 'text/plain;charset=utf-8'\n            # windows clipboard uses a utf-16 little endian encoding\n            self._encoding = 'utf-16-le'\n        elif platform == 'linux':\n            self._clip_mime_type = 'text/plain;charset=utf-8'\n            self._encoding = 'utf-8'\n        else:\n            self._clip_mime_type = 'text/plain'\n            self._encoding = 'utf-8'\n\n    def copy(self, data=''):\n        ''' Copy the value provided in argument `data` into current clipboard.\n        If data is not of type string it will be converted to string.\n\n        .. versionadded:: 1.9.0\n\n        '''\n        if data:\n            self._copy(data)\n\n    def paste(self):\n        ''' Get text from the system clipboard and return it a usable string.\n\n        .. versionadded:: 1.9.0\n\n        '''\n        return self._paste()\n\n    def _copy(self, data):\n        # explicitly terminate strings with a null character\n        # so as to avoid putting spurious data after the end.\n        # MS windows issue.\n        self._ensure_clipboard()\n        if not isinstance(data, bytes):\n            data = data.encode(self._encoding)\n        if platform == 'win':\n            data += b'\\x00'\n        self.put(data, self._clip_mime_type)\n\n    def _paste(self):\n        self._ensure_clipboard()\n        _clip_types = Clipboard.get_types()\n\n        mime_type = self._clip_mime_type\n        if mime_type not in _clip_types:\n            mime_type = 'text/plain'\n\n        data = self.get(mime_type)\n        if data is not None:\n            # decode only if we don't have unicode\n            # we would still need to decode from utf-16 (windows)\n            # data is of type bytes in PY3\n            if isinstance(data, bytes):\n                data = data.decode(self._encoding, 'ignore')\n            # remove null strings mostly a windows issue\n            data = data.replace(u'\\x00', u'')\n            return data\n        return u''\n\n\n# load clipboard implementation\n_clipboards = []\nif platform == 'android':\n    _clipboards.append(\n        ('android', 'clipboard_android', 'ClipboardAndroid'))\nelif platform == 'macosx':\n    _clipboards.append(\n        ('nspaste', 'clipboard_nspaste', 'ClipboardNSPaste'))\nelif platform == 'win':\n    _clipboards.append(\n        ('winctypes', 'clipboard_winctypes', 'ClipboardWindows'))\nelif platform == 'linux':\n    _clipboards.append(\n        ('dbusklipper', 'clipboard_dbusklipper', 'ClipboardDbusKlipper'))\n    _clipboards.append(\n        ('gtk3', 'clipboard_gtk3', 'ClipboardGtk3'))\n    _clipboards.append(\n        ('xclip', 'clipboard_xclip', 'ClipboardXclip'))\n    _clipboards.append(\n        ('xsel', 'clipboard_xsel', 'ClipboardXsel'))\n\nif USE_SDL2:\n    _clipboards.append(\n        ('sdl2', 'clipboard_sdl2', 'ClipboardSDL2'))\nelse:\n    _clipboards.append(\n        ('pygame', 'clipboard_pygame', 'ClipboardPygame'))\n\n_clipboards.append(\n    ('dummy', 'clipboard_dummy', 'ClipboardDummy'))\n\nClipboard = core_select_lib('clipboard', _clipboards, True)\nCutBuffer = None\n\nif platform == 'linux':\n    _cutbuffers = [\n        ('xclip', 'clipboard_xclip', 'ClipboardXclip'),\n        ('xsel', 'clipboard_xsel', 'ClipboardXsel'),\n    ]\n\n    if Clipboard.__class__.__name__ in (c[2] for c in _cutbuffers):\n        CutBuffer = Clipboard\n    else:\n        CutBuffer = core_select_lib('clipboard', _cutbuffers, True)\n\n    if CutBuffer:\n        Logger.info('CutBuffer: cut buffer support enabled')\n", "path": "kivy/core/clipboard/__init__.py"}, {"content": "'''\nCore Abstraction\n================\n\nThis module defines the abstraction layers for our core providers and their\nimplementations. For further information, please refer to\n:ref:`architecture` and the :ref:`providers` section of the documentation.\n\nIn most cases, you shouldn't directly use a library that's already covered\nby the core abstraction. Always try to use our providers first.\nIn case we are missing a feature or method, please let us know by\nopening a new Bug report instead of relying on your library.\n\n.. warning::\n    These are **not** widgets! These are just abstractions of the respective\n    functionality. For example, you cannot add a core image to your window.\n    You have to use the image **widget** class instead. If you're really\n    looking for widgets, please refer to :mod:`kivy.uix` instead.\n'''\n\n\nimport os\nimport sys\nimport traceback\nimport kivy\nfrom kivy.logger import Logger\n\n\nclass CoreCriticalException(Exception):\n    pass\n\n\ndef core_select_lib(category, llist, create_instance=False, base='kivy.core'):\n    if 'KIVY_DOC' in os.environ:\n        return\n    category = category.lower()\n    libs_ignored = []\n    errs = []\n    for option, modulename, classname in llist:\n        try:\n            # module activated in config ?\n            try:\n                if option not in kivy.kivy_options[category]:\n                    libs_ignored.append(modulename)\n                    Logger.debug(\n                        '{0}: Provider <{1}> ignored by config'.format(\n                            category.capitalize(), option))\n                    continue\n            except KeyError:\n                pass\n\n            # import module\n            mod = __import__(name='{2}.{0}.{1}'.format(\n                category, modulename, base),\n                globals=globals(),\n                locals=locals(),\n                fromlist=[modulename], level=0)\n            cls = mod.__getattribute__(classname)\n\n            # ok !\n            Logger.info('{0}: Provider: {1}{2}'.format(\n                category.capitalize(), option,\n                '({0} ignored)'.format(libs_ignored) if libs_ignored else ''))\n            if create_instance:\n                cls = cls()\n            return cls\n\n        except ImportError as e:\n            errs.append((option, e, sys.exc_info()[2]))\n            libs_ignored.append(modulename)\n            Logger.debug('{0}: Ignored <{1}> (import error)'.format(\n                category.capitalize(), option))\n            Logger.trace('', exc_info=e)\n\n        except CoreCriticalException as e:\n            errs.append((option, e, sys.exc_info()[2]))\n            Logger.error('{0}: Unable to use {1}'.format(\n                category.capitalize(), option))\n            Logger.error(\n                '{0}: The module raised an important error: {1!r}'.format(\n                    category.capitalize(), e.message))\n            raise\n\n        except Exception as e:\n            errs.append((option, e, sys.exc_info()[2]))\n            libs_ignored.append(modulename)\n            Logger.trace('{0}: Unable to use {1}'.format(\n                category.capitalize(), option, category))\n            Logger.trace('', exc_info=e)\n\n    err = '\\n'.join(['{} - {}: {}\\n{}'.format(opt, e.__class__.__name__, e,\n                   ''.join(traceback.format_tb(tb))) for opt, e, tb in errs])\n    Logger.critical(\n        '{0}: Unable to find any valuable {0} provider at all!\\n{1}'.format(\n            category.capitalize(), err))\n\n\ndef core_register_libs(category, libs, base='kivy.core'):\n    if 'KIVY_DOC' in os.environ:\n        return\n    category = category.lower()\n    kivy_options = kivy.kivy_options[category]\n    libs_loadable = {}\n    libs_ignored = []\n\n    for option, lib in libs:\n        # module activated in config ?\n        if option not in kivy_options:\n            Logger.debug('{0}: option <{1}> ignored by config'.format(\n                category.capitalize(), option))\n            libs_ignored.append(lib)\n            continue\n        libs_loadable[option] = lib\n\n    libs_loaded = []\n    for item in kivy_options:\n        try:\n            # import module\n            try:\n                lib = libs_loadable[item]\n            except KeyError:\n                continue\n            __import__(name='{2}.{0}.{1}'.format(category, lib, base),\n                       globals=globals(),\n                       locals=locals(),\n                       fromlist=[lib],\n                       level=0)\n\n            libs_loaded.append(lib)\n\n        except Exception as e:\n            Logger.trace('{0}: Unable to use <{1}> as loader!'.format(\n                category.capitalize(), option))\n            Logger.trace('', exc_info=e)\n            libs_ignored.append(lib)\n\n    Logger.info('{0}: Providers: {1} {2}'.format(\n        category.capitalize(),\n        ', '.join(libs_loaded),\n        '({0} ignored)'.format(\n            ', '.join(libs_ignored)) if libs_ignored else ''))\n    return libs_loaded\n", "path": "kivy/core/__init__.py"}], "after_files": [{"content": "'''\nClipboard\n=========\n\nCore class for accessing the Clipboard. If we are not able to access the\nsystem clipboard, a fake one will be used.\n\nUsage example::\n\n    >>> from kivy.core.clipboard import Clipboard\n    >>> Clipboard.get_types()\n    ['TIMESTAMP', 'TARGETS', 'MULTIPLE', 'SAVE_TARGETS', 'UTF8_STRING',\n    'COMPOUND_TEXT', 'TEXT', 'STRING', 'text/plain;charset=utf-8',\n    'text/plain']\n    >>> Clipboard.get('TEXT')\n    'Hello World'\n    >>> Clipboard.put('Great', 'UTF8_STRING')\n    >>> Clipboard.get_types()\n    ['UTF8_STRING']\n    >>> Clipboard.get('UTF8_STRING')\n    'Great'\n\n.. note:: The main implementation relies on Pygame and works well with\n          text/strings. Anything else might not work the same on all platforms.\n'''\n\n__all__ = ('ClipboardBase', 'Clipboard')\n\nfrom kivy import Logger\nfrom kivy.core import core_select_lib\nfrom kivy.utils import platform\nfrom kivy.setupconfig import USE_SDL2\n\n\nclass ClipboardBase(object):\n\n    def get(self, mimetype):\n        '''Get the current data in clipboard, using the mimetype if possible.\n        You not use this method directly. Use :meth:`paste` instead.\n        '''\n        return None\n\n    def put(self, data, mimetype):\n        '''Put data on the clipboard, and attach a mimetype.\n        You should not use this method directly. Use :meth:`copy` instead.\n        '''\n        pass\n\n    def get_types(self):\n        '''Return a list of supported mimetypes\n        '''\n        return []\n\n    def _ensure_clipboard(self):\n        ''' Ensure that the clipboard has been properly initialised.\n        '''\n\n        if hasattr(self, '_clip_mime_type'):\n            return\n\n        if platform == 'win':\n            self._clip_mime_type = 'text/plain;charset=utf-8'\n            # windows clipboard uses a utf-16 little endian encoding\n            self._encoding = 'utf-16-le'\n        elif platform == 'linux':\n            self._clip_mime_type = 'text/plain;charset=utf-8'\n            self._encoding = 'utf-8'\n        else:\n            self._clip_mime_type = 'text/plain'\n            self._encoding = 'utf-8'\n\n    def copy(self, data=''):\n        ''' Copy the value provided in argument `data` into current clipboard.\n        If data is not of type string it will be converted to string.\n\n        .. versionadded:: 1.9.0\n\n        '''\n        if data:\n            self._copy(data)\n\n    def paste(self):\n        ''' Get text from the system clipboard and return it a usable string.\n\n        .. versionadded:: 1.9.0\n\n        '''\n        return self._paste()\n\n    def _copy(self, data):\n        # explicitly terminate strings with a null character\n        # so as to avoid putting spurious data after the end.\n        # MS windows issue.\n        self._ensure_clipboard()\n        if not isinstance(data, bytes):\n            data = data.encode(self._encoding)\n        if platform == 'win':\n            data += b'\\x00'\n        self.put(data, self._clip_mime_type)\n\n    def _paste(self):\n        self._ensure_clipboard()\n        _clip_types = Clipboard.get_types()\n\n        mime_type = self._clip_mime_type\n        if mime_type not in _clip_types:\n            mime_type = 'text/plain'\n\n        data = self.get(mime_type)\n        if data is not None:\n            # decode only if we don't have unicode\n            # we would still need to decode from utf-16 (windows)\n            # data is of type bytes in PY3\n            if isinstance(data, bytes):\n                data = data.decode(self._encoding, 'ignore')\n            # remove null strings mostly a windows issue\n            data = data.replace(u'\\x00', u'')\n            return data\n        return u''\n\n\n# load clipboard implementation\n_clipboards = []\nif platform == 'android':\n    _clipboards.append(\n        ('android', 'clipboard_android', 'ClipboardAndroid'))\nelif platform == 'macosx':\n    _clipboards.append(\n        ('nspaste', 'clipboard_nspaste', 'ClipboardNSPaste'))\nelif platform == 'win':\n    _clipboards.append(\n        ('winctypes', 'clipboard_winctypes', 'ClipboardWindows'))\nelif platform == 'linux':\n    _clipboards.append(\n        ('dbusklipper', 'clipboard_dbusklipper', 'ClipboardDbusKlipper'))\n    _clipboards.append(\n        ('gtk3', 'clipboard_gtk3', 'ClipboardGtk3'))\n    _clipboards.append(\n        ('xclip', 'clipboard_xclip', 'ClipboardXclip'))\n    _clipboards.append(\n        ('xsel', 'clipboard_xsel', 'ClipboardXsel'))\n\nif USE_SDL2:\n    _clipboards.append(\n        ('sdl2', 'clipboard_sdl2', 'ClipboardSDL2'))\nelse:\n    _clipboards.append(\n        ('pygame', 'clipboard_pygame', 'ClipboardPygame'))\n\n_clipboards.append(\n    ('dummy', 'clipboard_dummy', 'ClipboardDummy'))\n\nClipboard = core_select_lib('clipboard', _clipboards, True)\nCutBuffer = None\n\nif platform == 'linux':\n    _cutbuffers = [\n        ('xclip', 'clipboard_xclip', 'ClipboardXclip'),\n        ('xsel', 'clipboard_xsel', 'ClipboardXsel'),\n    ]\n\n    if Clipboard.__class__.__name__ in (c[2] for c in _cutbuffers):\n        CutBuffer = Clipboard\n    else:\n        CutBuffer = core_select_lib('cutbuffer', _cutbuffers, True, basemodule='clipboard')\n\n    if CutBuffer:\n        Logger.info('CutBuffer: cut buffer support enabled')\n", "path": "kivy/core/clipboard/__init__.py"}, {"content": "'''\nCore Abstraction\n================\n\nThis module defines the abstraction layers for our core providers and their\nimplementations. For further information, please refer to\n:ref:`architecture` and the :ref:`providers` section of the documentation.\n\nIn most cases, you shouldn't directly use a library that's already covered\nby the core abstraction. Always try to use our providers first.\nIn case we are missing a feature or method, please let us know by\nopening a new Bug report instead of relying on your library.\n\n.. warning::\n    These are **not** widgets! These are just abstractions of the respective\n    functionality. For example, you cannot add a core image to your window.\n    You have to use the image **widget** class instead. If you're really\n    looking for widgets, please refer to :mod:`kivy.uix` instead.\n'''\n\n\nimport os\nimport sys\nimport traceback\nimport kivy\nfrom kivy.logger import Logger\n\n\nclass CoreCriticalException(Exception):\n    pass\n\n\ndef core_select_lib(category, llist, create_instance=False, base='kivy.core', basemodule=None):\n    if 'KIVY_DOC' in os.environ:\n        return\n    category = category.lower()\n    basemodule = basemodule or category\n    libs_ignored = []\n    errs = []\n    for option, modulename, classname in llist:\n        try:\n            # module activated in config ?\n            try:\n                if option not in kivy.kivy_options[category]:\n                    libs_ignored.append(modulename)\n                    Logger.debug(\n                        '{0}: Provider <{1}> ignored by config'.format(\n                            category.capitalize(), option))\n                    continue\n            except KeyError:\n                pass\n\n            # import module\n            mod = __import__(name='{2}.{0}.{1}'.format(\n                basemodule, modulename, base),\n                globals=globals(),\n                locals=locals(),\n                fromlist=[modulename], level=0)\n            cls = mod.__getattribute__(classname)\n\n            # ok !\n            Logger.info('{0}: Provider: {1}{2}'.format(\n                category.capitalize(), option,\n                '({0} ignored)'.format(libs_ignored) if libs_ignored else ''))\n            if create_instance:\n                cls = cls()\n            return cls\n\n        except ImportError as e:\n            errs.append((option, e, sys.exc_info()[2]))\n            libs_ignored.append(modulename)\n            Logger.debug('{0}: Ignored <{1}> (import error)'.format(\n                category.capitalize(), option))\n            Logger.trace('', exc_info=e)\n\n        except CoreCriticalException as e:\n            errs.append((option, e, sys.exc_info()[2]))\n            Logger.error('{0}: Unable to use {1}'.format(\n                category.capitalize(), option))\n            Logger.error(\n                '{0}: The module raised an important error: {1!r}'.format(\n                    category.capitalize(), e.message))\n            raise\n\n        except Exception as e:\n            errs.append((option, e, sys.exc_info()[2]))\n            libs_ignored.append(modulename)\n            Logger.trace('{0}: Unable to use {1}'.format(\n                category.capitalize(), option, category))\n            Logger.trace('', exc_info=e)\n\n    err = '\\n'.join(['{} - {}: {}\\n{}'.format(opt, e.__class__.__name__, e,\n                   ''.join(traceback.format_tb(tb))) for opt, e, tb in errs])\n    Logger.critical(\n        '{0}: Unable to find any valuable {0} provider at all!\\n{1}'.format(\n            category.capitalize(), err))\n\n\ndef core_register_libs(category, libs, base='kivy.core'):\n    if 'KIVY_DOC' in os.environ:\n        return\n    category = category.lower()\n    kivy_options = kivy.kivy_options[category]\n    libs_loadable = {}\n    libs_ignored = []\n\n    for option, lib in libs:\n        # module activated in config ?\n        if option not in kivy_options:\n            Logger.debug('{0}: option <{1}> ignored by config'.format(\n                category.capitalize(), option))\n            libs_ignored.append(lib)\n            continue\n        libs_loadable[option] = lib\n\n    libs_loaded = []\n    for item in kivy_options:\n        try:\n            # import module\n            try:\n                lib = libs_loadable[item]\n            except KeyError:\n                continue\n            __import__(name='{2}.{0}.{1}'.format(category, lib, base),\n                       globals=globals(),\n                       locals=locals(),\n                       fromlist=[lib],\n                       level=0)\n\n            libs_loaded.append(lib)\n\n        except Exception as e:\n            Logger.trace('{0}: Unable to use <{1}> as loader!'.format(\n                category.capitalize(), option))\n            Logger.trace('', exc_info=e)\n            libs_ignored.append(lib)\n\n    Logger.info('{0}: Providers: {1} {2}'.format(\n        category.capitalize(),\n        ', '.join(libs_loaded),\n        '({0} ignored)'.format(\n            ', '.join(libs_ignored)) if libs_ignored else ''))\n    return libs_loaded\n", "path": "kivy/core/__init__.py"}]}