-
Notifications
You must be signed in to change notification settings - Fork 9
/
Clipboard.c
75 lines (66 loc) · 1.56 KB
/
Clipboard.c
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
#include "Prototypes.h"
/*{
struct Clipboard_ {
char clipFileName[128];
bool disk;
char* text;
int len;
};
}*/
Clipboard* Clipboard_new(bool disk) {
Clipboard* this = (Clipboard*) malloc(sizeof(Clipboard));
sprintf(this->clipFileName, "%s/.clipboard", getenv("HOME"));
this->text = NULL;
this->disk = disk;
return this;
}
void Clipboard_delete(Clipboard* this) {
if (this->text)
free(this->text);
free(this);
}
Text Clipboard_get(Clipboard* this) {
if (this->disk) {
FILE* fd = fopen(this->clipFileName, "r");
if (fd) {
int size = 100;
char* out = malloc(size);
int len = 0;
while (!feof(fd)) {
if (size - len < 100) {
size = len + 100;
out = realloc(out, size+1);
}
char* walk = out + len;
int amt = fread(walk, 1, 100, fd);
len += amt;
}
out[len] = '\0';
fclose(fd);
return Text_new(out);
}
this->disk = false;
}
if (this->text) {
return Text_new(strdup(this->text));
}
return Text_null();
}
void Clipboard_set(Clipboard* this, char* text, int len) {
this->len = len;
if (this->disk) {
FILE* fd = fopen(this->clipFileName, "w");
if (fd) {
int pend = len;
while (pend > 0) {
int wrote = fwrite(text + (len - pend), 1, pend, fd);
pend -= wrote;
}
fclose(fd);
free(text);
return;
}
this->disk = false;
}
this->text = text;
}