forked from Ahmed-Ali/JSONExport
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathViewController.swift
More file actions
executable file
·490 lines (393 loc) · 16 KB
/
ViewController.swift
File metadata and controls
executable file
·490 lines (393 loc) · 16 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
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
//
// ViewController.swift
// JSONExport
//
// Created by Ahmed on 11/2/14.
// Copyright (c) 2014 Ahmed Ali. Eng.Ahmed.Ali.Awad@gmail.com.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. 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.
// 3. The name of the contributor can not 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 HOLDER 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
class ViewController: NSViewController, NSUserNotificationCenterDelegate, NSTableViewDelegate, NSTableViewDataSource, NSTextViewDelegate {
//Shows the list of files' preview
@IBOutlet weak var tableView: NSTableView!
//Connected to the top right corner to show the current parsing status
@IBOutlet weak var statusTextField: NSTextField!
//Connected to the save button
@IBOutlet weak var saveButton: NSButton!
//Connected to the JSON input text view
@IBOutlet var sourceText: NSTextView!
//Connected to the scroll view which wraps the sourceText
@IBOutlet weak var scrollView: NSScrollView!
//Connected to Constructors check box
@IBOutlet weak var generateConstructors: NSButtonCell!
//Connected to Utility Methods check box
@IBOutlet weak var generateUtilityMethods: NSButtonCell!
//Connected to root class name field
@IBOutlet weak var classNameField: NSTextFieldCell!
//Connected to parent class name field
@IBOutlet weak var parentClassName: NSTextField!
//Connected to class prefix field
@IBOutlet weak var classPrefixField: NSTextField!
//Connected to the first line statement field
@IBOutlet weak var firstLineField: NSTextField!
//Connected to the languages pop up
@IBOutlet weak var languagesPopup: NSPopUpButton!
//Holds the currently selected language
var selectedLang : LangModel!
//Returns the title of the selected language in the languagesPopup
var selectedLanguageName : String
{
return languagesPopup.titleOfSelectedItem!
}
//Should hold list of supported languages, where the key is the language name and the value is LangModel instance
var langs : [String : LangModel] = [String : LangModel]()
//Holds list of the generated files
var files : [FileRepresenter] = [FileRepresenter]()
override func viewDidLoad() {
super.viewDidLoad()
saveButton.isEnabled = false
sourceText.isAutomaticQuoteSubstitutionEnabled = false
loadSupportedLanguages()
setupNumberedTextView()
setLanguagesSelection()
loadLastSelectedLanguage()
updateUIFieldsForSelectedLanguage()
}
/**
Sets the values of languagesPopup items' titles
*/
func setLanguagesSelection()
{
let langNames = Array(langs.keys).sorted()
languagesPopup.removeAllItems()
languagesPopup.addItems(withTitles: langNames)
}
/**
Sets the needed configurations for show the line numbers in the input text view
*/
func setupNumberedTextView()
{
let lineNumberView = NoodleLineNumberView(scrollView: scrollView)
scrollView.hasHorizontalRuler = false
scrollView.hasVerticalRuler = true
scrollView.verticalRulerView = lineNumberView
scrollView.rulersVisible = true
sourceText.font = NSFont.userFixedPitchFont(ofSize: NSFont.smallSystemFontSize())
}
/**
Updates the visible fields according to the selected language
*/
func updateUIFieldsForSelectedLanguage()
{
loadSelectedLanguageModel()
if selectedLang.supportsFirstLineStatement != nil && selectedLang.supportsFirstLineStatement!{
firstLineField.isHidden = false
firstLineField.placeholderString = selectedLang.firstLineHint
}else{
firstLineField.isHidden = true
}
if selectedLang.modelDefinitionWithParent != nil || selectedLang.headerFileData?.modelDefinitionWithParent != nil{
parentClassName.isHidden = false
}else{
parentClassName.isHidden = true
}
}
/**
Loads last selected language by user
*/
func loadLastSelectedLanguage()
{
guard let lastSelectedLanguage = UserDefaults.standard.value(forKey: "selectedLanguage") as? String else{
return
}
if langs[lastSelectedLanguage] != nil{
languagesPopup.selectItem(withTitle: lastSelectedLanguage)
}
}
//MARK: - Handling pre defined languages
func loadSupportedLanguages()
{
if let langFiles = Bundle.main.urls(forResourcesWithExtension: "json", subdirectory: nil) as [URL]!{
for langFile in langFiles{
if let data = try? Data(contentsOf: langFile), let langDictionary = (try? JSONSerialization.jsonObject(with: data, options: [])) as? NSDictionary{
let lang = LangModel(fromDictionary: langDictionary)
if langs[lang.displayLangName] != nil{
continue
}
langs[lang.displayLangName] = lang
}
}
}
}
// MARK: - parse the json file
func parseJSONData(jsonData: Data!)
{
let jsonString = String(data: jsonData, encoding: .utf8)
sourceText.string = jsonString
}
//MARK: - Handlind events
@IBAction func openJSONFiles(sender: AnyObject)
{
let oPanel: NSOpenPanel = NSOpenPanel()
oPanel.canChooseDirectories = false
oPanel.canChooseFiles = true
oPanel.allowsMultipleSelection = false
oPanel.allowedFileTypes = ["json","JSON"]
oPanel.prompt = "Choose JSON file"
oPanel.beginSheetModal(for: self.view.window!, completionHandler: { (button : Int) -> Void in
if button == NSFileHandlingPanelOKButton{
let jsonPath = oPanel.urls.first!.path
let fileHandle = FileHandle(forReadingAtPath: jsonPath)
let urlStr:String = oPanel.urls.first!.lastPathComponent
self.classNameField.stringValue = urlStr.replacingOccurrences(of: ".json", with: "")
self.parseJSONData(jsonData: (fileHandle!.readDataToEndOfFile() as NSData!) as Data!)
}
})
}
@IBAction func toggleConstructors(_ sender: AnyObject)
{
generateClasses()
}
@IBAction func toggleUtilities(_ sender: AnyObject)
{
generateClasses()
}
@IBAction func rootClassNameChanged(_ sender: AnyObject) {
generateClasses()
}
@IBAction func parentClassNameChanged(_ sender: AnyObject)
{
generateClasses()
}
@IBAction func classPrefixChanged(_ sender: AnyObject)
{
generateClasses()
}
@IBAction func selectedLanguageChanged(_ sender: AnyObject)
{
updateUIFieldsForSelectedLanguage()
generateClasses()
UserDefaults.standard.set(selectedLanguageName, forKey: "selectedLanguage")
}
@IBAction func firstLineChanged(_ sender: AnyObject)
{
generateClasses()
}
//MARK: - NSTextDelegate
func textDidChange(_ notification: Notification) {
generateClasses()
}
//MARK: - Language selection handling
func loadSelectedLanguageModel()
{
selectedLang = langs[selectedLanguageName]
}
//MARK: - NSUserNotificationCenterDelegate
func userNotificationCenter(_ center: NSUserNotificationCenter,
shouldPresent notification: NSUserNotification) -> Bool
{
return true
}
//MARK: - Showing the open panel and save files
@IBAction func saveFiles(_ sender: AnyObject)
{
let openPanel = NSOpenPanel()
openPanel.allowsOtherFileTypes = false
openPanel.treatsFilePackagesAsDirectories = false
openPanel.canChooseFiles = false
openPanel.canChooseDirectories = true
openPanel.canCreateDirectories = true
openPanel.prompt = "Choose"
openPanel.beginSheetModal(for: self.view.window!, completionHandler: { (button : Int) -> Void in
if button == NSFileHandlingPanelOKButton{
self.saveToPath(openPanel.url!.path)
self.showDoneSuccessfully()
}
})
}
/**
Saves all the generated files in the specified path
- parameter path: in which to save the files
*/
func saveToPath(_ path : String)
{
var error : NSError?
for file in files{
var fileContent = file.fileContent
if fileContent == ""{
fileContent = file.toString()
}
var fileExtension = selectedLang.fileExtension
if file is HeaderFileRepresenter{
fileExtension = selectedLang.headerFileData.headerFileExtension
}
let filePath = "\(path)/\(file.className).\(fileExtension)"
do {
try fileContent.write(toFile: filePath, atomically: false, encoding: String.Encoding.utf8)
} catch let error1 as NSError {
error = error1
}
if error != nil{
showError(error!)
break
}
}
}
//MARK: - Messages
/**
Shows the top right notification. Call it after saving the files successfully
*/
func showDoneSuccessfully()
{
let notification = NSUserNotification()
notification.title = "Success!"
notification.informativeText = "Your \(selectedLang.langName) model files have been generated successfully."
notification.deliveryDate = Date()
let center = NSUserNotificationCenter.default
center.delegate = self
center.deliver(notification)
}
/**
Shows an NSAlert for the passed error
*/
func showError(_ error: NSError!)
{
if error == nil{
return;
}
let alert = NSAlert(error: error)
alert.runModal()
}
/**
Shows the passed error status message
*/
func showErrorStatus(_ errorMessage: String)
{
statusTextField.textColor = NSColor.red
statusTextField.stringValue = errorMessage
}
/**
Shows the passed success status message
*/
func showSuccessStatus(_ successMessage: String)
{
statusTextField.textColor = NSColor.green
statusTextField.stringValue = successMessage
}
//MARK: - Generate files content
/**
Validates the sourceText string input, and takes any needed action to generate the model classes and view them in the preview panel
*/
func generateClasses()
{
saveButton.isEnabled = false
var str = sourceText.string!
if str.characters.count == 0{
runOnUiThread{
//Nothing to do, just clear any generated files
self.files.removeAll(keepingCapacity: false)
self.tableView.reloadData()
}
return;
}
var rootClassName = classNameField.stringValue
if rootClassName.characters.count == 0{
rootClassName = "RootClass"
}
sourceText.isEditable = false
//Do the lengthy process in background, it takes time with more complicated JSONs
runOnBackground {
str = stringByRemovingControlCharacters(str)
if let data = str.data(using: String.Encoding.utf8){
var error : NSError?
do {
let jsonData : Any = try JSONSerialization.jsonObject(with: data, options: [])
var json : NSDictionary!
if jsonData is NSDictionary{
//fine nothing to do
json = jsonData as! NSDictionary
}else{
json = unionDictionaryFromArrayElements(jsonData as! NSArray)
}
self.loadSelectedLanguageModel()
self.files.removeAll(keepingCapacity: false)
runOnUiThread{
let fileGenerator = self.prepareAndGetFilesBuilder()
fileGenerator.addFileWithName(&rootClassName, jsonObject: json, files: &self.files)
fileGenerator.fixReferenceMismatches(inFiles: self.files)
self.files = Array(self.files.reversed())
self.sourceText.isEditable = true
self.showSuccessStatus("Valid JSON structure")
self.saveButton.isEnabled = true
self.tableView.reloadData()
self.tableView.layout()
}
} catch let error1 as NSError {
error = error1
runOnUiThread({ () -> Void in
self.sourceText.isEditable = true
self.saveButton.isEnabled = false
if error != nil{
print(error!)
}
self.showErrorStatus("It seems your JSON object is not valid!")
})
} catch {
fatalError()
}
}
}
}
/**
Creates and returns an instance of FilesContentBuilder. It also configure the values from the UI components to the instance. I.e includeConstructors
- returns: instance of configured FilesContentBuilder
*/
func prepareAndGetFilesBuilder() -> FilesContentBuilder
{
let filesBuilder = FilesContentBuilder.instance
filesBuilder.includeConstructors = (generateConstructors.state == NSOnState)
filesBuilder.includeUtilities = (generateUtilityMethods.state == NSOnState)
filesBuilder.firstLine = firstLineField.stringValue
filesBuilder.lang = selectedLang!
filesBuilder.classPrefix = classPrefixField.stringValue
filesBuilder.parentClassName = parentClassName.stringValue
return filesBuilder
}
//MARK: - NSTableViewDataSource
func numberOfRows(in tableView: NSTableView) -> Int
{
return files.count
}
//MARK: - NSTableViewDelegate
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView?
{
let cell = tableView.make(withIdentifier: "fileCell", owner: self) as! FilePreviewCell
let file = files[row]
cell.file = file
return cell
}
}