· 8 years ago · Aug 02, 2018, 01:38 PM
1/**
2 * @license
3 * Visual Blocks Editor
4 *
5 * Copyright 2011 Google Inc.
6 * https://developers.google.com/blockly/
7 *
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 */
20
21/**
22 * @fileoverview The class representing one block.
23 * @author fraser@google.com (Neil Fraser)
24 */
25'use strict';
26
27goog.provide('Blockly.Block');
28
29goog.require('Blockly.Blocks');
30goog.require('Blockly.Colours');
31goog.require('Blockly.Comment');
32goog.require('Blockly.ScratchBlockComment');
33goog.require('Blockly.Connection');
34goog.require('Blockly.Events.BlockChange');
35goog.require('Blockly.Events.BlockCreate');
36goog.require('Blockly.Events.BlockDelete');
37goog.require('Blockly.Events.BlockMove');
38goog.require('Blockly.Extensions');
39goog.require('Blockly.FieldLabelSerializable');
40goog.require('Blockly.FieldVariableGetter');
41goog.require('Blockly.Input');
42goog.require('Blockly.Mutator');
43goog.require('Blockly.Warning');
44goog.require('Blockly.Workspace');
45goog.require('Blockly.Xml');
46goog.require('goog.array');
47goog.require('goog.asserts');
48goog.require('goog.math.Coordinate');
49goog.require('goog.string');
50
51
52/**
53 * Class for one block.
54 * Not normally called directly, workspace.newBlock() is preferred.
55 * @param {!Blockly.Workspace} workspace The block's workspace.
56 * @param {?string} prototypeName Name of the language object containing
57 * type-specific functions for this block.
58 * @param {string=} opt_id Optional ID. Use this ID if provided, otherwise
59 * create a new ID. If the ID conflicts with an in-use ID, a new one will
60 * be generated.
61 * @constructor
62 */
63Blockly.Block = function(workspace, prototypeName, opt_id) {
64 var flyoutWorkspace = workspace && workspace.getFlyout && workspace.getFlyout() ?
65 workspace.getFlyout().getWorkspace() : null;
66 /** @type {string} */
67 this.id = (opt_id && !workspace.getBlockById(opt_id) &&
68 (!flyoutWorkspace || !flyoutWorkspace.getBlockById(opt_id))) ?
69 opt_id : Blockly.utils.genUid();
70 workspace.blockDB_[this.id] = this;
71 /** @type {Blockly.Connection} */
72 this.outputConnection = null;
73 /** @type {Blockly.Connection} */
74 this.nextConnection = null;
75 /** @type {Blockly.Connection} */
76 this.previousConnection = null;
77 /** @type {!Array.<!Blockly.Input>} */
78 this.inputList = [];
79 /** @type {boolean|undefined} */
80 this.inputsInline = true;
81 /** @type {boolean} */
82 this.disabled = false;
83 /** @type {string|!Function} */
84 this.tooltip = '';
85 /** @type {boolean} */
86 this.contextMenu = true;
87
88 /**
89 * @type {Blockly.Block}
90 * @protected
91 */
92 this.parentBlock_ = null;
93
94 /**
95 * @type {!Array.<!Blockly.Block>}
96 * @protected
97 */
98 this.childBlocks_ = [];
99
100 /**
101 * @type {boolean}
102 * @private
103 */
104 this.deletable_ = false;
105
106 /**
107 * @type {boolean}
108 * @private
109 */
110 this.movable_ = true;
111
112 /**
113 * @type {boolean}
114 * @private
115 */
116 this.editable_ = true;
117
118 /**
119 * @type {boolean}
120 * @private
121 */
122 this.isShadow_ = false;
123
124 /**
125 * @type {boolean}
126 * @protected
127 */
128 this.collapsed_ = false;
129
130 /**
131 * @type {boolean}
132 * @private
133 */
134 this.checkboxInFlyout_ = false;
135
136 /** @type {string|Blockly.Comment} */
137 this.comment = null;
138
139 /**
140 * @type {?number}
141 * @private
142 */
143 this.outputShape_ = null;
144
145 /**
146 * @type {?string}
147 * @private
148 */
149 this.category_ = null;
150
151 /**
152 * The block's position in workspace units. (0, 0) is at the workspace's
153 * origin; scale does not change this value.
154 * @type {!goog.math.Coordinate}
155 * @private
156 */
157 this.xy_ = new goog.math.Coordinate(0, 0);
158
159 /** @type {!Blockly.Workspace} */
160 this.workspace = workspace;
161 /** @type {boolean} */
162 this.isInFlyout = workspace.isFlyout;
163 /** @type {boolean} */
164 this.isInMutator = workspace.isMutator;
165
166 /** @type {boolean} */
167 this.RTL = workspace.RTL;
168
169 /** @type {boolean} */
170 this.isInsertionMarker_ = false;
171
172 // Copy the type-specific functions and data from the prototype.
173 if (prototypeName) {
174 /** @type {string} */
175 this.type = prototypeName;
176 var prototype = Blockly.Blocks[prototypeName];
177 goog.asserts.assertObject(prototype,
178 'Error: Unknown block type "%s".', prototypeName);
179 goog.mixin(this, prototype);
180 }
181
182 workspace.addTopBlock(this);
183
184 // Call an initialization function, if it exists.
185 if (goog.isFunction(this.init)) {
186 this.init();
187 }
188 // Record initial inline state.
189 /** @type {boolean|undefined} */
190 this.inputsInlineDefault = this.inputsInline;
191
192 // Fire a create event.
193 if (Blockly.Events.isEnabled()) {
194 var existingGroup = Blockly.Events.getGroup();
195 if (!existingGroup) {
196 Blockly.Events.setGroup(true);
197 }
198 try {
199 Blockly.Events.fire(new Blockly.Events.BlockCreate(this));
200 } finally {
201 if (!existingGroup) {
202 Blockly.Events.setGroup(false);
203 }
204 }
205
206 }
207 // Bind an onchange function, if it exists.
208 if (goog.isFunction(this.onchange)) {
209 this.setOnChange(this.onchange);
210 }
211};
212
213/**
214 * Optional text data that round-trips beween blocks and XML.
215 * Has no effect. May be used by 3rd parties for meta information.
216 * @type {?string}
217 */
218Blockly.Block.prototype.data = null;
219
220/**
221 * Colour of the block in '#RRGGBB' format.
222 * @type {string}
223 * @private
224 */
225Blockly.Block.prototype.colour_ = '#FF0000';
226
227/**
228 * Secondary colour of the block in '#RRGGBB' format.
229 * @type {string}
230 * @private
231 */
232Blockly.Block.prototype.colourSecondary_ = '#FF0000';
233
234/**
235 * Tertiary colour of the block in '#RRGGBB' format.
236 * @type {string}
237 * @private
238 */
239Blockly.Block.prototype.colourTertiary_ = '#FF0000';
240
241/**
242 * Dispose of this block.
243 * @param {boolean} healStack If true, then try to heal any gap by connecting
244 * the next statement with the previous statement. Otherwise, dispose of
245 * all children of this block.
246 */
247Blockly.Block.prototype.dispose = function(healStack) {
248 if (!this.workspace) {
249 // Already deleted.
250 return;
251 }
252 // Terminate onchange event calls.
253 if (this.onchangeWrapper_) {
254 this.workspace.removeChangeListener(this.onchangeWrapper_);
255 }
256 this.unplug(healStack);
257 if (Blockly.Events.isEnabled()) {
258 Blockly.Events.fire(new Blockly.Events.BlockDelete(this));
259 }
260 Blockly.Events.disable();
261
262 try {
263 // This block is now at the top of the workspace.
264 // Remove this block from the workspace's list of top-most blocks.
265 if (this.workspace) {
266 this.workspace.removeTopBlock(this);
267 // Remove from block database.
268 delete this.workspace.blockDB_[this.id];
269 this.workspace = null;
270 }
271
272 // Just deleting this block from the DOM would result in a memory leak as
273 // well as corruption of the connection database. Therefore we must
274 // methodically step through the blocks and carefully disassemble them.
275
276 if (Blockly.selected == this) {
277 Blockly.selected = null;
278 }
279
280 // First, dispose of all my children.
281 for (var i = this.childBlocks_.length - 1; i >= 0; i--) {
282 this.childBlocks_[i].dispose(false);
283 }
284 // Then dispose of myself.
285 // Dispose of all inputs and their fields.
286 for (var i = 0, input; input = this.inputList[i]; i++) {
287 input.dispose();
288 }
289 this.inputList.length = 0;
290 // Dispose of any remaining connections (next/previous/output).
291 var connections = this.getConnections_(true);
292 for (var i = 0; i < connections.length; i++) {
293 var connection = connections[i];
294 if (connection.isConnected()) {
295 connection.disconnect();
296 }
297 connections[i].dispose();
298 }
299 } finally {
300 Blockly.Events.enable();
301 }
302};
303
304/**
305 * Call initModel on all fields on the block.
306 * May be called more than once.
307 * Either initModel or initSvg must be called after creating a block and before
308 * the first interaction with it. Interactions include UI actions
309 * (e.g. clicking and dragging) and firing events (e.g. create, delete, and
310 * change).
311 * @public
312 */
313Blockly.Block.prototype.initModel = function() {
314 for (var i = 0, input; input = this.inputList[i]; i++) {
315 for (var j = 0, field; field = input.fieldRow[j]; j++) {
316 if (field.initModel) {
317 field.initModel();
318 }
319 }
320 }
321};
322
323/**
324 * Unplug this block from its superior block. If this block is a statement,
325 * optionally reconnect the block underneath with the block on top.
326 * @param {boolean=} opt_healStack Disconnect child statement and reconnect
327 * stack. Defaults to false.
328 */
329Blockly.Block.prototype.unplug = function(opt_healStack) {
330 if (this.outputConnection) {
331 if (this.outputConnection.isConnected()) {
332 // Disconnect from any superior block.
333 this.outputConnection.disconnect();
334 }
335 } else if (this.previousConnection) {
336 var previousTarget = null;
337 if (this.previousConnection.isConnected()) {
338 // Remember the connection that any next statements need to connect to.
339 previousTarget = this.previousConnection.targetConnection;
340 // Detach this block from the parent's tree.
341 this.previousConnection.disconnect();
342 }
343 var nextBlock = this.getNextBlock();
344 if (opt_healStack && nextBlock) {
345 // Disconnect the next statement.
346 var nextTarget = this.nextConnection.targetConnection;
347 nextTarget.disconnect();
348 if (previousTarget && previousTarget.checkType_(nextTarget)) {
349 // Attach the next statement to the previous statement.
350 previousTarget.connect(nextTarget);
351 }
352 }
353 }
354};
355
356/**
357 * Returns all connections originating from this block.
358 * @return {!Array.<!Blockly.Connection>} Array of connections.
359 * @private
360 */
361Blockly.Block.prototype.getConnections_ = function() {
362 var myConnections = [];
363 if (this.outputConnection) {
364 myConnections.push(this.outputConnection);
365 }
366 if (this.previousConnection) {
367 myConnections.push(this.previousConnection);
368 }
369 if (this.nextConnection) {
370 myConnections.push(this.nextConnection);
371 }
372 for (var i = 0, input; input = this.inputList[i]; i++) {
373 if (input.connection) {
374 myConnections.push(input.connection);
375 }
376 }
377 return myConnections;
378};
379
380/**
381 * Walks down a stack of blocks and finds the last next connection on the stack.
382 * @return {Blockly.Connection} The last next connection on the stack, or null.
383 * @package
384 */
385Blockly.Block.prototype.lastConnectionInStack = function() {
386 var nextConnection = this.nextConnection;
387 while (nextConnection) {
388 var nextBlock = nextConnection.targetBlock();
389 if (!nextBlock) {
390 // Found a next connection with nothing on the other side.
391 return nextConnection;
392 }
393 nextConnection = nextBlock.nextConnection;
394 }
395 // Ran out of next connections.
396 return null;
397};
398
399/**
400 * Bump unconnected blocks out of alignment. Two blocks which aren't actually
401 * connected should not coincidentally line up on screen.
402 * @protected
403 */
404Blockly.Block.prototype.bumpNeighbours_ = function() {
405 console.warn('Not expected to reach this bumpNeighbours_ function. The ' +
406 'BlockSvg function for bumpNeighbours_ was expected to be called instead.');
407};
408
409/**
410 * Return the parent block or null if this block is at the top level.
411 * @return {Blockly.Block} The block that holds the current block.
412 */
413Blockly.Block.prototype.getParent = function() {
414 // Look at the DOM to see if we are nested in another block.
415 return this.parentBlock_;
416};
417
418/**
419 * Return the input that connects to the specified block.
420 * @param {!Blockly.Block} block A block connected to an input on this block.
421 * @return {Blockly.Input} The input that connects to the specified block.
422 */
423Blockly.Block.prototype.getInputWithBlock = function(block) {
424 for (var i = 0, input; input = this.inputList[i]; i++) {
425 if (input.connection && input.connection.targetBlock() == block) {
426 return input;
427 }
428 }
429 return null;
430};
431
432/**
433 * Return the input that contains the specified connection
434 * @param {!Blockly.Connection} conn A connection on this block.
435 * @return {Blockly.Input} The input that contains the specified connection.
436 */
437Blockly.Block.prototype.getInputWithConnection = function(conn) {
438 for (var i = 0, input; input = this.inputList[i]; i++) {
439 if (input.connection == conn) {
440 return input;
441 }
442 }
443 return null;
444};
445
446/**
447 * Return the parent block that surrounds the current block, or null if this
448 * block has no surrounding block. A parent block might just be the previous
449 * statement, whereas the surrounding block is an if statement, while loop, etc.
450 * @return {Blockly.Block} The block that surrounds the current block.
451 */
452Blockly.Block.prototype.getSurroundParent = function() {
453 var block = this;
454 do {
455 var prevBlock = block;
456 block = block.getParent();
457 if (!block) {
458 // Ran off the top.
459 return null;
460 }
461 } while (block.getNextBlock() == prevBlock);
462 // This block is an enclosing parent, not just a statement in a stack.
463 return block;
464};
465
466/**
467 * Return the next statement block directly connected to this block.
468 * @return {Blockly.Block} The next statement block or null.
469 */
470Blockly.Block.prototype.getNextBlock = function() {
471 return this.nextConnection && this.nextConnection.targetBlock();
472};
473
474/**
475 * Return the previous statement block directly connected to this block.
476 * @return {Blockly.Block} The previous statement block or null.
477 */
478Blockly.Block.prototype.getPreviousBlock = function() {
479 return this.previousConnection && this.previousConnection.targetBlock();
480};
481
482/**
483 * Return the connection on the first statement input on this block, or null if
484 * there are none.
485 * @return {Blockly.Connection} The first statement connection or null.
486 */
487Blockly.Block.prototype.getFirstStatementConnection = function() {
488 for (var i = 0, input; input = this.inputList[i]; i++) {
489 if (input.connection && input.connection.type == Blockly.NEXT_STATEMENT) {
490 return input.connection;
491 }
492 }
493 return null;
494};
495
496/**
497 * Return the top-most block in this block's tree.
498 * This will return itself if this block is at the top level.
499 * @return {!Blockly.Block} The root block.
500 */
501Blockly.Block.prototype.getRootBlock = function() {
502 var rootBlock;
503 var block = this;
504 do {
505 rootBlock = block;
506 block = rootBlock.parentBlock_;
507 } while (block);
508 return rootBlock;
509};
510
511/**
512 * Find all the blocks that are directly nested inside this one.
513 * Includes value and statement inputs, as well as any following statement.
514 * Excludes any connection on an output tab or any preceding statement.
515 * Blocks are optionally sorted by position; top to bottom.
516 * @param {boolean} ordered Sort the list if true.
517 * @return {!Array.<!Blockly.Block>} Array of blocks.
518 */
519Blockly.Block.prototype.getChildren = function(ordered) {
520 if (!ordered) {
521 return this.childBlocks_;
522 }
523 var blocks = [];
524 for (var i = 0, input; input = this.inputList[i]; i++) {
525 if (input.connection) {
526 var child = input.connection.targetBlock();
527 if (child) {
528 blocks.push(child);
529 }
530 }
531 }
532 var next = this.getNextBlock();
533 if (next) {
534 blocks.push(next);
535 }
536 return blocks;
537};
538
539/**
540 * Set parent of this block to be a new block or null.
541 * @param {Blockly.Block} newParent New parent block.
542 */
543Blockly.Block.prototype.setParent = function(newParent) {
544 if (newParent == this.parentBlock_) {
545 return;
546 }
547 if (this.parentBlock_) {
548 // Remove this block from the old parent's child list.
549 goog.array.remove(this.parentBlock_.childBlocks_, this);
550
551 // Disconnect from superior blocks.
552 if (this.previousConnection && this.previousConnection.isConnected()) {
553 throw 'Still connected to previous block.';
554 }
555 if (this.outputConnection && this.outputConnection.isConnected()) {
556 throw 'Still connected to parent block.';
557 }
558 this.parentBlock_ = null;
559 // This block hasn't actually moved on-screen, so there's no need to update
560 // its connection locations.
561 } else {
562 // Remove this block from the workspace's list of top-most blocks.
563 this.workspace.removeTopBlock(this);
564 }
565
566 this.parentBlock_ = newParent;
567 if (newParent) {
568 // Add this block to the new parent's child list.
569 newParent.childBlocks_.push(this);
570 } else {
571 this.workspace.addTopBlock(this);
572 }
573};
574
575/**
576 * Find all the blocks that are directly or indirectly nested inside this one.
577 * Includes this block in the list.
578 * Includes value and statement inputs, as well as any following statements.
579 * Excludes any connection on an output tab or any preceding statements.
580 * Blocks are optionally sorted by position, top to bottom.
581 * @param {boolean} ordered Sort the list if true.
582 * @param {boolean=} opt_ignoreShadows If set, don't include shadow blocks.
583 * @return {!Array.<!Blockly.Block>} Flattened array of blocks.
584 */
585Blockly.Block.prototype.getDescendants = function(ordered, opt_ignoreShadows) {
586 var blocks = [this];
587 var childBlocks = this.getChildren(ordered);
588 for (var child, i = 0; child = childBlocks[i]; i++) {
589 if (!opt_ignoreShadows || !child.isShadow_) {
590 blocks.push.apply(
591 blocks, child.getDescendants(ordered, opt_ignoreShadows));
592 }
593 }
594 return blocks;
595};
596
597/**
598 * Get whether this block is deletable or not.
599 * @return {boolean} True if deletable.
600 */
601Blockly.Block.prototype.isDeletable = function() {
602 return this.deletable_ && !this.isShadow_ &&
603 !(this.workspace && this.workspace.options.readOnly);
604};
605
606/**
607 * Set whether this block is deletable or not.
608 * @param {boolean} deletable True if deletable.
609 */
610Blockly.Block.prototype.setDeletable = function(deletable) {
611 this.deletable_ = deletable;
612};
613
614/**
615 * Get whether this block is movable or not.
616 * @return {boolean} True if movable.
617 */
618Blockly.Block.prototype.isMovable = function() {
619 return this.movable_ && !this.isShadow_ &&
620 !(this.workspace && this.workspace.options.readOnly);
621};
622
623/**
624 * Set whether this block is movable or not.
625 * @param {boolean} movable True if movable.
626 */
627Blockly.Block.prototype.setMovable = function(movable) {
628 this.movable_ = movable;
629};
630
631/**
632 * Get whether this block is a shadow block or not.
633 * @return {boolean} True if a shadow.
634 */
635Blockly.Block.prototype.isShadow = function() {
636 return this.isShadow_;
637};
638
639/**
640 * Set whether this block is a shadow block or not.
641 * @param {boolean} shadow True if a shadow.
642 */
643Blockly.Block.prototype.setShadow = function(shadow) {
644 this.isShadow_ = shadow;
645};
646
647/**
648 * Get whether this block is an insertion marker block or not.
649 * @return {boolean} True if an insertion marker.
650 */
651Blockly.Block.prototype.isInsertionMarker = function() {
652 return this.isInsertionMarker_;
653};
654
655/**
656 * Set whether this block is an insertion marker block or not.
657 * @param {boolean} insertionMarker True if an insertion marker.
658 */
659Blockly.Block.prototype.setInsertionMarker = function(insertionMarker) {
660 if (this.isInsertionMarker_ == insertionMarker) {
661 return; // No change.
662 }
663 this.isInsertionMarker_ = insertionMarker;
664 // TODO: handle removing insertion marker status.
665 if (this.isInsertionMarker_) {
666 this.setColour(Blockly.Colours.insertionMarker);
667 this.setOpacity(Blockly.Colours.insertionMarkerOpacity);
668 Blockly.utils.addClass(/** @type {!Element} */ (this.svgGroup_),
669 'blocklyInsertionMarker');
670 }
671};
672
673/**
674 * Get whether this block is editable or not.
675 * @return {boolean} True if editable.
676 */
677Blockly.Block.prototype.isEditable = function() {
678 return this.editable_ && !(this.workspace && this.workspace.options.readOnly);
679};
680
681/**
682 * Set whether this block is editable or not.
683 * @param {boolean} editable True if editable.
684 */
685Blockly.Block.prototype.setEditable = function(editable) {
686 this.editable_ = editable;
687 for (var i = 0, input; input = this.inputList[i]; i++) {
688 for (var j = 0, field; field = input.fieldRow[j]; j++) {
689 field.updateEditable();
690 }
691 }
692};
693
694/**
695 * Set whether the connections are hidden (not tracked in a database) or not.
696 * Recursively walk down all child blocks (except collapsed blocks).
697 * @param {boolean} hidden True if connections are hidden.
698 */
699Blockly.Block.prototype.setConnectionsHidden = function(hidden) {
700 if (!hidden && this.isCollapsed()) {
701 if (this.outputConnection) {
702 this.outputConnection.setHidden(hidden);
703 }
704 if (this.previousConnection) {
705 this.previousConnection.setHidden(hidden);
706 }
707 if (this.nextConnection) {
708 this.nextConnection.setHidden(hidden);
709 var child = this.nextConnection.targetBlock();
710 if (child) {
711 child.setConnectionsHidden(hidden);
712 }
713 }
714 } else {
715 var myConnections = this.getConnections_(true);
716 for (var i = 0, connection; connection = myConnections[i]; i++) {
717 connection.setHidden(hidden);
718 if (connection.isSuperior()) {
719 var child = connection.targetBlock();
720 if (child) {
721 child.setConnectionsHidden(hidden);
722 }
723 }
724 }
725 }
726};
727
728/**
729 * Find the connection on this block that corresponds to the given connection
730 * on the other block.
731 * Used to match connections between a block and its insertion marker.
732 * @param {!Blockly.Block} otherBlock The other block to match against.
733 * @param {!Blockly.Connection} conn The other connection to match.
734 * @return {Blockly.Connection} the matching connection on this block, or null.
735 */
736Blockly.Block.prototype.getMatchingConnection = function(otherBlock, conn) {
737 var connections = this.getConnections_(true);
738 var otherConnections = otherBlock.getConnections_(true);
739 if (connections.length != otherConnections.length) {
740 throw "Connection lists did not match in length.";
741 }
742 for (var i = 0; i < otherConnections.length; i++) {
743 if (otherConnections[i] == conn) {
744 return connections[i];
745 }
746 }
747 return null;
748};
749
750/**
751 * Set the URL of this block's help page.
752 * @param {string|Function} url URL string for block help, or function that
753 * returns a URL. Null for no help.
754 */
755Blockly.Block.prototype.setHelpUrl = function(url) {
756 this.helpUrl = url;
757};
758
759/**
760 * Change the tooltip text for a block.
761 * @param {string|!Function} newTip Text for tooltip or a parent element to
762 * link to for its tooltip. May be a function that returns a string.
763 */
764Blockly.Block.prototype.setTooltip = function(newTip) {
765 this.tooltip = newTip;
766};
767
768/**
769 * Get the colour of a block.
770 * @return {string} #RRGGBB string.
771 */
772Blockly.Block.prototype.getColour = function() {
773 return this.colour_;
774};
775
776/**
777 * Get the secondary colour of a block.
778 * @return {string} #RRGGBB string.
779 */
780Blockly.Block.prototype.getColourSecondary = function() {
781 return this.colourSecondary_;
782};
783
784/**
785 * Get the tertiary colour of a block.
786 * @return {string} #RRGGBB string.
787 */
788Blockly.Block.prototype.getColourTertiary = function() {
789 return this.colourTertiary_;
790};
791
792/**
793* Create an #RRGGBB string colour from a colour HSV hue value or #RRGGBB string.
794* @param {number|string} colour HSV hue value, or #RRGGBB string.
795* @return {string} #RRGGBB string.
796* @private
797*/
798Blockly.Block.prototype.makeColour_ = function(colour) {
799 var hue = Number(colour);
800 if (!isNaN(hue)) {
801 return Blockly.hueToRgb(hue);
802 } else if (goog.isString(colour) && colour.match(/^#[0-9a-fA-F]{6}$/)) {
803 return colour;
804 } else {
805 throw 'Invalid colour: ' + colour;
806 }
807};
808
809/**
810 * Change the colour of a block, and optional secondary/teriarty colours.
811 * @param {number|string} colour HSV hue value, or #RRGGBB string.
812 * @param {number|string} colourSecondary HSV hue value, or #RRGGBB string.
813 * @param {number|string} colourTertiary HSV hue value, or #RRGGBB string.
814 */
815Blockly.Block.prototype.setColour = function(colour, colourSecondary, colourTertiary) {
816 this.colour_ = this.makeColour_(colour);
817 if (colourSecondary !== undefined) {
818 this.colourSecondary_ = this.makeColour_(colourSecondary);
819 } else {
820 this.colourSecondary_ = goog.color.rgbArrayToHex(
821 goog.color.darken(goog.color.hexToRgb(this.colour_), 0.1));
822 }
823 if (colourTertiary !== undefined) {
824 this.colourTertiary_ = this.makeColour_(colourTertiary);
825 } else {
826 this.colourTertiary_ = goog.color.rgbArrayToHex(
827 goog.color.darken(goog.color.hexToRgb(this.colour_), 0.2));
828 }
829 if (this.rendered) {
830 this.updateColour();
831 }
832};
833
834/**
835 * Sets a callback function to use whenever the block's parent workspace
836 * changes, replacing any prior onchange handler. This is usually only called
837 * from the constructor, the block type initializer function, or an extension
838 * initializer function.
839 * @param {function(Blockly.Events.Abstract)} onchangeFn The callback to call
840 * when the block's workspace changes.
841 * @throws {Error} if onchangeFn is not falsey or a function.
842 */
843Blockly.Block.prototype.setOnChange = function(onchangeFn) {
844 if (onchangeFn && !goog.isFunction(onchangeFn)) {
845 throw new Error("onchange must be a function.");
846 }
847 if (this.onchangeWrapper_) {
848 this.workspace.removeChangeListener(this.onchangeWrapper_);
849 }
850 this.onchange = onchangeFn;
851 if (this.onchange) {
852 this.onchangeWrapper_ = onchangeFn.bind(this);
853 this.workspace.addChangeListener(this.onchangeWrapper_);
854 }
855};
856
857/**
858 * Returns the named field from a block.
859 * @param {string} name The name of the field.
860 * @return {Blockly.Field} Named field, or null if field does not exist.
861 */
862Blockly.Block.prototype.getField = function(name) {
863 for (var i = 0, input; input = this.inputList[i]; i++) {
864 for (var j = 0, field; field = input.fieldRow[j]; j++) {
865 if (field.name === name) {
866 return field;
867 }
868 }
869 }
870 return null;
871};
872
873/**
874 * Return all variables referenced by this block.
875 * @return {!Array.<string>} List of variable names.
876 * @package
877 */
878Blockly.Block.prototype.getVars = function() {
879 var vars = [];
880 for (var i = 0, input; input = this.inputList[i]; i++) {
881 for (var j = 0, field; field = input.fieldRow[j]; j++) {
882 if (field.referencesVariables()) {
883 vars.push(field.getValue());
884 }
885 }
886 }
887 return vars;
888};
889
890/**
891 * Return all variables referenced by this block.
892 * @return {!Array.<!Blockly.VariableModel>} List of variable models.
893 * @package
894 */
895Blockly.Block.prototype.getVarModels = function() {
896 var vars = [];
897 for (var i = 0, input; input = this.inputList[i]; i++) {
898 for (var j = 0, field; field = input.fieldRow[j]; j++) {
899 if (field.referencesVariables()) {
900 var model = this.workspace.getVariableById(field.getValue());
901 // Check if the variable actually exists (and isn't just a potential
902 // variable).
903 if (model) {
904 vars.push(model);
905 }
906 }
907 }
908 }
909 return vars;
910};
911
912/**
913 * Notification that a variable is renaming but keeping the same ID. If the
914 * variable is in use on this block, rerender to show the new name.
915 * @param {!Blockly.VariableModel} variable The variable being renamed.
916 * @package
917 */
918Blockly.Block.prototype.updateVarName = function(variable) {
919 for (var i = 0, input; input = this.inputList[i]; i++) {
920 for (var j = 0, field; field = input.fieldRow[j]; j++) {
921 if (field.referencesVariables() &&
922 variable.getId() == field.getValue()) {
923 field.setText(variable.name);
924 }
925 }
926 }
927};
928
929/**
930 * Notification that a variable is renaming.
931 * If the ID matches one of this block's variables, rename it.
932 * @param {string} oldId ID of variable to rename.
933 * @param {string} newId ID of new variable. May be the same as oldId, but with
934 * an updated name.
935 */
936Blockly.Block.prototype.renameVarById = function(oldId, newId) {
937 for (var i = 0, input; input = this.inputList[i]; i++) {
938 for (var j = 0, field; field = input.fieldRow[j]; j++) {
939 if (field.referencesVariables() &&
940 oldId == field.getValue()) {
941 field.setValue(newId);
942 }
943 }
944 }
945};
946
947/**
948 * Returns the language-neutral value from the field of a block.
949 * @param {string} name The name of the field.
950 * @return {?string} Value from the field or null if field does not exist.
951 */
952Blockly.Block.prototype.getFieldValue = function(name) {
953 var field = this.getField(name);
954 if (field) {
955 return field.getValue();
956 }
957 return null;
958};
959
960/**
961 * Change the field value for a block (e.g. 'CHOOSE' or 'REMOVE').
962 * @param {string} newValue Value to be the new field.
963 * @param {string} name The name of the field.
964 */
965Blockly.Block.prototype.setFieldValue = function(newValue, name) {
966 var field = this.getField(name);
967 goog.asserts.assertObject(field, 'Field "%s" not found.', name);
968 field.setValue(newValue);
969};
970
971/**
972 * Set whether this block can chain onto the bottom of another block.
973 * @param {boolean} newBoolean True if there can be a previous statement.
974 * @param {(string|Array.<string>|null)=} opt_check Statement type or
975 * list of statement types. Null/undefined if any type could be connected.
976 */
977Blockly.Block.prototype.setPreviousStatement = function(newBoolean, opt_check) {
978 if (newBoolean) {
979 if (opt_check === undefined) {
980 opt_check = null;
981 }
982 if (!this.previousConnection) {
983 goog.asserts.assert(!this.outputConnection,
984 'Remove output connection prior to adding previous connection.');
985 this.previousConnection =
986 this.makeConnection_(Blockly.PREVIOUS_STATEMENT);
987 }
988 this.previousConnection.setCheck(opt_check);
989 } else {
990 if (this.previousConnection) {
991 goog.asserts.assert(!this.previousConnection.isConnected(),
992 'Must disconnect previous statement before removing connection.');
993 this.previousConnection.dispose();
994 this.previousConnection = null;
995 }
996 }
997};
998
999/**
1000 * Set whether another block can chain onto the bottom of this block.
1001 * @param {boolean} newBoolean True if there can be a next statement.
1002 * @param {(string|Array.<string>|null)=} opt_check Statement type or
1003 * list of statement types. Null/undefined if any type could be connected.
1004 */
1005Blockly.Block.prototype.setNextStatement = function(newBoolean, opt_check) {
1006 if (newBoolean) {
1007 if (opt_check === undefined) {
1008 opt_check = null;
1009 }
1010 if (!this.nextConnection) {
1011 this.nextConnection = this.makeConnection_(Blockly.NEXT_STATEMENT);
1012 }
1013 this.nextConnection.setCheck(opt_check);
1014 } else {
1015 if (this.nextConnection) {
1016 goog.asserts.assert(!this.nextConnection.isConnected(),
1017 'Must disconnect next statement before removing connection.');
1018 this.nextConnection.dispose();
1019 this.nextConnection = null;
1020 }
1021 }
1022};
1023
1024/**
1025 * Set whether this block returns a value.
1026 * @param {boolean} newBoolean True if there is an output.
1027 * @param {(string|Array.<string>|null)=} opt_check Returned type or list
1028 * of returned types. Null or undefined if any type could be returned
1029 * (e.g. variable get).
1030 */
1031Blockly.Block.prototype.setOutput = function(newBoolean, opt_check) {
1032 if (newBoolean) {
1033 if (opt_check === undefined) {
1034 opt_check = null;
1035 }
1036 if (!this.outputConnection) {
1037 goog.asserts.assert(!this.previousConnection,
1038 'Remove previous connection prior to adding output connection.');
1039 this.outputConnection = this.makeConnection_(Blockly.OUTPUT_VALUE);
1040 }
1041 this.outputConnection.setCheck(opt_check);
1042 } else {
1043 if (this.outputConnection) {
1044 goog.asserts.assert(!this.outputConnection.isConnected(),
1045 'Must disconnect output value before removing connection.');
1046 this.outputConnection.dispose();
1047 this.outputConnection = null;
1048 }
1049 }
1050};
1051
1052/**
1053 * Set whether value inputs are arranged horizontally or vertically.
1054 * @param {boolean} newBoolean True if inputs are horizontal.
1055 */
1056Blockly.Block.prototype.setInputsInline = function(newBoolean) {
1057 if (this.inputsInline != newBoolean) {
1058 Blockly.Events.fire(new Blockly.Events.BlockChange(
1059 this, 'inline', null, this.inputsInline, newBoolean));
1060 this.inputsInline = newBoolean;
1061 }
1062};
1063
1064/**
1065 * Get whether value inputs are arranged horizontally or vertically.
1066 * @return {boolean} True if inputs are horizontal.
1067 */
1068Blockly.Block.prototype.getInputsInline = function() {
1069 if (this.inputsInline != undefined) {
1070 // Set explicitly.
1071 return this.inputsInline;
1072 }
1073 // Not defined explicitly. Figure out what would look best.
1074 for (var i = 1; i < this.inputList.length; i++) {
1075 if (this.inputList[i - 1].type == Blockly.DUMMY_INPUT &&
1076 this.inputList[i].type == Blockly.DUMMY_INPUT) {
1077 // Two dummy inputs in a row. Don't inline them.
1078 return false;
1079 }
1080 }
1081 for (var i = 1; i < this.inputList.length; i++) {
1082 if (this.inputList[i - 1].type == Blockly.INPUT_VALUE &&
1083 this.inputList[i].type == Blockly.DUMMY_INPUT) {
1084 // Dummy input after a value input. Inline them.
1085 return true;
1086 }
1087 }
1088 return false;
1089};
1090
1091/**
1092 * Set whether the block is disabled or not.
1093 * @param {boolean} disabled True if disabled.
1094 */
1095Blockly.Block.prototype.setDisabled = function(disabled) {
1096 if (this.disabled != disabled) {
1097 Blockly.Events.fire(new Blockly.Events.BlockChange(
1098 this, 'disabled', null, this.disabled, disabled));
1099 this.disabled = disabled;
1100 }
1101};
1102
1103/**
1104 * Get whether the block is disabled or not due to parents.
1105 * The block's own disabled property is not considered.
1106 * @return {boolean} True if disabled.
1107 */
1108Blockly.Block.prototype.getInheritedDisabled = function() {
1109 var ancestor = this.getSurroundParent();
1110 while (ancestor) {
1111 if (ancestor.disabled) {
1112 return true;
1113 }
1114 ancestor = ancestor.getSurroundParent();
1115 }
1116 // Ran off the top.
1117 return false;
1118};
1119
1120/**
1121 * Get whether the block is collapsed or not.
1122 * @return {boolean} True if collapsed.
1123 */
1124Blockly.Block.prototype.isCollapsed = function() {
1125 return this.collapsed_;
1126};
1127
1128/**
1129 * Set whether the block is collapsed or not.
1130 * @param {boolean} collapsed True if collapsed.
1131 */
1132Blockly.Block.prototype.setCollapsed = function(collapsed) {
1133 if (this.collapsed_ != collapsed) {
1134 Blockly.Events.fire(new Blockly.Events.BlockChange(
1135 this, 'collapsed', null, this.collapsed_, collapsed));
1136 this.collapsed_ = collapsed;
1137 }
1138};
1139
1140/**
1141 * Create a human-readable text representation of this block and any children.
1142 * @param {number=} opt_maxLength Truncate the string to this length.
1143 * @param {string=} opt_emptyToken The placeholder string used to denote an
1144 * empty field. If not specified, '?' is used.
1145 * @return {string} Text of block.
1146 */
1147Blockly.Block.prototype.toString = function(opt_maxLength, opt_emptyToken) {
1148 var text = [];
1149 var emptyFieldPlaceholder = opt_emptyToken || '?';
1150 if (this.collapsed_) {
1151 text.push(this.getInput('_TEMP_COLLAPSED_INPUT').fieldRow[0].text_);
1152 } else {
1153 for (var i = 0, input; input = this.inputList[i]; i++) {
1154 for (var j = 0, field; field = input.fieldRow[j]; j++) {
1155 if (field instanceof Blockly.FieldDropdown && !field.getValue()) {
1156 text.push(emptyFieldPlaceholder);
1157 } else {
1158 text.push(field.getText());
1159 }
1160 }
1161 if (input.connection) {
1162 var child = input.connection.targetBlock();
1163 if (child) {
1164 text.push(child.toString(undefined, opt_emptyToken));
1165 } else {
1166 text.push(emptyFieldPlaceholder);
1167 }
1168 }
1169 }
1170 }
1171 text = goog.string.trim(text.join(' ')) || '???';
1172 if (opt_maxLength) {
1173 // TODO: Improve truncation so that text from this block is given priority.
1174 // E.g. "1+2+3+4+5+6+7+8+9=0" should be "...6+7+8+9=0", not "1+2+3+4+5...".
1175 // E.g. "1+2+3+4+5=6+7+8+9+0" should be "...4+5=6+7...".
1176 text = goog.string.truncate(text, opt_maxLength);
1177 }
1178 return text;
1179};
1180
1181/**
1182 * Shortcut for appending a value input row.
1183 * @param {string} name Language-neutral identifier which may used to find this
1184 * input again. Should be unique to this block.
1185 * @return {!Blockly.Input} The input object created.
1186 */
1187Blockly.Block.prototype.appendValueInput = function(name) {
1188 return this.appendInput_(Blockly.INPUT_VALUE, name);
1189};
1190
1191/**
1192 * Shortcut for appending a statement input row.
1193 * @param {string} name Language-neutral identifier which may used to find this
1194 * input again. Should be unique to this block.
1195 * @return {!Blockly.Input} The input object created.
1196 */
1197Blockly.Block.prototype.appendStatementInput = function(name) {
1198 return this.appendInput_(Blockly.NEXT_STATEMENT, name);
1199};
1200
1201/**
1202 * Shortcut for appending a dummy input row.
1203 * @param {string=} opt_name Language-neutral identifier which may used to find
1204 * this input again. Should be unique to this block.
1205 * @return {!Blockly.Input} The input object created.
1206 */
1207Blockly.Block.prototype.appendDummyInput = function(opt_name) {
1208 return this.appendInput_(Blockly.DUMMY_INPUT, opt_name || '');
1209};
1210
1211/**
1212 * Initialize this block using a cross-platform, internationalization-friendly
1213 * JSON description.
1214 * @param {!Object} json Structured data describing the block.
1215 */
1216Blockly.Block.prototype.jsonInit = function(json) {
1217 var warningPrefix = json['type'] ? 'Block "' + json['type'] + '": ' : '';
1218
1219 // Validate inputs.
1220 goog.asserts.assert(
1221 json['output'] == undefined || json['previousStatement'] == undefined,
1222 warningPrefix + 'Must not have both an output and a previousStatement.');
1223
1224 // Set basic properties of block.
1225 if (json['colour'] !== undefined) {
1226 this.setColourFromJson_(json);
1227 }
1228
1229 // Interpolate the message blocks.
1230 var i = 0;
1231 while (json['message' + i] !== undefined) {
1232 this.interpolate_(json['message' + i], json['args' + i] || [],
1233 json['lastDummyAlign' + i]);
1234 i++;
1235 }
1236
1237 if (json['inputsInline'] !== undefined) {
1238 this.setInputsInline(json['inputsInline']);
1239 }
1240 // Set output and previous/next connections.
1241 if (json['output'] !== undefined) {
1242 this.setOutput(true, json['output']);
1243 }
1244 if (json['previousStatement'] !== undefined) {
1245 this.setPreviousStatement(true, json['previousStatement']);
1246 }
1247 if (json['nextStatement'] !== undefined) {
1248 this.setNextStatement(true, json['nextStatement']);
1249 }
1250 if (json['tooltip'] !== undefined) {
1251 var rawValue = json['tooltip'];
1252 var localizedText = Blockly.utils.replaceMessageReferences(rawValue);
1253 this.setTooltip(localizedText);
1254 }
1255 if (json['enableContextMenu'] !== undefined) {
1256 var rawValue = json['enableContextMenu'];
1257 this.contextMenu = !!rawValue;
1258 }
1259 if (json['helpUrl'] !== undefined) {
1260 var rawValue = json['helpUrl'];
1261 var localizedValue = Blockly.utils.replaceMessageReferences(rawValue);
1262 this.setHelpUrl(localizedValue);
1263 }
1264 if (goog.isString(json['extensions'])) {
1265 console.warn('JSON attribute \'extensions\' should be an array of ' +
1266 'strings. Found raw string in JSON for \'' + json['type'] + '\' block.');
1267 json['extensions'] = [json['extensions']]; // Correct and continue.
1268 }
1269
1270 // Add the mutator to the block
1271 if (json['mutator'] !== undefined) {
1272 Blockly.Extensions.apply(json['mutator'], this, true);
1273 }
1274
1275 if (Array.isArray(json['extensions'])) {
1276 var extensionNames = json['extensions'];
1277 for (var i = 0; i < extensionNames.length; ++i) {
1278 var extensionName = extensionNames[i];
1279 Blockly.Extensions.apply(extensionName, this, false);
1280 }
1281 }
1282 if (json['outputShape'] !== undefined) {
1283 this.setOutputShape(json['outputShape']);
1284 }
1285 if (json['checkboxInFlyout'] !== undefined) {
1286 this.setCheckboxInFlyout(json['checkboxInFlyout']);
1287 }
1288 if (json['category'] !== undefined) {
1289 this.setCategory(json['category']);
1290 }
1291};
1292
1293/**
1294 * Add key/values from mixinObj to this block object. By default, this method
1295 * will check that the keys in mixinObj will not overwrite existing values in
1296 * the block, including prototype values. This provides some insurance against
1297 * mixin / extension incompatibilities with future block features. This check
1298 * can be disabled by passing true as the second argument.
1299 * @param {!Object} mixinObj The key/values pairs to add to this block object.
1300 * @param {boolean=} opt_disableCheck Option flag to disable overwrite checks.
1301 */
1302Blockly.Block.prototype.mixin = function(mixinObj, opt_disableCheck) {
1303 if (goog.isDef(opt_disableCheck) && !goog.isBoolean(opt_disableCheck)) {
1304 throw new Error("opt_disableCheck must be a boolean if provided");
1305 }
1306 if (!opt_disableCheck) {
1307 var overwrites = [];
1308 for (var key in mixinObj) {
1309 if (this[key] !== undefined) {
1310 overwrites.push(key);
1311 }
1312 }
1313 if (overwrites.length) {
1314 throw new Error('Mixin will overwrite block members: ' +
1315 JSON.stringify(overwrites));
1316 }
1317 }
1318 goog.mixin(this, mixinObj);
1319};
1320
1321/**
1322 * Set the colour of the block from strings or string table references.
1323 * @param {string|?} primary Primary colour, which may be a string that contains
1324 * string table references.
1325 * @param {string|?} secondary Secondary colour, which may be a string that
1326 * contains string table references.
1327 * @param {string|?} tertiary Tertiary colour, which may be a string that
1328 * contains string table references.
1329 * @private
1330 */
1331Blockly.Block.prototype.setColourFromRawValues_ = function(primary, secondary,
1332 tertiary) {
1333 primary = goog.isString(primary) ?
1334 Blockly.utils.replaceMessageReferences(primary) : primary;
1335 secondary = goog.isString(secondary) ?
1336 Blockly.utils.replaceMessageReferences(secondary) : secondary;
1337 tertiary = goog.isString(tertiary) ?
1338 Blockly.utils.replaceMessageReferences(tertiary) : tertiary;
1339
1340 this.setColour(primary, secondary, tertiary);
1341};
1342
1343/**
1344 * Set the colour of the block from JSON, replacing message references as
1345 * needed.
1346 * @param {!Object} json Structured data describing the block.
1347 * @private
1348 */
1349Blockly.Block.prototype.setColourFromJson_ = function(json) {
1350 this.setColourFromRawValues_(json['colour'], json['colourSecondary'],
1351 json['colourTertiary']);
1352};
1353
1354/**
1355 * Interpolate a message description onto the block.
1356 * @param {string} message Text contains interpolation tokens (%1, %2, ...)
1357 * that match with fields or inputs defined in the args array.
1358 * @param {!Array} args Array of arguments to be interpolated.
1359 * @param {string=} lastDummyAlign If a dummy input is added at the end,
1360 * how should it be aligned?
1361 * @private
1362 */
1363Blockly.Block.prototype.interpolate_ = function(message, args, lastDummyAlign) {
1364 var tokens = Blockly.utils.tokenizeInterpolation(message);
1365 // Interpolate the arguments. Build a list of elements.
1366 var indexDup = [];
1367 var indexCount = 0;
1368 var elements = [];
1369 for (var i = 0; i < tokens.length; i++) {
1370 var token = tokens[i];
1371 if (typeof token == 'number') {
1372 if (token <= 0 || token > args.length) {
1373 throw new Error('Block "' + this.type + '": ' +
1374 'Message index %' + token + ' out of range.');
1375 }
1376 if (indexDup[token]) {
1377 throw new Error('Block "' + this.type + '": ' +
1378 'Message index %' + token + ' duplicated.');
1379 }
1380 indexDup[token] = true;
1381 indexCount++;
1382 elements.push(args[token - 1]);
1383 } else {
1384 token = token.trim();
1385 if (token) {
1386 elements.push(token);
1387 }
1388 }
1389 }
1390 if (indexCount != args.length) {
1391 throw new Error('Block "' + this.type + '": ' +
1392 'Message does not reference all ' + args.length + ' arg(s).');
1393 }
1394 // Add last dummy input if needed.
1395 if (elements.length && (typeof elements[elements.length - 1] == 'string' ||
1396 goog.string.startsWith(
1397 elements[elements.length - 1]['type'], 'field_'))) {
1398 var dummyInput = {type: 'input_dummy'};
1399 if (lastDummyAlign) {
1400 dummyInput['align'] = lastDummyAlign;
1401 }
1402 elements.push(dummyInput);
1403 }
1404 // Lookup of alignment constants.
1405 var alignmentLookup = {
1406 'LEFT': Blockly.ALIGN_LEFT,
1407 'RIGHT': Blockly.ALIGN_RIGHT,
1408 'CENTRE': Blockly.ALIGN_CENTRE
1409 };
1410 // Populate block with inputs and fields.
1411 var fieldStack = [];
1412 for (var i = 0; i < elements.length; i++) {
1413 var element = elements[i];
1414 if (typeof element == 'string') {
1415 fieldStack.push([element, undefined]);
1416 } else {
1417 var field = null;
1418 var input = null;
1419 do {
1420 var altRepeat = false;
1421 if (typeof element == 'string') {
1422 field = new Blockly.FieldLabel(element);
1423 } else {
1424 switch (element['type']) {
1425 case 'input_value':
1426 input = this.appendValueInput(element['name']);
1427 break;
1428 case 'input_statement':
1429 input = this.appendStatementInput(element['name']);
1430 break;
1431 case 'input_dummy':
1432 input = this.appendDummyInput(element['name']);
1433 break;
1434 default:
1435 field = Blockly.Field.fromJson(element);
1436
1437 // Unknown field.
1438 if (!field) {
1439 if (element['alt']) {
1440 element = element['alt'];
1441 altRepeat = true;
1442 } else {
1443 console.warn('Blockly could not create a field of type ' +
1444 element['type'] +
1445 '. You may need to register your custom field. See ' +
1446 'github.com/google/blockly/issues/1584');
1447 }
1448 }
1449 }
1450 }
1451 } while (altRepeat);
1452 if (field) {
1453 fieldStack.push([field, element['name']]);
1454 } else if (input) {
1455 if (element['check']) {
1456 input.setCheck(element['check']);
1457 }
1458 if (element['align']) {
1459 input.setAlign(alignmentLookup[element['align']]);
1460 }
1461 for (var j = 0; j < fieldStack.length; j++) {
1462 input.appendField(fieldStack[j][0], fieldStack[j][1]);
1463 }
1464 fieldStack.length = 0;
1465 }
1466 }
1467 }
1468};
1469
1470/**
1471 * Add a value input, statement input or local variable to this block.
1472 * @param {number} type Either Blockly.INPUT_VALUE or Blockly.NEXT_STATEMENT or
1473 * Blockly.DUMMY_INPUT.
1474 * @param {string} name Language-neutral identifier which may used to find this
1475 * input again. Should be unique to this block.
1476 * @return {!Blockly.Input} The input object created.
1477 * @protected
1478 */
1479Blockly.Block.prototype.appendInput_ = function(type, name) {
1480 var connection = null;
1481 if (type == Blockly.INPUT_VALUE || type == Blockly.NEXT_STATEMENT) {
1482 connection = this.makeConnection_(type);
1483 }
1484 var input = new Blockly.Input(type, name, this, connection);
1485 // Append input to list.
1486 this.inputList.push(input);
1487 return input;
1488};
1489
1490/**
1491 * Move a named input to a different location on this block.
1492 * @param {string} name The name of the input to move.
1493 * @param {?string} refName Name of input that should be after the moved input,
1494 * or null to be the input at the end.
1495 */
1496Blockly.Block.prototype.moveInputBefore = function(name, refName) {
1497 if (name == refName) {
1498 return;
1499 }
1500 // Find both inputs.
1501 var inputIndex = -1;
1502 var refIndex = refName ? -1 : this.inputList.length;
1503 for (var i = 0, input; input = this.inputList[i]; i++) {
1504 if (input.name == name) {
1505 inputIndex = i;
1506 if (refIndex != -1) {
1507 break;
1508 }
1509 } else if (refName && input.name == refName) {
1510 refIndex = i;
1511 if (inputIndex != -1) {
1512 break;
1513 }
1514 }
1515 }
1516 goog.asserts.assert(inputIndex != -1, 'Named input "%s" not found.', name);
1517 goog.asserts.assert(
1518 refIndex != -1, 'Reference input "%s" not found.', refName);
1519 this.moveNumberedInputBefore(inputIndex, refIndex);
1520};
1521
1522/**
1523 * Move a numbered input to a different location on this block.
1524 * @param {number} inputIndex Index of the input to move.
1525 * @param {number} refIndex Index of input that should be after the moved input.
1526 */
1527Blockly.Block.prototype.moveNumberedInputBefore = function(
1528 inputIndex, refIndex) {
1529 // Validate arguments.
1530 goog.asserts.assert(inputIndex != refIndex, 'Can\'t move input to itself.');
1531 goog.asserts.assert(inputIndex < this.inputList.length,
1532 'Input index ' + inputIndex + ' out of bounds.');
1533 goog.asserts.assert(refIndex <= this.inputList.length,
1534 'Reference input ' + refIndex + ' out of bounds.');
1535 // Remove input.
1536 var input = this.inputList[inputIndex];
1537 this.inputList.splice(inputIndex, 1);
1538 if (inputIndex < refIndex) {
1539 refIndex--;
1540 }
1541 // Reinsert input.
1542 this.inputList.splice(refIndex, 0, input);
1543};
1544
1545/**
1546 * Remove an input from this block.
1547 * @param {string} name The name of the input.
1548 * @param {boolean=} opt_quiet True to prevent error if input is not present.
1549 * @throws {goog.asserts.AssertionError} if the input is not present and
1550 * opt_quiet is not true.
1551 */
1552Blockly.Block.prototype.removeInput = function(name, opt_quiet) {
1553 for (var i = 0, input; input = this.inputList[i]; i++) {
1554 if (input.name == name) {
1555 if (input.connection && input.connection.isConnected()) {
1556 input.connection.setShadowDom(null);
1557 var block = input.connection.targetBlock();
1558 if (block.isShadow()) {
1559 // Destroy any attached shadow block.
1560 block.dispose();
1561 } else {
1562 // Disconnect any attached normal block.
1563 block.unplug();
1564 }
1565 }
1566 input.dispose();
1567 this.inputList.splice(i, 1);
1568 return;
1569 }
1570 }
1571 if (!opt_quiet) {
1572 goog.asserts.fail('Input "%s" not found.', name);
1573 }
1574};
1575
1576/**
1577 * Fetches the named input object.
1578 * @param {string} name The name of the input.
1579 * @return {Blockly.Input} The input object, or null if input does not exist.
1580 */
1581Blockly.Block.prototype.getInput = function(name) {
1582 for (var i = 0, input; input = this.inputList[i]; i++) {
1583 if (input.name == name) {
1584 return input;
1585 }
1586 }
1587 // This input does not exist.
1588 return null;
1589};
1590
1591/**
1592 * Fetches the block attached to the named input.
1593 * @param {string} name The name of the input.
1594 * @return {Blockly.Block} The attached value block, or null if the input is
1595 * either disconnected or if the input does not exist.
1596 */
1597Blockly.Block.prototype.getInputTargetBlock = function(name) {
1598 var input = this.getInput(name);
1599 return input && input.connection && input.connection.targetBlock();
1600};
1601
1602/**
1603 * Returns the comment on this block (or '' if none).
1604 * @return {string} Block's comment.
1605 */
1606Blockly.Block.prototype.getCommentText = function() {
1607 return this.comment || '';
1608};
1609
1610/**
1611 * Set this block's comment text.
1612 * @param {?string} text The text, or null to delete.
1613 */
1614Blockly.Block.prototype.setCommentText = function(text) {
1615 if (this.comment != text) {
1616 Blockly.Events.fire(new Blockly.Events.BlockChange(
1617 this, 'comment', null, this.comment, text || ''));
1618 this.comment = text;
1619 }
1620};
1621
1622/**
1623 * Set this block's output shape.
1624 * e.g., null, OUTPUT_SHAPE_HEXAGONAL, OUTPUT_SHAPE_ROUND, OUTPUT_SHAPE_SQUARE.
1625 * @param {?number} outputShape Value representing output shape
1626 * (see constants.js).
1627 */
1628Blockly.Block.prototype.setOutputShape = function(outputShape) {
1629 this.outputShape_ = outputShape;
1630};
1631
1632/**
1633 * Get this block's output shape.
1634 * @return {?number} Value representing output shape (see constants.js).
1635 */
1636Blockly.Block.prototype.getOutputShape = function() {
1637 return this.outputShape_;
1638};
1639
1640/**
1641 * Set this block's category (for styling purposes)
1642 * @param {?string} category The block's category (see constants.js).
1643 */
1644Blockly.Block.prototype.setCategory = function(category) {
1645 this.category_ = category;
1646};
1647
1648/**
1649 * Get this block's category (for styling purposes)
1650 * @return {?string} category The block's category (see constants.js).
1651 */
1652Blockly.Block.prototype.getCategory = function() {
1653 return this.category_;
1654};
1655
1656/**
1657 * Set whether this block has a checkbox next to it in the flyout.
1658 * @param {boolean} hasCheckbox True if this block should have a checkbox.
1659 */
1660Blockly.Block.prototype.setCheckboxInFlyout = function(hasCheckbox) {
1661 this.checkboxInFlyout_ = hasCheckbox;
1662};
1663
1664/**
1665 * Get whether this block has a checkbox next to it in the flyout.
1666 * @return {boolean} True if this block should have a checkbox.
1667 */
1668Blockly.Block.prototype.hasCheckboxInFlyout = function() {
1669 return this.checkboxInFlyout_;
1670};
1671
1672/**
1673 * Set this block's warning text.
1674 * @param {?string} text The text, or null to delete.
1675 * @abstract
1676 */
1677Blockly.Block.prototype.setWarningText = function(/* text */) {
1678 // NOP.
1679};
1680
1681/**
1682 * Give this block a mutator dialog.
1683 * @param {Blockly.Mutator} mutator A mutator dialog instance or null to remove.
1684 * @abstract
1685 */
1686Blockly.Block.prototype.setMutator = function(/* mutator */) {
1687 // NOP.
1688};
1689
1690/**
1691 * Return the coordinates of the top-left corner of this block relative to the
1692 * drawing surface's origin (0,0), in workspace units.
1693 * @return {!goog.math.Coordinate} Object with .x and .y properties.
1694 */
1695Blockly.Block.prototype.getRelativeToSurfaceXY = function() {
1696 return this.xy_;
1697};
1698
1699/**
1700 * Move a block by a relative offset.
1701 * @param {number} dx Horizontal offset, in workspace units.
1702 * @param {number} dy Vertical offset, in workspace units.
1703 */
1704Blockly.Block.prototype.moveBy = function(dx, dy) {
1705 goog.asserts.assert(!this.parentBlock_, 'Block has parent.');
1706 var event = new Blockly.Events.BlockMove(this);
1707 this.xy_.translate(dx, dy);
1708 event.recordNew();
1709 Blockly.Events.fire(event);
1710};
1711
1712/**
1713 * Create a connection of the specified type.
1714 * @param {number} type The type of the connection to create.
1715 * @return {!Blockly.Connection} A new connection of the specified type.
1716 * @private
1717 */
1718Blockly.Block.prototype.makeConnection_ = function(type) {
1719 return new Blockly.Connection(this, type);
1720};
1721
1722/**
1723 * Recursively checks whether all statement and value inputs are filled with
1724 * blocks. Also checks all following statement blocks in this stack.
1725 * @param {boolean=} opt_shadowBlocksAreFilled An optional argument controlling
1726 * whether shadow blocks are counted as filled. Defaults to true.
1727 * @return {boolean} True if all inputs are filled, false otherwise.
1728 */
1729Blockly.Block.prototype.allInputsFilled = function(opt_shadowBlocksAreFilled) {
1730 // Account for the shadow block filledness toggle.
1731 if (opt_shadowBlocksAreFilled === undefined) {
1732 opt_shadowBlocksAreFilled = true;
1733 }
1734 if (!opt_shadowBlocksAreFilled && this.isShadow()) {
1735 return false;
1736 }
1737
1738 // Recursively check each input block of the current block.
1739 for (var i = 0, input; input = this.inputList[i]; i++) {
1740 if (!input.connection) {
1741 continue;
1742 }
1743 var target = input.connection.targetBlock();
1744 if (!target || !target.allInputsFilled(opt_shadowBlocksAreFilled)) {
1745 return false;
1746 }
1747 }
1748
1749 // Recursively check the next block after the current block.
1750 var next = this.getNextBlock();
1751 if (next) {
1752 return next.allInputsFilled(opt_shadowBlocksAreFilled);
1753 }
1754
1755 return true;
1756};
1757
1758/**
1759 * This method returns a string describing this Block in developer terms (type
1760 * name and ID; English only).
1761 *
1762 * Intended to on be used in console logs and errors. If you need a string that
1763 * uses the user's native language (including block text, field values, and
1764 * child blocks), use [toString()]{@link Blockly.Block#toString}.
1765 * @return {string} The description.
1766 */
1767Blockly.Block.prototype.toDevString = function() {
1768 var msg = this.type ? '"' + this.type + '" block' : 'Block';
1769 if (this.id) {
1770 msg += ' (id="' + this.id + '")';
1771 }
1772 return msg;
1773};