Cell.hx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. package hide.comp.cdb;
  2. import hxd.Key in K;
  3. class Cell extends Component {
  4. static var UID = 0;
  5. static var typeNames = [for( t in Type.getEnumConstructs(cdb.Data.ColumnType) ) t.substr(1).toLowerCase()];
  6. var editor : Editor;
  7. var currentValue : Dynamic;
  8. public var line(default,null) : Line;
  9. public var column(default, null) : cdb.Data.Column;
  10. public var columnIndex(get, never) : Int;
  11. public var value(get, never) : Dynamic;
  12. public var table(get, never) : Table;
  13. public function new( root : Element, line : Line, column : cdb.Data.Column ) {
  14. super(null,root);
  15. this.line = line;
  16. this.editor = line.table.editor;
  17. this.column = column;
  18. @:privateAccess line.cells.push(this);
  19. root.addClass("t_" + typeNames[column.type.getIndex()]);
  20. if( column.kind == Script ) root.addClass("t_script");
  21. refresh();
  22. }
  23. function get_table() return line.table;
  24. function get_columnIndex() return table.sheet.columns.indexOf(column);
  25. inline function get_value() return currentValue;
  26. public function refresh() {
  27. currentValue = Reflect.field(line.obj, column.name);
  28. var html = valueHtml(column, value, line.table.sheet, line.obj);
  29. if( html == "&nbsp;" ) element.text(" ") else if( html.indexOf('<') < 0 && html.indexOf('&') < 0 ) element.text(html) else element.html(html);
  30. updateClasses();
  31. }
  32. function updateClasses() {
  33. element.removeClass("edit");
  34. element.removeClass("edit_long");
  35. switch( column.type ) {
  36. case TBool:
  37. element.removeClass("true false").addClass( value==true ? "true" : "false" );
  38. case TInt, TFloat:
  39. element.removeClass("zero");
  40. if( value == 0 ) element.addClass("zero");
  41. default:
  42. }
  43. }
  44. public function valueHtml( c : cdb.Data.Column, v : Dynamic, sheet : cdb.Sheet, obj : Dynamic ) : String {
  45. if( v == null ) {
  46. if( c.opt )
  47. return "&nbsp;";
  48. return '<span class="error">#NULL</span>';
  49. }
  50. return switch( c.type ) {
  51. case TInt, TFloat:
  52. switch( c.display ) {
  53. case Percent:
  54. (Math.round(v * 10000)/100) + "%";
  55. default:
  56. v + "";
  57. }
  58. case TId:
  59. v == "" ? '<span class="error">#MISSING</span>' : (editor.base.getSheet(sheet.name).index.get(v).obj == obj ? v : '<span class="error">#DUP($v)</span>');
  60. case TString if( c.kind == Script ):
  61. v == "" ? "&nbsp;" : colorizeScript(v);
  62. case TString, TLayer(_):
  63. v == "" ? "&nbsp;" : StringTools.htmlEscape(v).split("\n").join("<br/>");
  64. case TRef(sname):
  65. if( v == "" )
  66. '<span class="error">#MISSING</span>';
  67. else {
  68. var s = editor.base.getSheet(sname);
  69. var i = s.index.get(v);
  70. i == null ? '<span class="error">#REF($v)</span>' : (i.ico == null ? "" : tileHtml(i.ico,true)+" ") + StringTools.htmlEscape(i.disp);
  71. }
  72. case TBool:
  73. v?"Y":"N";
  74. case TEnum(values):
  75. values[v];
  76. case TImage:
  77. '<span class="error">#DEPRECATED</span>';
  78. case TList:
  79. var a : Array<Dynamic> = v;
  80. var ps = sheet.getSub(c);
  81. var out : Array<String> = [];
  82. var size = 0;
  83. for( v in a ) {
  84. var vals = [];
  85. for( c in ps.columns )
  86. switch( c.type ) {
  87. case TList, TProperties:
  88. continue;
  89. default:
  90. vals.push(valueHtml(c, Reflect.field(v, c.name), ps, v));
  91. }
  92. var v = vals.length == 1 ? vals[0] : ""+vals;
  93. if( size > 200 ) {
  94. out.push("...");
  95. break;
  96. }
  97. var vstr = v;
  98. if( v.indexOf("<") >= 0 ) {
  99. vstr = ~/<img src="[^"]+" style="display:none"[^>]+>/g.replace(vstr, "");
  100. vstr = ~/<img src="[^"]+"\/>/g.replace(vstr, "[I]");
  101. vstr = ~/<div id="[^>]+><\/div>/g.replace(vstr, "[D]");
  102. }
  103. vstr = StringTools.trim(vstr);
  104. size += vstr.length;
  105. out.push(v);
  106. }
  107. if( out.length == 0 )
  108. return "";
  109. return out.join(", ");
  110. case TProperties:
  111. var ps = sheet.getSub(c);
  112. var out = [];
  113. for( c in ps.columns ) {
  114. var pval = Reflect.field(v, c.name);
  115. if( pval == null && c.opt ) continue;
  116. out.push(c.name+" : "+valueHtml(c, pval, ps, v));
  117. }
  118. return out.join("<br/>");
  119. case TCustom(name):
  120. var t = editor.base.getCustomType(name);
  121. var a : Array<Dynamic> = v;
  122. var cas = t.cases[a[0]];
  123. var str = cas.name;
  124. if( cas.args.length > 0 ) {
  125. str += "(";
  126. var out = [];
  127. var pos = 1;
  128. for( i in 1...a.length )
  129. out.push(valueHtml(cas.args[i-1], a[i], sheet, this));
  130. str += out.join(",");
  131. str += ")";
  132. }
  133. str;
  134. case TFlags(values):
  135. var v : Int = v;
  136. var flags = [];
  137. for( i in 0...values.length )
  138. if( v & (1 << i) != 0 )
  139. flags.push(StringTools.htmlEscape(values[i]));
  140. flags.length == 0 ? String.fromCharCode(0x2205) : flags.join("|<wbr>");
  141. case TColor:
  142. '<div class="color" style="background-color:#${StringTools.hex(v,6)}"></div>';
  143. case TFile:
  144. var path = ide.getPath(v);
  145. var url = "file://" + path;
  146. var ext = v.split(".").pop().toLowerCase();
  147. var html = v == "" ? '<span class="error">#MISSING</span>' : StringTools.htmlEscape(v);
  148. if( v != "" && !editor.quickExists(path) )
  149. html = '<span class="error">' + html + '</span>';
  150. else if( ext == "png" || ext == "jpg" || ext == "jpeg" || ext == "gif" )
  151. html = '<span class="preview">$html<div class="previewContent"><div class="label"></div><img src="$url" onload="$(this).parent().find(\'.label\').text(this.width+\'x\'+this.height)"/></div></span>';
  152. if( v != "" )
  153. html += ' <input type="submit" value="open" onclick="hide.Ide.inst.openFile(\'$path\')"/>';
  154. html;
  155. case TTilePos:
  156. return tileHtml(v);
  157. case TTileLayer:
  158. var v : cdb.Types.TileLayer = v;
  159. var path = ide.getPath(v.file);
  160. if( !editor.quickExists(path) )
  161. '<span class="error">' + v.file + '</span>';
  162. else
  163. '#DATA';
  164. case TDynamic:
  165. var str = Std.string(v).split("\n").join(" ").split("\t").join("");
  166. if( str.length > 50 ) str = str.substr(0, 47) + "...";
  167. str;
  168. }
  169. }
  170. static var KWDS = ["for","if","var","this","while","else","do","break","continue","switch","function","return","new","throw","try","catch","case","default"];
  171. static var KWD_REG = new EReg([for( k in KWDS ) "(\\b"+k+"\\b)"].join("|"),"g");
  172. function colorizeScript( ecode : String ) {
  173. var code = ecode;
  174. code = StringTools.htmlEscape(code);
  175. code = code.split("\n").join("<br/>");
  176. code = code.split("\t").join("&nbsp;&nbsp;&nbsp;&nbsp;");
  177. // typecheck
  178. var error = new ScriptEditor.ScriptChecker(editor.config, "cdb."+getDocumentName(), ["cdb."+table.sheet.name => line.obj]).check(ecode);
  179. if( error != null )
  180. return '<span class="error">'+code+'</span>';
  181. // strings
  182. code = ~/("[^"]*")/g.replace(code,'<span class="str">$1</span>');
  183. code = ~/('[^']*')/g.replace(code,'<span class="str">$1</span>');
  184. // keywords
  185. code = KWD_REG.map(code, function(r) return '<span class="kwd">${r.matched(0)}</span>');
  186. return code;
  187. }
  188. public function getGroup() : String {
  189. var gid : Null<Int> = Reflect.field(line.obj, "group");
  190. if( gid == null ) return null;
  191. return table.sheet.props.separatorTitles[gid-1];
  192. }
  193. public function getDocumentName() {
  194. var name = table.sheet.name;
  195. if( table.sheet.props.hasGroup ) {
  196. var g = getGroup();
  197. if( g != null ) name += "[group="+g+"]";
  198. }
  199. name += "."+column.name;
  200. return name;
  201. }
  202. function tileHtml( v : cdb.Types.TilePos, ?isInline ) {
  203. var path = ide.getPath(v.file);
  204. if( !editor.quickExists(path) ) {
  205. if( isInline ) return "";
  206. return '<span class="error">' + v.file + '</span>';
  207. }
  208. var id = UID++;
  209. var width = v.size * (v.width == null?1:v.width);
  210. var height = v.size * (v.height == null?1:v.height);
  211. var max = width > height ? width : height;
  212. var zoom = max <= 32 ? 2 : 64 / max;
  213. var inl = isInline ? 'display:inline-block;' : '';
  214. var url = "file://" + path;
  215. var html = '<div class="tile" id="_c${id}" style="width : ${Std.int(width * zoom)}px; height : ${Std.int(height * zoom)}px; background : url(\'$url\') -${Std.int(v.size*v.x*zoom)}px -${Std.int(v.size*v.y*zoom)}px; opacity:0; $inl"></div>';
  216. html += '<img src="$url" style="display:none" onload="$(\'#_c$id\').css({opacity:1, backgroundSize : ((this.width*$zoom)|0)+\'px \' + ((this.height*$zoom)|0)+\'px\' '+(zoom > 1 ? ", imageRendering : 'pixelated'" : "") +'}); if( this.parentNode != null ) this.parentNode.removeChild(this)"/>';
  217. return html;
  218. }
  219. public function isTextInput() {
  220. return switch( column.type ) {
  221. case TString if( column.kind == Script ):
  222. return false;
  223. case TString, TInt, TFloat, TId, TCustom(_), TDynamic, TRef(_):
  224. return true;
  225. default:
  226. return false;
  227. }
  228. }
  229. public function focus() {
  230. editor.focus();
  231. editor.cursor.set(table, this.columnIndex, this.line.index);
  232. }
  233. public function edit() {
  234. switch( column.type ) {
  235. case TString if( column.kind == Script ):
  236. open();
  237. case TInt, TFloat, TString, TId, TCustom(_), TDynamic:
  238. var str = value == null ? "" : editor.base.valToString(column.type, value);
  239. var textSpan = element.wrapInner("<span>").find("span");
  240. var textHeight = textSpan.height();
  241. var textWidth = textSpan.width();
  242. var longText = textHeight > 25 || str.indexOf("\n") >= 0;
  243. element.empty();
  244. element.addClass("edit");
  245. var i = new Element(longText ? "<textarea>" : "<input>").appendTo(element);
  246. i.keypress(function(e) e.stopPropagation());
  247. //if( str != "" && (table.displayMode == Properties || table.displayMode == AllProperties) )
  248. // i.css({ width : Math.ceil(textWidth - 3) + "px" }); -- bug if small text ?
  249. if( longText ) {
  250. element.addClass("edit_long");
  251. i.css({ height : Math.max(25,Math.ceil(textHeight - 1)) + "px" });
  252. }
  253. i.val(str);
  254. i.keydown(function(e) {
  255. switch( e.keyCode ) {
  256. case K.ESCAPE:
  257. refresh();
  258. table.editor.element.focus();
  259. case K.ENTER if( !e.shiftKey ):
  260. closeEdit();
  261. e.preventDefault();
  262. case K.ENTER if( !longText ):
  263. var old = currentValue;
  264. // hack to insert newline and tranform the input into textarea
  265. var newVal = i.val() + "\n";
  266. Reflect.setField(line.obj, column.name, newVal+"x");
  267. refresh();
  268. Reflect.setField(line.obj, column.name,old);
  269. currentValue = newVal;
  270. edit();
  271. (cast element.find("textarea")[0] : js.html.TextAreaElement).setSelectionRange(newVal.length,newVal.length);
  272. e.preventDefault();
  273. case K.UP, K.DOWN if( !longText ):
  274. closeEdit();
  275. return;
  276. case K.TAB:
  277. closeEdit();
  278. e.preventDefault();
  279. editor.cursor.move(e.shiftKey ? -1 : 1, 0, false, false);
  280. var c = editor.cursor.getCell();
  281. if( c != this ) c.edit();
  282. }
  283. e.stopPropagation();
  284. });
  285. i.keyup(function(_) try {
  286. editor.base.parseValue(column.type, i.val());
  287. setErrorMessage(null);
  288. } catch( e : Dynamic ) {
  289. setErrorMessage(StringTools.htmlUnescape(""+e));
  290. });
  291. i.keyup(null);
  292. i.blur(function(_) closeEdit());
  293. i.focus();
  294. i.select();
  295. if( longText ) i.scrollTop(0);
  296. case TBool:
  297. setValue( currentValue == false && column.opt && table.displayMode != Properties ? null : currentValue == null ? true : currentValue ? false : true );
  298. refresh();
  299. case TProperties, TList:
  300. open();
  301. case TRef(name):
  302. var sdat = editor.base.getSheet(name);
  303. if( sdat == null ) return;
  304. element.empty();
  305. element.addClass("edit");
  306. var s = new Element("<select>");
  307. var elts = [for( d in sdat.all ){ id : d.id, ico : d.ico, text : d.disp }];
  308. if( column.opt || currentValue == null || currentValue == "" )
  309. elts.unshift( { id : "~", ico : null, text : "--- None ---" } );
  310. element.append(s);
  311. var props : Dynamic = { data : elts };
  312. if( sdat.props.displayIcon != null ) {
  313. function buildElement(i) {
  314. var text = StringTools.htmlEscape(i.text);
  315. return new Element("<div>"+(i.ico == null ? "<div style='display:inline-block;width:16px'/>" : tileHtml(i.ico,true)) + " " + text+"</div>");
  316. }
  317. props.templateResult = props.templateSelection = buildElement;
  318. }
  319. (untyped s.select2)(props);
  320. (untyped s.select2)("val", currentValue == null ? "" : currentValue);
  321. (untyped s.select2)("open");
  322. var sel2 = s.data("select2");
  323. sel2.$dropdown.find("input").on("keydown", function(e) {
  324. e.stopPropagation();
  325. });
  326. s.change(function(e) {
  327. var val = s.val();
  328. if( val == "~" ) val = null;
  329. setValue(val);
  330. closeEdit();
  331. });
  332. s.on("select2:close", function(_) closeEdit());
  333. case TEnum(values):
  334. element.empty();
  335. element.addClass("edit");
  336. var s = new Element("<select>");
  337. var elts = [for( i in 0...values.length ){ id : ""+i, ico : null, text : values[i] }];
  338. if( column.opt )
  339. elts.unshift( { id : "-1", ico : null, text : "--- None ---" } );
  340. element.append(s);
  341. var props : Dynamic = { data : elts };
  342. (untyped s.select2)(props);
  343. (untyped s.select2)("val", currentValue == null ? "" : currentValue);
  344. (untyped s.select2)("open");
  345. s.change(function(e) {
  346. var val = Std.parseInt(s.val());
  347. if( val < 0 ) val = null;
  348. setValue(val);
  349. closeEdit();
  350. });
  351. s.keydown(function(e) {
  352. switch( e.keyCode ) {
  353. case K.LEFT, K.RIGHT:
  354. s.blur();
  355. return;
  356. case K.TAB:
  357. s.blur();
  358. editor.cursor.move(e.shiftKey? -1:1, 0, false, false);
  359. var c = editor.cursor.getCell();
  360. if( c != this ) c.edit();
  361. e.preventDefault();
  362. default:
  363. }
  364. e.stopPropagation();
  365. });
  366. s.on("select2:close", function(_) closeEdit());
  367. case TColor:
  368. var modal = new Element("<div>").addClass("hide-modal").appendTo(element);
  369. var color = new ColorPicker(element);
  370. color.value = currentValue;
  371. color.open();
  372. color.onChange = function(drag) {
  373. element.find(".color").css({backgroundColor : '#'+StringTools.hex(color.value,6) });
  374. };
  375. color.onClose = function() {
  376. setValue(color.value);
  377. color.remove();
  378. closeEdit();
  379. };
  380. modal.click(function(_) color.close());
  381. case TFile:
  382. ide.chooseFile(["*"], function(file) {
  383. if( file != null ) {
  384. setValue(file);
  385. refresh();
  386. }
  387. });
  388. case TFlags(values):
  389. var div = new Element("<div>").addClass("flagValues");
  390. div.click(function(e) e.stopPropagation()).dblclick(function(e) e.stopPropagation());
  391. var val = currentValue;
  392. for( i in 0...values.length ) {
  393. var f = new Element("<input>").attr("type", "checkbox").prop("checked", val & (1 << i) != 0).change(function(e) {
  394. val &= ~(1 << i);
  395. if( e.getThis().prop("checked") ) val |= 1 << i;
  396. e.stopPropagation();
  397. });
  398. new Element("<label>").text(values[i]).appendTo(div).prepend(f);
  399. }
  400. element.empty();
  401. var modal = new Element("<div>").addClass("hide-modal").appendTo(element);
  402. element.append(div);
  403. modal.click(function(e) {
  404. setValue(val);
  405. refresh();
  406. });
  407. case TTilePos:
  408. var modal = new hide.comp.Modal(element);
  409. modal.element.click(function(_) closeEdit());
  410. var t : cdb.Types.TilePos = currentValue;
  411. var file = t == null ? null : t.file;
  412. var size = t == null ? 16 : t.size;
  413. var pos = t == null ? { x : 0, y : 0, width : 1, height : 1 } : { x : t.x, y : t.y, width : t.width == null ? 1 : t.width, height : t.height == null ? 1 : t.height };
  414. if( file == null ) {
  415. var y = line.index - 1;
  416. while( y >= 0 ) {
  417. var o = line.table.lines[y--];
  418. var v2 = Reflect.field(o.obj, column.name);
  419. if( v2 != null ) {
  420. file = v2.file;
  421. size = v2.size;
  422. break;
  423. }
  424. }
  425. }
  426. function setVal() {
  427. var v : Dynamic = { file : file, size : size, x : pos.x, y : pos.y };
  428. if( pos.width != 1 ) v.width = pos.width;
  429. if( pos.height != 1 ) v.height = pos.height;
  430. setRawValue(v);
  431. }
  432. if( file == null ) {
  433. ide.chooseFile(["png","jpeg","jpg","gif"],function(path) {
  434. file = path;
  435. setVal();
  436. closeEdit();
  437. edit();
  438. });
  439. return;
  440. }
  441. var ts = new hide.comp.TileSelector(file,size,modal.content);
  442. ts.allowRectSelect = true;
  443. ts.allowSizeSelect = true;
  444. ts.allowFileChange = true;
  445. ts.value = pos;
  446. ts.onChange = function(cancel) {
  447. if( !cancel ) {
  448. file = ts.file;
  449. size = ts.size;
  450. pos = ts.value;
  451. setVal();
  452. }
  453. refresh();
  454. focus();
  455. };
  456. case TLayer(_), TTileLayer:
  457. // no edit
  458. case TImage:
  459. // deprecated
  460. }
  461. }
  462. public function open( ?immediate : Bool ) {
  463. if( column.type == TString && column.kind == Script ) {
  464. if( immediate ) return;
  465. var str = value == null ? "" : editor.base.valToString(column.type, value);
  466. @:privateAccess table.toggleList(this, function() return new ScriptTable(editor, this));
  467. } else
  468. @:privateAccess table.toggleList(this, immediate);
  469. }
  470. public function setErrorMessage( msg : String ) {
  471. element.find("div.error").remove();
  472. if( msg == null ) return;
  473. new Element("<div>").addClass("error").html(msg).appendTo(element);
  474. }
  475. function setRawValue( str : Dynamic ) {
  476. var newValue : Dynamic;
  477. if( Std.is(str,String) ) {
  478. newValue = try editor.base.parseValue(column.type, str, false) catch( e : Dynamic ) return;
  479. } else
  480. newValue = str;
  481. if( newValue == null || newValue == currentValue )
  482. return;
  483. switch( column.type ) {
  484. case TId:
  485. var obj = line.obj;
  486. var prevValue = value;
  487. // most likely our obj, unless there was a #DUP
  488. var prevObj = value != null ? table.sheet.index.get(value) : null;
  489. // have we already an obj mapped to the same id ?
  490. var prevTarget = table.sheet.index.get(newValue);
  491. editor.beginChanges();
  492. if( prevObj == null || prevObj.obj == obj ) {
  493. // remap
  494. var m = new Map();
  495. m.set(value, newValue);
  496. editor.base.updateRefs(table.sheet, m);
  497. }
  498. setValue(newValue);
  499. editor.endChanges();
  500. editor.refreshAll();
  501. focus();
  502. /*
  503. // creates or remove a #DUP : need to refresh the whole table
  504. if( prevTarget != null || (prevObj != null && (prevObj.obj != obj || table.sheet.index.get(prevValue) != null)) )
  505. table.refresh();
  506. */
  507. case TString if( column.kind == Script ):
  508. setValue(StringTools.trim(newValue));
  509. case TTilePos:
  510. // if we change a file that has moved, change it for all instances having the same file
  511. editor.beginChanges();
  512. var obj = line.obj;
  513. var change = false;
  514. var oldV : cdb.Types.TilePos = currentValue;
  515. var newV : cdb.Types.TilePos = newValue;
  516. if( newV != null && oldV != null && oldV.file != newV.file && !sys.FileSystem.exists(ide.getPath(oldV.file)) && sys.FileSystem.exists(ide.getPath(newV.file)) ) {
  517. for( l in table.lines) {
  518. if( l == line ) continue;
  519. var t : Dynamic = Reflect.field(l.obj, column.name);
  520. if( t != null && t.file == oldV.file ) {
  521. t.file = newV.file;
  522. change = true;
  523. }
  524. }
  525. }
  526. setValue(newValue);
  527. editor.endChanges();
  528. if( change )
  529. editor.refresh();
  530. default:
  531. setValue(newValue);
  532. }
  533. }
  534. public function setValue( value : Dynamic ) {
  535. currentValue = value;
  536. editor.changeObject(line,column,value);
  537. }
  538. public function closeEdit() {
  539. var str = element.find("input,textarea").val();
  540. if( str != null ) setRawValue(str);
  541. refresh();
  542. focus();
  543. }
  544. }