Major revision of services - all menu services stuff in place now.

git-svn-id: svn+ssh://svn.gna.org/svn/gnustep/libs/gui/trunk@3363 72102866-910b-0410-8b05-ffd578937521
This commit is contained in:
richard 1998-12-01 20:54:23 +00:00
parent 4d64c2187a
commit 15cfd849ba
11 changed files with 1434 additions and 861 deletions

1073
Source/GNUServicesManager.m Normal file

File diff suppressed because it is too large Load diff

View file

@ -106,6 +106,7 @@ NSView.m \
NSWindow.m \
NSWorkspace.m \
TrackingRectangle.m \
GNUServicesManager.m \
PSMatrix.m \
tiff.m \
externs.m
@ -199,6 +200,7 @@ AppKit/NSWindow.h \
AppKit/NSWorkspace.h \
AppKit/TrackingRectangle.h \
AppKit/PSMatrix.h \
AppKit/GNUServiceManager.h \
AppKit/nsimage-tiff.h \
-include GNUmakefile.preamble

View file

@ -64,641 +64,7 @@
[a release]; \
a = b;
//*****************************************************************************
//
// ApplicationListener
//
//*****************************************************************************
extern NSDictionary *GSAllServicesDictionary();
/*
* Local class for handling incoming service requests etc.
*/
@interface ApplicationListener : NSObject
{
id servicesProvider;
NSApplication *application;
NSMenu *servicesMenu;
NSMutableArray *languages;
NSMutableSet *returnInfo;
NSMutableDictionary *combinations;
NSMutableDictionary *title2info;
NSArray *menuTitles;
BOOL isRegistered;
}
+ (ApplicationListener*) newWithApplication: (NSApplication*)app;
- (void) doService: (NSCell*)item;
- (BOOL) hasRegisteredTypes: (NSDictionary*)service;
- (NSString*) item2title: (NSCell*)item;
- (void) rebuildServices;
- (void) rebuildServicesMenu;
- (void) registerAsServiceProvider;
- (void) registerSendTypes: (NSArray *)sendTypes
returnTypes: (NSArray *)returnTypes;
- (NSMenu *) servicesMenu;
- (id) servicesProvider;
- (void) setServicesMenu: (NSMenu *)anObject;
- (void) setServicesProvider: (id)anObject;
- (BOOL) validateMenuItem: (NSCell*)item;
- (void) updateServicesMenu;
@end
@implementation ApplicationListener
/*
* Create a new listener for this application.
* Uses NSRegisterServicesProvider() to register itsself as a service
* provider with the applications name so we can handle incoming
* service requests.
*/
+ (ApplicationListener*) newWithApplication: (NSApplication*)app
{
ApplicationListener *listener = [ApplicationListener alloc];
/*
* Don't retain application object - that would reate a cycle.
*/
listener->application = app;
listener->returnInfo = [[NSMutableSet alloc] initWithCapacity: 16];
listener->combinations = [[NSMutableDictionary alloc] initWithCapacity: 16];
return listener;
}
- (void) doService: (NSCell*)item
{
NSString *title = [self item2title: item];
NSDictionary *info = [title2info objectForKey: title];
NSArray *sendTypes = [info objectForKey: @"NSSendTypes"];
NSArray *returnTypes = [info objectForKey: @"NSReturnTypes"];
unsigned i, j;
unsigned es = [sendTypes count];
unsigned er = [returnTypes count];
NSWindow *resp = [[application keyWindow] firstResponder];
id obj = nil;
for (i = 0; i <= es; i++)
{
NSString *sendType;
sendType = (i < es) ? [sendTypes objectAtIndex: i] : nil;
for (j = 0; j <= er; j++)
{
NSString *returnType;
returnType = (j < er) ? [returnTypes objectAtIndex: j] : nil;
obj = [resp validRequestorForSendType: sendType
returnType: returnType];
if (obj != nil)
{
NSPasteboard *pb;
pb = [NSPasteboard pasteboardWithUniqueName];
if ([obj writeSelectionToPasteboard: pb
types: sendTypes] == NO)
{
NSLog(@"object failed to write to pasteboard\n");
}
else if (NSPerformService(title, pb) == NO)
{
NSLog(@"Failed to perform %@\n", title);
}
else if ([obj readSelectionFromPasteboard: pb] == NO)
{
NSLog(@"object failed to read from pasteboard\n");
}
return;
}
}
}
}
- (BOOL) hasRegisteredTypes: (NSDictionary*)service
{
NSArray *sendTypes = [service objectForKey: @"NSSendTypes"];
NSArray *returnTypes = [service objectForKey: @"NSReturnTypes"];
NSString *type;
unsigned i;
/*
* We know that both sendTypes and returnTypes can't be nil since
* make_services has validated the service entry for us.
*/
if (sendTypes == nil || [sendTypes count] == 0)
{
for (i = 0; i < [returnTypes count]; i++)
{
type = [returnTypes objectAtIndex: i];
if ([returnInfo member: type] != nil)
{
return YES;
}
}
}
else if (returnTypes == nil || [returnTypes count] == 0)
{
for (i = 0; i < [sendTypes count]; i++)
{
type = [sendTypes objectAtIndex: i];
if ([combinations objectForKey: type] != nil)
{
return YES;
}
}
}
else
{
for (i = 0; i < [sendTypes count]; i++)
{
NSSet *rset;
type = [sendTypes objectAtIndex: i];
rset = [combinations objectForKey: type];
if (rset != nil)
{
unsigned j;
for (j = 0; j < [returnTypes count]; j++)
{
type = [returnTypes objectAtIndex: j];
if ([rset member: type] != nil)
{
return YES;
}
}
}
}
}
return NO;
}
/*
* Use tag in menu cell to identify slot in menu titles array that
* contains the full title of the service.
* Return nil if this is not one of our service menu cells.
*/
- (NSString*) item2title: (NSCell*)item
{
unsigned pos;
if ([item target] != self)
return nil;
pos = [item tag];
if (pos > [menuTitles count])
return nil;
return [menuTitles objectAtIndex: pos];
}
- (void) dealloc
{
NSRegisterServicesProvider(nil, nil);
[languages release];
[servicesProvider release];
[returnInfo release];
[combinations release];
[title2info release];
[menuTitles release];
[servicesMenu release];
[super dealloc];
}
- forward: (SEL)aSel :(arglist_t)frame
{
NSString *selName = NSStringFromSelector(aSel);
/*
* If the selector matches the correct form for a services request,
* send the message to the services provider - otherwise raise an
* exception to say the method is not implemented.
*/
if ([selName hasSuffix: @":userData:error:"])
return [servicesProvider performv: aSel :frame];
else
return [self notImplemented: aSel];
}
- (void) rebuildServices
{
NSDictionary *services;
NSUserDefaults *defs;
NSMutableArray *newLang;
NSSet *disabled;
NSMutableSet *alreadyFound;
NSMutableDictionary *newServices;
unsigned pos;
/*
* If the application has not yet started up fully and registered us,
* we defer the rebuild intil we are registered. This avoids loads
* of successive rebuilds as responder classes register the types they
* can handle on startup.
*/
if (isRegistered == NO)
return;
defs = [NSUserDefaults standardUserDefaults];
newLang = [[[defs arrayForKey: @"Languages"] mutableCopy] autorelease];
if (newLang == nil)
{
newLang = [NSMutableArray arrayWithCapacity: 1];
}
if ([newLang containsObject: @"default"] == NO)
{
[newLang addObject: @"default"];
}
ASSIGN(languages, newLang);
disabled = [NSSet setWithArray: [defs arrayForKey: @"DisabledServices"]];
services = [GSAllServicesDictionary() objectForKey: @"ByService"];
newServices = [NSMutableDictionary dictionaryWithCapacity: 16];
alreadyFound = [NSMutableSet setWithCapacity: 16];
/*
* Build dictionary of services we can use.
* 1. make sure we make dictionary keyed on preferred menu item language
* 2. don't include entries for services already examined.
* 3. don't include entries for menu items specifically disabled.
* 4. don't include entries for which we have no registered types.
*/
for (pos = 0; pos < [languages count]; pos++)
{
NSDictionary *byLanguage;
byLanguage = [services objectForKey: [languages objectAtIndex: pos]];
if (byLanguage != nil)
{
NSEnumerator *enumerator = [byLanguage keyEnumerator];
NSString *menuItem;
while ((menuItem = [enumerator nextObject]) != nil)
{
NSDictionary *service = [byLanguage objectForKey: menuItem];
if ([alreadyFound member: service] != nil)
continue;
[alreadyFound addObject: service];
if ([disabled member: menuItem] != nil)
continue;
if ([self hasRegisteredTypes: service])
[newServices setObject: service forKey: menuItem];
}
}
}
if ([newServices isEqual: title2info] == NO)
{
NSArray *titles;
ASSIGN(title2info, newServices);
titles = [title2info allKeys];
titles = [titles sortedArrayUsingSelector: @selector(compare:)];
ASSIGN(menuTitles, titles);
[self rebuildServicesMenu];
}
}
- (void) rebuildServicesMenu
{
if (isRegistered && servicesMenu)
{
NSArray *itemArray;
NSMutableSet *keyEquivalents;
unsigned pos;
unsigned loc0;
unsigned loc1;
SEL sel = @selector(doService:);
NSMenu *submenu = nil;
itemArray = [[servicesMenu itemArray] retain];
pos = [itemArray count];
while (pos > 0)
{
[servicesMenu removeItem: [itemArray objectAtIndex: --pos]];
}
[itemArray release];
keyEquivalents = [NSMutableSet setWithCapacity: 4];
for (loc0 = pos = 0; pos < [menuTitles count]; pos++)
{
NSString *title = [menuTitles objectAtIndex: pos];
NSString *equiv = @"";
NSDictionary *info = [title2info objectForKey: title];
NSDictionary *titles;
NSDictionary *equivs;
NSRange r;
unsigned lang;
id<NSMenuItem> item;
/*
* Find the key equivalent corresponding to this menu title
* in the service definition.
*/
titles = [info objectForKey: @"NSMenuItem"];
equivs = [info objectForKey: @"NSKeyEquivalent"];
for (lang = 0; lang < [languages count]; lang++)
{
NSString *language = [languages objectAtIndex: lang];
NSString *t = [titles objectForKey: language];
if ([t isEqual: title])
{
equiv = [equivs objectForKey: language];
}
}
/*
* Make a note that we are using the key equivalent, or
* set to nil if we have already used it in this menu.
*/
if (equiv)
{
if ([keyEquivalents member: equiv] == nil)
{
[keyEquivalents addObject: equiv];
}
else
{
equiv = @"";
}
}
r = [title rangeOfString: @"/"];
if (r.length > 0)
{
NSString *subtitle = [title substringFromIndex: r.location+1];
NSString *parentTitle = [title substringToIndex: r.location];
NSMenu *menu;
item = [servicesMenu itemWithTitle: parentTitle];
if (item == nil)
{
loc1 = 0;
item = [servicesMenu insertItemWithTitle: parentTitle
action: 0
keyEquivalent: @""
atIndex: loc0++];
menu = [[NSMenu alloc] initWithTitle: parentTitle];
[servicesMenu setSubmenu: submenu
forItem: item];
}
else
{
menu = (NSMenu*)[item target];
}
if (menu != submenu)
{
[submenu sizeToFit];
submenu = menu;
}
item = [submenu insertItemWithTitle: subtitle
action: sel
keyEquivalent: equiv
atIndex: loc1++];
[item setTarget: self];
[item setTag: pos];
}
else
{
item = [servicesMenu insertItemWithTitle: title
action: sel
keyEquivalent: equiv
atIndex: loc0++];
[item setTarget: self];
[item setTag: pos];
}
}
[submenu sizeToFit];
[servicesMenu sizeToFit];
[servicesMenu update];
}
}
/*
* Set up connection to listen for incoming service requests.
*/
- (void) registerAsServiceProvider
{
if (isRegistered == NO)
{
NSString *appName;
isRegistered = YES;
[self rebuildServices];
appName = [[[NSProcessInfo processInfo] processName] lastPathComponent];
NSRegisterServicesProvider(self, appName);
}
}
/*
* Register send and return types that an object can handle - we keep
* a note of all the possible combinations -
* 'returnInfo' is a set of all the return types that can be handled
* without a send.
* 'combinations' is a dictionary of all send types, with the assciated
* values being sets of possible return types.
*/
- (void) registerSendTypes: (NSArray *)sendTypes
returnTypes: (NSArray *)returnTypes
{
BOOL didChange = NO;
unsigned i;
for (i = 0; i < [sendTypes count]; i++)
{
NSString *sendType = [sendTypes objectAtIndex: i];
NSMutableSet *returnSet = [combinations objectForKey: sendType];
if (returnSet == nil)
{
returnSet = [NSMutableSet setWithCapacity: [returnTypes count]];
[combinations setObject: returnSet forKey: sendType];
[returnSet addObjectsFromArray: returnTypes];
didChange = YES;
}
else
{
unsigned count = [returnSet count];
[returnSet addObjectsFromArray: returnTypes];
if ([returnSet count] != count)
{
didChange = YES;
}
}
}
i = [returnInfo count];
[returnInfo addObjectsFromArray: returnTypes];
if ([returnInfo count] != i)
{
didChange = YES;
}
if (didChange)
{
[self rebuildServices];
}
}
- (NSMenu*) servicesMenu
{
return servicesMenu;
}
- (id) servicesProvider
{
return servicesProvider;
}
- (void) setServicesMenu: (NSMenu*)aMenu
{
ASSIGN(servicesMenu, aMenu);
[self rebuildServicesMenu];
}
- (void) setServicesProvider: (id)anObject
{
ASSIGN(servicesProvider, anObject);
}
- (BOOL) validateMenuItem: (NSCell*)item
{
NSString *title = [self item2title: item];
NSDictionary *info = [title2info objectForKey: title];
NSArray *sendTypes = [info objectForKey: @"NSSendTypes"];
NSArray *returnTypes = [info objectForKey: @"NSReturnTypes"];
unsigned i, j;
unsigned es = [sendTypes count];
unsigned er = [returnTypes count];
NSWindow *resp = [[application keyWindow] firstResponder];
/*
* If the menu item is not in our map, it must be the cell containing
* a sub-menu - so we see if any cell in the submenu is valid.
*/
if (title == nil)
{
NSMenu *sub = [item target];
if (sub && [sub isKindOfClass: [NSMenu class]])
{
NSArray *a = [sub itemArray];
for (i = 0; i < [a count]; i++)
{
if ([self validateMenuItem: [a objectAtIndex: i]] == YES)
{
return YES;
}
}
}
return NO;
}
/*
* The cell corresponds to one of our services - so we check to see if
* there is anything that can deal with it.
*/
if (es == 0)
{
if (er == 0)
{
if ([resp validRequestorForSendType: nil
returnType: nil] != nil)
return YES;
}
else
{
for (j = 0; j < er; j++)
{
NSString *returnType;
returnType = [returnTypes objectAtIndex: j];
if ([resp validRequestorForSendType: nil
returnType: returnType] != nil)
return YES;
}
}
}
else
{
for (i = 0; i < es; i++)
{
NSString *sendType;
sendType = [sendTypes objectAtIndex: i];
if (er == 0)
{
if ([resp validRequestorForSendType: sendType
returnType: nil] != nil)
return YES;
}
else
{
for (j = 0; j < er; j++)
{
NSString *returnType;
returnType = [returnTypes objectAtIndex: j];
if ([resp validRequestorForSendType: sendType
returnType: returnType] != nil)
return YES;
}
}
}
}
return NO;
}
- (void) updateServicesMenu
{
if (servicesMenu && [[application mainMenu] autoenablesItems])
{
NSMenuMatrix *menuCells;
NSArray *a;
unsigned i;
NSMenu *mainMenu = [application mainMenu];
BOOL found = NO;
a = [mainMenu itemArray];
for (i = 0; i < [a count]; i++)
if ([[a objectAtIndex: i] target] == servicesMenu)
found = YES;
if (found == NO)
{
NSLog(@"Services menu not in main menu!\n");
return;
}
menuCells = [servicesMenu menuCells];
a = [menuCells itemArray];
for (i = 0; i < [a count]; i++)
{
NSCell *cell = [a objectAtIndex: i];
BOOL wasEnabled = [cell isEnabled];
BOOL shouldBeEnabled = [self validateMenuItem: cell];
if (wasEnabled != shouldBeEnabled)
{
[cell setEnabled: shouldBeEnabled];
[menuCells setNeedsDisplayInRect: [menuCells cellFrameAtRow: i]];
}
}
/* FIXME - only doing this here 'cos auto-display doesn't work */
if ([menuCells needsDisplay])
[menuCells display];
}
}
@end /* ApplicationListener */
#include "GNUServicesManager.h"
//*****************************************************************************
//
@ -754,7 +120,7 @@ static id NSApp;
NSDebugLog(@"Begin of NSApplication -init\n");
listener = [ApplicationListener newWithApplication: self];
listener = [GNUServicesManager newWithApplication: self];
window_list = [NSMutableArray new]; // allocate window list
window_count = 1;
@ -1609,7 +975,7 @@ int i;
returnTypes: (NSArray *)returnTypes
{
[listener registerSendTypes: sendTypes
returnTypes: returnTypes];
returnTypes: returnTypes];
}
- (NSMenu *) servicesMenu

