Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 060ff63

Browse files
authored
Merge pull request #10621 from anntzer/cleanup-gtk3
Cleanup and py3fy backend_gtk3.
2 parents f9b67a4 + 249df18 commit 060ff63

File tree

1 file changed

+99
-114
lines changed

1 file changed

+99
-114
lines changed

lib/matplotlib/backends/backend_gtk3.py

Lines changed: 99 additions & 114 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,9 @@
1-
from __future__ import (absolute_import, division, print_function,
2-
unicode_literals)
3-
4-
import six
5-
61
import logging
72
import os
83
import sys
94

105
import matplotlib
11-
from matplotlib import backend_tools, rcParams
6+
from matplotlib import backend_tools, cbook, rcParams
127
from matplotlib._pylab_helpers import Gcf
138
from matplotlib.backend_bases import (
149
_Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2,
@@ -84,55 +79,55 @@ def _on_timer(self):
8479

8580

8681
class FigureCanvasGTK3(Gtk.DrawingArea, FigureCanvasBase):
87-
keyvald = {65507 : 'control',
88-
65505 : 'shift',
89-
65513 : 'alt',
90-
65508 : 'control',
91-
65506 : 'shift',
92-
65514 : 'alt',
93-
65361 : 'left',
94-
65362 : 'up',
95-
65363 : 'right',
96-
65364 : 'down',
97-
65307 : 'escape',
98-
65470 : 'f1',
99-
65471 : 'f2',
100-
65472 : 'f3',
101-
65473 : 'f4',
102-
65474 : 'f5',
103-
65475 : 'f6',
104-
65476 : 'f7',
105-
65477 : 'f8',
106-
65478 : 'f9',
107-
65479 : 'f10',
108-
65480 : 'f11',
109-
65481 : 'f12',
110-
65300 : 'scroll_lock',
111-
65299 : 'break',
112-
65288 : 'backspace',
113-
65293 : 'enter',
114-
65379 : 'insert',
115-
65535 : 'delete',
116-
65360 : 'home',
117-
65367 : 'end',
118-
65365 : 'pageup',
119-
65366 : 'pagedown',
120-
65438 : '0',
121-
65436 : '1',
122-
65433 : '2',
123-
65435 : '3',
124-
65430 : '4',
125-
65437 : '5',
126-
65432 : '6',
127-
65429 : '7',
128-
65431 : '8',
129-
65434 : '9',
130-
65451 : '+',
131-
65453 : '-',
132-
65450 : '*',
133-
65455 : '/',
134-
65439 : 'dec',
135-
65421 : 'enter',
82+
keyvald = {65507: 'control',
83+
65505: 'shift',
84+
65513: 'alt',
85+
65508: 'control',
86+
65506: 'shift',
87+
65514: 'alt',
88+
65361: 'left',
89+
65362: 'up',
90+
65363: 'right',
91+
65364: 'down',
92+
65307: 'escape',
93+
65470: 'f1',
94+
65471: 'f2',
95+
65472: 'f3',
96+
65473: 'f4',
97+
65474: 'f5',
98+
65475: 'f6',
99+
65476: 'f7',
100+
65477: 'f8',
101+
65478: 'f9',
102+
65479: 'f10',
103+
65480: 'f11',
104+
65481: 'f12',
105+
65300: 'scroll_lock',
106+
65299: 'break',
107+
65288: 'backspace',
108+
65293: 'enter',
109+
65379: 'insert',
110+
65535: 'delete',
111+
65360: 'home',
112+
65367: 'end',
113+
65365: 'pageup',
114+
65366: 'pagedown',
115+
65438: '0',
116+
65436: '1',
117+
65433: '2',
118+
65435: '3',
119+
65430: '4',
120+
65437: '5',
121+
65432: '6',
122+
65429: '7',
123+
65431: '8',
124+
65434: '9',
125+
65451: '+',
126+
65453: '-',
127+
65450: '*',
128+
65455: '/',
129+
65439: 'dec',
130+
65421: 'enter',
136131
}
137132

138133
# Setting this as a static constant prevents
@@ -267,7 +262,7 @@ def configure_event(self, widget, event):
267262
return # empty fig
268263
# resize the figure (in inches)
269264
dpi = self.figure.dpi
270-
self.figure.set_size_inches(w/dpi, h/dpi, forward=False)
265+
self.figure.set_size_inches(w / dpi, h / dpi, forward=False)
271266
return False # finish event propagation?
272267

273268
def on_draw_event(self, widget, ctx):
@@ -279,7 +274,7 @@ def draw(self):
279274
self.queue_draw()
280275
# do a synchronous draw (its less efficient than an async draw,
281276
# but is required if/when animation is used)
282-
self.get_property("window").process_updates (False)
277+
self.get_property("window").process_updates(False)
283278

284279
def draw_idle(self):
285280
if self._idle_draw_id != 0:
@@ -325,11 +320,11 @@ class FigureManagerGTK3(FigureManagerBase):
325320
num : int or str
326321
The Figure number
327322
toolbar : Gtk.Toolbar
328-
The Gtk.Toolbar (gtk only)
323+
The Gtk.Toolbar
329324
vbox : Gtk.VBox
330-
The Gtk.VBox containing the canvas and toolbar (gtk only)
325+
The Gtk.VBox containing the canvas and toolbar
331326
window : Gtk.Window
332-
The Gtk.Window (gtk only)
327+
The Gtk.Window
333328
334329
"""
335330
def __init__(self, canvas, num):
@@ -340,14 +335,10 @@ def __init__(self, canvas, num):
340335
self.set_window_title("Figure %d" % num)
341336
try:
342337
self.window.set_icon_from_file(window_icon)
343-
except (SystemExit, KeyboardInterrupt):
344-
# re-raise exit type Exceptions
345-
raise
346-
except:
347-
# some versions of gtk throw a glib.GError but not
348-
# all, so I am not sure how to catch it. I am unhappy
349-
# doing a blanket catch here, but am not sure what a
350-
# better way is - JDH
338+
except Exception:
339+
# Some versions of gtk throw a glib.GError but not all, so I am not
340+
# sure how to catch it. I am unhappy doing a blanket catch here,
341+
# but am not sure what a better way is - JDH
351342
_log.info('Could not load matplotlib icon: %s', sys.exc_info()[1])
352343

353344
self.vbox = Gtk.Box()
@@ -359,8 +350,8 @@ def __init__(self, canvas, num):
359350

360351
self.vbox.pack_start(self.canvas, True, True, 0)
361352
# calculate size for window
362-
w = int (self.canvas.figure.bbox.width)
363-
h = int (self.canvas.figure.bbox.height)
353+
w = int(self.canvas.figure.bbox.width)
354+
h = int(self.canvas.figure.bbox.height)
364355

365356
self.toolmanager = self._get_toolmanager()
366357
self.toolbar = self._get_toolbar()
@@ -384,7 +375,7 @@ def add_widget(child, expand, fill, padding):
384375
self.toolbar.show()
385376
h += add_widget(self.toolbar, False, False, 0)
386377

387-
self.window.set_default_size (w, h)
378+
self.window.set_default_size(w, h)
388379

389380
def destroy(*args):
390381
Gcf.destroy(num)
@@ -421,7 +412,7 @@ def show(self):
421412
self.window.show()
422413
self.window.present()
423414

424-
def full_screen_toggle (self):
415+
def full_screen_toggle(self):
425416
self._full_screen_flag = not self._full_screen_flag
426417
if self._full_screen_flag:
427418
self.window.fullscreen()
@@ -476,10 +467,6 @@ def set_cursor(self, cursor):
476467
self.canvas.get_property("window").set_cursor(cursord[cursor])
477468
Gtk.main_iteration()
478469

479-
def release(self, event):
480-
try: del self._pixmapBack
481-
except AttributeError: pass
482-
483470
def draw_rubberband(self, event, x0, y0, x1, y1):
484471
'adapted from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/189744'
485472
self.ctx = self.canvas.get_property("window").cairo_create()
@@ -493,7 +480,7 @@ def draw_rubberband(self, event, x0, y0, x1, y1):
493480
y0 = height - y0
494481
w = abs(x1 - x0)
495482
h = abs(y1 - y0)
496-
rect = [int(val) for val in (min(x0,x1), min(y0, y1), w, h)]
483+
rect = [int(val) for val in (min(x0, x1), min(y0, y1), w, h)]
497484

498485
self.ctx.new_path()
499486
self.ctx.set_line_width(0.5)
@@ -503,7 +490,7 @@ def draw_rubberband(self, event, x0, y0, x1, y1):
503490

504491
def _init_toolbar(self):
505492
self.set_style(Gtk.ToolbarStyle.ICONS)
506-
basedir = os.path.join(rcParams['datapath'],'images')
493+
basedir = os.path.join(rcParams['datapath'], 'images')
507494

508495
for text, tooltip_text, image_file, callback in self.toolitems:
509496
if text is None:
@@ -549,15 +536,14 @@ def save_figure(self, *args):
549536
startpath = os.path.expanduser(rcParams['savefig.directory'])
550537
# Save dir for next time, unless empty str (i.e., use cwd).
551538
if startpath != "":
552-
rcParams['savefig.directory'] = (
553-
os.path.dirname(six.text_type(fname)))
539+
rcParams['savefig.directory'] = os.path.dirname(fname)
554540
try:
555541
self.canvas.figure.savefig(fname, format=format)
556542
except Exception as e:
557543
error_msg_gtk(str(e), parent=self)
558544

559545
def configure_subplots(self, button):
560-
toolfig = Figure(figsize=(6,3))
546+
toolfig = Figure(figsize=(6, 3))
561547
canvas = self._get_canvas(toolfig)
562548
toolfig.subplots_adjust(top=0.9)
563549
tool = SubplotTool(self.canvas.figure, toolfig)
@@ -568,10 +554,7 @@ def configure_subplots(self, button):
568554
window = Gtk.Window()
569555
try:
570556
window.set_icon_from_file(window_icon)
571-
except (SystemExit, KeyboardInterrupt):
572-
# re-raise exit type Exceptions
573-
raise
574-
except:
557+
except Exception:
575558
# we presumably already logged a message on the
576559
# failure of the main plot, don't keep reporting
577560
pass
@@ -594,66 +577,71 @@ class FileChooserDialog(Gtk.FileChooserDialog):
594577
"""GTK+ file selector which remembers the last file/directory
595578
selected and presents the user with a menu of supported image formats
596579
"""
597-
def __init__ (self,
598-
title = 'Save file',
599-
parent = None,
600-
action = Gtk.FileChooserAction.SAVE,
601-
buttons = (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
602-
Gtk.STOCK_SAVE, Gtk.ResponseType.OK),
603-
path = None,
604-
filetypes = [],
605-
default_filetype = None
606-
):
580+
def __init__(self,
581+
title = 'Save file',
582+
parent = None,
583+
action = Gtk.FileChooserAction.SAVE,
584+
buttons = (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
585+
Gtk.STOCK_SAVE, Gtk.ResponseType.OK),
586+
path = None,
587+
filetypes = [],
588+
default_filetype = None
589+
):
607590
super().__init__(title, parent, action, buttons)
608-
self.set_default_response (Gtk.ResponseType.OK)
591+
self.set_default_response(Gtk.ResponseType.OK)
609592

610-
if not path: path = os.getcwd() + os.sep
593+
if not path:
594+
path = os.getcwd()
611595

612596
# create an extra widget to list supported image formats
613-
self.set_current_folder (path)
614-
self.set_current_name ('image.' + default_filetype)
597+
self.set_current_folder(path)
598+
self.set_current_name('image.' + default_filetype)
615599

616600
hbox = Gtk.Box(spacing=10)
617601
hbox.pack_start(Gtk.Label(label="File Format:"), False, False, 0)
618602

619603
liststore = Gtk.ListStore(GObject.TYPE_STRING)
620-
cbox = Gtk.ComboBox() #liststore)
604+
cbox = Gtk.ComboBox()
621605
cbox.set_model(liststore)
622606
cell = Gtk.CellRendererText()
623607
cbox.pack_start(cell, True)
624608
cbox.add_attribute(cell, 'text', 0)
625609
hbox.pack_start(cbox, False, False, 0)
626610

627611
self.filetypes = filetypes
628-
self.sorted_filetypes = sorted(six.iteritems(filetypes))
612+
sorted_filetypes = sorted(filetypes.items())
629613
default = 0
630-
for i, (ext, name) in enumerate(self.sorted_filetypes):
614+
for i, (ext, name) in enumerate(sorted_filetypes):
631615
liststore.append(["%s (*.%s)" % (name, ext)])
632616
if ext == default_filetype:
633617
default = i
634618
cbox.set_active(default)
635619
self.ext = default_filetype
636620

637-
def cb_cbox_changed (cbox, data=None):
621+
def cb_cbox_changed(cbox, data=None):
638622
"""File extension changed"""
639623
head, filename = os.path.split(self.get_filename())
640624
root, ext = os.path.splitext(filename)
641625
ext = ext[1:]
642-
new_ext = self.sorted_filetypes[cbox.get_active()][0]
626+
new_ext = sorted_filetypes[cbox.get_active()][0]
643627
self.ext = new_ext
644628

645629
if ext in self.filetypes:
646630
filename = root + '.' + new_ext
647631
elif ext == '':
648632
filename = filename.rstrip('.') + '.' + new_ext
649633

650-
self.set_current_name (filename)
651-
cbox.connect ("changed", cb_cbox_changed)
634+
self.set_current_name(filename)
635+
cbox.connect("changed", cb_cbox_changed)
652636

653637
hbox.show_all()
654638
self.set_extra_widget(hbox)
655639

656-
def get_filename_from_user (self):
640+
@cbook.deprecated("3.0", alternative="sorted(self.filetypes.items())")
641+
def sorted_filetypes(self):
642+
return sorted(self.filetypes.items())
643+
644+
def get_filename_from_user(self):
657645
if self.run() == int(Gtk.ResponseType.OK):
658646
return self.get_filename(), self.ext
659647
else:
@@ -690,6 +678,7 @@ def draw_rubberband(self, x0, y0, x1, y1):
690678

691679
class ToolbarGTK3(ToolContainerBase, Gtk.Box):
692680
_icon_extension = '.png'
681+
693682
def __init__(self, toolmanager):
694683
ToolContainerBase.__init__(self, toolmanager)
695684
Gtk.Box.__init__(self)
@@ -799,8 +788,7 @@ def trigger(self, *args, **kwargs):
799788
rcParams['savefig.directory'] = startpath
800789
else:
801790
# save dir for next time
802-
rcParams['savefig.directory'] = os.path.dirname(
803-
six.text_type(fname))
791+
rcParams['savefig.directory'] = os.path.dirname(fname)
804792
try:
805793
self.figure.canvas.print_figure(fname, format=format_)
806794
except Exception as e:
@@ -824,10 +812,7 @@ def init_window(self):
824812

825813
try:
826814
self.window.window.set_icon_from_file(window_icon)
827-
except (SystemExit, KeyboardInterrupt):
828-
# re-raise exit type Exceptions
829-
raise
830-
except:
815+
except Exception:
831816
# we presumably already logged a message on the
832817
# failure of the main plot, don't keep reporting
833818
pass
@@ -880,7 +865,7 @@ def error_msg_gtk(msg, parent=None):
880865
if not parent.is_toplevel():
881866
parent = None
882867

883-
if not isinstance(msg, six.string_types):
868+
if not isinstance(msg, str):
884869
msg = ','.join(map(str, msg))
885870

886871
dialog = Gtk.MessageDialog(

0 commit comments

Comments
 (0)