Skip to content
This repository
Fetching contributors…

Cannot retrieve contributors at this time

file 310 lines (277 sloc) 9.487 kb
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
//
// HelperFunctions.m
// Vienna
//
// Created by Steve on 8/28/05.
// Copyright (c) 2004-2005 Steve Palmer. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
//

#import "HelperFunctions.h"
#import <SystemConfiguration/SCNetworkReachability.h>
#import <Carbon/Carbon.h>
#import <WebKit/WebKit.h>

// Private functions
static OSStatus RegisterMyHelpBook(void);

/* hasOSScriptsMenu
* Determines whether the OS script menu is present or not.
*/
BOOL hasOSScriptsMenu(void)
{
NSString * pathToUIServerPlist = [@"~/Library/Preferences/com.apple.systemuiserver.plist" stringByExpandingTildeInPath];
NSDictionary * properties = [NSDictionary dictionaryWithContentsOfFile:pathToUIServerPlist];
NSArray * menuExtras = [properties objectForKey:@"menuExtras"];
int index;

for (index = 0; index < [menuExtras count]; ++index)
{
if ([[menuExtras objectAtIndex:index] hasSuffix:@"Script Menu.menu"])
return YES;
}
return NO;
}

/* getDefaultBrowser
* Return the name of the default system browser.
*/
NSString * getDefaultBrowser(void)
{
NSURL * testURL = [NSURL URLWithString:@"http://example.net"];
NSString * registeredAppURL = nil;
CFURLRef appURL = nil;

if (LSGetApplicationForURL((CFURLRef)testURL, kLSRolesAll, NULL, &appURL) != kLSApplicationNotFoundErr)
registeredAppURL = [(NSURL *)appURL path];
if (appURL != nil)
CFRelease(appURL);
return [[registeredAppURL lastPathComponent] stringByDeletingPathExtension];
}

/* menuWithAction
* Returns the first NSMenuItem that matches the one that implements the corresponding
* action in the application main menu. Returns nil if no match is found.
*/
NSMenuItem * menuItemWithAction(SEL theSelector)
{
NSArray * arrayOfMenus = [[NSApp mainMenu] itemArray];
int count = [arrayOfMenus count];
int index;

for (index = 0; index < count; ++index)
{
NSMenu * subMenu = [[arrayOfMenus objectAtIndex:index] submenu];
int itemIndex = [subMenu indexOfItemWithTarget:[NSApp delegate] andAction:theSelector];
if (itemIndex >= 0)
return [subMenu itemAtIndex:itemIndex];
}
return nil;
}

/* menuWithAction
* Returns the first NSMenuItem that matches the one that implements the corresponding
* action in the application main menu. Returns nil if no match is found.
*/
NSMenuItem * menuItemOfMenuWithAction(NSMenu * menu, SEL theSelector)
{
NSArray * arrayOfMenus = [menu itemArray];
int count = [arrayOfMenus count];
int index;

for (index = 0; index < count; ++index)
{
NSMenu * subMenu = [[arrayOfMenus objectAtIndex:index] submenu];
int itemIndex = [subMenu indexOfItemWithTarget:[NSApp delegate] andAction:theSelector];
if (itemIndex >= 0)
return [subMenu itemAtIndex:itemIndex];
}
return nil;
}

/* percentEscape
* Escape invalid and reserved URL characters to make string suitable
* for embedding in mailto: URLs and custom app-specific schemes like papers://
*/
CFStringRef percentEscape(NSString *string)
{
return CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL,

// RFC2368 says all URL reserved characters must be encoded
// these are all the reserved characters from RFC3986
CFSTR("/:?#[]@!$&'()*+,;="),

kCFStringEncodingUTF8);
}

