File: Nat.java

package info (click to toggle)
natbraille 2.0rc3-14
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 7,080 kB
  • sloc: java: 31,266; xml: 7,747; sh: 165; haskell: 50; makefile: 32
file content (463 lines) | stat: -rw-r--r-- 17,376 bytes parent folder | download | duplicates (7)
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
/*
 * NAT - An universal Translator
 * Contact: bmascret@free.fr
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License.
 * 
 * This program 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package nat;

import java.awt.Frame;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import outils.ConfConv;
import nat.ConfigNat;
import nat.convertisseur.Convertisseur;
import nat.convertisseur.ConvertisseurChaine;
import nat.presentateur.PresentateurMEP;
import nat.transcodeur.Transcodeur;
import nat.transcodeur.TranscodeurNormal;
import nat.presentateur.Presentateur;

import joptsimple.OptionSet;
import joptsimple.OptionException;

import gestionnaires.AfficheurLog;
import gestionnaires.GestionnaireErreur;
import ui.AfficheurConsole;
import ui.FenetrePrinc;
/**
 * Classe principale de l'application
 * @author bruno
 *
 */
public class Nat 
{
    //constantes
	/** Représente un niveau de verbosité des logs muet */
	public final static int LOG_AUCUN = 0;
	/** Représente un niveau de verbosité des logs très faible */
    public final static int LOG_SILENCIEUX = 1;
    /** Représente un niveau de verbosité des logs normal */
    public final static int LOG_NORMAL = 2;
    /** Représente un niveau de verbosité des logs verbeux */
    public final static int LOG_VERBEUX = 3;
    /** Représente un niveau de verbosité des logs verbeux avec les informations de débuggage */
    public final static int LOG_DEBUG = 4;
    /** Représente la génération de version de configuration */
    public final static String CONFS_VERSION = "3" ;
    /** adresse web du fichier contenant le n° de la dernière version en ligne */
	private static final String CURRENT_VERSION_ADDRESS = "http://natbraille.free.fr/current-version.txt";
 
	/** String contenant la licence de NAT (GPL) */
    private static String licence;
    /** Une instance de gestionnaire d'erreur */
    private GestionnaireErreur gest;
    /** true si pas de transcriptions en cours */
    private boolean ready = true;
    /** true si nouvelle version disponible */
    private boolean updateAvailable = false;
    

	/** Liste d'instances de transcription représentant les transcription à réaliser */
	private ArrayList<Transcription> transcriptions = new ArrayList<Transcription>();
	//TODO raph a remplacer par ArrayList<Transcription> transcriptions = new ArrayList<Transcription>(); ???
	/**
	 * Constructeur
	 * @param g Une instance de GestionnaireErreur
	 */
    public Nat(GestionnaireErreur g) 
    {
		licence = getLicence("","");
		gest = g;
    }

    /* méthodes d'accès */
    /**
     * renvoie le nom du fichier de configuration
     * @return le nom du fichier de configuration
     */
    public String getFichierConf(){return ConfigNat.getCurrentConfig().getFichierConf();}	
	/**
	 * Renvoie une chaine contenant le numéro long de la version de NAT
	 * @return une chaine contenant le numéro long de version
	 */
    public String getVersionLong(){return ConfigNat.getVersionLong();}
    /**
	 * Renvoie une chaine contenant le nom de version de NAT
	 * @return une chaine contenant le nom de version
	 */
    public String getVersion(){return ConfigNat.getVersion();}
    /**
     * @param ua the updateAvailable to set
     * @see #updateAvailable
     */
    public void setUpdateAvailable(boolean ua){updateAvailable = ua;}

	/**
     * @return the updateAvailable value
     * @see #updateAvailable
     */
    public boolean isUpdateAvailable(){return updateAvailable;}

	/**
     * Renvoie l'instance de GestionnaireErreur
     * @return l'instance de GestionnaireErreur
     * @see Nat#gest
     */
	public GestionnaireErreur getGestionnaireErreur() {return gest;}
	
