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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  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 >= config_files.length) {
  213. // If not all files loaded set an error
  214. if (success_count < ajax_count)
  215. self.setMessage('Unable to load configurations. Try the upload field.', 'error');
  216. // Is the request near the rate limit? Set an error.
  217. var r;
  218. if (r = rateLimit) {
  219. if (r.quota < 20) {
  220. self.setMessage(
  221. 'Approaching request limit (' +
  222. r.quota + ' remaining.' +
  223. ' Reset in ' + Math.floor(r.timeLeft/60) + ':' + (r.timeLeft%60+'').zeroPad(2) + ')',
  224. 'warning'
  225. );
  226. }
  227. }
  228. // Post-process all the loaded files
  229. $.each(config_files, function(){ if (loaded_items[this]) loaded_items[this](); });
  230. }
  231. }
  232. });
  233. });
  234. },
  235. /**
  236. * Make a download link visible and active
  237. */
  238. activateDownloadLink: function(adv) {
  239. var $c = adv ? $config_adv : $config, txt = $c.text();
  240. var filename = (adv ? config_adv_file : config_file);
  241. $c.prevAll('.download:first')
  242. .unbind('mouseover click')
  243. .mouseover(function() {
  244. var d = new Date(), fn = d.fileStamp(filename);
  245. $(this).attr({ download:fn, href:'download:'+fn, title:'download:'+fn });
  246. })
  247. .click(function(){
  248. var $button = $(this);
  249. $(this).attr({ href:'data:text/plain;charset=utf-8,' + encodeURIComponent($c.text()) });
  250. setTimeout(function(){
  251. $button.attr({ href:$button.attr('title') });
  252. }, 100);
  253. return true;
  254. })
  255. .css({visibility:'visible'});
  256. },
  257. /**
  258. * Init the boards array from a boards.h file
  259. */
  260. initBoardsFromText: function(txt) {
  261. boards_list = {};
  262. var r, findDef = new RegExp('[ \\t]*#define[ \\t]+(BOARD_[\\w_]+)[ \\t]+(\\d+)[ \\t]*(//[ \\t]*)?(.+)?', 'gm');
  263. while((r = findDef.exec(txt)) !== null) {
  264. boards_list[r[1]] = r[2].prePad(3, '  ') + " — " + r[4].replace(/\).*/, ')');
  265. }
  266. this.log("Loaded boards:\n" + Object.keys(boards_list).join('\n'), 3);
  267. has_boards = true;
  268. },
  269. /**
  270. * Init the thermistors array from the Configuration.h file
  271. */
  272. initThermistorsFromText: function(txt) {
  273. // Get all the thermistors and save them into an object
  274. var r, s, findDef = new RegExp('(//.*\n)+\\s+(#define[ \\t]+TEMP_SENSOR_0)', 'g');
  275. r = findDef.exec(txt);
  276. findDef = new RegExp('^//[ \\t]*([-\\d]+)[ \\t]+is[ \\t]+(.*)[ \\t]*$', 'gm');
  277. while((s = findDef.exec(r[0])) !== null) {
  278. therms_list[s[1]] = s[1].prePad(4, '  ') + " — " + s[2];
  279. }
  280. },
  281. /**
  282. * Get all the unique define names
  283. */
  284. getDefinesFromText: function(txt) {
  285. var leave_out_defines = ['CONFIGURATION_H', 'CONFIGURATION_ADV_H', 'STRING_VERSION', 'STRING_URL', 'STRING_VERSION_CONFIG_H', 'STRING_CONFIG_H_AUTHOR', 'STRING_SPLASH_LINE1', 'STRING_SPLASH_LINE2'];
  286. // Get all the unique #define's and save them in an array
  287. var r, define_obj = {}, findDef = new RegExp('#define[ \\t]+(\\w+)', 'gm');
  288. while((r = findDef.exec(txt)) !== null) {
  289. if ($.inArray(r[1], leave_out_defines) < 0 && !(r[1] in define_obj))
  290. define_obj[r[1]] = null;
  291. }
  292. this.log(Object.keys(define_obj), 2);
  293. return Object.keys(define_obj);
  294. },
  295. /**
  296. * Create fields for any defines that have none
  297. */
  298. createFieldsForDefines: function(adv) {
  299. var e = adv ? 1 : 0, n = 0;
  300. var fail_list = [];
  301. $.each(define_list[e], function(i,name) {
  302. if (!$('#'+name).length) {
  303. var $ff = $('#more'),
  304. inf = self.getDefineInfo(name, adv);
  305. if (inf) {
  306. var $newlabel = $('<label>',{for:name}).text(name.toLabel());
  307. // if (!(++n % 3))
  308. $newlabel.addClass('newline');
  309. var $newfield;
  310. if (inf.options !== undefined) {
  311. $newfield = $('<select>'); //.addOptions(inf.options);
  312. }
  313. else {
  314. $newfield = inf.type == 'switch' ? $('<input>',{type:'checkbox'}) : $('<input>',{type:'text',size:10,maxlength:40});
  315. }
  316. $newfield.attr({id:name,name:name}).prop({defineInfo:inf});
  317. // Add the new field to the form
  318. $ff.append($newlabel, $newfield);
  319. }
  320. else
  321. fail_list.push(name);
  322. }
  323. });
  324. if (fail_list) this.log('Unable to parse:\n' + fail_list.join('\n'), 2);
  325. },
  326. /**
  327. * Handle a file being dropped on the file field
  328. */
  329. handleFileLoad: function(txt, $uploader) {
  330. txt += '';
  331. var filename = $uploader.val().replace(/.*[\/\\](.*)$/, '$1');
  332. switch(filename) {
  333. case boards_file:
  334. case config_file:
  335. case config_adv_file:
  336. this.fileLoaded(filename, txt);
  337. break;
  338. default:
  339. this.setMessage("Can't parse '"+filename+"'!");
  340. break;
  341. }
  342. },
  343. /**
  344. * Process a file after it's been successfully loaded
  345. */
  346. fileLoaded: function(filename, txt) {
  347. this.log("fileLoaded:"+filename,4);
  348. var err, init_index;
  349. switch(filename) {
  350. case boards_file:
  351. this.initBoardsFromText(txt);
  352. $('#MOTHERBOARD').html('').addOptions(boards_list);
  353. if (has_config) this.initField('MOTHERBOARD');
  354. break;
  355. case config_file:
  356. if (has_boards) {
  357. $config.text(txt);
  358. total_config_lines = txt.lineCount();
  359. // this.initThermistorsFromText(txt);
  360. init_index = 0;
  361. has_config = true;
  362. }
  363. else {
  364. err = boards_file;
  365. }
  366. break;
  367. case config_adv_file:
  368. if (has_config) {
  369. $config_adv.text(txt);
  370. total_config_adv_lines = txt.lineCount();
  371. init_index = 1;
  372. has_config_adv = true;
  373. }
  374. else {
  375. err = config_file;
  376. }
  377. break;
  378. }
  379. // When a config file loads defines might change
  380. if (init_index != null) {
  381. var adv = init_index == 1;
  382. define_list[init_index] = this.getDefinesFromText(txt);
  383. this.log(define_list[init_index], 2);
  384. this.purgeDefineInfo(adv);
  385. this.createFieldsForDefines(init_index);
  386. this.refreshConfigForm(init_index);
  387. this.activateDownloadLink(adv);
  388. }
  389. this.setMessage(err
  390. ? 'Please upload a "' + boards_file + '" file first!'
  391. : '"' + filename + '" loaded successfully.', err ? 'error' : 'message'
  392. );
  393. },
  394. /**
  395. * Add initial enhancements to the existing form
  396. */
  397. initConfigForm: function() {
  398. // Modify form fields and make the form responsive.
  399. // As values change on the form, we could update the
  400. // contents of text areas containing the configs, for
  401. // example.
  402. // while(!$config_adv.text() == null) {}
  403. // while(!$config.text() == null) {}
  404. // Go through all form items with names
  405. $form.find('[name]').each(function() {
  406. // Set its id to its name
  407. var name = $(this).attr('name');
  408. $(this).attr({id: name});
  409. // Attach its label sibling
  410. var $label = $(this).prev('label');
  411. if ($label.length) $label.attr('for',name);
  412. });
  413. // Get all 'switchable' class items and add a checkbox
  414. $form.find('.switchable').each(function(){
  415. $(this).after(
  416. $('<input>',{type:'checkbox',value:'1',class:'enabler'}).prop('checked',true)
  417. .attr('id',this.id + '-switch')
  418. .change(self.handleSwitch)
  419. );
  420. });
  421. // Add options to the popup menus
  422. // $('#SERIAL_PORT').addOptions([0,1,2,3,4,5,6,7]);
  423. // $('#BAUDRATE').addOptions([2400,9600,19200,38400,57600,115200,250000]);
  424. // $('#EXTRUDERS').addOptions([1,2,3,4]);
  425. // $('#POWER_SUPPLY').addOptions({'1':'ATX','2':'Xbox 360'});
  426. // Replace the Serial popup menu with a stepper control
  427. /*
  428. $('#serial_stepper').jstepper({
  429. min: 0,
  430. max: 3,
  431. val: $('#SERIAL_PORT').val(),
  432. arrowWidth: '18px',
  433. arrowHeight: '15px',
  434. color: '#FFF',
  435. acolor: '#F70',
  436. hcolor: '#FF0',
  437. id: 'select-me',
  438. textStyle: {width:'1.5em',fontSize:'120%',textAlign:'center'},
  439. onChange: function(v) { $('#SERIAL_PORT').val(v).trigger('change'); }
  440. });
  441. */
  442. },
  443. /**
  444. * Make tabs to switch between fieldsets
  445. */
  446. makeTabsForFieldsets: function() {
  447. // Make tabs for the fieldsets
  448. var $fset = $form.find('fieldset'),
  449. $tabs = $('<ul>',{class:'tabs'}),
  450. ind = 1;
  451. $fset.each(function(){
  452. var tabID = 'TAB'+ind;
  453. $(this).addClass(tabID);
  454. var $leg = $(this).find('legend');
  455. var $link = $('<a>',{href:'#'+ind,id:tabID}).text($leg.text());
  456. $tabs.append($('<li>').append($link));
  457. $link.click(function(e){
  458. e.preventDefault;
  459. var ind = this.id;
  460. $tabs.find('.active').removeClass('active');
  461. $(this).addClass('active');
  462. $fset.hide();
  463. $fset.filter('.'+this.id).show();
  464. return false;
  465. });
  466. ind++;
  467. });
  468. $('#tabs').html('').append($tabs);
  469. $('<br>',{class:'clear'}).appendTo('#tabs');
  470. $tabs.find('a:first').trigger('click');
  471. },
  472. /**
  473. * Update all fields on the form after loading a configuration
  474. */
  475. refreshConfigForm: function(init_index) {
  476. /**
  477. * Any manually-created form elements will remain
  478. * where they are. Unknown defines (currently most)
  479. * are added to the "More..." tab for now.
  480. *
  481. * Specific exceptions can be managed by applying
  482. * classes to the associated form fields.
  483. * Sorting and arrangement can come from an included
  484. * Javascript file that describes the configuration
  485. * in JSON, or using information added to the config
  486. * files.
  487. *
  488. */
  489. // Refresh the motherboard menu with new options
  490. $('#MOTHERBOARD').html('').addOptions(boards_list);
  491. // Init all existing fields, getting define info for any that need it
  492. // refreshing the options and updating their current values
  493. $.each(define_list[init_index], function() {
  494. if ($('#'+this).length)
  495. self.initField(this,init_index==1);
  496. else
  497. self.log(this + " is not on the page yet.", 2);
  498. });
  499. },
  500. /**
  501. * Get the defineInfo for a field on the form
  502. * Make it responsive, add a tooltip
  503. */
  504. initField: function(name, adv) {
  505. this.log("initField:"+name,4);
  506. var $elm = $('#'+name), elm = $elm[0], inf = elm.defineInfo;
  507. if (inf == null)
  508. inf = elm.defineInfo = this.getDefineInfo(name, adv);
  509. // Set options on the field if there are any
  510. if (inf.options !== undefined)
  511. $elm.html('').addOptions(inf.options);
  512. // Create a tooltip if there is one
  513. if (inf.tooltip) {
  514. var $tipme = $elm.prev('label');
  515. if ($tipme.length) {
  516. $tipme.unbind('mouseenter mouseleave');
  517. $tipme.hover(
  518. function() {
  519. if ($('#tipson input').prop('checked')) {
  520. var pos = $tipme.position();
  521. $tooltip.html(inf.tooltip)
  522. .append('<span>')
  523. .css({bottom:($tooltip.parent().outerHeight()-pos.top)+'px',left:(pos.left+70)+'px'})
  524. .show();
  525. if (hover_timer) {
  526. clearTimeout(hover_timer);
  527. hover_timer = null;
  528. }
  529. }
  530. },
  531. function() {
  532. hover_timer = setTimeout(function(){
  533. hover_timer = null;
  534. $tooltip.fadeOut(400);
  535. }, 400);
  536. }
  537. );
  538. }
  539. }
  540. $elm.unbind('input change');
  541. $elm.on($elm.attr('type') == 'text' ? 'input' : 'change', this.handleChange);
  542. // Set the field's initial value from the define
  543. this.setFieldFromDefine(name);
  544. },
  545. /**
  546. * Handle any value field being changed
  547. */
  548. handleChange: function() { self.updateDefineFromField(this.id); },
  549. /**
  550. * Handle a switch checkbox being changed
  551. */
  552. handleSwitch: function() {
  553. var $elm = $(this), $prev = $elm.prev();
  554. var on = $elm.prop('checked') || false;
  555. $prev.attr('disabled', !on);
  556. self.setDefineEnabled($prev[0].id, on);
  557. },
  558. /**
  559. * Get the current value of a #define (from the config text)
  560. */
  561. defineValue: function(name) {
  562. this.log('defineValue:'+name,4);
  563. var inf = $('#'+name)[0].defineInfo;
  564. if (inf == null) return 'n/a';
  565. var result = inf.regex.exec($(inf.field).text());
  566. this.log(result,2);
  567. return inf.type == 'switch' ? result[inf.val_i] != '//' : result[inf.val_i];
  568. },
  569. /**
  570. * Get the current enabled state of a #define (from the config text)
  571. */
  572. defineIsEnabled: function(name) {
  573. this.log('defineIsEnabled:'+name,4);
  574. var inf = $('#'+name)[0].defineInfo;
  575. if (inf == null) return false;
  576. var result = inf.regex.exec($(inf.field).text());
  577. this.log(result,2);
  578. var on = result !== null ? result[1].trim() != '//' : true;
  579. this.log(name + ' = ' + on, 2);
  580. return on;
  581. },
  582. /**
  583. * Set a #define enabled or disabled by altering the config text
  584. */
  585. setDefineEnabled: function(name, val) {
  586. this.log('setDefineEnabled:'+name,4);
  587. var inf = $('#'+name)[0].defineInfo;
  588. if (inf) {
  589. var slash = val ? '' : '//';
  590. var newline = inf.line
  591. .replace(/^([ \t]*)(\/\/)([ \t]*)/, '$1$3') // remove slashes
  592. .replace(inf.pre+inf.define, inf.pre+slash+inf.define); // add them back
  593. this.setDefineLine(name, newline);
  594. }
  595. },
  596. /**
  597. * Update a #define (from the form) by altering the config text
  598. */
  599. updateDefineFromField: function(name) {
  600. this.log('updateDefineFromField:'+name,4);
  601. var $elm = $('#'+name), inf = $elm[0].defineInfo;
  602. if (inf == null) return;
  603. var isCheck = $elm.attr('type') == 'checkbox',
  604. val = isCheck ? $elm.prop('checked') : $elm.val();
  605. var newline;
  606. switch(inf.type) {
  607. case 'switch':
  608. var slash = val ? '' : '//';
  609. newline = inf.line.replace(inf.repl, '$1'+slash+'$3');
  610. break;
  611. case 'quoted':
  612. case 'plain':
  613. if (isCheck)
  614. this.setMessage(name + ' should not be a checkbox!', 'error');
  615. else
  616. newline = inf.line.replace(inf.repl, '$1'+val.replace('$','\\$')+'$3');
  617. break;
  618. }
  619. this.setDefineLine(name, newline);
  620. },
  621. /**
  622. * Set the define's line in the text to a new line,
  623. * then update, highlight, and scroll to the line
  624. */
  625. setDefineLine: function(name, newline) {
  626. this.log('setDefineLine:'+name+'\n'+newline,4);
  627. var inf = $('#'+name)[0].defineInfo;
  628. var $c = $(inf.field), txt = $c.text();
  629. var hilite_token = '[HIGHLIGHTER-TOKEN]';
  630. txt = txt.replace(inf.line, hilite_token + newline);
  631. inf.line = newline;
  632. // Convert txt into HTML before storing
  633. var html = txt.toHTML().replace(hilite_token, '<span></span>');
  634. // Set the final text including the highlighter
  635. $c.html(html);
  636. // Scroll to reveal the define
  637. if ($c.is(':visible')) this.scrollToDefine(name);
  638. },
  639. /**
  640. * Scroll a pre box to reveal a #define
  641. */
  642. scrollToDefine: function(name, always) {
  643. this.log('scrollToDefine:'+name,4);
  644. var inf = $('#'+name)[0].defineInfo, $c = $(inf.field);
  645. // Scroll to the altered text if it isn't visible
  646. var halfHeight = $c.height()/2, scrollHeight = $c.prop('scrollHeight'),
  647. lineHeight = scrollHeight/(inf.adv ? total_config_adv_lines : total_config_lines),
  648. textScrollY = (inf.lineNum * lineHeight - halfHeight).limit(0, scrollHeight - 1);
  649. if (always || Math.abs($c.prop('scrollTop') - textScrollY) > halfHeight) {
  650. $c.find('span').height(lineHeight);
  651. $c.animate({ scrollTop: textScrollY });
  652. }
  653. },
  654. /**
  655. * Set a form field to the current #define value in the config text
  656. */
  657. setFieldFromDefine: function(name) {
  658. var $elm = $('#'+name), val = this.defineValue(name);
  659. this.log('setFieldFromDefine:' + name + ' to ' + val, 2);
  660. // Set the field value
  661. $elm.attr('type') == 'checkbox' ? $elm.prop('checked', val) : $elm.val(''+val);
  662. // If the item has a checkbox then set enabled state too
  663. var $cb = $('#'+name+'-switch');
  664. if ($cb.length) {
  665. var on = self.defineIsEnabled(name);
  666. $elm.attr('disabled', !on); // enable/disable the form field (could also dim it)
  667. $cb.prop('checked', on); // check/uncheck the checkbox
  668. }
  669. },
  670. /**
  671. * Purge #define information for one of the config files
  672. */
  673. purgeDefineInfo: function(adv) {
  674. if (adv === undefined) adv = false;
  675. $('[name]').each(function() {
  676. var inf = this.defineInfo;
  677. if (inf && adv === inf.adv) $(this).removeProp('defineInfo');
  678. });
  679. },
  680. /**
  681. * Update #define information for one of the config files
  682. */
  683. refreshDefineInfo: function(adv) {
  684. if (adv === undefined) adv = false;
  685. $('[name]').each(function() {
  686. var inf = this.defineInfo;
  687. if (inf && adv == inf.adv) this.defineInfo = self.getDefineInfo(this.id, adv);
  688. });
  689. },
  690. /**
  691. * Get information about a #define from configuration file text:
  692. *
  693. * - Pre-examine the #define for its prefix, value position, suffix, etc.
  694. * - Construct RegExp's for the #define to quickly find (and replace) values.
  695. * - Store the existing #define line as a fast key to finding it later.
  696. * - Determine the line number of the #define so it can be scrolled to.
  697. * - Gather nearby comments to be used as tooltips.
  698. * - Look for JSON in nearby comments to use as select options.
  699. */
  700. getDefineInfo: function(name, adv) {
  701. if (adv === undefined) adv = false;
  702. this.log('getDefineInfo:'+name,4);
  703. var $c = adv ? $config_adv : $config,
  704. txt = $c.text();
  705. // a switch line with no value
  706. var findDef = new RegExp('^([ \\t]*//)?([ \\t]*#define[ \\t]+' + name + ')([ \\t]*/[*/].*)?$', 'm'),
  707. result = findDef.exec(txt),
  708. info = { type:0, adv:adv, field:$c[0], val_i: 2 };
  709. if (result !== null) {
  710. $.extend(info, {
  711. val_i: 1,
  712. type: 'switch',
  713. line: result[0], // whole line
  714. pre: result[1] === undefined ? '' : result[1].replace('//',''),
  715. define: result[2],
  716. post: result[3] === undefined ? '' : result[3]
  717. });
  718. info.regex = new RegExp('([ \\t]*//)?([ \\t]*' + info.define.regEsc() + info.post.regEsc() + ')', 'm');
  719. info.repl = new RegExp('([ \\t]*)(\/\/)?([ \\t]*' + info.define.regEsc() + info.post.regEsc() + ')', 'm');
  720. }
  721. else {
  722. // a define with curly braces
  723. findDef = new RegExp('^(.*//)?(.*#define[ \\t]+' + name + '[ \\t]+)(\{[^\}]*\})([ \\t]*/[*/].*)?$', 'm');
  724. result = findDef.exec(txt);
  725. if (result !== null) {
  726. $.extend(info, {
  727. type: 'list',
  728. line: result[0],
  729. pre: result[1] === undefined ? '' : result[1].replace('//',''),
  730. define: result[2],
  731. post: result[4] === undefined ? '' : result[4]
  732. });
  733. info.regex = new RegExp('([ \\t]*//)?[ \\t]*' + info.define.regEsc() + '\{([^\}]*)\}' + info.post.regEsc(), 'm');
  734. info.repl = new RegExp('(([ \\t]*//)?[ \\t]*' + info.define.regEsc() + '\{)[^\}]*(\}' + info.post.regEsc() + ')', 'm');
  735. }
  736. else {
  737. // a define with quotes
  738. findDef = new RegExp('^(.*//)?(.*#define[ \\t]+' + name + '[ \\t]+)("[^"]*")([ \\t]*/[*/].*)?$', 'm');
  739. result = findDef.exec(txt);
  740. if (result !== null) {
  741. $.extend(info, {
  742. type: 'quoted',
  743. line: result[0],
  744. pre: result[1] === undefined ? '' : result[1].replace('//',''),
  745. define: result[2],
  746. post: result[4] === undefined ? '' : result[4]
  747. });
  748. info.regex = new RegExp('([ \\t]*//)?[ \\t]*' + info.define.regEsc() + '"([^"]*)"' + info.post.regEsc(), 'm');
  749. info.repl = new RegExp('(([ \\t]*//)?[ \\t]*' + info.define.regEsc() + '")[^"]*("' + info.post.regEsc() + ')', 'm');
  750. }
  751. else {
  752. // a define with no quotes
  753. findDef = new RegExp('^([ \\t]*//)?([ \\t]*#define[ \\t]+' + name + '[ \\t]+)(\\S*)([ \\t]*/[*/].*)?$', 'm');
  754. result = findDef.exec(txt);
  755. if (result !== null) {
  756. $.extend(info, {
  757. type: 'plain',
  758. line: result[0],
  759. pre: result[1] === undefined ? '' : result[1].replace('//',''),
  760. define: result[2],
  761. post: result[4] === undefined ? '' : result[4]
  762. });
  763. info.regex = new RegExp('([ \\t]*//)?[ \\t]*' + info.define.regEsc() + '(\\S*)' + info.post.regEsc(), 'm');
  764. info.repl = new RegExp('(([ \\t]*//)?[ \\t]*' + info.define.regEsc() + ')\\S*(' + info.post.regEsc() + ')', 'm');
  765. }
  766. }
  767. }
  768. }
  769. // Success?
  770. if (info.type) {
  771. // Get the end-of-line comment, if there is one
  772. var tooltip = '';
  773. findDef = new RegExp('.*#define[ \\t].*/[/*]+[ \\t]*(.*)');
  774. if (info.line.search(findDef) >= 0)
  775. tooltip = info.line.replace(findDef, '$1');
  776. // Get all the comments immediately before the item
  777. var r, s;
  778. findDef = new RegExp('(([ \\t]*(//|#)[^\n]+\n){1,4})([ \\t]*\n){0,1}' + info.line.regEsc(), 'g');
  779. if (r = findDef.exec(txt)) {
  780. findDef = new RegExp('^[ \\t]*//+[ \\t]*(.*)[ \\t]*$', 'gm');
  781. while((s = findDef.exec(r[1])) !== null) {
  782. if (s[1].match(/^#define[ \\t]/) != null) {
  783. tooltip = '';
  784. break;
  785. }
  786. // JSON data? Save as select options
  787. if (s[1].match(/:[\[{]/) != null) {
  788. // TODO
  789. // :[1-6] = value limits
  790. eval('info.options = ' + s[1].substr(1));
  791. }
  792. else {
  793. // Other lines added to the tooltip
  794. tooltip += ' ' + s[1] + '\n';
  795. }
  796. }
  797. }
  798. findDef = new RegExp('^'+name); // To strip the name from the start
  799. $.extend(info, {
  800. tooltip: '<strong>'+name+'</strong> '+tooltip.trim().replace(findDef,'').toHTML(),
  801. lineNum: this.getLineNumberOfText(info.line, txt)
  802. });
  803. }
  804. else
  805. info = null;
  806. this.log(info,2);
  807. return info;
  808. },
  809. /**
  810. * Count the number of lines before a match, return -1 on fail
  811. */
  812. getLineNumberOfText: function(line, txt) {
  813. var pos = txt.indexOf(line);
  814. return (pos < 0) ? pos : txt.substr(0, pos).lineCount();
  815. },
  816. /**
  817. * Add a temporary message to the page
  818. */
  819. setMessage: function(msg,type) {
  820. if (msg) {
  821. if (type === undefined) type = 'message';
  822. var $err = $('<p class="'+type+'">'+msg+'<span>x</span></p>').appendTo($msgbox), err = $err[0];
  823. var baseColor = $err.css('color').replace(/rgba?\(([^),]+,[^),]+,[^),]+).*/, 'rgba($1,');
  824. err.pulse_offset = (pulse_offset += 200);
  825. err.startTime = Date.now() + pulse_offset;
  826. err.pulser = setInterval(function(){
  827. var pulse_time = Date.now() + err.pulse_offset;
  828. var opac = 0.5+Math.sin(pulse_time/200)*0.4;
  829. $err.css({color:baseColor+(opac)+')'});
  830. if (pulse_time - err.startTime > 2500 && opac > 0.899) {
  831. clearInterval(err.pulser);
  832. }
  833. }, 50);
  834. $err.click(function(e) { $(this).remove(); return false; }).css({cursor:'pointer'});
  835. }
  836. else {
  837. $msgbox.find('p.error, p.warning').each(function() {
  838. if (this.pulser !== undefined && this.pulser)
  839. clearInterval(this.pulser);
  840. $(this).remove();
  841. });
  842. }
  843. },
  844. setRequestError: function(stat, path) {
  845. self.setMessage('Error '+stat+' – ' + path.replace(/^(https:\/\/[^\/]+\/)?.+(\/[^\/]+)$/, '$1...$2'), 'error');
  846. },
  847. log: function(o,l) {
  848. if (l === undefined) l = 0;
  849. if (this.logging>=l*1) console.log(o);
  850. },
  851. logOnce: function(o) {
  852. if (o.didLogThisObject === undefined) {
  853. this.log(o);
  854. o.didLogThisObject = true;
  855. }
  856. },
  857. EOF: null
  858. };
  859. })();
  860. // Typically the app would be in its own file, but this would be here
  861. configuratorApp.init();
  862. });