Browse Source

Did work on how AtomicQuery is being used inside the WebView editors to make it have a more consistent API. Also attached AtomicQueryPromise to the window object so it's available to everything.

Shaddock Heath 9 years ago
parent
commit
9561aae986

+ 22 - 21
Script/AtomicWebViewEditor/interop.ts

@@ -37,27 +37,35 @@ const DEBUG_ALERT = false;
 
 /**
  * Promise version of atomic query
- * @param  {string} message the query to use to pass to atomicQuery.  If there is no payload, this will be passed directly, otherwise it will be passed in a data object
- * @param  {any} payload optional data to send
+ * @param  {string} messageType the message type to pass to atomicQuery.  If there is no payload, this will be passed directly, otherwise it will be passed in a data object
+ * @param  {any} data optional data to send
  * @return {Promise}
  */
-function atomicQueryPromise(message: any): Promise<{}> {
+window.atomicQueryPromise = function(messageType: string, data?: {}): Promise<{}> {
     return new Promise(function(resolve, reject) {
-        let queryMessage = message;
 
-        // if message is coming in as an object then let's stringify it
-        if (typeof (message) != "string") {
-            queryMessage = JSON.stringify(message);
+        let queryMessage;
+
+        // if we have a data element, then we need to structure the message so that the host understands it
+        // by adding the message to the object and then stringify-ing the whole thing
+        if (data) {
+            // stringify and reparse since we need to modify the data, but don't want to modify the passed in object
+            queryMessage = JSON.parse(JSON.stringify(data));
+            queryMessage.message = messageType;
+        } else {
+            queryMessage = {
+                message: messageType
+            };
         }
 
         window.atomicQuery({
-            request: queryMessage,
+            request: JSON.stringify(queryMessage),
             persistent: false,
             onSuccess: resolve,
             onFailure: (error_code, error_message) => reject({ error_code: error_code, error_message: error_message })
         });
     });
-}
+};
 
 export default class HostInteropType {
 
@@ -96,9 +104,7 @@ export default class HostInteropType {
         // get the code
         this.getResource(codeUrl).then((src: string) => {
             editorCommands.loadCodeIntoEditor(src, filename, fileExt);
-            atomicQueryPromise({
-                message: HostInteropType.EDITOR_GET_USER_PREFS
-            });
+            window.atomicQueryPromise(HostInteropType.EDITOR_GET_USER_PREFS);
         }).catch((e: Editor.ClientExtensions.AtomicErrorMessage) => {
             console.log("Error loading code: " + e.error_message);
         });
@@ -110,8 +116,7 @@ export default class HostInteropType {
      */
     saveCode(): Promise<any> {
         let source = editorCommands.getSourceText();
-        return atomicQueryPromise({
-            message: HostInteropType.EDITOR_SAVE_CODE,
+        return window.atomicQueryPromise(HostInteropType.EDITOR_SAVE_CODE, {
             payload: source
         }).then(() => {
             editorCommands.codeSaved(this.fileName, this.fileExt, source);
@@ -125,13 +130,9 @@ export default class HostInteropType {
      * @return {Promise}
      */
     saveFile(filename: string, fileContents: string): Promise<any> {
-        const fileExt = filename.indexOf(".") != -1 ? filename.split(".").pop() : "";
-        return atomicQueryPromise({
-            message: HostInteropType.EDITOR_SAVE_FILE,
+        return window.atomicQueryPromise(HostInteropType.EDITOR_SAVE_FILE, {
             filename: filename,
             payload: fileContents
-        }).then(() => {
-            editorCommands.codeSaved(filename, fileExt, fileContents);
         });
     }
 
@@ -143,7 +144,7 @@ export default class HostInteropType {
         if (DEBUG_ALERT) {
             alert(`Attach chrome dev tools to this instance by navigating to http://localhost:${DEBUG_PORT}`);
         }
-        atomicQueryPromise(HostInteropType.EDITOR_LOAD_COMPLETE);
+        window.atomicQueryPromise(HostInteropType.EDITOR_LOAD_COMPLETE);
     }
 
     /**
@@ -177,7 +178,7 @@ export default class HostInteropType {
      * Notify the host that the contents of the editor has changed
      */
     notifyEditorChange() {
-        atomicQueryPromise(HostInteropType.EDITOR_CHANGE).catch((e: Editor.ClientExtensions.AtomicErrorMessage) => {
+        window.atomicQueryPromise(HostInteropType.EDITOR_CHANGE).catch((e: Editor.ClientExtensions.AtomicErrorMessage) => {
             console.log("Error on change: " + e.error_message);
         });
     }

+ 15 - 1
Script/AtomicWebViewEditor/typings/WindowExt.d.ts

@@ -24,7 +24,21 @@
  * Defines the interface to what is available for the host to call or for the client to call on the window object
  */
 interface Window {
-    atomicQuery: any;
+    atomicQuery: (message: {
+        request: any,
+        persistent: boolean,
+        onSuccess: () => void,
+        onFailure: (error_code, error_message) => void
+    }) => void;
+
+    /**
+     * Used to call into the host and provide messages
+     * @param {string} messageType
+     * @param {object} data
+     * @return {Promise}
+     */
+    atomicQueryPromise: (messageType: string, data?: {}) => Promise<{}>;
+
     HOST_loadCode: (codeUrl) => void;
     HOST_saveCode: () => void;
 

+ 32 - 35
Source/AtomicEditor/Editors/JSResourceEditor.cpp

@@ -127,46 +127,43 @@ void JSResourceEditor::HandleWebMessage(StringHash eventType, VariantMap& eventD
 
     WebMessageHandler* handler = static_cast<WebMessageHandler*>(eventData[P_HANDLER].GetPtr());
 
-    if (request == EDITOR_CHANGE)
+    // All messages come in as a JSON string with a "message" property describing what the message is
+    JSONValue jvalue;
+    if (JSONFile::ParseJSON(request, jvalue, false))
     {
-        SetModified(true);
-    }
-    else
-    {
-        JSONValue jvalue;
-        if (JSONFile::ParseJSON(request, jvalue, false))
+        String message = jvalue["message"].GetString();
+        if (message == EDITOR_CHANGE) {
+            SetModified(true);
+        }
+        else if (message == EDITOR_SAVE_CODE)
         {
-            String message = jvalue["message"].GetString();
-            if (message == EDITOR_SAVE_CODE)
-            {
-                String code = jvalue["payload"].GetString();
-                File file(context_, fullpath_, FILE_WRITE);
-                file.Write((void*) code.CString(), code.Length());
-                file.Close();
-            }
-            else if (message == EDITOR_SAVE_FILE)
-            {
-                String code = jvalue["payload"].GetString();
-                String fn = jvalue["filename"].GetString();
+            String code = jvalue["payload"].GetString();
+            File file(context_, fullpath_, FILE_WRITE);
+            file.Write((void*) code.CString(), code.Length());
+            file.Close();
+        }
+        else if (message == EDITOR_SAVE_FILE)
+        {
+            String code = jvalue["payload"].GetString();
+            String fn = jvalue["filename"].GetString();
 
-                // NOTE: We only want to be able save into the resource directory, so parse out the file path and append
-                // it to the resource directory
-                ToolSystem* tsys = GetSubsystem<ToolSystem>();
-                String fullFilePath = tsys->GetProject()->GetProjectPath() + getNormalizedPath(fn);
+            // NOTE: We only want to be able save into the resource directory, so parse out the file path and append
+            // it to the resource directory
+            ToolSystem* tsys = GetSubsystem<ToolSystem>();
+            String fullFilePath = tsys->GetProject()->GetProjectPath() + getNormalizedPath(fn);
 
-                File file(context_, fullFilePath, FILE_WRITE);
-                file.Write((void*) code.CString(), code.Length());
-                file.Close();
-            }
-            else if (message == EDITOR_GET_USER_PREFS)
+            File file(context_, fullFilePath, FILE_WRITE);
+            file.Write((void*) code.CString(), code.Length());
+            file.Close();
+        }
+        else if (message == EDITOR_GET_USER_PREFS)
+        {
+            ToolSystem* tsys = GetSubsystem<ToolSystem>();
+            Project* proj = tsys->GetProject();
+            FileSystem* fileSystem = GetSubsystem<FileSystem>();
+            if (fileSystem->FileExists(proj->GetUserPrefsFullPath()))
             {
-                ToolSystem* tsys = GetSubsystem<ToolSystem>();
-                Project* proj = tsys->GetProject();
-                FileSystem* fileSystem = GetSubsystem<FileSystem>();
-                if (fileSystem->FileExists(proj->GetUserPrefsFullPath()))
-                {
-                    webClient_->ExecuteJavaScript(ToString("HOST_loadPreferences(\"atomic://%s\");", proj->GetUserPrefsFullPath().CString()));
-                }
+                webClient_->ExecuteJavaScript(ToString("HOST_loadPreferences(\"atomic://%s\");", proj->GetUserPrefsFullPath().CString()));
             }
         }
     }