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 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  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. /**
  17. * Github API useful GET paths. (Start with "https://api.github.com/repos/:owner/:repo/")
  18. *
  19. * contributors Get a list of contributors
  20. * tags Get a list of tags
  21. * contents/[path]?ref=branch/tag/commit Get the contents of a file
  22. */
  23. // GitHub
  24. // Warning! Limited to 60 requests per hour!
  25. var config = {
  26. type: 'github',
  27. host: 'https://api.github.com',
  28. owner: 'thinkyhead',
  29. repo: 'Marlin',
  30. ref: 'marlin_configurator',
  31. path: 'Marlin/configurator/config'
  32. };
  33. /**/
  34. /* // Remote
  35. var config = {
  36. type: 'remote',
  37. host: 'http://www.thinkyhead.com',
  38. path: '_marlin/config'
  39. };
  40. /**/
  41. /* // Local
  42. var config = {
  43. type: 'local',
  44. path: 'config'
  45. };
  46. /**/
  47. function github_command(conf, command, path) {
  48. var req = conf.host+'/repos/'+conf.owner+'/'+conf.repo+'/'+command;
  49. if (path) req += '/' + path;
  50. return req;
  51. }
  52. function config_path(item) {
  53. var path = '', ref = '';
  54. switch(config.type) {
  55. case 'github':
  56. path = github_command(config, 'contents', config.path);
  57. if (config.ref !== undefined) ref = '?ref=' + config.ref;
  58. break;
  59. case 'remote':
  60. path = config.host + '/' + config.path + '/';
  61. break;
  62. case 'local':
  63. path = config.path + '/';
  64. break;
  65. }
  66. return path + '/' + item + ref;
  67. }
  68. // Extend builtins
  69. String.prototype.lpad = function(len, chr) {
  70. if (chr === undefined) { chr = ' '; }
  71. var s = this+'', need = len - s.length;
  72. if (need > 0) { s = new Array(need+1).join(chr) + s; }
  73. return s;
  74. };
  75. String.prototype.prePad = function(len, chr) { return len ? this.lpad(len, chr) : this; };
  76. String.prototype.zeroPad = function(len) { return this.prePad(len, '0'); };
  77. String.prototype.toHTML = function() { return jQuery('<div>').text(this).html(); };
  78. String.prototype.regEsc = function() { return this.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&"); }
  79. String.prototype.lineCount = function() { var len = this.split(/\r?\n|\r/).length; return len > 0 ? len - 1 : 0; };
  80. String.prototype.toLabel = function() { return this.replace(/_/g, ' ').toTitleCase(); }
  81. String.prototype.toTitleCase = function() { return this.replace(/([A-Z])(\w+)/gi, function(m,p1,p2) { return p1.toUpperCase() + p2.toLowerCase(); }); }
  82. Number.prototype.limit = function(m1, m2) {
  83. if (m2 == null) return this > m1 ? m1 : this;
  84. return this < m1 ? m1 : this > m2 ? m2 : this;
  85. };
  86. Date.prototype.fileStamp = function(filename) {
  87. var fs = this.getFullYear()
  88. + ((this.getMonth()+1)+'').zeroPad(2)
  89. + (this.getDate()+'').zeroPad(2)
  90. + (this.getHours()+'').zeroPad(2)
  91. + (this.getMinutes()+'').zeroPad(2)
  92. + (this.getSeconds()+'').zeroPad(2);
  93. if (filename !== undefined)
  94. return filename.replace(/^(.+)(\.\w+)$/g, '$1-['+fs+']$2');
  95. return fs;
  96. }
  97. /**
  98. * selectField.addOptions takes an array or keyed object
  99. */
  100. $.fn.extend({
  101. addOptions: function(arrObj) {
  102. return this.each(function() {
  103. var sel = $(this);
  104. var isArr = Object.prototype.toString.call(arrObj) == "[object Array]";
  105. $.each(arrObj, function(k, v) {
  106. sel.append( $('<option>',{value:isArr?v:k}).text(v) );
  107. });
  108. });
  109. },
  110. noSelect: function() {
  111. return this
  112. .attr('unselectable', 'on')
  113. .css('user-select', 'none')
  114. .on('selectstart', false);
  115. }
  116. });
  117. // The app is a singleton
  118. var configuratorApp = (function(){
  119. // private variables and functions go here
  120. var self,
  121. pi2 = Math.PI * 2,
  122. has_boards = false, has_config = false, has_config_adv = false,
  123. boards_file = 'boards.h',
  124. config_file = 'Configuration.h',
  125. config_adv_file = 'Configuration_adv.h',
  126. $msgbox = $('#message'),
  127. $form = $('#config_form'),
  128. $tooltip = $('#tooltip'),
  129. $config = $('#config_text pre'),
  130. $config_adv = $('#config_adv_text pre'),
  131. define_list = [[],[]],
  132. boards_list = {},
  133. therms_list = {},
  134. total_config_lines,
  135. total_config_adv_lines,
  136. hover_timer,
  137. pulse_offset = 0;
  138. // Return this anonymous object as configuratorApp
  139. return {
  140. my_public_var: 4,
  141. logging: 1,
  142. init: function() {
  143. self = this; // a 'this' for use when 'this' is something else
  144. // Set up the form, creating fields and fieldsets as-needed
  145. this.initConfigForm();
  146. // Make tabs for all the fieldsets
  147. this.makeTabsForFieldsets();
  148. // No selection on errors
  149. $msgbox.noSelect();
  150. // Make a droppable file uploader, if possible
  151. var $uploader = $('#file-upload');
  152. var fileUploader = new BinaryFileUploader({
  153. element: $uploader[0],
  154. onFileLoad: function(file) { self.handleFileLoad(file, $uploader); }
  155. });
  156. if (!fileUploader.hasFileUploaderSupport())
  157. this.setMessage("Your browser doesn't support the file reading API.", 'error');
  158. // Make the disclosure items work
  159. $('.disclose').click(function(){
  160. var $dis = $(this), $pre = $dis.nextAll('pre:first');
  161. var didAnim = function() {$dis.toggleClass('closed almost');};
  162. $dis.addClass('almost').hasClass('closed')
  163. ? $pre.slideDown(200, didAnim)
  164. : $pre.slideUp(200, didAnim);
  165. });
  166. // Read boards.h, Configuration.h, Configuration_adv.h
  167. var ajax_count = 0, success_count = 0;
  168. var loaded_items = {};
  169. var config_files = [boards_file, config_file, config_adv_file];
  170. var isGithub = config.type == 'github';
  171. var rateLimit = 0;
  172. $.each(config_files, function(i,fname){
  173. var url = config_path(fname);
  174. $.ajax({
  175. url: url,
  176. type: 'GET',
  177. dataType: isGithub ? 'jsonp' : undefined,
  178. async: true,
  179. cache: false,
  180. error: function(req, stat, err) {
  181. self.log(req, 1);
  182. if (req.status == 200) {
  183. if (typeof req.responseText === 'string') {
  184. var txt = req.responseText;
  185. loaded_items[fname] = function(){ self.fileLoaded(fname, txt); };
  186. success_count++;
  187. // self.setMessage('The request for "'+fname+'" may be malformed.', 'error');
  188. }
  189. }
  190. else {
  191. self.setRequestError(req.status ? req.status : '(Access-Control-Allow-Origin?)', url);
  192. }
  193. },
  194. success: function(txt) {
  195. if (isGithub && typeof txt.meta.status !== undefined && txt.meta.status != 200) {
  196. self.setRequestError(txt.meta.status, url);
  197. }
  198. else {
  199. // self.log(txt, 1);
  200. if (isGithub) {
  201. rateLimit = {
  202. quota: 1 * txt.meta['X-RateLimit-Remaining'],
  203. timeLeft: Math.floor(txt.meta['X-RateLimit-Reset'] - Date.now()/1000),
  204. };
  205. }
  206. loaded_items[fname] = function(){ self.fileLoaded(fname, isGithub ? atob(txt.data.content) : txt); };
  207. success_count++;
  208. }
  209. },
  210. complete: function() {
  211. ajax_count++;
  212. if (ajax_count >= 3) {
  213. $.each(config_files, function(){ if (loaded_items[this]) loaded_items[this](); });
  214. if (success_count < ajax_count)
  215. self.setMessage('Unable to load configurations. Try the upload field.', 'error');
  216. var r;
  217. if (r = rateLimit) {
  218. if (r.quota < 20) {
  219. self.setMessage(
  220. 'Approaching request limit (' +
  221. r.quota + ' remaining.' +
  222. ' Reset in ' + Math.floor(r.timeLeft/60) + ':' + (r.timeLeft%60+'').zeroPad(2) + ')'
  223. );
  224. }
  225. }
  226. }
  227. }
  228. });
  229. });
  230. },
  231. createDownloadLink: function(adv) {
  232. var $c = adv ? $config_adv : $config, txt = $c.text();
  233. var filename = (adv ? config_adv_file : config_file);
  234. $c.prevAll('.download:first')
  235. .mouseover(function() {
  236. var d = new Date(), fn = d.fileStamp(filename);
  237. $(this).attr({ download:fn, href:'download:'+fn, title:'download:'+fn });
  238. })
  239. .click(function(){
  240. var $button = $(this);
  241. $(this).attr({ href:'data:text/plain;charset=utf-8,' + encodeURIComponent($c.text()) });
  242. setTimeout(function(){
  243. $button.attr({ href:$button.attr('title') });
  244. }, 100);
  245. return true;
  246. })
  247. .css({visibility:'visible'});
  248. },
  249. /**
  250. * Init the boards array from a boards.h file
  251. */
  252. initBoardsFromText: function(txt) {
  253. boards_list = {};
  254. var r, findDef = new RegExp('[ \\t]*#define[ \\t]+(BOARD_[\\w_]+)[ \\t]+(\\d+)[ \\t]*(//[ \\t]*)?(.+)?', 'gm');
  255. while((r = findDef.exec(txt)) !== null) {
  256. boards_list[r[1]] = r[2].prePad(3, '  ') + " — " + r[4].replace(/\).*/, ')');
  257. }
  258. this.log("Loaded boards:\n" + Object.keys(boards_list).join('\n'), 3);
  259. has_boards = true;
  260. },
  261. /**
  262. * Init the thermistors array from the Configuration.h file
  263. */
  264. initThermistorsFromText: function(txt) {
  265. // Get all the thermistors and save them into an object
  266. var r, s, findDef = new RegExp('(//.*\n)+\\s+(#define[ \\t]+TEMP_SENSOR_0)', 'g');
  267. r = findDef.exec(txt);
  268. findDef = new RegExp('^//[ \\t]*([-\\d]+)[ \\t]+is[ \\t]+(.*)[ \\t]*$', 'gm');
  269. while((s = findDef.exec(r[0])) !== null) {
  270. therms_list[s[1]] = s[1].prePad(4, '  ') + " — " + s[2];
  271. }
  272. },
  273. /**
  274. * Get all the unique define names
  275. */
  276. getDefinesFromText: function(txt) {
  277. // Get all the unique #define's and save them in an array
  278. var r, define_obj = {}, findDef = new RegExp('#define[ \\t]+(\\w+)', 'gm');
  279. var cnt = 0;
  280. while((r = findDef.exec(txt)) !== null) {
  281. if (cnt++ && !(r[1] in define_obj)) define_obj[r[1]] = null;
  282. }
  283. this.log(Object.keys(define_obj), 2);
  284. return Object.keys(define_obj);
  285. },
  286. /**
  287. * Create placeholder fields for defines, as needed
  288. */
  289. createFieldsForDefines: function(adv) {
  290. var e = adv ? 1 : 0, n = 0;
  291. var fail_list = [];
  292. $.each(define_list[e], function(i,name) {
  293. if (!$('#'+name).length) {
  294. var $ff = $('#more');
  295. var inf = self.getDefineInfo(name, adv);
  296. if (inf) {
  297. var $newlabel = $('<label>',{for:name}).text(name.toLabel());
  298. // if (!(++n % 3))
  299. $newlabel.addClass('newline');
  300. var $newfield = inf.type == 'switch' ? $('<input>',{type:'checkbox'}) : $('<input>',{type:'text',size:10,maxlength:40});
  301. $newfield.attr({id:name,name:name}).prop({defineInfo:inf});
  302. $ff.append($newlabel, $newfield);
  303. }
  304. else
  305. fail_list.push(name);
  306. }
  307. });
  308. if (fail_list) this.log('Unable to parse:\n' + fail_list.join('\n'), 2);
  309. },
  310. /**
  311. * Handle a file being dropped on the file field
  312. */
  313. handleFileLoad: function(txt, $uploader) {
  314. txt += '';
  315. var filename = $uploader.val().replace(/.*[\/\\](.*)$/, '$1');
  316. switch(filename) {
  317. case boards_file:
  318. case config_file:
  319. case config_adv_file:
  320. this.fileLoaded(filename, txt);
  321. break;
  322. default:
  323. this.setMessage("Can't parse '"+filename+"'!");
  324. break;
  325. }
  326. },
  327. /**
  328. * Process a file after it's been successfully loaded
  329. */
  330. fileLoaded: function(filename, txt) {
  331. this.log("fileLoaded:"+filename,4);
  332. var err;
  333. switch(filename) {
  334. case boards_file:
  335. this.initBoardsFromText(txt);
  336. $('#MOTHERBOARD').html('').addOptions(boards_list);
  337. if (has_config) this.initField('MOTHERBOARD');
  338. break;
  339. case config_file:
  340. if (has_boards) {
  341. $config.text(txt);
  342. total_config_lines = txt.lineCount();
  343. this.initThermistorsFromText(txt);
  344. this.purgeDefineInfo(false);
  345. define_list[0] = this.getDefinesFromText(txt);
  346. this.log(define_list[0], 2);
  347. this.createFieldsForDefines(0);
  348. this.refreshConfigForm();
  349. this.createDownloadLink(false);
  350. has_config = true;
  351. }
  352. else {
  353. err = boards_file;
  354. }
  355. break;
  356. case config_adv_file:
  357. if (has_config) {
  358. $config_adv.text(txt);
  359. total_config_adv_lines = txt.lineCount();
  360. this.purgeDefineInfo(true);
  361. define_list[1] = this.getDefinesFromText(txt);
  362. this.log(define_list[1], 2);
  363. this.refreshConfigForm();
  364. this.createDownloadLink(true);
  365. has_config_adv = true;
  366. }
  367. else {
  368. err = config_file;
  369. }
  370. break;
  371. }
  372. this.setMessage(err
  373. ? 'Please upload a "' + boards_file + '" file first!'
  374. : '"' + filename + '" loaded successfully.', err ? 'error' : 'message'
  375. );
  376. },
  377. /**
  378. * Add enhancements to the form
  379. */
  380. initConfigForm: function() {
  381. // Modify form fields and make the form responsive.
  382. // As values change on the form, we could update the
  383. // contents of text areas containing the configs, for
  384. // example.
  385. // while(!$config_adv.text() == null) {}
  386. // while(!$config.text() == null) {}
  387. // Go through all form items with names
  388. $form.find('[name]').each(function() {
  389. // Set its id to its name
  390. var name = $(this).attr('name');
  391. $(this).attr({id: name});
  392. // Attach its label sibling
  393. var $label = $(this).prev('label');
  394. if ($label.length) $label.attr('for',name);
  395. });
  396. // Get all 'switchable' class items and add a checkbox
  397. $form.find('.switchable').each(function(){
  398. $(this).after(
  399. $('<input>',{type:'checkbox',value:'1',class:'enabler'}).prop('checked',true)
  400. .attr('id',this.id + '-switch')
  401. .change(self.handleSwitch)
  402. );
  403. });
  404. // Add options to the popup menus
  405. $('#SERIAL_PORT').addOptions([0,1,2,3,4,5,6,7]);
  406. $('#BAUDRATE').addOptions([2400,9600,19200,38400,57600,115200,250000]);
  407. $('#EXTRUDERS').addOptions([1,2,3,4]);
  408. $('#POWER_SUPPLY').addOptions({'1':'ATX','2':'Xbox 360'});
  409. // Replace the Serial popup menu with a stepper control
  410. $('#serial_stepper').jstepper({
  411. min: 0,
  412. max: 3,
  413. val: $('#SERIAL_PORT').val(),
  414. arrowWidth: '18px',
  415. arrowHeight: '15px',
  416. color: '#FFF',
  417. acolor: '#F70',
  418. hcolor: '#FF0',
  419. id: 'select-me',
  420. textStyle: {width:'1.5em',fontSize:'120%',textAlign:'center'},
  421. onChange: function(v) { $('#SERIAL_PORT').val(v).trigger('change'); }
  422. });
  423. },
  424. /**
  425. * Make tabs to switch between fieldsets
  426. */
  427. makeTabsForFieldsets: function() {
  428. // Make tabs for the fieldsets
  429. var $fset = $form.find('fieldset');
  430. var $tabs = $('<ul>',{class:'tabs'}), ind = 1;
  431. $fset.each(function(){
  432. var tabID = 'TAB'+ind;
  433. $(this).addClass(tabID);
  434. var $leg = $(this).find('legend');
  435. var $link = $('<a>',{href:'#'+ind,id:tabID}).text($leg.text());
  436. $tabs.append($('<li>').append($link));
  437. $link.click(function(e){
  438. e.preventDefault;
  439. var ind = this.id;
  440. $tabs.find('.active').removeClass('active');
  441. $(this).addClass('active');
  442. $fset.hide();
  443. $fset.filter('.'+this.id).show();
  444. return false;
  445. });
  446. ind++;
  447. });
  448. $('#tabs').html('').append($tabs);
  449. $('<br>',{class:'clear'}).appendTo('#tabs');
  450. $tabs.find('a:first').trigger('click');
  451. },
  452. /**
  453. * Update all fields on the form after loading a configuration
  454. */
  455. refreshConfigForm: function() {
  456. /**
  457. * Any manually-created form elements will remain
  458. * where they are. Unknown defines (currently most)
  459. * are added to the "More..." tab for now.
  460. *
  461. * Specific exceptions can be managed by applying
  462. * classes to the associated form fields.
  463. * Sorting and arrangement can come from an included
  464. * js file that describes the configuration in JSON.
  465. *
  466. * For now I'm trying to derive information
  467. * about options directly from the config file.
  468. */
  469. $('#MOTHERBOARD').html('').addOptions(boards_list);
  470. $('#TEMP_SENSOR_0, #TEMP_SENSOR_1, #TEMP_SENSOR_2, #TEMP_SENSOR_BED').html('').addOptions(therms_list);
  471. $.each(define_list, function() { $.each(this, function() { if ($('#'+this).length) self.initField(this); }); });
  472. },
  473. /**
  474. * Make a field responsive and initialize its defineInfo
  475. */
  476. initField: function(name, adv) {
  477. this.log("initField:"+name,4);
  478. var $elm = $('#'+name), elm = $elm[0];
  479. if (elm.defineInfo == null) {
  480. var inf = elm.defineInfo = this.getDefineInfo(name, adv);
  481. $elm.on($elm.attr('type') == 'text' ? 'input' : 'change', this.handleChange);
  482. if (inf.tooltip) {
  483. var $tipme = $elm.prev('label');
  484. if ($tipme.length) {
  485. $tipme.hover(
  486. function() {
  487. if ($('#tipson input').prop('checked')) {
  488. var pos = $tipme.position();
  489. $tooltip.html(inf.tooltip)
  490. .append('<span>')
  491. .css({bottom:($tooltip.parent().outerHeight()-pos.top)+'px',left:(pos.left+70)+'px'})
  492. .show();
  493. if (hover_timer) {
  494. clearTimeout(hover_timer);
  495. hover_timer = null;
  496. }
  497. }
  498. },
  499. function() {
  500. hover_timer = setTimeout(function(){
  501. hover_timer = null;
  502. $tooltip.fadeOut(400);
  503. }, 400);
  504. }
  505. );
  506. }
  507. }
  508. }
  509. this.setFieldFromDefine(name);
  510. },
  511. /**
  512. * Handle any value field being changed
  513. */
  514. handleChange: function() { self.updateDefineFromField(this.id); },
  515. /**
  516. * Handle a switch checkbox being changed
  517. */
  518. handleSwitch: function() {
  519. var $elm = $(this), $prev = $elm.prev();
  520. var on = $elm.prop('checked') || false;
  521. $prev.attr('disabled', !on);
  522. self.setDefineEnabled($prev[0].id, on);
  523. },
  524. /**
  525. * Get the current value of a #define (from the config text)
  526. */
  527. defineValue: function(name) {
  528. this.log('defineValue:'+name,4);
  529. var inf = $('#'+name)[0].defineInfo;
  530. if (inf == null) return 'n/a';
  531. var result = inf.regex.exec($(inf.field).text());
  532. this.log(result,2);
  533. return inf.type == 'switch' ? result[inf.val_i] != '//' : result[inf.val_i];
  534. },
  535. /**
  536. * Get the current enabled state of a #define (from the config text)
  537. */
  538. defineIsEnabled: function(name) {
  539. this.log('defineIsEnabled:'+name,4);
  540. var inf = $('#'+name)[0].defineInfo;
  541. if (inf == null) return false;
  542. var result = inf.regex.exec($(inf.field).text());
  543. this.log(result,2);
  544. var on = result !== null ? result[1].trim() != '//' : true;
  545. this.log(name + ' = ' + on, 2);
  546. return on;
  547. },
  548. /**
  549. * Set a #define enabled or disabled by altering the config text
  550. */
  551. setDefineEnabled: function(name, val) {
  552. this.log('setDefineEnabled:'+name,4);
  553. var inf = $('#'+name)[0].defineInfo;
  554. if (inf) {
  555. var slash = val ? '' : '//';
  556. var newline = inf.line
  557. .replace(/^([ \t]*)(\/\/)([ \t]*)/, '$1$3') // remove slashes
  558. .replace(inf.pre+inf.define, inf.pre+slash+inf.define); // add them back
  559. this.setDefineLine(name, newline);
  560. }
  561. },
  562. /**
  563. * Update a #define (from the form) by altering the config text
  564. */
  565. updateDefineFromField: function(name) {
  566. this.log('updateDefineFromField:'+name,4);
  567. var $elm = $('#'+name), inf = $elm[0].defineInfo;
  568. if (inf == null) return;
  569. var isCheck = $elm.attr('type') == 'checkbox',
  570. val = isCheck ? $elm.prop('checked') : $elm.val();
  571. var newline;
  572. switch(inf.type) {
  573. case 'switch':
  574. var slash = val ? '' : '//';
  575. newline = inf.line.replace(inf.repl, '$1'+slash+'$3');
  576. break;
  577. case 'quoted':
  578. case 'plain':
  579. if (isCheck)
  580. this.setMessage(name + ' should not be a checkbox!', 'error');
  581. else
  582. newline = inf.line.replace(inf.repl, '$1'+val.replace('$','\\$')+'$3');
  583. break;
  584. }
  585. this.setDefineLine(name, newline);
  586. },
  587. /**
  588. * Set the define's line in the text to a new line,
  589. * then update, highlight, and scroll to the line
  590. */
  591. setDefineLine: function(name, newline) {
  592. this.log('setDefineLine:'+name+'\n'+newline,4);
  593. var inf = $('#'+name)[0].defineInfo;
  594. var $c = $(inf.field), txt = $c.text();
  595. var hilite_token = '[HIGHLIGHTER-TOKEN]';
  596. txt = txt.replace(inf.line, hilite_token + newline);
  597. inf.line = newline;
  598. // Convert txt into HTML before storing
  599. var html = txt.toHTML().replace(hilite_token, '<span></span>');
  600. // Set the final text including the highlighter
  601. $c.html(html);
  602. // Scroll to reveal the define
  603. if ($c.is(':visible')) this.scrollToDefine(name);
  604. },
  605. /**
  606. * Scroll a pre box to reveal a #define
  607. */
  608. scrollToDefine: function(name, always) {
  609. this.log('scrollToDefine:'+name,4);
  610. var inf = $('#'+name)[0].defineInfo, $c = $(inf.field);
  611. // Scroll to the altered text if it isn't visible
  612. var halfHeight = $c.height()/2, scrollHeight = $c.prop('scrollHeight'),
  613. lineHeight = scrollHeight/(inf.adv ? total_config_adv_lines : total_config_lines),
  614. textScrollY = (inf.lineNum * lineHeight - halfHeight).limit(0, scrollHeight - 1);
  615. if (always || Math.abs($c.prop('scrollTop') - textScrollY) > halfHeight) {
  616. $c.find('span').height(lineHeight);
  617. $c.animate({ scrollTop: textScrollY });
  618. }
  619. },
  620. /**
  621. * Set a form field to the current #define value in the config text
  622. */
  623. setFieldFromDefine: function(name) {
  624. var $elm = $('#'+name), val = this.defineValue(name);
  625. this.log('setFieldFromDefine:' + name + ' to ' + val, 2);
  626. // Set the field value
  627. $elm.attr('type') == 'checkbox' ? $elm.prop('checked', val) : $elm.val(''+val);
  628. // If the item has a checkbox then set enabled state too
  629. var $cb = $('#'+name+'-switch');
  630. if ($cb.length) {
  631. var on = self.defineIsEnabled(name);
  632. $elm.attr('disabled', !on); // enable/disable the form field (could also dim it)
  633. $cb.prop('checked', on); // check/uncheck the checkbox
  634. }
  635. },
  636. /**
  637. * Purge #define information for one of the config files
  638. */
  639. purgeDefineInfo: function(adv) {
  640. if (adv === undefined) adv = false;
  641. $('[name]').each(function() {
  642. var inf = this.defineInfo;
  643. if (inf && adv === inf.adv) $(this).removeProp('defineInfo');
  644. });
  645. },
  646. /**
  647. * Update #define information for one of the config files
  648. */
  649. refreshDefineInfo: function(adv) {
  650. if (adv === undefined) adv = false;
  651. $('[name]').each(function() {
  652. var inf = this.defineInfo;
  653. if (inf && adv == inf.adv) this.defineInfo = self.getDefineInfo(this.id, adv);
  654. });
  655. },
  656. /**
  657. * Get information about a #define from configuration file text:
  658. *
  659. * - Pre-examine the #define for its prefix, value position, suffix, etc.
  660. * - Construct RegExp's for the #define to quickly find (and replace) values.
  661. * - Store the existing #define line as a fast key to finding it later.
  662. * - Determine the line number of the #define so it can be scrolled to.
  663. * - Gather nearby comments to be used as tooltips.
  664. */
  665. getDefineInfo: function(name, adv) {
  666. if (adv === undefined) adv = false;
  667. this.log('getDefineInfo:'+name,4);
  668. var $c = adv ? $config_adv : $config,
  669. txt = $c.text();
  670. // a switch line with no value
  671. var findDef = new RegExp('^([ \\t]*//)?([ \\t]*#define[ \\t]+' + name + ')([ \\t]*/[*/].*)?$', 'm'),
  672. result = findDef.exec(txt),
  673. info = { type:0, adv:adv, field:$c[0], val_i: 2 };
  674. if (result !== null) {
  675. $.extend(info, {
  676. val_i: 1,
  677. type: 'switch',
  678. line: result[0], // whole line
  679. pre: result[1] === undefined ? '' : result[1].replace('//',''),
  680. define: result[2],
  681. post: result[3] === undefined ? '' : result[3]
  682. });
  683. info.regex = new RegExp('([ \\t]*//)?([ \\t]*' + info.define.regEsc() + info.post.regEsc() + ')', 'm');
  684. info.repl = new RegExp('([ \\t]*)(\/\/)?([ \\t]*' + info.define.regEsc() + info.post.regEsc() + ')', 'm');
  685. }
  686. else {
  687. // a define with quotes
  688. findDef = new RegExp('^(.*//)?(.*#define[ \\t]+' + name + '[ \\t]+)("[^"]*")([ \\t]*/[*/].*)?$', 'm');
  689. result = findDef.exec(txt);
  690. if (result !== null) {
  691. $.extend(info, {
  692. type: 'quoted',
  693. line: result[0],
  694. pre: result[1] === undefined ? '' : result[1].replace('//',''),
  695. define: result[2],
  696. post: result[4] === undefined ? '' : result[4]
  697. });
  698. info.regex = new RegExp('([ \\t]*//)?[ \\t]*' + info.define.regEsc() + '"([^"]*)"' + info.post.regEsc(), 'm');
  699. info.repl = new RegExp('(([ \\t]*//)?[ \\t]*' + info.define.regEsc() + '")[^"]*("' + info.post.regEsc() + ')', 'm');
  700. }
  701. else {
  702. // a define with no quotes
  703. findDef = new RegExp('^([ \\t]*//)?([ \\t]*#define[ \\t]+' + name + '[ \\t]+)(\\S*)([ \\t]*/[*/].*)?$', 'm');
  704. result = findDef.exec(txt);
  705. if (result !== null) {
  706. $.extend(info, {
  707. type: 'plain',
  708. line: result[0],
  709. pre: result[1] === undefined ? '' : result[1].replace('//',''),
  710. define: result[2],
  711. post: result[4] === undefined ? '' : result[4]
  712. });
  713. info.regex = new RegExp('([ \\t]*//)?[ \\t]*' + info.define.regEsc() + '(\\S*)' + info.post.regEsc(), 'm');
  714. info.repl = new RegExp('(([ \\t]*//)?[ \\t]*' + info.define.regEsc() + ')\\S*(' + info.post.regEsc() + ')', 'm');
  715. }
  716. }
  717. }
  718. // Success?
  719. if (info.type) {
  720. // Get the end-of-line comment, if there is one
  721. var tooltip = '';
  722. findDef = new RegExp('.*#define[ \\t].*/[/*]+[ \\t]*(.*)');
  723. if (info.line.search(findDef) >= 0)
  724. tooltip = info.line.replace(findDef, '$1');
  725. // Get all the comments immediately before the item
  726. var r, s;
  727. findDef = new RegExp('(([ \\t]*(//|#)[^\n]+\n){1,4})([ \\t]*\n){0,1}' + info.line.regEsc(), 'g');
  728. if (r = findDef.exec(txt)) {
  729. findDef = new RegExp('^[ \\t]*//+[ \\t]*(.*)[ \\t]*$', 'gm');
  730. while((s = findDef.exec(r[1])) !== null) {
  731. if (s[1].match(/^#define[ \\t]/) != null) {
  732. tooltip = '';
  733. break;
  734. }
  735. tooltip += ' ' + s[1] + '\n';
  736. }
  737. }
  738. findDef = new RegExp('^[ \\t]*'+name); // To strip the name from the start
  739. $.extend(info, {
  740. tooltip: '<strong>'+name+'</strong> '+tooltip.replace(findDef,'').trim().toHTML(),
  741. lineNum: this.getLineNumberOfText(info.line, txt)
  742. });
  743. }
  744. else
  745. info = null;
  746. this.log(info,2);
  747. return info;
  748. },
  749. /**
  750. * Count the number of lines before a match, return -1 on fail
  751. */
  752. getLineNumberOfText: function(line, txt) {
  753. var pos = txt.indexOf(line);
  754. return (pos < 0) ? pos : txt.substr(0, pos).lineCount();
  755. },
  756. /**
  757. * Add a temporary message to the page
  758. */
  759. setMessage: function(msg,type) {
  760. if (msg) {
  761. if (type === undefined) type = 'message';
  762. var $err = $('<p class="'+type+'">'+msg+'<span>x</span></p>').appendTo($msgbox), err = $err[0];
  763. var baseColor = $err.css('color').replace(/rgba?\(([^),]+,[^),]+,[^),]+).*/, 'rgba($1,');
  764. err.pulse_offset = (pulse_offset += 200);
  765. err.startTime = Date.now() + pulse_offset;
  766. err.pulser = setInterval(function(){
  767. var pulse_time = Date.now() + err.pulse_offset;
  768. var opac = 0.5+Math.sin(pulse_time/200)*0.4;
  769. $err.css({color:baseColor+(opac)+')'});
  770. if (pulse_time - err.startTime > 2500 && opac > 0.899) {
  771. clearInterval(err.pulser);
  772. }
  773. }, 50);
  774. $err.click(function(e) { $(this).remove(); return false; }).css({cursor:'pointer'});
  775. }
  776. else {
  777. $msgbox.find('p.error, p.warning').each(function() {
  778. if (this.pulser !== undefined && this.pulser)
  779. clearInterval(this.pulser);
  780. $(this).remove();
  781. });
  782. }
  783. },
  784. setRequestError: function(stat, path) {
  785. self.setMessage('Error '+stat+' – ' + path.replace(/^(https:\/\/[^\/]+\/)?.+(\/[^\/]+)$/, '$1...$2'), 'error');
  786. },
  787. log: function(o,l) {
  788. if (l === undefined) l = 0;
  789. if (this.logging>=l*1) console.log(o);
  790. },
  791. logOnce: function(o) {
  792. if (o.didLogThisObject === undefined) {
  793. this.log(o);
  794. o.didLogThisObject = true;
  795. }
  796. },
  797. EOF: null
  798. };
  799. })();
  800. // Typically the app would be in its own file, but this would be here
  801. configuratorApp.init();
  802. });