Commit ce63f70b authored by ellen.spertus's avatar ellen.spertus

Automatic commit Mon Jan 13 03:00:02 PST 2014

parent 0b5cc3cf
...@@ -435,13 +435,18 @@ Blockly.Blocks['field_image'] = { ...@@ -435,13 +435,18 @@ Blockly.Blocks['field_image'] = {
.appendField(new Blockly.FieldTextInput(src), 'SRC'); .appendField(new Blockly.FieldTextInput(src), 'SRC');
this.appendDummyInput() this.appendDummyInput()
.appendField('width') .appendField('width')
.appendField(new Blockly.FieldTextInput('15'), 'WIDTH') .appendField(new Blockly.FieldTextInput('15',
Blockly.FieldTextInput.numberValidator), 'WIDTH')
.appendField('height') .appendField('height')
.appendField(new Blockly.FieldTextInput('15'), 'HEIGHT'); .appendField(new Blockly.FieldTextInput('15',
Blockly.FieldTextInput.numberValidator), 'HEIGHT')
.appendField('alt text')
.appendField(new Blockly.FieldTextInput('*'), 'ALT');
this.setPreviousStatement(true, 'Field'); this.setPreviousStatement(true, 'Field');
this.setNextStatement(true, 'Field'); this.setNextStatement(true, 'Field');
this.setTooltip('Static image (JPEG, PNG, GIF, SVG, BMP).\n' + this.setTooltip('Static image (JPEG, PNG, GIF, SVG, BMP).\n' +
'Retains aspect ratio regardless of height and width.'); 'Retains aspect ratio regardless of height and width.\n' +
'Alt text is for when collapsed.');
} }
}; };
......
...@@ -209,8 +209,9 @@ function getFields(block) { ...@@ -209,8 +209,9 @@ function getFields(block) {
var src = escapeString(block.getFieldValue('SRC')); var src = escapeString(block.getFieldValue('SRC'));
var width = Number(block.getFieldValue('WIDTH')); var width = Number(block.getFieldValue('WIDTH'));
var height = Number(block.getFieldValue('HEIGHT')); var height = Number(block.getFieldValue('HEIGHT'));
var alt = escapeString(block.getFieldValue('ALT'));
fields.push('new Blockly.FieldImage(' + fields.push('new Blockly.FieldImage(' +
src + ', ' + width + ', ' + height + ')'); src + ', ' + width + ', ' + height + ', ' + alt + ')');
break; break;
} }
block = block.nextConnection && block.nextConnection.targetBlock(); block = block.nextConnection && block.nextConnection.targetBlock();
......
...@@ -35,10 +35,10 @@ Blockly.Blocks['text'] = { ...@@ -35,10 +35,10 @@ Blockly.Blocks['text'] = {
this.setColour(160); this.setColour(160);
this.appendDummyInput() this.appendDummyInput()
.appendField(new Blockly.FieldImage(Blockly.pathToBlockly + .appendField(new Blockly.FieldImage(Blockly.pathToBlockly +
'media/quote0.png', 12, 12)) 'media/quote0.png', 12, 12, '"'))
.appendField(new Blockly.FieldTextInput(''), 'TEXT') .appendField(new Blockly.FieldTextInput(''), 'TEXT')
.appendField(new Blockly.FieldImage(Blockly.pathToBlockly + .appendField(new Blockly.FieldImage(Blockly.pathToBlockly +
'media/quote1.png', 12, 12)); 'media/quote1.png', 12, 12, '"'));
this.setOutput(true, 'String'); this.setOutput(true, 'String');
this.setTooltip(Blockly.Msg.TEXT_TEXT_TOOLTIP); this.setTooltip(Blockly.Msg.TEXT_TEXT_TOOLTIP);
} }
...@@ -76,9 +76,9 @@ Blockly.Blocks['text_join'] = { ...@@ -76,9 +76,9 @@ Blockly.Blocks['text_join'] = {
if (this.itemCount_ == 0) { if (this.itemCount_ == 0) {
this.appendDummyInput('EMPTY') this.appendDummyInput('EMPTY')
.appendField(new Blockly.FieldImage(Blockly.pathToBlockly + .appendField(new Blockly.FieldImage(Blockly.pathToBlockly +
'media/quote0.png', 12, 12)) 'media/quote0.png', 12, 12, '"'))
.appendField(new Blockly.FieldImage(Blockly.pathToBlockly + .appendField(new Blockly.FieldImage(Blockly.pathToBlockly +
'media/quote1.png', 12, 12)); 'media/quote1.png', 12, 12, '"'));
} }
}, },
decompose: function(workspace) { decompose: function(workspace) {
...@@ -122,9 +122,9 @@ Blockly.Blocks['text_join'] = { ...@@ -122,9 +122,9 @@ Blockly.Blocks['text_join'] = {
if (this.itemCount_ == 0) { if (this.itemCount_ == 0) {
this.appendDummyInput('EMPTY') this.appendDummyInput('EMPTY')
.appendField(new Blockly.FieldImage(Blockly.pathToBlockly + .appendField(new Blockly.FieldImage(Blockly.pathToBlockly +
'media/quote0.png', 12, 12)) 'media/quote0.png', 12, 12, '"'))
.appendField(new Blockly.FieldImage(Blockly.pathToBlockly + .appendField(new Blockly.FieldImage(Blockly.pathToBlockly +
'media/quote1.png', 12, 12)); 'media/quote1.png', 12, 12, '"'));
} }
}, },
saveConnections: function(containerBlock) { saveConnections: function(containerBlock) {
...@@ -468,10 +468,10 @@ Blockly.Blocks['text_prompt'] = { ...@@ -468,10 +468,10 @@ Blockly.Blocks['text_prompt'] = {
this.appendDummyInput() this.appendDummyInput()
.appendField(dropdown, 'TYPE') .appendField(dropdown, 'TYPE')
.appendField(new Blockly.FieldImage(Blockly.pathToBlockly + .appendField(new Blockly.FieldImage(Blockly.pathToBlockly +
'media/quote0.png', 12, 12)) 'media/quote0.png', 12, 12, '"'))
.appendField(new Blockly.FieldTextInput(''), 'TEXT') .appendField(new Blockly.FieldTextInput(''), 'TEXT')
.appendField(new Blockly.FieldImage(Blockly.pathToBlockly + .appendField(new Blockly.FieldImage(Blockly.pathToBlockly +
'media/quote1.png', 12, 12)); 'media/quote1.png', 12, 12, '"'));
this.setOutput(true, 'String'); this.setOutput(true, 'String');
// Assign 'this' to a variable for use in the tooltip closure below. // Assign 'this' to a variable for use in the tooltip closure below.
var thisBlock = this; var thisBlock = this;
......
...@@ -34,15 +34,17 @@ goog.require('goog.userAgent'); ...@@ -34,15 +34,17 @@ goog.require('goog.userAgent');
* @param {string} src The URL of the image. * @param {string} src The URL of the image.
* @param {number} width Width of the image. * @param {number} width Width of the image.
* @param {number} height Height of the image. * @param {number} height Height of the image.
* @param {?string} opt_alt Optional alt text for when block is collapsed.
* @extends {Blockly.Field} * @extends {Blockly.Field}
* @constructor * @constructor
*/ */
Blockly.FieldImage = function(src, width, height) { Blockly.FieldImage = function(src, width, height, opt_alt) {
this.sourceBlock_ = null; this.sourceBlock_ = null;
// Ensure height and width are numbers. Strings are bad at math. // Ensure height and width are numbers. Strings are bad at math.
this.height_ = Number(height); this.height_ = Number(height);
this.width_ = Number(width); this.width_ = Number(width);
this.size_ = {height: this.height_ + 10, width: this.width_}; this.size_ = {height: this.height_ + 10, width: this.width_};
this.text_ = opt_alt || '';
// Build the DOM. // Build the DOM.
var offsetY = 6 - Blockly.BlockSvg.FIELD_HEIGHT; var offsetY = 6 - Blockly.BlockSvg.FIELD_HEIGHT;
this.fieldGroup_ = Blockly.createSvgElement('g', {}, null); this.fieldGroup_ = Blockly.createSvgElement('g', {}, null);
...@@ -50,7 +52,7 @@ Blockly.FieldImage = function(src, width, height) { ...@@ -50,7 +52,7 @@ Blockly.FieldImage = function(src, width, height) {
{'height': this.height_ + 'px', {'height': this.height_ + 'px',
'width': this.width_ + 'px', 'width': this.width_ + 'px',
'y': offsetY}, this.fieldGroup_); 'y': offsetY}, this.fieldGroup_);
this.setText(src); this.setValue(src);
if (goog.userAgent.GECKO) { if (goog.userAgent.GECKO) {
// Due to a Firefox bug which eats mouse events on image elements, // Due to a Firefox bug which eats mouse events on image elements,
// a transparent rectangle needs to be placed on top of the image. // a transparent rectangle needs to be placed on top of the image.
...@@ -69,7 +71,8 @@ goog.inherits(Blockly.FieldImage, Blockly.Field); ...@@ -69,7 +71,8 @@ goog.inherits(Blockly.FieldImage, Blockly.Field);
* with the current values of the arguments used during construction. * with the current values of the arguments used during construction.
*/ */
Blockly.FieldImage.prototype.clone = function() { Blockly.FieldImage.prototype.clone = function() {
return new Blockly.FieldImage(this.getText(), this.width_, this.height_); return new Blockly.FieldImage(this.getSrc(), this.width_, this.height_,
this.getText());
}; };
/** /**
...@@ -126,7 +129,7 @@ Blockly.FieldImage.prototype.setTooltip = function(newTip) { ...@@ -126,7 +129,7 @@ Blockly.FieldImage.prototype.setTooltip = function(newTip) {
* @return {string} Current text. * @return {string} Current text.
* @override * @override
*/ */
Blockly.FieldImage.prototype.getText = function() { Blockly.FieldImage.prototype.getValue = function() {
return this.src_; return this.src_;
}; };
...@@ -135,7 +138,7 @@ Blockly.FieldImage.prototype.getText = function() { ...@@ -135,7 +138,7 @@ Blockly.FieldImage.prototype.getText = function() {
* @param {?string} src New source. * @param {?string} src New source.
* @override * @override
*/ */
Blockly.FieldImage.prototype.setText = function(src) { Blockly.FieldImage.prototype.setValue = function(src) {
if (src === null) { if (src === null) {
// No change if null. // No change if null.
return; return;
...@@ -144,3 +147,16 @@ Blockly.FieldImage.prototype.setText = function(src) { ...@@ -144,3 +147,16 @@ Blockly.FieldImage.prototype.setText = function(src) {
this.imageElement_.setAttributeNS('http://www.w3.org/1999/xlink', this.imageElement_.setAttributeNS('http://www.w3.org/1999/xlink',
'xlink:href', goog.isString(src) ? src : ''); 'xlink:href', goog.isString(src) ? src : '');
}; };
/**
* Set the alt text of this image.
* @param {?string} alt New alt text.
* @override
*/
Blockly.FieldImage.prototype.setText = function(alt) {
if (alt === null) {
// No change if null.
return;
}
this.text_ = alt;
};
/**
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Helper functions for generating Dart for blocks.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Dart');
goog.require('Blockly.CodeGenerator');
Blockly.Dart = Blockly.Generator.get('Dart');
/**
* List of illegal variable names.
* This is not intended to be a security feature. Blockly is 100% client-side,
* so bypassing this list is trivial. This is intended to prevent users from
* accidentally clobbering a built-in object or function.
* @private
*/
Blockly.Dart.addReservedWords(
// http://www.dartlang.org/docs/spec/latest/dart-language-specification.pdf
// Section 16.1.1
'assert,break,case,catch,class,const,continue,default,do,else,extends,false,final,finally,for,if,in,is,new,null,return,super,switch,this,throw,true,try,var,void,while,with,' +
// http://api.dartlang.org/dart_core.html
'Collection,Comparable,Completer,Date,double,Function,Future,Hashable,HashMap,HashSet,int,InvocationMirror,Iterable,Iterator,LinkedHashMap,List,Map,Match,num,Options,Pattern,Queue,RegExp,Sequence,SequenceCollection,Set,Stopwatch,String,StringBuffer,Strings,Type,bool,DoubleLinkedQueue,DoubleLinkedQueueEntry,Duration,Expando,Expect,Futures,Object,SequenceIterator,SequenceList,Comparator,AbstractClassInstantiationError,ArgumentError,AssertionError,CastError,Error,Exception,ExpectException,FallThroughError,FormatException,FutureAlreadyCompleteException,FutureNotCompleteException,FutureUnhandledException,IllegalJSRegExpException,IntegerDivisionByZeroException,NoSuchMethodError,NullThrownError,OutOfMemoryError,RangeError,RuntimeError,StackOverflowError,StateError,TypeError,UnimplementedError,UnsupportedError');
/**
* Order of operation ENUMs.
* http://www.dartlang.org/docs/dart-up-and-running/ch02.html#operator_table
*/
Blockly.Dart.ORDER_ATOMIC = 0; // 0 "" ...
Blockly.Dart.ORDER_UNARY_POSTFIX = 1; // expr++ expr-- () [] .
Blockly.Dart.ORDER_UNARY_PREFIX = 2; // -expr !expr ~expr ++expr --expr
Blockly.Dart.ORDER_MULTIPLICATIVE = 3; // * / % ~/
Blockly.Dart.ORDER_ADDITIVE = 4; // + -
Blockly.Dart.ORDER_SHIFT = 5; // << >>
Blockly.Dart.ORDER_RELATIONAL = 6; // is is! >= > <= <
Blockly.Dart.ORDER_EQUALITY = 7; // == != === !==
Blockly.Dart.ORDER_BITWISE_AND = 8; // &
Blockly.Dart.ORDER_BITWISE_XOR = 9; // ^
Blockly.Dart.ORDER_BITWISE_OR = 10; // |
Blockly.Dart.ORDER_LOGICAL_AND = 11; // &&
Blockly.Dart.ORDER_LOGICAL_OR = 12; // ||
Blockly.Dart.ORDER_CONDITIONAL = 13; // expr ? expr : expr
Blockly.Dart.ORDER_ASSIGNMENT = 14; // = *= /= ~/= %= += -= <<= >>= &= ^= |=
Blockly.Dart.ORDER_NONE = 99; // (...)
/**
* Arbitrary code to inject into locations that risk causing infinite loops.
* Any instances of '%1' will be replaced by the block ID that failed.
* E.g. ' checkTimeout(%1);\n'
* @type ?string
*/
Blockly.Dart.INFINITE_LOOP_TRAP = null;
/**
* Initialise the database of variable names.
*/
Blockly.Dart.init = function() {
// Create a dictionary of definitions to be printed before the code.
Blockly.Dart.definitions_ = {};
if (Blockly.Variables) {
if (!Blockly.Dart.variableDB_) {
Blockly.Dart.variableDB_ =
new Blockly.Names(Blockly.Dart.RESERVED_WORDS_);
} else {
Blockly.Dart.variableDB_.reset();
}
var defvars = [];
var variables = Blockly.Variables.allVariables();
for (var x = 0; x < variables.length; x++) {
defvars[x] = 'var ' +
Blockly.Dart.variableDB_.getName(variables[x],
Blockly.Variables.NAME_TYPE) + ';';
}
Blockly.Dart.definitions_['variables'] = defvars.join('\n');
}
};
/**
* Prepend the generated code with the variable definitions.
* @param {string} code Generated code.
* @return {string} Completed code.
*/
Blockly.Dart.finish = function(code) {
// Indent every line.
code = ' ' + code.replace(/\n/g, '\n ');
code = code.replace(/\n\s+$/, '\n');
code = 'main() {\n' + code + '}';
// Convert the definitions dictionary into a list.
var imports = [];
var definitions = [];
for (var name in Blockly.Dart.definitions_) {
var def = Blockly.Dart.definitions_[name];
if (def.match(/^import\s/)) {
imports.push(def);
} else {
definitions.push(def);
}
}
var allDefs = imports.join('\n') + '\n\n' + definitions.join('\n\n');
return allDefs.replace(/\n\n+/g, '\n\n').replace(/\n*$/, '\n\n\n') + code;
};
/**
* Naked values are top-level blocks with outputs that aren't plugged into
* anything. A trailing semicolon is needed to make this legal.
* @param {string} line Line of generated code.
* @return {string} Legal line of code.
*/
Blockly.Dart.scrubNakedValue = function(line) {
return line + ';\n';
};
/**
* Encode a string as a properly escaped Dart string, complete with quotes.
* @param {string} string Text to encode.
* @return {string} Dart string.
* @private
*/
Blockly.Dart.quote_ = function(string) {
// TODO: This is a quick hack. Replace with goog.string.quote
string = string.replace(/\\/g, '\\\\')
.replace(/\n/g, '\\\n')
.replace(/\$/g, '\\$')
.replace(/'/g, '\\\'');
return '\'' + string + '\'';
};
/**
* Common tasks for generating Dart from blocks.
* Handles comments for the specified block and any connected value blocks.
* Calls any statements following this block.
* @param {!Blockly.Block} block The current block.
* @param {string} code The Dart code created for this block.
* @return {string} Dart code with comments and subsequent blocks added.
* @this {Blockly.CodeGenerator}
* @private
*/
Blockly.Dart.scrub_ = function(block, code) {
if (code === null) {
// Block has handled code generation itself.
return '';
}
var commentCode = '';
// Only collect comments for blocks that aren't inline.
if (!block.outputConnection || !block.outputConnection.targetConnection) {
// Collect comment for this block.
var comment = block.getCommentText();
if (comment) {
commentCode += Blockly.Generator.prefixLines(comment, '// ') + '\n';
}
// Collect comments for all value arguments.
// Don't collect comments for nested statements.
for (var x = 0; x < block.inputList.length; x++) {
if (block.inputList[x].type == Blockly.INPUT_VALUE) {
var childBlock = block.inputList[x].connection.targetBlock();
if (childBlock) {
var comment = Blockly.Generator.allNestedComments(childBlock);
if (comment) {
commentCode += Blockly.Generator.prefixLines(comment, '// ');
}
}
}
}
}
var nextBlock = block.nextConnection && block.nextConnection.targetBlock();
var nextCode = this.blockToCode(nextBlock);
return commentCode + code + nextCode;
};
/**
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Dart for colour blocks.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Dart.colour');
goog.require('Blockly.Dart');
Blockly.Dart.addReservedWords('Math');
Blockly.Dart.colour_picker = function() {
// Colour picker.
var code = '\'' + this.getTitleValue('COLOUR') + '\'';
return [code, Blockly.Dart.ORDER_ATOMIC];
};
Blockly.Dart.colour_rgb = function() {
// Compose a colour from RGB components.
var red = Blockly.Dart.valueToCode(this, 'RED',
Blockly.Dart.ORDER_NONE) || 0;
var green = Blockly.Dart.valueToCode(this, 'GREEN',
Blockly.Dart.ORDER_NONE) || 0;
var blue = Blockly.Dart.valueToCode(this, 'BLUE',
Blockly.Dart.ORDER_NONE) || 0;
if (!Blockly.Dart.definitions_['colour_rgb']) {
Blockly.Dart.definitions_['import_dart_math'] =
'import \'dart:math\' as Math;';
var functionName = Blockly.Dart.variableDB_.getDistinctName(
'colour_rgb', Blockly.Generator.NAME_TYPE);
Blockly.Dart.colour_rgb.functionName = functionName;
var func = [];
func.push('String ' + functionName + '(num r, num g, num b) {');
func.push(' num rn = (Math.max(Math.min(r, 1), 0) * 255).round();');
func.push(' String rs = rn.toInt().toRadixString(16);');
func.push(' rs = \'0$rs\';');
func.push(' rs = rs.substring(rs.length - 2);');
func.push(' num gn = (Math.max(Math.min(g, 1), 0) * 255).round();');
func.push(' String gs = gn.toInt().toRadixString(16);');
func.push(' gs = \'0$gs\';');
func.push(' gs = gs.substring(gs.length - 2);');
func.push(' num bn = (Math.max(Math.min(b, 1), 0) * 255).round();');
func.push(' String bs = bn.toInt().toRadixString(16);');
func.push(' bs = \'0$bs\';');
func.push(' bs = bs.substring(bs.length - 2);');
func.push(' return \'#$rs$gs$bs\';');
func.push('}');
Blockly.Dart.definitions_['colour_rgb'] = func.join('\n');
}
var code = Blockly.Dart.colour_rgb.functionName +
'(' + red + ', ' + green + ', ' + blue + ')';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};
Blockly.Dart.colour_blend = function() {
// Blend two colours together.
var c1 = Blockly.Dart.valueToCode(this, 'COLOUR1',
Blockly.Dart.ORDER_NONE) || '\'#000000\'';
var c2 = Blockly.Dart.valueToCode(this, 'COLOUR2',
Blockly.Dart.ORDER_NONE) || '\'#000000\'';
var ratio = Blockly.Dart.valueToCode(this, 'RATIO',
Blockly.Dart.ORDER_NONE) || 0.5;
if (!Blockly.Dart.definitions_['colour_blend']) {
Blockly.Dart.definitions_['import_dart_math'] =
'import \'dart:math\' as Math;';
var functionName = Blockly.Dart.variableDB_.getDistinctName(
'colour_blend', Blockly.Generator.NAME_TYPE);
Blockly.Dart.colour_blend.functionName = functionName;
var func = [];
func.push('String ' + functionName + '(String c1, String c2, num ratio) {');
func.push(' ratio = Math.max(Math.min(ratio, 1), 0);');
func.push(' int r1 = int.parse(\'0x${c1.substring(1, 3)}\');');
func.push(' int g1 = int.parse(\'0x${c1.substring(3, 5)}\');');
func.push(' int b1 = int.parse(\'0x${c1.substring(5, 7)}\');');
func.push(' int r2 = int.parse(\'0x${c2.substring(1, 3)}\');');
func.push(' int g2 = int.parse(\'0x${c2.substring(3, 5)}\');');
func.push(' int b2 = int.parse(\'0x${c2.substring(5, 7)}\');');
func.push(' num rn = (r1 * (1 - ratio) + r2 * ratio).round();');
func.push(' String rs = rn.toInt().toRadixString(16);');
func.push(' num gn = (g1 * (1 - ratio) + g2 * ratio).round();');
func.push(' String gs = gn.toInt().toRadixString(16);');
func.push(' num bn = (b1 * (1 - ratio) + b2 * ratio).round();');
func.push(' String bs = bn.toInt().toRadixString(16);');
func.push(' rs = \'0$rs\';');
func.push(' rs = rs.substring(rs.length - 2);');
func.push(' gs = \'0$gs\';');
func.push(' gs = gs.substring(gs.length - 2);');
func.push(' bs = \'0$bs\';');
func.push(' bs = bs.substring(bs.length - 2);');
func.push(' return \'#$rs$gs$bs\';');
func.push('}');
Blockly.Dart.definitions_['colour_blend'] = func.join('\n');
}
var code = Blockly.Dart.colour_blend.functionName +
'(' + c1 + ', ' + c2 + ', ' + ratio + ')';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};
This diff is collapsed.
/**
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Dart for logic blocks.
* @author q.neutron@gmail.com (Quynh Neutron)
*/
'use strict';
goog.provide('Blockly.Dart.logic');
goog.require('Blockly.Dart');
Blockly.Dart.logic_compare = function() {
// Comparison operator.
var mode = this.getTitleValue('OP');
var operator = Blockly.Dart.logic_compare.OPERATORS[mode];
var order = (operator == '==' || operator == '!=') ?
Blockly.Dart.ORDER_EQUALITY : Blockly.Dart.ORDER_RELATIONAL;
var argument0 = Blockly.Dart.valueToCode(this, 'A', order) || '0';
var argument1 = Blockly.Dart.valueToCode(this, 'B', order) || '0';
var code = argument0 + ' ' + operator + ' ' + argument1;
return [code, order];
};
Blockly.Dart.logic_compare.OPERATORS = {
EQ: '==',
NEQ: '!=',
LT: '<',
LTE: '<=',
GT: '>',
GTE: '>='
};
Blockly.Dart.logic_operation = function() {
// Operations 'and', 'or'.
var operator = (this.getTitleValue('OP') == 'AND') ? '&&' : '||';
var order = (operator == '&&') ? Blockly.Dart.ORDER_LOGICAL_AND :
Blockly.Dart.ORDER_LOGICAL_OR;
var argument0 = Blockly.Dart.valueToCode(this, 'A', order) || 'false';
var argument1 = Blockly.Dart.valueToCode(this, 'B', order) || 'false';
var code = argument0 + ' ' + operator + ' ' + argument1;
return [code, order];
};
Blockly.Dart.logic_negate = function() {
// Negation.
var order = Blockly.Dart.ORDER_UNARY_PREFIX;
var argument0 = Blockly.Dart.valueToCode(this, 'BOOL', order) || 'false';
var code = '!' + argument0;
return [code, order];
};
Blockly.Dart.logic_boolean = function() {
// Boolean values true and false.
var code = (this.getTitleValue('BOOL') == 'TRUE') ? 'true' : 'false';
return [code, Blockly.Dart.ORDER_ATOMIC];
};
Blockly.Dart.logic_null = function() {
// Null data type.
return ['null', Blockly.Dart.ORDER_ATOMIC];
};
Blockly.Dart.logic_ternary = function() {
// Ternary operator.
var value_if = Blockly.Dart.valueToCode(this, 'IF',
Blockly.Dart.ORDER_CONDITIONAL) || 'false';
var value_then = Blockly.Dart.valueToCode(this, 'THEN',
Blockly.Dart.ORDER_CONDITIONAL) || 'null';
var value_else = Blockly.Dart.valueToCode(this, 'ELSE',
Blockly.Dart.ORDER_CONDITIONAL) || 'null';
var code = value_if + ' ? ' + value_then + ' : ' + value_else
return [code, Blockly.Dart.ORDER_CONDITIONAL];
};
/**
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Dart for control blocks.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Dart.control');
goog.require('Blockly.Dart');
Blockly.Dart.controls_if = function() {
// If/elseif/else condition.
var n = 0;
var argument = Blockly.Dart.valueToCode(this, 'IF' + n,
Blockly.Dart.ORDER_NONE) || 'false';
var branch = Blockly.Dart.statementToCode(this, 'DO' + n);
var code = 'if (' + argument + ') {\n' + branch + '}';
for (n = 1; n <= this.elseifCount_; n++) {
argument = Blockly.Dart.valueToCode(this, 'IF' + n,
Blockly.Dart.ORDER_NONE) || 'false';
branch = Blockly.Dart.statementToCode(this, 'DO' + n);
code += ' else if (' + argument + ') {\n' + branch + '}';
}
if (this.elseCount_) {
branch = Blockly.Dart.statementToCode(this, 'ELSE');
code += ' else {\n' + branch + '}';
}
return code + '\n';
};
Blockly.Dart.controls_repeat = function() {
// Repeat n times.
var repeats = Number(this.getTitleValue('TIMES'));
var branch = Blockly.Dart.statementToCode(this, 'DO');
if (Blockly.Dart.INFINITE_LOOP_TRAP) {
branch = Blockly.Dart.INFINITE_LOOP_TRAP.replace(/%1/g,
'\'' + this.id + '\'') + branch;
}
var loopVar = Blockly.Dart.variableDB_.getDistinctName(
'count', Blockly.Variables.NAME_TYPE);
var code = 'for (int ' + loopVar + ' = 0; ' +
loopVar + ' < ' + repeats + '; ' +
loopVar + '++) {\n' +
branch + '}\n';
return code;
};
Blockly.Dart.controls_whileUntil = function() {
// Do while/until loop.
var argument0 = Blockly.Dart.valueToCode(this, 'BOOL',
Blockly.Dart.ORDER_NONE) || 'false';
var branch = Blockly.Dart.statementToCode(this, 'DO');
if (Blockly.Dart.INFINITE_LOOP_TRAP) {
branch = Blockly.Dart.INFINITE_LOOP_TRAP.replace(/%1/g,
'\'' + this.id + '\'') + branch;
}
if (this.getTitleValue('MODE') == 'UNTIL') {
if (!argument0.match(/^\w+$/)) {
argument0 = '(' + argument0 + ')';
}
argument0 = '!' + argument0;
}
return 'while (' + argument0 + ') {\n' + branch + '}\n';
};
Blockly.Dart.controls_for = function() {
// For loop.
var variable0 = Blockly.Dart.variableDB_.getName(
this.getTitleValue('VAR'), Blockly.Variables.NAME_TYPE);
var argument0 = Blockly.Dart.valueToCode(this, 'FROM',
Blockly.Dart.ORDER_ASSIGNMENT) || '0';
var argument1 = Blockly.Dart.valueToCode(this, 'TO',
Blockly.Dart.ORDER_ASSIGNMENT) || '0';
var branch = Blockly.Dart.statementToCode(this, 'DO');
if (Blockly.Dart.INFINITE_LOOP_TRAP) {
branch = Blockly.Dart.INFINITE_LOOP_TRAP.replace(/%1/g,
'\'' + this.id + '\'') + branch;
}
var code;
if (argument0.match(/^-?\d+(\.\d+)?$/) &&
argument1.match(/^-?\d+(\.\d+)?$/)) {
// Both arguments are simple numbers.
var up = parseFloat(argument0) <= parseFloat(argument1);
code = 'for (num ' + variable0 + ' = ' + argument0 + '; ' +
variable0 + (up ? ' <= ' : ' >= ') + argument1 + '; ' +
variable0 + (up ? '++' : '--') + ') {\n' +
branch + '}\n';
} else {
code = '';
// Cache non-trivial values to variables to prevent repeated look-ups.
var startVar = argument0;
if (!argument0.match(/^\w+$/) && !argument0.match(/^-?\d+(\.\d+)?$/)) {
var startVar = Blockly.Dart.variableDB_.getDistinctName(
variable0 + '_start', Blockly.Variables.NAME_TYPE);
code += 'var ' + startVar + ' = ' + argument0 + ';\n';
}
var endVar = argument1;
if (!argument1.match(/^\w+$/) && !argument1.match(/^-?\d+(\.\d+)?$/)) {
var endVar = Blockly.Dart.variableDB_.getDistinctName(
variable0 + '_end', Blockly.Variables.NAME_TYPE);
code += 'var ' + endVar + ' = ' + argument1 + ';\n';
}
code += 'for (' + variable0 + ' = ' + startVar + ';\n' +
' (' + startVar + ' <= ' + endVar + ') ? ' +
variable0 + ' <= ' + endVar + ' : ' +
variable0 + ' >= ' + endVar + ';\n' +
' ' + variable0 + ' += (' + startVar + ' <= ' + endVar +
') ? 1 : -1) {\n' +
branch + '}\n';
}
return code;
};
Blockly.Dart.controls_forEach = function() {
// For each loop.
var variable0 = Blockly.Dart.variableDB_.getName(
this.getTitleValue('VAR'), Blockly.Variables.NAME_TYPE);
var argument0 = Blockly.Dart.valueToCode(this, 'LIST',
Blockly.Dart.ORDER_ASSIGNMENT) || '[]';
var branch = Blockly.Dart.statementToCode(this, 'DO');
if (Blockly.Dart.INFINITE_LOOP_TRAP) {
branch = Blockly.Dart.INFINITE_LOOP_TRAP.replace(/%1/g,
'\'' + this.id + '\'') + branch;
}
var code = 'for (var ' + variable0 + ' in ' + argument0 + ') {\n' +
branch + '}\n';
return code;
};
Blockly.Dart.controls_flow_statements = function() {
// Flow statements: continue, break.
switch (this.getTitleValue('FLOW')) {
case 'BREAK':
return 'break;\n';
case 'CONTINUE':
return 'continue;\n';
}
throw 'Unknown flow statement.';
};
This diff is collapsed.
/**
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Dart for variable blocks.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Dart.procedures');
goog.require('Blockly.Dart');
Blockly.Dart.procedures_defreturn = function() {
// Define a procedure with a return value.
var funcName = Blockly.Dart.variableDB_.getName(this.getTitleValue('NAME'),
Blockly.Procedures.NAME_TYPE);
var branch = Blockly.Dart.statementToCode(this, 'STACK');
if (Blockly.Dart.INFINITE_LOOP_TRAP) {
branch = Blockly.Dart.INFINITE_LOOP_TRAP.replace(/%1/g,
'\'' + this.id + '\'') + branch;
}
var returnValue = Blockly.Dart.valueToCode(this, 'RETURN',
Blockly.Dart.ORDER_NONE) || '';
if (returnValue) {
returnValue = ' return ' + returnValue + ';\n';
}
var returnType = returnValue ? 'dynamic' : 'void';
var args = [];
for (var x = 0; x < this.arguments_.length; x++) {
args[x] = Blockly.Dart.variableDB_.getName(this.arguments_[x],
Blockly.Variables.NAME_TYPE);
}
var code = returnType + ' ' + funcName + '(' + args.join(', ') + ') {\n' +
branch + returnValue + '}';
code = Blockly.Dart.scrub_(this, code);
Blockly.Dart.definitions_[funcName] = code;
return null;
};
// Defining a procedure without a return value uses the same generator as
// a procedure with a return value.
Blockly.Dart.procedures_defnoreturn = Blockly.Dart.procedures_defreturn;
Blockly.Dart.procedures_callreturn = function() {
// Call a procedure with a return value.
var funcName = Blockly.Dart.variableDB_.getName(this.getTitleValue('NAME'),
Blockly.Procedures.NAME_TYPE);
var args = [];
for (var x = 0; x < this.arguments_.length; x++) {
args[x] = Blockly.Dart.valueToCode(this, 'ARG' + x,
Blockly.Dart.ORDER_NONE) || 'null';
}
var code = funcName + '(' + args.join(', ') + ')';
return [code, Blockly.Dart.ORDER_UNARY_POSTFIX];
};
Blockly.Dart.procedures_callnoreturn = function() {
// Call a procedure with no return value.
var funcName = Blockly.Dart.variableDB_.getName(this.getTitleValue('NAME'),
Blockly.Procedures.NAME_TYPE);
var args = [];
for (var x = 0; x < this.arguments_.length; x++) {
args[x] = Blockly.Dart.valueToCode(this, 'ARG' + x,
Blockly.Dart.ORDER_NONE) || 'null';
}
var code = funcName + '(' + args.join(', ') + ');\n';
return code;
};
Blockly.Dart.procedures_ifreturn = function() {
// Conditionally return value from a procedure.
var condition = Blockly.Dart.valueToCode(this, 'CONDITION',
Blockly.Dart.ORDER_NONE) || 'false';
var code = 'if (' + condition + ') {\n';
if (this.hasReturnValue_) {
var value = Blockly.Dart.valueToCode(this, 'VALUE',
Blockly.Dart.ORDER_NONE) || 'null';
code += ' return ' + value + ';\n';
} else {
code += ' return;\n';
}
code += '}\n';
return code;
};
This diff is collapsed.
/**
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Dart for variable blocks.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.Dart.variables');
goog.require('Blockly.Dart');
Blockly.Dart.variables_get = function() {
// Variable getter.
var code = Blockly.Dart.variableDB_.getName(this.getTitleValue('VAR'),
Blockly.Variables.NAME_TYPE);
return [code, Blockly.Dart.ORDER_ATOMIC];
};
Blockly.Dart.variables_set = function() {
// Variable setter.
var argument0 = Blockly.Dart.valueToCode(this, 'VALUE',
Blockly.Dart.ORDER_ASSIGNMENT) || '0';
var varName = Blockly.Dart.variableDB_.getName(this.getTitleValue('VAR'),
Blockly.Variables.NAME_TYPE);
return varName + ' = ' + argument0 + ';\n';
};
/**
* Visual Blocks Language
*
* Copyright 2012 Google Inc.
* http://blockly.googlecode.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Generating Dart for unit test blocks.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
Blockly.Dart = Blockly.Generator.get('Dart');
Blockly.Dart.unittest_main = function() {
// Container for unit tests.
var resultsVar = Blockly.Dart.variableDB_.getName('unittestResults',
Blockly.Variables.NAME_TYPE);
if (!Blockly.Dart.definitions_['unittest_report']) {
var functionName = Blockly.Dart.variableDB_.getDistinctName(
'testReport', Blockly.Generator.NAME_TYPE);
Blockly.Dart.unittest_main.report = functionName;
var func = [];
func.push('String ' + functionName + '() {');
func.push(' // Create test report.');
func.push(' List report = [];');
func.push(' StringBuffer summary = new StringBuffer();');
func.push(' int fails = 0;');
func.push(' for (int x = 0; x < ' + resultsVar + '.length; x++) {');
func.push(' if (' + resultsVar + '[x][0]) {');
func.push(' summary.write(".");');
func.push(' } else {');
func.push(' summary.write("F");');
func.push(' fails++;');
func.push(' report.add("");');
func.push(' report.add("FAIL: ${' + resultsVar + '[x][2]}");');
func.push(' report.add(' + resultsVar + '[x][1]);');
func.push(' }');
func.push(' }');
func.push(' report.insertRange(0, 1, summary.toString());');
func.push(' report.add("");');
func.push(' report.add("Ran ${' + resultsVar + '.length} tests.");');
func.push(' report.add("");');
func.push(' if (fails != 0) {');
func.push(' report.add("FAILED (failures=$fails)");');
func.push(' } else {');
func.push(' report.add("OK");');
func.push(' }');
func.push(' return report.join("\\n");');
func.push('}');
func.push('');
Blockly.Dart.definitions_['unittest_report'] = func.join('\n');
}
// Setup global to hold test results.
var code = resultsVar + ' = [];\n';
// Run tests (unindented).
code += Blockly.Dart.statementToCode(this, 'DO')
.replace(/^ /, '').replace(/\n /g, '\n');
var reportVar = Blockly.Dart.variableDB_.getDistinctName(
'report', Blockly.Variables.NAME_TYPE);
code += 'String ' + reportVar + ' = ' +
Blockly.Dart.unittest_main.report + '();\n';
// Destroy results.
code += resultsVar + ' = null;\n';
// Print the report to the console (that's where errors will go anyway).
code += 'print(' + reportVar + ');\n';
return code;
};
Blockly.Dart.unittest_main.defineAssert_ = function() {
if (!Blockly.Dart.definitions_['unittest_assertequals']) {
var resultsVar = Blockly.Dart.variableDB_.getName('unittestResults',
Blockly.Variables.NAME_TYPE);
var functionName = Blockly.Dart.variableDB_.getDistinctName(
'assertEquals', Blockly.Generator.NAME_TYPE);
Blockly.Dart.unittest_main.assert_ = functionName;
var func = [];
func.push('void ' + functionName +
'(dynamic actual, dynamic expected, String message) {');
func.push(' // Asserts that a value equals another value.');
func.push(' if (' + resultsVar + ' == null) {');
func.push(' throw "Orphaned assert: ${message}";');
func.push(' }');
func.push(' if (actual == expected) {');
func.push(' ' + resultsVar + '.add([true, "OK", message]);');
func.push(' } else {');
func.push(' ' + resultsVar + '.add([false, ' +
'"Expected: $expected\\nActual: $actual", message]);');
func.push(' }');
func.push('}');
func.push('');
Blockly.Dart.definitions_['unittest_assertequals'] = func.join('\n');
}
return Blockly.Dart.unittest_main.assert_;
};
Blockly.Dart.unittest_assertequals = function() {
// Asserts that a value equals another value.
var resultsVar = Blockly.Dart.variableDB_.getName('unittestResults',
Blockly.Variables.NAME_TYPE);
var message = Blockly.Dart.quote_(this.getTitleValue('MESSAGE'));
var actual = Blockly.Dart.valueToCode(this, 'ACTUAL',
Blockly.Dart.ORDER_NONE) || 'null';
var expected = Blockly.Dart.valueToCode(this, 'EXPECTED',
Blockly.Dart.ORDER_NONE) || 'null';
return Blockly.Dart.unittest_main.defineAssert_() +
'(' + actual + ', ' + expected + ', ' + message + ');\n';
};
Blockly.Dart.unittest_assertvalue = function() {
// Asserts that a value is true, false, or null.
var resultsVar = Blockly.Dart.variableDB_.getName('unittestResults',
Blockly.Variables.NAME_TYPE);
var message = Blockly.Dart.quote_(this.getTitleValue('MESSAGE'));
var actual = Blockly.Dart.valueToCode(this, 'ACTUAL',
Blockly.Dart.ORDER_NONE) || 'true';
var expected = this.getTitleValue('EXPECTED');
if (expected == 'TRUE') {
expected = 'true';
} else if (expected == 'FALSE') {
expected = 'false';
} else if (expected == 'NULL') {
expected = 'null';
}
return Blockly.Dart.unittest_main.defineAssert_() +
'(' + actual + ', ' + expected + ', ' + message + ');\n';
};
Blockly.Dart.unittest_fail = function() {
// Always assert an error.
var resultsVar = Blockly.Dart.variableDB_.getName('unittestResults',
Blockly.Variables.NAME_TYPE);
var message = Blockly.Dart.quote_(this.getTitleValue('MESSAGE'));
if (!Blockly.Dart.definitions_['unittest_fail']) {
var functionName = Blockly.Dart.variableDB_.getDistinctName(
'fail', Blockly.Generator.NAME_TYPE);
Blockly.Dart.unittest_fail.assert = functionName;
var func = [];
func.push('void ' + functionName + '(String message) {');
func.push(' // Always assert an error.');
func.push(' if (' + resultsVar + ' == null) {');
func.push(' throw "Orphaned assert fail: ' + message + '";');
func.push(' }');
func.push(' ' + resultsVar + '.add([false, "Fail.", message]);');
func.push('}');
func.push('');
Blockly.Dart.definitions_['unittest_fail'] = func.join('\n');
}
return Blockly.Dart.unittest_fail.assert + '(' + message + ');\n';
};
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment