Grammalecte  Diff

Differences From Artifact [a0e3390e07]:

To Artifact [fefd8da4f7]:


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
1
2
3
4
5
6
7
8

9
10


11
12
13



14


15
16






17
18
19
20
21
22
23








-
+

-
-
+
+

-
-
-

-
-
+
+
-
-
-
-
-
-







// JavaScript

"use strict";


const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
const { require } = Cu.import("resource://gre/modules/commonjs/toolkit/require.js", {});
//const { require } = Cu.import("resource://gre/modules/commonjs/toolkit/require.js", {});

const { BasePromiseWorker } = Cu.import('resource://gre/modules/PromiseWorker.jsm', {});
const Task = Cu.import("resource://gre/modules/Task.jsm").Task;
const { BasePromiseWorker } = ChromeUtils.import('resource://gre/modules/PromiseWorker.jsm', {});
const Task = ChromeUtils.import("resource://gre/modules/Task.jsm").Task;
const prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("extensions.grammarchecker.");
//Cu.import("resource://gre/modules/Console.jsm"); // doesn’t work
//const xConsole = Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService);
//xConsole.logStringMessage("Grammalecte: " + args.join(" · ")); // useless now. Use: Services.console.logStringMessage("***");

const text = require("resource://grammalecte/text.js");
const tf = require("resource://grammalecte/fr/textformatter.js");
//const text = require("resource://grammalecte/text.js");
//const tf = require("resource://grammalecte/fr/textformatter.js");


function echo (...args) {
    dump(args.join(" -- ") + "\n");  // obsolete since TB 52?
    Services.console.logStringMessage("Grammalecte: " + args.join(" · "));
}