	/**
	 * Renvoie la licence de nat préfixée par prefixe et terminée par suffixe
	 * @param prefixe préfixe à insérer avant la licence (/* ou <!-- par exemple)
	 * @param suffixe suffixe à insérer après la licence (* / ou --> par exemple)
	 * @return la licence de NAT
	 */
    public static String getLicence(String prefixe, String suffixe)
    {
	licence =  prefixe + " * NAT - An universal Translator\n" +
	    "* Copyright (C) 2009 Bruno Mascret\n" +
	    "* Contact: bmascret@free.fr\n" +
	    "* \n" +
	    "* This program is free software; you can redistribute it and/or\n" +
	    "* modify it under the terms of the GNU General Public License\n" +
	    "* as published by the Free Software Foundation; either version 2\n" +
	    "* of the License.\n" +
	    "* \n" +
	    "* This program is distributed in the hope that it will be useful,\n" +
	    "* but WITHOUT ANY WARRANTY; without even the implied warranty of\n" +
	    "* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n" +
	    "* GNU General Public License for more details.\n" +
	    "* \n" +
	    "* You should have received a copy of the GNU General Public License\n" +
	    "* along with this program; if not, write to the Free Software\n" +
	    "* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.\n" +
	    suffixe;	
	return licence;
    }
    /**
     * Fait appel à la fabrique Transcription pour obtenir les instances de transcription à réaliser
     * Utilise le booléen <code>reverse</code> pour contraindre le sens de transcription 
     * @param noirs les adresses des fichiers noir
     * @param brailles les adresses des fichiers braille
     * @param reverse indique le sens de transcription: true si inverse, false sinon
     * @return <code>true</code> si la fabrication a réussi
     * @see Transcription#fabriqueTranscription(String, String, GestionnaireErreur, boolean)
     */
    public boolean fabriqueTranscriptions(ArrayList<String> noirs, ArrayList<String> brailles, boolean reverse)
    {
		boolean retour = true;
		//on vide la liste
		transcriptions.removeAll(transcriptions);
		for(int i=0;i<noirs.size();i++)
		{
			String noir = noirs.get(i);
			String braille = brailles.get(i);
			Transcription t = Transcription.fabriqueTranscription(noir,braille,gest,reverse);
			if(t!=null){transcriptions.add(t);}
			else{retour=false;}
		}
		return retour;
    }
    /**
     * Fait appel à la fabrique Transcription pour obtenir les instances de transcription à réaliser
     * Ne détermine pas le sens de la transcription, qui sera établit dans {@link Transcription#fabriqueTranscription(String, String, GestionnaireErreur)}
     * @param noirs les adresses des fichiers noirs
     * @param brailles les adresses des fichiers braille
     * @return <code>true</code> si la fabrication a réussi
     * @see Transcription#fabriqueTranscription(String, String, GestionnaireErreur)
     */
    public boolean fabriqueTranscriptions(ArrayList<String> noirs, ArrayList<String> brailles)
    {
		boolean retour = true;
		//on vide la liste
		transcriptions.removeAll(transcriptions);
		for(int i=0;i<noirs.size();i++)
		{
			String noir = noirs.get(i);
			String braille = brailles.get(i);
			Transcription t = Transcription.fabriqueTranscription(noir,braille,gest);
			if(t!=null){transcriptions.add(t);}
			else{retour=false;}
		}
		return retour;
    }
    /**
     * Lance le processus complet de transcription des instances de <code>transcription</code>
     * Attends éventuellement si une transcription est en cours
     * @return true si le scénario s'est déroulé normallement
     * @see Nat#transcriptions
     */
    public boolean lanceScenario()
    {
    	if(!ready)
    	{
    		gest.afficheMessage("\nLa transcription commencera dès la fin de la transcription en cours\n", Nat.LOG_NORMAL);
	    	while(!ready)
	    	{
	    		try {Thread.sleep(1000);}
				catch (InterruptedException e) {e.printStackTrace();}
	    	}
    	}
    	ready=false;
    	gest.setException(null);
    	boolean retour = true;
    	for(Transcription t : transcriptions)
    	{
	    	try
	    	{
	    		retour = retour & t.transcrire();
	    	}
	    	catch(OutOfMemoryError oome)
	    	{
	    		gest.setException(new Exception("mémoire",oome));
	    		gest.gestionErreur();
	    	}
    	}
    	ready =true;
		return retour;
    }
    /**
     * Appel à la méthode touveEncodingSource de Transcription
     * @param source le fichier source
     * @return une chaîne correspondant à l'encodage du fichier source
     * @see Transcription#trouveEncodingSource(String, GestionnaireErreur)
     */
    public String trouveEncodingSource(String source){return Transcription.trouveEncodingSource(source, gest);}
    /**
     * Charge certaines options de la ligne de commande dans le singleton de ConfigNat 
     * @param options OptionSet des options
     */
    public static void loadCliOptions(OptionSet options)
    {	
		ConfigNat cc = ConfigNat.getCurrentConfig();
	
		String nom = OptNames.ge_log_verbosity;
		if (options.has(nom)){cc.setNiveauLog(((Integer) options.valueOf(nom)).intValue());}
	
		nom = OptNames.fi_braille_table;
		String sys = OptNames.fi_is_sys_braille_table;
		if (options.has(nom))
		{
			if(options.has(sys))
			{
				cc.setIsSysTable(((Boolean) options.valueOf(sys)).booleanValue());
				cc.setTableBraille(((String) options.valueOf(nom)),cc.getIsSysConfig());
			}
			else{cc.setTableBraille(((String) options.valueOf(nom)),true);}
		}
		
		nom = OptNames.fi_math_transcribe;
		if (options.has(nom)){cc.setTraiterMaths(((Boolean) options.valueOf(nom)).booleanValue());}
	
		nom = OptNames.fi_math_use_trigo_spec;
		if (options.has(nom)){cc.setMathTrigoSpec(((Boolean) options.valueOf(nom)).booleanValue());}
		
		nom = OptNames.fi_litt_transcribe;
		if (options.has(nom)){cc.setTraiterLiteraire(((Boolean) options.valueOf(nom)).booleanValue());}
	
		nom = OptNames.fi_litt_abbreg;
		if (options.has(nom)){cc.setAbreger(((Boolean) options.valueOf(nom)).booleanValue());}
	
		nom = OptNames.fi_music_transcribe;
		if (options.has(nom)){cc.setTraiterMusique(((Boolean) options.valueOf(nom)).booleanValue());}
	
		nom = OptNames.fi_hyphenation;
		if (options.has(nom)){cc.setCoupure(((Boolean) options.valueOf(nom)).booleanValue());}
	
		nom = OptNames.fi_hyphenation_dirty;
		if  (options.has(nom)){cc.setModeCoupureSagouin(((Boolean) options.valueOf(nom)).booleanValue());}
	
		nom = OptNames.fi_line_lenght;
		if (options.has(nom)){cc.setLongueurLigne(((Integer) options.valueOf(nom)).intValue());}
		
		nom = OptNames.en_in;
		if (options.has(nom)){cc.setNoirEncoding((String)options.valueOf(nom));}
	
		nom = OptNames.en_out;
		if (options.has(nom)){cc.setBrailleEncoding((String)options.valueOf(nom));}
    }
    
