Android关于Blockly对Workspace中的block数据保存及读取的流程,及改造原生代码实现Trash垃圾桶中的block保存及读取
一.Blockly对Workspace中的block数据保存及读取的流程源码分析:
1.Workspace的自动保存:在AbstractBlocklyActivity中
有onAutosave()的方法用于对Workspace的block数据进行保存。保存的流程如下
1).在AbstractBlocklyActivity的onAutosave(),获取自动保存的路径:
/** * Called when an autosave of the workspace is triggered, typically by {@link #onPause()}. * By default this saves the workspace to a file in the app's directory. */ protected void onAutosave() { try { mBlocklyActivityHelper.saveWorkspaceToAppDir(getWorkspaceAutosavePath()); //获取自动保存Workspace的block数据的路径 } catch (FileNotFoundException | BlocklySerializerException e) { Log.e(TAG, "Failed to autosaving workspace.", e); } }
2).
在BlocklyActivityHelper中获取到Wrokspace的对象对传入的文件路径,进行serialToXml序列化到xml的操作:
/** * Save the workspace to the given file in the application's private data directory, and show a * status toast. If the save fails, the error is logged. */ public void saveWorkspaceToAppDir(String filename) throws FileNotFoundException, BlocklySerializerException{ Workspace workspace = mWorkspaceFragment.getWorkspace(); workspace.serializeToXml(mActivity.openFileOutput(filename, Context.MODE_PRIVATE)); //将Workspace的数据序列化到xml文件保存 }
3).在Workspace中能获取到画布中的block的集合mRootBlocks,最终把这mRootBlocks和文件路径交给BlocklyXmlHelper
实现具体的数据序列化到XML中保存:
/** * Outputs the workspace as an XML string. * * @param os The output stream to write to. * @throws BlocklySerializerException if there was a failure while serializing. */ public void serializeToXml(OutputStream os) throws BlocklySerializerException { BlocklyXmlHelper.writeToXml(mRootBlocks, os, IOOptions.WRITE_ALL_DATA);//在拖Workspace的mRootBlocks的block写到xml文件中,mRootBlocks即是连接到画布中的block块的集合 }
4).BlocklyXmlHelper具体到把每个block块的数据以tag的形式存在xml中:
/** * Serializes all Blocks in the given list and writes them to the given output stream. * * @param toSerialize A list of Blocks to serialize. * @param os An OutputStream to write the blocks to. * @param options The options to configure the block serialization. If omitted, * {@link IOOptions#WRITE_ALL_DATA} will be used by default. * * @throws BlocklySerializerException */ public static void writeToXml(@NonNull List<Block> toSerialize, @NonNull OutputStream os, @Nullable IOOptions options) throws BlocklySerializerException { writeToXmlImpl(toSerialize, os, null, options); }
/** * Serializes all Blocks in the given list and writes them to the either the output stream or * writer, whichever is not null. * * @param toSerialize A list of Blocks to serialize. * @param os An OutputStream to write the blocks to. * @param writer A writer to write the blocks to, if {@code os} is null. * @param options The options to configure the block serialization. If omitted, * {@link IOOptions#WRITE_ALL_DATA} will be used by default. * * @throws BlocklySerializerException */ public static void writeToXmlImpl(final @NonNull List<Block> toSerialize, @Nullable OutputStream os, @Nullable Writer writer, @Nullable IOOptions options) throws BlocklySerializerException { final IOOptions finalOptions = options == null ? IOOptions.WRITE_ALL_DATA : options; XmlContentWriter contentWriter = new XmlContentWriter() { @Override public void write(XmlSerializer serializer) throws IOException { serializer.setPrefix("", XML_NAMESPACE); serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); serializer.startTag(XML_NAMESPACE, "xml"); for (int i = 0; i < toSerialize.size(); i++) { //遍历每个block块以tag的形式存在xml中 toSerialize.get(i).serialize(serializer, true, finalOptions); } serializer.endTag(XML_NAMESPACE, "xml"); } }; try { if (os != null) { writeXml(os, contentWriter); } else { writeXml(writer, contentWriter); } } catch (IOException e) { throw new BlocklySerializerException(e); } }
以上就是Workspace中的block自动保存的流程。
2.Workspace的自动加载:在AbstractBlocklyActivity中有onAutoload()的方法用于对保存在xml里Workspace的block数据
读取并加载显示到Workspace。保存的流程如下
1).在AbstractBlocklyActivity的onAutoload(),获取自动保存的路径把路径传给BlocklyActivityHelper:
/** * Called when the activity tries to restore the autosaved workspace, typically by * {@link #onCreate(Bundle)} if there was no workspace data in the bundle. * * @return true if a previously saved workspace was loaded, false otherwise. */ protected boolean onAutoload() { String filePath = getWorkspaceAutosavePath(); try { mBlocklyActivityHelper.loadWorkspaceFromAppDir(filePath); return true; } catch (FileNotFoundException e) { // No workspace was saved previously. } catch (BlockLoadingException | IOException e) { Log.e(TAG, "Failed to load workspace", e); mBlocklyActivityHelper.getController().resetWorkspace(); File file = getFileStreamPath(filePath); if (!file.delete()) { Log.e(TAG, "Failed to delete corrupted autoload workspace: " + filePath); } } return false; }
2).BlocklyActivityHelper获取到BlocklyController的实例接收自动保存的路径:
/** * Loads the workspace from the given file in the application's private data directory. * @param filename The path to the file, in the application's local storage. * @throws IOException If there is a underlying problem with the input. * @throws BlockLoadingException If there is a error with the workspace XML format or blocks. */ public void loadWorkspaceFromAppDir(String filename) throws IOException, BlockLoadingException { mController.loadWorkspaceContents(mActivity.openFileInput(filename)); //把路径传到BlocklyController }
3).BlocklyController中操作Workspace读取数据并显示把数据转成block显示在画布中:
/** * Reads the workspace in from a XML stream. This will clear the workspace and replace it with * the contents of the xml. * * @param workspaceXmlStream The input stream to read from. * @return True if successful. Otherwise, false with error logged. */ public void loadWorkspaceContents(InputStream workspaceXmlStream) throws BlockLoadingException { mWorkspace.loadWorkspaceContents(workspaceXmlStream); //在Workspace读取保存的数据 initBlockViews(); //初始化所读取到的block数据显示在画布中 }
4).在保存的流程可以知道,Workspace是保存中数据的源头,同样是读取加载数据后显示的源头:
/** * Reads the workspace in from a XML stream. This will clear the workspace and replace it with * the contents of the xml. * * @param is The input stream to read from. * @throws BlockLoadingException If workspace was not loaded. May wrap an IOException or another * BlockLoadingException. */ public void loadWorkspaceContents(InputStream is) throws BlockLoadingException { List<Block> newBlocks = BlocklyXmlHelper.loadFromXml(is, mBlockFactory); //读取自动保存数据转成block的集合 // Successfully deserialized. Update workspace. // TODO: (#22) Add proper variable support. // For now just save and restore the list of variables. Set<String> vars = mVariableNameManager.getUsedNames(); mController.resetWorkspace(); for (String varName : vars) { mController.addVariable(varName); } mRootBlocks.addAll(newBlocks); //将加载的block的集合加载到mRootBlocks mStats.collectStats(newBlocks, true /* recursive */); }
5).Workspace中block数据的保存和读取都是转交给BlocklyXmlHelper进行具体的数据的序列化操作的:
/** * Convenience function that creates a new {@link ArrayList}. * @param inputXml The input stream of XML from which to read. * @throws BlockLoadingException If any error occurs with the input. It may wrap an IOException * or XmlPullParserException as a root cause. */ public static List<Block> loadFromXml(InputStream inputXml, BlockFactory blockFactory) throws BlockLoadingException { List<Block> result = new ArrayList<>(); loadBlocksFromXml(inputXml, null, blockFactory, result); return result; }
保存的xml数据解析成一个个的block块:
/** * Loads a list of top-level Blocks from XML. Each top-level Block may have many Blocks * contained in it or descending from it. * * @param inStream The input stream to read blocks from. Maybe null. * @param inString The xml string to read blocks from if {@code insStream} is null. * @param blockFactory The BlockFactory for the workspace where the Blocks are being loaded. * @param result An list (usually empty) to append new top-level Blocks to. * * @throws BlockLoadingException If any error occurs with the input. It may wrap an IOException * or XmlPullParserException as a root cause. */ private static void loadBlocksFromXml( InputStream inStream, String inString, BlockFactory blockFactory, List<Block> result) throws BlockLoadingException { StringReader reader = null; try { XmlPullParser parser = PARSER_FACTORY.newPullParser(); if (LOG_INPUT_XML) { if (inStream != null) { StringBuilder sb = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(inStream)); String line = br.readLine(); while (line != null) { sb.append(line).append('\n'); line = br.readLine(); } br.close(); inStream = null; inString = sb.toString(); } Log.d(TAG, "BlocklyXmlHelper.loadBlocksFromXml()\n" + inString); } if (inStream != null) { parser.setInput(inStream, null); } else { reader = new StringReader(inString); parser.setInput(reader); } int eventType = parser.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_TAG: if (parser.getName() == null) { throw new BlockLoadingException("Malformed XML; aborting."); } if (parser.getName().equalsIgnoreCase("block")) { result.add(blockFactory.fromXml(parser)); } else if (parser.getName().equalsIgnoreCase("shadow")) { throw new IllegalArgumentException( "Shadow blocks may not be top level blocks."); } break; default: break; } eventType = parser.next(); } } catch (XmlPullParserException | IOException e) { throw new BlockLoadingException(e); } if (reader != null) { reader.close(); } }
二、对于Trash垃圾桶所涉及的逻辑分析:
1.如图,是原生Blockly中关于Trash的逻辑。点击Trash垃圾桶就会把用户的删除的block:
2).接下来分析,Trash中的逻辑是怎么添加到代码中去的,a.首先在AbstractBlocklyFragment依附在
AbstractBlocklyActivity时已经在onCreatView()创建BlocklyActivityHelper,这样就把关于业务逻辑交给了
BlocklyActivityHelper处理;b.接下来在BlocklyActivityHelper的构造方法中初始一系列化的帮助类,实例化帮助类之后
用BlocklyController建造者模式构建出每个模块的UI及业务逻辑处理;c.BlocklyController中管控着所有block的操作,
其下属FlyoutController控制器管控着ToolBox和Trash的界面显示和关闭;d.而本篇博客要分析的Trash垃圾桶Block的数据
的来源最终来自Workspace,存储在Trash垃圾桶Block的数据保存在对象BlocklyCategory里的mItem字段中。
3).用Blockly的源码来体现2)中描述的逻辑流程:
a.首先在AbstractBlocklyFragment依附在AbstractBlocklyActivity时已经在onCreatView()创建
BlocklyActivityHelper,这样就把关于业务逻辑交给了BlocklyActivityHelper处理:
/** * Creates the activity's views and subfragments (via {@link #onCreateSubViews}, and then * initializes Blockly via {@link #onCreateActivityHelper()}, using the values from * {@link #getBlockDefinitionsJsonPaths} and {@link #getToolboxContentsXmlPath}. * Subclasses should override those methods to configure the Blockly environment. * <p/> * Once the controller and fragments are configured, if {@link #checkAllowRestoreBlocklyState} * returns true, the activity will attempt to load a prior workspace from the instance state * bundle. If no workspace is loaded, it defers to {@link #onLoadInitialWorkspace}. */ @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mRootView = onCreateSubViews(inflater); //创建AbstractBlocklyFragment时实例化BlocklyActivityHelper,把有关于业务逻辑都交给BlocklyActivityHelper处理 mBlocklyActivityHelper = onCreateActivityHelper(); if (mBlocklyActivityHelper == null) { throw new IllegalStateException("BlocklyActivityHelper is null. " + "onCreateActivityHelper must return a instance."); } resetBlockFactory(); // Initial load of block definitions, extensions, and mutators. configureCategoryFactories(); // After BlockFactory; before Toolbox reloadToolbox(); // Load the workspace. boolean loadedPriorInstance = checkAllowRestoreBlocklyState(savedInstanceState) && (getController().onRestoreSnapshot(savedInstanceState) || onAutoload()); if (!loadedPriorInstance) { onLoadInitialWorkspace(); } setHasOptionsMenu(true); return mRootView; }
b.接下来在BlocklyActivityHelper的构造方法中初始一系列化的帮助类,实例化帮助类之后
用BlocklyController建造者模式构建出每个模块的UI及业务逻辑处理:
/** * Creates the activity helper and initializes Blockly. Must be called during * {@link Activity#onCreate}. Executes the following sequence of calls during initialization: * <ul> * <li>{@link #onFindFragments} to find fragments</li> * <li>{@link #onCreateBlockViewFactory}</li> * </ul> * Subclasses should override those methods to configure the Blockly environment. * * @throws IllegalStateException If error occurs during initialization. Assumes all initial * compile-time assets are known to be valid. */ public BlocklyActivityHelper(AppCompatActivity activity, FragmentManager fragmentManager) { mActivity = activity; onFindFragments(fragmentManager); if (mWorkspaceFragment == null) { throw new IllegalStateException("mWorkspaceFragment is null"); } //初始实例化帮助类 mWorkspaceHelper = new WorkspaceHelper(activity); mBlockViewFactory = onCreateBlockViewFactory(mWorkspaceHelper); mClipDataHelper = onCreateClipDataHelper(); mCodeGeneratorManager = new CodeGeneratorManager(activity); //用BlocklyController建造者模式构建出每个模块的UI及业务逻辑处理 BlocklyController.Builder builder = new BlocklyController.Builder(activity) .setClipDataHelper(mClipDataHelper) .setWorkspaceHelper(mWorkspaceHelper) .setBlockViewFactory(mBlockViewFactory) .setWorkspaceFragment(mWorkspaceFragment) .setTrashUi(mTrashBlockList) //设置Trash中的UI及业务逻辑实现 .setToolboxUi(mToolboxBlockList, mCategoryFragment); mController = builder.build(); onCreateVariableCallback(); onCreateMutatorListener(); onConfigureTrashIcon(); onConfigureZoomInButton(); onConfigureZoomOutButton(); onConfigureCenterViewButton(); }
BlocklyController中建造者模式的构建:
/** * Create a new workspace using the configuration in this builder. * * @return A new {@link BlocklyController}. */ public BlocklyController build() { if (mViewFactory == null && (mWorkspaceFragment != null || mTrashUi != null || mToolbox != null || mCategoryUi != null)) { throw new IllegalStateException( "BlockViewFactory cannot be null when using UIs."); } if (mWorkspaceHelper == null) { mWorkspaceHelper = new WorkspaceHelper(mContext); } BlockClipDataHelper blockClipDataHelper = mClipHelper; if (blockClipDataHelper == null) { blockClipDataHelper = SingleMimeTypeClipDataHelper.getDefault(mContext); } BlockFactory factory = new BlockFactory(); loadBlockDefinitionsFromResources(factory, mBlockDefResources); loadBlockDefinitionsFromAssets(factory, mBlockDefAssets); BlocklyController controller = new BlocklyController( mContext, factory, mWorkspaceHelper, blockClipDataHelper, mViewFactory); loadToolbox(controller); // Any of the following may be null and result in a no-op. controller.setWorkspaceFragment(mWorkspaceFragment); controller.setTrashUi(mTrashUi); //在BlocklyController以建造者模式构建的时候设置了Trash垃圾桶的具体逻辑实现 controller.setToolboxUi(mToolbox, mCategoryUi); controller.setTrashIcon(mTrashIcon); controller.setVariableCallback(mVariableCallback); return controller; }
c.BlocklyController中管控着所有block的操作,其下属FlyoutController控制器管控着ToolBox和
Trash的界面显示和关闭:
BlocklyController的setTrashUi()方法是设置数据的来源:
/** * Connects a {@link BlockListUI} for the trash to this controller. * * @param trashUi */ public void setTrashUi(@Nullable BlockListUI trashUi) { if (trashUi != null && mViewFactory == null) { throw new IllegalStateException("Cannot set UIs without a BlockViewFactory."); } //BlocklyController中管控着所有Block的操作,其下属FlyoutController控制器管控着 //ToolBox和Trash能关闭显示的控制 mFlyoutController.setTrashUi(trashUi); //给从Workspace拿到TrashCategory的内容设置到FlyoutController mFlyoutController.setTrashContents(mWorkspace.getTrashCategory()); }
在BlocklyController的setTrashIcon()方法是设置Trash的图标及内部逻辑实现:
/** * Assigns the view used for opening/closing the trash. * * @param trashIcon The trash icon for dropping blocks. */ public void setTrashIcon(View trashIcon) { //设置Trash的图标及其内部逻辑实现初始化 mFlyoutController.setTrashIcon(trashIcon); }
在FlyoutController的setTrashIcon()设置Trash的打开及关闭的监听:
/** * @param trashIcon The view for toggling the trash. */ public void setTrashIcon(View trashIcon) { if (trashIcon == null) { return; } // The trash icon is always a drop target. trashIcon.setOnDragListener(new OnDragToTrashListener(mController)); if (mTrashUi != null && mTrashIsCloseable) { // But we only need a click listener if the trash can be closed. trashIcon.setOnClickListener(mTrashClickListener);//设置Trash的打开及关闭的监听 } }
/** Opens/closes the trash in response to clicks on the trash icon. */ protected View.OnClickListener mTrashClickListener = new View.OnClickListener() { @Override public void onClick(View v) { // Toggle opened state. if (mTrashUi.isOpen()) { //点击Trash图标关闭Trash垃圾桶删除block的显示 closeTrash(); } else { //点击Trash图标显示Trash垃圾桶删除block mTrashUi.setCurrentCategory(mTrashCategory); closeToolbox(); } } };
d.而本篇博客要分析的Trash垃圾桶Block的数据的来源最终来自Workspace,存储在Trash垃圾桶Block的
数据保存在对象BlocklyCategory里的mItem字段中:
/** * Add a root block to the trash. * * @param block The block to put in the trash, possibly with descendants attached. */ // TODO(#56): Make sure the block doesn't have a parent. public void addBlockToTrash(Block block) { BlocklyCategory.BlockItem blockItem = new BlocklyCategory.BlockItem(block); blockItem.getBlock().setEventWorkspaceId(BlocklyEvent.WORKSPACE_ID_TRASH); mTrashCategory.addItem(0, blockItem);//在Trash中被删除掉block保存在TrashCategory的mItem字段中 }三.结合(一)和(二)的分析,现在实现一个原生Blockly中没有实现的功能:在Wrokspace中删除block到Trash中没有对Trash里面的
数据进行Xml的序列化的存储:
1.在原生Blockly中SimpleActivity设置保存Trash垃圾桶block的路径:
private static final String AUTOSAVE_TRASH_FILENAME = "simple_trash_temp.xml";重写onAutoload()的方法传入保存Workspace和Trash数据的路径:
@NonNull @Override protected String getTrashAutosavePath() { return AUTOSAVE_TRASH_FILENAME; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); onAutoload(); } @Override protected boolean onAutoload() { boolean safely = mBlocklyActivityHelper.loadWorkspaceFromAppDirSafely(AUTOSAVE_FILENAME); try { mBlocklyActivityHelper.loadTrashFromSdcard(AUTOSAVE_TRASH_FILENAME); } catch (IOException e) { e.printStackTrace(); } catch (BlockLoadingException e) { e.printStackTrace(); } return safely; }2.在BlcoklyActivityHelper依葫芦画瓢的加入加载和保存的方法:
加载的代码:
/** * Loads the workspace from the given file in the application's private data directory. * @param filename The path to the file, in the application's local storage. * @throws IOException If there is a underlying problem with the input. * @throws BlockLoadingException If there is a error with the workspace XML format or blocks. */ public void loadWorkspaceFromAppDir(String filename) throws IOException, BlockLoadingException { Log.i("yao1" ,"取出loadWorkspaceFromAppDir:"+filename); mController.loadWorkspaceContents(mActivity.openFileInput(filename)); //把路径传到BlocklyController } public void loadTrashFromSdcard(String filename) throws IOException,BlockLoadingException { Log.i("yao1" ,"取出loadTrashFromSdcard:"+filename); mController.loadTrashContents(mActivity.openFileInput(filename));
保存的代码:
/** * Save the workspace to the given file in the application's private data directory, and show a * status toast. If the save fails, the error is logged. */ public void saveWorkspaceToAppDir(String filename) throws FileNotFoundException, BlocklySerializerException{ Workspace workspace = mWorkspaceFragment.getWorkspace(); workspace.serializeToXml(mActivity.openFileOutput(filename, Context.MODE_PRIVATE)); //将Workspace的数据序列化到xml文件保存 } public void saveTrashToSdCard(String filename) throws BlocklySerializerException,FileNotFoundException{ Workspace workspace = mWorkspaceFragment.getWorkspace(); workspace.serializeTrashToXml(mActivity.openFileOutput(filename, Context.MODE_PRIVATE)); }
3.在Workspace中对Trash里面的block的数据进行xml的保存及读取xml数据转成mTrashCategory:
将mTrashCategory的数据写入xml:
/** * Outputs the workspace as an XML string. * * @param os The output stream to write to. * @throws BlocklySerializerException if there was a failure while serializing. */ public void serializeToXml(OutputStream os) throws BlocklySerializerException { BlocklyXmlHelper.writeToXml(mRootBlocks, os, IOOptions.WRITE_ALL_DATA); //在拖Workspace的mRootBlocks的block写到xml文件中,mRootBlocks即是连接到画布中的block块的集合 } /** * 序列化xml保存数据 * @param os * @throws BlocklySerializerException */ public void serializeTrashToXml(OutputStream os) throws BlocklySerializerException { //mTrashCategory的字段mItem保存着Trash中的被用户删掉的block,在Workspace中存入mTrashCategory的字段mItem的数据即可 if (mTrashCategory != null && mTrashCategory.getItems().size() > 0){ mTrashBlocks.clear(); for (int i = 0; i < mTrashCategory.getItems().size(); i++) { if (BlocklyCategory.BlockItem.TYPE_BLOCK == mTrashCategory.getItems().get(i).getType()) { BlocklyCategory.BlockItem blockItem = (BlocklyCategory.BlockItem) mTrashCategory.getItems().get(i); mTrashBlocks.add(blockItem.getBlock()); } } BlocklyXmlHelper.writeToXml(mTrashBlocks, os, IOOptions.WRITE_ALL_DATA); } }
将xml保存的数据转成mTrashCategory:
/** * Reads the workspace in from a XML stream. This will clear the workspace and replace it with * the contents of the xml. * * @param is The input stream to read from. * @throws BlockLoadingException If workspace was not loaded. May wrap an IOException or another * BlockLoadingException. */ public void loadWorkspaceContents(InputStream is) throws BlockLoadingException { List<Block> newBlocks = BlocklyXmlHelper.loadFromXml(is, mBlockFactory); //读取自动保存数据转成block的集合 // Successfully deserialized. Update workspace. // TODO: (#22) Add proper variable support. // For now just save and restore the list of variables. Set<String> vars = mVariableNameManager.getUsedNames(); mController.resetWorkspace(); for (String varName : vars) { mController.addVariable(varName); } mRootBlocks.addAll(newBlocks); //将加载的block的集合加载到mRootBlocks mStats.collectStats(newBlocks, true /* recursive */); } public void loadTrashContentsToTrashCategory(InputStream is) throws BlockLoadingException { List<Block> newBlocks = BlocklyXmlHelper.loadFromXml(is, mBlockFactory); for (int i = 0; i < newBlocks.size(); i++) { BlocklyCategory.BlockItem blockItem = new BlocklyCategory.BlockItem(newBlocks.get(i)); mTrashCategory.addItem(blockItem); } }
以上就实现了Trash垃圾桶被用户删除block的保存与取出,如图所示:
修改Blockly源码实现上述功能的代码地址:http://download.csdn.net/download/wangyongyao1989/10234076