Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-112898: Fix double close dialog with warning about unsafed files #113513

Open
wants to merge 18 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions Lib/idlelib/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@

from tkinter.font import Font
import idlelib
from idlelib import macosx

class InvalidConfigType(Exception): pass
class InvalidConfigSet(Exception): pass
Expand Down Expand Up @@ -660,6 +661,17 @@ def GetCoreKeys(self, keySetName=None):
'<<zoom-height>>': ['<Alt-Key-2>'],
}

if macosx.isAquaTk():
# There appears to be a system default binding for `Command-Q`
# on macOS that interferes with IDLE's setup. Don't add it
# to the key bindings an rely the default binding.
#
# Without this IDLE will prompt twice about closing a file with
# unsaved changes when the user quits IDLE using the keyboard
# shortcutand then chooses "Cancel" the first time the dialog
# appears.
del keyBindings['<<close-all-windows>>']

if keySetName:
if not (self.userCfg['keys'].has_section(keySetName) or
self.defaultCfg['keys'].has_section(keySetName)):
Expand Down
12 changes: 7 additions & 5 deletions Lib/idlelib/editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,7 @@ def set_line_and_column(self, event=None):
* mainmenu.menudefs - a list of tuples, one for each menubar item.
Each tuple pairs a lower-case name and list of dropdown items.
Each item is a name, virtual event pair or None for separator.
* mainmenu.default_keydefs - maps events to keys.
* mainmenu.get_default_keydefs() - maps events to keys.
* text.keydefs - same.
* cls.menu_specs - menubar name, titlecase display form pairs
with Alt-hotkey indicator. A subset of menudefs items.
Expand Down Expand Up @@ -902,7 +902,8 @@ def RemoveKeybindings(self):
Leaves the default Tk Text keybindings.
"""
# Called from configdialog.deactivate_current_config.
self.mainmenu.default_keydefs = keydefs = idleConf.GetCurrentKeySet()
keydefs = idleConf.GetCurrentKeySet()
self.mainmenu.set_default_keydefs(keydefs)
for event, keylist in keydefs.items():
self.text.event_delete(event, *keylist)
for extensionName in self.get_standard_extension_names():
Expand All @@ -917,7 +918,8 @@ def ApplyKeybindings(self):
Alse update hotkeys to current keyset.
"""
# Called from configdialog.activate_config_changes.
self.mainmenu.default_keydefs = keydefs = idleConf.GetCurrentKeySet()
keydefs = idleConf.GetCurrentKeySet()
self.mainmenu.set_default_keydefs(keydefs)
self.apply_bindings()
for extensionName in self.get_standard_extension_names():
xkeydefs = idleConf.GetExtensionBindings(extensionName)
Expand Down Expand Up @@ -1205,7 +1207,7 @@ def load_extension(self, name):
def apply_bindings(self, keydefs=None):
"""Add events with keys to self.text."""
if keydefs is None:
keydefs = self.mainmenu.default_keydefs
keydefs = self.mainmenu.get_default_keydefs()
text = self.text
text.keydefs = keydefs
for event, keylist in keydefs.items():
Expand All @@ -1221,7 +1223,7 @@ def fill_menus(self, menudefs=None, keydefs=None):
if menudefs is None:
menudefs = self.mainmenu.menudefs
if keydefs is None:
keydefs = self.mainmenu.default_keydefs
keydefs = self.mainmenu.get_default_keydefs()
menudict = self.menudict
text = self.text
for mname, entrylist in menudefs:
Expand Down
5 changes: 5 additions & 0 deletions Lib/idlelib/idle_test/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,9 +197,14 @@ def setUpClass(cls):
cls.orig_warn = config._warn
config._warn = Func()

cls._patcher = mock.patch("idlelib.macosx._tk_type", new="cocoa" if sys.platform == "darwin" else "other")
cls._patcher.start()


@classmethod
def tearDownClass(cls):
config._warn = cls.orig_warn
cls._patcher.stop()

