File: clipboard.c

package info (click to toggle)
multitail 7.1.5-2
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 884 kB
  • sloc: ansic: 14,945; makefile: 119; sh: 28; perl: 25
file content (113 lines) | stat: -rw-r--r-- 2,167 bytes parent folder | download
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
#define _LARGEFILE64_SOURCE
#include <fcntl.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>

#include "mt.h"
#include "error.h"
#include "config.h"
#include "utils.h"
#include "term.h"
#include "ui.h"
#include "clipboard.h"

char *clipboard = "/usr/bin/" CLIPBOARD_NAME;

void send_to_clipboard_binary(char *what)
{
	int fds[2] = { 0 };
	pid_t pid = -1;

	if (pipe(fds) == -1)
		error_exit(TRUE, TRUE, "error creating pipe\n");

	pid = fork();
	if (pid == -1)
		error_exit(TRUE, TRUE, "error forking\n");

	if (pid == 0)
	{
		int loop;

		for(loop=0; loop<1024; loop++)
		{
			if (fds[0] != loop)
				close(loop);
		}

		signal(SIGHUP, SIG_DFL);

		if (dup(fds[0]) == -1)
			error_exit(TRUE, TRUE, "dup() failed\n");

		setsid();
#ifndef __minix
                setpgid(0, 0);
#endif

		if (execl(clipboard, clipboard, NULL) == -1)
			error_exit(TRUE, FALSE, "execl of %s failed\n", clipboard);

		exit(1);
	}

	WRITE(fds[1], what, strlen(what), CLIPBOARD_NAME);

	close(fds[1]);
	close(fds[0]);
}

void send_to_clipboard(buffer *pb)
{
	if (file_exist(clipboard) == -1)
		error_popup("Copy to clipboard", -1, CLIPBOARD_NAME " program not found");
	else if (getenv("DISPLAY") == NULL)
		error_popup("Copy to clipboard", -1, "DISPLAY environment variable not set");
	else
	{
		char *data = NULL;
		int len_out = 0;
		int loop = 0;
		NEWWIN *mywin = create_popup(9, 40);

#ifdef __APPLE__
		win_header(mywin, "Copy buffer to clipboard");
#else
		win_header(mywin, "Copy buffer to X clipboard");
#endif
		mydoupdate();

		for(loop=0; loop<pb -> curpos; loop++)
		{
			int len = 0;

			if ((pb -> be)[loop].Bline == NULL)
				continue;

			len = strlen((pb -> be)[loop].Bline);

			data = (char *)realloc(data, len_out + len + 1);

			memcpy(&data[len_out], (pb -> be)[loop].Bline, len + 1);

			len_out += len;
		}

		send_to_clipboard_binary(data);

		free(data);

		mvwprintw(mywin -> win, 3, 2, "Finished!");
		mvwprintw(mywin -> win, 4, 2, "Press any key to continue...");
		mydoupdate();

		(void)wait_for_keypress(-1, 0, mywin, 0);

		delete_popup(mywin);
	}
}