/
integration.js
2968 lines (2618 loc) · 100 KB
/
integration.js
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
"use strict";
/*
***** BEGIN LICENSE BLOCK *****
Copyright © 2009 Center for History and New Media
George Mason University, Fairfax, Virginia, USA
http://zotero.org
This file is part of Zotero.
Zotero is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Zotero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Zotero. If not, see <http://www.gnu.org/licenses/>.
***** END LICENSE BLOCK *****
*/
const DATA_VERSION = 3;
// Specifies that citations should only be updated if changed
const FORCE_CITATIONS_FALSE = 0;
// Specifies that citations should only be updated if formattedText has changed from what is encoded
// in the field code
const FORCE_CITATIONS_REGENERATE = 1;
// Specifies that citations should be reset regardless of whether formattedText has changed
const FORCE_CITATIONS_RESET_TEXT = 2;
// These must match the constants in corresponding word plugins
const DIALOG_ICON_STOP = 0;
const DIALOG_ICON_WARNING = 1;
const DIALOG_ICON_CAUTION = 2;
const DIALOG_BUTTONS_OK = 0;
const DIALOG_BUTTONS_OK_CANCEL = 1;
const DIALOG_BUTTONS_YES_NO = 2;
const DIALOG_BUTTONS_YES_NO_CANCEL = 3;
const NOTE_FOOTNOTE = 1;
const NOTE_ENDNOTE = 2;
const INTEGRATION_TYPE_ITEM = 1;
const INTEGRATION_TYPE_BIBLIOGRAPHY = 2;
const INTEGRATION_TYPE_TEMP = 3;
const DELAY_CITATIONS_PROMPT_TIMEOUT = 15/*seconds*/;
const DELAYED_CITATION_RTF_STYLING = "\\uldash";
const DELAYED_CITATION_RTF_STYLING_CLEAR = "\\ulclear";
const DELAYED_CITATION_HTML_STYLING = "<div class='delayed-zotero-citation-updates'>"
const DELAYED_CITATION_HTML_STYLING_END = "</div>"
Zotero.Integration = new function() {
Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/AddonManager.jsm");
this.currentWindow = false;
this.sessions = {};
/**
* Initializes the pipe used for integration on non-Windows platforms.
*/
this.init = function() {
// We only use an integration pipe on OS X.
// On Linux, we use the alternative communication method in the OOo plug-in
// On Windows, we use a command line handler for integration. See
// components/zotero-integration-service.js for this implementation.
if(!Zotero.isMac) return;
// Determine where to put the pipe
// on OS X, first try /Users/Shared for those who can't put pipes in their home
// directories
var pipe = null;
var sharedDir = Components.classes["@mozilla.org/file/local;1"].
createInstance(Components.interfaces.nsILocalFile);
sharedDir.initWithPath("/Users/Shared");
if(sharedDir.exists() && sharedDir.isDirectory()) {
var logname = Components.classes["@mozilla.org/process/environment;1"].
getService(Components.interfaces.nsIEnvironment).
get("LOGNAME");
var sharedPipe = sharedDir.clone();
sharedPipe.append(".zoteroIntegrationPipe_"+logname);
if(sharedPipe.exists()) {
if(this.deletePipe(sharedPipe) && sharedDir.isWritable()) {
pipe = sharedPipe;
}
} else if(sharedDir.isWritable()) {
pipe = sharedPipe;
}
}
if(!pipe) {
// on other platforms, or as a fallback, use home directory
pipe = Components.classes["@mozilla.org/file/directory_service;1"].
getService(Components.interfaces.nsIProperties).
get("Home", Components.interfaces.nsIFile);
pipe.append(".zoteroIntegrationPipe");
// destroy old pipe, if one exists
if(!this.deletePipe(pipe)) return;
}
// try to initialize pipe
try {
this.initPipe(pipe);
} catch(e) {
Zotero.logError(e);
}
}
/**
* Begin listening for integration commands on the given pipe
* @param {String} pipe The path to the pipe
*/
this.initPipe = function(pipe) {
Zotero.IPC.Pipe.initPipeListener(pipe, function(string) {
if(string != "") {
// exec command if possible
var parts = string.match(/^([^ \n]*) ([^ \n]*)(?: ([^\n]*))?\n?$/);
if(parts) {
var agent = parts[1].toString();
var cmd = parts[2].toString();
var document = parts[3] ? parts[3].toString() : null;
Zotero.Integration.execCommand(agent, cmd, document);
} else {
Components.utils.reportError("Zotero: Invalid integration input received: "+string);
}
}
});
}
/**
* Deletes a defunct pipe on OS X
*/
this.deletePipe = function(pipe) {
try {
if(pipe.exists()) {
Zotero.IPC.safePipeWrite(pipe, "Zotero shutdown\n");
pipe.remove(false);
}
return true;
} catch (e) {
// if pipe can't be deleted, log an error
Zotero.debug("Error removing old integration pipe "+pipe.path, 1);
Zotero.logError(e);
Components.utils.reportError(
"Zotero word processor integration initialization failed. "
+ "See http://forums.zotero.org/discussion/12054/#Item_10 "
+ "for instructions on correcting this problem."
);
// can attempt to delete on OS X
try {
var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
.getService(Components.interfaces.nsIPromptService);
var deletePipe = promptService.confirm(null, Zotero.getString("integration.error.title"), Zotero.getString("integration.error.deletePipe"));
if(!deletePipe) return false;
let escapedFifoFile = pipe.path.replace("'", "'\\''");
Zotero.Utilities.Internal.executeAppleScript("do shell script \"rmdir '"+escapedFifoFile+"'; rm -f '"+escapedFifoFile+"'\" with administrator privileges", true);
if(pipe.exists()) return false;
} catch(e) {
Zotero.logError(e);
return false;
}
}
}
this.resetSessionStyles = Zotero.Promise.coroutine(function* (){
for (let sessionID in Zotero.Integration.sessions) {
let session = Zotero.Integration.sessions[sessionID];
yield session.setData(session.data, true);
}
});
this.getApplication = function(agent, command, docId) {
if (agent == 'http') {
return new Zotero.HTTPIntegrationClient.Application();
}
// Try to load the appropriate Zotero component; otherwise display an error
var component
try {
var componentClass = "@zotero.org/Zotero/integration/application?agent="+agent+";1";
Zotero.debug("Integration: Instantiating "+componentClass+" for command "+command+(docId ? " with doc "+docId : ""));
try {
return Components.classes[componentClass]
.getService(Components.interfaces.zoteroIntegrationApplication);
} catch (e) {
return Components.classes[componentClass]
.getService(Components.interfaces.nsISupports).wrappedJSObject;
}
} catch(e) {
throw new Zotero.Exception.Alert("integration.error.notInstalled",
[], "integration.error.title");
}
},
/**
* Executes an integration command, first checking to make sure that versions are compatible
*/
this.execCommand = async function(agent, command, docId) {
var document, session;
if (Zotero.Integration.currentDoc) {
Zotero.Utilities.Internal.activate();
if(Zotero.Integration.currentWindow && !Zotero.Integration.currentWindow.closed) {
Zotero.Integration.currentWindow.focus();
}
Zotero.debug("Integration: Request already in progress; not executing "+agent+" "+command);
return;
}
Zotero.Integration.currentDoc = true;
Zotero.debug(`Integration: ${agent}-${command}${docId ? `:'${docId}'` : ''} invoked`)
var startTime = (new Date()).getTime();
// Try to execute the command; otherwise display an error in alert service or word processor
// (depending on what is possible)
try {
// Word for windows throws RPC_E_CANTCALLOUT_ININPUTSYNCCALL if we invoke an OLE call in the
// current event loop (which.. who would have guessed would be the case?)
await Zotero.Promise.delay();
var application = Zotero.Integration.getApplication(agent, command, docId);
var documentPromise = (application.getDocument && docId ? application.getDocument(docId) : application.getActiveDocument());
if (!documentPromise.then) {
Zotero.debug('Synchronous integration plugin functions are deprecated -- ' +
'update to asynchronous methods');
application = Zotero.Integration.LegacyPluginWrapper(application);
documentPromise = new Zotero.Promise(resolve =>
resolve(Zotero.Integration.LegacyPluginWrapper.wrapDocument(documentPromise)));
}
Zotero.Integration.currentDoc = document = await documentPromise;
Zotero.Integration.currentSession = session = await Zotero.Integration.getSession(application, document, agent);
// TODO: this is a pretty awful circular dependence
session.fields = new Zotero.Integration.Fields(session, document);
// TODO: figure this out
// Zotero.Notifier.trigger('delete', 'collection', 'document');
await (new Zotero.Integration.Interface(application, document, session))[command]();
await document.setDocumentData(session.data.serialize());
}
catch (e) {
if(!(e instanceof Zotero.Exception.UserCancelled)) {
try {
var displayError = null;
if(e instanceof Zotero.Exception.Alert) {
displayError = e.message;
} else {
if(e.toString().indexOf("ExceptionAlreadyDisplayed") === -1) {
displayError = Zotero.getString("integration.error.generic")+"\n\n"+(e.message || e.toString());
}
if(e.stack) {
Zotero.debug(e.stack);
}
}
if(displayError) {
if (Zotero.Integration.currentSession && Zotero.Integration.currentSession.progressBar) {
Zotero.Promise.delay(5).then(function() {
Zotero.Integration.currentSession.progressBar.hide();
});
}
var showErrorInFirefox = !document;
if(document) {
try {
await document.activate();
await document.displayAlert(displayError, DIALOG_ICON_STOP, DIALOG_BUTTONS_OK);
} catch(e) {
showErrorInFirefox = true;
}
}
if(showErrorInFirefox) {
Zotero.Utilities.Internal.activate();
Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
.getService(Components.interfaces.nsIPromptService)
.alert(null, Zotero.getString("integration.error.title"), displayError);
}
}
} finally {
Zotero.logError(e);
}
} else {
// If user cancels we should still write the currently assigned session ID
await document.setDocumentData(session.data.serialize());
}
}
finally {
var diff = ((new Date()).getTime() - startTime)/1000;
Zotero.debug(`Integration: ${agent}-${command}${docId ? `:'${docId}'` : ''} complete in ${diff}s`)
if (document) {
try {
await document.cleanup();
await document.activate();
// Call complete function if one exists
if (document.wrappedJSObject && document.wrappedJSObject.complete) {
document.wrappedJSObject.complete();
} else if (document.complete) {
await document.complete();
}
} catch(e) {
Zotero.logError(e);
}
}
if(Zotero.Integration.currentWindow && !Zotero.Integration.currentWindow.closed) {
var oldWindow = Zotero.Integration.currentWindow;
Zotero.Promise.delay(100).then(function() {
oldWindow.close();
});
}
if (Zotero.Integration.currentSession && Zotero.Integration.currentSession.progressBar) {
Zotero.Promise.delay(5).then(function() {
Zotero.Integration.currentSession.progressBar.hide();
});
}
// This technically shouldn't be necessary since we call document.activate(),
// but http integration plugins may not have OS level access to windows to be
// able to activate themselves. E.g. Google Docs on Safari.
if (Zotero.isMac && agent == 'http') {
Zotero.Utilities.Internal.sendToBack();
}
Zotero.Integration.currentDoc = Zotero.Integration.currentWindow = false;
}
};
/**
* Displays a dialog in a modal-like fashion without hanging the thread
* @param {String} url The chrome:// URI of the window
* @param {String} [options] Options to pass to the window
* @param {String} [io] Data to pass to the window
* @return {Promise} Promise resolved when the window is closed
*/
this.displayDialog = async function displayDialog(url, options, io) {
Zotero.debug(`Integration: Displaying dialog ${url}`);
await Zotero.Integration.currentDoc.cleanup();
Zotero.Integration.currentSession && await Zotero.Integration.currentSession.progressBar.hide(true);
var allOptions = 'chrome,centerscreen';
// without this, Firefox gets raised with our windows under Compiz
if(Zotero.isLinux) allOptions += ',dialog=no';
if(options) allOptions += ','+options;
var window = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
.getService(Components.interfaces.nsIWindowWatcher)
.openWindow(null, url, '', allOptions, (io ? io : null));
Zotero.Integration.currentWindow = window;
Zotero.Utilities.Internal.activate(window);
var deferred = Zotero.Promise.defer();
var listener = function() {
if(window.location.toString() === "about:blank") return;
if(window.newWindow) {
window = window.newWindow;
Zotero.Integration.currentWindow = window;
window.addEventListener("unload", listener, false);
return;
}
Zotero.Integration.currentWindow = false;
deferred.resolve();
}
window.addEventListener("unload", listener, false);
await deferred.promise;
// We do not want to redisplay the progress bar if this window close
// was the final close of the integration command
await Zotero.Promise.delay(10);
if (Zotero.Integration.currentDoc && Zotero.Integration.currentSession
&& Zotero.Integration.currentSession.progressBar) {
Zotero.Integration.currentSession.progressBar.show();
}
};
/**
* Gets a session for a given doc.
* Either loads a cached session if doc communicated since restart or creates a new one
* @return {Zotero.Integration.Session} Promise
*/
this.getSession = async function (app, doc, agent) {
try {
var progressBar = new Zotero.Integration.Progress(4, Zotero.isMac && agent != 'http');
progressBar.show();
var dataString = await doc.getDocumentData(),
data, session;
try {
data = new Zotero.Integration.DocumentData(dataString);
} catch(e) {
data = new Zotero.Integration.DocumentData();
}
if (data.prefs.fieldType) {
if (data.dataVersion < DATA_VERSION) {
if (data.dataVersion == 1
&& data.prefs.fieldType == "Field"
&& app.primaryFieldType == "ReferenceMark") {
// Converted OOo docs use ReferenceMarks, not fields
data.prefs.fieldType = "ReferenceMark";
}
var warning = await doc.displayAlert(Zotero.getString("integration.upgradeWarning", [Zotero.clientName, '5.0']),
DIALOG_ICON_WARNING, DIALOG_BUTTONS_OK_CANCEL);
if (!warning) {
throw new Zotero.Exception.UserCancelled("document upgrade");
}
// Don't throw for version 4(JSON) during the transition from 4.0 to 5.0
} else if ((data.dataVersion > DATA_VERSION) && data.dataVersion != 4) {
throw new Zotero.Exception.Alert("integration.error.newerDocumentVersion",
[data.zoteroVersion, Zotero.version], "integration.error.title");
}
if (data.prefs.fieldType !== app.primaryFieldType
&& data.prefs.fieldType !== app.secondaryFieldType) {
throw new Zotero.Exception.Alert("integration.error.fieldTypeMismatch",
[], "integration.error.title");
}
session = Zotero.Integration.sessions[data.sessionID];
}
// Make sure we don't maintain the session if agent changes (i.e. LO -> Word)
// and display wrong field types in doc preferences.
if (!session || session.agent != agent) {
session = new Zotero.Integration.Session(doc, app);
session.reload = true;
}
try {
await session.setData(data);
} catch(e) {
// make sure style is defined
if (e instanceof Zotero.Exception.Alert && e.name === "integration.error.invalidStyle") {
if (data.style.styleID) {
let trustedSource = /^https?:\/\/(www\.)?(zotero\.org|citationstyles\.org)/.test(data.style.styleID);
let errorString = Zotero.getString("integration.error.styleMissing", data.style.styleID);
if (trustedSource ||
await doc.displayAlert(errorString, DIALOG_ICON_WARNING, DIALOG_BUTTONS_YES_NO)) {
let installed = false;
try {
let { styleTitle, styleID } = await Zotero.Styles.install(
{url: data.style.styleID}, data.style.styleID, true
);
data.style.styleID = styleID;
installed = true;
}
catch (e) {
await doc.displayAlert(
Zotero.getString(
'integration.error.styleNotFound', data.style.styleID
),
DIALOG_ICON_WARNING,
DIALOG_BUTTONS_OK
);
}
if (installed) {
await session.setData(data, true);
} else {
await session.setDocPrefs();
}
} else {
await session.setDocPrefs();
}
} else {
await session.setDocPrefs();
}
} else {
throw e;
}
}
} catch (e) {
progressBar.hide(true);
throw e;
}
session.agent = agent;
session._doc = doc;
if (session.progressBar) {
progressBar.reset();
progressBar.segments = session.progressBar.segments;
}
session.progressBar = progressBar;
return session;
};
}
/**
* An exception thrown when a document contains an item that no longer exists in the current document.
*/
Zotero.Integration.MissingItemException = function(item) {this.item = item;};
Zotero.Integration.MissingItemException.prototype = {
"name":"MissingItemException",
"message":`An item in this document is missing from your Zotero library.}`,
"toString":function() { return this.message + `\n ${JSON.stringify(this.item)}` }
};
Zotero.Integration.NO_ACTION = 0;
Zotero.Integration.UPDATE = 1;
Zotero.Integration.DELETE = 2;
Zotero.Integration.REMOVE_CODE = 3;
/**
* All methods for interacting with a document
* @constructor
*/
Zotero.Integration.Interface = function(app, doc, session) {
this._app = app;
this._doc = doc;
this._session = session;
}
/**
* Adds a citation to the current document.
* @return {Promise}
*/
Zotero.Integration.Interface.prototype.addCitation = Zotero.Promise.coroutine(function* () {
yield this._session.init(false, false);
let [idx, field, citation] = yield this._session.fields.addEditCitation(null);
yield this._session.addCitation(idx, yield field.getNoteIndex(), citation);
if (this._session.data.prefs.delayCitationUpdates) {
return this._session.writeDelayedCitation(idx, field, citation);
} else {
return this._session.fields.updateDocument(FORCE_CITATIONS_FALSE, false, false);
}
});
/**
* Edits the citation at the cursor position.
* @return {Promise}
*/
Zotero.Integration.Interface.prototype.editCitation = Zotero.Promise.coroutine(function* () {
yield this._session.init(true, false);
var docField = yield this._doc.cursorInField(this._session.data.prefs['fieldType']);
if(!docField) {
throw new Zotero.Exception.Alert("integration.error.notInCitation", [],
"integration.error.title");
}
return this.addEditCitation(docField);
});
/**
* Edits the citation at the cursor position if one exists, or else adds a new one.
* @return {Promise}
*/
Zotero.Integration.Interface.prototype.addEditCitation = async function (docField) {
await this._session.init(false, false);
docField = docField || await this._doc.cursorInField(this._session.data.prefs['fieldType']);
let [idx, field, citation] = await this._session.fields.addEditCitation(docField);
await this._session.addCitation(idx, await field.getNoteIndex(), citation);
if (this._session.data.prefs.delayCitationUpdates) {
return this._session.writeDelayedCitation(idx, field, citation);
} else {
return this._session.fields.updateDocument(FORCE_CITATIONS_FALSE, false, false);
}
};
/**
* Adds a bibliography to the current document.
* @return {Promise}
*/
Zotero.Integration.Interface.prototype.addBibliography = Zotero.Promise.coroutine(function* () {
var me = this;
yield this._session.init(true, false);
// Make sure we can have a bibliography
if(!me._session.data.style.hasBibliography) {
throw new Zotero.Exception.Alert("integration.error.noBibliography", [],
"integration.error.title");
}
let field = new Zotero.Integration.BibliographyField(yield this._session.fields.addField());
var citationsMode = FORCE_CITATIONS_FALSE;
yield field.clearCode();
if(this._session.data.prefs.delayCitationUpdates) {
// Refreshes citeproc state before proceeding
this._session.reload = true;
citationsMode = FORCE_CITATIONS_REGENERATE;
}
yield this._session.fields.updateSession(citationsMode);
yield this._session.fields.updateDocument(citationsMode, true, false);
})
/**
* Edits bibliography metadata.
* @return {Promise}
*/
Zotero.Integration.Interface.prototype.editBibliography = Zotero.Promise.coroutine(function*() {
// Make sure we have a bibliography
yield this._session.init(true, false);
var fields = yield this._session.fields.get();
var bibliographyField;
for (let i = fields.length-1; i >= 0; i--) {
let field = yield Zotero.Integration.Field.loadExisting(fields[i]);
if (field.type == INTEGRATION_TYPE_BIBLIOGRAPHY) {
bibliographyField = field;
break;
}
}
if(!bibliographyField) {
throw new Zotero.Exception.Alert("integration.error.mustInsertBibliography",
[], "integration.error.title");
}
let bibliography = new Zotero.Integration.Bibliography(bibliographyField, yield bibliographyField.unserialize());
var citationsMode = FORCE_CITATIONS_FALSE;
if(this._session.data.prefs.delayCitationUpdates) {
// Refreshes citeproc state before proceeding
this._session.reload = true;
citationsMode = FORCE_CITATIONS_REGENERATE;
}
yield this._session.fields.updateSession(citationsMode);
yield this._session.editBibliography(bibliography);
yield this._session.fields.updateDocument(citationsMode, true, false);
});
Zotero.Integration.Interface.prototype.addEditBibliography = Zotero.Promise.coroutine(function *() {
// Check if we have a bibliography
yield this._session.init(true, false);
if (!this._session.data.style.hasBibliography) {
throw new Zotero.Exception.Alert("integration.error.noBibliography", [],
"integration.error.title");
}
var fields = yield this._session.fields.get();
var bibliographyField;
for (let i = fields.length-1; i >= 0; i--) {
let field = yield Zotero.Integration.Field.loadExisting(fields[i]);
if (field.type == INTEGRATION_TYPE_BIBLIOGRAPHY) {
bibliographyField = field;
break;
}
}
var newBibliography = !bibliographyField;
if (!bibliographyField) {
bibliographyField = new Zotero.Integration.BibliographyField(yield this._session.fields.addField());
yield bibliographyField.clearCode();
}
let bibliography = new Zotero.Integration.Bibliography(bibliographyField, yield bibliographyField.unserialize());
var citationsMode = FORCE_CITATIONS_FALSE;
if(this._session.data.prefs.delayCitationUpdates) {
// Refreshes citeproc state before proceeding
this._session.reload = true;
citationsMode = FORCE_CITATIONS_REGENERATE;
}
yield this._session.fields.updateSession(citationsMode);
if (!newBibliography) yield this._session.editBibliography(bibliography);
yield this._session.fields.updateDocument(citationsMode, true, false);
});
/**
* Updates the citation data for all citations and bibliography entries.
* @return {Promise}
*/
Zotero.Integration.Interface.prototype.refresh = async function() {
await this._session.init(true, false)
this._session.reload = this._session.reload || this._session.data.prefs.delayCitationUpdates;
await this._session.fields.updateSession(FORCE_CITATIONS_REGENERATE)
await this._session.fields.updateDocument(FORCE_CITATIONS_REGENERATE, true, false);
}
/**
* Deletes field codes.
* @return {Promise}
*/
Zotero.Integration.Interface.prototype.removeCodes = Zotero.Promise.coroutine(function* () {
var me = this;
yield this._session.init(true, false)
let fields = yield this._session.fields.get()
var result = yield me._doc.displayAlert(Zotero.getString("integration.removeCodesWarning"),
DIALOG_ICON_WARNING, DIALOG_BUTTONS_OK_CANCEL);
if (result) {
for(var i=fields.length-1; i>=0; i--) {
yield fields[i].removeCode();
}
}
})
/**
* Displays a dialog to set document preferences (style, footnotes/endnotes, etc.)
* @return {Promise}
*/
Zotero.Integration.Interface.prototype.setDocPrefs = Zotero.Promise.coroutine(function* () {
var oldData;
let haveSession = yield this._session.init(false, true);
if(!haveSession) {
// This is a brand new document; don't try to get fields
oldData = yield this._session.setDocPrefs();
} else {
// Can get fields while dialog is open
oldData = yield Zotero.Promise.all([
this._session.fields.get(),
this._session.setDocPrefs()
]).spread(function (fields, setDocPrefs) {
// Only return value from setDocPrefs
return setDocPrefs;
});
}
// If oldData is null, then there was no document data, so we don't need to update
// fields
if (!oldData) return false;
// Perform noteType or fieldType conversion
let fields = yield this._session.fields.get();
var convertBibliographies = oldData.prefs.fieldType != this._session.data.prefs.fieldType;
var convertItems = convertBibliographies
|| oldData.prefs.noteType != this._session.data.prefs.noteType;
var fieldsToConvert = new Array();
var fieldNoteTypes = new Array();
for (var i=0, n=fields.length; i<n; i++) {
let field = yield Zotero.Integration.Field.loadExisting(fields[i]);
if (convertItems && field.type === INTEGRATION_TYPE_ITEM) {
var citation = yield field.unserialize();
if (!citation.properties.dontUpdate) {
fieldsToConvert.push(fields[i]);
fieldNoteTypes.push(this._session.data.prefs.noteType);
}
} else if(convertBibliographies
&& field.type === INTEGRATION_TYPE_BIBLIOGRAPHY) {
fieldsToConvert.push(fields[i]);
fieldNoteTypes.push(0);
}
}
if(fieldsToConvert.length) {
// Pass to conversion function
yield this._doc.convert(fieldsToConvert,
this._session.data.prefs.fieldType, fieldNoteTypes,
fieldNoteTypes.length);
}
// Refresh contents
this._session.fields = new Zotero.Integration.Fields(this._session, this._doc);
this._session.fields.ignoreEmptyBibliography = false;
if (this._session.data.prefs.delayCitationUpdates && !fieldsToConvert.length) return;
yield this._session.fields.updateSession(FORCE_CITATIONS_RESET_TEXT);
return this._session.fields.updateDocument(FORCE_CITATIONS_RESET_TEXT, true, true);
});
/**
* An exceedingly simple nsISimpleEnumerator implementation
*/
Zotero.Integration.JSEnumerator = function(objArray) {
this.objArray = objArray;
}
Zotero.Integration.JSEnumerator.prototype.hasMoreElements = function() {
return this.objArray.length;
}
Zotero.Integration.JSEnumerator.prototype.getNext = function() {
return this.objArray.shift();
}
/**
* Methods for retrieving fields from a document
* @constructor
*/
Zotero.Integration.Fields = function(session, doc) {
this.ignoreEmptyBibliography = true;
// Callback called while retrieving fields with the percentage complete.
this.progressCallback = null;
this._session = session;
this._doc = doc;
this._removeCodeFields = {};
this._deleteFields = {};
this._bibliographyFields = [];
}
/**
* Checks that it is appropriate to add fields to the current document at the current
* position, then adds one.
*/
Zotero.Integration.Fields.prototype.addField = async function(note) {
// Get citation types if necessary
if (!await this._doc.canInsertField(this._session.data.prefs['fieldType'])) {
return Zotero.Promise.reject(new Zotero.Exception.Alert("integration.error.cannotInsertHere",
[], "integration.error.title"));
}
var field = await this._doc.cursorInField(this._session.data.prefs['fieldType']);
if (field) {
if (!await this._session.displayAlert(Zotero.getString("integration.replace"),
DIALOG_ICON_STOP,
DIALOG_BUTTONS_OK_CANCEL)) {
return Zotero.Promise.reject(new Zotero.Exception.UserCancelled("inserting citation"));
}
}
if (!field) {
field = await this._doc.insertField(this._session.data.prefs['fieldType'],
(note ? this._session.data.prefs["noteType"] : 0));
// Older doc plugins do not initialize the field code to anything meaningful
// so we ensure it here manually
field.setCode('TEMP');
}
// If fields already retrieved, further this.get() calls will returned the cached version
// So we append this field to that list
if (this._fields) {
this._fields.push(field);
}
return Zotero.Promise.resolve(field);
}
/**
* Gets all fields for a document
* @return {Promise} Promise resolved with field list.
*/
Zotero.Integration.Fields.prototype.get = new function() {
var deferred;
return async function() {
// If we already have fields, just return them
if(this._fields != undefined) {
return this._fields;
}
if (deferred) {
return deferred.promise;
}
deferred = Zotero.Promise.defer();
var promise = deferred.promise;
// Otherwise, start getting fields
var timer = new Zotero.Integration.Timer();
timer.start();
this._session.progressBar.start();
try {
var fields = this._fields = Array.from(await this._doc.getFields(this._session.data.prefs['fieldType']));
var retrieveTime = timer.stop();
this._session.progressBar.finishSegment();
Zotero.debug("Integration: Retrieved " + fields.length + " fields in " +
retrieveTime + "; " + fields.length/retrieveTime + " fields/second");
deferred.resolve(fields);
} catch(e) {
deferred.reject(e);
}
deferred = null;
return promise;
}
}
/**
* Updates Zotero.Integration.Session attached to Zotero.Integration.Fields in line with document
*/
Zotero.Integration.Fields.prototype.updateSession = Zotero.Promise.coroutine(function* (forceCitations) {
yield this.get();
this._session.resetRequest(this._doc);
this._removeCodeFields = {};
this._deleteFields = {};
this._bibliographyFields = [];
var timer = new Zotero.Integration.Timer();
timer.start();
this._session.progressBar.start();
if (forceCitations) {
this._session.regenAll = true;
}
yield this._processFields();
this._session.regenAll = false;
var updateTime = timer.stop();
this._session.progressBar.finishSegment();
Zotero.debug("Integration: Updated session data for " + this._fields.length + " fields in "
+ updateTime + "; " + this._fields.length/updateTime + " fields/second");
if (this._session.reload) {
this._session.restoreProcessorState();
delete this._session.reload;
}
});
/**
* Keep processing fields until all have been processed
*/
Zotero.Integration.Fields.prototype._processFields = Zotero.Promise.coroutine(function* () {
if (!this._fields) {
throw new Error("_processFields called without fetching fields first");
}
for (var i = 0; i < this._fields.length; i++) {
let field = yield Zotero.Integration.Field.loadExisting(this._fields[i]);
if (field.type === INTEGRATION_TYPE_ITEM) {
var noteIndex = yield field.getNoteIndex(),
data = yield field.unserialize(),
citation = new Zotero.Integration.Citation(field, data, noteIndex);
yield this._session.addCitation(i, noteIndex, citation);
} else if (field.type === INTEGRATION_TYPE_BIBLIOGRAPHY) {
if (this.ignoreEmptyBibliography && (yield field.getText()).trim() === "") {
this._removeCodeFields[i] = true;
} else {
this._bibliographyFields.push(field);
}
}
}
if (this._bibliographyFields.length) {
var data = yield this._bibliographyFields[0].unserialize()
this._session.bibliography = new Zotero.Integration.Bibliography(this._bibliographyFields[0], data);
yield this._session.bibliography.loadItemData();
} else {
delete this._session.bibliography;
}
// TODO: figure this out
// Zotero.Notifier.trigger('add', 'collection', 'document');
});
/**
* Updates bibliographies and fields within a document
* @param {Boolean} forceCitations Whether to regenerate all citations
* @param {Boolean} forceBibliography Whether to regenerate all bibliography entries
* @param {Boolean} [ignoreCitationChanges] Whether to ignore changes to citations that have been
* modified since they were created, instead of showing a warning
* @return {Promise} A promise resolved when the document is updated
*/
Zotero.Integration.Fields.prototype.updateDocument = Zotero.Promise.coroutine(function* (forceCitations, forceBibliography,
ignoreCitationChanges) {
this._session.timer = new Zotero.Integration.Timer();
this._session.timer.start();
this._session.progressBar.start();
yield this._session._updateCitations()
this._session.progressBar.finishSegment();
this._session.progressBar.start();
yield this._updateDocument(forceCitations, forceBibliography, ignoreCitationChanges)
this._session.progressBar.finishSegment();
var diff = this._session.timer.stop();
this._session.timer = null;
Zotero.debug(`Integration: updateDocument complete in ${diff}s`)
// If the update takes longer than 5s suggest delaying citation updates
if (diff > DELAY_CITATIONS_PROMPT_TIMEOUT && !this._session.data.prefs.dontAskDelayCitationUpdates && !this._session.data.prefs.delayCitationUpdates) {
yield this._doc.activate();
var interfaceType = 'tab';
if (['MacWord2008', 'OpenOffice'].includes(this._session.agent)) {
interfaceType = 'toolbar';
}
var result = yield this._session.displayAlert(
Zotero.getString('integration.delayCitationUpdates.alert.text1')
+ "\n\n"
+ Zotero.getString(`integration.delayCitationUpdates.alert.text2.${interfaceType}`)
+ "\n\n"
+ Zotero.getString('integration.delayCitationUpdates.alert.text3'),
DIALOG_ICON_WARNING,
DIALOG_BUTTONS_YES_NO_CANCEL
);
if (result == 2) {
this._session.data.prefs.delayCitationUpdates = true;
}
if (result) {
this._session.data.prefs.dontAskDelayCitationUpdates = true;
// yield this._session.setDocPrefs(true);
}
}
});
/**
* Helper function to update bibliographys and fields within a document
* @param {Boolean} forceCitations Whether to regenerate all citations
* @param {Boolean} forceBibliography Whether to regenerate all bibliography entries
* @param {Boolean} [ignoreCitationChanges] Whether to ignore changes to citations that have been
* modified since they were created, instead of showing a warning