Debian Codegraph @

src/cdemu

raw
1 #!/usr/bin/env python3
2 #
3 # cdemu: command-line CDEmu client
4 # Copyright (C) 2006-2026 Rok Mandeljc
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with this program; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20 import argparse
21 import configparser
22 import datetime
23 import getpass
24 import gettext
25 import os
26 import shlex
27 import subprocess
28 import sys
29 import time
30
31 import gi
32
33 # Put under if block to avoid triggering E402 warnings in subsequent imports...
34 if True:
35 gi.require_version('GLib', '2.0')
36 gi.require_version('Gio', '2.0')
37
38 from gi.repository import GLib, Gio
39
40
41 # *** Globals ***
42 app_name = "cdemu"
43 app_version = "3.3.0"
44 supported_daemon_interface_version = (7, 0)
45
46 # I18n
47 gettext.install(app_name)
48
49 # Set process name
50 if sys.platform == "linux":
51 try:
52 import ctypes
53 libc = ctypes.CDLL("libc.so.6")
54 libc.prctl(15, app_name.encode('utf-8'), 0, 0, 0) # 15 = PR_SET_NAME
55 except Exception:
56 pass
57
58
59 # String to boolean conversion helper
60 def str2bool(value):
61 return value.lower() in {"yes", "true", "t", "1"}
62
63
64 ########################################################################
65 # Terminal colors #
66 ########################################################################
67 # attrs is a comma separated list of integers, where valid values include
68 # foreground: 30-37, background: 40-47, reset: 0, bold: 1. (ECMA-48 / VT102)
69 def set_terminal_color(stream, *attrs):
70 if stream.isatty():
71 attrs_str = ";".join(str(attr) for attr in attrs)
72 stream.write(f"\x1b[{attrs_str:s}m")
73
74
75 def print_header(message):
76 set_terminal_color(sys.stdout, 1, 34)
77 print(message, file=sys.stdout)
78 set_terminal_color(sys.stdout, 0)
79
80
81 def print_error(message):
82 set_terminal_color(sys.stderr, 1, 31)
83 print(_("ERROR: %s") % (message), file=sys.stderr)
84 set_terminal_color(sys.stderr, 0)
85
86
87 def print_warning(message):
88 set_terminal_color(sys.stdout, 1, 33)
89 print(_("WARNING: %s") % (message), file=sys.stdout)
90 set_terminal_color(sys.stdout, 0)
91
92
93 ########################################################################
94 # Error #
95 ########################################################################
96 class CDEmuError(Exception):
97 pass
98
99
100 class CDEmuParserError(Exception):
101 pass
102
103
104 ########################################################################
105 # Load device #
106 ########################################################################
107 class cmd_load:
108 def __init__(self, subparsers):
109 name = "load"
110 description_msg = _("")
111 help_msg = _("loads an image to the device")
112
113 parser = subparsers.add_parser(
114 name,
115 description=description_msg,
116 help=help_msg,
117 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
118 argument_default=argparse.SUPPRESS,
119 )
120 parser.set_defaults(command_function=self)
121
122 parser.add_argument(
123 "device",
124 type=str,
125 help=_("device"),
126 )
127 parser.add_argument(
128 "image_file",
129 type=str,
130 nargs="+",
131 help=_("image file(s)"),
132 )
133 parser.add_argument(
134 "--encoding",
135 type=str,
136 help=_("encoding for text-based images"),
137 )
138 parser.add_argument(
139 "--unload",
140 "--replace",
141 action="store_true",
142 dest="unload",
143 default=False,
144 help=_("unload image from a loaded device if necessary"),
145 )
146 parser.add_argument(
147 "--create",
148 action="store_true",
149 dest="create",
150 default=False,
151 help=_("create a new device if necessary"),
152 )
153
154 def __call__(self, proxy, arguments):
155 # We need to pass absolute filenames to daemon
156 filenames = [os.path.abspath(filename) for filename in arguments.image_file]
157
158 # Gather parser parameters into a dictionary
159 parser_params = {}
160 if hasattr(arguments, "encoding"):
161 parser_params["encoding"] = GLib.Variant("s", arguments.encoding)
162
163 # Particular device vs. any device
164 if arguments.device == "any":
165 try:
166 num_devices = proxy.GetNumberOfDevices()
167 except GLib.Error as e:
168 raise CDEmuError(_("Failed to get number of devices: %s") % (e))
169
170 for device in range(num_devices):
171 # Device's status
172 try:
173 status = proxy.DeviceGetStatus(device)
174 except GLib.Error as e:
175 print_warning(_("Failed to get status of device %i: %s") % (device, e))
176 continue
177
178 # If device is already loaded, skip it
179 if status[0]:
180 continue
181
182 # Load device
183 return self.load_device(proxy, device, filenames, parser_params)
184
185 # If we are here, it means we did not find an empty device...
186
187 # We are allowed to unload a device; go over all devices again, and load the first device that we manage
188 # to unload.
189 if arguments.unload:
190 for device in range(num_devices):
191 try:
192 if self.try_unload_device(proxy, device):
193 return self.load_device(proxy, device, filenames, parser_params)
194 except Exception:
195 print_warning(_("Error while trying to unload device %d: %s") % (device, e))
196 continue
197
198 # We are allowed to create a new device.
199 if arguments.create:
200 # Create new device
201 try:
202 proxy.AddDevice()
203 except GLib.Error as e:
204 raise CDEmuError(_("Failed to add device: %s") % (e))
205
206 # Query the number again, just in case
207 try:
208 num_devices = proxy.GetNumberOfDevices()
209 except GLib.Error as e:
210 raise CDEmuError(_("Failed to get number of devices: %s") % (e))
211
212 # Load the last (= newly added) device
213 return self.load_device(proxy, num_devices - 1, filenames, parser_params)
214
215 raise CDEmuError(_("No empty device found"))
216 else:
217 try:
218 device = int(arguments.device, 0)
219 except ValueError:
220 raise CDEmuError(_("String '%s' is not a number") % (arguments.device))
221
222 # If we are allowed to unload the device, ensure that it is unloaded before submitting load command.
223 if arguments.unload:
224 try:
225 self.try_unload_device(proxy, device)
226 except Exception as e:
227 print_warning(_("Error while trying to unload device %d: %s") % (device, e))
228
229 return self.load_device(proxy, device, filenames, parser_params)
230
231 # Check if device is loaded, and try to unload it
232 def try_unload_device(self, proxy, device):
233 status = proxy.DeviceGetStatus(device)
234 if not status[0]:
235 return True # Already unloaded
236
237 # Request unload. Note that this does not necessarily unload the device, and even if it does, it usually happens
238 # some time after the command returns. For example, when linux mounts the filesystem on the optical disc, it
239 # issues a lock command to the optical drive. Therefore, the unload command only generates an event that is
240 # equivalent to the press on the eject button on the physical drive, and returns immediately. The system then
241 # picks up the generated event, unmounts the filesystem, unlocks the device, and ejects the disc from it.
242 # Therefore, after we submit the unload command, we wait for a bit while polling the device status. We cannot be
243 # too eager here, otherwise a "cdemu load --unload any <file>" might cause all devices to be unloaded and still
244 # report failing to find an empty device. On the other hand, we also do not want to wait forever...
245 TIMEOUT = 15 # seconds
246 proxy.DeviceUnload(device)
247
248 start_time = time.time()
249 while True:
250 elapsed = time.time() - start_time
251
252 # Query status
253 status = proxy.DeviceGetStatus(device)
254 if not status[0]:
255 return True # Unloaded
256
257 # Timeout
258 if elapsed > TIMEOUT:
259 break
260
261 # Wait...
262 time.sleep(0.25)
263
264 return False
265
266 # Device loading with password query support
267 def load_device(self, proxy, device, filenames, params):
268 # Try to load it
269 try:
270 proxy.DeviceLoad(device, filenames, params)
271 except GLib.Error as e:
272 if "net.sf.cdemu.CDEmuDaemon.errorMirage.EncryptedImage" in str(e):
273 # We need password to load the image, so ask the user for it
274 try:
275 password = self.ask_for_password()
276 except Exception as e:
277 raise CDEmuError(_("Failed to obtain password for encrypted image: %s") % (e, ))
278
279 # Append password to params
280 params["password"] = GLib.Variant("s", password)
281 return self.load_device(proxy, device, filenames, params)
282 else:
283 raise CDEmuError(_("Failed to load image: %s") % (e))
284
285 def ask_for_password(self):
286 def _get_command_output(command_args):
287 output = subprocess.run(
288 command_args,
289 check=True,
290 text=True,
291 stdout=subprocess.PIPE,
292 ).stdout
293
294 # Remove the trailing newline, if preset. Some commands,
295 # such as zenity, seem to include it in their output.
296 if output.endswith('\n'):
297 output = output[:-1]
298
299 return output
300
301 # If zenity integration is enabled via CDEMU_USE_ZENITY environment
302 # variable, use zenity dialog to ask for password. While this could
303 # also be achieved by setting CDEMU_ASKPASS to "zenity --password",
304 # we can better customize the dialog in this dedicated codepath.
305 if os.environ.get("CDEMU_USE_ZENITY", "0") != "0":
306 try:
307 command_args = [
308 "zenity",
309 "--entry",
310 "--title",
311 _("CDEmu client"),
312 "--text",
313 _("Please enter password for encrypted image"),
314 "--hide-text",
315 ]
316 return _get_command_output(command_args)
317 except Exception as e:
318 raise CDEmuError(_("Failed to obtain password via zenity: %s") % (e, ))
319
320 # If CDEMU_ASKPASS is defined, use it.
321 if "CDEMU_ASKPASS" in os.environ:
322 try:
323 command_args = shlex.split(os.environ["CDEMU_ASKPASS"])
324 return _get_command_output(command_args)
325 except Exception as e:
326 raise CDEmuError(_("Failed to run password agent defined via CDEMU_ASKPASS environment variable: %s") % (e, ))
327
328 # If we have console available, use `getpass`.
329 if sys.stdin.isatty():
330 print(_("The image you are trying to load is encrypted."))
331 return getpass.getpass(_("Password: "))
332
333 # Otherwise, use the command defined by SSH_ASKPASS, if available.
334 if "SSH_ASKPASS" in os.environ:
335 try:
336 command_args = shlex.split(os.environ["SSH_ASKPASS"])
337 return _get_command_output(command_args)
338 except Exception as e:
339 raise CDEmuError(_("Failed to run password agent defined via SSH_ASKPASS environment variable: %s") % (e, ))
340
341 raise CDEmuError(_("No password agent was supplied."))
342
343
344 ########################################################################
345 # Create blank #
346 ########################################################################
347 class cmd_create_blank:
348 def __init__(self, subparsers):
349 name = "create-blank"
350 description_msg = _("")
351 help_msg = _("load blank/recordable image to the device")
352
353 parser = subparsers.add_parser(
354 name,
355 description=description_msg,
356 help=help_msg,
357 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
358 argument_default=argparse.SUPPRESS,
359 )
360 parser.set_defaults(command_function=self)
361
362 parser.add_argument(
363 "device",
364 type=str,
365 help=_("device"),
366 )
367 parser.add_argument(
368 "image_file",
369 type=str,
370 help=_("image filename/basename"),
371 )
372 parser.add_argument(
373 "--writer-id",
374 type=str,
375 nargs="?",
376 required=True,
377 help=_("ID of image writer to use"),
378 )
379 parser.add_argument(
380 "--medium-type",
381 type=str,
382 nargs="?",
383 choices=['cdr74', 'cdr80', 'cdr90', 'cdr99', 'dvd+r', 'bdr'],
384 help=_("medium type"),
385 )
386 parser.add_argument(
387 "--param",
388 type=str,
389 nargs="?",
390 action='append',
391 help=_("additional writer parameter(s)"),
392 )
393
394 def __call__(self, proxy, arguments):
395 # We need to pass absolute filename/basename to daemon
396 filename = os.path.abspath(arguments.image_file)
397
398 # Gather writer parameters into a dictionary
399 parameters = {}
400 if hasattr(arguments, "writer_id"):
401 parameters["writer-id"] = GLib.Variant("s", arguments.writer_id)
402 if hasattr(arguments, "medium_type"):
403 parameters["medium-type"] = GLib.Variant("s", arguments.medium_type)
404 if hasattr(arguments, "param"):
405 # Process parameters
406 writer_parameters = self.process_writer_parameters(arguments.param)
407 # Validate parameters using writer's parameter sheet
408 writer_parameters = self.validate_writer_parameters(
409 proxy,
410 arguments.writer_id,
411 writer_parameters,
412 )
413 # Set to parameters dictionary that we will send to daemon
414 parameters.update(writer_parameters)
415
416 # Particular device vs. any device
417 if arguments.device == "any":
418 try:
419 num_devices = proxy.GetNumberOfDevices()
420 except GLib.Error as e:
421 raise CDEmuError(_("Failed to get number of devices: %s") % (e))
422
423 for device in range(num_devices):
424 # Device's status
425 try:
426 status = proxy.DeviceGetStatus(device)
427 except GLib.Error as e:
428 print_warning(_("Failed to get status of device %i: %s") % (device, e))
429 continue
430
431 # If device is already loaded, skip it
432 if status[0]:
433 continue
434
435 # Load device
436 return self.load_device(proxy, device, filename, parameters)
437 else:
438 # If we're here, it means we didn't get an empty device
439 raise CDEmuError(_("No empty device found"))
440 else:
441 try:
442 device = int(arguments.device, 0)
443 except ValueError:
444 raise CDEmuError(_("String '%s' is not a number") % (arguments.device))
445
446 return self.load_device(proxy, device, filename, parameters)
447
448 # Device loading
449 def load_device(self, proxy, device, filenames, params):
450 # Try to load it
451 try:
452 proxy.DeviceCreateBlank(device, filenames, params)
453 except GLib.Error as e:
454 raise CDEmuError(_("Failed to load blank image: %s") % (e))
455
456 # Image writer parameter processing
457 def process_writer_parameters(self, parameter_strings):
458 parameters = {}
459
460 # In general, we can be given multiple strings, one for each
461 # command-line argument...
462 for parameter_string in parameter_strings:
463 # ... and to make things interesting, each string can
464 # contain several "key=value" pairs, separated by semi-colon
465 parameter_tokens = parameter_string.split(";")
466
467 for parameter_token in parameter_tokens:
468 # Split into key and value
469 try:
470 key, value = parameter_token.split("=")
471 except ValueError:
472 raise CDEmuError(_("Parameter token '%s' is not a key=value pair!") % parameter_token)
473
474 # Strip whitespaces and insert into dictionary
475 parameters[key.strip()] = value.strip()
476
477 return parameters
478
479 # Writer parameter validation
480 def validate_writer_parameters(self, proxy, writer_id, parameters):
481 # Grab writer's parameter sheet
482 try:
483 parameter_sheet = proxy.EnumWriterParameters(writer_id)
484 except GLib.Error as e:
485 raise CDEmuError(_("Failed to get parameter sheet for writer: %s") % (e))
486
487 # Convert the XML tree into a dictionary for convenience
488 valid_parameters = {}
489 for parameter_entry in parameter_sheet:
490 valid_parameters[parameter_entry[0]] = parameter_entry
491
492 # Now, go over given parameters and validate them
493 # NOTE: we need to use list(parameters.items()) because we may
494 # change the dictionary (pop() call during validation), and that
495 # raises error in python3
496 for key, value in list(parameters.items()):
497 try:
498 parameter_entry = valid_parameters[key]
499 except KeyError:
500 print_warning(_("Parameter '%s' not found in writer's parameter sheet!") % (key))
501 parameters.pop(key, '') # Remove from dictionary
502 continue
503
504 # Determine type
505 if len(parameter_entry[4]):
506 # Enum; no conversion to be done, but check if value is
507 # on the list of valid values, and if not, print a warning
508 for enum_value in parameter_entry[4]:
509 if value == enum_value:
510 parameters[key] = GLib.Variant("s", value)
511 break
512 else:
513 print_warning(_("Invalid value '%s' given for parameter '%s'!") % (value, key))
514 elif isinstance(parameter_entry[3], str):
515 # String
516 parameters[key] = GLib.Variant("s", value)
517 elif isinstance(parameter_entry[3], bool):
518 # Boolean; convert string value to boolean
519 parameters[key] = GLib.Variant("b", str2bool(value))
520 elif isinstance(parameter_entry[3], int):
521 # Convert string value to integer
522 try:
523 parameters[key] = GLib.Variant("i", int(value, 0))
524 except ValueError:
525 raise CDEmuError(
526 _("String '%s' given as value for parameter '%s' is not a number!") % (value, key))
527 else:
528 print_warning(
529 _("Unhandled parameter type '%s' declared for parameter '%s'!") %
530 (type(parameter_entry[3]), key),
531 )
532 continue
533
534 return parameters
535
536
537 ########################################################################
538 # Unload device #
539 ########################################################################
540 class cmd_unload:
541 def __init__(self, subparsers):
542 name = "unload"
543 description_msg = _("")
544 help_msg = _("unloads the device")
545
546 parser = subparsers.add_parser(
547 name,
548 description=description_msg,
549 help=help_msg,
550 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
551 argument_default=argparse.SUPPRESS,
552 )
553 parser.set_defaults(command_function=self)
554
555 parser.add_argument(
556 "device",
557 type=str,
558 help=_("device"),
559 )
560
561 def __call__(self, proxy, arguments):
562 # Particular device vs. all devices
563 if arguments.device == "all":
564 try:
565 num_devices = proxy.GetNumberOfDevices()
566 except GLib.Error as e:
567 raise CDEmuError(_("Failed to get number of devices: %s") % (e))
568
569 for device in range(num_devices):
570 try:
571 proxy.DeviceUnload(device)
572 except GLib.Error as e:
573 print_warning(_("Failed to unload device %i: %s") % (device, e))
574 continue
575 else:
576 try:
577 device = int(arguments.device, 0)
578 proxy.DeviceUnload(device)
579 except GLib.Error as e:
580 raise CDEmuError(_("Failed to unload device %i: %s") % (device, e))
581 except ValueError:
582 raise CDEmuError(_("String '%s' is not a number") % (arguments.device))
583
584
585 ########################################################################
586 # Display status #
587 ########################################################################
588 class cmd_display_status:
589 def __init__(self, subparsers):
590 name = "status"
591 description_msg = _("")
592 help_msg = _("displays the devices' status")
593
594 parser = subparsers.add_parser(
595 name,
596 description=description_msg,
597 help=help_msg,
598 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
599 argument_default=argparse.SUPPRESS,
600 )
601 parser.set_defaults(command_function=self)
602
603 def __call__(self, proxy, arguments):
604 # Print status for all devices
605 try:
606 num_devices = proxy.GetNumberOfDevices()
607 except GLib.Error as e:
608 raise CDEmuError(_("Failed to get number of devices: %s") % (e))
609
610 print_header(_("Devices' status:"))
611 print("%-5s %-10s %s" % (_("DEV"), _("LOADED"), _("FILENAME")))
612 for device in range(num_devices):
613 try:
614 loaded, filenames = proxy.DeviceGetStatus(device)
615 except GLib.Error as e:
616 print_warning(_("Failed to get status of device %i: %s") % (device, e))
617 continue
618
619 if not loaded:
620 filenames = [""]
621
622 # First line is for all device's data, the rest are for additional filenames
623 print("%-5s %-10s %s" % (device, loaded, filenames[0]))
624 for filename in filenames[1:]:
625 print("%-5s %-10s %s" % ("", "", filename))
626
627
628 ########################################################################
629 # Device mapping #
630 ########################################################################
631 class cmd_device_mapping:
632 def __init__(self, subparsers):
633 name = "device-mapping"
634 description_msg = _("")
635 help_msg = _("displays the device mapping information")
636
637 parser = subparsers.add_parser(
638 name,
639 description=description_msg,
640 help=help_msg,
641 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
642 argument_default=argparse.SUPPRESS,
643 )
644 parser.set_defaults(command_function=self)
645
646 def __call__(self, proxy, arguments):
647 # Print device mapping for all devices
648 try:
649 num_devices = proxy.GetNumberOfDevices()
650 except GLib.Error as e:
651 raise CDEmuError(_("Failed to get number of devices: %s") % (e))
652
653 print_header(_("Device mapping:"))
654 print("%-5s %-15s %-15s" % (_("DEV"), _("SCSI CD-ROM"), _("SCSI generic")))
655 for device in range(num_devices):
656 try:
657 dev_sr, dev_sg = proxy.DeviceGetMapping(device)
658 except GLib.Error as e:
659 print_warning(_("Failed to get device mapping of device %i: %s") % (device, e))
660 continue
661
662 print("%-5s %-15s %-15s" % (device, dev_sr, dev_sg))
663
664
665 ########################################################################
666 # Daemon debug mask #
667 ########################################################################
668 class cmd_daemon_debug_mask:
669 def __init__(self, subparsers):
670 name = "daemon-debug-mask"
671 description_msg = _("")
672 help_msg = _("displays/sets daemon debug mask")
673
674 parser = subparsers.add_parser(
675 name,
676 description=description_msg,
677 help=help_msg,
678 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
679 argument_default=argparse.SUPPRESS,
680 )
681 parser.set_defaults(command_function=self)
682
683 parser.add_argument(
684 "device",
685 type=str,
686 help=_("device"),
687 )
688 parser.add_argument(
689 "new_value",
690 nargs="?",
691 type=str,
692 help=_("new value"),
693 )
694 parser.set_defaults(command_function=self)
695
696 def __call__(self, proxy, arguments):
697 # Retrieve list of valid masks (for encoding/decoding)
698 mask_mapping = self._get_debug_mask_mapping(proxy)
699
700 # Set daemon debug mask
701 if hasattr(arguments, "new_value"):
702 # Convert the input value to mask
703 mask = self._convert_input_to_mask(arguments.new_value, mask_mapping)
704
705 # Set the mask
706 if arguments.device == "all":
707 try:
708 num_devices = proxy.GetNumberOfDevices()
709 except GLib.Error as e:
710 raise CDEmuError(_("Failed to get number of devices: %s") % (e))
711
712 print(_("Setting daemon debug mask of all devices to 0x%X.") % (mask))
713 for device in range(num_devices):
714 try:
715 proxy.DeviceSetOption(device, "daemon-debug-mask", GLib.Variant("i", mask))
716 except GLib.Error as e:
717 print_warning(
718 _("Failed to set daemon debug mask of device %i to 0x%X: %s") %
719 (device, mask, e),
720 )
721 continue
722 else:
723 try:
724 device = int(arguments.device, 0)
725 except ValueError:
726 raise CDEmuError(_("String '%s' is not a number") % (arguments.device))
727
728 print(_("Setting daemon debug mask of device %i to 0x%X.") % (device, mask))
729 try:
730 proxy.DeviceSetOption(device, "daemon-debug-mask", GLib.Variant("i", mask))
731 except GLib.Error as e:
732 raise CDEmuError(
733 _("Failed to set daemon debug mask of device %i to 0x%X: %s") %
734 (device, mask, e),
735 )
736
737 # Get daemon debug mask
738 else:
739 # Particular device vs. all devices
740 if arguments.device == "all":
741 try:
742 num_devices = proxy.GetNumberOfDevices()
743 except GLib.Error as e:
744 raise CDEmuError(_("Failed to get number of devices: %s") % (e))
745
746 print_header(_("Devices' daemon debug masks:"))
747 print("%-5s %-10s %s" % (_("DEV"), _("DEBUG MASK"), _("MEANING")))
748
749 for device in range(num_devices):
750 try:
751 mask = proxy.DeviceGetOption(device, "daemon-debug-mask")
752 except GLib.Error as e:
753 print_warning(
754 _("Failed to get daemon debug mask of device %i: %s") %
755 (device, e),
756 )
757 continue
758
759 mask_meaning = self._convert_mask_to_string(mask, mask_mapping)
760
761 print("%-5s 0x%08X %s" % (device, mask, mask_meaning))
762 else:
763 try:
764 device = int(arguments.device, 0)
765 mask = proxy.DeviceGetOption(device, "daemon-debug-mask")
766 except GLib.Error as e:
767 raise CDEmuError(
768 _("Failed to get daemon debug mask of device %i: %s") %
769 (device, e),
770 )
771 except ValueError:
772 raise CDEmuError(_("String '%s' is not a number") % (arguments.device))
773
774 mask_meaning = self._convert_mask_to_string(mask, mask_mapping)
775
776 print(
777 _("Daemon debug mask of device %i: 0x%X (%s)") %
778 (device, mask, mask_meaning),
779 )
780
781 def _convert_input_to_mask(self, input_str, mapping):
782 output_mask = 0
783
784 # Split input string on pipe (|)
785 tokens = input_str.split("|")
786 for token in tokens:
787 token = token.strip()
788
789 try:
790 if token in mapping:
791 val = mapping[token]
792 else:
793 val = int(token, 0)
794 except ValueError:
795 raise CDEmuError(
796 _("String '%s' is not a number nor was it found in the list of valid debug mask identifiers") %
797 (token)
798 )
799
800 output_mask |= val
801
802 return output_mask
803
804 def _convert_mask_to_string(self, value, mapping):
805 output_list = [
806 mask_name for mask_name, mask_value in mapping.items()
807 if value & mask_value != 0
808 ]
809 return "|".join(output_list)
810
811 def _get_debug_mask_mapping(self, proxy):
812 try:
813 debug_masks = proxy.EnumDaemonDebugMasks()
814 mapping = {
815 mask_entry[0]: mask_entry[1]
816 for mask_entry in debug_masks
817 }
818 except GLib.Error as e:
819 print_warning(_("Failed to enumerate supported daemon debug masks: %s") % (e))
820 mapping = {}
821
822 return mapping
823
824
825 ########################################################################
826 # Library debug mask #
827 ########################################################################
828 class cmd_library_debug_mask:
829 def __init__(self, subparsers):
830 name = "library-debug-mask"
831 description_msg = _("")
832 help_msg = _("displays/sets library debug mask")
833
834 parser = subparsers.add_parser(
835 name,
836 description=description_msg,
837 help=help_msg,
838 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
839 argument_default=argparse.SUPPRESS,
840 )
841 parser.set_defaults(command_function=self)
842
843 parser.add_argument(
844 "device",
845 type=str,
846 help=_("device"),
847 )
848 parser.add_argument(
849 "new_value",
850 nargs="?",
851 type=str,
852 help=_("new value"),
853 )
854
855 def __call__(self, proxy, arguments):
856 # Retrieve list of valid masks (for encoding/decoding)
857 mask_mapping = self._get_debug_mask_mapping(proxy)
858
859 # Set debug mask
860 if hasattr(arguments, "new_value"):
861 # Convert the input value to mask
862 mask = self._convert_input_to_mask(arguments.new_value, mask_mapping)
863
864 # Set the mask
865 if arguments.device == "all":
866 try:
867 num_devices = proxy.GetNumberOfDevices()
868 except GLib.Error as e:
869 raise CDEmuError(_("Failed to get number of devices: %s") % (e))
870
871 print(_("Setting library debug mask of all devices to 0x%X.") % (mask))
872 for device in range(num_devices):
873 try:
874 proxy.DeviceSetOption(device, "library-debug-mask", GLib.Variant("i", mask))
875 except GLib.Error as e:
876 print_warning(
877 _("Failed to set library debug mask of device %i to 0x%X: %s") %
878 (device, mask, e),
879 )
880 continue
881 else:
882 try:
883 device = int(arguments.device, 0)
884 except ValueError:
885 raise CDEmuError(_("String '%s' is not a number") % (arguments.device))
886
887 print(_("Setting library debug mask of device %i to 0x%X.") % (device, mask))
888 try:
889 proxy.DeviceSetOption(device, "library-debug-mask", GLib.Variant("i", mask))
890 except GLib.Error as e:
891 raise CDEmuError(
892 _("Failed to set library debug mask of device %i to 0x%X: %s") %
893 (device, mask, e),
894 )
895
896 # Get debug mask
897 else:
898 # Particular device vs. all devices
899 if arguments.device == "all":
900 try:
901 num_devices = proxy.GetNumberOfDevices()
902 except GLib.Error as e:
903 raise CDEmuError(_("Failed to get number of devices: %s") % (e))
904
905 print_header(_("Devices' library debug masks:"))
906 print("%-5s %-10s %s" % (_("DEV"), _("DEBUG MASK"), _("MEANING")))
907
908 for device in range(num_devices):
909 try:
910 mask = proxy.DeviceGetOption(device, "library-debug-mask")
911 except GLib.Error as e:
912 print_warning(
913 _("Failed to get library debug mask of device %i: %s") %
914 (device, e),
915 )
916
917 mask_meaning = self._convert_mask_to_string(mask, mask_mapping)
918
919 print("%-5s 0x%08X %s" % (device, mask, mask_meaning))
920 else:
921 try:
922 device = int(arguments.device, 0)
923 mask = proxy.DeviceGetOption(device, "library-debug-mask")
924 except GLib.Error as e:
925 raise CDEmuError(
926 _("Failed to get library debug mask of device %i: %s") %
927 (device, e),
928 )
929 except ValueError:
930 raise CDEmuError(_("String '%s' is not a number") % (mask))
931
932 mask_meaning = self._convert_mask_to_string(mask, mask_mapping)
933
934 print(
935 _("Library debug mask of device %i: 0x%X (%s)") %
936 (device, mask, mask_meaning),
937 )
938
939 def _convert_input_to_mask(self, input_str, mapping):
940 output_mask = 0
941
942 # Split input string on pipe (|)
943 tokens = input_str.split("|")
944 for token in tokens:
945 token = token.strip()
946
947 try:
948 if token in mapping:
949 val = mapping[token]
950 else:
951 val = int(token, 0)
952 except ValueError:
953 raise CDEmuError(
954 _("String '%s' is not a number nor was it found in the list of valid debug mask identifiers") %
955 (token),
956 )
957
958 output_mask |= val
959
960 return output_mask
961
962 def _convert_mask_to_string(self, value, mapping):
963 output_list = [
964 mask_name for mask_name, mask_value in mapping.items()
965 if value & mask_value != 0
966 ]
967 return "|".join(output_list)
968
969 def _get_debug_mask_mapping(self, proxy):
970 try:
971 debug_masks = proxy.EnumLibraryDebugMasks()
972 mapping = {
973 mask_entry[0]: mask_entry[1]
974 for mask_entry in debug_masks
975 }
976 except GLib.Error as e:
977 print_warning(_("Failed to enumerate supported library debug masks: %s") % (e))
978 mapping = {}
979
980 return mapping
981
982
983 ########################################################################
984 # DPM emulation #
985 ########################################################################
986 class cmd_dpm_emulation:
987 def __init__(self, subparsers):
988 name = "dpm-emulation"
989 description_msg = _("")
990 help_msg = _("displays/sets DPM emulation flag")
991
992 parser = subparsers.add_parser(
993 name,
994 description=description_msg,
995 help=help_msg,
996 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
997 argument_default=argparse.SUPPRESS,
998 )
999 parser.set_defaults(command_function=self)
1000
1001 parser.add_argument(
1002 "device",
1003 type=str,
1004 help=_("device"),
1005 )
1006 parser.add_argument(
1007 "new_value",
1008 nargs="?",
1009 type=str,
1010 help=_("new value"),
1011 )
1012
1013 def __call__(self, proxy, arguments):
1014 # Set DPM emulation flag
1015 if hasattr(arguments, "new_value"):
1016 try:
1017 enabled = str2bool(arguments.new_value)
1018 except ValueError:
1019 raise CDEmuError(_("String '%s' is not a number") % (arguments.new_value))
1020
1021 if arguments.device == "all":
1022 try:
1023 num_devices = proxy.GetNumberOfDevices()
1024 except GLib.Error as e:
1025 raise CDEmuError(_("Failed to get number of devices: %s") % (e))
1026
1027 print(_("Setting DPM emulation flag of all devices to %i.") % (enabled))
1028 for device in range(num_devices):
1029 try:
1030 proxy.DeviceSetOption(device, "dpm-emulation", GLib.Variant("b", enabled))
1031 except GLib.Error as e:
1032 print_warning(
1033 _("Failed to set DPM emulation flag of device %i to %i: %s") %
1034 (device, enabled, e),
1035 )
1036 continue
1037 else:
1038 try:
1039 device = int(arguments.device, 0)
1040 except ValueError:
1041 raise CDEmuError(_("String '%s' is not a number") % (arguments.device))
1042
1043 print(_("Setting DPM emulation flag of device %i to %i.") % (device, enabled))
1044 try:
1045 proxy.DeviceSetOption(device, "dpm-emulation", GLib.Variant("b", enabled))
1046 except GLib.Error as e:
1047 raise CDEmuError(
1048 _("Failed to set DPM emulation flag of device %i to %i: %s") %
1049 (device, enabled, e),
1050 )
1051
1052 # Get DPM emulation flag
1053 else:
1054 # Particular device vs. all devices
1055 if arguments.device == "all":
1056 try:
1057 num_devices = proxy.GetNumberOfDevices()
1058 except GLib.Error as e:
1059 raise CDEmuError(_("Failed to get number of devices: %s") % (e))
1060
1061 print_header(_("Devices' DPM emulation flag:"))
1062 print("%-5s %-10s" % (_("DEV"), _("ENABLED")))
1063
1064 for device in range(num_devices):
1065 try:
1066 enabled = proxy.DeviceGetOption(device, "dpm-emulation")
1067 except GLib.Error as e:
1068 print_warning(_("Failed to get DPM emulation flag of device %i: %s") % (device, e))
1069 continue
1070
1071 print("%-5s %i" % (device, enabled))
1072 else:
1073 try:
1074 device = int(arguments.device, 0)
1075 enabled = proxy.DeviceGetOption(device, "dpm-emulation")
1076 except GLib.Error as e:
1077 raise CDEmuError(_("Failed to get DPM emulation flag of device %i: %s") % (device, e))
1078 except ValueError:
1079 raise CDEmuError(_("String '%s' is not a number") % (arguments.device))
1080
1081 print(_("DPM emulation flag of device %i: %i") % (device, enabled))
1082
1083
1084 ########################################################################
1085 # Transfer rate emulation #
1086 ########################################################################
1087 class cmd_tr_emulation:
1088 def __init__(self, subparsers):
1089 name = "tr-emulation"
1090 description_msg = _("")
1091 help_msg = _("displays/sets transfer rate emulation flag")
1092
1093 parser = subparsers.add_parser(
1094 name,
1095 description=description_msg,
1096 help=help_msg,
1097 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
1098 argument_default=argparse.SUPPRESS,
1099 )
1100 parser.set_defaults(command_function=self)
1101
1102 parser.add_argument(
1103 "device",
1104 type=str,
1105 help=_("device"),
1106 )
1107 parser.add_argument(
1108 "new_value",
1109 nargs="?",
1110 type=str,
1111 help=_("new value"),
1112 )
1113
1114 def __call__(self, proxy, arguments):
1115 # Set TR emulation flag
1116 if hasattr(arguments, "new_value"):
1117 try:
1118 enabled = str2bool(arguments.new_value)
1119 except ValueError:
1120 raise CDEmuError(_("String '%s' is not a number") % (arguments[1]))
1121
1122 if arguments.device == "all":
1123 try:
1124 num_devices = proxy.GetNumberOfDevices()
1125 except GLib.Error as e:
1126 raise CDEmuError(_("Failed to get number of devices: %s") % (e))
1127
1128 print(_("Setting transfer rate emulation flag of all devices to %i.") % (enabled))
1129 for device in range(num_devices):
1130 try:
1131 proxy.DeviceSetOption(device, "tr-emulation", GLib.Variant("b", enabled))
1132 except GLib.Error as e:
1133 print_warning(
1134 _("Failed to set transfer rate emulation flag of device %i to %i: %s") %
1135 (device, enabled, e),
1136 )
1137 continue
1138 else:
1139 try:
1140 device = int(arguments.device, 0)
1141 except ValueError:
1142 raise CDEmuError(_("String '%s' is not a number") % (arguments.device))
1143
1144 print(_("Setting transfer rate emulation flag of device %i to %i.") % (device, enabled))
1145 try:
1146 proxy.DeviceSetOption(device, "tr-emulation", GLib.Variant("b", enabled))
1147 except GLib.Error as e:
1148 raise CDEmuError(
1149 _("Failed to set transfer rate emulation flag of device %i to %i: %s") %
1150 (device, enabled, e),
1151 )
1152
1153 # Get TR emulation flag
1154 else:
1155 # Particular device vs. all devices
1156 if arguments.device == "all":
1157 try:
1158 num_devices = proxy.GetNumberOfDevices()
1159 except GLib.Error as e:
1160 raise CDEmuError(_("Failed to get number of devices: %s") % (e))
1161
1162 print(_("Devices' transfer rate emulation flag:"))
1163 print("%-5s %-10s" % (_("DEV"), _("ENABLED")))
1164
1165 for device in range(num_devices):
1166 try:
1167 enabled = proxy.DeviceGetOption(device, "tr-emulation")
1168 except GLib.Error as e:
1169 print_warning(_("Failed to get transfer rate emulation flag of device %i: %s") % (device, e))
1170 continue
1171
1172 print("%-5s %i" % (device, enabled))
1173 else:
1174 try:
1175 device = int(arguments.device, 0)
1176 enabled = proxy.DeviceGetOption(device, "tr-emulation")
1177 except GLib.Error as e:
1178 raise CDEmuError(_("Failed to get transfer rate emulation flag of device %i: %s") % (device, e))
1179 except ValueError:
1180 raise CDEmuError(_("String '%s' is not a number") % (arguments.device))
1181
1182 print(_("Transfer rate emulation flag of device %i: %i") % (device, enabled))
1183
1184
1185 ########################################################################
1186 # Bad sector emulation #
1187 ########################################################################
1188 class cmd_bad_sector_emulation:
1189 def __init__(self, subparsers):
1190 name = "bad-sector-emulation"
1191 description_msg = _("")
1192 help_msg = _("displays/sets bad sector emulation flag")
1193
1194 parser = subparsers.add_parser(
1195 name,
1196 description=description_msg,
1197 help=help_msg,
1198 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
1199 argument_default=argparse.SUPPRESS,
1200 )
1201 parser.set_defaults(command_function=self)
1202
1203 parser.add_argument(
1204 "device",
1205 type=str,
1206 help=_("device"),
1207 )
1208 parser.add_argument(
1209 "new_value",
1210 nargs="?",
1211 type=str,
1212 help=_("new value"),
1213 )
1214
1215 def __call__(self, proxy, arguments):
1216 # Set bad sector emulation flag
1217 if hasattr(arguments, "new_value"):
1218 try:
1219 enabled = str2bool(arguments.new_value)
1220 except ValueError:
1221 raise CDEmuError(_("String '%s' is not a number") % (arguments[1]))
1222
1223 if arguments.device == "all":
1224 try:
1225 num_devices = proxy.GetNumberOfDevices()
1226 except GLib.Error as e:
1227 raise CDEmuError(_("Failed to get number of devices: %s") % (e))
1228
1229 print(_("Setting bad sector emulation flag of all devices to %i.") % (enabled))
1230 for device in range(num_devices):
1231 try:
1232 proxy.DeviceSetOption(device, "bad-sector-emulation", GLib.Variant("b", enabled))
1233 except GLib.Error as e:
1234 print_warning(
1235 _("Failed to set bad sector emulation flag of device %i to %i: %s") %
1236 (device, enabled, e),
1237 )
1238 continue
1239 else:
1240 try:
1241 device = int(arguments.device, 0)
1242 except ValueError:
1243 raise CDEmuError(_("String '%s' is not a number") % (arguments.device))
1244
1245 print(_("Setting bad sector emulation flag of device %i to %i.") % (device, enabled))
1246 try:
1247 proxy.DeviceSetOption(device, "bad-sector-emulation", GLib.Variant("b", enabled))
1248 except GLib.Error as e:
1249 raise CDEmuError(
1250 _("Failed to set bad sector emulation flag of device %i to %i: %s") %
1251 (device, enabled, e),
1252 )
1253
1254 # Get bad sector emulation flag
1255 else:
1256 # Particular device vs. all devices
1257 if arguments.device == "all":
1258 try:
1259 num_devices = proxy.GetNumberOfDevices()
1260 except GLib.Error as e:
1261 raise CDEmuError(_("Failed to get number of devices: %s") % (e))
1262
1263 print_header(_("Devices' bad sector emulation flag:"))
1264 print("%-5s %-10s" % (_("DEV"), _("ENABLED")))
1265
1266 for device in range(num_devices):
1267 try:
1268 enabled = proxy.DeviceGetOption(device, "bad-sector-emulation")
1269 except GLib.Error as e:
1270 print_warning(_("Failed to get bad sector emulation flag of device %i: %s") % (device, e))
1271 continue
1272
1273 print("%-5s %i" % (device, enabled))
1274 else:
1275 try:
1276 device = int(arguments.device, 0)
1277 enabled = proxy.DeviceGetOption(device, "bad-sector-emulation")
1278 except GLib.Error as e:
1279 raise CDEmuError(_("Failed to get bad sector emulation flag of device %i: %s") % (device, e))
1280 except ValueError:
1281 raise CDEmuError(_("String '%s' is not a number") % (arguments.device))
1282
1283 print(_("Bad sector emulation flag of device %i: %i") % (device, enabled))
1284
1285
1286 ########################################################################
1287 # DVD report CSS #
1288 ########################################################################
1289 class cmd_dvd_report_css:
1290 def __init__(self, subparsers):
1291 name = "dvd-report-css"
1292 description_msg = _("")
1293 help_msg = _("displays/sets DVD report CSS/CPPM flag")
1294
1295 parser = subparsers.add_parser(
1296 name,
1297 description=description_msg,
1298 help=help_msg,
1299 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
1300 argument_default=argparse.SUPPRESS,
1301 )
1302 parser.set_defaults(command_function=self)
1303
1304 parser.add_argument(
1305 "device",
1306 type=str,
1307 help=_("device"),
1308 )
1309 parser.add_argument(
1310 "new_value",
1311 nargs="?",
1312 type=str,
1313 help=_("new value"),
1314 )
1315
1316 def __call__(self, proxy, arguments):
1317 # Set DVD report CSS flag
1318 if hasattr(arguments, "new_value"):
1319 try:
1320 enabled = str2bool(arguments.new_value)
1321 except ValueError:
1322 raise CDEmuError(_("String '%s' is not a number") % (arguments[1]))
1323
1324 if arguments.device == "all":
1325 try:
1326 num_devices = proxy.GetNumberOfDevices()
1327 except GLib.Error as e:
1328 raise CDEmuError(_("Failed to get number of devices: %s") % (e))
1329
1330 print(_("Setting DVD report CSS/CPPM flag of all devices to %i.") % (enabled))
1331 for device in range(num_devices):
1332 try:
1333 proxy.DeviceSetOption(device, "dvd-report-css", GLib.Variant("b", enabled))
1334 except GLib.Error as e:
1335 print_warning(
1336 _("Failed to set DVD report CSS/CPPM flag of device %i to %i: %s") %
1337 (device, enabled, e),
1338 )
1339 continue
1340 else:
1341 try:
1342 device = int(arguments.device, 0)
1343 except ValueError:
1344 raise CDEmuError(_("String '%s' is not a number") % (arguments.device))
1345
1346 print(_("Setting DVD report CSS/CPPM flag of device %i to %i.") % (device, enabled))
1347 try:
1348 proxy.DeviceSetOption(device, "dvd-report-css", GLib.Variant("b", enabled))
1349 except GLib.Error as e:
1350 raise CDEmuError(
1351 _("Failed to set DVD report CSS/CPPM flag of device %i to %i: %s") %
1352 (device, enabled, e),
1353 )
1354
1355 # Get DVD report CSS flag
1356 else:
1357 # Particular device vs. all devices
1358 if arguments.device == "all":
1359 try:
1360 num_devices = proxy.GetNumberOfDevices()
1361 except GLib.Error as e:
1362 raise CDEmuError(_("Failed to get number of devices: %s") % (e))
1363
1364 print_header(_("Devices' DVD report CSS/CPPM flag:"))
1365 print("%-5s %-10s" % (_("DEV"), _("ENABLED")))
1366
1367 for device in range(num_devices):
1368 try:
1369 enabled = proxy.DeviceGetOption(device, "dvd-report-css")
1370 except GLib.Error as e:
1371 print_warning(_("Failed to get DVD report CSS/CPPM flag of device %i: %s") % (device, e))
1372 continue
1373
1374 print("%-5s %i" % (device, enabled))
1375 else:
1376 try:
1377 device = int(arguments.device, 0)
1378 enabled = proxy.DeviceGetOption(device, "dvd-report-css")
1379 except GLib.Error as e:
1380 raise CDEmuError(_("Failed to get DVD report CSS/CPPM flag of device %i: %s") % (device, e))
1381 except ValueError:
1382 raise CDEmuError(_("String '%s' is not a number") % (arguments.device))
1383
1384 print(_("DVD report CSS/CPPM flag of device %i: %i") % (device, enabled))
1385
1386
1387 ########################################################################
1388 # Device ID #
1389 ########################################################################
1390 class cmd_device_id:
1391 def __init__(self, subparsers):
1392 name = "device-id"
1393 description_msg = _("")
1394 help_msg = _("displays/sets device ID")
1395
1396 parser = subparsers.add_parser(
1397 name,
1398 description=description_msg,
1399 help=help_msg,
1400 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
1401 argument_default=argparse.SUPPRESS,
1402 )
1403 parser.set_defaults(command_function=self)
1404
1405 parser.add_argument(
1406 "device",
1407 type=str,
1408 help=_("device"),
1409 )
1410 parser.add_argument(
1411 "new_id",
1412 nargs='*',
1413 type=str,
1414 help=_("new device ID: vendor ID, product ID, revision and vendor-specific string"),
1415 )
1416
1417 def __call__(self, proxy, arguments):
1418 # Set device ID
1419 if hasattr(arguments, "new_id"):
1420 device_id = tuple(arguments.new_id)
1421
1422 if len(device_id) != 4:
1423 raise CDEmuError(_("New device ID must consist of exactly four strings!"))
1424
1425 if arguments.device == "all":
1426 try:
1427 num_devices = proxy.GetNumberOfDevices()
1428 except GLib.Error as e:
1429 raise CDEmuError(_("Failed to get number of devices: %s") % (e))
1430
1431 print(_("Setting device ID of all devices to %s.") % (device_id))
1432 for device in range(num_devices):
1433 try:
1434 proxy.DeviceSetOption(device, "device-id", GLib.Variant("(ssss)", device_id))
1435 except GLib.Error as e:
1436 print_warning(_("Failed to set device ID of device %i to %s: %s") % (device, device_id, e))
1437 continue
1438 else:
1439 try:
1440 device = int(arguments.device, 0)
1441 except ValueError:
1442 raise CDEmuError(_("String '%s' is not a number") % (arguments.device))
1443
1444 print(_("Setting device ID of device %i to %s.") % (device, device_id))
1445 try:
1446 proxy.DeviceSetOption(device, "device-id", GLib.Variant("(ssss)", device_id))
1447 except GLib.Error as e:
1448 raise CDEmuError(_("Failed to set device ID of device %i to %s: %s") % (device, device_id, e))
1449
1450 # Get device ID
1451 else:
1452 # Particular device vs. all devices
1453 if arguments.device == "all":
1454 try:
1455 num_devices = proxy.GetNumberOfDevices()
1456 except GLib.Error as e:
1457 raise CDEmuError(_("Failed to get number of devices: %s") % (e))
1458
1459 print_header(_("Devices' IDs:"))
1460 print("%-5s %s" % (_("DEV"), _("DEVICE ID")))
1461
1462 for device in range(num_devices):
1463 try:
1464 values = proxy.DeviceGetOption(device, "device-id")
1465 device_id = [str(value) for value in values]
1466 except GLib.Error as e:
1467 print_warning(_("Failed to get device ID of device %i: %s") % (device, e))
1468 continue
1469
1470 print("%-5s %s" % (device, device_id))
1471 else:
1472 try:
1473 device = int(arguments.device, 0)
1474 values = proxy.DeviceGetOption(device, "device-id")
1475 device_id = [str(value) for value in values]
1476 except GLib.Error as e:
1477 raise CDEmuError(_("Failed to get device ID of device %i: %s") % (device, e))
1478 except ValueError:
1479 raise CDEmuError(_("String '%s' is not a number") % (arguments.device))
1480
1481 print(_("Device ID of device %i: %s") % (device, device_id))
1482
1483
1484 ########################################################################
1485 # Enumerate parsers #
1486 ########################################################################
1487 class cmd_enum_parsers:
1488 def __init__(self, subparsers):
1489 name = "enum-parsers"
1490 description_msg = _("")
1491 help_msg = _("enumerates supported parsers")
1492
1493 parser = subparsers.add_parser(
1494 name,
1495 description=description_msg,
1496 help=help_msg,
1497 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
1498 argument_default=argparse.SUPPRESS,
1499 )
1500 parser.set_defaults(command_function=self)
1501
1502 def __call__(self, proxy, arguments):
1503 # Display supported parsers
1504 try:
1505 parsers = proxy.EnumSupportedParsers()
1506 except GLib.Error as e:
1507 raise CDEmuError(_("Failed to enumerate supported parsers: %s") % (e))
1508 return False
1509
1510 # Print all parsers
1511 print_header(_("Supported parsers:"))
1512 for info in parsers:
1513 print(" %s: %s" % (info[0], info[1]))
1514 for description, mime_type in info[2]:
1515 print(" %s: %s" % (mime_type, description))
1516
1517
1518 ########################################################################
1519 # Enumerate writers #
1520 ########################################################################
1521 class cmd_enum_writers:
1522 def __init__(self, subparsers):
1523 name = "enum-writers"
1524 description_msg = _("")
1525 help_msg = _("enumerates supported writers")
1526
1527 parser = subparsers.add_parser(
1528 name,
1529 description=description_msg,
1530 help=help_msg,
1531 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
1532 argument_default=argparse.SUPPRESS
1533 )
1534 parser.set_defaults(command_function=self)
1535
1536 def __call__(self, proxy, arguments):
1537 # Display supported writers
1538 try:
1539 writers = proxy.EnumSupportedWriters()
1540 except GLib.Error as e:
1541 raise CDEmuError(_("Failed to enumerate supported writers: %s") % (e))
1542
1543 # Print all writers
1544 print_header(_("Supported writers:"))
1545 for info in writers:
1546 print(" %s: %s" % (info[0], info[1]))
1547
1548
1549 ########################################################################
1550 # Enumerate filter streams #
1551 ########################################################################
1552 class cmd_enum_filter_streams:
1553 def __init__(self, subparsers):
1554 name = "enum-filter-streams"
1555 description_msg = _("")
1556 help_msg = _("enumerates supported filter streams")
1557
1558 parser = subparsers.add_parser(
1559 name,
1560 description=description_msg,
1561 help=help_msg,
1562 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
1563 argument_default=argparse.SUPPRESS,
1564 )
1565 parser.set_defaults(command_function=self)
1566
1567 def __call__(self, proxy, arguments):
1568 # Display supported filter streams
1569 try:
1570 filter_streams = proxy.EnumSupportedFilterStreams()
1571 except GLib.Error as e:
1572 raise CDEmuError(_("Failed to enumerate supported filter streams: %s") % (e))
1573
1574 # Print all filter streams
1575 print_header(_("Supported filter streams:"))
1576 for info in filter_streams:
1577 print(" %s: %s" % (info[0], info[1]))
1578 print(_(" write support: %d") % (info[2]))
1579 for description, mime_type in info[3]:
1580 print(" %s: %s" % (mime_type, description))
1581
1582
1583 ########################################################################
1584 # Enumerate daemon debug masks #
1585 ########################################################################
1586 class cmd_enum_daemon_debug_masks:
1587 def __init__(self, subparsers):
1588 name = "enum-daemon-debug-masks"
1589 description_msg = _("")
1590 help_msg = _("enumerates valid daemon debug masks")
1591
1592 parser = subparsers.add_parser(
1593 name,
1594 description=description_msg,
1595 help=help_msg,
1596 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
1597 argument_default=argparse.SUPPRESS,
1598 )
1599 parser.set_defaults(command_function=self)
1600
1601 def __call__(self, proxy, arguments):
1602 # Print module's debug masks
1603 try:
1604 debug_masks = proxy.EnumDaemonDebugMasks()
1605 except GLib.Error as e:
1606 raise CDEmuError(_("Failed to enumerate supported daemon debug masks: %s") % (e))
1607
1608 print_header(_("Supported daemon debug masks:"))
1609 for debug_mask in debug_masks:
1610 print(" %-25s: 0x%04X" % (debug_mask[0], debug_mask[1]))
1611
1612
1613 ########################################################################
1614 # Enumerate library debug masks #
1615 ########################################################################
1616 class cmd_enum_library_debug_masks:
1617 def __init__(self, subparsers):
1618 name = "enum-library-debug-masks"
1619 description_msg = _("")
1620 help_msg = _("enumerates valid library debug masks")
1621
1622 parser = subparsers.add_parser(
1623 name,
1624 description=description_msg,
1625 help=help_msg,
1626 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
1627 argument_default=argparse.SUPPRESS,
1628 )
1629 parser.set_defaults(command_function=self)
1630
1631 def __call__(self, proxy, arguments):
1632 # Print module's debug masks
1633 try:
1634 debug_masks = proxy.EnumLibraryDebugMasks()
1635 except GLib.Error as e:
1636 raise CDEmuError(_("Failed to enumerate supported library debug masks: %s") % (e))
1637
1638 print_header(_("Supported library debug masks:"))
1639 for debug_mask in debug_masks:
1640 print(" %-25s: 0x%04X" % (debug_mask[0], debug_mask[1]))
1641
1642
1643 ########################################################################
1644 # Enumerate writer parameters #
1645 ########################################################################
1646 class cmd_enum_writer_parameters:
1647 def __init__(self, subparsers):
1648 name = "enum-writer-parameters"
1649 description_msg = _("")
1650 help_msg = _("prints the list of writer's parameters")
1651
1652 parser = subparsers.add_parser(
1653 name,
1654 description=description_msg,
1655 help=help_msg,
1656 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
1657 argument_default=argparse.SUPPRESS,
1658 )
1659 parser.set_defaults(command_function=self)
1660
1661 parser.add_argument("writer", type=str, help=_("writer ID"))
1662
1663 def __call__(self, proxy, arguments):
1664 # Get parameter sheet for the specified writer
1665 try:
1666 parameter_sheet = proxy.EnumWriterParameters(arguments.writer)
1667 except GLib.Error as e:
1668 raise CDEmuError(_("Failed to get parameter sheet for writer: %s") % (e))
1669
1670 # Print the sheet
1671 print_header(_("Writer's parameter sheet:"))
1672
1673 for parameter in parameter_sheet:
1674 print("")
1675 print_header("%s" % (parameter[0]))
1676 print(_(" Name: %s") % (parameter[1]))
1677 print(_(" Description: %s") % (parameter[2]))
1678 print(_(" Type: %s") % (self._parameter_type_name(parameter)))
1679 print(_(" Default value: %s") % (parameter[3]))
1680
1681 for enum_value in parameter[4]:
1682 print(_(" Possible value: %s") % (enum_value))
1683
1684 @staticmethod
1685 def _parameter_type_name(parameter):
1686 if len(parameter[4]):
1687 return _("enum")
1688 elif isinstance(parameter[3], str):
1689 return _("string")
1690 elif isinstance(parameter[3], bool):
1691 return _("boolean")
1692 elif isinstance(parameter[3], int):
1693 return _("integer")
1694 else:
1695 return _("unknown")
1696
1697
1698 ########################################################################
1699 # Version #
1700 ########################################################################
1701 class cmd_version:
1702 def __init__(self, subparsers):
1703 name = "version"
1704 description_msg = "Displays daemon and library version information."
1705 help_msg = _("displays version information")
1706
1707 parser = subparsers.add_parser(
1708 name,
1709 description=description_msg,
1710 help=help_msg,
1711 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
1712 argument_default=argparse.SUPPRESS,
1713 )
1714 parser.set_defaults(command_function=self)
1715
1716 def __call__(self, proxy, arguments):
1717 # Print version information
1718 try:
1719 library_version = proxy.GetLibraryVersion()
1720 except GLib.Error as e:
1721 raise CDEmuError(_("Failed to get library version: %s") % (e))
1722
1723 try:
1724 daemon_version = proxy.GetDaemonVersion()
1725 except GLib.Error as e:
1726 raise CDEmuError(_("Failed to get daemon version: %s") % (e))
1727
1728 print(_("Library version: %s") % (library_version))
1729 print(_("Daemon version: %s") % (daemon_version))
1730
1731
1732 ########################################################################
1733 # Add device #
1734 ########################################################################
1735 class cmd_add_device:
1736 def __init__(self, subparsers):
1737 name = "add-device"
1738 description_msg = _("")
1739 help_msg = _("creates another virtual device")
1740
1741 parser = subparsers.add_parser(
1742 name,
1743 description=description_msg,
1744 help=help_msg,
1745 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
1746 argument_default=argparse.SUPPRESS,
1747 )
1748 parser.set_defaults(command_function=self)
1749
1750 def __call__(self, proxy, arguments):
1751 try:
1752 proxy.AddDevice()
1753 except GLib.Error as e:
1754 raise CDEmuError(_("Failed to add device: %s") % (e))
1755
1756 print(_("Device added successfully."))
1757
1758
1759 ########################################################################
1760 # Remove device #
1761 ########################################################################
1762 class cmd_remove_device:
1763 def __init__(self, subparsers):
1764 name = "remove-device"
1765 description_msg = _("")
1766 help_msg = _("removes the last virtual device")
1767
1768 parser = subparsers.add_parser(
1769 name,
1770 description=description_msg,
1771 help=help_msg,
1772 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
1773 argument_default=argparse.SUPPRESS,
1774 )
1775 parser.set_defaults(command_function=self)
1776
1777 def __call__(self, proxy, arguments):
1778 try:
1779 proxy.RemoveDevice()
1780 except GLib.Error as e:
1781 raise CDEmuError(_("Failed to remove device: %s") % (e))
1782
1783 print(_("Device removed successfully."))
1784
1785
1786 ########################################################################
1787 # Command-line parser #
1788 ########################################################################
1789 class CDEmuCommandLineParser(argparse.ArgumentParser):
1790 def error(self, message):
1791 self.print_usage(sys.stderr)
1792 print_error(message)
1793 sys.exit(2)
1794
1795
1796 class ActionDeviceId(argparse.Action):
1797 def __call__(self, parser, namespace, values, option_string=None):
1798 print("%r %r %r" % (namespace, values, option_string))
1799 setattr(namespace, self.dest, values)
1800
1801
1802 def create_parser():
1803 parser = CDEmuCommandLineParser(
1804 description=_("Command-line CDEmu client."),
1805 formatter_class=argparse.ArgumentDefaultsHelpFormatter,
1806 argument_default=argparse.SUPPRESS,
1807 )
1808 parser.add_argument(
1809 "--bus",
1810 metavar="BUS",
1811 choices=["system", "session"],
1812 help=_("sets D-BUS bus type to use"),
1813 )
1814 parser.add_argument(
1815 "--version",
1816 action="version",
1817 version="%s %s - (C) 2006-%d Rok Mandeljc" % (app_name, app_version, datetime.date.today().year),
1818 )
1819
1820 subparsers = parser.add_subparsers(
1821 title=_("valid commands"),
1822 metavar="command",
1823 help=_("command help"),
1824 )
1825 subparsers.required = True
1826
1827 # Command sub-parsers
1828 cmd_load(subparsers) # Load
1829 cmd_create_blank(subparsers) # Create blank
1830 cmd_unload(subparsers) # Unload
1831 cmd_display_status(subparsers) # Status
1832 cmd_add_device(subparsers) # Add device
1833 cmd_remove_device(subparsers) # Remove device
1834 cmd_device_mapping(subparsers) # Device mapping
1835 cmd_daemon_debug_mask(subparsers) # Daemon debug mask
1836 cmd_library_debug_mask(subparsers) # Library debug mask
1837 cmd_dpm_emulation(subparsers) # DPM emulation
1838 cmd_tr_emulation(subparsers) # TR emulation
1839 cmd_bad_sector_emulation(subparsers) # Bad sector emulation
1840 cmd_dvd_report_css(subparsers) # DVD report CSS/CPPM
1841 cmd_device_id(subparsers) # Device ID
1842 cmd_enum_parsers(subparsers) # Enumerate parsers
1843 cmd_enum_writers(subparsers) # Enumerate writers
1844 cmd_enum_filter_streams(subparsers) # Enumerate filter streams
1845 cmd_enum_daemon_debug_masks(subparsers) # Enumerate daemon debug masks
1846 cmd_enum_library_debug_masks(subparsers) # Enumerate library debug masks
1847 cmd_enum_writer_parameters(subparsers) # Enumerate writer parameters
1848 cmd_version(subparsers) # Version
1849
1850 return parser
1851
1852
1853 ########################################################################
1854 # CDEmuDaemonProxy: Daemon proxy object #
1855 ########################################################################
1856 class CDEmuDaemonProxy:
1857 _name = 'net.sf.cdemu.CDEmuDaemon'
1858 _object_path = '/Daemon'
1859
1860 def __init__(self, bus_type):
1861 try:
1862 if bus_type == "system":
1863 bus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)
1864 elif bus_type == "session":
1865 bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
1866 else:
1867 print_warning(_("Invalid bus parameter '%s', using default!") % (bus_type))
1868 bus = Gio.bus_get_sync(Gio.BusType.SESSION, None) # Use session bus by default
1869
1870 self.proxy = Gio.DBusProxy.new_sync(
1871 bus,
1872 0,
1873 None,
1874 "net.sf.cdemu.CDEmuDaemon",
1875 "/Daemon",
1876 "net.sf.cdemu.CDEmuDaemon",
1877 None,
1878 )
1879 except GLib.Error as e:
1880 raise CDEmuError(_("Failed to connect to CDEmu daemon: %s") % (e))
1881
1882 # Get daemon interface version
1883 try:
1884 interface_version = self.GetDaemonInterfaceVersion2()
1885 except GLib.Error as e:
1886 raise CDEmuError(
1887 _("Failed to acquire daemon interface version (this most likely means your daemon is out-of-date): %s") % # noqa: E501
1888 (e)
1889 )
1890
1891 # Check daemon interface version
1892 if (
1893 # The major version must be exact match...
1894 interface_version[0] != supported_daemon_interface_version[0] or
1895 # ... and the daemon's interface version needs to be greater
1896 # or equal to what is supported by client.
1897 interface_version[1] < supported_daemon_interface_version[1]
1898 ):
1899 raise CDEmuError(
1900 _("CDEmu daemon interface version %i.%i detected, but version %i.%i is required!") %
1901 (
1902 interface_version[0],
1903 interface_version[1],
1904 supported_daemon_interface_version[0],
1905 supported_daemon_interface_version[1],
1906 ),
1907 )
1908
1909 def GetDaemonVersion(self):
1910 return self.proxy.GetDaemonVersion()
1911
1912 def GetLibraryVersion(self):
1913 return self.proxy.GetLibraryVersion()
1914
1915 def GetDaemonInterfaceVersion2(self):
1916 return self.proxy.GetDaemonInterfaceVersion2()
1917
1918 def EnumDaemonDebugMasks(self):
1919 return self.proxy.EnumDaemonDebugMasks()
1920
1921 def EnumLibraryDebugMasks(self):
1922 return self.proxy.EnumLibraryDebugMasks()
1923
1924 def EnumSupportedParsers(self):
1925 return self.proxy.EnumSupportedParsers()
1926
1927 def EnumSupportedWriters(self):
1928 return self.proxy.EnumSupportedWriters()
1929
1930 def EnumSupportedFilterStreams(self):
1931 return self.proxy.EnumSupportedFilterStreams()
1932
1933 def EnumWriterParameters(self, writer_id):
1934 return self.proxy.EnumWriterParameters('(s)', writer_id)
1935
1936 def GetNumberOfDevices(self):
1937 return self.proxy.GetNumberOfDevices()
1938
1939 def DeviceGetMapping(self, device_number):
1940 return self.proxy.DeviceGetMapping('(i)', device_number)
1941
1942 def DeviceGetStatus(self, device_number):
1943 return self.proxy.DeviceGetStatus('(i)', device_number)
1944
1945 def DeviceLoad(self, device_number, filenames, parameters):
1946 return self.proxy.DeviceLoad('(iasa{sv})', device_number, filenames, parameters)
1947
1948 def DeviceCreateBlank(self, device_number, filename, parameters):
1949 return self.proxy.DeviceCreateBlank('(isa{sv})', device_number, filename, parameters)
1950
1951 def DeviceUnload(self, device_number):
1952 return self.proxy.DeviceUnload('(i)', device_number)
1953
1954 def DeviceGetOption(self, device_number, option_name):
1955 return self.proxy.DeviceGetOption('(is)', device_number, option_name)
1956
1957 def DeviceSetOption(self, device_number, option_name, option_value):
1958 return self.proxy.DeviceSetOption('(isv)', device_number, option_name, option_value)
1959
1960 def AddDevice(self):
1961 return self.proxy.AddDevice()
1962
1963 def RemoveDevice(self):
1964 return self.proxy.RemoveDevice()
1965
1966
1967 ########################################################################
1968 # Main #
1969 ########################################################################
1970 def main():
1971 bus_type = "session" # Use session bus as hard-coded default.
1972
1973 # *** Parse config file, if available ***
1974 # Load options; try "~/.cdemu-client" first, followed by "/etc/cdemu-client.conf".
1975 paths = (
1976 os.path.expanduser("~/.cdemu-client"),
1977 "/etc/cdemu-client.conf",
1978 )
1979 for path in paths:
1980 if os.path.exists(path):
1981 break
1982 else:
1983 path = None
1984
1985 if path is not None:
1986 try:
1987 config = configparser.ConfigParser()
1988 config.read(path)
1989
1990 # Read default bus type
1991 if config.has_option("defaults", "bus"):
1992 bus_type = config.get("defaults", "bus")
1993 except configparser.Error as e:
1994 # No harm, just print a warning
1995 print_warning(_("Failed to load configuration from file '%s': %s") % (path, e))
1996
1997 # *** Parse command-line ***
1998 arguments = create_parser().parse_args()
1999
2000 # Do we need to override bus type?
2001 if hasattr(arguments, "bus"):
2002 bus_type = arguments.bus
2003
2004 # *** Connect to daemon ***
2005 proxy = CDEmuDaemonProxy(bus_type)
2006
2007 # *** Execute command ***
2008 arguments.command_function(proxy, arguments)
2009
2010
2011 if __name__ == "__main__":
2012 try:
2013 main()
2014 sys.exit(0)
2015 except CDEmuError as e:
2016 print_error(e)
2017
2018 # Check if we need to report error through zenity-based dialog as well.
2019 if os.environ.get("CDEMU_USE_ZENITY", "0") != "0":
2020 try:
2021 subprocess.run(
2022 ["zenity", "--error", "--title", _("CDEmu client"), "--text", str(e)],
2023 check=True,
2024 stdin=subprocess.DEVNULL,
2025 stdout=subprocess.DEVNULL,
2026 stderr=subprocess.DEVNULL,
2027 )
2028 except Exception:
2029 print_warning(_("Failed to report error via zenity: %s") % (e, ))
2030
2031 sys.exit(-1)