internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: beeware/toga

Issue:
toga-winforms\windows.py openFileDialog needs an "s"
**Describe the bug**
When using multiselect = True in winforms the returned value is a single file because 

   if dialog.ShowDialog() == WinForms.DialogResult.OK:
            return dialog.FileName

should be 

   if dialog.ShowDialog() == WinForms.DialogResult.OK:
            return dialog.FileName**s**

 

**To Reproduce**

            fname = self.main_window.open_file_dialog(
                title="Open the file",
                multiselect=True
            )


**Expected behavior**
returns a list of files (fname) which is true on a Mac.  On Windows it is the name of the first file as a single string .  With suggested fix return selection but it still needs to be coerced into a list.


**Environment:**
 - Operating System:  Mac OS 10.15.6 & Windows 10
 - Python version: 3.8
 - Software versions:
   - Briefcase: 0.3.3
   - Toga: 0.3.0 dev23



Discussion:

Resolving patch:
diff --git a/src/winforms/toga_winforms/window.py b/src/winforms/toga_winforms/window.py
--- a/src/winforms/toga_winforms/window.py
+++ b/src/winforms/toga_winforms/window.py
@@ -187,7 +187,7 @@ def open_file_dialog(self, title, initial_directory, file_types, multiselect):
         if multiselect:
             dialog.Multiselect = True
         if dialog.ShowDialog() == WinForms.DialogResult.OK:
-            return dialog.FileName
+            return dialog.FileNames if multiselect else dialog.FileName
         else:
             raise ValueError("No filename provided in the open file dialog")
 


Test patch:
Repository: beeware/toga

Issue:
Memory leaks in Windows
**Describe the bug**
Unfortunately, it seems like there are memory leaks issues in the Windows implementation of toga

**To Reproduce**
Steps to reproduce the behavior:
1. install memory profiler, briefcase and matplotlib using `pip install memory_profiler briefcase matplotlib`
2. Go to the Box example directory (or any other example for that matter)
3. Run `mprof run --include-children briefcase dev`
4. Click some buttons and wait for a few seconds
5. Exit the program
6. run `mprof plot` and see the memory leak

