]> git.lyx.org Git - lyx.git/blob - src/support/linkback/LinkBackServer.m
tiger support on mac snow leopard, include Qt4 frameworks, smart build script with...
[lyx.git] / src / support / linkback / LinkBackServer.m
1 //
2 //  LinkBackServer.m
3 //  LinkBack
4 //
5 //  Created by Charles Jolley on Tue Jun 15 2004.
6 //  Copyright (c) 2004, Nisus Software, Inc.
7 //  All rights reserved.
8
9 //  Redistribution and use in source and binary forms, with or without 
10 //  modification, are permitted provided that the following conditions are met:
11 //
12 //  Redistributions of source code must retain the above copyright notice, 
13 //  this list of conditions and the following disclaimer.
14 //
15 //  Redistributions in binary form must reproduce the above copyright notice, 
16 //  this list of conditions and the following disclaimer in the documentation 
17 //  and/or other materials provided with the distribution.
18 //
19 //  Neither the name of the Nisus Software, Inc. nor the names of its 
20 //  contributors may be used to endorse or promote products derived from this 
21 //  software without specific prior written permission.
22 //
23 //  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 
24 //  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
25 //  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26 //  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
27 //  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
28 //  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
29 //  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
30 //  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
31 //  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
32 //  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
33 //  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 //
35
36 #import "LinkBackServer.h"
37 #import "LinkBack.h"
38
39 NSString* MakeLinkBackServerName(NSString* bundleIdentifier, NSString* name)
40 {
41     return [bundleIdentifier stringByAppendingFormat: @":%@",name] ;
42 }
43
44 NSMutableDictionary* LinkBackServers = nil ;
45
46 @implementation LinkBackServer
47
48 + (void)initialize
49 {
50     static BOOL inited = NO ;
51     if (inited) return ;
52
53     [super initialize] ; 
54     inited = YES ;
55     
56     if (!LinkBackServers) LinkBackServers = [[NSMutableDictionary alloc] init];
57 }
58
59 + (LinkBackServer*)LinkBackServerWithName:(NSString*)aName  
60 {
61     return [LinkBackServers objectForKey: aName] ;
62 }
63
64 + (BOOL)publishServerWithName:(NSString*)aName delegate:(id<LinkBackServerDelegate>)del 
65 {
66     LinkBackServer* serv = [[LinkBackServer alloc] initWithName: aName delegate: del] ;
67     BOOL ret = [serv publish] ; // retains if successful
68     [serv release] ;
69     return ret ;
70 }
71
72 BOOL LinkBackServerIsSupported(NSString* name, id supportedServers)
73 {
74         BOOL ret = NO ;
75         int idx ;
76         NSString* curServer = supportedServers ;
77         
78         // NOTE: supportedServers may be nil, an NSArray, or NSString.
79         if (supportedServers) {
80                 if ([supportedServers isKindOfClass: [NSArray class]]) {
81                         idx = [supportedServers count] ;
82                         while((NO==ret) && (--idx >= 0)) {
83                                 curServer = [supportedServers objectAtIndex: idx] ;
84                                 ret = [curServer isEqualToString: name] ;
85                         }
86                 } else ret = [curServer isEqualToString: name] ; 
87         }
88         
89         return ret ;
90 }
91
92 NSString* FindLinkBackServer(NSString* bundleIdentifier, NSString* serverName, NSString* dir, int level)
93 {
94         NSString* ret = nil ;
95
96         NSFileManager* fm = [NSFileManager defaultManager] ;
97 #if defined(__GNUC__) && (__GNUC__ == 4 && __GNUC_MINOR__ >= 2)
98         NSArray* contents = [fm contentsOfDirectoryAtPath: dir error: nil] ;
99 #else
100         NSArray* contents = [fm directoryContentsAtPath: dir] ;
101 #endif
102         int idx ;
103
104         NSLog(@"searching for %@ in folder: %@", serverName, dir) ;
105         
106         // working info
107         NSString* cpath ;
108         NSBundle* cbundle ;
109         NSString* cbundleIdentifier ;
110         id supportedServers ;
111
112         // resolve any symlinks, expand tildes.
113         dir = [dir stringByStandardizingPath] ;
114         
115         // find all .app bundles in the directory and test them.
116         idx = (contents) ? [contents count] : 0 ;
117         while((nil==ret) && (--idx >= 0)) {
118                 cpath = [contents objectAtIndex: idx] ;
119                 
120                 if ([[cpath pathExtension] isEqualToString: @"app"]) {
121                         cpath = [dir stringByAppendingPathComponent: cpath] ;
122                         cbundle = [NSBundle bundleWithPath: cpath] ;
123                         cbundleIdentifier = [cbundle bundleIdentifier] ;
124                         
125                         if ([cbundleIdentifier isEqualToString: bundleIdentifier]) {
126                                 supportedServers = [[cbundle infoDictionary] objectForKey: @"LinkBackServer"] ;
127                                 ret= (LinkBackServerIsSupported(serverName, supportedServers)) ? cpath : nil ;
128                         }
129                 }
130         }
131         
132         // if the app was not found, descend into non-app dirs.  only descend 4 levels to avoid taking forever.
133         if ((nil==ret) && (level<4)) {
134                 idx = (contents) ? [contents count] : 0 ;
135                 while((nil==ret) && (--idx >= 0)) {
136                         BOOL isdir ;
137                         
138                         cpath = [contents objectAtIndex: idx] ;
139                         [fm fileExistsAtPath: cpath isDirectory: &isdir] ;
140                         if (isdir && (![[cpath pathExtension] isEqualToString: @"app"])) {
141                                 cpath = [dir stringByAppendingPathComponent: cpath] ;
142                                 ret = FindLinkBackServer(bundleIdentifier, serverName, cpath, level+1) ;
143                         }
144                 }
145         }
146         
147         return ret ;
148 }
149
150 void LinkBackRunAppNotFoundPanel(NSString* appName, NSURL* url)
151 {
152         int result ;
153         
154         // strings for panel
155         NSBundle* b = [NSBundle bundleForClass: [LinkBack class]] ;
156         NSString* title ;
157         NSString* msg ;
158         NSString* ok ;
159         NSString* urlstr ;
160         
161         title = NSLocalizedStringFromTableInBundle(@"_AppNotFoundTitle", @"Localized", b, @"app not found title") ;
162         ok = NSLocalizedStringFromTableInBundle(@"_OK", @"Localized", b, @"ok") ;
163
164         msg = (url) ? NSLocalizedStringFromTableInBundle(@"_AppNotFoundMessageWithURL", @"Localized", b, @"app not found msg") : NSLocalizedStringFromTableInBundle(@"_AppNotFoundMessageNoURL", @"Localized", b, @"app not found msg") ;
165         
166         urlstr = (url) ? NSLocalizedStringFromTableInBundle(@"_GetApplication", @"Localized", b, @"Get application") : nil ;
167
168         title = [NSString stringWithFormat: title, appName] ;
169         
170         result = NSRunCriticalAlertPanel(title, msg, ok, urlstr, nil) ;
171         if (NSAlertAlternateReturn == result) {
172                 [[NSWorkspace sharedWorkspace] openURL: url] ;
173         }
174 }
175
176 + (LinkBackServer*)LinkBackServerWithName:(NSString*)aName inApplication:(NSString*)bundleIdentifier launchIfNeeded:(BOOL)flag fallbackURL:(NSURL*)url appName:(NSString*)appName ;
177 {
178         BOOL connect = YES ;
179         NSString* serverName = MakeLinkBackServerName(bundleIdentifier, aName) ;
180     id ret = nil ;
181         NSTimeInterval tryMark ;
182         
183         // Try to connect
184         ret = [NSConnection rootProxyForConnectionWithRegisteredName: serverName host: nil] ;
185         
186     // if launchIfNeeded, and the connection was not available, try to launch.
187         if((!ret) && (flag)) {
188                 NSString* appPath ;
189                 id linkBackServers ;
190                 
191                 // first, try to find the app with the bundle identifier
192                 appPath = [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier: bundleIdentifier] ;
193                 linkBackServers = [[[NSBundle bundleWithPath: appPath] infoDictionary] objectForKey: @"LinkBackServer"] ; 
194                 appPath = (LinkBackServerIsSupported(aName, linkBackServers)) ? appPath : nil ;
195                 
196                 // if the found app is not supported, we will need to search for the app ourselves.
197                 if (nil==appPath) appPath = FindLinkBackServer(bundleIdentifier, aName, @"/Applications",0);
198                 
199                 if (nil==appPath) appPath = FindLinkBackServer(bundleIdentifier, aName, @"~/Applications",0);
200                 
201                 if (nil==appPath) appPath = FindLinkBackServer(bundleIdentifier, aName, @"/Network/Applications",0);
202                 
203                 // if app path has been found, launch the app.
204                 if (appPath) {
205                         [[NSWorkspace sharedWorkspace] launchApplication: appName] ;
206                 } else {
207                         LinkBackRunAppNotFoundPanel(appName, url) ;
208                         connect = NO ;
209                 }
210         }
211     
212     // if needed, try to connect.  
213         // retry connection for a while if we did not succeed at first.  This gives the app time to launch.
214         if (connect && (nil==ret)) {
215                 tryMark = [NSDate timeIntervalSinceReferenceDate] ;
216                 do {
217                         ret = [NSConnection rootProxyForConnectionWithRegisteredName: serverName host: nil] ;
218                 } while ((!ret) && (([NSDate timeIntervalSinceReferenceDate]-tryMark)<10)) ;
219                 
220         }
221
222         // setup protocol and return
223     if (ret) [ret setProtocolForProxy: @protocol(LinkBackServer)] ;
224     return ret ;
225 }
226
227 - (id)initWithName:(NSString*)aName delegate:(id<LinkBackServerDelegate>)aDel
228 {
229     if (self = [super init]) {
230         name = [aName copy] ;
231         delegate = aDel ;
232         listener = nil ;
233     }
234     
235     return self ;
236 }
237
238 - (void)dealloc
239 {
240     if (listener) [self retract] ;
241     [name release] ;
242     [super dealloc] ;
243 }
244
245 - (BOOL)publish
246 {
247     NSString* serverName = MakeLinkBackServerName([[NSBundle mainBundle] bundleIdentifier], name) ;
248     BOOL ret = YES ;
249     
250     // create listener and connect
251     NSPort* port = [NSPort port] ;
252     listener = [NSConnection connectionWithReceivePort: port sendPort:port] ;
253     [listener setRootObject: self] ;
254     ret = [listener registerName: serverName] ;
255     
256     // if successful, retain connection and add self to list of servers.
257     if (ret) {
258         [listener retain] ;
259         [LinkBackServers setObject: self forKey: name] ;
260     } else listener = nil ; // listener will dealloc on its own. 
261     
262     return ret ;
263 }
264
265 - (void)retract 
266 {
267     if (listener) {
268         [listener invalidate] ;
269         [listener release] ;
270         listener = nil ;
271     }
272     
273     [LinkBackServers removeObjectForKey: name] ;
274 }
275
276 - (LinkBack*)initiateLinkBackFromClient:(LinkBack*)clientLinkBack 
277 {
278     LinkBack* ret = [[LinkBack alloc] initServerWithClient: clientLinkBack delegate: delegate] ;
279     
280     // NOTE: we do not release because LinkBack will release itself when it the link closes. (caj)
281     
282     return ret ; 
283 }
284
285 @end