Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: decee3d318cf470a8172e82f080fddae8df5f42a (plain) (blame)
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
/*******************************************************************************
 * Copyright (c) 2005, 2007 Intel Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * Intel Corporation - Initial API and implementation
 *******************************************************************************/
package org.eclipse.cdt.internal.core.cdtvariables;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.cdtvariables.CdtVariableException;
import org.eclipse.cdt.core.cdtvariables.ICdtVariable;
import org.eclipse.cdt.core.settings.model.ICStorageElement;
import org.eclipse.cdt.core.settings.model.util.CDataUtil;
import org.eclipse.cdt.core.settings.model.util.XmlStorageElement;
import org.eclipse.cdt.internal.core.settings.model.CConfigurationSpecSettings;
import org.eclipse.cdt.internal.core.settings.model.ExceptionFactory;
import org.eclipse.cdt.internal.core.settings.model.IInternalCCfgInfo;
import org.eclipse.cdt.utils.cdtvariables.CdtVariableResolver;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.osgi.service.prefs.BackingStoreException;
import org.osgi.service.prefs.Preferences;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * This supplier is used to obtain the user-defined macros
 * 
 * @since 3.0
 */
public class UserDefinedVariableSupplier extends CoreMacroSupplierBase {
//	public static final String MACROS_ELEMENT_NAME = "macros"; //$NON-NLS-1$
	public static final String NODENAME = "macros";  //$NON-NLS-1$
	public static final String PREFNAME_WORKSPACE = "workspace";  //$NON-NLS-1$
	static final String OLD_VARIABLE_PREFIX = "pathEntryVariable."; //$NON-NLS-1$


	private static UserDefinedVariableSupplier fInstance;
	
	private StorableCdtVariables fWorkspaceMacros;
	private Set fListeners;
	
	private StorableCdtVariables getStorableMacros(int contextType, Object contextData){
		StorableCdtVariables macros = null;
		switch(contextType){
		case ICoreVariableContextInfo.CONTEXT_CONFIGURATION:
			if(contextData instanceof IInternalCCfgInfo){
				try {
					CConfigurationSpecSettings settings = ((IInternalCCfgInfo)contextData).getSpecSettings();
					macros = settings.getMacros();
				} catch (CoreException e) {
				}
			}
			break;
		case ICoreVariableContextInfo.CONTEXT_WORKSPACE:
			if(contextData == null || contextData instanceof IWorkspace){
				if(fWorkspaceMacros == null)
					fWorkspaceMacros = loadWorkspaceMacros();
				macros = fWorkspaceMacros;
			}
		}

		return macros;
	}
	
	private UserDefinedVariableSupplier(){
		fListeners = Collections.synchronizedSet(new HashSet());
	}

	public static UserDefinedVariableSupplier getInstance(){
		if(fInstance == null)
			fInstance = new UserDefinedVariableSupplier();
		return fInstance;
	}
	