![memory_leak](https://user-images.githubusercontent.com/19425795/96552884-11b31500-12bd-11eb-8c31-78aaeab5ca88.png)

**Environment:**
 - Operating System: Windows 10
 - Python version: python 3.8
 - Software versions:
   - Briefcase: latest
   - Toga: latest



Discussion:

Resolving patch:
diff --git a/src/winforms/toga_winforms/libs/proactor.py b/src/winforms/toga_winforms/libs/proactor.py
--- a/src/winforms/toga_winforms/libs/proactor.py
+++ b/src/winforms/toga_winforms/libs/proactor.py
@@ -100,7 +100,8 @@ def run_forever(self, app_context):
 
     def enqueue_tick(self):
         # Queue a call to tick in 5ms.
-        Task.Delay(5).ContinueWith(Action[Task](self.tick))
+        self.task = Action[Task](self.tick)
+        Task.Delay(5).ContinueWith(self.task)
 
     def tick(self, *args, **kwargs):
         """
@@ -113,6 +114,9 @@ def tick(self, *args, **kwargs):
         # message, it will be caught by the MessageFilter we installed on the
         # Application thread.
 
+        if self.task:
+            self.task.Dispose()
+            del self.task
         # The message is sent with:
         # * HWND 0xfff (all windows),
         # * MSG self.msg_id (a message ID in the WM_USER range)
@@ -124,7 +128,10 @@ def tick(self, *args, **kwargs):
         # If the app context has a main form, invoke run_once_recurring()
         # on the thread associated with that form.
         if self.app_context.MainForm:
-            self.app_context.MainForm.Invoke(Action(self.run_once_recurring))
+            action = Action(self.run_once_recurring)
+            self.app_context.MainForm.Invoke(action)
+            action.Dispose()
+            del action
 
     def run_once_recurring(self):
         """


Test patch:
Repository: beeware/toga

Issue:
toga_gtk.widgets.internal moduel not found
**Describe the bug**
toga-demo doesn't start. When run, the following error occurs.
![image](https://user-images.githubusercontent.com/24705058/96589679-636f9580-12e5-11eb-9e72-dde4ad6d5d89.png)


**To Reproduce**
Steps to reproduce the behavior:
1. I am on manjaro so running 
```sh
$ sudo pacman -Syu git pkgconf cairo python-cairo pango gobject-introspection gobject-introspection-runtime python-gobject webkit2gtk
```
2. Installing toga-demo
```sh
$ sudo pip -H install --pre toga-demo
```
3. Running toga-demo
```sh
$ toga-demo
```
4. See error

**Expected behavior**
Toga Demo starts

**Screenshots**
See above.

**Environment:**
 - Operating System: Manjaro
 - Python version: 3.8
 - Software versions:
   - Briefcase: N/a
   - Toga: 0.3.0.dev24
   - ...

**Additional context**
Add any other context about the problem here.



Discussion:
I am facing same problem on linux mint 19
however on Manjaro 20.1.1 I am facing issues too,
Can anyone suggest me which OS should I use to get reliable output?

Resolving patch:
diff --git a/src/gtk/toga_gtk/widgets/internal/__init__.py b/src/gtk/toga_gtk/widgets/internal/__init__.py
new file mode 100644


Test patch:
Repository: beeware/toga

Issue:
ImageView only works with square images
I created a hello world app following this tutorial under Linux Mint 20: [https://docs.beeware.org/en/latest/tutorial/tutorial-0.html](https://docs.beeware.org/en/latest/tutorial/tutorial-0.html)
My python version is 3.8.5
When trying to add images some work and some not.

This code doesn't work:
`image_from_url = toga.Image("https://dummyimage.com/100x67/000/fff")
imageview_from_url = toga.ImageView(image=image_from_url, style=Pack(width=100, height=67))`

And this is working fine:
`image_from_url = toga.Image("https://dummyimage.com/100x100/000/fff")
imageview_from_url = toga.ImageView(image=image_from_url, style=Pack(width=100, height=100))`

The error I get is:

> (__main__.py:67130): GdkPixbuf-CRITICAL **: 16:12:00.644: gdk_pixbuf_scale_simple: assertion 'dest_height > 0' failed
>  ... TypeError: Argument 0 does not allow None as a value



Discussion:
I'm having the same issue.
Thanks for the report. I've found the source of the problem; the issue is that the first time GTK tries to display the image, it allocates an available size of 1x1. Toga tries to preserve aspect ratio, which scales non-square images to have once of the dimensions with a size of 0 - which then breaks, because you can't have an image of size 0. A fix is incoming shortly.



Resolving patch:
diff --git a/examples/imageview/imageview/app.py b/examples/imageview/imageview/app.py
--- a/examples/imageview/imageview/app.py
+++ b/examples/imageview/imageview/app.py
@@ -14,10 +14,9 @@ def startup(self):
         # image from local path
         # load brutus.png from the package
         # We set the style width/height parameters for this one
-        image_from_path = toga.Image('resources/brutus.png')
+        image_from_path = toga.Image('resources/pride-brutus.png')
         imageview_from_path = toga.ImageView(image_from_path)
         imageview_from_path.style.update(height=72)
-        imageview_from_path.style.update(width=72)
         box.add(imageview_from_path)
 
         # image from remote URL
diff --git a/src/gtk/toga_gtk/widgets/imageview.py b/src/gtk/toga_gtk/widgets/imageview.py
--- a/src/gtk/toga_gtk/widgets/imageview.py
+++ b/src/gtk/toga_gtk/widgets/imageview.py
@@ -55,4 +55,8 @@ def _resize_max(original_height, original_width, max_height, max_width):
             height = original_height * height_ratio
             width = original_width * height_ratio
 
-        return int(height), int(width)
+        # On the first display the allocated height/width will be 1x1.
+        # If the image isn't square, this will result in one of the dimensions
+        # scaling to 0, which breaks GTK. So; constraint the minimum height
+        # and width to 1.
+        return max(int(height), 1), max(int(width), 1)


Test patch:
Repository: beeware/toga

Issue:
WebView in MacOS not accepting keyboard input
**Describe the bug**

I am unable to type text in HTML input fields within a Toga WebView on Mac OS.

**To Reproduce**
Steps to reproduce the behavior:
1. Follow the tutorial at https://docs.beeware.org/en/latest/tutorial/tutorial-1.html until you are able to run `briefcase dev` successfully.
2. Modify the `startup` function so that its body is:
   ```main_box = toga.Box()
        self.main_window = toga.MainWindow(title=self.formal_name)
        self.main_window.content = toga.WebView(style=Pack(flex=1))
        self.main_window.content.url = 'https://www.google.ca/'
        self.main_window.show()
   ```
3. Attempt to search for something in the Google search input.
4. When I try, I am unable to type characters. Nothing happens with my key presses. Note that specified command shortcuts do seem to work.

**Expected behavior**
I expect to be able to enter text into text boxes in a WebView in Toga.

**Environment:**
 - Operating System: Mac OS 10.15.6
 - Python version: 3.6.5
 - Software versions:
   - Briefcase: 0.3.0
   - Toga: 0.3.0.dev26

**Additional context**
I discovered that If I just comment out the `keyDown_` method in toga_cocoa [here](https://github.com/beeware/toga/blob/master/src/cocoa/toga_cocoa/widgets/webview.py#L23-L27) then I am able to enter text in a WebView.


Discussion:
Thanks for the report! 

Based on your additional notes, I'm guessing the solution will be to propagate the keyDown message to the superclass - that way the "native" key handling will be executed in addition to the Toga-specific handling. If I'm right, adding:

    send_super(__class__, self, 'keyDown:', event)

to the end of the `keyDown:` message will fix the problem.

Resolving patch:
diff --git a/src/cocoa/toga_cocoa/widgets/webview.py b/src/cocoa/toga_cocoa/widgets/webview.py
--- a/src/cocoa/toga_cocoa/widgets/webview.py
+++ b/src/cocoa/toga_cocoa/widgets/webview.py
@@ -4,7 +4,7 @@
 
 from toga_cocoa.keys import toga_key
 from toga_cocoa.libs import NSURL, NSURLRequest, WKWebView
-from rubicon.objc import objc_method, py_from_ns
+from rubicon.objc import objc_method, py_from_ns, send_super
 from rubicon.objc.runtime import objc_id
 
 from .base import Widget
@@ -24,6 +24,7 @@ def acceptsFirstResponder(self) -> bool:
     def keyDown_(self, event) -> None:
         if self.interface.on_key_down:
             self.interface.on_key_down(self.interface, **toga_key(event))
+        send_super(__class__, self, 'keyDown:', event)
 
     @objc_method
     def touchBar(self):


Test patch:
Repository: beeware/toga

Issue:
Make app respond to Cmd-H, Cmd-Opt-H on macOS; add menu bar items
Toga apps do not respond to Cmd-H and Cmd-Opt-H on macOS and there are no options to hide the app or hide other apps on the application menu.  These could be added to the `APP` command group in `toga-cocoa` so that they are always present for macOS apps, under a separate section.  I could look into what this might require although I've no experience with ObjC and friends.


Discussion:
Completely agreed that this is desirable; the goal of a Toga app should be that the "hello world" demo should have all the menu items and behaviours you'd expect a native app to have. The "Hide"/"Hide others" menu items on the app menu are definitely items that we should have.

From a cursory investigation, it looks like we just need to hook into the [`hide:`](https://developer.apple.com/documentation/appkit/nsapplication/1428733-hide?language=objc) and [`unhide:`](https://developer.apple.com/documentation/appkit/nsapplication/1428761-unhide?language=objc) message on `NSApplication`, adding a menu item in the Cocoa backend. If you'd like any pointers on how to proceed, ask here, or join us on [Discord](https://beeware.org/bee/chat)

Resolving patch:
diff --git a/src/cocoa/toga_cocoa/app.py b/src/cocoa/toga_cocoa/app.py
--- a/src/cocoa/toga_cocoa/app.py
+++ b/src/cocoa/toga_cocoa/app.py
@@ -131,8 +131,37 @@ def create(self):
                 'About ' + formal_name,
                 group=toga.Group.APP
             ),
-            toga.Command(None, 'Preferences', group=toga.Group.APP),
-            # Quit should always be the last item, in a section on it's own
+            toga.Command(
+                None,
+                'Preferences',
+                shortcut=toga.Key.MOD_1 + ',',
+                group=toga.Group.APP,
+                section=20,
+            ),
+            toga.Command(
+                lambda _: self.native.hide(self.native),
+                'Hide ' + formal_name,
+                shortcut=toga.Key.MOD_1 + 'h',
+                group=toga.Group.APP,
+                order=0,
+                section=sys.maxsize - 1,
+            ),
+            toga.Command(
+                lambda _: self.native.hideOtherApplications(self.native),
+                'Hide Others',
+                shortcut=toga.Key.MOD_1 + toga.Key.MOD_2 + 'h',
+                group=toga.Group.APP,
+                order=1,
+                section=sys.maxsize - 1,
+            ),
+            toga.Command(
+                lambda _: self.native.unhideAllApplications(self.native),
+                'Show All',
+                group=toga.Group.APP,
+                order=2,
+                section=sys.maxsize - 1,
+            ),
+            # Quit should always be the last item, in a section on its own
             toga.Command(
                 lambda _: self.interface.exit(),
                 'Quit ' + formal_name,


Test patch:
Repository: beeware/toga

Issue:
[toga-cocoa] Some enums have incorrect values on Apple Silicon Macs
**Describe the bug**
The enum values for `NSTextAlignment` and `NSImageResizingMode` are different in macOS for Intel and Apple Silicon Macs. This is documented in the porting guide at:

https://developer.apple.com/documentation/apple-silicon/addressing-architectural-differences-in-your-macos-code

and also apparent in the headers, for example in `NSText.h`:

```objc
typedef NS_ENUM(NSInteger, NSTextAlignment) {
    NSTextAlignmentLeft      = 0,    // Visually left aligned
#if TARGET_ABI_USES_IOS_VALUES
    NSTextAlignmentCenter    = 1,    // Visually centered
    NSTextAlignmentRight     = 2,    // Visually right aligned
#else /* !TARGET_ABI_USES_IOS_VALUES */
    NSTextAlignmentRight     = 1,    // Visually right aligned
    NSTextAlignmentCenter    = 2,    // Visually centered
#endif
    NSTextAlignmentJustified = 3,    // Fully-justified. The last line in a paragraph is natural-aligned.
    NSTextAlignmentNatural   = 4     // Indicates the default alignment for script
} API_AVAILABLE(macos(10.0), ios(6.0), watchos(2.0), tvos(9.0));
```

This results in center aligned-text in toga currently appearing as right-aligned text on M1 machines and vice-versa.

**Environment:**
 - Operating System: macOS 11
 - Platform: Apple Silicon
 


Discussion:
but.... WHYYYYYYYY 🤦 

Thanks for the heads up. `platform.machine()` will tell us what we need to know to differentiate ('arm64' vs 'x86_64').

Resolving patch:
diff --git a/src/cocoa/toga_cocoa/libs/appkit.py b/src/cocoa/toga_cocoa/libs/appkit.py
--- a/src/cocoa/toga_cocoa/libs/appkit.py
+++ b/src/cocoa/toga_cocoa/libs/appkit.py
@@ -1,6 +1,7 @@
 ##########################################################################
 # System/Library/Frameworks/AppKit.framework
 ##########################################################################
+import platform
 from ctypes import Structure, c_void_p
 from enum import Enum, IntEnum
 
@@ -371,6 +372,19 @@ class NSImageAlignment(Enum):
 NSImageScaleNone = 2
 NSImageScaleProportionallyUpOrDown = 3
 
+if platform == 'arm64':
+    NSImageResizingModeTile = 1
+    NSImageResizingModeStretch = 0
+else:
+    NSImageResizingModeTile = 0
+    NSImageResizingModeStretch = 1
+
+
+class NSImageResizingMode(Enum):
+    Tile = NSImageResizingModeTile
+    Stretch = NSImageResizingModeStretch
+
+
 ######################################################################
 # NSImageCell.h
 
@@ -639,8 +653,13 @@ class NSTableViewAnimation(Enum):
 ######################################################################
 # NSText.h
 NSLeftTextAlignment = 0
-NSRightTextAlignment = 1
-NSCenterTextAlignment = 2
+if platform.machine() == 'arm64':
+    NSRightTextAlignment = 2
+    NSCenterTextAlignment = 1
+else:
+    NSRightTextAlignment = 1
+    NSCenterTextAlignment = 2
+
 NSJustifiedTextAlignment = 3
 NSNaturalTextAlignment = 4
 


Test patch:
Repository: beeware/toga

Issue:
Use Alpha Version of Pythonnet
**Description**
Pythonnet has released a few days ago an [alpha version](https://pypi.org/project/pythonnet/3.0.0a1/) of Pythonnet 3.0.
ATM we use a hashed version (8d93c39d) of Pythonnet instead of an official release.

In the case that we don't want to wait until an official version of Pythonnet is released (which we don't have any approximation when this would happen), I think we should at least use the alpha version.

**Describe alternatives you've considered**
An alternative is to keep the hashed version as it is :)


Discussion:
Ooh! +1 Lets jump on this ASAP! The lack of Python 3.9/3.10 support on the Python.net 2.X branch is causing enough problems with user support that adopting an alpha is definitely preferable.

I *think* this also means we no longer need the advice about installing the Python.net SDK... but we should confirm this.
My testing appears to confirm the Python.net SDK is no longer required - it's only needed to *build* the Python.net wheel; if we're installing a wheel from PyPI, we can just use it.

Resolving patch:
diff --git a/src/winforms/setup.py b/src/winforms/setup.py
--- a/src/winforms/setup.py
+++ b/src/winforms/setup.py
@@ -24,14 +24,11 @@
         # and their development effort seems to be focussed on the 3.X branch;
         # they've indicated they're not planning to make the 2.X branch compatible
         # with Python 3.10. If we want to be able to support "current" Python,
-        # we need to work off a source release until they formally release 3.0.
+        # we need to use the 3.0 branch.
         #
-        # The 8d93c39d hash is, as best as I can work out, what was in the
-        # 3.0.0-preview2021-10-05 release published to nuget - but they didn't
-        # tag anything for that release. That release contained a bug
-        # (https://github.com/pythonnet/pythonnet/issues/1613) that didn't play well
-        # with pip 21.3, so we use 94b1a71c which was released about a month later.
-        'pythonnet @ git+https://github.com/pythonnet/pythonnet@94b1a71c#egg=pythonnet',
+        # At time of writing, the most recent (and only) version of Python.net 3.0
+        # that has been released is the alpha version 3.0.0a1.
+        'pythonnet>=3.0.0a1',
         'toga-core==%s' % version,
     ],
     test_suite='tests',


Test patch:
Repository: beeware/toga

Issue:
"Your first Toga app" (helloworld) does not work as shown in the docs
I copy-pasted the code [found here](https://toga.readthedocs.io/en/latest/tutorial/tutorial-0.html).  When I ran it, I got this error message:

```
$ python -m helloworld
Traceback (most recent call last):
  File "C:\Users\brendan\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 197, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Users\brendan\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "C:\bjk\tmp\beeware-toga\helloworld.py", line 2, in <module>
    from tutorial import __version__
ModuleNotFoundError: No module named 'tutorial'
```

If I comment out the line `from tutorial import __version__` and delete the kwarg `version=__version__` in the call to `toga.App`, the module does run; i.e., the GUI window pops up and seems to work.  However, during the run, I get a warning:

```
$ python -m helloworld
C:\Users\brendan\AppData\Local\Programs\Python\Python39\lib\site-packages\clr_loader\wrappers.py:20: DeprecationWarning:
 builtin type GC Offset Base has no __module__ attribute
  return self._callable(ffi.cast("void*", buf_arr), len(buf_arr))
```

Maybe it's just out-of-date documentation?

P.S. FWIW, a straight copy-paste of the second tutorial, "[A slightly less toy example](https://toga.readthedocs.io/en/latest/tutorial/tutorial-1.html)" works as is, although it does produce the same DeprecationWarning.

P.P.S.  Ditto the fourth tutorial, "[Let’s build a browser!](https://toga.readthedocs.io/en/latest/tutorial/tutorial-3.html)"


Discussion:

Resolving patch:
diff --git a/examples/tutorial0/tutorial/app.py b/examples/tutorial0/tutorial/app.py
--- a/examples/tutorial0/tutorial/app.py
+++ b/examples/tutorial0/tutorial/app.py
@@ -1,5 +1,4 @@
 import toga
-from tutorial import __version__
 
 
 def button_handler(widget):
@@ -18,15 +17,7 @@ def build(app):
 
 
 def main():
-    return toga.App(
-        'First App',
-        'org.beeware.helloworld',
-        author='Tiberius Yak',
-        description="A testing app",
-        version=__version__,
-        home_page="https://beeware.org",
-        startup=build
-    )
+    return toga.App('First App', 'org.beeware.helloworld', startup=build)
 
 
 if __name__ == '__main__':


Test patch:
Repository: beeware/toga

Issue:
RuntimeError in toga-demo
**Describe the bug**
when you run the toga-demo app and click on "Action 2" and then either Yes or No at the dialog, you get ```RuntimeError: Can't check dialog result directly; use await or an on_result handler``` printed on the console and no followup dialog.

**To Reproduce**
Steps to reproduce the behavior:
1. Install toga-core, toga-gtk, toga and demo using `pip install -e`
2. Run toga-demo
3. Click on Action 2
4. Click on either Yes or No in popup dialog
5. Note it logs a RuntimeError in the terminal you ran it from.

**Expected behavior**
Should not throw an error and instead it should pop up an enthusiastic response dialog.

**Screenshots**
```
Traceback (most recent call last):
  File "/home/nick/Work/beeware/toga/src/core/toga/handlers.py", line 66, in _handler
    result = handler(interface, *args, **kwargs)
  File "/home/nick/Work/beeware/toga/src/core/toga/handlers.py", line 66, in _handler
    result = handler(interface, *args, **kwargs)
  File "/home/nick/Work/beeware/toga/demo/toga_demo/app.py", line 91, in action2
    if self.main_window.question_dialog('Toga', 'Is this cool or what?'):
  File "/home/nick/Work/beeware/toga/src/gtk/toga_gtk/dialogs.py", line 16, in __bool__
    raise RuntimeError("Can't check dialog result directly; use await or an on_result handler")
RuntimeError: Can't check dialog result directly; use await or an on_result handler
```

If applicable, add screenshots to help explain your problem.

**Environment:**
 - Operating System: Ubuntu 20.04.4
 - Python version: 3.8.10
 - Software versions:
   - Toga: 0.3.0.dev34 400b6935c4689bedb134324b38eb1286af5b5ec6
   
**Suggested Fix**
It works if you make the `action2` function async, and make it await the question_dialog.
I'll submit an extremely trivial PR for this soon :-)



Discussion:

Resolving patch:
diff --git a/demo/toga_demo/app.py b/demo/toga_demo/app.py
--- a/demo/toga_demo/app.py
+++ b/demo/toga_demo/app.py
@@ -87,8 +87,8 @@ def button_handler(self, widget):
     def action1(self, widget):
         self.main_window.info_dialog('Toga', 'THIS! IS! TOGA!!')
 
-    def action2(self, widget):
-        if self.main_window.question_dialog('Toga', 'Is this cool or what?'):
+    async def action2(self, widget):
+        if await self.main_window.question_dialog('Toga', 'Is this cool or what?'):
             self.main_window.info_dialog('Happiness', 'I know, right! :-)')
         else:
             self.main_window.info_dialog('Shucks...', "Well aren't you a spoilsport... :-(")


Test patch: