Revision: 6481
          http://skim-app.svn.sourceforge.net/skim-app/?rev=6481&view=rev
Author:   hofman
Date:     2010-04-22 14:45:10 +0000 (Thu, 22 Apr 2010)

Log Message:
-----------
Add optional script menu to main menu, but only when an app support Scripts 
folder exists. Uses FSEvent to track changes to the Scripts folders.

Modified Paths:
--------------
    trunk/SKApplicationController.m
    trunk/Skim.xcodeproj/project.pbxproj

Added Paths:
-----------
    trunk/Images/ScriptMenu.tiff
    trunk/SKScriptMenu.h
    trunk/SKScriptMenu.m

Added: trunk/Images/ScriptMenu.tiff
===================================================================
(Binary files differ)


Property changes on: trunk/Images/ScriptMenu.tiff
___________________________________________________________________
Added: svn:mime-type
   + application/octet-stream

Modified: trunk/SKApplicationController.m
===================================================================
--- trunk/SKApplicationController.m     2010-04-22 08:57:36 UTC (rev 6480)
+++ trunk/SKApplicationController.m     2010-04-22 14:45:10 UTC (rev 6481)
@@ -75,6 +75,7 @@
 #import "NSMenu_SKExtensions.h"
 #import "SKFDFParser.h"
 #import "SKLocalization.h"
+#import "SKScriptMenu.h"
 
 #define WEBSITE_URL @"http://skim-app.sourceforge.net/";
 #define WIKI_URL    @"http://sourceforge.net/apps/mediawiki/skim-app/";
@@ -145,6 +146,8 @@
     
     [[[NSApp mainMenu] itemAtIndex:BOOKMARKS_MENU_INDEX] 
setRepresentedObject:[[SKBookmarkController sharedBookmarkController] 
bookmarkRoot]];
     
+    [SKScriptMenu setupScriptMenu];
+    
     [[NSColorPanel sharedColorPanel] setShowsAlpha:YES];
 }
 

