/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, ann*/
Ext.namespace('sitools.env');
var i18n = {
map : [],
/**
* Load a properties file and and the name/values in a associative array ;
* Executing this function on multiple properties file increase the size of
* the array Results can be displayed in the help panel with the display()
* function
*
* @param url URL of the i18n file
* @param callback No args function that will be executed
* @returns void
*/
load : function (url, callback) {
var i18nRef = this;
Ext.Ajax.request({
method : 'GET',
url : url,
// params:'formLogin', using autorization instead
success : function (response, opts) {
ann(response.responseText, "no response is sent");
i18nRef.map = i18nRef.transformsPropertiesToMap(response.responseText);
callback();
},
failure : function (response, opts) {
Ext.Msg.alert("Error! Can't read i18n file with url :" + url);
}
});
},
/**
* Transforms a properties Text to a map
*
* @param text
* raw properties file
* @returns a map (associative array) TODO check when the raw properties
* file is rotten
*/
transformsPropertiesToMap : function (text) {
var array = text.split('\n');
var localMap = [];
for (var i = 0; i < array.length; i++) {
var string = array[i];
var indexOfEqualsSign = string.indexOf('=');
if (indexOfEqualsSign >= 1) {
var key = string.substring(0, indexOfEqualsSign).replace('\r', '');
var value = string.substring(indexOfEqualsSign + 1).replace('\r', '');
localMap[key] = value;
}
}
return localMap;
},
/**
* return the i18n value
* @param name
* @returns
*/
get : function (entry) {
return !Ext.isEmpty(this.map[entry])?this.map[entry]:entry;
}
};
var sql2ext = {
map : [],
load : function (url) {
var i18nRef = this;
Ext.Ajax.request({
method : 'GET',
url : url,
// params:'formLogin', using autorization instead
success : function (response, opts) {
ann(response.responseText, "no response is sent");
i18nRef.map = i18nRef.transformsPropertiesToMap(response.responseText);
},
failure : function (response, opts) {
alert("Error! Can't read i18n file with url :" + url);
}
});
},
/**
* Transforms a properties Text to a map
*
* @param text
* raw properties file
* @returns a map (associative array) TODO check when the raw properties
*/
transformsPropertiesToMap : function (text) {
var array = text.split('\n');
var localMap = [];
var i;
for (i = 0; i < array.length; i++) {
var string = array[i];
var indexOfEqualsSign = string.indexOf('=');
if (indexOfEqualsSign >= 1) {
var key = string.substring(0, indexOfEqualsSign).replace('\r', '');
var value = string.substring(indexOfEqualsSign + 1).replace('\r', '');
localMap[key] = value;
}
}
return localMap;
},
/**
* return the i18n value
*
* @param name
* @returns
*/
get : function (entry) {
return !Ext.isEmpty(this.map[entry]) ? this.map[entry] : 'auto';
}
};
/**
* To be defined
*/
var componentManager = {
loadedComponents : [],
load : function (name) {
}
};
var data = {
ret : null,
/**
* Fetch a html file in the url, and display its content into the helpPanel. *
*
* @param url
* @returns
*/
get : function (url, cbk) {
Ext.Ajax.request({
method : 'GET',
url : url,
success : function (response, opts) {
cbk(Ext.decode(response.responseText));
},
failure : function (response, opts) {
Ext.Msg.alert("Warning", "Error! Can't get data with url :" + url);
}
});
return this.ret;
}
};
Ext.applyIf(Array.prototype, {
clone : function() {
return [].concat(this);
}
});
/*******************************************************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* SITools2 is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* SITools2. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
/* global Ext, ann */
Ext.namespace('sitools.siteMap');
var loadUrl = {
map : [],
/**
* Load a properties file and and the name/values in a associative array ;
* Executing this function on multiple properties file increase the size of
* the array Results can be displayed in the help panel with the display()
* function
*
* @param url
* URL of the i18n file
* @param callback
* No args function that will be executed
* @returns void
*/
load : function (url, callback, scope) {
var siteMapRef = this;
siteMapRef.transformsPropertiesToMap(url, callback, scope);
},
/**
* Transforms a xml Text to a map
*
* @param text
* raw properties file
* @returns a map (associative array) TODO check when the raw properties
* file is rotten
*/
transformsPropertiesToMap : function (url, callback, scope) {
var store = new Ext.data.Store({
proxy : new Ext.data.HttpProxy({
url : url,
restful : true
}),
reader : new Ext.data.XmlReader({
record : 'url'
}, [ {
name : 'name',
mapping : 'name'
}, {
name : 'loc',
mapping : 'loc'
} ])
});
var localMap = this.map;
store.load({
scope : scope,
callback : function (r, options, success) {
var i = 0;
while (i != undefined) {
var rec = r[i];
if (rec != undefined) {
var url = rec.data.loc;
var name = rec.data.name;
localMap[name] = url;
i++;
} else {
i = undefined;
}
}
callback.call(this);
}
});
},
/**
* return the url value
*
* @param name
* @returns
*/
get : function (entry) {
return !Ext.isEmpty(this.map[entry]) ? this.map[entry] : entry;
}
};
/**
* To be defined
*/
var componentManager = {
loadedComponents : [],
load : function (name) {
}
};
var data = {
ret : null,
/**
* Fetch a html file in the url, and display its content into the helpPanel. *
*
* @param url
* @returns
*/
get : function (url, cbk) {
Ext.Ajax.request({
method : 'GET',
url : url,
success : function (response, opts) {
cbk(Ext.decode(response.responseText));
},
failure : function (response, opts) {
Ext.Msg.alert("Warning", "Error! Can't get data with url :" + url);
}
});
return this.ret;
}
};
Ext.applyIf(Array.prototype, {
clone : function () {
return [].concat(this);
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/**
*
* Base64 encode / decode
* http://www.webtoolkit.info/
*
**/
var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
};
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*
* md5.js 1.0b 27/06/96
*
* Javascript implementation of the RSA Data Security, Inc. MD5
* Message-Digest Algorithm.
*
* Copyright (c) 1996 Henri Torgemane. All Rights Reserved.
*
* Permission to use, copy, modify, and distribute this software
* and its documentation for any purposes and without
* fee is hereby granted provided that this copyright notice
* appears in all copies.
*
* Of course, this soft is provided "as is" without express or implied
* warranty of any kind.
*
*
* Modified with german comments and some information about collisions.
* (Ralf Mieke, ralf@miekenet.de, http://mieke.home.pages.de)
* French translation: Serge François, serge@selfhtml.org, http://fr.selfhtml.org
*/
function array(n) {
for(i=0;i<n;i++) this[i]=0;
this.length=n;
}
/* Quelques fonctions fondamentales doivent être transformées à cause
* d'erreurs Javascript.
* Essayez par exemple de calculer 0xffffffff >> 4 ...
* Les fonctions utilisées maintenant sont il est vrai plus lentes que les
* fonctions originales mais elles fonctionnent.
*/
function integer(n) { return n%(0xffffffff+1); }
function shr(a,b) {
a=integer(a);
b=integer(b);
if (a-0x80000000>=0) {
a=a%0x80000000;
a>>=b;
a+=0x40000000>>(b-1);
} else
a>>=b;
return a;
}
function shl1(a) {
a=a%0x80000000;
if (a&0x40000000==0x40000000)
{
a-=0x40000000;
a*=2;
a+=0x80000000;
} else
a*=2;
return a;
}
function shl(a,b) {
a=integer(a);
b=integer(b);
for (var i=0;i<b;i++) a=shl1(a);
return a;
}
function and(a,b) {
a=integer(a);
b=integer(b);
var t1=(a-0x80000000);
var t2=(b-0x80000000);
if (t1>=0)
if (t2>=0)
return ((t1&t2)+0x80000000);
else
return (t1&b);
else
if (t2>=0)
return (a&t2);
else
return (a&b);
}
function or(a,b) {
a=integer(a);
b=integer(b);
var t1=(a-0x80000000);
var t2=(b-0x80000000);
if (t1>=0)
if (t2>=0)
return ((t1|t2)+0x80000000);
else
return ((t1|b)+0x80000000);
else
if (t2>=0)
return ((a|t2)+0x80000000);
else
return (a|b);
}
function xor(a,b) {
a=integer(a);
b=integer(b);
var t1=(a-0x80000000);
var t2=(b-0x80000000);
if (t1>=0)
if (t2>=0)
return (t1^t2);
else
return ((t1^b)+0x80000000);
else
if (t2>=0)
return ((a^t2)+0x80000000);
else
return (a^b);
}
function not(a) {
a=integer(a);
return (0xffffffff-a);
}
/* Début de l'algorithme */
var state = new array(4);
var count = new array(2);
count[0] = 0;
count[1] = 0;
var buffer = new array(64);
var transformBuffer = new array(16);
var digestBits = new array(16);
var S11 = 7;
var S12 = 12;
var S13 = 17;
var S14 = 22;
var S21 = 5;
var S22 = 9;
var S23 = 14;
var S24 = 20;
var S31 = 4;
var S32 = 11;
var S33 = 16;
var S34 = 23;
var S41 = 6;
var S42 = 10;
var S43 = 15;
var S44 = 21;
function F(x,y,z) {
return or(and(x,y),and(not(x),z));
}
function G(x,y,z) {
return or(and(x,z),and(y,not(z)));
}
function H(x,y,z) {
return xor(xor(x,y),z);
}
function I(x,y,z) {
return xor(y ,or(x , not(z)));
}
function rotateLeft(a,n) {
return or(shl(a, n),(shr(a,(32 - n))));
}
function FF(a,b,c,d,x,s,ac) {
a = a+F(b, c, d) + x + ac;
a = rotateLeft(a, s);
a = a+b;
return a;
}
function GG(a,b,c,d,x,s,ac) {
a = a+G(b, c, d) +x + ac;
a = rotateLeft(a, s);
a = a+b;
return a;
}
function HH(a,b,c,d,x,s,ac) {
a = a+H(b, c, d) + x + ac;
a = rotateLeft(a, s);
a = a+b;
return a;
}
function II(a,b,c,d,x,s,ac) {
a = a+I(b, c, d) + x + ac;
a = rotateLeft(a, s);
a = a+b;
return a;
}
function transform(buf,offset) {
var a=0, b=0, c=0, d=0;
var x = transformBuffer;
a = state[0];
b = state[1];
c = state[2];
d = state[3];
for (i = 0; i < 16; i++) {
x[i] = and(buf[i*4+offset],0xff);
for (j = 1; j < 4; j++) {
x[i]+=shl(and(buf[i*4+j+offset] ,0xff), j * 8);
}
}
/* tour 1 */
a = FF ( a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
d = FF ( d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
c = FF ( c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
b = FF ( b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
a = FF ( a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
d = FF ( d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
c = FF ( c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
b = FF ( b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
a = FF ( a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
d = FF ( d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
c = FF ( c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
b = FF ( b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
a = FF ( a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
d = FF ( d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
c = FF ( c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
b = FF ( b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
/* tour 2 */
a = GG ( a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
d = GG ( d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
c = GG ( c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
b = GG ( b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
a = GG ( a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
d = GG ( d, a, b, c, x[10], S22, 0x2441453); /* 22 */
c = GG ( c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
b = GG ( b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
a = GG ( a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
d = GG ( d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
c = GG ( c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
b = GG ( b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
a = GG ( a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
d = GG ( d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
c = GG ( c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
b = GG ( b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
/* tour 3 */
a = HH ( a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
d = HH ( d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
c = HH ( c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
b = HH ( b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
a = HH ( a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
d = HH ( d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
c = HH ( c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
b = HH ( b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
a = HH ( a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
d = HH ( d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
c = HH ( c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
b = HH ( b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
a = HH ( a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
d = HH ( d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
c = HH ( c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
b = HH ( b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
/* tour 4 */
a = II ( a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
d = II ( d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
c = II ( c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
b = II ( b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
a = II ( a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
d = II ( d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
c = II ( c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
b = II ( b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
a = II ( a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
d = II ( d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
c = II ( c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
b = II ( b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
a = II ( a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
d = II ( d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
c = II ( c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
b = II ( b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
state[0] +=a;
state[1] +=b;
state[2] +=c;
state[3] +=d;
}
/* Avec l'initialisation de Dobbertin:
state[0] = 0x12ac2375;
state[1] = 0x3b341042;
state[2] = 0x5f62b97c;
state[3] = 0x4ba763ed;
s'il y a une collision:
begin 644 Message1
M7MH=JO6_>MG!X?!51$)W,CXV!A"=(!AR71,<X`Y-IIT9^Z&8L$2N'Y*Y:R.;
39GIK9>TF$W()/MEHR%C4:G1R:Q"=
`
end
begin 644 Message2
M7MH=JO6_>MG!X?!51$)W,CXV!A"=(!AR71,<X`Y-IIT9^Z&8L$2N'Y*Y:R.;
39GIK9>TF$W()/MEHREC4:G1R:Q"=
`
end
*/
function init() {
count[0]=count[1] = 0;
state[0] = 0x67452301;
state[1] = 0xefcdab89;
state[2] = 0x98badcfe;
state[3] = 0x10325476;
for (i = 0; i < digestBits.length; i++)
digestBits[i] = 0;
}
function update(b) {
var index,i;
index = and(shr(count[0],3) , 0x3f);
if (count[0]<0xffffffff-7)
count[0] += 8;
else {
count[1]++;
count[0]-=0xffffffff+1;
count[0]+=8;
}
buffer[index] = and(b,0xff);
if (index >= 63) {
transform(buffer, 0);
}
}
function finish() {
var bits = new array(8);
var padding;
var i=0, index=0, padLen=0;
for (i = 0; i < 4; i++) {
bits[i] = and(shr(count[0],(i * 8)), 0xff);
}
for (i = 0; i < 4; i++) {
bits[i+4]=and(shr(count[1],(i * 8)), 0xff);
}
index = and(shr(count[0], 3) ,0x3f);
padLen = (index < 56) ? (56 - index) : (120 - index);
padding = new array(64);
padding[0] = 0x80;
for (i=0;i<padLen;i++)
update(padding[i]);
for (i=0;i<8;i++)
update(bits[i]);
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
digestBits[i*4+j] = and(shr(state[i], (j * 8)) , 0xff);
}
}
}
/* Fin de l'algorithme MD5 */
function hexa(n) {
var hexa_h = "0123456789abcdef";
var hexa_c="";
var hexa_m=n;
for (hexa_i=0;hexa_i<8;hexa_i++) {
hexa_c=hexa_h.charAt(Math.abs(hexa_m)%16)+hexa_c;
hexa_m=Math.floor(hexa_m/16);
}
return hexa_c;
}
var ascii="01234567890123456789012345678901" +
" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ"+
"[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
function MD5(message)
{
var l,s,k,ka,kb,kc,kd;
init();
for (k=0;k<message.length;k++) {
l=message.charAt(k);
update(ascii.lastIndexOf(l));
}
finish();
ka=kb=kc=kd=0;
for (i=0;i<4;i++) ka+=shl(digestBits[15-i], (i*8));
for (i=4;i<8;i++) kb+=shl(digestBits[15-i], ((i-4)*8));
for (i=8;i<12;i++) kc+=shl(digestBits[15-i], ((i-8)*8));
for (i=12;i<16;i++) kd+=shl(digestBits[15-i], ((i-12)*8));
s=hexa(kd)+hexa(kc)+hexa(kb)+hexa(ka);
return s;
}
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
function Digest (config) {
this.url = config.url;
this.usr = config.usr;
this.pwd = config.pwd;
this.realm = config.realm;
this.algorithm = config.algorithm;
this.nonce = config.nonce;
this.method = config.method;
this.mode = config.mode;
this.A1 = config.A1;
this.getDigestAuth = function () {
this.resetHeaders();
return this.buildAuthenticationRequest();
};
this.getA1 = function () {
this.resetHeaders();
return this.digest(this.usr + ':' + this.realm + ':' + this.pwd);
};
this.resetHeaders = function () {
if ( typeof( this.headers) != "undefined" ) {
delete this.headers;
}
this.headers = {
'uri' : this.url,
'username' : this.usr,
'algorithm' : this.algorithm,
'realm' : this.realm,
'nonce' : this.nonce
};
};
this.digest = function (s) {
// Fallback to MD5 if requested algorithm is unavilable.
if (typeof ( window[this.headers.algorithm] ) != 'function') {
if (typeof ( window['MD5'] ) != 'function') {
alert('Votre navigateur ne supporte pas l\'authentification HTTP Digest !');
return false;
} else {
return MD5(s);
}
}
return window[this.headers.algorithm](s);
};
this.buildResponseHash = function () {
if (this.headers.salt) {
auth.secret = auth.secret + ':' + auth.headers.salt;
delete auth.headers.salt;
}
if (this.headers.migrate) {
auth.secret = this.digest(auth.secret);
}
var A1;
if (Ext.isEmpty(this.A1)){
A1 = this.getA1();
}
else {
A1 = this.A1;
}
//delete this.secret;
var A2 = this.digest(this.method + ':' + this.headers.uri);
if (this.mode == 'digest') {
return this.digest(A1 + ":" + this.headers.nonce + ":" + A2);
}
//TODO : voir s'il y a d'autres encodages possibles
return null;
};
this.buildAuthenticationRequest = function () {
var request = "Digest";
var comma = ' ';
for (name in this.headers) {
request += comma + name + '="' + this.headers[name] + '"';
comma = ',';
}
// request += ' username="'+ auth.headers.username+ '"';
// don't continue further if there is no algorithm yet.
if (typeof( this.headers.algorithm ) == 'undefined') {
return request;
}
var r = this.buildResponseHash();
if (r) {
request += ", response=\"" + r + "\"";
return request;
}
return false;
};
};
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/**
* shortcut for console.assert(object is not null neither undefined neither
* empty string)
*/
/*global cerr,ctrace,isFirebugConsoleIsActive,console */
function ann(obj, message) {
if (obj === true || obj === false) {
return;
}
if (obj === undefined) {
cerr('Object is undefined - ' + message);
ctrace();
return;
}
if (obj === null) {
cerr('Object is null - ' + message);
ctrace();
return;
}
if (obj === "") {
cerr('String seems empty - ' + message);
ctrace();
return;
}
if (obj == NaN) {
cerr('Object equals NaN - ' + message);
ctrace();
return;
}
}
/**
* shortcut for console.assert(object is not null neither undefined neither
* empty string)
*/
function assert(condition, message) {
if (!condition) {
cerr('Condition is not valid : ' + message);
ctrace();
return;
}
}
/**
* Log on the console
*/
function clog(message) {
if (isFirebugConsoleIsActive()) {
console.log(message);
}
}
/**
* Display an error on the console
*/
function cerr(message) {
if (isFirebugConsoleIsActive()) {
console.trace();
}
}
/**
* Trace the Javascript stack to this point
*/
function ctrace() {
if (isFirebugConsoleIsActive()) {
console.trace();
}
}
/**
* Trace the Javascript stack to this point
*/
function cdir(obj) {
if (isFirebugConsoleIsActive()) {
console.dir(obj);
}
}
/**
* Return true if the firebug console is active, false elsewhere
*/
function isFirebugConsoleIsActive() {
try {
if (console !== null && console !== undefined)
{
return true;
} else {
return false;
}
}
catch (e) {
return false;
}
}
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
Ext.ns("sitools.common.utils");
/**
* An utility class to use in sitools.
*/
sitools.common.utils.Utils = {
/**
* Transform an Array of Sitools properties (with field name, value) into an object.
* @param {Array} array the array to transform
* @return {Object} An object containing all properties as attributes.
*/
arrayProperties2Object : function (array) {
var result = {};
Ext.each(array, function(item){
if (!Ext.isEmpty(item.name) && !Ext.isEmpty(item.value)) {
result[item.name] = item.value;
}
});
return result;
},
/**
* Highlight a json string inside a <pre> html tag
*/
syntaxHighlight : function (json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
}
sitoolsUtils = sitools.common.utils.Utils;
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
Ext.ns("sitools.common.utils");
/**
* An utility class to use for specific sitools dates.
*/
sitools.common.utils.Date = {
/**
* The regExp to test if a string can be transformed to a date
*/
regToday : new RegExp("^\{\\$TODAY\} *(\\+ *[0-9]*|\\- *[0-9]*)?$"),
/**
* in the template {$TODAY} + x, determine the x unit (currently it is a Day)
* @type
*/
timeInterval : Date.DAY,
/**
* Transform a String value containing {$TODAY} into a valid date.
* @param {String} val the string value
* @return {Date} the date Value.
*/
stringWithTodayToDate : function(val) {
if (Ext.isDate(val)) {
return val;
}
if (!this.regToday.test(val)) {
return null;
}
var regNbJour = new RegExp("[0-9]+", "g");
var regOp = new RegExp("[+]|[-]");
var nbJour = parseFloat(regNbJour.exec(val));
var op = regOp.exec(val);
var result = new Date();
if (Ext.isEmpty(nbJour) && !Ext.isEmpty(op)) {
return null;
}
if (!Ext.isEmpty(nbJour) && !Ext.isEmpty(op)) {
if (op == "-") {
nbJour = nbJour * -1;
}
result = result.add(this.timeInterval, nbJour);
}
return result;
},
/**
* Test if a date object is valid or not.
* @param {Date} d date value
* @return {Boolean} valid or not valid
*/
isValidDate : function (d) {
if ( Object.prototype.toString.call(d) !== "[object Date]" )
return false;
return !isNaN(d.getTime());
}
}/* URL class for JavaScript
* Copyright (C) 2003 Johan Känngård, <johan AT kanngard DOT net>
* http://dev.kanngard.net/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* The GPL is located at: http://www.gnu.org/licenses/gpl.txt
*/
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/* Creates a new URL object with the specified url String. */
function URL(url){
if(url.length==0) eval('throw "Invalid URL ['+url+'];');
this.url=url;
this.port=-1;
this.query=(this.url.indexOf('?')>=0)?this.url.substring(this.url.indexOf('?')+1):'';
if(this.query.indexOf('#')>=0) this.query=this.query.substring(0,this.query.indexOf('#'));
this.protocol='';
this.host='';
var protocolSepIndex=this.url.indexOf('://');
if(protocolSepIndex>=0){
this.protocol=this.url.substring(0,protocolSepIndex).toLowerCase();
this.host=this.url.substring(protocolSepIndex+3);
if(this.host.indexOf('/')>=0) this.host=this.host.substring(0,this.host.indexOf('/'));
var atIndex=this.host.indexOf('@');
if(atIndex>=0){
var credentials=this.host.substring(0,atIndex);
var colonIndex=credentials.indexOf(':');
if(colonIndex>=0){
this.username=credentials.substring(0,colonIndex);
this.password=credentials.substring(colonIndex);
}else{
this.username=credentials;
}
this.host=this.host.substring(atIndex+1);
}
var portColonIndex=this.host.indexOf(':');
if(portColonIndex>=0){
this.port=this.host.substring(portColonIndex);
this.host=this.host.substring(0,portColonIndex);
}
this.file=this.url.substring(protocolSepIndex+3);
this.file=this.file.substring(this.file.indexOf('/'));
}else{
this.file=this.url;
}
if(this.file.indexOf('?')>=0) this.file=this.file.substring(0, this.file.indexOf('?'));
var refSepIndex=url.indexOf('#');
if(refSepIndex>=0){
this.file=this.file.substring(0,refSepIndex);
this.reference=this.url.substring(this.url.indexOf('#'));
}else{
this.reference='';
}
this.path=this.file;
if(this.query.length>0) this.file+='?'+this.query;
if(this.reference.length>0) this.file+='#'+this.reference;
this.getPort=getPort;
this.getQuery=getQuery;
this.getProtocol=getProtocol;
this.getHost=getHost;
this.getUserName=getUserName;
this.getPassword=getPassword;
this.getFile=getFile;
this.getReference=getReference;
this.getPath=getPath;
this.getArgumentValue=getArgumentValue;
this.getArgumentValues=getArgumentValues;
this.toString=toString;
/* Returns the port part of this URL, i.e. '8080' in the url 'http://server:8080/' */
function getPort(){
return this.port;
}
/* Returns the query part of this URL, i.e. 'Open' in the url 'http://server/?Open' */
function getQuery(){
return this.query;
}
/* Returns the protocol of this URL, i.e. 'http' in the url 'http://server/' */
function getProtocol(){
return this.protocol;
}
/* Returns the host name of this URL, i.e. 'server.com' in the url 'http://server.com/' */
function getHost(){
return this.host;
}
/* Returns the user name part of this URL, i.e. 'joe' in the url 'http://joe@server.com/' */
function getUserName(){
return this.username;
}
/* Returns the password part of this url, i.e. 'secret' in the url 'http://joe:secret@server.com/' */
function getPassword(){
return this.password;
}
/* Returns the file part of this url, i.e. everything after the host name. */
function getFile(){
return this.file;
}
/* Returns the reference of this url, i.e. 'bookmark' in the url 'http://server/file.html#bookmark' */
function getReference(){
return this.reference;
}
/* Returns the file path of this url, i.e. '/dir/file.html' in the url 'http://server/dir/file.html' */
function getPath(){
return this.path;
}
/* Returns the FIRST matching value to the specified key in the query.
If the url has a non-value argument, like 'Open' in '?Open&bla=12', this method
returns the same as the key: 'Open'...
The url must be correctly encoded, ampersands must encoded as &
I.e. returns 'value' if the key is 'key' in the url 'http://server/?Open&key=value' */
function getArgumentValue(key){
var a=this.getArgumentValues();
if(a.length<1) return '';
for(var i=0;i<a.length;i++){
if(a[i][0]==key) return a[i][1];
}
return '';
}
/* Returns all key / value pairs in the query as a two dimensional array */
function getArgumentValues(){
var a=new Array();
var b=this.query.split('&');
var c='';
if(b.length<1) return a;
for(var i=0;i<b.length;i++){
c=b[i].split('=');
a[i]=new Array(c[0],((c.length==1)?c[0]:c[1]));
}
return a;
}
/* Returns a String representation of this url */
function toString(){
return this.url;
}
}/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*
* Ext JS Library 3.2.1
* Copyright(c) 2006-2010 Ext JS, Inc.
* licensing@extjs.com
* http://www.extjs.com/license
*/
/**
* @class Ext.ux.StatusBar
* <p>Basic status bar component that can be used as the bottom toolbar of any {@link Ext.Panel}. In addition to
* supporting the standard {@link Ext.Toolbar} interface for adding buttons, menus and other items, the StatusBar
* provides a greedy status element that can be aligned to either side and has convenient methods for setting the
* status text and icon. You can also indicate that something is processing using the {@link #showBusy} method.</p>
* <pre><code>
new Ext.Panel({
title: 'StatusBar',
// etc.
bbar: new Ext.ux.StatusBar({
id: 'my-status',
// defaults to use when the status is cleared:
defaultText: 'Default status text',
defaultIconCls: 'default-icon',
// values to set initially:
text: 'Ready',
iconCls: 'ready-icon',
// any standard Toolbar items:
items: [{
text: 'A Button'
}, '-', 'Plain Text']
})
});
// Update the status bar later in code:
var sb = Ext.getCmp('my-status');
sb.setStatus({
text: 'OK',
iconCls: 'ok-icon',
clear: true // auto-clear after a set interval
});
// Set the status bar to show that something is processing:
sb.showBusy();
// processing....
sb.clearStatus(); // once completeed
</code></pre>
* @extends Ext.Toolbar
* @constructor
* Creates a new StatusBar
* @param {Object/Array} config A config object
*/
Ext.ux.StatusBar = Ext.extend(Ext.Toolbar, {
/**
* @cfg {String} statusAlign
* The alignment of the status element within the overall StatusBar layout. When the StatusBar is rendered,
* it creates an internal div containing the status text and icon. Any additional Toolbar items added in the
* StatusBar's {@link #items} config, or added via {@link #add} or any of the supported add* methods, will be
* rendered, in added order, to the opposite side. The status element is greedy, so it will automatically
* expand to take up all sapce left over by any other items. Example usage:
* <pre><code>
// Create a left-aligned status bar containing a button,
// separator and text item that will be right-aligned (default):
new Ext.Panel({
title: 'StatusBar',
// etc.
bbar: new Ext.ux.StatusBar({
defaultText: 'Default status text',
id: 'status-id',
items: [{
text: 'A Button'
}, '-', 'Plain Text']
})
});
// By adding the statusAlign config, this will create the
// exact same toolbar, except the status and toolbar item
// layout will be reversed from the previous example:
new Ext.Panel({
title: 'StatusBar',
// etc.
bbar: new Ext.ux.StatusBar({
defaultText: 'Default status text',
id: 'status-id',
statusAlign: 'right',
items: [{
text: 'A Button'
}, '-', 'Plain Text']
})
});
</code></pre>
*/
/**
* @cfg {String} defaultText
* The default {@link #text} value. This will be used anytime the status bar is cleared with the
* <tt>useDefaults:true</tt> option (defaults to '').
*/
/**
* @cfg {String} defaultIconCls
* The default {@link #iconCls} value (see the iconCls docs for additional details about customizing the icon).
* This will be used anytime the status bar is cleared with the <tt>useDefaults:true</tt> option (defaults to '').
*/
/**
* @cfg {String} text
* A string that will be <b>initially</b> set as the status message. This string
* will be set as innerHTML (html tags are accepted) for the toolbar item.
* If not specified, the value set for <code>{@link #defaultText}</code>
* will be used.
*/
/**
* @cfg {String} iconCls
* A CSS class that will be <b>initially</b> set as the status bar icon and is
* expected to provide a background image (defaults to '').
* Example usage:<pre><code>
// Example CSS rule:
.x-statusbar .x-status-custom {
padding-left: 25px;
background: transparent url(images/custom-icon.gif) no-repeat 3px 2px;
}
// Setting a default icon:
var sb = new Ext.ux.StatusBar({
defaultIconCls: 'x-status-custom'
});
// Changing the icon:
sb.setStatus({
text: 'New status',
iconCls: 'x-status-custom'
});
</code></pre>
*/
/**
* @cfg {String} cls
* The base class applied to the containing element for this component on render (defaults to 'x-statusbar')
*/
cls : 'x-statusbar',
/**
* @cfg {String} busyIconCls
* The default <code>{@link #iconCls}</code> applied when calling
* <code>{@link #showBusy}</code> (defaults to <tt>'x-status-busy'</tt>).
* It can be overridden at any time by passing the <code>iconCls</code>
* argument into <code>{@link #showBusy}</code>.
*/
busyIconCls : 'x-status-busy',
/**
* @cfg {String} busyText
* The default <code>{@link #text}</code> applied when calling
* <code>{@link #showBusy}</code> (defaults to <tt>'Loading...'</tt>).
* It can be overridden at any time by passing the <code>text</code>
* argument into <code>{@link #showBusy}</code>.
*/
busyText : 'Loading...',
/**
* @cfg {Number} autoClear
* The number of milliseconds to wait after setting the status via
* <code>{@link #setStatus}</code> before automatically clearing the status
* text and icon (defaults to <tt>5000</tt>). Note that this only applies
* when passing the <tt>clear</tt> argument to <code>{@link #setStatus}</code>
* since that is the only way to defer clearing the status. This can
* be overridden by specifying a different <tt>wait</tt> value in
* <code>{@link #setStatus}</code>. Calls to <code>{@link #clearStatus}</code>
* always clear the status bar immediately and ignore this value.
*/
autoClear : 5000,
/**
* @cfg {String} emptyText
* The text string to use if no text has been set. Defaults to
* <tt>' '</tt>). If there are no other items in the toolbar using
* an empty string (<tt>''</tt>) for this value would end up in the toolbar
* height collapsing since the empty string will not maintain the toolbar
* height. Use <tt>''</tt> if the toolbar should collapse in height
* vertically when no text is specified and there are no other items in
* the toolbar.
*/
emptyText : ' ',
// private
activeThreadId : 0,
// private
initComponent : function(){
if(this.statusAlign=='right'){
this.cls += ' x-status-right';
}
Ext.ux.StatusBar.superclass.initComponent.call(this);
},
// private
afterRender : function(){
Ext.ux.StatusBar.superclass.afterRender.call(this);
var right = this.statusAlign == 'right';
this.currIconCls = this.iconCls || this.defaultIconCls;
this.statusEl = new Ext.Toolbar.TextItem({
cls: 'x-status-text ' + (this.currIconCls || ''),
text: this.text || this.defaultText || ''
});
if(right){
this.add('->');
this.add(this.statusEl);
}else{
this.insert(0, this.statusEl);
this.insert(1, '->');
}
this.doLayout();
},
/**
* Sets the status {@link #text} and/or {@link #iconCls}. Also supports automatically clearing the
* status that was set after a specified interval.
* @param {Object/String} config A config object specifying what status to set, or a string assumed
* to be the status text (and all other options are defaulted as explained below). A config
* object containing any or all of the following properties can be passed:<ul>
* <li><tt>text</tt> {String} : (optional) The status text to display. If not specified, any current
* status text will remain unchanged.</li>
* <li><tt>iconCls</tt> {String} : (optional) The CSS class used to customize the status icon (see
* {@link #iconCls} for details). If not specified, any current iconCls will remain unchanged.</li>
* <li><tt>clear</tt> {Boolean/Number/Object} : (optional) Allows you to set an internal callback that will
* automatically clear the status text and iconCls after a specified amount of time has passed. If clear is not
* specified, the new status will not be auto-cleared and will stay until updated again or cleared using
* {@link #clearStatus}. If <tt>true</tt> is passed, the status will be cleared using {@link #autoClear},
* {@link #defaultText} and {@link #defaultIconCls} via a fade out animation. If a numeric value is passed,
* it will be used as the callback interval (in milliseconds), overriding the {@link #autoClear} value.
* All other options will be defaulted as with the boolean option. To customize any other options,
* you can pass an object in the format:<ul>
* <li><tt>wait</tt> {Number} : (optional) The number of milliseconds to wait before clearing
* (defaults to {@link #autoClear}).</li>
* <li><tt>anim</tt> {Number} : (optional) False to clear the status immediately once the callback
* executes (defaults to true which fades the status out).</li>
* <li><tt>useDefaults</tt> {Number} : (optional) False to completely clear the status text and iconCls
* (defaults to true which uses {@link #defaultText} and {@link #defaultIconCls}).</li>
* </ul></li></ul>
* Example usage:<pre><code>
// Simple call to update the text
statusBar.setStatus('New status');
// Set the status and icon, auto-clearing with default options:
statusBar.setStatus({
text: 'New status',
iconCls: 'x-status-custom',
clear: true
});
// Auto-clear with custom options:
statusBar.setStatus({
text: 'New status',
iconCls: 'x-status-custom',
clear: {
wait: 8000,
anim: false,
useDefaults: false
}
});
</code></pre>
* @return {Ext.ux.StatusBar} this
*/
setStatus : function(o){
o = o || {};
if(typeof o == 'string'){
o = {text:o};
}
if(o.text !== undefined){
this.setText(o.text);
}
if(o.iconCls !== undefined){
this.setIcon(o.iconCls);
}
if(o.clear){
var c = o.clear,
wait = this.autoClear,
defaults = {useDefaults: true, anim: true};
if(typeof c == 'object'){
c = Ext.applyIf(c, defaults);
if(c.wait){
wait = c.wait;
}
}else if(typeof c == 'number'){
wait = c;
c = defaults;
}else if(typeof c == 'boolean'){
c = defaults;
}
c.threadId = this.activeThreadId;
this.clearStatus.defer(wait, this, [c]);
}
return this;
},
/**
* Clears the status {@link #text} and {@link #iconCls}. Also supports clearing via an optional fade out animation.
* @param {Object} config (optional) A config object containing any or all of the following properties. If this
* object is not specified the status will be cleared using the defaults below:<ul>
* <li><tt>anim</tt> {Boolean} : (optional) True to clear the status by fading out the status element (defaults
* to false which clears immediately).</li>
* <li><tt>useDefaults</tt> {Boolean} : (optional) True to reset the text and icon using {@link #defaultText} and
* {@link #defaultIconCls} (defaults to false which sets the text to '' and removes any existing icon class).</li>
* </ul>
* @return {Ext.ux.StatusBar} this
*/
clearStatus : function(o){
o = o || {};
if(o.threadId && o.threadId !== this.activeThreadId){
// this means the current call was made internally, but a newer
// thread has set a message since this call was deferred. Since
// we don't want to overwrite a newer message just ignore.
return this;
}
var text = o.useDefaults ? this.defaultText : this.emptyText,
iconCls = o.useDefaults ? (this.defaultIconCls ? this.defaultIconCls : '') : '';
if(o.anim){
// animate the statusEl Ext.Element
this.statusEl.el.fadeOut({
remove: false,
useDisplay: true,
scope: this,
callback: function(){
this.setStatus({
text: text,
iconCls: iconCls
});
this.statusEl.el.show();
}
});
}else{
// hide/show the el to avoid jumpy text or icon
this.statusEl.hide();
this.setStatus({
text: text,
iconCls: iconCls
});
this.statusEl.show();
}
return this;
},
/**
* Convenience method for setting the status text directly. For more flexible options see {@link #setStatus}.
* @param {String} text (optional) The text to set (defaults to '')
* @return {Ext.ux.StatusBar} this
*/
setText : function(text){
this.activeThreadId++;
this.text = text || '';
if(this.rendered){
this.statusEl.setText(this.text);
}
return this;
},
/**
* Returns the current status text.
* @return {String} The status text
*/
getText : function(){
return this.text;
},
/**
* Convenience method for setting the status icon directly. For more flexible options see {@link #setStatus}.
* See {@link #iconCls} for complete details about customizing the icon.
* @param {String} iconCls (optional) The icon class to set (defaults to '', and any current icon class is removed)
* @return {Ext.ux.StatusBar} this
*/
setIcon : function(cls){
this.activeThreadId++;
cls = cls || '';
if(this.rendered){
if(this.currIconCls){
this.statusEl.removeClass(this.currIconCls);
this.currIconCls = null;
}
if(cls.length > 0){
this.statusEl.addClass(cls);
this.currIconCls = cls;
}
}else{
this.currIconCls = cls;
}
return this;
},
/**
* Convenience method for setting the status text and icon to special values that are pre-configured to indicate
* a "busy" state, usually for loading or processing activities.
* @param {Object/String} config (optional) A config object in the same format supported by {@link #setStatus}, or a
* string to use as the status text (in which case all other options for setStatus will be defaulted). Use the
* <tt>text</tt> and/or <tt>iconCls</tt> properties on the config to override the default {@link #busyText}
* and {@link #busyIconCls} settings. If the config argument is not specified, {@link #busyText} and
* {@link #busyIconCls} will be used in conjunction with all of the default options for {@link #setStatus}.
* @return {Ext.ux.StatusBar} this
*/
showBusy : function(o){
if(typeof o == 'string'){
o = {text:o};
}
o = Ext.applyIf(o || {}, {
text: this.busyText,
iconCls: this.busyIconCls
});
return this.setStatus(o);
}
});
Ext.reg('statusbar', Ext.ux.StatusBar);
// create namespace for plugins
Ext.namespace('Ext.ux.plugins');
/**
* Ext.ux.plugins.SliderRange plugin for Ext.Slider
*
* @author Dorothea Loew
* @date Februar 15, 2009
*
* @class Ext.ux.plugins.SliderRange
* @extends Ext.util.Observable
*/
Ext.ux.plugins.SliderRange = function(config) {
Ext.apply(this, config);
};
// plugin code
Ext.extend(Ext.ux.plugins.SliderRange, Ext.util.Observable, {
init:function(slider) {
Ext.apply(slider, {
onResize:slider.onResize.createSequence(function(ct, position) {
// slider needs more space with range: height="50px"
this.el.addClass ('ux-sliderrange-slider');
if (slider.range)
slider.range.remove();
// create range-object, width from sliders-element
slider.range = slider.el.createChild({cls: 'ux-sliderrange'});
// get position of two joining values
var startPos = slider.translateValue(slider.minValue);
var nextPos = slider.translateValue((slider.minValue+slider.increment));
// get diff of positions
var diff = nextPos - startPos;
var counter;
counter = 0;
// create one child per value and show value in html-config
for (var i=slider.minValue; i<=slider.maxValue; i=i+slider.increment) {
slider.range.createChild({html: ''+i, cls: 'ux-sliderrange-val', style: 'left: '+(startPos + (diff * counter)) +'px;'});
counter++;
}
}) // end of function afterRender
});
} // end of function init
}); // end of extend
/*******************************************************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* SITools2 is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* SITools2. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
/* global Ext, sitools, ID, i18n, showResponse, alertFailure,clog,window,Base64 */
Ext.namespace('sitools.userProfile');
/*
* defurl: default page url to load if click on Cancel button url: url to
* request if click on Login button handler: if request is OK then is called
* register: url to set to Register button reset: url to set to Reset Password
* button
*/
sitools.userProfile.Login = Ext.extend(Ext.Window, {
id : 'winLogin',
layout : 'hbox',
width : 392,
height : 200,
resizable : false,
closable : false,
modal : true,
initComponent : function () {
this.title = i18n.get('label.login');
this.bbar = new Ext.ux.StatusBar({
text : i18n.get('label.ready'),
id : 'sbWinLogin',
iconCls : 'x-status-valid',
items : [ {
text : i18n.get('label.passwordLost'),
hidden : !this.reset,
scope : this,
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/wadl.gif',
iconAlign : 'right',
handler : function () {
Ext.getCmp('winLogin').close();
var reset = new sitools.userProfile.resetPassword({
closable : this.closable,
url : this.reset,
handler : this.handler
});
reset.show();
}
} ]
});
this.combo = new Ext.form.ComboBox({
typeAhead : true,
triggerAction : 'all',
forceSelection : true,
allowBlank : false,
lazyRender : true,
mode : 'local',
store : new Ext.data.ArrayStore({
id : 0,
fields : [ 'myId', 'displayText' ],
data : [ [ 1, i18n.get('label.userPortal') ], [ 2, i18n.get('label.administration') ] ]
}),
valueField : 'myId',
displayField : 'displayText',
anchor : '80%',
value : 1,
fieldLabel : i18n.get('label.target'),
hideLabel : true
});
if (this.chooseLocation) {
this.combo.setVisible(true);
this.combo.hideLabel = false;
} else {
this.combo.setVisible(false);
this.setSize(392, 160);
}
this.items = [ {
xtype : 'form',
frame : true,
border : false,
buttonAlign : 'center',
id : 'frmLogin',
width : 392,
labelWidth : 100,
padding : "10px 10px 0px 60px",
bodyStyle : "background-image: url("+loadUrl.get('APP_URL')+"/common/res/images/ux/login-big.gif);" +
"background-position: top left;" +
"background-repeat: no-repeat;",
items : [ {
xtype : 'textfield',
fieldLabel : i18n.get('label.login'),
name : 'login',
id : 'logId',
allowBlank : false,
anchor : '80%'
}, {
xtype : 'textfield',
fieldLabel : i18n.get('label.password'),
name : 'password',
id : 'pwdId',
allowBlank : false,
inputType : 'password',
anchor : '80%',
listeners : {
scope : this,
specialkey : function (field, e) {
if (e.getKey() == e.ENTER) {
this.getAuth();
}
}
}
}, this.combo ],
buttons : [ {
text : i18n.get('label.login'),
handler : this.getAuth,
scope : this
}, {
text : i18n.get('label.reset'),
handler : function () {
Ext.getCmp('frmLogin').getForm().reset();
Ext.getCmp('sbWinLogin').setStatus({
text : i18n.get('label.ready'),
iconCls : 'x-status-valid'
});
}
}, {
text : i18n.get('label.cancel'),
hidden : !this.defurl,
scope : this,
handler : function () {
window.location.href = this.defurl;
}
}, {
text : i18n.get('label.register'),
hidden : !this.register,
scope : this,
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/refresh.png',
handler : function () {
Ext.getCmp('winLogin').close();
var register = new sitools.userProfile.Register({
closable : this.closable,
url : this.register,
login : this.url,
handler : this.handler
});
register.show();
}
} ]
} ];
sitools.userProfile.Login.superclass.initComponent.call(this);
},
getAuth : function () {
/*
* var usr = Ext.getCmp('logId').getValue(); var pwd =
* Ext.getCmp('pwdId').getValue(); var tok = usr + ':' + pwd; var hash =
* Base64.encode(tok); var auth = 'Basic ' + hash;
* Ext.util.Cookies.set('hashCode', auth);
* Ext.apply(Ext.Ajax.defaultHeaders, { "Authorization" : auth });
* this.login();
*/
Ext.util.Cookies.set('A1', "");
Ext.util.Cookies.set('userLogin', "");
Ext.util.Cookies.set('scheme', "");
Ext.util.Cookies.set('algorithm', "");
Ext.util.Cookies.set('realm', "");
Ext.util.Cookies.set('nonce', "");
Ext.util.Cookies.set('hashCode', "");
Ext.apply(Ext.Ajax.defaultHeaders, {
"Authorization" : ""
});
Ext.Ajax.request({
url : this.url,
method : 'GET',
scope : this,
success : function (response, opts) {
var Json = Ext.decode(response.responseText);
var date = new Date();
if (!Ext.isEmpty(Json.data)) {
if (Json.data.scheme == 'HTTP_Digest') {
var auth = new Digest({
usr : Ext.getCmp('logId').getValue(),
pwd : Ext.getCmp('pwdId').getValue(),
realm : Json.data.realm
});
var A1 = auth.getA1();
// stockage en cookie du mode d'authorization
Ext.util.Cookies.set('A1', A1);
Ext.util.Cookies.set('userLogin', auth.usr, date.add(Date.MINUTE, 1));
Ext.util.Cookies.set('scheme', Json.data.scheme);
Ext.util.Cookies.set('algorithm', Json.data.algorithm);
Ext.util.Cookies.set('realm', auth.realm);
Ext.util.Cookies.set('nonce', Json.data.nonce);
} else if (Json.data.scheme == "HTTP_Basic") {
var usr = Ext.getCmp('logId').getValue();
var pwd = Ext.getCmp('pwdId').getValue();
var tok = usr + ':' + pwd;
var hash = Base64.encode(tok);
var auth = 'Basic ' + hash;
// stockage en cookie du mode d'authorization
Ext.util.Cookies.set('userLogin', usr, date.add(Date.MINUTE, 1));
Ext.util.Cookies.set('scheme', Json.data.scheme);
Ext.util.Cookies.set('hashCode', auth, date.add(Date.MINUTE, 1));
}
}
this.login();
},
failure : alertFailure
});
},
login : function () {
if (!Ext.getCmp('frmLogin').getForm().isValid()) {
Ext.getCmp('sbWinLogin').setStatus({
text : i18n.get('warning.checkForm'),
iconCls : 'x-status-error'
});
return;
}
Ext.getCmp('winLogin').body.mask();
Ext.getCmp('sbWinLogin').showBusy();
Ext.Ajax.request({
url : this.url,
method : 'GET',
scope : this,
success : function (response, opts) {
try {
var Json = Ext.decode(response.responseText);
if (Json.success) {
// var date = new Date();
Ext.apply(Ext.Ajax.defaultHeaders, {
"Authorization" : Ext.util.Cookies.get('hashCode')
});
Ext.getCmp('winLogin').close();
// this.handler.call(this.scope || this);
if (this.chooseLocation) {
if (this.combo.getValue() == 1) {
window.location.href = loadUrl.get('APP_URL') + '/login-redirect?kwd=/client-user/index.html';
// window.location.href =
// "/sitools/client-user/index.html?authorization="
// + hash;
} else {
Ext.Ajax.request({
url : loadUrl.get('APP_URL') + '/login-redirect?kwd=/client-admin',
method : "GET",
success : function (response) {
Ext.Msg.alert('error login.js redirect with authorization');
}
});
// window.location.href =
// "/sitools/client-admin";
}
} else {
window.location.reload();
}
} else {
Ext.util.Cookies.set('userLogin', "", new Date().add(Date.MINUTE, COOKIE_DURATION * -1));
Ext.util.Cookies.set('scheme', "", new Date().add(Date.MINUTE, COOKIE_DURATION * -1));
Ext.util.Cookies.set('hashCode', "", new Date().add(Date.MINUTE, COOKIE_DURATION * -1));
var txt = i18n.get('warning.serverError') + ': ' + Json.message;
Ext.getCmp('winLogin').body.unmask();
Ext.getCmp('sbWinLogin').setStatus({
// text: ret.error ? ret.error :
// i18n.get('warning.serverUnreachable'),
text : txt,
iconCls : 'x-status-error'
});
}
} catch (err) {
Ext.Msg.alert(i18n.get('label.error'), err);
}
},
failure : function (response, opts) {
Ext.util.Cookies.set('userLogin', "", new Date().add(Date.MINUTE, COOKIE_DURATION * -1));
Ext.util.Cookies.set('scheme', "", new Date().add(Date.MINUTE, COOKIE_DURATION * -1));
Ext.util.Cookies.set('hashCode', "", new Date().add(Date.MINUTE, COOKIE_DURATION * -1));
var txt;
if (response.status == 200) {
var ret = Ext.decode(response.responseText).error;
txt = i18n.get('msg.error') + ': ' + ret;
} else {
txt = i18n.get('warning.serverError') + ': ' + response.statusText;
}
Ext.getCmp('winLogin').body.unmask();
Ext.getCmp('sbWinLogin').setStatus({
// text: ret.error ? ret.error :
// i18n.get('warning.serverUnreachable'),
text : txt,
iconCls : 'x-status-error'
});
}
});
}
});
Ext.reg('s-login', sitools.userProfile.Login);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, showResponse, alertFailure,clog*/
Ext.namespace('sitools.widget');
/**
* Common component for creating a dynamic link
*/
sitools.widget.ActionLink = Ext.extend(Ext.BoxComponent, {
/**
* must be declared at the configuration
*/
text : undefined,
initComponent : function () {
Ext.apply(this, {
autoEl : {
tag : 'div',
html : '<a class="small-link">' + this.text + "</a>"
}
});
sitools.widget.ActionLink.superclass.initComponent.apply(this, arguments);
},
onRender : function () {
sitools.widget.ActionLink.superclass.onRender.apply(this, arguments);
Ext.get(this.id).child('a').on('click', this._bubbleClick);
Ext.get(this.id).child('a').on('mouseover', this._bubbleOver);
Ext.get(this.id).child('a').on('mouseout', this._bubbleOut);
},
_bubbleClick : function () {
// we are not in the Component, but in the <a> tag inside this
// component.
// finding the adder Wrapper
var actionLink = Ext.getCmp(this.parent().id);
actionLink.onClick();
},
_bubbleOver : function () {
var actionLink = Ext.getCmp(this.parent().id);
actionLink.onMouseOver();
},
_bubbleOut : function () {
var actionLink = Ext.getCmp(this.parent().id);
actionLink.onMouseOut();
},
onClick : function () {
clog("actionLink " + this + " onClick() function is not yet implemented !");
},
onMouseOver : function () {
// To be implemented by extension
},
onMouseOut : function () {
// To be implemented by extension
},
toString : function () {
return "ActionLink " + this.text;
}
});
// register type
Ext.reg('s-actionlink', sitools.widget.ActionLink);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
Ext.namespace('sitools.widget');
/**
* Text component that allows Highlighting
*/
sitools.widget.HighlightText = Ext.extend(Ext.BoxComponent,{
/**
* must be declared at the configuration
*/
text:undefined,
initComponent : function(){
Ext.apply(this, {
autoEl : {
// tag:'div',
html:this.text
}
});
sitools.widget.HighlightText.superclass.initComponent.apply(this, arguments);
},
onRender : function (){
sitools.widget.HighlightText.superclass.onRender.apply(this, arguments);
},
highlight : function (color){
clog('try highlight');
if (color==null) color="yellow";
this.getEl().applyStyles("background-color:"+color);
},
stopHighlight : function(){
this.getEl().applyStyles("background-color:");
},
updateHtml : function(html){
this.getEl().update(html);
//this.doLayout();
}
});
//register type
Ext.reg('s-lighttext', sitools.widget.HighlightText);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*
* Ext JS Library 3.2.1
* Copyright(c) 2006-2010 Ext JS, Inc.
* licensing@extjs.com
* http://www.extjs.com/license
*/
/*global Ext, sitools, ID, i18n, showResponse, alertFailure,clog*/
Ext.ns('Ext.ux.grid');
/**
* @class Ext.ux.grid.CheckColumn
* @extends Object GridPanel plugin to add a column with check boxes to a grid.
* <p>
* Example usage:
* </p>
*
* <pre><code>
* // create the column
* var checkColumn = new Ext.grid.CheckColumn({
* header: 'Indoor?',
* dataIndex: 'indoor',
* id: 'check',
* width: 55
* });
*
* // add the column to the column model
* var cm = new Ext.grid.ColumnModel([{
* header: 'Foo',
* ...
* },
* checkColumn
* ]);
*
* // create the grid
* var grid = new Ext.grid.EditorGridPanel({
* ...
* cm: cm,
* plugins: [checkColumn], // include plugin
* ...
* });
* </code></pre>
*
* In addition to storing a Boolean value within the record data, this class
* toggles a css class between <tt>'x-grid3-check-col'</tt> and
* <tt>'x-grid3-check-col-on'</tt> to alter the background image used for a
* column.
*/
Ext.ux.grid.CheckColumn = function(config){
Ext.apply(this, config);
if(!this.id){
this.id = Ext.id();
}
this.renderer = this.renderer.createDelegate(this);
};
Ext.ux.grid.CheckColumn = Ext.extend(Ext.Component, {
enabled : true,
init : function(grid){
this.grid = grid;
this.grid.on('render', function(){
var view = this.grid.getView();
view.mainBody.on('mousedown', this.onMouseDown, this);
}, this);
},
onMouseDown : function(e, t){
if(Ext.fly(t).hasClass(this.createId()) && Ext.fly(t).hasClass("x-grid3-check-col-enabled")){
e.stopEvent();
var index = this.grid.getView().findRowIndex(t);
var record = this.grid.store.getAt(index);
record.set(this.dataIndex, !record.data[this.dataIndex]);
}
},
renderer : function(v, p, record){
p.css += ' x-grid3-check-col-td';
var cmp = Ext.getCmp(this.id);
if (cmp.enabled) {
return String.format('<div id="{2}" class="x-grid3-check-col{0} x-grid3-check-col-enabled {1}"> </div>', v ? '-on' : '', cmp.createId(), this.id);
}
else {
return String.format('<div id="{2}" class="x-grid3-check-disabled-col{0} {1}"> </div>', v ? '-on' : '', cmp.createId(), this.id);
}
},
createId : function(){
return 'x-grid3-cc-' + this.id;
} ,
getEnabled : function () {
return this.enabled;
},
setEnabled : function (value) {
this.enabled = value;
}
});
// register ptype
Ext.preg('checkcolumn', Ext.ux.grid.CheckColumn);
// backwards compat
Ext.grid.CheckColumn = Ext.ux.grid.CheckColumn;
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*
* ux.ManagedIFrame for ExtJS Library 3.1+
* Copyright(c) 2008-2009 Active Group, Inc.
* licensing@theactivegroup.com
* http://licensing.theactivegroup.com
*/
/**
* @class Ext.ux.plugin.VisibilityMode
* @version 1.3.1
* @author Doug Hendricks. doug[always-At]theactivegroup.com
* @copyright 2007-2010, Active Group, Inc. All rights reserved.
* @license <a href="http://www.gnu.org/licenses/gpl.html">GPL 3.0</a>
* Commercial Developer License (CDL) is available at http://licensing.theactivegroup.com.
* @singleton
* @static
* @desc This plugin provides an alternate mechanism for hiding Ext.Elements and a new hideMode for Ext.Components.<br />
* <p>It is generally designed for use with all browsers <b>except</b> Internet Explorer, but may used on that Browser as well.
* <p>If included in a Component as a plugin, it sets it's hideMode to 'nosize' and provides a new supported
* CSS rule that sets the height and width of an element and all child elements to 0px (rather than
* 'display:none', which causes DOM reflow to occur and re-initializes nested OBJECT, EMBED, and IFRAMES elements)
* @example
var div = Ext.get('container');
new Ext.ux.plugin.VisibilityMode().extend(div);
//You can override the Element (instance) visibilityCls to any className you wish at any time
div.visibilityCls = 'my-hide-class';
div.hide() //or div.setDisplayed(false);
// In Ext Layouts:
someContainer.add({
xtype:'flashpanel',
plugins: [new Ext.ux.plugin.VisibilityMode() ],
...
});
// or, Fix a specific Container only and all of it's child items:
// Note: An upstream Container may still cause Reflow issues when hidden/collapsed
var V = new Ext.ux.plugin.VisibilityMode({ bubble : false }) ;
new Ext.TabPanel({
plugins : V,
defaults :{ plugins: V },
items :[....]
});
*/
Ext.namespace('Ext.ux.plugin');
Ext.onReady(function(){
/* This important rule solves many of the <object/iframe>.reInit issues encountered
* when setting display:none on an upstream(parent) element (on all Browsers except IE).
* This default rule enables the new Panel:hideMode 'nosize'. The rule is designed to
* set height/width to 0 cia CSS if hidden or collapsed.
* Additional selectors also hide 'x-panel-body's within layouts to prevent
* container and <object, img, iframe> bleed-thru.
*/
var CSS = Ext.util.CSS;
if(CSS){
CSS.getRule('.x-hide-nosize') || //already defined?
CSS.createStyleSheet('.x-hide-nosize{height:0px!important;width:0px!important;border:none!important;zoom:1;}.x-hide-nosize * {height:0px!important;width:0px!important;border:none!important;zoom:1;}');
CSS.refreshCache();
}
});
(function(){
var El = Ext.Element, A = Ext.lib.Anim, supr = El.prototype;
var VISIBILITY = "visibility",
DISPLAY = "display",
HIDDEN = "hidden",
NONE = "none";
var fx = {};
fx.El = {
/**
* Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true.
* @param {Mixed} value Boolean value to display the element using its default display, or a string to set the display directly.
* @return {Ext.Element} this
*/
setDisplayed : function(value) {
var me=this;
me.visibilityCls ? (me[value !== false ?'removeClass':'addClass'](me.visibilityCls)) :
supr.setDisplayed.call(me, value);
return me;
},
/**
* Returns true if display is not "none" or the visibilityCls has not been applied
* @return {Boolean}
*/
isDisplayed : function() {
return !(this.hasClass(this.visibilityCls) || this.isStyle(DISPLAY, NONE));
},
// private
fixDisplay : function(){
var me = this;
supr.fixDisplay.call(me);
me.visibilityCls && me.removeClass(me.visibilityCls);
},
/**
* Checks whether the element is currently visible using both visibility, display, and nosize class properties.
* @param {Boolean} deep (optional) True to walk the dom and see if parent elements are hidden (defaults to false)
* @return {Boolean} True if the element is currently visible, else false
*/
isVisible : function(deep) {
var vis = this.visible ||
(!this.isStyle(VISIBILITY, HIDDEN) &&
(this.visibilityCls ?
!this.hasClass(this.visibilityCls) :
!this.isStyle(DISPLAY, NONE))
);
if (deep !== true || !vis) {
return vis;
}
var p = this.dom.parentNode,
bodyRE = /^body/i;
while (p && !bodyRE.test(p.tagName)) {
if (!Ext.fly(p, '_isVisible').isVisible()) {
return false;
}
p = p.parentNode;
}
return true;
},
//Assert isStyle method for Ext 2.x
isStyle: supr.isStyle || function(style, val) {
return this.getStyle(style) == val;
}
};
//Add basic capabilities to the Ext.Element.Flyweight class
Ext.override(El.Flyweight, fx.El);
Ext.ux.plugin.VisibilityMode = function(opt) {
Ext.apply(this, opt||{});
var CSS = Ext.util.CSS;
if(CSS && !Ext.isIE && this.fixMaximizedWindow !== false && !Ext.ux.plugin.VisibilityMode.MaxWinFixed){
//Prevent overflow:hidden (reflow) transitions when an Ext.Window is maximize.
CSS.updateRule ( '.x-window-maximized-ct', 'overflow', '');
Ext.ux.plugin.VisibilityMode.MaxWinFixed = true; //only updates the CSS Rule once.
}
};
Ext.extend(Ext.ux.plugin.VisibilityMode , Object, {
/**
* @cfg {Boolean} bubble If true, the VisibilityMode fixes are also applied to parent Containers which may also impact DOM reflow.
* @default true
*/
bubble : true,
/**
* @cfg {Boolean} fixMaximizedWindow If not false, the ext-all.css style rule 'x-window-maximized-ct' is disabled to <b>prevent</b> reflow
* after overflow:hidden is applied to the document.body.
* @default true
*/
fixMaximizedWindow : true,
/**
*
* @cfg {array} elements (optional) A list of additional named component members to also adjust visibility for.
* <br />By default, the plugin handles most scenarios automatically.
* @default null
* @example ['bwrap','toptoolbar']
*/
elements : null,
/**
* @cfg {String} visibilityCls A specific CSS classname to apply to Component element when hidden/made visible.
* @default 'x-hide-nosize'
*/
visibilityCls : 'x-hide-nosize',
/**
* @cfg {String} hideMode A specific hideMode value to assign to affected Components.
* @default 'nosize'
*/
hideMode : 'nosize' ,
ptype : 'uxvismode',
/**
* Component plugin initialization method.
* @param {Ext.Component} c The Ext.Component (or subclass) for which to apply visibilityMode treatment
*/
init : function(c) {
var hideMode = this.hideMode || c.hideMode,
plugin = this,
bubble = Ext.Container.prototype.bubble,
changeVis = function(){
var els = [this.collapseEl, this.actionMode].concat(plugin.elements||[]);
Ext.each(els, function(el){
plugin.extend( this[el] || el );
},this);
var cfg = {
visFixed : true,
animCollapse : false,
animFloat : false,
hideMode : hideMode,
defaults : this.defaults || {}
};
cfg.defaults.hideMode = hideMode;
Ext.apply(this, cfg);
Ext.apply(this.initialConfig || {}, cfg);
};
c.on('render', function(){
// Bubble up the layout and set the new
// visibility mode on parent containers
// which might also cause DOM reflow when
// hidden or collapsed.
if(plugin.bubble !== false && this.ownerCt){
bubble.call(this.ownerCt, function(){
this.visFixed || this.on('afterlayout', changeVis, this, {single:true} );
});
}
changeVis.call(this);
}, c, {single:true});
},
/**
* @param {Element/Array} el The Ext.Element (or Array of Elements) to extend visibilityCls handling to.
* @param {String} visibilityCls The className to apply to the Element when hidden.
* @return this
*/
extend : function(el, visibilityCls){
el && Ext.each([].concat(el), function(e){
if(e && e.dom){
if('visibilityCls' in e)return; //already applied or defined?
Ext.apply(e, fx.El);
e.visibilityCls = visibilityCls || this.visibilityCls;
}
},this);
return this;
}
});
Ext.preg && Ext.preg('uxvismode', Ext.ux.plugin.VisibilityMode );
/** @sourceURL=<uxvismode.js> */
Ext.provide && Ext.provide('uxvismode');
})();/* global Ext El ElFrame ELD*/
/*
* ******************************************************************************
* This file is distributed on an AS IS BASIS WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* ***********************************************************************************
* License: multidom.js is offered under an MIT License.
* Donations are welcomed: http://donate.theactivegroup.com
*/
/**
* @class multidom
* @version 2.13
* @license MIT
* @author Doug Hendricks. Forum ID: <a href="http://extjs.com/forum/member.php?u=8730">hendricd</a>
* @donate <a target="tag_donate" href="http://donate.theactivegroup.com"><img border="0" src="http://www.paypal.com/en_US/i/btn/x-click-butcc-donate.gif" border="0" alt="Make a donation to support ongoing development"></a>
* @copyright 2007-2010, Active Group, Inc. All rights reserved.
* @description [Designed For Ext Core and ExtJs Frameworks (using ext-base adapter only) 3.0 or higher ONLY]
* The multidom library extends (overloads) Ext Core DOM methods and functions to
* provide document-targeted access to the documents loaded in external (FRAME/IFRAME)
* documents.
* <p>It maintains seperate DOM Element caches (and more) for each document instance encountered by the
* framework, permitting safe access to DOM Elements across document instances that may share
* the same Element id or name. In essence, multidom extends the functionality provided by Ext Core
* into any child document without having to load the Core library into the frame's global context.
* <h3>Custom Element classes.</h3>
* The Ext.get method is enhanced to support resolution of the custom Ext.Element implementations.
* (The ux.ManagedIFrame 2 Element class is an example of such a class.)
* <p>For example: If you were retrieving the Ext.Element instance for an IFRAME and the class
* Ext.Element.IFRAME were defined:
* <pre><code>Ext.get('myFrame')</pre></code>
* would return an instance of Ext.Element.IFRAME for 'myFrame' if it were found.
* @example
// return the Ext.Element with an id 'someDiv' located in external document hosted by 'iframe'
var iframe = Ext.get('myFrame');
var div = Ext.get('someDiv', iframe.getFrameDocument()); //Firefox example
if(div){
div.center();
}
Note: ux.ManagedIFrame provides an equivalent 'get' method of it's own to access embedded DOM Elements
for the document it manages.
<pre><code>iframe.get('someDiv').center();</pre></code>
Likewise, you can retrieve the raw Element of another document with:
var el = Ext.getDom('myDiv', iframe.getFrameDocument());
*/
(function(){
/*
* Ext.Element and Ext.lib.DOM enhancements.
* Primarily provides the ability to interact with any document context
* (not just the one Ext was loaded into).
*/
var El = Ext.Element,
ElFrame,
ELD = Ext.lib.Dom,
A = Ext.lib.Anim,
Evm = Ext.EventManager,
E = Ext.lib.Event,
DOC = document,
emptyFn = function(){},
OP = Object.prototype,
OPString = OP.toString,
HTMLDoc = '[object HTMLDocument]';
if(!Ext.elCache || parseInt( Ext.version.replace(/\./g,''),10) < 311 ) {
alert ('Ext Release '+Ext.version+' is not supported');
}
/**
* @private
*/
Ext._documents= {};
Ext._documents[Ext.id(document,'_doc')]=Ext.elCache;
/**
* @private
* Resolve the Element cache for a given element/window/document context.
*/
var resolveCache = ELD.resolveDocumentCache = function(el, cacheId){
var doc = GETDOC(el),
c = Ext.isDocument(doc) ? Ext.id(doc) : cacheId,
cache = Ext._documents[c] || null;
return cache || (c ? Ext._documents[c] = {}: null);
},
clearCache = ELD.clearDocumentCache = function(cacheId){
delete Ext._documents[cacheId];
};
El.addMethods || ( El.addMethods = function(ov){ Ext.apply(El.prototype, ov||{}); });
Ext.removeNode = function(n){
var dom = n ? n.dom || n : null,
el, elc, elCache = resolveCache(dom), parent;
//clear out any references if found in the El.cache(s)
if(dom && (elc = elCache[dom.id]) && (el = elc.el) ){
if(el.dom){
Ext.enableNestedListenerRemoval ? Evm.purgeElement(el.dom, true) : Evm.removeAll(el.dom);
}
delete elCache[dom.id];
delete el.dom;
delete el._context;
el = null;
}
//No removal for window, documents, or bodies
if(dom && !dom.navigator && !Ext.isDocument(dom) && dom.tagName != 'BODY'){
(parent = dom.parentElement || dom.parentNode) && parent.removeChild(dom);
}
dom = parent = null;
};
var overload = function(pfn, fn ){
var f = typeof pfn === 'function' ? pfn : function t(){};
var ov = f._ovl; //call signature hash
if(!ov){
ov = { base: f};
ov[f.length|| 0] = f;
f= function t(){ //the proxy stub
var o = arguments.callee._ovl;
var fn = o[arguments.length] || o.base;
//recursion safety
return fn && fn != arguments.callee ? fn.apply(this,arguments): undefined;
};
}
var fnA = [].concat(fn);
for(var i=0,l=fnA.length; i<l; ++i){
//ensures no duplicate call signatures, but last in rules!
ov[fnA[i].length] = fnA[i];
}
f._ovl= ov;
var t = null;
return f;
};
Ext.applyIf( Ext, {
overload : overload( overload,
[
function(fn){ return overload(null, fn);},
function(obj, mname, fn){
return obj[mname] = overload(obj[mname],fn);}
]),
isArray : function(v){
return !!v && OPString.apply(v) == '[object Array]';
},
isObject:function(obj){
return !!obj && typeof obj == 'object';
},
/**
* HTMLDocument assertion with optional accessibility testing
* @param {HTMLELement} el The DOM Element to test
* @param {Boolean} testOrigin (optional) True to test "same-origin" access
*
*/
isDocument : function(el, testOrigin){
var elm = el ? el.dom || el : null;
var test = elm && ((OPString.apply(elm) == HTMLDoc) || (elm && elm.nodeType == 9));
if(test && testOrigin){
try{
test = !!elm.location;
}
catch(e){return false;}
}
return test;
},
isWindow : function(el){
var elm = el ? el.dom || el : null;
return elm ? !!elm.navigator || OPString.apply(elm) == "[object Window]" : false;
},
isIterable : function(v){
//check for array or arguments
if(Ext.isArray(v) || v.callee){
return true;
}
//check for node list type
if(/NodeList|HTMLCollection/.test(OPString.call(v))){
return true;
}
//NodeList has an item and length property
//IXMLDOMNodeList has nextNode method, needs to be checked first.
return ((typeof v.nextNode != 'undefined' || v.item) && Ext.isNumber(v.length));
},
isElement : function(obj){
return obj && Ext.type(obj)== 'element';
},
isEvent : function(obj){
return OPString.apply(obj) == '[object Event]' || (Ext.isObject(obj) && !Ext.type(o.constructor) && (window.event && obj.clientX && obj.clientX == window.event.clientX));
},
isFunction: function(obj){
return !!obj && typeof obj == 'function';
},
/**
* Determine whether a specified DOMEvent is supported by a given HTMLElement or Object.
* @param {String} type The eventName (without the 'on' prefix)
* @param {HTMLElement/Object/String} testEl (optional) A specific HTMLElement/Object to test against, otherwise a tagName to test against.
* based on the passed eventName is used, or DIV as default.
* @return {Boolean} True if the passed object supports the named event.
*/
isEventSupported : function(evName, testEl){
var TAGNAMES = {
'select':'input',
'change':'input',
'submit':'form',
'reset':'form',
'load':'img',
'error':'img',
'abort':'img'
},
//Cached results
cache = {},
onPrefix = /^on/i,
//Get a tokenized string of the form nodeName:type
getKey = function(type, el){
var tEl = Ext.getDom(el);
return (tEl ?
(Ext.isElement(tEl) || Ext.isDocument(tEl) ?
tEl.nodeName.toLowerCase() :
el.self ? '#window' : el || '#object')
: el || 'div') + ':' + type;
};
return function (evName, testEl) {
evName = (evName || '').replace(onPrefix,'');
var el, isSupported = false;
var eventName = 'on' + evName;
var tag = (testEl ? testEl : TAGNAMES[evName]) || 'div';
var key = getKey(evName, tag);
if(key in cache){
//Use a previously cached result if available
return cache[key];
}
el = Ext.isString(tag) ? DOC.createElement(tag): testEl;
isSupported = (!!el && (eventName in el));
isSupported || (isSupported = window.Event && !!(String(evName).toUpperCase() in window.Event));
if (!isSupported && el) {
el.setAttribute && el.setAttribute(eventName, 'return;');
isSupported = Ext.isFunction(el[eventName]);
}
//save the cached result for future tests
cache[key] = isSupported;
el = null;
return isSupported;
};
}()
});
/**
* @private
* Determine Ext.Element[tagName] or Ext.Element (default)
*/
var assertClass = function(el){
return El;
return El[(el.tagName || '-').toUpperCase()] || El;
};
var libFlyweight;
function fly(el, doc) {
if (!libFlyweight) {
libFlyweight = new Ext.Element.Flyweight();
}
libFlyweight.dom = Ext.getDom(el, null, doc);
return libFlyweight;
}
Ext.apply(Ext, {
/*
* Overload Ext.get to permit Ext.Element access to other document objects
* This implementation maintains safe element caches for each document queried.
*
*/
get : El.get = function(el, doc){ //document targeted
if(!el ){ return null; }
var isDoc = Ext.isDocument(el);
Ext.isDocument(doc) || (doc = DOC);
var ex, elm, id, cache = resolveCache(doc);
if(typeof el == "string"){ // element id
elm = Ext.getDom(el, null, doc);
if(!elm) return null;
if(cache[el] && cache[el].el){
ex = cache[el].el;
ex.dom = elm;
}else{
ex = El.addToCache(new (assertClass(elm))(elm, null, doc));
}
return ex;
}else if(isDoc){
if(!Ext.isDocument(el, true)){ return false; } //is it accessible
cache = resolveCache(el);
if(cache[Ext.id(el)] && cache[el.id].el){
return cache[el.id].el;
}
// create a bogus element object representing the document object
var f = function(){};
f.prototype = El.prototype;
var docEl = new f();
docEl.dom = el;
docEl.id = Ext.id(el,'_doc');
docEl._isDoc = true;
El.addToCache( docEl, null, cache);
return docEl;
}else if( el instanceof El ){
// refresh dom element in case no longer valid,
// catch case where it hasn't been appended
if(el.dom){
el.id = Ext.id(el.dom);
}else{
el.dom = el.id ? Ext.getDom(el.id, true) : null;
}
if(el.dom){
cache = resolveCache(el);
(cache[el.id] ||
(cache[el.id] = {data : {}, events : {}}
)).el = el; // in case it was created directly with Element(), let's cache it
}
return el;
}else if(el.tagName || Ext.isWindow(el)){ // dom element
cache = resolveCache(el);
id = Ext.id(el);
if(cache[id] && (ex = cache[id].el)){
ex.dom = el;
}else{
ex = El.addToCache(new (assertClass(el))(el, null, doc), null, cache);
}
return ex;
}else if(el.isComposite){
return el;
}else if(Ext.isArray(el)){
return Ext.get(doc,doc).select(el);
}
return null;
},
/**
* Ext.getDom to support targeted document contexts
*/
getDom : function(el, strict, doc){
var D = doc || DOC;
if(!el || !D){
return null;
}
if (el.dom){
return el.dom;
} else {
if (Ext.isString(el)) {
var e = D.getElementById(el);
// IE returns elements with the 'name' and 'id' attribute.
// we do a strict check to return the element with only the id attribute
if (e && Ext.isIE && strict) {
if (el == e.getAttribute('id')) {
return e;
} else {
return null;
}
}
return e;
} else {
return el;
}
}
},
/**
* Returns the current/specified document body as an {@link Ext.Element}.
* @param {HTMLDocument} doc (optional)
* @return Ext.Element The document's body
*/
getBody : function(doc){
var D = ELD.getDocument(doc) || DOC;
return Ext.get(D.body || D.documentElement);
},
getDoc :Ext.overload([
Ext.getDoc,
function(doc){ return Ext.get(doc,doc); }
])
});
// private method for getting and setting element data
El.data = function(el, key, value){
el = El.get(el);
if (!el) {
return null;
}
var c = resolveCache(el)[el.id].data;
if(arguments.length == 2){
return c[key];
}else{
return (c[key] = value);
}
};
El.addToCache = function(el, id, cache ){
id = id || Ext.id(el);
var C = cache || resolveCache(el);
C[id] = {
el: el.dom ? el : Ext.get(el),
data: {},
events: {}
};
var d = C[id].el.dom;
(d.getElementById || d.navigator) && (C[id].skipGC = true);
return C[id].el;
};
El.removeFromCache = function(el, cache){
if(el && el.id){
var C = cache || resolveCache(el);
delete C[el.id];
}
};
/*
* Add new Visibility Mode to element (sets height and width to 0px instead of display:none )
*/
El.ASCLASS = 3;
El.visibilityCls = 'x-hide-nosize';
var propCache = {},
camelRe = /(-[a-z])/gi,
camelFn = function(m, a){ return a.charAt(1).toUpperCase(); },
opacityRe = /alpha\(opacity=(.*)\)/i,
trimRe = /^\s+|\s+$/g,
marginRightRe = /marginRight/,
propFloat = Ext.isIE ? 'styleFloat' : 'cssFloat',
view = DOC.defaultView,
VISMODE = 'visibilityMode',
ELDISPLAY = El.DISPLAY,
ELVISIBILITY = El.VISIBILITY,
ELASCLASS = El.ASCLASS,
ORIGINALDISPLAY = 'originalDisplay',
PADDING = "padding",
MARGIN = "margin",
BORDER = "border",
LEFT = "-left",
RIGHT = "-right",
TOP = "-top",
BOTTOM = "-bottom",
WIDTH = "-width",
MATH = Math,
OPACITY = "opacity",
VISIBILITY = "visibility",
DISPLAY = "display",
OFFSETS = "offsets",
ASCLASS = "asclass",
HIDDEN = "hidden",
NONE = "none",
ISVISIBLE = 'isVisible',
ISCLIPPED = 'isClipped',
OVERFLOW = 'overflow',
OVERFLOWX = 'overflow-x',
OVERFLOWY = 'overflow-y',
ORIGINALCLIP = 'originalClip',
XMASKED = "x-masked",
XMASKEDRELATIVE = "x-masked-relative",
// special markup used throughout Ext when box wrapping elements
borders = {l: BORDER + LEFT + WIDTH, r: BORDER + RIGHT + WIDTH, t: BORDER + TOP + WIDTH, b: BORDER + BOTTOM + WIDTH},
paddings = {l: PADDING + LEFT, r: PADDING + RIGHT, t: PADDING + TOP, b: PADDING + BOTTOM},
margins = {l: MARGIN + LEFT, r: MARGIN + RIGHT, t: MARGIN + TOP, b: MARGIN + BOTTOM},
data = El.data,
GETDOM = Ext.getDom,
GET = Ext.get,
DH = Ext.DomHelper,
propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/,
CSS = Ext.util.CSS, //Not available in Ext Core.
getDisplay = function(dom){
var d = data(dom, ORIGINALDISPLAY);
if(d === undefined){
data(dom, ORIGINALDISPLAY, d = '');
}
return d;
},
getVisMode = function(dom){
var m = data(dom, VISMODE);
if(m === undefined){
data(dom, VISMODE, m = El.prototype.visibilityMode);
}
return m;
};
function chkCache(prop) {
return propCache[prop] || (propCache[prop] = prop == 'float' ? propFloat : prop.replace(camelRe, camelFn));
};
El.addMethods({
/**
* Resolves the current document context of this Element
*/
getDocument : function(){
return this._context || (this._context = GETDOC(this));
},
/**
* Removes this element from the DOM and deletes it from the cache
* @param {Boolean} cleanse (optional) Perform a cleanse of immediate childNodes as well.
* @param {Boolean} deep (optional) Perform a deep cleanse of all nested childNodes as well.
*/
remove : function(cleanse, deep){
var dom = this.dom;
this.isMasked() && this.unmask();
if(dom){
Ext.removeNode(dom);
delete this._context;
delete this.dom;
}
},
/**
* Appends the passed element(s) to this element
* @param {String/HTMLElement/Array/Element/CompositeElement} el
* @param {Document} doc (optional) specific document context for the Element search
* @return {Ext.Element} this
*/
appendChild: function(el, doc){
return GET(el, doc || this.getDocument()).appendTo(this);
},
/**
* Appends this element to the passed element
* @param {Mixed} el The new parent element
* @param {Document} doc (optional) specific document context for the Element search
* @return {Ext.Element} this
*/
appendTo: function(el, doc){
GETDOM(el, false, doc || this.getDocument()).appendChild(this.dom);
return this;
},
/**
* Inserts this element before the passed element in the DOM
* @param {Mixed} el The element before which this element will be inserted
* @param {Document} doc (optional) specific document context for the Element search
* @return {Ext.Element} this
*/
insertBefore: function(el, doc){
(el = GETDOM(el, false, doc || this.getDocument())).parentNode.insertBefore(this.dom, el);
return this;
},
/**
* Inserts this element after the passed element in the DOM
* @param {Mixed} el The element to insert after
* @param {Document} doc (optional) specific document context for the Element search
* @return {Ext.Element} this
*/
insertAfter: function(el, doc){
(el = GETDOM(el, false, doc || this.getDocument())).parentNode.insertBefore(this.dom, el.nextSibling);
return this;
},
/**
* Inserts (or creates) an element (or DomHelper config) as the first child of this element
* @param {Mixed/Object} el The id or element to insert or a DomHelper config to create and insert
* @param {Document} doc (optional) specific document context for the Element search
* @return {Ext.Element} The new child
*/
insertFirst: function(el, returnDom){
el = el || {};
if(el.nodeType || el.dom || typeof el == 'string'){ // element
el = GETDOM(el);
this.dom.insertBefore(el, this.dom.firstChild);
return !returnDom ? GET(el) : el;
}else{ // dh config
return this.createChild(el, this.dom.firstChild, returnDom);
}
},
/**
* Replaces the passed element with this element
* @param {Mixed} el The element to replace
* @param {Document} doc (optional) specific document context for the Element search
* @return {Ext.Element} this
*/
replace: function(el, doc){
el = GET(el, doc || this.getDocument());
this.insertBefore(el);
el.remove();
return this;
},
/**
* Replaces this element with the passed element
* @param {Mixed/Object} el The new element or a DomHelper config of an element to create
* @param {Document} doc (optional) specific document context for the Element search
* @return {Ext.Element} this
*/
replaceWith: function(el, doc){
var me = this;
if(el.nodeType || el.dom || typeof el == 'string'){
el = GETDOM(el, false, doc || me.getDocument());
me.dom.parentNode.insertBefore(el, me.dom);
}else{
el = DH.insertBefore(me.dom, el);
}
var C = resolveCache(me);
Ext.removeNode(me.dom);
me.id = Ext.id(me.dom = el);
El.addToCache(me.isFlyweight ? new (assertClass(me.dom))(me.dom, null, C) : me);
return me;
},
/**
* Inserts an html fragment into this element
* @param {String} where Where to insert the html in relation to this element - beforeBegin, afterBegin, beforeEnd, afterEnd.
* @param {String} html The HTML fragment
* @param {Boolean} returnEl (optional) True to return an Ext.Element (defaults to false)
* @return {HTMLElement/Ext.Element} The inserted node (or nearest related if more than 1 inserted)
*/
insertHtml : function(where, html, returnEl){
var el = DH.insertHtml(where, this.dom, html);
return returnEl ? Ext.get(el, GETDOC(el)) : el;
},
/**
* Sets the element's visibility mode. When setVisible() is called it
* will use this to determine whether to set the visibility or the display property.
* @param {Number} visMode Ext.Element.VISIBILITY or Ext.Element.DISPLAY
* @return {Ext.Element} this
*/
setVisibilityMode : function(visMode){
data(this.dom, VISMODE, visMode);
return this;
},
/**
* Checks whether the element is currently visible using both visibility and display properties.
* @return {Boolean} True if the element is currently visible, else false
*/
isVisible : function() {
return this.visible || Ext.value( data(this.dom, ISVISIBLE ),
!this.isStyle(VISIBILITY, HIDDEN) && !this.isStyle(DISPLAY, NONE));
},
//visibilityMode : El.DISPLAY = 3,
/**
* Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
* the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
* @param {Boolean} visible Whether the element is visible
* @param {Boolean/Object} animate (optional) True for the default animation, or a standard Element animation config object, or one of four
* possible hideMode strings: 'display, visibility, offsets, asclass'
* @return {Ext.Element} this
*/
setVisible : function(visible, animate){
var me = this,
dom = me.dom,
isDisplay, isVisibility, isOffsets, isClass;
// hideMode string override
if (typeof animate == 'string'){
isDisplay = animate == DISPLAY;
isVisibility = animate == VISIBILITY;
isOffsets = animate == OFFSETS;
isClass = animate == ASCLASS;
animate = false;
} else {
var visMode = getVisMode(dom);
isDisplay = visMode == ELDISPLAY;
isVisibility = visMode == ELVISIBILITY;
isClass = visMode == ELASCLASS;
}
if (!animate || !me.anim) {
if (isClass){
me[visible?'removeClass':'addClass'](me.visibilityCls || El.visibilityCls);
} else if (isDisplay){
return me.setDisplayed(visible);
} else if (isOffsets){
if (!visible){
me.hideModeStyles = {
position: me.getStyle('position'),
top: me.getStyle('top'),
left: me.getStyle('left')
};
me.applyStyles({position: 'absolute', top: '-10000px', left: '-10000px'});
} else {
me.applyStyles(me.hideModeStyles || {position: '', top: '', left: ''});
delete me.hideModeStyles;
}
}else{
me.fixDisplay();
if (dom) {
dom.style.visibility = visible ? "visible" : HIDDEN;
}
}
}else{
// closure for composites
if(visible){
me.setOpacity(.01);
me.setVisible(true);
}
me.anim({opacity: { to: (visible?1:0) }},
me.preanim(arguments, 1),
null,
.35,
'easeIn',
function(){
if(!visible){
isClass ?
me.addClass(me.visibilityCls || El.visibilityCls) :
dom.style[isDisplay ? DISPLAY : VISIBILITY] = (isDisplay) ? NONE : HIDDEN;
me.setOpacity(1);
}
});
}
data(dom, ISVISIBLE, visible); //set logical visibility state
return me;
},
/**
* Sets the CSS display property. Uses originalDisplay if the specified value is a boolean true.
* @param {Mixed} value Boolean value to display the element using its default display, or a string to set the display directly.
* @return {Ext.Element} this
*/
setDisplayed : function(value) {
var dom = this.dom,
visMode = getVisMode(dom);
if(typeof value == "boolean"){
if(visMode == El.ASCLASS){
return this.setVisible(value, ASCLASS);
}
data(this.dom, ISVISIBLE, value);
value = value ? getDisplay(dom) : NONE;
}
this.setStyle(DISPLAY, value);
return this;
},
// private
fixDisplay : function(){
var me = this;
if(me.isStyle(DISPLAY, NONE)){
me.setStyle(VISIBILITY, HIDDEN);
me.setStyle(DISPLAY, getDisplay(me.dom)); // first try reverting to default
if(me.isStyle(DISPLAY, NONE)){ // if that fails, default to block
me.setStyle(DISPLAY, "block");
}
}
data(me.dom, ISVISIBLE) || me.removeClass(me.visibilityCls || El.visibilityCls);
},
/**
* Convenience method for setVisibilityMode(Element.DISPLAY)
* @param {String} display (optional) What to set display to when visible
* @return {Ext.Element} this
*/
enableDisplayMode : function(display){
this.setVisibilityMode(El.DISPLAY);
if(!Ext.isEmpty(display)){
data(this.dom, ORIGINALDISPLAY, display);
}
return this;
},
scrollIntoView : function(container, hscroll){
var d = this.getDocument(),
c = Ext.getDom(container, null, d) || Ext.getBody(d).dom,
el = this.dom,
o = this.getOffsetsTo(c),
l = o[0] + c.scrollLeft,
t = o[1] + c.scrollTop,
b = t + el.offsetHeight,
r = l + el.offsetWidth,
ch = c.clientHeight,
ct = parseInt(c.scrollTop, 10),
cl = parseInt(c.scrollLeft, 10),
cb = ct + ch,
cr = cl + c.clientWidth;
if(el.offsetHeight > ch || t < ct){
c.scrollTop = t;
}else if(b > cb){
c.scrollTop = b-ch;
}
// corrects IE, other browsers will ignore
c.scrollTop = c.scrollTop;
if(hscroll !== false){
if(el.offsetWidth > c.clientWidth || l < cl){
c.scrollLeft = l;
}else if(r > cr){
c.scrollLeft = r-c.clientWidth;
}
c.scrollLeft = c.scrollLeft;
}
return this;
},
contains : function(el){
try {
return !el ? false : ELD.isAncestor(this.dom, el.dom ? el.dom : el);
} catch(e) {
return false;
}
},
/**
* Returns the current scroll position of the element.
* @return {Object} An object containing the scroll position in the format {left: (scrollLeft), top: (scrollTop)}
*/
getScroll : function(){
var d = this.dom,
doc = this.getDocument(),
body = doc.body,
docElement = doc.documentElement,
l,
t,
ret;
if(Ext.isDocument(d) || d == body){
if(Ext.isIE && ELD.docIsStrict(doc)){
l = docElement.scrollLeft;
t = docElement.scrollTop;
}else{
l = window.pageXOffset;
t = window.pageYOffset;
}
ret = {left: l || (body ? body.scrollLeft : 0), top: t || (body ? body.scrollTop : 0)};
}else{
ret = {left: d.scrollLeft, top: d.scrollTop};
}
return ret;
},
/**
* Normalizes currentStyle and computedStyle.
* @param {String} property The style property whose value is returned.
* @return {String} The current value of the style property for this element.
*/
getStyle : function(){
var getStyle =
view && view.getComputedStyle ?
function GS(prop){
var el = !this._isDoc ? this.dom : null,
v,
cs,
out,
display,
wk = Ext.isWebKit,
display;
if(!el || !el.style) return null;
prop = chkCache(prop);
out = (v = el.style[prop]) ? v :
(cs = view.getComputedStyle(el, '')) ? cs[prop] : null;
// Fix bug caused by this: https://bugs.webkit.org/show_bug.cgi?id=13343
if(wk){
if((marginRightRe.test(prop)) && out != '0px'){
display = this.getStyle('display');
el.style.display = 'inline-block';
out = view.getComputedStyle(el, '');
el.style.display = display;
}
// Webkit returns rgb values for transparent.
if(out == 'rgba(0, 0, 0, 0)'){
out = 'transparent';
}
}
return out;
} :
function GS(prop){ //IE
var el = !this._isDoc ? this.dom : null,
m,
cs;
if(!el || !el.style) return null;
if (prop == OPACITY) {
if (el.style.filter.match) {
if(m = el.style.filter.match(opacityRe)){
var fv = parseFloat(m[1]);
if(!isNaN(fv)){
return fv ? fv / 100 : 0;
}
}
}
return 1;
}
prop = chkCache(prop);
return el.style[prop] || ((cs = el.currentStyle) ? cs[prop] : null);
};
var GS = null;
return getStyle;
}(),
/**
* Wrapper for setting style properties, also takes single object parameter of multiple styles.
* @param {String/Object} property The style property to be set, or an object of multiple styles.
* @param {String} value (optional) The value to apply to the given property, or null if an object was passed.
* @return {Ext.Element} this
*/
setStyle : function(prop, value){
if(this._isDoc || Ext.isDocument(this.dom)) return this;
var tmp, style;
if (typeof prop != 'object') {
tmp = {};
tmp[prop] = value;
prop = tmp;
}
for (style in prop) {
value = prop[style];
if (style == OPACITY) {
this.setOpacity(value)
}
else {
try {
this.dom.style[chkCache(style)] = value;
}
catch (err) {
null;
}
}
}
return this;
},
/**
* Centers the Element in either the viewport, or another Element.
* @param {Mixed} centerIn (optional) The element in which to center the element.
*/
center : function(centerIn){
return this.alignTo(centerIn || this.getDocument(), 'c-c');
},
/**
* Puts a mask over this element to disable user interaction. Requires core.css.
* This method can only be applied to elements which accept child nodes.
* @param {String} msg (optional) A message to display in the mask
* @param {String} msgCls (optional) A css class to apply to the msg element
* @return {Element} The mask element
*/
mask : function(msg, msgCls){
var me = this,
dom = me.dom,
dh = Ext.DomHelper,
EXTELMASKMSG = "ext-el-mask-msg",
el,
mask;
if(me.getStyle("position") == "static"){
me.addClass(XMASKEDRELATIVE);
}
if((el = data(dom, 'maskMsg'))){
el.remove();
}
if((el = data(dom, 'mask'))){
el.remove();
}
mask = dh.append(dom, {cls : "ext-el-mask"}, true);
data(dom, 'mask', mask);
me.addClass(XMASKED);
mask.setDisplayed(true);
if(typeof msg == 'string'){
var mm = dh.append(dom, {cls : EXTELMASKMSG, cn:{tag:'div'}}, true);
data(dom, 'maskMsg', mm);
mm.dom.className = msgCls ? EXTELMASKMSG + " " + msgCls : EXTELMASKMSG;
mm.dom.firstChild.innerHTML = msg;
mm.setDisplayed(true);
mm.center(me);
}
if(Ext.isIE && !(Ext.isIE7 && Ext.isStrict) && me.getStyle('height') == 'auto'){ // ie will not expand full height automatically
mask.setSize(undefined, me.getHeight());
}
return mask;
},
/**
* Removes a previously applied mask.
*/
unmask : function(){
var me = this,
dom = me.dom,
mask = data(dom, 'mask'),
maskMsg = data(dom, 'maskMsg');
if(mask){
if(maskMsg){
maskMsg.remove();
data(dom, 'maskMsg', undefined);
}
mask.remove();
data(dom, 'mask', undefined);
}
me.removeClass([XMASKED, XMASKEDRELATIVE]);
},
/**
* Returns true if this element is masked
* @return {Boolean}
*/
isMasked : function(){
var m = data(this.dom, 'mask');
return m && m.isVisible();
},
/**
* Calculates the x, y to center this element on the screen
* @return {Array} The x, y values [x, y]
*/
getCenterXY : function(){
return this.getAlignToXY(this.getDocument(), 'c-c');
},
/**
* Gets the x,y coordinates specified by the anchor position on the element.
* @param {String} anchor (optional) The specified anchor position (defaults to "c"). See {@link #alignTo}
* for details on supported anchor positions.
* @param {Boolean} local (optional) True to get the local (element top/left-relative) anchor position instead
* of page coordinates
* @param {Object} size (optional) An object containing the size to use for calculating anchor position
* {width: (target width), height: (target height)} (defaults to the element's current size)
* @return {Array} [x, y] An array containing the element's x and y coordinates
*/
getAnchorXY : function(anchor, local, s){
//Passing a different size is useful for pre-calculating anchors,
//especially for anchored animations that change the el size.
anchor = (anchor || "tl").toLowerCase();
s = s || {};
var me = this, doc = this.getDocument(),
vp = me.dom == doc.body || me.dom == doc,
w = s.width || vp ? ELD.getViewWidth(false,doc) : me.getWidth(),
h = s.height || vp ? ELD.getViewHeight(false,doc) : me.getHeight(),
xy,
r = Math.round,
o = me.getXY(),
scroll = me.getScroll(),
extraX = vp ? scroll.left : !local ? o[0] : 0,
extraY = vp ? scroll.top : !local ? o[1] : 0,
hash = {
c : [r(w * .5), r(h * .5)],
t : [r(w * .5), 0],
l : [0, r(h * .5)],
r : [w, r(h * .5)],
b : [r(w * .5), h],
tl : [0, 0],
bl : [0, h],
br : [w, h],
tr : [w, 0]
};
xy = hash[anchor];
return [xy[0] + extraX, xy[1] + extraY];
},
/**
* Anchors an element to another element and realigns it when the window is resized.
* @param {Mixed} element The element to align to.
* @param {String} position The position to align to.
* @param {Array} offsets (optional) Offset the positioning by [x, y]
* @param {Boolean/Object} animate (optional) True for the default animation or a standard Element animation config object
* @param {Boolean/Number} monitorScroll (optional) True to monitor body scroll and reposition. If this parameter
* is a number, it is used as the buffer delay (defaults to 50ms).
* @param {Function} callback The function to call after the animation finishes
* @return {Ext.Element} this
*/
anchorTo : function(el, alignment, offsets, animate, monitorScroll, callback){
var me = this,
dom = me.dom;
function action(){
fly(dom).alignTo(el, alignment, offsets, animate);
Ext.callback(callback, fly(dom));
};
Ext.EventManager.onWindowResize(action, me);
if(!Ext.isEmpty(monitorScroll)){
Ext.EventManager.on(window, 'scroll', action, me,
{buffer: !isNaN(monitorScroll) ? monitorScroll : 50});
}
action.call(me); // align immediately
return me;
},
/**
* Returns the current scroll position of the element.
* @return {Object} An object containing the scroll position in the format {left: (scrollLeft), top: (scrollTop)}
*/
getScroll : function(){
var d = this.dom,
doc = this.getDocument(),
body = doc.body,
docElement = doc.documentElement,
l,
t,
ret;
if(d == doc || d == body){
if(Ext.isIE && ELD.docIsStrict(doc)){
l = docElement.scrollLeft;
t = docElement.scrollTop;
}else{
l = window.pageXOffset;
t = window.pageYOffset;
}
ret = {left: l || (body ? body.scrollLeft : 0), top: t || (body ? body.scrollTop : 0)};
}else{
ret = {left: d.scrollLeft, top: d.scrollTop};
}
return ret;
},
/**
* Gets the x,y coordinates to align this element with another element. See {@link #alignTo} for more info on the
* supported position values.
* @param {Mixed} element The element to align to.
* @param {String} position The position to align to.
* @param {Array} offsets (optional) Offset the positioning by [x, y]
* @return {Array} [x, y]
*/
getAlignToXY : function(el, p, o){
var doc;
el = Ext.get(el, doc = this.getDocument());
if(!el || !el.dom){
throw "Element.getAlignToXY with an element that doesn't exist";
}
o = o || [0,0];
p = (p == "?" ? "tl-bl?" : (!/-/.test(p) && p != "" ? "tl-" + p : p || "tl-bl")).toLowerCase();
var me = this,
d = me.dom,
a1,
a2,
x,
y,
//constrain the aligned el to viewport if necessary
w,
h,
r,
dw = ELD.getViewWidth(false,doc) -10, // 10px of margin for ie
dh = ELD.getViewHeight(false,doc)-10, // 10px of margin for ie
p1y,
p1x,
p2y,
p2x,
swapY,
swapX,
docElement = doc.documentElement,
docBody = doc.body,
scrollX = (docElement.scrollLeft || docBody.scrollLeft || 0)+5,
scrollY = (docElement.scrollTop || docBody.scrollTop || 0)+5,
c = false, //constrain to viewport
p1 = "",
p2 = "",
m = p.match(/^([a-z]+)-([a-z]+)(\?)?$/);
if(!m){
throw "Element.getAlignToXY with an invalid alignment " + p;
}
p1 = m[1];
p2 = m[2];
c = !!m[3];
//Subtract the aligned el's internal xy from the target's offset xy
//plus custom offset to get the aligned el's new offset xy
a1 = me.getAnchorXY(p1, true);
a2 = el.getAnchorXY(p2, false);
x = a2[0] - a1[0] + o[0];
y = a2[1] - a1[1] + o[1];
if(c){
w = me.getWidth();
h = me.getHeight();
r = el.getRegion();
//If we are at a viewport boundary and the aligned el is anchored on a target border that is
//perpendicular to the vp border, allow the aligned el to slide on that border,
//otherwise swap the aligned el to the opposite border of the target.
p1y = p1.charAt(0);
p1x = p1.charAt(p1.length-1);
p2y = p2.charAt(0);
p2x = p2.charAt(p2.length-1);
swapY = ((p1y=="t" && p2y=="b") || (p1y=="b" && p2y=="t"));
swapX = ((p1x=="r" && p2x=="l") || (p1x=="l" && p2x=="r"));
if (x + w > dw + scrollX) {
x = swapX ? r.left-w : dw+scrollX-w;
}
if (x < scrollX) {
x = swapX ? r.right : scrollX;
}
if (y + h > dh + scrollY) {
y = swapY ? r.top-h : dh+scrollY-h;
}
if (y < scrollY){
y = swapY ? r.bottom : scrollY;
}
}
return [x,y];
},
// private ==> used outside of core
adjustForConstraints : function(xy, parent, offsets){
return this.getConstrainToXY(parent || this.getDocument(), false, offsets, xy) || xy;
},
// private ==> used outside of core
getConstrainToXY : function(el, local, offsets, proposedXY){
var os = {top:0, left:0, bottom:0, right: 0};
return function(el, local, offsets, proposedXY){
var doc = this.getDocument();
el = Ext.get(el, doc);
offsets = offsets ? Ext.applyIf(offsets, os) : os;
var vw, vh, vx = 0, vy = 0;
if(el.dom == doc.body || el.dom == doc){
vw = ELD.getViewWidth(false,doc);
vh = ELD.getViewHeight(false,doc);
}else{
vw = el.dom.clientWidth;
vh = el.dom.clientHeight;
if(!local){
var vxy = el.getXY();
vx = vxy[0];
vy = vxy[1];
}
}
var s = el.getScroll();
vx += offsets.left + s.left;
vy += offsets.top + s.top;
vw -= offsets.right;
vh -= offsets.bottom;
var vr = vx + vw,
vb = vy + vh,
xy = proposedXY || (!local ? this.getXY() : [this.getLeft(true), this.getTop(true)]);
x = xy[0], y = xy[1],
offset = this.getConstrainOffset(),
w = this.dom.offsetWidth + offset,
h = this.dom.offsetHeight + offset;
// only move it if it needs it
var moved = false;
// first validate right/bottom
if((x + w) > vr){
x = vr - w;
moved = true;
}
if((y + h) > vb){
y = vb - h;
moved = true;
}
// then make sure top/left isn't negative
if(x < vx){
x = vx;
moved = true;
}
if(y < vy){
y = vy;
moved = true;
}
return moved ? [x, y] : false;
};
}(),
// private, used internally
getConstrainOffset : function(){
return 0;
},
/**
* Calculates the x, y to center this element on the screen
* @return {Array} The x, y values [x, y]
*/
getCenterXY : function(){
return this.getAlignToXY(Ext.getBody(this.getDocument()), 'c-c');
},
/**
* Centers the Element in either the viewport, or another Element.
* @param {Mixed} centerIn (optional) The element in which to center the element.
*/
center : function(centerIn){
return this.alignTo(centerIn || Ext.getBody(this.getDocument()), 'c-c');
} ,
/**
* Looks at this node and then at parent nodes for a match of the passed simple selector (e.g. div.some-class or span:first-child)
* @param {String} selector The simple selector to test
* @param {Number/Mixed} maxDepth (optional) The max depth to search as a number or element (defaults to 50 || document.body)
* @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node
* @return {HTMLElement} The matching DOM node (or null if no match was found)
*/
findParent : function(simpleSelector, maxDepth, returnEl){
var p = this.dom,
D = this.getDocument(),
b = D.body,
depth = 0,
stopEl;
if(Ext.isGecko && OPString.call(p) == '[object XULElement]') {
return null;
}
maxDepth = maxDepth || 50;
if (isNaN(maxDepth)) {
stopEl = Ext.getDom(maxDepth, null, D);
maxDepth = Number.MAX_VALUE;
}
while(p && p.nodeType == 1 && depth < maxDepth && p != b && p != stopEl){
if(Ext.DomQuery.is(p, simpleSelector)){
return returnEl ? Ext.get(p, D) : p;
}
depth++;
p = p.parentNode;
}
return null;
},
/**
* Store the current overflow setting and clip overflow on the element - use <tt>{@link #unclip}</tt> to remove
* @return {Ext.Element} this
*/
clip : function(){
var me = this,
dom = me.dom;
if(!data(dom, ISCLIPPED)){
data(dom, ISCLIPPED, true);
data(dom, ORIGINALCLIP, {
o: me.getStyle(OVERFLOW),
x: me.getStyle(OVERFLOWX),
y: me.getStyle(OVERFLOWY)
});
me.setStyle(OVERFLOW, HIDDEN);
me.setStyle(OVERFLOWX, HIDDEN);
me.setStyle(OVERFLOWY, HIDDEN);
}
return me;
},
/**
* Return clipping (overflow) to original clipping before <tt>{@link #clip}</tt> was called
* @return {Ext.Element} this
*/
unclip : function(){
var me = this,
dom = me.dom;
if(data(dom, ISCLIPPED)){
data(dom, ISCLIPPED, false);
var o = data(dom, ORIGINALCLIP);
if(o.o){
me.setStyle(OVERFLOW, o.o);
}
if(o.x){
me.setStyle(OVERFLOWX, o.x);
}
if(o.y){
me.setStyle(OVERFLOWY, o.y);
}
}
return me;
},
getViewSize : function(){
var doc = this.getDocument(),
d = this.dom,
isDoc = (d == doc || d == doc.body);
// If the body, use Ext.lib.Dom
if (isDoc) {
var extdom = Ext.lib.Dom;
return {
width : extdom.getViewWidth(),
height : extdom.getViewHeight()
};
// Else use clientHeight/clientWidth
} else {
return {
width : d.clientWidth,
height : d.clientHeight
};
}
},
/**
* <p>Returns the dimensions of the element available to lay content out in.<p>
*
* getStyleSize utilizes prefers style sizing if present, otherwise it chooses the larger of offsetHeight/clientHeight and offsetWidth/clientWidth.
* To obtain the size excluding scrollbars, use getViewSize
*
* Sizing of the document body is handled at the adapter level which handles special cases for IE and strict modes, etc.
*/
getStyleSize : function(){
var me = this,
w, h,
doc = this.getDocument(),
d = this.dom,
isDoc = (d == doc || d == doc.body),
s = d.style;
// If the body, use Ext.lib.Dom
if (isDoc) {
var extdom = Ext.lib.Dom;
return {
width : extdom.getViewWidth(),
height : extdom.getViewHeight()
};
}
// Use Styles if they are set
if(s.width && s.width != 'auto'){
w = parseFloat(s.width);
if(me.isBorderBox()){
w -= me.getFrameWidth('lr');
}
}
// Use Styles if they are set
if(s.height && s.height != 'auto'){
h = parseFloat(s.height);
if(me.isBorderBox()){
h -= me.getFrameWidth('tb');
}
}
// Use getWidth/getHeight if style not set.
return {width: w || me.getWidth(true), height: h || me.getHeight(true)};
}
});
//Stop the existing collectorThread
Ext.isDefined(El.collectorThreadId) && clearInterval(El.collectorThreadId);
// private
// Garbage collection - uncache elements/purge listeners on orphaned elements
// so we don't hold a reference and cause the browser to retain them
function garbageCollect(){
if(!Ext.enableGarbageCollector){
clearInterval(El.collectorThreadId);
} else {
var eid,
el,
d,
o,
EC = Ext.elCache;
for(eid in EC){
o = EC[eid];
if(o.skipGC){
continue;
}
el = o.el;
d = el.dom;
// -------------------------------------------------------
// Determining what is garbage:
// -------------------------------------------------------
// !d
// dom node is null, definitely garbage
// -------------------------------------------------------
// !d.parentNode
// no parentNode == direct orphan, definitely garbage
// -------------------------------------------------------
// !d.offsetParent && !document.getElementById(eid)
// display none elements have no offsetParent so we will
// also try to look it up by it's id. However, check
// offsetParent first so we don't do unneeded lookups.
// This enables collection of elements that are not orphans
// directly, but somewhere up the line they have an orphan
// parent.
// -------------------------------------------------------
if(!d || !d.parentNode || (!d.offsetParent && !DOC.getElementById(eid))){
if(Ext.enableListenerCollection){
Ext.EventManager.removeAll(d);
}
delete EC[eid];
}
}
// Cleanup IE COM Object Hash reference leaks
if (Ext.isIE) {
var t = {};
for (eid in EC) {
t[eid] = EC[eid];
}
Ext.elCache = Ext._documents[Ext.id(document)] = t;
t = null;
}
}
}
//Restart if enabled
if(Ext.enableGarbageCollector){
El.collectorThreadId = setInterval(garbageCollect, 30000);
}
Ext.apply(ELD , {
/**
* Resolve the current document context of the passed Element
*/
getDocument : function(el, accessTest){
var dom= null;
try{
dom = Ext.getDom(el, null, null); //will fail if El.dom is non "same-origin" document
}catch(ex){}
var isDoc = Ext.isDocument(dom);
if(isDoc){
if(accessTest){
return Ext.isDocument(dom, accessTest) ? dom : null;
}
return dom;
}
return dom ?
dom.ownerDocument || //Element
dom.document //Window
: null;
},
/**
* Return the Compatability Mode of the passed document or Element
*/
docIsStrict : function(doc){
return (Ext.isDocument(doc) ? doc : this.getDocument(doc)).compatMode == "CSS1Compat";
},
getViewWidth : Ext.overload ([
ELD.getViewWidth || function(full){},
function() { return this.getViewWidth(false);},
function(full, doc) {
return full ? this.getDocumentWidth(doc) : this.getViewportWidth(doc);
}]
),
getViewHeight : Ext.overload ([
ELD.getViewHeight || function(full){},
function() { return this.getViewHeight(false);},
function(full, doc) {
return full ? this.getDocumentHeight(doc) : this.getViewportHeight(doc);
}]),
getDocumentHeight: Ext.overload([
ELD.getDocumentHeight || emptyFn,
function(doc) {
if(doc=this.getDocument(doc)){
return Math.max(
!this.docIsStrict(doc) ? doc.body.scrollHeight : doc.documentElement.scrollHeight
, this.getViewportHeight(doc)
);
}
return undefined;
}
]),
getDocumentWidth: Ext.overload([
ELD.getDocumentWidth || emptyFn,
function(doc) {
if(doc=this.getDocument(doc)){
return Math.max(
!this.docIsStrict(doc) ? doc.body.scrollWidth : doc.documentElement.scrollWidth
, this.getViewportWidth(doc)
);
}
return undefined;
}
]),
getViewportHeight: Ext.overload([
ELD.getViewportHeight || emptyFn,
function(doc){
if(doc=this.getDocument(doc)){
if(Ext.isIE){
return this.docIsStrict(doc) ? doc.documentElement.clientHeight : doc.body.clientHeight;
}else{
return doc.defaultView.innerHeight;
}
}
return undefined;
}
]),
getViewportWidth: Ext.overload([
ELD.getViewportWidth || emptyFn,
function(doc) {
if(doc=this.getDocument(doc)){
return !this.docIsStrict(doc) && !Ext.isOpera ? doc.body.clientWidth :
Ext.isIE ? doc.documentElement.clientWidth : doc.defaultView.innerWidth;
}
return undefined;
}
]),
getXY : Ext.overload([
ELD.getXY || emptyFn,
function(el, doc) {
el = Ext.getDom(el, null, doc);
var D= this.getDocument(el),
bd = D ? (D.body || D.documentElement): null;
if(!el || !bd || el == bd){ return [0, 0]; }
return this.getXY(el);
}
])
});
var GETDOC = ELD.getDocument,
flies = El._flyweights;
/**
* @private
* Add Ext.fly support for targeted document contexts
*/
Ext.fly = El.fly = function(el, named, doc){
var ret = null;
named = named || '_global';
if (el = Ext.getDom(el, null, doc)) {
(ret = flies[named] = (flies[named] || new El.Flyweight())).dom = el;
Ext.isDocument(el) && (ret._isDoc = true);
}
return ret;
};
var flyFn = function(){};
flyFn.prototype = El.prototype;
// dom is optional
El.Flyweight = function(dom){
this.dom = dom;
};
El.Flyweight.prototype = new flyFn();
El.Flyweight.prototype.isFlyweight = true;
function addListener(el, ename, fn, task, wrap, scope){
el = Ext.getDom(el);
if(!el){ return; }
var id = Ext.id(el),
cache = resolveCache(el);
cache[id] || El.addToCache(el, id, cache);
var es = cache[id].events || {}, wfn;
wfn = E.on(el, ename, wrap);
es[ename] = es[ename] || [];
es[ename].push([fn, wrap, scope, wfn, task]);
// this is a workaround for jQuery and should somehow be removed from Ext Core in the future
// without breaking ExtJS.
if(el.addEventListener && ename == "mousewheel" ){
var args = ["DOMMouseScroll", wrap, false];
el.addEventListener.apply(el, args);
Ext.EventManager.addListener(window, 'beforeunload', function(){
el.removeEventListener.apply(el, args);
});
}
if(ename == "mousedown" && DOC == el){ // fix stopped mousedowns on the document
Ext.EventManager.stoppedMouseDownEvent.addListener(wrap);
}
};
function createTargeted(h, o){
return function(){
var args = Ext.toArray(arguments);
if(o.target == Ext.EventObject.setEvent(args[0]).target){
h.apply(this, args);
}
};
};
function createBuffered(h, o, task){
return function(e){
// create new event object impl so new events don't wipe out properties
task.delay(o.buffer, h, null, [new Ext.EventObjectImpl(e)]);
};
};
function createSingle(h, el, ename, fn, scope){
return function(e){
Ext.EventManager.removeListener(el, ename, fn, scope);
h(e);
};
};
function createDelayed(h, o, fn){
return function(e){
var task = new Ext.util.DelayedTask(h);
(fn.tasks || (fn.tasks = [])).push(task);
task.delay(o.delay || 10, h, null, [new Ext.EventObjectImpl(e)]);
};
};
function listen(element, ename, opt, fn, scope){
var o = !Ext.isObject(opt) ? {} : opt,
el = Ext.getDom(element), task;
fn = fn || o.fn;
scope = scope || o.scope;
if(!el){
throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
}
function h(e){
// prevent errors while unload occurring
if(!window.Ext){ return; }
e = Ext.EventObject.setEvent(e);
var t;
if (o.delegate) {
if(!(t = e.getTarget(o.delegate, el))){
return;
}
} else {
t = e.target;
}
if (o.stopEvent) {
e.stopEvent();
}
if (o.preventDefault) {
e.preventDefault();
}
if (o.stopPropagation) {
e.stopPropagation();
}
if (o.normalized) {
e = e.browserEvent;
}
fn.call(scope || el, e, t, o);
};
if(o.target){
h = createTargeted(h, o);
}
if(o.delay){
h = createDelayed(h, o, fn);
}
if(o.single){
h = createSingle(h, el, ename, fn, scope);
}
if(o.buffer){
task = new Ext.util.DelayedTask(h);
h = createBuffered(h, o, task);
}
addListener(el, ename, fn, task, h, scope);
return h;
};
Ext.apply(Evm ,{
addListener : Evm.on = function(element, eventName, fn, scope, options){
if(typeof eventName == 'object'){
var o = eventName, e, val;
for(e in o){
val = o[e];
if(!propRe.test(e)){
if(Ext.isFunction(val)){
// shared options
listen(element, e, o, val, o.scope);
}else{
// individual options
listen(element, e, val);
}
}
}
} else {
listen(element, eventName, options, fn, scope);
}
},
/**
* Removes an event handler from an element. The shorthand version {@link #un} is equivalent. Typically
* you will use {@link Ext.Element#removeListener} directly on an Element in favor of calling this version.
* @param {String/HTMLElement} el The id or html element from which to remove the listener.
* @param {String} eventName The name of the event.
* @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b>
* @param {Object} scope If a scope (<b><code>this</code></b> reference) was specified when the listener was added,
* then this must refer to the same object.
*/
removeListener : Evm.un = function(element, eventName, fn, scope){
var el = Ext.getDom(element);
el && Ext.get(el);
var elCache = el ? resolveCache(el) : {},
f = el && ((elCache[el.id]||{events:{}}).events)[eventName] || [],
wrap, i, l, k, len, fnc;
for (i = 0, len = f.length; i < len; i++) {
/* 0 = Original Function,
1 = Event Manager Wrapped Function,
2 = Scope,
3 = Adapter Wrapped Function,
4 = Buffered Task
*/
if (Ext.isArray(fnc = f[i]) && fnc[0] == fn && (!scope || fnc[2] == scope)) {
fnc[4] && fnc[4].cancel();
k = fn.tasks && fn.tasks.length;
if(k) {
while(k--) {
fn.tasks[k].cancel();
}
delete fn.tasks;
}
wrap = fnc[1];
E.un(el, eventName, E.extAdapter ? fnc[3] : wrap);
// jQuery workaround that should be removed from Ext Core
if(wrap && eventName == "mousewheel" && el.addEventListener ){
el.removeEventListener("DOMMouseScroll", wrap, false);
}
if(wrap && eventName == "mousedown" && DOC == el){ // fix stopped mousedowns on the document
Ext.EventManager.stoppedMouseDownEvent.removeListener(wrap);
}
f.splice(i,1);
if (f.length === 0) {
delete elCache[el.id].events[eventName];
}
for (k in elCache[el.id].events) {
return false;
}
elCache[el.id].events = {};
return false;
}
}
},
/**
* Removes all event handers from an element. Typically you will use {@link Ext.Element#removeAllListeners}
* directly on an Element in favor of calling this version.
* @param {String/HTMLElement} el The id or html element from which to remove all event handlers.
*/
removeAll : function(el){
if (!(el = Ext.getDom(el))) {
return;
}
var id = el.id,
elCache = resolveCache(el)||{},
es = elCache[id] || {},
ev = es.events || {},
f, i, len, ename, fn, k, wrap;
for(ename in ev){
if(ev.hasOwnProperty(ename)){
f = ev[ename];
/* 0 = Original Function,
1 = Event Manager Wrapped Function,
2 = Scope,
3 = Adapter Wrapped Function,
4 = Buffered Task
*/
for (i = 0, len = f.length; i < len; i++) {
fn = f[i];
fn[4] && fn[4].cancel();
if(fn[0].tasks && (k = fn[0].tasks.length)) {
while(k--) {
fn[0].tasks[k].cancel();
}
delete fn.tasks;
}
wrap = fn[1];
E.un(el, ename, E.extAdapter ? fn[3] : wrap);
// jQuery workaround that should be removed from Ext Core
if(wrap && el.addEventListener && ename == "mousewheel"){
el.removeEventListener("DOMMouseScroll", wrap, false);
}
// fix stopped mousedowns on the document
if(wrap && DOC == el && ename == "mousedown"){
Ext.EventManager.stoppedMouseDownEvent.removeListener(wrap);
}
}
}
}
elCache[id] && (elCache[id].events = {});
},
getListeners : function(el, eventName) {
el = Ext.getDom(el);
if (!el) {
return;
}
var id = (Ext.get(el)||{}).id,
elCache = resolveCache(el),
es = ( elCache[id] || {} ).events || {};
return es[eventName] || null;
},
purgeElement : function(el, recurse, eventName) {
el = Ext.getDom(el);
var id = Ext.id(el),
elCache = resolveCache(el),
es = (elCache[id] || {}).events || {},
i, f, len;
if (eventName) {
if (es.hasOwnProperty(eventName)) {
f = es[eventName];
for (i = 0, len = f.length; i < len; i++) {
Evm.removeListener(el, eventName, f[i][0]);
}
}
} else {
Evm.removeAll(el);
}
if (recurse && el && el.childNodes) {
for (i = 0, len = el.childNodes.length; i < len; i++) {
Evm.purgeElement(el.childNodes[i], recurse, eventName);
}
}
}
});
// deprecated, call from EventManager
E.getListeners = function(el, eventName) {
return Ext.EventManager.getListeners(el, eventName);
};
/** @sourceURL=<multidom.js> */
Ext.provide && Ext.provide('multidom');
})();/* global Ext */
/*
* Copyright 2007-2010, Active Group, Inc. All rights reserved.
* ******************************************************************************
* This file is distributed on an AS IS BASIS WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* ***********************************************************************************
* @version 2.1.3
* [For Ext 3.1.1 or higher only]
*
* License: ux.ManagedIFrame, ux.ManagedIFrame.Panel, ux.ManagedIFrame.Portlet, ux.ManagedIFrame.Window
* are licensed under the terms of the Open Source GPL 3.0 license:
* http://www.gnu.org/licenses/gpl.html
*
* Commercial use is prohibited without a Commercial Developement License. See
* http://licensing.theactivegroup.com.
*
* Donations are welcomed: http://donate.theactivegroup.com
*
*/
(function(){
var El = Ext.Element,
ElFrame,
ELD = Ext.lib.Dom,
EMPTYFN = function(){},
OP = Object.prototype,
addListener = function () {
var handler;
if (window.addEventListener) {
handler = function F(el, eventName, fn, capture) {
el.addEventListener(eventName, fn, !!capture);
};
} else if (window.attachEvent) {
handler = function F(el, eventName, fn, capture) {
el.attachEvent("on" + eventName, fn);
};
} else {
handler = function F(){};
}
var F = null; //Gbg collect
return handler;
}(),
removeListener = function() {
var handler;
if (window.removeEventListener) {
handler = function F(el, eventName, fn, capture) {
el.removeEventListener(eventName, fn, (capture));
};
} else if (window.detachEvent) {
handler = function F(el, eventName, fn) {
el.detachEvent("on" + eventName, fn);
};
} else {
handler = function F(){};
}
var F = null; //Gbg collect
return handler;
}();
//assert multidom support: REQUIRED for Ext 3 or higher!
if(typeof ELD.getDocument != 'function'){
alert("MIF 2.1 requires multidom support" );
}
//assert Ext 3.1.1+
if(!Ext.elCache || parseInt( Ext.version.replace(/\./g,''),10) < 311 ) {
alert ('Ext Release '+Ext.version+' is not supported');
}
Ext.ns('Ext.ux.ManagedIFrame', 'Ext.ux.plugin');
var MIM, MIF = Ext.ux.ManagedIFrame, MIFC;
var frameEvents = ['documentloaded',
'domready',
'focus',
'blur',
'resize',
'scroll',
'unload',
'scroll',
'exception',
'message',
'reset'];
var reSynthEvents = new RegExp('^('+frameEvents.join('|')+ ')', 'i');
/**
* @class Ext.ux.ManagedIFrame.Element
* @extends Ext.Element
* @version 2.1.3
* @license <a href="http://www.gnu.org/licenses/gpl.html">GPL 3.0</a>
* @author Doug Hendricks. Forum ID: <a href="http://extjs.com/forum/member.php?u=8730">hendricd</a>
* @donate <a target="tag_donate" href="http://donate.theactivegroup.com"><img border="0" src="http://www.paypal.com/en_US/i/btn/x-click-butcc-donate.gif" border="0" alt="Make a donation to support ongoing development"></a>
* @copyright 2007-2010, Active Group, Inc. All rights reserved.
* @constructor Create a new Ext.ux.ManagedIFrame.Element directly.
* @param {String/HTMLElement} element
* @param {Boolean} forceNew (optional) By default the constructor checks to see if there is already an instance of this element in the cache and if there is it returns the same instance. This will skip that check (useful for extending this class).
* @param {DocumentElement} (optional) Document context uses to resolve an Element search by its id.
*/
Ext.ux.ManagedIFrame.Element = Ext.extend(Ext.Element, {
constructor : function(element, forceNew, doc ){
var d = doc || document,
elCache = ELD.resolveDocumentCache(d),
dom = Ext.getDom(element, false, d);
if(!dom || !(/^(iframe|frame)/i).test(dom.tagName)) { // invalid id/element
return null;
}
var id = Ext.id(dom);
/**
* The DOM element
* @type HTMLElement
*/
this.dom = dom;
/**
* The DOM element ID
* @type String
*/
this.id = id ;
(elCache[id] ||
(elCache[id] = {
el: this,
events : {},
data : {}
})
).el = this;
this.dom.name || (this.dom.name = this.id);
if(Ext.isIE){
document.frames && (document.frames[this.dom.name] || (document.frames[this.dom.name] = this.dom));
}
this.dom.ownerCt = this;
MIM.register(this);
if(!this._observable){
(this._observable = new Ext.util.Observable()).addEvents(
/**
* Fires when the iFrame has reached a loaded/complete state.
* @event documentloaded
* @param {Ext.ux.MIF.Element} this
*/
'documentloaded',
/**
* Fires ONLY when an iFrame's Document(DOM) has reach a
* state where the DOM may be manipulated ('same origin' policy)
* Note: This event is only available when overwriting the iframe
* document using the update or load methods and "same-origin"
* documents. Returning false from the eventHandler stops further event
* (documentloaded) processing.
* @event domready
* @param {Ext.ux.MIF.Element} this
*/
'domready',
/**
* Fires when the frame actions raise an error
* @event exception
* @param {Ext.ux.MIF.Element} this.iframe
* @param {Error/string} exception
*/
'exception',
/**
* Fires when the frame's window is resized. This event, when raised from a "same-origin" frame,
* will send current height/width reports with the event.
* @event resize
* @param {Ext.ux.MIF.Element} this.iframe
* @param {Object} documentSize A height/width object signifying the new document size
* @param {Object} viewPortSize A height/width object signifying the size of the frame's viewport
* @param {Object} viewSize A height/width object signifying the size of the frame's view
*/
'resize',
/**
* Fires upon receipt of a message generated by window.sendMessage
* method of the embedded Iframe.window object
* @event message
* @param {Ext.ux.MIF} this.iframe
* @param {object}
* message (members: type: {string} literal "message", data
* {Mixed} [the message payload], domain [the document domain
* from which the message originated ], uri {string} the
* document URI of the message sender source (Object) the
* window context of the message sender tag {string} optional
* reference tag sent by the message sender
* <p>Alternate event handler syntax for message:tag filtering Fires upon
* receipt of a message generated by window.sendMessage method which
* includes a specific tag value of the embedded Iframe.window object
*/
'message',
/**
* Fires when the frame is blurred (loses focus).
* @event blur
* @param {Ext.ux.MIF} this
* @param {Ext.Event}
* Note: This event is only available when overwriting the
* iframe document using the update method and to pages
* retrieved from a "same domain". Returning false from the
* eventHandler [MAY] NOT cancel the event, as this event is
* NOT ALWAYS cancellable in all browsers.
*/
'blur',
/**
* Fires when the frame gets focus. Note: This event is only available
* when overwriting the iframe document using the update method and to
* pages retrieved from a "same domain". Returning false from the
* eventHandler [MAY] NOT cancel the event, as this event is NOT ALWAYS
* cancellable in all browsers.
* @event focus
* @param {Ext.ux.MIF.Element} this
* @param {Ext.Event}
*
*/
'focus',
/**
* Note: This event is only available when overwriting the iframe
* document using the update method and to pages retrieved from a "same-origin"
* domain. Note: Opera does not raise this event.
* @event unload * Fires when(if) the frames window object raises the unload event
* @param {Ext.ux.MIF.Element} this.
* @param {Ext.Event}
*/
'unload',
/**
* Note: This event is only available when overwriting the iframe
* document using the update method and to pages retrieved from a "same-origin"
* domain. To prevent numerous scroll events from being raised use the buffer listener
* option to limit the number of times the event is raised.
* @event scroll
* @param {Ext.ux.MIF.Element} this.
* @param {Ext.Event}
*/
'scroll',
/**
* Fires when the iFrame has been reset to a neutral domain state (blank document).
* @event reset
* @param {Ext.ux.MIF.Element} this
*/
'reset'
);
// Private internal document state events.
this._observable.addEvents('_docready','_docload');
}
var H = Ext.isIE?'onreadystatechange':'onload';
// Hook the Iframes loaded and error state handlers
this.dom[H] = this.loadHandler.createDelegate(this);
this.dom['onerror'] = this.loadHandler.createDelegate(this);
},
/** @private
* Removes the MIFElement interface from the FRAME Element.
* It does NOT remove the managed FRAME from the DOM. Use the {@link Ext.#ux.ManagedIFrame.Element-remove} method to perfom both functions.
*/
destructor : function () {
this.dom[Ext.isIE?'onreadystatechange':'onload'] = this.dom['onerror'] = EMPTYFN;
MIM.deRegister(this);
this.removeAllListeners();
Ext.destroy(this.frameShim, this.DDM);
this.hideMask(true);
delete this.loadMask;
this.reset();
this.manager = null;
this.dom.ownerCt = null;
},
/**
* Deep cleansing childNode Removal
* @param {Boolean} forceReclean (optional) By default the element
* keeps track if it has been cleansed already so
* you can call this over and over. However, if you update the element and
* need to force a reclean, you can pass true.
* @param {Boolean} deep (optional) Perform a deep cleanse of all childNodes as well.
*/
cleanse : function(forceReclean, deep){
if(this.isCleansed && forceReclean !== true){
return this;
}
var d = this.dom, n = d.firstChild, nx;
while(d && n){
nx = n.nextSibling;
deep && Ext.fly(n).cleanse(forceReclean, deep);
Ext.removeNode(n);
n = nx;
}
this.isCleansed = true;
return this;
},
/** (read-only) The last known URI set programmatically by the Component
* @property
* @type {String|Function}
*/
src : null,
/** (read-only) For "same-origin" frames only. Provides a reference to
* the Ext.util.CSS singleton to manipulate the style sheets of the frame's
* embedded document.
*
* @property
* @type Ext.util.CSS
*/
CSS : null,
/** Provides a reference to the managing Ext.ux.MIF.Manager instance.
*
* @property
* @type Ext.ux.MIF.Manager
*/
manager : null,
/**
* @cfg {Boolean} disableMessaging False to enable cross-frame messaging API
* @default true
*
*/
disableMessaging : true,
/**
* @cfg {Integer} domReadyRetries
* Maximum number of domready event detection retries for IE. IE does not provide
* a native DOM event to signal when the frames DOM may be manipulated, so a polling process
* is used to determine when the documents BODY is available. <p> Certain documents may not contain
* a BODY tag: eg. MHT(rfc/822), XML, or other non-HTML content. Detection polling will stop after this number of 2ms retries
* or when the documentloaded event is raised.</p>
* @default 7500 (* 2 = 15 seconds)
*/
domReadyRetries : 7500,
/**
* True to set focus on the frame Window as soon as its document
* reports loaded. <p>(Many external sites use IE's document.createRange to create
* DOM elements, but to be successful, IE requires that the FRAME have focus before
* such methods are called)</p>
* @cfg focusOnLoad
* @default true if IE
*/
focusOnLoad : Ext.isIE,
/**
* Toggles raising of events for URL actions that the Component did not initiate.
* @cfg {Boolean} eventsFollowFrameLinks set true to propogate domready and documentloaded
* events anytime the IFRAME's URL changes
* @default true
*/
eventsFollowFrameLinks : true,
/**
* Removes the FRAME from the DOM and deletes it from the cache
*/
remove : function(){
this.destructor.apply(this, arguments);
ElFrame.superclass.remove.apply(this,arguments);
},
/**
* Return the ownerDocument property of the IFRAME Element.
* (Note: This is not the document context of the FRAME's loaded document.
* See the getFrameDocument method for that.)
*/
getDocument :
function(){ return this.dom ? this.dom.ownerDocument : document;},
/**
* Loads the frame Element with the response from a form submit to the
* specified URL with the ManagedIframe.Element as it's submit target.
*
* @param {Object} submitCfg A config object containing any of the following options:
* <pre><code>
* myIframe.submitAsTarget({
* form : formPanel.form, //optional Ext.FormPanel, Ext form element, or HTMLFormElement
* url: "your-url.php",
* action : (see url) ,
* params: {param1: "foo", param2: "bar"}, // or URL encoded string or function that returns either
* callback: yourFunction, //optional, called with the signature (frame)
* scope: yourObject, // optional scope for the callback
* method: 'POST', //optional form.method
* encoding : "multipart/form-data" //optional, default = HTMLForm default
* });
*
* </code></pre>
* @return {Ext.ux.ManagedIFrame.Element} this
*
*/
submitAsTarget : function(submitCfg){
var opt = submitCfg || {},
D = this.getDocument(),
form = Ext.getDom(
opt.form ? opt.form.form || opt.form: null, false, D) ||
Ext.DomHelper.append(D.body, {
tag: 'form',
cls : 'x-hidden x-mif-form',
encoding : 'multipart/form-data'
}),
formFly = Ext.fly(form, '_dynaForm'),
formState = {
target: form.target || '',
method: form.method || '',
encoding: form.encoding || '',
enctype: form.enctype || '',
action: form.action || ''
},
encoding = opt.encoding || form.encoding,
method = opt.method || form.method || 'POST';
formFly.set({
target : this.dom.name,
method : method,
encoding: encoding,
action : opt.url || opt.action || form.action
});
if(method == 'POST' || !!opt.enctype){
formFly.set({enctype : opt.enctype || form.enctype || encoding});
}
var hiddens, hd, ps;
// add any additional dynamic params
if(opt.params && (ps = Ext.isFunction(opt.params) ? opt.params() : opt.params)){
hiddens = [];
Ext.iterate(ps = typeof ps == 'string'? Ext.urlDecode(ps, false): ps,
function(n, v){
Ext.fly(hd = D.createElement('input')).set({
type : 'hidden',
name : n,
value: v
});
form.appendChild(hd);
hiddens.push(hd);
});
}
opt.callback &&
this._observable.addListener('_docready',opt.callback, opt.scope,{single:true});
this._frameAction = true;
this._targetURI = location.href;
this.showMask();
//slight delay for masking
(function(){
form.submit();
// remove dynamic inputs
hiddens && Ext.each(hiddens, Ext.removeNode, Ext);
//Remove if dynamically generated, restore state otherwise
if(formFly.hasClass('x-mif-form')){
formFly.remove();
}else{
formFly.set(formState);
}
delete El._flyweights['_dynaForm'];
formFly = null;
this.hideMask(true);
}).defer(100, this);
return this;
},
/**
* @cfg {String} resetUrl Frame document reset string for use with the {@link #Ext.ux.ManagedIFrame.Element-reset} method.
* Defaults:<p> For IE on SSL domains - the current value of Ext.SSL_SECURE_URL<p> "about:blank" for all others.
*/
resetUrl : (function(){
return Ext.isIE && Ext.isSecure ? Ext.SSL_SECURE_URL : 'about:blank';
})(),
/**
* Sets the embedded Iframe src property. Note: invoke the function with
* no arguments to refresh the iframe based on the current src value.
*
* @param {String/Function} url (Optional) A string or reference to a Function that
* returns a URI string when called
* @param {Boolean} discardUrl (Optional) If not passed as <tt>false</tt>
* the URL of this action becomes the default SRC attribute
* for this iframe, and will be subsequently used in future
* setSrc calls (emulates autoRefresh by calling setSrc
* without params).
* @param {Function} callback (Optional) A callback function invoked when the
* frame document has been fully loaded.
* @param {Object} scope (Optional) scope by which the callback function is
* invoked.
*/
setSrc : function(url, discardUrl, callback, scope) {
var src = url || this.src || this.resetUrl;
var O = this._observable;
this._unHook();
Ext.isFunction(callback) && O.addListener('_docload', callback, scope||this, {single:true});
this.showMask();
(discardUrl !== true) && (this.src = src);
var s = this._targetURI = (Ext.isFunction(src) ? src() || '' : src);
try {
this._frameAction = true; // signal listening now
this.dom.src = s;
this.checkDOM();
} catch (ex) {
O.fireEvent.call(O, 'exception', this, ex);
}
return this;
},
/**
* Sets the embedded Iframe location using its replace method (precluding a history update).
* Note: invoke the function with no arguments to refresh the iframe based on the current src value.
*
* @param {String/Function} url (Optional) A string or reference to a Function that
* returns a URI string when called
* @param {Boolean} discardUrl (Optional) If not passed as <tt>false</tt>
* the URL of this action becomes the default SRC attribute
* for this iframe, and will be subsequently used in future
* setSrc calls (emulates autoRefresh by calling setSrc
* without params).
* @param {Function} callback (Optional) A callback function invoked when the
* frame document has been fully loaded.
* @param {Object} scope (Optional) scope by which the callback function is
* invoked.
*
*/
setLocation : function(url, discardUrl, callback, scope) {
var src = url || this.src || this.resetUrl;
var O = this._observable;
this._unHook();
Ext.isFunction(callback) && O.addListener('_docload', callback, scope||this, {single:true});
this.showMask();
var s = this._targetURI = (Ext.isFunction(src) ? src() || '' : src);
if (discardUrl !== true) {
this.src = src;
}
try {
this._frameAction = true; // signal listening now
this.getWindow().location.replace(s);
this.checkDOM();
} catch (ex) {
O.fireEvent.call(O,'exception', this, ex);
}
return this;
},
/**
* Resets the frame to a neutral (blank document) state without
* loadMasking.
*
* @param {String}
* src (Optional) A specific reset string (eg. 'about:blank')
* to use for resetting the frame.
* @param {Function}
* callback (Optional) A callback function invoked when the
* frame reset is complete.
* @param {Object}
* scope (Optional) scope by which the callback function is
* invoked.
*/
reset : function(src, callback, scope) {
this._unHook();
var loadMaskOff = false,
s = src,
win = this.getWindow(),
O = this._observable;
if(this.loadMask){
loadMaskOff = this.loadMask.disabled;
this.loadMask.disabled = false;
}
this.hideMask(true);
if(win){
this.isReset= true;
var cb = callback;
O.addListener('_docload',
function(frame) {
if(this.loadMask){
this.loadMask.disabled = loadMaskOff;
};
Ext.isFunction(cb) && (cb = cb.apply(scope || this, arguments));
O.fireEvent("reset", this);
}, this, {single:true});
Ext.isFunction(s) && ( s = src());
s = this._targetURI = Ext.isEmpty(s, true)? this.resetUrl: s;
win.location ? (win.location.href = s) : O.fireEvent('_docload', this);
}
return this;
},
/**
* @private
* Regular Expression filter pattern for script tag removal.
* @cfg {regexp} scriptRE script removal RegeXp
* Default: "/(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/gi"
*/
scriptRE : /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/gi,
/**
* Write(replacing) string content into the IFrames document structure
* @param {String} content The new content
* @param {Boolean} loadScripts
* (optional) true to also render and process embedded scripts
* @param {Function} callback (Optional) A callback function invoked when the
* frame document has been written and fully loaded. @param {Object}
* scope (Optional) scope by which the callback function is invoked.
*/
update : function(content, loadScripts, callback, scope) {
loadScripts = loadScripts || this.getUpdater().loadScripts || false;
content = Ext.DomHelper.markup(content || '');
content = loadScripts === true ? content : content.replace(this.scriptRE, "");
var doc;
if ((doc = this.getFrameDocument()) && !!content.length) {
this._unHook();
this.src = null;
this.showMask();
Ext.isFunction(callback) &&
this._observable.addListener('_docload', callback, scope||this, {single:true});
this._targetURI = location.href;
doc.open();
this._frameAction = true;
doc.write(content);
doc.close();
this.checkDOM();
} else {
this.hideMask(true);
Ext.isFunction(callback) && callback.call(scope, this);
}
return this;
},
/**
* Executes a Midas command on the current document, current selection, or the given range.
* @param {String} command The command string to execute in the frame's document context.
* @param {Booloean} userInterface (optional) True to enable user interface (if supported by the command)
* @param {Mixed} value (optional)
* @param {Boolean} validate If true, the command is validated to ensure it's invocation is permitted.
* @return {Boolean} indication whether command execution succeeded
*/
execCommand : function(command, userInterface, value, validate){
var doc, assert;
if ((doc = this.getFrameDocument()) && !!command) {
try{
Ext.isIE && this.getWindow().focus();
assert = validate && Ext.isFunction(doc.queryCommandEnabled) ?
doc.queryCommandEnabled(command) : true;
return assert && doc.execCommand(command, !!userInterface, value);
}catch(eex){return false;}
}
return false;
},
/**
* Sets the current DesignMode attribute of the Frame's document
* @param {Boolean/String} active True (or "on"), to enable designMode
*
*/
setDesignMode : function(active){
var doc;
(doc = this.getFrameDocument()) &&
(doc.designMode = (/on|true/i).test(String(active))?'on':'off');
},
/**
* Gets this element's Updater
*
* @return {Ext.ux.ManagedIFrame.Updater} The Updater
*/
getUpdater : function(){
return this.updateManager ||
(this.updateManager = new MIF.Updater(this));
},
/**
* Method to retrieve frame's history object.
* @return {object} or null if permission was denied
*/
getHistory : function(){
var h=null;
try{ h=this.getWindow().history; }catch(eh){}
return h;
},
/**
* Method to retrieve embedded frame Element objects. Uses simple
* caching (per frame) to consistently return the same object.
* Automatically fixes if an object was recreated with the same id via
* AJAX or DOM.
*
* @param {Mixed}
* el The id of the node, a DOM Node or an existing Element.
* @return {Element} The Element object (or null if no matching element
* was found)
*/
get : function(el) {
var doc = this.getFrameDocument();
return doc? Ext.get(el, doc) : doc=null;
},
/**
* Gets the globally shared flyweight Element for the frame, with the
* passed node as the active element. Do not store a reference to this
* element - the dom node can be overwritten by other code.
*
* @param {String/HTMLElement}
* el The dom node or id
* @param {String}
* named (optional) Allows for creation of named reusable
* flyweights to prevent conflicts (e.g. internally Ext uses
* "_internal")
* @return {Element} The shared Element object (or null if no matching
* element was found)
*/
fly : function(el, named) {
var doc = this.getFrameDocument();
return doc ? Ext.fly(el, named, doc) : null;
},
/**
* Return the dom node for the passed string (id), dom node, or
* Ext.Element relative to the embedded frame document context.
*
* @param {Mixed} el
* @return HTMLElement
*/
getDom : function(el) {
var d;
if (!el || !(d = this.getFrameDocument())) {
return (d=null);
}
return Ext.getDom(el, d);
},
/**
* Creates a {@link Ext.CompositeElement} for child nodes based on the
* passed CSS selector (the selector should not contain an id).
*
* @param {String} selector The CSS selector
* @param {Boolean} unique (optional) True to create a unique Ext.Element for
* each child (defaults to false, which creates a single
* shared flyweight object)
* @return {Ext.CompositeElement/Ext.CompositeElementLite} The composite element
*/
select : function(selector, unique) {
var d; return (d = this.getFrameDocument()) ? Ext.Element.select(selector,unique, d) : d=null;
},
/**
* Selects frame document child nodes based on the passed CSS selector
* (the selector should not contain an id).
*
* @param {String} selector The CSS selector
* @return {Array} An array of the matched nodes
*/
query : function(selector) {
var d; return (d = this.getFrameDocument()) ? Ext.DomQuery.select(selector, d): null;
},
/**
* Removes a DOM Element from the embedded document
* @param {Element/String} node The node id or node Element to remove
*/
removeNode : Ext.removeNode,
/**
* @private execScript sandbox and messaging interface
*/
_renderHook : function() {
this._windowContext = null;
this.CSS = this.CSS ? this.CSS.destroy() : null;
this._hooked = false;
try {
if (this.writeScript('(function(){(window.hostMIF = parent.document.getElementById("'
+ this.id
+ '").ownerCt)._windowContext='
+ (Ext.isIE
? 'window'
: '{eval:function(s){return new Function("return ("+s+")")();}}')
+ ';})()')) {
var w, p = this._frameProxy, D = this.getFrameDocument();
if(w = this.getWindow()){
p || (p = this._frameProxy = this._eventProxy.createDelegate(this));
addListener(w, 'focus', p);
addListener(w, 'blur', p);
addListener(w, 'resize', p);
addListener(w, 'unload', p);
D && addListener(Ext.isIE ? w : D, 'scroll', p);
}
D && (this.CSS = new Ext.ux.ManagedIFrame.CSS(D));
}
} catch (ex) {}
return this.domWritable();
},
/** @private : clear all event listeners and Element cache */
_unHook : function() {
if (this._hooked) {
this._windowContext && (this._windowContext.hostMIF = null);
this._windowContext = null;
var w, p = this._frameProxy;
if(p && this.domWritable() && (w = this.getWindow())){
removeListener(w, 'focus', p);
removeListener(w, 'blur', p);
removeListener(w, 'resize', p);
removeListener(w, 'unload', p);
removeListener(Ext.isIE ? w : this.getFrameDocument(), 'scroll', p);
}
}
ELD.clearDocumentCache && ELD.clearDocumentCache(this.id);
this.CSS = this.CSS ? this.CSS.destroy() : null;
this.domFired = this._frameAction = this.domReady = this._hooked = false;
},
/** @private */
_windowContext : null,
/**
* If sufficient privilege exists, returns the frame's current document
* as an HTMLElement.
*
* @return {HTMLElement} The frame document or false if access to document object was denied.
*/
getFrameDocument : function() {
var win = this.getWindow(), doc = null;
try {
doc = (Ext.isIE && win ? win.document : null)
|| this.dom.contentDocument
|| window.frames[this.dom.name].document || null;
} catch (gdEx) {
ELD.clearDocumentCache && ELD.clearDocumentCache(this.id);
return false; // signifies probable access restriction
}
doc = (doc && Ext.isFunction(ELD.getDocument)) ? ELD.getDocument(doc,true) : doc;
return doc;
},
/**
* Returns the frame's current HTML document object as an
* {@link Ext.Element}.
* @return {Ext.Element} The document
*/
getDoc : function() {
var D = this.getFrameDocument();
return Ext.get(D,D);
},
/**
* If sufficient privilege exists, returns the frame's current document
* body as an HTMLElement.
*
* @return {HTMLElement} The frame document body or Null if access to
* document object was denied.
*/
getBody : function() {
var d;
return (d = this.getFrameDocument()) ? this.get(d.body || d.documentElement) : null;
},
/**
* Attempt to retrieve the frames current URI via frame's document object
* @return {string} The frame document's current URI or the last know URI if permission was denied.
*/
getDocumentURI : function() {
var URI, d;
try {
URI = this.src && (d = this.getFrameDocument()) ? d.location.href: null;
} catch (ex) { // will fail on NON-same-origin domains
}
return URI || (Ext.isFunction(this.src) ? this.src() : this.src);
// fallback to last known
},
/**
* Attempt to retrieve the frames current URI via frame's Window object
* @return {string} The frame document's current URI or the last know URI if permission was denied.
*/
getWindowURI : function() {
var URI, w;
try {
URI = (w = this.getWindow()) ? w.location.href : null;
} catch (ex) {
} // will fail on NON-same-origin domains
return URI || (Ext.isFunction(this.src) ? this.src() : this.src);
// fallback to last known
},
/**
* Returns the frame's current window object.
*
* @return {Window} The frame Window object.
*/
getWindow : function() {
var dom = this.dom, win = null;
try {
win = dom.contentWindow || window.frames[dom.name] || null;
} catch (gwEx) {}
return win;
},
/**
* Scrolls a frame document's child element into view within the passed container.
* @param {String} child The id of the element to scroll into view.
* @param {Mixed} container (optional) The container element to scroll (defaults to the frame's document.body). Should be a
* string (id), dom node, or Ext.Element.
* @param {Boolean} hscroll (optional) False to disable horizontal scroll (defaults to true)
* @return {Ext.ux.ManagedIFrame.Element} this
*/
scrollChildIntoView : function(child, container, hscroll){
this.fly(child, '_scrollChildIntoView').scrollIntoView(this.getDom(container) || this.getBody().dom, hscroll);
return this;
},
/**
* Print the contents of the Iframes (if we own the document)
* @return {Ext.ux.ManagedIFrame.Element} this
*/
print : function() {
try {
var win;
if( win = this.getWindow()){
Ext.isIE && win.focus();
win.print();
}
} catch (ex) {
throw new MIF.Error('printexception' , ex.description || ex.message || ex);
}
return this;
},
/**
* Returns the general DOM modification capability (same-origin status) of the frame.
* @return {Boolean} accessible If True, the frame's inner DOM can be manipulated, queried, and
* Event Listeners set.
*/
domWritable : function() {
return !!Ext.isDocument(this.getFrameDocument(),true) //test access
&& !!this._windowContext;
},
/**
* eval a javascript code block(string) within the context of the
* Iframes' window object.
* @param {String} block A valid ('eval'able) script source block.
* @param {Boolean} useDOM if true, inserts the function
* into a dynamic script tag, false does a simple eval on the function
* definition. (useful for debugging) <p> Note: will only work after a
* successful iframe.(Updater) update or after same-domain document has
* been hooked, otherwise an exception is raised.
* @return {Mixed}
*/
execScript : function(block, useDOM) {
try {
if (this.domWritable()) {
if (useDOM) {
this.writeScript(block);
} else {
return this._windowContext.eval(block);
}
} else {
throw new MIF.Error('execscript-secure-context');
}
} catch (ex) {
this._observable.fireEvent.call(this._observable,'exception', this, ex);
return false;
}
return true;
},
/**
* Write a script block into the iframe's document
* @param {String} block A valid (executable) script source block.
* @param {object} attributes Additional Script tag attributes to apply to the script
* Element (for other language specs [vbscript, Javascript] etc.) <p>
* Note: writeScript will only work after a successful iframe.(Updater)
* update or after same-domain document has been hooked, otherwise an
* exception is raised.
*/
writeScript : function(block, attributes) {
attributes = Ext.apply({}, attributes || {}, {
type : "text/javascript",
text : block
});
try {
var head, script, doc = this.getFrameDocument();
if (doc && typeof doc.getElementsByTagName != 'undefined') {
if (!(head = doc.getElementsByTagName("head")[0])) {
// some browsers (Webkit, Safari) do not auto-create
// head elements during document.write
head = doc.createElement("head");
doc.getElementsByTagName("html")[0].appendChild(head);
}
if (head && (script = doc.createElement("script"))) {
for (var attrib in attributes) {
if (attributes.hasOwnProperty(attrib)
&& attrib in script) {
script[attrib] = attributes[attrib];
}
}
return !!head.appendChild(script);
}
}
} catch (ex) {
this._observable.fireEvent.call(this._observable, 'exception', this, ex);
}finally{
script = head = null;
}
return false;
},
/**
* Eval a function definition into the iframe window context.
* @param {String/Object} fn Name of the function or function map
* object: {name:'encodeHTML',fn:Ext.util.Format.htmlEncode}
* @param {Boolean} useDOM if true, inserts the fn into a dynamic script tag,
* false does a simple eval on the function definition
* @param {Boolean} invokeIt if true, the function specified is also executed in the
* Window context of the frame. Function arguments are not supported.
* @example <pre><code> var trim = function(s){ return s.replace(/^\s+|\s+$/g,''); };
* iframe.loadFunction('trim');
* iframe.loadFunction({name:'myTrim',fn:String.prototype.trim || trim});</code></pre>
*/
loadFunction : function(fn, useDOM, invokeIt) {
var name = fn.name || fn;
var fnSrc = fn.fn || window[fn];
name && fnSrc && this.execScript(name + '=' + fnSrc, useDOM); // fn.toString coercion
invokeIt && this.execScript(name + '()'); // no args only
},
/**
* @private
* Evaluate the Iframes readyState/load event to determine its
* 'load' state, and raise the 'domready/documentloaded' event when
* applicable.
*/
loadHandler : function(e, target) {
var rstatus = (this.dom||{}).readyState || (e || {}).type ;
if (this.eventsFollowFrameLinks || this._frameAction || this.isReset ) {
switch (rstatus) {
case 'domready' : // MIF
case 'DOMFrameContentLoaded' :
case 'domfail' : // MIF
this._onDocReady (rstatus);
break;
case 'load' : // Gecko, Opera, IE
case 'complete' :
this._onDocLoaded(rstatus);
break;
case 'error':
this._observable.fireEvent.apply(this._observable,['exception', this].concat(arguments));
break;
default :
}
this.frameState = rstatus;
}
},
/**
* @private
* @param {String} eventName
*/
_onDocReady : function(eventName ){
var w, obv = this._observable, D;
if(!this.isReset && this.focusOnLoad && (w = this.getWindow())){
w.focus();
}
//raise internal event regardless of state.
obv.fireEvent("_docready", this);
(D = this.getDoc()) && (D.isReady = true);
if ( !this.domFired &&
(this._hooked = this._renderHook())) {
// Only raise if sandBox injection succeeded (same origin)
this.domFired = true;
this.isReset || obv.fireEvent.call(obv, 'domready', this);
}
this.domReady = true;
this.hideMask();
},
/**
* @private
* @param {String} eventName
*/
_onDocLoaded : function(eventName ){
var obv = this._observable, w;
this.domReady || this._onDocReady('domready');
obv.fireEvent("_docload", this); //invoke any callbacks
this.isReset || obv.fireEvent("documentloaded", this);
this.hideMask(true);
this._frameAction = this.isReset = false;
},
/**
* @private
* Poll the Iframes document structure to determine DOM ready
* state, and raise the 'domready' event when applicable.
*/
checkDOM : function( win) {
if ( Ext.isGecko ) { return; }
// initialise the counter
var n = 0, frame = this, domReady = false,
b, l, d,
max = this.domReadyRetries || 2500, //default max 5 seconds
polling = false,
startLocation = (this.getFrameDocument() || {location : {}}).location.href;
(function() { // DOM polling for IE and others
d = frame.getFrameDocument() || {location : {}};
// wait for location.href transition
polling = (d.location.href !== startLocation || d.location.href === frame._targetURI);
if ( frame.domReady) { return;}
domReady = polling && ((b = frame.getBody()) && !!(b.dom.innerHTML || '').length) || false;
// null href is a 'same-origin' document access violation,
// so we assume the DOM is built when the browser updates it
if (d.location.href && !domReady && (++n < max)) {
setTimeout(arguments.callee, 2); // try again
return;
}
frame.loadHandler({ type : domReady ? 'domready' : 'domfail'});
})();
},
/**
* @private
*/
filterEventOptionsRe: /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/,
/**
* @private override to handle synthetic events vs DOM events
*/
addListener : function(eventName, fn, scope, options){
if(typeof eventName == "object"){
var o = eventName;
for(var e in o){
if(this.filterEventOptionsRe.test(e)){
continue;
}
if(typeof o[e] == "function"){
// shared options
this.addListener(e, o[e], o.scope, o);
}else{
// individual options
this.addListener(e, o[e].fn, o[e].scope, o[e]);
}
}
return;
}
if(reSynthEvents.test(eventName)){
var O = this._observable;
if(O){
O.events[eventName] || (O.addEvents(eventName));
O.addListener.call(O, eventName, fn, scope || this, options) ;}
}else {
ElFrame.superclass.addListener.call(this, eventName,
fn, scope || this, options);
}
return this;
},
/**
* @private override
* Removes an event handler from this element.
*/
removeListener : function(eventName, fn, scope){
var O = this._observable;
if(reSynthEvents.test(eventName)){
O && O.removeListener.call(O, eventName, fn, scope || this, options);
}else {
ElFrame.superclass.removeListener.call(this, eventName, fn, scope || this);
}
return this;
},
/**
* Removes all previous added listeners from this element
* @private override
*/
removeAllListeners : function(){
Ext.EventManager.removeAll(this.dom);
var O = this._observable;
O && O.purgeListeners.call(this._observable);
return this;
},
/**
* Forcefully show the defined loadMask
* @param {String} msg Mask text to display during the mask operation, defaults to previous defined
* loadMask config value.
* @param {String} msgCls The CSS class to apply to the loading message element (defaults to "x-mask-loading")
* @param {String} maskCls The CSS class to apply to the mask element
*/
showMask : function(msg, msgCls, maskCls) {
var lmask = this.loadMask;
if (lmask && !lmask.disabled ){
this.mask(msg || lmask.msg, msgCls || lmask.msgCls, maskCls || lmask.maskCls, lmask.maskEl);
}
},
/**
* Hide the defined loadMask
* @param {Boolean} forced True to hide the mask regardless of document ready/loaded state.
*/
hideMask : function(forced) {
var tlm = this.loadMask || {};
if (forced || (tlm.hideOnReady && this.domReady)) {
this.unmask();
}
},
/**
* Puts a mask over the FRAME to disable user interaction. Requires core.css.
* @param {String} msg (optional) A message to display in the mask
* @param {String} msgCls (optional) A css class to apply to the msg element
* @param {String} maskCls (optional) A css class to apply to the mask element
* @param {String/Element} maskEl (optional) A targeted Element (parent of the IFRAME) to use the masking agent
* @return {Element} The mask element
*/
mask : function(msg, msgCls, maskCls, maskEl){
this._mask && this.unmask();
var p = Ext.get(maskEl) || this.parent('.ux-mif-mask-target') || this.parent();
if(p.getStyle("position") == "static" &&
!p.select('iframe,frame,object,embed').elements.length){
p.addClass("x-masked-relative");
}
p.addClass("x-masked");
this._mask = Ext.DomHelper.append(p, {cls: maskCls || "ux-mif-el-mask"} , true);
this._mask.setDisplayed(true);
this._mask._agent = p;
if(typeof msg == 'string'){
this._maskMsg = Ext.DomHelper.append(p, {cls: msgCls || "ux-mif-el-mask-msg" , style: {visibility:'hidden'}, cn:{tag:'div', html:msg}}, true);
this._maskMsg
.setVisibilityMode(Ext.Element.VISIBILITY)
.center(p).setVisible(true);
}
if(Ext.isIE && !(Ext.isIE7 && Ext.isStrict) && this.getStyle('height') == 'auto'){ // ie will not expand full height automatically
this._mask.setSize(undefined, this._mask.getHeight());
}
return this._mask;
},
/**
* Removes a previously applied mask.
*/
unmask : function(){
var a;
if(this._mask){
(a = this._mask._agent) && a.removeClass(["x-masked-relative","x-masked"]);
if(this._maskMsg){
this._maskMsg.remove();
delete this._maskMsg;
}
this._mask.remove();
delete this._mask;
}
},
/**
* Creates an (frontal) transparent shim agent for the frame. Used primarily for masking the frame during drag operations.
* @return {Ext.Element} The new shim element.
* @param {String} imgUrl Optional Url of image source to use during shimming (defaults to Ext.BLANK_IMAGE_URL).
* @param {String} shimCls Optional CSS style selector for the shimming agent. (defaults to 'ux-mif-shim' ).
* @return (HTMLElement} the shim element
*/
createFrameShim : function(imgUrl, shimCls ){
this.shimCls = shimCls || this.shimCls || 'ux-mif-shim';
this.frameShim || (this.frameShim = this.next('.'+this.shimCls) || //already there ?
Ext.DomHelper.append(
this.dom.parentNode,{
tag : 'img',
src : imgUrl|| Ext.BLANK_IMAGE_URL,
cls : this.shimCls ,
galleryimg : "no"
}, true)) ;
this.frameShim && (this.frameShim.autoBoxAdjust = false);
return this.frameShim;
},
/**
* Toggles visibility of the (frontal) transparent shim agent for the frame. Used primarily for masking the frame during drag operations.
* @param {Boolean} show Optional True to activate the shim, false to hide the shim agent.
*/
toggleShim : function(show){
var shim = this.frameShim || this.createFrameShim();
var cls = this.shimCls + '-on';
!show && shim.removeClass(cls);
show && !shim.hasClass(cls) && shim.addClass(cls);
},
/**
* Loads this panel's iframe immediately with content returned from an XHR call.
* @param {Object/String/Function} config A config object containing any of the following options:
* <pre><code>
* frame.load({
* url: "your-url.php",
* params: {param1: "foo", param2: "bar"}, // or encoded string
* callback: yourFunction,
* scope: yourObject, // optional scope for the callback
* discardUrl: false,
* nocache: false,
* text: "Loading...",
* timeout: 30,
* scripts: false,
* //optional custom renderer
* renderer:{render:function(el, response, updater, callback){....}}
* });
* </code></pre>
* The only required property is url. The optional properties
* nocache, text and scripts are shorthand for
* disableCaching, indicatorText and loadScripts and are used
* to set their associated property on this panel Updater
* instance.
* @return {Ext.ManagedIFrame.Element} this
*/
load : function(loadCfg) {
var um;
if (um = this.getUpdater()) {
if (loadCfg && loadCfg.renderer) {
um.setRenderer(loadCfg.renderer);
delete loadCfg.renderer;
}
um.update.apply(um, arguments);
}
return this;
},
/** @private
* Frame document event proxy
*/
_eventProxy : function(e) {
if (!e) return;
e = Ext.EventObject.setEvent(e);
var be = e.browserEvent || e, er, args = [e.type, this];
if (!be['eventPhase']
|| (be['eventPhase'] == (be['AT_TARGET'] || 2))) {
if(e.type == 'resize'){
var doc = this.getFrameDocument();
doc && (args.push(
{ height: ELD.getDocumentHeight(doc), width : ELD.getDocumentWidth(doc) },
{ height: ELD.getViewportHeight(doc), width : ELD.getViewportWidth(doc) },
{ height: ELD.getViewHeight(false, doc), width : ELD.getViewWidth(false, doc) }
));
}
er = this._observable ?
this._observable.fireEvent.apply(this._observable, args.concat(
Array.prototype.slice.call(arguments,0)))
: null;
// same-domain unloads should clear ElCache for use with the
// next document rendering
(e.type == 'unload') && this._unHook();
}
return er;
},
/**
* dispatch a message to the embedded frame-window context (same-origin frames only)
* @name sendMessage
* @param {Mixed} message The message payload. The payload can be any supported JS type.
* @param {String} tag Optional reference tag
* @param {String} origin Optional domain designation of the sender (defaults
* to document.domain).
*/
sendMessage : function(message, tag, origin) {
//(implemented by mifmsg.js )
},
/**
* Dispatch a cross-document message (per HTML5 specification) if the browser supports it natively.
* @name postMessage
* @param {String} message Required message payload (String only)
* @param {String} origin (Optional) Site designation of the sender (defaults
* to the current site in the form: http://site.example.com ).
* <p>Notes: on IE8, this action is synchronous.<br/>
* Messaging support requires that the optional messaging driver source
* file (mifmsg.js) is also included in your project.
*
*/
postMessage : function(message ,origin ){
//(implemented by mifmsg.js )
}
});
ElFrame = Ext.Element.IFRAME = Ext.Element.FRAME = Ext.ux.ManagedIFrame.Element;
var fp = ElFrame.prototype;
/**
* @ignore
*/
Ext.override ( ElFrame , {
/**
* Appends an event handler (shorthand for {@link #addListener}).
* @param {String} eventName The type of event to handle
* @param {Function} fn The handler function the event invokes
* @param {Object} scope (optional) The scope (this element) of the handler function
* @param {Object} options (optional) An object containing standard {@link #addListener} options
* @member Ext.Element
* @method on
*/
on : fp.addListener,
/**
* Removes an event handler from this element (shorthand for {@link #removeListener}).
* @param {String} eventName the type of event to remove
* @param {Function} fn the method the event invokes
* @return {MIF.Element} this
* @member Ext.Element
* @method un
*/
un : fp.removeListener,
getUpdateManager : fp.getUpdater
});
/**
* @class Ext.ux.ManagedIFrame.ComponentAdapter
* @version 2.1.3
* @author Doug Hendricks. doug[always-At]theactivegroup.com
* @donate <a target="tag_donate" href="http://donate.theactivegroup.com"><img border="0" src="http://www.paypal.com/en_US/i/btn/x-click-butcc-donate.gif" border="0" alt="Make a donation to support ongoing development"></a>
* @copyright 2007-2010, Active Group, Inc. All rights reserved.
* @license <a href="http://www.gnu.org/licenses/gpl.html">GPL 3.0</a>
* @constructor
* @desc
* Abstract class. This class should not be instantiated.
*/
Ext.ux.ManagedIFrame.ComponentAdapter = function(){};
Ext.ux.ManagedIFrame.ComponentAdapter.prototype = {
/** @property */
version : 2.12,
/**
* @cfg {String} defaultSrc the default src property assigned to the Managed Frame when the component is rendered.
* @default null
*/
defaultSrc : null,
/**
* @cfg {String} unsupportedText Text to display when the IFRAMES/FRAMESETS are disabled by the browser.
*
*/
unsupportedText : 'Inline frames are NOT enabled\/supported by your browser.',
hideMode : !Ext.isIE && !!Ext.ux.plugin.VisibilityMode ? 'nosize' : 'display',
animCollapse : Ext.isIE ,
animFloat : Ext.isIE ,
/**
* @cfg {Boolean} disableMessaging False to enable cross-frame messaging API
* @default true
*
*/
disableMessaging : true,
/**
* @cfg {Boolean} eventsFollowFrameLinks set true to propagate domready and documentloaded
* events anytime the IFRAME's URL changes
* @default true
*/
eventsFollowFrameLinks : true,
/**
* @cfg {object} frameConfig Frames DOM configuration options
* This optional configuration permits override of the IFRAME's DOM attributes
* @example
frameConfig : {
name : 'framePreview',
frameborder : 1,
allowtransparency : true
}
*/
frameConfig : null,
/**
* @cfg focusOnLoad True to set focus on the frame Window as soon as its document
* reports loaded. (Many external sites use IE's document.createRange to create
* DOM elements, but to be successfull IE requires that the FRAME have focus before
* the method is called)
* @default false (true for Internet Explorer)
*/
focusOnLoad : Ext.isIE,
/**
* @property {Object} frameEl An {@link #Ext.ux.ManagedIFrame.Element} reference to rendered frame Element.
*/
frameEl : null,
/**
* @cfg {Boolean} useShim
* True to use to create a transparent shimming agent for use in masking the frame during
* drag operations.
* @default false
*/
useShim : false,
/**
* @cfg {Boolean} autoScroll
* True to use overflow:'auto' on the frame element and show scroll bars automatically when necessary,
* false to clip any overflowing content (defaults to true).
* @default true
*/
autoScroll: true,
/**
* @cfg {String/Object} autoLoad
* Loads this Components frame after the Component is rendered with content returned from an
* XHR call or optionally from a form submission. See {@link #Ext.ux.ManagedIFrame.ComponentAdapter-load} and {@link #Ext.ux.ManagedIFrame.ComponentAdapter-submitAsTarget} methods for
* available configuration options.
* @default null
*/
autoLoad: null,
/** @private */
getId : function(){
return this.id || (this.id = "mif-comp-" + (++Ext.Component.AUTO_ID));
},
stateEvents : ['documentloaded'],
stateful : false,
/**
* Sets the autoScroll state for the frame.
* @param {Boolean} auto True to set overflow:auto on the frame, false for overflow:hidden
* @return {Ext.ux.ManagedIFrame.Component} this
*/
setAutoScroll : function(auto){
var scroll = Ext.value(auto, this.autoScroll === true);
this.rendered && this.getFrame() &&
this.frameEl.setOverflow( (this.autoScroll = scroll) ? 'auto':'hidden');
return this;
},
getContentTarget : function(){
return this.getFrame();
},
/**
* Returns the Ext.ux.ManagedIFrame.Element of the frame.
* @return {Ext.ux.ManagedIFrame.Element} this.frameEl
*/
getFrame : function(){
if(this.rendered){
if(this.frameEl){ return this.frameEl;}
var f = this.items && this.items.first ? this.items.first() : null;
f && (this.frameEl = f.frameEl);
return this.frameEl;
}
return null;
},
/**
* Returns the frame's current window object.
*
* @return {Window} The frame Window object.
*/
getFrameWindow : function() {
return this.getFrame() ? this.frameEl.getWindow() : null;
},
/**
* If sufficient privilege exists, returns the frame's current document
* as an HTMLElement.
*
* @return {HTMLElement} The frame document or false if access to
* document object was denied.
*/
getFrameDocument : function() {
return this.getFrame() ? this.frameEl.getFrameDocument() : null;
},
/**
* Get the embedded iframe's document as an Ext.Element.
*
* @return {Ext.Element object} or null if unavailable
*/
getFrameDoc : function() {
return this.getFrame() ? this.frameEl.getDoc() : null;
},
/**
* If sufficient privilege exists, returns the frame's current document
* body as an HTMLElement.
*
* @return {Ext.Element} The frame document body or Null if access to
* document object was denied.
*/
getFrameBody : function() {
return this.getFrame() ? this.frameEl.getBody() : null;
},
/**
* Reset the embedded frame to a neutral domain state and clear its contents
* @param {String}src (Optional) A specific reset string (eg. 'about:blank')
* to use for resetting the frame.
* @param {Function} callback (Optional) A callback function invoked when the
* frame reset is complete.
* @param {Object} scope (Optional) scope by which the callback function is
* invoked.
* @return {Ext.ux.ManagedIFrame.Component} this
*/
resetFrame : function() {
this.getFrame() && this.frameEl.reset.apply(this.frameEl, arguments);
return this;
},
/**
* Loads the Components frame with the response from a form submit to the
* specified URL with the ManagedIframe.Element as it's submit target.
* @param {Object} submitCfg A config object containing any of the following options:
* <pre><code>
* mifPanel.submitAsTarget({
* form : formPanel.form, //optional Ext.FormPanel, Ext form element, or HTMLFormElement
* url: "your-url.php",
* params: {param1: "foo", param2: "bar"}, // or a URL encoded string
* callback: yourFunction, //optional
* scope: yourObject, // optional scope for the callback
* method: 'POST', //optional form.action (default:'POST')
* encoding : "multipart/form-data" //optional, default HTMLForm default
* });
*
* </code></pre>
*
* @return {Ext.ux.ManagedIFrame.Component} this
*/
submitAsTarget : function(submitCfg){
this.getFrame() && this.frameEl.submitAsTarget.apply(this.frameEl, arguments);
return this;
},
/**
* Loads this Components's frame immediately with content returned from an
* XHR call.
*
* @param {Object/String/Function} loadCfg A config object containing any of the following
* options:
*
* <pre><code>
* mifPanel.load({
* url: "your-url.php",
* params: {param1: "foo", param2: "bar"}, // or a URL encoded string
* callback: yourFunction,
* scope: yourObject, // optional scope for the callback
* discardUrl: false,
* nocache: false,
* text: "Loading...",
* timeout: 30,
* scripts: false,
* submitAsTarget : false, //optional true, to use Form submit to load the frame (see submitAsTarget method)
* renderer:{render:function(el, response, updater, callback){....}} //optional custom renderer
* });
*
* </code></pre>
*
* The only required property is url. The optional properties
* nocache, text and scripts are shorthand for
* disableCaching, indicatorText and loadScripts and are used
* to set their associated property on this panel Updater
* instance.
* @return {Ext.ux.ManagedIFrame.Component} this
*/
load : function(loadCfg) {
if(loadCfg && this.getFrame()){
var args = arguments;
this.resetFrame(null, function(){
loadCfg.submitAsTarget ?
this.submitAsTarget.apply(this,args):
this.frameEl.load.apply(this.frameEl,args);
},this);
}
this.autoLoad = loadCfg;
return this;
},
/** @private */
doAutoLoad : function() {
this.autoLoad && this.load(typeof this.autoLoad == 'object' ?
this.autoLoad : { url : this.autoLoad });
},
/**
* Get the {@link #Ext.ux.ManagedIFrame.Updater} for this panel's iframe. Enables
* Ajax-based document replacement of this panel's iframe document.
*
* @return {Ext.ux.ManagedIFrame.Updater} The Updater
*/
getUpdater : function() {
return this.getFrame() ? this.frameEl.getUpdater() : null;
},
/**
* Sets the embedded Iframe src property. Note: invoke the function with
* no arguments to refresh the iframe based on the current src value.
*
* @param {String/Function} url (Optional) A string or reference to a Function that
* returns a URI string when called
* @param {Boolean} discardUrl (Optional) If not passed as <tt>false</tt>
* the URL of this action becomes the default SRC attribute
* for this iframe, and will be subsequently used in future
* setSrc calls (emulates autoRefresh by calling setSrc
* without params).
* @param {Function} callback (Optional) A callback function invoked when the
* frame document has been fully loaded.
* @param {Object} scope (Optional) scope by which the callback function is
* invoked.
* @return {Ext.ux.ManagedIFrame.Component} this
*/
setSrc : function(url, discardUrl, callback, scope) {
this.getFrame() && this.frameEl.setSrc.apply(this.frameEl, arguments);
return this;
},
/**
* Sets the embedded Iframe location using its replace method. Note: invoke the function with
* no arguments to refresh the iframe based on the current src value.
*
* @param {String/Function} url (Optional) A string or reference to a Function that
* returns a URI string when called
* @param {Boolean} discardUrl (Optional) If not passed as <tt>false</tt>
* the URL of this action becomes the default SRC attribute
* for this iframe, and will be subsequently used in future
* setSrc calls (emulates autoRefresh by calling setSrc
* without params).
* @param {Function} callback (Optional) A callback function invoked when the
* frame document has been fully loaded.
* @param {Object} scope (Optional) scope by which the callback function is
* invoked.
* @return {Ext.ux.ManagedIFrame.Component} this
*/
setLocation : function(url, discardUrl, callback, scope) {
this.getFrame() && this.frameEl.setLocation.apply(this.frameEl, arguments);
return this;
},
/**
* @private //Make it state-aware
*/
getState : function() {
var URI = this.getFrame() ? this.frameEl.getDocumentURI() || null : null;
var state = this.supr().getState.call(this);
state = Ext.apply(state || {},
{defaultSrc : Ext.isFunction(URI) ? URI() : URI,
autoLoad : this.autoLoad
});
return state;
},
/**
* @private
*/
setMIFEvents : function(){
this.addEvents(
/**
* Fires when the iFrame has reached a loaded/complete state.
* @event documentloaded
* @memberOf Ext.ux.ManagedIFrame.ComponentAdapter
* @param {Ext.ux.ManagedIFrame.Element} frameEl
*/
'documentloaded',
/**
* Fires ONLY when an iFrame's Document(DOM) has reach a
* state where the DOM may be manipulated (ie same domain policy)
* Note: This event is only available when overwriting the iframe
* document using the update method and to pages retrieved from a "same
* domain". Returning false from the eventHandler stops further event
* (documentloaded) processing.
* @event domready
* @memberOf Ext.ux.ManagedIFrame.ComponentAdapter
* @param {Ext.ux.ManagedIFrame.Element} this.frameEl
*/
'domready',
/**
* Fires when the frame actions raise an error
* @event exception
* @memberOf Ext.ux.ManagedIFrame.ComponentAdapter
* @param {Ext.ux.MIF.Element} frameEl
* @param {Error/string} exception
*/
'exception',
/**
* Fires upon receipt of a message generated by window.sendMessage
* method of the embedded Iframe.window object
* @event message
* @memberOf Ext.ux.ManagedIFrame.ComponentAdapter
* @param {Ext.ux.ManagedIFrame.Element} this.frameEl
* @param {object}
* message (members: type: {string} literal "message", data
* {Mixed} [the message payload], domain [the document domain
* from which the message originated ], uri {string} the
* document URI of the message sender source (Object) the
* window context of the message sender tag {string} optional
* reference tag sent by the message sender
* <p>Alternate event handler syntax for message:tag filtering Fires upon
* receipt of a message generated by window.sendMessage method which
* includes a specific tag value of the embedded Iframe.window object
*
*/
'message',
/**
* Fires when the frame is blurred (loses focus).
* @event blur
* @memberOf Ext.ux.ManagedIFrame.ComponentAdapter
* @param {Ext.ux.ManagedIFrame.Element} frameEl
* @param {Ext.Event} e Note: This event is only available when overwriting the
* iframe document using the update method and to pages
* retrieved from a "same domain". Returning false from the
* eventHandler [MAY] NOT cancel the event, as this event is
* NOT ALWAYS cancellable in all browsers.
*/
'blur',
/**
* Fires when the frame gets focus. Note: This event is only available
* when overwriting the iframe document using the update method and to
* pages retrieved from a "same domain". Returning false from the
* eventHandler [MAY] NOT cancel the event, as this event is NOT ALWAYS
* cancellable in all browsers.
* @event focus
* @memberOf Ext.ux.ManagedIFrame.ComponentAdapter
* @param {Ext.ux.ManagedIFrame.Element} frameEl
* @param {Ext.Event} e
*
*/
'focus',
/**
* Note: This event is only available when overwriting the iframe
* document using the update method and to pages retrieved from a "same-origin"
* domain. To prevent numerous scroll events from being raised use the <i>buffer</i> listener
* option to limit the number of times the event is raised.
* @event scroll
* @param {Ext.ux.MIF.Element} this.
* @param {Ext.Event}
*/
'scroll',
/**
* Fires when the frames window is resized. Note: This event is only available
* when overwriting the iframe document using the update method and to
* pages retrieved from a "same domain".
* @event resize
* @memberOf Ext.ux.ManagedIFrame.ComponentAdapter
* @param {Ext.ux.ManagedIFrame.Element} frameEl
* @param {Ext.Event} e
* @param {Object} documentSize A height/width object signifying the new document size
* @param {Object} viewPortSize A height/width object signifying the size of the frame's viewport
* @param {Object} viewSize A height/width object signifying the size of the frame's view
*
*/
'resize',
/**
* Fires when(if) the frames window object raises the unload event
* Note: This event is only available when overwriting the iframe
* document using the update method and to pages retrieved from a "same-origin"
* domain. Note: Opera does not raise this event.
* @event unload
* @memberOf Ext.ux.ManagedIFrame.ComponentAdapter
* @param {Ext.ux.ManagedIFrame.Element} frameEl
* @param {Ext.Event}
*/
'unload',
/**
* Fires when the iFrame has been reset to a neutral domain state (blank document).
* @event reset
* @param {Ext.ux.ManagedIFrame.Element} frameEl
*/
'reset'
);
},
/**
* dispatch a message to the embedded frame-window context (same-origin frames only)
* @name sendMessage
* @memberOf Ext.ux.ManagedIFrame.Element
* @param {Mixed} message The message payload. The payload can be any supported JS type.
* @param {String} tag Optional reference tag
* @param {String} origin Optional domain designation of the sender (defaults
* to document.domain).
*/
sendMessage : function(message, tag, origin) {
//(implemented by mifmsg.js )
},
//Suspend (and queue) host container events until the child MIF.Component is rendered.
onAdd : function(C){
C.relayTarget && this.suspendEvents(true);
},
initRef: function() {
if(this.ref){
var t = this,
levels = this.ref.split('/'),
l = levels.length,
i;
for (i = 0; i < l; i++) {
if(t.ownerCt){
t = t.ownerCt;
}
}
this.refName = levels[--i];
t[this.refName] || (t[this.refName] = this);
this.refOwner = t;
}
}
};
/*
* end Adapter
*/
/**
* @class Ext.ux.ManagedIFrame.Component
* @extends Ext.BoxComponent
* @version 2.1.3
* @author Doug Hendricks. doug[always-At]theactivegroup.com
* @donate <a target="tag_donate" href="http://donate.theactivegroup.com"><img border="0" src="http://www.paypal.com/en_US/i/btn/x-click-butcc-donate.gif" border="0" alt="Make a donation to support ongoing development"></a>
* @copyright 2007-2010, Active Group, Inc. All rights reserved.
* @license <a href="http://www.gnu.org/licenses/gpl.html">GPL 3.0</a>
* @constructor
* @base Ext.ux.ManagedIFrame.ComponentAdapter
* @param {Object} config The config object
*/
Ext.ux.ManagedIFrame.Component = Ext.extend(Ext.BoxComponent , {
ctype : "Ext.ux.ManagedIFrame.Component",
/** @private */
initComponent : function() {
var C = {
monitorResize : this.monitorResize || (this.monitorResize = !!this.fitToParent),
plugins : (this.plugins ||[]).concat(
this.hideMode === 'nosize' && Ext.ux.plugin.VisibilityMode ?
[new Ext.ux.plugin.VisibilityMode(
{hideMode :'nosize',
elements : ['bwrap']
})] : [] )
};
MIF.Component.superclass.initComponent.call(
Ext.apply(this,
Ext.apply(this.initialConfig, C)
));
this.setMIFEvents();
},
/** @private */
onRender : function(ct, position){
//default child frame's name to that of MIF-parent id (if not specified on frameCfg).
var frCfg = this.frameCfg || this.frameConfig || (this.relayTarget ? {name : this.relayTarget.id}: {}) || {};
//backward compatability with MIF 1.x
var frDOM = frCfg.autoCreate || frCfg;
frDOM = Ext.apply({tag : 'iframe', id: Ext.id()}, frDOM);
var el = Ext.getDom(this.el);
(el && el.tagName == 'iframe') ||
(this.autoEl = Ext.apply({
name : frDOM.id,
frameborder : 0
}, frDOM ));
MIF.Component.superclass.onRender.apply(this, arguments);
if(this.unsupportedText){
ct.child('noframes') || ct.createChild({tag: 'noframes', html : this.unsupportedText || null});
}
var frame = this.el ;
var F;
if( F = this.frameEl = (this.el ? new MIF.Element(this.el.dom, true): null)){
Ext.apply(F,{
ownerCt : this.relayTarget || this,
disableMessaging : Ext.value(this.disableMessaging, true),
focusOnLoad : Ext.value(this.focusOnLoad, Ext.isIE),
eventsFollowFrameLinks : Ext.value(this.eventsFollowFrameLinks ,true)
});
F.ownerCt.frameEl = F;
F.addClass('ux-mif');
if (this.loadMask) {
//resolve possible maskEl by Element name eg. 'body', 'bwrap', 'actionEl'
var mEl = this.loadMask.maskEl;
F.loadMask = Ext.apply({
disabled : false,
hideOnReady : false,
msgCls : 'ext-el-mask-msg x-mask-loading',
maskCls : 'ext-el-mask'
},
{
maskEl : F.ownerCt[String(mEl)] || F.parent('.' + String(mEl)) || F.parent('.ux-mif-mask-target') || mEl
},
Ext.isString(this.loadMask) ? {msg:this.loadMask} : this.loadMask
);
Ext.get(F.loadMask.maskEl) && Ext.get(F.loadMask.maskEl).addClass('ux-mif-mask-target');
}
F._observable &&
(this.relayTarget || this).relayEvents(F._observable, frameEvents.concat(this._msgTagHandlers || []));
delete this.contentEl;
}
},
/** @private */
afterRender : function(container) {
MIF.Component.superclass.afterRender.apply(this,arguments);
// only resize (to Parent) if the panel is NOT in a layout.
// parentNode should have {style:overflow:hidden;} applied.
if (this.fitToParent && !this.ownerCt) {
var pos = this.getPosition(), size = (Ext.get(this.fitToParent)
|| this.getEl().parent()).getViewSize();
this.setSize(size.width - pos[0], size.height - pos[1]);
}
this.getEl().setOverflow('hidden'); //disable competing scrollers
this.setAutoScroll();
var F;
/* Enable auto-Shims if the Component participates in (nested?)
* border layout.
* Setup event handlers on the SplitBars and region panels to enable the frame
* shims when needed
*/
if(F = this.frameEl){
var ownerCt = this.ownerCt;
while (ownerCt) {
ownerCt.on('afterlayout', function(container, layout) {
Ext.each(['north', 'south', 'east', 'west'],
function(region) {
var reg;
if ((reg = layout[region]) &&
reg.split && reg.split.dd &&
!reg._splitTrapped) {
reg.split.dd.endDrag = reg.split.dd.endDrag.createSequence(MIM.hideShims, MIM );
reg.split.on('beforeresize',MIM.showShims,MIM);
reg._splitTrapped = MIM._splitTrapped = true;
}
}, this);
}, this, { single : true}); // and discard
ownerCt = ownerCt.ownerCt; // nested layouts?
}
/*
* Create an img shim if the component participates in a layout or forced
*/
if(!!this.ownerCt || this.useShim ){ this.frameShim = F.createFrameShim(); }
this.getUpdater().showLoadIndicator = this.showLoadIndicator || false;
//Resume Parent containers' events
var resumeEvents = this.relayTarget && this.ownerCt ?
this.ownerCt.resumeEvents.createDelegate(this.ownerCt) : null;
if(this.autoload){
this.doAutoLoad();
} else if(this.frameMarkup || this.html) {
F.update(this.frameMarkup || this.html, true, resumeEvents);
delete this.html;
delete this.frameMarkup;
return;
}else{
if(this.defaultSrc){
F.setSrc(this.defaultSrc, false);
}else{
/* If this is a no-action frame, reset it first, then resume parent events
* allowing access to a fully reset frame by upstream afterrender/layout events
*/
F.reset(null, resumeEvents);
return;
}
}
resumeEvents && resumeEvents();
}
},
/** @private */
beforeDestroy : function() {
var F;
if(F = this.getFrame()){
F.remove();
this.frameEl = this.frameShim = null;
}
this.relayTarget && (this.relayTarget.frameEl = null);
MIF.Component.superclass.beforeDestroy.call(this);
}
});
Ext.override(MIF.Component, MIF.ComponentAdapter.prototype);
Ext.reg('mif', MIF.Component);
/*
* end Component
*/
/**
* @private
* this function renders a child MIF.Component to MIF.Panel and MIF.Window
* designed to be called by the constructor of higher-level MIF.Components only.
*/
function embed_MIF(config){
config || (config={});
config.layout = 'fit';
config.items = {
xtype : 'mif',
ref : 'mifChild',
useShim : true,
autoScroll : Ext.value(config.autoScroll , this.autoScroll),
defaultSrc : Ext.value(config.defaultSrc , this.defaultSrc),
frameMarkup : Ext.value(config.html , this.html),
loadMask : Ext.value(config.loadMask , this.loadMask),
disableMessaging : Ext.value(config.disableMessaging, this.disableMessaging),
eventsFollowFrameLinks : Ext.value(config.eventsFollowFrameLinks, this.eventsFollowFrameLinks),
focusOnLoad : Ext.value(config.focusOnLoad, this.focusOnLoad),
frameConfig : Ext.value(config.frameConfig || config.frameCfg , this.frameConfig),
relayTarget : this //direct relay of events to the parent component
};
delete config.html;
this.setMIFEvents();
return config;
};
/**
* @class Ext.ux.ManagedIFrame.Panel
* @extends Ext.Panel
* @version 2.1.3
* @author Doug Hendricks. doug[always-At]theactivegroup.com
* @donate <a target="tag_donate" href="http://donate.theactivegroup.com"><img border="0" src="http://www.paypal.com/en_US/i/btn/x-click-butcc-donate.gif" border="0" alt="Make a donation to support ongoing development"></a>
* @copyright 2007-2010, Active Group, Inc. All rights reserved.
* @license <a href="http://www.gnu.org/licenses/gpl.html">GPL 3.0</a>
* @constructor
* @base Ext.ux.ManagedIFrame.ComponentAdapter
* @param {Object} config The config object
*/
Ext.ux.ManagedIFrame.Panel = Ext.extend( Ext.Panel , {
ctype : 'Ext.ux.ManagedIFrame.Panel',
bodyCssClass: 'ux-mif-mask-target',
constructor : function(config){
MIF.Panel.superclass.constructor.call(this, embed_MIF.call(this, config));
}
});
Ext.override(MIF.Panel, MIF.ComponentAdapter.prototype);
Ext.reg('iframepanel', MIF.Panel);
/*
* end Panel
*/
/**
* @class Ext.ux.ManagedIFrame.Portlet
* @extends Ext.ux.ManagedIFrame.Panel
* @version 2.1.3
* @donate <a target="tag_donate" href="http://donate.theactivegroup.com"><img border="0" src="http://www.paypal.com/en_US/i/btn/x-click-butcc-donate.gif" border="0" alt="Make a donation to support ongoing development"></a>
* @license <a href="http://www.gnu.org/licenses/gpl.html">GPL 3.0</a>
* @author Doug Hendricks. Forum ID: <a href="http://extjs.com/forum/member.php?u=8730">hendricd</a>
* @copyright 2007-2010, Active Group, Inc. All rights reserved.
* @constructor Create a new Ext.ux.ManagedIFramePortlet
* @param {Object} config The config object
*/
Ext.ux.ManagedIFrame.Portlet = Ext.extend(Ext.ux.ManagedIFrame.Panel, {
ctype : "Ext.ux.ManagedIFrame.Portlet",
anchor : '100%',
frame : true,
collapseEl : 'bwrap',
collapsible: true,
draggable : true,
cls : 'x-portlet'
});
Ext.reg('iframeportlet', MIF.Portlet);
/*
* end Portlet
*/
/**
* @class Ext.ux.ManagedIFrame.Window
* @extends Ext.Window
* @version 2.1.3
* @author Doug Hendricks.
* @donate <a target="tag_donate" href="http://donate.theactivegroup.com"><img border="0" src="http://www.paypal.com/en_US/i/btn/x-click-butcc-donate.gif" border="0" alt="Make a donation to support ongoing development"></a>
* @copyright 2007-2010, Active Group, Inc. All rights reserved.
* @license <a href="http://www.gnu.org/licenses/gpl.html">GPL 3.0</a>
* @constructor
* @base Ext.ux.ManagedIFrame.ComponentAdapter
* @param {Object} config The config object
*/
Ext.ux.ManagedIFrame.Window = Ext.extend( Ext.Window ,
{
ctype : "Ext.ux.ManagedIFrame.Window",
bodyCssClass: 'ux-mif-mask-target',
constructor : function(config){
MIF.Window.superclass.constructor.call(this, embed_MIF.call(this, config));
}
});
Ext.override(MIF.Window, MIF.ComponentAdapter.prototype);
Ext.reg('iframewindow', MIF.Window);
/*
* end Window
*/
/**
* @class Ext.ux.ManagedIFrame.Updater
* @extends Ext.Updater
* @version 2.1.3
* @donate <a target="tag_donate" href="http://donate.theactivegroup.com"><img border="0" src="http://www.paypal.com/en_US/i/btn/x-click-butcc-donate.gif" border="0" alt="Make a donation to support ongoing development"></a>
* @license <a href="http://www.gnu.org/licenses/gpl.html">GPL 3.0</a>
* @author Doug Hendricks. Forum ID: <a href="http://extjs.com/forum/member.php?u=8730">hendricd</a>
* @copyright 2007-2010, Active Group, Inc. All rights reserved.
* @constructor Creates a new Ext.ux.ManagedIFrame.Updater instance.
* @param {String/Object} el The element to bind the Updater instance to.
*/
Ext.ux.ManagedIFrame.Updater = Ext.extend(Ext.Updater, {
/**
* Display the element's "loading" state. By default, the element is updated with {@link #indicatorText}. This
* method may be overridden to perform a custom action while this Updater is actively updating its contents.
*/
showLoading : function(){
this.showLoadIndicator && this.el && this.el.mask(this.indicatorText);
},
/**
* Hide the Frames masking agent.
*/
hideLoading : function(){
this.showLoadIndicator && this.el && this.el.unmask();
},
// private
updateComplete : function(response){
MIF.Updater.superclass.updateComplete.apply(this,arguments);
this.hideLoading();
},
// private
processFailure : function(response){
MIF.Updater.superclass.processFailure.apply(this,arguments);
this.hideLoading();
}
});
var styleCamelRe = /(-[a-z])/gi;
var styleCamelFn = function(m, a) {
return a.charAt(1).toUpperCase();
};
/**
* @class Ext.ux.ManagedIFrame.CSS
* Stylesheet interface object
* @version 2.1.3
* @author Doug Hendricks. doug[always-At]theactivegroup.com
* @donate <a target="tag_donate" href="http://donate.theactivegroup.com"><img border="0" src="http://www.paypal.com/en_US/i/btn/x-click-butcc-donate.gif" border="0" alt="Make a donation to support ongoing development"></a>
* @copyright 2007-2010, Active Group, Inc. All rights reserved.
* @license <a href="http://www.gnu.org/licenses/gpl.html">GPL 3.0</a>
*/
Ext.ux.ManagedIFrame.CSS = function(hostDocument) {
var doc;
if (hostDocument) {
doc = hostDocument;
return {
rules : null,
/** @private */
destroy : function(){ return doc = null; },
/**
* Creates a stylesheet from a text blob of rules. These rules
* will be wrapped in a STYLE tag and appended to the HEAD of
* the document.
*
* @param {String}
* cssText The text containing the css rules
* @param {String} id An (optional) id to add to the stylesheet for later removal
* @return {StyleSheet}
*/
createStyleSheet : function(cssText, id) {
var ss;
if (!doc)return;
var head = doc.getElementsByTagName("head")[0];
var rules = doc.createElement("style");
rules.setAttribute("type", "text/css");
Ext.isString(id) && rules.setAttribute("id", id);
if (Ext.isIE) {
head.appendChild(rules);
ss = rules.styleSheet;
ss.cssText = cssText;
} else {
try {
rules.appendChild(doc.createTextNode(cssText));
} catch (e) {
rules.cssText = cssText;
}
head.appendChild(rules);
ss = rules.styleSheet
? rules.styleSheet
: (rules.sheet || doc.styleSheets[doc.styleSheets.length - 1]);
}
this.cacheStyleSheet(ss);
return ss;
},
/**
* Removes a style or link tag by id
*
* @param {String}
* id The id of the tag
*/
removeStyleSheet : function(id) {
if (!doc || !id)return;
var existing = doc.getElementById(id);
if (existing) {
existing.parentNode.removeChild(existing);
}
},
/**
* Dynamically swaps an existing stylesheet reference for a new
* one
*
* @param {String}
* id The id of an existing link tag to remove
* @param {String}
* url The href of the new stylesheet to include
*/
swapStyleSheet : function(id, url) {
if (!doc)return;
this.removeStyleSheet(id);
var ss = doc.createElement("link");
ss.setAttribute("rel", "stylesheet");
ss.setAttribute("type", "text/css");
Ext.isString(id) && ss.setAttribute("id", id);
ss.setAttribute("href", url);
doc.getElementsByTagName("head")[0].appendChild(ss);
},
/**
* Refresh the rule cache if you have dynamically added stylesheets
* @return {Object} An object (hash) of rules indexed by selector
*/
refreshCache : function() {
return this.getRules(true);
},
// private
cacheStyleSheet : function(ss, media) {
this.rules || (this.rules = {});
try{// try catch for cross domain access issue
Ext.each(ss.cssRules || ss.rules || [],
function(rule){
this.hashRule(rule, ss, media);
}, this);
//IE @imports
Ext.each(ss.imports || [],
function(sheet){
sheet && this.cacheStyleSheet(sheet,this.resolveMedia([sheet, sheet.parentStyleSheet]));
}
,this);
}catch(e){}
},
// @private
hashRule : function(rule, sheet, mediaOverride){
var mediaSelector = mediaOverride || this.resolveMedia(rule);
//W3C @media
if( rule.cssRules || rule.rules){
this.cacheStyleSheet(rule, this.resolveMedia([rule, rule.parentRule ]));
}
//W3C @imports
if(rule.styleSheet){
this.cacheStyleSheet(rule.styleSheet, this.resolveMedia([rule, rule.ownerRule, rule.parentStyleSheet]));
}
rule.selectorText &&
Ext.each((mediaSelector || '').split(','),
function(media){
this.rules[((media ? media.trim() + ':' : '') + rule.selectorText).toLowerCase()] = rule;
}, this);
},
/**
* @private
* @param {Object/Array} rule CSS Rule (or array of Rules/sheets) to evaluate media types.
* @return a comma-delimited string of media types.
*/
resolveMedia : function(rule){
var media;
Ext.each([].concat(rule),function(r){
if(r && r.media && r.media.length){
media = r.media;
return false;
}
});
return media ? (Ext.isIE ? String(media) : media.mediaText ) : '';
},
/**
* Gets all css rules for the document
*
* @param {Boolean}
* refreshCache true to refresh the internal cache
* @return {Object} An object (hash) of rules indexed by
* selector
*/
getRules : function(refreshCache) {
if (!this.rules || refreshCache) {
this.rules = {};
if (doc) {
var ds = doc.styleSheets;
for (var i = 0, len = ds.length; i < len; i++) {
try {
this.cacheStyleSheet(ds[i]);
} catch (e) {}
}
}
}
return this.rules;
},
/**
* Gets an an individual CSS rule by selector(s)
* @param {String/Array} selector The CSS selector or an array of selectors to try. The first selector that is found is returned.
* @param {Boolean} refreshCache true to refresh the internal cache if you have recently updated any rules or added styles dynamically
* @param {String} mediaSelector Name of optional CSS media context (eg. print, screen)
* @return {CSSRule} The CSS rule or null if one is not found
*/
getRule : function(selector, refreshCache, mediaSelector) {
var rs = this.getRules(refreshCache);
if(Ext.type(mediaSelector) == 'string'){
mediaSelector = mediaSelector.trim() + ':';
}else{
mediaSelector = '';
}
if(!Ext.isArray(selector)){
return rs[(mediaSelector + selector).toLowerCase()];
}
var select;
for(var i = 0; i < selector.length; i++){
select = (mediaSelector + selector[i]).toLowerCase();
if(rs[select]){
return rs[select];
}
}
return null;
},
/**
* Updates a rule property
* @param {String/Array} selector If it's an array it tries each selector until it finds one. Stops immediately once one is found.
* @param {String} property The css property
* @param {String} value The new value for the property
* @param {String} mediaSelector Name(s) of optional media contexts. Multiple may be specified, delimited by commas (eg. print,screen)
* @return {Boolean} true If a rule was found and updated
*/
updateRule : function(selector, property, value, mediaSelector){
Ext.each((mediaSelector || '').split(','), function(mediaSelect){
if(!Ext.isArray(selector)){
var rule = this.getRule(selector, false, mediaSelect);
if(rule){
rule.style[property.replace(camelRe, camelFn)] = value;
return true;
}
}else{
for(var i = 0; i < selector.length; i++){
if(this.updateRule(selector[i], property, value, mediaSelect)){
return true;
}
}
}
return false;
}, this);
}
};
}
};
/**
* @class Ext.ux.ManagedIFrame.Manager
* @version 2.1.3
* @author Doug Hendricks. doug[always-At]theactivegroup.com
* @donate <a target="tag_donate" href="http://donate.theactivegroup.com"><img border="0" src="http://www.paypal.com/en_US/i/btn/x-click-butcc-donate.gif" border="0" alt="Make a donation to support ongoing development"></a>
* @copyright 2007-2010, Active Group, Inc. All rights reserved.
* @license <a href="http://www.gnu.org/licenses/gpl.html">GPL 3.0</a>
* @singleton
*/
Ext.ux.ManagedIFrame.Manager = function() {
var frames = {};
var implementation = {
// private DOMFrameContentLoaded handler for browsers (Gecko, Webkit, Opera) that support it.
_DOMFrameReadyHandler : function(e) {
try {
var $frame ;
if ($frame = e.target.ownerCt){
$frame.loadHandler.call($frame,e);
}
} catch (rhEx) {} //nested iframes will throw when accessing target.id
},
/**
* @cfg {String} shimCls
* @default "ux-mif-shim"
* The default CSS rule applied to MIF image shims to toggle their visibility.
*/
shimCls : 'ux-mif-shim',
/** @private */
register : function(frame) {
frame.manager = this;
frames[frame.id] = frames[frame.name] = {ref : frame };
return frame;
},
/** @private */
deRegister : function(frame) {
delete frames[frame.id];
delete frames[frame.name];
},
/**
* Toggles the built-in MIF shim off on all visible MIFs
* @methodOf Ext.ux.MIF.Manager
*
*/
hideShims : function() {
var mm = MIF.Manager;
mm.shimsApplied && Ext.select('.' + mm.shimCls, true).removeClass(mm.shimCls+ '-on');
mm.shimsApplied = false;
},
/**
* Shim ALL MIFs (eg. when a region-layout.splitter is on the move or before start of a drag operation)
* @methodOf Ext.ux.MIF.Manager
*/
showShims : function() {
var mm = MIF.Manager;
!mm.shimsApplied && Ext.select('.' + mm.shimCls, true).addClass(mm.shimCls+ '-on');
mm.shimsApplied = true;
},
/**
* Retrieve a MIF instance by its DOM ID
* @methodOf Ext.ux.MIF.Manager
* @param {Ext.ux.MIF/string} id
*/
getFrameById : function(id) {
return typeof id == 'string' ? (frames[id] ? frames[id].ref
|| null : null) : null;
},
/**
* Retrieve a MIF instance by its DOM name
* @methodOf Ext.ux.MIF.Manager
* @param {Ext.ux.MIF/string} name
*/
getFrameByName : function(name) {
return this.getFrameById(name);
},
/** @private */
// retrieve the internal frameCache object
getFrameHash : function(frame) {
return frames[frame.id] || frames[frame.id] || null;
},
/** @private */
destroy : function() {
if (document.addEventListener && !Ext.isOpera) {
window.removeEventListener("DOMFrameContentLoaded", this._DOMFrameReadyHandler , false);
}
}
};
// for Gecko and any who might support it later
document.addEventListener && !Ext.isOpera &&
window.addEventListener("DOMFrameContentLoaded", implementation._DOMFrameReadyHandler , false);
Ext.EventManager.on(window, 'beforeunload', implementation.destroy, implementation);
return implementation;
}();
MIM = MIF.Manager;
MIM.showDragMask = MIM.showShims;
MIM.hideDragMask = MIM.hideShims;
/**
* Shim all MIF's during a Window drag operation.
*/
var winDD = Ext.Window.DD;
Ext.override(winDD, {
startDrag : winDD.prototype.startDrag.createInterceptor(MIM.showShims),
endDrag : winDD.prototype.endDrag.createInterceptor(MIM.hideShims)
});
//Previous release compatibility
Ext.ux.ManagedIFramePanel = MIF.Panel;
Ext.ux.ManagedIFramePortlet = MIF.Portlet;
Ext.ux.ManagedIframe = function(el,opt){
var args = Array.prototype.slice.call(arguments, 0),
el = Ext.get(args[0]),
config = args[0];
if (el && el.dom && el.dom.tagName == 'IFRAME') {
config = args[1] || {};
} else {
config = args[0] || args[1] || {};
el = config.autoCreate ? Ext.get(Ext.DomHelper.append(
config.autoCreate.parent || Ext.getBody(), Ext.apply({
tag : 'iframe',
frameborder : 0,
cls : 'x-mif',
src : (Ext.isIE && Ext.isSecure)? Ext.SSL_SECURE_URL: 'about:blank'
}, config.autoCreate)))
: null;
if(el && config.unsupportedText){
Ext.DomHelper.append(el.dom.parentNode, {tag:'noframes',html: config.unsupportedText } );
}
}
var mif = new MIF.Element(el,true);
if(mif){
Ext.apply(mif, {
disableMessaging : Ext.value(config.disableMessaging , true),
focusOnLoad : Ext.value(config.focusOnLoad , Ext.isIE),
eventsFollowFrameLinks : Ext.value(config.eventsFollowFrameLinks ,true),
loadMask : !!config.loadMask ? Ext.apply({
msg : 'Loading..',
msgCls : 'x-mask-loading',
maskEl : null,
hideOnReady : false,
disabled : false
}, config.loadMask) : false,
_windowContext : null
});
config.listeners && mif.on(config.listeners);
if(!!config.html){
mif.update(config.html);
} else {
!!config.src && mif.setSrc(config.src);
}
}
return mif;
};
/**
* Internal Error class for ManagedIFrame Components
* @class Ext.ux.ManagedIFrame.Error
* @extends Ext.Error
* @version 2.1.3
* @donate <a target="tag_donate" href="http://donate.theactivegroup.com"><img border="0" src="http://www.paypal.com/en_US/i/btn/x-click-butcc-donate.gif" border="0" alt="Make a donation to support ongoing development"></a>
* @license <a href="http://www.gnu.org/licenses/gpl.html">GPL 3.0</a>
* @author Doug Hendricks. Forum ID: <a href="http://extjs.com/forum/member.php?u=8730">hendricd</a>
* @copyright 2007-2010, Active Group, Inc. All rights reserved.
* @constructor
* @param {String} message
* @param {Mixed} arg optional argument to include in Error object.
*/
Ext.ux.ManagedIFrame.Error = Ext.extend(Ext.Error, {
constructor : function(message, arg) {
this.arg = arg;
Ext.Error.call(this, message);
},
name : 'Ext.ux.ManagedIFrame'
});
Ext.apply(Ext.ux.ManagedIFrame.Error.prototype, {
lang: {
'documentcontext-remove': 'An attempt was made to remove an Element from the wrong document context.',
'execscript-secure-context': 'An attempt was made at script execution within a document context with limited access permissions.',
'printexception': 'An Error was encountered attempting the print the frame contents (document access is likely restricted).'
}
});
/** @private */
Ext.onReady(function() {
// Generate CSS Rules but allow for overrides.
var CSS = new Ext.ux.ManagedIFrame.CSS(document), rules = [];
CSS.getRule('.ux-mif-fill')|| (rules.push('.ux-mif-fill{height:100%;width:100%;}'));
CSS.getRule('.ux-mif-mask-target')|| (rules.push('.ux-mif-mask-target{position:relative;zoom:1;}'));
CSS.getRule('.ux-mif-el-mask')|| (rules.push(
'.ux-mif-el-mask {z-index: 100;position: absolute;top:0;left:0;-moz-opacity: 0.5;opacity: .50;*filter: alpha(opacity=50);width: 100%;height: 100%;zoom: 1;} ',
'.ux-mif-el-mask-msg {z-index: 1;position: absolute;top: 0;left: 0;border:1px solid;background:repeat-x 0 -16px;padding:2px;} ',
'.ux-mif-el-mask-msg div {padding:5px 10px 5px 10px;border:1px solid;cursor:wait;} '
));
if (!CSS.getRule('.ux-mif-shim')) {
rules.push('.ux-mif-shim {z-index:8500;position:absolute;top:0px;left:0px;background:transparent!important;overflow:hidden;display:none;}');
rules.push('.ux-mif-shim-on{width:100%;height:100%;display:block;zoom:1;}');
rules.push('.ext-ie6 .ux-mif-shim{margin-left:5px;margin-top:3px;}');
}
if (!CSS.getRule('.x-hide-nosize')){
rules.push ('.x-hide-nosize{height:0px!important;width:0px!important;visibility:hidden!important;border:none!important;zoom:1;}.x-hide-nosize * {height:0px!important;width:0px!important;visibility:hidden!important;border:none!important;zoom:1;}');
}
!!rules.length && CSS.createStyleSheet(rules.join(' '), 'mifCSS');
});
/** @sourceURL=<mif.js> */
Ext.provide && Ext.provide('mif');
})();
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
Ext.namespace('sitools.widget');
sitools.widget.TextFilter = Ext.extend(Ext.form.TriggerField, {
ctCls:"s-textfilter",
cls:"s-textfilter-text",
triggerConfig:{tag:"div", cls:"x-form-trigger s-textfilter-trigger"},
enableKeyEvents:true,
listeners:{
keyup: { fn:function(tf,a) {tf.trigger.setVisible((tf.getValue()!==""));} },
render: { fn:function(tf) {tf.trigger.hide();} }
},
queryDelay:500,
queryAction:"find",
enumAction:"enum",
queryParam:"query",
localFilter:false,
localFilterField:"",
pageSize:"",
constructor:function(params){
sitools.widget.TextFilter.superclass.constructor.call(this,params);
if(this.store&&!this.localFilter){
this.mon(this.store,"beforeload",this.onBeforeLoad,this);
}
if(this.localFilter===true){
this.mon(this.store,"load",this.reset,this);
}
},
initEvents:function(){
sitools.widget.TextFilter.superclass.initEvents.call(this);
this.mon(this.el,"keyup",this.filter,this,{buffer:this.queryDelay});
},
setPageSize:function(size){
this.pageSize=size;
},
onBeforeLoad:function(a,b){
var c=this.getValue();
if(c){
b.params[this.queryParam]=c;
b.params.action=this.queryAction;
}else{
b.params.action=this.enumAction;
}
return true;
},
filter: function(){
var b=this.getValue();
var a = {};
if(!this.store){
return;
}
if(this.localFilter===true){
if(b){
this.store.filter(this.localFilterField,b,true);
}else{
this.store.clearFilter(false);
}
return;
}
if (!Ext.isEmpty(this.pageSize)){
a={start:0,limit:this.pageSize};
}
if(b){
a.action=this.queryAction;
a[this.queryParam]=b;
this.store.load({params:a});
}else{
a.action=this.enumAction;
this.store.load({params:a});
}
},
reset: function(){
sitools.widget.TextFilter.superclass.reset.call(this);
if(this.localFilterField===false&&this.store){
this.store.clearFilter(false);
}
},
onTriggerClick: function(){
if(this.getValue()){
this.setValue("");
this.trigger.hide();
this.filter();
}
}
});
//register type
Ext.reg('s-filter', sitools.widget.TextFilter);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*
* Ext JS Library 3.2.1
* Copyright(c) 2006-2010 Ext JS, Inc.
* licensing@extjs.com
* http://www.extjs.com/license
*/
/**
* @class Ext.ux.Spinner
* @extends Ext.util.Observable
* Creates a Spinner control utilized by Ext.ux.form.SpinnerField
*/
Ext.ux.Spinner = Ext.extend(Ext.util.Observable, {
incrementValue: 1,
alternateIncrementValue: 5,
triggerClass: 'x-form-spinner-trigger',
splitterClass: 'x-form-spinner-splitter',
alternateKey: Ext.EventObject.shiftKey,
defaultValue: 0,
accelerate: false,
constructor: function(config){
Ext.ux.Spinner.superclass.constructor.call(this, config);
Ext.apply(this, config);
this.mimicing = false;
},
init: function(field){
this.field = field;
field.afterMethod('onRender', this.doRender, this);
field.afterMethod('onEnable', this.doEnable, this);
field.afterMethod('onDisable', this.doDisable, this);
field.afterMethod('afterRender', this.doAfterRender, this);
field.afterMethod('onResize', this.doResize, this);
field.afterMethod('onFocus', this.doFocus, this);
field.beforeMethod('onDestroy', this.doDestroy, this);
},
doRender: function(ct, position){
var el = this.el = this.field.getEl();
var f = this.field;
if (!f.wrap) {
f.wrap = this.wrap = el.wrap({
cls: "x-form-field-wrap"
});
}
else {
this.wrap = f.wrap.addClass('x-form-field-wrap');
}
this.trigger = this.wrap.createChild({
tag: "img",
src: Ext.BLANK_IMAGE_URL,
cls: "x-form-trigger " + this.triggerClass
});
if (!f.width) {
this.wrap.setWidth(el.getWidth() + this.trigger.getWidth());
}
this.splitter = this.wrap.createChild({
tag: 'div',
cls: this.splitterClass,
style: 'width:13px; height:2px;'
});
this.splitter.setRight((Ext.isIE) ? 1 : 2).setTop(10).show();
this.proxy = this.trigger.createProxy('', this.splitter, true);
this.proxy.addClass("x-form-spinner-proxy");
this.proxy.setStyle('left', '0px');
this.proxy.setSize(14, 1);
this.proxy.hide();
this.dd = new Ext.dd.DDProxy(this.splitter.dom.id, "SpinnerDrag", {
dragElId: this.proxy.id
});
this.initTrigger();
this.initSpinner();
},
doAfterRender: function(){
var y;
if (Ext.isIE && this.el.getY() != (y = this.trigger.getY())) {
this.el.position();
this.el.setY(y);
}
},
doEnable: function(){
if (this.wrap) {
this.wrap.removeClass(this.field.disabledClass);
}
},
doDisable: function(){
if (this.wrap) {
this.wrap.addClass(this.field.disabledClass);
this.el.removeClass(this.field.disabledClass);
}
},
doResize: function(w, h){
if (typeof w == 'number') {
this.el.setWidth(w - this.trigger.getWidth());
}
this.wrap.setWidth(this.el.getWidth() + this.trigger.getWidth());
},
doFocus: function(){
if (!this.mimicing) {
this.wrap.addClass('x-trigger-wrap-focus');
this.mimicing = true;
Ext.get(Ext.isIE ? document.body : document).on("mousedown", this.mimicBlur, this, {
delay: 10
});
this.el.on('keydown', this.checkTab, this);
}
},
// private
checkTab: function(e){
if (e.getKey() == e.TAB) {
this.triggerBlur();
}
},
// private
mimicBlur: function(e){
if (!this.wrap.contains(e.target) && this.field.validateBlur(e)) {
this.triggerBlur();
}
},
// private
triggerBlur: function(){
this.mimicing = false;
Ext.get(Ext.isIE ? document.body : document).un("mousedown", this.mimicBlur, this);
this.el.un("keydown", this.checkTab, this);
this.field.beforeBlur();
this.wrap.removeClass('x-trigger-wrap-focus');
this.field.onBlur.call(this.field);
},
initTrigger: function(){
this.trigger.addClassOnOver('x-form-trigger-over');
this.trigger.addClassOnClick('x-form-trigger-click');
},
initSpinner: function(){
this.field.addEvents({
'spin': true,
'spinup': true,
'spindown': true
});
this.keyNav = new Ext.KeyNav(this.el, {
"up": function(e){
e.preventDefault();
this.onSpinUp();
},
"down": function(e){
e.preventDefault();
this.onSpinDown();
},
"pageUp": function(e){
e.preventDefault();
this.onSpinUpAlternate();
},
"pageDown": function(e){
e.preventDefault();
this.onSpinDownAlternate();
},
scope: this
});
this.repeater = new Ext.util.ClickRepeater(this.trigger, {
accelerate: this.accelerate
});
this.field.mon(this.repeater, "click", this.onTriggerClick, this, {
preventDefault: true
});
this.field.mon(this.trigger, {
mouseover: this.onMouseOver,
mouseout: this.onMouseOut,
mousemove: this.onMouseMove,
mousedown: this.onMouseDown,
mouseup: this.onMouseUp,
scope: this,
preventDefault: true
});
this.field.mon(this.wrap, "mousewheel", this.handleMouseWheel, this);
this.dd.setXConstraint(0, 0, 10)
this.dd.setYConstraint(1500, 1500, 10);
this.dd.endDrag = this.endDrag.createDelegate(this);
this.dd.startDrag = this.startDrag.createDelegate(this);
this.dd.onDrag = this.onDrag.createDelegate(this);
},
onMouseOver: function(){
if (this.disabled) {
return;
}
var middle = this.getMiddle();
this.tmpHoverClass = (Ext.EventObject.getPageY() < middle) ? 'x-form-spinner-overup' : 'x-form-spinner-overdown';
this.trigger.addClass(this.tmpHoverClass);
},
//private
onMouseOut: function(){
this.trigger.removeClass(this.tmpHoverClass);
},
//private
onMouseMove: function(){
if (this.disabled) {
return;
}
var middle = this.getMiddle();
if (((Ext.EventObject.getPageY() > middle) && this.tmpHoverClass == "x-form-spinner-overup") ||
((Ext.EventObject.getPageY() < middle) && this.tmpHoverClass == "x-form-spinner-overdown")) {
}
},
//private
onMouseDown: function(){
if (this.disabled) {
return;
}
var middle = this.getMiddle();
this.tmpClickClass = (Ext.EventObject.getPageY() < middle) ? 'x-form-spinner-clickup' : 'x-form-spinner-clickdown';
this.trigger.addClass(this.tmpClickClass);
},
//private
onMouseUp: function(){
this.trigger.removeClass(this.tmpClickClass);
},
//private
onTriggerClick: function(){
if (this.disabled || this.el.dom.readOnly) {
return;
}
var middle = this.getMiddle();
var ud = (Ext.EventObject.getPageY() < middle) ? 'Up' : 'Down';
this['onSpin' + ud]();
},
//private
getMiddle: function(){
var t = this.trigger.getTop();
var h = this.trigger.getHeight();
var middle = t + (h / 2);
return middle;
},
//private
//checks if control is allowed to spin
isSpinnable: function(){
if (this.disabled || this.el.dom.readOnly) {
Ext.EventObject.preventDefault(); //prevent scrolling when disabled/readonly
return false;
}
return true;
},
handleMouseWheel: function(e){
//disable scrolling when not focused
if (this.wrap.hasClass('x-trigger-wrap-focus') == false) {
return;
}
var delta = e.getWheelDelta();
if (delta > 0) {
this.onSpinUp();
e.stopEvent();
}
else
if (delta < 0) {
this.onSpinDown();
e.stopEvent();
}
},
//private
startDrag: function(){
this.proxy.show();
this._previousY = Ext.fly(this.dd.getDragEl()).getTop();
},
//private
endDrag: function(){
this.proxy.hide();
},
//private
onDrag: function(){
if (this.disabled) {
return;
}
var y = Ext.fly(this.dd.getDragEl()).getTop();
var ud = '';
if (this._previousY > y) {
ud = 'Up';
} //up
if (this._previousY < y) {
ud = 'Down';
} //down
if (ud != '') {
this['onSpin' + ud]();
}
this._previousY = y;
},
//private
onSpinUp: function(){
if (this.isSpinnable() == false) {
return;
}
if (Ext.EventObject.shiftKey == true) {
this.onSpinUpAlternate();
return;
}
else {
this.spin(false, false);
}
this.field.fireEvent("spin", this);
this.field.fireEvent("spinup", this);
},
//private
onSpinDown: function(){
if (this.isSpinnable() == false) {
return;
}
if (Ext.EventObject.shiftKey == true) {
this.onSpinDownAlternate();
return;
}
else {
this.spin(true, false);
}
this.field.fireEvent("spin", this);
this.field.fireEvent("spindown", this);
},
//private
onSpinUpAlternate: function(){
if (this.isSpinnable() == false) {
return;
}
this.spin(false, true);
this.field.fireEvent("spin", this);
this.field.fireEvent("spinup", this);
},
//private
onSpinDownAlternate: function(){
if (this.isSpinnable() == false) {
return;
}
this.spin(true, true);
this.field.fireEvent("spin", this);
this.field.fireEvent("spindown", this);
},
spin: function(down, alternate){
var v = parseFloat(this.field.getValue());
var incr = (alternate == true) ? this.alternateIncrementValue : this.incrementValue;
(down == true) ? v -= incr : v += incr;
v = (isNaN(v)) ? this.defaultValue : v;
v = this.fixBoundries(v);
this.field.setRawValue(v);
},
fixBoundries: function(value){
var v = value;
if (this.field.minValue != undefined && v < this.field.minValue) {
v = this.field.minValue;
}
if (this.field.maxValue != undefined && v > this.field.maxValue) {
v = this.field.maxValue;
}
return this.fixPrecision(v);
},
// private
fixPrecision: function(value){
var nan = isNaN(value);
if (!this.field.allowDecimals || this.field.decimalPrecision == -1 || nan || !value) {
return nan ? '' : value;
}
return parseFloat(parseFloat(value).toFixed(this.field.decimalPrecision));
},
doDestroy: function(){
if (this.trigger) {
this.trigger.remove();
}
if (this.wrap) {
this.wrap.remove();
delete this.field.wrap;
}
if (this.splitter) {
this.splitter.remove();
}
if (this.dd) {
this.dd.unreg();
this.dd = null;
}
if (this.proxy) {
this.proxy.remove();
}
if (this.repeater) {
this.repeater.purgeListeners();
}
}
});
//backwards compat
Ext.form.Spinner = Ext.ux.Spinner;
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*
* Ext JS Library 3.2.1
* Copyright(c) 2006-2010 Ext JS, Inc.
* licensing@extjs.com
* http://www.extjs.com/license
*/
Ext.ns('Ext.ux.form');
/**
* @class Ext.ux.form.SpinnerField
* @extends Ext.form.NumberField
* Creates a field utilizing Ext.ux.Spinner
* @xtype spinnerfield
*/
Ext.ux.form.SpinnerField = Ext.extend(Ext.form.NumberField, {
actionMode: 'wrap',
deferHeight: true,
autoSize: Ext.emptyFn,
onBlur: Ext.emptyFn,
adjustSize: Ext.BoxComponent.prototype.adjustSize,
constructor: function(config) {
var spinnerConfig = Ext.copyTo({}, config, 'incrementValue,alternateIncrementValue,accelerate,defaultValue,triggerClass,splitterClass');
var spl = this.spinner = new Ext.ux.Spinner(spinnerConfig);
var plugins = config.plugins
? (Ext.isArray(config.plugins)
? config.plugins.push(spl)
: [config.plugins, spl])
: spl;
Ext.ux.form.SpinnerField.superclass.constructor.call(this, Ext.apply(config, {plugins: plugins}));
},
// private
getResizeEl: function(){
return this.wrap;
},
// private
getPositionEl: function(){
return this.wrap;
},
// private
alignErrorIcon: function(){
if (this.wrap) {
this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
}
},
validateBlur: function(){
return true;
}
});
Ext.reg('spinnerfield', Ext.ux.form.SpinnerField);
//backwards compat
Ext.form.SpinnerField = Ext.ux.form.SpinnerField;
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, i18n,document*/
Ext.namespace('sitools.component.datasets');
sitools.component.datasets.selectItems = function (config) {
Ext.apply(this, config);
var commandPanel = new Ext.Panel({
layout : "vbox",
layoutConfig : {
align : "center",
pack : "center",
defaultMargins : {top:10, right:0, bottom:0, left:0}
},
flex : 0.06,
defaults : {
scope : this
},
items : [ {
xtype : 'button',
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/simple-arrow-right.png',
handler : this._onAdd
}, {
xtype : 'button',
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/double-arrow-right.png',
handler : this._onAddAll
}, {
xtype : 'button',
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/simple-arrow-left.png',
handler : this._onRemove
}, {
xtype : 'button',
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/double-arrow-left.png',
handler : this._onRemoveAll
} ]
});
Ext.applyIf(this.grid1, {
flex : this.defaultFlexGrid
});
Ext.applyIf(this.grid2, {
flex : this.defaultFlexGrid
});
sitools.component.datasets.selectItems.superclass.constructor.call(this, Ext.apply({
layout : 'hbox',
layoutConfig : {
flex : "ratio" ,
align : 'stretch'
},
//height : height,
items : [ this.grid1, commandPanel, this.grid2 ]
}));
};
Ext.extend(sitools.component.datasets.selectItems, Ext.Panel, {
grid1 : null,
grid2 : null,
defaultRecord : null,
defaultFlexGrid : 0.47,
_onAdd : function () {
var store2 = this.grid2.getStore();
// var recs = this.scope.datasourceUtils.getFieldsBDDSelected(this.grid1);
var recs = [];
if (this.grid1 instanceof Ext.grid.GridPanel) {
recs = this.grid1.getSelectionModel().getSelections();
}
if (this.grid1 instanceof Ext.tree.TreePanel) {
var treeNodes = this.grid1.getSelectionModel().getSelectedNodes();
var RecType = store2.recordType;
Ext.each (treeNodes, function (node) {
var attributes = Ext.apply(node.attributes, {
columnAlias : node.attributes.name.toLowerCase(),
dataIndex : this.buildDataIndex(node),
sqlColumnType : node.attributes.type,
tableName : this.grid1.getRootNode().attributes.collection
});
recs.push(new RecType(node.attributes));
}, this)
}
if (recs.length === 0) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
return;
}
var recTmp;
Ext.each(recs, function (rec) {
recTmp = rec.copy();
recTmp.id = Ext.data.Record.id(recTmp);
Ext.each(this.defaultRecord, function (property) {
if (!recTmp.get(property.name)) {
recTmp.set(property.name, property.value);
}
}, this);
store2.add(recTmp);
}, this);
this.grid2.getView().refresh();
},
_onAddAll : function () {
var store2 = this.grid2.getStore();
var recs = [];
if (this.grid1 instanceof Ext.grid.GridPanel) {
var store1 = this.grid1.getStore();
recs = store1.data.items;
}
if (this.grid1 instanceof Ext.tree.TreePanel) {
var treeNodes = this.grid1.getRootNode().childNodes;
var RecType = store2.recordType;
Ext.each (treeNodes, function (node) {
var attributes = Ext.apply(node.attributes, {
columnAlias : node.attributes.name.toLowerCase(),
dataIndex : this.buildDataIndex(node),
sqlColumnType : node.attributes.type,
tableName : node.ownerTree.getRootNode().attributes.collection
});
recs.push(new RecType(node.attributes));
}, this)
}
var recTmp;
Ext.each(recs, function (rec) {
recTmp = rec.copy();
recTmp.id = Ext.data.Record.id(recTmp);
Ext.each(this.defaultRecord, function (property) {
if (!recTmp.get(property.name)) {
recTmp.set(property.name, property.value);
}
}, this);
store2.add(recTmp);
}, this);
},
_onRemove : function () {
var store2 = this.grid2.getStore();
var recs = this.grid2.getSelectionModel().getSelections();
if (recs.length === 0) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
return;
}
Ext.each(recs, function (rec) {
store2.remove(rec);
});
this.grid2.getView().refresh();
},
_onRemoveAll : function () {
var store2 = this.grid2.getStore();
store2.each(function (rec) {
store2.remove(rec);
});
},
setFirstGrid : function (grid) {
this.remove(this.grid1);
Ext.applyIf(grid, {
flex : this.defaultFlexGrid
});
this.grid1 = grid;
this.insert(0, this.grid1);
this.doLayout();
},
getFirstGrid : function () {
return this.grid1;
},
getSecondGrid : function () {
return this.grid2;
},
buildDataIndex : function (node, currentName) {
if (Ext.isEmpty(currentName)) {
currentName = node.attributes.name;
}
while (node.parentNode && !node.parentNode.isRoot) {
node = node.parentNode;
currentName = node.attributes.name + "." + currentName;
this.buildDataIndex(node, currentName)
}
return currentName;
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
Ext.namespace('sitools.widget');
sitools.widget.GridUp = Ext.extend(Ext.Button, {
initComponent : function () {
this.icon = loadUrl.get('APP_URL') + '/common/res/images/icons/simple-arrow-up.png';
sitools.widget.GridUp.superclass.initComponent.call(this);
},
handler: function (){
if (Ext.isEmpty(this.gridId)) {
var grid = this.findByType('grid')[0];
} else {
var grid = Ext.getCmp(this.gridId);
}
if (! grid) {
var grid = this;
}
var rec = grid.getSelectionModel().getSelected();
if (!rec){
return;
}
var store = grid.getStore();
if (!store){
return;
}
var index = store.data.items.indexOf(rec);
if( index > 0){
store.remove (rec);
store.insert (index-1, rec);
grid.getSelectionModel().selectRow(index-1);
}
grid.getView().refresh();
}
});
sitools.widget.GridDown = Ext.extend(Ext.Button, {
initComponent : function () {
this.icon = loadUrl.get('APP_URL') + '/common/res/images/icons/simple-arrow-down.png';
sitools.widget.GridDown.superclass.initComponent.call(this);
},
handler: function (){
if (Ext.isEmpty(this.gridId)) {
var grid = this.findByType('grid')[0];
} else {
var grid = Ext.getCmp(this.gridId);
}
if (! grid) {
var grid = this;
}
var rec = grid.getSelectionModel().getSelected();
if (!rec){
return;
}
var store = grid.getStore();
if (!store){
return;
}
var index = store.data.items.indexOf(rec);
if(index < store.getCount()-1){
store.remove (rec);
store.insert (index+1, rec);
grid.getSelectionModel().selectRow(index+1);
}
grid.getView().refresh();
}
});
sitools.widget.GridTop = Ext.extend(Ext.Button, {
initComponent : function () {
this.icon = loadUrl.get('APP_URL') + '/common/res/images/icons/double-arrow-up.png';
sitools.widget.GridTop.superclass.initComponent.call(this);
},
handler: function (){
if (Ext.isEmpty(this.gridId)) {
var grid = this.findByType('grid')[0];
} else {
var grid = Ext.getCmp(this.gridId);
}
if (! grid) {
var grid = this;
}
var rec = grid.getSelectionModel().getSelected();
if (!rec){
return;
}
var store = grid.getStore();
if (!store){
return;
}
store.remove (rec);
store.insert (0, rec);
grid.getSelectionModel().selectRow(0);
grid.getView().refresh();
}
});
sitools.widget.GridBottom = Ext.extend(Ext.Button, {
initComponent : function () {
this.icon = loadUrl.get('APP_URL') + '/common/res/images/icons/double-arrow-down.png';
sitools.widget.GridBottom.superclass.initComponent.call(this);
},
handler: function (){
if (Ext.isEmpty(this.gridId)) {
var grid = this.findByType('grid')[0];
} else {
var grid = Ext.getCmp(this.gridId);
}
if (! grid) {
var grid = this;
}
var rec = grid.getSelectionModel().getSelected();
if (!rec){
return;
}
var store = grid.getStore();
if (!store){
return;
}
var index = store.data.items.indexOf(rec);
store.remove (rec);
store.insert (store.getCount(), rec);
grid.getSelectionModel().selectRow(store.getCount() - 1);
grid.getView().refresh();
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/** (c) 2007-2008 Timo Michna / www.matikom.de
* All rights reserved
*
* This script is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/***************************************************************
* For commercial use, ask the author for permission and different license
***************************************************************/
Ext.namespace('Ext.ux');
Ext.namespace('Ext.ux.Plugin');
Ext.ux.Plugin.LiteRemoteComponent = function (config){
var defaultType = config.xtype || 'panel';
var callback = function(res){
this.container.add(Ext.ComponentMgr.create(Ext.decode(res.responseText), defaultType)).show();
this.container.doLayout() ;
};
return{
init : function (container){
this.container = container;
Ext.Ajax.request(Ext.apply(config, {success: callback, scope: this}));
}
}
};
/**
* @author Timo Michna / matikom
* @class Ext.ux.Plugin.RemoteComponent
* @extends Ext.util.Observable
* @constructor
* @param {Object} config
* @version 0.3.0
* Plugin for Ext.Container/Ext.Toolbar Elements to dynamically
* add Components from a remote source to the Element�s body.
* Loads configuration as JSON-String from a remote source.
* Creates the Components from configuration.
* Adds the Components to the Container body.
* Additionally to its own config options the class accepts all the
* configuration options required to configure its internal Ext.Ajax.request().
*/
Ext.ux.Plugin.RemoteComponent = function (config){
/**
* @cfg {String} breakOn
* set to one of the plugins events, to stop any
* further processing of the plugin, when the event fires.
*/
/**
* @cfg {mixed} loadOn
* Set to one of the Containers events {String}, to defer
* further processing of the plugin to when the event fires.
* Set as an object literal {event: 'event', scope: 'scope'}
* to listen for a different components (not the container) event.
* Set to an numeric Array to listen to different events or components.
* Use String or Literal style in numeric Array. Plugin will load by
* the first occurence of any of the events.
*/
/**
* @cfg {String} xtype
* Default xtype for loaded toplevel component.
* Overwritten by config.xtype or xtype declaration
* Defaults to 'panel'
* in loaded toplevel component.
*/
/**
* @cfg {Boolean} purgeSubscribers
* set to 'true' to avoid unsubstribing all listeners after successfull process chain
* Defaults to false
*/
/**
* @cfg {Mixed el} mask
* The element or DOM node, or its id to mask with loading indicator
*/
/**
* @cfg {Object} maskConfig
* Configuration for LoadMask.
* only effective if config option 'mask' is set.
*/
var defaultType = config.xtype || 'panel';
Ext.applyIf(config, {
purgeSubscribers:true
});
this.initialConfig = config;
Ext.apply(this, config);
//this.purgeSubscribers = config.purgeSubscribers || true;
this.addEvents({
/**
* @event beforeload
* Fires before AJAX request. Return false to stop further processing.
* @param {Object} config
* @param {Ext.ux.Plugin.RemoteComponent} this
*/
'beforeload' : true,
/**
* @event beforecreate
* Fires before creation of new Components from AJAX response.
* Return false to stop further processing.
* @param {Object} JSON-Object decoded from AJAX response
* @param {Ext.ux.Plugin.RemoteComponent} this
*/
'beforecreate' : true,
/**
* @event beforeadd
* Fires before adding the new Components to the Container.
* Return false to stop further processing.
* @param {Object} new Components created from AJAX response.
* @param {Ext.ux.Plugin.RemoteComponent} this
*/
'beforeadd' : true,
/**
* @event beforecomponshow
* Fires before show() is called on the new Components.
* Return false to stop further processing.
* @param {Object} new Components created from AJAX response.
* @param {Ext.ux.Plugin.RemoteComponent} this
*/
'beforecomponshow': true,
/**
* @event beforecontainshow
* Fires before show() is called on the Container.
* Return false to stop further processing.
* @param {Object} new Components created from AJAX response.
* @param {Ext.ux.Plugin.RemoteComponent} this
*/
'beforecontainshow': true,
/**
* @event success
* Fires after full process chain.
* Return false to stop further processing.
* @param {Object} new Components created from AJAX response.
* @param {Ext.ux.Plugin.RemoteComponent} this
*/
'success': true
});
Ext.ux.Plugin.RemoteComponent.superclass.constructor.call(this, config);
// set breakpoint
if(config.breakOn){
this.on(config.breakOn, function(){return false;});
}
/**
* private
* method adds component to container.
* Creates Components from responseText and
* and populates Components in Container.
* @param {Object} JSON Config for new component.
*/
var renderComponent = function(JSON){
if(this.fireEvent('beforeadd', JSON, this)){
//this.container.initComponent();
var component = this.container.add(JSON);
component.fireEvent ('bodyResize', this);
//alert (this.container.ownerCt.height());
if(this.fireEvent('beforecomponshow', component, this)){
return component;
}
}
}.createDelegate(this);
/**
* private
* Callback method for successful Ajax request.
* Creates Components from responseText and
* and populates Components in Container.
* @param {Object} response object from successful AJAX request.
*/
var callback = function(res){
var JSON = Ext.decode(res.responseText);
if(this.fireEvent('beforecreate', JSON, this)){
var component = null;
//JSON = JSON instanceof Array ? JSON[0] : JSON;
if(JSON instanceof Array){
Ext.each(JSON, function(j, i){
component = renderComponent(j).show();;
});
}else{
component = renderComponent(JSON).show();
}
if(this.fireEvent('beforecontainshow', component, this)){
this.container.ownerCt.doLayout();
this.fireEvent('success', component, this);
}
}
if(this.purgeSubscribers){
this.purgeListeners();
}
}.createDelegate(this);
/**
* public
* Processes the AJAX request.
* Generally only called internal. Can be called external,
* when processing has been stopped or defered by config
* options breakOn or loadOn.
*/
this.load = function(){
if(this.fireEvent('beforeload', config, this)){
if(config.mask){
var mask = new Ext.LoadMask(Ext.getDom(config.mask), Ext.apply({msg:'loading components...'}, config.maskConfig || {}));
mask.show();
this.on('success', mask.hide, mask);
}
Ext.Ajax.request(Ext.apply(config, {success: callback, scope: this}));
}
};
/**
* public
* Initialization method called by the Container.
*/
this.init = function (container){
container.on('beforedestroy', function(){this.purgeListeners();}, this);
this.container = container;
if(config.loadOn){
if(config.loadOn instanceof Array){
Ext.each(config.loadOn, function(l, i, a){
var evt = l.event || l.loadOn;
var defer = function (){
this.load();
Ext.each(a, function(lo){
(lo.scope || container).un(evt, defer, this);
}.createDelegate(this));
}.createDelegate(this);
(l.scope || container).on(evt, defer, this);
}.createDelegate(this));
}else{
(config.loadOn.scope || container).on((config.loadOn.event || config.loadOn), this.load, this, {single:true});
}
}else{
this.load();
}
};
};
Ext.extend(Ext.ux.Plugin.RemoteComponent, Ext.util.Observable);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*
* ColumnLock v1.7.1 for Ext 3
*/
Ext.ns('Ext.ux.grid');
Ext.ux.grid.LockingGridPanel = Ext.extend(Ext.grid.GridPanel, {
initComponent : function(){
if(!this.cm && !this.colModel && Ext.isArray(this.columns)){
this.colModel = new Ext.ux.grid.LockingColumnModel(this.columns);
delete this.columns;
}
Ext.ux.grid.LockingGridPanel.superclass.initComponent.call(this);
},
getView : function(){
if(!this.view){
this.view = new Ext.ux.grid.LockingGridView(this.viewConfig);
}
return this.view;
}
});
Ext.ux.grid.LockingEditorGridPanel = Ext.extend(Ext.grid.EditorGridPanel, {
initComponent : function(){
if(!this.cm && !this.colModel && Ext.isArray(this.columns)){
this.colModel = new Ext.ux.grid.LockingColumnModel(this.columns);
delete this.columns;
}
Ext.ux.grid.LockingEditorGridPanel.superclass.initComponent.call(this);
},
getView : function(){
if(!this.view){
this.view = new Ext.ux.grid.LockingGridView(this.viewConfig);
}
return this.view;
}
});
// Added after Ext 3.0.0
Ext.applyIf(Ext.grid.GridView.prototype, {
getScrollOffset: function(){
return Ext.isDefined(this.scrollOffset) ? this.scrollOffset : Ext.getScrollBarWidth();
}
});
/*!
* Ext JS Library 3.4.0
* Copyright(c) 2006-2011 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
/*!
* Ext JS Library 3.4.0
* Copyright(c) 2006-2010 Ext JS, Inc.
* licensing@extjs.com
* http://www.extjs.com/license
*/
Ext.ns('Ext.ux.grid');
Ext.ux.grid.LockingGridView = Ext.extend(Ext.grid.GridView, {
lockText : 'Lock',
unlockText : 'Unlock',
rowBorderWidth : 1,
lockedBorderWidth : 1,
/*
* This option ensures that height between the rows is synchronized
* between the locked and unlocked sides. This option only needs to be used
* when the row heights aren't predictable.
*/
syncHeights: false,
initTemplates : function(){
var ts = this.templates || {};
if (!ts.masterTpl) {
ts.masterTpl = new Ext.Template(
'<div class="x-grid3" hidefocus="true">',
'<div class="x-grid3-locked">',
'<div class="x-grid3-header"><div class="x-grid3-header-inner"><div class="x-grid3-header-offset" style="{lstyle}">{lockedHeader}</div></div><div class="x-clear"></div></div>',
'<div class="x-grid3-scroller"><div class="x-grid3-body" style="{lstyle}">{lockedBody}</div><div class="x-grid3-scroll-spacer"></div></div>',
'</div>',
'<div class="x-grid3-viewport x-grid3-unlocked">',
'<div class="x-grid3-header"><div class="x-grid3-header-inner"><div class="x-grid3-header-offset" style="{ostyle}">{header}</div></div><div class="x-clear"></div></div>',
'<div class="x-grid3-scroller"><div class="x-grid3-body" style="{bstyle}">{body}</div><a href="#" class="x-grid3-focus" tabIndex="-1"></a></div>',
'</div>',
'<div class="x-grid3-resize-marker"> </div>',
'<div class="x-grid3-resize-proxy"> </div>',
'</div>'
);
}
this.templates = ts;
Ext.ux.grid.LockingGridView.superclass.initTemplates.call(this);
},
getEditorParent : function(ed){
return this.el.dom;
},
initElements : function(){
var el = Ext.get(this.grid.getGridEl().dom.firstChild),
lockedWrap = el.child('div.x-grid3-locked'),
lockedHd = lockedWrap.child('div.x-grid3-header'),
lockedScroller = lockedWrap.child('div.x-grid3-scroller'),
mainWrap = el.child('div.x-grid3-viewport'),
mainHd = mainWrap.child('div.x-grid3-header'),
scroller = mainWrap.child('div.x-grid3-scroller');
if (this.grid.hideHeaders) {
lockedHd.setDisplayed(false);
mainHd.setDisplayed(false);
}
if(this.forceFit){
scroller.setStyle('overflow-x', 'hidden');
}
Ext.apply(this, {
el : el,
mainWrap: mainWrap,
mainHd : mainHd,
innerHd : mainHd.dom.firstChild,
scroller: scroller,
mainBody: scroller.child('div.x-grid3-body'),
focusEl : scroller.child('a'),
resizeMarker: el.child('div.x-grid3-resize-marker'),
resizeProxy : el.child('div.x-grid3-resize-proxy'),
lockedWrap: lockedWrap,
lockedHd: lockedHd,
lockedScroller: lockedScroller,
lockedBody: lockedScroller.child('div.x-grid3-body'),
lockedInnerHd: lockedHd.child('div.x-grid3-header-inner', true)
});
this.focusEl.swallowEvent('click', true);
},
getLockedRows : function(){
return this.hasRows() ? this.lockedBody.dom.childNodes : [];
},
getLockedRow : function(row){
return this.getLockedRows()[row];
},
getCell : function(row, col){
var lockedLen = this.cm.getLockedCount();
if(col < lockedLen){
return this.getLockedRow(row).getElementsByTagName('td')[col];
}
return Ext.ux.grid.LockingGridView.superclass.getCell.call(this, row, col - lockedLen);
},
getHeaderCell : function(index){
var lockedLen = this.cm.getLockedCount();
if(index < lockedLen){
return this.lockedHd.dom.getElementsByTagName('td')[index];
}
return Ext.ux.grid.LockingGridView.superclass.getHeaderCell.call(this, index - lockedLen);
},
addRowClass : function(row, cls){
var lockedRow = this.getLockedRow(row);
if(lockedRow){
this.fly(lockedRow).addClass(cls);
}
Ext.ux.grid.LockingGridView.superclass.addRowClass.call(this, row, cls);
},
removeRowClass : function(row, cls){
var lockedRow = this.getLockedRow(row);
if(lockedRow){
this.fly(lockedRow).removeClass(cls);
}
Ext.ux.grid.LockingGridView.superclass.removeRowClass.call(this, row, cls);
},
removeRow : function(row) {
Ext.removeNode(this.getLockedRow(row));
Ext.ux.grid.LockingGridView.superclass.removeRow.call(this, row);
},
removeRows : function(firstRow, lastRow){
var lockedBody = this.lockedBody.dom,
rowIndex = firstRow;
for(; rowIndex <= lastRow; rowIndex++){
Ext.removeNode(lockedBody.childNodes[firstRow]);
}
Ext.ux.grid.LockingGridView.superclass.removeRows.call(this, firstRow, lastRow);
},
syncScroll : function(e){
this.lockedScroller.dom.scrollTop = this.scroller.dom.scrollTop;
Ext.ux.grid.LockingGridView.superclass.syncScroll.call(this, e);
},
updateSortIcon : function(col, dir){
var sortClasses = this.sortClasses,
lockedHeaders = this.lockedHd.select('td').removeClass(sortClasses),
headers = this.mainHd.select('td').removeClass(sortClasses),
lockedLen = this.cm.getLockedCount(),
cls = sortClasses[dir == 'DESC' ? 1 : 0];
if(col < lockedLen){
lockedHeaders.item(col).addClass(cls);
}else{
headers.item(col - lockedLen).addClass(cls);
}
},
updateAllColumnWidths : function(){
var tw = this.getTotalWidth(),
clen = this.cm.getColumnCount(),
lw = this.getLockedWidth(),
llen = this.cm.getLockedCount(),
ws = [], len, i;
this.updateLockedWidth();
for(i = 0; i < clen; i++){
ws[i] = this.getColumnWidth(i);
var hd = this.getHeaderCell(i);
hd.style.width = ws[i];
}
var lns = this.getLockedRows(), ns = this.getRows(), row, trow, j;
for(i = 0, len = ns.length; i < len; i++){
row = lns[i];
row.style.width = lw;
if(row.firstChild){
row.firstChild.style.width = lw;
trow = row.firstChild.rows[0];
for (j = 0; j < llen; j++) {
trow.childNodes[j].style.width = ws[j];
}
}
row = ns[i];
row.style.width = tw;
if(row.firstChild){
row.firstChild.style.width = tw;
trow = row.firstChild.rows[0];
for (j = llen; j < clen; j++) {
trow.childNodes[j - llen].style.width = ws[j];
}
}
}
this.onAllColumnWidthsUpdated(ws, tw);
this.syncHeaderHeight();
},
updateColumnWidth : function(col, width){
var w = this.getColumnWidth(col),
llen = this.cm.getLockedCount(),
ns, rw, c, row;
this.updateLockedWidth();
if(col < llen){
ns = this.getLockedRows();
rw = this.getLockedWidth();
c = col;
}else{
ns = this.getRows();
rw = this.getTotalWidth();
c = col - llen;
}
var hd = this.getHeaderCell(col);
hd.style.width = w;
for(var i = 0, len = ns.length; i < len; i++){
row = ns[i];
row.style.width = rw;
if(row.firstChild){
row.firstChild.style.width = rw;
row.firstChild.rows[0].childNodes[c].style.width = w;
}
}
this.onColumnWidthUpdated(col, w, this.getTotalWidth());
this.syncHeaderHeight();
},
updateColumnHidden : function(col, hidden){
var llen = this.cm.getLockedCount(),
ns, rw, c, row,
display = hidden ? 'none' : '';
this.updateLockedWidth();
if(col < llen){
ns = this.getLockedRows();
rw = this.getLockedWidth();
c = col;
}else{
ns = this.getRows();
rw = this.getTotalWidth();
c = col - llen;
}
var hd = this.getHeaderCell(col);
hd.style.display = display;
for(var i = 0, len = ns.length; i < len; i++){
row = ns[i];
row.style.width = rw;
if(row.firstChild){
row.firstChild.style.width = rw;
row.firstChild.rows[0].childNodes[c].style.display = display;
}
}
this.onColumnHiddenUpdated(col, hidden, this.getTotalWidth());
delete this.lastViewWidth;
this.layout();
},
doRender : function(cs, rs, ds, startRow, colCount, stripe){
var ts = this.templates, ct = ts.cell, rt = ts.row, last = colCount-1,
tstyle = 'width:'+this.getTotalWidth()+';',
lstyle = 'width:'+this.getLockedWidth()+';',
buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r;
for(var j = 0, len = rs.length; j < len; j++){
r = rs[j]; cb = []; lcb = [];
var rowIndex = (j+startRow);
for(var i = 0; i < colCount; i++){
c = cs[i];
p.id = c.id;
p.css = (i === 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : '')) +
(this.cm.config[i].cellCls ? ' ' + this.cm.config[i].cellCls : '');
p.attr = p.cellAttr = '';
p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
p.style = c.style;
if(Ext.isEmpty(p.value)){
p.value = ' ';
}
if(this.markDirty && r.dirty && Ext.isDefined(r.modified[c.name])){
p.css += ' x-grid3-dirty-cell';
}
if(c.locked){
lcb[lcb.length] = ct.apply(p);
}else{
cb[cb.length] = ct.apply(p);
}
}
var alt = [];
if(stripe && ((rowIndex+1) % 2 === 0)){
alt[0] = 'x-grid3-row-alt';
}
if(r.dirty){
alt[1] = ' x-grid3-dirty-row';
}
rp.cols = colCount;
if(this.getRowClass){
alt[2] = this.getRowClass(r, rowIndex, rp, ds);
}
rp.alt = alt.join(' ');
rp.cells = cb.join('');
rp.tstyle = tstyle;
buf[buf.length] = rt.apply(rp);
rp.cells = lcb.join('');
rp.tstyle = lstyle;
lbuf[lbuf.length] = rt.apply(rp);
}
return [buf.join(''), lbuf.join('')];
},
processRows : function(startRow, skipStripe){
if(!this.ds || this.ds.getCount() < 1){
return;
}
var rows = this.getRows(),
lrows = this.getLockedRows(),
row, lrow;
skipStripe = skipStripe || !this.grid.stripeRows;
startRow = startRow || 0;
for(var i = 0, len = rows.length; i < len; ++i){
row = rows[i];
lrow = lrows[i];
row.rowIndex = i;
lrow.rowIndex = i;
if(!skipStripe){
row.className = row.className.replace(this.rowClsRe, ' ');
lrow.className = lrow.className.replace(this.rowClsRe, ' ');
if ((i + 1) % 2 === 0){
row.className += ' x-grid3-row-alt';
lrow.className += ' x-grid3-row-alt';
}
}
this.syncRowHeights(row, lrow);
}
if(startRow === 0){
Ext.fly(rows[0]).addClass(this.firstRowCls);
Ext.fly(lrows[0]).addClass(this.firstRowCls);
}
Ext.fly(rows[rows.length - 1]).addClass(this.lastRowCls);
Ext.fly(lrows[lrows.length - 1]).addClass(this.lastRowCls);
},
syncRowHeights: function(row1, row2){
if(this.syncHeights){
var el1 = Ext.get(row1),
el2 = Ext.get(row2),
h1 = el1.getHeight(),
h2 = el2.getHeight();
if(h1 > h2){
el2.setHeight(h1);
}else if(h2 > h1){
el1.setHeight(h2);
}
}
},
afterRender : function(){
if(!this.ds || !this.cm){
return;
}
var bd = this.renderRows() || [' ', ' '];
this.mainBody.dom.innerHTML = bd[0];
this.lockedBody.dom.innerHTML = bd[1];
this.processRows(0, true);
if(this.deferEmptyText !== true){
this.applyEmptyText();
}
this.grid.fireEvent('viewready', this.grid);
},
renderUI : function(){
var templates = this.templates,
header = this.renderHeaders(),
body = templates.body.apply({rows:' '});
return templates.masterTpl.apply({
body : body,
header: header[0],
ostyle: 'width:' + this.getOffsetWidth() + ';',
bstyle: 'width:' + this.getTotalWidth() + ';',
lockedBody: body,
lockedHeader: header[1],
lstyle: 'width:'+this.getLockedWidth()+';'
});
},
afterRenderUI: function(){
var g = this.grid;
this.initElements();
Ext.fly(this.innerHd).on('click', this.handleHdDown, this);
Ext.fly(this.lockedInnerHd).on('click', this.handleHdDown, this);
this.mainHd.on({
scope: this,
mouseover: this.handleHdOver,
mouseout: this.handleHdOut,
mousemove: this.handleHdMove
});
this.lockedHd.on({
scope: this,
mouseover: this.handleHdOver,
mouseout: this.handleHdOut,
mousemove: this.handleHdMove
});
this.scroller.on('scroll', this.syncScroll, this);
if(g.enableColumnResize !== false){
this.splitZone = new Ext.grid.GridView.SplitDragZone(g, this.mainHd.dom);
this.splitZone.setOuterHandleElId(Ext.id(this.lockedHd.dom));
this.splitZone.setOuterHandleElId(Ext.id(this.mainHd.dom));
}
if(g.enableColumnMove){
this.columnDrag = new Ext.grid.GridView.ColumnDragZone(g, this.innerHd);
this.columnDrag.setOuterHandleElId(Ext.id(this.lockedInnerHd));
this.columnDrag.setOuterHandleElId(Ext.id(this.innerHd));
this.columnDrop = new Ext.grid.HeaderDropZone(g, this.mainHd.dom);
}
if(g.enableHdMenu !== false){
this.hmenu = new Ext.menu.Menu({id: g.id + '-hctx'});
this.hmenu.add(
{itemId: 'asc', text: this.sortAscText, cls: 'xg-hmenu-sort-asc'},
{itemId: 'desc', text: this.sortDescText, cls: 'xg-hmenu-sort-desc'}
);
if(this.grid.enableColLock !== false){
this.hmenu.add('-',
{itemId: 'lock', text: this.lockText, cls: 'xg-hmenu-lock'},
{itemId: 'unlock', text: this.unlockText, cls: 'xg-hmenu-unlock'}
);
}
this.hmenu.add('-',
{itemId: 'help', text: "help", cls: 'xg-hmenu-help'}
);
if(g.enableColumnHide !== false){
this.colMenu = new Ext.menu.Menu({id:g.id + '-hcols-menu'});
this.colMenu.on({
scope: this,
beforeshow: this.beforeColMenuShow,
itemclick: this.handleHdMenuClick
});
this.hmenu.add('-', {
itemId:'columns',
hideOnClick: false,
text: this.columnsText,
menu: this.colMenu,
iconCls: 'x-cols-icon'
});
}
this.hmenu.on('itemclick', this.handleHdMenuClick, this);
}
if(g.trackMouseOver){
this.mainBody.on({
scope: this,
mouseover: this.onRowOver,
mouseout: this.onRowOut
});
this.lockedBody.on({
scope: this,
mouseover: this.onRowOver,
mouseout: this.onRowOut
});
}
if(g.enableDragDrop || g.enableDrag){
this.dragZone = new Ext.grid.GridDragZone(g, {
ddGroup : g.ddGroup || 'GridDD'
});
}
this.updateHeaderSortState();
},
layout : function(){
if(!this.mainBody){
return;
}
var g = this.grid;
var c = g.getGridEl();
var csize = c.getSize(true);
var vw = csize.width;
if(!g.hideHeaders && (vw < 20 || csize.height < 20)){
return;
}
this.syncHeaderHeight();
if(g.autoHeight){
this.scroller.dom.style.overflow = 'visible';
this.lockedScroller.dom.style.overflow = 'visible';
if(Ext.isWebKit){
this.scroller.dom.style.position = 'static';
this.lockedScroller.dom.style.position = 'static';
}
}else{
this.el.setSize(csize.width, csize.height);
var hdHeight = this.mainHd.getHeight();
var vh = csize.height - (hdHeight);
}
this.updateLockedWidth();
if(this.forceFit){
if(this.lastViewWidth != vw){
this.fitColumns(false, false);
this.lastViewWidth = vw;
}
}else {
this.autoExpand();
this.syncHeaderScroll();
}
this.onLayout(vw, vh);
},
getOffsetWidth : function() {
return (this.cm.getTotalWidth() - this.cm.getTotalLockedWidth() + this.getScrollOffset()) + 'px';
},
renderHeaders : function(){
var cm = this.cm,
ts = this.templates,
ct = ts.hcell,
cb = [], lcb = [],
p = {},
len = cm.getColumnCount(),
last = len - 1;
for(var i = 0; i < len; i++){
p.id = cm.getColumnId(i);
p.value = cm.getColumnHeader(i) || '';
p.style = this.getColumnStyle(i, true);
p.tooltip = this.getColumnTooltip(i);
p.css = (i === 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : '')) +
(cm.config[i].headerCls ? ' ' + cm.config[i].headerCls : '');
if(cm.config[i].align == 'right'){
p.istyle = 'padding-right:16px';
} else {
delete p.istyle;
}
if(cm.isLocked(i)){
lcb[lcb.length] = ct.apply(p);
}else{
cb[cb.length] = ct.apply(p);
}
}
return [ts.header.apply({cells: cb.join(''), tstyle:'width:'+this.getTotalWidth()+';'}),
ts.header.apply({cells: lcb.join(''), tstyle:'width:'+this.getLockedWidth()+';'})];
},
updateHeaders : function(){
var hd = this.renderHeaders();
this.innerHd.firstChild.innerHTML = hd[0];
this.innerHd.firstChild.style.width = this.getOffsetWidth();
this.innerHd.firstChild.firstChild.style.width = this.getTotalWidth();
this.lockedInnerHd.firstChild.innerHTML = hd[1];
var lw = this.getLockedWidth();
this.lockedInnerHd.firstChild.style.width = lw;
this.lockedInnerHd.firstChild.firstChild.style.width = lw;
},
getResolvedXY : function(resolved){
if(!resolved){
return null;
}
var c = resolved.cell, r = resolved.row;
return c ? Ext.fly(c).getXY() : [this.scroller.getX(), Ext.fly(r).getY()];
},
syncFocusEl : function(row, col, hscroll){
Ext.ux.grid.LockingGridView.superclass.syncFocusEl.call(this, row, col, col < this.cm.getLockedCount() ? false : hscroll);
},
ensureVisible : function(row, col, hscroll){
return Ext.ux.grid.LockingGridView.superclass.ensureVisible.call(this, row, col, col < this.cm.getLockedCount() ? false : hscroll);
},
insertRows : function(dm, firstRow, lastRow, isUpdate){
var last = dm.getCount() - 1;
if(!isUpdate && firstRow === 0 && lastRow >= last){
this.refresh();
}else{
if(!isUpdate){
this.fireEvent('beforerowsinserted', this, firstRow, lastRow);
}
var html = this.renderRows(firstRow, lastRow),
before = this.getRow(firstRow);
if(before){
if(firstRow === 0){
this.removeRowClass(0, this.firstRowCls);
}
Ext.DomHelper.insertHtml('beforeBegin', before, html[0]);
before = this.getLockedRow(firstRow);
Ext.DomHelper.insertHtml('beforeBegin', before, html[1]);
}else{
this.removeRowClass(last - 1, this.lastRowCls);
Ext.DomHelper.insertHtml('beforeEnd', this.mainBody.dom, html[0]);
Ext.DomHelper.insertHtml('beforeEnd', this.lockedBody.dom, html[1]);
}
if(!isUpdate){
this.fireEvent('rowsinserted', this, firstRow, lastRow);
this.processRows(firstRow);
}else if(firstRow === 0 || firstRow >= last){
this.addRowClass(firstRow, firstRow === 0 ? this.firstRowCls : this.lastRowCls);
}
}
this.syncFocusEl(firstRow);
},
getColumnStyle : function(col, isHeader){
var style = !isHeader ? this.cm.config[col].cellStyle || this.cm.config[col].css || '' : this.cm.config[col].headerStyle || '';
style += 'width:'+this.getColumnWidth(col)+';';
if(this.cm.isHidden(col)){
style += 'display:none;';
}
var align = this.cm.config[col].align;
if(align){
style += 'text-align:'+align+';';
}
return style;
},
getLockedWidth : function() {
return this.cm.getTotalLockedWidth() + 'px';
},
getTotalWidth : function() {
return (this.cm.getTotalWidth() - this.cm.getTotalLockedWidth()) + 'px';
},
getColumnData : function(){
var cs = [], cm = this.cm, colCount = cm.getColumnCount();
for(var i = 0; i < colCount; i++){
var name = cm.getDataIndex(i);
cs[i] = {
name : (!Ext.isDefined(name) ? this.ds.fields.get(i).name : name),
renderer : cm.getRenderer(i),
scope : cm.getRendererScope(i),
id : cm.getColumnId(i),
style : this.getColumnStyle(i),
locked : cm.isLocked(i)
};
}
return cs;
},
renderBody : function(){
var markup = this.renderRows() || [' ', ' '];
return [this.templates.body.apply({rows: markup[0]}), this.templates.body.apply({rows: markup[1]})];
},
refreshRow: function(record){
var store = this.ds,
colCount = this.cm.getColumnCount(),
columns = this.getColumnData(),
last = colCount - 1,
cls = ['x-grid3-row'],
rowParams = {
tstyle: String.format("width: {0};", this.getTotalWidth())
},
lockedRowParams = {
tstyle: String.format("width: {0};", this.getLockedWidth())
},
colBuffer = [],
lockedColBuffer = [],
cellTpl = this.templates.cell,
rowIndex,
row,
lockedRow,
column,
meta,
css,
i;
if (Ext.isNumber(record)) {
rowIndex = record;
record = store.getAt(rowIndex);
} else {
rowIndex = store.indexOf(record);
}
if (!record || rowIndex < 0) {
return;
}
for (i = 0; i < colCount; i++) {
column = columns[i];
if (i == 0) {
css = 'x-grid3-cell-first';
} else {
css = (i == last) ? 'x-grid3-cell-last ' : '';
}
meta = {
id: column.id,
style: column.style,
css: css,
attr: "",
cellAttr: ""
};
meta.value = column.renderer.call(column.scope, record.data[column.name], meta, record, rowIndex, i, store);
if (Ext.isEmpty(meta.value)) {
meta.value = ' ';
}
if (this.markDirty && record.dirty && typeof record.modified[column.name] != 'undefined') {
meta.css += ' x-grid3-dirty-cell';
}
if (column.locked) {
lockedColBuffer[i] = cellTpl.apply(meta);
} else {
colBuffer[i] = cellTpl.apply(meta);
}
}
row = this.getRow(rowIndex);
row.className = '';
lockedRow = this.getLockedRow(rowIndex);
lockedRow.className = '';
if (this.grid.stripeRows && ((rowIndex + 1) % 2 === 0)) {
cls.push('x-grid3-row-alt');
}
if (this.getRowClass) {
rowParams.cols = colCount;
cls.push(this.getRowClass(record, rowIndex, rowParams, store));
}
// Unlocked rows
this.fly(row).addClass(cls).setStyle(rowParams.tstyle);
rowParams.cells = colBuffer.join("");
row.innerHTML = this.templates.rowInner.apply(rowParams);
// Locked rows
this.fly(lockedRow).addClass(cls).setStyle(lockedRowParams.tstyle);
lockedRowParams.cells = lockedColBuffer.join("");
lockedRow.innerHTML = this.templates.rowInner.apply(lockedRowParams);
lockedRow.rowIndex = rowIndex;
this.syncRowHeights(row, lockedRow);
this.fireEvent('rowupdated', this, rowIndex, record);
},
refresh : function(headersToo){
this.fireEvent('beforerefresh', this);
this.grid.stopEditing(true);
var result = this.renderBody();
this.mainBody.update(result[0]).setWidth(this.getTotalWidth());
this.lockedBody.update(result[1]).setWidth(this.getLockedWidth());
if(headersToo === true){
this.updateHeaders();
this.updateHeaderSortState();
}
this.processRows(0, true);
this.layout();
this.applyEmptyText();
this.fireEvent('refresh', this);
},
onDenyColumnLock : function(){
},
initData : function(ds, cm){
if(this.cm){
this.cm.un('columnlockchange', this.onColumnLock, this);
}
Ext.ux.grid.LockingGridView.superclass.initData.call(this, ds, cm);
if(this.cm){
this.cm.on('columnlockchange', this.onColumnLock, this);
}
},
onColumnLock : function(){
this.refresh(true);
},
handleHdMenuClick : function(item){
var index = this.hdCtxIndex,
cm = this.cm,
id = item.getItemId(),
llen = cm.getLockedCount();
switch(id){
case 'lock':
if(cm.getColumnCount(true) <= llen + 1){
this.onDenyColumnLock();
return undefined;
}
cm.setLocked(index, true, llen != index);
if(llen != index){
cm.moveColumn(index, llen);
this.grid.fireEvent('columnmove', index, llen);
}
break;
case 'unlock':
if(llen - 1 != index){
cm.setLocked(index, false, true);
cm.moveColumn(index, llen - 1);
this.grid.fireEvent('columnmove', index, llen - 1);
}else{
cm.setLocked(index, false);
}
break;
case 'help' :
cm.showHelp (index);
break;
default:
return Ext.ux.grid.LockingGridView.superclass.handleHdMenuClick.call(this, item);
}
return true;
},
handleHdDown : function(e, t){
Ext.ux.grid.LockingGridView.superclass.handleHdDown.call(this, e, t);
if(this.grid.enableColLock !== false){
if(Ext.fly(t).hasClass('x-grid3-hd-btn')){
var hd = this.findHeaderCell(t),
index = this.getCellIndex(hd),
ms = this.hmenu.items, cm = this.cm;
ms.get('lock').setDisabled(cm.isLocked(index));
ms.get('unlock').setDisabled(!cm.isLocked(index));
ms.get('help').setDisabled(cm.isHelp(index));
}
}
},
syncHeaderHeight: function(){
var hrow = Ext.fly(this.innerHd).child('tr', true),
lhrow = Ext.fly(this.lockedInnerHd).child('tr', true);
hrow.style.height = 'auto';
lhrow.style.height = 'auto';
var hd = hrow.offsetHeight,
lhd = lhrow.offsetHeight,
height = Math.max(lhd, hd) + 'px';
hrow.style.height = height;
lhrow.style.height = height;
},
updateLockedWidth: function(){
var lw = this.cm.getTotalLockedWidth(),
tw = this.cm.getTotalWidth() - lw,
csize = this.grid.getGridEl().getSize(true),
lp = Ext.isBorderBox ? 0 : this.lockedBorderWidth,
rp = Ext.isBorderBox ? 0 : this.rowBorderWidth,
vw = Math.max(csize.width - lw - lp - rp, 0) + 'px',
so = this.getScrollOffset();
if(!this.grid.autoHeight){
var vh = Math.max(csize.height - this.mainHd.getHeight(), 0) + 'px';
this.lockedScroller.dom.style.height = vh;
this.scroller.dom.style.height = vh;
}
this.lockedWrap.dom.style.width = (lw + rp) + 'px';
this.scroller.dom.style.width = vw;
this.mainWrap.dom.style.left = (lw + lp + rp) + 'px';
if(this.innerHd){
this.lockedInnerHd.firstChild.style.width = lw + 'px';
this.lockedInnerHd.firstChild.firstChild.style.width = lw + 'px';
this.innerHd.style.width = vw;
this.innerHd.firstChild.style.width = (tw + rp + so) + 'px';
this.innerHd.firstChild.firstChild.style.width = tw + 'px';
}
if(this.mainBody){
this.lockedBody.dom.style.width = (lw + rp) + 'px';
this.mainBody.dom.style.width = (tw + rp) + 'px';
}
},
getLockedBody : function(){
return this.lockedBody;
}
});
Ext.ux.grid.LockingColumnModel = Ext.extend(Ext.grid.ColumnModel, {
isHelp : function (colIndex) {
return Ext.isEmpty (this.config[colIndex].helpUrl);
},
showHelp : function (colIndex) {
showHelp (this.config[colIndex].helpUrl);
},
/**
* Returns true if the given column index is currently locked
* @param {Number} colIndex The column index
* @return {Boolean} True if the column is locked
*/
isLocked : function(colIndex){
return this.config[colIndex].locked === true;
},
/**
* Locks or unlocks a given column
* @param {Number} colIndex The column index
* @param {Boolean} value True to lock, false to unlock
* @param {Boolean} suppressEvent Pass false to cause the columnlockchange event not to fire
*/
setLocked : function(colIndex, value, suppressEvent){
if (this.isLocked(colIndex) == value) {
return;
}
this.config[colIndex].locked = value;
if (!suppressEvent) {
this.fireEvent('columnlockchange', this, colIndex, value);
}
},
/**
* Returns the total width of all locked columns
* @return {Number} The width of all locked columns
*/
getTotalLockedWidth : function(){
var totalWidth = 0;
for (var i = 0, len = this.config.length; i < len; i++) {
if (this.isLocked(i) && !this.isHidden(i)) {
totalWidth += this.getColumnWidth(i);
}
}
return totalWidth;
},
/**
* Returns the total number of locked columns
* @return {Number} The number of locked columns
*/
getLockedCount : function() {
var len = this.config.length;
for (var i = 0; i < len; i++) {
if (!this.isLocked(i)) {
return i;
}
}
//if we get to this point all of the columns are locked so we return the total
return len;
},
/**
* Moves a column from one position to another
* @param {Number} oldIndex The current column index
* @param {Number} newIndex The destination column index
*/
moveColumn : function(oldIndex, newIndex){
var oldLocked = this.isLocked(oldIndex),
newLocked = this.isLocked(newIndex);
if (oldIndex < newIndex && oldLocked && !newLocked) {
this.setLocked(oldIndex, false, true);
} else if (oldIndex > newIndex && !oldLocked && newLocked) {
this.setLocked(oldIndex, true, true);
}
Ext.ux.grid.LockingColumnModel.superclass.moveColumn.apply(this, arguments);
}
});
//Ext.ux.grid.LockingGridView = Ext.extend(Ext.grid.GridView, {
// lockText : 'label.lock',
// unlockText : 'label.unlock',
// rowBorderWidth : 1,
// lockedBorderWidth : 1,
// initTemplates : function(){
// var ts = this.templates || {};
// if(!ts.master){
// ts.master = new Ext.Template(
// '<div class="x-grid3" hidefocus="true">',
// '<div class="x-grid3-locked">',
// '<div class="x-grid3-header"><div class="x-grid3-header-inner"><div class="x-grid3-header-offset" style="{lstyle}">{lockedHeader}</div></div><div class="x-clear"></div></div>',
// '<div class="x-grid3-scroller"><div class="x-grid3-body" style="{lstyle}">{lockedBody}</div><div class="x-grid3-scroll-spacer"></div></div>',
// '</div>',
// '<div class="x-grid3-viewport x-grid3-unlocked">',
// '<div class="x-grid3-header"><div class="x-grid3-header-inner"><div class="x-grid3-header-offset" style="{ostyle}">{header}</div></div><div class="x-clear"></div></div>',
// '<div class="x-grid3-scroller"><div class="x-grid3-body" style="{bstyle}">{body}</div><a href="#" class="x-grid3-focus" tabIndex="-1"></a></div>',
// '</div>',
// '<div class="x-grid3-resize-marker"> </div>',
// '<div class="x-grid3-resize-proxy"> </div>',
// '</div>'
// );
// }
// this.templates = ts;
// Ext.ux.grid.LockingGridView.superclass.initTemplates.call(this);
// },
// getEditorParent : function(ed){
// return this.el.dom;
// },
// initElements : function(){
// var E = Ext.Element;
// var el = this.grid.getGridEl().dom.firstChild;
// var cs = el.childNodes;
// this.el = new E(el);
// this.lockedWrap = new E(cs[0]);
// this.lockedHd = new E(this.lockedWrap.dom.firstChild);
// this.lockedInnerHd = this.lockedHd.dom.firstChild;
// this.lockedScroller = new E(this.lockedWrap.dom.childNodes[1]);
// this.lockedBody = new E(this.lockedScroller.dom.firstChild);
// this.mainWrap = new E(cs[1]);
// this.mainHd = new E(this.mainWrap.dom.firstChild);
// if(this.grid.hideHeaders){
// this.lockedHd.setDisplayed(false);
// this.mainHd.setDisplayed(false);
// }
// this.innerHd = this.mainHd.dom.firstChild;
// this.scroller = new E(this.mainWrap.dom.childNodes[1]);
// if(this.forceFit){
// this.scroller.setStyle('overflow-x', 'hidden');
// }
// this.mainBody = new E(this.scroller.dom.firstChild);
// this.focusEl = new E(this.scroller.dom.childNodes[1]);
// this.focusEl.swallowEvent('click', true);
// this.resizeMarker = new E(cs[2]);
// this.resizeProxy = new E(cs[3]);
// },
// getLockedRows : function(){
// return this.hasRows() ? this.lockedBody.dom.childNodes : [];
// },
// getLockedRow : function(row){
// return this.getLockedRows()[row];
// },
// getCell : function(row, col){
// var llen = this.cm.getLockedCount();
// if(col < llen){
// return this.getLockedRow(row).getElementsByTagName('td')[col];
// }
// return Ext.ux.grid.LockingGridView.superclass.getCell.call(this, row, col - llen);
// },
// getHeaderCell : function(index){
// var llen = this.cm.getLockedCount();
// if(index < llen){
// return this.lockedHd.dom.getElementsByTagName('td')[index];
// }
// return Ext.ux.grid.LockingGridView.superclass.getHeaderCell.call(this, index - llen);
// },
// addRowClass : function(row, cls){
// var r = this.getLockedRow(row);
// if(r){
// this.fly(r).addClass(cls);
// }
// Ext.ux.grid.LockingGridView.superclass.addRowClass.call(this, row, cls);
// },
// removeRowClass : function(row, cls){
// var r = this.getLockedRow(row);
// if(r){
// this.fly(r).removeClass(cls);
// }
// Ext.ux.grid.LockingGridView.superclass.removeRowClass.call(this, row, cls);
// },
// removeRow : function(row) {
// Ext.removeNode(this.getLockedRow(row));
// Ext.ux.grid.LockingGridView.superclass.removeRow.call(this, row);
// },
// removeRows : function(firstRow, lastRow){
// var bd = this.lockedBody.dom;
// for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
// Ext.removeNode(bd.childNodes[firstRow]);
// }
// Ext.ux.grid.LockingGridView.superclass.removeRows.call(this, firstRow, lastRow);
// },
// syncScroll : function(e){
// var mb = this.scroller.dom;
// this.lockedScroller.dom.scrollTop = mb.scrollTop;
// Ext.ux.grid.LockingGridView.superclass.syncScroll.call(this, e);
// },
// updateSortIcon : function(col, dir){
// var sc = this.sortClasses,
// lhds = this.lockedHd.select('td').removeClass(sc),
// hds = this.mainHd.select('td').removeClass(sc),
// llen = this.cm.getLockedCount();
// if(col < llen){
// lhds.item(col).addClass(sc[dir == 'DESC' ? 1 : 0]);
// }else{
// hds.item(col - llen).addClass(sc[dir == 'DESC' ? 1 : 0]);
// }
// },
// updateAllColumnWidths : function(){
// var tw = this.getTotalWidth(),
// clen = this.cm.getColumnCount(),
// lw = this.getLockedWidth(),
// llen = this.cm.getLockedCount(),
// ws = [], len, i;
// this.updateLockedWidth();
// for(i = 0; i < clen; i++){
// ws[i] = this.getColumnWidth(i);
// var hd = this.getHeaderCell(i);
// hd.style.width = ws[i];
// }
// var lns = this.getLockedRows(), ns = this.getRows(), row, trow, j;
// for(i = 0, len = ns.length; i < len; i++){
// row = lns[i];
// row.style.width = lw;
// if(row.firstChild){
// row.firstChild.style.width = lw;
// trow = row.firstChild.rows[0];
// for (j = 0; j < llen; j++) {
// trow.childNodes[j].style.width = ws[j];
// }
// }
// row = ns[i];
// row.style.width = tw;
// if(row.firstChild){
// row.firstChild.style.width = tw;
// trow = row.firstChild.rows[0];
// for (j = llen; j < clen; j++) {
// trow.childNodes[j - llen].style.width = ws[j];
// }
// }
// }
// this.onAllColumnWidthsUpdated(ws, tw);
// this.syncHeaderHeight();
// },
// updateColumnWidth : function(col, width){
// var w = this.getColumnWidth(col),
// llen = this.cm.getLockedCount(),
// ns, rw, c, row;
// this.updateLockedWidth();
// if(col < llen){
// ns = this.getLockedRows();
// rw = this.getLockedWidth();
// c = col;
// }else{
// ns = this.getRows();
// rw = this.getTotalWidth();
// c = col - llen;
// }
// var hd = this.getHeaderCell(col);
// hd.style.width = w;
// for(var i = 0, len = ns.length; i < len; i++){
// row = ns[i];
// row.style.width = rw;
// if(row.firstChild){
// row.firstChild.style.width = rw;
// row.firstChild.rows[0].childNodes[c].style.width = w;
// }
// }
// this.onColumnWidthUpdated(col, w, this.getTotalWidth());
// this.syncHeaderHeight();
// },
// updateColumnHidden : function(col, hidden){
// var llen = this.cm.getLockedCount(),
// ns, rw, c, row,
// display = hidden ? 'none' : '';
// this.updateLockedWidth();
// if(col < llen){
// ns = this.getLockedRows();
// rw = this.getLockedWidth();
// c = col;
// }else{
// ns = this.getRows();
// rw = this.getTotalWidth();
// c = col - llen;
// }
// var hd = this.getHeaderCell(col);
// hd.style.display = display;
// for(var i = 0, len = ns.length; i < len; i++){
// row = ns[i];
// row.style.width = rw;
// if(row.firstChild){
// row.firstChild.style.width = rw;
// row.firstChild.rows[0].childNodes[c].style.display = display;
// }
// }
// this.onColumnHiddenUpdated(col, hidden, this.getTotalWidth());
// delete this.lastViewWidth;
// this.layout();
// },
// doRender : function(cs, rs, ds, startRow, colCount, stripe){
// var ts = this.templates, ct = ts.cell, rt = ts.row, last = colCount-1,
// tstyle = 'width:'+this.getTotalWidth()+';',
// lstyle = 'width:'+this.getLockedWidth()+';',
// buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r;
// for(var j = 0, len = rs.length; j < len; j++){
// r = rs[j]; cb = []; lcb = [];
// var rowIndex = (j+startRow);
// for(var i = 0; i < colCount; i++){
// c = cs[i];
// p.id = c.id;
// p.css = (i === 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : '')) +
// (this.cm.config[i].cellCls ? ' ' + this.cm.config[i].cellCls : '');
// p.attr = p.cellAttr = '';
// p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
// p.style = c.style;
// if(Ext.isEmpty(p.value)){
// p.value = ' ';
// }
// if(this.markDirty && r.dirty && Ext.isDefined(r.modified[c.name])){
// p.css += ' x-grid3-dirty-cell';
// }
// if(c.locked){
// lcb[lcb.length] = ct.apply(p);
// }else{
// cb[cb.length] = ct.apply(p);
// }
// }
// var alt = [];
// if(stripe && ((rowIndex+1) % 2 === 0)){
// alt[0] = 'x-grid3-row-alt';
// }
// if(r.dirty){
// alt[1] = ' x-grid3-dirty-row';
// }
// rp.cols = colCount;
// if(this.getRowClass){
// alt[2] = this.getRowClass(r, rowIndex, rp, ds);
// }
// rp.alt = alt.join(' ');
// rp.cells = cb.join('');
// rp.tstyle = tstyle;
// buf[buf.length] = rt.apply(rp);
// rp.cells = lcb.join('');
// rp.tstyle = lstyle;
// lbuf[lbuf.length] = rt.apply(rp);
// }
// return [buf.join(''), lbuf.join('')];
// },
// processRows : function(startRow, skipStripe){
// if(!this.ds || this.ds.getCount() < 1){
// return;
// }
// var rows = this.getRows(),
// lrows = this.getLockedRows();
// skipStripe = skipStripe || !this.grid.stripeRows;
// startRow = startRow || 0;
// Ext.each(rows, function(row, idx){
// var lrow = lrows[idx];
// row.rowIndex = idx;
// lrow.rowIndex = idx;
// if (!skipStripe && (idx + 1) % 2 === 0) {
// row.className = row.className.replace(this.rowClsRe, ' ');
// lrow.className = lrow.className.replace(this.rowClsRe, ' ');
// row.className += ' x-grid3-row-alt';
// lrow.className += ' x-grid3-row-alt';
// }
// }, this);
// if(startRow === 0){
// Ext.fly(rows[0]).addClass(this.firstRowCls);
// Ext.fly(lrows[0]).addClass(this.firstRowCls);
// }
// Ext.fly(rows[rows.length - 1]).addClass(this.lastRowCls);
// Ext.fly(lrows[lrows.length - 1]).addClass(this.lastRowCls);
// },
// afterRender : function(){
// if(!this.ds || !this.cm){
// return;
// }
// var bd = this.renderRows() || [' ', ' '];
// this.mainBody.dom.innerHTML = bd[0];
// this.lockedBody.dom.innerHTML = bd[1];
// this.processRows(0, true);
// if(this.deferEmptyText !== true){
// this.applyEmptyText();
// }
// },
// renderUI : function(){
// var header = this.renderHeaders();
// var body = this.templates.body.apply({rows:' '});
// var html = this.templates.master.apply({
// body: body,
// header: header[0],
// ostyle: 'width:'+this.getOffsetWidth()+';',
// bstyle: 'width:'+this.getTotalWidth()+';',
// lockedBody: body,
// lockedHeader: header[1],
// lstyle: 'width:'+this.getLockedWidth()+';'
// });
// var g = this.grid;
// g.getGridEl().dom.innerHTML = html;
// this.initElements();
// Ext.fly(this.innerHd).on('click', this.handleHdDown, this);
// Ext.fly(this.lockedInnerHd).on('click', this.handleHdDown, this);
// this.mainHd.on({
// scope: this,
// mouseover: this.handleHdOver,
// mouseout: this.handleHdOut,
// mousemove: this.handleHdMove
// });
// this.lockedHd.on({
// scope: this,
// mouseover: this.handleHdOver,
// mouseout: this.handleHdOut,
// mousemove: this.handleHdMove
// });
// this.scroller.on('scroll', this.syncScroll, this);
// if(g.enableColumnResize !== false){
// this.splitZone = new Ext.grid.GridView.SplitDragZone(g, this.mainHd.dom);
// this.splitZone.setOuterHandleElId(Ext.id(this.lockedHd.dom));
// this.splitZone.setOuterHandleElId(Ext.id(this.mainHd.dom));
// }
// if(g.enableColumnMove){
// this.columnDrag = new Ext.grid.GridView.ColumnDragZone(g, this.innerHd);
// this.columnDrag.setOuterHandleElId(Ext.id(this.lockedInnerHd));
// this.columnDrag.setOuterHandleElId(Ext.id(this.innerHd));
// this.columnDrop = new Ext.grid.HeaderDropZone(g, this.mainHd.dom);
// }
// if(g.enableHdMenu !== false){
// this.hmenu = new Ext.menu.Menu({id: g.id + '-hctx'});
// this.hmenu.add(
// {itemId: 'asc', text: this.sortAscText, cls: 'xg-hmenu-sort-asc'},
// {itemId: 'desc', text: this.sortDescText, cls: 'xg-hmenu-sort-desc'}
// );
// if(this.grid.enableColLock !== false){
// this.hmenu.add('-',
// {itemId: 'lock', text: i18n.get (this.lockText), cls: 'xg-hmenu-lock'},
// {itemId: 'unlock', text: i18n.get (this.unlockText), cls: 'xg-hmenu-unlock'}
// );
// }
//
// this.hmenu.add('-',
// {itemId: 'help', text: "help", cls: 'xg-hmenu-help'}
// );
//
// if(g.enableColumnHide !== false){
// this.colMenu = new Ext.menu.Menu({id:g.id + '-hcols-menu'});
// this.colMenu.on({
// scope: this,
// beforeshow: this.beforeColMenuShow,
// itemclick: this.handleHdMenuClick
// });
// this.hmenu.add('-', {
// itemId:'columns',
// hideOnClick: false,
// text: this.columnsText,
// menu: this.colMenu,
// iconCls: 'x-cols-icon'
// });
// }
// this.hmenu.on('itemclick', this.handleHdMenuClick, this);
// }
// if(g.trackMouseOver){
// this.mainBody.on({
// scope: this,
// mouseover: this.onRowOver,
// mouseout: this.onRowOut
// });
// this.lockedBody.on({
// scope: this,
// mouseover: this.onRowOver,
// mouseout: this.onRowOut
// });
// }
// if(g.enableDragDrop || g.enableDrag){
// this.dragZone = new Ext.grid.GridDragZone(g, {
// ddGroup : g.ddGroup || 'GridDD'
// });
// }
// this.updateHeaderSortState();
// },
// layout : function(){
// if(!this.mainBody){
// return;
// }
// var g = this.grid;
// var c = g.getGridEl();
// var csize = c.getSize(true);
// var vw = csize.width;
// if(!g.hideHeaders && (vw < 20 || csize.height < 20)){
// return;
// }
// this.syncHeaderHeight();
// if(g.autoHeight){
// this.scroller.dom.style.overflow = 'visible';
// this.lockedScroller.dom.style.overflow = 'visible';
// if(Ext.isWebKit){
// this.scroller.dom.style.position = 'static';
// this.lockedScroller.dom.style.position = 'static';
// }
// }else{
// this.el.setSize(csize.width, csize.height);
// var hdHeight = this.mainHd.getHeight();
// var vh = csize.height - (hdHeight);
// }
// this.updateLockedWidth();
// if(this.forceFit){
// if(this.lastViewWidth != vw){
// this.fitColumns(false, false);
// this.lastViewWidth = vw;
// }
// }else {
// this.autoExpand();
// this.syncHeaderScroll();
// }
// this.onLayout(vw, vh);
// },
// getOffsetWidth : function() {
// return (this.cm.getTotalWidth() - this.cm.getTotalLockedWidth() + this.getScrollOffset()) + 'px';
// },
// renderHeaders : function(){
// var cm = this.cm,
// ts = this.templates,
// ct = ts.hcell,
// cb = [], lcb = [],
// p = {},
// len = cm.getColumnCount(),
// last = len - 1;
// for(var i = 0; i < len; i++){
// p.id = cm.getColumnId(i);
// p.value = cm.getColumnHeader(i) || '';
// p.style = this.getColumnStyle(i, true);
// p.tooltip = this.getColumnTooltip(i);
// p.css = (i === 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : '')) +
// (cm.config[i].headerCls ? ' ' + cm.config[i].headerCls : '');
// if(cm.config[i].align == 'right'){
// p.istyle = 'padding-right:16px';
// } else {
// delete p.istyle;
// }
// if(cm.isLocked(i)){
// lcb[lcb.length] = ct.apply(p);
// }else{
// cb[cb.length] = ct.apply(p);
// }
// }
// return [ts.header.apply({cells: cb.join(''), tstyle:'width:'+this.getTotalWidth()+';'}),
// ts.header.apply({cells: lcb.join(''), tstyle:'width:'+this.getLockedWidth()+';'})];
// },
// updateHeaders : function(){
// var hd = this.renderHeaders();
// this.innerHd.firstChild.innerHTML = hd[0];
// this.innerHd.firstChild.style.width = this.getOffsetWidth();
// this.innerHd.firstChild.firstChild.style.width = this.getTotalWidth();
// this.lockedInnerHd.firstChild.innerHTML = hd[1];
// var lw = this.getLockedWidth();
// this.lockedInnerHd.firstChild.style.width = lw;
// this.lockedInnerHd.firstChild.firstChild.style.width = lw;
// },
// getResolvedXY : function(resolved){
// if(!resolved){
// return null;
// }
// var c = resolved.cell, r = resolved.row;
// return c ? Ext.fly(c).getXY() : [this.scroller.getX(), Ext.fly(r).getY()];
// },
// syncFocusEl : function(row, col, hscroll){
// Ext.ux.grid.LockingGridView.superclass.syncFocusEl.call(this, row, col, col < this.cm.getLockedCount() ? false : hscroll);
// },
// ensureVisible : function(row, col, hscroll){
// return Ext.ux.grid.LockingGridView.superclass.ensureVisible.call(this, row, col, col < this.cm.getLockedCount() ? false : hscroll);
// },
// insertRows : function(dm, firstRow, lastRow, isUpdate){
// var last = dm.getCount() - 1;
// if(!isUpdate && firstRow === 0 && lastRow >= last){
// this.refresh();
// }else{
// if(!isUpdate){
// this.fireEvent('beforerowsinserted', this, firstRow, lastRow);
// }
// var html = this.renderRows(firstRow, lastRow),
// before = this.getRow(firstRow);
// if(before){
// if(firstRow === 0){
// this.removeRowClass(0, this.firstRowCls);
// }
// Ext.DomHelper.insertHtml('beforeBegin', before, html[0]);
// before = this.getLockedRow(firstRow);
// Ext.DomHelper.insertHtml('beforeBegin', before, html[1]);
// }else{
// this.removeRowClass(last - 1, this.lastRowCls);
// Ext.DomHelper.insertHtml('beforeEnd', this.mainBody.dom, html[0]);
// Ext.DomHelper.insertHtml('beforeEnd', this.lockedBody.dom, html[1]);
// }
// if(!isUpdate){
// this.fireEvent('rowsinserted', this, firstRow, lastRow);
// this.processRows(firstRow);
// }else if(firstRow === 0 || firstRow >= last){
// this.addRowClass(firstRow, firstRow === 0 ? this.firstRowCls : this.lastRowCls);
// }
// }
// this.syncFocusEl(firstRow);
// },
// getColumnStyle : function(col, isHeader){
// var style = !isHeader ? this.cm.config[col].cellStyle || this.cm.config[col].css || '' : this.cm.config[col].headerStyle || '';
// style += 'width:'+this.getColumnWidth(col)+';';
// if(this.cm.isHidden(col)){
// style += 'display:none;';
// }
// var align = this.cm.config[col].align;
// if(align){
// style += 'text-align:'+align+';';
// }
// return style;
// },
// getLockedWidth : function() {
// return this.cm.getTotalLockedWidth() + 'px';
// },
// getTotalWidth : function() {
// return (this.cm.getTotalWidth() - this.cm.getTotalLockedWidth()) + 'px';
// },
// getColumnData : function(){
// var cs = [], cm = this.cm, colCount = cm.getColumnCount();
// for(var i = 0; i < colCount; i++){
// var name = cm.getDataIndex(i);
// cs[i] = {
// name : (!Ext.isDefined(name) ? this.ds.fields.get(i).name : name),
// renderer : cm.getRenderer(i),
// id : cm.getColumnId(i),
// style : this.getColumnStyle(i),
// locked : cm.isLocked(i)
// };
// }
// return cs;
// },
// renderBody : function(){
// var markup = this.renderRows() || [' ', ' '];
// return [this.templates.body.apply({rows: markup[0]}), this.templates.body.apply({rows: markup[1]})];
// },
// refreshRow : function(record){
// Ext.ux.grid.LockingGridView.superclass.refreshRow.call(this, record);
// var index = Ext.isNumber(record) ? record : this.ds.indexOf(record);
// this.getLockedRow(index).rowIndex = index;
// },
// refresh : function(headersToo){
// this.fireEvent('beforerefresh', this);
// this.grid.stopEditing(true);
// var result = this.renderBody();
// this.mainBody.update(result[0]).setWidth(this.getTotalWidth());
// this.lockedBody.update(result[1]).setWidth(this.getLockedWidth());
// if(headersToo === true){
// this.updateHeaders();
// this.updateHeaderSortState();
// }
// this.processRows(0, true);
// this.layout();
// this.applyEmptyText();
// this.fireEvent('refresh', this);
// },
// onDenyColumnLock : function(){
//
// },
// initData : function(ds, cm){
// if(this.cm){
// this.cm.un('columnlockchange', this.onColumnLock, this);
// }
// Ext.ux.grid.LockingGridView.superclass.initData.call(this, ds, cm);
// if(this.cm){
// this.cm.on('columnlockchange', this.onColumnLock, this);
// }
// },
// onColumnLock : function(){
// this.refresh(true);
// },
// handleHdMenuClick : function(item){
// var index = this.hdCtxIndex,
// cm = this.cm,
// id = item.getItemId(),
// llen = cm.getLockedCount();
// switch(id){
// case 'lock':
// if(cm.getColumnCount(true) <= llen + 1){
// this.onDenyColumnLock();
// return;
// }
// if(llen != index){
// cm.setLocked(index, true, true);
// cm.moveColumn(index, llen);
// this.grid.fireEvent('columnmove', index, llen);
// }else{
// cm.setLocked(index, true);
// }
// break;
// case 'unlock':
// if(llen - 1 != index){
// cm.setLocked(index, false, true);
// cm.moveColumn(index, llen - 1);
// this.grid.fireEvent('columnmove', index, llen - 1);
// }else{
// cm.setLocked(index, false);
// }
// break;
// case 'help' :
// cm.showHelp (index);
// break;
// default:
// return Ext.ux.grid.LockingGridView.superclass.handleHdMenuClick.call(this, item);
// }
// return true;
// },
// handleHdDown : function(e, t){
// Ext.ux.grid.LockingGridView.superclass.handleHdDown.call(this, e, t);
// if(this.grid.enableColLock !== false){
// if(Ext.fly(t).hasClass('x-grid3-hd-btn')){
// var hd = this.findHeaderCell(t),
// index = this.getCellIndex(hd),
// ms = this.hmenu.items, cm = this.cm;
// ms.get('lock').setDisabled(cm.isLocked(index));
// ms.get('unlock').setDisabled(!cm.isLocked(index));
// ms.get('help').setDisabled(cm.isHelp(index));
// }
// }
// },
// syncHeaderHeight: function(){
// this.innerHd.firstChild.firstChild.style.height = 'auto';
// this.lockedInnerHd.firstChild.firstChild.style.height = 'auto';
// var hd = this.innerHd.firstChild.firstChild.offsetHeight,
// lhd = this.lockedInnerHd.firstChild.firstChild.offsetHeight,
// height = (lhd > hd ? lhd : hd) + 'px';
// this.innerHd.firstChild.firstChild.style.height = height;
// this.lockedInnerHd.firstChild.firstChild.style.height = height;
// },
// updateLockedWidth: function(){
// var lw = this.cm.getTotalLockedWidth(),
// tw = this.cm.getTotalWidth() - lw,
// csize = this.grid.getGridEl().getSize(true),
// lp = Ext.isBorderBox ? 0 : this.lockedBorderWidth,
// rp = Ext.isBorderBox ? 0 : this.rowBorderWidth,
// vw = (csize.width - lw - lp - rp) + 'px',
// so = this.getScrollOffset();
// if(!this.grid.autoHeight){
// var vh = (csize.height - this.mainHd.getHeight()) + 'px';
// this.lockedScroller.dom.style.height = vh;
// this.scroller.dom.style.height = vh;
// }
// this.lockedWrap.dom.style.width = (lw + rp) + 'px';
// this.scroller.dom.style.width = vw;
// this.mainWrap.dom.style.left = (lw + lp + rp) + 'px';
// if(this.innerHd){
// this.lockedInnerHd.firstChild.style.width = lw + 'px';
// this.lockedInnerHd.firstChild.firstChild.style.width = lw + 'px';
// this.innerHd.style.width = vw;
// this.innerHd.firstChild.style.width = (tw + rp + so) + 'px';
// this.innerHd.firstChild.firstChild.style.width = tw + 'px';
// }
// if(this.mainBody){
// this.lockedBody.dom.style.width = (lw + rp) + 'px';
// this.mainBody.dom.style.width = (tw + rp) + 'px';
// }
// },
// getEl : function(){
// return this.el;
// },
//
// getLockedBody : function(){
// return this.lockedBody;
// }
//});
//
//Ext.ux.grid.LockingColumnModel = Ext.extend(Ext.grid.ColumnModel, {
// isLocked : function(colIndex){
// return this.config[colIndex].locked === true;
// },
// isHelp : function (colIndex) {
// return Ext.isEmpty (this.config[colIndex].helpUrl);
// },
// showHelp : function (colIndex) {
// showHelp (this.config[colIndex].helpUrl);
// },
// setLocked : function(colIndex, value, suppressEvent){
// if(this.isLocked(colIndex) == value){
// return;
// }
// this.config[colIndex].locked = value;
// if(!suppressEvent){
// this.fireEvent('columnlockchange', this, colIndex, value);
// }
// },
// getTotalLockedWidth : function(){
// var totalWidth = 0;
// for(var i = 0, len = this.config.length; i < len; i++){
// if(this.isLocked(i) && !this.isHidden(i)){
// totalWidth += this.getColumnWidth(i);
// }
// }
// return totalWidth;
// },
// getLockedCount : function(){
// for(var i = 0, len = this.config.length; i < len; i++){
// if(!this.isLocked(i)){
// return i;
// }
// }
// },
// moveColumn : function(oldIndex, newIndex){
// if(oldIndex < newIndex && this.isLocked(oldIndex) && !this.isLocked(newIndex)){
// this.setLocked(oldIndex, false, true);
// }else if(oldIndex > newIndex && !this.isLocked(oldIndex) && this.isLocked(newIndex)){
// this.setLocked(oldIndex, true, true);
// }
// Ext.ux.grid.LockingColumnModel.superclass.moveColumn.apply(this, arguments);
// }
//});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
Ext.namespace("Ext.ux");
Ext.ux.NotificationMgr = {
positions: []
};
Ext.ux.Notification = Ext.extend(Ext.Window, {
initComponent: function(){
Ext.apply(this, {
iconCls: this.iconCls || 'x-icon-information',
cls: 'x-notification',
width: 200,
autoHeight: true,
plain: false,
draggable: false,
shadow:false,
bodyStyle: 'text-align:center'
});
if(this.autoDestroy) {
this.task = new Ext.util.DelayedTask(this.hide, this);
} else {
this.closable = true;
}
Ext.ux.Notification.superclass.initComponent.apply(this);
},
setMessage: function(msg){
this.body.update(msg);
},
setTitle: function(title, iconCls){
Ext.ux.Notification.superclass.setTitle.call(this, title, iconCls||this.iconCls);
},
onDestroy: function(){
Ext.ux.NotificationMgr.positions.remove(this.pos);
Ext.ux.Notification.superclass.onDestroy.call(this);
},
cancelHiding: function(){
this.addClass('fixed');
if(this.autoDestroy) {
this.task.cancel();
}
},
afterShow: function(){
Ext.ux.Notification.superclass.afterShow.call(this);
Ext.fly(this.body.dom).on('click', this.cancelHiding, this);
if(this.autoDestroy) {
this.task.delay(this.hideDelay || 5000);
}
},
animShow: function(){
this.pos = 0;
while(Ext.ux.NotificationMgr.positions.indexOf(this.pos)>-1)
this.pos++;
Ext.ux.NotificationMgr.positions.push(this.pos);
this.setSize(200,100);
this.el.alignTo(document, "br-br", [ -20, -140-((this.getSize().height+10)*this.pos) ]);
this.el.slideIn('b', {
duration: 1,
callback: this.afterShow,
scope: this
});
},
animHide: function(){
this.el.ghost("b", {
duration: 1,
remove: false,
callback : function () {
Ext.ux.NotificationMgr.positions.remove(this.pos);
this.destroy();
}.createDelegate(this)
});
},
focus: Ext.emptyFn
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*
* Ext JS Library 3.3.0
* Copyright(c) 2006-2010 Ext JS, Inc.
* licensing@extjs.com
* http://www.extjs.com/license
*/
Ext.ns('Ext.ux.form');
/**
* @class Ext.ux.form.MultiSelect
* @extends Ext.form.Field
* A control that allows selection and form submission of multiple list items.
*
* @history
* 2008-06-19 bpm Original code contributed by Toby Stuart (with contributions from Robert Williams)
* 2008-06-19 bpm Docs and demo code clean up
*
* @constructor
* Create a new MultiSelect
* @param {Object} config Configuration options
* @xtype multiselect
*/
Ext.ux.form.MultiSelect = Ext.extend(Ext.form.Field, {
/**
* @cfg {String} legend Wraps the object with a fieldset and specified legend.
*/
/**
* @cfg {Ext.ListView} view The {@link Ext.ListView} used to render the multiselect list.
*/
/**
* @cfg {String/Array} dragGroup The ddgroup name(s) for the MultiSelect DragZone (defaults to undefined).
*/
/**
* @cfg {String/Array} dropGroup The ddgroup name(s) for the MultiSelect DropZone (defaults to undefined).
*/
/**
* @cfg {Boolean} ddReorder Whether the items in the MultiSelect list are drag/drop reorderable (defaults to false).
*/
ddReorder:false,
/**
* @cfg {Object/Array} tbar The top toolbar of the control. This can be a {@link Ext.Toolbar} object, a
* toolbar config, or an array of buttons/button configs to be added to the toolbar.
*/
/**
* @cfg {String} appendOnly True if the list should only allow append drops when drag/drop is enabled
* (use for lists which are sorted, defaults to false).
*/
appendOnly:false,
/**
* @cfg {Number} width Width in pixels of the control (defaults to 100).
*/
width:100,
/**
* @cfg {Number} height Height in pixels of the control (defaults to 100).
*/
height:100,
/**
* @cfg {String/Number} displayField Name/Index of the desired display field in the dataset (defaults to 0).
*/
displayField:0,
/**
* @cfg {String/Number} valueField Name/Index of the desired value field in the dataset (defaults to 1).
*/
valueField:1,
/**
* @cfg {Boolean} allowBlank False to require at least one item in the list to be selected, true to allow no
* selection (defaults to true).
*/
allowBlank:true,
/**
* @cfg {Number} minSelections Minimum number of selections allowed (defaults to 0).
*/
minSelections:0,
/**
* @cfg {Number} maxSelections Maximum number of selections allowed (defaults to Number.MAX_VALUE).
*/
maxSelections:Number.MAX_VALUE,
/**
* @cfg {String} blankText Default text displayed when the control contains no items (defaults to the same value as
* {@link Ext.form.TextField#blankText}.
*/
blankText:Ext.form.TextField.prototype.blankText,
/**
* @cfg {String} minSelectionsText Validation message displayed when {@link #minSelections} is not met (defaults to 'Minimum {0}
* item(s) required'). The {0} token will be replaced by the value of {@link #minSelections}.
*/
minSelectionsText:'Minimum {0} item(s) required',
/**
* @cfg {String} maxSelectionsText Validation message displayed when {@link #maxSelections} is not met (defaults to 'Maximum {0}
* item(s) allowed'). The {0} token will be replaced by the value of {@link #maxSelections}.
*/
maxSelectionsText:'Maximum {0} item(s) allowed',
/**
* @cfg {String} delimiter The string used to delimit between items when set or returned as a string of values
* (defaults to ',').
*/
delimiter:',',
/**
* @cfg {Ext.data.Store/Array} store The data source to which this MultiSelect is bound (defaults to <tt>undefined</tt>).
* Acceptable values for this property are:
* <div class="mdetail-params"><ul>
* <li><b>any {@link Ext.data.Store Store} subclass</b></li>
* <li><b>an Array</b> : Arrays will be converted to a {@link Ext.data.ArrayStore} internally.
* <div class="mdetail-params"><ul>
* <li><b>1-dimensional array</b> : (e.g., <tt>['Foo','Bar']</tt>)<div class="sub-desc">
* A 1-dimensional array will automatically be expanded (each array item will be the combo
* {@link #valueField value} and {@link #displayField text})</div></li>
* <li><b>2-dimensional array</b> : (e.g., <tt>[['f','Foo'],['b','Bar']]</tt>)<div class="sub-desc">
* For a multi-dimensional array, the value in index 0 of each item will be assumed to be the combo
* {@link #valueField value}, while the value at index 1 is assumed to be the combo {@link #displayField text}.
* </div></li></ul></div></li></ul></div>
*/
// private
defaultAutoCreate : {tag: "div"},
// private
initComponent: function(){
Ext.ux.form.MultiSelect.superclass.initComponent.call(this);
if(Ext.isArray(this.store)){
if (Ext.isArray(this.store[0])){
this.store = new Ext.data.ArrayStore({
fields: ['value','text'],
data: this.store
});
this.valueField = 'value';
}else{
this.store = new Ext.data.ArrayStore({
fields: ['text'],
data: this.store,
expandData: true
});
this.valueField = 'text';
}
this.displayField = 'text';
} else {
this.store = Ext.StoreMgr.lookup(this.store);
this.displayField = this.store.displayField;
this.valueField = this.store.valueField;
}
this.addEvents({
'dblclick' : true,
'click' : true,
'change' : true,
'drop' : true
});
},
// private
onRender: function(ct, position){
Ext.ux.form.MultiSelect.superclass.onRender.call(this, ct, position);
var fs = this.fs = new Ext.form.FieldSet({
renderTo: this.el,
title: this.legend,
height: this.height - 20,
width: this.width,
style: "padding:0;",
tbar: this.tbar
});
fs.body.addClass('ux-mselect');
this.view = new Ext.ListView({
multiSelect: true,
store: this.store,
columns: [{ header: 'Value', width: 1, dataIndex: this.displayField }],
hideHeaders: true
});
fs.add(this.view);
this.view.on('click', this.onViewClick, this);
this.view.on('beforeclick', this.onViewBeforeClick, this);
this.view.on('dblclick', this.onViewDblClick, this);
this.hiddenName = this.name || Ext.id();
var hiddenTag = { tag: "input", type: "hidden", value: "", name: this.hiddenName };
this.hiddenField = this.el.createChild(hiddenTag);
this.hiddenField.dom.disabled = this.hiddenName != this.name;
fs.doLayout();
},
// private
afterRender: function(){
Ext.ux.form.MultiSelect.superclass.afterRender.call(this);
if (this.ddReorder && !this.dragGroup && !this.dropGroup){
this.dragGroup = this.dropGroup = 'MultiselectDD-' + Ext.id();
}
if (this.draggable || this.dragGroup){
this.dragZone = new Ext.ux.form.MultiSelect.DragZone(this, {
ddGroup: this.dragGroup
});
}
if (this.droppable || this.dropGroup){
this.dropZone = new Ext.ux.form.MultiSelect.DropZone(this, {
ddGroup: this.dropGroup
});
}
if (this.values) {
this.setValue(this.values);
}
},
// private
onViewClick: function(vw, index, node, e) {
this.fireEvent('change', this, this.getValue(), this.hiddenField.dom.value);
this.hiddenField.dom.value = this.getValue();
this.fireEvent('click', this, e);
this.validate();
},
// private
onViewBeforeClick: function(vw, index, node, e) {
if (this.disabled || this.readOnly) {
return false;
}
},
// private
onViewDblClick : function(vw, index, node, e) {
return this.fireEvent('dblclick', vw, index, node, e);
},
/**
* Returns an array of data values for the selected items in the list. The values will be separated
* by {@link #delimiter}.
* @return {Array} value An array of string data values
*/
getValue: function(valueField){
var returnArray = [];
var selectionsArray = this.view.getSelectedIndexes();
if (selectionsArray.length == 0) {return '';}
for (var i=0; i<selectionsArray.length; i++) {
var returnValue = this.store.getAt(selectionsArray[i]).get((valueField != null) ? valueField : this.valueField);
if (Ext.isString(returnValue)){
returnValue = returnValue;
}
returnArray.push(returnValue);
} return returnArray.join(this.delimiter);
},
/**
* Sets a delimited string (using {@link #delimiter}) or array of data values into the list.
* @param {String/Array} values The values to set
*/
setValue: function(values) {
var index;
var selections = [];
this.view.clearSelections();
this.hiddenField.dom.value = '';
if (!values || (values == '')) { return; }
if (!Ext.isArray(values)) { values = values.split(this.delimiter); }
for (var i=0; i<values.length; i++) {
index = this.view.store.indexOf(this.view.store.query(this.valueField,
new RegExp('^' + values[i] + '$', "i")).itemAt(0));
selections.push(index);
}
this.view.select(selections);
this.hiddenField.dom.value = this.getValue();
this.validate();
},
// inherit docs
reset : function() {
this.setValue('');
},
// inherit docs
getRawValue: function(valueField) {
var tmp = this.getValue(valueField);
if (tmp.length) {
tmp = tmp.split(this.delimiter);
}
else {
tmp = [];
}
return tmp;
},
// inherit docs
setRawValue: function(values){
setValue(values);
},
// inherit docs
validateValue : function(value){
if (value.length < 1) { // if it has no value
if (this.allowBlank) {
this.clearInvalid();
return true;
} else {
this.markInvalid(this.blankText);
return false;
}
}
if (value.length < this.minSelections) {
this.markInvalid(String.format(this.minSelectionsText, this.minSelections));
return false;
}
if (value.length > this.maxSelections) {
this.markInvalid(String.format(this.maxSelectionsText, this.maxSelections));
return false;
}
return true;
},
// inherit docs
disable: function(){
this.disabled = true;
if (!Ext.isEmpty(this.hiddenField)){
this.hiddenField.dom.disabled = true;
}
if (!Ext.isEmpty(this.fs)){
this.fs.disable();
}
},
// inherit docs
enable: function(){
this.disabled = false;
this.hiddenField.dom.disabled = false;
this.fs.enable();
},
// inherit docs
destroy: function(){
Ext.destroy(this.fs, this.dragZone, this.dropZone);
Ext.ux.form.MultiSelect.superclass.destroy.call(this);
}
});
Ext.reg('multiselect', Ext.ux.form.MultiSelect);
//backwards compat
Ext.ux.Multiselect = Ext.ux.form.MultiSelect;
Ext.ux.form.MultiSelect.DragZone = function(ms, config){
this.ms = ms;
this.view = ms.view;
var ddGroup = config.ddGroup || 'MultiselectDD';
var dd;
if (Ext.isArray(ddGroup)){
dd = ddGroup.shift();
} else {
dd = ddGroup;
ddGroup = null;
}
Ext.ux.form.MultiSelect.DragZone.superclass.constructor.call(this, this.ms.fs.body, { containerScroll: true, ddGroup: dd });
this.setDraggable(ddGroup);
};
Ext.extend(Ext.ux.form.MultiSelect.DragZone, Ext.dd.DragZone, {
onInitDrag : function(x, y){
var el = Ext.get(this.dragData.ddel.cloneNode(true));
this.proxy.update(el.dom);
el.setWidth(el.child('em').getWidth());
this.onStartDrag(x, y);
return true;
},
// private
collectSelection: function(data) {
data.repairXY = Ext.fly(this.view.getSelectedNodes()[0]).getXY();
var i = 0;
this.view.store.each(function(rec){
if (this.view.isSelected(i)) {
var n = this.view.getNode(i);
var dragNode = n.cloneNode(true);
dragNode.id = Ext.id();
data.ddel.appendChild(dragNode);
data.records.push(this.view.store.getAt(i));
data.viewNodes.push(n);
}
i++;
}, this);
},
// override
onEndDrag: function(data, e) {
var d = Ext.get(this.dragData.ddel);
if (d && d.hasClass("multi-proxy")) {
d.remove();
}
},
// override
getDragData: function(e){
var target = this.view.findItemFromChild(e.getTarget());
if(target) {
if (!this.view.isSelected(target) && !e.ctrlKey && !e.shiftKey) {
this.view.select(target);
this.ms.setValue(this.ms.getValue());
}
if (this.view.getSelectionCount() == 0 || e.ctrlKey || e.shiftKey) return false;
var dragData = {
sourceView: this.view,
viewNodes: [],
records: []
};
if (this.view.getSelectionCount() == 1) {
var i = this.view.getSelectedIndexes()[0];
var n = this.view.getNode(i);
dragData.viewNodes.push(dragData.ddel = n);
dragData.records.push(this.view.store.getAt(i));
dragData.repairXY = Ext.fly(n).getXY();
} else {
dragData.ddel = document.createElement('div');
dragData.ddel.className = 'multi-proxy';
this.collectSelection(dragData);
}
return dragData;
}
return false;
},
// override the default repairXY.
getRepairXY : function(e){
return this.dragData.repairXY;
},
// private
setDraggable: function(ddGroup){
if (!ddGroup) return;
if (Ext.isArray(ddGroup)) {
Ext.each(ddGroup, this.setDraggable, this);
return;
}
this.addToGroup(ddGroup);
}
});
Ext.ux.form.MultiSelect.DropZone = function(ms, config){
this.ms = ms;
this.view = ms.view;
var ddGroup = config.ddGroup || 'MultiselectDD';
var dd;
if (Ext.isArray(ddGroup)){
dd = ddGroup.shift();
} else {
dd = ddGroup;
ddGroup = null;
}
Ext.ux.form.MultiSelect.DropZone.superclass.constructor.call(this, this.ms.fs.body, { containerScroll: true, ddGroup: dd });
this.setDroppable(ddGroup);
};
Ext.extend(Ext.ux.form.MultiSelect.DropZone, Ext.dd.DropZone, {
/**
* Part of the Ext.dd.DropZone interface. If no target node is found, the
* whole Element becomes the target, and this causes the drop gesture to append.
*/
getTargetFromEvent : function(e) {
var target = e.getTarget();
return target;
},
// private
getDropPoint : function(e, n, dd){
if (n == this.ms.fs.body.dom) { return "below"; }
var t = Ext.lib.Dom.getY(n), b = t + n.offsetHeight;
var c = t + (b - t) / 2;
var y = Ext.lib.Event.getPageY(e);
if(y <= c) {
return "above";
}else{
return "below";
}
},
// private
isValidDropPoint: function(pt, n, data) {
if (!data.viewNodes || (data.viewNodes.length != 1)) {
return true;
}
var d = data.viewNodes[0];
if (d == n) {
return false;
}
if ((pt == "below") && (n.nextSibling == d)) {
return false;
}
if ((pt == "above") && (n.previousSibling == d)) {
return false;
}
return true;
},
// override
onNodeEnter : function(n, dd, e, data){
return false;
},
// override
onNodeOver : function(n, dd, e, data){
var dragElClass = this.dropNotAllowed;
var pt = this.getDropPoint(e, n, dd);
if (this.isValidDropPoint(pt, n, data)) {
if (this.ms.appendOnly) {
return "x-tree-drop-ok-below";
}
// set the insert point style on the target node
if (pt) {
var targetElClass;
if (pt == "above"){
dragElClass = n.previousSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-above";
targetElClass = "x-view-drag-insert-above";
} else {
dragElClass = n.nextSibling ? "x-tree-drop-ok-between" : "x-tree-drop-ok-below";
targetElClass = "x-view-drag-insert-below";
}
if (this.lastInsertClass != targetElClass){
Ext.fly(n).replaceClass(this.lastInsertClass, targetElClass);
this.lastInsertClass = targetElClass;
}
}
}
return dragElClass;
},
// private
onNodeOut : function(n, dd, e, data){
this.removeDropIndicators(n);
},
// private
onNodeDrop : function(n, dd, e, data){
if (this.ms.fireEvent("drop", this, n, dd, e, data) === false) {
return false;
}
var pt = this.getDropPoint(e, n, dd);
if (n != this.ms.fs.body.dom)
n = this.view.findItemFromChild(n);
if(this.ms.appendOnly) {
insertAt = this.view.store.getCount();
} else {
insertAt = n == this.ms.fs.body.dom ? this.view.store.getCount() - 1 : this.view.indexOf(n);
if (pt == "below") {
insertAt++;
}
}
var dir = false;
// Validate if dragging within the same MultiSelect
if (data.sourceView == this.view) {
// If the first element to be inserted below is the target node, remove it
if (pt == "below") {
if (data.viewNodes[0] == n) {
data.viewNodes.shift();
}
} else { // If the last element to be inserted above is the target node, remove it
if (data.viewNodes[data.viewNodes.length - 1] == n) {
data.viewNodes.pop();
}
}
// Nothing to drop...
if (!data.viewNodes.length) {
return false;
}
// If we are moving DOWN, then because a store.remove() takes place first,
// the insertAt must be decremented.
if (insertAt > this.view.store.indexOf(data.records[0])) {
dir = 'down';
insertAt--;
}
}
for (var i = 0; i < data.records.length; i++) {
var r = data.records[i];
if (data.sourceView) {
data.sourceView.store.remove(r);
}
this.view.store.insert(dir == 'down' ? insertAt : insertAt++, r);
var si = this.view.store.sortInfo;
if(si){
this.view.store.sort(si.field, si.direction);
}
}
return true;
},
// private
removeDropIndicators : function(n){
if(n){
Ext.fly(n).removeClass([
"x-view-drag-insert-above",
"x-view-drag-insert-left",
"x-view-drag-insert-right",
"x-view-drag-insert-below"]);
this.lastInsertClass = "_noclass";
}
},
// private
setDroppable: function(ddGroup){
if (!ddGroup) return;
if (Ext.isArray(ddGroup)) {
Ext.each(ddGroup, this.setDroppable, this);
return;
}
this.addToGroup(ddGroup);
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, i18n,document */
Ext.ns("sitools.common.forms");
/**
* A static method to transform a parameter to a sitools component.
* @static
* @param {} parameter the parameter as stored in the formParameter Model
* @param {string} dataUrl the Url to request eventual data
* @param {string} formId the main formId
* @param {} datasetCm the dataset Column model
* @param {string} context should be dataset or project.
* @return {Ext.Container} the container to include into form
*/
sitools.common.forms.formParameterToComponent = function (parameter, dataUrl, formId, datasetCm, context) {
var valuesToSelect = null;
this.component = null;
var value, values, items, i, component, defaultValues, existsWidgetForParameterCode, selectedValue, minValue, maxValue, disabledDates;
//The name of the constructor
var constructor = eval(parameter.jsUserObject);
component = new constructor ({
parameterId : parameter.id,
values : Ext.isArray(parameter.values) ? parameter.values : [],
code : parameter.code,
type : parameter.type,
label : parameter.label,
height : parameter.height,
widthBox : parameter.width,
valueSelection : parameter.valueSelection,
parentParam : parameter.parentParam,
dataUrl : dataUrl,
autoComplete : parameter.autoComplete,
formId : formId,
dimensionId : parameter.dimensionId,
unit : parameter.unit,
css : parameter.css,
defaultValues : parameter.defaultValues,
extraParams : parameter.extraParams,
datasetCm : datasetCm,
context : context
});
return {
parameter : parameter,
component : component
};
};
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, locale, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.common.forms');
/**
* Object to expose methods to build form Components user objects in dataset Context
* @class sitools.common.forms.DatasetContex
*
*/
sitools.common.forms.DatasetContext = function () {
//sitools.user.forms.components.DatasetContext = function () {
this.context = "dataset";
/**
* Return the unit corresponding to a given column Alias
* @param {} scope the initial config
* @return {} the unit founded
*/
this.getRefUnit = function (scope) {
var columnAlias = scope.code[0];
if (Ext.isEmpty(scope.datasetCm)) {
return;
}
var result;
Ext.each(scope.datasetCm, function(column){
if (column.columnAlias == columnAlias) {
result = column.unit;
}
});
return result;
};
};
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, locale, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.common.forms');
/**
* Object to expose methods to build form Components user objects in project Context
* @class sitools.common.forms.ProjectContext
*
*/
sitools.common.forms.ProjectContext = function () {
//sitools.user.forms.components.ProjectContext = function () {
this.context = "project";
/**
* Return the unit corresponding to a given scope
* @param {} scope the initial config
* @return {} the unit founded
*/
this.getRefUnit = function (scope) {
return scope.unit;
};
};
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, locale, ImageChooser,
showHelp, loadUrl*/
/*
* @include "DatasetContext.js"
* @include "ProjectContext.js"
*/
Ext.namespace('sitools.common.forms');
/**
* Basic factory to return DatasetFactory or ProjectFactory according with context.
* @param {String} context must be "dataset" or project"
* @class sitools.common.forms.ComponentFactory
* @return {}
*/
sitools.common.forms.ComponentFactory = function (context) {
//sitools.user.forms.components.ComponentFactory = function (context) {
if (context == "dataset") {
return new sitools.common.forms.DatasetContext();
}
if (context == "project") {
return new sitools.common.forms.ProjectContext();
}
};
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools*/
Ext.ns('sitools.common.forms');
/**
* Abstract class to build Sitools form components with units.
* @class sitools.common.forms.AbstractWithUnit
* @extends Ext.Container
*/
sitools.common.forms.AbstractWithUnit = Ext.extend(Ext.Container, {
//sitools.component.users.SubSelectionParameters.AbstractComponentsWithUnit = Ext.extend(Ext.Container, {
dimensionId : null,
userUnit : null,
userDimension : null,
initComponent : function () {
this.userDimension = this.dimensionId;
this.userUnit = this.unit;
this.storeUnits = new Ext.data.JsonStore({
id : 'storeUnitSelect',
root : 'dimension.units',
idProperty : 'id',
fields : [ {
name : 'unitName',
type : 'string'
}, {
name : 'label',
type : 'string'
}]
});
sitools.common.forms.AbstractWithUnit.superclass.initComponent.call(this);
},
/**
* Load all units available with a given dimension.
* On Callback : show a {Ext.Window} with the result in a gridPanel
* @param {} event The click event (to get coordinates)
*/
loadUnits : function (event) {
if (!this.unitsLoaded) {
this.storeUnits.removeAll();
Ext.Ajax.request({
method : "GET",
url : loadUrl.get('APP_URL') + loadUrl.get('APP_DIMENSIONS_ADMIN_URL') + '/dimension/' + this.dimensionId,
scope : this,
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (!Json.success) {
Ext.Msg.alert(i18n.get('label.warning'), Json.message);
return;
}
var units = Json.dimension.sitoolsUnits;
this.dimensionName = Json.dimension.name;
for (var i = 0; i < units.length; i++) {
this.storeUnits.add(new Ext.data.Record(units[i]));
}
},
failure : alertFailure,
callback : function () {
this.unitsLoaded = true;
this.showWinUnits(event);
}
});
}
else {
this.showWinUnits(event);
}
},
/**
* Create and show a {Ext.Window} window with the loaded units
* build the gridUnits.
* @param {} event The click event to get coordinates for the window
*/
showWinUnits : function (event) {
var cmUnits = new Ext.grid.ColumnModel({
columns : [ {
header : i18n.get('headers.name'),
dataIndex : 'label',
width : 100
}],
defaults : {
sortable : true,
width : 100
}
});
var smUnits = new Ext.grid.RowSelectionModel({
singleSelect : true
});
this.gridUnits = new Ext.grid.GridPanel({
autoScroll : true,
store : this.storeUnits,
cm : cmUnits,
sm : smUnits,
layout : 'fit',
listeners : {
scope : this,
rowClick : function (grid, rowIndex) {
this.onValidateUnits();
}
}
});
var winUnit = new Ext.Window({
layout : 'fit',
width : 200,
title : i18n.get('title.unitList'),
modal : true,
height : 300,
items : [this.gridUnits],
buttons : [{
text : i18n.get('label.ok'),
handler : this.onValidateUnits,
scope : this
}, {
text : i18n.get('label.cancel'),
scope : winUnit,
handler : function () {
this.ownerCt.ownerCt.close();
}
}]
});
winUnit.show();
winUnit.setPosition(event.getXY()[0], event.getXY()[1]);
},
/**
* update property this.userDimension and this.userUnit, depending on the selected record in this.gridUnits
* update the label of the button withe the new unit
*/
onValidateUnits : function () {
var rec = this.gridUnits.getSelectionModel().getSelected();
if (Ext.isEmpty(rec)) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('label.noSelection'));
return;
}
this.userUnit = rec.data;
this.userDimension = this.dimensionName;
var btn = this.getEl().query("button")[0];
if (! Ext.isEmpty(btn)) {
this.getEl().query("button")[0].update(rec.get('label'));
}
this.gridUnits.ownerCt.close();
},
// /**
// * Return the unit corresponding to a given column Alias
// * @param {String} columnAlias the column Alias to retrieve
// * @return {} the unit founded
// */
// getColumnUnit : function (columnAlias) {
// if (Ext.isEmpty(this.datasetCm)) {
// return;
// }
// var result;
// Ext.each(this.datasetCm, function(column){
// if (column.columnAlias == columnAlias) {
// result = column.unit;
// }
// });
// return result;
// },
/**
* build a {Ext.Container} container with
* <ul><li>a {Ext.Button} button if column unit is not null and administrator defines a dimension</li>
* <li>A simple text if column unit is not null and administrator not defines a dimension</li>
* <li>null when column unit is null</li></ul>
* @return {} null or the builded container
*/
getUnitComponent : function () {
var columnUnit = this.context.getRefUnit(this);
//the administrator defines a dimension for this component
// and the column unit is not null
if (!Ext.isEmpty(this.dimensionId)) {
var btn = new Ext.Button({
scope : this,
text : Ext.isEmpty(columnUnit) ? " " : columnUnit.label,
width : 90,
handler : function (b, e) {
this.loadUnits(e);
//this.userDimension = this.dimensionId;
}
});
unit = new Ext.Container({
layout : "hbox",
layoutConfig : {
pack : "center",
align : "middle"
},
margins : {top:0, right:0, bottom:0, left:10},
width : 100,
items : [btn]
});
}
else {
if (!Ext.isEmpty(columnUnit)) {
unit = new Ext.Container({
html : columnUnit.label,
margins : {top:0, right:0, bottom:0, left:10},
flex : 1
});
}
else {
unit = null;
}
}
return unit;
}
});
/*
* Ext JS Library 3.3.1
* Copyright(c) 2006-2010 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
Ext.ns('Ext.ux.grid');
/**
* @class Ext.ux.grid.RowExpander
* @extends Ext.util.Observable
* Plugin (ptype = 'rowexpander') that adds the ability to have a Column in a grid which enables
* a second row body which expands/contracts. The expand/contract behavior is configurable to react
* on clicking of the column, double click of the row, and/or hitting enter while a row is selected.
*
* @ptype rowexpander
*/
Ext.ux.grid.RowExpander = Ext.extend(Ext.util.Observable, {
/**
* @cfg {Boolean} expandOnEnter
* <tt>true</tt> to toggle selected row(s) between expanded/collapsed when the enter
* key is pressed (defaults to <tt>true</tt>).
*/
expandOnEnter : true,
/**
* @cfg {Boolean} expandOnDblClick
* <tt>true</tt> to toggle a row between expanded/collapsed when double clicked
* (defaults to <tt>true</tt>).
*/
expandOnDblClick : true,
header : '',
width : 20,
sortable : false,
fixed : true,
hideable: false,
menuDisabled : true,
dataIndex : '',
id : 'expander',
lazyRender : true,
enableCaching : true,
constructor: function (config) {
Ext.apply(this, config);
this.addEvents({
/**
* @event beforeexpand
* Fires before the row expands. Have the listener return false to prevent the row from expanding.
* @param {Object} this RowExpander object.
* @param {Object} Ext.data.Record Record for the selected row.
* @param {Object} body body element for the secondary row.
* @param {Number} rowIndex The current row index.
*/
beforeexpand: true,
/**
* @event expand
* Fires after the row expands.
* @param {Object} this RowExpander object.
* @param {Object} Ext.data.Record Record for the selected row.
* @param {Object} body body element for the secondary row.
* @param {Number} rowIndex The current row index.
*/
expand: true,
/**
* @event beforecollapse
* Fires before the row collapses. Have the listener return false to prevent the row from collapsing.
* @param {Object} this RowExpander object.
* @param {Object} Ext.data.Record Record for the selected row.
* @param {Object} body body element for the secondary row.
* @param {Number} rowIndex The current row index.
*/
beforecollapse: true,
/**
* @event collapse
* Fires after the row collapses.
* @param {Object} this RowExpander object.
* @param {Object} Ext.data.Record Record for the selected row.
* @param {Object} body body element for the secondary row.
* @param {Number} rowIndex The current row index.
*/
collapse: true
});
Ext.ux.grid.RowExpander.superclass.constructor.call(this);
if (this.tpl) {
if (typeof this.tpl == 'string') {
this.tpl = new Ext.Template(this.tpl);
}
this.tpl.compile();
}
this.state = {};
this.bodyContent = {};
},
getRowClass : function (record, rowIndex, p, ds) {
p.cols = p.cols - 1;
var content = this.bodyContent[record.id];
if (!content && !this.lazyRender) {
content = this.getBodyContent(record, rowIndex);
}
if (content) {
p.body = content;
}
return this.state[record.id] ? 'x-grid3-row-expanded' : 'x-grid3-row-collapsed';
},
init : function (grid) {
this.grid = grid;
var view = grid.getView();
view.getRowClass = this.getRowClass.createDelegate(this);
view.enableRowBody = true;
grid.on('render', this.onRender, this);
grid.on('destroy', this.onDestroy, this);
},
// @private
onRender : function () {
var grid = this.grid;
var mainBody = grid.getView().mainBody;
mainBody.on('mousedown', this.onMouseDown, this, {delegate: '.x-grid3-row-expander'});
if (this.expandOnEnter) {
this.keyNav = new Ext.KeyNav(this.grid.getGridEl(), {
'enter' : this.onEnter,
scope: this
});
}
if (this.expandOnDblClick) {
grid.on('rowdblclick', this.onRowDblClick, this);
}
},
// @private
onDestroy : function () {
if (this.keyNav) {
this.keyNav.disable();
delete this.keyNav;
}
/*
* A majority of the time, the plugin will be destroyed along with the grid,
* which means the mainBody won't be available. On the off chance that the plugin
* isn't destroyed with the grid, take care of removing the listener.
*/
var mainBody = this.grid.getView().mainBody;
if (mainBody) {
mainBody.un('mousedown', this.onMouseDown, this);
}
},
// @private
onRowDblClick : function (grid, rowIdx, e) {
this.toggleRow(rowIdx);
},
onEnter : function (e) {
var g = this.grid;
var sm = g.getSelectionModel();
var sels = sm.getSelections();
for (var i = 0, len = sels.length; i < len; i++) {
var rowIdx = g.getStore().indexOf(sels[i]);
this.toggleRow(rowIdx);
}
},
getBodyContent : function (record, index) {
if (!this.enableCaching) {
return this.tpl.apply(record.data);
}
var content = this.bodyContent[record.id];
if (!content) {
content = this.tpl.apply(record.data);
this.bodyContent[record.id] = content;
}
return content;
},
onMouseDown : function (e, t) {
e.stopEvent();
var row = e.getTarget('.x-grid3-row');
this.toggleRow(row);
},
renderer : function (v, p, record) {
p.cellAttr = 'rowspan="2"';
return '<div class="x-grid3-row-expander"> </div>';
},
beforeExpand : function (record, body, rowIndex) {
if (this.fireEvent('beforeexpand', this, record, body, rowIndex) !== false) {
if (this.tpl && this.lazyRender) {
body.innerHTML = this.getBodyContent(record, rowIndex);
}
return true;
} else {
return false;
}
},
toggleRow : function (row) {
if (typeof row == 'number') {
row = this.grid.view.getRow(row);
}
this[Ext.fly(row).hasClass('x-grid3-row-collapsed')
? 'expandRow'
: 'collapseRow'](row);
},
expandRow : function (row) {
if (typeof row == 'number') {
row = this.grid.view.getRow(row);
}
var record = this.grid.store.getAt(row.rowIndex);
var body = Ext.DomQuery.selectNode('tr:nth(2) div.x-grid3-row-body',
row);
if (this.beforeExpand(record, body, row.rowIndex)) {
this.state[record.id] = true;
Ext.fly(row).replaceClass('x-grid3-row-collapsed',
'x-grid3-row-expanded');
this.fireEvent('expand', this, record, body, row.rowIndex);
}
},
collapseRow : function (row) {
if (typeof row == 'number') {
row = this.grid.view.getRow(row);
}
var record = this.grid.store.getAt(row.rowIndex);
var body = Ext.fly(row).child('tr:nth(1) div.x-grid3-row-body', true);
if (this.fireEvent('beforecollapse', this, record, body, row.rowIndex) !== false) {
this.state[record.id] = false;
Ext.fly(row).replaceClass('x-grid3-row-expanded',
'x-grid3-row-collapsed');
this.fireEvent('collapse', this, record, body, row.rowIndex);
}
}
});
Ext.preg('rowexpander', Ext.ux.grid.RowExpander);
//backwards compat
Ext.grid.RowExpander = Ext.ux.grid.RowExpander;
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, showResponse, alertFailure*/
Ext.namespace('sitools.widget');
/**
* Basic Box for all admin panels.
* @class sitools.widget.Box
* @extends Ext.Panel
*/
sitools.widget.Box = Ext.extend(Ext.Panel, {
width : '98%',
frame : true,
baseCls : 'x-box',
cls : 'x-box-blue module-root centering',
_title : '',
constructor : function (cfg) {
sitools.widget.Box.superclass.constructor.call(this, Ext.apply({
_title : cfg.label,
_idItem : cfg.idItem
}, cfg));
},
initComponent : function () {
this.items.unshift({
xtype : 'component',
html : this._title,
cls : 'subtitle icon-' + this.idItem
});
sitools.widget.Box.superclass.initComponent.call(this);
}
});
// register type
Ext.reg('s-box', sitools.widget.Box);
/**
* A simple json store with new methods
* @class sitools.widget.JsonStore
* @extends Ext.data.JsonStore
*/
sitools.widget.JsonStore = Ext.extend(Ext.data.JsonStore, {
/**
* dirty : true if one record have been added
* @type Boolean
*/
dirty : false,
/**
* Setter for dirty
* @param {Boolean} value
*/
_setDirty : function (value) {
this.dirty = value;
},
/**
* Get the dirty value
* @return {Boolean}
*/
_getDirty : function () {
return this.dirty;
},
/**
* Set dirty to true
* @param {Array} records the list of records added
*/
add : function (records) {
this.dirty = true;
sitools.widget.JsonStore.superclass.add.call(this, records);
},
/**
* Set dirty to true
* @param {Ext.data.Record} record the record removed
*/
remove : function (record) {
this.dirty = true;
sitools.widget.JsonStore.superclass.remove.call(this, record);
}
});
* A simple Ext.Button with a specific iconCls
* @class sitools.widget.menuButton
* @extends Ext.Button
*/
sitools.widget.menuButton = Ext.extend(Ext.Button, {
constructor : function (config) {
config = Ext.apply({
iconCls : 'menu-button'
}, config);
sitools.widget.menuButton.superclass.constructor.call(this, config);
}
});
Ext.reg('s-menuButton', sitools.widget.menuButton);
/**
* @class TemplateTreeNode
* @extends Ext.tree.AsyncTreeNode
*
*/
sitools.widget.templateTreeNode = function (attributes) {
var tpl;
if (attributes.tpl === undefined) {
tpl = new Ext.Template(
"<div >{text}<b>{nbRecords} records</b><img src='{urlImage}'></img><a style='text-align:right' href='{urlReadme}'>readme</a></div>");
} else {
tpl = attributes.tpl;
}
attributes.text = tpl.apply(attributes);
attributes.leaf = false;
var config = Ext.apply({
children : []
}, attributes);
sitools.widget.templateTreeNode.superclass.constructor.call(this, config);
};
Ext.extend(sitools.widget.templateTreeNode, Ext.tree.AsyncTreeNode, {
});
// add this new node to the list of nodes
Ext.tree.TreePanel.nodeTypes.templateTreeNode = sitools.widget.templateTreeNode;
/**
* Window that contains a tools to sort a store
* @cfg {} pos The position to apply to the window
* @cfg {Ext.data.Store} store the store to sort
* @cfg {} columnModel the dataset ColumnModel to know all columns on wich you can do a sort.
* @class sitools.widget.sortersTool
* @extends Ext.Window
*/
sitools.widget.sortersTool = Ext.extend(Ext.Window, {
initComponent : function () {
var dataCombo = [ [ "", "" ] ];
var columns;
if (! Ext.isEmpty(this.columnModel.columns)) {
var columns = this.columnModel.columns;
}
else {
columns = this.columnModel;
}
Ext.each(columns, function (column) {
dataCombo.push([ column.columnAlias, column.header ]);
});
this.storeCombo = new Ext.data.ArrayStore({
fields : [ "dataIndex", "columnHeader" ],
data : dataCombo
});
this.f = new Ext.form.FormPanel({
padding : 5
});
var sorters = this.store.getSortState(), len;
if (! Ext.isEmpty(sorters)) {
if (Ext.isArray(sorters.sorters)) {
this.sorters = sorters.sorters;
}
else {
this.sorters = [sorters];
}
len = this.sorters.length;
}
else {
this.sorter = [];
len = 3;
}
for (var i = 0; i < len; i++) {
var compositeField = this.buildCompositeField(i);
this.f.add(compositeField);
}
Ext.apply(this, {
title : i18n.get("label.multiSort"),
autoScroll : true,
width : 400,
modal : true,
items : [ this.f ],
buttons : [ {
text : i18n.get('label.add'),
scope : this,
handler : this.onAdd
}, {
text : i18n.get('label.remove'),
scope : this,
handler : this.onRemove
}, {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ]
});
sitools.widget.sortersTool.superclass.initComponent.call(this);
},
/**
* Build a sorters objetct to apply it to a store.
*/
onValidate : function () {
var sorters = [];
Ext.each(this.f.items.items, function (compositeField) {
if (!Ext.isEmpty(compositeField.items.items[0].getValue())) {
sorters.push({
field : compositeField.items.items[0].getValue(),
direction : compositeField.items.items[1].getValue().getGroupValue()
});
}
}, this);
if (sorters.length < 1) {
this.close();
return;
}
else if (sorters.length == 1) {
this.store.sort(sorters[0].field, sorters[0].direction);
}
else {
this.store.sort(sorters);
}
this.close();
},
/**
* Add a new sort option.
* @param {numeric} i the index of the sort option
* @return {Ext.form.CompositeField} the composite field with a comboBox to choose the column and a sort information.
*/
buildCompositeField : function (i) {
var combo = new Ext.form.ComboBox({
typeAhead : true,
name : "field" + 1,
triggerAction : 'all',
lazyRender : true,
mode : 'local',
store : this.storeCombo,
valueField : 'dataIndex',
displayField : 'columnHeader',
flex : 0.6
});
var direction = new Ext.form.RadioGroup({
fieldLabel : i18n.get('label.direction'),
flex : 0.4,
value : 'ASC',
items : [ {
boxLabel : 'ASC',
name : 'direction' + i,
inputValue : 'ASC'
}, {
boxLabel : 'DESC',
name : 'direction' + i,
inputValue : 'DESC'
} ]
});
var compositeField = new Ext.form.CompositeField({
labelWidth : 100,
anchor : '100%',
fieldLabel : i18n.get('label.sortingOrder'),
items : [ combo, direction ]
});
return compositeField;
},
/**
* Called on add button :
* Adds a new sort option.
*/
onAdd : function () {
var i = this.f.items.length;
var compositeField = this.buildCompositeField(i);
this.f.add(compositeField);
this.f.doLayout();
this.doLayout();
},
/**
* Called when remove button is pressed.
* Remove the last sort option.
*/
onRemove : function () {
var i = this.f.items.length - 1;
if (i < 0) {
return;
}
this.f.remove(this.f.getComponent(i));
this.f.doLayout();
this.doLayout();
},
/**
* Fill the panel with the sort configuration of the store.
*/
afterRender : function () {
sitools.widget.sortersTool.superclass.afterRender.call(this);
this.setPosition(this.pos);
var i = 0;
Ext.each(this.sorters, function (sorter) {
var compositeField = this.f.getComponent(i);
compositeField.items.items[0].setValue(sorter.field);
compositeField.items.items[1].setValue(sorter.direction);
i++;
}, this);
}
});
Ext.reg('sitools.widget.sortersTool', sitools.widget.sortersTool);
/**
* Build a window to define filter on a store using Filter API.
* @class sitools.widget.filterTool
* @extends Ext.Window
*/
sitools.widget.filterTool = Ext.extend(Ext.Window, {
paramPrefix : 'filter',
initComponent : function () {
var dataCombo = [ [ "", "" ] ];
var columns;
if (! Ext.isEmpty(this.columnModel.columns)) {
var columns = this.columnModel.columns;
}
else {
columns = this.columnModel;
}
Ext.each(columns, function (column) {
dataCombo.push({
columnAlias : column.columnAlias,
columnHeader : column.header,
columnType : sql2ext.get(column.sqlColumnType)
});
});
this.storeCombo = new Ext.data.JsonStore({
fields : [ "columnAlias", "columnHeader", "columnType" ],
data : dataCombo
});
this.f = new Ext.Panel();
this.filters = this.store.filtersCfg;
var len;
if (! Ext.isEmpty(this.filters)) {
len = this.filters.length;
}
else {
this.filters = [];
len = 3;
}
for (var i = 0; i < len; i++) {
var compositeField = this.buildCompositeField(i);
this.f.add(compositeField);
}
Ext.apply(this, {
title : i18n.get("label.filter"),
autoScroll : true,
width : 400,
modal : true,
items : [ this.f ],
buttons : [ {
text : i18n.get('label.add'),
scope : this,
handler : this.onAdd
}, {
text : i18n.get('label.remove'),
scope : this,
handler : this.onRemove
}, {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ]
});
sitools.widget.sortersTool.superclass.initComponent.call(this);
},
getCompositeField : function (index) {
return this.f.items.items[index];
},
onValidate : function () {
if(Ext.isEmpty(this.store.filters)){
this.store.filters = new sitools.widget.FiltersCollection();
}
this.store.filters.clear();
var filters = [];
var filtersCfg = [];
var i = 0;
var store = this.store;
Ext.each(this.f.items.items, function (compositeField) {
if (!Ext.isEmpty(compositeField.items.items[0].getValue())) {
var filterCmp = compositeField.findBy(function(cmp) {
return cmp.specificType == "filter";
});
var filterValue;
if (!Ext.isEmpty(filterCmp) && ! Ext.isEmpty(filterCmp[0])) {
var filter = filterCmp[0];
//Build the filters for the store query
filterValue = filter.getValue();
Ext.each(filterValue, function (filterValueItem) {
store.filters.add(i++, filterValueItem);
if (!Ext.isEmpty(filterValueItem)) {
filters.push (filterValueItem);
}
});
if (!Ext.isEmpty(filter.getConfig())) {
filtersCfg.push(filter.getConfig());
}
}
}
}, this);
this.store.filtersCfg = filtersCfg;
// this.store.filters = filters;
// var options = this.store.storeOptions() || {};
var options = this.store.lastOptions || {};
//
options.params = options.params || {};
this.cleanParams(options.params);
//var params = this.store.buildQuery(filters);
//set that this a new filter configuration
this.store.isNewFilter = true;
//Ext.apply(options.params, params);
//save the options has last options in the store
//this.store.storeOptions(options);
this.store.load(options);
this.close();
},
cleanParams : function (p) {
// if encoding just delete the property
if (this.encode) {
delete p[this.paramPrefix];
// otherwise scrub the object of filter data
} else {
var regex, key;
regex = new RegExp('^' + this.paramPrefix + '\[[0-9]+\]');
for (key in p) {
if (regex.test(key)) {
delete p[key];
}
}
}
},
buildCompositeField : function (i) {
var combo = new Ext.form.ComboBox({
index : i,
typeAhead : true,
name : "field" + 1,
triggerAction : 'all',
lazyRender : true,
mode : 'local',
store : this.storeCombo,
valueField : 'columnAlias',
displayField : 'columnHeader',
flex : 0.4,
listeners : {
"select" : function (combo, rec, index) {
if (Ext.isEmpty(rec.data.columnAlias)) {
return;
}
var compositeField = combo.ownerCt;
var containerFilter = compositeField.items.items[1];
containerFilter.removeAll();
switch (rec.data.columnType) {
case ("numeric") :
var filter = new sitools.widget.NumericFilter({
columnAlias : rec.data.columnAlias
});
containerFilter.add(filter);
compositeField.setHeight(filter._getHeight());
containerFilter.setHeight(filter._getHeight());
//containerFilter.syncSize();
break;
case ("string") :
var filter = new sitools.widget.StringFilter({
columnAlias : rec.data.columnAlias
});
containerFilter.add(filter);
compositeField.setHeight(filter._getHeight());
containerFilter.setHeight(filter._getHeight());
break;
case ("dateAsString") :
var filter = new sitools.widget.DateFilter({
columnAlias : rec.data.columnAlias
});
containerFilter.add(filter);
compositeField.setHeight(filter._getHeight());
containerFilter.setHeight(filter._getHeight());
break;
default :
var filter = new sitools.widget.StringFilter({
columnAlias : rec.data.columnAlias
});
containerFilter.add(filter);
compositeField.setHeight(filter._getHeight());
containerFilter.setHeight(filter._getHeight());
break;
}
}
}
});
var filter = new Ext.Container({
flex : 0.6
});
var compositeField = new Ext.Container({
layout : "hbox",
items : [ combo, filter ],
style: {
padding: '5px'
}
});
return compositeField;
},
onAdd : function () {
var i = this.f.items.length;
var compositeField = this.buildCompositeField(i);
this.f.add(compositeField);
this.f.doLayout();
this.doLayout();
},
onRemove : function () {
var i = this.f.items.length - 1;
if (i < 0) {
return;
}
this.f.remove(this.f.getComponent(i));
this.f.doLayout();
this.doLayout();
},
afterRender : function () {
sitools.widget.sortersTool.superclass.afterRender.call(this);
this.setPosition(this.pos);
var i = 0;
Ext.each(this.filters, function (filter) {
var compositeField = this.f.getComponent(i);
this.updateFilterUI (compositeField, filter);
i++;
}, this);
},
updateFilterUI : function (container, filter) {
var combo = container.items.items[0];
var store = combo.getStore();
var index = store.find("columnAlias", filter.columnAlias);
if (index)
var rec = store.getAt(index);
combo.setValue(filter.columnAlias);
combo.fireEvent('select', combo, rec, index);
var filterCmp = container.findBy(function(cmp) {
return cmp.specificType == "filter";
});
filterCmp[0].setValue(filter.value);
// console.log(container);
// console.log(filterCmp);
}
});
Ext.reg('sitools.widget.sortersTool', sitools.widget.sortersTool);
/**
* A toolbar with buttons to move rows up or down
*
* @cfg {string} gridId :
* the id of the grid. This is not mandatory if the grid is
* not the scope of the buttons
* @class sitools.widget.GridSorterToolbar
* @extends Ext.Toolbar
*/
sitools.widget.GridSorterToolbar = Ext.extend(Ext.Toolbar, {
initComponent : function () {
sitools.widget.GridSorterToolbar.superclass.initComponent.call(this);
this.add('->', new sitools.widget.GridTop({
gridId : this.gridId
}), new sitools.widget.GridUp({
gridId : this.gridId
}), new sitools.widget.GridDown({
gridId : this.gridId
}), new sitools.widget.GridBottom({
gridId : this.gridId
}));
}
});
Ext.reg('sitools.widget.GridSorterToolbar', sitools.widget.GridSorterToolbar);
/**
* A RowExpander used for plugin grids to add violation informations
* The parameters are the same as the class Ext.ux.grid.RowExpander
*
* @class sitools.admin.resourcesPlugins.violationRowExpander
* @extends Ext.ux.grid.RowExpander
*/
sitools.widget.ViolationRowExpander = Ext.extend(
Ext.ux.grid.RowExpander, {
getRowClass : function (record, index, rowParams, store) {
//call the method from the superclass
var cls = sitools.widget.ViolationRowExpander.superclass.getRowClass.call(this,
record, index, rowParams, store);
//add a class depending on the violation type
var violation = record.get("violation");
if (!Ext.isEmpty(violation)) {
if (violation.level == "CRITICAL") {
cls += " red-row";
} else if (violation.level == "WARNING") {
cls += " orange-row";
}
}
return cls;
}
});
Ext.reg('sitools.widget.ViolationRowExpander', sitools.widget.ViolationRowExpander);
/**
* Color picker on a triggerField *
* @event select when a new color is selected
* @class sitools.widget.colorField
* @extends Ext.form.TriggerField
*/
sitools.widget.colorField = Ext.extend(
Ext.form.TriggerField, {
onTriggerClick : function (e) {
var cp = new Ext.menu.ColorMenu({
scope : this,
handler: function (cm, color) {
this.setValue("#" + color);
this.setFontColor("#" + color);
this.fireEvent("select", this, color);
}
});
cp.showAt(e.getXY());
},
setFontColor : function (color) {
var h2d = function (d) {
return parseInt(d, 16);
};
var value = [
h2d(color.slice(1, 3)),
h2d(color.slice(3, 5)),
h2d(color.slice(5))
];
var avg = (value[0] + value[1] + value[2]) / 3;
this.el.setStyle({
'color' : (avg > 128) ? '#000' : '#FFF',
'background-color' : color,
'background-image' : "none"
});
},
listeners : {
afterrender : function (tf) {
tf.setFontColor(tf.getValue());
}
}
}
)
sitools.widget.DateFieldWithToday = Ext.extend(Ext.form.DateField, {
regToday : new RegExp("^\{\\$TODAY\}"),
invalidTextWithToday : "Impossible to make a date with {0}. A valid example is {$TODAY} + 1",
parseDate : function (value) {
if(!value || Ext.isDate(value)){
return value;
}
//Ajout d'un test sur la valeur pour sortir s'il y a la valeur {$TODAY}
if (this.regToday.test(value)) {
return value;
}
var v = this.safeParse(value, this.format),
af = this.altFormats,
afa = this.altFormatsArray;
if (!v && af) {
afa = afa || af.split("|");
for (var i = 0, len = afa.length; i < len && !v; i++) {
v = this.safeParse(value, afa[i]);
}
}
return v;
},
getErrors : function (value) {
var errors = Ext.form.DateField.superclass.getErrors.apply(this, arguments);
value = this.formatDate(value || this.processValue(this.getRawValue()));
if (value.length < 1) { // if it's blank and textfield didn't flag it then it's valid
return errors;
}
var svalue = value;
// Ne pas parser la date en objet Date si {$TODAY} est présent
var time = false;
if (this.regToday.test(value)) {
try {
value = sitools.common.utils.Date.stringWithTodayToDate(value);
if (!sitools.common.utils.Date.isValidDate(value)) {
throw "";
}
}
catch (err) {
errors.push(String.format(this.invalidTextWithToday, svalue));
return errors;
}
}
else {
value = this.parseDate(value);
}
if (!value) {
errors.push(String.format(this.invalidText, svalue, this.format));
return errors;
}
time = value.getTime();
if (this.minValue && time < this.minValue.clearTime().getTime()) {
errors.push(String.format(this.minText, this.formatDate(this.minValue)));
}
if (this.maxValue && time > this.maxValue.clearTime().getTime()) {
errors.push(String.format(this.maxText, this.formatDate(this.maxValue)));
}
if (this.disabledDays) {
var day = value.getDay();
for(var i = 0; i < this.disabledDays.length; i++) {
if (day === this.disabledDays[i]) {
errors.push(this.disabledDaysText);
break;
}
}
}
var fvalue = this.formatDate(value);
if (this.disabledDatesRE && this.disabledDatesRE.test(fvalue)) {
errors.push(String.format(this.disabledDatesText, fvalue));
}
return errors;
},
setValue : function (date) {
if (this.regToday.test(date)) {
return Ext.form.DateField.superclass.setValue.call(this, date);
}
else {
return Ext.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
}
}
});
sitools.widget.rootTreeLoader = Ext.extend(Ext.tree.TreeLoader, {
createNode : function (attr) {
if (Ext.isEmpty(attr.children)) {
attr.leaf = true;
}
return Ext.tree.TreeLoader.prototype.createNode.call(this, attr);
},
processResponse : function (response, node, callback, scope) {
var json = response.responseText, children, newNode, i = 0, len;
try {
if (!(children = response.responseData)) {
children = Ext.decode(json);
if (this.root) {
if (!this.getRoot) {
this.getRoot = Ext.data.JsonReader.prototype.createAccessor(this.root);
}
children = this.getRoot(children);
}
}
node.beginUpdate();
for (len = children.length; i < len; i++) {
newNode = this.createNode(children[i]);
if (newNode) {
node.appendChild(newNode);
}
}
node.endUpdate();
this.runCallback(callback, scope || node, [ node ]);
} catch (e) {
this.handleFailure(response);
}
},
setUrl : function (url) {
this.url = url;
}
});/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext,window*/
function utils_logout() {
Ext.util.Cookies.set('userLogin', '');
Ext.util.Cookies.set('hashCode', '');
Ext.Ajax.defaultHeaders.Authorization = '';
window.location.reload();
}
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*
* Ext JS Library 3.3.1
* Copyright(c) 2006-2010 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
var ImageChooser = function(config){
this.config = config;
}
ImageChooser.prototype = {
// cache data by image name for easy lookup
lookup : {},
show : function(el, callback){
if(!this.win){
this.initTemplates();
this.store = new Ext.data.JsonStore({
url: this.config.url,
root: 'items',
fields: [
'name', 'url',
{name:'size', type: 'float'},
{name:'lastmod', type:'date', dateFormat:'timestamp'}
],
listeners: {
'load': {fn:function(){ this.view.select(0); }, scope:this, single:true}
}
});
this.store.load();
var formatSize = function(data){
if(data.size < 1024) {
return data.size + " bytes";
} else {
return (Math.round(((data.size*10) / 1024))/10) + " KB";
}
};
var formatData = function(data){
data.shortName = data.name.ellipse(15);
data.sizeString = formatSize(data);
data.dateString = new Date(data.lastmod).format("d/m/Y g:i a");
this.lookup[data.name] = data;
return data;
};
this.view = new Ext.DataView({
tpl: this.thumbTemplate,
id : 'imageChooserDataViewId',
singleSelect: true,
overClass:'x-view-over',
itemSelector: 'div.thumb-wrap',
emptyText : '<div style="padding:10px;">No images match the specified filter</div>',
store: this.store,
listeners: {
'selectionchange': {fn:this.showDetails, scope:this, buffer:100},
'dblclick' : {fn:this.doCallback, scope:this},
'loadexception' : {fn:this.onLoadException, scope:this},
'beforeselect' : {fn:function(view){
return view.store.getRange().length > 0;
}}
},
prepareData: formatData.createDelegate(this)
});
if (!Ext.isEmpty(fp)){
fp.destroy();
}
var fp = new Ext.FormPanel({
fileUpload: true,
frame: true,
formId : 'formUploadId',
autoHeight: true,
bodyStyle: 'padding: 10px 10px 0 10px;',
labelWidth: 50,
defaults: {
anchor: '95%',
allowBlank: false,
msgTarget: 'side'
},
items: [{
xtype: 'fileuploadfield',
id: 'form-file',
// emptyText: 'Select an image',
fieldLabel: 'Photo',
name: 'image',
buttonText: '',
buttonCfg: {
iconCls: 'upload-icon'
}
}],
buttons: [{
text: 'upload',
// scope : this,
handler: function(){
if(fp.getForm().isValid()){
Ext.Ajax.request ({
url : loadUrl.get('APP_URL') + '/upload/?media=json',
form : 'formUploadId',
// isUpload : true,
waitMsg : "wait...",
method : 'PUT',
success : function (response) {
new Ext.ux.Notification({
iconCls: 'x-icon-information',
title: i18n.get('label.information'),
html: i18n.get ('label.imageUploaded'),
autoDestroy: true,
hideDelay: 1000
}).show(document);
Ext.getCmp('imageChooserDataViewId').refresh();
},
failure : function (response){
Ext.Msg.alert (i18n.get('label.error'));
},
callback : function (){
Ext.getCmp('imageChooserDataViewId').getStore().load();
Ext.getCmp('imageChooserDataViewId').refresh();
}
});
}
}
}]
});
var cfg = {
title: i18n.get('label.chooseImage'),
id: 'img-chooser-dlg',
layout: 'border',
minWidth: 500,
minHeight: 450,
modal: true,
// closeAction: 'hide',
border: false,
items:[{
id: 'img-chooser-view',
region: 'center',
autoScroll: true,
items: this.view,
tbar:[{
text: i18n.get ('label.filter')
},{
xtype: 'textfield',
id: 'filter',
selectOnFocus: true,
width: 100,
listeners: {
'render': {fn:function(){
Ext.getCmp('filter').getEl().on('keyup', function(){
this.filter();
}, this, {buffer:500});
}, scope:this}
}
}, ' ', '-', {
text: i18n.get ('label.sortBy')
}, {
id: 'sortSelect',
xtype: 'combo',
typeAhead: true,
triggerAction: 'all',
width: 100,
editable: false,
mode: 'local',
displayField: 'desc',
valueField: 'name',
lazyInit: false,
value: 'name',
store: new Ext.data.ArrayStore({
fields: ['name', 'desc'],
data : [['name', 'Name'],['size', 'File Size'],['lastmod', 'Last Modified']]
}),
listeners: {
'select': {fn:this.sortImages, scope:this}
}
}]
},{
id: 'img-detail-panel',
region: 'east',
split: true,
width: 150,
minWidth: 150,
maxWidth: 250
},{
id: 'img-upload-panel',
title : i18n.get('label.upload'),
region: 'south',
collapsible : true,
autoHeight : true,
// height : 100,
items: [fp]
}],
buttons: [{
id: 'ok-btn',
text: 'OK',
handler: this.doCallback,
scope: this
},{
text: 'Cancel',
handler: function(){ this.win.close(); },
scope: this
}],
keys: {
key: 27, // Esc key
handler: function(){ this.win.close(); },
scope: this
}
};
Ext.apply(cfg, this.config);
this.win = new Ext.Window(cfg);
}
this.reset();
this.win.show(el);
this.callback = callback;
this.animateTarget = el;
},
initTemplates : function(){
this.thumbTemplate = new Ext.XTemplate(
'<tpl for=".">',
'<div class="thumb-wrap" id="{name}">',
'<div class="thumb"><img src="{url}" height="96" width="96" title="{name}"></div>',
'<span>{shortName}</span></div>',
'</tpl>'
);
this.thumbTemplate.compile();
this.detailsTemplate = new Ext.XTemplate(
'<div class="details">',
'<tpl for=".">',
'<img height="96" width="96" src="{url}"><div class="details-info">',
'<b>Image Name:</b>',
'<span>{name}</span>',
'<b>Size:</b>',
'<span>{sizeString}</span>',
'<b>Last Modified:</b>',
'<span>{dateString}</span></div>',
'</tpl>',
'</div>'
);
this.detailsTemplate.compile();
},
showDetails : function(){
var selNode = this.view.getSelectedNodes();
var detailEl = Ext.getCmp('img-detail-panel').body;
if(selNode && selNode.length > 0){
selNode = selNode[0];
Ext.getCmp('ok-btn').enable();
var data = this.lookup[selNode.id];
detailEl.hide();
this.detailsTemplate.overwrite(detailEl, data);
detailEl.slideIn('l', {stopFx:true,duration:.2});
}else{
Ext.getCmp('ok-btn').disable();
detailEl.update('');
}
},
filter : function(){
var filter = Ext.getCmp('filter');
this.view.store.filter('name', filter.getValue());
this.view.select(0);
},
sortImages : function(){
var v = Ext.getCmp('sortSelect').getValue();
this.view.store.sort(v, v == 'name' ? 'asc' : 'desc');
this.view.select(0);
},
reset : function(){
if(this.win.rendered){
Ext.getCmp('filter').reset();
this.view.getEl().dom.scrollTop = 0;
}
this.view.store.clearFilter();
this.view.select(0);
},
doCallback : function(){
var selNode = this.view.getSelectedNodes()[0];
var callback = this.callback;
var lookup = this.lookup;
var config = this.config;
if(selNode && callback){
var data = lookup[selNode.id];
var url = new URL(data.url);
data.url = url.getFile();
callback(data, config);
};
this.win.close();
},
onLoadException : function(v,o){
this.view.getEl().update('<div style="padding:10px;">Error loading images.</div>');
}
};
String.prototype.ellipse = function(maxLength){
if(this.length > maxLength){
return this.substr(0, maxLength-3) + '...';
}
return this;
};
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*
* Ext JS Library 3.3.1
* Copyright(c) 2006-2010 Sencha Inc.
* licensing@sencha.com
* http://www.sencha.com/license
*/
Ext.ns('Ext.ux.form');
/**
* @class Ext.ux.form.FileUploadField
* @extends Ext.form.TextField
* Creates a file upload field.
* @xtype fileuploadfield
*/
Ext.ux.form.FileUploadField = Ext.extend(Ext.form.TextField, {
/**
* @cfg {String} buttonText The button text to display on the upload button (defaults to
* 'Browse...'). Note that if you supply a value for {@link #buttonCfg}, the buttonCfg.text
* value will be used instead if available.
*/
buttonText: 'Browse...',
/**
* @cfg {Boolean} buttonOnly True to display the file upload field as a button with no visible
* text field (defaults to false). If true, all inherited TextField members will still be available.
*/
buttonOnly: false,
/**
* @cfg {Number} buttonOffset The number of pixels of space reserved between the button and the text field
* (defaults to 3). Note that this only applies if {@link #buttonOnly} = false.
*/
buttonOffset: 3,
/**
* @cfg {Object} buttonCfg A standard {@link Ext.Button} config object.
*/
// private
readOnly: true,
/**
* @hide
* @method autoSize
*/
autoSize: Ext.emptyFn,
// private
initComponent: function(){
Ext.ux.form.FileUploadField.superclass.initComponent.call(this);
this.addEvents(
/**
* @event fileselected
* Fires when the underlying file input field's value has changed from the user
* selecting a new file from the system file selection dialog.
* @param {Ext.ux.form.FileUploadField} this
* @param {String} value The file value returned by the underlying file input field
*/
'fileselected'
);
},
// private
onRender : function(ct, position){
Ext.ux.form.FileUploadField.superclass.onRender.call(this, ct, position);
this.wrap = this.el.wrap({cls:'x-form-field-wrap x-form-file-wrap'});
this.el.addClass('x-form-file-text');
this.el.dom.removeAttribute('name');
this.createFileInput();
var btnCfg = Ext.applyIf(this.buttonCfg || {}, {
text: this.buttonText
});
this.button = new Ext.Button(Ext.apply(btnCfg, {
renderTo: this.wrap,
cls: 'x-form-file-btn' + (btnCfg.iconCls ? ' x-btn-icon' : '')
}));
if(this.buttonOnly){
this.el.hide();
this.wrap.setWidth(this.button.getEl().getWidth());
}
this.bindListeners();
this.resizeEl = this.positionEl = this.wrap;
},
bindListeners: function(){
this.fileInput.on({
scope: this,
mouseenter: function() {
this.button.addClass(['x-btn-over','x-btn-focus'])
},
mouseleave: function(){
this.button.removeClass(['x-btn-over','x-btn-focus','x-btn-click'])
},
mousedown: function(){
this.button.addClass('x-btn-click')
},
mouseup: function(){
this.button.removeClass(['x-btn-over','x-btn-focus','x-btn-click'])
},
change: function(){
var v = this.fileInput.dom.value;
this.setValue(v);
this.fireEvent('fileselected', this, v);
}
});
},
createFileInput : function() {
this.fileInput = this.wrap.createChild({
id: this.getFileInputId(),
name: this.name||this.getId(),
cls: 'x-form-file',
tag: 'input',
type: 'file',
size: 1
});
},
reset : function(){
this.fileInput.remove();
this.createFileInput();
this.bindListeners();
Ext.ux.form.FileUploadField.superclass.reset.call(this);
},
// private
getFileInputId: function(){
return this.id + '-file';
},
// private
onResize : function(w, h){
Ext.ux.form.FileUploadField.superclass.onResize.call(this, w, h);
this.wrap.setWidth(w);
if(!this.buttonOnly){
var w = this.wrap.getWidth() - this.button.getEl().getWidth() - this.buttonOffset;
this.el.setWidth(w);
}
},
// private
onDestroy: function(){
Ext.ux.form.FileUploadField.superclass.onDestroy.call(this);
Ext.destroy(this.fileInput, this.button, this.wrap);
},
onDisable: function(){
Ext.ux.form.FileUploadField.superclass.onDisable.call(this);
this.doDisable(true);
},
onEnable: function(){
Ext.ux.form.FileUploadField.superclass.onEnable.call(this);
this.doDisable(false);
},
// private
doDisable: function(disabled){
this.fileInput.dom.disabled = disabled;
this.button.setDisabled(disabled);
},
// private
preFocus : Ext.emptyFn,
// private
alignErrorIcon : function(){
this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
}
});
Ext.reg('fileuploadfield', Ext.ux.form.FileUploadField);
// backwards compat
Ext.form.FileUploadField = Ext.ux.form.FileUploadField;
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n,ImageChooser,document, validate*/
/**
* This triggerField is loading a new ImageChooser onTriggerClick.
* @class Ext.form.SitoolsSelectImage
* @extends Ext.form.TriggerField
*/
Ext.form.SitoolsSelectImage = Ext.extend(Ext.form.TriggerField, {
onTriggerClick : function () {
if (!this.disabled) {
function validate(data, config) {
config.fieldUrl.setValue(data.url);
config.fieldUrl.fireEvent('change', this, data.url, config.fieldUrl.startValue);
}
// console.dir (this);
var chooser = new ImageChooser({
url : loadUrl.get('APP_URL') + '/upload/?media=json',
width : 515,
height : 450,
fieldUrl : this
});
chooser.show(document, validate);
}
}
});
Ext.reg('sitoolsSelectImage', Ext.form.SitoolsSelectImage);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
var loginErrLength = 'Login minimum 4 character !';
var loginErrUnique = 'Login already in use !';
var loginSuccess = 'Login avaliable';
var emailErrFormat = 'Email not valid !';
var emailErrUnique = 'Email already in use !';
var emailSuccess = 'Email valid & avaliable';
Ext.apply(Ext.form.VTypes, {
uniqueloginMask : /[a-z0-9_\.\-@\+]/i,
uniquelogin : function(val) {
if (val.length < 4) {
Ext.apply(Ext.form.VTypes, {
uniqueloginText: loginErrLength
});
return false;
} else {
/*Ext.Ajax.request({
url: 'user/ext_is_unique_login',
method: 'POST',
params: 'login=' + val,
success: function(o) {
if (o.responseText == 0) {
resetLoginValidator(false);
Ext.apply(Ext.form.VTypes, {
uniqueloginText: loginErrUnique
});
return false;
} else {
resetLoginValidator(true);
}
}
});*/
return true;
}
},
uniqueloginText : loginErrUnique,
uniqueemailMask : /[a-z0-9_\.\-@\+]/i,
uniqueemail : function(val) {
var uniqueemail = /^(\w+)([\-+.][\w]+)*@(\w[\-\w]*\.){1,5}([A-Za-z]){2,6}$/;
if (uniqueemail.test(val)) {
/*
Ext.Ajax.request({
url: BASE_URL + 'user/ext_is_unique_email',
method: 'POST',
params: 'email=' + val,
success: function(o) {
if (o.responseText == 0) {
resetEmailValidator(false);
Ext.apply(Ext.form.VTypes, {
uniqueemailText: emailErrUnique
});
} else {
resetEmailValidator(true);
}
}
});*/
return true;
} else {
return false;
}
},
uniqueemailText : emailErrFormat,
password : function(val, field) {
if (field.initialPassField) {
var pwd = Ext.getCmp(field.initialPassField);
return (val == pwd.getValue());
}
return true;
},
passwordText : 'Passwords do not match',
passwordlength : function(val) {
if (val.length < 6 || val.length > 40) {
return false;
} else {
return true;
}
},
passwordlengthText : 'Invalid Password Length. It must be between 6 and 40'
});
function resetLoginValidator(is_error) {
Ext.apply(Ext.form.VTypes, {
uniquelogin : function(val) {
if (val.length < 4) {
Ext.apply(Ext.form.VTypes, {
uniqueloginText: loginErrLength
});
return false;
} else {
/*
Ext.Ajax.request({
url: 'user/ext_is_unique_login',
method: 'POST',
params: 'login=' + val,
success: function(o) {
if (o.responseText == 0) {
resetLoginValidator(false);
} else {
resetLoginValidator(true);
}
}
});
return is_error;
*/return true;
}
}
});
}
function resetEmailValidator(value) {
Ext.apply(Ext.form.VTypes, {
uniqueemail : function(val) {
var uniqueemail = /^(\w+)([\-+.][\w]+)*@(\w[\-\w]*\.){1,5}([A-Za-z]){2,6}$/;
if (uniqueemail.test(val)) {
/*Ext.Ajax.request({
url: BASE_URL + 'user/ext_is_unique_email',
method: 'POST',
params: 'email=' + val,
success: function(o) {
if (o.responseText == 0) {
resetEmailValidator(false);
Ext.apply(Ext.form.VTypes, {
uniqueemailText: emailErrUnique
});
} else {
resetEmailValidator(true);
}
}
});*/return true;
} else {
return false;
}
return (value);
}
});
}
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure*/
Ext.namespace('sitools.component.version');
sitools.component.version.sitoolsVersion = Ext.extend(Ext.Panel, {
layout : 'fit',
version : null,
initComponent : function () {
this.versionUrl = loadUrl.get('APP_URL') + '/version';
var title = new Ext.form.Label({
html : '<h2>SITools2</h2'
});
var logo = new Ext.form.Label({
html : '<img src='+loadUrl.get('APP_URL')+'/res/images/logo_02_tailleMoyenne.png>'
});
var credits = new Ext.form.Label({
html : '<p>Copyright 2010, 2011, 2012 CNES</p>'
});
var website = new Ext.form.Label({
html : '<a href="http://www.sitools2.sourceforge.net">sitools2.sourceforge.net</>'
});
this.versionLabel = new Ext.form.Label({
});
var panelVersion = new Ext.Panel({
title : i18n.get("label.version"),
layout : 'fit',
padding : 10
});
var panelLicence = new Ext.ux.ManagedIFrame.Panel({
title : i18n.get("label.licence"),
layout : 'fit',
defaultSrc : loadUrl.get('APP_URL') + "/res/licences/gpl-3.0.txt"
});
panelVersion.add([logo, title, this.versionLabel, credits, website]);
this.tabs = new Ext.TabPanel({
activeTab: 0,
items: [ panelVersion, panelLicence]
});
this.items = [this.tabs];
this.listeners = {
scope : this,
resize : function (window) {
var size = window.body.getSize();
this.tabs.setSize(size);
}
};
sitools.component.version.sitoolsVersion.superclass.initComponent.call(this);
},
afterRender : function () {
sitools.component.version.sitoolsVersion.superclass.afterRender.apply(this, arguments);
Ext.Ajax.request({
url : this.versionUrl,
method : 'GET',
scope : this,
success : function (ret) {
var json = Ext.decode(ret.responseText);
if (!json.success) {
Ext.Msg.alert(i18n.get('label.warning'), json.message);
return false;
}
this.version = json.version;
this.versionLabel.setText("<h3>Version : " + this.version + "</h3>", false);
//this.doLayout();
},
failure : alertFailure
});
var size = this.ownerCt.body.getSize();
this.tabs.setSize(size);
}
});
function showVersion () {
var versionHelp = Ext.getCmp('winVersionId');
if (!versionHelp) {
var panelHelp = new sitools.component.version.sitoolsVersion();
versionHelp = new Ext.Window({
title : i18n.get('label.version'),
id : 'winVersionId',
items : [panelHelp],
modal : false,
width : 700,
height : 480,
resizable : false,
modal : true,
buttons : [{
text : i18n.get('label.close'),
handler : function () {
this.ownerCt.ownerCt.close();
}
} ]
});
versionHelp.show();
} else {
versionHelp.show();
}
}
/**
* Define a specific DatePicker to offer possibility to choose Hours Minutes and Seconds
* @class Ext.SitoolsDatePicker
* @extends Ext.BoxComponent
*/
Ext.SitoolsDatePicker = Ext.extend(Ext.BoxComponent, {
todayText : 'Today',
/**
* @cfg {String} okText
* The text to display on the ok button (defaults to <code>' OK '</code> to give the user extra clicking room)
*/
okText : ' OK ',
/**
* @cfg {String} cancelText
* The text to display on the cancel button (defaults to <code>'Cancel'</code>)
*/
cancelText : 'Cancel',
/**
* @cfg {Function} handler
* Optional. A function that will handle the select event of this picker.
* The handler is passed the following parameters:<div class="mdetail-params"><ul>
* <li><code>picker</code> : DatePicker<div class="sub-desc">This DatePicker.</div></li>
* <li><code>date</code> : Date<div class="sub-desc">The selected date.</div></li>
* </ul></div>
*/
/**
* @cfg {Object} scope
* The scope (<code><b>this</b></code> reference) in which the <code>{@link #handler}</code>
* function will be called. Defaults to this DatePicker instance.
*/
/**
* @cfg {String} todayTip
* A string used to format the message for displaying in a tooltip over the button that
* selects the current date. Defaults to <code>'{0} (Spacebar)'</code> where
* the <code>{0}</code> token is replaced by today's date.
*/
todayTip : '{0} (Spacebar)',
/**
* @cfg {String} minText
* The error text to display if the minDate validation fails (defaults to <code>'This date is before the minimum date'</code>)
*/
minText : 'This date is before the minimum date',
/**
* @cfg {String} maxText
* The error text to display if the maxDate validation fails (defaults to <code>'This date is after the maximum date'</code>)
*/
maxText : 'This date is after the maximum date',
/**
* @cfg {String} format
* The default date format string which can be overriden for localization support. The format must be
* valid according to {@link Date#parseDate} (defaults to <code>'m/d/y'</code>).
*/
format : 'm/d/y',
/**
* @cfg {String} disabledDaysText
* The tooltip to display when the date falls on a disabled day (defaults to <code>'Disabled'</code>)
*/
disabledDaysText : 'Disabled',
/**
* @cfg {String} disabledDatesText
* The tooltip text to display when the date falls on a disabled date (defaults to <code>'Disabled'</code>)
*/
disabledDatesText : 'Disabled',
/**
* @cfg {Array} monthNames
* An array of textual month names which can be overriden for localization support (defaults to Date.monthNames)
*/
monthNames : Date.monthNames,
/**
* @cfg {Array} dayNames
* An array of textual day names which can be overriden for localization support (defaults to Date.dayNames)
*/
dayNames : Date.dayNames,
/**
* @cfg {String} nextText
* The next month navigation button tooltip (defaults to <code>'Next Month (Control+Right)'</code>)
*/
nextText : 'Next Month (Control+Right)',
/**
* @cfg {String} prevText
* The previous month navigation button tooltip (defaults to <code>'Previous Month (Control+Left)'</code>)
*/
prevText : 'Previous Month (Control+Left)',
/**
* @cfg {String} monthYearText
* The header month selector tooltip (defaults to <code>'Choose a month (Control+Up/Down to move years)'</code>)
*/
monthYearText : 'Choose a month (Control+Up/Down to move years)',
/**
* @cfg {Number} startDay
* Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
*/
startDay : 0,
/**
* @cfg {Boolean} showToday
* False to hide the footer area containing the Today button and disable the keyboard handler for spacebar
* that selects the current date (defaults to <code>true</code>).
*/
showToday : true,
/**
* @cfg {Boolean} showTime
* False to hide the footer area containing the hour definition
* (defaults to <code>false</code>).
*/
showTime : false,
// private
// Set by other components to stop the picker focus being updated when the value changes.
focusOnSelect: true,
// default value used to initialise each date in the DatePicker
// (note: 12 noon was chosen because it steers well clear of all DST timezone changes)
initHour: 12,
initComponent : function(){
Ext.SitoolsDatePicker.superclass.initComponent.call(this);
this.value = this.value ?
this.value.clearTime(true) : new Date().clearTime();
this.hourValue = this.value ? this.value.getHours() : new Date().getHours();
this.minuteValue = this.value ? this.value.getMinutes() : new Date().getMinutes();
this.secondValue = this.value ? this.value.getSeconds() : new Date().getSeconds();
this.addEvents(
'select'
);
if(this.handler){
this.on('select', this.handler, this.scope || this);
}
this.initDisabledDays();
},
// private
initDisabledDays : function(){
if(!this.disabledDatesRE && this.disabledDates){
var dd = this.disabledDates,
len = dd.length - 1,
re = '(?:';
Ext.each(dd, function(d, i){
re += Ext.isDate(d) ? '^' + Ext.escapeRe(d.dateFormat(this.format)) + '$' : dd[i];
if(i != len){
re += '|';
}
}, this);
this.disabledDatesRE = new RegExp(re + ')');
}
},
/**
* Replaces any existing disabled dates with new values and refreshes the DatePicker.
* @param {Array/RegExp} disabledDates An array of date strings (see the {@link #disabledDates} config
* for details on supported values), or a JavaScript regular expression used to disable a pattern of dates.
*/
setDisabledDates : function(dd){
if(Ext.isArray(dd)){
this.disabledDates = dd;
this.disabledDatesRE = null;
}else{
this.disabledDatesRE = dd;
}
this.initDisabledDays();
this.update(this.value, true);
},
/**
* Replaces any existing disabled days (by index, 0-6) with new values and refreshes the DatePicker.
* @param {Array} disabledDays An array of disabled day indexes. See the {@link #disabledDays} config
* for details on supported values.
*/
setDisabledDays : function(dd){
this.disabledDays = dd;
this.update(this.value, true);
},
/**
* Replaces any existing {@link #minDate} with the new value and refreshes the DatePicker.
* @param {Date} value The minimum date that can be selected
*/
setMinDate : function(dt){
this.minDate = dt;
this.update(this.value, true);
},
/**
* Replaces any existing {@link #maxDate} with the new value and refreshes the DatePicker.
* @param {Date} value The maximum date that can be selected
*/
setMaxDate : function(dt){
this.maxDate = dt;
this.update(this.value, true);
},
/**
* Sets the value of the date field
* @param {Date} value The date to set
*/
setValue : function(value){
this.value = value;
this.update(this.value);
},
/**
* Gets the current selected value of the date field
* @return {Date} The selected date
*/
getValue : function(){
return this.value;
},
// private
focus : function(){
this.update(this.activeDate);
if (this.showTime) {
this.updateTime(this.activeDate);
}
},
// private
updateTime : function (date) {
this.hourField.setValue(date.getHours());
this.minuteField.setValue(date.getMinutes());
this.secondField.setValue(date.getSeconds());
},
// private
onEnable: function(initial){
Ext.SitoolsDatePicker.superclass.onEnable.call(this);
this.doDisabled(false);
this.update(initial ? this.value : this.activeDate);
if(Ext.isIE){
this.el.repaint();
}
},
// private
onDisable : function(){
Ext.SitoolsDatePicker.superclass.onDisable.call(this);
this.doDisabled(true);
if(Ext.isIE && !Ext.isIE8){
/* Really strange problem in IE6/7, when disabled, have to explicitly
* repaint each of the nodes to get them to display correctly, simply
* calling repaint on the main element doesn't appear to be enough.
*/
Ext.each([].concat(this.textNodes, this.el.query('th span')), function(el){
Ext.fly(el).repaint();
});
}
},
// private
doDisabled : function(disabled){
this.keyNav.setDisabled(disabled);
this.prevRepeater.setDisabled(disabled);
this.nextRepeater.setDisabled(disabled);
if(this.showToday){
this.todayKeyListener.setDisabled(disabled);
this.todayBtn.setDisabled(disabled);
}
},
// private
onRender : function(container, position){
var m = [
'<table cellspacing="0">',
'<tr><td class="x-date-left"><a href="#" title="', this.prevText ,'"> </a></td><td class="x-date-middle" align="center"></td><td class="x-date-right"><a href="#" title="', this.nextText ,'"> </a></td></tr>',
'<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'],
dn = this.dayNames,
i;
for(i = 0; i < 7; i++){
var d = this.startDay+i;
if(d > 6){
d = d-7;
}
m.push('<th><span>', dn[d].substr(0,1), '</span></th>');
}
m[m.length] = '</tr></thead><tbody><tr>';
for(i = 0; i < 42; i++) {
if(i % 7 === 0 && i !== 0){
m[m.length] = '</tr><tr>';
}
m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
}
m.push('</tr></tbody></table></td></tr>',
this.showTime ? '<tr><td colspan="3" class="x-date-time" align="center"></td></tr>' : '',
this.showToday ? '<tr><td colspan="3" class="x-date-bottom" align="center"></td></tr>' : '',
'</table><div class="x-date-mp"></div>');
var el = document.createElement('div');
el.className = 'x-date-picker';
el.innerHTML = m.join('');
container.dom.insertBefore(el, position);
this.el = Ext.get(el);
this.eventEl = Ext.get(el.firstChild);
this.prevRepeater = new Ext.util.ClickRepeater(this.el.child('td.x-date-left a'), {
handler: this.showPrevMonth,
scope: this,
preventDefault:true,
stopDefault:true
});
this.nextRepeater = new Ext.util.ClickRepeater(this.el.child('td.x-date-right a'), {
handler: this.showNextMonth,
scope: this,
preventDefault:true,
stopDefault:true
});
this.monthPicker = this.el.down('div.x-date-mp');
this.monthPicker.enableDisplayMode('block');
this.keyNav = new Ext.KeyNav(this.eventEl, {
'left' : function(e){
if(e.ctrlKey){
this.showPrevMonth();
}else{
this.update(this.activeDate.add('d', -1));
}
},
'right' : function(e){
if(e.ctrlKey){
this.showNextMonth();
}else{
this.update(this.activeDate.add('d', 1));
}
},
'up' : function(e){
if(e.ctrlKey){
this.showNextYear();
}else{
this.update(this.activeDate.add('d', -7));
}
},
'down' : function(e){
if(e.ctrlKey){
this.showPrevYear();
}else{
this.update(this.activeDate.add('d', 7));
}
},
'pageUp' : function(e){
this.showNextMonth();
},
'pageDown' : function(e){
this.showPrevMonth();
},
'enter' : function(e){
e.stopPropagation();
return true;
},
scope : this
});
//Suppress unselectable option to allow chrome input fields to be modified.
// this.el.unselectable();
this.cells = this.el.select('table.x-date-inner tbody td');
this.textNodes = this.el.query('table.x-date-inner tbody span');
this.mbtn = new Ext.Button({
text: ' ',
tooltip: this.monthYearText,
renderTo: this.el.child('td.x-date-middle', true)
});
this.mbtn.el.child('em').addClass('x-btn-arrow');
if(this.showToday){
this.todayKeyListener = this.eventEl.addKeyListener(Ext.EventObject.SPACE, this.selectToday, this);
var today = (new Date()).dateFormat(this.format);
this.todayBtn = new Ext.Button({
renderTo: this.el.child('td.x-date-bottom', true),
text: String.format(this.todayText, today),
tooltip: String.format(this.todayTip, today),
handler: this.selectToday,
scope: this
});
}
if (this.showTime){
this.hourField = new Ext.form.TextField({
value : this.hourValue,
width : "25"
,
listeners : {
scope : this,
specialkey : function (field, e) {
if (e.getKey() == e.TAB) {
if (e.shiftKey) {
this.secondField.focus();
}
else {
this.minuteField.focus();
}
}
}
}
,
maxLength : 2,
maskRe : /[0-9]/,
disabled : false,
validationEvent : "blur",
validator : function (value) {
var intValue = parseInt(value);
if (!Ext.isEmpty(intValue) && intValue <= 23 && intValue >= 0) {
if (value.length == 1) {
this.setValue("0" + value);
}
return true;
}
else {
return "incorrect Value";
}
}
});
this.minuteField = new Ext.form.TextField({
value : this.minuteValue,
width : "25",
listeners : {
scope : this,
specialkey : function (field, e) {
if (e.getKey() == e.TAB) {
if (e.shiftKey) {
this.hourField.focus();
}
else {
this.secondField.focus();
}
}
}
},
maxLength : 2,
maskRe : /[0-9]/,
validationEvent : "blur",
validator : function (value) {
var intValue = parseInt(value);
if (!Ext.isEmpty(intValue) && intValue <= 59 && intValue >= 0) {
if (value.length == 1) {
this.setValue("0" + value);
}
return true;
}
else {
return "incorrect Value";
}
}
});
this.secondField = new Ext.form.TextField({
value : this.minuteValue,
width : "25",
listeners : {
scope : this,
specialkey : function (field, e) {
if (e.getKey() == e.TAB) {
if (e.shiftKey) {
this.minuteField.focus();
}
else {
this.hourField.focus();
}
}
}
},
maxLength : 2,
maskRe : /[0-9]/,
validationEvent : "blur",
validator : function (value) {
var intValue = parseInt(value);
if (!Ext.isEmpty(intValue) && intValue <= 59 && intValue >= 0) {
if (value.length == 1) {
this.setValue("0" + value);
}
return true;
}
else {
return "incorrect Value";
}
}
});
var sepLabel1 = new Ext.form.DisplayField({
value : ":"
});
var sepLabel2 = new Ext.form.DisplayField({
value : ":"
});
this.timeForm = new Ext.form.FormPanel({
labelWidth : 1,
itemsCls : "sitools-no-margin",
items : [{
xtype : "compositefield",
width : 135,
style : {
padding : "3px"
},
items : [this.hourField, sepLabel1, this.minuteField, sepLabel2, this.secondField]
}],
renderTo : this.el.child('td.x-date-time', true)
});
/**/
}
this.mon(this.eventEl, 'mousewheel', this.handleMouseWheel, this);
this.mon(this.eventEl, 'click', this.handleDateClick, this, {delegate: 'a.x-date-date'});
this.mon(this.mbtn, 'click', this.showMonthPicker, this);
this.onEnable(true);
},
// private
createMonthPicker : function(){
if(!this.monthPicker.dom.firstChild){
var buf = ['<table border="0" cellspacing="0">'];
for(var i = 0; i < 6; i++){
buf.push(
'<tr><td class="x-date-mp-month"><a href="#">', Date.getShortMonthName(i), '</a></td>',
'<td class="x-date-mp-month x-date-mp-sep"><a href="#">', Date.getShortMonthName(i + 6), '</a></td>',
i === 0 ?
'<td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-prev"></a></td><td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-next"></a></td></tr>' :
'<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
);
}
buf.push(
'<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
this.okText,
'</button><button type="button" class="x-date-mp-cancel">',
this.cancelText,
'</button></td></tr>',
'</table>'
);
this.monthPicker.update(buf.join(''));
this.mon(this.monthPicker, 'click', this.onMonthClick, this);
this.mon(this.monthPicker, 'dblclick', this.onMonthDblClick, this);
this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
this.mpYears = this.monthPicker.select('td.x-date-mp-year');
this.mpMonths.each(function(m, a, i){
i += 1;
if((i%2) === 0){
m.dom.xmonth = 5 + Math.round(i * 0.5);
}else{
m.dom.xmonth = Math.round((i-1) * 0.5);
}
});
}
},
// private
showMonthPicker : function(){
if(!this.disabled){
this.createMonthPicker();
var size = this.el.getSize();
this.monthPicker.setSize(size);
this.monthPicker.child('table').setSize(size);
this.mpSelMonth = (this.activeDate || this.value).getMonth();
this.updateMPMonth(this.mpSelMonth);
this.mpSelYear = (this.activeDate || this.value).getFullYear();
this.updateMPYear(this.mpSelYear);
this.monthPicker.slideIn('t', {duration:0.2});
}
},
// private
updateMPYear : function(y){
this.mpyear = y;
var ys = this.mpYears.elements;
for(var i = 1; i <= 10; i++){
var td = ys[i-1], y2;
if((i%2) === 0){
y2 = y + Math.round(i * 0.5);
td.firstChild.innerHTML = y2;
td.xyear = y2;
}else{
y2 = y - (5-Math.round(i * 0.5));
td.firstChild.innerHTML = y2;
td.xyear = y2;
}
this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
}
},
// private
updateMPMonth : function(sm){
this.mpMonths.each(function(m, a, i){
m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
});
},
// private
selectMPMonth : function(m){
},
// private
onMonthClick : function(e, t){
e.stopEvent();
var el = new Ext.Element(t), pn;
if(el.is('button.x-date-mp-cancel')){
this.hideMonthPicker();
}
else if(el.is('button.x-date-mp-ok')){
var d = new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate());
if(d.getMonth() != this.mpSelMonth){
d = new Date(this.mpSelYear, this.mpSelMonth, 1).getLastDateOfMonth();
}
this.update(d);
this.hideMonthPicker();
}
else if((pn = el.up('td.x-date-mp-month', 2))){
this.mpMonths.removeClass('x-date-mp-sel');
pn.addClass('x-date-mp-sel');
this.mpSelMonth = pn.dom.xmonth;
}
else if((pn = el.up('td.x-date-mp-year', 2))){
this.mpYears.removeClass('x-date-mp-sel');
pn.addClass('x-date-mp-sel');
this.mpSelYear = pn.dom.xyear;
}
else if(el.is('a.x-date-mp-prev')){
this.updateMPYear(this.mpyear-10);
}
else if(el.is('a.x-date-mp-next')){
this.updateMPYear(this.mpyear+10);
}
},
// private
onMonthDblClick : function(e, t){
e.stopEvent();
var el = new Ext.Element(t), pn;
if((pn = el.up('td.x-date-mp-month', 2))){
this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
this.hideMonthPicker();
}
else if((pn = el.up('td.x-date-mp-year', 2))){
this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
this.hideMonthPicker();
}
},
// private
hideMonthPicker : function(disableAnim){
if(this.monthPicker){
if(disableAnim === true){
this.monthPicker.hide();
}else{
this.monthPicker.slideOut('t', {duration:0.2});
}
}
},
// private
showPrevMonth : function(e){
this.update(this.activeDate.add('mo', -1));
},
// private
showNextMonth : function(e){
this.update(this.activeDate.add('mo', 1));
},
// private
showPrevYear : function(){
this.update(this.activeDate.add('y', -1));
},
// private
showNextYear : function(){
this.update(this.activeDate.add('y', 1));
},
// private
handleMouseWheel : function(e){
e.stopEvent();
if(!this.disabled){
var delta = e.getWheelDelta();
if(delta > 0){
this.showPrevMonth();
} else if(delta < 0){
this.showNextMonth();
}
}
},
// private
handleDateClick : function(e, t){
e.stopEvent();
if(!this.disabled && t.dateValue && !Ext.fly(t.parentNode).hasClass('x-date-disabled')){
this.cancelFocus = this.focusOnSelect === false;
var date = new Date(t.dateValue);
if (this.showTime) {
date = date.add(Date.HOUR, this.hourField.getValue());
date = date.add(Date.MINUTE, this.minuteField.getValue());
date = date.add(Date.SECOND, this.secondField.getValue());
if (!this.hourField.isValid() || !this.minuteField.isValid() || !this.secondField.isValid()) {
return;
}
}
this.setValue(date);
delete this.cancelFocus;
this.fireEvent('select', this, this.value);
}
},
// private
selectToday : function(){
if(this.todayBtn && !this.todayBtn.disabled){
var dateNow = new Date();
this.setValue(dateNow);
if (this.showTime) {
this.hourField.setValue(dateNow.getHours());
this.minuteField.setValue(dateNow.getMinutes());
this.secondField.setValue(dateNow.getSeconds());
}
this.fireEvent('select', this, this.value);
}
},
// private
update : function(date, forceRefresh){
if(this.rendered){
if (!Ext.isDate(date)) {
date = new Date();
}
var vd = this.activeDate, vis = this.isVisible();
var dateWithoutTime = new Date(date.getTime());
dateWithoutTime.setHours(0);
dateWithoutTime.setMinutes(0);
dateWithoutTime.setMilliseconds(0);
dateWithoutTime.setSeconds(0);
this.activeDate = date;
if(!forceRefresh && vd && this.el){
var t = dateWithoutTime.getTime();
if(vd.getMonth() == dateWithoutTime.getMonth() && vd.getFullYear() == dateWithoutTime.getFullYear()){
this.cells.removeClass('x-date-selected');
this.cells.each(function(c){
if(c.dom.firstChild.dateValue == t){
c.addClass('x-date-selected');
if(vis && !this.cancelFocus){
Ext.fly(c.dom.firstChild).focus(50);
}
return false;
}
}, this);
return;
}
}
var days = date.getDaysInMonth(),
firstOfMonth = date.getFirstDateOfMonth(),
startingPos = firstOfMonth.getDay()-this.startDay;
if(startingPos < 0){
startingPos += 7;
}
days += startingPos;
var pm = date.add('mo', -1),
prevStart = pm.getDaysInMonth()-startingPos,
cells = this.cells.elements,
textEls = this.textNodes,
d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart, this.initHour));
d.setHours(pm.getHours());
d.setMinutes(pm.getMinutes());
d.setSeconds(pm.getSeconds());
today = new Date().getTime(),
sel = date.clearTime(true).getTime(),
min = this.minDate ? this.minDate.clearTime(true) : Number.NEGATIVE_INFINITY,
max = this.maxDate ? this.maxDate.clearTime(true) : Number.POSITIVE_INFINITY,
ddMatch = this.disabledDatesRE,
ddText = this.disabledDatesText,
ddays = this.disabledDays ? this.disabledDays.join('') : false,
ddaysText = this.disabledDaysText,
format = this.format;
if(this.showToday){
var td = new Date().clearTime(),
disable = (td < min || td > max ||
(ddMatch && format && ddMatch.test(td.dateFormat(format))) ||
(ddays && ddays.indexOf(td.getDay()) != -1));
if(!this.disabled){
this.todayBtn.setDisabled(disable);
this.todayKeyListener[disable ? 'disable' : 'enable']();
}
}
var setCellClass = function(cal, cell){
cell.title = '';
var t = d.clearTime(true).getTime();
cell.firstChild.dateValue = t;
if(t == today){
cell.className += ' x-date-today';
cell.title = cal.todayText;
}
if(t == sel){
cell.className += ' x-date-selected';
if(vis){
Ext.fly(cell.firstChild).focus(50);
}
}
if(t < min) {
cell.className = ' x-date-disabled';
cell.title = cal.minText;
return;
}
if(t > max) {
cell.className = ' x-date-disabled';
cell.title = cal.maxText;
return;
}
if(ddays){
if(ddays.indexOf(d.getDay()) != -1){
cell.title = ddaysText;
cell.className = ' x-date-disabled';
}
}
if(ddMatch && format){
var fvalue = d.dateFormat(format);
if(ddMatch.test(fvalue)){
cell.title = ddText.replace('%0', fvalue);
cell.className = ' x-date-disabled';
}
}
};
var i = 0;
for(; i < startingPos; i++) {
textEls[i].innerHTML = (++prevStart);
d.setDate(d.getDate()+1);
cells[i].className = 'x-date-prevday';
setCellClass(this, cells[i]);
}
for(; i < days; i++){
var intDay = i - startingPos + 1;
textEls[i].innerHTML = (intDay);
d.setDate(d.getDate()+1);
cells[i].className = 'x-date-active';
setCellClass(this, cells[i]);
}
var extraDays = 0;
for(; i < 42; i++) {
textEls[i].innerHTML = (++extraDays);
d.setDate(d.getDate()+1);
cells[i].className = 'x-date-nextday';
setCellClass(this, cells[i]);
}
this.mbtn.setText(this.monthNames[date.getMonth()] + ' ' + date.getFullYear());
if(!this.internalRender){
var main = this.el.dom.firstChild,
w = main.offsetWidth;
this.el.setWidth(w + this.el.getBorderWidth('lr'));
Ext.fly(main).setWidth(w);
this.internalRender = true;
if(Ext.isOpera && !this.secondPass){
main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + 'px';
this.secondPass = true;
this.update.defer(10, this, [date]);
}
}
}
},
// private
beforeDestroy : function() {
if(this.rendered){
Ext.destroy(
this.keyNav,
this.monthPicker,
this.eventEl,
this.mbtn,
this.nextRepeater,
this.prevRepeater,
this.cells.el,
this.todayBtn
);
delete this.textNodes;
delete this.cells.elements;
}
}
});
Ext.reg('datepicker', Ext.SitoolsDatePicker);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, Digest, window*/
// GLOBAL BEHAVIOUR
var DEFAULT_NATIVEJSON = false; // can be set to true if greater than FF 3.5, IE
// 8, Opera 10.5, Webkit-based browsers
var DEFAULT_TIMEOUT = 30000; // server request timeout (msec)
var DEFAULT_TIMEBUF = 10; // time to wait before sending request (msec)
var DEFAULT_NBRETRY = 0;// 3; // nb of request retries (if failure)
var LOCALE = 'en';
var DEFAULT_HELP_WIDTH = 600;
var DEFAULT_HELP_HEIGHT = 400;
var ADMIN_PANEL_HEIGHT = 300;
var ADMIN_PANEL_NB_ELEMENTS = 10;
var SHOW_HELP = true;
var COOKIE_DURATION = 20;
var SITOOLS_DATE_FORMAT = 'Y-m-d\\TH:i:s.u';
var SITOOLS_DEFAULT_IHM_DATE_FORMAT = 'Y-m-d H:i:s.u';
var JAVA_TYPES = [{
name : "String"
}, {
name : "Date"
}, {
name : "Double"
}, {
name : "Float"
}, {
name : "Integer"
}, {
name : "Boolean"
}, {
name : "BasicDBObject"
}, {
name : "BasicDBList"
}];
Ext.Ajax.defaultHeaders = {
"Accept" : "application/json",
"X-User-Agent" : "Sitools"
};
var onBeforeRequest = function (conn, options) {
var date = new Date();
if (!Ext.isEmpty(Ext.util.Cookies.get('scheme'))) {
if (Ext.util.Cookies.get('scheme') == "HTTP_Digest") {
var tmp = null;
var method = "GET";
if (!Ext.isEmpty(options.method)) {
method = options.method;
}
var url = options.url;
if (Ext.isEmpty(options.url) && !Ext.isEmpty(options.scope)) {
if (!Ext.isEmpty(options.scope.url)) {
url = options.scope.url;
}
}
var A1 = Ext.util.Cookies.get("A1");
var auth = new Digest({
usr : Ext.util.Cookies.get("userLogin"),
algorithm : Ext.util.Cookies.get("algorithm"),
realm : Ext.util.Cookies.get("realm"),
url : url,
nonce : Ext.util.Cookies.get('nonce'),
method : method,
mode : "digest",
A1 : A1
});
Ext.apply(Ext.Ajax.defaultHeaders, {
Authorization : auth.getDigestAuth()
});
}
else {
if (!Ext.isEmpty(Ext.util.Cookies.get('hashCode'))) {
Ext.util.Cookies.set('hashCode', Ext.util.Cookies.get('hashCode'), date.add(Date.MINUTE, COOKIE_DURATION));
Ext.apply(Ext.Ajax.defaultHeaders, {
Authorization : Ext.util.Cookies.get('hashCode')
});
}
}
}
if (!Ext.isEmpty(Ext.util.Cookies.get('userLogin'))) {
Ext.util.Cookies.set('userLogin', Ext.util.Cookies.get('userLogin'), date.add(Date.MINUTE, 20));
}
};
Ext.Ajax.on('beforerequest', onBeforeRequest, this);
/**
* Method called if any Ajax Request has an error status.
* The attribute doNotHandleRequestexception of the options parameter can be used to true in order to do nothing in this method
* @param {Connection} conn the connection object
* @param {Object] response The XHR object containing the response data. See The XMLHttpRequest Object for details.
* @param {Object} options The options config object passed to the request method.
*/
var onRequestException = function (conn, response, options) {
// if the parameter doNotHandleRequestexception was set in the options, do nothing
if (!options.doNotHandleRequestexception) {
// si on a un cookie de session et une erreur 403
if ((response.status == 403) && !Ext.isEmpty(Ext.util.Cookies.get('hashCode'))) {
Ext.MessageBox.minWidth = 360;
Ext.MessageBox.alert(i18n.get('label.session.expired'), response.responseText);
} else {
Ext.MessageBox.minWidth = 360;
Ext.MessageBox.alert(i18n.get('label.error'), response.responseText);
}
}
};
Ext.Ajax.on('requestexception', onRequestException, this);
var helpUrl;
Ext.BLANK_IMAGE_URL = '/sitools/cots/extjs/resources/images/default/s.gif';
Ext.USE_NATIVE_JSON = DEFAULT_NATIVEJSON;
Ext.Ajax.timeout = DEFAULT_TIMEOUT;
// Default headers to pass in every request
// Application d'exception sur tous les JsonStores :
// Ext.override (Ext.data.JsonStore, {
// listeners : {
// exception : function (dataProxy, type, action, options, response){
// Ext.Msg.alert (i18n.get('label.warning'), response.responseText);
// }
// }
// });
// GLOBAL PANELS
var treePanel, mainPanel, helpPanel;
var SERVER_OK = 200;
var predicatOperators = {
operators : [[ 'EQ', '=' ], [ 'GT', '>' ], [ 'GTE', '>=' ], [ 'LT', '<' ], [ 'LTE', '<=' ], [ 'LIKE', 'like' ],
[ 'NE', '!=' ]],
getOperatorValueForServer : function (clientValue){
var value = null;
Ext.each(this.operators, function (operator) {
if (operator[1] == clientValue) {
value = operator[0];
return false;
}
}, this);
return value;
},
getOperatorValueForClient : function(serverValue) {
var value = null;
Ext.each(this.operators, function (operator) {
if (operator[0] == serverValue) {
value = operator[1];
return false;
}
}, this);
return value;
}
};
/**
* Open a basic alert popup that shows the repsonse Message
* @param {string} response the server response
* @param {} opts the options of the Ajax Call
*/
function alertFailure(response, opts) {
var txt;
if (response.status == SERVER_OK) {
var ret = Ext.decode(response.responseText).message;
txt = i18n.get('msg.error') + ': ' + i18n.get(ret);
} else {
txt = i18n.get('warning.serverError') + ': ' + i18n.get(response.statusText);
}
Ext.Msg.alert(i18n.get('label.warning'), txt);
}
function showResponse(ret) {
try {
var Json = Ext.decode(ret.responseText);
if (!Json.success) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get(Json.message));
return false;
}
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get(Json.message),
autoDestroy : true,
hideDelay : 1000
}).show(document);
return true;
} catch (err) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.javascriptError') + " : " + err);
return false;
}
}
//Basic formFields Validation
Ext.apply(Ext.form.VTypes, {
'name': function () {
var re = new RegExp("^.*[!\"#$%&\'()*+,:;<=>?@\\`{}|~/]+.*$");
return function (v) {
return ! re.test(v);
};
}(),
'nameText' : "Invalid caracters : should not contain . * [ ! \" # $ % & ' ( ) * + , : ; < = > ? @ \ ` { } | ~ / ] + . * $",
'image' : function () {
var re = new RegExp("^[http://]+[/:a-zA-Z0-9-_]+.*(jpg|gif|png|bmp|ico)$");
return function (v) {
return re.test(v);
};
}(),
'imageText' : "Invalid image URL : should start with http and finish with a image extension",
'attachment' : function () {
var re1 = new RegExp("^/.*$");
var re2 = new RegExp("^.*//.*$");
var re3 = new RegExp("^.*[!\"#$%&\'()*+,:;<=>?@\\`{}|~]+.*$");
return function (v) {
return (re1.test(v) && ! re2.test(v) && !re3.test(v));
};
}(),
'attachmentText' : "invalid Attachment : should not contain ! \" # $ % & ' ( ) * + , : ; < = > ? @ \ ` { } | ~ ] + . * and must begin with /",
'nameWithoutSpace': function () {
var re = new RegExp("^.*[!\"#$%&\'()*+,:;<=>?@\\`{}|~ ]+.*$");
return function (v) {
return ! re.test(v);
};
}(),
'nameWithoutSpaceText' : i18n.get('label.invalidCharacters'),
'withoutSpace': function () {
var re = new RegExp("^.*[ ]+.*$");
return function (v) {
return ! re.test(v);
};
}(),
'withoutSpaceText' : i18n.get('label.invalidCharacters'),
'uri' : function () {
var re = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
var regEspace = new RegExp("^.*[ ]+$");
return function (v) {
return re.test(v) && !regEspace.test(v);
};
}(),
'uriText' : "The format of the URL is invalid, should start with http, ftp or https and finish without space"
});
Ext.override(Ext.grid.GridPanel, {
stripeRows : true
});
//override the spinnerField to use validation when spining
Ext.override(Ext.ux.Spinner, {
spin: function (down, alternate) {
var v = parseFloat(this.field.getValue());
var incr = (alternate === true) ? this.alternateIncrementValue : this.incrementValue;
if (down === true) {
v -= incr;
}
else {
v += incr;
}
v = (isNaN(v)) ? this.defaultValue : v;
v = this.fixBoundries(v);
//use setValue instead of setRawValue to use validator
this.field.setValue(v);
}
});
/**
* Add a tooltip on every form field: tooltip could be an object like tooltip : {
* text : string width : number }, or a simple string
*/
Ext.override(Ext.form.Field, {
tooltip : null,
listeners : {
render: function () {
Ext.form.Field.superclass.render.apply(this, arguments);
if (!Ext.isEmpty(this.tooltip)) {
var ttConfig = {};
if (Ext.isString(this.tooltip)) {
ttConfig = {
html : this.tooltip,
width : 200,
dismissDelay : 5000
};
}
else if (Ext.isObject(this.tooltip)) {
ttConfig = this.tooltip;
} else {
return;
}
Ext.apply(ttConfig, {
target : this.el
});
this.tTip = new Ext.ToolTip(ttConfig);
}
}
}
});
//
function onClickOption(urloption) {
// CHROME : OK
// Ext.Ajax.request({
// url : urloption + "?media=text/html",
// method : "OPTIONS",
// success : function(response) {
// OpenWindow = window.open("", urloption);
// OpenWindow.document.write(response.responseText);
// OpenWindow.document.close();
// },
// failure : function(response) { },
// scope:this
// });
// SOUS FIREFOX PB : preferer le tunneling si autorisation.
var urltunnel = urloption + "?method=options&media=text/html";
var saved = Ext.Ajax.defaultHeaders.Authorization;
Ext.Ajax.defaultHeaders.Authorization = '';
var savedScheme = Ext.util.Cookies.get('scheme');
var savedHashCode = Ext.util.Cookies.get('hashCode');
Ext.util.Cookies.set('scheme', null);
Ext.util.Cookies.set('hashCode', null);
Ext.Ajax.un('requestexception', onRequestException, this);
Ext.Ajax.request({
url : urltunnel,
headers : {
'Authorization' : 'none'
},
method : "GET",
success : function (response) {
if (response.status == 200) {
var OpenWindow = window.open(urltunnel);
}
// SINON ? ...
Ext.Ajax.defaultHeaders.Authorization = saved;
Ext.util.Cookies.set('scheme', savedScheme);
Ext.util.Cookies.set('hashCode', savedHashCode);
Ext.Ajax.on('requestexception', onRequestException, this);
},
callback : function () {
Ext.util.Cookies.set('scheme', savedScheme);
Ext.util.Cookies.set('hashCode', savedHashCode);
Ext.Ajax.on('requestexception', onRequestException, this);
},
failure : function (response) {
Ext.Ajax.defaultHeaders.Authorization = saved;
Ext.util.Cookies.set('scheme', savedScheme);
Ext.util.Cookies.set('hashCode', savedHashCode);
if (response.status == 403) {
Ext.Ajax.request({
url : urloption + "?media=text/html",
method : "OPTIONS",
success : function (response) {
var OpenWindow = window.open("", urloption);
OpenWindow.document.write(response.responseText);
OpenWindow.document.close();
},
failure : function (response) {
},
scope : this
});
} // SINON ? ...
Ext.Ajax.on('requestexception', onRequestException, this);
},
scope : this
//the scope in which to execute the callbacks
});
}
function includeJs(url) {
if (Ext.isEmpty(url)) {
return;
}
var trouve = false;
var targetEl = "script";
var targetAttr = "src";
var scripts = document.getElementsByTagName(targetEl);
var script;
for (var i = scripts.length; i > 0; i--) {
script = scripts[i - 1];
if (script && script.getAttribute(targetAttr) !== null && script.getAttribute(targetAttr).indexOf(url) != -1) {
trouve = true;
}
}
if (!trouve) {
var head = document.getElementsByTagName('head')[0];
script = document.createElement('script');
script.setAttribute('src', url);
script.setAttribute('type', 'text/javascript');
head.appendChild(script);
}
}
function includeJsForceOrder(ConfUrls, indexAInclure) {
//Test if all inclusions are done for this module
if (indexAInclure < ConfUrls.length) {
// if not : include the Js Script
var DSLScript = document.createElement("script");
DSLScript.type = "text/javascript";
DSLScript.onload = includeJsForceOrder.createDelegate(this, [ ConfUrls, indexAInclure + 1 ]);
DSLScript.onreadystatechange = includeJsForceOrder.createDelegate(this, [ ConfUrls, indexAInclure + 1 ]);
DSLScript.src = ConfUrls[indexAInclure].url;
var headID = document.getElementsByTagName('head')[0];
headID.appendChild(DSLScript);
}
}
Ext.override(Ext.PagingToolbar, {
initComponent : function () {
var T = Ext.Toolbar;
var pagingItems = [this.first = new T.Button({
tooltip: this.firstText,
overflowText: this.firstText,
iconCls: 'x-tbar-page-first',
disabled: true,
handler: this.moveFirst,
scope: this
}), this.prev = new T.Button({
tooltip: this.prevText,
overflowText: this.prevText,
iconCls: 'x-tbar-page-prev',
disabled: true,
handler: this.movePrevious,
scope: this
}), '-', this.beforePageText,
this.inputItem = new Ext.form.NumberField({
cls: 'x-tbar-page-number',
allowDecimals: false,
allowNegative: false,
enableKeyEvents: true,
selectOnFocus: true,
submitValue: false,
listeners: {
scope: this,
keydown: this.onPagingKeyDown,
blur: this.onPagingBlur
}
}), this.afterTextItem = new T.TextItem({
text: String.format(this.afterPageText, 1)
}), '-', this.next = new T.Button({
tooltip: this.nextText,
overflowText: this.nextText,
iconCls: 'x-tbar-page-next',
disabled: true,
handler: this.moveNext,
scope: this
}), this.last = new T.Button({
tooltip: this.lastText,
overflowText: this.lastText,
iconCls: 'x-tbar-page-last',
disabled: true,
handler: this.moveLast,
scope: this
}), '-'];
var userItems = this.items || this.buttons || [];
if (this.prependButtons) {
this.items = userItems.concat(pagingItems);
} else {
this.items = pagingItems.concat(userItems);
}
delete this.buttons;
if (this.displayInfo) {
this.items.push('->');
this.items.push(this.displayItem = new T.TextItem({}));
}
Ext.PagingToolbar.superclass.initComponent.call(this);
this.addEvents(
/**
* @event change
* Fires after the active page has been changed.
* @param {Ext.PagingToolbar} this
* @param {Object} pageData An object that has these properties:<ul>
* <li><code>total</code> : Number <div class="sub-desc">The total number of records in the dataset as
* returned by the server</div></li>
* <li><code>activePage</code> : Number <div class="sub-desc">The current page number</div></li>
* <li><code>pages</code> : Number <div class="sub-desc">The total number of pages (calculated from
* the total number of records in the dataset as returned by the server and the current {@link #pageSize})</div></li>
* </ul>
*/
'change',
/**
* @event beforechange
* Fires just before the active page is changed.
* Return false to prevent the active page from being changed.
* @param {Ext.PagingToolbar} this
* @param {Object} params An object hash of the parameters which the PagingToolbar will send when
* loading the required page. This will contain:<ul>
* <li><code>start</code> : Number <div class="sub-desc">The starting row number for the next page of records to
* be retrieved from the server</div></li>
* <li><code>limit</code> : Number <div class="sub-desc">The number of records to be retrieved from the server</div></li>
* </ul>
* <p>(note: the names of the <b>start</b> and <b>limit</b> properties are determined
* by the store's {@link Ext.data.Store#paramNames paramNames} property.)</p>
* <p>Parameters may be added as required in the event handler.</p>
*/
'beforechange'
);
this.on('afterlayout', this.onFirstLayout, this, {single: true});
this.cursor = 0;
this.bindStore(this.store, true);
},
onFirstLayout : function () {
this.refresh = new Ext.Toolbar.Button({
tooltip: i18n.get('label.refreshText'),
overflowText: i18n.get('label.refreshText'),
iconCls: 'x-tbar-loading',
handler: this.doRefresh,
scope: this
});
this.insert(10, this.refresh);
if (this.dsLoaded) {
this.onLoad.apply(this, this.dsLoaded);
}
}
});
Ext.override(Ext.menu.DateMenu, {
initComponent : function () {
this.on('beforeshow', this.onBeforeShow, this);
if (this.strict == (Ext.isIE7 && Ext.isStrict)) {
this.on('show', this.onShow, this, {single: true, delay: 20});
}
Ext.apply(this, {
plain: true,
showSeparator: false,
items: this.picker = new Ext.SitoolsDatePicker(Ext.applyIf({
internalRender: this.strict || !Ext.isIE,
ctCls: 'x-menu-date-item',
id: this.pickerId
}, this.initialConfig))
});
this.picker.purgeListeners();
Ext.menu.DateMenu.superclass.initComponent.call(this);
this.relayEvents(this.picker, ['select']);
this.on('show', this.picker.focus, this.picker);
this.on('select', this.menuHide, this);
if (this.handler) {
this.on('select', this.handler, this.scope || this);
}
}
});
Ext.override(Ext.form.DateField, {
showTime : false,
onTriggerClick : function () {
if (this.disabled) {
return;
}
if (Ext.isEmpty(this.menu)) {
this.menu = new Ext.menu.DateMenu({
hideOnClick: false,
showTime : this.showTime,
focusOnSelect: false
});
}
this.onFocus();
Ext.apply(this.menu.picker, {
minDate : this.minValue,
maxDate : this.maxValue,
disabledDatesRE : this.disabledDatesRE,
disabledDatesText : this.disabledDatesText,
disabledDays : this.disabledDays,
disabledDaysText : this.disabledDaysText,
format : this.format,
showToday : this.showToday,
minText : String.format(this.minText, this.formatDate(this.minValue)),
maxText : String.format(this.maxText, this.formatDate(this.maxValue))
});
this.menu.picker.setValue(this.getValue() || new Date());
this.menu.show(this.el, "tl-bl?");
this.menuEvents('on');
}
});
Ext.override(Ext.slider.SingleSlider, {
listeners : {
afterrender : function (slider) {
slider.syncThumb();
}
},
doSnap : function (value) {
if (!(this.increment && value)) {
return value;
}
var newValue = value,
inc = this.increment,
m = value % inc;
if (m !== 0) {
newValue -= m;
if (m * 2 >= inc) {
newValue += inc;
} else if (m * 2 < -inc) {
newValue -= inc;
}
}
if (Ext.isString(newValue)) {
newValue = parseFloat(newValue);
}
return newValue.constrain(this.minValue, this.maxValue);
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
var ID = {
PANEL : {
MENU : 'menuPanelId',
TREE : 'treePanelId',
MAIN : 'mainPanelId',
HELP : 'helpPanelId',
DATAVIEW : 'dataviewPanelId'
},
CMP : {
TOOLBAR : 'toolbarId',
MENU : 'menuId'
},
WIN : {
LOGIN : 'loginWinId',
HELP : 'helpWinId'
},
BOX : {
REG : 'regBoxId',
USER : 'userBoxId',
GROUP : 'groupBoxId',
ROLE : 'roleBoxId',
FIREWALL : 'firewallBoxId',
PROJECTS : 'projectsBoxId',
DATASETS : 'datasetsBoxId',
DICTIONARY : 'dictionaryBoxId',
TEMPLATE : 'templateBoxId',
DATABASE : 'databaseBoxId',
FORMS : 'formsBoxId',
APPLICATION : 'applicationsBoxId',
USERSTORAGE : 'userStorageBoxId',
GRAPHS : 'graphsBoxId',
CONVERTERS : 'convertersBoxId',
RSSPROJECTS : "rssProjectsId",
STORAGES : "storagesBoxId",
PROJECTPLUGIN : "projectPluginBoxId",
UNITS : "unitsBoxId",
DATASETVIEW : "datasetViewBoxId",
PROJECTMODULE : "projectModuleBoxId",
PROJECTMODULECONFIG : "projectModuleConfigBoxId",
FILEEDITORFTL : "fileEditorFtlBoxId",
FILEEDITORCSS : "fileEditorCssBoxId",
FILEEDITORLICENCE : "fileEditorLicenceBoxId",
COLLECTIONS : "collectionBoxId",
MULTIDS : "multiDsBoxId",
APPLICATIONPLUGIN : "applicationPluginBoxId"
},
PROP : {
DATASETVIEW : "datasetViewPropId",
PROJECTMODULE : "projectModulePropId",
FILEEDITORPROP : "fileEditorBoxId",
MULTIDSPROP : "multiDsPropId"
},
COMPONENT_SETUP : {
DATABASE : 'cmpSetupDatabaseId',
PROJECT : 'cmpSetupProjectId',
OPENSEARCH : 'cmpOpenSearchId',
COLLECTIONS : "cmpCollectionsId",
MULTIDS : "cmpMultiDsId"
},
ITEM : {
OKBUTTON : 'okButtonId',
CANCELBUTTON : 'cancelButtonId'
}
};
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, initGui, initTreeMenu, utils_logout, i18n, ID, DEFAULT_HELP_WIDTH, DEFAULT_HELP_HEIGHT, helpPanel, LOCALE, loadUrl, showVersion, SHOW_HELP:true, includeJs */
/* list of global objects*/
/*
* @include "menu/TreeMenu.js"
*/
var user = null;
var viewport = null;
var treePanel = null;
var dataViewMenu = null;
var seeAlsoMenu = null;
var dataViewWin = null;
var mainPanel = null;
var seeAlsoPanel = null;
// var helpPanel = null;
var helpUrl = null;
var componentsPanel = null;
function onMenuSelect(but) {
if (Ext.isEmpty(but.getItemId())) {
return;
}
if (but.getItemId() == 'menu_logout') {
utils_logout();
} else {
Ext.Msg.alert('Click on Menu: ', but.getItemId());
}
}
function showHelp(helpUrl) {
if (Ext.isEmpty(helpUrl)) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('label.noHelpUrl'));
return;
}
var winHelp = Ext.getCmp(ID.WIN.HELP);
if (!winHelp) {
var helpPanel = new Ext.ux.ManagedIFrame.Panel({
id : ID.WIN.HELP,
layout : 'fit',
// autoScroll:true,
defaultSrc : helpUrl,
defaults : {
padding : 10
}
});
// helpPanel.setSrc(helpUrl);
winHelp = new Ext.Window({
title : i18n.get('label.help'),
width : DEFAULT_HELP_WIDTH,
autoScroll : true,
modal : true,
id : 'winHelpId',
height : DEFAULT_HELP_HEIGHT,
items : [ helpPanel ],
buttons : [ {
text : 'close',
handler : function () {
this.ownerCt.ownerCt.close();
}
} ],
listeners : {
resize : function (win, width, height) {
this.findById(ID.WIN.HELP).setHeight(height - 65);
}
}
});
winHelp.show();
winHelp.doLayout(false, true);
helpPanel.setHeight(winHelp.getHeight() - 65);
} else {
winHelp.show();
}
}
var clientAdmin = {
initDatasetViews : function (callback) {
Ext.Ajax.request({
url : loadUrl.get('APP_URL') + loadUrl.get('APP_DATASETS_VIEWS_URL'),
params : {
sort : "priority",
dir : "DESC"
},
method : "GET",
scope : this,
success : function (ret) {
var json = Ext.decode(ret.responseText);
if (!json.success) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noProjectName'));
return false;
} else {
var data = json.data;
Ext.each(data, function (datasetViewComponent) {
includeJsForceOrder(datasetViewComponent.dependencies.js, 0);
});
}
},
callback : function () {
this.initProjectsModules(callback);
}
});
},
initProjectsModules : function (callback) {
Ext.Ajax.request({
url : loadUrl.get('APP_URL') + loadUrl.get('APP_PROJECTS_MODULES_URL'),
params : {
sort : "priority",
dir : "DESC"
},
method : "GET",
scope : this,
success : function (ret) {
// utils.js contains commonTreeUtils from env.js
includeJs("/sitools/client-user/js/utils.js");
var json = Ext.decode(ret.responseText);
if (!json.success) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noProjectName'));
return false;
} else {
var data = json.data;
Ext.each(data, function (projectModuleComponent) {
if (!Ext.isEmpty(projectModuleComponent.dependencies.js)) {
includeJsForceOrder(projectModuleComponent.dependencies.js, 0);
}
});
}
},
callback : function () {
callback.call(this);
}
});
},
initGui : function () {
var menuLogout = {
xtype : 'tbbutton',
text : i18n.get('label.logout'),
itemId : 'menu_logout',
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/logout.png',
handler : function () {
utils_logout();
}
};
// var menuList = { xtype: 'tbbutton', text: 'Menu 2', itemId:'menu_list',
// handler: onMenuShow,
// menu: [
// {text: 'Item 1', itemId:'menu2_item1', handler: onMenuSelect},
// {text: 'Item 2', itemId:'menu2_item2', handler: onMenuSelect},
// '-',
// {text: 'Item 3', itemId:'menu2_item3', handler: onMenuSelect}
// ] };
// var menuHelp = { xtype: 'tbbutton', text: 'Help', disabled: true };
var toolbar = {
xtype : 'toolbar',
id : ID.CMP.TOOLBAR,
items : [ {
xtype : 'label',
html : '<img src=res/images/cnes.png width=92 height=28>'
}, {
xtype : 'label',
text : i18n.get('label.title')
}, '->', {
xtype : 'label',
text : i18n.get('label.welcome') + ' ' + Ext.util.Cookies.get('userLogin')
}, '-', {
text : 'Version',
id : 'versionButtonId',
// scope : this,
handler : function () {
showVersion();
},
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/version.png'
}, '-', {
text: 'Show Help',
enableToggle: true,
toggleHandler: function (item, checked) {
var helpPanel = Ext.getCmp(ID.PANEL.HELP);
if (!checked) {
helpPanel.toggleCollapse(false);
SHOW_HELP = false;
}
else {
helpPanel.toggleCollapse(true);
SHOW_HELP = true;
}
},
pressed: true,
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/help.png'
}, "-", {
text : 'Advanced Mode',
id : 'switchModeId',
enableToggle: true,
pressed : true,
toggleHandler : function (item, checked) {
var main = Ext.getCmp(ID.PANEL.MAIN);
var tree = Ext.getCmp(ID.PANEL.TREE);
if (checked) {
tree.show();
main.getTopToolbar().hide();
main.doLayout();
dataViewWin.hide();
}
else {
tree.hide();
if (Ext.isEmpty(dataViewWin)) {
seeAlsoMenu = new sitools.admin.menu.seeAlso();
seeAlsoPanel = new Ext.Panel({
id : 'seeAlsoId',
flex : 1,
autoScroll : true,
width : 265,
html : '<div class="title-seeAlso"></div>',
cls : 'background-seeAlso',
height : Ext.getBody().getSize().height - 110,
items : [seeAlsoMenu]
});
seeAlsoMenu.getStore().loadData({
links : []
});
dataViewMenu = new sitools.admin.menu.dataView();
var dataViewPanel = new Ext.Panel({
id : 'panDataview',
flex : 2,
items : [dataViewMenu],
listeners : {
resize : function (panel) {
var size = panel.body.getSize();
dataViewMenu.setSize({
height : size.height - 5,
width : size.width - 5
});
seeAlsoPanel.setSize(panel.body.getSize());
}
}
});
dataViewWin = new Ext.Window({
border : false,
id : ID.PANEL.DATAVIEW,
layout: 'hbox',
resizable : false,
layoutConfig: {
align : 'stretch',
pack : 'start'
},
closable : false,
draggable : false,
items : [seeAlsoPanel, dataViewPanel],
height : Ext.getBody().getSize().height - 82,
width : Ext.getBody().getSize().width,
y : 82,
allButtons : [],
tbar : {
cls : 'root-toolbar',
id : 'idToolbarView'
}
});
}
dataViewWin.show();
main.getTopToolbar().show();
var dataViewEl = dataViewWin.getEl();
dataViewEl.fadeIn({
endOpacity: 0.95, //can be any value between 0 and 1 (e.g. .5)
easing: 'easeOut',
duration: 0.5
});
}
viewport.doLayout();
}
}, menuLogout
// menuList,
// '-',
// menuHelp
]
};
var menuPanel = new Ext.Panel({
id : ID.PANEL.MENU,
region : 'north',
layout : 'fit',
height : 28,
items : [ toolbar ]
});
treePanel = new Ext.Panel({
id : ID.PANEL.TREE,
region : 'west',
title : i18n.get('label.menu'),
split : true,
autoScroll : true,
width : 250,
layout : 'fit',
defaults : {
padding : 10
}
});
var helpPanel = new Ext.ux.ManagedIFrame.Panel({
// {xtype:'iframepanel',
id : ID.PANEL.HELP,
// region: 'east',
title : i18n.get('label.help'),
split : true,
collapsible : true,
autoScroll : true,
// width : 200,
layout : 'fit',
defaults : {
padding : 10
}
});
var pan_config = new sitools.admin.menu.dataView();
mainPanel = new Ext.Panel({
layout : 'vbox',
layoutConfig: {
align : 'stretch',
pack : 'start'
},
xtype : 'panel',
id : ID.PANEL.MAIN,
tbar : {
cls : 'root-toolbar',
id : 'idConfig'
},
title : i18n.get('label.main'),
items : [{
xtype : 'panel',
layout : 'fit',
height : 1200,
autoLoad : 'res/html/' + LOCALE + '/welcome.html'
}],
region : 'center'
});
/*
* contextMenu = new Ext.Window({ title: FILTER_TITLE, layout: 'hbox',
* width: 260, autoHeight: true, shadow: 'drop', closable: false,
* //closeAction:'hide', plain: true, //buttonAlign: 'center', items: [ ],
* buttons: [ { text: 'OK', handler: function() {contextMenu.hide(),
* setFilter(Ext.getCmp('filterValueId').getValue())} }, { text: 'Cancel',
* handler: function() {contextMenu.hide()} } ] });
*/
// Setting the viewport
viewport = new Ext.Viewport({
layout : 'border',
items : [ menuPanel, treePanel, mainPanel
// ,
// helpPanel
],
listeners : {
scope : this,
resize : function () {
if (dataViewWin) {
dataViewWin.setSize({
height : Ext.getBody().getSize().height - 87,
width : Ext.getBody().getSize().width - 5
});
dataViewWin.setPosition(0, 82);
dataViewWin.doLayout();
}
}
}
});
var menu = new sitools.admin.menu.TreeMenu('res/json/menu.json');
treePanel.add(menu);
treePanel.doLayout();
// viewport.doLayout();
// Checking if user is logged
}
};
/**
* Init application Gui and logic
*/
function initAppli() {
//loadUrl.load('/sitools/client-admin/siteMap', clientAdmin.initGui());
Ext.Ajax.request({
url : loadUrl.get('APP_URL') + loadUrl.get('APP_FORMCOMPONENTS_URL'),
params : {
sort : "priority",
dir : "DESC"
},
method : "GET",
scope : this,
success : function (ret) {
var json = Ext.decode(ret.responseText);
if (!json.success) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noProjectName'));
return false;
} else {
var data = json.data;
Ext.each(data, function (formComponent) {
includeJs(formComponent.fileUrlAdmin);
includeJs(formComponent.fileUrlUser);
});
}
},
callback : function () {
sql2ext.load(loadUrl.get('APP_URL') + "/client-user/conf/sql2ext.properties");
var cb = function () {
clientAdmin.initGui();
};
clientAdmin.initDatasetViews(cb);
}
});
}
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, ID*/
function getI(c) {
return c.getId();
}
function getCmp(id) {
return Ext.getCmp(id);
}
function getMenu() {
return Ext.getCmp(ID.CMP.MENU);
}
function getMenuRoot() {
return getMenu().getRootNode();
}
function getMenuNode(id) {
return getMenu().getNodeById(id);
}
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, ann, mainPanel, helpUrl:true, loadUrl, SHOW_HELP*/
Ext.namespace('sitools.admin.menu');
//sitools.component.dataViewNodes = Ext.extend(Ext.DataView, {
* Create A Dataview from the file menu.json
*
* @cfg {Ext.XTemplate} the template to display in the dataView
* @cfg {Ext.data.JsonStore} the store where nodes are saved
* @class sitools.admin.menu.dataView
* @extends Ext.DataView
*/
sitools.admin.menu.dataView = Ext.extend(Ext.DataView, {
id: 'nodes',
itemSelector: 'div.nodes',
overClass : 'nodes-hover',
singleSelect: true,
multiSelect : false,
autoScroll : true,
initComponent : function () {
var tpl = new Ext.XTemplate(
'<div id="adminMenu">',
'<div class="title">Choose a Task...</div>',
'<div class="float columns">',
'<tpl for=".">',
'<tpl if="(this.round(xcount /2) - xindex) < 0"></div>', // Pour revenir à la ligne tout les 2 icones
'<div>',
'</tpl>',
'<div id="{nodeName}" class="nodes">',
'<img class="float"',
'<tpl if="this.isNotEmpty(children)">',
'ext:qtip="',
'<tpl for="children">',
'{textChildren}<br>',
'</tpl>',
'" ',
'</tpl>',
'width="96" height="96" src="',
'<tpl if="this.isNotEmpty(iconMenu)">',
'{iconMenu}',
'</tpl>',
'<tpl if="this.isEmpty(iconMenu)">',
'/sitools/common/res/images/icons/menu/collections.png',
'</tpl>',
'" />',
'<span>{name}</span>',
'</div>',
'</tpl>',
'</div>',
'<img class="icon-sitools" src="/sitools/common/res/images/icons/menu/logoSitools.png" />',
'</div>',
{
compiled : true,
isNotEmpty : function (children) {
return !Ext.isEmpty(children);
},
isEmpty : function (children) {
return Ext.isEmpty(children);
},
round : function (xcount) { // arrondi à l'entier supérieur
return Math.round(xcount);
}
});
this.tpl = tpl;
this.height = Ext.getBody().getSize().height - 100;
this.listeners = {
dblclick : function (t, ind, node, e) {
var nodeName = node.id;
var title = node.childNodes[1].textContent;
this.openSubCategory(t, title, e, nodeName);
},
click : function (t, ind, node, e) {
var rec = dataViewMenu.getStore().getAt(ind);
seeAlsoMenu.getStore().loadData(rec.data);
},
afterrender : function (view) {
Ext.Ajax.request({
url : 'res/json/menu.json',
method : 'GET',
success: function (response) {
view.allData = Ext.decode(response.responseText);
mainPanel.toolbars[0].addText('Path : / Menu');
mainPanel.toolbars[0].addSeparator();
view.openSubCategory(view, 'root');
},
failure: function () {
Ext.Msg.alert('Error', 'Cannot load nodes from menu.json');
},
scope : view
});
}
};
this.store = new Ext.data.JsonStore({
root : '',
restful : true,
remoteSort : false,
fields : [
{name: 'name', mapping : 'text'},
{name: 'nodeName'},
{name : 'id'},
{name : 'parentNode'},
{name : 'children'},
{name : 'iconMenu'},
{name : 'category'},
{name : 'links'},
{name : 'label'},
{name : 'path'}
]
});
this.allButtons = [];
sitools.admin.menu.dataView.superclass.initComponent.call(this);
},
* Display children of a node
*
* @param t the parent element
* @param title the title
* @param e the event
* @param nodeName the nodeId
*/
openSubCategory : function (t, title, e, nodeName) {
var isAddable = this.populateStore(t, title);
// On ajoute le noeud sur lequel on vient de cliquer en tant que bouton de la toolbar
if (isAddable) {
var button = {
xtype : 'button',
overCls : 'nodes-hover',
labelStyle: 'font-weight:bold !important;',
text : title,
id : title + 'Id',
nodeName : nodeName,
scope : t,
handler : function (btn, e) {
this.populateStore(this, btn.getText());
this.deleteItemsFromToolbar(mainPanel.toolbars[0], btn.getText());
dataViewWin.show();
mainPanel.getTopToolbar().show();
var dataViewEl = dataViewWin.getEl();
dataViewEl.fadeIn({
endOpacity: 0.95, //can be any value between 0 and 1 (e.g. .5)
easing: 'easeOut',
duration: 0.5
});
}
};
this.allButtons.push(button);
mainPanel.toolbars[0].addButton(button);
mainPanel.toolbars[0].add(['-']);
mainPanel.doLayout();
}
else {
this.treeAction(title, nodeName);
}
},
* Delete the item from the top toolbar
*
* @param toolbar
* @param title the title of the item to delete
*/
deleteItemsFromToolbar : function (toolbar, title) {
var saveToolbar = [];
var textRoot = toolbar.items.items[0].text;
toolbar.removeAll();
toolbar.addText(textRoot);
toolbar.addSeparator();
for (var i = 0; i < this.allButtons.length; i++) {
toolbar.addButton(this.allButtons[i]);
toolbar.addSeparator();
saveToolbar[i] = this.allButtons[i];
if (this.allButtons[i].text == title) {
break;
}
}
this.allButtons = saveToolbar;
mainPanel.doLayout();
},
* Populate the store with children of a node
*
* @param t
* @param title the title of the item to populate
* @returns {Boolean}
*/
populateStore : function (t, title) {
var children = t.getChildrenByParentNode(t.allData, title);
if (!Ext.isEmpty(children)) {
t.store.removeAll();
//Internationalisation des noeuds.
Ext.each(children, function (child) {
child.text = i18n.get('label.' + child.nodeName);
Ext.each(child.children, function (child) {
child.textChildren = i18n.get('label.' + child.nodeName);
});
});
t.store.loadData(children);
return true;
}
else {
return false;
}
},
* Get All the children of a parent node
*
* @param data all the node
* @param parentNode the name of the parentNode
* @returns
*/
getChildrenByParentNode : function (data, parentNode) {
if (Ext.isEmpty(data)) {
return null;
}
if (parentNode == 'root') {
return data;
}
else {
for (var i = 0; i < data.length; i++) {
if (data[i].text == parentNode) {
return data[i].children;
}
else {
var tmp = this.getChildrenByParentNode(data[i].children, parentNode);
if (!Ext.isEmpty(tmp)) {
return tmp;
}
}
}
}
},
* Create a component from his component Registry name
*
* @param title
* @param nodeName
*/
treeAction : function (title, nodeName) {
// Getting nodeName
var nodeId = title + 'id';
if (!Ext.isDefined(nodeName)) {
Ext.Msg.alert('warning', 'Undefined');
return;
}
var selectedNode = this.getSelectedRecords()[0];
if (!Ext.ComponentMgr.isRegistered('s-' + nodeName)) {
Ext.Msg.alert('warning', 'label.component' + ' \'' + 's-' + nodeName + '\' ' + 'msg.undefined');
return;
}
var pan_config = new sitools.admin.menu.dataView();
// Loading component 's-nodeName'
mainPanel.removeAll();
mainPanel.add({
width: "100%",
items : [ {
xtype : 's-box',
label : i18n.get('label.' + nodeName),
items : [ {
xtype : 's-' + nodeName,
sitoolsType : "mainAdminPanel"
} ],
idItem : selectedNode.get('id')
} ],
listeners : {
resize : function (panel, width, height) {
var size = panel.items.items[0].body.getSize();
var sBoxTitle = panel.items.items[0].items.items[0].getEl();
size = {
height : size.height - (sBoxTitle.getHeight() + sBoxTitle.getMargins("t") + sBoxTitle.getMargins("b")),
width : size.width - 8
};
var mainAdminPanel = panel.find("sitoolsType", "mainAdminPanel");
mainAdminPanel[0].setSize(size);
}
}
});
var helpPanel = new Ext.ux.ManagedIFrame.Panel({
id : ID.PANEL.HELP,
width : "100%",
flex : 1,
// autoScroll:true,
defaultSrc : loadUrl.get('APP_URL') + "/client-admin/res/help/" + LOCALE + "/" + nodeName + ".html",
defaults : {
padding : 10
}
});
mainPanel.add(
helpPanel
);
mainPanel.doLayout();
helpPanel.setVisible(SHOW_HELP);
helpUrl = loadUrl.get('APP_URL') + "/client-admin/res/help/" + LOCALE + "/" + nodeName + ".html";
mainPanel.getTopToolbar().show();
dataViewWin.hide();
}
});
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, ann, mainPanel, helpUrl:true, loadUrl, SHOW_HELP*/
Ext.namespace('sitools.admin.menu');
* Create A dynamic Dataview in function of the sitools.admin.menu.dataView Dataview
*
* @cfg {Ext.XTemplate} the template to display in the dataView
* @cfg {Ext.data.JsonStore} the store where nodes are saved
* @class sitools.admin.menu.seeAlso
* @extends Ext.DataView
*/
sitools.admin.menu.seeAlso = Ext.extend(Ext.DataView, {
id: 'links',
itemSelector: 'div.links',
overClass : 'links-hover',
singleSelect: true,
multiSelect : false,
autoScroll : false,
initComponent : function () {
var tpl = new Ext.XTemplate(
'<div class="title-seeAlso">See Also...</div>',
'<tpl for=".">',
'<tpl if="this.isNotEmpty(links)">',
'<tpl for="links">',
'<div id="{nodeName}" name="{text}" class="links">',
'<img class="icon-seeAlso" width="16" height="16" src="{iconMenu}" />',
'<span id="{nodeName}">{label}</span>',
'</div>',
'</tpl>',
'</tpl>',
'</tpl>',
{
compiled : true,
isNotEmpty : function (children) {
return !Ext.isEmpty(children);
},
isEmpty : function (children) {
return Ext.isEmpty(children);
}
}
);
this.tpl = tpl;
this.height = Ext.getBody().getSize().height - 220;
this.listeners = {
click : function (t, ind, node, e) {
var nodeName = node.id;
var title = node.attributes[1].textContent;
var rec = seeAlsoMenu.getStore().getAt(0);
var path = this.getPath(rec, title);
this.openSubCategory(t, title, e, nodeName, path);
}
};
this.store = new Ext.data.JsonStore({
root : '',
restful : true,
remoteSort : false,
fields : [
{name: 'nodeName'},
{name : 'id'},
{name : 'parentNode'},
{name : 'children'},
{name : 'iconMenu'},
{name : 'category'},
{name : 'links'},
{name : 'label'},
{name : 'path'}
]
});
this.allButtons = [];
sitools.admin.menu.seeAlso.superclass.initComponent.call(this);
},
* Get the path from the split of a string
*
* @param rec the record
* @param title the title of the item to get the path
* @returns pathTab a tab of strings
*/
getPath : function (rec, title) {
var reg = new RegExp("/");
for (var i = 0; i < rec.data.links.length; i++){
if (rec.data.links[i].text == title){
var pathTab = rec.data.links[i].path.split(reg);
return pathTab;
}
}
},
* Display children of a node
*
* @param t the parent element
* @param title the title
* @param e the event
* @param nodeName the nodeId
* @param path
*/
openSubCategory : function (t, title, e, nodeName, path) {
dataViewMenu.allButtons = [];
var isAddable = this.populateStore(t, title);
var toolbar = mainPanel.toolbars[0];
var textRoot = toolbar.items.items[0].text;
// On ajoute le noeud sur lequel on vient de cliquer en tant que bouton de la toolbar
toolbar.removeAll();
toolbar.addText(textRoot);
toolbar.addSeparator();
this.addRootButton();
for (var i = 0; i < path.length; i++){
var button = {
xtype : 'button',
text : path[i],
id : path[i] + 'Id',
scope : t,
path : path,
handler : function (btn, e) {
this.populateStore(this, btn.getText());
dataViewMenu.deleteItemsFromToolbar(mainPanel.toolbars[0], btn.getText(), path);
dataViewWin.show();
mainPanel.getTopToolbar().show();
var dataViewEl = dataViewWin.getEl();
dataViewEl.fadeIn({
endOpacity: 0.95, //can be any value between 0 and 1 (e.g. .5)
easing: 'easeOut',
duration: 0.5
});
}
};
this.addButton (button, toolbar);
}
mainPanel.doLayout();
if (!isAddable) {
this.treeAction(title, nodeName);
}
},
* Add a button to the a toolbar
*
* @param btn the button to add
* @param toolbar which receive the button
*/
addButton : function (btn, toolbar) {
toolbar.add(btn);
toolbar.addSeparator();
dataViewMenu.allButtons.push(btn);
},
* Add the Root button to the top toolbar
*/
addRootButton : function () {
var button = {
xtype : 'button',
text : 'root',
id : 'rootId',
scope : this,
handler : function (btn, e) {
this.populateStore(this, btn.getText());
dataViewMenu.deleteItemsFromToolbar(mainPanel.toolbars[0], btn.getText());
dataViewWin.show();
mainPanel.getTopToolbar().show();
var dataViewEl = dataViewWin.getEl();
dataViewEl.fadeIn({
endOpacity: 0.95, //can be any value between 0 and 1 (e.g. .5)
easing: 'easeOut',
duration: 0.5
});
}
};
this.addButton (button, mainPanel.toolbars[0]);
mainPanel.doLayout();
},
* Populate the store with children of a node
*
* @param t
* @param title the title of the item to populate
* @returns {Boolean}
*/
populateStore : function (t, title) {
var children = t.getChildrenByParentNode(dataViewMenu.allData, title);
if (!Ext.isEmpty(children)) {
t.store.removeAll();
dataViewMenu.store.removeAll();
dataViewMenu.store.loadData(children);
return true;
}
else {
return false;
}
},
* Get All the children of a parent node
*
* @param data all the node
* @param parentNode the name of the parentNode
* @returns
*/
getChildrenByParentNode : function (data, parentNode) {
if (Ext.isEmpty(data)) {
return null;
}
if (parentNode == 'root') {
return data;
}
else {
for (var i = 0; i < data.length; i++) {
if (data[i].text == parentNode) {
return data[i].children;
}
else {
var tmp = this.getChildrenByParentNode(data[i].children, parentNode);
if (!Ext.isEmpty(tmp)) {
return tmp;
}
}
}
}
},
* Create a component from his component Registry name
*
* @param title
* @param nodeName
*/
treeAction : function (title, nodeName) {
// Getting nodeName
var nodeId = title + 'id';
if (!Ext.isDefined(nodeName)) {
Ext.Msg.alert('warning', 'Undefined');
return;
}
var selectedNode = this.getSelectedRecords()[0];
if (!Ext.ComponentMgr.isRegistered('s-' + nodeName)) {
Ext.Msg.alert('warning', 'label.component' + ' \'' + 's-' + nodeName + '\' ' + 'msg.undefined');
return;
}
var pan_config = new sitools.admin.menu.dataView();
// Loading component 's-nodeName'
mainPanel.removeAll();
mainPanel.add({
width: "100%",
items : [ {
xtype : 's-box',
label : i18n.get('label.' + nodeName),
items : [ {
xtype : 's-' + nodeName,
sitoolsType : "mainAdminPanel"
} ],
idItem : nodeId //selectedNode.get('id')
} ],
listeners : {
resize : function (panel, width, height) {
var size = panel.items.items[0].body.getSize();
var sBoxTitle = panel.items.items[0].items.items[0].getEl();
size = {
height : size.height - (sBoxTitle.getHeight() + sBoxTitle.getMargins("t") + sBoxTitle.getMargins("b")),
width : size.width - 8
};
var mainAdminPanel = panel.find("sitoolsType", "mainAdminPanel");
mainAdminPanel[0].setSize(size);
}
}
});
var helpPanel = new Ext.ux.ManagedIFrame.Panel({
id : ID.PANEL.HELP,
width : "100%",
flex : 1,
// autoScroll:true,
defaultSrc : loadUrl.get('APP_URL') + "/client-admin/res/help/" + LOCALE + "/" + nodeName + ".html",
defaults : {
padding : 10
}
});
mainPanel.add(
helpPanel
);
mainPanel.doLayout();
helpPanel.setVisible(SHOW_HELP);
helpUrl = loadUrl.get('APP_URL') + "/client-admin/res/help/" + LOCALE + "/" + nodeName + ".html";
mainPanel.getTopToolbar().show();
dataViewWin.hide();
}
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, ann, mainPanel, helpUrl:true, loadUrl, SHOW_HELP*/
Ext.namespace('sitools.admin.menu');
* Build the sitools tree menu
* @class sitools.admin.menu.TreeMenu
*/
//sitools.component.tree.Menu = Ext.extend(Object, {
sitools.admin.menu.TreeMenu = Ext.extend(Object, {
constructor : function (jsonUrl) {
var tree = new Ext.tree.TreePanel({
id : ID.CMP.MENU,
component : this,
useArrows : false,
autoScroll : true,
animate : true,
root : {
nodeType : 'async'
},
loader : new Ext.tree.TreeLoader({
requestMethod : 'GET',
url : jsonUrl
}),
rootVisible : false,
listeners : {
beforeload : function (node) {
node.setText(i18n.get('label.' + node.attributes.nodeName));
return node.isRoot || Ext.isDefined(node.attributes.children);
},
load : function (node) {
node.eachChild(function (item) {
item.setText(i18n.get('label.' + item.attributes.nodeName));
return true;
});
},
click : function (node) {
if (node.isLeaf()) {
this.component.treeAction(node);
}
}
}
});
tree.getRootNode().expand(true);
return tree;
},
* Action executed ; 'this' refers to this component
*
* @param node
* @returns
*/
treeAction : function (node) {
// Getting nodeName
var nodeName = node.attributes.nodeName;
var nodeId = node.attributes.id;
if (!Ext.isDefined(nodeName)) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('msg.nodeundefined'));
return;
}
if (!Ext.ComponentMgr.isRegistered('s-' + nodeName)) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('label.component') + ' \'' + 's-' + nodeName + '\' ' + i18n.get('msg.undefined'));
return;
}
// Displaying Main Panel
ann(mainPanel, "mainPanel is null");
var pan_config = new sitools.admin.menu.dataView();
// Loading component 's-nodeName'
mainPanel.removeAll();
mainPanel.add(
{
width: "100%",
items : [ {
xtype : 's-box',
label : i18n.get('label.' + nodeName),
items : [ {
xtype : 's-' + nodeName,
sitoolsType : "mainAdminPanel"
} ],
idItem : nodeId
} ],
listeners : {
resize : function (panel, width, height) {
var size = panel.items.items[0].body.getSize();
var sBoxTitle = panel.items.items[0].items.items[0].getEl();
size = {
height : size.height - (sBoxTitle.getHeight() + sBoxTitle.getMargins("t") + sBoxTitle.getMargins("b")),
width : size.width - 8
};
var mainAdminPanel = panel.find("sitoolsType", "mainAdminPanel");
mainAdminPanel[0].setSize(size);
}
}
});
var helpPanel = new Ext.ux.ManagedIFrame.Panel({
id : ID.PANEL.HELP,
width : "100%",
flex : 1,
// autoScroll:true,
defaultSrc : loadUrl.get('APP_URL') + "/client-admin/res/help/" + LOCALE + "/" + nodeName + ".html",
defaults : {
padding : 10
}
});
mainPanel.add(
helpPanel
);
mainPanel.doLayout();
helpPanel.setVisible(SHOW_HELP);
helpUrl = loadUrl.get('APP_URL') + "/client-admin/res/help/" + LOCALE + "/" + nodeName + ".html";
}
});
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.admin.usergroups');
/**
* A Panel to show all the groups in Sitools2
*
* @cfg {String} the url where get the registers
* @cfg {Ext.data.JsonStore} the store where saved the register data
* @class sitools.admin.usergroups.RegCrudPanel
* @extends Ext.grid.GridPanel
*/
//sitools.component.usergroups.RegCrudPanel = Ext.extend(Ext.grid.GridPanel, {
sitools.admin.usergroups.RegCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.REG,
sm : new Ext.grid.RowSelectionModel({
singleSelect : true
}),
pageSize : 10,
// loadMask: true,
initComponent : function () {
this.url = loadUrl.get('APP_URL') + loadUrl.get('APP_INSCRIPTIONS_ADMIN_URL');
/*
* // The new DataWriter component. var writer = new
* Ext.data.JsonWriter({ encode: false // <-- don't return encoded JSON --
* causes Ext.Ajax#request to send data using jsonData config rather
* than HTTP params });
*/
// create the restful Store
// Method url action
// POST /users create
// GET /users read
// PUT /users/[id] update
// DESTROY /users/[id] delete
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
url : this.url,
remoteSort : true,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'identifier',
type : 'string'
}, {
name : 'firstName',
type : 'string'
}, {
name : 'lastName',
type : 'string'
}, {
name : 'email',
type : 'string'
}
]
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.login'),
dataIndex : 'identifier',
width : 100
}, {
header : i18n.get('label.firstName'),
dataIndex : 'firstName',
width : 100
}, {
header : i18n.get('label.lastName'),
dataIndex : 'lastName',
width : 100
}, {
header : i18n.get('label.email'),
dataIndex : 'email',
width : 100
} ]
});
this.bbar = {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
};
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.validate'),
icon : 'res/images/icons/icons_perso/toolbar_validate.png',
handler : this.onValidate,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this.onModify,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDelete,
xtype : 's-menuButton'
}, '->', {
xtype : 's-filter',
emptyText : i18n.get('label.search'),
store : this.store,
pageSize : this.pageSize
} ]
};
this.view = new Ext.grid.GridView({
forceFit : true
});
this.listeners = {
scope : this,
rowDblClick : this.onModify
};
sitools.admin.usergroups.RegCrudPanel.superclass.initComponent.call(this);
},
/**
* done a specific render to load registers from the store.
*/
onRender : function () {
sitools.admin.usergroups.RegCrudPanel.superclass.onRender.apply(this, arguments);
this.store.load({
params : {
start : 0,
limit : this.pageSize
}
});
},
/**
* Accept a registration and create an user
*/
onValidate : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.url + '/' + rec.id,
method : 'PUT',
scope : this,
success : function (ret) {
this.store.reload();
},
failure : alertFailure
});
},
/**
* Open a panel to edit properties of the selected user registration
*/
onModify : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.admin.usergroups.RegPropPanel({
url : this.url + '/' + rec.id,
store : this.store
});
up.show(ID.BOX.REG);
},
/**
* Diplay confirm delete Msg box and call the method doDelete
*/
onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return false;
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('userCrud.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec);
}
}
});
},
/**
* done the delete of the passed record
* @param rec the record to delete
*/
doDelete : function (rec) {
Ext.Ajax.request({
url : this.url + "/" + rec.id,
method : 'DELETE',
scope : this,
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (!Json.success) {
Ext.Msg.alert(i18n.get('label.warning'), Json.message);
return;
}
this.store.reload();
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get(Json.message),
autoDestroy : true,
hideDelay : 1000
}).show(document);
},
failure : alertFailure
});
}
});
Ext.reg('s-regcrud', sitools.admin.usergroups.RegCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.admin.usergroups');
/**
* A Panel to show all the users in Sitools2
*
* @cfg {String} the url where get the users
* @cfg {Ext.data.JsonStore} the store where saved the users data
* @class sitools.admin.usergroups.UserCrudPanel
* @extends Ext.grid.GridPanel
*/
//sitools.component.usergroups.UserCrudPanel = Ext.extend(Ext.grid.GridPanel, {
sitools.admin.usergroups.UserCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.USER,
sm : new Ext.grid.RowSelectionModel({
singleSelect : true
}),
pageSize : 10,
// loadMask: true,
initComponent : function () {
this.url = loadUrl.get('APP_URL') + loadUrl.get('APP_SECURITY_URL') + '/users';
/*
* // The new DataWriter component. var writer = new
* Ext.data.JsonWriter({ encode: false // <-- don't return encoded JSON --
* causes Ext.Ajax#request to send data using jsonData config rather
* than HTTP params });
*/
// create the restful Store
// Method url action
// POST /users create
// GET /users read
// PUT /users/id update
// DESTROY /users/id delete
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
autoSave : false,
url : this.url,
idProperty : 'identifier',
remoteSort : true,
fields : [ {
name : 'identifier',
type : 'string'
}, {
name : 'firstName',
type : 'string'
}, {
name : 'lastName',
type : 'string'
}, {
name : 'email',
type : 'string'
} ]
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.login'),
dataIndex : 'identifier',
width : 100
}, {
header : i18n.get('label.firstName'),
dataIndex : 'firstName',
width : 100
}, {
header : i18n.get('label.lastName'),
dataIndex : 'lastName',
width : 250
}, {
header : i18n.get('label.email'),
dataIndex : 'email',
width : 200
} ]
});
this.bbar = {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
};
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this._onCreate,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this._onModify,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this._onDelete,
xtype : 's-menuButton'
}, '->', {
xtype : 's-filter',
emptyText : i18n.get('label.search'),
store : this.store,
pageSize : this.pageSize
} ]
};
this.view = new Ext.grid.GridView({
forceFit : true
});
this.listeners = {
scope : this,
rowDblClick : this._onModify
};
sitools.admin.usergroups.UserCrudPanel.superclass.initComponent.call(this);
},
/**
* done a specific render to load users from the store.
*/
onRender : function () {
sitools.admin.usergroups.UserCrudPanel.superclass.onRender.apply(this, arguments);
this.store.load({
params : {
start : 0,
limit : this.pageSize
}
});
},
/**
* Open a {sitools.admin.usergroups.UserPropPanel} userPropertyPanel to create a new user
*/
_onCreate : function () {
var up = new sitools.admin.usergroups.UserPropPanel({
url : this.url,
action : 'create',
store : this.getStore()
});
up.show(ID.BOX.USER);
// return Ext.Msg.alert(i18n.get('label.information'),
// i18n.get('msg.notavailable'));
},
/**
* Open a {sitools.admin.usergroups.UserPropPanel} userPropertyPanel to modify an user
*/
_onModify : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.admin.usergroups.UserPropPanel({
url : this.url + '/' + rec.id,
action : 'modify',
store : this.getStore()
});
up.show(ID.BOX.USER);
},
/**
* Diplay confirm delete Msg box and call the method doDelete
*/
_onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return false;
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('userCrud.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec);
}
}
});
},
/**
* done the delete of the passed record
* @param rec the record to delete
*/
doDelete : function (rec) {
Ext.Ajax.request({
url : this.url + "/" + rec.id,
method : 'DELETE',
scope : this,
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (!Json.success) {
Ext.Msg.alert(i18n.get('label.warning'), Json.message);
return;
}
this.store.reload();
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get(Json.message),
autoDestroy : true,
hideDelay : 1000
}).show(document);
},
failure : alertFailure
});
}
});
Ext.reg('s-usercrud', sitools.admin.usergroups.UserCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.admin.usergroups');
/**
* A Panel to show all the groups in Sitools2
*
* @cfg {String} the url where get the resource
* @cfg {Ext.data.JsonStore} the store where saved the group data
* @class sitools.admin.usergroups.GroupCrudPanel
* @extends Ext.grid.GridPanel
*/
//sitools.component.usergroups.GroupCrudPanel = Ext.extend(Ext.grid.GridPanel, {
sitools.admin.usergroups.GroupCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.GROUP,
sm : new Ext.grid.RowSelectionModel({
singleSelect : true
}),
pageSize : 10,
// loadMask: true,
initComponent : function () {
this.url = loadUrl.get('APP_URL') + loadUrl.get('APP_SECURITY_URL') + '/groups';
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
url : this.url,
remoteSort : true,
idProperty : 'name',
fields : [ {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
} ]
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 200
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 400
} ]
});
this.bbar = {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
};
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreate,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this.onModify,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDelete,
xtype : 's-menuButton'
}, {
text : i18n.get('label.users'),
icon : 'res/images/icons/icons_perso/toolbar_userman.png',
handler : this.onMembers,
xtype : 's-menuButton'
}, '->', {
xtype : 's-filter',
emptyText : i18n.get('label.search'),
store : this.store,
pageSize : this.pageSize
} ]
};
this.view = new Ext.grid.GridView({
forceFit : true
});
this.listeners = {
scope : this,
rowDblClick : this.onModify
};
sitools.admin.usergroups.GroupCrudPanel.superclass.initComponent.call(this);
},
/**
* done a specific render to load informations from the store.
*/
onRender : function () {
sitools.admin.usergroups.GroupCrudPanel.superclass.onRender.apply(this, arguments);
this.store.load({
params : {
start : 0,
limit : this.pageSize
}
});
},
/**
* Create a new {sitools.admin.usergroups.GroupPropPanel} groupPropertyPanel to create a new group
*/
onCreate : function () {
var up = new sitools.admin.usergroups.GroupPropPanel({
url : this.url,
action : 'create',
store : this.getStore()
});
up.show(ID.BOX.GROUP);
// return Ext.Msg.alert(i18n.get('label.information'),
// i18n.get('msg.notavailable'));
},
/**
* Create a new {sitools.admin.usergroups.GroupPropPanel} groupPropertyPanel to modify an existing group
*/
onModify : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.admin.usergroups.GroupPropPanel({
url : this.url + '/' + rec.id,
action : 'modify',
store : this.getStore()
});
up.show(ID.BOX.GROUP);
},
/**
* Diplay confirm delete Msg box and call the method doDelete
*/
onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('msg.group.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec);
}
}
});
},
/**
* done the delete of the passed record
* @param rec the record to delete
*/
doDelete : function (rec) {
// var rec = this.getSelectionModel().getSelected();
// if (!rec) return false;
Ext.Ajax.request({
url : this.url + "/" + rec.id,
method : 'DELETE',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
/**
* Gets all the members of the selected group and display them in an {sitools.admin.usergroups.UsersPanel} users Panel
* @returns
*/
onMembers : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.admin.usergroups.UsersPanel({
mode : 'list',
url : this.url + '/' + rec.id + '/users',
data : rec.data
});
up.show(ID.BOX.GROUP);
}
});
Ext.reg('s-groupcrud', sitools.admin.usergroups.GroupCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.admin.usergroups');
/**
* A Panel to show all the Roles in Sitools2
*
* @cfg {String} the url where get the registers
* @cfg {Ext.data.JsonStore} the store where saved the roles data
* @class sitools.admin.usergroups.RoleCrudPanel
* @extends Ext.grid.GridPanel
*/
//sitools.component.usergroups.RoleCrudPanel = Ext.extend(Ext.grid.GridPanel, {
sitools.admin.usergroups.RoleCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.ROLE,
sm : new Ext.grid.RowSelectionModel({
singleSelect : true
}),
pageSize : 10,
// loadMask: true,
initComponent : function () {
this.url = loadUrl.get('APP_URL') + loadUrl.get('APP_ROLES_URL');
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
url : this.url,
remoteSort : true,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
} ]
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 200
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 400,
sortable : false
} ]
});
this.bbar = {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
};
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreate,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this.onModify,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDelete,
xtype : 's-menuButton'
}, {
text : i18n.get('label.users'),
icon : 'res/images/icons/icons_perso/toolbar_userman.png',
handler : this.onUsers,
xtype : 's-menuButton'
}, {
text : i18n.get('label.groups'),
icon : 'res/images/icons/icons_perso/toolbar_groupman.png',
handler : this.onGroups,
xtype : 's-menuButton'
}, '->', {
xtype : 's-filter',
emptyText : i18n.get('label.search'),
store : this.store,
pageSize : this.pageSize
} ]
};
this.view = new Ext.grid.GridView({
forceFit : true
});
this.listeners = {
scope : this,
rowDblClick : this.onModify
};
sitools.admin.usergroups.RoleCrudPanel.superclass.initComponent.call(this);
},
/**
* done a specific render to load roles from the store.
*/
onRender : function () {
sitools.admin.usergroups.RoleCrudPanel.superclass.onRender.apply(this, arguments);
this.store.load({
params : {
start : 0,
limit : this.pageSize
}
});
},
/**
* Open a {sitools.admin.usergroups.RolePropPanel} role panel to create a new role
*/
onCreate : function () {
var up = new sitools.admin.usergroups.RolePropPanel({
url : this.url,
action : 'create',
store : this.store
});
up.show(ID.BOX.ROLE);
},
/**
* Open a {sitools.admin.usergroups.RolePropPanel} role panel to modify an existing role
*/
onModify : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.admin.usergroups.RolePropPanel({
url : this.url + '/' + rec.id,
action : 'modify',
store : this.store
});
up.show(ID.BOX.ROLE);
},
/**
* Diplay confirm delete Msg box and call the method doDelete
*/
onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return false;
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('roleCrud.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec);
}
}
});
},
/**
* done the delete of the passed record
* @param rec the record to delete
*/
doDelete : function (rec) {
// var rec = this.getSelectionModel().getSelected();
// if (!rec) return false;
Ext.Ajax.request({
url : this.url + "/" + rec.id,
method : 'DELETE',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
/**
* Open a {sitools.admin.usergroups.UsersPanel} users panel retrieving all the users of the current role
*/
onUsers : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.admin.usergroups.UsersPanel({
mode : 'list',
url : this.url + '/' + rec.id + '/users',
data : rec.data
});
up.show(ID.BOX.ROLE);
},
/**
* Open a {sitools.admin.usergroups.GroupsPanel} groups panel retrieving all the groups of the current role
*/
onGroups : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var gp = new sitools.admin.usergroups.GroupsPanel({
mode : 'list',
url : this.url + '/' + rec.id + '/groups',
data : rec.data
});
gp.show(ID.BOX.ROLE);
}
});
Ext.reg('s-rolecrud', sitools.admin.usergroups.RoleCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp*/
Ext.namespace('sitools.admin.usergroups');
/**
* A Panel role data from a specific role
*
* @cfg {String} the url where get the role
* @cfg {String} the action to perform
* @cfg {Ext.data.JsonStore} the store where saved the roles data
* @class sitools.admin.usergroups.RolePropPanel
* @extends Ext.Window
*/
//sitools.component.usergroups.RolePropPanel = Ext.extend(Ext.Window, {
sitools.admin.usergroups.RolePropPanel = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
initComponent : function () {
if (this.action == 'modify') {
this.title = i18n.get('label.modifyRole');
} else {
this.title = i18n.get('label.createRole');
}
this.items = [ {
xtype : 'panel',
height : 450,
title : i18n.get('label.roleInfo'),
items : [ {
xtype : 'form',
border : false,
padding : 10,
items : [ {
xtype : 'hidden',
name : 'id',
fieldLabel : i18n.get('label.id'),
anchor : '100%'
}, {
xtype : 'textfield',
name : 'name',
fieldLabel : i18n.get('label.name'),
anchor : '100%',
allowBlank : false
}, {
xtype : 'textfield',
name : 'description',
fieldLabel : i18n.get('label.description'),
anchor : '100%',
growMax : 400
} ]
} ],
buttons : [ {
id : ID.ITEM.OKBUTTON,
text : i18n.get('label.ok'),
scope : this,
handler : this.onModify
}, {
id : ID.ITEM.CANCELBUTTON,
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ]
} ];
sitools.admin.usergroups.RolePropPanel.superclass.initComponent.call(this);
},
/**
* Action to perform on the button handler (modify or create)
*/
onModify : function () {
var f = this.findByType('form')[0].getForm();
if (!f.isValid()) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.invalidForm'));
return;
}
if (this.action == 'modify') {
Ext.Ajax.request({
url : this.url,
method : 'PUT',
scope : this,
jsonData : f.getValues(),
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (Json.success) {
this.store.reload();
this.close();
} else {
Ext.Msg.alert(i18n.get('label.warning'), Json.message);
}
// Ext.Msg.alert(i18n.get('label.information'),
// i18n.get('msg.uservalidate'));
},
failure : alertFailure
});
} else {
Ext.Ajax.request({
url : this.url,
method : 'POST',
scope : this,
jsonData : f.getValues(),
failure : alertFailure,
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (Json.success) {
this.store.reload();
this.close();
} else {
Ext.Msg.alert(i18n.get('label.warning'), Json.message);
}
}
});
}
},
/**
* done a specific render to load role data from the store.
*/
onRender : function () {
sitools.admin.usergroups.RolePropPanel.superclass.onRender.apply(this, arguments);
if (this.url) {
var f = this.findByType('form')[0].getForm();
if (this.action == 'modify') {
Ext.Ajax.request({
url : this.url,
method : 'GET',
scope : this,
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (data.success) {
f.setValues(data.role);
} else {
this.close();
Ext.Msg.alert(i18n.get('label.warning'), data.message);
return;
}
},
failure : alertFailure
});
}
}
}
});
Ext.reg('s-roleprop', sitools.admin.usergroups.RolePropPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.admin.usergroups');
/**
* A Panel to show register data from a specific register
*
* @cfg {String} the url where get the registers
* @cfg {Ext.data.JsonStore} the store where saved the register data
* @class sitools.admin.usergroups.RegPropPanel
* @extends Ext.Window
*/
//sitools.component.usergroups.RegPropPanel = Ext.extend(Ext.Window, {
sitools.admin.usergroups.RegPropPanel = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
storePanel : null,
initComponent : function () {
this.storePanel = this.store;
this.title = i18n.get('label.modifyRegister');
var storeProperties = new Ext.data.JsonStore({
fields : [ {
name : 'name',
type : 'string'
}, {
name : 'value',
type : 'string'
},
{
name : 'scope',
type : 'string'
}],
autoLoad : false
});
var dataScope = [ [ 'Editable' ], [ 'ReadOnly' ], [ 'Hidden' ] ];
var storeScope = new Ext.data.ArrayStore({
fields : [ 'scope' ],
data : dataScope
});
var smProperties = new Ext.grid.RowSelectionModel({
singleSelect : true
});
var cmProperties = new Ext.grid.ColumnModel({
columns : [ {
header : i18n.get('headers.name'),
dataIndex : 'name',
editor : new Ext.form.TextField({
allowBlank : false
})
}, {
header : i18n.get('headers.value'),
dataIndex : 'value',
editor : new Ext.form.TextField({
allowBlank : false
})
},
{
header : i18n.get('headers.scope'),
dataIndex : 'scope',
editor : new Ext.form.ComboBox({
typeAhead : true,
triggerAction : 'all',
lazyRender : true,
lazyInit : false,
mode : 'local',
forceSelection : true,
valueField : 'scope',
displayField : 'scope',
store : storeScope
})
}],
defaults : {
sortable : false,
width : 100
}
});
var tbar = new Ext.Toolbar({
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreateProperties
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDeleteProperties
}]
});
this.gridProperties = new Ext.grid.EditorGridPanel({
title : i18n.get('title.properties'),
id : 'userGridProperties',
height : 180,
store : storeProperties,
tbar : tbar,
cm : cmProperties,
sm : smProperties,
viewConfig : {
forceFit : true
}
});
this.items = [ {
xtype : 'panel',
height : 450,
items : [ {
xtype : 'panel',
title : i18n.get('label.userInfo'),
items : [ {
xtype : 'form',
border : false,
padding : 10,
items : [ {
xtype : 'textfield',
name : 'id',
hidden : true
}, {
xtype : 'textfield',
name : 'identifier',
fieldLabel : i18n.get('label.login'),
anchor : '100%'
}, {
xtype : 'textfield',
name : 'firstName',
fieldLabel : i18n.get('label.firstName'),
anchor : '100%'
}, {
xtype : 'textfield',
name : 'lastName',
fieldLabel : i18n.get('label.lastName'),
anchor : '100%',
growMax : 400
}, {
xtype : 'textfield',
name : 'email',
fieldLabel : i18n.get('label.email'),
anchor : '100%'
}, {
xtype : 'textfield',
fieldLabel : i18n.get('label.password'),
anchor : '100%',
inputType : 'password',
name : 'password',
id : "regPassword"
}, {
xtype : 'textfield',
fieldLabel : i18n.get('label.confirmPassword'),
anchor : '100%',
inputType : 'password',
name : 'confirmPassword',
submitValue : false,
initialPassField: 'regPassword',
vtype : 'password'
} ]
} ]
}, this.gridProperties ],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onModify
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ]
} ];
sitools.admin.usergroups.RegPropPanel.superclass.initComponent.call(this);
},
onCreateProperties : function () {
var e = new Ext.data.Record();
this.gridProperties.getStore().insert(this.gridProperties.getStore().getCount(), e);
},
onDeleteProperties : function () {
var s = this.gridProperties.getSelectionModel().getSelections();
var i, r;
for (i = 0; s[i]; i++) {
r = s[i];
this.gridProperties.getStore().remove(r);
}
},
onModify : function () {
var f = this.findByType('form')[0].getForm();
if (!f.isValid()) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.invalidForm'));
return;
}
var putObject = f.getValues();
putObject.properties = [];
this.gridProperties.getStore().each(function (item) {
putObject.properties.push({
name : item.data.name,
value : item.data.value,
scope : item.data.scope
});
});
Ext.Ajax.request({
url : this.url,
method : 'PUT',
scope : this,
jsonData : putObject,
success : function (ret) {
var jsonObject = Ext.decode(ret.responseText);
if (!jsonObject.success) {
alertFailure(ret);
this.storePanel.reload();
return;
}
this.close();
this.storePanel.reload();
},
failure : alertFailure
});
},
onRender : function () {
sitools.admin.usergroups.RegPropPanel.superclass.onRender.apply(this, arguments);
if (this.url) {
var f = this.findByType('form')[0].getForm();
Ext.Ajax.request({
url : this.url,
method : 'GET',
scope : this,
success : function (ret) {
var data = Ext.decode(ret.responseText);
data.inscription.password = "";
f.setValues(data.inscription);
if (!Ext.isEmpty(data.inscription.properties)) {
Ext.each(data.inscription.properties, function (property) {
var rec = new Ext.data.Record({
name : property.name,
value : property.value,
scope : property.scope
});
this.gridProperties.getStore().add(rec);
}, this);
}
},
failure : alertFailure
});
}
}
});
Ext.reg('s-regprop', sitools.admin.usergroups.RegPropPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.admin.usergroups');
/**
* A Panel user data from a specific user
*
* @cfg {String} the url where get the user
* @cfg {String} the action to perform
* @cfg {Ext.data.JsonStore} the store where saved the user data
* @class sitools.admin.usergroups.UserPropPanel
* @extends Ext.Window
*/
//sitools.component.usergroups.UserPropPanel = Ext.extend(Ext.Window, {
sitools.admin.usergroups.UserPropPanel = Ext.extend(Ext.Window, {
id: 'winCreateUser',
width : 700,
height : 480,
modal : true,
pageSize : 10,
// quotaStore : new Ext.data.JsonStore({
// fields: [
// {name: 'vol', type: 'string'},
// {name: 'used', type: 'float'},
// {name: 'quota', type: 'float'},
// {name: 'unit', type: 'string'},
// {name: 'quota_enabled', type: 'boolean'}
// ]}),
//
// joinCheck : new Ext.grid.CheckColumn({dataIndex: 'join', header:
// i18n.get('header.add')}),
// quotaCheck : new Ext.grid.CheckColumn({dataIndex: 'quota_enabled',
// header: i18n.get('header.enabledquota')}),
initComponent : function () {
if (this.action == "create") {
this.title = i18n.get('label.createUser');
} else {
this.title = i18n.get('label.modifyUser');
}
// this.joinCheck.header = i18n.get('header.add');
// this.quotaCheck.header = i18n.get('header.enabledquota');
// this.groupStore = new Ext.data.JsonStore({
// root: 'data',
// restful: true,
// url:this.url+'/groups',
// fields: [
// {name: 'name', type: 'string'},
// {name: 'description', type: 'string'},
// {name: 'join', type: 'boolean'},
// ]});
var storeProperties = new Ext.data.JsonStore({
fields : [ {
name : 'name',
type : 'string'
}, {
name : 'value',
type : 'string'
},
{
name : 'scope',
type : 'string'
}],
autoLoad : false
});
var dataScope = [ [ 'Editable' ], [ 'ReadOnly' ], [ 'Hidden' ] ];
var storeScope = new Ext.data.ArrayStore({
fields : ['scope'],
data : dataScope
});
var smProperties = new Ext.grid.RowSelectionModel({
singleSelect : true
});
var cmProperties = new Ext.grid.ColumnModel({
columns : [ {
header : i18n.get('headers.name'),
dataIndex : 'name',
editor : new Ext.form.TextField({
allowBlank : false
})
}, {
header : i18n.get('headers.value'),
dataIndex : 'value',
editor : new Ext.form.TextField({
allowBlank : false
})
},
{
header : i18n.get('headers.scope'),
dataIndex : 'scope',
editor : new Ext.form.ComboBox({
typeAhead : true,
triggerAction : 'all',
lazyRender : true,
lazyInit : false,
mode : 'local',
forceSelection : true,
valueField : 'scope',
displayField : 'scope',
store : storeScope
})
}],
defaults : {
sortable : false,
width : 100
}
});
var tbar = new Ext.Toolbar({
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreateProperties
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDeleteProperties
}]
});
this.gridProperties = new Ext.grid.EditorGridPanel({
title : i18n.get('title.properties'),
id : 'userGridProperties',
height : 180,
store : storeProperties,
tbar : tbar,
cm : cmProperties,
sm : smProperties,
viewConfig : {
forceFit : true
}
});
this.items = [ {
// xtype: 'tabpanel',
// activeTab: 0,
// layoutOnTabChange: true,
// height: 450,
// items: [
// {
xtype : 'panel',
height : 450,
title : i18n.get('label.userInfo'),
items : [ {
xtype : 'form',
id: 'formCreateUser',
border : false,
padding : 10,
items : [ {
xtype : 'textfield',
name : 'firstName',
fieldLabel : i18n.get('label.firstName'),
anchor : '100%',
allowBlank : false
}, {
xtype : 'textfield',
name : 'lastName',
fieldLabel : i18n.get('label.lastName'),
anchor : '100%',
growMax : 400,
allowBlank : false
}, {
xtype : 'textfield',
name : 'email',
fieldLabel : i18n.get('label.email'),
vtype: 'uniqueemail',
allowBlank: false,
validationEvent : '',
anchor : '100%'
}, {
xtype : 'textfield',
name : 'identifier',
fieldLabel : i18n.get('label.login'),
anchor : '100%',
allowBlank : false,
disabled : this.action == "create" ? false : true,
vtype : "name",
id : "nameField"
}, {
xtype : 'textfield',
fieldLabel : i18n.get('label.password'),
anchor : '100%',
inputType : 'password',
name : 'secret',
value : '',
id : "passwordField",
vtype: 'passwordlength'
}, {
id : "confirmSecret",
xtype : 'textfield',
fieldLabel : i18n.get('label.confirmPassword'),
anchor : '100%',
inputType : 'password',
initialPassField: 'passwordField',
vtype: 'password',
name : 'confirmSecret',
submitValue : false,
value : ''
}, {
xtype : 'button',
name : 'generate',
id : 'generatePass',
text : i18n.get('label.generatePassword'),
anchor : '9%',
handler : this.generatePassword
} ]
}, this.gridProperties],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onModifyOrCreate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ]
} ];
// ,
// {
// xtype: 'panel',
// title: i18n.get('label.userGroups'),
// items: [
// {
// xtype: 'grid',
// store: this.groupStore,
// plugins: this.joinCheck,
// height: 400,
// columns: [
// {header: i18n.get('label.name'), dataIndex: 'name', width: 100},
// {header: i18n.get('label.description'), dataIndex: 'description',
// width: 400},
// this.joinCheck
// ]
// }
// ]
// },
// {
// xtype: 'panel',
// title: i18n.get('label.userQuota'),
// items: [
// {
// xtype: 'editorgrid',
// store: this.quotaStore,
// plugins: this.quotaCheck,
// height: 400,
// columns: [
// {xtype: 'gridcolumn', dataIndex: 'vol', header:
// i18n.get('label.volume'), width: 100, editor: {xtype: 'textfield'}},
// {xtype: 'numbercolumn', dataIndex: 'used', header:
// i18n.get('label.usedcapacity'), width: 100, align: 'right', editor:
// {xtype: 'numberfield'}},
// {xtype: 'numbercolumn', dataIndex: 'quota', header:
// i18n.get('label.quota'), width: 100, align: 'right', format:'0',
// editor: {xtype: 'numberfield'}},
// {dataIndex: 'unit', header: i18n.get('headers.unit'), align: 'right',
// width: 100, editor:
// { xtype:'combo', mode:'local', editable:false, width:30,
// triggerAction:'all', lazyRender:true,
// store: new Ext.data.ArrayStore({fields: ['v','l'], data:
// [['MB','MB'],['GB','GB']] }),
// valueField: 'v', displayField: 'l' }
// },
// this.quotaCheck
// ]
// }
// ]
// }
// ],
// }
// ];
sitools.admin.usergroups.UserPropPanel.superclass.initComponent.call(this);
},
/**
* Create a new record to add a property to the current user
*/
onCreateProperties : function () {
var e = new Ext.data.Record();
this.gridProperties.getStore().insert(this.gridProperties.getStore().getCount(), e);
},
/**
* Delete the selected user property
*/
onDeleteProperties : function () {
var s = this.gridProperties.getSelectionModel().getSelections();
var i, r;
for (i = 0; s[i]; i++) {
r = s[i];
this.gridProperties.getStore().remove(r);
}
},
/**
* Create or save an user properties
*/
onModifyOrCreate : function () {
var method = (this.action == "create") ? "POST" : "PUT";
var f = this.findByType('form')[0].getForm();
if (!f.isValid()) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.invalidForm'));
return;
}
var putObject = f.getValues();
putObject.properties = [];
this.gridProperties.getStore().each(function (item) {
putObject.properties.push({
name : item.data.name,
value : item.data.value,
scope : item.data.scope
});
});
Ext.Ajax.request({
url : this.url,
method : method,
scope : this,
jsonData : putObject,
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (!data.success) {
Ext.Msg.alert(i18n.get('label.warning'), data.message);
return false;
}
this.close();
this.store.reload();
// Ext.Msg.alert(i18n.get('label.information'),
// i18n.get('msg.uservalidate'));
},
failure : alertFailure
});
},
/**
* done a specific render to load informations from the user.
*/
onRender : function () {
sitools.admin.usergroups.UserPropPanel.superclass.onRender.apply(this, arguments);
if (this.url) {
// var gs = this.groupStore, qs = this.quotaStore;
Ext.Ajax.request({
url : this.url,
method : 'GET',
scope : this,
success : function (ret) {
var f = this.findByType('form')[0].getForm();
var data = Ext.decode(ret.responseText);
if (data.user !== undefined) {
f.setValues(data.user);
f.findField('identifier').setValue(data.user.identifier);
if (!Ext.isEmpty(data.user.properties)) {
Ext.each(data.user.properties, function (property) {
var rec = new Ext.data.Record({
name : property.name,
value : property.value,
scope : property.scope
});
this.gridProperties.getStore().add(rec);
}, this);
}
}
},
failure : alertFailure
});
}
},
/**
* Generate a random password
*/
generatePassword : function () {
var chars = "!0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 6;
var randomstring = '';
for (var i = 0; i < string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum, rnum + 1);
}
var f = Ext.getCmp('formCreateUser').getForm();
f.findField('secret').setValue(randomstring);
f.findField('confirmSecret').setValue(randomstring);
}
});
Ext.reg('s-userprop', sitools.admin.usergroups.UserPropPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp*/
Ext.namespace('sitools.admin.usergroups');
/**
* A Panel to show group properties from a specific group
*
* @cfg {String} the action to perform (modify or create)
* @cfg {String} the url where get the resource
* @cfg {Ext.data.JsonStore} the store where get the record
* @class sitools.admin.usergroups.GroupPropPanel
* @extends Ext.Window
*/
//sitools.component.usergroups.GroupPropPanel = Ext.extend(Ext.Window, {
sitools.admin.usergroups.GroupPropPanel = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
pageSize : 10,
initComponent : function () {
if (this.action == "create") {
this.title = i18n.get('label.createGroup');
} else {
this.title = i18n.get('label.modifyGroup');
}
this.items = [ {
// xtype: 'tabpanel',
// activeTab: 0,
// layoutOnTabChange: true,
// height: 450,
// items: [
// {
xtype : 'panel',
height : 450,
title : i18n.get('label.groupInfo'),
items : [ {
xtype : 'form',
border : false,
padding : 10,
items : [ {
xtype : 'textfield',
name : 'name',
fieldLabel : i18n.get('label.name'),
anchor : '100%',
disabled : this.action != "create",
allowBlank : false
}, {
xtype : 'textfield',
name : 'description',
fieldLabel : i18n.get('label.description'),
anchor : '100%',
growMax : 400
} ]
} ],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onModifyOrCreate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ]
} ];
// ,
// {
// xtype: 'panel',
// disabled: true,
// title: i18n.get('label.groupPrivileges'),
// items: [
// {
// xtype: 'grid',
// height: 400,
// columns: [
// {
// xtype: 'gridcolumn',
// dataIndex: 'string',
// header: 'Name',
// sortable: true,
// width: 100,
// editable: false
// },
// {
// xtype: 'booleancolumn',
// dataIndex: 'bool',
// header: 'R',
// sortable: true,
// width: 100
// },
// {
// xtype: 'booleancolumn',
// dataIndex: 'bool',
// header: 'W',
// sortable: true,
// width: 100
// }
// ]
// }
// ]
// }
// ],
//
// }
// ];
sitools.admin.usergroups.GroupPropPanel.superclass.initComponent.call(this);
},
/**
* Create or save a group properties
*/
onModifyOrCreate : function () {
var jsonGroup = {};
var f = this.findByType('form')[0].getForm();
if (!f.isValid()) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.invalidForm'));
return;
}
Ext.iterate(f.getFieldValues(), function (key, value) {
jsonGroup[key] = value;
});
var method = (this.action === "create") ? "POST" : "PUT";
if (!f.isValid()) {
Ext.Msg.alert(i18n.get('warning.invalidForm'));
return;
}
Ext.Ajax.request({
url : this.url,
method : method,
scope : this,
jsonData : jsonGroup,
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (!data.success) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get(data.message));
return false;
}
this.close();
this.store.reload();
// Ext.Msg.alert(i18n.get('label.information'),
// i18n.get('msg.uservalidate'));
},
failure : alertFailure
});
},
/**
* done a specific render to load informations from the group.
*/
onRender : function () {
sitools.admin.usergroups.GroupPropPanel.superclass.onRender.apply(this, arguments);
if (this.url) {
var f = this.findByType('form')[0].getForm();
Ext.Ajax.request({
url : this.url,
method : 'GET',
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (data.group !== undefined) {
f.setValues(data.group);
}
},
failure : alertFailure
});
}
}
});
Ext.reg('s-groupprop', sitools.admin.usergroups.GroupPropPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.admin.usergroups');
/**
* A Panel retrieving sitools2 users
*
* @cfg {String} the mode (select or list) to load roles
* @cfg {String} the url where get the selected user property
* @cfg {Ext.form.TextField} the user field
* @cfg {Ext.form.Field} the value of the user field
* @class sitools.admin.usergroups.UsersPanel
* @extends Ext.Window
*/
//sitools.component.usergroups.UsersPanel = Ext.extend(Ext.Window, {
sitools.admin.usergroups.UsersPanel = Ext.extend(Ext.Window, {
// url + mode + storeref
width : 350,
modal : true,
closable : false,
pageSize : 10,
initComponent : function () {
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
autoSave : false,
idProperty : 'identifier',
url : this.url,
fields : [ {
name : 'identifier',
type : 'string'
}, {
name : 'firstName',
type : 'string'
}, {
name : 'lastName',
type : 'string'
} ]
});
this.grid = new Ext.grid.GridPanel({
xtype : 'grid',
sm : new Ext.grid.RowSelectionModel(),
store : this.store,
height : 200,
columns : [ {
header : i18n.get('label.login'),
dataIndex : 'identifier'
}, {
header : i18n.get('label.firstName'),
dataIndex : 'firstName'
}, {
header : i18n.get('label.lastName'),
dataIndex : 'lastName'
} ],
bbar : {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
}
});
this.items = [ {
xtype : 'panel',
title : this.mode == 'list' ? i18n.get('label.members') : i18n.get('label.selectUsers'),
items : [ this.grid ],
tbar : {
xtype : 'toolbar',
defaults : {
scope : this,
hidden : true
},
items : [ {
text : i18n.get('label.add'),
hidden : (this.mode == 'select' || this.mode == 'selectUnique'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this._onCreate
}, {
text : i18n.get('label.remove'),
hidden : (this.mode == 'select' || this.mode == 'selectUnique'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this._onDelete
}, '->', {
xtype : 's-filter',
hidden : this.mode == 'list',
emptyText : i18n.get('label.search'),
store : this.store,
pageSize : this.pageSize
} ]
},
bbar : {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ '->', {
text : i18n.get('label.ok'),
handler : this._onAdd,
hidden : this.mode == 'list'
}, {
text : i18n.get('label.ok'),
handler : this._onOK,
hidden : (this.mode == 'select' || this.mode == 'selectUnique')
}, {
text : i18n.get('label.cancel'),
handler : this._onCancel
} ]
}
} ];
// this.relayEvents(this.store, ['destroy', 'save', 'update']);
sitools.admin.usergroups.UsersPanel.superclass.initComponent.call(this);
},
/**
* done a specific render to load users from the store.
*/
onRender : function () {
sitools.admin.usergroups.UsersPanel.superclass.onRender.apply(this, arguments);
this.store.load({
scope : this,
params : {
start : 0,
limit : this.pageSize
},
callback : function (r, options, success) {
if (!success) {
this.close();
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('label.loadError'));
}
}
});
},
/**
* Create a new {sitools.admin.usergroups.UsersPanel} users panel and display all users
*/
_onCreate : function () {
var up = new sitools.admin.usergroups.UsersPanel({
mode : 'select',
url : loadUrl.get('APP_URL') + loadUrl.get('APP_SECURITY_URL') + '/users?media=json',
storeref : this.store
});
up.show(this);
},
/**
* Delete the selected user from the store
*/
_onDelete : function () {
var rec = this.grid.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
this.store.remove(rec);
},
/**
* Gets the selected users and add them to the list users of the current parent object
*/
_onAdd : function () { // sub window -> no action
if (this.mode == "select") {
var recs = this.grid.getSelectionModel().getSelections();
var newrecs = [];
Ext.each(recs, function (rec) {
newrecs.push(new this.store.recordType({
identifier : rec.data.identifier,
firstName : rec.data.firstName,
lastName : rec.data.lastName
}));
});
this.storeref.add(newrecs);
}
if (this.mode == "selectUnique") {
var rec = this.grid.getSelectionModel().getSelected();
this.displayField.setValue(rec.data.firstName + " " + rec.data.lastName);
this.valueField.setValue(rec.data.identifier);
}
this.close();
},
/**
* Save the user of the current parent object
*/
_onOK : function () {
var putObject = this.data;
putObject.users = [];
this.store.each(function (record) {
var resource = {
id : record.data.identifier
};
putObject.users.push(resource);
});
Ext.Ajax.request({
url : this.url,
method : 'PUT',
scope : this,
jsonData : putObject,
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (!data.success) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get(data.message));
return false;
}
this.close();
this.store.reload();
},
failure : alertFailure
});
},
/**
* Destroy the {sitools.admin.usergroups.UsersPanel} users Panel
*/
_onCancel : function () {
this.destroy();
}
});
Ext.reg('s-users', sitools.admin.usergroups.UsersPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.admin.usergroups');
/**
* A Panel retrieving all the groups in Sitools2
*
* @cfg {String} the mode (select or list) to load groups
* @cfg {data} the groups data from the record
* @class sitools.admin.usergroups.GroupsPanel
* @extends Ext.Window
*/
//sitools.component.usergroups.GroupsPanel = Ext.extend(Ext.Window, {
sitools.admin.usergroups.GroupsPanel = Ext.extend(Ext.Window, {
// url + mode
width : 350,
modal : true,
closable : false,
pageSize : 10,
initComponent : function () {
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
autoSave : false,
idProperty : 'name',
url : this.url,
fields : [ {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
} ]
});
this.grid = new Ext.grid.GridPanel({
xtype : 'grid',
sm : new Ext.grid.RowSelectionModel(),
store : this.store,
height : 200,
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name'
}, {
header : i18n.get('label.description'),
dataIndex : 'description'
} ],
bbar : {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
}
});
this.items = [ {
xtype : 'panel',
title : this.mode == 'list' ? i18n.get('label.groups') : i18n.get('label.selectGroups'),
items : [ this.grid ],
tbar : {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.add'),
hidden : this.mode == 'select',
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this._onCreate
}, {
text : i18n.get('label.remove'),
hidden : this.mode == 'select',
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this._onDelete
}, '->', {
xtype : 's-filter',
hidden : this.mode == 'list',
emptyText : i18n.get('label.search'),
store : this.store,
pageSize : this.pageSize
} ]
},
bbar : {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ '->', {
text : i18n.get('label.add'),
handler : this._onAdd,
hidden : this.mode == 'list'
}, {
text : i18n.get('label.ok'),
handler : this._onOK,
hidden : this.mode == 'select'
}, {
text : i18n.get('label.cancel'),
handler : this._onCancel
} ]
}
} ];
sitools.admin.usergroups.GroupsPanel.superclass.initComponent.call(this);
},
/**
* done a specific render to load groups from the store.
*/
onRender : function () {
sitools.admin.usergroups.GroupsPanel.superclass.onRender.apply(this, arguments);
this.store.load({
scope : this,
params : {
start : 0,
limit : this.pageSize
},
callback : function (r, options, success) {
if (!success) {
this.close();
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('label.loadError'));
}
}
});
},
/**
* Create a new {sitools.admin.usergroups.GroupsPanel} group Panel and retrieve all the groups
*/
_onCreate : function () {
var up = new sitools.admin.usergroups.GroupsPanel({
mode : 'select',
url : loadUrl.get('APP_URL') + loadUrl.get('APP_SECURITY_URL') + '/groups?media=json',
storeref : this.store
});
up.show(this);
},
/**
* Delete the selected group from the selected role
*/
_onDelete : function () {
var rec = this.grid.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
this.store.remove(rec);
},
/**
* Gets the selected groups and add them to the list groups of the current parent object
*/
_onAdd : function () { // sub window -> no action
var recs = this.grid.getSelectionModel().getSelections();
var newrecs = [];
Ext.each(recs, function (rec) {
newrecs.push(new this.store.recordType({
name : rec.data.name,
description : rec.data.description
}));
});
this.storeref.add(newrecs);
this.close();
},
/**
* Save the groups of the current role
*/
_onOK : function () {
var putObject = this.data;
putObject.groups = [];
this.store.each(function (record) {
var resource = {
id : record.data.name
};
putObject.groups.push(resource);
});
Ext.Ajax.request({
url : this.url,
method : 'PUT',
scope : this,
jsonData : putObject,
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (!data.success) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get(data.message));
return false;
}
this.close();
this.store.reload();
},
failure : alertFailure
});
},
/**
* Destroy the {sitools.admin.usergroups.GroupsPanel} group Panel
*/
_onCancel : function () {
this.destroy();
}
});
Ext.reg('s-groups', sitools.admin.usergroups.GroupsPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.admin.projects');
/**
* A Panel to show all the datasets in Sitools2
*
* @cfg {String} the url where get the resource
* @cfg {String}, the type of mode
* @cfg {Ext.data.JsonStore} storeDatasets, the store with all datasets of the project
* @class sitools.admin.projects.datasetsWin
* @extends Ext.Window
*/
//sitools.component.projects.datasetsWin = Ext.extend(Ext.Window, {
sitools.admin.projects.datasetsWin = Ext.extend(Ext.Window, {
// url + mode + storeref
width : 350,
modal : true,
closable : false,
pageSize : 10,
id : 'projectsDatasetWinId',
initComponent : function () {
this.title = i18n.get('label.datasets');
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
autoSave : false,
idProperty : 'id',
totalProperty : 'total',
url : loadUrl.get('APP_URL') + loadUrl.get('APP_DATASETS_URL'),
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'type',
type : 'string'
}, {
name : 'mediaType',
type : 'string'
}, {
name : 'visible',
type : 'boolean'
}, {
name : 'status',
type : 'string'
}, {
name : 'nbRecords',
type : "string"
}, {
name : 'sitoolsAttachementForUsers',
type : 'string'
}, {
name : 'image'
}, {
name : 'descriptionHTML',
type : "string"
} ]
});
this.grid = new Ext.grid.GridPanel({
sm : new Ext.grid.RowSelectionModel(),
store : this.store,
height : 200,
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name'
}, {
header : i18n.get('label.description'),
dataIndex : 'description'
} ]
});
this.items = [ {
xtype : 'panel',
title : i18n.get('label.selectDataset'),
items : [ this.grid ],
bbar : {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
}
} ];
this.buttons = [{
text : i18n.get('label.ok'),
scope : this,
handler : this._onOK
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : this._onCancel
} ];
// this.relayEvents(this.store, ['destroy', 'save', 'update']);
sitools.admin.projects.datasetsWin.superclass.initComponent.call(this);
},
/**
* done a specific render to load datasets informations.
*/
onRender : function () {
sitools.admin.projects.datasetsWin.superclass.onRender.apply(this, arguments);
this.store.load({
scope : this,
params : {
start : 0,
limit : this.pageSize
},
callback : function (r, options, success) {
if (!success) {
this.close();
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('label.loadError'));
}
}
});
},
/**
* Add selected Datasets to the project
*/
_onOK : function () {
Ext.each(this.grid.getSelectionModel().getSelections(), function (dataset) {
if (this.storeDatasets.find('id', dataset.data.id) == -1) {
var image = dataset.data.image;
var properties = [{
name : "nbRecord",
value : dataset.data.nbRecords
}, {
name : "descriptionHTML",
value : dataset.data.descriptionHTML
}];
if (!Ext.isEmpty(image)) {
properties.push({
name : "imageUrl",
value : image.url
});
}
this.storeDatasets.add(new Ext.data.Record({
id : dataset.data.id,
name : dataset.data.name,
description : dataset.data.description,
type : dataset.data.type,
mediaType : dataset.data.mediaType,
visible : dataset.data.visible,
status : dataset.data.status,
properties : properties,
url : dataset.data.sitoolsAttachementForUsers
}));
}
}, this);
this.close();
},
/**
* Close the window
*/
_onCancel : function () {
this.destroy();
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.component.projects');
/**
* Create, or Edit a Project
* @cfg {String} url the url to request the project,
* @cfg {string} action should be "view", "modify", "create"
* @cfg {Ext.data.Store} store the store that contains all projects
* @cfg {string} projectName the name of the selected project if action != "create"
* @cfg {string} projectAttachement the sitoolsAttachement of the edit project.
* @class sitools.component.projects.ProjectsPropPanel
* @extends Ext.Window
*/
sitools.component.projects.ProjectsPropPanel = Ext.extend(Ext.Window, {
/** Default Width */
width : 700,
/** Default height */
height : 580,
/** Default modal */
modal : true,
/** Default pageSize for Dataset Store */
pageSize : 10,
/** Default id */
id : ID.COMPONENT_SETUP.PROJECT,
/** Default Value */
allModulesDetached : false,
/** Default Value when creating a project. */
defaultValueTpl : "default.project.ftl",
/** Default Value when creating a project. */
defaultDescription : "SITools2 est une plate-forme web conviviale permettant de mettre en place un système de recherche et d'accès aux données à partir d'une ou plusieurs bases de données existantes. SiTools2 permet de prendre en compte et de s'adapter aux structures de nombreuses bases de données qui sont gérées dans divers centres scientifiques, et permet d'éviter des processus lourds et complexes de migration de données. <div class='field-items'> <p>L'architecture de cette plate-forme est composée :</p> <ol> <li>d'un serveur de données exposant des ressources, </li><li>d'une interface web pour l'administrateur permettant de configurer l'ensemble des fonctionnalités du serveur, </li><li>d'une interface web pour les utilisateurs comportant un portail qui liste les projets, avec un bureau pour chaque projet qui expose l'ensemble des services mis à disposition par l'administrateur, </li><li>d'un mécanisme de plugins permettant aux développeurs d'ajouter des fonctionnalités métiers aussi bien au niveau du serveur qu'au niveau du client et de les partager avec une communauté d'utilisateurs. </li></ol> <p>SITools2 s'articule autour de trois concepts importants :</p> <ul> <li>la source de données : infrastructure contenant les données (actuellement une base de données relationnelle accessible via l'API JDBC), </li><li>le jeu de données : exposition d'un sous-ensemble de la source de données par l'intermédiaire d'un service web, </li><li>le projet : ensemble de jeux de données. </li></ul> <p>Des services peuvent être ensuite définis à partir de ces trois concepts :</p> <ul> <li>définition et exposition du formulaire de recherche, </li><li>définition et exposition de la recherche OpenSearch, </li><li>définition et exposition des fonctions de conversion (unité, fonction de transfert), </li><li>définition et exposition des fonctions de filtrage, </li><li>définition et exposition de dictionnaires de données, </li><li>définition et exposition de flux RSS, </li><li>définition et exposition des plugins. </li></ul> <p>Comme tout système d'accès, il est important de pouvoir sécuriser l'accès à certaines ressources selon le profil de l'utilisateur. C'est pourquoi SITools2 implémente une gestion complète des utilisateurs (information personnalisable, espace de stockage sur le serveur de données) et permet de sécuriser l'ensemble des ressources en fonction du rôle de chaque utilisateur.</p></div>",
defaultHeader : '<div id="top-header" style="background-color: black;"> <a href="http://www.cnes.fr" target="_blank"> <img src="/sitools/common/res/images/bg_cnes.jpg" style="border: none;"> </a> </div>',
/** Default Value when creating a project. */
defaultLinks : [{
name : "label.legalInformations",
url : "/sitools/common/html/legalInformations.html"
}, {
name : "label.personalInformations",
url : "/sitools/common/html/personalInformations.html"
}, {
name : "label.contacts",
url : "/sitools/common/html/contacts.html"
}, {
name : "label.help",
url : "/sitools/common/html/help.html"
}, {
name : "label.editorialInformations",
url : "/sitools/common/html/editorialInformations.html"
}],
initComponent : function () {
var action = this.action;
if (this.action === 'view') {
this.title = i18n.get('label.viewProject');
}
if (this.action === 'modify') {
this.title = i18n.get('label.modifyProject');
}
if (this.action === 'create') {
this.title = i18n.get('label.createProject');
}
var storeDataSets = new Ext.data.JsonStore({
id : 'storeDataSets',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'type',
type : 'string'
}, {
name : 'mediaType',
type : 'string'
}, {
name : 'visible',
type : 'string'
}, {
name : 'status',
type : 'string'
}, {
name : 'properties'
}, {
name : 'url',
type : 'string'
} ]
});
var cmDataSets = new Ext.grid.ColumnModel({
columns : [ {
header : i18n.get('headers.name'),
dataIndex : 'name',
width : 100
}, {
header : i18n.get('headers.description'),
dataIndex : 'description',
width : 100
} ],
defaults : {
sortable : true,
width : 100
}
});
var smDataSets = new Ext.grid.RowSelectionModel({
singleSelect : false
});
var tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.add'),
hidden : this.mode === 'select',
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this._onCreate
}, {
text : i18n.get('label.remove'),
hidden : this.mode === 'select',
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this._onDelete
}, '->', {
xtype : 's-filter',
hidden : this.mode === 'list',
emptyText : i18n.get('label.search'),
store : this.store,
pageSize : this.pageSize
} ]
};
/**
* {Ext.grid.EditorGridPanel} gridDataSets The grid that displays datasets
*/
this.gridDataSets = new Ext.grid.EditorGridPanel({
id : 'gridDataSets',
title : i18n.get('title.gridDataSets'),
store : storeDataSets,
tbar : tbar,
cm : cmDataSets,
sm : smDataSets,
viewConfig : {
forceFit : true
},
listeners : {
"activate" : function () {
if (action === 'view') {
this.getEl().mask();
}
}
}
});
/**
* {Ext.FormPanel} formProject The main Form
*/
this.formProject = new Ext.FormPanel({
title : i18n.get('label.projectInfo'),
xtype : 'form',
border : false,
autoScroll : true,
padding : 10,
trackResetOnLoad : true,
items : [ {
xtype : 'hidden',
name : 'id'
}, {
xtype : 'hidden',
name : 'maintenance'
}, {
xtype : 'textfield',
name : 'name',
fieldLabel : i18n.get('label.name'),
anchor : '100%',
maxLength : 30,
allowBlank : false
}, {
xtype : 'textfield',
name : 'description',
fieldLabel : i18n.get('label.description'),
anchor : '100%'
// ,
// maxLength : 100
}, {
xtype : 'textfield',
vtype : "attachment",
name : 'sitoolsAttachementForUsers',
fieldLabel : i18n.get('label.userAttach'),
anchor : '100%',
maxLength : 100
}, {
xtype : 'sitoolsSelectImage',
name : 'image',
fieldLabel : i18n.get('label.image'),
anchor : '100%',
growMax : 400
}, {
xtype : 'checkbox',
name : 'visible',
fieldLabel : i18n.get('label.isVisible'),
anchor : '100%',
maxLength : 100
}, {
xtype : 'htmleditor',
id : 'htmlDescription',
fieldLabel : i18n.get('label.descriptionHTML'),
height : 150,
anchor : '95%',
value : this.defaultDescription
}, {
xtype : 'htmleditor',
id : 'maintenanceText',
fieldLabel : i18n.get('label.maintenanceText'),
height : 150,
anchor : '95%'
} ],
listeners : {
"activate" : function () {
if (action === 'view') {
this.getEl().mask();
}
}
}
});
/**
* {Ext.FormPanel} formProject The main Form
*/
this.ihmProfile = new Ext.FormPanel({
title : i18n.get('label.ihmProfile'),
xtype : 'form',
border : false,
autoScroll : true,
padding : 10,
trackResetOnLoad : true,
items : [ {
xtype: 'radiogroup',
fieldLabel: i18n.get('label.navigationMode'),
items: [
{boxLabel: i18n.get('label.desktop'), name: 'navigationMode', inputValue: "desktop", checked : true},
{boxLabel: i18n.get('label.fixed'), name: 'navigationMode', inputValue: "fixed"}
]
}, {
xtype : 'textfield',
name : 'css',
fieldLabel : i18n.get('label.css'),
anchor : '100%',
maxLength : 100
}, {
xtype : 'textfield',
name : 'ftlTemplateFile',
fieldLabel : i18n.get('label.ftlTemplateFile'),
anchor : '100%',
tooltip : i18n.get("label.projectTemplateHelp"),
value : this.defaultValueTpl
}, {
xtype : 'htmleditor',
id : 'htmlHeader',
fieldLabel : i18n.get('label.htmlHeader'),
height : 150,
anchor : '95%',
value : this.defaultHeader
} ],
listeners : {
"activate" : function () {
if (action === 'view') {
this.getEl().mask();
}
}
}
});
this.allModulesAttachedBtn = new Ext.Button({
text : this.allModulesDetached ? i18n.get('label.allDetached') : i18n.get('label.allAttached'),
hidden : this.mode === 'select',
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this._onAllModulesAttached,
scope : this
});
this.listRolesBtn = new Ext.Button({
text : i18n.get('label.rolecrud'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/tree_role.png',
scope : this,
handler : this._onRoles
});
var tbarModules = {
xtype : 'sitools.widget.GridSorterToolbar',
gridId : "gridModules",
items: [this.allModulesAttachedBtn, this.listRolesBtn]
};
// The store that contains all distinct Modules
var storeAllModules = new Ext.data.JsonStore({
root : 'data',
url : loadUrl.get('APP_URL') + loadUrl.get('APP_PROJECTS_MODULES_URL'),
restful : true,
remoteSort : false,
autoSave : false,
autoLoad : true,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : "attached",
type : "boolean"
}, {
name : "listRoles"
}, {
name : "categoryModule"
}, {
name : "divIdToDisplay"
}, {
name : 'xtype',
type : 'string'
}, {
name : 'moduleConfig'
}, {
name : 'label'
}],
listeners : {
scope : this,
load : function (store) {
this.loadNonAvailableProjects(store);
if (this.action === "create") {
this._onAllModulesAttached();
var rec;
//renseigner artificiellement les deux specific div du template
var storeProject = this.modulePanel.getStore();
var recDsExplorerIdx = storeProject.find("name", "DataSetExplorer");
if (recDsExplorerIdx !== -1) {
rec = storeProject.getAt(recDsExplorerIdx);
rec.set("divIdToDisplay", "news");
}
var recNewsIdx = storeProject.find("name", "ProjectsFeeds");
if (recNewsIdx !== -1) {
rec = storeProject.getAt(recNewsIdx);
rec.set("divIdToDisplay", "shortcuts");
}
}
}
}
});
// The store that contains modules for this project.
var storeProjectModules = new Ext.data.JsonStore({
autoLoad : false,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : "attached",
type : "boolean"
}, {
name : "listRoles"
}, {
name : "categoryModule"
}, {
name : "divIdToDisplay"
}, {
name : 'xtype',
type : 'string'
}, {
name : 'listProjectModulesConfig'
}, {
name : 'label',
type : 'string'
},
{
name : 'dirty',
type : 'boolean'
}],
listeners : {
scope : this,
add : function (store) {
if (store.allAttached()) {
this.allModulesAttachedBtn.setText(i18n.get("label.Detached"));
this.allModulesDetached = true;
}
if (store.allDetached()) {
this.allModulesAttachedBtn.setText(i18n.get("label.Attached"));
this.allModulesDetached = false;
}
},
update : function (store, record) {
var index = store.indexOf(record);
if (store.allAttached()) {
this.allModulesAttachedBtn.setText(i18n.get("label.Detached"));
this.allModulesDetached = true;
}
if (store.allDetached()) {
this.allModulesAttachedBtn.setText(i18n.get("label.Attached"));
this.allModulesDetached = false;
}
}
},
allAttached : function () {
var result = true;
this.each(function (record) {
if (record.get("attached") === false) {
result = false;
return false;
}
});
return result;
},
allDetached : function () {
var result = true;
this.each(function (record) {
if (record.get("attached") === true) {
result = false;
return false;
}
});
return result;
}
});
var smModules = new Ext.grid.RowSelectionModel({
singleSelect : false
});
var attached = new Ext.grid.CheckColumn({
header : i18n.get('headers.attached'),
dataIndex : "attached",
width : 55
});
var visible = new Ext.grid.CheckColumn({
header : i18n.get('headers.visible'),
dataIndex : "visible",
width : 55
});
var cmModules = new Ext.grid.ColumnModel({
columns : [attached, {
header : i18n.get('headers.name'),
dataIndex : 'name',
width : 100
}, {
header : i18n.get('headers.description'),
dataIndex : 'description',
width : 100
}, {
header : i18n.get('headers.label'),
dataIndex : 'label',
width : 100,
editor : new Ext.form.TextField()
}, {
header : i18n.get('headers.category'),
dataIndex : 'categoryModule',
width : 100,
editor : new Ext.form.TextField()
}, {
header : i18n.get('headers.divIdToDisplay'),
dataIndex : 'divIdToDisplay',
width : 100,
editor : new Ext.form.TextField()
}, {
xtype : 'actioncolumn',
header : i18n.get('headers.projectModuleParameters'),
width : 100,
items : [{
icon : loadUrl.get('APP_URL') + "/common/res/images/icons/tree_projects_resources.png",
scope : this,
handler : function (grid, row) {
this.modulePanel.getSelectionModel().selectRow(row);
var rec = this.modulePanel.getSelectionModel().getSelected();
this._onModuleConfig(rec);
}
}],
scope : this,
renderer : function (value, metadata, record, rowInd,
colInd, store) {
if (record.data.xtype) {
try {
var getParametersMethod = eval(record.data.xtype + ".getParameters");
if (!Ext.isFunction(getParametersMethod)) {
metadata.attr += 'style="display:none;"';
}
}
catch (err) {
metadata.attr += 'style="display:none;"';
return;
}
}
}
}],
defaults : {
sortable : true,
width : 100
}
});
/**
* {Ext.grid.GridPanel} modulePanel The grid that displays modules
*/
this.modulePanel = new Ext.grid.EditorGridPanel({
id : 'gridModules',
title : i18n.get('title.modules'),
store : storeProjectModules,
cm : cmModules,
sm : smModules,
tbar : tbarModules,
viewConfig : {
forceFit : true,
getRowClass : function (row, index) {
var cls = '';
var data = row.data;
if (data.dirty) {
cls = "red-row";
}
return cls;
}
},
listeners : {
"activate" : function () {
if (action == 'view') {
this.getEl().mask();
}
}
},
plugins : [attached, visible]
});
var storeLinks = new Ext.data.JsonStore({
idProperty : 'name',
fields : [ {
name : 'name',
type : 'string'
}, {
name : 'url',
type : 'string'
}]
});
var linksPanelTbar = {
xtype : 'sitools.widget.GridSorterToolbar',
gridId : "linksPanelGrid",
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreateLink,
scope : this
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDeleteLink,
scope : this
}]
};
this.linksPanel = new Ext.grid.EditorGridPanel({
title : i18n.get('label.links'),
store : storeLinks,
tbar : linksPanelTbar,
id : "linksPanelGrid",
cm : new Ext.grid.ColumnModel({
columns : [{
header : i18n.get('headers.name'),
dataIndex : 'name',
width : 100,
editor : new Ext.form.TextField({
allowBlank : false
})
}, {
header : i18n.get('headers.url'),
dataIndex : 'url',
width : 100,
editor : new Ext.form.TextField({
allowBlank : false
})
}]
}),
sm : new Ext.grid.RowSelectionModel({
singleSelect : true
}),
viewConfig : {
forceFit : true
},
listeners : {
"activate" : function () {
if (action == 'view') {
this.getEl().mask();
}
}
}
});
/**
* {Ext.TabPanel} tabPanel the main Item of the window
*/
this.tabPanel = new Ext.TabPanel({
height : 550,
activeTab : 0,
items : [this.formProject, this.ihmProfile, this.gridDataSets, this.modulePanel, this.linksPanel ],
deferredRender : false,
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate,
hidden : this.action == "view"
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ]
});
this.items = [this.tabPanel];
this.listeners = {
scope : this,
resize : function (window, width, height) {
var size = window.body.getSize();
this.tabPanel.setSize(size);
}
};
sitools.component.projects.ProjectsPropPanel.superclass.initComponent.call(this);
},
/**
* Create a {sitools.admin.projects.datasetsWin} datasetWindow to add datasets
*/
_onCreate : function () {
var up = new sitools.admin.projects.datasetsWin({
mode : 'select',
url : loadUrl.get('APP_URL') + '/datasets',
storeDatasets : this.gridDataSets.getStore()
});
up.show(this);
},
/**
* Delete a selected Dataset
* @return {}
*/
_onDelete : function () {
var recs = this.gridDataSets.getSelectionModel().getSelections();
if (recs.length === 0) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
this.gridDataSets.getStore().remove(recs);
},
_onRoles : function () {
var rec = this.modulePanel.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var gp = new sitools.admin.usergroups.RolesPanel({
mode : 'list',
rec : rec
});
gp.show(ID.BOX.ROLE);
},
_onModuleConfig : function (){
var rec = this.modulePanel.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var mc = new sitools.admin.projects.modules.ProjectModuleConfig({
module : rec
});
mc.show(ID.BOX.PROJECTMODULECONFIG);
},
onUpload : function () {
function validate(data, config) {
config.fieldUrl.setValue(data.url);
}
var chooser = new ImageChooser({
url : loadUrl.get('APP_URL') + '/client-admin/res/json/componentList.json',
width : 515,
height : 350,
fieldUrl : this.ownerCt.items.items[0]
});
chooser.show(document, validate);
},
/**
* Check the validity of form
* and call onSaveProject method
* @return {Boolean}
*/
onValidate : function () {
var f = this.findByType('form')[0].getForm();
if (!f.isValid()) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.invalidForm'));
return false;
}
if (this.action == 'modify') {
var name = f.findField("name").getValue();
var originalName = f.findField("name").originalValue;
if (originalName != name) {
Ext.Msg.show({
title : i18n.get('label.warning'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('projectProp.warning.projectName.changed'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.onSaveProject();
}
}
});
} else {
this.onSaveProject();
}
} else {
this.onSaveProject();
}
},
/**
* Build the object to save project.
* Then call a PUT or POST request (depending on action) to save project.
*/
onSaveProject : function () {
var f = this.findByType('form')[0].getForm();
var putObject = {};
Ext.iterate(f.getValues(), function (key, value) {
if (key == 'image') {
// TODO : definir une liste de mediaType et type
putObject.image = {};
putObject.image.url = value;
putObject.image.type = "Image";
putObject.image.mediaType = "Image";
} else if (key != "visible") {
putObject[key] = value;
}
}, this);
//visible field handling
var visibleField = f.findField("visible");
putObject.visible = visibleField.getValue();
f = this.ihmProfile.getForm();
Ext.iterate(f.getValues(), function (key, value) {
putObject[key] = value;
}, this);
// //navigation Mode
// var navigationMode = f.findField("visible");
// putObject.visible = visibleField.getValue();
var store = this.findById('gridDataSets').getStore();
if (store.getCount() > 0) {
putObject.dataSets = [];
store.each(function (record) {
putObject.dataSets.push({
id : record.data.id,
description : record.data.description,
name : record.data.name,
mediaType : 'DataSet',
type : 'DataSet',
visible : record.data.visible,
status : record.data.status,
properties : record.data.properties,
url : record.data.url
});
});
}
var storeModule = this.modulePanel.getStore();
var correctlyParamModule = true;
if (storeModule.getCount() > 0) {
putObject.modules = [];
var i = 0;
storeModule.each(function (record) {
if (record.data.attached) {
if (Ext.isEmpty(record.data.listRoles)) {
record.data.listRoles = undefined;
}
record.set('dirty', false);
// Si la méthode getParameter du projectModule est implémenté on récupère les paramètres
if (record.data.xtype) {
var getParametersMethod;
try {
if (!Ext.isFunction(eval(record.data.xtype))) {
record.set('dirty', true);
Ext.Msg.alert(i18n.get('label.warning'), String.format(i18n.get('label.undefinedModule'), record.data.name));
correctlyParamModule = false;
}
getParametersMethod = eval(record.data.xtype + ".getParameters");
}
catch (err) {
var tmp = null;
}
if (Ext.isFunction(getParametersMethod)) {
var listProjectModulesConfig;
if (record.data.listProjectModulesConfig != undefined && record.data.listProjectModulesConfig.length != 0){
listProjectModulesConfig = record.data.listProjectModulesConfig;
putObject.modules.push({
description : record.data.description,
id : record.data.id,
name : record.data.name,
visible : record.data.visible,
priority : i,
listRoles : record.data.listRoles,
categoryModule : record.data.categoryModule,
divIdToDisplay : record.data.divIdToDisplay,
xtype : record.data.xtype,
listProjectModulesConfig : listProjectModulesConfig,
label : record.data.label
});
}
else {
// var ind = storeModule.indexOf(record);
// var row = this.modulePanel.getView().getRow(ind);
// row.style.color = "#FF0033";
record.set('dirty', true);
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('label.needToParamModule'));
correctlyParamModule = false;
}
}
else {
putObject.modules.push({
description : record.data.description,
id : record.data.id,
name : record.data.name,
visible : record.data.visible,
priority : i,
listRoles : record.data.listRoles,
categoryModule : record.data.categoryModule,
divIdToDisplay : record.data.divIdToDisplay,
xtype : record.data.xtype,
label : record.data.label
});
}
}
else {
putObject.modules.push({
description : record.data.description,
id : record.data.id,
name : record.data.name,
visible : record.data.visible,
priority : i,
listRoles : record.data.listRoles,
categoryModule : record.data.categoryModule,
divIdToDisplay : record.data.divIdToDisplay,
label : record.data.label
});
}
i++;
}
}, this);
}
var storeLinks = this.linksPanel.getStore();
if (storeLinks.getCount() > 0) {
putObject.links = [];
storeLinks.each(function (record) {
putObject.links.push({
name : record.get("name"),
url : record.get("url")
});
});
}
var method = (this.action == 'modify') ? "PUT" : "POST";
if (correctlyParamModule) {
Ext.Ajax.request({
url : this.url,
method : method,
scope : this,
jsonData : putObject,
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (data.success === false) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get(data.message));
} else {
this.close();
this.store.reload();
}
// Ext.Msg.alert(i18n.get('label.information'),
// i18n.get('msg.uservalidate'));
},
failure : alertFailure
});
}
},
/**
* do a specific render to fill informations from the project.
*/
onRender : function () {
sitools.component.projects.ProjectsPropPanel.superclass.onRender.apply(this, arguments);
// console.log('onRender');
if (this.url) {
// var gs = this.groupStore, qs = this.quotaStore;
if (this.action == 'modify' || this.action == "view") {
Ext.Ajax.request({
url : this.url,
method : 'GET',
scope : this,
success : function (ret) {
var f = this.findByType('form')[0].getForm();
var grid = this.findById('gridDataSets');
var store = grid.getStore();
var data = Ext.decode(ret.responseText).project;
var dataSets = data.dataSets;
// Chargement des dataSets disponible et mise a jour de
Ext.each(dataSets, function (dataSet) {
var rec = {};
rec.id = dataSet.id;
rec.name = dataSet.name;
rec.description = dataSet.description;
rec.type = dataSet.description;
rec.mediaType = dataSet.mediaType;
rec.status = dataSet.status;
rec.visible = dataSet.visible;
rec.properties = dataSet.properties;
rec.url = dataSet.url;
store.add(new Ext.data.Record(rec));
});
// ceuw attaches au projet
var rec = {};
rec.id = data.id;
rec.name = data.name;
rec.description = data.description;
rec.sitoolsAttachementForUsers = data.sitoolsAttachementForUsers;
rec.image = data.image.url;
rec.visible = data.visible;
rec.htmlDescription = data.htmlDescription;
rec.maintenanceText = data.maintenanceText;
rec.maintenance = data.maintenance;
var record = new Ext.data.Record(rec);
f.loadRecord(record);
rec = {};
rec.css = data.css;
rec.htmlHeader = data.htmlHeader;
rec.ftlTemplateFile = data.ftlTemplateFile;
rec.navigationMode = data.navigationMode;
f = this.ihmProfile.getForm();
f.setValues(rec);
//Mise a jour manuelle de la combo
try {
this.ihmProfile.find('xtype', 'radiogroup')[0].setValue(rec.navigationMode);
}
catch (err) {
var tmp;
}
//Chargement manuel du store de project Module
if (!Ext.isEmpty(data.modules)) {
Ext.each(data.modules, function (module) {
var rec = new Ext.data.Record(Ext.apply(module, {
attached : true
}));
this.modulePanel.getStore().add(rec);
}, this);
}
var links = data.links;
var storeLinks = this.linksPanel.getStore();
if (!Ext.isEmpty(links)) {
Ext.each(links, function (item) {
storeLinks.add(new Ext.data.Record(item));
}, this);
}
},
failure : function (ret) {
var data = Ext.decode(ret.responseText);
Ext.Msg.alert(i18n.get('label.warning'), data.errorMessage);
}
});
}
if (this.action === "create") {
this.fillDefaultLinks();
}
}
},
fillDefaultLinks : function () {
Ext.each(this.defaultLinks, function (link) {
var rec = new Ext.data.Record(link);
this.linksPanel.getStore().add(rec);
}, this);
},
/**
* Will fill information from the project to the modulesRecords.
* Then will call a sort on the store
* @param {[Ext.data.Records]} modulesRecords an Array of records loaded from request to modules application
* @param {} project the project object containing projectModules
*/
displayProjectModules : function (modulesRecords, project) {
if (this.action === 'create') {
this.modulePanel.getStore().each(function (rec) {
rec.set("attached", true);
});
}
else {
Ext.each(modulesRecords, function (moduleRec) {
moduleRec.set("priority", modulesRecords.length + 1);
Ext.each(project.modules, function (projectModule) {
if (moduleRec.id == projectModule.id) {
moduleRec.set("attached", true);
moduleRec.set("priority", projectModule.priority);
moduleRec.set("listRoles", projectModule.listRoles);
moduleRec.set("divIdToDisplay", projectModule.divIdToDisplay);
moduleRec.set("categoryModule", projectModule.categoryModule);
moduleRec.set("xtype", projectModule.xtype);
return false;
}
});
});
}
this.modulePanel.getStore().sort('priority');
},
/**
* Called when this.allModulesAttachedBtn is pressed
*/
_onAllModulesAttached : function () {
var attach = this.allModulesDetached;
this.modulePanel.getStore().each(function (rec) {
rec.set("attached", ! attach);
}, this);
},
/**
* Add a new Record to the dependencies property of a project module
*/
onCreateLink : function () {
var e = new Ext.data.Record();
this.linksPanel.getStore().insert(this.linksPanel.getStore().getCount(), e);
},
/**
* Delete the selected dependency of a project module
*/
onDeleteLink : function () {
var s = this.linksPanel.getSelectionModel().getSelections();
var i, r;
for (i = 0; s[i]; i++) {
r = s[i];
this.linksPanel.getStore().remove(r);
}
},
loadNonAvailableProjects : function (store) {
store.each(function (rec) {
// Chargement des dependances pour permettre le parametrage du module dans le projet
// pour eviter de recharger la page
if (!Ext.isEmpty(rec.get('dependencies') && !Ext.isEmpty(rec.get('dependencies').js))) {
Ext.each(rec.get('dependencies').js, function (dependencies) {
includeJs(dependencies.url);
}, this);
}
var storeModules = this.modulePanel.getStore();
if (storeModules.findExact("name", rec.get('name')) == -1) {
storeModules.add(rec);
}
}, this);
// this.modulePanel.getView().refresh();
}
});
Ext.reg('s-projectsprop', sitools.component.projects.ProjectsPropPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.component.projects');
sitools.component.projects.projectsCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.PROJECTS,
sm : new Ext.grid.RowSelectionModel(),
pageSize : 10,
// loadMask: true,
initComponent : function () {
this.url = loadUrl.get('APP_URL') + loadUrl.get('APP_PROJECTS_URL');
/*
* // The new DataWriter component. var writer = new
* Ext.data.JsonWriter({ encode: false // <-- don't return encoded JSON --
* causes Ext.Ajax#request to send data using jsonData config rather
* than HTTP params });
*/
// create the restful Store
// Method url action
// POST /groups create
// GET /groups read
// PUT /groups/id update
// DESTROY /groups/id delete
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
url : this.url,
remoteSort : true,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'image',
type : 'string',
mapping : 'image.url'
}, {
name : 'description',
type : 'string'
}, {
name : 'status',
type : 'string'
}, {
name : 'maintenance',
type : 'boolean'
} ]
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : false
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100,
sortable : true
}, {
header : i18n.get('label.image'),
dataIndex : 'image',
width : 300
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 400
}, {
header : i18n.get('label.status'),
dataIndex : 'status',
width : 150
}, {
header : i18n.get('label.maintenance'),
dataIndex : 'maintenance',
width : 150,
renderer: function (value) {
if (value) {
return '<div class="sitools-maintenance"> </div>';
}
else {
return '<div> </div>';
}
}
} ]
});
this.bbar = {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
};
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreate,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this.onModify,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDelete,
xtype : 's-menuButton'
}, {
text : i18n.get('label.active'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_active.png',
handler : this._onActive,
xtype : 's-menuButton'
}, {
text : i18n.get('label.disactive'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_disactive.png',
handler : this._onDisactive,
xtype : 's-menuButton'
}, '-', {
text : i18n.get('label.startmaintenance'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_active.png',
handler : this._onStartMaintenance,
xtype : 's-menuButton'
}, {
text : i18n.get('label.stopmaintenance'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_disactive.png',
handler : this._onStopMaintenance,
xtype : 's-menuButton'
},
// { text: i18n.get('label.members'), icon:
// 'res/images/icons/toolbar_group_add.png', handler: this.onMembers
// },
'->', {
xtype : 's-filter',
emptyText : i18n.get('label.search'),
store : this.store,
pageSize : this.pageSize
} ]
};
this.view = new Ext.grid.GridView({
forceFit : true
});
this.listeners = {
scope : this,
rowDblClick : this.onModify
};
sitools.component.projects.projectsCrudPanel.superclass.initComponent.call(this);
},
onRender : function () {
sitools.component.projects.projectsCrudPanel.superclass.onRender.apply(this, arguments);
this.store.load({
params : {
start : 0,
limit : this.pageSize
}
});
},
onCreate : function () {
var up = new sitools.component.projects.ProjectsPropPanel({
url : this.url,
action : 'create',
store : this.getStore()
});
up.show(ID.BOX.PROJECTS);
},
onModify : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
// if (rec.data.status == i18n.get('status.active')) {
// Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.wrongStatus'));
// return;
// }
var up = new sitools.component.projects.ProjectsPropPanel({
url : this.url + '/' + rec.id,
action : rec.data.status == 'ACTIVE' ? "view" : "modify",
store : this.getStore(),
projectName : rec.name,
projectAttachement : rec.sitoolsAttachementForUsers
});
up.show(ID.BOX.PROJECTS);
},
/**
* Handler to delete a project
* @return {Boolean} false if there is an error while deleting the project
*/
onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return false;
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('projectCrud.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec);
}
}
});
},
/**
* Delete the project with the specified identifier given
* @param {String} rec the identifier of the project to delete
*/
doDelete : function (rec) {
// var rec = this.getSelectionModel().getSelected();
// if (!rec) return false;
Ext.Ajax.request({
url : this.url + "/" + rec.id,
method : 'DELETE',
scope : this,
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
_onStartMaintenance : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.url + '/' + rec.id + '/startmaintenance',
method : 'PUT',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
_onStopMaintenance : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.url + '/' + rec.id + '/stopmaintenance',
method : 'PUT',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
_onActive : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.url + '/' + rec.id + '/start',
method : 'PUT',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
_onDisactive : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.url + '/' + rec.id + '/stop',
method : 'PUT',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
}
});
Ext.reg('s-projects', sitools.component.projects.projectsCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
/*
* @include "../id.js"
* @include "CollectionsPropPanel.js"
*/
Ext.namespace('sitools.admin.collections');
//sitools.component.forms.formsCrudPanel = Ext.extend(Ext.grid.GridPanel, {
/**
* A GridPanel to show all collections.
* @class sitools.admin.collections.CollectionsCrudPanel
* @extends Ext.grid.GridPanel
* @requires sitools.admin.collections.CollectionsPropPanel
*/
sitools.admin.collections.CollectionsCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.COLLECTIONS,
pageSize : 10,
// loadMask: true,
initComponent : function () {
this.urlCollections = loadUrl.get('APP_URL') + loadUrl.get('APP_COLLECTIONS_URL');
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
url : this.urlCollections,
remoteSort : true,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
} ],
autoLoad : true
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100,
sortable : true
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 400,
sortable : false
} ]
});
this.bbar = {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
};
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreate,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this.onModify,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDelete,
xtype : 's-menuButton'
}, '->', {
xtype : 's-filter',
emptyText: i18n.get('label.search'),
store : this.store,
pageSize : this.pageSize
}]
};
this.view = new Ext.grid.GridView({
forceFit : true
});
this.listeners = {
scope : this,
rowDblClick : this.onModify
};
sitools.admin.collections.CollectionsCrudPanel.superclass.initComponent.call(this);
},
/**
* Action on Create Button
*/
onCreate : function () {
var up = new sitools.admin.collections.CollectionsPropPanel({
urlCollections : this.urlCollections,
action : 'create',
store : this.getStore()
});
up.show(ID.BOX.FORMS);
},
/**
* Action on Modify Button
*/
onModify : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.admin.collections.CollectionsPropPanel({
urlCollections : this.urlCollections + "/" + rec.data.id,
action : 'modify',
store : this.getStore()
});
up.show();
},
/**
* Action on Delete Button
*/
onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return false;
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('collectionsCrud.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec);
}
}
});
},
/**
* send the Delete request
*/
doDelete : function (rec) {
// var rec = this.getSelectionModel().getSelected();
// if (!rec) return false;
Ext.Ajax.request({
url : this.urlCollections + "/" + rec.id,
method : 'DELETE',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
}
});
Ext.reg('s-collections', sitools.admin.collections.CollectionsCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
/*
* @include "../id.js"
* @include "../projects/datasetsWin.js"
*/
Ext.namespace('sitools.admin.collections');
/**
* Create, or Edit a Collection
* @cfg {String} urlCollections the url to request the collection,
* @cfg {string} action should be "modify", "create"
* @cfg {Ext.data.Store} store the store that contains all collections
* @class sitools.admin.collections.CollectionsPropPanel
* @extends Ext.Window
*/
sitools.admin.collections.CollectionsPropPanel = Ext.extend(Ext.Window, {
width : 700,
height : 580,
modal : true,
pageSize : 10,
dataSets : "",
id : ID.COMPONENT_SETUP.COLLECTIONS,
allModulesDetached : false,
allModulesInvisible : false,
initComponent : function () {
var action = this.action;
if (this.action == 'modify') {
this.title = i18n.get('label.modifyCollection');
}
if (this.action == 'create') {
this.title = i18n.get('label.createCollection');
}
var storeDataSets = new Ext.data.JsonStore({
id : 'storeDataSets',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'type',
type : 'string'
}, {
name : 'mediaType',
type : 'string'
}, {
name : 'visible',
type : 'string'
}, {
name : 'status',
type : 'string'
}, {
name : 'properties'
}, {
name : 'url',
type : 'string'
} ]
});
var cmDataSets = new Ext.grid.ColumnModel({
columns : [ {
header : i18n.get('headers.name'),
dataIndex : 'name',
width : 100
}, {
header : i18n.get('headers.description'),
dataIndex : 'description',
width : 100
} ],
defaults : {
sortable : true,
width : 100
}
});
var smDataSets = new Ext.grid.RowSelectionModel({
singleSelect : false
});
var tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.add'),
hidden : this.mode == 'select',
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this._onAttachDataset
}, {
text : i18n.get('label.remove'),
hidden : this.mode == 'select',
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this._onDeleteDataset
} ]
};
/**
* {Ext.grid.EditorGridPanel} gridDataSets The grid that displays datasets
*/
this.gridDataSets = new Ext.grid.GridPanel({
id : 'gridDataSets',
flex : 1,
title : i18n.get('title.gridDataSets'),
store : storeDataSets,
tbar : tbar,
cm : cmDataSets,
sm : smDataSets,
viewConfig : {
forceFit : true
},
listeners : {
"activate" : function () {
if (action == 'view') {
this.getEl().mask();
}
}
}
});
/**
* {Ext.FormPanel} formCollection The main Form
*/
this.formCollection = new Ext.FormPanel({
title : i18n.get('label.CollectionInfo'),
xtype : 'form',
border : false,
padding : 10,
trackResetOnLoad : true,
items : [ {
xtype : 'hidden',
name : 'id'
}, {
xtype : 'textfield',
name : 'name',
fieldLabel : i18n.get('label.name'),
anchor : '100%',
maxLength : 30,
allowBlank : false
}, {
xtype : 'textfield',
name : 'description',
fieldLabel : i18n.get('label.description'),
anchor : '100%'
}]
});
/**
* {Ext.Panel} mainPanel the main Item of the window
*/
this.mainPanel = new Ext.Panel({
height : 550,
layout : "vbox",
layoutConfig : {
align : "stretch"
},
items : [this.formCollection, this.gridDataSets],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate,
hidden : this.action == "view"
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ]
});
this.items = [this.mainPanel];
this.listeners = {
scope : this,
resize : function (window, width, height) {
var size = window.body.getSize();
this.mainPanel.setSize(size);
}
};
sitools.admin.collections.CollectionsPropPanel.superclass.initComponent.call(this);
},
/**
* Create a {sitools.admin.projects.datasetsWin} datasetWindow to add datasets
*/
_onAttachDataset : function () {
var up = new sitools.admin.projects.datasetsWin({
mode : 'select',
url : loadUrl.get('APP_URL') + '/datasets',
storeDatasets : this.gridDataSets.getStore()
});
up.show(this);
},
/**
* Delete a selected Dataset
* @return {}
*/
_onDeleteDataset : function () {
var recs = this.gridDataSets.getSelectionModel().getSelections();
if (recs.length === 0) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
this.gridDataSets.getStore().remove(recs);
},
/**
* Check the validity of form
* and call onSaveCollection method
* @return {Boolean}
*/
onValidate : function () {
var f = this.findByType('form')[0].getForm();
if (!f.isValid()) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.invalidForm'));
return false;
}
this.onSaveCollection();
},
/**
* Build the object to save collection.
* Then call a PUT or POST request (depending on action) to save collection.
*/
onSaveCollection : function () {
var f = this.findByType('form')[0].getForm();
var putObject = {};
Ext.iterate(f.getValues(), function (key, value) {
putObject[key] = value;
}, this);
var store = this.findById('gridDataSets').getStore();
if (store.getCount() > 0) {
putObject.dataSets = [];
store.each(function (record) {
putObject.dataSets.push({
id : record.data.id,
description : record.data.description,
name : record.data.name,
mediaType : 'DataSet',
type : 'DataSet',
visible : record.data.visible,
status : record.data.status,
properties : record.data.properties,
url : record.data.url
});
});
}
var method = (this.action == 'modify') ? "PUT" : "POST";
Ext.Ajax.request({
url : this.urlCollections,
method : method,
scope : this,
jsonData : putObject,
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (data.success === false) {
Ext.Msg.alert(i18n.get('label.warning'), i18n
.get(data.message));
} else {
this.close();
this.store.reload();
}
// Ext.Msg.alert(i18n.get('label.information'),
// i18n.get('msg.uservalidate'));
},
failure : alertFailure
});
},
/**
* do a specific render to fill informations from the collection.
*/
onRender : function () {
sitools.admin.collections.CollectionsPropPanel.superclass.onRender.apply(this, arguments);
if (this.urlCollections) {
// var gs = this.groupStore, qs = this.quotaStore;
if (this.action == 'modify') {
Ext.Ajax.request({
url : this.urlCollections,
method : 'GET',
scope : this,
success : function (ret) {
var f = this.findByType('form')[0].getForm();
var grid = this.findById('gridDataSets');
var store = grid.getStore();
var data = Ext.decode(ret.responseText).collection;
var dataSets = data.dataSets;
// Chargement des dataSets disponible et mise a jour de
Ext.each(dataSets, function (dataSet) {
var rec = {};
rec.id = dataSet.id;
rec.name = dataSet.name;
rec.description = dataSet.description;
rec.type = dataSet.description;
rec.mediaType = dataSet.mediaType;
rec.status = dataSet.status;
rec.visible = dataSet.visible;
rec.properties = dataSet.properties;
rec.url = dataSet.url;
store.add(new Ext.data.Record(rec));
});
// ceuw attaches au projet
var rec = {};
rec.id = data.id;
rec.name = data.name;
rec.description = data.description;
var record = new Ext.data.Record(rec);
f.loadRecord(record);
},
failure : function (ret) {
var data = Ext.decode(ret.responseText);
Ext.Msg.alert(i18n.get('label.warning'), data.errorMessage);
}
});
}
}
}
});
Ext.reg('s-collectionsprop', sitools.admin.collections.CollectionsPropPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
/*
* @include "../id.js"
* @include "MultiDsPropPanel.js"
*/
Ext.namespace('sitools.admin.multiDs');
//sitools.component.forms.formsCrudPanel = Ext.extend(Ext.grid.GridPanel, {
/**
* A Grid to display all projects Forms
* @class sitools.admin.multiDs.MultiDsCrudPanel
* @extends Ext.grid.GridPanel
* @requires sitools.admin.multiDs.MultiDsPropPanel
*/
sitools.admin.multiDs.MultiDsCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.MULTIDS,
pageSize : 10,
urlMultiDs : "/tmp",
// loadMask: true,
initComponent : function () {
this.baseUrlMultiDs = loadUrl.get('APP_URL') + loadUrl.get('APP_PROJECTS_URL');
this.urlProjects = loadUrl.get('APP_URL') + loadUrl.get('APP_PROJECTS_URL');
this.httpProxyMultiDs = new Ext.data.HttpProxy({
url : this.baseUrlMultiDs,
restful : true,
method : 'GET'
});
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
proxy : this.httpProxyMultiDs,
remoteSort : true,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'collection'
}, {
name : 'dictionary'
} ]
});
var storeProjects = new Ext.data.JsonStore({
fields : [ 'id', 'name'],
url : this.urlProjects,
root : "data",
autoLoad : true
});
this.comboProjects = new Ext.form.ComboBox({
store : storeProjects,
displayField : 'name',
valueField : 'id',
typeAhead : true,
mode : 'local',
forceSelection : true,
triggerAction : 'all',
emptyText : i18n.get('label.selectProjects'),
selectOnFocus : true,
listeners : {
scope : this,
select : function (combo, rec, index) {
// this.projectId = rec.data.id;
this.loadProject(rec.data.id);
}
}
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100,
sortable : true
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 400,
sortable : false
} ]
});
this.bbar = {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
};
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ this.comboProjects, {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreate,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this.onModify,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDelete,
xtype : 's-menuButton'
}]
};
this.view = new Ext.grid.GridView({
forceFit : true
});
this.listeners = {
scope : this,
rowDblClick : this.onModify
};
sitools.admin.multiDs.MultiDsCrudPanel.superclass.initComponent.call(this);
},
loadProject : function (projectId) {
// alert (dictionaryId);
this.httpProxyMultiDs.setUrl(this.baseUrlMultiDs + "/" + projectId + loadUrl.get('APP_FORMPROJECT_URL'), true);
this.getStore().load({
scope : this,
callback : function () {
this.getView().refresh();
}
});
},
onCreate : function () {
var projectId = this.comboProjects.getValue();
if (Ext.isEmpty(projectId)) {
return;
}
this.httpProxyMultiDs.setUrl(this.baseUrlMultiDs + "/" + projectId + loadUrl.get('APP_FORMPROJECT_URL'), true);
var up = new sitools.admin.multiDs.MultiDsPropPanel({
urlMultiDs : this.baseUrlMultiDs + "/" + projectId + loadUrl.get('APP_FORMPROJECT_URL'),
action : 'create',
store : this.getStore()
});
up.show(ID.BOX.FORMS);
},
onModify : function () {
var projectId = this.comboProjects.getValue();
if (Ext.isEmpty(projectId)) {
return;
}
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
this.httpProxyMultiDs.setUrl(this.baseUrlMultiDs + "/" + projectId + loadUrl.get('APP_FORMPROJECT_URL'), true);
var up = new sitools.admin.multiDs.MultiDsPropPanel({
urlMultiDs : this.baseUrlMultiDs + "/" + projectId + loadUrl.get('APP_FORMPROJECT_URL'),
action : 'modify',
store : this.getStore(),
formId : rec.data.id,
collection : rec.data.collection,
dictionary : rec.data.dictionary
});
up.show(ID.PROP.MULTIDSPROP);
},
onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return false;
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('formsCrud.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec);
}
}
});
},
doDelete : function (rec) {
var projectId = this.comboProjects.getValue();
if (Ext.isEmpty(projectId)) {
return;
}
Ext.Ajax.request({
url : this.baseUrlMultiDs + "/" + projectId + loadUrl.get('APP_FORMPROJECT_URL') + "/" + rec.id,
method : 'DELETE',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.httpProxyMultiDs.setUrl(this.baseUrlMultiDs + "/" + projectId + loadUrl.get('APP_FORMPROJECT_URL'), true);
this.store.reload();
}
},
failure : alertFailure
});
}
});
Ext.reg('s-multiDs', sitools.admin.multiDs.MultiDsCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
/*
* @include "../id.js"
* @include "../forms/FormGridComponents.js"
* @include "../forms/ComponentsDisplayPanel.js"
*/
Ext.namespace('sitools.admin.multiDs');
/**
* Create, or Edit a MultiDataset
* @cfg {String} urlMultiDs the url to request the project,
* @cfg {string} action should be "view", "modify", "create"
* @cfg {Ext.data.Store} store the store that contains all projects
* @cfg {string} projectId the id of the selected project
* @cfg {string} formId the id of the multiDs form if action != "create".
* @cfg {} collection the collection object in modification mode
* @cfg {} dictionary the dictionary object in modification mode
* @class sitools.admin.multiDs.MultiDsPropPanel
* @extends Ext.Window
*/
sitools.admin.multiDs.MultiDsPropPanel = Ext.extend(Ext.Window, {
width : 700,
height : 700,
modal : true,
pageSize : 10,
id : ID.COMPONENT_SETUP.MULTIDS,
collectionId : null,
dictionaryId : null,
urlCollections : null,
propServiceDefaultUrl : "/propService",
multiDSServiceDefaultUrl : "/multiDsService",
formSize : {
width : 500,
height : 600
},
initComponent : function () {
this.urlCollections = loadUrl.get('APP_URL') + loadUrl.get('APP_COLLECTIONS_URL');
this.urlDictionnaires = loadUrl.get('APP_URL') + loadUrl.get('APP_DICTIONARIES_URL');
var action = this.action;
if (this.action == 'modify') {
this.title = i18n.get('label.modifyForm');
}
if (this.action == 'create') {
this.title = i18n.get('label.createForm');
}
var storeCollections = new Ext.data.JsonStore({
id : 'storeCollections',
restful : true,
url : this.urlCollections,
root : "data",
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'dataSets'
}],
autoLoad : true,
listeners : {
scope : this,
load : function (store) {
this.fireEvent("collectionStoreLoaded", store);
}
}
});
/**
* Combo to select Datasets Views.
* Uses the storeDatasetViews.
*/
this.comboCollections = new Ext.form.ComboBox({
disabled : false,
id : "comboCollections",
store : storeCollections,
fieldLabel : i18n.get('label.collection'),
mode : 'local',
displayField : 'name',
valueField : 'name',
typeAhead : true,
name : 'comboCollections',
forceSelection : true,
triggerAction : 'all',
editable : false,
emptyText : i18n.get('label.CollectionsSelect'),
selectOnFocus : true,
anchor : '95%',
itemSelector : 'div.search-item',
allowBlank : false,
autoSelect : true,
maxHeight : 200,
tpl : new Ext.XTemplate(
'<tpl for=".">',
'<div class="search-item combo-datasetview"><div class="combo-datasetview-name">{name}</div>',
'<tpl if="this.descEmpty(description) == false" ><div class="sitoolsDescription-datasetview"><div class="sitoolsDescriptionHeader">Description : </div><p class="sitoolsDescriptionText"> {description} </p></div></tpl>',
'</div></tpl>',
{
compiled : true,
descEmpty : function (description) {
return Ext.isEmpty(description);
}
}
),
listeners : {
change : function (field, newValue, oldValue) {
this.getBubbleTarget().fireEvent("collectionChanged", field, newValue, oldValue);
},
beforeselect : function (field, record) {
var newValue = record.get("name");
var oldValue = field.getValue();
this.getBubbleTarget().fireEvent("collectionChanged", field, newValue, oldValue);
}
}
});
var storeDictionnaires = new Ext.data.JsonStore({
id : 'storeDictionnaires',
restful : true,
url : this.urlDictionnaires,
root : "data",
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}],
autoLoad : true,
listeners : {
scope : this,
load : function (store) {
this.fireEvent("dictionaryStoreLoaded", store);
}
}
});
/**
* Combo to select Dictionnaires.
* Uses the storeDictionnaires.
*/
this.comboDictionnaires = new Ext.form.ComboBox({
disabled : false,
id : "comboDictionnaires",
store : storeDictionnaires,
fieldLabel : i18n.get('label.dictionary'),
displayField : 'name',
valueField : 'name',
typeAhead : true,
name : 'comboDictionnaires',
forceSelection : true,
triggerAction : 'all',
editable : false,
emptyText : i18n.get('label.DictionarySelect'),
selectOnFocus : true,
anchor : '95%',
itemSelector : 'div.search-item',
allowBlank : false,
autoSelect : true,
maxHeight : 200,
tpl : new Ext.XTemplate(
'<tpl for=".">',
'<div class="search-item combo-datasetview"><div class="combo-datasetview-name">{name}</div>',
'<tpl if="this.descEmpty(description) == false" ><div class="sitoolsDescription-datasetview"><div class="sitoolsDescriptionHeader">Description : </div><p class="sitoolsDescriptionText"> {description} </p></div></tpl>',
'</div></tpl>',
{
compiled : true,
descEmpty : function (description) {
return Ext.isEmpty(description);
}
}
),
listeners : {
change : function (field, newValue, oldValue) {
this.getBubbleTarget().fireEvent("dictionaryChanged", field, newValue, oldValue);
},
beforeselect : function (field, record) {
var newValue = record.get("name");
var oldValue = field.getValue();
this.getBubbleTarget().fireEvent("dictionaryChanged", field, newValue, oldValue);
}
}
});
/**
* {Ext.FormPanel} formProject The main Form
*/
this.mainForm = new Ext.FormPanel({
xtype : 'form',
border : false,
padding : 10,
trackResetOnLoad : true,
id : "formMainFormId",
items : [ {
xtype : 'hidden',
name : 'id'
}, {
xtype : 'textfield',
name : 'name',
fieldLabel : i18n.get('label.name'),
anchor : '100%',
maxLength : 30,
allowBlank : false,
vtype : "nameWithoutSpace",
listeners : {
scope : this,
blur : function (field) {
if (field.isValid()) {
var urlPropField = field.ownerCt.getForm().findField("urlServicePropertiesSearch");
if (Ext.isEmpty(urlPropField.getValue())) {
urlPropField.setValue("/" + field.getValue() + this.propServiceDefaultUrl);
}
var urlMultiDsField = field.ownerCt.getForm().findField("urlServiceDatasetSearch");
if (Ext.isEmpty(urlMultiDsField.getValue())) {
urlMultiDsField.setValue("/" + field.getValue() + this.multiDSServiceDefaultUrl);
}
}
}
}
}, {
xtype : 'textfield',
name : 'description',
fieldLabel : i18n.get('label.description'),
anchor : '100%'
}, {
xtype : 'textfield',
vtype : "attachment",
name : 'urlServicePropertiesSearch',
fieldLabel : i18n.get('label.urlServicePropertiesSearch'),
anchor : '100%',
maxLength : 100
}, {
xtype : 'textfield',
vtype : "attachment",
name : 'urlServiceDatasetSearch',
fieldLabel : i18n.get('label.urlServiceDatasetSearch'),
anchor : '100%',
maxLength : 100
}, {
xtype : 'textfield',
name : 'css',
fieldLabel : i18n.get('label.css'),
anchor : '100%',
maxLength : 100
}, {
xtype : 'textfield',
name : 'nbDatasetsMax',
fieldLabel : i18n.get('label.nbDatasetsMax'),
anchor : '100%',
maxLength : 100
}, this.comboCollections, this.comboDictionnaires, {
xtype : 'hidden',
name : 'idServicePropertiesSearch'
}, {
xtype : 'hidden',
name : 'idServiceDatasetSearch'
}],
listeners : {
"activate" : function () {
if (action == 'view') {
this.getEl().mask();
}
},
collectionChanged : function (field, newValue, oldValue) {
this.getBubbleTarget().fireEvent("collectionChanged", field, newValue, oldValue);
},
dictionaryChanged : function (field, newValue, oldValue) {
this.getBubbleTarget().fireEvent("dictionaryChanged", field, newValue, oldValue);
}
},
flex : 1
});
var httpProxyConcepts = new Ext.data.HttpProxy({
url : this.action == "create" ? "/tmp" : loadUrl.get('APP_URL') + loadUrl.get('APP_COLLECTIONS_URL') + "/" + this.collection.id + "/concepts/" + this.dictionary.id,
restful : true
});
var storeConcepts = new Ext.data.JsonStore({
root : 'data',
// url : loadUrl.get('APP_URL') + loadUrl.get('APP_COLLECTIONS_URL') + "/" + config.collectionId + "/concepts/" + config.dictionaryId,
proxy : httpProxyConcepts,
restful : true,
remoteSort : false,
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}],
autoLoad : this.action != "create"
});
var cmConcepts = new Ext.grid.ColumnModel({
columns : [{
header : i18n.get("label.name"),
dataIndex : 'name',
type : 'string'
}, {
header : i18n.get("label.description"),
dataIndex : 'description',
type : 'string'
}]
});
this.gridConcepts = new Ext.grid.GridPanel({
store : storeConcepts,
cm : cmConcepts,
title : i18n.get('label.sharedConcepts'),
flex : 1,
viewConfig : {
forceFit : true
}
});
var firstPanel = new Ext.Panel({
title : i18n.get('label.FormInfo'),
layout : "vbox",
layoutConfig : {
align : "stretch"
},
items : [this.mainForm, this.gridConcepts],
listeners : {
collectionChanged : function (field, newValue, oldValue) {
this.getBubbleTarget().fireEvent("collectionChanged", field, newValue, oldValue);
},
dictionaryChanged : function (field, newValue, oldValue) {
this.getBubbleTarget().fireEvent("dictionaryChanged", field, newValue, oldValue);
}
}
});
var storeProperties = new Ext.data.JsonStore({
fields : [ {
name : 'name',
type : 'string'
}, {
name : 'type',
type : 'string'
}],
autoLoad : false
});
var smProperties = new Ext.grid.RowSelectionModel({
singleSelect : true
});
var storeTypesProperties = new Ext.data.JsonStore({
fields : ['name'],
data : [{name : "TEXTFIELD"}, {name : "NUMERIC_BETWEEN"}, {name : "DATE_BETWEEN"}, {name : "NUMBER_FIELD"}]
});
var comboTypesProperties = new Ext.form.ComboBox({
store : storeTypesProperties,
mode : 'local',
typeAhead : true,
triggerAction : 'all',
forceSelection : true,
selectOnFocus : true,
dataIndex : 'orderBy',
lazyRender : true,
listClass : 'x-combo-list-small',
valueField : 'name',
displayField : 'name',
tpl : '<tpl for="."><div class="x-combo-list-item comboItem">{name}</div></tpl>',
width : 55
});
/*
* Proxy used to request a datasource
* @type Ext.data.HttpProxy
*/
var httpProxyProperties = new Ext.data.HttpProxy({
url : this.urlCollections + "/" + this.collectionId + "/properties",
restful : true,
method : 'GET'
});
/**
* A store to request all properties from a collection.
* The url to request properties is build as
* /sitools/collections/collectionId/properties
*/
this.storeComboProperties = new Ext.data.JsonStore({
fields : [ 'id', 'name', 'description' ],
proxy : httpProxyProperties,
root : "data"
});
/*
* Combo to select Properties.
*/
var comboProperties = new Ext.form.ComboBox({
disabled : false,
id : "comboProperties",
store : this.storeComboProperties,
displayField : 'name',
valueField : 'name',
typeAhead : true,
mode : 'local',
name : 'comboProperties',
forceSelection : true,
triggerAction : 'all',
editable : false,
emptyText : i18n.get('label.comboPropertiesSelect'),
selectOnFocus : true,
allowBlank : false,
autoSelect : true
});
var cmProperties = new Ext.grid.ColumnModel({
columns : [ {
header : i18n.get('headers.name'),
dataIndex : 'name',
editor : comboProperties
}, {
header : i18n.get('headers.type'),
dataIndex : 'type',
editor : comboTypesProperties
}],
defaults : {
sortable : false,
width : 100
}
});
var tbar = {
xtype : 'sitools.widget.GridSorterToolbar',
gridId : "gridProperties",
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : function () {
var grid = this.gridProperties;
var e = new Ext.data.Record();
grid.getStore().insert(0, e);
},
scope : this
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : function () {
var grid = this.gridProperties;
var s = grid.getSelectionModel().getSelections();
var i, r;
for (i = 0; s[i]; i++) {
r = s[i];
grid.getStore().remove(r);
}
},
scope : this
} ]
};
/**
* The grid to display, create, edit properties on a multiDS search form.
* When activating this panel, the storeComboProperties url is build and the store is loaded.
*/
this.gridProperties = new Ext.grid.EditorGridPanel({
layout : "fit",
title : i18n.get('title.properties'),
id : 'gridProperties',
store : storeProperties,
tbar : tbar,
cm : cmProperties,
sm : smProperties,
viewConfig : {
forceFit : true
},
listeners : {
scope : this,
activate : function () {
this.storeComboProperties.proxy.setUrl(this.urlCollections + "/" + this.collectionId + "/properties");
this.storeComboProperties.reload();
}
}
});
/**
* A Store to store all components of this form.
* This object is the reference of all components.
*/
this.formComponentsStore = new Ext.data.JsonStore({
root : 'data',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'label',
type : 'string'
}, {
name : 'type',
type : 'string'
}, {
name : 'code',
type : 'string'
}, {
name : 'values'
}, {
name : 'width',
type : 'int'
}, {
name : 'height',
type : 'int'
}, {
name : 'xpos',
type : 'int'
}, {
name : 'ypos',
type : 'int'
}, {
name : 'css',
type : 'string'
}, {
name : 'jsAdminObject',
type : 'string'
}, {
name : 'jsUserObject',
type : 'string'
}, {
name : 'defaultValues'
}, {
name : 'valueSelection',
type : 'string'
}, {
name : 'autoComplete',
type : 'boolean'
}, {
name : 'parentParam'
}, {
name : 'dimensionId',
type : 'string'
}, {
name : 'unit'
}, {
name : 'extraParams'
}],
autoLoad : false
});
/**
* An absolute panel to display the components.
*/
this.absoluteLayout = new sitools.admin.forms.ComponentsDisplayPanel({
formComponentsStore : this.formComponentsStore,
storeConcepts : this.gridConcepts.getStore(),
context : "project",
formSize : this.formSize
});
var absContainer = new Ext.Panel({
flex : 1,
autoScroll : true,
items : [this.absoluteLayout]
});
/**
* The list with all components type.
* It is used to create new form Component by drag & drop.
*/
this.componentListPanel = new sitools.admin.forms.componentsListPanel({
formComponentsStore : this.formComponentsStore,
action : 'create',
context : "project",
storeConcepts : this.gridConcepts.getStore()
});
var dispPanel = new Ext.Panel({
layout : "hbox",
title : i18n.get('label.disposition'),
layoutConfig : {
align : "stretch"
},
items : [this.componentListPanel, absContainer],
listeners : {
scope : this,
activate : function () {
this.absoluteLayout.fireEvent('activate');
var absoluteLayout = this.absoluteLayout;
var displayPanelDropTargetEl = absoluteLayout.body.dom;
var formComponentsStore = this.formComponentsStore;
var storeConcepts = this.storeConcepts;
var gridConcepts = this.gridConcepts;
var displayPanelDropTarget = new Ext.dd.DropTarget(displayPanelDropTargetEl, {
ddGroup : 'gridComponentsList',
notifyDrop : function (ddSource, e, data) {
var xyDrop = e.xy;
var xyRef = Ext.get(absoluteLayout.body).getXY();
var xyOnCreate = {
x : xyDrop[0] - xyRef[0],
y : xyDrop[1] - xyRef[1]
};
// Reference the record (single selection) for readability
var rec = ddSource.dragData.selections[0];
var ComponentWin = new sitools.admin.forms.componentPropPanel({
urlAdmin : rec.data.jsonDefinitionAdmin,
ctype : rec.data.type,
action : "create",
componentDefaultHeight : rec.data.componentDefaultHeight,
componentDefaultWidth : rec.data.componentDefaultWidth,
dimensionId : rec.data.dimensionId,
unit : rec.data.unit,
extraParams : rec.data.extraParams,
jsAdminObject : rec.data.jsAdminObject,
jsUserObject : rec.data.jsUserObject,
context : "project",
storeConcepts : gridConcepts.getStore(),
absoluteLayout : absoluteLayout,
record : rec,
formComponentsStore : formComponentsStore,
xyOnCreate : xyOnCreate
});
ComponentWin.show();
}
});
}
}
});
/**
* The main tapPanel of the window.
*/
this.tabPanel = new Ext.TabPanel({
height : 550,
activeTab : 0,
items : [firstPanel, this.gridProperties, dispPanel],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate,
hidden : this.action == "view"
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ],
listeners : {
scope : this,
collectionChanged : function (field, newValue, oldValue) {
var index = field.getStore().find("name", newValue);
var rec = field.getStore().getAt(index);
if (!Ext.isEmpty(oldValue) && newValue != oldValue && this.formComponentsStore.getCount() > 0) {
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('warning.changeCollection'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
// this.gridFormComponents.fireEvent("collectionChanged", rec.data.id);
this.collectionId = rec.data.id;
this.loadConcepts();
this.eraseComponents();
this.eraseProperties();
} else {
field.setValue(oldValue);
}
}
});
}
else {
this.collectionId = rec.data.id;
this.loadConcepts();
}
},
dictionaryChanged : function (field, newValue, oldValue) {
var index = field.getStore().find("name", newValue);
var rec = field.getStore().getAt(index);
if (!Ext.isEmpty(oldValue) && newValue != oldValue && this.formComponentsStore.getCount() > 0) {
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('warning.changeDictionary'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.dictionaryId = rec.data.id;
this.loadConcepts();
this.eraseComponents();
} else {
field.setValue(oldValue);
}
}
});
}
else {
this.dictionaryId = rec.data.id;
this.loadConcepts();
}
}
}
});
this.items = [this.tabPanel];
/**
* Adds the events listeners :
* dictionaryStoreLoaded : Loads the shared Concept if possible,
* collectionStoreLoaded : Loads the shared Concept if possible
*/
this.listeners = {
scope : this,
resize : function (window, width, height) {
var size = window.body.getSize();
this.tabPanel.setSize(size);
},
dictionaryStoreLoaded : function (store) {
var index = store.find("name", this.comboCollections.getValue());
var rec = this.comboCollections.getStore().getAt(index);
if (Ext.isEmpty(rec)) {
return;
}
this.collectionId = rec.data.id;
if (! Ext.isEmpty(this.collectionId) && !Ext.isEmpty(this.dictionaryId)) {
this.loadConcepts();
}
},
collectionStoreLoaded : function (store) {
var index = store.find("name", this.comboDictionnaires.getValue());
var rec = this.comboDictionnaires.getStore().getAt(index);
if (Ext.isEmpty(rec)) {
return;
}
this.dictionaryId = rec.data.id;
if (! Ext.isEmpty(this.collectionId) && !Ext.isEmpty(this.dictionaryId)) {
this.loadConcepts();
}
}
};
sitools.component.projects.ProjectsPropPanel.superclass.initComponent.call(this);
},
/**
* Load the conceptsGrid store with the right url
*/
loadConcepts : function () {
var url = loadUrl.get('APP_URL') + loadUrl.get('APP_COLLECTIONS_URL') + "/" + this.collectionId + "/concepts/" + this.dictionaryId;
this.gridConcepts.getStore().proxy.setUrl(url);
this.gridConcepts.getStore().load();
},
/**
* Erase all form components
*/
eraseComponents : function () {
this.formComponentsStore.removeAll();
},
/**
* Erase all form Properties
*/
eraseProperties : function () {
this.gridProperties.getStore().removeAll();
},
/**
* Check the validity of form
* and call onSaveProject method
* @return {Boolean}
*/
onValidate : function () {
var f = this.findByType('form')[0].getForm();
if (!f.isValid()) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.invalidForm'));
return false;
}
var putObject = {};
Ext.iterate(f.getValues(), function (key, value) {
var rec, index;
if (key == 'comboCollections') {
index = this.comboCollections.getStore().find("name", this.comboCollections.getValue());
rec = this.comboCollections.getStore().getAt(index);
var collection = {
name : rec.data.name,
id : rec.data.id,
description : rec.data.description
};
putObject.collection = collection;
} else if (key == "comboDictionnaires") {
index = this.comboDictionnaires.getStore().find("name", this.comboDictionnaires.getValue());
rec = this.comboDictionnaires.getStore().getAt(index);
var dictionary = {
name : rec.data.name,
id : rec.data.id,
description : rec.data.description
};
putObject.dictionary = dictionary;
}
else {
putObject[key] = value;
}
}, this);
var width = this.formSize.width;
var height = this.formSize.height;
putObject.width = width;
putObject.height = height;
var storeProperties = this.gridProperties.getStore();
if (storeProperties.getCount() > 0) {
putObject.properties = [];
}
storeProperties.each(function (rec) {
putObject.properties.push(rec.data);
});
var store = this.formComponentsStore;
if (store.getCount() > 0) {
putObject.parameters = [];
}
store.each(function (component) {
putObject.parameters.push({
type : component.data.type,
code : component.data.code,
label : component.data.label,
values : component.data.values,
width : component.data.width,
height : component.data.height,
xpos : component.data.xpos,
ypos : component.data.ypos,
id : component.data.id,
css : component.data.css,
jsAdminObject : component.data.jsAdminObject,
jsUserObject : component.data.jsUserObject,
defaultValues : component.data.defaultValues,
valueSelection : component.data.valueSelection,
autoComplete : component.data.autoComplete,
parentParam : component.data.parentParam,
dimensionId : component.data.dimensionId,
unit : component.data.unit,
extraParams : component.data.extraParams
});
});
var method = (this.action == 'modify') ? "PUT" : "POST";
var url = (this.action == 'modify') ? this.urlMultiDs + "/" + this.formId : this.urlMultiDs;
Ext.Ajax.request({
url : url,
method : method,
scope : this,
jsonData : putObject,
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (data.success === false) {
Ext.Msg.alert(i18n.get('label.warning'), i18n
.get(data.message));
} else {
this.close();
this.store.reload();
}
// Ext.Msg.alert(i18n.get('label.information'),
// i18n.get('msg.uservalidate'));
},
failure : alertFailure
});
},
/**
* Loads the form as defined if in modification mode.
*/
onRender : function () {
sitools.admin.multiDs.MultiDsPropPanel.superclass.onRender.apply(this, arguments);
if (this.formId) {
// Si l'objet est en modification, on charge l'objet en question
if (this.action == 'modify') {
Ext.Ajax.request({
url : this.urlMultiDs + "/" + this.formId,
method : 'GET',
scope : this,
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (!Json.success) {
this.close();
Ext.Msg.alert(i18n.get('label.warning'), Json.message);
return;
}
var f = this.findByType('form')[0].getForm();
var data = Json.formProject;
if (!Ext.isEmpty(data.width)) {
this.formSize.width = data.width;
}
if (!Ext.isEmpty(data.height)) {
this.formSize.height = data.height;
}
var rec = {};
rec.id = data.id;
rec.name = data.name;
rec.description = data.description;
rec.css = data.css;
rec.nbDatasetsMax = data.nbDatasetsMax;
rec.urlServicePropertiesSearch = data.urlServicePropertiesSearch;
rec.urlServiceDatasetSearch = data.urlServiceDatasetSearch;
rec.idServiceDatasetSearch = data.idServiceDatasetSearch;
rec.idServicePropertiesSearch = data.idServicePropertiesSearch;
var record = new Ext.data.Record(rec);
f.loadRecord(record);
this.comboCollections.setValue(data.collection.name);
this.comboDictionnaires.setValue(data.dictionary.name);
this.collectionId = data.collection.id;
this.dictionaryId = data.dictionary.id;
if (data.properties) {
var properties = data.properties;
var storeProperties = this.gridProperties.getStore();
Ext.each(properties, function (prop) {
storeProperties.add(new Ext.data.Record(prop));
});
}
if (data.parameters) {
var parameters = data.parameters;
var storeTablesComponents = this.formComponentsStore;
var i;
for (i = 0; i < parameters.length; i++) {
storeTablesComponents.add(new Ext.data.Record({
type : parameters[i].type,
code : parameters[i].code,
label : parameters[i].label,
values : parameters[i].values,
width : parameters[i].width,
height : parameters[i].height,
xpos : parameters[i].xpos,
ypos : parameters[i].ypos,
id : parameters[i].id,
css : parameters[i].css,
jsAdminObject : parameters[i].jsAdminObject,
jsUserObject : parameters[i].jsUserObject,
defaultValues : parameters[i].defaultValues,
valueSelection : parameters[i].valueSelection,
autoComplete : parameters[i].autoComplete,
parentParam : parameters[i].parentParam,
dimensionId : parameters[i].dimensionId,
unit : parameters[i].unit,
extraParams : parameters[i].extraParams
}));
}
}
this.doLayout();
},
failure : function (ret) {
var data = Ext.decode(ret.responseText);
Ext.Msg.alert(i18n.get('label.warning'), data.errorMessage);
}
});
}
}
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, showResponse, alertFailure*/
/*
* @include "../../../client-admin/js/datasets/selectPredicat.js"
*/
Ext.ns("sitools.admin.datasets");
/**
* @class sitools.admin.datasets.PredicatsPanel
* @extends Ext.grid.EditorGridPanel
* @param {string} gridId
* @param {Ext.data.Store} storeSelectFields
* @param {string} type
*/
sitools.admin.datasets.PredicatsPanel = function (config) {
Ext.apply(this, config);
var myData = [];
// create the data store
var storeCritere = new Ext.data.JsonStore({
fields : [ {
name : 'parentheseOuvrante',
type : 'text'
}, {
name : 'leftAttribute'
}, {
name : 'operateur',
type : 'text'
}, {
name : 'rightAttribute'
}, {
name : 'parentheseFermante'
}, {
name : 'opLogique'
} ]
});
Ext.util.Format.comboRenderer = function (combo) {
return function (value) {
var record = combo.findRecord(combo.valueField, value);
return record ? record.get(combo.displayField) : combo.valueNotFoundText;
};
};
// Ici on cr�e les combos pour utilisation dans l'Editor Grid
var comboOl = new Ext.form.ComboBox({
id : "comboOlEditor",
typeAhead : false,
triggerAction : 'all',
lazyRender : true,
mode : 'local',
store : new Ext.data.ArrayStore({
id : 0,
fields : [ 'myId', 'displayText' ],
data : [ [ '', '' ], [ 'and', 'and' ], [ 'or', 'or' ] ]
}),
valueField : 'myId',
displayField : 'displayText'
});
var comboOp = new Ext.form.ComboBox({
id : "comboOpEditor",
typeAhead : false,
triggerAction : 'all',
lazyRender : true,
mode : 'local',
store : new Ext.data.ArrayStore({
id : 0,
fields : [ 'myId', 'displayText' ],
data : [ [ 'GT', '>' ], [ 'GTE', '>=' ], [ 'LT', '<' ], [ 'LTE', '<=' ], [ 'LIKE', 'like' ],
[ 'EQ', '=' ], [ 'NE', '!=' ] ]
}),
valueField : 'myId',
displayField : 'displayText'
});
Ext.util.Format.attributeRenderer = function () {
return function (value) {
if (value) {
var tableName = "";
if (value.tableAlias) {
tableName = value.tableAlias + ".";
}
else {
if (value.tableName) {
tableName = value.tableName + ".";
}
}
return tableName + value.dataIndex;
}
};
};
var rightAttribute;
if (this.type == "join") {
rightAttribute = {
id : 'rightAttribute',
name : "rightAttribute",
header : i18n.get('label.rightAttribute'),
width : 100,
sortable : false,
dataIndex : 'rightAttribute',
// editor : comboChamp1,
renderer : Ext.util.Format.attributeRenderer()
};
} else {
rightAttribute = {
header : i18n.get('label.rightAttribute'),
width : 200,
sortable : false,
dataIndex : 'rightAttribute',
editor : new Ext.form.TextField({
allowBlank : false
})
};
}
var tbar = {
xtype : 'sitools.widget.GridSorterToolbar',
defaults : {
scope : this
},
items: []
};
sitools.admin.datasets.PredicatsPanel.superclass.constructor.call(this, Ext.apply({
layout : 'fit',
flex : 0.45,
id : this.gridId,
resizable : true,
autoHeight : false,
viewConfig : {
forceFit : true
},
autoScroll : true,
store : storeCritere,
enableColumnHide : false,
enableColumnMove : false,
enableColumnSort : false,
clicksToEdit : 2,
tbar : tbar,
// Definition des colonnes avec monType
columns : [ {
header : "",
width : 50,
sortable : false,
dataIndex : 'opLogique',
editor : comboOl,
renderer : Ext.util.Format.comboRenderer(comboOl)
}, {
header : "",
width : 20,
sortable : false,
dataIndex : 'parentheseOuvrante'
}, {
id : 'leftAttribute',
name : "leftAttribute",
header : i18n.get('header.leftAttribute'),
width : 100,
sortable : false,
dataIndex : 'leftAttribute',
// editor : comboChamp1,
renderer : Ext.util.Format.attributeRenderer()
}, {
header : i18n.get('header.operateur'),
width : 70,
sortable : false,
dataIndex : 'operateur',
editor : comboOp,
renderer : Ext.util.Format.comboRenderer(comboOp)
}, rightAttribute, {
header : "",
width : 20,
sortable : false,
dataIndex : 'parentheseFermante',
monType : 'parenthese'
} ],
// ajout du plugin pour d�finir la drop Zone
stripeRows : true,
sm : new Ext.grid.RowSelectionModel(),
// menu contextuel
listeners : {
// levee du traitement pour les champs de la grille
// scope : this,
celldblclick : function (grid, rowIndex, columnIndex, e) {
var record;
var selectPredicatWin;
var fieldName;
var data;
if (columnIndex == 1) {
record = grid.getStore().getAt(rowIndex); // Get the Record
fieldName = grid.getColumnModel().getDataIndex(columnIndex); // Get field name
data = record.get(fieldName);
record.set(fieldName, data + '(');
}
if (columnIndex == 2) {
record = grid.getStore().getAt(rowIndex); // Get the
// Record
selectPredicatWin = new sitools.admin.datasets.selectPredicat({
field : 'leftAttribute',
recordPredicat : record,
storePredicat : this.storeSelectFields,
viewPredicat : grid.getView()
});
selectPredicatWin.show(ID.BOX.DATASETS);
}
if (columnIndex == 4 && this.type == 'join') {
record = grid.getStore().getAt(rowIndex); // Get the
// Record
selectPredicatWin = new sitools.admin.datasets.selectPredicat({
field : 'rightAttribute',
recordPredicat : record,
storePredicat : this.storeSelectFields,
viewPredicat : grid.getView()
});
selectPredicatWin.show(ID.BOX.DATASETS);
}
if (columnIndex == 5) {
record = grid.getStore().getAt(rowIndex); // Get the
// Record
fieldName = grid.getColumnModel().getDataIndex(columnIndex); // Get
// field
// name
data = record.get(fieldName);
record.set(fieldName, data + ')');
}
grid.getView().refresh();
},
contextmenu : function (e) {
if (!Ext.isEmpty(Ext.getCmp('gridCritereCtxMenu'))) {
Ext.getCmp('gridCritereCtxMenu').destroy();
}
this.contextMenu = new Ext.menu.Menu({
id : 'gridCritereCtxMenu',
items : [
{
text : i18n.get('label.ajoutCondition'),
icon : loadUrl.get('APP_URL') + "/res/images/icons/add_condition.png",
listeners : {
scope : this,
click : function () {
var rowIndex = 0;
var selModel = this.getSelectionModel();
if (selModel.hasSelection()) {
rowIndex = this.getStore().indexOf(selModel.getSelected()) + 1;
}
var RecordType = this.getStore().recordType;
var p = new RecordType({
parentheseOuvrante : ' ',
parentheseFermante : ' '
});
this.stopEditing();
storeCritere.insert(rowIndex, p);
}
}
},
{
text : i18n.get('label.suppressionCondition'),
icon : loadUrl.get('APP_URL') + "/res/images/icons/delete_condition.png",
listeners : {
scope : this,
click : function () {
if (!this.getSelectionModel().hasSelection()) {
Ext.Msg.alert(i18n.get('warning.noselection'), i18n
.get('warning.noselection'));
return;
}
var s = this.getSelectionModel().getSelections();
for (var i = 0, r; r = s[i]; i++) {
storeCritere.remove(r);
}
}
}
},
{
text : i18n.get('label.suppressionParenthese'),
icon : loadUrl.get('APP_URL') + "/res/images/icons/delete_parenthesis.png",
listeners : {
scope : this,
click : function () {
var selModel = this.getSelectionModel();
if (!selModel.hasSelection()) {
Ext.Msg.alert(i18n.get('warning.noselection'), i18n
.get('warning.noselection'));
return;
}
var selectedRecords = selModel.getSelections();
var i = 0;
selModel.each(function (selected) {
selected.data.parentheseOuvrante = " ";
selected.data.parentheseFermante = " ";
});
this.getView().refresh();
}
}
}
]
});
var xy = e.getXY();
this.contextMenu.showAt(xy);
e.stopEvent();
}
}
}));
};
Ext.extend(sitools.admin.datasets.PredicatsPanel, Ext.grid.EditorGridPanel, {});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp*/
Ext.namespace('sitools.admin.datasets');
/**
* @cfg string field the attribute of the record to edit
* @cfg Ext.data.Record recordPredicat the record to edit
* @cfg Ext.data.Store storePredicat the store that contains the record
* @cfg Ext.grid.GridView the view of the parent grid
* @class sitools.admin.datasets.selectPredicat
* @extends Ext.Window
*/
sitools.admin.datasets.selectPredicat = Ext.extend(Ext.Window, {
//sitools.component.datasets.selectPredicat = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
pageSize : 10,
id : 'selectPredicatId',
initComponent : function () {
this.title = i18n.get('label.selectPredicat');
this.cmSelectPredicat = new Ext.grid.ColumnModel({
columns : [ {
id : 'tableAlias',
header : i18n.get('headers.tableAlias'),
sortable : true,
dataIndex : 'tableAlias'
}, {
id : 'tableName',
header : i18n.get('headers.tableName'),
sortable : true,
dataIndex : 'tableName'
}, {
id : 'name',
header : i18n.get('headers.alias'),
sortable : true,
dataIndex : 'columnAlias'
} ]
});
this.smSelectPredicat = new Ext.grid.RowSelectionModel({
singleSelect : true
});
this.gridSelectPredicat = new Ext.grid.GridPanel({
title : i18n.get('title.gridSelectPredicat'),
height : 380,
autoScroll : true,
store : this.storePredicat,
cm : this.cmSelectPredicat,
sm : this.smSelectPredicat
});
this.items = [ {
xtype : 'panel',
layout : 'fit',
items : [ this.gridSelectPredicat ],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ]
} ];
sitools.admin.datasets.selectPredicat.superclass.initComponent.call(this);
},
onValidate : function () {
var rec = this.gridSelectPredicat.getSelectionModel().getSelected();
var nomAffiche = rec.data.tableAlias ? rec.data.tableAlias : rec.data.tableName;
nomAffiche = nomAffiche + "." + rec.data.dataIndex;
this.recordPredicat.data.nomAffiche = nomAffiche;
if (this.field == 'leftAttribute') {
this.recordPredicat.data.leftAttribute = {
tableName : rec.data.tableName,
tableAlias : rec.data.tableAlias,
dataIndex : rec.data.dataIndex,
schema : rec.data.schemaName,
columnAlias : rec.data.columnAlias,
specificColumnType : rec.data.specificColumnType,
sqlColumnType : rec.data.sqlColumnType,
javaSqlColumnType : rec.data.javaSqlColumnType
};
} else {
this.recordPredicat.data.rightAttribute = {
tableName : rec.data.tableName,
tableAlias : rec.data.tableAlias,
dataIndex : rec.data.dataIndex,
schema : rec.data.schemaName,
columnAlias : rec.data.columnAlias,
specificColumnType : rec.data.specificColumnType,
sqlColumnType : rec.data.sqlColumnType,
javaSqlColumnType : rec.data.javaSqlColumnType
};
}
// this.recordPredicat.data.dataIndex = rec.data.dataIndex;
// this.recordPredicat.data.schema = rec.data.schema;
this.viewPredicat.refresh();
this.close();
}
});
Ext.reg('s-datasetspredicat', sitools.admin.datasets.selectPredicat);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, predicatOperators*/
Ext.namespace('sitools.admin.datasets');
/**
* Window used to define a joinCondition between two tables of a dataset.
* @cfg {Ext.tree.TreeNode} node (required) the parent node where to add join Condition.
storeColumnDataset
* @cfg {String} mode (required) should be "edit" or "create"
* @cfg {Ext.data.Store} storeColumnDataset (required) the store of dataset columns
* @class sitools.admin.datasets.joinConditionWin
* @extends Ext.Window
*/
//sitools.component.datasets.joinConditionWin = Ext.extend(Ext.Window, {
sitools.admin.datasets.joinConditionWin = Ext.extend(Ext.Window, {
// url + mode + storeref
width : 650,
modal : true,
closable : false,
pageSize : 10,
resizable : false,
id : 'joinConditionWin',
initComponent : function () {
this.storeColumnDataset.filterBy(function (rec) {
return rec.data.specificColumnType == "DATABASE";
});
var defaultPredicat;
try {
defaultPredicat = this.node.attributes.predicat || {};
}
catch (err) {
defaultPredicat = {};
}
this.logicOperator = new Ext.form.ComboBox({
typeAhead : false,
triggerAction : 'all',
lazyRender : true,
mode : 'local',
width : 50,
store : new Ext.data.ArrayStore({
id : 0,
fields : [ 'myId', 'displayText' ],
data : [ [ '', '' ], [ 'on', 'on' ], [ 'and', 'and' ], [ 'or', 'or' ] ]
}),
valueField : 'myId',
displayField : 'displayText',
value : Ext.isEmpty(defaultPredicat.logicOperator) ? "on" : defaultPredicat.logicOperator
});
var myTpl = new Ext.XTemplate('<tpl for=".">',
'<div class="x-combo-list-item">',
'<tpl if="this.isNull(tableAlias)">',
'<tpl if="this.isNotNull(tableName)">{[values.tableName.toUpperCase()]}.</tpl>',
'</tpl>',
'<tpl if="this.isNotNull(tableAlias)">[values.tableAlias.toUpperCase()].</tpl>',
'{columnAlias}</div>',
'</tpl>',
{
compiled : true,
isNull : function (value) {
return Ext.isEmpty(value);
},
isNotNull : function (value) {
return !Ext.isEmpty(value);
},
isDatabase : function (value) {
return value == "DATABASE";
}
});
this.leftAttribute = new Ext.form.ComboBox({
fieldLabel : "left",
typeAhead : false,
triggerAction : 'all',
forceSelection : true,
id : "leftAttributeField",
flex : 2,
lazyRender : true,
mode : 'local',
displayField : 'columnAlias',
valueField : 'columnAlias',
store : this.storeColumnDataset,
value : defaultPredicat.leftAttribute ? defaultPredicat.leftAttribute.columnAlias : null,
tpl : myTpl
});
this.compareOperator = new Ext.form.ComboBox({
typeAhead : false,
forceSelection : true,
triggerAction : 'all',
lazyRender : true,
mode : 'local',
width : 50,
store : new Ext.data.ArrayStore({
id : 1,
fields : [ 'myId', 'displayText' ],
data : predicatOperators.operators
}),
valueField : 'myId',
displayField : 'displayText',
hiddenName : 'compareOperator',
value : Ext.isEmpty(defaultPredicat.compareOperator) ? "EQ" : defaultPredicat.compareOperator
});
this.rightAttribute = new Ext.form.ComboBox({
fieldLabel : "left",
typeAhead : false,
triggerAction : 'all',
forceSelection : true,
lazyRender : true,
id : "rightAttributeField",
mode : 'local',
flex : 2,
displayField : 'columnAlias',
valueField : 'columnAlias',
store : this.storeColumnDataset,
value : defaultPredicat.rightAttribute ? defaultPredicat.rightAttribute.columnAlias : null,
tpl : myTpl
});
var form = new Ext.form.FormPanel({
labelWidth : 100, // label settings here cascade unless overridden
bodyStyle : 'padding:5px 5px 0',
width : 640,
items : [{
xtype : 'compositefield',
fieldLabel : i18n.get('label.joinCondition'),
defaults : {
flex : 1
},
items : [this.logicOperator, this.leftAttribute, this.compareOperator, this.rightAttribute]
}]
});
this.title = i18n.get('label.joinCondition');
this.items = [form];
this.buttons = [ {
text : i18n.get('label.ok'),
handler : this._onOK,
scope : this
}, {
text : i18n.get('label.cancel'),
handler : this._onCancel,
scope : this
} ]
;
// this.relayEvents(this.store, ['destroy', 'save', 'update']);
sitools.admin.datasets.joinConditionWin.superclass.initComponent.call(this);
},
/**
* When click on ok button.
* Depending on mode, edit or create a node
*/
_onOK : function () {
this.storeColumnDataset.clearFilter();
var rightColumn = this.rightAttribute.getStore().getAt(this.rightAttribute.getStore().findExact("columnAlias", this.rightAttribute.getValue())).data;
var leftColumn = this.leftAttribute.getStore().getAt(this.leftAttribute.getStore().findExact("columnAlias", this.leftAttribute.getValue())).data;
// var compareOperatorStore = this.compareOperator.getStore();
// var compareOperatorIndex = compareOperatorStore.find("displayText", this.compareOperator.getValue());
// var compareOperator = compareOperatorStore.getAt(compareOperatorIndex).get("myId");
//
var predicat = {
logicOperator : this.logicOperator.getValue(),
rightAttribute : {
id : rightColumn.id,
dataIndex : rightColumn.dataIndex,
header : rightColumn.header,
toolTip : rightColumn.toolTip,
width : rightColumn.width,
sortable : rightColumn.sortable,
visible : rightColumn.visible,
filter : rightColumn.filter,
sqlColumnType : rightColumn.sqlColumnType,
columnOrder : rightColumn.columnOrder,
primaryKey : rightColumn.primaryKey,
schema : rightColumn.schemaName,
tableAlias : rightColumn.tableAlias,
tableName : rightColumn.tableName,
specificColumnType : rightColumn.specificColumnType,
columnAlias : rightColumn.columnAlias,
datasetDetailUrl : rightColumn.datasetDetailUrl,
columnAliasDetail : rightColumn.columnAliasDetail,
notion : rightColumn.notion,
javaSqlColumnType : rightColumn.javaSqlColumnType,
columnClass : rightColumn.columnClass,
image : rightColumn.image,
dimensionId : rightColumn.dimensionId,
unit : rightColumn.unit
},
leftAttribute : {
id : leftColumn.id,
dataIndex : leftColumn.dataIndex,
header : leftColumn.header,
toolTip : leftColumn.toolTip,
width : leftColumn.width,
sortable : leftColumn.sortable,
visible : leftColumn.visible,
filter : leftColumn.filter,
sqlColumnType : leftColumn.sqlColumnType,
columnOrder : leftColumn.columnOrder,
primaryKey : leftColumn.primaryKey,
schema : leftColumn.schemaName,
tableAlias : leftColumn.tableAlias,
tableName : leftColumn.tableName,
specificColumnType : leftColumn.specificColumnType,
columnAlias : leftColumn.columnAlias,
datasetDetailUrl : leftColumn.datasetDetailUrl,
columnAliasDetail : leftColumn.columnAliasDetail,
notion : leftColumn.notion,
javaSqlColumnType : leftColumn.javaSqlColumnType,
columnClass : leftColumn.columnClass,
image : leftColumn.image,
dimensionId : leftColumn.dimensionId,
unit : leftColumn.unit
},
compareOperator : this.compareOperator.getValue()
};
if (this.mode == 'edit') {
this.node.attributes.predicat = predicat;
this.node.setText(this.getNodeText(predicat));
} else {
var newNode = {
leaf : true,
predicat : predicat,
text : this.getNodeText(predicat),
type : "join"
};
if (!this.node.isExpanded()) {
this.node.expand();
}
if (this.node.childNodes.length !== 0) {
this.node.insertBefore(newNode, this.node.findChild("leaf", false));
}
else {
this.node.appendChild(newNode);
}
}
this.destroy();
},
/**
* return a string from a predicat.
* @param {} predicat
* @return {String}
*/
getNodeText : function (predicat) {
predicat.leftAttribute = predicat.leftAttribute || {};
predicat.rightAttribute = predicat.rightAttribute || {};
var compareOperator = predicatOperators.getOperatorValueForClient(predicat.compareOperator);
return String.format("{0} {1} {2} {3}",
predicat.logicOperator,
this.getDisplayName(predicat.leftAttribute),
compareOperator,
this.getDisplayName(predicat.rightAttribute));
},
/**
* Close this window
*/
_onCancel : function () {
this.storeColumnDataset.clearFilter();
this.destroy();
},
/**
* get the string to display from a column
* @param {} column
* @return {String}
*/
getDisplayName : function (column) {
if (column.specificColumnType == "DATABASE") {
return String.format("{0}.{1}",
Ext.isEmpty(column.tableAlias) ? column.tableName: column.tableAlias,
column.columnAlias);
}
else {
return column.columnAlias;
}
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp*/
Ext.namespace('sitools.admin.datasets');
/**
* the Window used to edit or add a new table on the sql Join Wizard Panel.
* @cfg {String} datasetId (required) the datasetId
* @cfg {Ext.grid.GridPanel} datasetSelectTables (required) the Panel that displays all Tables
* @cfg {String} action (required) Should be 'create' or 'modify'
* @class sitools.admin.datasets.joinTableWin
* @extends Ext.Window
*/
sitools.admin.datasets.joinTableWin = Ext.extend(Ext.Window, {
//sitools.component.datasets.joinTableWin = Ext.extend(Ext.Window, {
width : 350,
height : 300,
modal : true,
closable : false,
layout : "fit",
initComponent : function () {
this.title = i18n.get('label.tables');
var cm = new Ext.grid.ColumnModel({
columns : [ {
id : 'name',
header : i18n.get('headers.name'),
width : 160,
sortable : true,
dataIndex : 'name'
}, {
id : 'alias',
header : i18n.get('headers.tableAlias'),
width : 80,
sortable : true,
dataIndex : 'alias',
editor : new Ext.form.TextField({
disabled : this.action == 'view' ? true : false
})
} ]
});
/**
* The store that contains the tables of a Dataset.
* @type Ext.grid.ColumnModel
*/
var store = new sitools.widget.JsonStore({
id : 'storeTablesDataset',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'alias',
type : 'string'
}, {
name : 'schemaName',
type : 'string'
}
]
});
store.add(this.datasetSelectTables.getStoreSelectedTables().data.items);
this.grid = new Ext.grid.GridPanel({
layout : 'fit',
store : store,
cm : cm,
sm : new Ext.grid.RowSelectionModel({
singleSelect : true
}),
autoScroll : true,
enableDragDrop : false,
stripeRows : true,
title : 'Tables Dataset'
});
this.items = [this.grid];
this.buttons = [{
text : i18n.get('label.ok'),
handler : this._onOK,
scope : this
}, {
text : i18n.get('label.cancel'),
handler : this._onCancel,
scope : this
} ];
// this.relayEvents(this.store, ['destroy', 'save', 'update']);
sitools.admin.datasets.joinTableWin.superclass.initComponent.call(this);
},
/**
* Called when button Ok is pressed
* Depending on action mode, it could edit the root node, edit a node, or add new node.
*/
_onOK : function () {
var table = this.grid.getSelectionModel().getSelected();
if(!Ext.isEmpty(table)){
if (this.mode == 'edit') {
this.node.setText(this.typeJointure + " " + table.data.name);
this.node.attributes.table = {
alias : table.data.alias,
name : table.data.name,
schema : table.data.schemaName
};
this.destroy();
} else if (this.mode == "edit-root") {
this.node.setText(table.data.name);
this.node.attributes.table = {
alias : table.data.alias,
name : table.data.name,
schema : table.data.schemaName
};
this.destroy();
} else {
var newNode = {
text : this.typeJointure + " " + table.data.name,
typeJointure : this.typeJointure,
type : "table",
table : {
name : table.data.name,
alias : table.data.alias,
schema : table.data.schemaName
},
leaf : false,
children : []
};
if (!this.node.isExpanded()) {
this.node.expand();
}
this.node.appendChild(newNode);
this.destroy();
}
} else {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
return;
}
},
/**
* Close this window.
*/
_onCancel : function () {
this.destroy();
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
/*
* @include "joinConditionWin.js"
* @include "joinTableWin.js"
*
*/
Ext.namespace('sitools.admin.datasets');
/**
* The panel that displays the sql join wizard
* @cfg {String} datasetId (required) the dataset Id
* @cfg {Ext.grid.GridPanel} datasetSelectTables (required) The Panel that shows dataset tables
* @cfg {string} action (required)
* @cfg {Ext.data.Store} storeColumnDataset (required) The store of the dataset columns
* @class sitools.admin.datasets.joinPanel
* @extends Ext.Panel
*/
//sitools.component.datasets.joinPanel = Ext.extend(Ext.Panel, {
sitools.admin.datasets.joinPanel = Ext.extend(Ext.Panel, {
border : false,
urlJDBC : loadUrl.get('APP_URL') + "/",
autoScroll: true,
layout : 'fit',
height : 180,
initComponent : function () {
this.title = "Join Configuration";
this.tree = new sitools.component.datasets.joinCrudTreePanel(this);
this.items = [this.tree];
this.addEvents('contextmenu');
sitools.admin.datasets.joinPanel.superclass.initComponent.call(this);
},
loadGraph : function () {
this.removeAll();
this.tree = new sitools.component.datasets.joinCrudTreePanel({
datasetId : this.datasetId
});
this.tree.getRootNode().expand(true);
this.add(this.tree);
this.doLayout();
},
_onSave : function () {
var projectId = this.comboProjects.getValue();
if (!Ext.isEmpty(projectId)) {
var root = this.tree.getRootNode();
var tree = [];
var childs = root.childNodes;
var i;
for (i = 0; i < childs.length; i++) {
this.getAllNodes(childs[i], tree);
}
var idGraph = this.tree.getIdGraph();
var jsonReturn = {
nodeList : tree,
id : idGraph
};
// var tree = this.getAllNodes(root,array);
var method = (!Ext.isEmpty(idGraph)) ? "PUT" : "POST";
Ext.Ajax.request({
url : this.urlProjects + "/" + projectId + "/graph",
method : method,
scope : this,
jsonData : jsonReturn,
success : function (ret) {
// check for the success of the request
var data = Ext.decode(ret.responseText);
if (!data.success) {
Ext.Msg.alert(i18n.get('label.warning'), data.message);
return false;
} else {
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('label.graphSaved'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
this.loadGraph(projectId);
}
},
failure : alertFailure
});
} else {
Ext.Msg.alert(i18n.get("label.warning"), i18n.get("warning.noselection"));
}
},
getAllNodes : function (root, parent) {
var node = {};
if (Ext.isEmpty(root)) {
return;
} else if (root.isLeaf()) {
node = {
text : root.text,
predicat : root.predicat,
leaf : root.leaf
};
parent.push(node);
} else {
node = {
text : root.text,
children : [],
type : root.attributes.type,
typeJointure : root.attributes.typeJointure,
table : root.attributes.table,
leaf : false
};
parent.push(node);
// we call recursively getAllNodes to get all childNodes
var childs = root.childNodes;
var i;
for (i = 0; i < childs.length; i++) {
this.getAllNodes(childs[i], node.children);
}
}
},
buildDefault : function () {
// if (this.action == "create") {
this.tree.buildDefault();
// }
},
deleteJoinPanelItems : function () {
this.tree.deleteJoinPanelItems();
}
});
sitools.component.datasets.joinCrudTreePanel = Ext.extend(Ext.tree.TreePanel, {
loader : null,
projectId : null,
layout : "fit",
autoScroll : true,
initComponent : function () {
var root;
root = new Ext.tree.TreeNode({
text : this.name,
leaf : false,
expanded : true
});
Ext.apply(this, {
rootVisible : true,
layout : 'fit',
enableDD: false,
root : root,
contextMenuRoot : new Ext.menu.Menu({
items : [{
id : 'create-node',
text : i18n.get("Add Table"),
icon : loadUrl.get('APP_URL') + '/res/images/icons/add_folder.png',
menu : {
items : [ {
id : 'INNER_JOIN',
action : "addTable",
text : i18n.get("label.innerJoin")
}, {
id : 'CROSS_JOIN',
action : "addTable",
text : i18n.get("label.crossJoin")
}, {
id : 'LEFT_JOIN',
action : "addTable",
text : i18n.get("label.leftJoin")
}, {
id : 'LEFT_OUTER_JOIN',
action : "addTable",
text : i18n.get("label.leftOuterJoin")
}, {
id : 'RIGHT_JOIN',
action : "addTable",
text : i18n.get("label.rightJoin")
}, {
id : 'RIGHT_OUTER_JOIN',
action : "addTable",
text : i18n.get("label.rightOuterJoin")
}],
listeners : {
scope : this,
itemclick : this._cxtMenuHandler
}
}
}, {
id : 'edit-root',
text : i18n.get("label.modify"),
icon : loadUrl.get('APP_URL') + '/res/images/icons/toolbar_edit.png'
}],
listeners : {
scope : this,
itemclick : this._cxtMenuHandler
}
}),
contextMenuNode : new Ext.menu.Menu({
items : [ {
id : 'add-joinCondition',
text : i18n.get("Add Join Condition"),
icon : loadUrl.get('APP_URL') + '/res/images/icons/add_datasets.png'
}, {
id : 'edit-node',
text : i18n.get("label.modify"),
icon : loadUrl.get('APP_URL') + '/res/images/icons/toolbar_edit.png'
}, {
id : 'edit-jointure',
text : i18n.get("editJointure"),
icon : loadUrl.get('APP_URL') + '/res/images/icons/toolbar_edit.png',
menu : {
items : [ {
id : 'INNER_JOIN',
action : "editJointure",
text : i18n.get("label.innerJoin")
}, {
id : 'CROSS_JOIN',
action : "editJointure",
text : i18n.get("label.crossJoin")
}, {
id : 'LEFT_JOIN',
action : "editJointure",
text : i18n.get("label.leftJoin")
}, {
id : 'LEFT_OUTER_JOIN',
action : "editJointure",
text : i18n.get("label.leftOuterJoin")
}, {
id : 'RIGHT_JOIN',
action : "editJointure",
text : i18n.get("label.rightJoin")
}, {
id : 'RIGHT_OUTER_JOIN',
action : "editJointure",
text : i18n.get("label.rightOuterJoin")
}],
listeners : {
scope : this,
itemclick : this._cxtMenuHandler
}
}
}, {
id : 'delete-node',
text : i18n.get("label.delete"),
icon : loadUrl.get('APP_URL') + '/res/images/icons/toolbar_delete.png'
} ],
listeners : {
scope : this,
itemclick : this._cxtMenuHandler
}
}),
contextMenuLeaf : new Ext.menu.Menu({
items : [ {
id : 'edit-node',
text : i18n.get("label.modify"),
icon : loadUrl.get('APP_URL') + '/res/images/icons/toolbar_edit.png'
}, {
id : 'delete-node',
text : i18n.get("label.delete"),
icon : loadUrl.get('APP_URL') + '/res/images/icons/toolbar_delete.png'
} ],
listeners : {
scope : this,
itemclick : this._cxtMenuHandler
}
}),
listeners : {
scope : this,
contextmenu : function (node, e) {
e.stopEvent();
// Register the context node with the menu so that a Menu
// Item's handler function can access
// it via its parentMenu property.
node.select();
var c;
if (node == this.getRootNode()) {
c = node.getOwnerTree().contextMenuRoot;
c.contextNode = this.getRootNode();
}
else {
if (node.isLeaf()) {
c = node.getOwnerTree().contextMenuLeaf;
} else {
c = node.getOwnerTree().contextMenuNode;
}
c.contextNode = node;
}
c.showAt(e.getXY());
},
beforenodedrop : function (dropEvent) {
if (dropEvent.target.attributes.type == dropEvent.data.node.attributes.type) {
return false;
}
return true;
}
}
});
sitools.component.datasets.joinCrudTreePanel.superclass.initComponent.call(this);
},
onRender : function () {
sitools.component.datasets.joinCrudTreePanel.superclass.onRender.apply(this, arguments);
},
_cxtMenuHandler : function (item) {
var node, up;
switch (item.id) {
case 'delete-node':
var tot = Ext.Msg.show({
title : i18n.get('label.warning'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('label.graphs.node.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
var n = item.parentMenu.contextNode;
if (n.parentNode) {
n.remove();
}
}
}
});
break;
case 'add-joinCondition':
node = item.parentMenu.contextNode;
// this.doLayout();
up = new sitools.admin.datasets.joinConditionWin({
node : node,
mode : 'create',
storeColumnDataset : this.storeColumnDataset
});
up.show(this);
break;
case 'INNER_JOIN':
case 'LEFT_JOIN':
case 'CROSS_JOIN':
case 'LEFT_OUTER_JOIN':
case 'RIGHT_JOIN':
case 'RIGHT_OUTER_JOIN':
if (item.action == "addTable") {
node = item.parentMenu.parentMenu.contextNode;
// this.doLayout();
up = new sitools.admin.datasets.joinTableWin({
node : node,
mode : 'create',
datasetSelectTables : this.datasetSelectTables,
typeJointure : item.id
});
up.show();
}
if (item.action == "editJointure") {
node = item.parentMenu.parentMenu.contextNode;
node.attributes.typeJointure = item.id;
node.setText(this.getNodeText(node.attributes));
}
break;
case 'edit-node':
node = item.parentMenu.contextNode;
if (node.isLeaf()) {
up = new sitools.admin.datasets.joinConditionWin({
node : node,
mode : 'edit',
storeColumnDataset : this.storeColumnDataset
});
} else {
up = new sitools.admin.datasets.joinTableWin({
node : node,
mode : 'edit',
datasetSelectTables : this.datasetSelectTables,
typeJointure : node.attributes.typeJointure
});
}
up.show();
break;
case 'edit-root' :
node = item.parentMenu.contextNode;
up = new sitools.admin.datasets.joinTableWin({
node : node,
mode : 'edit-root',
datasetSelectTables : this.datasetSelectTables
});
up.show();
break;
}
},
getIdGraph : function () {
return this.loader.getIdGraph();
},
buildDefault : function () {
//load the first table as main table and the others as children
var storeTables = this.scope.panelSelectTables.getStoreSelectedTables();
if (storeTables.getCount() !== 0 && Ext.isEmpty(this.getRootNode().attributes.table)) {
var rec = storeTables.getAt(0);
var rootNode = this.getRootNode();
Ext.apply(rootNode, {
text : rec.data.name,
leaf : false,
children : [],
type : "table"
});
rootNode.setText(rec.data.name);
Ext.apply(rootNode.attributes, {
table : {
name : rec.data.name,
alias : rec.data.alias,
schema : rec.data.schemaName
}
});
var i = 0;
storeTables.each(function (rec) {
if (i !== 0) {
rootNode.appendChild({
typeJointure : "INNER_JOIN",
text : "INNER_JOIN " + rec.data.name,
table : {
name : rec.data.name,
alias : rec.data.alias,
schema : rec.data.schemaName
},
leaf : false,
type : "table",
children : []
});
}
i++;
}, this);
}
},
loadTree : function (dataset) {
var rootNode = this.getRootNode();
var mainTable = dataset.structure.mainTable;
if (!Ext.isEmpty(mainTable)) {
Ext.apply(rootNode, {
text : mainTable.name,
leaf : false,
expanded : true
});
Ext.apply(rootNode.attributes, {
table : mainTable
});
}
Ext.each(dataset.structure.nodeList, function (node) {
this.loadNode(node, rootNode);
}, this);
},
loadNode : function (node, parent) {
var treeNode;
if (node.leaf) {
Ext.apply(node, {
text : this.getNodeText(node),
nodeType : "sync",
expanded : true
});
treeNode = new Ext.tree.TreeNode(node);
node.children = [];
parent.appendChild(treeNode);
}
else {
Ext.apply(node, {
text : this.getNodeText(node),
nodeType : "sync",
iconCls : "x-tree-node-folder",
expanded : true
});
var children = node.children;
parent.appendChild(node);
var nodeInserted = parent.lastChild;
Ext.each(children, function (nodeChildren) {
this.loadNode(nodeChildren, nodeInserted);
}, this);
}
},
getNodeText : function (node) {
if (node.leaf) {
var predicat = node.predicat || {};
predicat.leftAttribute = predicat.leftAttribute || {};
predicat.rightAttribute = predicat.rightAttribute || {};
var compareOperator = predicatOperators.getOperatorValueForClient(predicat.compareOperator);
return String.format("{0} {1} {2} {3}",
predicat.logicOperator,
this.getDisplayName(predicat.leftAttribute),
compareOperator,
this.getDisplayName(predicat.rightAttribute));
}
else {
var table = ! Ext.isEmpty(node.table) ? node.table : node.attributes.table;
if (!Ext.isEmpty(table)) {
return node.typeJointure + " " + table.name;
}
else {
return "wrong node";
}
}
},
getDisplayName : function (column) {
if (column.specificColumnType == "DATABASE") {
return String.format("{0}.{1}",
Ext.isEmpty(column.tableAlias) ? column.tableName: column.tableAlias,
column.columnAlias);
}
else {
return column.columnAlias;
}
},
deleteJoinPanelItems : function () {
var root = new Ext.tree.TreeNode({
text : this.name,
leaf : false,
expanded : true
});
this.setRootNode(root);
}
});
Ext.apply(Ext.tree.TreePanel.nodeTypes, {
"sync" : Ext.tree.TreeNode
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser, loadUrl, ColumnRendererEnum*/
/*
* @include "datasetUrlWin.js"
* @include "unitWin.js"
*/
Ext.namespace('sitools.admin.datasets');
/**
* @class sitools.admin.datasets.gridFieldSetup
* @cfg {String} urlDictionary (required) the Url to request directories
* @cfg {String} action (required) modify, view, or create
* @cfg {String} urlDataset (required) the url to get the dataset definition
*/
sitools.admin.datasets.gridFieldSetup = function (config) {
this.scope = config.scope;
var storeColumn = new Ext.data.JsonStore({
id : 'storeColumnSelect',
root : 'ColumnModel',
idProperty : 'columnAlias',
remoteSort : false,
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'dataIndex',
type : 'string'
}, {
name : 'schemaName',
mapping : 'schema',
type : 'string'
}, {
name : 'tableAlias',
type : 'string'
}, {
name : 'tableName',
type : 'string'
}, {
name : 'header',
type : 'string'
}, {
name : 'toolTip',
type : 'string'
}, {
name : 'width',
type : 'int'
}, {
name : 'sortable',
type : 'boolean'
}, {
name : 'visible',
type : 'boolean'
}, {
name : 'filter',
type : 'boolean'
}, {
name : 'columnOrder',
type : 'int'
},
// {name : 'urlColumn', type : 'boolean'},
// {name : 'previewColumn', type : 'boolean'},
{
name : 'columnRendererCategory',
type : 'String'
}, {
name : 'columnRenderer',
type : 'object'
}, {
name : 'primaryKey',
type : 'boolean'
}, {
name : 'sqlColumnType',
type : 'string'
}, {
name : 'columnAlias',
type : 'string'
}, {
name : 'specificColumnType',
type : 'string'
}, {
name : 'javaSqlColumnType',
type : 'int'
}, {
name : 'columnClass',
type : 'int'
}, {
name : 'dimensionId',
type : 'string'
}, {
name : 'unit'
}, {
name : 'format',
type : 'string'
}],
listeners : {
add : function (store, records) {
Ext.each(records, function (record) {
if (record.data.specificColumnType == 'DATABASE') {
if (Ext.isEmpty(record.data.header)) {
record.data.header = record.data.dataIndex;
}
if (Ext.isEmpty(record.data.columnAlias)) {
record.data.columnAlias = record.data.dataIndex.toLowerCase();
}
if (sql2ext.get(record.get("sqlColumnType")) == "dateAsString" && Ext.isEmpty(record.data.format)) {
record.data.format = SITOOLS_DEFAULT_IHM_DATE_FORMAT;
}
}
});
}
}
});
var visible = new Ext.grid.CheckColumn({
header : i18n.get('headers.visible'),
dataIndex : 'visible',
width : 55,
helpUrl : loadUrl.get('APP_URL') + "/client-admin/res/help/" + LOCALE + "/dataset/visible.html"
});
var sortable = new Ext.grid.CheckColumn({
header : i18n.get('headers.sortable'),
dataIndex : 'sortable',
width : 55,
helpUrl : loadUrl.get('APP_URL') + "/client-admin/res/help/" + LOCALE + "/dataset/sortable.html"
});
var primaryKey = new Ext.grid.CheckColumn({
header : i18n.get('headers.primaryKey'),
dataIndex : 'primaryKey',
width : 55,
helpUrl : loadUrl.get('APP_URL') + "/client-admin/res/help/" + LOCALE + "/dataset/primaryKey.html"
});
var comboStoreOrderBy = new Ext.data.ArrayStore({
fields : [ 'value', 'display' ],
data : [ [ '', '' ], [ 'ASC', 'ASC' ], [ 'DESC', 'DESC' ] ]
});
var comboOrderBy = new Ext.form.ComboBox({
header : i18n.get('headers.orderBy'),
store : comboStoreOrderBy,
mode : 'local',
typeAhead : true,
triggerAction : 'all',
forceSelection : true,
selectOnFocus : true,
dataIndex : 'orderBy',
lazyRender : true,
listClass : 'x-combo-list-small',
valueField : 'value',
displayField : 'display',
tpl : '<tpl for="."><div class="x-combo-list-item comboItem">{display}</div></tpl>',
width : 55,
helpUrl : loadUrl.get('APP_URL') + "/client-admin/res/help/" + LOCALE + "/dataset/orderBy.html"
});
var comboStore = new Ext.data.ArrayStore({
fields : [ 'value', 'display', 'tooltip' ],
data : [ [ '', '' ],
[ 'Image', 'Image', i18n.get("label.image.tooltip") ],
[ 'URL', 'URL', i18n.get("label.url.tooltip") ],
[ 'DataSetLink', 'DataSetLink', i18n.get("label.datasetlink.tooltip") ],
[ 'Other', 'Other', i18n.get("label.other.tooltip") ]]
});
var comboColumnRenderer = new Ext.form.ComboBox({
disabled : this.action == 'view' ? true : false,
store : comboStore,
mode : 'local',
typeAhead : true,
triggerAction : 'all',
forceSelection : true,
selectOnFocus : true,
data : 'light',
lazyRender : true,
listClass : 'x-combo-list-small',
valueField : 'value',
displayField : 'display',
tpl : '<tpl for="."><div ext:qtip="{tooltip}" class="x-combo-list-item comboItem">{display}</div></tpl>',
listeners : {
scope : this,
select : function (combo, record) {
var columnRendererType = combo.getValue();
//get the last value, which is either the last value selected or the first value.
var lastValue = (Ext.isEmpty(combo.lastValue)) ? combo.startValue : combo.lastValue;
var selectedRecord = this.getSelectionModel().getSelected();
if (!Ext.isEmpty(columnRendererType)) {
var colWindow = new sitools.admin.datasets.columnRendererWin({
selectedRecord : selectedRecord,
gridView : this.getView(),
columnRendererType : columnRendererType,
datasetColumnStore : storeColumn,
lastColumnRendererType : lastValue
});
colWindow.show();
}
}
}
});
var filterColumn = new Ext.grid.CheckColumn({
header : i18n.get('headers.filter'),
dataIndex : 'filter',
width : 55,
helpUrl : loadUrl.get('APP_URL') + "/client-admin/res/help/" + LOCALE + "/dataset/filters.html"
});
var cmColumn = new Ext.ux.grid.LockingColumnModel({
columns : [ {
header : i18n.get('headers.sqlDefinition'),
dataIndex : 'dataIndex',
width : 120,
locked : true,
helpUrl : loadUrl.get('APP_URL') + "/client-admin/res/help/" + LOCALE + "/dataset/sqlDefinition.html"
}, {
header : i18n.get('headers.tableName'),
dataIndex : 'tableName',
width : 80
}, {
header : i18n.get('headers.tableAlias'),
dataIndex : 'tableAlias',
width : 80
}, {
header : i18n.get('headers.columnAlias'),
dataIndex : 'columnAlias',
width : 80,
editor : new Ext.form.TextField({
disabled : this.action == 'view' ? true : false,
allowBlank : false,
maxLength : 50,
validator : function (v) {
var re = new RegExp("^.*[!\"#$%&\'/()*+,:;<=>?@\\`{}|~]+.*$");
if (!re.test(v)) {
return !re.test(v);
}
else {
return i18n.get('label.invalidColumnAlias');
}
}
}),
helpUrl : loadUrl.get('APP_URL') + "/client-admin/res/help/" + LOCALE + "/dataset/columnAlias.html"
}, {
header : i18n.get('headers.format'),
dataIndex : 'format',
width : 80,
editor : new Ext.form.TextField({
disabled : this.action == 'view' ? true : false,
allowBlank : true,
maxLength : 50,
value : "Y-m-d\\TH:i:s.u"
}),
helpUrl : loadUrl.get('APP_URL') + "/client-admin/res/help/" + LOCALE + "/dataset/format.html"
}, {
header : i18n.get('headers.unit'),
dataIndex : 'unit',
width : 80,
helpUrl : loadUrl.get('APP_URL') + "client-admin/res/help/" + LOCALE + "/dataset/unit.html",
renderer : function (value) {
if (Ext.isEmpty(value)) {
return "";
}
else {
return value.label;
}
}
}, {
header : i18n.get('headers.header'),
dataIndex : 'header',
width : 80,
editor : new Ext.form.TextField({
disabled : this.action == 'view' ? true : false,
allowBlank : false,
maxLength : 50
}),
helpUrl : loadUrl.get('APP_URL') + "client-admin/res/help/" + LOCALE + "/dataset/headers.html"
}, {
header : i18n.get('headers.width'),
dataIndex : 'width',
width : 40,
editor : new Ext.form.TextField({
disabled : this.action == 'view' ? true : false,
allowBlank : false,
maxLength : 50
})
}, sortable, visible, filterColumn, {
header : i18n.get('headers.orderBy'),
dataIndex : 'orderBy',
width : 55,
editor : comboOrderBy,
helpUrl : loadUrl.get('APP_URL') + "/client-admin/res/help/" + LOCALE + "/dataset/orderBy.html"
}, primaryKey, {
header : i18n.get('headers.previewUrl'),
dataIndex : 'columnRendererCategory',
width : 120,
editor : comboColumnRenderer,
helpUrl : loadUrl.get('APP_URL') + "/client-admin/res/help/" + LOCALE + "/dataset/previewUrl.html"
},
{
header : i18n.get('headers.tooltip'),
dataIndex : 'toolTip',
width : 80,
helpUrl : loadUrl.get('APP_URL') + "client-admin/res/help/" + LOCALE + "/dataset/tooltip.html",
editor : new Ext.form.TextField({
disabled : this.action == 'view' ? true : false,
maxLength : 50
})
}],
defaults : {
sortable : false,
width : 80
}
});
var smColumn = new Ext.grid.RowSelectionModel({
singleSelect : true
});
var menuActions = new Ext.menu.Menu({
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.assignUnit'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/refresh_clue.png',
handler : this.onAssignUnit
}, {
text : i18n.get('label.deleteUnit'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/refresh_clue.png',
handler : this.onDeleteUnit
}]
});
var tbar = {
xtype : 'sitools.widget.GridSorterToolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreateColumn
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this.onModifyColumn
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDeleteColumn
}, {
text : i18n.get('label.action'),
menu : menuActions
}]
};
sitools.admin.datasets.gridFieldSetup.superclass.constructor.call(this, Ext.apply({
id : 'gridColumnSelect',
title : i18n.get('title.gridColumn'),
layout : 'fit',
store : storeColumn,
tbar : tbar,
cm : cmColumn,
sm : smColumn,
urlDictionary : config.urlDictionary,
urlDimension : config.urlDimension,
urlDataset : config.urlDataset,
action : config.action,
plugins : [ sortable, visible, filterColumn, primaryKey ],
listeners : {
scope : this,
beforeedit : function (e) {
//Créer l'éditeur en fonction du type
if (e.column == 4) {
var grid = e.grid;
var rec = e.record;
if (sql2ext.get(rec.get("sqlColumnType")) != "dateAsString") {
return false;
}
}
return true;
},
activate : function (p) {
this.datasourceUtils = this.scope.datasourceUtils;
}
}
}));
};
Ext.extend(sitools.admin.datasets.gridFieldSetup, Ext.ux.grid.LockingEditorGridPanel, {
/**
* Open a sitools.admin.datasets.unitWin to assign a unit to the selected column.
* @method
*/
onAssignUnit : function () {
var grid = this;
var rec = grid.getSelectionModel().getSelected();
if (!rec) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
return;
}
var unitWin = new sitools.admin.datasets.unitWin({
recordColumn : rec,
viewColumn : grid.getView(),
urlDimension : this.urlDimension
});
unitWin.show(ID.BOX.DATASETS);
},
/**
* Open a {@link sitools.admin.datasets.columnsPropPanel sitools.admin.datasets.columnsPropPanel} to create a new Column
* @method
*/
onCreateColumn : function () {
var winPropColumn = new sitools.admin.datasets.columnsPropPanel({
action : 'create',
store : this.getStore(),
datasourceUtils : this.datasourceUtils
});
winPropColumn.show();
// this.getStore().add(new Ext.data.Record());
},
/**
* Open a {@link sitools.admin.datasets.columnsPropPanel sitools.admin.datasets.columnsPropPanel} to edit a Column
* @method
*/
onModifyColumn : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
return;
}
if (rec.get('specificColumnType') === "DATABASE" && this.datasourceUtils.isJdbc) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.cannotUpdateDatabaseColumn'));
return;
}
var winPropColumn = new sitools.admin.datasets.columnsPropPanel({
action : 'modify',
store : this.getStore(),
recordColumn : rec,
datasourceUtils : this.datasourceUtils
});
winPropColumn.show();
// this.getStore().add(new Ext.data.Record());
},
/**
* delete a column.
* @method
*/
onDeleteColumn : function () {
var grid = this;
var rec = grid.getSelectionModel().getSelected();
if (!rec) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
return;
}
grid.getStore().remove(rec);
grid.getView().refresh();
},
/**
* Remove a unit from a selected Column.
* @method
*/
onDeleteUnit : function () {
var grid = this;
var rec = grid.getSelectionModel().getSelected();
if (!rec) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
return;
}
// clear the notion
rec.set("unit", null);
rec.set("dimensionId", null);
},
/**
* Remove all records and adds records to the store with a columnModel.
* @param Ext.grid.ColumnModel columnModel
*/
getData : function (columnModel) {
var i;
this.getStore().removeAll();
for (i = 0; i < columnModel.length; i++) {
var name;
var columnRenderer = columnModel[i].columnRenderer;
var columnRendererCategory = "";
if (!Ext.isEmpty(columnRenderer)) {
columnRendererCategory = ColumnRendererEnum
.getColumnRendererCategoryFromBehavior(columnRenderer.behavior);
}
this.getStore().add(new Ext.data.Record({
id : columnModel[i].id,
dataIndex : columnModel[i].dataIndex,
header : columnModel[i].header,
toolTip : columnModel[i].toolTip,
width : columnModel[i].width,
sortable : columnModel[i].sortable,
orderBy : columnModel[i].orderBy,
visible : columnModel[i].visible,
filter : columnModel[i].filter,
sqlColumnType : columnModel[i].sqlColumnType,
columnOrder : columnModel[i].columnOrder,
primaryKey : columnModel[i].primaryKey,
columnRenderer : columnRenderer,
columnRendererCategory : columnRendererCategory,
schemaName : columnModel[i].schema,
tableName : columnModel[i].tableName,
tableAlias : columnModel[i].tableAlias,
specificColumnType : columnModel[i].specificColumnType,
columnAlias : columnModel[i].columnAlias,
javaSqlColumnType : columnModel[i].javaSqlColumnType,
columnClass : columnModel[i].columnClass,
format : columnModel[i].format,
dimensionId : columnModel[i].dimensionId,
unit : columnModel[i].unit
}));
}
},
/**
* validate the fourth tab of the window.
* @return an object with attributes :
* - success : boolean
* - message : a message if success == false
*/
gridFieldSetupValidation : function () {
var result = {
success : true,
message : ""
};
var store = this.getStore();
var nbPrimaryKey = 0;
var nbOrderBy = 0;
if (store.getCount() > 0) {
var i;
for (i = 0; i < store.getCount(); i++) {
var rec = store.getAt(i).data;
if (rec.columnAlias.toLowerCase() != rec.columnAlias) {
result = {
success : false,
message : String.format(i18n.get('label.columnAliasMaj'), rec.columnAlias)
};
return result;
}
if (!Ext.isEmpty(rec.primaryKey) && rec.primaryKey) {
nbPrimaryKey++;
if (Ext.isEmpty(rec.filter) || !rec.filter) {
result = {
success : false,
message : String.format(i18n.get('label.columnPKNoFilter'), rec.columnAlias)
};
return result;
}
}
if (!Ext.isEmpty(rec.orderBy) && rec.orderBy) {
nbOrderBy++;
}
}
if (nbPrimaryKey != 1) {
result = {
success : false,
message : nbPrimaryKey + i18n.get('label.wrongPrimaryKey')
};
return result;
}
if (nbOrderBy < 1) {
result = {
success : false,
message : i18n.get('label.noOrderBy')
};
return result;
}
}
var chekForDoublon = this.checkForDoublon();
if (chekForDoublon.found) {
result = {
success : false,
message : i18n.get('label.doublonFound') + chekForDoublon.doublon
};
}
return result;
},
/**
* Check the uniqueness of the ColumnAlias
* @returns {} an object with attributes
* - found : Boolean true if at least one duplicate
* - doublon : the name of the first duplicate columnAlias found
*
*/
checkForDoublon : function () {
var doublon = null, i;
var store = this.getStore();
var found = false;
for (i = 0; i < store.getCount() && !found; i++) {
var rec1 = store.getAt(i).data;
found = false;
for (var j = 0; j < store.getCount() && doublon === null && !found; j++) {
var rec2 = store.getAt(j).data;
if (rec1.columnAlias == rec2.columnAlias && rec1 != rec2) {
found = true;
doublon = rec1.columnAlias;
}
}
}
return {
found : found,
doublon : doublon
};
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser*/
Ext.namespace('sitools.admin.datasets');
/**
* Define the window of the dataset Configuration
* @cfg {String} url the Url to save the data (only when modify)
* @cfg {String} action (required) "active", "modify" "view"
* @cfg {Ext.data.Store} store (required) : the datasets store
* @cfg {String} urlDatasources The url of the JDBC datasources
* @cfg {String} urlDatasourcesMongoDB The url of the MongoDB datasources
* @class sitools.admin.datasets.datasetForm
* @extends Ext.Panel
*/
sitools.admin.datasets.datasetCriteria = Ext.extend(Ext.Panel, {
initComponent : function () {
/**
* The panel that displays the join conditions.
* @type sitools.admin.datasets.joinPanel
*/
this.wizardJoinCondition = new sitools.admin.datasets.joinPanel({
datasetId : this.scope.datasetId,
datasetSelectTables : this.scope.panelSelectTables,
action : this.scope.action,
storeColumnDataset : this.scope.gridFields.getStore(),
scope : this.scope
});
/**
* the panel that displays the where clause
* @type sitools.admin.datasets.PredicatsPanel
*/
this.wizardWhereClause = new sitools.admin.datasets.PredicatsPanel({
gridId : 'whereClauseId',
title : i18n.get('label.wizardWhereClause'),
storeSelectFields : this.scope.gridFields.getStore(),
type : 'where'
});
/**
* the panel that displays the SQL specific query.
* @type Ext.Panel
*/
this.SqlWhereClause = new Ext.Panel({
height : 350,
items : [ {
xtype : 'form',
items : [ {
xtype : 'textarea',
id : "sqlQuery",
autoScroll : true,
height : 350,
anchor : '100%',
name : "sqlQuery",
validator : function (value) {
if (value.toLowerCase().match("where")) {
if (value.toLowerCase().match("from")) {
return true;
}
else {
return false;
}
}
else {
return false;
}
},
invalidText : i18n.get('label.invalidSQl')
} ]
} ]
});
var selecteur = new Ext.form.FormPanel({
height : 30,
flex : 0.1,
id : "selecteurId",
items : [ {
xtype : 'radiogroup',
id : 'radioQueryType',
fieldLabel : i18n.get('label.queryType'),
width : 300,
height : 30,
items : [ {
disabled : this.action === 'view' ? true : false,
boxLabel : i18n.get('label.assistant'),
name : 'queryType',
inputValue : "W",
checked : true
}, {
disabled : this.action === 'view' ? true : false,
boxLabel : i18n.get('label.sql'),
name : 'queryType',
inputValue : "S"
} ],
listeners : {
scope : this,
change : function (radioGroup, radio) {
if (!Ext.isEmpty(radio)) {
this.scope.queryType = radio.inputValue;
}
if (this.scope.queryType === 'W') {
this.whereClausePanel.remove(this.SqlWhereClause, false);
this.SqlWhereClause.hide();
this.whereClausePanel.add(this.wizardJoinCondition);
this.whereClausePanel.add(this.wizardWhereClause);
this.wizardJoinCondition.show();
this.wizardWhereClause.show();
this.whereClausePanel.doLayout();
} else {
this.whereClausePanel.remove(this.wizardJoinCondition, false);
this.whereClausePanel.remove(this.wizardWhereClause, false);
this.wizardJoinCondition.hide();
this.wizardWhereClause.hide();
this.whereClausePanel.add(this.SqlWhereClause);
this.SqlWhereClause.show();
this.whereClausePanel.doLayout();
}
}
}
} ]
});
/**
* A single container with a flex layout.
* @type Ext.Panel
*/
this.whereClausePanel = new Ext.Panel({
flex : 0.9,
layout : "vbox",
layoutConfig : {
align : "stretch"
}
});
Ext.apply(this, {
items : [selecteur, this.whereClausePanel],
listeners : {
"activate" : function () {
if (this.scope.action === 'view') {
this.getEl().mask();
}
if (!Ext.isEmpty(this.scope.datasourceUtils)) {
this.wizardJoinCondition.setVisible(this.scope.datasourceUtils.isJdbc);
selecteur.setVisible(this.scope.datasourceUtils.isJdbc);
if (this.scope.queryType === 'W') {
this.scope.datasourceUtils.loadColumnsBDD();
this.wizardJoinCondition.buildDefault();
this.whereClausePanel.add([this.wizardJoinCondition, this.wizardWhereClause]);
this.whereClausePanel.doLayout();
} else {
this.whereClausePanel.add(this.SqlWhereClause);
this.whereClausePanel.doLayout();
}
}
},
scope : this
}
});
sitools.admin.datasets.datasetCriteria.superclass.initComponent.call(this);
},
/**
* Returns the wizard panel
* @returns {sitools.admin.datasets.PredicatsPanel}
*/
getWizardWhereClause : function () {
return this.wizardWhereClause;
},
/**
* Returns the join Panel
* @returns
*/
getWizardJoinCondition : function () {
return this.wizardJoinCondition;
},
getQueryType : function () {
return this.scope.queryType;
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, showResponse, alertFailure, extColModelToSrv*/
/**
* Redefine the method beforeColMenuShow to request the store when adding a column
* @class Ext.ux.sitoolsGridView
* @extends Ext.grid.GridView
*/
Ext.ux.sitoolsGridView = Ext.extend(Ext.grid.GridView, {
// surcharge de la m�thode pour que l'ajout d'une colonne relance une
// interrogation du store
// avec comme parametre le nouveau columnModel
beforeColMenuShow : function () {
var cm = this.cm, colCount = cm.getColumnCount();
this.colMenu.removeAll();
for (var i = 0; i < colCount; i++) {
if (cm.config[i].hideable !== false) {
this.colMenu.add(new Ext.menu.CheckItem({
itemId : 'col-' + cm.getColumnId(i),
text : cm.getColumnHeader(i),
checked : !cm.isHidden(i),
hideOnClick : false,
disabled : cm.config[i].hideable === false,
listeners : {
scope : this,
checkchange : function (ci, checked) {
if (checked) {
var colModel = extColModelToSrv(this.cm);
this.grid.getStore().load({
params : {
colModel : Ext.util.JSON.encode(colModel)
}
});
}
}
}
}));
}
}
},
doRender : function(columns, records, store, startRow, colCount, stripe) {
var templates = this.templates,
cellTemplate = templates.cell,
rowTemplate = templates.row,
last = colCount - 1;
var tstyle = 'width:' + this.getTotalWidth() + ';';
var rowBuffer = [],
colBuffer = [],
rowParams = {tstyle: tstyle},
meta = {},
column,
record;
for (var j = 0, len = records.length; j < len; j++) {
record = records[j];
colBuffer = [];
var rowIndex = j + startRow;
for (var i = 0; i < colCount; i++) {
column = columns[i];
meta.id = column.id;
meta.css = i === 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : '');
meta.attr = meta.cellAttr = '';
meta.style = column.style;
meta.value = column.renderer.call(column.scope, record.data[column.name], meta, record, rowIndex, i, store);
if (Ext.isEmpty(meta.value)) {
meta.value = ' ';
}
if (this.markDirty && record.dirty && Ext.isDefined(record.modified[column.name])) {
meta.css += ' x-grid3-dirty-cell';
}
colBuffer[colBuffer.length] = cellTemplate.apply(meta);
}
var alt = [];
if (stripe && ((rowIndex + 1) % 2 === 0)) {
alt[0] = 'x-grid3-row-alt';
}
if (record.dirty) {
alt[1] = ' x-grid3-dirty-row';
}
rowParams.cols = colCount;
if (this.getRowClass) {
alt[2] = this.getRowClass(record, rowIndex, rowParams, store);
}
rowParams.alt = alt.join(' ');
rowParams.cells = colBuffer.join('');
rowBuffer[rowBuffer.length] = rowTemplate.apply(rowParams);
}
//Ajout du cas où il n'y a pas de records.
if (records.length == 0) {
var alt = [];
rowParams.cols = colCount;
rowParams.cells = " ";
rowBuffer[0] = rowTemplate.apply(rowParams);
}
return rowBuffer.join('');
},
renderRows : function(startRow, endRow){
var g = this.grid, cm = g.colModel, ds = g.store, stripe = g.stripeRows;
var colCount = cm.getColumnCount();
//if(ds.getCount() < 1){
// return '';
//}
var cs = this.getColumnData();
startRow = startRow || 0;
endRow = !Ext.isDefined(endRow) ? ds.getCount()-1 : endRow;
var rs = ds.getRange(startRow, endRow);
return this.doRender(cs, rs, ds, startRow, colCount, stripe);
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/**
* Ext.ux.grid.livegrid.GridPanel Copyright (c) 2007-2008,
* http://www.siteartwork.de
*
* Ext.ux.grid.livegrid.GridPanel is licensed under the terms of the GNU Open
* Source GPL 3.0 license.
*
* Commercial use is prohibited. Visit <http://www.siteartwork.de/livegrid> if
* you need to obtain a commercial license.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/gpl.html>.
*
*/
/*global Ext, sitools, i18n, extColModelToSrv*/
Ext.namespace('Ext.ux.grid.livegrid');
/**
* @class Ext.ux.grid.livegrid.GridPanel
* @extends Ext.grid.GridPanel
* @constructor
* @param {Object}
* config
*
* @author Thorsten Suckow-Homberg <ts@siteartwork.de>
*/
Ext.ux.grid.livegrid.GridPanel = Ext.extend(Ext.grid.GridPanel, {
initComponent : function () {
if (this.cls) {
this.cls += ' ext-ux-livegrid';
} else {
this.cls = 'ext-ux-livegrid';
}
Ext.ux.grid.livegrid.GridPanel.superclass.initComponent.call(this);
},
/**
* Overriden to make sure the attached store loads only when the grid has
* been fully rendered if, and only if the store's "autoLoad" property is
* set to true.
*
*/
onRender : function (ct, position) {
Ext.ux.grid.livegrid.GridPanel.superclass.onRender.call(this, ct, position);
var ds = this.getStore();
if (ds._autoLoad === true) {
delete ds._autoLoad;
ds.load();
}
},
/**
* Overriden since the original implementation checks for getCount() of the
* store, not getTotalCount().
*
*/
walkCells : function (row, col, step, fn, scope) {
var ds = this.store;
var _oF = ds.getCount;
ds.getCount = ds.getTotalCount;
var ret = Ext.ux.grid.livegrid.GridPanel.superclass.walkCells.call(this, row, col, step, fn, scope);
ds.getCount = _oF;
return ret;
}
});
/**
* Ext.ux.grid.livegrid.GridView Copyright (c) 2007-2008,
* http://www.siteartwork.de
*
* Ext.ux.grid.livegrid.GridView is licensed under the terms of the GNU Open
* Source GPL 3.0 license.
*
* Commercial use is prohibited. Visit <http://www.siteartwork.de/livegrid> if
* you need to obtain a commercial license.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/gpl.html>.
*
*/
Ext.namespace('Ext.ux.grid.livegrid');
/**
* @class Ext.ux.grid.livegrid.GridView
* @extends Ext.grid.GridView
* @constructor
* @param {Object}
* config
*
* @author Thorsten Suckow-Homberg <ts@siteartwork.de>
*/
Ext.ux.grid.livegrid.GridView = function (config) {
this.addEvents({
/**
* @event beforebuffer Fires when the store is about to buffer new data.
* @param {Ext.ux.BufferedGridView}
* this
* @param {Ext.data.Store}
* store The store
* @param {Number}
* rowIndex
* @param {Number}
* visibleRows
* @param {Number}
* totalCount
* @param {Number}
* options The options with which the buffer request was
* called
*/
'beforebuffer' : true,
/**
* @event buffer Fires when the store is finsihed buffering new data.
* @param {Ext.ux.BufferedGridView}
* this
* @param {Ext.data.Store}
* store The store
* @param {Number}
* rowIndex
* @param {Number}
* visibleRows
* @param {Number}
* totalCount
* @param {Object}
* options
*/
'buffer' : true,
/**
* @event bufferfailure Fires when buffering failed.
* @param {Ext.ux.BufferedGridView}
* this
* @param {Ext.data.Store}
* store The store
* @param {Object}
* options The options the buffer-request was initiated with
*/
'bufferfailure' : true,
/**
* @event cursormove Fires when the the user scrolls through the data.
* @param {Ext.ux.BufferedGridView}
* this
* @param {Number}
* rowIndex The index of the first visible row in the grid
* absolute to it's position in the model.
* @param {Number}
* visibleRows The number of rows visible in the grid.
* @param {Number}
* totalCount
*/
'cursormove' : true,
/**
* @event abortrequest Fires when the store is about to reload (this
* does NOT mean buffering). If you are using a custom proxy in
* your store, you should listen to this event and abort any
* ongoing server request established in your custom proxy.
* @param {Ext.data.Store}
* store
* @param {Object}
* options
*/
'abortrequest' : true
});
/**
* @cfg {Number} scrollDelay The number of microseconds a call to the
* onLiveScroll-lisener should be delayed when the scroll event fires
*/
/**
* @cfg {Number} bufferSize The number of records that will at least always
* be available in the store for rendering. This value will be send to
* the server as the <tt>limit</tt> parameter and should not change
* during the lifetime of a grid component. Note: In a paging grid,
* this number would indicate the page size. The value should be set
* high enough to make a userfirendly scrolling possible and should be
* greater than the sum of {nearLimit} and {visibleRows}. Usually, a
* value in between 150 and 200 is good enough. A lesser value will
* more often make the store re-request new data, while a larger number
* will make loading times higher.
*/
/**
* @cfg {Number} nearLimit This value represents a near value that is
* responsible for deciding if a request for new data is needed. The
* lesser the number, the more often new data will be requested. The
* number should be set to a value that lies in between 1/4 to 1/2 of
* the {bufferSize}.
*/
/**
* @cfg {Number} horizontalScrollOffset The height of a horizontal aligned
* scrollbar. The scrollbar is shown if the total width of all visible
* columns exceeds the width of the grid component. On Windows XP (IE7,
* FF2), this value defaults to 17.
*/
this.horizontalScrollOffset = 17;
/**
* @type {Boolean} _checkEmptyBody Since Ext 3.0, would initially
* added to the mainBody as the first child if there are no rows to
* render. This element has to be removed when the first rows get
* added so the UI does not crash. This property is here to determine
* if this element was already removed, so we don't have to query
* innerHTML all the time.
*/
this._checkEmptyBody = true;
Ext.apply(this, config);
this.templates = {};
/**
* The master template adds an addiiotnal scrollbar to make cursoring in the
* data possible.
*/
this.templates.master = new Ext.Template(
'<div class="x-grid3" hidefocus="true"><div class="liveScroller"><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div></div>',
'<div class="x-grid3-viewport"">',
'<div class="x-grid3-header"><div class="x-grid3-header-inner"><div class="x-grid3-header-offset" style="{ostyle}">{header}</div></div><div class="x-clear"></div></div>',
'<div class="x-grid3-scroller" style="overflow-y:hidden !important;"><div class="x-grid3-body" style="{bstyle}">{body}</div><a href="#" class="x-grid3-focus" tabIndex="-1"></a></div>',
"</div>", '<div class="x-grid3-resize-marker"> </div>',
'<div class="x-grid3-resize-proxy"> </div>', "</div>");
// shorthands for often used parent classes
this._gridViewSuperclass = Ext.ux.grid.livegrid.GridView.superclass;
this._gridViewSuperclass.constructor.call(this);
};
Ext.extend(Ext.ux.grid.livegrid.GridView, Ext.ux.sitoolsGridView, {
// {{{
// --------------------------properties-------------------------------------
/**
* Stores the height of the header. Needed for recalculating scroller inset
* height.
*
* @param {Number}
*/
hdHeight : 0,
/**
* Indicates wether the last row in the grid is clipped and thus not fully
* display. 1 if clipped, otherwise 0.
*
* @param {Number}
*/
rowClipped : 0,
/**
* This is the actual y-scroller that does control sending request to the
* server based upon the position of the scrolling cursor.
*
* @param {Ext.Element}
*/
liveScroller : null,
/**
* This array holds the divs that represent the amount of data in a given
* repository. The sum of heights of this divs gets computed via the total
* amount of records multiplied with the fixed(!) row height. There is a
* total of 3 divs responsible for the scroll amount to prevent issues with
* the max number of pxiels a div alone can grow in height.
*
* @param {native
* HTMLObject}
*/
liveScrollerInsets : null,
/**
* The <b>fixed</b> row height for <b>every</b> row in the grid. The value
* is computed once the store has been loaded for the first time and used
* for various calculations during the lifetime of the grid component, such
* as the height of the scroller and the number of visible rows.
*
* @param {Number}
*/
rowHeight : -1,
/**
* Stores the number of visible rows that have to be rendered.
*
* @param {Number}
*/
visibleRows : 1,
/**
* Stores the last offset relative to a previously scroll action. This is
* needed for deciding wether the user scrolls up or down.
*
* @param {Number}
*/
lastIndex : -1,
/**
* Stores the last visible row at position "0" in the table view before a
* new scroll event was created and fired.
*
* @param {Number}
*/
lastRowIndex : 0,
/**
* Stores the value of the <tt>liveScroller</tt>'s <tt>scrollTop</tt>
* DOM property.
*
* @param {Number}
*/
lastScrollPos : 0,
/**
* The current index of the row in the model that is displayed as the first
* visible row in the view.
*
* @param {Number}
*/
rowIndex : 0,
/**
* Set to <tt>true</tt> if the store is busy with loading new data.
*
* @param {Boolean}
*/
isBuffering : false,
/**
* If a request for new data was made and the user scrolls to a new position
* that lays not within the requested range of the new data, the queue will
* hold the latest requested position. If the buffering succeeds and the
* value of requestQueue is not within the range of the current buffer, data
* may be re-requested.
*
* @param {Number}
*/
requestQueue : -1,
/**
* An {@Ext.LoadMask} config that will be shown when a request to data was
* made and there are no rows in the buffer left to render.
*
* @param {Object}
*/
loadMask : false,
/**
* A shortcut to indicate whether the loadMask is currently being displayed.
*
* @type {Boolean}
* @private
*/
loadMaskDisplayed : false,
/**
* Set to <tt>true</tt> if a request for new data has been made while
* there are still rows in the buffer that can be rendered before the
* request finishes.
*
* @param {Boolean}
*/
isPrebuffering : false,
/**
* The dom node for which the node mask will be rendered.
*
* @type {Ext.Element}
* @private
*/
_loadMaskAnchor : null,
/**
* used to know if you have to display Warning if too many rows
*/
_displayWarningTooManyRows : true,
// }}}
// {{{ --------------------------public API
// methods-----------------------------
/**
* Resets the view to display the first row in the data model. This will
* change the scrollTop property of the scroller and may trigger a request
* to buffer new data, if the row index "0" is not within the buffer range
* and forceReload is set to true.
*
* @param {Boolean}
* forceReload <tt>true</tt> to reload the buffers contents,
* othwerwise <tt>false</tt>
*
* @return {Boolean} Whether the store loads after reset(true); returns
* false if any of the attached beforeload listeners cancels the
* load-event
*/
reset : function (forceReload) {
if (forceReload === false) {
this.ds.modified = [];
// this.grid.selModel.clearSelections(true);
this.rowIndex = 0;
this.lastScrollPos = 0;
this.lastRowIndex = 0;
this.lastIndex = 0;
this.adjustVisibleRows();
this.adjustScrollerPos(-this.liveScroller.dom.scrollTop, true);
this.showLoadMask(false);
var _ofn = this.processRows;
this.processRows = Ext.emptyFn;
this.refresh(true);
this.processRows = _ofn;
this.processRows(0);
this.fireEvent('cursormove', this, 0, Math.min(this.ds.totalLength, this.visibleRows - this.rowClipped),
this.ds.totalLength);
return false;
} else {
var params = {
colModel : Ext.util.JSON.encode(extColModelToSrv(this.cm))
};
var sInfo = this.ds.sortInfo;
if (sInfo) {
Ext.apply(params, {
dir : sInfo.direction,
sort : sInfo.field
});
}
return this.ds.load({
params : params
});
}
},
// {{{ ------------adjusted methods for applying custom
// behavior----------------
// private
render : function() {
if (this.autoFill) {
var ct = this.grid.ownerCt;
if (ct && ct.getLayout()) {
ct.on('afterlayout', function() {
this.fitColumns(true, true);
this.updateHeaders();
this.updateHeaderSortState();
}, this, {single: true});
}
} else if (this.forceFit) {
this.fitColumns(true, false);
} else if (this.grid.autoExpandColumn) {
this.autoExpand(true);
}
this.grid.getGridEl().dom.innerHTML = this.renderUI();
this.afterRenderUI();
},
/**
* Overwritten so the {@link Ext.ux.grid.livegrid.DragZone} can be used with
* this view implementation.
*
* Since detaching a previously created DragZone from a grid panel seems to
* be impossible, a little workaround will tell the parent implementation
* that drad/drop is not enabled for this view's grid, and right after that
* the custom DragZone will be created, if neccessary.
*/
renderUI : function () {
var g = this.grid;
var dEnabled = g.enableDragDrop || g.enableDrag;
g.enableDragDrop = false;
g.enableDrag = false;
var m = this._gridViewSuperclass.renderUI.call(this);
g = this.grid;
g.enableDragDrop = dEnabled;
g.enableDrag = dEnabled;
if (dEnabled) {
this.dragZone = new Ext.ux.grid.livegrid.DragZone(g, {
ddGroup : g.ddGroup || 'GridDD'
});
}
return m;
},
afterRenderUI : function()
{
this._gridViewSuperclass.afterRenderUI.call(this);
if (this.loadMask) {
this._loadMaskAnchor = Ext.get(this.mainBody.dom.parentNode.parentNode);
Ext.apply(this.loadMask, {
msgCls : 'x-mask-loading'
});
this._loadMaskAnchor.mask(this.loadMask.msg, this.loadMask.msgCls);
var dom = this._loadMaskAnchor.dom;
var data = Ext.Element.data;
data(dom, 'mask').addClass('ext-ux-livegrid');
data(dom, 'mask').setDisplayed(false);
data(dom, 'maskMsg').setDisplayed(false);
}
},
/**
* The extended implementation attaches an listener to the beforeload event
* of the store of the grid. It is guaranteed that the listener will only be
* executed upon reloading of the store, sorting and initial loading of
* data. When the store does "buffer", all events are suspended and the
* beforeload event will not be triggered.
*
* @param {Ext.grid.GridPanel}
* grid The grid panel this view is attached to
*/
init : function (grid) {
this._gridViewSuperclass.init.call(this, grid);
grid.on('expand', this._onExpand, this);
},
initData : function (ds, cm) {
if (this.ds) {
this.ds.un('bulkremove', this.onBulkRemove, this);
this.ds.un('beforeload', this.onBeforeLoad, this);
}
if (ds) {
ds.on('bulkremove', this.onBulkRemove, this);
ds.on('beforeload', this.onBeforeLoad, this);
}
this._gridViewSuperclass.initData.call(this, ds, cm);
},
/**
* Only render the viewable rect of the table. The number of rows visible to
* the user is defined in <tt>visibleRows</tt>. This implementation does
* completely overwrite the parent's implementation.
*/
// private
renderBody : function () {
var markup = this.renderRows(0, this.visibleRows - 1);
return this.templates.body.apply({
rows : markup
});
},
/**
* Overriden so the renderer of the specific cells gets the index of the row
* as available in the view passed (row's rowIndex property)-
*
*/
doRender : function (cs, rs, ds, startRow, colCount, stripe) {
return this._gridViewSuperclass.doRender.call(this, cs, rs, ds, startRow + this.ds.bufferRange[0], colCount,
stripe);
},
/**
* Inits the DOM native elements for this component. The properties
* <tt>liveScroller</tt> and <tt>liveScrollerInsets</tt> will be
* respected as provided by the master template. The <tt>scroll</tt>
* listener for the <tt>liverScroller</tt> will also be added here as the
* <tt>mousewheel</tt> listener. This method overwrites the parents
* implementation.
*/
// private
initElements : function () {
var E = Ext.Element;
var el = this.grid.getGridEl().dom.firstChild;
var cs = el.childNodes;
this.el = new E(el);
this.mainWrap = new E(cs[1]);
// liveScroller and liveScrollerInsets
this.liveScroller = new E(cs[0]);
var f = this.liveScroller.dom.firstChild;
this.liveScrollerInsets = [ f ];
var divSuivante = f.nextSibling;
while (!Ext.isEmpty(divSuivante)) {
this.liveScrollerInsets.push(divSuivante);
divSuivante = divSuivante.nextSibling;
}
//this.liveScrollerInsets = [ f, f.nextSibling, f.nextSibling.nextSibling, f.nextSibling.nextSibling.nextSibling, f.nextSibling.nextSibling.nextSibling.nextSibling, f.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling ];
this.liveScroller.on('scroll', this.onLiveScroll, this, {
buffer : this.scrollDelay
});
var thd = this.mainWrap.dom.firstChild;
this.mainHd = new E(thd);
this.hdHeight = thd.offsetHeight;
this.innerHd = this.mainHd.dom.firstChild;
this.scroller = new E(this.mainWrap.dom.childNodes[1]);
if (this.forceFit) {
this.scroller.setStyle('overflow-x', 'hidden');
}
this.mainBody = new E(this.scroller.dom.firstChild);
// addd the mousewheel event to the table's body
this.mainBody.on('mousewheel', this.handleWheel, this);
this.focusEl = new E(this.scroller.dom.childNodes[1]);
this.focusEl.swallowEvent("click", true);
this.resizeMarker = new E(cs[2]);
this.resizeProxy = new E(cs[3]);
},
/**
* Layouts the grid's view taking the scroller into account. The height of
* the scroller gets adjusted depending on the total width of the columns.
* The width of the grid view will be adjusted so the header and the rows do
* not overlap the scroller. This method will also compute the row-height
* based on the first row this grid displays and will adjust the number of
* visible rows if a resize of the grid component happened. This method
* overwrites the parents implementation.
*/
// private
layout : function () {
if (!this.mainBody) {
return; // not rendered
}
var g = this.grid;
var c = g.getGridEl(), cm = this.cm, expandCol = g.autoExpandColumn, gv = this;
var csize = c.getSize(true);
// set vw to 19 to take scrollbar width into account!
var vw = csize.width;
if (!g.hideHeaders && vw < 20 || csize.height < 20) { // display:
// none?
return;
}
if (g.autoHeight) {
this.scroller.dom.style.overflow = 'visible';
if (Ext.isWebKit) {
this.scroller.dom.style.position = 'static';
}
} else {
this.el.setSize(csize.width, csize.height);
var hdHeight = this.mainHd.getHeight();
var vh = csize.height - (hdHeight);
this.scroller.setSize(vw, vh);
if (this.innerHd) {
this.innerHd.style.width = (vw) + 'px';
}
}
this.liveScroller.dom.style.top = this.hdHeight + "px";
if (this.forceFit) {
if (this.lastViewWidth != vw) {
this.fitColumns(false, false);
this.lastViewWidth = vw;
}
} else {
this.autoExpand();
}
// adjust the number of visible rows and the height of the scroller.
this.adjustVisibleRows();
this.adjustBufferInset();
this.onLayout(vw, vh);
},
/**
* Overriden for Ext 2.2 to prevent call to focus Row.
*
*/
removeRow : function (row) {
Ext.removeNode(this.getRow(row));
},
/**
* Overriden for Ext 2.2 to prevent call to focus Row. This method i s here
* for dom operations only - the passed arguments are the index of the nodes
* in the dom, not in the model.
*
*/
removeRows : function (firstRow, lastRow) {
var bd = this.mainBody.dom;
for (var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++) {
Ext.removeNode(bd.childNodes[firstRow]);
}
},
// {{{ ----------------------dom/mouse
// listeners--------------------------------
/**
* Tells the view to recalculate the number of rows displayable and the
* buffer inset, when it gets expanded after it has been collapsed.
*
*/
_onExpand : function (panel) {
this.adjustVisibleRows();
this.adjustBufferInset();
this.adjustScrollerPos(this.rowHeight * this.rowIndex, true);
},
// private
onColumnMove : function (cm, oldIndex, newIndex) {
this.indexMap = null;
this.replaceLiveRows(this.rowIndex, true);
this.updateHeaders();
this.updateHeaderSortState();
this.afterMove(newIndex);
this.grid.fireEvent('columnmove', oldIndex, newIndex);
},
/**
* Called when a column width has been updated. Adjusts the scroller height
* and the number of visible rows wether the horizontal scrollbar is shown
* or not.
*/
onColumnWidthUpdated : function (col, w, tw) {
this.adjustVisibleRows();
this.adjustBufferInset();
},
/**
* Called when the width of all columns has been updated. Adjusts the
* scroller height and the number of visible rows wether the horizontal
* scrollbar is shown or not.
*/
onAllColumnWidthsUpdated : function (ws, tw) {
this.adjustVisibleRows();
this.adjustBufferInset();
},
/**
* Callback for selecting a row. The index of the row is the absolute index
* in the datamodel. If the row is not rendered, this method will do
* nothing.
*/
// private
onRowSelect : function (row) {
if (row < this.rowIndex || row > this.rowIndex+this.visibleRows) {
return;
}
this.addRowClass(row, this.selectedRowClass);
},
/**
* Callback for deselecting a row. The index of the row is the absolute
* index in the datamodel. If the row is not currently rendered in the view,
* this method will do nothing.
*/
// private
onRowDeselect : function (row) {
if (row < this.rowIndex || row > this.rowIndex+this.visibleRows) {
return;
}
this.removeRowClass(row, this.selectedRowClass);
},
// {{{ ----------------------data
// listeners-------------------------------------
/**
* Called when the buffer gets cleared. Simply calls the updateLiveRows
* method with the adjusted index and should force the store to reload
*/
// private
onClear : function () {
this.reset(false);
},
/**
* Callback for the "bulkremove" event of the attached datastore.
*
* @param {Ext.ux.grid.livegrid.Store}
* store
* @param {Array}
* removedData
*
*/
onBulkRemove : function (store, removedData) {
var record = null;
var index = 0;
var viewIndex = 0;
var len = removedData.length;
var removedInView = false;
var removedAfterView = false;
var scrollerAdjust = 0;
if (len === 0) {
return;
}
var tmpRowIndex = this.rowIndex;
var removedBefore = 0;
var removedAfter = 0;
var removedIn = 0;
for (var i = 0; i < len; i++) {
record = removedData[i][0];
index = removedData[i][1];
viewIndex = (index != Number.MIN_VALUE && index != Number.MAX_VALUE) ? index + this.ds.bufferRange[0] : index;
if (viewIndex < this.rowIndex) {
removedBefore++;
} else if (viewIndex >= this.rowIndex && viewIndex <= this.rowIndex + (this.visibleRows - 1)) {
removedIn++;
} else if (viewIndex >= this.rowIndex + this.visibleRows) {
removedAfter++;
}
this.fireEvent("beforerowremoved", this, viewIndex, record);
this.fireEvent("rowremoved", this, viewIndex, record);
}
var totalLength = this.ds.totalLength;
this.rowIndex = Math.max(0, Math.min(this.rowIndex - removedBefore, totalLength - (this.visibleRows - 1)));
this.lastRowIndex = this.rowIndex;
this.adjustScrollerPos(-(removedBefore * this.rowHeight), true);
this.updateLiveRows(this.rowIndex, true);
this.adjustBufferInset();
this.processRows(0, undefined, false);
},
/**
* Callback for the underlying store's remove method. The current
* implementation does only remove the selected row which record is in the
* current store.
*
* @see onBulkRemove()
*/
// private
onRemove : function (ds, record, index) {
this.onBulkRemove(ds, [ [ record, index ] ]);
},
/**
* The callback for the underlying data store when new data was added. If
* <tt>index</tt> equals to <tt>Number.MIN_VALUE</tt> or
* <tt>Number.MAX_VALUE</tt>, the method can't tell at which position in
* the underlying data model the records where added. However, if
* <tt>index</tt> equals to <tt>Number.MIN_VALUE</tt>, the
* <tt>rowIndex</tt> property will be adjusted to
* <tt>rowIndex+records.length</tt>, and the <tt>liveScroller</tt>'s
* properties get adjusted so it matches the new total number of records of
* the underlying data model. The same will happen to any records that get
* added at the store index which is currently represented by the first
* visible row in the view. Any other value will cause the method to compute
* the number of rows that have to be (re-)painted and calling the
* <tt>insertRows</tt> method, if neccessary.
*
* This method triggers the <tt>beforerowsinserted</tt> and
* <tt>rowsinserted</tt> event, passing the indexes of the records as they
* may default to the positions in the underlying data model. However, due
* to the fact that any sort algorithm may have computed the indexes of the
* records, it is not guaranteed that the computed indexes equal to the
* indexes of the underlying data model.
*
* @param {Ext.ux.grid.livegrid.Store}
* ds The datastore that buffers records from the underlying data
* model
* @param {Array}
* records An array containing the newly added
* {@link Ext.data.Record}s
* @param {Number}
* index The index of the position in the underlying
* {@link Ext.ux.grid.livegrid.Store} where the rows were added.
*/
// private
onAdd : function (ds, records, index) {
if (this._checkEmptyBody) {
if (this.mainBody.dom.innerHTML == ' ') {
this.mainBody.dom.innerHTML = '';
}
this._checkEmptyBody = false;
}
var recordLen = records.length;
// values of index which equal to Number.MIN_VALUE or Number.MAX_VALUE
// indicate that the records were not added to the store. The component
// does not know which index those records do have in the underlying
// data model
if (index == Number.MAX_VALUE || index == Number.MIN_VALUE) {
this.fireEvent("beforerowsinserted", this, index, index);
// if index equals to Number.MIN_VALUE, shift rows!
if (index == Number.MIN_VALUE) {
this.rowIndex = this.rowIndex + recordLen;
this.lastRowIndex = this.rowIndex;
this.adjustBufferInset();
this.adjustScrollerPos(this.rowHeight * recordLen, true);
this.fireEvent("rowsinserted", this, index, index, recordLen);
this.processRows(0, undefined, false);
// the cursor did virtually move
this.fireEvent('cursormove', this, this.rowIndex, Math.min(this.ds.totalLength, this.visibleRows - this.rowClipped), this.ds.totalLength);
return;
}
this.adjustBufferInset();
this.fireEvent("rowsinserted", this, index, index, recordLen);
return;
}
// only insert the rows which affect the current view.
var start = index + this.ds.bufferRange[0];
var end = start + (recordLen - 1);
var len = this.getRows().length;
var firstRow = 0;
var lastRow = 0;
// rows would be added at the end of the rows which are currently
// displayed, so fire the event, resize buffer and adjust visible
// rows and return
if (start > this.rowIndex + (this.visibleRows - 1)) {
this.fireEvent("beforerowsinserted", this, start, end);
this.fireEvent("rowsinserted", this, start, end, recordLen);
this.adjustVisibleRows();
this.adjustBufferInset();
}
// rows get added somewhere in the current view.
else if (start >= this.rowIndex && start <= this.rowIndex + (this.visibleRows - 1)) {
firstRow = index;
// compute the last row that would be affected of an insert
// operation
lastRow = index + (recordLen - 1);
this.lastRowIndex = this.rowIndex;
this.rowIndex = (start > this.rowIndex) ? this.rowIndex : start;
this.insertRows(ds, firstRow, lastRow);
if (this.lastRowIndex != this.rowIndex) {
this.fireEvent('cursormove', this, this.rowIndex, Math.min(this.ds.totalLength, this.visibleRows - this.rowClipped), this.ds.totalLength);
}
this.adjustVisibleRows();
this.adjustBufferInset();
}
// rows get added before the first visible row, which would not affect
// any
// rows to be re-rendered
else if (start < this.rowIndex) {
this.fireEvent("beforerowsinserted", this, start, end);
this.rowIndex = this.rowIndex + recordLen;
this.lastRowIndex = this.rowIndex;
this.adjustVisibleRows();
this.adjustBufferInset();
this.adjustScrollerPos(this.rowHeight * recordLen, true);
this.fireEvent("rowsinserted", this, start, end, recordLen);
this.processRows(0, undefined, true);
this.fireEvent('cursormove', this, this.rowIndex, Math.min(this.ds.totalLength, this.visibleRows - this.rowClipped), this.ds.totalLength);
}
},
// {{{ ----------------------store
// listeners------------------------------------
/**
* This callback for the store's "beforeload" event will adjust the start
* position and the limit of the data in the model to fetch. It is
* guaranteed that this method will only be called when the store initially
* loads, remeote-sorts or reloads. All other load events will be suspended
* when the view requests buffer data. See {updateLiveRows}. Note: If you
* are using a custom proxy, such as {Ext.data.DirectProxy}, you should
* listen to the 'abortrequest'-event, which will tell that an ongoing
* "read" request should be aborted, since the grid's store gets refreshed.
* If the store is using an instance of {Ext.data.HttpProxy}, the method
* will still be fired, but the request made through this proxy will be
* aborted automatically.
*
*
* @param {Ext.data.Store}
* store The store the Grid Panel uses
* @param {Object}
* options The configuration object for the proxy that loads data
* from the server
*/
onBeforeLoad : function (store, options) {
var proxy = store.proxy;
if (proxy.activeRequest && proxy.activeRequest[Ext.data.Api.actions.read]) {
proxy.getConnection().abort(proxy.activeRequest[Ext.data.Api.actions.read]);
}
this.fireEvent('abortrequest', store, options);
this.isBuffering = false;
this.isPreBuffering = false;
options.params = options.params || {};
var apply = Ext.apply;
apply(options, {
scope : this,
callback : function () {
this.reset(false);
},
suspendLoadEvent : false
});
apply(options.params, {
start : 0,
limit : this.ds.bufferSize
});
return true;
},
/**
* Method is used as a callback for the load-event of the attached data
* store. Adjusts the buffer inset based upon the <tt>totalCount</tt>
* property returned by the response. Overwrites the parent's
* implementation.
*/
onLoad : function (o1, o2, options) {
this.adjustBufferInset();
},
/**
* This will be called when the data in the store has changed, i.e. a
* re-buffer has occured. If the table was not rendered yet, a call to
* <tt>refresh</tt> will initially render the table, which DOM elements
* will then be used to re-render the table upon scrolling.
*
*/
// private
onDataChange : function (store) {
this.updateHeaderSortState();
},
/**
* A callback for the store when new data has been buffered successfully. If
* the current row index is not within the range of the newly created data
* buffer or another request to new data has been made while the store was
* loading, new data will be re-requested.
*
* Additionally, if there are any rows that have been selected which were
* not in the data store, the method will request the pending selections
* from the grid's selection model and add them to the selections if
* available. This is because the component assumes that a user who scrolls
* through the rows and updates the view's buffer during scrolling, can
* check the selected rows which come into the view for integrity. It is up
* to the user to deselect those rows not matchuing the selection.
* Additionally, if the version of the store changes during various requests
* and selections are still pending, the versionchange event of the store
* can delete the pending selections after a re-bufer happened and before
* this method was called.
*
*/
// private
liveBufferUpdate : function (records, options, success) {
if (success === true) {
this.adjustBufferInset();
this.fireEvent('buffer', this, this.ds, this.rowIndex, Math.min(this.ds.totalLength, this.visibleRows - this.rowClipped), this.ds.totalLength, options);
// this is needed since references to records which have been
// unloaded
// get lost when the store gets loaded with new data.
// from the store
this.grid.selModel.replaceSelections(records);
this.isBuffering = false;
this.isPrebuffering = false;
this.showLoadMask(false);
if (this.requestQueue >= 0) {
var offset = this.requestQueue;
this.requestQueue = -1;
this.updateLiveRows(offset);
return;
}
if (this.isInRange(this.rowIndex)) {
this.replaceLiveRows(this.rowIndex, options.forceRepaint);
} else {
this.updateLiveRows(this.rowIndex);
}
return;
} else {
this.fireEvent('bufferfailure', this, this.ds, options);
}
this.requestQueue = -1;
this.isBuffering = false;
this.isPrebuffering = false;
this.showLoadMask(false);
},
// {{{ ----------------------scroll
// listeners------------------------------------
/**
* Handles mousewheel event on the table's body. This is neccessary since
* the <tt>liveScroller</tt> element is completely detached from the
* table's body.
*
* @param {Ext.EventObject}
* e The event object
*/
handleWheel : function (e) {
if (this.rowHeight == -1) {
e.stopEvent();
return;
}
var d = e.getWheelDelta();
this.adjustScrollerPos(-(d * this.rowHeight));
e.stopEvent();
},
/**
* Handles scrolling through the grid. Since the grid is fixed and rows get
* removed/ added subsequently, the only way to determine the actual row in
* view is to measure the <tt>scrollTop</tt> property of the
* <tt>liveScroller</tt>'s DOM element.
*
*/
onLiveScroll : function () {
var scrollTop = this.liveScroller.dom.scrollTop;
var cursor = Math.floor((scrollTop) / this.rowHeight);
this.rowIndex = cursor;
// the lastRowIndex will be set when refreshing the view has finished
if (cursor == this.lastRowIndex) {
return;
}
this.updateLiveRows(cursor);
this.lastScrollPos = this.liveScroller.dom.scrollTop;
},
// {{{
// --------------------------helpers----------------------------------------
// private
refreshRow : function (record) {
var ds = this.ds, index;
if (typeof record == 'number') {
index = record;
record = ds.getAt(index);
} else {
index = ds.indexOf(record);
}
var viewIndex = index + this.ds.bufferRange[0];
if (viewIndex < this.rowIndex || viewIndex >= this.rowIndex + this.visibleRows) {
this.fireEvent("rowupdated", this, viewIndex, record);
return;
}
this.insertRows(ds, index, index, true);
this.fireEvent("rowupdated", this, viewIndex, record);
},
/**
* Overwritten so the rowIndex can be changed to the absolute index.
*
* If the third parameter equals to <tt>true</tt>, the method will also
* repaint the selections.
*/
// private
processRows : function (startRow, skipStripe, paintSelections) {
if (!this.ds || this.ds.getCount() < 1) {
return;
}
skipStripe = skipStripe || !this.grid.stripeRows;
var cursor = this.rowIndex;
var rows = this.getRows();
var index = 0;
var row = null;
for (var idx = 0, len = rows.length; idx < len; idx++) {
row = rows[idx];
row.rowIndex = index = cursor + idx;
row.className = row.className.replace(this.rowClsRe, ' ');
if (!skipStripe && (index + 1) % 2 === 0) {
row.className += ' x-grid3-row-alt';
}
if (paintSelections !== false) {
if (this.grid.selModel.isSelected(this.ds.getAt(index)) === true) {
this.addRowClass(index, this.selectedRowClass);
} else {
this.removeRowClass(index, this.selectedRowClass);
}
this.fly(row).removeClass("x-grid3-row-over");
}
}
// add first/last-row classes
if (cursor === 0) {
Ext.fly(rows[0]).addClass(this.firstRowCls);
} else if (cursor + rows.length == this.ds.totalLength) {
Ext.fly(rows[rows.length - 1]).addClass(this.lastRowCls);
}
},
/**
* API only, since the passed arguments are the indexes in the buffer store.
* However, the method will try to compute the indexes so they might match
* the indexes of the records in the underlying data model.
*
*/
// private
insertRows : function (dm, firstRow, lastRow, isUpdate) {
var viewIndexFirst = firstRow + this.ds.bufferRange[0];
var viewIndexLast = lastRow + this.ds.bufferRange[0];
if (!isUpdate) {
this.fireEvent("beforerowsinserted", this, viewIndexFirst, viewIndexLast);
}
// first off, remove the rows at the bottom of the view to match the
// visibleRows value and to not cause any spill in the DOM
if (isUpdate !== true && (this.getRows().length + (lastRow - firstRow)) >= this.visibleRows) {
this.removeRows((this.visibleRows - 1) - (lastRow - firstRow), this.visibleRows - 1);
} else if (isUpdate) {
this.removeRows(viewIndexFirst - this.rowIndex, viewIndexLast - this.rowIndex);
}
// compute the range of possible records which could be drawn into the
// view without
// causing any spill
var lastRenderRow = (firstRow == lastRow) ? lastRow : Math.min(lastRow,
(this.rowIndex - this.ds.bufferRange[0]) + (this.visibleRows - 1));
var html = this.renderRows(firstRow, lastRenderRow);
var before = this.getRow(viewIndexFirst);
if (before) {
Ext.DomHelper.insertHtml('beforeBegin', before, html);
} else {
Ext.DomHelper.insertHtml('beforeEnd', this.mainBody.dom, html);
}
// if a row is replaced, we need to set the row index for this
// row
if (isUpdate === true) {
var rows = this.getRows();
var cursor = this.rowIndex;
for (var i = 0, max_i = rows.length; i < max_i; i++) {
rows[i].rowIndex = cursor + i;
}
}
if (!isUpdate) {
this.fireEvent("rowsinserted", this, viewIndexFirst, viewIndexLast, (viewIndexLast - viewIndexFirst) + 1);
this.processRows(0, undefined, true);
}
},
/**
* Return the
* <TR> HtmlElement which represents a Grid row for the specified index. The
* passed argument is assumed to be the absolute index and will get
* translated to the index of the row that represents the data in the view.
*
* @param {Number}
* index The row index
*
* @return {null|HtmlElement} The
* <TR> element, or null if the row is not rendered in the view.
*/
getRow : function (row) {
if (row - this.rowIndex < 0) {
return null;
}
return this.getRows()[row - this.rowIndex];
},
/**
* Returns the grid's
* <TD> HtmlElement at the specified coordinates. Returns null if the
* specified row is not currently rendered.
*
* @param {Number}
* row The row index in which to find the cell.
* @param {Number}
* col The column index of the cell.
* @return {HtmlElement} The <TD> at the specified coordinates.
*/
getCell : function (row, col) {
var arow = this.getRow(row);
return arow ? arow.getElementsByTagName('td')[col] : null;
},
/**
* Focuses the specified cell.
*
* @param {Number}
* row The row index
* @param {Number}
* col The column index
*/
focusCell : function (row, col, hscroll) {
var xy = this.ensureVisible(row, col, hscroll);
if (!xy) {
return;
}
this.focusEl.setXY(xy);
if (Ext.isGecko) {
this.focusEl.focus();
} else {
this.focusEl.focus.defer(1, this.focusEl);
}
},
/**
* Makes sure that the requested /row/col is visible in the viewport. The
* method may invoke a request for new buffer data and triggers the
* scroll-event of the <tt>liveScroller</tt> element.
*
*/
// private
ensureVisible : function (row, col, hscroll) {
if (typeof row != "number") {
row = row.rowIndex;
}
if (row < 0 || row >= this.ds.totalLength) {
return;
}
col = (col !== undefined ? col : 0);
var rowInd = row - this.rowIndex;
if (this.rowClipped && row == this.rowIndex + this.visibleRows - 1) {
this.adjustScrollerPos(this.rowHeight);
} else if (row >= this.rowIndex + this.visibleRows) {
this.adjustScrollerPos(((row - (this.rowIndex + this.visibleRows)) + 1) * this.rowHeight);
} else if (row <= this.rowIndex) {
this.adjustScrollerPos((rowInd) * this.rowHeight);
}
var rowEl = this.getRow(row), cellEl;
if (!rowEl) {
return;
}
if (!(hscroll === false && col === 0)) {
while (this.cm.isHidden(col)) {
col++;
}
cellEl = this.getCell(row, col);
}
var c = this.scroller.dom;
if (hscroll !== false) {
var cleft = parseInt(cellEl.offsetLeft, 10);
var cright = cleft + cellEl.offsetWidth;
var sleft = parseInt(c.scrollLeft, 10);
var sright = sleft + c.clientWidth;
if (cleft < sleft) {
c.scrollLeft = cleft;
} else if (cright > sright) {
c.scrollLeft = cright - c.clientWidth;
}
}
return cellEl ? Ext.fly(cellEl).getXY() : [ c.scrollLeft + this.el.getX(), Ext.fly(rowEl).getY() ];
},
/**
* Return strue if the passed record is in the visible rect of this view.
*
* @param {Ext.data.Record}
* record
*
* @return {Boolean} true if the record is rendered in the view, otherwise
* false.
*/
isRecordRendered : function (record) {
var ind = this.ds.indexOf(record);
if (ind >= this.rowIndex && ind < this.rowIndex + this.visibleRows) {
return true;
}
return false;
},
/**
* Checks if the passed argument <tt>cursor</tt> lays within a renderable
* area. The area is renderable, if the sum of cursor and the visibleRows
* property does not exceed the current upper buffer limit.
*
* If this method returns <tt>true</tt>, it's basically save to re-render
* the view with <tt>cursor</tt> as the absolute position in the model as
* the first visible row.
*
* @param {Number}
* cursor The absolute position of the row in the data model.
*
* @return {Boolean} <tt>true</tt>, if the row can be rendered, otherwise
* <tt>false</tt>
*
*/
isInRange : function (rowIndex) {
var lastRowIndex = Math.min(this.ds.totalLength - 1, rowIndex + (this.visibleRows - 1));
return (rowIndex >= this.ds.bufferRange[0]) && (lastRowIndex <= this.ds.bufferRange[1]);
},
/**
* Calculates the bufferRange start index for a buffer request
*
* @param {Boolean}
* inRange If the index is within the current buffer range
* @param {Number}
* index The index to use as a reference for the calculations
* @param {Boolean}
* down Wether the calculation was requested when the user
* scrolls down
*/
getPredictedBufferIndex : function (index, inRange, down) {
if (!inRange) {
if (index + this.ds.bufferSize >= this.ds.totalLength) {
return this.ds.totalLength - this.ds.bufferSize;
}
// we need at last to render the index + the visible Rows
return Math.max(0, (index + this.visibleRows) - Math.round(this.ds.bufferSize / 2));
}
if (!down) {
return Math.max(0, (index - this.ds.bufferSize) + this.visibleRows);
}
if (down) {
return Math.max(0, Math.min(index, this.ds.totalLength - this.ds.bufferSize));
}
},
/**
* Updates the table view. Removes/appends rows as needed and fetches the
* cells content out of the available store. If the needed rows are not
* within the buffer, the method will advise the store to update it's
* contents.
*
* The method puts the requested cursor into the queue if a previously
* called buffering is in process.
*
* @param {Number}
* cursor The row's position, absolute to it's position in the
* data model
*
*/
updateLiveRows : function (index, forceRepaint, forceReload) {
var inRange = this.isInRange(index);
if (this.isBuffering) {
if (this.isPrebuffering) {
if (inRange) {
this.replaceLiveRows(index, forceRepaint);
} else {
this.showLoadMask(true);
}
}
this.fireEvent('cursormove', this, index,
Math.min(this.ds.totalLength, this.visibleRows - this.rowClipped), this.ds.totalLength);
this.requestQueue = index;
return;
}
var lastIndex = this.lastIndex;
this.lastIndex = index;
inRange = this.isInRange(index);
var down = false;
if (inRange && forceReload !== true) {
// repaint the table's view
this.replaceLiveRows(index, forceRepaint);
// has to be called AFTER the rowIndex was recalculated
this.fireEvent('cursormove', this, index,
Math.min(this.ds.totalLength, this.visibleRows - this.rowClipped), this.ds.totalLength);
// lets decide if we can void this method or stay in here for
// requesting a buffer update
if (index > lastIndex) { // scrolling down
down = true;
var totalCount = this.ds.totalLength;
// while scrolling, we have not yet reached the row index
// that would trigger a re-buffer
if (index + this.visibleRows + this.nearLimit <= this.ds.bufferRange[1]) {
return;
}
// If we have already buffered the last range we can ever get
// by the queried data repository, we don't need to buffer
// again.
// This basically means that a re-buffer would only occur again
// if we are scrolling up.
if (this.ds.bufferRange[1] + 1 >= totalCount) {
return;
}
} else if (index < lastIndex) { // scrolling up
down = false;
// We are scrolling up in the first buffer range we can ever get
// Re-buffering would only occur upon scrolling down.
if (this.ds.bufferRange[0] <= 0) {
return;
}
// if we are scrolling up and we are moving in an acceptable
// buffer range, lets return.
if (index - this.nearLimit > this.ds.bufferRange[0]) {
return;
}
} else {
return;
}
this.isPrebuffering = true;
}
// prepare for rebuffering
this.isBuffering = true;
var bufferOffset = this.getPredictedBufferIndex(index, inRange, down);
if (!inRange) {
this.showLoadMask(true);
}
this.ds.suspendEvents();
var sInfo = this.ds.sortInfo;
var params = {};
if (this.ds.lastOptions) {
Ext.apply(params, this.ds.lastOptions.params);
}
params.start = bufferOffset;
params.limit = this.ds.bufferSize;
// if(this.ds.doCount){
params.nocount = true;
/*}else{
params.nocount = false;
}*/
if (sInfo) {
params.dir = sInfo.direction;
params.sort = sInfo.field;
}
var opts = {
forceRepaint : forceRepaint,
callback : this.liveBufferUpdate,
scope : this,
params : params,
suspendLoadEvent : true
};
this.fireEvent('beforebuffer', this, this.ds, index, Math.min(this.ds.totalLength, this.visibleRows - this.rowClipped), this.ds.totalLength, opts);
this.ds.load(opts);
this.ds.resumeEvents();
},
/**
* Shows this' view own load mask to indicate that a large amount of buffer
* data was requested by the store.
*
* @param {Boolean}
* show <tt>true</tt> to show the load mask, otherwise
* <tt>false</tt>
*/
showLoadMask : function (show) {
if (!this.loadMask || show == this.loadMaskDisplayed) {
return;
}
var dom = this._loadMaskAnchor.dom;
var data = Ext.Element.data;
var mask = data(dom, 'mask');
var maskMsg = data(dom, 'maskMsg');
if (show) {
mask.setDisplayed(true);
maskMsg.setDisplayed(true);
maskMsg.center(this._loadMaskAnchor);
// this lines will help IE8 to re-calculate the height of the
// loadmask
if (Ext.isIE && !(Ext.isIE7 && Ext.isStrict) && this._loadMaskAnchor.getStyle('height') == 'auto') {
mask.setSize(undefined, this._loadMaskAnchor.getHeight());
}
} else {
mask.setDisplayed(false);
maskMsg.setDisplayed(false);
}
this.loadMaskDisplayed = show;
},
/**
* Renders the table body with the contents of the model. The method will
* prepend/ append rows after removing from either the end or the beginning
* of the table DOM to reduce expensive DOM calls. It will also take care of
* rendering the rows selected, taking the property
* <tt>bufferedSelections</tt> of the {@link BufferedRowSelectionModel}
* into account. Instead of calling this method directly, the
* <tt>updateLiveRows</tt> method should be called which takes care of
* rebuffering if needed, since this method will behave erroneous if data of
* the buffer is requested which may not be available.
*
* @param {Number}
* cursor The position of the data in the model to start
* rendering.
*
* @param {Boolean}
* forceReplace <tt>true</tt> for recomputing the DOM in the
* view, otherwise <tt>false</tt>.
*/
// private
replaceLiveRows : function (cursor, forceReplace, processRows) {
var spill = cursor - this.lastRowIndex;
if (spill === 0 && forceReplace !== true) {
return;
}
// decide wether to prepend or append rows
// if spill is negative, we are scrolling up. Thus we have to prepend
// rows. If spill is positive, we have to append the buffers data.
var append = spill > 0;
// abs spill for simplyfiying append/prepend calculations
spill = Math.abs(spill);
// adjust cursor to the buffered model index
var bufferRange = this.ds.bufferRange;
var cursorBuffer = cursor - bufferRange[0];
// compute the last possible renderindex
var lpIndex = Math.min(cursorBuffer + this.visibleRows - 1, bufferRange[1] - bufferRange[0]);
// we can skip checking for append or prepend if the spill is larger
// than
// visibleRows. We can paint the whole rows new then-
if (spill >= this.visibleRows || spill === 0) {
this.mainBody.update(this.renderRows(cursorBuffer, lpIndex));
} else {
if (append) {
this.removeRows(0, spill - 1);
if (cursorBuffer + this.visibleRows - spill <= bufferRange[1] - bufferRange[0]) {
var html = this.renderRows(cursorBuffer + this.visibleRows - spill, lpIndex);
Ext.DomHelper.insertHtml('beforeEnd', this.mainBody.dom, html);
}
} else {
this.removeRows(this.visibleRows - spill, this.visibleRows - 1);
html = this.renderRows(cursorBuffer, cursorBuffer + spill - 1);
Ext.DomHelper.insertHtml('beforeBegin', this.mainBody.dom.firstChild, html);
}
}
if (processRows !== false) {
this.processRows(0, undefined, true);
}
this.lastRowIndex = cursor;
},
/**
* Adjusts the scroller height to make sure each row in the dataset will be
* can be displayed, no matter which value the current height of the grid
* component equals to.
*/
// protected
adjustBufferInset : function () {
var liveScrollerDom = this.liveScroller.dom;
var g = this.grid, ds = g.store;
var c = g.getGridEl();
var elWidth = c.getSize().width;
// hidden rows is the number of rows which cannot be
// displayed and for which a scrollbar needs to be
// rendered. This does also take clipped rows into account
var hiddenRows = (ds.totalLength == this.visibleRows - this.rowClipped) ? 0 : Math.max(0, ds.totalLength - (this.visibleRows - this.rowClipped));
if (hiddenRows === 0) {
this.scroller.setWidth(elWidth);
liveScrollerDom.style.display = 'none';
return;
} else {
this.scroller.setWidth(elWidth - this.getScrollOffset());
liveScrollerDom.style.display = '';
}
var scrollbar = this.cm.getTotalWidth() + this.getScrollOffset() > elWidth;
// adjust the height of the scrollbar
var contHeight = liveScrollerDom.parentNode.offsetHeight + ((ds.totalLength > 0 && scrollbar) ? -this.horizontalScrollOffset : 0) - this.hdHeight;
liveScrollerDom.style.height = Math.max(contHeight, this.horizontalScrollOffset * 2) + "px";
this.liveScroller.dom.style.width = (this.getScrollOffset() + 2) + "px";
if (this.rowHeight == -1) {
return;
}
var cm = this.cm;
var vw = elWidth - this.getScrollOffset();
var hso = 0, hh = 0;
// horizontal scrollbar shown?
if (cm.getTotalWidth() > vw) {
// yes!
hso = this.horizontalScrollOffset;
}
hh = this.mainHd.getHeight();
var h = (hiddenRows === 0 ? 0 : ds.totalLength * this.rowHeight + hso + hh);//contHeight + (hiddenRows * this.rowHeight));
//DA : Ajouter une limitation a la taille de la div générée. Générer un message pour l'utilisateur en cas de dépassement.
if (h > 35791380) {
h = 35000000;
var nbRecords = Math.floor(h / this.rowHeight);
if (this._displayWarningTooManyRows) {
Ext.Msg.alert(i18n.get('label.warning'), String.format(i18n.get("label.tooManyRecords"), nbRecords, this.visibleRows + hiddenRows));
this._displayWarningTooManyRows = false;
}
}
var oh = h;
var len = this.liveScrollerInsets.length;
if (h === 0) {
h = 0;
} else {
h = Math.round(h / len);
}
for (var i = 0; i < len; i++) {
if (i == len - 1 && h !== 0) {
h = oh - (h * i);
}
this.liveScrollerInsets[i].style.height = h + "px";
}
},
/**
* Recomputes the number of visible rows in the table based upon the height
* of the component. The method adjusts the <tt>rowIndex</tt> property as
* needed, if the sum of visible rows and the current row index exceeds the
* number of total data available.
*/
// protected
adjustVisibleRows : function () {
if (this.rowHeight == -1) {
if (this.getRows()[0]) {
this.rowHeight = this.getRows()[0].offsetHeight;
if (this.rowHeight <= 0) {
this.rowHeight = -1;
return;
}
} else {
return;
}
}
var g = this.grid, ds = g.store;
var c = g.getGridEl();
var cm = this.cm;
var size = c.getSize();
var width = size.width;
var vh = size.height;
var vw = width - this.getScrollOffset();
// horizontal scrollbar shown?
if (cm.getTotalWidth() > vw) {
// yes!
vh -= this.horizontalScrollOffset;
}
vh -= this.mainHd.getHeight();
var totalLength = ds.totalLength || 0;
var visibleRows = Math.max(1, Math.floor(vh / this.rowHeight));
this.rowClipped = 0;
// only compute the clipped row if the total length of records
// exceeds the number of visible rows displayable
if (totalLength > visibleRows && this.rowHeight / 3 < (vh - (visibleRows * this.rowHeight))) {
visibleRows = Math.min(visibleRows + 1, totalLength);
this.rowClipped = 1;
}
// if visibleRows didn't change, simply void and return.
if (this.visibleRows == visibleRows) {
return;
}
this.visibleRows = visibleRows;
// skip recalculating the row index if we are currently buffering, but
// not if we
// are just pre-buffering
if (this.isBuffering && !this.isPrebuffering) {
return;
}
// when re-rendering, doe not take the clipped row into account
if (this.rowIndex + (visibleRows - this.rowClipped) > totalLength) {
this.rowIndex = Math.max(0, totalLength - (visibleRows - this.rowClipped));
this.lastRowIndex = this.rowIndex;
}
this.updateLiveRows(this.rowIndex, true);
},
adjustScrollerPos : function (pixels, suspendEvent) {
if (pixels === 0) {
return;
}
var liveScroller = this.liveScroller;
var scrollDom = liveScroller.dom;
if (suspendEvent === true) {
liveScroller.un('scroll', this.onLiveScroll, this);
}
this.lastScrollPos = scrollDom.scrollTop;
scrollDom.scrollTop += pixels;
if (suspendEvent === true) {
scrollDom.scrollTop = scrollDom.scrollTop;
liveScroller.on('scroll', this.onLiveScroll, this, {
buffer : this.scrollDelay
});
}
}
});
/**
* Ext.ux.grid.livegrid.JsonReader Copyright (c) 2007-2008,
* http://www.siteartwork.de
*
* Ext.ux.grid.livegrid.JsonReader is licensed under the terms of the GNU Open
* Source GPL 3.0 license.
*
* Commercial use is prohibited. Visit <http://www.siteartwork.de/livegrid> if
* you need to obtain a commercial license.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/gpl.html>.
*
*/
Ext.namespace('Ext.ux.grid.livegrid');
/**
* @class Ext.ux.grid.livegrid.JsonReader
* @extends Ext.data.JsonReader
* @constructor
* @param {Object}
* config
*
* @author Thorsten Suckow-Homberg <ts@siteartwork.de>
*/
Ext.ux.grid.livegrid.JsonReader = function (meta, recordType) {
Ext.ux.grid.livegrid.JsonReader.superclass.constructor.call(this, meta, recordType);
};
Ext.extend(Ext.ux.grid.livegrid.JsonReader, Ext.data.JsonReader, {
/**
* @cfg {String} versionProperty Name of the property from which to retrieve
* the version of the data repository this reader parses the reponse
* from
*/
buildExtractors : function () {
if (this.ef) {
return;
}
var s = this.meta;
if (s.versionProperty) {
this.getVersion = this.createAccessor(s.versionProperty);
}
Ext.ux.grid.livegrid.JsonReader.superclass.buildExtractors.call(this);
},
/**
* Create a data block containing Ext.data.Records from a JSON object.
*
* @param {Object}
* o An object which contains an Array of row objects in the
* property specified in the config as 'root, and optionally a
* property, specified in the config as 'totalProperty' which
* contains the total size of the dataset.
* @return {Object} data A data block which is used by an Ext.data.Store
* object as a cache of Ext.data.Records.
*/
readRecords : function (o) {
// shorten for future calls
if (!this.__readRecords) {
this.__readRecords = Ext.ux.grid.livegrid.JsonReader.superclass.readRecords;
}
var intercept = this.__readRecords.call(this, o);
if (this.meta.versionProperty) {
var v = this.getVersion(o);
intercept.version = (v === undefined || v === "") ? null : v;
}
//TODO
if (Ext.isEmpty(o.total)) {
intercept.totalRecords = this.totalRecordsSitools;
} else {
this.totalRecordsSitools = o.total;
}
return intercept;
}
});
/**
* Ext.ux.grid.livegrid.RowSelectionModel Copyright (c) 2007-2008,
* http://www.siteartwork.de
*
* Ext.ux.grid.livegrid.RowSelectionModel is licensed under the terms of the GNU
* Open Source GPL 3.0 license.
*
* Commercial use is prohibited. Visit <http://www.siteartwork.de/livegrid> if
* you need to obtain a commercial license.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/gpl.html>.
*
*/
Ext.namespace('Ext.ux.grid.livegrid');
/**
* @class Ext.ux.grid.livegrid.RowSelectionModel
* @extends Ext.grid.RowSelectionModel
* @constructor
* @param {Object}
* config
*
* @author Thorsten Suckow-Homberg <ts@siteartwork.de>
*/
Ext.ux.grid.livegrid.RowSelectionModel = function (config) {
this.addEvents({
/**
* The selection dirty event will be triggered in case records were
* inserted/ removed at view indexes that may affect the current
* selection ranges which are only represented by view indexes, but not
* current record-ids
*/
'selectiondirty' : true,
//SITOOLS, MG, nouvel event pour gérer les selections
'handleMouseDown' : true
});
Ext.apply(this, config);
this.pendingSelections = {};
Ext.ux.grid.livegrid.RowSelectionModel.superclass.constructor.call(this);
};
Ext.extend(Ext.ux.grid.livegrid.RowSelectionModel, Ext.grid.RowSelectionModel, {
// private
initEvents : function () {
Ext.ux.grid.livegrid.RowSelectionModel.superclass.initEvents.call(this);
this.grid.view.on('rowsinserted', this.onAdd, this);
this.grid.store.on('selectionsload', this.onSelectionsLoad, this);
},
// private : DA : supprimer le view.focusRow (celui ci provoque un probleme
// lorsque le scroll horizontal est important
//SITOOLS, MG, nouvel event pour gérer les selections
handleMouseDown : function (g, rowIndex, e) {
if (e.button !== 0 || this.isLocked()) {
return;
}
var view = this.grid.getView();
if (e.shiftKey && !this.singleSelect && this.last !== false) {
var last = this.last;
this.selectRange(last, rowIndex, e.ctrlKey);
this.last = last;
// view.focusRow(rowIndex);
this.fireEvent('handleMouseDown', this);
} else {
var isSelected = this.isSelected(rowIndex);
if (e.ctrlKey && isSelected) {
this.deselectRow(rowIndex);
this.fireEvent('handleMouseDown', this);
} else if (!isSelected || this.getCount() > 1) {
this.selectRow(rowIndex, e.ctrlKey || e.shiftKey);
this.fireEvent('handleMouseDown', this);
// view.focusRow(rowIndex);
}
}
},
/**
* Callback is called when a row gets removed in the view. The process to
* invoke this method is as follows:
*
* <ul>
* <li>1. store.remove(record);</li>
* <li>2. view.onRemove(store, record, indexInStore, isUpdate)<br />
* [view triggers rowremoved event]</li>
* <li>3. this.onRemove(view, indexInStore, record)</li>
* </ul>
*
* If r defaults to <tt>null</tt> and index is within the pending
* selections range, the selectionchange event will be called, too.
* Additionally, the method will shift all selections and trigger the
* selectiondirty event if any selections are pending.
*
*/
onRemove : function (v, index, r) {
var ranges = this.getPendingSelections();
var rangesLength = ranges.length;
var selectionChanged = false;
// if index equals to Number.MIN_VALUE or Number.MAX_VALUE, mark current
// pending selections as dirty
if (index == Number.MIN_VALUE || index == Number.MAX_VALUE) {
if (r) {
// if the record is part of the current selection, shift the
// selection down by 1
// if the index equals to Number.MIN_VALUE
if (this.isIdSelected(r.id) && index == Number.MIN_VALUE) {
// bufferRange already counted down when this method gets
// called
this.shiftSelections(this.grid.store.bufferRange[1], -1);
}
this.selections.remove(r);
selectionChanged = true;
}
// clear all pending selections that are behind the first
// bufferrange, and shift all pending Selections that lay in front
// front of the second bufferRange down by 1!
if (index == Number.MIN_VALUE) {
this.clearPendingSelections(0, this.grid.store.bufferRange[0]);
} else {
// clear pending selections that are in front of bufferRange[1]
this.clearPendingSelections(this.grid.store.bufferRange[1]);
}
// only fire the selectiondirty event if there were pendning ranges
if (rangesLength !== 0) {
this.fireEvent('selectiondirty', this, index, 1);
}
} else {
selectionChanged = this.isIdSelected(r.id);
// if the record was not part of the selection, return
if (!selectionChanged) {
return;
}
this.selections.remove(r);
// this.last = false;
// if there are currently pending selections, look up the interval
// to tell whether removing the record would mark the selection
// dirty
if (rangesLength !== 0) {
var startRange = ranges[0];
var endRange = ranges[rangesLength - 1];
if (index <= endRange || index <= startRange) {
this.shiftSelections(index, -1);
this.fireEvent('selectiondirty', this, index, 1);
}
}
}
if (selectionChanged) {
this.fireEvent('selectionchange', this);
}
},
/**
* If records where added to the store, this method will work as a callback,
* called by the views' rowsinserted event. Selections will be shifted down
* if, and only if, the listeners for the selectiondirty event will return
* <tt>true</tt>.
*
*/
onAdd : function (store, index, endIndex, recordLength) {
var ranges = this.getPendingSelections();
var rangesLength = ranges.length;
// if index equals to Number.MIN_VALUE or Number.MAX_VALUE, mark current
// pending selections as dirty
if ((index == Number.MIN_VALUE || index == Number.MAX_VALUE)) {
if (index == Number.MIN_VALUE) {
// bufferRange already counted down when this method gets
// called
this.clearPendingSelections(0, this.grid.store.bufferRange[0]);
this.shiftSelections(this.grid.store.bufferRange[1], recordLength);
} else {
this.clearPendingSelections(this.grid.store.bufferRange[1]);
}
// only fire the selectiondirty event if there were pendning ranges
if (rangesLength !== 0) {
this.fireEvent('selectiondirty', this, index, r);
}
return;
}
// it is safe to say that the selection is dirty when the inserted index
// is less or equal to the first selection range index or less or equal
// to the last selection range index
var startRange = ranges[0];
var endRange = ranges[rangesLength - 1];
var viewIndex = index;
if (viewIndex <= endRange || viewIndex <= startRange) {
this.fireEvent('selectiondirty', this, viewIndex, recordLength);
this.shiftSelections(viewIndex, recordLength);
}
},
/**
* Shifts current/pending selections. This method can be used when rows
* where inserted/removed and the selection model has to synchronize itself.
*/
shiftSelections : function (startRow, length) {
var index = 0;
var newIndex = 0;
var newRequests = {};
var ds = this.grid.store;
var storeIndex = startRow - ds.bufferRange[0];
var newStoreIndex = 0;
var totalLength = this.grid.store.totalLength;
var rec = null;
// this.last = false;
var ranges = this.getPendingSelections();
var rangesLength = ranges.length;
if (rangesLength === 0) {
return;
}
for (var i = 0; i < rangesLength; i++) {
index = ranges[i];
if (index < startRow) {
continue;
}
newIndex = index + length;
newStoreIndex = storeIndex + length;
if (newIndex >= totalLength) {
break;
}
rec = ds.getAt(newStoreIndex);
if (rec) {
this.selections.add(rec);
} else {
newRequests[newIndex] = true;
}
//DA : Ajout de l'objet allSelections
this.allSelections[newIndex] = true;
}
this.pendingSelections = newRequests;
},
/**
*
* @param {Array}
* records The records that have been loaded
* @param {Array}
* ranges An array representing the model index ranges the reords
* have been loaded for.
*/
onSelectionsLoad : function (store, records, ranges) {
this.replaceSelections(records);
},
/**
* Returns true if there is a next record to select
*
* @return {Boolean}
*/
hasNext : function () {
return this.last !== false && (this.last + 1) < this.grid.store.getTotalCount();
},
/**
* Gets the number of selected rows.
*
* @return {Number}
*/
getCount : function () {
return this.selections.length + this.getPendingSelections().length;
},
/**
* Returns True if the specified row is selected.
*
* @param {Number/Record}
* record The record or index of the record to check
* @return {Boolean}
*/
isSelected : function (index) {
if (typeof index == "number") {
var orgInd = index;
index = this.grid.store.getAt(orgInd);
if (!index) {
var ind = this.getPendingSelections().indexOf(orgInd);
if (ind != -1) {
return true;
}
return false;
}
}
var r = index;
return (r && this.selections.key(r.id) ? true : false);
},
/**
* Deselects a record. The emthod assumes that the record is physically
* available, i.e. pendingSelections will not be taken into account
*/
deselectRecord : function (record, preventViewNotify) {
if (this.locked) {
return;
}
var isSelected = this.selections.key(record.id);
if (!isSelected) {
return;
}
var store = this.grid.store;
var index = store.indexOfId(record.id);
if (index == -1) {
index = store.findInsertIndex(record);
if (index != Number.MIN_VALUE && index != Number.MAX_VALUE) {
index += store.bufferRange[0];
}
} else {
// just to make sure, though this should not be
// set if the record was availablein the selections
delete this.pendingSelections[index];
}
if (this.last == index) {
this.last = false;
}
if (this.lastActive == index) {
this.lastActive = false;
}
//DA : suppression de l'item ds allSelections
delete this.allSelections[index];
this.selections.remove(record);
if (!preventViewNotify) {
this.grid.getView().onRowDeselect(index);
}
this.fireEvent("rowdeselect", this, index, record);
this.fireEvent("selectionchange", this);
},
/**
* Deselects a row.
*
* @param {Number}
* row The index of the row to deselect
*/
deselectRow : function (index, preventViewNotify) {
if (this.locked) {
return;
}
if (this.last == index) {
this.last = false;
}
if (this.lastActive == index) {
this.lastActive = false;
}
var r = this.grid.store.getAt(index);
//DA : gestion de l'objet allSelections
delete this.allSelections[index];
delete this.pendingSelections[index];
if (r) {
this.selections.remove(r);
}
if (!preventViewNotify) {
this.grid.getView().onRowDeselect(index);
}
this.fireEvent("rowdeselect", this, index, r);
this.fireEvent("selectionchange", this);
},
/**
* Selects a row.
*
* @param {Number}
* row The index of the row to select
* @param {Boolean}
* keepExisting (optional) True to keep existing selections
*/
selectRow : function (index, keepExisting, preventViewNotify) {
if (// this.last === index
// ||
this.locked || index < 0 || index >= this.grid.store.getTotalCount()) {
return;
}
var r = this.grid.store.getAt(index);
if (this.fireEvent("beforerowselect", this, index, keepExisting, r) !== false) {
if (!keepExisting || this.singleSelect) {
this.clearSelections();
}
if (r) {
this.selections.add(r);
delete this.pendingSelections[index];
} else {
this.pendingSelections[index] = true;
}
//DA : gestion de l'objet allSelections
this.allSelections[index] = true;
this.last = this.lastActive = index;
if (!preventViewNotify) {
this.grid.getView().onRowSelect(index);
}
this.fireEvent("rowselect", this, index, r);
this.fireEvent("selectionchange", this);
}
},
clearPendingSelections : function (startIndex, endIndex) {
if (endIndex === undefined) {
endIndex = Number.MAX_VALUE;
}
var newSelections = {};
var ranges = this.getPendingSelections();
var rangesLength = ranges.length;
var index = 0;
for (var i = 0; i < rangesLength; i++) {
index = ranges[i];
if (index <= endIndex && index >= startIndex) {
continue;
}
newSelections[index] = true;
}
this.pendingSelections = newSelections;
},
/**
* Replaces already set data with new data from the store if those records
* can be found within this.selections or this.pendingSelections
*
* @param {Array}
* An array with records buffered by the store
*/
replaceSelections : function (records) {
if (!records || records.length === 0) {
return;
}
var ds = this.grid.store;
var rec = null;
var assigned = [];
var ranges = this.getPendingSelections();
var rangesLength = ranges.length;
var selections = this.selections;
var index = 0;
for (var i = 0; i < rangesLength; i++) {
index = ranges[i];
rec = ds.getAt(index);
if (rec) {
selections.add(rec);
assigned.push(rec.id);
delete this.pendingSelections[index];
}
}
var id = null;
var len = null;
for (i = 0, len = records.length; i < len; i++) {
rec = records[i];
id = rec.id;
if (assigned.indexOf(id) == -1 && selections.containsKey(id)) {
selections.add(rec);
}
}
},
getPendingSelections : function (asRange) {
var index = 1;
var ranges = [];
var currentRange = 0;
var tmpArray = [];
for (var i in this.pendingSelections) {
tmpArray.push(parseInt(i));
}
tmpArray.sort(function (o1, o2) {
if (o1 > o2) {
return 1;
} else if (o1 < o2) {
return -1;
} else {
return 0;
}
});
if (!asRange) {
return tmpArray;
}
var max_i = tmpArray.length;
if (max_i === 0) {
return [];
}
ranges[currentRange] = [ tmpArray[0], tmpArray[0] ];
for (var i = 0, max_i = max_i - 1; i < max_i; i++) {
if (tmpArray[i + 1] - tmpArray[i] == 1) {
ranges[currentRange][1] = tmpArray[i + 1];
} else {
currentRange++;
ranges[currentRange] = [ tmpArray[i + 1], tmpArray[i + 1] ];
}
}
return ranges;
},
getAllSelections : function (asRange) {
var index = 1;
var ranges = [];
var currentRange = 0;
var tmpArray = [];
for (var i in this.allSelections) {
tmpArray.push(parseInt(i));
}
tmpArray.sort(function (o1, o2) {
if (o1 > o2) {
return 1;
} else if (o1 < o2) {
return -1;
} else {
return 0;
}
});
if (!asRange) {
return tmpArray;
}
var max_i = tmpArray.length;
if (max_i === 0) {
return [];
}
ranges[currentRange] = [ tmpArray[0], tmpArray[0] ];
for (var i = 0, max_i = max_i - 1; i < max_i; i++) {
if (tmpArray[i + 1] - tmpArray[i] == 1) {
ranges[currentRange][1] = tmpArray[i + 1];
} else {
currentRange++;
ranges[currentRange] = [ tmpArray[i + 1], tmpArray[i + 1] ];
}
}
return ranges;
},
/**
* Clears all selections.
*/
clearSelections : function (fast) {
if (this.locked) {
return;
}
if (fast !== true) {
var ds = this.grid.store;
var s = this.selections;
var ind = -1;
s.each(function (r) {
ind = ds.indexOfId(r.id);
if (ind != -1) {
this.deselectRow(ind + ds.bufferRange[0]);
}
}, this);
s.clear();
this.pendingSelections = {};
} else {
this.selections.clear();
this.pendingSelections = {};
}
this.allSelections = {};
this.last = false;
},
/**
* Selects a range of rows. All rows in between startRow and endRow are also
* selected.
*
* @param {Number}
* startRow The index of the first row in the range
* @param {Number}
* endRow The index of the last row in the range
* @param {Boolean}
* keepExisting (optional) True to retain existing selections
*/
selectRange : function (startRow, endRow, keepExisting) {
if (this.locked) {
return;
}
if (!keepExisting) {
this.clearSelections();
}
if (startRow <= endRow) {
for (var i = startRow; i <= endRow; i++) {
this.selectRow(i, true);
}
} else {
for (var i = startRow; i >= endRow; i--) {
this.selectRow(i, true);
}
}
}
});
/**
* Ext.ux.grid.livegrid.Store Copyright (c) 2007-2008, http://www.siteartwork.de
*
* Ext.ux.grid.livegrid.Store is licensed under the terms of the GNU Open Source
* GPL 3.0 license.
*
* Commercial use is prohibited. Visit <http://www.siteartwork.de/livegrid> if
* you need to obtain a commercial license.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/gpl.html>.
*
*/
Ext.namespace('Ext.ux.grid.livegrid');
/**
* @class Ext.ux.grid.livegrid.Store
* @extends Ext.data.Store
*
* The BufferedGridSore is a special implementation of a Ext.data.Store. It is
* used for loading chunks of data from the underlying data repository as
* requested by the Ext.ux.BufferedGridView. It's size is limited to the config
* parameter bufferSize and is thereby guaranteed to never hold more than this
* amount of records in the store.
*
* Requesting selection ranges: ---------------------------- This store
* implementation has 2 Http-proxies: A data proxy for requesting data from the
* server for displaying and another proxy to request pending selections:
* Pending selections are represented by row indexes which have been selected
* but which records have not yet been available in the store. The
* loadSelections method will initiate a request to the data repository (same
* url as specified in the url config parameter for the store) to fetch the
* pending selections. The additional parameter send to the server is the
* "ranges" parameter, which will hold a json encoded string representing ranges
* of row indexes to load from the data repository. As an example, pending
* selections with the indexes 1,2,3,4,5,9,10,11,16 would have to be translated
* to [1,5],[9,11],[16]. Please note, that by indexes we do not understand
* (primary) keys of the data, but indexes as represented by the view. To get
* the ranges of pending selections, you can use the getPendingSelections method
* of the BufferedRowSelectionModel, which should be used as the default
* selection model of the grid.
*
* Version-property: ----------------- This implementation does also introduce a
* new member called "version". The version property will help you in
* determining if any pending selections indexes are still valid or may have
* changed. This is needed to reduce the danger of data inconsitence when you
* are requesting data from the server: As an example, a range of indexes must
* be read from the server but may have been become invalid when the row
* represented by the index is no longer available in teh underlying data store,
* caused by a delete or insert operation. Thus, you have to take care of the
* version property by yourself (server side) and change this value whenever a
* row was deleted or inserted. You can specify the path to the version property
* in the BufferedJsonReader, which should be used as the default reader for
* this store. If the store recognizes a version change, it will fire the
* versionchange event. It is up to the user to remove all selections which are
* pending, or use them anyway.
*
* Inserting data: --------------- Another thing to notice is the way a user
* inserts records into the data store. A user should always provide a sortInfo
* for the grid, so the findInsertIndex method can return a value that comes
* close to the value as it would have been computed by the underlying store's
* sort algorithm. Whenever a record should be added to the store, the insert
* index should be calculated and the used as the parameter for the insert
* method. The findInsertIndex method will return a value that equals to
* Number.MIN_VALUE or Number.MAX_VALUE if the added record would not change the
* current state of the store. If that happens, this data is not available in
* the store, and may be requested later on when a new request for new data is
* made.
*
* Sorting: -------- remoteSort will always be set to true, no matter what value
* the user provides using the config object.
*
* @constructor Creates a new Store.
* @param {Object}
* config A config object containing the objects needed for the Store
* to access data, and read the data into Records.
*
* @author Thorsten Suckow-Homberg <ts@siteartwork.de>
*/
Ext.ux.grid.livegrid.Store = function (config) {
config = config || {};
// remoteSort will always be set to true.
config.remoteSort = true;
// we will intercept the autoLoad property and set it to false so we do not
// load any contents of the store before the View has not fully initialized
// itself. if autoLoad was set to true, the Ext.ux.grid.livegrid.GridPanel
// will take care of loading the store once it has been rendered
this._autoLoad = config.autoLoad ? true : false;
config.autoLoad = false;
this.addEvents(
/**
* @event bulkremove Fires when a bulk remove operation was finished.
* @param {Ext.ux.BufferedGridStore}
* this
* @param {Array}
* An array with the records that have been removed. The values
* for each array index are record - the record that was removed
* index - the index of the removed record in the store
*/
'bulkremove',
/**
* @event versionchange Fires when the version property has changed.
* @param {Ext.ux.BufferedGridStore}
* this
* @param {String}
* oldValue
* @param {String}
* newValue
*/
'versionchange',
/**
* @event beforeselectionsload Fires before the store sends a request for
* ranges of records to the server.
* @param {Ext.ux.BufferedGridStore}
* this
* @param {Array}
* ranges
*/
'beforeselectionsload',
/**
* @event selectionsload Fires when selections have been loaded.
* @param {Ext.ux.BufferedGridStore}
* this
* @param {Array}
* records An array containing the loaded records from the
* server.
* @param {Array}
* ranges An array containing the ranges of indexes this records
* may represent.
*/
'selectionsload');
Ext.ux.grid.livegrid.Store.superclass.constructor.call(this, config);
this.totalLength = 0;
/**
* The array represents the range of rows available in the buffer absolute
* to the indexes of the data model. Initialized with [-1, -1] which tells
* that no records are currrently buffered
*
* @param {Array}
*/
this.bufferRange = [ -1, -1 ];
this.on('clear', function () {
this.bufferRange = [ -1, -1 ];
}, this);
if (this.url && !this.selectionsProxy) {
this.selectionsProxy = new Ext.data.HttpProxy({
url : this.url
});
}
};
Ext.extend(Ext.ux.grid.livegrid.Store, Ext.data.Store, {
/**
* The version of the data in the store. This value is represented by the
* versionProperty-property of the BufferedJsonReader.
*
* @property
*/
version : null,
/**
* Inserts a record at the position as specified in index. If the index
* equals to Number.MIN_VALUE or Number.MAX_VALUE, the record will not be
* added to the store, but still fire the add-event to indicate that the set
* of data in the underlying store has been changed. If the index equals to
* 0 and the length of data in the store equals to bufferSize, the add-event
* will be triggered with Number.MIN_VALUE to indicate that a record has
* been prepended. If the index equals to bufferSize, the method will assume
* that the record has been appended and trigger the add event with index
* set to Number.MAX_VALUE.
*
* Note: ----- The index parameter is not a view index, but a value in the
* range of [0, this.bufferSize].
*
* You are strongly advised to not use this method directly. Instead, call
* findInsertIndex wirst and use the return-value as the first parameter for
* for this method.
*/
insert : function (index, records) {
// hooray for haskell!
records = [].concat(records);
index = index >= this.bufferSize ? Number.MAX_VALUE : index;
if (index == Number.MIN_VALUE || index == Number.MAX_VALUE) {
var l = records.length;
if (index == Number.MIN_VALUE) {
this.bufferRange[0] += l;
this.bufferRange[1] += l;
}
this.totalLength += l;
this.fireEvent("add", this, records, index);
return;
}
var split = false;
var insertRecords = records;
if (records.length + index >= this.bufferSize) {
split = true;
insertRecords = records.splice(0, this.bufferSize - index);
}
this.totalLength += insertRecords.length;
// if the store was loaded without data and the bufferRange
// has to be filled first
if (this.bufferRange[0] <= -1) {
this.bufferRange[0] = 0;
}
if (this.bufferRange[1] < (this.bufferSize - 1)) {
this.bufferRange[1] = Math.min(this.bufferRange[1] + insertRecords.length, this.bufferSize - 1);
}
for (var i = 0, len = insertRecords.length; i < len; i++) {
this.data.insert(index, insertRecords[i]);
insertRecords[i].join(this);
}
while (this.getCount() > this.bufferSize) {
this.data.remove(this.data.last());
}
this.fireEvent("add", this, insertRecords, index);
if (split === true) {
this.fireEvent("add", this, records, Number.MAX_VALUE);
}
},
/**
* Remove a Record from the Store and fires the remove event.
*
* This implementation will check for the appearance of the record id in the
* store. The record to be removed does not neccesarily be bound to the
* instance of this store. If the record is not within the store, the method
* will try to guess it's index by calling findInsertIndex.
*
* Please note that this method assumes that the records that's about to be
* removed from the store does belong to the data within the store or the
* underlying data store, thus the remove event will always be fired. This
* may lead to inconsitency if you have to stores up at once. Let A be the
* store that reads from the data repository C, and B the other store that
* only represents a subset of data of the data repository C. If you now
* remove a record X from A, which has not been in the store, but is assumed
* to be available in the data repository, and would like to sync the
* available data of B, then you have to check first if X may have apperead
* in the subset of data C represented by B before calling remove from the B
* store (because the remove operation will always trigger the "remove"
* event, no matter what). (Common use case: you have selected a range of
* records which are then stored in the row selection model. User scrolls
* through the data and the store's buffer gets refreshed with new data for
* displaying. Now you want to remove all records which are within the
* rowselection model, but not anymore within the store.) One possible
* workaround is to only remove the record X from B if, and only if the
* return value of a call to [object instance of store B].data.indexOf(X)
* does not return a value less than 0. Though not removing the record from
* B may not update the view of an attached BufferedGridView immediately.
*
* @param {Ext.data.Record}
* record
* @param {Boolean}
* suspendEvent true to suspend the "remove"-event
*
* @return Number the index of the record removed.
*/
remove : function (record, suspendEvent) {
// check wether the record.id can be found in this store
var index = this._getIndex(record);
if (index < 0) {
this.totalLength -= 1;
if (this.pruneModifiedRecords) {
this.modified.remove(record);
}
// adjust the buffer range if a record was removed
// in the range that is actually behind the bufferRange
this.bufferRange[0] = Math.max(-1, this.bufferRange[0] - 1);
this.bufferRange[1] = Math.max(-1, this.bufferRange[1] - 1);
if (suspendEvent !== true) {
this.fireEvent("remove", this, record, index);
}
return index;
}
this.bufferRange[1] = Math.max(-1, this.bufferRange[1] - 1);
this.data.removeAt(index);
if (this.pruneModifiedRecords) {
this.modified.remove(record);
}
this.totalLength -= 1;
if (suspendEvent !== true) {
this.fireEvent("remove", this, record, index);
}
return index;
},
_getIndex : function (record) {
var index = this.indexOfId(record.id);
if (index < 0) {
index = this.findInsertIndex(record);
}
return index;
},
/**
* Removes a larger amount of records from the store and fires the
* "bulkremove" event. This helps listeners to determine whether the remove
* operation of multiple records is still pending.
*
* @param {Array}
* records
*/
bulkRemove : function (records) {
var rec = null;
var recs = [];
var ind = 0;
var len = records.length;
var orgIndexes = [];
for (var i = 0; i < len; i++) {
rec = records[i];
orgIndexes[rec.id] = this._getIndex(rec);
}
for (var i = 0; i < len; i++) {
rec = records[i];
this.remove(rec, true);
recs.push([ rec, orgIndexes[rec.id] ]);
}
this.fireEvent("bulkremove", this, recs);
},
/**
* Remove all Records from the Store and fires the clear event. The method
* assumes that there will be no data available anymore in the underlying
* data store.
*/
removeAll : function () {
this.totalLength = 0;
this.bufferRange = [ -1, -1 ];
this.data.clear();
if (this.pruneModifiedRecords) {
this.modified = [];
}
this.fireEvent("clear", this);
},
/**
* Requests a range of data from the underlying data store. Similiar to the
* start and limit parameter usually send to the server, the method needs an
* array of ranges of indexes. Example: To load all records at the positions
* 1,2,3,4,9,12,13,14, the supplied parameter should equal to
* [[1,4],[9],[12,14]]. The request will only be done if the
* beforeselectionsloaded events return value does not equal to false.
*/
loadRanges : function (ranges) {
var max_i = ranges.length;
if (max_i > 0 && !this.selectionsProxy.activeRequest[Ext.data.Api.actions.read] && this.fireEvent("beforeselectionsload", this, ranges) !== false) {
var lParams = this.lastOptions.params;
var params = {};
params.ranges = Ext.encode(ranges);
if (lParams) {
if (lParams.sort) {
params.sort = lParams.sort;
}
if (lParams.dir) {
params.dir = lParams.dir;
}
}
var options = {};
for (var i in this.lastOptions) {
options.i = this.lastOptions.i;
}
options.ranges = params.ranges;
this.selectionsProxy.doRequest(Ext.data.Api.actions.read, null, options, this.reader,
this.selectionsLoaded, this, options);
}
},
/**
* Alias for loadRanges.
*/
loadSelections : function (ranges) {
if (ranges.length === 0) {
return;
}
this.loadRanges(ranges);
},
/**
* Called as a callback by the proxy which loads pending selections. Will
* fire the selectionsload event with the loaded records if, and only if the
* return value of the checkVersionChange event does not equal to false.
*/
selectionsLoaded : function (o, options, success) {
if (this.checkVersionChange(o, options, success) !== false) {
var r = o.records;
for (var i = 0, len = r.length; i < len; i++) {
r[i].join(this);
}
this.fireEvent("selectionsload", this, o.records, Ext.decode(options.ranges));
} else {
this.fireEvent("selectionsload", this, [], Ext.decode(options.ranges));
}
},
/**
* Checks if the version supplied in <tt>o</tt> differs from the version
* property of the current instance of this object and fires the
* versionchange event if it does.
*/
// private
checkVersionChange : function (o, options, success) {
if (o && success !== false) {
if (o.version !== undefined) {
var old = this.version;
this.version = o.version;
if (this.version !== old) {
return this.fireEvent('versionchange', this, old, this.version);
}
}
}
},
/**
* The sort procedure tries to respect the current data in the buffer. If
* the found index would not be within the bufferRange, Number.MIN_VALUE is
* returned to indicate that the record would be sorted below the first
* record in the buffer range, while Number.MAX_VALUE would indicate that
* the record would be added after the last record in the buffer range.
*
* The method is not guaranteed to return the relative index of the record
* in the data model as returned by the underlying domain model.
*/
findInsertIndex : function (record) {
this.remoteSort = false;
var index = Ext.ux.grid.livegrid.Store.superclass.findInsertIndex.call(this, record);
this.remoteSort = true;
// special case... index is 0 and we are at the very first record
// buffered
if (this.bufferRange[0] <= 0 && index === 0) {
return index;
} else if (this.bufferRange[0] > 0 && index === 0) {
return Number.MIN_VALUE;
} else if (index >= this.bufferSize) {
return Number.MAX_VALUE;
}
return index;
},
/**
* Removed snapshot check
*/
// private
sortData : function (f, direction) {
direction = direction || 'ASC';
var st = this.fields.get(f).sortType;
var fn = function (r1, r2) {
var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
};
this.data.sort(direction, fn);
},
/**
* @cfg {Number} bufferSize The number of records that will at least always
* be available in the store for rendering. This value will be send to
* the server as the <tt>limit</tt> parameter and should not change
* during the lifetime of a grid component. Note: In a paging grid,
* this number would indicate the page size. The value should be set
* high enough to make a userfirendly scrolling possible and should be
* greater than the sum of {nearLimit} and {visibleRows}. Usually, a
* value in between 150 and 200 is good enough. A lesser value will
* more often make the store re-request new data, while a larger number
* will make loading times higher.
*/
// private
onMetaChange : function (meta, rtype, o) {
this.version = null;
Ext.ux.grid.livegrid.Store.superclass.onMetaChange.call(this, meta, rtype, o);
},
/**
* Will fire the versionchange event if the version of incoming data has
* changed.
*/
// private
loadRecords : function (o, options, success) {
this.checkVersionChange(o, options, success);
// we have to stay in sync with rows that may have been skipped while
// the request was loading.
// if the response didn't make it through, set buffer range to -1,-1
if (!o) {
this.bufferRange = [ -1, -1 ];
} else {
this.bufferRange = [ options.params.start,
Math.max(0, Math.min((options.params.start + options.params.limit) - 1, o.totalRecords - 1)) ];
}
if (options.suspendLoadEvent === true) {
this.suspendEvents();
}
Ext.ux.grid.livegrid.Store.superclass.loadRecords.call(this, o, options, success);
if (options.suspendLoadEvent === true) {
this.resumeEvents();
}
},
/**
* Get the Record at the specified index. The function will take the
* bufferRange into account and translate the passed argument to the index
* of the record in the current buffer.
*
* @param {Number}
* index The index of the Record to find.
* @return {Ext.data.Record} The Record at the passed index. Returns
* undefined if not found.
*/
getAt : function (index) {
// anything buffered yet?
if (this.bufferRange[0] == -1) {
return undefined;
}
var modelIndex = index - this.bufferRange[0];
return this.data.itemAt(modelIndex);
},
// --------------------------------------EMPTY-----------------------------------
// no interface concept, so simply overwrite and leave them empty as for now
clearFilter : function () {
},
isFiltered : function () {
},
collect : function () {
},
createFilterFn : function () {
},
sum : function () {
},
filter : function () {
},
filterBy : function () {
},
query : function () {
},
queryBy : function () {
},
find : function () {
},
findBy : function () {
}
});
/**
* Ext.ux.grid.livegrid.Toolbar Copyright (c) 2007-2008,
* http://www.siteartwork.de
*
* Ext.ux.grid.livegrid.Toolbar is licensed under the terms of the GNU Open
* Source GPL 3.0 license.
*
* Commercial use is prohibited. Visit <http://www.siteartwork.de/livegrid> if
* you need to obtain a commercial license.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/gpl.html>.
*
*/
Ext.namespace('Ext.ux.grid.livegrid');
/**
* toolbar that is bound to a {@link Ext.ux.grid.livegrid.GridView} and provides
* information about the indexes of the requested data and the buffer state.
*
* @class Ext.ux.grid.livegrid.Toolbar
* @extends Ext.Toolbar
* @constructor
* @param {Object}
* config
*
* @author Thorsten Suckow-Homberg <ts@siteartwork.de>
*/
Ext.ux.grid.livegrid.Toolbar = Ext.extend(Ext.Toolbar, {
/**
* @cfg {Ext.grid.GridPanel} grid The grid the toolbar is bound to. If
* ommited, use the cfg property "view"
*/
/**
* @cfg {Ext.grid.GridView} view The view the toolbar is bound to The grid
* the toolbar is bound to. If ommited, use the cfg property "grid"
*/
/**
* @cfg {Boolean} displayInfo True to display the displayMsg (defaults to
* false)
*/
/**
* @cfg {String} displayMsg The paging status message to display (defaults
* to "Displaying {start} - {end} of {total}")
*/
displayMsg : "",
/**
* @cfg {String} emptyMsg The message to display when no records are found
* (defaults to "No data to display")
*/
emptyMsg : 'No data to display',
/**
* Value to display as the tooltip text for the refresh button. Defaults to
* "Refresh"
*
* @param {String}
*/
refreshText : "Refresh",
initComponent : function () {
this.displayMsg = i18n.get('paging.display');
Ext.ux.grid.livegrid.Toolbar.superclass.initComponent.call(this);
if (this.grid) {
this.view = this.grid.getView();
}
var me = this;
this.view.init = this.view.init.createSequence(function () {
me.bind(this);
}, this.view);
},
// private
updateInfo : function (rowIndex, visibleRows, totalCount) {
if (this.displayEl) {
var msg = totalCount === 0 ? this.emptyMsg : String.format(this.displayMsg, rowIndex + 1, Math.min(rowIndex + 1 + visibleRows, totalCount), totalCount);
this.displayEl.update(msg);
}
},
/**
* Unbinds the toolbar.
*
* @param {Ext.grid.GridView|Ext.gid.GridPanel}
* view Either The view to unbind or the grid
*/
unbind : function (view) {
var st;
var vw;
if (view instanceof Ext.grid.GridView) {
vw = view;
} else {
// assuming parameter is of type Ext.grid.GridPanel
vw = view.getView();
}
st = view.ds;
st.un('loadexception', this.enableLoading, this);
st.un('beforeload', this.disableLoading, this);
st.un('load', this.enableLoading, this);
vw.un('rowremoved', this.onRowRemoved, this);
vw.un('rowsinserted', this.onRowsInserted, this);
vw.un('beforebuffer', this.beforeBuffer, this);
vw.un('cursormove', this.onCursorMove, this);
vw.un('buffer', this.onBuffer, this);
vw.un('bufferfailure', this.enableLoading, this);
this.view = undefined;
},
/**
* Binds the toolbar to the specified {@link Ext.ux.grid.Livegrid}
*
* @param {Ext.grird.GridView}
* view The view to bind
*/
bind : function (view) {
this.view = view;
var st = view.ds;
st.on('loadexception', this.enableLoading, this);
st.on('beforeload', this.disableLoading, this);
st.on('load', this.enableLoading, this);
view.on('rowremoved', this.onRowRemoved, this);
view.on('rowsinserted', this.onRowsInserted, this);
view.on('beforebuffer', this.beforeBuffer, this);
view.on('cursormove', this.onCursorMove, this);
view.on('buffer', this.onBuffer, this);
view.on('bufferfailure', this.enableLoading, this);
},
// ----------------------------------- Listeners
// -------------------------------
enableLoading : function () {
this.loading.setDisabled(false);
},
disableLoading : function () {
this.loading.setDisabled(true);
},
onCursorMove : function (view, rowIndex, visibleRows, totalCount) {
this.updateInfo(rowIndex, visibleRows, totalCount);
},
// private
onRowsInserted : function (view, start, end) {
this.updateInfo(view.rowIndex, Math.min(view.ds.totalLength, view.visibleRows - view.rowClipped),
view.ds.totalLength);
},
// private
onRowRemoved : function (view, index, record) {
this.updateInfo(view.rowIndex, Math.min(view.ds.totalLength, view.visibleRows - view.rowClipped),
view.ds.totalLength);
},
// private
beforeBuffer : function (view, store, rowIndex, visibleRows, totalCount, options) {
this.loading.disable();
this.updateInfo(rowIndex, visibleRows, totalCount);
},
// private
onBuffer : function (view, store, rowIndex, visibleRows, totalCount) {
this.loading.enable();
this.updateInfo(rowIndex, visibleRows, totalCount);
//plot refresh when data is buffered
var plotComp = Ext.getCmp("plot" + this.ownerCt.datasetId);
if (plotComp) {
var rightPanel = plotComp.findById('plot-right-panel');
var success = rightPanel.fireEvent('buffer', store, rowIndex, visibleRows, totalCount);
}
},
// private
onClick : function (type) {
switch (type) {
case 'refresh':
if (this.view.reset(true)) {
this.loading.disable();
} else {
this.loading.enable();
}
break;
}
},
// private
onRender : function (ct, position) {
Ext.PagingToolbar.superclass.onRender.call(this, ct, position);
this.loading = new Ext.Toolbar.Button({
tooltip : this.refreshText,
iconCls : "x-tbar-loading",
handler : this.onClick.createDelegate(this, [ "refresh" ])
});
this.addButton(this.loading);
this.addSeparator();
if (this.displayInfo) {
this.displayEl = Ext.fly(this.el.dom).createChild({
cls : 'x-paging-info'
});
}
}
});
/**
* Ext.ux.grid.livegrid.DragZone Copyright (c) 2007-2008,
* http://www.siteartwork.de
*
* Ext.ux.grid.livegrid.DragZone is licensed under the terms of the GNU Open
* Source GPL 3.0 license.
*
* Commercial use is prohibited. Visit <http://www.siteartwork.de/livegrid> if
* you need to obtain a commercial license.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/gpl.html>.
*
*/
Ext.namespace('Ext.ux.grid.livegrid');
/**
* @class Ext.ux.grid.livegrid.DragZone
* @extends Ext.dd.DragZone
* @author Thorsten Suckow-Homberg <ts@siteartwork.de>
*/
Ext.ux.grid.livegrid.DragZone = function (grid, config) {
Ext.ux.grid.livegrid.DragZone.superclass.constructor.call(this, grid, config);
this.view.ds.on('beforeselectionsload', this._onBeforeSelectionsLoad, this);
this.view.ds.on('selectionsload', this._onSelectionsLoad, this);
};
Ext.extend(Ext.ux.grid.livegrid.DragZone, Ext.grid.GridDragZone, {
/**
* Tells whether a drop is valid. Used inetrnally to determine if pending
* selections need to be loaded/ have been loaded.
*
* @type {Boolean}
*/
isDropValid : true,
/**
* Overriden for loading pending selections if needed.
*/
onInitDrag : function (e) {
this.view.ds.loadSelections(this.grid.selModel.getPendingSelections(true));
Ext.ux.grid.livegrid.DragZone.superclass.onInitDrag.call(this, e);
},
/**
* Gets called before pending selections are loaded. Any drop operations are
* invalid/get paused if the component needs to wait for selections to load
* from the server.
*
*/
_onBeforeSelectionsLoad : function () {
this.isDropValid = false;
Ext.fly(this.proxy.el.dom.firstChild).addClass('ext-ux-livegrid-drop-waiting');
},
/**
* Gets called after pending selections have been loaded. Any paused drop
* operation will be resumed.
*
*/
_onSelectionsLoad : function () {
this.isDropValid = true;
this.ddel.innerHTML = this.grid.getDragDropText();
Ext.fly(this.proxy.el.dom.firstChild).removeClass('ext-ux-livegrid-drop-waiting');
}
});
/**
* Ext.ux.grid.livegrid.EditorGridPanel Copyright (c) 2007-2008,
* http://www.siteartwork.de
*
* Ext.ux.grid.livegrid.EditorGridPanel is licensed under the terms of the GNU
* Open Source GPL 3.0 license.
*
* Commercial use is prohibited. Visit <http://www.siteartwork.de/livegrid> if
* you need to obtain a commercial license.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/gpl.html>.
*
*/
Ext.namespace('Ext.ux.grid.livegrid');
/**
* @class Ext.ux.grid.livegrid.EditorGridPanel
* @extends Ext.grid.EditorGridPanel
* @constructor
* @param {Object}
* config
*
* @author Thorsten Suckow-Homberg <ts@siteartwork.de>
*/
Ext.ux.grid.livegrid.EditorGridPanel = Ext.extend(Ext.grid.EditorGridPanel, {
/**
* Overriden so the panel listens to the "cursormove" event for cancelling
* any edit that is in progress.
*
* @private
*/
initEvents : function () {
Ext.ux.grid.livegrid.EditorGridPanel.superclass.initEvents.call(this);
this.view.on("cursormove", this.stopEditing, this, [ true ]);
},
/**
* Starts editing the specified for the specified row/column Will be
* cancelled if the requested row index to edit is not represented by data
* due to out of range regarding the view's store buffer.
*
* @param {Number}
* rowIndex
* @param {Number}
* colIndex
*/
startEditing : function (row, col) {
this.stopEditing();
if (this.colModel.isCellEditable(col, row)) {
this.view.ensureVisible(row, col, true);
if (!this.store.getAt(row)) {
return;
}
}
return Ext.ux.grid.livegrid.EditorGridPanel.superclass.startEditing.call(this, row, col);
},
// Since we do not have multiple inheritance, we need to override the
// same methods in this class we have overriden for
// Ext.ux.grid.livegrid.GridPanel
walkCells : function (row, col, step, fn, scope) {
return Ext.ux.grid.livegrid.GridPanel.prototype.walkCells.call(this, row, col, step, fn, scope);
},
onRender : function (ct, position) {
return Ext.ux.grid.livegrid.GridPanel.prototype.onRender.call(this, ct, position);
},
initComponent : function () {
if (this.cls) {
this.cls += ' ext-ux-livegrid';
} else {
this.cls = 'ext-ux-livegrid';
}
return Ext.ux.grid.livegrid.EditorGridPanel.superclass.initComponent.call(this);
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, i18n, extColModelToStorage, projectId, userStorage, window,
extColModelToSrv, userLogin, alertFailure, DEFAULT_LIVEGRID_BUFFER_SIZE, projectGlobal, SitoolsDesk, DEFAULT_ORDER_FOLDER, DEFAULT_PREFERENCES_FOLDER, getColumnModel */
/*
* @include "../../../env.js"
* @include "Ext.ux.livegrid/Ext.ux.livegrid-all-debug.js"
* @include "../../../def.js"
*/
Ext.namespace('sitools.user.component.dataviews.livegrid');
// Surcharge de l'objet Store de la liveGrid pour gestion du multiSort.
Ext.override(Ext.ux.grid.livegrid.Store, {
/**
* Sort by multiple fields in the specified order.
*
* @param {Array}
* An Array of field sort specifications, or, if ascending sort
* is required on all columns, an Array of field names. A field
* specification looks like:
*
* <pre><code>
* {
* ordersList : [ {
* field : firstname,
* direction : ASC
* }, {
* field : name
* direction : DESC
* } ]
* }
*
* </code>
*
*/
multiSort : function (sorters, direction) {
this.hasMultiSort = true;
direction = direction || "ASC";
if (this.multiSortInfo && direction == this.multiSortInfo.direction) {
direction = direction.toggle("ASC", "DESC");
}
this.multiSortInfo = {
sorters : sorters,
direction : direction
};
if (this.remoteSort) {
// this.singleSort(sorters[0].field, sorters[0].direction);
this.load(this.lastOptions);
} else {
this.applySort();
this.fireEvent('datachanged', this);
}
},
getSortState : function () {
return this.hasMultiSort ? this.multiSortInfo : this.sortInfo;
},
// application du tri multiple sur le store
load : function (options) {
options = Ext.apply({}, options);
this.storeOptions(options);
if ((this.sortInfo || this.multiSortInfo) && this.remoteSort) {
var pn = this.paramNames;
options.params = Ext.apply({}, options.params);
this.isInSort = true;
var root = pn.sort;
if (this.hasMultiSort) {
options.params[pn.sort] = Ext.encode({
"ordersList" : this.multiSortInfo.sorters
});
} else {
options.params[pn.sort] = Ext.encode({
"ordersList" : [ this.sortInfo ]
});
}
}
try {
return this.execute('read', null, options);
} catch (e) {
this.handleException(e);
return false;
}
}
});
/**
* @class sitools.user.component.dataviews.livegrid.StoreLiveGrid
* @extends Ext.ux.grid.livegrid.Store
* @cfg [] datasetCm The Dataset columnModel,
* @cfg {string} urlRecords The url to request the API
* @cfg {string} sitoolsAttachementForUsers the dataset Attachement
* @cfg {} userPreference Object containing all userPreference for this dataset
* @cfg {numeric} bufferSize the buffer Size of the store
* @cfg [] formParams an array of all formParams to apply to the store
* @cfg [] formMultiDsParams an array of all formParams to apply to the store
* @cfg {} mainView the View of the grid
* @cfg {string} datasetId the DatasetId
* @requires Ext.ux.grid.livegrid.JsonReader
* @requires sql2ext
* @return {Boolean}
*/
sitools.user.component.dataviews.livegrid.StoreLiveGrid = function (config) {
this.storeUtils = sitools.user.component.dataviews.storeUtils;
if (Ext.isEmpty(config)) {
return false;
}
/**
* Construction of the column Model : user preferences have priority on the
* initial definition of the model column in the dataset
*/
var colModel;
if (!Ext.isEmpty(config.userPreference) && config.userPreference.datasetView == "Ext.ux.livegrid" && !Ext.isEmpty(config.userPreference.colModel)) {
colModel = Ext.applyIf(config.userPreference.colModel, config.datasetCm);
}
else {
colModel = config.datasetCm;
}
var cm = getColumnModel(colModel);
/**
* the fields of the store
*/
var map = this.storeUtils.getFields(config.datasetCm);
var primaryKey = this.storeUtils.getPrimaryKey(config.datasetCm);
/*
* JSON Reader : BufferedJsonReader derives from Ext.data.JsonReader and
* allows to pass a version value representing the current state of the
* underlying data repository. Version handling on server side is totally up
* to the user. The version property should change whenever a record gets
* added or deleted on the server side, so the store can be notified of
* changes between the previous and current request. If the store notices a
* version change, it will fire the version change event. Speaking of data
* integrity: If there are any selections pending, the user can react to
* this event and cancel all pending selections.
*/
var bufferedReaderSimple = new Ext.ux.grid.livegrid.JsonReader({
idProperty : primaryKey,
root : 'data',
versionProperty : 'version',
totalProperty : 'total'
}, map);
/*
* Building the params used to request the data :
*/
var params;
// sending the columnModel to the server
if (this.userPreference) {
colModel = extColModelToSrv(cm);
params = {
colModel : Ext.util.JSON.encode(colModel)
};
} else {
params = {};
}
var i = 0;
// sending the formParams to the server
this.formParams = {};
if (!Ext.isEmpty(config.formParams)) {
Ext.each(config.formParams, function (param) {
this.formParams["p[" + i + "]"] = param;
i += 1;
}, this);
Ext.apply(params, this.formParams);
}
// sending the formParams to the server
i = 0;
if (!Ext.isEmpty(config.formMultiDsParams)) {
Ext.each(config.formMultiDsParams, function (param) {
this.formParams["c[" + i + "]"] = param;
i += 1;
}, this);
Ext.apply(params, this.formParams);
}
Ext.apply(config, {
autoLoad : true,
bufferSize : DEFAULT_LIVEGRID_BUFFER_SIZE,
restful : true,
reader : bufferedReaderSimple,
storeUtils : sitools.user.component.dataviews.storeUtils,
url : config.urlRecords,
dataUrl : config.sitoolsAttachementForUsers,
baseParams : params,
listeners : {
scope : this,
exception : function (dp, type, action, options, response, arg) {
// load the alert & close the window.
this.removeAll();
Ext.Msg.show({
title : i18n.get('label.error'),
msg : response.responseText,
buttons : Ext.Msg.OK,
width : 400
});
this.fireEvent("load", this, []);
}
}
});
sitools.user.component.dataviews.livegrid.StoreLiveGrid.superclass.constructor.call(this, config);
};
Ext.extend(sitools.user.component.dataviews.livegrid.StoreLiveGrid, Ext.ux.grid.livegrid.Store, {
getFormParams : function () {
return this.storeUtils.getFormParams();
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, SITOOLS_DATE_FORMAT, SITOOLS_DEFAULT_IHM_DATE_FORMAT, document, showResponse, alertFailure, LOCALE, ImageChooser, loadUrl*/
Ext.namespace('sitools.admin.datasets.datasourceUtils');
/**
* @class sitools.admin.datasets.DatasourceFactory
*/
//sitools.component.datasets.abstractDatasetWin = {
sitools.admin.datasets.datasourceUtils.DatasourceFactory = function (datasourceType, scope) {
if (datasourceType.jdbc) {
return new sitools.admin.datasets.datasourceUtils.jdbcUtils({
scope : scope
});
}
if (datasourceType.mongoDb) {
return new sitools.admin.datasets.datasourceUtils.mongoDbUtils({
scope : scope
});
}
};/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, SITOOLS_DATE_FORMAT, SITOOLS_DEFAULT_IHM_DATE_FORMAT, document, showResponse, alertFailure, LOCALE, ImageChooser, loadUrl*/
Ext.namespace('sitools.admin.datasets.datasourceUtils');
/**
* @class sitools.admin.datasets.DatasourceFactory
*/
//sitools.component.datasets.abstractDatasetWin = {
sitools.admin.datasets.datasourceUtils.jdbcUtils = Ext.extend(Ext.util.Observable, {
isJdbc : true,
isMongoDb : false,
constructor : function (config) {
Ext.apply(this, config.scope);
sitools.admin.datasets.datasourceUtils.jdbcUtils.superclass.constructor.call(this);
},
logInfo : function () {
console.log('jdbc');
},
/**
* Get the url of the datasource
* @return {string}
*/
getDataSourceUrl : function () {
var record = this.formulairePrincipal.getDataSourceCombo().getStore().getById(this.formulairePrincipal.getDataSourceCombo().getValue());
if (!record) {
return false;
}
return record.data.sitoolsAttachementForUsers;
},
getFieldsBDDSelected : function (grid) {
return grid.getSelectionModel().getSelections();
},
createGridFieldsBDD : function () {
/**
* The proxy used to get the description of a JDBC table
* @type Ext.data.HttpProxy
*/
var httpProxyFields = new Ext.data.HttpProxy({
url : "/",
restful : true,
method : 'GET'
});
var storeFields = new Ext.data.JsonStore({
proxy : httpProxyFields,
datasourceUtils : this,
root : "table.attributes",
autoLoad : false,
fields : [ {
name : 'name'
}, {
name : 'tableName'
}, {
name : 'schemaName'
}, {
name : 'structure'
}, {
name : 'nomAffiche'
}, {
name : 'sqlColumnType',
mapping : 'type'
}, {
name : 'javaSqlColumnType',
mapping : 'javaSqlType'
}, {
name : 'columnClass'
}],
listeners : {
scope : this,
beforeload : function (store) {
var dataSourceUrl = this.datasourceUtils.getDataSourceUrl();
if (!this.dataSourceUrl) {
return false;
}
this.proxy.setUrl(dataSourceUrl);
},
add : function (store, records) {
Ext.each(records, function (record) {
record.data.structure = {
tableName : record.data.tableName,
tableAlias : record.data.tableAlias,
schemaName : record.data.schemaName,
dataIndex : record.data.dataIndex
};
var tmp = record.data.tableAlias ? record.data.tableAlias : record.data.tableName;
tmp += "." + record.data.dataIndex;
record.data.nomAffiche = tmp;
});
}
}
});
var cmFields = new Ext.grid.ColumnModel({
columns : [ {
id : 'tableName',
header : i18n.get('headers.tableName'),
sortable : true,
dataIndex : 'tableName'
}, {
id : 'name',
header : i18n.get('headers.name'),
sortable : true,
dataIndex : 'dataIndex'
} ]
});
/**
* The grid used to display the columns of selected tables
* @type Ext.grid.GridPanel
*/
return new Ext.grid.GridPanel({
layout : 'fit',
store : storeFields,
cm : cmFields,
enableDragDrop : true,
stripeRows : true,
title : 'Columns Table'
});
},
createGridTablesBDD : function () {
/**
* Proxy used to request a datasource
* @type Ext.data.HttpProxy
*/
var httpProxyJDBC = new Ext.data.HttpProxy({
url : loadUrl.get('APP_URL'),
restful : true,
method : 'GET'
});
/**
* This store contains all tables of a datasource.
* @type Ext.data.JsonStore
*/
var storeTablesJDBC = new Ext.data.JsonStore({
root : "database.tables",
datasourceUtils : this,
fields : [ {
name : 'url'
}, {
name : 'schemaName',
mapping : 'schema'
}, {
name : 'name'
} ],
proxy : httpProxyJDBC,
listeners : {
beforeload : function () {
var dataSourceUrl = this.datasourceUtils.getDataSourceUrl();
this.proxy.setUrl(dataSourceUrl);
}
}
});
/**
* The columnModel of the grid that displays the tables of a datasource.
* @type Ext.grid.ColumnModel
*/
var cmTablesJDBC = new Ext.grid.ColumnModel({
columns : [ {
id : 'name',
header : i18n.get('headers.name'),
width : 160,
sortable : true,
dataIndex : 'name'
} ]
});
/**
* The grid that displays the tables of a datasource.
* @type Ext.grid.ColumnModel
*/
return new Ext.grid.GridPanel({
layout : 'fit',
store : storeTablesJDBC,
cm : cmTablesJDBC,
sm : new Ext.grid.RowSelectionModel({}),
enableDragDrop : true,
stripeRows : true,
title : 'Tables JDBC',
id : 'Tables_JDBC'
});
},
/**
* called to refresh the store of the gridColumnTables.
* For each record in the gridTablesDataset, il will request the datasource to get the definition of a JDBC Table
* @method
*/
loadColumnsBDD : function () {
var store = this.panelSelectTables.getStoreSelectedTables();
var dataSourceUrl = this.getDataSourceUrl();
if (!dataSourceUrl) {
return false;
}
if (store._getDirty() || store.getModifiedRecords().length > 0) {
if (this.panelSelectFields.getBDDPanel()) {
var storeFields = this.panelSelectFields.getBDDPanel().getStore();
storeFields.removeAll();
}
store.each(function (rec) {
Ext.Ajax.request({
url : dataSourceUrl + "/" + rec.data.name,
method : 'GET',
params : {
tableName : rec.data.name,
tableAlias : rec.data.alias,
schemaName : rec.data.schemaName
},
scope : this,
success : function (ret, options) {
var Json = Ext.decode(ret.responseText);
if (Json.success) {
// var store = this.panelSelectFields.getBDDPanel().getStore();
var columns = Json.table;
Ext.each(columns.attributes, function (column, index, columns) {
this.panelSelectFields.getBDDPanel().getStore().add(new Ext.data.Record({
dataIndex : column.name,
schemaName : options.params.schemaName,
tableName : options.params.tableName,
tableAlias : options.params.tableAlias,
sqlColumnType : column.type,
javaSqlColumnType : column.javaSqlType,
columnClass : column.columnClass
}));
}, this);
} else {
Ext.Msg.alert(i18n.get('label.warning'), Json.message);
}
},
failure : alertFailure
});
}, this);
store._setDirty(false);
store.commitChanges();
}
},
/**
* Validate the tables Selection
* @returns {} an object with boolean success attribute.
*/
validateTablesSelection : function (grid) {
return {
success : true
};
},
/**
* Returns the column Model for Dataset Tables grid
* @returns {Ext.grid.ColumnModel} columnModel
*/
getCmTablesDataset : function () {
return new Ext.grid.ColumnModel({
columns : [ {
id : 'name',
header : i18n.get('headers.name'),
width : 160,
sortable : true,
dataIndex : 'name'
}, {
id : 'alias',
header : i18n.get('headers.tableAlias'),
width : 80,
sortable : true,
dataIndex : 'alias',
editor : new Ext.form.TextField({
disabled : this.action === 'view' ? true : false
})
} ]
});
},
/**
* Returns the column Model for Dataset Fields grid
* @returns {Ext.grid.ColumnModel} columnModel
*/
getCmFieldsDataset : function () {
return new Ext.grid.ColumnModel({
columns : [ {
id : 'tableAlias',
header : i18n.get('headers.tableAlias'),
sortable : true,
dataIndex : 'tableAlias'
}, {
id : 'tableName',
header : i18n.get('headers.tableName'),
sortable : true,
dataIndex : 'tableName'
}, {
id : 'name',
header : i18n.get('headers.name'),
sortable : true,
dataIndex : 'dataIndex'
} ]
});
},
/**
* Returns an array of possible types for dataset Columns
* @returns []
*/
getColumnsType : function () {
return [ [ 'SQL', i18n.get('label.sql') ], [ 'VIRTUAL', i18n.get('label.virtual') ] ];
}
});/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, SITOOLS_DATE_FORMAT, SITOOLS_DEFAULT_IHM_DATE_FORMAT, document, showResponse, alertFailure, LOCALE, ImageChooser, loadUrl*/
Ext.namespace('sitools.admin.datasets.datasourceUtils');
/**
* @class sitools.admin.datasets.DatasourceFactory
*/
//sitools.component.datasets.abstractDatasetWin = {
sitools.admin.datasets.datasourceUtils.mongoDbUtils = Ext.extend(Ext.util.Observable, {
isJdbc : false,
isMongoDb : true,
constructor : function (config) {
Ext.apply(this, config.scope);
sitools.admin.datasets.datasourceUtils.jdbcUtils.superclass.constructor.call(this);
},
logInfo : function () {
console.log('mongoDb');
},
/**
* Get the url of the datasource
* @return {string}
*/
getDataSourceUrl : function () {
var record = this.formulairePrincipal.getDataSourceCombo().getStore().getById(this.formulairePrincipal.getDataSourceCombo().getValue());
if (!record) {
return false;
}
return record.data.sitoolsAttachementForUsers + "/collections";
},
getFieldsBDDSelected : function (tree) {
return tree.getSelectionModel().getSelectedNodes();
},
/**
* create an empty Panel
* @returns
*/
createGridFieldsBDD : function () {
var metadataPanel = new Ext.Panel();
return metadataPanel;
},
/**
* Creates the real object
* @returns
*/
loadColumnsBDD : function () {
var store = this.panelSelectTables.getStoreSelectedTables();
var dataSourceUrl = this.getDataSourceUrl();
if (!dataSourceUrl) {
return false;
}
if (store._getDirty() || store.getModifiedRecords().length > 0) {
if (store.getCount() > 0) {
var url = dataSourceUrl + "/" + store.getAt(0).data.name;
var treePanel = new sitools.admin.datasource.mongoDb.CollectionExplorer({
collection : {
name : store.getAt(0).data.name,
url : url
}
});
this.panelSelectFields.setFirstGrid(treePanel);
}
}
},
createGridTablesBDD : function () {
/**
* Proxy used to request a datasource
* @type Ext.data.HttpProxy
*/
var httpProxyJDBC = new Ext.data.HttpProxy({
url : loadUrl.get('APP_URL'),
restful : true,
method : 'GET'
});
/**
* This store contains all tables of a datasource.
* @type Ext.data.JsonStore
*/
var storeTablesMongo = new Ext.data.JsonStore({
root : "mongodbdatabase.collections",
datasourceUtils : this,
fields : [ {
name : 'url'
}, {
name : 'name'
}],
proxy : httpProxyJDBC,
listeners : {
beforeload : function () {
var dataSourceUrl = this.datasourceUtils.getDataSourceUrl();
this.proxy.setUrl(dataSourceUrl);
//TODO : changer ça
// this.httpProxyColumns.setUrl(dataSourceUrl);
}
}
});
/**
* The columnModel of the grid that displays the tables of a datasource.
* @type Ext.grid.ColumnModel
*/
var cmTablesMongo = new Ext.grid.ColumnModel({
columns : [ {
id : 'name',
header : i18n.get('headers.name'),
width : 160,
sortable : true,
dataIndex : 'name'
} ]
});
/**
* The grid that displays the tables of a datasource.
* @type Ext.grid.ColumnModel
*/
return new Ext.grid.GridPanel({
layout : 'fit',
store : storeTablesMongo,
cm : cmTablesMongo,
sm : new Ext.grid.RowSelectionModel({}),
enableDragDrop : true,
stripeRows : true,
title : 'Tables Mongo',
id : 'Tables_Mongo'
});
},
/**
* Validate the tables Selection
* @returns {} an object with boolean success attribute.
*/
validateTablesSelection : function (grid) {
if (grid.getStore().getCount() > 1) {
return {
success : false,
message : i18n.get('label.tooManyTablesSelected')
};
}
return {
success : true
};
},
/**
* Returns the column Model for Dataset Tables grid
* @returns {Ext.grid.ColumnModel} columnModel
*/
getCmTablesDataset : function () {
return new Ext.grid.ColumnModel({
columns : [ {
id : 'name',
header : i18n.get('headers.name'),
width : 160,
sortable : true,
dataIndex : 'name'
}]
});
},
/**
* Returns the column Model for Dataset Fields grid
* @returns {Ext.grid.ColumnModel} columnModel
*/
getCmFieldsDataset : function () {
return new Ext.grid.ColumnModel({
columns : [{
id : 'tableName',
header : i18n.get('headers.tableName'),
sortable : true,
dataIndex : 'tableName'
}, {
id : 'name',
header : i18n.get('headers.name'),
sortable : true,
dataIndex : 'dataIndex'
} ]
});
},
/**
* Returns an array of possible types for dataset Columns
* @returns []
*/
getColumnsType : function () {
return [ [ 'DATABASE', i18n.get('label.database') ], [ 'VIRTUAL', i18n.get('label.virtual') ] ];
}
});/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser*/
Ext.namespace('sitools.admin.datasets');
/**
* Define the window of the dataset Configuration
* @cfg {String} action (required) "active", "modify" "view"
* @cfg {String} urlDatasetViews the url to request all dataviews available
* @cfg {Array} viewConfigParamsValue An array containing all params value for view Config
* @class sitools.admin.datasets.datasetForm
* @extends Ext.Panel
*/
sitools.admin.datasets.datasetViewConfig = Ext.extend(Ext.form.FormPanel, {
padding : 10,
initComponent : function () {
this.title = i18n.get('label.viewConfig');
var action = this.action;
//Store of the comboDatasetsViews.
var storeDatasetViews = new Ext.data.JsonStore({
fields : [ 'id', 'name', 'description', 'jsObject', 'fileUrl', 'priority' ],
url : this.urlDatasetViews,
root : "data",
sortInfo : {
field : 'priority',
direction : 'ASC'
},
listeners : {
scope : this,
load : function (store, recs) {
if (Ext.isEmpty(this.comboDatasetViews.getValue())) {
if (!Ext.isEmpty(recs) && Ext.isArray(recs) && recs.length > 0) {
var minPriorityRec = null;
for (var i = 0; i < recs.length; i++) {
if (Ext.isEmpty(minPriorityRec) || recs[i].data.priority < minPriorityRec.data.priority) {
minPriorityRec = recs[i];
}
}
this.comboDatasetViews.setValue(minPriorityRec.id);
this.comboDatasetViews.fireEvent("select", this.comboDatasetViews, minPriorityRec);
}
}
}
}
});
/**
* Combo to select Datasets Views.
* Uses the storeDatasetViews.
*/
this.comboDatasetViews = new Ext.form.ComboBox({
disabled : this.action == 'view' ? true : false,
id : "comboDatasetViews",
store : storeDatasetViews,
fieldLabel : i18n.get('label.datasetViews'),
displayField : 'name',
valueField : 'id',
typeAhead : true,
mode : 'local',
name : 'comboDatasetViews',
forceSelection : true,
triggerAction : 'all',
editable : false,
emptyText : i18n.get('label.datasetViewsSelect'),
selectOnFocus : true,
anchor : '95%',
itemSelector : 'div.search-item',
allowBlank : false,
autoSelect : true,
maxHeight : 200,
validator : function (value) {
if (Ext.isEmpty(value)) {
return false;
} else {
return true;
}
},
tpl : new Ext.XTemplate(
'<tpl for=".">',
'<div class="search-item combo-datasetview"><div class="combo-datasetview-name">{name}</div>',
'<tpl if="this.descEmpty(description) == false" ><div class="sitoolsDescription-datasetview"><div class="sitoolsDescriptionHeader">Description : </div><p class="sitoolsDescriptionText"> {description} </p></div></tpl>',
'</div></tpl>',
{
compiled : true,
descEmpty : function (description) {
return Ext.isEmpty(description);
}
}
),
listeners : {
scope : this,
select : function (combo, rec, index) {
this.buildViewConfig(rec);
}
}
});
this.parametersFieldset = new Ext.form.FieldSet({
title : i18n.get('label.parameters'),
anchor : "95%"
});
Ext.apply(this, {
items : [this.comboDatasetViews, this.parametersFieldset],
listeners : {
"activate" : function () {
if (action == 'view') {
this.getEl().mask();
}
}
}
});
sitools.admin.datasets.datasetViewConfig.superclass.initComponent.call(this);
},
getDatasetViewsCombo : function () {
return this.comboDatasetViews;
},
setViewConfigParamsValue : function (data) {
this.viewConfigParamsValue = data;
},
buildViewConfig : function (recSelected) {
try {
this.parametersFieldset.removeAll();
var getParametersMethod = eval(recSelected.json.jsObject + ".getParameters");
if (!Ext.isFunction(getParametersMethod)) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('label.notImplementedMethod <br/>' + getParametersMethod));
return;
}
var parameters = getParametersMethod();
if (Ext.isEmpty(parameters)) {
this.parametersFieldset.setVisible(false);
}
else {
this.parametersFieldset.setVisible(true);
}
Ext.each(parameters, function (param) {
var parameterValue = this.findDefaultParameterValue(param);
var JsObj = eval(param.jsObj);
var config = Ext.applyIf(param.config, {
anchor : "95%"
});
var p = new JsObj(config);
if (!Ext.isEmpty(parameterValue)) {
p.setValue(parameterValue);
}
this.parametersFieldset.add(p);
}, this);
this.doLayout();
}
catch (err) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('label.notImplementedMethod <br/>') + err);
return;
}
},
getParametersValue : function () {
var result = [];
if (Ext.isEmpty(this.parametersFieldset.items)) {
return result;
}
this.parametersFieldset.items.each(function (param) {
result.push({
name : param.parameterName,
value : param.getValue()
});
}, this);
return result;
},
findDefaultParameterValue : function (param) {
var result;
Ext.each(this.viewConfigParamsValue, function (paramValue) {
if (paramValue.name == param.config.parameterName) {
result = paramValue.value;
}
});
return result;
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser*/
Ext.namespace('sitools.admin.datasets');
/**
* Define the window of the dataset Configuration
* @cfg {String} url the Url to save the data (only when modify)
* @cfg {String} action (required) "active", "modify" "view"
* @cfg {Ext.data.Store} store (required) : the datasets store
* @cfg {String} urlDatasources The url of the JDBC datasources
* @cfg {String} urlDatasourcesMongoDB The url of the MongoDB datasources
* @class sitools.admin.datasets.datasetForm
* @extends Ext.Panel
*/
//sitools.component.datasets.datasetForm = Ext.extend(Ext.Panel, {
sitools.admin.datasets.datasetForm = Ext.extend(Ext.Panel, {
initComponent : function () {
var action = this.action;
//Datasource Store
var storeDataSource = new Ext.data.JsonStore({
fields : [ 'id', 'name', 'sitoolsAttachementForUsers', 'jdbc', 'mongoDb' ],
root : "data",
listeners : {
scope : this,
load : function (store, recs) {
if (this.action === "create") {
if (!Ext.isEmpty(recs) && Ext.isArray(recs) && recs.length > 0) {
this.comboDataSource.setValue(recs[0].id);
this.comboDataSource.fireEvent("initValue", this.comboDataSource, recs[0].id);
}
}
}
}
});
/**
* Combo to select Datasources.
* Uses the storeDataSource.
*/
this.comboDataSource = new Ext.form.ComboBox({
disabled : this.action == 'view' ? true : false,
id : "comboDataSource",
store : storeDataSource,
fieldLabel : i18n.get('label.dataSource'),
displayField : 'name',
valueField : 'id',
typeAhead : true,
mode : 'local',
name : 'comboDataSource',
forceSelection : true,
triggerAction : 'all',
editable : false,
emptyText : i18n.get('label.dataSourceSelect'),
selectOnFocus : true,
anchor : '50%',
value : "",
listeners : {
scope : this,
change : function (field, newValue, oldValue) {
this.getBubbleTarget().fireEvent("datasourceChanged", field, newValue, oldValue);
},
select : function (field, rec, index) {
var newValue = rec.get("id");
field.fireEvent("change", newValue, field.getValue());
},
initValue : function (field, newValue) {
this.getBubbleTarget().fireEvent("initComboDatasource", field, newValue);
}
},
validator : function (value) {
if (Ext.isEmpty(value)) {
return false;
} else {
return true;
}
},
getDatasourceType : function () {
var rec = this.getStore().getAt(this.getStore().findExact("id", this.getValue()));
return {
jdbc : rec.get('jdbc'),
mongoDb : rec.get('mongoDb')
};
}
});
Ext.apply(this, {
layout : 'fit',
id : "datasetMainForm",
title : i18n.get('label.datasetInfo'),
items : [ {
xtype : 'form',
border : false,
padding : 10,
defaults : {
disabled : this.action == 'view' ? true : false
},
items : [ {
xtype : 'hidden',
name : 'id'
}, {
xtype : 'textfield',
name : 'name',
fieldLabel : i18n.get('label.name'),
anchor : '95%',
vtype : "name",
maxLength : 50
}, {
xtype : 'textfield',
name : 'description',
fieldLabel : i18n.get('label.description'),
anchor : '95%',
maxLength : 200
}, {
xtype : 'sitoolsSelectImage',
name : 'image',
vtype : "image",
fieldLabel : i18n.get('label.image'),
anchor : '95%',
growMax : 400
}, this.comboDataSource, {
xtype : 'textfield',
vtype : "attachment",
name : 'sitoolsAttachementForUsers',
id : 'sitoolsAttachementForUsers',
fieldLabel : i18n.get('label.userAttach'),
anchor : '95%',
maxLength : 100
}, {
xtype : 'checkbox',
name : 'visible',
id : 'visible',
fieldLabel : i18n.get('label.isVisible'),
anchor : '95%',
maxLength : 100
}, {
xtype : 'textfield',
disabled : true,
name : 'expirationDate',
id : 'expirationDate',
fieldLabel : i18n.get('label.expirationDate'),
anchor : '95%',
maxLength : 100
}, {
xtype : 'htmleditor',
id : 'descriptionHTML',
fieldLabel : i18n.get('label.descriptionHTML'),
height : 150,
anchor : '95%'
}, {
xtype : 'hidden',
name : 'dirty',
value : false
} ]
} ],
listeners : {
"activate" : function () {
if (action == 'view') {
this.getEl().mask();
}
}
}
});
sitools.admin.datasets.datasetForm.superclass.initComponent.call(this);
},
getForm : function () {
return this.items.items[0].getForm();
},
/**
* Get the combo of dataSources
* @return {Ext.form.ComboBox}
*/
getDataSourceCombo : function () {
return this.comboDataSource;
},
// /**
// * Get the combo of Dataviews
// * @return {Ext.form.ComboBox}
// */
// getDatasetViewsCombo : function () {
// return this.comboDatasetViews;
// },
/**
* Get the url of the datasource
* @return {string}
*/
getDataSourceUrl : function () {
var record = this.getDataSourceCombo().getStore().getById(this.getDataSourceCombo().getValue());
if (!record) {
return false;
}
return record.data.sitoolsAttachementForUsers;
},
loadDatasources : function (callback, callbackScope) {
var urlDatasources = this.urlDatasources;
var urlDatasourcesMongoDB = this.urlDatasourcesMongoDB;
var store = this.comboDataSource.getStore();
//load JDBC datasources
Ext.Ajax.request({
url : urlDatasources,
method : 'GET',
scope : this,
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (!Json.success) {
Ext.Msg.alert(i18n.get('label.warning'), Json.message);
return;
}
//var records = Json.data;
Ext.each(Json.data, function (data) {
data.jdbc = true;
});
store.loadData(Json);
Ext.Ajax.request({
url : urlDatasourcesMongoDB,
method : 'GET',
scope : callbackScope,
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (!Json.success) {
Ext.Msg.alert(i18n.get('label.warning'), Json.message);
return;
}
Ext.each(Json.data, function (record) {
record.mongoDb = true;
});
store.loadData(Json, true);
// store.each(function (record) {
// record.set("sitoolsAttachementForUsers", record.set("sitoolsAttachementForUsers") + "/collection");
// });
//var records = Json.data;
store.fireEvent("load", store, store.getRange(0, store.getTotalCount()));
},
failure : alertFailure,
callback : callback
});
},
failure : alertFailure
});
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, SITOOLS_DATE_FORMAT, SITOOLS_DEFAULT_IHM_DATE_FORMAT, document, showResponse, alertFailure, LOCALE, ImageChooser, loadUrl*/
Ext.namespace('sitools.admin.datasets');
/**
* @class sitools.admin.datasets.abstractDatasetWin
*/
//sitools.component.datasets.abstractDatasetWin = {
sitools.admin.datasets.abstractDatasetWin = {
/**
* @cfg minWidth
* @inheritdoc
*/
minWidth : 700,
/**
* @cfg minHeight
* @inheritdoc
*/
minHeight : 480,
/**
* @cfg width
* @inheritdoc
*/
width : 700,
/**
* @cfg height
* @inheritdoc
*/
height : 480,
/**
* @cfg modal
* @inheritdoc
*/
modal : true,
/**
* The defaultValue of width for each Column
* @type Number
*/
defaultColumnWidth : 100,
/**
* The defaultValue of visible for each Column
* @type boolean
*/
defaultColumnVisible : true,
/**
* The defaultValue of Sortable for each Column
* @type boolean
*/
defaultColumnSortable : true,
/**
* The defaultValue of filtrable for each Column
* @type boolean
*/
defaultColumnFiltrable : true,
/**
* The query type should be W for Wizard or S for SQL
* @type String
*/
queryType : 'W',
/**
* @cfg id
* @inheritdoc
*/
id : 'datasetsMultiTablesPanel',
/**
* @cfg resizable
* @inheritdoc
*/
resizable : true,
/**
* TODO : à documenter...
* @method
*/
onUpload : function () {
function validate(data, config) {
config.fieldUrl.setValue(data.url);
}
var chooser = new ImageChooser({
url : loadUrl.get('APP_URL') + loadUrl.get('APP_UPLOAD_URL') + '/?media=json',
width : 515,
height : 350,
fieldUrl : this.ownerCt.items.items[0]
});
chooser.show(document, validate);
},
/**
* get all the nodes of the wizard to build sql join
* @method
* @param {} root
* @param {} parent
*/
getAllNodes : function (root, parent) {
var node = {};
if (Ext.isEmpty(root)) {
return;
} else if (root.isLeaf()) {
node = {
leaf : true,
predicat : root.attributes.predicat,
type : root.attributes.type
};
parent.push(node);
} else {
node = {
table : root.attributes.table,
typeJointure : root.attributes.typeJointure,
children : [],
leaf : false,
type : root.attributes.type
};
parent.push(node);
// we call recursively getAllNodes to get all childNodes
var childs = root.childNodes;
var i;
for (i = 0; i < childs.length; i++) {
this.getAllNodes(childs[i], node.children);
}
}
},
/**
* Call to fill the window with the initialValue
* @method
*/
loadDataset : function () {
// Si l'objet est en modification, on charge l'objet en
// question
if (this.action === 'modify' || this.action === 'view' || this.action === "duplicate") {
var url = "";
if (this.action === "duplicate") {
url = this.datasetUrlToCopy;
}
else {
url = this.url;
}
Ext.Ajax.request({
url : url,
method : 'GET',
scope : this,
success : function (ret) {
var i;
var Json = Ext.decode(ret.responseText);
if (!Json.success) {
this.close();
Ext.Msg.alert(i18n.get('label.warning'), Json.message);
return;
}
var f = this.findByType('form')[0].getForm();
var store = this.findById('gridColumnSelect').getStore();
var data = Json.dataset;
this.initialData = data;
var rec = {};
if (this.action !== "duplicate") {
rec.id = data.id;
rec.sitoolsAttachementForUsers = data.sitoolsAttachementForUsers;
rec.dirty = data.dirty;
rec.name = data.name;
}
else {
rec.name = data.name + "_copy";
}
rec.description = data.description;
if (!Ext.isEmpty(data.image)) {
rec.image = data.image.url;
}
rec.expirationDate = data.expirationDate;
rec.queryType = data.queryType;
rec.visible = data.visible;
rec.orderBy = data.orderBy;
rec.descriptionHTML = data.descriptionHTML;
var record = new Ext.data.Record(rec);
f.loadRecord(record);
this.queryType = data.queryType;
Ext.getCmp('radioQueryType').setValue(this.queryType);
Ext.getCmp('sqlQuery').setValue(data.sqlQuery);
this.formulairePrincipal.loadDatasources(
function () {
if (data.datasource) {
var combo = this.findByType('form')[0].getComponent('comboDataSource');
var oldValue = combo.getValue();
combo.setValue(data.datasource.id);
combo.fireEvent("initValue", combo, data.datasource.id);
}
},
this.formulairePrincipal
);
this.viewConfigPanel.getDatasetViewsCombo().getStore().load({
scope : this,
callback : function (recs) {
if (data.datasetView) {
var me = this.viewConfigPanel.getDatasetViewsCombo().getStore();
var recSelected = me.getAt(me.find("id", data.datasetView.id));
this.viewConfigPanel.getDatasetViewsCombo().setValue(data.datasetView.id);
this.viewConfigPanel.setViewConfigParamsValue(data.datasetViewConfig);
this.viewConfigPanel.getDatasetViewsCombo().fireEvent("select", this.viewConfigPanel.getDatasetViewsCombo(), recSelected);
}
}
});
// if (data.structures) {
// var structures = data.structures;
// var storeTablesDataset = this.gridTablesDataset.getStore();
// for (i = 0; i < structures.length; i++) {
// storeTablesDataset.add(new Ext.data.Record({
// name : structures[i].name,
// alias : structures[i].alias,
// schemaName : structures[i].schemaName
// }));
//
// }
// }
if (data.predicat) {
// this.loadColumnsJDBC();
var predicat = data.predicat;
var storeWhereClause = this.panelWhere.getWizardWhereClause().getStore();
for (i = 0; i < predicat.length; i++) {
var leftAttribute;
if (predicat[i]) {
leftAttribute = {
tableName : predicat[i].leftAttribute.tableName,
tableAlias : predicat[i].leftAttribute.tableAlias,
schemaName : predicat[i].leftAttribute.schemaName,
dataIndex : predicat[i].leftAttribute.dataIndex,
columnAlias : predicat[i].leftAttribute.columnAlias,
specificColumnType : predicat[i].leftAttribute.specificColumnType
};
var RecordType = storeWhereClause.recordType;
rec = new RecordType({
parentheseFermante : predicat[i].closedParenthesis,
parentheseOuvrante : predicat[i].openParenthesis,
opLogique : predicat[i].logicOperator,
operateur : predicat[i].compareOperator,
leftAttribute : leftAttribute,
rightAttribute : predicat[i].rightValue.$
});
storeWhereClause.add(rec);
}
}
}
if (!data.columnModel) {
return;
}
var columnModel = data.columnModel;
this.findById('gridColumnSelect').getData(columnModel);
if (! Ext.isEmpty(data.structure)) {
this.panelWhere.getWizardJoinCondition().items.items[0].loadTree(data);
}
if (data.properties) {
var storeProp = this.gridProperties.getStore();
var recProp;
Ext.each(data.properties, function (prop) {
if (prop.type == "Date") {
var date = Date.parseDate(prop.value, SITOOLS_DATE_FORMAT);
if (Ext.isEmpty(date)) {
prop.value = "invalid date";
} else {
prop.value = date.format(SITOOLS_DEFAULT_IHM_DATE_FORMAT);
}
}
recProp = new Ext.data.Record(prop);
storeProp.add(recProp);
});
}
},
failure : function (ret) {
var data = Ext.decode(ret.responseText);
Ext.Msg.alert(i18n.get('label.warning'), data.errorMessage);
}
});
} else {
// this.formulairePrincipal.getDataSourceCombo().getStore().load();
this.formulairePrincipal.loadDatasources();
this.viewConfigPanel.getDatasetViewsCombo().getStore().load();
}
}
};
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, SITOOLS_DEFAULT_IHM_DATE_FORMAT, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser*/
Ext.namespace('sitools.admin.datasets');
/**
* Define the dataset properties gridPanel
* @class sitools.admin.datasets.datasetProperties
* @extends Ext.grid.GridPanel
*/
sitools.admin.datasets.datasetProperties = Ext.extend(Ext.grid.EditorGridPanel, {
initComponent : function () {
var action = this.action;
var storeProperties = new Ext.data.JsonStore({
fields : [ {
name : 'name',
type : 'string'
}, {
name : 'type',
type : 'string'
}, {
name : 'value',
type : 'string'
} ],
autoLoad : false
});
var smProperties = new Ext.grid.RowSelectionModel({
singleSelect : true
});
var storeTypesProperties = new Ext.data.JsonStore({
fields : ['name'],
data : [{name : "String"}, {name : "Enum"}, {name : "Numeric"}, {name : "Date"}]
});
var comboTypesProperties = new Ext.form.ComboBox({
store : storeTypesProperties,
mode : 'local',
typeAhead : true,
triggerAction : 'all',
forceSelection : true,
selectOnFocus : true,
dataIndex : 'orderBy',
lazyRender : true,
listClass : 'x-combo-list-small',
valueField : 'name',
displayField : 'name',
tpl : '<tpl for="."><div class="x-combo-list-item comboItem">{name}</div></tpl>',
width : 55
});
var cmProperties = new Ext.grid.ColumnModel({
columns : [ {
header : i18n.get('headers.name'),
dataIndex : 'name',
editor : new Ext.form.TextField()
}, {
header : i18n.get('headers.type'),
dataIndex : 'type',
editor : comboTypesProperties
}, {
header : i18n.get('headers.value'),
dataIndex : 'value',
editor : new Ext.form.TextField()
}],
defaults : {
sortable : false,
width : 100
}
});
var tbar = {
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreateProperty
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDeleteProperty
} ]
};
Ext.apply(this, {
title : i18n.get('title.properties'),
id : 'componentGridProperties',
tbar : tbar,
anchor : "95%",
height : 180,
store : storeProperties,
cm : cmProperties,
sm : smProperties,
viewConfig : {
forceFit : true
},
listeners : {
scope : this,
activate : function (panel) {
if (this.action == 'view') {
panel.getEl().mask();
}
},
beforeedit : function (e) {
//Créer l'éditeur en fonction du type
if (e.column == 2) {
var grid = e.grid;
var rec = e.record;
var column = grid.getColumnModel().columns[e.column];
if (Ext.isEmpty(rec.get("type"))) {
return false;
}
var editor;
switch (rec.get('type')) {
case "String" :
editor = new Ext.form.TextField();
break;
case "Numeric" :
editor = new Ext.form.NumberField();
break;
case "Date" :
editor = new Ext.form.DateField({
format : SITOOLS_DEFAULT_IHM_DATE_FORMAT,
showTime : true
});
break;
case "Enum" :
editor = new Ext.form.TextField();
break;
}
column.setEditor(editor);
}
return true;
},
afteredit : function (e) {
//Formatter en string
if (e.column == 2) {
var grid = e.grid;
var rec = e.record;
var column = grid.getColumnModel().columns[e.column];
var value = e.value;
if (Ext.isEmpty(rec.get("type"))) {
return false;
}
switch (rec.get('type')) {
case "String" :
value = String.format(value);
break;
case "Numeric" :
value = Ext.util.Format.number(value, "0.00");
break;
case "Date" :
value = value.format(SITOOLS_DEFAULT_IHM_DATE_FORMAT);
break;
case "Enum" :
value = String.format(value);
break;
}
rec.set("value", value);
}
}
}
});
sitools.admin.datasets.datasetProperties.superclass.initComponent.call(this);
},
/**
* A method called on create button of the property grid.
* Creates a new record with a String default type
*/
onCreateProperty : function () {
var e = new Ext.data.Record({
type : "String"
});
this.getStore().insert(0, e);
},
/**
* Called on delete button of the property grid.
* Deletes all selected records.
*/
onDeleteProperty : function () {
var s = this.getSelectionModel().getSelections();
var i, r;
for (i = 0; s[i]; i++) {
r = s[i];
this.getStore().remove(r);
}
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser*/
Ext.namespace('sitools.admin.datasets');
/**
* Define the window of the dataset Configuration
* @cfg {String} url the Url to save the data (only when modify)
* @cfg {String} action (required) "active", "modify" "view"
* @cfg {Ext.data.Store} store (required) : the datasets store
* @cfg {String} urlDatasources The url of the JDBC datasources
* @cfg {String} urlDatasourcesMongoDB The url of the MongoDB datasources
* @class sitools.admin.datasets.datasetForm
* @extends Ext.Panel
*/
//sitools.component.datasets.datasetForm = Ext.extend(Ext.Panel, {
sitools.admin.datasets.datasetSelectTables = Ext.extend(Ext.Panel, {
initComponent : function () {
var action = this.action;
Ext.apply(this, {
title : i18n.get('label.selectTables'), // "select Tables",
layout : 'fit',
id : "selectTablesPanel",
listeners : {
scope : this,
activate : function (panel) {
//instanciate the panels at the first passage
if (Ext.isEmpty(this.items)) {
this.buildPanel();
this.loadInitialData();
}
// this.storeTablesJDBC.load();
if (action == 'view') {
panel.getEl().mask();
}
},
datasourceChanged : function () {
this.datasourceUtils = this.scope.datasourceUtils;
this.gridTablesBDD = this.datasourceUtils.createGridTablesBDD();
this.displayPanelTables.setFirstGrid(this.gridTablesBDD);
this.gridTablesBDD.getStore().load();
},
initializeDatasource : function () {
if (Ext.isEmpty(this.items)) {
this.buildPanel();
this.loadInitialData();
}
}
}
});
sitools.admin.datasets.datasetSelectTables.superclass.initComponent.call(this);
},
loadInitialData : function () {
var data = this.scope.initialData;
if (data && data.structures) {
var structures = data.structures;
for (var i = 0; i < structures.length; i++) {
this.storeTablesDataset.add(new Ext.data.Record({
name : structures[i].name,
alias : structures[i].alias,
schemaName : structures[i].schemaName
}));
}
}
},
buildPanel : function () {
this.datasourceUtils = this.scope.datasourceUtils;
this.gridTablesBDD = this.datasourceUtils.createGridTablesBDD();
this.gridTablesBDD.getStore().load();
var cmTablesDataSet = this.datasourceUtils.getCmTablesDataset();
/**
* The store that contains the tables of a Dataset.
* @type Ext.grid.ColumnModel
*/
this.storeTablesDataset = new sitools.widget.JsonStore({
id : 'storeTablesDataset',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'alias',
type : 'string'
}, {
name : 'schemaName',
type : 'string'
}
]
});
/**
* The grid that displays the tables of a dataset.
* @type Ext.grid.ColumnModel
*/
this.gridTablesDataset = new Ext.grid.EditorGridPanel({
layout : 'fit',
store : this.storeTablesDataset,
cm : cmTablesDataSet,
sm : new Ext.grid.RowSelectionModel({}),
autoScroll : true,
enableDragDrop : true,
stripeRows : true,
title : 'Tables Dataset'
});
this.displayPanelTables = new sitools.component.datasets.selectItems({
grid1 : this.gridTablesBDD,
grid2 : this.gridTablesDataset,
defaultRecord : {}
});
this.add(this.displayPanelTables);
this.doLayout();
},
/**
* Returns true when at least one Table is selected
* @returns {boolean}
*/
isFilled : function () {
return this.gridTablesDataset.getStore().getCount() > 0;
},
/**
* Returns the store of the dataset Tables
* @returns {Ext.data.Store}
*/
getStoreSelectedTables : function () {
return this.gridTablesDataset.getStore();
},
/**
* A method to validate the panel.
* @returns {} an objec with a "success" attributes
*/
validatePanel : function () {
return this.datasourceUtils.validateTablesSelection(this.gridTablesDataset);
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser*/
Ext.namespace('sitools.admin.datasets');
/**
* Define the window of the dataset Configuration
* @class sitools.admin.datasets.datasetSelectFields
* @extends Ext.Panel
*/
sitools.admin.datasets.datasetSelectFields = Ext.extend(Ext.Panel, {
initComponent : function () {
var action = this.action;
Ext.apply(this, {
title : i18n.get('label.selectFields'),
layout : 'fit',
id : "selectTablesFields",
listeners : {
scope : this,
activate : function (panel) {
//instanciate the panels if not yet done
if (Ext.isEmpty(this.items) || this.items.getCount() === 0) {
this.buildPanel();
this.loadInitialData();
}
this.scope.datasourceUtils.loadColumnsBDD();
if (action == 'view') {
panel.getEl().mask();
}
},
datasourceChanged : function () {
this.datasourceUtils = this.scope.datasourceUtils;
this.gridTablesBDD = this.datasourceUtils.getGridTablesBDD();
this.displayPanelTables.setFirstGrid(this.gridTablesBDD);
this.gridTablesBDD.getStore().load();
},
initializeDatasource : function () {
if (Ext.isEmpty(this.items) || this.items.getCount() === 0) {
this.buildPanel();
this.loadInitialData();
}
}
}
});
sitools.admin.datasets.datasetSelectTables.superclass.initComponent.call(this);
},
loadInitialData : function () {
//nothing to do...
return;
},
buildPanel : function () {
this.datasourceUtils = this.scope.datasourceUtils;
this.gridFieldsBDD = this.datasourceUtils.createGridFieldsBDD();
// this.datasourceUtils.loadColumnsBDD();
var cmFieldsDataset = this.datasourceUtils.getCmFieldsDataset();
/**
* The grid that displays the Fields of a dataset.
* @type Ext.grid.ColumnModel
*/
this.gridFieldsDataset = new Ext.grid.GridPanel({
layout : 'fit',
store : this.gridFieldsDataset,
cm : cmFieldsDataset,
autoScroll : true,
enableDragDrop : true,
stripeRows : true,
title : 'Columns Dataset'
});
var defaultRecord = [ {
name : 'width',
value : this.scope.defaultColumnWidth
}, {
name : 'visible',
value : this.scope.defaultColumnVisible
}, {
name : 'sortable',
value : this.scope.defaultColumnSortable
}, {
name : 'filter',
value : this.scope.defaultColumnFiltrable
}, {
name : 'specificColumnType',
value : 'DATABASE'
} ];
this.displayPanelFields = new sitools.component.datasets.selectItems({
grid1 : this.gridFieldsBDD,
grid2 : this.gridFieldsDataset,
defaultRecord : defaultRecord,
listeners : {
activate : function (panel) {
if (action == 'view') {
panel.getEl().mask();
}
}
},
scope : this.scope
});
this.add(this.displayPanelFields);
this.datasourceUtils.loadColumnsBDD();
this.doLayout();
},
isFilled : function () {
return this.gridFieldsDataset.getStore().getCount() > 0;
},
getBDDPanel : function () {
return this.gridFieldsBDD;
},
setFirstGrid : function (panel) {
if (!Ext.isEmpty(this.displayPanelFields)) {
this.displayPanelFields.setFirstGrid(panel);
}
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, includeJs, sitools, ID, i18n, document, showResponse, SITOOLS_DATE_FORMAT, SITOOLS_DEFAULT_IHM_DATE_FORMAT, alertFailure, LOCALE, ImageChooser, loadUrl*/
Ext.namespace('sitools.component.datasets');
/**
* Define the window of the dataset Configuration
* @cfg {String} url the Url to save the data (only when modify)
* @cfg {String} action (required) "active", "modify" "view"
* @cfg {Ext.data.Store} store (required) : the datasets store
*
* @class sitools.component.datasets.datasetsMultiTablesPanel
* @requires sitools.admin.datasets.PredicatsPanel
* @extends Ext.Window
*/
sitools.component.datasets.datasetsMultiTablesPanel = Ext.extend(Ext.Window, {
closeAction : 'close',
initComponent : function () {
Ext.apply(this, sitools.admin.datasets.abstractDatasetWin);
//do it when loadUrl is ready.
this.urlDictionary = loadUrl.get('APP_URL') + loadUrl.get('APP_DICTIONARIES_URL');
this.urlDatasources = loadUrl.get('APP_URL') + loadUrl.get('APP_DATASOURCES_URL');
this.urlDatasourcesMongoDB = loadUrl.get('APP_URL') + loadUrl.get('APP_DATASOURCES_MONGODB_URL');
this.urlDimension = loadUrl.get('APP_URL') + loadUrl.get('APP_DIMENSIONS_ADMIN_URL') + '/dimension';
this.urlDatasetViews = loadUrl.get('APP_URL') + loadUrl.get('APP_DATASETS_VIEWS_URL');
var action = this.action;
if (this.action === 'modify') {
this.title = i18n.get('label.modifyDataset');
}
if (this.action === 'create' || this.action === "duplicate") {
this.title = i18n.get('label.datasetProject');
}
if (this.action === 'view') {
this.title = i18n.get('label.viewDataset');
}
/**
* Construction de la grille Fields Setup
*/
this.gridFields = new sitools.admin.datasets.gridFieldSetup({
urlDictionary : this.urlDictionary,
urlDimension : this.urlDimension,
action : action,
urlDataset : this.url,
scope : this
});
this.gridFields.addListener('activate', function (panel) {
if (action === 'view') {
panel.getEl().mask();
}
});
/**
* The main form of the dataset definition.
*/
this.formulairePrincipal = new sitools.admin.datasets.datasetForm({
urlDatasetViews : this.urlDatasetViews,
action : this.action,
urlDatasources : this.urlDatasources,
urlDatasourcesMongoDB : this.urlDatasourcesMongoDB,
observer : this
});
this.panelSelectTables = new sitools.admin.datasets.datasetSelectTables({
scope : this,
action : this.action
});
// Creation de la grid des columns d'une table
// !!! le store de cette grille est le meme que celui de fields
// setup....
this.panelSelectFields = new sitools.admin.datasets.datasetSelectFields({
scope : this,
gridFieldsDataset : this.gridFields.getStore(),
action : this.action
});
this.panelWhere = new sitools.admin.datasets.datasetCriteria({
scope : this,
layout : "vbox",
layoutConfig : {
align : "stretch",
flex : "ratio"
},
title : i18n.get('label.whereClause')
});
this.panelWhere.addListener('activate', function () {
if (action === 'view') {
this.getEl().mask();
}
});
this.gridProperties = new sitools.admin.datasets.datasetProperties({
action : this.action
});
Ext.Ajax.request({
url : this.urlDatasetViews,
method : "GET",
scope : this,
success : function (ret) {
var json = Ext.decode(ret.responseText);
if (!json.success) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noProjectName'));
return false;
} else {
var data = json.data;
Ext.each(data, function (datasetViewComponent) {
if (!Ext.isEmpty(datasetViewComponent.dependencies) && !Ext.isEmpty(datasetViewComponent.dependencies.js)) {
Ext.each(datasetViewComponent.dependencies.js, function (dependencies) {
includeJs(dependencies.url);
}, this);
}
});
}
}
});
this.viewConfigPanel = new sitools.admin.datasets.datasetViewConfig({
urlDatasetViews : this.urlDatasetViews,
action : this.action
});
/**
* The main tabPanel of the window
* @type Ext.TabPanel
*/
this.tabPanel = new Ext.TabPanel({
height : 450,
layoutConfig : {
layoutOnCardChange : true
},
activeTab : 0,
items : [ this.formulairePrincipal, this.gridProperties, this.panelSelectTables, this.panelSelectFields, this.gridFields, this.panelWhere, this.viewConfigPanel ],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate,
disabled : action === "view" ? true : false
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ],
listeners : {
scope : this,
beforetabchange : function (tabP, newTab, currentTab) {
var check = {
success : true
};
if (!Ext.isEmpty(currentTab) && currentTab.id === "gridColumnSelect") {
check = this.gridFields.gridFieldSetupValidation();
}
if (!Ext.isEmpty(currentTab) && currentTab.id === "selectTablesPanel") {
check = this.panelSelectTables.validatePanel();
}
if (! check.success) {
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.error'),
html : check.message,
autoDestroy : true,
hideDelay : 1000
}).show(document);
return false;
}
return true;
},
initComboDatasource : function (field, value) {
var datasourceType = this.formulairePrincipal.getDataSourceCombo().getDatasourceType();
this.datasourceUtils = new sitools.admin.datasets.datasourceUtils.DatasourceFactory(datasourceType, this);
this.panelSelectTables.fireEvent("initializeDatasource");
this.panelSelectFields.fireEvent("initializeDatasource");
},
datasourceChanged : function (field, newValue, oldValue) {
var datasourceType = this.formulairePrincipal.getDataSourceCombo().getDatasourceType();
this.datasourceUtils = new sitools.admin.datasets.datasourceUtils.DatasourceFactory(datasourceType, this);
if (Ext.isEmpty(oldValue)) {
this.panelSelectTables.fireEvent("initializeDatasource");
this.panelSelectFields.fireEvent("initializeDatasource");
return;
}
if (newValue != oldValue) {
if (this.gridFields.getStore().getCount() > 0 ||
this.panelWhere.getWizardWhereClause().getStore().getCount() > 0 || this.panelSelectTables.isFilled() ||
(Ext.getCmp('sqlQuery').getValue() && Ext.getCmp('sqlQuery').getValue() !== "")) {
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('warning.changeDatasource'),
scope : this,
fn : function (btn, text) {
if (btn === 'yes') {
this.gridFields.getStore().removeAll();
this.panelWhere.getWizardJoinCondition().deleteJoinPanelItems();
this.panelWhere.getWizardWhereClause().getStore().removeAll();
this.panelSelectTables.getStoreSelectedTables().removeAll();
Ext.getCmp('sqlQuery').setValue("");
} else {
field.setValue(oldValue);
}
}
});
}
this.panelSelectTables.fireEvent("datasourceChanged");
}
}
}
});
this.listeners = {
scope : this,
resize : function (window, width, height) {
var size = window.body.getSize();
this.tabPanel.setSize(size);
}
};
this.items = [ this.tabPanel ];
sitools.component.datasets.datasetsMultiTablesPanel.superclass.initComponent.call(this);
},
/**
* @method
* Execute the parent onRender, and load the dataset, if url is set.
*/
onRender : function () {
sitools.component.datasets.datasetsMultiTablesPanel.superclass.onRender.apply(this, arguments);
if (this.url) {
this.loadDataset();
}
},
/**
* called when user click on Ok button.
* it will
* <ul class="mdetail-params">
* <li>check the dataset (calling datasetValidation())</li>
* <li>build the json object of the Dataset</li>
* <li>call a method (PUT or POST depending on Action config)</li>
* </ul>
* @method
*/
onValidate : function () {
this.queryType = this.panelWhere.getQueryType();
var datasetValidation = this.datasetValidation();
if (!datasetValidation.success) {
Ext.Msg.alert(i18n.get('label.error'), datasetValidation.message);
return;
}
var f = this.findByType('form')[0].getForm();
if (!f.isValid()) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.invalidForm'));
return;
}
var putObject = {};
Ext.iterate(f.getValues(), function (key, value) {
if (key === 'image') {
// TODO : definir une liste de mediaType et type
putObject.image = {};
putObject.image.url = value;
putObject.image.type = "Image";
putObject.image.mediaType = "Image";
} else if (key === 'comboDataSource') {
putObject.datasource = {};
putObject.datasource.url = this.dataSourceUrl;
putObject.datasource.id = this.formulairePrincipal.getDataSourceCombo().getValue();
putObject.datasource.type = "datasource";
putObject.datasource.mediaType = "datasource";
} else if (key !== "visible") {
putObject[key] = value;
}
}, this);
putObject.datasetView = {};
var storeDatasetView = this.viewConfigPanel.getDatasetViewsCombo().getStore();
var indexSelected = storeDatasetView.find("id", this.viewConfigPanel.getDatasetViewsCombo().getValue());
var recDatasetView = storeDatasetView.getAt(indexSelected);
putObject.datasetView = recDatasetView.data;
putObject.datasetViewConfig = this.viewConfigPanel.getParametersValue();
//save Properties...
putObject.properties = [];
this.gridProperties.getStore().each(function (rec) {
if (rec.data.type === "Date") {
var dateValue = rec.get("value");
var date = Date.parseDate(dateValue, SITOOLS_DEFAULT_IHM_DATE_FORMAT);
if (!Ext.isEmpty(date)) {
rec.data.value = date.format(SITOOLS_DATE_FORMAT);
}
}
putObject.properties.push(rec.data);
});
//visible field handling
var visibleField = f.findField("visible");
putObject.visible = visibleField.getValue();
putObject.queryType = this.queryType;
putObject.sqlQuery = Ext.getCmp('sqlQuery').getValue();
if (this.panelWhere.getWizardJoinCondition() || this.panelWhere.getWizardWhereClause()) {
putObject.predicat = [];
}
if (this.panelWhere.getWizardWhereClause()) {
this.panelWhere.getWizardWhereClause().getStore().each(function (item) {
putObject.predicat.push({
closedParenthesis : item.data.parentheseFermante,
openParenthesis : item.data.parentheseOuvrante,
logicOperator : item.data.opLogique,
compareOperator : item.data.operateur,
leftAttribute : item.data.leftAttribute,
rightValue : item.data.rightAttribute
});
});
}
putObject.structures = [];
this.panelSelectTables.getStoreSelectedTables().each(function (item) {
putObject.structures.push({
alias : item.data.alias,
name : item.data.name,
schemaName : item.data.schemaName,
type : 'table'
});
});
var store = this.gridFields.getStore();
store.clearFilter();
if (store.getCount() > 0) {
putObject.columnModel = [];
var i;
for (i = 0; i < store.getCount(); i++) {
var rec = store.getAt(i).data;
var tmp = {
id : rec.id,
dataIndex : rec.dataIndex,
header : rec.header,
toolTip : rec.toolTip,
width : rec.width,
sortable : rec.sortable,
orderBy : rec.orderBy,
visible : rec.visible,
filter : rec.filter,
sqlColumnType : rec.sqlColumnType,
columnOrder : rec.columnOrder,
primaryKey : rec.primaryKey,
schema : rec.schemaName,
tableAlias : rec.tableAlias,
tableName : rec.tableName,
specificColumnType : rec.specificColumnType,
columnAlias : rec.columnAlias,
datasetDetailUrl : rec.datasetDetailUrl,
columnAliasDetail : rec.columnAliasDetail,
javaSqlColumnType : rec.javaSqlColumnType,
format : rec.format,
columnClass : rec.columnClass,
image : rec.image,
dimensionId : rec.dimensionId,
unit : rec.unit
};
if (!Ext.isEmpty(rec.columnRendererCategory) && !Ext.isEmpty(rec.columnRenderer)) {
tmp.columnRenderer = rec.columnRenderer;
}
putObject.columnModel.push(tmp);
}
}
//Gestion des structures
//build Default if the panel is not activated...
this.panelWhere.getWizardJoinCondition().buildDefault();
this.treeStructure = this.panelWhere.getWizardJoinCondition().items.items[0];
var mainTableNode = this.treeStructure.getRootNode();
if (Ext.isEmpty(mainTableNode)) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('label.noStructure'));
return;
}
var mainTable = mainTableNode.attributes.table;
var tree = [];
var childs = mainTableNode.childNodes;
for (var j = 0; j < childs.length; j++) {
this.getAllNodes(childs[j], tree);
}
var structure = {
mainTable : mainTable,
nodeList : tree
};
putObject.structure = structure;
if (this.action === 'modify') {
Ext.Ajax.request({
url : this.url,
method : 'PUT',
scope : this,
jsonData : putObject,
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (!Json.success) {
Ext.Msg.alert(i18n.get('label.warning'), Json.message);
return;
}
this.close();
this.store.reload();
},
failure : alertFailure
});
} else {
Ext.Ajax.request({
url : this.url,
method : 'POST',
scope : this,
jsonData : putObject,
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (!Json.success) {
Ext.Msg.alert(i18n.get('label.warning'), Json.message);
return;
}
this.close();
this.store.reload();
},
failure : alertFailure
});
}
},
/**
* Validate the Dataset :
* - One and only one primary key
* - columnAlias must be unique
* @returns {} an object with attributes :
* - success : boolean
* - message : a message if success == false
*
*/
datasetValidation : function () {
var result = this.gridFields.gridFieldSetupValidation();
if (this.queryType === "S" && (Ext.getCmp('sqlQuery').getValue().substr(0, 4) !== "FROM" || !Ext.getCmp('sqlQuery').getValue().toLowerCase().match("where"))) {
result = {
success : false,
message : i18n.get('label.invalidSQl')
};
}
return result;
}
});
Ext.reg('s-datasetsMultiTablesPanel', sitools.component.datasets.datasetsMultiTablesPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl, ColumnRendererEnum*/
Ext.namespace('sitools.admin.datasets.columnRenderer');
/**
* List of constants
* @type sitools.admin.datasets.columnRenderer.columnRenderEnum
*/
sitools.admin.datasets.columnRenderer.behaviorEnum = {
/**
* URL_LOCAL constant
* @static
* @type String
*/
URL_LOCAL : "localUrl",
/**
* URL_EXT_NEW_TAB constant
* @static
* @type String
*/
URL_EXT_NEW_TAB : "extUrlNewTab",
/**
* URL_EXT_DESKTOP constant
* @static
* @type String
*/
URL_EXT_DESKTOP : "extUrlDesktop",
/**
* IMAGE_NO_THUMB constant
* @static
* @type String
*/
IMAGE_NO_THUMB : "ImgNoThumb",
/**
* IMAGE_THUMB_FROM_IMAGE constant
* @static
* @type String
*/
IMAGE_THUMB_FROM_IMAGE : "ImgAutoThumb",
/**
* IMAGE_FROM_SQL constant
* @static
* @type String
*/
IMAGE_FROM_SQL : "ImgThumbSQL",
/**
* DATASET_LINK constant
* @static
* @type String
*/
DATASET_LINK : "datasetLink",
/**
* DATASET_ICON_LINK constant
* @static
* @type String
*/
DATASET_ICON_LINK : "datasetIconLink",
/**
* NO_CLIENT_ACCESS constant
* @static
* @type String
*/
NO_CLIENT_ACCESS : "noClientAccess",
getColumnRendererCategoryFromBehavior : function (behavior) {
var category;
switch (behavior) {
case ColumnRendererEnum.URL_LOCAL:
case ColumnRendererEnum.URL_EXT_NEW_TAB:
case ColumnRendererEnum.URL_EXT_DESKTOP:
category = "URL";
break;
case ColumnRendererEnum.IMAGE_NO_THUMB:
case ColumnRendererEnum.IMAGE_THUMB_FROM_IMAGE:
case ColumnRendererEnum.IMAGE_FROM_SQL:
category = "Image";
break;
case ColumnRendererEnum.DATASET_LINK:
case ColumnRendererEnum.DATASET_ICON_LINK:
category = "DataSetLink";
break;
case ColumnRendererEnum.NO_CLIENT_ACCESS:
category = "Other";
break;
default :
category = "";
break;
}
return category;
},
/**
* According to a given column Renderer, return true if the column should be displayed as an image
* @param {Object} cr the Column Renderer
* @return {Boolean} true when displaying an image, false otherwise.
*/
isDisplayingImage : function (cr) {
var result = false;
switch (cr.behavior) {
case ColumnRendererEnum.IMAGE_THUMB_FROM_IMAGE:
case ColumnRendererEnum.IMAGE_FROM_SQL:
case ColumnRendererEnum.DATASET_ICON_LINK:
result = true;
break;
case ColumnRendererEnum.URL_LOCAL:
case ColumnRendererEnum.URL_EXT_NEW_TAB:
case ColumnRendererEnum.URL_EXT_DESKTOP:
if (cr.type == "Image")
result = true;
break;
}
return result;
}
};
var ColumnRendererEnum = sitools.admin.datasets.columnRenderer.behaviorEnum;/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl, ColumnRendererEnum*/
Ext.namespace('sitools.admin.datasets.columnRenderer');
/**
* Form panel used to fill specific information from a datasetLink columnRenderer
* @cfg {String} behaviorType (required) : the type of the behavior selected (datasetLink ou datasetIconLink)
* @class sitools.admin.datasets.columnRenderer.datasetLinkPanel
* @extends Ext.form.FormPanel
*/
sitools.admin.datasets.columnRenderer.datasetLinkPanel = Ext.extend(Ext.Panel, {
flex : 1,
layout : {
type : 'vbox',
align : 'stretch'
},
border : false,
initComponent : function () {
this.urlDatasets = loadUrl.get('APP_URL') + loadUrl.get('APP_DATASETS_URL');
this.httpProxy = new Ext.data.HttpProxy({
url : this.urlDatasets,
restful : true,
method : 'GET'
});
this.storeColumns = new Ext.data.JsonStore({
id : 'datasetColumnId',
root : 'dataset.columnModel',
idProperty : 'id',
proxy : this.httpProxy,
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'tableName',
type : 'string'
}, {
name : 'columnAlias',
type : 'string'
} ]
});
this.gridViewColumns = new Ext.grid.GridView({
forceFit: true,
listeners : {
scope : this,
refresh : function () {
if (!Ext.isEmpty(this.columnRenderer)
&& !Ext.isEmpty(this.columnRenderer.columnAlias)
&& this.comboDatasets.getValue() == this.columnRenderer.datasetLinkUrl) {
var columnAlias = this.columnRenderer.columnAlias;
var index = this.gridColumns.getStore().find("columnAlias", columnAlias);
if (index != -1) {
this.gridColumns.getSelectionModel().selectRow(index);
}
}
}
}
});
this.cmColumns = new Ext.grid.ColumnModel({
columns : [ {
header : i18n.get('headers.tableName'),
dataIndex : 'tableName'
}, {
header : i18n.get('headers.columnAlias'),
dataIndex : 'columnAlias'
}],
defaults : {
sortable : true
}
});
this.smColumns = new Ext.grid.RowSelectionModel({
singleSelect : true,
listeners : {
scope : this,
rowselect : function (selectionModel, rowIndex, record) {
Ext.getCmp('status_bar_column').hide();
this.doLayout();
}
}
});
this.bbar = new Ext.ux.StatusBar({
id : "status_bar_column",
hidden : true,
text: i18n.get("label.no_column_selected"),
iconCls: 'x-status-error'
});
var storeDatasets = new Ext.data.JsonStore({
fields : [ 'id', 'name', 'sitoolsAttachementForUsers' ],
url : this.urlDatasets,
root : "data",
autoLoad : true,
listeners : {
scope : this,
load : function () {
if (!Ext.isEmpty(this.columnRenderer) && this.columnRenderer.behavior == this.behaviorType) {
var datasetLinkUrl = this.columnRenderer.datasetLinkUrl;
var index = this.comboDatasets.getStore().find("sitoolsAttachementForUsers", datasetLinkUrl);
if (index != -1) {
this.comboDatasets.setValue(datasetLinkUrl);
var record = this.comboDatasets.getStore().getAt(index);
this.comboDatasets.fireEvent("select", this.comboDatasets, record, index);
}
}
}
}
});
this.comboDatasets = new Ext.form.ComboBox({
store : storeDatasets,
name : "comboDatasets",
displayField : 'name',
valueField : 'sitoolsAttachementForUsers',
typeAhead : true,
mode : 'local',
forceSelection : true,
triggerAction : 'all',
emptyText : i18n.get("label.selectADataset"),
selectOnFocus : true,
anchor : "100%",
fieldLabel : i18n.get('label.dataset'),
allowBlank : false,
listeners : {
scope : this,
select : function (combo, rec, index) {
this.loadColumns(rec.data.id);
}
}
});
this.gridColumns = new Ext.grid.GridPanel({
id : 'gridColumnsSelect',
title : i18n.get('title.datasetLinkDetails'),
layout : 'fit',
flex : 1,
view : this.gridViewColumns,
autoScroll : true,
store : this.storeColumns,
cm : this.cmColumns,
sm : this.smColumns,
bbar : this.bbar,
tbar : {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ this.comboDatasets ]
}
});
this.items = [];
if (this.behaviorType == ColumnRendererEnum.DATASET_ICON_LINK) {
this.formImage = new Ext.form.FormPanel({
padding : 5,
items : [{
xtype : 'sitoolsSelectImage',
name : 'image',
vtype : "image",
fieldLabel : i18n.get('label.image'),
anchor : '100%',
allowBlank : false
}]
});
this.items.push(this.formImage);
} else {
this.title = "";
}
this.items.push(this.gridColumns);
sitools.admin.datasets.columnRenderer.datasetLinkPanel.superclass.initComponent.call(this);
},
afterRender : function () {
sitools.admin.datasets.columnRenderer.datasetLinkPanel.superclass.afterRender.apply(this, arguments);
if (!Ext.isEmpty(this.columnRenderer) && this.columnRenderer.behavior == this.behaviorType) {
if (this.columnRenderer.behavior == ColumnRendererEnum.DATASET_ICON_LINK
&& !Ext.isEmpty(this.columnRenderer.image)) {
this.formImage.getForm().findField("image").setValue(this.columnRenderer.image.url);
}
}
},
/**
* This function is used to validate the panel
* @return {Boolean} true if the panel is valid, false otherwise
*/
isValid : function () {
var isValid = true;
if (this.behaviorType == ColumnRendererEnum.DATASET_ICON_LINK) {
isValid = this.formImage.getForm().isValid();
}
if (isValid) {
isValid = this.comboDatasets.isValid();
if (isValid) {
var column = this.gridColumns.getSelectionModel().getSelected();
if (Ext.isEmpty(column)) {
isValid = false;
Ext.getCmp('status_bar_column').show();
}
}
}
return isValid;
},
/**
* This function is used to fill the record with the specific information of the
* @return {boolean} true if it has succeed, false otherwise
*
*/
fillSpecificValue : function (columnRenderer) {
var dataset = this.comboDatasets.getValue();
columnRenderer.datasetLinkUrl = dataset;
var column = this.gridColumns.getSelectionModel().getSelected();
if (Ext.isEmpty(column)) {
return false;
}
columnRenderer.columnAlias = column.get("columnAlias");
if (this.behaviorType == ColumnRendererEnum.DATASET_ICON_LINK) {
var image = this.formImage.getForm().findField("image").getValue();
var resourceImage = {};
if (!Ext.isEmpty(image)) {
resourceImage.url = image;
resourceImage.type = "Image";
resourceImage.mediaType = "Image";
}
columnRenderer.image = resourceImage;
}
return true;
},
/**
* Load the columns of a specific dataset
* @param {String} datasetId (required) the dataset Id
*/
loadColumns : function (datasetId) {
// alert (dictionaryId);
this.httpProxy.setUrl(this.urlDatasets + "/" + datasetId);
this.gridColumns.getStore().load({
callback : function () {
this.gridColumns.getView().refresh();
},
scope : this
});
}
});/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl, ColumnRendererEnum*/
Ext.namespace('sitools.admin.datasets.columnRenderer');
/**
* Form panel used to fill specific information from a datasetLink columnRenderer
* @cfg {String} behaviorType (required) : the type of the behavior selected (dsLink ou dsIconLink)
* @cfg {Object} columnRenderer : the columnRenderer Object to load if we modify the value
* @class sitools.admin.datasets.columnRenderer.datasetLinkPanel
* @extends Ext.form.FormPanel
*/
sitools.admin.datasets.columnRenderer.urlPanel = Ext.extend(Ext.Panel, {
flex : 1,
layout : "fit",
initComponent : function () {
this.formPanel = new Ext.form.FormPanel({
defaults : {
anchor : "100%"
},
padding : 5,
items : [{
fieldLabel : i18n.get('label.display'),
name : 'display',
xtype : 'radiogroup',
columns : 2,
items : [ {
boxLabel : 'Text',
name : 'display',
inputValue : "Text",
checked : true
}, {
boxLabel : 'Image',
name : 'display',
inputValue : "Image"
} ],
listeners : {
scope : this,
change : function (radioGroup, radioChecked) {
var name = radioChecked.getGroupValue();
var isImage = true;
if (name == "Text") {
isImage = false;
}
this.formPanel.getForm().findField("linkText").setVisible(!isImage);
this.formPanel.getForm().findField("linkText").setDisabled(isImage);
this.formPanel.getForm().findField("image").setVisible(isImage);
this.formPanel.getForm().findField("image").setDisabled(!isImage);
this.doLayout();
}
}
}, {
fieldLabel : i18n.get('label.linkText'),
name : 'linkText',
xtype : 'textfield',
allowBlank : false
}, {
xtype : 'sitoolsSelectImage',
name : 'image',
vtype : "image",
hidden : true,
disabled : true,
fieldLabel : i18n.get('label.image'),
anchor : '100%',
growMax : 400,
allowBlank : false
}, {
xtype : 'checkbox',
fieldLabel : i18n.get('label.isDisplayable'),
name : 'displayable',
anchor : '100%',
tooltip : i18n.get('label.isDisplayable.tooltip'),
hidden : (this.behaviorType != ColumnRendererEnum.URL_EXT_DESKTOP),
disabled : (this.behaviorType != ColumnRendererEnum.URL_EXT_DESKTOP)
}
]
});
this.items = [this.formPanel];
sitools.admin.datasets.columnRenderer.urlPanel.superclass.initComponent.call(this);
},
/**
* This function is used to validate the panel
* @return {Boolean} true if the panel is valid, false otherwise
*/
isValid : function () {
var form = this.formPanel.getForm();
return form.isValid();
},
/**
* This function is used to fill the record with the specific information of the
*
*/
fillSpecificValue : function (columnRenderer) {
var form = this.formPanel.getForm();
var display = form.findField("display").getValue().getGroupValue();
if ("Text" == display) {
var linkText = form.findField("linkText").getValue();
columnRenderer.linkText = linkText;
} else {
var image = form.findField("image").getValue();
var resourceImage = {};
if (!Ext.isEmpty(image)) {
resourceImage.url = image;
resourceImage.type = "Image";
resourceImage.mediaType = "Image";
columnRenderer.image = resourceImage;
}
}
if (this.behaviorType == ColumnRendererEnum.URL_EXT_DESKTOP) {
columnRenderer.displayable = form.findField("displayable").getValue();
}
return true;
},
afterRender : function () {
sitools.admin.datasets.columnRenderer.urlPanel.superclass.afterRender.apply(this, arguments);
if (!Ext.isEmpty(this.columnRenderer) && this.columnRenderer.behavior == this.behaviorType) {
var form = this.formPanel.getForm();
var record = {};
var isImage;
if (!Ext.isEmpty(this.columnRenderer.linkText)) {
record.linkText = this.columnRenderer.linkText;
record.display = "Text";
isImage = false;
}
if (!Ext.isEmpty(this.columnRenderer.image)) {
record.image = this.columnRenderer.image.url;
record.display = "Image";
isImage = true;
}
if (this.behaviorType == ColumnRendererEnum.URL_EXT_DESKTOP) {
record.displayable = this.columnRenderer.displayable;
} else {
record.displayable = false;
}
var rec = new Ext.data.Record(record);
form.loadRecord(rec);
form.findField("linkText").setVisible(!isImage);
form.findField("linkText").setDisabled(isImage);
form.findField("image").setVisible(isImage);
form.findField("image").setDisabled(!isImage);
}
}
});/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl, ColumnRendererEnum*/
Ext.namespace('sitools.admin.datasets.columnRenderer');
/**
* Form panel used to fill specific information from a datasetLink columnRenderer
* @cfg {String} behaviorType (required) : the type of the behavior selected (ImgNoThumb, ImgAutoThumb and ImgThumbSQL)
* @cfg {Ext.data.JsonStore} datasetColumnStore (required) : the store of the column chosen for the current dataset
* @cfg {Object} columnRenderer : the columnRenderer Object to load if we modify the value
* @class sitools.admin.datasets.columnRenderer.datasetLinkPanel
* @extends Ext.form.FormPanel
*/
sitools.admin.datasets.columnRenderer.imagePanel = Ext.extend(Ext.Panel, {
flex : 1,
layout : {
type : 'vbox',
align : 'stretch'
},
initComponent : function () {
this.items = [];
switch (this.behaviorType) {
case ColumnRendererEnum.IMAGE_NO_THUMB :
this.formPanel = new Ext.form.FormPanel({
flex : 1,
defaults : {
anchor : "100%"
},
padding : 5,
items : {
fieldLabel : i18n.get('label.linkText'),
name : 'linkText',
xtype : 'textfield',
allowBlank : false
}
});
this.items.push(this.formPanel);
break;
case ColumnRendererEnum.IMAGE_THUMB_FROM_IMAGE :
//clear the title because nothing has to be configured
this.title = undefined;
this.border = false;
this.frame = true;
break;
case ColumnRendererEnum.IMAGE_FROM_SQL :
this.items.push(this.createDatasetColumnGrid(this.datasetColumnStore));
break;
default :
break;
}
sitools.admin.datasets.columnRenderer.imagePanel.superclass.initComponent.call(this);
},
afterRender : function () {
sitools.admin.datasets.columnRenderer.imagePanel.superclass.afterRender.apply(this, arguments);
if (!Ext.isEmpty(this.columnRenderer) && this.columnRenderer.behavior == this.behaviorType) {
switch (this.behaviorType) {
case ColumnRendererEnum.IMAGE_NO_THUMB :
this.formPanel.getForm().findField("linkText").setValue(this.columnRenderer.linkText);
break;
}
}
},
/**
* Create a GridPanel to display and select a column from the store given
* @param {Ext.data.JsonStore} store the store containing the list of columns for the dataset
* @return {Ext.grid.GridPanel} a grid panel from the given store
* @private
*/
createDatasetColumnGrid : function (store) {
var cmColumns = new Ext.grid.ColumnModel({
columns : [ {
header : i18n.get('headers.tableName'),
dataIndex : 'tableName'
}, {
header : i18n.get('headers.columnAlias'),
dataIndex : 'columnAlias'
}],
defaults : {
sortable : true,
width : 100
}
});
var smColumns = new Ext.grid.RowSelectionModel({
singleSelect : true,
listeners : {
scope : this,
rowselect : function (selectionModel, rowIndex, record) {
this.formPanel.getForm().findField("url").disable();
Ext.getCmp('status_bar_column').hide();
this.doLayout();
},
rowdeselect : function (selectionModel, rowIndex, record) {
this.formPanel.getForm().findField("url").enable();
}
}
});
this.bbar = new Ext.ux.StatusBar({
id : "status_bar_column",
hidden : true,
text: i18n.get("label.no_column_selected"),
iconCls: 'x-status-error'
});
this.gridColumns = new Ext.grid.GridPanel({
id : 'gridColumnsSelect',
layout : 'fit',
autoScroll : true,
store : store,
cm : cmColumns,
sm : smColumns,
flex : 1,
bbar : this.bbar,
viewConfig: {
forceFit: true
},
listeners : {
scope : this,
//select the column selected before
viewReady : function () {
if (!Ext.isEmpty(this.columnRenderer) && !Ext.isEmpty(this.columnRenderer.columnAlias)) {
var columnAlias = this.columnRenderer.columnAlias;
var index = this.gridColumns.getStore().find("columnAlias", columnAlias);
if (index != -1) {
this.gridColumns.getSelectionModel().selectRow(index);
}
}
}
}
});
return this.gridColumns;
},
/**
* This function is used to validate the panel
* @return {Boolean} true if the panel is valid, false otherwise
*/
isValid : function () {
var isValid = true, form;
switch (this.behaviorType) {
case ColumnRendererEnum.IMAGE_NO_THUMB :
form = this.formPanel.getForm();
isValid = form.isValid();
break;
case ColumnRendererEnum.IMAGE_FROM_SQL :
var column = this.gridColumns.getSelectionModel().getSelected();
if (Ext.isEmpty(column)) {
isValid = false;
Ext.getCmp('status_bar_column').show();
}
break;
}
return isValid;
},
/**
* This function is used to fill the record with the specific information of the
*
*/
fillSpecificValue : function (columnRenderer) {
switch (this.behaviorType) {
case ColumnRendererEnum.IMAGE_NO_THUMB :
columnRenderer.linkText = this.formPanel.getForm().findField("linkText").getValue();
break;
case ColumnRendererEnum.IMAGE_FROM_SQL :
var column = this.gridColumns.getSelectionModel().getSelected();
if (Ext.isEmpty(column)) {
return false;
}
columnRenderer.columnAlias = column.get("columnAlias");
break;
}
return true;
}
});/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl, ColumnRendererEnum*/
/*
* @include "columnRender/ColumnRenderEnum.js"
*/
Ext.namespace('sitools.admin.datasets');
/**
* This window is used when the administrator needs to configure a columnRenderer
* (aka featureType) on a particular column.
* @cfg {Ext.data.Record} selectedRecord (required) the selected Column
* @cfg {Ext.grid.GridView} gridView (required) : the view to refresh when saving
* @cfg {Ext.data.JsonStore} datasetColumnStore (required) : the store of the column chosen for the current dataset
* @cfg {String} columnRendererType (required) : the type of the columnRenderer (Image, URL or datasetLink)
* @cfg {String} lastColumnRendererType (required) : the type of columnRenderer configured before calling this window
* @class sitools.admin.datasets.columnRendererWin
* @extends Ext.Window
*/
sitools.admin.datasets.columnRendererWin = Ext.extend(Ext.Window, {
width : 400,
height : 600,
modal : true,
layout : {
type : 'vbox',
align : 'stretch'
},
initComponent : function () {
this.title = this.columnRendererType + " " + i18n.get('label.detailColumnDefinition');
var behaviorData;
switch (this.columnRendererType) {
case "URL" :
behaviorData = [[i18n.get("label.url_local"), ColumnRendererEnum.URL_LOCAL],
[i18n.get("label.url_ext_new_tab"), ColumnRendererEnum.URL_EXT_NEW_TAB],
[i18n.get("label.url_ext_desktop"), ColumnRendererEnum.URL_EXT_DESKTOP]];
break;
case "Image" :
behaviorData = [[i18n.get("label.image_no_thumb"), ColumnRendererEnum.IMAGE_NO_THUMB],
[i18n.get("label.image_thumb_from_image"), ColumnRendererEnum.IMAGE_THUMB_FROM_IMAGE],
[i18n.get("label.image_from_sql"), ColumnRendererEnum.IMAGE_FROM_SQL]];
break;
case "DataSetLink" :
behaviorData = [[i18n.get("label.dataset_link"), ColumnRendererEnum.DATASET_LINK],
[i18n.get("label.dataset_icon_link"), ColumnRendererEnum.DATASET_ICON_LINK]];
break;
case "Other" :
behaviorData = [[i18n.get("label.noClientAccess"), ColumnRendererEnum.NO_CLIENT_ACCESS]];
break;
default :
break;
}
var storeBehavior = new Ext.data.ArrayStore({
fields : [ {
name : 'name'
}, {
name : 'behavior'
} ],
data : behaviorData
});
this.comboBehavior = new Ext.form.ComboBox({
store : storeBehavior,
displayField : 'name',
valueField : 'behavior',
typeAhead : true,
mode : 'local',
forceSelection : true,
triggerAction : 'all',
emptyText : i18n.get("label.selectABehavior"),
fieldLabel : i18n.get('label.behavior'),
anchor : "100%",
selectOnFocus : true,
allowBlank : false,
listeners : {
scope : this,
select : function (combo, rec, index) {
if (!Ext.isEmpty(this.panelDetails)) {
this.remove(this.panelDetails);
this.panelDetails = null;
}
var value = rec.get("behavior");
//if we modify the columnRenderer it will not be null
var columnRenderer = this.selectedRecord.get("columnRenderer");
switch (this.columnRendererType) {
case "URL" :
this.panelDetails = new sitools.admin.datasets.columnRenderer.urlPanel({
behaviorType : value,
title : i18n.get("label.behaviorDetails"),
columnRenderer : columnRenderer
});
break;
case "Image" :
this.panelDetails = new sitools.admin.datasets.columnRenderer.imagePanel({
behaviorType : value,
title : i18n.get("label.behaviorDetails"),
datasetColumnStore : this.datasetColumnStore,
columnRenderer : columnRenderer
});
break;
case "DataSetLink" :
this.panelDetails = new sitools.admin.datasets.columnRenderer.datasetLinkPanel({
behaviorType : value,
title : i18n.get("label.behaviorDetails"),
columnRenderer : columnRenderer
});
break;
default :
break;
}
if (!Ext.isEmpty(this.panelDetails)) {
this.add(this.panelDetails);
this.doLayout();
}
}
}
});
this.behaviorForm = new Ext.form.FormPanel({
title : i18n.get('label.behavior'),
height : 80,
padding : 5,
items : [this.comboBehavior , {
fieldLabel : i18n.get('label.tooltip'),
name : 'toolTip',
xtype : 'textfield',
}]
});
this.items = [this.behaviorForm];
this.buttons = [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ];
this.listeners = {
scope : this,
beforeclose : function () {
if (!this.validAction) {
// clear the grid record
var colRendererCategory = this.lastColumnRendererType;
this.selectedRecord.set("columnRendererCategory", colRendererCategory);
this.gridView.refresh();
}
}
};
sitools.admin.datasets.columnRendererWin.superclass.initComponent.call(this);
},
afterRender : function () {
sitools.admin.datasets.columnRendererWin.superclass.afterRender.apply(this, arguments);
var columnRenderer = this.selectedRecord.get("columnRenderer");
if (!Ext.isEmpty(columnRenderer)) {
var behavior = columnRenderer.behavior;
var toolTip = columnRenderer.toolTip;
this.behaviorForm.getForm().findField('toolTip').setValue(toolTip);
var index = this.comboBehavior.getStore().find("behavior", behavior);
if (index != -1) {
this.comboBehavior.setValue(behavior);
var record = this.comboBehavior.getStore().getAt(index);
this.comboBehavior.fireEvent("select", this.comboBehavior, record, index);
}
}
},
onValidate : function () {
var behavior = this.comboBehavior.getValue();
var tooltip = this.behaviorForm.getForm().findField('toolTip').getValue();
var ok = true;
if (this.behaviorForm.getForm().isValid()) {
var columnRenderer = {};
columnRenderer.behavior = behavior;
columnRenderer.toolTip = tooltip;
if (!Ext.isEmpty(this.panelDetails)) {
if (this.panelDetails.isValid()) {
this.panelDetails.fillSpecificValue(columnRenderer);
} else {
ok = false;
}
}
if (ok) {
this.selectedRecord.set("columnRenderer", columnRenderer);
this.gridView.refresh();
this.validAction = true;
this.close();
}
}
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.admin.datasets');
/**
* This window is used when the administrator needs to link a dataset with another.
* @cfg {Ext.data.Record} selectedRecord (required) the selected Column
* @cfg {Ext.grid.GridView} gridView (required) : the view to refresh when saving
* @cfg {boolean} withImage : true if this link is with image
* @class sitools.admin.datasets.datasetUrlWin
* @extends Ext.Window
*/
//sitools.component.datasets.datasetUrlWin = Ext.extend(Ext.Window, {
sitools.admin.datasets.datasetUrlWin = Ext.extend(Ext.Window, {
width : 400,
height : 400,
modal : true,
initComponent : function () {
this.urlDatasets = loadUrl.get('APP_URL') + loadUrl.get('APP_DATASETS_URL');
this.title = i18n.get('label.detailColumnDefinition');
this.httpProxy = new Ext.data.HttpProxy({
url : this.urlDatasets,
restful : true,
method : 'GET'
});
this.storeColumns = new Ext.data.JsonStore({
id : 'datasetColumnId',
root : 'dataset.columnModel',
idProperty : 'id',
proxy : this.httpProxy,
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'tableName',
type : 'string'
}, {
name : 'columnAlias',
type : 'string'
} ]
});
this.gridViewColumns = new Ext.grid.GridView({
listeners : {
scope : this,
refresh : function () {
if (!Ext.isEmpty(this.selectedRecord.data.columnAliasDetail)) {
var recIndex = this.storeColumns.find('columnAlias', this.selectedRecord.data.columnAliasDetail);
if (recIndex > -1) {
this.smColumns.selectRow(recIndex);
}
}
}
}
});
this.cmColumns = new Ext.grid.ColumnModel({
columns : [ {
header : i18n.get('headers.tableName'),
dataIndex : 'tableName'
}, {
header : i18n.get('headers.columnAlias'),
dataIndex : 'columnAlias'
}],
defaults : {
sortable : true,
width : 100
}
});
this.smColumns = new Ext.grid.RowSelectionModel({
singleSelect : true
});
this.gridColumns = new Ext.grid.EditorGridPanel({
id : 'gridColumnsSelect',
title : i18n.get('title.gridColumns'),
layout : 'fit',
height : 280,
view : this.gridViewColumns,
autoScroll : true,
store : this.storeColumns,
cm : this.cmColumns,
sm : this.smColumns
});
var storeDatasets = new Ext.data.JsonStore({
fields : [ 'id', 'name', 'sitoolsAttachementForUsers' ],
url : this.urlDatasets,
root : "data",
autoLoad : true,
listeners : {
scope : this,
load : function () {
if (!Ext.isEmpty(this.selectedRecord.data.datasetDetailUrl)) {
this.comboDatasets.setValue(this.selectedRecord.data.datasetDetailUrl);
this.loadColumns(this.selectedRecord.data.datasetDetailUrl);
}
}
}
});
this.comboDatasets = new Ext.form.ComboBox({
store : storeDatasets,
displayField : 'name',
valueField : 'sitoolsAttachementForUsers',
typeAhead : true,
mode : 'local',
forceSelection : true,
triggerAction : 'all',
emptyText : 'Select a dataset...',
selectOnFocus : true,
listeners : {
scope : this,
select : function (combo, rec, index) {
this.loadColumns(rec.data.id);
}
}
});
this.formImage = new Ext.form.FormPanel({
layout : 'fit',
title : i18n.get('label.formImage'),
height : 80,
items : [{
xtype : 'sitoolsSelectImage',
name : 'image',
vtype : "image",
fieldLabel : i18n
.get('label.image'),
anchor : '100%',
growMax : 400
}]
});
var items = [ this.comboDatasets, this.gridColumns];
if (this.withImage) {
this.height += 80;
items.push(this.formImage);
}
this.items = [ {
xtype : 'panel',
layout : 'fit',
title : i18n.get('label.datasetSelect'),
items : items,
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ]
} ];
sitools.admin.datasets.datasetUrlWin.superclass.initComponent.call(this);
},
/**
* Load the selectedRecord if not empty
*/
afterRender : function () {
sitools.admin.datasets.datasetUrlWin.superclass.afterRender.apply(this, arguments);
if (!Ext.isEmpty(this.selectedRecord) && !Ext.isEmpty(this.selectedRecord.data) && !Ext.isEmpty(this.selectedRecord.data.image)) {
var rec = {};
var form = this.formImage.getForm();
rec.image = this.selectedRecord.data.image.url;
form.loadRecord(new Ext.data.Record(rec));
}
},
/**
* Load the columns of a specific dataset
* @param {String} datasetId (required) the dataset Id
*/
loadColumns : function (datasetId) {
// alert (dictionaryId);
this.httpProxy.setUrl(this.urlDatasets + "/" + datasetId);
this.gridColumns.getStore().load({
callback : function () {
this.gridColumns.getView().refresh();
},
scope : this
});
},
/**
* When click on button ok.
* Validate the link.
*/
onValidate : function () {
var rec = this.gridColumns.getSelectionModel().getSelected();
this.selectedRecord.data.datasetDetailUrl = this.comboDatasets.getValue();
this.selectedRecord.data.columnAliasDetail = rec.data.columnAlias;
var form = this.formImage.getForm();
var image = form.findField("image").getValue();
if (!Ext.isEmpty(image)) {
this.selectedRecord.data.image = {};
this.selectedRecord.data.image.url = image;
this.selectedRecord.data.image.type = "Image";
this.selectedRecord.data.image.mediaType = "Image";
}
this.gridView.refresh();
this.close();
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
//
// Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
//
// This file is part of SITools2.
//
// SITools2 is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// SITools2 is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with SITools2. If not, see <http://www.gnu.org/licenses/>.
//
/*global Ext, sitools, ID, i18n, document, showResponse*/
Ext.namespace('sitools.admin.datasets');
/**
* @cfg {String} action (required) should be 'create' or 'modifiy'
* @cfg {Ext.data.JsonStore} store (required) the store of the columns of the dataset
* @cfg {Ext.data.Record} recordColumn (required) the selected record
* @class sitools.admin.datasets.columnsPropPanel
* @extends Ext.Window
*/
sitools.admin.datasets.columnsPropPanel = Ext.extend(Ext.Window, {
width : 600,
height : 300,
modal : true,
id : 'columnPropId',
dataSets : "",
initComponent : function () {
this.title = i18n.get('label.details');
var data = this.datasourceUtils.getColumnsType();
var comboStore = new Ext.data.ArrayStore({
fields : [ 'value', 'display' ],
data : data
});
this.comboColumnType = new Ext.form.ComboBox({
store : comboStore,
mode : 'local',
fieldLabel : i18n.get('label.specificColumnType'),
typeAhead : true,
triggerAction : 'all',
forceSelection : true,
selectOnFocus : true,
lazyRender : true,
listClass : 'x-combo-list-small',
valueField : 'value',
displayField : 'display',
anchor : '90%',
value : this.datasourceUtils.isJdbc ? 'SQL' : 'DATABASE',
listeners : {
scope : this,
change : function (field, newValue, oldValue) {
if (newValue === 'SQL' || newValue === "DATABASE") {
this.sqlDef.setDisabled(false);
} else {
this.sqlDef.setDisabled(true);
}
}
}
});
this.columnAlias = new Ext.form.TextField({
fieldLabel : i18n.get('label.columnAlias'),
anchor : '90%',
validator : function (v) {
var re = new RegExp("^.*[!\"#$%&\'/()*+,:;<=>?@\\`{}|~]+.*$");
if (!re.test(v)) {
return !re.test(v);
}
else {
return i18n.get('label.invalidColumnAlias');
}
}
});
this.sqlDef = new Ext.form.TextArea({
fieldLabel : i18n.get('label.SQLDefinition'),
anchor : '90%'
});
var storeColumnType = new Ext.data.JsonStore({
fields : ['name'],
data : JAVA_TYPES
});
this.sqlColumnType = new Ext.form.ComboBox({
store : storeColumnType,
mode : 'local',
fieldLabel : i18n.get('label.columnType'),
typeAhead : true,
triggerAction : 'all',
forceSelection : true,
selectOnFocus : true,
lazyRender : true,
listClass : 'x-combo-list-small',
valueField : 'name',
displayField : 'name',
anchor : '90%',
value : "String"
});
this.items = [ {
xtype : 'panel',
height : 250,
items : [ {
xtype : 'form',
border : false,
labelWidth : 150,
padding : 10,
defaults : {
disabled : false
},
items : [ this.comboColumnType, this.columnAlias, this.sqlDef, this.sqlColumnType]
} ],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : function () {
this.onValidate();
}
}, {
text : i18n.get('label.close'),
scope : this,
handler : function () {
this.close();
}
} ]
} ];
sitools.admin.datasets.columnsPropPanel.superclass.initComponent.call(this);
},
/**
* load value depends on action value
* @inheritdoc
* @method
*/
onRender : function () {
sitools.admin.datasets.columnsPropPanel.superclass.onRender.apply(this, arguments);
if (this.action == 'modify') {
this.comboColumnType.setValue(this.recordColumn.get('specificColumnType'));
this.columnAlias.setValue(this.recordColumn.get('columnAlias'));
this.sqlDef.setValue(this.recordColumn.get('dataIndex'));
this.sqlColumnType.setValue(this.recordColumn.get('sqlColumnType'));
// f.loadRecord (this.recordColumn);
}
},
/**
* Validate the changes.
* <li>on modify mode : change the record value</li>
* <li>on create mode : create a new Record in the store given as config</li>
* @method
*/
onValidate : function () {
if (this.action == 'modify') {
this.recordColumn.set('specificColumnType', this.comboColumnType.getValue());
this.recordColumn.set('columnAlias', this.columnAlias.getValue());
this.recordColumn.set('dataIndex', this.sqlDef.getValue());
this.recordColumn.set('sqlColumnType', this.sqlColumnType.getValue());
} else {
var rec;
if (this.comboColumnType.getValue() == 'DATABASE') {
rec = new Ext.data.Record({
dataIndex : this.sqlDef.getValue(),
specificColumnType : this.comboColumnType.getValue(),
header : this.columnAlias.getValue(),
columnAlias : this.columnAlias.getValue(),
width : 100,
visible : true,
sortable : true,
tableName : "",
tableAlias : "",
sqlColumnType : this.sqlColumnType.getValue()
});
}
if (this.comboColumnType.getValue() == 'SQL') {
rec = new Ext.data.Record({
dataIndex : this.sqlDef.getValue(),
specificColumnType : this.comboColumnType.getValue(),
header : this.columnAlias.getValue(),
columnAlias : this.columnAlias.getValue(),
width : 100,
visible : true,
sortable : true,
tableName : "",
tableAlias : "",
sqlColumnType : this.sqlColumnType.getValue()
});
}
if (this.comboColumnType.getValue() === "VIRTUAL") {
rec = new Ext.data.Record({
specificColumnType : this.comboColumnType.getValue(),
header : this.columnAlias.getValue(),
columnAlias : this.columnAlias.getValue(),
width : 100,
visible : true,
sortable : true,
tableName : "",
tableAlias : ""
});
}
this.store.add(rec);
}
this.close();
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, loadUrl, ADMIN_PANEL_HEIGHT, ADMIN_PANEL_NB_ELEMENTS */
/*
*@include "datasetsMultiTablesProp.js"
*@include "../../../public/js/env.js"
*/
Ext.namespace('sitools.admin.datasets');
/**
* Displays the list of all the datasets in the Administration
* @class sitools.admin.datasets.datasetsCrudPanel
* @extends Ext.grid.GridPanel
*/
//sitools.component.datasets.datasetsCrudPanel = Ext.extend(Ext.grid.GridPanel, {
sitools.admin.datasets.datasetsCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : ADMIN_PANEL_HEIGHT,
id : ID.BOX.DATASETS,
sm : new Ext.grid.RowSelectionModel(),
pageSize : ADMIN_PANEL_NB_ELEMENTS,
viewConfig : {
forceFit : true,
autoFill : true,
getRowClass : function (row, index) {
var cls = '';
var data = row.data;
if (data.dirty == "true") {
cls = "red-row";
}
return cls;
}
},
// loadMask: true,
initComponent : function () {
this.url = loadUrl.get('APP_URL') + loadUrl.get('APP_DATASETS_URL');
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
remoteSort : true,
url : this.url,
// sortField: 'name',
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'status',
type : 'string'
}, {
name : 'dirty',
type : 'string'
} ]
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : false
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100,
sortable : true
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 350
}, {
header : i18n.get('label.status'),
dataIndex : 'status',
width : 90,
sortable : true
} ]
});
this.bbar = {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
};
var buttons = [];
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this,
xtype : 's-menuButton'
},
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreate
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this.onEdit
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDelete
}, {
text : i18n.get('label.opensearch'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_open_search.png',
handler : this.onEditOpenSearch
}, {
text : i18n.get('label.refresh'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_refresh.png',
handler : this._onRefresh
}, {
text : i18n.get('label.active'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_active.png',
handler : this._onActive
}, {
text : i18n.get('label.disactive'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_disactive.png',
handler : this._onDisactive
}, {
text : i18n.get('label.sqlString'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/sql_request.png',
handler : this._getSqlString
}, {
text : i18n.get('label.semantic'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/tree_dictionary.png',
handler : this._onEditSemantic
}, {
text : i18n.get('label.duplicate'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this.onDuplicate
}, '->', {
xtype : 's-filter',
emptyText : i18n.get('label.search'),
store : this.store,
pageSize : this.pageSize
} ]
};
this.listeners = {
scope : this,
rowDblClick : this.onEdit
};
sitools.admin.datasets.datasetsCrudPanel.superclass.initComponent.call(this);
},
/**
* Called when double click on a dataset, or the edit Button
* Will open {@link sitools.component.datasets.datasetsMultiTablesPanel} window.
* @method
* @return {}
*/
onEdit : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
if (rec.data.status == "ACTIVE") {
this.onView();
}
else {
this.onModify();
}
},
/**
* Called when click on duplicate Button
* Will open {@link sitools.component.datasets.datasetsMultiTablesPanel} window.
* @method
* @return {}
*/
onDuplicate : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.component.datasets.datasetsMultiTablesPanel({
datasetUrlToCopy : this.url + "/" + rec.id,
action : 'duplicate',
store : this.getStore(),
url : this.url
});
up.show(ID.BOX.DATASETS);
},
/**
* Load the store of the datasets when rendering the grid
* @method
*/
onRender : function () {
sitools.admin.usergroups.GroupCrudPanel.superclass.onRender.apply(this, arguments);
this.store.load({
params : {
start : 0,
limit : this.pageSize
}
});
},
/**
* Called when click on create Button
* @method
*/
onCreate : function () {
var up = new sitools.component.datasets.datasetsMultiTablesPanel({
url : this.url,
action : 'create',
store : this.getStore()
});
up.show(ID.BOX.DATASETS);
},
/**
* Called when click on view Button
* @method
*/
onView : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.component.datasets.datasetsMultiTablesPanel({
url : this.url + '/' + rec.id,
action : 'view',
store : this.getStore(),
datasetId : rec.id
});
up.show(ID.BOX.DATASETS);
},
/**
* Called when click on modify Button
* @method
*/
onModify : function () {
var rec = this.getSelectionModel().getSelected();
if (rec.data.status == i18n.get('status.active')) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.wrongStatus'));
return;
}
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.component.datasets.datasetsMultiTablesPanel({
url : this.url + '/' + rec.id,
action : 'modify',
store : this.getStore(),
datasetId : rec.id
});
up.show(ID.BOX.DATASETS);
},
/**
* Called when click on delete Button
* @method
*/
onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return false;
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('datasetCrud.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec);
}
}
});
},
/**
* Called by the onDelete method : delete the record
* @param Ext.data.Record the selected record.
* @method
*/
doDelete : function (rec) {
// var rec = this.getSelectionModel().getSelected();
// if (!rec) return false;
Ext.Ajax.request({
url : this.url + "/" + rec.id,
method : 'DELETE',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
/**
* Called when click on openSearch Button
* @method
*/
onEditOpenSearch : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.admin.datasets.datasetsOpenSearch({
url : this.url + '/' + rec.id,
action : 'edit',
store : this.getStore()
});
up.show(ID.BOX.DATASETS);
},
/**
* Called when click on refresh Button
* Execute a request on the dataset with refresh
* @method
*/
_onRefresh : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
if (rec.data.status != i18n.get("status.active")) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.wrongStatus'));
return;
}
Ext.Ajax.request({
url : this.url + '/' + rec.id + '/refresh',
method : 'PUT',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
/**
* Called when click on active Button
* @method
*/
_onActive : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.url + '/' + rec.id + '/start',
method : 'PUT',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
/**
* Called when click on disactive Button
* @method
*/
_onDisactive : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.url + '/' + rec.id + '/stop',
method : 'PUT',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
/**
* Called when click on sqlString Button
* @method
*/
_getSqlString : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.url + '/' + rec.id + '/getSqlString',
method : 'PUT',
scope : this,
success : function (ret) {
var json = Ext.decode(ret.responseText);
if (json.success) {
var winMsg = new Ext.Window({
title : i18n.get('label.sqlString'),
height : 300,
width : 500,
modal : true,
resizable : true,
autoScroll : true,
html : json.message,
buttons : [ {
text : i18n.get('label.ok'),
handler : function () {
this.ownerCt.ownerCt.close();
}
} ]
});
winMsg.show();
// Ext.Msg.alert (ret.responseText);
}
},
failure : alertFailure
});
},
/**
* Called when click on semantic Button
* @method
*/
_onEditSemantic : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.admin.datasets.DicoMapping({
url : this.url + '/' + rec.id,
masked : (rec.data.status == "ACTIVE")
});
up.show(ID.BOX.DATASETS);
}
});
Ext.reg('s-datasets', sitools.admin.datasets.datasetsCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp*/
Ext.namespace('sitools.admin.datasets');
/**
* @deprecated
* @class sitools.admin.datasets.dictionaryWin
* @extends Ext.Window
*/
//sitools.component.datasets.dictionaryWin = Ext.extend(Ext.Window, {
sitools.admin.datasets.dictionaryWin = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
pageSize : 10,
initComponent : function () {
this.title = i18n.get('label.dictionary');
this.httpProxy = new Ext.data.HttpProxy({
url : this.urlDictionary,
restful : true,
method : 'GET'
});
this.storeNotion = new Ext.data.JsonStore({
id : 'storeNotionSelect',
root : 'dictionary.notions',
idProperty : 'id',
proxy : this.httpProxy,
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'unit',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'type',
type : 'string'
}, {
name : 'dictionaryId',
type : 'string'
} ]
});
this.cmNotion = new Ext.grid.ColumnModel({
columns : [ {
header : i18n.get('headers.id'),
dataIndex : 'id',
width : 100
}, {
header : i18n.get('headers.name'),
dataIndex : 'name',
width : 100
}, {
header : i18n.get('headers.unit'),
dataIndex : 'unit',
width : 100
}, {
header : i18n.get('headers.type'),
dataIndex : 'type',
width : 50
}, {
header : i18n.get('headers.description'),
dataIndex : 'description',
width : 100
} ],
defaults : {
sortable : true,
width : 100
}
});
this.smNotion = new Ext.grid.RowSelectionModel({
singleSelect : true
});
this.gridNotion = new Ext.grid.EditorGridPanel({
id : 'gridNotionSelect',
title : i18n.get('title.gridNotion'),
layout : 'fit',
height : 350,
autoScroll : true,
store : this.storeNotion,
cm : this.cmNotion,
sm : this.smNotion
});
var storeDictionary = new Ext.data.JsonStore({
fields : [ 'id', 'name' ],
url : this.urlDictionary,
root : "data",
autoLoad : true
});
this.comboDictionary = new Ext.form.ComboBox({
store : storeDictionary,
displayField : 'name',
valueField : 'id',
typeAhead : true,
mode : 'local',
forceSelection : true,
triggerAction : 'all',
emptyText : 'Select a dictionary...',
selectOnFocus : true,
listeners : {
scope : this,
select : function (combo, rec, index) {
this.loadNotions(rec.data.id);
}
}
});
this.items = [ {
xtype : 'panel',
height : 450,
title : i18n.get('label.dictionarySelect'),
items : [ this.comboDictionary, this.gridNotion ],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ]
} ];
sitools.admin.datasets.dictionaryWin.superclass.initComponent.call(this);
},
loadNotions : function (dictionaryId) {
// alert (dictionaryId);
this.httpProxy.setUrl(this.urlDictionary + dictionaryId);
this.gridNotion.getStore().load({
callback : function () {
this.gridNotion.getView().refresh();
},
scope : this
});
},
onValidate : function () {
var rec = this.gridNotion.getSelectionModel().getSelected();
this.recordColumn.data.notion = rec.data;
this.recordColumn.data.notion.url = this.urlDictionary + this.comboDictionary.getValue() + "/notions/" + rec.data.id;
//this.recordColumn.data.notionDescription = rec.data.description;
this.viewColumn.refresh();
this.close();
}
});
Ext.reg('s-datasetsdictionary', sitools.admin.datasets.dictionaryWin);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp*/
Ext.namespace('sitools.admin.datasets');
/**
* @cfg Ext.data.Record recordColumn The record to edit
* @cfg Ext.grid.GridView viewColumn The grid view to refresh
* @cfg string urlDimension The Url of the dimension to get all the units.
* @class sitools.admin.datasets.unitWin
* @extends Ext.Window
*/
sitools.admin.datasets.unitWin = Ext.extend(Ext.Window, {
//sitools.component.datasets.unitWin = Ext.extend(Ext.Window, {
width : 600,
height : 400,
modal : true,
pageSize : 10,
initComponent : function () {
this.title = i18n.get('label.units');
this.httpProxy = new Ext.data.HttpProxy({
url : this.urlDimension,
restful : true,
method : 'GET'
});
this.storeUnits = new Ext.data.JsonStore({
id : 'storeUnitSelect',
root : 'dimension.sitoolsUnits',
idProperty : 'id',
proxy : this.httpProxy,
fields : [ {
name : 'label',
type : 'string'
}, {
name : 'unitName',
type : 'string'
}]
});
this.cmUnits = new Ext.grid.ColumnModel({
columns : [ {
header : i18n.get('headers.label'),
dataIndex : 'label',
width : 100
}],
defaults : {
sortable : true,
width : 100
}
});
this.smUnits = new Ext.grid.RowSelectionModel({
singleSelect : true
});
this.gridUnits = new Ext.grid.GridPanel({
id : 'gridUnitId',
title : i18n.get('title.unitList'),
autoScroll : true,
store : this.storeUnits,
cm : this.cmUnits,
sm : this.smUnits,
region : "center"
});
var storeDimensions = new Ext.data.JsonStore({
fields : [ 'id', 'name', 'description' ],
url : this.urlDimension,
root : "data",
autoLoad : true
});
this.cmDimensions = new Ext.grid.ColumnModel({
columns : [ {
header : i18n.get('headers.name'),
dataIndex : 'name',
width : 100
}, {
header : i18n.get('headers.description'),
dataIndex : 'description',
width : 100
}],
defaults : {
sortable : true,
width : 100
}
});
this.smDimensions = new Ext.grid.RowSelectionModel({
singleSelect : true
});
this.gridDimensions = new Ext.grid.GridPanel({
id : 'gridViewDimensionsId',
title : i18n.get('title.DimensionsList'),
region : "west",
autoScroll : true,
store : storeDimensions,
cm : this.cmDimensions,
sm : this.smDimensions,
width : 200,
collapsible : true,
resizable : true,
listeners : {
scope : this,
rowclick : function (grid, rowIndex) {
var rec = grid.getStore().getAt(rowIndex);
var dimensionId = rec.get('id');
this.loadUnits(dimensionId);
}
}
});
this.layout = "border";
this.items = [this.gridUnits, this.gridDimensions ];
this.buttons = [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ];
sitools.admin.datasets.unitWin.superclass.initComponent.call(this);
},
loadUnits : function (dimensionId) {
// alert (dictionaryId);
this.httpProxy.setUrl(this.urlDimension + "/" + dimensionId);
this.storeUnits.load({
callback : function () {
this.gridUnits.getView().refresh();
},
scope : this
});
},
onValidate : function () {
var recUnit = this.gridUnits.getSelectionModel().getSelected();
if (Ext.isEmpty(recUnit)) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('label.noSelection'));
return;
}
var recDimension = this.gridDimensions.getSelectionModel().getSelected();
this.recordColumn.data.unit = recUnit.data;
this.recordColumn.data.dimensionId = recDimension.data.id;
//this.recordColumn.data.notionDescription = rec.data.description;
this.viewColumn.refresh();
this.close();
}
});
Ext.reg('s-datasetsUnits', sitools.admin.datasets.unitWin);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.admin.datasets');
/**
* Define an openSearch on a Dataset.
* @cfg {String} url (required) The url of the dataset
* @cfg {Ext.data.Store} store (required) The store that contains all datasets.
* @class sitools.admin.datasets.datasetsOpenSearch
* @extends Ext.Window
*/
//sitools.component.datasets.datasetsOpenSearch = Ext.extend(Ext.Window, {
sitools.admin.datasets.datasetsOpenSearch = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
resizable : false,
state : null,
id : ID.COMPONENT_SETUP.OPENSEARCH,
initComponent : function () {
// paramètre métier de la fenêtre
this.idOpenSearch = null;
this.title = i18n.get('label.editOpenSearchIndexes');
/*
* this.httpProxyForms = new Ext.data.HttpProxy ({ url : this.url,
* restful : true, method : 'GET' });
*/
/* paramétres du formulaire */
var itemsForm = [ {
fieldLabel : i18n.get('label.name'),
name : 'name',
anchor : '100%',
maxLength : 16, // name size must be less or equal 16 (opensearch
// 1.1 specifications)
allowBlank : false
}, {
fieldLabel : i18n.get('label.description'),
name : 'description',
anchor : '100%',
allowBlank : false
}, {
xtype : 'sitoolsSelectImage',
name : 'image',
fieldLabel : i18n.get('label.image'),
anchor : '100%',
growMax : 400
}, {
fieldLabel : i18n.get('label.lastImportDate'),
name : 'lastImportDate',
anchor : '100%',
disabled : true
} ];
this.formPanel = new Ext.FormPanel({
labelWidth : 100, // label settings here cascade unless overridden
height : 120,
frame : true,
defaultType : 'textfield',
items : itemsForm,
region : 'north'
});
// ########### paramètres de la grid ####### //
// définition du store pour les entrées de la grid
var store = new Ext.data.JsonStore({
root : 'dataset.columnModel',
// restful: true,
// proxy : this.httpProxyForms,
// sortField: 'name',
idProperty : 'id',
// on stocke tous les champs d'une colonne dans le store au cas ou
// on en ai besoin plus tard
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'dataIndex',
type : 'string'
}, {
name : 'width',
type : 'string'
}, {
name : 'sortable',
type : 'boolean'
}, {
name : 'visible',
type : 'boolean'
}, {
name : 'filter',
type : 'boolean'
}, {
name : 'columnOrder',
type : 'string'
}, {
name : 'columnType',
type : 'string'
}, {
name : 'notion',
type : 'string'
}, {
name : 'schema',
type : 'string'
}, {
name : 'tableName',
type : 'string'
}, {
name : 'sqlColumnType',
type : 'string'
}, {
name : "specificColumnType",
type : 'string'
}, {
name : "columnAlias",
type : "string"
}, {
name : 'indexed',
type : 'boolean'
}, {
name : 'returned'
}, {
name : 'defaultSearchField',
type : 'boolean'
}, {
name : 'uniqueKey',
type : 'boolean'
}, {
name : 'primaryKey',
type : 'boolean'
}, {
name : 'keyword',
type : 'boolean'
}, {
name : 'solrType',
type : 'string'
}, {
name : 'linkFieldRelative',
type : 'boolean'
} ]
// ,
// autoLoad : true
});
// colonne avec checkbox pour choisir quelles colonnes indexer
var indexed = new Ext.grid.CheckColumn({
header : i18n.get('header.indexed'),
dataIndex : 'indexed',
width : 60
});
// colonne avec checkbox pour choisir quelle est la colonne de recherche
// par défault
var defaultSearchField = new Ext.grid.CheckColumn({
header : i18n.get('header.defaultSearchField'),
dataIndex : 'defaultSearchField',
width : 120
});
// colonne avec checkbox pour choisir quelle colonne est la clé primaire
var uniqueKey = new Ext.grid.CheckColumn({
header : i18n.get('header.uniqueKey'),
dataIndex : 'uniqueKey',
width : 80
});
// colonne avec checkbox pour choisir quelles colonnes sont utilisées
// pour l'autocompletion mots clés
var keyWords = new Ext.grid.CheckColumn({
header : i18n.get('header.useForKeyWord'),
dataIndex : 'keyword',
width : 80
});
// définition des champs d'un flux RSS pour le retour des données
this.rssFieldData = [ [ 0, "" ], [ 1, 'titleField' ], [ 2, 'linkField' ], [ 3, 'guidField' ], [ 4, 'pubDateField' ], [ 5, 'descriptionField' ] ];
// définition de la combobox pour choisir le champs pour le retour des
// données
var returned = {
header : i18n.get('header.returned'),
dataIndex : 'returned',
width : 130,
scope : this,
// définition de la combobox
editor : new Ext.form.ComboBox({
typeAhead : true,
triggerAction : 'all',
lazyRender : true,
lazyInit : false,
mode : 'local',
emptyText : " ",
// on force la selection pour que l'utilisateur ne puisse pas
// saisir de valeur au clavier
forceSelection : true,
store : new Ext.data.ArrayStore({
fields : [ 'idRssField', 'textRssField' ],
// utilisation des donnees definie precedement
data : this.rssFieldData
}),
valueField : 'textRssField',
displayField : 'textRssField',
// template pour les items de la combobox, permet d'ajouter une
// classe CSS a chacun des items
tpl : '<tpl for="."><div class="x-combo-list-item comboItem">{textRssField}</div></tpl>',
listeners : {
scope : this,
select : function (combo, record) {
if (record.data.textRssField == "linkField") {
var tmp = new sitools.admin.datasets.datasetsOpenSearch.relativeLink({
selectedRecord : this.grid.getSelectionModel().getSelected()
});
tmp.show();
}
}
}
})
};
// définition des type solr
this.solrTypeData = [ [ 0, "" ], [1, 'text' ], [ 2, 'text_ws' ], [ 3, 'string' ], [ 4, 'rss_date' ], [ 5, 'date' ] ];
// définition de la combobox pour choisir le champs pour le retour des
// données
var solrType = {
header : i18n.get('headers.solrType'),
dataIndex : 'solrType',
width : 130,
helpUrl : loadUrl.get('APP_URL') + "/client-admin/res/help/" + LOCALE + "/dataset/opensearch/solrType.html",
// définition de la combobox
editor : new Ext.form.ComboBox({
triggerAction : 'all',
mode : 'local',
emptyText : " ",
store : new Ext.data.ArrayStore({
fields : [ 'idSolrType', 'textSolrType' ],
// utilisation des donnees definie precedement
data : this.solrTypeData
}),
valueField : 'textSolrType',
displayField : 'textSolrType',
// template pour les items de la combobox, permet d'ajouter une
// classe CSS a chacun des items
tpl : '<tpl for="."><div class="x-combo-list-item comboItem">{textSolrType}</div></tpl>'
})
};
// définition du columnModel
var cm = new Ext.ux.grid.LockingColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are sortable by default
},
columns : [ {
header : i18n.get('label.name'),
id : 'dataIndex',
dataIndex : 'columnAlias',
locked : true
}, {
header : i18n.get('headers.tableName'),
id : 'tableName',
dataIndex : 'tableName',
locked : true
}, indexed, returned, defaultSearchField, uniqueKey, keyWords, solrType ]
});
// définition des plugins nécessaires (colonnes avec checkbox )
var plugins = [ indexed, defaultSearchField, uniqueKey, keyWords];
var smColumn = new Ext.grid.RowSelectionModel({
singleSelect : true
});
// instantiation du grid
this.grid = new Ext.ux.grid.LockingEditorGridPanel({
border : false,
layout : 'fit',
pageSize : 10,
urlDatasets : loadUrl.get('APP_URL') + loadUrl.get('APP_DATASETS_URL'),
cm : cm,
sm : smColumn,
store : store,
plugins : plugins,
autoExpandColumn : "dataIndex",
clicksToEdit : 1,
enableColumnMove : false,
region : 'center',
viewConfig : {
forceFit : true,
autoFill : true,
getRowClass : function (row, index) {
var cls = '';
var data = row.data;
if (!data.indexed && !Ext.isEmpty(data.returned)) {
cls = "red-row";
}
return cls;
}
}
});
this.layout = 'border';
// ajout du grid dans la fenêtre
this.items = [ this.formPanel, this.grid ];
this.saveAndQuitButton = new Ext.Button({
text : i18n.get('label.save'),
scope : this,
hidden : true
});
this.refreshStatusButton = new Ext.Button({
text : i18n.get('label.refreshStatus'),
scope : this,
handler : function () {
this._onRefreshStatusHandler();
},
hidden : true
});
this.buttonCancel = new Ext.Button({
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this._onCancel();
},
hidden : true
});
// ajout des boutons dans la fenetre
this.buttons = [ this.saveAndQuitButton, this.refreshStatusButton, this.buttonCancel, {
text : i18n.get('label.close'),
scope : this,
handler : function () {
this.close();
}
} ];
// définition des différents boutons en fonction des états
this.buttonState1 = [ {
text : i18n.get('label.saveIndex'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/save.png',
handler : this._onSaveIndexHandler,
xtype : 's-menuButton'
}, {
text : i18n.get('label.help'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/help.png',
handler : this._onHelp,
xtype : 's-menuButton'
} ];
this.buttonState2 = [ {
text : i18n.get('label.saveIndex'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/save.png',
handler : this._onUpdateIndexHandler,
xtype : 's-menuButton'
}, {
text : i18n.get('label.deleteIndex'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this._onDeleteIndex,
xtype : 's-menuButton'
}, {
text : i18n.get('label.activateIndex'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_active.png',
handler : this._onActivateIndex,
xtype : 's-menuButton'
}, {
text : i18n.get('label.help'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/help.png',
handler : this._onHelp,
xtype : 's-menuButton'
} ];
this.buttonState3 = [];
this.buttonState4 = [ {
text : i18n.get('label.refreshIndex'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_refresh.png',
handler : this._onRefreshIndex,
xtype : 's-menuButton'
}, {
text : i18n.get('label.desactivateIndex'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_disactive.png',
handler : this._onDesactivateIndex,
xtype : 's-menuButton'
}, {
text : i18n.get('label.help'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/help.png',
handler : this._onHelp,
xtype : 's-menuButton'
} ];
// définition des constantes pour la définition des états
//edition de l'opensearch
this.state1 = 1;
//opensearch créé
this.state2 = 2;
//opensearch en cours d'indexation
this.state3 = 3;
//opensearch activé
this.state4 = 4;
// instantiation de la toolbar
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
height : 27
};
this.buttonbbar = new Ext.Button({
text : i18n.get("label.errorDetails")
});
this.bbar = new Ext.ux.StatusBar({
id: 'statusBar',
hidden : true,
items : [this.buttonbbar],
text: i18n.get("label.osErrorLastExe"),
iconCls: 'x-status-error'
});
this.grid.getView().addListener("refresh", function () {
this.applyMask(this.state);
}, this);
sitools.admin.datasets.datasetsOpenSearch.superclass.initComponent.call(this);
},
/**
* @method
* On render, load the dataset values requesting the Dataset Url .
* Call loadModification if success.
*/
onRender : function () {
sitools.admin.datasets.datasetsOpenSearch.superclass.onRender.apply(this, arguments);
this.objectList = {};
// vérification d'un index existant
// sinon on charge le dataset
Ext.Ajax.request({
url : this.url,
method : 'GET',
scope : this,
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (!data.success) {
Ext.Msg.alert(i18n.get('label.warning'), data.message);
return false;
}
this.idOpenSearch = data.dataset.id;
var dataIndexList = data.dataset.columnModel;
var store = this.grid.getStore();
for (var i = 0; i < dataIndexList.length; i++) {
// on stocke l'ensemble des colonnes d'un dataset de
// specificColumnType DATABASE
if (dataIndexList[i].specificColumnType === "DATABASE" || dataIndexList[i].specificColumnType === "SQL") {
store.add(new Ext.data.Record(dataIndexList[i]));
}
}
// on charge les valeurs de l'index s'il y en a déjà un
this.loadModifications();
}
});
},
/**
* @method
* if exists, load the index values
* on Success will call updateState, populateForm, populateStore
*/
loadModifications : function () {
Ext.Ajax.request({
url : this.url + loadUrl.get('APP_OPENSEARCH_URL'),
method : 'GET',
scope : this,
// si index existe on le charge
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (!data.success) {
Ext.Msg.alert(i18n.get('label.information'), "Server error");
return false;
}
data = data.opensearch;
this.updateState(data);
this.populateForm(data);
this.populateStore(data);
},
// si on a une erreur serveur
failure : alertFailure
});
},
/**
* Will populate the store of the grid
* @param {} data (required) The index request data.
*/
populateStore : function (data) {
this.cleanGridInput();
if (data !== undefined) {
var i;
var valueObject;
var dataColumnIndex = data.indexedColumns;
if (dataColumnIndex !== undefined) {
for (i = 0; i < dataColumnIndex.length; i++) {
valueObject = this.getObjectFromStore("id", dataColumnIndex[i].idColumn);
if (valueObject !== undefined) {
valueObject.indexed = true;
valueObject.solrType = dataColumnIndex[i].type;
}
}
}
var keyword = data.keywordColumns;
if (keyword !== undefined) {
for (i = 0; i < keyword.length; i++) {
valueObject = this.getObjectFromStore("columnAlias", keyword[i]);
if (valueObject !== undefined) {
valueObject.keyword = true;
}
}
}
// set defaultSearchField value
valueObject = this.getObjectFromStore("id", data.defaultSearchField);
if (valueObject !== undefined) {
valueObject.defaultSearchField = true;
}
// set uniqueKey value
valueObject = this.getObjectFromStore("id", data.uniqueKey);
if (valueObject !== undefined) {
valueObject.uniqueKey = true;
}
this.setReturnField("titleField", data);
this.setReturnField("linkField", data);
this.setReturnField("guidField", data);
this.setReturnField("pubDateField", data);
this.setReturnField("descriptionField", data);
if (keyword !== undefined) {
for (i = 0; i < keyword.length; i++) {
valueObject = this.getObjectFromStore("dataIndex", keyword[i]);
if (valueObject !== undefined) {
valueObject.keyword = true;
}
}
}
this.grid.getView().refresh();
}
},
/**
*
* @param {} data (required) The index request data.
*/
updateState : function (data) {
Ext.getCmp('statusBar').hide();
if (data !== undefined) {
// check if the index is activated or not
if (data.status == "ACTIVE") {
this.updateButtons(this.state4);
this.state = this.state4;
} else if (data.status == "PENDING") {
this.updateButtons(this.state3);
this.state = this.state3;
} else {
this.updateButtons(this.state2);
this.state = this.state2;
if (!Ext.isEmpty(data.errorMsg)) {
/*
* Ext.Msg.alert(i18n.get("msg.error"), i18n
* .get("label.osErrorLastExe") + "<BR/>" + data.errorMsg + "<BR/>" +
* i18n.get("label.checkLogMoreInfo"));
*/
Ext.getCmp('statusBar').show();
this.buttonbbar.setHandler(function () {
Ext.Msg
.alert(
i18n.get("msg.error"),
i18n
.get("label.osErrorLastExe")
+ "<BR/>"
+ data.errorMsg
+ "<BR/>"
+ i18n
.get("label.checkLogMoreInfo"));
});
}
}
} else {
this.updateButtons(this.state1);
this.state = this.state1;
}
},
/**
* load the main form with requested data
* @param {} data (required) The index request data.
*/
populateForm : function (data) {
if (data !== undefined) {
var form = this.formPanel.getForm();
var rec = {};
rec.name = data.name;
rec.description = data.description;
if (data.image !== undefined) {
rec.image = data.image.url;
}
if (data.lastImportDate !== undefined) {
rec.lastImportDate = data.lastImportDate;
}
var record = new Ext.data.Record(rec);
form.loadRecord(record);
}
},
/**
* retourne l'objet de type field et de valeur value présente dans le store
* retourne undefined si l'objet n'est pas trouve
* @param {String} field the field to get
* @param {} value the value to look for
* @return {}
*/
getObjectFromStore : function (field, value) {
var store = this.grid.getStore();
var index = store.find(field, value);
if (index != -1) {
var valueObject = store.getAt(index);
return valueObject.data;
} else {
return undefined;
}
},
/**
*
* @param {} field
* @param {} data
*/
setReturnField : function (field, data) {
var store = this.grid.getStore();
if (data[field] !== undefined) {
var valueObject = this.getObjectFromStore("id", data[field]);
if (valueObject !== undefined) {
valueObject.returned = field;
if (field == "linkField") {
valueObject.linkFieldRelative = data.linkFieldRelative;
}
}
}
},
/**
* met à jour les boutons en fonction des actions de l'utilisateur
* @param {} state
*/
updateButtons : function (state) {
var tb = this.getTopToolbar();
tb.removeAll();
this.hideLoadingMask();
this.applyMask(state);
if (state == this.state1) {
this.addButtonToToolbar(tb, this.buttonState1);
this.saveAndQuitButton.setHandler(this._onSaveAndQuitIndexHandler, this);
this.saveAndQuitButton.show();
this.refreshStatusButton.hide();
this.buttonCancel.hide();
} else if (state == this.state2) {
this.addButtonToToolbar(tb, this.buttonState2);
this.saveAndQuitButton.show();
this.saveAndQuitButton.setHandler(this._onUpdateAndQuitIndexHandler, this);
this.refreshStatusButton.hide();
this.buttonCancel.hide();
} else if (state == this.state3) {
this.addButtonToToolbar(tb, this.buttonState2);
this.saveAndQuitButton.hide();
this.refreshStatusButton.show();
this.buttonCancel.show();
} else if (state == this.state4) {
this.addButtonToToolbar(tb, this.buttonState4);
this.saveAndQuitButton.hide();
this.refreshStatusButton.hide();
this.buttonCancel.hide();
}
this.doLayout();
},
/**
* Apply a mask on all window
* @param {} state
*/
applyMask : function (state) {
if (state == this.state4) {
this.grid.getView().getLockedBody().mask();
this.grid.getView().mainBody.mask();
this.formPanel.getEl().mask();
} else if (state == this.state3) {
this.applyLoadingMask();
} else {
this.grid.getView().getLockedBody().unmask();
this.grid.getView().mainBody.unmask();
this.formPanel.getEl().unmask();
}
this.doLayout();
},
/**
* Apply a loading Mask on grid
*/
applyLoadingMask : function () {
this.items.items[0].getEl().mask();
this.getTopToolbar().getEl().mask();
var myMask = new Ext.LoadMask(this.items.items[1].getEl(), {
msg : i18n.get("label.waitForActivation") + "<br/>" + i18n.get("label.refreshOsToCheckStatus")
});
myMask.show();
},
/**
* hide loadingMask
*/
hideLoadingMask : function () {
this.items.items[0].getEl().unmask();
this.items.items[1].getEl().unmask();
this.getTopToolbar().getEl().unmask();
},
/**
* ajoute les boutons a la top bar tb = la top bar buttonStates = la liste
* des boutons a ajouter
*/
addButtonToToolbar : function (tb, buttonStates) {
for (var i = 0; i < buttonStates.length; i++) {
tb.add(buttonStates[i]);
}
},
// action d'activer un index
_onActivateIndex : function () {
this.applyLoadingMask();
Ext.Ajax.request({
url : this.url + loadUrl.get('APP_OPENSEARCH_URL') + "/start",
method : 'PUT',
scope : this,
//timeout : 300000,
/*listeners : {
beforerequest : function (conn, options) {
this.getEl().mask();
}
},*/
success : function (ret) {
var getData = Ext.decode(ret.responseText);
if (!getData.success) {
Ext.Msg.alert(i18n.get('label.warning'),
getData.message);
return false;
}
var data = getData.opensearch;
this.updateState(data);
this.populateForm(data);
this.populateStore(data);
},
failure : function (response, opts) {
alertFailure(response, opts);
//myMask.hide();
}
});
},
// action de desactiver un index
_onDesactivateIndex : function () {
Ext.Ajax.request({
url : this.url + loadUrl.get('APP_OPENSEARCH_URL') + "/stop",
method : 'PUT',
scope : this,
success : function (ret) {
var getData = Ext.decode(ret.responseText);
if (!getData.success) {
Ext.Msg.alert(i18n.get('label.warning'), getData.message);
return false;
}
var data = getData.opensearch;
this.updateState(data);
this.populateForm(data);
this.populateStore(data);
},
failure : alertFailure
});
// envoyer requète au serveur
},
// handler to modify the index and quit
_onUpdateAndQuitIndexHandler : function () {
this._onSaveIndex("update", true);
},
// handler to create the index and quit
_onSaveAndQuitIndexHandler : function () {
this._onSaveIndex("create", true);
},
// handler to modify the index
_onUpdateIndexHandler : function () {
this._onSaveIndex("update", false);
},
// handler to create the index
_onSaveIndexHandler : function () {
this._onSaveIndex("create", false);
},
_onHelp : function () {
showHelp(loadUrl.get('APP_URL') + '/client-admin/res/help/en/openSearch.html');
},
// fonction de génération de l'index
// envoi au serveur la liste des colonnes à indexer et des colonnes à
// retourner
// le paramètre verbose permet de spécifier si la fenetre doit se fermer a
// la fin de l'execution
_onSaveIndex : function (action, quit) {
var storeGrid = this.grid.getStore();
// récupère un potentiel doublon dans le choix des colonnes à retourner
var doublonValue = this.checkForDoubloon(this.rssFieldData, storeGrid, "returned");
// notify the errors
if (doublonValue !== null) {
Ext.Msg.alert(i18n.get('label.information'), i18n.get('label.doubloonReturnAsMsg') + doublonValue);
return false;
}
var gridView = this.grid.getView();
var colReturnedButNotIndex = false;
// var to store indexed column
var listIndex = [];
// var to store keyword column
var keywordIndex = [];
// var to store the JSON to be send
var returnedJSON = {};
for (var i = 0; i < storeGrid.getCount(); i++) {
var rec = storeGrid.getAt(i).data;
if (rec.indexed) {
var indexColumn = {};
indexColumn.idColumn = rec.id;
if (!Ext.isEmpty(rec.solrType) && rec.solrType !== "") {
indexColumn.type = rec.solrType;
}
listIndex.push(indexColumn);
}
if (rec.keyword) {
keywordIndex.push(rec.columnAlias);
}
if (rec.defaultSearchField) {
returnedJSON.defaultSearchField = rec.id;
}
if (rec.uniqueKey) {
returnedJSON.uniqueKey = rec.id;
}
var tmp = rec.returned;
if (!Ext.isEmpty(rec.returned)) {
returnedJSON[rec.returned] = rec.id;
if (!rec.indexed) {
colReturnedButNotIndex = true;
}
if (rec.returned == "linkField") {
returnedJSON.linkFieldRelative = rec.linkFieldRelative;
}
}
}
if (colReturnedButNotIndex) {
Ext.Msg.alert(i18n.get('label.information'), i18n.get('label.osColReturnedButNotIndexed'));
return false;
}
returnedJSON.indexedColumns = listIndex;
returnedJSON.keywordColumns = keywordIndex;
returnedJSON.id = this.idOpenSearch;
// store the form fields
var form = this.formPanel.getForm();
Ext.iterate(form.getValues(), function (key, value) {
if (key == 'image') {
// TODO : définir une liste de mediaType et type
returnedJSON.image = {};
returnedJSON.image.url = value;
returnedJSON.image.type = "Image";
returnedJSON.image.mediaType = "Image";
} else {
returnedJSON[key] = value;
}
}, this);
if (listIndex.length === 0) {
Ext.Msg.alert(i18n.get('label.information'), i18n.get('label.noColumnMsg'));
} else if (returnedJSON.defaultSearchField === undefined) {
Ext.Msg.alert(i18n.get('label.information'), i18n.get('label.noDefaultSearchField'));
} else if (returnedJSON.uniqueKey === undefined) {
Ext.Msg.alert(i18n.get('label.information'), i18n.get('label.noUniqueKey'));
}
// check if the the form is valid before sending to the server
else if (!form.isValid()) {
Ext.Msg.alert(i18n.get('label.information'), i18n.get('label.formErrorValidation'));
}
// vérifie si tout les champs rss sont mappés
var checkMapping = this.checkMapping(this.rssFieldData, storeGrid, "returned");
// notify the errors
if (!checkMapping) {
var tot = Ext.Msg.show({
title : i18n.get('label.information'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('label.opensearch.checkMapping'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this._doSaveIndex(action, quit, returnedJSON);
}
}
});
} else {
this._doSaveIndex(action, quit, returnedJSON);
}
},
_doSaveIndex : function (action, quit, returnedJSON) {
// if no error send the request
// set the method depending on the action needed
// POST = create
// PUT = modify
var method = (action == "create") ? "POST" : "PUT";
Ext.Ajax.request({
url : this.url + loadUrl.get('APP_OPENSEARCH_URL'),
method : method,
scope : this,
jsonData : returnedJSON,
success : function (ret) {
// check for the success of the request
var data = Ext.decode(ret.responseText);
if (!data.success) {
Ext.Msg.alert(i18n.get('label.warning'), data.message);
return false;
}
if (!quit) {
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('label.indexSaved'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
// update the buttons state
this.updateButtons(this.state2);
} else {
this.close();
}
},
failure : alertFailure
});
},
// handler to delete an opensearch index
_onDeleteIndex : function () {
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('label.opensearch.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete();
}
}
});
},
// method to delete an opensearch index
doDelete : function () {
Ext.Ajax.request({
url : this.url + loadUrl.get('APP_OPENSEARCH_URL'),
method : 'DELETE',
scope : this,
success : function (ret) {
// check if the request was successfull
var Json = Ext.decode(ret.responseText);
if (!Json.success) {
Ext.Msg.alert(i18n.get('label.warning'), Json.message);
return;
}
this.cleanGridInput();
this.cleanForm();
this.updateButtons(this.state1);
},
failure : alertFailure
});
},
cleanGridInput : function () {
// update the store to clean the datas
var storeGrid = this.grid.getStore();
for (var i = 0; i < storeGrid.getCount(); i++) {
var rec = storeGrid.getAt(i).data;
rec.indexed = false;
rec.returned = undefined;
rec.defaultSearchField = false;
rec.uniqueKey = false;
rec.keyword = false;
rec.solrType = undefined;
}
// refresh the grid
this.grid.getView().refresh();
},
cleanForm : function () {
var form = this.formPanel.getForm();
form.reset();
},
_onRefreshIndex : function () {
this.applyLoadingMask();
Ext.Ajax.request({
url : this.url + loadUrl.get('APP_OPENSEARCH_URL') + "/refresh",
method : 'PUT',
scope : this,
success : function (ret) {
var getData = Ext.decode(ret.responseText);
if (!getData.success) {
Ext.Msg.alert(i18n.get('label.warning'), getData.message);
return false;
}
var data = getData.opensearch;
this.updateState(data);
this.populateForm(data);
},
failure : function (response, opts) {
alertFailure(response, opts);
}
});
},
_onRefreshStatusHandler : function () {
Ext.Ajax.request({
url : this.url + loadUrl.get('APP_OPENSEARCH_URL'),
method : 'GET',
scope : this,
success : function (ret) {
var getData = Ext.decode(ret.responseText);
if (!getData.success) {
Ext.Msg.alert(i18n.get('label.warning'), getData.message);
return false;
}
var data = getData.opensearch;
this.updateState(data);
this.populateForm(data);
},
failure : function (response, opts) {
alertFailure(response, opts);
}
});
},
_onCancel : function () {
this.hideLoadingMask();
Ext.Ajax.request({
url : this.url + loadUrl.get('APP_OPENSEARCH_URL') + "/cancel",
method : 'PUT',
scope : this,
success : function (ret) {
var getData = Ext.decode(ret.responseText);
if (!getData.success) {
Ext.Msg.alert(i18n.get('label.warning'), getData.message);
return false;
}
//if the cancel is successfull, status is INACTIVE
var osData = {};
osData.opensearch = {};
osData.opensearch.status = "INACTIVE";
this.updateState(osData);
},
failure : function (response, opts) {
alertFailure(response, opts);
}
});
},
// vérifie s'il y a des doublons dans les choix de retour RSS
// retourne le nom du premier doublon trouvé s'il y en a un
// retourne undefined sinon
checkForDoubloon : function (data, array, field) {
var arrayCount = [data.length];
for (var i = 0; i < data.length; i++) {
arrayCount[i] = 0;
}
var doublon = null;
for (i = 0; i < array.getCount() && doublon === null; i++) {
var rec = array.getAt(i).data;
var found = false;
if (rec[field] !== "") {
for (var j = 0; j < data.length && doublon === null && !found; j++) {
if (rec[field] == data[j][1]) {
arrayCount[j]++;
found = true;
if (arrayCount[j] > 1) {
doublon = data[j][1];
}
}
}
}
}
return doublon;
},
checkMapping : function (data, array, field) {
var nbMapping = 0;
var nbFields = data.length - 1; // the first field is an empty field
for (var i = 0; i < array.getCount() && nbMapping < nbFields; i++) {
var rec = array.getAt(i).data;
if (!Ext.isEmpty(rec[field])) {
nbMapping++;
}
}
return nbMapping == nbFields;
}
});
Ext.reg('s-datasetsOpenSearch', sitools.admin.datasets.datasetsOpenSearch);
//sitools.component.datasets.datasetsOpenSearch.relativeLink = Ext.extend(Ext.Window, {
sitools.admin.datasets.datasetsOpenSearch.relativeLink = Ext.extend(Ext.Window, {
modal : true,
width : 200,
initComponent : function () {
this.title = i18n.get('label.detailColumnDefinition');
this.formRelative = new Ext.form.FormPanel({
padding : 10,
labelWidth: 120,
items : [{
xtype : 'checkbox',
name : 'relative',
fieldLabel : i18n.get('label.isRelative'),
anchor : '100%',
maxLength : 100
}]
});
this.buttons = [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
}];
this.items = [this.formRelative];
sitools.admin.datasets.datasetsOpenSearch.relativeLink.superclass.initComponent.call(this);
},
afterRender : function () {
sitools.admin.datasets.datasetsOpenSearch.relativeLink.superclass.afterRender.apply(this, arguments);
if (!Ext.isEmpty(this.selectedRecord) && !Ext.isEmpty(this.selectedRecord.data)) {
var rec = {};
var form = this.formRelative.getForm();
rec.relative = this.selectedRecord.data.linkFieldRelative;
form.loadRecord(new Ext.data.Record(rec));
}
},
onValidate : function () {
var form = this.formRelative.getForm();
var relative = form.findField("relative").getValue();
this.selectedRecord.data.linkFieldRelative = relative;
this.close();
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.component.dictionary');
sitools.component.dictionary.dictionaryPropPanel = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
pageSize : 10,
templateLoaded : false,
//the copy of the conceptTemplate contained in the dictionary (only used when action = modify)
conceptTemplate : null,
initComponent : function () {
this.conceptTemplatesUrl = loadUrl.get('APP_URL') + loadUrl.get('APP_DICTIONARIES_TEMPLATES_URL');
if (this.action == 'modify') {
this.title = i18n.get('label.modifyDictionary');
}
if (this.action == 'create') {
this.title = i18n.get('label.createDictionary');
}
this.gridTemplates = new Ext.grid.GridPanel({
viewConfig : {
forceFit : true
},
id : 'gridTemplates',
title : i18n.get('title.conceptTemplates'),
store : new Ext.data.JsonStore({
root : 'data',
restful : true,
proxy : new Ext.data.HttpProxy({
url : this.conceptTemplatesUrl,
restful : true,
method : 'GET'
}),
remoteSort : false,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'properties'
}],
autoLoad : true,
listeners : {
scope : this,
load : function () {
this.templateLoaded = true;
if (this.action == "modify") {
this.gridTemplates.fireEvent("conceptTemplateLoaded");
}
}
}
}),
cm : new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100,
sortable : true
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 300,
sortable : true
} ]
}),
listeners : {
scope : this,
rowclick : this.onTemplateClick,
conceptTemplateLoaded : function () {
if (this.templateLoaded && !Ext.isEmpty(this.conceptTemplate) && this.action == "modify" && !Ext.isEmpty(this.conceptTemplate.id)) {
var recIndex = this.gridTemplates.getStore().indexOfId(this.conceptTemplate.id);
if (recIndex > -1) {
this.gridTemplates.getSelectionModel().selectRow(recIndex);
}
}
}
}
});
//temporary panel to show the concept tab
var panelConceptTmp = new Ext.Panel({
title : i18n.get('title.gridConcept'),
id : 'gridConceptsSelect',
listeners : {
scope : this,
activate : this.onTemplateClick
}
});
this.dictionaryFormPanel = new Ext.FormPanel({
border : false,
padding : 10,
id : 'dictionaryFormPanel',
title : i18n.get('label.dictionaryInfo'),
height : 400,
items : [ {
xtype : 'hidden',
name : 'id'
}, {
xtype : 'textfield',
name : 'name',
fieldLabel : i18n.get('label.name'),
anchor : '100%',
allowBlank : false
}, {
xtype : 'textfield',
name : 'description',
fieldLabel : i18n.get('label.description'),
anchor : '100%'
} ]
});
this.mainTabPanel = new Ext.TabPanel({
xtype : 'tabpanel',
height : 450,
activeTab : 0,
id : 'tabPanelDictionary',
items : [ this.gridTemplates, this.dictionaryFormPanel, panelConceptTmp ],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ],
listeners : {
scope : this,
beforetabchange : this.beforeTabChange
}
});
this.items = [ this.mainTabPanel];
this.listeners = {
scope : this,
resize : function (window, width, height) {
var size = window.body.getSize();
this.mainTabPanel.setSize(size);
}
};
sitools.component.dictionary.dictionaryPropPanel.superclass.initComponent.call(this);
},
onUpload : function () {
// TODO gerer l'upload de fichier.
Ext.Msg.alert('upload non implémenté');
},
onCreateConcept : function () {
//create a new concept with the default values, specified in the template selected
var templateSelected;
if (Ext.isEmpty(this.conceptTemplate)) {
templateSelected = this.gridTemplates.getSelectionModel().getSelected().data;
} else {
templateSelected = this.conceptTemplate;
}
var newConcept = {};
for (var i = 0; i < templateSelected.properties.length; i++) {
var property = templateSelected.properties[i];
newConcept[property.name] = property.value;
}
this.findById('gridConceptsSelect').getStore().add(new Ext.data.Record(newConcept));
if (this.findById('gridConceptsSelect').getStore().getCount() == 1) {
this.gridTemplates.getEl().mask();
}
},
onDeleteConcet : function () {
var grid = this.findById('gridConceptsSelect');
var rec = grid.getSelectionModel().getSelected();
if (!rec) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
return;
}
grid.getStore().remove(rec);
if (this.findById('gridConceptsSelect').getStore().getCount() === 0) {
this.gridTemplates.getEl().unmask();
}
},
onValidate : function () {
var rec = this.gridTemplates.getSelectionModel().getSelected();
var tmp;
if (!rec) {
tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('warning.noTemplateselection'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
return false;
}
var f, putObject = {}, store, i;
tmp = [];
f = this.dictionaryFormPanel.getForm();
if (!f.isValid()) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.invalidForm'));
return false;
}
Ext.iterate(f.getFieldValues(), function (key, value) {
if (key == 'image') {
// TODO : definir une liste de mediaType et type
putObject.image = {};
putObject.image.url = value;
putObject.image.type = "Image";
putObject.image.mediaType = "Image";
} else {
putObject[key] = value;
}
}, this);
var templateSelected;
if (Ext.isEmpty(this.conceptTemplate)) {
templateSelected = this.gridTemplates.getSelectionModel().getSelected().data;
} else {
templateSelected = this.conceptTemplate;
}
if (!Ext.isEmpty(templateSelected)) {
putObject.conceptTemplate = templateSelected;
if (Ext.isEmpty(putObject.conceptTemplate.properties)) {
putObject.conceptTemplate.properties = [];
}
}
var gridConcept = this.findById('gridConceptsSelect');
if (!Ext.isEmpty(gridConcept) && Ext.isFunction(gridConcept.getStore)) {
store = this.findById('gridConceptsSelect').getStore();
if (store.getCount() > 0) {
putObject.concepts = [];
for (i = 0; i < store.getCount(); i++) {
var recConcept = store.getAt(i).data;
var concept = {
id : recConcept.id,
name : recConcept.name,
description : recConcept.description,
properties : []
};
for (var key in recConcept) {
if (key != "id" && key != "name"
&& key != "description") {
concept.properties.push({
name : key,
value : recConcept[key]
});
}
}
putObject.concepts.push(concept);
}
}
}
var method = (this.action == 'modify') ? "PUT" : "POST";
Ext.Ajax.request({
url : this.url,
method : method,
scope : this,
jsonData : putObject,
success : function (ret) {
this.close();
this.store.reload();
// Ext.Msg.alert(i18n.get('label.information'),
// i18n.get('msg.uservalidate'));
},
failure : alertFailure
});
},
onRender : function () {
sitools.component.dictionary.dictionaryPropPanel.superclass.onRender.apply(this, arguments);
if (this.url) {
// var gs = this.groupStore, qs = this.quotaStore;
var i;
if (this.action == 'modify') {
Ext.Ajax.request({
url : this.url,
method : 'GET',
scope : this,
success : function (ret) {
var data = Ext.decode(ret.responseText).dictionary;
//load the form
var f = this.findById('dictionaryFormPanel').getForm();
var rec = {};
rec.id = data.id;
rec.name = data.name;
rec.description = data.description;
var record = new Ext.data.Record(rec);
f.loadRecord(record);
if (!Ext.isEmpty(data.conceptTemplate)) {
//save the conceptTemplate id
this.conceptTemplate = data.conceptTemplate;
}
this.gridTemplates.fireEvent("conceptTemplateLoaded");
//first lets create the grid
this.createConceptGrid(data.conceptTemplate);
//load the concepts
if (!data.concepts) {
return;
}
var store = this.findById('gridConceptsSelect').getStore();
var nbConcepts = 0;
for (i = 0; i < data.concepts.length; i++) {
nbConcepts++;
var conceptIn = data.concepts[i];
var conceptOut = {
id : conceptIn.id,
name : conceptIn.name,
description : conceptIn.description
};
for (var j = 0; j < conceptIn.properties.length; j++) {
var property = conceptIn.properties[j];
conceptOut[property.name] = property.value;
}
rec = new Ext.data.Record(conceptOut);
store.add(rec);
}
if (nbConcepts > 0) {
this.gridTemplates.getEl().mask();
}
},
failure : function (ret) {
var data = Ext.decode(ret.responseText);
Ext.Msg.alert(i18n.get('label.warning'), data.errorMessage);
}
});
}
}
},
onTemplateClick : function (self, rowIndex, e) {
var rec = this.gridTemplates.getSelectionModel().getSelected();
if (!rec) {
return false;
}
var currentConceptTemplateId = rec.data.id;
if (Ext.isEmpty(this.conceptTemplate) || this.conceptTemplate.id != currentConceptTemplateId) {
this.createConceptGrid(rec.data);
this.conceptTemplate = rec.data;
}
},
createConceptGrid : function (template) {
var gridConceptsSelect = new sitools.component.dictionary.gridPanel({
template : template,
sm : new Ext.grid.RowSelectionModel({
singleSelect : true
}),
tbar : {
xtype : 'sitools.widget.GridSorterToolbar',
gridId : "gridConceptsSelect",
items : [{
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreateConcept,
scope : this
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDeleteConcet,
scope : this
}]
},
id : 'gridConceptsSelect',
title : i18n.get('title.gridConcept'),
editable : true
});
var tabPanel = this.get("tabPanelDictionary");
tabPanel.remove('gridConceptsSelect');
tabPanel.add(gridConceptsSelect);
this.doLayout();
},
beforeTabChange : function (self, newTab, currentTab) {
// if (this.action == "create") {
if (newTab.id == "gridConceptsSelect" || newTab.id == "dictionaryFormPanel") {
var rec = this.gridTemplates.getSelectionModel().getSelected();
if (!rec && Ext.isEmpty(this.conceptTemplate)) {
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('warning.noTemplateselection'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
return false;
}
}
// }
}
});
Ext.reg('s-dictionaryprop', sitools.component.dictionary.dictionaryPropPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.component.dictionary');
sitools.component.dictionary.dictionaryCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.GROUP,
sm : new Ext.grid.RowSelectionModel(),
pageSize : 10,
// loadMask: true,
initComponent : function () {
this.url = loadUrl.get('APP_URL') + loadUrl.get('APP_DICTIONARIES_URL');
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
url : this.url,
remoteSort : true,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'template',
type : 'string'
} ]
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 400,
sortable : false
} ]
});
this.bbar = {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
};
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreate,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this.onModify,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDelete,
xtype : 's-menuButton'
}, '->', {
xtype : 's-filter',
emptyText : i18n.get('label.search'),
store : this.store,
pageSize : this.pageSize
} ]
};
this.view = new Ext.grid.GridView({
forceFit : true
});
this.listeners = {
scope : this,
rowDblClick : this.onModify
};
sitools.component.dictionary.dictionaryCrudPanel.superclass.initComponent.call(this);
},
onRender : function () {
sitools.component.dictionary.dictionaryCrudPanel.superclass.onRender.apply(this, arguments);
this.store.load({
params : {
start : 0,
limit : this.pageSize
}
});
},
onCreate : function () {
var up = new sitools.component.dictionary.dictionaryPropPanel({
url : this.url,
action : 'create',
store : this.getStore()
});
up.show(ID.BOX.DICTIONARY);
},
onModify : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.component.dictionary.dictionaryPropPanel({
url : this.url + '/' + rec.id,
action : 'modify',
store : this.getStore()
});
up.show(ID.BOX.DICTIONARY);
},
onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return false;
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('dictionaryCrud.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec);
}
}
});
},
doDelete : function (rec) {
Ext.Ajax.request({
url : this.url + "/" + rec.id,
method : 'DELETE',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
}
});
Ext.reg('s-dictionary', sitools.component.dictionary.dictionaryCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.component.dictionary');
sitools.component.dictionary.templatePropPanel = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
pageSize : 10,
initComponent : function () {
if (this.action == 'modify') {
this.title = i18n.get('label.modifyTemplate');
}
if (this.action == 'create') {
this.title = i18n.get('label.createTemplate');
}
var storeProperty = new Ext.data.JsonStore({
id : 'storePropertiesSelect',
root : 'property',
idProperty : 'name',
fields : [ {
name : 'name',
type : 'string'
}, {
name : 'value',
type : 'string'
} ]
});
var cmProperty = new Ext.grid.ColumnModel({
columns : [ {
header : i18n.get('headers.name'),
dataIndex : 'name',
width : 100,
editor : new Ext.form.TextField({
allowBlank : false
})
}, {
header : i18n.get('headers.value'),
dataIndex : 'value',
width : 150,
editor : new Ext.form.TextField({
allowBlank : true
})
} ],
defaults : {
sortable : true,
width : 100,
editor : new Ext.form.TextField({
allowBlank : false
})
}
});
var smProperty = new Ext.grid.RowSelectionModel({
singleSelect : true
});
var tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreateProperty
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDeleteProperty
} ]
};
var gridProperty = new Ext.grid.EditorGridPanel({
id : 'gridPropertySelect',
title : i18n.get('title.gridProperty'),
store : storeProperty,
tbar : tbar,
cm : cmProperty,
sm : smProperty
});
this.items = [ {
xtype : 'tabpanel',
height : 450,
activeTab : 0,
items : [ {
xtype : 'panel',
height : 400,
title : i18n.get('label.templateInfo'),
items : [ {
xtype : 'form',
border : false,
padding : 10,
items : [ {
xtype : 'hidden',
name : 'id'
}, {
xtype : 'textfield',
name : 'name',
fieldLabel : i18n.get('label.name'),
anchor : '100%',
allowBlank : false
}, {
xtype : 'textfield',
name : 'description',
fieldLabel : i18n.get('label.description'),
anchor : '100%'
} ]
} ]
}, gridProperty ],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ]
} ];
sitools.component.dictionary.templatePropPanel.superclass.initComponent.call(this);
},
onUpload : function () {
// TODO gerer l'upload de fichier.
Ext.Msg.alert('upload non implémenté');
},
onCreateProperty : function () {
this.findById('gridPropertySelect').getStore().add(new Ext.data.Record());
},
onDeleteProperty : function () {
var grid = this.findById('gridPropertySelect');
var rec = grid.getSelectionModel().getSelected();
if (!rec) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
return;
}
grid.getStore().remove(rec);
},
onValidate : function () {
var f, putObject = {}, store, tmp = [], i;
f = this.findByType('form')[0].getForm();
if (!f.isValid()) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.invalidForm'));
return false;
}
if (this.action == 'modify') {
Ext.iterate(f.getValues(), function (key, value) {
if (key == 'image') {
// TODO : definir une liste de mediaType et type
putObject.image = {};
putObject.image.url = value;
putObject.image.type = "Image";
putObject.image.mediaType = "Image";
} else {
putObject[key] = value;
}
}, this);
store = this.findById('gridPropertySelect').getStore();
if (store.getCount() > 0) {
putObject.properties = [];
for (i = 0; i < store.getCount(); i++) {
putObject.properties.push(store.getAt(i).data);
}
}
Ext.Ajax.request({
url : this.url,
method : 'PUT',
scope : this,
jsonData : putObject,
success : function (ret) {
this.close();
this.store.reload();
},
failure : alertFailure
});
}
if (this.action == 'create') {
Ext.iterate(f.getValues(), function (key, value) {
if (key == 'image') {
// TODO : definir une liste de mediaType et type
putObject.image = {};
putObject.image.url = value;
putObject.image.type = "Image";
putObject.image.mediaType = "Image";
} else {
putObject[key] = value;
}
}, this);
store = this.findById('gridPropertySelect').getStore();
if (store.getCount() > 0) {
putObject.properties = [];
for (i = 0; i < store.getCount(); i++) {
putObject.properties.push(store.getAt(i).data);
}
}
Ext.Ajax.request({
url : this.url,
method : 'POST',
scope : this,
jsonData : putObject,
success : function (ret) {
this.close();
this.store.reload();
// Ext.Msg.alert(i18n.get('label.information'),
// i18n.get('msg.uservalidate'));
},
failure : alertFailure
});
}
},
onRender : function () {
sitools.component.dictionary.templatePropPanel.superclass.onRender.apply(this, arguments);
if (this.url) {
// var gs = this.groupStore, qs = this.quotaStore;
var i;
if (this.action == 'modify') {
Ext.Ajax.request({
url : this.url,
method : 'GET',
scope : this,
success : function (ret) {
var f = this.findByType('form')[0].getForm();
var store = this.findById('gridPropertySelect').getStore();
var data = Ext.decode(ret.responseText).template;
var rec = {};
rec.id = data.id;
rec.name = data.name;
rec.description = data.description;
var record = new Ext.data.Record(rec);
f.loadRecord(record);
if (!data.properties) {
return;
}
var properties;
if (typeof data.properties[0] && data.properties[0] instanceof Array) {
properties = data.properties[0];
} else {
properties = data.properties;
}
for (i = 0; i < properties.length; i++) {
rec = new Ext.data.Record(properties[i]);
store.add(rec);
}
},
failure : function (ret) {
var data = Ext.decode(ret.responseText);
Ext.Msg.alert(i18n.get('label.warning'), data.errorMessage);
}
});
}
}
}
});
Ext.reg('s-templateprop', sitools.component.dictionary.templatePropPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.component.dictionary');
sitools.component.dictionary.templateCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.GROUP,
sm : new Ext.grid.RowSelectionModel(),
pageSize : 10,
initComponent : function () {
this.url = loadUrl.get('APP_URL') + loadUrl.get('APP_DICTIONARIES_TEMPLATES_URL');
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
url : this.url,
remoteSort : true,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
} ]
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 400,
sortable : false
} ]
});
this.bbar = {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
};
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreate,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this.onModify,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDelete,
xtype : 's-menuButton'
}, '->', {
xtype : 's-filter',
emptyText : i18n.get('label.search'),
store : this.store,
pageSize : this.pageSize
} ]
};
this.view = new Ext.grid.GridView({
forceFit : true
});
this.listeners = {
scope : this,
rowDblClick : this.onModify
};
sitools.component.dictionary.templateCrudPanel.superclass.initComponent.call(this);
},
onRender : function () {
sitools.component.dictionary.templateCrudPanel.superclass.onRender.apply(this, arguments);
this.store.load({
params : {
start : 0,
limit : this.pageSize
}
});
},
onCreate : function () {
var up = new sitools.component.dictionary.templatePropPanel({
url : this.url,
action : 'create',
store : this.getStore()
});
up.show(ID.BOX.TEMPLATE);
},
onModify : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.component.dictionary.templatePropPanel({
url : this.url + '/' + rec.id,
action : 'modify',
store : this.getStore()
});
up.show(ID.BOX.TEMPLATE);
},
onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return false;
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('templateCrud.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec);
}
}
});
},
doDelete : function (rec) {
Ext.Ajax.request({
url : this.url + "/" + rec.id,
method : 'DELETE',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
}
});
Ext.reg('s-template', sitools.component.dictionary.templateCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp*/
Ext.namespace('sitools.component.dictionary');
/**
* A window that displays the columns of a dataset.
* @cfg string field The attribute of the record to edit
* @cfg Ext.data.Record storeRecord the record to edit
* @cfg Ext.data.Store parentStore the store of the record
* @cfg Ext.grid.GridView parentView the view of the grid
* @cfg string url the url to request dataset
* @class sitools.component.dictionary.selectDictionary
* @extends Ext.Window
*/
sitools.component.dictionary.selectDictionary = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
pageSize : 10,
initComponent : function () {
this.title = i18n.get('title.selectDictionary');
this.cmselectDictionary = new Ext.grid.ColumnModel({
columns : [ {
id : 'name',
header : i18n.get('headers.name'),
sortable : true,
dataIndex : 'name'
}, {
id : 'description',
header : i18n.get('headers.description'),
sortable : false,
dataIndex : 'description'
} ]
});
this.smselectDictionary = new Ext.grid.RowSelectionModel({
singleSelect : true
});
this.gridselectDictionary = new Ext.grid.GridPanel({
height : 380,
autoScroll : true,
viewConfig : {
forceFit : true
},
store : new Ext.data.JsonStore({
root : 'data',
restful : true,
proxy : new Ext.data.HttpProxy({
url : this.url,
restful : true,
method : 'GET'
}),
remoteSort : true,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
} ],
autoLoad : true
}),
cm : this.cmselectDictionary,
sm : this.smselectDictionary
});
this.items = [ {
xtype : 'panel',
layout : 'fit',
items : [ this.gridselectDictionary ],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ]
} ];
sitools.component.dictionary.selectDictionary.superclass.initComponent.call(this);
},
/**
* Method called on Ok button.
* update the Record and close the window
*/
onValidate : function () {
var rec = this.gridselectDictionary.getSelectionModel().getSelected();
if (rec !== null) {
this.record.data[this.field] = rec.data.name;
this.parentView.refresh();
this.close();
} else {
new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('warning.noselection'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
}
}
});
Ext.reg('s-selectDictionaryWin', sitools.component.dictionary.selectDictionary);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.admin.datasource.jdbc');
/**
* Displays all databases defined.
* @requires sitools.admin.datasource.jdbc.DataBasePropPanel
* @requires sitools.admin.datasource.jdbc.DataBaseTest
* @class sitools.admin.datasource.jdbc.DataBaseCrudPanel
* @extends Ext.grid.GridPanel
*/
sitools.admin.datasource.jdbc.DataBaseCrudPanel = Ext.extend(Ext.grid.GridPanel, {
//sitools.admin.datasource.DataBaseCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.DATABASE,
sm : new Ext.grid.RowSelectionModel({
singleSelect : true
}),
pageSize : 10,
// loadMask: true,
initComponent : function () {
this.url = loadUrl.get('APP_URL') + loadUrl.get('APP_DATASOURCES_URL');
// create the restful Store
// Method url action
// POST /datasources create
// GET /datasources read
// PUT /datasources/[id] update
// DELETE /datasources/[id] delete
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
remoteSort : true,
autoSave : false,
url : this.url,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'url',
type : 'string'
}, {
name : 'status',
type : 'string'
} ]
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100,
sortable : true
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 205,
sortable : false
}, {
header : i18n.get('label.url'),
dataIndex : 'url',
width : 350,
sortable : false
}, {
header : i18n.get('label.status'),
dataIndex : 'status',
width : 90,
sortable : true
} ]
});
this.bbar = {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
};
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this._onCreate,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this._onModify,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this._onDelete,
xtype : 's-menuButton'
}, {
text : i18n.get('label.active'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_active.png',
handler : this._onActive,
xtype : 's-menuButton'
}, {
text : i18n.get('label.disactive'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_disactive.png',
handler : this._onDisactive,
xtype : 's-menuButton'
}, {
text : i18n.get('label.testCnx'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_test_connection.png',
handler : this._onTest,
xtype : 's-menuButton'
}, '->', {
xtype : 's-filter',
emptyText : i18n.get('label.search'),
store : this.store,
pageSize : this.pageSize
} ]
};
this.view = new Ext.grid.GridView({
forceFit : true
});
this.listeners = {
scope : this,
rowDblClick : this._onModify
};
sitools.admin.datasource.jdbc.DataBaseCrudPanel.superclass.initComponent.call(this);
},
onRender : function () {
sitools.admin.datasource.jdbc.DataBaseCrudPanel.superclass.onRender.apply(this, arguments);
this.store.load({
params : {
start : 0,
limit : this.pageSize
}
});
},
_onCreate : function () {
var dbp = new sitools.admin.datasource.jdbc.DataBasePropPanel({
url : this.url,
action : 'create',
store : this.store
});
dbp.show(ID.BOX.DATABASE);
},
_onModify : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
if (rec.data.status == i18n.get('status.active')) {
this._onView();
return;
}
var dbp = new sitools.admin.datasource.jdbc.DataBasePropPanel({
url : this.url + '/' + rec.id,
action : 'modify',
store : this.store
});
dbp.show(ID.BOX.DATABASE);
},
_onView : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.admin.datasource.jdbc.DataBasePropPanel({
url : this.url + '/' + rec.id,
action : 'view',
store : this.store
});
up.show();
},
_onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return false;
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('databaseCrud.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec);
}
}
});
},
doDelete : function (rec) {
// var rec = this.getSelectionModel().getSelected();
// if (!rec) return false;
Ext.Ajax.request({
url : this.url + "/" + rec.id,
method : 'DELETE',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
_onActive : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.url + '/' + rec.id + '/start',
method : 'PUT',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
_onDisactive : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.url + '/' + rec.id + '/stop',
method : 'PUT',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
_onTest : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var dbt = new sitools.admin.datasource.DataBaseTest({
url : this.url + '/' + rec.id + '/test'
});
dbt.show();
}
});
Ext.reg('s-databaseJDBC', sitools.admin.datasource.jdbc.DataBaseCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp*/
/*
* @include "../id.js"
* @include "databasetest.js"
*/
Ext.namespace('sitools.admin.datasource.jdbc');
/**
* A panel to view, modify databases config
* @requires sitools.admin.datasource.jdbc.DataBaseTest
* @cfg {string} url the url to request the database
* @cfg {string} action the action to perform should be view, modify or create
* @cfg {Ext.data.Store} store the store that contains all databases.
* @class sitools.admin.datasource.jdbc.DataBasePropPanel
* @extends Ext.Window
*/
sitools.admin.datasource.jdbc.DataBasePropPanel = Ext.extend(Ext.Window, {
//sitools.admin.datasource.DataBasePropPanel = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
id : ID.COMPONENT_SETUP.DATABASE,
initComponent : function () {
if (this.action == 'create') {
this.title = i18n.get('label.createDatabase');
} else if (this.action == 'modify') {
this.title = i18n.get('label.modifyDatabase');
} else if (this.action == 'view') {
this.title = i18n.get('label.viewDatabase');
}
this.items = [ {
xtype : 'panel',
layout : "fit",
title : i18n.get('label.databaseInfo'),
items : [ {
xtype : 'form',
formId : 'datasourceForm',
border : false,
labelWidth : 150,
padding : 10,
defaultType : "textfield",
defaults : {
anchor : '100%',
allowBlank : false
},
items : [ {
name : 'id',
hidden : true,
allowBlank : true
}, {
name : 'name',
fieldLabel : i18n.get('label.name')
}, {
name : 'description',
fieldLabel : i18n.get('label.description'),
allowBlank : true
}, {
xtype : 'combo',
id : 'driverDatasourceId',
mode : 'local',
triggerAction : 'all',
editable : false,
name : 'driverClass',
fieldLabel : i18n.get('label.driver'),
width : 100,
store : new Ext.data.ArrayStore({
fields : [ {
name : 'code'
}, {
name : 'label'
} ],
data : [ [ 'org.gjt.mm.mysql.Driver', 'MySQL' ], [ 'org.postgresql.Driver', 'PostgreSQL' ] ]
}),
valueField : 'code',
displayField : 'label',
anchor : "50%"
}, {
name : 'url',
fieldLabel : i18n.get('label.url'),
validator : function (value) {
var driverValue = Ext.getCmp('driverDatasourceId').getValue();
if (Ext.isEmpty(driverValue)) {
return "The Driver is empty";
}
else {
switch (driverValue) {
case 'org.gjt.mm.mysql.Driver' :
if (value.match("mysql")) {
return true;
} else {
return "The driver doesn't match with this url";
}
break;
case 'org.postgresql.Driver' :
if (value.match("postgresql")) {
return true;
} else {
return "The driver doesn't match with this url";
}
break;
}
}
return true;
}
}, {
name : 'schemaOnConnection',
fieldLabel : i18n.get('label.schemaOnConnection'),
allowBlank : true
}, {
name : 'sitoolsAttachementForUsers',
fieldLabel : i18n.get('label.userAttach'),
vtype : "attachment"
}, {
name : 'userLogin',
fieldLabel : i18n.get('label.userLogin'),
vtype : "withoutSpace"
}, {
fieldLabel : i18n.get('label.userPassword'),
inputType : 'password',
name : 'userPassword',
vtype : "withoutSpace"
}, {
xtype : 'spinnerfield',
name : 'maxActive',
id : 'maxActiveId',
fieldLabel : i18n.get('label.maxActive'),
minValue : 0,
maxValue : 20,
allowDecimals : false,
incrementValue : 1,
accelerate : true,
anchor : "50%",
value : 10,
validator : function (value) {
var initialSizeValue = Ext.getCmp("initialSizeId").getValue();
if (Ext.isEmpty(initialSizeValue)) {
initialSizeValue = 0;
}
if (Ext.isEmpty(value)) {
return i18n.get('label.nullValue');
}
if (initialSizeValue > value) {
return String.format(i18n.get('label.dbMaxActiveError'), value, initialSizeValue);
}
else {
return true;
}
}
}, {
xtype : 'spinnerfield',
name : 'initialSize',
id : 'initialSizeId',
fieldLabel : i18n.get('label.initialSize'),
minValue : 0,
maxValue : 20,
allowDecimals : false,
incrementValue : 1,
accelerate : true,
anchor : "50%",
value : 5,
validator : function (value) {
var maxActiveValue = Ext.getCmp("maxActiveId").getValue();
if (Ext.isEmpty(maxActiveValue)) {
maxActiveValue = 0;
}
if (Ext.isEmpty(value)) {
return i18n.get('label.nullValue');
}
if (maxActiveValue < value) {
return String.format(i18n.get('label.dbMaxActiveError'), maxActiveValue, value);
}
else {
return true;
}
}
} ]
} ],
buttons : [ {
text : i18n.get('label.testCnx'),
scope : this,
handler : this._onTest
}, {
text : i18n.get('label.ok'),
scope : this,
handler : this._onValidate
},
{
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ]
} ];
this.listeners = {
scope : this,
resize : function (window, width, height) {
var size = window.body.getSize();
this.findByType('panel')[0].setSize(size);
}
};
sitools.admin.datasource.jdbc.DataBasePropPanel.superclass.initComponent.call(this);
},
onRender : function () {
sitools.admin.datasource.jdbc.DataBasePropPanel.superclass.onRender.apply(this, arguments);
Ext.each(this.findByType('form')[0].items.items, function (item) {
item.disable();
}, this);
this.findByType('panel')[0].buttons[1].disable();
this.findByType('panel')[0].buttons[0].disable();
if (this.action == 'modify' || this.action == 'view') {
var f = this.findByType('form')[0].getForm();
Ext.Ajax.request({
url : this.url,
method : 'GET',
scope : this,
success : function (ret) {
var data = Ext.decode(ret.responseText);
f.setValues(data.jdbcdatasource);
var tmp = f.isValid();
},
failure : alertFailure
});
}
if (this.action == 'modify' || this.action == "create") {
Ext.each(this.findByType('form')[0].items.items, function (item) {
item.enable();
}, this);
this.findByType('panel')[0].buttons[1].enable();
this.findByType('panel')[0].buttons[0].enable();
}
},
_onValidate : function () {
var frm = this.findByType('form')[0].getForm();
if (!frm.isValid()) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.invalidForm'));
return;
}
var met = this.action == 'modify' ? 'PUT' : 'POST';
Ext.Ajax.request({
url : this.url,
method : met,
scope : this,
jsonData : frm.getFieldValues(),
success : function (ret) {
this.store.reload();
this.close();
},
failure : alertFailure
});
},
_onTest : function () {
var frm = this.findByType('form')[0].getForm();
var vals = frm.getFieldValues();
var dbt = new sitools.admin.datasource.DataBaseTest({
url : this.url + '/test',
data : vals
});
dbt.show();
}
});
Ext.reg('s-databaseprop', sitools.admin.datasource.jdbc.DataBasePropPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp*/
Ext.namespace('sitools.admin.datasource');
/**
* Open A window with a status bar, and test database. Displays the result with a status bar.
* @cfg {string} url the url to request to test database
* @cfg {} data the private data of current database.
* @class sitools.admin.datasource.DataBaseTest
* @extends Ext.Window
*/
sitools.admin.datasource.DataBaseTest = Ext.extend(Ext.Window, {
//sitools.admin.datasource.DataBaseTest = Ext.extend(Ext.Window, {
width : 400,
height : 210,
modal : true,
closable : false,
layout : 'fit',
buttonAlign : 'center',
initComponent : function () {
this.title = i18n.get('label.databaseInfo');
this.bbar = new Ext.ux.StatusBar({
text : i18n.get('label.ready'),
id : 'sbDBTest',
iconCls : 'x-status-valid'
});
this.items = [ {
xtype : 'panel',
baseCls : 'x-plain',
layout : 'fit',
items : [ {
xtype : 'textarea',
id : 'DBText'
} ]
} ];
this.buttons = [ {
text : i18n.get('label.ok'),
scope : this,
handler : function () {
this.close();
}
} ];
sitools.admin.datasource.DataBaseTest.superclass.initComponent.call(this);
},
onRender : function () {
sitools.admin.datasource.DataBaseTest.superclass.onRender.apply(this, arguments);
Ext.getCmp('sbDBTest').showBusy();
Ext.Ajax.request({
url : this.url,
method : 'PUT',
scope : this,
jsonData : this.data,
success : function (ret) {
var rep = Ext.decode(ret.responseText);
var status = rep.success ? i18n.get('msg.success') : i18n.get('msg.failure');
var msg = rep.data ? rep.data.join('\n') : rep.message;
Ext.getCmp('sbDBTest').setStatus({
text : status,
iconCls : rep.success ? 'x-status-valid' : 'x-status-error'
});
Ext.getCmp('DBText').setValue(msg);
},
failure : function (ret) {
var rep = i18n.get('warning.serverError');
try {
rep = Ext.decode(ret.responseText).logs.join('\n');
} catch (Exception) {
}
Ext.getCmp('sbDBTest').setStatus({
text : ret.statusText,
iconCls : 'x-status-error'
});
Ext.getCmp('DBText').setValue(rep);
}
});
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.admin.datasource.mongoDb');
/**
* Displays all databases defined.
* @requires sitools.admin.datasource.mongoDb.DataBasePropPanel
* @requires sitools.admin.datasource.mongoDb.DataBaseTest
* @class sitools.admin.datasource.mongoDb.DataBaseCrudPanel
* @extends Ext.grid.GridPanel
*/
sitools.admin.datasource.mongoDb.DataBaseCrudPanel = Ext.extend(Ext.grid.GridPanel, {
//sitools.admin.datasource.DataBaseCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.DATABASE,
sm : new Ext.grid.RowSelectionModel({
singleSelect : true
}),
pageSize : 10,
// loadMask: true,
initComponent : function () {
this.url = loadUrl.get('APP_URL') + loadUrl.get('APP_DATASOURCES_MONGODB_URL');
// create the restful Store
// Method url action
// POST /datasources create
// GET /datasources read
// PUT /datasources/[id] update
// DELETE /datasources/[id] delete
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
remoteSort : true,
autoSave : false,
url : this.url,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'url',
type : 'string'
}, {
name : 'sitoolsAttachementForUsers',
type : 'numeric'
}, {
name : 'portNumber',
type : 'numeric'
}, {
name : 'databaseName',
type : 'string'
}, {
name : 'status',
type : 'string'
}, {
name : 'authentication',
type : 'boolean'
}, {
name : 'userLogin',
type : 'string'
}, {
name : 'userPassword',
type : 'string'
} ]
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100,
sortable : true
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 205,
sortable : false
}, {
header : i18n.get('label.url'),
dataIndex : 'url',
width : 350,
sortable : false
}, {
header : i18n.get('label.status'),
dataIndex : 'status',
width : 90,
sortable : true
}, {
xtype: 'actioncolumn',
width: 30,
items: [{
getClass: function (v, meta, rec) { // Or return a class from a function
if (rec.get("status") === "ACTIVE") {
this.items[0].tooltip = i18n.get('label.databaseExplorer');
return 'sitools-explore-datasource';
} else {
return '';
}
},
handler: function (grid, rowIndex, colIndex) {
var rec = grid.getStore().getAt(rowIndex);
var win = new sitools.admin.datasource.mongoDb.DataBaseExplorer({
database : rec.data
});
win.show();
}
}]
} ]
});
this.bbar = {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
};
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this._onCreate,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this._onModify,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this._onDelete,
xtype : 's-menuButton'
}, {
text : i18n.get('label.active'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_active.png',
handler : this._onActive,
xtype : 's-menuButton'
}, {
text : i18n.get('label.disactive'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_disactive.png',
handler : this._onDisactive,
xtype : 's-menuButton'
}, {
text : i18n.get('label.testCnx'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_test_connection.png',
handler : this._onTest,
xtype : 's-menuButton'
}, '->', {
xtype : 's-filter',
emptyText : i18n.get('label.search'),
store : this.store,
pageSize : this.pageSize
} ]
};
this.view = new Ext.grid.GridView({
forceFit : true
});
this.listeners = {
scope : this,
rowDblClick : this._onModify
};
sitools.admin.datasource.mongoDb.DataBaseCrudPanel.superclass.initComponent.call(this);
},
onRender : function () {
sitools.admin.datasource.mongoDb.DataBaseCrudPanel.superclass.onRender.apply(this, arguments);
this.store.load({
params : {
start : 0,
limit : this.pageSize
}
});
},
_onCreate : function () {
var dbp = new sitools.admin.datasource.mongoDb.DataBasePropPanel({
url : this.url,
action : 'create',
store : this.store
});
dbp.show(ID.BOX.DATABASE);
},
_onModify : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
if (rec.data.status === i18n.get('status.active')) {
this._onView();
return;
}
var dbp = new sitools.admin.datasource.mongoDb.DataBasePropPanel({
url : this.url + '/' + rec.id,
action : 'modify',
store : this.store
});
dbp.show(ID.BOX.DATABASE);
},
_onView : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.admin.datasource.mongoDb.DataBasePropPanel({
url : this.url + '/' + rec.id,
action : 'view',
store : this.store
});
up.show();
},
_onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return false;
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('databaseCrud.delete'),
scope : this,
fn : function (btn, text) {
if (btn === 'yes') {
this.doDelete(rec);
}
}
});
},
doDelete : function (rec) {
// var rec = this.getSelectionModel().getSelected();
// if (!rec) return false;
Ext.Ajax.request({
url : this.url + "/" + rec.id,
method : 'DELETE',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
_onActive : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.url + '/' + rec.id + '/start',
method : 'PUT',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
_onDisactive : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.url + '/' + rec.id + '/stop',
method : 'PUT',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
_onTest : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var dbt = new sitools.admin.datasource.DataBaseTest({
url : this.url + '/' + rec.id + '/test'
});
dbt.show();
}
});
Ext.reg('s-databaseMongoDb', sitools.admin.datasource.mongoDb.DataBaseCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp*/
/*
* @include "../id.js"
* @include "databasetest.js"
*/
Ext.namespace('sitools.admin.datasource.mongoDb');
/**
* A panel to view, modify databases config
* @requires sitools.admin.datasource.mongoDb.DataBaseTest
* @cfg {string} url the url to request the database
* @cfg {string} action the action to perform should be view, modify or create
* @cfg {Ext.data.Store} store the store that contains all databases.
* @class sitools.admin.datasource.mongoDb.DataBasePropPanel
* @extends Ext.Window
*/
sitools.admin.datasource.mongoDb.DataBasePropPanel = Ext.extend(Ext.Window, {
//sitools.admin.datasource.DataBasePropPanel = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
id : ID.COMPONENT_SETUP.DATABASE,
initComponent : function () {
if (this.action === 'create') {
this.title = i18n.get('label.createDatabase');
} else if (this.action === 'modify') {
this.title = i18n.get('label.modifyDatabase');
} else if (this.action === 'view') {
this.title = i18n.get('label.viewDatabase');
}
this.items = [ {
xtype : 'panel',
layout : "fit",
title : i18n.get('label.databaseInfo'),
items : [ {
xtype : 'form',
formId : 'datasourceForm',
border : false,
labelWidth : 150,
padding : 10,
defaultType : "textfield",
defaults : {
anchor : '100%',
allowBlank : false
},
items : [ {
name : 'id',
hidden : true,
allowBlank : true
}, {
name : 'name',
fieldLabel : i18n.get('label.name')
}, {
name : 'description',
fieldLabel : i18n.get('label.description'),
allowBlank : true
}, {
xtype : 'combo',
id : 'driverDatasourceId',
mode : 'local',
triggerAction : 'all',
editable : false,
name : 'driverClass',
fieldLabel : i18n.get('label.driver'),
width : 100,
store : new Ext.data.ArrayStore({
fields : [ {
name : 'code'
}, {
name : 'label'
} ],
data : [ [ 'com.mongo.driver', 'MongoDb' ]]
}),
valueField : 'code',
displayField : 'label',
anchor : "50%",
value : "com.mongo.driver"
}, {
name : 'url',
fieldLabel : i18n.get('label.url'),
validator : function (value) {
var driverValue = Ext.getCmp('driverDatasourceId').getValue();
if (Ext.isEmpty(driverValue)) {
return "The Driver is empty";
}
return true;
}
}, {
name : 'sitoolsAttachementForUsers',
fieldLabel : i18n.get('label.userAttach'),
vtype : "attachment"
}, {
name : 'databaseName',
fieldLabel : i18n.get('label.databaseName'),
vtype : "withoutSpace"
}, {
xtype : "numberfield",
name : 'portNumber',
fieldLabel : i18n.get('label.portNumber')
}, {
name : 'authentication',
fieldLabel : i18n.get('label.authentication'),
xtype : "checkbox",
listeners : {
check : function (me, checked) {
var f = me.ownerCt.getForm();
f.findField("userLogin").setVisible(checked);
f.findField("userPassword").setVisible(checked);
}
}
}, {
name : 'userLogin',
allowBlank : true,
fieldLabel : i18n.get('label.userLogin')
}, {
fieldLabel : i18n.get('label.userPassword'),
allowBlank : true,
inputType : 'password',
name : 'userPassword'
}, {
xtype : 'spinnerfield',
name : 'maxActive',
id : 'maxActiveId',
fieldLabel : i18n.get('label.maxActive'),
minValue : 0,
maxValue : 20,
allowDecimals : false,
incrementValue : 1,
accelerate : true,
anchor : "50%",
value : 10
}]
} ],
buttons : [ {
text : i18n.get('label.testCnx'),
scope : this,
handler : this._onTest
}, {
text : i18n.get('label.ok'),
scope : this,
handler : this._onValidate
},
{
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ]
} ];
this.listeners = {
scope : this,
resize : function (window, width, height) {
var size = window.body.getSize();
this.findByType('panel')[0].setSize(size);
}
};
sitools.admin.datasource.mongoDb.DataBasePropPanel.superclass.initComponent.call(this);
},
onRender : function () {
sitools.admin.datasource.mongoDb.DataBasePropPanel.superclass.onRender.apply(this, arguments);
var frm = this.findByType('form')[0];
var basicFrm = this.findByType('form')[0].getForm();
Ext.each(frm.items.items, function (item) {
item.disable();
}, this);
this.findByType('panel')[0].buttons[1].disable();
this.findByType('panel')[0].buttons[0].disable();
if (this.action === 'modify' || this.action === 'view') {
var f = this.findByType('form')[0].getForm();
Ext.Ajax.request({
url : this.url,
method : 'GET',
scope : this,
success : function (ret) {
var data = Ext.decode(ret.responseText);
f.setValues(data.mongodbdatasource);
var tmp = f.isValid();
},
failure : alertFailure
});
}
else {
basicFrm.findField("authentication").setValue(true);
}
if (this.action === 'modify' || this.action === "create") {
Ext.each(frm.items.items, function (item) {
item.enable();
}, this);
this.findByType('panel')[0].buttons[1].enable();
this.findByType('panel')[0].buttons[0].enable();
}
basicFrm.findField("userLogin").setVisible(basicFrm.findField("authentication").getValue());
basicFrm.findField("userPassword").setVisible(basicFrm.findField("authentication").getValue());
},
_onValidate : function () {
var frm = this.findByType('form')[0].getForm();
if (!frm.isValid()) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.invalidForm'));
return;
}
var met = this.action === 'modify' ? 'PUT' : 'POST';
Ext.Ajax.request({
url : this.url,
method : met,
scope : this,
jsonData : frm.getFieldValues(),
success : function (ret) {
this.store.reload();
this.close();
},
failure : alertFailure
});
},
_onTest : function () {
var frm = this.findByType('form')[0].getForm();
var vals = frm.getFieldValues();
var dbt = new sitools.admin.datasource.DataBaseTest({
url : this.url + '/test',
data : vals
});
dbt.show();
}
});
Ext.reg('s-databaseprop', sitools.admin.datasource.mongoDb.DataBasePropPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp*/
Ext.namespace('sitools.admin.datasource.mongoDb');
/**
* A window to visualize a Mongo DB database.
* show 2 panels :
* - sitools.admin.datasource.mongoDb.CollectionExplorer
* - sitools.admin.datasource.mongoDb.RecordsPanel
* @cfg {} database An object representing the Database mongo DB
* @class sitools.admin.datasource.mongoDb.DataBaseExplorer
* @extends Ext.Window
*/
sitools.admin.datasource.mongoDb.DataBaseExplorer = Ext.extend(Ext.Window, {
width : 800,
height : 500,
closable : true,
layout : 'hbox',
layoutConfig : {
pack : "start",
align : "stretch"
},
initComponent : function () {
this.title = i18n.get('label.databaseExplorer');
var storeCombo = new Ext.data.JsonStore({
fields : [ 'name', 'url' ],
url : this.database.sitoolsAttachementForUsers + "/collections",
root : "mongodbdatabase.collections",
autoLoad : true,
listeners : {
scope : this,
load : function (store, recs) {
if (recs.length !== 0) {
this.combobox.setValue(recs[0]
.get('name'));
this.combobox.fireEvent("select",
this.combobox, recs[0], 0);
}
}
}
});
/**
* The collection ComboBox
*/
this.combobox = new Ext.form.ComboBox({
store : storeCombo,
fieldLabel : i18n.get('label.selectCollection'),
displayField : 'name',
valueField : 'name',
typeAhead : true,
mode : 'local',
emptyText : i18n.get('label.selectACollection'),
forceSelection : true,
triggerAction : 'all',
selectOnFocus : true,
listeners : {
scope : this,
select : function (combo, rec, index) {
this.collection = rec.data;
this.loadCollection();
}
}
});
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
xtype : "label",
text : i18n.get('label.selectCollection') + " : "
}, this.combobox]
};
this.buttons = [ {
text : i18n.get('label.ok'),
scope : this,
handler : function () {
this.close();
}
} ];
this.listeners = {
scope : this,
metadataLoaded : function (node) {
this.displayRecords(node);
}
};
sitools.admin.datasource.mongoDb.DataBaseExplorer.superclass.initComponent.call(this);
},
/**
* Called when a collection is choosen.
* Builds a sitools.admin.datasource.mongoDb.CollectionExplorer panel
* @returns
*/
loadCollection : function () {
if (!Ext.isEmpty(this.metadataPanel)) {
this.remove(this.metadataPanel);
}
this.metadataPanel = new sitools.admin.datasource.mongoDb.CollectionExplorer({
collection : this.collection,
observer : this,
flex : 1
});
this.add(this.metadataPanel);
this.doLayout();
},
/**
* Called when event metadataLoaded is fired.
* Builds a sitools.admin.datasource.mongoDb.RecordsPanel if possible.
* If any errors occurs, remove all children.
* @param {Ext.tree.TreeNode} node The ExtJs Node containing metadata to build the columnModel and store.
* @returns
*/
displayRecords : function (node) {
if (!Ext.isEmpty(this.recordsPanel)) {
this.remove(this.recordsPanel);
}
try {
this.recordsPanel = new sitools.admin.datasource.mongoDb.RecordsPanel({
collection : this.collection,
node : node,
flex : 2
});
this.add(this.recordsPanel);
this.doLayout();
}
catch (err) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('label.displayRecordsProblem'));
this.removeAll();
this.doLayout();
}
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp*/
Ext.namespace('sitools.admin.datasource.mongoDb');
/**
* A tree Panel to represent a metadata coming from mongoDb resourceRepresentation.
* @cfg {} collection An object representing the collection mongo DB
* @class sitools.admin.datasource.mongoDb.CollectionExplorer
* @extends Ext.tree.TreePanel
*/
sitools.admin.datasource.mongoDb.CollectionExplorer = Ext.extend(Ext.tree.TreePanel, {
initComponent : function () {
var url = !Ext.isEmpty(this.collection) ? this.collection.url + "/metadata" : null;
sitools.admin.datasource.mongoDb.CollectionExplorer.superclass.initComponent.call(Ext.apply(this, {
title : i18n.get("label.metadata"),
useArrows : false,
autoScroll : true,
animate : true,
selModel : new Ext.tree.MultiSelectionModel(),
root : {
nodeType : 'async'
},
loader : new sitools.widget.rootTreeLoader({
requestMethod : 'GET',
root: "data",
url : url,
listeners : {
scope : this,
load : function (loader, node, response) {
if (this.observer) {
this.observer.fireEvent("metadataLoaded", node);
}
}
}
}),
rootVisible : false,
listeners : {
scope : this,
beforeload : function (node) {
node.setText(node.attributes.name);
node.attributes.collection = this.collection.name;
return node.isRoot || Ext.isDefined(node.attributes.children);
},
load : function (node) {
node.eachChild(function (item) {
item.setText(item.attributes.name);
return true;
});
}
}
}));
},
getLoader : function () {
return this.loader;
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp*/
Ext.namespace('sitools.admin.datasource.mongoDb');
/**
* Open A window with a status bar, and test database. Displays the result with a status bar.
* @cfg {} collection An object representing the collection mongo DB
* @cfg {} node The ExtJs Node containing metadata.
* @class sitools.admin.datasource.mongoDb.RecordsPanel
* @extends Ext.grid.GridPanel
*/
sitools.admin.datasource.mongoDb.RecordsPanel = Ext.extend(Ext.grid.GridPanel, {
initComponent : function () {
var tmp = this.metadatas2ExtObject(this.node) || {};
var cm = tmp.columnModel || new Ext.grid.ColumnModel({columns : []});;
var store = tmp.store;
store.load({
params : {
start : 0,
limit : 300
}
});
sitools.admin.datasource.mongoDb.RecordsPanel.superclass.initComponent.call(Ext.apply(this, {
cm : cm,
store : store,
loadMask : true,
title : i18n.get('label.records'),
bbar: new Ext.PagingToolbar({
store: store, // grid and PagingToolbar using same store
displayInfo: true,
pageSize: 300,
prependButtons: true
}),
listeners : {
scope : this,
render : function (grid) {
grid.getEl().mask(i18n.get("label.loading"), "ext-el-mask-msg x-mask-loading");
}
}
}));
},
/**
* Build Store & columnModel according to the metadatas.
* @param {Ext.tree.TreeNode} metadatas the treeNode containing metadatas
* @returns {} An object with 2 attributes : store, columnModel to build the grid.
*/
metadatas2ExtObject : function (metadatas) {
if (Ext.isEmpty(metadatas.childNodes)) {
return null;
}
var columns = [], fields = [], column, field;
Ext.each(metadatas.childNodes, function (firstLevelItem) {
column = !Ext.isEmpty(firstLevelItem.leaf) && firstLevelItem.leaf ? this.metadata2Column(firstLevelItem) : this.metadata2ActionColumn(firstLevelItem);
field = {
name : firstLevelItem.text
};
fields.push(field);
columns.push(column);
}, this);
return {
columnModel : new Ext.grid.ColumnModel({
columns : columns,
defaults : [{
width : 100
}]
}),
store : new Ext.data.JsonStore({
fields : fields,
url : this.collection.url + "/records",
autoLoad : false,
restful : true,
root : "data",
totalProperty : "total",
listeners : {
scope : this,
load : function (store) {
if (this.getEl()) {
this.getEl().unmask();
}
}
}
})
};
},
/**
* Transform a TreeNode with children into an ActionColumn
* @param {Ext.tree.TreeNode} metadata the metadata
* @returns {Ext.grid.ActionColumn} the action column
*/
metadata2ActionColumn : function (metadata) {
var column = new Ext.grid.Column({
scope : this,
// icon : "/sitools/common/res/images/icons/tree_databases.png",
header : metadata.text,
dataIndex : metadata.text,
width : 70,
processEvent : function (name, evt, grid, rowIndex, colIndex) {
if (Ext.getCmp("jsonDetailWin")) {
Ext.getCmp("jsonDetailWin").destroy();
}
var column = grid.getColumnModel().columns[colIndex];
var value = grid.getStore().getAt(rowIndex).get(column.dataIndex);
grid.getSelectionModel().selectRow(rowIndex);
var win = new Ext.Window({
id : "jsonDetailWin",
title : i18n.get('label.detail') + " " + column.header + " object",
modal : true,
autoScroll : true,
html : String.format("<pre>{0}</pre>", sitools.common.utils.Utils.syntaxHighlight(JSON.stringify(value, undefined, 4))),
height : 400,
x : evt.getXY()[0],
y : evt.getXY()[1]
});
win.show();
win.toFront();
},
renderer : function (value, metaData, record, rowIndex, colIndex, store) {
var i = 0;
for (var attr in value) {
i++;
}
return "<div style='float: left; width:50px;'>[" + i + " " + i18n.get("label.key") + "] " + "</div><div style='width:18px;'><img src=/sitools/common/res/images/icons/detailJson.png></div>";
}
});
return column;
},
/**
* Transform a TreeNode without children into an Column
* @param {Ext.tree.TreeNode} metadata the metadata
* @returns {Ext.grid.Column} the column
*/
metadata2Column : function (metadata) {
var column = new Ext.grid.Column({
header : metadata.text,
dataIndex : metadata.text
});
// Verrue pour traiter l'identifiant MongoDB :
// le champ _id est retourné sous la forme d'une string ou d'un objet Mongo {"$oid" : String Id}
if (metadata.text === "_id") {
Ext.apply(column, {
renderer : function (value) {
if (Ext.isString(value)) {
return value;
}
if (Ext.isObject(value) && value.$oid) {
return value.$oid;
}
return value;
}
});
}
return column;
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.component.forms.componentsAdminDef');
/**
* Object to build form Components administration objects in dataset Context
* @class sitools.component.forms.componentsAdminDef.DatasetContext
*
*/
sitools.component.forms.componentsAdminDef.DatasetContext = function () {
this.context = "dataset";
/**
* @method buildComboParam1 build a single
* @param {} scope the scope for this method.
*/
this.buildComboParam1 = function (scope) {
scope.storeColumn = new Ext.data.JsonStore({
root : 'ColumnModel',
idProperty : 'header',
remoteSort : false,
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'dataIndex',
type : 'string'
}, {
name : 'schema',
type : 'string'
}, {
name : 'tableAlias',
type : 'string'
}, {
name : 'tableName',
type : 'string'
}, {
name : 'header',
type : 'string'
}, {
name : 'toolTip',
type : 'string'
}, {
name : 'width',
type : 'int'
}, {
name : 'sortable',
type : 'boolean'
}, {
name : 'visible',
type : 'boolean'
}, {
name : 'filter',
type : 'boolean'
}, {
name : 'columnOrder',
type : 'int'
}, {
name : 'columnType',
type : 'string'
}, {
name : 'notion',
type : 'string',
mapping : 'notion.name'
}, {
name : 'notionUrl',
type : 'string',
mapping : 'notion.url'
}, {
name : 'columnAlias',
type : 'string'
}, {
name : 'dimensionId',
type : 'string'
}, {
name : 'unitName',
type : 'string'
}
]
});
Ext.each(scope.datasetColumnModel, function (column) {
if (column.specificColumnType != 'VIRTUAL') {
scope.storeColumn.add(new Ext.data.Record(column));
}
}, this);
return new Ext.form.ComboBox({
fieldLabel : i18n.get('label.column') + "1",
triggerAction : 'all',
name : "PARAM1",
specificType : "mapParam",
columnIndex : 1,
lazyRender : true,
mode : 'local',
store : scope.storeColumn,
valueField : 'columnAlias',
displayField : 'header',
anchor : '100%',
allowBlank : false
});
};
/**
* @method buildCombosConeSearch build 3 combos
* @param {} scope the scope for this method.
*/
this.buildCombosConeSearch = function (scope) {
var labels = ['X/RA', 'Y/DEC', 'Z/ID'];
for (var i = 1; i <= 3; i++) {
scope['mapParam' + i] = new Ext.form.ComboBox({
fieldLabel : labels[i - 1],
triggerAction : 'all',
name : "PARAM" + i,
specificType : "mapParam",
columnIndex : i,
lazyRender : true,
mode : 'local',
store : scope.storeColumn,
valueField : 'columnAlias',
displayField : 'header',
anchor : '100%',
allowBlank : false
});
if (scope.action == "modify") {
Ext.apply(scope['mapParam' + i], {
value : scope.selectedRecord.data.code[i - 1]
});
}
//this.setHeight(this.getHeight() + 30);
//this.ownerCt.ownerCt.setHeight(this.ownerCt.ownerCt.getHeight() + 30);
scope.insert(i, scope['mapParam' + i]);
}
};
this.onChangeColumn = function () {
var storeColumns = this.storeColumn;
var columnAlias = this.mapParam1.getValue();
if (Ext.isEmpty(columnAlias)) {
this.dimension.setValue(null);
this.dimension.setDisabled(true);
return;
}
var rec = storeColumns.getAt(storeColumns.find("columnAlias", columnAlias));
if (Ext.isEmpty(rec)) {
this.dimension.setValue(null);
this.dimension.setDisabled(true);
return;
}
this.columnDimensionId = rec.get("dimensionId");
if (!Ext.isEmpty(this.columnDimensionId)) {
this.dimension.setValue(this.columnDimensionId);
this.dimension.setDisabled(false);
}
else {
this.dimension.setValue(null);
this.dimension.setDisabled(true);
}
this.columnUnit = rec.get("unit");
};
this.activeDimension = function () {
var storeColumns = this.storeColumn;
var columnAlias = this.mapParam1.getValue();
if (!Ext.isEmpty(columnAlias)) {
var rec = storeColumns.getAt(storeColumns.find("columnAlias", columnAlias));
if (!Ext.isEmpty(rec)) {
this.columnDimensionId = rec.get("dimensionId");
if (!Ext.isEmpty(this.columnDimensionId)) {
this.dimension.setDisabled(false);
}
}
}
};
this.buildUnit = function () {
return;
};
};
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.component.forms.componentsAdminDef');
/**
* Object to build form Components administration objects in project Context (multiDatasets)
* @class sitools.component.forms.componentsAdminDef.ProjectContext
*
*/
sitools.component.forms.componentsAdminDef.ProjectContext = function () {
this.context = "project";
/**
* @method buildComboParam1 build a single
* @param {} scope the scope for this method.
*/
this.buildComboParam1 = function (scope) {
return new Ext.form.ComboBox({
fieldLabel : i18n.get('label.concept'),
triggerAction : 'all',
name : "PARAM1",
specificType : "mapParam",
columnIndex : 1,
lazyRender : false,
mode : 'local',
store : scope.storeConcepts,
valueField : 'name',
displayField : 'name',
anchor : '100%',
allowBlank : false
});
};
/**
* @method buildCombosConeSearch build 3 combos
* @param {} scope the scope for this method.
*/
this.buildCombosConeSearch = function (scope) {
var labels = ['X/RA', 'Y/DEC', 'Z/ID'];
for (var i = 1; i <= 3; i++) {
scope['mapParam' + i] = new Ext.form.ComboBox({
fieldLabel : labels[i - 1],
triggerAction : 'all',
name : "PARAM" + i,
specificType : "mapParam",
columnIndex : i,
lazyRender : true,
mode : 'local',
store : scope.storeConcepts,
valueField : 'name',
displayField : 'name',
anchor : '100%',
allowBlank : false
});
if (scope.action == "modify") {
Ext.apply(scope['mapParam' + i], {
value : scope.selectedRecord.data.code[i - 1]
});
}
scope.insert(i, scope['mapParam' + i]);
}
};
this.onChangeColumn = function () {
return;
};
this.activeDimension = function () {
this.dimension.setDisabled(false);
this.dimension.on("select", this.context.onChangeDimension, this);
};
this.onChangeDimension = function () {
this.storeUnits.proxy.setUrl(loadUrl.get('APP_URL') + loadUrl.get('APP_DIMENSIONS_ADMIN_URL') + '/dimension/' + this.dimension.getValue());
this.storeUnits.load();
};
this.buildUnit = function () {
var httpProxyUnits = new Ext.data.HttpProxy({
url : loadUrl.get('APP_URL') + loadUrl.get('APP_DIMENSIONS_ADMIN_URL') + '/dimension/' + this.dimensionId,
restful : true
});
this.storeUnits = new Ext.data.JsonStore({
root : "dimension.sitoolsUnits",
fields : [{
name : "label",
type : "string"
}, {
name : "unitName",
type : "string"
}],
proxy : httpProxyUnits,
autoLoad : this.action == "modify" && (!Ext.isEmpty(this.dimensionId)),
listeners : {
scope : this,
// beforeload : this.onBeforeLoad,
load : this.context._onUnitLoad
}
});
this.unitCombo = new Ext.form.ComboBox({
fieldLabel : i18n.get('label.unit'),
store : this.storeUnits,
displayField : "label",
mode : 'local',
forceSelection : false,
triggerAction : 'all',
emptyText : i18n.get('label.selectUnits'),
selectOnFocus : true,
valueField : "unitName",
name : 'unit',
anchor : '100%'
});
this.add(this.unitCombo);
this.doLayout();
};
this._onUnitLoad = function () {
if (this.dimensionId == this.dimension.getValue()) {
var unit = Ext.isEmpty(this.selectedRecord) ? null : this.selectedRecord.data.unit;
this.unitCombo.setValue(unit ? unit.unitName : null);
}
else {
this.unitCombo.setValue(null);
}
};
};
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
/*
* @include "DatasetContext.js"
* @include "ProjectContext.js"
*/
Ext.namespace('sitools.component.forms.componentsAdminDef');
/**
* Basic factory to return DatasetFactory or ProjectFactory according with context.
* @param {String} context must be "dataset" or project"
* @return {}
*/
sitools.component.forms.componentsAdminDef.ComponentFactory = function (context) {
if (context == "dataset") {
return new sitools.component.forms.componentsAdminDef.DatasetContext();
}
if (context == "project") {
return new sitools.component.forms.componentsAdminDef.ProjectContext();
}
};
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
/*
* @include "componentsListPanel.js"
* @include "componentPropPanel.js"
*/
Ext.namespace('sitools.admin.forms');
/**
* A grid to display all components of the selected Form.
* @cfg {Ext.grid.ColumnModel} datasetColumnModel the dataset Column Model (used for dataset mode)
* @cfg {Ext.data.JsonStore} storeConcepts the store of concepts
* @cfg {String} context The concept should be "dataset" or "project"
* @class sitools.admin.forms.FormGridComponents
* @extends Ext.grid.GridPanel
*/
sitools.admin.forms.FormGridComponents = Ext.extend(Ext.grid.GridPanel, {
initComponent : function () {
var storeComponents = new Ext.data.JsonStore({
root : 'data',
// url : this.urlFormulaire,
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'label',
type : 'string'
}, {
name : 'type',
type : 'string'
}, {
name : 'code',
type : 'string'
}, {
name : 'values'
}, {
name : 'width',
type : 'int'
}, {
name : 'height',
type : 'int'
}, {
name : 'xpos',
type : 'int'
}, {
name : 'ypos',
type : 'int'
}, {
name : 'css',
type : 'string'
}, {
name : 'jsAdminObject',
type : 'string'
}, {
name : 'jsUserObject',
type : 'string'
}, {
name : 'defaultValues'
}, {
name : 'valueSelection',
type : 'string'
}, {
name : 'autoComplete',
type : 'boolean'
}, {
name : 'parentParam'
}, {
name : 'dimensionId',
type : 'string'
}, {
name : 'unit'
}, {
name : 'extraParams'
}],
autoLoad : false
});
var smComponents = new Ext.grid.RowSelectionModel({
singleSelect : true
});
var cmComponents = new Ext.grid.ColumnModel({
columns : [ {
header : i18n.get('headers.label'),
dataIndex : 'label'
}, {
header : i18n.get('headers.type'),
dataIndex : 'type'
} ],
defaults : {
sortable : true,
width : 100
}
});
/*if (this.action == 'modify') {
// storeComponents.load();
}*/
var tbar = {
xtype : 'sitools.widget.GridSorterToolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreate
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this.onModify
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDelete
} ]
};
Ext.apply(this, {
title : i18n.get('title.gridComponents'),
id : "gridFormComponents",
height : 430,
store : storeComponents,
cm : cmComponents,
sm : smComponents,
tbar : tbar,
viewConfig : {
forceFit : true
},
listeners : {
scope : this,
rowDblClick : this.onModify,
dictionaryChanged : function (dictionaryId) {
this.dictionaryId = dictionaryId;
},
collectionChanged : function (collectionId) {
this.collectionId = collectionId;
}
}
});
sitools.admin.forms.FormGridComponents.superclass.initComponent.call(this);
},
onCreate : function () {
var listComponentWin = new sitools.admin.forms.componentsListPanel({
datasetColumnModel : this.datasetColumnModel,
gridFormComponents : this,
action : 'create',
context : this.context,
storeConcepts : this.storeConcepts
});
listComponentWin.show();
},
onModify : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var propComponentPanel = new sitools.admin.forms.componentPropPanel({
datasetColumnModel : this.datasetColumnModel,
gridFormComponents : this,
action : 'modify',
urlFormulaire : this.urlFormulaire,
context : this.context,
storeConcepts : this.storeConcepts
});
propComponentPanel.show();
},
onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var childrenExists = false, childrens = [];
this.getStore().each(function (record) {
if (rec.data.id === record.data.parentParam) {
childrenExists = true;
childrens.push(record.data.label);
}
});
if (childrens.length > 0) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('label.atLeastOneChildren') + childrens.join(", "));
return;
}
this.getStore().remove(rec);
}
});/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
/*
* @include "absoluteLayoutProp.js"
* @include "componentsListPanel.js"
* @include "componentPropPanel.js"
* @include "../../../client-public/js/forms/formParameterToComponent.js"
*/
Ext.namespace('sitools.admin.forms');
/**
* Panel de disposition des composants de formulaires.
* @cfg {Ext.data.Store} storeColumns The store with all filtrable columns
* @cfg {Ext.data.Store} formComponentsStore The store with all Components.
* @class sitools.admin.forms.ComponentsDisplayPanel
* @extends Ext.Panel
*/
sitools.admin.forms.ComponentsDisplayPanel = Ext.extend(Ext.Panel, {
initComponent : function () {
Ext.apply(this, {
id : "absoluteLayout",
layout : 'absolute',
title : i18n.get('label.disposition'),
autoScroll : true,
height : this.formSize.height,
width : this.formSize.width,
tbar : new Ext.Toolbar({
items : [ {
scope : this,
text : i18n.get("label.changeFormSize"),
handler : this._sizeUp
} ]
}),
listeners : {
scope : this,
activate : this._activeDisposition,
afterRender : function () {
var ddTarget = new Ext.dd.DDTarget("ddTargetId", 'group');
}
}
});
sitools.admin.forms.ComponentsDisplayPanel.superclass.initComponent.call(this);
},
_sizeUp : function () {
var panelProp = new sitools.admin.forms.absoluteLayoutProp({
absoluteLayout : this,
tabPanel : this.ownerCt.ownerCt.ownerCt,
win : this.ownerCt.ownerCt.ownerCt.ownerCt,
formSize : this.formSize
});
panelProp.show();
},
_activeDisposition : function () {
this.body.addClass(Ext.getCmp("formMainFormId").find('name', 'css')[0].getValue());
this.setSize(this.formSize);
var y = 0;
var x = 25;
var componentId = "";
this.removeAll(true);
this.formComponentsStore.each(function (component) {
y = Ext.isEmpty(component.data.ypos) ? y + 50 : component.data.ypos;
x = Ext.isEmpty(component.data.xpos) ? x : component.data.xpos;
// height = Ext.isEmpty (component.data.height) ? height :
// component.data.height;
var containerItems = [ sitools.common.forms.formParameterToComponent(component.data, null, null, this.datasetColumnModel, this.context).component ];
containerItems[0].setDisabled(true);
var container = new Ext.Container({
width : parseInt(component.data.width, 10),
height : parseInt(component.data.height, 10),
bodyCssClass : "noborder",
cls : component.data.css,
x : x,
y : y,
id : component.data.id,
componentData : component.data,
labelWidth : 100,
items : containerItems,
displayPanel : this,
record : component,
onEdit : function () {
var rec = this.record;
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var propComponentPanel = new sitools.admin.forms.componentPropPanel({
datasetColumnModel : this.displayPanel.datasetColumnModel,
action : 'modify',
urlFormulaire : this.displayPanel.urlFormulaire,
context : this.displayPanel.context,
storeConcepts : this.displayPanel.storeConcepts,
record : this.record,
formComponentsStore : this.displayPanel.formComponentsStore,
absoluteLayout : this.displayPanel
});
propComponentPanel.show();
},
onDelete : function () {
var rec = this.record;
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var childrenExists = false, childrens = [];
this.displayPanel.formComponentsStore.each(function (record) {
if (rec.data.id === record.data.parentParam) {
childrenExists = true;
childrens.push(record.data.label);
}
});
if (childrens.length > 0) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('label.atLeastOneChildren') + childrens.join(", "));
return;
}
this.displayPanel.formComponentsStore.remove(rec);
this.displayPanel.fireEvent("activate");
}
});
this.add(container);
}, this);
this.doLayout();
//add a resizer on each container.
Ext.each(this.items.items, function (container) {
var resizer = new Ext.Resizable(container.getId(), {
handles : 's e',
minWidth : 150,
maxWidth : 1000,
// minHeight : 30,
// maxHeight : 200,
constrainTo : this.body,
resizeChild : true,
listeners : {
scope : this,
resize : function (resizable, width, height, e) {
var store = this.formComponentsStore;
var rec = store.getAt(store.find('id', container.getId()));
var PanelPos = this.getEl().getAnchorXY();
rec.set("width", width);
rec.set("height", height);
container.items.items[0].setSize(width - container.getEl().getPadding('l') - container.getEl().getPadding('r'), height);
//redimensionner dans le cas de listbox :
if (rec.data.type === "LISTBOX" || rec.data.type === "LISTBOXMULTIPLE") {
var multiselect = container.findByType('multiselect')[0];
multiselect.view.container.setHeight(height - container.getEl().getPadding('b') - container.getEl().getPadding('t') - 40);
}
}
}
});
}, this);
Ext.each(this.items.items, function (container) {
container.getEl().on('contextmenu', this.onContextMenu, container);
var dd = new Ext.dd.DDProxy(container.getEl().dom.id, 'group', {
isTarget : false
});
Ext.apply(dd, {
win : this,
startDrag : function (x, y) {
var dragEl = Ext.get(this.getDragEl());
var el = Ext.get(this.getEl());
dragEl.applyStyles({
border : '',
'z-index' : this.win.ownerCt.ownerCt.lastZIndex + 1
});
dragEl.update(el.dom.innerHTML);
dragEl.addClass(el.dom.className);
this.constrainTo(this.win.body);
},
afterDrag : function () {
var dragEl = Ext.get(this.getDragEl());
var container = Ext.get(this.getEl());
var x = dragEl.getX();
var y = dragEl.getY();
var store = this.win.formComponentsStore;
var rec = store.getAt(store.find('id', container.id));
var PanelPos = Ext.get(this.win.body).getAnchorXY();
rec.set("xpos", x - PanelPos[0]);
rec.set("ypos", y - PanelPos[1]);
}
});
}, this);
},
onContextMenu : function (event, htmlEl, options) {
//ici le this est le container sur lequel on a cliqué.
event.stopEvent();
var ctxMenu = new Ext.menu.Menu({
items : [{
text : i18n.get('label.edit'),
scope : this,
handler : this.onEdit
}, {
text : i18n.get('label.delete'),
scope : this,
handler : this.onDelete
}]
});
var xy = event.getXY();
ctxMenu.showAt(xy);
}
});/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
/*
* @include "../id.js"
* @include "formPropPanel.js"
*/
Ext.namespace('sitools.admin.forms');
/**
* A GridPanel to display all forms.
* @class sitools.admin.forms.formsCrudPanel
* @extends Ext.grid.GridPanel
*/
sitools.admin.forms.formsCrudPanel = Ext.extend(Ext.grid.GridPanel, {
//sitools.component.forms.formsCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.FORMS,
pageSize : 10,
urlFormulaires : "/tmp",
// loadMask: true,
initComponent : function () {
this.baseUrlFormulaires = loadUrl.get('APP_URL') + loadUrl.get('APP_DATASETS_URL');
this.urlDatasets = loadUrl.get('APP_URL') + loadUrl.get('APP_DATASETS_URL');
this.httpProxyForms = new Ext.data.HttpProxy({
url : "/tmp",
restful : true,
method : 'GET'
});
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
proxy : this.httpProxyForms,
remoteSort : true,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
} ]
});
var storeDatasets = new Ext.data.JsonStore({
fields : [ 'id', 'name', 'columnModel' ],
url : this.urlDatasets,
root : "data",
autoLoad : true
});
this.comboDatasets = new Ext.form.ComboBox({
store : storeDatasets,
displayField : 'name',
valueField : 'id',
typeAhead : true,
mode : 'local',
forceSelection : true,
triggerAction : 'all',
emptyText : i18n.get('label.selectDatasets'),
selectOnFocus : true,
listeners : {
scope : this,
select : function (combo, rec, index) {
this.datasetId = rec.data.id;
this.datasetColumnModel = rec.data.columnModel;
this.httpProxyForms.setUrl(this.baseUrlFormulaires + "/" + rec.data.id + "/forms", true);
this.loadFormulaires(rec.data.id);
}
}
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100,
sortable : true
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 400,
sortable : false
} ]
});
this.bbar = {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
};
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ this.comboDatasets, {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreate,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this.onModify,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDelete,
xtype : 's-menuButton'
}
// { text: i18n.get('label.members'), icon:
// 'res/images/icons/toolbar_group_add.png', handler: this.onMembers
// },
// '->',
// {xtype:'s-filter', emptyText:i18n.get('label.search'),
// store:this.store, pageSize:this.pageSize}
]
};
this.view = new Ext.grid.GridView({
forceFit : true
});
this.listeners = {
scope : this,
rowDblClick : this.onModify
};
sitools.admin.forms.formsCrudPanel.superclass.initComponent.call(this);
},
loadFormulaires : function (datasetId) {
// alert (dictionaryId);
this.urlFormulaires = this.baseUrlFormulaires + "/" + datasetId + "/forms";
this.httpProxyForms.setUrl(this.urlFormulaires, true);
this.getStore().load({
scope : this,
callback : function () {
this.getView().refresh();
}
});
},
// onRender : function (){
// sitools.admin.forms.formsCrudPanel.superclass.onRender.apply(this,
// arguments);
// this.store.load({params:{start:0, limit:this.pageSize}});
// },
onCreate : function () {
if (Ext.isEmpty(this.comboDatasets.getValue())) {
return;
}
var up = new sitools.admin.forms.formPropPanel({
urlFormulaire : this.urlFormulaires,
action : 'create',
store : this.getStore(),
datasetColumnModel : this.datasetColumnModel
});
up.show(ID.BOX.FORMS);
},
onModify : function () {
if (Ext.isEmpty(this.comboDatasets.getValue())) {
return;
}
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.admin.forms.formPropPanel({
urlFormulaire : this.baseUrlFormulaires + '/' + this.datasetId + '/forms/' + rec.data.id,
action : 'modify',
store : this.getStore(),
datasetColumnModel : this.datasetColumnModel
});
up.show(ID.BOX.FORMS.COMPONENTLIST);
},
onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return false;
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('formsCrud.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec);
}
}
});
},
doDelete : function (rec) {
// var rec = this.getSelectionModel().getSelected();
// if (!rec) return false;
Ext.Ajax.request({
url : this.baseUrlFormulaires + "/" + this.datasetId + "/forms/" + rec.id,
method : 'DELETE',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
}
});
Ext.reg('s-forms', sitools.admin.forms.formsCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
/*
* @include "absoluteLayoutProp.js"
* @include "componentsListPanel.js"
*/
Ext.namespace('sitools.admin.forms');
/**
* A window that contains a definition of Form Component.
* @cfg {string} collectionId the collectionId
* @cfg {Ext.data.Record} record The record to edit.
* @cfg {} xyOnCreate An object containing xy position to create the new component.
* @class sitools.admin.forms.componentPropPanel
* @extends Ext.Window
*/
sitools.admin.forms.componentPropPanel = Ext.extend(Ext.Window, {
modal : true,
pageSize : 10,
initComponent : function () {
this.title = i18n.get('label.componentProperties');
var specificComponentString, config = {}, JsObj;
if (this.action == 'modify') {
var rec = this.record;
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
JsObj = eval(rec.data.jsAdminObject);
config = {
datasetColumnModel : this.datasetColumnModel,
winPropComponent : this,
action : this.action,
selectedRecord : rec,
jsUserObject : rec.data.jsUserObject,
ctype : rec.data.type,
componentDefaultHeight : rec.data.height,
componentDefaultWidth : rec.data.width,
dimensionId : rec.data.dimensionId,
unit : rec.data.unit,
extraParams : rec.data.extraParams,
context : this.context,
storeConcepts : this.storeConcepts,
formComponentsStore : this.formComponentsStore
};
} else {
JsObj = eval(this.jsAdminObject);
config = {
datasetColumnModel : this.datasetColumnModel,
winPropComponent : this,
action : this.action,
ctype : this.ctype,
jsAdminObject : this.jsAdminObject,
jsUserObject : this.jsUserObject,
componentDefaultHeight : this.componentDefaultHeight,
componentDefaultWidth : this.componentDefaultWidth,
extraParams : this.extraParams,
context : this.context,
storeConcepts : this.storeConcepts,
formComponentsStore : this.formComponentsStore,
xyOnCreate : this.xyOnCreate
};
}
var specificComponent = new JsObj(config);
this.componentPropPanel = new Ext.Panel({
layout : 'fit',
padding : 10,
autoScroll : true,
items : [ specificComponent ],
buttons : [ {
text : i18n.get('label.addColumn'),
hidden : !Ext.isFunction(specificComponent.addColumn),
handler : function () {
specificComponent.addColumn();
}
}, {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : this._close
} ]
});
this.items = [ this.componentPropPanel ];
// console.dir (this.component);
sitools.admin.forms.componentPropPanel.superclass.initComponent.call(this);
},
afterRender : function () {
this.height = this.specificHeight;
this.width = this.specificWidth;
sitools.admin.forms.componentPropPanel.superclass.afterRender.call(this);
},
onValidate : function () {
var component = this.findById('sitools.component.forms.definitionId');
if (component._onValidate(this.action, this.formComponentsStore)) {
this.close();
}
this.absoluteLayout.fireEvent("activate");
},
_close : function () {
this.close();
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace("sitools.admin.forms");
/**
* A simple window to edit Absolute Layout Size.
* @cfg {numeric} width the initial width
* @cfg {numeric} height the initial height
* @cfg {Ext.Panel} absoluteLayout The panel to change size
* @cfg {Ext.TabPanel} tabPanel The main TabPanel
* @cfg {Ext.Window} win The window to define a form.
* @class sitools.admin.forms.absoluteLayoutProp
* @extends Ext.Window
*/
sitools.admin.forms.absoluteLayoutProp = Ext.extend(Ext.Window, {
modal : true,
initComponent : function () {
var width = this.formSize.width;
var height = this.formSize.height;
var form = new Ext.form.FormPanel({
labelWidth : 75,
padding : 5,
items : [ {
xtype : 'textfield',
id : "absolutePanelWidth",
value : width,
fieldLabel : i18n.get('label.width'),
anchor : "100%"
}, {
xtype : 'textfield',
id : "absolutePanelHeight",
value : height,
fieldLabel : i18n.get('label.height'),
anchor : "100%"
} ],
buttons : [ {
scope : this,
text : i18n.get('label.ok'),
handler : this._onValidate
}, {
scope : this,
text : i18n.get('label.cancel'),
handler : this._onCancel
} ]
});
this.height = 130;
this.width = 260;
this.title = i18n.get('label.setSize');
this.items = [ form ];
sitools.admin.forms.absoluteLayoutProp.superclass.initComponent.call(this);
},
_onValidate : function () {
var f = this.findByType('form')[0].getForm();
var width = parseInt(f.findField('absolutePanelWidth').getValue(), 10);
var height = parseInt(f.findField('absolutePanelHeight').getValue(), 10);
var size = {
width : width,
height : height
};
// this.tabPanel.setSize({
// width : size.width + 225,
// height : size.height
// });
// this.tabPanel.doLayout();
this.absoluteLayout.setSize(size);
this.absoluteLayout.doLayout();
this.absoluteLayout.formSize = size;
this.win.formSize = size;
this.win.doLayout();
this.destroy();
},
_onCancel : function () {
this.destroy();
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
/*
* @include "absoluteLayoutProp.js"
*/
Ext.namespace('sitools.admin.forms');
/**
* A window to present all form Components type
* @cfg {Ext.data.JsonStore} storeConcepts the store with concepts
* @class sitools.admin.forms.componentsListPanel
* @extends Ext.Window
*/
sitools.admin.forms.componentsListPanel = Ext.extend(Ext.grid.GridPanel, {
width : 220,
initComponent : function () {
this.title = i18n.get('label.chooseComponent');
var storeComponents = new Ext.data.JsonStore({
root : 'data',
url : loadUrl.get('APP_URL') + loadUrl.get('APP_FORMCOMPONENTS_URL'),
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'type',
type : 'string'
}, {
name : 'componentDefaultHeight',
type : 'string'
}, {
name : 'componentDefaultWidth',
type : 'string'
}, {
name : 'jsAdminObject',
type : 'string'
}, {
name : 'jsUserObject',
type : 'string'
}, {
name : 'imageUrl',
type : 'string'
}, {
name : 'dimensionId',
type : 'string'
}, {
name : 'unit',
type : 'string'
}, {
name : 'extraParams'
} ],
autoLoad : true,
sortInfo: {
field: 'type',
direction: 'ASC' // or 'DESC' (case sensitive for local sorting)
}
});
var smComponents = new Ext.grid.RowSelectionModel({
singleSelect : true
});
var cmComponents = new Ext.grid.ColumnModel({
columns : [ {
header : i18n.get('headers.type'),
dataIndex : 'type',
width : 150
}, {
header : i18n.get('headers.image'),
dataIndex : 'imageUrl',
renderer : function (value) {
return "<a href='#' onClick='sitools.admin.forms.componentsListPanel.showPreview(\"" + value + "\"); return false;'>" + i18n.get('label.preview') + "</a>";
},
width : 70
} ],
defaults : {
sortable : true,
width : 100
}
});
// this.gridComponents = new Ext.grid.GridPanel({
// layout : "fit",
// title : i18n.get('title.componentList'),
// autoScroll : true,
// store : storeComponents,
// cm : cmComponents,
// sm : smComponents,
// viewConfig : {
// forceFit : true
// },
// buttons : [ {
// text : i18n.get('label.ok'),
// scope : this,
// handler : this.onValidate
// }, {
// text : i18n.get('label.cancel'),
// scope : this,
// handler : function () {
// this.close();
// }
// } ]
// });
//// this.items = [ this.gridComponents ];
Ext.apply(this, {
layout : "fit",
title : i18n.get('title.componentList'),
autoScroll : true,
store : storeComponents,
cm : cmComponents,
sm : smComponents,
ddGroup : 'gridComponentsList',
enableDragDrop : true,
viewConfig : {
forceFit : true
}
// ,
// buttons : [ {
// text : i18n.get('label.ok'),
// scope : this,
// handler : this.onValidate
// }, {
// text : i18n.get('label.cancel'),
// scope : this,
// handler : function () {
// this.close();
// }
// } ]
});
sitools.admin.forms.componentsListPanel.superclass.initComponent.call(this);
},
afterRender : function () {
sitools.admin.forms.componentsListPanel.superclass.afterRender.apply(this, arguments);
// this.gridComponents.setSize(this.body.getSize());
},
// onValidate : function () {
// var rec = this.getSelectionModel().getSelected();
// if (!rec) {
// return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
// }
// var ComponentWin = new sitools.admin.forms.componentPropPanel({
// urlAdmin : rec.data.jsonDefinitionAdmin,
// datasetColumnModel : this.datasetColumnModel,
// ctype : rec.data.type,
// gridFormComponents : this.gridFormComponents,
// action : this.action,
// componentDefaultHeight : rec.data.componentDefaultHeight,
// componentDefaultWidth : rec.data.componentDefaultWidth,
// dimensionId : rec.data.dimensionId,
// unit : rec.data.unit,
// extraParams : rec.data.extraParams,
// jsAdminObject : rec.data.jsAdminObject,
// jsUserObject : rec.data.jsUserObject,
// context : this.context,
// storeConcepts : this.storeConcepts
// });
// ComponentWin.show();
// this.close();
// },
onClose : function () {
this.close();
}
});
/**
* Show a preview of a specific compoennt type
* @static
* @param {string} value
*/
sitools.admin.forms.componentsListPanel.showPreview = function (value) {
var previewWin = new Ext.Window({
title : i18n.get('label.showPreview'),
modal : true,
html : "<img src ='" + value + "'>",
layout : "fit",
height : "auto",
width : "auto",
buttons : [ {
text : i18n.get('label.close'),
handler : function () {
this.ownerCt.ownerCt.destroy();
}
} ]
});
previewWin.show();
};/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
/*
* @include "absoluteLayoutProp.js"
* @include "componentsListPanel.js"
* @include "componentPropPanel.js"
* @include "ComponentsDisplayPanel.js"
* @include "FormGridComponents.js"
*/
Ext.namespace('sitools.admin.forms');
/**
*
* @class sitools.admin.forms.formPropPanel
* @extends Ext.Window
*/
sitools.admin.forms.formPropPanel = Ext.extend(Ext.Window, {
width : 700,
height : 580,
modal : true,
pageSize : 10,
autoScroll : true,
formSize : {
width : 500,
height : 500
},
initComponent : function () {
if (this.action == 'modify') {
this.title = i18n.get('label.modifyForm');
}
if (this.action == 'create') {
this.title = i18n.get('label.createForm');
}
this.formComponentsStore = new Ext.data.JsonStore({
root : 'data',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'label',
type : 'string'
}, {
name : 'type',
type : 'string'
}, {
name : 'code',
type : 'string'
}, {
name : 'values'
}, {
name : 'width',
type : 'int'
}, {
name : 'height',
type : 'int'
}, {
name : 'xpos',
type : 'int'
}, {
name : 'ypos',
type : 'int'
}, {
name : 'css',
type : 'string'
}, {
name : 'jsAdminObject',
type : 'string'
}, {
name : 'jsUserObject',
type : 'string'
}, {
name : 'defaultValues'
}, {
name : 'valueSelection',
type : 'string'
}, {
name : 'autoComplete',
type : 'boolean'
}, {
name : 'parentParam'
}, {
name : 'dimensionId',
type : 'string'
}, {
name : 'unit'
}, {
name : 'extraParams'
}],
autoLoad : false
});
this.formulairePrincipal = new Ext.FormPanel({
title : i18n.get('label.formInfo'),
id : "formMainFormId",
border : false,
padding : 10,
items : [ {
xtype : 'hidden',
name : 'id'
}, {
xtype : 'textfield',
name : 'name',
fieldLabel : i18n.get('label.name'),
anchor : '100%',
maxLength : 50,
vtype : 'name',
allowBlank : false
}, {
xtype : 'textfield',
name : 'description',
fieldLabel : i18n.get('label.description'),
anchor : '100%',
maxLength : 50
}, {
xtype : 'textfield',
name : 'css',
fieldLabel : i18n.get('label.css'),
anchor : '100%',
maxLength : 50
} ]
});
var storeColumns = new Ext.data.JsonStore({
// root : 'data',
// url : loadUrl.get('APP_URL') + loadUrl.get('APP_COLLECTIONS_URL') + "/" + config.collectionId + "/concepts/" + config.dictionaryId,
// proxy : httpProxyConcepts,
// restful : true,
remoteSort : false,
fields : [ {
name : 'tableName',
type : 'string'
}, {
name : 'columnAlias',
type : 'string'
}, {
name : 'filtrable'
}],
autoLoad : false
});
var cmColumns = new Ext.grid.ColumnModel({
columns : [{
header : i18n.get("label.tableName"),
dataIndex : 'tableName',
type : 'string'
}, {
header : i18n.get("label.columnAlias"),
dataIndex : 'columnAlias',
type : 'string'
}]
});
this.gridColumns = new Ext.grid.GridPanel({
store : storeColumns,
cm : cmColumns,
title : i18n.get('label.datasetColumns'),
flex : 1,
viewConfig : {
forceFit : true
}
});
Ext.each(this.datasetColumnModel, function (column) {
if (column.specificColumnType != 'VIRTUAL') {
this.gridColumns.getStore().add(new Ext.data.Record(column));
}
}, this);
var firstPanel = new Ext.Panel({
title : i18n.get('label.FormInfo'),
layout : "vbox",
layoutConfig : {
align : "stretch"
},
items : [this.formulairePrincipal, this.gridColumns],
listeners : {
collectionChanged : function (field, newValue, oldValue) {
this.getBubbleTarget().fireEvent("collectionChanged", field, newValue, oldValue);
},
dictionaryChanged : function (field, newValue, oldValue) {
this.getBubbleTarget().fireEvent("dictionaryChanged", field, newValue, oldValue);
}
}
});
this.absoluteLayout = new sitools.admin.forms.ComponentsDisplayPanel({
formComponentsStore : this.formComponentsStore,
datasetColumnModel : this.datasetColumnModel,
context : "dataset",
formSize : this.formSize
});
var absContainer = new Ext.Panel({
flex : 1,
autoScroll : true,
items : [this.absoluteLayout]
});
this.componentListPanel = new sitools.admin.forms.componentsListPanel({
datasetColumnModel : this.datasetColumnModel,
formComponentsStore : this.formComponentsStore,
action : 'create',
context : "dataset",
storeConcepts : this.storeConcepts
});
var dispPanel = new Ext.Panel({
layout : "hbox",
title : i18n.get('label.disposition'),
layoutConfig : {
align : "stretch"
},
items : [this.componentListPanel, absContainer],
listeners : {
scope : this,
activate : function () {
this.absoluteLayout.fireEvent('activate');
var absoluteLayout = this.absoluteLayout;
var displayPanelDropTargetEl = absoluteLayout.body.dom;
var formComponentsStore = this.formComponentsStore;
var datasetColumnModel = this.datasetColumnModel;
var storeConcepts = this.storeConcepts;
var displayPanelDropTarget = new Ext.dd.DropTarget(displayPanelDropTargetEl, {
ddGroup : 'gridComponentsList',
notifyDrop : function (ddSource, e, data) {
var xyDrop = e.xy;
var xyRef = Ext.get(absoluteLayout.body).getXY();
var xyOnCreate = {
x : xyDrop[0] - xyRef[0],
y : xyDrop[1] - xyRef[1]
};
// Reference the record (single selection) for readability
var rec = ddSource.dragData.selections[0];
var ComponentWin = new sitools.admin.forms.componentPropPanel({
urlAdmin : rec.data.jsonDefinitionAdmin,
datasetColumnModel : datasetColumnModel,
ctype : rec.data.type,
action : "create",
componentDefaultHeight : rec.data.componentDefaultHeight,
componentDefaultWidth : rec.data.componentDefaultWidth,
dimensionId : rec.data.dimensionId,
unit : rec.data.unit,
extraParams : rec.data.extraParams,
jsAdminObject : rec.data.jsAdminObject,
jsUserObject : rec.data.jsUserObject,
context : "dataset",
xyOnCreate : xyOnCreate,
storeConcepts : this.storeConcepts,
absoluteLayout : absoluteLayout,
record : rec,
formComponentsStore : formComponentsStore
});
ComponentWin.show();
}
});
}
}
});
this.tabPanel = new Ext.TabPanel({
height : 450,
activeTab : 0,
items : [ firstPanel, dispPanel ],
listeners : {
scope : this,
afterrender : function (panel) {
panel.setSize(this.body.getSize());
}
}
});
this.items = [ this.tabPanel ];
this.buttons = [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ];
this.listeners = {
scope : this,
resize : function (window, width, height) {
var size = window.body.getSize();
this.tabPanel.setSize(size);
}
};
sitools.admin.forms.formPropPanel.superclass.initComponent.call(this);
},
onRender : function () {
sitools.admin.forms.formPropPanel.superclass.onRender.apply(this, arguments);
if (this.urlFormulaire) {
// Si l'objet est en modification, on charge l'objet en question
if (this.action == 'modify') {
Ext.Ajax.request({
url : this.urlFormulaire,
method : 'GET',
scope : this,
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (!Json.success) {
this.close();
Ext.Msg.alert(i18n.get('label.warning'), Json.message);
return;
}
var f = this.findByType('form')[0].getForm();
var data = Json.form;
if (!Ext.isEmpty(data.width)) {
this.formSize.width = data.width;
}
if (!Ext.isEmpty(data.height)) {
this.formSize.height = data.height;
}
var rec = {};
rec.id = data.id;
rec.name = data.name;
rec.description = data.description;
rec.css = data.css;
var record = new Ext.data.Record(rec);
f.loadRecord(record);
if (data.parameters) {
var parameters = data.parameters;
var i;
for (i = 0; i < parameters.length; i++) {
this.formComponentsStore.add(new Ext.data.Record({
type : parameters[i].type,
code : parameters[i].code,
label : parameters[i].label,
values : parameters[i].values,
width : parameters[i].width,
height : parameters[i].height,
xpos : parameters[i].xpos,
ypos : parameters[i].ypos,
id : parameters[i].id,
css : parameters[i].css,
jsAdminObject : parameters[i].jsAdminObject,
jsUserObject : parameters[i].jsUserObject,
defaultValues : parameters[i].defaultValues,
valueSelection : parameters[i].valueSelection,
autoComplete : parameters[i].autoComplete,
parentParam : parameters[i].parentParam,
dimensionId : parameters[i].dimensionId,
unit : parameters[i].unit,
extraParams : parameters[i].extraParams
}));
}
}
// this.setSize(data.width + 25, data.height + 35);
this.doLayout();
},
failure : function (ret) {
var data = Ext.decode(ret.responseText);
Ext.Msg.alert(i18n.get('label.warning'), data.errorMessage);
}
});
}
}
},
onValidate : function () {
var f = this.findByType('form')[0].getForm();
if (!f.isValid()) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.invalidForm'));
return false;
}
var putObject = {};
Ext.iterate(f.getValues(), function (key, value) {
putObject[key] = value;
}, this);
var width = this.formSize.width;
var height = this.formSize.height;
putObject.width = width;
putObject.height = height;
var store = this.formComponentsStore;
if (store.getCount() > 0) {
putObject.parameters = [];
}
store.each(function (component) {
putObject.parameters.push({
type : component.data.type,
code : component.data.code,
label : component.data.label,
values : component.data.values,
width : component.data.width,
height : component.data.height,
xpos : component.data.xpos,
ypos : component.data.ypos,
id : component.data.id,
css : component.data.css,
jsAdminObject : component.data.jsAdminObject,
jsUserObject : component.data.jsUserObject,
defaultValues : component.data.defaultValues,
valueSelection : component.data.valueSelection,
autoComplete : component.data.autoComplete,
parentParam : component.data.parentParam,
dimensionId : component.data.dimensionId,
unit : component.data.unit,
extraParams : component.data.extraParams
});
});
if (this.action == 'modify') {
Ext.Ajax.request({
url : this.urlFormulaire,
method : 'PUT',
scope : this,
jsonData : putObject,
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (!Json.success) {
Ext.Msg.alert(i18n.get('label.warning'), Json.message);
return;
}
this.close();
this.store.reload();
},
failure : alertFailure
});
} else {
Ext.Ajax.request({
url : this.urlFormulaire,
method : 'POST',
scope : this,
jsonData : putObject,
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (!Json.success) {
Ext.Msg.alert(i18n.get('label.warning'), Json.message);
return;
}
this.close();
this.store.reload();
// Ext.Msg.alert(i18n.get('label.information'),
// i18n.get('msg.uservalidate'));
},
failure : alertFailure
});
}
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp */
Ext.namespace('sitools.admin.forms');
sitools.admin.forms.parentParamWin = Ext.extend(Ext.Window, {
//sitools.component.forms.parentParamWin = Ext.extend(Ext.Window, {
modal : true,
title : i18n.get('label.chooseParent'),
width : 500,
initComponent : function () {
var storeComponents = this.store;
var smComponents = new Ext.grid.RowSelectionModel({
singleSelect : true
});
var cmComponents = new Ext.grid.ColumnModel({
columns : [ {
header : i18n.get('headers.label'),
dataIndex : 'label'
}, {
header : i18n.get('headers.type'),
dataIndex : 'type'
}],
defaults : {
sortable : true,
width : 100
}
});
this.gridFormComponents = new Ext.grid.GridPanel({
title : i18n.get('title.gridComponents'),
layout : 'fit',
id : "gridFormParentComponents",
height : 430,
store : storeComponents,
cm : cmComponents,
sm : smComponents,
viewConfig : {
forceFit : true
}
});
this.items = [{
xtype : 'panel',
layout : 'fit',
items : [this.gridFormComponents ],
buttons : [{
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.none'),
scope : this,
handler : this._none
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : this._close
}]
}];
sitools.admin.forms.parentParamWin.superclass.initComponent.call(this);
},
onRender : function () {
sitools.admin.forms.parentParamWin.superclass.onRender.apply(this, arguments);
},
onValidate : function () {
this.parentParamField.setValue(this.gridFormComponents.getSelectionModel().getSelected().data);
this.parentParamFieldDisplay.setValue(this.gridFormComponents.getSelectionModel().getSelected().data.label);
this.close();
},
_close : function () {
this.close();
},
_none : function () {
this.parentParamField.setValue(null);
this.parentParamFieldDisplay.setValue(null);
this.close();
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp*/
/*
* @include "../ComponentFactory.js"
*/
Ext.namespace('sitools.admin.forms.oneParam');
/**
* An abstract form to build one Param components
* @class sitools.admin.forms.oneParam.abstractForm
* @extends Ext.form.FormPanel
*/
sitools.admin.forms.oneParam.abstractForm = Ext.extend(Ext.form.FormPanel, {
//sitools.component.forms.oneParam.abstractForm = Ext.extend(Ext.form.FormPanel, {
autoScroll : true,
context : null,
initComponent : function () {
this.context = new sitools.component.forms.componentsAdminDef.ComponentFactory(this.context);
this.buttonAdd = new Ext.Button({
text : i18n.get('label.addColumn'),
scope : this,
handler : function (button) {
this.addColumn(button);
}
});
this.buttonDel = new Ext.Button({
text : i18n.get('label.deleteColumn'),
scope : this,
handler : function (button) {
this.deleteColumn(button);
}
});
this.labelParam1 = new Ext.form.TextField({
fieldLabel : i18n.get('label.label'),
name : 'LABEL_PARAM1',
anchor : '100%',
tooltip : i18n.get("label.formLabel")
});
/**
* The combo that contains the list of Columns or shared Concepts.
* it is required to build this mapParam1 for all forms components.
*/
this.mapParam1 = this.context.buildComboParam1(this);
this.css = new Ext.form.TextField({
fieldLabel : i18n.get('label.css'),
name : 'CSS',
anchor : '100%'
});
this.componentDefaultHeight = new Ext.form.TextField({
fieldLabel : i18n.get('label.height'),
name : 'componentDefaultHeight',
anchor : '100%',
value : this.componentDefaultHeight,
allowBlank : false
});
this.componentDefaultWidth = new Ext.form.TextField({
fieldLabel : i18n.get('label.width'),
name : 'componentDefaultWidth',
anchor : '100%',
value : this.componentDefaultWidth,
allowBlank : false
});
this.items = [ this.labelParam1, this.mapParam1, this.css];
if (this.action == "create") {
this.items.push(this.componentDefaultHeight, this.componentDefaultWidth);
}
this.padding = 10;
sitools.admin.forms.oneParam.abstractForm.superclass.initComponent.call(this);
},
afterRender : function () {
sitools.admin.forms.oneParam.abstractForm.superclass.afterRender.apply(this, arguments);
if (this.action == 'modify') {
this.labelParam1.setValue(this.selectedRecord.data.label);
this.css.setValue(this.selectedRecord.data.css);
var codes = this.selectedRecord.data.code;
this.mapParam1.setValue(this.selectedRecord.data.code[0]);
}
},
_onValidate : function (action, formComponentsStore) {
/**
* Chaque classe étandant cet objet doit redéfinir cette méthode
*/
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('msg.OnvalidateNotDefined'));
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser, loadUrl
showHelp*/
/*
* @include "../ComponentFactory.js"
* @include "Abstract.js"
* @include "../ComponentFactory.js"
* @include "../DatasetContext.js"
* @include "../ProjectContext.js"
*/
Ext.namespace('sitools.admin.forms.oneParam');
/**
* Another Abstract formPanel to define one param components with unit.
* @class sitools.admin.forms.oneParam.abstractWithUnit
* @extends sitools.admin.forms.oneParam.abstractForm
*/
sitools.admin.forms.oneParam.abstractWithUnit = Ext.extend(sitools.admin.forms.oneParam.abstractForm, {
//sitools.admin.forms.components.oneParam.abstractWithUnit = Ext.extend(sitools.admin.forms.oneParam.abstractForm, {
initComponent : function () {
sitools.admin.forms.oneParam.abstractWithUnit.superclass.initComponent.call(this);
this.storeDimension = new Ext.data.JsonStore({
root : "data",
fields : [{
name : "id",
type : "string"
}, {
name : "name",
type : "string"
}, {
name : "description",
type : "string"
}, {
name : "dimensionHelperName",
type : "string"
}],
url : loadUrl.get('APP_URL') + loadUrl.get('APP_DIMENSIONS_ADMIN_URL') + '/dimension',
restful : true,
autoLoad : false,
listeners : {
scope : this,
// beforeload : this.onBeforeLoad,
load : this._onDimensionLoad
}
});
this.on("beforerender", this.onBeforeRender, this);
this.mapParam1.on("select", this.onChangeColumn, this);
},
onBeforeRender : function () {
if (!this.loaded) {
this.storeDimension.load();
}
},
// onBeforeLoad : function () {
// this.storeDimension.baseParams = this.baseParams;
// return true;
// },
_onDimensionLoad : function () {
this.dimension = new Ext.form.ComboBox({
fieldLabel : i18n.get('label.dimension'),
store : this.storeDimension,
displayField : "name",
mode : 'local',
forceSelection : false,
triggerAction : 'all',
emptyText : i18n.get('label.selectDimension'),
selectOnFocus : true,
valueField : "id",
name : 'dimensionId',
anchor : '100%',
disabled : true,
value : Ext.isEmpty(this.selectedRecord) ? null : this.selectedRecord.data.dimensionId
});
//determine if the dimension must be active
this.context.activeDimension.call(this);
this.add(this.dimension);
this.doLayout();
this.context.buildUnit.call(this);
},
onChangeColumn : function () {
this.context.onChangeColumn.call(this);
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp*/
Ext.namespace('sitools.admin.forms.multiParam');
/**
* An abstract form to define MultiParam Components
* @class sitools.admin.forms.multiParam.abstractForm
* @extends Ext.form.FormPanel
*/
sitools.admin.forms.multiParam.abstractForm = Ext.extend(Ext.form.FormPanel, {
//sitools.component.forms.multiParam.abstractForm = Ext.extend(Ext.form.FormPanel, {
autoScroll : true,
initComponent : function () {
this.context = new sitools.component.forms.componentsAdminDef.ComponentFactory(this.context);
this.storeColumn = new Ext.data.JsonStore({
id : 'storeColumnSelect',
root : 'ColumnModel',
idProperty : 'header',
remoteSort : false,
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'dataIndex',
type : 'string'
}, {
name : 'schema',
type : 'string'
}, {
name : 'tableAlias',
type : 'string'
}, {
name : 'tableName',
type : 'string'
}, {
name : 'header',
type : 'string'
}, {
name : 'toolTip',
type : 'string'
}, {
name : 'width',
type : 'int'
}, {
name : 'sortable',
type : 'boolean'
}, {
name : 'visible',
type : 'boolean'
}, {
name : 'filter',
type : 'boolean'
}, {
name : 'columnOrder',
type : 'int'
}, {
name : 'columnType',
type : 'string'
}, {
name : 'notion',
type : 'string',
mapping : 'notion.name'
}, {
name : 'notionUrl',
type : 'string',
mapping : 'notion.url'
}, {
name : 'columnAlias',
type : 'string'
}
]
});
Ext.each(this.datasetColumnModel, function (column) {
if (column.specificColumnType != 'VIRTUAL') {
this.storeColumn.add(new Ext.data.Record(column));
}
}, this);
this.buttonAdd = new Ext.Button({
text : i18n.get('label.addColumn'),
scope : this,
handler : function (button) {
this.addColumn(button);
}
});
this.buttonDel = new Ext.Button({
text : i18n.get('label.deleteColumn'),
scope : this,
handler : function (button) {
this.deleteColumn(button);
}
});
this.labelParam1 = new Ext.form.TextField({
fieldLabel : i18n.get('label.label'),
name : 'LABEL_PARAM1',
anchor : '100%'
});
this.css = new Ext.form.TextField({
fieldLabel : i18n.get('label.css'),
name : 'CSS',
anchor : '100%'
});
this.componentDefaultHeight = new Ext.form.TextField({
fieldLabel : i18n.get('label.height'),
name : 'componentDefaultHeight',
anchor : '100%',
value : this.componentDefaultHeight,
allowBlank : false
});
this.componentDefaultWidth = new Ext.form.TextField({
fieldLabel : i18n.get('label.width'),
name : 'componentDefaultWidth',
anchor : '100%',
value : this.componentDefaultWidth,
allowBlank : false
});
this.items = [ this.labelParam1, this.css ];
if (this.action == "create") {
this.items.push(this.componentDefaultHeight, this.componentDefaultWidth);
}
this.padding = 10;
sitools.admin.forms.multiParam.abstractForm.superclass.initComponent.call(this);
},
afterRender : function () {
sitools.admin.forms.multiParam.abstractForm.superclass.afterRender.apply(this, arguments);
if (this.action == 'modify') {
this.labelParam1.setValue(this.selectedRecord.data.label);
this.css.setValue(this.selectedRecord.data.css);
}
},
_onValidate : function (action, formComponentsStore) {
/**
* Chaque classe étandant cet objet doit redéfinir cette méthode
*/
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('msg.OnvalidateNotDefined'));
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, showResponse, alertFailure, loadUrl*/
/*
* @include "roleWin.js"
*/
Ext.namespace('sitools.admin.applications');
/**
* A window to display Roles and authorizations for each options.
* @cfg {string} urlAuthorizations
* @cfg {Ext.data.Record} applicationRecord
* @class sitools.admin.applications.applicationsRolePanel
* @extends Ext.Window
* @requires sitools.component.applications.rolesPanel
*/
//sitools.component.applications.applicationsRolePanel = Ext.extend(Ext.Window, {
sitools.admin.applications.applicationsRolePanel = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
pageSize : 10,
dataSets : "",
initComponent : function () {
this.title = i18n.get('label.authorizations') + " : " + this.applicationRecord.data.name;
var storeAuthorizations = new Ext.data.JsonStore({
id : 'storeAuthorizations',
root : 'authorization.authorizations',
url : this.urlAuthorizations,
idProperty : 'role',
fields : [ {
name : 'role',
type : 'string'
}, {
name : 'allMethod',
type : 'boolean'
}, {
name : 'postMethod',
type : 'boolean'
}, {
name : 'getMethod',
type : 'boolean'
}, {
name : 'putMethod',
type : 'boolean'
}, {
name : 'deleteMethod',
type : 'boolean'
}, {
name : 'headMethod',
type : 'boolean'
}, {
name : 'optionsMethod',
type : 'boolean'
} ],
autoLoad : true,
listeners : {
scope : this,
update : function (store, record) {
var grid = this.gridAuthorizations;
var index = store.indexOf(record);
var value = record.get('allMethod');
for (var i = 2; i < 8; i++) {
var idPost = grid.getView().getCell(index, i).firstChild.firstChild.id;
var cmpPost = Ext.getCmp(idPost);
cmpPost.setEnabled(!value);
}
},
load : function (store, records) {
var grid = this.gridAuthorizations;
var value, index, idPost, cmpPost;
Ext.each(records, function (record) {
store.fireEvent("update", store, record);
}, this);
}
}
});
this.cbAll = new Ext.grid.CheckColumn({
header : i18n.get('headers.all'),
dataIndex : 'allMethod',
width : 55
});
this.cbPost = new Ext.grid.CheckColumn({
header : i18n.get('headers.post'),
dataIndex : 'postMethod',
width : 55
});
this.cbGet = new Ext.grid.CheckColumn({
header : i18n.get('headers.get'),
dataIndex : 'getMethod',
width : 55
});
this.cbPut = new Ext.grid.CheckColumn({
header : i18n.get('headers.put'),
dataIndex : 'putMethod',
width : 55
});
this.cbDelete = new Ext.grid.CheckColumn({
header : i18n.get('headers.delete'),
dataIndex : 'deleteMethod',
width : 55
});
this.cbHead = new Ext.grid.CheckColumn({
header : i18n.get('headers.head'),
dataIndex : 'headMethod',
width : 55
});
this.cbOptions = new Ext.grid.CheckColumn({
header : i18n.get('headers.options'),
dataIndex : 'optionsMethod',
width : 55
});
var cmAuthorizations = new Ext.grid.ColumnModel({
columns : [ {
header : i18n.get('headers.role'),
dataIndex : 'role',
width : 100
}, this.cbAll, this.cbGet, this.cbPost, this.cbPut, this.cbDelete, this.cbHead, this.cbOptions ],
defaults : {
sortable : true,
width : 100
}
});
var smAuthorizations = new Ext.grid.RowSelectionModel({
singleSelect : true
});
this.gridAuthorizations = new Ext.grid.EditorGridPanel({
id : 'gridAuthorizations',
height : 450,
store : storeAuthorizations,
tbar : {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.create'),
hidden : this.mode == 'select',
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this._onCreateRole
}, {
text : i18n.get('label.remove'),
hidden : this.mode == 'select',
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this._onDeleteRole
} ]
},
cm : cmAuthorizations,
sm : smAuthorizations,
plugins : [ this.cbAll, this.cbGet, this.cbPost, this.cbPut, this.cbDelete, this.cbHead, this.cbOptions ],
viewConfig : {
forceFit : true
}
});
this.items = [ this.gridAuthorizations ];
this.buttons = [ {
text : i18n.get('label.ok'),
scope : this,
handler : function () {
this._onValidate();
}
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ];
sitools.admin.applications.applicationsRolePanel.superclass.initComponent.call(this);
},
/**
* Adds a record to the role store.
*/
_onCreateRole : function () {
var winRole = new sitools.component.applications.rolesPanel({
storeRolesApplication : this.gridAuthorizations.getStore()
});
winRole.show();
},
/**
* Delete a record to the role store.
* @return {}
*/
_onDeleteRole : function () {
var recs = this.gridAuthorizations.getSelectionModel().getSelections();
if (recs.length === 0) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
this.gridAuthorizations.getStore().remove(recs);
},
/**
* Send a PUT request to the urlAuthorizations with all roles as defined.
*/
_onValidate : function () {
var putObject = {};
putObject.id = this.applicationRecord.data.id;
putObject.url = this.applicationRecord.data.url;
putObject.name = this.applicationRecord.data.name;
putObject.description = this.applicationRecord.data.description;
var store = this.findById('gridAuthorizations').getStore();
if (store.getCount() > 0) {
putObject.authorizations = [];
store.each(function (record) {
var item = {
role : record.data.role,
allMethod : record.data.allMethod,
postMethod : record.data.postMethod,
getMethod : record.data.getMethod,
putMethod : record.data.putMethod,
deleteMethod : record.data.deleteMethod,
headMethod : record.data.headMethod,
optionsMethod : record.data.optionsMethod
};
putObject.authorizations.push(item);
});
}
Ext.Ajax.request({
url : this.urlAuthorizations,
method : 'PUT',
scope : this,
jsonData : putObject,
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (!Json.success) {
Ext.Msg.alert(i18n.get('label.warning'), Json.message);
return;
}
this.close();
// this.store.reload();
},
failure : alertFailure
});
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, showResponse, alertFailure, loadUrl*/
Ext.namespace('sitools.component.applications');
/**
* A window to display roles and add any selected roles to a parameter store.
* @cfg {Ext.data.JsonStore} storeRolesApplication The store to add records.
* @class sitools.component.applications.rolesPanel
* @extends Ext.Window
*/
sitools.component.applications.rolesPanel = Ext.extend(Ext.Window, {
// url + mode + storeref
width : 350,
modal : true,
closable : false,
pageSize : 10,
/**
*
*/
initComponent : function () {
this.title = i18n.get('label.roleWin');
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
autoSave : false,
idProperty : 'id',
url : loadUrl.get('APP_URL') + loadUrl.get('APP_ROLES_URL'),
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
} ]
});
this.grid = new Ext.grid.GridPanel({
sm : new Ext.grid.RowSelectionModel(),
store : this.store,
height : 200,
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name'
}, {
header : i18n.get('label.description'),
dataIndex : 'description'
} ]
});
this.items = [ {
xtype : 'panel',
title : i18n.get('label.selectRoles'),
items : [ this.grid ],
bbar : {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ '->', {
text : i18n.get('label.ok'),
handler : this._onOK
}, {
text : i18n.get('label.cancel'),
handler : this._onCancel
} ]
}
} ];
// this.relayEvents(this.store, ['destroy', 'save', 'update']);
sitools.component.applications.rolesPanel.superclass.initComponent.call(this);
},
/**
* Loads the store
*/
onRender : function () {
sitools.component.applications.rolesPanel.superclass.onRender.apply(this, arguments);
this.store.load({
scope : this,
params : {
start : 0,
limit : this.pageSize
},
callback : function (r, options, success) {
if (!success) {
this.close();
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('label.loadError'));
}
}
});
},
/**
* Called when button ok is pressed.
* will add the selected roles in the storeRolesApplication.
*/
_onOK : function () {
Ext.each(this.grid.getSelectionModel().getSelections(), function (role) {
if (this.storeRolesApplication.find('role', role.data.name) == -1) {
this.storeRolesApplication.add(new Ext.data.Record({
role : role.data.name
}));
}
}, this);
this.close();
},
/**
* Called when button cancel is pressed.
*/
_onCancel : function () {
this.destroy();
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, showResponse, alertFailure*/
Ext.namespace('sitools.admin.applications');
/**
* A window to view application details;
* @class sitools.admin.applications.applicationsPropPanel
* @cfg {Ext.data.Record} applicationRecord the selected record
* @extends Ext.Window
*/
//sitools.component.applications.applicationsPropPanel = Ext.extend(Ext.Window, {
sitools.admin.applications.applicationsPropPanel = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
pageSize : 10,
dataSets : "",
initComponent : function () {
this.title = i18n.get('label.details');
this.items = [ {
xtype : 'panel',
height : 450,
items : [ {
xtype : 'form',
border : false,
padding : 10,
defaults : {
disabled : true
},
items : [ {
xtype : 'hidden',
name : 'id',
id : 'appFormIdId'
}, {
xtype : 'textfield',
name : 'name',
fieldLabel : i18n.get('label.name'),
anchor : '100%',
maxLength : 30,
id : 'appFormNameId'
}, {
xtype : 'textarea',
name : 'description',
fieldLabel : i18n.get('label.description'),
anchor : '100%',
id : 'appFormDescriptionId'
}, {
xtype : 'textfield',
name : 'urn',
fieldLabel : i18n.get('label.urn'),
anchor : '100%',
id : 'appFormUrnId'
}, {
xtype : 'textfield',
name : 'type',
fieldLabel : i18n.get('label.type'),
anchor : '100%',
id : 'appFormTypeId'
}, {
xtype : 'textfield',
name : 'url',
fieldLabel : i18n.get('label.url'),
anchor : '100%',
id : 'appFormUrlId'
}, {
xtype : 'textfield',
name : 'author',
fieldLabel : i18n.get('label.author'),
anchor : '100%',
id : 'appFormAuthotId'
}, {
xtype : 'textfield',
name : 'owner',
fieldLabel : i18n.get('label.owner'),
anchor : '100%',
id : 'appFormOwnerId'
}, {
xtype : 'textfield',
name : 'lastUpdate',
fieldLabel : i18n.get('label.lastUpdate'),
anchor : '100%',
id : 'appFormLastUpdateId'
}, {
xtype : 'textfield',
name : 'status',
fieldLabel : i18n.get('label.status'),
anchor : '100%',
id : 'appFormStatus'
} ]
} ],
buttons : [ {
text : i18n.get('label.close'),
scope : this,
handler : function () {
this.close();
}
} ]
} ];
sitools.admin.applications.applicationsPropPanel.superclass.initComponent.call(this);
},
/**
* Load the selected record in the main form.
*/
onRender : function () {
sitools.component.projects.ProjectsPropPanel.superclass.onRender.apply(this, arguments);
if (this.applicationRecord) {
var f = this.findByType('form')[0].getForm();
f.loadRecord(this.applicationRecord);
}
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, showResponse, alertFailure, loadUrl*/
Ext.namespace('sitools.admin.applications');
/**
* A Panel to display all sitools Applications.
* @class sitools.admin.applications.applicationsCrudPanel
* @extends Ext.grid.GridPanel
* @requires sitools.admin.applications.applicationsPropPanel
* @requires sitools.admin.applications.applicationsRolePanel
*/
sitools.admin.applications.applicationsCrudPanel = Ext.extend(Ext.grid.GridPanel, {
//sitools.component.applications.applicationsCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.GROUP,
sm : new Ext.grid.RowSelectionModel(),
pageSize : 10,
initComponent : function () {
this.url = loadUrl.get('APP_URL') + loadUrl.get('APP_APPLICATIONS_URL');
this.urlAuthorizations = loadUrl.get('APP_URL') + loadUrl.get('APP_AUTHORIZATIONS_URL');
var reader = new Ext.data.JsonReader({
root : 'data',
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'category',
type : 'string'
}, {
name : 'urn',
type : 'string'
}, {
name : 'type',
type : 'string'
}, {
name : 'url',
type : 'string'
}, {
name : 'author',
type : 'string'
}, {
name : 'owner',
type : 'string'
}, {
name : 'lastUpdate',
type : 'string'
}, {
name : 'status',
type : 'string'
}, {
name : 'wadl',
type : 'string',
convert : function (v, record) {
}
} ]
});
this.store = new Ext.data.GroupingStore({
reader : reader,
url : this.url,
restful : true,
remoteSort : false,
sortInfo : {field : 'name', direction : "ASC"},
groupField : 'category'
});
var expander = new Ext.ux.grid.RowExpander({
tpl : new Ext.XTemplate(
'<tpl if="this.descEmpty(description)" ><div></div></tpl>',
'<tpl if="this.descEmpty(description) == false" ><div class="sitoolsDescription"><div class="sitoolsDescriptionHeader">Description : </div><p class="sitoolsDescriptionText"> {description} </p></div></tpl>',
{
compiled : true,
descEmpty : function (description) {
return Ext.isEmpty(description);
}
}),
expandOnDblClick : true
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [expander, {
header : i18n.get('label.category'),
dataIndex : 'category',
width : 150,
hidden : true
}, {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 500
}, {
header : i18n.get('label.status'),
dataIndex : 'status',
width : 50,
sortable : false
}, {
header : "",
dataIndex : "url",
width : 20,
sortable : false,
renderer : function (value, metadata, record, rowIndex, colIndex, store) {
var applicationStatus = record.get("status");
if (Ext.isEmpty(applicationStatus) || "INACTIVE" == applicationStatus) {
return null;
} else {
return String.format("<a onClick='onClickOption(\"{0}\"); return false;' href=#>{1}</a>", value, String.format(
"<img alt={0} src='" + loadUrl.get('APP_URL') + "/common/res/images/icons/wadl.gif'>", i18n
.get('label.wadl')));
}
}
}]
});
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.details'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_details.png',
handler : this.onDetails,
xtype : 's-menuButton'
}, {
text : i18n.get('label.authorizations'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_autorizations.png',
handler : this.onDefineRole,
xtype : 's-menuButton'
}, {
text : i18n.get('label.active'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_active.png',
handler : this._onActive,
xtype : 's-menuButton'
}, {
text : i18n.get('label.disactive'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_disactive.png',
handler : this._onDisactive,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDelete,
xtype : 's-menuButton'
}, '->', {
xtype : 's-filter',
emptyText : i18n.get('label.search'),
store : this.store
} ]
};
this.view = new Ext.grid.GroupingView({
forceFit : true,
groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
});
this.plugins = expander;
sitools.admin.applications.applicationsCrudPanel.superclass.initComponent.call(this);
},
/**
* Basic on Render and load the applications store...
*/
onRender : function () {
sitools.admin.applications.applicationsCrudPanel.superclass.onRender.apply(this, arguments);
this.store.load();
},
/**
* Called when user click on Authorizations button
* Open a {sitools.admin.applications.applicationsRolePanel} window.
* @return {}
*/
onDefineRole : function () {
var rec = this.getSelectionModel().getSelected(), up = new sitools.admin.applications.applicationsRolePanel({
urlAuthorizations : this.urlAuthorizations + "/" + rec.data.id,
applicationRecord : rec
});
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
up.show(ID.BOX.APPLICATION);
},
/**
* Called when user click on Details button
* Open a {sitools.admin.applications.applicationsPropPanel} window.
* @return {}
*/
onDetails : function () {
var rec = this.getSelectionModel().getSelected(), up = new sitools.admin.applications.applicationsPropPanel({
applicationRecord : rec
});
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
up.show(ID.BOX.APPLICATION);
},
// /**
// * Called when user click on Details button
// * Open a {sitools.admin.applications.applicationsPropPanel} window.
// * @return {}
// */
// onModify : function () {
// var rec = this.getSelectionModel().getSelected(), up = new sitools.admin.applications.applicationsPropPanel({
// url : this.url + '/' + rec.id,
// action : 'modify',
// store : this.getStore()
// });
// if (!rec) {
// return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
// }
//
// up.show(ID.BOX.APPLICATION);
// },
/**
* Called when delete Button is pressed :
* Ask for confirmation and call doDelete
* @return {Boolean}
*/
onDelete : function () {
var rec = this.getSelectionModel().getSelected(), tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('applicationsCrud.delete'),
scope : this,
fn : function (btn, text) {
if (btn === 'yes') {
this.doDelete(rec);
}
}
});
if (!rec) {
return false;
}
},
/**
* Send a delete request to the server with the application url.
* @param {} rec
*/
doDelete : function (rec) {
// var rec = this.getSelectionModel().getSelected();
// if (!rec) return false;
Ext.Ajax.request({
url : this.url + "/" + rec.id,
method : 'DELETE',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
/**
* Call the resource start on the application
*/
_onActive : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.url + '/' + rec.id + '?action=start',
method : 'PUT',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
/**
* Call the resource stop on the application
*/
_onDisactive : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.url + '/' + rec.id + '?action=stop',
method : 'PUT',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
}
});
Ext.reg('s-applications', sitools.admin.applications.applicationsCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, showResponse, alertFailure, loadUrl*/
Ext.namespace('sitools.admin.authorizations');
/**
*
* @class sitools.admin.authorizations.authorizationsCrudPanel
* @extends Ext.grid.GridPanel
*/
//sitools.component.authorizations.authorizationsCrudPanel = Ext.extend(Ext.grid.GridPanel, {
sitools.admin.authorizations.authorizationsCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.GROUP,
sm : new Ext.grid.RowSelectionModel(),
pageSize : 10,
initComponent : function () {
this.url = loadUrl.get('APP_URL') + loadUrl.get('APP_AUTHORIZATIONS_URL');
this.urlAuthorizations = loadUrl.get('APP_URL') + loadUrl.get('APP_AUTHORIZATIONS_URL');
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
url : this.url,
remoteSort : true,
// sortField: 'name',
idProperty : 'id',
baseParams : {
type : "class"
},
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'url',
type : 'string'
}, {
name : 'authorizations'
} ]
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.id'),
dataIndex : 'id',
width : 100,
hidden : true
}, {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 150
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 450,
sortable : false
} ]
});
this.bbar = {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
};
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.authorizations'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_autorizations.png',
handler : this.onDefineRole,
xtype : 's-menuButton'
}, '->', {
xtype : 's-filter',
emptyText : i18n.get('label.search'),
store : this.store,
pageSize : this.pageSize
} ]
};
this.sm = new Ext.grid.RowSelectionModel();
this.view = new Ext.grid.GridView({
forceFit : true
});
this.listeners = {
scope : this,
rowDblClick : this.onDefineRole
};
sitools.admin.authorizations.authorizationsCrudPanel.superclass.initComponent.call(this);
},
onRender : function () {
sitools.admin.authorizations.authorizationsCrudPanel.superclass.onRender.apply(this, arguments);
this.store.load({
params : {
start : 0,
limit : this.pageSize
}
});
},
onDefineRole : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.admin.applications.applicationsRolePanel({
urlAuthorizations : this.urlAuthorizations + "/" + rec.data.id,
applicationRecord : rec
});
up.show(ID.BOX.APPLICATION);
},
onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return false;
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('applicationsCrud.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec);
}
}
});
},
doDelete : function (rec) {
Ext.Ajax.request({
url : this.url + "/" + rec.id,
method : 'DELETE',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
}
});
Ext.reg('s-authorizations', sitools.admin.authorizations.authorizationsCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.admin.userStorage');
/**
* A Panel to show the data from a specific user Storage
*
* @cfg {String} the action to perform
* @cfg {String} the url where get the resource
* @cfg {Ext.data.JsonStore} the store where get the record
* @class sitools.admin.userStorage.userStoragePropPanel
* @extends Ext.Window
*/
//sitools.component.userStorage.userStoragePropPanel = Ext.extend(Ext.Window, {
sitools.admin.userStorage.userStoragePropPanel = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
pageSize : 10,
dataSets : "",
initComponent : function () {
if (this.action == 'modify') {
this.title = i18n.get('label.modifyUserStorage') + " : " + this.userStorageRec.data.userId;
}
if (this.action == 'create') {
this.title = i18n.get('label.createUserStorage');
}
this.items = [ {
xtype : 'panel',
height : 450,
items : [ {
xtype : 'panel',
height : 400,
items : [ {
xtype : 'form',
border : false,
padding : 10,
defaults : [ {
readOnly : true
} ],
items : [ {
xtype : 'hidden',
name : 'userId',
id : 'userValueFieldId'
}, {
xtype : 'textfield',
name : 'displayUser',
fieldLabel : i18n.get('label.user'),
anchor : '100%',
maxLength : 100,
allowBlank : false,
blankText : 'The user field cannot be empty',
listeners : {
scope : this,
focus : function (field) {
if (this.action == 'create') {
/**
* Create a {sitools.admin.usergroups.UsersPanel} to select an existing user
*/
var usersWin = new sitools.admin.usergroups.UsersPanel({
mode : 'selectUnique',
url : loadUrl.get('APP_URL') + loadUrl.get('APP_SECURITY_URL') + '/users',
displayField : field,
valueField : this.findByType('form')[0].getForm().findField('userValueFieldId')
});
usersWin.show();
}
}
}
}, {
xtype : 'compositefield',
fieldLabel : i18n.get('label.quota'),
anchor : '100%',
defaults : {
flex : 1
},
items : [ {
xtype : 'textfield',
name : 'quota',
fieldLabel : i18n.get('label.quota'),
anchor : '75%'
}, {
xtype : 'label',
text : i18n.get('label.quota.unit'),
width : 50,
flex : 0
} ]
}, {
xtype : 'textfield',
name : 'userStoragePath',
fieldLabel : i18n.get('label.userStoragePath'),
anchor : '100%',
maxLength : 100,
readOnly : true,
disabled : true
}, {
xtype : 'numberfield',
name : 'freeUserSpace',
fieldLabel : i18n.get('label.freeUserSpace'),
anchor : '100%',
maxLength : 100,
readOnly : true,
disabled : true
}, {
xtype : 'numberfield',
name : 'busyUserSpace',
fieldLabel : i18n.get('label.busyUserSpace'),
anchor : '100%',
maxLength : 100,
readOnly : true,
disabled : true
}, {
xtype : 'textfield',
name : 'status',
fieldLabel : i18n.get('label.status'),
anchor : '100%',
maxLength : 30,
readOnly : true,
disabled : true
} ]
} ]
} ],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ]
} ];
sitools.admin.userStorage.userStoragePropPanel.superclass.initComponent.call(this);
},
/**
* Save {sitools.admin.userStorage.userStoragePropPanel} user Storage in function of the action (create,modify)
*/
onValidate : function () {
var f = this.findByType('form')[0].getForm();
if (!f.isValid()) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.invalidForm'));
return;
}
var putObject = {};
putObject.userId = f.findField('userValueFieldId').getValue();
putObject.storage = {};
putObject.storage.quota = f.findField('quota').getValue();
if (this.action == 'modify') {
Ext.Ajax.request({
url : this.url,
method : 'PUT',
scope : this,
jsonData : putObject,
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (data.success === false) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get(data.message));
} else {
this.close();
this.store.reload();
}
},
failure : alertFailure
});
}
if (this.action == 'create') {
Ext.Ajax.request({
url : this.url,
method : 'POST',
scope : this,
jsonData : putObject,
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (data.success === false) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get(data.message));
} else {
this.close();
this.store.reload();
}
// Ext.Msg.alert(i18n.get('label.information'),
// i18n.get('msg.uservalidate'));
},
failure : alertFailure
});
}
},
/**
* Delete the user field if the action is modify
*/
afterRender : function () {
sitools.admin.userStorage.userStoragePropPanel.superclass.afterRender.apply(this, arguments);
if (this.action == 'modify') {
var f = this.findByType('form')[0].getForm();
f.loadRecord(this.userStorageRec);
f.findField("displayUser").destroy();
}
}
});
Ext.reg('s-userStoragesprop', sitools.admin.userStorage.userStoragePropPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.admin.userStorage');
/**
* A Panel to show all the user Storage in Sitools2
*
* @cfg {String} the url where get the resource
* @cfg {Ext.data.JsonStore} the store where saved the user storage data
* @class sitools.admin.userStorage.userStorageCrudPanel
* @extends Ext.grid.GridPanel
*/
//sitools.component.userStorage.userStorageCrudPanel = Ext.extend(Ext.grid.GridPanel, {
sitools.admin.userStorage.userStorageCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.GROUP,
sm : new Ext.grid.RowSelectionModel(),
pageSize : 10,
// loadMask: true,
initComponent : function () {
this.url = loadUrl.get('APP_URL') + loadUrl.get('APP_USERSTORAGE_URL') + '/users';
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
url : this.url,
remoteSort : true,
idProperty : 'userId',
fields : [ {
name : 'userId',
type : 'string'
}, {
name : 'status',
type : 'string',
mapping : 'status'
}, {
name : 'freeUserSpace',
type : 'float',
mapping : 'storage.freeUserSpace'
}, {
name : 'busyUserSpace',
type : 'float',
mapping : 'storage.busyUserSpace'
}, {
name : 'quota',
type : 'float',
mapping : 'storage.quota'
}, {
name : 'userStoragePath',
type : 'string',
mapping : 'storage.userStoragePath'
} ]
});
/**
* {Ext.grid.ColumnModel} the columns definition for the store
*/
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.userLogin'),
dataIndex : 'userId',
width : 100
}, {
header : i18n.get('label.userStoragePath'),
dataIndex : 'userStoragePath',
width : 160
}, {
header : i18n.get('label.freeUserSpace'),
dataIndex : 'freeUserSpace',
width : 80,
renderer : function (value) {
return Ext.util.Format.fileSize(value);
}
}, {
header : i18n.get('label.busyUserSpace'),
dataIndex : 'busyUserSpace',
width : 80,
renderer : function (value) {
return Ext.util.Format.fileSize(value);
}
}, {
header : i18n.get('label.quota'),
dataIndex : 'quota',
width : 80,
renderer : function (value) {
return Ext.util.Format.fileSize(value);
}
}, {
header : i18n.get('label.usedPourcentage'),
width : 80,
renderer : function (value, metaData, record, rowIndex, colIndex, store) {
var totalSpace = record.get("quota");
var usedSpace = record.get("busyUserSpace");
var pourcentage = usedSpace / totalSpace * 100;
if (pourcentage >= 90 && pourcentage < 100) {
metaData.css = "sitools-userProfile-warning-text";
}
else if (pourcentage > 100) {
metaData.css = "sitools-userProfile-error-text";
}
return pourcentage + "%";
}
}, {
header : i18n.get('label.status'),
dataIndex : 'status',
width : 100
} ]
});
this.bbar = {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
};
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreate,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this.onModify,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDelete,
xtype : 's-menuButton'
}, {
text : i18n.get('label.active'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_active.png',
handler : this._onActive,
xtype : 's-menuButton'
}, {
text : i18n.get('label.disactive'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_disactive.png',
handler : this._onDisactive,
xtype : 's-menuButton'
}, {
text : i18n.get('label.clean'),
icon : 'res/images/icons/icons_perso/toolbar_clean.png',
handler : this._onClean,
xtype : 's-menuButton'
}, {
text : i18n.get('label.refresh'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_refresh.png',
handler : this._onRefresh,
xtype : 's-menuButton'
}, {
text : i18n.get('label.notify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/notify.png',
handler : this._onNotify,
xtype : 's-menuButton'
} ]
};
this.view = new Ext.grid.GridView({
forceFit : true
});
this.listeners = {
scope : this,
rowDblClick : this.onModify
};
sitools.admin.userStorage.userStorageCrudPanel.superclass.initComponent.call(this);
},
/**
* do a specific render to load informations from the store.
*/
onRender : function () {
sitools.admin.userStorage.userStorageCrudPanel.superclass.onRender.apply(this, arguments);
this.store.load({
params : {
start : 0,
limit : this.pageSize
}
});
},
/**
* Create a {sitools.admin.userStorage.userStoragePropPanel} user Storage to add to the storage
*/
onCreate : function () {
var up = new sitools.admin.userStorage.userStoragePropPanel({
url : this.url,
action : 'create',
store : this.getStore()
});
up.show(ID.BOX.PROJECTS);
},
/**
* Modify the selected {sitools.admin.userStorage.userStoragePropPanel} user Storage
*/
onModify : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.admin.userStorage.userStoragePropPanel({
url : this.url + '/' + rec.id,
userStorageRec : rec,
action : 'modify',
store : this.getStore()
});
up.show(ID.BOX.USERSTORAGE);
},
/**
* Diplay confirm delete Msg box and call the method doDelete
*/
onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return false;
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('userStorageCrud.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec);
}
}
});
},
/**
* done the delete of the passed record
* @param rec the record to delete
*/
doDelete : function (rec) {
Ext.Ajax.request({
url : this.url + "/" + rec.id,
method : 'DELETE',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
/**
* Activate the selected {sitools.admin.userStorage.userStoragePropPanel} user Storage
*/
_onActive : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.url + '/' + rec.id + '/start',
method : 'PUT',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
/**
* Deactivate the selected {sitools.admin.userStorage.userStoragePropPanel} user Storage
*/
_onDisactive : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.url + '/' + rec.id + '/stop',
method : 'PUT',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
/**
* Delete all files from the selected {sitools.admin.userStorage.userStoragePropPanel} user Storage
*/
_onClean : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('userStorageCrud.clean'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doClean(rec);
}
}
});
},
doClean : function (rec) {
// var rec = this.getSelectionModel().getSelected();
// if (!rec) return false;
Ext.Ajax.request({
url : this.url + '/' + rec.id + '/clean',
method : 'PUT',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
/**
* Refresh the selected {sitools.admin.userStorage.userStoragePropPanel} user Storage
*/
_onRefresh : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.url + '/' + rec.id + '/refresh',
method : 'PUT',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
/**
* Notify the selected {sitools.admin.userStorage.userStoragePropPanel} user Storage by e-mail
*/
_onNotify : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.url + '/' + rec.id + '/notify',
method : 'PUT',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
}
});
Ext.reg('s-userStorage', sitools.admin.userStorage.userStorageCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp*/
Ext.namespace('sitools.component.order');
sitools.component.order.orderPropPanel = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
pageSize : 10,
dataSets : "",
layout : 'fit',
initComponent : function () {
this.title = i18n.get('label.details') + " : ";
this.title += this.orderRec.data.userId;
this.title += " " + i18n.get('label.the');
this.title += " " + this.orderRec.data.dateOrder;
var eventsStore = new Ext.data.JsonStore({
fields : [ {
name : 'eventDate',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'message',
type : 'string'
} ],
data : this.orderRec.data.events
});
var eventsCm = new Ext.grid.ColumnModel({
columns : [ {
header : i18n.get("headers.date"),
dataIndex : 'eventDate',
width : 150
},
// {header : i18n.get("headers.order"), dataIndex: 'order', width :
// 100},
{
header : i18n.get("headers.description"),
dataIndex : 'description',
width : 250
}, {
header : i18n.get("headers.message"),
dataIndex : 'message',
width : 150
} ]
});
var eventsGrid = new Ext.grid.GridPanel({
layout : 'fit',
flex : 0.5,
title : i18n.get('label.events'),
store : eventsStore,
cm : eventsCm,
rowSelectionModel : new Ext.grid.RowSelectionModel(),
autoScroll : true,
collapsible : false
});
var resourceCollectionStore = new Ext.data.JsonStore({
fields : [ {
name : 'resourceCollection',
type : 'string'
} ]
});
if (!Ext.isEmpty(this.orderRec.data.resourceCollection)) {
Ext.each(this.orderRec.data.resourceCollection, function (resource) {
var rec = new resourceCollectionStore.recordType({
resourceCollection : resource
});
resourceCollectionStore.add(rec);
});
}
if (!Ext.isEmpty(this.orderRec.data.adminResourceCollection)) {
Ext.each(this.orderRec.data.adminResourceCollection, function (resource) {
var rec = new resourceCollectionStore.recordType({
resourceCollection : resource
});
resourceCollectionStore.add(rec);
});
}
var resourceCollectionCm = new Ext.grid.ColumnModel({
columns : [ {
header : i18n.get("headers.resource"),
dataIndex : 'resourceCollection',
width : 600
} ]
});
var resourceCollectionGrid = new Ext.grid.GridPanel({
layout : 'fit',
flex : 0.5,
title : i18n.get('label.resourceCollection'),
store : resourceCollectionStore,
cm : resourceCollectionCm,
rowSelectionModel : new Ext.grid.RowSelectionModel(),
autoScroll : true,
collapsible : false
});
this.items = [ {
xtype : 'panel',
layout : 'fit',
items : [ {
xtype : 'panel',
layout : 'vbox',
layoutConfig : {
align : 'stretch',
flex : 'ratio'
},
items : [ {
xtype : 'form',
border : false,
padding : 10,
items : [ {
xtype : 'hidden',
name : 'orderId',
id : 'userValueFieldId'
}, {
xtype : 'textfield',
name : 'userId',
fieldLabel : i18n.get('label.userLogin'),
anchor : '100%',
maxLength : 100,
readOnly : true
}, {
xtype : 'textfield',
name : 'description',
fieldLabel : i18n.get('label.description'),
anchor : '100%',
maxLength : 100,
readOnly : true
}, {
xtype : 'textfield',
name : 'resourceDescriptor',
fieldLabel : i18n.get('label.url'),
anchor : '100%',
maxLength : 30,
readOnly : true
}, {
xtype : 'textfield',
name : 'dateOrder',
fieldLabel : i18n.get('label.dateOrder'),
anchor : '100%',
maxLength : 100,
readOnly : true
} ]
}, resourceCollectionGrid, eventsGrid ]
} ],
buttons : [ {
text : i18n.get('label.close'),
scope : this,
handler : function () {
this.close();
}
} ]
} ];
sitools.component.order.orderPropPanel.superclass.initComponent.call(this);
},
onRender : function () {
sitools.component.order.orderPropPanel.superclass.onRender.apply(this, arguments);
var f = this.findByType('form')[0].getForm();
f.loadRecord(this.orderRec);
}
});
Ext.reg('s-orderprop', sitools.component.order.orderPropPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.component.order');
sitools.component.order.orderCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.GROUP,
sm : new Ext.grid.RowSelectionModel(),
pageSize : 10,
// loadMask: true,
initComponent : function () {
this.url = loadUrl.get('APP_URL') + loadUrl.get('APP_ORDERS_ADMIN_URL');
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
url : this.url,
remoteSort : true,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'userId',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'resourceCollection'
}, {
name : 'resourceDescriptor',
type : 'string'
}, {
name : 'status',
type : 'string'
}, {
name : 'dateOrder',
type : 'string'
}, {
name : 'events'
}, {
name : 'adminResourceCollection'
}]
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.userLogin'),
dataIndex : 'userId',
width : 100
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 350
}, {
header : i18n.get('label.status'),
dataIndex : 'status',
width : 80
}, {
header : i18n.get('label.dateOrder'),
dataIndex : 'dateOrder',
width : 150
} ]
});
this.bbar = {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
};
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.details'),
// icon: 'res/images/icons/toolbar_project_add.png',
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_details.png',
handler : this._onDetail,
xtype : 's-menuButton'
}, {
text : i18n.get('label.active'),
// icon: 'res/images/icons/toolbar_project_add.png',
icon : 'res/images/icons/icons_perso/toolbar_beginning.png',
handler : this._onActive,
xtype : 's-menuButton'
}, {
text : i18n.get('label.done'),
// icon: 'res/images/icons/toolbar_project_edit.png',
icon : 'res/images/icons/icons_perso/toolbar_end.png',
handler : this._onDone,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
// icon: 'res/images/icons/toolbar_project_edit.png',
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDelete,
xtype : 's-menuButton'
}, '->', {
xtype : 's-filter',
emptyText : i18n.get('label.search'),
store : this.store,
pageSize : this.pageSize
} ]
};
this.view = new Ext.grid.GridView({
forceFit : true
});
this.listeners = {
scope : this,
rowDblClick : this._onDetail
};
sitools.component.order.orderCrudPanel.superclass.initComponent.call(this);
},
onRender : function () {
sitools.component.order.orderCrudPanel.superclass.onRender.apply(this, arguments);
this.store.load({
params : {
start : 0,
limit : this.pageSize
}
});
},
_onDetail : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.component.order.orderPropPanel({
url : this.url,
action : 'detail',
store : this.getStore(),
orderRec : rec
});
up.show(ID.BOX.ORDER);
},
_onActive : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.component.order.events({
baseUrl : this.url + "/" + rec.data.id,
action : 'active',
store : this.getStore(),
orderRec : rec
});
up.show();
},
_onDone : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.component.order.events({
baseUrl : this.url + "/" + rec.data.id,
action : 'done',
store : this.getStore(),
orderRec : rec
});
up.show();
},
onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return false;
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('orderCrud.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec);
}
}
});
},
doDelete : function (rec) {
// var rec = this.getSelectionModel().getSelected();
// if (!rec) return false;
Ext.Ajax.request({
url : this.url + "/" + rec.id,
method : 'DELETE',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
}
});
Ext.reg('s-order', sitools.component.order.orderCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp*/
Ext.namespace('sitools.component.order');
sitools.component.order.events = Ext.extend(Ext.Window, {
width : 350,
height : 230,
modal : true,
closable : true,
baseUrl : this.baseUrl,
initComponent : function () {
this.title = i18n.get('label.orders');
this.items = [ {
xtype : 'panel',
height : 200,
items : [ {
xtype : 'form',
border : false,
padding : 10,
items : [ {
xtype : 'textarea',
name : 'description',
fieldLabel : i18n.get('label.description'),
anchor : '100%',
maxLength : 100
}, {
xtype : 'textarea',
name : 'message',
fieldLabel : i18n.get('label.message'),
anchor : '100%',
maxLength : 100
} ]
} ],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this._onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ]
} ];
sitools.component.order.events.superclass.initComponent.call(this);
},
_onValidate : function () {
var url = this.baseUrl + "/" + this.action;
var f = this.findByType('form')[0].getForm();
if (!f.isValid()) {
Ext.Msg.alert(i18n.get('warning.invalidForm'));
return;
}
var putObject = {};
Ext.iterate(f.getValues(), function (key, value) {
putObject[key] = value;
}, this);
Ext.Ajax.request({
url : url,
method : 'PUT',
scope : this,
jsonData : putObject,
success : function (ret) {
this.store.reload();
this.close();
},
failure : alertFailure
});
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.component.graphs');
sitools.component.graphs.graphsCrudPanel = Ext.extend(Ext.Panel, {
border : false,
height : 300,
id : ID.BOX.GRAPHS,
autoScroll: true,
// loadMask: true,
initComponent : function () {
this.urlProjects = loadUrl.get('APP_URL') + loadUrl.get('APP_PROJECTS_URL');
this.storeProjects = new Ext.data.JsonStore({
fields : [ 'id', 'name' ],
url : this.urlProjects,
root : "data",
autoLoad : true
});
this.comboProjects = new Ext.form.ComboBox({
store : this.storeProjects,
displayField : 'name',
valueField : 'id',
typeAhead : true,
mode : 'local',
forceSelection : true,
triggerAction : 'all',
emptyText : i18n.get('label.selectProject'),
selectOnFocus : true,
listeners : {
scope : this,
select : function (combo, rec, index) {
this.loadGraph(rec.data.id);
}
}
});
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ this.comboProjects, {
text : i18n.get('label.save'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/save.png',
handler : this._onSave,
xtype : 's-menuButton'
}, {
text : i18n.get('label.reset'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_refresh.png',
handler : this._onReset,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this._onDelete,
xtype : 's-menuButton'
} ]
};
this.buttons = [ {
text : i18n.get('label.save'),
scope : this,
handler : this._onSave
}, {
text : i18n.get('label.reset'),
scope : this,
handler : this._onReset
}, {
text : i18n.get('label.delete'),
scope : this,
handler : this._onDelete
} ];
sitools.component.graphs.graphsCrudPanel.superclass.initComponent.call(this);
},
loadGraph : function (projectId) {
var index = this.storeProjects.find("id", projectId);
var rec = this.storeProjects.getAt(index);
var projectName = rec.data.name;
this.removeAll();
this.tree = new sitools.component.graphs.graphsCrudTreePanel({
name : projectName,
projectId : projectId
});
this.tree.getRootNode().expand(true);
this.add(this.tree);
this.doLayout();
},
_onSave : function () {
var projectId = this.comboProjects.getValue();
if (!Ext.isEmpty(projectId)) {
var root = this.tree.getRootNode();
var tree = [];
var childs = root.childNodes;
var i;
for (i = 0; i < childs.length; i++) {
this.getAllNodes(childs[i], tree);
}
var idGraph = this.tree.getIdGraph();
var jsonReturn = {
nodeList : tree,
id : idGraph
};
// var tree = this.getAllNodes(root,array);
var method = (!Ext.isEmpty(idGraph)) ? "PUT" : "POST";
Ext.Ajax.request({
url : this.urlProjects + "/" + projectId + "/graph",
method : method,
scope : this,
jsonData : jsonReturn,
success : function (ret) {
// check for the success of the request
var data = Ext.decode(ret.responseText);
if (!data.success) {
Ext.Msg.alert(i18n.get('label.warning'), data.message);
return false;
} else {
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('label.graphSaved'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
this.loadGraph(projectId);
}
},
failure : alertFailure
});
} else {
Ext.Msg.alert(i18n.get("label.warning"), i18n.get("warning.noselection"));
}
},
getAllNodes : function (root, parent) {
var node = {};
if (Ext.isEmpty(root)) {
return;
} else if (root.isLeaf()) {
node = {
text : root.text,
datasetId : root.attributes.datasetId,
visible : root.attributes.visible,
status : root.attributes.status,
nbRecord : root.attributes.nbRecord,
imageDs : root.attributes.imageDs,
readme : root.attributes.readme,
url : root.attributes.url,
leaf : true,
type : root.attributes.type
};
parent.push(node);
} else {
node = {
text : root.text,
image : root.attributes.image,
description : root.attributes.description,
children : [],
type : root.attributes.type,
leaf : false
};
parent.push(node);
// we call recursively getAllNodes to get all childNodes
var childs = root.childNodes;
var i;
for (i = 0; i < childs.length; i++) {
this.getAllNodes(childs[i], node.children);
}
}
},
_onReset : function () {
var projectId = this.comboProjects.getValue();
if (!Ext.isEmpty(projectId)) {
var tot = Ext.Msg.show({
title : i18n.get('label.warning'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('label.graphs.reset'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doReset();
}
}
});
} else {
Ext.Msg.alert(i18n.get("label.warning"), i18n.get("warning.noselection"));
}
},
doReset : function () {
if (!Ext.isEmpty(this.tree)) {
var root = this.tree.getRootNode();
root.removeAll(true);
this.tree.getLoader().load(root, function () {
root.expand(true);
}, this);
}
},
_onDelete : function () {
var projectId = this.comboProjects.getValue();
if (!Ext.isEmpty(projectId)) {
var tot = Ext.Msg.show({
title : i18n.get('label.warning'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('label.graphs.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(projectId);
}
}
});
} else {
Ext.Msg.alert(i18n.get("label.warning"), i18n.get("warning.noselection"));
}
},
doDelete : function (projectId) {
Ext.Ajax.request({
url : this.urlProjects + "/" + projectId + "/graph",
method : "DELETE",
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.loadGraph(projectId);
}
}
});
}
});
sitools.component.graphs.graphsCrudTreePanel = Ext.extend(Ext.tree.TreePanel, {
idGraph : null,
loader : null,
projectId : null,
constructor : function (config) {
this.loader = new sitools.component.graphs.graphTreeLoader({
requestMethod : 'GET',
url : loadUrl.get('APP_URL') + loadUrl.get('APP_PROJECTS_URL') + "/" + config.projectId + "/graph",
root : 'graph.nodeList'
});
/*
* this.root = { text : config.name, children : [], nodeType:'async' };
*/
this.projectId = config.projectId;
config = Ext.apply({
rootVisible : true,
loader : this.loader,
layout : 'fit',
enableDD: true,
root : {
nodeType : 'async',
text : config.name
},
contextMenuRoot : new Ext.menu.Menu({
items : [ {
id : 'create-node',
text : i18n.get("label.createNode"),
icon : loadUrl.get('APP_URL') + '/res/images/icons/add_folder.png'
}, {
id : 'add-dataset',
text : i18n.get("label.addDataset"),
icon : loadUrl.get('APP_URL') + '/res/images/icons/add_datasets.png'
} ],
listeners : {
scope : this,
itemclick : this._cxtMenuHandler
}
}),
contextMenuNode : new Ext.menu.Menu({
items : [ {
id : 'create-node',
text : i18n.get("label.createNode"),
icon : loadUrl.get('APP_URL') + '/res/images/icons/add_folder.png'
}, {
id : 'add-dataset',
text : i18n.get("label.addDataset"),
icon : loadUrl.get('APP_URL') + '/res/images/icons/add_datasets.png'
}, {
id : 'edit-node',
text : i18n.get("label.modify"),
icon : loadUrl.get('APP_URL') + '/res/images/icons/toolbar_edit.png'
}, {
id : 'delete-node',
text : i18n.get("label.delete"),
icon : loadUrl.get('APP_URL') + '/res/images/icons/toolbar_delete.png'
} ],
listeners : {
scope : this,
itemclick : this._cxtMenuHandler
}
}),
contextMenuLeaf : new Ext.menu.Menu({
items : [ {
id : 'edit-node',
text : i18n.get("label.modify"),
icon : loadUrl.get('APP_URL') + '/res/images/icons/toolbar_edit.png'
}, {
id : 'delete-node',
text : i18n.get("label.delete"),
icon : loadUrl.get('APP_URL') + '/res/images/icons/toolbar_delete.png'
} ],
listeners : {
scope : this,
itemclick : this._cxtMenuHandler
}
}),
listeners : {
scope : this,
contextmenu : function (node, e) {
// Register the context node with the menu so that a Menu
// Item's handler function can access
// it via its parentMenu property.
node.select();
var c;
if (node.id == this.root.id) {
c = node.getOwnerTree().contextMenuRoot;
} else {
if (node.isLeaf()) {
c = node.getOwnerTree().contextMenuLeaf;
} else {
c = node.getOwnerTree().contextMenuNode;
}
}
c.contextNode = node;
c.showAt(e.getXY());
}
}
});
sitools.component.graphs.graphsCrudTreePanel.superclass.constructor.call(this, config);
},
onRender : function () {
sitools.component.graphs.graphsCrudTreePanel.superclass.onRender.apply(this, arguments);
},
_cxtMenuHandler : function (item) {
var node, up;
switch (item.id) {
case 'delete-node':
var tot = Ext.Msg.show({
title : i18n.get('label.warning'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('label.graphs.node.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
var n = item.parentMenu.contextNode;
if (n.parentNode) {
n.remove();
}
}
}
});
break;
case 'add-dataset':
node = item.parentMenu.contextNode;
// this.doLayout();
up = new sitools.component.graphs.graphsDatasetWin({
node : node,
url : loadUrl.get('APP_URL') + '/projects/' + this.projectId + '?media=json',
mode : 'create'
});
up.show(this);
break;
case 'create-node':
node = item.parentMenu.contextNode;
// this.doLayout();
up = new sitools.component.graphs.graphsNodeWin({
node : node,
mode : 'create'
});
up.show(this);
break;
case 'edit-node':
node = item.parentMenu.contextNode;
if (node.isLeaf()) {
up = new sitools.component.graphs.graphsDatasetWin({
node : node,
url : loadUrl.get('APP_URL') + '/projects/' + this.projectId + '?media=json',
mode : 'edit'
});
} else {
up = new sitools.component.graphs.graphsNodeWin({
node : node,
mode : 'edit'
});
}
up.show(this);
break;
}
},
getIdGraph : function () {
return this.loader.getIdGraph();
}
});
/**
* Custom TreeLoader to deal with JSON returned from the server
*/
sitools.component.graphs.graphTreeLoader = Ext.extend(Ext.tree.TreeLoader, {
idGraph : null,
createNode : function (attr) {
return Ext.tree.TreeLoader.prototype.createNode.call(this, attr);
},
processResponse : function (response, node, callback, scope) {
var json = response.responseText, children, newNode, i = 0, len;
try {
if (!(children = response.responseData)) {
children = Ext.decode(json);
this.idGraph = children.graph.id;
if (this.root) {
if (!this.getRoot) {
this.getRoot = Ext.data.JsonReader.prototype.createAccessor(this.root);
}
children = this.getRoot(children);
}
}
node.beginUpdate();
for (len = children.length; i < len; i++) {
newNode = this.createNode(children[i]);
if (newNode) {
node.appendChild(newNode);
}
}
node.endUpdate();
this.runCallback(callback, scope || node, [ node ]);
} catch (e) {
this.handleFailure(response);
}
},
getIdGraph : function () {
return this.idGraph;
}
});
Ext.reg('s-graphs', sitools.component.graphs.graphsCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp*/
Ext.namespace('sitools.component.graphs');
sitools.component.graphs.graphsDatasetWin = Ext.extend(Ext.Window, {
// url + mode + storeref
width : 350,
modal : true,
closable : false,
pageSize : 10,
initComponent : function () {
this.title = i18n.get('label.datasets');
var projectId = this.projectId;
this.store = new Ext.data.JsonStore({
root : 'project.dataSets',
restful : true,
autoSave : false,
idProperty : 'id',
url : this.url,
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'type',
type : 'string'
}, {
name : 'mediaType',
type : 'string'
}, {
name : 'visible',
type : 'boolean'
}, {
name : 'status',
type : 'string'
}, {
name : 'url',
type : 'string'
}, {
name : 'properties'
} ]
});
this.grid = new Ext.grid.GridPanel({
sm : new Ext.grid.RowSelectionModel({
singleSelect : true
}),
store : this.store,
height : 200,
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name'
}, {
header : i18n.get('label.description'),
dataIndex : 'description'
} ],
listeners : {
scope : this,
viewReady : function () {
var node = this.node;
if (this.mode == 'edit') {
var index = this.store.find('name', node.text);
var sm = this.grid.getSelectionModel();
sm.selectRow(index);
}
}
}
});
this.items = [ {
xtype : 'panel',
title : i18n.get('label.selectDataset'),
items : [ this.grid ],
bbar : {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ '->', {
text : i18n.get('label.ok'),
handler : this._onOK
}, {
text : i18n.get('label.cancel'),
handler : this._onCancel
} ]
}
} ];
// this.relayEvents(this.store, ['destroy', 'save', 'update']);
sitools.component.graphs.graphsDatasetWin.superclass.initComponent.call(this);
},
onRender : function () {
sitools.component.graphs.graphsDatasetWin.superclass.onRender.apply(this, arguments);
this.store.load({
scope : this,
params : {
start : 0,
limit : this.pageSize
},
callback : function (r, options, success) {
if (!success) {
this.close();
Ext.Msg.alert(i18n.get('label.error'), i18n.get('label.error.project.nodataset'));
}
}
});
},
_onOK : function () {
var dataset = this.grid.getSelectionModel().getSelected();
if (this.mode == 'edit') {
this.node.setText(dataset.data.name);
} else {
var properties = dataset.data.properties;
var nbRecord = 0;
var imageDs;
var descriptionHTML;
if (!Ext.isEmpty(properties)) {
Ext.each(properties, function (property) {
if (property.name == "nbRecord") {
nbRecord = property.value;
}
if (property.name == "imageUrl") {
imageDs = property.value;
}
if (property.name == "descriptionHTML") {
descriptionHTML = property.value;
}
});
}
var newNode = {
text : dataset.data.name,
datasetId : dataset.data.id,
visible : dataset.data.visible,
status : dataset.data.status,
nbRecord : nbRecord,
leaf : true,
type : "dataset",
imageDs : imageDs,
readme : descriptionHTML,
url : dataset.data.url
};
if (!this.node.isExpanded()) {
this.node.expand();
}
this.node.appendChild(newNode);
}
this.close();
},
_onCancel : function () {
this.destroy();
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp*/
Ext.namespace('sitools.component.projects');
sitools.component.graphs.graphsNodeWin = Ext.extend(Ext.Window, {
// url + mode + storeref
width : 350,
modal : true,
closable : false,
initComponent : function () {
this.title = i18n.get('label.nodeDescription');
/* paramétres du formulaire */
this.itemsForm = [ {
fieldLabel : i18n.get('label.name'),
name : 'name',
anchor : '100%',
allowBlank : false
}, {
fieldLabel : i18n.get('label.description'),
name : 'description',
anchor : '100%'
}, {
xtype : 'sitoolsSelectImage',
name : 'image',
fieldLabel : i18n.get('label.image'),
anchor : '100%',
growMax : 400
} ];
this.bbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ '->', {
text : i18n.get('label.ok'),
handler : this._onOK
}, {
text : i18n.get('label.cancel'),
handler : this._onCancel
} ]
};
this.formPanel = new Ext.FormPanel({
labelWidth : 100, // label settings here cascade unless overridden
frame : true,
defaultType : 'textfield',
items : this.itemsForm
});
this.items = [ this.formPanel ];
// this.relayEvents(this.store, ['destroy', 'save', 'update']);
sitools.component.graphs.graphsNodeWin.superclass.initComponent.call(this);
},
onRender : function () {
sitools.component.graphs.graphsNodeWin.superclass.onRender.apply(this, arguments);
},
afterRender : function () {
sitools.component.graphs.graphsNodeWin.superclass.afterRender.apply(this, arguments);
if (this.mode == 'edit') {
var node = this.node;
var form = this.formPanel.getForm();
var rec = {};
rec.name = node.text;
rec.image = node.attributes.image.url;
rec.description = node.attributes.description;
var record = new Ext.data.Record(rec);
form.loadRecord(record);
}
},
_onOK : function () {
var form = this.formPanel.getForm();
var values = form.getValues();
var image = {};
if (!Ext.isEmpty(values.image)) {
image.url = values.image;
image.type = "Image";
image.mediaType = "Image";
}
if (this.mode == 'edit') {
this.node.setText(values.name);
this.node.attributes.description = values.description;
this.node.attributes.image = image;
} else {
var newNode = {
text : values.name,
image : image,
description : values.description,
type : "node",
children : []
};
if (!this.node.isExpanded()) {
this.node.expand();
}
this.node.appendChild(newNode);
}
this.close();
},
_onCancel : function () {
this.destroy();
},
_onUpload : function () {
Ext.msg.alert("Information", "TODO");
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp*/
Ext.namespace('sitools.admin.datasets');
/**
* A window that displays the columns of a dataset.
* @cfg string field The attribute of the record to edit
* @cfg Ext.data.Record storeRecord the record to edit
* @cfg Ext.data.Store parentStore the store of the record
* @cfg Ext.grid.GridView parentView the view of the grid
* @cfg string url the url to request dataset
* @class sitools.admin.datasets.selectColumn
* @extends Ext.Window
*/
sitools.admin.datasets.selectColumn = Ext.extend(Ext.Window, {
//sitools.component.datasets.selectColumn = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
pageSize : 10,
initComponent : function () {
this.title = i18n.get('title.selectColumn');
this.cmSelectColumn = new Ext.grid.ColumnModel({
columns : [ {
id : 'name',
header : i18n.get('headers.name'),
sortable : true,
dataIndex : 'columnAlias'
} ]
});
this.smSelectColumn = new Ext.grid.RowSelectionModel({
singleSelect : true
});
this.gridSelectColumn = new Ext.grid.GridPanel({
height : 380,
autoScroll : true,
store : new Ext.data.JsonStore({
root : 'dataset.columnModel',
restful : true,
proxy : new Ext.data.HttpProxy({
url : this.url,
restful : true,
method : 'GET'
}),
remoteSort : true,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'columnAlias',
type : 'string'
}, {
name : 'visible',
type : 'boolean'
}, {
name : 'schema',
type : 'string'
}, {
name : 'tableName',
type : 'string'
}, {
name : 'columnRenderer',
type : 'string'
} ],
autoLoad : true,
listeners : {
scope : this,
load : function (store, records, options) {
var i;
for (i = 0; i < records.length; i++) {
if (records[i].data !== undefined && !records[i].data.visible && records[i].data.columnRenderer != "noClientAccess") {
store.remove(records[i]);
}
}
}
}
}),
cm : this.cmSelectColumn,
sm : this.smSelectColumn
});
this.items = [ {
xtype : 'panel',
layout : 'fit',
items : [ this.gridSelectColumn ],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ]
} ];
sitools.admin.datasets.selectColumn.superclass.initComponent.call(this);
},
/**
* Method called on Ok button.
* update the Record and close the window
*/
onValidate : function () {
var rec = this.gridSelectColumn.getSelectionModel().getSelected();
if (rec !== null) {
this.record.data[this.field] = rec.data.columnAlias;
// this.recordColumn.data.dataIndex = rec.data.dataIndex;
// this.recordColumn.data.schema = rec.data.schema;
this.parentView.refresh();
this.close();
} else {
new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('warning.noselection'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
}
}
});
Ext.reg('s-datasetscolumnwin', sitools.admin.datasets.selectColumn);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, loadUrl*/
/*
* @include "convertersProp.js"
* @include "../id.js"
*/
Ext.namespace('sitools.admin.converters');
/**
* Converters Crud Panel
* @requires sitools.admin.converters.convertersProp
* @class sitools.admin.converters.convertersCrudPanel
* @extends Ext.grid.GridPanel
*/
sitools.admin.converters.convertersCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.CONVERTERS,
pageSize : 10,
modify : false,
urlGrid : null,
converterChainedId : {},
// loadMask: true,
conflictWarned : false,
viewConfig : {
forceFit : true,
autoFill : true,
getRowClass : function (row, index) {
var cls = '';
var data = row.data;
if (data.classVersion !== data.currentClassVersion
&& data.currentClassVersion !== null
&& data.currentClassVersion !== undefined) {
if (!this.conflictWarned) {
Ext.Msg.alert("warning.version.conflict", "Converter "
+ data.name
+ " definition (v"
+ data.classVersion
+ ") may conflict with current class version : "
+ data.currentClassVersion);
this.conflictWarned = true;
}
cls = "red-row";
}
return cls;
}
},
initComponent : function () {
this.urlDatasets = loadUrl.get('APP_URL') + loadUrl.get('APP_DATASETS_URL');
this.converterUrlPart = loadUrl.get('APP_DATASETS_CONVERTERS_URL');
this.httpProxyForms = new Ext.data.HttpProxy({
url : "/tmp",
restful : true,
method : 'GET'
});
this.store = new Ext.data.JsonStore({
idProperty : 'id',
root : "converterChainedModel.converters",
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'className',
type : 'string'
}, {
name : 'descriptionAction',
type : 'string'
}, {
name : 'parameters'
}, {
name : 'classVersion',
type : 'string'
}, {
name : 'classAuthor',
type : 'string'
}, {
name : 'currentClassVersion',
type : 'string'
}, {
name : 'currentClassAuthor',
type : 'string'
}, {
name : 'status',
type : 'string'
}, {
name : 'classOwner',
type : 'string'
}],
proxy : this.httpProxyForms
});
var storeDatasets = new Ext.data.JsonStore({
fields : [ 'id', 'name' ],
url : this.urlDatasets,
root : "data",
autoLoad : true
});
this.comboDatasets = new Ext.form.ComboBox({
store : storeDatasets,
displayField : 'name',
valueField : 'id',
typeAhead : true,
mode : 'local',
forceSelection : true,
triggerAction : 'all',
emptyText : i18n.get('label.selectDatasets'),
selectOnFocus : true,
listeners : {
scope : this,
select : function (combo, rec, index) {
this.datasetId = rec.data.id;
this.httpProxyForms.setUrl(this.urlDatasets + "/" + this.datasetId + this.converterUrlPart, true);
this.getStore().removeAll();
this.getStore().load();
}
}
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 150,
sortable : false
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 200,
sortable : false
}, {
header : i18n.get('label.descriptionAction'),
dataIndex : 'descriptionAction',
width : 200,
sortable : false
}, {
header : i18n.get('label.status'),
dataIndex : 'status',
width : 50,
sortable : false
}, {
header : i18n.get('label.className'),
dataIndex : 'className',
width : 150,
sortable : false
}, {
header : i18n.get('label.classVersion'),
dataIndex : 'classVersion',
width : 50,
sortable : false
}, {
header : i18n.get('label.currentClassVersion'),
dataIndex : 'currentClassVersion',
width : 50,
sortable : false
}, {
header : i18n.get('label.classAuthor'),
dataIndex : 'classAuthor',
width : 100,
sortable : false
}, {
header : i18n.get('label.classOwner'),
dataIndex : 'classOwner',
width : 100,
sortable : false
} ]
});
this.tbar = {
xtype : 'sitools.widget.GridSorterToolbar',
defaults : {
scope : this
},
items : [ this.comboDatasets, {
text : i18n.get('label.add'),
icon : '/sitools/common/res/images/icons/toolbar_create.png',
handler : this.onCreate,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : '/sitools/common/res/images/icons/toolbar_edit.png',
handler : this.onModify,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : '/sitools/common/res/images/icons/toolbar_delete.png',
handler : this.onDelete,
xtype : 's-menuButton'
}, '-', {
text : i18n.get('label.deleteAll'),
icon : '/sitools/common/res/images/icons/toolbar_delete.png',
handler : this.onDeleteAll,
xtype : 's-menuButton'
}, {
text : i18n.get('label.saveOrder'),
icon : '/sitools/common/res/images/icons/save.png',
handler : this.onSave,
xtype : 's-menuButton'
}, {
text : i18n.get('label.active'),
icon : '/sitools/common/res/images/icons/toolbar_active.png',
handler : this._onActive,
xtype : 's-menuButton'
}, {
text : i18n.get('label.disactive'),
icon : '/sitools/common/res/images/icons/toolbar_disactive.png',
handler : this._onDisactive,
xtype : 's-menuButton'
} ]
};
this.listeners = {
scope : this,
rowDblClick : this.onModify
};
sitools.admin.converters.convertersCrudPanel.superclass.initComponent.call(this);
},
onCreate : function () {
if (Ext.isEmpty(this.comboDatasets.getValue())) {
return;
}
var up = new sitools.admin.converters.convertersProp({
action : 'create',
parent : this,
datasetId : this.datasetId,
converterUrlPart : this.converterUrlPart,
urlDatasets : this.urlDatasets
});
up.show();
},
onSave : function () {
if (Ext.isEmpty(this.comboDatasets.getValue())) {
return;
}
var datasetId = this.comboDatasets.getValue(), jsonReturn = {};
jsonReturn.id = datasetId;
jsonReturn.idOrder = [];
for (var i = 0; i < this.store.getCount(); i++) {
var rec = this.store.getAt(i).data;
jsonReturn.idOrder.push(rec.id);
}
var url = this.urlDatasets + "/" + datasetId + this.converterUrlPart;
Ext.Ajax.request({
url : url,
method : "PUT",
scope : this,
jsonData : jsonReturn,
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (!data.success) {
Ext.Msg.alert(i18n.get('label.warning'), data.message);
return false;
}
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('label.converterSaved'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
Ext.Msg.alert(i18n.get("label.information"), i18n.get("label.restartDsNeededConv"));
//this.fillGrid(data);
this.getStore().reload();
}
});
},
onModify : function () {
if (Ext.isEmpty(this.comboDatasets.getValue())) {
return;
}
var rec = this.getSelectionModel().getSelected();
var index = this.getStore().indexOf(rec);
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.admin.converters.convertersProp({
action : 'modify',
parent : this,
converter : rec.data,
index : index,
datasetId : this.datasetId,
converterUrlPart : this.converterUrlPart,
urlDatasets : this.urlDatasets,
converterChainedId : this.converterChainedId
});
up.show();
},
onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (Ext.isEmpty(rec)) {
return false;
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('label.convertersCrud.deleteConverter'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec.data.id);
}
}
});
},
doDelete : function (converterId) {
var datasetId = this.comboDatasets.getValue();
var url = this.urlDatasets + "/" + datasetId + this.converterUrlPart + "/" + converterId;
Ext.Ajax.request({
url : url,
method : "DELETE",
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.getStore().reload();
Ext.Msg.alert(i18n.get("label.information"), i18n.get("label.restartDsNeededConvDelete"));
}
}
});
},
onDeleteAll : function () {
if (Ext.isEmpty(this.comboDatasets.getValue())) {
return;
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('label.convertersCrud.delete.all'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDeleteAll();
}
}
});
},
doDeleteAll : function () {
var datasetId = this.comboDatasets.getValue();
var url = this.urlDatasets + "/" + datasetId + this.converterUrlPart;
Ext.Ajax.request({
url : url,
method : "DELETE",
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.getStore().removeAll();
this.getStore().reload();
Ext.Msg.alert(i18n.get("label.information"), i18n.get("label.restartDsNeededConvDelete"));
}
}
});
},
_onActive : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.urlDatasets + "/" + this.datasetId + this.converterUrlPart + "/" + rec.data.id + "/start",
method : 'PUT',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
_onDisactive : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.urlDatasets + "/" + this.datasetId + this.converterUrlPart + "/" + rec.data.id + "/stop",
method : 'PUT',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
}
});
Ext.reg('s-converters', sitools.admin.converters.convertersCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, loadUrl*/
/*
* @include "../datasets/selectColumn.js"
*/
Ext.namespace('sitools.admin.converters');
/**
* A converter properties panel.
* Administrator should create or update converters on a specific Dataset.
* @cfg {string} action Should be 'create' or 'modify'
* @cfg {} parent Component caller.
* @cfg {string} datasetId The Dataset Id
* @cfg {string} converterUrlPart The string to add to convert dataset url to converters url
* @cfg {string} urlDatasets the url of the datasets collection resource.
* @class sitools.admin.converters.convertersProp
* @extends Ext.Window
*/
//sitools.component.converters.convertersProp = Ext.extend(Ext.Window, {
sitools.admin.converters.convertersProp = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
resizable : true,
initComponent : function () {
this.convertersPluginUrl = loadUrl.get('APP_URL') + loadUrl.get('APP_DATASETS_CONVERTERS_PLUGINS_URL');
this.title = this.action == "create" ? i18n.get('label.createConverter') : i18n.get('label.modifyConverter');
var expander = new Ext.ux.grid.RowExpander({
tpl : new Ext.XTemplate(
'<tpl if="this.descEmpty(description)" ><div></div></tpl>',
'<tpl if="this.descEmpty(description) == false" ><div class="sitoolsDescription"><div class="sitoolsDescriptionHeader">Description : </div><p class="sitoolsDescriptionText"> {description} </p></div></tpl>',
{
compiled : true,
descEmpty : function (description) {
return Ext.isEmpty(description);
}
}),
expandOnDblClick : true
});
this.gridConverter = new Ext.grid.GridPanel({
viewConfig : {
forceFit : true
},
id : 'gridConverter',
title : i18n.get('title.converterClass'),
store : new Ext.data.JsonStore({
root : 'data',
restful : true,
proxy : new Ext.data.HttpProxy({
url : this.convertersPluginUrl,
restful : true,
method : 'GET'
}),
remoteSort : false,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'className',
type : 'string'
}, {
name : 'classAuthor',
type : 'string'
}, {
name : 'classVersion',
type : 'string'
},
{
name : 'classOwner',
type : 'string'
}],
autoLoad : true
}),
cm : new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ expander, {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100,
sortable : true
}, {
header : i18n.get('label.className'),
dataIndex : 'className',
width : 300,
sortable : true
}, {
header : i18n.get('label.author'),
dataIndex : 'classAuthor',
width : 100,
sortable : true
}, {
header : i18n.get('label.version'),
dataIndex : 'classVersion',
width : 100,
sortable : true
},
{
header : i18n.get('label.classOwner'),
dataIndex : 'classOwner',
width : 100,
sortable : true
}]
}),
listeners : {
scope : this,
rowclick : this.onClassClick
},
plugins : expander
});
this.proxyFieldMapping = new Ext.data.HttpProxy({
url : '/tmp',
restful : true,
method : 'GET'
});
var expanderGridFieldMapping = new sitools.widget.ViolationRowExpander({
tpl : new Ext.XTemplate(
'<tpl if="this.descEmpty(description)" ><div></div></tpl>',
'<tpl if="this.descEmpty(description) == false" ><div class="sitoolsDescription"><div class="sitoolsDescriptionHeader">Description : </div><p class="sitoolsDescriptionText"> {description} </p></div></tpl>',
{
compiled : true,
descEmpty : function (description) {
return Ext.isEmpty(description);
}
}),
expandOnDblClick : false
});
this.gridFieldMapping = new Ext.grid.EditorGridPanel({
viewConfig : {
forceFit : true,
scope : this,
getRowClass : function (record, index, rowParams, store) {
var cls = '';
var violation = record.get("violation");
if (!Ext.isEmpty(violation)) {
if (violation.level == "CRITICAL") {
cls = "red-row";
} else if (violation.level == "WARNING") {
cls = "orange-row";
}
}
return cls;
},
listeners : {
scope : this,
refresh : function (view) {
var grid = this.gridFieldMapping;
var store = grid.getStore();
store.each(function (record) {
var violation = record.get("violation");
if (!Ext.isEmpty(violation)) {
var index = store.indexOf(record);
//var view = this.scope.gridFieldMapping.getView();
var htmlLineEl = view.getRow(index);
var el = Ext.get(htmlLineEl);
var cls = (violation.level == "CRITICAL")
? "x-form-invalid-tip"
: "x-form-invalid-tip x-form-warning-tip";
var ttConfig = {
html : violation.message,
dismissDelay : 0,
target : el,
cls : cls
};
var ttip = new Ext.ToolTip(ttConfig);
}
});
}
}
},
layout : 'fit',
region : 'center',
store : new Ext.data.JsonStore({
root : 'converter.parameters',
proxy : this.proxyFieldMapping,
restful : true,
remoteSort : false,
idProperty : 'name',
fields : [ {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'parameterType',
type : 'string'
}, {
name : 'attachedColumn',
type : 'string'
}, {
name : 'value',
type : 'string'
}, {
name : 'valueType',
type : 'string'
}, {
name : 'violation'
} ]
}),
cm : new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [expanderGridFieldMapping, {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100,
sortable : true
}, {
header : i18n.get('label.type'),
dataIndex : 'parameterType',
width : 150,
sortable : false
}, {
header : i18n.get('label.attachedColumn'),
dataIndex : 'attachedColumn',
width : 100,
sortable : false
}, {
header : i18n.get('label.value'),
dataIndex : 'value',
width : 80,
sortable : false,
editable : true,
editor : new Ext.form.TextField()
} ]
}),
bbar : new Ext.ux.StatusBar({
id: 'statusBar',
hidden : true,
iconCls: 'x-status-error',
text : i18n.get("label.converterErrorValidationNotification")
}),
listeners : {
scope : this,
celldblclick : function (grid, rowIndex, columnIndex, e) {
var storeRecord = grid.getStore().getAt(rowIndex);
var rec = storeRecord.data;
if (columnIndex == 3 && rec.parameterType != "CONVERTER_PARAMETER_INTERN") {
var selectColumnWin = new sitools.admin.datasets.selectColumn({
field : "attachedColumn",
record : storeRecord,
parentStore : this.gridFieldMapping.getStore(),
parentView : this.gridFieldMapping.getView(),
url : this.urlDatasets + "/" + this.datasetId
});
selectColumnWin.show(ID.BOX.DATASETS);
} else if (columnIndex == 4 && rec.parameterType == "CONVERTER_PARAMETER_INTERN") {
return true;
} else {
return false;
}
}
},
plugins : expanderGridFieldMapping
});
// set the search form
this.fieldMappingFormPanel = new Ext.FormPanel({
height : 40,
frame : true,
defaultType : 'textfield',
items : [ {
fieldLabel : i18n.get('label.descriptionAction'),
name : 'descriptionAction',
anchor : '100%'
} ],
region : 'north'
});
this.fieldMappingPanel = new Ext.Panel({
layout : 'border',
id : 'gridFieldMapping',
title : i18n.get('title.fieldMapping'),
items : [ this.fieldMappingFormPanel, this.gridFieldMapping ]
});
this.tabPanel = new Ext.TabPanel({
height : 450,
activeTab : 0,
items : (this.action == "create") ? [ this.gridConverter, this.fieldMappingPanel ] : [ this.fieldMappingPanel ],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ],
listeners : {
scope : this,
beforetabchange : this.beforeTabChange
}
});
this.listeners = {
scope : this,
resize : function (window, width, height) {
var size = window.body.getSize();
this.tabPanel.setSize(size);
}
};
this.items = [ this.tabPanel ];
sitools.admin.converters.convertersProp.superclass.initComponent.call(this);
},
/**
* Method called on main tabPanel beforeTabChange event
* @param {Ext.TabPanel} self main Tab Panel
* @param {Ext.Panel} newTab new Tab
* @param {Ext.Panel} currentTab current Tab
* @return {Boolean}
*/
beforeTabChange : function (self, newTab, currentTab) {
if (this.action == "create") {
if (newTab.id == "gridFieldMapping") {
var rec = this.gridConverter.getSelectionModel().getSelected();
if (!rec) {
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('warning.noselection'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
return false;
}
}
}
},
/**
* Method called on grid click
* @param {} self
* @param {} rowIndex
* @param {} e
* @return {Boolean}
*/
onClassClick : function (self, rowIndex, e) {
if (this.action == "create") {
var rec = this.gridConverter.getSelectionModel().getSelected();
if (!rec) {
return false;
}
var className = rec.data.className;
this.proxyFieldMapping.setUrl(this.convertersPluginUrl + "/" + className
+ "/" + this.datasetId);
var store = this.gridFieldMapping.getStore();
store.removeAll();
store.load();
}
},
/**
* load the selected converter properties
*/
afterRender : function () {
sitools.admin.converters.convertersProp.superclass.afterRender.apply(this, arguments);
if (this.action == "modify") {
var form = this.fieldMappingFormPanel.getForm();
var rec = {};
rec.descriptionAction = this.converter.descriptionAction;
form.loadRecord(new Ext.data.Record(rec));
var parameters = this.converter.parameters;
if (parameters !== null) {
var store = this.gridFieldMapping.getStore();
for (var i = 0; i < parameters.length; i++) {
var recTmp = new Ext.data.Record(parameters[i]);
store.add(recTmp);
}
this.gridFieldMapping.getView().refresh();
}
}
},
/**
* Called on save Button : Validate fields and send POST or PUT request depending on action
* @return {Boolean}
*/
onValidate : function () {
var rec = this.gridConverter.getSelectionModel().getSelected();
if (!rec && this.action == "create") {
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('warning.noselection'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
return false;
}
var jsonReturn = {};
var form = this.fieldMappingFormPanel.getForm();
if (!form.isValid()) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.invalidForm'));
return;
}
if (!Ext.isEmpty(form)) {
jsonReturn.descriptionAction = form.findField("descriptionAction").getValue();
} else {
jsonReturn.descriptionAction = undefined;
}
var parameters = [];
if (this.action == "create") {
rec = this.gridConverter.getSelectionModel().getSelected();
var classParam = rec.data;
jsonReturn.className = classParam.className;
jsonReturn.name = classParam.name;
jsonReturn.description = classParam.description;
jsonReturn.classVersion = classParam.classVersion;
jsonReturn.classAuthor = classParam.classAuthor;
jsonReturn.classOwner = classParam.classOwner;
}
var storeField = this.gridFieldMapping.getStore();
for (var i = 0; i < storeField.getCount(); i++) {
var recTmp = storeField.getAt(i).data;
recTmp.violation = undefined;
parameters.push(recTmp);
}
jsonReturn.parameters = parameters;
var url = this.urlDatasets + "/" + this.datasetId + this.converterUrlPart;
var method;
if (this.action == "modify") {
url += "/" + this.converter.id;
method = "PUT";
} else {
method = "POST";
}
Ext.Ajax.request({
url : url,
method : method,
scope : this,
jsonData : jsonReturn,
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (!data.success) {
if (Ext.isEmpty(data.message)) {
var violations = data.data;
this.notifyViolations(violations);
Ext.getCmp("statusBar").show();
} else {
Ext.Msg.alert(i18n.get('label.warning'),
data.message);
}
return false;
}
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('label.converterSaved'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
//var idConvChained = data.converterChainedModel.id;
this.parent.getStore().reload();
this.close();
}
});
},
/**
* Notify violations.
* @param {Array} violations
*/
notifyViolations : function (violations) {
for (var i = 0; i < violations.length; i++) {
var violation = violations[i];
var store = this.gridFieldMapping.getStore();
var lineNb = store.findExact("name", violation.valueName);
var rec = store.getAt(lineNb);
rec.set("violation", violation);
}
this.gridFieldMapping.getView().refresh();
},
onClose : function () {
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.component.filters');
sitools.component.filters.filtersCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.FILTERS,
pageSize : 10,
modify : false,
urlGrid : null,
filterChainedId : {},
// loadMask: true,
conflictWarned : false,
viewConfig : {
forceFit : true,
autoFill : true,
getRowClass : function (row, index) {
var cls = '';
var data = row.data;
if (data.classVersion !== data.currentClassVersion
&& data.currentClassVersion !== null
&& data.currentClassVersion !== undefined) {
if (!this.conflictWarned) {
Ext.Msg.alert("warning.version.conflict", "Filter "
+ data.name
+ " definition (v"
+ data.classVersion
+ ") may conflict with current class version : "
+ data.currentClassVersion);
this.conflictWarned = true;
}
cls = "red-row";
}
return cls;
}
},
initComponent : function () {
this.urlDatasets = loadUrl.get('APP_URL') + loadUrl.get('APP_DATASETS_URL');
this.filterUrlPart = loadUrl.get('APP_DATASETS_FILTERS_URL');
this.httpFilterForms = new Ext.data.HttpProxy({
url : '/tmp',
restful : true,
method : 'GET'
});
this.store = new Ext.data.JsonStore({
idProperty : 'id',
root : "filterChainedModel.filters",
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'className',
type : 'string'
}, {
name : 'descriptionAction',
type : 'string'
}, {
name : 'parameters'
}, {
name : 'classVersion',
type : 'string'
}, {
name : 'classAuthor',
type : 'string'
}, {
name : 'currentClassVersion',
type : 'string'
}, {
name : 'currentClassAuthor',
type : 'string'
}, {
name : 'status',
type : 'string'
}, {
name : 'classOwner',
type : 'string'
}
],
proxy : this.httpFilterForms
});
var storeDatasets = new Ext.data.JsonStore({
fields : [ 'id', 'name' ],
url : this.urlDatasets,
root : "data",
autoLoad : true
});
this.comboDatasets = new Ext.form.ComboBox({
store : storeDatasets,
displayField : 'name',
valueField : 'id',
typeAhead : true,
mode : 'local',
forceSelection : true,
triggerAction : 'all',
emptyText : i18n.get('label.selectDatasets'),
selectOnFocus : true,
listeners : {
scope : this,
select : function (combo, rec, index) {
this.datasetId = rec.data.id;
this.httpFilterForms.setUrl(this.urlDatasets + "/" + this.datasetId + this.filterUrlPart, true);
this.getStore().removeAll();
this.getStore().load();
}
}
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 150,
sortable : true
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 200,
sortable : false
}, {
header : i18n.get('label.descriptionAction'),
dataIndex : 'descriptionAction',
width : 200,
sortable : false
}, {
header : i18n.get('label.status'),
dataIndex : 'status',
width : 50,
sortable : false
}, {
header : i18n.get('label.className'),
dataIndex : 'className',
width : 150,
sortable : false
}, {
header : i18n.get('label.classVersion'),
dataIndex : 'classVersion',
width : 50,
sortable : false
}, {
header : i18n.get('label.currentClassVersion'),
dataIndex : 'currentClassVersion',
width : 50,
sortable : false
}, {
header : i18n.get('label.classAuthor'),
dataIndex : 'classAuthor',
width : 100,
sortable : false
}, {
header : i18n.get('label.classOwner'),
dataIndex : 'classOwner',
width : 100,
sortable : false
} ]
});
this.tbar = {
xtype : 'sitools.widget.GridSorterToolbar',
defaults : {
scope : this
},
items : [ this.comboDatasets, {
text : i18n.get('label.add'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreate,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this.onModify,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDelete,
xtype : 's-menuButton'
}, '-', {
text : i18n.get('label.deleteAll'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDeleteAll,
xtype : 's-menuButton'
}, {
text : i18n.get('label.saveOrder'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/save.png',
handler : this.onSave,
xtype : 's-menuButton'
}, {
text : i18n.get('label.active'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_active.png',
handler : this._onActive,
xtype : 's-menuButton'
}, {
text : i18n.get('label.disactive'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_disactive.png',
handler : this._onDisactive,
xtype : 's-menuButton'
} ]
};
this.listeners = {
scope : this,
rowDblClick : this.onModify
};
sitools.component.filters.filtersCrudPanel.superclass.initComponent.call(this);
},
onRender : function () {
sitools.component.filters.filtersCrudPanel.superclass.onRender.apply(this, arguments);
},
onCreate : function () {
if (Ext.isEmpty(this.comboDatasets.getValue())) {
return;
}
var up = new sitools.component.filters.filtersProp({
action : 'create',
parent : this,
datasetId : this.datasetId,
urlDatasets : this.urlDatasets,
filterUrlPart : this.filterUrlPart
});
up.show();
},
onSave : function () {
if (Ext.isEmpty(this.comboDatasets.getValue())) {
return;
}
var datasetId = this.comboDatasets.getValue(), jsonReturn = {};
jsonReturn.id = datasetId;
jsonReturn.idOrder = [];
for (var i = 0; i < this.store.getCount(); i++) {
var rec = this.store.getAt(i).data;
jsonReturn.idOrder.push(rec.id);
}
var url = this.urlDatasets + "/" + datasetId + this.filterUrlPart;
Ext.Ajax.request({
url : url,
method : "PUT",
scope : this,
jsonData : jsonReturn,
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (!data.success) {
Ext.Msg.alert(i18n.get('label.warning'), data.message);
return false;
}
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('label.filtersSaved'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
Ext.Msg.alert(i18n.get("label.information"), i18n.get("label.restartDsNeededFilter"));
//this.fillGrid(data);
this.getStore().reload();
}
});
},
onModify : function () {
if (Ext.isEmpty(this.comboDatasets.getValue())) {
return;
}
var rec = this.getSelectionModel().getSelected();
var index = this.getStore().indexOf(rec);
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.component.filters.filtersProp({
action : 'modify',
parent : this,
filter : rec.data,
index : index,
datasetId : this.datasetId,
urlDatasets : this.urlDatasets,
filterChainedId : this.filterChainedId,
filterUrlPart : this.filterUrlPart
});
up.show();
},
onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (Ext.isEmpty(rec)) {
return false;
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('label.filtersCrud.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec.data.id);
}
}
});
},
doDelete : function (filterId) {
var datasetId = this.comboDatasets.getValue();
var url = this.urlDatasets + "/" + datasetId + this.filterUrlPart + "/" + filterId;
Ext.Ajax.request({
url : url,
method : "DELETE",
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.getStore().reload();
Ext.Msg.alert(i18n.get("label.information"), i18n.get("label.restartDsNeededFilterDelete"));
}
}
});
},
onDeleteAll : function () {
if (Ext.isEmpty(this.comboDatasets.getValue())) {
return;
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('label.filtersCrud.delete.all'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDeleteAll();
}
}
});
},
doDeleteAll : function () {
var datasetId = this.comboDatasets.getValue();
var url = this.urlDatasets + "/" + datasetId + this.filterUrlPart;
Ext.Ajax.request({
url : url,
method : "DELETE",
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.getStore().removeAll();
this.getStore().reload();
Ext.Msg.alert(i18n.get("label.information"), i18n.get("label.restartDsNeededFilterDelete"));
}
}
});
},
_onActive : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.urlDatasets + "/" + this.datasetId + this.filterUrlPart + "/" + rec.data.id + "/start",
method : 'PUT',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
_onDisactive : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.urlDatasets + "/" + this.datasetId + this.filterUrlPart + "/" + rec.data.id + "/stop",
method : 'PUT',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
}
});
Ext.reg('s-filters', sitools.component.filters.filtersCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
/*
* @include "../datasets/selectColumn.js"
*/
Ext.namespace('sitools.component.filters');
sitools.component.filters.filtersProp = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
resizable : true,
initComponent : function () {
this.filtersUrl = loadUrl.get('APP_URL') + loadUrl.get('APP_DATASETS_FILTERS_PLUGINS_URL');
this.title = this.action == "create" ? i18n.get('label.createFilter') : i18n.get('label.modifyFilter');
var expander = new Ext.ux.grid.RowExpander({
tpl : new Ext.XTemplate(
'<tpl if="this.descEmpty(description)" ><div></div></tpl>',
'<tpl if="this.descEmpty(description) == false" ><div class="sitoolsDescription"><div class="sitoolsDescriptionHeader">Description : </div><p class="sitoolsDescriptionText"> {description} </p></div></tpl>',
{
compiled : true,
descEmpty : function (description) {
return Ext.isEmpty(description);
}
}),
expandOnDblClick : true
});
this.gridFilter = new Ext.grid.GridPanel({
viewConfig : {
forceFit : true
},
id : 'gridFilter',
title : i18n.get('title.filterClass'),
store : new Ext.data.JsonStore({
root : 'data',
restful : true,
proxy : new Ext.data.HttpProxy({
url : this.filtersUrl,
restful : true,
method : 'GET'
}),
remoteSort : false,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'className',
type : 'string'
}, {
name : 'classAuthor',
type : 'string'
}, {
name : 'classVersion',
type : 'string'
},
{
name : 'classOwner',
type : 'string'
}],
autoLoad : true
}),
cm : new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ expander, {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100,
sortable : true
}, {
header : i18n.get('label.className'),
dataIndex : 'className',
width : 300,
sortable : true
}, {
header : i18n.get('label.author'),
dataIndex : 'classAuthor',
width : 100,
sortable : true
}, {
header : i18n.get('label.version'),
dataIndex : 'classVersion',
width : 100,
sortable : true
},
{
header : i18n.get('label.classOwner'),
dataIndex : 'classOwner',
width : 100,
sortable : true
}]
}),
listeners : {
scope : this,
rowclick : this.onClassClick
},
plugins : expander
});
this.proxyFieldMapping = new Ext.data.HttpProxy({
url : '/tmp',
restful : true,
method : 'GET'
});
var expanderGridFieldMapping = new sitools.widget.ViolationRowExpander({
tpl : new Ext.XTemplate(
'<tpl if="this.descEmpty(description)" ><div></div></tpl>',
'<tpl if="this.descEmpty(description) == false" ><div class="sitoolsDescription"><div class="sitoolsDescriptionHeader">Description : </div><p class="sitoolsDescriptionText"> {description} </p></div></tpl>',
{
compiled : true,
descEmpty : function (description) {
return Ext.isEmpty(description);
}
}),
expandOnDblClick : false
});
this.gridFieldMapping = new Ext.grid.EditorGridPanel({
viewConfig : {
forceFit : true,
scope : this,
getRowClass : function (record, index, rowParams, store) {
var cls = '';
var violation = record.get("violation");
if (!Ext.isEmpty(violation)) {
if (violation.level == "CRITICAL") {
cls = "red-row";
} else if (violation.level == "WARNING") {
cls = "orange-row";
}
}
return cls;
},
listeners : {
scope : this,
refresh : function (view) {
var grid = this.gridFieldMapping;
var store = grid.getStore();
store.each(function (record) {
var violation = record.get("violation");
if (!Ext.isEmpty(violation)) {
var index = store.indexOf(record);
//var view = this.scope.gridFieldMapping.getView();
var htmlLineEl = view.getRow(index);
var el = Ext.get(htmlLineEl);
var cls = (violation.level == "CRITICAL")
? "x-form-invalid-tip"
: "x-form-invalid-tip x-form-warning-tip";
var ttConfig = {
html : violation.message,
dismissDelay : 0,
target : el,
cls : cls
};
var ttip = new Ext.ToolTip(ttConfig);
}
});
}
}
},
layout : 'fit',
region : 'center',
store : new Ext.data.JsonStore({
root : 'filter.parameters',
proxy : this.proxyFieldMapping,
restful : true,
remoteSort : false,
idProperty : 'name',
fields : [ {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'parameterType',
type : 'string'
}, {
name : 'attachedColumn',
type : 'string'
}, {
name : 'value',
type : 'string'
}, {
name : 'valueType',
type : 'string'
}, {
name : 'violation'
}
]
}),
cm : new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [expanderGridFieldMapping, {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100,
sortable : true
}, {
header : i18n.get('label.type'),
dataIndex : 'parameterType',
width : 150,
sortable : false
}, {
header : i18n.get('label.attachedColumn'),
dataIndex : 'attachedColumn',
width : 100,
sortable : false
}, {
header : i18n.get('label.value'),
dataIndex : 'value',
width : 80,
sortable : false,
editable : true,
editor : new Ext.form.TextField()
} ]
}),
bbar : new Ext.ux.StatusBar({
id: 'statusBar',
hidden : true,
iconCls: 'x-status-error',
text : i18n.get("label.filterErrorValidationNotification")
}),
listeners : {
scope : this,
celldblclick : function (grid, rowIndex, columnIndex, e) {
var storeRecord = grid.getStore().getAt(rowIndex);
var rec = storeRecord.data;
if (columnIndex == 3 && rec.parameterType != "PARAMETER_INTERN") {
var selectColumnWin = new sitools.admin.datasets.selectColumn({
field : "attachedColumn",
record : storeRecord,
parentStore : this.gridFieldMapping.getStore(),
parentView : this.gridFieldMapping.getView(),
url : this.urlDatasets + "/" + this.datasetId
});
selectColumnWin.show(ID.BOX.DATASETS);
} else if (columnIndex == 4 && rec.parameterType == "PARAMETER_INTERN") {
return true;
} else {
return false;
}
}
},
plugins : expanderGridFieldMapping
});
// set the search form
this.fieldMappingFormPanel = new Ext.FormPanel({
height : 40,
frame : true,
defaultType : 'textfield',
items : [ {
fieldLabel : i18n.get('label.descriptionAction'),
name : 'descriptionAction',
anchor : '100%'
} ],
region : 'north'
});
this.fieldMappingPanel = new Ext.Panel({
layout : 'border',
id : 'gridFieldMapping',
title : i18n.get('title.fieldMapping'),
items : [ this.fieldMappingFormPanel, this.gridFieldMapping ]
});
this.tabPanel = new Ext.TabPanel({
height : 450,
activeTab : 0,
items : (this.action == "create") ? [ this.gridFilter, this.fieldMappingPanel ] : [ this.fieldMappingPanel ],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ],
listeners : {
scope : this,
beforetabchange : this.beforeTabChange
}
});
this.listeners = {
scope : this,
resize : function (window, width, height) {
var size = window.body.getSize();
this.tabPanel.setSize(size);
}
};
this.items = [ this.tabPanel ];
sitools.component.filters.filtersProp.superclass.initComponent.call(this);
},
beforeTabChange : function (self, newTab, currentTab) {
if (this.action == "create") {
if (newTab.id == "gridFieldMapping") {
var rec = this.gridFilter.getSelectionModel().getSelected();
if (!rec) {
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('warning.noselection'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
return false;
}
}
}
},
onClassClick : function (self, rowIndex, e) {
if (this.action == "create") {
var rec = this.gridFilter.getSelectionModel().getSelected();
if (!rec) {
// var tmp = new Ext.ux.Notification({
// iconCls : 'x-icon-information',
// title : i18n.get('label.information'),
// html : i18n.get('warning.noselection'),
// autoDestroy : true,
// hideDelay : 1000
// }).show(document);
return false;
}
var className = rec.data.className;
this.proxyFieldMapping.setUrl(this.filtersUrl + "/" + className
+ "/" + this.datasetId);
var store = this.gridFieldMapping.getStore();
store.removeAll();
store.load();
}
},
afterRender : function () {
sitools.component.filters.filtersProp.superclass.afterRender.apply(this, arguments);
if (this.action == "modify") {
var form = this.fieldMappingFormPanel.getForm();
var rec = {};
rec.descriptionAction = this.filter.descriptionAction;
form.loadRecord(new Ext.data.Record(rec));
var parameters = this.filter.parameters;
if (parameters !== null) {
var store = this.gridFieldMapping.getStore();
var i;
for (i = 0; i < parameters.length; i++) {
rec = new Ext.data.Record(parameters[i]);
store.add(rec);
}
this.gridFieldMapping.getView().refresh();
}
}
},
onValidate : function () {
var rec = this.gridFilter.getSelectionModel().getSelected();
if (!rec && this.action == "create") {
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('warning.noselection'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
return false;
}
var jsonReturn = {};
var form = this.fieldMappingFormPanel.getForm();
if (!form.isValid()) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.invalidForm'));
return false;
}
if (!Ext.isEmpty(form)) {
jsonReturn.descriptionAction = form.findField("descriptionAction").getValue();
} else {
jsonReturn.descriptionAction = undefined;
}
var parameters = [];
if (this.action == "create") {
rec = this.gridFilter.getSelectionModel().getSelected();
var classParam = rec.data;
jsonReturn.className = classParam.className;
jsonReturn.name = classParam.name;
jsonReturn.description = classParam.description;
jsonReturn.classVersion = classParam.classVersion;
jsonReturn.classAuthor = classParam.classAuthor;
jsonReturn.classOwner = classParam.classOwner;
}
var storeField = this.gridFieldMapping.getStore();
for (var i = 0; i < storeField.getCount(); i++) {
var recTmp = storeField.getAt(i).data;
//not to send the violation object, used only on the client part
recTmp.violation = undefined;
parameters.push(recTmp);
}
jsonReturn.parameters = parameters;
var url = this.urlDatasets + "/" + this.datasetId + this.filterUrlPart;
var method;
if (this.action == "modify") {
url += "/" + this.filter.id;
method = "PUT";
} else {
method = "POST";
}
Ext.Ajax.request({
url : url,
method : method,
scope : this,
jsonData : jsonReturn,
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (!data.success) {
if (Ext.isEmpty(data.message)) {
var violations = data.data;
this.notifyViolations(violations);
Ext.getCmp("statusBar").show();
} else {
Ext.Msg.alert(i18n.get('label.warning'),
data.message);
}
return false;
}
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('label.filterSaved'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
this.parent.getStore().reload();
this.close();
}
});
},
notifyViolations : function (violations) {
for (var i = 0; i < violations.length; i++) {
var violation = violations[i];
var store = this.gridFieldMapping.getStore();
var lineNb = store.findExact("name", violation.valueName);
var rec = store.getAt(lineNb);
rec.set("violation", violation);
}
this.gridFieldMapping.getView().refresh();
},
onClose : function () {
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.component.formComponents');
sitools.component.formComponents.FormComponentsCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.FORMCOMPONENTS,
sm : new Ext.grid.RowSelectionModel({
singleSelect : true
}),
pageSize : 10,
initComponent : function () {
this.url = loadUrl.get('APP_URL') + loadUrl.get('APP_FORMCOMPONENTS_URL');
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
remoteSort : true,
autoSave : false,
url : this.url,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'type',
type : 'string'
}, {
name : 'componentDefaultHeight',
type : 'string'
}, {
name : 'componentDefaultWidth',
type : 'string'
}, {
name : 'jsAdminObject',
type : 'string'
}, {
name : 'jsUserObject',
type : 'string'
}, {
name : 'imageUrl',
type : 'string'
}, {
name : "priority",
type : "integer"
}]
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.type'),
dataIndex : 'type',
width : 100,
sortable : true
}, {
header : i18n.get('label.jsAdminObject'),
dataIndex : 'jsAdminObject',
width : 350,
sortable : false
}, {
header : i18n.get('label.jsUserObject'),
dataIndex : 'jsUserObject',
width : 350,
sortable : false
}, {
header : i18n.get('label.priority'),
dataIndex : 'priority',
width : 50,
sortable : true
} ]
});
this.bbar = {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
};
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this._onCreate,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this._onModify,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this._onDelete,
xtype : 's-menuButton'
}, '->', {
xtype : 's-filter',
emptyText : i18n.get('label.search'),
store : this.store,
pageSize : this.pageSize
} ]
};
this.view = new Ext.grid.GridView({
forceFit : true
});
this.listeners = {
scope : this,
rowDblClick : this._onModify
};
sitools.component.formComponents.FormComponentsCrudPanel.superclass.initComponent.call(this);
},
onRender : function () {
sitools.component.formComponents.FormComponentsCrudPanel.superclass.onRender.apply(this, arguments);
this.store.load({
params : {
start : 0,
limit : this.pageSize
}
});
},
_onCreate : function () {
var dbp = new sitools.component.formComponents.FormComponentsPropPanel({
url : this.url,
action : 'create',
store : this.store
});
dbp.show(ID.BOX.FORMCOMPONENTS);
},
_onModify : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var dbp = new sitools.component.formComponents.FormComponentsPropPanel({
url : this.url + '/' + rec.id,
action : 'modify',
store : this.store
});
dbp.show(ID.BOX.FORMCOMPONENTS);
},
_onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return false;
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('formComponentsCrud.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec);
}
}
});
},
doDelete : function (rec) {
// var rec = this.getSelectionModel().getSelected();
// if (!rec) return false;
Ext.Ajax.request({
url : this.url + "/" + rec.id,
method : 'DELETE',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
}
});
Ext.reg('s-formComponents', sitools.component.formComponents.FormComponentsCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, includeJs*/
Ext.namespace('sitools.component.formComponents');
sitools.component.formComponents.FormComponentsPropPanel = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
id : ID.COMPONENT_SETUP.FORMCOMPONENTS,
layout : 'fit',
initComponent : function () {
if (this.action == 'create') {
this.title = i18n.get('label.createFormComponents');
} else if (this.action == 'modify') {
this.title = i18n.get('label.modifyFormComponents');
}
this.items = [ {
xtype : 'panel',
layout : 'fit',
title : i18n.get('label.formComponentsInfo'),
items : [ {
xtype : 'form',
border : false,
labelWidth : 150,
padding : 10,
items : [ {
xtype : 'textfield',
name : 'id',
hidden : true
}, {
xtype : 'textfield',
name : 'type',
fieldLabel : i18n.get('label.type'),
anchor : '100%',
allowBlank : false
}, {
xtype : 'textfield',
name : 'componentDefaultHeight',
fieldLabel : i18n.get('label.defaultHeight'),
anchor : '100%',
allowBlank : false
}, {
xtype : 'textfield',
name : 'componentDefaultWidth',
fieldLabel : i18n.get('label.defaultWidth'),
anchor : '100%',
allowBlank : false
}, {
xtype : 'textfield',
name : 'jsAdminObject',
fieldLabel : i18n.get('label.jsAdminObject'),
anchor : '100%',
allowBlank : false
}, {
xtype : 'textfield',
name : 'jsUserObject',
fieldLabel : i18n.get('label.jsUserObject'),
anchor : '100%',
allowBlank : false
}, {
xtype : 'textfield',
name : 'fileUrlUser',
id : 'fileUrlUserId',
fieldLabel : i18n.get('label.fileUrlUser'),
anchor : '100%',
allowBlank : false
}, {
xtype : 'textfield',
id : 'fileUrlAdminId',
name : 'fileUrlAdmin',
fieldLabel : i18n.get('label.fileUrlAdmin'),
anchor : '100%',
allowBlank : false
}, {
xtype : 'sitoolsSelectImage',
name : 'imageUrl',
fieldLabel : i18n.get('label.image'),
anchor : '100%',
allowBlank : false
}, {
xtype : 'spinnerfield',
name : 'priority',
id : 'priorityId',
fieldLabel : i18n.get('label.priority'),
minValue : 0,
maxValue : 10,
allowDecimals : false,
incrementValue : 1,
accelerate : true,
anchor : "50%",
allowBlank : false
}]
} ],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this._onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ]
} ];
sitools.component.formComponents.FormComponentsPropPanel.superclass.initComponent.call(this);
},
onRender : function () {
sitools.component.formComponents.FormComponentsPropPanel.superclass.onRender.apply(this, arguments);
if (this.action == 'modify') {
var f = this.findByType('form')[0].getForm();
Ext.Ajax.request({
url : this.url,
method : 'GET',
scope : this,
success : function (ret) {
var data = Ext.decode(ret.responseText);
f.setValues(data.formComponent);
},
failure : alertFailure
});
}
},
_onValidate : function () {
var frm = this.findByType('form')[0].getForm();
if (!frm.isValid()) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.invalidForm'));
return false;
}
var met = this.action == 'modify' ? 'PUT' : 'POST';
var jsonObject = frm.getFieldValues();
Ext.Ajax.request({
url : this.url,
method : met,
scope : this,
jsonData : jsonObject,
success : function (ret) {
//load the scripts defined in this component.
includeJs(frm.items.get('fileUrlUserId').getValue());
includeJs(frm.items.get('fileUrlAdminId').getValue());
this.store.reload();
this.close();
},
failure : alertFailure
});
}
});
Ext.reg('s-formComponentsprop', sitools.component.formComponents.FormComponentsPropPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
/*
* @include "datasetViewprop.js"
*/
Ext.namespace('sitools.admin.datasetView');
/**
* A Panel to show the different datasetView available in Sitools2.
* @requires sitools.admin.datasetView.DatasetViewPropPanel
* @class sitools.admin.datasetView.DatasetViewsCrudPanel
* @extends Ext.grid.GridPanel
*/
sitools.admin.datasetView.DatasetViewsCrudPanel = Ext.extend(Ext.grid.GridPanel, {
//sitools.component.datasetView.DatasetViewsCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.DATASETVIEW,
sm : new Ext.grid.RowSelectionModel({
singleSelect : true
}),
pageSize : 10,
// loadMask: true,
initComponent : function () {
this.url = loadUrl.get('APP_URL') + loadUrl.get('APP_DATASETS_VIEWS_URL');
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
remoteSort : true,
autoSave : false,
url : this.url,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'jsObject',
type : 'string'
}, {
name : 'fileUrl',
type : 'string'
}, {
name : 'imageUrl',
type : 'string'
}, {
name : "priority",
type : "integer"
}]
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100,
sortable : true
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 350,
sortable : false
}, {
header : i18n.get('label.jsObject'),
dataIndex : 'jsObject',
width : 350,
sortable : false
}, {
header : i18n.get('label.priority'),
dataIndex : 'priority',
width : 50,
sortable : true
} ]
});
this.bbar = {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
};
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this._onCreate,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this._onModify,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this._onDelete,
xtype : 's-menuButton'
}, '->', {
xtype : 's-filter',
emptyText : i18n.get('label.search'),
store : this.store,
pageSize : this.pageSize
} ]
};
this.view = new Ext.grid.GridView({
forceFit : true
});
this.listeners = {
scope : this,
rowDblClick : this._onModify
};
sitools.admin.datasetView.DatasetViewsCrudPanel.superclass.initComponent.call(this);
},
onRender : function () {
sitools.admin.datasetView.DatasetViewsCrudPanel.superclass.onRender.apply(this, arguments);
this.store.load({
params : {
start : 0,
limit : this.pageSize
}
});
},
_onCreate : function () {
var dbp = new sitools.admin.datasetView.DatasetViewPropPanel({
url : this.url,
action : 'create',
store : this.store
});
dbp.show(ID.PROP.DATASETVIEW);
},
_onModify : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var dbp = new sitools.admin.datasetView.DatasetViewPropPanel({
url : this.url + '/' + rec.id,
action : 'modify',
store : this.store
});
dbp.show(ID.PROP.DATASETVIEW);
},
_onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return false;
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('datasetViewsCrud.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec);
}
}
});
},
doDelete : function (rec) {
// var rec = this.getSelectionModel().getSelected();
// if (!rec) return false;
Ext.Ajax.request({
url : this.url + "/" + rec.id,
method : 'DELETE',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
}
});
Ext.reg('s-datasetView', sitools.admin.datasetView.DatasetViewsCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, includeJs*/
Ext.namespace('sitools.admin.datasetView');
/**
* A panel to edit Dataviews.
* @class sitools.admin.datasetView.DatasetViewPropPanel
* @extends Ext.Window
*/
sitools.admin.datasetView.DatasetViewPropPanel = Ext.extend(Ext.Window, {
//sitools.component.datasetView.DatasetViewPropPanel = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
id : ID.PROP.DATAVIEW,
layout : 'fit',
initComponent : function () {
if (this.action == 'create') {
this.title = i18n.get('label.createDatasetView');
} else if (this.action == 'modify') {
this.title = i18n.get('label.modifyDatasetView');
}
var storeDependencies = new Ext.data.JsonStore({
fields : [ {
name : 'url',
type : 'string'
}],
autoLoad : false
});
var tbar = {
xtype : 'sitools.widget.GridSorterToolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreateDependencies
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDeleteDependencies
}]
};
this.gridDependencies = new Ext.grid.EditorGridPanel({
title : i18n.get('title.dependencies'),
height : 180,
store : storeDependencies,
tbar : tbar,
cm : new Ext.grid.ColumnModel({
columns : [ {
header : i18n.get('label.url'),
dataIndex : 'url',
editor : new Ext.form.TextField({
allowBlank : false
})
} ]
}),
sm : new Ext.grid.RowSelectionModel({
singleSelect : true
}),
viewConfig : {
forceFit : true
}
});
this.formPanel = new Ext.form.FormPanel({
title : i18n.get('label.datasetViewInfo'),
border : false,
labelWidth : 150,
padding : 10,
items : [ {
xtype : 'textfield',
name : 'id',
hidden : true
}, {
xtype : 'textfield',
name : 'name',
fieldLabel : i18n.get('label.name'),
anchor : '100%',
allowBlank : false
}, {
xtype : 'textfield',
name : 'description',
fieldLabel : i18n.get('label.description'),
anchor : '100%',
allowBlank : false
}, {
xtype : 'textfield',
name : 'jsObject',
fieldLabel : i18n.get('label.jsObject'),
anchor : '100%',
allowBlank : false
}, {
xtype : 'textfield',
name : 'fileUrl',
id : 'fileUrlId',
fieldLabel : i18n.get('label.fileUrl'),
anchor : '100%'
}, {
xtype : 'sitoolsSelectImage',
name : 'imageUrl',
fieldLabel : i18n.get('label.image'),
anchor : '100%',
allowBlank : true
}, {
xtype : 'spinnerfield',
name : 'priority',
id : 'priorityId',
fieldLabel : i18n.get('label.priority'),
minValue : 0,
maxValue : 10,
allowDecimals : false,
incrementValue : 1,
accelerate : true,
anchor : "50%",
allowBlank : false
}]
});
this.tabPanel = new Ext.TabPanel({
activeTab : 0,
items : [this.formPanel, this.gridDependencies ],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this._onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ]
});
this.items = [this.tabPanel];
sitools.admin.datasetView.DatasetViewPropPanel.superclass.initComponent.call(this);
},
onRender : function () {
sitools.admin.datasetView.DatasetViewPropPanel.superclass.onRender.apply(this, arguments);
if (this.action == 'modify') {
var f = this.findByType('form')[0].getForm();
Ext.Ajax.request({
url : this.url,
method : 'GET',
scope : this,
success : function (ret) {
var data = Ext.decode(ret.responseText);
f.setValues(data.datasetView);
var dependencies = data.datasetView.dependencies;
var storeDependencies = this.gridDependencies.getStore();
if (!Ext.isEmpty(dependencies.js)) {
Ext.each(dependencies.js, function (item) {
storeDependencies.add(new Ext.data.Record(item));
}, this);
}
if (!Ext.isEmpty(dependencies.css)) {
Ext.each(dependencies.css, function (item) {
storeDependencies.add(new Ext.data.Record(item));
}, this);
}
},
failure : alertFailure
});
}
},
/**
* Called when ok Button is pressed.
* Send a request (POST or PUT depending on action param) to the server with a definition of a datasetView JSON object.
*/
_onValidate : function () {
var frm = this.findByType('form')[0].getForm();
if (!frm.isValid()) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.invalidForm'));
return;
}
var met = this.action == 'modify' ? 'PUT' : 'POST';
var jsonObject = frm.getFieldValues();
jsonObject.dependencies = {};
jsonObject.dependencies.js = [];
jsonObject.dependencies.css = [];
this.gridDependencies.getStore().each(function (item) {
if (!Ext.isEmpty(item.data.url)) {
if (item.data.url.indexOf(".css") != -1) {
jsonObject.dependencies.css.push({
url : item.data.url
});
}
if (item.data.url.indexOf(".js") != -1) {
jsonObject.dependencies.js.push({
url : item.data.url
});
}
}
});
Ext.Ajax.request({
url : this.url,
method : met,
scope : this,
jsonData : jsonObject,
success : function (ret) {
//load the scripts defined in this component.
// includeJs(frm.items.get('fileUrlId').getValue());
this.store.reload();
this.close();
},
failure : alertFailure
});
},
/**
* Add a new Record to the dependencies property of a project module
*/
onCreateDependencies : function () {
var e = new Ext.data.Record();
this.gridDependencies.getStore().insert(this.gridDependencies.getStore().getCount(), e);
},
/**
* Delete the selected dependency of a project module
*/
onDeleteDependencies : function () {
var s = this.gridDependencies.getSelectionModel().getSelections();
var i, r;
for (i = 0; s[i]; i++) {
r = s[i];
this.gridDependencies.getStore().remove(r);
}
}
});
Ext.reg('s-datasetViewprop', sitools.admin.datasetView.DatasetViewPropPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.admin.rssFeed');
* Generic component to create RssFeed Can be used for DataSets, Projects or
* archive Parameters :
*
* @cfg : url , the url to get the list of DataSets, Projects or archive
* @cfg : label , the label to display ( Select DataSet ... )
* @cfg : urlRef , the relative url of the RSS API
* @class sitools.admin.rssFeed.rssFeedCrud
* @extends Ext.grid.GridPanel
*/
//sitools.component.rssFeedCrud = Ext.extend(Ext.grid.GridPanel, {
sitools.admin.rssFeed.rssFeedCrud = Ext.extend(Ext.grid.GridPanel, {
border : false,
pageSize : 10,
modify : false,
forceFit : "true",
initComponent : function () {
this.httpProxyRss = new Ext.data.HttpProxy({
url : "/tmp",
restful : true,
method : 'GET'
});
this.store = new Ext.data.JsonStore({
idProperty : 'id',
root : 'data',
proxy : this.httpProxyRss,
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'title',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'link',
type : 'string'
}, {
name : 'feedType',
type : 'string'
}, {
name : 'feedSource',
type : 'string'
}, {
name : 'name',
type : 'string'
} ]
});
var storeCombo = new Ext.data.JsonStore({
fields : [ 'id', 'name' ],
url : this.url,
root : "data",
autoLoad : true
});
this.combobox = new Ext.form.ComboBox({
store : storeCombo,
displayField : 'name',
valueField : 'id',
typeAhead : true,
mode : 'local',
forceSelection : true,
triggerAction : 'all',
emptyText : this.label,
selectOnFocus : true,
listeners : {
scope : this,
select : function (combo, rec, index) {
this.dataId = rec.data.id;
this.getTopToolbar().findById("s-filter").enable();
this.loadRss();
}
}
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100
}, {
header : i18n.get('label.titleRss'),
dataIndex : 'title',
width : 150
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 200
}, {
header : i18n.get('label.linkTitle'),
dataIndex : 'link',
width : 200
}, {
header : i18n.get('headers.type'),
dataIndex : 'feedType',
width : 50
}, {
header : i18n.get('headers.feedSource'),
dataIndex : 'feedSource',
width : 100
} ]
});
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ this.combobox, {
text : i18n.get('label.add'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreate,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this.onModify,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDelete,
xtype : 's-menuButton'
}, '->', {
xtype : 's-filter',
emptyText : i18n.get('label.search'),
store : this.store,
pageSize : this.pageSize,
disabled : true,
id : "s-filter"
} ]
};
this.bbar = {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
};
this.listeners = {
scope : this,
rowDblClick : this.onModify
};
sitools.admin.rssFeed.rssFeedCrud.superclass.initComponent.call(this);
},
* Load the rss feeds of the selected dataset in the comboBox
*/
loadRss : function () {
var urlRss = this.url + "/" + this.dataId + this.urlRef;
this.httpProxyRss.setUrl(urlRss, true);
this.getStore().load({
scope : this,
callback : function () {
this.getView().refresh();
}
});
},
* Open a {sitools.admin.rssFeed.rssFeedProps} rss property window
* to create a new rss feed for the selected dataset
*/
onCreate : function () {
if (Ext.isEmpty(this.combobox.getValue())) {
return;
}
var up = new sitools.admin.rssFeed.rssFeedProps({
action : 'create',
store : this.store,
id : this.dataId,
url : this.url,
urlRef : this.urlRef
});
up.show();
},
* Open a {sitools.admin.rssFeed.rssFeedProps} rss property window
* to modify an existing rss feed
*/
onModify : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.admin.rssFeed.rssFeedProps({
action : 'modify',
store : this.store,
id : this.dataId,
url : this.url,
urlRef : this.urlRef,
idFeed : rec.data.id
});
up.show();
},
* Diplay confirm delete Msg box and call the method doDelete
*/
onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return false;
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('feedCrud.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec);
}
}
});
},
* done the delete of the passed record
* @param rec the record to delete
*/
doDelete : function (rec) {
Ext.Ajax.request({
url : this.url + "/" + this.dataId + this.urlRef + "/" + rec.data.id,
method : 'DELETE',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
}
});
Ext.reg('s-rssFeedCrud', sitools.admin.rssFeed.rssFeedCrud);
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.admin.rssFeed');
* A Panel to show the rss properties
*
* @cfg url, the url where the Rss API is attached
* @cfg urlRef, the relative url of the RSS API
* @cfg id, the id of the DataSet, Project or Archive
* @cfg store, the CRUD store
* @cfg action, the type of action ( create or modify )
* @cfg idFeed, the id of the Feed to load in case of edit ( optional )
* @class sitools.admin.rssFeed.rssFeedProps
* @extends Ext.Window
*/
//sitools.component.rssFeedProps = Ext.extend(Ext.Window, {
sitools.admin.rssFeed.rssFeedProps = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
resizable : false,
stateful : false,
urlValid : false,
initComponent : function () {
this.crudStore = this.store;
* *********************************************** TAB1 FORMULAIRE
* ***********************************************
*/
this.buttonValidUrl = new Ext.Button({
text : i18n.get('label.validateUrl'),
scope : this,
handler : function () {
this.validateUrl();
},
width : 150,
iconCls : "img-help",
iconAlign : "left"
});
this.boxComponent = new Ext.BoxComponent({
hidden : true,
labelSeparator : "",
fieldLabel : " ",
id : "boxComponentValid",
cls : "sitools-form-valid-msg",
setHtml : function (html) {
var el = this.getEl();
el.update(html);
}
});
this.formPanel = new Ext.FormPanel({
labelWidth : 100, // label settings here cascade unless overridden
defaultType : 'textfield',
padding : 10,
height : 165,
title : i18n.get("title.feedDetails"),
trackResetOnLoad : true,
items : [{
xtype : 'fieldset',
title : i18n.get('title.feedDetailsCommon'),
autoHeight : true,
defaultType : 'textfield',
items : [{
name : 'id',
xtype : 'hidden'
}, {
fieldLabel : i18n.get('label.name'),
name : 'name',
anchor : '100%',
allowBlank : false
}, {
fieldLabel : i18n.get('label.feedSource'),
name : 'feedSource',
xtype : 'radiogroup',
columns : 1,
items : [ {
boxLabel : 'CLASSIC',
name : 'feedSource',
inputValue : "CLASSIC",
checked : true
}, {
boxLabel : 'EXTERNAL',
name : 'feedSource',
inputValue : "EXTERNAL"
} ],
listeners : {
scope : this,
change : function (radioGroup, radioChecked) {
var name = radioChecked.getGroupValue();
this.toogleSpecificForm(name);
if (name == "CLASSIC") {
this.gridPanel.setDisabled(false);
} else {
this.gridPanel.setDisabled(true);
}
this.doLayout();
}
}
}]
}, {
xtype : 'fieldset',
title : i18n.get('title.feedDetailsSpecific'),
autoHeight : true,
defaultType : 'textfield',
items : [{
fieldLabel : i18n.get('label.titleRss'),
name : 'title',
anchor : '100%'
}, {
fieldLabel : i18n.get('label.description'),
name : 'description',
anchor : '100%'
}, {
fieldLabel : i18n.get('label.linkTitle'),
name : 'link',
anchor : '100%'
}, {
fieldLabel : i18n.get('label.authorName'),
name : 'authorName',
anchor : '100%'
}, {
fieldLabel : i18n.get('label.authorEmail'),
name : 'authorEmail',
anchor : '100%'
}, {
fieldLabel : i18n.get('label.feedType'),
name : 'feedType',
xtype : 'radiogroup',
columns : 1,
items : [ {
boxLabel : 'RSS',
name : 'feedType',
inputValue : "rss_2.0",
checked : true
}, {
boxLabel : 'ATOM',
name : 'feedType',
inputValue : "atom_1.0"
} ]
}, {
xtype: 'compositefield',
anchor : "100%",
fieldLabel : i18n.get('label.url'),
msgTarget: 'under',
hidden : true,
id : 'compositeFieldExternalUrl',
items: [{
name : 'externalUrl',
xtype: 'textfield',
anchor : "100%",
flex : 1,
status : "pending",
allowBlank : "false",
vtype : "uri",
validator : function (value) {
var status = this.status;
if (status == "invalid") {
return this.invalidText;
} else {
return true;
}
},
listeners : {
scope : this,
change : function (textField, newValue, oldValue) {
textField.fireEvent("changeStatus", textField, "pending");
},
changeStatus : function (textField, status, errorMessage) {
textField.status = status;
textField.clearInvalid();
var imgClass;
switch (status) {
case "pending":
imgClass = "img-help";
this.boxComponent.setVisible(false);
break;
case "valid":
imgClass = "img-valid";
break;
case "invalid":
this.boxComponent.setVisible(false);
imgClass = "img-error";
if (Ext.isEmpty(errorMessage)) {
textField.markInvalid();
} else {
textField.markInvalid(errorMessage);
textField.invalidText = errorMessage;
}
break;
default :
this.boxComponent.setVisible(false);
imgClass = "img-error";
break;
}
this.buttonValidUrl.setIconClass(imgClass);
}
}
}, this.buttonValidUrl
]
}, this.boxComponent
]
}]
});
* *********************************************** TAB2 GRID LIST ITEMS
* ***********************************************
*/
this.storeItem = new Ext.data.JsonStore({
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'title',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'link',
type : 'string'
}, {
name : 'pubDate',
type : 'date'
} /*
* ,{ name : 'guid', type :'guid' }
*/
]
});
var cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.titleRss'),
dataIndex : 'title',
width : 150,
sortable : true
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 200,
sortable : false
}, {
header : i18n.get('label.linkTitle'),
dataIndex : 'link',
width : 200,
sortable : false
}, {
header : i18n.get('label.updatedDate'),
dataIndex : 'updatedDate',
width : 100,
sortable : true
} ]
});
var tbar = {
xtype : 'sitools.widget.GridSorterToolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.add'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreate,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this.onModify,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDelete,
xtype : 's-menuButton'
}]
};
this.gridPanel = new Ext.grid.GridPanel({
viewConfig : {
forceFit : true
},
layout : 'fit',
title : i18n.get("title.feedItems"),
store : this.storeItem,
cm : cm,
tbar : tbar
});
* *********************************************** TAB PANEL
* ***********************************************
*/
this.saveButton = new Ext.Button({
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
});
this.tabPanel = new Ext.TabPanel({
height : 450,
activeTab : 0,
items : [ this.formPanel, this.gridPanel ],
buttons : [ this.saveButton, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ]
});
this.items = [ this.tabPanel ];
sitools.admin.rssFeed.rssFeedProps.superclass.initComponent.call(this);
},
* done a specific render to load rss informations.
*/
onRender : function () {
sitools.admin.rssFeed.rssFeedProps.superclass.onRender.apply(this, arguments);
if (this.action == "create") {
this.title = i18n.get("title.createFeed");
} else {
this.title = i18n.get("title.editFeed");
// load data from the server
Ext.Ajax.request({
url : this.url + "/" + this.id + this.urlRef + "/" + this.idFeed,
method : "GET",
scope : this,
success : function (ret) {
// check for the success of the request
var json = Ext.decode(ret.responseText);
if (!json.success) {
Ext.Msg.alert(i18n.get('label.warning'), json.message);
return false;
}
var data = json.FeedModel;
this.populateForm(data);
this.populateStore(data);
if (data.feedSource == "OPENSEARCH") {
this.gridPanel.setDisabled(true);
var feedTypeField = this.formPanel.getForm().findField("feedType");
feedTypeField.setDisabled(true);
} else if (data.feedSource == "EXTERNAL") {
this.gridPanel.setDisabled(true);
var externalUrlField = this.formPanel.getForm().findField("externalUrl");
if (!Ext.isEmpty(externalUrlField.getValue())) {
externalUrlField.fireEvent("changeStatus", externalUrlField, "valid");
}
}
},
failure : alertFailure
});
}
},
* Fill rss fields properties
*
* @param data, the data containing the feed model
*/
populateForm : function (data) {
if (data !== undefined) {
var form = this.formPanel.getForm();
var rec = {};
rec.id = data.id;
rec.name = data.name;
rec.feedType = data.feedType;
rec.feedSource = data.feedSource;
if (data.feedSource == "EXTERNAL") {
rec.externalUrl = data.externalUrl;
} else {
rec.title = data.title;
rec.description = data.description;
rec.link = data.link;
if (data.author !== undefined) {
rec.authorName = data.author.name;
rec.authorEmail = data.author.email;
}
}
var record = new Ext.data.Record(rec);
form.loadRecord(record);
}
},
* Fill the grid store with data
*
* @param data, the data containing the feed model
*/
populateStore : function (data) {
this.storeItem.removeAll();
if (data !== undefined && data.entries !== undefined) {
var i;
for (i = 0; i < data.entries.length; i++) {
var entry = data.entries[i];
var date = new Date(entry.updatedDate);
entry.updatedDate = date;
var rec = new Ext.data.Record(entry);
this.storeItem.add(rec);
}
}
},
* Check rss name property and save all rss properties
*/
onValidate : function () {
// gets the RSS details from the form
var form = this.formPanel.getForm();
if (!form.isValid()) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.invalidForm'));
return;
}
var feedSource = form.findField("feedSource").getValue().inputValue;
var externalUrlField = form.findField("externalUrl");
var externalUrlStatus = externalUrlField.status;
if (feedSource == "EXTERNAL" && ("pending" == externalUrlStatus)) {
this.validateUrl(this.onValidateModify);
}
else if (feedSource == "EXTERNAL" && "invalid" == externalUrlStatus) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.invalidForm'));
return;
}
else {
this.onValidateModify();
}
},
onValidateModify : function () {
var form = this.formPanel.getForm();
if (this.action == 'modify') {
var name = form.findField("name").getValue();
var originalName = form.findField("name").originalValue;
if (originalName != name) {
Ext.Msg.show({
title : i18n.get('label.warning'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('rssFeedProp.warning.feedName.changed'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.onSaveFeed();
}
}
});
} else {
this.onSaveFeed();
}
} else {
this.onSaveFeed();
}
},
* Save rss properties fields
*/
onSaveFeed : function () {
var form = this.formPanel.getForm();
var feedTypeField = form.findField("feedType");
feedTypeField.setDisabled(false);
var json = {};
json.author = {};
Ext.iterate(form.getValues(), function (key, value) {
if (key == "authorName") {
json.author.name = value;
} else if (key == "authorEmail") {
json.author.email = value;
} else {
json[key] = value;
}
}, this);
// // if the id is empty (create) we assign the name to it
// if (Ext.isEmpty(json.id)) {
// json.id = json.name;
// }
// gets the value from the grid
json.entries = [];
if (json.feedSource == "CLASSIC") {
var i;
for (i = 0; i < this.storeItem.getCount(); i++) {
var rec = this.storeItem.getAt(i).copy().data;
var date = rec.updatedDate;
if (date !== null && date !== undefined) {
var updatedDate = new Date(date);
rec.updatedDate = updatedDate.format('Y-m-d\\TH:i:s.u') + updatedDate.getGMTOffset();
}
date = rec.publishedDate;
if (date !== null && date !== undefined) {
var publishedDate = new Date(date);
rec.publishedDate = publishedDate.format('Y-m-d\\TH:i:s.u') + publishedDate.getGMTOffset();
}
json.entries.push(rec);
}
}
var url = this.url + "/" + this.id + this.urlRef;
var method;
if (this.action == "create") {
method = "POST";
} else {
method = "PUT";
url += "/" + this.idFeed;
}
Ext.Ajax.request({
url : url,
method : method,
scope : this,
jsonData : json,
success : function (ret) {
// check for the success of the request
var data = Ext.decode(ret.responseText);
if (!data.success) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get(data.message));
return false;
}
this.store.reload();
this.close();
},
failure : alertFailure
});
},
toogleSpecificForm : function (feedSource) {
var isClassic = (feedSource == "CLASSIC");
var form = this.formPanel.getForm();
form.findField("title").setDisabled(!isClassic);
form.findField("title").setVisible(isClassic);
form.findField("description").setDisabled(!isClassic);
form.findField("description").setVisible(isClassic);
form.findField("link").setDisabled(!isClassic);
form.findField("link").setVisible(isClassic);
form.findField("authorName").setDisabled(!isClassic);
form.findField("authorName").setVisible(isClassic);
form.findField("authorEmail").setDisabled(!isClassic);
form.findField("authorEmail").setVisible(isClassic);
form.findField("authorEmail").setDisabled(!isClassic);
form.findField("authorEmail").setVisible(isClassic);
form.findField("feedType").setVisible(isClassic);
Ext.getCmp('boxComponentValid').setDisabled(isClassic);
Ext.getCmp('boxComponentValid').setVisible(!isClassic);
Ext.getCmp('compositeFieldExternalUrl').setDisabled(isClassic);
Ext.getCmp('compositeFieldExternalUrl').setVisible(!isClassic);
},
* Create a {sitools.admin.rssFeed.rssFeedItemProps} rss item property field
* to create a property
*/
onCreate : function () {
var up = new sitools.admin.rssFeed.rssFeedItemProps({
store : this.storeItem,
parent : this.gridPanel,
action : "create"
});
up.show();
},
* Open a {sitools.admin.rssFeed.rssFeedItemProps} rss item property field
* to modify a property
*/
onModify : function () {
var rec = this.gridPanel.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.admin.rssFeed.rssFeedItemProps({
store : this.storeItem,
parent : this.gridPanel,
action : "modify",
rec : rec
});
up.show();
},
* Delete the selected rss property from the store
*/
onDelete : function () {
var rec = this.gridPanel.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
this.storeItem.remove(rec);
},
validateUrl : function (successCallback) {
var externalUrlField = this.formPanel.getForm().findField("externalUrl");
if (externalUrlField.isValid()) {
var externalUrl = externalUrlField.getValue();
var url = "/sitools/proxy";
this.saveButton.disable();
this.buttonValidUrl.disable();
this.buttonValidUrl.setIconClass("img-loading");
Ext.Ajax.request({
url : url,
method : "GET",
scope : this,
//custom parameters to avoid calling the requestexception event if there is an error
doNotHandleRequestexception : true,
params : {
external_url : externalUrl
},
success : function (ret) {
var responseXML = ret.responseXML;
var isRss = false, isAtom = false;
if (!Ext.isEmpty(responseXML)) {
// isRss = responseXML.firstChild.localName == "rss";
// isAtom = responseXML.firstChild.localName == "feed";
isRss = !Ext.isEmpty(Ext.DomQuery.selectNode("rss", responseXML));
isAtom = !Ext.isEmpty(Ext.DomQuery.selectNode("feed", responseXML));
}
var feedField = this.formPanel.getForm().findField("feedType");
var externalUrlField = this.formPanel.getForm().findField("externalUrl");
if (isRss) {
feedField.setValue("rss_2.0");
} else if (isAtom) {
feedField.setValue("atom_1.0");
}
if (isRss || isAtom) {
this.boxComponent.setHtml(String.format(i18n.get("label.feedTypeDetected"), feedField.getValue().inputValue));
this.boxComponent.setVisible(true);
externalUrlField.fireEvent("changeStatus", externalUrlField, "valid");
if (Ext.isFunction(successCallback)) {
successCallback.call(this);
}
} else {
externalUrlField.fireEvent("changeStatus", externalUrlField, "invalid", i18n.get("label.incompatible.feed.type"));
}
},
failure : function (response, options) {
this.urlValid = false;
var externalUrlField = this.formPanel.getForm().findField("externalUrl");
externalUrlField.fireEvent("changeStatus", externalUrlField, "invalid", i18n.get("label.urlInvalid"));
},
callback : function (options, success, response) {
this.saveButton.enable();
this.buttonValidUrl.enable();
}
});
}
}
});
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp*/
Ext.namespace('sitools.admin.rssFeed');
* Create a new feed item for a specific feed
*
* @param store, the RSS feed store
* @param parent, the grid parent
* @param action, the type of action ( create or modify )
* @param rec, the record to load in case of edit ( optional )
* @class sitools.admin.rssFeed.rssFeedItemProps
* @extends Ext.Window
*/
//sitools.component.rssFeedItemProps = Ext.extend(Ext.Window, {
sitools.admin.rssFeed.rssFeedItemProps = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
resizable : false,
layout : 'fit',
initComponent : function () {
this.title = i18n.get('title.feedItemDetails');
/* paramétres du formulaire */
var itemsForm = [ {
fieldLabel : i18n.get('label.titleRss'),
name : 'title',
anchor : '100%'
}, {
fieldLabel : i18n.get('label.description'),
name : 'description',
anchor : '100%',
xtype : "textarea"
}, {
fieldLabel : i18n.get('label.linkTitle'),
name : 'link',
anchor : '100%'
}, {
xtype : "sitoolsSelectImage",
fieldLabel : i18n.get('label.image'),
name : 'image',
anchor : '100%'
}, {
fieldLabel : i18n.get('label.authorName'),
name : 'name',
anchor : '100%'
}, {
fieldLabel : i18n.get('label.authorEmail'),
name : 'email',
anchor : '100%'
}/*
* , { fieldLabel : i18n.get('label.guid'), name : 'guid', anchor :
* '100%' }
*/, {
xtype : 'compositefield',
fieldLabel : i18n.get('label.updatedDate'),
items : [ {
fieldLabel : i18n.get("label.day"),
name : 'date',
xtype : "datefield"
}, {
name : 'hours',
xtype : 'numberfield',
width : 48,
maxValue : 23,
minValue : 0
}, {
xtype : 'displayfield',
value : i18n.get("label.hours")
}, {
name : 'minutes',
xtype : 'numberfield',
width : 48,
maxValue : 59,
minValue : 0
}, {
xtype : 'displayfield',
value : i18n.get("label.minutes")
}, {
xtype : 'button',
name : 'nowUpdated',
text : i18n.get("label.now"),
width : 50,
flex : 0,
scope : this,
handler : this.nowDate
} ]
}, {
xtype : 'compositefield',
fieldLabel : i18n.get('label.publishedDate'),
items : [ {
fieldLabel : i18n.get("label.day"),
name : 'datePub',
xtype : "datefield",
allowBlank : false
}, {
name : 'hoursPub',
xtype : 'numberfield',
width : 48,
maxValue : 23,
minValue : 0,
allowBlank : false
}, {
xtype : 'displayfield',
value : i18n.get("label.hours")
}, {
name : 'minutesPub',
xtype : 'numberfield',
width : 48,
maxValue : 59,
minValue : 0,
allowBlank : false
}, {
xtype : 'displayfield',
value : i18n.get("label.minutes")
}, {
xtype : 'button',
name : 'nowPublished',
text : i18n.get("label.now"),
width : 50,
flex : 0,
scope : this,
handler : this.nowDate
}]
} ];
this.formPanel = new Ext.FormPanel({
labelWidth : 100, // label settings here cascade unless overridden
defaultType : 'textfield',
items : itemsForm,
border : false,
padding : 10
});
this.items = [ this.formPanel ];
this.buttons = [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ];
sitools.admin.rssFeed.rssFeedItemProps.superclass.initComponent.call(this);
},
* If the "action" is "modify", fill fields with the record data
*/
afterRender : function () {
sitools.admin.rssFeed.rssFeedItemProps.superclass.afterRender.apply(this, arguments);
if (this.action == "modify") {
var form = this.formPanel.getForm();
var record = this.rec.copy();
Ext.data.Record.id(record); // automatically generate a unique
// sequential id
var dateStr = this.rec.get("updatedDate");
var date = new Date(dateStr);
record.set("date", date.format('m/d/Y'));
record.set("hours", date.format('H'));
record.set("minutes", date.format('i'));
var dateStrPub = this.rec.get("publishedDate");
var datePub = new Date(dateStrPub);
record.set("datePub", datePub.format('m/d/Y'));
record.set("hoursPub", datePub.format('H'));
record.set("minutesPub", datePub.format('i'));
var author = record.get("author");
if (!Ext.isEmpty(author)) {
record.set('name', author.name);
record.set('email', author.email);
}
if (!Ext.isEmpty(record.get('image'))) {
record.set("image", record.get('image').url);
}
form.loadRecord(record);
}
},
* Save dates fields
*/
onValidate : function () {
var frm = this.findByType('form')[0].getForm();
if (!frm.isValid()) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.invalidForm'));
return;
}
var rec;
if (this.action == "create") {
rec = new Ext.data.Record();
} else {
rec = this.rec;
}
// store the form fields
var form = this.formPanel.getForm();
if (!form.isValid()) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.invalidForm'));
return false;
}
var mins = null;
var hours = null;
var dateStr = null;
var minsPub = null;
var hoursPub = null;
var dateStrPub = null;
var author = {};
rec.set("author", author);
Ext.iterate(form.getValues(), function (key, value) {
if (key == "date") {
dateStr = value;
} else if (key == "hours") {
hours = value;
} else if (key == "minutes") {
mins = value;
} else if (key == "datePub") {
dateStrPub = value;
} else if (key == "hoursPub") {
hoursPub = value;
} else if (key == "minutesPub") {
minsPub = value;
} else if (key == "name" || key == "email") {
author[key] = value;
} else if (key == "image") {
if (! Ext.isEmpty(value)) {
var type = this.getTypeFromUrl(value);
rec.set(key, {
url : value,
type : type
});
}
} else {
rec.set(key, value);
}
}, this);
var date;
if (dateStr !== null && dateStr !== "") {
if (hours !== null && mins !== null) {
dateStr += " " + hours + ":" + mins;
}
date = new Date(dateStr);
rec.set("updatedDate", date);
}
if (dateStrPub !== null && dateStrPub !== "") {
if (hoursPub !== null && hoursPub !== "" && minsPub !== null && minsPub !== "") {
dateStrPub += " " + hoursPub + ":" + minsPub;
}
date = new Date(dateStrPub);
rec.set("publishedDate", date);
}
if (this.action == "create") {
this.store.add(rec);
}
this.parent.getView().refresh();
this.close();
},
* Set dates fields with date of the current day
* @param button, the button clic
* @param e, the event click
*/
nowDate : function (button, e) {
var date = new Date(), form, record;
if (button.name == "nowUpdated") {
form = this.formPanel.getForm();
record = new Ext.data.Record(form.getValues());
record.set("date", date.format('m/d/Y'));
record.set("hours", date.format('H'));
record.set("minutes", date.format('i'));
form.loadRecord(record);
}
if (button.name == "nowPublished") {
form = this.formPanel.getForm();
record = new Ext.data.Record(form.getValues());
record.set("datePub", date.format('m/d/Y'));
record.set("hoursPub", date.format('H'));
record.set("minutesPub", date.format('i'));
form.loadRecord(record);
}
},
* Get the image extension from the url
* @param url, the image url
*/
getTypeFromUrl : function (url) {
var tmp = url.split(".");
var type = tmp[tmp.length - 1];
switch (type.toLowerCase()) {
case "jpg" :
case "jpeg" :
case "jpe" :
type = "image/jpeg";
break;
case "gif" :
case "man" :
type = "image/gif";
break;
case "png" :
type = "image/png";
break;
case "tif" :
case "tiff" :
type = "image/tiff";
break;
case "pbm" :
type = "image/x-portable-bitmap";
break;
case "pgm" :
type = "image/x-portable-graymap";
break;
case "ppm" :
type = "image/x-portable-pixmap";
break;
default :
type = null;
}
return type;
}
});
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.component.projects');
sitools.component.projects.rssFeedProject = Ext.extend(Ext.Panel, {
border : false,
height : 300,
id : ID.BOX.RSSPROJECT,
layout : 'fit',
initComponent : function () {
var rssFeedCRUD = new sitools.admin.rssFeed.rssFeedCrud({
url : loadUrl.get('APP_URL') + loadUrl.get('APP_PROJECTS_URL'),
label : i18n.get("label.selectProject"),
urlRef : loadUrl.get('APP_FEEDS_URL')
});
this.items = [ rssFeedCRUD ];
sitools.component.projects.rssFeedProject.superclass.initComponent.call(this);
}
});
Ext.reg('s-rssFeedProjects', sitools.component.projects.rssFeedProject);
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.admin.datasets');
* A simple panel with an {@link sitools.admin.rssFeed.rssFeedCrud} component
* @class sitools.admin.datasets.rssFeedDatasets
* @extends Ext.Panel
*/
sitools.admin.datasets.rssFeedDatasets = Ext.extend(Ext.Panel, {
//sitools.component.datasets.rssFeedDatasets = Ext.extend(Ext.Panel, {
border : false,
height : 300,
id : ID.BOX.RSSPROJECT,
layout : 'fit',
initComponent : function () {
var rssFeedCRUD = new sitools.admin.rssFeed.rssFeedCrud({
url : loadUrl.get('APP_URL') + loadUrl.get('APP_DATASETS_URL'),
label : i18n.get("label.selectDatasets"),
urlRef : loadUrl.get('APP_FEEDS_URL')
});
this.items = [ rssFeedCRUD ];
sitools.admin.datasets.rssFeedDatasets.superclass.initComponent.call(this);
}
});
Ext.reg('s-rssFeedDatasets', sitools.admin.datasets.rssFeedDatasets);
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.component.portal');
sitools.component.portal.rssFeedPortalCrud = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.RSSPORTAL,
pageSize : 10,
label : i18n.get("label.selectPortal"),
forceFit : "true",
initComponent : function () {
this.url = loadUrl.get('APP_URL') + loadUrl.get('APP_PORTAL_URL');
this.urlRef = loadUrl.get('APP_FEEDS_URL');
this.httpProxyRss = new Ext.data.HttpProxy({
url : "/tmp",
restful : true,
method : 'GET'
});
this.store = new Ext.data.JsonStore({
idProperty : 'id',
root : 'data',
proxy : this.httpProxyRss,
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'title',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'link',
type : 'string'
}, {
name : 'feedType',
type : 'string'
}, {
name : 'visible',
type : 'boolean'
}, {
name : 'feedSource',
type : 'string'
}, {
name : 'externalUrl',
type : 'string'
} ]
});
// var storeCombo = new Ext.data.JsonStore({
// fields : [ 'id', 'name' ],
// url : this.url,
// root : "data",
// autoLoad : true
// });
//
// this.combobox = new Ext.form.ComboBox({
// store : storeCombo,
// displayField : 'name',
// valueField : 'id',
// typeAhead : true,
// mode : 'local',
// forceSelection : true,
// triggerAction : 'all',
// emptyText : this.label,
// selectOnFocus : true,
// listeners : {
// scope : this,
// select : function(combo, rec, index) {
// this.dataId = rec.data.id;
//
// this.loadRss();
//
// }
//
// }
// });
// colonne avec checkbox pour choisir quelle colonne est la clé primaire
var visible = new Ext.grid.CheckColumn({
header : i18n.get('headers.visible'),
dataIndex : 'visible',
width : 80
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
},
columns : [ {
header : i18n.get('label.titleRss'),
dataIndex : 'title',
width : 150
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 150
}, {
header : i18n.get('label.url'),
dataIndex : 'externalUrl',
width : 150
}, {
header : i18n.get('headers.type'),
dataIndex : 'feedType',
width : 50
}, visible, {
header : i18n.get('headers.feedSource'),
dataIndex : 'feedSource',
width : 100
} ]
});
// définition des plugins nécessaires (colonnes avec checkbox )
this.plugins = [ visible ];
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.save'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/save.png',
handler : this.onSave,
xtype : 's-menuButton'
}, '->', {
xtype : 's-filter',
emptyText : i18n.get('label.search'),
store : this.store,
pageSize : this.pageSize
} ]
};
this.dataId = "idPortal";
this.loadRss();
sitools.component.portal.rssFeedPortalCrud.superclass.initComponent.call(this);
},
loadRss : function () {
var urlRss = this.url + "/" + this.dataId + this.urlRef;
this.httpProxyRss.setUrl(urlRss, true);
this.getStore().load({
scope : this,
callback : function () {
this.getView().refresh();
}
});
},
onSave : function () {
var json = {};
json.feeds = [];
var i;
for (i = 0; i < this.store.getCount(); i++) {
var rec = this.store.getAt(i).data;
json.feeds.push(rec);
}
var url = this.url + "/" + this.dataId + this.urlRef;
Ext.Ajax.request({
url : url,
method : "PUT",
scope : this,
jsonData : json,
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (!data.success) {
Ext.Msg.alert(i18n.get('label.warning'), data.message);
return false;
}
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('label.feedsSaved'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
this.store.load();
}
});
}
});
Ext.reg('s-rssFeedPortal', sitools.component.portal.rssFeedPortalCrud);
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, loadUrl*/
/*
* @include "applicationPluginProp.js"
* @include "../../id.js"
*/
Ext.namespace('sitools.admin.applications.plugins');
/**
* @class sitools.admin.applications.plugins.ApplicationPluginCrudPanel
* @extends Ext.grid.GridPanel
*/
//sitools.component.applicationPlugin.applicationPluginCrudPanel = Ext.extend(Ext.grid.GridPanel, {
sitools.admin.applications.plugins.ApplicationPluginCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.APPLICATIONPLUGIN,
pageSize : 10,
modify : false,
urlGrid : null,
// Warning for version conflicts
conflictWarned : false,
viewConfig : {
forceFit : true,
autoFill : true,
getRowClass : function (row, index) {
var cls = '';
var data = row.data;
if (data.classVersion !== data.currentClassVersion
&& data.currentClassVersion !== null
&& data.currentClassVersion !== undefined) {
if (!this.conflictWarned) {
Ext.Msg.alert("warning.version.conflict", "Application plugin "
+ data.name
+ "definition (v"
+ data.classVersion
+ ") may conflict with current class version : "
+ data.currentClassVersion);
this.conflictWarned = true;
}
cls = "red-row";
}
return cls;
}
},
initComponent : function () {
this.urlAdmin = loadUrl.get('APP_URL') + loadUrl.get('APP_PLUGINS_APPLICATIONS_URL') + '/instances';
this.urlList = loadUrl.get('APP_URL') + loadUrl.get('APP_PLUGINS_APPLICATIONS_URL') + '/classes';
this.httpProxyForms = new Ext.data.HttpProxy({
url : this.urlAdmin,
restful : true,
method : 'GET'
});
this.store = new Ext.data.JsonStore({
idProperty : 'id',
root : "data",
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'className',
type : 'string'
}, {
name : 'status',
type : 'string'
}, {
name : 'label',
type : 'string'
}, {
name : 'urlAttach',
type : 'string'
}, {
name : 'classVersion',
type : 'string'
}, {
name : 'classAuthor',
type : 'string'
}, {
name : 'currentClassVersion',
type : 'string'
}, {
name : 'currentClassAuthor',
type : 'string'
},
{
name : 'classOwner',
type : 'string'
}],
proxy : this.httpProxyForms
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 150
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 200,
sortable : false
}, {
header : i18n.get('label.label'),
dataIndex : 'label',
width : 100,
sortable : false
}, {
header : i18n.get('label.urlAttach'),
dataIndex : 'urlAttach',
width : 100,
sortable : false
}, {
header : i18n.get('label.status'),
dataIndex : 'status',
width : 100,
sortable : false
}, {
header : i18n.get('label.className'),
dataIndex : 'className',
width : 150,
sortable : false
}, {
header : i18n.get('label.classVersion'),
dataIndex : 'classVersion',
width : 50,
sortable : false
}, {
header : i18n.get('label.currentClassVersion'),
dataIndex : 'currentClassVersion',
width : 50,
sortable : false
}, {
header : i18n.get('label.classAuthor'),
dataIndex : 'classAuthor',
width : 100,
sortable : false
},
{
header : i18n.get('label.classOwner'),
dataIndex : 'classOwner',
width : 100,
sortable : false
}]
});
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.add'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreate,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this.onModify,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDelete,
xtype : 's-menuButton'
}, {
text : i18n.get('label.active'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_active.png',
handler : this._onActive,
xtype : 's-menuButton'
}, {
text : i18n.get('label.disactive'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_disactive.png',
handler : this._onDisactive,
xtype : 's-menuButton'
} ]
};
this.bbar = {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
};
this.listeners = {
scope : this,
rowDblClick : this.onModify
};
sitools.admin.applications.plugins.ApplicationPluginCrudPanel.superclass.initComponent.call(this);
},
/**
* Load the Store on render event
*/
onRender : function () {
sitools.admin.applications.plugins.ApplicationPluginCrudPanel.superclass.onRender.apply(this, arguments);
this.store.load({
params : {
start : 0,
limit : this.pageSize
}
});
},
/**
* Open a {sitools.admin.applications.plugins.applicationPluginProp} window
* to create a new Application plugin
*/
onCreate : function () {
var up = new sitools.admin.applications.plugins.applicationPluginProp({
action : 'create',
parent : this,
urlList : this.urlList,
urlAdmin : this.urlAdmin
});
up.show();
},
/**
* Open a {sitools.admin.applications.plugins.applicationPluginProp} window
* to edit an Application plugin
*/
onModify : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
if ("ACTIVE" === rec.data.status) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.wrongStatus'));
return;
}
var up = new sitools.admin.applications.plugins.applicationPluginProp({
action : 'modify',
record : rec,
parent : this,
urlList : this.urlList,
urlAdmin : this.urlAdmin
});
up.show();
},
/**
* Open a confirmation window before deleting selected record
*/
onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('applicationPluginCrud.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec);
}
}
});
},
/**
* Call the delete method
*/
doDelete : function (rec) {
Ext.Ajax.request({
url : this.urlAdmin + "/" + rec.id,
method : 'DELETE',
scope : this,
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
/**
* Call the resource start on the application
*/
_onActive : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.urlAdmin + "/" + rec.id + "/start",
method : 'PUT',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
/**
* Call the resource stop on the application
*/
_onDisactive : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.urlAdmin + "/" + rec.id + "/stop",
method : 'PUT',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
}
});
Ext.reg('s-Application_plugins', sitools.admin.applications.plugins.ApplicationPluginCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, ImageChooser*/
Ext.namespace('sitools.admin.applications.plugins');
/**
* A Window to define application plugin properties.
* @cfg {string} action Should be create or modify
* @cfg {} parent The componennt caller
* @cfg {string} urlList the url of application plugins
* @cfg {string} urlAdmin
* @class sitools.admin.applications.plugins.applicationPluginProp
* @extends Ext.Window
*/
//sitools.component.applicationPlugin.applicationPluginProp = Ext.extend(Ext.Window, {
sitools.admin.applications.plugins.applicationPluginProp = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
resizable : true,
classChosen : "",
applicationPluginId : null,
initComponent : function () {
this.title = this.action == "create" ? i18n.get('label.createApplicationPlugin') : i18n.get('label.modifyApplicationPlugin');
this.crudStore = this.store;
var expander = new Ext.ux.grid.RowExpander({
tpl : new Ext.XTemplate(
'<tpl if="this.descEmpty(description)" ><div></div></tpl>',
'<tpl if="this.descEmpty(description) == false" ><div class="sitoolsDescription"><div class="sitoolsDescriptionHeader">Description : </div><p class="sitoolsDescriptionText"> {description} </p></div></tpl>',
{
compiled : true,
descEmpty : function (description) {
return Ext.isEmpty(description);
}
}),
expandOnDblClick : true
});
this.gridapplicationPlugin = new Ext.grid.GridPanel({
viewConfig : {
forceFit : true
},
id : 'gridapplicationPlugin',
title : i18n.get('title.applicationPluginClass'),
store : new Ext.data.JsonStore({
root : 'data',
restful : true,
proxy : new Ext.data.HttpProxy({
url : this.urlList,
restful : true,
method : 'GET'
}),
remoteSort : false,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'className',
type : 'string'
}, {
name : 'classAuthor',
type : 'string'
}, {
name : 'classOwner',
type : 'string'
}, {
name : 'classVersion',
type : 'string'
}, {
name : 'classOwner',
type : 'string'
}, {
name : 'violation'
} ],
autoLoad : true
}),
cm : new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ expander, {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100,
sortable : true
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 300,
sortable : true
}, {
header : i18n.get('label.className'),
dataIndex : 'className',
width : 300,
sortable : true
}, {
header : i18n.get('label.author'),
dataIndex : 'classAuthor',
width : 100,
sortable : true
}, {
header : i18n.get('label.classOwner'),
dataIndex : 'classOwner',
width : 100,
sortable : false
}, {
header : i18n.get('label.version'),
dataIndex : 'classVersion',
width : 100,
sortable : true
} ]
}),
bbar : new Ext.ux.StatusBar({
id: 'statusBar',
hidden : true,
iconCls: 'x-status-error',
text : i18n.get("label.filterErrorValidationNotification")
}),
listeners : {
scope : this,
rowclick : this.onClassClick
},
plugins : expander
});
this.fieldMappingFormPanel = new Ext.FormPanel({
padding : 10,
id : 'fieldMappingFormPanel',
defaultType : 'textfield',
title : i18n.get('title.applicationPluginDetails'),
items : [ {
fieldLabel : i18n.get('label.label'),
name : 'label',
anchor : '100%'
}, {
fieldLabel : i18n.get('label.userAttach'),
name : 'urlAttach',
anchor : '100%',
vtype : "attachment",
allowBlank: false
} ]
});
this.proxyFieldMapping = new Ext.data.HttpProxy({
url : '/tmp',
restful : true,
method : 'GET'
});
this.gridFieldMapping = new Ext.grid.EditorGridPanel({
viewConfig : {
forceFit : true,
scope : this,
getRowClass : function (record, index, rowParams, store) {
var cls = '';
var violation = record.get("violation");
if (!Ext.isEmpty(violation)) {
if (violation.level == "CRITICAL") {
cls = "red-row";
} else if (violation.level == "WARNING") {
cls = "orange-row";
}
}
return cls;
},
listeners : {
scope : this,
refresh : function (view) {
var grid = this.gridFieldMapping;
var store = grid.getStore();
store.each(function (record) {
var violation = record.get("violation");
if (!Ext.isEmpty(violation)) {
var index = store.indexOf(record);
//var view = this.scope.gridFieldMapping.getView();
var htmlLineEl = view.getRow(index);
var el = Ext.get(htmlLineEl);
var cls = (violation.level == "CRITICAL")
? "x-form-invalid-tip"
: "x-form-invalid-tip x-form-warning-tip";
var ttConfig = {
html : violation.message,
dismissDelay : 0,
target : el,
cls : cls
};
var ttip = new Ext.ToolTip(ttConfig);
}
});
}
}
},
id : 'gridFieldMapping',
layout : 'fit',
title : i18n.get('title.parametersMapping'),
store : new Ext.data.JsonStore({
root : 'ApplicationPlugin.model.parameters',
proxy : this.proxyFieldMapping,
restful : true,
remoteSort : false,
idProperty : 'name',
fields : [ {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'value',
type : 'string'
}, {
name : 'valueType',
type : 'string'
} ]
}),
bbar : new Ext.ux.StatusBar({
id: 'statusBar',
hidden : true,
iconCls: 'x-status-error',
text : i18n.get("label.applicationPluginErrorValidationNotification")
}),
cm : new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100,
sortable : true
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 200,
sortable : false
}, {
header : i18n.get('label.value'),
dataIndex : 'value',
width : 100,
sortable : false,
editable : true,
editor : new Ext.form.TextField()
} ]
}),
listeners : {
scope : this,
celldblclick : function (grid, rowIndex, columnIndex, e) {
var storeRecord = grid.getStore().getAt(rowIndex);
var rec = storeRecord.data;
if (grid.getColumnModel().getColumnHeader(columnIndex) == "Value") {
if (rec.valueType == "xs:dictionary") {
var selectDictionaryWin = new sitools.component.dictionary.selectDictionary({
field : "value",
record : storeRecord,
parentStore : this.gridFieldMapping.getStore(),
parentView : this.gridFieldMapping.getView(),
url : loadUrl.get("APP_URL") + loadUrl.get("APP_DICTIONARIES_URL")
});
selectDictionaryWin.show(ID.BOX.DATASETS);
}
else if (rec.valueType == "xs:boolean") {
var selectBooleanWin = new sitools.admin.resourcesPlugins.enumerationValueTypeSelector({
field : "value",
record : storeRecord,
parentView : this.gridFieldMapping.getView(),
type : rec.name,
enumeration : "[true,false]",
value : rec.value
});
selectBooleanWin.show(ID.BOX.DATASETS);
}
else if (rec.valueType == "xs:image") {
// console.dir (this);
var chooser = new ImageChooser({
url : loadUrl.get('APP_URL') + loadUrl.get('APP_UPLOAD_URL') + '/?media=json',
width : 515,
height : 450,
field : "value",
parentView : this.gridFieldMapping.getView(),
record : storeRecord
});
chooser.show(document, function (data, config) {
config.record.data[config.field] = data.url;
config.parentView.refresh();
});
}
else if (rec.valueType.indexOf("xs:enum") != -1) {
var enumType;
if (rec.valueType.indexOf("xs:enum-editable-multiple") != -1) {
enumType = "EEM";
}
else if (rec.valueType.indexOf("xs:enum-editable") != -1) {
enumType = "EE";
}
else if (rec.valueType.indexOf("xs:enum-multiple") != -1) {
enumType = "EM";
}
else {
enumType = "E";
}
var selectEnumWin = new sitools.admin.resourcesPlugins.enumerationValueTypeSelector({
enumType : enumType,
field : "value",
fieldEnum : "valueType",
record : storeRecord,
parentView : this.gridFieldMapping.getView(),
type : rec.name,
enumeration : rec.valueType,
value : rec.value
});
selectEnumWin.show(ID.BOX.DATASETS);
}
} else {
return false;
}
}
}
});
this.tabPanel = new Ext.TabPanel({
activeTab : 0,
items : (this.action == "create") ? [ this.gridapplicationPlugin, this.fieldMappingFormPanel, this.gridFieldMapping ] : [
this.fieldMappingFormPanel, this.gridFieldMapping
],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ],
listeners : {
scope : this,
beforetabchange : this.beforeTabChange
}
});
this.listeners = {
scope : this,
resize : function (window, width, height) {
var size = window.body.getSize();
this.tabPanel.setSize(size);
}
};
this.items = [ this.tabPanel ];
sitools.admin.applications.plugins.applicationPluginProp.superclass.initComponent.call(this);
},
/**
* Method called on main tabPanel beforeTabChange event
* @param {Ext.TabPanel} self main Tab Panel
* @param {Ext.Panel} newTab new Tab
* @param {Ext.Panel} currentTab current Tab
* @return {Boolean}
*/
beforeTabChange : function (self, newTab, currentTab) {
if (this.action == "create") {
if (newTab.id == "fieldMappingFormPanel" || newTab.id == "gridFieldMapping") {
var rec = this.gridapplicationPlugin.getSelectionModel().getSelected();
if (!rec) {
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('warning.noselection'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
return false;
}
}
}
},
/**
* Method called on grid click
* @param {} self
* @param {} rowIndex
* @param {} e
* @return {Boolean}
*/
onClassClick : function (self, rowIndex, e) {
if (this.action == "create") {
var rec = this.gridapplicationPlugin.getSelectionModel().getSelected();
if (!rec) {
return false;
}
var className = rec.data.className;
if (className != this.classChosen) {
this.proxyFieldMapping.setUrl(this.urlList + "/"
+ className);
var store = this.gridFieldMapping.getStore();
this.classChosen = className;
store.removeAll();
store.load();
}
}
},
/**
* Requests the selected plugin Application properties
*/
afterRender : function () {
sitools.admin.applications.plugins.applicationPluginProp.superclass.afterRender.apply(this, arguments);
if (this.action == "modify") {
this.applicationPluginId = this.record.data.id;
Ext.Ajax.request({
url : this.urlAdmin + "/" + this.applicationPluginId,
method : 'GET',
scope : this,
success : function (ret) {
var json = Ext.decode(ret.responseText);
if (!json.success) {
Ext.Msg.alert(i18n.get('label.warning'), json.message);
return false;
}
this.fillFormAndGrid(json.ApplicationPluginModel);
},
failure : alertFailure
});
}
},
/**
* Fill the properties from the requested object.
* @param {} applicationPlugin
*/
fillFormAndGrid : function (applicationPlugin) {
var form = this.fieldMappingFormPanel.getForm();
if (!Ext.isEmpty(applicationPlugin)) {
var rec = {};
rec.label = applicationPlugin.label;
rec.urlAttach = applicationPlugin.urlAttach;
form.loadRecord(new Ext.data.Record(rec));
var parameters = applicationPlugin.parameters;
if (!Ext.isEmpty(parameters)) {
var store = this.gridFieldMapping.getStore();
for (var i = 0; i < parameters.length; i++) {
var recTmp = new Ext.data.Record(parameters[i]);
store.add(recTmp);
}
}
}
},
/**
* Called on save Button : Validate fields and send POST or PUT request depending on action
* @return {Boolean}
*/
onValidate : function () {
var rec;
var jsonReturn = {};
if (this.action == "create") {
rec = this.gridapplicationPlugin.getSelectionModel().getSelected();
if (!rec) {
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('warning.noselection'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
return false;
}
jsonReturn.name = rec.data.name;
jsonReturn.description = rec.data.description;
}
var form = this.fieldMappingFormPanel.getForm();
if (!form.isValid()) {
var temp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('warning.invalidForm'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
return false;
}
Ext.iterate(form.getFieldValues(), function (key, value) {
jsonReturn[key] = value;
});
var parameters = [];
var applicationPlugin;
if (this.action == "create") {
rec = this.gridapplicationPlugin.getSelectionModel().getSelected();
applicationPlugin = rec.data;
// jsonReturn.name = applicationPlugin.name;
// jsonReturn.description = applicationPlugin.description;
} else {
applicationPlugin = this.record.data;
jsonReturn.id = this.applicationPluginId;
// jsonReturn.status = applicationPlugin.status;
}
jsonReturn.className = applicationPlugin.className;
jsonReturn.classVersion = applicationPlugin.classVersion;
jsonReturn.classAuthor = applicationPlugin.classAuthor;
jsonReturn.classOwner = applicationPlugin.classOwner;
var storeField = this.gridFieldMapping.getStore();
for (var i = 0; i < storeField.getCount(); i++) {
var recTmp = storeField.getAt(i).data;
recTmp.violation = undefined;
parameters.push(recTmp);
}
jsonReturn.parameters = parameters;
// var rec2 = new Ext.data.Record(jsonReturn);
// if (this.action == "create") {
// this.crudStore.add(rec2);
//
// } else {
// var record = this.crudStore.getAt(this.index);
// record.set("parameters", parameters);
// record.set("descriptionAction", jsonReturn.descriptionAction);
// }
var url = this.urlAdmin, method;
if (this.action == "modify") {
url += "/" + this.applicationPluginId;
method = "PUT";
} else {
method = "POST";
}
Ext.Ajax.request({
url : url,
method : method,
scope : this,
jsonData : jsonReturn,
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (!data.success) {
if (Ext.isEmpty(data.message)) {
var violations = data.data;
this.notifyViolations(violations);
Ext.getCmp("statusBar").show();
} else {
Ext.Msg.alert(i18n.get('label.warning'),
data.message);
}
return false;
}
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('label.applicationPluginSaved'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
this.parent.getStore().reload();
this.close();
},
failure : alertFailure
});
},
/**
* Notify violations.
* @param {Array} violations
*/
notifyViolations : function (violations) {
for (var i = 0; i < violations.length; i++) {
var violation = violations[i];
var store = this.gridFieldMapping.getStore();
var lineNb = store.findExact("name", violation.valueName);
var rec = store.getAt(lineNb);
rec.set("violation", violation);
}
this.gridFieldMapping.getView().refresh();
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp,loadUrl*/
/*
* @include "../applications/applicationsRole.js"
*/
Ext.namespace('sitools.admin.storages');
/**
* A Panel to show all the Storages in Sitools2
*
* @cfg {String} the url of data storage directory
* @cfg {String} the urlAuthorizations of authorizations
* @cfg {String} the urlFilters of classes filters
* @cfg {String} the urlParents of instances filters
* @cfg {Ext.data.JsonStore} the store where saved the user storage data
* @class sitools.admin.storages.storagesCrudPanel
* @extends Ext.grid.GridPanel
*/
//sitools.component.storages.storagesCrudPanel = Ext.extend(Ext.grid.GridPanel, {
sitools.admin.storages.storagesCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.STORAGES,
sm : new Ext.grid.RowSelectionModel(),
pageSize : 10,
// loadMask: true,
initComponent : function () {
this.url = loadUrl.get('APP_URL') + loadUrl.get('APP_DATASTORAGE_ADMIN_URL') + '/directories';
this.urlAuthorizations = loadUrl.get('APP_URL') + loadUrl.get('APP_AUTHORIZATIONS_URL');
this.urlFilters = loadUrl.get('APP_URL') + loadUrl.get('APP_PLUGINS_FILTERS_CLASSES_URL');
this.urlParents = loadUrl.get('APP_URL') + loadUrl.get('APP_PLUGINS_FILTERS_INSTANCES_URL');
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
url : this.url,
remoteSort : true,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'localPath',
type : 'string'
}, {
name : 'publicUrl',
type : 'string'
}, {
name : 'attachUrl',
type : 'string'
}, {
name : 'deeplyAccessible',
type : 'boolean'
}, {
name : 'listingAllowed',
type : 'boolean'
}, {
name : 'modifiable',
type : 'boolean'
}, {
name : 'status',
type : 'string'
} ]
});
var deeplyAccessible = new Ext.grid.CheckColumn({
header : i18n.get('label.deeplyAccessible'),
dataIndex : 'deeplyAccessible',
width : 80,
tooltip : i18n.get('label.deeplyAccessible')
});
var listingAllowed = new Ext.grid.CheckColumn({
header : i18n.get('label.listingAllowed'),
dataIndex : 'listingAllowed',
width : 55,
tooltip : i18n.get('label.listingAllowed')
});
var modifiable = new Ext.grid.CheckColumn({
header : i18n.get('label.modifiable'),
dataIndex : 'modifiable',
width : 55,
tooltip : i18n.get('label.modifiable')
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : false
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 50,
sortable : true
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 120
}, {
header : i18n.get('label.localPath'),
dataIndex : 'localPath',
width : 150
}, {
header : i18n.get('label.attachUrl'),
dataIndex : 'attachUrl',
width : 150
}, deeplyAccessible, listingAllowed, modifiable, {
header : i18n.get('label.status'),
dataIndex : 'status',
width : 50
}]
});
this.bbar = {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
};
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreate,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this.onModify,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDelete,
xtype : 's-menuButton'
}, {
text : i18n.get('label.authorizations'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_autorizations.png',
handler : this.onDefineRole,
xtype : 's-menuButton'
}, {
text : i18n.get('label.customfilter'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/filters.png',
xtype : 's-menuButton',
handler : this.onDefineFilter
}, {
text : i18n.get('label.active'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_active.png',
handler : this.onActive,
xtype : 's-menuButton'
}, {
text : i18n.get('label.disactive'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_disactive.png',
handler : this.onDisactive,
xtype : 's-menuButton'
},{
text : i18n.get('label.storageCopy'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/converter.png',
handler : this.onCopy,
xtype : 's-menuButton'
},
// { text: i18n.get('label.members'), icon:
// 'res/images/icons/toolbar_group_add.png', handler: this.onMembers
// },
'->', {
xtype : 's-filter',
emptyText : i18n.get('label.search'),
store : this.store,
pageSize : this.pageSize
} ]
};
this.view = new Ext.grid.GridView({
forceFit : true
});
this.listeners = {
scope : this,
rowDblClick : this.onModify
};
sitools.admin.storages.storagesCrudPanel.superclass.initComponent.call(this);
},
/**
* do a specific render to load storages from the store.
*/
onRender : function () {
sitools.admin.storages.storagesCrudPanel.superclass.onRender.apply(this, arguments);
this.store.load({
params : {
start : 0,
limit : this.pageSize
}
});
},
/**
* Open a {sitools.admin.applications.applicationsRolePanel} role panel to add a role authorization to the selected storage
*/
onDefineRole : function () {
var rec = this.getSelectionModel().getSelected(), up = new sitools.admin.applications.applicationsRolePanel({
urlAuthorizations : this.urlAuthorizations + "/" + rec.data.id,
applicationRecord : rec
});
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
if (rec.data.status == "STARTED") {
return Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.wrongStatus'));
}
up.show(ID.BOX.APPLICATION);
},
/**
* Open a {sitools.component.filtersPlugins.filtersPluginsSingle} filter plugin panel to add a filter plugin to the selected storage
*/
onDefineFilter : function (item, e) {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.noselection'));
}
if (rec.data.status == "STARTED") {
return Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.wrongStatus'));
}
Ext.Ajax.request({
url : this.url + "/" + rec.data.id + "/filter",
method : "GET",
scope : this,
success : function (ret) {
var data = Ext.decode(ret.responseText), action;
if (data.success) {
action = "editDelete";
} else {
action = "create";
}
var filterPlugin = data.filterPlugin;
var up = new sitools.component.filtersPlugins.filtersPluginsSingle({
action : action,
parentPanel : this,
urlFilters : this.urlFilters,
urlParent : this.urlParents + "/" + rec.data.id,
parentType : 'storage',
filterPlugin : filterPlugin
});
up.show();
},
failure : alertFailure
});
},
/**
* Open a {sitools.admin.storages.storagesPropPanel} storage property panel to create a new storage
*/
onCreate : function () {
var up = new sitools.admin.storages.storagesPropPanel({
url : this.url,
action : 'create',
store : this.getStore()
});
up.show();
},
/**
* Open a {sitools.admin.storages.storagesPropPanel} storage property panel to create a new storage
*/
onModify : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.admin.storages.storagesPropPanel({
url : this.url + '/' + rec.id,
action : 'modify',
store : this.getStore()
});
up.show();
},
/**
* Diplay confirm delete Msg box and call the method doDelete
*/
onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return false;
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('storageCrud.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec);
}
}
});
},
/**
* done the delete of the passed record
* @param rec the record to delete
*/
doDelete : function (rec) {
// var rec = this.getSelectionModel().getSelected();
// if (!rec) return false;
Ext.Ajax.request({
url : this.url + "/" + rec.id,
method : 'DELETE',
scope : this,
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
/**
* Activate the selected storage and set his status to "started"
*/
onActive : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.url + "/" + rec.id + "?action=start",
method : 'PUT',
scope : this,
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
/**
* Deactivate the selected storage and set his status to "stopped"
*/
onDisactive : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
Ext.Ajax.request({
url : this.url + "/" + rec.id + "?action=stop",
method : 'PUT',
scope : this,
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
},
onCopy : function (){
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.admin.storages.storageCopyProp({
urlDirectories : this.url,
idSrc : rec.id,
store : this.getStore()
});
up.show();
}
});
Ext.reg('s-storages', sitools.admin.storages.storagesCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
/*
* @include "../def.js"
*/
Ext.namespace('sitools.admin.storages');
/**
* A window that displays Storages properties.
*
* @cfg {string} url The url to Save the data
* @cfg {string} action The action should be modify or create
* @cfg {Ext.data.Store} store The storages store
* @class sitools.admin.storages.storagesPropPanel
* @extends Ext.Window
*/
//sitools.component.storages.storagesPropPanel = Ext.extend(Ext.Window, {
sitools.admin.storages.storagesPropPanel = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
pageSize : 10,
dataSets : "",
id : ID.COMPONENT_SETUP.STORAGE,
initComponent : function () {
if (this.action == 'modify') {
this.title = i18n.get('label.modifyStorage');
}
if (this.action == 'create') {
this.title = i18n.get('label.createStorage');
}
this.items = [ {
xtype : 'panel',
height : 450,
items : [ {
xtype : 'panel',
height : 410,
title : i18n.get('label.storageInfo'),
items : [ {
xtype : 'form',
border : false,
padding : 10,
items : [ {
xtype : 'hidden',
name : 'id'
}, {
xtype : 'textfield',
name : 'name',
fieldLabel : i18n.get('label.name'),
anchor : '100%',
maxLength : 30,
allowBlank : false
}, {
xtype : 'textfield',
name : 'description',
fieldLabel : i18n.get('label.description'),
anchor : '100%',
maxLength : 100
}, {
xtype : 'textfield',
name : 'localPath',
fieldLabel : i18n.get('label.localPath'),
anchor : '100%',
maxLength : 100
}, {
xtype : 'textfield',
name : 'attachUrl',
fieldLabel : i18n.get('label.attachUrl'),
anchor : '100%',
maxLength : 100,
vtype : "attachment",
allowBlank : false
}, {
xtype : 'checkbox',
fieldLabel: i18n.get('label.deeplyAccessible'),
name: 'deeplyAccessible'
}, {
xtype : 'checkbox',
fieldLabel: i18n.get('label.listingAllowed'),
name: 'listingAllowed'
}, {
xtype : 'checkbox',
fieldLabel: i18n.get('label.modifiable'),
name: 'modifiable'
}]
} ]
}],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ]
} ];
sitools.admin.storages.storagesPropPanel.superclass.initComponent.call(this);
},
/**
* Validate the modification.
* Call an ajax request with method depending on action.
* @return {Boolean}
*/
onValidate : function () {
var f = this.findByType('form')[0].getForm();
if (!f.isValid()) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.invalidForm'));
return false;
}
var putObject = {};
Ext.iterate(f.getFieldValues(), function (key, value) {
putObject[key] = value;
}, this);
if (this.action == 'modify') {
Ext.Ajax.request({
url : this.url,
method : 'PUT',
scope : this,
jsonData : putObject,
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (showResponse(ret)) {
this.close();
this.store.reload();
}
},
failure : alertFailure
});
}
if (this.action == 'create') {
Ext.Ajax.request({
url : this.url,
method : 'POST',
scope : this,
jsonData : putObject,
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (showResponse(ret)) {
this.close();
this.store.reload();
}
},
failure : alertFailure
});
}
},
/**
* Load the selected storage in case of modification.
*/
onRender : function () {
sitools.admin.storages.storagesPropPanel.superclass.onRender.apply(this, arguments);
if (this.url) {
// var gs = this.groupStore, qs = this.quotaStore;
if (this.action == 'modify') {
Ext.Ajax.request({
url : this.url,
method : 'GET',
scope : this,
success : function (ret) {
var f = this.findByType('form')[0].getForm();
var data = Ext.decode(ret.responseText).directory;
var record = new Ext.data.Record(data);
f.loadRecord(record);
},
failure : function (ret) {
var data = Ext.decode(ret.responseText);
Ext.Msg.alert(i18n.get('label.warning'), data.errorMessage);
}
});
}
}
}
});
Ext.reg('s-storagesprop', sitools.admin.storages.storagesPropPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, loadUrl*/
Ext.namespace('sitools.admin.resourcesPlugins');
/**
* A Generic Panel to display resources plugin informations in Sitools2
*
* @param urlParents, the url of the parent object
* @param resourcesUrlPart, the url of thes resources part
* @param urlResources, the url of the resources listing
* @param parentType, the type of the parent, string used only for i18n label
* @class sitools.admin.resourcesPlugins.resourcesPluginsCrudPanel
* @extends Ext.grid.GridPanel
*/
//sitools.component.resourcesPlugins.resourcesPluginsCrudPanel = Ext.extend(Ext.grid.GridPanel, {
sitools.admin.resourcesPlugins.resourcesPluginsCrudPanel = Ext.extend(Ext.grid.GridPanel, {
urlParentsParams : '',
border : false,
height : 300,
pageSize : 10,
modify : false,
urlGrid : null,
// Warning for version conflicts
conflictWarned : false,
viewConfig : {
forceFit : true,
autoFill : true,
getRowClass : function (row, index) {
var cls = '';
var data = row.data;
if (data.classVersion !== data.currentClassVersion
&& data.currentClassVersion !== null
&& data.currentClassVersion !== undefined) {
if (!this.conflictWarned) {
Ext.Msg.alert("warning.version.conflict", "Resources "
+ data.name
+ " definition (v"
+ data.classVersion
+ ") may conflict with current class version : "
+ data.currentClassVersion);
this.conflictWarned = true;
}
cls = "red-row";
}
return cls;
}
},
initComponent : function () {
//LIST OF PARENTS
var storeParents = new Ext.data.JsonStore({
fields : [ 'id', 'name', 'type' ],
url : this.urlParents + this.urlParentsParams,
root : "data",
autoLoad : true
});
this.comboParents = new Ext.form.ComboBox({
store : storeParents,
displayField : 'name',
valueField : 'id',
typeAhead : true,
mode : 'local',
forceSelection : true,
triggerAction : 'all',
emptyText : i18n.get('label.select' + this.parentType + 's'),
selectOnFocus : true,
listeners : {
scope : this,
select : function (combo, rec, index) {
this.parentId = rec.data.id;
if (!Ext.isEmpty(rec.data.type)) {
this.appClassName = rec.data.type;
}
var url = this.urlParents + "/" + this.parentId + this.resourcesUrlPart + this.urlParentsParams;
this.httpProxyResources.setUrl(url, true);
this.getStore().load();
}
}
});
this.httpProxyResources = new Ext.data.HttpProxy({
url : "/tmp",
restful : true,
method : 'GET'
});
this.store = new Ext.data.JsonStore({
idProperty : 'id',
root : "data",
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'descriptionAction',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'classVersion',
type : 'string'
}, {
name : 'classAuthor',
type : 'string'
}, {
name : 'currentClassVersion',
type : 'string'
}, {
name : 'currentClassAuthor',
type : 'string'
}, {
name : 'resourceClassName',
type : 'string'
}, {
name : 'classOwner',
type : 'string'
}, {
name : 'parameters'
}, {
name : 'parent',
type : 'string'
}, {
name : 'className',
type : 'string'
}, {
name : 'dataSetSelection',
type : 'string'
}, {
name : 'behavior',
type : 'string'
} ],
proxy : this.httpProxyResources
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 150
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 200,
sortable : false
}, {
header : i18n.get('label.resourceClassName'),
dataIndex : 'resourceClassName',
width : 150,
sortable : false
}, {
header : i18n.get('label.classVersion'),
dataIndex : 'classVersion',
width : 50,
sortable : false
}, {
header : i18n.get('label.currentClassVersion'),
dataIndex : 'currentClassVersion',
width : 50,
sortable : false
}, {
header : i18n.get('label.classAuthor'),
dataIndex : 'classAuthor',
width : 100,
sortable : false
}, {
header : i18n.get('label.classOwner'),
dataIndex : 'classOwner',
width : 100,
sortable : false
}, {
header : i18n.get('label.descriptionAction'),
dataIndex : 'descriptionAction',
width : 200,
sortable : false
} ]
});
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ this.comboParents, {
text : i18n.get('label.add'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreate,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this.onModify,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDelete,
xtype : 's-menuButton'
} ]
};
this.bbar = {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
};
this.listeners = {
scope : this,
rowDblClick : this.onModify
};
sitools.admin.resourcesPlugins.resourcesPluginsCrudPanel.superclass.initComponent.call(this);
},
/**
* done a specific render to load resources plugins from the store.
*/
onRender : function () {
sitools.admin.resourcesPlugins.resourcesPluginsCrudPanel.superclass.onRender.apply(this, arguments);
},
/**
* Open a {sitools.admin.resourcesPlugins.resourcesPluginsProp} resource plugin property window
* to create a new resource for the selected dataset in the comboBox
*/
onCreate : function () {
if (Ext.isEmpty(this.comboParents.getValue())) {
return;
}
var parentId = this.comboParents.getValue();
var urlParent = this.urlParents + "/" + parentId;
var up = new sitools.admin.resourcesPlugins.resourcesPluginsProp({
action : 'create',
parentPanel : this,
urlResources : this.urlResources,
urlResourcesCRUD : this.httpProxyResources.url,
urlParent : urlParent,
parentType : this.parentType,
appClassName : this.appClassName,
idParent : parentId
});
up.show();
},
/**
* Open a {sitools.admin.resourcesPlugins.resourcesPluginsProp} resource plugin property window
* to modify a resource for the selected dataset in the comboBox
*/
onModify : function () {
if (Ext.isEmpty(this.comboParents.getValue())) {
return;
}
var parentId = this.comboParents.getValue();
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
if ("ACTIVE" === rec.data.status) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.wrongStatus'));
return;
}
var urlParent = this.urlParents + "/" + parentId;
var up = new sitools.admin.resourcesPlugins.resourcesPluginsProp({
action : 'modify',
record : rec,
parentPanel : this,
urlResources : this.urlResources,
urlResourcesCRUD : this.httpProxyResources.url,
urlParent : urlParent,
appClassName : this.appClassName,
idParent : parentId,
parentType : this.parentType
});
up.show();
},
/**
* Diplay confirm delete Msg box and call the method doDelete
*/
onDelete : function () {
if (Ext.isEmpty(this.comboParents.getValue())) {
return;
}
var parentId = this.comboParents.getValue();
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('resourcesPlugins' + this.parentType + 'Crud.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec, parentId);
}
}
});
},
/**
* done the delete of the passed record
* @param rec the record to delete
*/
doDelete : function (rec, parentId) {
Ext.Ajax.request({
url : this.urlParents + "/" + parentId + this.resourcesUrlPart + "/" + rec.id,
method : 'DELETE',
scope : this,
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
}
});
Ext.reg('s-plugins_resources', sitools.admin.resourcesPlugins.resourcesPluginsCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, ImageChooser, loadUrl*/
/*
* @include "../datasets/selectColumn.js"
*/
Ext.namespace('sitools.admin.resourcesPlugins');
/**
* A window of a resource plugin properties
*
* @param action
* create or modify
* @param parentPanel
* the parent panel
* @param urlResources
* the resources url
* @param urlResourcesCRUD
* the URL of the resource CRUD
* @param urlParent
* the url of the parent Object
* @param appClassName
* the parent className
* @param idParent
* the parent id
* @param parentType
* the type of the parent, string used only for i18n label
* @class sitools.admin.resourcesPlugins.resourcesPluginsProp
* @extends Ext.Window
*/
//sitools.component.resourcesPlugins.resourcesPluginsProp = Ext.extend(Ext.Window, {
sitools.admin.resourcesPlugins.resourcesPluginsProp = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
resizable : true,
classChosen : "",
resourcePluginId : null,
modelClassName : null,
initComponent : function () {
this.title = this.action == "create" ? i18n.get('label.create' + this.parentType + 'Resource') : i18n.get('label.modify' + this.parentType + 'Resource');
var expander = new Ext.ux.grid.RowExpander({
tpl : new Ext.XTemplate(
'<tpl if="this.descEmpty(description)" ><div></div></tpl>',
'<tpl if="this.descEmpty(description) == false" ><div class="sitoolsDescription"><div class="sitoolsDescriptionHeader">Description : </div><p class="sitoolsDescriptionText"> {description} </p></div></tpl>',
{
compiled : true,
descEmpty : function (description) {
return Ext.isEmpty(description);
}
}),
expandOnDblClick : true
});
this.gridresourcePlugin = new Ext.grid.GridPanel({
viewConfig : {
forceFit : true
},
layout : "fit",
id : 'gridresourcePlugin',
title : i18n.get('title.resourcePlugin' + this.parentType + 'Class'),
store : new Ext.data.JsonStore({
root : 'data',
restful : true,
proxy : new Ext.data.HttpProxy({
url : this.urlResources,
restful : true,
method : 'GET'
}),
remoteSort : false,
sortInfo : {
field : "name",
direction : "ASC"
},
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'resourceClassName',
type : 'string'
}, {
name : 'classAuthor',
type : 'string'
}, {
name : 'classVersion',
type : 'string'
}, {
name : 'parameters'
}, {
name : 'className',
type : 'string'
}, {
name : 'classOwner',
type : 'string'
}, {
name : 'applicationClassName',
type : 'string'
}, {
name : 'dataSetSelection',
type : 'string'
} ]
}),
cm : new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ expander, {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100,
sortable : true
}, {
header : i18n.get('label.resourceClassName'),
dataIndex : 'className',
width : 300,
sortable : true
}, {
header : i18n.get('label.author'),
dataIndex : 'classAuthor',
width : 100,
sortable : true
}, {
header : i18n.get('label.version'),
dataIndex : 'classVersion',
width : 100,
sortable : true
}, {
header : i18n.get('label.classOwner'),
dataIndex : 'classOwner',
width : 100,
sortable : true
} ]
}),
listeners : {
scope : this,
rowclick : this.onClassClick
},
plugins : expander
});
this.proxyFieldMapping = new Ext.data.HttpProxy({
url : "/tmp",
restful : true,
method : 'GET'
});
var userUpdatable = new Ext.grid.CheckColumn({
header : i18n.get('headers.userUpdatable'),
dataIndex : 'userUpdatable',
width : 55
});
var expanderGridFieldMapping = new sitools.widget.ViolationRowExpander({
tpl : new Ext.XTemplate(
'<tpl if="this.descEmpty(description)" ><div></div></tpl>',
'<tpl if="this.descEmpty(description) == false" ><div class="sitoolsDescription"><div class="sitoolsDescriptionHeader">Description : </div><p class="sitoolsDescriptionText"> {description} </p></div></tpl>',
{
compiled : true,
descEmpty : function (description) {
return Ext.isEmpty(description);
}
}),
expandOnDblClick : false
});
this.gridFieldMapping = new Ext.grid.EditorGridPanel({
viewConfig : {
forceFit : true,
scope : this,
getRowClass : function (record, index, rowParams, store) {
var cls = '';
var violation = record.get("violation");
if (!Ext.isEmpty(violation)) {
if (violation.level == "CRITICAL") {
cls = "red-row";
} else if (violation.level == "WARNING") {
cls = "orange-row";
}
}
return cls;
},
listeners : {
scope : this,
refresh : function (view) {
var grid = this.gridFieldMapping;
var store = grid.getStore();
store.each(function (record) {
var violation = record.get("violation");
if (!Ext.isEmpty(violation)) {
var index = store.indexOf(record);
//var view = this.scope.gridFieldMapping.getView();
var htmlLineEl = view.getRow(index);
var el = Ext.get(htmlLineEl);
var cls = (violation.level == "CRITICAL")
? "x-form-invalid-tip"
: "x-form-invalid-tip x-form-warning-tip";
var ttConfig = {
html : violation.message,
dismissDelay : 0,
target : el,
cls : cls
};
var ttip = new Ext.ToolTip(ttConfig);
}
});
this.showOptions(this.gridFieldMapping);
},
rowupdated : function () {
this.showOptions(this.gridFieldMapping);
}
}
},
id : 'gridFieldMapping',
layout : 'fit',
region : 'center',
title : i18n.get('title.parametersMapping'),
store : new Ext.data.JsonStore({
root : 'resourcePlugin.parameters',
proxy : this.proxyFieldMapping,
restful : true,
remoteSort : false,
idProperty : 'name',
fields : [ {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'type',
type : 'string'
}, {
name : 'value',
type : 'string'
}, {
name : 'valueType',
type : 'string'
}, {
name : 'violation'
}, {
name : "userUpdatable",
type : "boolean"
}]
}),
bbar : new Ext.ux.StatusBar({
id: 'statusBar',
hidden : true,
iconCls: 'x-status-error',
text : i18n.get("label.resourcesPluginErrorValidationNotification")
}),
cm : new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [expanderGridFieldMapping, {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100,
sortable : true
}/*, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 100,
sortable : false
}*/, {
header : i18n.get('label.type'),
dataIndex : 'type',
width : 150,
sortable : false
}, {
header : i18n.get('label.value'),
dataIndex : 'value',
width : 230,
sortable : false,
editable : true,
editor : new Ext.form.TextField()
}, userUpdatable ]
}),
listeners : {
scope : this,
celldblclick : function (grid, rowIndex, columnIndex, e) {
var storeRecord = grid.getStore().getAt(rowIndex);
var rec = storeRecord.data;
if (columnIndex == 3) {
if (rec.valueType == "xs:dataset.columnAlias") {
var selectColumnWin = new sitools.admin.datasets.selectColumn({
field : "value",
record : storeRecord,
parentStore : this.gridFieldMapping.getStore(),
parentView : this.gridFieldMapping.getView(),
url : loadUrl.get("APP_URL") + loadUrl.get("APP_DATASETS_URL") + "/" + this.idParent
});
selectColumnWin.show(ID.BOX.DATASETS);
}
else if (rec.valueType == "xs:dictionary") {
var selectDictionaryWin = new sitools.component.dictionary.selectDictionary({
field : "value",
record : storeRecord,
parentStore : this.gridFieldMapping.getStore(),
parentView : this.gridFieldMapping.getView(),
url : loadUrl.get("APP_URL") + loadUrl.get("APP_DICTIONARIES_URL")
});
selectDictionaryWin.show(ID.BOX.DATASETS);
}
else if (rec.valueType == "xs:boolean") {
var selectBooleanWin = new sitools.admin.resourcesPlugins.enumerationValueTypeSelector({
field : "value",
record : storeRecord,
parentView : this.gridFieldMapping.getView(),
type : rec.name,
enumeration : "[true,false]",
value : rec.value
});
selectBooleanWin.show(ID.BOX.DATASETS);
}
else if (rec.valueType == "xs:image") {
// console.dir (this);
var chooser = new ImageChooser({
url : loadUrl.get('APP_URL') + loadUrl.get('APP_UPLOAD_URL') + '/?media=json',
width : 515,
height : 450,
field : "value",
parentView : this.gridFieldMapping.getView(),
record : storeRecord
});
chooser.show(document, function (data, config) {
config.record.data[config.field] = data.url;
config.parentView.refresh();
});
}
else if (rec.valueType.indexOf("xs:enum") != -1) {
var enumType;
if (rec.valueType.indexOf("xs:enum-editable-multiple") != -1) {
enumType = "EEM";
}
else if (rec.valueType.indexOf("xs:enum-editable") != -1) {
enumType = "EE";
}
else if (rec.valueType.indexOf("xs:enum-multiple") != -1) {
enumType = "EM";
}
else {
enumType = "E";
}
var selectEnumWin = new sitools.admin.resourcesPlugins.enumerationValueTypeSelector({
enumType : enumType,
field : "value",
fieldEnum : "valueType",
record : storeRecord,
parentView : this.gridFieldMapping.getView(),
type : rec.name,
enumeration : rec.valueType,
value : rec.value
});
selectEnumWin.show(ID.BOX.DATASETS);
}
} else {
return false;
}
},
viewready : function (grid) {
this.showOptions(grid);
}
},
plugins : [userUpdatable, expanderGridFieldMapping]
});
var comboBehavior = new Ext.form.ComboBox({
typeAhead : false,
fieldLabel : i18n.get("label.behavior"),
name : "behavior",
triggerAction : 'all',
lazyRender : true,
mode : 'local',
anchor : "100%",
store : new Ext.data.ArrayStore({
id : 0,
fields : [ 'myId', 'displayText' ],
data : [
[ 'DISPLAY_IN_NEW_TAB', i18n.get('DISPLAY_IN_NEW_TAB') ],
[ 'DISPLAY_IN_DESKTOP', i18n.get('DISPLAY_IN_DESKTOP') ]
]
}),
valueField : 'myId',
displayField : 'displayText'
});
// set the search form
this.fieldMappingFormPanel = new Ext.FormPanel({
height : 95,
frame : true,
defaultType : 'textfield',
items : [{
fieldLabel : i18n.get('label.name'),
name : 'name',
anchor : '100%'
}, {
fieldLabel : i18n.get('label.descriptionAction'),
name : 'descriptionAction',
anchor : '100%'
}, comboBehavior],
region : 'north'
});
this.fieldMappingPanel = new Ext.Panel({
layout : 'border',
id : 'fieldMappingPanel',
title : i18n.get('title.fieldMapping'),
items : [ this.fieldMappingFormPanel, this.gridFieldMapping ],
listeners : {
scope : this,
activate : function () {
this.showOptions(this.gridFieldMapping);
}
}
});
this.tabPanel = new Ext.TabPanel({
height : 450,
activeTab : 0,
items : (this.action == "create") ? [ this.gridresourcePlugin, this.fieldMappingPanel ] : [
this.fieldMappingPanel
],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ],
listeners : {
scope : this,
beforetabchange : this.beforeTabChange
}
});
this.listeners = {
scope : this,
resize : function (window, width, height) {
var size = window.body.getSize();
this.tabPanel.setSize(size);
}
};
this.items = [ this.tabPanel ];
sitools.admin.resourcesPlugins.resourcesPluginsProp.superclass.initComponent.call(this);
},
/**
* Notify the user if no resource plugin was selected
* when he wants to change of tab
*/
beforeTabChange : function (self, newTab, currentTab) {
if (this.action == "create") {
if (newTab.id == "gridFieldMapping") {
var rec = this.gridresourcePlugin.getSelectionModel().getSelected();
if (!rec) {
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('warning.noselection'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
return false;
}
}
}
},
/**
* Load fields mapping form fields and parameters in fonction of the class clicked
*/
onClassClick : function (self, rowIndex, e) {
if (this.action == "create") {
var rec = this.gridresourcePlugin.getSelectionModel().getSelected();
if (!rec) {
return false;
}
var className = rec.data.className;
if (className != this.classChosen) {
var url = this.urlResources + "/" + className;
var store = this.gridFieldMapping.getStore();
store.removeAll();
Ext.Ajax.request({
url : url,
method : 'GET',
scope : this,
params : {
appClassName : this.appClassName,
parent : this.idParent
},
success : function (ret) {
var json = Ext.decode(ret.responseText);
if (!json.success) {
Ext.Msg.alert(i18n.get('label.warning'),
json.message);
return false;
}
var resourcePlugin = json.resourcePlugin;
this.fillGridAndForm(resourcePlugin, this.action);
this.classChosen = className;
}
});
}
// this.fillGridAndForm(rec.data, this.action);
}
},
/**
* If "action" is "modify", load data from record into the form else load empty form
*/
afterRender : function () {
sitools.admin.resourcesPlugins.resourcesPluginsProp.superclass.afterRender.apply(this, arguments);
if (this.action == "modify") {
this.fillGridAndForm(this.record.data, this.action);
} else {
//only need to load the resourcesPlugins for creation
this.gridresourcePlugin.getStore().load({
params : {
appClassName : this.appClassName,
parent : this.idParent
}
});
}
},
/**
* Fill the grid and form with data from resourcePlugin
*
* @param resourcePlugin, the resource to fill the form with
* @param action, the mode (create or modify)
*/
fillGridAndForm : function (resourcePlugin, action) {
if (!Ext.isEmpty(resourcePlugin)) {
var rec = {};
var form = this.fieldMappingFormPanel.getForm();
rec.name = resourcePlugin.name;
rec.descriptionAction = resourcePlugin.descriptionAction;
rec.id = resourcePlugin.id;
rec.resourceClassName = resourcePlugin.resourceClassName;
rec.behavior = resourcePlugin.behavior;
form.loadRecord(new Ext.data.Record(rec));
var parameters = resourcePlugin.parameters;
var store = this.gridFieldMapping.getStore();
store.removeAll();
if (!Ext.isEmpty(parameters)) {
for (var i = 0; i < parameters.length; i++) {
var recTmp = new Ext.data.Record(parameters[i]);
if (action == "create" && Ext.isEmpty(parameters[i].value)) {
recTmp.set("value", "");
}
store.add(recTmp);
}
}
store.sort('name', 'ASC');
}
},
/**
* Save the resource plugin properties
*/
onValidate : function () {
var rec;
var jsonReturn = {};
var parameters = [];
var resourcePlugin;
if (this.action == "create") {
rec = this.gridresourcePlugin.getSelectionModel().getSelected();
if (!rec) {
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('warning.noselection'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
return false;
}
resourcePlugin = rec.data;
} else {
resourcePlugin = this.record.data;
jsonReturn.id = this.record.data.id;
}
jsonReturn.classVersion = resourcePlugin.classVersion;
jsonReturn.classAuthor = resourcePlugin.classAuthor;
jsonReturn.classOwner = resourcePlugin.classOwner;
jsonReturn.description = resourcePlugin.description;
jsonReturn.className = resourcePlugin.className;
jsonReturn.resourceClassName = resourcePlugin.resourceClassName;
jsonReturn.parent = resourcePlugin.parent;
jsonReturn.applicationClassName = resourcePlugin.applicationClassName;
if (!Ext.isEmpty(resourcePlugin.dataSetSelection)) {
jsonReturn.dataSetSelection = resourcePlugin.dataSetSelection;
}
var form = this.fieldMappingFormPanel.getForm();
if (!form.isValid()) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.invalidForm'));
return false;
}
Ext.iterate(form.getValues(), function (key, value) {
if (!Ext.isEmpty(value)) {
jsonReturn[key] = value;
}
});
var storeField = this.gridFieldMapping.getStore();
var re1 = new RegExp("^/.*$");
var re2 = new RegExp("^.*//.*$");
var re3 = new RegExp("^.*[!\"#$%&\'()*+,:;<=>?@\\`|~]+.*$");
for (var i = 0; i < storeField.getCount(); i++) {
var recTmp = storeField.getAt(i).data;
recTmp.violation = undefined;
if (recTmp.type == "PARAMETER_ATTACHMENT") {
var attach = recTmp.value;
var ok = re1.test(attach) && !re2.test(attach) && !re3.test(attach);
if (!ok) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('label.invalidAttachment') + " : " + attach);
}
}
parameters.push(recTmp);
}
jsonReturn.parameters = parameters;
var url = this.urlResourcesCRUD, method;
if (this.action == "modify") {
url += "/" + jsonReturn.id;
method = "PUT";
} else {
method = "POST";
}
Ext.Ajax.request({
url : url,
method : method,
scope : this,
jsonData : jsonReturn,
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (!data.success) {
if (Ext.isEmpty(data.message)) {
var violations = data.data;
this.notifyViolations(violations);
Ext.getCmp("statusBar").show();
} else {
Ext.Msg.alert(i18n.get('label.warning'),
data.message);
}
return false;
}
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('label.resourcePlugin' + this.parentType + 'Saved'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
this.parentPanel.getStore().reload();
this.close();
},
failure : alertFailure
});
},
/**
* Notify the user there are violations error
* @param violations
*/
notifyViolations : function (violations) {
for (var i = 0; i < violations.length; i++) {
var violation = violations[i];
var store = this.gridFieldMapping.getStore();
var lineNb = store.findExact("name", violation.valueName);
var rec = store.getAt(lineNb);
rec.set("violation", violation);
}
this.gridFieldMapping.getView().refresh();
},
onClose : function () {
},
/**
* Show parameters of a specific application resource
* except parameter of "PARAMETER_USER_INPUT" type
*
* @param grid, the mapping grid
*/
showOptions : function (grid) {
var toShow, rec;
var colIndex = grid.getColumnModel().findColumnIndex("userUpdatable");
for (var i = 0; i < grid.getStore().getCount(); i++) {
rec = grid.getStore().getAt(i);
toShow = rec.get("type") == "PARAMETER_USER_INPUT";
if (!toShow) {
try {
grid.getView().getCell(i, colIndex).innerHTML = " ";
}
catch (err) {
return;
}
}
}
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.admin.resourcesPlugins');
/**
* A window to show values enumeration
*
* @param type
* the type to select used for i18n
* @param field
* the name of the field in the parent record
* @param record
* the parent record
* @param enumeration
* the complete enumeration value
* @class sitools.admin.resourcesPlugins.enumerationValueTypeSelector
* @extends Ext.Window
*/
//sitools.component.resourcesPlugins.enumerationValueTypeSelector = Ext.extend(Ext.Window, {
sitools.admin.resourcesPlugins.enumerationValueTypeSelector = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
pageSize : 10,
editable : false,
initComponent : function () {
this.title = i18n.get('title.select' + this.type);
this.editable = this.enumType == "EE" || this.enumType == "EEM";
var enumeration = this.enumeration.split("[");
enumeration = enumeration[1].split("]");
enumeration = enumeration[0].split(",");
this.storeEnum = new Ext.data.ArrayStore({
fields: ["enumValue"],
idIndex: 0
});
Ext.each(enumeration, function (item, index) {
this.storeEnum.add(new Ext.data.Record({
enumValue : item.trim()
}));
}, this);
var column = {
id : 'name',
header : i18n.get('headers.name'),
sortable : true,
dataIndex : "enumValue",
width : 250
};
if (this.editable) {
Ext.apply(column, {
editor : new Ext.form.TextField({
disabled : !this.editable
})
});
}
this.cmSelectColumn = new Ext.grid.ColumnModel({
columns : [ column ]
});
var tbar = {
xtype : 'sitools.widget.GridSorterToolbar',
hidden : ! this.editable,
defaults : {
scope : this
},
items : [{
text : i18n.get('label.add'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onAddValue,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this.onModifyValue,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDeleteValue,
xtype : 's-menuButton'
}]
};
this.smSelectColumn = new Ext.grid.RowSelectionModel({
singleSelect : this.enumType == "E" || this.enumType == "EE"
});
this.gridSelect = new Ext.grid.EditorGridPanel({
tbar : tbar,
height : 380,
autoScroll : true,
store : this.storeEnum,
cm : this.cmSelectColumn,
sm : this.smSelectColumn,
listeners : {
scope : this,
viewready : this.showSelectedRecords
}
});
this.items = [ {
xtype : 'panel',
layout : 'fit',
items : [ this.gridSelect ],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ]
} ];
sitools.admin.resourcesPlugins.enumerationValueTypeSelector.superclass.initComponent.call(this);
},
/**
* Save the selected value
*/
onValidate : function () {
var recs = this.gridSelect.getSelectionModel().getSelections();
var result = [];
Ext.each(recs, function (rec) {
result.push(rec.data.enumValue);
});
this.record.data[this.field] = result.join("|");
// this.recordColumn.data.dataIndex = rec.data.dataIndex;
// this.recordColumn.data.schema = rec.data.schema;
if (this.editable) {
result = [];
this.gridSelect.getStore().each(function (rec) {
result.push(rec.data.enumValue);
});
this.record.data[this.fieldEnum] = "xs:enum-editable";
if (this.enumType == "EEM") {
this.record.data[this.fieldEnum] += "-multiple";
}
this.record.data[this.fieldEnum] += "[" + result.join(",") + "]";
}
this.parentView.refresh();
this.close();
},
/**
* Set the enumeration field with value(s) selected
*
* @param grid, the grid to set the enumeration field
*/
showSelectedRecords : function (grid) {
var value = this.record.get(this.field);
if (Ext.isEmpty(value)) {
return;
}
var values = value.split("|");
if (Ext.isEmpty(values)) {
return;
}
Ext.each(values, function (value) {
var index = grid.getStore().find("enumValue", value);
if (index != -1) {
grid.getSelectionModel().selectRow(index, true);
}
});
},
/**
* Add a new line to the enumeration
*/
onAddValue : function () {
this.gridSelect.getStore().add(new (this.gridSelect.getStore().recordType));
this.gridSelect.getView().refresh();
},
/**
* Delete a value enumeration
*/
onDeleteValue : function () {
var recs = this.gridSelect.getSelectionModel().getSelections();
if (Ext.isEmpty(recs)) {
return;
}
Ext.each(recs, function (rec) {
this.gridSelect.getStore().remove(rec);
}, this);
this.gridSelect.getView().refresh();
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, loadUrl*/
Ext.namespace('sitools.admin.projectResources');
/**
* A Panel to display project resource plugin informations
*
* @class sitools.admin.projectResources.projectResourcesCrudPanel
* @extends Ext.Panel
*/
//sitools.component.projectResources.projectResourcesCrudPanel = Ext.extend(Ext.Panel, {
sitools.admin.projectResources.projectResourcesCrudPanel = Ext.extend(Ext.Panel, {
border : false,
height : 300,
layout : 'fit',
initComponent : function () {
var resourcePluginProject = new sitools.admin.resourcesPlugins.resourcesPluginsCrudPanel({
urlParents : loadUrl.get('APP_URL') + loadUrl.get('APP_PROJECTS_URL'),
resourcesUrlPart : loadUrl.get('APP_RESOURCES_URL'),
urlResources : loadUrl.get('APP_URL') + loadUrl.get('APP_PLUGINS_RESOURCES_URL') + '/classes',
parentType : "project",
appClassName : "fr.cnes.sitools.project.ProjectApplication"
});
this.items = [ resourcePluginProject ];
sitools.admin.projectResources.projectResourcesCrudPanel.superclass.initComponent.call(this);
}
});
Ext.reg('s-project_resources', sitools.admin.projectResources.projectResourcesCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, loadUrl*/
/*
* @include "../../resourcesPlugins/resourcesPluginsCrud.js"
*/
Ext.namespace('sitools.admin.datasets.plugins');
/**
* A panel to managed Dataset resources.
* @requires sitools.admin.resourcesPlugins.resourcesPluginsCrudPanel
* @class sitools.admin.datasets.plugins.resourcesCrudPanel
* @extends Ext.Panel
*/
sitools.admin.datasets.plugins.resourcesCrudPanel = Ext.extend(Ext.Panel, {
//sitools.component.datasetResources.datasetResourcesCrudPanel = Ext.extend(Ext.Panel, {
border : false,
height : 300,
layout : 'fit',
initComponent : function () {
var resourcePlugindataset = new sitools.admin.resourcesPlugins.resourcesPluginsCrudPanel({
urlParents : loadUrl.get('APP_URL') + loadUrl.get('APP_DATASETS_URL'),
resourcesUrlPart : loadUrl.get('APP_RESOURCES_URL'),
urlResources : loadUrl.get('APP_URL') + loadUrl.get('APP_PLUGINS_RESOURCES_URL') + '/classes',
parentType : "dataset",
appClassName : "fr.cnes.sitools.dataset.DataSetApplication"
});
this.items = [ resourcePlugindataset ];
sitools.admin.datasets.plugins.resourcesCrudPanel.superclass.initComponent.call(this);
}
});
Ext.reg('s-dataset_resources', sitools.admin.datasets.plugins.resourcesCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, loadUrl*/
Ext.namespace('sitools.admin.applications.plugins');
/**
* @class sitools.admin.applications.plugins.applicationResourcesCrudPanel
* @extends Ext.Panel
* @requires sitools.admin.resourcesPlugins.resourcesPluginsCrudPanel
*/
//sitools.component.applicationResources.applicationResourcesCrudPanel = Ext.extend(Ext.Panel, {
sitools.admin.applications.plugins.applicationResourcesCrudPanel = Ext.extend(Ext.Panel, {
border : false,
height : 300,
layout : 'fit',
initComponent : function () {
var resourcePluginapplication = new sitools.admin.resourcesPlugins.resourcesPluginsCrudPanel({
urlParents : loadUrl.get('APP_URL') + loadUrl.get('APP_APPLICATIONS_URL'),
urlParentsParams : '?customizable=true',
resourcesUrlPart : loadUrl.get('APP_RESOURCES_URL'),
urlResources : loadUrl.get('APP_URL') + loadUrl.get('APP_PLUGINS_RESOURCES_URL') + '/classes',
parentType : "application"
});
this.items = [ resourcePluginapplication ];
sitools.admin.applications.plugins.applicationResourcesCrudPanel.superclass.initComponent.call(this);
}
});
Ext.reg('s-application_resources', sitools.admin.applications.plugins.applicationResourcesCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, ImageChooser*/
Ext.namespace('sitools.component.filtersPlugins');
/**
* @cfg {String} action
* create or modify
* @param parentPanel
* the parent panel
* @param urlFilters
* the filters url
* @param urlParent
* the parent object url
* @param parentType
* the type of the parent, string used only for i18n label
* @class sitools.component.filtersPlugins.filtersPluginsProp
* @extends Ext.Window
*/
sitools.component.filtersPlugins.filtersPluginsProp = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
resizable : false,
classChosen : "",
filterPluginId : null,
modelClassName : null,
initComponent : function () {
this.title = this.action == "create" ? i18n.get('label.create' + this.parentType + 'Filter') : i18n.get('label.modify' + this.parentType + 'Filter');
var expander = new Ext.ux.grid.RowExpander({
tpl : new Ext.XTemplate(
'<tpl if="this.descEmpty(description)" ><div></div></tpl>',
'<tpl if="this.descEmpty(description) == false" ><div class="sitoolsDescription"><div class="sitoolsDescriptionHeader">Description : </div><p class="sitoolsDescriptionText"> {description} </p></div></tpl>',
{
compiled : true,
descEmpty : function (description) {
return Ext.isEmpty(description);
}
}),
expandOnDblClick : true
});
this.gridfilterPlugin = new Ext.grid.GridPanel({
viewConfig : {
forceFit : true
},
id : 'gridfilterPlugin',
title : i18n.get('title.filterPlugin' + this.parentType + 'Class'),
store : new Ext.data.JsonStore({
root : 'data',
restful : true,
proxy : new Ext.data.HttpProxy({
url : this.urlFilters,
restful : true,
method : 'GET'
}),
remoteSort : false,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'filterClassName',
type : 'string'
}, {
name : 'classAuthor',
type : 'string'
}, {
name : 'classVersion',
type : 'string'
}, {
name : 'parameters'
}, {
name : 'className',
type : 'string'
} ]
}),
cm : new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ expander, {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100,
sortable : true
}, {
header : i18n.get('label.filterClassName'),
dataIndex : 'filterClassName',
width : 300,
sortable : true
}, {
header : i18n.get('label.author'),
dataIndex : 'classAuthor',
width : 100,
sortable : true
}, {
header : i18n.get('label.version'),
dataIndex : 'classVersion',
width : 100,
sortable : true
} ]
}),
listeners : {
scope : this,
rowclick : this.onClassClick
},
plugins : expander
});
this.proxyFieldMapping = new Ext.data.HttpProxy({
url : "/tmp",
restful : true,
method : 'GET'
});
this.gridFieldMapping = new Ext.grid.EditorGridPanel({
viewConfig : {
forceFit : true,
scope : this,
getRowClass : function (record, index, rowParams, store) {
var cls = '';
var violation = record.get("violation");
if (!Ext.isEmpty(violation)) {
if (violation.level == "CRITICAL") {
cls = "red-row";
} else if (violation.level == "WARNING") {
cls = "orange-row";
}
}
return cls;
},
listeners : {
scope : this,
refresh : function (view) {
var grid = this.gridFieldMapping;
var store = grid.getStore();
store.each(function (record) {
var violation = record.get("violation");
if (!Ext.isEmpty(violation)) {
var index = store.indexOf(record);
//var view = this.scope.gridFieldMapping.getView();
var htmlLineEl = view.getRow(index);
var el = Ext.get(htmlLineEl);
var cls = (violation.level == "CRITICAL")
? "x-form-invalid-tip"
: "x-form-invalid-tip x-form-warning-tip";
var ttConfig = {
html : violation.message,
dismissDelay : 0,
target : el,
cls : cls
};
var ttip = new Ext.ToolTip(ttConfig);
}
});
}
}
},
id : 'gridFieldMapping',
layout : 'fit',
region : 'center',
title : i18n.get('title.parametersMapping'),
store : new Ext.data.JsonStore({
root : 'filterPlugin.parameters',
proxy : this.proxyFieldMapping,
restful : true,
remoteSort : false,
idProperty : 'name',
fields : [ {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'type',
type : 'string'
}, {
name : 'value',
type : 'string'
}, {
name : 'valueType',
type : 'string'
}, {
name : 'violation'
}]
}),
bbar : new Ext.ux.StatusBar({
id: 'statusBar',
hidden : true,
iconCls: 'x-status-error',
text : i18n.get("label.filtersPluginErrorValidationNotification")
}),
cm : new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100,
sortable : true
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 100,
sortable : false
}, {
header : i18n.get('label.type'),
dataIndex : 'type',
width : 150,
sortable : false
}, {
header : i18n.get('label.value'),
dataIndex : 'value',
width : 230,
sortable : false,
editable : true,
editor : new Ext.form.TextField()
} ]
})
});
// set the search form
this.fieldMappingFormPanel = new Ext.FormPanel({
height : 65,
frame : true,
defaultType : 'textfield',
items : [{
fieldLabel : i18n.get('label.name'),
name : 'name',
anchor : '100%'
}, {
fieldLabel : i18n.get('label.descriptionAction'),
name : 'descriptionAction',
anchor : '100%'
} ],
region : 'north'
});
this.fieldMappingPanel = new Ext.Panel({
layout : 'border',
id : 'fieldMappingPanel',
title : i18n.get('title.fieldMapping'),
items : [ this.fieldMappingFormPanel, this.gridFieldMapping ]
});
this.tabPanel = new Ext.TabPanel({
height : 450,
activeTab : 0,
items : (this.action == "create") ? [ this.gridfilterPlugin, this.fieldMappingPanel ] : [
this.fieldMappingPanel
],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ],
listeners : {
scope : this,
beforetabchange : this.beforeTabChange
}
});
this.items = [ this.tabPanel ];
sitools.component.filtersPlugins.filtersPluginsProp.superclass.initComponent.call(this);
},
beforeTabChange : function (self, newTab, currentTab) {
if (this.action == "create") {
if (newTab.id == "gridFieldMapping") {
var rec = this.gridfilterPlugin.getSelectionModel().getSelected();
if (!rec) {
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('warning.noselection'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
return false;
}
}
}
},
onClassClick : function (self, rowIndex, e) {
if (this.action == "create") {
var rec = this.gridfilterPlugin.getSelectionModel().getSelected();
if (!rec) {
// var tmp = new Ext.ux.Notification({
// iconCls : 'x-icon-information',
// title : i18n.get('label.information'),
// html : i18n.get('warning.noselection'),
// autoDestroy : true,
// hideDelay : 1000
// }).show(document);
return false;
}
/*var className = rec.data.className;
if (className != this.classChosen) {
this.proxyFieldMapping.setUrl(this.urlFilters + "/"
+ className);
this.classChosen = className;
var store = this.gridFieldMapping.getStore();
store.removeAll();
store.load();
}*/
this.fillGridAndForm(rec.data, this.action);
}
},
afterRender : function () {
sitools.component.filtersPlugins.filtersPluginsProp.superclass.afterRender.apply(this, arguments);
if (this.action == "modify") {
//this.filterPluginId = this.record.data.id;
this.fillGridAndForm(this.record.data, this.action);
//this.proxyFieldMapping.setUrl(this.urlParent + "/" + this.filterPluginId);
//var store = this.gridFieldMapping.getStore();
//store.load();
} else {
//only need to load the filtersPlugins for creation
this.gridfilterPlugin.getStore().load();
}
},
fillGridAndForm : function (filterPlugin, action) {
if (!Ext.isEmpty(filterPlugin)) {
var rec = {};
var form = this.fieldMappingFormPanel.getForm();
rec.name = filterPlugin.name;
rec.descriptionAction = filterPlugin.descriptionAction;
rec.id = filterPlugin.id;
rec.filterClassName = filterPlugin.filterClassName;
form.loadRecord(new Ext.data.Record(rec));
var parameters = filterPlugin.parameters;
var store = this.gridFieldMapping.getStore();
store.removeAll();
if (!Ext.isEmpty(parameters)) {
for (var i = 0; i < parameters.length; i++) {
var recTmp = new Ext.data.Record(parameters[i]);
if (action == "create" && Ext.isEmpty(parameters[i].value)) {
recTmp.set("value", "");
}
store.add(recTmp);
}
}
}
},
onValidate : function () {
var rec;
var jsonReturn = {};
var parameters = [];
var filterPlugin;
if (this.action == "create") {
rec = this.gridfilterPlugin.getSelectionModel().getSelected();
if (!rec) {
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('warning.noselection'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
return false;
}
filterPlugin = rec.data;
} else {
filterPlugin = this.record.data;
jsonReturn.id = this.record.data.id;
}
jsonReturn.classVersion = filterPlugin.classVersion;
jsonReturn.classAuthor = filterPlugin.classAuthor;
jsonReturn.description = filterPlugin.description;
jsonReturn.filterClassName = filterPlugin.filterClassName;
jsonReturn.parent = filterPlugin.parent;
jsonReturn.className = filterPlugin.className;
var form = this.fieldMappingFormPanel.getForm();
if (!form.isValid()) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.invalidForm'));
return false;
}
Ext.iterate(form.getValues(), function (key, value) {
if (!Ext.isEmpty(value)) {
jsonReturn[key] = value;
}
});
var storeField = this.gridFieldMapping.getStore();
var re1 = new RegExp("^/.*$");
var re2 = new RegExp("^.*//.*$");
var re3 = new RegExp("^.*[!\"#$%&\'()*+,:;<=>?@\\`{}|~]+.*$");
for (var i = 0; i < storeField.getCount(); i++) {
var recTmp = storeField.getAt(i).data;
recTmp.violation = undefined;
if (recTmp.type == "PARAMETER_ATTACHMENT") {
var attach = recTmp.value;
var ok = re1.test(attach) && !re2.test(attach) && !re3.test(attach);
if (!ok) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('label.invalidAttachment') + " : " + attach);
}
}
parameters.push(recTmp);
}
jsonReturn.parameters = parameters;
var url = this.urlParent, method;
if (this.action == "modify") {
url += "/" + jsonReturn.id;
method = "PUT";
} else {
method = "POST";
}
Ext.Ajax.request({
url : url,
method : method,
scope : this,
jsonData : jsonReturn,
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (!data.success) {
if (Ext.isEmpty(data.message)) {
var violations = data.data;
this.notifyViolations(violations);
Ext.getCmp("statusBar").show();
} else {
Ext.Msg.alert(i18n.get('label.warning'),
data.message);
}
return false;
}
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('label.filterPlugin' + this.parentType + 'Saved'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
this.parentPanel.getStore().reload();
this.close();
},
failure : alertFailure
});
},
notifyViolations : function (violations) {
for (var i = 0; i < violations.length; i++) {
var violation = violations[i];
var store = this.gridFieldMapping.getStore();
var lineNb = store.findExact("name", violation.valueName);
var rec = store.getAt(lineNb);
rec.set("violation", violation);
}
this.gridFieldMapping.getView().refresh();
},
onClose : function () {
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, ImageChooser*/
Ext.namespace('sitools.component.filtersPlugins');
/**
* @param action
* create or modify
* @param parentPanel
* the parent panel
* @param urlfilters
* the filters url
* @param urlParent
* the parent object url
* @param parentType
* the type of the parent, string used only for i18n label
* @class sitools.component.filtersPlugins.filtersPluginsProp
* @extends Ext.Window
*/
sitools.component.filtersPlugins.filtersPluginsSingle = Ext.extend(Ext.Window, {
width : 700,
height : 500,
modal : true,
resizable : true,
classChosen : "",
filterPluginId : null,
modelClassName : null,
initComponent : function () {
this.title = this.action == "create" ? i18n.get('label.create' + this.parentType + 'Filter') : i18n.get('label.modify' + this.parentType + 'Filter');
var expander = new Ext.ux.grid.RowExpander({
tpl : new Ext.XTemplate(
'<tpl if="this.descEmpty(description)" ><div></div></tpl>',
'<tpl if="this.descEmpty(description) == false" ><div class="sitoolsDescription"><div class="sitoolsDescriptionHeader">Description : </div><p class="sitoolsDescriptionText"> {description} </p></div></tpl>',
{
compiled : true,
descEmpty : function (description) {
return Ext.isEmpty(description);
}
}),
expandOnDblClick : true
});
this.gridfilterPlugin = new Ext.grid.GridPanel({
viewConfig : {
forceFit : true
},
id : 'gridfilterPlugin',
title : i18n.get('title.filterPlugin' + this.parentType + 'Class'),
store : new Ext.data.JsonStore({
root : 'data',
restful : true,
proxy : new Ext.data.HttpProxy({
url : this.urlFilters,
restful : true,
method : 'GET'
}),
remoteSort : false,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'filterClassName',
type : 'string'
}, {
name : 'classAuthor',
type : 'string'
}, {
name : 'classVersion',
type : 'string'
}, {
name : 'parameters'
}, {
name : 'className',
type : 'string'
}, {
name : 'classOwner',
type : 'string'
}
]
}),
cm : new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ expander, {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100,
sortable : true
}, {
header : i18n.get('label.filterClassName'),
dataIndex : 'filterClassName',
width : 300,
sortable : true
}, {
header : i18n.get('label.author'),
dataIndex : 'classAuthor',
width : 100,
sortable : true
}, {
header : i18n.get('label.version'),
dataIndex : 'classVersion',
width : 100,
sortable : true
}, {
header : i18n.get('label.classOwner'),
dataIndex : 'classOwner',
width : 100,
sortable : true
} ]
}),
listeners : {
scope : this,
rowclick : this.onClassClick
},
plugins : expander
});
this.proxyFieldMapping = new Ext.data.HttpProxy({
url : "/tmp",
restful : true,
method : 'GET'
});
var expanderGridFieldMapping = new sitools.widget.ViolationRowExpander({
tpl : new Ext.XTemplate(
'<tpl if="this.descEmpty(description)" ><div></div></tpl>',
'<tpl if="this.descEmpty(description) == false" ><div class="sitoolsDescription"><div class="sitoolsDescriptionHeader">Description : </div><p class="sitoolsDescriptionText"> {description} </p></div></tpl>',
{
compiled : true,
descEmpty : function (description) {
return Ext.isEmpty(description);
}
}),
expandOnDblClick : false
});
this.gridFieldMapping = new Ext.grid.EditorGridPanel({
viewConfig : {
forceFit : true,
scope : this,
getRowClass : function (record, index, rowParams, store) {
var cls = '';
var violation = record.get("violation");
if (!Ext.isEmpty(violation)) {
if (violation.level == "CRITICAL") {
cls = "red-row";
} else if (violation.level == "WARNING") {
cls = "orange-row";
}
}
return cls;
},
listeners : {
scope : this,
refresh : function (view) {
var grid = this.gridFieldMapping;
var store = grid.getStore();
store.each(function (record) {
var violation = record.get("violation");
if (!Ext.isEmpty(violation)) {
var index = store.indexOf(record);
//var view = this.scope.gridFieldMapping.getView();
var htmlLineEl = view.getRow(index);
var el = Ext.get(htmlLineEl);
var cls = (violation.level == "CRITICAL")
? "x-form-invalid-tip"
: "x-form-invalid-tip x-form-warning-tip";
var ttConfig = {
html : violation.message,
dismissDelay : 0,
target : el,
cls : cls
};
var ttip = new Ext.ToolTip(ttConfig);
}
});
}
}
},
id : 'gridFieldMapping',
layout : 'fit',
region : 'center',
title : i18n.get('title.parametersMapping'),
store : new Ext.data.JsonStore({
root : 'filterPlugin.parameters',
proxy : this.proxyFieldMapping,
restful : true,
remoteSort : false,
idProperty : 'name',
fields : [ {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'type',
type : 'string'
}, {
name : 'value',
type : 'string'
}, {
name : 'valueType',
type : 'string'
}, {
name : 'violation'
}]
}),
bbar : new Ext.ux.StatusBar({
id: 'statusBar',
hidden : true,
iconCls: 'x-status-error',
text : i18n.get("label.filtersPluginErrorValidationNotification")
}),
cm : new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [expanderGridFieldMapping, {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100,
sortable : true
}, {
header : i18n.get('label.type'),
dataIndex : 'type',
width : 150,
sortable : false
}, {
header : i18n.get('label.value'),
dataIndex : 'value',
width : 230,
sortable : false,
editable : true,
editor : new Ext.form.TextField()
} ]
}),
plugins : expanderGridFieldMapping
});
// set the search form
this.fieldMappingFormPanel = new Ext.FormPanel({
height : 65,
frame : true,
defaultType : 'textfield',
items : [{
fieldLabel : i18n.get('label.name'),
name : 'name',
anchor : '100%'
}, {
fieldLabel : i18n.get('label.descriptionAction'),
name : 'descriptionAction',
anchor : '100%'
} ],
region : 'north'
});
this.fieldMappingPanel = new Ext.Panel({
layout : 'border',
id : 'fieldMappingPanel',
title : i18n.get('title.fieldMapping'),
items : [ this.fieldMappingFormPanel, this.gridFieldMapping ]
});
this.tabPanel = new Ext.TabPanel({
activeTab : 0,
items : (this.action == "create") ? [ this.gridfilterPlugin, this.fieldMappingPanel ] : [
this.fieldMappingPanel
],
buttons : [ {
text : this.action == "editDelete" ? i18n.get('label.ok') : i18n.get('label.add'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.delete'),
scope : this,
handler : this.onDelete,
hidden : this.action == "create"
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ],
listeners : {
scope : this,
beforetabchange : this.beforeTabChange
}
});
this.listeners = {
scope : this,
resize : function (window, width, height) {
var size = window.body.getSize();
this.tabPanel.setSize(size);
}
};
this.items = [ this.tabPanel ];
sitools.component.filtersPlugins.filtersPluginsSingle.superclass.initComponent.call(this);
},
beforeTabChange : function (self, newTab, currentTab) {
if (this.action == "create") {
if (newTab.id == "fieldMappingPanel") {
var rec = this.gridfilterPlugin.getSelectionModel().getSelected();
if (!rec) {
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('warning.noselection'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
return false;
}
}
}
},
onClassClick : function (self, rowIndex, e) {
if (this.action == "create") {
var rec = this.gridfilterPlugin.getSelectionModel().getSelected();
if (!rec) {
return false;
}
this.fillGridAndForm(rec.data, this.action);
}
},
afterRender : function () {
sitools.component.filtersPlugins.filtersPluginsSingle.superclass.afterRender.apply(this, arguments);
if (this.action == "editDelete") {
this.fillGridAndForm(this.filterPlugin, this.action);
} else {
//only need to load the filtersPlugins for creation
this.gridfilterPlugin.getStore().load();
}
this.tabPanel.setHeight(this.body.getHeight());
},
fillGridAndForm : function (filterPlugin, action) {
if (!Ext.isEmpty(filterPlugin)) {
var rec = {};
var form = this.fieldMappingFormPanel.getForm();
rec.name = filterPlugin.name;
rec.descriptionAction = filterPlugin.descriptionAction;
rec.id = filterPlugin.id;
rec.filterClassName = filterPlugin.filterClassName;
form.loadRecord(new Ext.data.Record(rec));
var parameters = filterPlugin.parameters;
var store = this.gridFieldMapping.getStore();
store.removeAll();
if (!Ext.isEmpty(parameters)) {
for (var i = 0; i < parameters.length; i++) {
var recTmp = new Ext.data.Record(parameters[i]);
if (action == "editDelete" && Ext.isEmpty(parameters[i].value)) {
recTmp.set("value", "");
}
store.add(recTmp);
}
}
}
},
onValidate : function () {
var rec;
var jsonReturn = {};
var parameters = [];
var filterPlugin;
if (this.action == "create") {
rec = this.gridfilterPlugin.getSelectionModel().getSelected();
if (!rec) {
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('warning.noselection'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
return false;
}
filterPlugin = rec.data;
} else {
filterPlugin = this.filterPlugin;
jsonReturn.id = this.filterPlugin.id;
}
jsonReturn.classVersion = filterPlugin.classVersion;
jsonReturn.classAuthor = filterPlugin.classAuthor;
jsonReturn.description = filterPlugin.description;
jsonReturn.filterClassName = filterPlugin.filterClassName;
jsonReturn.parent = filterPlugin.parent;
jsonReturn.className = filterPlugin.className;
jsonReturn.classOwner = filterPlugin.classOwner;
var form = this.fieldMappingFormPanel.getForm();
Ext.iterate(form.getValues(), function (key, value) {
if (!Ext.isEmpty(value)) {
jsonReturn[key] = value;
}
});
var storeField = this.gridFieldMapping.getStore();
var re1 = new RegExp("^/.*$");
var re2 = new RegExp("^.*//.*$");
var re3 = new RegExp("^.*[!\"#$%&\'()*+,:;<=>?@\\`{}|~]+.*$");
for (var i = 0; i < storeField.getCount(); i++) {
var recTmp = storeField.getAt(i).data;
recTmp.violation = undefined;
if (recTmp.type == "PARAMETER_ATTACHMENT") {
var attach = recTmp.value;
var ok = re1.test(attach) && !re2.test(attach) && !re3.test(attach);
if (!ok) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('label.invalidAttachment') + " : " + attach);
}
}
parameters.push(recTmp);
}
jsonReturn.parameters = parameters;
var url = this.urlParent, method;
if (this.action == "editDelete") {
url += "/filter";
method = "PUT";
} else {
method = "POST";
}
Ext.Ajax.request({
url : url,
method : method,
scope : this,
jsonData : jsonReturn,
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (!data.success) {
if (Ext.isEmpty(data.message)) {
var violations = data.data;
this.notifyViolations(violations);
Ext.getCmp("statusBar").show();
} else {
Ext.Msg.alert(i18n.get('label.warning'),
data.message);
}
return false;
}
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('label.filterPlugin' + this.parentType + 'Saved'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
this.parentPanel.getStore().reload();
this.close();
},
failure : alertFailure
});
},
notifyViolations : function (violations) {
for (var i = 0; i < violations.length; i++) {
var violation = violations[i];
var store = this.gridFieldMapping.getStore();
var lineNb = store.findExact("name", violation.valueName);
var rec = store.getAt(lineNb);
rec.set("violation", violation);
}
this.gridFieldMapping.getView().refresh();
},
onClose : function () {
},
onDelete : function () {
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('filtersPlugins' + this.parentType + 'Crud.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete();
}
}
});
},
doDelete : function (rec) {
Ext.Ajax.request({
url : this.urlParent,
method : 'DELETE',
scope : this,
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (showResponse(ret)) {
this.close();
}
},
failure : alertFailure
});
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, loadUrl
*/
/*
*@include "datasetsMultiTablesProp.js"
*@include "../../../public/js/env.js"
*/
Ext.namespace('sitools.component.fileEditor');
sitools.component.fileEditor.ftlEditorCrud = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.FILEEDITORFTL,
sm : new Ext.grid.RowSelectionModel({
singleSelect : true
}),
pageSize : 15,
initComponent : function () {
this.url = loadUrl.get('APP_URL') + loadUrl.get('APP_ADMINISTRATOR_URL');
this.iconCls = loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png';
this.store = new Ext.data.JsonStore({
root : 'items',
restful : true,
remoteSort : false,
url : this.url + '/ftl',
idProperty : 'name',
fields : [ {
name : 'name',
type : 'string',
mapping : 'name'
}, {
name : 'url',
type : 'string',
mapping : 'url'
}, {
name : 'lastModif',
type : 'date',
mapping : 'lastmod',
dateFormat : 'timestamp'
}, {
name : 'size',
type : 'int',
mapping : 'size'
} ]
});
this.cm = new Ext.grid.ColumnModel({
defaults : {
sortable : true
},
columns : [{
header : i18n.get('label.name'),
dataIndex : 'name',
width : 500,
sortable : true
},
{
header : i18n.get('label.size'),
dataIndex : 'size',
width : 100,
sortable : true
},
{
header : i18n.get('label.lastModif'),
dataIndex : 'lastModif',
width : 360,
sortable : true
}]
});
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [{
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this.onModify,
xtype : 's-menuButton'
}]
};
this.listeners = {
scope : this,
rowDblClick : this.onModify
};
sitools.component.fileEditor.ftlEditorCrud.superclass.initComponent.call(this);
},
onRender : function () {
sitools.component.fileEditor.ftlEditorCrud.superclass.onRender.apply(this, arguments);
this.store.load();
},
onModify : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var l = rec.data.name.length;
var from = l - 3;
var ftlProp;
if (rec.id.substring(from, l) == "txt") {
ftlProp = new sitools.component.fileEditor.fileEditorProp({
url : this.url + '/ftl/' + rec.id,
fileName : rec.id,
sourceEdit : false,
modalType : false,
mediaType : 'text/plain',
editable : true
});
ftlProp.show();
} else {
ftlProp = new sitools.component.fileEditor.fileEditorProp({
url : this.url + '/ftl/' + rec.id,
fileName : rec.id,
sourceEdit : true,
modalType : true,
mediaType : 'text/freemarker',
editable : false
});
ftlProp.show();
}
}
});
Ext.reg('s-ftlEditor', sitools.component.fileEditor.ftlEditorCrud);/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, loadUrl
*/
/*
*@include "datasetsMultiTablesProp.js"
*@include "../../../public/js/env.js"
*/
Ext.namespace('sitools.component.fileEditor');
sitools.component.fileEditor.cssEditorCrud = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.FILEEDITORCSS,
sm : new Ext.grid.RowSelectionModel({
singleSelect : true
}),
pageSize : 15,
initComponent : function () {
this.url = loadUrl.get('APP_URL') + loadUrl.get('APP_ADMINISTRATOR_URL');
this.iconCls = loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png';
this.store = new Ext.data.JsonStore({
root : 'items',
restful : true,
remoteSort : false,
url : this.url + '/css',
idProperty : 'name',
fields : [ {
name : 'name',
type : 'string',
mapping : 'name'
}, {
name : 'url',
type : 'string',
mapping : 'url'
}, {
name : 'lastModif',
type : 'date',
mapping : 'lastmod',
dateFormat : 'timestamp'
}, {
name : 'size',
type : 'int',
mapping : 'size'
} ]
});
this.cm = new Ext.grid.ColumnModel({
defaults : {
sortable : true
},
columns : [{
header : i18n.get('label.name'),
dataIndex : 'name',
width : 500,
sortable : true
},
{
header : i18n.get('label.size'),
dataIndex : 'size',
width : 100,
sortable : true
},
{
header : i18n.get('label.lastModif'),
dataIndex : 'lastModif',
width : 360,
sortable : true
}]
});
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this.onModify,
xtype : 's-menuButton'
} ]
};
this.listeners = {
scope : this,
rowDblClick : this.onModify
};
sitools.component.fileEditor.cssEditorCrud.superclass.initComponent.call(this);
},
onRender : function () {
sitools.component.fileEditor.cssEditorCrud.superclass.onRender.apply(this, arguments);
this.store.load();
},
onModify : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var cssProp = new sitools.component.fileEditor.fileEditorProp({
url : this.url + '/css/' + rec.id,
fileName : rec.id,
sourceEdit : true,
modalType : true,
mediaType : 'text/css',
editable : false
});
cssProp.show();
}
});
Ext.reg('s-cssEditor', sitools.component.fileEditor.cssEditorCrud);/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.component.fileEditor');
sitools.component.fileEditor.licenceEditorProp = Ext.extend(Ext.Panel, {
border : false,
height : 480,
id : ID.BOX.FILEEDITORLICENCE,
width : 700,
initComponent : function () {
this.url = loadUrl.get('APP_URL') + loadUrl.get('APP_ADMINISTRATOR_URL');
this.title = i18n.get('label.modifyLicence');
this.layout = 'fit';
var bToolBar = new Ext.Toolbar({
items : [ '->', {
xtype : 'button',
text : i18n.get('label.save'),
scope : this,
icon : '/sitools/common/res/images/icons/save.png',
handler : this.onValidate
} ]
});
this.bbar = bToolBar;
this.items = [{
xtype : 'htmleditor',
id : 'fileEditor',
autoScroll : true,
listeners : {
afterrender : function () {
this.syncValue();
}
}
}];
this.listeners = {
scope : this,
activate : function () {
this.findByType('htmleditor')[0].syncValue();
}
};
sitools.component.fileEditor.licenceEditorProp.superclass.initComponent.call(this);
},
onRender : function () {
sitools.component.fileEditor.licenceEditorProp.superclass.onRender.apply(this, arguments);
if (this.url) {
Ext.Ajax.request({
url : this.url + '/cgu.html',
method : 'GET',
scope : this,
success : function (ret) {
var data = ret.responseText;
this.findByType('htmleditor')[0].setValue(data);
},
failure : alertFailure
});
}
},
onValidate : function () {
var text = this.findByType('htmleditor')[0].getValue();
Ext.Ajax.request({
url : this.url + '/cgu.html',
method : 'PUT',
scope : this,
headers : {
'Content-Type' : 'text/html'
},
jsonData : text,
success : function (ret) {
var temp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('label.changeSaved'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
},
failure : alertFailure
});
}
});
Ext.reg('s-licenceEditor', sitools.component.fileEditor.licenceEditorProp);/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp*/
Ext.namespace('sitools.component.fileEditor');
sitools.component.fileEditor.fileEditorProp = Ext.extend(Ext.Window, {
width : 700,
height : 480,
mediaType : null,
initComponent : function () {
this.title = i18n.get('label.modifyFile') + this.fileName;
this.layout = 'fit';
this.modal = this.modalType;
var buttons;
if (this.modal === true) {
buttons = [ [{
text : i18n.get('label.save'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ] ];
} else {
buttons = [{
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ];
}
this.items = [{
xtype : 'panel',
layout : 'fit',
items : [{
xtype : 'htmleditor',
id : 'fileEditor',
readOnly : this.editable,
autoScroll : true,
listeners : {
afterrender : function () {
this.syncValue();
this.toggleSourceEdit(true);
}
}
}],
buttons : buttons
}];
this.listeners = {
scope : this,
activate : function () {
this.findByType('htmleditor')[0].syncValue();
this.findByType('htmleditor')[0].toggleSourceEdit(true);
}
};
sitools.component.fileEditor.fileEditorProp.superclass.initComponent.call(this);
},
onRender : function () {
sitools.component.fileEditor.fileEditorProp.superclass.onRender.apply(this, arguments);
if (this.url) {
Ext.Ajax.request({
url : this.url,
method : 'GET',
scope : this,
success : function (ret) {
var data = ret.responseText;
this.findByType('htmleditor')[0].setValue(data);
},
failure : alertFailure
});
}
},
onValidate : function () {
var text = this.findByType('htmleditor')[0].getValue();
Ext.Ajax.request({
url : this.url,
method : 'PUT',
scope : this,
headers : {
'Content-Type' : this.mediaType
},
jsonData : text,
success : function (ret) {
var temp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('label.changeSaved'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
this.close();
},
failure : alertFailure
});
}
});
Ext.reg('s-fileEditorProp', sitools.component.fileEditor.fileEditorProp);/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.component.logs');
sitools.component.logs.analogProp = Ext.extend(Ext.Panel, {
border : false,
height : 480,
id : "analogBoxId",
width : 700,
initComponent : function () {
this.url = loadUrl.get('APP_URL') + loadUrl.get('APP_ADMINISTRATOR_URL') + '/plugin/analog';
this.layout = 'fit';
this.tbar = new Ext.Toolbar({
items : [ {
xtype : 'button',
text : i18n.get('label.logGenerate'),
scope : this,
icon : '/sitools/common/res/images/icons/tree_application_plugin.png',
handler : this.refresh
} ]
});
var htmlReaderCfg = {
defaultSrc : this.url + '?_dc=' + new Date().getTime(),
id : 'log',
layout : "fit",
padding : 10
};
this.panLog = new Ext.ux.ManagedIFrame.Panel(htmlReaderCfg);
this.items = [this.panLog];
sitools.component.logs.analogProp.superclass.initComponent.call(this);
},
onGenerate : function () {
Ext.Ajax.request({
url : this.url,
method : 'PUT',
scope : this,
success : function (ret) {
var json = Ext.decode(ret.responseText);
if (!json.success) {
Ext.Msg.alert(i18n.get("label.warning"), json.message);
return;
}
var temp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('label.logsChanged'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
this.panLog.setSrc(this.url + '?_dc=' + new Date().getTime());
},
failure : alertFailure,
callback : function () {
Ext.getCmp('analogBoxId').getEl().unmask();
}
});
},
refresh : function () {
var myMask = new Ext.LoadMask(Ext.getCmp('analogBoxId').getEl(), {
msg : "Generating"
});
myMask.show();
this.onGenerate();
}
});
Ext.reg('s-analog', sitools.component.logs.analogProp);/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, loadUrl*/
Ext.namespace('sitools.component.storageFilters');
sitools.component.storageFilters.storageFiltersCrudPanel = Ext.extend(Ext.Panel, {
border : false,
height : 300,
layout : 'fit',
initComponent : function () {
var filterPluginstorage = new sitools.component.filtersPlugins.filtersPluginsCrudPanel({
urlParents : loadUrl.get('APP_URL') + loadUrl.get('APP_DATASTORAGE_ADMIN_URL') + '/directories',
filtersUrlPart : "/filters",
urlFilters : loadUrl.get('APP_URL') + loadUrl.get('APP_PLUGINS_FILTERS_CLASSES_URL'),
parentType : "storage"
});
this.items = [ filterPluginstorage ];
sitools.component.storageFilters.storageFiltersCrudPanel.superclass.initComponent.call(this);
}
});
Ext.reg('s-storage_filters', sitools.component.storageFilters.storageFiltersCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
/*
* @include "../def.js"
*/
Ext.namespace('sitools.admin.storageFilters');
/**
* A window that displays Storages properties.
*
* @cfg {string} url The url to Save the data
* @cfg {string} action The action should be modify or create
* @cfg {Ext.data.Store} store The storages store
* @class sitools.admin.storages.storageCopyProp
* @extends Ext.Window
*/
sitools.admin.storages.storageCopyProp = Ext.extend(Ext.Window, {
width : 230,
height : 130,
modal : true,
initComponent : function () {
this.title = i18n.get('label.storageCopy');
this.items = [{
xtype : 'form',
id : 'formCopyId',
layout : 'fit',
frame: false,
border: false,
buttonAlign: 'center',
bodyStyle: 'padding:15px 10px 15px 15px;',
items : [{
xtype : 'label',
text : i18n.get('label.destinationStorage')
},{
xtype : 'combo',
id: 'comboId',
fieldLabel: 'Name',
height : 30,
typeAhead : true,
triggerAction : 'all',
lazyRender : true,
store : this.store,
valueField : 'id',
displayField : 'name'
}]
}];
this.buttons = [
{
xtype : 'button',
iconAlign : 'right',
text : i18n.get('label.storageRunCopy'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/converter.png',
scope : this,
handler : this.runCopy
}];
sitools.admin.storages.storageCopyProp.superclass.initComponent.call(this);
},
runCopy : function () {
var f = Ext.getCmp('formCopyId').getForm();
var idDest = f.findField('comboId').getValue();
if (this.idSrc == idDest){
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.sameStorage'));
}
else {
Ext.Ajax.request({
url : this.urlDirectories + "/" + this.idSrc + "?action=copy&idDest=" + idDest,
method : 'PUT',
scope : this,
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (showResponse(ret)) {
this.store.reload();
}
this.close();
},
failure : alertFailure
});
}
}
});
Ext.reg('s-storage_copy', sitools.admin.storages.storageCopyProp);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, ann, mainPanel, helpUrl:true, loadUrl*/
Ext.namespace('sitools.admin.units');
/**
* A Panel to show all the dimensions in Sitools2
*
* @cfg {String} the urlAdmin where get the resource
* @cfg {Ext.data.JsonStore} the store where saved the dimensions data
* @class sitools.admin.units.unitsCrudPanel
* @extends Ext.grid.GridPanel
*/
//sitools.component.units.unitsCrudPanel = Ext.extend(Ext.grid.GridPanel, {
sitools.admin.units.unitsCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.UNITS,
pageSize : 10,
initComponent : function () {
this.urlAdmin = loadUrl.get('APP_URL') + loadUrl.get('APP_DIMENSIONS_ADMIN_URL');
this.httpProxy = new Ext.data.HttpProxy({
url : this.urlAdmin + "/dimension",
restful : true,
method : 'GET'
});
this.store = new Ext.data.JsonStore({
idProperty : 'id',
root : "data",
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'dimensionHelperName',
type : 'string'
}, {
name : 'unitConverters'
}, {
name : 'unitNames'
}, {
name : 'isConsistent',
type : 'boolean'
} ],
proxy : this.httpProxy
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 150
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 200,
sortable : false
}, {
header : i18n.get('label.dimensionHelperName'),
dataIndex : 'dimensionHelperName',
width : 300,
sortable : false
}, {
header : i18n.get('label.isConsistent'),
dataIndex : 'isConsistent',
width : 100,
sortable : false
} ]
});
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.add'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreate,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this.onModify,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDelete,
xtype : 's-menuButton'
} ]
};
this.bbar = {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
};
this.listeners = {
scope : this,
rowDblClick : this.onModify
};
sitools.admin.units.unitsCrudPanel.superclass.initComponent.call(this);
},
/**
* done a specific render to load dimensions from the store.
*/
onRender : function () {
sitools.admin.units.unitsCrudPanel.superclass.onRender.apply(this, arguments);
this.store.load({
params : {
start : 0,
limit : this.pageSize
}
});
},
/**
* Create a new {sitools.admin.units.unitsProp} unit prop to create a new dimension
*/
onCreate : function () {
var up = new sitools.admin.units.unitsProp({
action : 'create',
parent : this,
urlAdmin : this.urlAdmin
});
up.show();
},
/**
* Create a new {sitools.admin.units.unitsProp} unit prop to modify a dimension
*/
onModify : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var up = new sitools.admin.units.unitsProp({
action : 'modify',
record : rec,
parent : this,
urlAdmin : this.urlAdmin
});
up.show();
},
/**
* Diplay confirm delete Msg box and call the method doDelete
*/
onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('unitsCrud.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec);
}
}
});
},
/**
* done the delete of the passed record
* @param rec the record to delete
*/
doDelete : function (rec) {
Ext.Ajax.request({
url : this.urlAdmin + "/dimension/" + rec.id,
method : 'DELETE',
scope : this,
success : function (ret) {
var Json = Ext.decode(ret.responseText);
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
}
});
Ext.reg('s-units', sitools.admin.units.unitsCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, ann, mainPanel, helpUrl:true, loadUrl*/
Ext.namespace('sitools.admin.units');
/**
* A Panel to show dimension data from a specific dimension
*
* @cfg {String} the action to perform
* @cfg {sitools.admin.units.unitsCrudPanel} the parent
* @cfg {String} the urlAdmin
* @class sitools.admin.units.unitsProp
* @extends Ext.Window
*/
//sitools.component.units.unitsProp = Ext.extend(Ext.Window, {
sitools.admin.units.unitsProp = Ext.extend(Ext.Window, {
width : 700,
height : 480,
modal : true,
resizable : false,
classChosen : "",
unitsId : null,
helperName : null,
initComponent : function () {
this.title = this.action == "create" ? i18n.get('label.createUnits') : i18n.get('label.modifyUnits');
this.gridHelper = new Ext.grid.GridPanel({
viewConfig : {
forceFit : true
},
id : 'gridHelper',
title : i18n.get('title.unitsHelperClass'),
store : new Ext.data.JsonStore({
root : 'data',
restful : true,
proxy : new Ext.data.HttpProxy({
url : this.urlAdmin + "/unithelpers",
restful : true,
method : 'GET'
}),
remoteSort : false,
idProperty : 'id',
fields : [ {
name : 'helperName',
type : 'string'
} ],
autoLoad : true
}),
cm : new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.helperName'),
dataIndex : 'helperName',
width : 100,
sortable : true
} ]
})/*,
listeners : {
scope : this,
cellclick : this.onClassClick
}*/
});
this.formPanel = new Ext.FormPanel({
padding : 10,
id : 'formPanel',
defaultType : 'textfield',
title : i18n.get('title.unitsDetails'),
items : [ {
fieldLabel : i18n.get('label.name'),
name : 'name',
anchor : '100%',
allowBlank : false
}, {
fieldLabel : i18n.get('label.description'),
name : 'description',
anchor : '100%'
} ]
});
// ---------------- CONVERTERS GRID
// Creation de la grid des tables d'une datasource
this.storeConvertersFromHelper = new Ext.data.JsonStore({
root : "data.converters",
fields : [ {
name : 'name',
type : 'string'
}]
});
this.cmConvertersFromHelper = new Ext.grid.ColumnModel({
columns : [ {
id : 'name',
header : i18n.get('headers.name'),
width : 500,
sortable : true,
dataIndex : 'name'
} ]
});
this.gridConvertersFromHelper = new Ext.grid.GridPanel({
layout : 'fit',
store : this.storeConvertersFromHelper,
cm : this.cmConvertersFromHelper,
sm : new Ext.grid.RowSelectionModel({}),
enableDragDrop : true,
stripeRows : true,
title : i18n.get("title.convertersFromHelper")
});
// Creation de la grid des tables du dataset
var cmConvertersForDimension = new Ext.grid.ColumnModel({
columns : [ {
id : 'name',
header : i18n.get('headers.name'),
width : 500,
sortable : true,
dataIndex : 'name'
} ]
});
this.storeConvertersForDimension = new Ext.data.JsonStore({
fields : [ {
name : 'name',
type : 'string'
} ]
});
this.gridConverters = new Ext.grid.EditorGridPanel({
layout : 'fit',
store : this.storeConvertersForDimension,
cm : cmConvertersForDimension,
sm : new Ext.grid.RowSelectionModel({}),
autoScroll : true,
enableDragDrop : true,
stripeRows : true,
title : i18n.get("title.convertersForDimension")
});
var displayPanelConverters = new sitools.component.datasets.selectItems({
grid1 : this.gridConvertersFromHelper,
grid2 : this.gridConverters,
defaultRecord : {}
});
this.gridChooseConverters = new Ext.Panel({
title : i18n.get('label.gridConverters'),
layout : 'fit',
items : [ displayPanelConverters ],
listeners : {
scope : this,
activate : function () {
this.loadConverters();
}
}
});
// colonne avec checkbox pour choisir quelles colonnes indexer
/*var indexed = new Ext.grid.CheckColumn({
header : i18n.get('header.selected'),
dataIndex : 'selected',
width : 60
});
// définition des plugins nécessaires (colonnes avec checkbox )
var plugins = [ indexed ];
this.gridConverters = new Ext.grid.EditorGridPanel({
viewConfig : {
forceFit : true
},
plugins : plugins,
id : 'gridFieldMapping',
layout : 'fit',
title : i18n.get('title.parametersMapping'),
store : new Ext.data.JsonStore({
idProperty : 'name',
fields : [ {
name : 'name',
type : 'string'
}, {
name : 'selected',
type : 'boolean'
}],
autoLoad : false
}),
cm : new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 100,
sortable : true
}, indexed ]
})
});*/
//------------------- UNITS GRID
this.gridUnit = new Ext.grid.EditorGridPanel({
id : 'gridUnit',
title : i18n.get('title.gridUnit'),
store : new Ext.data.JsonStore({
idProperty : 'name',
fields : [ {
name : 'label',
type : 'string'
}, {
name : 'unitName',
type : 'string'
}]
}),
tbar : {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreateUnit
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDeleteUnit
} ]
},
cm : new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'label',
width : 250,
editor : new Ext.form.TextField({
allowBlank : false
})
}, {
header : i18n.get('label.unit'),
dataIndex : 'unitName',
width : 250,
editor : new Ext.form.TextField({
allowBlank : false
})
} ],
autoLoad : false
}),
sm : new Ext.grid.RowSelectionModel({
singleSelect : true
})
});
this.tabPanel = new Ext.TabPanel({
height : 450,
activeTab : 0,
items : (this.action == "create") ? [ this.gridHelper, this.formPanel, this.gridChooseConverters, this.gridUnit ] : [
this.formPanel, this.gridChooseConverters, this.gridUnit
],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this.onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ],
listeners : {
scope : this,
beforetabchange : this.beforeTabChange
}
});
this.items = [ this.tabPanel ];
sitools.admin.units.unitsProp.superclass.initComponent.call(this);
},
beforeTabChange : function (self, newTab, currentTab) {
if (this.action == "create") {
if (newTab.id == "fieldMappingFormPanel" || newTab.id == "gridFieldMapping") {
var rec = this.gridHelper.getSelectionModel().getSelected();
if (!rec) {
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('warning.noselection'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
return false;
}
}
}
},
/*onClassClick : function (self, rowIndex, columnIndex, e) {
if (this.action == "create") {
var rec = this.gridHelper.getSelectionModel().getSelected();
if (!rec) {
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('warning.noselection'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
return false;
}
//fill in the converter grid
var converterStore = this.gridConverters.getStore();
converterStore.removeAll();
Ext.each(rec.data.converters, function (record) {
var conv = {};
conv.name = record;
conv.selected = true;
converterStore.add(new Ext.data.Record(conv));
});
}
},*/
/**
* Set the dimension information if the action is "modify"
*/
afterRender : function () {
sitools.admin.units.unitsProp.superclass.afterRender.apply(this, arguments);
if (this.action == "modify") {
this.unitsId = this.record.data.id;
Ext.Ajax.request({
url : this.urlAdmin + "/dimension/" + this.unitsId,
method : 'GET',
scope : this,
success : function (ret) {
var json = Ext.decode(ret.responseText);
if (!json.success) {
Ext.Msg.alert(i18n.get('label.warning'), json.message);
return false;
}
this.fillFormAndGrids(json.dimension);
},
failure : alertFailure
});
}
},
/**
* Fill the properties fields of the dimension
* @param unit to fill the dimension with
*/
fillFormAndGrids : function (unit) {
var form = this.formPanel.getForm();
if (!Ext.isEmpty(unit)) {
//helperName
this.helperName = unit.dimensionHelperName;
//form
var rec = {};
rec.name = unit.name;
rec.description = unit.description;
form.loadRecord(new Ext.data.Record(rec));
//converters
var converters = unit.unitConverters;
if (!Ext.isEmpty(converters)) {
var storeConverter = this.gridConverters.getStore();
for (var i = 0; i < converters.length; i++) {
var converter = {};
converter.name = converters[i];
storeConverter.add(new Ext.data.Record(converter));
}
}
//units
//converters
var units = unit.sitoolsUnits;
if (!Ext.isEmpty(units)) {
var storeUnit = this.gridUnit.getStore();
for (var j = 0; j < units.length; j++) {
var unitTmp = {};
unitTmp.label = units[j].label;
unitTmp.unitName = units[j].unitName;
storeUnit.add(new Ext.data.Record(unitTmp));
}
}
}
},
/**
* Load Converters into store
*/
loadConverters : function () {
var helperName;
if (this.action == "create") {
var record = this.gridHelper.getSelectionModel().getSelected();
if (!record) {
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('warning.noselection'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
return false;
}
helperName = record.data.helperName;
} else {
helperName = this.helperName;
}
var url = this.urlAdmin + "/unithelpers/" + helperName;
this.gridConvertersFromHelper.getStore().removeAll();
Ext.Ajax.request({
url : url,
method : "GET",
scope : this,
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (!data.success) {
Ext.Msg.alert(i18n.get('label.warning'),
data.message);
return false;
}
var converters = data.dimensionHelper.converters;
if (!Ext.isEmpty(converters)) {
var storeConverter = this.gridConvertersFromHelper.getStore();
for (var i = 0; i < converters.length; i++) {
var converter = {};
converter.name = converters[i];
storeConverter.add(new Ext.data.Record(converter));
}
}
},
failure : alertFailure
});
},
/**
* Create dimension from selected converters
*/
onValidate : function () {
var rec;
var jsonReturn = {};
if (this.action == "create") {
rec = this.gridHelper.getSelectionModel().getSelected();
if (!rec) {
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('warning.noselection'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
return false;
}
jsonReturn.dimensionHelperName = rec.data.helperName;
} else {
jsonReturn.id = this.unitsId;
jsonReturn.dimensionHelperName = this.helperName;
}
var form = this.formPanel.getForm();
if (!form.isValid()) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('warning.invalidForm'));
return false;
}
Ext.iterate(form.getFieldValues(), function (key, value) {
jsonReturn[key] = value;
});
//converters
jsonReturn.unitConverters = [];
var storeConverters = this.gridConverters.getStore();
for (var i = 0; i < storeConverters.getCount(); i++) {
var recTmp = storeConverters.getAt(i);
jsonReturn.unitConverters.push(recTmp.data.name);
}
//units
jsonReturn.units = [];
var storeUnits = this.gridUnit.getStore();
for (i = 0; i < storeUnits.getCount(); i++) {
var unit = storeUnits.getAt(i).data;
jsonReturn.units.push(unit);
}
var url = this.urlAdmin + "/dimension", method;
if (this.action == "modify") {
url += "/" + this.unitsId;
method = "PUT";
} else {
method = "POST";
}
Ext.Ajax.request({
url : url,
method : method,
scope : this,
jsonData : jsonReturn,
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (!data.success) {
Ext.Msg.alert(i18n.get('label.warning'),
data.message);
return false;
}
var tmp = new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get('label.unitsSaved'),
autoDestroy : true,
hideDelay : 1000
}).show(document);
this.parent.getStore().reload();
this.close();
},
failure : alertFailure
});
},
onClose : function () {
},
/**
* Create a new {Ext.data.Record} record to add a unit property
*/
onCreateUnit : function () {
this.gridUnit.getStore().add(new Ext.data.Record());
},
/**
* Delete the selected unit property
*/
onDeleteUnit : function () {
var grid = this.gridUnit;
var rec = grid.getSelectionModel().getSelected();
if (!rec) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
return;
}
grid.getStore().remove(rec);
}
});/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.admin.datasets');
/**
* A window to determine the mapping between dataset columns and dictionnary concept
* @cfg string url The Url to request the dataset.
* @cfg boolean masked false to allowed modification true to disable any modification.
* @class sitools.admin.datasets.DicoMapping
* @extends Ext.Window
*/
//sitools.component.datasets.DicoMapping = Ext.extend(Ext.Window, {
sitools.admin.datasets.DicoMapping = Ext.extend(Ext.Window, {
width : 800,
height : 680,
modal : true,
resizable : true,
urlDataset : null,
layout : 'vbox',
dictionaryId : null,
isModified : false,
urlMappingPart : "/mappings",
layoutConfig : {
align : 'stretch',
pack : 'start'
},
initComponent : function () {
this.urlDictionaries = loadUrl.get('APP_URL') + loadUrl.get('APP_DICTIONARIES_URL');
this.title = i18n.get("title.dicoMapping");
this.urlDataset = this.url;
/** ###################################### */
/** Dataset column grid */
/** ###################################### */
var storeDatasetColumns = new Ext.data.JsonStore({
root : 'dataset.columnModel',
idProperty : 'id',
remoteSort : false,
url : this.urlDataset,
autoLoad : true,
restful : true,
fields : [{
name : 'id',
type : 'string'
}, {
name : 'columnAlias',
type : 'string'
}]
});
var cmDatasetColumns = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : false
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.columnAlias'),
dataIndex : 'columnAlias',
sortable : true
} ]
});
this.gridDatasetColumn = new Ext.grid.GridPanel({
store : storeDatasetColumns,
cm : cmDatasetColumns,
flex : 1,
title : i18n.get("label.datasetColumn"),
viewConfig : {
forceFit : true,
autoFill : true
},
listeners : {
scope : this,
mappingsSelected : function (grid, columnsId) {
var selModel = grid.getSelectionModel();
selModel.clearSelections();
var records = [];
Ext.each(columnsId, function (columnId) {
records.push(grid.getStore().getById(columnId));
});
selModel.selectRecords(records);
}
}
// ,
// sm : new Ext.grid.RowSelectionModel({
// listeners : {
// scope : this,
// rowselect : this.gridColumnRowSelectionModelListener,
// rowdeselect : this.gridColumnRowSelectionModelListener
// }
// })
});
/** ###################################### */
/** Dictionnaries combo box and GRID */
/** ###################################### */
var storeDictionaries = new Ext.data.JsonStore({
fields : [ 'id', 'name', 'conceptTemplate' ],
url : this.urlDictionaries,
root : "data",
autoLoad : true
});
this.comboDictionaries = new Ext.form.ComboBox({
store : storeDictionaries,
displayField : 'name',
valueField : 'id',
typeAhead : true,
mode : 'local',
forceSelection : true,
triggerAction : 'all',
emptyText : i18n.get('label.selectDictionary'),
selectOnFocus : true,
listeners : {
scope : this,
select : function (combo, rec, index) {
this.isModified = false;
this.createDictionaryConceptGrid(rec);
}
}
});
//temporary definition of gridDictionaryConcept to display the title
this.gridDictionaryConcept = new Ext.Panel({
id : 'gridDictionaryConcept',
flex : 2,
title : i18n.get("label.dictionaryConcepts")
});
this.checkboxDefaultDictionary = new Ext.form.Checkbox({
name : 'defaultDico',
boxLabel: i18n.get("label.defaultDictionary"),
anchor : '100%',
maxLength : 100,
disabled : this.masked
});
this.choicePanel = new Ext.Panel({
items : [this.gridDatasetColumn, this.gridDictionaryConcept],
flex : 1,
layout : "hbox",
layoutConfig : {
align : 'stretch',
pack : 'start'
},
tbar : {
xtype : 'toolbar',
defaults : {
scope : this,
xtype : 's-menuButton'
},
items : [this.comboDictionaries, '-',
{
xtype: 'tbspacer',
width : '5'
}, this.checkboxDefaultDictionary, '-'
, {
text : i18n.get('label.save'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/save.png',
handler : function () {
this.onValidate(false);
},
disabled : this.masked
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDelete,
disabled : this.masked
}]
},
listeners : {
scope : this,
afterrender : function () {
if (this.masked) {
this.choicePanel.body.mask();
}
}
}
});
/** ###################################### */
/** Concepts Mapping */
/** ###################################### */
var storeMapping = new Ext.data.JsonStore({
root : 'ColumnModel',
idProperty : 'concatColConcept',
remoteSort : false,
url : this.urlConcepts,
restful : true,
fields : [{
name : 'concatColConcept',
type : 'string'
}, {
name : 'columnId',
type : 'string'
}, {
name : 'conceptsId'
}, {
name : 'conceptName'
}]
});
var cmMapping = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : false
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.columnAlias'),
dataIndex : 'columnId',
width : 100,
sortable : true
}, {
header : i18n.get('label.conceptName'),
dataIndex : 'conceptName',
width : 100,
sortable : true
} ]
});
//temporary definition of gridMapping to diplay the title
this.gridMapping = new Ext.Panel({
flex : 1,
title : i18n.get("label.mappingConceptColumn"),
listeners : {
scope : this,
afterrender : function () {
if (this.masked) {
this.gridMapping.getEl().mask();
}
}
}
});
this.items = [this.choicePanel, this.gridMapping];
this.buttons = [ {
text : i18n.get('label.saveAndClose'),
scope : this,
handler : this.onValidateAndQuit,
disabled : this.masked
}, {
text : i18n.get('label.close'),
scope : this,
handler : function () {
this.close();
}
}];
sitools.admin.datasets.DicoMapping.superclass.initComponent.call(this);
},
//##############################################
//Create Grids
//##############################################
/**
* Create the dictionnary concept grid
* @param Ext.data.Record rec
*/
createDictionaryConceptGrid : function (rec) {
//refresh dico grid
this.dictionaryId = rec.data.id;
var templateConcept = rec.data.conceptTemplate;
this.gridDictionaryConcept = new sitools.component.dictionary.gridPanel({
template : templateConcept,
editable : false,
url : this.urlDictionaries + "/" + this.dictionaryId,
id : 'gridDictionaryConcept',
sm : new Ext.grid.RowSelectionModel(),
flex : 2,
title : i18n.get("label.dictionaryConcepts"),
enableColumnResize : true,
listeners : {
scope : this,
mappingsSelected : function (grid, conceptsId) {
var selModel = grid.getSelectionModel();
selModel.clearSelections();
var records = [];
Ext.each(conceptsId, function (conceptId) {
records.push(grid.getStore().getById(conceptId));
});
selModel.selectRecords(records);
}
}
});
this.choicePanel.remove('gridDictionaryConcept');
this.choicePanel.add(this.gridDictionaryConcept);
var store = this.gridDictionaryConcept.getStore();
store.removeAll();
store.on("load", function () {
//refresh mapping grid
this.createMappingGrid();
this.loadMapping();
this.doLayout();
}, this);
store.loadConcepts();
},
/**
* Create the mapping grid
* @method
*/
createMappingGrid : function () {
var store = this.gridDictionaryConcept.getStore();
var fieldsDicoConcept = store.fields;
var fields = [];
fieldsDicoConcept.each(function (record) {
fields.push({
name : record.name,
type : record.type.type
});
});
fields.push({
name : 'columnAlias',
type : 'string'
});
fields.push({
name : 'columnId',
type : 'string'
});
fields.push({
name : 'idMapping',
type : 'string'
});
var reader = new Ext.data.JsonReader({
fields : fields,
idProperty : 'idMapping'
});
var storeMapping = new Ext.data.GroupingStore({
reader : reader,
remoteSort : false,
fields : fields,
sortInfo: {field: 'columnAlias', direction: 'ASC'},
listeners : {
scope : this,
add : function (store, records, index) {
if (this.isModified && !this.comboDictionaries.disabled) {
this.comboDictionaries.disable();
}
},
remove : function (store, records, index) {
if (this.isModified && !this.comboDictionaries.disabled) {
this.comboDictionaries.disable();
}
}
},
groupField: 'columnAlias'
});
var cmConfig = this.gridDictionaryConcept.getColumnModel().config;
var cmConfigNew = cmConfig.clone();
// Ext.each(cmConfigNew, function (col) {
// col.resizable = true;
// });
cmConfigNew.push(new Ext.grid.Column({
header : i18n.get('label.columnAlias'),
dataIndex : 'columnAlias',
width : 100,
sortable : true,
hidden : true,
resizable : true
}));
var cmMapping = new Ext.grid.ColumnModel(cmConfigNew);
this.remove(this.gridMapping);
this.gridMapping = new Ext.grid.GridPanel({
store : storeMapping,
cm : cmMapping,
flex : 1,
title : i18n.get("label.mappingConceptColumn"),
tbar : {
xtype : 'toolbar',
defaults : {
scope : this,
xtype : 's-menuButton'
},
items : [ {
text : i18n.get('label.map'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onAddMapping
}, {
text : i18n.get('label.unmap'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onRemoveMapping
}]
},
view : new Ext.grid.GroupingView({
groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})',
autoFill : true
}),
listeners : {
scope : this,
afterrender : function () {
if (this.masked) {
this.gridMapping.getEl().mask();
}
}
},
// listeners : {
// scope : this,
// columnSelected : function (grid, columnsId) {
// var selModel = grid.getSelectionModel();
// selModel.clearSelections();
// var records = [];
// Ext.each(columnsId, function (columnId) {
// var index = grid.getStore().find("columnId", columnId);
// if (index != -1) {
// records.push(grid.getStore().getAt(index));
// }
// });
// selModel.selectRecords(records);
// }
// },
sm : new Ext.grid.RowSelectionModel({
listeners : {
scope : this,
rowselect : this.gridMappingRowSelectionModelListener,
rowdeselect : this.gridMappingRowSelectionModelListener
}
})
});
this.add(this.gridMapping);
},
/**
* @method called when select or deselect a mapping.
* @param Ext.grid.RowSelectionModel sm
* @param Number rowIndex
* @param Ext.data.Record record
*/
gridMappingRowSelectionModelListener : function (sm, rowIndex, record) {
var records = sm.getSelections();
var columnsId = [];
var conceptsId = [];
Ext.each(records, function (rec) {
columnsId.push(rec.get("columnId"));
conceptsId.push(rec.get("id"));
});
this.gridDatasetColumn.fireEvent('mappingsSelected', this.gridDatasetColumn, columnsId);
this.gridDictionaryConcept.fireEvent('mappingsSelected', this.gridDictionaryConcept, conceptsId);
},
// gridColumnRowSelectionModelListener : function (sm, rowIndex, record) {
// var records = sm.getSelections();
// var columnsId = [];
// Ext.each(records, function (rec) {
// columnsId.push(rec.get("id"));
// });
// this.gridMapping.fireEvent('columnSelected', this.gridMapping, columnsId);
// },
//##############################################
//Actions
//##############################################
/**
* @method
* Execute onValidate
*/
onValidateAndQuit : function () {
this.onValidate(true);
},
/**
* build the json object and call the request to save the mapping.
* @param boolean quit
*/
onValidate : function (quit) {
var jsonObject = {};
if (Ext.isEmpty(this.dictionaryId)) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noSelection.dicoMapping'));
return;
}
jsonObject.dictionaryId = this.dictionaryId;
jsonObject.defaultDico = this.checkboxDefaultDictionary.getValue();
jsonObject.mapping = [];
var storeMapping = this.gridMapping.getStore();
storeMapping.each(function (mapping) {
var rec = {
columnId : mapping.get("columnId"),
conceptId : mapping.get("id")
};
jsonObject.mapping.push(rec);
});
Ext.Ajax.request({
url : this.urlDataset + this.urlMappingPart + "/"
+ this.dictionaryId,
method : 'PUT',
jsonData : jsonObject,
scope : this,
success : function (ret) {
var json = Ext.decode(ret.responseText);
if (!json.success) {
Ext.Msg.alert(i18n.get('label.warning'),
json.message);
return;
}
this.loadMappingData(json.dictionaryMapping);
new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get("dictionary.mapping.saved"),
autoDestroy : true,
hideDelay : 1000
}).show(document);
if (quit) {
this.close();
}
},
failure : alertFailure
});
},
/**
* check if the delete Action is possible and call doDelete().
* @method
*/
onDelete : function () {
if (Ext.isEmpty(this.dictionaryId)) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
return;
}
Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('dictionaryMapping.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete();
}
}
});
},
/**
* Invoke a delete method on the mapping.
* @method
*/
doDelete : function () {
Ext.Ajax.request({
url : this.urlDataset + this.urlMappingPart + "/"
+ this.dictionaryId,
method : 'DELETE',
scope : this,
success : function (ret) {
var json = Ext.decode(ret.responseText);
if (!json.success) {
Ext.Msg.alert(i18n.get('label.warning'),
json.message);
return;
}
new Ext.ux.Notification({
iconCls : 'x-icon-information',
title : i18n.get('label.information'),
html : i18n.get("dictionary.mapping.deleted"),
autoDestroy : true,
hideDelay : 1000
}).show(document);
this.loadMappingData();
},
failure : alertFailure
});
},
/**
* Load the data already saved for that dictionary
*/
loadMapping : function () {
Ext.Ajax.request({
url : this.urlDataset + this.urlMappingPart + "/"
+ this.dictionaryId,
method : 'GET',
scope : this,
success : function (ret) {
var json = Ext.decode(ret.responseText);
if (json.success) {
//fill the mapping grid
var dictionaryMapping = json.dictionaryMapping;
this.loadMappingData(dictionaryMapping);
} else {
this.checkboxDefaultDictionary.setValue(false);
return;
}
},
failure : alertFailure
});
},
/**
* load the gridMappingStore with the dictionnary mapping info
* @param {} dictionaryMapping
*/
loadMappingData : function (dictionaryMapping) {
var defaultDico = (dictionaryMapping.defaultDico === true) ? true : false;
this.checkboxDefaultDictionary.setValue(defaultDico);
this.isModified = false;
this.comboDictionaries.enable();
var storeColumn = this.gridDatasetColumn.getStore();
var storeConcept = this.gridDictionaryConcept.getStore();
var storeGridMapping = this.gridMapping.getStore();
storeGridMapping.removeAll();
var mappings = dictionaryMapping.mapping;
if (Ext.isEmpty(mappings)) {
return;
}
Ext.each(mappings, function (mapDetails) {
var column = storeColumn.getById(mapDetails.columnId);
var concept = storeConcept.getById(mapDetails.conceptId);
var idNewRec = column.get('columnAlias') + concept.get('id');
var rec = {
idMapping : idNewRec,
columnAlias : column.get('columnAlias'),
columnId : column.get('id')
};
Ext.iterate(concept.data, function (key, value) {
rec[key] = value;
});
storeGridMapping.add(new Ext.data.Record(rec, rec.idMapping));
});
storeGridMapping.sort();
},
/**
* Called when click on add mapping button.
* @method
*
*/
onAddMapping : function () {
// first let's loop on the column grid to get all the selected rows
var columnSelected = this.gridDatasetColumn.getSelectionModel().getSelections();
//then loop on the concept grid to get all the selected rows
var conceptSelected = this.gridDictionaryConcept.getSelectionModel().getSelections();
var storeGridMapping = this.gridMapping.getStore();
//calculate all the combination and create records on the mapping grid
Ext.each(columnSelected, function (column) {
Ext.each(conceptSelected, function (concept) {
var idNewRec = column.get('columnAlias') + concept.get('id');
if (Ext.isEmpty(storeGridMapping.getById(idNewRec))) {
var rec = {
idMapping : idNewRec,
columnAlias : column.get('columnAlias'),
columnId : column.get('id')
};
Ext.iterate(concept.data, function (key, value) {
rec[key] = value;
});
this.isModified = true;
storeGridMapping.add(new Ext.data.Record(rec, rec.idMapping));
}
}, this);
}, this);
if (this.isModified) {
storeGridMapping.sort();
}
},
/**
* called when click on remove mapping button.
* @method
*/
onRemoveMapping : function () {
var grid = this.gridMapping;
var mappingSelected = grid.getSelectionModel().getSelections();
if (mappingSelected.length === 0) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
return;
}
this.isModified = true;
grid.getStore().remove(mappingSelected);
this.gridDatasetColumn.getSelectionModel().clearSelections();
this.gridDictionaryConcept.getSelectionModel().clearSelections();
grid.getStore().sort();
}
});
Ext.reg('s-DicoMapping', sitools.admin.datasets.DicoMapping);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp*/
Ext.namespace('sitools.component.dictionary.gridPanel');
/**
* @param template
* the dictionary template
* @param editable
* true if the grid is editable, false otherwise
* @param url
* the url of the store
* @class sitools.component.dictionary.gridPanel
* @extends Ext.grid.GridPanel
*/
sitools.component.dictionary.gridPanel = Ext.extend(Ext.grid.EditorGridPanel, {
template : null,
initComponent : function () {
this.store = this.getStoreConcepts(this.template, this.url);
this.cm = this.getColumnModelConcepts(this.template, this.editable);
sitools.component.dictionary.gridPanel.superclass.initComponent.call(this);
},
getStoreConcepts : function (template, url) {
var fields = [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
} ];
for (var i = 0; i < template.properties.length; i++) {
var property = template.properties[i];
fields.push({
name : property.name,
type : 'string'
});
}
var storeConcept = new Ext.data.JsonStore({
idProperty : 'id',
fields : fields,
url : url,
// on surchage la fonction load
loadConcepts : function (options) {
Ext.Ajax.request({
url : this.url,
method : 'GET',
scope : this,
success : function (ret) {
var data = Ext.decode(ret.responseText).dictionary;
var nbConcepts = 0;
if (!Ext.isEmpty(data.concepts)) {
for (i = 0; i < data.concepts.length; i++) {
nbConcepts++;
var conceptIn = data.concepts[i];
var conceptOut = {
id : conceptIn.id,
name : conceptIn.name,
description : conceptIn.description
};
for (var j = 0; j < conceptIn.properties.length; j++) {
var property = conceptIn.properties[j];
conceptOut[property.name] = property.value;
}
var rec = new Ext.data.Record(conceptOut, conceptOut.id);
this.add(rec);
}
}
this.fireEvent("load", this);
},
failure : alertFailure
});
}
});
return storeConcept;
},
getColumnModelConcepts : function (template, editable) {
var columns = [];
columns.push(this.createColumn(i18n.get("headers.name"), 'name', 100,
editable, false));
columns.push(this.createColumn(i18n.get("headers.description"), 'description', 120,
editable, true));
for (var i = 0; i < template.properties.length; i++) {
var property = template.properties[i];
columns.push(this.createColumn(property.name, property.name, 80,
editable, true));
}
var cmConcepts = new Ext.grid.ColumnModel({
columns : columns,
defaults : {
sortable : true,
width : 100,
editor : new Ext.form.TextField({
allowBlank : false
})
}
});
return cmConcepts;
},
createColumn : function (header, dataIndex, width, editable, allowBlank) {
var column = {
header : header,
dataIndex : dataIndex,
width : width,
editor : (editable === true) ? (new Ext.form.TextField({
allowBlank : allowBlank
})) : null
};
return column;
},
getProxy : function () {
return this.proxyGrid;
}
});
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.admin.projects.modules');
/**
* A Panel to show project module properties from a specific project
*
* @cfg {String} the url where get the resource
* @cfg {String} the action to perform (modify or create)
* @cfg {Ext.data.JsonStore} the store where get the record
* @class sitools.admin.projects.modules.ProjectModulePropPanel
* @extends Ext.Window
*/
//sitools.component.projects.modules.ProjectModulePropPanel = Ext.extend(Ext.Window, {
sitools.admin.projects.modules.ProjectModulePropPanel = Ext.extend(Ext.Window, {
width : 700,
height : 540,
modal : true,
id : ID.PROP.PROJECTMODULE,
layout : 'fit',
initComponent : function () {
if (this.action == 'create') {
this.title = i18n.get('label.createProjectModule');
} else if (this.action == 'modify') {
this.title = i18n.get('label.modifyProjectModule');
}
var storeDependencies = new Ext.data.JsonStore({
fields : [ {
name : 'url',
type : 'string'
}],
autoLoad : false
});
var tbar = {
xtype : 'sitools.widget.GridSorterToolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this.onCreateDependencies
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this.onDeleteDependencies
}]
};
this.gridDependencies = new Ext.grid.EditorGridPanel({
title : i18n.get('title.dependencies'),
height : 180,
store : storeDependencies,
tbar : tbar,
cm : new Ext.grid.ColumnModel({
columns : [ {
header : i18n.get('label.url'),
dataIndex : 'url',
editor : new Ext.form.TextField({
allowBlank : false
})
} ]
}),
sm : new Ext.grid.RowSelectionModel({
singleSelect : true
}),
viewConfig : {
forceFit : true
}
});
this.formPanel = new Ext.form.FormPanel({
title : i18n.get('label.projectModuleInfo'),
border : false,
labelWidth : 150,
padding : 10,
items : [ {
xtype : 'textfield',
name : 'id',
hidden : true
}, {
xtype : 'textfield',
name : 'name',
fieldLabel : i18n.get('label.name'),
anchor : '100%',
allowBlank : false
}, {
xtype : 'textfield',
name : 'description',
fieldLabel : i18n.get('label.description'),
anchor : '100%',
allowBlank : false
}, {
xtype : 'textfield',
name : 'label',
fieldLabel : i18n.get('headers.label'),
anchor : '100%',
allowBlank : false
}, {
xtype : 'textfield',
name : 'author',
fieldLabel : i18n.get('label.author'),
anchor : '100%',
allowBlank : false
}, {
xtype : 'textfield',
name : 'version',
fieldLabel : i18n.get('label.version'),
anchor : '100%',
allowBlank : false
}, {
xtype : 'textfield',
name : 'title',
fieldLabel : i18n.get('label.form.title'),
anchor : '100%',
allowBlank : true
}, {
xtype : 'numberfield',
name : 'defaultWidth',
fieldLabel : i18n.get('label.width'),
anchor : '100%',
allowBlank : false,
allowDecimals : false,
allowNegative : false
}, {
xtype : 'numberfield',
name : 'defaultHeight',
fieldLabel : i18n.get('label.height'),
anchor : '100%',
allowBlank : false,
allowDecimals : false,
allowNegative : false
}, {
xtype : 'textfield',
name : 'icon',
fieldLabel : i18n.get('label.iconClass'),
anchor : '100%',
allowBlank : true
}, /*{ NEVER USED DIRECTLY BY USER
xtype : 'textfield',
name : 'specificType',
fieldLabel : i18n.get('label.specificType'),
anchor : '100%',
allowBlank : true
},*/ {
xtype : 'numberfield',
name : 'x',
fieldLabel : i18n.get('label.x'),
anchor : '100%',
allowBlank : false,
allowDecimals : false,
allowNegative : false
}, {
xtype : 'numberfield',
name : 'y',
fieldLabel : i18n.get('label.y'),
anchor : '100%',
allowBlank : false,
allowDecimals : false,
allowNegative : false
}, {
xtype : 'textfield',
name : 'xtype',
fieldLabel : i18n.get('label.xtype'),
anchor : '100%',
allowBlank : false
}, {
xtype : 'spinnerfield',
name : 'priority',
id : 'priorityId',
fieldLabel : i18n.get('label.priority'),
minValue : 0,
maxValue : 10,
allowDecimals : false,
incrementValue : 1,
accelerate : true,
anchor : "50%",
allowBlank : false
}
]
});
this.tabPanel = new Ext.TabPanel({
activeTab : 0,
items : [ this.formPanel, this.gridDependencies ],
buttons : [ {
text : i18n.get('label.ok'),
scope : this,
handler : this._onValidate
}, {
text : i18n.get('label.cancel'),
scope : this,
handler : function () {
this.close();
}
} ]
});
this.items = [this.tabPanel];
sitools.admin.projects.modules.ProjectModulePropPanel.superclass.initComponent.call(this);
},
/**
* done a specific render to load project modules properties.
*/
onRender : function () {
sitools.admin.projects.modules.ProjectModulePropPanel.superclass.onRender.apply(this, arguments);
if (this.action == 'modify') {
var f = this.findByType('form')[0].getForm();
Ext.Ajax.request({
url : this.url,
method : 'GET',
scope : this,
success : function (ret) {
var data = Ext.decode(ret.responseText);
f.setValues(data.projectModule);
var dependencies = data.projectModule.dependencies;
var storeDependencies = this.gridDependencies.getStore();
if (!Ext.isEmpty(dependencies.js)) {
Ext.each(dependencies.js, function (item) {
storeDependencies.add(new Ext.data.Record(item));
}, this);
}
if (!Ext.isEmpty(dependencies.css)) {
Ext.each(dependencies.css, function (item) {
storeDependencies.add(new Ext.data.Record(item));
}, this);
}
},
failure : alertFailure
});
}
},
/**
* Save project modules properties for a specific project module
*/
_onValidate : function () {
var frm = this.findByType('form')[0].getForm();
if (!frm.isValid()) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.invalidForm'));
return;
}
var met = this.action == 'modify' ? 'PUT' : 'POST';
var jsonObject = frm.getFieldValues();
jsonObject.dependencies = {};
jsonObject.dependencies.js = [];
jsonObject.dependencies.css = [];
this.gridDependencies.getStore().each(function (item) {
if (!Ext.isEmpty(item.data.url)) {
if (item.data.url.indexOf(".css") != -1) {
jsonObject.dependencies.css.push({
url : item.data.url
});
}
if (item.data.url.indexOf(".js") != -1) {
jsonObject.dependencies.js.push({
url : item.data.url
});
}
}
});
Ext.Ajax.request({
url : this.url,
method : met,
scope : this,
jsonData : jsonObject,
success : function (ret) {
var data = Ext.decode(ret.responseText);
if (!data.success) {
Ext.Msg.alert(i18n.get('label.warning'), i18n.get(data.message));
return false;
}
//load the scripts defined in this component.
// includeJs(frm.items.get('url').getValue());
this.store.reload();
this.close();
},
failure : alertFailure
});
},
/**
* Add a new Record to the dependencies property of a project module
*/
onCreateDependencies : function () {
var e = new Ext.data.Record();
this.gridDependencies.getStore().insert(this.gridDependencies.getStore().getCount(), e);
},
/**
* Delete the selected dependency of a project module
*/
onDeleteDependencies : function () {
var s = this.gridDependencies.getSelectionModel().getSelections();
var i, r;
for (i = 0; s[i]; i++) {
r = s[i];
this.gridDependencies.getStore().remove(r);
}
}
});
Ext.reg('s-projectmoduleprop', sitools.admin.projects.modules.ProjectModulePropPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.admin.projects.modules');
/**
* A Panel to show all the project modules in Sitools2
*
* @cfg {String} the url where get the resource
* @cfg {Ext.data.JsonStore} the store where saved the project modules data
* @class sitools.admin.projects.modules.ProjectModulesCrudPanel
* @extends Ext.grid.GridPanel
*/
//sitools.component.projects.modules.ProjectModulesCrudPanel = Ext.extend(Ext.grid.GridPanel, {
sitools.admin.projects.modules.ProjectModulesCrudPanel = Ext.extend(Ext.grid.GridPanel, {
border : false,
height : 300,
id : ID.BOX.PROJECTMODULE,
sm : new Ext.grid.RowSelectionModel({
singleSelect : true
}),
pageSize : 10,
// loadMask: true,
initComponent : function () {
// url = '/sitools/projectModules'
this.url = loadUrl.get('APP_URL') + loadUrl.get('APP_PROJECTS_MODULES_URL');
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
remoteSort : true,
autoSave : false,
url : this.url,
idProperty : 'id',
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
}, {
name : 'author',
type : 'string'
}, {
name : 'version',
type : 'string'
}, {
name : 'url',
type : 'string'
}, {
name : 'imagePath',
type : 'string'
}, {
name : 'defaultWidth',
type : 'string'
}, {
name : 'defaultHeight',
type : 'string'
}, {
name : 'x',
type : 'string'
}, {
name : 'y',
type : 'string'
}, {
name : 'xtype',
type : 'string'
}, {
name : 'specificType',
type : 'string'
}, {
name : 'dependencies',
type : 'string'
}, {
name : "priority",
type : "integer"
}]
});
this.cm = new Ext.grid.ColumnModel({
// specify any defaults for each column
defaults : {
sortable : true
// columns are not sortable by default
},
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name',
width : 150,
sortable : true
}, {
header : i18n.get('label.description'),
dataIndex : 'description',
width : 300,
sortable : false
}, {
header : i18n.get('label.xtype'),
dataIndex : 'xtype',
width : 350,
sortable : false
} ]
});
this.bbar = {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
};
this.tbar = {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.create'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this._onCreate,
xtype : 's-menuButton'
}, {
text : i18n.get('label.modify'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_edit.png',
handler : this._onModify,
xtype : 's-menuButton'
}, {
text : i18n.get('label.delete'),
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this._onDelete,
xtype : 's-menuButton'
}, '->', {
xtype : 's-filter',
emptyText : i18n.get('label.search'),
store : this.store,
pageSize : this.pageSize
} ]
};
this.view = new Ext.grid.GridView({
forceFit : true
});
this.listeners = {
scope : this,
rowDblClick : this._onModify
};
sitools.admin.projects.modules.ProjectModulesCrudPanel.superclass.initComponent.call(this);
},
/**
* done a specific render to load project modules informations from the store.
*/
onRender : function () {
sitools.admin.projects.modules.ProjectModulesCrudPanel.superclass.onRender.apply(this, arguments);
this.store.load({
params : {
start : 0,
limit : this.pageSize
}
});
},
/**
* Open a {sitools.admin.projects.modules.ProjectModulePropPanel} project property panel
* to create a new project module
*/
_onCreate : function () {
var dbp = new sitools.admin.projects.modules.ProjectModulePropPanel({
url : this.url,
action : 'create',
store : this.store
});
dbp.show(ID.PROP.PROJECTMODULE);
},
/**
* Open a {sitools.admin.projects.modules.ProjectModulePropPanel} project property panel
* to modify an existing project module
*/
_onModify : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
var dbp = new sitools.admin.projects.modules.ProjectModulePropPanel({
url : this.url + '/' + rec.id,
action : 'modify',
store : this.store
});
dbp.show(ID.PROP.PROJECTMODULE);
},
/**
* Diplay confirm delete Msg box and call the method doDelete
*/
_onDelete : function () {
var rec = this.getSelectionModel().getSelected();
if (!rec) {
return false;
}
var tot = Ext.Msg.show({
title : i18n.get('label.delete'),
buttons : Ext.Msg.YESNO,
msg : i18n.get('projectModulesCrud.delete'),
scope : this,
fn : function (btn, text) {
if (btn == 'yes') {
this.doDelete(rec);
}
}
});
},
/**
* done the delete of the passed record
* @param rec the record to delete
*/
doDelete : function (rec) {
// var rec = this.getSelectionModel().getSelected();
// if (!rec) return false;
Ext.Ajax.request({
url : this.url + "/" + rec.id,
method : 'DELETE',
scope : this,
success : function (ret) {
if (showResponse(ret)) {
this.store.reload();
}
},
failure : alertFailure
});
}
});
Ext.reg('s-projectmodule', sitools.admin.projects.modules.ProjectModulesCrudPanel);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.admin.projects.modules');
/**
* A Panel to show project module parameters which are configurable for a specific project
*
* @class sitools.admin.projects.modules.ProjectModuleConfig
* @extends Ext.Window
*/
sitools.admin.projects.modules.ProjectModuleConfig = Ext.extend(Ext.Window, {
width : 500,
height : 400,
modal : true,
id : ID.BOX.PROJECTMODULECONFIG,
layout : 'fit',
initComponent : function () {
this.parametersFieldset = new Ext.form.FieldSet({
title : i18n.get('label.parameters'),
padding : 6
});
this.formPanel = new Ext.form.FormPanel({
id : 'formModuleConfigId',
autoScroll : true,
frame: true,
border: false,
monitorValid : true,
labelWidth : 150,
items : [this.parametersFieldset],
listeners : {
clientvalidation : function (formPanel, valid) {
if (valid) {
formPanel.getFooterToolbar().getComponent('btnValidateId').setDisabled(false);
}
else {
formPanel.getFooterToolbar().getComponent('btnValidateId').setDisabled(true);
}
}
},
buttons : [{
text : i18n.get('label.ok'),
id : "btnValidateId",
handler : this._onValidate,
scope : this,
disabled : true
}, {
text : i18n.get('label.cancel'),
handler : function () {
this.close();
},
scope : this
}]
});
this.items = [this.formPanel];
sitools.admin.projects.modules.ProjectModuleConfig.superclass.initComponent.call(this);
},
onRender : function () {
sitools.admin.projects.modules.ProjectModuleConfig.superclass.onRender.apply(this, arguments);
this.title = i18n.get('label.projectModuleConfig') + " " + this.module.data.name;
this.buildViewConfig(this.module);
},
buildViewConfig : function (recSelected) {
try {
this.parametersFieldset.removeAll();
var getParametersMethod = eval(recSelected.data.xtype + ".getParameters");
if (!Ext.isFunction(getParametersMethod)) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('label.notImplementedMethod'));
return;
}
var parameters = getParametersMethod();
if (Ext.isEmpty(parameters)) {
this.parametersFieldset.setVisible(false);
}
else {
this.parametersFieldset.setVisible(true);
}
Ext.each(parameters, function (param) {
if (!Ext.isEmpty(this.module.data.listProjectModulesConfig)){
// on recharge les parametres définis par l'utilisateur
Ext.iterate(this.module.data.listProjectModulesConfig, function (cmp){
if (cmp.name == param.config.name){
var customValue = cmp.value;
var JsObj = eval(param.jsObj);
var config = Ext.applyIf(param.config, {
anchor : "100%"
});
var p = new JsObj(config);
p.setValue(customValue);
this.parametersFieldset.add(p);
}
}, this);
}
else {
// on charge les parametres par défaut définis dans le projectModule
//var parameterValue = this.findDefaultParameterValue(param);
var JsObj = eval(param.jsObj);
var config = Ext.applyIf(param.config, {
anchor : "100%"
});
var p = new JsObj(config);
// if (!Ext.isEmpty(parameterValue)) {
// p.setValue(parameterValue);
// }
this.parametersFieldset.add(p);
}
}, this);
// this.doLayout();
}
catch (err) {
Ext.Msg.alert(i18n.get('label.error'), i18n.get('label.notImplementedMethod'));
return;
}
},
_onValidate : function () {
this.module.set('listProjectModulesConfig', this.getParametersValue());
this.close();
},
getParametersValue : function () {
var result = [];
if (Ext.isEmpty(this.parametersFieldset.items)) {
return result;
}
this.parametersFieldset.items.each(function (param) {
if (Ext.isFunction(param.getValue)) {
result.push({
name : param.name,
value : param.getValue()
});
}
}, this);
return result;
}
});
Ext.reg('s-projectmoduleconfig', sitools.admin.projects.modules.ProjectModuleConfig);
/***************************************
* Copyright 2011, 2012 CNES - CENTRE NATIONAL d'ETUDES SPATIALES
*
* This file is part of SITools2.
*
* SITools2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SITools2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SITools2. If not, see <http://www.gnu.org/licenses/>.
***************************************/
/*global Ext, sitools, ID, i18n, document, showResponse, alertFailure, LOCALE, ImageChooser,
showHelp, loadUrl*/
Ext.namespace('sitools.admin.usergroups');
/**
* A Panel retrieving sitools2 roles
*
* @cfg {String} the mode (select or list) to load roles
* @cfg {Ext.data.Record} the project record
* @class sitools.admin.usergroups.RolesPanel
* @extends Ext.Window
*/
//sitools.component.usergroups.RolesPanel = Ext.extend(Ext.Window, {
sitools.admin.usergroups.RolesPanel = Ext.extend(Ext.Window, {
width : 350,
modal : true,
closable : false,
pageSize : 10,
initComponent : function () {
this.store = new Ext.data.JsonStore({
root : 'data',
restful : true,
autoSave : false,
idProperty : 'name',
url : this.url,
fields : [ {
name : 'id',
type : 'string'
}, {
name : 'name',
type : 'string'
}, {
name : 'description',
type : 'string'
} ]
});
this.grid = new Ext.grid.GridPanel({
xtype : 'grid',
sm : new Ext.grid.RowSelectionModel(),
store : this.store,
height : 200,
columns : [ {
header : i18n.get('label.name'),
dataIndex : 'name'
}, {
header : i18n.get('label.description'),
dataIndex : 'description'
} ],
bbar : {
xtype : 'paging',
pageSize : this.pageSize,
store : this.store,
displayInfo : true,
displayMsg : i18n.get('paging.display'),
emptyMsg : i18n.get('paging.empty')
}
});
this.items = [ {
xtype : 'panel',
title : this.mode == 'list' ? i18n.get('label.roles') : i18n.get('label.selectRoles'),
items : [ this.grid ],
tbar : {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ {
text : i18n.get('label.add'),
hidden : this.mode == 'select',
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_create.png',
handler : this._onCreate
}, {
text : i18n.get('label.remove'),
hidden : this.mode == 'select',
icon : loadUrl.get('APP_URL') + '/common/res/images/icons/toolbar_delete.png',
handler : this._onDelete
}, '->', {
xtype : 's-filter',
hidden : this.mode == 'list',
emptyText : i18n.get('label.search'),
store : this.store,
pageSize : this.pageSize
} ]
},
bbar : {
xtype : 'toolbar',
defaults : {
scope : this
},
items : [ '->', {
text : i18n.get('label.add'),
handler : this._onAdd,
hidden : this.mode == 'list'
}, {
text : i18n.get('label.ok'),
handler : this._onOK,
hidden : this.mode == 'select'
}, {
text : i18n.get('label.cancel'),
handler : this._onCancel
} ]
}
} ];
sitools.admin.usergroups.RolesPanel.superclass.initComponent.call(this);
},
/**
* done a specific render to load roles from the store.
*/
onRender : function () {
sitools.admin.usergroups.RolesPanel.superclass.onRender.apply(this, arguments);
if (this.mode == 'select'){
this.store.load({
scope : this,
params : {
start : 0,
limit : this.pageSize
},
callback : function (r, options, success) {
if (!success) {
this.close();
Ext.Msg.alert(i18n.get('label.warning'), i18n.get('label.loadError'));
}
}
});
}
else {
Ext.each(this.rec.data.listRoles, function (item){
var it = new Ext.data.Record(item);
this.store.add(it);
}, this);
}
},
/**
* Create a new {sitools.admin.usergroups.RolesPanel} role panel and display all roles
*/
_onCreate : function () {
var up = new sitools.admin.usergroups.RolesPanel({
mode : 'select',
url : loadUrl.get('APP_URL') + loadUrl.get('APP_SECURITY_URL') + '/roles?media=json',
storeref : this.store
});
up.show(this);
},
/**
* Delete the selected role from the store
*/
_onDelete : function () {
var rec = this.grid.getSelectionModel().getSelected();
if (!rec) {
return Ext.Msg.alert(i18n.get('label.warning'), i18n.get('warning.noselection'));
}
this.store.remove(rec);
},
/**
* Gets the selected roles and add them to the list roles of the current parent object
*/
_onAdd : function () { // sub window -> no action
var recs = this.grid.getSelectionModel().getSelections();
var newrecs = [];
Ext.each(recs, function (rec) {
newrecs.push(new this.store.recordType({
name : rec.data.name,
description : rec.data.description
}));
});
this.storeref.add(newrecs);
this.close();
},
/**
* Save the groups of the current project
*/
_onOK : function () {
var putObject = [];
this.store.each(function (record) {
var resource = {
id : record.data.id,
name : record.data.name,
description : record.data.description
};
putObject.push(resource);
});
this.rec.set('listRoles', putObject);
this.close();
},
/**
* Destroy the {sitools.admin.usergroups.RolesPanel} role Panel
*/
_onCancel : function () {
this.destroy();
}
});
Ext.reg('s-roles', sitools.admin.usergroups.RolesPanel);