Roo/grid/GridView.js
[roojs1] / Roo / grid / GridView.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11   
12 /**
13  * @class Roo.grid.GridView
14  * @extends Roo.util.Observable
15  *
16  * @constructor
17  * @param {Object} config
18  */
19 Roo.grid.GridView = function(config){
20     Roo.grid.GridView.superclass.constructor.call(this);
21     this.el = null;
22
23     Roo.apply(this, config);
24 };
25
26 Roo.extend(Roo.grid.GridView, Roo.grid.AbstractGridView, {
27
28     /**
29      * Override this function to apply custom css classes to rows during rendering
30      * @param {Record} record The record
31      * @param {Number} index
32      * @method getRowClass
33      */
34     rowClass : "x-grid-row",
35
36     cellClass : "x-grid-col",
37
38     tdClass : "x-grid-td",
39
40     hdClass : "x-grid-hd",
41
42     splitClass : "x-grid-split",
43
44     sortClasses : ["sort-asc", "sort-desc"],
45
46     enableMoveAnim : false,
47
48     hlColor: "C3DAF9",
49
50     dh : Roo.DomHelper,
51
52     fly : Roo.Element.fly,
53
54     css : Roo.util.CSS,
55
56     borderWidth: 1,
57
58     splitOffset: 3,
59
60     scrollIncrement : 22,
61
62     cellRE: /(?:.*?)x-grid-(?:hd|cell|csplit)-(?:[\d]+)-([\d]+)(?:.*?)/,
63
64     findRE: /\s?(?:x-grid-hd|x-grid-col|x-grid-csplit)\s/,
65
66     bind : function(ds, cm){
67         if(this.ds){
68             this.ds.un("load", this.onLoad, this);
69             this.ds.un("datachanged", this.onDataChange, this);
70             this.ds.un("add", this.onAdd, this);
71             this.ds.un("remove", this.onRemove, this);
72             this.ds.un("update", this.onUpdate, this);
73             this.ds.un("clear", this.onClear, this);
74         }
75         if(ds){
76             ds.on("load", this.onLoad, this);
77             ds.on("datachanged", this.onDataChange, this);
78             ds.on("add", this.onAdd, this);
79             ds.on("remove", this.onRemove, this);
80             ds.on("update", this.onUpdate, this);
81             ds.on("clear", this.onClear, this);
82         }
83         this.ds = ds;
84
85         if(this.cm){
86             this.cm.un("widthchange", this.onColWidthChange, this);
87             this.cm.un("headerchange", this.onHeaderChange, this);
88             this.cm.un("hiddenchange", this.onHiddenChange, this);
89             this.cm.un("columnmoved", this.onColumnMove, this);
90             this.cm.un("columnlockchange", this.onColumnLock, this);
91         }
92         if(cm){
93             this.generateRules(cm);
94             cm.on("widthchange", this.onColWidthChange, this);
95             cm.on("headerchange", this.onHeaderChange, this);
96             cm.on("hiddenchange", this.onHiddenChange, this);
97             cm.on("columnmoved", this.onColumnMove, this);
98             cm.on("columnlockchange", this.onColumnLock, this);
99         }
100         this.cm = cm;
101     },
102
103     init: function(grid){
104         Roo.grid.GridView.superclass.init.call(this, grid);
105
106         this.bind(grid.dataSource, grid.colModel);
107
108         grid.on("headerclick", this.handleHeaderClick, this);
109
110         if(grid.trackMouseOver){
111             grid.on("mouseover", this.onRowOver, this);
112             grid.on("mouseout", this.onRowOut, this);
113         }
114         grid.cancelTextSelection = function(){};
115         this.gridId = grid.id;
116
117         var tpls = this.templates || {};
118
119         if(!tpls.master){
120             tpls.master = new Roo.Template(
121                '<div class="x-grid" hidefocus="true">',
122                   '<div class="x-grid-topbar"></div>',
123                   '<div class="x-grid-scroller"><div></div></div>',
124                   '<div class="x-grid-locked">',
125                       '<div class="x-grid-header">{lockedHeader}</div>',
126                       '<div class="x-grid-body">{lockedBody}</div>',
127                   "</div>",
128                   '<div class="x-grid-viewport">',
129                       '<div class="x-grid-header">{header}</div>',
130                       '<div class="x-grid-body">{body}</div>',
131                   "</div>",
132                   '<div class="x-grid-bottombar"></div>',
133                   '<a href="#" class="x-grid-focus" tabIndex="-1"></a>',
134                   '<div class="x-grid-resize-proxy">&#160;</div>',
135                "</div>"
136             );
137             tpls.master.disableformats = true;
138         }
139
140         if(!tpls.header){
141             tpls.header = new Roo.Template(
142                '<table border="0" cellspacing="0" cellpadding="0">',
143                '<tbody><tr class="x-grid-hd-row">{cells}</tr></tbody>',
144                "</table>{splits}"
145             );
146             tpls.header.disableformats = true;
147         }
148         tpls.header.compile();
149
150         if(!tpls.hcell){
151             tpls.hcell = new Roo.Template(
152                 '<td class="x-grid-hd x-grid-td-{id} {cellId}"><div title="{title}" class="x-grid-hd-inner x-grid-hd-{id}">',
153                 '<div class="x-grid-hd-text" unselectable="on">{value}<img class="x-grid-sort-icon" src="', Roo.BLANK_IMAGE_URL, '" /></div>',
154                 "</div></td>"
155              );
156              tpls.hcell.disableFormats = true;
157         }
158         tpls.hcell.compile();
159
160         if(!tpls.hsplit){
161             tpls.hsplit = new Roo.Template('<div class="x-grid-split {splitId} x-grid-split-{id}" style="{style}" unselectable="on">&#160;</div>');
162             tpls.hsplit.disableFormats = true;
163         }
164         tpls.hsplit.compile();
165
166         if(!tpls.body){
167             tpls.body = new Roo.Template(
168                '<table border="0" cellspacing="0" cellpadding="0">',
169                "<tbody>{rows}</tbody>",
170                "</table>"
171             );
172             tpls.body.disableFormats = true;
173         }
174         tpls.body.compile();
175
176         if(!tpls.row){
177             tpls.row = new Roo.Template('<tr class="x-grid-row {alt}">{cells}</tr>');
178             tpls.row.disableFormats = true;
179         }
180         tpls.row.compile();
181
182         if(!tpls.cell){
183             tpls.cell = new Roo.Template(
184                 '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">',
185                 '<div class="x-grid-col-{id} x-grid-cell-inner"><div class="x-grid-cell-text" unselectable="on" {attr}>{value}</div></div>',
186                 "</td>"
187             );
188             tpls.cell.disableFormats = true;
189         }
190         tpls.cell.compile();
191
192         this.templates = tpls;
193     },
194
195     // remap these for backwards compat
196     onColWidthChange : function(){
197         this.updateColumns.apply(this, arguments);
198     },
199     onHeaderChange : function(){
200         this.updateHeaders.apply(this, arguments);
201     }, 
202     onHiddenChange : function(){
203         this.handleHiddenChange.apply(this, arguments);
204     },
205     onColumnMove : function(){
206         this.handleColumnMove.apply(this, arguments);
207     },
208     onColumnLock : function(){
209         this.handleLockChange.apply(this, arguments);
210     },
211
212     onDataChange : function(){
213         this.refresh();
214         this.updateHeaderSortState();
215     },
216
217     onClear : function(){
218         this.refresh();
219     },
220
221     onUpdate : function(ds, record){
222         this.refreshRow(record);
223     },
224
225     refreshRow : function(record){
226         var ds = this.ds, index;
227         if(typeof record == 'number'){
228             index = record;
229             record = ds.getAt(index);
230         }else{
231             index = ds.indexOf(record);
232         }
233         this.insertRows(ds, index, index, true);
234         this.onRemove(ds, record, index+1, true);
235         this.syncRowHeights(index, index);
236         this.layout();
237         this.fireEvent("rowupdated", this, index, record);
238     },
239
240     onAdd : function(ds, records, index){
241         this.insertRows(ds, index, index + (records.length-1));
242     },
243
244     onRemove : function(ds, record, index, isUpdate){
245         if(isUpdate !== true){
246             this.fireEvent("beforerowremoved", this, index, record);
247         }
248         var bt = this.getBodyTable(), lt = this.getLockedTable();
249         if(bt.rows[index]){
250             bt.firstChild.removeChild(bt.rows[index]);
251         }
252         if(lt.rows[index]){
253             lt.firstChild.removeChild(lt.rows[index]);
254         }
255         if(isUpdate !== true){
256             this.stripeRows(index);
257             this.syncRowHeights(index, index);
258             this.layout();
259             this.fireEvent("rowremoved", this, index, record);
260         }
261     },
262
263     onLoad : function(){
264         this.scrollToTop();
265     },
266
267     /**
268      * Scrolls the grid to the top
269      */
270     scrollToTop : function(){
271         if(this.scroller){
272             this.scroller.dom.scrollTop = 0;
273             this.syncScroll();
274         }
275     },
276
277     /**
278      * Gets a panel in the header of the grid that can be used for toolbars etc.
279      * After modifying the contents of this panel a call to grid.autoSize() may be
280      * required to register any changes in size.
281      * @param {Boolean} doShow By default the header is hidden. Pass true to show the panel
282      * @return Roo.Element
283      */
284     getHeaderPanel : function(doShow){
285         if(doShow){
286             this.headerPanel.show();
287         }
288         return this.headerPanel;
289     },
290
291     /**
292      * Gets a panel in the footer of the grid that can be used for toolbars etc.
293      * After modifying the contents of this panel a call to grid.autoSize() may be
294      * required to register any changes in size.
295      * @param {Boolean} doShow By default the footer is hidden. Pass true to show the panel
296      * @return Roo.Element
297      */
298     getFooterPanel : function(doShow){
299         if(doShow){
300             this.footerPanel.show();
301         }
302         return this.footerPanel;
303     },
304
305     initElements : function(){
306         var E = Roo.Element;
307         var el = this.grid.getGridEl().dom.firstChild;
308         var cs = el.childNodes;
309
310         this.el = new E(el);
311         this.headerPanel = new E(el.firstChild);
312         this.headerPanel.enableDisplayMode("block");
313
314         this.scroller = new E(cs[1]);
315         this.scrollSizer = new E(this.scroller.dom.firstChild);
316
317         this.lockedWrap = new E(cs[2]);
318         this.lockedHd = new E(this.lockedWrap.dom.firstChild);
319         this.lockedBody = new E(this.lockedWrap.dom.childNodes[1]);
320
321         this.mainWrap = new E(cs[3]);
322         this.mainHd = new E(this.mainWrap.dom.firstChild);
323         this.mainBody = new E(this.mainWrap.dom.childNodes[1]);
324
325         this.footerPanel = new E(cs[4]);
326         this.footerPanel.enableDisplayMode("block");
327
328         this.focusEl = new E(cs[5]);
329         this.focusEl.swallowEvent("click", true);
330         this.resizeProxy = new E(cs[6]);
331
332         this.headerSelector = String.format(
333            '#{0} td.x-grid-hd, #{1} td.x-grid-hd',
334            this.lockedHd.id, this.mainHd.id
335         );
336
337         this.splitterSelector = String.format(
338            '#{0} div.x-grid-split, #{1} div.x-grid-split',
339            this.idToCssName(this.lockedHd.id), this.idToCssName(this.mainHd.id)
340         );
341     },
342     idToCssName : function(s)
343     {
344         return s.replace(/[^a-z0-9]+/ig, '-');
345     },
346
347     getHeaderCell : function(index){
348         return Roo.DomQuery.select(this.headerSelector)[index];
349     },
350
351     getHeaderCellMeasure : function(index){
352         return this.getHeaderCell(index).firstChild;
353     },
354
355     getHeaderCellText : function(index){
356         return this.getHeaderCell(index).firstChild.firstChild;
357     },
358
359     getLockedTable : function(){
360         return this.lockedBody.dom.firstChild;
361     },
362
363     getBodyTable : function(){
364         return this.mainBody.dom.firstChild;
365     },
366
367     getLockedRow : function(index){
368         return this.getLockedTable().rows[index];
369     },
370
371     getRow : function(index){
372         return this.getBodyTable().rows[index];
373     },
374
375     getRowComposite : function(index){
376         if(!this.rowEl){
377             this.rowEl = new Roo.CompositeElementLite();
378         }
379         var els = [], lrow, mrow;
380         if(lrow = this.getLockedRow(index)){
381             els.push(lrow);
382         }
383         if(mrow = this.getRow(index)){
384             els.push(mrow);
385         }
386         this.rowEl.elements = els;
387         return this.rowEl;
388     },
389
390     getCell : function(rowIndex, colIndex){
391         var locked = this.cm.getLockedCount();
392         var source;
393         if(colIndex < locked){
394             source = this.lockedBody.dom.firstChild;
395         }else{
396             source = this.mainBody.dom.firstChild;
397             colIndex -= locked;
398         }
399         return source.rows[rowIndex].childNodes[colIndex];
400     },
401
402     getCellText : function(rowIndex, colIndex){
403         return this.getCell(rowIndex, colIndex).firstChild.firstChild;
404     },
405
406     getCellBox : function(cell){
407         var b = this.fly(cell).getBox();
408         if(Roo.isOpera){ // opera fails to report the Y
409             b.y = cell.offsetTop + this.mainBody.getY();
410         }
411         return b;
412     },
413
414     getCellIndex : function(cell){
415         var id = String(cell.className).match(this.cellRE);
416         if(id){
417             return parseInt(id[1], 10);
418         }
419         return 0;
420     },
421
422     findHeaderIndex : function(n){
423         var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
424         return r ? this.getCellIndex(r) : false;
425     },
426
427     findHeaderCell : function(n){
428         var r = Roo.fly(n).findParent("td." + this.hdClass, 6);
429         return r ? r : false;
430     },
431
432     findRowIndex : function(n){
433         if(!n){
434             return false;
435         }
436         var r = Roo.fly(n).findParent("tr." + this.rowClass, 6);
437         return r ? r.rowIndex : false;
438     },
439
440     findCellIndex : function(node){
441         var stop = this.el.dom;
442         while(node && node != stop){
443             if(this.findRE.test(node.className)){
444                 return this.getCellIndex(node);
445             }
446             node = node.parentNode;
447         }
448         return false;
449     },
450
451     getColumnId : function(index){
452         return this.cm.getColumnId(index);
453     },
454
455     getSplitters : function(){
456     if(this.splitterSelector){
457        return Roo.DomQuery.select(this.splitterSelector);
458     }else{
459         return null;
460     }
461     },
462
463     getSplitter : function(index){
464     return this.getSplitters()[index];
465     },
466
467     onRowOver : function(e, t){
468         var row;
469         if((row = this.findRowIndex(t)) !== false){
470             this.getRowComposite(row).addClass("x-grid-row-over");
471         }
472     },
473
474     onRowOut : function(e, t){
475         var row;
476         if((row = this.findRowIndex(t)) !== false && row !== this.findRowIndex(e.getRelatedTarget())){
477             this.getRowComposite(row).removeClass("x-grid-row-over");
478         }
479     },
480
481     renderHeaders : function(){
482         var cm = this.cm;
483         var ct = this.templates.hcell, ht = this.templates.header, st = this.templates.hsplit;
484         var cb = [], lb = [], sb = [], lsb = [], p = {};
485         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
486             p.cellId = "x-grid-hd-0-" + i;
487             p.splitId = "x-grid-csplit-0-" + i;
488             p.id = cm.getColumnId(i);
489             p.title = cm.getColumnTooltip(i) || "";
490             p.value = cm.getColumnHeader(i) || "";
491             p.style = (this.grid.enableColumnResize === false || !cm.isResizable(i) || cm.isFixed(i)) ? 'cursor:default' : '';
492             if(!cm.isLocked(i)){
493                 cb[cb.length] = ct.apply(p);
494                 sb[sb.length] = st.apply(p);
495             }else{
496                 lb[lb.length] = ct.apply(p);
497                 lsb[lsb.length] = st.apply(p);
498             }
499         }
500         return [ht.apply({cells: lb.join(""), splits:lsb.join("")}),
501                 ht.apply({cells: cb.join(""), splits:sb.join("")})];
502     },
503
504     updateHeaders : function(){
505         var html = this.renderHeaders();
506         this.lockedHd.update(html[0]);
507         this.mainHd.update(html[1]);
508     },
509
510     /**
511      * Focuses the specified row.
512      * @param {Number} row The row index
513      */
514     focusRow : function(row){
515         var x = this.scroller.dom.scrollLeft;
516         this.focusCell(row, 0, false);
517         this.scroller.dom.scrollLeft = x;
518     },
519
520     /**
521      * Focuses the specified cell.
522      * @param {Number} row The row index
523      * @param {Number} col The column index
524      * @param {Boolean} hscroll false to disable horizontal scrolling
525      */
526     focusCell : function(row, col, hscroll){
527         var el = this.ensureVisible(row, col, hscroll);
528         this.focusEl.alignTo(el, "tl-tl");
529         if(Roo.isGecko){
530             this.focusEl.focus();
531         }else{
532             this.focusEl.focus.defer(1, this.focusEl);
533         }
534     },
535
536     /**
537      * Scrolls the specified cell into view
538      * @param {Number} row The row index
539      * @param {Number} col The column index
540      * @param {Boolean} hscroll false to disable horizontal scrolling
541      */
542     ensureVisible : function(row, col, hscroll){
543         if(typeof row != "number"){
544             row = row.rowIndex;
545         }
546         if(row < 0 && row >= this.ds.getCount()){
547             return;
548         }
549         col = (col !== undefined ? col : 0);
550         var cm = this.grid.colModel;
551         while(cm.isHidden(col)){
552             col++;
553         }
554
555         var el = this.getCell(row, col);
556         if(!el){
557             return;
558         }
559         var c = this.scroller.dom;
560
561         var ctop = parseInt(el.offsetTop, 10);
562         var cleft = parseInt(el.offsetLeft, 10);
563         var cbot = ctop + el.offsetHeight;
564         var cright = cleft + el.offsetWidth;
565
566         var ch = c.clientHeight - this.mainHd.dom.offsetHeight;
567         var stop = parseInt(c.scrollTop, 10);
568         var sleft = parseInt(c.scrollLeft, 10);
569         var sbot = stop + ch;
570         var sright = sleft + c.clientWidth;
571
572         if(ctop < stop){
573             c.scrollTop = ctop;
574         }else if(cbot > sbot){
575             c.scrollTop = cbot-ch;
576         }
577
578         if(hscroll !== false){
579             if(cleft < sleft){
580                 c.scrollLeft = cleft;
581             }else if(cright > sright){
582                 c.scrollLeft = cright-c.clientWidth;
583             }
584         }
585         return el;
586     },
587
588     updateColumns : function(){
589         this.grid.stopEditing();
590         var cm = this.grid.colModel, colIds = this.getColumnIds();
591         //var totalWidth = cm.getTotalWidth();
592         var pos = 0;
593         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
594             //if(cm.isHidden(i)) continue;
595             var w = cm.getColumnWidth(i);
596             this.css.updateRule(this.colSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
597             this.css.updateRule(this.hdSelector+this.idToCssName(colIds[i]), "width", (w - this.borderWidth) + "px");
598         }
599         this.updateSplitters();
600     },
601
602     generateRules : function(cm){
603         var ruleBuf = [], rulesId = this.idToCssName(this.grid.id)+ '-cssrules';
604         Roo.util.CSS.removeStyleSheet(rulesId);
605         for(var i = 0, len = cm.getColumnCount(); i < len; i++){
606             var cid = cm.getColumnId(i);
607             var align = '';
608             if(cm.config[i].align){
609                 align = 'text-align:'+cm.config[i].align+';';
610             }
611             var hidden = '';
612             if(cm.isHidden(i)){
613                 hidden = 'display:none;';
614             }
615             var width = "width:" + (cm.getColumnWidth(i) - this.borderWidth) + "px;";
616             ruleBuf.push(
617                     this.colSelector, cid, " {\n", cm.config[i].css, align, width, "\n}\n",
618                     this.hdSelector, cid, " {\n", align, width, "}\n",
619                     this.tdSelector, cid, " {\n",hidden,"\n}\n",
620                     this.splitSelector, cid, " {\n", hidden , "\n}\n");
621         }
622         return Roo.util.CSS.createStyleSheet(ruleBuf.join(""), rulesId);
623     },
624
625     updateSplitters : function(){
626         var cm = this.cm, s = this.getSplitters();
627         if(s){ // splitters not created yet
628             var pos = 0, locked = true;
629             for(var i = 0, len = cm.getColumnCount(); i < len; i++){
630                 if(cm.isHidden(i)) continue;
631                 var w = cm.getColumnWidth(i);
632                 if(!cm.isLocked(i) && locked){
633                     pos = 0;
634                     locked = false;
635                 }
636                 pos += w;
637                 s[i].style.left = (pos-this.splitOffset) + "px";
638             }
639         }
640     },
641
642     handleHiddenChange : function(colModel, colIndex, hidden){
643         if(hidden){
644             this.hideColumn(colIndex);
645         }else{
646             this.unhideColumn(colIndex);
647         }
648     },
649
650     hideColumn : function(colIndex){
651         var cid = this.getColumnId(colIndex);
652         this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "none");
653         this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "none");
654         if(Roo.isSafari){
655             this.updateHeaders();
656         }
657         this.updateSplitters();
658         this.layout();
659     },
660
661     unhideColumn : function(colIndex){
662         var cid = this.getColumnId(colIndex);
663         this.css.updateRule(this.tdSelector+this.idToCssName(cid), "display", "");
664         this.css.updateRule(this.splitSelector+this.idToCssName(cid), "display", "");
665
666         if(Roo.isSafari){
667             this.updateHeaders();
668         }
669         this.updateSplitters();
670         this.layout();
671     },
672
673     insertRows : function(dm, firstRow, lastRow, isUpdate){
674         if(firstRow == 0 && lastRow == dm.getCount()-1){
675             this.refresh();
676         }else{
677             if(!isUpdate){
678                 this.fireEvent("beforerowsinserted", this, firstRow, lastRow);
679             }
680             var s = this.getScrollState();
681             var markup = this.renderRows(firstRow, lastRow);
682             this.bufferRows(markup[0], this.getLockedTable(), firstRow);
683             this.bufferRows(markup[1], this.getBodyTable(), firstRow);
684             this.restoreScroll(s);
685             if(!isUpdate){
686                 this.fireEvent("rowsinserted", this, firstRow, lastRow);
687                 this.syncRowHeights(firstRow, lastRow);
688                 this.stripeRows(firstRow);
689                 this.layout();
690             }
691         }
692     },
693
694     bufferRows : function(markup, target, index){
695         var before = null, trows = target.rows, tbody = target.tBodies[0];
696         if(index < trows.length){
697             before = trows[index];
698         }
699         var b = document.createElement("div");
700         b.innerHTML = "<table><tbody>"+markup+"</tbody></table>";
701         var rows = b.firstChild.rows;
702         for(var i = 0, len = rows.length; i < len; i++){
703             if(before){
704                 tbody.insertBefore(rows[0], before);
705             }else{
706                 tbody.appendChild(rows[0]);
707             }
708         }
709         b.innerHTML = "";
710         b = null;
711     },
712
713     deleteRows : function(dm, firstRow, lastRow){
714         if(dm.getRowCount()<1){
715             this.fireEvent("beforerefresh", this);
716             this.mainBody.update("");
717             this.lockedBody.update("");
718             this.fireEvent("refresh", this);
719         }else{
720             this.fireEvent("beforerowsdeleted", this, firstRow, lastRow);
721             var bt = this.getBodyTable();
722             var tbody = bt.firstChild;
723             var rows = bt.rows;
724             for(var rowIndex = firstRow; rowIndex <= lastRow; rowIndex++){
725                 tbody.removeChild(rows[firstRow]);
726             }
727             this.stripeRows(firstRow);
728             this.fireEvent("rowsdeleted", this, firstRow, lastRow);
729         }
730     },
731
732     updateRows : function(dataSource, firstRow, lastRow){
733         var s = this.getScrollState();
734         this.refresh();
735         this.restoreScroll(s);
736     },
737
738     handleSort : function(dataSource, sortColumnIndex, sortDir, noRefresh){
739         if(!noRefresh){
740            this.refresh();
741         }
742         this.updateHeaderSortState();
743     },
744
745     getScrollState : function(){
746         var sb = this.scroller.dom;
747         return {left: sb.scrollLeft, top: sb.scrollTop};
748     },
749
750     stripeRows : function(startRow){
751         if(!this.grid.stripeRows || this.ds.getCount() < 1){
752             return;
753         }
754         startRow = startRow || 0;
755         var rows = this.getBodyTable().rows;
756         var lrows = this.getLockedTable().rows;
757         var cls = ' x-grid-row-alt ';
758         for(var i = startRow, len = rows.length; i < len; i++){
759             var row = rows[i], lrow = lrows[i];
760             var isAlt = ((i+1) % 2 == 0);
761             var hasAlt = (' '+row.className + ' ').indexOf(cls) != -1;
762             if(isAlt == hasAlt){
763                 continue;
764             }
765             if(isAlt){
766                 row.className += " x-grid-row-alt";
767             }else{
768                 row.className = row.className.replace("x-grid-row-alt", "");
769             }
770             if(lrow){
771                 lrow.className = row.className;
772             }
773         }
774     },
775
776     restoreScroll : function(state){
777         var sb = this.scroller.dom;
778         sb.scrollLeft = state.left;
779         sb.scrollTop = state.top;
780         this.syncScroll();
781     },
782
783     syncScroll : function(){
784         var sb = this.scroller.dom;
785         var sh = this.mainHd.dom;
786         var bs = this.mainBody.dom;
787         var lv = this.lockedBody.dom;
788         sh.scrollLeft = bs.scrollLeft = sb.scrollLeft;
789         lv.scrollTop = bs.scrollTop = sb.scrollTop;
790     },
791
792     handleScroll : function(e){
793         this.syncScroll();
794         var sb = this.scroller.dom;
795         this.grid.fireEvent("bodyscroll", sb.scrollLeft, sb.scrollTop);
796         e.stopEvent();
797     },
798
799     handleWheel : function(e){
800         var d = e.getWheelDelta();
801         this.scroller.dom.scrollTop -= d*22;
802         // set this here to prevent jumpy scrolling on large tables
803         this.lockedBody.dom.scrollTop = this.mainBody.dom.scrollTop = this.scroller.dom.scrollTop;
804         e.stopEvent();
805     },
806
807     renderRows : function(startRow, endRow){
808         // pull in all the crap needed to render rows
809         var g = this.grid, cm = g.colModel, ds = g.dataSource, stripe = g.stripeRows;
810         var colCount = cm.getColumnCount();
811
812         if(ds.getCount() < 1){
813             return ["", ""];
814         }
815
816         // build a map for all the columns
817         var cs = [];
818         for(var i = 0; i < colCount; i++){
819             var name = cm.getDataIndex(i);
820             cs[i] = {
821                 name : typeof name == 'undefined' ? ds.fields.get(i).name : name,
822                 renderer : cm.getRenderer(i),
823                 id : cm.getColumnId(i),
824                 locked : cm.isLocked(i)
825             };
826         }
827
828         startRow = startRow || 0;
829         endRow = typeof endRow == "undefined"? ds.getCount()-1 : endRow;
830
831         // records to render
832         var rs = ds.getRange(startRow, endRow);
833
834         return this.doRender(cs, rs, ds, startRow, colCount, stripe);
835     },
836
837     // As much as I hate to duplicate code, this was branched because FireFox really hates
838     // [].join("") on strings. The performance difference was substantial enough to
839     // branch this function
840     doRender : Roo.isGecko ?
841             function(cs, rs, ds, startRow, colCount, stripe){
842                 var ts = this.templates, ct = ts.cell, rt = ts.row;
843                 // buffers
844                 var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r, rowIndex;
845                 
846                 var hasListener = this.grid.hasListener('rowclass');
847                 var rowcfg = {};
848                 for(var j = 0, len = rs.length; j < len; j++){
849                     r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
850                     for(var i = 0; i < colCount; i++){
851                         c = cs[i];
852                         p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
853                         p.id = c.id;
854                         p.css = p.attr = "";
855                         p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
856                         if(p.value == undefined || p.value === "") p.value = "&#160;";
857                         if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
858                             p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell';
859                         }
860                         var markup = ct.apply(p);
861                         if(!c.locked){
862                             cb+= markup;
863                         }else{
864                             lcb+= markup;
865                         }
866                     }
867                     var alt = [];
868                     if(stripe && ((rowIndex+1) % 2 == 0)){
869                         alt.push("x-grid-row-alt")
870                     }
871                     if(r.dirty){
872                         alt.push(  " x-grid-dirty-row");
873                     }
874                     rp.cells = lcb;
875                     if(this.getRowClass){
876                         alt.push(this.getRowClass(r, rowIndex));
877                     }
878                     if (hasListener) {
879                         rowcfg = {
880                              
881                             record: r,
882                             rowIndex : rowIndex,
883                             rowClass : ''
884                         }
885                         this.grid.fireEvent('rowclass', this, rowcfg);
886                         alt.push(rowcfg.rowClass);
887                     }
888                     rp.alt = alt.join(" ");
889                     lbuf+= rt.apply(rp);
890                     rp.cells = cb;
891                     buf+=  rt.apply(rp);
892                 }
893                 return [lbuf, buf];
894             } :
895             function(cs, rs, ds, startRow, colCount, stripe){
896                 var ts = this.templates, ct = ts.cell, rt = ts.row;
897                 // buffers
898                 var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r, rowIndex;
899                 var hasListener = this.grid.hasListener('rowclass');
900                 var rowcfg = {};
901                 for(var j = 0, len = rs.length; j < len; j++){
902                     r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
903                     for(var i = 0; i < colCount; i++){
904                         c = cs[i];
905                         p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
906                         p.id = c.id;
907                         p.css = p.attr = "";
908                         p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
909                         if(p.value == undefined || p.value === "") p.value = "&#160;";
910                         if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
911                             p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell';
912                         }
913                         var markup = ct.apply(p);
914                         if(!c.locked){
915                             cb[cb.length] = markup;
916                         }else{
917                             lcb[lcb.length] = markup;
918                         }
919                     }
920                     var alt = [];
921                     if(stripe && ((rowIndex+1) % 2 == 0)){
922                         alt.push( "x-grid-row-alt");
923                     }
924                     if(r.dirty){
925                         alt.push(" x-grid-dirty-row");
926                     }
927                     rp.cells = lcb;
928                     if(this.getRowClass){
929                         alt.push( this.getRowClass(r, rowIndex));
930                     }
931                     if (hasListener) {
932                         rowcfg = {
933                              
934                             record: r,
935                             rowIndex : rowIndex,
936                             rowClass : ''
937                         }
938                         this.grid.fireEvent('rowclass', this, rowcfg);
939                         alt.push(rowcfg.rowClass);
940                     }
941                     rp.alt = alt.join(" ");
942                     rp.cells = lcb.join("");
943                     lbuf[lbuf.length] = rt.apply(rp);
944                     rp.cells = cb.join("");
945                     buf[buf.length] =  rt.apply(rp);
946                 }
947                 return [lbuf.join(""), buf.join("")];
948             },
949
950     renderBody : function(){
951         var markup = this.renderRows();
952         var bt = this.templates.body;
953         return [bt.apply({rows: markup[0]}), bt.apply({rows: markup[1]})];
954     },
955
956     /**
957      * Refreshes the grid
958      * @param {Boolean} headersToo
959      */
960     refresh : function(headersToo){
961         this.fireEvent("beforerefresh", this);
962         this.grid.stopEditing();
963         var result = this.renderBody();
964         this.lockedBody.update(result[0]);
965         this.mainBody.update(result[1]);
966         if(headersToo === true){
967             this.updateHeaders();
968             this.updateColumns();
969             this.updateSplitters();
970             this.updateHeaderSortState();
971         }
972         this.syncRowHeights();
973         this.layout();
974         this.fireEvent("refresh", this);
975     },
976
977     handleColumnMove : function(cm, oldIndex, newIndex){
978         this.indexMap = null;
979         var s = this.getScrollState();
980         this.refresh(true);
981         this.restoreScroll(s);
982         this.afterMove(newIndex);
983     },
984
985     afterMove : function(colIndex){
986         if(this.enableMoveAnim && Roo.enableFx){
987             this.fly(this.getHeaderCell(colIndex).firstChild).highlight(this.hlColor);
988         }
989     },
990
991     updateCell : function(dm, rowIndex, dataIndex){
992         var colIndex = this.getColumnIndexByDataIndex(dataIndex);
993         if(typeof colIndex == "undefined"){ // not present in grid
994             return;
995         }
996         var cm = this.grid.colModel;
997         var cell = this.getCell(rowIndex, colIndex);
998         var cellText = this.getCellText(rowIndex, colIndex);
999
1000         var p = {
1001             cellId : "x-grid-cell-" + rowIndex + "-" + colIndex,
1002             id : cm.getColumnId(colIndex),
1003             css: colIndex == cm.getColumnCount()-1 ? "x-grid-col-last" : ""
1004         };
1005         var renderer = cm.getRenderer(colIndex);
1006         var val = renderer(dm.getValueAt(rowIndex, dataIndex), p, rowIndex, colIndex, dm);
1007         if(typeof val == "undefined" || val === "") val = "&#160;";
1008         cellText.innerHTML = val;
1009         cell.className = this.cellClass + " " + this.idToCssName(p.cellId) + " " + p.css;
1010         this.syncRowHeights(rowIndex, rowIndex);
1011     },
1012
1013     calcColumnWidth : function(colIndex, maxRowsToMeasure){
1014         var maxWidth = 0;
1015         if(this.grid.autoSizeHeaders){
1016             var h = this.getHeaderCellMeasure(colIndex);
1017             maxWidth = Math.max(maxWidth, h.scrollWidth);
1018         }
1019         var tb, index;
1020         if(this.cm.isLocked(colIndex)){
1021             tb = this.getLockedTable();
1022             index = colIndex;
1023         }else{
1024             tb = this.getBodyTable();
1025             index = colIndex - this.cm.getLockedCount();
1026         }
1027         if(tb && tb.rows){
1028             var rows = tb.rows;
1029             var stopIndex = Math.min(maxRowsToMeasure || rows.length, rows.length);
1030             for(var i = 0; i < stopIndex; i++){
1031                 var cell = rows[i].childNodes[index].firstChild;
1032                 maxWidth = Math.max(maxWidth, cell.scrollWidth);
1033             }
1034         }
1035         return maxWidth + /*margin for error in IE*/ 5;
1036     },
1037     /**
1038      * Autofit a column to its content.
1039      * @param {Number} colIndex
1040      * @param {Boolean} forceMinSize true to force the column to go smaller if possible
1041      */
1042      autoSizeColumn : function(colIndex, forceMinSize, suppressEvent){
1043          if(this.cm.isHidden(colIndex)){
1044              return; // can't calc a hidden column
1045          }
1046         if(forceMinSize){
1047             var cid = this.cm.getColumnId(colIndex);
1048             this.css.updateRule(this.colSelector +this.idToCssName( cid), "width", this.grid.minColumnWidth + "px");
1049            if(this.grid.autoSizeHeaders){
1050                this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", this.grid.minColumnWidth + "px");
1051            }
1052         }
1053         var newWidth = this.calcColumnWidth(colIndex);
1054         this.cm.setColumnWidth(colIndex,
1055             Math.max(this.grid.minColumnWidth, newWidth), suppressEvent);
1056         if(!suppressEvent){
1057             this.grid.fireEvent("columnresize", colIndex, newWidth);
1058         }
1059     },
1060
1061     /**
1062      * Autofits all columns to their content and then expands to fit any extra space in the grid
1063      */
1064      autoSizeColumns : function(){
1065         var cm = this.grid.colModel;
1066         var colCount = cm.getColumnCount();
1067         for(var i = 0; i < colCount; i++){
1068             this.autoSizeColumn(i, true, true);
1069         }
1070         if(cm.getTotalWidth() < this.scroller.dom.clientWidth){
1071             this.fitColumns();
1072         }else{
1073             this.updateColumns();
1074             this.layout();
1075         }
1076     },
1077
1078     /**
1079      * Autofits all columns to the grid's width proportionate with their current size
1080      * @param {Boolean} reserveScrollSpace Reserve space for a scrollbar
1081      */
1082     fitColumns : function(reserveScrollSpace){
1083         var cm = this.grid.colModel;
1084         var colCount = cm.getColumnCount();
1085         var cols = [];
1086         var width = 0;
1087         var i, w;
1088         for (i = 0; i < colCount; i++){
1089             if(!cm.isHidden(i) && !cm.isFixed(i)){
1090                 w = cm.getColumnWidth(i);
1091                 cols.push(i);
1092                 cols.push(w);
1093                 width += w;
1094             }
1095         }
1096         var avail = Math.min(this.scroller.dom.clientWidth, this.el.getWidth());
1097         if(reserveScrollSpace){
1098             avail -= 17;
1099         }
1100         var frac = (avail - cm.getTotalWidth())/width;
1101         while (cols.length){
1102             w = cols.pop();
1103             i = cols.pop();
1104             cm.setColumnWidth(i, Math.floor(w + w*frac), true);
1105         }
1106         this.updateColumns();
1107         this.layout();
1108     },
1109
1110     onRowSelect : function(rowIndex){
1111         var row = this.getRowComposite(rowIndex);
1112         row.addClass("x-grid-row-selected");
1113     },
1114
1115     onRowDeselect : function(rowIndex){
1116         var row = this.getRowComposite(rowIndex);
1117         row.removeClass("x-grid-row-selected");
1118     },
1119
1120     onCellSelect : function(row, col){
1121         var cell = this.getCell(row, col);
1122         if(cell){
1123             Roo.fly(cell).addClass("x-grid-cell-selected");
1124         }
1125     },
1126
1127     onCellDeselect : function(row, col){
1128         var cell = this.getCell(row, col);
1129         if(cell){
1130             Roo.fly(cell).removeClass("x-grid-cell-selected");
1131         }
1132     },
1133
1134     updateHeaderSortState : function(){
1135         var state = this.ds.getSortState();
1136         if(!state){
1137             return;
1138         }
1139         this.sortState = state;
1140         var sortColumn = this.cm.findColumnIndex(state.field);
1141         if(sortColumn != -1){
1142             var sortDir = state.direction;
1143             var sc = this.sortClasses;
1144             var hds = this.el.select(this.headerSelector).removeClass(sc);
1145             hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]);
1146         }
1147     },
1148
1149     handleHeaderClick : function(g, index){
1150         if(this.headersDisabled){
1151             return;
1152         }
1153         var dm = g.dataSource, cm = g.colModel;
1154         if(!cm.isSortable(index)){
1155             return;
1156         }
1157         g.stopEditing();
1158         dm.sort(cm.getDataIndex(index));
1159     },
1160
1161
1162     destroy : function(){
1163         if(this.colMenu){
1164             this.colMenu.removeAll();
1165             Roo.menu.MenuMgr.unregister(this.colMenu);
1166             this.colMenu.getEl().remove();
1167             delete this.colMenu;
1168         }
1169         if(this.hmenu){
1170             this.hmenu.removeAll();
1171             Roo.menu.MenuMgr.unregister(this.hmenu);
1172             this.hmenu.getEl().remove();
1173             delete this.hmenu;
1174         }
1175         if(this.grid.enableColumnMove){
1176             var dds = Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
1177             if(dds){
1178                 for(var dd in dds){
1179                     if(!dds[dd].config.isTarget && dds[dd].dragElId){
1180                         var elid = dds[dd].dragElId;
1181                         dds[dd].unreg();
1182                         Roo.get(elid).remove();
1183                     } else if(dds[dd].config.isTarget){
1184                         dds[dd].proxyTop.remove();
1185                         dds[dd].proxyBottom.remove();
1186                         dds[dd].unreg();
1187                     }
1188                     if(Roo.dd.DDM.locationCache[dd]){
1189                         delete Roo.dd.DDM.locationCache[dd];
1190                     }
1191                 }
1192                 delete Roo.dd.DDM.ids['gridHeader' + this.grid.getGridEl().id];
1193             }
1194         }
1195         Roo.util.CSS.removeStyleSheet(this.idToCssName(this.grid.id) + '-cssrules');
1196         this.bind(null, null);
1197         Roo.EventManager.removeResizeListener(this.onWindowResize, this);
1198     },
1199
1200     handleLockChange : function(){
1201         this.refresh(true);
1202     },
1203
1204     onDenyColumnLock : function(){
1205
1206     },
1207
1208     onDenyColumnHide : function(){
1209
1210     },
1211
1212     handleHdMenuClick : function(item){
1213         var index = this.hdCtxIndex;
1214         var cm = this.cm, ds = this.ds;
1215         switch(item.id){
1216             case "asc":
1217                 ds.sort(cm.getDataIndex(index), "ASC");
1218                 break;
1219             case "desc":
1220                 ds.sort(cm.getDataIndex(index), "DESC");
1221                 break;
1222             case "lock":
1223                 var lc = cm.getLockedCount();
1224                 if(cm.getColumnCount(true) <= lc+1){
1225                     this.onDenyColumnLock();
1226                     return;
1227                 }
1228                 if(lc != index){
1229                     cm.setLocked(index, true, true);
1230                     cm.moveColumn(index, lc);
1231                     this.grid.fireEvent("columnmove", index, lc);
1232                 }else{
1233                     cm.setLocked(index, true);
1234                 }
1235             break;
1236             case "unlock":
1237                 var lc = cm.getLockedCount();
1238                 if((lc-1) != index){
1239                     cm.setLocked(index, false, true);
1240                     cm.moveColumn(index, lc-1);
1241                     this.grid.fireEvent("columnmove", index, lc-1);
1242                 }else{
1243                     cm.setLocked(index, false);
1244                 }
1245             break;
1246             default:
1247                 index = cm.getIndexById(item.id.substr(4));
1248                 if(index != -1){
1249                     if(item.checked && cm.getColumnCount(true) <= 1){
1250                         this.onDenyColumnHide();
1251                         return false;
1252                     }
1253                     cm.setHidden(index, item.checked);
1254                 }
1255         }
1256         return true;
1257     },
1258
1259     beforeColMenuShow : function(){
1260         var cm = this.cm,  colCount = cm.getColumnCount();
1261         this.colMenu.removeAll();
1262         for(var i = 0; i < colCount; i++){
1263             this.colMenu.add(new Roo.menu.CheckItem({
1264                 id: "col-"+cm.getColumnId(i),
1265                 text: cm.getColumnHeader(i),
1266                 checked: !cm.isHidden(i),
1267                 hideOnClick:false
1268             }));
1269         }
1270     },
1271
1272     handleHdCtx : function(g, index, e){
1273         e.stopEvent();
1274         var hd = this.getHeaderCell(index);
1275         this.hdCtxIndex = index;
1276         var ms = this.hmenu.items, cm = this.cm;
1277         ms.get("asc").setDisabled(!cm.isSortable(index));
1278         ms.get("desc").setDisabled(!cm.isSortable(index));
1279         if(this.grid.enableColLock !== false){
1280             ms.get("lock").setDisabled(cm.isLocked(index));
1281             ms.get("unlock").setDisabled(!cm.isLocked(index));
1282         }
1283         this.hmenu.show(hd, "tl-bl");
1284     },
1285
1286     handleHdOver : function(e){
1287         var hd = this.findHeaderCell(e.getTarget());
1288         if(hd && !this.headersDisabled){
1289             if(this.grid.colModel.isSortable(this.getCellIndex(hd))){
1290                this.fly(hd).addClass("x-grid-hd-over");
1291             }
1292         }
1293     },
1294
1295     handleHdOut : function(e){
1296         var hd = this.findHeaderCell(e.getTarget());
1297         if(hd){
1298             this.fly(hd).removeClass("x-grid-hd-over");
1299         }
1300     },
1301
1302     handleSplitDblClick : function(e, t){
1303         var i = this.getCellIndex(t);
1304         if(this.grid.enableColumnResize !== false && this.cm.isResizable(i) && !this.cm.isFixed(i)){
1305             this.autoSizeColumn(i, true);
1306             this.layout();
1307         }
1308     },
1309
1310     render : function(){
1311
1312         var cm = this.cm;
1313         var colCount = cm.getColumnCount();
1314
1315         if(this.grid.monitorWindowResize === true){
1316             Roo.EventManager.onWindowResize(this.onWindowResize, this, true);
1317         }
1318         var header = this.renderHeaders();
1319         var body = this.templates.body.apply({rows:""});
1320         var html = this.templates.master.apply({
1321             lockedBody: body,
1322             body: body,
1323             lockedHeader: header[0],
1324             header: header[1]
1325         });
1326
1327         //this.updateColumns();
1328
1329         this.grid.getGridEl().dom.innerHTML = html;
1330
1331         this.initElements();
1332         
1333         // a kludge to fix the random scolling effect in webkit
1334         this.el.on("scroll", function() {
1335             this.el.dom.scrollTop=0; // hopefully not recursive..
1336         },this);
1337
1338         this.scroller.on("scroll", this.handleScroll, this);
1339         this.lockedBody.on("mousewheel", this.handleWheel, this);
1340         this.mainBody.on("mousewheel", this.handleWheel, this);
1341
1342         this.mainHd.on("mouseover", this.handleHdOver, this);
1343         this.mainHd.on("mouseout", this.handleHdOut, this);
1344         this.mainHd.on("dblclick", this.handleSplitDblClick, this,
1345                 {delegate: "."+this.splitClass});
1346
1347         this.lockedHd.on("mouseover", this.handleHdOver, this);
1348         this.lockedHd.on("mouseout", this.handleHdOut, this);
1349         this.lockedHd.on("dblclick", this.handleSplitDblClick, this,
1350                 {delegate: "."+this.splitClass});
1351
1352         if(this.grid.enableColumnResize !== false && Roo.grid.SplitDragZone){
1353             new Roo.grid.SplitDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
1354         }
1355
1356         this.updateSplitters();
1357
1358         if(this.grid.enableColumnMove && Roo.grid.HeaderDragZone){
1359             new Roo.grid.HeaderDragZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
1360             new Roo.grid.HeaderDropZone(this.grid, this.lockedHd.dom, this.mainHd.dom);
1361         }
1362
1363         if(this.grid.enableCtxMenu !== false && Roo.menu.Menu){
1364             this.hmenu = new Roo.menu.Menu({id: this.grid.id + "-hctx"});
1365             this.hmenu.add(
1366                 {id:"asc", text: this.sortAscText, cls: "xg-hmenu-sort-asc"},
1367                 {id:"desc", text: this.sortDescText, cls: "xg-hmenu-sort-desc"}
1368             );
1369             if(this.grid.enableColLock !== false){
1370                 this.hmenu.add('-',
1371                     {id:"lock", text: this.lockText, cls: "xg-hmenu-lock"},
1372                     {id:"unlock", text: this.unlockText, cls: "xg-hmenu-unlock"}
1373                 );
1374             }
1375             if(this.grid.enableColumnHide !== false){
1376
1377                 this.colMenu = new Roo.menu.Menu({id:this.grid.id + "-hcols-menu"});
1378                 this.colMenu.on("beforeshow", this.beforeColMenuShow, this);
1379                 this.colMenu.on("itemclick", this.handleHdMenuClick, this);
1380
1381                 this.hmenu.add('-',
1382                     {id:"columns", text: this.columnsText, menu: this.colMenu}
1383                 );
1384             }
1385             this.hmenu.on("itemclick", this.handleHdMenuClick, this);
1386
1387             this.grid.on("headercontextmenu", this.handleHdCtx, this);
1388         }
1389
1390         if((this.grid.enableDragDrop || this.grid.enableDrag) && Roo.grid.GridDragZone){
1391             this.dd = new Roo.grid.GridDragZone(this.grid, {
1392                 ddGroup : this.grid.ddGroup || 'GridDD'
1393             });
1394         }
1395
1396         /*
1397         for(var i = 0; i < colCount; i++){
1398             if(cm.isHidden(i)){
1399                 this.hideColumn(i);
1400             }
1401             if(cm.config[i].align){
1402                 this.css.updateRule(this.colSelector + i, "textAlign", cm.config[i].align);
1403                 this.css.updateRule(this.hdSelector + i, "textAlign", cm.config[i].align);
1404             }
1405         }*/
1406         
1407         this.updateHeaderSortState();
1408
1409         this.beforeInitialResize();
1410         this.layout(true);
1411
1412         // two part rendering gives faster view to the user
1413         this.renderPhase2.defer(1, this);
1414     },
1415
1416     renderPhase2 : function(){
1417         // render the rows now
1418         this.refresh();
1419         if(this.grid.autoSizeColumns){
1420             this.autoSizeColumns();
1421         }
1422     },
1423
1424     beforeInitialResize : function(){
1425
1426     },
1427
1428     onColumnSplitterMoved : function(i, w){
1429         this.userResized = true;
1430         var cm = this.grid.colModel;
1431         cm.setColumnWidth(i, w, true);
1432         var cid = cm.getColumnId(i);
1433         this.css.updateRule(this.colSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
1434         this.css.updateRule(this.hdSelector + this.idToCssName(cid), "width", (w-this.borderWidth) + "px");
1435         this.updateSplitters();
1436         this.layout();
1437         this.grid.fireEvent("columnresize", i, w);
1438     },
1439
1440     syncRowHeights : function(startIndex, endIndex){
1441         if(this.grid.enableRowHeightSync === true && this.cm.getLockedCount() > 0){
1442             startIndex = startIndex || 0;
1443             var mrows = this.getBodyTable().rows;
1444             var lrows = this.getLockedTable().rows;
1445             var len = mrows.length-1;
1446             endIndex = Math.min(endIndex || len, len);
1447             for(var i = startIndex; i <= endIndex; i++){
1448                 var m = mrows[i], l = lrows[i];
1449                 var h = Math.max(m.offsetHeight, l.offsetHeight);
1450                 m.style.height = l.style.height = h + "px";
1451             }
1452         }
1453     },
1454
1455     layout : function(initialRender, is2ndPass){
1456         var g = this.grid;
1457         var auto = g.autoHeight;
1458         var scrollOffset = 16;
1459         var c = g.getGridEl(), cm = this.cm,
1460                 expandCol = g.autoExpandColumn,
1461                 gv = this;
1462         //c.beginMeasure();
1463
1464         if(!c.dom.offsetWidth){ // display:none?
1465             if(initialRender){
1466                 this.lockedWrap.show();
1467                 this.mainWrap.show();
1468             }
1469             return;
1470         }
1471
1472         var hasLock = this.cm.isLocked(0);
1473
1474         var tbh = this.headerPanel.getHeight();
1475         var bbh = this.footerPanel.getHeight();
1476
1477         if(auto){
1478             var ch = this.getBodyTable().offsetHeight + tbh + bbh + this.mainHd.getHeight();
1479             var newHeight = ch + c.getBorderWidth("tb");
1480             if(g.maxHeight){
1481                 newHeight = Math.min(g.maxHeight, newHeight);
1482             }
1483             c.setHeight(newHeight);
1484         }
1485
1486         if(g.autoWidth){
1487             c.setWidth(cm.getTotalWidth()+c.getBorderWidth('lr'));
1488         }
1489
1490         var s = this.scroller;
1491
1492         var csize = c.getSize(true);
1493
1494         this.el.setSize(csize.width, csize.height);
1495
1496         this.headerPanel.setWidth(csize.width);
1497         this.footerPanel.setWidth(csize.width);
1498
1499         var hdHeight = this.mainHd.getHeight();
1500         var vw = csize.width;
1501         var vh = csize.height - (tbh + bbh);
1502
1503         s.setSize(vw, vh);
1504
1505         var bt = this.getBodyTable();
1506         var ltWidth = hasLock ?
1507                       Math.max(this.getLockedTable().offsetWidth, this.lockedHd.dom.firstChild.offsetWidth) : 0;
1508
1509         var scrollHeight = bt.offsetHeight;
1510         var scrollWidth = ltWidth + bt.offsetWidth;
1511         var vscroll = false, hscroll = false;
1512
1513         this.scrollSizer.setSize(scrollWidth, scrollHeight+hdHeight);
1514
1515         var lw = this.lockedWrap, mw = this.mainWrap;
1516         var lb = this.lockedBody, mb = this.mainBody;
1517
1518         setTimeout(function(){
1519             var t = s.dom.offsetTop;
1520             var w = s.dom.clientWidth,
1521                 h = s.dom.clientHeight;
1522
1523             lw.setTop(t);
1524             lw.setSize(ltWidth, h);
1525
1526             mw.setLeftTop(ltWidth, t);
1527             mw.setSize(w-ltWidth, h);
1528
1529             lb.setHeight(h-hdHeight);
1530             mb.setHeight(h-hdHeight);
1531
1532             if(is2ndPass !== true && !gv.userResized && expandCol){
1533                 // high speed resize without full column calculation
1534                 
1535                 var ci = cm.getIndexById(expandCol);
1536                 if (ci < 0) {
1537                     ci = cm.findColumnIndex(expandCol);
1538                 }
1539                 ci = Math.max(0, ci); // make sure it's got at least the first col.
1540                 var expandId = cm.getColumnId(ci);
1541                 var  tw = cm.getTotalWidth(false);
1542                 var currentWidth = cm.getColumnWidth(ci);
1543                 var cw = Math.min(Math.max(((w-tw)+currentWidth-2)-/*scrollbar*/(w <= s.dom.offsetWidth ? 0 : 18), g.autoExpandMin), g.autoExpandMax);
1544                 if(currentWidth != cw){
1545                     cm.setColumnWidth(ci, cw, true);
1546                     gv.css.updateRule(gv.colSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
1547                     gv.css.updateRule(gv.hdSelector+gv.idToCssName(expandId), "width", (cw - gv.borderWidth) + "px");
1548                     gv.updateSplitters();
1549                     gv.layout(false, true);
1550                 }
1551             }
1552
1553             if(initialRender){
1554                 lw.show();
1555                 mw.show();
1556             }
1557             //c.endMeasure();
1558         }, 10);
1559     },
1560
1561     onWindowResize : function(){
1562         if(!this.grid.monitorWindowResize || this.grid.autoHeight){
1563             return;
1564         }
1565         this.layout();
1566     },
1567
1568     appendFooter : function(parentEl){
1569         return null;
1570     },
1571
1572     sortAscText : "Sort Ascending",
1573     sortDescText : "Sort Descending",
1574     lockText : "Lock Column",
1575     unlockText : "Unlock Column",
1576     columnsText : "Columns"
1577 });
1578
1579
1580 Roo.grid.GridView.ColumnDragZone = function(grid, hd){
1581     Roo.grid.GridView.ColumnDragZone.superclass.constructor.call(this, grid, hd, null);
1582     this.proxy.el.addClass('x-grid3-col-dd');
1583 };
1584
1585 Roo.extend(Roo.grid.GridView.ColumnDragZone, Roo.grid.HeaderDragZone, {
1586     handleMouseDown : function(e){
1587
1588     },
1589
1590     callHandleMouseDown : function(e){
1591         Roo.grid.GridView.ColumnDragZone.superclass.handleMouseDown.call(this, e);
1592     }
1593 });