const oConverterToExponent = {
    dNumbers: new Map ([
        ["1", "¹"], ["2", "²"], ["3", "³"], ["4", "⁴"], ["5", "⁵"],
        ["6", "⁶"], ["7", "⁷"], ["8", "⁸"], ["9", "⁹"], ["0", "⁰"]
    ]),
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
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







-
+





-
+








-
+

-
+





-
+



-
-
+
+

-
+

-
+



-
+






-
+


-
+


-
+

-
+



-
+



-
+


-
+

-
+






-
+


-
+

-
+








var oGrammarChecker = {
    // you must use var to be able to call this object from elsewhere
    xGCEWorker: null,
    loadGC: function () {
        if (this.xGCEWorker === null) {
            // Grammar checker
            echo('Loading Grammalecte');
            console.log('Loading Grammalecte');
            this.xGCEWorker = new BasePromiseWorker('chrome://promiseworker/content/gce_worker.js');
            let that = this;
            let xPromise = this.xGCEWorker.post('loadGrammarChecker', [prefs.getCharPref("sGCOptions"), "Thunderbird"]);
            xPromise.then(
                function (aVal) {
                    echo(aVal);
                    console.log(aVal);
                    prefs.setCharPref("sGCOptions", aVal);
                    if (prefs.getBoolPref("bPersonalDictionary")) {
                        let sDicJSON = oFileHandler.loadFile("fr.personal.json");
                        if (sDicJSON) {
                            that.xGCEWorker.post('setDictionary', ["personal", sDicJSON]);
                        }
                    }
                },
                function (aReason) { echo('Promise rejected - ', aReason); }
                function (aReason) { console.log('Promise rejected - ', aReason); }
            ).catch(
                function (aCaught) { echo('Promise Error - ', aCaught); }
                function (aCaught) { console.log('Promise Error - ', aCaught); }
            );

        }
    },
    fullTests: function () {
        echo('Performing tests... Wait...');
        console.log('Performing tests... Wait...');
        let xPromise = this.xGCEWorker.post('fullTests', ['{"nbsp":true, "esp":true, "unit":true, "num":true}']);
        xPromise.then(
            function (aVal) {
                echo('Done.');
                echo(aVal);
                console.log('Done.');
                console.log(aVal);
            },
            function (aReason) { echo('Promise rejected', aReason); }
            function (aReason) { console.log('Promise rejected', aReason); }
        ).catch(
            function (aCaught) { echo('Promise Error', aCaught); }
            function (aCaught) { console.log('Promise Error', aCaught); }
        );
    },
    test: function (sText) {
        echo("Test...");
        console.log("Test...");
        let xPromise = this.xGCEWorker.post('parse', [sText, "FR", true]);
        xPromise.then(
            function (aVal) {
                let lErr = JSON.parse(aVal);
                if (lErr.length > 0) {
                    for (let dErr of lErr) {
                        echo(text.getReadableError(dErr));
                        console.log(text.getReadableError(dErr));
                    }
                } else {
                    echo("no error found");
                    console.log("no error found");
                }
            },
            function (aReason) { echo('Promise rejected', aReason); }
            function (aReason) { console.log('Promise rejected', aReason); }
        ).catch(
            function (aCaught) { echo('Promise Error', aCaught); }
            function (aCaught) { console.log('Promise Error', aCaught); }
        );
    },
    setOptions: function () {
        echo('Set options');
        console.log('Set options');
        let xPromise = this.xGCEWorker.post('setOptions', [prefs.getCharPref("sGCOptions")]);
        xPromise.then(
            function (aVal) {
                echo(aVal);
                console.log(aVal);
                prefs.setCharPref("sGCOptions", aVal);
            },
            function (aReason) { echo('Promise rejected', aReason); }
            function (aReason) { console.log('Promise rejected', aReason); }
        ).catch(
            function (aCaught) { echo('Promise Error', aCaught); }
            function (aCaught) { console.log('Promise Error', aCaught); }
        );
    },
    resetOptions: function () {
        let xPromise = this.xGCEWorker.post('resetOptions');
        xPromise.then(
            function (aVal) {
                echo(aVal);
                console.log(aVal);
                prefs.setCharPref("sGCOptions", aVal);
            },
            function (aReason) { echo('Promise rejected', aReason); }
            function (aReason) { console.log('Promise rejected', aReason); }
        ).catch(
            function (aCaught) { echo('Promise Error', aCaught); }
            function (aCaught) { console.log('Promise Error', aCaught); }
        );
    },
    _getGCResultPromise: function (sParagraph, sLang, bDebug, bContext) {
        // For some reason, you can’t use result of PromiseWorker within a Task,
        // you have to wrap it in a common Promise. Task and yield can be replaced with async / await when it is available.
        let that = this;
        return new Promise(function (resolve, reject) {
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
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







+
-
+
















-
+










+
-
+







                document.getElementById("grammalecte-errors").appendChild(xNodeP);
            }
            return nParagraph;
        }).then(function (res) {
            that.setInfo("Nombre de paragraphes analysés : " + res);
        }, function (e) {
            that.setInfo("Erreur : " + e.message);
            console.error(e);
            Cu.reportError(e);
            // Cu.reportError(e);
        });
    },
    createResultNode: function (xEditor, sParagraph, iParagraph, aGrammErr, aSpellErr) {
        let xResultNode = document.createElement("div");
        xResultNode.setAttribute("id", "resnode" + iParagraph);
        this.fillResultNode(xResultNode, xEditor, sParagraph, iParagraph, aGrammErr, aSpellErr);
        return xResultNode;
    },
    reparseParagraph: function (xEditor, iParagraph) {
        try {
            let that = this;
            let xResultNode = document.getElementById("resnode"+iParagraph);
            xResultNode.textContent = "…………… réanalyse en cours ……………";
            let sParagraph = xEditor.getParagraph(iParagraph);
            let xPromise = this._getGCResultPromise(sParagraph, "FR", false, false);
            xPromise.then(function (res) {
                //echo("res: " + res);
                //console.log("res: " + res);
                xResultNode.textContent = "";
                let oRes = JSON.parse(res);
                if (oRes.aGrammErr.length > 0 || oRes.aSpellErr.length > 0) {
                    that.fillResultNode(xResultNode, xEditor, sParagraph, iParagraph, oRes.aGrammErr, oRes.aSpellErr);
                }
            }, function (res) {
                xResultNode.textContent = "Erreur: " + res;
            });
        }
        catch (e) {
            console.error(e);
            Cu.reportError(e);
            // Cu.reportError(e);
        }
    },
    fillResultNode: function (xResultNode, xEditor, sParagraph, iParagraph, aGrammErr, aSpellErr) {
        try {
            if (aGrammErr.length === 0  &&  aSpellErr.length === 0) {
                return null;
            }
252
253
254
255
256
257
258

259

260
261
262
263
264
265
266
245
246
247
248
249
250
251
252

253
254
255
256
257
258
259
260







+
-
+







            xParagraphNode.appendChild(document.createTextNode(this._purgeTags(sParagraph.slice(nEndLastErr))));
            xResultNode.appendChild(xParagraphNode);
            for (let xNode of lNodeError) {
                xResultNode.appendChild(xNode);
            }
        }
        catch (e) {
            console.error(e);
            Cu.reportError(e);
            // Cu.reportError(e);
            xResultNode.textContent = "# Error: " + e.message;
        }
    },
    _createNodeGCErrorDescription: function (xEditor, nError, dErr, iParagraph) {
        let xNodeDiv = document.createElement("div");
        let that = this;
        // message
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
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







-











-
+







                            });
                            xNodeSuggLine.appendChild(xNodeSugg);
                            n += 1;
                        }
                    } else {
                        xNodeSuggLine.appendChild(document.createTextNode("Aucune suggestion."));
                    }
                    
                },
                function (aReason) { console.error('Promise rejected - ', aReason); }
            ).catch(
                function (aCaught) { console.error('Promise Error - ', aCaught); }
            );
        });
        xNodeSuggLine.appendChild(xNodeSuggButton);
        xNodeDiv.appendChild(xNodeSuggLine);
        return xNodeDiv;
    },
    loadUI: function() {
        echo("loadUI");
        console.log("loadUI");
        this._strings = document.getElementById("grammarchecker-strings");
        let that = this;
        let nsGrammarCommand = {
            isCommandEnabled: function (aCommand, dummy) {
                return (IsDocumentEditable() && !IsInHTMLSourceMode());
            },
            getCommandStateParams: function (aCommand, aParams, aRefCon) {},
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
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







+
-
+















+
-
+



















+
-
+














+
-
+








+
-
+













-
+


-
+

-
+





-
+

-
+







            xNavBar.setAttribute("currentset", aSet.join(","));
            xNavBar.currentSet = aSet.join(",");
            document.persist(xNavBar.id, "currentset");
            try {
                BrowserToolboxCustomizeDone(true);
            }
            catch (e) {
                console.error(e);
                Cu.reportError(e);
                // Cu.reportError(e);
            }
        }
    },
    clearPreview: function() {
        let xPreview = document.getElementById("grammalecte-errors");
        while (xPreview.firstChild) {
            xPreview.removeChild(xPreview.firstChild);
        };
        let xEditor = GetCurrentEditor();
        if (xEditor != null) {
            try {
                xEditor.QueryInterface(Ci.nsIEditorStyleSheets);
                xEditor.addOverrideStyleSheet("chrome://grammarchecker/content/overlay.css");
            }
            catch (e) {
                console.error(e);
                Cu.reportError(e);
                // Cu.reportError(e);
            }
        }
        this.setInfo("[vide]");
    },
    setInfo: function (sText) {
        document.getElementById("grammalecte-info").textContent = sText;
    },
    openPanel: function () {
        document.getElementById("textformatter-splitter").setAttribute("state", "collapsed");
        document.getElementById("grammarchecker-splitter").setAttribute("state", "open");
    },
    closePanel: function () {
        document.getElementById("grammarchecker-splitter").setAttribute("state", "collapsed");
    },
    openDialog: function (sWhat, sName="", sOptions="") {
        try {
            window.openDialog(sWhat, sName, sOptions);
        }
        catch (e) {
            console.error(e);
            Cu.reportError(e);
            // Cu.reportError(e);
        }
    },
    openInTabURL: function (sURL) {
        // method found in S3.Google.Translator
        try {
            let xWM = Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator);
            let xWin = xWM.getMostRecentWindow("mail:3pane");
            let xTabmail = xWin.document.getElementById('tabmail');
            xWin.focus();
            if (xTabmail) {
                xTabmail.openTab('contentTab', { contentPage: sURL });
            }
        }
        catch (e) {
            console.error(e);
            Cu.reportError(e);
            // Cu.reportError(e);
        }
    },
    openInBrowserURL: function (sURL) {
        // method found in S3.Google.Translator
        try {
            openURL(sURL);
        }
        catch (e) {
            console.error(e);
            Cu.reportError(e);
            // Cu.reportError(e);
        }
    },
    onParseText: function (e) {
        this.parse();
    },
    onClosePanel: function (e) {
        this.closePanel();
    },
    onOpenGCOptions: function (e) {
        let that = this;
        let xPromise = this.xGCEWorker.post('getDefaultOptions');
        xPromise.then(
            function (aVal) {
                echo(aVal);
                console.log(aVal);
                prefs.setCharPref("sGCDefaultOptions", aVal);
            },
            function (aReason) { echo('Promise rejected', aReason); }
            function (aReason) { console.log('Promise rejected', aReason); }
        ).catch(
            function (aCaught) { echo('Promise Error', aCaught); }
            function (aCaught) { console.log('Promise Error', aCaught); }
        ).then(
            function () {
                that.openDialog("chrome://grammarchecker/content/gc_options.xul", "", "chrome, dialog, modal, resizable=no");
                that.setOptions();
            },
            function (aReason) { echo('Error options dialog', aReason); }
            function (aReason) { console.log('Error options dialog', aReason); }
        ).catch(
            function (aCaught) { echo('Error', aCaught); }
            function (aCaught) { console.log('Error', aCaught); }
        );
    },
    onOpenSpellOptions: function (e) {
        this.openDialog("chrome://grammarchecker/content/spell_options.xul", "", "chrome, dialog, modal, resizable=no");
    },
    onOpenOptions: function (e) {
        this.openDialog("chrome://grammarchecker/content/options.xul", "", "chrome, dialog, modal, resizable=no");
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
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







+
-
+


















+
-
+
















+
-
+







-
+







        }
    },
    _setDictionary: function (sDicName, sOptName) {
        try {
            oSpellControl.setExtensionDictFolder(sDicName, prefs.getBoolPref(sOptName));
        }
        catch (e) {
            console.error(e);
            Cu.reportError(e);
            // Cu.reportError(e);
        }
    }
}


