Bonjour à tous,

Je suis débutant en javascript et je souhaite écrire un programme javascript pour interagir avec indesign.

Je souhaiterais avoir votre avis sur une architecture à choisir avec si possible un framework permettant «d'organiser» mon code pour faciliter le développement. Mon application n'aura pas de model (pas de base de données).

Pour l'instant mon application fonctionne mais je souhaiterais faire plusieurs projets de ce type est donc améliorer le code. J'ai déjà comme projet de réécrire ce code en orienté objet peut-être?

En bref, je fais une fonction main et j'utilise des includes pour ajouter des fonctions que j'ai écrites …



Ci-joint un exemple de mon code:
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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
 
 
#target indesign
#include "includes/idsHelper.jsx"
#include "includes/dialog_box.jsx"
#include "includes/tools.jsx"
#include "includes/pictures_tools.jsx"
#include "includes/document_tools.jsx"
 
 
//constants
const SAVE_DIR = "~/Desktop" + "/indd_resize_script";
const SCRIPT_DIR = new File($.fileName).parent;
const LOG_DIR = SCRIPT_DIR + "/log";
 
// globale variables
/**
* @var the document 
**/
var doc = null;
/**
 * @var the document name
 **/
var doc_name = null;
 
 
try{
    app.colorSettings.mismatchAskWhenOpening = false;
    main();
}
catch(ex){
    var logger = idsLog(File (LOG_DIR + "/log.txt"));
    logger.errorAlert("document name: "+ doc_name +" – error: "+ ex.message + "  – error line: "+ ex.line);
    exit();
}
 
 
function main() {
    //if version is cs6
    if(app.version >= "8.0" && app.version < "9.0"){
        //then open photoshop
        open_photoshop();
        // a indesign doc must be open
        if(app.documents.length > 0){
            doc = app.activeDocument;
            doc_name = doc.name;
            //the doc must be saved
            if(!doc.saved){
                var save_doc = confirm("le document doit être sauvé pour continuer le script. Voulez-vous enregistrer le document sous");
                if(save_doc){
                    doc.save();
                    run_script ();
                }
                else{
                    alert("le script a été annulé");
                    exit();
                }
             }
             else{
                 // if the doc is already saved, is it modified?
                 if(doc.modified){
                    var modified_doc = confirm("le document doit être sauvé pour continuer le script. Voulez-vous enregistrer les modifications");
                     if(modified_doc){
                         doc.save();
                         run_script ();
                     }
                     else{
                        alert("le script a été annulé");
                        exit();
                     }
                 }
                 else{
                    run_script ();
                 }
            }
        }
        else{
            alert("vous devez ouvrir un document pour lancer le script");
            exit();
        }
    }
    else{
        throw new Error ("ce script fonctionne sur la version d'indesign 8.0 (CS6), veuillez contacter l'administrateur si vous souhaitez utiliser ce script sur une autre version");
    }
}
 
 
function run_script(){
    if(check_outOfDate_link (doc) || check_is_missing_link (doc)){
        alert("le script contient un lien manquant ou un lien modifié, veuillez mettre à jour les liens puis recommencer.");
        exit();
    }
    else{
        var results = create_dialog_main ();
        // the user click run script and init proprieties
        if(results != null){
            // package the doc, open the new doc
            var doc_package_str = save_with_package (doc, SAVE_DIR);
            doc.close(SaveOptions.NO);
            var doc_package = app.open(new File(doc_package_str));
            // folder after the package
            var folder_package = new File(doc_package_str).parent;
            // rapport logger
            var rapport_logger = idsLog(File (folder_package + "/rapport.txt"));
            // get all links from package doc
            var array_all_links = doc_package.links;
            for(var i = 0; i<array_all_links.length; i++){
                var current_link = array_all_links[i];
                var is_valid = is_link_valid (current_link, results.array_of_ignored_picture);
                //modifie only a valid link
                if(is_valid){
                    // modifie only a link if I is used 1 time
                    var use_number = is_link_used_many_time(array_all_links[i], doc_package);
                    if(use_number ==1){
                        // if jpg or png record as tiff or psd
                        if(current_link.linkType == "JPEG" || current_link.linkType == "Portable Network Graphics (PNG)"){
                            // if image has alpha channel
                            if(has_item_alpha_channel(current_link) ){
                                // record as psd
                                var new_file_path = save_to_PSD({file_path: encodeURI(current_link.filePath)});
                                rapport_logger.info("l'image "+ array_all_links[i].name +
                                " a été réenregistrée en psd");
                            }
                            else{
                                // record as tiff
                                var new_file_path = save_to_TIFF({file_path: encodeURI(current_link.filePath)});
                                 rapport_logger.info("l'image "+ array_all_links[i].name +
                                " a été réenregistrée en tif");
                            }
                             // delete the old File
                            new File(current_link.filePath).remove();
                            // relink
                            current_link.relink(new File(new_file_path));
                        }
                        //resample
                        var was_current_link_modified = resampling(current_link, rapport_logger, results.cibleBitmap, results.cibleRaster, results.isPictureNotPropAllowed, 
                            results.isSousEchantillonnage, results.isSurEchantillonnage, results.limitBitmap, results.limitRaster);
                        if(was_current_link_modified){
                            update_link(current_link);
                        }
                    }
                    else{
                        rapport_logger.infoAlert("l'image "+ array_all_links[i].name +
                        " est utilisée plusieurs fois, aucun changement ne sera effectué sur cette image");
                    }
                }
            }
            doc_package.save();
            alert("le script est terminé");
        }
        // the user click cancel script
        else{
            alert("le script a été annulé");
            exit();
        }
    }
}
 
