Grammalecte  Check-in [2d0855bb95]

Overview
Comment:[tb] store personal dictionary in file instead of preferences.js: create a file handler to simplify the mess
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | tb | multid
Files: files | file ages | folders
SHA3-256: 2d0855bb95a0b1fed35f8c6ffa9b6696d2b904a229352fc1a9fe4396bfb7bc40
User & Date: olr on 2018-03-19 12:37:38
Other Links: branch diff | manifest | tags
Context
2018-03-19
18:57
[tb] lexicon editor: delete selected items check-in: d21c8802ec user: olr tags: tb, multid
12:37
[tb] store personal dictionary in file instead of preferences.js: create a file handler to simplify the mess check-in: 2d0855bb95 user: olr tags: tb, multid
2018-03-18
17:27
[tb] lexicon editor: update check-in: d61338b1a8 user: olr tags: tb, multid
Changes

Modified gc_lang/fr/tb/content/lex_editor.js from [4b52ef9dfc] to [9022aa2b92].

1
2
3
4
5
6
7
8
9


10
11
12
13
14
15
16
// JavaScript

"use strict";

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
const prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("extensions.grammarchecker.");




/*
    Common functions
*/

function showError (e) {
    Cu.reportError(e);









>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// JavaScript

"use strict";

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;
const prefs = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("extensions.grammarchecker.");

const {TextDecoder, TextEncoder, OS} = Cu.import("resource://gre/modules/osfile.jsm", {});


/*
    Common functions
*/

function showError (e) {
    Cu.reportError(e);
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
}


const oBinaryDict = {
    
    oIBDAWG: null,

    load: function () {
        let sJSON = prefs.getCharPref("oPersonalDictionary");
        if (sJSON != "") {
            let oJSON = JSON.parse(sJSON);
            this.oIBDAWG = new IBDAWG(oJSON);
            let lEntry = [];
            for (let s of this.oIBDAWG.select()) {
                lEntry.push(s.split("\t"));
            }        
            oLexiconTable.fill(lEntry);
            this.setDictData(this.oIBDAWG.nEntry, this.oIBDAWG.sDate);
            enableElement("export_button");
        } else {

            disableElement("export_button");
        }
    },

    setDictData: function (nEntries, sDate) {
        document.getElementById("dic_num_entries").value = nEntries;
        document.getElementById("dic_save_date").value = sDate;







|
|











>







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
}


const oBinaryDict = {
    
    oIBDAWG: null,

    load: async function () {
        let sJSON = await oFileHandler.loadFile("fr.personal.json");
        if (sJSON != "") {
            let oJSON = JSON.parse(sJSON);
            this.oIBDAWG = new IBDAWG(oJSON);
            let lEntry = [];
            for (let s of this.oIBDAWG.select()) {
                lEntry.push(s.split("\t"));
            }        
            oLexiconTable.fill(lEntry);
            this.setDictData(this.oIBDAWG.nEntry, this.oIBDAWG.sDate);
            enableElement("export_button");
        } else {
            this.setDictData(0, "[néant]");
            disableElement("export_button");
        }
    },

    setDictData: function (nEntries, sDate) {
        document.getElementById("dic_num_entries").value = nEntries;
        document.getElementById("dic_save_date").value = sDate;
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

    build: function () {
        let xProgressNode = document.getElementById("wait_progress");
        let lEntry = oLexiconTable.getEntries();
        if (lEntry.length > 0) {
            let oDAWG = new DAWG(lEntry, "S", "fr", "Français", "Dictionnaire personnel", xProgressNode);
            let oJSON = oDAWG.createBinaryJSON(1);
            prefs.setCharPref("oPersonalDictionary", JSON.stringify(oJSON));
            this.oIBDAWG = new IBDAWG(oJSON);
            this.setDictData(this.oIBDAWG.nEntry, this.oIBDAWG.sDate);
            //browser.runtime.sendMessage({ sCommand: "setDictionary", dParam: {sType: "personal", oDict: oJSON}, dInfo: {} });
            enableElement("export_button");
        } else {
            prefs.setCharPref("oPersonalDictionary", "");

            this.setDictData(0, "[néant]");
            disableElement("export_button");
        }
    },

    import: function () {
        console.log("import");
    },

    export: function () {
        let sJSON = JSON.stringify(this.oIBDAWG.getJSON());































































        let xFilePicker = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
        xFilePicker.init(window, "Enregistrer sous", Ci.nsIFilePicker.modeSave);
        xFilePicker.appendFilters(Ci.nsIFilePicker.filterAll | Ci.nsIFilePicker.filterText);
        xFilePicker.open(function (nReturnValue) {
            if (nReturnValue == Ci.nsIFilePicker.returnOK || nReturnValue == Ci.nsIFilePicker.returnReplace) {
                // https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/OSFile.jsm

                OS.File.writeAtomic(xFilePicker.file.path, sJSON, {tmpPath: "file.txt.tmp"}); 
                /*
                var FileUtils = Cu.import("resource://gre/modules/FileUtils.jsm").FileUtils
                var NetUtil = Cu.import("resource://gre/modules/NetUtil.jsm").NetUtil;
                // You can also optionally pass a flags parameter here. It defaults to
                // FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_TRUNCATE;
                let xOutStream = FileUtils.openSafeFileOutputStream(xFilePicker.file);
                let xConverter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Ci.nsIScriptableUnicodeConverter);
                xConverter.charset = "UTF-8";
                let xInStream = xConverter.convertToInputStream(sJSON);
                // The last argument (the callback) is optional.
                NetUtil.asyncCopy(xInStream, xOutStream, function (status) {
                    if (!Components.isSuccessCode(status)) {
                        console.log(status);
                        return;
                    }
                });
                */
             }
        });
    }
}



const oLexiconTable = new Table("lexicon_table", ["Flexions", "Lemmes", "Étiquettes"], [10, 7, 10], "progress_lexicon", "num_entries");
const oGenWordsTable = new Table("generated_words_table", ["Flexions", "Étiquettes"], [1, 1], "progress_new_words");

oBinaryDict.load();
oBinaryDict.listen();
oGenerator.listen();







|






>











>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>





|
>
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




<








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

    build: function () {
        let xProgressNode = document.getElementById("wait_progress");
        let lEntry = oLexiconTable.getEntries();
        if (lEntry.length > 0) {
            let oDAWG = new DAWG(lEntry, "S", "fr", "Français", "Dictionnaire personnel", xProgressNode);
            let oJSON = oDAWG.createBinaryJSON(1);
            oFileHandler.saveFile("fr.personal.json", JSON.stringify(oJSON));
            this.oIBDAWG = new IBDAWG(oJSON);
            this.setDictData(this.oIBDAWG.nEntry, this.oIBDAWG.sDate);
            //browser.runtime.sendMessage({ sCommand: "setDictionary", dParam: {sType: "personal", oDict: oJSON}, dInfo: {} });
            enableElement("export_button");
        } else {
            prefs.setCharPref("oPersonalDictionary", "");
            oFileHandler.deleteFile("fr.personal.json");
            this.setDictData(0, "[néant]");
            disableElement("export_button");
        }
    },

    import: function () {
        console.log("import");
    },

    export: function () {
        let sJSON = JSON.stringify(this.oIBDAWG.getJSON());
        oFileHandler.saveAs(sJSON);
    }
}


const oFileHandler = {
    // https://developer.mozilla.org/fr/docs/Mozilla/JavaScript_code_modules/OSFile.jsm/OS.File_for_the_main_thread

    xDataFolder: null,

    createDataFolder: function () {
        let xDirectoryService = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties);
        // this is a reference to the profile dir (ProfD) now.
        let xExtFolder = xDirectoryService.get("ProfD", Ci.nsIFile);
        xExtFolder.append("grammalecte-data");
        if (!xExtFolder.exists() || !xExtFolder.isDirectory()) {
            // read and write permissions to owner and group, read-only for others.
            xExtFolder.create(Ci.nsIFile.DIRECTORY_TYPE, 774);
        }
        this.xDataFolder = xExtFolder;
    },

    createPathFileName: function (sFilename) {
        let spfDest = this.xDataFolder.path;
        spfDest += (/^[A-Z]:/.test(this.xDataFolder.path)) ? "\\" + sFilename : "/" + sFilename;
        return spfDest;
    },

    loadFile: async function (sFilename) {
        if (!this.xDataFolder) {
            this.createDataFolder();
        }
        try {
            let xDecoder = new TextDecoder();
            let array = await OS.File.read(this.createPathFileName(sFilename));
            return xDecoder.decode(array);
        }
        catch (e) {
            console.error(e);
            return "";
        }
    },

    saveFile: function (sFilename, sData) {
        if (!this.xDataFolder) {
            this.createDataFolder();
        }
        let xEncoder = new TextEncoder();
        let xEncodedRes = xEncoder.encode(sData);
        console.log("save dictionary: " + this.createPathFileName(sFilename));
        OS.File.writeAtomic(this.createPathFileName(sFilename), xEncodedRes);
        //OS.File.writeAtomic(this.createPathFileName(sFilename), xEncodedRes, {tmpPath: "file.txt.tmp"}); // error with a temporary file (can’t move it)
    },

    deleteFile: function (sFilename) {
        if (!this.xDataFolder) {
            this.createDataFolder();
        }
        OS.File.remove(this.createPathFileName(sFilename), {ignoreAbsent: true});
    },

    saveAs: function (sData) {
        // save anywhere with file picker
        let xFilePicker = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
        xFilePicker.init(window, "Enregistrer sous", Ci.nsIFilePicker.modeSave);
        xFilePicker.appendFilters(Ci.nsIFilePicker.filterAll | Ci.nsIFilePicker.filterText);
        xFilePicker.open(function (nReturnValue) {
            if (nReturnValue == Ci.nsIFilePicker.returnOK || nReturnValue == Ci.nsIFilePicker.returnReplace) {
                let xEncoder = new TextEncoder();
                let xEncodedRes = xEncoder.encode(sData);
                OS.File.writeAtomic(xFilePicker.file.path, xEncodedRes, {tmpPath: "file.txt.tmp"});

















             }
        });
    }
}



const oLexiconTable = new Table("lexicon_table", ["Flexions", "Lemmes", "Étiquettes"], [10, 7, 10], "progress_lexicon", "num_entries");
const oGenWordsTable = new Table("generated_words_table", ["Flexions", "Étiquettes"], [1, 1], "progress_new_words");

oBinaryDict.load();
oBinaryDict.listen();
oGenerator.listen();