Esempio n. 1
0
 public void reset()
 {
     Debug2.LogDebug("reset callback id=" + id);
     type          = CallbackType.UNKNOWN;
     mailruEventId = UNSET_HTML_EVENT_ID;
     action        = null;
 }
    public void callMailruByCallbackAndParams(string functionName, Action <object, Callback> action, params object[] parameters)
    {
        Callback callback = callbackPool.getCallback(CallbackType.DISPOSABLE);

        callback.action = action;
        string initialization = "";
        string functionParams = "";

        for (int i = 0; i < parameters.Length; i++)
        {
            initialization += @"
				paramNUM=PARAMETER_JSON;	
			"            .Replace("NUM", "" + i)
                              .Replace("PARAMETER_JSON", Json.Serialize(parameters[i]));
            functionParams += ", paramNUM".Replace("NUM", "" + i);
        }
        string eval = @"
			INITIALIZATION
			
			function _callbackCALLBACK_ID(result){ 
				callback(CALLBACK_ID, result); 
			}			

			FUNCTION_NAME(_callbackCALLBACK_ID ADDITIONAL_PARAMETERS);
		"        .Replace("INITIALIZATION", initialization)
                      .Replace("CALLBACK_ID", "" + callback.id)
                      .Replace("FUNCTION_NAME", functionName)
                      .Replace("ADDITIONAL_PARAMETERS", functionParams);


        Debug2.LogDebug("callMailruByCallbackAndParams external evaluation: \n" + eval);
        Application.ExternalEval(eval);
    }
    public void uploadTexture(Texture2D tex, Action <object, Callback> action)
    {
        string   b64string = System.Convert.ToBase64String(tex.EncodeToPNG());
        Callback callback  = callbackPool.getCallback(CallbackType.DISPOSABLE);

        callback.action = action;

        string eval = @"
			var data = new FormData();
			data.append('imgdata','BASE64_STRING')			
			$.ajax({
				url         : 'saveimage.php',
				data        : data,
				cache       : false,
				contentType : false,
				processData : false,
				type        : 'POST',
				success     : function(data){					
					var url = window.location.href;
					var fullPath=url.substring(0, url.lastIndexOf('/') + 1)+data;
					callback(CALLBACK_ID, fullPath);					
				}
		});
		"        .Replace("BASE64_STRING", b64string)
                      .Replace("CALLBACK_ID", "" + callback.id);

        Debug2.LogDebug("uploadTexture external evaluation: \n" + eval);
        Application.ExternalEval(eval);
    }
 public void onPictureSave(Texture2D texture, string pictureName)
 {
     vkc.api("photos.getAlbums", new Dictionary <string, object>(), delegate(object arg1, Callback arg2) {
         Debug2.LogDebug("im at  takeScreenshot=====\n" + Json.Serialize(arg1));
         Dictionary <string, object> resultDict = arg1 as Dictionary <string, object>;
         if (!resultDict.ContainsKey("response"))
         {
             Debug2.LogError("vk api error \n" + Json.Serialize(arg1));
             return;
         }
         Dictionary <string, object> response = resultDict["response"] as Dictionary <string, object>;
         List <object> items = response["items"] as List <object>;
         long albumId        = -1;
         for (int i = 0; i < items.Count; i++)
         {
             Dictionary <string, object> album = items[i] as Dictionary <string, object>;
             if (((string)album["title"]).Equals(albumName))
             {
                 albumId = (long)album["id"];
                 break;
             }
         }
         string wallText = wallMessage.Replace("PICTURE_NAME", pictureName);
         if (albumId == -1)
         {
             createAlbumAndPostScreenShot(texture, wallText);
         }
         else
         {
             postScreenShot(texture, wallText, albumId);
         }
     });
 }
