forked from srwalter/smartpen-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
smartpen-browser.py
448 lines (369 loc) · 13.4 KB
/
smartpen-browser.py
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
#!/usr/bin/python
import gtk
import pysmartpen
import xml.dom.minidom
import zipfile
import parsestf
import tempfile
import cairo
import os
import threading
import thread
import gobject
import subprocess
gobject.threads_init()
class ImagePopup(gtk.Menu):
def __init__(self, view_cb, pdf_cb):
super(gtk.Menu, self).__init__()
mi = gtk.MenuItem('View Full Size...')
mi.connect('activate', view_cb)
mi.show()
self.append(mi)
mi = gtk.MenuItem('Export as PDF...')
mi.connect('activate', pdf_cb)
mi.show()
self.append(mi)
class Parser(parsestf.STFParser):
def __init__(self, stream):
super(Parser, self).__init__(stream)
self.last_force=0
def handle_stroke_end(self, time):
self.ctx.stroke()
self.last_force = 0
def handle_point(self, x, y, f, time):
ctx = self.ctx
if f:
if self.last_force:
ctx.line_to(x, y)
else:
ctx.move_to(x, y)
self.last_force = 1
def parse(self, ctx):
self.ctx = ctx
super(Parser, self).parse()
class Notebook(object):
def __init__(self, pen, guid, title, pages, builder):
self.guid = guid
self.title = title
self.pen = pen
self.pages = pages
self.is_rendered = False
self.status_bar = builder.get_object('statusbar1')
self.progress_bar = builder.get_object('progressbar1')
self.builder = builder
ls = gtk.ListStore(str, gtk.gdk.Pixbuf, str, str)
self.ls = ls
# XXX: cleanup temp dir
self.tmpdir = tempfile.mkdtemp()
self.work_queue = []
self.work_queue_lock = threading.Lock()
self.work_queue_sem = threading.Semaphore(0)
args = tuple()
self.thread = thread.start_new_thread(self.worker_thread, args)
iv = gtk.IconView(ls)
iv.connect('item-activated', self.page_activated)
iv.connect('button-press-event', self.page_popup)
iv.modify_base(gtk.STATE_NORMAL, gtk.gdk.Color("gray"))
iv.set_text_column(0)
iv.set_pixbuf_column(1)
iv.show()
sw = gtk.ScrolledWindow()
sw.props.hscrollbar_policy = "never"
sw.add(iv)
sw.show()
self.contents = sw
def page_popup(self, iv, event):
if event.button != 3:
return None
x = event.x
y = event.y
path = iv.get_path_at_pos(int(x), int(y))
iv.set_cursor(path)
def view_cb(*args):
self._page_activated(path)
def pdf_cb(*args):
dlg = gtk.FileChooserDialog(title="Save As...",
action=gtk.FILE_CHOOSER_ACTION_SAVE,
buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,
gtk.STOCK_SAVE,gtk.RESPONSE_OK))
filter = gtk.FileFilter()
filter.set_name("PDF")
filter.add_pattern("*.pdf")
dlg.add_filter(filter)
resp = dlg.run()
filename = dlg.get_filename()
dlg.destroy()
if resp != gtk.RESPONSE_OK:
return
fd, tmpfile = tempfile.mkstemp()
self.pen.get_guid(tmpfile, self.guid, 0)
z = zipfile.ZipFile(tmpfile, "r")
name = self.ls[path][3]
f = z.open(name)
p = Parser(f)
surface = cairo.PDFSurface(filename, 4963,6278)
ctx = cairo.Context(surface)
ctx.set_source_rgb(255,255,255)
ctx.paint()
ctx.set_source_rgb(0,0,0)
try:
p.parse(ctx)
except Exception, e:
print "Parse error"
print e
os.unlink(tmpfile)
popup = ImagePopup(view_cb, pdf_cb)
popup.popup(None, None, None, event.button, event.time)
return True
def page_activated(self, iv, path):
self._page_activated(path)
def _page_activated(self, path):
fn = self.ls[path][2]
subprocess.call(["gnome-open", fn])
def worker_thread(self):
tmpdir = self.tmpdir
def make_progress():
if self.progress_bar:
frac = self.progress_bar.get_fraction()
frac *= self.progress_bar.props.discrete_blocks
frac += 1
frac /= float(self.progress_bar.props.discrete_blocks)
self.progress_bar.set_fraction(frac)
while True:
self.work_queue_sem.acquire()
self.work_queue_lock.acquire()
work = self.work_queue.pop(0)
self.work_queue_lock.release()
i, f, name = work
if i is None and f is None and name is None:
break
if self.status_bar:
ctx = self.status_bar.get_context_id("THREAD")
self.status_bar.push(ctx, "Rendering page %d..." % i)
p = Parser(f)
# XXX: get dimension from pen data
surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 4963, 6278)
ctx = cairo.Context(surface)
ctx.set_source_rgb(255, 255, 255)
ctx.paint()
ctx.set_source_rgb(0,0,0)
make_progress()
try:
p.parse(ctx)
except Exception, e:
print "Parse error"
print e
make_progress()
fn = os.path.join(tmpdir, "page%d" % i)
surface.write_to_png(fn)
make_progress()
img = gtk.gdk.pixbuf_new_from_file(fn)
img = img.scale_simple(img.props.width / 20,
img.props.height / 20,
"bilinear")
make_progress()
self.ls.append(["Page %d" % i, img, fn, name])
make_progress()
if self.status_bar:
ctx = self.status_bar.get_context_id("THREAD")
self.status_bar.pop(ctx)
if self.progress_bar:
self.progress_bar.set_fraction(0.0)
def add(self, notebook):
tab = gtk.Label(self.title)
tab.show()
notebook.append_page(self.contents, tab)
def render(self):
if self.is_rendered is True:
return
fd, tmpfile = tempfile.mkstemp()
self.pen.get_guid(tmpfile, self.guid, 0)
z = zipfile.ZipFile(tmpfile, "r")
i = 0
for name in z.namelist():
if not name.startswith('data/'):
continue
i += 1
f = z.open(name)
self.work_queue_lock.acquire()
self.work_queue.append([i, f, name])
self.work_queue_sem.release()
self.work_queue_lock.release()
if self.progress_bar:
self.progress_bar.props.discrete_blocks = i * 5
self.work_queue_lock.acquire()
self.work_queue.append([None, None, None])
self.work_queue_sem.release()
self.work_queue_lock.release()
self.is_rendered = True
os.unlink(tmpfile)
class SmartpenBrowser(object):
def pen_connect(self, *args):
usbids = [ 0x1010, 0x1020, 0x1030, 0x1032 ]
for id in usbids:
try:
self.pen.connect(product=id)
self.connected = True
except:
continue
if not self.connected:
dlg = gtk.MessageDialog(self.window, 0, "error", gtk.BUTTONS_OK,
"Failed to connect to the pen. Check permissions")
dlg.run()
dlg.destroy()
return
changes = self.pen.get_changelist()
dom = xml.dom.minidom.parseString(changes)
cl = dom.getElementsByTagName('changelist')[0]
notebooks = []
tabs = self.builder.get_object('notebook1')
tabs.connect('switch-page', self.switch_page, notebooks)
lsps = {}
for elm in cl.getElementsByTagName('lsp'):
guid = elm.getAttribute('guid')
if not guid:
continue
if guid not in lsps:
lsps[guid] = {}
lsps[guid]['pages'] = []
title = elm.getAttribute('title')
lsps[guid]['title'] = title
for p in elm.getElementsByTagName('page'):
addr = p.getAttribute('pageaddress')
lsps[guid]['pages'].insert(0, addr)
for guid, value in lsps.items():
nb = Notebook(self.pen, guid, value['title'], value['pages'],
self.builder)
notebooks.append(nb)
nb.add(tabs)
pass
def switch_page(self, notebook, page, page_num, notebooks):
while gtk.events_pending():
gtk.main_iteration()
notebooks[page_num].render()
def pen_disconnect(self, *args):
self.pen.disconnect()
self.connected = False
def pen_audio(self, *args):
if not self.connected:
dlg = gtk.MessageDialog(self.window, 0, "error", gtk.BUTTONS_OK,
"Connect to a pen first")
dlg.run()
dlg.destroy()
return
dlg = gtk.FileChooserDialog(title="Save As...",
action=gtk.FILE_CHOOSER_ACTION_CREATE_FOLDER,
buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,
gtk.STOCK_SAVE,gtk.RESPONSE_OK))
resp = dlg.run()
dirname = dlg.get_filenames()[0]
dlg.destroy()
if resp != gtk.RESPONSE_OK:
return
done = [ False ]
def copy_fds(f_in, f_out):
while True:
data = f_in.read(4096)
if not data:
break
f_out.write(data)
def background_thread(done):
fd, tmpfile = tempfile.mkstemp()
self.pen.get_paperreplay(tmpfile, 0)
z = zipfile.ZipFile(tmpfile, "r")
i = 0
for name in z.namelist():
if not name.endswith('.aac'):
continue
f_in = z.open(name)
f_out = file(os.path.join(dirname, "recording-%d.aac" % i), "wb")
copy_fds(f_in, f_out)
i += 1
done[0] = True
dlg = gtk.Dialog("Downloading Audio...", None, 0, tuple())
box = dlg.get_child()
widget = gtk.Label("Downloading audio, this may take several minutes.")
box.pack_start(widget, False, False, 0)
widget = gtk.ProgressBar()
box.pack_start(widget, False, False, 0)
dlg.show_all()
while gtk.events_pending():
gtk.main_iteration()
args = (done,)
self.audio_thread = thread.start_new_thread(background_thread, args)
while done[0] is False:
# wait for thread to finish
import time
time.sleep(0.25)
while gtk.events_pending():
gtk.main_iteration()
widget.pulse()
dlg.destroy()
dlg = gtk.MessageDialog(self.window, 0, "info", gtk.BUTTONS_OK,
"Audio download complete")
dlg.run()
dlg.destroy()
return
def pen_info(self, *args):
info = self.pen.get_info()
dom = xml.dom.minidom.parseString(info)
info = dom.getElementsByTagName('peninfo')[0]
penid = info.getAttribute('penid')
elem = info.getElementsByTagName('battery')[0]
voltage = elem.getAttribute('voltage')
battlevel = elem.getAttribute('level')
elem = info.getElementsByTagName('memory')[0]
totalmem = elem.getAttribute('totalbytes')
freemem = elem.getAttribute('freebytes')
elem = info.getElementsByTagName('version')[0]
swrev = elem.getAttribute('swrev')
freemem = int(freemem)
totalmem = int(totalmem)
label = self.builder.get_object('penid')
label.props.label = penid
label = self.builder.get_object('battery')
label.props.label = battlevel
label = self.builder.get_object('memory')
label.props.label = "%dk / %dk" % ((totalmem - freemem)/1024,
totalmem / 1024)
label = self.builder.get_object('version')
label.props.label = swrev
dlg = self.builder.get_object('infowin')
dlg.run()
dlg.hide()
def about(self, *args):
dlg = self.builder.get_object('aboutwin')
dlg.run()
dlg.hide()
def quit(self, *args):
if self.connected is True:
self.pen.disconnect()
gtk.main_quit()
def __init__(self):
builder = gtk.Builder()
try:
builder.add_from_file("smartpen-browser.glade")
except:
builder.add_from_file("/usr/share/smartpen-browser/smartpen-browser.glade")
self.builder = builder
self.connected = False
cbs = {
'on_connect_clicked': self.pen_connect,
'on_disconnect_clicked': self.pen_disconnect,
'on_audio_clicked': self.pen_audio,
'on_info_clicked': self.pen_info,
'on_quit_clicked': self.quit,
}
builder.connect_signals(cbs)
pen = pysmartpen.Smartpen()
self.pen = pen
window = builder.get_object("window1")
self.window = window
window.connect('delete-event', self.quit)
window.set_size_request(640, 480)
window.show_all()
mi = builder.get_object("about-mi")
mi.connect('activate', self.about)
if __name__ == "__main__":
x = SmartpenBrowser()
gtk.main()