初始化提交

This commit is contained in:
王立帮
2024-07-19 10:16:00 +08:00
parent 4c7b571f20
commit 4a2d56dcc4
7084 changed files with 741212 additions and 63 deletions

View File

@@ -0,0 +1,722 @@
/**
* @license
* Visual Blocks Editor
*
* Copyright 2012 Google Inc.
* https://developers.google.com/blockly/
*
* 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 Utility functions for handling class_test.
* @author fraser@google.com (Neil Fraser)
*/
import * as Blockly from 'blockly/core';
//类
Blockly.Block.prototype.class_getVars = function () { for (var a = [], b = 0, c; c = this.inputList[b]; b++)for (var d = 0, e; e = c.fieldRow[d]; d++)e instanceof Blockly.FieldVariable && a.push(e.getValue()); return a }; Blockly.Block.prototype.class_renameVar = function (a, b) { for (var c = 0, d; d = this.inputList[c]; c++)for (var e = 0, f; f = d.fieldRow[e]; e++)f instanceof Blockly.FieldVariable && Blockly.Names.equals(a, f.getValue()) && f.setValue(b) };
//属性
Blockly.Block.prototype.property_getVars = function () { for (var a = [], b = 0, c; c = this.inputList[b]; b++)for (var d = 0, e; e = c.fieldRow[d]; d++)e instanceof Blockly.FieldVariable && a.push(e.getValue()); return a }; Blockly.Block.prototype.property_renameVar = function (a, b) { for (var c = 0, d; d = this.inputList[c]; c++)for (var e = 0, f; f = d.fieldRow[e]; e++)f instanceof Blockly.FieldVariable && Blockly.Names.equals(a, f.getValue()) && f.setValue(b) };
//对象
Blockly.Block.prototype.object_getVars = function () { for (var a = [], b = 0, c; c = this.inputList[b]; b++)for (var d = 0, e; e = c.fieldRow[d]; d++)e instanceof Blockly.FieldVariable && a.push(e.getValue()); return a }; Blockly.Block.prototype.object_renameVar = function (a, b) { for (var c = 0, d; d = this.inputList[c]; c++)for (var e = 0, f; f = d.fieldRow[e]; e++)f instanceof Blockly.FieldVariable && Blockly.Names.equals(a, f.getValue()) && f.setValue(b) };
//类
Blockly.Class.CLASS_NAME_TYPE = 'CLASS';
//属性
Blockly.Class.PROPERTY_NAME_TYPE = 'PROPERTY';
//方法
Blockly.Class.METHOD_NAME_TYPE = 'METHOD';
//对象
Blockly.Class.OBJECT_NAME_TYPE = 'OBJECT';
/**** 类 ****/
Blockly.Class.allClass = function (root) {
var blocks;
if (root.getDescendants) {
// Root is Block.
blocks = root.getDescendants();
} else if (root.getAllBlocks) {
// Root is Workspace.
blocks = root.getAllBlocks();
} else {
throw 'Not Block or Workspace: ' + root;
}
var variableHash = Object.create(null);
// Iterate through every block and add each variable to the hash.
for (var x = 0; x < blocks.length; x++) {
var blockClass = blocks[x].class_getVars();
for (var y = 0; y < blockClass.length; y++) {
var varName = blockClass[y];
// Variable name may be null if the block is only half-built.
if (varName) {
variableHash[varName.toLowerCase()] = varName;
}
}
}
// Flatten the hash into a list.
var variableList = [];
for (var name in variableHash) {
variableList.push(variableHash[name]);
}
return variableList;
};
Blockly.Class.renameClass = function (oldName, newName, workspace) {
Blockly.Events.setGroup(true);
var blocks = workspace.getAllBlocks();
// Iterate through every block.
for (var i = 0; i < blocks.length; i++) {
blocks[i].class_renameVar(oldName, newName);
}
Blockly.Events.setGroup(false);
};
Blockly.Class.class_generateUniqueName = function (workspace) {
var variableList = Blockly.Class.allClass(workspace);
var newName = '';
if (variableList.length) {
var nameSuffix = 1;
var letters = 'ijkmnopqrstuvwxyzabcdefgh'; // No 'l'.
var letterIndex = 0;
var potName = letters.charAt(letterIndex);
while (!newName) {
var inUse = false;
for (var i = 0; i < variableList.length; i++) {
if (variableList[i].toLowerCase() == potName) {
// This potential name is already used.
inUse = true;
break;
}
}
if (inUse) {
// Try the next potential name.
letterIndex++;
if (letterIndex == letters.length) {
// Reached the end of the character sequence so back to 'i'.
// a new suffix.
letterIndex = 0;
nameSuffix++;
}
potName = letters.charAt(letterIndex);
if (nameSuffix > 1) {
potName += nameSuffix;
}
} else {
// We can use the current potential name.
newName = potName;
}
}
} else {
newName = 'i';
}
return newName;
};
Blockly.Class.class_flyoutCategory = function (workspace) {
var variableList = Blockly.Class.allClass(workspace);
//variableList.sort(goog.string.caseInsensitiveCompare);
var xmlList = [];
//创建类
if (Blockly.Blocks['class_make']) {
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'class_make');
if (Blockly.Blocks['class_make']) {
block.setAttribute('gap', 16);
}
xmlList.push(block);
}
if (Blockly.Blocks['class_make_with_base']) {
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'class_make_with_base');
if (Blockly.Blocks['class_make_with_base']) {
block.setAttribute('gap', 16);
}
xmlList.push(block);
}
if (xmlList.length) {
xmlList[xmlList.length - 1].setAttribute('gap', 30);
}
for (var i = 0; i < variableList.length; i++) {
if (Blockly.Blocks['class_get']) {
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'class_get');
if (Blockly.Blocks['class_get']) {
block.setAttribute('gap', 16);
}
var field = Blockly.utils.xml.createElement('field', null, variableList[i]);
field.setAttribute('name', 'VAR');
block.appendChild(field);
xmlList.push(block);
}
}
return xmlList;
};
/**** 属性 ****/
Blockly.Class.allProperty = function (root) {
var blocks;
if (root.getDescendants) {
// Root is Block.
blocks = root.getDescendants();
} else if (root.getAllBlocks) {
// Root is Workspace.
blocks = root.getAllBlocks();
} else {
throw 'Not Block or Workspace: ' + root;
}
var variableHash = Object.create(null);
// Iterate through every block and add each variable to the hash.
for (var x = 0; x < blocks.length; x++) {
var blockClass = blocks[x].property_getVars();
for (var y = 0; y < blockClass.length; y++) {
var varName = blockClass[y];
// Variable name may be null if the block is only half-built.
if (varName) {
variableHash[varName.toLowerCase()] = varName;
}
}
}
// Flatten the hash into a list.
var variableList = [];
for (var name in variableHash) {
variableList.push(variableHash[name]);
}
return variableList;
};
Blockly.Class.renameProperty = function (oldName, newName, workspace) {
Blockly.Events.setGroup(true);
var blocks = workspace.getAllBlocks();
// Iterate through every block.
for (var i = 0; i < blocks.length; i++) {
blocks[i].property_renameVar(oldName, newName);
}
Blockly.Events.setGroup(false);
};
Blockly.Class.property_generateUniqueName = function (workspace) {
var variableList = Blockly.Class.allProperty(workspace);
var newName = '';
if (variableList.length) {
var nameSuffix = 1;
var letters = 'ijkmnopqrstuvwxyzabcdefgh'; // No 'l'.
var letterIndex = 0;
var potName = letters.charAt(letterIndex);
while (!newName) {
var inUse = false;
for (var i = 0; i < variableList.length; i++) {
if (variableList[i].toLowerCase() == potName) {
// This potential name is already used.
inUse = true;
break;
}
}
if (inUse) {
// Try the next potential name.
letterIndex++;
if (letterIndex == letters.length) {
// Reached the end of the character sequence so back to 'i'.
// a new suffix.
letterIndex = 0;
nameSuffix++;
}
potName = letters.charAt(letterIndex);
if (nameSuffix > 1) {
potName += nameSuffix;
}
} else {
// We can use the current potential name.
newName = potName;
}
}
} else {
newName = 'i';
}
return newName;
};
Blockly.Class.property_flyoutCategory = function (workspace) {
var variableList = Blockly.Class.allProperty(workspace);
//variableList.sort(goog.string.caseInsensitiveCompare);
var xmlList = [];
//创建属性
if (Blockly.Blocks['property_set']) {
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'property_set');
xmlList.push(block);
}
if (xmlList.length) {
xmlList[xmlList.length - 1].setAttribute('gap', 30);
}
for (var i = 0; i < variableList.length; i++) {
if (Blockly.Blocks['property_set']) {
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'property_set');
if (Blockly.Blocks['property_set']) {
block.setAttribute('gap', 16);
}
var field = Blockly.utils.xml.createElement('field', null, variableList[i]);
field.setAttribute('name', 'VAR');
block.appendChild(field);
xmlList.push(block);
}
if (Blockly.Blocks['property_get']) {
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'property_get');
if (Blockly.Blocks['property_get']) {
block.setAttribute('gap', 25);
}
var field = Blockly.utils.xml.createElement('field', null, variableList[i]);
field.setAttribute('name', 'VAR');
block.appendChild(field);
xmlList.push(block);
}
}
return xmlList;
};
/**** 方法 ****/
Blockly.Class.proallProcedures = function (root) {
var blocks = root.getAllBlocks();
var proceduresReturn = [];
var proceduresNoReturn = [];
var name_data = [];
var select = true;
for (var i = 0; i < blocks.length; i++) {
if (blocks[i].method_getProcedureDef) {
var tuple = blocks[i].method_getProcedureDef();
if (tuple) {
if (tuple[4]) {
if (name_data.length == 0) {
if (tuple[4].indexOf("_") != -1) {
select = true;
name_data.push(tuple[4]);
}
else {
select = false;
}
}
else {
for (var j = 0; j < name_data.length; j++) {
if (name_data[j] == tuple[4] || tuple[4].indexOf("_") == -1) {
select = false;
break;
}
if (j == name_data.length - 1) {
select = true;
name_data.push(tuple[4]);
break;
}
}
}
}
if (select) {
if (tuple[2]) {
proceduresReturn.push(tuple);
} else {
proceduresNoReturn.push(tuple);
}
}
}
}
}
proceduresNoReturn.sort(Blockly.Class.proprocTupleComparator_);
proceduresReturn.sort(Blockly.Class.proprocTupleComparator_);
return [proceduresNoReturn, proceduresReturn];
};
/**
* Comparison function for case-insensitive sorting of the first element of
* a tuple.
* @param {!Array} ta First tuple.
* @param {!Array} tb Second tuple.
* @return {number} -1, 0, or 1 to signify greater than, equality, or less than.
* @private
*/
Blockly.Class.proprocTupleComparator_ = function (ta, tb) {
return ta[0].toLowerCase().localeCompare(tb[0].toLowerCase());
};
/**
* Ensure two identically-named procedures don't exist.
* @param {string} name Proposed procedure name.
* @param {!Blockly.Block} block Block to disambiguate.
* @return {string} Non-colliding name.
*/
Blockly.Class.profindLegalName = function (name, block) {
/*
if (block.isInFlyout) {
// Flyouts can have multiple procedures called 'do something'.
return name;
}
while (!Blockly.Class.proisLegalName(name, block.workspace, block)) {
// Collision with another procedure.
var r = name.match(/^(.*?)(\d+)$/);
if (!r) {
name += '2';
} else {
name = r[1] + (parseInt(r[2], 10) + 1);
}
name = '';
}
*/
return name;
};
/**
* Does this procedure have a legal name? Illegal names include names of
* procedures already defined.
* @param {string} name The questionable name.
* @param {!Blockly.Workspace} workspace The workspace to scan for collisions.
* @param {Blockly.Block=} opt_exclude Optional block to exclude from
* comparisons (one doesn't want to collide with oneself).
* @return {boolean} True if the name is legal.
*/
Blockly.Class.proisLegalName = function (name, workspace, opt_exclude) {
var blocks = workspace.getAllBlocks();
// Iterate through every block and check the name.
for (var i = 0; i < blocks.length; i++) {
if (blocks[i] == opt_exclude) {
continue;
}
if (blocks[i].method_getProcedureDef) {
var procName = blocks[i].method_getProcedureDef();
if (Blockly.Names.equals(procName[0], name)) {
return false;
}
}
}
return true;
};
/**
* Rename a procedure. Called by the editable field.
* @param {string} text The proposed new name.
* @return {string} The accepted name.
* @this {!Blockly.Field}
*/
Blockly.Class.prorename = function (text) {
// Strip leading and trailing whitespace. Beyond this, all names are legal.
text = text.replace(/^[\s\xa0]+|[\s\xa0]+$/g, '');
// Ensure two identically-named procedures don't exist.
text = Blockly.Class.profindLegalName(text, this.sourceBlock_);
// Rename any callers.
var blocks = this.sourceBlock_.workspace.getAllBlocks();
for (var i = 0; i < blocks.length; i++) {
if (blocks[i].method_renameProcedure) {
blocks[i].method_renameProcedure(this.text_, text);
}
}
return text;
};
/**
* Find all the callers of a named procedure.
* @param {string} name Name of procedure.
* @param {!Blockly.Workspace} workspace The workspace to find callers in.
* @return {!Array.<!Blockly.Block>} Array of caller blocks.
*/
Blockly.Class.progetCallers = function (name, workspace) {
var callers = [];
var blocks = workspace.getAllBlocks();
// Iterate through every block and check the name.
for (var i = 0; i < blocks.length; i++) {
if (blocks[i].method_getProcedureCall) {
var procName = blocks[i].method_getProcedureCall();
// Procedure name may be null if the block is only half-built.
if (procName && Blockly.Names.equals(procName, name)) {
callers.push(blocks[i]);
}
}
}
return callers;
};
/**
* When a procedure definition is disposed of, find and dispose of all its
* callers.
* @param {string} name Name of deleted procedure definition.
* @param {!Blockly.Workspace} workspace The workspace to delete callers from.
*/
Blockly.Class.prodisposeCallers = function (name, workspace) {
var callers = Blockly.Class.progetCallers(name, workspace);
for (var i = 0; i < callers.length; i++) {
callers[i].dispose(true, false);
}
};
/**
* When a procedure definition changes its parameters, find and edit all its
* callers.
* @param {!Blockly.Block} defBlock Procedure definition block.
*/
Blockly.Class.mutateCallers = function (defBlock) {
var oldRecordUndo = Blockly.Events.recordUndo;
var name = defBlock.method_getProcedureDef()[0];
var xmlElement = defBlock.mutationToDom(true);
var callers = Blockly.Procedures.getCallers(name, defBlock.workspace);
for (var i = 0, caller; caller = callers[i]; i++) {
var oldMutationDom = caller.mutationToDom();
var oldMutation = oldMutationDom && Blockly.Xml.domToText(oldMutationDom);
caller.domToMutation(xmlElement);
var newMutationDom = caller.mutationToDom();
var newMutation = newMutationDom && Blockly.Xml.domToText(newMutationDom);
if (oldMutation != newMutation) {
// Fire a mutation on every caller block. But don't record this as an
// undo action since it is deterministically tied to the procedure's
// definition mutation.
Blockly.Events.recordUndo = false;
Blockly.Events.fire(new Blockly.Events.BlockChange(
caller, 'mutation', null, oldMutation, newMutation));
Blockly.Events.recordUndo = oldRecordUndo;
}
}
};
/**
* Find the definition block for the named procedure.
* @param {string} name Name of procedure.
* @param {!Blockly.Workspace} workspace The workspace to search.
* @return {Blockly.Block} The procedure definition block, or null not found.
*/
Blockly.Class.progetDefinition = function (name, workspace) {
var blocks = workspace.getAllBlocks();
for (var i = 0; i < blocks.length; i++) {
if (blocks[i].method_getProcedureDef) {
var tuple = blocks[i].method_getProcedureDef();
if (tuple && Blockly.Names.equals(tuple[0], name)) {
return blocks[i];
}
}
}
return null;
};
Blockly.Class.method_flyoutCategory = function (workspace) {
var xmlList = [];
//创建方法
if (Blockly.Blocks['method_procedures_defnoreturn']) {
// <block type="procedures_defnoreturn" gap="16"></block>
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'method_procedures_defnoreturn');
block.setAttribute('gap', 16);
xmlList.push(block);
}
if (Blockly.Blocks['method_procedures_defreturn']) {
// <block type="procedures_defreturn" gap="16"></block>
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'method_procedures_defreturn');
block.setAttribute('gap', 16);
xmlList.push(block);
}
/*
if (Blockly.Blocks['method_procedures_return']) {
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'method_procedures_return');
block.setAttribute('gap', 16);
xmlList.push(block);
}
if (Blockly.Blocks['method_procedures_ifreturn']) {
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'method_procedures_ifreturn');
block.setAttribute('gap', 16);
xmlList.push(block);
}
*/
if (Blockly.Blocks['procedures_return']) {
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'procedures_return');
block.setAttribute('gap', 16);
xmlList.push(block);
}
if (Blockly.Blocks['procedures_ifreturn']) {
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'procedures_ifreturn');
block.setAttribute('gap', 16);
xmlList.push(block);
}
function populateProcedures(procedureList, templateName) {
for (var i = 0; i < procedureList.length; i++) {
var name = procedureList[i][0];
var args = procedureList[i][1];
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', templateName);
block.setAttribute('gap', 16);
var mutation = Blockly.utils.xml.createElement('mutation');
mutation.setAttribute('name', name);
block.appendChild(mutation);
for (var t = 0; t < args.length; t++) {
var arg = Blockly.utils.xml.createElement('arg');
arg.setAttribute('name', args[t]);
mutation.appendChild(arg);
}
xmlList.push(block);
}
}
var tuple = Blockly.Class.proallProcedures(workspace);
populateProcedures(tuple[0], 'method_procedures_callnoreturn');
populateProcedures(tuple[1], 'method_procedures_callreturn');
return xmlList;
};
/**** 对象 ****/
Blockly.Class.allObject = function (root) {
var blocks;
if (root.getDescendants) {
// Root is Block.
blocks = root.getDescendants();
} else if (root.getAllBlocks) {
// Root is Workspace.
blocks = root.getAllBlocks();
} else {
throw 'Not Block or Workspace: ' + root;
}
var variableHash = Object.create(null);
// Iterate through every block and add each variable to the hash.
for (var x = 0; x < blocks.length; x++) {
var blockClass = blocks[x].object_getVars();
for (var y = 0; y < blockClass.length; y++) {
var varName = blockClass[y];
// Variable name may be null if the block is only half-built.
if (varName) {
variableHash[varName.toLowerCase()] = varName;
}
}
}
// Flatten the hash into a list.
var variableList = [];
for (var name in variableHash) {
variableList.push(variableHash[name]);
}
return variableList;
};
Blockly.Class.renameObject = function (oldName, newName, workspace) {
Blockly.Events.setGroup(true);
var blocks = workspace.getAllBlocks();
// Iterate through every block.
for (var i = 0; i < blocks.length; i++) {
blocks[i].object_renameVar(oldName, newName);
}
Blockly.Events.setGroup(false);
};
Blockly.Class.object_generateUniqueName = function (workspace) {
var variableList = Blockly.Class.allObject(workspace);
var newName = '';
if (variableList.length) {
var nameSuffix = 1;
var letters = 'ijkmnopqrstuvwxyzabcdefgh'; // No 'l'.
var letterIndex = 0;
var potName = letters.charAt(letterIndex);
while (!newName) {
var inUse = false;
for (var i = 0; i < variableList.length; i++) {
if (variableList[i].toLowerCase() == potName) {
// This potential name is already used.
inUse = true;
break;
}
}
if (inUse) {
// Try the next potential name.
letterIndex++;
if (letterIndex == letters.length) {
// Reached the end of the character sequence so back to 'i'.
// a new suffix.
letterIndex = 0;
nameSuffix++;
}
potName = letters.charAt(letterIndex);
if (nameSuffix > 1) {
potName += nameSuffix;
}
} else {
// We can use the current potential name.
newName = potName;
}
}
} else {
newName = 'i';
}
return newName;
};
Blockly.Class.object_flyoutCategory = function (workspace) {
var variableList = Blockly.Class.allObject(workspace);
//variableList.sort(goog.string.caseInsensitiveCompare);
var xmlList = [];
//创建对象
if (Blockly.Blocks['object_set']) {
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'object_set');
xmlList.push(block);
}
if (xmlList.length) {
xmlList[xmlList.length - 1].setAttribute('gap', 30);
}
var variableList_class = Blockly.Class.allClass(workspace);
//variableList_class.sort(goog.string.caseInsensitiveCompare);
for (var i = 0; i < variableList_class.length; i++) {
if (Blockly.Blocks['object_set']) {
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'object_set');
if (Blockly.Blocks['object_set']) {
block.setAttribute('gap', 16);
}
var field = Blockly.utils.xml.createElement('field', null, variableList_class[i]);
field.setAttribute('name', 'VAR10');
block.appendChild(field);
xmlList.push(block);
}
}
for (var i = 0; i < variableList.length; i++) {
if (Blockly.Blocks['object_get']) {
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'object_get');
if (Blockly.Blocks['object_get']) {
block.setAttribute('gap', 16);
}
var field = Blockly.utils.xml.createElement('field', null, variableList[i]);
field.setAttribute('name', 'VAR');
block.appendChild(field);
xmlList.push(block);
}
}
return xmlList;
};

