Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagesmc
Path: blob/master/src/mac-app/AppDelegate.m
8815 views
1
//
2
// AppDelegate.m
3
//
4
// Created by Ivan Andrus on 26/6/10.
5
// Copyright 2010 __MyCompanyName__. All rights reserved.
6
//
7
8
#import "AppDelegate.h"
9
#import "AppController.h"
10
#import <WebKit/WebFrame.h>
11
#import <WebKit/WebView.h>
12
#import <Carbon/Carbon.h>
13
14
@implementation AppDelegate
15
16
+ (void)initialize{
17
// Make sure default are up to date
18
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
19
NSDictionary *factoryDefaults = [NSDictionary dictionaryWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"Defaults" ofType:@"plist"]];
20
[defaults registerDefaults: factoryDefaults];
21
}
22
23
- (void)applicationWillFinishLaunching:(NSNotification *)aNotification{
24
// This is early enough to show in the dock if we want to
25
// http://www.cocoadev.com/index.pl?LSUIElement
26
// http://codesorcery.net/2008/02/06/feature-requests-versus-the-right-way-to-do-it
27
28
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
29
BOOL isInDock = [defaults boolForKey:@"myShowInDock"];
30
31
if ( isInDock ) {
32
ProcessSerialNumber psn = { 0, kCurrentProcess };
33
// display dock icon
34
OSStatus returnCode = TransformProcessType(&psn, kProcessTransformToForegroundApplication);
35
if( returnCode != 0 ) {
36
// According to http://www.cocoadev.com/index.pl?TransformProcessType
37
// TransformProcessType is available since 10.3, but doen't work for our case until 10.5
38
NSLog(@"Could not show Sage.app in the dock. Error %ld", returnCode);
39
// It's forbidden to showInDock since it doesn't work
40
[defaults setBool:NO forKey:@"myShowInDock"];
41
[defaults synchronize];
42
43
} else {
44
45
// enable menu bar
46
SetSystemUIMode(kUIModeNormal, 0);
47
// switch to Dock.app
48
[[NSWorkspace sharedWorkspace] launchAppWithBundleIdentifier:@"com.apple.dock"
49
options:NSWorkspaceLaunchDefault
50
additionalEventParamDescriptor:nil
51
launchIdentifier:nil];
52
// switch back
53
[[NSApplication sharedApplication] activateIgnoringOtherApps:TRUE];
54
}
55
} else {
56
// NSLog(@"Not showing in Dock");
57
}
58
59
// If we are using the system browser we don't need all of the menus
60
// TODO: make this use menu titles not indexes
61
if ( [defaults boolForKey:@"useSystemBrowser"] ) {
62
[[NSApp mainMenu] removeItemAtIndex:6]; // Window menu
63
[[NSApp mainMenu] removeItemAtIndex:2]; // Edit menu
64
}
65
}
66
67
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
68
// Register that we can open URLs
69
NSAppleEventManager *em = [NSAppleEventManager sharedAppleEventManager];
70
[em setEventHandler:self
71
andSelector:@selector(getUrl:withReplyEvent:)
72
forEventClass:kInternetEventClass
73
andEventID:kAEGetURL];
74
}
75
76
- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender{
77
return NO;
78
}
79
80
// From here down are methods from NSApplicationDelegate, which probably do belong in another file.
81
// If/when this is done, I think you have to change the "File's Owner"'s delegate in IB
82
- (BOOL)application: (NSApplication * )theApplication openFile: (NSString * )filename{
83
84
NSString *extension = [filename pathExtension];
85
NSLog(@"Told to open %@ of type %@", filename, extension);
86
87
// Handle the file based on extension
88
if ( [extension isEqual:@"sage"] || [extension isEqual:@"py"] ) {
89
// Run sage and python files in your terminal
90
[appController sageTerminalRun:nil withArguments:[NSArray arrayWithObject:filename]];
91
92
} else if ( [extension isEqual:@"sws"]
93
|| [extension isEqual:@"txt"]
94
|| [extension isEqual:@"zip"] )
95
{
96
97
// Browse to a url which will upload the file.
98
// Perhaps we should have an option to delete the file when done...
99
NSString* theURL = [NSString stringWithFormat:@"upload_worksheet?url=%@",
100
[[NSURL fileURLWithPath: filename] relativeString]];
101
[appController browseLocalSageURL:theURL];
102
103
} else if ( [extension isEqual:@"spkg"] ) {
104
// Install the spkg
105
[appController sageTerminalRun:@"i" withArguments:[NSArray arrayWithObject:filename]];
106
107
} else if ( [extension isEqual:@"html"] || [extension isEqual:@"htm"] ) { // maybe others?
108
109
NSError *outError = nil;
110
id myDocument = [[NSDocumentController sharedDocumentController]
111
openUntitledDocumentAndDisplay:YES error:&outError];
112
if ( myDocument == nil ) {
113
[NSApp presentError:outError];
114
NSLog(@"sageBrowser: Error creating document: %@", [outError localizedDescription]);
115
} else {
116
[[[myDocument webView] mainFrame]
117
loadRequest:[NSURLRequest requestWithURL:
118
[NSURL URLWithString:
119
[NSString stringWithFormat:@"file://%@",
120
[filename stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]]]];
121
}
122
123
} else if ( [[NSFileManager defaultManager] isExecutableFileAtPath:[NSString stringWithFormat:@"%@/sage", filename]] ) {
124
// Use this as the sage folder
125
// NSFileManager *fileManager = [NSFileManager defaultManager];
126
[[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%@/sage", filename]
127
forKey:@"SageBinary"];
128
[appController setupPaths];
129
130
} else {
131
NSLog(@"I have no idea how I got a file of type %@.", extension);
132
return NO;
133
}
134
return YES;
135
}
136
137
// http://stackoverflow.com/questions/49510/how-do-you-set-your-cocoa-application-as-the-default-web-browser
138
- (void)getUrl:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent{
139
// Get the URL
140
NSString *urlStr = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
141
// Activate us
142
[[NSApplication sharedApplication] activateIgnoringOtherApps:TRUE];
143
144
if ( [[urlStr pathExtension] isEqual:@"spkg"] ) {
145
// We can install spkg's from URLs
146
[appController sageTerminalRun:@"i" withArguments:[NSArray arrayWithObject:urlStr]];
147
148
} else if ( ( [[urlStr pathExtension] isEqual:@"sws"]
149
|| [[urlStr pathExtension] isEqual:@"txt"]
150
|| [[urlStr pathExtension] isEqual:@"zip"] )
151
&&
152
! ( [[urlStr substringToIndex:16] isEqual:@"http://localhost"]
153
|| [[urlStr substringToIndex:17] isEqual:@"https://localhost"] ) )
154
{
155
156
// Browse to a url which will upload the file.
157
// Perhaps we should have an option to delete the file when done...
158
NSString* theURL = [NSString stringWithFormat:@"upload_worksheet?url=%@",
159
[[NSURL URLWithString: urlStr] relativeString]];
160
[appController browseLocalSageURL:theURL];
161
162
} else {
163
164
// Open the url in a new window
165
NSError *outError = nil;
166
id myDocument = [[NSDocumentController sharedDocumentController]
167
openUntitledDocumentAndDisplay:YES error:&outError];
168
if ( myDocument == nil ) {
169
[NSApp presentError:outError];
170
NSLog(@"sageBrowser: Error creating document: %@", [outError localizedDescription]);
171
} else {
172
[[[myDocument webView] mainFrame]
173
loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]];
174
}
175
176
// Check if the server has started
177
// TODO: This detection will only work if we are SAGE_BROWSER (i.e. we are in the dock)
178
NSArray *components = [urlStr componentsSeparatedByString:@"/?startup_token="];
179
if ( [components count] > 1 ) {
180
urlStr = [components objectAtIndex:0];
181
components = [urlStr componentsSeparatedByString:@"localhost:"];
182
if ( [components count] > 1 ) {
183
const int port = (int)[[components objectAtIndex:1] floatValue];
184
// We need to give it some time to load before we start loading queued things
185
// which happens from serverStartedWithPort
186
if ([[myDocument webView] respondsToSelector: @selector(isLoading)]) {
187
// block while the webview loads
188
while ([[myDocument webView] isLoading]) {
189
[[NSRunLoop currentRunLoop]
190
runMode:NSDefaultRunLoopMode
191
beforeDate:[NSDate distantFuture]];
192
}
193
} else {
194
// Eyeball it... This should only happen before 10.4.11
195
sleep(1);
196
}
197
[appController serverStartedWithPort:port];
198
}
199
}
200
}
201
}
202
203
-(IBAction)openDocumentWithDialogBox:(id)sender{
204
NSLog(@"openDocument:%@",sender);
205
206
// Create the File Open Dialog class.
207
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
208
[openDlg setCanChooseFiles:YES];
209
[openDlg setCanChooseDirectories:NO];
210
211
// Display the dialog. If the OK button was pressed,
212
// process the files.
213
if ( [openDlg runModalForDirectory:nil file:nil] == NSOKButton )
214
{
215
// Get an array containing the full filenames of all
216
// files and directories selected.
217
NSArray* files = [openDlg filenames];
218
for( int i = 0; i < [files count]; i++ )
219
{
220
NSString* fileName = [files objectAtIndex:i];
221
[self application:nil openFile:fileName];
222
}
223
}
224
}
225
226
227
@end
228
229