View file

@ -738,177 +738,3 @@ NSGetFileTypes(NSArray *pboardTypes)
return nil;
}
extern NSDictionary* GSAllServicesDictionary();
extern NSDictionary* GSApplicationsDictionary();
static NSConnection *listener = nil;
void
NSRegisterServicesProvider(id provider, NSString *name)
{
if (listener)
{
/*
* Ensure there is no previous listener and nothing else using
* the given port name.
*/
[[NSPortNameServer defaultPortNameServer] removePortForName: name];
[listener release];
}
listener = [NSConnection newRegisteringAtName: name
withRootObject: provider];
[listener retain];
}
BOOL
NSPerformService(NSString *serviceItem, NSPasteboard *pboard)
{
NSUserDefaults *defs;
NSArray *languages;
NSDictionary *services;
NSDictionary *byLanguage;
NSDictionary *service;
NSString *port;
unsigned end;
unsigned pos;
NSString *timeout;
double seconds;
NSDate *finishBy;
NSString *appPath;
id provider;
NSConnection *connection;
NSString *message;
NSString *selName;
SEL msgSel;
NSString *userData;
IMP msgImp;
NSString *error = nil;
NSDictionary *allServices;
/*
* Get language preference array.
*/
defs = [NSUserDefaults standardUserDefaults];
languages = [defs arrayForKey: @"Languages"];
/*
* Get dictionary of menu services from workspace manager.
*/
allServices = GSAllServicesDictionary();
services = [allServices objectForKey: @"ByService"];
/*
* Find service information for a service matching the given menu item
* Search in language preference order.
*/
if (languages)
end = [languages count];
else
end = 0;
byLanguage = nil;
for (pos = 0; pos < end; pos++)
{
NSString *language = [languages objectAtIndex: pos];
byLanguage = [services objectForKey: language];
if (byLanguage != nil)
break;
}
if (byLanguage == nil)
byLanguage = [services objectForKey: @"default"];
service = [byLanguage objectForKey: serviceItem];
if (service == nil)
return NO; /* No matching service. */
port = [service objectForKey: @"NSPortName"];
timeout = [service objectForKey: @"NSTimeout"];
if (timeout && [timeout floatValue] > 100)
{
seconds = [timeout floatValue] / 1000.0;
}
else
{
seconds = 30.0;
}
finishBy = [NSDate dateWithTimeIntervalSinceNow: seconds];
appPath = [service objectForKey: @"ServicePath"];
userData = [service objectForKey: @"NSUserData"];
message = [service objectForKey: @"NSMessage"];
selName = [message stringByAppendingString: @":userData:error:"];
msgSel = NSSelectorFromString(selName);
/*
* If there is no selector - we need to generate one with the
* appropriate types.
*/
if (msgSel == 0)
{
NSMethodSignature *sig;
const char *name;
const char *type;
sig = [NSMethodSignature signatureWithObjCTypes: "v@:@@^@"];
type = [sig methodType];
name = [selName cString];
msgSel = sel_register_typed_name(name, type);
}
provider = [NSConnection rootProxyForConnectionWithRegisteredName: port
host: @""];
if (provider == nil)
{
if ([[NSWorkspace sharedWorkspace] launchApplication: appPath] == NO)
{
return NO; /* Unable to launch. */
}
provider = [NSConnection rootProxyForConnectionWithRegisteredName: port
host: @""];
while (provider == nil && [finishBy timeIntervalSinceNow] > 1.0)
{
NSRunLoop *loop = [NSRunLoop currentRunLoop];
NSDate *next;
[NSTimer scheduledTimerWithTimeInterval: 1.0
invocation: nil
repeats: NO];
next = [NSDate dateWithTimeIntervalSinceNow: 5.0];
[loop runUntilDate: next];
provider = [NSConnection
rootProxyForConnectionWithRegisteredName: port
host: @""];
}
}
if (provider == nil)
{
return NO; /* Unable to contact. */
}
connection = [(NSDistantObject*)provider connectionForProxy];
seconds = [finishBy timeIntervalSinceNow];
[connection setRequestTimeout: seconds];
[connection setReplyTimeout: seconds];
msgImp = get_imp(fastClass(provider), msgSel);
NS_DURING
{
(*msgImp)(provider, msgSel, pboard, userData, &error);
}
NS_HANDLER
{
[NSException raise: NSPasteboardCommunicationException
format: @"%s", [[localException reason] cString]];
}
NS_ENDHANDLER
if (error != nil)
{
NSLog(error);
return NO;
}
return YES;
}

