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

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