Esempio n. 5
0
        public static void EraseCircale(RaycastHit hit, int radius)
        {
            var anilMaterial = hit.collider.GetComponent <AnilMaterial>();

            if (!anilMaterial)
            {
                return;
            }

            renderer  = anilMaterial.renderer;
            texture2D = anilMaterial.texture2D;

            if (!texture2D.isReadable)
            {
                Debug2.Log("texture is not readable");
                return;
            }

            pCoord    = hit.textureCoord;
            pCoord.x *= texture2D.width;
            pCoord.y *= texture2D.height;

            int x = Mathf.RoundToInt(pCoord.x * renderer.material.mainTextureScale.x);
            int y = Mathf.RoundToInt(pCoord.y * renderer.material.mainTextureScale.y);

            anilMaterial.Erase(x, y, radius);
        }
 void setResolutionToActualSizeAndSendEvent()
 {
     Debug2.LogDebug("setResolutionToActualSizeAndSendEvent current resolution	"+ Screen.currentResolution);
     lastWidth      = Screen.width;
     lastHeight     = Screen.height;
     lastFullScreen = Screen.fullScreen;
     if (Screen.width < PropertiesSingleton.instance.screen.minWidth || Screen.height < PropertiesSingleton.instance.screen.minHeight)
     {
         scaleScreenAndSendEvent();
     }
     else
     {
         IntVector2 resolution;
         if (Screen.fullScreen)
         {
             Resolution maxRes = Screen.resolutions[Screen.resolutions.Length - 1];
             Screen.SetResolution(maxRes.width, maxRes.height, true);
             Debug2.LogDebug("trying to change to full screen");
             resolution = new IntVector2(maxRes.width, maxRes.height);
         }
         else
         {
             Screen.SetResolution(Screen.width, Screen.height, false);
             resolution = new IntVector2(Screen.width, Screen.height);
         }
         sendEventOnResolutionChange(resolution, new Vector2(1.0f, 1.0f));
     }
 }
Esempio n. 7
0
    void createAlbumAndSavePictureOnSucess(string pictureName, Texture2D texture)
    {
        Dictionary <string, object> paramsObject = new Dictionary <string, object>();

        paramsObject.Add("name", albumName);

        MRUController.instance.callMailruByObjectMailruListenerAndCallback(
            "mailru.common.photos.createAlbum",
            paramsObject,
            "mailru.common.events.createAlbum",
            delegate(object obj, Callback callback){
            Dictionary <string, object> result = obj as Dictionary <string, object>;
            string status = (string)result["status"];
            if (status.Equals("closed"))
            {
                Debug2.LogDebug("album window has closed without creation");
                CallbackPool.instance.releasePermanentCallback(callback);
            }
            else if (status.Equals("createSuccess"))
            {
                string aid = (string)result["aid"];
                Debug2.LogDebug("album created id = " + aid);
                CallbackPool.instance.releasePermanentCallback(callback);
                savePicture(aid, pictureName, texture);
            }
        });
    }
Esempio n. 8
0
        /// <summary>
        /// objeyi yüklemeye yarar
        /// </summary>
        /// <typeparam name="T">Objenin türünü giriniz</typeparam>
        /// <param name="path">objenin Load edileceği yer örn: meshler</param>
        /// <param name="name">örn: /objeler.json ve .json  zorunlu</param>
        public async static UniTask <T[]> LoadArrayAsync <T>(string path, string name)
        {
            CheckPath(path);

            DirectoryInfo directoryInfo = new DirectoryInfo(SavesFolder + path);

            int count = directoryInfo.GetFiles().Length;

            T[] objectToLoad = new T[count];
            var tasks        = new List <UniTask>();

            for (int i = 0; i < count; i++)
            {
                tasks.Add(UniTask.Create(async() =>
                {
                    await UniTask.Yield();
                    string konum = Path.Combine(SavesFolder + path + i.ToString() + name);
                    if (File.Exists(konum))
                    {
                        string loadText = File.ReadAllText(konum);
                        objectToLoad[i] = JsonUtility.FromJson <T>(loadText);
                        Debug2.Log(loadText);
                    }
                }));
            }

            await UniTask.WhenAll(tasks);

            return(objectToLoad);
        }
    public void callbackHandler(string resultString)
    {
        Debug2.LogDebug("callbackHandler fired with resutlString: \n" + resultString);
        Dictionary <string, object> resultObj = Json.Deserialize(resultString) as Dictionary <string, object>;
        long callbackId = (long)resultObj["id"];

        Debug2.LogDebug("callbackId=" + callbackId);
        object   result   = resultObj.ContainsKey("object") ? resultObj["object"] : null;
        Callback callback = callbackDict[callbackId];

        if (callback.action != null)
        {
            callback.action(result, callback);
        }
        else
        {
            Debug2.LogError("callback " + callbackId + " is empty");
        }

        if (callback.type == CallbackType.DISPOSABLE)
        {
            disposableCallbacks.Remove(callback);
            enqueCallback(callback);
        }
    }