View file

@ -39,18 +39,10 @@
#define stringify_it(X) #X
#define prog_path(X,Y) \
stringify_it(X) "/Tools/" GNUSTEP_TARGET_DIR "/" LIBRARY_COMBO Y
stringify_it(X) "/Tools/" GNUSTEP_TARGET_DIR "/" LIBRARY_COMBO
static NSDictionary *allServices = nil;
static NSDictionary *applications = nil;
NSDictionary*
GSAllServicesDictionary()
{
if (allServices == nil)
[[NSWorkspace sharedWorkspace] findApplications];
return allServices;
}
NSDictionary*
GSApplicationsDictionary()
@ -60,20 +52,14 @@ GSApplicationsDictionary()
return applications;
}
void
NSUpdateDynamicServices()
{
[[NSWorkspace sharedWorkspace] findApplications];
}
@implementation NSWorkspace
static NSWorkspace *sharedWorkspace = nil;
static NSNotificationCenter *workspaceCenter = nil;
static BOOL userDefaultsChanged = NO;
static NSString *cacheName = @".GNUstepServices";
static NSString *servicesPath = nil;
static NSString *appListName = @".GNUstepAppList";
static NSString *appListPath = nil;
static NSString* gnustep_target_dir =
#ifdef GNUSTEP_TARGET_DIR
@ -130,9 +116,10 @@ static NSString* library_combo =
str = [env objectForKey: @"GNUSTEP_USER_ROOT"];
if (str == nil)
str = [NSString stringWithFormat: @"%@/GNUstep", NSHomeDirectory()];
str = [str stringByAppendingPathComponent: cacheName];
servicesPath = [str retain];
str = [NSString stringWithFormat: @"%@/GNUstep/Services",
NSHomeDirectory()];
str = [str stringByAppendingPathComponent: appListName];
appListPath = [str retain];
if ((str = [env objectForKey: @"GNUSTEP_TARGET_DIR"]) != nil)
gnustep_target_dir = [str retain];
@ -258,7 +245,7 @@ inFileViewerRootedAtPath:(NSString *)rootFullpath
NSString *last = [appName lastPathComponent];
if (applications == nil)
NSUpdateDynamicServices();
[self findApplications];
if ([appName isEqual: last])
{
@ -322,21 +309,18 @@ inFileViewerRootedAtPath:(NSString *)rootFullpath
- (void)findApplications
{
NSData *data;
NSDictionary *newServices;
NSDictionary *dict;
NSDictionary *newApps;
system(prog_path(GNUSTEP_INSTALL_PREFIX, "/make_services"));
data = [NSData dataWithContentsOfFile: servicesPath];
data = [NSData dataWithContentsOfFile: appListPath];
if (data)
newServices = [NSDeserializer deserializePropertyListFromData: data
mutableContainers: NO];
newApps = [NSDeserializer deserializePropertyListFromData: data
mutableContainers: NO];
else
newServices = [NSDictionary dictionary];
newApps = [NSDictionary dictionary];
ASSIGN(allServices, newServices);
dict = [newServices objectForKey: @"Applications"];
ASSIGN(applications, dict);
ASSIGN(applications, newApps);
}
//