Commit da048b6c authored by Dmitrijs Ledkovs's avatar Dmitrijs Ledkovs Committed by Michael Catanzaro
Browse files

gnome-sudoku python 2to3 port.

https://bugzilla.gnome.org/show_bug.cgi?id=688024
parent f64029b9
......@@ -6,7 +6,7 @@ GNOME_MAINTAINER_MODE_DEFINES
GLIB_GSETTINGS
AM_PATH_PYTHON([2.4],,AC_MSG_ERROR([Python not found]))
AM_PATH_PYTHON([3.0],,AC_MSG_ERROR([Python not found]))
dnl ###########################################################################
dnl Dependencies
......
#! /usr/bin/python
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# GNOME Sudoku is a simple sudoku generator and player. Sudoku is a
......
# -*- coding: utf-8 -*-
from gi.repository import Gtk,GObject
import colors
from . import colors
class GridDancer:
......@@ -33,7 +33,7 @@ class GridDancer:
self.adjustment = 0
def start_dancing (self):
for box in self.grid.__entries__.values():
for box in list(self.grid.__entries__.values()):
box.props.can_focus = False
if box.read_only:
box.read_only = False
......@@ -46,7 +46,7 @@ class GridDancer:
def stop_dancing (self):
self.dancing = False
for box in self.grid.__entries__.values():
for box in list(self.grid.__entries__.values()):
box.props.can_focus = True
if box.need_restore:
box.read_only = True
......@@ -105,7 +105,7 @@ class GridDancer:
if __name__ == '__main__':
def test_dance_grid ():
import gsudoku
from . import gsudoku
window = Gtk.Window()
game = '''9 1 6 3 2 8 4 5 7
5 7 4 6 1 9 2 8 3
......
......@@ -41,16 +41,16 @@ class SwappableArea (Gtk.Notebook):
def run_dialog (self, d):
self.running = d
if not self.swallowed.has_key(d):
if d not in self.swallowed:
self.swallow_dialog(d)
self.set_current_page(self.swallowed[d])
try:
Gtk.main()
except:
print 'Error in dialog!'
print('Error in dialog!')
import traceback
traceback.print_exc()
print 'forge on fearlessly...'
print('forge on fearlessly...')
self.set_current_page(self.main_page)
self.running = None
tmp_response = self.response
......
# -*- coding: utf-8 -*-
from gi.repository import Gtk,GdkPixbuf,GObject
import os.path
import sudoku, saver, sudoku_maker
import sudoku_thumber
from . import sudoku, saver, sudoku_maker
from . import sudoku_thumber
from gettext import gettext as _
from gettext import ngettext
import time
import defaults
from simple_debug import simple_debug
from colors import color_hex_to_float
from . import defaults
from .simple_debug import simple_debug
from .colors import color_hex_to_float
def color_from_difficulty (diff):
DR = sudoku.DifficultyRating
......@@ -128,7 +128,7 @@ class NewOrSavedGameSelector:
if puzzles:
puzzle, diff_val = puzzles[0]
else:
print 'WARNING: Repeating puzzle for difficulty %s -- generate more puzzles to avoid this.' % cat
print('WARNING: Repeating puzzle for difficulty %s -- generate more puzzles to avoid this.' % cat)
puzzles = self.sudoku_maker.get_puzzles(1, [cat], new = False)
if puzzles:
puzzle, diff_val = puzzles[0]
......@@ -138,7 +138,7 @@ class NewOrSavedGameSelector:
for n in lpuz:
puzzle += n
else:
print 'WARNING: No puzzle for difficulty', cat
print('WARNING: No puzzle for difficulty', cat)
continue
grid = sudoku.sudoku_grid_from_string(puzzle).grid
self.new_game_model.append(('<b><i>' + label + '</i></b>',
......
......@@ -9,6 +9,9 @@ class SafeStdout:
def fileno(self):
return self.stdout.fileno()
def flush(self):
return self.stdout.flush()
def write(self, data):
try:
self.stdout.write(data)
......@@ -18,5 +21,5 @@ class SafeStdout:
sys.stdout = SafeStdout()
def start_game ():
import main
from . import main
main.start_game()
# -*- coding: utf-8 -*-
from gi.repository import Gtk,Gdk,GObject
import colors
from . import colors
import math
import random
import logging
from simple_debug import simple_debug
import sudoku
import number_box
import tracker_info
from .simple_debug import simple_debug
from . import sudoku
from . import number_box
from . import tracker_info
def gtkcolor_to_rgb (color):
return (color.red / float(2**16),
......@@ -43,11 +43,11 @@ class SudokuNumberGrid (Gtk.AspectFrame):
self.show_all()
def set_parent_for(self, parent):
for entry in self.__entries__.values():
for entry in list(self.__entries__.values()):
entry.set_parent_win(parent)
def set_timer(self, timer):
for entry in self.__entries__.values():
for entry in list(self.__entries__.values()):
entry.set_timer(timer)
def get_focused_entry (self):
......@@ -69,7 +69,7 @@ class SudokuNumberGrid (Gtk.AspectFrame):
self.table.override_color(Gtk.StateFlags.NORMAL, color)
self.table.override_background_color(Gtk.StateFlags.NORMAL, color)
for e in self.__entries__.values():
for e in list(self.__entries__.values()):
e.override_background_color(Gtk.StateFlags.NORMAL, color)
class SudokuGameDisplay (SudokuNumberGrid, GObject.GObject):
......@@ -96,7 +96,7 @@ class SudokuGameDisplay (SudokuNumberGrid, GObject.GObject):
GObject.GObject.__init__(self)
SudokuNumberGrid.__init__(self, group_size = group_size)
self.setup_grid(grid, group_size)
for e in self.__entries__.values():
for e in list(self.__entries__.values()):
e.show()
e.connect('undo-change', self.entry_callback, 'undo-change')
e.connect('changed', self.entry_callback)
......@@ -158,7 +158,7 @@ class SudokuGameDisplay (SudokuNumberGrid, GObject.GObject):
self.highlight_cells()
def unhighlight_cells (self, *args):
for e in self.__entries__.values():
for e in list(self.__entries__.values()):
e.set_background_color(None)
def highlight_cells (self, *args):
......@@ -221,8 +221,8 @@ class SudokuGameDisplay (SudokuNumberGrid, GObject.GObject):
def show_hint (self):
min_options = 10;
squares = []
for x in xrange(9):
for y in xrange(9):
for x in range(9):
for y in range(9):
if self.grid._get_(x, y) != 0:
continue
n_options = len(self.grid.possible_values(x, y))
......@@ -476,7 +476,7 @@ class SudokuGameDisplay (SudokuNumberGrid, GObject.GObject):
are stored in InteractiveGrid.conflicts
'''
# Return if there are no conflicts for this cell
if not self.grid.conflicts.has_key((x, y)):
if (x, y) not in self.grid.conflicts:
return
# Highlight the current cell
self.__entries__[(x, y)].set_error_highlight(True)
......@@ -673,7 +673,7 @@ class SudokuGameDisplay (SudokuNumberGrid, GObject.GObject):
if check_conflicts:
for xx, yy in self.grid.cleared_conflicts:
self.mark_impossible_implications(xx, yy, False)
if self.grid.conflicts.has_key((x, y)):
if (x, y) in self.grid.conflicts:
for xx, yy in self.grid.conflicts[(x, y)]:
self.mark_impossible_implications(xx, yy, False)
# Update the hints if we need to
......@@ -689,7 +689,7 @@ class SudokuGameDisplay (SudokuNumberGrid, GObject.GObject):
tracker = self.tinfo.get_tracker(self.tinfo.showing_tracker)
if not tracker:
return ret
for (x, y), value in tracker.items():
for (x, y), value in list(tracker.items()):
ret.append((x, y, value, self.tinfo.showing_tracker))
self.remove(x, y)
if self.grid and self.grid._get_(x, y):
......@@ -705,7 +705,7 @@ class SudokuGameDisplay (SudokuNumberGrid, GObject.GObject):
'''
track = self.tinfo.get_tracker(self.tinfo.showing_tracker)
if track:
for coord in track.keys():
for coord in list(track.keys()):
self.__entries__[coord].set_value(0, tracker_info.NO_TRACKER)
self.grid.remove(*coord)
self.remove_error_highlight()
......@@ -725,7 +725,7 @@ class SudokuGameDisplay (SudokuNumberGrid, GObject.GObject):
track = self.tinfo.get_tracker(self.tinfo.showing_tracker)
if not track:
return
for (x, y), value in track.items():
for (x, y), value in list(track.items()):
self.__entries__[(x, y)].set_value(value, self.tinfo.showing_tracker)
self.__entries__[(x, y)].recolor(self.tinfo.showing_tracker)
# Add it to the underlying grid
......@@ -760,7 +760,7 @@ if __name__ == '__main__':
t.__entries__[(3, 1)].set_note_text('234', '12')
def reproduce_foobared_rendering ():
from dialog_swallower import SwappableArea
from .dialog_swallower import SwappableArea
sgd = SudokuGameDisplay()
sgd.set_bg_color('black')
vb = Gtk.VBox()
......@@ -780,7 +780,7 @@ if __name__ == '__main__':
vb.pack_start(swallower, padding = 12)
window.add(vb)
window.show_all()
from gtk_goodies.dialog_extras import MessageDialog
from .gtk_goodies.dialog_extras import MessageDialog
md = MessageDialog(title = "Foo", label = "Foo", sublabel = "Bar "*12)
swallower.run_dialog(md)
hb.pack_start(sgd, padding = 6)
......
......@@ -3,7 +3,7 @@ from gi.repository import Gtk
import difflib,re
DEBUG=False
def debug (*args,**kwargs):
if DEBUG: print args,kwargs
if DEBUG: print(args,kwargs)
class TooManyChanges (Exception):
def __init__ (self, value):
......@@ -99,7 +99,7 @@ class UndoableTextChange (UndoableObject):
blocks=self.sm.get_matching_blocks()
# we only are interested in similar blocks at different positions
# (which tell us where the changes happened).
ch_blocks = filter(lambda x: x[0] != x[1] and x[2] != 0, blocks)
ch_blocks = [x for x in blocks if x[0] != x[1] and x[2] != 0]
if ch_blocks and len(ch_blocks)>1:
raise TooManyChanges("More than one block changed: %s in %s"%(ch_blocks,text2))
if ch_blocks:
......@@ -418,7 +418,7 @@ class MultipleUndoLists:
def get_history (self):
hid=self.get_current_id()
if self.histories.has_key(hid):
if hid in self.histories:
#debug('Returning history %s for id %s'%([repr(i) for i in self.histories[hid]],hid),0)
return self.histories[hid]
else:
......@@ -465,7 +465,7 @@ if __name__ == '__main__':
w.connect('delete-event',lambda *args:Gtk.main_quit())
def show_changes (*args):
for c in uhl:
print c,' initial: ',c.initial_text,' current: ',c.text
print(c,' initial: ',c.initial_text,' current: ',c.text)
ub.connect('clicked',lambda *args: debug('Undo clicked!',0))
sc.connect('clicked',show_changes)
rb.connect('clicked',lambda *args: debug('Redo clicked!',0))
......
......@@ -82,10 +82,10 @@ class ModalDialog (Gtk.Dialog):
self.connect('response',self.response_cb)
def response_cb (self, dialog, response, *params):
if self.responses.has_key(response):
if response in self.responses:
self.responses[response]()
else:
print 'WARNING, no response for ',response
print('WARNING, no response for ',response)
def setup_expander (self, expander):
label,body = expander
......@@ -105,7 +105,7 @@ class ModalDialog (Gtk.Dialog):
l.set_line_wrap(True)
expander_vbox.pack_start(l, expand=False, fill=False)
elif type(item) == [] or type(item) == ():
map(self._add_expander_item, expander_vbox, item)
list(map(self._add_expander_item, expander_vbox, item))
else:
expander_vbox.pack_start(item, True, True, 0)
......@@ -140,7 +140,7 @@ class MessageDialog (Gtk.MessageDialog, ModalDialog):
def setup_dialog (self, *args, **kwargs):
kwargs['type']=self.message_type
if kwargs.has_key('title'):
if 'title' in kwargs:
del kwargs['title']
GObject.GObject.__init__(self, *args, **kwargs)
if self.icon:
......@@ -148,7 +148,7 @@ class MessageDialog (Gtk.MessageDialog, ModalDialog):
self.image.set_from_file(self.icon)
else:
self.image.set_from_pixbuf(self.icon)
print "123"
print("123")
def setup_label (self, label):
label = '<span weight="bold" size="larger">%s</span>'%xml.sax.saxutils.escape(label)
......
......@@ -10,18 +10,18 @@ from gettext import gettext as _
from gettext import ngettext
import cairo
import dialog_swallower
import game_selector
import gsudoku
import printing
import saver
import sudoku_maker
import timer
import tracker_info
from defaults import (APPNAME, APPNAME_SHORT, AUTHORS, COPYRIGHT, DESCRIPTION, DOMAIN,
from . import dialog_swallower
from . import game_selector
from . import gsudoku
from . import printing
from . import saver
from . import sudoku_maker
from . import timer
from . import tracker_info
from .defaults import (APPNAME, APPNAME_SHORT, AUTHORS, COPYRIGHT, DESCRIPTION, DOMAIN,
IMAGE_DIR, MIN_NEW_PUZZLES, UI_DIR, VERSION, WEBSITE, WEBSITE_LABEL)
from gtk_goodies import Undo, dialog_extras
from simple_debug import simple_debug, options
from .gtk_goodies import Undo, dialog_extras
from .simple_debug import simple_debug, options
def inactivate_new_game_etc (fun):
def inactivate_new_game_etc_ (ui, *args, **kwargs):
......@@ -45,7 +45,7 @@ def inactivate_new_game_etc (fun):
if not action:
action = ui.uimanager.get_widget(p)
if not action:
print 'No action at path', p
print('No action at path', p)
else:
action.set_sensitive(False)
ret = fun(ui, *args, **kwargs)
......@@ -54,7 +54,7 @@ def inactivate_new_game_etc (fun):
if not action:
action = ui.uimanager.get_widget(p)
if not action:
print 'No action at path', p
print('No action at path', p)
else:
action.set_sensitive(True)
return ret
......@@ -256,7 +256,7 @@ class UI:
undo_widg = self.main_actions.get_action('Undo')
redo_widg = self.main_actions.get_action('Redo')
self.history = Undo.UndoHistoryList(undo_widg, redo_widg)
for entry in self.gsd.__entries__.values():
for entry in list(self.gsd.__entries__.values()):
Undo.UndoableGenericWidget(entry, self.history,
set_method = 'set_value_for_undo',
get_method = 'get_value_for_undo',
......@@ -310,7 +310,7 @@ class UI:
def setup_toggles (self):
# sync up toggles with gsettings values...
map(lambda tpl: self.wrap_toggle(*tpl),
list(map(lambda tpl: self.wrap_toggle(*tpl),
[('always-show-hints',
self.main_actions.get_action('AlwaysShowPossible')),
('show-impossible-implications',
......@@ -321,7 +321,7 @@ class UI:
self.main_actions.get_action('ToggleHighlight')),
('show-tracker',
self.main_actions.get_action('Tracker')),
])
]))
@simple_debug
def start_worker_thread (self, *args):
......@@ -348,7 +348,7 @@ class UI:
delattr(self, 'dancer')
def start_dancer (self):
import dancer
from . import dancer
self.dancer = dancer.GridDancer(self.gsd)
self.dancer.start_dancing()
......@@ -674,9 +674,9 @@ class UI:
def show_help (self, *args):
try:
Gtk.show_uri(self.w.get_screen(), "help:gnome-sudoku", Gtk.get_current_event_time())
except GObject.GError, error:
except GObject.GError as error:
# FIXME: This should create a pop-up dialog
print _('Unable to display help: %s') % str(error)
print(_('Unable to display help: %s') % str(error))
@simple_debug
def print_game (self, *args):
......@@ -781,7 +781,7 @@ class TrackerBox (Gtk.VBox):
@simple_debug
def add_tracker (self, *args, **keys):
if keys and keys.has_key('tracker_id'):
if keys and 'tracker_id' in keys:
tracker_id = self.tinfo.create_tracker(keys['tracker_id'])
else:
tracker_id = self.tinfo.create_tracker()
......@@ -964,7 +964,7 @@ class TrackerBox (Gtk.VBox):
def start_game ():
if options.debug:
print 'Starting GNOME Sudoku in debug mode'
print('Starting GNOME Sudoku in debug mode')
## You must call g_thread_init() before executing any other GLib
## functions in a threaded GLib program.
......@@ -984,7 +984,7 @@ def start_game ():
u.quit_cb()
def profile_me ():
print 'Profiling GNOME Sudoku'
print('Profiling GNOME Sudoku')
import tempfile, hotshot, hotshot.stats
pname = os.path.join(tempfile.gettempdir(), 'GNOME_SUDOKU_HOTSHOT_PROFILE')
prof = hotshot.Profile(pname)
......@@ -992,4 +992,3 @@ def profile_me ():
stats = hotshot.stats.load(pname)
stats.strip_dirs()
stats.sort_stats('time', 'calls').print_stats()
......@@ -4,10 +4,10 @@
from gi.repository import Gtk,Gdk,GObject,Pango,PangoCairo
import math
import random
import tracker_info
from . import tracker_info
from gettext import gettext as _
from simple_debug import simple_debug
from .simple_debug import simple_debug
ERROR_HIGHLIGHT_COLOR = (1.0, 0, 0)
......@@ -800,7 +800,7 @@ if __name__ == '__main__':
def test_number_selector ():
nselector = NumberSelector(default = 3)
def tell_me (b):
print 'value->', b.get_value()
print('value->', b.get_value())
nselector.connect('changed', tell_me)
window.add(nselector)
......
# -*- coding: utf-8 -*-
import time
import collections
class MethodWrapper:
def __call__ (self, cls):
for attr in dir(cls):
attrobj = getattr(cls, attr)
if callable(attrobj) and attr.find('__')!=0:
if isinstance(attrobj, collections.Callable) and attr.find('__')!=0:
setattr(cls, attr, self.wrap(attrobj))
def wrap (self, f):
......@@ -16,7 +17,7 @@ class MethodWrapper:
return _
def wrapper (self, *args, **kwargs):
print args, kwargs
print(args, kwargs)
class PausableWrapper (MethodWrapper):
......
......@@ -3,7 +3,7 @@ from gi.repository import Gtk,Gio
import cairo
import time
import os.path
import sudoku, gsudoku, saver, defaults
from . import sudoku, gsudoku, saver, defaults
from gettext import gettext as _
def fit_squares_in_rectangle (width, height, n, margin = 0):
......@@ -58,7 +58,7 @@ class SudokuPrinter:
operation.set_n_pages(pages)
def draw_page(self, operation, context, page_nr):
import sudoku_thumber
from . import sudoku_thumber
margin = 25
cr = context.get_cairo_context()
......@@ -174,7 +174,7 @@ class GamePrinter:
).get_active():
levels.append(cat)
if not levels:
levels = sudoku.DifficultyRating.categories.keys()
levels = list(sudoku.DifficultyRating.categories.keys())
nsudokus = self.sudokusToPrintSpinButton.get_adjustment().get_value()
sudokus = self.sudoku_maker.get_puzzles(
nsudokus,
......@@ -182,7 +182,7 @@ class GamePrinter:
new = not self.includeOldGamesToggle.get_active()
)
# Convert floating point difficulty into a label string
sudokus.sort(cmp = lambda a, b: cmp(a[1], b[1]))
sudokus.sort(key=lambda a: a[1])
labels = {'easy': _('Easy'),
'medium': _('Medium'),
'hard': _('Hard'),
......
# -*- coding: utf-8 -*-
from gi.repository import Gtk
import pickle, types, os, errno
import defaults
from gtk_goodies.dialog_extras import show_message_dialog
from . import defaults
from .gtk_goodies.dialog_extras import show_message_dialog
from gettext import gettext as _
import tracker_info
from . import tracker_info
SAVE_ATTRIBUTES = [('gsd.hints'),
('gsd.impossible_hints'),
......@@ -52,7 +52,7 @@ def jar_game (ui):
jar['game'] = ui.gsd.grid.to_string()
jar['tracker_info'] = tracker_info.TrackerInfo().save()
jar['tracked_notes'] = []
for e in ui.gsd.__entries__.values():
for e in list(ui.gsd.__entries__.values()):
if e.top_note_list or e.bottom_note_list:
jar['tracked_notes'].append((e.x, e.y, e.top_note_list, e.bottom_note_list))
for attr in SAVE_ATTRIBUTES:
......@@ -70,26 +70,26 @@ def open_game (ui, jar):
# The 'notes' and 'trackers' sections are for transition from the old
# style tracker storage. The tracker values and notes are stored in the
# 'tracked_notes' and 'tracker_info' sections now.
if jar.has_key('notes') and jar['notes']:
if 'notes' in jar and jar['notes']:
for x, y, top, bot in jar['notes']:
ui.gsd.__entries__[(x, y)].set_note_text(top, bot)
if jar.has_key('trackers'):
for tracker, tracked in jar.get('trackers', {}).items():
if 'trackers' in jar:
for tracker, tracked in list(jar.get('trackers', {}).items()):
# add 1 tracker per existing tracker...
ui.tracker_ui.add_tracker()
for x, y, val in tracked:
tinfo.add_trace(x, y, val)
set_value_from_jar(ui, jar)
if jar.has_key('tracking'):
for tracker, tracking in jar.get('tracking', {}).items():
if 'tracking' in jar:
for tracker, tracking in list(jar.get('tracking', {}).items()):
if tracking:
ui.tracker_ui.select_tracker(tracker)
if jar.has_key('tracked_notes') and jar['tracked_notes']:
if 'tracked_notes' in jar and jar['tracked_notes']:
for x, y, top, bot in jar['tracked_notes']:
ui.gsd.__entries__[(x, y)].set_notelist(top, bot)
if jar.has_key('tracker_info'):
if 'tracker_info' in jar:
trackers = jar['tracker_info'][2]
for tracking in trackers.keys():
for tracking in list(trackers.keys()):
ui.tracker_ui.add_tracker(tracker_id = tracking)
tinfo.load(jar['tracker_info'])
ui.tracker_ui.select_tracker(tinfo.current_tracker)
......@@ -99,23 +99,19 @@ def open_game (ui, jar):
ui.gsd.update_all_notes()
def pickle_game (ui, target):
close_me = False
if type(target) in types.StringTypes:
target = file(target, 'w')
close_me = True
to_dump = jar_game(ui)
pickle.dump(to_dump, target)
if close_me:
target.close()
if isinstance(target, str):
with open(target, 'wb'):
pickle.dump(to_dump, target)
else:
pickle.dump(to_dump, target)
def unpickle_game (ui, target):
close_me = False
if type(target) == str