Debian Codegraph @

scripts/nxt_filer

raw symbols SCIP
1 #!/usr/bin/env python3
2 #
3 # nxt_filemgr program -- Updated from nxt_filer
4 # Based on: nxt_filer program -- Simple GUI to manage files on a LEGO MINDSTORMS NXT
5 # Copyright (C) 2006 Douglas P Lau
6 # Copyright (C) 2010 rhn
7 # Copyright (C) 2017 TC Wan
8 # Copyright (C) 2018 David Lechner <[email protected]>
9 #
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 2 of the License, or
13 # (at your option) any later version.
14 #
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
19
20 import os.path
21 import shutil
22 import sys
23 import urllib.request
24
25 import gi
26 from usb.core import USBError
27
28 import nxt.locator
29 from nxt.error import FileExistsError, SystemProtocolError
30 from nxt.locator import BrickNotFoundError
31
32 gi.require_version("GLib", "2.0")
33 gi.require_version("Gio", "2.0")
34 gi.require_version("Gtk", "3.0")
35
36 from gi.repository import Gio, GLib, Gtk # noqa: E402
37
38 VERSION = "2.0"
39 PROTOCOL_VER = (1, 124)
40
41 COPYRIGHT = "2006-2018"
42 AUTHORS = ["Douglas P. Lau", "rhn", "TC Wan", "David Lechner"]
43
44 FILENAME_MINWIDTH = 100
45 FILENAME_MAXWIDTH = 300
46 FILENAME_WIDTH = 200
47 FILESIZE_MINWIDTH = 40
48 FILESIZE_MAXWIDTH = 120
49 FILESIZE_WIDTH = 80
50 FILELIST_HEIGHT = 300
51
52 WIN_WIDTH = 800
53 WIN_HEIGHT = 600
54
55 FILELIST_MINWIDTH = 1.0 * WIN_WIDTH
56 FILELIST_MAXWIDTH = 1.0 * WIN_WIDTH
57
58
59 def play_soundfile(b, fname):
60 b.play_sound_file(0, fname)
61
62
63 def run_program(b, fname):
64 b.start_program(fname)
65
66
67 def delete_file(b, fname):
68 b.file_delete(fname)
69
70
71 def read_file(b, fname):
72 with b.open_file(fname, "rb") as r:
73 with open(fname, "wb") as f:
74 shutil.copyfileobj(r, f)
75
76
77 def file_exists_dialog(win, fname):
78 fileexists_str = "Cannot add %s!" % fname
79 dialog = Gtk.MessageDialog(
80 win, 0, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, "File Exists"
81 )
82 dialog.format_secondary_text(fileexists_str)
83 dialog.run()
84 dialog.destroy()
85
86
87 def system_error_dialog(win):
88 dialog = Gtk.MessageDialog(
89 win, 0, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, "System Error"
90 )
91 dialog.format_secondary_text(
92 "Insufficient Contiguous Space!\n\n"
93 "Please delete files to create contiguous space."
94 )
95 dialog.run()
96 dialog.destroy()
97
98
99 def usb_error_dialog(win):
100 dialog = Gtk.MessageDialog(
101 win, 0, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, "USB Error"
102 )
103 dialog.format_secondary_text("Can't connect to NXT!\n\nIs the NXT powered off?")
104 dialog.run()
105 dialog.destroy()
106
107
108 def write_file(win, b, fname, data):
109 try:
110 with b.open_file(fname, "wb", len(data)) as w:
111 w.write(data)
112 except FileExistsError:
113 file_exists_dialog(win, fname)
114 except SystemProtocolError:
115 system_error_dialog(win)
116 except USBError:
117 raise
118
119
120 def write_files(win, b, names):
121 for fname in names.split("\r\n"):
122 if fname:
123 bname = os.path.basename(fname)
124 url = urllib.request.urlopen(fname)
125 try:
126 data = url.read()
127 finally:
128 url.close()
129 write_file(win, b, bname, data)
130
131
132 class NXTListing(Gtk.ListStore):
133 def __init__(self):
134 "Create an empty file list"
135 Gtk.ListStore.__init__(self, str, str)
136 self.set_sort_column_id(0, Gtk.SortType(Gtk.SortType.ASCENDING))
137
138 def populate(self, brick, pattern):
139 for fname, size in brick.find_files(pattern):
140 self.append((fname, str(size)))
141
142
143 class ApplicationWindow(Gtk.ApplicationWindow):
144 # FIXME
145 # TARGETS = Gtk.target_list_add_uri_targets()
146
147 def __init__(self, *args, **kwargs):
148 super().__init__(*args, **kwargs)
149 self.set_default_size(WIN_WIDTH, WIN_HEIGHT)
150 self.set_resizable(False)
151 self.set_border_width(6)
152 self.brick = None
153 self.selected_file = None
154 self.brick_info_str = "Disconnected"
155 self.nxt_filelist = NXTListing()
156
157 self.status_bar = Gtk.Statusbar()
158 self.connect_status_id = self.status_bar.get_context_id("connect")
159 self.connect_msg_id = None
160
161 h = Gtk.Box.new(Gtk.Orientation.VERTICAL, 6)
162 self.brick_button = Gtk.Button(label="Connect")
163 self.brick_button.connect("clicked", self.reload_filelist)
164 h.pack_start(self.brick_button, False, True, 0)
165 h.pack_start(self.make_file_panel(), True, True, 0)
166 h.pack_start(self.make_button_panel(), False, True, 0)
167 h.pack_end(self.status_bar, False, True, 0)
168 self.add(h)
169 self.reload_filelist(self.nxt_filelist)
170 self.show_all()
171
172 def make_file_view(self):
173 tv = Gtk.TreeView()
174 tv.set_headers_visible(True)
175 tv.set_property("fixed_height_mode", True)
176 r = Gtk.CellRendererText()
177 c = Gtk.TreeViewColumn("File name", r, text=0)
178 c.set_fixed_width(FILENAME_WIDTH)
179 c.set_min_width(FILENAME_MINWIDTH)
180 c.set_max_width(FILENAME_MAXWIDTH)
181 c.set_resizable(True)
182 c.set_sizing(Gtk.TreeViewColumnSizing.FIXED)
183 tv.append_column(c)
184 r = Gtk.CellRendererText()
185 c = Gtk.TreeViewColumn("Bytes", r, text=1)
186 c.set_resizable(True)
187 c.set_fixed_width(FILESIZE_WIDTH)
188 c.set_min_width(FILESIZE_MINWIDTH)
189 c.set_max_width(FILESIZE_MAXWIDTH)
190 c.set_sizing(Gtk.TreeViewColumnSizing.FIXED)
191 tv.append_column(c)
192
193 # FIXME
194 # tv.enable_model_drag_source(Gtk.gdk.BUTTON1_MASK, self.TARGETS,
195 # Gtk.gdk.ACTION_DEFAULT | Gtk.gdk.ACTION_MOVE)
196 # tv.enable_model_drag_dest(self.TARGETS, Gtk.gdk.ACTION_COPY)
197 # tv.connect("drag_data_get", self.drag_data_get_data)
198
199 tv.connect("drag_data_received", self.drag_data_received_data)
200 tv.connect("row_activated", self.row_activated_action)
201 return tv
202
203 def make_file_panel(self):
204 v = Gtk.Box(homogeneous=Gtk.Orientation.VERTICAL, spacing=0)
205 tv = self.make_file_view()
206 tv.set_model(self.nxt_filelist)
207 select = tv.get_selection()
208 select.connect("changed", self.on_tree_selection_changed)
209
210 s = Gtk.ScrolledWindow()
211 s.set_min_content_width(FILELIST_MINWIDTH)
212 s.set_min_content_height(FILELIST_HEIGHT)
213 s.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
214 s.add(tv)
215 s.set_border_width(2)
216 v.pack_start(s, True, False, 0)
217 return v
218
219 def make_button_panel(self):
220 vb = Gtk.Box(homogeneous=Gtk.Orientation.HORIZONTAL, spacing=0)
221
222 self.delete_button = Gtk.Button(label="Remove")
223 self.delete_button.connect("clicked", self.remove_file)
224 vb.pack_start(self.delete_button, True, True, 10)
225
226 self.add_button = Gtk.Button(label="Add")
227 self.add_button.connect("clicked", self.add_file)
228 vb.pack_start(self.add_button, True, True, 10)
229
230 self.exec_button = Gtk.Button(label="Execute")
231 self.exec_button.connect("clicked", self.execute_file)
232 vb.pack_start(self.exec_button, True, True, 10)
233 return vb
234
235 def do_housekeeping(self):
236 self.brick.close()
237 self.brick = None
238 self.selected_file = None
239
240 def reload_filelist(self, widget):
241 if self.brick:
242 self.do_housekeeping()
243 try:
244 self.brick = nxt.locator.find()
245 except BrickNotFoundError:
246 print("Brick not found!")
247 except USBError:
248 usb_error_dialog(self)
249 self.do_housekeeping()
250 if self.brick:
251 self.update_view()
252
253 def update_view(self):
254 self.get_brick_info()
255 if self.connect_msg_id:
256 self.status_bar.remove(self.connect_status_id, self.connect_msg_id)
257 self.connect_msg_id = self.status_bar.push(
258 self.connect_status_id, self.brick_info_str
259 )
260 self.nxt_filelist.clear()
261 if self.brick:
262 self.nxt_filelist.populate(self.brick, "*.*")
263
264 def get_brick_info(self):
265 if self.brick:
266 print("Reading from NXT..."),
267 prot_version, fw_version = self.brick.get_firmware_version()
268 print("Protocol version: %s.%s" % prot_version)
269 if prot_version == PROTOCOL_VER:
270 (
271 brick_name,
272 brick_hostid,
273 brick_signal_strengths,
274 brick_user_flash,
275 ) = self.brick.get_device_info()
276 connection_type = str(self.brick._sock)
277 self.brick_info_str = (
278 "Connected via %s to %s [%s]\tFirmware: v%s.%s\tFree space: %s"
279 % (
280 connection_type,
281 brick_name,
282 brick_hostid,
283 fw_version[0],
284 fw_version[1],
285 brick_user_flash,
286 )
287 )
288 else:
289 print("Invalid Protocol version! Closing connection.")
290 self.do_housekeeping()
291 else:
292 self.brick_info_str = "Disconnected"
293 sys.stdout.flush()
294
295 def choose_files(self):
296 dialog = Gtk.FileChooserNative()
297 dialog.new("Add File", self, Gtk.FileChooserAction.OPEN, None, None)
298 dialog.set_transient_for(self)
299 dialog.set_select_multiple(False)
300 res = dialog.run()
301 if res == Gtk.ResponseType.ACCEPT:
302 # Handle single file download for now
303 uri = dialog.get_uri()
304 try:
305 write_files(self, self.brick, uri)
306 except USBError:
307 # Cannot recover, close connection
308 usb_error_dialog(self)
309 self.do_housekeeping()
310 dialog.destroy()
311
312 def on_tree_selection_changed(self, selection):
313 model, treeiter = selection.get_selected()
314 if treeiter:
315 self.selected_file = model[treeiter][0]
316 else:
317 self.selected_file = None
318
319 def drag_data_get_data(self, treeview, context, selection, target_id, etime):
320 treeselection = treeview.get_selection()
321 model, iter = treeselection.get_selected()
322 data = model.get_value(iter, 0)
323 print(data)
324 selection.set(selection.target, 8, data)
325
326 def drag_data_received_data(self, treeview, context, x, y, selection, info, etime):
327 if context.action == Gtk.gdk.ACTION_COPY:
328 write_files(self, self.brick, selection.data)
329 # FIXME: update file listing after writing files
330 # FIXME: finish context
331
332 def row_activated_action(self, treeview, context, selection):
333 self.execute_file(selection)
334
335 def execute_file(self, widget):
336 if self.selected_file:
337 name = ""
338 ext = ""
339 try:
340 name, ext = self.selected_file.split(".")
341 if ext == "rso":
342 play_soundfile(self.brick, self.selected_file)
343 elif ext == "rxe":
344 run_program(self.brick, self.selected_file)
345 self.do_housekeeping()
346 self.update_view()
347 else:
348 print("Can't execute '*.%s' files" % ext)
349 except ValueError:
350 print("No file extension (unknown file type)")
351 except USBError:
352 # Cannot recover, close connection
353 usb_error_dialog(self)
354 self.do_housekeeping()
355 self.update_view()
356
357 def remove_file(self, widget):
358 if self.selected_file:
359 warning_str = "Do you really want to remove %s?" % self.selected_file
360 dialog = Gtk.MessageDialog(
361 self,
362 0,
363 Gtk.MessageType.WARNING,
364 Gtk.ButtonsType.OK_CANCEL,
365 "Remove File",
366 )
367 dialog.format_secondary_text(warning_str)
368 response = dialog.run()
369 dialog.destroy()
370 if response == Gtk.ResponseType.OK:
371 try:
372 delete_file(self.brick, self.selected_file)
373 except USBError:
374 # Cannot recover, close connection
375 usb_error_dialog(self)
376 self.do_housekeeping()
377 self.selected_file = None
378 self.update_view()
379
380 def add_file(self, widget):
381 if self.brick:
382 self.choose_files()
383 self.selected_file = None
384 self.update_view()
385
386
387 class AboutDialog(Gtk.AboutDialog):
388 def __init__(self, *args, **kwargs):
389 super().__init__(*args, **kwargs)
390 self.set_version(VERSION)
391 self.set_copyright(COPYRIGHT)
392 self.set_comments("LEGO® MINDSTORMS NXT File Manager")
393 self.set_license("Released under GPL v2 or later")
394 self.set_website("https://sr.ht/~ni/nxt-python/")
395 self.set_website_label("Wiki")
396 self.set_authors(AUTHORS)
397
398 markup = "<span size='x-small'>{}</span>".format(
399 "LEGO® is a trademark of the LEGO Group of companies which does not "
400 "sponsor, authorize or endorse this software."
401 )
402 disclaimer = Gtk.Label()
403 disclaimer.set_line_wrap(True)
404 disclaimer.set_max_width_chars(10)
405 disclaimer.set_markup(markup)
406 disclaimer.show()
407 self.get_content_area().pack_end(disclaimer, False, False, 6)
408
409 def do_response(self, response):
410 self.close()
411
412
413 class Application(Gtk.Application):
414 def __init__(self, *args, **kwargs):
415 super().__init__(*args, **kwargs)
416 self.window = None
417
418 self.set_option_context_summary(
419 "Simple GUI to manage files on a LEGO MINDSTORMS NXT"
420 )
421
422 def do_startup(self):
423 Gtk.Application.do_startup(self)
424
425 action = Gio.SimpleAction.new("about", None)
426 action.connect("activate", self.on_about)
427 self.add_action(action)
428
429 action = Gio.SimpleAction.new("quit", None)
430 action.connect("activate", self.on_quit)
431 self.add_action(action)
432
433 # on macOS, the menu is created automatically, but still uses the
434 # actions above
435 if app.prefers_app_menu():
436 menu1 = Gio.Menu.new()
437 menu1.append("_About", "app.about")
438
439 menu2 = Gio.Menu.new()
440 menu2.append("_Quit", "app.quit")
441 app.set_accels_for_action("app.quit", ["<Control>q"])
442
443 appMenu = Gio.Menu.new()
444 appMenu.append_section(None, menu1)
445 appMenu.append_section(None, menu2)
446 app.set_app_menu(appMenu)
447
448 def do_activate(self):
449 if not self.window:
450 self.window = ApplicationWindow(application=self)
451 self.window.present()
452
453 def on_about(self, action, param):
454 about_dialog = AboutDialog(transient_for=self.window, modal=True)
455 about_dialog.present()
456
457 def on_quit(self, action, param):
458 self.quit()
459
460
461 if __name__ == "__main__":
462 GLib.set_prgname("nxt_filer")
463 GLib.set_application_name("NXT File Manager")
464 app = Application()
465 app.run(sys.argv)