Blame view

js/app/views/CalculatorUI.js 14.7 KB
16035364   Benjamin Renard   First commit
1
2
3
4
5
6
/**
 * Project      : AMDA-NG4
 * Name         : CalculatorUI.js
 * @class   amdaDesktop.ExplorerModule 
 * @extends Ext.util.Observable
 * @brief   Calculator Plugin used in SearchUI and ParameterUI
ab55087c   Elena.Budnik   idl => math
7
 * @author  elena        
16035364   Benjamin Renard   First commit
8
9
10
11
12
13
14
15
16
17
 */


/**
 * @plugin calculator
 * @extends Ext.util.Observable 
 * @ptype calculator
 */

var CalculatorData = ['1','2','3','4','5','6','7','8','9','0','(',')','[',']','+','-','*','/','^', '.','>','<', '&', '|'];
a3db3a90   Elena.Budnik   calcularor_restru...
18
// var CalculatorData = ['1','2','3','4','5','6','7','8','9','0','(',')','[',']','+','-','*','/','^', '.','>','>=', '=', '<=', '<', '&', '|'];
16035364   Benjamin Renard   First commit
19
20
21

Ext.define('amdaUI.CalculatorUI', {
	extend: 'Ext.util.Observable',
ab55087c   Elena.Budnik   idl => math
22

16035364   Benjamin Renard   First commit
23
	requires : [
ab55087c   Elena.Budnik   idl => math
24
25
		'amdaModel.Constant',
		'amdaModel.Function'
16035364   Benjamin Renard   First commit
26
27
28
29
30
	],
	
	alias: 'plugin.calculator',
	
	statics : {
ab55087c   Elena.Budnik   idl => math
31
32
		constantStore : null,
		functionStore : null
16035364   Benjamin Renard   First commit
33
34
35
	},
	
	win: null,
ab55087c   Elena.Budnik   idl => math
36

16035364   Benjamin Renard   First commit
37
38
39
40
41
42
43
	constructor: function(config) { 
		Ext.apply(this, config);  
		this.callParent(arguments);
	},

	init: function(cmp) 
	{  
ab55087c   Elena.Budnik   idl => math
44
45
46
47
48
49
50
51
52
53
54
		this.hostCmp = cmp;
		this.hostCmp.on({
			scope: this,		 	       
			added: function(){
			this.hostCmp.ownerCt.on({
			render: this.onRender,
				show: this.onShow,
				hide : this.onHide,
			scope: this });		   
			}
		});
16035364   Benjamin Renard   First commit
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
	},
	
	onRender: function() 
	{
		this.win = new Ext.Window({
			width: 350, 
			height: 170,
			x: 380, y: 0,
			baseCls:'x-panel',	 
			title: 'Tools For ' + this.context + ' Construction',
			layout: 'fit',
			closable: false,
			collapsible: true,
			constrain: true,
			floating: true,
			ghost: false,
			renderTo: this.hostCmp.id,
			items: this.getFormConfig(),
			listeners : {
				boxready: function (w) 
				{
					if (w.y + w.height > myDesktopApp.desktop.el.getHeight())
						w.el.setY((myDesktopApp.desktop.el.getHeight()-w.height > 0) ? myDesktopApp.desktop.el.getHeight()-w.height : 0);
        		}
			},
			getConstrainVector: function(constrainTo){
				var me = this;
ab55087c   Elena.Budnik   idl => math
82
83
84
85
86
				if (me.constrain || me.constrainHeader) {
					constrainTo = constrainTo || (me.floatParent && me.floatParent.getTargetEl()) || me.container || me.el.getScopeParent();
					return (me.constrainHeader ? me.header.el : me.el).getConstrainVector(constrainTo);
				}
			}
16035364   Benjamin Renard   First commit
87
88
89
90
91
		});
		
		//load constants store
		if (!amdaUI.CalculatorUI.constantStore)
		{
ab55087c   Elena.Budnik   idl => math
92
93
94
95
96
			amdaUI.CalculatorUI.constantStore = Ext.create('Ext.data.Store',{model: 'amdaModel.Constant'});
			amdaUI.CalculatorUI.constantStore.load({
				scope   : this,
				callback: function(records, operation, success) 
				{
a3db3a90   Elena.Budnik   calcularor_restru...
97
				this.createAllConstantBtns();
ab55087c   Elena.Budnik   idl => math
98
99
				}
			});
16035364   Benjamin Renard   First commit
100
101
		}
		else
a3db3a90   Elena.Budnik   calcularor_restru...
102
			this.createAllConstantBtns();
16035364   Benjamin Renard   First commit
103
104
105
106

		//load functions store
		if (!amdaUI.CalculatorUI.functionStore)
		{
ab55087c   Elena.Budnik   idl => math
107
108
109
110
111
112
113
114
			amdaUI.CalculatorUI.functionStore = Ext.create('Ext.data.Store',{model: 'amdaModel.Function'});
			amdaUI.CalculatorUI.functionStore.load({
				scope   : this,
				callback: function(records, operation, success) 
				{
				this.createAllFunctionBtns();
				}
			});
16035364   Benjamin Renard   First commit
115
116
117
		}
		else
			this.createAllFunctionBtns();
16035364   Benjamin Renard   First commit
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
	},
	
	onShow: function() {
		this.win.show(); 
		var parentWin = this.hostCmp.findParentByType('window');
		
		if (parentWin.getId() === myDesktopApp.dynamicModules.param.id) {
			this.win.setPosition(335,10);
		}
		else {
			
			var posX =  parentWin.getWidth() - this.win.getWidth() - 30;
			var posY = parentWin.getHeight() - this.win.getHeight() - 110 - 30/*20*/;
			this.win.setPosition(posX,posY);//(420,290);
		}
	},
	
	onHide : function()
	{
		this.win.hide(); 
	},
 	
	getFormConfig: function(){
		return {
			xtype: 'tabpanel',
			border: false, frame: true, plain: true,
			enableTabScroll: true, 
			defaults: { frame: true, border: false, plain: true, autoScroll:true},
			activeTab: 0,
			items: [ {
				title: 'Calculator',layout: 'column',
				defaults: { xtype: 'button', columnWidth: .11},
				items: this.getItems('Calculator')
			} , {
a3db3a90   Elena.Budnik   calcularor_restru...
152
153
154
155
				title: 'Constants', xtype:'tabpanel', //iconCls: 'tabs',
				enableTabScroll: true,	tabPosition: 'bottom',	
				defaults: { frame: true, border: false, plain: true, layout: 'column', autoScroll:true},
				activeTab: 0, 
16035364   Benjamin Renard   First commit
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
				id : 'calc_tab_const_id'
			}, {
				title: 'Functions', xtype:'tabpanel', //iconCls: 'tabs',
				enableTabScroll: true,	tabPosition: 'bottom',	
				defaults: { frame: true, border: false, plain: true, layout: 'column', autoScroll:true},
				activeTab: 0,
				id : 'calc_tab_func_id'
			}]
		};					 
	},

	/**
	 * Prompt any argument to user before processing Formula
	 * @param sel selected text
	 * @param currentBtn calculator button pressed
	 * @param params array of parameters
	 */
	preProcessFormula: function(sel,currentBtn, params) {
		
		if (currentBtn.initialConfig.args!=0 && currentBtn.initialConfig.prompt!=""){
			// Prompt for user precision and process the result using a callback
			Ext.Msg.prompt('Argument',currentBtn.initialConfig.prompt, function(bt2, text){
				if (bt2 === 'ok'){
					var afterParamsText = "," + text + ")";
					//TODO: more than one args and prompt
					this.processFormula(sel,currentBtn, params, afterParamsText);

				}
			},this);
		} else {
			this.processFormula(sel,currentBtn, params, ")");
		}// endif prompt
	},
	
	processFormula : function(sel,currentBtn, params, afterParamsText){
		// calculation of the required number of parameters
		var nbParams = currentBtn.initialConfig.params;
		var fnText = currentBtn.text.split('(');
		var newConstruction = sel.beforeText + fnText[0]+"(";
		// if there at least one parameter selected
		if (params.length){
			for (var i=0;i<nbParams;i++) {
				if(i>0) {
					newConstruction += ",";
				}
				newConstruction += params[i];
			}
		}
		// we keep position
		var afterParameterPos = newConstruction.length;
		newConstruction += afterParamsText;
		var caretPos = newConstruction.length;
		newConstruction += sel.afterText;
		this.hostCmp.constructionField.setValue(newConstruction);

		// If we haven't the right number of selected parameters
		if (params.length < nbParams){
			var stringParamRequired = currentBtn.initialConfig.params+" parameter(s)";
			Ext.Msg.alert('Caution', 'you\'ll have to add '+ stringParamRequired +' to apply this function', 
				function(){
					// set Caret Position at placement of required parameter in function
					this.hostCmp.constructionField.setCaretPosition(afterParameterPos);
				},this
			);											        	
		} else {
			// set Caret Position after inserted Text
			this.hostCmp.constructionField.setCaretPosition(caretPos);
		}
	},
	
	/**
	 * This method construct an array of arguments into selected text
	 * @param selectedText the selection to parse
	 * @param parseIndex the index to start parsing
	 * @return the arguments array
	 */
	parseArgsInFormula : function (selectedText, parseIndex) {
		
		if (!selectedText || selectedText==""){
			return [];
		} else {
			var params = [];
			var startIndex = parseIndex;
			var curIndex = parseIndex;
			var openBrace = 0;
			var sep = 0;
			var closeBrace = 0;
			
			// while there is a separator
			while(sep!=-1){
				openBrace = selectedText.indexOf("(",curIndex);
				sep = selectedText.indexOf(",",curIndex);
				closeBrace = selectedText.indexOf(")",curIndex);
				
				// if there's an open bracket and no close bracket or inversely
				if (openBrace!=-1 && closeBrace==-1 || openBrace==-1 && closeBrace!=-1) {
					// invalid selection
					return -1;
				}
				
				// if there's a separator and opening brackets into selection
				if (sep!=-1 && openBrace!=-1){
					// if brace is before separator 
					if (openBrace<sep) {
						curIndex = this.getEndBracket(selectedText,openBrace+1);
						if (curIndex===-1){
							return -1;
						}
					} else {// else separator is before brace
						params.push(selectedText.substring(startIndex,sep));
						startIndex = curIndex = sep+1;
					}
				// if there's only separators into selection
				} else if (sep!=-1) {
					params.push(selectedText.substring(startIndex,sep));
					startIndex = curIndex = sep+1;
				}
			}
			params.push(selectedText.substring(startIndex,selectedText.length));			
			return params;
		}
	},

	getEndBracket : function(string,indOpenBrace){
		// we search for the corresponding end brace (after open bracket)
		var currentIndex = indOpenBrace;
		var nextCloseBrace = 0;
		var nextOpenBrace = 0;
		var braceLevel = 1;
		while (nextCloseBrace!==-1 && braceLevel!==0){
			// get index of next opening bracket
			nextOpenBrace = string.indexOf("(",currentIndex);
			// get index of next closing bracket
			nextCloseBrace = string.indexOf(")",currentIndex);
			// if both exist
			if (nextOpenBrace!=-1 && nextCloseBrace!=-1) {
				// if opening bracket is before closing one
				if (nextOpenBrace<nextCloseBrace) {
					currentIndex = nextOpenBrace+1;
					braceLevel++;
				} else { // if closing bracket is before opening one
					currentIndex = nextCloseBrace+1;
					braceLevel--;
				}
			// if there's only a next opening bracket
			} else if (nextOpenBrace!=-1 && nextCloseBrace==-1) {
				currentIndex = nextOpenBrace+1;
				braceLevel++;
			// if there's only a next closing bracket
			} else if (nextOpenBrace==-1 && nextCloseBrace!=-1) {
				currentIndex = nextCloseBrace+1;
				braceLevel--;
			}
		}
		// if no level imbrication left return index after closing bracket of block else -1
		return braceLevel==0 ? currentIndex : -1;
	},
	
	getCalculatorBtn : function()
	{
		var btns = [];
		
		Ext.each(CalculatorData, function (c){
		  btns.push({
		    text: c,
			scope: this,
			handler: function(b,e){
			  // keep selection into construction field
			  var selection = this.hostCmp.constructionField.getSelection();
			  // the new value of construction field
			  var newConstruction = "";
			  // replacement of selection into construction field by text of clicked button
			  newConstruction = selection.beforeText + b.text;
			  var caretPos = newConstruction.length;
			  newConstruction += selection.afterText;
			  this.hostCmp.constructionField.setValue(newConstruction);
			  // set Caret Position after inserted Text
			  this.hostCmp.constructionField.setCaretPosition(caretPos);
		    }
		  })
		},
		this
	  );
		
	  return btns;
	},
	
a3db3a90   Elena.Budnik   calcularor_restru...
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
	createAllFunctionBtns : function()
	{
		this.createFunctionBtns('MathFunctions','Simple Maths');	
		this.createFunctionBtns('VectorFunctions','Vector Functions');
		this.createFunctionBtns('TimeFunctions','Statistics');
		this.createFunctionBtns('FunctionsSliding','Statistics/Sliding');
		this.createFunctionBtns('AmdaFunctions','Special');
	},
	
	createAllConstantBtns : function()
	{
		this.createConstantBtns('Space','Planets Constants');	
		this.createConstantBtns('Physics','Physics Constants');
		this.createConstantBtns('Units','Units Conversion');
	},
	
	createConstantBtns : function(item, tabTitle)
	{
ab55087c   Elena.Budnik   idl => math
361
		var constTab = this.win.query('#calc_tab_const_id');
a3db3a90   Elena.Budnik   calcularor_restru...
362
		  
ab55087c   Elena.Budnik   idl => math
363
		if (constTab.length < 1)
a3db3a90   Elena.Budnik   calcularor_restru...
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
		  return;
		
		switch (item) 
		{
		  case 'Space' :
			  amdaUI.CalculatorUI.constantStore.filter('kind','space');
		    break;
		  case 'Physics' :
			  amdaUI.CalculatorUI.constantStore.filter('kind','physics');  
			break;
		  case 'Units' :
			  amdaUI.CalculatorUI.constantStore.filter('kind','units'); 
			  break;
		}
		
		 var crtTab = constTab[0].add(
				{
					title : tabTitle,
					defaults: { xtype: 'button',  columnWidth: .20}
				});
		 
ab55087c   Elena.Budnik   idl => math
385
		amdaUI.CalculatorUI.constantStore.each( function(c){
a3db3a90   Elena.Budnik   calcularor_restru...
386
			crtTab.add(
ab55087c   Elena.Budnik   idl => math
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
			{
				text: c.get('name'),
				tooltip: c.get('units') == '' ? c.get('info')+'<br/>'+c.get('value') :
								c.get('info')+'<br/>'+c.get('value')+' '+c.get('units'),
				scope: this,
				handler: function(b,e){
					// keep selection into construction field
					var selection = this.hostCmp.constructionField.getSelection();
					// the new value of construction field
					var newConstruction = "";
					// replacement of selection into construction field by text of clicked button
					newConstruction = selection.beforeText + '@'+b.text;
					var caretPos = newConstruction.length;
					newConstruction += selection.afterText;
					this.hostCmp.constructionField.setValue(newConstruction);
					// set Caret Position after inserted Text
					this.hostCmp.constructionField.setCaretPosition(caretPos);
				}
			});
16035364   Benjamin Renard   First commit
406
	  },this);
a3db3a90   Elena.Budnik   calcularor_restru...
407
408
409
410
		
		//clear filter
		amdaUI.CalculatorUI.constantStore.clearFilter();    
	},	
16035364   Benjamin Renard   First commit
411
412
413
414
415
416
417
418
419
420
	
	createFunctionBtns : function(item, tabTitle)
	{
		var funcTab = this.win.query('#calc_tab_func_id');
		  
		if (funcTab.length < 1)
		  return;
		
		switch (item) 
		{
ab55087c   Elena.Budnik   idl => math
421
422
		  case 'MathFunctions' :
			  amdaUI.CalculatorUI.functionStore.filter('kind','math');
16035364   Benjamin Renard   First commit
423
424
425
426
427
428
429
430
431
432
		    break;
		  case 'AmdaFunctions' :
			  amdaUI.CalculatorUI.functionStore.filter('kind','amda');  
			break;
		  case 'TimeFunctions' :
			  amdaUI.CalculatorUI.functionStore.filter('kind','time'); 
			  break;
		  case 'FunctionsSliding' :
			  amdaUI.CalculatorUI.functionStore.filter('kind','sliding'); 
		    break;
a3db3a90   Elena.Budnik   calcularor_restru...
433
434
435
		case 'VectorFunctions' :
			  amdaUI.CalculatorUI.functionStore.filter('kind','vector'); 
		    break;
16035364   Benjamin Renard   First commit
436
437
438
439
440
441
442
443
444
445
446
447
448
		}
		
		var crtTab = funcTab[0].add(
				{
					title : tabTitle,
					defaults: { xtype: 'button',  columnWidth: .20}
				});
		
		amdaUI.CalculatorUI.functionStore.each( function(f){
			crtTab.add(
					{
						text: f.get('name'),
						args: f.get('args'),
ab55087c   Elena.Budnik   idl => math
449
						params: f.get('params'),
16035364   Benjamin Renard   First commit
450
451
						prompt: f.get('prompt'),
						tooltip: f.get('info_brief'),
16035364   Benjamin Renard   First commit
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
						scope: this,
						handler: function(b,e){
							var selection = this.hostCmp.constructionField.getSelection();
							var selectedText = selection&&selection.text!="" ? Ext.util.Format.trim(selection.text) : null;
							if (selectedText && selectedText!==""){
								selectedText.replace("[","(");
								selectedText.replace("{","(");
								selectedText.replace("}",")");
								selectedText.replace("]",")");
							}
							// Formula Parsing for arguments
							var params = this.parseArgsInFormula(selectedText,0);
//							var params = selectedText ? selectedText.split(',') : [];
							if (params === -1) {
								Ext.Msg.alert("Invalid Selection", "Action aborted");
							} 
							else {
								// calculation of the required number of parameters
								var nbParams = b.initialConfig.params;

								if (params.length>nbParams)
								{
									// Show a dialog using config options:
									Ext.Msg.show({
										title:'Caution',
										msg: 'you have selected more than '+nbParams+' parameter(s) to apply this function<br>Only the first will be kept, others will be deleted',
										buttons: Ext.Msg.OKCANCEL,
//										animEl: 'elId',
										icon: Ext.MessageBox.WARNING,
										fn: function(bt1){
										if (bt1 === 'ok'){
											this.preProcessFormula(selection,b, params);
										}
									},
									scope:this
									});
								} 
								else 
								{
									this.preProcessFormula(selection,b, params);
								}
							}
						}
					});
ab55087c   Elena.Budnik   idl => math
496
497
498
499
500
			},
			this
		);
		//clear filter
		amdaUI.CalculatorUI.functionStore.clearFilter();      
16035364   Benjamin Renard   First commit
501
502
503
504
	},
      
	getItems:  function(item)
	{          
ab55087c   Elena.Budnik   idl => math
505
506
507
508
		switch (item) 
		{
			case 'Calculator': 
			return this.getCalculatorBtn();
16035364   Benjamin Renard   First commit
509
		default: break;
ab55087c   Elena.Budnik   idl => math
510
511
512
		}
		return [];      
	}  
16035364   Benjamin Renard   First commit
513
});