yutani-clipboard.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /* vim: tabstop=4 shiftwidth=4 noexpandtab
  2. * This file is part of ToaruOS and is released under the terms
  3. * of the NCSA / University of Illinois License - see LICENSE.md
  4. * Copyright (C) 2018 K. Lange
  5. *
  6. * yutani-clipboard - Manipulate the Yutani clipboard
  7. *
  8. * Gets and sets clipboard values.
  9. */
  10. #include <stdio.h>
  11. #include <unistd.h>
  12. #include <getopt.h>
  13. #include <toaru/yutani.h>
  14. void show_usage(int argc, char * argv[]) {
  15. printf(
  16. "yutani-clipboard - set and obtain clipboard contents\n"
  17. "\n"
  18. "usage: %s -g\n"
  19. " %s -s TEXT...\n"
  20. " %s -f FILE\n"
  21. "\n"
  22. " -s \033[3mset the clipboard text to argument\033[0m\n"
  23. " -f \033[3mset the clibboard text to file\033[0m\n"
  24. " -g \033[3mprint clipboard contents to stdout\033[0m\n"
  25. " -? \033[3mshow this help text\033[0m\n"
  26. "\n", argv[0], argv[0], argv[0]);
  27. }
  28. yutani_t * yctx;
  29. int set_clipboard_from_file(char * file) {
  30. FILE * f;
  31. f = fopen(file, "r");
  32. if (!f) return 1;
  33. fseek(f, 0, SEEK_END);
  34. size_t size = ftell(f);
  35. fseek(f, 0, SEEK_SET);
  36. char * tmp = malloc(size);
  37. fread(tmp, 1, size, f);
  38. yutani_set_clipboard(yctx, tmp);
  39. free(tmp);
  40. return 0;
  41. }
  42. void get_clipboard(void) {
  43. yutani_special_request(yctx, NULL, YUTANI_SPECIAL_REQUEST_CLIPBOARD);
  44. yutani_msg_t * clipboard = yutani_wait_for(yctx, YUTANI_MSG_CLIPBOARD);
  45. struct yutani_msg_clipboard * cb = (void *)clipboard->data;
  46. if (*cb->content == '\002') {
  47. int size = atoi(&cb->content[2]);
  48. FILE * clipboard = yutani_open_clipboard(yctx);
  49. char * selection_text = malloc(size + 1);
  50. fread(selection_text, 1, size, clipboard);
  51. selection_text[size] = '\0';
  52. fclose(clipboard);
  53. fwrite(selection_text, 1, size, stdout);
  54. } else {
  55. char * selection_text = malloc(cb->size+1);
  56. memcpy(selection_text, cb->content, cb->size);
  57. selection_text[cb->size] = '\0';
  58. fwrite(selection_text, 1, cb->size, stdout);
  59. }
  60. }
  61. int main(int argc, char * argv[]) {
  62. yctx = yutani_init();
  63. if (!yctx) {
  64. fprintf(stderr, "%s: failed to connect to compositor\n", argv[0]);
  65. return 1;
  66. }
  67. int opt;
  68. while ((opt = getopt(argc, argv, "?s:f:g")) != -1) {
  69. switch (opt) {
  70. case 's':
  71. yutani_set_clipboard(yctx, optarg);
  72. return 0;
  73. case 'f':
  74. return set_clipboard_from_file(optarg);
  75. case 'g':
  76. get_clipboard();
  77. return 0;
  78. case '?':
  79. show_usage(argc,argv);
  80. return 1;
  81. }
  82. }
  83. show_usage(argc, argv);
  84. return 1;
  85. }