summaryrefslogtreecommitdiff
path: root/tikzit/src/gtk/Application.m
blob: 89fb7fda1d3d1150525bd87fd08e14ede8b121b0 (plain)
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/*
 * Copyright 2011-2012  Alex Merry <dev@randomguy3.me.uk>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#import "Application.h"

#import "Configuration.h"
#import "EdgeStylesModel.h"
#import "NodeStylesModel.h"
#import "PreambleEditor.h"
#import "ContextWindow.h"
#import "Shape.h"
#import "SettingsDialog.h"
#import "StyleManager.h"
#import "StyleManager+Storage.h"
#import "SupportDir.h"
#import "TikzDocument.h"
#import "ToolBox.h"
#import "Window.h"

#ifdef HAVE_POPPLER
#import "Preambles.h"
#import "Preambles+Storage.h"
#import "PreviewWindow.h"
#endif

#import "BoundingBoxTool.h"
#import "CreateNodeTool.h"
#import "CreateEdgeTool.h"
#import "HandTool.h"
#import "SelectTool.h"

// used for args to g_mkdir_with_parents
#import "stat.h"

Application* app = nil;

@interface Application (Notifications)
- (void) windowClosed:(NSNotification*)notification;
- (void) windowGainedFocus:(NSNotification*)notification;
- (void) selectedToolChanged:(NSNotification*)notification;
- (void) windowDocumentChanged:(NSNotification*)n;
@end

@interface Application (Private)
- (void) setActiveWindow:(Window*)window;
@end

@implementation Application

@synthesize mainConfiguration=configFile;
@synthesize styleManager, preambles;
@synthesize lastOpenFolder, lastSaveAsFolder;
@synthesize tools;

+ (Application*) app {
    if (app == nil) {
        [[[self alloc] init] release];
    }
    return app;
}

- (id) _initCommon {
    if (app != nil) {
        [self release];
        self = app;
        return self;
    }
    self = [super init];

    if (self) {
        NSError *error = nil;
        configFile = [[Configuration alloc] initWithName:@"tikzit" loadError:&error];
        if (error != nil) {
            logError (error, @"WARNING: Failed to load configuration");
        }

        styleManager = [[StyleManager alloc] init];
        [styleManager loadStylesUsingConfigurationName:@"styles"]; // FIXME: error message?
        NodeStylesModel *nsm = [NodeStylesModel modelWithStyleManager:styleManager];
        EdgeStylesModel *esm = [EdgeStylesModel modelWithStyleManager:styleManager];

#ifdef HAVE_POPPLER
        NSString *preamblesDir = [[SupportDir userSupportDir] stringByAppendingPathComponent:@"preambles"];
        preambles = [[Preambles alloc] initFromDirectory:preamblesDir]; // FIXME: error message?
        [preambles setStyleManager:styleManager];
        NSString *selectedPreamble = [configFile stringEntry:@"selectedPreamble" inGroup:@"Preambles"];
        if (selectedPreamble != nil) {
            [preambles setSelectedPreambleName:selectedPreamble];
        }
#endif

        lastOpenFolder = [[configFile stringEntry:@"lastOpenFolder" inGroup:@"Paths"] retain];
        if (lastOpenFolder == nil)
            lastOpenFolder = [[configFile stringEntry:@"lastFolder" inGroup:@"Paths"] retain];
        lastSaveAsFolder = [[configFile stringEntry:@"lastSaveAsFolder" inGroup:@"Paths"] retain];
        if (lastSaveAsFolder == nil)
            lastSaveAsFolder = [[configFile stringEntry:@"lastFolder" inGroup:@"Paths"] retain];

        openWindows = [[NSMutableArray alloc] init];

        tools = [[NSArray alloc] initWithObjects:
            [SelectTool tool],
            [CreateNodeTool toolWithNodeStylesModel:nsm],
            [CreateEdgeTool toolWithEdgeStylesModel:esm],
            [BoundingBoxTool tool],
            [HandTool tool],
            nil];
        activeTool = [tools objectAtIndex:0];
        for (id<Tool> tool in tools) {
            [tool loadConfiguration:configFile];
        }

        toolBox = [[ToolBox alloc] initWithTools:tools];
        [toolBox loadConfiguration:configFile];
        [toolBox setSelectedTool:activeTool];
        [[NSNotificationCenter defaultCenter]
            addObserver:self
               selector:@selector(selectedToolChanged:)
                   name:@"ToolSelectionChanged"
                 object:toolBox];
        [toolBox show];

        contextWindow = [[ContextWindow alloc] initWithNodeStylesModel:nsm
                                                    andEdgeStylesModel:esm];
        [contextWindow loadConfiguration:configFile];

        app = [self retain];
    }

    return self;
}

- (id) init {
    self = [self _initCommon];

    if (self) {
        [self newWindow];
    }

    return self;
}

- (id) initWithFiles:(NSArray*)files {
    self = [self _initCommon];

    if (self) {
        int fileOpenCount = 0;
        for (NSString *file in files) {
            NSError *error = nil;
            TikzDocument *doc = [TikzDocument documentFromFile:file styleManager:styleManager error:&error];
            if (doc != nil) {
                [self newWindowWithDocument:doc];
                ++fileOpenCount;
            } else {
                logError(error, @"WARNING: failed to open file");
            }
        }
        if (fileOpenCount == 0) {
            [self newWindow];
        }
    }

    return self;
}

- (void) dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    [configFile release];
    [styleManager release];
    [preambles release];
    [lastOpenFolder release];
    [lastSaveAsFolder release];
    [preambleWindow release];
    [previewWindow release];
    [settingsDialog release];
    [openWindows release];
    [tools release];
    [activeTool release];
    [toolBox release];
    [contextWindow release];

    [super dealloc];
}

- (id<Tool>) activeTool { return activeTool; }
- (void) setActiveTool:(id<Tool>)tool {
    if (activeTool == tool)
        return;

    activeTool = tool;
    [toolBox setSelectedTool:tool];
    for (Window* window in openWindows) {
        [window setActiveTool:tool];
    }
}

- (BOOL) activateToolForKey:(unsigned int)keyVal withMask:(InputMask)mask {
    // FIXME: cache the accel info, rather than reparsing it every time?
    for (id<Tool> tool in tools) {
        guint toolKey = 0;
        GdkModifierType toolMod = 0;
        gtk_accelerator_parse ([[tool shortcut] UTF8String], &toolKey, &toolMod);
        if (toolKey != 0 && toolKey == keyVal && (int)mask == (int)toolMod) {
            [self setActiveTool:tool];
            return YES;
        }
    }
    return NO;
}

- (void) _addWindow:(Window*)window {
    [window setActiveTool:activeTool];
    [openWindows addObject:window];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(windowClosed:)
                                                 name:@"WindowClosed"
                                               object:window];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(windowGainedFocus:)
                                                 name:@"WindowGainedFocus"
                                               object:window];
    if ([window hasFocus]) {
        [self setActiveWindow:window];
    }
}

- (void) newWindow {
    [self _addWindow:[Window window]];
}

- (void) newWindowWithDocument:(TikzDocument*)doc {
    [self _addWindow:[Window windowWithDocument:doc]];
}

- (void) quit {
    NSMutableArray *unsavedDocs = [NSMutableArray arrayWithCapacity:[openWindows count]];
    for (Window *window in openWindows) {
        TikzDocument *doc = [window document];
        if ([doc hasUnsavedChanges]) {
            [unsavedDocs addObject:doc];
        }
    }
    if ([unsavedDocs count] > 0) {
        // FIXME: show a dialog
        return;
    }
    gtk_main_quit();
}

- (void) presentPreamblesEditor {
#ifdef HAVE_POPPLER
    if (preambleWindow == nil) {
        preambleWindow = [[PreambleEditor alloc] initWithPreambles:preambles];
        //[preambleWindow setParentWindow:mainWindow];
    }
    [preambleWindow present];
#endif
}

- (void) presentContextWindow {
    [contextWindow present];
}

- (void) presentPreviewForDocument:(TikzDocument*)doc {
#ifdef HAVE_POPPLER
    if (previewWindow == nil) {
        previewWindow = [[PreviewWindow alloc] initWithPreambles:preambles config:configFile];
        //[previewWindow setParentWindow:mainWindow];
        [previewWindow setDocument:doc];
    }
    [previewWindow present];
#endif
}

- (void) previewDocument:(TikzDocument*)doc {
#ifdef HAVE_POPPLER
    if (previewWindow == nil) {
        previewWindow = [[PreviewWindow alloc] initWithPreambles:preambles config:configFile];
        //[previewWindow setParentWindow:mainWindow];
        [previewWindow setDocument:doc];
    }
    [previewWindow show];
#endif
}

- (void) presentSettingsDialog {
    if (settingsDialog == nil) {
        settingsDialog = [[SettingsDialog alloc] initWithConfiguration:configFile
                                                       andStyleManager:styleManager];
        //[settingsDialog setParentWindow:mainWindow];
    }
    [settingsDialog present];
}

- (Configuration*) mainConfiguration {
    return configFile;
}

- (void) saveConfiguration {
    NSError *error = nil;

#ifdef HAVE_POPPLER
    if (preambles != nil) {
        NSString *preamblesDir = [[SupportDir userSupportDir] stringByAppendingPathComponent:@"preambles"];
        // NSFileManager is slightly dodgy on Windows
	g_mkdir_with_parents ([preamblesDir UTF8String], S_IRUSR | S_IWUSR | S_IXUSR);
        [preambles storeToDirectory:preamblesDir];
        [configFile setStringEntry:@"selectedPreamble" inGroup:@"Preambles" value:[preambles selectedPreambleName]];
    }
#endif

    [styleManager saveStylesUsingConfigurationName:@"styles"];

    for (id<Tool> tool in tools) {
        [tool saveConfiguration:configFile];
    }
    [toolBox saveConfiguration:configFile];

    [contextWindow saveConfiguration:configFile];

    if (lastOpenFolder != nil) {
        [configFile setStringEntry:@"lastOpenFolder" inGroup:@"Paths" value:lastOpenFolder];
    }
    if (lastSaveAsFolder != nil) {
        [configFile setStringEntry:@"lastSaveAsFolder" inGroup:@"Paths" value:lastSaveAsFolder];
    }

    if (![configFile writeToStoreWithError:&error]) {
        logError (error, @"Could not write config file");
    }
}

@end

@implementation Application (Notifications)
- (void) windowClosed:(NSNotification*)notification {
    Window *window = [notification object];
    [openWindows removeObjectIdenticalTo:window];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:nil
                                                  object:window];
    if ([openWindows count] == 0) {
        gtk_main_quit();
    } else {
        [self setActiveWindow:[openWindows objectAtIndex:0]];
    }
}

- (void) windowGainedFocus:(NSNotification*)notification {
    Window *window = [notification object];
    [self setActiveWindow:window];
}

- (void) selectedToolChanged:(NSNotification*)n {
    id<Tool> tool = [[n userInfo] objectForKey:@"tool"];
    if (tool != nil)
        [self setActiveTool:tool];
    else
        NSLog(@"nil tool!");
}

- (void) windowDocumentChanged:(NSNotification*)n {
    [contextWindow setDocument:[[n userInfo] objectForKey:@"document"]];
}
@end

@implementation Application (Private)
- (void) setActiveWindow:(Window*)window {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:@"DocumentChanged"
                                                  object:nil];

    [contextWindow setDocument:[window document]];

    [contextWindow setTransientFor:window];
    [toolBox setTransientFor:window];

    [[NSNotificationCenter defaultCenter]
        addObserver:self
           selector:@selector(windowDocumentChanged:)
               name:@"DocumentChanged"
             object:window];
}
@end

// vim:ft=objc:ts=8:et:sts=4:sw=4:foldmethod=marker