My Marlin configs for Fabrikator Mini and CTC i3 Pro B
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

configurator.js 25KB

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