]> git.lyx.org Git - lyx.git/blob - src/support/linkback/LinkBackServer.m
reduce compiler warnings (deprecated method, uninitialized vars)
[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         NSArray* contents = [fm contentsOfDirectoryAtPath: dir error: nil] ;
98         int idx ;
99
100         NSLog(@"searching for %@ in folder: %@", serverName, dir) ;
101         
102         // working info
103         NSString* cpath ;
104         NSBundle* cbundle ;
105         NSString* cbundleIdentifier ;
106         id supportedServers ;
107
108         // resolve any symlinks, expand tildes.
109         dir = [dir stringByStandardizingPath] ;
110         
111         // find all .app bundles in the directory and test them.
112         idx = (contents) ? [contents count] : 0 ;
113         while((nil==ret) && (--idx >= 0)) {
114                 cpath = [contents objectAtIndex: idx] ;
115                 
116                 if ([[cpath pathExtension] isEqualToString: @"app"]) {
117                         cpath = [dir stringByAppendingPathComponent: cpath] ;
118                         cbundle = [NSBundle bundleWithPath: cpath] ;
119                         cbundleIdentifier = [cbundle bundleIdentifier] ;
120                         
121                         if ([cbundleIdentifier isEqualToString: bundleIdentifier]) {
122                                 supportedServers = [[cbundle infoDictionary] objectForKey: @"LinkBackServer"] ;
123                                 ret= (LinkBackServerIsSupported(serverName, supportedServers)) ? cpath : nil ;
124                         }
125                 }
126         }
127         
128         // if the app was not found, descend into non-app dirs.  only descend 4 levels to avoid taking forever.
129         if ((nil==ret) && (level<4)) {
130                 idx = (contents) ? [contents count] : 0 ;
131                 while((nil==ret) && (--idx >= 0)) {
132                         BOOL isdir ;
133                         
134                         cpath = [contents objectAtIndex: idx] ;
135                         [fm fileExistsAtPath: cpath isDirectory: &isdir] ;
136                         if (isdir && (![[cpath pathExtension] isEqualToString: @"app"])) {
137                                 cpath = [dir stringByAppendingPathComponent: cpath] ;
138                                 ret = FindLinkBackServer(bundleIdentifier, serverName, cpath, level+1) ;
139                         }
140                 }
141         }
142         
143         return ret ;
144 }
145
146 void LinkBackRunAppNotFoundPanel(NSString* appName, NSURL* url)
147 {
148         int result ;
149         
150         // strings for panel
151         NSBundle* b = [NSBundle bundleForClass: [LinkBack class]] ;
152         NSString* title ;
153         NSString* msg ;
154         NSString* ok ;
155         NSString* urlstr ;
156         
157         title = NSLocalizedStringFromTableInBundle(@"_AppNotFoundTitle", @"Localized", b, @"app not found title") ;
158         ok = NSLocalizedStringFromTableInBundle(@"_OK", @"Localized", b, @"ok") ;
159
160         msg = (url) ? NSLocalizedStringFromTableInBundle(@"_AppNotFoundMessageWithURL", @"Localized", b, @"app not found msg") : NSLocalizedStringFromTableInBundle(@"_AppNotFoundMessageNoURL", @"Localized", b, @"app not found msg") ;
161         
162         urlstr = (url) ? NSLocalizedStringFromTableInBundle(@"_GetApplication", @"Localized", b, @"Get application") : nil ;
163
164         title = [NSString stringWithFormat: title, appName] ;
165         
166         result = NSRunCriticalAlertPanel(title, msg, ok, urlstr, nil) ;
167         if (NSAlertAlternateReturn == result) {
168                 [[NSWorkspace sharedWorkspace] openURL: url] ;
169         }
170 }
171
172 + (LinkBackServer*)LinkBackServerWithName:(NSString*)aName inApplication:(NSString*)bundleIdentifier launchIfNeeded:(BOOL)flag fallbackURL:(NSURL*)url appName:(NSString*)appName ;
173 {
174         BOOL connect = YES ;
175         NSString* serverName = MakeLinkBackServerName(bundleIdentifier, aName) ;
176     id ret = nil ;
177         NSTimeInterval tryMark ;
178         
179         // Try to connect
180         ret = [NSConnection rootProxyForConnectionWithRegisteredName: serverName host: nil] ;
181         
182     // if launchIfNeeded, and the connection was not available, try to launch.
183         if((!ret) && (flag)) {
184                 NSString* appPath ;
185                 id linkBackServers ;
186                 
187                 // first, try to find the app with the bundle identifier
188                 appPath = [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier: bundleIdentifier] ;
189                 linkBackServers = [[[NSBundle bundleWithPath: appPath] infoDictionary] objectForKey: @"LinkBackServer"] ; 
190                 appPath = (LinkBackServerIsSupported(aName, linkBackServers)) ? appPath : nil ;
191                 
192                 // if the found app is not supported, we will need to search for the app ourselves.
193                 if (nil==appPath) appPath = FindLinkBackServer(bundleIdentifier, aName, @"/Applications",0);
194                 
195                 if (nil==appPath) appPath = FindLinkBackServer(bundleIdentifier, aName, @"~/Applications",0);
196                 
197                 if (nil==appPath) appPath = FindLinkBackServer(bundleIdentifier, aName, @"/Network/Applications",0);
198                 
199                 // if app path has been found, launch the app.
200                 if (appPath) {
201                         [[NSWorkspace sharedWorkspace] launchApplication: appName] ;
202                 } else {
203                         LinkBackRunAppNotFoundPanel(appName, url) ;
204                         connect = NO ;
205                 }
206         }
207     
208     // if needed, try to connect.  
209         // retry connection for a while if we did not succeed at first.  This gives the app time to launch.
210         if (connect && (nil==ret)) {
211                 tryMark = [NSDate timeIntervalSinceReferenceDate] ;
212                 do {
213                         ret = [NSConnection rootProxyForConnectionWithRegisteredName: serverName host: nil] ;
214                 } while ((!ret) && (([NSDate timeIntervalSinceReferenceDate]-tryMark)<10)) ;
215                 
216         }
217
218         // setup protocol and return
219     if (ret) [ret setProtocolForProxy: @protocol(LinkBackServer)] ;
220     return ret ;
221 }
222
223 - (id)initWithName:(NSString*)aName delegate:(id<LinkBackServerDelegate>)aDel
224 {
225     if (self = [super init]) {
226         name = [aName copy] ;
227         delegate = aDel ;
228         listener = nil ;
229     }
230     
231     return self ;
232 }
233
234 - (void)dealloc
235 {
236     if (listener) [self retract] ;
237     [name release] ;
238     [super dealloc] ;
239 }
240
241 - (BOOL)publish
242 {
243     NSString* serverName = MakeLinkBackServerName([[NSBundle mainBundle] bundleIdentifier], name) ;
244     BOOL ret = YES ;
245     
246     // create listener and connect
247     NSPort* port = [NSPort port] ;
248     listener = [NSConnection connectionWithReceivePort: port sendPort:port] ;
249     [listener setRootObject: self] ;
250     ret = [listener registerName: serverName] ;
251     
252     // if successful, retain connection and add self to list of servers.
253     if (ret) {
254         [listener retain] ;
255         [LinkBackServers setObject: self forKey: name] ;
256     } else listener = nil ; // listener will dealloc on its own. 
257     
258     return ret ;
259 }
260
261 - (void)retract 
262 {
263     if (listener) {
264         [listener invalidate] ;
265         [listener release] ;
266         listener = nil ;
267     }
268     
269     [LinkBackServers removeObjectForKey: name] ;
270 }
271
272 - (LinkBack*)initiateLinkBackFromClient:(LinkBack*)clientLinkBack 
273 {
274     LinkBack* ret = [[LinkBack alloc] initServerWithClient: clientLinkBack delegate: delegate] ;
275     
276     // NOTE: we do not release because LinkBack will release itself when it the link closes. (caj)
277     
278     return ret ; 
279 }
280
281 @end