def new_config(self, _utest=False):
return config.IdleConf(_utest=_utest)
Expand Down
3 changes: 3 additions & 0 deletions Lib/idlelib/idle_test/test_macosx.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ def tearDownClass(cls):
def test_init_sets_tktype(self):
"Test that _init_tk_type sets _tk_type according to platform."
for platform, types in ('darwin', alltypes), ('other', nontypes):
orig_root = None
macosx._idle_root = self.root
self.addCleanup(lambda: setattr(macosx, "_idle_root", orig_root))
with self.subTest(platform=platform):
macosx.platform = platform
macosx._tk_type = None
Expand Down
10 changes: 9 additions & 1 deletion Lib/idlelib/idle_test/test_mainmenu.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,18 @@

from idlelib import mainmenu
import re
import sys
import unittest
from unittest import mock


class MainMenuTest(unittest.TestCase):
def setUp(self):
self._patcher = mock.patch("idlelib.macosx._tk_type", new="cocoa" if sys.platform == "darwin" else "other")
self._patcher.start()

def tearDown(self):
self._patcher.stop()

def test_menudefs(self):
actual = [item[0] for item in mainmenu.menudefs]
Expand All @@ -15,7 +23,7 @@ def test_menudefs(self):
self.assertEqual(actual, expect)

def test_default_keydefs(self):
self.assertGreaterEqual(len(mainmenu.default_keydefs), 50)
self.assertGreaterEqual(len(mainmenu.get_default_keydefs()), 50)

def test_tcl_indexes(self):
# Test tcl patterns used to find menuitem to alter.
Expand Down
45 changes: 25 additions & 20 deletions Lib/idlelib/idle_test/test_squeezer.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"Test squeezer, coverage 95%"

import sys
from textwrap import dedent
from tkinter import Text, Tk
import unittest
Expand All @@ -22,8 +23,11 @@ def get_test_tk_root(test_instance):
requires('gui')
root = Tk()
root.withdraw()
patcher = patch("idlelib.macosx._idle_root", new=root)
patcher.start()

def cleanup_root():
patcher.stop()
root.update_idletasks()
root.destroy()
test_instance.addCleanup(cleanup_root)
Expand Down Expand Up @@ -170,27 +174,28 @@ def test_write_not_stdout(self):

def test_write_stdout(self):
"""Test Squeezer's overriding of the EditorWindow's write() method."""
editwin = self.make_mock_editor_window()

for text in ['', 'TEXT']:
editwin.write = orig_write = Mock(return_value=SENTINEL_VALUE)
squeezer = self.make_squeezer_instance(editwin)
squeezer.auto_squeeze_min_lines = 50

self.assertEqual(squeezer.editwin.write(text, "stdout"),
SENTINEL_VALUE)
self.assertEqual(orig_write.call_count, 1)
orig_write.assert_called_with(text, "stdout")
self.assertEqual(len(squeezer.expandingbuttons), 0)

for text in ['LONG TEXT' * 1000, 'MANY_LINES\n' * 100]:
editwin.write = orig_write = Mock(return_value=SENTINEL_VALUE)
squeezer = self.make_squeezer_instance(editwin)
squeezer.auto_squeeze_min_lines = 50
with patch("idlelib.macosx._tk_type", new="cocoa" if sys.platform == "darwin" else "other"):
editwin = self.make_mock_editor_window()

self.assertEqual(squeezer.editwin.write(text, "stdout"), None)
self.assertEqual(orig_write.call_count, 0)
self.assertEqual(len(squeezer.expandingbuttons), 1)
for text in ['', 'TEXT']:
editwin.write = orig_write = Mock(return_value=SENTINEL_VALUE)
squeezer = self.make_squeezer_instance(editwin)
squeezer.auto_squeeze_min_lines = 50

self.assertEqual(squeezer.editwin.write(text, "stdout"),
SENTINEL_VALUE)
self.assertEqual(orig_write.call_count, 1)
orig_write.assert_called_with(text, "stdout")
self.assertEqual(len(squeezer.expandingbuttons), 0)

for text in ['LONG TEXT' * 1000, 'MANY_LINES\n' * 100]:
editwin.write = orig_write = Mock(return_value=SENTINEL_VALUE)
squeezer = self.make_squeezer_instance(editwin)
squeezer.auto_squeeze_min_lines = 50

