File: Services.m

package info (click to toggle)
terminal.app 0.9.4+cvs20051125-5
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 460 kB
  • ctags: 106
  • sloc: objc: 6,098; makefile: 42; sh: 13
file content (389 lines) | stat: -rw-r--r-- 9,483 bytes parent folder | download | duplicates (4)
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
/*
copyright 2002 Alexander Malmberg <alexander@malmberg.org>

This file is a part of Terminal.app. Terminal.app is free software; you
can redistribute it and/or modify it under the terms of the GNU General
Public License as published by the Free Software Foundation; version 2
of the License. See COPYING or main.m for more information.
*/

#include <Foundation/NSString.h>
#include <Foundation/NSDebug.h>
#include <Foundation/NSBundle.h>
#include <Foundation/NSDictionary.h>
#include <Foundation/NSUserDefaults.h>
#include <Foundation/NSTask.h>
#include <Foundation/NSData.h>
#include <Foundation/NSPathUtilities.h>
#include <AppKit/NSPasteboard.h>
#include <AppKit/NSWorkspace.h>

#include "Services.h"

#include "ServicesParameterWindowController.h"

#include "TerminalWindow.h"
#include "TerminalView.h"


@implementation TerminalServices


-(NSDictionary *) _serviceInfoForName: (NSString *)name
{
	NSDictionary *d;
	d=[TerminalServices terminalServicesDictionary];
	d=[d objectForKey: name];
	if (!d || ![d isKindOfClass: [NSDictionary class]])
		return nil;
	return d;
}