function open_photoshop() {  
	var mySpecifier = BridgeTalk.getSpecifier("photoshop");
	if (mySpecifier == null){
        throw new Error("photoshop n'est pas installé");
     }
     if (!BridgeTalk.isRunning ("photoshop")) {
        var myConfirm = confirm("voulez-vous démarrer photoshop?");
        if (myConfirm) {
            BridgeTalk.launch("photoshop");
            alert("attendez que photoshop soit démarré, puis relancer le script");
            exit();
        }
        else {
            exit();
        }
     }
}
 
 
function resampling(link_item, rapport_logger, target_res_bitmap, target_res_raster, isPictureNotPropAllowed, 
    is_under_sampling, is_over_sampling, limit_bitmap, limit_raster){
    var link_was_modified = false;
 
    var target_resolution; 
    var target_limit;
 
    var is_image_prop = is_link_proportionnal(link_item);
    var is_current_link_bitmap = is_image_bitmap(link_item);
    var file_path = link_item.filePath;
    var image = link_item.parent;
    var effective_PPI = image.effectivePpi[0];
    var horizontal_scale = Math.abs(image.absoluteHorizontalScale);
    var vertical_scale = Math.abs(image.absoluteVerticalScale);
 
    // select target resolution and limit resolution
    if(is_current_link_bitmap){
        target_resolution = target_res_bitmap;
        target_limit = limit_bitmap;
    }
    else{
        target_resolution = target_res_raster;
        target_limit = limit_raster;
    }
 
 
    // if an image is not prop and the user select image not proportionnal not allowed -> alert
    if(!isPictureNotPropAllowed){
        if(!is_image_prop){
            rapport_logger.warnAlert("l'image "+ link_item.name +
            "est non proportionnelle, aucun changement ne sera apporté à cette illustration");
            return link_was_modified;
        }
    }
 
 
    if(is_under_sampling){
        if(effective_PPI > target_resolution){
            var resample_method = "ResampleMethod.BICUBICSHARPER";
            resampling_photoshop({
                file_path : encodeURI(file_path),
                horizontal_scale : horizontal_scale,
                vertical_scale : vertical_scale,
                resolution : target_resolution,
                resample_method : resample_method
            });
            rapport_logger.info("l'image "+ link_item.name +" a été sous échantillonnée");
            return link_was_modified = true;
        }
    }
 
    if(is_over_sampling){
        if(effective_PPI < target_resolution){
            if(effective_PPI < target_limit){
                rapport_logger.warnAlert("l'image "+ link_item.name +
                "a une résolution en dessous de la limite spécifiée: "+target_limit);
            }
            var resample_method = "ResampleMethod.BICUBICSMOOTHER";
            resampling_photoshop({
                file_path : encodeURI(file_path),
                horizontal_scale : horizontal_scale,
                vertical_scale : vertical_scale,
                resolution : target_resolution,
                resample_method : resample_method
            });
            rapport_logger.info("l'image "+ link_item.name +" a été sur échantillonnée");
            return link_was_modified = true;
        }   
    }
    return link_was_modified;
}
 
function update_link(link_item) {
    var status = link_item.status;
    if(status == LinkStatus.LINK_OUT_OF_DATE){
        link_item.update();
    }
 
    if(link_item.status != LinkStatus.NORMAL){
        throw new Error("le lien "+link_item.name+" a un statut incorrect");
    }
 
    if(is_link_proportionnal(link_item)){
        if ( link_item.parent.absoluteHorizontalScale > 99.95 && link_item.parent.absoluteHorizontalScale < 100.05 ) {
            link_item.parent.absoluteHorizontalScale = 100;
            link_item.parent.absoluteVerticalScale = 100;
        }
    }
    else{
        link_item.parent.absoluteHorizontalScale = 100;
        link_item.parent.absoluteVerticalScale = 100;
    }
}
 
 
 
 
 
 
 
 
 
#include "tools.jsx"
 
/**
 * function who return true if one link is out of date
 * @return true if a link is out of date, then false
 **/
function check_outOfDate_link(doc) {
    var link_statut = false;
    for(var i = 0; i<doc.links.length; i++){
        var current_link = doc.links[i];
        if(current_link.status == LinkStatus.LINK_OUT_OF_DATE){
            link_statut = true;
        }
    }
    return link_statut;
}
 
/**
 * function who return true if one link is missing
 * @return true, if a link is missing then false
 **/
function check_is_missing_link(doc) {
    var link_statut = false;
    for(var i = 0; i<doc.links.length; i++){
        var current_link = doc.links[i];
        if(current_link.status == LinkStatus.LINK_MISSING){
            link_statut = true;
        }
    }
    return link_statut;
}
 
/**
 * function who package a document and his link
 * @param the save dir path
 * @return the new doc path
 * @throw error if the package occured an error
 **/
function save_with_package (doc, directories_path_str) {
    var result_package = false;
	var current_date = new Date();
	var folder_package = Folder (directories_path_str);
	if (folder_package.exists == false) {
        folder_package.create();
    }
	var doc_file = doc.fullName;
	var current_folder = Folder (folder_package + "/" + format_date(doc_file.modified) + "_" + format_time(current_date) + "__" + doc.name);
	current_folder.create();
    /**bool packageForPrint (to: File, copyingFonts: bool, copyingLinkedGraphics: bool, copyingProfiles: bool, updatingGraphics: bool, 
      *  includingHiddenLayers: bool, ignorePreflightErrors: bool, creatingReport: bool[, versionComments: string][, forceSave: bool=false])
      **/
    result_package = doc.packageForPrint(current_folder, false, true, false, true, false, true, false);
    if(!result_package){
        throw new Error("il y a eu un problème lors de l'assemblage");
    }
    return current_folder + "/" + doc.name;
}
 
 
 
 
function is_link_used_many_time(link_item, doc_to_check){
    var array_all_links = doc_to_check.links;
    var counter = 0;
    for(var i = 0; i<array_all_links.length; i++){
        var current_link = array_all_links[i];
        if(link_item.filePath == current_link.filePath){
            counter++;
        }
    }
    return counter;
}
 
function is_link_proportionnal(link_item){
    var is_prop;
    var myImage = link_item.parent;
    var myHorScale = Math.abs(myImage.absoluteHorizontalScale);
    var myVerScale = Math.abs(myImage.absoluteVerticalScale);
    if(Math.round(myHorScale) == Math.round(myVerScale) ){
        is_prop = true;
    }
    else{
        is_prop = false;
    }
    return is_prop;
}
Si quelqu'un a une idée pour être plus propre c'est avec plaisir?

Merci beaucoup à tous.
Meilleures salutations.