diff --git a/2021-07-07-21-48-14.js b/2021-07-07-21-48-14.js new file mode 100644 index 0000000..9502a56 --- /dev/null +++ b/2021-07-07-21-48-14.js @@ -0,0 +1,10 @@ +(async () => { + var _E7_95_AA_E5_8F_B7; + + + for (_E7_95_AA_E5_8F_B7 = 3; _E7_95_AA_E5_8F_B7 >= 1; _E7_95_AA_E5_8F_B7 -= 1) { + console.log(_E7_95_AA_E5_8F_B7); + + } + +})(); \ No newline at end of file diff --git a/google-blockly/python_compressed.js b/google-blockly/python_compressed.js new file mode 100644 index 0000000..21b9501 --- /dev/null +++ b/google-blockly/python_compressed.js @@ -0,0 +1,100 @@ +// Do not edit this file; automatically generated by gulp. + +/* eslint-disable */ +;(function(root, factory) { + if (typeof define === 'function' && define.amd) { // AMD + define(['./blockly_compressed.js'], factory); + } else if (typeof exports === 'object') { // Node.js + module.exports = factory(require('./blockly_compressed.js')); + } else { // Browser + root.Blockly.Python = factory(root.Blockly); + } +}(this, function(Blockly) { + 'use strict';Blockly.Python=new Blockly.Generator("Python");Blockly.Python.addReservedWords("False,None,True,and,as,assert,break,class,continue,def,del,elif,else,except,exec,finally,for,from,global,if,import,in,is,lambda,nonlocal,not,or,pass,print,raise,return,try,while,with,yield,NotImplemented,Ellipsis,__debug__,quit,exit,copyright,license,credits,ArithmeticError,AssertionError,AttributeError,BaseException,BlockingIOError,BrokenPipeError,BufferError,BytesWarning,ChildProcessError,ConnectionAbortedError,ConnectionError,ConnectionRefusedError,ConnectionResetError,DeprecationWarning,EOFError,Ellipsis,EnvironmentError,Exception,FileExistsError,FileNotFoundError,FloatingPointError,FutureWarning,GeneratorExit,IOError,ImportError,ImportWarning,IndentationError,IndexError,InterruptedError,IsADirectoryError,KeyError,KeyboardInterrupt,LookupError,MemoryError,ModuleNotFoundError,NameError,NotADirectoryError,NotImplemented,NotImplementedError,OSError,OverflowError,PendingDeprecationWarning,PermissionError,ProcessLookupError,RecursionError,ReferenceError,ResourceWarning,RuntimeError,RuntimeWarning,StandardError,StopAsyncIteration,StopIteration,SyntaxError,SyntaxWarning,SystemError,SystemExit,TabError,TimeoutError,TypeError,UnboundLocalError,UnicodeDecodeError,UnicodeEncodeError,UnicodeError,UnicodeTranslateError,UnicodeWarning,UserWarning,ValueError,Warning,ZeroDivisionError,_,__build_class__,__debug__,__doc__,__import__,__loader__,__name__,__package__,__spec__,abs,all,any,apply,ascii,basestring,bin,bool,buffer,bytearray,bytes,callable,chr,classmethod,cmp,coerce,compile,complex,copyright,credits,delattr,dict,dir,divmod,enumerate,eval,exec,execfile,exit,file,filter,float,format,frozenset,getattr,globals,hasattr,hash,help,hex,id,input,int,intern,isinstance,issubclass,iter,len,license,list,locals,long,map,max,memoryview,min,next,object,oct,open,ord,pow,print,property,quit,range,raw_input,reduce,reload,repr,reversed,round,set,setattr,slice,sorted,staticmethod,str,sum,super,tuple,type,unichr,unicode,vars,xrange,zip"); +Blockly.Python.ORDER_ATOMIC=0;Blockly.Python.ORDER_COLLECTION=1;Blockly.Python.ORDER_STRING_CONVERSION=1;Blockly.Python.ORDER_MEMBER=2.1;Blockly.Python.ORDER_FUNCTION_CALL=2.2;Blockly.Python.ORDER_EXPONENTIATION=3;Blockly.Python.ORDER_UNARY_SIGN=4;Blockly.Python.ORDER_BITWISE_NOT=4;Blockly.Python.ORDER_MULTIPLICATIVE=5;Blockly.Python.ORDER_ADDITIVE=6;Blockly.Python.ORDER_BITWISE_SHIFT=7;Blockly.Python.ORDER_BITWISE_AND=8;Blockly.Python.ORDER_BITWISE_XOR=9;Blockly.Python.ORDER_BITWISE_OR=10; +Blockly.Python.ORDER_RELATIONAL=11;Blockly.Python.ORDER_LOGICAL_NOT=12;Blockly.Python.ORDER_LOGICAL_AND=13;Blockly.Python.ORDER_LOGICAL_OR=14;Blockly.Python.ORDER_CONDITIONAL=15;Blockly.Python.ORDER_LAMBDA=16;Blockly.Python.ORDER_NONE=99; +Blockly.Python.ORDER_OVERRIDES=[[Blockly.Python.ORDER_FUNCTION_CALL,Blockly.Python.ORDER_MEMBER],[Blockly.Python.ORDER_FUNCTION_CALL,Blockly.Python.ORDER_FUNCTION_CALL],[Blockly.Python.ORDER_MEMBER,Blockly.Python.ORDER_MEMBER],[Blockly.Python.ORDER_MEMBER,Blockly.Python.ORDER_FUNCTION_CALL],[Blockly.Python.ORDER_LOGICAL_NOT,Blockly.Python.ORDER_LOGICAL_NOT],[Blockly.Python.ORDER_LOGICAL_AND,Blockly.Python.ORDER_LOGICAL_AND],[Blockly.Python.ORDER_LOGICAL_OR,Blockly.Python.ORDER_LOGICAL_OR]]; +Blockly.Python.isInitialized=!1; +Blockly.Python.init=function(a){Blockly.Python.PASS=this.INDENT+"pass\n";Blockly.Python.definitions_=Object.create(null);Blockly.Python.functionNames_=Object.create(null);Blockly.Python.variableDB_?Blockly.Python.variableDB_.reset():Blockly.Python.variableDB_=new Blockly.Names(Blockly.Python.RESERVED_WORDS_);Blockly.Python.variableDB_.setVariableMap(a.getVariableMap());for(var b=[],c=Blockly.Variables.allDeveloperVariables(a),d=0;dc?"int("+a+" - "+-c+")":"int("+a+")",d&&(a="-"+a));return a};Blockly.Python.colour={};Blockly.Python.colour_picker=function(a){return[Blockly.Python.quote_(a.getFieldValue("COLOUR")),Blockly.Python.ORDER_ATOMIC]};Blockly.Python.colour_random=function(a){Blockly.Python.definitions_.import_random="import random";return["'#%06x' % random.randint(0, 2**24 - 1)",Blockly.Python.ORDER_FUNCTION_CALL]}; +Blockly.Python.colour_rgb=function(a){var b=Blockly.Python.provideFunction_("colour_rgb",["def "+Blockly.Python.FUNCTION_NAME_PLACEHOLDER_+"(r, g, b):"," r = round(min(100, max(0, r)) * 2.55)"," g = round(min(100, max(0, g)) * 2.55)"," b = round(min(100, max(0, b)) * 2.55)"," return '#%02x%02x%02x' % (r, g, b)"]),c=Blockly.Python.valueToCode(a,"RED",Blockly.Python.ORDER_NONE)||0,d=Blockly.Python.valueToCode(a,"GREEN",Blockly.Python.ORDER_NONE)||0;a=Blockly.Python.valueToCode(a,"BLUE",Blockly.Python.ORDER_NONE)|| +0;return[b+"("+c+", "+d+", "+a+")",Blockly.Python.ORDER_FUNCTION_CALL]}; +Blockly.Python.colour_blend=function(a){var b=Blockly.Python.provideFunction_("colour_blend",["def "+Blockly.Python.FUNCTION_NAME_PLACEHOLDER_+"(colour1, colour2, ratio):"," r1, r2 = int(colour1[1:3], 16), int(colour2[1:3], 16)"," g1, g2 = int(colour1[3:5], 16), int(colour2[3:5], 16)"," b1, b2 = int(colour1[5:7], 16), int(colour2[5:7], 16)"," ratio = min(1, max(0, ratio))"," r = round(r1 * (1 - ratio) + r2 * ratio)"," g = round(g1 * (1 - ratio) + g2 * ratio)"," b = round(b1 * (1 - ratio) + b2 * ratio)", +" return '#%02x%02x%02x' % (r, g, b)"]),c=Blockly.Python.valueToCode(a,"COLOUR1",Blockly.Python.ORDER_NONE)||"'#000000'",d=Blockly.Python.valueToCode(a,"COLOUR2",Blockly.Python.ORDER_NONE)||"'#000000'";a=Blockly.Python.valueToCode(a,"RATIO",Blockly.Python.ORDER_NONE)||0;return[b+"("+c+", "+d+", "+a+")",Blockly.Python.ORDER_FUNCTION_CALL]};Blockly.Python.lists={};Blockly.Python.lists_create_empty=function(a){return["[]",Blockly.Python.ORDER_ATOMIC]};Blockly.Python.lists_create_with=function(a){for(var b=Array(a.itemCount_),c=0;c",GTE:">="}[a.getFieldValue("OP")],c=Blockly.Python.ORDER_RELATIONAL,d=Blockly.Python.valueToCode(a,"A",c)||"0";a=Blockly.Python.valueToCode(a,"B",c)||"0";return[d+" "+b+" "+a,c]}; +Blockly.Python.logic_operation=function(a){var b="AND"==a.getFieldValue("OP")?"and":"or",c="and"==b?Blockly.Python.ORDER_LOGICAL_AND:Blockly.Python.ORDER_LOGICAL_OR,d=Blockly.Python.valueToCode(a,"A",c);a=Blockly.Python.valueToCode(a,"B",c);if(d||a){var e="and"==b?"True":"False";d||(d=e);a||(a=e)}else a=d="False";return[d+" "+b+" "+a,c]};Blockly.Python.logic_negate=function(a){return["not "+(Blockly.Python.valueToCode(a,"BOOL",Blockly.Python.ORDER_LOGICAL_NOT)||"True"),Blockly.Python.ORDER_LOGICAL_NOT]}; +Blockly.Python.logic_boolean=function(a){return["TRUE"==a.getFieldValue("BOOL")?"True":"False",Blockly.Python.ORDER_ATOMIC]};Blockly.Python.logic_null=function(a){return["None",Blockly.Python.ORDER_ATOMIC]}; +Blockly.Python.logic_ternary=function(a){var b=Blockly.Python.valueToCode(a,"IF",Blockly.Python.ORDER_CONDITIONAL)||"False",c=Blockly.Python.valueToCode(a,"THEN",Blockly.Python.ORDER_CONDITIONAL)||"None";a=Blockly.Python.valueToCode(a,"ELSE",Blockly.Python.ORDER_CONDITIONAL)||"None";return[c+" if "+b+" else "+a,Blockly.Python.ORDER_CONDITIONAL]};Blockly.Python.loops={};Blockly.Python.controls_repeat_ext=function(a){var b=a.getField("TIMES")?String(parseInt(a.getFieldValue("TIMES"),10)):Blockly.Python.valueToCode(a,"TIMES",Blockly.Python.ORDER_NONE)||"0";b=Blockly.isNumber(b)?parseInt(b,10):"int("+b+")";var c=Blockly.Python.statementToCode(a,"DO");c=Blockly.Python.addLoopTrap(c,a)||Blockly.Python.PASS;return"for "+Blockly.Python.variableDB_.getDistinctName("count",Blockly.VARIABLE_CATEGORY_NAME)+" in range("+b+"):\n"+c}; +Blockly.Python.controls_repeat=Blockly.Python.controls_repeat_ext;Blockly.Python.controls_whileUntil=function(a){var b="UNTIL"==a.getFieldValue("MODE"),c=Blockly.Python.valueToCode(a,"BOOL",b?Blockly.Python.ORDER_LOGICAL_NOT:Blockly.Python.ORDER_NONE)||"False",d=Blockly.Python.statementToCode(a,"DO");d=Blockly.Python.addLoopTrap(d,a)||Blockly.Python.PASS;b&&(c="not "+c);return"while "+c+":\n"+d}; +Blockly.Python.controls_for=function(a){var b=Blockly.Python.variableDB_.getName(a.getFieldValue("VAR"),Blockly.VARIABLE_CATEGORY_NAME),c=Blockly.Python.valueToCode(a,"FROM",Blockly.Python.ORDER_NONE)||"0",d=Blockly.Python.valueToCode(a,"TO",Blockly.Python.ORDER_NONE)||"0",e=Blockly.Python.valueToCode(a,"BY",Blockly.Python.ORDER_NONE)||"1",f=Blockly.Python.statementToCode(a,"DO");f=Blockly.Python.addLoopTrap(f,a)||Blockly.Python.PASS;var n="",k=function(){return Blockly.Python.provideFunction_("upRange", +["def "+Blockly.Python.FUNCTION_NAME_PLACEHOLDER_+"(start, stop, step):"," while start <= stop:"," yield start"," start += abs(step)"])},h=function(){return Blockly.Python.provideFunction_("downRange",["def "+Blockly.Python.FUNCTION_NAME_PLACEHOLDER_+"(start, stop, step):"," while start >= stop:"," yield start"," start -= abs(step)"])};a=function(g,l,p){return"("+g+" <= "+l+") and "+k()+"("+g+", "+l+", "+p+") or "+h()+"("+g+", "+l+", "+p+")"};if(Blockly.isNumber(c)&&Blockly.isNumber(d)&& +Blockly.isNumber(e))c=Number(c),d=Number(d),e=Math.abs(Number(e)),0===c%1&&0===d%1&&0===e%1?(c<=d?(d++,a=0==c&&1==e?d:c+", "+d,1!=e&&(a+=", "+e)):(d--,a=c+", "+d+", -"+e),a="range("+a+")"):(a=ca?Blockly.Python.ORDER_UNARY_SIGN:Blockly.Python.ORDER_ATOMIC;return[a,b]}; +Blockly.Python.math_arithmetic=function(a){var b={ADD:[" + ",Blockly.Python.ORDER_ADDITIVE],MINUS:[" - ",Blockly.Python.ORDER_ADDITIVE],MULTIPLY:[" * ",Blockly.Python.ORDER_MULTIPLICATIVE],DIVIDE:[" / ",Blockly.Python.ORDER_MULTIPLICATIVE],POWER:[" ** ",Blockly.Python.ORDER_EXPONENTIATION]}[a.getFieldValue("OP")],c=b[0];b=b[1];var d=Blockly.Python.valueToCode(a,"A",b)||"0";a=Blockly.Python.valueToCode(a,"B",b)||"0";return[d+c+a,b]}; +Blockly.Python.math_single=function(a){var b=a.getFieldValue("OP");if("NEG"==b){var c=Blockly.Python.valueToCode(a,"NUM",Blockly.Python.ORDER_UNARY_SIGN)||"0";return["-"+c,Blockly.Python.ORDER_UNARY_SIGN]}Blockly.Python.definitions_.import_math="import math";a="SIN"==b||"COS"==b||"TAN"==b?Blockly.Python.valueToCode(a,"NUM",Blockly.Python.ORDER_MULTIPLICATIVE)||"0":Blockly.Python.valueToCode(a,"NUM",Blockly.Python.ORDER_NONE)||"0";switch(b){case "ABS":c="math.fabs("+a+")";break;case "ROOT":c="math.sqrt("+ +a+")";break;case "LN":c="math.log("+a+")";break;case "LOG10":c="math.log10("+a+")";break;case "EXP":c="math.exp("+a+")";break;case "POW10":c="math.pow(10,"+a+")";break;case "ROUND":c="round("+a+")";break;case "ROUNDUP":c="math.ceil("+a+")";break;case "ROUNDDOWN":c="math.floor("+a+")";break;case "SIN":c="math.sin("+a+" / 180.0 * math.pi)";break;case "COS":c="math.cos("+a+" / 180.0 * math.pi)";break;case "TAN":c="math.tan("+a+" / 180.0 * math.pi)"}if(c)return[c,Blockly.Python.ORDER_FUNCTION_CALL];switch(b){case "ASIN":c= +"math.asin("+a+") / math.pi * 180";break;case "ACOS":c="math.acos("+a+") / math.pi * 180";break;case "ATAN":c="math.atan("+a+") / math.pi * 180";break;default:throw Error("Unknown math operator: "+b);}return[c,Blockly.Python.ORDER_MULTIPLICATIVE]}; +Blockly.Python.math_constant=function(a){var b={PI:["math.pi",Blockly.Python.ORDER_MEMBER],E:["math.e",Blockly.Python.ORDER_MEMBER],GOLDEN_RATIO:["(1 + math.sqrt(5)) / 2",Blockly.Python.ORDER_MULTIPLICATIVE],SQRT2:["math.sqrt(2)",Blockly.Python.ORDER_MEMBER],SQRT1_2:["math.sqrt(1.0 / 2)",Blockly.Python.ORDER_MEMBER],INFINITY:["float('inf')",Blockly.Python.ORDER_ATOMIC]};a=a.getFieldValue("CONSTANT");"INFINITY"!=a&&(Blockly.Python.definitions_.import_math="import math");return b[a]}; +Blockly.Python.math_number_property=function(a){var b=Blockly.Python.valueToCode(a,"NUMBER_TO_CHECK",Blockly.Python.ORDER_MULTIPLICATIVE)||"0",c=a.getFieldValue("PROPERTY");if("PRIME"==c)return Blockly.Python.definitions_.import_math="import math",Blockly.Python.definitions_.from_numbers_import_Number="from numbers import Number",[Blockly.Python.provideFunction_("math_isPrime",["def "+Blockly.Python.FUNCTION_NAME_PLACEHOLDER_+"(n):"," # https://en.wikipedia.org/wiki/Primality_test#Naive_methods", +" # If n is not a number but a string, try parsing it."," if not isinstance(n, Number):"," try:"," n = float(n)"," except:"," return False"," if n == 2 or n == 3:"," return True"," # False if n is negative, is 1, or not whole, or if n is divisible by 2 or 3."," if n <= 1 or n % 1 != 0 or n % 2 == 0 or n % 3 == 0:"," return False"," # Check all the numbers of form 6k +/- 1, up to sqrt(n)."," for x in range(6, int(math.sqrt(n)) + 2, 6):"," if n % (x - 1) == 0 or n % (x + 1) == 0:", +" return False"," return True"])+"("+b+")",Blockly.Python.ORDER_FUNCTION_CALL];switch(c){case "EVEN":var d=b+" % 2 == 0";break;case "ODD":d=b+" % 2 == 1";break;case "WHOLE":d=b+" % 1 == 0";break;case "POSITIVE":d=b+" > 0";break;case "NEGATIVE":d=b+" < 0";break;case "DIVISIBLE_BY":a=Blockly.Python.valueToCode(a,"DIVISOR",Blockly.Python.ORDER_MULTIPLICATIVE);if(!a||"0"==a)return["False",Blockly.Python.ORDER_ATOMIC];d=b+" % "+a+" == 0"}return[d,Blockly.Python.ORDER_RELATIONAL]}; +Blockly.Python.math_change=function(a){Blockly.Python.definitions_.from_numbers_import_Number="from numbers import Number";var b=Blockly.Python.valueToCode(a,"DELTA",Blockly.Python.ORDER_ADDITIVE)||"0";a=Blockly.Python.variableDB_.getName(a.getFieldValue("VAR"),Blockly.VARIABLE_CATEGORY_NAME);return a+" = ("+a+" if isinstance("+a+", Number) else 0) + "+b+"\n"};Blockly.Python.math_round=Blockly.Python.math_single;Blockly.Python.math_trig=Blockly.Python.math_single; +Blockly.Python.math_on_list=function(a){var b=a.getFieldValue("OP");a=Blockly.Python.valueToCode(a,"LIST",Blockly.Python.ORDER_NONE)||"[]";switch(b){case "SUM":b="sum("+a+")";break;case "MIN":b="min("+a+")";break;case "MAX":b="max("+a+")";break;case "AVERAGE":Blockly.Python.definitions_.from_numbers_import_Number="from numbers import Number";b=Blockly.Python.provideFunction_("math_mean",["def "+Blockly.Python.FUNCTION_NAME_PLACEHOLDER_+"(myList):"," localList = [e for e in myList if isinstance(e, Number)]", +" if not localList: return"," return float(sum(localList)) / len(localList)"]);b=b+"("+a+")";break;case "MEDIAN":Blockly.Python.definitions_.from_numbers_import_Number="from numbers import Number";b=Blockly.Python.provideFunction_("math_median",["def "+Blockly.Python.FUNCTION_NAME_PLACEHOLDER_+"(myList):"," localList = sorted([e for e in myList if isinstance(e, Number)])"," if not localList: return"," if len(localList) % 2 == 0:"," return (localList[len(localList) // 2 - 1] + localList[len(localList) // 2]) / 2.0", +" else:"," return localList[(len(localList) - 1) // 2]"]);b=b+"("+a+")";break;case "MODE":b=Blockly.Python.provideFunction_("math_modes",["def "+Blockly.Python.FUNCTION_NAME_PLACEHOLDER_+"(some_list):"," modes = []"," # Using a lists of [item, count] to keep count rather than dict",' # to avoid "unhashable" errors when the counted item is itself a list or dict.'," counts = []"," maxCount = 1"," for item in some_list:"," found = False"," for count in counts:"," if count[0] == item:", +" count[1] += 1"," maxCount = max(maxCount, count[1])"," found = True"," if not found:"," counts.append([item, 1])"," for counted_item, item_count in counts:"," if item_count == maxCount:"," modes.append(counted_item)"," return modes"]);b=b+"("+a+")";break;case "STD_DEV":Blockly.Python.definitions_.import_math="import math";b=Blockly.Python.provideFunction_("math_standard_deviation",["def "+Blockly.Python.FUNCTION_NAME_PLACEHOLDER_+"(numbers):"," n = len(numbers)", +" if n == 0: return"," mean = float(sum(numbers)) / n"," variance = sum((x - mean) ** 2 for x in numbers) / n"," return math.sqrt(variance)"]);b=b+"("+a+")";break;case "RANDOM":Blockly.Python.definitions_.import_random="import random";b="random.choice("+a+")";break;default:throw Error("Unknown operator: "+b);}return[b,Blockly.Python.ORDER_FUNCTION_CALL]}; +Blockly.Python.math_modulo=function(a){var b=Blockly.Python.valueToCode(a,"DIVIDEND",Blockly.Python.ORDER_MULTIPLICATIVE)||"0";a=Blockly.Python.valueToCode(a,"DIVISOR",Blockly.Python.ORDER_MULTIPLICATIVE)||"0";return[b+" % "+a,Blockly.Python.ORDER_MULTIPLICATIVE]}; +Blockly.Python.math_constrain=function(a){var b=Blockly.Python.valueToCode(a,"VALUE",Blockly.Python.ORDER_NONE)||"0",c=Blockly.Python.valueToCode(a,"LOW",Blockly.Python.ORDER_NONE)||"0";a=Blockly.Python.valueToCode(a,"HIGH",Blockly.Python.ORDER_NONE)||"float('inf')";return["min(max("+b+", "+c+"), "+a+")",Blockly.Python.ORDER_FUNCTION_CALL]}; +Blockly.Python.math_random_int=function(a){Blockly.Python.definitions_.import_random="import random";var b=Blockly.Python.valueToCode(a,"FROM",Blockly.Python.ORDER_NONE)||"0";a=Blockly.Python.valueToCode(a,"TO",Blockly.Python.ORDER_NONE)||"0";return["random.randint("+b+", "+a+")",Blockly.Python.ORDER_FUNCTION_CALL]};Blockly.Python.math_random_float=function(a){Blockly.Python.definitions_.import_random="import random";return["random.random()",Blockly.Python.ORDER_FUNCTION_CALL]}; +Blockly.Python.math_atan2=function(a){Blockly.Python.definitions_.import_math="import math";var b=Blockly.Python.valueToCode(a,"X",Blockly.Python.ORDER_NONE)||"0";return["math.atan2("+(Blockly.Python.valueToCode(a,"Y",Blockly.Python.ORDER_NONE)||"0")+", "+b+") / math.pi * 180",Blockly.Python.ORDER_MULTIPLICATIVE]};Blockly.Python.procedures={}; +Blockly.Python.procedures_defreturn=function(a){for(var b=[],c,d=a.workspace,e=Blockly.Variables.allUsedVarModels(d)||[],f=0;c=e[f];f++)c=c.name,-1==a.getVars().indexOf(c)&&b.push(Blockly.Python.variableDB_.getName(c,Blockly.VARIABLE_CATEGORY_NAME));e=Blockly.Variables.allDeveloperVariables(d);for(f=0;f -
Javascript Code:
+
Source Code:

     
-    
-    ファイルに保存
+    CLI
     
    @@ -918,6 +918,7 @@ + diff --git a/installer/install.sh b/installer/install.sh index 955c546..8e6dcfa 100644 --- a/installer/install.sh +++ b/installer/install.sh @@ -6,6 +6,8 @@ curl -L https://raw.githubusercontent.com/tj/n/master/bin/n -o n sudo bash n 14.16.0 # Install latest version of n via npm globally # sudo npm install -g n +# install python code formatter +python3 -m pip install yapf # install desktop entry cp -r ./files/share ~/.local/ # install binary files if exists diff --git a/package.json b/package.json index 918675d..7b14ed8 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,7 @@ }, "homepage": "https://github.com/ocogeclub/ocoge#readme", "devDependencies": { - "electron": "^12.0.8", + "electron": "^13.1.5", "electron-rebuild": "^2.3.5" }, "dependencies": { @@ -27,4 +27,4 @@ "nodemailer": "^6.6.0", "ocoge_pigpiod": "file:local_modules/ocoge_pigpiod" } -} +} \ No newline at end of file diff --git a/scripts/eleclib.js b/scripts/eleclib.js index 48cbd3f..0f544ad 100644 --- a/scripts/eleclib.js +++ b/scripts/eleclib.js @@ -160,20 +160,22 @@ exports.saveFile = (data, ext) => { } // ファイル保存ダイアログ const selectSaveFile = ext => { - let filter; + let filter, filter_name; let defName; if (ext == 'xml') { filter = { name: 'xml file', extensions: ['xml'] }; defName = getUniqueFilepath() + '.xml'; - } else if (ext == 'js') { - filter = { name: 'javascript file', extensions: ['js'] }; + } else if (ext == 'js' || ext == 'py') { + if (ext == 'js') filter_name = 'javascript file'; + else filter_name = 'python file' + filter = { name: filter_name, extensions: [ext] }; // ワークスペース保存名がある場合、それをベースにファイル名の候補を決める if (saveFilepath === null) { - defName = getUniqueFilepath() + '.js'; + defName = getUniqueFilepath() + '.' + ext; } else { let dirname = path.dirname(saveFilepath); let basename = path.basename(saveFilepath, '.xml'); - defName = path.join(dirname, basename) + '.js'; + defName = path.join(dirname, basename) + '.' + ext; } } else { filter = { name: 'text file', extensions: ['txt'] }; diff --git a/scripts/ugj_blocks.js b/scripts/ugj_blocks.js index 8d9393e..3117ee5 100644 --- a/scripts/ugj_blocks.js +++ b/scripts/ugj_blocks.js @@ -2,68 +2,119 @@ const appDocRoot = '/home/pi/Documents/ocoge_docs/' /** Fix Basic Blocks ****************************************************************************************/ +var ugjConsrolForDefinition = { + "type": "ugj_control_for", + "message0": "%{BKY_UGJ_CONTROL_FOR_TITLE}", + "args0": [ + { + "type": "field_variable", + "name": "index", + "variable": "番号" + }, + { + "type": "input_dummy" + }, + { + "type": "input_value", + "name": "from", + "check": "Number" + }, + { + "type": "input_value", + "name": "to", + "check": "Number" + }, + { + "type": "input_value", + "name": "by", + "check": "Number" + }, + { + "type": "input_dummy" + }, + { + "type": "input_statement", + "name": "do" + } + ], + "inputsInline": true, + "previousStatement": null, + "nextStatement": null, + "style": "loop_blocks", + "tooltip": "%{BKY_UGJ_CONTROL_FOR_TOOLTIP}", + "helpUrl": "" +} Blockly.Blocks['ugj_control_for'] = { init: function () { - this.appendDummyInput() - .appendField(new Blockly.FieldVariable("番号"), "index"); - this.appendValueInput("from") - .setCheck("Number") - .appendField("を"); - this.appendValueInput("to") - .setCheck("Number") - .appendField("から"); - this.appendValueInput("by") - .setCheck("Number") - .appendField("まで"); - this.appendDummyInput() - .appendField("ずつ") - .appendField(new Blockly.FieldDropdown([["増やして", "increase"], ["減らして", "decrease"]]), "crease"); - this.appendStatementInput("do") - .setCheck(null); - this.setInputsInline(true); - this.setPreviousStatement(true, null); - this.setNextStatement(true, null); - this.setColour(Blockly.Msg.LOOPS_HUE); - this.setTooltip("インデックス番号を決められた数ずつ増やし(減らし)ながら、ステートメントを実行します。"); - this.setHelpUrl(""); + this.jsonInit(ugjConsrolForDefinition); } }; Blockly.JavaScript['ugj_control_for'] = function (block) { var variable_index = Blockly.JavaScript.variableDB_.getName(block.getFieldValue('index'), Blockly.Variables.NAME_TYPE); var value_from = Blockly.JavaScript.valueToCode(block, 'from', Blockly.JavaScript.ORDER_ATOMIC); var value_to = Blockly.JavaScript.valueToCode(block, 'to', Blockly.JavaScript.ORDER_ATOMIC); - var value_by = Blockly.JavaScript.valueToCode(block, 'by', Blockly.JavaScript.ORDER_ATOMIC); - var dropdown_crease = block.getFieldValue('crease'); + var value_by = Blockly.JavaScript.valueToCode(block, 'by', Blockly.JavaScript.ORDER_NONE); var statements_do = Blockly.JavaScript.statementToCode(block, 'do'); let daishou, tasuhiku; - if (dropdown_crease == 'increase') { daishou = '<'; tasuhiku = '+'; } + if (value_from < value_to) { daishou = '<'; tasuhiku = '+'; } else { daishou = '>'; tasuhiku = '-'; } var code = [ - `for (${variable_index} = ${value_from}; ${variable_index} ${daishou}= ${value_to}; ${variable_index} ${tasuhiku}= ${value_by}) {`, + `for (${variable_index} = ${value_from}; ${variable_index} ${daishou}= ${value_to}; ${variable_index} ${tasuhiku}= ${Math.abs(value_by)}) {`, statements_do, `}`, '' ].join('\n'); return code; }; +Blockly.Python['ugj_control_for'] = function (block) { + var variable_index = Blockly.Python.variableDB_.getName(block.getFieldValue('index'), Blockly.Variables.NAME_TYPE); + var value_from = Blockly.Python.valueToCode(block, 'from', Blockly.Python.ORDER_ATOMIC); + var value_to = Blockly.Python.valueToCode(block, 'to', Blockly.Python.ORDER_ATOMIC); + var value_by = Blockly.Python.valueToCode(block, 'by', Blockly.Python.ORDER_NONE); + var statements_do = Blockly.Python.statementToCode(block, 'do'); + if (statements_do === '') statements_do = ' pass'; + if (value_from < value_to) { value_by = Math.abs(value_by); value_to++; } + else { value_by = Math.abs(value_by) * (-1); value_to--; } + var code = [ + `for ${variable_index} in range(${value_from}, ${value_to}, ${value_by}) :`, + statements_do, + '' + ].join('\n'); + return code; +}; +var ugjForEachDefinition = { + "type": "ugj_controls_foreach", + "message0": "%{BKY_UGJ_FOREACH_TITLE}", + "args0": [ + { + "type": "input_value", + "name": "list", + "check": "Array" + }, + { + "type": "field_variable", + "name": "item", + "variable": "%{BKY_UGJ_FOREACH_ITEM}" + }, + { + "type": "input_dummy" + }, + { + "type": "input_statement", + "name": "do" + } + ], + "inputsInline": true, + "previousStatement": null, + "nextStatement": null, + "style": "loop_blocks", + "tooltip": "%{BKY_UGJ_FOREACH_TOOLTIP}", + "helpUrl": "" +} Blockly.Blocks['ugj_controls_forEach'] = { init: function () { - this.appendValueInput("list") - .setCheck("Array") - .appendField("リスト"); - this.appendDummyInput() - .appendField("の各") - .appendField(new Blockly.FieldVariable("項目"), "item") - .appendField("について"); - this.appendStatementInput("do") - .setCheck(null); - this.setInputsInline(true); - this.setPreviousStatement(true, null); - this.setNextStatement(true, null); - this.setColour(Blockly.Msg.LOOPS_HUE); - this.setTooltip("リストの各項目について、その項目を変数「項目」としてステートメントを実行します。"); - this.setHelpUrl(""); + this.jsonInit(ugjForEachDefinition); } }; Blockly.JavaScript['ugj_controls_forEach'] = function (block) { @@ -79,26 +130,18 @@ Blockly.JavaScript['ugj_controls_forEach'] = function (block) { ].join('\n'); return code; }; - -/** Additional Basic Blocks********************************************************************************* */ - -Blockly.Blocks['ugj_hextodec'] = { - init: function () { - this.appendValueInput("hex") - .setCheck("String") - .appendField("0x"); - this.setInputsInline(true); - this.setOutput(true, "Number"); - this.setOutputShape(Blockly.OUTPUT_SHAPE_ROUND); - this.setColour(Blockly.Msg.MATH_HUE); - this.setTooltip("16進数を10進数に変換します。"); - this.setHelpUrl(""); - } -}; -Blockly.JavaScript['ugj_hextodec'] = function (block) { - var value_hex = Blockly.JavaScript.valueToCode(block, 'hex', Blockly.JavaScript.ORDER_ATOMIC); - var code = `parseInt (${value_hex}, 16)`; - return [code, Blockly.JavaScript.ORDER_ATOMIC]; +Blockly.Python['ugj_controls_forEach'] = function (block) { + var value_list = Blockly.Python.valueToCode(block, 'list', Blockly.Python.ORDER_ATOMIC); + var variable_item = Blockly.Python.variableDB_.getName(block.getFieldValue('item'), Blockly.Variables.NAME_TYPE); + var statements_do = Blockly.Python.statementToCode(block, 'do'); + if (value_list === '') value_list = '[]'; + if (statements_do === '') statements_do = ' pass'; + var code = [ + `for ${variable_item} in ${value_list}:`, + statements_do, + '' + ].join('\n'); + return code; }; /** GPIO *****************************************************************************************************/ @@ -106,7 +149,7 @@ Blockly.JavaScript['ugj_hextodec'] = function (block) { /************* */ /** GPIO Start */ /************* */ -var ugjGpioStart = { +var ugjGpioStartDefinition = { "type": "ugj_gpio_start", "message0": "%{BKY_GPIO_START_TITLE}", "previousStatement": null, @@ -117,27 +160,44 @@ var ugjGpioStart = { }; Blockly.Blocks['ugj_gpio_start'] = { init: function () { - this.jsonInit(ugjGpioStart); + this.jsonInit(ugjGpioStartDefinition); } }; Blockly.JavaScript['ugj_gpio_start'] = function (block) { + Blockly.JavaScript.provideFunction_( + 'require_ocpig', [`const pi = require('ocoge_pigpiod');\n`] + ) var code = `pi.start();\n`; // return code; }; -// remote +Blockly.Python['ugj_gpio_start'] = function (block) { + Blockly.Python.provideFunction_( + 'import_pigpio', ['import pigpio'] + ) + var code = `pi = pigpio.pi()\n`; // + return code; +}; +// remote gpio +var ugjGpioStartRemoteDefinition = { + "type": "ugj_gpio_start_remote", + "message0": "%{BKY_GPIO_START_REMOTE_TITLE}", + "args0": [ + { + "type": "input_value", + "name": "host", + "check": "String" + } + ], + "inputsInline": true, + "previousStatement": null, + "nextStatement": null, + "tooltip": "%{BKY_GPIO_START_REMOTE_TOOLTIP}", + "helpUrl": "", + "style": "gpio_blocks" +}; Blockly.Blocks['ugj_gpio_start_remote'] = { init: function () { - this.appendValueInput("host") - .setCheck("String") - .appendField("ホスト"); - this.appendDummyInput() - .appendField("のGPIO を使えるようにする"); - this.setInputsInline(true); - this.setPreviousStatement(true, null); - this.setNextStatement(true, null); - this.setStyle('gpio_blocks') - this.setTooltip("他のマシンのリモートGPIOに接続します。"); - this.setHelpUrl(""); + this.jsonInit(ugjGpioStartRemoteDefinition); } }; Blockly.JavaScript['ugj_gpio_start_remote'] = function (block) { @@ -145,25 +205,19 @@ Blockly.JavaScript['ugj_gpio_start_remote'] = function (block) { var code = `pi.start_remote(${value_host}, '8888');\n`; // return code; }; +Blockly.Python['ugj_gpio_start_remote'] = function (block) { + Blockly.Python.provideFunction_( + 'import_pigpio', ['import pigpio'] + ) + var value_host = Blockly.Python.valueToCode(block, 'host', Blockly.Python.ORDER_ATOMIC); + var code = `pi = pigpio.pi(${value_host}, '8888')\n`; + return code; +}; /************ */ /** GPIO Stop */ /************ */ -// var ugjGpioStart = { -// "type": "ugj_gpio_start", -// "message0": "%{BKY_GPIO_START_TITLE}", -// "previousStatement": null, -// "nextStatement": null, -// "tooltip": "%{BKY_GPIO_START_TOOLTIP}", -// "helpUrl": "", -// "style": "gpio_blocks" -// }; -// Blockly.Blocks['ugj_gpio_start'] = { -// init: function () { -// this.jsonInit(ugjGpioStart); -// } -// }; -var ugjGpioStop = { +var ugjGpioStopDefinition = { "type": "ugj_gpio_stop", "message0": "%{BKY_GPIO_STOP_TITLE}", "previousStatement": null, @@ -174,21 +228,17 @@ var ugjGpioStop = { }; Blockly.Blocks['ugj_gpio_stop'] = { init: function () { - this.jsonInit(ugjGpioStop); - // this.appendDummyInput() - // .appendField("GPIO の後片付けをする"); - // this.setInputsInline(true); - // this.setPreviousStatement(true, null); - // this.setNextStatement(true, null); - // this.setStyle('gpio_blocks') - // this.setTooltip("GPIOとの接続を終了します。"); - // this.setHelpUrl(""); + this.jsonInit(ugjGpioStopDefinition); } }; Blockly.JavaScript['ugj_gpio_stop'] = function (block) { var code = 'pi.stop();\n'; return code; }; +Blockly.Python['ugj_gpio_stop'] = function (block) { + var code = `pi.stop()\n`; + return code; +}; /********************* */ /** GPIO Set Output ** */ @@ -875,15 +925,25 @@ Blockly.JavaScript['ugj_canvas_say'] = function (block) { /*************************** */ /** Canvas Initialization ** */ /*************************** */ +var ugj_canvas_init_definition = { + "type": "ugj_canvas_init", + "message0": "%{BKY_UGJ_CANVAS_INIT_TITLE}", + "previousStatement": null, + "nextStatement": null, + "tooltip": "%{BKY_UGJ_CANVAS_INIT_TOOLTIP}", + "helpUrl": "", + "style": "multimedia_blocks" +} Blockly.Blocks['ugj_canvas_init'] = { init: function () { - this.appendDummyInput() - .appendField("キャンバスを表示"); - this.setPreviousStatement(true, null); - this.setNextStatement(true, null); - this.setStyle('multimedia_blocks') - this.setTooltip("キャンバスを表示し、使用できるようにします。"); - this.setHelpUrl(""); + this.jsonInit(ugj_canvas_init_definition); + // this.appendDummyInput() + // .appendField("キャンバスを表示"); + // this.setPreviousStatement(true, null); + // this.setNextStatement(true, null); + // this.setStyle('multimedia_blocks') + // this.setTooltip("キャンバスを表示し、使用できるようにします。"); + // this.setHelpUrl(""); } }; Blockly.JavaScript['ugj_canvas_init'] = function (block) { diff --git a/scripts/ugj_script.js b/scripts/ugj_script.js index 5c177fb..1ad17ed 100644 --- a/scripts/ugj_script.js +++ b/scripts/ugj_script.js @@ -3,7 +3,6 @@ const testfunc = () => { } //============ User Customize Start =============== -// テーマ // カスタムブロックカラー定義 Blockly.HSV_SATURATION = 0.55; Blockly.HSV_VALUE = 0.75; @@ -12,7 +11,7 @@ var multimedia_color = '240'; var network_color = '340'; var special_color = '20'; var snippets_color = '90'; - +// テーマ var theme = Blockly.Theme.defineTheme('ocoge', { 'base': Blockly.Themes.Classic, 'startHats': true, @@ -63,15 +62,29 @@ Blockly.Msg["CONTROLS_IF_MSG_THEN"] = "ならば"; Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"] = ""; Blockly.Msg["MATH_CHANGE_TITLE"] = "変数 %1 を %2 増やす"; Blockly.Msg["VARIABLES_SET"] = "変数 %1 を %2 にする"; -Blockly.Msg["TEXT_PRINT_TITLE"] = "ダイアログに %1 を表示"; +// Blockly.Msg["TEXT_PRINT_TITLE"] = "ダイアログに %1 を表示"; Blockly.Msg["LOGIC_BOOLEAN_FALSE"] = "偽"; Blockly.Msg["LOGIC_BOOLEAN_TOOLTIP"] = "真 または 偽 を返します。"; Blockly.Msg["LOGIC_BOOLEAN_TRUE"] = "真"; // ローカライズ対応の準備 +Blockly.Msg["UGJ_CONTROL_FOR_TITLE"] = "%1 %2 を %3 から %4 まで %5 ずつ増や(減ら)して %6 %7"; +Blockly.Msg["UGJ_CONTROL_FOR_INDEX"] = "番号"; +Blockly.Msg["UGJ_CONTROL_FOR_INCREASE"] = "増やして"; +Blockly.Msg["UGJ_CONTROL_FOR_DECREASE"] = "減らして"; +Blockly.Msg["UGJ_CONTROL_FOR_TOOLTIP"] = "インデックス番号を決められた数ずつ増やし(減らし)ながら、ステートメントを実行します。"; +Blockly.Msg["UGJ_FOREACH_TITLE"] = "リスト %1 の各 %2 について %3 %4"; +Blockly.Msg["UGJ_FOREACH_ITEM"] = "項目"; +Blockly.Msg["UGJ_FOREACH_TOOLTIP"] = "リストの各項目について、その項目を変数「項目」としてステートメントを実行します。"; + Blockly.Msg["GPIO_START_TITLE"] = "GPIO を使えるようにする"; Blockly.Msg["GPIO_START_TOOLTIP"] = "GPIOを初期化して接続します。"; Blockly.Msg["GPIO_STOP_TITLE"] = "GPIO の後片付けをする"; Blockly.Msg["GPIO_STOP_TOOLTIP"] = "GPIOとの接続を終了します。"; +Blockly.Msg["GPIO_START_REMOTE_TITLE"] = "ホスト %1 のGPIO を使えるようにする"; +Blockly.Msg["GPIO_START_REMOTE_TOOLTIP"] = "他のマシンのリモートGPIOに接続します。"; + +Blockly.Msg["UGJ_CANVAS_INIT_TITLE"] = "キャンバスを表示"; +Blockly.Msg["UGJ_CANVAS_INIT_TOOLTIP"] = "キャンバスを表示し、使用できるようにします。"; // Customize Toolbox class CustomCategory extends Blockly.ToolboxCategory { @@ -232,25 +245,57 @@ const ugj_loadWorkspace = () => { } } +// // Python コードフォーマッタ YAPF をコール +// const ugj_pyBeautify = (code) => { +// let formatted; +// formatted = require('child_process').spawnSync('python3', ['-m', 'yapf'], { input: code }).stdout.toString(); +// return formatted; +// } +// Python コードフォーマッタ Black をコール +const ugj_pyBeautify = (code) => { + let formatted; + formatted = require('child_process').spawnSync('python3', ['-m', 'black', '-'], { input: code }).stdout.toString(); + return formatted; +} + // ワークスペースからコードを生成して必要であれば整形処理をする const ugj_createCode = (args) => { addAsync = args.async || false; beautify = args.beautify || false; + prettify = args.prettify || false; + ext = args.ext || 'js'; - let code = Blockly.JavaScript.workspaceToCode(workspace); + let code, requires; + if (ext == 'py') { // Python コード出力 + try { + code = Blockly.Python.workspaceToCode(workspace); + } catch (e) { // Pythonコードを持たないブロックがある場合 + window.alert('Python 非対応のブロックが使用されています。\n' + e.message); + } + code = Blockly.Python.workspaceToCode(workspace); + // 追加モジュールのrequire 本当は import + requires = [ + // ['_gpio_', false, `import pigpio\n`] + ] + } + else { // Javascript コード出力 + code = Blockly.JavaScript.workspaceToCode(workspace); + // 追加モジュールのrequire + requires = [ + // ['_gpio_', false, `const pi = require('ocoge_pigpiod');\n`], + ['_axios_', false, `const axios = require('axios');\n`], + ['_sendmail', false, `const nodemailer = require('nodemailer');\n`], + ['_cloudspeech_', false, `const speech = require('@google-cloud/speech');\nconst recorder = require('node-record-lpcm16');\n`], + ['_httpserver', false, `const http = require('http');\n`], + ['_file_', false, `const fs = require('fs');\n`], + // ['_bme280', false, `const BME280 = require('bme280-sensor');`], + ['_dht', false, `const dht = require("node-dht-sensor").promises;`], + ['_socket_', false, `const net = require('net');`] + ]; - // 追加モジュールのrequire - let requires = [ - ['_gpio_', false, `const pi = require('ocoge_pigpiod');\n`], - ['_axios_', false, `const axios = require('axios');\n`], - ['_sendmail', false, `const nodemailer = require('nodemailer');\n`], - ['_cloudspeech_', false, `const speech = require('@google-cloud/speech');\nconst recorder = require('node-record-lpcm16');\n`], - ['_httpserver', false, `const http = require('http');\n`], - ['_file_', false, `const fs = require('fs');\n`], - // ['_bme280', false, `const BME280 = require('bme280-sensor');`], - ['_dht', false, `const dht = require("node-dht-sensor").promises;`], - ['_socket_', false, `const net = require('net');`] - ]; + } + + // import/require の要不要をワークスペース内の全てのブロックに対してチェック let blockArray = workspace.getAllBlocks(); blockArray.forEach(value => { for (var i = 0, l = requires.length; i < l; i++) { @@ -261,17 +306,23 @@ const ugj_createCode = (args) => { if (requires[i][1]) code = requires[i][2] + code; } - // await使用のため、必要に応じてコード全体をasync付き即時関数でラップ - if (addAsync) { - code = [ - '(async () => {', - code, - '})();' - ].join('\n'); + if (ext == 'py') { //Python + // コードを綺麗に + if (beautify) code = ugj_pyBeautify(code); + } else { // JavaScript + // await使用のため、必要に応じてコード全体をasync付き即時関数でラップ + if (addAsync) { + code = [ + '(async () => {', + code, + '})();' + ].join('\n'); + } + // コードを綺麗に + if (beautify) code = js_beautify(code, { indent_size: 2 }); } - - // コードを綺麗に - if (beautify) code = js_beautify(code, { indent_size: 2 }); + // シンタックスハイライト(HTML化): 先に HTML エンティティをエスケープ + if (prettify) code = PR.prettyPrintOne(ugj_htmlEntities(code), ext, true); return code; } @@ -287,19 +338,23 @@ const ugj_runCode = () => { } } -// JavaScriptコードをダイアログで表示・保存 -// エレメントのオブジェクトとかコールバックとか +// コードをダイアログで表示・保存 +// エレメントのオブジェクトとかコールバックとか Python対応とか // 色々この中で完結させてみる const ugj_showCode = () => { + var ext = 'js'; const dialog = document.getElementById('codeDlg'); const content = document.getElementById('dlgContent'); const btn_close = document.getElementById('dlgClose'); const btn_export = document.getElementById('dlgExport'); const chkbox_cli = document.getElementById('dlgCli'); - let code = ugj_createCode({ 'beautify': true }); - code = ugj_htmlEntities(code); - content.innerHTML = PR.prettyPrintOne(code, 'js', true); + const dialog_title = document.getElementById('dlgTitle'); + + const showCode = () => + content.innerHTML = ugj_createCode({ 'beautify': true, 'ext': ext, 'prettify': true }); + + showCode(); dialog.showModal(); @@ -309,18 +364,30 @@ const ugj_showCode = () => { btn_export.removeEventListener('click', export_cb); } const export_cb = () => { - code = ugj_createCode({ 'async': true, 'beautify': true }); - // blackboardWrite()をconsole.log()に書き換え、 + code = ugj_createCode({ 'ext': ext, 'async': true, 'beautify': true }); + // blackboardWrite()とwindow.alert()をconsole.log()に書き換え、 // document... と ugj_... と elec... をコメントアウト(ブラウザ関連部分の追放という意味では不完全なので注意) - if (chkbox_cli.checked) - code = code.replace(/const appendDiv[^#]*\/\/#/gm, 'const blackboardWrite = text => console.log(text);').replace(/(^(?=.*document.)[^;]*;)/gm, '/* $1 */').replace(/(^(?=.*ugj_)[^;]*;)/gm, '/* $1 */').replace(/(^(?=.*elec.)[^;]*;)/gm, '/* $1 */'); - if (elec.saveFile(code, 'js') === false) { + if (chkbox_cli.checked && ext == 'js') + code = code.replace(/const appendDiv[^#]*\/\/#/gm, 'const blackboardWrite = text => console.log(text);').replace('window.alert', 'console.log').replace(/(^(?=.*document.)[^;]*;)/gm, '/* $1 */').replace(/(^(?=.*ugj_)[^;]*;)/gm, '/* $1 */').replace(/(^(?=.*elec.)[^;]*;)/gm, '/* $1 */'); + if (elec.saveFile(code, ext) === false) { alert('保存できませんでした。'); } close_cb(); } btn_close.addEventListener('click', close_cb); btn_export.addEventListener('click', export_cb); + document.addEventListener('keypress', (ev) => { + if (ev.key == 'p' && ext == 'js') { + ext = 'py'; + showCode(); + } + }); + document.addEventListener('keyup', (ev) => { + if (ev.key == 'p') { + ext = 'js'; + showCode(); + } + }); } @@ -426,6 +493,11 @@ const ugj_fukidashi = (text, sec) => { // https://qiita.com/horikeso/items/95595f379a8dfa63c34a } +// コードジェネレータモード(Javascript/Python切り替え) +var isPyMode; +const ugj_pyMode = (checked) => isPyMode = checked; + + //===================================== //======= Blockly GUI codes =========== // Use in a block or block definition: @@ -514,6 +586,7 @@ window.onload = () => { window.onbeforeunload = () => { ugj_saveWorkspace(); elec.savePrefsToLS(); + elec.killAllChildren(); } // Electron動作とブラウザ動作を自動で仕分け