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 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
|
/*
GSServicesManager.m
Copyright (C) 1998 Free Software Foundation, Inc.
Author: Richard Frith-Macdonald <richard@brainstorm.co.uk>
Date: Novemeber 1998
This file is part of the GNUstep GUI Library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; see the file COPYING.LIB.
If not, see <http://www.gnu.org/licenses/> or write to the
Free Software Foundation, 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#import "config.h"
#import <Foundation/NSArray.h>
#import <Foundation/NSSet.h>
#import <Foundation/NSException.h>
#import <Foundation/NSData.h>
#import <Foundation/NSDictionary.h>
#import <Foundation/NSNotification.h>
#import <Foundation/NSRunLoop.h>
#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSTimer.h>
#import <Foundation/NSProcessInfo.h>
#import <Foundation/NSFileManager.h>
#import <Foundation/NSConnection.h>
#import <Foundation/NSDistantObject.h>
#import <Foundation/NSMethodSignature.h>
#import <Foundation/NSPathUtilities.h>
#import <Foundation/NSUserDefaults.h>
#import <Foundation/NSSerialization.h>
#import <Foundation/NSPort.h>
#import <Foundation/NSPortNameServer.h>
#import <Foundation/NSTask.h>
#import <Foundation/NSObjCRuntime.h>
#import <Foundation/NSInvocation.h>
#import "AppKit/NSApplication.h"
#import "AppKit/NSPasteboard.h"
#import "AppKit/NSMenu.h"
#import "AppKit/NSPanel.h"
#import "AppKit/NSWindow.h"
#import "AppKit/NSWorkspace.h"
#import "AppKit/NSDocumentController.h"
#import "GNUstepGUI/GSServicesManager.h"
#import "GSGuiPrivate.h"
static GSServicesManager *manager = nil;
/**
* The GSListener class is for talking to other applications.
* It is a proxy with some dangerous methods implemented in a
* harmless manner to reduce the chances of a malicious app
* messing with us. This is responsible for forwarding service
* requests and other communications with the outside world.
*/
@interface GSListener : NSProxy
+ (id) connectionBecameInvalid: (NSNotification*)notification;
+ (GSListener*) listener;
+ (id) servicesProvider;
+ (void) setServicesProvider: (id)anObject;
- (Class) class;
- (void) dealloc;
- (void) release;
- (id) retain;
- (void) activateIgnoringOtherApps: (BOOL)flag;
- (id) self;
@end
static NSConnection *listenerConnection = nil;
static NSMutableArray *listeners = nil;
static GSListener *listener = nil;
static id servicesProvider = nil;
static NSString *providerName = nil;
/**
* Unregisters the service provider registered on the named port.<br />
* Applications should use [NSApplication-setServicesProvider:] with a nil
* argument instead.
*/
void
NSUnregisterServicesProvider(NSString *name)
{
if (listenerConnection != nil)
{
/*
* Ensure there is no previous listener and nothing else using
* the given port name.
*/
[[NSPortNameServer systemDefaultPortNameServer] removePortForName: name];
[[NSNotificationCenter defaultCenter]
removeObserver: [GSListener class]
name: NSConnectionDidDieNotification
object: listenerConnection];
DESTROY(listenerConnection);
}
ASSIGN(servicesProvider, nil);
ASSIGN(providerName, nil);
}
/**
* Registers a services providing object using the specified port name.<br />
* Applications should not need to use this, as they can use the
* [NSApplication-setServicesProvider:] method instead. The NSApplication
* method will use the name of the application rather than an other port name.
*/
void
NSRegisterServicesProvider(id provider, NSString *name)
{
NSPortNameServer *ns;
id namedPort;
if ([name length] == 0)
{
[NSException raise: NSInvalidArgumentException
format: @"NSRegisterServicesProvider() no name provided"];
}
if (provider == nil)
{
[NSException raise: NSInvalidArgumentException
format: @"NSRegisterServicesProvider() no provider"];
}
if (servicesProvider == provider && [providerName isEqual: name])
{
return; // Already registered.
}
ns = [NSPortNameServer systemDefaultPortNameServer];
namedPort = [ns portForName: name];
if (namedPort && [listenerConnection receivePort] == namedPort)
{
[ns removePortForName: name];
namedPort = nil;
}
if (namedPort != nil)
{
[NSException raise: NSInvalidArgumentException
format: @"NSRegisterServicesProvider() %@ already in use",
name];
}
if (listenerConnection != nil)
{
[[NSNotificationCenter defaultCenter]
removeObserver: [GSListener class]
name: NSConnectionDidDieNotification
object: listenerConnection];
DESTROY(listenerConnection);
}
listenerConnection = [[NSConnection alloc]
initWithReceivePort: [NSPort port] sendPort: nil];
[listenerConnection setRootObject: [GSListener listener]];
if ([listenerConnection registerName: name] == NO)
{
DESTROY(listenerConnection);
}
if (listenerConnection != nil)
{
RETAIN(listenerConnection);
[[NSNotificationCenter defaultCenter]
addObserver: [GSListener class]
selector: @selector(connectionBecameInvalid:)
name: NSConnectionDidDieNotification
object: listenerConnection];
}
else
{
[NSException raise: NSGenericException
format: @"unable to register %@", name];
}
ASSIGN(servicesProvider, provider);
ASSIGN(providerName, name);
}
@interface NSNotificationCenter (NSWorkspacePrivate)
- (void) _postLocal: (NSString*)name userInfo: (NSDictionary*)info;
@end
/**
* The GSListener class exists as a proxy to forward messages to
* service provider objects. It implements very few methods and
* those that it does implement are generally designed to defeat
* any attack by a malicious program.
*/
@implementation GSListener
+ (id) connectionBecameInvalid: (NSNotification*)notification
{
NSAssert(listenerConnection==[notification object],
NSInternalInconsistencyException);
[[NSNotificationCenter defaultCenter]
removeObserver: self
name: NSConnectionDidDieNotification
object: listenerConnection];
DESTROY(listenerConnection);
return self;
}
+ (void) initialize
{
static BOOL beenHere = NO;
if (beenHere == NO)
{
beenHere = YES;
listeners = [NSMutableArray new];
}
}
+ (GSListener*) listener
{
if (listener == nil)
{
listener = (id)NSAllocateObject(self, 0, NSDefaultMallocZone());
[listeners addObject: listener];
}
return listener;
}
/**
* Needed to permit use of this class as a notification observer,
* since the notification system caches method implementations for speed.
*/
+ (IMP) methodForSelector: (SEL)aSelector
{
if (aSelector == 0)
[NSException raise: NSInvalidArgumentException
format: @"%@ null selector given", NSStringFromSelector(_cmd)];
return class_getMethodImplementation(GSObjCClass(self), aSelector);
}
+ (id) servicesProvider
{
return servicesProvider;
}
+ (void) setServicesProvider: (id)anObject
{
if (servicesProvider != anObject)
{
NSString *port = [[GSServicesManager manager] port];
if (port == nil)
{
port = [[NSProcessInfo processInfo] processName];
}
NSRegisterServicesProvider(anObject, port);
}
}
- (id) autorelease
{
return self;
}
- (Class) class
{
return 0;
}
- (void) dealloc
{
GSNOSUPERDEALLOC;
}
/**
* Selectively forwards those messages which are thought to be safe,
* and perform any special operations we need for workspace management
* etc.<br />
* The logic in this method <strong>must</strong> match that in
* methodSignatureForSelector:
*/
- (void) forwardInvocation: (NSInvocation*)anInvocation
{
SEL aSel = [anInvocation selector];
NSString *selName = NSStringFromSelector(aSel);
id target = nil;
id delegate;
/*
* We never permit remote processes to call private methods in this
* application.
*/
if ([selName hasPrefix: @"_"] == YES)
{
[NSException raise: NSGenericException
format: @"method name '%@' private in '%@'",
selName, [manager port]];
}
if ([selName hasSuffix: @":userData:error:"] == YES)
{
/*
* The selector matches the correct form for a services request,
* so we send the message to the services provider.
*/
if ([servicesProvider respondsToSelector: aSel] == YES)
{
NSPasteboard *pb;
/*
* Create a local NSPasteboard object for this pasteboard.
* If we try to use the remote NSPasteboard object, we get
* trouble when setting property lists since the remote
* NSPasteboard fails to serialize the local property
* list objects for sending to gpbs.
*/
[anInvocation getArgument: (void*)&pb atIndex: 2];
pb = [NSPasteboard pasteboardWithName: [pb name]];
[anInvocation setArgument: (void*)&pb atIndex: 2];
[anInvocation invokeWithTarget: servicesProvider];
return;
}
[NSException raise: NSGenericException
format: @"service request '%@' not implemented in '%@'",
selName, [manager port]];
}
delegate = [[NSApplication sharedApplication] delegate];
/*
* We assume that messages of the form 'application:...' are all
* safe and do not need to be listed in GSPermittedMessages.
* They can be handled either by the application delegate or by
* the shared GSServicesManager instance.
*/
if ([selName hasPrefix: @"application:"] == YES)
{
if ([delegate respondsToSelector: aSel] == YES)
{
target = delegate;
}
else if ([manager respondsToSelector: aSel] == YES)
{
target = manager;
}
}
if (target == nil)
{
NSArray *messages;
/*
* Unless the message was of a format assumed to be safe,
* we must check it against the GSPermittedMessages array
* to see if the app allows it to be sent from a remote
* process.
*/
messages = [[NSUserDefaults standardUserDefaults] arrayForKey:
@"GSPermittedMessages"];
if (messages != nil && [messages containsObject: selName] == NO)
{
[NSException raise: NSGenericException
format: @"method '%@' not in GSPermittedMessages in '%@'",
selName, [manager port]];
}
if ([delegate respondsToSelector: aSel] == YES)
{
target = delegate;
}
else if ([NSApp respondsToSelector: aSel] == YES)
{
target = NSApp;
}
}
if (target == nil)
{
[NSException raise: NSGenericException
format: @"method '%@' not implemented in '%@'",
selName, [manager port]];
}
else
{
if ([selName isEqualToString: @"terminate:"])
{
NSNotificationCenter *c;
/*
* We handle the terminate: message as a special case, sending
* a power off notification before allowing it to be processed
* as normal.
*/
c = [[NSWorkspace sharedWorkspace] notificationCenter];
[c _postLocal: NSWorkspaceWillPowerOffNotification userInfo: nil];
}
[anInvocation invokeWithTarget: target];
}
}
/**
* Return the appropriate method signature for aSelector, checking
* to see if it's a standard service message or standard application
* message.<br />
* If the message is non-standard, it can be checked against a list
* of messages specified by the GSPermittedMessages user default.<br />
* The logic in this method <strong>must</strong> match that in
* forwardInvocation:
*/
- (NSMethodSignature*) methodSignatureForSelector: (SEL)aSelector
{
NSMethodSignature *sig = nil;
NSString *selName = NSStringFromSelector(aSelector);
id delegate;
if ([selName hasSuffix: @":userData:error:"])
{
return [servicesProvider methodSignatureForSelector: aSelector];
}
delegate = [[NSApplication sharedApplication] delegate];
if ([selName hasPrefix: @"application:"] == YES)
{
if ([delegate respondsToSelector: aSelector] == YES)
{
sig = [delegate methodSignatureForSelector: aSelector];
}
else if ([manager respondsToSelector: aSelector] == YES)
{
sig = [manager methodSignatureForSelector: aSelector];
}
}
if (sig == nil)
{
NSArray *messages;
messages = [[NSUserDefaults standardUserDefaults] arrayForKey:
@"GSPermittedMessages"];
if (messages != nil && [messages containsObject: selName] == NO)
{
return nil;
}
if ([delegate respondsToSelector: aSelector] == YES)
{
sig = [delegate methodSignatureForSelector: aSelector];
}
else if ([NSApp respondsToSelector: aSelector] == YES)
{
sig = [NSApp methodSignatureForSelector: aSelector];
}
}
return sig;
}
- (BOOL) respondsToSelector: (SEL)aSelector
{
if ([self methodSignatureForSelector: aSelector] != nil)
{
return YES;
}
return NO;
}
- (void) release
{
}
- (id) retain
{
return self;
}
- (void) activateIgnoringOtherApps: (BOOL)flag
{
[NSApp activateIgnoringOtherApps: flag];
}
- (id) self
{
return self;
}
@end /* GSListener */
@implementation GSServicesManager
static NSString *servicesName = @".GNUstepServices";
static NSString *disabledName = @".GNUstepDisabled";
/**
* 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.
*/
+ (GSServicesManager*) newWithApplication: (NSApplication*)app
{
NSString *str = nil;
NSArray *paths;
NSString *path = nil;
if (manager != nil)
{
if (manager->_application == nil)
{
manager->_application = app;
}
return RETAIN(manager);
}
manager = [GSServicesManager alloc];
paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
NSUserDomainMask, YES);
if ((paths != nil) && ([paths count] > 0))
{
str = [paths objectAtIndex: 0];
}
/*
* If standard search paths are not set up, try a default location.
*/
if (str == nil)
{
str = [[NSHomeDirectory() stringByAppendingPathComponent:
@"GNUstep"] stringByAppendingPathComponent: @"Library"];
}
str = [str stringByAppendingPathComponent: @"Services"];
path = [str stringByAppendingPathComponent: servicesName];
manager->_servicesPath = [path copy];
path = [str stringByAppendingPathComponent: disabledName];
manager->_disabledPath = [path copy];
/*
* Don't retain application object - that would create a cycle.
*/
manager->_application = app;
manager->_returnInfo = [[NSMutableSet alloc] initWithCapacity: 16];
manager->_combinations = [[NSMutableDictionary alloc] initWithCapacity: 16];
/*
* Check for changes to the services cache every thirty seconds.
*/
manager->_timer =
RETAIN([NSTimer scheduledTimerWithTimeInterval: 30.0
target: manager
selector: @selector(loadServices)
userInfo: nil
repeats: YES]);
[manager loadServices];
return manager;
}
+ (GSServicesManager*) manager
{
if (manager == nil)
{
[self newWithApplication: nil];
}
return manager;
}
- (BOOL) application: (NSApplication*)theApp
openFile: (NSString*)file
{
id del = [NSApp delegate];
BOOL result = NO;
NSError *err = nil;
if ([del respondsToSelector: _cmd])
{
result = [del application: theApp openFile: file];
}
else if ([[NSDocumentController sharedDocumentController]
openDocumentWithContentsOfURL: [NSURL fileURLWithPath: file]
display: YES
error: &err] != nil)
{
[NSApp activateIgnoringOtherApps: YES];
result = YES;
}
else
{
[NSApp presentError: err];
}
return result;
}
- (void) application: (NSApplication*)theApp
openFiles: (NSArray*)files
{
id del = [NSApp delegate];
if ([del respondsToSelector: _cmd])
{
[del application: theApp openFiles: files];
}
else
{
NSString *filePath;
NSEnumerator *en = [files objectEnumerator];
while ((filePath = (NSString *)[en nextObject]) != nil)
{
[self application: theApp openFile: filePath];
}
}
}
- (BOOL) application: (NSApplication*)theApp
openFileWithoutUI: (NSString*)file
{
id del = [NSApp delegate];
BOOL result = NO;
NSError *err = nil;
if ([del respondsToSelector: _cmd])
{
result = [del application: theApp openFileWithoutUI: file];
}
else if ([[NSDocumentController sharedDocumentController]
openDocumentWithContentsOfURL: [NSURL fileURLWithPath: file]
display: NO
error: &err] != nil)
{
result = YES;
}
return result;
}
- (BOOL) application: (NSApplication*)theApp
openTempFile: (NSString*)file
{
BOOL result = [self application: theApp openFile: file];
[[NSFileManager defaultManager] removeFileAtPath: file handler: nil];
return result;
}
- (BOOL) application: (NSApplication*)theApp
openURL: (NSURL*)aURL
{
id del = [NSApp delegate];
BOOL result = NO;
NSError *err = nil;
if ([del respondsToSelector: _cmd])
{
result = [del application: theApp openURL: aURL];
}
else if ([[NSDocumentController sharedDocumentController]
openDocumentWithContentsOfURL: aURL
display: YES
error: &err] != nil)
{
[NSApp activateIgnoringOtherApps: YES];
result = YES;
}
else
{
NSString *s = [aURL absoluteString];
result = [self application: theApp openFile: s];
}
return result;
}
- (BOOL) application: (NSApplication*)theApp
printFile: (NSString*)file
{
id del = [NSApp delegate];
if ([del respondsToSelector: _cmd])
return [del application: theApp printFile: file];
return NO;
}
- (void) dealloc
{
NSString *appName;
appName = [[NSProcessInfo processInfo] processName];
[_timer invalidate];
RELEASE(_timer);
NSUnregisterServicesProvider(appName);
RELEASE(_languages);
RELEASE(_returnInfo);
RELEASE(_combinations);
RELEASE(_title2info);
RELEASE(_menuTitles);
RELEASE(_servicesMenu);
RELEASE(_disabledPath);
RELEASE(_servicesPath);
RELEASE(_disabledStamp);
RELEASE(_servicesStamp);
RELEASE(_allDisabled);
RELEASE(_allServices);
[super dealloc];
}
- (void) doService: (NSMenuItem*)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];
NSResponder *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 (sendType
&& [obj writeSelectionToPasteboard: pb
types: sendTypes] == NO)
{
NSRunAlertPanel(nil,
@"object failed to write to pasteboard",
@"Continue", nil, nil);
}
else if (NSPerformService(title, pb) == YES)
{
if (returnType
&& [obj readSelectionFromPasteboard: pb] == NO)
{
NSRunAlertPanel(nil,
@"object failed to read from pasteboard",
@"Continue", nil, nil);
}
}
return;
}
}
}
}
/**
* Return a dictionary of information about registered filter services.
*/
- (NSArray*) filters
{
return [_allServices objectForKey: @"ByFilter"];
}
- (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 item 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 items.
*/
- (NSString*) item2title: (id<NSMenuItem>)item
{
unsigned pos;
if ([item target] != self)
return nil;
pos = [item tag];
if (pos > [_menuTitles count])
return nil;
return [_menuTitles objectAtIndex: pos];
}
- (void) loadServices
{
NSFileManager *mgr = [NSFileManager defaultManager];
BOOL changed = NO;
if ([mgr fileExistsAtPath: _disabledPath])
{
NSDictionary *attr;
NSDate *mod;
attr = [mgr fileAttributesAtPath: _disabledPath
traverseLink: YES];
mod = [attr objectForKey: NSFileModificationDate];
if (_disabledStamp == nil || [_disabledStamp laterDate: mod] == mod)
{
NSData *data;
id plist = nil;
data = [NSData dataWithContentsOfFile: _disabledPath];
if (data)
{
plist = [NSDeserializer deserializePropertyListFromData: data
mutableContainers: NO];
if (plist)
{
NSMutableSet *s;
changed = YES;
s = (NSMutableSet*)[NSMutableSet setWithArray: plist];
ASSIGN(_allDisabled, s);
}
}
/* Track most recent version of file loaded */
ASSIGN(_disabledStamp, mod);
}
}
if ([mgr fileExistsAtPath: _servicesPath])
{
NSDictionary *attr;
NSDate *mod;
attr = [mgr fileAttributesAtPath: _servicesPath
traverseLink: YES];
mod = [attr objectForKey: NSFileModificationDate];
if (_servicesStamp == nil || [_servicesStamp laterDate: mod] == mod)
{
NSData *data;
id plist = nil;
data = [NSData dataWithContentsOfFile: _servicesPath];
if (data)
{
plist = [NSDeserializer deserializePropertyListFromData: data
mutableContainers: YES];
if (plist)
{
ASSIGN(_allServices, plist);
changed = YES;
}
}
/* Track most recent version of file loaded */
ASSIGN(_servicesStamp, mod);
}
}
if (changed)
{
/* If we have changed the enabled/disabled services,
* or there have been services added/removed
* then we must rebuild the services menu to add/remove
* items as appropriate.
*/
[self rebuildServicesMenu];
}
}
- (NSDictionary*) menuServices
{
if (_allServices == nil)
{
[self loadServices];
}
return _title2info;
}
/**
* Returns the 'port' of this application ... this is the name the
* application is registered under so that other apps can connect to
* it to use any services it provides.
*/
- (NSString*) port
{
return _port;
}
/**
* Makes the current set of usable services consistent with the
* data types currently available.
*/
- (void) rebuildServices
{
NSDictionary *services;
NSMutableArray *newLang;
NSMutableSet *alreadyFound;
NSMutableDictionary *newServices;
unsigned pos;
if (_allServices == nil)
return;
newLang = [[[[NSUserDefaults standardUserDefaults]
stringArrayForKey: @"NSLanguages"] mutableCopy] autorelease];
if (newLang == nil)
{
newLang = [NSMutableArray arrayWithCapacity: 1];
}
if ([newLang containsObject: @"default"] == NO)
{
[newLang addObject: @"default"];
}
ASSIGN(_languages, newLang);
services = [_allServices 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];
/* See if this service item is disabled. */
if ([_allDisabled 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];
}
}
/** Adds or removes items in the services menu in response to a change
* in the services which are available to the app.
*/
- (void) rebuildServicesMenu
{
if (_servicesMenu != nil)
{
NSMutableSet *keyEquivalents;
unsigned pos;
unsigned loc0;
unsigned loc1 = 0;
SEL sel = @selector(doService:);
NSMenu *submenu = nil;
[_servicesMenu setAutoenablesItems: NO];
for (pos = [_servicesMenu numberOfItems]; pos > 0; pos--)
{
[_servicesMenu removeItemAtIndex: 0];
}
[_servicesMenu setAutoenablesItems: YES];
keyEquivalents = [NSMutableSet setWithCapacity: 4];
for (loc0 = pos = 0; pos < [_menuTitles count]; pos++)
{
NSString *title = [_menuTitles objectAtIndex: pos];
NSString *equiv = @"";
NSDictionary *info;
NSDictionary *titles;
NSDictionary *equivs;
NSRange r;
unsigned lang;
id<NSMenuItem> item;
if (NSShowsServicesMenuItem(title) == NO)
{
continue; // We don't want to show this one.
}
/*
* Find the key equivalent corresponding to this menu title
* in the service definition.
*/
info = [_title2info objectForKey: title];
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];
if (equiv == nil)
{
equiv = [equivs objectForKey: @"default"];
}
}
}
/*
* 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: menu
forItem: item];
RELEASE(menu);
}
else
{
menu = (NSMenu*)[item submenu];
}
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 update];
// [submenu sizeToFit];
// [_servicesMenu sizeToFit];
[_servicesMenu update];
}
}
/**
* Set up connection to listen for incoming service requests.
*/
- (void) registerAsServiceProvider
{
NSString *appName;
BOOL registered;
appName = [[NSProcessInfo processInfo] processName];
NS_DURING
{
NSRegisterServicesProvider(self, appName);
registered = YES;
}
NS_HANDLER
{
registered = NO;
}
NS_ENDHANDLER
if (registered == NO)
{
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
if ([defs boolForKey: @"NSUseRunningCopy"] == YES)
{
id app;
/*
* Try to activate the other app and terminate self.
*/
app = [NSConnection rootProxyForConnectionWithRegisteredName: appName
host: @""];
NS_DURING
{
[app activateIgnoringOtherApps: YES];
}
NS_HANDLER
{
/* maybe it terminated. */
}
NS_ENDHANDLER
registered = NO;
}
else
{
unsigned count = 0;
/*
* Try to rename self as a copy.
*/
while (registered == NO && ++count < 100)
{
NSString *tmp;
tmp = [appName stringByAppendingFormat: @"Copy%d", count];
NS_DURING
{
NSRegisterServicesProvider(self, tmp);
registered = YES;
appName = tmp;
}
NS_HANDLER
{
registered = NO;
}
NS_ENDHANDLER
}
if (registered == NO)
{
int result;
/*
* Something is seriously wrong - we can't talk to the
* nameserver, so all interaction with the workspace manager
* and/or other applications will fail.
* Give the user a chance to keep on going anyway.
*/
result = NSRunAlertPanel(appName,
@"Unable to register application with ANY name",
@"Abort", @"Continue", nil);
if (result == NSAlertDefaultReturn)
{
registered = YES;
}
}
}
if (registered == NO)
{
[[NSApplication sharedApplication] terminate: self];
}
}
ASSIGN(_port, 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 associated
* 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)
{
/* Types have changed, so we need to enable/disable items in the
* services menu depending on what types they support.
*/
[self rebuildServices];
}
}
- (NSMenu*) servicesMenu
{
return _servicesMenu;
}
- (id) servicesProvider
{
return [GSListener servicesProvider];
}
- (void) setServicesMenu: (NSMenu*)aMenu
{
ASSIGN(_servicesMenu, aMenu);
[self rebuildServicesMenu];
}
- (void) setServicesProvider: (id)anObject
{
[GSListener setServicesProvider: anObject];
}
- (int) setShowsServicesMenuItem: (NSString*)item to: (BOOL)enable
{
NSData *d;
[self loadServices];
if (_allDisabled == nil)
{
_allDisabled = [[NSMutableSet alloc] initWithCapacity: 1];
}
if (enable)
{
[_allDisabled removeObject: item];
}
else
{
[_allDisabled addObject: item];
}
d = [NSSerializer serializePropertyList: [_allDisabled allObjects]];
if ([d writeToFile: _disabledPath atomically: YES] == YES)
{
return 0;
}
return -1;
}
- (BOOL) showsServicesMenuItem: (NSString*)item
{
[self loadServices];
if ([_allDisabled member: item] == nil)
return YES;
return NO;
}
- (BOOL) validateMenuItem: (id<NSMenuItem>)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];
NSResponder *resp = [[_application keyWindow] firstResponder];
/*
* If the menu item is not in our map, it must be the item containing
* a sub-menu - so we see if any item in the submenu is valid.
*/
if (title == nil)
{
NSMenu *sub;
if (![item isKindOfClass: [NSMenuItem class]])
return NO;
sub = [item submenu];
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 item 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])
{
NSArray *a;
unsigned i;
a = [_servicesMenu itemArray];
for (i = 0; i < [a count]; i++)
{
NSMenuItem *item = [a objectAtIndex: i];
BOOL wasEnabled = [item isEnabled];
BOOL shouldBeEnabled;
NSString *title = [self item2title: item];
/*
* If there is no title mapping, this item must be a
* submenu - so we check the submenu items.
*
* We always enable the submenu item itself. We do this
* to prevent confusion (if the user is trying to use
* a disabled item, it's clearer to show that item disabled
* than to hide it in a disabled submenu), and to encourage
* the user to explore the interface (it makes it possible
* to browse the service list at any time).
*/
if (title == nil && [[item submenu] isKindOfClass: [NSMenu class]])
{
NSArray *sub = [[item submenu] itemArray];
unsigned j;
shouldBeEnabled = YES;
for (j = 0; j < [sub count]; j++)
{
NSMenuItem *subitem = [sub objectAtIndex: j];
BOOL subWasEnabled = [subitem isEnabled];
BOOL subShouldBeEnabled = NO;
if ([self validateMenuItem: subitem] == YES)
{
subShouldBeEnabled = YES;
}
if (subWasEnabled != subShouldBeEnabled)
{
[subitem setEnabled: subShouldBeEnabled];
}
}
}
else
{
shouldBeEnabled = [self validateMenuItem: item];
}
if (wasEnabled != shouldBeEnabled)
{
[item setEnabled: shouldBeEnabled];
}
}
}
}
@end /* GSServicesManager */
/**
* <p>Establishes an NSConnection to the application listening at port
* (by convention usually the application name), launching appName
* if necessary. Returns the proxy to the remote application, or nil
* on failure.
* </p>
* <p>The value of port specifies the name of the distributed objects
* service to which the connection is to be made. If this is nil
* it will be inferred from appName ... by convention, applications
* use their own name (minus any path or extension) for this.
* </p>
* <p>If appName is nil or cannot be launched, this attempts to locate any
* application in a standard location whose name matches port and launch
* that application.
* </p>
* <p>The value of expire provides a timeout in case the application cannot
* be contacted promptly. If it is omitted, a thirty second timeout is
* used.
* </p>
*/
id
GSContactApplication(NSString *appName, NSString *port, NSDate *expire)
{
id app;
if (port == nil)
{
port = [[appName lastPathComponent] stringByDeletingPathExtension];
}
if (expire == nil)
{
expire = [NSDate dateWithTimeIntervalSinceNow: 30.0];
}
if (providerName != nil && [port isEqual: providerName] == YES)
{
app = [GSListener listener]; // Contect our own listener.
}
else
{
NS_DURING
{
app = [NSConnection rootProxyForConnectionWithRegisteredName: port
host: @""];
}
NS_HANDLER
{
return nil; /* Fatal error in DO */
}
NS_ENDHANDLER
}
if (app == nil)
{
if (appName == nil
|| [[NSWorkspace sharedWorkspace] launchApplication: appName] == NO)
{
if (port == nil
|| [[NSWorkspace sharedWorkspace] launchApplication: port] == NO)
{
return nil; /* Unable to launch. */
}
}
NS_DURING
{
app = [NSConnection
rootProxyForConnectionWithRegisteredName: port
host: @""];
while (app == nil && [expire timeIntervalSinceNow] > 0.1)
{
NSRunLoop *loop = [NSRunLoop currentRunLoop];
NSDate *next;
[NSTimer scheduledTimerWithTimeInterval: 0.1
invocation: nil
repeats: NO];
next = [NSDate dateWithTimeIntervalSinceNow: 0.2];
[loop runUntilDate: next];
app = [NSConnection
rootProxyForConnectionWithRegisteredName: port
host: @""];
}
}
NS_HANDLER
{
return nil;
}
NS_ENDHANDLER
}
return app;
}
static NSDictionary *
serviceFromAnyLocalizedTitle(NSString *title)
{
NSDictionary *allServices;
NSEnumerator *e1;
NSDictionary *service;
allServices = [manager menuServices];
if (allServices == nil)
{
return nil;
}
if ([allServices objectForKey: title] != nil)
{
return [allServices objectForKey: title];
}
e1 = [allServices objectEnumerator];
while ((service = [e1 nextObject]) != nil)
{
NSDictionary *menuItems;
NSString *itemName;
NSEnumerator *e2;
menuItems = [service objectForKey: @"NSMenuItem"];
if (menuItems == nil)
{
continue;
}
e2 = [menuItems objectEnumerator];
while ((itemName = [e2 nextObject]) != nil)
{
if ([itemName isEqualToString: title] == YES)
{
return service;
}
}
}
return nil;
}
/**
* <p>Given the name of a serviceItem, and some data in a pasteboard
* this function sends the data to the service provider (launching
* another application if necessary) and retrieves the result of
* the service in the pastebaord.
* </p>
* Returns YES on success, NO otherwise.
*/
BOOL
NSPerformService(NSString *serviceItem, NSPasteboard *pboard)
{
NSDictionary *service;
NSString *port;
NSString *timeout;
double seconds;
NSDate *finishBy;
NSString *appPath;
id provider;
NSString *message;
NSString *selName;
NSString *userData;
NSString *error = nil;
service = serviceFromAnyLocalizedTitle(serviceItem);
if (service == nil)
{
NSRunAlertPanel(nil,
@"No service matching '%@'",
@"Continue", nil, nil,
serviceItem);
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:"];
/*
* Locate the service provider ... this will be a proxy to the remote
* object, or a local object (if we provide the service ourself)
*/
provider = GSContactApplication(appPath, port, finishBy);
if (provider == nil)
{
NSRunAlertPanel(nil,
@"Failed to contact service provider for '%@'",
@"Continue", nil, nil,
serviceItem);
return NO;
}
/*
* If the service provider is a remote object, we can set timeouts on
* the NSConnection so we don't hang waiting for it to reply.
*/
/*
This check for a remote object is ugly. When GSListener is reworked,
this should be improved.
For now, we can't use -isProxy since GSListener is a proxy, and we can't
use -isKindOfClass: since it gets forwarded. Fortunately, -class isn't
forwarded, so that's what we use.
(Note, though, that we can't even use
[provider class] == [GSListener class] since [GSListener -class] returns
NULL instead of the real class.)
*/
if ([provider class] == [NSDistantObject class])
{
NSConnection *connection;
connection = [(NSDistantObject*)provider connectionForProxy];
seconds = [finishBy timeIntervalSinceNow];
[connection setRequestTimeout: seconds];
[connection setReplyTimeout: seconds];
}
/*
* At last, we ask for the service to be performed.
* We create an untyped selector matching the message name we have,
* Using that, we get a method signature from the provider, and
* take the type information from that to make a fully typed
* selector, with which we can create and use an invocation.
*/
NS_DURING
{
SEL sel = NSSelectorFromString(selName);
NSMethodSignature *sig = [provider methodSignatureForSelector: sel];
if (sig != nil)
{
NSInvocation *inv;
NSString **errPtr = &error;
inv = [NSInvocation invocationWithMethodSignature: sig];
[inv setTarget: provider];
[inv setSelector: sel];
[inv setArgument: (void*)&pboard atIndex: 2];
[inv setArgument: (void*)&userData atIndex: 3];
[inv setArgument: (void*)&errPtr atIndex: 4];
[inv invoke];
}
}
NS_HANDLER
{
error = [NSString stringWithFormat: @"%@", [localException reason]];
}
NS_ENDHANDLER
if (error != nil)
{
NSRunAlertPanel(nil,
@"Failed to contact service provider for '%@': %@",
@"Continue", nil, nil,
serviceItem, error);
return NO;
}
return YES;
}
/**
* <p>Controls whether the item name should be included in the services menu.
* </p>
* <p>If enabled is YES then the services menu for each application will
* include the named item, if enabled is NO then the service will not be
* shown in application services menus.
* </p>
* <p>Returns 0 if the setting is successfuly changed. Non-zero otherwise.
* </p>
*/
int
NSSetShowsServicesMenuItem(NSString *name, BOOL enabled)
{
return [[GSServicesManager manager] setShowsServicesMenuItem: name
to: enabled];
}
/**
* Returns a flag indicating whether the named service is supposed to be
* displayed in application services menus.
*/
BOOL
NSShowsServicesMenuItem(NSString *name)
{
return [[GSServicesManager manager] showsServicesMenuItem: name];
}
/**
* A services providing application may use this to update the list of
* services it provides.<br />
* In order to update the services advertised, the application must
* create a <em>.service</em> bundle and place it in
* <code>~/Library/Services</code> before invoking this function.
*/
void
NSUpdateDynamicServices(void)
{
/* Get the workspace manager to make sure that cached service info is
* up to date.
*/
[[NSWorkspace sharedWorkspace] findApplications];
/* Reload service information from disk cache.
*/
[[GSServicesManager manager] loadServices];
}
|