<commit_before>/*
 *  Copyright 2016 Google Inc. All Rights Reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.tharvey.blocklybot;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.google.blockly.android.AbstractBlocklyActivity;
import com.google.blockly.android.codegen.CodeGenerationRequest;
import com.google.blockly.android.control.BlocklyController;
import com.google.blockly.android.ui.BlockViewFactory;
import com.google.blockly.android.ui.WorkspaceHelper;
import com.google.blockly.android.ui.vertical.VerticalBlockViewFactory;

import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * Simplest implementation of AbstractBlocklyActivity.
 */
public class BlocklyActivity extends AbstractBlocklyActivity implements IConnection {
    private static final String TAG = "BlocklyActivity";
    public static final String SAVED_WORKSPACE_FILENAME_DEFAULT = "robot_workspace.xml";
    private static final List<String> BLOCK_DEFINITIONS = Arrays.asList(new String[]{
            "default/loop_blocks.json",
            "default/logic_blocks.json",
            "default/math_blocks.json",
            "default/variable_blocks.json",
            "control_blocks.json",
            "robot_blocks.json",
            "speech_blocks.json",
            "audio_blocks.json"
    });
    private static final List<String> JAVASCRIPT_GENERATORS = Arrays.asList(new String[]{
            "robot_generators.js"
    });

    private ActionBar action;
    private File FILE_DIR;
    private AlertDialog alertNew, alertRename;
    private EditText editTextNew, editTextRename;
    private String workspaceName;
    static private Mobbob mRobot;
    static private JSParser mParser;
    SharedPreferences mPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        action = getSupportActionBar();
        FILE_DIR = getFilesDir();
        editTextNew = new EditText(this);
        editTextRename = new EditText(this);

        /* Text input alertBuilder for rename/new workspace actions */
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setView(editTextRename);
        alertBuilder.setCancelable(true);
        alertBuilder.setTitle("Rename Current Workspace");
        alertBuilder.setPositiveButton("OK", renameWorkspace);
        alertRename = alertBuilder.create();

        alertBuilder.setView(editTextNew);
        alertBuilder.setTitle("Enter New Workspace Name");
        alertBuilder.setPositiveButton("OK", newWorkspace);
        alertNew = alertBuilder.create();

        mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        workspaceName = mPreferences.getString("pref_lastWorkspace", SAVED_WORKSPACE_FILENAME_DEFAULT);

        mParser = new JSParser(this);
        mRobot = Mobbob.getMobob();

