My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

configurator.js 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. /**
  2. * configurator.js
  3. *
  4. * Marlin Configuration Utility
  5. * - Web form for entering configuration options
  6. * - A reprap calculator to calculate movement values
  7. * - Uses HTML5 to generate downloadables in Javascript
  8. * - Reads and parses standard configuration files from local folders
  9. *
  10. * Supporting functions
  11. * - Parser to read Marlin Configuration.h and Configuration_adv.h files
  12. * - Utilities to replace values in configuration files
  13. */
  14. "use strict";
  15. $(function(){
  16. var marlin_config = 'config';
  17. // Extend String
  18. String.prototype.lpad = function(len, chr) {
  19. if (chr === undefined) { chr = ' '; }
  20. var s = this+'', need = len - s.length;
  21. if (need > 0) { s = new Array(need+1).join(chr) + s; }
  22. return s;
  23. };
  24. String.prototype.prePad = function(len, chr) {
  25. return len ? this.lpad(len, chr) : this;
  26. };
  27. String.prototype.zeroPad = function(len) {
  28. return len ? this.prePad(len, '0') : this;
  29. };
  30. String.prototype.regEsc = function() {
  31. return this.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
  32. }
  33. /**
  34. * selectField.addOptions takes an array or keyed object
  35. */
  36. $.fn.extend({
  37. addOptions: function(arrObj) {
  38. return this.each(function() {
  39. var sel = $(this);
  40. var isArr = Object.prototype.toString.call(arrObj) == "[object Array]";
  41. $.each(arrObj, function(k, v) {
  42. sel.append( $('<option>',{value:isArr?v:k}).text(v) );
  43. });
  44. });
  45. }
  46. });
  47. // The app is a singleton
  48. var configuratorApp = (function(){
  49. // private variables and functions go here
  50. var self,
  51. pi2 = Math.PI * 2,
  52. has_boards = false, has_config = false, has_config_adv = false,
  53. boards_file = 'boards.h',
  54. config_file = 'Configuration.h',
  55. config_adv_file = 'Configuration_adv.h',
  56. $config = $('#config_text'),
  57. $config_adv = $('#config_adv_text'),
  58. boards_list = {},
  59. therms_list = {},
  60. total_config_lines,
  61. total_config_adv_lines;
  62. // Return this anonymous object as configuratorApp
  63. return {
  64. my_public_var: 4,
  65. logging: 1,
  66. init: function() {
  67. self = this; // a 'this' for use when 'this' is something else
  68. // Set up the form
  69. this.setupConfigForm();
  70. // Make tabs for the fieldsets
  71. var $fset = $('#config_form fieldset');
  72. var $tabs = $('<ul>',{class:'tabs'}), ind = 1;
  73. $('#config_form fieldset').each(function(){
  74. var tabID = 'TAB'+ind;
  75. $(this).addClass(tabID);
  76. var $leg = $(this).find('legend');
  77. var $link = $('<a>',{href:'#'+ind,id:tabID}).text($leg.text());
  78. $tabs.append($('<li>').append($link));
  79. $link.click(function(e){
  80. e.preventDefault;
  81. var ind = this.id;
  82. $tabs.find('.active').removeClass('active');
  83. $(this).addClass('active');
  84. $fset.hide();
  85. $fset.filter('.'+this.id).show();
  86. return false;
  87. });
  88. ind++;
  89. });
  90. $tabs.appendTo('#tabs');
  91. $('<br>',{class:'clear'}).appendTo('#tabs');
  92. $tabs.find('a:first').trigger('click');
  93. // Make a droppable file uploader
  94. var $uploader = $('#file-upload');
  95. var fileUploader = new BinaryFileUploader({
  96. element: $uploader[0],
  97. onFileLoad: function(file) { self.handleFileLoad(file, $uploader); }
  98. });
  99. if (!fileUploader.hasFileUploaderSupport()) alert('Your browser doesn\'t support the file reading API');
  100. // Read boards.h
  101. boards_list = {};
  102. var errFunc = function(jqXHR, textStatus, errorThrown) {
  103. alert('Failed to load '+this.url+'. Try the file field.');
  104. };
  105. $.ajax({
  106. url: marlin_config+'/'+boards_file,
  107. type: 'GET',
  108. async: false,
  109. cache: false,
  110. success: function(txt) {
  111. // Get all the boards and save them into an object
  112. self.initBoardsFromText(txt);
  113. has_boards = true;
  114. },
  115. error: errFunc
  116. });
  117. // Read Configuration.h
  118. $.ajax({
  119. url: marlin_config+'/'+config_file,
  120. type: 'GET',
  121. async: false,
  122. cache: false,
  123. success: function(txt) {
  124. // File contents into the textarea
  125. $config.text(txt);
  126. // Get thermistor info too
  127. self.initThermistorsFromText(txt);
  128. has_config = true;
  129. },
  130. error: errFunc
  131. });
  132. // Read Configuration.h
  133. $.ajax({
  134. url: marlin_config+'/'+config_adv_file,
  135. type: 'GET',
  136. async: false,
  137. cache: false,
  138. success: function(txt) {
  139. // File contents into the textarea
  140. $config_adv.text(txt);
  141. has_config_adv = true;
  142. self.refreshConfigForm();
  143. },
  144. error: errFunc
  145. });
  146. },
  147. initBoardsFromText: function(txt) {
  148. boards_list = {};
  149. var r, findDef = new RegExp('[ \\t]*#define[ \\t]+(BOARD_[\\w_]+)[ \\t]+(\\d+)[ \\t]*(//[ \\t]*)?(.+)?', 'gm');
  150. while((r = findDef.exec(txt)) !== null) {
  151. boards_list[r[1]] = r[2].prePad(3, '  ') + " — " + r[4].replace(/\).*/, ')');
  152. }
  153. this.log("Loaded boards", 0);
  154. this.log(boards_list, 0);
  155. },
  156. initThermistorsFromText: function(txt) {
  157. // Get all the thermistors and save them into an object
  158. var r, s, findDef = new RegExp('(//.*\n)+\\s+(#define[ \\t]+TEMP_SENSOR_0)', 'g');
  159. r = findDef.exec(txt);
  160. findDef = new RegExp('^//[ \\t]*([-\\d]+)[ \\t]+is[ \\t]+(.*)[ \\t]*$', 'gm');
  161. while((s = findDef.exec(r[0])) !== null) {
  162. therms_list[s[1]] = s[1].prePad(4, '  ') + " — " + s[2];
  163. }
  164. },
  165. handleFileLoad: function(file, $uploader) {
  166. file += '';
  167. var filename = $uploader.val().replace(/.*[\/\\](.*)$/, '$1');
  168. switch(filename) {
  169. case boards_file:
  170. this.initBoardsFromText(file);
  171. has_boards = true;
  172. $('#MOTHERBOARD').html('').addOptions(boards_list);
  173. if (has_config) this.initField('MOTHERBOARD');
  174. break;
  175. case config_file:
  176. if (has_boards) {
  177. $config.text(file);
  178. has_config = true;
  179. total_config_lines = file.replace(/[^\n]+/g, '').length;
  180. this.initThermistorsFromText(file);
  181. this.purgeDefineInfo(false);
  182. this.refreshConfigForm();
  183. }
  184. else {
  185. alert("Upload a " + boards_file + " file first!");
  186. }
  187. break;
  188. case config_adv_file:
  189. if (has_config) {
  190. $config_adv.text(file);
  191. has_config_adv = true;
  192. total_config_adv_lines = file.replace(/[^\n]+/g, '').length;
  193. this.purgeDefineInfo(true);
  194. this.refreshConfigForm();
  195. }
  196. else {
  197. alert("Upload a " + config_file + " file first!");
  198. }
  199. break;
  200. default:
  201. this.log("Can't parse "+filename, 1);
  202. break;
  203. }
  204. },
  205. setupConfigForm: function() {
  206. // Modify form fields and make the form responsive.
  207. // As values change on the form, we could update the
  208. // contents of text areas containing the configs, for
  209. // example.
  210. // while(!$config_adv.text() == null) {}
  211. // while(!$config.text() == null) {}
  212. // Go through all form items with names
  213. $('#config_form').find('[name]').each(function() {
  214. // Set its id to its name
  215. var name = $(this).attr('name');
  216. $(this).attr({id: name});
  217. // Attach its label sibling
  218. var $label = $(this).prev();
  219. if ($label[0].tagName == 'LABEL') {
  220. $label.attr('for',name);
  221. }
  222. });
  223. // Get all 'switchable' class items and add a checkbox
  224. $('#config_form .switchable').each(function(){
  225. $(this).after(
  226. $('<input>',{type:'checkbox',value:'1',class:'enabler'}).prop('checked',true)
  227. .attr('id',this.id + '-switch')
  228. .change(self.handleSwitch)
  229. );
  230. });
  231. $('#SERIAL_PORT').addOptions([0,1,2,3,4,5,6,7]);
  232. $('#BAUDRATE').addOptions([2400,9600,19200,38400,57600,115200,250000]);
  233. $('#EXTRUDERS').addOptions([1,2,3,4]);
  234. $('#POWER_SUPPLY').addOptions({'1':'ATX','2':'Xbox 360'});
  235. $('#serial_stepper').jstepper({
  236. min: 0,
  237. max: 7,
  238. val: $('#SERIAL_PORT').val(),
  239. arrowWidth: '18px',
  240. arrowHeight: '15px',
  241. color: '#FFF',
  242. acolor: '#F70',
  243. hcolor: '#FF0',
  244. id: 'select-me',
  245. textStyle: {width:'1.5em',fontSize:'120%',textAlign:'center'},
  246. onChange: function(v) { $('#SERIAL_PORT').val(v).trigger('change'); }
  247. });
  248. },
  249. refreshConfigForm: function() {
  250. /**
  251. * For now I'm manually creating these references
  252. * but I should be able to parse Configuration.h
  253. * and iterate the #defines.
  254. *
  255. * For any #ifdef blocks I can create field groups
  256. * which can be dimmed together when the option
  257. * is disabled.
  258. *
  259. * Then we only need to specify exceptions to
  260. * standard behavior, (which is to add a text field)
  261. */
  262. this.initField('SERIAL_PORT');
  263. this.initField('BAUDRATE');
  264. this.initField('BTENABLED');
  265. $('#MOTHERBOARD').html('').addOptions(boards_list);
  266. this.initField('MOTHERBOARD');
  267. this.initField('CUSTOM_MENDEL_NAME');
  268. this.initField('MACHINE_UUID');
  269. this.initField('EXTRUDERS');
  270. this.initField('POWER_SUPPLY');
  271. this.initField('PS_DEFAULT_OFF');
  272. $('#TEMP_SENSOR_0, #TEMP_SENSOR_1, #TEMP_SENSOR_2, #TEMP_SENSOR_BED').html('').addOptions(therms_list);
  273. this.initField('TEMP_SENSOR_0');
  274. this.initField('TEMP_SENSOR_1');
  275. this.initField('TEMP_SENSOR_2');
  276. this.initField('TEMP_SENSOR_BED');
  277. this.initField('TEMP_SENSOR_1_AS_REDUNDANT');
  278. this.initField('MAX_REDUNDANT_TEMP_SENSOR_DIFF');
  279. this.initField('TEMP_RESIDENCY_TIME');
  280. // prettyPrint();
  281. },
  282. /**
  283. * initField - make a field responsive and get info
  284. * about its configuration file define
  285. */
  286. initField: function(name, adv) {
  287. this.log("initField:"+name,3);
  288. var $elm = $('#'+name), elm = $elm[0];
  289. if (elm.defineInfo === undefined) {
  290. elm.defineInfo = this.getDefineInfo(name, adv);
  291. $elm.on($elm.attr('type') == 'text' ? 'input' : 'change', this.handleChange);
  292. }
  293. this.setFieldFromDefine(name);
  294. },
  295. handleChange: function(e) {
  296. self.updateDefineFromField(e.target.id);
  297. },
  298. handleSwitch: function(e) {
  299. var $elm = $(e.target), $prev = $elm.prev();
  300. var on = $elm.prop('checked') || false;
  301. $prev.attr('disabled', !on);
  302. self.setDefineEnabled($prev[0].id, on);
  303. },
  304. /**
  305. * Get the current value of a #define (from the config text)
  306. */
  307. defineValue: function(name) {
  308. this.log('defineValue:'+name,4);
  309. var $elm = $('#'+name), elm = $elm[0], inf = elm.defineInfo;
  310. var result = inf.regex.exec($(inf.field).text());
  311. this.log(result,2);
  312. return inf.type == 'switch' ? result[inf.val_i] != '//' : result[inf.val_i];
  313. },
  314. /**
  315. * Get the current enabled state of a #define (from the config text)
  316. */
  317. defineIsEnabled: function(name) {
  318. this.log('defineIsEnabled:'+name,4);
  319. var $elm = $('#'+name), elm = $elm[0], inf = elm.defineInfo;
  320. var result = inf.regex.exec($(inf.field).text());
  321. this.log(result,2);
  322. var on = result !== null ? result[1].trim() != '//' : true;
  323. this.log(name + ' = ' + on, 4);
  324. return on;
  325. },
  326. /**
  327. * Set a #define enabled or disabled by altering the config text
  328. */
  329. setDefineEnabled: function(name, val) {
  330. this.log('setDefineEnabled:'+name,4);
  331. var $elm = $('#'+name), elm = $elm[0], inf = elm.defineInfo;
  332. var $c = $(inf.field), txt = $c.text();
  333. var slash = val ? '' : '//';
  334. var newline = inf.line
  335. .replace(/^([ \t]*)(\/\/)([ \t]*)/, '$1$3') // remove slashes
  336. .replace(inf.pre+inf.define, inf.pre+slash+inf.define); // add them back
  337. txt = txt.replace(inf.line, newline);
  338. inf.line = newline;
  339. this.log(newline, 2);
  340. $c.text(txt);
  341. // Scroll to reveal the define
  342. this.scrollToDefine(name);
  343. },
  344. /**
  345. * Update a #define (from the form) by altering the config text
  346. */
  347. updateDefineFromField: function(name) {
  348. this.log('updateDefineFromField:'+name,4);
  349. var $elm = $('#'+name), elm = $elm[0], inf = elm.defineInfo;
  350. var $c = $(inf.field), txt = $c.text();
  351. // var result = inf.repl.exec(txt);
  352. // this.log(result, 2);
  353. var isCheck = $elm.attr('type') == 'checkbox',
  354. val = isCheck ? $elm.prop('checked') : $elm.val();
  355. var newline;
  356. switch(inf.type) {
  357. case 'switch':
  358. var slash = val ? '' : '//';
  359. newline = (inf.pre + slash + inf.define + inf.post);
  360. break;
  361. case 'quoted':
  362. if (isCheck) {
  363. this.log(name + ' should not be a checkbox', 1);
  364. var slash = val ? '' : '//';
  365. newline = (inf.pre + slash + inf.define + '"'+val+'"' + inf.post);
  366. }
  367. else {
  368. newline = inf.pre + inf.define + '"'+val+'"' + inf.post;
  369. }
  370. break;
  371. case 'plain':
  372. if (isCheck) {
  373. this.log(name + ' should not be a checkbox', 1);
  374. var slash = val ? '' : '//';
  375. newline = (inf.pre + slash + inf.define + val + inf.post);
  376. }
  377. else {
  378. newline = inf.pre + inf.define + val + inf.post;
  379. }
  380. break;
  381. }
  382. txt = txt.replace(inf.line, newline);
  383. inf.line = newline;
  384. this.log(newline, 2);
  385. $c.text(txt);
  386. // Scroll to reveal the define
  387. this.scrollToDefine(name);
  388. },
  389. /**
  390. * Scroll the field to show a define
  391. */
  392. scrollToDefine: function(name, always) {
  393. this.log('scrollToDefine:'+name,4);
  394. var $elm = $('#'+name), inf = $elm[0].defineInfo, $c = $(inf.field);
  395. // Scroll to the altered text if it isn't visible
  396. var halfHeight = $c.height()/2, scrollHeight = $c.prop('scrollHeight'),
  397. textScrollY = inf.lineNum * scrollHeight/(inf.adv ? total_config_adv_lines : total_config_lines) - halfHeight;
  398. if (textScrollY < 0)
  399. textScrollY = 0;
  400. else if (textScrollY > scrollHeight)
  401. textScrollY = scrollHeight - 1;
  402. if (always == true || Math.abs($c.prop('scrollTop') - textScrollY) > halfHeight)
  403. $c.animate({ scrollTop: textScrollY < 0 ? 0 : textScrollY });
  404. },
  405. /**
  406. * Set a form field to the current #define value in the config text
  407. */
  408. setFieldFromDefine: function(name) {
  409. var $elm = $('#'+name), val = this.defineValue(name);
  410. this.log('setFieldFromDefine:' + name + ' to ' + val, 4);
  411. // Set the field value
  412. $elm.attr('type') == 'checkbox' ? $elm.prop('checked', val) : $elm.val(''+val);
  413. // If the item has a checkbox then set enabled state too
  414. var $cb = $('#'+name+'-switch');
  415. if ($cb.length) {
  416. var on = self.defineIsEnabled(name);
  417. $elm.attr('disabled', !on); // enable/disable the form field (could also dim it)
  418. $cb.prop('checked', on); // check/uncheck the checkbox
  419. }
  420. },
  421. /**
  422. * Purge #define information for one of the config files
  423. */
  424. purgeDefineInfo: function(adv) {
  425. if (typeof adv == 'undefined') adv = false;
  426. $('[defineInfo]').each(function() {
  427. if (adv === this.defineInfo.adv) $(this).removeProp('defineInfo');
  428. });
  429. },
  430. /**
  431. * Update #define information for one of the config files
  432. */
  433. refreshDefineInfo: function(adv) {
  434. if (typeof adv == 'undefined') adv = false;
  435. $('[defineInfo]').each(function() {
  436. if (adv == this.defineInfo.adv) this.defineInfo = self.getDefineInfo(this.id, adv);
  437. });
  438. },
  439. /**
  440. * Get information about a #define from configuration file text:
  441. *
  442. * Pre-examine the #define for its prefix, value position, suffix, etc.
  443. * Construct a regex for the #define to quickly find (and replace) values.
  444. * Store the existing #define line as the key to finding it later.
  445. * Determine the line number of the #define so it can be scrolled to.
  446. */
  447. getDefineInfo: function(name, adv) {
  448. if (typeof adv == 'undefined') adv = false;
  449. this.log('getDefineInfo:'+name,4);
  450. var $elm = $('#'+name), elm = $elm[0];
  451. var $c = adv ? $config_adv : $config;
  452. // a switch line with no value
  453. var findDef = new RegExp('^(.*//)?(.*#define[ \\t]+' + elm.id + ')([ \\t]*/[*/].*)?$', 'm');
  454. var result = findDef.exec($c.text());
  455. if (result !== null) {
  456. var info = {
  457. type:'switch', adv:adv, field:$c[0], val_i: 1,
  458. line: result[0], // whole line
  459. pre: result[1] === undefined ? '' : result[1].replace('//',''),
  460. define: result[2],
  461. post: result[3] === undefined ? '' : result[3]
  462. };
  463. info.repl = info.regex = new RegExp('(.*//)?(.*' + info.define.regEsc() + info.post.regEsc() + ')', 'm');
  464. info.lineNum = this.getLineInText(info.line, $c.text());
  465. this.log(info,2);
  466. return info;
  467. }
  468. // a define with quotes
  469. findDef = new RegExp('^(.*//)?(.*#define[ \\t]+' + elm.id + '[ \\t]+)("[^"]*")([ \\t]*/[*/].*)?$', 'm');
  470. result = findDef.exec($c.text());
  471. if (result !== null) {
  472. var info = {
  473. type:'quoted', adv:adv, field:$c[0], val_i: 2,
  474. line: result[0],
  475. pre: result[1] === undefined ? '' : result[1].replace('//',''),
  476. define: result[2],
  477. post: result[4] === undefined ? '' : result[4]
  478. };
  479. info.regex = new RegExp('(.*//)?.*' + info.define.regEsc() + '"([^"]*)"' + info.post.regEsc(), 'm');
  480. info.repl = new RegExp('((.*//)?.*' + info.define.regEsc() + '")[^"]*("' + info.post.regEsc() + ')', 'm');
  481. info.lineNum = this.getLineInText(info.line, $c.text());
  482. this.log(info,2);
  483. return info;
  484. }
  485. // a define with no quotes
  486. findDef = new RegExp('^(.*//)?(.*#define[ \\t]+' + elm.id + '[ \\t]+)(\\S*)([ \\t]*/[*/].*)?$', 'm');
  487. result = findDef.exec($c.text());
  488. if (result !== null) {
  489. var info = {
  490. type:'plain', adv:adv, field:$c[0], val_i: 2,
  491. line: result[0],
  492. pre: result[1] === undefined ? '' : result[1].replace('//',''),
  493. define: result[2],
  494. post: result[4] === undefined ? '' : result[4]
  495. };
  496. info.regex = new RegExp('(.*//)?.*' + info.define.regEsc() + '(\\S*)' + info.post.regEsc(), 'm');
  497. info.repl = new RegExp('((.*//)?.*' + info.define.regEsc() + ')\\S*(' + info.post.regEsc() + ')', 'm');
  498. info.lineNum = this.getLineInText(info.line, $c.text());
  499. this.log(info,2);
  500. return info;
  501. }
  502. return null;
  503. },
  504. getLineInText: function(line, txt) {
  505. var pos = txt.indexOf(line);
  506. return (pos < 0) ? pos : txt.substr(0, pos).replace(/[^\n]+/g, '').length;
  507. },
  508. log: function(o,l) {
  509. if (l === undefined) l = 0;
  510. if (this.logging>=l*1) console.log(o);
  511. },
  512. logOnce: function(o) {
  513. if (typeof o.didLogThisObject === 'undefined') {
  514. this.log(o);
  515. o.didLogThisObject = true;
  516. }
  517. },
  518. EOF: null
  519. };
  520. })();
  521. // Typically the app would be in its own file, but this would be here
  522. configuratorApp.init();
  523. });