prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  Cannot close last figure window
  After updating ipython to 5.0 (from macports), I cannot close last figure window (neither with button in window bar, nor with 'close()'). The mouse cursor becomes spinning wheel inside the window, but I can still type command in the terminal window.
  
  However, if I type clf(), the figure window closes and a new one appears.
  
  This happens only when there is only one figure window remaining. 
  
  Here's my system (OS X  El Capitan, with python/ipython etc. installed via macports) :
  
  ```
  [~] $ python -c "import IPython; print(IPython.sys_info())"
  {'commit_hash': u'<not found>',
   'commit_source': '(none found)',
   'default_encoding': 'UTF-8',
   'ipython_path': '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython',
   'ipython_version': '5.0.0',
   'os_name': 'posix',
   'platform': 'Darwin-15.5.0-x86_64-i386-64bit',
   'sys_executable': '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python',
   'sys_platform': 'darwin',
   'sys_version': '2.7.12 (default, Jun 29 2016, 12:52:38) \n[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)]'}
  ```
  
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `IPython/terminal/pt_inputhooks/osx.py`
  Content:
  ```
  1 """Inputhook for OS X
  2 
  3 Calls NSApp / CoreFoundation APIs via ctypes.
  4 """
  5 
  6 # obj-c boilerplate from appnope, used under BSD 2-clause
  7 
  8 import ctypes
  9 import ctypes.util
  10 
  11 objc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('objc'))
  12 
  13 void_p = ctypes.c_void_p
  14 
  15 objc.objc_getClass.restype = void_p
  16 objc.sel_registerName.restype = void_p
  17 objc.objc_msgSend.restype = void_p
  18 objc.objc_msgSend.argtypes = [void_p, void_p]
  19 
  20 msg = objc.objc_msgSend
  21 
  22 def _utf8(s):
  23     """ensure utf8 bytes"""
  24     if not isinstance(s, bytes):
  25         s = s.encode('utf8')
  26     return s
  27 
  28 def n(name):
  29     """create a selector name (for ObjC methods)"""
  30     return objc.sel_registerName(_utf8(name))
  31 
  32 def C(classname):
  33     """get an ObjC Class by name"""
  34     return objc.objc_getClass(_utf8(classname))
  35 
  36 # end obj-c boilerplate from appnope
  37 
  38 # CoreFoundation C-API calls we will use:
  39 CoreFoundation = ctypes.cdll.LoadLibrary(ctypes.util.find_library('CoreFoundation'))
  40 
  41 CFFileDescriptorCreate = CoreFoundation.CFFileDescriptorCreate
  42 CFFileDescriptorCreate.restype = void_p
  43 CFFileDescriptorCreate.argtypes = [void_p, ctypes.c_int, ctypes.c_bool, void_p]
  44 
  45 CFFileDescriptorGetNativeDescriptor = CoreFoundation.CFFileDescriptorGetNativeDescriptor
  46 CFFileDescriptorGetNativeDescriptor.restype = ctypes.c_int
  47 CFFileDescriptorGetNativeDescriptor.argtypes = [void_p]
  48 
  49 CFFileDescriptorEnableCallBacks = CoreFoundation.CFFileDescriptorEnableCallBacks
  50 CFFileDescriptorEnableCallBacks.restype = None
  51 CFFileDescriptorEnableCallBacks.argtypes = [void_p, ctypes.c_ulong]
  52 
  53 CFFileDescriptorCreateRunLoopSource = CoreFoundation.CFFileDescriptorCreateRunLoopSource
  54 CFFileDescriptorCreateRunLoopSource.restype = void_p
  55 CFFileDescriptorCreateRunLoopSource.argtypes = [void_p, void_p, void_p]
  56 
  57 CFRunLoopGetCurrent = CoreFoundation.CFRunLoopGetCurrent
  58 CFRunLoopGetCurrent.restype = void_p
  59 
  60 CFRunLoopAddSource = CoreFoundation.CFRunLoopAddSource
  61 CFRunLoopAddSource.restype = None
  62 CFRunLoopAddSource.argtypes = [void_p, void_p, void_p]
  63 
  64 CFRelease = CoreFoundation.CFRelease
  65 CFRelease.restype = None
  66 CFRelease.argtypes = [void_p]
  67 
  68 CFFileDescriptorInvalidate = CoreFoundation.CFFileDescriptorInvalidate
  69 CFFileDescriptorInvalidate.restype = None
  70 CFFileDescriptorInvalidate.argtypes = [void_p]
  71 
  72 # From CFFileDescriptor.h
  73 kCFFileDescriptorReadCallBack = 1
  74 kCFRunLoopCommonModes = void_p.in_dll(CoreFoundation, 'kCFRunLoopCommonModes')
  75 
  76 
  77 def _NSApp():
  78     """Return the global NSApplication instance (NSApp)"""
  79     return msg(C('NSApplication'), n('sharedApplication'))
  80 
  81 
  82 def _wake(NSApp):
  83     """Wake the Application"""
  84     event = msg(C('NSEvent'),
  85         n('otherEventWithType:location:modifierFlags:'
  86           'timestamp:windowNumber:context:subtype:data1:data2:'),
  87         15, # Type
  88         0, # location
  89         0, # flags
  90         0, # timestamp
  91         0, # window
  92         None, # context
  93         0, # subtype
  94         0, # data1
  95         0, # data2
  96     )
  97     msg(NSApp, n('postEvent:atStart:'), void_p(event), True)
  98 
  99 
  100 def _input_callback(fdref, flags, info):
  101     """Callback to fire when there's input to be read"""
  102     CFFileDescriptorInvalidate(fdref)
  103     CFRelease(fdref)
  104     NSApp = _NSApp()
  105     msg(NSApp, n('stop:'), NSApp)
  106     _wake(NSApp)
  107 
  108 _c_callback_func_type = ctypes.CFUNCTYPE(None, void_p, void_p, void_p)
  109 _c_input_callback = _c_callback_func_type(_input_callback)
  110 
  111 
  112 def _stop_on_read(fd):
  113     """Register callback to stop eventloop when there's data on fd"""
  114     fdref = CFFileDescriptorCreate(None, fd, False, _c_input_callback, None)
  115     CFFileDescriptorEnableCallBacks(fdref, kCFFileDescriptorReadCallBack)
  116     source = CFFileDescriptorCreateRunLoopSource(None, fdref, 0)
  117     loop = CFRunLoopGetCurrent()
  118     CFRunLoopAddSource(loop, source, kCFRunLoopCommonModes)
  119     CFRelease(source)
  120 
  121 
  122 def inputhook(context):
  123     """Inputhook for Cocoa (NSApp)"""
  124     NSApp = _NSApp()
  125     window_count = msg(
  126         msg(NSApp, n('windows')),
  127         n('count')
  128     )
  129     if not window_count:
  130         return
  131     _stop_on_read(context.fileno())
  132     msg(NSApp, n('run'))
  133 
  134
  ```
  --- 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()
  
  ```
  
golden_diff: diff --git a/IPython/terminal/pt_inputhooks/osx.py b/IPython/terminal/pt_inputhooks/osx.py
  --- a/IPython/terminal/pt_inputhooks/osx.py
  +++ b/IPython/terminal/pt_inputhooks/osx.py
  @@ -7,6 +7,7 @@
   
   import ctypes
   import ctypes.util
  +from threading import Event
   
   objc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('objc'))
   
  @@ -97,8 +98,11 @@
       msg(NSApp, n('postEvent:atStart:'), void_p(event), True)
   
   
  +_triggered = Event()
  +
   def _input_callback(fdref, flags, info):
       """Callback to fire when there's input to be read"""
  +    _triggered.set()
       CFFileDescriptorInvalidate(fdref)
       CFRelease(fdref)
       NSApp = _NSApp()
  @@ -111,6 +115,7 @@
   
   def _stop_on_read(fd):
       """Register callback to stop eventloop when there's data on fd"""
  +    _triggered.clear()
       fdref = CFFileDescriptorCreate(None, fd, False, _c_input_callback, None)
       CFFileDescriptorEnableCallBacks(fdref, kCFFileDescriptorReadCallBack)
       source = CFFileDescriptorCreateRunLoopSource(None, fdref, 0)
  @@ -130,4 +135,9 @@
           return
       _stop_on_read(context.fileno())
       msg(NSApp, n('run'))
  -
  +    if not _triggered.is_set():
  +        # app closed without firing callback,
  +        # probably due to last window being closed.
  +        # Run the loop manually in this case,
  +        # since there may be events still to process (#9734)
  +        CoreFoundation.CFRunLoopRun()
  
verification_info: {"golden_diff": "diff --git a/IPython/terminal/pt_inputhooks/osx.py b/IPython/terminal/pt_inputhooks/osx.py\n--- a/IPython/terminal/pt_inputhooks/osx.py\n+++ b/IPython/terminal/pt_inputhooks/osx.py\n@@ -7,6 +7,7 @@\n \n import ctypes\n import ctypes.util\n+from threading import Event\n \n objc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('objc'))\n \n@@ -97,8 +98,11 @@\n     msg(NSApp, n('postEvent:atStart:'), void_p(event), True)\n \n \n+_triggered = Event()\n+\n def _input_callback(fdref, flags, info):\n     \"\"\"Callback to fire when there's input to be read\"\"\"\n+    _triggered.set()\n     CFFileDescriptorInvalidate(fdref)\n     CFRelease(fdref)\n     NSApp = _NSApp()\n@@ -111,6 +115,7 @@\n \n def _stop_on_read(fd):\n     \"\"\"Register callback to stop eventloop when there's data on fd\"\"\"\n+    _triggered.clear()\n     fdref = CFFileDescriptorCreate(None, fd, False, _c_input_callback, None)\n     CFFileDescriptorEnableCallBacks(fdref, kCFFileDescriptorReadCallBack)\n     source = CFFileDescriptorCreateRunLoopSource(None, fdref, 0)\n@@ -130,4 +135,9 @@\n         return\n     _stop_on_read(context.fileno())\n     msg(NSApp, n('run'))\n-\n+    if not _triggered.is_set():\n+        # app closed without firing callback,\n+        # probably due to last window being closed.\n+        # Run the loop manually in this case,\n+        # since there may be events still to process (#9734)\n+        CoreFoundation.CFRunLoopRun()\n", "issue": "Cannot close last figure window\nAfter updating ipython to 5.0 (from macports), I cannot close last figure window (neither with button in window bar, nor with 'close()'). The mouse cursor becomes spinning wheel inside the window, but I can still type command in the terminal window.\n\nHowever, if I type clf(), the figure window closes and a new one appears.\n\nThis happens only when there is only one figure window remaining. \n\nHere's my system (OS X  El Capitan, with python/ipython etc. installed via macports) :\n\n```\n[~] $ python -c \"import IPython; print(IPython.sys_info())\"\n{'commit_hash': u'<not found>',\n 'commit_source': '(none found)',\n 'default_encoding': 'UTF-8',\n 'ipython_path': '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IPython',\n 'ipython_version': '5.0.0',\n 'os_name': 'posix',\n 'platform': 'Darwin-15.5.0-x86_64-i386-64bit',\n 'sys_executable': '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python',\n 'sys_platform': 'darwin',\n 'sys_version': '2.7.12 (default, Jun 29 2016, 12:52:38) \\n[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)]'}\n```\n\n", "before_files": [{"content": "\"\"\"Inputhook for OS X\n\nCalls NSApp / CoreFoundation APIs via ctypes.\n\"\"\"\n\n# obj-c boilerplate from appnope, used under BSD 2-clause\n\nimport ctypes\nimport ctypes.util\n\nobjc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('objc'))\n\nvoid_p = ctypes.c_void_p\n\nobjc.objc_getClass.restype = void_p\nobjc.sel_registerName.restype = void_p\nobjc.objc_msgSend.restype = void_p\nobjc.objc_msgSend.argtypes = [void_p, void_p]\n\nmsg = objc.objc_msgSend\n\ndef _utf8(s):\n    \"\"\"ensure utf8 bytes\"\"\"\n    if not isinstance(s, bytes):\n        s = s.encode('utf8')\n    return s\n\ndef n(name):\n    \"\"\"create a selector name (for ObjC methods)\"\"\"\n    return objc.sel_registerName(_utf8(name))\n\ndef C(classname):\n    \"\"\"get an ObjC Class by name\"\"\"\n    return objc.objc_getClass(_utf8(classname))\n\n# end obj-c boilerplate from appnope\n\n# CoreFoundation C-API calls we will use:\nCoreFoundation = ctypes.cdll.LoadLibrary(ctypes.util.find_library('CoreFoundation'))\n\nCFFileDescriptorCreate = CoreFoundation.CFFileDescriptorCreate\nCFFileDescriptorCreate.restype = void_p\nCFFileDescriptorCreate.argtypes = [void_p, ctypes.c_int, ctypes.c_bool, void_p]\n\nCFFileDescriptorGetNativeDescriptor = CoreFoundation.CFFileDescriptorGetNativeDescriptor\nCFFileDescriptorGetNativeDescriptor.restype = ctypes.c_int\nCFFileDescriptorGetNativeDescriptor.argtypes = [void_p]\n\nCFFileDescriptorEnableCallBacks = CoreFoundation.CFFileDescriptorEnableCallBacks\nCFFileDescriptorEnableCallBacks.restype = None\nCFFileDescriptorEnableCallBacks.argtypes = [void_p, ctypes.c_ulong]\n\nCFFileDescriptorCreateRunLoopSource = CoreFoundation.CFFileDescriptorCreateRunLoopSource\nCFFileDescriptorCreateRunLoopSource.restype = void_p\nCFFileDescriptorCreateRunLoopSource.argtypes = [void_p, void_p, void_p]\n\nCFRunLoopGetCurrent = CoreFoundation.CFRunLoopGetCurrent\nCFRunLoopGetCurrent.restype = void_p\n\nCFRunLoopAddSource = CoreFoundation.CFRunLoopAddSource\nCFRunLoopAddSource.restype = None\nCFRunLoopAddSource.argtypes = [void_p, void_p, void_p]\n\nCFRelease = CoreFoundation.CFRelease\nCFRelease.restype = None\nCFRelease.argtypes = [void_p]\n\nCFFileDescriptorInvalidate = CoreFoundation.CFFileDescriptorInvalidate\nCFFileDescriptorInvalidate.restype = None\nCFFileDescriptorInvalidate.argtypes = [void_p]\n\n# From CFFileDescriptor.h\nkCFFileDescriptorReadCallBack = 1\nkCFRunLoopCommonModes = void_p.in_dll(CoreFoundation, 'kCFRunLoopCommonModes')\n\n\ndef _NSApp():\n    \"\"\"Return the global NSApplication instance (NSApp)\"\"\"\n    return msg(C('NSApplication'), n('sharedApplication'))\n\n\ndef _wake(NSApp):\n    \"\"\"Wake the Application\"\"\"\n    event = msg(C('NSEvent'),\n        n('otherEventWithType:location:modifierFlags:'\n          'timestamp:windowNumber:context:subtype:data1:data2:'),\n        15, # Type\n        0, # location\n        0, # flags\n        0, # timestamp\n        0, # window\n        None, # context\n        0, # subtype\n        0, # data1\n        0, # data2\n    )\n    msg(NSApp, n('postEvent:atStart:'), void_p(event), True)\n\n\ndef _input_callback(fdref, flags, info):\n    \"\"\"Callback to fire when there's input to be read\"\"\"\n    CFFileDescriptorInvalidate(fdref)\n    CFRelease(fdref)\n    NSApp = _NSApp()\n    msg(NSApp, n('stop:'), NSApp)\n    _wake(NSApp)\n\n_c_callback_func_type = ctypes.CFUNCTYPE(None, void_p, void_p, void_p)\n_c_input_callback = _c_callback_func_type(_input_callback)\n\n\ndef _stop_on_read(fd):\n    \"\"\"Register callback to stop eventloop when there's data on fd\"\"\"\n    fdref = CFFileDescriptorCreate(None, fd, False, _c_input_callback, None)\n    CFFileDescriptorEnableCallBacks(fdref, kCFFileDescriptorReadCallBack)\n    source = CFFileDescriptorCreateRunLoopSource(None, fdref, 0)\n    loop = CFRunLoopGetCurrent()\n    CFRunLoopAddSource(loop, source, kCFRunLoopCommonModes)\n    CFRelease(source)\n\n\ndef inputhook(context):\n    \"\"\"Inputhook for Cocoa (NSApp)\"\"\"\n    NSApp = _NSApp()\n    window_count = msg(\n        msg(NSApp, n('windows')),\n        n('count')\n    )\n    if not window_count:\n        return\n    _stop_on_read(context.fileno())\n    msg(NSApp, n('run'))\n\n", "path": "IPython/terminal/pt_inputhooks/osx.py"}], "after_files": [{"content": "\"\"\"Inputhook for OS X\n\nCalls NSApp / CoreFoundation APIs via ctypes.\n\"\"\"\n\n# obj-c boilerplate from appnope, used under BSD 2-clause\n\nimport ctypes\nimport ctypes.util\nfrom threading import Event\n\nobjc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('objc'))\n\nvoid_p = ctypes.c_void_p\n\nobjc.objc_getClass.restype = void_p\nobjc.sel_registerName.restype = void_p\nobjc.objc_msgSend.restype = void_p\nobjc.objc_msgSend.argtypes = [void_p, void_p]\n\nmsg = objc.objc_msgSend\n\ndef _utf8(s):\n    \"\"\"ensure utf8 bytes\"\"\"\n    if not isinstance(s, bytes):\n        s = s.encode('utf8')\n    return s\n\ndef n(name):\n    \"\"\"create a selector name (for ObjC methods)\"\"\"\n    return objc.sel_registerName(_utf8(name))\n\ndef C(classname):\n    \"\"\"get an ObjC Class by name\"\"\"\n    return objc.objc_getClass(_utf8(classname))\n\n# end obj-c boilerplate from appnope\n\n# CoreFoundation C-API calls we will use:\nCoreFoundation = ctypes.cdll.LoadLibrary(ctypes.util.find_library('CoreFoundation'))\n\nCFFileDescriptorCreate = CoreFoundation.CFFileDescriptorCreate\nCFFileDescriptorCreate.restype = void_p\nCFFileDescriptorCreate.argtypes = [void_p, ctypes.c_int, ctypes.c_bool, void_p]\n\nCFFileDescriptorGetNativeDescriptor = CoreFoundation.CFFileDescriptorGetNativeDescriptor\nCFFileDescriptorGetNativeDescriptor.restype = ctypes.c_int\nCFFileDescriptorGetNativeDescriptor.argtypes = [void_p]\n\nCFFileDescriptorEnableCallBacks = CoreFoundation.CFFileDescriptorEnableCallBacks\nCFFileDescriptorEnableCallBacks.restype = None\nCFFileDescriptorEnableCallBacks.argtypes = [void_p, ctypes.c_ulong]\n\nCFFileDescriptorCreateRunLoopSource = CoreFoundation.CFFileDescriptorCreateRunLoopSource\nCFFileDescriptorCreateRunLoopSource.restype = void_p\nCFFileDescriptorCreateRunLoopSource.argtypes = [void_p, void_p, void_p]\n\nCFRunLoopGetCurrent = CoreFoundation.CFRunLoopGetCurrent\nCFRunLoopGetCurrent.restype = void_p\n\nCFRunLoopAddSource = CoreFoundation.CFRunLoopAddSource\nCFRunLoopAddSource.restype = None\nCFRunLoopAddSource.argtypes = [void_p, void_p, void_p]\n\nCFRelease = CoreFoundation.CFRelease\nCFRelease.restype = None\nCFRelease.argtypes = [void_p]\n\nCFFileDescriptorInvalidate = CoreFoundation.CFFileDescriptorInvalidate\nCFFileDescriptorInvalidate.restype = None\nCFFileDescriptorInvalidate.argtypes = [void_p]\n\n# From CFFileDescriptor.h\nkCFFileDescriptorReadCallBack = 1\nkCFRunLoopCommonModes = void_p.in_dll(CoreFoundation, 'kCFRunLoopCommonModes')\n\n\ndef _NSApp():\n    \"\"\"Return the global NSApplication instance (NSApp)\"\"\"\n    return msg(C('NSApplication'), n('sharedApplication'))\n\n\ndef _wake(NSApp):\n    \"\"\"Wake the Application\"\"\"\n    event = msg(C('NSEvent'),\n        n('otherEventWithType:location:modifierFlags:'\n          'timestamp:windowNumber:context:subtype:data1:data2:'),\n        15, # Type\n        0, # location\n        0, # flags\n        0, # timestamp\n        0, # window\n        None, # context\n        0, # subtype\n        0, # data1\n        0, # data2\n    )\n    msg(NSApp, n('postEvent:atStart:'), void_p(event), True)\n\n\n_triggered = Event()\n\ndef _input_callback(fdref, flags, info):\n    \"\"\"Callback to fire when there's input to be read\"\"\"\n    _triggered.set()\n    CFFileDescriptorInvalidate(fdref)\n    CFRelease(fdref)\n    NSApp = _NSApp()\n    msg(NSApp, n('stop:'), NSApp)\n    _wake(NSApp)\n\n_c_callback_func_type = ctypes.CFUNCTYPE(None, void_p, void_p, void_p)\n_c_input_callback = _c_callback_func_type(_input_callback)\n\n\ndef _stop_on_read(fd):\n    \"\"\"Register callback to stop eventloop when there's data on fd\"\"\"\n    _triggered.clear()\n    fdref = CFFileDescriptorCreate(None, fd, False, _c_input_callback, None)\n    CFFileDescriptorEnableCallBacks(fdref, kCFFileDescriptorReadCallBack)\n    source = CFFileDescriptorCreateRunLoopSource(None, fdref, 0)\n    loop = CFRunLoopGetCurrent()\n    CFRunLoopAddSource(loop, source, kCFRunLoopCommonModes)\n    CFRelease(source)\n\n\ndef inputhook(context):\n    \"\"\"Inputhook for Cocoa (NSApp)\"\"\"\n    NSApp = _NSApp()\n    window_count = msg(\n        msg(NSApp, n('windows')),\n        n('count')\n    )\n    if not window_count:\n        return\n    _stop_on_read(context.fileno())\n    msg(NSApp, n('run'))\n    if not _triggered.is_set():\n        # app closed without firing callback,\n        # probably due to last window being closed.\n        # Run the loop manually in this case,\n        # since there may be events still to process (#9734)\n        CoreFoundation.CFRunLoopRun()\n", "path": "IPython/terminal/pt_inputhooks/osx.py"}]}