-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathapp.coffee
1528 lines (1355 loc) · 58.8 KB
/
app.coffee
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
define [
'backbone'
# 'FieldDB'
'./../routes/router'
'./base'
'./resource'
'./mainmenu'
'./notifier'
'./login-dialog'
'./register-dialog'
'./alert-dialog'
'./tasks-dialog'
'./help-dialog'
'./resource-displayer-dialog'
'./resources-displayer-dialog'
'./exporter-dialog'
'./home'
'./application-settings'
'./collections'
'./corpora'
'./elicitation-methods'
'./files'
'./forms'
'./keyboards'
'./language-models'
'./languages'
'./morphological-parsers'
'./morphologies'
'./orthographies'
'./pages'
'./phonologies'
'./searches'
'./sources'
'./speakers'
'./subcorpora'
'./syntactic-categories'
'./tags'
'./users'
'./event-based-keyboard'
'./collection'
'./elicitation-method'
'./file'
'./form'
'./keyboard'
'./language-model'
'./language'
'./morphological-parser'
'./morphology'
'./orthography'
'./page'
'./phonology'
'./search'
'./source'
'./speaker'
'./subcorpus'
'./syntactic-category'
'./tag'
'./user-old-circular'
'./../models/application-settings'
'./../models/collection'
'./../models/elicitation-method'
'./../models/file'
'./../models/form'
'./../models/keyboard'
'./../models/language-model'
'./../models/language'
'./../models/morphological-parser'
'./../models/morphology'
'./../models/old-application-settings'
'./../models/orthography'
'./../models/page'
'./../models/phonology'
'./../models/search'
'./../models/server'
'./../models/source'
'./../models/speaker'
'./../models/subcorpus'
'./../models/syntactic-category'
'./../models/tag'
'./../models/user-old'
'./../collections/collections'
'./../collections/elicitation-methods'
'./../collections/files'
'./../collections/forms'
'./../collections/keyboards'
'./../collections/language-models'
'./../collections/languages'
'./../collections/morphological-parsers'
'./../collections/morphologies'
'./../collections/orthographies'
'./../collections/old-application-settings'
'./../collections/pages'
'./../collections/phonologies'
'./../collections/searches'
'./../collections/servers'
'./../collections/sources'
'./../collections/speakers'
'./../collections/subcorpora'
'./../collections/syntactic-categories'
'./../collections/tags'
'./../collections/users'
'./../utils/globals'
'./../templates/app'
], (Backbone, Workspace, BaseView, ResourceView, MainMenuView,
NotifierView, LoginDialogView, RegisterDialogView, AlertDialogView,
TasksDialogView, HelpDialogView, ResourceDisplayerDialogView,
ResourcesDisplayerDialogView, ExporterDialogView, HomePageView,
ApplicationSettingsView, CollectionsView, CorporaView,
ElicitationMethodsView, FilesView, FormsView, KeyboardsView,
LanguageModelsView, LanguagesView, MorphologicalParsersView,
MorphologiesView, OrthographiesView, PagesView, PhonologiesView,
SearchesView, SourcesView, SpeakersView, SubcorporaView,
SyntacticCategoriesView, TagsView, UsersView,
EventBasedKeyboardView, CollectionView, ElicitationMethodView, FileView,
FormView, KeyboardView, LanguageModelView, LanguageView,
MorphologicalParserView, MorphologyView, OrthographyView, PageView,
PhonologyView, SearchView, SourceView, SpeakerView, SubcorpusView,
SyntacticCategoryView, TagView, UserView,
ApplicationSettingsModel, CollectionModel, ElicitationMethodModel, FileModel,
FormModel, KeyboardModel, LanguageModelModel, LanguageModel,
MorphologicalParserModel, MorphologyModel, OLDApplicationSettingsModel,
OrthographyModel, PageModel, PhonologyModel, SearchModel, ServerModel,
SourceModel, SpeakerModel, SubcorpusModel, SyntacticCategoryModel, TagModel,
UserModel,
CollectionsCollection, ElicitationMethodsCollection, FilesCollection,
FormsCollection, KeyboardsCollection, LanguageModelsCollection,
LanguagesCollection, MorphologicalParsersCollection, MorphologiesCollection,
OrthographiesCollection, OLDApplicationSettingsCollection, PagesCollection,
PhonologiesCollection, SearchesCollection, ServersCollection,
SourcesCollection, SpeakersCollection, SubcorporaCollection,
SyntacticCategoriesCollection, TagsCollection, UsersCollection,
globals, appTemplate) ->
# App View
# --------
#
# This is the spine of the application. Only one AppView object is created
# and it controls the creation and rendering of all of the subviews that
# control the content in the body of the page.
class AppView extends BaseView
template: appTemplate
el: '#dative-client-app'
close: ->
@closeVisibleView()
super
# A `FieldView` has just told us that one of its <textarea>s was focused;
# `index` tells us which one.
setLastFocusedField: (fieldView, index=0) ->
@lastFocusedField = fieldView
@lastFocusedFieldIndex = index
# An event-based keyboard is telling us to alert the last focused field view
# that it should insert `value` at its current cursor position.
keyboardValueReceived: (value) ->
if @lastFocusedField
@lastFocusedField.trigger 'keyboardValue', value, @lastFocusedFieldIndex
initialize: (options) ->
@lastFocusedField = null
@lastFocusedFieldIndex = 0
@setHash()
@preventParentScroll()
@getApplicationSettings options
@activeKeyboard = @getSystemWideKeyboard()
@fetchServers()
getSystemWideKeyboard: ->
systemWideKeyboard = super globals
if systemWideKeyboard
new KeyboardModel systemWideKeyboard
else
null
# If the user navigates to a particular part of the app using the hash
# string, then we want to remember that hash and navigate to it.
setHash: ->
hash = window.location.hash
if hash
@hash = @utils.hyphen2camel hash[1...]
else
@hash = null
# Continue initialization after fetching servers.json
initializeContinue: ->
globals.applicationSettings = @applicationSettings
# @overrideFieldDBNotificationHooks()
@initializePersistentSubviews()
@resourceModel = null # this and the next attribute are for displaying a single resource in the main page.
@resourcesCollection = null
@router = new Workspace
resources: @myResources
mainMenuView: @mainMenuView
@oldApplicationSettingsCollection = new OLDApplicationSettingsCollection()
@listenToEvents()
@render()
@setTheme()
Backbone.history.start()
@preventNavigationState = false
@navigate()
# Only navigate home if there is no hash string in the URL. This seems to
# be sufficient to ensure that refreshing on, say the forms browse page
# ('#forms') will result in that page being re-rendered.
navigate: ->
if not @hash
@showHomePageView()
# Calling this method will cause all scrollable <div>s with the class
# .Scrollable, to prevent (x and y axis) scroll propagation to parent divs.
# This is good because (with a trackpad, at least), there is often an
# annoying "over-scrolling" effect, which, in the x-axis can trigger the
# browser's forward or back button events, which is highly undesirable.
# See http://stackoverflow.com/a/16324762/992730
preventParentScroll: ->
$(document).on('DOMMouseScroll mousewheel', '.Scrollable', (ev) ->
$this = $ this
scrollTop = @scrollTop
scrollLeft = @scrollLeft
scrollHeight = @scrollHeight
scrollWidth = @scrollWidth
height = $this.height()
width = $this.width()
if ev.type is 'DOMMouseScroll'
delta = ev.originalEvent.detail * -40
else
delta = ev.originalEvent.wheelDelta
up = delta > 0
prevent = ->
ev.stopPropagation()
ev.preventDefault()
ev.returnValue = false
false
result = true
deltaX = ev.originalEvent.wheelDeltaX
if (not up) and -delta > scrollHeight - height - scrollTop
$this.scrollTop scrollHeight
if deltaX then $this.scrollLeft(@scrollLeft - deltaX)
result = prevent()
else if up and delta > scrollTop
$this.scrollTop(0)
if deltaX then $this.scrollLeft(@scrollLeft - deltaX)
result = prevent()
if deltaX
left = deltaX > 0
if (not left) and -deltaX > scrollWidth - width - scrollLeft
$this.scrollLeft scrollWidth
$this.scrollTop(@scrollTop - delta)
result = prevent()
else if left and deltaX > scrollLeft
$this.scrollLeft(0)
$this.scrollTop(@scrollTop - delta)
result = prevent()
result
)
events:
'click': 'bodyClicked'
'keydown': 'broadcastKeydown'
'keyup': 'broadcastKeyup'
broadcastKeydown: (event) ->
if @activeKeyboard
@activeKeyboard.trigger 'systemWideKeydown', event
broadcastKeyup: ->
if @activeKeyboard
@activeKeyboard.trigger 'systemWideKeyup', event
render: ->
if window.location.hostname is ['localhost', '127.0.0.1']
setTimeout ->
console.clear()
, 2000
@loggedIn()
@$el.html @template()
@renderPersistentSubviews()
@matchWindowDimensions()
@
# Another view has asked us to prevent navigation, i.e., the changing of
# the currently displayed view in the main page. The `msg` is the message
# that we display in the "Prevent Navigation" confirm dialog.
setPreventNavigation: (msg) ->
@preventNavigationState = true
@preventNavigationMsg = msg
# Unset our instance vars related to preventing navigation.
unsetPreventNavigation: ->
@preventNavigationState = false
@preventNavigationMsg = null
# Display the confirm dialog that asks the user whether they really want to
# navigate away from the current page.
displayPreventNavigationAlert: ->
if @preventNavigationMsg
msg = @preventNavigationMsg
else
msg = 'Do you really want to navigate away from the current page? Click
“Ok” to continue with navigation. Click “Cancel” to stay on
the current page.'
options =
confirm: false
text: msg
Backbone.trigger 'openAlertDialog', options
listenToEvents: ->
@listenTo Backbone, 'setPreventNavigation', @setPreventNavigation
@listenTo Backbone, 'unsetPreventNavigation', @unsetPreventNavigation
@listenTo Backbone, 'preventNavigation', @preventNavigation
@listenTo Backbone, 'mergeNewServers', @mergeNewServers
@listenTo Backbone, 'lastFocusedField', @setLastFocusedField
@listenTo Backbone, 'keyboardValue', @keyboardValueReceived
@listenTo @mainMenuView, 'request:home', @showHomePageView
@listenTo @mainMenuView, 'request:openLoginDialogBox', @toggleLoginDialog
@listenTo @mainMenuView, 'request:toggleHelpDialogBox', @toggleHelpDialog
@listenTo @mainMenuView, 'request:toggleTasksDialog', @toggleTasksDialog
@listenTo @mainMenuView, 'request:openRegisterDialogBox',
@toggleRegisterDialog
@listenTo @router, 'route:home', @showHomePageView
@listenTo @router, 'route:openLoginDialogBox', @toggleLoginDialog
@listenTo @router, 'route:openRegisterDialogBox', @toggleRegisterDialog
@listenTo @loginDialog, 'request:openRegisterDialogBox',
@toggleRegisterDialog
@listenTo Backbone, 'loginSuggest', @openLoginDialogWithDefaults
@listenTo Backbone, 'authenticateSuccess', @authenticateSuccess
@listenTo Backbone, 'authenticate:mustconfirmidentity',
@authenticateConfirmIdentity
@listenTo Backbone, 'logoutSuccess', @logoutSuccess
# @listenTo Backbone, 'useFieldDBCorpus', @useFieldDBCorpus
@listenTo Backbone, 'applicationSettings:changeTheme', @changeTheme
@listenTo Backbone, 'showResourceInDialog', @showResourceInDialog
@listenTo Backbone, 'showResourceModelInDialog',
@showResourceModelInDialog
@listenTo Backbone, 'showEventBasedKeyboardInDialog',
@showEventBasedKeyboardInDialog
@listenTo Backbone, 'closeAllResourceDisplayerDialogs',
@closeAllResourceDisplayerDialogs
@listenTo Backbone, 'openExporterDialog', @openExporterDialog
@listenTo Backbone, 'routerNavigateRequest', @routerNavigateRequest
@listenToResources()
@listenToOLDApplicationSettingsCollection()
@listenTo Backbone, 'homePageChanged', @homePageChanged
# Note the strange spellings of the events triggered here; just go along
# with it ...
listenToOLDApplicationSettingsCollection: ->
@listenTo Backbone, 'fetchOldApplicationSettingsesEnd',
@fetchOLDApplicationSettingsEnd
@listenTo Backbone, 'fetchOldApplicationSettingsesStart',
@fetchOLDApplicationSettingsStart
@listenTo Backbone, 'fetchOldApplicationSettingsesSuccess',
@fetchOLDApplicationSettingsSuccess
@listenTo Backbone, 'fetchOldApplicationSettingsesFail',
@fetchOLDApplicationSettingsFail
fetchOLDApplicationSettingsEnd: ->
fetchOLDApplicationSettingsStart: ->
fetchOLDApplicationSettingsSuccess: ->
if @oldApplicationSettingsCollection.length > 0
globals.oldApplicationSettings = @oldApplicationSettingsCollection
.at(@oldApplicationSettingsCollection.length - 1)
else
console.log 'This OLD has no app settings!?'
globals.oldApplicationSettings = null
fetchOLDApplicationSettingsFail: ->
console.log 'FAILED to get OLD app settings'
globals.oldApplicationSettings = null
# Failing to fetch the application settings of an OLD is an indication
# from the server that we are not logged in.
@applicationSettings.set 'loggedIn', false
@applicationSettings.save()
routerNavigateRequest: (route) -> @router.navigate route
# Listen for resource-related events. The resources and relevant events
# are configured by the `@myResources` object.
# TODO/QUESTION: why not just listen on the resources subclass instead of
# on Backbone with all of this complex naming stuff?
listenToResources: ->
for resource, config of @myResources
do =>
resourceName = resource
resourcePlural = @utils.pluralize resourceName
resourceCapitalized = @utils.capitalize resourceName
resourcePluralCapitalized = @utils.capitalize resourcePlural
@listenTo Backbone, "destroy#{resourceCapitalized}Success",
(resourceModel) => @destroyResourceSuccess resourceModel
@listenTo Backbone, "#{resourcePlural}View:showAllLabels",
=> @changeDisplaySetting resourcePlural, 'dataLabelsVisible', true
@listenTo Backbone, "#{resourcePlural}View:hideAllLabels",
=>
@changeDisplaySetting resourcePlural, 'dataLabelsVisible', false
@listenTo Backbone,
"#{resourcePlural}View:expandAll#{resourcePluralCapitalized}",
=>
@changeDisplaySetting resourcePlural,
"all#{resourcePluralCapitalized}Expanded", true
@listenTo Backbone,
"#{resourcePlural}View:collapseAll#{resourcePluralCapitalized}",
=>
@changeDisplaySetting resourcePlural,
"all#{resourcePluralCapitalized}Expanded", false
@listenTo Backbone, "#{resourcePlural}View:itemsPerPageChange",
(newItemsPerPage) =>
@changeDisplaySetting resourcePlural, 'itemsPerPage',
newItemsPerPage
@listenTo @mainMenuView, "request:#{resourcePlural}Browse",
(options={}) => @showResourcesView resourceName, options
@listenTo @mainMenuView, "meta:request:#{resourcePlural}Browse",
(options={}) => @showResourcesViewInDialog resourceName, options
@listenTo @mainMenuView, "request:#{resourceName}Add",
=> @showNewResourceView resourceName
@listenTo @mainMenuView, "request:#{resourcePlural}Import",
=> @showImportView resourceName
if config.params?.searchable is true
@listenTo Backbone, "request:#{resourcePlural}BrowseSearchResults",
(options={}) => @showResourcesView resourceName, options
if config.params?.corpusElement is true
@listenTo Backbone, "request:#{resourcePlural}BrowseCorpus",
(options={}) => @showResourcesView resourceName, options
@listenTo Backbone, "request:#{resourceCapitalized}View",
(id) => @showResourceView(resourceName, id)
initializePersistentSubviews: ->
@mainMenuView = new MainMenuView model: @applicationSettings
@loginDialog = new LoginDialogView model: @applicationSettings
@registerDialog = new RegisterDialogView model: @applicationSettings
@alertDialog = new AlertDialogView model: @applicationSettings
@tasksDialog = new TasksDialogView model: @applicationSettings
@helpDialog = new HelpDialogView()
@notifier = new NotifierView(@myResources)
@exporterDialog = new ExporterDialogView()
@getResourceDisplayerDialogs()
@resourcesDisplayerDialog = new ResourcesDisplayerDialogView()
renderPersistentSubviews: ->
@mainMenuView.setElement(@$('#mainmenu')).render()
@loginDialog.setElement(@$('#login-dialog-container')).render()
@registerDialog.setElement(@$('#register-dialog-container')).render()
@alertDialog.setElement(@$('#alert-dialog-container')).render()
@tasksDialog.setElement(@$('#tasks-dialog-container')).render()
@helpDialog.setElement(@$('#help-dialog-container'))
@renderResourceDisplayerDialogs()
@notifier.setElement(@$('#notifier-container')).render()
@exporterDialog.setElement(@$('#exporter-dialog-container')).render()
@resourcesDisplayerDialog.setElement(
@$('#resources-dialog-container')).render()
@rendered @mainMenuView
@rendered @loginDialog
@rendered @registerDialog
@rendered @alertDialog
@rendered @tasksDialog
@rendered @notifier
@rendered @exporterDialog
@rendered @resourcesDisplayerDialog
renderHelpDialog: ->
@helpDialog.render()
@rendered @helpDialog
bodyClicked: ->
Backbone.trigger 'bodyClicked' # Mainmenu superclick listens for this
useFieldDBCorpus: (corpusId) ->
currentlyActiveFieldDBCorpus = @activeFieldDBCorpus
fieldDBCorporaCollection = @corporaView?.collection
@activeFieldDBCorpus = fieldDBCorporaCollection?.findWhere
pouchname: corpusId
@applicationSettings.save
'activeFieldDBCorpus': corpusId
'activeFieldDBCorpusTitle': @activeFieldDBCorpus.get 'title'
'activeFieldDBCorpusModel': @activeFieldDBCorpus # TODO: FIX THIS ABERRATION!
globals.activeFieldDBCorpus = @activeFieldDBCorpus
if currentlyActiveFieldDBCorpus is @activeFieldDBCorpus
@showFormsView fieldDBCorpusHasChanged: false
else
# @mainMenuView.activeFieldDBCorpusChanged @activeFieldDBCorpus.get('title')
@showFormsView fieldDBCorpusHasChanged: true
logoutSuccess: ->
@closeVisibleView()
@corporaView = null
@usersView = null # TODO: all of these collection views should be DRY-ly emptied upon logout ...
@showHomePageView true
activeServerType: ->
try
@applicationSettings.get('activeServer').get 'type'
catch
null
authenticateSuccess: ->
activeServerType = @activeServerType()
switch activeServerType
when 'FieldDB'
if @applicationSettings.get('fieldDBApplication') isnt
FieldDB.FieldDBObject.application
@applicationSettings.set 'fieldDBApplication',
FieldDB.FieldDBObject.application
@showCorporaView()
when 'OLD'
@oldApplicationSettingsCollection.fetchResources()
@showFormsView()
else console.log 'Error: you logged in to a non-FieldDB/non-OLD server
(?).'
authenticateConfirmIdentity: (message) =>
message = message or 'We need to make sure this is you. Confirm your
password to continue.'
if not @originalMessage then @originalMessage = message
@displayConfirmIdentityDialog(
message
,
(loginDetails) =>
console.log 'no problem.. can keep working'
fieldDBApplication = @applicationSettings.get('fieldDBApplication')
@set
username: fieldDBApplication.authentication.user.username,
loggedInUser: fieldDBApplication.authentication.user
@save()
delete @originalMessage
,
(loginDetails) =>
if @confirmIdentityErrorCount > 3
console.log ' In this case of confirming identity, the user MUST
authenticate. If they cant remember their password, after 4
attempts, log them out.'
delete @originalMessage
Backbone.trigger 'authenticate:logout'
console.log 'Asking again'
@confirmIdentityErrorCount = @confirmIdentityErrorCount or 0
@confirmIdentityErrorCount += 1
@authenticateConfirmIdentity "#{@originalMessage}
#{loginDetails.userFriendlyErrors.join ' '}"
)
# Set `@applicationSettings`
getApplicationSettings: (options) ->
# Allowing an app settings model in the options facilitates testing.
if options?.applicationSettings
@applicationSettings = options.applicationSettings
else
@applicationSettings = new ApplicationSettingsModel()
# We have fetched the default servers array from the server hosting this
# Dative.
addDefaultServers: (serversArray) ->
# If the user has manually modified their locally stored list of servers,
# we won't overwrite that with what Dative gives them in servers.json.
# However, we will prompt them to see if they want to merge the new stuff
# from Dative into what they have.
if @applicationSettings.get('serversModified')
@promptServersMerge serversArray
else
serverModelsArray = []
for s in serversArray
s.id = @guid()
serverModelsArray.push(new ServerModel(s))
serversCollection = new ServersCollection(serverModelsArray)
@applicationSettings.set 'servers', serversCollection
try
activeServer = @applicationSettings.get('activeServer').get('name')
newActiveServer = serversCollection.findWhere name: activeServer
@applicationSettings.set 'activeServer', newActiveServer
catch e
activeServer = serversCollection.at 0
@applicationSettings.set 'activeServer', activeServer
@applicationSettings.save()
@initializeContinue()
# Display a confirm dialog that describes the servers that Dative knows
# about but which they don't and ask the user whether they want to add
# these servers to their list of servers.
promptServersMerge: (serversArray) ->
# `lastSeen` is the array of servers that we were prompted to merge last
# time. We don't want to keep pestering the user to merge the same array
# of servers.
lastSeen = @applicationSettings.get 'lastSeenServersFromDative'
if not _.isEqual(serversArray, lastSeen)
@applicationSettings.set 'lastSeenServersFromDative', serversArray
@applicationSettings.save()
existingServerNames = []
@applicationSettings.get('servers').each (m) ->
existingServerNames.push m.get('name')
newServers = (s for s in serversArray when s['name'] not in
existingServerNames)
if newServers.length > 0
newServerNames = "“#{(s['name'] for s in newServers).join '”, “'}”"
if newServers.length == 1
msg = "Dative knows about the OLD server #{newServerNames} but you
don't. Would you like to add the server #{newServerNames} to your
list of known servers?"
else
msg = "Dative knows about the following servers that you don't:
#{newServerNames}. Would you like to add these servers to your
list of known servers?"
options =
text: msg
confirm: true
confirmEvent: "mergeNewServers"
confirmArgument: newServers
setTimeout (-> Backbone.trigger 'openAlertDialog', options), 1000
# The user has confirmed that they want to merge the new servers in
# `newServers` into their current client-side list of servers.
mergeNewServers: (newServers) ->
serversCollection = @applicationSettings.get 'servers'
for s in newServers
s.id = @guid()
serversCollection.add(new ServerModel(s))
@applicationSettings.save()
# Fetch servers.json. This is a JSON object that contains an array of
# server objects. This allows the default list of (OLD/FieldDB) servers
# that this Dative knows about to be specified at runtime.
fetchServers: ->
url = 'servers.json'
$.ajax
url: url
type: 'GET'
dataType: 'json'
error: (jqXHR, textStatus, errorThrown) ->
console.log "Ajax request for #{url} threw an error:
#{errorThrown}"
@initializeContinue()
success: (serversArray, textStatus, jqXHR) =>
@addDefaultServers serversArray
# Size the #appview div relative to the window size
matchWindowDimensions: ->
@$('#appview').css height: $(window).height() - 50
$(window).resize =>
@$('#appview').css height: $(window).height() - 50
renderVisibleView: (taskId=null) ->
try
@__renderVisibleView__ taskId
catch
try
@__renderVisibleView__ taskId
catch
try
@__renderVisibleView__ taskId
__renderVisibleView__: (taskId=null) ->
if (@visibleView instanceof ResourceView)
@$('#appview')
.css 'overflow-y', 'scroll'
.html @visibleView.render().el
else
$appView = @$ '#appview'
$appView.css 'overflow-y', 'initial'
@visibleView.setElement $appView
@visibleView.render taskId
@rendered @visibleView
closeVisibleView: -> if @visibleView then @closeView @visibleView
closeVisibleViewInDialog: ->
if @visibleViewInDialog then @closeView @visibleViewInDialog
# Check if our application settings still thinks we're logged in.
loggedIn: ->
@loggedInFieldDB()
loggedIn = @applicationSettings.get 'loggedIn'
if loggedIn then @getOLDApplicationSettings()
loggedIn
# Check if FieldDB thinks we're logged in to a FieldDB. If it does, set
# `@loggedIn` to `true`, else `false`.
loggedInFieldDB: ->
if @applicationSettings.get('fieldDBApplication')
fieldDBApp = @applicationSettings.get 'fieldDBApplication'
if fieldDBApp.authentication and
fieldDBApp.authentication.user and
fieldDBApp.authentication.user.authenticated
@applicationSettings.set 'loggedIn', true
@applicationSettings.set 'loggedInUserRoles',
fieldDBApp.authentication.user.roles
else
@applicationSettings.set 'loggedIn', false
getOLDApplicationSettings: ->
if @activeServerType() is 'OLD'
@oldApplicationSettingsCollection.fetchResources()
showHomePageView: (logout=false) ->
if @preventNavigationState then @displayPreventNavigationAlert(); return
if (not logout) and @homePageView and (@visibleView is @homePageView)
return
@router.navigate 'home'
@closeVisibleView()
if not @homePageView then @homePageView = new HomePageView()
serversideHomepage = @applicationSettings.get 'homepage'
if serversideHomepage
@homePageView.setHTML(serversideHomepage.html,
serversideHomepage.heading)
else
@homePageView.setHTML null, null
@visibleView = @homePageView
@renderVisibleView()
homePageChanged: ->
if @homePageView
@homePageView.contentChanged()
############################################################################
# Show resources view machinery
############################################################################
# Render (and perhaps instantiate) a view over a collection of resources.
# This method works in conjunction with the metadata in the `@myResources`
# object; CRUCIALLY, only resources with an attribute in that object can be
# shown using this method. The simplest case is to call this method with
# the singular camelCase name of a resource as its first argument; e.g.,
# `@showResourcesView 'elicitationMethod'`.
showResourcesView: (resourceName, options={}) ->
if @preventNavigationState then @displayPreventNavigationAlert(); return
o = @showResourcesViewSetDefaultOptions resourceName, options
names = @getResourceNames resourceName
myViewAttr = "#{names.plural}View"
if o.authenticationRequired and not @loggedIn() then return
if o.searchable and o.search
@closeVisibleView()
@visibleView = null
if @[myViewAttr] and @visibleView is @[myViewAttr] then return
@router.navigate names.hypPlur
taskId = @guid()
Backbone.trigger 'longTask:register', "Opening #{names.regPlur} view",
taskId
@closeVisibleView()
if @[myViewAttr]
if @fieldDBCorpusHasChanged(myViewAttr, o)
@closeView @[myViewAttr]
@[myViewAttr] = @instantiateResourcesView resourceName, o
else
@[myViewAttr] = @instantiateResourcesView resourceName, o
@visibleView = @[myViewAttr]
@showNewResourceViewOption o
@showImportInterfaceOption o
@searchableOption o
@corpusElementOption o
@renderVisibleView taskId
# Render (and perhaps instantiate) a view over a collection of resources *in
# a modal dialog.* Compare to `showResourcesView`.
showResourcesViewInDialog: (resourceName, options={}) ->
o = @showResourcesViewSetDefaultOptions resourceName, options
names = @getResourceNames resourceName
myViewAttr = "#{names.plural}ViewInDialog"
if o.authenticationRequired and not @loggedIn() then return
if o.searchable and o.search
@closeVisibleViewInDialog()
@visibleViewInDialog = null
if @[myViewAttr] and @visibleViewInDialog is @[myViewAttr]
if @resourcesDisplayerDialog.isOpen()
return
@closeVisibleViewInDialog()
if @[myViewAttr]
if @fieldDBCorpusHasChanged(myViewAttr, o)
@closeView @[myViewAttr]
@[myViewAttr] = @instantiateResourcesView resourceName, o
else
@[myViewAttr] = @instantiateResourcesView resourceName, o
@visibleViewInDialog = @[myViewAttr]
@resourcesDisplayerDialog.showResourcesView @visibleViewInDialog
# Show the resource of type `resourceName` with id `resourceId` in the main
# page of the application. This is what happens when you navigate to, e.g.,
# /#form/123. This method also handles navigation to collections via their
# URL (i.e., path) values.
showResourceView: (resourceName, resourceId, options={}) ->
if @preventNavigationState then @displayPreventNavigationAlert(); return
o = @showResourceViewSetDefaultOptions resourceName, options
names = @getResourceNames resourceName
myViewAttr = "#{resourceName}View"
if o.authenticationRequired and not @loggedIn() then return
if @[myViewAttr] and @visibleView is @[myViewAttr] then return
@router.navigate "#{names.hyphen}/#{resourceId}"
@closeVisibleView()
@resourcesCollection =
new @myResources[resourceName].resourcesCollectionClass()
if @resourceModel then @stopListening @resourceModel
@resourceModel = new @myResources[resourceName].resourceModelClass(
{}, {collection: @resourcesCollection})
# Fetch a resource by its id value.
if _.isNumber(resourceId) or /^\d+$/.test(resourceId.trim())
# We have to listen and fetch here, which is different from
# `ResourcesView` sub-classes, which fetch their collections post-render.
@listenToOnce @resourceModel, "fetch#{names.capitalized}Fail",
(error, resourceModel) => @fetchResourceFail resourceName, resourceId
@listenToOnce @resourceModel, "fetch#{names.capitalized}Success",
(resourceObject) =>
@fetchResourceSuccess resourceName, myViewAttr, resourceObject
@resourceModel.fetchResource resourceId
# Fetch a collection by its url value.
else if resourceName is 'collection'
@listenToOnce @resourceModel, "searchFail",
(error) => @fetchResourceFail resourceName, resourceId, 'url'
@listenToOnce @resourceModel, "searchSuccess",
(responseJSON) =>
if @utils.type(responseJSON) is 'array' and responseJSON.length > 0
@fetchResourceSuccess resourceName, myViewAttr, responseJSON[0]
else
@fetchResourceFail resourceName, resourceId, 'url'
search =
filter: ["Collection", "url", "=", resourceId]
order_by: ["Form", "id", "desc" ]
@resourceModel.search search, null, false
else
@displayErrorPage "Sorry, there is no #{resourceName} with id
#{resourceId}"
# We failed to fetch the resource model data from the server.
fetchResourceFail: (resourceName, resourceId, attr='id') ->
@stopListening @resourceModel
@displayErrorPage "Sorry, there is no #{resourceName} with #{attr}
#{resourceId}"
# We succeeded in fetching the resource model data from the server,
# so we render a `ResourceView` subclass for it.
fetchResourceSuccess: (resourceName, myViewAttr, resourceObject) ->
@stopListening @resourceModel
@resourceModel.set resourceObject
@[myViewAttr] = new @myResources[resourceName].resourceViewClass
model: @resourceModel
dataLabelsVisible: true
expanded: true
@visibleView = @[myViewAttr]
@renderVisibleView()
displayErrorPage: (msg=null) ->
@router.navigate "error"
@closeVisibleView()
if not msg then msg = 'Sorry, an error occurred.'
@$('#appview').html(@getErrorPageHTML('Error', msg))
@$('.dative-error-page')
.css "border-color", @constructor.jQueryUIColors().defBo
getErrorPageHTML: (header, content) ->
"<div class='dative-error-page dative-resource-widget dative-form-object
dative-paginated-item dative-widget-center ui-corner-all expanded'>
<div class='dative-widget-header ui-widget-header ui-corner-top'>
<div class='dative-widget-header-title
container-center'>#{header}</div>
</div>
<div class='dative-widget-body'>#{content}</div>
</div>"
# We heard that a resource was destroyed. If the destroyed resource is the
# one that we are currently displaying, then we hide it, close it, and
# navigate to the home page.
destroyResourceSuccess: (resourceModel) ->
if @visibleView and
@visibleView.model is @resourceModel and
resourceModel.get('id') is @resourceModel.get('id') and
resourceModel instanceof @resourceModel.constructor
@visibleView.$el.slideUp
complete: =>
@closeVisibleView()
@showHomePageView()
# The information in this object controls how `@showResourcesView` behaves.
# The `resourceName` param of that method must be an attribute of this
# object. NOTE: default params not supplied here are filled in by
# `@showResourcesViewSetDefaultOptions`.
myResources:
applicationSetting:
resourcesViewClass: ApplicationSettingsView
resourceViewClass: null
resourceModelClass: null
resourcesCollectionClass: null
params:
authenticationRequired: false
needsAppSettings: true
collection:
resourcesViewClass: CollectionsView
resourceViewClass: CollectionView
resourceModelClass: CollectionModel
resourcesCollectionClass: CollectionsCollection
params:
searchable: true
corpus:
resourcesViewClass: CorporaView
resourceViewClass: null
resourceModelClass: null
resourcesCollectionClass: null
params:
needsAppSettings: true
needsActiveFieldDBCorpus: true
elicitationMethod:
resourcesViewClass: ElicitationMethodsView
resourceViewClass: ElicitationMethodView
resourceModelClass: ElicitationMethodModel
resourcesCollectionClass: ElicitationMethodsCollection
file:
resourcesViewClass: FilesView
resourceViewClass: FileView
resourceModelClass: FileModel
resourcesCollectionClass: FilesCollection
params:
searchable: true
form:
resourcesViewClass: FormsView
resourceViewClass: FormView
resourceModelClass: FormModel
resourcesCollectionClass: FormsCollection
params:
needsAppSettings: true
searchable: true
corpusElement: true
needsActiveFieldDBCorpus: true
importable: true
keyboard:
resourcesViewClass: KeyboardsView
resourceViewClass: KeyboardView
resourceModelClass: KeyboardModel
resourcesCollectionClass: KeyboardsCollection
languageModel:
resourcesViewClass: LanguageModelsView
resourceViewClass: LanguageModelView
resourceModelClass: LanguageModelModel
resourcesCollectionClass: LanguageModelsCollection
language:
resourcesViewClass: LanguagesView
resourceViewClass: LanguageView
resourceModelClass: LanguageModel
resourcesCollectionClass: LanguagesCollection
params:
searchable: true
morphologicalParser:
resourcesViewClass: MorphologicalParsersView
resourceViewClass: MorphologicalParserView
resourceModelClass: MorphologicalParserModel
resourcesCollectionClass: MorphologicalParsersCollection
morphology:
resourcesViewClass: MorphologiesView
resourceViewClass: MorphologyView
resourceModelClass: MorphologyModel
resourcesCollectionClass: MorphologiesCollection
orthography:
resourcesViewClass: OrthographiesView
resourceViewClass: OrthographyView
resourceModelClass: OrthographyModel
resourcesCollectionClass: OrthographiesCollection
page:
resourcesViewClass: PagesView
resourceViewClass: PageView
resourceModelClass: PageModel
resourcesCollectionClass: PagesCollection
phonology:
resourcesViewClass: PhonologiesView
resourceViewClass: PhonologyView
resourceModelClass: PhonologyModel
resourcesCollectionClass: PhonologiesCollection
search:
resourcesViewClass: SearchesView
resourceViewClass: SearchView
resourceModelClass: SearchModel
resourcesCollectionClass: SearchesCollection
params: