Révision 3422

TXM/trunk/org.txm.tigersearch.rcp/plugin.xml (revision 3422)
87 87
         </command>
88 88
      </menuContribution>
89 89
      <menuContribution
90
            locationURI="menu:menu.corpus.import">
90
            locationURI="menu:menu.file.import.annotations">
91 91
         <command
92 92
               commandId="org.txm.tigersearch.commands.ImportTIGERAnnotations"
93 93
               icon="icons/functions/TSplus.png"
TXM/trunk/org.txm.annotation.core/src/org/txm/annotation/core/AnnotationEnginesManager.java (revision 3422)
1 1
package org.txm.annotation.core;
2 2

  
3
import java.util.ArrayList;
4
import java.util.HashMap;
5
import java.util.List;
6

  
3 7
import org.eclipse.core.runtime.IConfigurationElement;
4 8
import org.eclipse.core.runtime.IProgressMonitor;
5 9
import org.eclipse.core.runtime.Platform;
6 10
import org.eclipse.osgi.util.NLS;
11
import org.txm.Toolbox;
7 12
import org.txm.core.engines.EngineType;
8 13
import org.txm.core.engines.EnginesManager;
9 14
import org.txm.objects.CorpusBuild;
15
import org.txm.objects.Project;
10 16
import org.txm.utils.logger.Log;
11 17

  
12 18

  
......
99 105
		
100 106
		return size() > 0;
101 107
	}
108
	
109
	public boolean isSaveNeeded() {
110
		
111
		for (AnnotationEngine a : values()) {
112
			for (Project project : Toolbox.workspace.getProjects()) {
113
				for (CorpusBuild corpus : project.getCorpora()) {
114
					if (a.hasAnnotationsToSave(corpus)) {
115
						return true;
116
					}
117
				}
118
			}
119
		}
120
		return false;
121
	}
122

  
123
	public List<AnnotationEngine> getEnginesWithSaveNeeded() {
124
		
125
		List<AnnotationEngine> tmp = new ArrayList<AnnotationEngine>();
126
		for (AnnotationEngine a : values()) {
127
			for (Project project : Toolbox.workspace.getProjects()) {
128
				for (CorpusBuild corpus : project.getCorpora()) {
129
					if (a.hasAnnotationsToSave(corpus)) {
130
						tmp.add(a);
131
					}
132
				}
133
			}
134
		}
135
		return tmp;
136
	}
137
	
138
	public HashMap<CorpusBuild, ArrayList<AnnotationEngine>> getEnginesWithSaveNeededPerCorpus() {
139
		
140
		HashMap<CorpusBuild, ArrayList<AnnotationEngine>> tmp = new HashMap<CorpusBuild, ArrayList<AnnotationEngine>>();
141
		for (AnnotationEngine a : values()) {
142
			for (Project project : Toolbox.workspace.getProjects()) {
143
				for (CorpusBuild corpus : project.getCorpora()) {
144
					if (a.hasAnnotationsToSave(corpus)) {
145
						if (!tmp.containsKey(corpus)) tmp.put(corpus, new ArrayList<>());
146
						tmp.get(corpus).add(a);
147
					}
148
				}
149
			}
150
		}
151
		return tmp;
152
	}
102 153
}
TXM/trunk/org.txm.annotation.core/src/org/txm/annotation/core/AnnotationEngine.java (revision 3422)
30 30
	 * @return true if the Annotation Engine has some annotations not saved (that will be lost if not saved)
31 31
	 */
32 32
	public abstract boolean hasAnnotationsToSave(CorpusBuild corpus);
33
	
33
		
34 34
	/**
35 35
	 * 
36 36
	 * @return a StringTokenizer, override this method if the engine needs a speciq tokenization
TXM/trunk/org.txm.annotation.kr.core/src/org/txm/annotation/kr/core/AnnotationManager.java (revision 3422)
1 1
package org.txm.annotation.kr.core;
2 2

  
3 3
import java.io.File;
4
import java.io.IOException;
5
import java.io.PrintWriter;
6
import java.nio.charset.Charset;
4 7
import java.util.ArrayList;
5 8
import java.util.Arrays;
9
import java.util.Comparator;
6 10
import java.util.HashMap;
7 11
import java.util.List;
8 12

  
13
import org.apache.commons.lang.StringUtils;
9 14
import org.eclipse.core.runtime.IProgressMonitor;
10 15
import org.eclipse.osgi.util.NLS;
16
import org.osgi.service.prefs.BackingStoreException;
11 17
import org.txm.annotation.kr.core.messages.KRAnnotationCoreMessages;
12 18
import org.txm.annotation.kr.core.repository.AnnotationEffect;
13 19
import org.txm.annotation.kr.core.repository.AnnotationType;
20
import org.txm.annotation.kr.core.repository.KnowledgeRepository;
14 21
import org.txm.annotation.kr.core.repository.TypedValue;
15 22
import org.txm.annotation.kr.core.storage.temporary.TemporaryAnnotationManager;
23
import org.txm.core.preferences.TBXPreferences;
24
import org.txm.core.preferences.TXMPreferences;
16 25
import org.txm.objects.Match;
17 26
import org.txm.objects.Match2P;
27
import org.txm.searchengine.cqp.AbstractCqiClient;
28
import org.txm.searchengine.cqp.CQPSearchEngine;
29
import org.txm.searchengine.cqp.clientExceptions.CqiClientException;
18 30
import org.txm.searchengine.cqp.corpus.MainCorpus;
31
import org.txm.searchengine.cqp.corpus.QueryResult;
32
import org.txm.searchengine.cqp.corpus.query.CQLQuery;
33
import org.txm.searchengine.cqp.serverException.CqiServerError;
19 34
import org.txm.utils.ConsoleProgressBar;
35
import org.txm.utils.CsvReader;
36
import org.txm.utils.io.IOUtils;
20 37
import org.txm.utils.logger.Log;
21 38

  
22 39
/**
......
286 303
							i--;
287 304
						}
288 305
						else if (!a.getType().equals(annotSelectedType.getId()) && (// different type and inner or outer wrap
289
						(a.getStart() <= start && end <= a.getEnd()) ||
306
								(a.getStart() <= start && end <= a.getEnd()) ||
290 307
								(start <= a.getStart() && a.getEnd() <= end))) {
291 308
							cqpAnnotations.remove(i);
292 309
							i--;
......
396 413
	public boolean isDirty() {
397 414
		return dirty;
398 415
	}
416
	
417
	public boolean exportAnnotationsToTable(File resultFile) throws Exception {
418
		
419
		final String encoding = TBXPreferences.getInstance().getString(TBXPreferences.EXPORT_ENCODING);
420
		String colseparator = TBXPreferences.getInstance().getString(TBXPreferences.EXPORT_COL_SEPARATOR);
421
		String txtseparator = TBXPreferences.getInstance().getString(TBXPreferences.EXPORT_TXT_SEPARATOR);
422
		
423
		List<String> krnames = KRAnnotationEngine.getKnowledgeRepositoryNames(corpus);
424
		if (krnames.size() == 0) {
425
			Log.severe(NLS.bind("** Error: no knowledge repository found in {0} corpus.", corpus));
426
			throw new IllegalArgumentException("No kr in " + corpus);
427
		}
428
		String firtsKRName = krnames.get(0);
429
		KnowledgeRepository defaultKR = KRAnnotationEngine.getKnowledgeRepository(corpus, firtsKRName);
430
		if (defaultKR == null) {
431
			Log.severe(NLS.bind("** Error: no knowledge repository {0} found in {0} corpus.", defaultKR, corpus));
432
			throw new IllegalArgumentException("No kr " + defaultKR + " in " + corpus);
433
		}
434
		
435
		PrintWriter writer = IOUtils.getWriter(resultFile, encoding, false);
436
		String cols [] = {"text_id", "id", "end_id", "start", "end", "type", "value", "mode", "date", "annotator"};
437
		writer.println(StringUtils.join(cols, colseparator));
438
		
439
		if (this.getTemporaryManager().getAnnotations().size() == 0) {
440
			Log.warning("Warning: no annotations to export. Aborting.");
441
			return false;
442
		}
443
		
444
		String[] textsIds = corpus.getCorpusTextIdsList();
445
		int[] textsEndPositions = corpus.getTextEndLimits();
446
		
447
		HashMap<Integer, String> positions2Ids = new HashMap<Integer, String>();
448
		HashMap<Integer, String> positions2TextIds = new HashMap<Integer, String>();
449
		for (Annotation a : this.getTemporaryManager().getAnnotations()) {
450
			positions2Ids.put(a.getStart(), null);
451
			positions2Ids.put(a.getEnd(), null);
452
		}
453
		int[] positions = new int[positions2Ids.keySet().size()];
454
		int i = 0;
455
		for (int p : positions2Ids.keySet()) {
456
			positions[i++] = p;
457
		}
458
		String values[] = corpus.getProperty("id").cpos2Str(positions);
459
		for (i = 0 ; i < positions.length ; i++) {
460
			positions2Ids.put(positions[i], values[i]);
461
		}
462
		
463
		List<Annotation> annotations = this.getTemporaryManager().getAnnotations();
464
		annotations.sort(new Comparator<Annotation>() {
465
			@Override
466
			public int compare(Annotation arg0, Annotation arg1) {
467
				return arg0.getStart() - arg1.getStart();
468
			}
469
		});
470
		
471
		Log.info(NLS.bind("Exporting {0} annotations.", annotations.size()));
472
		ConsoleProgressBar cpb = new ConsoleProgressBar(annotations.size());
473
		
474
		int currentText = 0;
475
		for (Annotation a : annotations) {
476
			cpb.tick();
477
			// text_id	id	start	end	type	value	effect	date	annotator
478
			String effect = defaultKR.getType(a.getType()).getEffect().name();
479
			String startId = positions2Ids.get(a.getStart());
480
			String endId = positions2Ids.get(a.getEnd());
481

  
482
			while (textsEndPositions[currentText] < a.getStart()) {
483
				// System.out.println("currentText="+currentText+" a="+a.getStart()+" text start="+textsEndPositions[currentText]+" text id="+textsIds[currentText]);
484
				currentText++;// go to next text
485
			}
486
			String textid = textsIds[currentText];
487
			
488
			writer.println(
489
					txtseparator+textid.replace(txtseparator, txtseparator+txtseparator)				+txtseparator
490
					+colseparator+txtseparator+startId.replace(txtseparator, txtseparator+txtseparator)				+txtseparator
491
					+colseparator+txtseparator+endId.replace(txtseparator, txtseparator+txtseparator)				+txtseparator
492
					+colseparator+txtseparator+a.getStart()															+txtseparator
493
					+colseparator+txtseparator+a.getEnd()															+txtseparator
494
					+colseparator+txtseparator+a.getType().replace(txtseparator, txtseparator+txtseparator)			+txtseparator
495
					+colseparator+txtseparator+a.getValue().replace(txtseparator, txtseparator+txtseparator)		+txtseparator
496
					+colseparator+txtseparator+effect.replace(txtseparator, txtseparator+txtseparator)				+txtseparator
497
					+colseparator+txtseparator+a.getDate().replace(txtseparator, txtseparator+txtseparator)			+txtseparator
498
					+colseparator+txtseparator+a.getAnnotator().replace(txtseparator, txtseparator+txtseparator)	+txtseparator);
499
		}
500
		writer.close();
501
		cpb.done();
502
		return true;
503
	}
504

  
505
	public boolean importAnnotationsFromTable(File annotationsFile) throws Exception {
506
		
507
		if (!isOpen()) {
508
			this.initialize();
509
		}
510
		
511
		final String encoding = TBXPreferences.getInstance().getString(TBXPreferences.EXPORT_ENCODING);
512
		String colseparator = TBXPreferences.getInstance().getString(TBXPreferences.EXPORT_COL_SEPARATOR);
513
		String txtseparator = TBXPreferences.getInstance().getString(TBXPreferences.EXPORT_TXT_SEPARATOR);
514
		
515
		List<String> krnames = KRAnnotationEngine.getKnowledgeRepositoryNames(corpus);
516
		if (krnames.size() == 0) {
517
			Log.severe(NLS.bind("** Error: no knowledge repository found in {0} corpus.", corpus));
518
			throw new IllegalArgumentException("No kr in " + corpus);
519
		}
520
		String firtsKRName = krnames.get(0);
521
		KnowledgeRepository defaultKR = KRAnnotationEngine.getKnowledgeRepository(corpus, firtsKRName);
522
		if (defaultKR == null) {
523
			Log.severe(NLS.bind("** Error: no knowledge repository {0} found in {0} corpus.", defaultKR, corpus));
524
			throw new IllegalArgumentException("No kr " + defaultKR + " in " + corpus);
525
		}
526
		
527
		CsvReader reader = new CsvReader(annotationsFile.getAbsolutePath(), colseparator.charAt(0), Charset.forName(encoding));
528
		if (txtseparator.length() > 0) reader.setTextQualifier(txtseparator.charAt(0));
529
		reader.readHeaders();
530
		String headers [] = reader.getHeaders();
531
		String cols [] = {"text_id", "id", "end_id", "start", "end", "type", "value", "mode", "date", "annotator"};
532
		if (headers.length != cols.length) {
533
			Log.warning("Error: annotation file header format is not well-formatted: "+StringUtils.join(headers, ", ")+". Should be: "+StringUtils.join(cols, ", "));
534
			return false;
535
		}
536
		for (int i = 0 ; i < cols.length ; i++) {
537
			if (!(headers[i].equals(cols[i]))) {
538
				Log.warning("Error: annotation file header format is not well-formatted: "+StringUtils.join(headers, ", ")+". Should be: "+StringUtils.join(cols, ", "));
539
				return false;
540
			}
541
		}
542
		
543
		int nLines = 0;
544
		while (reader.readRecord()) {
545
			nLines++;
546
		}
547
		reader.close();
548
		
549
		if (nLines == 0) {
550
			Log.warning("Error: no annotation line found");
551
			return false;
552
		}
553
		
554
		Log.info(NLS.bind("Importing {0} annotations...", nLines));
555
		reader = new CsvReader(annotationsFile.getAbsolutePath(), colseparator.charAt(0), Charset.forName(encoding));
556
		if (txtseparator.length() > 0) reader.setTextQualifier(txtseparator.charAt(0));
557
		reader.readHeaders();
558
		ConsoleProgressBar cpb = new ConsoleProgressBar(nLines);
559
		this.tempManager.getEntityManager().getTransaction().begin();
560
		while (reader.readRecord()) {
561
			cpb.tick();
562
			String[] record = reader.getValues();
563
			String typeName = record[5].trim();
564
			String typeEffect = record[7].trim();
565
			if (defaultKR.getType(typeName) == null) {
566
				defaultKR.addType(typeName, typeName, null, AnnotationEffect.valueOf(typeEffect));
567
			}
568
			AnnotationType type = defaultKR.getType(typeName);
569
			String startId = record[1].trim();
570
			String endId = record[2].trim();
571
			int startPos = -1;
572
			int endPos = -1;
573
			if (startId.length() > 0 && endId.length() > 0) { // use the word id if present
574
				String textId = record[0].trim();
575
				if (startId.equals(endId)) {
576
					CQLQuery cql = new CQLQuery(NLS.bind("[id=\"{0}\" & _.text_id=\"{1}\"]", startId, textId));
577
					QueryResult qr = corpus.query(cql , "TMP", false);
578
					if (qr.getNMatch() == 0) {
579
						Log.warning("No match found with CQL="+cql);
580
						continue;
581
					}
582
					startPos = qr.getMatch(0).getStart();
583
					endPos = startPos;
584
				} else {
585
					CQLQuery cql = new CQLQuery(NLS.bind("[id=\"{0}\" & _.text_id=\"{1}\"]", startId, textId));
586
					QueryResult qr = corpus.query(cql , "TMP", false);
587
					if (qr.getNMatch() == 0) {
588
						Log.warning("No match found with CQL="+cql);
589
						continue;
590
					}
591
					startPos = qr.getMatch(0).getStart();
592
					qr.drop();
593
					cql = new CQLQuery(NLS.bind("[id=\"{0}\" & _.text_id=\"{1}\"]", endId, textId));
594
					qr = corpus.query(cql , "TMP", false);
595
					if (qr.getNMatch() == 0) {
596
						Log.warning("No match found with CQL="+cql);
597
						continue;
598
					}
599
					endPos = qr.getMatch(0).getStart();
600
					qr.drop();
601
				}
602
			} else {
603
				startPos = Integer.parseInt(record[3]);
604
				endPos = Integer.parseInt(record[4]);
605
				
606
			}
607
			if (type.getTypedValue(record[6]) == null) {
608
				defaultKR.addValue(record[6], record[6], typeName);
609
			}
610
			TypedValue value = type.getTypedValue(record[6]);
611
			List<Annotation> a = this.tempManager.createAnnotationNoCommit(type, value, startPos, endPos);
612
		}
613
		this.tempManager.getEntityManager().getTransaction().commit();
614
		cpb.done();
615
		
616
		return true;
617
	}
399 618
}
TXM/trunk/org.txm.annotation.kr.core/src/org/txm/annotation/kr/core/storage/temporary/TemporaryAnnotationManager.java (revision 3422)
73 73
	private EntityManager em;
74 74
	
75 75
	private MainCorpus corpus;
76

  
77
	private EntityManagerFactory emf;
76 78
	
77 79
	public TemporaryAnnotationManager(MainCorpus corpus) {
78 80
		this.corpus = corpus;
......
100 102
		if (em != null) {
101 103
			em.close();
102 104
		}
105
		if (emf != null) {
106
			emf.close();
107
		}
103 108
	}
104 109
	
105 110
	
......
301 306
	 * @throws Exception
302 307
	 */
303 308
	public List<Annotation> getAnnotations(AnnotationType refType, int startPosition, int endPosition, String value) {
304
		String query = "SELECT annot FROM Annotation AS annot "
305
				+ "WHERE annot.PK.refType LIKE '" + refType.getId() + "'";
309
		String query = "SELECT annot FROM Annotation AS annot WHERE annot.PK.refType LIKE '" + refType.getId() + "'";
306 310
		if (startPosition >= 0)
307 311
			query += " AND annot.PK.startpos = " + startPosition;
312
		
308 313
		if (endPosition >= 0)
309 314
			query += " AND annot.PK.endpos = " + endPosition;
315
		
310 316
		if (value != null)
311 317
			query += " AND annot.refVal LIKE ':" + value + "' ";
312 318
		
......
501 507
		// infos.getManagedClassNames().add("org.txm.annotation.TypedValue");
502 508
		// pp.generateSchema(infos, properties);
503 509
		
504
		EntityManagerFactory emf = pp.createEntityManagerFactory(DatabasePersistenceManager.PERSISTENCE_UNIT_NAME, properties);
510
		emf = pp.createEntityManagerFactory(DatabasePersistenceManager.PERSISTENCE_UNIT_NAME, properties);
505 511
		
506 512
		em = emf.createEntityManager();
507 513
		
TXM/trunk/org.txm.annotation.kr.core/src/org/txm/annotation/kr/core/KRAnnotationEngine.java (revision 3422)
12 12
import org.osgi.service.prefs.BackingStoreException;
13 13
import org.osgi.service.prefs.Preferences;
14 14
import org.txm.annotation.core.AnnotationEngine;
15
import org.txm.annotation.kr.core.preferences.KRAnnotationPreferences;
15 16
import org.txm.annotation.kr.core.repository.KnowledgeRepository;
16 17
import org.txm.annotation.kr.core.repository.KnowledgeRepositoryManager;
17 18
import org.txm.annotation.kr.core.repository.SQLKnowledgeRepository;
......
427 428
	@Override
428 429
	public void notify(TXMResult r, String state) {
429 430
		
430
		if (r instanceof MainCorpus && "clean".equals(state)) {
431
		if (r instanceof MainCorpus && "before_clean".equals(state)) {
431 432
			
432 433
			MainCorpus c = (MainCorpus) r;
433 434
			
......
439 440
				Log.fine("cleaning KR: " + krname);
440 441
				KRAnnotationEngine.unregisterKnowledgeRepositoryName(c, krname);
441 442
			}
443
			
442 444
			if (c.getProjectDirectory() == null || !c.getProjectDirectory().exists()) {
443 445
				return;
444 446
			}
445 447
			
446 448
			if (ams.get(c) != null && ams.get(c).tempManager != null && ams.get(c).tempManager.getEntityManager() != null ) {
449
				Log.fine("closing temporary annotations database of: "+c);
447 450
				ams.get(c).tempManager.close(); // free files
448 451
			}
449 452
			
......
451 454
			if (buildDirectory.exists()) {
452 455
				DeleteDir.deleteDirectory(buildDirectory);
453 456
			}
457
		} else if (r instanceof MainCorpus && "clean".equals(state)) {
458
			
459
			MainCorpus c = (MainCorpus) r;
460
			
461
			if (c.getProject() == null || c.getProject().getDoUpdate()) {
462
				return;
463
			}
464
			
465
			for (String krname : KRAnnotationEngine.getKnowledgeRepositoryNames(c)) {
466
				Log.fine("cleaning KR: " + krname);
467
				KRAnnotationEngine.unregisterKnowledgeRepositoryName(c, krname);
468
			}
469
			
470
			
471
			
472
			if (c.getProjectDirectory() == null || !c.getProjectDirectory().exists()) {
473
				return;
474
			}
475
			
476
			if (ams.get(c) != null && ams.get(c).tempManager != null && ams.get(c).tempManager.getEntityManager() != null ) {
477
				Log.fine("closing temporary annotations databse of: "+c);
478
				ams.get(c).tempManager.close(); // free files
479
			}
480
			
481
			File buildDirectory = new File(c.getProjectDirectory(), "temporary_annotations/" + c.getID());
482
			if (buildDirectory.exists()) {
483
				DeleteDir.deleteDirectory(buildDirectory);
484
			}
454 485
		}
455 486
		else if (r instanceof Project && "clean".equals(state)) {
456 487
			
......
514 545
	
515 546
	@Override
516 547
	public boolean hasAnnotationsToSave(CorpusBuild corpus) {
548
		
549
		if (KRAnnotationPreferences.getInstance().getBoolean(KRAnnotationPreferences.PRESERVE_ANNOTATIONS)) return false;
550
		
517 551
		if (!ams.containsKey(corpus)) return false; // no annotation manager -> not annotations to save
518 552
		return ams.get(corpus).hasChanges();
519 553
	}
TXM/trunk/org.txm.annotation.kr.core/src/org/txm/annotation/kr/core/repository/KnowledgeRepositoryManager.java (revision 3422)
343 343
			kr.deleteType(annotType);
344 344
		}
345 345
		repositories.remove(kr.getName());
346
		kr.close();
346 347
	}
347 348
	
348 349
	
349
	
350
	
351 350
}
TXM/trunk/org.txm.annotation.kr.core/src/org/txm/annotation/kr/core/repository/KnowledgeRepository.java (revision 3422)
50 50
	protected String accessType;
51 51
	
52 52
	protected HashMap<String, String> accessProperties;
53

  
54
	private EntityManagerFactory emf;
53 55
	
54 56
	public final static String NAME = "name";
55 57
	
......
93 95
	public EntityManager initializeEntityManager() {
94 96
		this.dbPath = new File(Toolbox.getTxmHomePath(), "repositories/" + name).getAbsolutePath();
95 97
		// System.out.println("KnowledgeRepository.initializeEntityManager [DB @ "+dbPath+"]");
96
		EntityManagerFactory emf;
98
		
97 99
		HashMap<String, Object> properties = new HashMap<String, Object>();
98 100
		properties.put(PersistenceUnitProperties.CLASSLOADER, this.getClass().getClassLoader());
99 101
		// ClassLoader loader = BundleUtils.getLoader("org.txm.annotation.core");
......
311 313
				buildTypes();
312 314
			}
313 315
			else {
314
				Log.warning("KR Annotation Types already exist:");
315
				for (AnnotationType annotType : annotTypes) {
316
					Log.warning(NLS.bind(" - Type : {0}", annotType.getName()));
317
				}
316
//				Log.warning("KR Annotation Types already exist:");
317
//				for (AnnotationType annotType : annotTypes) {
318
//					Log.warning(NLS.bind(" - Type : {0}", annotType.getName()));
319
//				}
318 320
			}
319 321
		} else {
320 322
			buildTypes();
......
499 501
		// TODO Auto-generated method stub
500 502
		
501 503
	}
504

  
505
	public void close() {
506
		
507
		if (jpaem != null) jpaem.close();
508
		if (emf != null) emf.close();
509
	}
502 510
}
TXM/trunk/org.txm.core/src/java/org/txm/objects/Project.java (revision 3422)
1135 1135
	@Override
1136 1136
	public void clean() {
1137 1137
		
1138
		Toolbox.notifyEngines(this, "before_clean"); // if an extension needs to free some files before
1139
		
1138 1140
		if (rcpProject != null) {
1139 1141
			try {
1140 1142
				// Toolbox.getEngineManager(EngineType.SEARCH).getEngine("CQP").stop(); //$NON-NLS-1$
TXM/trunk/org.txm.annotation.kr.rcp/src/org/txm/annotation/kr/rcp/concordance/KRAnnotation.java (revision 3422)
194 194
			}
195 195
		});
196 196
		
197
		ext.getSaveButton().setEnabled(true);
197
//		ext.getSaveButton().setEnabled(true);
198 198
		return composeAnnotationArea(parent);
199 199
	}
200 200
	
......
1050 1050
	
1051 1051
	@Override
1052 1052
	public boolean isDirty() {
1053
		return annotManager != null;
1053
		return annotManager != null && annotManager.isDirty();
1054 1054
	}
1055 1055
	
1056 1056
	@Override
TXM/trunk/org.txm.annotation.kr.rcp/src/org/txm/annotation/kr/rcp/concordance/WordAnnotationToolbar.java (revision 3422)
831 831
		
832 832
		updateAnnotationWidgetStates();
833 833
		editor.layout(true);
834
		ext.getSaveButton().setEnabled(true);
834
//		ext.getSaveButton().setEnabled(true);
835 835
		return true;
836 836
	}
837 837
	
TXM/trunk/org.txm.annotation.kr.rcp/src/org/txm/annotation/kr/rcp/concordance/SimpleKRAnnotation.java (revision 3422)
388 388
		updateAnnotationWidgetStates();
389 389
		editor.layout(true);
390 390
		
391
		ext.getSaveButton().setEnabled(true);
391
//		ext.getSaveButton().setEnabled(true);
392 392
		return true;
393 393
	}
394 394
	
TXM/trunk/org.txm.annotation.kr.rcp/src/org/txm/annotation/kr/rcp/commands/ExportTable.java (revision 3422)
1
// Copyright © 2010-2020 ENS de Lyon., University of Franche-Comté
2
// Copyright © 2007-2010 ENS de Lyon, CNRS, INRP, University of
3
// Lyon 2, University of Franche-Comté, University of Nice
4
// Sophia Antipolis, University of Paris 3.
5
// 
6
// The TXM platform is free software: you can redistribute it
7
// and/or modify it under the terms of the GNU General Public
8
// License as published by the Free Software Foundation,
9
// either version 2 of the License, or (at your option) any
10
// later version.
11
// 
12
// The TXM platform is distributed in the hope that it will be
13
// useful, but WITHOUT ANY WARRANTY; without even the implied
14
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15
// PURPOSE. See the GNU General Public License for more
16
// details.
17
// 
18
// You should have received a copy of the GNU General
19
// Public License along with the TXM platform. If not, see
20
// http://www.gnu.org/licenses.
21
// 
22
// 
23
// 
24
// $LastChangedDate:$
25
// $LastChangedRevision:$
26
// $LastChangedBy:$ 
27
//
28
package org.txm.annotation.kr.rcp.commands;
29

  
30
import java.io.File;
31

  
32
import org.eclipse.core.commands.AbstractHandler;
33
import org.eclipse.core.commands.ExecutionEvent;
34
import org.eclipse.core.commands.ExecutionException;
35
import org.eclipse.core.runtime.IProgressMonitor;
36
import org.eclipse.core.runtime.IStatus;
37
import org.eclipse.core.runtime.Status;
38
import org.eclipse.jface.viewers.ISelection;
39
import org.eclipse.jface.viewers.IStructuredSelection;
40
import org.eclipse.osgi.util.NLS;
41
import org.eclipse.swt.SWT;
42
import org.eclipse.swt.widgets.FileDialog;
43
import org.eclipse.swt.widgets.Shell;
44
import org.eclipse.ui.handlers.HandlerUtil;
45
import org.txm.Toolbox;
46
import org.txm.annotation.kr.core.AnnotationManager;
47
import org.txm.annotation.kr.core.KRAnnotationEngine;
48
import org.txm.rcp.StatusLine;
49
import org.txm.rcp.messages.TXMUIMessages;
50
import org.txm.rcp.swt.dialog.LastOpened;
51
import org.txm.rcp.utils.JobHandler;
52
import org.txm.searchengine.cqp.corpus.MainCorpus;
53
import org.txm.utils.logger.Log;
54

  
55
/**
56
 * Open a file in the TxtEditor 
57
 * 
58
 * @author mdecorde.
59
 */
60
public class ExportTable extends AbstractHandler {
61
	
62
	public static final String ID = ExportTable.class.getCanonicalName();
63
	
64
	
65
	/* (non-Javadoc)
66
	 * @see org.eclipse.core.commands.AbstractHandler#execute(org.eclipse.core.commands.ExecutionEvent)
67
	 */
68
	@Override
69
	public Object execute(ExecutionEvent event) throws ExecutionException {
70
		
71
		ISelection sel = (IStructuredSelection) HandlerUtil.getCurrentSelection(event);
72
		if (!(sel instanceof IStructuredSelection)) return null;
73
		IStructuredSelection selection = (IStructuredSelection) sel;
74
		
75
		Object s = selection.getFirstElement();
76
		if (!(s instanceof MainCorpus)) {
77
			Log.warning(NLS.bind("Selection is not a Corpus: {0}. Aborting.", s));
78
			return null;
79
		}
80
		
81
		Shell shell = HandlerUtil.getActiveWorkbenchWindowChecked(event).getShell();
82
		//FileDialog dialog = new FileDialog(shell, SWT.SAVE);
83
		FileDialog dialog = new FileDialog(shell, SWT.SAVE);
84
		MainCorpus corpus = (MainCorpus) s;
85
		String path = Toolbox.getTxmHomePath();
86
		dialog.setFilterPath(path); //To set a specific path
87
		dialog.setFileName(corpus.getID()+"_annotations.csv");
88
		dialog.setFilterExtensions(new String[]{"*.csv", "*.tsv"});
89
		if (dialog.open() != null) {
90
			StatusLine.setMessage(TXMUIMessages.exportingAnnotations);
91
			String filepath = dialog.getFilterPath();
92
			String filename = dialog.getFileName();
93
			
94
			final File resultFile = new File(filepath, filename);
95
			LastOpened.set(ID, resultFile.getParent(), resultFile.getName());
96
			
97
			try {
98
				exportAnnotations(corpus, resultFile);
99
			} catch (Exception e) {
100
				// TODO Auto-generated catch block
101
				e.printStackTrace();
102
				return null;
103
			}
104
		}
105
		return corpus;
106
	}
107
	
108
	public static boolean exportAnnotations(final MainCorpus corpus, final File resultFile) throws Exception {
109
		final AnnotationManager am = KRAnnotationEngine.getAnnotationManager(corpus);
110
		if (am == null) return true; // nothing to do
111
				
112
		JobHandler jobhandler = new JobHandler("Exporting annotations in table for "+corpus) { //$NON-NLS-1$
113
			@Override
114
			protected IStatus run(IProgressMonitor monitor) {
115
				this.runInit(monitor);
116
				try {
117
					monitor.beginTask("Exporting annotations as standoff", 100);
118
					
119
					monitor.setTaskName("Writing annotations in the table file: "+resultFile);
120
					/*if (MessageDialog.openConfirm(Display.getCurrent().getActiveShell(), "Before saving annotations...", "All editors using this corpus are going to be closed. Continue ?")) {
121
						return false;
122
					}*/
123
					
124
					///lecture de tous les fichiers un par un
125
					///chaque annotation est récupérée et selon l'annotateur, écrite dans un fichier spécifique à celui-ci
126
					
127
					if (!am.exportAnnotationsToTable(resultFile)) {
128
						Log.warning("Error while exporting annotations (see logs above).");
129
						return Status.CANCEL_STATUS;
130
					}
131
					monitor.worked(30);
132
					
133
					Log.info("Done.");
134
					
135
				} catch(Exception e) {
136
					Log.warning(NLS.bind("Error while saving annotations: {0}.", e));
137
					Log.printStackTrace(e);
138
					return Status.CANCEL_STATUS;
139
				}
140
				return Status.OK_STATUS;
141
			}
142
		};
143
		
144
		jobhandler.startJob(true);
145
		return true;
146
	}
147
}
0 148

  
TXM/trunk/org.txm.annotation.kr.rcp/src/org/txm/annotation/kr/rcp/commands/ImportTable.java (revision 3422)
1
// Copyright © 2010-2020 ENS de Lyon., University of Franche-Comté
2
// Copyright © 2007-2010 ENS de Lyon, CNRS, INRP, University of
3
// Lyon 2, University of Franche-Comté, University of Nice
4
// Sophia Antipolis, University of Paris 3.
5
// 
6
// The TXM platform is free software: you can redistribute it
7
// and/or modify it under the terms of the GNU General Public
8
// License as published by the Free Software Foundation,
9
// either version 2 of the License, or (at your option) any
10
// later version.
11
// 
12
// The TXM platform is distributed in the hope that it will be
13
// useful, but WITHOUT ANY WARRANTY; without even the implied
14
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15
// PURPOSE. See the GNU General Public License for more
16
// details.
17
// 
18
// You should have received a copy of the GNU General
19
// Public License along with the TXM platform. If not, see
20
// http://www.gnu.org/licenses.
21
// 
22
// 
23
// 
24
// $LastChangedDate:$
25
// $LastChangedRevision:$
26
// $LastChangedBy:$ 
27
//
28
package org.txm.annotation.kr.rcp.commands;
29

  
30
import java.io.File;
31

  
32
import org.eclipse.core.commands.AbstractHandler;
33
import org.eclipse.core.commands.ExecutionEvent;
34
import org.eclipse.core.commands.ExecutionException;
35
import org.eclipse.core.runtime.IProgressMonitor;
36
import org.eclipse.core.runtime.IStatus;
37
import org.eclipse.core.runtime.Status;
38
import org.eclipse.jface.viewers.ISelection;
39
import org.eclipse.jface.viewers.IStructuredSelection;
40
import org.eclipse.osgi.util.NLS;
41
import org.eclipse.swt.SWT;
42
import org.eclipse.swt.widgets.FileDialog;
43
import org.eclipse.swt.widgets.Shell;
44
import org.eclipse.ui.handlers.HandlerUtil;
45
import org.txm.Toolbox;
46
import org.txm.annotation.kr.core.AnnotationManager;
47
import org.txm.annotation.kr.core.KRAnnotationEngine;
48
import org.txm.rcp.StatusLine;
49
import org.txm.rcp.messages.TXMUIMessages;
50
import org.txm.rcp.swt.dialog.LastOpened;
51
import org.txm.rcp.utils.JobHandler;
52
import org.txm.searchengine.cqp.corpus.MainCorpus;
53
import org.txm.utils.logger.Log;
54

  
55
/**
56
 * Open a file in the TxtEditor 
57
 * 
58
 * @author mdecorde.
59
 */
60
public class ImportTable extends AbstractHandler {
61
	
62
	public static final String ID = ImportTable.class.getCanonicalName();
63
	
64
	
65
	/* (non-Javadoc)
66
	 * @see org.eclipse.core.commands.AbstractHandler#execute(org.eclipse.core.commands.ExecutionEvent)
67
	 */
68
	@Override
69
	public Object execute(ExecutionEvent event) throws ExecutionException {
70
		
71
		ISelection sel = (IStructuredSelection) HandlerUtil.getCurrentSelection(event);
72
		if (!(sel instanceof IStructuredSelection)) return null;
73
		IStructuredSelection selection = (IStructuredSelection) sel;
74
		
75
		Object s = selection.getFirstElement();
76
		if (!(s instanceof MainCorpus)) {
77
			Log.warning(NLS.bind("Selection is not a Corpus: {0}. Aborting.", s));
78
			return null;
79
		}
80
		
81
		Shell shell = HandlerUtil.getActiveWorkbenchWindowChecked(event).getShell();
82
		//FileDialog dialog = new FileDialog(shell, SWT.SAVE);
83
		FileDialog dialog = new FileDialog(shell, SWT.OPEN);
84
		MainCorpus corpus = (MainCorpus) s;
85
		String path = Toolbox.getTxmHomePath();
86
		dialog.setFilterPath(path); //To set a specific path
87
		dialog.setFileName(corpus.getID()+"_annotations.csv");
88
		dialog.setFilterExtensions(new String[]{"*.csv", "*.tsv"});
89
		if (dialog.open() != null) {
90
			StatusLine.setMessage(TXMUIMessages.exportingAnnotations);
91
			String filepath = dialog.getFilterPath();
92
			String filename = dialog.getFileName();
93
			
94
			final File resultFile = new File(filepath, filename);
95
			LastOpened.set(ID, resultFile.getParent(), resultFile.getName());
96
			
97
			try {
98
				importAnnotations(corpus, resultFile);
99
			} catch (Exception e) {
100
				// TODO Auto-generated catch block
101
				e.printStackTrace();
102
				return null;
103
			}
104
		}
105
		return corpus;
106
	}
107
	
108
	public static boolean importAnnotations(final MainCorpus corpus, final File annotationsFile) throws Exception {
109
		final AnnotationManager am = KRAnnotationEngine.getAnnotationManager(corpus);
110
		if (am == null) return true; // nothing to do
111
				
112
		JobHandler jobhandler = new JobHandler("Importing annotations in table for "+corpus) { //$NON-NLS-1$
113
			@Override
114
			protected IStatus run(IProgressMonitor monitor) {
115
				this.runInit(monitor);
116
				try {
117
					monitor.beginTask("Importing annotations as standoff", 100);
118
					
119
					monitor.setTaskName("Reading annotations in the table file: "+annotationsFile);
120
					/*if (MessageDialog.openConfirm(Display.getCurrent().getActiveShell(), "Before saving annotations...", "All editors using this corpus are going to be closed. Continue ?")) {
121
						return false;
122
					}*/
123
					
124
					///lecture de tous les fichiers un par un
125
					///chaque annotation est récupérée et selon l'annotateur, écrite dans un fichier spécifique à celui-ci
126
					
127
					if (!am.importAnnotationsFromTable(annotationsFile)) {
128
						Log.warning("Error while importing annotations (see logs above).");
129
						return Status.CANCEL_STATUS;
130
					}
131
					monitor.worked(30);
132
					
133
					Log.info("Done.");
134
					
135
				} catch(Exception e) {
136
					Log.warning(NLS.bind("Error while importing annotations: {0}.", e));
137
					Log.printStackTrace(e);
138
					return Status.CANCEL_STATUS;
139
				}
140
				return Status.OK_STATUS;
141
			}
142
		};
143
		
144
		jobhandler.startJob(true);
145
		return true;
146
	}
147
}
0 148

  
TXM/trunk/org.txm.annotation.kr.rcp/src/org/txm/annotation/kr/rcp/commands/krview/Add.java (revision 3422)
66 66
	}
67 67

  
68 68
	/**
69
	 * Copy.
69
	 * Add a new annotation type or value.
70 70
	 *
71 71
	 * @param selection the selection
72 72
	 */
TXM/trunk/org.txm.annotation.kr.rcp/src/org/txm/annotation/kr/rcp/edition/WordAnnotationToolbar.java (revision 3422)
715 715
		
716 716
		updateAnnotationWidgetStates();
717 717
		editor.layout(true);
718
		ext.getSaveButton().setEnabled(true);
718
//		ext.getSaveButton().setEnabled(true);
719 719
		return true;
720 720
	}
721 721
	
TXM/trunk/org.txm.annotation.kr.rcp/OSGI-INF/l10n/bundle_fr.properties (revision 3422)
2 2
#Mon Jun 08 11:30:22 CEST 2020
3 3
command.label=Entrep?t de connaissances
4 4
command.label.0=Textes et Annotations CQP de s?quences de mots au format XML-TEI SyMoGIH (.xml)...
5
command.label.1=Annotations CQP au format Table (.csv)...
5 6
command.name=Recoder
6 7
command.name.0=Enregistrer les annotations
7 8
command.name.1=Ouvrir la vue d'entrep?ts de connaissance
TXM/trunk/org.txm.annotation.kr.rcp/OSGI-INF/l10n/bundle.properties (revision 3422)
3 3
Bundle-Name=KR Annotation RCP
4 4
command.label=Knowledge Respository
5 5
command.label.0=Texts and CQP Annotations of word sequences in XML-TEI SyMoGIH format (.xml)
6
command.label.1=CQP Annotations in Table format (.csv)
6 7
command.name=Recode
7 8
command.name.0=Save annotations
8 9
command.name.1=Open Knowledge Repository View
TXM/trunk/org.txm.annotation.kr.rcp/plugin.xml (revision 3422)
56 56
            id="org.txm.annotation.kr.rcp.commands.SaveAnnotationsAndUpdateCorpus"
57 57
            name="%command.label.111">
58 58
      </command>
59
      <command
60
            defaultHandler="org.txm.annotation.kr.rcp.commands.ExportTable"
61
            id="org.txm.annotation.kr.rcp.commands.ExportTable"
62
            name="Export in table">
63
      </command>
64
      <command
65
            defaultHandler="org.txm.annotation.kr.rcp.commands.ImportTable"
66
            id="org.txm.annotation.kr.rcp.commands.ImportTable"
67
            name="Import from table">
68
      </command>
59 69
   </extension>
60 70
  <extension
61 71
        point="org.eclipse.ui.preferencePages">
......
178 188
      </menuContribution>
179 189
     <menuContribution
180 190
           allPopups="false"
191
           locationURI="menu:menu.file.export.properties">
192
        <command
193
              commandId="org.txm.rcp.commands.annotation.ExportStandoff"
194
              id="menu.file.export.exporttei"
195
              label="%command.label.0"
196
              style="push">
197
           <visibleWhen
198
                 checkEnabled="false">
199
              <reference
200
                    definitionId="OneMainCorpusSelected">
201
              </reference>
202
           </visibleWhen>
203
        </command>
204
     </menuContribution>
205
     <menuContribution
206
           allPopups="false"
181 207
           locationURI="menu:menu.file.export.annotations">
182 208
           <command
183
                     commandId="org.txm.rcp.commands.annotation.ExportStandoff"
184
                     id="menu.file.export.exporttei"
185
                     label="%command.label.0"
186
                     style="push">
187
                  <visibleWhen
188
                        checkEnabled="false">
189
                     <reference
190
                           definitionId="OneMainCorpusSelected">
191
                     </reference>
192
                  </visibleWhen>
193
               </command>
209
                 commandId="org.txm.annotation.kr.rcp.commands.ExportTable"
210
                 id="menu.file.export.exporttable"
211
                 label="%command.label.1"
212
                 style="push">
213
              <visibleWhen
214
                    checkEnabled="false">
215
                 <reference
216
                       definitionId="OneMainCorpusSelected">
217
                 </reference>
218
              </visibleWhen>
219
           </command>
194 220
     </menuContribution>
195 221
     <menuContribution
196 222
           allPopups="false"
197 223
           locationURI="menu:corporaview.menu.file.export?after=org.txm.rcp.views.corpora.CorporaView.annotation">
198 224
            <command
199 225
                  commandId="org.txm.rcp.commands.annotation.ExportStandoff"
200
                  label="%command.label.193"
226
                  label="%command.label.0"
201 227
                  style="push">
202 228
               <visibleWhen
203 229
                     checkEnabled="false">
......
206 232
                  </reference>
207 233
               </visibleWhen>
208 234
            </command>
235
            <command
236
                  commandId="org.txm.annotation.kr.rcp.commands.ExportTable"
237
                  label="%command.label.1"
238
                  style="push">
239
               <visibleWhen
240
                     checkEnabled="false">
241
                  <reference
242
                        definitionId="OneMainCorpusSelected">
243
                  </reference>
244
               </visibleWhen>
245
            </command>
209 246
     </menuContribution>
210 247
     <menuContribution
211 248
           allPopups="false"
......
255 292
           </visibleWhen>
256 293
        </command>
257 294
     </menuContribution>
295
     <menuContribution
296
           locationURI="menu:menu.file.import.annotations">
297
        <command
298
              commandId="org.txm.annotation.kr.rcp.commands.ImportTable"
299
              label="CQP Annotation from Table (.csv)"
300
              style="push">
301
           <visibleWhen
302
                 checkEnabled="false">
303
              <reference
304
                    definitionId="OneMainCorpusSelected">
305
              </reference>
306
           </visibleWhen>
307
        </command>
308
     </menuContribution>
258 309
  </extension>
259 310
  <extension
260 311
         point="org.eclipse.ui.contexts">
TXM/trunk/org.txm.xmleditor.rcp/build.properties (revision 3422)
3 3
bin.includes = plugin.xml,\
4 4
               META-INF/,\
5 5
               .,\
6
               OSGI-INF/
6
               OSGI-INF/,\
7
               OSGI-INF/l10n/bundle.properties
7 8
source..=src/
8 9
#qualifier=svn
TXM/trunk/org.txm.xmleditor.rcp/OSGI-INF/l10n/bundle.properties (revision 3422)
1 1
#Properties file for XmlEditorRCP
2 2
command.name = Open XML File...
3
command.name2 = Open the XML-TEI TXM file
4 3
command.label = XmlEditor
5 4
command.tooltip = Open the selected file with the XML editor
6 5
activity.name = disable activity
7
Bundle-Name = XmlEditorRCP
6
Bundle-Name = XmlEditorRCP
7
command.label.0 = Open the XML-TEI TXM file
TXM/trunk/org.txm.xmleditor.rcp/OSGI-INF/l10n/bundle_fr.properties (revision 3422)
9 9

  
10 10
command.name = Ouvrir un fichier XML
11 11

  
12
command.name2 = Ouvrir le fichier XML-TEI TXM
13

  
12
command.label.0 = Ouvrir le fichier XML-TEI TXM
14 13
command.tooltip = Ouvre le fichier s\u00E9lectionner dans l'\u00E9diteur XML
TXM/trunk/org.txm.xmleditor.rcp/plugin.xml (revision 3422)
25 25
            locationURI="popup:org.txm.edition.rcp.editors.SynopticEditionEditor">
26 26
         <command
27 27
               commandId="org.txm.xmleditor.OpenXMLEditor"
28
               label="%command.label.0"
28 29
               style="push">
29 30
         </command>
30 31
      </menuContribution>
......
32 33
            locationURI="popup:org.txm.concordance.rcp.editors.ConcordanceEditor">
33 34
         <command
34 35
               commandId="org.txm.xmleditor.OpenXMLEditor"
35
               label="%command.name2"
36
               label="%command.label.0"
36 37
               style="push">
37 38
         </command>
38 39
      </menuContribution>
TXM/trunk/org.txm.xmleditor.rcp/src/org/txm/xmleditor/OpenXMLEditor.java (revision 3422)
12 12
import org.eclipse.core.runtime.CoreException;
13 13
import org.eclipse.core.runtime.FileLocator;
14 14
import org.eclipse.core.runtime.Path;
15
import org.eclipse.jface.dialogs.MessageDialog;
15 16
import org.eclipse.jface.viewers.ISelection;
16 17
import org.eclipse.jface.viewers.IStructuredSelection;
17 18
import org.eclipse.search.ui.ISearchQuery;
......
47 48
	
48 49
	public static String lastopenedfile;
49 50
	
51
	public int ALERT = 1000;
50 52
	
51 53
	@Override
52 54
	public Object execute(ExecutionEvent event) throws ExecutionException {
......
68 70
			
69 71
			File txmFile = text.getXMLTXMFile();
70 72
			if (txmFile != null && txmFile.exists()) {
73
				if (txmFile.length() > ALERT) {
74
					if (!MessageDialog.openQuestion(shell, "Big file /o\\", txmFile.getAbsolutePath()+" is a very big file. Do you want to continue and opens it?")) {
75
						Log.info("Aborting the opening of "+txmFile);
76
						return null;
77
					}
78
				}
71 79
				reditor = openfile(txmFile);
72 80
			}
73 81
			else { // wrong link ?
......
104 112
				XMLMultiPageEditorPart xmlEditor = (XMLMultiPageEditorPart) reditor;
105 113
				Object selectedPage = xmlEditor.getSelectedPage();
106 114
				if (selectedPage != null && selectedPage instanceof StructuredTextEditor) {
107
					System.out.println("Word selection: " + line.getKeywordIds());
115
					System.out.println("Word selection identifiers: " + line.getKeywordIds());
108 116
				}
109 117
			}
110 118
		}
TXM/trunk/org.txm.searchengine.cqp.rcp/plugin.xml (revision 3422)
222 222
         </command>
223 223
      </menuContribution>
224 224
      <menuContribution
225
            locationURI="menu:menu.file.export?after=menu.file.export.begin">
225
            locationURI="menu:menu.file.export.corpus">
226 226
         <command
227 227
               commandId="org.txm.searchengine.cqp.rcp.handlers.base.ExportCorpus"
228 228
               icon="icons/functions/compress.png"
TXM/trunk/org.txm.annotation.rcp/src/org/txm/annotation/rcp/editor/AnnotationExtension.java (revision 3422)
39 39
	
40 40
	private SelectionListener defaultListener;
41 41
	
42
	private ToolItem saveButton;
42
	//private ToolItem saveButton;
43 43
	
44 44
	public static final String GROUP_NAME = "Annotation";
45 45
	
......
48 48
		return GROUP_NAME;
49 49
	}
50 50
	
51
	/**
52
	 * use this to enable/disable the button
53
	 * 
54
	 * @return
55
	 */
56
	public ToolItem getSaveButton() {
57
		return saveButton;
58
	}
51
//	/**
52
//	 * use this to enable/disable the button
53
//	 * 
54
//	 * @return
55
//	 */
56
//	public ToolItem getSaveButton() {
57
//		return saveButton;
58
//	}
59 59
	