View File

@@ -0,0 +1,192 @@
/**
* @license
* Visual Blocks Editor
*
* Copyright 2012 Google Inc.
* https://developers.google.com/blockly/
*
* 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 Utility functions for handling variables and procedure names.
* @author fraser@google.com (Neil Fraser)
*/
import Variables from './variables';
/**
* Class for a database of entity names (variables, functions, etc).
* @param {string} reservedWords A comma-separated string of words that are
* illegal for use as names in a language (e.g. 'new,if,this,...').
* @param {string=} opt_variablePrefix Some languages need a '$' or a namespace
* before all variable names.
* @constructor
*/
class Names {
constructor(reservedWords, opt_variablePrefix) {
this.variablePrefix_ = opt_variablePrefix || '';
this.reservedDict_ = Object.create(null);
if (reservedWords) {
var splitWords = reservedWords.split(',');
for (var i = 0; i < splitWords.length; i++) {
this.reservedDict_[splitWords[i]] = true;
}
}
this.reset();
}
/**
* Do the given two entity names refer to the same entity?
* Blockly names are case-insensitive.
* @param {string} name1 First name.
* @param {string} name2 Second name.
* @return {boolean} True if names are the same.
*/
static equals(name1, name2) {
return name1.toLowerCase() == name2.toLowerCase();
}
/**
* When JavaScript (or most other languages) is generated, variable 'foo' and
* procedure 'foo' would collide. However, Blockly has no such problems since
* variable get 'foo' and procedure call 'foo' are unambiguous.
* Therefore, Blockly keeps a separate type name to disambiguate.
* getName('foo', 'variable') -> 'foo'
* getName('foo', 'procedure') -> 'foo2'
*/
/**
* Empty the database and start from scratch. The reserved words are kept.
*/
reset() {
this.db_ = Object.create(null);
this.dbReverse_ = Object.create(null);
this.variableMap_ = null;
}
/**
* Set the variable map that maps from variable name to variable object.
* @param {!Blockly.VariableMap} map The map to track.
* @package
*/
setVariableMap(map) {
this.variableMap_ = map;
}
/**
* Get the name for a user-defined variable, based on its ID.
* This should only be used for variables of type Variables.NAME_TYPE.
* @param {string} id The ID to look up in the variable map.
* @return {?string} The name of the referenced variable, or null if there was
* no variable map or the variable was not found in the map.
* @private
*/
getNameForUserVariable_(id) {
if (!this.variableMap_) {
/*
console.log('Deprecated call to Names.prototype.getName without ' +
'defining a variable map. To fix, add the folowing code in your ' +
'generator\'s init() function:\n' +
'Blockly.YourGeneratorName.variableDB_.setVariableMap(' +
'workspace.getVariableMap());');
*/
return null;
}
var variable = this.variableMap_.getVariableById(id);
if (variable) {
return variable.name;
}
return null;
}
/**
* Convert a Blockly entity name to a legal exportable entity name.
* @param {string} name The Blockly entity name (no constraints).
* @param {string} type The type of entity in Blockly
* ('VARIABLE', 'PROCEDURE', 'BUILTIN', etc...).
* @return {string} An entity name that is legal in the exported language.
*/
getName(name, type) {
if (type == Variables.NAME_TYPE) {
var varName = this.getNameForUserVariable_(name);
if (varName) {
name = varName;
}
}
var normalized = name.toLowerCase() + '_' + type;
var isVarType = type == Variables.NAME_TYPE ||
type == Names.DEVELOPER_VARIABLE_TYPE;
var prefix = isVarType ? this.variablePrefix_ : '';
if (normalized in this.db_) {
return prefix + this.db_[normalized];
}
var safeName = this.getDistinctName(name, type);
this.db_[normalized] = safeName.substr(prefix.length);
return safeName;
}
/**
* Convert a Blockly entity name to a legal exportable entity name.
* Ensure that this is a new name not overlapping any previously defined name.
* Also check against list of reserved words for the current language and
* ensure name doesn't collide.
* @param {string} name The Blockly entity name (no constraints).
* @param {string} type The type of entity in Blockly
* ('VARIABLE', 'PROCEDURE', 'BUILTIN', etc...).
* @return {string} An entity name that is legal in the exported language.
*/
getDistinctName(name, type) {
var safeName = this.safeName_(name);
var i = '';
while (this.dbReverse_[safeName + i] ||
(safeName + i) in this.reservedDict_) {
// Collision with existing name. Create a unique name.
i = i ? i + 1 : 2;
}
safeName += i;
this.dbReverse_[safeName] = true;
var isVarType = type == Variables.NAME_TYPE ||
type == Names.DEVELOPER_VARIABLE_TYPE;
var prefix = isVarType ? this.variablePrefix_ : '';
return prefix + safeName;
}
/**
* Given a proposed entity name, generate a name that conforms to the
* [_A-Za-z][_A-Za-z0-9]* format that most languages consider legal for
* variables.
* @param {string} name Potentially illegal entity name.
* @return {string} Safe entity name.
* @private
*/
safeName_(name) {
if (!name) {
name = 'unnamed';
} else {
// Unfortunately names in non-latin characters will look like
// _E9_9F_B3_E4_B9_90 which is pretty meaningless.
// https://github.com/google/blockly/issues/1654
name = encodeURI(name.replace(/ /g, '_')).replace(/[^,\w]/g, '_');
// Most languages don't allow names with leading numbers.
if ('0123456789'.indexOf(name[0]) != -1) {
name = 'my_' + name;
}
}
return name;
}
}
/**
* Constant to separate developer variable names from user-defined variable
* names when running generators.
* A developer variable will be declared as a global in the generated code, but
* will never be shown to the user in the workspace or stored in the variable
* map.
*/
Names.DEVELOPER_VARIABLE_TYPE = 'DEVELOPER_VARIABLE';
export default Names;

