kview.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <assert.h>
  5. #include <faux/str.h>
  6. #include <faux/list.h>
  7. #include <klish/khelper.h>
  8. #include <klish/kcommand.h>
  9. #include <klish/kview.h>
  10. struct kview_s {
  11. char *name;
  12. faux_list_t *commands;
  13. };
  14. // Simple attributes
  15. KGET_STR(kview, name);
  16. KSET_STR_ONCE(kview, name);
  17. static int kview_command_compare(const void *first, const void *second)
  18. {
  19. const kcommand_t *f = (const kcommand_t *)first;
  20. const kcommand_t *s = (const kcommand_t *)second;
  21. return strcmp(kcommand_name(f), kcommand_name(s));
  22. }
  23. static int kview_command_kcompare(const void *key, const void *list_item)
  24. {
  25. const char *f = (const char *)key;
  26. const kcommand_t *s = (const kcommand_t *)list_item;
  27. return strcmp(f, kcommand_name(s));
  28. }
  29. static kview_t *kview_new_empty(void)
  30. {
  31. kview_t *view = NULL;
  32. view = faux_zmalloc(sizeof(*view));
  33. assert(view);
  34. if (!view)
  35. return NULL;
  36. // Initialize
  37. view->name = NULL;
  38. view->commands = faux_list_new(FAUX_LIST_SORTED, FAUX_LIST_UNIQUE,
  39. kview_command_compare, kview_command_kcompare,
  40. (void (*)(void *))kcommand_free);
  41. assert(view->commands);
  42. return view;
  43. }
  44. kview_t *kview_new(const iview_t *info, kview_error_e *error)
  45. {
  46. kview_t *view = NULL;
  47. view = kview_new_empty();
  48. assert(view);
  49. if (!view)
  50. return NULL;
  51. if (!info)
  52. return view;
  53. if (!kview_parse(view, info, error)) {
  54. kview_free(view);
  55. return NULL;
  56. }
  57. return view;
  58. }
  59. void kview_free(kview_t *view)
  60. {
  61. if (!view)
  62. return;
  63. faux_str_free(view->name);
  64. faux_list_free(view->commands);
  65. faux_free(view);
  66. }
  67. bool_t kview_add_command(kview_t *view, kcommand_t *command)
  68. {
  69. assert(view);
  70. if (!view)
  71. return BOOL_FALSE;
  72. assert(command);
  73. if (!command)
  74. return BOOL_FALSE;
  75. if (!faux_list_add(view->commands, command))
  76. return BOOL_FALSE;
  77. return BOOL_TRUE;
  78. }
  79. bool_t kview_parse(kview_t *view, const iview_t *info, kview_error_e *error)
  80. {
  81. view = view;
  82. info = info;
  83. error = error;
  84. return BOOL_TRUE;
  85. }