var oTextFormatter = {
    init: function () {
        try {
            this.closePanel();
            let sTFOptions = prefs.getCharPref("sTFOptions");
            if (sTFOptions !== "") {
                this.setOptionsInPanel(JSON.parse(sTFOptions));
                this.resetProgressBar();
            } else {
                this.reset();
            }
        }
        catch (e) {
            console.error(e);
            Cu.reportError(e);
            // Cu.reportError(e);
        }
    },
    apply: function () {
        try {
            this.saveOptions();
            this.resetProgressBar();
            let xEditor = new Editor();
            let sText = xEditor.getContent();
            let iParagraph = 0;
            sText = this.applyOptions(sText);
            for (let sParagraph of text.getParagraph(sText)) {
                xEditor.writeParagraph(iParagraph, sParagraph);
                iParagraph += 1;
            }
        }
        catch (e) {
            console.error(e);
            Cu.reportError(e);
            // Cu.reportError(e);
        }
    },
    saveOptions: function () {
        let oOptions = {};
        for (let xNode of document.getElementsByClassName("option")) {
            oOptions[xNode.id] = xNode.checked;
        }
        //echo("save options: " + JSON.stringify(oOptions));
        //console.log("save options: " + JSON.stringify(oOptions));
        prefs.setCharPref("sTFOptions", JSON.stringify(oOptions));
    },
    setOptionsInPanel: function (oOptions) {
        for (let sOptName in oOptions) {
            //console.log(sOptName + ":" + oOptions[sOptName]);
            if (document.getElementById(sOptName) !== null) {
                document.getElementById(sOptName).checked = oOptions[sOptName];
607
608
609
610
611
612
613

614

615
616
617
618
619
620
621
608
609
610
611
612
613
614
615

616
617
618
619
620
621
622
623







+
-
+







                xNode.checked = (xNode.getAttribute('data-default') === "true");
                if (xNode.id.startsWith("o_group_")) {
                    this.switchGroup(xNode.id);
                }
            }
        }
        catch (e) {
            console.error(e);
            Cu.reportError(e);
            // Cu.reportError(e);
        }
    },
    resetProgressBar: function () {
        document.getElementById('progressbar').value = 0;
        document.getElementById('time_res').textContent = "";
    },
    getTimeRes: function (n) {
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
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







+
-
+






-
-
+
+


-
+





+
-
+

















-
+










            // end of processing

            //window.setCursor("auto"); // restore pointer
            const t1 = Date.now();
            document.getElementById('time_res').textContent = this.getTimeRes((t1-t0)/1000);
        }
        catch (e) {
            console.error(e);
            Cu.reportError(e);
            // Cu.reportError(e);
        }
        return sText;
    },
    formatText: function (sText, sOptName) {
        let nCount = 0;
        try {
            if (!tf.oReplTable.hasOwnProperty(sOptName)) {
                echo("# Error. TF: there is no option “" + sOptName+ "”.");
            if (!oReplTable.hasOwnProperty(sOptName)) {
                console.log("# Error. TF: there is no option “" + sOptName+ "”.");
                return [sText, nCount];
            }
            for (let [zRgx, sRep] of tf.oReplTable[sOptName]) {
            for (let [zRgx, sRep] of oReplTable[sOptName]) {
                nCount += (sText.match(zRgx) || []).length;
                sText = sText.replace(zRgx, sRep);
            }
        }
        catch (e) {
            console.error(e);
            Cu.reportError(e);
            // Cu.reportError(e);
        }
        return [sText, nCount];
    }
}


/* EVENTS */

window.addEventListener("click", function (xEvent) {
    let xElem = xEvent.target;
    if (xElem.id && xElem.id.startsWith("o_group_")) {
        oTextFormatter.switchGroup(xElem.id);
        oTextFormatter.resetProgressBar();
    }
}, false);

window.addEventListener("load", function (xEvent) {
    oDictIgniter.init();
    // oDictIgniter.init();
    oGrammarChecker.loadGC();
    //oGrammarChecker.fullTests();
}, false);

window.addEventListener("compose-window-init", function (xEvent) {
    oGrammarChecker.loadUI();
    oGrammarChecker.closePanel();
    oGrammarChecker.clearPreview();
    oTextFormatter.init();
}, true);