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

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