-(void) terminalService: (NSPasteboard *)pb
	userData: (NSString *)name
	error: (NSString **)error
{
	NSDictionary *info=[self _serviceInfoForName: name];

	int type,input,ret_data,accepttypes;
	NSString *cmdline;
	NSString *data;


	NSDebugLLog(@"service",@"run service %@\n",name);
	if (!info)
	{
		NSString *s=
			_(@"There is no terminal service called '%@'.\n"
			  @"Your services list is probably out-of-date.\n"
			  @"Run 'make_services' to update it.");

		*error=[[NSString stringWithFormat: s, name] retain];
		return;
	}

	type=[[info objectForKey: Type] intValue];
	ret_data=[[info objectForKey: ReturnData] intValue];
	input=[[info objectForKey: Input] intValue];
	cmdline=[info objectForKey: Commandline];
	if ([info objectForKey: AcceptTypes])
		accepttypes=[[info objectForKey: AcceptTypes] intValue];
	else
		accepttypes=ACCEPT_STRING;

	NSDebugLLog(@"service",@"cmdline='%@' %i %i %i %i",
		cmdline,type,ret_data,input,accepttypes);

	data=nil;
	if (input && accepttypes&ACCEPT_STRING &&
	    (data=[pb stringForType: NSStringPboardType]))
	{
	}
	else if (input && accepttypes&ACCEPT_FILENAMES &&
	    (data=[pb propertyListForType: NSFilenamesPboardType]))
	{
		NSDebugLLog(@"service",@"got filenames '%@' '%@' %i",data,[data class],[data isProxy]);
	}

	NSDebugLLog(@"service",@"got data '%@'",data);

	if (input==INPUT_STDIN)
	{
		if ([data isKindOfClass: [NSArray class]])
			data=[(NSArray *)data componentsJoinedByString: @"\n"];
	}
	else if (input==INPUT_CMDLINE)
	{
		if (data && [data isKindOfClass: [NSArray class]])
			data=[(NSArray *)data componentsJoinedByString: @" "];
	}

	{
		int i;
		BOOL add_args;
		NSMutableString *str=[cmdline mutableCopy];
		unichar ch;
		int p_pos;

		add_args=YES;
		p_pos=-1;
		for (i=0;i<[str length]-1;i++)
		{
			ch=[str characterAtIndex: i];
			if (ch!='%')
				continue;
			ch=[str characterAtIndex: i+1];
			if (ch=='%')
			{
				[str replaceCharactersInRange: NSMakeRange(i,1)
					withString: @""];
				continue;
			}
			if (ch=='s' && data && input==2)
			{
				add_args=NO;
				[str replaceCharactersInRange: NSMakeRange(i,2)
					withString: data];
				i+=[data length];
				continue;
			}
			if (ch=='p')
			{
				p_pos=i;
				continue;
			}
		}

		if (input==INPUT_CMDLINE && data && add_args)
		{
			[str appendString: @" "];
			[str appendString: data];
		}
		cmdline=[str autorelease];

		if (p_pos!=-1)
		{
			cmdline=[TerminalServicesParameterWindowController
				getCommandlineFrom: cmdline  selectRange: NSMakeRange(p_pos,2)
				service: name];
			if (!cmdline)
			{
				*error=[_(@"Service aborted by user.") retain];
				return;
			}
		}
	}

	NSDebugLLog(@"service",@"final command line='%@'",cmdline);

	switch (type)
	{
	case TYPE_BACKGROUND:
	{
		NSTask *t=[[[NSTask alloc] init] autorelease];
		NSPipe *sin,*sout;
		NSFileHandle *in,*out;

		[t setLaunchPath: @"/bin/sh"];
		[t setArguments: [NSArray arrayWithObjects: @"-c",cmdline,nil]];

		NSDebugLLog(@"service",@"t=%@",t);

		sin=[[[NSPipe alloc] init] autorelease];
		[t setStandardInput: sin];
		in=[sin fileHandleForWriting];
		sout=[[[NSPipe alloc] init] autorelease];
		[t setStandardOutput: sout];
		out=[sout fileHandleForReading];

		NSDebugLLog(@"service",@"launching");
		[t launch];

		if (data && input==INPUT_STDIN)
		{
			NSDebugLLog(@"service",@"writing data");
			[in writeData: [data dataUsingEncoding: NSUTF8StringEncoding]];
		}
		[in closeFile];

/*		NSDebugLLog(@"service",@"waitUntilExit");
		[t waitUntilExit];*/

		if (ret_data)
		{
			NSString *s;
			NSData *result;
			NSDebugLLog(@"service",@"get result");
			result=[out readDataToEndOfFile];
			NSDebugLLog(@"service",@"got data |%@|",result);
			s=[[NSString alloc] initWithData: result encoding: NSUTF8StringEncoding];
			s=[s autorelease];
			NSDebugLLog(@"service",@"= '%@'",s);

			if (accepttypes==(ACCEPT_STRING|ACCEPT_FILENAMES))
				[pb declareTypes: [NSArray arrayWithObjects:
						NSStringPboardType,NSFilenamesPboardType,nil]
					owner: self];
			else if (accepttypes==ACCEPT_FILENAMES)
				[pb declareTypes: [NSArray arrayWithObjects:
						NSFilenamesPboardType,nil]
					owner: self];
			else if (accepttypes==ACCEPT_STRING)
				[pb declareTypes: [NSArray arrayWithObjects:
						NSStringPboardType,nil]
					owner: self];

			if (accepttypes&ACCEPT_FILENAMES)
			{
				NSMutableArray *ma=[[[NSMutableArray alloc] init] autorelease];
				int i,c=[s length];
				NSRange cur;

				for (i=0;i<c;)
				{
					for (;i<c && [s characterAtIndex: i]<=32;i++) ;
					if (i==c)
						break;
					cur.location=i;
					for (;i<c && [s characterAtIndex: i]>32;i++) ;
					cur.length=i-cur.location;
					[ma addObject: [s substringWithRange: cur]];
				}

				NSDebugLLog(@"service",@"returning filenames: %@",ma);
				[pb setPropertyList: ma forType: NSFilenamesPboardType];
			}

			if (accepttypes&ACCEPT_STRING)
				[pb setString: s  forType: NSStringPboardType];

			NSDebugLLog(@"service",@"return is set");
		}
		else
		{
			NSDebugLLog(@"service",@"ignoring output");
			[out closeFile];
			[t waitUntilExit];
		}

		NSDebugLLog(@"service",@"clean up");
	}
		break;


	case TYPE_WINDOW_IDLE:
	case TYPE_WINDOW_NEW:
	{
		TerminalWindowController *twc=nil;

		if (type==TYPE_WINDOW_IDLE)
			twc=[TerminalWindowController idleTerminalWindow];
		if (!twc)
			twc=[TerminalWindowController newTerminalWindow];

		NSDebugLLog(@"service",@"got window %@",twc);

		[[twc terminalView] runProgram: @"/bin/sh"
			withArguments: [NSArray arrayWithObjects: @"-c",cmdline,nil]
			initialInput: input==INPUT_STDIN?data:nil];
	}
		break;

	}
	NSDebugLLog(@"service",@"return");
}


