forked from moicci/pngpaste
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pngcopy.m
135 lines (118 loc) · 2.81 KB
/
pngcopy.m
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
/*
* pngcopy
*/
#import <Foundation/Foundation.h>
#import <Cocoa/Cocoa.h>
#import <unistd.h>
#define APP_NAME "pngcopy"
#define APP_VERSION "0.1.0"
#define STDIN_FILENAME "-"
typedef struct parameters
{
NSString *imageFile;
BOOL wantsVersion;
BOOL wantsUsage;
BOOL wantsStdin;
BOOL malformed;
} Parameters;
void
usage ()
{
fprintf(stderr,
"Usage: %s [OPTIONS] <source.png>\n"
"\t-v\t" "Version" "\n"
"\t-h,-?\t" "This usage" "\n",
APP_NAME);
}
void
fatal (const char *msg)
{
if (msg != NULL) {
fprintf(stderr, "%s: %s\n", APP_NAME, msg);
}
}
void
version ()
{
fprintf(stderr, "%s %s\n", APP_NAME, APP_VERSION);
}
Parameters
parseArguments (int argc, char* const argv[])
{
Parameters params;
params.imageFile = nil;
params.wantsVersion = NO;
params.wantsUsage = NO;
params.wantsStdin = NO;
params.malformed = NO;
int ch;
while ((ch = getopt(argc, argv, "vh?")) != -1) {
switch (ch) {
case 'v':
params.wantsVersion = YES;
return params;
break;
case 'h':
case '?':
params.wantsUsage = YES;
return params;
break;
default:
params.malformed = YES;
return params;
break;
}
}
if (argc < 2) {
params.malformed = YES;
} else if (!strcmp(argv[1], STDIN_FILENAME)) {
params.wantsStdin = YES;
} else {
params.imageFile =
[[NSString alloc] initWithCString:argv[1]
encoding:NSUTF8StringEncoding];
}
return params;
}
int copyToPasteboard(NSData* imageData)
{
if (imageData == nil) {
fatal("Could not read data from file!");
return EXIT_FAILURE;
}
NSImage* image = [[NSImage alloc] initWithData:imageData];
if (image == nil) {
fatal("Could not read image from file!");
return EXIT_FAILURE;
}
NSPasteboard *pasteBoard = [NSPasteboard generalPasteboard];
[pasteBoard clearContents];
NSArray *copiedObjects = [NSArray arrayWithObject:image];
[pasteBoard writeObjects:copiedObjects];
return EXIT_SUCCESS;
}
int
main (int argc, char * const argv[])
{
Parameters params = parseArguments(argc, argv);
if (params.malformed) {
usage();
return EXIT_FAILURE;
} else if (params.wantsUsage) {
usage();
return EXIT_SUCCESS;
} else if (params.wantsVersion) {
version();
return EXIT_SUCCESS;
}
NSData *imageData;
if (params.wantsStdin) {
NSFileHandle *stdin = [NSFileHandle fileHandleWithStandardInput];
imageData = [stdin readDataToEndOfFile];
}
else {
imageData = [NSData dataWithContentsOfFile:params.imageFile];
}
int exitCode = copyToPasteboard(imageData);
return exitCode;
}