View File

@@ -0,0 +1,327 @@
/**
* @license
* Copyright 2012 Google LLC
*
* 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 Utility functions for handling procedures.
* @author fraser@google.com (Neil Fraser)
*/
import * as Blockly from 'blockly/core';
const Procedures = {};
/**
* Constant to separate procedure names from variables and generated functions
* when running generators.
* @deprecated Use Blockly.PROCEDURE_CATEGORY_NAME
*/
Procedures.NAME_TYPE = Blockly.PROCEDURE_CATEGORY_NAME;
/**
* Find all user-created procedure definitions in a workspace.
* @param {!Blockly.Workspace} root Root workspace.
* @return {!Array.<!Array.<!Array>>} Pair of arrays, the
* first contains procedures without return variables, the second with.
* Each procedure is defined by a three-element list of name, parameter
* list, and return value boolean.
*/
Procedures.allProcedures = function (root) {
var blocks = root.getAllBlocks(false);
var proceduresReturn = [];
var proceduresNoReturn = [];
for (var i = 0; i < blocks.length; i++) {
if (blocks[i].getProcedureDef) {
var tuple = blocks[i].getProcedureDef();
if (tuple) {
if (tuple[2]) {
proceduresReturn.push(tuple);
} else {
proceduresNoReturn.push(tuple);
}
}
}
}
proceduresNoReturn.sort(Procedures.procTupleComparator_);
proceduresReturn.sort(Procedures.procTupleComparator_);
return [proceduresNoReturn, proceduresReturn];
};
/**
* Comparison function for case-insensitive sorting of the first element of
* a tuple.
* @param {!Array} ta First tuple.
* @param {!Array} tb Second tuple.
* @return {number} -1, 0, or 1 to signify greater than, equality, or less than.
* @private
*/
Procedures.procTupleComparator_ = function (ta, tb) {
return ta[0].toLowerCase().localeCompare(tb[0].toLowerCase());
};
/**
* Ensure two identically-named procedures don't exist.
* Take the proposed procedure name, and return a legal name i.e. one that
* is not empty and doesn't collide with other procedures.
* @param {string} name Proposed procedure name.
* @param {!Blockly.Block} block Block to disambiguate.
* @return {string} Non-colliding name.
*/
Procedures.findLegalName = function (name, block) {
if (block.isInFlyout) {
// Flyouts can have multiple procedures called 'do something'.
return name;
}
name = name || Blockly.Msg['UNNAMED_KEY'] || 'unnamed';
while (!Procedures.isLegalName_(name, block.workspace, block)) {
// Collision with another procedure.
var r = name.match(/^(.*?)(\d+)$/);
if (!r) {
name += '2';
} else {
name = r[1] + (parseInt(r[2], 10) + 1);
}
}
return name;
};
/**
* Does this procedure have a legal name? Illegal names include names of
* procedures already defined.
* @param {string} name The questionable name.
* @param {!Blockly.Workspace} workspace The workspace to scan for collisions.
* @param {Blockly.Block=} opt_exclude Optional block to exclude from
* comparisons (one doesn't want to collide with oneself).
* @return {boolean} True if the name is legal.
* @private
*/
Procedures.isLegalName_ = function (name, workspace, opt_exclude) {
return !Procedures.isNameUsed(name, workspace, opt_exclude);
};
/**
* Return if the given name is already a procedure name.
* @param {string} name The questionable name.
* @param {!Blockly.Workspace} workspace The workspace to scan for collisions.
* @param {Blockly.Block=} opt_exclude Optional block to exclude from
* comparisons (one doesn't want to collide with oneself).
* @return {boolean} True if the name is used, otherwise return false.
*/
Procedures.isNameUsed = function (name, workspace, opt_exclude) {
var blocks = workspace.getAllBlocks(false);
// Iterate through every block and check the name.
for (var i = 0; i < blocks.length; i++) {
if (blocks[i] == opt_exclude) {
continue;
}
if (blocks[i].getProcedureDef) {
var procName = blocks[i].getProcedureDef();
if (Blockly.Names.equals(procName[0], name)) {
return true;
}
}
}
return false;
};
/**
* Rename a procedure. Called by the editable field.
* @param {string} name The proposed new name.
* @return {string} The accepted name.
* @this {Blockly.Field}
*/
Procedures.rename = function (name) {
// Strip leading and trailing whitespace. Beyond this, all names are legal.
name = name.trim();
var legalName = Procedures.findLegalName(name, this.getSourceBlock());
var oldName = this.getValue();
if (oldName != name && oldName != legalName) {
// Rename any callers.
var blocks = this.getSourceBlock().workspace.getAllBlocks(false);
for (var i = 0; i < blocks.length; i++) {
if (blocks[i].renameProcedure) {
blocks[i].renameProcedure(oldName, legalName);
}
}
}
return legalName;
};
/**
* Construct the blocks required by the flyout for the procedure category.
* @param {!Blockly.Workspace} workspace The workspace containing procedures.
* @return {!Array.<!Element>} Array of XML block elements.
*/
Procedures.flyoutCategory = function (workspace) {
var xmlList = [];
if (Blockly.Blocks['procedures_defnoreturn']) {
// <block type="procedures_defnoreturn" gap="16">
// <field name="NAME">do something</field>
// </block>
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'procedures_defnoreturn');
block.setAttribute('gap', 16);
var nameField = Blockly.utils.xml.createElement('field');
nameField.setAttribute('name', 'NAME');
nameField.appendChild(Blockly.utils.xml.createTextNode(
Blockly.Msg['PROCEDURES_DEFNORETURN_PROCEDURE']));
block.appendChild(nameField);
xmlList.push(block);
}
if (Blockly.Blocks['procedures_defreturn']) {
// <block type="procedures_defreturn" gap="16">
// <field name="NAME">do something</field>
// </block>
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'procedures_defreturn');
block.setAttribute('gap', 16);
var nameField = Blockly.utils.xml.createElement('field');
nameField.setAttribute('name', 'NAME');
nameField.appendChild(Blockly.utils.xml.createTextNode(
Blockly.Msg['PROCEDURES_DEFRETURN_PROCEDURE']));
block.appendChild(nameField);
xmlList.push(block);
}
if (Blockly.Blocks['procedures_return']) {
// <block type="procedures_return" gap="16"></block>
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'procedures_return');
block.setAttribute('gap', 16);
xmlList.push(block);
}
if (Blockly.Blocks['procedures_ifreturn']) {
// <block type="procedures_ifreturn" gap="16"></block>
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'procedures_ifreturn');
block.setAttribute('gap', 16);
xmlList.push(block);
}
if (xmlList.length) {
// Add slightly larger gap between system blocks and user calls.
xmlList[xmlList.length - 1].setAttribute('gap', 24);
}
function populateProcedures(procedureList, templateName) {
for (var i = 0; i < procedureList.length; i++) {
var name = procedureList[i][0];
var args = procedureList[i][1];
// <block type="procedures_callnoreturn" gap="16">
// <mutation name="do something">
// <arg name="x"></arg>
// </mutation>
// </block>
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', templateName);
block.setAttribute('gap', 16);
var mutation = Blockly.utils.xml.createElement('mutation');
mutation.setAttribute('name', name);
block.appendChild(mutation);
for (var j = 0; j < args.length; j++) {
var arg = Blockly.utils.xml.createElement('arg');
arg.setAttribute('name', args[j]);
mutation.appendChild(arg);
}
xmlList.push(block);
}
}
var tuple = Procedures.allProcedures(workspace);
populateProcedures(tuple[0], 'procedures_callnoreturn');
populateProcedures(tuple[1], 'procedures_callreturn');
return xmlList;
};
/**
* Find all the callers of a named procedure.
* @param {string} name Name of procedure.
* @param {!Blockly.Workspace} workspace The workspace to find callers in.
* @return {!Array.<!Blockly.Block>} Array of caller blocks.
*/
Procedures.getCallers = function (name, workspace) {
var callers = [];
var blocks = workspace.getAllBlocks(false);
// Iterate through every block and check the name.
for (var i = 0; i < blocks.length; i++) {
if (blocks[i].getProcedureCall) {
var procName = blocks[i].getProcedureCall();
// Procedure name may be null if the block is only half-built.
if (procName && Blockly.Names.equals(procName, name)) {
callers.push(blocks[i]);
}
}
}
return callers;
};
/**
* When a procedure definition changes its parameters, find and edit all its
* callers.
* @param {!Blockly.Block} defBlock Procedure definition block.
*/
Procedures.mutateCallers = function (defBlock) {
const oldRecordUndo = Blockly.Events.getRecordUndo();
const procedureBlock = defBlock;
const name = procedureBlock.getProcedureDef()[0];
const xmlElement = defBlock.mutationToDom(true);
const callers = Blockly.Procedures.getCallers(name, defBlock.workspace);
for (let i = 0, caller; (caller = callers[i]); i++) {
const oldMutationDom = caller.mutationToDom();
const oldMutation = oldMutationDom && Blockly.utils.xml.domToText(oldMutationDom);
if (caller.domToMutation) {
caller.domToMutation(xmlElement);
}
const newMutationDom = caller.mutationToDom();
const newMutation = newMutationDom && Blockly.utils.xml.domToText(newMutationDom);
if (oldMutation !== newMutation) {
// Fire a mutation on every caller block. But don't record this as an
// undo action since it is deterministically tied to the procedure's
// definition mutation.
Blockly.Events.setRecordUndo(false);
Blockly.Events.fire(
new (Blockly.Events.get(Blockly.Events.BLOCK_CHANGE))(
caller,
'mutation',
null,
oldMutation,
newMutation,
),
);
Blockly.Events.setRecordUndo(oldRecordUndo);
}
}
};
/**
* Find the definition block for the named procedure.
* @param {string} name Name of procedure.
* @param {!Blockly.Workspace} workspace The workspace to search.
* @return {Blockly.Block} The procedure definition block, or null not found.
*/
Procedures.getDefinition = function (name, workspace) {
// Assume that a procedure definition is a top block.
var blocks = workspace.getTopBlocks(false);
for (var i = 0; i < blocks.length; i++) {
if (blocks[i].getProcedureDef) {
var tuple = blocks[i].getProcedureDef();
if (tuple && Blockly.Names.equals(tuple[0], name)) {
return blocks[i];
}
}
}
return null;
};
export default Procedures;

