-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathactivity.py
More file actions
326 lines (275 loc) · 12.3 KB
/
activity.py
File metadata and controls
326 lines (275 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# -*- coding: utf-8 -*-
# Copyright (C) 2012 Cristhofer Travieso <cristhofert97@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
import locale
import convert
import re
import json
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Pango
from sugar3.activity import activity
from sugar3.activity.widgets import StopButton
from sugar3.activity.widgets import ActivityToolbarButton
from sugar3.graphics.toolbarbox import ToolbarBox
from sugar3.graphics.radiotoolbutton import RadioToolButton
from sugar3.graphics.style import FONT_SIZE, FONT_FACE
from gettext import gettext as _
class Ratio(Gtk.Label):
def __init__(self):
Gtk.Label.__init__(self)
self.set_selectable(True)
self._size = -1
def set_text(self, text):
Gtk.Label.set_text(self, text)
length = len(text)
if length == 0:
return
width = self.get_allocation().width
size = (60 * width / 100) / length + int(FONT_SIZE * 1.2)
if not size == self._size:
self.modify_font(Pango.FontDescription(
'%s %d' % (FONT_FACE, size)))
self._size = size
class ConvertActivity(activity.Activity):
def __init__(self, handle):
activity.Activity.__init__(self, handle, True)
self.max_participants = 1
self.units = {}
self._liststore = Gtk.ListStore(str)
self.label1 = Gtk.Label()
self.label1.set_markup('<big>From value</big>')
self.label2 = Gtk.Label()
self.label2.set_markup('<big>From unit</big>')
self.label3 = Gtk.Label()
self.label3.set_markup('<big>To value</big>')
self.label4 = Gtk.Label()
self.label4.set_markup('<big>To unit</big>')
u_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
u_hbox.pack_start(self.label1, True, True, 5)
u_hbox.pack_start(self.label2, True, True, 20)
u_hbox.pack_start(self.label3, True, True, 20)
u_hbox.pack_start(self.label4, True, True, 5)
arrow_font = Pango.FontDescription(
'%s %d' % (FONT_FACE, int(FONT_SIZE * 1.8)))
input_font = Pango.FontDescription(
'%s %d' % (FONT_FACE, int(FONT_SIZE * 1.2)))
self.from_value = Gtk.Entry()
self.from_value.set_placeholder_text("Enter value")
self.from_value.connect('insert-text', self._insert_text_cb)
self.from_value.connect('changed', self._from_changed_cb)
self.from_value.override_font(input_font)
self.from_unit = Gtk.ComboBox.new_with_model_and_entry(self._liststore)
self.from_unit.pack_start(Gtk.CellRendererText(), True)
self.from_unit.set_entry_text_column(0)
self.from_unit.set_id_column(0)
self.from_unit.connect('changed', self._from_changed_cb)
self.from_unit.override_font(input_font)
self.arrow = Gtk.Label()
self.arrow.override_font(arrow_font)
self.arrow.set_text("→")
self.to_value = Gtk.Entry()
self.to_value.connect('insert-text', self._insert_text_cb)
self.to_value.connect('changed', self._to_changed_cb)
self.to_value.override_font(input_font)
self.to_unit = Gtk.ComboBox.new_with_model_and_entry(self._liststore)
self.to_unit.pack_start(Gtk.CellRendererText(), True)
self.to_unit.set_entry_text_column(0)
self.to_unit.set_id_column(0)
self.to_unit.connect('changed', self._to_changed_cb)
self.to_unit.override_font(input_font)
l_hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
l_hbox.pack_start(self.from_value, True, True, 5)
l_hbox.pack_start(self.from_unit, True, True, 5)
l_hbox.pack_start(self.arrow, False, False, 15)
l_hbox.pack_start(self.to_value, True, True, 5)
l_hbox.pack_end(self.to_unit, True, True, 5)
self.ratio = Ratio()
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
box.pack_start(u_hbox, False, False, 30)
box.pack_start(l_hbox, False, False, 0)
box.pack_start(self.ratio, True, False, 0)
self.set_canvas(box)
# Toolbar
toolbarbox = ToolbarBox()
activity_button = ActivityToolbarButton(self)
toolbarbox.toolbar.insert(activity_button, 0)
separator = Gtk.SeparatorToolItem()
separator.set_expand(False)
separator.set_draw(True)
toolbarbox.toolbar.insert(separator, -1)
self.dimensions = {}
for name in convert.dimensions:
button = RadioToolButton()
button.set_tooltip(convert.dimension_tooltips[name])
button.props.icon_name = name
if len(self.dimensions) > 0:
button.props.group = self.dimensions['length']
button.connect('clicked', self.set_dimension, name)
toolbarbox.toolbar.insert(button, -1)
self.dimensions[name] = button
separator = Gtk.SeparatorToolItem()
separator.set_expand(True)
separator.set_draw(False)
toolbarbox.toolbar.insert(separator, -1)
stopbtn = StopButton(self)
toolbarbox.toolbar.insert(stopbtn, -1)
self.set_toolbar_box(toolbarbox)
self.set_dimension(None, 'length')
self.show_all()
def _from_changed_cb(self, widget):
direction = 'from'
if isinstance(widget, Gtk.Entry):
self._update_value(widget, direction)
elif isinstance(widget, Gtk.ComboBox):
if self.arrow.get_text() == '←':
direction = 'to'
self._update_unit(widget, direction)
def _to_changed_cb(self, widget):
direction = 'to'
if isinstance(widget, Gtk.Entry):
self._update_value(widget, direction)
elif isinstance(widget, Gtk.ComboBox):
if self.arrow.get_text() == '→':
direction = 'from'
self._update_unit(widget, direction)
def _update_value(self, entry, direction):
try:
num_value = str(entry.get_text())
num_value = float(num_value.replace(',', ''))
decimals = str(len(str(num_value).split('.')[-1]))
fmt = '%.' + decimals + 'f'
new_value = locale.format(fmt, float(num_value))
new_value = new_value.rstrip("0")
if new_value[-1] == '.':
new_value = new_value[0:len(new_value) - 1]
convert_value = str(self.convert(num_value, direction))
decimals = str(len(convert_value.split('.')[-1]))
fmt = '%.' + decimals + 'f'
new_convert = locale.format(fmt, float(convert_value))
new_convert = new_convert.rstrip("0")
if new_convert[-1] == '.':
new_convert = new_convert[0:len(new_convert) - 1]
self.change_result(new_value, new_convert, direction)
except ValueError:
self.change_result('', '', direction)
def _update_unit(self, combo, direction):
if direction == 'from':
self._update_value(self.from_value, direction)
elif direction == 'to':
self._update_value(self.to_value, direction)
def change_result(self, new_value, new_convert, direction):
if direction == 'from':
self.to_value.handler_block_by_func(self._to_changed_cb)
self.to_value.handler_block_by_func(self._insert_text_cb)
self.to_value.set_text(new_convert)
self.to_value.handler_unblock_by_func(self._insert_text_cb)
self.to_value.handler_unblock_by_func(self._to_changed_cb)
self.arrow.set_text("→")
self.label1.set_markup('<big>From value</big>')
self.label2.set_markup('<big>From unit</big>')
self.label3.set_markup('<big>To value</big>')
self.label4.set_markup('<big>To unit</big>')
if new_convert != '' and new_value != '':
text = '%s %s ~ %s %s' % (
new_value, self._get_active_text(self.from_unit),
new_convert, self._get_active_text(self.to_unit))
self.ratio.set_text(text)
else:
self.ratio.set_text('')
elif direction == 'to':
self.from_value.handler_block_by_func(self._from_changed_cb)
self.from_value.handler_block_by_func(self._insert_text_cb)
self.from_value.set_text(new_convert)
self.from_value.handler_unblock_by_func(self._insert_text_cb)
self.from_value.handler_unblock_by_func(self._from_changed_cb)
self.arrow.set_text("←")
self.label1.set_markup('<big>To value</big>')
self.label2.set_markup('<big>To unit</big>')
self.label3.set_markup('<big>From value</big>')
self.label4.set_markup('<big>From unit</big>')
if new_convert != '' and new_value != '':
text = '%s %s ~ %s %s' % (
new_convert, self._get_active_text(self.from_unit),
new_value, self._get_active_text(self.to_unit))
self.ratio.set_text(text)
else:
self.ratio.set_text('')
def set_dimension(self, widget, name):
self.dimension = name
self.units = convert.dimension_units[name]
keys = list(self.units.keys())
keys.sort()
self._liststore.clear()
for x in keys:
self._liststore.append(['%s' % (x)])
unit = convert.dimension_default_unit[name]
self.from_unit.set_active_id(unit)
self.to_unit.set_active_id(unit)
def _get_active_text(self, combobox):
active = combobox.get_active()
keys = list(self.units.keys())
keys.sort()
if active < 0:
active = 0
text = keys[active]
if '<sup>' in text:
text = text.split('<b>')[1].split('</b>')[0]
return text
def convert(self, num_value, direction):
if direction == 'from':
unit = self._get_active_text(self.from_unit)
to_unit = self._get_active_text(self.to_unit)
elif direction == 'to':
unit = self._get_active_text(self.to_unit)
to_unit = self._get_active_text(self.from_unit)
return convert.convert(num_value, unit, to_unit, self.units)
def _insert_text_cb(self, entry, text, length, position):
for char in text:
if char == "-" and \
entry.get_text() is "" and len(text) == 1:
return False
elif not re.match('[0-9,.]', char):
entry.emit_stop_by_name('insert-text')
return True
return False
def write_file(self, file_path):
direction = 'from'
if self.arrow.get_text() == '←':
direction = 'to'
state = {
'dimension': self.dimension,
'from-unit': self.from_unit.get_active_id(),
'from-value': self.from_value.get_text(),
'to-unit': self.to_unit.get_active_id(),
'to-value': self.to_value.get_text(),
'direction': direction,
}
self.metadata['state'] = json.dumps(state)
file(file_path, 'w').close()
def read_file(self, file_path):
if 'state' in self.metadata:
state = json.loads(self.metadata['state'])
self.dimensions[state['dimension']].set_active(True)
self.to_unit.set_active_id(state['to-unit'])
self.from_unit.set_active_id(state['from-unit'])
if state['direction'] == 'to':
self.to_value.set_text(state['to-value'])
self.from_value.set_text(state['from-value'])
else:
self.from_value.set_text(state['from-value'])
self.to_value.set_text(state['to-value'])