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

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