Blame view

js/app/views/CalculatorUI.js 13.5 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
18
19
20
 */


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

var CalculatorData = ['1','2','3','4','5','6','7','8','9','0','(',')','[',']','+','-','*','/','^', '.','>','<', '&', '|'];

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

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

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

	init: function(cmp) 
	{  
ab55087c   Elena.Budnik   idl => math
43
44
45
46
47
48
49
50
51
52
53
		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
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
	},
	
	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
81
82
83
84
85
				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
86
87
88
89
90
		});
		
		//load constants store
		if (!amdaUI.CalculatorUI.constantStore)
		{
ab55087c   Elena.Budnik   idl => math
91
92
93
94
95
96
97
98
			amdaUI.CalculatorUI.constantStore = Ext.create('Ext.data.Store',{model: 'amdaModel.Constant'});
			amdaUI.CalculatorUI.constantStore.load({
				scope   : this,
				callback: function(records, operation, success) 
				{
				this.createConstantBtns();
				}
			});
16035364   Benjamin Renard   First commit
99
100
101
102
103
104
105
		}
		else
			this.createConstantBtns();

		//load functions store
		if (!amdaUI.CalculatorUI.functionStore)
		{
ab55087c   Elena.Budnik   idl => math
106
107
108
109
110
111
112
113
			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
114
115
116
		}
		else
			this.createAllFunctionBtns();
16035364   Benjamin Renard   First commit
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
	},
	
	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')
			} , {
				title: 'Constants', layout: 'column',
				defaults: { xtype: 'button', columnWidth: .20},
				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;
	},
	
	createConstantBtns : function(){
ab55087c   Elena.Budnik   idl => math
341
342
343
344
		var constTab = this.win.query('#calc_tab_const_id');
		
		if (constTab.length < 1)
			return;
16035364   Benjamin Renard   First commit
345
	  
ab55087c   Elena.Budnik   idl => math
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
		amdaUI.CalculatorUI.constantStore.each( function(c){
			constTab[0].add(
			{
				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
367
368
369
370
371
	  },this);
	},
	
	createAllFunctionBtns : function()
	{
ab55087c   Elena.Budnik   idl => math
372
373
374
		this.createFunctionBtns('MathFunctions','Simple Maths');	  	
		this.createFunctionBtns('TimeFunctions','Statistics');
		this.createFunctionBtns('FunctionsSliding','Statistics/Sliding');
16035364   Benjamin Renard   First commit
375
376
377
378
379
380
381
382
383
384
385
386
		this.createFunctionBtns('AmdaFunctions','Space Physics');
	},
	
	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
387
388
		  case 'MathFunctions' :
			  amdaUI.CalculatorUI.functionStore.filter('kind','math');
16035364   Benjamin Renard   First commit
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
		    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;
		}
		
		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
412
						params: f.get('params'),
16035364   Benjamin Renard   First commit
413
414
						prompt: f.get('prompt'),
						tooltip: f.get('info_brief'),
16035364   Benjamin Renard   First commit
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
						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
459
460
461
462
463
			},
			this
		);
		//clear filter
		amdaUI.CalculatorUI.functionStore.clearFilter();      
16035364   Benjamin Renard   First commit
464
465
466
467
	},
      
	getItems:  function(item)
	{          
ab55087c   Elena.Budnik   idl => math
468
469
470
471
		switch (item) 
		{
			case 'Calculator': 
			return this.getCalculatorBtn();
16035364   Benjamin Renard   First commit
472
		default: break;
ab55087c   Elena.Budnik   idl => math
473
474
475
		}
		return [];      
	}  
16035364   Benjamin Renard   First commit
476
});