self.assertEqual(squeezer.editwin.write(text, "stdout"), None)
self.assertEqual(orig_write.call_count, 0)
self.assertEqual(len(squeezer.expandingbuttons), 1)

def test_auto_squeeze(self):
"""Test that the auto-squeezing creates an ExpandingButton properly."""
Expand Down
19 changes: 10 additions & 9 deletions Lib/idlelib/macosx.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
## _tk_type and its initializer are private to this section.

_tk_type = None
_idle_root = None

def _init_tk_type():
""" Initialize _tk_type for isXyzTk functions.
Expand All @@ -33,17 +34,20 @@ def _init_tk_type():
_tk_type = "cocoa"
return

root = tkinter.Tk()
ws = root.tk.call('tk', 'windowingsystem')
else:
if _idle_root is None:
_tk_type = "cocoa"
return
Comment on lines +38 to +40
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe everything from the 'testing' import to here can be deleted and these 3 lines dedented twice. IDLE will set _idle_root, at least when on mac and if a test on mac needs an accurate _tk_type, it should check requires('gui') and set _idle_root. Checking it here is redundant. Do as you wish for now.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm leaving this as is for now, I can check later if it is save to remove the testing import.


ws = _idle_root.tk.call('tk', 'windowingsystem')
if 'x11' in ws:
_tk_type = "xquartz"
elif 'aqua' not in ws:
_tk_type = "other"
elif 'AppKit' in root.tk.call('winfo', 'server', '.'):
elif 'AppKit' in _idle_root.tk.call('winfo', 'server', '.'):
_tk_type = "cocoa"
else:
_tk_type = "carbon"
root.destroy()
else:
_tk_type = "other"
return
Expand Down Expand Up @@ -216,11 +220,6 @@ def help_dialog(event=None):
root.bind('<<open-config-dialog>>', config_dialog)
root.createcommand('::tk::mac::ShowPreferences', config_dialog)
if flist:
root.bind('<<close-all-windows>>', flist.close_all_callback)

# The binding above doesn't reliably work on all versions of Tk
# on macOS. Adding command definition below does seem to do the
# right thing for now.
root.createcommand('::tk::mac::Quit', flist.close_all_callback)

if isCarbonTk():
Expand Down Expand Up @@ -266,6 +265,8 @@ def setupApp(root, flist):
isAquaTk(), isCarbonTk(), isCocoaTk(), isXQuartz() functions which
are initialized here as well.
"""
global _idle_root
_idle_root = root
if isAquaTk():
hideTkConsole(root)
overrideRootMenu(root, flist)
Expand Down
13 changes: 12 additions & 1 deletion Lib/idlelib/mainmenu.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,18 @@
if find_spec('turtledemo'):
menudefs[-1][1].append(('Turtle Demo', '<<open-turtle-demo>>'))

default_keydefs = idleConf.GetCurrentKeySet()
_default_keydefs = None

def get_default_keydefs():
global _default_keydefs
if _default_keydefs is None:
_default_keydefs = idleConf.GetCurrentKeySet()
return _default_keydefs

def set_default_keydefs(keydefs):
global _default_keydefs
_default_keydefs = keydefs


if __name__ == '__main__':
from unittest import main
Expand Down
11 changes: 6 additions & 5 deletions Lib/idlelib/pyshell.py
Original file line number Diff line number Diff line change
Expand Up @@ -1611,6 +1611,11 @@ def main():
from idlelib.run import fix_scaling
fix_scaling(root)

fixwordbreaks(root)
fix_x11_paste(root)
flist = PyShellFileList(root)
macosx.setupApp(root, flist)

# set application icon
icondir = os.path.join(os.path.dirname(__file__), 'Icons')
if system() == 'Windows':
Expand All @@ -1629,12 +1634,8 @@ def main():
for iconfile in iconfiles]
root.wm_iconphoto(True, *icons)

# start editor and/or shell windows:
fixwordbreaks(root)
fix_x11_paste(root)
flist = PyShellFileList(root)
macosx.setupApp(root, flist)

# start editor and/or shell windows:
if enable_edit:
if not (cmd or script):
for filename in args[:]:
Expand Down
Loading