View File

@@ -0,0 +1,221 @@
/**
* @license
* Visual Blocks Editor
*
* Copyright 2012 Google Inc.
* https://developers.google.com/blockly/
*
* 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 Utility functions for handling variables.
* @author fraser@google.com (Neil Fraser)
*/
import * as Blockly from 'blockly/core';
const Variables = {};
/**
* Category to separate variable names from procedures and generated functions.
*/
Variables.NAME_TYPE = 'VARIABLE';
/**
* Find all user-created variables.
* @param {!Blockly.Block|!Blockly.Workspace} root Root block or workspace.
* @return {!Array.<string>} Array of variable names.
*/
Variables.allVariables = function (root) {
var blocks;
if (root.getDescendants) {
// Root is Block.
blocks = root.getDescendants();
} else if (root.getAllBlocks) {
// Root is Workspace.
blocks = root.getAllBlocks();
} else {
throw 'Not Block or Workspace: ' + root;
}
var variableHash = Object.create(null);
// Iterate through every block and add each variable to the hash.
for (var x = 0; x < blocks.length; x++) {
var blockVariables = blocks[x].getVars();
for (var y = 0; y < blockVariables.length; y++) {
var varName = blockVariables[y];
// Variable name may be null if the block is only half-built.
if (varName) {
variableHash[varName.toLowerCase()] = varName;
}
}
}
// Flatten the hash into a list.
var variableList = [];
for (var name in variableHash) {
variableList.push(variableHash[name]);
}
return variableList;
};
/**
* Find all instances of the specified variable and rename them.
* @param {string} oldName Variable to rename.
* @param {string} newName New variable name.
* @param {!Blockly.Workspace} workspace Workspace rename variables in.
*/
Variables.renameVariable = function (oldName, newName, workspace) {
Blockly.Events.setGroup(true);
var blocks = workspace.getAllBlocks();
// Iterate through every block.
for (var i = 0; i < blocks.length; i++) {
blocks[i].renameVar(oldName, newName);
}
Blockly.Events.setGroup(false);
};
/**
* Construct the blocks required by the flyout for the variable category.
* @param {!Blockly.Workspace} workspace The workspace contianing variables.
* @return {!Array.<!Element>} Array of XML block elements.
*/
Variables.flyoutCategory = function (workspace) {
var variableList = Variables.allVariables(workspace);
//variableList.sort(goog.string.caseInsensitiveCompare);
// In addition to the user's variables, we also want to display the default
// variable name at the top. We also don't want this duplicated if the
// user has created a variable of the same name.
// alert(variableList)
// goog.array.remove(variableList, Blockly.Msg.VARIABLES_DEFAULT_NAME);
// variableList.unshift(Blockly.Msg.VARIABLES_DEFAULT_NAME);
var xmlList = [];
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'variables_global');
xmlList.push(block);
if (Blockly.Blocks['variables_set']) {
//增加variables_declare模块
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'variables_set');
xmlList.push(block);
}//change tyep
/*
if (Blockly.Blocks['variables_change']) {
//增加variables_declare模块
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'variables_change');
xmlList.push(block);
}*/
if (Blockly.Blocks['variables_change']) {
//增加variables_declare模块
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'variables_change');
xmlList.push(block);
}
if (Blockly.Blocks['controls_type']) {
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'controls_type');
xmlList.push(block);
}
if (Blockly.Blocks['controls_typeLists']) {
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'controls_typeLists');
xmlList.push(block);
}
for (var i = 0; i < variableList.length; i++) {
// alert(variableList)
// if(i==0&& !(Blockly.Python.setups_['variables_set'+''])){
// continue;
// }
if (Blockly.Blocks['variables_set']) {
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'variables_set');
if (Blockly.Blocks['variables_get']) {
block.setAttribute('gap', 8);
}
var field = Blockly.utils.xml.createElement('field', null, variableList[i]);
field.setAttribute('name', 'VAR');
var name = Blockly.utils.xml.createTextNode(variableList[i]);
field.appendChild(name);
block.appendChild(field);
xmlList.push(block);
}
if (Blockly.Blocks['variables_get']) {
var block = Blockly.utils.xml.createElement('block');
block.setAttribute('type', 'variables_get');
if (Blockly.Blocks['variables_set']) {
block.setAttribute('gap', 24);
}
var field = Blockly.utils.xml.createElement('field', null, variableList[i]);
field.setAttribute('name', 'VAR');
var name = Blockly.utils.xml.createTextNode(variableList[i]);
field.appendChild(name);
block.appendChild(field);
xmlList.push(block);
}
}
return xmlList;
};
/**
* Return a new variable name that is not yet being used. This will try to
* generate single letter variable names in the range 'i' to 'z' to start with.
* If no unique name is located it will try 'i' to 'z', 'a' to 'h',
* then 'i2' to 'z2' etc. Skip 'l'.
* @param {!Blockly.Workspace} workspace The workspace to be unique in.
* @return {string} New variable name.
*/
Variables.generateUniqueName = function (workspace) {
var variableList = Variables.allVariables(workspace);
var newName = '';
if (variableList.length) {
var nameSuffix = 1;
var letters = 'ijkmnopqrstuvwxyzabcdefgh'; // No 'l'.
var letterIndex = 0;
var potName = letters.charAt(letterIndex);
while (!newName) {
var inUse = false;
for (var i = 0; i < variableList.length; i++) {
if (variableList[i].toLowerCase() == potName) {
// This potential name is already used.
inUse = true;
break;
}
}
if (inUse) {
// Try the next potential name.
letterIndex++;
if (letterIndex == letters.length) {
// Reached the end of the character sequence so back to 'i'.
// a new suffix.
letterIndex = 0;
nameSuffix++;
}
potName = letters.charAt(letterIndex);
if (nameSuffix > 1) {
potName += nameSuffix;
}
} else {
// We can use the current potential name.
newName = potName;
}
}
} else {
newName = 'i';
}
return newName;
};
export default Variables;