    /**
     * Méthode main
     * Analyse la chaine de paramètres, lance ou non l'interface graphique, la transcription, etc
     * @param argv les paramètres de la méthode main
     */
    public static void main (String argv [])
    {
    	//System.setProperty("file.encoding","UTF-8");
    	// Gestionnaire d'erreur de base (non utilisé par interface graphique)
    	//initialisation de certaines propriétés
		System.setProperty("javax.xml.transform.TransformerFactory",
		"net.sf.saxon.TransformerFactoryImpl");
		System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
				"org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
    	ConfigNat.charger(null);  
    	GestionnaireErreur gestErreur = new GestionnaireErreur(null,ConfigNat.getCurrentConfig().getNiveauLog());
		
    	Nat nat = new Nat(gestErreur);
    	
		AfficheurConsole ac = new AfficheurConsole();
    	gestErreur.addAfficheur(ac);
    	gestErreur.addAfficheur(new AfficheurLog());
    	OptionParserNat parser = new OptionParserNat();
    	
    	try
	    {
    		OptionSet options = parser.parse(argv);
    		ConfConv.convert(gestErreur);
    		if (options.has("gui"))
		    {	 
				FenetrePrinc fenetre = new FenetrePrinc(nat);
				fenetre.pack();
				if (ConfigNat.getCurrentConfig().getMaximizedPrincipal())
		    		{fenetre.setExtendedState(Frame.MAXIMIZED_BOTH);}
				fenetre.setVisible(true);
		    }
    		else if (options.has("f") && options.has("t"))
		    {
    			if (options.has("q")) {gestErreur.removeAfficheur(ac);}
				if (options.has("c")) {ConfigNat.charger(options.valueOf( "c" ).toString());}
				loadCliOptions(options);
				
    			String[] cl_from = options.valueOf( "f" ).toString().split(":");
    			String[] cl_to = options.valueOf( "t" ).toString().split(":");
    			
    			/* exécution dans la console ou en ligne de commande?*/
    			if(cl_from[0].equals("-"))
    			{
    				gestErreur.removeAfficheur(ac);
    				gestErreur.afficheMessage("\nLecture de l'entrée standard... Ctrl+C pour quitter \n",Nat.LOG_NORMAL);
    				while(true)
    				{
    					boolean fin=false;
    					String chaine="";
    					while(!fin)
    					{
    						try 
    						{
								char c = (char)(System.in.read());
								if(c=='\n')
								{
									fin=true;
								}
								else
								{
									chaine=chaine+c;
								}
							} 
    						catch (IOException e) {e.printStackTrace();}
    					}
    					Convertisseur c = new ConvertisseurChaine(chaine,ConfigNat.getUserTempFolder()+"/tmp.xml","UTF-8");
    					Transcodeur t=new TranscodeurNormal(ConfigNat.getUserTempFolder()+"/tmp.xml",
    							ConfigNat.getUserTempFolder()+"/tmp.txt","UTF-8",gestErreur);
    					Presentateur p=new PresentateurMEP(gestErreur, "UTF-8", ConfigNat.getUserTempFolder()+"/tmp.txt",
    							ConfigNat.getUserTempFolder()+"/out.txt", "brailleUTF8");
    					
    					c.convertir(gestErreur);
    					t.transcrire(gestErreur);
    					p.presenter();
    					try {
    						BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(ConfigNat.getUserTempFolder()+"/out.txt")));
							System.out.println(br.readLine());
						} catch (FileNotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
    				}
    				/*
    				 * fin du programme ici, seul un arrêt total du programme permet de sortir de la
    				 * boucle infinie
    				 * 
    				 */
    			}
    			/*
    			 * Si pas fonctionnement temps réel
    			 */
				gestErreur.afficheMessage("conversion de "+cl_from+" vers "+cl_to,Nat.LOG_NORMAL);
				//fabrication des listes
				ArrayList<String> sources = new ArrayList<String>();
				ArrayList<String> cibles = new ArrayList<String>();
				for (int i=0;i<cl_from.length;i++)
				{
					sources.add(cl_from[i]);
					if(i>=cl_to.length){cibles.add(cl_from[i]+".braille");}
					else{cibles.add(cl_to[i]);}
				}
				if (nat.fabriqueTranscriptions(sources, cibles)){nat.lanceScenario();}
				else
				{
					gestErreur.afficheMessage("\n**ERREUR: certain fichiers n'existe pas et ne pourront être transcrits", Nat.LOG_SILENCIEUX);
					nat.lanceScenario();
				}
		    }
    		else 
		    {
    			try{parser.printCliUsage();}
    			catch(IOException ioe){gestErreur.afficheMessage("\nErreur d'affichage pour les options", Nat.LOG_SILENCIEUX);}
		    }
	    }
    	catch (OptionException ex)
	    {
    		System.err.println( "====" );
    		gestErreur.afficheMessage("\nProblème dans la ligne de commande", Nat.LOG_VERBEUX);
    		try{parser.printCliUsage();}
			catch(IOException ioe){gestErreur.afficheMessage("\nErreur d'affichage pour les options", Nat.LOG_SILENCIEUX);}
	    }
    }

	/**
     * Vérifie si une nouvelle version est disponible en ligne
     * Met à jour {@link #updateAvailable}
     * @return true si vérification effectuée, false si vérification impossible
     */
    public boolean checkUpdate()
    {
        boolean retour = true;
    	gest.afficheMessage("Recherche d'une mise à jour de NAT...", LOG_VERBEUX);
    	URL url;
		try 
		{
			url = new URL(CURRENT_VERSION_ADDRESS);
			URLConnection urlCon = url.openConnection();
	        
			BufferedReader br = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));
	        
	        String ligne= br.readLine();
	        br.close();
	        if(Integer.parseInt(ligne) > ConfigNat.getSvnVersion())
	        {
	        	updateAvailable = true;
	        }
		}
		catch (NumberFormatException nfe){gest.afficheMessage("\n** pas de connexion web pour vérifier la présence de mise à jour", Nat.LOG_SILENCIEUX);retour=false;}
		catch (MalformedURLException e) {gest.afficheMessage("\n** adresse internet " + CURRENT_VERSION_ADDRESS +" non valide", Nat.LOG_SILENCIEUX);retour=false;}
		catch (IOException e) {gest.afficheMessage("\n** erreur d'entrée sortie lors de la vérification de l'existence d'une mise à jour", Nat.LOG_SILENCIEUX);retour=false;}
                return retour;
	   
    }

}