Esempio n. 10
0
    bool Invoke <T>(AADCommand command, ISerializable parameters, [NotNullWhen(true)] out T?result) where T : class, ISerializable
    {
        result = null;
        if (!IsConnected)
        {
            return(false);
        }
        var r = InvokeOne(command, parameters, out var result2);

        Debug2.Assert(r != ExecutionResult.UnknownCommand);
        // internal error, we should fix it
        switch (r)
        {
        case ExecutionResult.IOError:
        case ExecutionResult.Disconnect:
            Disconnect();
            return(false);

        case ExecutionResult.Success:
            result = result2 as T;
            return(result is not null);

        default:
            return(false);
        }
    }
Esempio n. 11
0
    public static string[] OnWillSaveAssets(string[] paths)
    {
        // Get the name of the scene to save.
        string scenePath = string.Empty;
        string sceneName = string.Empty;

        Debug2.Log("SAVING");
        foreach (string path in paths)
        {
            Debug2.Log(" NEXT: ");
            if (path.Contains(".unity"))
            {
                scenePath = Path.GetDirectoryName(path);
                sceneName = Path.GetFileNameWithoutExtension(path);
            }
        }

        if (sceneName.Length == 0)
        {
            return(paths);
        }

        // DO WHAT YOU NEED TO DO HERE.
        // FOR EXAMPLE, CALL A STATIC FUNCTION FROM ANOTHER CLASS
        Debug2.Log("	\nscenePath: "+ scenePath);
        Debug2.Log("	sceneName: "+ sceneName);


        return(paths);
    }
Esempio n. 12
0
        public static void Register(ITickable task, UpdateType updateType = UpdateType.normal)
        {
            // be assure instance exist
            Checkinstance();
            var ableTask = Tasks.Find(x => x.InstanceId() == task.InstanceId() && x.InstanceId() != 0);

            if (ableTask != null)
            {
                switch (ableTask)
                {
                case MoveTask move:
                    move.Join(((MoveTask)task).CurrentData); break;

                case DirectionTask drecTask:
                    drecTask.Join(((DirectionTask)task).CurrentData); break;

                case UpdateTask updateTask:
                    Debug2.Log("update task exist it will add in queue");
                    updateTask.Join(((UpdateTask)task).currentData); break;
                }
            }
            else
            {
                if (updateType == UpdateType.normal)
                {
                    Tasks.Add(task);
                }
                else if (updateType == UpdateType.fixedTime)
                {
                    FixedTasks.Add(task);
                }
            }
        }
Esempio n. 13
0
        public string Test3()
        {
            StringBuilder Sb = new StringBuilder();
            List <Rule>   L  = RuleHelper.GetAllRules(true);
            {
                Type   R     = typeof(Rule);
                Type[] Types = GetTypes();
                int    count = 0;
                foreach (Type T in Types)
                {
                    if (T.BaseType == R)
                    {
                        Rule R2 = (Rule)Activator.CreateInstance(T);
                        if (R2.Identifier.ToLower() == "genricvruttam")
                        {
                            continue;
                        }
                        //Debug2.AppendLine ( R2.Name + "," + R2.PadyamType + "," + R2.PadyamSubType + "," + R2.CharLength );
                        count++;

                        if (T.Namespace == "Library.Chandam.Sans")
                        {
                            if (R2.Yati.Length >= 1)
                            {
                                Debug2.AppendLine(R2.Name);
                                continue;
                            }
                            //Sb.AppendLine ( "case "+R2.Identifier+": return new " + R2.Identifier + "();" );
                            Sb.AppendLine("new " + R2.Identifier + "(),");
                        }
                    }
                }
                return(Sb.ToString());
            }
        }