60 60
	/**
61 61
	 * install the annotation start button and dropdown list
......
144 144
				openCloseSelectionListener, modes, listeners);
145 145
		controlArea.setLayout(new GridLayout(1, true));
146 146
		
147
		saveButton = new ToolItem(editor.getTopToolbar(), SWT.PUSH);
148
		saveButton.setText("Save annotations");
149
		//saveButton.setImage(IImageKeys.getImage(IImageKeys.PENCIL_SAVE));
150
		saveButton.addSelectionListener(new SelectionListener() {
151
			
152
			@Override
153
			public void widgetSelected(SelectionEvent e) {
154
				try {
155
					notifyDoSave();
156
				}
157
				catch (Exception e1) {
158
					Log.printStackTrace(e1);
159
				}
160
			}
161
			
162
			@Override
163
			public void widgetDefaultSelected(SelectionEvent e) {}
164
		});
165
		saveButton.setEnabled(false);
147
//		saveButton = new ToolItem(editor.getTopToolbar(), SWT.PUSH);
148
//		saveButton.setText("Save annotations");
149
//		//saveButton.setImage(IImageKeys.getImage(IImageKeys.PENCIL_SAVE));
150
//		saveButton.addSelectionListener(new SelectionListener() {
151
//			
152
//			@Override
153
//			public void widgetSelected(SelectionEvent e) {
154
//				try {
155
//					notifyDoSave();
156
//				}
157
//				catch (Exception e1) {
158
//					Log.printStackTrace(e1);
159
//				}
160
//			}
161
//			
162
//			@Override
163
//			public void widgetDefaultSelected(SelectionEvent e) {}
164
//		});
165
//		saveButton.setEnabled(false);
166 166
	}
167 167
	
168 168
	public void closeAreasPanel() {
169 169
		editor.getTopToolbar().setVisible(GROUP_NAME, false);
170 170
		editor.getTopToolbar().getOpenCloseButton().setSelection(false);
171
		saveButton.setEnabled(false);
171
//		saveButton.setEnabled(false);
172 172
	}
173 173
	
174 174
	public void openAnnotationMode(AnnotationArea aa, int position) throws Exception {
......
268 268
	
269 269
	@Override
270 270
	public boolean isDirty() throws Exception {
271
		boolean dirty = false;
272
		for (AnnotationArea aa : annotationAreas) {
273
			dirty = dirty || aa.isDirty();
274
		}
275
		return dirty;
271
		return false;
272
		
273
//		boolean dirty = false;
274
//		for (AnnotationArea aa : annotationAreas) {
275
//			dirty = dirty || aa.isDirty();
276
//		}
277
//		return dirty;
276 278
	}
277 279
	
278 280
	@Override
......
284 286
	public void notifyDoSave() throws Exception {
285 287
		
286 288
		//		if (needToUpdateIndexes) {
287
		JobHandler job = new JobHandler("Updating corpus indexes and editions", true) {
288
			
289
			@Override
290
			protected IStatus run(IProgressMonitor monitor) {
291
				
292
				this.runInit(monitor);
293
				
294
				try {
295
					monitor.setTaskName("Updating corpus XML-TXM files");
296
					
297
					Log.info("Saving annotations...");
298
					boolean needToUpdateIndexes = false;
299
					boolean needToUpdateEditions = false;
300
					// System.out.println("Saving annotations...");
301
					if (annotationAreas != null && annotationAreas.size() > 0) {
302
						for (AnnotationArea aa : annotationAreas) {
303
							needToUpdateIndexes = needToUpdateIndexes 
304
									|| (aa.isDirty() 
305
											&& aa.save()
306
											&& aa.needToUpdateIndexes());
307
							needToUpdateEditions = needToUpdateEditions || aa.needToUpdateEditions();
308
						}
309
					}
310
					
311
					if (needToUpdateIndexes) {
312
						final MainCorpus corpus = editor.getResult().getFirstParent(MainCorpus.class);
313
						monitor.setTaskName("Updating corpus indexes and editions");
314
						if (corpus != null && UpdateCorpus.update(corpus, needToUpdateEditions) != null) {
315
							monitor.worked(50);
316
							this.syncExec(new Runnable() {
317
								
318
								@Override
319
								public void run() {
320
									Log.info("Done.");
321
									CorporaView.refreshObject(corpus);
322
									if (!saveButton.isDisposed()) {
323
										saveButton.setEnabled(false);
324
									}
325
								}
326
							});
327
							return Status.OK_STATUS;
328
						}
329
						else {
330
							monitor.worked(50);
331
							Log.warning("Fail to update corpus. Aborting");
332
							Log.warning("Fix XML-TXM files and call command 'UpdateCorpus'");
333
							return Status.CANCEL_STATUS;
334
						}
335
					} else {
336
						this.syncExec(new Runnable() {
337
							
338
							@Override
339
							public void run() {
340
								Log.info("Done.");
341
								if (!saveButton.isDisposed()) {
342
									saveButton.setEnabled(false);
343
								}
344
							}
345
						});
346
						return Status.OK_STATUS;
347
					}
348
				} catch(ThreadDeath ex) {
349
					Log.warning(TXMUIMessages.executionCanceled);
350
					return Status.CANCEL_STATUS;
351
				}
352
			}
353
		};
354
		job.schedule();
289
//		JobHandler job = new JobHandler("Updating corpus indexes and editions", true) {
290
//			
291
//			@Override
292
//			protected IStatus run(IProgressMonitor monitor) {
293
//				
294
//				this.runInit(monitor);
295
//				
296
//				try {
297
//					monitor.setTaskName("Updating corpus XML-TXM files");
298
//					
299
//					Log.info("Saving annotations...");
300
//					boolean needToUpdateIndexes = false;
301
//					boolean needToUpdateEditions = false;
302
//					// System.out.println("Saving annotations...");
303
//					if (annotationAreas != null && annotationAreas.size() > 0) {
304
//						for (AnnotationArea aa : annotationAreas) {
305
//							needToUpdateIndexes = needToUpdateIndexes 
306
//									|| (aa.isDirty() 
307
//											&& aa.save()
308
//											&& aa.needToUpdateIndexes());
309
//							needToUpdateEditions = needToUpdateEditions || aa.needToUpdateEditions();
310
//						}
311
//					}
312
//					
313
//					if (needToUpdateIndexes) {
314
//						final MainCorpus corpus = editor.getResult().getFirstParent(MainCorpus.class);
315
//						monitor.setTaskName("Updating corpus indexes and editions");
316
//						if (corpus != null && UpdateCorpus.update(corpus, needToUpdateEditions) != null) {
317
//							monitor.worked(50);
318
//							this.syncExec(new Runnable() {
319
//								
320
//								@Override
321
//								public void run() {
322
//									Log.info("Done.");
323
//									CorporaView.refreshObject(corpus);
324
//									if (!saveButton.isDisposed()) {
325
//										saveButton.setEnabled(false);
326
//									}
327
//								}
328
//							});
329
//							return Status.OK_STATUS;
330
//						}
331
//						else {
332
//							monitor.worked(50);
333
//							Log.warning("Fail to update corpus. Aborting");
334
//							Log.warning("Fix XML-TXM files and call command 'UpdateCorpus'");
335
//							return Status.CANCEL_STATUS;
336
//						}
337
//					} else {
338
//						this.syncExec(new Runnable() {
339
//							
340
//							@Override
341
//							public void run() {
342
//								Log.info("Done.");
343
//								if (!saveButton.isDisposed()) {
344
//									saveButton.setEnabled(false);
345
//								}
346
//							}
347
//						});
348
//						return Status.OK_STATUS;
349
//					}
350
//				} catch(ThreadDeath ex) {
351
//					Log.warning(TXMUIMessages.executionCanceled);
352
//					return Status.CANCEL_STATUS;
353
//				}
354
//			}
355
//		};
356
//		job.schedule();
355 357
		//		}
356 358
	}
357 359
	
......
359 361
	public void notifyDispose() throws Exception {
360 362
		
361 363
		//FIXME MD: I have to do this because Eclipse is not asking for editor saves before exiting the app - BUG
362
		try {
363
			boolean annotationsDirty = false;
364
			for (AnnotationArea aa : annotationAreas) {
365
				annotationsDirty = annotationsDirty || aa.isDirty();
366
			}
367
			if (annotationsDirty) {
368
				boolean doSave = MessageDialog.openQuestion(this.editor.getShell(), "Annotations not saved", "Do you want to save the annotations before closing the editor?");
369
				if (doSave) {
370
					notifyDoSave();
371
				}
372
			}
373
		} catch(Exception e) {
374
			Log.printStackTrace(e);
375
		}
364
//		try {
365
//			boolean annotationsDirty = false;
366
//			for (AnnotationArea aa : annotationAreas) {
367
//				annotationsDirty = annotationsDirty || aa.isDirty();
368
//			}
369
//			if (annotationsDirty) {
370
//				boolean doSave = MessageDialog.openQuestion(this.editor.getShell(), "Annotations not saved", "Do you want to save the annotations before closing the editor?");
371
//				if (doSave) {
372
//					notifyDoSave();
373
//				}
374
//			}
375
//		} catch(Exception e) {
376
//			Log.printStackTrace(e);
377
//		}
376 378
		
377 379
		for (AnnotationArea aa : annotationAreas) {
378 380
			aa._close();
... Ce différentiel a été tronqué car il excède la taille maximale pouvant être affichée.

Formats disponibles : Unified diff