Added: trunk/SKScriptMenu.h
===================================================================
--- trunk/SKScriptMenu.h                                (rev 0)
+++ trunk/SKScriptMenu.h        2010-04-22 14:45:10 UTC (rev 6481)
@@ -0,0 +1,47 @@
+//
+//  SKScriptMenu.h
+//  Skim
+//
+//  Created by Christiaan on 4/22/10.
+/*
+ This software is Copyright (c) 2010
+ Christiaan Hofman. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ - Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+
+ - Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in
+    the documentation and/or other materials provided with the
+    distribution.
+
+ - Neither the name of Christiaan Hofman nor the names of any
+    contributors may be used to endorse or promote products derived
+    from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import <Cocoa/Cocoa.h>
+
+
+...@interface SKScriptMenu : NSMenu <NSMenuDelegate> {
+    FSEventStreamRef streamRef;
+    NSArray *sortDescriptors;
+}
++ (void)setupScriptMenu;
+...@end

Added: trunk/SKScriptMenu.m
===================================================================
--- trunk/SKScriptMenu.m                                (rev 0)
+++ trunk/SKScriptMenu.m        2010-04-22 14:45:10 UTC (rev 6481)
@@ -0,0 +1,253 @@
+//
+//  SKScriptMenu.m
+//  Skim
+//
+//  Created by Christiaan on 4/22/10.
+/*
+ This software is Copyright (c) 2010
+ Christiaan Hofman. All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ - Redistributions of source code must retain the above copyright
+   notice, this list of conditions and the following disclaimer.
+
+ - Redistributions in binary form must reproduce the above copyright
+    notice, this list of conditions and the following disclaimer in
+    the documentation and/or other materials provided with the
+    distribution.
+
+ - Neither the name of Christiaan Hofman nor the names of any
+    contributors may be used to endorse or promote products derived
+    from this software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import "SKScriptMenu.h"
+#import "NSFileManager_SKExtensions.h"
+#import "NSMenu_SKExtensions.h"
+
+#define SCRIPTS_MENU_TITLE  @"Scripts"
+#define SCRIPTS_FOLDER_NAME @"Scripts"
+#define FILENAME_KEY        @"filename"
+#define CONTENT_KEY         @"content"
+
+...@interface SKScriptMenu (Private)
+- (id)initWithPaths:(NSArray *)scriptFolders;
+- (void)handleApplicationWillTerminateNotification:(NSNotification 
*)notification;
+- (NSArray *)directoryContentsAtPath:(NSString *)path 
recursionDepth:(NSInteger)depth;
+- (void)executeScript:(id)sender;
+...@end
+
+...@implementation SKScriptMenu
+
+static SKScriptMenu *sharedMenu = nil;
+static menuNeedsUpdate = NO;
+
++ (void)setupScriptMenu {
+    if (sharedMenu)
+        return;
+    
+    NSInteger itemIndex = [[NSApp mainMenu] numberOfItems] - 1;
+    if (itemIndex <= 0)
+        return;
+    
+    NSFileManager *fm = [NSFileManager defaultManager];
+    NSMutableArray *scriptFolders = [NSMutableArray array];
+    BOOL isDir;
+    
+    for (NSString *folder in [fm applicationSupportDirectories]) {
+        folder = [folder stringByAppendingPathComponent:SCRIPTS_FOLDER_NAME];
+        if ([fm fileExistsAtPath:folder isDirectory:&isDir] && isDir)
+            [scriptFolders addObject:folder];
+    }
+    
+    if ([scriptFolders count] == 0)
+        return;
+    
+    sharedMenu = [[self alloc] initWithPaths:scriptFolders];
+    NSMenuItem *menuItem = [[NSMenuItem allocWithZone:[NSMenu menuZone]] 
initWithTitle:SCRIPTS_MENU_TITLE action:NULL keyEquivalent:@""];
+    [menuItem setImage:[NSImage imageNamed:@"ScriptMenu"]];
+    [menuItem setSubmenu:sharedMenu];
+    [[NSApp mainMenu] insertItem:menuItem atIndex:itemIndex];
+    [menuItem release];
+}
+
+static void fsevents_callback(FSEventStreamRef streamRef, void 
*clientCallBackInfo, int numEvents, const char *const eventPaths[], const 
FSEventStreamEventFlags *eventMasks, const uint64_t *eventIDs) {
+    menuNeedsUpdate = YES;
+}
+
+- (id)initWithPaths:(NSArray *)scriptFolders {
+    if (self = [super initWithTitle:SCRIPTS_MENU_TITLE]) {
+        sortDescriptors = [[NSArray alloc] initWithObjects:[[[NSSortDescriptor 
alloc] initWithKey:FILENAME_KEY ascending:YES 
selector:@selector(localizedCaseInsensitiveCompare:)] autorelease], nil];
+        
+        FSEventStreamContext context = {0, NULL, NULL, NULL, NULL};
+        streamRef = FSEventStreamCreate(kCFAllocatorDefault,
+                                        
(FSEventStreamCallback)&fsevents_callback,
+                                        &context,
+                                        (CFArrayRef)scriptFolders,
+                                        kFSEventStreamEventIdSinceNow, // 
sinceWhen
+                                        1.0, // latency
+                                        0); // flags
+        FSEventStreamScheduleWithRunLoop(streamRef, CFRunLoopGetCurrent(), 
kCFRunLoopDefaultMode);
+        FSEventStreamStart(streamRef);
+        
+        [[NSNotificationCenter defaultCenter] addObserver:self 
selector:@selector(handleApplicationWillTerminateNotification:) 
name:NSApplicationWillTerminateNotification object:NSApp];
+        [self setDelegate:self];
+        menuNeedsUpdate = YES;
+    }
+    return self;
+}
+
+- (id)initWithTitle:(NSString *)aTitle {
+    [self release];
+    return nil;
+}
+
+- (void)handleApplicationWillTerminateNotification:(NSNotification 
*)notification {
+    if (streamRef) {
+        FSEventStreamStop(streamRef);
+        FSEventStreamInvalidate(streamRef);
+        FSEventStreamRelease(streamRef);
+        streamRef = NULL;
+    }
+    [self setDelegate:nil];
+}
+
+- (void)updateSubmenu:(NSMenu *)menu withScripts:(NSArray *)scripts {
+    static NSSet *scriptExtensions = nil;
+    if (scriptExtensions == nil)
+        scriptExtensions = [[NSSet alloc] initWithObjects:@"scpt", @"scptd", 
@"applescript", @"sh", @"csh", @"command", @"py", @"rb", @"pl", @"pm", @"app", 
@"workflow", nil];
+    
+    [menu removeAllItems];
+    
+    for (NSDictionary *scriptInfo in scripts) {
+        NSString *scriptFilename = [scriptInfo objectForKey:FILENAME_KEY];
+               NSArray *folderContent = [scriptInfo objectForKey:CONTENT_KEY];
+        NSString *scriptName = [scriptFilename lastPathComponent];
+               NSMenuItem *item;
+        
+        if (folderContent) {
+            NSMenu *submenu = [[NSMenu allocWithZone:[NSMenu menuZone]] 
initWithTitle:scriptName];
+            [menu addItemWithTitle:scriptName submenu:submenu];
+            [self updateSubmenu:submenu withScripts:folderContent];
+            [submenu release];
+        } else {
+            if ([scriptExtensions containsObject:[[scriptName pathExtension] 
lowercaseString]])
+                scriptName = [scriptName stringByDeletingPathExtension];
+            item = [menu addItemWithTitle:scriptName 
action:@selector(executeScript:) target:self];
+            [item setTarget:self];
+            [item setRepresentedObject:scriptFilename];
+        }
+    }
+}
+
+- (void)menuNeedsUpdate:(NSMenu *)menu {
+    if (streamRef == NULL || menuNeedsUpdate == NO)
+        return;
+    
+    NSArray *scriptFolders = (NSArray 
*)FSEventStreamCopyPathsBeingWatched(streamRef);
+    NSMutableArray *scripts = [NSMutableArray array];
+    for (NSString *folder in scriptFolders)
+        [scripts addObjectsFromArray:[self directoryContentsAtPath:folder 
recursionDepth:0]];
+    [scriptFolders release];
+    [scripts sortUsingDescriptors:sortDescriptors];
+    
+    [self updateSubmenu:menu withScripts:scripts];
+    
+    menuNeedsUpdate = NO;
+}
+
+static BOOL isAppleScriptUTI(NSString *theUTI) {
+    if (theUTI == NULL)
+        return NO;
+    return [[NSWorkspace sharedWorkspace] type:theUTI 
conformsToType:@"com.apple.applescript.script"] ||
+           [[NSWorkspace sharedWorkspace] type:theUTI 
conformsToType:@"com.apple.applescript.text"] ||
+           [[NSWorkspace sharedWorkspace] type:theUTI 
conformsToType:@"com.apple.applescript.script-bundle"];
+}
+
+static BOOL isApplicationUTI(NSString *theUTI) {
+    if (theUTI == NULL)
+        return NO;
+    return [[NSWorkspace sharedWorkspace] type:theUTI 
conformsToType:(id)kUTTypeApplication];
+}
+
+static BOOL isAutomatorWorkflowUTI(NSString *theUTI) {
+    if (theUTI == NULL)
+        return NO;
+    return [[NSWorkspace sharedWorkspace] type:theUTI 
conformsToType:@"com.apple.automator-workflow"];
+}
+
+static BOOL isFolderUTI(NSString *theUTI) {
+    if (theUTI == NULL)
+        return NO;
+    return [[NSWorkspace sharedWorkspace] type:theUTI 
conformsToType:(id)kUTTypeFolder];
+}
+
+- (NSArray *)directoryContentsAtPath:(NSString *)path 
recursionDepth:(NSInteger)depth {
+    NSMutableArray *files = [NSMutableArray array];
+    NSFileManager *fm = [NSFileManager defaultManager];
+    NSWorkspace *ws = [NSWorkspace sharedWorkspace];
+    
+    for (NSString *file in [fm contentsOfDirectoryAtPath:path error:NULL]) {
+        NSString *filePath = [path stringByAppendingPathComponent:file];
+        NSDictionary *fileAttributes = [fm attributesOfItemAtPath:filePath 
error:NULL];
+        NSString *fileType = [fileAttributes valueForKey:NSFileType];
+        BOOL isDir = [fileType isEqualToString:NSFileTypeDirectory];
+        NSString *theUTI = [ws typeOfFile:[[filePath 
stringByStandardizingPath] stringByResolvingSymlinksInPath] error:NULL];
+        
+        NSDictionary *dict;
+        
+        if ([file hasPrefix:@"."]) {
+        } else if (isAppleScriptUTI(theUTI) || isApplicationUTI(theUTI) || 
isAutomatorWorkflowUTI(theUTI) || ([fm isExecutableFileAtPath:filePath] && 
isDir == NO)) {
+            dict = [[NSDictionary alloc] initWithObjectsAndKeys:filePath, 
FILENAME_KEY, nil];
+            [files addObject:dict];
+            [dict release];
+        } else if (isDir && isFolderUTI(theUTI) && depth < 3) {
+            NSArray *content = [self directoryContentsAtPath:filePath 
recursionDepth:depth + 1];
+            if ([content count] > 0) {
+                dict = [[NSDictionary alloc] initWithObjectsAndKeys:filePath, 
FILENAME_KEY, content, CONTENT_KEY, nil];
+                [files addObject:dict];
+                [dict release];
+            }
+        }
+    }
+    [files sortUsingDescriptors:sortDescriptors];
+    return files;
+}
+
+- (void)executeScript:(id)sender {
+    NSString *scriptFilename = [sender representedObject];
+    NSString *theUTI = [[NSWorkspace sharedWorkspace] 
typeOfFile:[[scriptFilename stringByStandardizingPath] 
stringByResolvingSymlinksInPath] error:NULL];
+    
+    if (isAppleScriptUTI(theUTI)) {
+        NSDictionary *errorDictionary;
+        NSAppleScript *script = [[[NSAppleScript alloc] 
initWithContentsOfURL:[NSURL fileURLWithPath:scriptFilename] 
error:&errorDictionary] autorelease];
+        NSAppleEventDescriptor *result = [script 
executeAndReturnError:&errorDictionary];
+        if (result == nil)
+            NSBeep();
+    } else if (isApplicationUTI(theUTI)) {
+        BOOL result = [[NSWorkspace sharedWorkspace] 
launchApplication:scriptFilename];
+        if (result == NO)
+            NSBeep();
+    } else if (isAutomatorWorkflowUTI(theUTI)) {
+        [NSTask launchedTaskWithLaunchPath:@"/usr/bin/automator" 
arguments:[NSArray arrayWithObjects:scriptFilename, nil]];
+    } else if ([[NSFileManager defaultManager] 
isExecutableFileAtPath:scriptFilename]) {
+        [NSTask launchedTaskWithLaunchPath:scriptFilename arguments:[NSArray 
array]];
+    }
+}
+
+...@end

Modified: trunk/Skim.xcodeproj/project.pbxproj
===================================================================
--- trunk/Skim.xcodeproj/project.pbxproj        2010-04-22 08:57:36 UTC (rev 
6480)
+++ trunk/Skim.xcodeproj/project.pbxproj        2010-04-22 14:45:10 UTC (rev 
6481)
@@ -69,6 +69,8 @@
                CE0EB4D60DD054DC0034DF92 /* NSInvocation_SKExtensions.m in 
Sources */ = {isa = PBXBuildFile; fileRef = CE0EB4D50DD054DC0034DF92 /* 
NSInvocation_SKExtensions.m */; };
                CE0ECCDA0DE7188C006EEDDB /* Templates in Copy Files: Shared 
Support */ = {isa = PBXBuildFile; fileRef = CE0ECCD40DE71868006EEDDB /* 
Templates */; };
                CE0ECD1C0DE73604006EEDDB /* NSDocument_SKExtensions.m in 
Sources */ = {isa = PBXBuildFile; fileRef = CE0ECD1B0DE73604006EEDDB /* 
NSDocument_SKExtensions.m */; };
+               CE121AC81180644A00951425 /* SKScriptMenu.m in Sources */ = {isa 
= PBXBuildFile; fileRef = CE121AC71180644A00951425 /* SKScriptMenu.m */; };
+               CE121B2D1180770900951425 /* ScriptMenu.tiff in Resources */ = 
{isa = PBXBuildFile; fileRef = CE121B2C1180770900951425 /* ScriptMenu.tiff */; 
};
                CE121BFB11529D15001D92ED /* SKIBArray.m in Sources */ = {isa = 
PBXBuildFile; fileRef = CE121BFA11529D15001D92ED /* SKIBArray.m */; };
                CE17F47E0F1A17E200E741DD /* SKPDFSynchronizerServer.m in 
Sources */ = {isa = PBXBuildFile; fileRef = CE17F47D0F1A17E200E741DD /* 
SKPDFSynchronizerServer.m */; };
                CE19446310627483007E8770 /* BookmarksWindow.xib in Resources */ 