        /* Autoload last workspace */
        onLoadWorkspace();
    }

    private final CodeGenerationRequest.CodeGeneratorCallback mCodeGeneratorCallback =
            new CodeGenerationRequest.CodeGeneratorCallback() {
        @Override
        public void onFinishCodeGeneration(final String generatedCode) {
            Log.i(TAG, "generatedCode:\n" + generatedCode);
            Toast.makeText(getApplicationContext(), generatedCode, Toast.LENGTH_LONG).show();
            mParser.parseCode(mRobot, generatedCode);
        }
    };

    @Override
    public void connectionStateChanged(connectionStateEnum state) {
        Log.i(TAG, "connection state changed:" + state);
        mRobot = Mobbob.getMobob();
        updateTitlebar();
    }

    private void updateTitlebar() {
        if (mRobot != null && mRobot.getConnectionState() == connectionStateEnum.isConnected)
            action.setTitle(mRobot.getName() + " : " + workspaceName.replace(".xml", ""));
        else
            action.setTitle(workspaceName.replace(".xml", ""));
        SharedPreferences.Editor editor = mPreferences.edit();
        editor.putString("pref_lastWorkspace", workspaceName);
        editor.commit();
    }

    @Override
    public void onLoadWorkspace() {
        loadWorkspaceFromAppDir(workspaceName);
	    addDefaultVariables(getController());
        updateTitlebar();
    }

    @Override
    public void onSaveWorkspace() {
        saveWorkspaceToAppDir(workspaceName);<commit_msg>BlocklyActivity: catch exceptions around workspace loading<commit_after>/*
 *  Copyright 2016 Google Inc. All Rights Reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.tharvey.blocklybot;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.google.blockly.android.AbstractBlocklyActivity;
import com.google.blockly.android.codegen.CodeGenerationRequest;
import com.google.blockly.android.control.BlocklyController;
import com.google.blockly.android.ui.BlockViewFactory;
import com.google.blockly.android.ui.WorkspaceHelper;
import com.google.blockly.android.ui.vertical.VerticalBlockViewFactory;
import com.google.blockly.model.BlocklyParserException;

import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * Simplest implementation of AbstractBlocklyActivity.
 */
public class BlocklyActivity extends AbstractBlocklyActivity implements IConnection {
    private static final String TAG = "BlocklyActivity";
    public static final String SAVED_WORKSPACE_FILENAME_DEFAULT = "robot_workspace.xml";
    private static final List<String> BLOCK_DEFINITIONS = Arrays.asList(new String[]{
            "default/loop_blocks.json",
            "default/logic_blocks.json",
            "default/math_blocks.json",
            "default/variable_blocks.json",
            "control_blocks.json",
            "robot_blocks.json",
            "speech_blocks.json",
            "audio_blocks.json"
    });
    private static final List<String> JAVASCRIPT_GENERATORS = Arrays.asList(new String[]{
            "robot_generators.js"
    });

    private ActionBar action;
    private File FILE_DIR;
    private AlertDialog alertNew, alertRename;
    private EditText editTextNew, editTextRename;
    private String workspaceName;
    static private Mobbob mRobot;
    static private JSParser mParser;
    SharedPreferences mPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        action = getSupportActionBar();
        FILE_DIR = getFilesDir();
        editTextNew = new EditText(this);
        editTextRename = new EditText(this);

        /* Text input alertBuilder for rename/new workspace actions */
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertBuilder.setView(editTextRename);
        alertBuilder.setCancelable(true);
        alertBuilder.setTitle("Rename Current Workspace");
        alertBuilder.setPositiveButton("OK", renameWorkspace);
        alertRename = alertBuilder.create();

        alertBuilder.setView(editTextNew);
        alertBuilder.setTitle("Enter New Workspace Name");
        alertBuilder.setPositiveButton("OK", newWorkspace);
        alertNew = alertBuilder.create();

        mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        workspaceName = mPreferences.getString("pref_lastWorkspace", SAVED_WORKSPACE_FILENAME_DEFAULT);

        mParser = new JSParser(this);
        mRobot = Mobbob.getMobob();

        /* Autoload last workspace */
        onLoadWorkspace();
    }

    private final CodeGenerationRequest.CodeGeneratorCallback mCodeGeneratorCallback =
            new CodeGenerationRequest.CodeGeneratorCallback() {
        @Override
        public void onFinishCodeGeneration(final String generatedCode) {
            Log.i(TAG, "generatedCode:\n" + generatedCode);
            Toast.makeText(getApplicationContext(), generatedCode, Toast.LENGTH_LONG).show();
            mParser.parseCode(mRobot, generatedCode);
        }
    };

    @Override
    public void connectionStateChanged(connectionStateEnum state) {
        Log.i(TAG, "connection state changed:" + state);
        mRobot = Mobbob.getMobob();
        updateTitlebar();
    }

    private void updateTitlebar() {
        if (mRobot != null && mRobot.getConnectionState() == connectionStateEnum.isConnected)
            action.setTitle(mRobot.getName() + " : " + workspaceName.replace(".xml", ""));
        else
            action.setTitle(workspaceName.replace(".xml", ""));
        SharedPreferences.Editor editor = mPreferences.edit();
        editor.putString("pref_lastWorkspace", workspaceName);
        editor.commit();
    }

    @Override
    public void onLoadWorkspace() {
	    try {
		    loadWorkspaceFromAppDir(workspaceName);
	    } catch (BlocklyParserException e) {
		    // failed to parse xml
	    }
	    addDefaultVariables(getController());
        updateTitlebar();
    }

    @Override
    public void onSaveWorkspace() {
        saveWorkspaceToAppDir(workspaceName);
{'fraction_non_alphanumeric': 0.0918218327856882, 'fraction_numerical': 0.0018254837531945967, 'mean_word_length': 3.557820299500832, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 7}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6615286', 'n_tokens_mistral': 2942, 'n_tokens_neox': 2890, 'n_words': 676}