	/* (non-Javadoc)
	 * @see org.eclipse.cdt.managedbuilder.macros.IBuildMacroSupplier#getMacro(java.lang.String, int, java.lang.Object)
	 */
	public ICdtVariable getMacro(String macroName, int contextType, Object contextData) {
		if(macroName == null || "".equals(macroName))  //$NON-NLS-1$
			return null;
		
		StorableCdtVariables macros = getStorableMacros(contextType,contextData);
		if(macros != null)
			return macros.getMacro(macroName);
		return null;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.cdt.managedbuilder.macros.IBuildMacroSupplier#getMacros(int, java.lang.Object)
	 */
	public ICdtVariable[] getMacros(int contextType, Object contextData) {
		StorableCdtVariables macros = getStorableMacros(contextType,contextData);
		if(macros != null)
			return macros.getMacros();
		return null;
	}
	
	public ICdtVariable createMacro(String macroName, 
					int type, 
					String value, 
					int contextType,
					Object contextData){
		if(macroName == null || "".equals(macroName))  //$NON-NLS-1$
			return null;
		StorableCdtVariables macros = getStorableMacros(contextType, contextData);
		if(macros == null)
			return null;
		
		ICdtVariable oldVar = macros.getMacro(macroName);
		
		ICdtVariable macro = macros.createMacro(macroName,type,value);
		if(macros.isChanged()){
			setRebuildStateForContext(contextType, contextData);
			macros.setChanged(false);
		}
		
		if(macro != null){
			VariableChangeEvent event = createVariableChangeEvent(macro, oldVar);
			if(event != null){
				notifyListeners(event);
			}
		}

		return macro;

	}

	public ICdtVariable createMacro(String macroName, 
				int type, 
				String value[], 
				int contextType,
				Object contextData){
		if(macroName == null || "".equals(macroName))  //$NON-NLS-1$
			return null;
		StorableCdtVariables macros = getStorableMacros(contextType, contextData);
		if(macros == null)
			return null;
		
		ICdtVariable oldVar = macros.getMacro(macroName);

		ICdtVariable macro = macros.createMacro(macroName,type,value);
		if(macros.isChanged()){
			setRebuildStateForContext(contextType, contextData);
			macros.setChanged(false);
		}
		
		if(macro != null){
			VariableChangeEvent event = createVariableChangeEvent(macro, oldVar);
			if(event != null){
				notifyListeners(event);
			}
		}

		return macro;

	}

	public ICdtVariable createMacro(ICdtVariable copy, int contextType, Object contextData){
		if(copy == null)
			return null;
		String macroName = copy.getName();
		if(macroName == null || "".equals(macroName))  //$NON-NLS-1$
			return null;
		StorableCdtVariables macros = getStorableMacros(contextType, contextData);
		if(macros == null)
			return null;
		
		ICdtVariable oldVar = macros.getMacro(macroName);
		
		ICdtVariable macro = macros.createMacro(copy);
		if(macros.isChanged()){
			setRebuildStateForContext(contextType, contextData);
			macros.setChanged(false);
		}
		
		if(macro != null){
			VariableChangeEvent event = createVariableChangeEvent(macro, oldVar);
			if(event != null){
				notifyListeners(event);
			}
		}
		return macro;
	}

	public ICdtVariable deleteMacro(String name, int contextType, Object contextData){
		StorableCdtVariables macros = getStorableMacros(contextType,contextData);
		if(macros == null)
			return null;
		ICdtVariable macro = macros.deleteMacro(name);
		if(macro != null){
			setRebuildStateForContext(contextType, contextData);
			
			VariableChangeEvent event = createVariableChangeEvent(null, macro);
			if(event != null){
				notifyListeners(event);
			}

		}
		
		return macro;
	}
	
	public void deleteAll(int contextType, Object contextData){
		StorableCdtVariables macros = getStorableMacros(contextType, contextData);
		if(macros == null)
			return;

		ICdtVariable[] oldVars = macros.getMacros();
		
		if(macros.deleteAll())
			setRebuildStateForContext(contextType, contextData);
		
		VariableChangeEvent event = createVariableChangeEvent(null, oldVars);
		if(event != null){
			notifyListeners(event);
		}

	}
	
	public void setMacros(ICdtVariable m[], int contextType, Object contextData){
		StorableCdtVariables macros = getStorableMacros(contextType, contextData);
		if(macros == null)
			return;

		ICdtVariable[] oldVars = macros.getMacros();
		
		macros.setMacros(m);
		if(macros.isChanged()){
			setRebuildStateForContext(contextType, contextData);
			macros.setChanged(false);
			
			VariableChangeEvent event = createVariableChangeEvent(m, oldVars);
			if(event != null){
				notifyListeners(event);
			}

		}
	}
	
	private static class VarKey {
		private ICdtVariable fVar;
		private boolean fNameOnly;
		
		VarKey(ICdtVariable var, boolean nameOnly){
			fVar = var;
			fNameOnly = nameOnly;
		}
		
		public ICdtVariable getVariable(){
			return fVar; 
		}

		public boolean equals(Object obj) {
			if(obj == this)
				return true;
			
			if(!(obj instanceof VarKey))
				return false;
			
			VarKey other = (VarKey)obj;
			
			ICdtVariable otherVar = other.fVar;
			
			if(fVar == otherVar)
				return true;
			
			if(!CDataUtil.objectsEqual(fVar.getName(), otherVar.getName()))
				return false;

			if(fNameOnly)
				return true;
			
			if(fVar.getValueType() != otherVar.getValueType())
				return false;

			if(CdtVariableResolver.isStringListVariable(fVar.getValueType())){
				try {
					if(!Arrays.equals(fVar.getStringListValue(), otherVar.getStringListValue()))
						return false;
				} catch (CdtVariableException e) {
					CCorePlugin.log(e);
				}
			} else {
				try {
					if(!CDataUtil.objectsEqual(fVar.getStringValue(), otherVar.getStringValue()))
						return false;
				} catch (CdtVariableException e) {
					CCorePlugin.log(e);
				}
			}
				
			return true;
		}

		public int hashCode() {
			int code = 51;
			
			String name = fVar.getName();
			if(name != null)
				code += name.hashCode();

			if(fNameOnly)
				return code;
			
			code += fVar.getValueType();
			if(CdtVariableResolver.isStringListVariable(fVar.getValueType())){
				try {
					String[] value = fVar.getStringListValue();
					if(value != null){
						for(int i = 0; i < value.length; i++){
							code += value[i].hashCode();
						}
					}
				} catch (CdtVariableException e) {
					CCorePlugin.log(e);
				}
			} else {
				try {
					String value =fVar.getStringValue();
					if(value != null){
						code += value.hashCode();
					}
				} catch (CdtVariableException e) {
					CCorePlugin.log(e);
				}
			}
			
			return code;
		}
		
	}

	static VariableChangeEvent createVariableChangeEvent(ICdtVariable newVar, ICdtVariable oldVar){
		ICdtVariable newVars[] = newVar != null ? new ICdtVariable[]{newVar} : null;
		ICdtVariable oldVars[] = oldVar != null ? new ICdtVariable[]{oldVar} : null;
		
		return createVariableChangeEvent(newVars, oldVars);
	}

	static ICdtVariable[] varsFromKeySet(Set set){
		ICdtVariable vars[] = new ICdtVariable[set.size()];
		int i = 0;
		for(Iterator iter = set.iterator(); iter.hasNext(); i++){
			VarKey key = (VarKey)iter.next();
			vars[i] = key.getVariable();
		}
		
		return vars;
	}
	static VariableChangeEvent createVariableChangeEvent(ICdtVariable[] newVars, ICdtVariable[] oldVars){
		ICdtVariable[] addedVars = null, removedVars = null, changedVars = null;
		
		if(oldVars == null || oldVars.length == 0){
			if(newVars != null && newVars.length != 0)
				addedVars = (ICdtVariable[])newVars.clone() ;
		} else if(newVars == null || newVars.length == 0){
			removedVars = (ICdtVariable[])oldVars.clone();
		} else {
			HashSet newSet = new HashSet(newVars.length);
			HashSet oldSet = new HashSet(oldVars.length);
			
			for(int i = 0; i < newVars.length; i++){
				newSet.add(new VarKey(newVars[i], true));
			}
	
			for(int i = 0; i < oldVars.length; i++){
				oldSet.add(new VarKey(oldVars[i], true));
			}
	
			HashSet newSetCopy = (HashSet)newSet.clone();
	
			newSet.removeAll(oldSet);
			oldSet.removeAll(newSetCopy);
			
			if(newSet.size() != 0){
				addedVars = varsFromKeySet(newSet);
			}
			
			if(oldSet.size() != 0){
				removedVars = varsFromKeySet(oldSet);
			}
			
			newSetCopy.removeAll(newSet);
			
			HashSet modifiedSet = new HashSet(newSetCopy.size());
			for(Iterator iter = newSetCopy.iterator(); iter.hasNext();){
				VarKey key = (VarKey)iter.next();
				modifiedSet.add(new VarKey(key.getVariable(), false));
			}
			
			for(int i = 0; i < oldVars.length; i++){
				modifiedSet.remove(new VarKey(oldVars[i], false));
			}
			
			if(modifiedSet.size() != 0)
				changedVars = varsFromKeySet(modifiedSet); 
		}
		
		if(addedVars != null || removedVars != null || changedVars != null)
			return new VariableChangeEvent(addedVars, removedVars, changedVars);
		return null;
	}

	/*
	 * 
	 * methods used for loadding/storing workspace macros from properties 
	 * 
	 */
	public void storeWorkspaceVariables(boolean force){
		try{
			if(fWorkspaceMacros != null)
				storeWorkspaceMacros(fWorkspaceMacros,force);
		}catch(CoreException e){
		}
	}
	
	public StorableCdtVariables getWorkspaceVariablesCopy(){
		StorableCdtVariables vars = getStorableMacros(ICoreVariableContextInfo.CONTEXT_WORKSPACE, null);
		return new StorableCdtVariables(vars, false);
	}
	
	public void setWorkspaceVariables(StorableCdtVariables vars) throws CoreException{
		StorableCdtVariables old = getStorableMacros(ICoreVariableContextInfo.CONTEXT_WORKSPACE, null);
		ICdtVariable[] oldVars = null;
		if(old != null)
			oldVars = old.getMacros();
		
		ICdtVariable[] newVars = vars.getMacros();
		
		fWorkspaceMacros = new StorableCdtVariables(vars, false);
		
		VariableChangeEvent event = createVariableChangeEvent(newVars, oldVars);
		if(event != null){
			notifyListeners(event);
		}

		storeWorkspaceVariables(true);
	}
	
	private Preferences getWorkspaceNode(){
		Preferences prefNode = new InstanceScope().getNode(CCorePlugin.PLUGIN_ID);
		if(prefNode == null)
			return null;
		
		return prefNode.node(NODENAME);
	}

	
	/*
	 * loads the stored workspace macros
	 */
	protected StorableCdtVariables loadWorkspaceMacros(){
		StorableCdtVariables macros = loadNewStileWorkspaceMacros();
		
		//now load PathEntry Variables from preferences
		
		
		return macros;
	}
	
	protected void loadPathEntryVariables(StorableCdtVariables vars){
		org.eclipse.core.runtime.Preferences prefs = CCorePlugin.getDefault().getPluginPreferences();
		String[] names = prefs.propertyNames();
		for(int i = 0; i < names.length; i++){
			String name = names[i];
			if (name.startsWith(OLD_VARIABLE_PREFIX)) {
				String value = prefs.getString(name);
				prefs.setToDefault(name);
				if(value.length() != 0){
					name = name.substring(OLD_VARIABLE_PREFIX.length());
					vars.createMacro(name, ICdtVariable.VALUE_PATH_ANY, value);
				}
			}
		}
	}
	
	protected StorableCdtVariables loadNewStileWorkspaceMacros(){
		InputStream stream = loadInputStream(getWorkspaceNode(),PREFNAME_WORKSPACE);
		if(stream == null)
			return new StorableCdtVariables(false);
		return loadMacrosFromStream(stream);
	}
	
	
	/*
	 * stores the given macros 
	 */
	protected void storeWorkspaceMacros(StorableCdtVariables macros, boolean force) throws CoreException{
		if(!macros.isDirty() && !force)
			return;
		
		ByteArrayOutputStream stream = storeMacrosToStream(macros);
		if(stream == null)
			return;
		storeOutputStream(stream,getWorkspaceNode(),PREFNAME_WORKSPACE);
	}
	
	private StorableCdtVariables loadMacrosFromStream(InputStream stream){
		try{
			DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			InputSource inputSource = new InputSource(stream);
			Document document = parser.parse(inputSource);
			Element rootElement = document.getDocumentElement();
			
			if(!StorableCdtVariables.MACROS_ELEMENT_NAME.equals(rootElement.getNodeName()))
				return null;
			
			return new StorableCdtVariables(new XmlStorageElement(rootElement), true);
		}
		catch(ParserConfigurationException e){
			
		}
		catch(SAXException e){
			
		}
		catch(IOException e){
			
		}
		
		return null;
	}
	
	private ByteArrayOutputStream storeMacrosToStream(StorableCdtVariables macros) throws CoreException{
		try{
			DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
			DocumentBuilder builder= factory.newDocumentBuilder();		
			Document document= builder.newDocument();
			
			Element rootElement = document.createElement(StorableCdtVariables.MACROS_ELEMENT_NAME);
			document.appendChild(rootElement);
			ICStorageElement storageElement = new XmlStorageElement(rootElement);
			macros.serialize(storageElement);
			
			Transformer transformer=TransformerFactory.newInstance().newTransformer();
			transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //$NON-NLS-1$
			transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
			DOMSource source = new DOMSource(document);
			
			ByteArrayOutputStream stream = new ByteArrayOutputStream();
			StreamResult result = new StreamResult(stream);
	
			transformer.transform(source, result);
			return stream;
		}
		catch(ParserConfigurationException e){
			throw ExceptionFactory.createCoreException(e.getMessage(),
					e);
		}
		catch(TransformerConfigurationException e){
			throw ExceptionFactory.createCoreException(e.getMessage(),
					e);
		}
		catch(TransformerException e){
			throw ExceptionFactory.createCoreException(e.getMessage(),
					e);
		}
	}
	
	private InputStream loadInputStream(Preferences node, String key){
		if(node == null || key == null)
			return null;
		
		String value = node.get(key,null);
		if(value == null || value.length() == 0)
			return null;
		
		byte[] bytes;
		try {
			bytes = value.getBytes("UTF-8"); //$NON-NLS-1$
		} catch (UnsupportedEncodingException e) {
			bytes = value.getBytes();
		}
		
		return new ByteArrayInputStream(bytes);
	}
	
	private void storeOutputStream(ByteArrayOutputStream stream, Preferences node, String key) throws CoreException{
		if(stream == null || node == null || key == null)
			throw ExceptionFactory.createCoreException(new IllegalArgumentException());
		byte[] bytes= stream.toByteArray();
		
		String val = null;
		try {
			val= new String(bytes, "UTF-8"); //$NON-NLS-1$
		} catch (UnsupportedEncodingException e) {
			val= new String(bytes);
		}
		
		node.put(key,val);
		
		try{
			node.flush();
		}
		catch(BackingStoreException e){
			throw ExceptionFactory.createCoreException(e.getMessage(),
					e);
		}
	}
	
	protected void setRebuildStateForContext(int contextType, Object contextData){
/*		
		switch(contextType){
		case DefaultMacroContextInfo.CONTEXT_CONFIGURATION:
			if(contextData instanceof IConfiguration){
				((IConfiguration)contextData).setRebuildState(true);
			}
			break;
		case DefaultMacroContextInfo.CONTEXT_WORKSPACE:
			if(contextData instanceof IWorkspace){
				IProject projects[] = ((IWorkspace)contextData).getRoot().getProjects();
				for(int i = 0; i < projects.length; i++){
					if(ManagedBuildManager.manages(projects[i])){
						IManagedBuildInfo info = ManagedBuildManager.getBuildInfo(projects[i]);
						if(info != null){
							IConfiguration cfgs[] = info.getManagedProject().getConfigurations();
							for(int j = 0; j < cfgs.length; j++){
								cfgs[j].setRebuildState(true);
							}
						}
					}
				}
			}
		}

*/		
	}
	
	public void addListener(ICdtVariableChangeListener listener){
		fListeners.add(listener);
	}
	
	public void removeListener(ICdtVariableChangeListener listener){
		fListeners.remove(listener);
	}
	
	private void notifyListeners(VariableChangeEvent event){
		ICdtVariableChangeListener[] listeners = (ICdtVariableChangeListener[])fListeners.toArray(new ICdtVariableChangeListener[fListeners.size()]);
		for(int i = 0; i < listeners.length; i++){
			listeners[i].variablesChanged(event);
		}
	}
	
}

Back to the top