= {isa = PBXBuildFile; fileRef = CE19445C10627483007E8770 /* 
BookmarksWindow.xib */; };
@@ -574,6 +576,9 @@
                CE0ECCD40DE71868006EEDDB /* Templates */ = {isa = 
PBXFileReference; lastKnownFileType = folder; path = Templates; sourceTree = 
"<group>"; };
                CE0ECD1A0DE73604006EEDDB /* NSDocument_SKExtensions.h */ = {isa 
= PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path 
= NSDocument_SKExtensions.h; sourceTree = "<group>"; };
                CE0ECD1B0DE73604006EEDDB /* NSDocument_SKExtensions.m */ = {isa 
= PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; 
path = NSDocument_SKExtensions.m; sourceTree = "<group>"; };
+               CE121AC61180644A00951425 /* SKScriptMenu.h */ = {isa = 
PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = 
SKScriptMenu.h; sourceTree = "<group>"; };
+               CE121AC71180644A00951425 /* SKScriptMenu.m */ = {isa = 
PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path 
= SKScriptMenu.m; sourceTree = "<group>"; };
+               CE121B2C1180770900951425 /* ScriptMenu.tiff */ = {isa = 
PBXFileReference; lastKnownFileType = image.tiff; path = ScriptMenu.tiff; 
sourceTree = "<group>"; };
                CE121BF911529D15001D92ED /* SKIBArray.h */ = {isa = 
PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = 
SKIBArray.h; sourceTree = "<group>"; };
                CE121BFA11529D15001D92ED /* SKIBArray.m */ = {isa = 
PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path 
= SKIBArray.m; sourceTree = "<group>"; };
                CE17EE460E24ED7C00DE06EA /* Skim-App.xcconfig */ = {isa = 
PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = 
"Skim-App.xcconfig"; sourceTree = "<group>"; };
@@ -1709,6 +1714,8 @@
                        children = (
                                CE1F67FD0E37552400E07E76 /* SKRuntime.h */,
                                CE09FC3B0E3886C100BDF413 /* SKRuntime.m */,
+                               CE121AC61180644A00951425 /* SKScriptMenu.h */,
+                               CE121AC71180644A00951425 /* SKScriptMenu.m */,
                                45A3BD060B4F0770002B297F /* SKStringConstants.h 
*/,
                                45A3BD070B4F0770002B297F /* SKStringConstants.m 
*/,
                                CE5BD6710C7ADF1500EBDCF7 /* 
SKTypeSelectHelper.h */,
@@ -1800,6 +1807,7 @@
                                CE0E83EB114D15E000E37F38 /* 
DisplayPreferences.tiff */,
                                CE0E83EC114D15E000E37F38 /* 
GeneralPreferences.tiff */,
                                CE0E83ED114D15E000E37F38 /* 
NotesPreferences.tiff */,
+                               CE121B2C1180770900951425 /* ScriptMenu.tiff */,
                        );
                        path = Images;
                        sourceTree = "<group>";
@@ -2234,6 +2242,7 @@
                                CEF1D625117EFB500069E249 /* skimhelp.css in 
Resources */,
                                CEF1D628117EFB760069E249 /* applehelp.init in 
Resources */,
                                CEF1D629117EFB760069E249 /* 
postprocess-nontitle.py in Resources */,
+                               CE121B2D1180770900951425 /* ScriptMenu.tiff in 
Resources */,
                        );
                        runOnlyForDeploymentPostprocessing = 0;
                };
@@ -2521,6 +2530,7 @@
                                CE8BF027115F7C390029020F /* 
SKLeftSideViewController.m in Sources */,
                                CE8BF02A115F7C5C0029020F /* 
SKRightSideViewController.m in Sources */,
                                CE9768831161195C008DCB8F /* 
SKDownloadPreferenceController.m in Sources */,
+                               CE121AC81180644A00951425 /* SKScriptMenu.m in 
Sources */,
                        );
                        runOnlyForDeploymentPostprocessing = 0;
                };


This was sent by the SourceForge.net collaborative development platform, the 
world's largest Open Source development site.

------------------------------------------------------------------------------
_______________________________________________
Skim-app-commit mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/skim-app-commit

Reply via email to