Esempio n. 14
0
    private static void createCharPointsGameObjectElement(GameObject gameObject, XmlElement parentElement, XmlDocument xml)
    {
        CharPoints[] charPointList = gameObject.GetComponents <CharPoints>();
        Debug2.Log(charPointList, charPointList.Length);
        if (charPointList.Length <= 0)
        {
            return;
        }

        XmlElement gameObjElement = xml.CreateElement("GameObject");

        gameObjElement.SetAttribute("name", gameObject.name);
        //gameObjElement.SetAttribute("tag",gameObject.tag);
        gameObjElement.SetAttribute("activeSelf", gameObject.activeSelf.ToString());
        //gameObjElement.SetAttribute("instanceID",gameObject.GetInstanceID().ToString());
        //解析组件
        for (int i = 0; i < charPointList.Length; i++)
        {
            parseCharPoints(charPointList[i], gameObjElement, xml);
            parentElement.AppendChild(gameObjElement);
        }
        //解析子对象
        Transform transform  = gameObject.GetComponent <Transform>();
        int       childCount = transform.childCount;

        for (int i = 0; i < childCount; i++)
        {
            GameObject subGameObj = transform.GetChild(i).gameObject;
            createCharPointsGameObjectElement(subGameObj, parentElement, xml);
        }
    }
Esempio n. 15
0
 public void initializeVKApi(string key = "")
 {
     if (!String.IsNullOrEmpty(key))
     {
         privateKey = key;
     }
     if (initialized)
     {
         Debug2.LogWarning("vk api already initialized, init method will be ignored");
     }
     else
     {
         initialized  = true;
         callbackPool = CallbackPool.instance;
         callbackPool.initialize();
         initVKApi(privateKey,
                   delegate(object obj, Callback callback){
             inputData = HTTPUtility.ParseQueryString((string)obj);
             Debug2.LogDebug("viewer id =" + inputData["viewer_id"]);
             callbackPool.releaseDisposableCallback(callbackOnInitError);
             if (onApiReady != null)
             {
                 onApiReady(true);
             }
             Debug2.LogDebug("VK api is ready");
         },
                   delegate(object obj, Callback callback){
             onApiReady(false);
             callbackPool.releaseDisposableCallback(callBackOnInitDone);
             Debug2.LogError("problem with vk initialization\n" + Json.Serialize(obj));
         });
     }
 }
Esempio n. 16
0
    private static void OnPlayerModeStateChanged(PlayModeStateChange playModeState)
    {
        Debug.LogFormat("state:{0} will:{1} isPlaying:{2}", playModeState, EditorApplication.isPlayingOrWillChangePlaymode, EditorApplication.isPlaying);
        switch (playModeState)
        {
        case PlayModeStateChange.EnteredEditMode:
            break;

        case PlayModeStateChange.ExitingEditMode:
            Scene editorActiveScene = EditorSceneManager.GetActiveScene();
            int   instanceID        = editorActiveScene.GetRootGameObjects()[0].GetInstanceID();
            Debug2.Log(instanceID, HierarchyUtil.IsExpanded(editorActiveScene.GetRootGameObjects()[0]));
            RecordSceneToLocal(editorActiveScene);
            break;

        case PlayModeStateChange.EnteredPlayMode:
            //EditorApplication.playModeStateChanged -= OnPlayerModeStateChanged;
            break;

        case PlayModeStateChange.ExitingPlayMode:
            //EditorSceneManager.sceneLoaded -= OnSceneLoaded;
            EditorSceneManager.activeSceneChanged -= OnActiveSceneChanged;
            break;
        }
    }
    public Callback getCallback(CallbackType callbackType)
    {
        Callback callback;

        if (callbackQueue.Count > 0)
        {
            callback = callbackQueue.Dequeue();
            callback.reset();
        }
        else
        {
            callback = createNewCallback();
        }
        callback.type = callbackType;
        switch (callbackType)
        {
        case CallbackType.DISPOSABLE:
            disposableCallbacks.Add(callback);
            break;

        case CallbackType.PERMANENT:
            permanentCallback.Add(callback);
            break;

        default:
            Debug2.LogError("Wrong callbackType" + callbackType.ToString());
            break;
        }

        return(callback);
    }
 void takeScreenshot()
 {
     vkc.api("photos.getAlbums", new Dictionary <string, object>(), delegate(object arg1, Callback arg2) {
         Debug2.LogDebug("im at  takeScreenshot=====\n" + Json.Serialize(arg1));
         Dictionary <string, object> resultDict = arg1 as Dictionary <string, object>;
         if (!resultDict.ContainsKey("response"))
         {
             Debug2.LogError("vk api error \n" + Json.Serialize(arg1));
             return;
         }
         Dictionary <string, object> response = resultDict["response"] as Dictionary <string, object>;
         List <object> items = response["items"] as List <object>;
         long albumId        = -1;
         for (int i = 0; i < items.Count; i++)
         {
             Dictionary <string, object> album = items[i] as Dictionary <string, object>;
             if (((string)album["title"]).Equals(albumName))
             {
                 albumId = (long)album["id"];
                 break;
             }
         }
         if (albumId == -1)
         {
             createAlbumAndPostScreenShot();
         }
         else
         {
             postScreenShot(albumId);
         }
     });
 }