/* cleanedUpAndEscapedUrlFromString
* Uses WebKit to clean up user-entered URLs that might contain umlauts, diacritics and other
* IDNA related stuff in the domain, or God knows what in filenames and arguments.
*/
NSURL * cleanedUpAndEscapedUrlFromString(NSString * theUrl)
{
NSURL *urlToLoad = nil;
NSPasteboard * pasteboard = [NSPasteboard pasteboardWithName:@"ViennaIDNURLPasteboard"];
[pasteboard declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
@try
{
if ([pasteboard setString:theUrl forType:NSStringPboardType])
urlToLoad = [WebView URLFromPasteboard:pasteboard];
}
@catch (NSException * exception)
{
urlToLoad = nil;
{
// TODO: present error message to user?
NSBeep();
NSLog(@"Can't create URL from string '%@'.", theUrl);
}
}

return urlToLoad;
}

/* copyOfMenuItemWithAction
* Returns an NSMenuItem that matches the one that implements the corresponding
* action in the application main menu. Returns nil if no match is found.
*/
NSMenuItem * copyOfMenuItemWithAction(SEL theSelector)
{
NSMenuItem * item = menuItemWithAction(theSelector);
return (item) ? [[[NSMenuItem alloc] initWithTitle:[item title] action:theSelector keyEquivalent:@""] autorelease] : nil;
}

/* menuWithTitleAndAction
* Returns an NSMenuItem with the specified menu and action.
*/
NSMenuItem * menuItemWithTitleAndAction(NSString * theTitle, SEL theSelector)
{
return [[[NSMenuItem alloc] initWithTitle:theTitle action:theSelector keyEquivalent:@""] autorelease];
}

/* loadMapFromPath
* Iterates all files and folders in the specified path and adds them to the given mappings
* dictionary. If foldersOnly is YES, only folders are added. If foldersOnly is NO then only
* files are added.
*/
void loadMapFromPath(NSString * path, NSMutableDictionary * pathMappings, BOOL foldersOnly, NSArray * validExtensions)
{
NSFileManager * fileManager = [NSFileManager defaultManager];
NSArray * arrayOfFiles = [fileManager contentsOfDirectoryAtPath:path error:nil];
if (arrayOfFiles != nil)
{
if (validExtensions)
arrayOfFiles = [arrayOfFiles pathsMatchingExtensions:validExtensions];

for (NSString * fileName in arrayOfFiles)
{
NSString * fullPath = [path stringByAppendingPathComponent:fileName];
BOOL isDirectory;

if ([fileManager fileExistsAtPath:fullPath isDirectory:&isDirectory] && (isDirectory == foldersOnly))
{
if ([fileName isEqualToString:@".DS_Store"])
continue;

[pathMappings setValue:fullPath forKey:[fileName stringByDeletingPathExtension]];
}
}
}
}

/* isAccessible
* Returns whether the specified URL is immediately accessible.
*/
BOOL isAccessible(NSString * urlString)
{
SCNetworkReachabilityRef target;
SCNetworkReachabilityFlags flags = 0;
Boolean ok;

NSURL * url = [NSURL URLWithString:urlString];

target = SCNetworkReachabilityCreateWithName(NULL, [[url host] UTF8String]);
ok = SCNetworkReachabilityGetFlags(target, &flags);
CFRelease(target);

if (!ok)
return NO;
return (flags & kSCNetworkReachabilityFlagsReachable) && !(flags & kSCNetworkReachabilityFlagsConnectionRequired);
}

/* runOKAlertPanel
* Displays an alert panel with just an OK button.
*/
void runOKAlertPanel(NSString * titleString, NSString * bodyText, ...)
{
NSString * fullBodyText;
va_list arguments;

va_start(arguments, bodyText);
fullBodyText = [[NSString alloc] initWithFormat:bodyText arguments:arguments];
// Security: arguments may contain formatting characters, so don't use fullBodyText as format string.
NSRunAlertPanel(titleString, @"%@", NSLocalizedString(@"OK", nil), nil, nil, fullBodyText);
[fullBodyText release];
va_end(arguments);
}

/* runOKAlertSheet
* Displays an alert sheet with just an OK button.
*/
void runOKAlertSheet(NSString * titleString, NSString * bodyText, ...)
{
NSString * fullBodyText;
va_list arguments;

va_start(arguments, bodyText);
fullBodyText = [[NSString alloc] initWithFormat:bodyText arguments:arguments];
// Security: arguments may contain formatting characters, so don't use fullBodyText as format string.
NSBeginAlertSheet(titleString,
NSLocalizedString(@"OK", nil),
nil,
nil,
[NSApp mainWindow],
nil,
nil,
nil, nil,
@"%@",
fullBodyText);
[fullBodyText release];
va_end(arguments);
}

/* RegisterMyHelpBook
* Ensure that the help book is registered before GotoHelpPage can be used.
*/
static OSStatus RegisterMyHelpBook(void)
{
    OSStatus err = noErr;

    CFBundleRef myApplicationBundle = CFBundleGetMainBundle();
if (myApplicationBundle == NULL)
err = fnfErr;
else
{
CFURLRef myBundleURL = CFBundleCopyBundleURL(myApplicationBundle);
if (myBundleURL == NULL)
err = fnfErr;
else
{
FSRef myBundleRef;
if (!CFURLGetFSRef(myBundleURL, &myBundleRef))
err = fnfErr;
if (err == noErr)
err = AHRegisterHelpBook(&myBundleRef);
CFRelease(myBundleURL);
}
}
return err;
}

/* GotoHelpPage
* Displays a specified page of the help file.
*/
OSStatus GotoHelpPage (CFStringRef pagePath, CFStringRef anchorName)
{
    CFBundleRef myApplicationBundle = NULL;
    CFStringRef myBookName = NULL;
    OSStatus err;

err = RegisterMyHelpBook();
if (err != noErr)
return err;
    myApplicationBundle = CFBundleGetMainBundle();
if (myApplicationBundle == NULL)
err = fnfErr;
else
{
myBookName = CFBundleGetValueForInfoDictionaryKey(myApplicationBundle, CFSTR("CFBundleHelpBookName"));
if (myBookName == NULL)
err = fnfErr;
else
{
if (CFGetTypeID(myBookName) != CFStringGetTypeID())
err = paramErr;
}
}
if (err == noErr)
err = AHGotoPage(myBookName, pagePath, anchorName);
return err;
}
Something went wrong with that request. Please try again.