+(void) updateServicesPlist
{
	NSMutableArray *a;
	NSDictionary *d;
	NSEnumerator *e;
	NSString *name;

	d=[TerminalServices terminalServicesDictionary];

	a=[[NSMutableArray alloc] init];

	e=[d keyEnumerator];
	while ((name=[e nextObject]))
	{
		int i;
		NSString *key;
		NSMutableDictionary *md;
		NSDictionary *info;
		NSArray *types;
		NSString *menu_name;

		info=[d objectForKey: name];

		md=[[NSMutableDictionary alloc] init];
		[md setObject: @"Terminal" forKey: @"NSPortName"];
		[md setObject: @"terminalService" forKey: @"NSMessage"];
		[md setObject: name forKey: @"NSUserData"];

		if ([name characterAtIndex: 0]=='/')
			menu_name=[name substringFromIndex: 1];
		else
			menu_name=[NSString stringWithFormat: @"%@/%@",@"Terminal",name];
		[md setObject: [NSDictionary dictionaryWithObjectsAndKeys:
				menu_name,
				@"default",nil]
			forKey: @"NSMenuItem"];

		key=[info objectForKey: Key];
		if (key && [key length])
		{
			[md setObject: [NSDictionary dictionaryWithObjectsAndKeys:
					key,@"default",nil]
				forKey: @"NSKeyEquivalent"];
		}

		if ([info objectForKey: AcceptTypes])
			i=[[info objectForKey: AcceptTypes] intValue];
		else
			i=ACCEPT_STRING;
		if (i==(ACCEPT_STRING|ACCEPT_FILENAMES))
			types=[NSArray arrayWithObjects: NSStringPboardType,NSFilenamesPboardType,nil];
		else if (i==ACCEPT_FILENAMES)
			types=[NSArray arrayWithObjects: NSFilenamesPboardType,nil];
		else if (i==ACCEPT_STRING)
			types=[NSArray arrayWithObjects: NSStringPboardType,nil];
		else
			types=nil;

		i=[[info objectForKey: Input] intValue];
		if (types && (i==INPUT_STDIN || i==INPUT_CMDLINE))
			[md setObject: types
				forKey: @"NSSendTypes"];

		i=[[info objectForKey: Type] intValue];
		if (i==TYPE_BACKGROUND)
		{
			i=[[info objectForKey: ReturnData] intValue];
			if (types && i==1)
				[md setObject: types
					forKey: @"NSReturnTypes"];
		}

		[a addObject: md];
		DESTROY(md);
	}

	{
		NSString *path;

		path=[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES)
			lastObject];
		path=[path stringByAppendingPathComponent: @"Services"];
		path=[path stringByAppendingPathComponent: @"TerminalServices.plist"];

		d=[NSDictionary dictionaryWithObject: a forKey: @"NSServices"];
		[d writeToFile: path atomically: YES];
	}

	/* TODO: if a submenu of services is 'held' open when services are
	reloaded, -gui crashes */

	[[NSWorkspace sharedWorkspace] findApplications];
}


+(NSDictionary *) terminalServicesDictionary
{
	NSDictionary *d;

	d=[[NSUserDefaults standardUserDefaults]
		dictionaryForKey: @"TerminalServices"];
	if (d) return d;

	d=[NSDictionary dictionaryWithContentsOfFile:
		[[NSBundle mainBundle] pathForResource: @"DefaultTerminalServices"
			ofType: @"svcs"]];
	d=[d objectForKey: @"TerminalServices"];
	return d;
}

@end