Esempio n. 19
0
 public static void debug2Action(Debug2 fm, string mystring, string hex)
 {
     try
     {
         if (hex == "true")
         {
             if (mystring.Length != 0)
             {
                 Debug2SendCommand.action(mystring.Substring(mystring.LastIndexOf("x") + 1), fm);
             }
             else
             {
                 MessageBox.Show("No to-be-sent data!");
             }
         }
         else if (hex == "false")
         {
             fm.serialPort1.Write(mystring);
         }
     }
     catch (Exception)
     {
         //MessageBox.Show("Procedure Occurrence Mistake:" + ex.Message, "Anomalous", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Esempio n. 20
0
    void onWebContextReadyListener(object obj, Callback cb)
    {
        Debug2.Log("im here from callback");
        string pageName = (string)obj;

        initData = "";
        if (pageName.StartsWith("mru"))
        {
            webType  = WebType.MAIL_RU;
            initData = mailRuKey;
        }
        else if (pageName.StartsWith("vk"))
        {
            webType  = WebType.VK;
            initData = vkKey;
        }
        else if (pageName.StartsWith("fb"))
        {
            webType = WebType.FB;
        }
        else if (pageName.StartsWith("online"))
        {
            webType = WebType.ONLINE;
        }
        else
        {
            Debug2.LogError("unknown page");
        }
        ready          = true;
        activeStrategy = supportedWeb[webType];
        activeStrategy.onStart(initData);
    }
Esempio n. 21
0
    public void callMethod(string methodName, params object[] parameters)
    {
        string jsParams = "";

        for (int i = 0; i < parameters.Length; i++)
        {
            if (parameters[i] is string)
            {
                jsParams += ", \"" + (string)parameters[i] + "\"";
            }
            else if (parameters[i] is bool)
            {
                jsParams += ", " + ((bool)parameters[i]).ToString().ToLower();
            }
            else if (parameters[i] is int)
            {
                jsParams += ", " + parameters[i];
            }
        }
        string eval = @"
			VK.callMethod('METHOD_NAME'PARAMETERS);
		"        .Replace("METHOD_NAME", methodName)
                      .Replace("PARAMETERS", jsParams);

        Debug2.LogDebug("callMethod external evaluation \n" + eval);
        Application.ExternalEval(eval);
    }
Esempio n. 22
0
        public static void Test(string aName, Action a, string bName, Action b, long iteration)
        {
            Stopwatch stopwatch = new Stopwatch();

            Debug2.Log(aName);

            stopwatch.Start();

            for (long i = 0; i < iteration; i++)
            {
                a.Invoke();
            }

            stopwatch.Stop();
            Debug2.Log($" {stopwatch.ElapsedMilliseconds: 0.000}");

            stopwatch.Reset();
            Debug2.Log(bName);

            for (long i = 0; i < iteration; i++)
            {
                b.Invoke();
            }

            stopwatch.Stop();
            Debug2.Log($" {stopwatch.ElapsedMilliseconds: 0.000}");
        }
Esempio n. 23
0
    public void onNewPictureOpen(SheetObject sheetObject)
    {
        string text = "Colorus | " + sheetObject.nameKey.Localized();
        string eval = "document.title=\"TEXT\";".Replace("TEXT", text);

        Debug2.LogDebug(" onNewPictureOpen evaluation eval=\n" + eval);
        Application.ExternalEval(eval);
    }
 void sendEventOnResolutionChange(IntVector2 resolution, Vector2 scale)
 {
     Debug2.LogDebug("sendEventOnResolutionChange  resolution = " + resolution.ToString() + "   scale =" + scale);
     if (onResolutionChange != null)
     {
         onResolutionChange(resolution, scale);
     }
 }
Esempio n. 25
0
    /// <summary>
    /// Connects to a waiting server within the specified time-out period.
    /// </summary>
    /// <param name="timeout">The number of milliseconds to wait for the client to connect before the connection times out.</param>
    /// <returns></returns>
    bool WaitForConnection(int timeout)
    {
        // TODO: timeout
        Debug2.Assert(!IsConnected);
        var stream = (NamedPipeServerStream)base.stream;

        stream.WaitForConnection();
        return(IsConnected);
    }
Esempio n. 26
0
        //--------------------------------------------------------------------------------

        public virtual void            OutputDebugStructure()
        {
            Debug2.Push(this.ToString());
            foreach (TreeNode treeNode in this._treeNodes)
            {
                treeNode.OutputDebugStructure();
            }
            Debug2.Pop();
        }
    public void setMailruEventId(string parameters)
    {
        Debug2.LogDebug("setMailruEventId params=" + parameters);
        Dictionary <string, object> result = Json.Deserialize(parameters) as Dictionary <string, object>;
        long callbackId    = (long)result["callbackId"];
        long mailruEventId = (long)result["mailruEventId"];

        callbackDict[callbackId].mailruEventId = mailruEventId;
    }
Esempio n. 28
0
        /// <summary>
        /// Get the image bytes asynchronously. Must be called from the main thread,
        /// as the <see cref="DataPath"/> is accessed and Realm can only be used from the main
        /// thread. If you need to access the data from another thread, call
        /// <see cref="PrepareImageLoad"/> on the main thread and then call
        /// <see cref="PreparedImageLoad.GetDataAsync"/> on it.
        /// </summary>
        /// <returns></returns>
        public virtual async Task <byte[]> GetDataAsync()
        {
            var dataPath = DataPath; // DO NOT INLINE! See method documentation.

            Debug2.Assert(dataPath != null, $"dataPath is null for media with REST ID {IdForRestApi}");
            return(await MediaCache.GetBytesAsync(
                       IdForRestApi,
                       async() => await fileManager.ReadFromDiskAsync(dataPath)
                       ));
        }
Esempio n. 29
0
    public override void Init()
    {
        Debug2.Log("init MRUController");
        base.Init();

        if (initOnStart)
        {
            initializeVKApi();
        }
    }
Esempio n. 30
0
    /// <summary>
    /// Execute one command and return execution result
    /// </summary>
    /// <returns></returns>
    /// <remarks>See invoker: <seealso cref="AADClient.InvokeOne(AADCommand, ISerializable, out ISerializable?)"/></remarks>
    ExecutionResult ExecuteOne()
    {
        try {
            ReadCommand(out var command);

            if (command == AADCommand.Disconnect)
            {
                return(ExecutionResult.Disconnect);
            }

            if (!CommandHandlerManager.Handlers.TryGetValue(command, out var handler))
            {
                Debug2.Assert(false);
                return(ExecutionResult.UnknownCommand);
            }
            // phase 1: get the handler corresponding to the command

            if (Activator.CreateInstance(handler.ParametersType, true) is not ISerializable parameters)
            {
                throw new InvalidOperationException("Can't create parameters object");
            }
            // phase 2: create parameters instance

            Read(parameters);
            // phase 3: read parameters from stream

            bool          b;
            ISerializable?result;
            try {
                b = handler.Execute(parameters, out result);
            }
            catch (Exception ex) {
                WriteCommand(AADCommand.UnhandledException);
                Write(new AADServerInvocationException(ex.ToFullString()));
                return(ExecutionResult.UnhandledException);
            }
            if (!b)
            {
                WriteCommand(AADCommand.Failure);
                return(ExecutionResult.Failure);
            }
            // phase 4: execute command with parameters

            WriteCommand(AADCommand.Success);
            Write(result !);
            // phase 5: write result to stream

            return(ExecutionResult.Success);
        }
        catch (Exception ex) {
            Debug2.Assert(ex is IOException);
            // regard all unhandable exceptions as IO error
            return(ExecutionResult.IOError);
        }
    }